diff --git a/ComfyUI-Crystools/__pycache__/__init__.cpython-310.pyc b/ComfyUI-Crystools/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4e8d7d79aae868805385bb079077da997ed805b Binary files /dev/null and b/ComfyUI-Crystools/__pycache__/__init__.cpython-310.pyc differ diff --git a/ComfyUI-Crystools/nodes/__pycache__/__init__.cpython-310.pyc b/ComfyUI-Crystools/nodes/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4de165cd5a6b772dda705a76ad3376476015aedf Binary files /dev/null and b/ComfyUI-Crystools/nodes/__pycache__/__init__.cpython-310.pyc differ diff --git a/ComfyUI-Crystools/nodes/__pycache__/_names.cpython-310.pyc b/ComfyUI-Crystools/nodes/__pycache__/_names.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3eeb847164eaaee5b0cab1675f71fce9342b0d9b Binary files /dev/null and b/ComfyUI-Crystools/nodes/__pycache__/_names.cpython-310.pyc differ diff --git a/ComfyUI-Crystools/nodes/__pycache__/switch.cpython-310.pyc b/ComfyUI-Crystools/nodes/__pycache__/switch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a24b6e44e797482f1f598e99621e673d8181ca7 Binary files /dev/null and b/ComfyUI-Crystools/nodes/__pycache__/switch.cpython-310.pyc differ diff --git a/ComfyUI-Crystools/nodes/switch.py b/ComfyUI-Crystools/nodes/switch.py new file mode 100644 index 0000000000000000000000000000000000000000..72d7829274199b9c2f27d1c0136b325f949da349 --- /dev/null +++ b/ComfyUI-Crystools/nodes/switch.py @@ -0,0 +1,225 @@ +from ..core import BOOLEAN, STRING, CATEGORY, any, logger + + +class CSwitchFromAny: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "any": (any, ), + "boolean": BOOLEAN, + } + } + + CATEGORY = CATEGORY.MAIN.value + CATEGORY.SWITCH.value + RETURN_TYPES = (any, any,) + RETURN_NAMES = ("on_true", "on_false",) + + FUNCTION = "execute" + + def execute(self, any,boolean=True): + logger.debug("Any switch: " + str(boolean)) + + if boolean: + return any, None + else: + return None, any + +class CSwitchBooleanAny: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "on_true": (any, {"lazy": True}), + "on_false": (any, {"lazy": True}), + "boolean": BOOLEAN, + } + } + + CATEGORY = CATEGORY.MAIN.value + CATEGORY.SWITCH.value + RETURN_TYPES = (any,) + + FUNCTION = "execute" + + def check_lazy_status(self, on_true=None, on_false=None, boolean=True): + needed = "on_true" if boolean else "on_false" + return [needed] + + def execute(self, on_true, on_false, boolean=True): + logger.debug("Any switch: " + str(boolean)) + + if boolean: + return (on_true,) + else: + return (on_false,) + + +class CSwitchBooleanString: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "on_true": ("STRING", {"default": "", "lazy": True}), + "on_false": ("STRING", {"default": "", "lazy": True}), + "boolean": BOOLEAN, + } + } + + CATEGORY = CATEGORY.MAIN.value + CATEGORY.SWITCH.value + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("string",) + + FUNCTION = "execute" + + def check_lazy_status(self, on_true=None, on_false=None, boolean=True): + needed = "on_true" if boolean else "on_false" + return [needed] + + def execute(self, on_true, on_false, boolean=True): + logger.debug("String switch: " + str(boolean)) + + if boolean: + return (on_true,) + else: + return (on_false,) + + +class CSwitchBooleanConditioning: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "on_true": ("CONDITIONING", {"lazy": True}), + "on_false": ("CONDITIONING", {"lazy": True}), + "boolean": BOOLEAN, + } + } + + CATEGORY = CATEGORY.MAIN.value + CATEGORY.SWITCH.value + RETURN_TYPES = ("CONDITIONING",) + RETURN_NAMES = ("conditioning",) + + FUNCTION = "execute" + + def check_lazy_status(self, on_true=None, on_false=None, boolean=True): + needed = "on_true" if boolean else "on_false" + return [needed] + + def execute(self, on_true, on_false, boolean=True): + logger.debug("Conditioning switch: " + str(boolean)) + + if boolean: + return (on_true,) + else: + return (on_false,) + + +class CSwitchBooleanImage: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "on_true": ("IMAGE", {"lazy": True}), + "on_false": ("IMAGE", {"lazy": True}), + "boolean": BOOLEAN, + } + } + + CATEGORY = CATEGORY.MAIN.value + CATEGORY.SWITCH.value + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("image",) + + FUNCTION = "execute" + + def check_lazy_status(self, on_true=None, on_false=None, boolean=True): + needed = "on_true" if boolean else "on_false" + return [needed] + + def execute(self, on_true, on_false, boolean=True): + logger.debug("Image switch: " + str(boolean)) + + if boolean: + return (on_true,) + else: + return (on_false,) + + +class CSwitchBooleanLatent: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "on_true": ("LATENT", {"lazy": True}), + "on_false": ("LATENT", {"lazy": True}), + "boolean": BOOLEAN, + } + } + + CATEGORY = CATEGORY.MAIN.value + CATEGORY.SWITCH.value + RETURN_TYPES = ("LATENT",) + RETURN_NAMES = ("latent",) + + FUNCTION = "execute" + + def check_lazy_status(self, on_true=None, on_false=None, boolean=True): + needed = "on_true" if boolean else "on_false" + return [needed] + + def execute(self, on_true, on_false, boolean=True): + logger.debug("Latent switch: " + str(boolean)) + + if boolean: + return (on_true,) + else: + return (on_false,) + + +class CSwitchBooleanMask: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "on_true": ("MASK", {"lazy": True}), + "on_false": ("MASK", {"lazy": True}), + "boolean": BOOLEAN, + } + } + + CATEGORY = CATEGORY.MAIN.value + CATEGORY.SWITCH.value + RETURN_TYPES = ("MASK",) + RETURN_NAMES = ("mask",) + + FUNCTION = "execute" + + def check_lazy_status(self, on_true=None, on_false=None, boolean=True): + needed = "on_true" if boolean else "on_false" + return [needed] + + def execute(self, on_true, on_false, boolean=True): + logger.debug("Mask switch: " + str(boolean)) + + if boolean: + return (on_true,) + else: + return (on_false,) diff --git a/ComfyUI-Crystools/samples/debugger-any.json b/ComfyUI-Crystools/samples/debugger-any.json new file mode 100644 index 0000000000000000000000000000000000000000..5ff6472b0ea89771f616cdc1fdb77e2b3a4efd9a --- /dev/null +++ b/ComfyUI-Crystools/samples/debugger-any.json @@ -0,0 +1,102 @@ +{ + "last_node_id": 4, + "last_link_id": 4, + "nodes": [ + { + "id": 3, + "type": "Show any [Crystools]", + "pos": [ + 475, + 250 + ], + "size": { + "0": 400, + "1": 750 + }, + "flags": {}, + "order": 1, + "mode": 0, + "inputs": [ + { + "name": "any_value", + "type": "*", + "link": 3 + } + ], + "properties": { + "Node name for S&R": "Show any [Crystools]" + }, + "widgets_values": [ + false, + true, + "" + ] + }, + { + "id": 1, + "type": "Load image with metadata [Crystools]", + "pos": [ + 100, + 75 + ], + "size": [ + 325, + 350 + ], + "flags": {}, + "order": 0, + "mode": 0, + "outputs": [ + { + "name": "image", + "type": "IMAGE", + "links": null, + "shape": 3 + }, + { + "name": "mask", + "type": "MASK", + "links": null, + "shape": 3 + }, + { + "name": "prompt", + "type": "JSON", + "links": [ + 3 + ], + "shape": 3, + "slot_index": 2 + }, + { + "name": "Metadata RAW", + "type": "METADATA_RAW", + "links": [], + "shape": 3, + "slot_index": 3 + } + ], + "properties": { + "Node name for S&R": "Load image with metadata [Crystools]" + }, + "widgets_values": [ + "tests/ComfyUI_00314_20-8-euler.png", + "image" + ] + } + ], + "links": [ + [ + 3, + 1, + 2, + 3, + 0, + "*" + ] + ], + "groups": [], + "config": {}, + "extra": {}, + "version": 0.4 +} \ No newline at end of file diff --git a/ComfyUI-Crystools/samples/debugger-json.json b/ComfyUI-Crystools/samples/debugger-json.json new file mode 100644 index 0000000000000000000000000000000000000000..d37938e09eb9cd8e65d9311101f8fe101080af36 --- /dev/null +++ b/ComfyUI-Crystools/samples/debugger-json.json @@ -0,0 +1,182 @@ +{ + "last_node_id": 4, + "last_link_id": 4, + "nodes": [ + { + "id": 4, + "type": "Show any to JSON [Crystools]", + "pos": [ + 900, + 175 + ], + "size": { + "0": 400, + "1": 825 + }, + "flags": {}, + "order": 3, + "mode": 0, + "inputs": [ + { + "name": "any_value", + "type": "*", + "link": 4 + } + ], + "outputs": [ + { + "name": "string", + "type": "STRING", + "links": null, + "shape": 3 + } + ], + "properties": { + "Node name for S&R": "Show any to JSON [Crystools]" + } + }, + { + "id": 2, + "type": "Show any to JSON [Crystools]", + "pos": [ + 1350, + 50 + ], + "size": [ + 400, + 950 + ], + "flags": {}, + "order": 1, + "mode": 0, + "inputs": [ + { + "name": "any_value", + "type": "*", + "link": 2 + } + ], + "outputs": [ + { + "name": "string", + "type": "STRING", + "links": null, + "shape": 3 + } + ], + "properties": { + "Node name for S&R": "Show any to JSON [Crystools]" + } + }, + { + "id": 3, + "type": "Show any [Crystools]", + "pos": [ + 475, + 250 + ], + "size": [ + 400, + 750 + ], + "flags": {}, + "order": 2, + "mode": 0, + "inputs": [ + { + "name": "any_value", + "type": "*", + "link": 3 + } + ], + "properties": { + "Node name for S&R": "Show any [Crystools]" + } + }, + { + "id": 1, + "type": "Load image with metadata [Crystools]", + "pos": [ + 100, + 75 + ], + "size": [ + 325, + 350 + ], + "flags": {}, + "order": 0, + "mode": 0, + "outputs": [ + { + "name": "image", + "type": "IMAGE", + "links": null, + "shape": 3 + }, + { + "name": "mask", + "type": "MASK", + "links": null, + "shape": 3 + }, + { + "name": "prompt", + "type": "JSON", + "links": [ + 2, + 3 + ], + "shape": 3, + "slot_index": 2 + }, + { + "name": "Metadata RAW", + "type": "METADATA_RAW", + "links": [ + 4 + ], + "shape": 3, + "slot_index": 3 + } + ], + "properties": { + "Node name for S&R": "Load image with metadata [Crystools]" + }, + "widgets_values": [ + "tests/ComfyUI_00314_20-8-euler.png", + "image" + ] + } + ], + "links": [ + [ + 2, + 1, + 2, + 2, + 0, + "*" + ], + [ + 3, + 1, + 2, + 3, + 0, + "*" + ], + [ + 4, + 1, + 3, + 4, + 0, + "*" + ] + ], + "groups": [], + "config": {}, + "extra": {}, + "version": 0.4 +} \ No newline at end of file diff --git a/ComfyUI-Crystools/samples/debugger-metadata.json b/ComfyUI-Crystools/samples/debugger-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..e00fa3259c667601b9d89b72cc91541757ea87cd --- /dev/null +++ b/ComfyUI-Crystools/samples/debugger-metadata.json @@ -0,0 +1,382 @@ +{ + "last_node_id": 13, + "last_link_id": 11, + "nodes": [ + { + "id": 7, + "type": "CLIPTextEncode", + "pos": [ + 413, + 389 + ], + "size": { + "0": 425.27801513671875, + "1": 180.6060791015625 + }, + "flags": {}, + "order": 4, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 5 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 6 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "CLIPTextEncode" + }, + "widgets_values": [ + "text, watermark" + ] + }, + { + "id": 6, + "type": "CLIPTextEncode", + "pos": [ + 415, + 186 + ], + "size": { + "0": 422.84503173828125, + "1": 164.31304931640625 + }, + "flags": {}, + "order": 3, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 3 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 4 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "CLIPTextEncode" + }, + "widgets_values": [ + "beautiful scenery nature glass bottle landscape, , purple galaxy bottle," + ] + }, + { + "id": 5, + "type": "EmptyLatentImage", + "pos": [ + 473, + 609 + ], + "size": { + "0": 315, + "1": 106 + }, + "flags": {}, + "order": 0, + "mode": 0, + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "links": [ + 2 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "EmptyLatentImage" + }, + "widgets_values": [ + 512, + 512, + 1 + ] + }, + { + "id": 8, + "type": "VAEDecode", + "pos": [ + 1209, + 188 + ], + "size": { + "0": 210, + "1": 46 + }, + "flags": {}, + "order": 6, + "mode": 0, + "inputs": [ + { + "name": "samples", + "type": "LATENT", + "link": 7 + }, + { + "name": "vae", + "type": "VAE", + "link": 8 + } + ], + "outputs": [ + { + "name": "IMAGE", + "type": "IMAGE", + "links": [ + 9 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "VAEDecode" + } + }, + { + "id": 9, + "type": "SaveImage", + "pos": [ + 1451, + 189 + ], + "size": [ + 200, + 275 + ], + "flags": {}, + "order": 7, + "mode": 0, + "inputs": [ + { + "name": "images", + "type": "IMAGE", + "link": 9 + } + ], + "properties": {}, + "widgets_values": [ + "ComfyUI" + ] + }, + { + "id": 3, + "type": "KSampler", + "pos": [ + 863, + 186 + ], + "size": [ + 325, + 475 + ], + "flags": {}, + "order": 5, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 1 + }, + { + "name": "positive", + "type": "CONDITIONING", + "link": 4 + }, + { + "name": "negative", + "type": "CONDITIONING", + "link": 6 + }, + { + "name": "latent_image", + "type": "LATENT", + "link": 2 + } + ], + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "links": [ + 7 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "KSampler" + }, + "widgets_values": [ + 156680208700286, + "fixed", + 20, + 8, + "euler", + "normal", + 1 + ] + }, + { + "id": 10, + "type": "Show Metadata [Crystools]", + "pos": [ + 1225, + 525 + ], + "size": [ + 450, + 525 + ], + "flags": {}, + "order": 1, + "mode": 0, + "properties": {} + }, + { + "id": 4, + "type": "CheckpointLoaderSimple", + "pos": [ + 26, + 474 + ], + "size": { + "0": 315, + "1": 98 + }, + "flags": {}, + "order": 2, + "mode": 0, + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [ + 1 + ], + "slot_index": 0 + }, + { + "name": "CLIP", + "type": "CLIP", + "links": [ + 3, + 5 + ], + "slot_index": 1 + }, + { + "name": "VAE", + "type": "VAE", + "links": [ + 8 + ], + "slot_index": 2 + } + ], + "properties": { + "Node name for S&R": "CheckpointLoaderSimple" + }, + "widgets_values": [ + "sd-v1-5-pruned-emaonly.safetensors" + ] + } + ], + "links": [ + [ + 1, + 4, + 0, + 3, + 0, + "MODEL" + ], + [ + 2, + 5, + 0, + 3, + 3, + "LATENT" + ], + [ + 3, + 4, + 1, + 6, + 0, + "CLIP" + ], + [ + 4, + 6, + 0, + 3, + 1, + "CONDITIONING" + ], + [ + 5, + 4, + 1, + 7, + 0, + "CLIP" + ], + [ + 6, + 7, + 0, + 3, + 2, + "CONDITIONING" + ], + [ + 7, + 3, + 0, + 8, + 0, + "LATENT" + ], + [ + 8, + 4, + 2, + 8, + 1, + "VAE" + ], + [ + 9, + 8, + 0, + 9, + 0, + "IMAGE" + ] + ], + "groups": [], + "config": {}, + "extra": {}, + "version": 0.4 +} \ No newline at end of file diff --git a/ComfyUI-Crystools/samples/image-load.json b/ComfyUI-Crystools/samples/image-load.json new file mode 100644 index 0000000000000000000000000000000000000000..c5281d8e6020bb7f515b85d6098eb538e6522064 --- /dev/null +++ b/ComfyUI-Crystools/samples/image-load.json @@ -0,0 +1,59 @@ +{ + "last_node_id": 1, + "last_link_id": 0, + "nodes": [ + { + "id": 1, + "type": "Load image with metadata [Crystools]", + "pos": [ + 150, + 200 + ], + "size": [ + 325, + 350 + ], + "flags": {}, + "order": 0, + "mode": 0, + "outputs": [ + { + "name": "image", + "type": "IMAGE", + "links": null, + "shape": 3 + }, + { + "name": "mask", + "type": "MASK", + "links": null, + "shape": 3 + }, + { + "name": "prompt", + "type": "JSON", + "links": null, + "shape": 3 + }, + { + "name": "Metadata RAW", + "type": "METADATA_RAW", + "links": null, + "shape": 3 + } + ], + "properties": { + "Node name for S&R": "Load image with metadata [Crystools]" + }, + "widgets_values": [ + "tests/ComfyUI_00314_20-8-euler.png", + "image" + ] + } + ], + "links": [], + "groups": [], + "config": {}, + "extra": {}, + "version": 0.4 +} \ No newline at end of file diff --git a/ComfyUI-Crystools/samples/image-preview-image.json b/ComfyUI-Crystools/samples/image-preview-image.json new file mode 100644 index 0000000000000000000000000000000000000000..6dc27428e9cfa7232778a46aa126da1db14148a6 --- /dev/null +++ b/ComfyUI-Crystools/samples/image-preview-image.json @@ -0,0 +1,373 @@ +{ + "last_node_id": 14, + "last_link_id": 12, + "nodes": [ + { + "id": 7, + "type": "CLIPTextEncode", + "pos": [ + 413, + 389 + ], + "size": { + "0": 425.27801513671875, + "1": 180.6060791015625 + }, + "flags": {}, + "order": 3, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 5 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 6 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "CLIPTextEncode" + }, + "widgets_values": [ + "text, watermark" + ] + }, + { + "id": 6, + "type": "CLIPTextEncode", + "pos": [ + 415, + 186 + ], + "size": { + "0": 422.84503173828125, + "1": 164.31304931640625 + }, + "flags": {}, + "order": 2, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 3 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 4 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "CLIPTextEncode" + }, + "widgets_values": [ + "beautiful scenery nature glass bottle landscape, , purple galaxy bottle," + ] + }, + { + "id": 5, + "type": "EmptyLatentImage", + "pos": [ + 473, + 609 + ], + "size": { + "0": 315, + "1": 106 + }, + "flags": {}, + "order": 0, + "mode": 0, + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "links": [ + 2 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "EmptyLatentImage" + }, + "widgets_values": [ + 512, + 512, + 1 + ] + }, + { + "id": 8, + "type": "VAEDecode", + "pos": [ + 1209, + 188 + ], + "size": { + "0": 210, + "1": 46 + }, + "flags": {}, + "order": 5, + "mode": 0, + "inputs": [ + { + "name": "samples", + "type": "LATENT", + "link": 7 + }, + { + "name": "vae", + "type": "VAE", + "link": 8 + } + ], + "outputs": [ + { + "name": "IMAGE", + "type": "IMAGE", + "links": [ + 12 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "VAEDecode" + } + }, + { + "id": 4, + "type": "CheckpointLoaderSimple", + "pos": [ + 26, + 474 + ], + "size": { + "0": 315, + "1": 98 + }, + "flags": {}, + "order": 1, + "mode": 0, + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [ + 1 + ], + "slot_index": 0 + }, + { + "name": "CLIP", + "type": "CLIP", + "links": [ + 3, + 5 + ], + "slot_index": 1 + }, + { + "name": "VAE", + "type": "VAE", + "links": [ + 8 + ], + "slot_index": 2 + } + ], + "properties": { + "Node name for S&R": "CheckpointLoaderSimple" + }, + "widgets_values": [ + "sd-v1-5-pruned-emaonly.safetensors" + ] + }, + { + "id": 3, + "type": "KSampler", + "pos": [ + 863, + 186 + ], + "size": { + "0": 325, + "1": 475 + }, + "flags": {}, + "order": 4, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 1 + }, + { + "name": "positive", + "type": "CONDITIONING", + "link": 4 + }, + { + "name": "negative", + "type": "CONDITIONING", + "link": 6 + }, + { + "name": "latent_image", + "type": "LATENT", + "link": 2 + } + ], + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "links": [ + 7 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "KSampler" + }, + "widgets_values": [ + 156680208700286, + "fixed", + 20, + 8, + "euler", + "normal", + 1 + ] + }, + { + "id": 14, + "type": "Preview from image [Crystools]", + "pos": [ + 1525, + 175 + ], + "size": [ + 400, + 800 + ], + "flags": {}, + "order": 6, + "mode": 0, + "inputs": [ + { + "name": "image", + "type": "IMAGE", + "link": 12 + } + ], + "outputs": [ + { + "name": "Metadata RAW", + "type": "METADATA_RAW", + "links": null, + "shape": 3 + } + ], + "properties": { + "Node name for S&R": "Preview from image [Crystools]" + } + } + ], + "links": [ + [ + 1, + 4, + 0, + 3, + 0, + "MODEL" + ], + [ + 2, + 5, + 0, + 3, + 3, + "LATENT" + ], + [ + 3, + 4, + 1, + 6, + 0, + "CLIP" + ], + [ + 4, + 6, + 0, + 3, + 1, + "CONDITIONING" + ], + [ + 5, + 4, + 1, + 7, + 0, + "CLIP" + ], + [ + 6, + 7, + 0, + 3, + 2, + "CONDITIONING" + ], + [ + 7, + 3, + 0, + 8, + 0, + "LATENT" + ], + [ + 8, + 4, + 2, + 8, + 1, + "VAE" + ], + [ + 12, + 8, + 0, + 14, + 0, + "IMAGE" + ] + ], + "groups": [], + "config": {}, + "extra": {}, + "version": 0.4 +} \ No newline at end of file diff --git a/ComfyUI-Crystools/samples/image-preview-metadata.json b/ComfyUI-Crystools/samples/image-preview-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..1773a10bf1b5979f367cf6953bfd1bdd97ea8a28 --- /dev/null +++ b/ComfyUI-Crystools/samples/image-preview-metadata.json @@ -0,0 +1,104 @@ +{ + "last_node_id": 2, + "last_link_id": 1, + "nodes": [ + { + "id": 1, + "type": "Load image with metadata [Crystools]", + "pos": [ + 150, + 200 + ], + "size": [ + 325, + 350 + ], + "flags": {}, + "order": 0, + "mode": 0, + "outputs": [ + { + "name": "image", + "type": "IMAGE", + "links": null, + "shape": 3 + }, + { + "name": "mask", + "type": "MASK", + "links": null, + "shape": 3 + }, + { + "name": "prompt", + "type": "JSON", + "links": null, + "shape": 3 + }, + { + "name": "Metadata RAW", + "type": "METADATA_RAW", + "links": [ + 1 + ], + "shape": 3, + "slot_index": 3 + } + ], + "properties": { + "Node name for S&R": "Load image with metadata [Crystools]" + }, + "widgets_values": [ + "tests/ComfyUI_00314_20-8-euler.png", + "image" + ] + }, + { + "id": 2, + "type": "Preview from metadata [Crystools]", + "pos": [ + 575, + 200 + ], + "size": [ + 425, + 675 + ], + "flags": {}, + "order": 1, + "mode": 0, + "inputs": [ + { + "name": "metadata_raw", + "type": "METADATA_RAW", + "link": 1 + } + ], + "outputs": [ + { + "name": "Metadata RAW", + "type": "METADATA_RAW", + "links": null, + "shape": 3 + } + ], + "properties": { + "Node name for S&R": "Preview from metadata [Crystools]" + } + } + ], + "links": [ + [ + 1, + 1, + 3, + 2, + 0, + "METADATA_RAW" + ] + ], + "groups": [], + "config": {}, + "extra": {}, + "version": 0.4 +} \ No newline at end of file diff --git a/ComfyUI-Crystools/samples/image-resolution.json b/ComfyUI-Crystools/samples/image-resolution.json new file mode 100644 index 0000000000000000000000000000000000000000..78633841a193fe592338ba25383c2594a1983e71 --- /dev/null +++ b/ComfyUI-Crystools/samples/image-resolution.json @@ -0,0 +1,512 @@ +{ + "last_node_id": 13, + "last_link_id": 11, + "nodes": [ + { + "id": 7, + "type": "CLIPTextEncode", + "pos": [ + 413, + 389 + ], + "size": { + "0": 425.27801513671875, + "1": 180.6060791015625 + }, + "flags": {}, + "order": 4, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 5 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 6 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "CLIPTextEncode" + }, + "widgets_values": [ + "text, watermark" + ] + }, + { + "id": 6, + "type": "CLIPTextEncode", + "pos": [ + 415, + 186 + ], + "size": { + "0": 422.84503173828125, + "1": 164.31304931640625 + }, + "flags": {}, + "order": 3, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 3 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 4 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "CLIPTextEncode" + }, + "widgets_values": [ + "beautiful scenery nature glass bottle landscape, , purple galaxy bottle," + ] + }, + { + "id": 5, + "type": "EmptyLatentImage", + "pos": [ + 473, + 609 + ], + "size": { + "0": 315, + "1": 106 + }, + "flags": {}, + "order": 0, + "mode": 0, + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "links": [ + 2 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "EmptyLatentImage" + }, + "widgets_values": [ + 512, + 512, + 1 + ] + }, + { + "id": 4, + "type": "CheckpointLoaderSimple", + "pos": [ + 26, + 474 + ], + "size": { + "0": 315, + "1": 98 + }, + "flags": {}, + "order": 1, + "mode": 0, + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [ + 1 + ], + "slot_index": 0 + }, + { + "name": "CLIP", + "type": "CLIP", + "links": [ + 3, + 5 + ], + "slot_index": 1 + }, + { + "name": "VAE", + "type": "VAE", + "links": [ + 8 + ], + "slot_index": 2 + } + ], + "properties": { + "Node name for S&R": "CheckpointLoaderSimple" + }, + "widgets_values": [ + "SD1.5\\3d\\disneyPixarCartoon_v10.safetensors" + ] + }, + { + "id": 3, + "type": "KSampler", + "pos": [ + 863, + 186 + ], + "size": [ + 325, + 475 + ], + "flags": {}, + "order": 6, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 1 + }, + { + "name": "positive", + "type": "CONDITIONING", + "link": 4 + }, + { + "name": "negative", + "type": "CONDITIONING", + "link": 6 + }, + { + "name": "latent_image", + "type": "LATENT", + "link": 2 + } + ], + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "links": [ + 7 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "KSampler" + }, + "widgets_values": [ + 156680208700286, + "fixed", + 20, + 8, + "euler", + "normal", + 1 + ] + }, + { + "id": 8, + "type": "VAEDecode", + "pos": [ + 1209, + 188 + ], + "size": { + "0": 210, + "1": 46 + }, + "flags": {}, + "order": 7, + "mode": 0, + "inputs": [ + { + "name": "samples", + "type": "LATENT", + "link": 7 + }, + { + "name": "vae", + "type": "VAE", + "link": 8 + } + ], + "outputs": [ + { + "name": "IMAGE", + "type": "IMAGE", + "links": [ + 9, + 10 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "VAEDecode" + } + }, + { + "id": 9, + "type": "SaveImage", + "pos": [ + 1475, + 250 + ], + "size": [ + 200, + 275 + ], + "flags": {}, + "order": 8, + "mode": 0, + "inputs": [ + { + "name": "images", + "type": "IMAGE", + "link": 9 + } + ], + "properties": {}, + "widgets_values": [ + "ComfyUI" + ] + }, + { + "id": 10, + "type": "Get resolution [Crystools]", + "pos": [ + 1475, + 100 + ], + "size": { + "0": 200, + "1": 100 + }, + "flags": {}, + "order": 9, + "mode": 0, + "inputs": [ + { + "name": "image", + "type": "IMAGE", + "link": 10 + } + ], + "outputs": [ + { + "name": "width", + "type": "INT", + "links": null, + "shape": 3 + }, + { + "name": "height", + "type": "INT", + "links": null, + "shape": 3 + } + ], + "properties": { + "Node name for S&R": "Get resolution [Crystools]" + } + }, + { + "id": 12, + "type": "Load image with metadata [Crystools]", + "pos": [ + 1350, + 625 + ], + "size": [ + 325, + 350 + ], + "flags": {}, + "order": 2, + "mode": 0, + "outputs": [ + { + "name": "image", + "type": "IMAGE", + "links": [ + 11 + ], + "shape": 3, + "slot_index": 0 + }, + { + "name": "mask", + "type": "MASK", + "links": null, + "shape": 3 + }, + { + "name": "prompt", + "type": "JSON", + "links": null, + "shape": 3 + }, + { + "name": "Metadata RAW", + "type": "METADATA_RAW", + "links": null, + "shape": 3 + } + ], + "properties": { + "Node name for S&R": "Load image with metadata [Crystools]" + }, + "widgets_values": [ + "tests/ComfyUI_00314_20-8-euler.png", + "image" + ] + }, + { + "id": 13, + "type": "Get resolution [Crystools]", + "pos": [ + 1725, + 625 + ], + "size": { + "0": 200, + "1": 100 + }, + "flags": {}, + "order": 5, + "mode": 0, + "inputs": [ + { + "name": "image", + "type": "IMAGE", + "link": 11 + } + ], + "outputs": [ + { + "name": "width", + "type": "INT", + "links": null, + "shape": 3 + }, + { + "name": "height", + "type": "INT", + "links": null, + "shape": 3 + } + ], + "properties": { + "Node name for S&R": "Get resolution [Crystools]" + } + } + ], + "links": [ + [ + 1, + 4, + 0, + 3, + 0, + "MODEL" + ], + [ + 2, + 5, + 0, + 3, + 3, + "LATENT" + ], + [ + 3, + 4, + 1, + 6, + 0, + "CLIP" + ], + [ + 4, + 6, + 0, + 3, + 1, + "CONDITIONING" + ], + [ + 5, + 4, + 1, + 7, + 0, + "CLIP" + ], + [ + 6, + 7, + 0, + 3, + 2, + "CONDITIONING" + ], + [ + 7, + 3, + 0, + 8, + 0, + "LATENT" + ], + [ + 8, + 4, + 2, + 8, + 1, + "VAE" + ], + [ + 9, + 8, + 0, + 9, + 0, + "IMAGE" + ], + [ + 10, + 8, + 0, + 10, + 0, + "IMAGE" + ], + [ + 11, + 12, + 0, + 13, + 0, + "IMAGE" + ] + ], + "groups": [], + "config": {}, + "extra": {}, + "version": 0.4 +} \ No newline at end of file diff --git a/ComfyUI-Crystools/samples/image-save.json b/ComfyUI-Crystools/samples/image-save.json new file mode 100644 index 0000000000000000000000000000000000000000..5a993a81ee234560af8e0977737af15b0bd64af1 --- /dev/null +++ b/ComfyUI-Crystools/samples/image-save.json @@ -0,0 +1,422 @@ +{ + "last_node_id": 11, + "last_link_id": 11, + "nodes": [ + { + "id": 7, + "type": "CLIPTextEncode", + "pos": [ + 413, + 389 + ], + "size": { + "0": 425.27801513671875, + "1": 180.6060791015625 + }, + "flags": {}, + "order": 3, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 5 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 6 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "CLIPTextEncode" + }, + "widgets_values": [ + "text, watermark" + ] + }, + { + "id": 6, + "type": "CLIPTextEncode", + "pos": [ + 415, + 186 + ], + "size": { + "0": 422.84503173828125, + "1": 164.31304931640625 + }, + "flags": {}, + "order": 2, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 3 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 4 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "CLIPTextEncode" + }, + "widgets_values": [ + "beautiful scenery nature glass bottle landscape, , purple galaxy bottle," + ] + }, + { + "id": 5, + "type": "EmptyLatentImage", + "pos": [ + 473, + 609 + ], + "size": { + "0": 315, + "1": 106 + }, + "flags": {}, + "order": 0, + "mode": 0, + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "links": [ + 2 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "EmptyLatentImage" + }, + "widgets_values": [ + 512, + 512, + 1 + ] + }, + { + "id": 3, + "type": "KSampler", + "pos": [ + 863, + 186 + ], + "size": [ + 325, + 475 + ], + "flags": {}, + "order": 4, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 1 + }, + { + "name": "positive", + "type": "CONDITIONING", + "link": 4 + }, + { + "name": "negative", + "type": "CONDITIONING", + "link": 6 + }, + { + "name": "latent_image", + "type": "LATENT", + "link": 2 + } + ], + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "links": [ + 7 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "KSampler" + }, + "widgets_values": [ + 156680208700286, + "fixed", + 20, + 8, + "euler", + "normal", + 1 + ] + }, + { + "id": 4, + "type": "CheckpointLoaderSimple", + "pos": [ + 26, + 474 + ], + "size": { + "0": 315, + "1": 98 + }, + "flags": {}, + "order": 1, + "mode": 0, + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [ + 1 + ], + "slot_index": 0 + }, + { + "name": "CLIP", + "type": "CLIP", + "links": [ + 3, + 5 + ], + "slot_index": 1 + }, + { + "name": "VAE", + "type": "VAE", + "links": [ + 8 + ], + "slot_index": 2 + } + ], + "properties": { + "Node name for S&R": "CheckpointLoaderSimple" + }, + "widgets_values": [ + "SD1.5\\anime\\chilloutmix_NiPrunedFp32Fix.safetensors" + ] + }, + { + "id": 8, + "type": "VAEDecode", + "pos": [ + 1209, + 188 + ], + "size": { + "0": 210, + "1": 46 + }, + "flags": {}, + "order": 5, + "mode": 0, + "inputs": [ + { + "name": "samples", + "type": "LATENT", + "link": 7 + }, + { + "name": "vae", + "type": "VAE", + "link": 8 + } + ], + "outputs": [ + { + "name": "IMAGE", + "type": "IMAGE", + "links": [ + 10 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "VAEDecode" + } + }, + { + "id": 10, + "type": "Save image with extra metadata [Crystools]", + "pos": [ + 1450, + 200 + ], + "size": [ + 425, + 550 + ], + "flags": {}, + "order": 6, + "mode": 0, + "inputs": [ + { + "name": "image", + "type": "IMAGE", + "link": 10 + } + ], + "outputs": [ + { + "name": "Metadata RAW", + "type": "METADATA_RAW", + "links": [ + 11 + ], + "shape": 3, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "Save image with extra metadata [Crystools]" + }, + "widgets_values": [ + "ComfyUI", + false, + "{\n \"Title\": \"Image generated by Crystian\",\n \"Description\": \"More info: https:\\/\\/www.instagram.com\\/crystian.ia\",\n \"Author\": \"crystian.ia\",\n \"Software\": \"ComfyUI\",\n \"Category\": \"StableDiffusion\",\n \"Rating\": 5,\n \"UserComment\": \"\",\n \"Keywords\": [\n \"\"\n ],\n \"Copyrights\": \"\"\n}" + ] + }, + { + "id": 11, + "type": "Show any to JSON [Crystools]", + "pos": [ + 1925, + 200 + ], + "size": [ + 425, + 300 + ], + "flags": {}, + "order": 7, + "mode": 0, + "inputs": [ + { + "name": "any_value", + "type": "*", + "link": 11 + } + ], + "outputs": [ + { + "name": "string", + "type": "STRING", + "links": null, + "shape": 3 + } + ], + "properties": { + "Node name for S&R": "Show any to JSON [Crystools]" + } + } + ], + "links": [ + [ + 1, + 4, + 0, + 3, + 0, + "MODEL" + ], + [ + 2, + 5, + 0, + 3, + 3, + "LATENT" + ], + [ + 3, + 4, + 1, + 6, + 0, + "CLIP" + ], + [ + 4, + 6, + 0, + 3, + 1, + "CONDITIONING" + ], + [ + 5, + 4, + 1, + 7, + 0, + "CLIP" + ], + [ + 6, + 7, + 0, + 3, + 2, + "CONDITIONING" + ], + [ + 7, + 3, + 0, + 8, + 0, + "LATENT" + ], + [ + 8, + 4, + 2, + 8, + 1, + "VAE" + ], + [ + 10, + 8, + 0, + 10, + 0, + "IMAGE" + ], + [ + 11, + 10, + 0, + 11, + 0, + "*" + ] + ], + "groups": [], + "config": {}, + "extra": {}, + "version": 0.4 +} \ No newline at end of file diff --git a/ComfyUI-Crystools/samples/list-any.json b/ComfyUI-Crystools/samples/list-any.json new file mode 100644 index 0000000000000000000000000000000000000000..435c584dff1b2c63729007612660e89289ac31ae --- /dev/null +++ b/ComfyUI-Crystools/samples/list-any.json @@ -0,0 +1,375 @@ +{ + "last_node_id": 15, + "last_link_id": 13, + "nodes": [ + { + "id": 10, + "type": "Primitive integer [Crystools]", + "pos": [ + 175, + 525 + ], + "size": { + "0": 315, + "1": 58 + }, + "flags": {}, + "order": 0, + "mode": 0, + "outputs": [ + { + "name": "int", + "type": "INT", + "links": [ + 9 + ], + "shape": 3, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "Primitive integer [Crystools]" + }, + "widgets_values": [ + 1 + ] + }, + { + "id": 11, + "type": "Primitive float [Crystools]", + "pos": [ + 175, + 625 + ], + "size": { + "0": 315, + "1": 58 + }, + "flags": {}, + "order": 1, + "mode": 0, + "outputs": [ + { + "name": "float", + "type": "FLOAT", + "links": [ + 10 + ], + "shape": 3, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "Primitive float [Crystools]" + }, + "widgets_values": [ + 1 + ] + }, + { + "id": 9, + "type": "Primitive string multiline [Crystools]", + "pos": [ + 90, + 275 + ], + "size": { + "0": 400, + "1": 200 + }, + "flags": {}, + "order": 2, + "mode": 0, + "outputs": [ + { + "name": "string", + "type": "STRING", + "links": [ + 8 + ], + "shape": 3, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "Primitive string multiline [Crystools]" + }, + "widgets_values": [ + "sample\nmultiline" + ] + }, + { + "id": 12, + "type": "Primitive string [Crystools]", + "pos": [ + 240, + 175 + ], + "size": { + "0": 250, + "1": 58 + }, + "flags": {}, + "order": 3, + "mode": 0, + "outputs": [ + { + "name": "string", + "type": "STRING", + "links": [ + 6 + ], + "shape": 3, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "Primitive string [Crystools]" + }, + "widgets_values": [ + "sample" + ] + }, + { + "id": 14, + "type": "Load image with metadata [Crystools]", + "pos": [ + 165, + 750 + ], + "size": [ + 325, + 350 + ], + "flags": {}, + "order": 4, + "mode": 0, + "outputs": [ + { + "name": "image", + "type": "IMAGE", + "links": [ + 11 + ], + "shape": 3, + "slot_index": 0 + }, + { + "name": "mask", + "type": "MASK", + "links": null, + "shape": 3 + }, + { + "name": "prompt", + "type": "JSON", + "links": null, + "shape": 3 + }, + { + "name": "Metadata RAW", + "type": "METADATA_RAW", + "links": null, + "shape": 3 + } + ], + "properties": { + "Node name for S&R": "Load image with metadata [Crystools]" + }, + "widgets_values": [ + "tests/ComfyUI_00314_20-8-euler.png", + "image" + ] + }, + { + "id": 7, + "type": "List of any [Crystools]", + "pos": [ + 600, + 325 + ], + "size": { + "0": 210, + "1": 166 + }, + "flags": {}, + "order": 6, + "mode": 0, + "inputs": [ + { + "name": "any_1", + "type": "*", + "link": 5 + }, + { + "name": "any_2", + "type": "*", + "link": 6 + }, + { + "name": "any_3", + "type": "*", + "link": 8 + }, + { + "name": "any_4", + "type": "*", + "link": 9 + }, + { + "name": "any_5", + "type": "*", + "link": 10 + }, + { + "name": "any_6", + "type": "*", + "link": 11 + }, + { + "name": "any_7", + "type": "*", + "link": null + }, + { + "name": "any_8", + "type": "*", + "link": null + } + ], + "outputs": [ + { + "name": "any_list", + "type": "COMBO", + "links": [ + 12 + ], + "shape": 6, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "List of any [Crystools]" + } + }, + { + "id": 15, + "type": "Show any [Crystools]", + "pos": [ + 850, + 325 + ], + "size": [ + 575, + 625 + ], + "flags": {}, + "order": 7, + "mode": 0, + "inputs": [ + { + "name": "any_value", + "type": "*", + "link": 12 + } + ], + "properties": { + "Node name for S&R": "Show any [Crystools]" + } + }, + { + "id": 8, + "type": "Primitive boolean [Crystools]", + "pos": [ + 175, + 75 + ], + "size": { + "0": 315, + "1": 58 + }, + "flags": {}, + "order": 5, + "mode": 0, + "outputs": [ + { + "name": "boolean", + "type": "BOOLEAN", + "links": [ + 5 + ], + "shape": 3, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "Primitive boolean [Crystools]" + }, + "widgets_values": [ + true + ] + } + ], + "links": [ + [ + 5, + 8, + 0, + 7, + 0, + "*" + ], + [ + 6, + 12, + 0, + 7, + 1, + "*" + ], + [ + 8, + 9, + 0, + 7, + 2, + "*" + ], + [ + 9, + 10, + 0, + 7, + 3, + "*" + ], + [ + 10, + 11, + 0, + 7, + 4, + "*" + ], + [ + 11, + 14, + 0, + 7, + 5, + "*" + ], + [ + 12, + 7, + 0, + 15, + 0, + "*" + ] + ], + "groups": [], + "config": {}, + "extra": {}, + "version": 0.4 +} \ No newline at end of file diff --git a/ComfyUI-Crystools/samples/list-strings.json b/ComfyUI-Crystools/samples/list-strings.json new file mode 100644 index 0000000000000000000000000000000000000000..098c1034e245b07571d9704ea02277c6f7884e3c --- /dev/null +++ b/ComfyUI-Crystools/samples/list-strings.json @@ -0,0 +1,177 @@ +{ + "last_node_id": 6, + "last_link_id": 4, + "nodes": [ + { + "id": 3, + "type": "Primitive string [Crystools]", + "pos": [ + 50, + 100 + ], + "size": { + "0": 250, + "1": 58 + }, + "flags": {}, + "order": 0, + "mode": 0, + "outputs": [ + { + "name": "string", + "type": "STRING", + "links": [ + 2 + ], + "shape": 3, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "Primitive string [Crystools]" + }, + "widgets_values": [ + "folder2" + ] + }, + { + "id": 2, + "type": "List of strings [Crystools]", + "pos": [ + 350, + 100 + ], + "size": { + "0": 325, + "1": 275 + }, + "flags": {}, + "order": 1, + "mode": 0, + "inputs": [ + { + "name": "string_2", + "type": "STRING", + "link": 2, + "widget": { + "name": "string_2" + } + } + ], + "outputs": [ + { + "name": "concatenated", + "type": "STRING", + "links": [ + 4 + ], + "shape": 3, + "slot_index": 0 + }, + { + "name": "list_string", + "type": "ListString", + "links": [ + 3 + ], + "shape": 6, + "slot_index": 1 + } + ], + "properties": { + "Node name for S&R": "List of strings [Crystools]" + }, + "widgets_values": [ + "folder1", + "", + "folder3", + "", + "", + "", + "", + "", + "/" + ] + }, + { + "id": 6, + "type": "Show any [Crystools]", + "pos": [ + 775, + 100 + ], + "size": { + "0": 375, + "1": 150 + }, + "flags": {}, + "order": 2, + "mode": 0, + "inputs": [ + { + "name": "any_value", + "type": "*", + "link": 4 + } + ], + "properties": { + "Node name for S&R": "Show any [Crystools]" + } + }, + { + "id": 5, + "type": "Show any [Crystools]", + "pos": [ + 775, + 325 + ], + "size": { + "0": 375, + "1": 150 + }, + "flags": {}, + "order": 3, + "mode": 0, + "inputs": [ + { + "name": "any_value", + "type": "*", + "link": 3 + } + ], + "properties": { + "Node name for S&R": "Show any [Crystools]" + } + } + ], + "links": [ + [ + 2, + 3, + 0, + 2, + 0, + "STRING" + ], + [ + 3, + 2, + 1, + 5, + 0, + "*" + ], + [ + 4, + 2, + 0, + 6, + 0, + "*" + ] + ], + "groups": [], + "config": {}, + "extra": {}, + "version": 0.4 +} \ No newline at end of file diff --git a/ComfyUI-Crystools/samples/metadata-comparator.json b/ComfyUI-Crystools/samples/metadata-comparator.json new file mode 100644 index 0000000000000000000000000000000000000000..83251cd91868e25aaabd973671759083f55e591f --- /dev/null +++ b/ComfyUI-Crystools/samples/metadata-comparator.json @@ -0,0 +1,168 @@ +{ + "last_node_id": 10, + "last_link_id": 9, + "nodes": [ + { + "id": 1, + "type": "Load image with metadata [Crystools]", + "pos": [ + 100, + 75 + ], + "size": [ + 325, + 350 + ], + "flags": {}, + "order": 0, + "mode": 0, + "outputs": [ + { + "name": "image", + "type": "IMAGE", + "links": null, + "shape": 3 + }, + { + "name": "mask", + "type": "MASK", + "links": null, + "shape": 3 + }, + { + "name": "prompt", + "type": "JSON", + "links": null, + "shape": 3 + }, + { + "name": "Metadata RAW", + "type": "METADATA_RAW", + "links": [ + 8 + ], + "shape": 3, + "slot_index": 3 + } + ], + "properties": { + "Node name for S&R": "Load image with metadata [Crystools]" + }, + "widgets_values": [ + "tests/ComfyUI_00314_20-8-euler.png", + "image" + ] + }, + { + "id": 9, + "type": "Load image with metadata [Crystools]", + "pos": [ + 100, + 500 + ], + "size": [ + 325, + 350 + ], + "flags": {}, + "order": 1, + "mode": 0, + "outputs": [ + { + "name": "image", + "type": "IMAGE", + "links": null, + "shape": 3 + }, + { + "name": "mask", + "type": "MASK", + "links": null, + "shape": 3 + }, + { + "name": "prompt", + "type": "JSON", + "links": null, + "shape": 3 + }, + { + "name": "Metadata RAW", + "type": "METADATA_RAW", + "links": [ + 9 + ], + "shape": 3, + "slot_index": 3 + } + ], + "properties": { + "Node name for S&R": "Load image with metadata [Crystools]" + }, + "widgets_values": [ + "tests/ComfyUI_00315_21-81-heun.png", + "image" + ] + }, + { + "id": 10, + "type": "Metadata comparator [Crystools]", + "pos": [ + 550, + 100 + ], + "size": [ + 375, + 750 + ], + "flags": {}, + "order": 2, + "mode": 0, + "inputs": [ + { + "name": "metadata_raw_old", + "type": "METADATA_RAW", + "link": 8 + }, + { + "name": "metadata_raw_new", + "type": "METADATA_RAW", + "link": 9 + } + ], + "outputs": [ + { + "name": "diff", + "type": "JSON", + "links": null, + "shape": 3 + } + ], + "properties": { + "Node name for S&R": "Metadata comparator [Crystools]" + } + } + ], + "links": [ + [ + 8, + 1, + 3, + 10, + 0, + "METADATA_RAW" + ], + [ + 9, + 9, + 3, + 10, + 1, + "METADATA_RAW" + ] + ], + "groups": [], + "config": {}, + "extra": {}, + "version": 0.4 +} \ No newline at end of file diff --git a/ComfyUI-Crystools/samples/metadata-extractor.json b/ComfyUI-Crystools/samples/metadata-extractor.json new file mode 100644 index 0000000000000000000000000000000000000000..f69501af0d1564da89f71f0f2e999029bb8176dd --- /dev/null +++ b/ComfyUI-Crystools/samples/metadata-extractor.json @@ -0,0 +1,350 @@ +{ + "last_node_id": 8, + "last_link_id": 7, + "nodes": [ + { + "id": 5, + "type": "Show any [Crystools]", + "pos": [ + 1100, + 575 + ], + "size": [ + 475, + 225 + ], + "flags": {}, + "order": 4, + "mode": 0, + "inputs": [ + { + "name": "any_value", + "type": "*", + "link": 4 + } + ], + "properties": { + "Node name for S&R": "Show any [Crystools]" + } + }, + { + "id": 4, + "type": "Show any [Crystools]", + "pos": [ + 1100, + 50 + ], + "size": [ + 475, + 450 + ], + "flags": {}, + "order": 3, + "mode": 0, + "inputs": [ + { + "name": "any_value", + "type": "*", + "link": 3 + } + ], + "properties": { + "Node name for S&R": "Show any [Crystools]" + } + }, + { + "id": 8, + "type": "Show any [Crystools]", + "pos": [ + 100, + 900 + ], + "size": [ + 450, + 375 + ], + "flags": {}, + "order": 7, + "mode": 0, + "inputs": [ + { + "name": "any_value", + "type": "*", + "link": 7 + } + ], + "properties": { + "Node name for S&R": "Show any [Crystools]" + } + }, + { + "id": 1, + "type": "Load image with metadata [Crystools]", + "pos": [ + 100, + 75 + ], + "size": [ + 325, + 350 + ], + "flags": {}, + "order": 0, + "mode": 0, + "outputs": [ + { + "name": "image", + "type": "IMAGE", + "links": null, + "shape": 3 + }, + { + "name": "mask", + "type": "MASK", + "links": null, + "shape": 3 + }, + { + "name": "prompt", + "type": "JSON", + "links": null, + "shape": 3 + }, + { + "name": "Metadata RAW", + "type": "METADATA_RAW", + "links": [ + 1 + ], + "shape": 3, + "slot_index": 3 + } + ], + "properties": { + "Node name for S&R": "Load image with metadata [Crystools]" + }, + "widgets_values": [ + "tests/ComfyUI_00314_20-8-euler.png", + "image" + ] + }, + { + "id": 2, + "type": "Metadata extractor [Crystools]", + "pos": [ + 125, + 625 + ], + "size": { + "0": 355.20001220703125, + "1": 126 + }, + "flags": {}, + "order": 1, + "mode": 0, + "inputs": [ + { + "name": "metadata_raw", + "type": "METADATA_RAW", + "link": 1 + } + ], + "outputs": [ + { + "name": "prompt", + "type": "JSON", + "links": [ + 2 + ], + "shape": 3, + "slot_index": 0 + }, + { + "name": "workflow", + "type": "JSON", + "links": [ + 3 + ], + "shape": 3, + "slot_index": 1 + }, + { + "name": "file info", + "type": "JSON", + "links": [ + 4 + ], + "shape": 3, + "slot_index": 2 + }, + { + "name": "raw to JSON", + "type": "JSON", + "links": [ + 5 + ], + "shape": 3, + "slot_index": 3 + }, + { + "name": "raw to property", + "type": "STRING", + "links": [ + 6 + ], + "shape": 3, + "slot_index": 4 + }, + { + "name": "raw to csv", + "type": "STRING", + "links": [ + 7 + ], + "shape": 3, + "slot_index": 5 + } + ], + "properties": { + "Node name for S&R": "Metadata extractor [Crystools]" + } + }, + { + "id": 6, + "type": "Show any [Crystools]", + "pos": [ + 1100, + 900 + ], + "size": [ + 475, + 375 + ], + "flags": {}, + "order": 5, + "mode": 0, + "inputs": [ + { + "name": "any_value", + "type": "*", + "link": 5 + } + ], + "properties": { + "Node name for S&R": "Show any [Crystools]" + } + }, + { + "id": 7, + "type": "Show any [Crystools]", + "pos": [ + 600, + 900 + ], + "size": [ + 450, + 375 + ], + "flags": {}, + "order": 6, + "mode": 0, + "inputs": [ + { + "name": "any_value", + "type": "*", + "link": 6 + } + ], + "properties": { + "Node name for S&R": "Show any [Crystools]" + } + }, + { + "id": 3, + "type": "Show any [Crystools]", + "pos": [ + 625, + 50 + ], + "size": [ + 425, + 450 + ], + "flags": {}, + "order": 2, + "mode": 0, + "inputs": [ + { + "name": "any_value", + "type": "*", + "link": 2 + } + ], + "properties": { + "Node name for S&R": "Show any [Crystools]" + } + } + ], + "links": [ + [ + 1, + 1, + 3, + 2, + 0, + "METADATA_RAW" + ], + [ + 2, + 2, + 0, + 3, + 0, + "*" + ], + [ + 3, + 2, + 1, + 4, + 0, + "*" + ], + [ + 4, + 2, + 2, + 5, + 0, + "*" + ], + [ + 5, + 2, + 3, + 6, + 0, + "*" + ], + [ + 6, + 2, + 4, + 7, + 0, + "*" + ], + [ + 7, + 2, + 5, + 8, + 0, + "*" + ] + ], + "groups": [], + "config": {}, + "extra": {}, + "version": 0.4 +} \ No newline at end of file diff --git a/ComfyUI-Crystools/samples/pipe-1.json b/ComfyUI-Crystools/samples/pipe-1.json new file mode 100644 index 0000000000000000000000000000000000000000..ced5fa1fc1a5232f7b1687cc39671dfb4a1a736c --- /dev/null +++ b/ComfyUI-Crystools/samples/pipe-1.json @@ -0,0 +1,564 @@ +{ + "last_node_id": 15, + "last_link_id": 29, + "nodes": [ + { + "id": 3, + "type": "KSampler", + "pos": [ + 1350, + 125 + ], + "size": [ + 325, + 475 + ], + "flags": {}, + "order": 6, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 17 + }, + { + "name": "positive", + "type": "CONDITIONING", + "link": 26 + }, + { + "name": "negative", + "type": "CONDITIONING", + "link": 25 + }, + { + "name": "latent_image", + "type": "LATENT", + "link": 24 + } + ], + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "links": [ + 7 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "KSampler" + }, + "widgets_values": [ + 156680208700286, + "fixed", + 20, + 8, + "euler", + "normal", + 1 + ] + }, + { + "id": 8, + "type": "VAEDecode", + "pos": [ + 1400, + 675 + ], + "size": { + "0": 210, + "1": 46 + }, + "flags": {}, + "order": 7, + "mode": 0, + "inputs": [ + { + "name": "samples", + "type": "LATENT", + "link": 7 + }, + { + "name": "vae", + "type": "VAE", + "link": 27 + } + ], + "outputs": [ + { + "name": "IMAGE", + "type": "IMAGE", + "links": [ + 9 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "VAEDecode" + } + }, + { + "id": 9, + "type": "SaveImage", + "pos": [ + 1400, + 800 + ], + "size": [ + 200, + 275 + ], + "flags": {}, + "order": 8, + "mode": 0, + "inputs": [ + { + "name": "images", + "type": "IMAGE", + "link": 9 + } + ], + "properties": {}, + "widgets_values": [ + "ComfyUI" + ] + }, + { + "id": 7, + "type": "CLIPTextEncode", + "pos": [ + 75, + 525 + ], + "size": { + "0": 425.27801513671875, + "1": 180.6060791015625 + }, + "flags": {}, + "order": 3, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 5 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 22 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "CLIPTextEncode" + }, + "widgets_values": [ + "text, watermark" + ] + }, + { + "id": 15, + "type": "Pipe from any [Crystools]", + "pos": [ + 975, + 200 + ], + "size": { + "0": 216.59999084472656, + "1": 146 + }, + "flags": {}, + "order": 5, + "mode": 0, + "inputs": [ + { + "name": "CPipeAny", + "type": "CPipeAny", + "link": 12 + } + ], + "outputs": [ + { + "name": "CPipeAny", + "type": "CPipeAny", + "links": null, + "shape": 3 + }, + { + "name": "any_1", + "type": "*", + "links": [ + 17 + ], + "shape": 3, + "slot_index": 1 + }, + { + "name": "any_2", + "type": "*", + "links": [ + 27 + ], + "shape": 3, + "slot_index": 2 + }, + { + "name": "any_3", + "type": "*", + "links": [ + 26 + ], + "shape": 3, + "slot_index": 3 + }, + { + "name": "any_4", + "type": "*", + "links": [ + 25 + ], + "shape": 3, + "slot_index": 4 + }, + { + "name": "any_5", + "type": "*", + "links": [ + 24 + ], + "shape": 3, + "slot_index": 5 + }, + { + "name": "any_6", + "type": "*", + "links": null, + "shape": 3 + } + ], + "properties": { + "Node name for S&R": "Pipe from any [Crystools]" + } + }, + { + "id": 6, + "type": "CLIPTextEncode", + "pos": [ + 75, + 275 + ], + "size": { + "0": 422.84503173828125, + "1": 164.31304931640625 + }, + "flags": {}, + "order": 2, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 3 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 29 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "CLIPTextEncode" + }, + "widgets_values": [ + "beautiful scenery nature glass bottle landscape, , purple galaxy bottle," + ] + }, + { + "id": 4, + "type": "CheckpointLoaderSimple", + "pos": [ + 175, + 100 + ], + "size": { + "0": 315, + "1": 98 + }, + "flags": {}, + "order": 0, + "mode": 0, + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [ + 13 + ], + "slot_index": 0 + }, + { + "name": "CLIP", + "type": "CLIP", + "links": [ + 3, + 5 + ], + "slot_index": 1 + }, + { + "name": "VAE", + "type": "VAE", + "links": [ + 28 + ], + "slot_index": 2 + } + ], + "properties": { + "Node name for S&R": "CheckpointLoaderSimple" + }, + "widgets_values": [ + "SD1.5\\3d\\disneyPixarCartoon_v10.safetensors" + ] + }, + { + "id": 5, + "type": "EmptyLatentImage", + "pos": [ + 175, + 775 + ], + "size": { + "0": 315, + "1": 106 + }, + "flags": {}, + "order": 1, + "mode": 0, + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "links": [ + 21 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "EmptyLatentImage" + }, + "widgets_values": [ + 512, + 512, + 1 + ] + }, + { + "id": 14, + "type": "Pipe to/edit any [Crystools]", + "pos": [ + 625, + 200 + ], + "size": { + "0": 216.59999084472656, + "1": 146 + }, + "flags": {}, + "order": 4, + "mode": 0, + "inputs": [ + { + "name": "CPipeAny", + "type": "CPipeAny", + "link": null + }, + { + "name": "any_1", + "type": "*", + "link": 13 + }, + { + "name": "any_2", + "type": "*", + "link": 28 + }, + { + "name": "any_3", + "type": "*", + "link": 29 + }, + { + "name": "any_4", + "type": "*", + "link": 22 + }, + { + "name": "any_5", + "type": "*", + "link": 21 + }, + { + "name": "any_6", + "type": "*", + "link": null + } + ], + "outputs": [ + { + "name": "CPipeAny", + "type": "CPipeAny", + "links": [ + 12 + ], + "shape": 3, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "Pipe to/edit any [Crystools]" + } + } + ], + "links": [ + [ + 3, + 4, + 1, + 6, + 0, + "CLIP" + ], + [ + 5, + 4, + 1, + 7, + 0, + "CLIP" + ], + [ + 7, + 3, + 0, + 8, + 0, + "LATENT" + ], + [ + 9, + 8, + 0, + 9, + 0, + "IMAGE" + ], + [ + 12, + 14, + 0, + 15, + 0, + "CPipeAny" + ], + [ + 13, + 4, + 0, + 14, + 1, + "*" + ], + [ + 17, + 15, + 1, + 3, + 0, + "MODEL" + ], + [ + 21, + 5, + 0, + 14, + 5, + "*" + ], + [ + 22, + 7, + 0, + 14, + 4, + "*" + ], + [ + 24, + 15, + 5, + 3, + 3, + "LATENT" + ], + [ + 25, + 15, + 4, + 3, + 2, + "CONDITIONING" + ], + [ + 26, + 15, + 3, + 3, + 1, + "CONDITIONING" + ], + [ + 27, + 15, + 2, + 8, + 1, + "VAE" + ], + [ + 28, + 4, + 2, + 14, + 2, + "*" + ], + [ + 29, + 6, + 0, + 14, + 3, + "*" + ] + ], + "groups": [], + "config": {}, + "extra": {}, + "version": 0.4 +} \ No newline at end of file diff --git a/ComfyUI-Crystools/samples/pipe-2.json b/ComfyUI-Crystools/samples/pipe-2.json new file mode 100644 index 0000000000000000000000000000000000000000..41f58a19fdfdeafad128d67854459c48f180b8dc --- /dev/null +++ b/ComfyUI-Crystools/samples/pipe-2.json @@ -0,0 +1,849 @@ +{ + "last_node_id": 19, + "last_link_id": 37, + "nodes": [ + { + "id": 3, + "type": "KSampler", + "pos": [ + 1350, + 125 + ], + "size": [ + 325, + 475 + ], + "flags": {}, + "order": 10, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 17 + }, + { + "name": "positive", + "type": "CONDITIONING", + "link": 26 + }, + { + "name": "negative", + "type": "CONDITIONING", + "link": 25 + }, + { + "name": "latent_image", + "type": "LATENT", + "link": 24 + } + ], + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "links": [ + 7 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "KSampler" + }, + "widgets_values": [ + 156680208700286, + "fixed", + 20, + 8, + "euler", + "normal", + 1 + ] + }, + { + "id": 8, + "type": "VAEDecode", + "pos": [ + 1400, + 675 + ], + "size": { + "0": 210, + "1": 46 + }, + "flags": {}, + "order": 11, + "mode": 0, + "inputs": [ + { + "name": "samples", + "type": "LATENT", + "link": 7 + }, + { + "name": "vae", + "type": "VAE", + "link": 27 + } + ], + "outputs": [ + { + "name": "IMAGE", + "type": "IMAGE", + "links": [ + 9 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "VAEDecode" + } + }, + { + "id": 9, + "type": "SaveImage", + "pos": [ + 1400, + 800 + ], + "size": [ + 200, + 275 + ], + "flags": {}, + "order": 12, + "mode": 0, + "inputs": [ + { + "name": "images", + "type": "IMAGE", + "link": 9 + } + ], + "properties": {}, + "widgets_values": [ + "ComfyUI" + ] + }, + { + "id": 7, + "type": "CLIPTextEncode", + "pos": [ + 75, + 525 + ], + "size": { + "0": 425.27801513671875, + "1": 180.6060791015625 + }, + "flags": {}, + "order": 3, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 5 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 22 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "CLIPTextEncode" + }, + "widgets_values": [ + "text, watermark" + ] + }, + { + "id": 15, + "type": "Pipe from any [Crystools]", + "pos": [ + 975, + 200 + ], + "size": { + "0": 216.59999084472656, + "1": 146 + }, + "flags": {}, + "order": 9, + "mode": 0, + "inputs": [ + { + "name": "CPipeAny", + "type": "CPipeAny", + "link": 32 + } + ], + "outputs": [ + { + "name": "CPipeAny", + "type": "CPipeAny", + "links": null, + "shape": 3 + }, + { + "name": "any_1", + "type": "*", + "links": [ + 17 + ], + "shape": 3, + "slot_index": 1 + }, + { + "name": "any_2", + "type": "*", + "links": [ + 27 + ], + "shape": 3, + "slot_index": 2 + }, + { + "name": "any_3", + "type": "*", + "links": [ + 26 + ], + "shape": 3, + "slot_index": 3 + }, + { + "name": "any_4", + "type": "*", + "links": [ + 25 + ], + "shape": 3, + "slot_index": 4 + }, + { + "name": "any_5", + "type": "*", + "links": [ + 24 + ], + "shape": 3, + "slot_index": 5 + }, + { + "name": "any_6", + "type": "*", + "links": null, + "shape": 3 + } + ], + "properties": { + "Node name for S&R": "Pipe from any [Crystools]" + } + }, + { + "id": 6, + "type": "CLIPTextEncode", + "pos": [ + 75, + 275 + ], + "size": { + "0": 422.84503173828125, + "1": 164.31304931640625 + }, + "flags": {}, + "order": 2, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 3 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 29 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "CLIPTextEncode" + }, + "widgets_values": [ + "beautiful scenery nature glass bottle landscape, , purple galaxy bottle," + ] + }, + { + "id": 5, + "type": "EmptyLatentImage", + "pos": [ + 175, + 775 + ], + "size": { + "0": 315, + "1": 106 + }, + "flags": {}, + "order": 0, + "mode": 0, + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "links": [ + 21 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "EmptyLatentImage" + }, + "widgets_values": [ + 512, + 512, + 1 + ] + }, + { + "id": 14, + "type": "Pipe to/edit any [Crystools]", + "pos": [ + 625, + 200 + ], + "size": { + "0": 216.59999084472656, + "1": 146 + }, + "flags": {}, + "order": 4, + "mode": 0, + "inputs": [ + { + "name": "CPipeAny", + "type": "CPipeAny", + "link": null + }, + { + "name": "any_1", + "type": "*", + "link": 13 + }, + { + "name": "any_2", + "type": "*", + "link": 28 + }, + { + "name": "any_3", + "type": "*", + "link": 29 + }, + { + "name": "any_4", + "type": "*", + "link": 22 + }, + { + "name": "any_5", + "type": "*", + "link": 21 + }, + { + "name": "any_6", + "type": "*", + "link": 33 + } + ], + "outputs": [ + { + "name": "CPipeAny", + "type": "CPipeAny", + "links": [ + 30 + ], + "shape": 3, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "Pipe to/edit any [Crystools]" + } + }, + { + "id": 16, + "type": "Pipe to/edit any [Crystools]", + "pos": [ + 950, + 475 + ], + "size": { + "0": 216.59999084472656, + "1": 146 + }, + "flags": {}, + "order": 8, + "mode": 0, + "inputs": [ + { + "name": "CPipeAny", + "type": "CPipeAny", + "link": 31 + }, + { + "name": "any_1", + "type": "*", + "link": null + }, + { + "name": "any_2", + "type": "*", + "link": null + }, + { + "name": "any_3", + "type": "*", + "link": 37 + }, + { + "name": "any_4", + "type": "*", + "link": null + }, + { + "name": "any_5", + "type": "*", + "link": null + }, + { + "name": "any_6", + "type": "*", + "link": null + } + ], + "outputs": [ + { + "name": "CPipeAny", + "type": "CPipeAny", + "links": [ + 32 + ], + "shape": 3, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "Pipe to/edit any [Crystools]" + } + }, + { + "id": 4, + "type": "CheckpointLoaderSimple", + "pos": [ + 175, + 100 + ], + "size": { + "0": 315, + "1": 98 + }, + "flags": {}, + "order": 1, + "mode": 0, + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [ + 13 + ], + "slot_index": 0 + }, + { + "name": "CLIP", + "type": "CLIP", + "links": [ + 3, + 5, + 33 + ], + "slot_index": 1 + }, + { + "name": "VAE", + "type": "VAE", + "links": [ + 28 + ], + "slot_index": 2 + } + ], + "properties": { + "Node name for S&R": "CheckpointLoaderSimple" + }, + "widgets_values": [ + "SD1.5\\3d\\disneyPixarCartoon_v10.safetensors" + ] + }, + { + "id": 17, + "type": "Pipe from any [Crystools]", + "pos": [ + 650, + 475 + ], + "size": { + "0": 216.59999084472656, + "1": 146 + }, + "flags": {}, + "order": 5, + "mode": 0, + "inputs": [ + { + "name": "CPipeAny", + "type": "CPipeAny", + "link": 30 + } + ], + "outputs": [ + { + "name": "CPipeAny", + "type": "CPipeAny", + "links": [ + 31 + ], + "shape": 3, + "slot_index": 0 + }, + { + "name": "any_1", + "type": "*", + "links": [], + "shape": 3, + "slot_index": 1 + }, + { + "name": "any_2", + "type": "*", + "links": [], + "shape": 3, + "slot_index": 2 + }, + { + "name": "any_3", + "type": "*", + "links": [ + 35 + ], + "shape": 3, + "slot_index": 3 + }, + { + "name": "any_4", + "type": "*", + "links": [], + "shape": 3, + "slot_index": 4 + }, + { + "name": "any_5", + "type": "*", + "links": [], + "shape": 3, + "slot_index": 5 + }, + { + "name": "any_6", + "type": "*", + "links": [ + 34 + ], + "shape": 3, + "slot_index": 6 + } + ], + "properties": { + "Node name for S&R": "Pipe from any [Crystools]" + } + }, + { + "id": 19, + "type": "ConditioningCombine", + "pos": [ + 925, + 750 + ], + "size": { + "0": 342.5999755859375, + "1": 46 + }, + "flags": {}, + "order": 7, + "mode": 0, + "inputs": [ + { + "name": "conditioning_1", + "type": "CONDITIONING", + "link": 35 + }, + { + "name": "conditioning_2", + "type": "CONDITIONING", + "link": 36 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 37 + ], + "shape": 3, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "ConditioningCombine" + } + }, + { + "id": 18, + "type": "CLIPTextEncode", + "pos": [ + 650, + 775 + ], + "size": [ + 200, + 75.99999237060547 + ], + "flags": {}, + "order": 6, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 34 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 36 + ], + "shape": 3, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "CLIPTextEncode" + }, + "widgets_values": [ + "at night" + ] + } + ], + "links": [ + [ + 3, + 4, + 1, + 6, + 0, + "CLIP" + ], + [ + 5, + 4, + 1, + 7, + 0, + "CLIP" + ], + [ + 7, + 3, + 0, + 8, + 0, + "LATENT" + ], + [ + 9, + 8, + 0, + 9, + 0, + "IMAGE" + ], + [ + 13, + 4, + 0, + 14, + 1, + "*" + ], + [ + 17, + 15, + 1, + 3, + 0, + "MODEL" + ], + [ + 21, + 5, + 0, + 14, + 5, + "*" + ], + [ + 22, + 7, + 0, + 14, + 4, + "*" + ], + [ + 24, + 15, + 5, + 3, + 3, + "LATENT" + ], + [ + 25, + 15, + 4, + 3, + 2, + "CONDITIONING" + ], + [ + 26, + 15, + 3, + 3, + 1, + "CONDITIONING" + ], + [ + 27, + 15, + 2, + 8, + 1, + "VAE" + ], + [ + 28, + 4, + 2, + 14, + 2, + "*" + ], + [ + 29, + 6, + 0, + 14, + 3, + "*" + ], + [ + 30, + 14, + 0, + 17, + 0, + "CPipeAny" + ], + [ + 31, + 17, + 0, + 16, + 0, + "CPipeAny" + ], + [ + 32, + 16, + 0, + 15, + 0, + "CPipeAny" + ], + [ + 33, + 4, + 1, + 14, + 6, + "*" + ], + [ + 34, + 17, + 6, + 18, + 0, + "CLIP" + ], + [ + 35, + 17, + 3, + 19, + 0, + "CONDITIONING" + ], + [ + 36, + 18, + 0, + 19, + 1, + "CONDITIONING" + ], + [ + 37, + 19, + 0, + 16, + 3, + "*" + ] + ], + "groups": [], + "config": {}, + "extra": {}, + "version": 0.4 +} \ No newline at end of file diff --git a/ComfyUI-Crystools/samples/switch.json b/ComfyUI-Crystools/samples/switch.json new file mode 100644 index 0000000000000000000000000000000000000000..46e75e276e554e1b917e65914da7bfa2d26a8036 --- /dev/null +++ b/ComfyUI-Crystools/samples/switch.json @@ -0,0 +1,496 @@ +{ + "last_node_id": 12, + "last_link_id": 16, + "nodes": [ + { + "id": 7, + "type": "CLIPTextEncode", + "pos": [ + 425, + 525 + ], + "size": { + "0": 425.27801513671875, + "1": 180.6060791015625 + }, + "flags": {}, + "order": 4, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 5 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 6 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "CLIPTextEncode" + }, + "widgets_values": [ + "text, watermark" + ] + }, + { + "id": 5, + "type": "EmptyLatentImage", + "pos": [ + 475, + 750 + ], + "size": { + "0": 315, + "1": 106 + }, + "flags": {}, + "order": 0, + "mode": 0, + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "links": [ + 2 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "EmptyLatentImage" + }, + "widgets_values": [ + 512, + 512, + 1 + ] + }, + { + "id": 8, + "type": "VAEDecode", + "pos": [ + 1675, + 325 + ], + "size": { + "0": 210, + "1": 46 + }, + "flags": {}, + "order": 8, + "mode": 0, + "inputs": [ + { + "name": "samples", + "type": "LATENT", + "link": 7 + }, + { + "name": "vae", + "type": "VAE", + "link": 8 + } + ], + "outputs": [ + { + "name": "IMAGE", + "type": "IMAGE", + "links": [ + 9 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "VAEDecode" + } + }, + { + "id": 9, + "type": "SaveImage", + "pos": [ + 1900, + 325 + ], + "size": { + "0": 210, + "1": 275 + }, + "flags": {}, + "order": 9, + "mode": 0, + "inputs": [ + { + "name": "images", + "type": "IMAGE", + "link": 9 + } + ], + "properties": {}, + "widgets_values": [ + "ComfyUI" + ] + }, + { + "id": 4, + "type": "CheckpointLoaderSimple", + "pos": [ + 50, + 625 + ], + "size": { + "0": 315, + "1": 98 + }, + "flags": {}, + "order": 1, + "mode": 0, + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [ + 1 + ], + "slot_index": 0 + }, + { + "name": "CLIP", + "type": "CLIP", + "links": [ + 3, + 5, + 14 + ], + "slot_index": 1 + }, + { + "name": "VAE", + "type": "VAE", + "links": [ + 8 + ], + "slot_index": 2 + } + ], + "properties": { + "Node name for S&R": "CheckpointLoaderSimple" + }, + "widgets_values": [ + "SD1.5\\3d\\disneyPixarCartoon_v10.safetensors" + ] + }, + { + "id": 3, + "type": "KSampler", + "pos": [ + 1325, + 325 + ], + "size": { + "0": 325, + "1": 475 + }, + "flags": {}, + "order": 7, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 1 + }, + { + "name": "positive", + "type": "CONDITIONING", + "link": 13 + }, + { + "name": "negative", + "type": "CONDITIONING", + "link": 6 + }, + { + "name": "latent_image", + "type": "LATENT", + "link": 2 + } + ], + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "links": [ + 7 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "KSampler" + }, + "widgets_values": [ + 156680208700286, + "fixed", + 20, + 8, + "euler", + "normal", + 1 + ] + }, + { + "id": 6, + "type": "CLIPTextEncode", + "pos": [ + 425, + 325 + ], + "size": { + "0": 422.84503173828125, + "1": 164.31304931640625 + }, + "flags": {}, + "order": 3, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 3 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 16 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "CLIPTextEncode" + }, + "widgets_values": [ + "beautiful scenery nature glass bottle landscape, , purple galaxy bottle," + ] + }, + { + "id": 10, + "type": "CLIPTextEncode", + "pos": [ + 425, + 100 + ], + "size": { + "0": 422.84503173828125, + "1": 164.31304931640625 + }, + "flags": {}, + "order": 5, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 14 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 15 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "CLIPTextEncode" + }, + "widgets_values": [ + "beautiful scenery nature glass bottle landscape, in the bottle should be a cat (seen the camera:1.2), purple galaxy bottle," + ] + }, + { + "id": 11, + "type": "Switch conditioning [Crystools]", + "pos": [ + 950, + 200 + ], + "size": { + "0": 315, + "1": 78 + }, + "flags": {}, + "order": 6, + "mode": 0, + "inputs": [ + { + "name": "on_true", + "type": "CONDITIONING", + "link": 15 + }, + { + "name": "on_false", + "type": "CONDITIONING", + "link": 16 + } + ], + "outputs": [ + { + "name": "conditioning", + "type": "CONDITIONING", + "links": [ + 13 + ], + "shape": 3, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "Switch conditioning [Crystools]" + }, + "widgets_values": [ + true + ] + }, + { + "id": 12, + "type": "Note", + "pos": [ + 950, + 75 + ], + "size": [ + 300, + 52 + ], + "flags": {}, + "order": 2, + "mode": 0, + "properties": { + "text": "" + }, + "widgets_values": [ + "change the switch to select a prompt" + ], + "color": "#432", + "bgcolor": "#653" + } + ], + "links": [ + [ + 1, + 4, + 0, + 3, + 0, + "MODEL" + ], + [ + 2, + 5, + 0, + 3, + 3, + "LATENT" + ], + [ + 3, + 4, + 1, + 6, + 0, + "CLIP" + ], + [ + 5, + 4, + 1, + 7, + 0, + "CLIP" + ], + [ + 6, + 7, + 0, + 3, + 2, + "CONDITIONING" + ], + [ + 7, + 3, + 0, + 8, + 0, + "LATENT" + ], + [ + 8, + 4, + 2, + 8, + 1, + "VAE" + ], + [ + 9, + 8, + 0, + 9, + 0, + "IMAGE" + ], + [ + 13, + 11, + 0, + 3, + 1, + "CONDITIONING" + ], + [ + 14, + 4, + 1, + 10, + 0, + "CLIP" + ], + [ + 15, + 10, + 0, + 11, + 0, + "CONDITIONING" + ], + [ + 16, + 6, + 0, + 11, + 1, + "CONDITIONING" + ] + ], + "groups": [], + "config": {}, + "extra": {}, + "version": 0.4 +} \ No newline at end of file diff --git a/ComfyUI-Crystools/samples/utils-json-comparator.json b/ComfyUI-Crystools/samples/utils-json-comparator.json new file mode 100644 index 0000000000000000000000000000000000000000..0e6517b8bcbb3603f95fecc3b9eeaa38e0073620 --- /dev/null +++ b/ComfyUI-Crystools/samples/utils-json-comparator.json @@ -0,0 +1,212 @@ +{ + "last_node_id": 4, + "last_link_id": 3, + "nodes": [ + { + "id": 1, + "type": "Load image with metadata [Crystools]", + "pos": [ + 200, + 250 + ], + "size": [ + 325, + 350 + ], + "flags": {}, + "order": 0, + "mode": 0, + "outputs": [ + { + "name": "image", + "type": "IMAGE", + "links": null, + "shape": 3 + }, + { + "name": "mask", + "type": "MASK", + "links": null, + "shape": 3 + }, + { + "name": "prompt", + "type": "JSON", + "links": [ + 1 + ], + "shape": 3, + "slot_index": 2 + }, + { + "name": "Metadata RAW", + "type": "METADATA_RAW", + "links": null, + "shape": 3 + } + ], + "properties": { + "Node name for S&R": "Load image with metadata [Crystools]" + }, + "widgets_values": [ + "tests/ComfyUI_00314_20-8-euler.png", + "image" + ] + }, + { + "id": 2, + "type": "Load image with metadata [Crystools]", + "pos": [ + 200, + 700 + ], + "size": [ + 325, + 350 + ], + "flags": {}, + "order": 1, + "mode": 0, + "outputs": [ + { + "name": "image", + "type": "IMAGE", + "links": null, + "shape": 3 + }, + { + "name": "mask", + "type": "MASK", + "links": null, + "shape": 3 + }, + { + "name": "prompt", + "type": "JSON", + "links": [ + 2 + ], + "shape": 3, + "slot_index": 2 + }, + { + "name": "Metadata RAW", + "type": "METADATA_RAW", + "links": null, + "shape": 3 + } + ], + "properties": { + "Node name for S&R": "Load image with metadata [Crystools]" + }, + "widgets_values": [ + "tests/ComfyUI_00315_21-81-heun.png", + "image" + ] + }, + { + "id": 3, + "type": "Json comparator [Crystools]", + "pos": [ + 650, + 275 + ], + "size": { + "0": 279.5999755859375, + "1": 46 + }, + "flags": {}, + "order": 2, + "mode": 0, + "inputs": [ + { + "name": "json_old", + "type": "JSON", + "link": 1 + }, + { + "name": "json_new", + "type": "JSON", + "link": 2 + } + ], + "outputs": [ + { + "name": "json_compared", + "type": "JSON", + "links": [ + 3 + ], + "shape": 3, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "Json comparator [Crystools]" + } + }, + { + "id": 4, + "type": "Show any to JSON [Crystools]", + "pos": [ + 650, + 450 + ], + "size": [ + 325, + 350 + ], + "flags": {}, + "order": 3, + "mode": 0, + "inputs": [ + { + "name": "any_value", + "type": "*", + "link": 3 + } + ], + "outputs": [ + { + "name": "string", + "type": "STRING", + "links": null, + "shape": 3 + } + ], + "properties": { + "Node name for S&R": "Show any to JSON [Crystools]" + } + } + ], + "links": [ + [ + 1, + 1, + 2, + 3, + 0, + "JSON" + ], + [ + 2, + 2, + 2, + 3, + 1, + "JSON" + ], + [ + 3, + 3, + 0, + 4, + 0, + "*" + ] + ], + "groups": [], + "config": {}, + "extra": {}, + "version": 0.4 +} \ No newline at end of file diff --git a/ComfyUI-Crystools/samples/utils-stats.json b/ComfyUI-Crystools/samples/utils-stats.json new file mode 100644 index 0000000000000000000000000000000000000000..8d4dd97d733fd750bf64a92f1fb2ee3aa1d29c21 --- /dev/null +++ b/ComfyUI-Crystools/samples/utils-stats.json @@ -0,0 +1,410 @@ +{ + "last_node_id": 10, + "last_link_id": 11, + "nodes": [ + { + "id": 7, + "type": "CLIPTextEncode", + "pos": [ + 413, + 389 + ], + "size": { + "0": 425.27801513671875, + "1": 180.6060791015625 + }, + "flags": {}, + "order": 3, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 5 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 6 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "CLIPTextEncode" + }, + "widgets_values": [ + "text, watermark" + ] + }, + { + "id": 6, + "type": "CLIPTextEncode", + "pos": [ + 415, + 186 + ], + "size": { + "0": 422.84503173828125, + "1": 164.31304931640625 + }, + "flags": {}, + "order": 2, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 3 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 4 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "CLIPTextEncode" + }, + "widgets_values": [ + "beautiful scenery nature glass bottle landscape, , purple galaxy bottle," + ] + }, + { + "id": 5, + "type": "EmptyLatentImage", + "pos": [ + 473, + 609 + ], + "size": { + "0": 315, + "1": 106 + }, + "flags": {}, + "order": 0, + "mode": 0, + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "links": [ + 2 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "EmptyLatentImage" + }, + "widgets_values": [ + 512, + 512, + 1 + ] + }, + { + "id": 8, + "type": "VAEDecode", + "pos": [ + 1675, + 300 + ], + "size": { + "0": 210, + "1": 46 + }, + "flags": {}, + "order": 6, + "mode": 0, + "inputs": [ + { + "name": "samples", + "type": "LATENT", + "link": 11 + }, + { + "name": "vae", + "type": "VAE", + "link": 8 + } + ], + "outputs": [ + { + "name": "IMAGE", + "type": "IMAGE", + "links": [ + 9 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "VAEDecode" + } + }, + { + "id": 4, + "type": "CheckpointLoaderSimple", + "pos": [ + 26, + 474 + ], + "size": { + "0": 315, + "1": 98 + }, + "flags": {}, + "order": 1, + "mode": 0, + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [ + 1 + ], + "slot_index": 0 + }, + { + "name": "CLIP", + "type": "CLIP", + "links": [ + 3, + 5 + ], + "slot_index": 1 + }, + { + "name": "VAE", + "type": "VAE", + "links": [ + 8 + ], + "slot_index": 2 + } + ], + "properties": { + "Node name for S&R": "CheckpointLoaderSimple" + }, + "widgets_values": [ + "SD1.5\\3d\\disneyPixarCartoon_v10.safetensors" + ] + }, + { + "id": 3, + "type": "KSampler", + "pos": [ + 863, + 186 + ], + "size": [ + 325, + 475 + ], + "flags": {}, + "order": 4, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 1 + }, + { + "name": "positive", + "type": "CONDITIONING", + "link": 4 + }, + { + "name": "negative", + "type": "CONDITIONING", + "link": 6 + }, + { + "name": "latent_image", + "type": "LATENT", + "link": 2 + } + ], + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "links": [ + 10 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "KSampler" + }, + "widgets_values": [ + 156680208700286, + "fixed", + 20, + 8, + "euler", + "normal", + 1 + ] + }, + { + "id": 10, + "type": "Stats system [Crystools]", + "pos": [ + 1275, + 175 + ], + "size": [ + 350, + 125 + ], + "flags": {}, + "order": 5, + "mode": 0, + "inputs": [ + { + "name": "latent", + "type": "LATENT", + "link": 10 + } + ], + "outputs": [ + { + "name": "latent", + "type": "LATENT", + "links": [ + 11 + ], + "shape": 3, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "Stats system [Crystools]" + } + }, + { + "id": 9, + "type": "SaveImage", + "pos": [ + 1925, + 300 + ], + "size": [ + 200, + 275 + ], + "flags": {}, + "order": 7, + "mode": 0, + "inputs": [ + { + "name": "images", + "type": "IMAGE", + "link": 9 + } + ], + "properties": {}, + "widgets_values": [ + "ComfyUI" + ] + } + ], + "links": [ + [ + 1, + 4, + 0, + 3, + 0, + "MODEL" + ], + [ + 2, + 5, + 0, + 3, + 3, + "LATENT" + ], + [ + 3, + 4, + 1, + 6, + 0, + "CLIP" + ], + [ + 4, + 6, + 0, + 3, + 1, + "CONDITIONING" + ], + [ + 5, + 4, + 1, + 7, + 0, + "CLIP" + ], + [ + 6, + 7, + 0, + 3, + 2, + "CONDITIONING" + ], + [ + 8, + 4, + 2, + 8, + 1, + "VAE" + ], + [ + 9, + 8, + 0, + 9, + 0, + "IMAGE" + ], + [ + 10, + 3, + 0, + 10, + 0, + "LATENT" + ], + [ + 11, + 10, + 0, + 8, + 0, + "LATENT" + ] + ], + "groups": [], + "config": {}, + "extra": {}, + "version": 0.4 +} \ No newline at end of file diff --git a/ComfyUI-Crystools/server/__init__.py b/ComfyUI-Crystools/server/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b320e3511d53a84e597f2e43dc2f31f66e413458 --- /dev/null +++ b/ComfyUI-Crystools/server/__init__.py @@ -0,0 +1 @@ +from .monitor import * \ No newline at end of file diff --git a/ComfyUI-Crystools/server/__pycache__/__init__.cpython-310.pyc b/ComfyUI-Crystools/server/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6581984c64c1d629d8b17fc01c7bf33265d25384 Binary files /dev/null and b/ComfyUI-Crystools/server/__pycache__/__init__.cpython-310.pyc differ diff --git a/ComfyUI-Crystools/server/__pycache__/monitor.cpython-310.pyc b/ComfyUI-Crystools/server/__pycache__/monitor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22687df0a9c2a407e9b6b1668a7faba507246512 Binary files /dev/null and b/ComfyUI-Crystools/server/__pycache__/monitor.cpython-310.pyc differ diff --git a/ComfyUI-Crystools/server/monitor.py b/ComfyUI-Crystools/server/monitor.py new file mode 100644 index 0000000000000000000000000000000000000000..2424eca56cc2b00215517c552e9c5a74964102a5 --- /dev/null +++ b/ComfyUI-Crystools/server/monitor.py @@ -0,0 +1,125 @@ +from server import PromptServer +from aiohttp import web +from ..core import logger +from ..general import cmonitor + +@PromptServer.instance.routes.patch("/crystools/monitor") +async def newSettings(request): + try: + settings = await request.json() + # print(settings) + + if 'rate' in settings is not None: + rate = settings['rate'] + if type(rate) is not int and type(rate) is not float: + raise Exception('Rate must be an number.') + + if cmonitor.rate == 0 and rate > 0: + cmonitor.rate = rate + cmonitor.startMonitor() + else: + cmonitor.rate = rate + + + if 'switchCPU' in settings is not None: + switchCPU = settings['switchCPU'] + if type(switchCPU) is not bool: + raise Exception('switchCPU must be an boolean.') + + cmonitor.hardwareInfo.switchCPU = switchCPU + + if 'switchHDD' in settings is not None: + switchHDD = settings['switchHDD'] + if type(switchHDD) is not bool: + raise Exception('switchHDD must be an boolean.') + + cmonitor.hardwareInfo.switchHDD = switchHDD + + if 'switchRAM' in settings is not None: + switchRAM = settings['switchRAM'] + if type(switchRAM) is not bool: + raise Exception('switchRAM must be an boolean.') + + cmonitor.hardwareInfo.switchRAM = switchRAM + + if 'whichHDD' in settings is not None: + whichHDD = settings['whichHDD'] + if type(whichHDD) is not str: + raise Exception('whichHDD must be an string.') + + cmonitor.hardwareInfo.whichHDD = whichHDD + + + return web.Response(status=200) + except Exception as e: + logger.error(e) + return web.Response(status=400, text=str(e)) + + +@PromptServer.instance.routes.post("/crystools/monitor/switch") +async def monitorSwitch(request): + try: + switch = await request.json() + + if 'monitor' in switch is not None: + monitor = switch['monitor'] + if type(monitor) is not bool: + raise Exception('monitor must be an boolean.') + + if monitor: + cmonitor.startMonitor() + else: + cmonitor.stopMonitor() + + return web.Response(status=200) + except Exception as e: + logger.error(e) + return web.Response(status=400, text=str(e)) + + +@PromptServer.instance.routes.get("/crystools/monitor/HDD") +def getHDDs(request): + try: + return web.json_response(cmonitor.hardwareInfo.getHDDsInfo()) + except Exception as e: + logger.error(e) + return web.Response(status=400, text=str(e)) + + +@PromptServer.instance.routes.get("/crystools/monitor/GPU") +def getGPUs(request): + try: + gpuInfo = cmonitor.hardwareInfo.getGPUInfo() + return web.json_response(gpuInfo) + except Exception as e: + logger.error(e) + return web.Response(status=400, text=str(e)) + + +@PromptServer.instance.routes.patch("/crystools/monitor/GPU/{index}") +async def getGPUs(request): + try: + index = request.match_info["index"] + settings = await request.json() + if 'utilization' in settings is not None: + if type(settings['utilization']) is not bool: + raise Exception('utilization must be an boolean.') + + cmonitor.hardwareInfo.GPUInfo.gpusUtilization[int(index)] = settings['utilization'] + + if 'vram' in settings is not None: + if type(settings['vram']) is not bool: + raise Exception('vram must be an boolean.') + + cmonitor.hardwareInfo.GPUInfo.gpusVRAM[int(index)] = settings['vram'] + + if 'temperature' in settings is not None: + if type(settings['temperature']) is not bool: + raise Exception('temperature must be an boolean.') + + cmonitor.hardwareInfo.GPUInfo.gpusTemperature[int(index)] = settings['temperature'] + + return web.Response(status=200) + except Exception as e: + logger.error(e) + return web.Response(status=400, text=str(e)) diff --git a/ComfyUI-Crystools/web/comfy/index.d.ts b/ComfyUI-Crystools/web/comfy/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a1cc3ea3f226b252991217b258d391e32f406370 --- /dev/null +++ b/ComfyUI-Crystools/web/comfy/index.d.ts @@ -0,0 +1,5 @@ +export type * from './scripts.js'; +export * from './scripts.js'; +export type { ComfyApp } from './typings/comfy.js'; +export * from './liteGraph.js'; +export type * from './liteGraph.js'; diff --git a/ComfyUI-Crystools/web/comfy/index.js b/ComfyUI-Crystools/web/comfy/index.js new file mode 100644 index 0000000000000000000000000000000000000000..35c7ffb130eb9e6469ca520d905f201f656f59c9 --- /dev/null +++ b/ComfyUI-Crystools/web/comfy/index.js @@ -0,0 +1,2 @@ +export * from './scripts.js'; +export * from './liteGraph.js'; diff --git a/ComfyUI-Crystools/web/comfy/index.ts b/ComfyUI-Crystools/web/comfy/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..a1cc3ea3f226b252991217b258d391e32f406370 --- /dev/null +++ b/ComfyUI-Crystools/web/comfy/index.ts @@ -0,0 +1,5 @@ +export type * from './scripts.js'; +export * from './scripts.js'; +export type { ComfyApp } from './typings/comfy.js'; +export * from './liteGraph.js'; +export type * from './liteGraph.js'; diff --git a/ComfyUI-Crystools/web/comfy/liteGraph.d.ts b/ComfyUI-Crystools/web/comfy/liteGraph.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c942cc5bdc1a647127675cad0f72c16390e8d375 --- /dev/null +++ b/ComfyUI-Crystools/web/comfy/liteGraph.d.ts @@ -0,0 +1,19 @@ +export type * from './liteGraph.types.js'; +import type { IWidget as IWidgetOld, LGraphNode as TypeGraphNode, TypeLiteGraph } from './liteGraph.types.js'; +declare const LGraphNode: typeof TypeGraphNode; +export interface IWidget extends IWidgetOld { + onRemove?: () => void; + serializeValue?: () => Promise; +} +export declare class TLGraphNode extends LGraphNode { + static category: string; + static shape: number; + static color: string; + static bgcolor: string; + static collapsable: boolean; + isVirtualNode?: boolean; + widgets_values?: any[]; + name?: string; + prototype: TLGraphNode; +} +export declare const LiteGraph: TypeLiteGraph; diff --git a/ComfyUI-Crystools/web/comfy/liteGraph.js b/ComfyUI-Crystools/web/comfy/liteGraph.js new file mode 100644 index 0000000000000000000000000000000000000000..743706e8ad7da2469c08cd442cd559dbb54feeb8 --- /dev/null +++ b/ComfyUI-Crystools/web/comfy/liteGraph.js @@ -0,0 +1,30 @@ +export class TLGraphNode extends LGraphNode { + constructor() { + super(...arguments); + Object.defineProperty(this, "isVirtualNode", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "widgets_values", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "prototype", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + } +} +export const LiteGraph = window.LiteGraph; diff --git a/ComfyUI-Crystools/web/comfy/liteGraph.ts b/ComfyUI-Crystools/web/comfy/liteGraph.ts new file mode 100644 index 0000000000000000000000000000000000000000..8bbd88a35bef3ae653532d20fc7cdbe0b513de49 --- /dev/null +++ b/ComfyUI-Crystools/web/comfy/liteGraph.ts @@ -0,0 +1,32 @@ +// / +// A LOTS OF PATCHES FOR LITEGRAPH TYPES ¯\_(ツ)_/¯ +export type * from './liteGraph.types.js'; + +import type { IWidget as IWidgetOld, LGraphNode as TypeGraphNode, TypeLiteGraph } from './liteGraph.types.js'; + +declare const LGraphNode: typeof TypeGraphNode; // just for get the type + +export interface IWidget extends IWidgetOld { + onRemove?: () => void; + serializeValue?: () => Promise; +} + +export class TLGraphNode extends LGraphNode { + // on discovery... + static category: string; + static shape: number; + static color: string; + static bgcolor: string; + static collapsable: boolean; + + // widgets?: IWidget[]; + isVirtualNode?: boolean; + // override onResize?: (size: [number, number]) => void; + widgets_values?: any[]; + name?: string; + + prototype: TLGraphNode; // yes itself +} + +// from globals +export const LiteGraph: TypeLiteGraph = (window as any).LiteGraph; diff --git a/ComfyUI-Crystools/web/comfy/liteGraph.types.d.ts b/ComfyUI-Crystools/web/comfy/liteGraph.types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d528544ae664bc5bd862a750275d578165ed0263 --- /dev/null +++ b/ComfyUI-Crystools/web/comfy/liteGraph.types.d.ts @@ -0,0 +1,19 @@ +// A LOTS OF PATCHES FOR LITEGRAPH TYPES ¯\_(ツ)_/¯ +import { LGraph } from './typings/litegraph.js'; + +export type * from './typings/litegraph.js'; + +export declare type TypeLiteGraph = typeof LiteGraph & { + graph: LGraph; +}; + +// export declare type ComfyApi = typeof api; +export declare type ComfyNode = any; + +// I prefer not use global, but if I change of opinion: +// / +// import { LGraphNode as TLGraphNode, LiteGraph as TLiteGraph } from '/types/litegraph'; +// export declare const LGraphNode: typeof TLGraphNode; +// declare global { +// const LGraphNode: LGraphNode; +// } diff --git a/ComfyUI-Crystools/web/comfy/scripts.d.ts b/ComfyUI-Crystools/web/comfy/scripts.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1fa3186876320553e04a8781c2909277c49b5c56 --- /dev/null +++ b/ComfyUI-Crystools/web/comfy/scripts.d.ts @@ -0,0 +1,5 @@ +export { ComfyWidgets } from '../../../scripts/widgets.js'; +export { app } from '../../../scripts/app.js'; +export { api } from '../../../scripts/api.js'; +export * as utils from '../../../scripts/utils.js'; +export { ComfyButtonGroup } from '../../../scripts/ui/components/buttonGroup.js'; diff --git a/ComfyUI-Crystools/web/comfy/scripts.js b/ComfyUI-Crystools/web/comfy/scripts.js new file mode 100644 index 0000000000000000000000000000000000000000..1fa3186876320553e04a8781c2909277c49b5c56 --- /dev/null +++ b/ComfyUI-Crystools/web/comfy/scripts.js @@ -0,0 +1,5 @@ +export { ComfyWidgets } from '../../../scripts/widgets.js'; +export { app } from '../../../scripts/app.js'; +export { api } from '../../../scripts/api.js'; +export * as utils from '../../../scripts/utils.js'; +export { ComfyButtonGroup } from '../../../scripts/ui/components/buttonGroup.js'; diff --git a/ComfyUI-Crystools/web/comfy/scripts.ts b/ComfyUI-Crystools/web/comfy/scripts.ts new file mode 100644 index 0000000000000000000000000000000000000000..45e31007037695e14a0317516fe9bc4b35f06e04 --- /dev/null +++ b/ComfyUI-Crystools/web/comfy/scripts.ts @@ -0,0 +1,10 @@ +// @ts-expect-error I could not find a way to make this work +export { ComfyWidgets } from '../../../scripts/widgets.js'; +// @ts-expect-error I could not find a way to make this work +export { app } from '../../../scripts/app.js'; +// @ts-expect-error I could not find a way to make this work +export { api } from '../../../scripts/api.js'; +// @ts-expect-error I could not find a way to make this work +export * as utils from '../../../scripts/utils.js'; +// @ts-expect-error I could not find a way to make this work +export { ComfyButtonGroup } from '../../../scripts/ui/components/buttonGroup.js'; diff --git a/ComfyUI-Crystools/web/comfy/typings/README.md b/ComfyUI-Crystools/web/comfy/typings/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7348eef4cc2b27f367c7657ba2db7c3b382a32cd --- /dev/null +++ b/ComfyUI-Crystools/web/comfy/typings/README.md @@ -0,0 +1,5 @@ +COPIED FROM rgthree + +The typings in node_modules or in ComfyUI's web/ directory were not that well covered. These typings are hacked together with some of the inconsistencies I found. + +To be honest, I have no idea why I needed a bizarre workaround for litegraph's types. Usually the '/// <reference>' comment should have picked up the types, but it wasn't having it. ¯\_(ツ)_/¯ diff --git a/ComfyUI-Crystools/web/comfy/typings/comfy.d.ts b/ComfyUI-Crystools/web/comfy/typings/comfy.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d320ff51bb073329c34ea3333e7e2f45b666a0db --- /dev/null +++ b/ComfyUI-Crystools/web/comfy/typings/comfy.d.ts @@ -0,0 +1,227 @@ +import type { LGraphGroup as TLGraphGroup, LGraphNode as TLGraphNode, IWidget, SerializedLGraphNode, LGraph as TLGraph, LGraphCanvas as TLGraphCanvas, LiteGraph as TLiteGraph } from "./litegraph.js"; +import type {Constructor, SerializedGraph} from './index.js'; + +declare global { + const LiteGraph: typeof TLiteGraph; + const LGraph: typeof TLGraph; + const LGraphNode: typeof TLGraphNode; + const LGraphCanvas: typeof TLGraphCanvas; + const LGraphGroup: typeof TLGraphGroup; +} + +// @rgthree: Types on ComfyApp as needed. +export interface ComfyApp { + extensions: ComfyExtension[]; + async queuePrompt(number?: number, batchCount = 1): Promise; + graph: TLGraph; + canvas: TLGraphCanvas; + clean() : void; + registerExtension(extension: ComfyExtension): void; + getPreviewFormatParam(): string; + getRandParam(): string; + loadApiJson(apiData: {}, fileName: string): void; + async graphToPrompt(graph?: TLGraph, clean?: boolean): Promise; + // workflow: ComfyWorkflowInstance ??? + async loadGraphData(graphData: {}, clean?: boolean, restore_view?: boolean, workflow?: any|null): Promise + ui: { + settings: { + addSetting(config: {id: string, name: string, type: () => HTMLElement}) : void; + } + } + // Just marking as any for now. + menu?: any; +} + +export interface ComfyWidget extends IWidget { + // https://github.com/comfyanonymous/ComfyUI/issues/2193 Changes from SerializedLGraphNode to + // LGraphNode... + serializeValue(nodeType: TLGraphNode, index: number): Promise; + afterQueued(): void; + inputEl?: HTMLTextAreaElement; + width: number; +} + +export interface ComfyGraphNode extends TLGraphNode { + getExtraMenuOptions: (node: TLGraphNode, options: ContextMenuItem[]) => void; + onExecuted(message: any): void; +} + +export interface ComfyNode extends TLGraphNode { + comfyClass: string; +} + +// @rgthree +export interface ComfyNodeConstructor extends Constructor { + static title: string; + static type?: string; + static comfyClass: string; +} + +export type NodeMode = 0|1|2|3|4|undefined; + + +export interface ComfyExtension { + /** + * The name of the extension + */ + name: string; + /** + * Allows any initialisation, e.g. loading resources. Called after the canvas is created but before nodes are added + * @param app The ComfyUI app instance + */ + init?(app: ComfyApp): Promise; + /** + * Allows any additonal setup, called after the application is fully set up and running + * @param app The ComfyUI app instance + */ + setup?(app: ComfyApp): Promise; + /** + * Called before nodes are registered with the graph + * @param defs The collection of node definitions, add custom ones or edit existing ones + * @param app The ComfyUI app instance + */ + addCustomNodeDefs?(defs: Record, app: ComfyApp): Promise; + /** + * Allows the extension to add custom widgets + * @param app The ComfyUI app instance + * @returns An array of {[widget name]: widget data} + */ + getCustomWidgets?( + app: ComfyApp + ): Promise< + Record { widget?: IWidget; minWidth?: number; minHeight?: number }> + >; + /** + * Allows the extension to add additional handling to the node before it is registered with LGraph + * @rgthree changed nodeType from `typeof LGraphNode` to `ComfyNodeConstructor` + * @param nodeType The node class (not an instance) + * @param nodeData The original node object info config object + * @param app The ComfyUI app instance + */ + beforeRegisterNodeDef?(nodeType: ComfyNodeConstructor, nodeData: ComfyObjectInfo, app: ComfyApp): Promise; + /** + * Allows the extension to register additional nodes with LGraph after standard nodes are added + * @param app The ComfyUI app instance + */ + // @rgthree - add void for non async + registerCustomNodes?(app: ComfyApp): void|Promise; + /** + * Allows the extension to modify a node that has been reloaded onto the graph. + * If you break something in the backend and want to patch workflows in the frontend + * This is the place to do this + * @param node The node that has been loaded + * @param app The ComfyUI app instance + */ + loadedGraphNode?(node: TLGraphNode, app: ComfyApp); + /** + * Allows the extension to run code after the constructor of the node + * @param node The node that has been created + * @param app The ComfyUI app instance + */ + nodeCreated?(node: TLGraphNode, app: ComfyApp); +} + +export type ComfyObjectInfo = { + name: string; + display_name?: string; + description?: string; + category: string; + input?: { + required?: Record; + optional?: Record; + hidden?: Record; + }; + output?: string[]; + output_name: string[]; + // @rgthree + output_node?: boolean; +}; + +export type ComfyObjectInfoConfig = [string | any[]] | [string | any[], any]; + +// @rgthree +type ComfyApiInputLink = [ + /** The id string of the connected node. */ + string, + /** The output index. */ + number, +] + +// @rgthree +export type ComfyApiFormatNode = { + "inputs": { + [input_name: string]: string|number|boolean|ComfyApiInputLink, + }, + "class_type": string, + "_meta": { + "title": string, + } +} + +// @rgthree +export type ComfyApiFormat = { + [node_id: string]: ComfyApiFormatNode +} + +// @rgthree +export type ComfyApiPrompt = { + workflow: SerializedGraph, + output: ComfyApiFormat, +} + +// @rgthree +export type ComfyApiEventDetailStatus = { + exec_info: { + queue_remaining: number; + }; +}; + +// @rgthree +export type ComfyApiEventDetailExecutionStart = { + prompt_id: string; +}; + +// @rgthree +export type ComfyApiEventDetailExecuting = null | string; + +// @rgthree +export type ComfyApiEventDetailProgress = { + node: string; + prompt_id: string; + max: number; + value: number; +}; + +// @rgthree +export type ComfyApiEventDetailExecuted = { + node: string; + prompt_id: string; + output: any; +}; + +// @rgthree +export type ComfyApiEventDetailCached = { + nodes: string[]; + prompt_id: string; +}; + +// @rgthree +export type ComfyApiEventDetailExecuted = { + prompt_id: string; + node: string; + output: any; +}; + +// @rgthree +export type ComfyApiEventDetailError = { + prompt_id: string; + exception_type: string; + exception_message: string; + node_id: string; + node_type: string; + node_id: string; + traceback: string; + executed: any[]; + current_inputs: {[key: string]: (number[]|string[])}; + current_outputs: {[key: string]: (number[]|string[])}; +} diff --git a/ComfyUI-Crystools/web/comfy/typings/index.d.ts b/ComfyUI-Crystools/web/comfy/typings/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3cd8a1c443cd05d50b96f8b65e73ee840221825e --- /dev/null +++ b/ComfyUI-Crystools/web/comfy/typings/index.d.ts @@ -0,0 +1,55 @@ +import { LGraph } from "./litegraph.js"; + +export type Constructor = new(...args: any[]) => T; + +export type SerializedLink = [ + number, // this.id, + number, // this.origin_id, + number, // this.origin_slot, + number, // this.target_id, + number, // this.target_slot, + string, // this.type +]; + +export interface SerializedNodeInput { + name: string; + type: string; + link: number; +} +export interface SerializedNodeOutput { + name: string; + type: string; + link: number; + slot_index: number; + links: number[]; +} +export interface SerializedNode { + id: number; + inputs: SerializedNodeInput[]; + outputs: SerializedNodeOutput[]; + mode: number; + order: number; + pos: [number, number]; + properties: any; + size: [number, number]; + type: string; + widgets_values: Array; +} + +export interface SerializedGraph { + config: any; + extra: any; + groups: any; + last_link_id: number; + last_node_id: number; + links: SerializedLink[]; + nodes: SerializedNode[]; +} + +export interface BadLinksData { + hasBadLinks: boolean; + fixed: boolean; + graph: T; + patched: number; + deleted: number; +} diff --git a/ComfyUI-Crystools/web/comfy/typings/litegraph.d.ts b/ComfyUI-Crystools/web/comfy/typings/litegraph.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..abc535e836cebf5c7ba291762b55d15d45b66c9d --- /dev/null +++ b/ComfyUI-Crystools/web/comfy/typings/litegraph.d.ts @@ -0,0 +1,1750 @@ +// Type definitions for litegraph.js 0.7.0 +// Project: litegraph.js +// Definitions by: NateScarlet + +export type Vector2 = [number, number]; +export type Vector4 = [number, number, number, number]; +export type widgetTypes = + | "number" + | "slider" + | "combo" + | "text" + | "toggle" + | "button"; +export type SlotShape = + | typeof LiteGraph.BOX_SHAPE + | typeof LiteGraph.CIRCLE_SHAPE + | typeof LiteGraph.ARROW_SHAPE + | typeof LiteGraph.SQUARE_SHAPE + | number; // For custom shapes + +/** https://github.com/jagenjo/litegraph.js/tree/master/guides#node-slots */ +export interface INodeSlot { + name: string; + type: string | -1; + label?: string; + dir?: + | typeof LiteGraph.UP + | typeof LiteGraph.RIGHT + | typeof LiteGraph.DOWN + | typeof LiteGraph.LEFT; + color_on?: string; + color_off?: string; + shape?: SlotShape; + locked?: boolean; + nameLocked?: boolean; + pos?: Vector2; + // @rgthree + hidden?: boolean; + // @rgthree + disabled?: boolean; + // @rgthree - Found this checked in getSlotMenuOptions default. + removable?: boolean; + // @rgthree - A status we put on some nodes so we can draw things around it. + rgthree_status?: 'WARN' | 'ERROR'; +} + +export interface INodeInputSlot extends INodeSlot { + link: LLink["id"] | null; + // @rgthree - add comfy widget info + widget?: { + name: string; + } +} + +export interface INodeOutputSlot extends INodeSlot { + links: LLink["id"][] | null; +} + +export type WidgetCallback = ( + this: T, + value: T["value"], + graphCanvas: LGraphCanvas, + node: LGraphNode, + pos: Vector2, + event?: MouseEvent +) => void; + +// @rgthree +export type WidgetComboCallback = ( + this: T, + value: T["value"][0], + graphCanvas: LGraphCanvas, + node: LGraphNode, + pos: Vector2, + event?: MouseEvent +) => void; + +// @rgthree +export type IWidgetOptions = { + y?: number; // ? + property?: string; + serialize?: boolean; // ComfyUI in app.js + forceInput?: boolean; // ComfyUI in app.js + defaultInput?: boolean; // ComfyUI in app.js +} + +// @rgthree +export type IWidgetToggleOptions = IWidgetOptions & { + on?: string; + off?: string; +} + +// @rgthree +export type IWidgetNumberOptions = IWidgetOptions & { + precision?: number; + max?: number; + min?: number; +} + +// @rgthree +export type IWidgetSliderOptions = IWidgetNumberOptions & { + slider_color?: string; + marker_color?: string; +} + + +// @rgthree +export type IWidgetComboOptions = IWidgetOptions & { + values?: string[] | ((widget: IComboWidget, node: LGraphNode) => string[]); +} + +export interface IWidget { + name: string | null; + // @rgthree + label?: string | null; + value: TValue; + options?: TOptions; + // @rgthree - extend to string for custom + type?: widgetTypes | string; + y?: number; + property?: string; + last_y?: number; + clicked?: boolean; + marker?: boolean; + disabled?: boolean; + callback?: WidgetCallback; + // crystools + onRemove?: () => void; + /** Called by `LGraphCanvas.drawNodeWidgets` */ + draw?( + ctx: CanvasRenderingContext2D, + node: LGraphNode, + width: number, + posY: number, + height: number + ): void; + /** + * Called by `LGraphCanvas.processNodeWidgets` + * https://github.com/jagenjo/litegraph.js/issues/76 + */ + mouse?( + event: MouseEvent, + pos: Vector2, + node: LGraphNode + ): boolean; + /** Called by `LGraphNode.computeSize` */ + computeSize?(width: number): [number, number]; + // @rgthree - make optional, since it is in the code. + serializeValue?(serializedNode: SerializedLGraphNode, widgetIndex: number): TValue; + // @rgthree - Checked in LGraphCanvas.prototype.processNodeWidgets, and figured I'd use it too. + width?: number; +} +export interface IButtonWidget extends IWidget { + type: "button"; +} +// @rgthree: adding options +export interface IToggleWidget extends IWidget { + type: "toggle"; +} +// @rgthree: adding options +export interface ISliderWidget extends IWidget { + type: "slider"; +} +// @rgthree: adding options +export interface INumberWidget extends IWidget { + type: "number"; +} +// @rgthree: adding options +export interface IComboWidget extends IWidget { + value: T[0]; + type: "combo"; + callback?: WidgetComboCallback; +} + +export interface ITextWidget extends IWidget { + type: "text"; +} + +export interface IContextMenuItem { + // @rgthree - Make optional because, I guess it is? + content?: string; + value?: any; + callback?: ContextMenuEventListener; + /** Used as innerHTML for extra child element */ + title?: string; + disabled?: boolean; + has_submenu?: boolean; + submenu?: { + options: ContextMenuItem[]; + } & IContextMenuOptions; + className?: string; + // @rgthree - Added for menu_auto_nest + rgthree_originalValue?: IContextMenuItem; + // @rgthree - this was missing and passed through for getSlotMenuOptions default. + slot?: {input?: INodeInputSlot, output?: INodeOutputSlot}; +} +export interface IContextMenuOptions { + callback?: ContextMenuEventListener; + ignore_item_callbacks?: Boolean; + event?: MouseEvent | CustomEvent | AdjustedMouseEvent; + parentMenu?: ContextMenu|null; + autoopen?: boolean; + title?: string; + extra?: any; + // @rgthree + scale?: number; + // @rgthree + left?: number; + // @rgthree + top?: number; + // @rgthree + className?: string; + // @rgthree - Added for menu_auto_nest + rgthree_originalCallback?: ContextMenuEventListener; + // @rgthree - No idea since it's not documented, but we'll use it to pass data, like rgthree_doNotNest + extra?: any +} + +export type ContextMenuItem = IContextMenuItem | null; +export type ContextMenuEventListener = ( + value: ContextMenuItem, + options: IContextMenuOptions, + event: MouseEvent, + parentMenu: ContextMenu | undefined, + node: LGraphNode +) => boolean | void; + +export const LiteGraph: { + VERSION: number; + + CANVAS_GRID_SIZE: number; + + NODE_TITLE_HEIGHT: number; + NODE_TITLE_TEXT_Y: number; + NODE_SLOT_HEIGHT: number; + NODE_WIDGET_HEIGHT: number; + NODE_WIDTH: number; + NODE_MIN_WIDTH: number; + NODE_COLLAPSED_RADIUS: number; + NODE_COLLAPSED_WIDTH: number; + NODE_TITLE_COLOR: string; + NODE_TEXT_SIZE: number; + NODE_TEXT_COLOR: string; + NODE_SUBTEXT_SIZE: number; + NODE_DEFAULT_COLOR: string; + NODE_DEFAULT_BGCOLOR: string; + NODE_DEFAULT_BOXCOLOR: string; + NODE_DEFAULT_SHAPE: string; + // @rgthree - didn't exist. + NODE_BOX_OUTLINE_COLOR: string; + DEFAULT_SHADOW_COLOR: string; + DEFAULT_GROUP_FONT: number; + // @rgthree - Seems to have been missing. + NODE_BOX_OUTLINE_COLOR: string; + + WIDGET_BGCOLOR: string; + WIDGET_OUTLINE_COLOR: string; + WIDGET_TEXT_COLOR: string; + WIDGET_SECONDARY_TEXT_COLOR: string; + + LINK_COLOR: string; + EVENT_LINK_COLOR: string; + CONNECTING_LINK_COLOR: string; + + MAX_NUMBER_OF_NODES: number; //avoid infinite loops + DEFAULT_POSITION: Vector2; //default node position + VALID_SHAPES: ["default", "box", "round", "card"]; //,"circle" + + //shapes are used for nodes but also for slots + BOX_SHAPE: 1; + ROUND_SHAPE: 2; + CIRCLE_SHAPE: 3; + CARD_SHAPE: 4; + ARROW_SHAPE: 5; + GRID_SHAPE: 6; + + //enums + INPUT: 1; + OUTPUT: 2; + + EVENT: -1; //for outputs + ACTION: -1; //for inputs + + ALWAYS: 0; + ON_EVENT: 1; + NEVER: 2; + ON_TRIGGER: 3; + + UP: 1; + DOWN: 2; + LEFT: 3; + RIGHT: 4; + CENTER: 5; + + STRAIGHT_LINK: 0; + LINEAR_LINK: 1; + SPLINE_LINK: 2; + + NORMAL_TITLE: 0; + NO_TITLE: 1; + TRANSPARENT_TITLE: 2; + AUTOHIDE_TITLE: 3; + + node_images_path: string; + + // @rgthree. These just weren't there. Note, LiteGraph initializes these as an array, but + // ComfyUI overrides these to a string-keye'd object... ??? + slot_types_default_out: {[key: string]: string[]}; + slot_types_default_in: {[key: string]: string[]}; + + debug: boolean; + catch_exceptions: boolean; + throw_errors: boolean; + /** if set to true some nodes like Formula would be allowed to evaluate code that comes from unsafe sources (like node configuration), which could lead to exploits */ + allow_scripts: boolean; + /** node types by string */ + registered_node_types: Record; + /** used for dropping files in the canvas */ + node_types_by_file_extension: Record; + /** node types by class name */ + Nodes: Record; + + /** used to add extra features to the search box */ + searchbox_extras: Record< + string, + { + data: { outputs: string[][]; title: string }; + desc: string; + type: string; + } + >; + + //@rgthree + isValidConnection(type: string|string[], type: string|string[]):boolean; + overlapBounding(a: Vector4, b: Vector4) : boolean; + + createNode(type: string): T; + /** Register a node class so it can be listed when the user wants to create a new one */ + registerNodeType(type: string, base: { new (title?: string): T }): void; + /** removes a node type from the system */ + unregisterNodeType(type: string): void; + /** Removes all previously registered node's types. */ + clearRegisteredTypes(): void; + /** + * Create a new node type by passing a function, it wraps it with a proper class and generates inputs according to the parameters of the function. + * Useful to wrap simple methods that do not require properties, and that only process some input to generate an output. + * @param name node name with namespace (p.e.: 'math/sum') + * @param func + * @param param_types an array containing the type of every parameter, otherwise parameters will accept any type + * @param return_type string with the return type, otherwise it will be generic + * @param properties properties to be configurable + */ + wrapFunctionAsNode( + name: string, + func: (...args: any[]) => any, + param_types?: string[], + return_type?: string, + properties?: object + ): void; + + /** + * Adds this method to all node types, existing and to be created + * (You can add it to LGraphNode.prototype but then existing node types wont have it) + */ + addNodeMethod(name: string, func: (...args: any[]) => any): void; + + /** + * Create a node of a given type with a name. The node is not attached to any graph yet. + * @param type full name of the node class. p.e. "math/sin" + * @param name a name to distinguish from other nodes + * @param options to set options + */ + createNode( + type: string, + title: string, + options: object + ): T; + + /** + * Returns a registered node type with a given name + * @param type full name of the node class. p.e. "math/sin" + */ + getNodeType(type: string): LGraphNodeConstructor; + + /** + * Returns a list of node types matching one category + * @method getNodeTypesInCategory + * @param {String} category category name + * @param {String} filter only nodes with ctor.filter equal can be shown + * @return {Array} array with all the node classes + */ + getNodeTypesInCategory( + category: string, + filter: string + ): LGraphNodeConstructor[]; + + /** + * Returns a list with all the node type categories + * @method getNodeTypesCategories + * @param {String} filter only nodes with ctor.filter equal can be shown + * @return {Array} array with all the names of the categories + */ + getNodeTypesCategories(filter: string): string[]; + + /** debug purposes: reloads all the js scripts that matches a wildcard */ + reloadNodes(folder_wildcard: string): void; + + getTime(): number; + LLink: typeof LLink; + LGraph: typeof LGraph; + DragAndScale: typeof DragAndScale; + compareObjects(a: object, b: object): boolean; + distance(a: Vector2, b: Vector2): number; + colorToString(c: string): string; + isInsideRectangle( + x: number, + y: number, + left: number, + top: number, + width: number, + height: number + ): boolean; + growBounding(bounding: Vector4, x: number, y: number): Vector4; + isInsideBounding(p: Vector2, bb: Vector4): boolean; + hex2num(hex: string): [number, number, number]; + num2hex(triplet: [number, number, number]): string; + ContextMenu: typeof ContextMenu; + extendClass(target: A, origin: B): A & B; + getParameterNames(func: string): string[]; + // @rgthree + closeAllContextMenus(ref_window?: Window): void; +}; + +export type serializedLGraph< + TNode = ReturnType, + // https://github.com/jagenjo/litegraph.js/issues/74 + TLink = [number, number, number, number, number, string], + TGroup = ReturnType +> = { + last_node_id: LGraph["last_node_id"]; + last_link_id: LGraph["last_link_id"]; + nodes: TNode[]; + links: TLink[]; + groups: TGroup[]; + config: LGraph["config"]; + version: typeof LiteGraph.VERSION; +}; + +export declare class LGraph { + static supported_types: string[]; + static STATUS_STOPPED: 1; + static STATUS_RUNNING: 2; + + constructor(o?: object); + + filter: string; + catch_errors: boolean; + /** custom data */ + config: object; + elapsed_time: number; + fixedtime: number; + fixedtime_lapse: number; + globaltime: number; + inputs: any; + iteration: number; + last_link_id: number; + last_node_id: number; + last_update_time: number; + links: Record; + list_of_graphcanvas: LGraphCanvas[]; + outputs: any; + runningtime: number; + starttime: number; + status: typeof LGraph.STATUS_RUNNING | typeof LGraph.STATUS_STOPPED; + + // @rgthree, remove private; it's not really private b/c it's javascript. + _nodes: LGraphNode[]; + // @rgthree, remove private; it's not really private b/c it's javascript. + _groups: LGraphGroup[]; + private _nodes_by_id: Record; + /** nodes that are executable sorted in execution order */ + private _nodes_executable: + | (LGraphNode & { onExecute: NonNullable }[]) + | null; + /** nodes that contain onExecute */ + private _nodes_in_order: LGraphNode[]; + private _version: number; + + getSupportedTypes(): string[]; + /** Removes all nodes from this graph */ + clear(): void; + /** Attach Canvas to this graph */ + attachCanvas(graphCanvas: LGraphCanvas): void; + /** Detach Canvas to this graph */ + detachCanvas(graphCanvas: LGraphCanvas): void; + /** + * Starts running this graph every interval milliseconds. + * @param interval amount of milliseconds between executions, if 0 then it renders to the monitor refresh rate + */ + start(interval?: number): void; + /** Stops the execution loop of the graph */ + stop(): void; + /** + * Run N steps (cycles) of the graph + * @param num number of steps to run, default is 1 + */ + runStep(num?: number, do_not_catch_errors?: boolean): void; + /** + * Updates the graph execution order according to relevance of the nodes (nodes with only outputs have more relevance than + * nodes with only inputs. + */ + updateExecutionOrder(): void; + /** This is more internal, it computes the executable nodes in order and returns it */ + computeExecutionOrder(only_onExecute: boolean, set_level: any): T; + /** + * Returns all the nodes that could affect this one (ancestors) by crawling all the inputs recursively. + * It doesn't include the node itself + * @return an array with all the LGraphNodes that affect this node, in order of execution + */ + getAncestors(node: LGraphNode): LGraphNode[]; + /** + * Positions every node in a more readable manner + */ + arrange(margin?: number,layout?: string): void; + /** + * Returns the amount of time the graph has been running in milliseconds + * @return number of milliseconds the graph has been running + */ + getTime(): number; + + /** + * Returns the amount of time accumulated using the fixedtime_lapse var. This is used in context where the time increments should be constant + * @return number of milliseconds the graph has been running + */ + getFixedTime(): number; + + /** + * Returns the amount of time it took to compute the latest iteration. Take into account that this number could be not correct + * if the nodes are using graphical actions + * @return number of milliseconds it took the last cycle + */ + getElapsedTime(): number; + /** + * Sends an event to all the nodes, useful to trigger stuff + * @param eventName the name of the event (function to be called) + * @param params parameters in array format + */ + sendEventToAllNodes(eventName: string, params: any[], mode?: any): void; + + sendActionToCanvas(action: any, params: any[]): void; + /** + * Adds a new node instance to this graph + * @param node the instance of the node + */ + add(node: LGraphNode, skip_compute_order?: boolean): void; + /** + * Called when a new node is added + * @param node the instance of the node + */ + onNodeAdded(node: LGraphNode): void; + /** Removes a node from the graph */ + remove(node: LGraphNode): void; + /** + * Returns a node by its id. + * @rgthree - make id options/nullable. + */ + getNodeById(id?: number|null): LGraphNode | undefined; + /** + * Returns a list of nodes that matches a class + * @param classObject the class itself (not an string) + * @return a list with all the nodes of this type + */ + findNodesByClass( + classObject: LGraphNodeConstructor + ): T[]; + /** + * Returns a list of nodes that matches a type + * @param type the name of the node type + * @return a list with all the nodes of this type + */ + findNodesByType(type: string): T[]; + /** + * Returns the first node that matches a name in its title + * @param title the name of the node to search + * @return the node or null + */ + findNodeByTitle(title: string): T | null; + /** + * Returns a list of nodes that matches a name + * @param title the name of the node to search + * @return a list with all the nodes with this name + */ + findNodesByTitle(title: string): T[]; + /** + * Returns the top-most node in this position of the canvas + * @param x the x coordinate in canvas space + * @param y the y coordinate in canvas space + * @param nodes_list a list with all the nodes to search from, by default is all the nodes in the graph + * @return the node at this position or null + */ + getNodeOnPos( + x: number, + y: number, + node_list?: LGraphNode[], + margin?: number + ): T | null; + /** + * Returns the top-most group in that position + * @param x the x coordinate in canvas space + * @param y the y coordinate in canvas space + * @return the group or null + */ + getGroupOnPos(x: number, y: number): LGraphGroup | null; + + onAction(action: any, param: any): void; + trigger(action: any, param: any): void; + /** Tell this graph it has a global graph input of this type */ + addInput(name: string, type: string, value?: any): void; + /** Assign a data to the global graph input */ + setInputData(name: string, data: any): void; + /** Returns the current value of a global graph input */ + getInputData(name: string): T; + /** Changes the name of a global graph input */ + renameInput(old_name: string, name: string): false | undefined; + /** Changes the type of a global graph input */ + changeInputType(name: string, type: string): false | undefined; + /** Removes a global graph input */ + removeInput(name: string): boolean; + /** Creates a global graph output */ + addOutput(name: string, type: string, value: any): void; + /** Assign a data to the global output */ + setOutputData(name: string, value: string): void; + /** Returns the current value of a global graph output */ + getOutputData(name: string): T; + + /** Renames a global graph output */ + renameOutput(old_name: string, name: string): false | undefined; + /** Changes the type of a global graph output */ + changeOutputType(name: string, type: string): false | undefined; + /** Removes a global graph output */ + removeOutput(name: string): boolean; + triggerInput(name: string, value: any): void; + setCallback(name: string, func: (...args: any[]) => any): void; + beforeChange(info?: LGraphNode): void; + afterChange(info?: LGraphNode): void; + connectionChange(node: LGraphNode): void; + /** returns if the graph is in live mode */ + isLive(): boolean; + /** clears the triggered slot animation in all links (stop visual animation) */ + clearTriggeredSlots(): void; + /* Called when something visually changed (not the graph!) */ + change(): void; + setDirtyCanvas(fg: boolean, bg: boolean): void; + /** Destroys a link */ + removeLink(link_id: number): void; + /** Creates a Object containing all the info about this graph, it can be serialized */ + serialize(): T; + /** + * Configure a graph from a JSON string + * @param data configure a graph from a JSON string + * @returns if there was any error parsing + */ + configure(data: object, keep_old?: boolean): boolean | undefined; + load(url: string): void; +} + +export type SerializedLLink = [number, string, number, number, number, number]; +export declare class LLink { + id: number; + type: string; + origin_id: number; + origin_slot: number; + target_id: number; + target_slot: number; + constructor( + id: number, + type: string, + origin_id: number, + origin_slot: number, + target_id: number, + target_slot: number + ); + configure(o: LLink | SerializedLLink): void; + serialize(): SerializedLLink; + // @rgthree + color?: string; +} + +export type SerializedLGraphNode = { + id: T["id"]; + type: T["type"]; + pos: T["pos"]; + size: T["size"]; + flags: T["flags"]; + mode: T["mode"]; + inputs: T["inputs"]; + outputs: T["outputs"]; + title: T["title"]; + properties: T["properties"]; + widgets_values?: IWidget["value"][]; +}; + +/** https://github.com/jagenjo/litegraph.js/blob/master/guides/README.md#lgraphnode */ +export declare class LGraphNode { + + // @rgthree added + findInputSlotByType(type: string, returnObj?: boolean, preferFreeSlot?: boolean, doNotUseOccupied?: boolean): number + findOutputSlotByType(type: string, returnObj?: boolean, preferFreeSlot?: boolean, doNotUseOccupied?: boolean): number + onShowCustomPanelInfo(panel: HTMLElement): void; + onDblClick?(event: AdjustedMouseEvent, pos: Vector2, canvas: LGraphCanvas): void; + inResizeCorner(x: number, y:number) : boolean; + onWidgetChanged?(widgetName: string, widgetValue: any, oldWidgetValue: any, widget: IWidget): void; + + // end @rgthree added + + static title_color?: string; + static title: string; + static type: null | string; + static widgets_up: boolean; + constructor(title?: string); + + title: string; + // @rgthree - made undefined since ComfyNode does it (even through LiteGraph does not..) + type?: null | string; + size: Vector2; + graph: null | LGraph; + graph_version: number; + pos: Vector2; + is_selected: boolean; + mouseOver: boolean; + // @rgthree - missing. + block_delete: boolean; + + id: number; + + widgets: IWidget[]; + //inputs available: array of inputs + inputs: INodeInputSlot[]; + outputs: INodeOutputSlot[]; + connections: any[]; + + // @rgthree + _collapsed_width?: number; + + //local data + properties: Record; + properties_info: any[]; + + flags: Partial<{ + collapsed: boolean + // @rgthree + allow_interaction: boolean; + // @rgthree + pinned: boolean; + }>; + + color: string; + bgcolor: string; + boxcolor: string; + shape: + | typeof LiteGraph.BOX_SHAPE + | typeof LiteGraph.ROUND_SHAPE + | typeof LiteGraph.CIRCLE_SHAPE + | typeof LiteGraph.CARD_SHAPE + | typeof LiteGraph.ARROW_SHAPE; + + serialize_widgets: boolean; + skip_list: boolean; + + /** Used in `LGraphCanvas.onMenuNodeMode` */ + mode?: + | typeof LiteGraph.ON_EVENT + | typeof LiteGraph.ON_TRIGGER + | typeof LiteGraph.NEVER + | typeof LiteGraph.ALWAYS + | 4; // Comfy App "Bypass" + + /** If set to true widgets do not start after the slots */ + widgets_up: boolean; + /** widgets start at y distance from the top of the node */ + widgets_start_y: number; + /** if you render outside the node, it will be clipped */ + clip_area: boolean; + /** if set to false it wont be resizable with the mouse */ + resizable: boolean; + /** slots are distributed horizontally */ + horizontal: boolean; + /** if true, the node will show the bgcolor as 'red' */ + has_errors?: boolean; + + // @rgthree + setSize(size: Vector2): void; + onResize?(size: Vector2): void; + onInputClick(slot: number, event: MouseEvent): void; + onOutputClick(slot: number, event: MouseEvent): void; + getConnectionPos(isInput: boolean, slotNumber: number, out: Vector2): Vector2; + + /** configure a node from an object containing the serialized info */ + configure(info: SerializedLGraphNode): void; + /** serialize the content */ + serialize(): SerializedLGraphNode; + /** Creates a clone of this node */ + clone(): this; + /** serialize and stringify */ + toString(): string; + /** get the title string */ + getTitle(): string; + /** sets the value of a property */ + setProperty(name: string, value: any): void; + /** sets the output data */ + setOutputData(slot: number, data: any): void; + /** sets the output data */ + setOutputDataType(slot: number, type: string): void; + /** + * 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 + * @return data or if it is not connected returns undefined + */ + getInputData(slot: number, force_update?: boolean): T; + /** + * Retrieves the input data type (in case this supports multiple input types) + * @param slot + * @return datatype in string format + */ + getInputDataType(slot: number): string; + /** + * 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 + * @return data or if it is not connected returns null + */ + getInputDataByName(slot_name: string, force_update?: boolean): T; + /** tells you if there is a connection in one input slot */ + isInputConnected(slot: number): boolean; + /** tells you info about an input connection (which node, type, etc) */ + getInputInfo( + slot: number + ): { link: number; name: string; type: string | 0 } | null; + /** returns the node connected in the input slot */ + getInputNode(slot: number): LGraphNode | null; + /** returns the value of an input with this name, otherwise checks if there is a property with that name */ + getInputOrProperty(name: string): T; + /** tells you the last output data that went in that slot */ + getOutputData(slot: number): T | null; + /** tells you info about an output connection (which node, type, etc) */ + getOutputInfo( + slot: number + ): { name: string; type: string; links: number[] } | null; + /** tells you if there is a connection in one output slot */ + isOutputConnected(slot: number): boolean; + /** tells you if there is any connection in the output slots */ + isAnyOutputConnected(): boolean; + /** retrieves all the nodes connected to this output slot */ + getOutputNodes(slot: number): LGraphNode[]; + /** Triggers an event in this node, this will trigger any output with the same name */ + trigger(action: string, param: any): void; + /** + * Triggers an slot event in this node + * @param slot the index of the output slot + * @param param + * @param link_id in case you want to trigger and specific output link in a slot + */ + triggerSlot(slot: number, param: any, link_id?: number): void; + /** + * clears the trigger slot animation + * @param slot the index of the output slot + * @param link_id in case you want to trigger and specific output link in a slot + */ + clearTriggeredSlot(slot: number, link_id?: number): void; + /** + * add a new property to this node + * @param name + * @param default_value + * @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: any, + type: string, + extra_info?: object + ): T; + /** + * add a new output slot to use in this node + * @param name + * @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: string | -1, + extra_info?: Partial + ): INodeOutputSlot; + /** + * add a new output slot to use in this node + * @param array of triplets like [[name,type,extra_info],[...]] + */ + addOutputs( + array: [string, string | -1, Partial | undefined][] + ): void; + /** remove an existing output slot */ + removeOutput(slot: number): void; + /** + * add a new input slot to use in this node + * @param name + * @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: string | -1, + extra_info?: Partial + ): INodeInputSlot; + /** + * add several new input slots in this node + * @param array of triplets like [[name,type,extra_info],[...]] + */ + addInputs( + array: [string, string | -1, Partial | undefined][] + ): void; + /** remove an existing input slot */ + removeInput(slot: number): void; + /** + * add an special connection to this node (used for special kinds of graphs) + * @param name + * @param type string defining the input type ("vec3","number",...) + * @param pos position of the connection inside the node + * @param direction if is input or output + */ + addConnection( + name: string, + type: string, + pos: Vector2, + direction: string + ): { + name: string; + type: string; + pos: Vector2; + direction: string; + links: null; + }; + setValue(v: any): void; + /** computes the size of a node according to its inputs and output slots */ + computeSize(out?: Vector2): [number, number]; + /** + * https://github.com/jagenjo/litegraph.js/blob/master/guides/README.md#node-widgets + * @return created widget + */ + addWidget( + type: T["type"], + name: string, + value: T["value"], + // @rgthree + callback?: T["callback"] | string,//WidgetCallback | string, + options?: T["options"] + ): T; + + addCustomWidget(customWidget: T): T; + + /** + * returns the bounding of the object, used for rendering purposes + * @return [x, y, width, height] + */ + getBounding(): Vector4; + /** checks if a point is inside the shape of a node */ + isPointInside( + x: number, + y: number, + margin?: number, + skipTitle?: boolean + ): boolean; + /** checks if a point is inside a node slot, and returns info about which slot */ + getSlotInPosition( + x: number, + y: number + ): { + input?: INodeInputSlot; + output?: INodeOutputSlot; + slot: number; + link_pos: Vector2; + }; + /** + * returns the input slot with a given name (used for dynamic slots), -1 if not found + * @param name the name of the slot + * @return the slot (-1 if not found) + */ + findInputSlot(name: string): number; + /** + * returns the output slot with a given name (used for dynamic slots), -1 if not found + * @param name the name of the slot + * @return the slot (-1 if not found) + */ + findOutputSlot(name: string): number; + /** + * connect this node output to the input of another node + * @param slot (could be the number of the slot or the string with the name of the slot) + * @param targetNode the target node + * @param targetSlot 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) + * @return {Object} the link_info is created, otherwise null + */ + connect( + slot: number | string, + targetNode: LGraphNode, + targetSlot: number | string + ): T | null; + + connectByTypeOutput( + slot: number | string, + sourceNode: LGraphNode, + sourceSlotType: string, + optsIn: string + ): T | null; + + connectByType( + slot: number | string, + sourceNode: LGraphNode, + sourceSlotType: string, + optsIn: string + ): T | null; + + + /** + * 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] + * @return if it was disconnected successfully + */ + disconnectOutput(slot: number | string, targetNode?: LGraphNode): boolean; + /** + * disconnect one input + * @param slot (could be the number of the slot or the string with the name of the slot) + * @return if it was disconnected successfully + */ + disconnectInput(slot: number | string): boolean; + /** + * 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 (could be the number of the slot or the string with the name of the slot) + * @param out a place to store the output, to free garbage + * @return the position + **/ + getConnectionPos( + is_input: boolean, + slot: number | string, + out?: Vector2 + ): Vector2; + /** Force align to grid */ + alignToGrid(): void; + /** Console output */ + trace(msg: string): void; + /** Forces to redraw or the main canvas (LGraphNode) or the bg canvas (links) */ + setDirtyCanvas(fg: boolean, bg: boolean): void; + loadImage(url: string): void; + /** Allows to get onMouseMove and onMouseUp events even if the mouse is out of focus */ + captureInput(v: any): void; + /** Collapse the node to make it smaller on the canvas */ + collapse(force: boolean): void; + /** Forces the node to do not move or realign on Z */ + pin(v?: boolean): void; + localToScreen(x: number, y: number, graphCanvas: LGraphCanvas): Vector2; + + // https://github.com/jagenjo/litegraph.js/blob/master/guides/README.md#custom-node-appearance + onDrawBackground?( + ctx: CanvasRenderingContext2D, + // @rgthree fixed + canvas: LGraphCanvas + ): void; + onDrawForeground?( + ctx: CanvasRenderingContext2D, + // @rgthree fixed + canvas: LGraphCanvas + ): void; + + // https://github.com/jagenjo/litegraph.js/blob/master/guides/README.md#custom-node-behaviour + onMouseDown?( + event: MouseEvent, + pos: Vector2, + graphCanvas: LGraphCanvas + ): void; + onMouseMove?( + event: MouseEvent, + pos: Vector2, + graphCanvas: LGraphCanvas + ): void; + onMouseUp?( + event: MouseEvent, + pos: Vector2, + graphCanvas: LGraphCanvas + ): void; + onMouseEnter?( + event: MouseEvent, + pos: Vector2, + graphCanvas: LGraphCanvas + ): void; + onMouseLeave?( + event: MouseEvent, + pos: Vector2, + graphCanvas: LGraphCanvas + ): void; + onKey?(event: KeyboardEvent, pos: Vector2, graphCanvas: LGraphCanvas): void; + // @rgthree + onKeyDown?(event: KeyboardEvent): void; + // @rgthree + onKeyUp?(event: KeyboardEvent): void; + + onExecuted(message: any): void; + /** Called by `LGraphNode.createNode` */ + onNodeCreated?(): void; + /** Called by `LGraphCanvas.selectNodes` */ + onSelected?(): void; + /** Called by `LGraphCanvas.deselectNode` */ + onDeselected?(): void; + /** Called by `LGraph.runStep` `LGraphNode.getInputData` */ + onExecute?(): void; + /** Called by `LGraph.serialize` */ + onSerialize?(o: SerializedLGraphNode): void; + /** Called by `LGraph.configure` */ + onConfigure?(o: SerializedLGraphNode): void; + /** + * when added to graph (warning: this is called BEFORE the node is configured when loading) + * Called by `LGraph.add` + */ + onAdded?(graph: LGraph): void; + /** + * when removed from graph + * Called by `LGraph.remove` `LGraph.clear` + */ + onRemoved?(): void; + /** + * if returns false the incoming connection will be canceled + * Called by `LGraph.connect` + * @param inputIndex target input slot number + * @param outputType type of output slot + * @param outputSlot output slot object + * @param outputNode node containing the output + * @param outputIndex index of output slot + */ + onConnectInput?( + inputIndex: number, + outputType: INodeOutputSlot["type"], + outputSlot: INodeOutputSlot, + outputNode: LGraphNode, + outputIndex: number + ): boolean; + /** + * if returns false the incoming connection will be canceled + * Called by `LGraph.connect` + * @param outputIndex target output slot number + * @param inputType type of input slot + * @param inputSlot input slot object + * @param inputNode node containing the input + * @param inputIndex index of input slot + */ + onConnectOutput?( + outputIndex: number, + inputType: INodeInputSlot["type"], + inputSlot: INodeInputSlot, + inputNode: LGraphNode, + inputIndex: number + ): boolean; + + /** + * Called just before connection (or disconnect - if input is linked). + * A convenient place to switch to another input, or create new one. + * This allow for ability to automatically add slots if needed + * @param inputIndex + * @return selected input slot index, can differ from parameter value + */ + onBeforeConnectInput?( + inputIndex: number + ): number; + + /** a connection changed (new one or removed) (LiteGraph.INPUT or LiteGraph.OUTPUT, slot, true if connected, link_info, input_info or output_info ) */ + onConnectionsChange( + type: number, + slotIndex: number, + isConnected: boolean, + link: LLink, + // @rgthree - Make it INodeSlot instead of union + ioSlot: INodeSlot + ): void; + + /** + * if returns false, will abort the `LGraphNode.setProperty` + * Called when a property is changed + * @param property + * @param value + * @param prevValue + */ + onPropertyChanged?(property: string, value: any, prevValue: any): void | boolean; + + /** Called by `LGraphCanvas.processContextMenu` */ + getMenuOptions?(graphCanvas: LGraphCanvas): ContextMenuItem[]; + // @rgthree. This is fixed because the INodeSlot is wrong and, also, null can be returned to not trigger a menu. + // getSlotMenuOptions?(slot: INodeSlot): ContextMenuItem[]; + getSlotMenuOptions(slot: {input?: INodeInputSlot, output?: INodeOutputSlot}): ContextMenuItem[] | null; + + getExtraMenuOptions?(canvas: LGraphCanvas, options: ContextMenuItem[]): void; + + // @rgthree - Called in LiteGraph.core when the properties panel is constructed. + onShowCustomPanelInfo(panel: HTMLElement): void; +} + +export type LGraphNodeConstructor = { + new (): T; + + // @rgthree + title_mode?: + typeof LiteGraph.NORMAL_TITLE | + typeof LiteGraph.TRANSPARENT_TITLE | + typeof LiteGraph.AUTOHIDE_TITLE | + typeof LiteGraph.NO_TITLE; + title: string; + category: string; + type: string; + comfyClass?: string; +}; + +export type SerializedLGraphGroup = { + title: LGraphGroup["title"]; + bounding: LGraphGroup["_bounding"]; + color: LGraphGroup["color"]; + font: LGraphGroup["font"]; +}; +export declare class LGraphGroup { + title: string; + // @rgthree - mark unprivate + _bounding: Vector4; + // @rgthree - updated to make optional because it seems to be so. + color?: string|null; + font: string; + // @rgthree + _nodes: LGraphNode[]; + // @rgthree + _pos: Vector2; + // @rgthree + _size: Vector2; + // @rgthree + graph: LGraph; + // @rgthree - apparently it is available? + size: Vector2; + // @rgthree - apparently it is available? + pos: Vector2; + + + configure(o: SerializedLGraphGroup): void; + serialize(): SerializedLGraphGroup; + move(deltaX: number, deltaY: number, ignoreNodes?: boolean): void; + recomputeInsideNodes(): void; + isPointInside: LGraphNode["isPointInside"]; + setDirtyCanvas: LGraphNode["setDirtyCanvas"]; +} + +export declare class DragAndScale { + constructor(element?: HTMLElement, skipEvents?: boolean); + offset: [number, number]; + scale: number; + max_scale: number; + min_scale: number; + onredraw: Function | null; + enabled: boolean; + last_mouse: Vector2; + element: HTMLElement | null; + visible_area: Vector4; + bindEvents(element: HTMLElement): void; + computeVisibleArea(): void; + onMouse(e: MouseEvent): void; + toCanvasContext(ctx: CanvasRenderingContext2D): void; + convertOffsetToCanvas(pos: Vector2): Vector2; + convertCanvasToOffset(pos: Vector2): Vector2; + mouseDrag(x: number, y: number): void; + changeScale(value: number, zooming_center?: Vector2): void; + changeDeltaScale(value: number, zooming_center?: Vector2): void; + reset(): void; +} + +// @rgthree. +interface CanvasDivDialog extends HTMLDivElement { + close: () => void; + modified: () => void; + is_modified: boolean; +} + +/** + * This class is in charge of rendering one graph inside a canvas. And provides all the interaction required. + * Valid callbacks are: onNodeSelected, onNodeDeselected, onShowNodePanel, onNodeDblClicked + * + * @param canvas the canvas where you want to render (it accepts a selector in string format or the canvas element itself) + * @param graph + * @param options { skip_rendering, autoresize } + */ +export declare class LGraphCanvas { + static node_colors: Record< + string, + { + color: string; + bgcolor: string; + groupcolor: string; + } + >; + static link_type_colors: Record; + static gradients: object; + static search_limit: number; + + static getFileExtension(url: string): string; + static decodeHTML(str: string): string; + + static onMenuCollapseAll(): void; + static onMenuNodeEdit(): void; + static onShowPropertyEditor( + item: any, + options: any, + e: any, + menu: any, + node: any + ): void; + /** Create menu for `Add Group` */ + static onGroupAdd: ContextMenuEventListener; + /** Create menu for `Add Node` */ + static onMenuAdd: ContextMenuEventListener; + static showMenuNodeOptionalInputs: ContextMenuEventListener; + static showMenuNodeOptionalOutputs: ContextMenuEventListener; + static onShowMenuNodeProperties: ContextMenuEventListener; + static onResizeNode: ContextMenuEventListener; + static onMenuNodeCollapse: ContextMenuEventListener; + static onMenuNodePin: ContextMenuEventListener; + static onMenuNodeMode: ContextMenuEventListener; + static onMenuNodeColors: ContextMenuEventListener; + static onMenuNodeShapes: ContextMenuEventListener; + static onMenuNodeRemove: ContextMenuEventListener; + static onMenuNodeClone: ContextMenuEventListener; + + // @rgthree + static onShowPropertyEditor: ContextMenuEventListener; + + constructor( + canvas: HTMLCanvasElement | string, + graph?: LGraph, + options?: { + skip_render?: boolean; + autoresize?: boolean; + } + ); + + // @rgthree. This was "HTMLCanvasElement" but that is just wrong... it's LGraphCanvas + static active_canvas: LGraphCanvas; + + // @rgthree + pointer_is_down: boolean; + + allow_dragcanvas: boolean; + allow_dragnodes: boolean; + /** allow to control widgets, buttons, collapse, etc */ + allow_interaction: boolean; + /** allows to change a connection with having to redo it again */ + allow_reconnect_links: boolean; + /** allow selecting multi nodes without pressing extra keys */ + multi_select: boolean; + /** No effect */ + allow_searchbox: boolean; + always_render_background: boolean; + autoresize?: boolean; + background_image: string; + bgcanvas: HTMLCanvasElement; + bgctx: CanvasRenderingContext2D; + canvas: HTMLCanvasElement; + canvas_mouse: Vector2; + // @rgthree - Looks like this is to replace canvas_mouse. + graph_mouse: Vector2; + clear_background: boolean; + // connecting_node: LGraphNode | null; + // // @rgthree - for overriding. + // _connecting_node: LGraphNode | null; + // @rgthree + // connecting_input: INodeInputSlot | null; + // // @rgthree + // connecting_output: INodeOutputSlot | null; + // // @rgthree + // connecting_slot: number; + // // @rgthree + // connecting_pos: Vector2 | null; + // @rgthree - for some reason, the new comfyUI update renamed connecting_node to connecting_links (maybe) + connecting_links: { + node: LGraphNode, input?: INodeInputSlot, output?: INodeOutputSlot, pos: Vector2, slot: number + }[] | null; + _connecting_links: this['connecting_links'] | null; + + connections_width: number; + ctx: CanvasRenderingContext2D; + current_node: LGraphNode | null; + default_connection_color: { + input_off: string; + input_on: string; + output_off: string; + output_on: string; + }; + default_link_color: string; + dirty_area: Vector4 | null; + dirty_bgcanvas?: boolean; + dirty_canvas?: boolean; + drag_mode: boolean; + dragging_canvas: boolean; + dragging_rectangle: Vector4 | null; + // @rgthree; mark undefined. + // It doesn't look like this should ever be undefined.. but something changed in Comfy and folks + // reported https://github.com/rgthree/rgthree-comfy/issues/71. I couldn't reproduce, but we can + // handle it. + ds?: DragAndScale; + /** used for transition */ + editor_alpha: number; + filter: any; + fps: number; + frame: number; + graph: LGraph; + highlighted_links: Record; + highquality_render: boolean; + inner_text_font: string; + is_rendering: boolean; + last_draw_time: number; + last_mouse: Vector2; + /** + * Possible duplicated with `last_mouse` + * https://github.com/jagenjo/litegraph.js/issues/70 + */ + last_mouse_position: Vector2; + /** Timestamp of last mouse click, defaults to 0 */ + last_mouseclick: number; + links_render_mode: + | typeof LiteGraph.STRAIGHT_LINK + | typeof LiteGraph.LINEAR_LINK + | typeof LiteGraph.SPLINE_LINK; + live_mode: boolean; + node_capturing_input: LGraphNode | null; + node_dragged: LGraphNode | null; + node_in_panel: LGraphNode | null; + node_over: LGraphNode | null; + node_title_color: string; + node_widget: [LGraphNode, IWidget] | null; + /** Called by `LGraphCanvas.drawBackCanvas` */ + onDrawBackground: + | ((ctx: CanvasRenderingContext2D, visibleArea: Vector4) => void) + | null; + /** Called by `LGraphCanvas.drawFrontCanvas` */ + onDrawForeground: + | ((ctx: CanvasRenderingContext2D, visibleArea: Vector4) => void) + | null; + onDrawOverlay: ((ctx: CanvasRenderingContext2D) => void) | null; + /** Called by `LGraphCanvas.processMouseDown` */ + onMouse: ((event: MouseEvent) => boolean) | null; + /** Called by `LGraphCanvas.drawFrontCanvas` and `LGraphCanvas.drawLinkTooltip` */ + onDrawLinkTooltip: ((ctx: CanvasRenderingContext2D, link: LLink, _this: this) => void) | null; + /** Called by `LGraphCanvas.selectNodes` */ + onNodeMoved: ((node: LGraphNode) => void) | null; + /** Called by `LGraphCanvas.processNodeSelected` */ + onNodeSelected: ((node: LGraphNode) => void) | null; + /** Called by `LGraphCanvas.deselectNode` */ + onNodeDeselected: ((node: LGraphNode) => void) | null; + /** Called by `LGraphCanvas.processNodeDblClicked` */ + onShowNodePanel: ((node: LGraphNode) => void) | null; + /** Called by `LGraphCanvas.processNodeDblClicked` */ + onNodeDblClicked: ((node: LGraphNode) => void) | null; + /** Called by `LGraphCanvas.selectNodes` */ + onSelectionChange: ((nodes: Record) => void) | null; + /** Called by `LGraphCanvas.showSearchBox` */ + onSearchBox: + | (( + helper: Element, + value: string, + graphCanvas: LGraphCanvas + ) => string[]) + | null; + onSearchBoxSelection: + | ((name: string, event: MouseEvent, graphCanvas: LGraphCanvas) => void) + | null; + pause_rendering: boolean; + render_canvas_border: boolean; + render_collapsed_slots: boolean; + render_connection_arrows: boolean; + render_connections_border: boolean; + render_connections_shadows: boolean; + render_curved_connections: boolean; + render_execution_order: boolean; + render_only_selected: boolean; + render_shadows: boolean; + render_title_colored: boolean; + round_radius: number; + selected_group: null | LGraphGroup; + selected_group_resizing: boolean; + selected_nodes: Record; + show_info: boolean; + title_text_font: string; + /** set to true to render title bar with gradients */ + use_gradients: boolean; + visible_area: DragAndScale["visible_area"]; + visible_links: LLink[]; + visible_nodes: LGraphNode[]; + zoom_modify_alpha: boolean; + + /** clears all the data inside */ + clear(): void; + /** assigns a graph, you can reassign graphs to the same canvas */ + setGraph(graph: LGraph, skipClear?: boolean): void; + /** opens a graph contained inside a node in the current graph */ + openSubgraph(graph: LGraph): void; + /** closes a subgraph contained inside a node */ + closeSubgraph(): void; + /** assigns a canvas */ + setCanvas(canvas: HTMLCanvasElement, skipEvents?: boolean): void; + /** binds mouse, keyboard, touch and drag events to the canvas */ + bindEvents(): void; + /** unbinds mouse events from the canvas */ + unbindEvents(): void; + + /** + * this function allows to render the canvas using WebGL instead of Canvas2D + * this is useful if you plant to render 3D objects inside your nodes, it uses litegl.js for webgl and canvas2DtoWebGL to emulate the Canvas2D calls in webGL + **/ + enableWebGL(): void; + + /** + * marks as dirty the canvas, this way it will be rendered again + * @param fg if the foreground canvas is dirty (the one containing the nodes) + * @param bg if the background canvas is dirty (the one containing the wires) + */ + setDirty(fg: boolean, bg: boolean): void; + + /** + * Used to attach the canvas in a popup + * @return the window where the canvas is attached (the DOM root node) + */ + getCanvasWindow(): Window; + /** starts rendering the content of the canvas when needed */ + startRendering(): void; + /** stops rendering the content of the canvas (to save resources) */ + stopRendering(): void; + + processMouseDown(e: MouseEvent): boolean | undefined; + processMouseMove(e: MouseEvent): boolean | undefined; + processMouseUp(e: MouseEvent): boolean | undefined; + processMouseWheel(e: MouseEvent): boolean | undefined; + + /** returns true if a position (in graph space) is on top of a node little corner box */ + isOverNodeBox(node: LGraphNode, canvasX: number, canvasY: number): boolean; + /** returns true if a position (in graph space) is on top of a node input slot */ + isOverNodeInput( + node: LGraphNode, + canvasX: number, + canvasY: number, + slotPos: Vector2 + ): boolean; + + /** process a key event */ + processKey(e: KeyboardEvent): boolean | undefined; + + // @rgthree - added param + copyToClipboard(nodes: LGraphNode[]|{[key:number]:LGraphNode}): void; + pasteFromClipboard(): void; + processDrop(e: DragEvent): void; + checkDropItem(e: DragEvent): void; + processNodeDblClicked(n: LGraphNode): void; + processNodeSelected(n: LGraphNode, e: MouseEvent): void; + processNodeDeselected(node: LGraphNode): void; + + /** selects a given node (or adds it to the current selection) */ + selectNode(node: LGraphNode, add?: boolean): void; + /** selects several nodes (or adds them to the current selection) */ + selectNodes(nodes?: LGraphNode[], add?: boolean): void; + /** removes a node from the current selection */ + deselectNode(node: LGraphNode): void; + /** removes all nodes from the current selection */ + deselectAllNodes(): void; + /** deletes all nodes in the current selection from the graph */ + deleteSelectedNodes(): void; + + /** centers the camera on a given node */ + // @rgthree - narrow parameter + centerOnNode(node: {pos: Vector2, size: Vector2}): void; + /** changes the zoom level of the graph (default is 1), you can pass also a place used to pivot the zoom */ + setZoom(value: number, center: Vector2): void; + /** brings a node to front (above all other nodes) */ + bringToFront(node: LGraphNode): void; + /** sends a node to the back (below all other nodes) */ + sendToBack(node: LGraphNode): void; + /** checks which nodes are visible (inside the camera area) */ + computeVisibleNodes(nodes: LGraphNode[]): LGraphNode[]; + /** renders the whole canvas content, by rendering in two separated canvas, one containing the background grid and the connections, and one containing the nodes) */ + draw(forceFG?: boolean, forceBG?: boolean): void; + /** draws the front canvas (the one containing all the nodes) */ + drawFrontCanvas(): void; + /** draws some useful stats in the corner of the canvas */ + renderInfo(ctx: CanvasRenderingContext2D, x: number, y: number): void; + /** draws the back canvas (the one containing the background and the connections) */ + drawBackCanvas(): void; + /** draws the given node inside the canvas */ + drawNode(node: LGraphNode, ctx: CanvasRenderingContext2D): void; + /** draws graphic for node's slot */ + drawSlotGraphic(ctx: CanvasRenderingContext2D, pos: number[], shape: SlotShape, horizontal: boolean): void; + /** draws the shape of the given node in the canvas */ + drawNodeShape( + node: LGraphNode, + ctx: CanvasRenderingContext2D, + size: [number, number], + fgColor: string, + bgColor: string, + selected: boolean, + mouseOver: boolean + ): void; + /** draws every connection visible in the canvas */ + drawConnections(ctx: CanvasRenderingContext2D): void; + /** + * draws a link between two points + * @param a start pos + * @param b end pos + * @param link the link object with all the link info + * @param skipBorder ignore the shadow of the link + * @param flow show flow animation (for events) + * @param color the color for the link + * @param startDir the direction enum + * @param endDir the direction enum + * @param numSublines number of sublines (useful to represent vec3 or rgb) + **/ + renderLink( + a: Vector2, + b: Vector2, + link: object, + skipBorder: boolean, + flow: boolean, + color?: string, + startDir?: number, + endDir?: number, + numSublines?: number + ): void; + + computeConnectionPoint( + a: Vector2, + b: Vector2, + t: number, + startDir?: number, + endDir?: number + ): void; + + drawExecutionOrder(ctx: CanvasRenderingContext2D): void; + /** draws the widgets stored inside a node */ + drawNodeWidgets( + node: LGraphNode, + posY: number, + ctx: CanvasRenderingContext2D, + activeWidget: object + ): void; + /** process an event on widgets */ + processNodeWidgets( + node: LGraphNode, + pos: Vector2, + event: Event, + activeWidget: object + ): void; + /** draws every group area in the background */ + drawGroups(canvas: any, ctx: CanvasRenderingContext2D): void; + adjustNodesSize(): void; + /** resizes the canvas to a given size, if no size is passed, then it tries to fill the parentNode */ + resize(width?: number, height?: number): void; + /** + * switches to live mode (node shapes are not rendered, only the content) + * this feature was designed when graphs where meant to create user interfaces + **/ + switchLiveMode(transition?: boolean): void; + onNodeSelectionChange(): void; + touchHandler(event: TouchEvent): void; + + showLinkMenu(link: LLink, e: any): false; + prompt( + title: string, + value: any, + callback: Function, + event: any + ): HTMLDivElement; + showSearchBox(event?: MouseEvent): void; + showEditPropertyValue(node: LGraphNode, property: any, options: any): void; + createDialog( + html: string, + options?: { position?: Vector2; event?: MouseEvent } + // @rgthree - Fix return type from void (added above) + ): CanvasDivDialog; + + + + convertOffsetToCanvas: DragAndScale["convertOffsetToCanvas"]; + convertCanvasToOffset: DragAndScale["convertCanvasToOffset"]; + /** converts event coordinates from canvas2D to graph coordinates */ + // @rgthree - change MouseEvent to less restrictive {clientX: number, clientY: number} that + // implementation uses. + convertEventToCanvasOffset(e: {clientX: number, clientY: number}): Vector2; + /** adds some useful properties to a mouse event, like the position in graph coordinates */ + adjustMouseEvent(e: MouseEvent): void; + + getCanvasMenuOptions(): ContextMenuItem[]; + getNodeMenuOptions(node: LGraphNode): ContextMenuItem[]; + getGroupMenuOptions(): ContextMenuItem[]; + /** Called by `getCanvasMenuOptions`, replace default options */ + getMenuOptions?(): ContextMenuItem[]; + /** Called by `getCanvasMenuOptions`, append to default options */ + getExtraMenuOptions?(): ContextMenuItem[]; + /** Called when mouse right click */ + processContextMenu(node: LGraphNode, event: Event): void; + + // @rgthree - Adding this for ComfyUI, since they add this in their own overload in app.js + selected_group_moving?: boolean; + + // @rgthree + showShowNodePanel(node: LGraphNode): void; +} + +// @rgthree - The adjusted pointer event after calling adjustMouseEvent +export interface AdjustedMouseEvent extends PointerEvent { + deltaX: number; + deltaY: number; + canvasX: number; + canvasY: number; +} + +declare class ContextMenu { + static trigger( + element: HTMLElement, + event_name: string, + params: any, + origin: any + ): void; + static isCursorOverElement(event: MouseEvent, element: HTMLElement): void; + static closeAllContextMenus(window: Window): void; + constructor(values: ContextMenuItem[]|string[], options?: IContextMenuOptions, window?: Window); + options: IContextMenuOptions; + parentMenu?: ContextMenu; + lock: boolean; + current_submenu?: ContextMenu; + addItem( + name: string, + value: ContextMenuItem, + options?: IContextMenuOptions + ): void; + close(e?: MouseEvent, ignore_parent_menu?: boolean): void; + getTopMenu(): void; + getFirstEvent(): void; +} + +declare global { + interface Math { + clamp(v: number, min: number, max: number): number; + } +} diff --git a/ComfyUI-Crystools/web/common.d.ts b/ComfyUI-Crystools/web/common.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2ff0b26071ed9ae42874e4da60033520c876ea8b --- /dev/null +++ b/ComfyUI-Crystools/web/common.d.ts @@ -0,0 +1,4 @@ +import type { TLGraphNode } from './comfy/index.js'; +import { ComfyApp } from './comfy/index.js'; +export declare const commonPrefix = "\uD83E\uDE9B"; +export declare function displayContext(nodeType: TLGraphNode, appFromArg: ComfyApp, index?: number, serialize_widgets?: boolean, isVirtualNode?: boolean): void; diff --git a/ComfyUI-Crystools/web/common.js b/ComfyUI-Crystools/web/common.js new file mode 100644 index 0000000000000000000000000000000000000000..8e806ed6bc67b201b9b9f00415d090ca10580252 --- /dev/null +++ b/ComfyUI-Crystools/web/common.js @@ -0,0 +1,50 @@ +import { ComfyWidgets } from './comfy/index.js'; +export const commonPrefix = '🪛'; +export function displayContext(nodeType, appFromArg, index = 0, serialize_widgets = false, isVirtualNode = false) { + function populate(text) { + if (this.widgets) { + const pos = this.widgets.findIndex((w) => w.name === 'text'); + if (pos !== -1) { + for (let i = pos; i < this.widgets.length; i++) { + this.widgets[i]?.onRemove?.(); + } + this.widgets.length = pos; + } + } + this.serialize_widgets = serialize_widgets; + this.isVirtualNode = isVirtualNode; + const widget = ComfyWidgets.STRING(this, 'text', [ + 'STRING', { multiline: true }, + ], appFromArg).widget; + widget.inputEl.readOnly = true; + widget.inputEl.style.opacity = 0.6; + if (Array.isArray(text) && index !== undefined && text[index] !== undefined) { + text = text[index]; + } + widget.value = text || ''; + widget.serializeValue = async () => { }; + requestAnimationFrame(() => { + const sz = this.computeSize(); + if (sz[0] < this.size[0]) { + sz[0] = this.size[0]; + } + if (sz[1] < this.size[1]) { + sz[1] = this.size[1]; + } + this.onResize?.(sz); + appFromArg.graph.setDirtyCanvas(true, false); + }); + } + const onExecutedOriginal = nodeType.prototype.onExecuted; + nodeType.prototype.onExecuted = function (message) { + onExecutedOriginal?.apply(this, arguments); + populate.call(this, message.text); + }; + const onConfigureOriginal = nodeType.prototype.onConfigure; + nodeType.prototype.onConfigure = function () { + onConfigureOriginal?.apply(this, arguments); + if (this.widgets_values?.length) { + populate.call(this, this.widgets_values); + } + }; +} diff --git a/ComfyUI-Crystools/web/common.ts b/ComfyUI-Crystools/web/common.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e2068616f6cbf81430a95efdb90950470a81b28 --- /dev/null +++ b/ComfyUI-Crystools/web/common.ts @@ -0,0 +1,92 @@ +import type { TLGraphNode } from './comfy/index.js'; +import { ComfyWidgets, ComfyApp } from './comfy/index.js'; + +export const commonPrefix = '🪛'; + +export function displayContext( + nodeType: TLGraphNode, + appFromArg: ComfyApp, + index = 0, serialize_widgets = false, isVirtualNode = false, +): void { + function populate(this: TLGraphNode, text: string | string[]): void { + if (this.widgets) { + const pos = this.widgets.findIndex((w) => w.name === 'text'); + if (pos !== -1) { + for (let i = pos; i < this.widgets.length; i++) { + + this.widgets[i]?.onRemove?.(); + } + this.widgets.length = pos; + } + } + // If you want to do not save properties in the node (be careful with F5) + // BUG on isVirtualNode, with "true", it ignores OUTPUT_NODE on py file! + this.serialize_widgets = serialize_widgets; + this.isVirtualNode = isVirtualNode; + + const widget = ComfyWidgets.STRING(this, 'text', [ + 'STRING', { multiline: true }, + ], appFromArg).widget; + widget.inputEl.readOnly = true; + widget.inputEl.style.opacity = 0.6; + if (Array.isArray(text) && index !== undefined && text[index] !== undefined) { + // @ts-ignore + text = text[index]; + } + widget.value = text || ''; + // eslint-disable-next-line @typescript-eslint/no-empty-function + widget.serializeValue = async(): Promise => {}; // just for no serialized to itself! + + requestAnimationFrame(() => { + const sz = this.computeSize(); + if (sz[0] < this.size[0]) { + sz[0] = this.size[0]; + } + if (sz[1] < this.size[1]) { + sz[1] = this.size[1]; + } + this.onResize?.(sz); + appFromArg.graph.setDirtyCanvas(true, false); + }); + } + + // When the node is executed we will be sent the input text, display this in the widget + + // @ts-ignore + // eslint-disable-next-line @typescript-eslint/unbound-method + const onExecutedOriginal = nodeType.prototype.onExecuted; + nodeType.prototype.onExecuted = function(message: { text: string }): void { + // @ts-ignore + onExecutedOriginal?.apply(this, arguments); + populate.call(this, message.text); + }; + + // eslint-disable-next-line @typescript-eslint/unbound-method + const onConfigureOriginal = nodeType.prototype.onConfigure; + nodeType.prototype.onConfigure = function(): void { + // @ts-ignore + onConfigureOriginal?.apply(this, arguments); + if (this.widgets_values?.length) { + populate.call(this, this.widgets_values); + } + }; +} + + +// propagate the output value to the dependents nodes, it does not work with some nodes ¯\_(ツ)_/¯ +// const propagateOutputToDependentsNodes = function(output: serializedLGraph, value: string) { +// if (output.links?.length) { +// for (const l of output.links) { +// const link_info = app.graph.links[l]; +// const outNode = app.graph.getNodeById(link_info.target_id); +// const outIn = outNode?.inputs?.[link_info.target_slot]; +// if (outIn.widget) { +// const widget = outNode.widgets.find((w: IWidget) => w.name === outIn.widget.name); +// if (!widget) { +// continue; +// } +// widget.value = value; +// } +// } +// } +// }; diff --git a/ComfyUI-Crystools/web/debugger.d.ts b/ComfyUI-Crystools/web/debugger.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..509db1866f4b5fbb3046d4c04b51ccb638e79c80 --- /dev/null +++ b/ComfyUI-Crystools/web/debugger.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/ComfyUI-Crystools/web/debugger.js b/ComfyUI-Crystools/web/debugger.js new file mode 100644 index 0000000000000000000000000000000000000000..d1b5ecfc815c9901bce5ff489e2d7040e26b862b --- /dev/null +++ b/ComfyUI-Crystools/web/debugger.js @@ -0,0 +1,77 @@ +import { app, api, ComfyWidgets, LiteGraph, TLGraphNode } from './comfy/index.js'; +import { commonPrefix, displayContext } from './common.js'; +app.registerExtension({ + name: 'Crystools.Debugger.ConsoleAny', + beforeRegisterNodeDef(nodeType, nodeData, appFromArg) { + if (nodeData.name === 'Show any [Crystools]') { + displayContext(nodeType, appFromArg, 3); + } + }, +}); +app.registerExtension({ + name: 'Crystools.Debugger.Metadata', + registerCustomNodes() { + class MetadataNode extends TLGraphNode { + constructor() { + super(`${commonPrefix} Show Metadata `); + Object.defineProperty(this, "fillMetadataWidget", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + return app.graphToPrompt() + .then((workflow) => { + let result = 'inactive'; + if (this.widgets?.length !== 4) { + console.error('Something is wrong with the widgets, should be 4!'); + return 'error'; + } + const output = this.widgets[0]; + const active = this.widgets[1]?.value; + const parsed = this.widgets[2]?.value; + let what = this.widgets[3]?.value.toLowerCase(); + if (active) { + what = what === 'prompt' ? 'output' : what; + result = workflow[what]; + if (parsed) { + result = JSON.stringify(result, null, 2); + } + else { + result = JSON.stringify(result); + } + } + if (output) { + output.value = result; + } + else { + console.error('Something is wrong with the widgets, output is undefined!'); + return 'error'; + } + return result; + }); + } + }); + this.serialize_widgets = false; + this.isVirtualNode = true; + const widget = ComfyWidgets.STRING(this, '', [ + '', { default: '', multiline: true }, + ], app).widget; + widget.inputEl.readOnly = true; + ComfyWidgets.BOOLEAN(this, 'Active', [ + '', { default: true }, + ]); + ComfyWidgets.BOOLEAN(this, 'Parsed', [ + '', { default: true }, + ]); + ComfyWidgets.COMBO(this, 'What', [ + ['Prompt', 'Workflow'], { default: 'Prompt' }, + ]); + api.addEventListener('executed', this.fillMetadataWidget, false); + } + } + LiteGraph.registerNodeType('Show Metadata [Crystools]', MetadataNode); + MetadataNode.category = `crystools ${commonPrefix}/Debugger`; + MetadataNode.shape = LiteGraph.BOX_SHAPE; + MetadataNode.title = `${commonPrefix} Show Metadata`; + }, +}); diff --git a/ComfyUI-Crystools/web/debugger.ts b/ComfyUI-Crystools/web/debugger.ts new file mode 100644 index 0000000000000000000000000000000000000000..813db80de84b54dfb1cdcb59dd8517c99a367641 --- /dev/null +++ b/ComfyUI-Crystools/web/debugger.ts @@ -0,0 +1,86 @@ +import type { ComfyNode } from './comfy/index.js'; +import { app, api, ComfyWidgets, LiteGraph, TLGraphNode, ComfyApp } from './comfy/index.js'; +import { commonPrefix, displayContext } from './common.js'; + +// "Show any" Node +app.registerExtension({ + name: 'Crystools.Debugger.ConsoleAny', + beforeRegisterNodeDef(nodeType: ComfyNode, nodeData: TLGraphNode, appFromArg: ComfyApp) { + if (nodeData.name === 'Show any [Crystools]') { + // 3 is the index of the text field in the node + displayContext(nodeType, appFromArg, 3); + } + }, +}); + +app.registerExtension({ + name: 'Crystools.Debugger.Metadata', + registerCustomNodes() { + class MetadataNode extends TLGraphNode { + constructor() { + super(`${commonPrefix} Show Metadata `); + this.serialize_widgets = false; + this.isVirtualNode = true; + + const widget = ComfyWidgets.STRING(this, '', [ + '', {default: '', multiline: true}, + ], app).widget; + widget.inputEl.readOnly = true; + ComfyWidgets.BOOLEAN(this, 'Active', [ + '', {default: true}, + ]); + ComfyWidgets.BOOLEAN(this, 'Parsed', [ + '', {default: true}, + ]); + ComfyWidgets.COMBO(this, 'What', [ + ['Prompt', 'Workflow'], {default: 'Prompt'}, + ]); + + // It runs at finish on each prompt queue + api.addEventListener('executed', this.fillMetadataWidget, false); + } + + fillMetadataWidget = (): Promise => { + return app.graphToPrompt() + .then((workflow: any): string => { + let result = 'inactive'; + if (this.widgets?.length !== 4) { + console.error('Something is wrong with the widgets, should be 4!'); + return 'error'; + } + const output = this.widgets[0]; + const active = this.widgets[1]?.value; + const parsed = this.widgets[2]?.value; + let what = this.widgets[3]?.value.toLowerCase(); + + if (active) { + what = what === 'prompt' ? 'output' : what; // little fix for better understanding + // @ts-ignore + result = workflow[what]; + if (parsed) { + result = JSON.stringify(result, null, 2); + } else { + result = JSON.stringify(result); + } + } + if (output) { + output.value = result; + } else { + console.error('Something is wrong with the widgets, output is undefined!'); + return 'error'; + } + return result; + }); + }; + } + + // I'm not sure for what they're using prototype and lots of black magic, don't change the order! + LiteGraph.registerNodeType('Show Metadata [Crystools]', MetadataNode); + MetadataNode.category = `crystools ${commonPrefix}/Debugger`; + MetadataNode.shape = LiteGraph.BOX_SHAPE; + MetadataNode.title = `${commonPrefix} Show Metadata`; + // MetadataNode.collapsable = false; + // MetadataNode.color = '#FF2222'; + // MetadataNode.bgcolor = '#000000'; + }, +}); diff --git a/ComfyUI-Crystools/web/extensions.d.ts b/ComfyUI-Crystools/web/extensions.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..509db1866f4b5fbb3046d4c04b51ccb638e79c80 --- /dev/null +++ b/ComfyUI-Crystools/web/extensions.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/ComfyUI-Crystools/web/extensions.js b/ComfyUI-Crystools/web/extensions.js new file mode 100644 index 0000000000000000000000000000000000000000..18c47755e0dcd19a1d949fdd8f55fe4a0b5e2613 --- /dev/null +++ b/ComfyUI-Crystools/web/extensions.js @@ -0,0 +1,32 @@ +import { app } from './comfy/index.js'; +import { displayContext } from './common.js'; +const crystoolsExtensionsSerialized = { + 'Read JSON file [Crystools]': 'Crystools.Utils.ReadJsonFile', + 'JSON extractor [Crystools]': 'Crystools.Utils.JsonExtractor', +}; +const crystoolsExtensions = { + 'Get resolution [Crystools]': 'Crystools.Image.GetResolution', + 'Preview from image [Crystools]': 'Crystools.Image.PreviewFromImage', + 'Preview from metadata [Crystools]': 'Crystools.Image.PreviewFromMetadata', + 'Metadata comparator [Crystools]': 'Crystools.Metadata.MetadataComparator', + 'Stats system [Crystools]': 'Crystools.Utils.StatsSystem', + 'Show any to JSON [Crystools]': 'Crystools.Debugger.ConsoleAnyToJson', +}; +Object.keys(crystoolsExtensionsSerialized).forEach(prop => { + crystoolsExtensions[prop] = crystoolsExtensionsSerialized[prop]; +}); +Object.keys(crystoolsExtensions).forEach(key => { + app.registerExtension({ + name: crystoolsExtensions[key], + beforeRegisterNodeDef(nodeType, nodeData, appFromArg) { + if (nodeData.name === key) { + if (nodeData.name in crystoolsExtensionsSerialized) { + displayContext(nodeType, appFromArg, 0, true); + } + else { + displayContext(nodeType, appFromArg, 0); + } + } + }, + }); +}); diff --git a/ComfyUI-Crystools/web/extensions.ts b/ComfyUI-Crystools/web/extensions.ts new file mode 100644 index 0000000000000000000000000000000000000000..0ea283beb338b51cb93666012b2da380275cc8be --- /dev/null +++ b/ComfyUI-Crystools/web/extensions.ts @@ -0,0 +1,38 @@ +import { app, TLGraphNode, ComfyApp } from './comfy/index.js'; +import type { ComfyNode } from './comfy/index.js'; +import { displayContext } from './common.js'; + +const crystoolsExtensionsSerialized: Record = { + // 'External parameter from JSON file [Crystools]': 'Crystools.Utils.ExternalParameterFromJson', + 'Read JSON file [Crystools]': 'Crystools.Utils.ReadJsonFile', + 'JSON extractor [Crystools]': 'Crystools.Utils.JsonExtractor', +}; + +const crystoolsExtensions: Record = { + 'Get resolution [Crystools]': 'Crystools.Image.GetResolution', + 'Preview from image [Crystools]': 'Crystools.Image.PreviewFromImage', + 'Preview from metadata [Crystools]': 'Crystools.Image.PreviewFromMetadata', + 'Metadata comparator [Crystools]': 'Crystools.Metadata.MetadataComparator', + 'Stats system [Crystools]': 'Crystools.Utils.StatsSystem', + 'Show any to JSON [Crystools]': 'Crystools.Debugger.ConsoleAnyToJson', +}; + +Object.keys(crystoolsExtensionsSerialized).forEach(prop => { + // @ts-ignore + crystoolsExtensions[prop] = crystoolsExtensionsSerialized[prop]; +}); + +Object.keys(crystoolsExtensions).forEach(key => { + app.registerExtension({ + name: crystoolsExtensions[key], + beforeRegisterNodeDef(nodeType: ComfyNode, nodeData: TLGraphNode, appFromArg: ComfyApp) { + if (nodeData.name === key) { + if (nodeData.name in crystoolsExtensionsSerialized) { + displayContext(nodeType, appFromArg, 0, true); // serialize_widgets = true + } else { + displayContext(nodeType, appFromArg, 0); + } + } + }, + }); +}); diff --git a/ComfyUI-Crystools/web/monitor.css b/ComfyUI-Crystools/web/monitor.css new file mode 100644 index 0000000000000000000000000000000000000000..c68e2fed5a38718433ab742ea44e03a47a38e9e7 --- /dev/null +++ b/ComfyUI-Crystools/web/monitor.css @@ -0,0 +1,188 @@ +/* Vertical UI */ +.comfy-menu, .side-bar-panel { + #crystools-monitors-root { + /*background-color: red;*/ + box-shadow: 3px 3px 10px rgba(0, 0, 0, 0.3); + background-color: var(--comfy-menu-bg); + border-radius: 6px; + border: 1px solid var(--border-color); + display: flex; + width: 100%; + flex-direction: column; + margin: 7px; + padding: 5px 0; + cursor: crosshair; + + /* MONITORS */ + + .crystools-monitor { + margin: 1px 10px; + height: 12px; + display: flex; + align-items: center; + + .crystools-text { + width: 40px; + font-size: 10px; + text-align: right; + margin-right: 3px; + + &:hover { + font-weight: 600; + color: var(--input-text); + } + } + + .crystools-label { + &:hover { + font-weight: 700; + color: var(--input-text); + } + } + } + + .crystools-content { + flex-grow: 1; + position: relative; + background-color: var(--content-hover-bg) + } + + .crystools-slider { + position: absolute; + height: 100%; + width: 0; + box-shadow: inset 2px 2px 10px rgba(0, 0, 0, 0.2); + } + + .crystools-label { + position: relative; + color: var(--input-text); + font-size: 10px; + } + } + + /* PROGRESS BAR */ + + #crystools-progressBar-root { + cursor: pointer; + margin: 0 12px 4px; + height: 18px; + position: relative; + border-radius: 3px; + width: 100%; + background-color: var(--comfy-input-bg); + + .crystools-slider { + position: absolute; + height: 100%; + width: 50%; + transition: width 0.2s; + background-color: green; + box-shadow: inset 2px 2px 10px rgba(0, 0, 0, 0.3); + } + + .crystools-label { + position: absolute; + margin: auto 0; + width: 100%; + color: var(--input-text); + font-size: 14px; + } + } +} + +/* side-bar-panel */ +.side-bar-panel { + #crystools-monitors-root { + width: 230px; + margin-left: auto; + margin-right: auto; + } +} + +.comfyui-queue-button { + /*width: unset !important;*/ +} + +/* Horizontal UI */ +#crystools-monitors-root { + /*background-color: red;*/ + /*display: none;*/ + flex-direction: row; + /*flex-grow: 5;*/ + justify-content: flex-end; + /*flex: auto;*/ + flex-shrink: 1; + /*min-width: max-content;*/ + /*height: 100%;*/ + /* max-width: 40vw;*/ + /* min-width: 10vw;*/ + /*gap: 5px;*/ + /*margin: 0 auto;*/ + /*align-items: center;*/ + /*align-self: center;*/ + /*width: min-content;*/ + /*width: 100%;*/ + cursor: crosshair; + /*margin: 4px 0;*/ + display: flex; /* by progress bar base */ + flex-wrap: wrap; + /*flex-direction: row;*/ + /*justify-content: flex-end;*/ + /*align-items: center;*/ + gap: 5px; + align-self: center; + + .crystools-monitor { + background-color: var(--comfy-input-bg); + position: relative; + align-items: center; + flex-direction: row; + /*width: 60px;*/ + /*height: 100%;*/ + + .crystools-text { + font-size: 10px; + text-align: right; + margin-left: 3px; + position: absolute; + font-weight: 100; + bottom: 2px; + z-index: 10; + + /*&:hover {*/ + /* font-weight: 600;*/ + /* color: var(--input-text);*/ + /*}*/ + } + + /*.crystools-label {*/ + /* &:hover {*/ + /* font-weight: 800;*/ + /* color: var(--input-text);*/ + /* }*/ + /*}*/ + } + + .crystools-content { + position: relative; + } + + .crystools-slider { + position: absolute; + height: 100%; + width: 0; + box-shadow: inset 2px 2px 10px rgba(0, 0, 0, 0.2); + } + + .crystools-label { + position: relative; + width: 100%; + color: var(--input-text); + font-weight: 500; + font-size: 11px; + right: 2px; + top: 2px; + text-align: right; + } +} diff --git a/ComfyUI-Crystools/web/monitor.d.ts b/ComfyUI-Crystools/web/monitor.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..509db1866f4b5fbb3046d4c04b51ccb638e79c80 --- /dev/null +++ b/ComfyUI-Crystools/web/monitor.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/ComfyUI-Crystools/web/monitor.js b/ComfyUI-Crystools/web/monitor.js new file mode 100644 index 0000000000000000000000000000000000000000..95eaefe544792951bee4490c04c04c8c0fc68bc7 --- /dev/null +++ b/ComfyUI-Crystools/web/monitor.js @@ -0,0 +1,656 @@ +import { app, api, ComfyButtonGroup } from './comfy/index.js'; +import { commonPrefix } from './common.js'; +import { MonitorUI } from './monitorUI.js'; +import { Colors } from './styles.js'; +import { convertNumberToPascalCase } from './utils.js'; +import { ComfyKeyMenuDisplayOption, MenuDisplayOptions } from './progressBarUIBase.js'; +class CrystoolsMonitor { + constructor() { + Object.defineProperty(this, "idExtensionName", { + enumerable: true, + configurable: true, + writable: true, + value: 'Crystools.monitor' + }); + Object.defineProperty(this, "menuPrefix", { + enumerable: true, + configurable: true, + writable: true, + value: commonPrefix + }); + Object.defineProperty(this, "menuDisplayOption", { + enumerable: true, + configurable: true, + writable: true, + value: MenuDisplayOptions.Disabled + }); + Object.defineProperty(this, "crystoolsButtonGroup", { + enumerable: true, + configurable: true, + writable: true, + value: null + }); + Object.defineProperty(this, "settingsRate", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "settingsMonitorHeight", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "settingsMonitorWidth", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "monitorCPUElement", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "monitorRAMElement", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "monitorHDDElement", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "settingsHDD", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "monitorGPUSettings", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "monitorVRAMSettings", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "monitorTemperatureSettings", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "monitorUI", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "monitorWidthId", { + enumerable: true, + configurable: true, + writable: true, + value: 'Crystools.MonitorWidth' + }); + Object.defineProperty(this, "monitorWidth", { + enumerable: true, + configurable: true, + writable: true, + value: 60 + }); + Object.defineProperty(this, "monitorHeightId", { + enumerable: true, + configurable: true, + writable: true, + value: 'Crystools.MonitorHeight' + }); + Object.defineProperty(this, "monitorHeight", { + enumerable: true, + configurable: true, + writable: true, + value: 30 + }); + Object.defineProperty(this, "createSettingsRate", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + this.settingsRate = { + id: 'Crystools.RefreshRate', + name: 'Refresh per second', + category: ['Crystools', this.menuPrefix + ' Configuration', 'refresh'], + tooltip: 'This is the time (in seconds) between each update of the monitors, 0 means no refresh', + type: 'slider', + attrs: { + min: 0, + max: 2, + step: .25, + }, + defaultValue: .5, + onChange: async (value) => { + let valueNumber; + try { + valueNumber = parseFloat(value); + if (isNaN(valueNumber)) { + throw new Error('invalid value'); + } + } + catch (error) { + console.error(error); + return; + } + try { + await this.updateServer({ rate: valueNumber }); + } + catch (error) { + console.error(error); + return; + } + const data = { + cpu_utilization: 0, + device: 'cpu', + gpus: [ + { + gpu_utilization: 0, + gpu_temperature: 0, + vram_total: 0, + vram_used: 0, + vram_used_percent: 0, + }, + ], + hdd_total: 0, + hdd_used: 0, + hdd_used_percent: 0, + ram_total: 0, + ram_used: 0, + ram_used_percent: 0, + }; + if (valueNumber === 0) { + this.monitorUI.updateDisplay(data); + } + this.monitorUI?.updateAllAnimationDuration(valueNumber); + }, + }; + } + }); + Object.defineProperty(this, "createSettingsMonitorWidth", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + this.settingsMonitorWidth = { + id: this.monitorWidthId, + name: 'Pixel Width', + category: ['Crystools', this.menuPrefix + ' Configuration', 'width'], + tooltip: 'The width of the monitor in pixels on the UI (only on top/bottom UI)', + type: 'slider', + attrs: { + min: 60, + max: 100, + step: 1, + }, + defaultValue: this.monitorWidth, + onChange: (value) => { + let valueNumber; + try { + valueNumber = parseInt(value); + if (isNaN(valueNumber)) { + throw new Error('invalid value'); + } + } + catch (error) { + console.error(error); + return; + } + const h = app.extensionManager.setting.get(this.monitorHeightId); + this.monitorUI?.updateMonitorSize(valueNumber, h); + }, + }; + } + }); + Object.defineProperty(this, "createSettingsMonitorHeight", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + this.settingsMonitorHeight = { + id: this.monitorHeightId, + name: 'Pixel Height', + category: ['Crystools', this.menuPrefix + ' Configuration', 'height'], + tooltip: 'The height of the monitor in pixels on the UI (only on top/bottom UI)', + type: 'slider', + attrs: { + min: 16, + max: 50, + step: 1, + }, + defaultValue: this.monitorHeight, + onChange: async (value) => { + let valueNumber; + try { + valueNumber = parseInt(value); + if (isNaN(valueNumber)) { + throw new Error('invalid value'); + } + } + catch (error) { + console.error(error); + return; + } + const w = await app.extensionManager.setting.get(this.monitorWidthId); + this.monitorUI?.updateMonitorSize(w, valueNumber); + }, + }; + } + }); + Object.defineProperty(this, "createSettingsCPU", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + this.monitorCPUElement = { + id: 'Crystools.ShowCpu', + name: 'CPU Usage', + category: ['Crystools', this.menuPrefix + ' Hardware', 'Cpu'], + type: 'boolean', + label: 'CPU', + symbol: '%', + defaultValue: true, + htmlMonitorRef: undefined, + htmlMonitorSliderRef: undefined, + htmlMonitorLabelRef: undefined, + cssColor: Colors.CPU, + onChange: async (value) => { + await this.updateServer({ switchCPU: value }); + this.updateWidget(this.monitorCPUElement); + }, + }; + } + }); + Object.defineProperty(this, "createSettingsRAM", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + this.monitorRAMElement = { + id: 'Crystools.ShowRam', + name: 'RAM Used', + category: ['Crystools', this.menuPrefix + ' Hardware', 'Ram'], + type: 'boolean', + label: 'RAM', + symbol: '%', + defaultValue: true, + htmlMonitorRef: undefined, + htmlMonitorSliderRef: undefined, + htmlMonitorLabelRef: undefined, + cssColor: Colors.RAM, + onChange: async (value) => { + await this.updateServer({ switchRAM: value }); + this.updateWidget(this.monitorRAMElement); + }, + }; + } + }); + Object.defineProperty(this, "createSettingsGPUUsage", { + enumerable: true, + configurable: true, + writable: true, + value: (name, index, moreThanOneGPU) => { + if (name === undefined || index === undefined) { + console.warn('getGPUsFromServer: name or index undefined', name, index); + return; + } + let label = 'GPU '; + label += moreThanOneGPU ? index : ''; + const monitorGPUNElement = { + id: 'Crystools.ShowGpuUsage' + convertNumberToPascalCase(index), + name: ' Usage', + category: ['Crystools', `${this.menuPrefix} Show GPU [${index}] ${name}`, 'Usage'], + type: 'boolean', + label, + symbol: '%', + monitorTitle: `${index}: ${name}`, + defaultValue: true, + htmlMonitorRef: undefined, + htmlMonitorSliderRef: undefined, + htmlMonitorLabelRef: undefined, + cssColor: Colors.GPU, + onChange: async (value) => { + await this.updateServerGPU(index, { utilization: value }); + this.updateWidget(monitorGPUNElement); + }, + }; + this.monitorGPUSettings[index] = monitorGPUNElement; + app.ui.settings.addSetting(this.monitorGPUSettings[index]); + this.monitorUI.createDOMGPUMonitor(this.monitorGPUSettings[index]); + } + }); + Object.defineProperty(this, "createSettingsGPUVRAM", { + enumerable: true, + configurable: true, + writable: true, + value: (name, index, moreThanOneGPU) => { + if (name === undefined || index === undefined) { + console.warn('getGPUsFromServer: name or index undefined', name, index); + return; + } + let label = 'VRAM '; + label += moreThanOneGPU ? index : ''; + const monitorVRAMNElement = { + id: 'Crystools.ShowGpuVram' + convertNumberToPascalCase(index), + name: 'VRAM', + category: ['Crystools', `${this.menuPrefix} Show GPU [${index}] ${name}`, 'VRAM'], + type: 'boolean', + label: label, + symbol: '%', + monitorTitle: `${index}: ${name}`, + defaultValue: true, + htmlMonitorRef: undefined, + htmlMonitorSliderRef: undefined, + htmlMonitorLabelRef: undefined, + cssColor: Colors.VRAM, + onChange: async (value) => { + await this.updateServerGPU(index, { vram: value }); + this.updateWidget(monitorVRAMNElement); + }, + }; + this.monitorVRAMSettings[index] = monitorVRAMNElement; + app.ui.settings.addSetting(this.monitorVRAMSettings[index]); + this.monitorUI.createDOMGPUMonitor(this.monitorVRAMSettings[index]); + } + }); + Object.defineProperty(this, "createSettingsGPUTemp", { + enumerable: true, + configurable: true, + writable: true, + value: (name, index, moreThanOneGPU) => { + if (name === undefined || index === undefined) { + console.warn('getGPUsFromServer: name or index undefined', name, index); + return; + } + let label = 'Temp '; + label += moreThanOneGPU ? index : ''; + const monitorTemperatureNElement = { + id: 'Crystools.ShowGpuTemperature' + convertNumberToPascalCase(index), + name: 'Temperature', + category: ['Crystools', `${this.menuPrefix} Show GPU [${index}] ${name}`, 'Temperature'], + type: 'boolean', + label: label, + symbol: '°', + monitorTitle: `${index}: ${name}`, + defaultValue: true, + htmlMonitorRef: undefined, + htmlMonitorSliderRef: undefined, + htmlMonitorLabelRef: undefined, + cssColor: Colors.TEMP_START, + cssColorFinal: Colors.TEMP_END, + onChange: async (value) => { + await this.updateServerGPU(index, { temperature: value }); + this.updateWidget(monitorTemperatureNElement); + }, + }; + this.monitorTemperatureSettings[index] = monitorTemperatureNElement; + app.ui.settings.addSetting(this.monitorTemperatureSettings[index]); + this.monitorUI.createDOMGPUMonitor(this.monitorTemperatureSettings[index]); + } + }); + Object.defineProperty(this, "createSettingsHDD", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + this.monitorHDDElement = { + id: 'Crystools.ShowHdd', + name: 'Show HDD Used', + category: ['Crystools', this.menuPrefix + ' Show Hard Disk', 'Show'], + type: 'boolean', + label: 'HDD', + symbol: '%', + defaultValue: false, + htmlMonitorRef: undefined, + htmlMonitorSliderRef: undefined, + htmlMonitorLabelRef: undefined, + cssColor: Colors.DISK, + onChange: async (value) => { + await this.updateServer({ switchHDD: value }); + this.updateWidget(this.monitorHDDElement); + }, + }; + this.settingsHDD = { + id: 'Crystools.WhichHdd', + name: 'Partition to show', + category: ['Crystools', this.menuPrefix + ' Show Hard Disk', 'Which'], + type: 'combo', + defaultValue: '/', + options: [], + onChange: async (value) => { + await this.updateServer({ whichHDD: value }); + }, + }; + } + }); + Object.defineProperty(this, "createSettings", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + app.ui.settings.addSetting(this.settingsRate); + app.ui.settings.addSetting(this.settingsMonitorHeight); + app.ui.settings.addSetting(this.settingsMonitorWidth); + app.ui.settings.addSetting(this.monitorRAMElement); + app.ui.settings.addSetting(this.monitorCPUElement); + void this.getHDDsFromServer().then((data) => { + this.settingsHDD.options = data; + app.ui.settings.addSetting(this.settingsHDD); + }); + app.ui.settings.addSetting(this.monitorHDDElement); + void this.getGPUsFromServer().then((gpus) => { + let moreThanOneGPU = false; + if (gpus.length > 1) { + moreThanOneGPU = true; + } + gpus?.forEach(({ name, index }) => { + this.createSettingsGPUTemp(name, index, moreThanOneGPU); + this.createSettingsGPUVRAM(name, index, moreThanOneGPU); + this.createSettingsGPUUsage(name, index, moreThanOneGPU); + }); + this.finishedLoad(); + }); + } + }); + Object.defineProperty(this, "finishedLoad", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + this.monitorUI.orderMonitors(); + this.updateAllWidget(); + this.moveMonitor(this.menuDisplayOption); + const w = app.extensionManager.setting.get(this.monitorWidthId); + const h = app.extensionManager.setting.get(this.monitorHeightId); + this.monitorUI.updateMonitorSize(w, h); + } + }); + Object.defineProperty(this, "updateDisplay", { + enumerable: true, + configurable: true, + writable: true, + value: (value) => { + if (value !== this.menuDisplayOption) { + this.menuDisplayOption = value; + this.moveMonitor(this.menuDisplayOption); + } + } + }); + Object.defineProperty(this, "moveMonitor", { + enumerable: true, + configurable: true, + writable: true, + value: (menuPosition) => { + let parentElement; + switch (menuPosition) { + case MenuDisplayOptions.Disabled: + parentElement = document.getElementById('queue-button'); + if (parentElement && this.monitorUI.rootElement) { + parentElement.insertAdjacentElement('afterend', this.crystoolsButtonGroup.element); + } + else { + console.error('Crystools: parentElement to move monitors not found!', parentElement); + } + break; + case MenuDisplayOptions.Top: + case MenuDisplayOptions.Bottom: + app.menu?.settingsGroup.element.before(this.crystoolsButtonGroup.element); + } + } + }); + Object.defineProperty(this, "updateAllWidget", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + this.updateWidget(this.monitorCPUElement); + this.updateWidget(this.monitorRAMElement); + this.updateWidget(this.monitorHDDElement); + this.monitorGPUSettings.forEach((monitorSettings) => { + monitorSettings && this.updateWidget(monitorSettings); + }); + this.monitorVRAMSettings.forEach((monitorSettings) => { + monitorSettings && this.updateWidget(monitorSettings); + }); + this.monitorTemperatureSettings.forEach((monitorSettings) => { + monitorSettings && this.updateWidget(monitorSettings); + }); + } + }); + Object.defineProperty(this, "updateWidget", { + enumerable: true, + configurable: true, + writable: true, + value: (monitorSettings) => { + if (this.monitorUI) { + const value = app.extensionManager.setting.get(monitorSettings.id); + this.monitorUI.showMonitor(monitorSettings, value); + } + } + }); + Object.defineProperty(this, "updateServer", { + enumerable: true, + configurable: true, + writable: true, + value: async (data) => { + const resp = await api.fetchApi('/crystools/monitor', { + method: 'PATCH', + body: JSON.stringify(data), + cache: 'no-store', + }); + if (resp.status === 200) { + return await resp.text(); + } + throw new Error(resp.statusText); + } + }); + Object.defineProperty(this, "updateServerGPU", { + enumerable: true, + configurable: true, + writable: true, + value: async (index, data) => { + const resp = await api.fetchApi(`/crystools/monitor/GPU/${index}`, { + method: 'PATCH', + body: JSON.stringify(data), + cache: 'no-store', + }); + if (resp.status === 200) { + return await resp.text(); + } + throw new Error(resp.statusText); + } + }); + Object.defineProperty(this, "getHDDsFromServer", { + enumerable: true, + configurable: true, + writable: true, + value: async () => { + return this.getDataFromServer('HDD'); + } + }); + Object.defineProperty(this, "getGPUsFromServer", { + enumerable: true, + configurable: true, + writable: true, + value: async () => { + return this.getDataFromServer('GPU'); + } + }); + Object.defineProperty(this, "getDataFromServer", { + enumerable: true, + configurable: true, + writable: true, + value: async (what) => { + const resp = await api.fetchApi(`/crystools/monitor/${what}`, { + method: 'GET', + cache: 'no-store', + }); + if (resp.status === 200) { + return await resp.json(); + } + throw new Error(resp.statusText); + } + }); + Object.defineProperty(this, "setup", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + if (this.monitorUI) { + return; + } + this.createSettingsRate(); + this.createSettingsMonitorHeight(); + this.createSettingsMonitorWidth(); + this.createSettingsCPU(); + this.createSettingsRAM(); + this.createSettingsHDD(); + this.createSettings(); + const currentRate = parseFloat(app.extensionManager.setting.get(this.settingsRate.id)); + this.menuDisplayOption = app.extensionManager.setting.get(ComfyKeyMenuDisplayOption); + app.ui.settings.addEventListener(`${ComfyKeyMenuDisplayOption}.change`, (e) => { + this.updateDisplay(e.detail.value); + }); + this.crystoolsButtonGroup = new ComfyButtonGroup(); + app.menu?.settingsGroup.element.before(this.crystoolsButtonGroup.element); + this.monitorUI = new MonitorUI(this.crystoolsButtonGroup.element, this.monitorCPUElement, this.monitorRAMElement, this.monitorHDDElement, this.monitorGPUSettings, this.monitorVRAMSettings, this.monitorTemperatureSettings, currentRate); + this.updateDisplay(this.menuDisplayOption); + this.registerListeners(); + } + }); + Object.defineProperty(this, "registerListeners", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + api.addEventListener('crystools.monitor', (event) => { + if (event?.detail === undefined) { + return; + } + this.monitorUI.updateDisplay(event.detail); + }, false); + } + }); + } +} +const crystoolsMonitor = new CrystoolsMonitor(); +app.registerExtension({ + name: crystoolsMonitor.idExtensionName, + setup: crystoolsMonitor.setup, +}); diff --git a/ComfyUI-Crystools/web/monitor.ts b/ComfyUI-Crystools/web/monitor.ts new file mode 100644 index 0000000000000000000000000000000000000000..4fa7e4378f95e7ff38ccb2174debaea76ab26a65 --- /dev/null +++ b/ComfyUI-Crystools/web/monitor.ts @@ -0,0 +1,588 @@ +import { app, api, ComfyButtonGroup } from './comfy/index.js'; +import { commonPrefix } from './common.js'; +import { MonitorUI } from './monitorUI.js'; +import { Colors } from './styles.js'; +import { convertNumberToPascalCase } from './utils.js'; +import { ComfyKeyMenuDisplayOption, MenuDisplayOptions } from './progressBarUIBase.js'; + +// enum MonitorPosition { +// 'Top' = 'Top', +// 'Sidebar' = 'Sidebar', +// 'Floating' = 'Floating', +// } + +class CrystoolsMonitor { + readonly idExtensionName = 'Crystools.monitor'; + private readonly menuPrefix = commonPrefix; + private menuDisplayOption: MenuDisplayOptions = MenuDisplayOptions.Disabled; + private crystoolsButtonGroup: ComfyButtonGroup = null; + + // private settingsMonitorPosition: TMonitorSettings; + private settingsRate: TMonitorSettings; + private settingsMonitorHeight: TMonitorSettings; + private settingsMonitorWidth: TMonitorSettings; + private monitorCPUElement: TMonitorSettings; + private monitorRAMElement: TMonitorSettings; + private monitorHDDElement: TMonitorSettings; + private settingsHDD: TMonitorSettings; + private monitorGPUSettings: TMonitorSettings[] = []; + private monitorVRAMSettings: TMonitorSettings[] = []; + private monitorTemperatureSettings: TMonitorSettings[] = []; + + private monitorUI: MonitorUI; + + // private readonly monitorPositionId = 'Crystools.MonitorPosition'; + private readonly monitorWidthId = 'Crystools.MonitorWidth'; + private readonly monitorWidth = 60; + private readonly monitorHeightId = 'Crystools.MonitorHeight'; + private readonly monitorHeight = 30; + + // NO POSIBLE TO IMPLEMENT INSIDE THE PANEL + // createSettingsMonitorPosition = (): void => { + // const position = app.extensionManager.setting.get(this.monitorPositionId); + // console.log('position', position); + // this.settingsMonitorPosition = { + // id: this.monitorPositionId, + // name: 'Position (floating not implemented yet)', + // category: ['Crystools', this.menuPrefix + ' Configuration', 'position'], + // tooltip: 'Only for new UI', + // experimental: true, + // // data: [], + // type: 'combo', + // options: [ + // MonitorPoistion.Top, + // MonitorPoistion.Sidebar, + // MonitorPoistion.Floating + // ], + // + // defaultValue: MonitorPoistion.Sidebar, + // // @ts-ignore + // onChange: (_value: string): void => { + // // if (this.monitorUI) { + // // console.log('onChange', _value); + // // this.moveMonitor(this.menuDisplayOption); + // // } + // }, + // }; + // }; + + createSettingsRate = (): void => { + this.settingsRate = { + id: 'Crystools.RefreshRate', + name: 'Refresh per second', + category: ['Crystools', this.menuPrefix + ' Configuration', 'refresh'], + tooltip: 'This is the time (in seconds) between each update of the monitors, 0 means no refresh', + type: 'slider', + attrs: { + min: 0, + max: 2, + step: .25, + }, + defaultValue: .5, + + // @ts-ignore + onChange: async(value: string): Promise => { + let valueNumber: number; + + try { + valueNumber = parseFloat(value); + if (isNaN(valueNumber)) { + throw new Error('invalid value'); + } + } catch (error) { + console.error(error); + return; + } + try { + await this.updateServer({rate: valueNumber}); + } catch (error) { + console.error(error); + return; + } + + const data = { + cpu_utilization: 0, + device: 'cpu', + + gpus: [ + { + gpu_utilization: 0, + gpu_temperature: 0, + vram_total: 0, + vram_used: 0, + vram_used_percent: 0, + }, + ], + hdd_total: 0, + hdd_used: 0, + hdd_used_percent: 0, + ram_total: 0, + ram_used: 0, + ram_used_percent: 0, + }; + if (valueNumber === 0) { + this.monitorUI.updateDisplay(data); + } + + this.monitorUI?.updateAllAnimationDuration(valueNumber); + }, + }; + }; + + createSettingsMonitorWidth = (): void => { + this.settingsMonitorWidth = { + id: this.monitorWidthId, + name: 'Pixel Width', + category: ['Crystools', this.menuPrefix + ' Configuration', 'width'], + tooltip: 'The width of the monitor in pixels on the UI (only on top/bottom UI)', + type: 'slider', + attrs: { + min: 60, + max: 100, + step: 1, + }, + defaultValue: this.monitorWidth, + // @ts-ignore + onChange: (value: string): void => { + let valueNumber: number; + + try { + valueNumber = parseInt(value); + if (isNaN(valueNumber)) { + throw new Error('invalid value'); + } + } catch (error) { + console.error(error); + return; + } + + const h = app.extensionManager.setting.get(this.monitorHeightId); + this.monitorUI?.updateMonitorSize(valueNumber, h); + }, + }; + }; + + createSettingsMonitorHeight = (): void => { + this.settingsMonitorHeight = { + id: this.monitorHeightId, + name: 'Pixel Height', + category: ['Crystools', this.menuPrefix + ' Configuration', 'height'], + tooltip: 'The height of the monitor in pixels on the UI (only on top/bottom UI)', + type: 'slider', + attrs: { + min: 16, + max: 50, + step: 1, + }, + defaultValue: this.monitorHeight, + // @ts-ignore + onChange: async(value: string): void => { + let valueNumber: number; + + try { + valueNumber = parseInt(value); + if (isNaN(valueNumber)) { + throw new Error('invalid value'); + } + } catch (error) { + console.error(error); + return; + } + + const w = await app.extensionManager.setting.get(this.monitorWidthId); + this.monitorUI?.updateMonitorSize(w, valueNumber); + }, + }; + }; + + createSettingsCPU = (): void => { + // CPU Variables + this.monitorCPUElement = { + id: 'Crystools.ShowCpu', + name: 'CPU Usage', + category: ['Crystools', this.menuPrefix + ' Hardware', 'Cpu'], + type: 'boolean', + label: 'CPU', + symbol: '%', + defaultValue: true, + htmlMonitorRef: undefined, + htmlMonitorSliderRef: undefined, + htmlMonitorLabelRef: undefined, + cssColor: Colors.CPU, + // @ts-ignore + onChange: async(value: boolean): Promise => { + await this.updateServer({switchCPU: value}); + this.updateWidget(this.monitorCPUElement); + }, + }; + }; + + createSettingsRAM = (): void => { + // RAM Variables + this.monitorRAMElement = { + id: 'Crystools.ShowRam', + name: 'RAM Used', + category: ['Crystools', this.menuPrefix + ' Hardware', 'Ram'], + type: 'boolean', + label: 'RAM', + symbol: '%', + defaultValue: true, + htmlMonitorRef: undefined, + htmlMonitorSliderRef: undefined, + htmlMonitorLabelRef: undefined, + cssColor: Colors.RAM, + // @ts-ignore + onChange: async(value: boolean): Promise => { + await this.updateServer({switchRAM: value}); + this.updateWidget(this.monitorRAMElement); + }, + }; + }; + + createSettingsGPUUsage = (name: string, index: number, moreThanOneGPU: boolean): void => { + if (name === undefined || index === undefined) { + console.warn('getGPUsFromServer: name or index undefined', name, index); + return; + } + + let label = 'GPU '; + label += moreThanOneGPU ? index : ''; + + const monitorGPUNElement: TMonitorSettings = { + id: 'Crystools.ShowGpuUsage' + convertNumberToPascalCase(index), + name: ' Usage', + category: ['Crystools', `${this.menuPrefix} Show GPU [${index}] ${name}`, 'Usage'], + type: 'boolean', + label, + symbol: '%', + monitorTitle: `${index}: ${name}`, + defaultValue: true, + htmlMonitorRef: undefined, + htmlMonitorSliderRef: undefined, + htmlMonitorLabelRef: undefined, + cssColor: Colors.GPU, + // @ts-ignore + onChange: async(value: boolean): Promise => { + await this.updateServerGPU(index, {utilization: value}); + this.updateWidget(monitorGPUNElement); + }, + }; + + this.monitorGPUSettings[index] = monitorGPUNElement; + app.ui.settings.addSetting(this.monitorGPUSettings[index]); + this.monitorUI.createDOMGPUMonitor(this.monitorGPUSettings[index]); + }; + + createSettingsGPUVRAM = (name: string, index: number, moreThanOneGPU: boolean): void => { + if (name === undefined || index === undefined) { + console.warn('getGPUsFromServer: name or index undefined', name, index); + return; + } + + let label = 'VRAM '; + label += moreThanOneGPU ? index : ''; + + // GPU VRAM Variables + const monitorVRAMNElement: TMonitorSettings = { + id: 'Crystools.ShowGpuVram' + convertNumberToPascalCase(index), + name: 'VRAM', + category: ['Crystools', `${this.menuPrefix} Show GPU [${index}] ${name}`, 'VRAM'], + type: 'boolean', + label: label, + symbol: '%', + monitorTitle: `${index}: ${name}`, + defaultValue: true, + htmlMonitorRef: undefined, + htmlMonitorSliderRef: undefined, + htmlMonitorLabelRef: undefined, + cssColor: Colors.VRAM, + // @ts-ignore + onChange: async(value: boolean): Promise => { + await this.updateServerGPU(index, {vram: value}); + this.updateWidget(monitorVRAMNElement); + }, + }; + + this.monitorVRAMSettings[index] = monitorVRAMNElement; + app.ui.settings.addSetting(this.monitorVRAMSettings[index]); + this.monitorUI.createDOMGPUMonitor(this.monitorVRAMSettings[index]); + }; + + createSettingsGPUTemp = (name: string, index: number, moreThanOneGPU: boolean): void => { + if (name === undefined || index === undefined) { + console.warn('getGPUsFromServer: name or index undefined', name, index); + return; + } + + let label = 'Temp '; + label += moreThanOneGPU ? index : ''; + + // GPU Temperature Variables + const monitorTemperatureNElement: TMonitorSettings = { + id: 'Crystools.ShowGpuTemperature' + convertNumberToPascalCase(index), + name: 'Temperature', + category: ['Crystools', `${this.menuPrefix} Show GPU [${index}] ${name}`, 'Temperature'], + type: 'boolean', + label: label, + symbol: '°', + monitorTitle: `${index}: ${name}`, + defaultValue: true, + htmlMonitorRef: undefined, + htmlMonitorSliderRef: undefined, + htmlMonitorLabelRef: undefined, + cssColor: Colors.TEMP_START, + cssColorFinal: Colors.TEMP_END, + // @ts-ignore + onChange: async(value: boolean): Promise => { + await this.updateServerGPU(index, {temperature: value}); + this.updateWidget(monitorTemperatureNElement); + }, + }; + + this.monitorTemperatureSettings[index] = monitorTemperatureNElement; + app.ui.settings.addSetting(this.monitorTemperatureSettings[index]); + this.monitorUI.createDOMGPUMonitor(this.monitorTemperatureSettings[index]); + }; + + createSettingsHDD = (): void => { + // HDD Variables + this.monitorHDDElement = { + id: 'Crystools.ShowHdd', + name: 'Show HDD Used', + category: ['Crystools', this.menuPrefix + ' Show Hard Disk', 'Show'], + type: 'boolean', + label: 'HDD', + symbol: '%', + // tooltip: 'See Partition to show (HDD)', + defaultValue: false, + htmlMonitorRef: undefined, + htmlMonitorSliderRef: undefined, + htmlMonitorLabelRef: undefined, + cssColor: Colors.DISK, + // @ts-ignore + onChange: async(value: boolean): Promise => { + await this.updateServer({switchHDD: value}); + this.updateWidget(this.monitorHDDElement); + }, + }; + + this.settingsHDD = { + id: 'Crystools.WhichHdd', + name: 'Partition to show', + category: ['Crystools', this.menuPrefix + ' Show Hard Disk', 'Which'], + type: 'combo', + defaultValue: '/', + options: [], + // @ts-ignore + onChange: async(value: string): Promise => { + await this.updateServer({whichHDD: value}); + }, + }; + }; + + createSettings = (): void => { + app.ui.settings.addSetting(this.settingsRate); + app.ui.settings.addSetting(this.settingsMonitorHeight); + app.ui.settings.addSetting(this.settingsMonitorWidth); + // app.ui.settings.addSetting(this.settingsMonitorPosition); + app.ui.settings.addSetting(this.monitorRAMElement); + app.ui.settings.addSetting(this.monitorCPUElement); + + void this.getHDDsFromServer().then((data: string[]): void => { + // @ts-ignore + this.settingsHDD.options = data; + app.ui.settings.addSetting(this.settingsHDD); + }); + app.ui.settings.addSetting(this.monitorHDDElement); + + void this.getGPUsFromServer().then((gpus: TGpuName[]): void => { + let moreThanOneGPU = false; + if (gpus.length > 1) { + moreThanOneGPU = true; + } + + gpus?.forEach(({name, index}) => { + this.createSettingsGPUTemp(name, index, moreThanOneGPU); + this.createSettingsGPUVRAM(name, index, moreThanOneGPU); + this.createSettingsGPUUsage(name, index, moreThanOneGPU); + }); + + this.finishedLoad(); + }); + }; + + finishedLoad = (): void => { + this.monitorUI.orderMonitors(); + this.updateAllWidget(); + this.moveMonitor(this.menuDisplayOption); + + const w = app.extensionManager.setting.get(this.monitorWidthId); + const h = app.extensionManager.setting.get(this.monitorHeightId); + this.monitorUI.updateMonitorSize(w, h); + }; + + updateDisplay = (value: MenuDisplayOptions): void => { + if (value !== this.menuDisplayOption) { + this.menuDisplayOption = value; + this.moveMonitor(this.menuDisplayOption); + } + }; + + moveMonitor = (menuPosition: MenuDisplayOptions): void => { + // console.log('moveMonitor', menuPosition); + // setTimeout(() => { + let parentElement: Element | null | undefined; + + switch (menuPosition) { + case MenuDisplayOptions.Disabled: + parentElement = document.getElementById('queue-button'); + if (parentElement && this.monitorUI.rootElement) { + parentElement.insertAdjacentElement('afterend', this.crystoolsButtonGroup.element); + } else { + console.error('Crystools: parentElement to move monitors not found!', parentElement); + } + break; + + case MenuDisplayOptions.Top: + case MenuDisplayOptions.Bottom: + // const position = app.extensionManager.setting.get(this.monitorPositionId); + // if(position === MonitorPosition.Top) { + app.menu?.settingsGroup.element.before(this.crystoolsButtonGroup.element); + // } else { + // parentElement = document.getElementsByClassName('comfy-vue-side-bar-header')[0]; + // if(parentElement){ + // parentElement.insertBefore(this.crystoolsButtonGroup.element, parentElement.firstChild); + // } else { + // console.error('Crystools: parentElement to move monitors not found! back to top'); + // app.ui.settings.setSettingValue(this.monitorPositionId, MonitorPoistion.Top); + // } + // } + } + // }, 100); + }; + + updateAllWidget = (): void => { + this.updateWidget(this.monitorCPUElement); + this.updateWidget(this.monitorRAMElement); + this.updateWidget(this.monitorHDDElement); + + this.monitorGPUSettings.forEach((monitorSettings) => { + monitorSettings && this.updateWidget(monitorSettings); + }); + this.monitorVRAMSettings.forEach((monitorSettings) => { + monitorSettings && this.updateWidget(monitorSettings); + }); + this.monitorTemperatureSettings.forEach((monitorSettings) => { + monitorSettings && this.updateWidget(monitorSettings); + }); + }; + + /** + * for the settings menu + * @param monitorSettings + */ + updateWidget = (monitorSettings: TMonitorSettings): void => { + if (this.monitorUI) { + const value = app.extensionManager.setting.get(monitorSettings.id); + this.monitorUI.showMonitor(monitorSettings, value); + } + }; + + updateServer = async(data: TStatsSettings): Promise => { + const resp = await api.fetchApi('/crystools/monitor', { + method: 'PATCH', + body: JSON.stringify(data), + cache: 'no-store', + }); + if (resp.status === 200) { + return await resp.text(); + } + throw new Error(resp.statusText); + }; + + updateServerGPU = async(index: number, data: TGpuSettings): Promise => { + const resp = await api.fetchApi(`/crystools/monitor/GPU/${index}`, { + method: 'PATCH', + body: JSON.stringify(data), + cache: 'no-store', + }); + if (resp.status === 200) { + return await resp.text(); + } + throw new Error(resp.statusText); + }; + + getHDDsFromServer = async(): Promise => { + return this.getDataFromServer('HDD'); + }; + + getGPUsFromServer = async(): Promise => { + return this.getDataFromServer('GPU'); + }; + + getDataFromServer = async (what: string): Promise => { + const resp = await api.fetchApi(`/crystools/monitor/${what}`, { + method: 'GET', + cache: 'no-store', + }); + if (resp.status === 200) { + return await resp.json(); + } + throw new Error(resp.statusText); + }; + + setup = (): void => { + if (this.monitorUI) { + return; + } + // this.createSettingsMonitorPosition(); + this.createSettingsRate(); + this.createSettingsMonitorHeight(); + this.createSettingsMonitorWidth(); + this.createSettingsCPU(); + this.createSettingsRAM(); + this.createSettingsHDD(); + this.createSettings(); + + const currentRate = + parseFloat(app.extensionManager.setting.get(this.settingsRate.id)); + + this.menuDisplayOption = app.extensionManager.setting.get(ComfyKeyMenuDisplayOption); + app.ui.settings.addEventListener(`${ComfyKeyMenuDisplayOption}.change`, (e: any) => { + this.updateDisplay(e.detail.value); + }, + ); + + this.crystoolsButtonGroup = new ComfyButtonGroup(); + app.menu?.settingsGroup.element.before(this.crystoolsButtonGroup.element); + + this.monitorUI = new MonitorUI( + this.crystoolsButtonGroup.element, + this.monitorCPUElement, + this.monitorRAMElement, + this.monitorHDDElement, + this.monitorGPUSettings, + this.monitorVRAMSettings, + this.monitorTemperatureSettings, + currentRate, + ); + + this.updateDisplay(this.menuDisplayOption); + this.registerListeners(); + }; + + registerListeners = (): void => { + api.addEventListener('crystools.monitor', (event: CustomEvent) => { + if (event?.detail === undefined) { + return; + } + this.monitorUI.updateDisplay(event.detail); + }, false); + }; +} + +const crystoolsMonitor = new CrystoolsMonitor(); +app.registerExtension({ + name: crystoolsMonitor.idExtensionName, + setup: crystoolsMonitor.setup, +}); diff --git a/ComfyUI-Crystools/web/monitorUI.d.ts b/ComfyUI-Crystools/web/monitorUI.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..10fee45e4eb4a3f1a1f8829d33f2237ffef33973 --- /dev/null +++ b/ComfyUI-Crystools/web/monitorUI.d.ts @@ -0,0 +1,26 @@ +import { ProgressBarUIBase } from './progressBarUIBase.js'; +export declare class MonitorUI extends ProgressBarUIBase { + rootElement: HTMLElement; + private monitorCPUElement; + private monitorRAMElement; + private monitorHDDElement; + private monitorGPUSettings; + private monitorVRAMSettings; + private monitorTemperatureSettings; + private currentRate; + lastMonitor: number; + styleSheet: HTMLStyleElement; + maxVRAMUsed: Record; + constructor(rootElement: HTMLElement, monitorCPUElement: TMonitorSettings, monitorRAMElement: TMonitorSettings, monitorHDDElement: TMonitorSettings, monitorGPUSettings: TMonitorSettings[], monitorVRAMSettings: TMonitorSettings[], monitorTemperatureSettings: TMonitorSettings[], currentRate: number); + createDOM: () => void; + createDOMGPUMonitor: (monitorSettings?: TMonitorSettings) => void; + orderMonitors: () => void; + updateDisplay: (data: TStatsData) => void; + updateMonitor: (monitorSettings: TMonitorSettings, percent: number, used?: number, total?: number) => void; + updateAllAnimationDuration: (value: number) => void; + updatedAnimationDuration: (monitorSettings: TMonitorSettings, value: number) => void; + createMonitor: (monitorSettings?: TMonitorSettings) => HTMLDivElement; + updateMonitorSize: (width: number, height: number) => void; + showMonitor: (monitorSettings: TMonitorSettings, value: boolean) => void; + resetMaxVRAM: () => void; +} diff --git a/ComfyUI-Crystools/web/monitorUI.js b/ComfyUI-Crystools/web/monitorUI.js new file mode 100644 index 0000000000000000000000000000000000000000..c93e35979b049eeec536788d245801a72edf1aba --- /dev/null +++ b/ComfyUI-Crystools/web/monitorUI.js @@ -0,0 +1,303 @@ +import { ProgressBarUIBase } from './progressBarUIBase.js'; +import { createStyleSheet, formatBytes } from './utils.js'; +export class MonitorUI extends ProgressBarUIBase { + constructor(rootElement, monitorCPUElement, monitorRAMElement, monitorHDDElement, monitorGPUSettings, monitorVRAMSettings, monitorTemperatureSettings, currentRate) { + super('crystools-monitors-root', rootElement); + Object.defineProperty(this, "rootElement", { + enumerable: true, + configurable: true, + writable: true, + value: rootElement + }); + Object.defineProperty(this, "monitorCPUElement", { + enumerable: true, + configurable: true, + writable: true, + value: monitorCPUElement + }); + Object.defineProperty(this, "monitorRAMElement", { + enumerable: true, + configurable: true, + writable: true, + value: monitorRAMElement + }); + Object.defineProperty(this, "monitorHDDElement", { + enumerable: true, + configurable: true, + writable: true, + value: monitorHDDElement + }); + Object.defineProperty(this, "monitorGPUSettings", { + enumerable: true, + configurable: true, + writable: true, + value: monitorGPUSettings + }); + Object.defineProperty(this, "monitorVRAMSettings", { + enumerable: true, + configurable: true, + writable: true, + value: monitorVRAMSettings + }); + Object.defineProperty(this, "monitorTemperatureSettings", { + enumerable: true, + configurable: true, + writable: true, + value: monitorTemperatureSettings + }); + Object.defineProperty(this, "currentRate", { + enumerable: true, + configurable: true, + writable: true, + value: currentRate + }); + Object.defineProperty(this, "lastMonitor", { + enumerable: true, + configurable: true, + writable: true, + value: 1 + }); + Object.defineProperty(this, "styleSheet", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "maxVRAMUsed", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "createDOM", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + if (!this.rootElement) { + throw Error('Crystools: MonitorUI - Container not found'); + } + this.rootElement.appendChild(this.createMonitor(this.monitorCPUElement)); + this.rootElement.appendChild(this.createMonitor(this.monitorRAMElement)); + this.rootElement.appendChild(this.createMonitor(this.monitorHDDElement)); + this.updateAllAnimationDuration(this.currentRate); + } + }); + Object.defineProperty(this, "createDOMGPUMonitor", { + enumerable: true, + configurable: true, + writable: true, + value: (monitorSettings) => { + if (!(monitorSettings && this.rootElement)) { + return; + } + this.rootElement.appendChild(this.createMonitor(monitorSettings)); + this.updateAllAnimationDuration(this.currentRate); + } + }); + Object.defineProperty(this, "orderMonitors", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + try { + this.monitorCPUElement.htmlMonitorRef.style.order = '' + this.lastMonitor++; + this.monitorRAMElement.htmlMonitorRef.style.order = '' + this.lastMonitor++; + this.monitorGPUSettings.forEach((_monitorSettings, index) => { + this.monitorGPUSettings[index].htmlMonitorRef.style.order = '' + this.lastMonitor++; + this.monitorVRAMSettings[index].htmlMonitorRef.style.order = '' + this.lastMonitor++; + this.monitorTemperatureSettings[index].htmlMonitorRef.style.order = '' + this.lastMonitor++; + }); + this.monitorHDDElement.htmlMonitorRef.style.order = '' + this.lastMonitor++; + } + catch (error) { + console.error('orderMonitors', error); + } + } + }); + Object.defineProperty(this, "updateDisplay", { + enumerable: true, + configurable: true, + writable: true, + value: (data) => { + this.updateMonitor(this.monitorCPUElement, data.cpu_utilization); + this.updateMonitor(this.monitorRAMElement, data.ram_used_percent, data.ram_used, data.ram_total); + this.updateMonitor(this.monitorHDDElement, data.hdd_used_percent, data.hdd_used, data.hdd_total); + if (data.gpus === undefined || data.gpus.length === 0) { + console.warn('UpdateAllMonitors: no GPU data'); + return; + } + this.monitorGPUSettings.forEach((monitorSettings, index) => { + if (data.gpus[index]) { + const gpu = data.gpus[index]; + if (gpu === undefined) { + return; + } + this.updateMonitor(monitorSettings, gpu.gpu_utilization); + } + else { + } + }); + this.monitorVRAMSettings.forEach((monitorSettings, index) => { + if (data.gpus[index]) { + const gpu = data.gpus[index]; + if (gpu === undefined) { + return; + } + this.updateMonitor(monitorSettings, gpu.vram_used_percent, gpu.vram_used, gpu.vram_total); + } + else { + } + }); + this.monitorTemperatureSettings.forEach((monitorSettings, index) => { + if (data.gpus[index]) { + const gpu = data.gpus[index]; + if (gpu === undefined) { + return; + } + this.updateMonitor(monitorSettings, gpu.gpu_temperature); + if (monitorSettings.cssColorFinal && monitorSettings.htmlMonitorSliderRef) { + monitorSettings.htmlMonitorSliderRef.style.backgroundColor = + `color-mix(in srgb, ${monitorSettings.cssColorFinal} ${gpu.gpu_temperature}%, ${monitorSettings.cssColor})`; + } + } + else { + } + }); + } + }); + Object.defineProperty(this, "updateMonitor", { + enumerable: true, + configurable: true, + writable: true, + value: (monitorSettings, percent, used, total) => { + if (!(monitorSettings.htmlMonitorSliderRef && monitorSettings.htmlMonitorLabelRef)) { + return; + } + if (percent < 0) { + return; + } + const prefix = monitorSettings.monitorTitle ? monitorSettings.monitorTitle + ' - ' : ''; + let title = `${Math.floor(percent)}${monitorSettings.symbol}`; + let postfix = ''; + if (used !== undefined && total !== undefined) { + const gpuIndex = parseInt(monitorSettings.monitorTitle?.split(':')[0] || '0'); + if (!this.maxVRAMUsed[gpuIndex] || this.maxVRAMUsed[gpuIndex] > total) { + this.maxVRAMUsed[gpuIndex] = 0; + } + if (used > this.maxVRAMUsed[gpuIndex]) { + this.maxVRAMUsed[gpuIndex] = used; + } + postfix = ` - ${formatBytes(used)} / ${formatBytes(total)}`; + postfix += ` Max: ${formatBytes(this.maxVRAMUsed[gpuIndex])}`; + } + title = `${prefix}${title}${postfix}`; + if (monitorSettings.htmlMonitorRef) { + monitorSettings.htmlMonitorRef.title = title; + } + monitorSettings.htmlMonitorLabelRef.innerHTML = `${Math.floor(percent)}${monitorSettings.symbol}`; + monitorSettings.htmlMonitorSliderRef.style.width = `${Math.floor(percent)}%`; + } + }); + Object.defineProperty(this, "updateAllAnimationDuration", { + enumerable: true, + configurable: true, + writable: true, + value: (value) => { + this.updatedAnimationDuration(this.monitorCPUElement, value); + this.updatedAnimationDuration(this.monitorRAMElement, value); + this.updatedAnimationDuration(this.monitorHDDElement, value); + this.monitorGPUSettings.forEach((monitorSettings) => { + monitorSettings && this.updatedAnimationDuration(monitorSettings, value); + }); + this.monitorVRAMSettings.forEach((monitorSettings) => { + monitorSettings && this.updatedAnimationDuration(monitorSettings, value); + }); + this.monitorTemperatureSettings.forEach((monitorSettings) => { + monitorSettings && this.updatedAnimationDuration(monitorSettings, value); + }); + } + }); + Object.defineProperty(this, "updatedAnimationDuration", { + enumerable: true, + configurable: true, + writable: true, + value: (monitorSettings, value) => { + const slider = monitorSettings.htmlMonitorSliderRef; + if (!slider) { + return; + } + slider.style.transition = `width ${value.toFixed(1)}s`; + } + }); + Object.defineProperty(this, "createMonitor", { + enumerable: true, + configurable: true, + writable: true, + value: (monitorSettings) => { + if (!monitorSettings) { + return document.createElement('div'); + } + const htmlMain = document.createElement('div'); + htmlMain.classList.add(monitorSettings.id); + htmlMain.classList.add('crystools-monitor'); + monitorSettings.htmlMonitorRef = htmlMain; + if (monitorSettings.title) { + htmlMain.title = monitorSettings.title; + } + const htmlMonitorText = document.createElement('div'); + htmlMonitorText.classList.add('crystools-text'); + htmlMonitorText.innerHTML = monitorSettings.label; + htmlMain.append(htmlMonitorText); + const htmlMonitorContent = document.createElement('div'); + htmlMonitorContent.classList.add('crystools-content'); + htmlMain.append(htmlMonitorContent); + const htmlMonitorSlider = document.createElement('div'); + htmlMonitorSlider.classList.add('crystools-slider'); + if (monitorSettings.cssColorFinal) { + htmlMonitorSlider.style.backgroundColor = + `color-mix(in srgb, ${monitorSettings.cssColorFinal} 0%, ${monitorSettings.cssColor})`; + } + else { + htmlMonitorSlider.style.backgroundColor = monitorSettings.cssColor; + } + monitorSettings.htmlMonitorSliderRef = htmlMonitorSlider; + htmlMonitorContent.append(htmlMonitorSlider); + const htmlMonitorLabel = document.createElement('div'); + htmlMonitorLabel.classList.add('crystools-label'); + monitorSettings.htmlMonitorLabelRef = htmlMonitorLabel; + htmlMonitorContent.append(htmlMonitorLabel); + htmlMonitorLabel.innerHTML = '0%'; + return monitorSettings.htmlMonitorRef; + } + }); + Object.defineProperty(this, "updateMonitorSize", { + enumerable: true, + configurable: true, + writable: true, + value: (width, height) => { + this.styleSheet.innerText = `#crystools-monitors-root .crystools-monitor .crystools-content {height: ${height}px; width: ${width}px;}`; + } + }); + Object.defineProperty(this, "showMonitor", { + enumerable: true, + configurable: true, + writable: true, + value: (monitorSettings, value) => { + if (monitorSettings.htmlMonitorRef) { + monitorSettings.htmlMonitorRef.style.display = value ? 'flex' : 'none'; + } + } + }); + Object.defineProperty(this, "resetMaxVRAM", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + this.maxVRAMUsed = {}; + } + }); + this.createDOM(); + this.styleSheet = createStyleSheet('crystools-monitors-size'); + } +} diff --git a/ComfyUI-Crystools/web/monitorUI.ts b/ComfyUI-Crystools/web/monitorUI.ts new file mode 100644 index 0000000000000000000000000000000000000000..68ceae943a2304c062bdd2352f70614c8731f040 --- /dev/null +++ b/ComfyUI-Crystools/web/monitorUI.ts @@ -0,0 +1,250 @@ +import { ProgressBarUIBase } from './progressBarUIBase.js'; +import { createStyleSheet, formatBytes } from './utils.js'; + +export class MonitorUI extends ProgressBarUIBase { + lastMonitor = 1; // just for order on monitors section + styleSheet: HTMLStyleElement; + maxVRAMUsed: Record = {}; // Add this to track max VRAM per GPU + + constructor( + public override rootElement: HTMLElement, + private monitorCPUElement: TMonitorSettings, + private monitorRAMElement: TMonitorSettings, + private monitorHDDElement: TMonitorSettings, + private monitorGPUSettings: TMonitorSettings[], + private monitorVRAMSettings: TMonitorSettings[], + private monitorTemperatureSettings: TMonitorSettings[], + private currentRate: number, + ) { + super('crystools-monitors-root', rootElement); + this.createDOM(); + + this.styleSheet = createStyleSheet('crystools-monitors-size'); + } + + createDOM = (): void => { + if (!this.rootElement) { + throw Error('Crystools: MonitorUI - Container not found'); + } + + // this.container.style.order = '2'; + this.rootElement.appendChild(this.createMonitor(this.monitorCPUElement)); + this.rootElement.appendChild(this.createMonitor(this.monitorRAMElement)); + this.rootElement.appendChild(this.createMonitor(this.monitorHDDElement)); + this.updateAllAnimationDuration(this.currentRate); + }; + + createDOMGPUMonitor = (monitorSettings?: TMonitorSettings): void => { + if (!(monitorSettings && this.rootElement)) { + return; + } + + this.rootElement.appendChild(this.createMonitor(monitorSettings)); + this.updateAllAnimationDuration(this.currentRate); + }; + + orderMonitors = (): void => { + try { + // @ts-ignore + this.monitorCPUElement.htmlMonitorRef.style.order = '' + this.lastMonitor++; + // @ts-ignore + this.monitorRAMElement.htmlMonitorRef.style.order = '' + this.lastMonitor++; + // @ts-ignore + this.monitorGPUSettings.forEach((_monitorSettings, index) => { + // @ts-ignore + this.monitorGPUSettings[index].htmlMonitorRef.style.order = '' + this.lastMonitor++; + // @ts-ignore + this.monitorVRAMSettings[index].htmlMonitorRef.style.order = '' + this.lastMonitor++; + // @ts-ignore + this.monitorTemperatureSettings[index].htmlMonitorRef.style.order = '' + this.lastMonitor++; + }); + // @ts-ignore + this.monitorHDDElement.htmlMonitorRef.style.order = '' + this.lastMonitor++; + } catch (error) { + console.error('orderMonitors', error); + } + }; + + updateDisplay = (data: TStatsData): void => { + this.updateMonitor(this.monitorCPUElement, data.cpu_utilization); + this.updateMonitor(this.monitorRAMElement, data.ram_used_percent, data.ram_used, data.ram_total); + this.updateMonitor(this.monitorHDDElement, data.hdd_used_percent, data.hdd_used, data.hdd_total); + + if (data.gpus === undefined || data.gpus.length === 0) { + console.warn('UpdateAllMonitors: no GPU data'); + return; + } + + this.monitorGPUSettings.forEach((monitorSettings, index) => { + if (data.gpus[index]) { + const gpu = data.gpus[index]; + if (gpu === undefined) { + // console.error('UpdateAllMonitors: no GPU data for index', index); + return; + } + + this.updateMonitor(monitorSettings, gpu.gpu_utilization); + } else { + // console.error('UpdateAllMonitors: no GPU data for index', index); + } + }); + + this.monitorVRAMSettings.forEach((monitorSettings, index) => { + if (data.gpus[index]) { + const gpu = data.gpus[index]; + if (gpu === undefined) { + // console.error('UpdateAllMonitors: no GPU VRAM data for index', index); + return; + } + + this.updateMonitor(monitorSettings, gpu.vram_used_percent, gpu.vram_used, gpu.vram_total); + } else { + // console.error('UpdateAllMonitors: no GPU VRAM data for index', index); + } + }); + + this.monitorTemperatureSettings.forEach((monitorSettings, index) => { + if (data.gpus[index]) { + const gpu = data.gpus[index]; + if (gpu === undefined) { + // console.error('UpdateAllMonitors: no GPU VRAM data for index', index); + return; + } + + this.updateMonitor(monitorSettings, gpu.gpu_temperature); + if (monitorSettings.cssColorFinal && monitorSettings.htmlMonitorSliderRef) { + monitorSettings.htmlMonitorSliderRef.style.backgroundColor = + `color-mix(in srgb, ${monitorSettings.cssColorFinal} ${gpu.gpu_temperature}%, ${monitorSettings.cssColor})`; + } + } else { + // console.error('UpdateAllMonitors: no GPU VRAM data for index', index); + } + }); + }; + + // eslint-disable-next-line complexity + updateMonitor = (monitorSettings: TMonitorSettings, percent: number, used?: number, total?: number): void => { + if (!(monitorSettings.htmlMonitorSliderRef && monitorSettings.htmlMonitorLabelRef)) { + return; + } + + if (percent < 0) { + return; + } + + const prefix = monitorSettings.monitorTitle ? monitorSettings.monitorTitle + ' - ' : ''; + let title = `${Math.floor(percent)}${monitorSettings.symbol}`; + let postfix = ''; + + // Add max VRAM tracking for VRAM monitors + if (used !== undefined && total !== undefined) { + // Extract GPU index from monitorTitle (assuming format "X: GPU Name") + const gpuIndex = parseInt(monitorSettings.monitorTitle?.split(':')[0] || '0'); + + // Initialize max VRAM if not set or glitch + if (!this.maxVRAMUsed[gpuIndex] || this.maxVRAMUsed[gpuIndex]! > total) { + this.maxVRAMUsed[gpuIndex] = 0; + } + + // Update max VRAM if current usage is higher + if ( used > this.maxVRAMUsed[gpuIndex]!) { + this.maxVRAMUsed[gpuIndex] = used; + } + + postfix = ` - ${formatBytes(used)} / ${formatBytes(total)}`; + // Add max VRAM to tooltip + postfix += ` Max: ${formatBytes(this.maxVRAMUsed[gpuIndex]!)}`; + } + + title = `${prefix}${title}${postfix}`; + + if (monitorSettings.htmlMonitorRef) { + monitorSettings.htmlMonitorRef.title = title; + } + monitorSettings.htmlMonitorLabelRef.innerHTML = `${Math.floor(percent)}${monitorSettings.symbol}`; + monitorSettings.htmlMonitorSliderRef.style.width = `${Math.floor(percent)}%`; + }; + + updateAllAnimationDuration = (value: number): void => { + this.updatedAnimationDuration(this.monitorCPUElement, value); + this.updatedAnimationDuration(this.monitorRAMElement, value); + this.updatedAnimationDuration(this.monitorHDDElement, value); + this.monitorGPUSettings.forEach((monitorSettings) => { + monitorSettings && this.updatedAnimationDuration(monitorSettings, value); + }); + this.monitorVRAMSettings.forEach((monitorSettings) => { + monitorSettings && this.updatedAnimationDuration(monitorSettings, value); + }); + this.monitorTemperatureSettings.forEach((monitorSettings) => { + monitorSettings && this.updatedAnimationDuration(monitorSettings, value); + }); + }; + + updatedAnimationDuration = (monitorSettings: TMonitorSettings, value: number): void => { + const slider = monitorSettings.htmlMonitorSliderRef; + if (!slider) { + return; + } + + slider.style.transition = `width ${value.toFixed(1)}s`; + }; + + createMonitor = (monitorSettings?: TMonitorSettings): HTMLDivElement => { + if (!monitorSettings) { + // just for typescript + return document.createElement('div'); + } + + const htmlMain = document.createElement('div'); + htmlMain.classList.add(monitorSettings.id); + htmlMain.classList.add('crystools-monitor'); + + monitorSettings.htmlMonitorRef = htmlMain; + + if (monitorSettings.title) { + htmlMain.title = monitorSettings.title; + } + + const htmlMonitorText = document.createElement('div'); + htmlMonitorText.classList.add('crystools-text'); + htmlMonitorText.innerHTML = monitorSettings.label; + htmlMain.append(htmlMonitorText); + + const htmlMonitorContent = document.createElement('div'); + htmlMonitorContent.classList.add('crystools-content'); + htmlMain.append(htmlMonitorContent); + + const htmlMonitorSlider = document.createElement('div'); + htmlMonitorSlider.classList.add('crystools-slider'); + if (monitorSettings.cssColorFinal) { + htmlMonitorSlider.style.backgroundColor = + `color-mix(in srgb, ${monitorSettings.cssColorFinal} 0%, ${monitorSettings.cssColor})`; + } else { + htmlMonitorSlider.style.backgroundColor = monitorSettings.cssColor; + } + monitorSettings.htmlMonitorSliderRef = htmlMonitorSlider; + htmlMonitorContent.append(htmlMonitorSlider); + + const htmlMonitorLabel = document.createElement('div'); + htmlMonitorLabel.classList.add('crystools-label'); + monitorSettings.htmlMonitorLabelRef = htmlMonitorLabel; + htmlMonitorContent.append(htmlMonitorLabel); + htmlMonitorLabel.innerHTML = '0%'; + return monitorSettings.htmlMonitorRef; + }; + + updateMonitorSize = (width: number, height: number): void => { + // eslint-disable-next-line max-len + this.styleSheet.innerText = `#crystools-monitors-root .crystools-monitor .crystools-content {height: ${height}px; width: ${width}px;}`; + }; + + showMonitor = (monitorSettings: TMonitorSettings, value: boolean): void => { + if (monitorSettings.htmlMonitorRef) { + monitorSettings.htmlMonitorRef.style.display = value ? 'flex' : 'none'; + } + }; + + resetMaxVRAM = (): void => { + this.maxVRAMUsed = {}; + }; +} diff --git a/ComfyUI-Crystools/web/progressBar.d.ts b/ComfyUI-Crystools/web/progressBar.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..509db1866f4b5fbb3046d4c04b51ccb638e79c80 --- /dev/null +++ b/ComfyUI-Crystools/web/progressBar.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/ComfyUI-Crystools/web/progressBar.js b/ComfyUI-Crystools/web/progressBar.js new file mode 100644 index 0000000000000000000000000000000000000000..5948d9a27fae1870a6cd2b2c113fc731e73becf8 --- /dev/null +++ b/ComfyUI-Crystools/web/progressBar.js @@ -0,0 +1,187 @@ +import { app, api } from './comfy/index.js'; +import { commonPrefix } from './common.js'; +import { ProgressBarUI } from './progressBarUI.js'; +import { ComfyKeyMenuDisplayOption, EStatus, MenuDisplayOptions } from './progressBarUIBase.js'; +class CrystoolsProgressBar { + constructor() { + Object.defineProperty(this, "idExtensionName", { + enumerable: true, + configurable: true, + writable: true, + value: 'Crystools.progressBar' + }); + Object.defineProperty(this, "idShowProgressBar", { + enumerable: true, + configurable: true, + writable: true, + value: 'Crystools.ProgressBar' + }); + Object.defineProperty(this, "defaultShowStatus", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "menuPrefix", { + enumerable: true, + configurable: true, + writable: true, + value: commonPrefix + }); + Object.defineProperty(this, "menuDisplayOption", { + enumerable: true, + configurable: true, + writable: true, + value: MenuDisplayOptions.Disabled + }); + Object.defineProperty(this, "currentStatus", { + enumerable: true, + configurable: true, + writable: true, + value: EStatus.executed + }); + Object.defineProperty(this, "currentProgress", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + Object.defineProperty(this, "currentNode", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "timeStart", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + Object.defineProperty(this, "progressBarUI", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "createSettings", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + app.ui.settings.addSetting({ + id: this.idShowProgressBar, + name: 'Show progress bar', + category: ['Crystools', this.menuPrefix + ' Progress Bar', 'Show'], + tooltip: 'This apply only on "Disabled" (old) menu', + type: 'boolean', + defaultValue: this.defaultShowStatus, + onChange: this.progressBarUI.showProgressBar, + }); + } + }); + Object.defineProperty(this, "updateDisplay", { + enumerable: true, + configurable: true, + writable: true, + value: (menuDisplayOption) => { + if (menuDisplayOption !== this.menuDisplayOption) { + this.menuDisplayOption = menuDisplayOption; + this.progressBarUI.showSection(this.menuDisplayOption === MenuDisplayOptions.Disabled); + } + if (this.menuDisplayOption === MenuDisplayOptions.Disabled && this.progressBarUI.showProgressBarFlag) { + this.progressBarUI.updateDisplay(this.currentStatus, this.timeStart, this.currentProgress); + } + } + }); + Object.defineProperty(this, "setup", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + if (this.progressBarUI) { + this.progressBarUI + .showProgressBar(app.extensionManager.setting.get(this.idShowProgressBar)); + return; + } + this.menuDisplayOption = app.extensionManager.setting.get(ComfyKeyMenuDisplayOption); + app.ui.settings.addEventListener(`${ComfyKeyMenuDisplayOption}.change`, (e) => { + this.updateDisplay(e.detail.value); + }); + const progressBarElement = document.createElement('div'); + progressBarElement.classList.add('crystools-monitors-container'); + this.progressBarUI = new ProgressBarUI(progressBarElement, (this.menuDisplayOption === MenuDisplayOptions.Disabled), this.centerNode); + const parentElement = document.getElementById('queue-button'); + if (parentElement) { + parentElement.insertAdjacentElement('afterend', progressBarElement); + } + else { + console.error('Crystools: parentElement to move monitors not found!', parentElement); + } + this.createSettings(); + this.updateDisplay(this.menuDisplayOption); + this.registerListeners(); + } + }); + Object.defineProperty(this, "registerListeners", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + api.addEventListener('status', ({ detail }) => { + this.currentStatus = this.currentStatus === EStatus.execution_error ? EStatus.execution_error : EStatus.executed; + const queueRemaining = detail?.exec_info.queue_remaining; + if (queueRemaining) { + this.currentStatus = EStatus.executing; + } + this.updateDisplay(this.menuDisplayOption); + }, false); + api.addEventListener('progress', ({ detail }) => { + const { value, max, node } = detail; + const progress = Math.floor((value / max) * 100); + if (!isNaN(progress) && progress >= 0 && progress <= 100) { + this.currentProgress = progress; + this.currentNode = node; + } + this.updateDisplay(this.menuDisplayOption); + }, false); + api.addEventListener('executed', ({ detail }) => { + if (detail?.node) { + this.currentNode = detail.node; + } + this.updateDisplay(this.menuDisplayOption); + }, false); + api.addEventListener('execution_start', ({ _detail }) => { + this.currentStatus = EStatus.executing; + this.timeStart = Date.now(); + this.updateDisplay(this.menuDisplayOption); + }, false); + api.addEventListener('execution_error', ({ _detail }) => { + this.currentStatus = EStatus.execution_error; + this.updateDisplay(this.menuDisplayOption); + }, false); + } + }); + Object.defineProperty(this, "centerNode", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + const id = this.currentNode; + if (!id) { + return; + } + const node = app.graph.getNodeById(id); + if (!node) { + return; + } + app.canvas.centerOnNode(node); + } + }); + } +} +const crystoolsProgressBar = new CrystoolsProgressBar(); +app.registerExtension({ + name: crystoolsProgressBar.idExtensionName, + setup: crystoolsProgressBar.setup, +}); diff --git a/ComfyUI-Crystools/web/progressBar.ts b/ComfyUI-Crystools/web/progressBar.ts new file mode 100644 index 0000000000000000000000000000000000000000..20d212fc7681532c3b660cc3b8cc67e0dd5996b7 --- /dev/null +++ b/ComfyUI-Crystools/web/progressBar.ts @@ -0,0 +1,140 @@ +import { app, api } from './comfy/index.js'; +import { commonPrefix } from './common.js'; +import { ProgressBarUI } from './progressBarUI.js'; +import { ComfyKeyMenuDisplayOption, EStatus, MenuDisplayOptions } from './progressBarUIBase.js'; + +class CrystoolsProgressBar { + idExtensionName = 'Crystools.progressBar'; + idShowProgressBar = 'Crystools.ProgressBar'; + defaultShowStatus = true; + menuPrefix = commonPrefix; + menuDisplayOption: MenuDisplayOptions = MenuDisplayOptions.Disabled; + + currentStatus = EStatus.executed; + currentProgress = 0; + currentNode?: number = undefined; + timeStart = 0; + + progressBarUI: ProgressBarUI; + + // not on setup because this affect the order on settings, I prefer to options at first + createSettings = (): void => { + app.ui.settings.addSetting({ + id: this.idShowProgressBar, + name: 'Show progress bar', + category: ['Crystools', this.menuPrefix + ' Progress Bar', 'Show'], + tooltip: 'This apply only on "Disabled" (old) menu', + type: 'boolean', + defaultValue: this.defaultShowStatus, + onChange: this.progressBarUI.showProgressBar, + }); + }; + + updateDisplay = (menuDisplayOption: MenuDisplayOptions): void => { + if (menuDisplayOption !== this.menuDisplayOption) { + this.menuDisplayOption = menuDisplayOption; + this.progressBarUI.showSection(this.menuDisplayOption === MenuDisplayOptions.Disabled); + } + if (this.menuDisplayOption === MenuDisplayOptions.Disabled && this.progressBarUI.showProgressBarFlag) { + this.progressBarUI.updateDisplay(this.currentStatus, this.timeStart, this.currentProgress); + } + }; + + // automatically called by ComfyUI + setup = (): void => { + if (this.progressBarUI) { + this.progressBarUI + .showProgressBar(app.extensionManager.setting.get(this.idShowProgressBar)); + return; + } + + this.menuDisplayOption = app.extensionManager.setting.get(ComfyKeyMenuDisplayOption); + app.ui.settings.addEventListener(`${ComfyKeyMenuDisplayOption}.change`, (e: any) => { + this.updateDisplay(e.detail.value); + }, + ); + + const progressBarElement = document.createElement('div'); + progressBarElement.classList.add('crystools-monitors-container'); + + this.progressBarUI = new ProgressBarUI( + progressBarElement, + (this.menuDisplayOption === MenuDisplayOptions.Disabled), + this.centerNode, + ); + + const parentElement = document.getElementById('queue-button'); + if (parentElement) { + parentElement.insertAdjacentElement('afterend', progressBarElement); + } else { + console.error('Crystools: parentElement to move monitors not found!', parentElement); + } + + this.createSettings(); + this.updateDisplay(this.menuDisplayOption); + this.registerListeners(); + }; + + registerListeners = (): void => { + api.addEventListener('status', ({detail}: any) => { + this.currentStatus = this.currentStatus === EStatus.execution_error ? EStatus.execution_error : EStatus.executed; + const queueRemaining = detail?.exec_info.queue_remaining; + + if (queueRemaining) { + this.currentStatus = EStatus.executing; + } + this.updateDisplay(this.menuDisplayOption); + }, false); + + api.addEventListener('progress', ({detail}: any) => { + const {value, max, node} = detail; + const progress = Math.floor((value / max) * 100); + + if (!isNaN(progress) && progress >= 0 && progress <= 100) { + this.currentProgress = progress; + this.currentNode = node; + } + + this.updateDisplay(this.menuDisplayOption); + }, false); + + api.addEventListener('executed', ({detail}: any) => { + if (detail?.node) { + this.currentNode = detail.node; + } + + this.updateDisplay(this.menuDisplayOption); + }, false); + + api.addEventListener('execution_start', ({_detail}: any) => { + this.currentStatus = EStatus.executing; + this.timeStart = Date.now(); + + this.updateDisplay(this.menuDisplayOption); + }, false); + + api.addEventListener('execution_error', ({_detail}: any) => { + this.currentStatus = EStatus.execution_error; + + this.updateDisplay(this.menuDisplayOption); + }, false); + }; + + centerNode = (): void => { + const id = this.currentNode; + if (!id) { + return; + } + const node = app.graph.getNodeById(id); + if (!node) { + return; + } + app.canvas.centerOnNode(node); + }; +} + +const crystoolsProgressBar = new CrystoolsProgressBar(); +app.registerExtension({ + name: crystoolsProgressBar.idExtensionName, + setup: crystoolsProgressBar.setup, +}); diff --git a/ComfyUI-Crystools/web/progressBarUI.d.ts b/ComfyUI-Crystools/web/progressBarUI.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..284eb20556ec3eab5822ded4fadaed9210f68752 --- /dev/null +++ b/ComfyUI-Crystools/web/progressBarUI.d.ts @@ -0,0 +1,18 @@ +import { EStatus, ProgressBarUIBase } from './progressBarUIBase.js'; +export declare class ProgressBarUI extends ProgressBarUIBase { + rootElement: HTMLElement; + showSectionFlag: boolean; + private centerNode; + htmlProgressSliderRef: HTMLDivElement; + htmlProgressLabelRef: HTMLDivElement; + currentStatus: EStatus; + timeStart: number; + currentProgress: number; + showProgressBarFlag: boolean; + constructor(rootElement: HTMLElement, showSectionFlag: boolean, centerNode: () => void); + createDOM: () => void; + updateDisplay: (currentStatus: EStatus, timeStart: number, currentProgress: number) => void; + showSection: (value: boolean) => void; + showProgressBar: (value: boolean) => void; + private displaySection; +} diff --git a/ComfyUI-Crystools/web/progressBarUI.js b/ComfyUI-Crystools/web/progressBarUI.js new file mode 100644 index 0000000000000000000000000000000000000000..f60fe6ac6ab0e10e77fa42605a9d61fd56c8113b --- /dev/null +++ b/ComfyUI-Crystools/web/progressBarUI.js @@ -0,0 +1,142 @@ +import { EStatus, ProgressBarUIBase } from './progressBarUIBase.js'; +export class ProgressBarUI extends ProgressBarUIBase { + constructor(rootElement, showSectionFlag, centerNode) { + super('crystools-progressBar-root', rootElement); + Object.defineProperty(this, "rootElement", { + enumerable: true, + configurable: true, + writable: true, + value: rootElement + }); + Object.defineProperty(this, "showSectionFlag", { + enumerable: true, + configurable: true, + writable: true, + value: showSectionFlag + }); + Object.defineProperty(this, "centerNode", { + enumerable: true, + configurable: true, + writable: true, + value: centerNode + }); + Object.defineProperty(this, "htmlProgressSliderRef", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "htmlProgressLabelRef", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "currentStatus", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "timeStart", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "currentProgress", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "showProgressBarFlag", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "createDOM", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + this.rootElement.setAttribute('title', 'click to see the current working node'); + this.rootElement.addEventListener('click', this.centerNode); + const progressBar = document.createElement('div'); + progressBar.classList.add('crystools-progress-bar'); + this.rootElement.append(progressBar); + const progressSlider = document.createElement('div'); + this.htmlProgressSliderRef = progressSlider; + progressSlider.classList.add('crystools-slider'); + progressBar.append(this.htmlProgressSliderRef); + const progressLabel = document.createElement('div'); + progressLabel.classList.add('crystools-label'); + progressLabel.innerHTML = '0%'; + this.htmlProgressLabelRef = progressLabel; + progressBar.append(this.htmlProgressLabelRef); + } + }); + Object.defineProperty(this, "updateDisplay", { + enumerable: true, + configurable: true, + writable: true, + value: (currentStatus, timeStart, currentProgress) => { + if (!(this.showSectionFlag && this.showProgressBarFlag)) { + return; + } + if (!(this.htmlProgressLabelRef && this.htmlProgressSliderRef)) { + console.error('htmlProgressLabelRef or htmlProgressSliderRef is undefined'); + return; + } + this.currentStatus = currentStatus; + this.timeStart = timeStart; + this.currentProgress = currentProgress; + if (currentStatus === EStatus.executed) { + this.htmlProgressLabelRef.innerHTML = 'cached'; + const timeElapsed = Date.now() - timeStart; + if (timeStart > 0 && timeElapsed > 0) { + this.htmlProgressLabelRef.innerHTML = new Date(timeElapsed).toISOString().substr(11, 8); + } + this.htmlProgressSliderRef.style.width = '0'; + } + else if (currentStatus === EStatus.execution_error) { + this.htmlProgressLabelRef.innerHTML = 'ERROR'; + this.htmlProgressSliderRef.style.backgroundColor = 'var(--error-text)'; + } + else if (currentStatus === EStatus.executing) { + this.htmlProgressLabelRef.innerHTML = `${currentProgress}%`; + this.htmlProgressSliderRef.style.width = this.htmlProgressLabelRef.innerHTML; + this.htmlProgressSliderRef.style.backgroundColor = 'green'; + } + } + }); + Object.defineProperty(this, "showSection", { + enumerable: true, + configurable: true, + writable: true, + value: (value) => { + this.showSectionFlag = value; + this.displaySection(); + } + }); + Object.defineProperty(this, "showProgressBar", { + enumerable: true, + configurable: true, + writable: true, + value: (value) => { + this.showProgressBarFlag = value; + this.displaySection(); + } + }); + Object.defineProperty(this, "displaySection", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + this.rootElement.style.display = (this.showSectionFlag && this.showProgressBarFlag) ? 'block' : 'none'; + } + }); + this.createDOM(); + } +} diff --git a/ComfyUI-Crystools/web/progressBarUI.ts b/ComfyUI-Crystools/web/progressBarUI.ts new file mode 100644 index 0000000000000000000000000000000000000000..46fc31060880b508f272056901db4b9430b8d0ce --- /dev/null +++ b/ComfyUI-Crystools/web/progressBarUI.ts @@ -0,0 +1,95 @@ +import { EStatus, ProgressBarUIBase } from './progressBarUIBase.js'; + +export class ProgressBarUI extends ProgressBarUIBase { + htmlProgressSliderRef: HTMLDivElement; + htmlProgressLabelRef: HTMLDivElement; + currentStatus: EStatus; + timeStart: number; + currentProgress: number; + showProgressBarFlag: boolean; + + constructor( + public override rootElement: HTMLElement, + public showSectionFlag: boolean, + private centerNode: () => void, + ) { + super('crystools-progressBar-root', rootElement); + this.createDOM(); + } + + createDOM = (): void => { + this.rootElement.setAttribute('title', 'click to see the current working node'); + this.rootElement.addEventListener('click', this.centerNode); + + const progressBar = document.createElement('div'); + progressBar.classList.add('crystools-progress-bar'); + this.rootElement.append(progressBar); + + const progressSlider = document.createElement('div'); + this.htmlProgressSliderRef = progressSlider; + progressSlider.classList.add('crystools-slider'); + progressBar.append(this.htmlProgressSliderRef); + + const progressLabel = document.createElement('div'); + progressLabel.classList.add('crystools-label'); + progressLabel.innerHTML = '0%'; + this.htmlProgressLabelRef = progressLabel; + progressBar.append(this.htmlProgressLabelRef); + }; + + // eslint-disable-next-line complexity + updateDisplay = (currentStatus: EStatus, timeStart: number, currentProgress: number): void => { + if (!(this.showSectionFlag && this.showProgressBarFlag)) { + return; + } + + if (!(this.htmlProgressLabelRef && this.htmlProgressSliderRef)) { + console.error('htmlProgressLabelRef or htmlProgressSliderRef is undefined'); + return; + } + + // console.log('only if showSection and progressBar', timeStart, currentProgress); + + this.currentStatus = currentStatus; + this.timeStart = timeStart; + this.currentProgress = currentProgress; + + if (currentStatus === EStatus.executed) { + // finished + this.htmlProgressLabelRef.innerHTML = 'cached'; + + const timeElapsed = Date.now() - timeStart; + if (timeStart > 0 && timeElapsed > 0) { + this.htmlProgressLabelRef.innerHTML = new Date(timeElapsed).toISOString().substr(11, 8); + } + this.htmlProgressSliderRef.style.width = '0'; + + } else if (currentStatus === EStatus.execution_error) { + // an error occurred + this.htmlProgressLabelRef.innerHTML = 'ERROR'; + this.htmlProgressSliderRef.style.backgroundColor = 'var(--error-text)'; + + } else if (currentStatus === EStatus.executing) { + // on going + this.htmlProgressLabelRef.innerHTML = `${currentProgress}%`; + this.htmlProgressSliderRef.style.width = this.htmlProgressLabelRef.innerHTML; + this.htmlProgressSliderRef.style.backgroundColor = 'green'; // by reset the color + } + + }; + + public showSection = (value: boolean): void => { + this.showSectionFlag = value; + this.displaySection(); + }; + + // remember it can't have more parameters because it is used on settings automatically + public showProgressBar = (value: boolean): void => { + this.showProgressBarFlag = value; + this.displaySection(); + }; + + private displaySection = (): void => { + this.rootElement.style.display = (this.showSectionFlag && this.showProgressBarFlag) ? 'block' : 'none'; + }; +} diff --git a/ComfyUI-Crystools/web/progressBarUIBase.d.ts b/ComfyUI-Crystools/web/progressBarUIBase.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..45a230fb6622c061c86b6e2c190fde3ca3742d8f --- /dev/null +++ b/ComfyUI-Crystools/web/progressBarUIBase.d.ts @@ -0,0 +1,18 @@ +export declare enum EStatus { + executing = "Executing", + executed = "Executed", + execution_error = "Execution error" +} +export declare const ComfyKeyMenuDisplayOption = "Comfy.UseNewMenu"; +export declare enum MenuDisplayOptions { + 'Disabled' = "Disabled", + 'Top' = "Top", + 'Bottom' = "Bottom" +} +export declare abstract class ProgressBarUIBase { + rootId: string; + rootElement: HTMLElement | null | undefined; + protected htmlClassMonitor: string; + protected constructor(rootId: string, rootElement: HTMLElement | null | undefined); + abstract createDOM(): void; +} diff --git a/ComfyUI-Crystools/web/progressBarUIBase.js b/ComfyUI-Crystools/web/progressBarUIBase.js new file mode 100644 index 0000000000000000000000000000000000000000..ab31bbac2f353daf23f0fb6d554e486fdabc7af6 --- /dev/null +++ b/ComfyUI-Crystools/web/progressBarUIBase.js @@ -0,0 +1,42 @@ +export var EStatus; +(function (EStatus) { + EStatus["executing"] = "Executing"; + EStatus["executed"] = "Executed"; + EStatus["execution_error"] = "Execution error"; +})(EStatus || (EStatus = {})); +export const ComfyKeyMenuDisplayOption = 'Comfy.UseNewMenu'; +export var MenuDisplayOptions; +(function (MenuDisplayOptions) { + MenuDisplayOptions["Disabled"] = "Disabled"; + MenuDisplayOptions["Top"] = "Top"; + MenuDisplayOptions["Bottom"] = "Bottom"; +})(MenuDisplayOptions || (MenuDisplayOptions = {})); +export class ProgressBarUIBase { + constructor(rootId, rootElement) { + Object.defineProperty(this, "rootId", { + enumerable: true, + configurable: true, + writable: true, + value: rootId + }); + Object.defineProperty(this, "rootElement", { + enumerable: true, + configurable: true, + writable: true, + value: rootElement + }); + Object.defineProperty(this, "htmlClassMonitor", { + enumerable: true, + configurable: true, + writable: true, + value: 'crystools-monitors-container' + }); + if (this.rootElement && this.rootElement.children.length === 0) { + this.rootElement.setAttribute('id', this.rootId); + this.rootElement.classList.add(this.htmlClassMonitor); + this.rootElement.classList.add(this.constructor.name); + } + else { + } + } +} diff --git a/ComfyUI-Crystools/web/progressBarUIBase.ts b/ComfyUI-Crystools/web/progressBarUIBase.ts new file mode 100644 index 0000000000000000000000000000000000000000..70f2befaec0cd30f9c509ba299ef489f95851683 --- /dev/null +++ b/ComfyUI-Crystools/web/progressBarUIBase.ts @@ -0,0 +1,32 @@ +export enum EStatus { + executing = 'Executing', + executed = 'Executed', + execution_error = 'Execution error', +} + +export const ComfyKeyMenuDisplayOption = 'Comfy.UseNewMenu'; +export enum MenuDisplayOptions { + 'Disabled' = 'Disabled', + 'Top' = 'Top', + 'Bottom' = 'Bottom', +} + +export abstract class ProgressBarUIBase { + protected htmlClassMonitor = 'crystools-monitors-container'; + + protected constructor( + public rootId: string, + public rootElement: HTMLElement | null | undefined, + ) { + // IMPORTANT duplicate on crystools-save + if (this.rootElement && this.rootElement.children.length === 0) { + this.rootElement.setAttribute('id', this.rootId); + this.rootElement.classList.add(this.htmlClassMonitor); + this.rootElement.classList.add(this.constructor.name); + } else { + // it was created before + } + } + + abstract createDOM(): void; +} diff --git a/ComfyUI-Crystools/web/styles.d.ts b/ComfyUI-Crystools/web/styles.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3b7a634539640f61650758532c81211dbca3a34a --- /dev/null +++ b/ComfyUI-Crystools/web/styles.d.ts @@ -0,0 +1,12 @@ +export declare enum Styles { + 'BARS' = "BARS" +} +export declare enum Colors { + 'CPU' = "#0AA015", + 'RAM' = "#07630D", + 'DISK' = "#730F92", + 'GPU' = "#0C86F4", + 'VRAM' = "#176EC7", + 'TEMP_START' = "#00ff00", + 'TEMP_END' = "#ff0000" +} diff --git a/ComfyUI-Crystools/web/styles.js b/ComfyUI-Crystools/web/styles.js new file mode 100644 index 0000000000000000000000000000000000000000..24c3cbac8aaa46540fb438c5e325dc46aeb7317d --- /dev/null +++ b/ComfyUI-Crystools/web/styles.js @@ -0,0 +1,16 @@ +import { utils } from './comfy/index.js'; +utils.addStylesheet('extensions/ComfyUI-Crystools/monitor.css'); +export var Styles; +(function (Styles) { + Styles["BARS"] = "BARS"; +})(Styles || (Styles = {})); +export var Colors; +(function (Colors) { + Colors["CPU"] = "#0AA015"; + Colors["RAM"] = "#07630D"; + Colors["DISK"] = "#730F92"; + Colors["GPU"] = "#0C86F4"; + Colors["VRAM"] = "#176EC7"; + Colors["TEMP_START"] = "#00ff00"; + Colors["TEMP_END"] = "#ff0000"; +})(Colors || (Colors = {})); diff --git a/ComfyUI-Crystools/web/styles.ts b/ComfyUI-Crystools/web/styles.ts new file mode 100644 index 0000000000000000000000000000000000000000..e10d4d088d5e65e14535e59207dcc058277d27c7 --- /dev/null +++ b/ComfyUI-Crystools/web/styles.ts @@ -0,0 +1,17 @@ +import { utils } from './comfy/index.js'; + +utils.addStylesheet('extensions/ComfyUI-Crystools/monitor.css'); + +export enum Styles { + 'BARS' = 'BARS' +} + +export enum Colors { + 'CPU' = '#0AA015', + 'RAM' = '#07630D', + 'DISK' = '#730F92', + 'GPU' = '#0C86F4', + 'VRAM' = '#176EC7', + 'TEMP_START' = '#00ff00', + 'TEMP_END' = '#ff0000', +} diff --git a/ComfyUI-Crystools/web/types.d.ts b/ComfyUI-Crystools/web/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c1d9e93192056f79cd11990a7575d79c5cb1f767 --- /dev/null +++ b/ComfyUI-Crystools/web/types.d.ts @@ -0,0 +1,61 @@ + +type TGpuStatData = { + gpu_utilization: number, + gpu_temperature: number, + vram_total: number, + vram_used: number, + vram_used_percent: number, +} + +type TGpuSettings = { + utilization?: boolean, + vram?: boolean, + temperature?: boolean, +} + +type TGpuName = { + name: string, + index: number, +} + +type TStatsData = { + cpu_utilization: number, + device: string, + gpus: TGpuStatData[], + hdd_total: number, + hdd_used: number, + hdd_used_percent: number, + ram_total: number, + ram_used: number, + ram_used_percent: number, +} + +type TStatsSettings = { + rate?: number, + switchCPU?: boolean, + switchGPU?: boolean, + switchHDD?: boolean, + switchRAM?: boolean, + switchVRAM?: boolean, + whichHDD?: string, +} + +type TMonitorSettings = { + id: string, + name: string, + category: string[], // for settings location + label: string, // on monitor + symbol: string, // on monitor + monitorTitle?: string, // on monitor + title?: string, // on monitor + tooltip?: string, // on settings + type: 'boolean' | 'number' | 'string' | 'slider' | 'combo', + defaultValue: boolean | number | string, + data?: any, + onChange: (value: boolean | number | string) => Promise, + htmlMonitorRef?: HTMLDivElement, + htmlMonitorSliderRef?: HTMLDivElement, + htmlMonitorLabelRef?: HTMLDivElement, + cssColor: string, + cssColorFinal?: string, +} diff --git a/ComfyUI-Crystools/web/utils.d.ts b/ComfyUI-Crystools/web/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fea4ae761c79f8dbf706c38315ac56c4f8cff77d --- /dev/null +++ b/ComfyUI-Crystools/web/utils.d.ts @@ -0,0 +1,5 @@ +export declare function numberToWords(num: number): string; +export declare function toPascalCase(strings: string[]): string; +export declare function convertNumberToPascalCase(num: number): string; +export declare function formatBytes(bytes: number): string; +export declare function createStyleSheet(id: string): HTMLStyleElement; diff --git a/ComfyUI-Crystools/web/utils.js b/ComfyUI-Crystools/web/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..4ccefc388de95ad9c61e23a6ae744b8a48c902bc --- /dev/null +++ b/ComfyUI-Crystools/web/utils.js @@ -0,0 +1,56 @@ +export function numberToWords(num) { + if (num === 0) + return 'zero'; + const belowTwenty = [ + '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', + 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' + ]; + const tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']; + const thousands = ['', 'thousand', 'million', 'billion']; + function helper(n) { + if (n === 0) + return ''; + else if (n < 20) + return belowTwenty[n] + ' '; + else if (n < 100) + return tens[Math.floor(n / 10)] + ' ' + helper(n % 10); + return belowTwenty[Math.floor(n / 100)] + ' hundred ' + helper(n % 100); + } + let word = ''; + let i = 0; + while (num > 0) { + if (num % 1000 !== 0) { + word = helper(num % 1000) + thousands[i] + ' ' + word; + } + num = Math.floor(num / 1000); + i++; + } + return word.trim(); +} +export function toPascalCase(strings) { + if (!Array.isArray(strings)) + return ''; + function capitalize(word) { + return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); + } + return strings.map(capitalize).join(''); +} +export function convertNumberToPascalCase(num) { + return toPascalCase(numberToWords(num).split(' ')); +} +export function formatBytes(bytes) { + if (bytes === 0) + return '0 Bytes'; + const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; + const i = Math.floor(Math.log(bytes) / Math.log(1024)); + const formattedSize = (bytes / Math.pow(1024, i)).toFixed(2); + return `${formattedSize} ${sizes[i]}`; +} +export function createStyleSheet(id) { + const style = document.createElement('style'); + style.setAttribute('id', id); + style.setAttribute('rel', 'stylesheet'); + style.setAttribute('type', 'text/css'); + document.head.appendChild(style); + return style; +} diff --git a/ComfyUI-Crystools/web/utils.ts b/ComfyUI-Crystools/web/utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..7b2bf23e55b1c31a76e4acee7550182fb51fa95b --- /dev/null +++ b/ComfyUI-Crystools/web/utils.ts @@ -0,0 +1,64 @@ +export function numberToWords(num: number): string { + if (num === 0) return 'zero'; + + const belowTwenty = [ + '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', + 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' + ]; + const tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']; + const thousands = ['', 'thousand', 'million', 'billion']; + + function helper(n: number): string { + if (n === 0) return ''; + else if (n < 20) return belowTwenty[n] + ' '; + else if (n < 100) return tens[Math.floor(n / 10)] + ' ' + helper(n % 10); + return belowTwenty[Math.floor(n / 100)] + ' hundred ' + helper(n % 100); + } + + let word = ''; + let i = 0; + + while (num > 0) { + if (num % 1000 !== 0) { + word = helper(num % 1000) + thousands[i] + ' ' + word; + } + num = Math.floor(num / 1000); + i++; + } + + return word.trim(); +} + +export function toPascalCase(strings: string[]): string { + if (!Array.isArray(strings)) return ''; + + function capitalize(word: string): string { + return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); + } + + return strings.map(capitalize).join(''); +} + + +export function convertNumberToPascalCase(num: number): string { + return toPascalCase(numberToWords(num).split(' ')); +} + +export function formatBytes(bytes: number): string { + if (bytes === 0) return '0 Bytes'; + + const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; + const i = Math.floor(Math.log(bytes) / Math.log(1024)); + const formattedSize = (bytes / Math.pow(1024, i)).toFixed(2); + + return `${formattedSize} ${sizes[i]}`; +} + +export function createStyleSheet(id: string): HTMLStyleElement { + const style = document.createElement('style'); + style.setAttribute('id', id); + style.setAttribute('rel', 'stylesheet'); + style.setAttribute('type', 'text/css'); + document.head.appendChild(style); + return style; +} diff --git a/ComfyUI-Dimensional-Latent-Perlin/LICENSE b/ComfyUI-Dimensional-Latent-Perlin/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9f36fe0635a475187c56048650d9034b91b7b818 --- /dev/null +++ b/ComfyUI-Dimensional-Latent-Perlin/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 NeuralSamurAI + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/ComfyUI-Dimensional-Latent-Perlin/README.md b/ComfyUI-Dimensional-Latent-Perlin/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c6b6eb3c940867fd1a06bae3adfa2321e100efba --- /dev/null +++ b/ComfyUI-Dimensional-Latent-Perlin/README.md @@ -0,0 +1,69 @@ +# Dimensional Latent Perlin for ComfyUI + +![Node](https://github.com/NeuralSamurAI/ComfyUI-Dimensional-Latent-Perlin/blob/main/assets/Node.png) + +## Description + +Dimensional Latent Perlin is a custom node for ComfyUI that generates Perlin noise in the latent space. This node is designed to work seamlessly with various diffusion models and can be used as an alternative or complement to standard random noise generators in image generation pipelines. + +## Features + +- Generate Perlin noise that matches the latent space of diffusion models +- Adjustable parameters for fine-tuning the noise generation +- Compatible with different model architectures and latent space dimensions +- Can adapt to existing latent images or model specifications +- Supports batch processing + +## Installation + +1. Clone this repository into your ComfyUI custom nodes directory via ComfyUI Manager or: + +```git clone https://github.com/neuralsamurai/ComfyUI-Dimensional-Latent-Perlin.git``` + +2. Restart ComfyUI or reload custom nodes. + +## Usage + +After installation, the Dimensional Latent Perlin node will be available in the ComfyUI interface under the "latent/noise" category. + +### Input Parameters + +- `seed`: Seed for random number generation (for reproducibility) +- `width`: Width of the output image +- `height`: Height of the output image +- `batch_size`: Number of images to generate in a batch +- `detail_level`: Controls the level of detail in the Perlin noise +- `downsample_factor`: Downsampling factor for the latent space + +### Optional Inputs + +- `latent_image`: An existing latent image to match dimensions +- `model`: A diffusion model to match latent space specifications + +### Output + +- `LATENT`: A latent representation of the generated Perlin noise + +## Examples + +Workflow available in the asset directory + +## Contributing + +Contributions are welcome! Please feel free to submit a Pull Request. + +## License + +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. + +## Credits + +This node was inspired by and based on the work of Extraltodeus: +- Original Author: [Extraltodeus](https://github.com/Extraltodeus) +- Original Repository: [noise_latent_perlinpinpin](https://github.com/Extraltodeus/noise_latent_perlinpinpin) + +## Acknowledgements + +- Special thanks to Extraltodeus for the original implementation that inspired this node. +- This node builds upon the concept of controllable noise generation in latent diffusion models. +- Thanks to the Image Diffusion, AI Twitter, ComfyUI & Banodoco communities for their support and inspiration. diff --git a/ComfyUI-Dimensional-Latent-Perlin/__init__.py b/ComfyUI-Dimensional-Latent-Perlin/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..55c38769f5669726d4c399ef264d4ef1b95a9ee6 --- /dev/null +++ b/ComfyUI-Dimensional-Latent-Perlin/__init__.py @@ -0,0 +1,11 @@ +from .dimensional_latent_perlin import NoisyLatentPerlinD + +NODE_CLASS_MAPPINGS = { + "NoisyLatentPerlinD": NoisyLatentPerlinD +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "NoisyLatentPerlinD": "Noisy Latent Perlin Dimensional" +} + +__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS'] \ No newline at end of file diff --git a/ComfyUI-Dimensional-Latent-Perlin/__pycache__/__init__.cpython-310.pyc b/ComfyUI-Dimensional-Latent-Perlin/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3c688016df9a354adff0605ddb30c6f86d3a57f Binary files /dev/null and b/ComfyUI-Dimensional-Latent-Perlin/__pycache__/__init__.cpython-310.pyc differ diff --git a/ComfyUI-Dimensional-Latent-Perlin/__pycache__/dimensional_latent_perlin.cpython-310.pyc b/ComfyUI-Dimensional-Latent-Perlin/__pycache__/dimensional_latent_perlin.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da5a0d280647088fda4f7c8606a3d387aa67690e Binary files /dev/null and b/ComfyUI-Dimensional-Latent-Perlin/__pycache__/dimensional_latent_perlin.cpython-310.pyc differ diff --git a/ComfyUI-Dimensional-Latent-Perlin/dimensional_latent_perlin.py b/ComfyUI-Dimensional-Latent-Perlin/dimensional_latent_perlin.py new file mode 100644 index 0000000000000000000000000000000000000000..f459a9cfcb52460231b9b5ee49c48340bdab5d2f --- /dev/null +++ b/ComfyUI-Dimensional-Latent-Perlin/dimensional_latent_perlin.py @@ -0,0 +1,102 @@ +""" +NoisyLatentPerlinD for ComfyUI + +This implementation is inspired by and based on the work of Extraltodeus: +https://github.com/Extraltodeus/noise_latent_perlinpinpin + +Modifications and enhancements have been made to adapt it for broader use cases. +""" +import torch +import math +import numpy as np +import comfy.utils + +class NoisyLatentPerlinD: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(s): + return {"required": { + "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}), + "width": ("INT", {"default": 1024, "min": 8, "max": 8192, "step": 8}), + "height": ("INT", {"default": 1024, "min": 8, "max": 8192, "step": 8}), + "batch_size": ("INT", {"default": 1, "min": 1, "max": 64}), + "detail_level": ("FLOAT", {"default": 0, "min": -1, "max": 1.0, "step": 0.1}), + "downsample_factor": ("INT", {"default": 8, "min": 1, "max": 64, "step": 1}), + }, + "optional": { + "latent_image": ("LATENT", ), + "model": ("MODEL", ), + }} + + RETURN_TYPES = ("LATENT",) + FUNCTION = "generate_noise" + CATEGORY = "latent/noise" + + def rand_perlin_2d(self, shape, res, fade = lambda t: 6*t**5 - 15*t**4 + 10*t**3): + delta = (res[0] / shape[0], res[1] / shape[1]) + d = (shape[0] // res[0], shape[1] // res[1]) + + grid = torch.stack(torch.meshgrid(torch.arange(0, res[0], delta[0]), torch.arange(0, res[1], delta[1])), dim = -1) % 1 + angles = 2*math.pi*torch.rand(res[0]+1, res[1]+1) + gradients = torch.stack((torch.cos(angles), torch.sin(angles)), dim = -1) + + tile_grads = lambda slice1, slice2: gradients[slice1[0]:slice1[1], slice2[0]:slice2[1]].repeat_interleave(d[0], 0).repeat_interleave(d[1], 1) + dot = lambda grad, shift: (torch.stack((grid[:shape[0],:shape[1],0] + shift[0], grid[:shape[0],:shape[1], 1] + shift[1] ), dim = -1) * grad[:shape[0], :shape[1]]).sum(dim = -1) + + n00 = dot(tile_grads([0, -1], [0, -1]), [0, 0]) + n10 = dot(tile_grads([1, None], [0, -1]), [-1, 0]) + n01 = dot(tile_grads([0, -1],[1, None]), [0, -1]) + n11 = dot(tile_grads([1, None], [1, None]), [-1,-1]) + t = fade(grid[:shape[0], :shape[1]]) + return math.sqrt(2) * torch.lerp(torch.lerp(n00, n10, t[..., 0]), torch.lerp(n01, n11, t[..., 0]), t[..., 1]) + + def rand_perlin_2d_octaves(self, shape, res, octaves=1, persistence=0.5): + noise = torch.zeros(shape) + frequency = 1 + amplitude = 1 + for _ in range(octaves): + noise += amplitude * self.rand_perlin_2d(shape, (frequency*res[0], frequency*res[1])) + frequency *= 2 + amplitude *= persistence + noise = torch.remainder(torch.abs(noise)*1000000,11)/11 + return noise + + def scale_tensor(self, x): + min_value = x.min() + max_value = x.max() + x = (x - min_value) / (max_value - min_value) + return x + + def generate_noise(self, seed, width, height, batch_size, detail_level, downsample_factor, latent_image=None, model=None): + torch.manual_seed(seed) + + # Determine the number of dimensions (channels) + if model is not None: + dimensions = model.get_model_object("latent_format").latent_channels + elif latent_image is not None: + dimensions = latent_image["samples"].shape[1] + else: + dimensions = 4 # Default to 4 if neither model nor latent_image is provided + + noise = torch.zeros((batch_size, dimensions, height // downsample_factor, width // downsample_factor), dtype=torch.float32, device="cpu") + + for i in range(batch_size): + for j in range(dimensions): + noise_values = self.rand_perlin_2d_octaves((height // downsample_factor, width // downsample_factor), (1,1), 1, 1) + result = (1+detail_level/10)*torch.erfinv(2 * noise_values - 1) * (2 ** 0.5) + result = torch.clamp(result,-5,5) + noise[i, j, :, :] = result + + # If a latent_image is provided, ensure the noise matches its shape + if latent_image is not None: + noise = self.fix_latent_shape(noise, latent_image["samples"]) + + return ({"samples": noise},) + + def fix_latent_shape(self, noise, latent_image): + if noise.shape != latent_image.shape: + noise = comfy.utils.repeat_to_batch_size(noise, latent_image.shape[1], dim=1) + noise = noise[:latent_image.shape[0], :, :latent_image.shape[2], :latent_image.shape[3]] + return noise \ No newline at end of file diff --git a/ComfyUI-DyPE/.github/workflows/publish.yml b/ComfyUI-DyPE/.github/workflows/publish.yml new file mode 100644 index 0000000000000000000000000000000000000000..50cc62b571840ba16e238e481a408db83054000e --- /dev/null +++ b/ComfyUI-DyPE/.github/workflows/publish.yml @@ -0,0 +1,28 @@ +name: Publish to Comfy registry +on: + workflow_dispatch: + push: + branches: + - main + - master + paths: + - "pyproject.toml" + +permissions: + issues: write + +jobs: + publish-node: + name: Publish Custom Node to registry + runs-on: ubuntu-latest + if: ${{ github.repository_owner == 'wildminder' }} + steps: + - name: Check out code + uses: actions/checkout@v4 + with: + submodules: true + - name: Publish Custom Node + uses: Comfy-Org/publish-node-action@v1 + with: + ## Add your own personal access token to your Github Repository secrets and reference it here. + personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }} diff --git a/ComfyUI-DyPE/.gitignore b/ComfyUI-DyPE/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..d2a4d9a53e59bc9f9fca8d74ae37f3cb8821d0b4 --- /dev/null +++ b/ComfyUI-DyPE/.gitignore @@ -0,0 +1,163 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.idea +.Python +__pycache__ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ +.rar + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ diff --git a/ComfyUI-DyPE/LICENSE b/ComfyUI-DyPE/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..29f81d812f3e768fa89638d1f72920dbfd1413a8 --- /dev/null +++ b/ComfyUI-DyPE/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/ComfyUI-DyPE/README.md b/ComfyUI-DyPE/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a7baec29fccc7d13d1ddb4204476a13ad910c089 --- /dev/null +++ b/ComfyUI-DyPE/README.md @@ -0,0 +1,229 @@ +
+

ComfyUI-DyPE

+ +ComfyUI-DyPE Banner + + +

+ A ComfyUI custom node that implements DyPE (Dynamic Position Extrapolation), enabling Diffusion Transformers (like FLUX, Qwen Image, and Z-Image) to generate ultra-high-resolution images (4K and beyond) with exceptional coherence and detail. +
+
+ Report Bug + · + Request Feature +

+
+ + +
+ +[![Stargazers][stars-shield]][stars-url] +[![Issues][issues-shield]][issues-url] +[![Forks][forks-shield]][forks-url] + +
+ +
+ +## About The Project + +DyPE is a training-free method that allows pre-trained DiT models to generate images at resolutions far beyond their training data, with no additional sampling cost. + +It works by taking advantage of the spectral progression inherent to the diffusion process. By dynamically adjusting the model's positional encodings at each step, DyPE matches their frequency spectrum with the current stage of the generative process—focusing on low-frequency structures early on and resolving high-frequency details in later steps. This prevents the repeating artifacts and structural degradation typically seen when pushing models beyond their native resolution. + +
+ + ComfyUI-DyPE example workflow +

A simple, single-node integration to patch your model for high-resolution generation.

+
+ + + +This node provides a seamless, "plug-and-play" integration of DyPE into your workflow. + +**✨ Key Features:** +* **Multi-Architecture Support:** Supports **FLUX** (Standard), **Nunchaku** (Quantized Flux), **Qwen Image**, and **Z-Image** (Lumina 2). +* **High-Resolution Generation:** Push models to 4096x4096 and beyond. +* **Single-Node Integration:** Simply place the `DyPE for FLUX` node after your model loader to patch the model. No complex workflow changes required. +* **Full Compatibility:** Works seamlessly with your existing ComfyUI workflows, samplers, schedulers, and other optimization nodes. +* **Fine-Grained Control:** Exposes key DyPE hyperparameters, allowing you to tune the algorithm's strength and behavior for optimal results at different target resolutions. +* **Zero Inference Overhead:** DyPE's adjustments happen on-the-fly with negligible performance impact. + +
+Node +
+ +## Example output + +
+Example dype +
+ +

(back to top)

+ +## Getting Started + +The easiest way to install is via **ComfyUI Manager**. Search for `ComfyUI-DyPE` and click "Install". + +Alternatively, to install manually: + +1. **Clone the Repository:** + + Navigate to your `ComfyUI/custom_nodes/` directory and clone this repository: + ```sh + git clone https://github.com/wildminder/ComfyUI-DyPE.git + ``` +2. **Start/Restart ComfyUI:** + Launch ComfyUI. No further dependency installation is required. + +

(back to top)

+ +## 🛠️ Usage + +Using the node is straightforward and designed for minimal workflow disruption. + +1. **Load Your Model:** Use your preferred loader (e.g., `Load Checkpoint` for Flux, `Nunchaku Flux DiT Loader`, or `ZImage` loader). +2. **Add the DyPE Node:** Add the `DyPE for FLUX` node to your graph (found under `model_patches/unet`). +3. **Connect the Model:** Connect the `MODEL` output from your loader to the `model` input of the DyPE node. +4. **Set Resolution:** Set the `width` and `height` on the DyPE node to match the resolution of your `Empty Latent Image`. +5. **Connect to KSampler:** Use the `MODEL` output from the DyPE node as the input for your `KSampler`. +6. **Generate!** That's it. Your workflow is now DyPE-enabled. + +> [!NOTE] +> This node specifically patches the **diffusion model (UNet)** positional embeddings. It does not modify the CLIP or VAE models. + +### Node Inputs + +#### 1. Model Configuration +* **`model_type`**: + * **`auto`**: Attempts to automatically detect the model architecture. Recommended. + * **`flux`**: Forces Standard Flux logic. + * **`nunchaku`**: Forces Nunchaku (Quantized Flux) logic. + * **`qwen`**: Forces Qwen Image logic. + * **`zimage`**: Forces Z-Image (Lumina 2) logic. +* **`base_resolution`**: The native resolution the model was trained on. + * Flux / Z-Image: `1024` + * Qwen: `1328` (Recommended setting for Qwen models) + +#### 2. Method Selection +* **`method`**: + * **`vision_yarn`:** A novel variant designed specifically for aspect-ratio robustness. It decouples structure from texture: low frequencies (shapes) are scaled to fit your canvas aspect ratio, while high frequencies (details) are scaled uniformly. It uses a dynamic attention schedule to ensure sharpness. + * **`yarn`:** The standard YaRN method. Good general performance but can struggle with extreme aspect ratios. + * **`ntk`:** Neural Tangent Kernel scaling. Very stable but tends to be softer/blurrier at high resolutions. + * **`base`:** No positional interpolation (standard behavior). + +##### Scaling Options +* **`yarn_alt_scaling`** (Only affects `yarn` method): + * **Anisotropic (High-Res):** Scales Height and Width independently. Can cause geometric stretching if the aspect ratio differs significantly from the training data. + * **Isotropic (Stable Default):** Scales both dimensions based on the largest axis. . + * *Note: `vision_yarn` automatically handles this balance internally, so this switch is ignored when `vision_yarn` is selected.* + +> [!TIP] +> **Z-Image (Lumina 2) Specifics:** +> * Z-Image models use a very low RoPE base frequency (`theta=256`). +> * **Geometric Stretching:** To prevent vertical stretching, the node automatically enforces **Isotropic Scaling** for Z-Image, regardless of user settings. +> * **Method Choice:** recommend **`vision_yarn`** or **`ntk`**. Standard `yarn` may produce artifacts. + +#### 3. Dynamic Control +* **`enable_dype`**: Enables or disables the **dynamic, time-aware** component of DyPE. + * **Enabled (True):** Both the noise schedule and RoPE will be dynamically adjusted throughout sampling. This is the full DyPE algorithm. + * **Disabled (False):** The node will only apply the dynamic noise schedule shift. The RoPE will use static extrapolation. +* **`dype_scale`**: (λs) Controls the "magnitude" of the DyPE modulation. Default is `2.0`. +* **`dype_exponent`**: (λt) Controls the "strength" of the dynamic effect over time. + * `2.0`: Recommended for **4K+** resolutions. Aggressive schedule that transitions quickly to clean up artifacts. + * `1.0`: Good starting point for **~2K-3K** resolutions. + * `0.5`: Gentler schedule for resolutions just above native. + +#### 4. Advanced Noise Scheduling +* **`base_shift` / `max_shift`**: These parameters control the Noise Schedule Shift (`mu`). In this implementation, `max_shift` (Default 1.15) acts as the target shift for any resolution larger than the base. + +

(back to top)

+ +## Changelog + +#### v2.3.0 +* **Z-Image Overhaul:** Fixed geometric stretching artifacts +* **Method Fixes** + +#### v2.2.0 +* **Z-Image Support:** Added experimental support for **Z-Image (Lumina 2)** architecture. + +#### v2.1.0 +* **New Architecture Support:** Added support for **Qwen Image** and **Nunchaku** (Quantized Flux) models. +* **Modular Architecture:** Refactored codebase into a modular adapter pattern (`src/models/`) to ensure stability and easier updates for future models. +* **UI Updates:** Added `model_type` selector for explicit model definition. + +#### v2.0.0 +* **Vision-YaRN:** Introduced the `vision_yarn` method for decoupled aspect-ratio handling. +* **Dynamic Attention:** Implemented quadratic decay schedule for `mscale` to balance sharpness and artifacts. +* **Start Sigma:** Added `dype_start_sigma` control. + +#### v1.0.0 +* **Initial Release:** Core DyPE implementation for Standard Flux models. +* **Basic Modes:** Support for `yarn` (Isotropic/Anisotropic) and `ntk`. + +

(back to top)

+ +## ❗ Important Notes & Best Practices + +> [!IMPORTANT] +> **Limitations at Extreme Resolutions (4K)** +> While DyPE significantly extends the capabilities of DiT models, generating perfectly clean 4096x4096 images is still a limitation of the base model itself. Even with DyPE, you are pushing a model trained on ~1 megapixel to generate 16 megapixels. You may still encounter minor artifacts at these extreme scales. + +> [!TIP] +> **Dealing with Speckle Noise** +> At extreme resolutions (4K+), you may notice high-frequency "speckle" noise in focused areas (e.g., hair, eyes). This is a side effect of scaling the model's attention mechanism beyond its training limits. +> +> **How to fix:** +> 1. **Increase `dype_exponent`:** Try raising this to `3.0` or `4.0` or any other higher values. +> 2. **Use LoRAs:** Smoothing or "Detailer" LoRAs can help suppress high-frequency artifacts. + +> [!TIP] +> **Experimentation is Required** +> There is no single "magic setting" that works for every prompt and every resolution. To achieve the best results: +> * **Test different Methods:** Start with `vision_yarn`, but try `yarn` if you encounter issues. +> * **Adjust `dype_exponent`:** This is your main knob for balancing sharpness vs. artifacts. + +

══════════════════════════════════

+ +Beyond the code, I believe in the power of community and continuous learning. I invite you to join the 'TokenDiff AI News' and 'TokenDiff Community Hub' + + + + + + +
+

TokenDiff AI News

+ + tokendiff-tg-qw + +

AI for every home, creativity for every mind!

+
+

TokenDiff Community Hub

+ + token_hub-tg-qr + +

questions, help, and thoughtful discussion.

+
+ +

══════════════════════════════════

+ +

(back to top)

+ + +## Acknowledgments + +* **Noam Issachar, Guy Yariv, and the co-authors** for their groundbreaking research and for open-sourcing the [DyPE](https://github.com/guyyariv/DyPE) project. +* **The ComfyUI team** for creating such a powerful and extensible platform for diffusion model research and creativity. + +

(back to top)

+ + + +[stars-shield]: https://img.shields.io/github/stars/wildminder/ComfyUI-DyPE.svg?style=for-the-badge +[stars-url]: https://github.com/wildminder/ComfyUI-DyPE/stargazers +[issues-shield]: https://img.shields.io/github/issues/wildminder/ComfyUI-DyPE.svg?style=for-the-badge +[issues-url]: https://github.com/wildminder/ComfyUI-DyPE/issues +[forks-shield]: https://img.shields.io/github/forks/wildminder/ComfyUI-DyPE.svg?style=for-the-badge +[forks-url]: https://github.com/wildminder/ComfyUI-DyPE/network/members diff --git a/ComfyUI-DyPE/__init__.py b/ComfyUI-DyPE/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ea06f6817f19c1d9db5ce0a4a0593e31c089bf92 --- /dev/null +++ b/ComfyUI-DyPE/__init__.py @@ -0,0 +1,111 @@ +import torch +from comfy_api.latest import ComfyExtension, io +from .src.patch_utils import apply_dype_to_model + +class DyPE_FLUX(io.ComfyNode): + """ + Applies DyPE (Dynamic Position Extrapolation) to a FLUX model. + """ + + @classmethod + def define_schema(cls) -> io.Schema: + return io.Schema( + node_id="DyPE_FLUX", + display_name="DyPE", + category="model_patches/unet", + description="Applies DyPE (Dynamic Position Extrapolation) to a models for ultra-high-resolution generation.", + inputs=[ + io.Model.Input( + "model", + tooltip="The model to patch with DyPE.", + ), + io.Int.Input( + "width", + default=1024, min=16, max=8192, step=8, + tooltip="Target image width. Must match the width of your empty latent." + ), + io.Int.Input( + "height", + default=1024, min=16, max=8192, step=8, + tooltip="Target image height. Must match the height of your empty latent." + ), + io.Combo.Input( + "model_type", + options=["auto", "flux", "nunchaku", "qwen", "zimage"], + default="auto", + tooltip="Specify the model architecture. 'auto' usually works", + ), + io.Combo.Input( + "method", + options=["vision_yarn", "yarn", "ntk", "base"], + default="vision_yarn", + tooltip="Position encoding extrapolation method.", + ), + io.Boolean.Input( + "yarn_alt_scaling", + default=False, + label_on="Anisotropic (High-Res)", + label_off="Isotropic (Stable Default)", + tooltip="[YARN Only] Alternate scaling for ultra-high resolutions. Not used for 'vision_yarn'.", + ), + io.Boolean.Input( + "enable_dype", + default=True, + label_on="Enabled", + label_off="Disabled", + tooltip="Enable or disable DyPE", + ), + io.Int.Input( + "base_resolution", + default=1024, min=256, max=4096, step=16, + tooltip="The native training resolution.", + ), + io.Float.Input( + "dype_start_sigma", + default=1.0, min=0.0, max=1.0, step=0.01, + tooltip="When to start decaying the scaling effect (1.0 = Start, 0.5 = 50% through generation)." + ), + io.Float.Input( + "dype_scale", + default=2.0, min=0.0, max=8.0, step=0.1, + optional=True, + tooltip="Controls DyPE magnitude (λs). Default is 2.0." + ), + io.Float.Input( + "dype_exponent", + default=2.0, min=0.0, max=1000.0, step=0.1, + optional=True, + tooltip="Controls DyPE decay speed (λt). Higher = Faster decay. 2.0=Quadratic." + ), + io.Float.Input( + "base_shift", + default=0.5, min=0.0, max=10.0, step=0.01, + optional=True, + tooltip="Advanced: Base shift for the noise schedule (mu)." + ), + io.Float.Input( + "max_shift", + default=1.15, min=0.0, max=10.0, step=0.01, + optional=True, + tooltip="Advanced: Max shift for the noise schedule (mu) at high resolutions." + ), + ], + outputs=[ + io.Model.Output( + display_name="Patched Model", + tooltip="The model patched with DyPE.", + ), + ], + ) + + @classmethod + def execute(cls, model, width: int, height: int, model_type: str, method: str, yarn_alt_scaling: bool, enable_dype: bool, base_resolution: int = 1024, dype_start_sigma: float = 1.0, dype_scale: float = 2.0, dype_exponent: float = 2.0, base_shift: float = 0.5, max_shift: float = 1.15) -> io.NodeOutput: + patched_model = apply_dype_to_model(model, model_type, width, height, method, yarn_alt_scaling, enable_dype, dype_scale, dype_exponent, base_shift, max_shift, base_resolution, dype_start_sigma) + return io.NodeOutput(patched_model) + +class DyPEExtension(ComfyExtension): + async def get_node_list(self) -> list[type[io.ComfyNode]]: + return [DyPE_FLUX] + +async def comfy_entrypoint() -> DyPEExtension: + return DyPEExtension() \ No newline at end of file diff --git a/ComfyUI-DyPE/example_workflows/DyPE-Flux-Nunchaku-workflow.json b/ComfyUI-DyPE/example_workflows/DyPE-Flux-Nunchaku-workflow.json new file mode 100644 index 0000000000000000000000000000000000000000..c0483061495463f8ff31c9fec99050e056aabdd9 --- /dev/null +++ b/ComfyUI-DyPE/example_workflows/DyPE-Flux-Nunchaku-workflow.json @@ -0,0 +1,791 @@ +{ + "id": "908d0bfb-e192-4627-9b57-147496e6e2dd", + "revision": 0, + "last_node_id": 107, + "last_link_id": 293, + "nodes": [ + { + "id": 42, + "type": "ConditioningZeroOut", + "pos": [ + 151.75751860615074, + 416.7514387263594 + ], + "size": [ + 200, + 30 + ], + "flags": { + "collapsed": true + }, + "order": 8, + "mode": 0, + "inputs": [ + { + "name": "conditioning", + "type": "CONDITIONING", + "link": 66 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 110 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.40", + "Node name for S&R": "ConditioningZeroOut", + "ue_properties": { + "widget_ue_connectable": {}, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [] + }, + { + "id": 8, + "type": "VAEDecode", + "pos": [ + 391.97558139331176, + 122.95473372107558 + ], + "size": [ + 319.2356335124862, + 46 + ], + "flags": { + "collapsed": false + }, + "order": 10, + "mode": 0, + "inputs": [ + { + "name": "samples", + "type": "LATENT", + "link": 52 + }, + { + "name": "vae", + "type": "VAE", + "link": 85 + } + ], + "outputs": [ + { + "name": "IMAGE", + "type": "IMAGE", + "slot_index": 0, + "links": [] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.40", + "Node name for S&R": "VAEDecode", + "ue_properties": { + "widget_ue_connectable": {}, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [] + }, + { + "id": 55, + "type": "VAEDecodeTiled", + "pos": [ + 391.97558139331176, + 226.612614517858 + ], + "size": [ + 322.89304359551966, + 150 + ], + "flags": {}, + "order": 11, + "mode": 0, + "inputs": [ + { + "name": "samples", + "type": "LATENT", + "link": 112 + }, + { + "name": "vae", + "type": "VAE", + "link": 77 + } + ], + "outputs": [ + { + "name": "IMAGE", + "type": "IMAGE", + "links": [ + 288 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.66", + "Node name for S&R": "VAEDecodeTiled", + "ue_properties": { + "widget_ue_connectable": { + "tile_size": true, + "overlap": true, + "temporal_size": true, + "temporal_overlap": true + }, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + 512, + 64, + 64, + 8 + ] + }, + { + "id": 45, + "type": "CLIPTextEncode", + "pos": [ + 7.045080197257759, + 159.16529405661166 + ], + "size": [ + 330, + 210 + ], + "flags": {}, + "order": 6, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 64 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 66, + 111 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.47", + "Node name for S&R": "CLIPTextEncode", + "ue_properties": { + "widget_ue_connectable": { + "text": true + }, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "A muscular, bald man holds a flower above his head with both arms, set against a soft circular background in black and white." + ], + "color": "#232", + "bgcolor": "#353" + }, + { + "id": 27, + "type": "EmptySD3LatentImage", + "pos": [ + -316.20890581244436, + 792.0300000000001 + ], + "size": [ + 270, + 120 + ], + "flags": {}, + "order": 0, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "slot_index": 0, + "links": [ + 287 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.40", + "Node name for S&R": "EmptySD3LatentImage", + "ue_properties": { + "widget_ue_connectable": { + "width": true, + "height": true, + "batch_size": true + }, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + 2048, + 3072, + 1 + ], + "color": "#223", + "bgcolor": "#335" + }, + { + "id": 31, + "type": "KSampler", + "pos": [ + 395.5510343546297, + 433.7293334706151 + ], + "size": [ + 319.9248663379035, + 486 + ], + "flags": {}, + "order": 9, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 292 + }, + { + "name": "positive", + "type": "CONDITIONING", + "link": 111 + }, + { + "name": "negative", + "type": "CONDITIONING", + "link": 110 + }, + { + "name": "latent_image", + "type": "LATENT", + "link": 287 + } + ], + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "slot_index": 0, + "links": [ + 52, + 112 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.40", + "Node name for S&R": "KSampler", + "ue_properties": { + "widget_ue_connectable": { + "seed": true, + "steps": true, + "cfg": true, + "sampler_name": true, + "scheduler": true, + "denoise": true + }, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + 42, + "fixed", + 30, + 1, + "euler", + "beta", + 1 + ] + }, + { + "id": 104, + "type": "SaveImage", + "pos": [ + 756.4546199065986, + 123.01805911034799 + ], + "size": [ + 521.9900516956579, + 799.3659500468921 + ], + "flags": {}, + "order": 12, + "mode": 0, + "inputs": [ + { + "name": "images", + "type": "IMAGE", + "link": 288 + } + ], + "outputs": [], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.40", + "Node name for S&R": "SaveImage" + }, + "widgets_values": [ + "flux_dype" + ] + }, + { + "id": 39, + "type": "VAELoader", + "pos": [ + -314.4999999999999, + 595.4000000000001 + ], + "size": [ + 270, + 58 + ], + "flags": {}, + "order": 1, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "VAE", + "type": "VAE", + "links": [ + 77, + 85 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.40", + "Node name for S&R": "VAELoader", + "models": [ + { + "name": "ae.safetensors", + "url": "https://huggingface.co/Comfy-Org/Lumina_Image_2.0_Repackaged/resolve/main/split_files/vae/ae.safetensors", + "directory": "vae" + } + ], + "ue_properties": { + "widget_ue_connectable": { + "vae_name": true + }, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "FLUX1\\ae.safetensors" + ], + "color": "#223", + "bgcolor": "#335" + }, + { + "id": 40, + "type": "DualCLIPLoader", + "pos": [ + -314.4999999999999, + 415.4000000000002 + ], + "size": [ + 270, + 130 + ], + "flags": {}, + "order": 2, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "CLIP", + "type": "CLIP", + "links": [ + 64 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.40", + "Node name for S&R": "DualCLIPLoader", + "models": [ + { + "name": "clip_l.safetensors", + "url": "https://huggingface.co/comfyanonymous/flux_text_encoders/resolve/main/clip_l.safetensors", + "directory": "text_encoders" + }, + { + "name": "t5xxl_fp16.safetensors", + "url": "https://huggingface.co/comfyanonymous/flux_text_encoders/resolve/main/t5xxl_fp16.safetensors", + "directory": "text_encoders" + } + ], + "ue_properties": { + "widget_ue_connectable": { + "clip_name1": true, + "clip_name2": true, + "type": true, + "device": true + }, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "clip_l.safetensors", + "t5xxl_fp16.safetensors", + "flux", + "default" + ], + "color": "#223", + "bgcolor": "#335" + }, + { + "id": 107, + "type": "NunchakuFluxDiTLoader", + "pos": [ + -318.2170000000008, + 161.3490000000002 + ], + "size": [ + 274.55224656081157, + 202 + ], + "flags": {}, + "order": 3, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [ + 293 + ] + } + ], + "properties": { + "cnr_id": "comfyui-nunchaku", + "ver": "1.0.2", + "Node name for S&R": "NunchakuFluxDiTLoader" + }, + "widgets_values": [ + "svd\\svdq-int4_r32-flux.1-krea-dev.safetensors", + 0, + "nunchaku-fp16", + "auto", + 0, + "bfloat16", + "enabled" + ], + "color": "#223", + "bgcolor": "#335" + }, + { + "id": 43, + "type": "MarkdownNote", + "pos": [ + -870, + 110 + ], + "size": [ + 518.3471074380165, + 297.4380165289257 + ], + "flags": {}, + "order": 4, + "mode": 0, + "inputs": [], + "outputs": [], + "title": "Model links", + "properties": { + "ue_properties": { + "widget_ue_connectable": {}, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "## Model links\n\n**Diffusion Model**\n\n\n\n**Text Encoder**\n\n- [clip_l.safetensors](https://huggingface.co/comfyanonymous/flux_text_encoders/blob/main/clip_l.safetensors)\n\n- [t5xxl_fp16.safetensors](https://huggingface.co/comfyanonymous/flux_text_encoders/resolve/main/t5xxl_fp16.safetensors) or [t5xxl_fp8_e4m3fn_scaled.safetensors](https://huggingface.co/comfyanonymous/flux_text_encoders/resolve/main/t5xxl_fp8_e4m3fn_scaled.safetensors)\n\n**VAE**\n\n- [ae.safetensors](https://huggingface.co/Comfy-Org/Lumina_Image_2.0_Repackaged/resolve/main/split_files/vae/ae.safetensors)\n\n\n```\nComfyUI/\n├── models/\n│ ├── diffusion_models/\n│ │ └─── \n│ ├── text_encoders/\n│ │ ├── clip_l.safetensors\n│ │ └─── t5xxl_fp16.safetensors # or t5xxl_fp8_e4m3fn_scaled.safetensors\n│ └── vae/\n│ └── ae.safetensors\n```\n" + ], + "color": "#432", + "bgcolor": "#653" + }, + { + "id": 69, + "type": "MarkdownNote", + "pos": [ + -871.340102289358, + 583.6702113673653 + ], + "size": [ + 519.2421649643175, + 338.01057378012047 + ], + "flags": {}, + "order": 5, + "mode": 0, + "inputs": [], + "outputs": [], + "title": "DyPE", + "properties": { + "ue_properties": { + "widget_ue_connectable": {}, + "version": "7.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "### Node Inputs\n\n* **`method`**: The extrapolation strategy.\n * **`vision_yarn`:** Best for 4K+ and non-square images. Fixes stretching and artifacts automatically.\n * **`yarn` / `ntk`**: Legacy methods. Use `yarn` with `yarn_alt_scaling` for manual control.\n* **`enable_dype`**: Toggles the dynamic (time-aware) algorithm. Keep enabled for best quality.\n* **`dype_scale`**: Magnitude of the frequency shift. Default: `2.0`.\n* **`dype_exponent`**: Aggressiveness of the dynamic schedule.\n * `2.0`: Best for **4K**.\n * `1.0`: Best for **2K**.\n * `0.5`: Best for **~1.5K**.\n* **`yarn_alt_scaling`**: *(Legacy `yarn` only)* Switch between Anisotropic (Sharper, potential stretching) and Isotropic (Softer, accurate geometry).\n* **`base_shift` / `max_shift`**: Advanced noise schedule controls. Defaults (`0.5` / `1.15`) are optimized for FLUX.\n\n## Join\n\n### [TokenDiffusion](https://t.me/TokenDiff) - AI for every home, creativity for every mind!\n\n### [TokenDiff Community Hub](https://t.me/TokenDiff_hub) - Questions, help, and thoughtful discussion. " + ], + "color": "#322", + "bgcolor": "#533" + }, + { + "id": 106, + "type": "DyPE_FLUX", + "pos": [ + 20.50266316562786, + 590.5579455354278 + ], + "size": [ + 301.89999999999986, + 322 + ], + "flags": {}, + "order": 7, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 293 + } + ], + "outputs": [ + { + "name": "Patched Model", + "type": "MODEL", + "links": [ + 292 + ] + } + ], + "title": "DyPE", + "properties": { + "cnr_id": "ComfyUI-DyPE", + "ver": "a717a8a26882dbb852f19c05d1bfe973d9f7eab3", + "Node name for S&R": "DyPE_FLUX" + }, + "widgets_values": [ + 2048, + 2048, + "auto", + "yarn", + true, + true, + 1024, + 1, + 2, + 2, + 0.5, + 1.15 + ], + "color": "#332922", + "bgcolor": "#593930" + } + ], + "links": [ + [ + 52, + 31, + 0, + 8, + 0, + "LATENT" + ], + [ + 64, + 40, + 0, + 45, + 0, + "CLIP" + ], + [ + 66, + 45, + 0, + 42, + 0, + "CONDITIONING" + ], + [ + 77, + 39, + 0, + 55, + 1, + "VAE" + ], + [ + 85, + 39, + 0, + 8, + 1, + "VAE" + ], + [ + 110, + 42, + 0, + 31, + 2, + "CONDITIONING" + ], + [ + 111, + 45, + 0, + 31, + 1, + "CONDITIONING" + ], + [ + 112, + 31, + 0, + 55, + 0, + "LATENT" + ], + [ + 287, + 27, + 0, + 31, + 3, + "LATENT" + ], + [ + 288, + 55, + 0, + 104, + 0, + "IMAGE" + ], + [ + 292, + 106, + 0, + 31, + 0, + "MODEL" + ], + [ + 293, + 107, + 0, + 106, + 0, + "MODEL" + ] + ], + "groups": [ + { + "id": 1, + "title": "Step 1 - Load Models Here", + "bounding": [ + -330, + 80, + 301.1, + 608.5 + ], + "color": "#3f789e", + "font_size": 24, + "flags": {} + }, + { + "id": 2, + "title": "Step 2 - Image Size", + "bounding": [ + -326.20890581244436, + 722.0300000000001, + 300, + 200 + ], + "color": "#3f789e", + "font_size": 24, + "flags": {} + }, + { + "id": 3, + "title": "Step 3 - Prompt", + "bounding": [ + -10, + 80, + 361.9005764856456, + 399.16989485829595 + ], + "color": "#3f789e", + "font_size": 24, + "flags": {} + }, + { + "id": 5, + "title": "Model patch", + "bounding": [ + -10, + 510, + 364.41774449769594, + 418.2186315256216 + ], + "color": "#3f789e", + "font_size": 24, + "flags": {} + } + ], + "config": {}, + "extra": { + "ds": { + "scale": 0.7513148009015779, + "offset": [ + 908.7831022893579, + 25.93699999999999 + ] + }, + "frontendVersion": "1.32.9", + "VHS_latentpreview": false, + "VHS_latentpreviewrate": 0, + "VHS_MetadataImage": true, + "VHS_KeepIntermediate": true, + "workflowRendererVersion": "LG" + }, + "version": 0.4 +} \ No newline at end of file diff --git a/ComfyUI-DyPE/example_workflows/DyPE-Flux-workflow.json b/ComfyUI-DyPE/example_workflows/DyPE-Flux-workflow.json new file mode 100644 index 0000000000000000000000000000000000000000..c1c2e8d23a4d16eb2026458575a8bffd5d3da461 --- /dev/null +++ b/ComfyUI-DyPE/example_workflows/DyPE-Flux-workflow.json @@ -0,0 +1,801 @@ +{ + "id": "908d0bfb-e192-4627-9b57-147496e6e2dd", + "revision": 0, + "last_node_id": 106, + "last_link_id": 292, + "nodes": [ + { + "id": 40, + "type": "DualCLIPLoader", + "pos": [ + -320, + 290 + ], + "size": [ + 270, + 130 + ], + "flags": {}, + "order": 0, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "CLIP", + "type": "CLIP", + "links": [ + 64 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.40", + "Node name for S&R": "DualCLIPLoader", + "models": [ + { + "name": "clip_l.safetensors", + "url": "https://huggingface.co/comfyanonymous/flux_text_encoders/resolve/main/clip_l.safetensors", + "directory": "text_encoders" + }, + { + "name": "t5xxl_fp16.safetensors", + "url": "https://huggingface.co/comfyanonymous/flux_text_encoders/resolve/main/t5xxl_fp16.safetensors", + "directory": "text_encoders" + } + ], + "ue_properties": { + "widget_ue_connectable": { + "clip_name1": true, + "clip_name2": true, + "type": true, + "device": true + }, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "clip_l.safetensors", + "t5xxl_fp16.safetensors", + "flux", + "default" + ], + "color": "#223", + "bgcolor": "#335" + }, + { + "id": 43, + "type": "MarkdownNote", + "pos": [ + -870, + 110 + ], + "size": [ + 520, + 390 + ], + "flags": {}, + "order": 1, + "mode": 0, + "inputs": [], + "outputs": [], + "title": "Model links", + "properties": { + "ue_properties": { + "widget_ue_connectable": {}, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "## Model links\n\n**Diffusion Model**\n\n- [flux1-krea-dev_fp8_scaled.safetensors](https://huggingface.co/Comfy-Org/FLUX.1-Krea-dev_ComfyUI/resolve/main/split_files/diffusion_models/flux1-krea-dev_fp8_scaled.safetensors)\n\nIf you need the original weights, head to [black-forest-labs/FLUX.1-Krea-dev](https://huggingface.co/black-forest-labs/FLUX.1-Krea-dev/), accept the agreement in the repo, then click the link below to download the models:\n\n- [flux1-krea-dev.safetensors](https://huggingface.co/black-forest-labs/FLUX.1-Krea-dev/resolve/main/flux1-krea-dev.safetensors)\n\n**Text Encoder**\n\n- [clip_l.safetensors](https://huggingface.co/comfyanonymous/flux_text_encoders/blob/main/clip_l.safetensors)\n\n- [t5xxl_fp16.safetensors](https://huggingface.co/comfyanonymous/flux_text_encoders/resolve/main/t5xxl_fp16.safetensors) or [t5xxl_fp8_e4m3fn_scaled.safetensors](https://huggingface.co/comfyanonymous/flux_text_encoders/resolve/main/t5xxl_fp8_e4m3fn_scaled.safetensors)\n\n**VAE**\n\n- [ae.safetensors](https://huggingface.co/Comfy-Org/Lumina_Image_2.0_Repackaged/resolve/main/split_files/vae/ae.safetensors)\n\n\n```\nComfyUI/\n├── models/\n│ ├── diffusion_models/\n│ │ └─── flux1-krea-dev_fp8_scaled.safetensors\n│ ├── text_encoders/\n│ │ ├── clip_l.safetensors\n│ │ └─── t5xxl_fp16.safetensors # or t5xxl_fp8_e4m3fn_scaled.safetensors\n│ └── vae/\n│ └── ae.safetensors\n```\n" + ], + "color": "#432", + "bgcolor": "#653" + }, + { + "id": 39, + "type": "VAELoader", + "pos": [ + -320, + 470 + ], + "size": [ + 270, + 58 + ], + "flags": {}, + "order": 2, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "VAE", + "type": "VAE", + "links": [ + 77, + 85 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.40", + "Node name for S&R": "VAELoader", + "models": [ + { + "name": "ae.safetensors", + "url": "https://huggingface.co/Comfy-Org/Lumina_Image_2.0_Repackaged/resolve/main/split_files/vae/ae.safetensors", + "directory": "vae" + } + ], + "ue_properties": { + "widget_ue_connectable": { + "vae_name": true + }, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "FLUX1\\ae.safetensors" + ], + "color": "#223", + "bgcolor": "#335" + }, + { + "id": 42, + "type": "ConditioningZeroOut", + "pos": [ + 151.75751860615074, + 416.7514387263594 + ], + "size": [ + 200, + 30 + ], + "flags": { + "collapsed": true + }, + "order": 8, + "mode": 0, + "inputs": [ + { + "name": "conditioning", + "type": "CONDITIONING", + "link": 66 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 110 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.40", + "Node name for S&R": "ConditioningZeroOut", + "ue_properties": { + "widget_ue_connectable": {}, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [] + }, + { + "id": 8, + "type": "VAEDecode", + "pos": [ + 391.97558139331176, + 122.95473372107558 + ], + "size": [ + 319.2356335124862, + 46 + ], + "flags": { + "collapsed": false + }, + "order": 10, + "mode": 0, + "inputs": [ + { + "name": "samples", + "type": "LATENT", + "link": 52 + }, + { + "name": "vae", + "type": "VAE", + "link": 85 + } + ], + "outputs": [ + { + "name": "IMAGE", + "type": "IMAGE", + "slot_index": 0, + "links": [] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.40", + "Node name for S&R": "VAEDecode", + "ue_properties": { + "widget_ue_connectable": {}, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [] + }, + { + "id": 38, + "type": "UNETLoader", + "pos": [ + -319.9999999999996, + 154.75892789151453 + ], + "size": [ + 270, + 82 + ], + "flags": {}, + "order": 3, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [ + 291 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.40", + "Node name for S&R": "UNETLoader", + "models": [ + { + "name": "flux1-krea-dev_fp8_scaled.safetensors", + "url": "https://huggingface.co/Comfy-Org/FLUX.1-Krea-dev_ComfyUI/resolve/main/split_files/diffusion_models/flux1-krea-dev_fp8_scaled.safetensors", + "directory": "diffusion_models" + } + ], + "ue_properties": { + "widget_ue_connectable": { + "unet_name": true, + "weight_dtype": true + }, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "FLUX1\\flux1-krea-dev.safetensors", + "default" + ], + "color": "#223", + "bgcolor": "#335" + }, + { + "id": 55, + "type": "VAEDecodeTiled", + "pos": [ + 391.97558139331176, + 226.612614517858 + ], + "size": [ + 322.89304359551966, + 150 + ], + "flags": {}, + "order": 11, + "mode": 0, + "inputs": [ + { + "name": "samples", + "type": "LATENT", + "link": 112 + }, + { + "name": "vae", + "type": "VAE", + "link": 77 + } + ], + "outputs": [ + { + "name": "IMAGE", + "type": "IMAGE", + "links": [ + 288 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.66", + "Node name for S&R": "VAEDecodeTiled", + "ue_properties": { + "widget_ue_connectable": { + "tile_size": true, + "overlap": true, + "temporal_size": true, + "temporal_overlap": true + }, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + 512, + 64, + 64, + 8 + ] + }, + { + "id": 45, + "type": "CLIPTextEncode", + "pos": [ + 7.045080197257759, + 159.16529405661166 + ], + "size": [ + 330, + 210 + ], + "flags": {}, + "order": 6, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 64 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 66, + 111 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.47", + "Node name for S&R": "CLIPTextEncode", + "ue_properties": { + "widget_ue_connectable": { + "text": true + }, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "A muscular, bald man holds a flower above his head with both arms, set against a soft circular background in black and white." + ], + "color": "#232", + "bgcolor": "#353" + }, + { + "id": 27, + "type": "EmptySD3LatentImage", + "pos": [ + -320, + 630 + ], + "size": [ + 270, + 120 + ], + "flags": {}, + "order": 4, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "slot_index": 0, + "links": [ + 287 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.40", + "Node name for S&R": "EmptySD3LatentImage", + "ue_properties": { + "widget_ue_connectable": { + "width": true, + "height": true, + "batch_size": true + }, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + 2048, + 3072, + 1 + ], + "color": "#223", + "bgcolor": "#335" + }, + { + "id": 31, + "type": "KSampler", + "pos": [ + 395.5510343546297, + 433.7293334706151 + ], + "size": [ + 319.9248663379035, + 486 + ], + "flags": {}, + "order": 9, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 292 + }, + { + "name": "positive", + "type": "CONDITIONING", + "link": 111 + }, + { + "name": "negative", + "type": "CONDITIONING", + "link": 110 + }, + { + "name": "latent_image", + "type": "LATENT", + "link": 287 + } + ], + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "slot_index": 0, + "links": [ + 52, + 112 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.40", + "Node name for S&R": "KSampler", + "ue_properties": { + "widget_ue_connectable": { + "seed": true, + "steps": true, + "cfg": true, + "sampler_name": true, + "scheduler": true, + "denoise": true + }, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + 42, + "fixed", + 30, + 1, + "euler", + "beta", + 1 + ] + }, + { + "id": 69, + "type": "MarkdownNote", + "pos": [ + -869.9740753786278, + 574.7910364476191 + ], + "size": [ + 519.2421649643175, + 338.01057378012047 + ], + "flags": {}, + "order": 5, + "mode": 0, + "inputs": [], + "outputs": [], + "title": "DyPE", + "properties": { + "ue_properties": { + "widget_ue_connectable": {}, + "version": "7.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "### Node Inputs\n\n* **`method`**: The extrapolation strategy.\n * **`vision_yarn`:** Best for 4K+ and non-square images. Fixes stretching and artifacts automatically.\n * **`yarn` / `ntk`**: Legacy methods. Use `yarn` with `yarn_alt_scaling` for manual control.\n* **`enable_dype`**: Toggles the dynamic (time-aware) algorithm. Keep enabled for best quality.\n* **`dype_scale`**: Magnitude of the frequency shift. Default: `2.0`.\n* **`dype_exponent`**: Aggressiveness of the dynamic schedule.\n * `2.0`: Best for **4K**.\n * `1.0`: Best for **2K**.\n * `0.5`: Best for **~1.5K**.\n* **`yarn_alt_scaling`**: *(Legacy `yarn` only)* Switch between Anisotropic (Sharper, potential stretching) and Isotropic (Softer, accurate geometry).\n* **`base_shift` / `max_shift`**: Advanced noise schedule controls. Defaults (`0.5` / `1.15`) are optimized for FLUX.\n\n## Join\n\n### [TokenDiffusion](https://t.me/TokenDiff) - AI for every home, creativity for every mind!\n\n### [TokenDiff Community Hub](https://t.me/TokenDiff_hub) - Questions, help, and thoughtful discussion. " + ], + "color": "#322", + "bgcolor": "#533" + }, + { + "id": 104, + "type": "SaveImage", + "pos": [ + 756.4546199065986, + 123.01805911034799 + ], + "size": [ + 521.9900516956579, + 799.3659500468921 + ], + "flags": {}, + "order": 12, + "mode": 0, + "inputs": [ + { + "name": "images", + "type": "IMAGE", + "link": 288 + } + ], + "outputs": [], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.40", + "Node name for S&R": "SaveImage" + }, + "widgets_values": [ + "flux_dype" + ] + }, + { + "id": 106, + "type": "DyPE_FLUX", + "pos": [ + 20.50266316562786, + 590.5579455354278 + ], + "size": [ + 301.89999999999986, + 322 + ], + "flags": {}, + "order": 7, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 291 + } + ], + "outputs": [ + { + "name": "Patched Model", + "type": "MODEL", + "links": [ + 292 + ] + } + ], + "title": "DyPE", + "properties": { + "cnr_id": "ComfyUI-DyPE", + "ver": "a717a8a26882dbb852f19c05d1bfe973d9f7eab3", + "Node name for S&R": "DyPE_FLUX" + }, + "widgets_values": [ + 2048, + 2048, + "auto", + "vision_yarn", + false, + true, + 1024, + 1, + 2, + 2, + 0.5, + 1.15 + ], + "color": "#332922", + "bgcolor": "#593930" + } + ], + "links": [ + [ + 52, + 31, + 0, + 8, + 0, + "LATENT" + ], + [ + 64, + 40, + 0, + 45, + 0, + "CLIP" + ], + [ + 66, + 45, + 0, + 42, + 0, + "CONDITIONING" + ], + [ + 77, + 39, + 0, + 55, + 1, + "VAE" + ], + [ + 85, + 39, + 0, + 8, + 1, + "VAE" + ], + [ + 110, + 42, + 0, + 31, + 2, + "CONDITIONING" + ], + [ + 111, + 45, + 0, + 31, + 1, + "CONDITIONING" + ], + [ + 112, + 31, + 0, + 55, + 0, + "LATENT" + ], + [ + 287, + 27, + 0, + 31, + 3, + "LATENT" + ], + [ + 288, + 55, + 0, + 104, + 0, + "IMAGE" + ], + [ + 291, + 38, + 0, + 106, + 0, + "MODEL" + ], + [ + 292, + 106, + 0, + 31, + 0, + "MODEL" + ] + ], + "groups": [ + { + "id": 1, + "title": "Step 1 - Load Models Here", + "bounding": [ + -330, + 80, + 300, + 460 + ], + "color": "#3f789e", + "font_size": 24, + "flags": {} + }, + { + "id": 2, + "title": "Step 2 - Image Size", + "bounding": [ + -330, + 560, + 300, + 200 + ], + "color": "#3f789e", + "font_size": 24, + "flags": {} + }, + { + "id": 3, + "title": "Step 3 - Prompt", + "bounding": [ + -10, + 80, + 361.9005764856456, + 399.16989485829595 + ], + "color": "#3f789e", + "font_size": 24, + "flags": {} + }, + { + "id": 5, + "title": "Model patch", + "bounding": [ + -10, + 510, + 364.41774449769594, + 418.2186315256216 + ], + "color": "#3f789e", + "font_size": 24, + "flags": {} + } + ], + "config": {}, + "extra": { + "ds": { + "scale": 0.7513148009015777, + "offset": [ + 981.9790000000002, + 69.86000000000001 + ] + }, + "frontendVersion": "1.32.9", + "VHS_latentpreview": false, + "VHS_latentpreviewrate": 0, + "VHS_MetadataImage": true, + "VHS_KeepIntermediate": true, + "workflowRendererVersion": "LG" + }, + "version": 0.4 +} \ No newline at end of file diff --git a/ComfyUI-DyPE/example_workflows/DyPE-Qwen-workflow.json b/ComfyUI-DyPE/example_workflows/DyPE-Qwen-workflow.json new file mode 100644 index 0000000000000000000000000000000000000000..e44647a5b8aedc2178ac75d90954b4915a7afe07 --- /dev/null +++ b/ComfyUI-DyPE/example_workflows/DyPE-Qwen-workflow.json @@ -0,0 +1,1125 @@ +{ + "id": "91f6bbe2-ed41-4fd6-bac7-71d5b5864ecb", + "revision": 0, + "last_node_id": 87, + "last_link_id": 147, + "nodes": [ + { + "id": 66, + "type": "ModelSamplingAuraFlow", + "pos": [ + 850, + 10 + ], + "size": [ + 300, + 58 + ], + "flags": {}, + "order": 17, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 143 + } + ], + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.48", + "Node name for S&R": "ModelSamplingAuraFlow", + "enableTabs": false, + "tabWidth": 65, + "tabXOffset": 10, + "hasSecondTab": false, + "secondTabText": "Send Back", + "secondTabOffset": 80, + "secondTabWidth": 65, + "ue_properties": { + "version": "7.5.1", + "widget_ue_connectable": {}, + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + 3.1000000000000005 + ] + }, + { + "id": 69, + "type": "MarkdownNote", + "pos": [ + -540, + -220 + ], + "size": [ + 390, + 180 + ], + "flags": {}, + "order": 0, + "mode": 0, + "inputs": [], + "outputs": [], + "title": "VRAM Usage", + "properties": { + "ue_properties": { + "version": "7.5.1", + "widget_ue_connectable": {}, + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "## GPU:RTX4090D 24GB\n\n| Configuration | VRAM Usage | 1st Generation | 2nd Generation |\n|---------------------|---------------|---------------|-----------------|\n| Fp8_e4m3fn | 86% | ≈ 94s | ≈ 71s |\n| With 8steps LoRA | 86% | ≈ 55s | ≈ 34s |\n| Distill fp8_e4m3fn | 86% | ≈ 69s | ≈ 36s |" + ], + "color": "#432", + "bgcolor": "#653" + }, + { + "id": 71, + "type": "Note", + "pos": [ + 850, + -120 + ], + "size": [ + 300, + 88 + ], + "flags": {}, + "order": 1, + "mode": 0, + "inputs": [], + "outputs": [], + "properties": { + "ue_properties": { + "widget_ue_connectable": {}, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "Increase the shift if you get too many blury/dark/bad images. Decrease if you want to try increasing detail." + ], + "color": "#432", + "bgcolor": "#653" + }, + { + "id": 37, + "type": "UNETLoader", + "pos": [ + 20, + 50 + ], + "size": [ + 330, + 90 + ], + "flags": {}, + "order": 2, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "slot_index": 0, + "links": [ + 129 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.48", + "Node name for S&R": "UNETLoader", + "models": [ + { + "name": "qwen_image_fp8_e4m3fn.safetensors", + "url": "https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI/resolve/main/split_files/diffusion_models/qwen_image_fp8_e4m3fn.safetensors", + "directory": "diffusion_models" + } + ], + "enableTabs": false, + "tabWidth": 65, + "tabXOffset": 10, + "hasSecondTab": false, + "secondTabText": "Send Back", + "secondTabOffset": 80, + "secondTabWidth": 65, + "ue_properties": { + "version": "7.5.1", + "widget_ue_connectable": {}, + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "Qwen_Image_fp8_e5m2_scaled_KJ.safetensors", + "default" + ] + }, + { + "id": 38, + "type": "CLIPLoader", + "pos": [ + 20, + 190 + ], + "size": [ + 330, + 110 + ], + "flags": {}, + "order": 3, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "CLIP", + "type": "CLIP", + "slot_index": 0, + "links": [ + 74, + 75 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.48", + "Node name for S&R": "CLIPLoader", + "models": [ + { + "name": "qwen_2.5_vl_7b_fp8_scaled.safetensors", + "url": "https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI/resolve/main/split_files/text_encoders/qwen_2.5_vl_7b_fp8_scaled.safetensors", + "directory": "text_encoders" + } + ], + "enableTabs": false, + "tabWidth": 65, + "tabXOffset": 10, + "hasSecondTab": false, + "secondTabText": "Send Back", + "secondTabOffset": 80, + "secondTabWidth": 65, + "ue_properties": { + "version": "7.5.1", + "widget_ue_connectable": {}, + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "qwen_2.5_vl_7b_fp8_scaled.safetensors", + "qwen_image", + "default" + ] + }, + { + "id": 39, + "type": "VAELoader", + "pos": [ + 20, + 340 + ], + "size": [ + 330, + 60 + ], + "flags": {}, + "order": 4, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "VAE", + "type": "VAE", + "slot_index": 0, + "links": [ + 76 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.48", + "Node name for S&R": "VAELoader", + "models": [ + { + "name": "qwen_image_vae.safetensors", + "url": "https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI/resolve/main/split_files/vae/qwen_image_vae.safetensors", + "directory": "vae" + } + ], + "enableTabs": false, + "tabWidth": 65, + "tabXOffset": 10, + "hasSecondTab": false, + "secondTabText": "Send Back", + "secondTabOffset": 80, + "secondTabWidth": 65, + "ue_properties": { + "version": "7.5.1", + "widget_ue_connectable": {}, + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "qwen_image_vae.safetensors" + ] + }, + { + "id": 7, + "type": "CLIPTextEncode", + "pos": [ + 390, + 440 + ], + "size": [ + 425.27801513671875, + 180.6060791015625 + ], + "flags": { + "collapsed": true + }, + "order": 15, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 75 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "slot_index": 0, + "links": [ + 52 + ] + } + ], + "title": "CLIP Text Encode (Negative Prompt)", + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.48", + "Node name for S&R": "CLIPTextEncode", + "enableTabs": false, + "tabWidth": 65, + "tabXOffset": 10, + "hasSecondTab": false, + "secondTabText": "Send Back", + "secondTabOffset": 80, + "secondTabWidth": 65, + "ue_properties": { + "version": "7.5.1", + "widget_ue_connectable": {}, + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "" + ], + "color": "#322", + "bgcolor": "#533" + }, + { + "id": 67, + "type": "MarkdownNote", + "pos": [ + -540, + 10 + ], + "size": [ + 536.8095568252323, + 509.56077015252083 + ], + "flags": {}, + "order": 5, + "mode": 0, + "inputs": [], + "outputs": [], + "title": "Model links", + "properties": { + "ue_properties": { + "version": "7.5.1", + "widget_ue_connectable": {}, + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "[Tutorial](https://docs.comfy.org/tutorials/image/qwen/qwen-image) \n\n## Model links\n\nYou can find all the models on [Huggingface](https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI/tree/main) or [Modelscope](https://modelscope.cn/models/Comfy-Org/Qwen-Image_ComfyUI/files)\n\n**Diffusion model**\n\n- [qwen_image_fp8_e4m3fn.safetensors](https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI/resolve/main/split_files/diffusion_models/qwen_image_fp8_e4m3fn.safetensors)\n\nQwen_image_distill\n\n- [qwen_image_distill_full_fp8_e4m3fn.safetensors](https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI/resolve/main/non_official/diffusion_models/qwen_image_distill_full_fp8_e4m3fn.safetensors)\n- [qwen_image_distill_full_bf16.safetensors](https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI/resolve/main/non_official/diffusion_models/qwen_image_distill_full_bf16.safetensors)\n\n**LoRA**\n\n- [Qwen-Image-Lightning-8steps-V1.0.safetensors](https://huggingface.co/lightx2v/Qwen-Image-Lightning/resolve/main/Qwen-Image-Lightning-8steps-V1.0.safetensors)\n\n**Text encoder**\n\n- [qwen_2.5_vl_7b_fp8_scaled.safetensors](https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI/resolve/main/split_files/text_encoders/qwen_2.5_vl_7b_fp8_scaled.safetensors)\n\n**VAE**\n\n- [qwen_image_vae.safetensors](https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI/resolve/main/split_files/vae/qwen_image_vae.safetensors)\n\nModel Storage Location\n\n```\n📂 ComfyUI/\n├── 📂 models/\n│ ├── 📂 diffusion_models/\n│ │ ├── qwen_image_fp8_e4m3fn.safetensors\n│ │ └── qwen_image_distill_full_fp8_e4m3fn.safetensors\n│ ├── 📂 loras/\n│ │ └── Qwen-Image-Lightning-8steps-V1.0.safetensors\n│ ├── 📂 vae/\n│ │ └── qwen_image_vae.safetensors\n│ └── 📂 text_encoders/\n│ └── qwen_2.5_vl_7b_fp8_scaled.safetensors\n```\n" + ], + "color": "#432", + "bgcolor": "#653" + }, + { + "id": 70, + "type": "Note", + "pos": [ + 382.3234815942132, + -139.82996037638443 + ], + "size": [ + 446.0829746907252, + 96.9357457599759 + ], + "flags": {}, + "order": 6, + "mode": 0, + "inputs": [], + "outputs": [], + "title": "For fp8 without 8steps LoRA", + "properties": { + "ue_properties": { + "widget_ue_connectable": {}, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "Set cfg to 1.0 for a speed boost at the cost of consistency. Samplers like res_multistep work pretty well at cfg 1.0\n\nThe official number of steps is 50 but I think that's too much. Even just 10 steps seems to work." + ], + "color": "#432", + "bgcolor": "#653" + }, + { + "id": 8, + "type": "VAEDecode", + "pos": [ + 1189.8522933717531, + -95.83890981522165 + ], + "size": [ + 210, + 46 + ], + "flags": { + "collapsed": false + }, + "order": 19, + "mode": 0, + "inputs": [ + { + "name": "samples", + "type": "LATENT", + "link": 128 + }, + { + "name": "vae", + "type": "VAE", + "link": 76 + } + ], + "outputs": [ + { + "name": "IMAGE", + "type": "IMAGE", + "slot_index": 0, + "links": [ + 147 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.48", + "Node name for S&R": "VAEDecode", + "enableTabs": false, + "tabWidth": 65, + "tabXOffset": 10, + "hasSecondTab": false, + "secondTabText": "Send Back", + "secondTabOffset": 80, + "secondTabWidth": 65, + "ue_properties": { + "version": "7.5.1", + "widget_ue_connectable": {}, + "input_ue_unconnectable": {} + } + }, + "widgets_values": [] + }, + { + "id": 6, + "type": "CLIPTextEncode", + "pos": [ + 390, + 240 + ], + "size": [ + 422.84503173828125, + 164.31304931640625 + ], + "flags": {}, + "order": 14, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 74 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "slot_index": 0, + "links": [ + 46 + ] + } + ], + "title": "CLIP Text Encode (Positive Prompt)", + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.48", + "Node name for S&R": "CLIPTextEncode", + "enableTabs": false, + "tabWidth": 65, + "tabXOffset": 10, + "hasSecondTab": false, + "secondTabText": "Send Back", + "secondTabOffset": 80, + "secondTabWidth": 65, + "ue_properties": { + "version": "7.5.1", + "widget_ue_connectable": {}, + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "A muscular, bald man holds a flower above his head with both arms, set against a soft circular background in black and white." + ], + "color": "#232", + "bgcolor": "#353" + }, + { + "id": 58, + "type": "EmptySD3LatentImage", + "pos": [ + 50, + 510 + ], + "size": [ + 270, + 106 + ], + "flags": {}, + "order": 7, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "links": [ + 107 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.48", + "Node name for S&R": "EmptySD3LatentImage", + "enableTabs": false, + "tabWidth": 65, + "tabXOffset": 10, + "hasSecondTab": false, + "secondTabText": "Send Back", + "secondTabOffset": 80, + "secondTabWidth": 65, + "ue_properties": { + "version": "7.5.1", + "widget_ue_connectable": {}, + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + 2048, + 3072, + 1 + ] + }, + { + "id": 86, + "type": "VAEDecodeTiled", + "pos": [ + 1198.6859676376419, + -3.510055414695172 + ], + "size": [ + 214.2893210323973, + 150 + ], + "flags": {}, + "order": 8, + "mode": 0, + "inputs": [ + { + "name": "samples", + "type": "LATENT", + "link": null + }, + { + "name": "vae", + "type": "VAE", + "link": null + } + ], + "outputs": [ + { + "name": "IMAGE", + "type": "IMAGE", + "links": [] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.66", + "Node name for S&R": "VAEDecodeTiled", + "ue_properties": { + "widget_ue_connectable": { + "tile_size": true, + "overlap": true, + "temporal_size": true, + "temporal_overlap": true + }, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + 512, + 64, + 64, + 8 + ] + }, + { + "id": 84, + "type": "Note", + "pos": [ + 127.85552070578971, + 697.2085344493496 + ], + "size": [ + 230.1795530804054, + 88 + ], + "flags": {}, + "order": 9, + "mode": 0, + "inputs": [], + "outputs": [], + "properties": {}, + "widgets_values": [ + "Base resolution for Qwen: 1328 (paper suggests)" + ], + "color": "#432", + "bgcolor": "#653" + }, + { + "id": 87, + "type": "Note", + "pos": [ + 1451.2767236896004, + -0.28977601296752376 + ], + "size": [ + 230.1795530804054, + 88 + ], + "flags": {}, + "order": 10, + "mode": 0, + "inputs": [], + "outputs": [], + "properties": {}, + "widgets_values": [ + "In case of VAE OOM at higher resolution, use VAE tiled" + ], + "color": "#432", + "bgcolor": "#653" + }, + { + "id": 74, + "type": "MarkdownNote", + "pos": [ + 855.4484793317094, + 646.470925717398 + ], + "size": [ + 291.9524605711331, + 193.0140805375371 + ], + "flags": {}, + "order": 11, + "mode": 0, + "inputs": [], + "outputs": [], + "title": "KSampler settings", + "properties": { + "ue_properties": { + "widget_ue_connectable": {}, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "You can test and find the best setting by yourself. The following table is for reference.\n\n| model | steps | cfg |\n|---------------------|---------------|---------------|\n| fp8_e4m3fn(Qwen team's suggestion) | 40 | 2.5 \n| fp8_e4m3fn | 20 | 2.5 |\n| fp8_e4m3fn + 8steps LoRA | 8 | 1.0 |\n| distill fp8_e4m3fn | 10 | 1.0 |" + ], + "color": "#432", + "bgcolor": "#653" + }, + { + "id": 83, + "type": "MarkdownNote", + "pos": [ + -532.5918528644575, + 578.8669399944761 + ], + "size": [ + 527.1046728188984, + 338.93083892915456 + ], + "flags": {}, + "order": 12, + "mode": 0, + "inputs": [], + "outputs": [], + "title": "DyPE", + "properties": { + "ue_properties": { + "widget_ue_connectable": {}, + "version": "7.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "### Node Inputs\n\n* **`method`**: The extrapolation strategy.\n * **`vision_yarn`:** Best for 4K+ and non-square images. Fixes stretching and artifacts automatically.\n * **`yarn` / `ntk`**: Legacy methods. Use `yarn` with `yarn_alt_scaling` for manual control.\n* **`enable_dype`**: Toggles the dynamic (time-aware) algorithm. Keep enabled for best quality.\n* **`dype_scale`**: Magnitude of the frequency shift. Default: `2.0`.\n* **`dype_exponent`**: Aggressiveness of the dynamic schedule.\n * `2.0`: Best for **4K**.\n * `1.0`: Best for **2K**.\n * `0.5`: Best for **~1.5K**.\n* **`yarn_alt_scaling`**: *(Legacy `yarn` only)* Switch between Anisotropic (Sharper, potential stretching) and Isotropic (Softer, accurate geometry).\n* **`base_shift` / `max_shift`**: Advanced noise schedule controls. Defaults (`0.5` / `1.15`) are optimized for FLUX.\n\n\n## Join\n\n### [TokenDiffusion](https://t.me/TokenDiff) - AI for every home, creativity for every mind!\n\n### [TokenDiff Community Hub](https://t.me/TokenDiff_hub) - Questions, help, and thoughtful discussion. " + ], + "color": "#322", + "bgcolor": "#533" + }, + { + "id": 73, + "type": "LoraLoaderModelOnly", + "pos": [ + 418.83291410517865, + 50.4286704756969 + ], + "size": [ + 347.36824698811677, + 92.36894031799505 + ], + "flags": {}, + "order": 13, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 129 + } + ], + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [ + 142 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.49", + "Node name for S&R": "LoraLoaderModelOnly", + "models": [ + { + "name": "Qwen-Image-Lightning-8steps-V1.0.safetensors", + "url": "https://huggingface.co/lightx2v/Qwen-Image-Lightning/resolve/main/Qwen-Image-Lightning-8steps-V1.0.safetensors", + "directory": "loras" + } + ], + "ue_properties": { + "widget_ue_connectable": { + "lora_name": true, + "strength_model": true + }, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "qwen\\Qwen-Image-Lightning-8steps-V2.0-bf16.safetensors", + 1 + ] + }, + { + "id": 3, + "type": "KSampler", + "pos": [ + 850, + 120 + ], + "size": [ + 300, + 474 + ], + "flags": {}, + "order": 18, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 146 + }, + { + "name": "positive", + "type": "CONDITIONING", + "link": 46 + }, + { + "name": "negative", + "type": "CONDITIONING", + "link": 52 + }, + { + "name": "latent_image", + "type": "LATENT", + "link": 107 + } + ], + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "slot_index": 0, + "links": [ + 128 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.48", + "Node name for S&R": "KSampler", + "enableTabs": false, + "tabWidth": 65, + "tabXOffset": 10, + "hasSecondTab": false, + "secondTabText": "Send Back", + "secondTabOffset": 80, + "secondTabWidth": 65, + "ue_properties": { + "version": "7.5.1", + "widget_ue_connectable": {}, + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + 91534580598587, + "fixed", + 8, + 1, + "euler", + "simple", + 1 + ] + }, + { + "id": 82, + "type": "DyPE_FLUX", + "pos": [ + 420.94687820112836, + 578.0070284351821 + ], + "size": [ + 370.4292488218126, + 322 + ], + "flags": {}, + "order": 16, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 142 + } + ], + "outputs": [ + { + "name": "Patched Model", + "type": "MODEL", + "links": [ + 143, + 146 + ] + } + ], + "properties": { + "cnr_id": "ComfyUI-DyPE", + "ver": "a717a8a26882dbb852f19c05d1bfe973d9f7eab3", + "Node name for S&R": "DyPE_FLUX", + "ue_properties": { + "widget_ue_connectable": { + "width": true, + "height": true, + "method": true, + "enable_dype": true, + "dype_exponent": true, + "base_shift": true, + "max_shift": true + }, + "version": "7.5.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + 4096, + 4096, + "auto", + "vision_yarn", + true, + true, + 1328, + 1, + 2, + 10, + 0.5, + 1.15 + ], + "color": "#332922", + "bgcolor": "#593930" + }, + { + "id": 85, + "type": "SaveImage", + "pos": [ + 1190.7567281085715, + 197.79219937488617 + ], + "size": [ + 507.8598899428216, + 713.1719633545902 + ], + "flags": {}, + "order": 20, + "mode": 0, + "inputs": [ + { + "name": "images", + "type": "IMAGE", + "link": 147 + } + ], + "outputs": [], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.40", + "Node name for S&R": "SaveImage" + }, + "widgets_values": [ + "qwen_dype" + ] + } + ], + "links": [ + [ + 46, + 6, + 0, + 3, + 1, + "CONDITIONING" + ], + [ + 52, + 7, + 0, + 3, + 2, + "CONDITIONING" + ], + [ + 74, + 38, + 0, + 6, + 0, + "CLIP" + ], + [ + 75, + 38, + 0, + 7, + 0, + "CLIP" + ], + [ + 76, + 39, + 0, + 8, + 1, + "VAE" + ], + [ + 107, + 58, + 0, + 3, + 3, + "LATENT" + ], + [ + 128, + 3, + 0, + 8, + 0, + "LATENT" + ], + [ + 129, + 37, + 0, + 73, + 0, + "MODEL" + ], + [ + 142, + 73, + 0, + 82, + 0, + "MODEL" + ], + [ + 143, + 82, + 0, + 66, + 0, + "MODEL" + ], + [ + 146, + 82, + 0, + 3, + 0, + "MODEL" + ], + [ + 147, + 8, + 0, + 85, + 0, + "IMAGE" + ] + ], + "groups": [ + { + "id": 1, + "title": "Step1 - Load models", + "bounding": [ + 10, + -20, + 350, + 433.6000061035156 + ], + "color": "#3f789e", + "font_size": 24, + "flags": {} + }, + { + "id": 2, + "title": "Step2 - Image size", + "bounding": [ + 10, + 430, + 350, + 210 + ], + "color": "#3f789e", + "font_size": 24, + "flags": {} + }, + { + "id": 3, + "title": "Step3 - Prompt", + "bounding": [ + 380, + 160, + 455.6520647011346, + 296.19901044011226 + ], + "color": "#3f789e", + "font_size": 24, + "flags": {} + }, + { + "id": 4, + "title": "Lightx2v 8steps LoRA", + "bounding": [ + 380, + -20, + 450, + 170 + ], + "color": "#3f789e", + "font_size": 24, + "flags": {} + }, + { + "id": 6, + "title": "Model Patching", + "bounding": [ + 384.83801869752796, + 481.45994817875567, + 449.90889198206656, + 448.6671733031452 + ], + "color": "#3f789e", + "font_size": 24, + "flags": {} + } + ], + "config": {}, + "extra": { + "ds": { + "scale": 0.7077059820630021, + "offset": [ + 755.6494571265252, + 282.90090632629403 + ] + }, + "frontendVersion": "1.32.9", + "ue_links": [], + "links_added_by_ue": [], + "VHS_latentpreview": false, + "VHS_latentpreviewrate": 0, + "VHS_MetadataImage": true, + "VHS_KeepIntermediate": true, + "workflowRendererVersion": "LG" + }, + "version": 0.4 +} \ No newline at end of file diff --git a/ComfyUI-DyPE/example_workflows/DyPE-ZIT-workflow.json b/ComfyUI-DyPE/example_workflows/DyPE-ZIT-workflow.json new file mode 100644 index 0000000000000000000000000000000000000000..a7aadb496a7b7b0de72acabb25e71402b6de5cd8 --- /dev/null +++ b/ComfyUI-DyPE/example_workflows/DyPE-ZIT-workflow.json @@ -0,0 +1,838 @@ +{ + "id": "9ae6082b-c7f4-433c-9971-7a8f65a3ea65", + "revision": 0, + "last_node_id": 52, + "last_link_id": 49, + "nodes": [ + { + "id": 44, + "type": "KSampler", + "pos": [ + 900.2638101844517, + 375.2545050421948 + ], + "size": [ + 317.95033878771574, + 474 + ], + "flags": {}, + "order": 12, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 40 + }, + { + "name": "positive", + "type": "CONDITIONING", + "link": 41 + }, + { + "name": "negative", + "type": "CONDITIONING", + "link": 42 + }, + { + "name": "latent_image", + "type": "LATENT", + "link": 43 + } + ], + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "slot_index": 0, + "links": [ + 38 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.64", + "Node name for S&R": "KSampler", + "enableTabs": false, + "tabWidth": 65, + "tabXOffset": 10, + "hasSecondTab": false, + "secondTabText": "Send Back", + "secondTabOffset": 80, + "secondTabWidth": 65 + }, + "widgets_values": [ + 410513707389275, + "fixed", + 9, + 1, + "res_multistep", + "simple", + 1 + ] + }, + { + "id": 39, + "type": "CLIPLoader", + "pos": [ + 130.2638101844517, + 435.2545050421948 + ], + "size": [ + 270, + 106 + ], + "flags": {}, + "order": 0, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "CLIP", + "type": "CLIP", + "links": [ + 44 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.73", + "Node name for S&R": "CLIPLoader", + "models": [ + { + "name": "qwen_3_4b.safetensors", + "url": "https://huggingface.co/Comfy-Org/z_image_turbo/resolve/main/split_files/text_encoders/qwen_3_4b.safetensors", + "directory": "text_encoders" + } + ], + "enableTabs": false, + "tabWidth": 65, + "tabXOffset": 10, + "hasSecondTab": false, + "secondTabText": "Send Back", + "secondTabOffset": 80, + "secondTabWidth": 65 + }, + "widgets_values": [ + "Qwen_3-4B-abliterated.safetensors", + "lumina2", + "default" + ] + }, + { + "id": 40, + "type": "VAELoader", + "pos": [ + 130.2638101844517, + 585.2545050421948 + ], + "size": [ + 270, + 58 + ], + "flags": {}, + "order": 1, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "VAE", + "type": "VAE", + "links": [ + 39 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.73", + "Node name for S&R": "VAELoader", + "models": [ + { + "name": "ae.safetensors", + "url": "https://huggingface.co/Comfy-Org/z_image_turbo/resolve/main/split_files/vae/ae.safetensors", + "directory": "vae" + } + ], + "enableTabs": false, + "tabWidth": 65, + "tabXOffset": 10, + "hasSecondTab": false, + "secondTabText": "Send Back", + "secondTabOffset": 80, + "secondTabWidth": 65 + }, + "widgets_values": [ + "FLUX1\\ae.safetensors" + ] + }, + { + "id": 9, + "type": "SaveImage", + "pos": [ + 1240, + 260 + ], + "size": [ + 389.6898473104816, + 590.9817412927072 + ], + "flags": {}, + "order": 14, + "mode": 0, + "inputs": [ + { + "name": "images", + "type": "IMAGE", + "link": 45 + } + ], + "outputs": [], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.64", + "Node name for S&R": "SaveImage", + "enableTabs": false, + "tabWidth": 65, + "tabXOffset": 10, + "hasSecondTab": false, + "secondTabText": "Send Back", + "secondTabOffset": 80, + "secondTabWidth": 65 + }, + "widgets_values": [ + "z-image" + ] + }, + { + "id": 41, + "type": "EmptySD3LatentImage", + "pos": [ + 137.14793402245462, + 741.155182617626 + ], + "size": [ + 260, + 110 + ], + "flags": {}, + "order": 2, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "slot_index": 0, + "links": [ + 43 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.64", + "Node name for S&R": "EmptySD3LatentImage", + "enableTabs": false, + "tabWidth": 65, + "tabXOffset": 10, + "hasSecondTab": false, + "secondTabText": "Send Back", + "secondTabOffset": 80, + "secondTabWidth": 65 + }, + "widgets_values": [ + 2048, + 3072, + 1 + ] + }, + { + "id": 47, + "type": "ModelSamplingAuraFlow", + "pos": [ + 900.2638101844517, + 265.2545050421948 + ], + "size": [ + 310, + 60 + ], + "flags": {}, + "order": 11, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 47 + } + ], + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "slot_index": 0, + "links": [ + 40 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.64", + "Node name for S&R": "ModelSamplingAuraFlow", + "enableTabs": false, + "tabWidth": 65, + "tabXOffset": 10, + "hasSecondTab": false, + "secondTabText": "Send Back", + "secondTabOffset": 80, + "secondTabWidth": 65 + }, + "widgets_values": [ + 3 + ] + }, + { + "id": 45, + "type": "CLIPTextEncode", + "pos": [ + 450.2638101844517, + 305.2545050421948 + ], + "size": [ + 407.0496612122845, + 203.79758162535745 + ], + "flags": {}, + "order": 7, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 44 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 36, + 41 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.73", + "Node name for S&R": "CLIPTextEncode", + "enableTabs": false, + "tabWidth": 65, + "tabXOffset": 10, + "hasSecondTab": false, + "secondTabText": "Send Back", + "secondTabOffset": 80, + "secondTabWidth": 65 + }, + "widgets_values": [ + "Latina female with thick wavy hair, harbor boats and pastel houses behind. Breezy seaside light, warm tones, cinematic close-up." + ], + "color": "#232", + "bgcolor": "#353" + }, + { + "id": 42, + "type": "ConditioningZeroOut", + "pos": [ + 648.4624550335893, + 557.0851941424083 + ], + "size": [ + 197.712890625, + 26 + ], + "flags": {}, + "order": 9, + "mode": 0, + "inputs": [ + { + "name": "conditioning", + "type": "CONDITIONING", + "link": 36 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 42 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.73", + "Node name for S&R": "ConditioningZeroOut", + "enableTabs": false, + "tabWidth": 65, + "tabXOffset": 10, + "hasSecondTab": false, + "secondTabText": "Send Back", + "secondTabOffset": 80, + "secondTabWidth": 65 + }, + "widgets_values": [] + }, + { + "id": 46, + "type": "UNETLoader", + "pos": [ + 130.2638101844517, + 305.2545050421948 + ], + "size": [ + 270, + 82 + ], + "flags": {}, + "order": 3, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [ + 48 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.73", + "Node name for S&R": "UNETLoader", + "models": [ + { + "name": "z_image_turbo_bf16.safetensors", + "url": "https://huggingface.co/Comfy-Org/z_image_turbo/resolve/main/split_files/diffusion_models/z_image_turbo_bf16.safetensors", + "directory": "diffusion_models" + } + ], + "enableTabs": false, + "tabWidth": 65, + "tabXOffset": 10, + "hasSecondTab": false, + "secondTabText": "Send Back", + "secondTabOffset": 80, + "secondTabWidth": 65 + }, + "widgets_values": [ + "z_image_turbo_bf16.safetensors", + "default" + ] + }, + { + "id": 48, + "type": "DyPE_FLUX", + "pos": [ + 487.4055670233965, + 706.7051732742663 + ], + "size": [ + 342.5881686404282, + 326.75987991084776 + ], + "flags": {}, + "order": 10, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 49 + } + ], + "outputs": [ + { + "name": "Patched Model", + "type": "MODEL", + "links": [ + 47 + ] + } + ], + "properties": { + "cnr_id": "ComfyUI-DyPE", + "ver": "7dbea3b189ef5d75ead0f7bb5c237eee180ac19a", + "Node name for S&R": "DyPE_FLUX" + }, + "widgets_values": [ + 2048, + 2048, + "auto", + "vision_yarn", + true, + true, + 1024, + 1, + 2, + 2, + 0.5, + 1.15 + ], + "color": "#332922", + "bgcolor": "#593930" + }, + { + "id": 52, + "type": "MarkdownNote", + "pos": [ + 908.5210076660273, + 908.6339681882662 + ], + "size": [ + 297.9693678810893, + 137.84797136317843 + ], + "flags": {}, + "order": 4, + "mode": 0, + "inputs": [], + "outputs": [], + "title": "Better quality", + "properties": { + "ue_properties": { + "widget_ue_connectable": {}, + "version": "7.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "## Speckle noise\n\n* To eliminate white speckle noise, use a LoRA. [DeJPEG-LoRA](https://huggingface.co/wcde/Z-Image-Turbo-DeJPEG-Lora) works quite well. It also improves proportions.\n* Increasing dype_exponent can reduce this noise, but it may distort proportions.\n\n" + ], + "color": "#322", + "bgcolor": "#533" + }, + { + "id": 35, + "type": "MarkdownNote", + "pos": [ + -390, + 270 + ], + "size": [ + 489.2486851990984, + 317.3553719008264 + ], + "flags": { + "collapsed": false + }, + "order": 5, + "mode": 0, + "inputs": [], + "outputs": [], + "title": "Model link", + "properties": {}, + "widgets_values": [ + "## Model links\n\n**text_encoders**\n\n- [qwen_3_4b.safetensors](https://huggingface.co/Comfy-Org/z_image_turbo/resolve/main/split_files/text_encoders/qwen_3_4b.safetensors)\n\n**diffusion_models**\n\n- [z_image_turbo_bf16.safetensors](https://huggingface.co/Comfy-Org/z_image_turbo/resolve/main/split_files/diffusion_models/z_image_turbo_bf16.safetensors)\n\n**vae**\n\n- [ae.safetensors](https://huggingface.co/Comfy-Org/z_image_turbo/resolve/main/split_files/vae/ae.safetensors)\n\n\nModel Storage Location\n\n```\n📂 ComfyUI/\n├── 📂 models/\n│ ├── 📂 text_encoders/\n│ │ └── qwen_3_4b.safetensors\n│ ├── 📂 diffusion_models/\n│ │ └── z_image_turbo_bf16.safetensors\n│ └── 📂 vae/\n│ └── ae.safetensors\n```\n\n" + ], + "color": "#432", + "bgcolor": "#653" + }, + { + "id": 49, + "type": "MarkdownNote", + "pos": [ + -386.35832527136625, + 631.5235598806564 + ], + "size": [ + 481.8661447405933, + 328.1129300408643 + ], + "flags": {}, + "order": 6, + "mode": 0, + "inputs": [], + "outputs": [], + "title": "DyPE", + "properties": { + "ue_properties": { + "widget_ue_connectable": {}, + "version": "7.1", + "input_ue_unconnectable": {} + } + }, + "widgets_values": [ + "### Node Inputs\n\n* **`method`**: The extrapolation strategy.\n * **`vision_yarn`:** Best for 4K+ and non-square images. Fixes stretching and artifacts automatically.\n * **`yarn` / `ntk`**: Legacy methods. Use `yarn` with `yarn_alt_scaling` for manual control.\n* **`enable_dype`**: Toggles the dynamic (time-aware) algorithm. Keep enabled for best quality.\n* **`dype_scale`**: Magnitude of the frequency shift. Default: `2.0`.\n* **`dype_exponent`**: Aggressiveness of the dynamic schedule.\n * `2.0`: Best for **4K**.\n * `1.0`: Best for **2K**.\n * `0.5`: Best for **~1.5K**.\n* **`yarn_alt_scaling`**: *(Legacy `yarn` only)* Switch between Anisotropic (Sharper, potential stretching) and Isotropic (Softer, accurate geometry).\n* **`base_shift` / `max_shift`**: Advanced noise schedule controls. Defaults (`0.5` / `1.15`) are optimized for FLUX.\n\n\n## Join\n\n### [TokenDiffusion](https://t.me/TokenDiff) - AI for every home, creativity for every mind!\n\n### [TokenDiff Community Hub](https://t.me/TokenDiff_hub) - Questions, help, and thoughtful discussion. " + ], + "color": "#322", + "bgcolor": "#533" + }, + { + "id": 43, + "type": "VAEDecode", + "pos": [ + 1257.0059843684596, + 911.2044563819945 + ], + "size": [ + 210, + 46 + ], + "flags": {}, + "order": 13, + "mode": 0, + "inputs": [ + { + "name": "samples", + "type": "LATENT", + "link": 38 + }, + { + "name": "vae", + "type": "VAE", + "link": 39 + } + ], + "outputs": [ + { + "name": "IMAGE", + "type": "IMAGE", + "slot_index": 0, + "links": [ + 45 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.64", + "Node name for S&R": "VAEDecode", + "enableTabs": false, + "tabWidth": 65, + "tabXOffset": 10, + "hasSecondTab": false, + "secondTabText": "Send Back", + "secondTabOffset": 80, + "secondTabWidth": 65 + }, + "widgets_values": [] + }, + { + "id": 50, + "type": "LoraLoaderModelOnly", + "pos": [ + 133.36299999999994, + 926.2149999999997 + ], + "size": [ + 270, + 82 + ], + "flags": {}, + "order": 8, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 48 + } + ], + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [ + 49 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.76", + "Node name for S&R": "LoraLoaderModelOnly" + }, + "widgets_values": [ + "zit\\ench-ZI-dejpeg_lite.safetensors", + 1 + ] + } + ], + "links": [ + [ + 36, + 45, + 0, + 42, + 0, + "CONDITIONING" + ], + [ + 38, + 44, + 0, + 43, + 0, + "LATENT" + ], + [ + 39, + 40, + 0, + 43, + 1, + "VAE" + ], + [ + 40, + 47, + 0, + 44, + 0, + "MODEL" + ], + [ + 41, + 45, + 0, + 44, + 1, + "CONDITIONING" + ], + [ + 42, + 42, + 0, + 44, + 2, + "CONDITIONING" + ], + [ + 43, + 41, + 0, + 44, + 3, + "LATENT" + ], + [ + 44, + 39, + 0, + 45, + 0, + "CLIP" + ], + [ + 45, + 43, + 0, + 9, + 0, + "IMAGE" + ], + [ + 47, + 48, + 0, + 47, + 0, + "MODEL" + ], + [ + 48, + 46, + 0, + 50, + 0, + "MODEL" + ], + [ + 49, + 50, + 0, + 48, + 0, + "MODEL" + ] + ], + "groups": [ + { + "id": 2, + "title": "Step2 - Image size", + "bounding": [ + 120.2638101844517, + 665.2545050421948, + 290, + 200 + ], + "color": "#3f789e", + "font_size": 24, + "flags": {} + }, + { + "id": 3, + "title": "Step3 - Prompt", + "bounding": [ + 430.2638101844517, + 235.2545050421948, + 450, + 363.9631189996389 + ], + "color": "#3f789e", + "font_size": 24, + "flags": {} + }, + { + "id": 4, + "title": "Step1 - Load models", + "bounding": [ + 120.2638101844517, + 235.2545050421948, + 290, + 413.6 + ], + "color": "#3f789e", + "font_size": 24, + "flags": {} + }, + { + "id": 5, + "title": "Model Patching", + "bounding": [ + 436.9001236929169, + 612.8672841136505, + 443.02476814406367, + 434.8989256271392 + ], + "color": "#3f789e", + "font_size": 24, + "flags": {} + } + ], + "config": {}, + "extra": { + "ds": { + "scale": 0.7513148009015777, + "offset": [ + 490, + -160 + ] + }, + "frontendVersion": "1.33.10", + "VHS_latentpreview": false, + "VHS_latentpreviewrate": 0, + "VHS_MetadataImage": true, + "VHS_KeepIntermediate": true, + "workflowRendererVersion": "LG" + }, + "version": 0.4 +} \ No newline at end of file diff --git a/ComfyUI-DyPE/pyproject.toml b/ComfyUI-DyPE/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..11be8bac72776412d6b5692cb24fe7e1b7c361a8 --- /dev/null +++ b/ComfyUI-DyPE/pyproject.toml @@ -0,0 +1,15 @@ +[project] +name = "ComfyUI-DyPE" +description = "DyPE. Artifact-free 4K+ image generation. Qwen, Flux, Nunchacku, Z-Image" +version = "2.3.0" +license = {file = "LICENSE"} +dependencies = ["torch"] + +[project.urls] +Repository = "https://github.com/wildminder/ComfyUI-DyPE" +# Used by Comfy Registry https://comfyregistry.org + +[tool.comfy] +PublisherId = "wildai" +DisplayName = "ComfyUI-DyPE" +Icon = "" diff --git a/ComfyUI-DyPE/requirements.txt b/ComfyUI-DyPE/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..08ed5eeb4b9f080b780db7d3e0af6712866c0493 --- /dev/null +++ b/ComfyUI-DyPE/requirements.txt @@ -0,0 +1 @@ +torch \ No newline at end of file diff --git a/ComfyUI-DyPE/src/__init__.py b/ComfyUI-DyPE/src/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/ComfyUI-DyPE/src/__pycache__/base.cpython-310.pyc b/ComfyUI-DyPE/src/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16ffddf1aff30f178b9b4939ccc44caa830337a8 Binary files /dev/null and b/ComfyUI-DyPE/src/__pycache__/base.cpython-310.pyc differ diff --git a/ComfyUI-DyPE/src/base.py b/ComfyUI-DyPE/src/base.py new file mode 100644 index 0000000000000000000000000000000000000000..e4ff0fc55e8748ca8b445da735c81468c2c6e484 --- /dev/null +++ b/ComfyUI-DyPE/src/base.py @@ -0,0 +1,211 @@ +import torch +import torch.nn as nn +import math +from .rope import get_1d_dype_yarn_pos_embed, get_1d_yarn_pos_embed, get_1d_ntk_pos_embed + +class DyPEBasePosEmbed(nn.Module): + """ + Base class for Dynamic Position Extrapolation. + Handles the calculation of DyPE scaling factors and raw (cos, sin) components. + Subclasses must implement `forward` to format the output for specific model architectures. + """ + def __init__(self, theta: int, axes_dim: list[int], method: str = 'yarn', yarn_alt_scaling: bool = False, dype: bool = True, dype_scale: float = 2.0, dype_exponent: float = 2.0, base_resolution: int = 1024, dype_start_sigma: float = 1.0, base_patch_grid: tuple[int, int] = None): + super().__init__() + self.theta = theta + self.axes_dim = axes_dim + self.method = method + self.yarn_alt_scaling = yarn_alt_scaling + self.dype = True if method == 'vision_yarn' else (dype if method != 'base' else False) + self.dype_scale = dype_scale + self.dype_exponent = dype_exponent + self.base_resolution = base_resolution + self.dype_start_sigma = max(0.001, min(1.0, dype_start_sigma)) # Clamp 0.001-1.0 + + self.current_timestep = 1.0 + + # Determine Base Patch Grid and Max Patches + if base_patch_grid is None: + # Default heuristic: 1024px -> 128 latent -> 64 patches (assuming patch_size=2) + val = (self.base_resolution // 8) // 2 + self.base_patch_grid = (val, val) + elif isinstance(base_patch_grid, int): + self.base_patch_grid = (base_patch_grid, base_patch_grid) + else: + self.base_patch_grid = base_patch_grid + + self.base_patches = max(self.base_patch_grid) + + def set_timestep(self, timestep: float): + self.current_timestep = timestep + + @staticmethod + def _axis_token_span(axis_pos: torch.Tensor) -> float: + flat = axis_pos.float().reshape(-1) + + if flat.numel() <= 1: return 1.0 + + min_val, max_val = flat.min(), flat.max() + span = max_val - min_val + + if span <= 0: return 1.0 + + unique_vals = torch.unique(flat) + + if unique_vals.numel() <= 1: return 1.0 + + step = torch.diff(unique_vals).min().item() + + if step <= 1e-6: return float(flat.numel()) + return float((span / step) + 1.0) + + def _get_mscale(self, scale_global): + mscale_start = 0.1 * math.log(scale_global) + 1.0 + mscale_end = 1.0 + t_effective = self.current_timestep + t_norm = 1.0 if t_effective > self.dype_start_sigma else (t_effective / self.dype_start_sigma) + return mscale_end + (mscale_start - mscale_end) * math.pow(t_norm, self.dype_exponent) + + def _calc_vision_yarn_components(self, pos: torch.Tensor, freqs_dtype: torch.dtype): + n_axes = pos.shape[-1] + components = [] + + if n_axes >= 3: + h_span = self._axis_token_span(pos[..., 1]) + w_span = self._axis_token_span(pos[..., 2]) + scale_global = max(1.0, max(h_span/self.base_patch_grid[0], w_span/self.base_patch_grid[1])) + else: + max_current_patches = self._axis_token_span(pos) + scale_global = max(1.0, max_current_patches / self.base_patches) + + current_mscale = self._get_mscale(scale_global) + + for i in range(n_axes): + axis_pos = pos[..., i] + axis_dim = self.axes_dim[i] + current_patches = self._axis_token_span(axis_pos) + + common_kwargs = {'dim': axis_dim, 'pos': axis_pos, 'theta': self.theta, 'use_real': True, 'repeat_interleave_real': True, 'freqs_dtype': freqs_dtype} + dype_kwargs = {'dype': self.dype, 'current_timestep': self.current_timestep, 'dype_scale': self.dype_scale, 'dype_exponent': self.dype_exponent, 'ntk_scale': scale_global, 'override_mscale': current_mscale} + + if i > 0: + base_axis_len = self.base_patch_grid[i-1] if (n_axes >=3 and i-1 < len(self.base_patch_grid)) else self.base_patches + + scale_local = max(1.0, current_patches / base_axis_len) + dype_kwargs['linear_scale'] = scale_local + + if scale_global > 1.0: + cos, sin = get_1d_dype_yarn_pos_embed(**common_kwargs, ori_max_pe_len=base_axis_len, **dype_kwargs) + else: + cos, sin = get_1d_ntk_pos_embed(**common_kwargs, ntk_factor=1.0) + else: + cos, sin = get_1d_ntk_pos_embed(**common_kwargs, ntk_factor=1.0) + + components.append((cos, sin)) + + return components + + def _calc_yarn_components(self, pos: torch.Tensor, freqs_dtype: torch.dtype): + n_axes = pos.shape[-1] + components = [] + + if n_axes >= 3: + h_span = self._axis_token_span(pos[..., 1]) + w_span = self._axis_token_span(pos[..., 2]) + max_current_patches = max(h_span, w_span) + else: + max_current_patches = self._axis_token_span(pos) + + needs_extrapolation = (max_current_patches > self.base_patches) + + if needs_extrapolation and self.yarn_alt_scaling: + for i in range(n_axes): + axis_pos = pos[..., i] + axis_dim = self.axes_dim[i] + common_kwargs = {'dim': axis_dim, 'pos': axis_pos, 'theta': self.theta, 'use_real': True, 'repeat_interleave_real': True, 'freqs_dtype': freqs_dtype} + dype_kwargs = {'dype': self.dype, 'current_timestep': self.current_timestep, 'dype_scale': self.dype_scale, 'dype_exponent': self.dype_exponent} + + current_patches = self._axis_token_span(axis_pos) + base_axis_len = self.base_patch_grid[i-1] if (n_axes >=3 and i > 0 and i-1 < len(self.base_patch_grid)) else self.base_patches + + if i > 0 and current_patches > base_axis_len: + max_pe_len = torch.tensor(current_patches, dtype=freqs_dtype, device=pos.device) + cos, sin = get_1d_yarn_pos_embed(**common_kwargs, max_pe_len=max_pe_len, ori_max_pe_len=base_axis_len, **dype_kwargs, use_aggressive_mscale=True) + else: + cos, sin = get_1d_ntk_pos_embed(**common_kwargs, ntk_factor=1.0) + + components.append((cos, sin)) + else: + cos_full_spatial, sin_full_spatial = None, None + if needs_extrapolation: + spatial_axis_dim = self.axes_dim[1] + square_pos = torch.arange(0, max_current_patches, device=pos.device).float() + max_pe_len = torch.tensor(max_current_patches, dtype=freqs_dtype, device=pos.device) + + common_kwargs_spatial = {'dim': spatial_axis_dim, 'theta': self.theta, 'use_real': True, 'repeat_interleave_real': True, 'freqs_dtype': freqs_dtype} + dype_kwargs = {'dype': self.dype, 'current_timestep': self.current_timestep, 'dype_scale': self.dype_scale, 'dype_exponent': self.dype_exponent} + + cos_full_spatial, sin_full_spatial = get_1d_yarn_pos_embed( + **common_kwargs_spatial, pos=square_pos, max_pe_len=max_pe_len, ori_max_pe_len=self.base_patches, **dype_kwargs, use_aggressive_mscale=False + ) + + for i in range(n_axes): + axis_pos = pos[..., i] + axis_dim = self.axes_dim[i] + + if i > 0 and needs_extrapolation: + offset_indices = axis_pos.long() - axis_pos.long().min() + pos_indices = offset_indices.view(-1) + pos_indices = torch.clamp(pos_indices, max=cos_full_spatial.shape[0]-1) + + cos = cos_full_spatial[pos_indices].view(*axis_pos.shape, -1) + sin = sin_full_spatial[pos_indices].view(*axis_pos.shape, -1) + else: + common_kwargs = {'dim': axis_dim, 'pos': axis_pos, 'theta': self.theta, 'use_real': True, 'repeat_interleave_real': True, 'freqs_dtype': freqs_dtype} + cos, sin = get_1d_ntk_pos_embed(**common_kwargs, ntk_factor=1.0) + + components.append((cos, sin)) + + return components + + def _calc_ntk_components(self, pos: torch.Tensor, freqs_dtype: torch.dtype): + n_axes = pos.shape[-1] + components = [] + + if n_axes >= 3: + h_span = self._axis_token_span(pos[..., 1]) + w_span = self._axis_token_span(pos[..., 2]) + scale_global = max(1.0, max(h_span/self.base_patch_grid[0], w_span/self.base_patch_grid[1])) + else: + max_current_patches = self._axis_token_span(pos) + scale_global = max(1.0, max_current_patches / self.base_patches) + + for i in range(n_axes): + axis_pos = pos[..., i] + axis_dim = self.axes_dim[i] + common_kwargs = {'dim': axis_dim, 'pos': axis_pos, 'theta': self.theta, 'use_real': True, 'repeat_interleave_real': True, 'freqs_dtype': freqs_dtype} + + ntk_factor = 1.0 + if i > 0 and scale_global > 1.0: + base_ntk = scale_global ** (axis_dim / (axis_dim - 2)) + if self.dype: + k_t = self.dype_scale * (self.current_timestep ** self.dype_exponent) + ntk_factor = base_ntk ** k_t + else: + ntk_factor = base_ntk + ntk_factor = max(1.0, ntk_factor) + + cos, sin = get_1d_ntk_pos_embed(**common_kwargs, ntk_factor=ntk_factor) + components.append((cos, sin)) + return components + + # Public Interface + def get_components(self, pos: torch.Tensor, freqs_dtype: torch.dtype): + if self.method == 'vision_yarn': + return self._calc_vision_yarn_components(pos, freqs_dtype) + elif self.method == 'yarn': + return self._calc_yarn_components(pos, freqs_dtype) + else: + return self._calc_ntk_components(pos, freqs_dtype) + + def forward(self, ids: torch.Tensor) -> torch.Tensor: + raise NotImplementedError("Base class does not implement forward. Use a specific model subclass.") diff --git a/ComfyUI-DyPE/src/models/__init__.py b/ComfyUI-DyPE/src/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/ComfyUI-DyPE/src/models/__pycache__/__init__.cpython-310.pyc b/ComfyUI-DyPE/src/models/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6bf09d719e4d2bd43dce28286fea4b61bf789fa Binary files /dev/null and b/ComfyUI-DyPE/src/models/__pycache__/__init__.cpython-310.pyc differ diff --git a/ComfyUI-DyPE/src/models/__pycache__/flux.cpython-310.pyc b/ComfyUI-DyPE/src/models/__pycache__/flux.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72b57027a2fdcf8c48191a450da1ca94a22d777b Binary files /dev/null and b/ComfyUI-DyPE/src/models/__pycache__/flux.cpython-310.pyc differ diff --git a/ComfyUI-DyPE/src/models/__pycache__/nunchaku.cpython-310.pyc b/ComfyUI-DyPE/src/models/__pycache__/nunchaku.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd6e05ade8bee96091d99f5e904af65de2d7f1ed Binary files /dev/null and b/ComfyUI-DyPE/src/models/__pycache__/nunchaku.cpython-310.pyc differ diff --git a/ComfyUI-DyPE/src/models/__pycache__/qwen.cpython-310.pyc b/ComfyUI-DyPE/src/models/__pycache__/qwen.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19aaaa061d912c39760088b91cbd61ae26aa22e8 Binary files /dev/null and b/ComfyUI-DyPE/src/models/__pycache__/qwen.cpython-310.pyc differ diff --git a/ComfyUI-DyPE/src/models/__pycache__/zimage.cpython-310.pyc b/ComfyUI-DyPE/src/models/__pycache__/zimage.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7224b8c0ec0243144f61e4ec975ef1b472cc0d05 Binary files /dev/null and b/ComfyUI-DyPE/src/models/__pycache__/zimage.cpython-310.pyc differ diff --git a/ComfyUI-DyPE/src/models/flux.py b/ComfyUI-DyPE/src/models/flux.py new file mode 100644 index 0000000000000000000000000000000000000000..d9bbb0b067972d7f90a19e3e43dbc3966a1e8c84 --- /dev/null +++ b/ComfyUI-DyPE/src/models/flux.py @@ -0,0 +1,25 @@ +import torch +from ..base import DyPEBasePosEmbed + +class PosEmbedFlux(DyPEBasePosEmbed): + """ + DyPE Implementation for Standard ComfyUI Flux Models. + Output Format: Rotation Matrix (concatenated) -> (B, 1, L, D) + """ + def forward(self, ids: torch.Tensor) -> torch.Tensor: + pos = ids.float() + freqs_dtype = torch.bfloat16 if pos.device.type == 'cuda' else torch.float32 + + components = self.get_components(pos, freqs_dtype) + + emb_parts = [] + for cos, sin in components: + cos_reshaped = cos.view(*cos.shape[:-1], -1, 2)[..., :1] + sin_reshaped = sin.view(*sin.shape[:-1], -1, 2)[..., :1] + row1 = torch.cat([cos_reshaped, -sin_reshaped], dim=-1) + row2 = torch.cat([sin_reshaped, cos_reshaped], dim=-1) + matrix = torch.stack([row1, row2], dim=-2) + emb_parts.append(matrix) + + emb = torch.cat(emb_parts, dim=-3) + return emb.unsqueeze(1).to(ids.device) \ No newline at end of file diff --git a/ComfyUI-DyPE/src/models/nunchaku.py b/ComfyUI-DyPE/src/models/nunchaku.py new file mode 100644 index 0000000000000000000000000000000000000000..fe9159b3b840c5c86811e4e0bf7083ef6424dea0 --- /dev/null +++ b/ComfyUI-DyPE/src/models/nunchaku.py @@ -0,0 +1,66 @@ +import torch +from ..base import DyPEBasePosEmbed + +class PosEmbedNunchaku(DyPEBasePosEmbed): + """ + DyPE Implementation for Nunchaku Flux Models. + Output Format: Specific tensor layout for Nunchaku's custom RoPE kernel. + Shape: (B, M, D//2, 1, 2) + """ + def _axis_rope_from_cos_sin(self, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: + """ + Convert cos/sin with shape (..., M, D) into rope shape (B, M, D//2, 1, 2). + """ + if cos.dim() < 2: + raise RuntimeError(f"Unexpected cos shape {tuple(cos.shape)}") + + *lead, M, D = list(cos.shape) + if lead: + batch = int(torch.prod(torch.tensor(lead, dtype=torch.int64)).item()) + cos_flat = cos.reshape(batch, M, D) + sin_flat = sin.reshape(batch, M, D) + else: + batch = 1 + cos_flat = cos.reshape(1, M, D) + sin_flat = sin.reshape(1, M, D) + + assert D % 2 == 0, "rotary dimension must be even" + D_half = D // 2 + + # cos/sin were produced with repeat_interleave(2) style: [..., d0, d0, d1, d1, ...] + # view pairs and take the first of each pair. + cos_pairs = cos_flat.view(batch, M, D_half, 2) + sin_pairs = sin_flat.view(batch, M, D_half, 2) + cos_out = cos_pairs[..., 0] # (batch, M, D_half) + sin_out = sin_pairs[..., 0] # (batch, M, D_half) + + stacked = torch.stack([sin_out, cos_out], dim=-1) # (batch, M, D_half, 2) + rope = stacked.view(batch, M, D_half, 1, 2).contiguous() # (batch, M, D_half, 1, 2) + + if lead: + restore_shape = (*lead, M, D_half, 1, 2) + rope = rope.reshape(restore_shape) + + return rope.float() + + def forward(self, ids: torch.Tensor) -> torch.Tensor: + added_batch = False + if ids.ndim == 1: + ids = ids.unsqueeze(0) + added_batch = True + + pos = ids.float() + freqs_dtype = torch.float32 + + components = self.get_components(pos, freqs_dtype) + + emb_parts = [] + for cos, sin in components: + rope_i = self._axis_rope_from_cos_sin(cos, sin) + emb_parts.append(rope_i) + + # shape: (B, M, D_total//2, 1, 2) + emb = torch.cat(emb_parts, dim=-3) + + out = emb.unsqueeze(1).to(ids.device) + return out \ No newline at end of file diff --git a/ComfyUI-DyPE/src/models/qwen.py b/ComfyUI-DyPE/src/models/qwen.py new file mode 100644 index 0000000000000000000000000000000000000000..17c5056ebb512e179db45a045ae776a21295b0cc --- /dev/null +++ b/ComfyUI-DyPE/src/models/qwen.py @@ -0,0 +1,42 @@ +import torch +from ..base import DyPEBasePosEmbed + +class PosEmbedQwen(DyPEBasePosEmbed): + """ + DyPE Implementation for Qwen Image Models. + + Qwen's `apply_rope1` expects `D/2` frequency matrices (corresponding to coordinate pairs) + rather than the `D` repeated values produced by standard RoPE logic. + + Output Format: (B, 1, L, D/2, 2, 2) + This broadcasts correctly against input (B, H, L, D/2, 1, 2). + """ + def forward(self, ids: torch.Tensor) -> torch.Tensor: + pos = ids.float() + freqs_dtype = torch.bfloat16 if pos.device.type == 'cuda' else torch.float32 + + components = self.get_components(pos, freqs_dtype) + + emb_parts = [] + for cos, sin in components: + # cos: (B, L, D) (interleaved [c0, c0, c1, c1...]) + # Decimate to (B, L, D/2) -> [c0, c1...] + cos_half = cos[..., ::2] + sin_half = sin[..., ::2] + + # Construct Rotation Matrix Columns for apply_rope1 + # F0: [cos, sin] + col0 = torch.stack([cos_half, sin_half], dim=-1) # D/2, 2 + # F1: [-sin, cos] + col1 = torch.stack([-sin_half, cos_half], dim=-1) # D/2, 2 + + # Stack columns -> (D/2, 2, 2) + # Last dim is the selector [0, 1] used by apply_rope1 + matrix = torch.stack([col0, col1], dim=-1) + + emb_parts.append(matrix) + + emb = torch.cat(emb_parts, dim=-3) # Concatenate along Feature Dimension (D/2) + + out = emb.unsqueeze(1).to(ids.device) # (B, 1, L, Total_D/2, 2, 2) + return out \ No newline at end of file diff --git a/ComfyUI-DyPE/src/patch_utils.py b/ComfyUI-DyPE/src/patch_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5b066442328ce23b50afa6bb529a585377185a7c --- /dev/null +++ b/ComfyUI-DyPE/src/patch_utils.py @@ -0,0 +1,271 @@ +import math +import types +import torch +import torch.nn.functional as F +import comfy +from comfy.model_patcher import ModelPatcher +from comfy import model_sampling + +from .models.flux import PosEmbedFlux +from .models.nunchaku import PosEmbedNunchaku +from .models.qwen import PosEmbedQwen +from .models.zimage import PosEmbedZImage + +def apply_dype_to_model(model: ModelPatcher, model_type: str, width: int, height: int, method: str, yarn_alt_scaling: bool, enable_dype: bool, dype_scale: float, dype_exponent: float, base_shift: float, max_shift: float, base_resolution: int = 1024, dype_start_sigma: float = 1.0) -> ModelPatcher: + m = model.clone() + + is_nunchaku = False + is_qwen = False + is_z_image = False + + if model_type == "nunchaku": + is_nunchaku = True + elif model_type == "qwen": + is_qwen = True + elif model_type == "z_image": + is_z_image = True + elif model_type == "flux": + pass + else: # auto + if hasattr(m.model, "diffusion_model"): + dm = m.model.diffusion_model + model_class_name = dm.__class__.__name__ + if "QwenImage" in model_class_name: + is_qwen = True + elif hasattr(dm, "rope_embedder"): + is_z_image = True + elif hasattr(dm, "model") and hasattr(dm.model, "pos_embed"): + is_nunchaku = True + else: + raise ValueError("The provided model is not a compatible model.") + + new_dype_params = (width, height, base_shift, max_shift, method, yarn_alt_scaling, base_resolution, dype_start_sigma, is_nunchaku, is_qwen, is_z_image) + + should_patch_schedule = True + if hasattr(m.model, "_dype_params"): + if m.model._dype_params == new_dype_params: + should_patch_schedule = False + + base_patch_h_tokens = None + base_patch_w_tokens = None + if is_z_image: + axes_lens = getattr(m.model.diffusion_model, "axes_lens", None) + if isinstance(axes_lens, (list, tuple)) and len(axes_lens) >= 3: + base_patch_h_tokens = int(axes_lens[1]) + base_patch_w_tokens = int(axes_lens[2]) + + patch_size = 2 + try: + if is_nunchaku: + patch_size = m.model.diffusion_model.model.config.patch_size + else: + patch_size = m.model.diffusion_model.patch_size + except: + pass + + if base_patch_h_tokens is not None and base_patch_w_tokens is not None: + derived_base_patches = max(base_patch_h_tokens, base_patch_w_tokens) + derived_base_seq_len = base_patch_h_tokens * base_patch_w_tokens + else: + derived_base_patches = (base_resolution // 8) // 2 + derived_base_seq_len = derived_base_patches * derived_base_patches + + if enable_dype and should_patch_schedule: + try: + if isinstance(m.model.model_sampling, model_sampling.ModelSamplingFlux) or is_qwen or is_z_image: + latent_h, latent_w = height // 8, width // 8 + padded_h, padded_w = math.ceil(latent_h / patch_size) * patch_size, math.ceil(latent_w / patch_size) * patch_size + image_seq_len = (padded_h // patch_size) * (padded_w // patch_size) + + base_seq_len = derived_base_seq_len + max_seq_len = image_seq_len + + if max_seq_len <= base_seq_len: + dype_shift = base_shift + else: + slope = (max_shift - base_shift) / (max_seq_len - base_seq_len) + intercept = base_shift - slope * base_seq_len + dype_shift = image_seq_len * slope + intercept + + dype_shift = max(0.0, dype_shift) + + class DypeModelSamplingFlux(model_sampling.ModelSamplingFlux, model_sampling.CONST): + pass + + new_model_sampler = DypeModelSamplingFlux(m.model.model_config) + new_model_sampler.set_parameters(shift=dype_shift) + + m.add_object_patch("model_sampling", new_model_sampler) + m.model._dype_params = new_dype_params + except: + pass + + elif not enable_dype: + if hasattr(m.model, "_dype_params"): + class DefaultModelSamplingFlux(model_sampling.ModelSamplingFlux, model_sampling.CONST): pass + default_sampler = DefaultModelSamplingFlux(m.model.model_config) + m.add_object_patch("model_sampling", default_sampler) + del m.model._dype_params + + try: + if is_nunchaku: + orig_embedder = m.model.diffusion_model.model.pos_embed + target_patch_path = "diffusion_model.model.pos_embed" + elif is_z_image: + orig_embedder = m.model.diffusion_model.rope_embedder + target_patch_path = "diffusion_model.rope_embedder" + else: + orig_embedder = m.model.diffusion_model.pe_embedder + target_patch_path = "diffusion_model.pe_embedder" + + theta, axes_dim = orig_embedder.theta, orig_embedder.axes_dim + except AttributeError: + raise ValueError("The provided model is not a compatible FLUX/Qwen model structure.") + + embedder_cls = PosEmbedFlux + if is_nunchaku: + embedder_cls = PosEmbedNunchaku + elif is_qwen: + embedder_cls = PosEmbedQwen + elif is_z_image: + embedder_cls = PosEmbedZImage + + embedder_base_patches = derived_base_patches if is_z_image else None + + new_pe_embedder = embedder_cls( + theta, axes_dim, method, yarn_alt_scaling, enable_dype, + dype_scale, dype_exponent, base_resolution, dype_start_sigma, embedder_base_patches + ) + + m.add_object_patch(target_patch_path, new_pe_embedder) + + if is_z_image: + base_hw_override = None + if base_patch_h_tokens is not None and base_patch_w_tokens is not None: + base_hw_override = (base_patch_h_tokens, base_patch_w_tokens) + elif derived_base_patches is not None: + base_hw_override = (derived_base_patches, derived_base_patches) + + if base_hw_override is not None: + m.model.diffusion_model._dype_base_hw = base_hw_override + + def dype_patchify_and_embed(self, x, cap_feats, cap_mask, t, num_tokens, transformer_options={}, **kwargs): + bsz = len(x) + pH = pW = self.patch_size + device = x[0].device + + if self.pad_tokens_multiple is not None: + pad_extra = (-cap_feats.shape[1]) % self.pad_tokens_multiple + if pad_extra: + cap_pad = self.cap_pad_token.to(device=cap_feats.device, dtype=cap_feats.dtype, copy=True).unsqueeze(0) + cap_feats = torch.cat((cap_feats, cap_pad.repeat(cap_feats.shape[0], pad_extra, 1)), dim=1) + + cap_pos_ids = torch.zeros(bsz, cap_feats.shape[1], 3, dtype=torch.float32, device=device) + cap_pos_ids[:, :, 0] = torch.arange(cap_feats.shape[1], dtype=torch.float32, device=device) + 1.0 + + B, C, H, W = x.shape + x = self.x_embedder(x.view(B, C, H // pH, pH, W // pW, pW).permute(0, 2, 4, 3, 5, 1).flatten(3).flatten(1, 2)) + + requested_hw = transformer_options.get("dype_requested_hw", (height, width)) + rope_base_resolution = transformer_options.get("dype_base_resolution", base_resolution) + + raw_scale_y = float(rope_base_resolution) / max(1.0, float(requested_hw[0])) + raw_scale_x = float(rope_base_resolution) / max(1.0, float(requested_hw[1])) + + iso_scale = min(raw_scale_y, raw_scale_x) + rope_scale_y = iso_scale + rope_scale_x = iso_scale + + freq_scale_factor = 1.0 / iso_scale + new_pe_embedder.set_scale_hint(freq_scale_factor) + + h_start = 0.0 + w_start = 0.0 + + original_hw = transformer_options.get("dype_original_hw") + if original_hw is None: + original_hw = (H, W) + + H_tokens = math.ceil(original_hw[0] / pH) + W_tokens = math.ceil(original_hw[1] / pW) + + token_stride_y = (original_hw[0] / max(1, H_tokens)) * rope_scale_y + token_stride_x = (original_hw[1] / max(1, W_tokens)) * rope_scale_x + + shift_y = h_start * (original_hw[0] / max(1, H_tokens)) + shift_x = w_start * (original_hw[1] / max(1, W_tokens)) + + def _build_spatial_pos_ids(batch: int, total_len: int, width_tokens: int, cap_len: int, stride_y: float, stride_x: float, h_start: float, w_start: float, device: torch.device): + base_pos = torch.arange(total_len, device=device, dtype=torch.float32) + y = torch.div(base_pos, width_tokens, rounding_mode='floor') * stride_y + h_start + x = torch.remainder(base_pos, width_tokens) * stride_x + w_start + + pos = torch.stack([ + torch.full_like(base_pos, cap_len + 1), + y, + x + ], dim=-1) + return pos.unsqueeze(0).repeat(batch, 1, 1) + + base_img_tokens = H_tokens * W_tokens + x_pos_ids = _build_spatial_pos_ids(bsz, base_img_tokens, W_tokens, cap_feats.shape[1], token_stride_y, token_stride_x, shift_y, shift_x, device) + + if self.pad_tokens_multiple is not None: + pad_extra = (-x.shape[1]) % self.pad_tokens_multiple + if pad_extra: + x = torch.cat((x, self.x_pad_token.to(device=x.device, dtype=x.dtype, copy=True).unsqueeze(0).repeat(x.shape[0], pad_extra, 1)), dim=1) + + if x.shape[1] != x_pos_ids.shape[1]: + x_pos_ids = _build_spatial_pos_ids(bsz, x.shape[1], W_tokens, cap_feats.shape[1], token_stride_y, token_stride_x, shift_y, shift_x, device) + + freqs_cis = self.rope_embedder(torch.cat((cap_pos_ids, x_pos_ids), dim=1)).movedim(1, 2) + + for layer in self.context_refiner: + cap_feats = layer(cap_feats, cap_mask, freqs_cis[:, :cap_pos_ids.shape[1]], transformer_options=transformer_options) + + padded_img_mask = None + for layer in self.noise_refiner: + x = layer(x, padded_img_mask, freqs_cis[:, cap_pos_ids.shape[1]:], t, transformer_options=transformer_options) + + padded_full_embed = torch.cat((cap_feats, x), dim=1) + mask = None + img_sizes = [(H, W)] * bsz + l_effective_cap_len = [cap_feats.shape[1]] * bsz + return padded_full_embed, mask, img_sizes, l_effective_cap_len, freqs_cis + + # Skip patching patchify_and_embed for Z-Image - use original function + # to preserve ref_latents and other Z-Image specific arguments + pass # m.add_object_patch skipped for zimage compatibility + + sigma_max = m.model.model_sampling.sigma_max.item() + + def dype_wrapper_function(model_function, args_dict): + timestep_tensor = args_dict.get("timestep") + if timestep_tensor is not None and timestep_tensor.numel() > 0: + current_sigma = timestep_tensor.flatten()[0].item() + + if sigma_max > 0: + normalized_timestep = min(max(current_sigma / sigma_max, 0.0), 1.0) + new_pe_embedder.set_timestep(normalized_timestep) + + input_x, c = args_dict.get("input"), args_dict.get("c", {}) + + if is_z_image and isinstance(input_x, torch.Tensor) and input_x.dim() >= 4: + c = dict(c) + transformer_options = dict(c.get("transformer_options", {})) + transformer_options["dype_original_hw"] = (input_x.shape[-2], input_x.shape[-1]) + transformer_options["dype_requested_hw"] = (height, width) + transformer_options["dype_base_resolution"] = base_resolution + c["transformer_options"] = transformer_options + + try: + return model_function(input_x, args_dict.get("timestep"), **c) + except TypeError as e: + if "ref_latents" in str(e) or "ref_contexts" in str(e) or "siglip_feats" in str(e): + safe_c = {k: v for k, v in c.items() if k not in ("ref_latents", "ref_contexts", "siglip_feats")} + return model_function(input_x, args_dict.get("timestep"), **safe_c) + raise + + m.set_model_unet_function_wrapper(dype_wrapper_function) + + return m \ No newline at end of file diff --git a/ComfyUI-DyPE/src/rope.py b/ComfyUI-DyPE/src/rope.py new file mode 100644 index 0000000000000000000000000000000000000000..7592931a0c933ffd306b399e309ffa422c256aed --- /dev/null +++ b/ComfyUI-DyPE/src/rope.py @@ -0,0 +1,179 @@ +import torch +import numpy as np +import math + +def find_correction_factor(num_rotations, dim, base, max_position_embeddings): + return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base)) + +def find_correction_range(low_ratio, high_ratio, dim, base, ori_max_pe_len): + low = np.floor(find_correction_factor(low_ratio, dim, base, ori_max_pe_len)) + high = np.ceil(find_correction_factor(high_ratio, dim, base, ori_max_pe_len)) + return max(low, 0), min(high, dim-1) + +def linear_ramp_mask(min_val, max_val, dim): + if min_val == max_val: + max_val += 0.001 + linear_func = (torch.arange(dim, dtype=torch.float32) - min_val) / (max_val - min_val) + ramp_func = torch.clamp(linear_func, 0, 1) + return ramp_func + +def find_newbase_ntk(dim, base, scale): + return base * (scale ** (dim / (dim - 2))) + +# Magic is here...Vision YaRN +def get_1d_dype_yarn_pos_embed( + dim: int, + pos: torch.Tensor, + theta: float, + use_real: bool, + repeat_interleave_real: bool, + freqs_dtype: torch.dtype, + linear_scale: float, + ntk_scale: float, + ori_max_pe_len: int, + dype: bool, + current_timestep: float, + dype_scale: float, + dype_exponent: float, + override_mscale: float = None, +): + device = pos.device + linear_scale = max(linear_scale, 1.0) + ntk_scale = max(ntk_scale, 1.0) + + beta_0, beta_1 = 1.25, 0.75 + gamma_0, gamma_1 = 16, 2 + + if dype: + k_t = dype_scale * (current_timestep ** dype_exponent) + beta_0 = beta_0 ** k_t + beta_1 = beta_1 ** k_t + gamma_0 = gamma_0 ** k_t + gamma_1 = gamma_1 ** k_t + + freqs_base = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=freqs_dtype, device=device) / dim)) + freqs_linear = freqs_base / linear_scale + + new_base = find_newbase_ntk(dim, theta, ntk_scale) + if isinstance(new_base, torch.Tensor) and new_base.dim() > 0: + new_base = new_base.view(-1, 1) + freqs_ntk = 1.0 / torch.pow(new_base, (torch.arange(0, dim, 2, dtype=freqs_dtype, device=device) / dim)) + if freqs_ntk.dim() > 1: freqs_ntk = freqs_ntk.squeeze() + + low, high = find_correction_range(beta_0, beta_1, dim, theta, ori_max_pe_len) + low, high = max(0, low), min(dim // 2, high) + mask_beta = (1 - linear_ramp_mask(low, high, dim // 2).to(device).to(freqs_dtype)) + freqs = freqs_linear * (1 - mask_beta) + freqs_ntk * mask_beta + + low, high = find_correction_range(gamma_0, gamma_1, dim, theta, ori_max_pe_len) + low, high = max(0, low), min(dim // 2, high) + mask_gamma = (1 - linear_ramp_mask(low, high, dim // 2).to(device).to(freqs_dtype)) + freqs = freqs * (1 - mask_gamma) + freqs_base * mask_gamma + + freqs = torch.einsum("...s,d->...sd", pos, freqs) + + if use_real and repeat_interleave_real: + freqs_cos = freqs.cos().repeat_interleave(2, dim=-1).float() + freqs_sin = freqs.sin().repeat_interleave(2, dim=-1).float() + + if override_mscale is not None: + mscale = torch.tensor(override_mscale, dtype=freqs_dtype, device=device) + else: + mscale_val = 1.0 + 0.1 * math.log(ntk_scale) / math.sqrt(ntk_scale) + mscale = torch.tensor(mscale_val, dtype=freqs_dtype, device=device) + + return freqs_cos * mscale, freqs_sin * mscale + elif use_real: + return freqs.cos().float(), freqs.sin().float() + else: + return torch.polar(torch.ones_like(freqs), freqs) + +# YaRN +def get_1d_yarn_pos_embed( + dim: int, + pos: torch.Tensor, + theta: float, + use_real: bool, + repeat_interleave_real: bool, + freqs_dtype: torch.dtype, + max_pe_len: torch.Tensor, + ori_max_pe_len: int, + dype: bool, + current_timestep: float, + dype_scale: float, + dype_exponent: float, + use_aggressive_mscale: bool = False, +): + device = pos.device + scale = torch.clamp_min(max_pe_len / ori_max_pe_len, 1.0) + + beta_0, beta_1 = 1.25, 0.75 + gamma_0, gamma_1 = 16, 2 + + freqs_base = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=freqs_dtype, device=device) / dim)) + freqs_linear = 1.0 / torch.einsum('..., f -> ... f', scale, (theta ** (torch.arange(0, dim, 2, dtype=freqs_dtype, device=device) / dim))) + + new_base = find_newbase_ntk(dim, theta, scale) + if new_base.dim() > 0: new_base = new_base.view(-1, 1) + freqs_ntk = 1.0 / torch.pow(new_base, (torch.arange(0, dim, 2, dtype=freqs_dtype, device=device) / dim)) + if freqs_ntk.dim() > 1: freqs_ntk = freqs_ntk.squeeze() + + if dype: + k_t = dype_scale * (current_timestep ** dype_exponent) + beta_0 = beta_0 ** k_t + beta_1 = beta_1 ** k_t + + low, high = find_correction_range(beta_0, beta_1, dim, theta, ori_max_pe_len) + low, high = max(0, low), min(dim // 2, high) + freqs_mask = (1 - linear_ramp_mask(low, high, dim // 2).to(device).to(freqs_dtype)) + freqs = freqs_linear * (1 - freqs_mask) + freqs_ntk * freqs_mask + + if dype: + k_t = dype_scale * (current_timestep ** dype_exponent) + gamma_0 = gamma_0 ** k_t + gamma_1 = gamma_1 ** k_t + + low, high = find_correction_range(gamma_0, gamma_1, dim, theta, ori_max_pe_len) + low, high = max(0, low), min(dim // 2, high) + freqs_mask = (1 - linear_ramp_mask(low, high, dim // 2).to(device).to(freqs_dtype)) + freqs = freqs * (1 - freqs_mask) + freqs_base * freqs_mask + + freqs = torch.einsum("...s,d->...sd", pos, freqs) + + if use_real and repeat_interleave_real: + freqs_cos = freqs.cos().repeat_interleave(2, dim=-1).float() + freqs_sin = freqs.sin().repeat_interleave(2, dim=-1).float() + + mscale = None + if use_aggressive_mscale: + mscale = torch.where(scale <= 1., torch.tensor(1.0), 0.1 * torch.log(scale) + 1.0).to(scale) + else: + mscale = torch.where(scale <= 1., torch.tensor(1.0), 1.0 + 0.1 * torch.log(scale) / torch.sqrt(scale)).to(scale) + + return freqs_cos * mscale, freqs_sin * mscale + elif use_real: + return freqs.cos().float(), freqs.sin().float() + else: + return torch.polar(torch.ones_like(freqs), freqs) + +# NTK / Base +def get_1d_ntk_pos_embed( + dim: int, + pos: torch.Tensor, + theta: float, + use_real: bool, + repeat_interleave_real: bool, + freqs_dtype: torch.dtype, + ntk_factor: float, +): + device = pos.device + theta_ntk = theta * ntk_factor + freqs = 1.0 / (theta_ntk ** (torch.arange(0, dim, 2, dtype=freqs_dtype, device=device) / dim)) + freqs = torch.einsum("...s,d->...sd", pos, freqs) + + if use_real and repeat_interleave_real: + return freqs.cos().repeat_interleave(2, dim=-1).float(), freqs.sin().repeat_interleave(2, dim=-1).float() + elif use_real: + return freqs.cos().float(), freqs.sin().float() + else: + return torch.polar(torch.ones_like(freqs), freqs) \ No newline at end of file diff --git a/comfyui-art-venture/modules/__pycache__/image_utils.cpython-310.pyc b/comfyui-art-venture/modules/__pycache__/image_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88db71f176c9df99df3457877d69d2ccd77a8a55 Binary files /dev/null and b/comfyui-art-venture/modules/__pycache__/image_utils.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/__pycache__/ip_adapter_nodes.cpython-310.pyc b/comfyui-art-venture/modules/__pycache__/ip_adapter_nodes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9aff57860c1e5b52af52291ef806220a3a79640e Binary files /dev/null and b/comfyui-art-venture/modules/__pycache__/ip_adapter_nodes.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/__pycache__/logger.cpython-310.pyc b/comfyui-art-venture/modules/__pycache__/logger.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab68ea4284608c524f993b17186677e1d1ccffca Binary files /dev/null and b/comfyui-art-venture/modules/__pycache__/logger.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/__pycache__/masking.cpython-310.pyc b/comfyui-art-venture/modules/__pycache__/masking.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c389d108930195bae1435037eb84c75e0522972 Binary files /dev/null and b/comfyui-art-venture/modules/__pycache__/masking.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/__pycache__/model_utils.cpython-310.pyc b/comfyui-art-venture/modules/__pycache__/model_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0628e4b65fa72e15a2969ec27a11eb81e3c71de Binary files /dev/null and b/comfyui-art-venture/modules/__pycache__/model_utils.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/__pycache__/nodes.cpython-310.pyc b/comfyui-art-venture/modules/__pycache__/nodes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..404a6ee42549cbfaf09340dcb726820a54e9b5bb Binary files /dev/null and b/comfyui-art-venture/modules/__pycache__/nodes.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/__pycache__/utils.cpython-310.pyc b/comfyui-art-venture/modules/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a819f7dc4e78fd225074661797f4926ca00db133 Binary files /dev/null and b/comfyui-art-venture/modules/__pycache__/utils.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/sdxl_prompt_styler/__init__.py b/comfyui-art-venture/modules/sdxl_prompt_styler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..edb890e115261c8e917c3f3fbfffddd5ec5f351d --- /dev/null +++ b/comfyui-art-venture/modules/sdxl_prompt_styler/__init__.py @@ -0,0 +1,3 @@ +from .sdxl_prompt_styler import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS + +__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS'] diff --git a/comfyui-art-venture/modules/sdxl_prompt_styler/sdxl_prompt_styler.py b/comfyui-art-venture/modules/sdxl_prompt_styler/sdxl_prompt_styler.py new file mode 100644 index 0000000000000000000000000000000000000000..a8609e73858fbfb074b3336e1f3b6fc88c84ff76 --- /dev/null +++ b/comfyui-art-venture/modules/sdxl_prompt_styler/sdxl_prompt_styler.py @@ -0,0 +1,192 @@ +import os +import json + + +def read_json_file(file_path): + """ + Reads the content of a JSON file and returns it as a Python data structure. + """ + if not os.access(file_path, os.R_OK): + print(f"Warning: No read permissions for file {file_path}") + return None + + try: + with open(file_path, "r", encoding="utf-8") as file: + content = json.load(file) + # Check if the content matches the expected format. + if not all( + [ + "name" in item and "prompt" in item and "negative_prompt" in item + for item in content + ] + ): + print(f"Warning: Invalid content in file {file_path}") + return None + return content + except Exception as e: + print(f"An error occurred while reading {file_path}: {str(e)}") + return None + + +def read_sdxl_styles(json_data): + """ + Extracts style names from the provided data. + """ + if not isinstance(json_data, list): + print("Error: input data must be a list") + return [] + + return [ + item["name"] for item in json_data if isinstance(item, dict) and "name" in item + ] + + +def get_all_json_files(directory): + """ + Retrieves all JSON files present in the specified directory. + """ + return [ + os.path.join(directory, file) + for file in os.listdir(directory) + if file.endswith(".json") and os.path.isfile(os.path.join(directory, file)) + ] + + +def load_styles_from_directory(directory): + """ + Loads style names and combined data from all JSON files in the directory. + Ensures style names are unique by appending a suffix to duplicates. + """ + json_files = get_all_json_files(directory) + combined_data = [] + seen = set() + + for json_file in json_files: + json_data = read_json_file(json_file) + if json_data: + for item in json_data: + original_style = item["name"] + style = original_style + suffix = 1 + while style in seen: + style = f"{original_style}_{suffix}" + suffix += 1 + item["name"] = style + seen.add(style) + combined_data.append(item) + + unique_style_names = [ + item["name"] + for item in combined_data + if isinstance(item, dict) and "name" in item + ] + + return combined_data, unique_style_names + + +def read_sdxl_templates_replace_and_combine( + json_data, template_name, positive_prompt, negative_prompt +): + try: + # Check if json_data is a list + if not isinstance(json_data, list): + raise ValueError("Invalid JSON data. Expected a list of templates.") + + for template in json_data: + # Check if template contains 'name' and 'prompt' fields + if "name" not in template or "prompt" not in template: + raise ValueError("Invalid template. Missing 'name' or 'prompt' field.") + + # Replace {prompt} in the matching template + if template["name"] == template_name: + positive_prompt = template["prompt"].replace( + "{prompt}", positive_prompt + ) + + json_negative_prompt = template.get("negative_prompt", "") + if negative_prompt: + negative_prompt = ( + f"{json_negative_prompt}, {negative_prompt}" + if json_negative_prompt + else negative_prompt + ) + else: + negative_prompt = json_negative_prompt + + return positive_prompt, negative_prompt + + # If function hasn't returned yet, no matching template was found + raise ValueError(f"No template found with name '{template_name}'.") + + except Exception as e: + print(f"An error occurred: {str(e)}") + + +class SDXLPromptStyler: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(self): + current_directory = os.path.dirname(os.path.realpath(__file__)) + self.json_data, self.styles = load_styles_from_directory(current_directory) + + return { + "required": { + "text_positive": ("STRING", {"default": "", "multiline": True}), + "text_negative": ("STRING", {"default": "", "multiline": True}), + "style": ((self.styles),), + "log_prompt": (["No", "Yes"], {"default": "No"}), + }, + "optional": { + "style_name": ("STRING", {"multiline": False}), + }, + } + + RETURN_TYPES = ( + "STRING", + "STRING", + ) + RETURN_NAMES = ( + "positive_prompt_text_g", + "negative_prompt_text_g", + ) + FUNCTION = "prompt_styler" + CATEGORY = "utils" + + def prompt_styler( + self, text_positive, text_negative, style, log_prompt, style_name=None + ): + if style_name and style_name not in self.styles: + print(f"Warning: Style '{style_name}' not found. Using '{style}' instead.") + style_name = None + + if style_name: + style = style_name + + # Process and combine prompts in templates + # The function replaces the positive prompt placeholder in the template, + # and combines the negative prompt with the template's negative prompt, if they exist. + positive_prompt, negative_prompt = read_sdxl_templates_replace_and_combine( + self.json_data, style, text_positive, text_negative + ) + + # If logging is enabled (log_prompt is set to "Yes"), + # print the style, positive and negative text, and positive and negative prompts to the console + if log_prompt == "Yes": + print(f"style: {style}") + print(f"text_positive: {text_positive}") + print(f"text_negative: {text_negative}") + print(f"positive_prompt: {positive_prompt}") + print(f"negative_prompt: {negative_prompt}") + + return positive_prompt, negative_prompt + + +NODE_CLASS_MAPPINGS = { + "SDXLPromptStyler": SDXLPromptStyler, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "SDXLPromptStyler": "SDXL Prompt Styler", +} diff --git a/comfyui-art-venture/modules/sdxl_prompt_styler/sdxl_styles_twri.json b/comfyui-art-venture/modules/sdxl_prompt_styler/sdxl_styles_twri.json new file mode 100644 index 0000000000000000000000000000000000000000..687a19d2bf97d7d9f40d46fd4d89fec4a9f057b6 --- /dev/null +++ b/comfyui-art-venture/modules/sdxl_prompt_styler/sdxl_styles_twri.json @@ -0,0 +1,447 @@ +[ + { + "name": "ads-advertising", + "prompt": "advertising poster style {prompt} . Professional, modern, product-focused, commercial, eye-catching, highly detailed", + "negative_prompt": "noisy, blurry, amateurish, sloppy, unattractive" + }, + { + "name": "ads-automotive", + "prompt": "automotive advertisement style {prompt} . sleek, dynamic, professional, commercial, vehicle-focused, high-resolution, highly detailed", + "negative_prompt": "noisy, blurry, unattractive, sloppy, unprofessional" + }, + { + "name": "ads-corporate", + "prompt": "corporate branding style {prompt} . professional, clean, modern, sleek, minimalist, business-oriented, highly detailed", + "negative_prompt": "noisy, blurry, grungy, sloppy, cluttered, disorganized" + }, + { + "name": "ads-fashion editorial", + "prompt": "fashion editorial style {prompt} . high fashion, trendy, stylish, editorial, magazine style, professional, highly detailed", + "negative_prompt": "outdated, blurry, noisy, unattractive, sloppy" + }, + { + "name": "ads-food photography", + "prompt": "food photography style {prompt} . appetizing, professional, culinary, high-resolution, commercial, highly detailed", + "negative_prompt": "unappetizing, sloppy, unprofessional, noisy, blurry" + }, + { + "name": "ads-gourmet food photography", + "prompt": "gourmet food photo of {prompt} . soft natural lighting, macro details, vibrant colors, fresh ingredients, glistening textures, bokeh background, styled plating, wooden tabletop, garnished, tantalizing, editorial quality", + "negative_prompt": "cartoon, anime, sketch, grayscale, dull, overexposed, cluttered, messy plate, deformed" + }, + { + "name": "ads-luxury", + "prompt": "luxury product style {prompt} . elegant, sophisticated, high-end, luxurious, professional, highly detailed", + "negative_prompt": "cheap, noisy, blurry, unattractive, amateurish" + }, + { + "name": "ads-real estate", + "prompt": "real estate photography style {prompt} . professional, inviting, well-lit, high-resolution, property-focused, commercial, highly detailed", + "negative_prompt": "dark, blurry, unappealing, noisy, unprofessional" + }, + { + "name": "ads-retail", + "prompt": "retail packaging style {prompt} . vibrant, enticing, commercial, product-focused, eye-catching, professional, highly detailed", + "negative_prompt": "noisy, blurry, amateurish, sloppy, unattractive" + }, + { + "name": "artstyle-abstract", + "prompt": "abstract style {prompt} . non-representational, colors and shapes, expression of feelings, imaginative, highly detailed", + "negative_prompt": "realistic, photographic, figurative, concrete" + }, + { + "name": "artstyle-abstract expressionism", + "prompt": "abstract expressionist painting {prompt} . energetic brushwork, bold colors, abstract forms, expressive, emotional", + "negative_prompt": "realistic, photorealistic, low contrast, plain, simple, monochrome" + }, + { + "name": "artstyle-art deco", + "prompt": "art deco style {prompt} . geometric shapes, bold colors, luxurious, elegant, decorative, symmetrical, ornate, detailed", + "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, modernist, minimalist" + }, + { + "name": "artstyle-art nouveau", + "prompt": "art nouveau style {prompt} . elegant, decorative, curvilinear forms, nature-inspired, ornate, detailed", + "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, modernist, minimalist" + }, + { + "name": "artstyle-constructivist", + "prompt": "constructivist style {prompt} . geometric shapes, bold colors, dynamic composition, propaganda art style", + "negative_prompt": "realistic, photorealistic, low contrast, plain, simple, abstract expressionism" + }, + { + "name": "artstyle-cubist", + "prompt": "cubist artwork {prompt} . geometric shapes, abstract, innovative, revolutionary", + "negative_prompt": "anime, photorealistic, 35mm film, deformed, glitch, low contrast, noisy" + }, + { + "name": "artstyle-expressionist", + "prompt": "expressionist {prompt} . raw, emotional, dynamic, distortion for emotional effect, vibrant, use of unusual colors, detailed", + "negative_prompt": "realism, symmetry, quiet, calm, photo" + }, + { + "name": "artstyle-graffiti", + "prompt": "graffiti style {prompt} . street art, vibrant, urban, detailed, tag, mural", + "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, realism, photorealistic" + }, + { + "name": "artstyle-hyperrealism", + "prompt": "hyperrealistic art {prompt} . extremely high-resolution details, photographic, realism pushed to extreme, fine texture, incredibly lifelike", + "negative_prompt": "simplified, abstract, unrealistic, impressionistic, low resolution" + }, + { + "name": "artstyle-impressionist", + "prompt": "impressionist painting {prompt} . loose brushwork, vibrant color, light and shadow play, captures feeling over form", + "negative_prompt": "anime, photorealistic, 35mm film, deformed, glitch, low contrast, noisy" + }, + { + "name": "artstyle-pointillism", + "prompt": "pointillism style {prompt} . composed entirely of small, distinct dots of color, vibrant, highly detailed", + "negative_prompt": "line drawing, smooth shading, large color fields, simplistic" + }, + { + "name": "artstyle-pop art", + "prompt": "pop Art style {prompt} . bright colors, bold outlines, popular culture themes, ironic or kitsch", + "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, minimalist" + }, + { + "name": "artstyle-psychedelic", + "prompt": "psychedelic style {prompt} . vibrant colors, swirling patterns, abstract forms, surreal, trippy", + "negative_prompt": "monochrome, black and white, low contrast, realistic, photorealistic, plain, simple" + }, + { + "name": "artstyle-renaissance", + "prompt": "renaissance style {prompt} . realistic, perspective, light and shadow, religious or mythological themes, highly detailed", + "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, modernist, minimalist, abstract" + }, + { + "name": "artstyle-steampunk", + "prompt": "steampunk style {prompt} . antique, mechanical, brass and copper tones, gears, intricate, detailed", + "negative_prompt": "deformed, glitch, noisy, low contrast, anime, photorealistic" + }, + { + "name": "artstyle-surrealist", + "prompt": "surrealist art {prompt} . dreamlike, mysterious, provocative, symbolic, intricate, detailed", + "negative_prompt": "anime, photorealistic, realistic, deformed, glitch, noisy, low contrast" + }, + { + "name": "artstyle-typography", + "prompt": "typographic art {prompt} . stylized, intricate, detailed, artistic, text-based", + "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, realism, photorealistic" + }, + { + "name": "artstyle-watercolor", + "prompt": "watercolor painting {prompt} . vibrant, beautiful, painterly, detailed, textural, artistic", + "negative_prompt": "anime, photorealistic, 35mm film, deformed, glitch, low contrast, noisy" + }, + { + "name": "futuristic-biomechanical", + "prompt": "biomechanical style {prompt} . blend of organic and mechanical elements, futuristic, cybernetic, detailed, intricate", + "negative_prompt": "natural, rustic, primitive, organic, simplistic" + }, + { + "name": "futuristic-biomechanical cyberpunk", + "prompt": "biomechanical cyberpunk {prompt} . cybernetics, human-machine fusion, dystopian, organic meets artificial, dark, intricate, highly detailed", + "negative_prompt": "natural, colorful, deformed, sketch, low contrast, watercolor" + }, + { + "name": "futuristic-cybernetic", + "prompt": "cybernetic style {prompt} . futuristic, technological, cybernetic enhancements, robotics, artificial intelligence themes", + "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, historical, medieval" + }, + { + "name": "futuristic-cybernetic robot", + "prompt": "cybernetic robot {prompt} . android, AI, machine, metal, wires, tech, futuristic, highly detailed", + "negative_prompt": "organic, natural, human, sketch, watercolor, low contrast" + }, + { + "name": "futuristic-cyberpunk cityscape", + "prompt": "cyberpunk cityscape {prompt} . neon lights, dark alleys, skyscrapers, futuristic, vibrant colors, high contrast, highly detailed", + "negative_prompt": "natural, rural, deformed, low contrast, black and white, sketch, watercolor" + }, + { + "name": "futuristic-futuristic", + "prompt": "futuristic style {prompt} . sleek, modern, ultramodern, high tech, detailed", + "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, vintage, antique" + }, + { + "name": "futuristic-retro cyberpunk", + "prompt": "retro cyberpunk {prompt} . 80's inspired, synthwave, neon, vibrant, detailed, retro futurism", + "negative_prompt": "modern, desaturated, black and white, realism, low contrast" + }, + { + "name": "futuristic-retro futurism", + "prompt": "retro-futuristic {prompt} . vintage sci-fi, 50s and 60s style, atomic age, vibrant, highly detailed", + "negative_prompt": "contemporary, realistic, rustic, primitive" + }, + { + "name": "futuristic-sci-fi", + "prompt": "sci-fi style {prompt} . futuristic, technological, alien worlds, space themes, advanced civilizations", + "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, historical, medieval" + }, + { + "name": "futuristic-vaporwave", + "prompt": "vaporwave style {prompt} . retro aesthetic, cyberpunk, vibrant, neon colors, vintage 80s and 90s style, highly detailed", + "negative_prompt": "monochrome, muted colors, realism, rustic, minimalist, dark" + }, + { + "name": "game-bubble bobble", + "prompt": "Bubble Bobble style {prompt} . 8-bit, cute, pixelated, fantasy, vibrant, reminiscent of Bubble Bobble game", + "negative_prompt": "realistic, modern, photorealistic, violent, horror" + }, + { + "name": "game-cyberpunk game", + "prompt": "cyberpunk game style {prompt} . neon, dystopian, futuristic, digital, vibrant, detailed, high contrast, reminiscent of cyberpunk genre video games", + "negative_prompt": "historical, natural, rustic, low detailed" + }, + { + "name": "game-fighting game", + "prompt": "fighting game style {prompt} . dynamic, vibrant, action-packed, detailed character design, reminiscent of fighting video games", + "negative_prompt": "peaceful, calm, minimalist, photorealistic" + }, + { + "name": "game-gta", + "prompt": "GTA-style artwork {prompt} . satirical, exaggerated, pop art style, vibrant colors, iconic characters, action-packed", + "negative_prompt": "realistic, black and white, low contrast, impressionist, cubist, noisy, blurry, deformed" + }, + { + "name": "game-mario", + "prompt": "Super Mario style {prompt} . vibrant, cute, cartoony, fantasy, playful, reminiscent of Super Mario series", + "negative_prompt": "realistic, modern, horror, dystopian, violent" + }, + { + "name": "game-minecraft", + "prompt": "Minecraft style {prompt} . blocky, pixelated, vibrant colors, recognizable characters and objects, game assets", + "negative_prompt": "smooth, realistic, detailed, photorealistic, noise, blurry, deformed" + }, + { + "name": "game-pokemon", + "prompt": "Pokémon style {prompt} . vibrant, cute, anime, fantasy, reminiscent of Pokémon series", + "negative_prompt": "realistic, modern, horror, dystopian, violent" + }, + { + "name": "game-retro arcade", + "prompt": "retro arcade style {prompt} . 8-bit, pixelated, vibrant, classic video game, old school gaming, reminiscent of 80s and 90s arcade games", + "negative_prompt": "modern, ultra-high resolution, photorealistic, 3D" + }, + { + "name": "game-retro game", + "prompt": "retro game art {prompt} . 16-bit, vibrant colors, pixelated, nostalgic, charming, fun", + "negative_prompt": "realistic, photorealistic, 35mm film, deformed, glitch, low contrast, noisy" + }, + { + "name": "game-rpg fantasy game", + "prompt": "role-playing game (RPG) style fantasy {prompt} . detailed, vibrant, immersive, reminiscent of high fantasy RPG games", + "negative_prompt": "sci-fi, modern, urban, futuristic, low detailed" + }, + { + "name": "game-strategy game", + "prompt": "strategy game style {prompt} . overhead view, detailed map, units, reminiscent of real-time strategy video games", + "negative_prompt": "first-person view, modern, photorealistic" + }, + { + "name": "game-streetfighter", + "prompt": "Street Fighter style {prompt} . vibrant, dynamic, arcade, 2D fighting game, highly detailed, reminiscent of Street Fighter series", + "negative_prompt": "3D, realistic, modern, photorealistic, turn-based strategy" + }, + { + "name": "game-zelda", + "prompt": "Legend of Zelda style {prompt} . vibrant, fantasy, detailed, epic, heroic, reminiscent of The Legend of Zelda series", + "negative_prompt": "sci-fi, modern, realistic, horror" + }, + { + "name": "misc-architectural", + "prompt": "architectural style {prompt} . clean lines, geometric shapes, minimalist, modern, architectural drawing, highly detailed", + "negative_prompt": "curved lines, ornate, baroque, abstract, grunge" + }, + { + "name": "misc-disco", + "prompt": "disco-themed {prompt} . vibrant, groovy, retro 70s style, shiny disco balls, neon lights, dance floor, highly detailed", + "negative_prompt": "minimalist, rustic, monochrome, contemporary, simplistic" + }, + { + "name": "misc-dreamscape", + "prompt": "dreamscape {prompt} . surreal, ethereal, dreamy, mysterious, fantasy, highly detailed", + "negative_prompt": "realistic, concrete, ordinary, mundane" + }, + { + "name": "misc-dystopian", + "prompt": "dystopian style {prompt} . bleak, post-apocalyptic, somber, dramatic, highly detailed", + "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, cheerful, optimistic, vibrant, colorful" + }, + { + "name": "misc-fairy tale", + "prompt": "fairy tale {prompt} . magical, fantastical, enchanting, storybook style, highly detailed", + "negative_prompt": "realistic, modern, ordinary, mundane" + }, + { + "name": "misc-gothic", + "prompt": "gothic style {prompt} . dark, mysterious, haunting, dramatic, ornate, detailed", + "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, cheerful, optimistic" + }, + { + "name": "misc-grunge", + "prompt": "grunge style {prompt} . textured, distressed, vintage, edgy, punk rock vibe, dirty, noisy", + "negative_prompt": "smooth, clean, minimalist, sleek, modern, photorealistic" + }, + { + "name": "misc-horror", + "prompt": "horror-themed {prompt} . eerie, unsettling, dark, spooky, suspenseful, grim, highly detailed", + "negative_prompt": "cheerful, bright, vibrant, light-hearted, cute" + }, + { + "name": "misc-kawaii", + "prompt": "kawaii style {prompt} . cute, adorable, brightly colored, cheerful, anime influence, highly detailed", + "negative_prompt": "dark, scary, realistic, monochrome, abstract" + }, + { + "name": "misc-lovecraftian", + "prompt": "lovecraftian horror {prompt} . eldritch, cosmic horror, unknown, mysterious, surreal, highly detailed", + "negative_prompt": "light-hearted, mundane, familiar, simplistic, realistic" + }, + { + "name": "misc-macabre", + "prompt": "macabre style {prompt} . dark, gothic, grim, haunting, highly detailed", + "negative_prompt": "bright, cheerful, light-hearted, cartoonish, cute" + }, + { + "name": "misc-manga", + "prompt": "manga style {prompt} . vibrant, high-energy, detailed, iconic, Japanese comic style", + "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, Western comic style" + }, + { + "name": "misc-metropolis", + "prompt": "metropolis-themed {prompt} . urban, cityscape, skyscrapers, modern, futuristic, highly detailed", + "negative_prompt": "rural, natural, rustic, historical, simple" + }, + { + "name": "misc-minimalist", + "prompt": "minimalist style {prompt} . simple, clean, uncluttered, modern, elegant", + "negative_prompt": "ornate, complicated, highly detailed, cluttered, disordered, messy, noisy" + }, + { + "name": "misc-monochrome", + "prompt": "monochrome {prompt} . black and white, contrast, tone, texture, detailed", + "negative_prompt": "colorful, vibrant, noisy, blurry, deformed" + }, + { + "name": "misc-nautical", + "prompt": "nautical-themed {prompt} . sea, ocean, ships, maritime, beach, marine life, highly detailed", + "negative_prompt": "landlocked, desert, mountains, urban, rustic" + }, + { + "name": "misc-space", + "prompt": "space-themed {prompt} . cosmic, celestial, stars, galaxies, nebulas, planets, science fiction, highly detailed", + "negative_prompt": "earthly, mundane, ground-based, realism" + }, + { + "name": "misc-stained glass", + "prompt": "stained glass style {prompt} . vibrant, beautiful, translucent, intricate, detailed", + "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, realism, photorealistic" + }, + { + "name": "misc-techwear fashion", + "prompt": "techwear fashion {prompt} . futuristic, cyberpunk, urban, tactical, sleek, dark, highly detailed", + "negative_prompt": "vintage, rural, colorful, low contrast, realism, sketch, watercolor" + }, + { + "name": "misc-tribal", + "prompt": "tribal style {prompt} . indigenous, ethnic, traditional patterns, bold, natural colors, highly detailed", + "negative_prompt": "modern, futuristic, minimalist, pastel" + }, + { + "name": "misc-zentangle", + "prompt": "zentangle {prompt} . intricate, abstract, monochrome, patterns, meditative, highly detailed", + "negative_prompt": "colorful, representative, simplistic, large fields of color" + }, + { + "name": "papercraft-collage", + "prompt": "collage style {prompt} . mixed media, layered, textural, detailed, artistic", + "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, realism, photorealistic" + }, + { + "name": "papercraft-flat papercut", + "prompt": "flat papercut style {prompt} . silhouette, clean cuts, paper, sharp edges, minimalist, color block", + "negative_prompt": "3D, high detail, noise, grainy, blurry, painting, drawing, photo, disfigured" + }, + { + "name": "papercraft-kirigami", + "prompt": "kirigami representation of {prompt} . 3D, paper folding, paper cutting, Japanese, intricate, symmetrical, precision, clean lines", + "negative_prompt": "painting, drawing, 2D, noisy, blurry, deformed" + }, + { + "name": "papercraft-paper mache", + "prompt": "paper mache representation of {prompt} . 3D, sculptural, textured, handmade, vibrant, fun", + "negative_prompt": "2D, flat, photo, sketch, digital art, deformed, noisy, blurry" + }, + { + "name": "papercraft-paper quilling", + "prompt": "paper quilling art of {prompt} . intricate, delicate, curling, rolling, shaping, coiling, loops, 3D, dimensional, ornamental", + "negative_prompt": "photo, painting, drawing, 2D, flat, deformed, noisy, blurry" + }, + { + "name": "papercraft-papercut collage", + "prompt": "papercut collage of {prompt} . mixed media, textured paper, overlapping, asymmetrical, abstract, vibrant", + "negative_prompt": "photo, 3D, realistic, drawing, painting, high detail, disfigured" + }, + { + "name": "papercraft-papercut shadow box", + "prompt": "3D papercut shadow box of {prompt} . layered, dimensional, depth, silhouette, shadow, papercut, handmade, high contrast", + "negative_prompt": "painting, drawing, photo, 2D, flat, high detail, blurry, noisy, disfigured" + }, + { + "name": "papercraft-stacked papercut", + "prompt": "stacked papercut art of {prompt} . 3D, layered, dimensional, depth, precision cut, stacked layers, papercut, high contrast", + "negative_prompt": "2D, flat, noisy, blurry, painting, drawing, photo, deformed" + }, + { + "name": "papercraft-thick layered papercut", + "prompt": "thick layered papercut art of {prompt} . deep 3D, volumetric, dimensional, depth, thick paper, high stack, heavy texture, tangible layers", + "negative_prompt": "2D, flat, thin paper, low stack, smooth texture, painting, drawing, photo, deformed" + }, + { + "name": "photo-alien", + "prompt": "alien-themed {prompt} . extraterrestrial, cosmic, otherworldly, mysterious, sci-fi, highly detailed", + "negative_prompt": "earthly, mundane, common, realistic, simple" + }, + { + "name": "photo-film noir", + "prompt": "film noir style {prompt} . monochrome, high contrast, dramatic shadows, 1940s style, mysterious, cinematic", + "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, vibrant, colorful" + }, + { + "name": "photo-glamour", + "prompt": "glamorous photo {prompt} . high fashion, luxurious, extravagant, stylish, sensual, opulent, elegance, stunning beauty, professional, high contrast, detailed", + "negative_prompt": "ugly, deformed, noisy, blurry, distorted, grainy, sketch, low contrast, dull, plain, modest" + }, + { + "name": "photo-hdr", + "prompt": "HDR photo of {prompt} . High dynamic range, vivid, rich details, clear shadows and highlights, realistic, intense, enhanced contrast, highly detailed", + "negative_prompt": "flat, low contrast, oversaturated, underexposed, overexposed, blurred, noisy" + }, + { + "name": "photo-iphone photographic", + "prompt": "iphone photo {prompt} . large depth of field, deep depth of field, highly detailed", + "negative_prompt": "drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly, shallow depth of field, bokeh" + }, + { + "name": "photo-long exposure", + "prompt": "long exposure photo of {prompt} . Blurred motion, streaks of light, surreal, dreamy, ghosting effect, highly detailed", + "negative_prompt": "static, noisy, deformed, shaky, abrupt, flat, low contrast" + }, + { + "name": "photo-neon noir", + "prompt": "neon noir {prompt} . cyberpunk, dark, rainy streets, neon signs, high contrast, low light, vibrant, highly detailed", + "negative_prompt": "bright, sunny, daytime, low contrast, black and white, sketch, watercolor" + }, + { + "name": "photo-silhouette", + "prompt": "silhouette style {prompt} . high contrast, minimalistic, black and white, stark, dramatic", + "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, color, realism, photorealistic" + }, + { + "name": "photo-tilt-shift", + "prompt": "tilt-shift photo of {prompt} . selective focus, miniature effect, blurred background, highly detailed, vibrant, perspective control", + "negative_prompt": "blurry, noisy, deformed, flat, low contrast, unrealistic, oversaturated, underexposed" + } +] \ No newline at end of file diff --git a/comfyui-art-venture/modules/video/__init__.py b/comfyui-art-venture/modules/video/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dd5b544ba7df4b5b1a35ba4959a8d00093e4ba35 --- /dev/null +++ b/comfyui-art-venture/modules/video/__init__.py @@ -0,0 +1,223 @@ +import os +import torch + +import folder_paths +from comfy.utils import common_upscale + +from ..utils import load_module, pil2tensor + +custom_nodes = folder_paths.get_folder_paths("custom_nodes") +video_dir_names = ["VideoHelperSuite", "ComfyUI-VideoHelperSuite"] + +output_dir = folder_paths.get_output_directory() +input_dir = folder_paths.get_input_directory() +temp_dir = folder_paths.get_temp_directory() + +NODE_CLASS_MAPPINGS = {} +NODE_DISPLAY_NAME_MAPPINGS = {} + +try: + module_path = None + + for custom_node in custom_nodes: + custom_node = custom_node if not os.path.islink(custom_node) else os.readlink(custom_node) + for module_dir in video_dir_names: + if module_dir in os.listdir(custom_node): + module_path = os.path.abspath(os.path.join(custom_node, module_dir)) + break + + if module_path is None: + raise Exception("Could not find VideoHelperSuite nodes") + + module_path = os.path.join(module_path) + module = load_module(module_path) + print("Loaded VideoHelperSuite from", module_path) + + LoadVideoPath = module.NODE_CLASS_MAPPINGS["VHS_LoadVideoPath"] + + def target_size(width, height, force_size) -> tuple[int, int]: + force_size = force_size.split("x") + if force_size[0] == "?": + width = (width * int(force_size[1])) // height + width = int(width) + 4 & ~7 + height = int(force_size[1]) + elif force_size[1] == "?": + height = (height * int(force_size[0])) // width + height = int(height) + 4 & ~7 + width = int(force_size[0]) + + return (width, height) + + class UtilLoadVideoFromUrl(LoadVideoPath): + @classmethod + def INPUT_TYPES(s): + inputs = LoadVideoPath.INPUT_TYPES() + inputs["required"]["video"] = ("STRING", {"default": ""}) + return inputs + + CATEGORY = "Art Venture/Loaders" + FUNCTION = "load" + RETURN_TYPES = ("IMAGE", "INT", "BOOLEAN") + RETURN_NAMES = ("frames", "frame_count", "has_video") + OUTPUT_IS_LIST = (True, True, False) + + def load_gif( + self, + gif_path: str, + force_rate: int, + force_size: str, + skip_first_frames: int, + frame_load_cap: int, + select_every_nth: int, + ): + from PIL import Image, ImageSequence + + image = Image.open(gif_path) + frames = [] + total_frames_evaluated = -1 + + if force_rate != 0: + print(f"Force rate is not supported for gifs/webps") + if frame_load_cap == 0: + frame_load_cap = 999999999 + + for i, frame in enumerate(ImageSequence.Iterator(image)): + if i < skip_first_frames: + continue + elif i >= skip_first_frames + frame_load_cap: + break + else: + total_frames_evaluated += 1 + if total_frames_evaluated % select_every_nth == 0: + frames.append(pil2tensor(frame.copy().convert("RGB"))) + + images = torch.cat(frames, dim=0) + + if force_size != "Disabled": + height = images.shape[1] + width = images.shape[2] + new_size = target_size(width, height, force_size) + if new_size[0] != width or new_size[1] != height: + s = images.movedim(-1, 1) + s = common_upscale(s, new_size[0], new_size[1], "lanczos", "disabled") + images = s.movedim(1, -1) + + return (images, len(frames)) + + def load_url(self, video: str, **kwargs): + url = video.strip('"') + + if url == "": + return (None, 0) + + if os.path.isfile(url): + pass + elif url.startswith("file://"): + url = url[7:] + url = os.path.abspath(url) + + if not os.path.isfile(url): + raise Exception(f"File {url} does not exist") + + if url.startswith(input_dir): + video = url[len(input_dir) + 1 :] + " [input]" + elif url.startswith(output_dir): + video = url[len(output_dir) + 1 :] + " [output]" + elif url.startswith(temp_dir): + video = url[len(temp_dir) + 1 :] + " [temp]" + else: + # move file to temp_dir + import shutil + + tempdir = os.path.join(temp_dir, "video") + if not os.path.exists(tempdir): + os.makedirs(tempfile, exist_ok=True) + + filename = os.path.basename(url) + filepath = os.path.join(tempdir, filename) + + i = 1 + split = os.path.splitext(filename) + while os.path.exists(filepath): + filename = f"{split[0]} ({i}){split[1]}" + filepath = os.path.join(tempdir, filename) + i += 1 + + shutil.copy(url, filepath) + video = "video/" + filename + " [temp]" + elif url.startswith("http://") or url.startswith("https://"): + from torch.hub import download_url_to_file + from urllib.parse import urlparse + + parts = urlparse(url) + filename = os.path.basename(parts.path) + tempfile = os.path.join(temp_dir, "video") + if not os.path.exists(tempfile): + os.makedirs(tempfile, exist_ok=True) + tempfile = os.path.join(tempfile, filename) + + print(f'Downloading: "{url}" to {tempfile}\n') + download_url_to_file(url, tempfile, progress=True) + + video = "video/" + filename + " [temp]" + elif url.startswith(("/view?", "/api/view?")): + from urllib.parse import parse_qs + + qs_idx = url.find("?") + qs = parse_qs(url[qs_idx + 1:]) + filename = qs.get("name", qs.get("filename", None)) + if filename is None: + raise Exception(f"Invalid url: {url}") + + filename = filename[0] + subfolder = qs.get("subfolder", None) + if subfolder is not None: + filename = os.path.join(subfolder[0], filename) + + dirtype = qs.get("type", ["input"]) + video = f"{filename} [{dirtype[0]}]" + else: + raise Exception(f"Invalid url: {url}") + + if ".gif [" in video.lower() or ".webp [" in video.lower(): + gif_path = folder_paths.get_annotated_filepath(video.strip('"')) + res = self.load_gif(gif_path, **kwargs) + else: + res = self.load_video(video=video, **kwargs) + + return res + + def load(self, video: str, **kwargs): + urls = video.strip().split("\n") + + videos = [] + frame_counts = [] + + for url in urls: + images, frame_count = self.load_url(url, **kwargs) + if images is not None and frame_count > 0: + videos.append(images) + frame_counts.append(frame_count) + + has_video = len(videos) > 0 + if not has_video: + image = torch.zeros((1, 64, 64, 3), dtype=torch.float32, device="cpu") + videos.append(image) + frame_counts.append(1) + + return (videos, frame_counts, has_video) + + @classmethod + def IS_CHANGED(s, video: str, **kwargs): + return video + + @classmethod + def VALIDATE_INPUTS(s, **kwargs): + return True + + NODE_CLASS_MAPPINGS["LoadVideoFromUrl"] = UtilLoadVideoFromUrl + NODE_DISPLAY_NAME_MAPPINGS["LoadVideoFromUrl"] = "Load Video From Url" + + +except Exception as e: + print(e) diff --git a/comfyui-custom-scripts/.github/workflows/publish.yml b/comfyui-custom-scripts/.github/workflows/publish.yml new file mode 100644 index 0000000000000000000000000000000000000000..c9c70bf7f47b9e294ac2436b8fe2a2b8878bc106 --- /dev/null +++ b/comfyui-custom-scripts/.github/workflows/publish.yml @@ -0,0 +1,25 @@ +name: Publish to Comfy registry +on: + workflow_dispatch: + push: + branches: + - main + paths: + - "pyproject.toml" + +permissions: + issues: write + +jobs: + publish-node: + name: Publish Custom Node to registry + runs-on: ubuntu-latest + if: ${{ github.repository_owner == 'pythongosssss' }} + steps: + - name: Check out code + uses: actions/checkout@v4 + - name: Publish Custom Node + uses: Comfy-Org/publish-node-action@v1 + with: + ## Add your own personal access token to your Github Repository secrets and reference it here. + personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }} diff --git a/comfyui-custom-scripts/.gitignore b/comfyui-custom-scripts/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..8d303a4effdf5bf2a332042b2cb31a77589ab333 --- /dev/null +++ b/comfyui-custom-scripts/.gitignore @@ -0,0 +1,5 @@ +__pycache__ +pysssss.json +user/autocomplete.txt +web/js/assets/favicon.user.ico +web/js/assets/favicon-active.user.ico \ No newline at end of file diff --git a/comfyui-custom-scripts/.tracking b/comfyui-custom-scripts/.tracking new file mode 100644 index 0000000000000000000000000000000000000000..bc5b1cc664b2af6fa0b1d0ccb1cb92957c0957fd --- /dev/null +++ b/comfyui-custom-scripts/.tracking @@ -0,0 +1,68 @@ +.github/workflows/publish.yml +.gitignore +LICENSE +README.md +__init__.py +py/autocomplete.py +py/better_combos.py +py/constrain_image.py +py/constrain_image_for_video.py +py/math_expression.py +py/model_info.py +py/play_sound.py +py/repeater.py +py/reroute_primitive.py +py/show_text.py +py/string_function.py +py/system_notification.py +py/text_files.py +py/workflows.py +pyproject.toml +pysssss.default.json +pysssss.example.json +pysssss.py +user/text_file_dirs.json +web/js/assets/canvas2svg.js +web/js/assets/favicon-active.ico +web/js/assets/favicon.ico +web/js/assets/no-image.png +web/js/assets/notify.mp3 +web/js/autocompleter.js +web/js/betterCombos.js +web/js/common/autocomplete.css +web/js/common/autocomplete.js +web/js/common/binding.js +web/js/common/lightbox.css +web/js/common/lightbox.js +web/js/common/modelInfoDialog.css +web/js/common/modelInfoDialog.js +web/js/common/spinner.css +web/js/common/spinner.js +web/js/common/utils.js +web/js/contextMenuHook.js +web/js/customColors.js +web/js/faviconStatus.js +web/js/graphArrange.js +web/js/imageFeed.js +web/js/kSamplerAdvDenoise.js +web/js/linkRenderMode.js +web/js/mathExpression.js +web/js/middleClickAddDefaultNode.js +web/js/modelInfo.js +web/js/nodeFinder.js +web/js/playSound.js +web/js/presetText.js +web/js/quickNodes.js +web/js/repeater.js +web/js/reroutePrimitive.js +web/js/showImageOnMenu.js +web/js/showText.js +web/js/snapToGrid.js +web/js/snapToGridGuide.js +web/js/stringFunction.js +web/js/swapResolution.js +web/js/systemNotification.js +web/js/useNumberInputPrompt.js +web/js/widgetDefaults.js +web/js/workflowImage.js +web/js/workflows.js \ No newline at end of file diff --git a/comfyui-custom-scripts/LICENSE b/comfyui-custom-scripts/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..acf31806a2507192169eca2137ea9ceb7685f51c --- /dev/null +++ b/comfyui-custom-scripts/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 pythongosssss + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/comfyui-custom-scripts/README.md b/comfyui-custom-scripts/README.md new file mode 100644 index 0000000000000000000000000000000000000000..690bfe1c46018bdd63385abf77a58d226388623f --- /dev/null +++ b/comfyui-custom-scripts/README.md @@ -0,0 +1,160 @@ +# ComfyUI-Custom-Scripts + +### ⚠️ While these extensions work for the most part, i'm very busy at the moment and so unable to keep on top of everything here, thanks for your patience! + +# Installation + +1. Clone the repository: +`git clone https://github.com/pythongosssss/ComfyUI-Custom-Scripts.git` +to your ComfyUI `custom_nodes` directory + + The script will then automatically install all custom scripts and nodes. + It will attempt to use symlinks and junctions to prevent having to copy files and keep them up to date. + +- For uninstallation: + - Delete the cloned repo in `custom_nodes` + - Ensure `web/extensions/pysssss/CustomScripts` has also been removed + +# Update +1. Navigate to the cloned repo e.g. `custom_nodes/ComfyUI-Custom-Scripts` +2. `git pull` + +# Features + +## Autocomplete +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/b5971135-414f-4f4e-a6cf-2650dc01085f) +Provides embedding and custom word autocomplete. You can view embedding details by clicking on the info icon on the list. +Define your list of custom words via the settings. +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/160ef61c-7d7e-49d0-b60f-5a1501b74c9d) +You can quickly default to danbooru tags using the Load button, or load/manage other custom word lists. +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/cc180b35-5f45-442f-9285-3ddf3fa320d0) + +## Auto Arrange Graph +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/04b06081-ca6f-4c0f-8584-d0a157c36747) +Adds a menu option to auto arrange the graph in order of execution, this makes very wide graphs! + +## Always Snap to Grid +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/66f36d1f-e579-4959-9880-9a9624922e3a) +Adds a setting to make moving nodes always snap to grid. + +## [Testing] "Better" Loader Lists +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/664caa71-f25f-4a96-a04a-1466d6b2b8b4) +Adds custom Lora and Checkpoint loader nodes, these have the ability to show preview images, just place a png or jpg next to the file and it'll display in the list on hover (e.g. sdxl.safetensors and sdxl.png). +Optionally enable subfolders via the settings: +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/e15b5e83-4f9d-4d57-8324-742bedf75439) +Adds an "examples" widget to load sample prompts, triggerwords, etc: +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/ad1751e4-4c85-42e7-9490-e94fb1cbc8e7) +These should be stored in a folder matching the name of the model, e.g. if it is `loras/add_detail.safetensors` put your files in as `loras/add_detail/*.txt` +To quickly save a generated image as the preview to use for the model, you can right click on an image on a node, and select Save as Preview and choose the model to save the preview for: +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/9fa8e9db-27b3-45cb-85c2-0860a238fd3a) + +## Checkpoint/LoRA/Embedding Info +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/6b67bf40-ee17-4fa6-a0c1-7947066bafc2) +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/32405df6-b367-404f-a5df-2d4347089a9e) +Adds "View Info" menu option to view details about the selected LoRA or Checkpoint. To view embedding details, click the info button when using embedding autocomplete. + +## Constrain Image +Adds a node for resizing an image to a max & min size optionally cropping if required. + +## Custom Colors +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/fa7883f3-f81c-49f6-9ab6-9526e4debab6) +Adds a custom color picker to nodes & groups + +## Favicon Status +![image](https://user-images.githubusercontent.com/125205205/230171227-31f061a6-6324-4976-bed9-723a87500cf3.png) +![image](https://user-images.githubusercontent.com/125205205/230171445-c7202a45-b511-4d69-87fa-945ad44c063f.png) +Adds a favicon and title to the window, favicon changes color while generating and the window title includes the number of prompts in the queue + +## Image Feed +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/caea0d48-85b9-4ca9-9771-5c795db35fbc) +Adds a panel showing images that have been generated in the current session, you can control the direction that images are added and the position of the panel via the ComfyUI settings screen and the size of the panel and the images via the sliders at the top of the panel. +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/ca093d38-41a3-4647-9223-5bd0b9ee4f1e) + +## KSampler (Advanced) denoise helper +Provides a simple method to set custom denoise on the advanced sampler +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/42946bd8-0078-4c7a-bfe9-7adb1382b5e2) +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/7cfccb22-f155-4848-934b-a2b2a6efe16f) + +## Math Expression +Allows for evaluating complex expressions using values from the graph. You can input `INT`, `FLOAT`, `IMAGE` and `LATENT` values. +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/1593edde-67b8-45d8-88cb-e75f52dba039) +Other nodes values can be referenced via the `Node name for S&R` via the `Properties` menu item on a node, or the node title. +Supported operators: `+ - * /` (basic ops) `//` (floor division) `**` (power) `^` (xor) `%` (mod) +Supported functions `floor(num, dp?)` `floor(num)` `ceil(num)` `randomint(min,max)` +If using a `LATENT` or `IMAGE` you can get the dimensions using `a.width` or `a.height` where `a` is the input name. + +## Node Finder +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/177d2b67-acbc-4ec3-ab31-7c295a98c194) +Adds a menu item for following/jumping to the executing node, and a menu to quickly go to a node of a specific type. + +## Preset Text +![image](https://user-images.githubusercontent.com/125205205/230173939-08459efc-785b-46da-93d1-b02f0300c6f4.png) +Adds a node that lets you save and use text presets (e.g. for your 'normal' negatives) + +## Quick Nodes +![image](https://user-images.githubusercontent.com/125205205/230174266-5232831a-a03b-4bf7-bc8b-c45466a0bc64.png) +Adds various menu items to some nodes for quickly setting up common parts of graphs + +## Play Sound +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/9bcf9fb3-5898-4432-a974-fb1e17d3b7e8) +Plays a sound when the node is executed, either after each prompt or only when the queue is empty for queuing multiple prompts. +You can customize the sound by replacing the mp3 file `ComfyUI/custom_nodes/ComfyUI-Custom-Scripts/web/js/assets/notify.mp3` + +## System Notification +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/30354775/993fd783-5cd6-4779-aa97-173bc06cc405) +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/30354775/e45227fb-5714-4f45-b96b-6601902ef6e2) + +Sends a system notification via the browser when the node is executed, either after each prompt or only when the queue is empty for queuing multiple prompts. + +## [WIP] Repeater +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/ec0dac25-14e4-4d44-b975-52193656709d) +Node allows you to either create a list of N repeats of the input node, or create N outputs from the input node. +You can optionally decide if you want to reuse the input node, or create a new instance each time (e.g. a Checkpoint Loader would want to be re-used, but a random number would want to be unique) +TODO: Type safety on the wildcard outputs to require match with input + +## Show Text +![image](https://user-images.githubusercontent.com/125205205/230174888-c004fd48-da78-4de9-81c2-93a866fcfcd1.png) +Takes input from a node that produces a string and displays it, useful for things like interrogator, prompt generators, etc. + +## Show Image on Menu +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/b6ab58f2-583b-448c-bcfc-f93f5cdab0fc) +Shows the current generating image on the menu at the bottom, you can disable this via the settings menu. + +## String Function +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/01107137-8a93-4765-bae0-fcc110a09091) +Supports appending and replacing text +`tidy_tags` will add commas between parts when in `append` mode. +`replace` mode supports regex replace by using `/your regex here/` and you can reference capturing groups using `\number` e.g. `\1` + +## Touch Support +Provides basic support for touch screen devices, its not perfect but better than nothing + +## Widget Defaults +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/3d675032-2b19-4da8-a7d7-fa2d7c555daa) +Allows you to specify default values for widgets when adding new nodes, the values are configured via the settings menu +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/7b57a3d8-98d3-46e9-9b33-6645c0da41e7) + +## Workflows +Adds options to the menu for saving + loading workflows: +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/7b5a3012-4c59-47c6-8eea-85cf534403ea) + +## Workflow Images +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/06453fd2-c020-46ee-a7db-2b8bf5bcba7e) +Adds menu options for importing/exporting the graph as SVG and PNG showing a view of the nodes + +## (Testing) Reroute Primitive +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/8b870eef-d572-43f9-b394-cfa7abbd2f98) Provides a node that allows rerouting primitives. +The node can also be collapsed to a single point that you can drag around. +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/a9bd0112-cf8f-44f3-af6d-f9a8fed152a7) +Warning: Don't use normal reroutes or primitives with these nodes, it isn't tested and this node replaces their functionality. + +
+
+ + +## WD14 Tagger +Moved to: https://github.com/pythongosssss/ComfyUI-WD14-Tagger + +## ~~Lock Nodes & Groups~~ +This is now a standard feature of ComfyUI +~~Adds a lock option to nodes & groups that prevents you from moving them until unlocked~~ diff --git a/comfyui-custom-scripts/__init__.py b/comfyui-custom-scripts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ae43dd2090ce782074bf72f2b7f49ad28dff1a5c --- /dev/null +++ b/comfyui-custom-scripts/__init__.py @@ -0,0 +1,25 @@ +import importlib.util +import glob +import os +import sys +from .pysssss import init, get_ext_dir + +NODE_CLASS_MAPPINGS = {} +NODE_DISPLAY_NAME_MAPPINGS = {} + +if init(): + py = get_ext_dir("py") + files = glob.glob(os.path.join(py, "*.py"), recursive=False) + for file in files: + name = os.path.splitext(file)[0] + spec = importlib.util.spec_from_file_location(name, file) + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + if hasattr(module, "NODE_CLASS_MAPPINGS") and getattr(module, "NODE_CLASS_MAPPINGS") is not None: + NODE_CLASS_MAPPINGS.update(module.NODE_CLASS_MAPPINGS) + 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) + +WEB_DIRECTORY = "./web" +__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"] diff --git a/comfyui-custom-scripts/__pycache__/__init__.cpython-310.pyc b/comfyui-custom-scripts/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..982729f6518918119ca5a76ad0581972c9aaa112 Binary files /dev/null and b/comfyui-custom-scripts/__pycache__/__init__.cpython-310.pyc differ diff --git a/comfyui-custom-scripts/__pycache__/pysssss.cpython-310.pyc b/comfyui-custom-scripts/__pycache__/pysssss.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..613b294b9ef068996ea0c6fdaa6b963037b40e2c Binary files /dev/null and b/comfyui-custom-scripts/__pycache__/pysssss.cpython-310.pyc differ diff --git a/comfyui-custom-scripts/py/__pycache__/autocomplete.cpython-310.pyc b/comfyui-custom-scripts/py/__pycache__/autocomplete.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a128233fc8e06da666aab7e435298e8c36373a1 Binary files /dev/null and b/comfyui-custom-scripts/py/__pycache__/autocomplete.cpython-310.pyc differ diff --git a/comfyui-custom-scripts/py/__pycache__/better_combos.cpython-310.pyc b/comfyui-custom-scripts/py/__pycache__/better_combos.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3129499efd6461ab107e15514918e0b4bbb115d3 Binary files /dev/null and b/comfyui-custom-scripts/py/__pycache__/better_combos.cpython-310.pyc differ diff --git a/comfyui-custom-scripts/py/__pycache__/constrain_image.cpython-310.pyc b/comfyui-custom-scripts/py/__pycache__/constrain_image.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92bfac0675f32d85e07bce376759039c79d02057 Binary files /dev/null and b/comfyui-custom-scripts/py/__pycache__/constrain_image.cpython-310.pyc differ diff --git a/comfyui-custom-scripts/py/__pycache__/constrain_image_for_video.cpython-310.pyc b/comfyui-custom-scripts/py/__pycache__/constrain_image_for_video.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1dd6fce762516580c622b2151ffe66afb21dfa1c Binary files /dev/null and b/comfyui-custom-scripts/py/__pycache__/constrain_image_for_video.cpython-310.pyc differ diff --git a/comfyui-custom-scripts/py/__pycache__/math_expression.cpython-310.pyc b/comfyui-custom-scripts/py/__pycache__/math_expression.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..266c70c079874dc86239cb76bd9e08ca82017aa8 Binary files /dev/null and b/comfyui-custom-scripts/py/__pycache__/math_expression.cpython-310.pyc differ diff --git a/comfyui-custom-scripts/py/__pycache__/model_info.cpython-310.pyc b/comfyui-custom-scripts/py/__pycache__/model_info.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..741659c0b7dc600418e1c872c898a8e9403bd3ec Binary files /dev/null and b/comfyui-custom-scripts/py/__pycache__/model_info.cpython-310.pyc differ diff --git a/comfyui-custom-scripts/py/__pycache__/play_sound.cpython-310.pyc b/comfyui-custom-scripts/py/__pycache__/play_sound.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c1936df5644a8df62aa93e5833e53ee3b9ada70 Binary files /dev/null and b/comfyui-custom-scripts/py/__pycache__/play_sound.cpython-310.pyc differ diff --git a/comfyui-custom-scripts/py/__pycache__/repeater.cpython-310.pyc b/comfyui-custom-scripts/py/__pycache__/repeater.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..263bdc1ee2f3f5a45cf3d34fdf77912ff58c0cb7 Binary files /dev/null and b/comfyui-custom-scripts/py/__pycache__/repeater.cpython-310.pyc differ diff --git a/comfyui-custom-scripts/py/__pycache__/reroute_primitive.cpython-310.pyc b/comfyui-custom-scripts/py/__pycache__/reroute_primitive.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f50c1744b129fccae9b189c44914bdeee81ceb2 Binary files /dev/null and b/comfyui-custom-scripts/py/__pycache__/reroute_primitive.cpython-310.pyc differ diff --git a/comfyui-custom-scripts/py/__pycache__/show_text.cpython-310.pyc b/comfyui-custom-scripts/py/__pycache__/show_text.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1038dbd5dad07e8825f18a35d1c3a30af779287a Binary files /dev/null and b/comfyui-custom-scripts/py/__pycache__/show_text.cpython-310.pyc differ diff --git a/comfyui-custom-scripts/py/__pycache__/string_function.cpython-310.pyc b/comfyui-custom-scripts/py/__pycache__/string_function.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..386447b8855022a6a8a1ec2914b060c85de448df Binary files /dev/null and b/comfyui-custom-scripts/py/__pycache__/string_function.cpython-310.pyc differ diff --git a/comfyui-custom-scripts/py/__pycache__/system_notification.cpython-310.pyc b/comfyui-custom-scripts/py/__pycache__/system_notification.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56e5056ce2664d735a7d0a296baafa815d167745 Binary files /dev/null and b/comfyui-custom-scripts/py/__pycache__/system_notification.cpython-310.pyc differ diff --git a/comfyui-custom-scripts/py/__pycache__/text_files.cpython-310.pyc b/comfyui-custom-scripts/py/__pycache__/text_files.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39ceced2b7941f23f88021202e59e8d5d95d861a Binary files /dev/null and b/comfyui-custom-scripts/py/__pycache__/text_files.cpython-310.pyc differ diff --git a/comfyui-custom-scripts/py/__pycache__/workflows.cpython-310.pyc b/comfyui-custom-scripts/py/__pycache__/workflows.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69236663f9bfce684fdd66d7bff99970e82b0ce5 Binary files /dev/null and b/comfyui-custom-scripts/py/__pycache__/workflows.cpython-310.pyc differ diff --git a/comfyui-custom-scripts/py/autocomplete.py b/comfyui-custom-scripts/py/autocomplete.py new file mode 100644 index 0000000000000000000000000000000000000000..8ac6a0524823d13849b6cbe02efedc7bffea8f38 --- /dev/null +++ b/comfyui-custom-scripts/py/autocomplete.py @@ -0,0 +1,29 @@ +from server import PromptServer +from aiohttp import web +import os +import folder_paths + +dir = os.path.abspath(os.path.join(__file__, "../../user")) +if not os.path.exists(dir): + os.mkdir(dir) +file = os.path.join(dir, "autocomplete.txt") + + +@PromptServer.instance.routes.get("/pysssss/autocomplete") +async def get_autocomplete(request): + if os.path.isfile(file): + return web.FileResponse(file) + return web.Response(status=404) + + +@PromptServer.instance.routes.post("/pysssss/autocomplete") +async def update_autocomplete(request): + with open(file, "w", encoding="utf-8") as f: + f.write(await request.text()) + return web.Response(status=200) + + +@PromptServer.instance.routes.get("/pysssss/loras") +async def get_loras(request): + loras = folder_paths.get_filename_list("loras") + return web.json_response(list(map(lambda a: os.path.splitext(a)[0], loras))) diff --git a/comfyui-custom-scripts/py/better_combos.py b/comfyui-custom-scripts/py/better_combos.py new file mode 100644 index 0000000000000000000000000000000000000000..d31043b0afdb8943409f3d97adbdde2db9dc38ee --- /dev/null +++ b/comfyui-custom-scripts/py/better_combos.py @@ -0,0 +1,172 @@ +import glob +import os +from nodes import LoraLoader, CheckpointLoaderSimple +import folder_paths +from server import PromptServer +from folder_paths import get_directory_by_type +from aiohttp import web +import shutil + + +@PromptServer.instance.routes.get("/pysssss/view/{name}") +async def view(request): + name = request.match_info["name"] + pos = name.index("/") + type = name[0:pos] + name = name[pos+1:] + + image_path = folder_paths.get_full_path( + type, name) + if not image_path: + return web.Response(status=404) + + filename = os.path.basename(image_path) + return web.FileResponse(image_path, headers={"Content-Disposition": f"filename=\"{filename}\""}) + + +@PromptServer.instance.routes.post("/pysssss/save/{name}") +async def save_preview(request): + name = request.match_info["name"] + pos = name.index("/") + type = name[0:pos] + name = name[pos+1:] + + body = await request.json() + + dir = get_directory_by_type(body.get("type", "output")) + subfolder = body.get("subfolder", "") + full_output_folder = os.path.join(dir, os.path.normpath(subfolder)) + + filepath = os.path.join(full_output_folder, body.get("filename", "")) + + if os.path.commonpath((dir, os.path.abspath(filepath))) != dir: + return web.Response(status=400) + + image_path = folder_paths.get_full_path(type, name) + image_path = os.path.splitext( + image_path)[0] + os.path.splitext(filepath)[1] + + shutil.copyfile(filepath, image_path) + + return web.json_response({ + "image": type + "/" + os.path.basename(image_path) + }) + + +@PromptServer.instance.routes.get("/pysssss/examples/{name}") +async def get_examples(request): + name = request.match_info["name"] + pos = name.index("/") + type = name[0:pos] + name = name[pos+1:] + + file_path = folder_paths.get_full_path( + type, name) + if not file_path: + return web.Response(status=404) + + file_path_no_ext = os.path.splitext(file_path)[0] + examples = [] + + if os.path.isdir(file_path_no_ext): + examples += sorted(map(lambda t: os.path.relpath(t, file_path_no_ext), + glob.glob(file_path_no_ext + "/*.txt"))) + + if os.path.isfile(file_path_no_ext + ".txt"): + examples += ["notes"] + + return web.json_response(examples) + + +@PromptServer.instance.routes.post("/pysssss/examples/{name}") +async def save_example(request): + name = request.match_info["name"] + pos = name.index("/") + type = name[0:pos] + name = name[pos+1:] + body = await request.json() + example_name = body["name"] + example = body["example"] + + file_path = folder_paths.get_full_path( + type, name) + if not file_path: + return web.Response(status=404) + + if not example_name.endswith(".txt"): + example_name += ".txt" + + file_path_no_ext = os.path.splitext(file_path)[0] + example_file = os.path.join(file_path_no_ext, example_name) + if not os.path.exists(file_path_no_ext): + os.mkdir(file_path_no_ext) + with open(example_file, 'w', encoding='utf8') as f: + f.write(example) + + return web.Response(status=201) + + +@PromptServer.instance.routes.get("/pysssss/images/{type}") +async def get_images(request): + type = request.match_info["type"] + names = folder_paths.get_filename_list(type) + + images = {} + for item_name in names: + file_name = os.path.splitext(item_name)[0] + file_path = folder_paths.get_full_path(type, item_name) + + if file_path is None: + continue + + file_path_no_ext = os.path.splitext(file_path)[0] + + for ext in ["png", "jpg", "jpeg", "preview.png", "preview.jpeg"]: + if os.path.isfile(file_path_no_ext + "." + ext): + images[item_name] = f"{type}/{file_name}.{ext}" + break + + return web.json_response(images) + + +class LoraLoaderWithImages(LoraLoader): + RETURN_TYPES = (*LoraLoader.RETURN_TYPES, "STRING",) + RETURN_NAMES = (*getattr(LoraLoader, "RETURN_NAMES", + LoraLoader.RETURN_TYPES), "example") + + @classmethod + def INPUT_TYPES(s): + types = super().INPUT_TYPES() + types["optional"] = {"prompt": ("STRING", {"hidden": True})} + return types + + def load_lora(self, **kwargs): + prompt = kwargs.pop("prompt", "") + return (*super().load_lora(**kwargs), prompt) + + +class CheckpointLoaderSimpleWithImages(CheckpointLoaderSimple): + RETURN_TYPES = (*CheckpointLoaderSimple.RETURN_TYPES, "STRING",) + RETURN_NAMES = (*getattr(CheckpointLoaderSimple, "RETURN_NAMES", + CheckpointLoaderSimple.RETURN_TYPES), "example") + + @classmethod + def INPUT_TYPES(s): + types = super().INPUT_TYPES() + types["optional"] = {"prompt": ("STRING", {"hidden": True})} + return types + + def load_checkpoint(self, **kwargs): + prompt = kwargs.pop("prompt", "") + return (*super().load_checkpoint(**kwargs), prompt) + + +NODE_CLASS_MAPPINGS = { + "LoraLoader|pysssss": LoraLoaderWithImages, + "CheckpointLoader|pysssss": CheckpointLoaderSimpleWithImages, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LoraLoader|pysssss": "Lora Loader 🐍", + "CheckpointLoader|pysssss": "Checkpoint Loader 🐍", +} diff --git a/comfyui-custom-scripts/py/constrain_image.py b/comfyui-custom-scripts/py/constrain_image.py new file mode 100644 index 0000000000000000000000000000000000000000..1c768893c5ed5c1cb1247bca77414dc8762d3fde --- /dev/null +++ b/comfyui-custom-scripts/py/constrain_image.py @@ -0,0 +1,71 @@ +import torch +import numpy as np +from PIL import Image + +class ConstrainImage: + """ + A node that constrains an image to a maximum and minimum size while maintaining aspect ratio. + """ + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "images": ("IMAGE",), + "max_width": ("INT", {"default": 1024, "min": 0}), + "max_height": ("INT", {"default": 1024, "min": 0}), + "min_width": ("INT", {"default": 0, "min": 0}), + "min_height": ("INT", {"default": 0, "min": 0}), + "crop_if_required": (["yes", "no"], {"default": "no"}), + }, + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "constrain_image" + CATEGORY = "image" + OUTPUT_IS_LIST = (True,) + + def constrain_image(self, images, max_width, max_height, min_width, min_height, crop_if_required): + crop_if_required = crop_if_required == "yes" + results = [] + for image in images: + i = 255. * image.cpu().numpy() + img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8)).convert("RGB") + + current_width, current_height = img.size + aspect_ratio = current_width / current_height + + constrained_width = min(max(current_width, min_width), max_width) + constrained_height = min(max(current_height, min_height), max_height) + + if constrained_width / constrained_height > aspect_ratio: + constrained_width = max(int(constrained_height * aspect_ratio), min_width) + if crop_if_required: + constrained_height = int(current_height / (current_width / constrained_width)) + else: + constrained_height = max(int(constrained_width / aspect_ratio), min_height) + if crop_if_required: + constrained_width = int(current_width / (current_height / constrained_height)) + + resized_image = img.resize((constrained_width, constrained_height), Image.LANCZOS) + + if crop_if_required and (constrained_width > max_width or constrained_height > max_height): + left = max((constrained_width - max_width) // 2, 0) + top = max((constrained_height - max_height) // 2, 0) + right = min(constrained_width, max_width) + left + bottom = min(constrained_height, max_height) + top + resized_image = resized_image.crop((left, top, right, bottom)) + + resized_image = np.array(resized_image).astype(np.float32) / 255.0 + resized_image = torch.from_numpy(resized_image)[None,] + results.append(resized_image) + + return (results,) + +NODE_CLASS_MAPPINGS = { + "ConstrainImage|pysssss": ConstrainImage, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "ConstrainImage|pysssss": "Constrain Image 🐍", +} diff --git a/comfyui-custom-scripts/py/constrain_image_for_video.py b/comfyui-custom-scripts/py/constrain_image_for_video.py new file mode 100644 index 0000000000000000000000000000000000000000..91c0c502b8d8f6202d96a26b045e393b4552fc8e --- /dev/null +++ b/comfyui-custom-scripts/py/constrain_image_for_video.py @@ -0,0 +1,72 @@ +import torch +import numpy as np +from PIL import Image + +class ConstrainImageforVideo: + """ + A node that constrains an image to a maximum and minimum size while maintaining aspect ratio. + """ + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "images": ("IMAGE",), + "max_width": ("INT", {"default": 1024, "min": 0}), + "max_height": ("INT", {"default": 1024, "min": 0}), + "min_width": ("INT", {"default": 0, "min": 0}), + "min_height": ("INT", {"default": 0, "min": 0}), + "crop_if_required": (["yes", "no"], {"default": "no"}), + }, + } + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("IMAGE",) + FUNCTION = "constrain_image_for_video" + CATEGORY = "image" + + def constrain_image_for_video(self, images, max_width, max_height, min_width, min_height, crop_if_required): + crop_if_required = crop_if_required == "yes" + results = [] + for image in images: + i = 255. * image.cpu().numpy() + img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8)).convert("RGB") + + current_width, current_height = img.size + aspect_ratio = current_width / current_height + + constrained_width = max(min(current_width, min_width), max_width) + constrained_height = max(min(current_height, min_height), max_height) + + if constrained_width / constrained_height > aspect_ratio: + constrained_width = max(int(constrained_height * aspect_ratio), min_width) + if crop_if_required: + constrained_height = int(current_height / (current_width / constrained_width)) + else: + constrained_height = max(int(constrained_width / aspect_ratio), min_height) + if crop_if_required: + constrained_width = int(current_width / (current_height / constrained_height)) + + resized_image = img.resize((constrained_width, constrained_height), Image.LANCZOS) + + if crop_if_required and (constrained_width > max_width or constrained_height > max_height): + left = max((constrained_width - max_width) // 2, 0) + top = max((constrained_height - max_height) // 2, 0) + right = min(constrained_width, max_width) + left + bottom = min(constrained_height, max_height) + top + resized_image = resized_image.crop((left, top, right, bottom)) + + resized_image = np.array(resized_image).astype(np.float32) / 255.0 + resized_image = torch.from_numpy(resized_image)[None,] + results.append(resized_image) + all_images = torch.cat(results, dim=0) + + return (all_images, all_images.size(0),) + +NODE_CLASS_MAPPINGS = { + "ConstrainImageforVideo|pysssss": ConstrainImageforVideo, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "ConstrainImageforVideo|pysssss": "Constrain Image for Video 🐍", +} diff --git a/comfyui-custom-scripts/py/math_expression.py b/comfyui-custom-scripts/py/math_expression.py new file mode 100644 index 0000000000000000000000000000000000000000..4a41655b6876a077338040b0099c4d4e8c9dbcd2 --- /dev/null +++ b/comfyui-custom-scripts/py/math_expression.py @@ -0,0 +1,252 @@ +import ast +import math +import random +import operator as op + +# Hack: string type that is always equal in not equal comparisons +class AnyType(str): + def __ne__(self, __value: object) -> bool: + return False + + +# Our any instance wants to be a wildcard string +any = AnyType("*") + +operators = { + ast.Add: op.add, + ast.Sub: op.sub, + ast.Mult: op.mul, + ast.Div: op.truediv, + ast.FloorDiv: op.floordiv, + ast.Pow: op.pow, + ast.BitXor: op.xor, + ast.USub: op.neg, + ast.Mod: op.mod, + ast.BitAnd: op.and_, + ast.BitOr: op.or_, + ast.Invert: op.invert, + ast.And: lambda a, b: 1 if a and b else 0, + ast.Or: lambda a, b: 1 if a or b else 0, + ast.Not: lambda a: 0 if a else 1, + ast.RShift: op.rshift, + ast.LShift: op.lshift +} + +# TODO: restructure args to provide more info, generate hint based on args to save duplication +functions = { + "round": { + "args": (1, 2), + "call": lambda a, b = None: round(a, b), + "hint": "number, dp? = 0" + }, + "ceil": { + "args": (1, 1), + "call": lambda a: math.ceil(a), + "hint": "number" + }, + "floor": { + "args": (1, 1), + "call": lambda a: math.floor(a), + "hint": "number" + }, + "min": { + "args": (2, None), + "call": lambda *args: min(*args), + "hint": "...numbers" + }, + "max": { + "args": (2, None), + "call": lambda *args: max(*args), + "hint": "...numbers" + }, + "randomint": { + "args": (2, 2), + "call": lambda a, b: random.randint(a, b), + "hint": "min, max" + }, + "randomchoice": { + "args": (2, None), + "call": lambda *args: random.choice(args), + "hint": "...numbers" + }, + "sqrt": { + "args": (1, 1), + "call": lambda a: math.sqrt(a), + "hint": "number" + }, + "int": { + "args": (1, 1), + "call": lambda a = None: int(a), + "hint": "number" + }, + "iif": { + "args": (3, 3), + "call": lambda a, b, c = None: b if a else c, + "hint": "value, truepart, falsepart" + }, +} + +autocompleteWords = list({ + "text": x, + "value": f"{x}()", + "showValue": False, + "hint": f"{functions[x]['hint']}", + "caretOffset": -1 +} for x in functions.keys()) + + +class MathExpression: + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "expression": ("STRING", {"multiline": True, "dynamicPrompts": False, "pysssss.autocomplete": { + "words": autocompleteWords, + "separator": "" + }}), + }, + "optional": { + "a": (any, ), + "b": (any,), + "c": (any, ), + }, + "hidden": {"extra_pnginfo": "EXTRA_PNGINFO", + "prompt": "PROMPT"}, + } + + RETURN_TYPES = ("INT", "FLOAT", ) + FUNCTION = "evaluate" + CATEGORY = "utils" + OUTPUT_NODE = True + + @classmethod + def IS_CHANGED(s, expression, **kwargs): + if "random" in expression: + return float("nan") + return expression + + def get_widget_value(self, extra_pnginfo, prompt, node_name, widget_name): + workflow = extra_pnginfo["workflow"] if "workflow" in extra_pnginfo else { "nodes": [] } + node_id = None + for node in workflow["nodes"]: + name = node["type"] + if "properties" in node: + if "Node name for S&R" in node["properties"]: + name = node["properties"]["Node name for S&R"] + if name == node_name: + node_id = node["id"] + break + if "title" in node: + name = node["title"] + if name == node_name: + node_id = node["id"] + break + if node_id is not None: + values = prompt[str(node_id)] + if "inputs" in values: + if widget_name in values["inputs"]: + value = values["inputs"][widget_name] + if isinstance(value, list): + raise ValueError("Converted widgets are not supported via named reference, use the inputs instead.") + return value + raise NameError(f"Widget not found: {node_name}.{widget_name}") + raise NameError(f"Node not found: {node_name}.{widget_name}") + + def get_size(self, target, property): + if isinstance(target, dict) and "samples" in target: + # Latent + if property == "width": + return target["samples"].shape[3] * 8 + return target["samples"].shape[2] * 8 + else: + # Image + if property == "width": + return target.shape[2] + return target.shape[1] + + def evaluate(self, expression, prompt, extra_pnginfo={}, a=None, b=None, c=None): + expression = expression.replace('\n', ' ').replace('\r', '') + node = ast.parse(expression, mode='eval').body + + lookup = {"a": a, "b": b, "c": c} + + def eval_op(node, l, r): + l = eval_expr(l) + r = eval_expr(r) + l = l if isinstance(l, int) else float(l) + r = r if isinstance(r, int) else float(r) + return operators[type(node.op)](l, r) + + def eval_expr(node): + if isinstance(node, ast.Constant) or isinstance(node, ast.Num): + return node.n + elif isinstance(node, ast.BinOp): + return eval_op(node, node.left, node.right) + elif isinstance(node, ast.BoolOp): + return eval_op(node, node.values[0], node.values[1]) + elif isinstance(node, ast.UnaryOp): + return operators[type(node.op)](eval_expr(node.operand)) + elif isinstance(node, ast.Attribute): + if node.value.id in lookup: + if node.attr == "width" or node.attr == "height": + return self.get_size(lookup[node.value.id], node.attr) + + return self.get_widget_value(extra_pnginfo, prompt, node.value.id, node.attr) + elif isinstance(node, ast.Name): + if node.id in lookup: + val = lookup[node.id] + if isinstance(val, (int, float, complex)): + return val + else: + raise TypeError( + f"Compex types (LATENT/IMAGE) need to reference their width/height, e.g. {node.id}.width") + raise NameError(f"Name not found: {node.id}") + elif isinstance(node, ast.Call): + if node.func.id in functions: + fn = functions[node.func.id] + l = len(node.args) + if l < fn["args"][0] or (fn["args"][1] is not None and l > fn["args"][1]): + if fn["args"][1] is None: + toErr = " or more" + else: + toErr = f" to {fn['args'][1]}" + raise SyntaxError( + f"Invalid function call: {node.func.id} requires {fn['args'][0]}{toErr} arguments") + args = [] + for arg in node.args: + args.append(eval_expr(arg)) + return fn["call"](*args) + raise NameError(f"Invalid function call: {node.func.id}") + elif isinstance(node, ast.Compare): + l = eval_expr(node.left) + r = eval_expr(node.comparators[0]) + if isinstance(node.ops[0], ast.Eq): + return 1 if l == r else 0 + if isinstance(node.ops[0], ast.NotEq): + return 1 if l != r else 0 + if isinstance(node.ops[0], ast.Gt): + return 1 if l > r else 0 + if isinstance(node.ops[0], ast.GtE): + return 1 if l >= r else 0 + if isinstance(node.ops[0], ast.Lt): + return 1 if l < r else 0 + if isinstance(node.ops[0], ast.LtE): + return 1 if l <= r else 0 + raise NotImplementedError( + "Operator " + node.ops[0].__class__.__name__ + " not supported.") + else: + raise TypeError(node) + + r = eval_expr(node) + return {"ui": {"value": [r]}, "result": (int(r), float(r),)} + + +NODE_CLASS_MAPPINGS = { + "MathExpression|pysssss": MathExpression, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "MathExpression|pysssss": "Math Expression 🐍", +} + diff --git a/comfyui-custom-scripts/py/model_info.py b/comfyui-custom-scripts/py/model_info.py new file mode 100644 index 0000000000000000000000000000000000000000..b360bafb35fdfc25dd94902076fab6baa39ee23c --- /dev/null +++ b/comfyui-custom-scripts/py/model_info.py @@ -0,0 +1,115 @@ +import hashlib +import json +from aiohttp import web +from server import PromptServer +import folder_paths +import os + + +def get_metadata(filepath): + with open(filepath, "rb") as file: + # https://github.com/huggingface/safetensors#format + # 8 bytes: N, an unsigned little-endian 64-bit integer, containing the size of the header + header_size = int.from_bytes(file.read(8), "little", signed=False) + + if header_size <= 0: + raise BufferError("Invalid header size") + + header = file.read(header_size) + if header_size <= 0: + raise BufferError("Invalid header") + + header_json = json.loads(header) + return header_json["__metadata__"] if "__metadata__" in header_json else None + + +@PromptServer.instance.routes.post("/pysssss/metadata/notes/{name}") +async def save_notes(request): + name = request.match_info["name"] + pos = name.index("/") + type = name[0:pos] + name = name[pos+1:] + + file_path = None + if type == "embeddings" or type == "loras": + name = name.lower() + files = folder_paths.get_filename_list(type) + for f in files: + lower_f = f.lower() + if lower_f == name: + file_path = folder_paths.get_full_path(type, f) + else: + n = os.path.splitext(f)[0].lower() + if n == name: + file_path = folder_paths.get_full_path(type, f) + + if file_path is not None: + break + else: + file_path = folder_paths.get_full_path( + type, name) + if not file_path: + return web.Response(status=404) + + file_no_ext = os.path.splitext(file_path)[0] + info_file = file_no_ext + ".txt" + with open(info_file, "w") as f: + f.write(await request.text()) + + return web.Response(status=200) + + +@PromptServer.instance.routes.get("/pysssss/metadata/{name}") +async def load_metadata(request): + name = request.match_info["name"] + pos = name.index("/") + type = name[0:pos] + name = name[pos+1:] + + file_path = None + if type == "embeddings" or type == "loras": + name = name.lower() + files = folder_paths.get_filename_list(type) + for f in files: + lower_f = f.lower() + if lower_f == name: + file_path = folder_paths.get_full_path(type, f) + else: + n = os.path.splitext(f)[0].lower() + if n == name: + file_path = folder_paths.get_full_path(type, f) + + if file_path is not None: + break + else: + file_path = folder_paths.get_full_path( + type, name) + if not file_path: + return web.Response(status=404) + + try: + meta = get_metadata(file_path) + except: + meta = None + + if meta is None: + meta = {} + + file_no_ext = os.path.splitext(file_path)[0] + + info_file = file_no_ext + ".txt" + if os.path.isfile(info_file): + with open(info_file, "r") as f: + meta["pysssss.notes"] = f.read() + + hash_file = file_no_ext + ".sha256" + if os.path.isfile(hash_file): + with open(hash_file, "rt") as f: + meta["pysssss.sha256"] = f.read() + else: + with open(file_path, "rb") as f: + meta["pysssss.sha256"] = hashlib.sha256(f.read()).hexdigest() + with open(hash_file, "wt") as f: + f.write(meta["pysssss.sha256"]) + + return web.json_response(meta) diff --git a/comfyui-custom-scripts/py/play_sound.py b/comfyui-custom-scripts/py/play_sound.py new file mode 100644 index 0000000000000000000000000000000000000000..65f599d2680553a20031d81d1fdf161d73edefef --- /dev/null +++ b/comfyui-custom-scripts/py/play_sound.py @@ -0,0 +1,42 @@ +# Hack: string type that is always equal in not equal comparisons +class AnyType(str): + def __ne__(self, __value: object) -> bool: + return False + + +# Our any instance wants to be a wildcard string +any = AnyType("*") + + +class PlaySound: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "any": (any, {}), + "mode": (["always", "on empty queue"], {}), + "volume": ("FLOAT", {"min": 0, "max": 1, "step": 0.1, "default": 0.5}), + "file": ("STRING", { "default": "notify.mp3" }) + }} + + FUNCTION = "nop" + INPUT_IS_LIST = True + OUTPUT_IS_LIST = (True,) + OUTPUT_NODE = True + RETURN_TYPES = (any,) + + CATEGORY = "utils" + + def IS_CHANGED(self, **kwargs): + return float("NaN") + + def nop(self, any, mode, volume, file): + return {"ui": {"a": []}, "result": (any,)} + + +NODE_CLASS_MAPPINGS = { + "PlaySound|pysssss": PlaySound, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "PlaySound|pysssss": "PlaySound 🐍", +} diff --git a/comfyui-custom-scripts/py/repeater.py b/comfyui-custom-scripts/py/repeater.py new file mode 100644 index 0000000000000000000000000000000000000000..1d83c67e2132b9db708ef087ad788d22c58c80c2 --- /dev/null +++ b/comfyui-custom-scripts/py/repeater.py @@ -0,0 +1,46 @@ +# Hack: string type that is always equal in not equal comparisons +class AnyType(str): + def __ne__(self, __value: object) -> bool: + return False + + +# Our any instance wants to be a wildcard string +any = AnyType("*") + + +class Repeater: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "source": (any, {}), + "repeats": ("INT", {"min": 0, "max": 5000, "default": 2}), + "output": (["single", "multi"], {}), + "node_mode": (["reuse", "create"], {}), + }} + + RETURN_TYPES = (any,) + FUNCTION = "repeat" + OUTPUT_NODE = False + OUTPUT_IS_LIST = (True,) + + CATEGORY = "utils" + + def repeat(self, repeats, output, node_mode, **kwargs): + if output == "multi": + # Multi outputs are split to indiviual nodes on the frontend when serializing + return ([kwargs["source"]],) + elif node_mode == "reuse": + # When reusing we have a single input node, repeat that N times + return ([kwargs["source"]] * repeats,) + else: + # When creating new nodes, they'll be added dynamically when the graph is serialized + return ((list(kwargs.values())),) + + +NODE_CLASS_MAPPINGS = { + "Repeater|pysssss": Repeater, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "Repeater|pysssss": "Repeater 🐍", +} diff --git a/comfyui-custom-scripts/py/reroute_primitive.py b/comfyui-custom-scripts/py/reroute_primitive.py new file mode 100644 index 0000000000000000000000000000000000000000..c22a7d1ef00eddfbde6185e702b6c3462521ccda --- /dev/null +++ b/comfyui-custom-scripts/py/reroute_primitive.py @@ -0,0 +1,59 @@ +# Hack: string type that is always equal in not equal comparisons +class AnyType(str): + def __ne__(self, __value: object) -> bool: + return False + + +# Our any instance wants to be a wildcard string +any = AnyType("*") + + +class ReroutePrimitive: + @classmethod + def INPUT_TYPES(cls): + return { + "required": {"value": (any, )}, + } + + @classmethod + def VALIDATE_INPUTS(s, **kwargs): + return True + + RETURN_TYPES = (any,) + FUNCTION = "route" + CATEGORY = "__hidden__" + + def route(self, value): + return (value,) + + +class MultiPrimitive: + @classmethod + def INPUT_TYPES(cls): + return { + "required": {}, + "optional": {"value": (any, )}, + } + + @classmethod + def VALIDATE_INPUTS(s, **kwargs): + return True + + RETURN_TYPES = (any,) + FUNCTION = "listify" + CATEGORY = "utils" + OUTPUT_IS_LIST = (True,) + + def listify(self, **kwargs): + return (list(kwargs.values()),) + + +NODE_CLASS_MAPPINGS = { + "ReroutePrimitive|pysssss": ReroutePrimitive, + # "MultiPrimitive|pysssss": MultiPrimitive, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "ReroutePrimitive|pysssss": "Reroute Primitive 🐍", + # "MultiPrimitive|pysssss": "Multi Primitive 🐍", +} diff --git a/comfyui-custom-scripts/py/show_text.py b/comfyui-custom-scripts/py/show_text.py new file mode 100644 index 0000000000000000000000000000000000000000..5a013a5bc7a82e29f38f35ff85dab827ba42a254 --- /dev/null +++ b/comfyui-custom-scripts/py/show_text.py @@ -0,0 +1,49 @@ +class ShowText: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "text": ("STRING", {"forceInput": True}), + }, + "hidden": { + "unique_id": "UNIQUE_ID", + "extra_pnginfo": "EXTRA_PNGINFO", + }, + } + + INPUT_IS_LIST = True + RETURN_TYPES = ("STRING",) + FUNCTION = "notify" + OUTPUT_NODE = True + OUTPUT_IS_LIST = (True,) + + CATEGORY = "utils" + + def notify(self, text, unique_id=None, extra_pnginfo=None): + if unique_id is not None and extra_pnginfo is not None: + if not isinstance(extra_pnginfo, list): + print("Error: extra_pnginfo is not a list") + elif ( + not isinstance(extra_pnginfo[0], dict) + or "workflow" not in extra_pnginfo[0] + ): + print("Error: extra_pnginfo[0] is not a dict or missing 'workflow' key") + else: + workflow = extra_pnginfo[0]["workflow"] + node = next( + (x for x in workflow["nodes"] if str(x["id"]) == str(unique_id[0])), + None, + ) + if node: + node["widgets_values"] = [text] + + return {"ui": {"text": text}, "result": (text,)} + + +NODE_CLASS_MAPPINGS = { + "ShowText|pysssss": ShowText, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "ShowText|pysssss": "Show Text 🐍", +} diff --git a/comfyui-custom-scripts/py/string_function.py b/comfyui-custom-scripts/py/string_function.py new file mode 100644 index 0000000000000000000000000000000000000000..f502ba31f52720f019c9f1d155d17a9cb9e335f9 --- /dev/null +++ b/comfyui-custom-scripts/py/string_function.py @@ -0,0 +1,49 @@ +import re + +class StringFunction: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "action": (["append", "replace"], {}), + "tidy_tags": (["yes", "no"], {}), + }, + "optional": { + "text_a": ("STRING", {"multiline": True, "dynamicPrompts": False}), + "text_b": ("STRING", {"multiline": True, "dynamicPrompts": False}), + "text_c": ("STRING", {"multiline": True, "dynamicPrompts": False}) + } + } + + RETURN_TYPES = ("STRING",) + FUNCTION = "exec" + CATEGORY = "utils" + OUTPUT_NODE = True + + def exec(self, action, tidy_tags, text_a="", text_b="", text_c=""): + tidy_tags = tidy_tags == "yes" + out = "" + if action == "append": + out = (", " if tidy_tags else "").join(filter(None, [text_a, text_b, text_c])) + else: + if text_c is None: + text_c = "" + if text_b.startswith("/") and text_b.endswith("/"): + regex = text_b[1:-1] + out = re.sub(regex, text_c, text_a) + else: + out = text_a.replace(text_b, text_c) + if tidy_tags: + out = re.sub(r"\s{2,}", " ", out) + out = out.replace(" ,", ",") + out = re.sub(r",{2,}", ",", out) + out = out.strip() + return {"ui": {"text": (out,)}, "result": (out,)} + +NODE_CLASS_MAPPINGS = { + "StringFunction|pysssss": StringFunction, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "StringFunction|pysssss": "String Function 🐍", +} diff --git a/comfyui-custom-scripts/py/system_notification.py b/comfyui-custom-scripts/py/system_notification.py new file mode 100644 index 0000000000000000000000000000000000000000..d5a52c14773ff86bbb3b29c6405a05238d8b46eb --- /dev/null +++ b/comfyui-custom-scripts/py/system_notification.py @@ -0,0 +1,41 @@ +# Hack: string type that is always equal in not equal comparisons +class AnyType(str): + def __ne__(self, __value: object) -> bool: + return False + + +# Our any instance wants to be a wildcard string +any = AnyType("*") + + +class SystemNotification: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "message": ("STRING", {"default": "Your notification has triggered."}), + "any": (any, {}), + "mode": (["always", "on empty queue"], {}), + }} + + FUNCTION = "nop" + INPUT_IS_LIST = True + OUTPUT_IS_LIST = (True,) + OUTPUT_NODE = True + RETURN_TYPES = (any,) + + CATEGORY = "utils" + + def IS_CHANGED(self, **kwargs): + return float("NaN") + + def nop(self, any, message, mode): + return {"ui": {"message": message, "mode": mode}, "result": (any,)} + + +NODE_CLASS_MAPPINGS = { + "SystemNotification|pysssss": SystemNotification, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "SystemNotification|pysssss": "SystemNotification 🐍", +} diff --git a/comfyui-custom-scripts/py/text_files.py b/comfyui-custom-scripts/py/text_files.py new file mode 100644 index 0000000000000000000000000000000000000000..253de9b6bde24b8daa15df627516801faf68e9a0 --- /dev/null +++ b/comfyui-custom-scripts/py/text_files.py @@ -0,0 +1,200 @@ +import os +import folder_paths +import json +from server import PromptServer +import glob +from aiohttp import web + + +def get_allowed_dirs(): + dir = os.path.abspath(os.path.join(__file__, "../../user")) + file = os.path.join(dir, "text_file_dirs.json") + with open(file, "r") as f: + return json.loads(f.read()) + + +def get_valid_dirs(): + return get_allowed_dirs().keys() + + +def get_dir_from_name(name): + dirs = get_allowed_dirs() + if name not in dirs: + raise KeyError(name + " dir not found") + + path = dirs[name] + path = path.replace("$input", folder_paths.get_input_directory()) + path = path.replace("$output", folder_paths.get_output_directory()) + path = path.replace("$temp", folder_paths.get_temp_directory()) + return path + + +def is_child_dir(parent_path, child_path): + parent_path = os.path.abspath(parent_path) + child_path = os.path.abspath(child_path) + return os.path.commonpath([parent_path]) == os.path.commonpath([parent_path, child_path]) + + +def get_real_path(dir): + dir = dir.replace("/**/", "/") + dir = os.path.abspath(dir) + dir = os.path.split(dir)[0] + return dir + + +@PromptServer.instance.routes.get("/pysssss/text-file/{name}") +async def get_files(request): + name = request.match_info["name"] + dir = get_dir_from_name(name) + recursive = "/**/" in dir + # Ugh cant use root_path on glob... lazy hack.. + pre = get_real_path(dir) + + files = list(map(lambda t: os.path.relpath(t, pre), + glob.glob(dir, recursive=recursive))) + + if len(files) == 0: + files = ["[none]"] + return web.json_response(files) + + +def get_file(root_dir, file): + if file == "[none]" or not file or not file.strip(): + raise ValueError("No file") + + root_dir = get_dir_from_name(root_dir) + root_dir = get_real_path(root_dir) + if not os.path.exists(root_dir): + os.mkdir(root_dir) + full_path = os.path.join(root_dir, file) + + if not is_child_dir(root_dir, full_path): + raise ReferenceError() + + return full_path + + +class TextFileNode: + RETURN_TYPES = ("STRING",) + CATEGORY = "utils" + + @classmethod + def VALIDATE_INPUTS(self, root_dir, file, **kwargs): + if file == "[none]" or not file or not file.strip(): + return True + get_file(root_dir, file) + return True + + def load_text(self, **kwargs): + self.file = get_file(kwargs["root_dir"], kwargs["file"]) + with open(self.file, "r") as f: + return (f.read(), ) + + +class LoadText(TextFileNode): + @classmethod + def IS_CHANGED(self, **kwargs): + return os.path.getmtime(self.file) + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "root_dir": (list(get_valid_dirs()), {}), + "file": (["[none]"], { + "pysssss.binding": [{ + "source": "root_dir", + "callback": [{ + "type": "set", + "target": "$this.disabled", + "value": True + }, { + "type": "fetch", + "url": "/pysssss/text-file/{$source.value}", + "then": [{ + "type": "set", + "target": "$this.options.values", + "value": "$result" + }, { + "type": "validate-combo" + }, { + "type": "set", + "target": "$this.disabled", + "value": False + }] + }], + }] + }) + }, + } + + FUNCTION = "load_text" + + +class SaveText(TextFileNode): + OUTPUT_NODE = True + + @classmethod + def IS_CHANGED(self, **kwargs): + return float("nan") + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "root_dir": (list(get_valid_dirs()), {}), + "file": ("STRING", {"default": "file.txt"}), + "append": (["append", "overwrite", "new only"], {}), + "insert": ("BOOLEAN", { + "default": True, "label_on": "new line", "label_off": "none", + "pysssss.binding": [{ + "source": "append", + "callback": [{ + "type": "if", + "condition": [{ + "left": "$source.value", + "op": "eq", + "right": '"append"' + }], + "true": [{ + "type": "set", + "target": "$this.disabled", + "value": False + }], + "false": [{ + "type": "set", + "target": "$this.disabled", + "value": True + }], + }] + }] + }), + "text": ("STRING", {"forceInput": True, "multiline": True}) + }, + } + + FUNCTION = "write_text" + + def write_text(self, **kwargs): + self.file = get_file(kwargs["root_dir"], kwargs["file"]) + if kwargs["append"] == "new only" and os.path.exists(self.file): + raise FileExistsError( + self.file + " already exists and 'new only' is selected.") + with open(self.file, "a+" if kwargs["append"] == "append" else "w") as f: + is_append = f.tell() != 0 + if is_append and kwargs["insert"]: + f.write("\n") + f.write(kwargs["text"]) + + return super().load_text(**kwargs) + + +NODE_CLASS_MAPPINGS = { + "LoadText|pysssss": LoadText, + "SaveText|pysssss": SaveText, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LoadText|pysssss": "Load Text 🐍", + "SaveText|pysssss": "Save Text 🐍", +} diff --git a/comfyui-custom-scripts/py/workflows.py b/comfyui-custom-scripts/py/workflows.py new file mode 100644 index 0000000000000000000000000000000000000000..233e8c84ce490a1fd2a51e603b9836d869dc0262 --- /dev/null +++ b/comfyui-custom-scripts/py/workflows.py @@ -0,0 +1,61 @@ +from server import PromptServer +from aiohttp import web +import os +import inspect +import json +import importlib +import sys +sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) +import pysssss + +root_directory = os.path.dirname(inspect.getfile(PromptServer)) +workflows_directory = os.path.join(root_directory, "pysssss-workflows") +workflows_directory = pysssss.get_config_value( + "workflows.directory", workflows_directory) +if not os.path.isabs(workflows_directory): + workflows_directory = os.path.abspath(os.path.join(root_directory, workflows_directory)) + +NODE_CLASS_MAPPINGS = {} +NODE_DISPLAY_NAME_MAPPINGS = {} + + +@PromptServer.instance.routes.get("/pysssss/workflows") +async def get_workflows(request): + files = [] + for dirpath, directories, file in os.walk(workflows_directory): + for file in file: + if (file.endswith(".json")): + files.append(os.path.relpath(os.path.join( + dirpath, file), workflows_directory)) + return web.json_response(list(map(lambda f: os.path.splitext(f)[0].replace("\\", "/"), files))) + + +@PromptServer.instance.routes.get("/pysssss/workflows/{name:.+}") +async def get_workflow(request): + file = os.path.abspath(os.path.join( + workflows_directory, request.match_info["name"] + ".json")) + if os.path.commonpath([file, workflows_directory]) != workflows_directory: + return web.Response(status=403) + + return web.FileResponse(file) + + +@PromptServer.instance.routes.post("/pysssss/workflows") +async def save_workflow(request): + json_data = await request.json() + file = os.path.abspath(os.path.join( + workflows_directory, json_data["name"] + ".json")) + if os.path.commonpath([file, workflows_directory]) != workflows_directory: + return web.Response(status=403) + + if os.path.exists(file) and ("overwrite" not in json_data or json_data["overwrite"] == False): + return web.Response(status=409) + + sub_path = os.path.dirname(file) + if not os.path.exists(sub_path): + os.makedirs(sub_path) + + with open(file, "w") as f: + f.write(json.dumps(json_data["workflow"])) + + return web.Response(status=201) diff --git a/comfyui-custom-scripts/pyproject.toml b/comfyui-custom-scripts/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..b34f8cfc4a4af33575586c2c11313bdd34d1dfee --- /dev/null +++ b/comfyui-custom-scripts/pyproject.toml @@ -0,0 +1,13 @@ +[project] +name = "comfyui-custom-scripts" +description = "Enhancements & experiments for ComfyUI, mostly focusing on UI features" +version = "1.2.5" +license = { file = "LICENSE" } + +[project.urls] +Repository = "https://github.com/pythongosssss/ComfyUI-Custom-Scripts" + +[tool.comfy] +PublisherId = "pythongosssss" +DisplayName = "ComfyUI-Custom-Scripts" +Icon = "" diff --git a/comfyui-custom-scripts/pysssss.default.json b/comfyui-custom-scripts/pysssss.default.json new file mode 100644 index 0000000000000000000000000000000000000000..6ca06420135d024f925a0d70d5dd0328c69b271e --- /dev/null +++ b/comfyui-custom-scripts/pysssss.default.json @@ -0,0 +1,4 @@ +{ + "name": "CustomScripts", + "logging": false +} diff --git a/comfyui-custom-scripts/pysssss.example.json b/comfyui-custom-scripts/pysssss.example.json new file mode 100644 index 0000000000000000000000000000000000000000..251e3c720067fc06b4458db51cb8c12182c05dee --- /dev/null +++ b/comfyui-custom-scripts/pysssss.example.json @@ -0,0 +1,7 @@ +{ + "name": "CustomScripts", + "logging": false, + "workflows": { + "directory": "C:\\ComfyUI-Workflows" + } +} diff --git a/comfyui-custom-scripts/pysssss.json b/comfyui-custom-scripts/pysssss.json new file mode 100644 index 0000000000000000000000000000000000000000..6ca06420135d024f925a0d70d5dd0328c69b271e --- /dev/null +++ b/comfyui-custom-scripts/pysssss.json @@ -0,0 +1,4 @@ +{ + "name": "CustomScripts", + "logging": false +} diff --git a/comfyui-custom-scripts/pysssss.py b/comfyui-custom-scripts/pysssss.py new file mode 100644 index 0000000000000000000000000000000000000000..b1024f5a220779239bdadc56aaf7b9431cfa77cc --- /dev/null +++ b/comfyui-custom-scripts/pysssss.py @@ -0,0 +1,300 @@ +import asyncio +import os +import json +import shutil +import inspect +import aiohttp +from server import PromptServer +from tqdm import tqdm + +config = None + + +def is_logging_enabled(): + config = get_extension_config() + if "logging" not in config: + return False + return config["logging"] + + +def log(message, type=None, always=False, name=None): + if not always and not is_logging_enabled(): + return + + if type is not None: + message = f"[{type}] {message}" + + if name is None: + name = get_extension_config()["name"] + + print(f"(pysssss:{name}) {message}") + + +def get_ext_dir(subpath=None, mkdir=False): + dir = os.path.dirname(__file__) + if subpath is not None: + dir = os.path.join(dir, subpath) + + dir = os.path.abspath(dir) + + if mkdir and not os.path.exists(dir): + os.makedirs(dir) + return dir + + +def get_comfy_dir(subpath=None, mkdir=False): + dir = os.path.dirname(inspect.getfile(PromptServer)) + if subpath is not None: + dir = os.path.join(dir, subpath) + + dir = os.path.abspath(dir) + + if mkdir and not os.path.exists(dir): + os.makedirs(dir) + return dir + + +def get_web_ext_dir(): + config = get_extension_config() + name = config["name"] + dir = get_comfy_dir("web/extensions/pysssss") + if not os.path.exists(dir): + os.makedirs(dir) + dir = os.path.join(dir, name) + return dir + + +def get_extension_config(reload=False): + global config + if reload == False and config is not None: + return config + + config_path = get_ext_dir("pysssss.json") + default_config_path = get_ext_dir("pysssss.default.json") + if not os.path.exists(config_path): + if os.path.exists(default_config_path): + shutil.copy(default_config_path, config_path) + if not os.path.exists(config_path): + log(f"Failed to create config at {config_path}", type="ERROR", always=True, name="???") + print(f"Extension path: {get_ext_dir()}") + return {"name": "Unknown", "version": -1} + + else: + log("Missing pysssss.default.json, this extension may not work correctly. Please reinstall the extension.", + type="ERROR", always=True, name="???") + print(f"Extension path: {get_ext_dir()}") + return {"name": "Unknown", "version": -1} + + with open(config_path, "r") as f: + config = json.loads(f.read()) + return config + + +def link_js(src, dst): + src = os.path.abspath(src) + dst = os.path.abspath(dst) + if os.name == "nt": + try: + import _winapi + _winapi.CreateJunction(src, dst) + return True + except: + pass + try: + os.symlink(src, dst) + return True + except: + import logging + logging.exception('') + return False + + +def is_junction(path): + if os.name != "nt": + return False + try: + return bool(os.readlink(path)) + except OSError: + return False + + +def install_js(): + src_dir = get_ext_dir("web/js") + if not os.path.exists(src_dir): + log("No JS") + return + + should_install = should_install_js() + if should_install: + log("it looks like you're running an old version of ComfyUI that requires manual setup of web files, it is recommended you update your installation.", "warning", True) + dst_dir = get_web_ext_dir() + linked = os.path.islink(dst_dir) or is_junction(dst_dir) + if linked or os.path.exists(dst_dir): + if linked: + if should_install: + log("JS already linked") + else: + os.unlink(dst_dir) + log("JS unlinked, PromptServer will serve extension") + elif not should_install: + shutil.rmtree(dst_dir) + log("JS deleted, PromptServer will serve extension") + return + + if not should_install: + log("JS skipped, PromptServer will serve extension") + return + + if link_js(src_dir, dst_dir): + log("JS linked") + return + + log("Copying JS files") + shutil.copytree(src_dir, dst_dir, dirs_exist_ok=True) + + +def should_install_js(): + return not hasattr(PromptServer.instance, "supports") or "custom_nodes_from_web" not in PromptServer.instance.supports + + +def init(check_imports=None): + log("Init") + + if check_imports is not None: + import importlib.util + for imp in check_imports: + spec = importlib.util.find_spec(imp) + if spec is None: + log(f"{imp} is required, please check requirements are installed.", + type="ERROR", always=True) + return False + + install_js() + return True + + +def get_async_loop(): + loop = None + try: + loop = asyncio.get_event_loop() + except: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + return loop + + +def get_http_session(): + loop = get_async_loop() + return aiohttp.ClientSession(loop=loop) + + +async def download(url, stream, update_callback=None, session=None): + close_session = False + if session is None: + close_session = True + session = get_http_session() + try: + async with session.get(url) as response: + size = int(response.headers.get('content-length', 0)) or None + + with tqdm( + unit='B', unit_scale=True, miniters=1, desc=url.split('/')[-1], total=size, + ) as progressbar: + perc = 0 + async for chunk in response.content.iter_chunked(2048): + stream.write(chunk) + progressbar.update(len(chunk)) + if update_callback is not None and progressbar.total is not None and progressbar.total != 0: + last = perc + perc = round(progressbar.n / progressbar.total, 2) + if perc != last: + last = perc + await update_callback(perc) + finally: + if close_session and session is not None: + await session.close() + + +async def download_to_file(url, destination, update_callback=None, is_ext_subpath=True, session=None): + if is_ext_subpath: + destination = get_ext_dir(destination) + with open(destination, mode='wb') as f: + download(url, f, update_callback, session) + + +def wait_for_async(async_fn, loop=None): + res = [] + + async def run_async(): + r = await async_fn() + res.append(r) + + if loop is None: + try: + loop = asyncio.get_event_loop() + except: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + + loop.run_until_complete(run_async()) + + return res[0] + + +def update_node_status(client_id, node, text, progress=None): + if client_id is None: + client_id = PromptServer.instance.client_id + + if client_id is None: + return + + PromptServer.instance.send_sync("pysssss/update_status", { + "node": node, + "progress": progress, + "text": text + }, client_id) + + +async def update_node_status_async(client_id, node, text, progress=None): + if client_id is None: + client_id = PromptServer.instance.client_id + + if client_id is None: + return + + await PromptServer.instance.send("pysssss/update_status", { + "node": node, + "progress": progress, + "text": text + }, client_id) + + +def get_config_value(key, default=None, throw=False): + split = key.split(".") + obj = get_extension_config() + for s in split: + if s in obj: + obj = obj[s] + else: + if throw: + raise KeyError("Configuration key missing: " + key) + else: + return default + return obj + + +def is_inside_dir(root_dir, check_path): + root_dir = os.path.abspath(root_dir) + if not os.path.isabs(check_path): + check_path = os.path.abspath(os.path.join(root_dir, check_path)) + return os.path.commonpath([check_path, root_dir]) == root_dir + + +def get_child_dir(root_dir, child_path, throw_if_outside=True): + child_path = os.path.abspath(os.path.join(root_dir, child_path)) + if is_inside_dir(root_dir, child_path): + return child_path + if throw_if_outside: + raise NotADirectoryError( + "Saving outside the target folder is not allowed.") + return None diff --git a/comfyui-custom-scripts/user/text_file_dirs.json b/comfyui-custom-scripts/user/text_file_dirs.json new file mode 100644 index 0000000000000000000000000000000000000000..15adc2255e0109be7b860d591f54187520c673aa --- /dev/null +++ b/comfyui-custom-scripts/user/text_file_dirs.json @@ -0,0 +1,5 @@ +{ + "input": "$input/**/*.txt", + "output": "$output/**/*.txt", + "temp": "$temp/**/*.txt" +} diff --git a/comfyui-custom-scripts/web/js/assets/canvas2svg.js b/comfyui-custom-scripts/web/js/assets/canvas2svg.js new file mode 100644 index 0000000000000000000000000000000000000000..03dc3923759ccbe8cf70eaab387b792cc0ba32ca --- /dev/null +++ b/comfyui-custom-scripts/web/js/assets/canvas2svg.js @@ -0,0 +1,1192 @@ +/*!! + * Canvas 2 Svg v1.0.19 + * A low level canvas to SVG converter. Uses a mock canvas context to build an SVG document. + * + * Licensed under the MIT license: + * http://www.opensource.org/licenses/mit-license.php + * + * Author: + * Kerry Liu + * + * Copyright (c) 2014 Gliffy Inc. + */ + +;(function() { + "use strict"; + + var STYLES, ctx, CanvasGradient, CanvasPattern, namedEntities; + + //helper function to format a string + function format(str, args) { + var keys = Object.keys(args), i; + for (i=0; i 1) { + options = defaultOptions; + options.width = arguments[0]; + options.height = arguments[1]; + } else if( !o ) { + options = defaultOptions; + } else { + options = o; + } + + if(!(this instanceof ctx)) { + //did someone call this without new? + return new ctx(options); + } + + //setup options + this.width = options.width || defaultOptions.width; + this.height = options.height || defaultOptions.height; + this.enableMirroring = options.enableMirroring !== undefined ? options.enableMirroring : defaultOptions.enableMirroring; + + this.canvas = this; ///point back to this instance! + this.__document = options.document || document; + this.__canvas = this.__document.createElement("canvas"); + this.__ctx = this.__canvas.getContext("2d"); + + this.__setDefaultStyles(); + this.__stack = [this.__getStyleState()]; + this.__groupStack = []; + + //the root svg element + this.__root = this.__document.createElementNS("http://www.w3.org/2000/svg", "svg"); + this.__root.setAttribute("version", 1.1); + this.__root.setAttribute("xmlns", "http://www.w3.org/2000/svg"); + this.__root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink"); + this.__root.setAttribute("width", this.width); + this.__root.setAttribute("height", this.height); + + //make sure we don't generate the same ids in defs + this.__ids = {}; + + //defs tag + this.__defs = this.__document.createElementNS("http://www.w3.org/2000/svg", "defs"); + this.__root.appendChild(this.__defs); + + //also add a group child. the svg element can't use the transform attribute + this.__currentElement = this.__document.createElementNS("http://www.w3.org/2000/svg", "g"); + this.__root.appendChild(this.__currentElement); + }; + + + /** + * Creates the specified svg element + * @private + */ + ctx.prototype.__createElement = function (elementName, properties, resetFill) { + if (typeof properties === "undefined") { + properties = {}; + } + + var element = this.__document.createElementNS("http://www.w3.org/2000/svg", elementName), + keys = Object.keys(properties), i, key; + if(resetFill) { + //if fill or stroke is not specified, the svg element should not display. By default SVG's fill is black. + element.setAttribute("fill", "none"); + element.setAttribute("stroke", "none"); + } + for(i=0; i 0) { + var group = this.__createElement("g"); + parent.appendChild(group); + this.__currentElement = group; + } + + var transform = this.__currentElement.getAttribute("transform"); + if(transform) { + transform += " "; + } else { + transform = ""; + } + transform += t; + this.__currentElement.setAttribute("transform", transform); + }; + + /** + * scales the current element + */ + ctx.prototype.scale = function(x, y) { + if(y === undefined) { + y = x; + } + this.__addTransform(format("scale({x},{y})", {x:x, y:y})); + }; + + /** + * rotates the current element + */ + ctx.prototype.rotate = function(angle){ + var degrees = (angle * 180 / Math.PI); + this.__addTransform(format("rotate({angle},{cx},{cy})", {angle:degrees, cx:0, cy:0})); + }; + + /** + * translates the current element + */ + ctx.prototype.translate = function(x, y){ + this.__addTransform(format("translate({x},{y})", {x:x,y:y})); + }; + + /** + * applies a transform to the current element + */ + ctx.prototype.transform = function(a, b, c, d, e, f){ + this.__addTransform(format("matrix({a},{b},{c},{d},{e},{f})", {a:a, b:b, c:c, d:d, e:e, f:f})); + }; + + /** + * Create a new Path Element + */ + ctx.prototype.beginPath = function(){ + var path, parent; + + // Note that there is only one current default path, it is not part of the drawing state. + // See also: https://html.spec.whatwg.org/multipage/scripting.html#current-default-path + this.__currentDefaultPath = ""; + this.__currentPosition = {}; + + path = this.__createElement("path", {}, true); + parent = this.__closestGroupOrSvg(); + parent.appendChild(path); + this.__currentElement = path; + }; + + /** + * Helper function to apply currentDefaultPath to current path element + * @private + */ + ctx.prototype.__applyCurrentDefaultPath = function() { + if(this.__currentElement.nodeName === "path") { + var d = this.__currentDefaultPath; + this.__currentElement.setAttribute("d", d); + } else { + throw new Error("Attempted to apply path command to node " + this.__currentElement.nodeName); + } + }; + + /** + * Helper function to add path command + * @private + */ + ctx.prototype.__addPathCommand = function(command){ + this.__currentDefaultPath += " "; + this.__currentDefaultPath += command; + }; + + /** + * Adds the move command to the current path element, + * if the currentPathElement is not empty create a new path element + */ + ctx.prototype.moveTo = function(x,y){ + if(this.__currentElement.nodeName !== "path") { + this.beginPath(); + } + + // creates a new subpath with the given point + this.__currentPosition = {x: x, y: y}; + this.__addPathCommand(format("M {x} {y}", {x:x, y:y})); + }; + + /** + * Closes the current path + */ + ctx.prototype.closePath = function(){ + this.__addPathCommand("Z"); + }; + + /** + * Adds a line to command + */ + ctx.prototype.lineTo = function(x, y){ + this.__currentPosition = {x: x, y: y}; + if (this.__currentDefaultPath.indexOf('M') > -1) { + this.__addPathCommand(format("L {x} {y}", {x:x, y:y})); + } else { + this.__addPathCommand(format("M {x} {y}", {x:x, y:y})); + } + }; + + /** + * Add a bezier command + */ + ctx.prototype.bezierCurveTo = function(cp1x, cp1y, cp2x, cp2y, x, y) { + this.__currentPosition = {x: x, y: y}; + this.__addPathCommand(format("C {cp1x} {cp1y} {cp2x} {cp2y} {x} {y}", + {cp1x:cp1x, cp1y:cp1y, cp2x:cp2x, cp2y:cp2y, x:x, y:y})); + }; + + /** + * Adds a quadratic curve to command + */ + ctx.prototype.quadraticCurveTo = function(cpx, cpy, x, y){ + this.__currentPosition = {x: x, y: y}; + this.__addPathCommand(format("Q {cpx} {cpy} {x} {y}", {cpx:cpx, cpy:cpy, x:x, y:y})); + }; + + + /** + * Return a new normalized vector of given vector + */ + var normalize = function(vector) { + var len = Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1]); + return [vector[0] / len, vector[1] / len]; + }; + + /** + * Adds the arcTo to the current path + * + * @see http://www.w3.org/TR/2015/WD-2dcontext-20150514/#dom-context-2d-arcto + */ + ctx.prototype.arcTo = function(x1, y1, x2, y2, radius) { + // Let the point (x0, y0) be the last point in the subpath. + var x0 = this.__currentPosition && this.__currentPosition.x; + var y0 = this.__currentPosition && this.__currentPosition.y; + + // First ensure there is a subpath for (x1, y1). + if (typeof x0 == "undefined" || typeof y0 == "undefined") { + return; + } + + // Negative values for radius must cause the implementation to throw an IndexSizeError exception. + if (radius < 0) { + throw new Error("IndexSizeError: The radius provided (" + radius + ") is negative."); + } + + // If the point (x0, y0) is equal to the point (x1, y1), + // or if the point (x1, y1) is equal to the point (x2, y2), + // or if the radius radius is zero, + // then the method must add the point (x1, y1) to the subpath, + // and connect that point to the previous point (x0, y0) by a straight line. + if (((x0 === x1) && (y0 === y1)) + || ((x1 === x2) && (y1 === y2)) + || (radius === 0)) { + this.lineTo(x1, y1); + return; + } + + // Otherwise, if the points (x0, y0), (x1, y1), and (x2, y2) all lie on a single straight line, + // then the method must add the point (x1, y1) to the subpath, + // and connect that point to the previous point (x0, y0) by a straight line. + var unit_vec_p1_p0 = normalize([x0 - x1, y0 - y1]); + var unit_vec_p1_p2 = normalize([x2 - x1, y2 - y1]); + if (unit_vec_p1_p0[0] * unit_vec_p1_p2[1] === unit_vec_p1_p0[1] * unit_vec_p1_p2[0]) { + this.lineTo(x1, y1); + return; + } + + // Otherwise, let The Arc be the shortest arc given by circumference of the circle that has radius radius, + // and that has one point tangent to the half-infinite line that crosses the point (x0, y0) and ends at the point (x1, y1), + // and that has a different point tangent to the half-infinite line that ends at the point (x1, y1), and crosses the point (x2, y2). + // The points at which this circle touches these two lines are called the start and end tangent points respectively. + + // note that both vectors are unit vectors, so the length is 1 + var cos = (unit_vec_p1_p0[0] * unit_vec_p1_p2[0] + unit_vec_p1_p0[1] * unit_vec_p1_p2[1]); + var theta = Math.acos(Math.abs(cos)); + + // Calculate origin + var unit_vec_p1_origin = normalize([ + unit_vec_p1_p0[0] + unit_vec_p1_p2[0], + unit_vec_p1_p0[1] + unit_vec_p1_p2[1] + ]); + var len_p1_origin = radius / Math.sin(theta / 2); + var x = x1 + len_p1_origin * unit_vec_p1_origin[0]; + var y = y1 + len_p1_origin * unit_vec_p1_origin[1]; + + // Calculate start angle and end angle + // rotate 90deg clockwise (note that y axis points to its down) + var unit_vec_origin_start_tangent = [ + -unit_vec_p1_p0[1], + unit_vec_p1_p0[0] + ]; + // rotate 90deg counter clockwise (note that y axis points to its down) + var unit_vec_origin_end_tangent = [ + unit_vec_p1_p2[1], + -unit_vec_p1_p2[0] + ]; + var getAngle = function(vector) { + // get angle (clockwise) between vector and (1, 0) + var x = vector[0]; + var y = vector[1]; + if (y >= 0) { // note that y axis points to its down + return Math.acos(x); + } else { + return -Math.acos(x); + } + }; + var startAngle = getAngle(unit_vec_origin_start_tangent); + var endAngle = getAngle(unit_vec_origin_end_tangent); + + // Connect the point (x0, y0) to the start tangent point by a straight line + this.lineTo(x + unit_vec_origin_start_tangent[0] * radius, + y + unit_vec_origin_start_tangent[1] * radius); + + // Connect the start tangent point to the end tangent point by arc + // and adding the end tangent point to the subpath. + this.arc(x, y, radius, startAngle, endAngle); + }; + + /** + * Sets the stroke property on the current element + */ + ctx.prototype.stroke = function(){ + if(this.__currentElement.nodeName === "path") { + this.__currentElement.setAttribute("paint-order", "fill stroke markers"); + } + this.__applyCurrentDefaultPath(); + this.__applyStyleToCurrentElement("stroke"); + }; + + /** + * Sets fill properties on the current element + */ + ctx.prototype.fill = function(){ + if(this.__currentElement.nodeName === "path") { + this.__currentElement.setAttribute("paint-order", "stroke fill markers"); + } + this.__applyCurrentDefaultPath(); + this.__applyStyleToCurrentElement("fill"); + }; + + /** + * Adds a rectangle to the path. + */ + ctx.prototype.rect = function(x, y, width, height){ + if(this.__currentElement.nodeName !== "path") { + this.beginPath(); + } + this.moveTo(x, y); + this.lineTo(x+width, y); + this.lineTo(x+width, y+height); + this.lineTo(x, y+height); + this.lineTo(x, y); + this.closePath(); + }; + + + /** + * adds a rectangle element + */ + ctx.prototype.fillRect = function(x, y, width, height){ + var rect, parent; + rect = this.__createElement("rect", { + x : x, + y : y, + width : width, + height : height + }, true); + parent = this.__closestGroupOrSvg(); + parent.appendChild(rect); + this.__currentElement = rect; + this.__applyStyleToCurrentElement("fill"); + }; + + /** + * Draws a rectangle with no fill + * @param x + * @param y + * @param width + * @param height + */ + ctx.prototype.strokeRect = function(x, y, width, height){ + var rect, parent; + rect = this.__createElement("rect", { + x : x, + y : y, + width : width, + height : height + }, true); + parent = this.__closestGroupOrSvg(); + parent.appendChild(rect); + this.__currentElement = rect; + this.__applyStyleToCurrentElement("stroke"); + }; + + + /** + * Clear entire canvas: + * 1. save current transforms + * 2. remove all the childNodes of the root g element + */ + ctx.prototype.__clearCanvas = function() { + var current = this.__closestGroupOrSvg(), + transform = current.getAttribute("transform"); + var rootGroup = this.__root.childNodes[1]; + var childNodes = rootGroup.childNodes; + for (var i = childNodes.length - 1; i >= 0; i--) { + if (childNodes[i]) { + rootGroup.removeChild(childNodes[i]); + } + } + this.__currentElement = rootGroup; + //reset __groupStack as all the child group nodes are all removed. + this.__groupStack = []; + if (transform) { + this.__addTransform(transform); + } + }; + + /** + * "Clears" a canvas by just drawing a white rectangle in the current group. + */ + ctx.prototype.clearRect = function(x, y, width, height) { + //clear entire canvas + if (x === 0 && y === 0 && width === this.width && height === this.height) { + this.__clearCanvas(); + return; + } + var rect, parent = this.__closestGroupOrSvg(); + rect = this.__createElement("rect", { + x : x, + y : y, + width : width, + height : height, + fill : "#FFFFFF" + }, true); + parent.appendChild(rect); + }; + + /** + * Adds a linear gradient to a defs tag. + * Returns a canvas gradient object that has a reference to it's parent def + */ + ctx.prototype.createLinearGradient = function(x1, y1, x2, y2){ + var grad = this.__createElement("linearGradient", { + id : randomString(this.__ids), + x1 : x1+"px", + x2 : x2+"px", + y1 : y1+"px", + y2 : y2+"px", + "gradientUnits" : "userSpaceOnUse" + }, false); + this.__defs.appendChild(grad); + return new CanvasGradient(grad, this); + }; + + /** + * Adds a radial gradient to a defs tag. + * Returns a canvas gradient object that has a reference to it's parent def + */ + ctx.prototype.createRadialGradient = function(x0, y0, r0, x1, y1, r1){ + var grad = this.__createElement("radialGradient", { + id : randomString(this.__ids), + cx : x1+"px", + cy : y1+"px", + r : r1+"px", + fx : x0+"px", + fy : y0+"px", + "gradientUnits" : "userSpaceOnUse" + }, false); + this.__defs.appendChild(grad); + return new CanvasGradient(grad, this); + + }; + + /** + * Parses the font string and returns svg mapping + * @private + */ + ctx.prototype.__parseFont = function() { + var regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\'\"\sa-z]+?)\s*$/i; + var fontPart = regex.exec( this.font ); + var data = { + style : fontPart[1] || 'normal', + size : fontPart[4] || '10px', + family : fontPart[6] || 'sans-serif', + weight: fontPart[3] || 'normal', + decoration : fontPart[2] || 'normal', + href : null + }; + + //canvas doesn't support underline natively, but we can pass this attribute + if(this.__fontUnderline === "underline") { + data.decoration = "underline"; + } + + //canvas also doesn't support linking, but we can pass this as well + if(this.__fontHref) { + data.href = this.__fontHref; + } + + return data; + }; + + /** + * Helper to link text fragments + * @param font + * @param element + * @return {*} + * @private + */ + ctx.prototype.__wrapTextLink = function(font, element) { + if(font.href) { + var a = this.__createElement("a"); + a.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", font.href); + a.appendChild(element); + return a; + } + return element; + }; + + /** + * Fills or strokes text + * @param text + * @param x + * @param y + * @param action - stroke or fill + * @private + */ + ctx.prototype.__applyText = function(text, x, y, action) { + var font = this.__parseFont(), + parent = this.__closestGroupOrSvg(), + textElement = this.__createElement("text", { + "font-family" : font.family, + "font-size" : font.size, + "font-style" : font.style, + "font-weight" : font.weight, + "text-decoration" : font.decoration, + "x" : x, + "y" : y, + "text-anchor": getTextAnchor(this.textAlign), + "dominant-baseline": getDominantBaseline(this.textBaseline) + }, true); + + textElement.appendChild(this.__document.createTextNode(text)); + this.__currentElement = textElement; + this.__applyStyleToCurrentElement(action); + parent.appendChild(this.__wrapTextLink(font,textElement)); + }; + + /** + * Creates a text element + * @param text + * @param x + * @param y + */ + ctx.prototype.fillText = function(text, x, y){ + this.__applyText(text, x, y, "fill"); + }; + + /** + * Strokes text + * @param text + * @param x + * @param y + */ + ctx.prototype.strokeText = function(text, x, y){ + this.__applyText(text, x, y, "stroke"); + }; + + /** + * No need to implement this for svg. + * @param text + * @return {TextMetrics} + */ + ctx.prototype.measureText = function(text){ + this.__ctx.font = this.font; + return this.__ctx.measureText(text); + }; + + /** + * Arc command! + */ + ctx.prototype.arc = function(x, y, radius, startAngle, endAngle, counterClockwise) { + // in canvas no circle is drawn if no angle is provided. + if (startAngle === endAngle) { + return; + } + startAngle = startAngle % (2*Math.PI); + endAngle = endAngle % (2*Math.PI); + if(startAngle === endAngle) { + //circle time! subtract some of the angle so svg is happy (svg elliptical arc can't draw a full circle) + endAngle = ((endAngle + (2*Math.PI)) - 0.001 * (counterClockwise ? -1 : 1)) % (2*Math.PI); + } + var endX = x+radius*Math.cos(endAngle), + endY = y+radius*Math.sin(endAngle), + startX = x+radius*Math.cos(startAngle), + startY = y+radius*Math.sin(startAngle), + sweepFlag = counterClockwise ? 0 : 1, + largeArcFlag = 0, + diff = endAngle - startAngle; + + // https://github.com/gliffy/canvas2svg/issues/4 + if(diff < 0) { + diff += 2*Math.PI; + } + + if(counterClockwise) { + largeArcFlag = diff > Math.PI ? 0 : 1; + } else { + largeArcFlag = diff > Math.PI ? 1 : 0; + } + + this.lineTo(startX, startY); + this.__addPathCommand(format("A {rx} {ry} {xAxisRotation} {largeArcFlag} {sweepFlag} {endX} {endY}", + {rx:radius, ry:radius, xAxisRotation:0, largeArcFlag:largeArcFlag, sweepFlag:sweepFlag, endX:endX, endY:endY})); + + this.__currentPosition = {x: endX, y: endY}; + }; + + /** + * Generates a ClipPath from the clip command. + */ + ctx.prototype.clip = function(){ + var group = this.__closestGroupOrSvg(), + clipPath = this.__createElement("clipPath"), + id = randomString(this.__ids), + newGroup = this.__createElement("g"); + + this.__applyCurrentDefaultPath(); + group.removeChild(this.__currentElement); + clipPath.setAttribute("id", id); + clipPath.appendChild(this.__currentElement); + + this.__defs.appendChild(clipPath); + + //set the clip path to this group + group.setAttribute("clip-path", format("url(#{id})", {id:id})); + + //clip paths can be scaled and transformed, we need to add another wrapper group to avoid later transformations + // to this path + group.appendChild(newGroup); + + this.__currentElement = newGroup; + + }; + + /** + * Draws a canvas, image or mock context to this canvas. + * Note that all svg dom manipulation uses node.childNodes rather than node.children for IE support. + * http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-drawimage + */ + ctx.prototype.drawImage = function(){ + //convert arguments to a real array + var args = Array.prototype.slice.call(arguments), + image=args[0], + dx, dy, dw, dh, sx=0, sy=0, sw, sh, parent, svg, defs, group, + currentElement, svgImage, canvas, context, id; + + if(args.length === 3) { + dx = args[1]; + dy = args[2]; + sw = image.width; + sh = image.height; + dw = sw; + dh = sh; + } else if(args.length === 5) { + dx = args[1]; + dy = args[2]; + dw = args[3]; + dh = args[4]; + sw = image.width; + sh = image.height; + } else if(args.length === 9) { + sx = args[1]; + sy = args[2]; + sw = args[3]; + sh = args[4]; + dx = args[5]; + dy = args[6]; + dw = args[7]; + dh = args[8]; + } else { + throw new Error("Inavlid number of arguments passed to drawImage: " + arguments.length); + } + + parent = this.__closestGroupOrSvg(); + currentElement = this.__currentElement; + var translateDirective = "translate(" + dx + ", " + dy + ")"; + if(image instanceof ctx) { + //canvas2svg mock canvas context. In the future we may want to clone nodes instead. + //also I'm currently ignoring dw, dh, sw, sh, sx, sy for a mock context. + svg = image.getSvg().cloneNode(true); + if (svg.childNodes && svg.childNodes.length > 1) { + defs = svg.childNodes[0]; + while(defs.childNodes.length) { + id = defs.childNodes[0].getAttribute("id"); + this.__ids[id] = id; + this.__defs.appendChild(defs.childNodes[0]); + } + group = svg.childNodes[1]; + if (group) { + //save original transform + var originTransform = group.getAttribute("transform"); + var transformDirective; + if (originTransform) { + transformDirective = originTransform+" "+translateDirective; + } else { + transformDirective = translateDirective; + } + group.setAttribute("transform", transformDirective); + parent.appendChild(group); + } + } + } else if(image.nodeName === "CANVAS" || image.nodeName === "IMG") { + //canvas or image + svgImage = this.__createElement("image"); + svgImage.setAttribute("width", dw); + svgImage.setAttribute("height", dh); + svgImage.setAttribute("preserveAspectRatio", "none"); + + if(sx || sy || sw !== image.width || sh !== image.height) { + //crop the image using a temporary canvas + canvas = this.__document.createElement("canvas"); + canvas.width = dw; + canvas.height = dh; + context = canvas.getContext("2d"); + context.drawImage(image, sx, sy, sw, sh, 0, 0, dw, dh); + image = canvas; + } + svgImage.setAttribute("transform", translateDirective); + svgImage.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", + image.nodeName === "CANVAS" ? image.toDataURL() : image.getAttribute("src")); + parent.appendChild(svgImage); + } + }; + + /** + * Generates a pattern tag + */ + ctx.prototype.createPattern = function(image, repetition){ + var pattern = this.__document.createElementNS("http://www.w3.org/2000/svg", "pattern"), id = randomString(this.__ids), + img; + pattern.setAttribute("id", id); + pattern.setAttribute("width", image.width); + pattern.setAttribute("height", image.height); + if(image.nodeName === "CANVAS" || image.nodeName === "IMG") { + img = this.__document.createElementNS("http://www.w3.org/2000/svg", "image"); + img.setAttribute("width", image.width); + img.setAttribute("height", image.height); + img.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", + image.nodeName === "CANVAS" ? image.toDataURL() : image.getAttribute("src")); + pattern.appendChild(img); + this.__defs.appendChild(pattern); + } else if(image instanceof ctx) { + pattern.appendChild(image.__root.childNodes[1]); + this.__defs.appendChild(pattern); + } + return new CanvasPattern(pattern, this); + }; + + ctx.prototype.setLineDash = function(dashArray) { + if (dashArray && dashArray.length > 0) { + this.lineDash = dashArray.join(","); + } else { + this.lineDash = null; + } + }; + + /** + * Not yet implemented + */ + ctx.prototype.drawFocusRing = function(){}; + ctx.prototype.createImageData = function(){}; + ctx.prototype.getImageData = function(){}; + ctx.prototype.putImageData = function(){}; + ctx.prototype.globalCompositeOperation = function(){}; + ctx.prototype.setTransform = function(){}; + + //add options for alternative namespace + if (typeof window === "object") { + window.C2S = ctx; + } + + // CommonJS/Browserify + if (typeof module === "object" && typeof module.exports === "object") { + module.exports = ctx; + } + +}()); diff --git a/comfyui-custom-scripts/web/js/assets/favicon-active.ico b/comfyui-custom-scripts/web/js/assets/favicon-active.ico new file mode 100644 index 0000000000000000000000000000000000000000..64045ab56e87879adb039b1fdb0bbbe0462143e7 Binary files /dev/null and b/comfyui-custom-scripts/web/js/assets/favicon-active.ico differ diff --git a/comfyui-custom-scripts/web/js/assets/favicon.ico b/comfyui-custom-scripts/web/js/assets/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..08df2481551bb6903735fa69d658b5abfb0a5ae1 Binary files /dev/null and b/comfyui-custom-scripts/web/js/assets/favicon.ico differ diff --git a/comfyui-custom-scripts/web/js/assets/no-image.png b/comfyui-custom-scripts/web/js/assets/no-image.png new file mode 100644 index 0000000000000000000000000000000000000000..d0b58b2c9d3ad82a2a949933648f8691ff36ba84 Binary files /dev/null and b/comfyui-custom-scripts/web/js/assets/no-image.png differ diff --git a/comfyui-custom-scripts/web/js/assets/notify.mp3 b/comfyui-custom-scripts/web/js/assets/notify.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..5e3fdabbb12142dfa75702a0b0e0ca5e5425a7dd Binary files /dev/null and b/comfyui-custom-scripts/web/js/assets/notify.mp3 differ diff --git a/comfyui-custom-scripts/web/js/autocompleter.js b/comfyui-custom-scripts/web/js/autocompleter.js new file mode 100644 index 0000000000000000000000000000000000000000..d0fb2ecae710d291d0d42845a6e0395f61c74e4d --- /dev/null +++ b/comfyui-custom-scripts/web/js/autocompleter.js @@ -0,0 +1,602 @@ +import { app } from "../../../scripts/app.js"; +import { ComfyWidgets } from "../../../scripts/widgets.js"; +import { api } from "../../../scripts/api.js"; +import { $el, ComfyDialog } from "../../../scripts/ui.js"; +import { TextAreaAutoComplete } from "./common/autocomplete.js"; +import { ModelInfoDialog } from "./common/modelInfoDialog.js"; +import { LoraInfoDialog } from "./modelInfo.js"; + +function parseCSV(csvText) { + const rows = []; + const delimiter = ","; + const quote = '"'; + let currentField = ""; + let inQuotedField = false; + + function pushField() { + rows[rows.length - 1].push(currentField); + currentField = ""; + inQuotedField = false; + } + + rows.push([]); // Initialize the first row + + for (let i = 0; i < csvText.length; i++) { + const char = csvText[i]; + const nextChar = csvText[i + 1]; + + // Special handling for backslash escaped quotes + if (char === "\\" && nextChar === quote) { + currentField += quote; + i++; + } + + if (!inQuotedField) { + if (char === quote) { + inQuotedField = true; + } else if (char === delimiter) { + pushField(); + } else if (char === "\r" || char === "\n" || i === csvText.length - 1) { + pushField(); + if (nextChar === "\n") { + i++; // Handle Windows line endings (\r\n) + } + rows.push([]); // Start a new row + } else { + currentField += char; + } + } else { + if (char === quote && nextChar === quote) { + currentField += quote; + i++; // Skip the next quote + } else if (char === quote) { + inQuotedField = false; + } else if (char === "\r" || char === "\n" || i === csvText.length - 1) { + // Dont allow new lines in quoted text, assume its wrong + const parsed = parseCSV(currentField); + rows.pop(); + rows.push(...parsed); + inQuotedField = false; + currentField = ""; + rows.push([]); + } else { + currentField += char; + } + } + } + + if (currentField || csvText[csvText.length - 1] === ",") { + pushField(); + } + + // Remove the last row if it's empty + if (rows[rows.length - 1].length === 0) { + rows.pop(); + } + + return rows; +} + +async function getCustomWords() { + const resp = await api.fetchApi("/pysssss/autocomplete", { cache: "no-store" }); + if (resp.status === 200) { + return await resp.text(); + } + return undefined; +} + +async function addCustomWords(text) { + if (!text) { + text = await getCustomWords(); + } + if (text) { + TextAreaAutoComplete.updateWords( + "pysssss.customwords", + parseCSV(text).reduce((p, n) => { + let text; + let priority; + let value; + let num; + switch (n.length) { + case 0: + return; + case 1: + // Single word + text = n[0]; + break; + case 2: + // Word,[priority|alias] + num = +n[1]; + if (isNaN(num)) { + text = n[0] + "🔄️" + n[1]; + value = n[0]; + } else { + text = n[0]; + priority = num; + } + break; + case 4: + // a1111 csv format? + value = n[0]; + priority = +n[2]; + const aliases = n[3]?.trim(); + if (aliases && aliases !== "null") { // Weird null in an example csv, maybe they are JSON.parsing the last column? + const split = aliases.split(","); + for (const text of split) { + p[text] = { text, priority, value }; + } + } + text = value; + break; + default: + // Word,alias,priority + text = n[1]; + value = n[0]; + priority = +n[2]; + break; + } + p[text] = { text, priority, value }; + return p; + }, {}) + ); + } +} + +function toggleLoras() { + [TextAreaAutoComplete.globalWords, TextAreaAutoComplete.globalWordsExclLoras] = [ + TextAreaAutoComplete.globalWordsExclLoras, + TextAreaAutoComplete.globalWords, + ]; +} + +class EmbeddingInfoDialog extends ModelInfoDialog { + async addInfo() { + super.addInfo(); + const info = await this.addCivitaiInfo(); + if (info) { + $el("div", { + parent: this.content, + innerHTML: info.description, + style: { + maxHeight: "250px", + overflow: "auto", + }, + }); + } + } +} + +class CustomWordsDialog extends ComfyDialog { + async show() { + const text = await getCustomWords(); + this.words = $el("textarea", { + textContent: text, + style: { + width: "70vw", + height: "70vh", + }, + }); + + const input = $el("input", { + style: { + flex: "auto", + }, + value: + "https://gist.githubusercontent.com/pythongosssss/1d3efa6050356a08cea975183088159a/raw/a18fb2f94f9156cf4476b0c24a09544d6c0baec6/danbooru-tags.txt", + }); + + super.show( + $el( + "div", + { + style: { + display: "flex", + flexDirection: "column", + overflow: "hidden", + maxHeight: "100%", + }, + }, + [ + $el("h2", { + textContent: "Custom Autocomplete Words", + style: { + color: "#fff", + marginTop: 0, + textAlign: "center", + fontFamily: "sans-serif", + }, + }), + $el( + "div", + { + style: { + color: "#fff", + fontFamily: "sans-serif", + display: "flex", + alignItems: "center", + gap: "5px", + }, + }, + [ + $el("label", { textContent: "Load Custom List: " }), + input, + $el("button", { + textContent: "Load", + onclick: async () => { + try { + const res = await fetch(input.value); + if (res.status !== 200) { + throw new Error("Error loading: " + res.status + " " + res.statusText); + } + this.words.value = await res.text(); + } catch (error) { + alert("Error loading custom list, try manually copy + pasting the list"); + } + }, + }), + ] + ), + this.words, + ] + ) + ); + } + + createButtons() { + const btns = super.createButtons(); + const save = $el("button", { + type: "button", + textContent: "Save", + onclick: async (e) => { + try { + const res = await api.fetchApi("/pysssss/autocomplete", { method: "POST", body: this.words.value }); + if (res.status !== 200) { + throw new Error("Error saving: " + res.status + " " + res.statusText); + } + save.textContent = "Saved!"; + addCustomWords(this.words.value); + setTimeout(() => { + save.textContent = "Save"; + }, 500); + } catch (error) { + alert("Error saving word list!"); + console.error(error); + } + }, + }); + + btns.unshift(save); + return btns; + } +} + +const id = "pysssss.AutoCompleter"; + +app.registerExtension({ + name: id, + init() { + const STRING = ComfyWidgets.STRING; + const SKIP_WIDGETS = new Set(["ttN xyPlot.x_values", "ttN xyPlot.y_values"]); + ComfyWidgets.STRING = function (node, inputName, inputData) { + const r = STRING.apply(this, arguments); + + if (inputData[1]?.multiline) { + // Disabled on this input + const config = inputData[1]?.["pysssss.autocomplete"]; + if (config === false) return r; + + // In list of widgets to skip + const id = `${node.comfyClass}.${inputName}`; + if (SKIP_WIDGETS.has(id)) return r; + + let words; + let separator; + if (typeof config === "object") { + separator = config.separator; + words = {}; + if (config.words) { + // Custom wordlist, this will have been registered on setup + Object.assign(words, TextAreaAutoComplete.groups[node.comfyClass + "." + inputName] ?? {}); + } + + for (const item of config.groups ?? []) { + if (item === "*") { + // This widget wants all global words included + Object.assign(words, TextAreaAutoComplete.globalWords); + } else { + // This widget wants a specific group included + Object.assign(words, TextAreaAutoComplete.groups[item] ?? {}); + } + } + } + + new TextAreaAutoComplete(r.widget.inputEl, words, separator); + } + + return r; + }; + + TextAreaAutoComplete.globalSeparator = localStorage.getItem(id + ".AutoSeparate") ?? ", "; + const enabledSetting = app.ui.settings.addSetting({ + id, + name: "🐍 Text Autocomplete", + defaultValue: true, + type: (name, setter, value) => { + return $el("tr", [ + $el("td", [ + $el("label", { + for: id.replaceAll(".", "-"), + textContent: name, + }), + ]), + $el("td", [ + $el( + "label", + { + textContent: "Enabled ", + style: { + display: "block", + }, + }, + [ + $el("input", { + id: id.replaceAll(".", "-"), + type: "checkbox", + checked: value, + onchange: (event) => { + const checked = !!event.target.checked; + TextAreaAutoComplete.enabled = checked; + setter(checked); + }, + }), + ] + ), + $el( + "label.comfy-tooltip-indicator", + { + title: "This requires other ComfyUI nodes/extensions that support using LoRAs in the prompt.", + textContent: "Loras enabled ", + style: { + display: "block", + }, + }, + [ + $el("input", { + type: "checkbox", + checked: !!TextAreaAutoComplete.lorasEnabled, + onchange: (event) => { + const checked = !!event.target.checked; + TextAreaAutoComplete.lorasEnabled = checked; + toggleLoras(); + localStorage.setItem(id + ".ShowLoras", TextAreaAutoComplete.lorasEnabled); + }, + }), + ] + ), + $el( + "label", + { + textContent: "Auto-insert comma ", + style: { + display: "block", + }, + }, + [ + $el("input", { + type: "checkbox", + checked: !!TextAreaAutoComplete.globalSeparator, + onchange: (event) => { + const checked = !!event.target.checked; + TextAreaAutoComplete.globalSeparator = checked ? ", " : ""; + localStorage.setItem(id + ".AutoSeparate", TextAreaAutoComplete.globalSeparator); + }, + }), + ] + ), + $el( + "label", + { + textContent: "Replace _ with space ", + style: { + display: "block", + }, + }, + [ + $el("input", { + type: "checkbox", + checked: !!TextAreaAutoComplete.replacer, + onchange: (event) => { + const checked = !!event.target.checked; + TextAreaAutoComplete.replacer = checked ? (v) => v.replaceAll("_", " ") : undefined; + localStorage.setItem(id + ".ReplaceUnderscore", checked); + }, + }), + ] + ), + $el( + "label", + { + textContent: "Insert suggestion on: ", + style: { + display: "block", + }, + }, + [ + $el( + "label", + { + textContent: "Tab", + style: { + display: "block", + marginLeft: "20px", + }, + }, + [ + $el("input", { + type: "checkbox", + checked: !!TextAreaAutoComplete.insertOnTab, + onchange: (event) => { + const checked = !!event.target.checked; + TextAreaAutoComplete.insertOnTab = checked; + localStorage.setItem(id + ".InsertOnTab", checked); + }, + }), + ] + ), + $el( + "label", + { + textContent: "Enter", + style: { + display: "block", + marginLeft: "20px", + }, + }, + [ + $el("input", { + type: "checkbox", + checked: !!TextAreaAutoComplete.insertOnEnter, + onchange: (event) => { + const checked = !!event.target.checked; + TextAreaAutoComplete.insertOnEnter = checked; + localStorage.setItem(id + ".InsertOnEnter", checked); + }, + }), + ] + ), + ] + ), + $el( + "label", + { + textContent: "Max suggestions: ", + style: { + display: "block", + }, + }, + [ + $el("input", { + type: "number", + value: +TextAreaAutoComplete.suggestionCount, + style: { + width: "80px" + }, + onchange: (event) => { + const value = +event.target.value; + TextAreaAutoComplete.suggestionCount = value;; + localStorage.setItem(id + ".SuggestionCount", TextAreaAutoComplete.suggestionCount); + }, + }), + ] + ), + $el("button", { + textContent: "Manage Custom Words", + onclick: () => { + try { + // Try closing old settings window + if (typeof app.ui.settings.element?.close === "function") { + app.ui.settings.element.close(); + } + } catch (error) { + } + try { + // Try closing new vue dialog + document.querySelector(".p-dialog-close-button").click(); + } catch (error) { + // Fallback to just hiding the element + app.ui.settings.element.style.display = "none"; + } + + new CustomWordsDialog().show(); + }, + style: { + fontSize: "14px", + display: "block", + marginTop: "5px", + }, + }), + ]), + ]); + }, + }); + + TextAreaAutoComplete.enabled = enabledSetting.value; + TextAreaAutoComplete.replacer = localStorage.getItem(id + ".ReplaceUnderscore") === "true" ? (v) => v.replaceAll("_", " ") : undefined; + TextAreaAutoComplete.insertOnTab = localStorage.getItem(id + ".InsertOnTab") !== "false"; + TextAreaAutoComplete.insertOnEnter = localStorage.getItem(id + ".InsertOnEnter") !== "false"; + TextAreaAutoComplete.lorasEnabled = localStorage.getItem(id + ".ShowLoras") === "true"; + TextAreaAutoComplete.suggestionCount = +localStorage.getItem(id + ".SuggestionCount") || 20; + }, + setup() { + async function addEmbeddings() { + const embeddings = await api.getEmbeddings(); + const words = {}; + words["embedding:"] = { text: "embedding:" }; + + for (const emb of embeddings) { + const v = `embedding:${emb}`; + words[v] = { + text: v, + info: () => new EmbeddingInfoDialog(emb).show("embeddings", emb), + use_replacer: false, + }; + } + + TextAreaAutoComplete.updateWords("pysssss.embeddings", words); + } + + async function addLoras() { + let loras; + try { + loras = LiteGraph.registered_node_types["LoraLoader"]?.nodeData.input.required.lora_name[0]; + } catch (error) {} + + if (!loras?.length) { + loras = await api.fetchApi("/pysssss/loras", { cache: "no-store" }).then((res) => res.json()); + } + + const words = {}; + words["lora:"] = { text: "lora:" }; + + for (const lora of loras) { + const v = ``; + words[v] = { + text: v, + info: () => new LoraInfoDialog(lora).show("loras", lora), + use_replacer: false, + }; + } + + TextAreaAutoComplete.updateWords("pysssss.loras", words); + } + + // store global words with/without loras + Promise.all([addEmbeddings(), addCustomWords()]) + .then(() => { + TextAreaAutoComplete.globalWordsExclLoras = Object.assign({}, TextAreaAutoComplete.globalWords); + }) + .then(addLoras) + .then(() => { + if (!TextAreaAutoComplete.lorasEnabled) { + toggleLoras(); // off by default + } + }); + }, + beforeRegisterNodeDef(_, def) { + // Process each input to see if there is a custom word list for + // { input: { required: { something: ["STRING", { "pysssss.autocomplete": ["groupid", ["custom", "words"] ] }] } } } + const inputs = { ...def.input?.required, ...def.input?.optional }; + for (const input in inputs) { + const config = inputs[input][1]?.["pysssss.autocomplete"]; + if (!config) continue; + if (typeof config === "object" && config.words) { + const words = {}; + for (const text of config.words || []) { + const obj = typeof text === "string" ? { text } : text; + words[obj.text] = obj; + } + TextAreaAutoComplete.updateWords(def.name + "." + input, words, false); + } + } + }, +}); diff --git a/comfyui-custom-scripts/web/js/betterCombos.js b/comfyui-custom-scripts/web/js/betterCombos.js new file mode 100644 index 0000000000000000000000000000000000000000..cbf0a0740471035dc1d1d4f14101c4888dd91c2a --- /dev/null +++ b/comfyui-custom-scripts/web/js/betterCombos.js @@ -0,0 +1,534 @@ +import { app } from "../../../scripts/app.js"; +import { ComfyWidgets } from "../../../scripts/widgets.js"; +import { $el } from "../../../scripts/ui.js"; +import { api } from "../../../scripts/api.js"; + +const CHECKPOINT_LOADER = "CheckpointLoader|pysssss"; +const LORA_LOADER = "LoraLoader|pysssss"; +const IMAGE_WIDTH = 384; +const IMAGE_HEIGHT = 384; + +function getType(node) { + if (node.comfyClass === CHECKPOINT_LOADER) { + return "checkpoints"; + } + return "loras"; +} + +function getWidgetName(type) { + return type === "checkpoints" ? "ckpt_name" : "lora_name"; +} + +function encodeRFC3986URIComponent(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`); +} + +const calculateImagePosition = (el, bodyRect) => { + let { top, left, right } = el.getBoundingClientRect(); + const { width: bodyWidth, height: bodyHeight } = bodyRect; + + const isSpaceRight = right + IMAGE_WIDTH <= bodyWidth; + if (isSpaceRight) { + left = right; + } else { + left -= IMAGE_WIDTH; + } + + top = top - IMAGE_HEIGHT / 2; + if (top + IMAGE_HEIGHT > bodyHeight) { + top = bodyHeight - IMAGE_HEIGHT; + } + if (top < 0) { + top = 0; + } + + return { left: Math.round(left), top: Math.round(top), isLeft: !isSpaceRight }; +}; + +function showImage(relativeToEl, imageEl) { + const bodyRect = document.body.getBoundingClientRect(); + if (!bodyRect) return; + + const { left, top, isLeft } = calculateImagePosition(relativeToEl, bodyRect); + + imageEl.style.left = `${left}px`; + imageEl.style.top = `${top}px`; + + if (isLeft) { + imageEl.classList.add("left"); + } else { + imageEl.classList.remove("left"); + } + + document.body.appendChild(imageEl); +} + +let imagesByType = {}; +const loadImageList = async (type) => { + imagesByType[type] = await (await api.fetchApi(`/pysssss/images/${type}`)).json(); +}; + +app.registerExtension({ + name: "pysssss.Combo++", + init() { + const displayOptions = { "List (normal)": 0, "Tree (subfolders)": 1, "Thumbnails (grid)": 2 }; + const displaySetting = app.ui.settings.addSetting({ + id: "pysssss.Combo++.Submenu", + name: "🐍 Lora & Checkpoint loader display mode", + defaultValue: 1, + type: "combo", + options: (value) => { + value = +value; + + return Object.entries(displayOptions).map(([k, v]) => ({ + value: v, + text: k, + selected: k === value, + })); + }, + }); + + $el("style", { + textContent: ` + .pysssss-combo-image { + position: absolute; + left: 0; + top: 0; + width: ${IMAGE_WIDTH}px; + height: ${IMAGE_HEIGHT}px; + object-fit: contain; + object-position: top left; + z-index: 9999; + } + .pysssss-combo-image.left { + object-position: top right; + } + .pysssss-combo-folder { opacity: 0.7 } + .pysssss-combo-folder-arrow { display: inline-block; width: 15px; } + .pysssss-combo-folder:hover { background-color: rgba(255, 255, 255, 0.1); } + .pysssss-combo-prefix { display: none } + + /* Special handling for when the filter input is populated to revert to normal */ + .litecontextmenu:has(input:not(:placeholder-shown)) .pysssss-combo-folder-contents { + display: block !important; + } + .litecontextmenu:has(input:not(:placeholder-shown)) .pysssss-combo-folder { + display: none; + } + .litecontextmenu:has(input:not(:placeholder-shown)) .pysssss-combo-prefix { + display: inline; + } + .litecontextmenu:has(input:not(:placeholder-shown)) .litemenu-entry { + padding-left: 2px !important; + } + + /* Grid mode */ + .pysssss-combo-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); + gap: 10px; + overflow-x: hidden; + max-width: 60vw; + } + .pysssss-combo-grid .comfy-context-menu-filter { + grid-column: 1 / -1; + position: sticky; + top: 0; + } + .pysssss-combo-grid .litemenu-entry { + word-break: break-word; + display: flex; + flex-direction: column; + justify-content: space-between; + align-items: center; + } + .pysssss-combo-grid .litemenu-entry:before { + content: ""; + display: block; + width: 100%; + height: 250px; + background-size: contain; + background-position: center; + background-repeat: no-repeat; + /* No-image image attribution: Picture icons created by Pixel perfect - Flaticon */ + background-image: var(--background-image, url(extensions/ComfyUI-Custom-Scripts/js/assets/no-image.png)); + } + + `, + parent: document.body, + }); + const p1 = loadImageList("checkpoints"); + const p2 = loadImageList("loras"); + + const refreshComboInNodes = app.refreshComboInNodes; + app.refreshComboInNodes = async function () { + const r = await Promise.all([ + refreshComboInNodes.apply(this, arguments), + loadImageList("checkpoints").catch(() => {}), + loadImageList("loras").catch(() => {}), + ]); + return r[0]; + }; + + const imageHost = $el("img.pysssss-combo-image"); + + const positionMenu = (menu, fillWidth) => { + // compute best position + let left = app.canvas.last_mouse[0] - 10; + let top = app.canvas.last_mouse[1] - 10; + + const body_rect = document.body.getBoundingClientRect(); + const root_rect = menu.getBoundingClientRect(); + + if (body_rect.width && left > body_rect.width - root_rect.width - 10) left = body_rect.width - root_rect.width - 10; + if (body_rect.height && top > body_rect.height - root_rect.height - 10) top = body_rect.height - root_rect.height - 10; + + menu.style.left = `${left}px`; + menu.style.top = `${top}px`; + if (fillWidth) { + menu.style.right = "10px"; + } + }; + + const updateMenu = async (menu, type) => { + try { + await p1; + await p2; + } catch (error) { + console.error(error); + console.error("Error loading pysssss.betterCombos data"); + } + + // Clamp max height so it doesn't overflow the screen + const position = menu.getBoundingClientRect(); + const maxHeight = window.innerHeight - position.top - 20; + menu.style.maxHeight = `${maxHeight}px`; + + const images = imagesByType[type]; + const items = menu.querySelectorAll(".litemenu-entry"); + + // Add image handler to items + const addImageHandler = (item) => { + const text = item.getAttribute("data-value").trim(); + if (images[text]) { + const textNode = document.createTextNode("*"); + item.appendChild(textNode); + + item.addEventListener( + "mouseover", + () => { + imageHost.src = `/pysssss/view/${encodeRFC3986URIComponent(images[text])}?${+new Date()}`; + document.body.appendChild(imageHost); + showImage(item, imageHost); + }, + { passive: true } + ); + item.addEventListener( + "mouseout", + () => { + imageHost.remove(); + }, + { passive: true } + ); + item.addEventListener( + "click", + () => { + imageHost.remove(); + }, + { passive: true } + ); + } + }; + + const createTree = () => { + // Create a map to store folder structures + const folderMap = new Map(); + const rootItems = []; + const splitBy = (navigator.platform || navigator.userAgent).includes("Win") ? /\/|\\/ : /\//; + const itemsSymbol = Symbol("items"); + + // First pass - organize items into folder structure + for (const item of items) { + const path = item.getAttribute("data-value").split(splitBy); + + // Remove path from visible text + item.textContent = path[path.length - 1]; + if (path.length > 1) { + // Add the prefix path back in so it can be filtered on + const prefix = $el("span.pysssss-combo-prefix", { + textContent: path.slice(0, -1).join("/") + "/", + }); + item.prepend(prefix); + } + + addImageHandler(item); + + if (path.length === 1) { + rootItems.push(item); + continue; + } + + // Temporarily remove the item from current position + item.remove(); + + // Create folder hierarchy + let currentLevel = folderMap; + for (let i = 0; i < path.length - 1; i++) { + const folder = path[i]; + if (!currentLevel.has(folder)) { + currentLevel.set(folder, new Map()); + } + currentLevel = currentLevel.get(folder); + } + + // Store the actual item in the deepest folder + if (!currentLevel.has(itemsSymbol)) { + currentLevel.set(itemsSymbol, []); + } + currentLevel.get(itemsSymbol).push(item); + } + + const createFolderElement = (name) => { + const folder = $el("div.litemenu-entry.pysssss-combo-folder", { + innerHTML: `▶ ${name}`, + style: { paddingLeft: "5px" }, + }); + return folder; + }; + + const insertFolderStructure = (parentElement, map, level = 0) => { + for (const [folderName, content] of map.entries()) { + if (folderName === itemsSymbol) continue; + + const folderElement = createFolderElement(folderName); + folderElement.style.paddingLeft = `${level * 10 + 5}px`; + parentElement.appendChild(folderElement); + + const childContainer = $el("div.pysssss-combo-folder-contents", { + style: { display: "none" }, + }); + + // Add items in this folder + const items = content.get(itemsSymbol) || []; + for (const item of items) { + item.style.paddingLeft = `${(level + 1) * 10 + 14}px`; + childContainer.appendChild(item); + } + + // Recursively add subfolders + insertFolderStructure(childContainer, content, level + 1); + parentElement.appendChild(childContainer); + + // Add click handler for folder + folderElement.addEventListener("click", (e) => { + e.stopPropagation(); + const arrow = folderElement.querySelector(".pysssss-combo-folder-arrow"); + const contents = folderElement.nextElementSibling; + if (contents.style.display === "none") { + contents.style.display = "block"; + arrow.textContent = "▼"; + } else { + contents.style.display = "none"; + arrow.textContent = "▶"; + } + }); + } + }; + + insertFolderStructure(items[0]?.parentElement || menu, folderMap); + positionMenu(menu); + }; + + const addImageData = (item) => { + const text = item.getAttribute("data-value").trim(); + if (images[text]) { + item.style.setProperty("--background-image", `url(/pysssss/view/${encodeRFC3986URIComponent(images[text])})`); + } + }; + + if (displaySetting.value === 1 || displaySetting.value === true) { + createTree(); + } else if (displaySetting.value === 2) { + menu.classList.add("pysssss-combo-grid"); + + for (const item of items) { + addImageData(item); + } + positionMenu(menu, true); + } else { + for (const item of items) { + addImageHandler(item); + } + } + }; + + const mutationObserver = new MutationObserver((mutations) => { + const node = app.canvas.current_node; + + if (!node || (node.comfyClass !== LORA_LOADER && node.comfyClass !== CHECKPOINT_LOADER)) { + return; + } + + for (const mutation of mutations) { + for (const removed of mutation.removedNodes) { + if (removed.classList?.contains("litecontextmenu")) { + imageHost.remove(); + } + } + + for (const added of mutation.addedNodes) { + if (added.classList?.contains("litecontextmenu")) { + const overWidget = app.canvas.getWidgetAtCursor(); + const type = getType(node); + if (overWidget?.name === getWidgetName(type)) { + requestAnimationFrame(() => { + // Bad hack to prevent showing on right click menu by checking for the filter input + if (!added.querySelector(".comfy-context-menu-filter")) return; + updateMenu(added, type); + }); + } + return; + } + } + } + }); + mutationObserver.observe(document.body, { childList: true, subtree: false }); + }, + async beforeRegisterNodeDef(nodeType, nodeData, app) { + const isCkpt = nodeData.name === CHECKPOINT_LOADER; + const isLora = nodeData.name === LORA_LOADER; + if (isCkpt || isLora) { + const onAdded = nodeType.prototype.onAdded; + nodeType.prototype.onAdded = function () { + onAdded?.apply(this, arguments); + const { widget: exampleList } = ComfyWidgets["COMBO"](this, "example", [[""], {}], app); + this.widgets.find((w) => w.name === "prompt").computeSize = () => [0, -4]; + let exampleWidget; + + const get = async (route, suffix) => { + const url = encodeRFC3986URIComponent(`${getType(nodeType)}${suffix || ""}`); + return await api.fetchApi(`/pysssss/${route}/${url}`); + }; + + const getExample = async () => { + if (exampleList.value === "[none]") { + if (exampleWidget) { + exampleWidget.inputEl.remove(); + exampleWidget = null; + this.widgets.length -= 1; + } + return; + } + + const v = this.widgets[0].value; + const pos = v.lastIndexOf("."); + const name = v.substr(0, pos); + let exampleName = exampleList.value; + let viewPath = `/${name}`; + if (exampleName === "notes") { + viewPath += ".txt"; + } else { + viewPath += `/${exampleName}`; + } + const example = await (await get("view", viewPath)).text(); + if (!exampleWidget) { + exampleWidget = ComfyWidgets["STRING"](this, "prompt", ["STRING", { multiline: true }], app).widget; + exampleWidget.inputEl.readOnly = true; + exampleWidget.inputEl.style.opacity = 0.6; + } + exampleWidget.value = example; + }; + + const exampleCb = exampleList.callback; + exampleList.callback = function () { + getExample(); + return exampleCb?.apply(this, arguments) ?? exampleList.value; + }; + + const listExamples = async () => { + exampleList.disabled = true; + exampleList.options.values = ["[none]"]; + exampleList.value = "[none]"; + let examples = []; + if (this.widgets[0].value) { + try { + examples = await (await get("examples", `/${this.widgets[0].value}`)).json(); + } catch (error) {} + } + exampleList.options.values = ["[none]", ...examples]; + exampleList.value = exampleList.options.values[+!!examples.length]; + exampleList.callback(); + exampleList.disabled = !examples.length; + app.graph.setDirtyCanvas(true, true); + }; + + // Expose function to update examples + nodeType.prototype["pysssss.updateExamples"] = listExamples; + + const modelWidget = this.widgets[0]; + const modelCb = modelWidget.callback; + let prev = undefined; + modelWidget.callback = function () { + let ret = modelCb?.apply(this, arguments) ?? modelWidget.value; + if (typeof ret === "object" && "content" in ret) { + ret = ret.content; + modelWidget.value = ret; + } + let v = ret; + if (prev !== v) { + listExamples(); + prev = v; + } + return ret; + }; + setTimeout(() => { + modelWidget.callback(); + }, 30); + }; + } + + const getExtraMenuOptions = nodeType.prototype.getExtraMenuOptions; + nodeType.prototype.getExtraMenuOptions = function (_, options) { + if (this.imgs) { + // If this node has images then we add an open in new tab item + let img; + if (this.imageIndex != null) { + // An image is selected so select that + img = this.imgs[this.imageIndex]; + } else if (this.overIndex != null) { + // No image is selected but one is hovered + img = this.imgs[this.overIndex]; + } + if (img) { + const nodes = app.graph._nodes.filter((n) => n.comfyClass === LORA_LOADER || n.comfyClass === CHECKPOINT_LOADER); + if (nodes.length) { + options.unshift({ + content: "Save as Preview", + submenu: { + options: nodes.map((n) => ({ + content: n.widgets[0].value, + callback: async () => { + const url = new URL(img.src); + await api.fetchApi("/pysssss/save/" + encodeRFC3986URIComponent(`${getType(n)}/${n.widgets[0].value}`), { + method: "POST", + body: JSON.stringify({ + filename: url.searchParams.get("filename"), + subfolder: url.searchParams.get("subfolder"), + type: url.searchParams.get("type"), + }), + headers: { + "content-type": "application/json", + }, + }); + loadImageList(getType(n)); + }, + })), + }, + }); + } + } + } + return getExtraMenuOptions?.apply(this, arguments); + }; + }, +}); diff --git a/comfyui-custom-scripts/web/js/common/autocomplete.css b/comfyui-custom-scripts/web/js/common/autocomplete.css new file mode 100644 index 0000000000000000000000000000000000000000..1f371d6203a94202c48c851a3321c7e423de477b --- /dev/null +++ b/comfyui-custom-scripts/web/js/common/autocomplete.css @@ -0,0 +1,62 @@ +.pysssss-autocomplete { + color: var(--descrip-text); + background-color: var(--comfy-menu-bg); + position: absolute; + font-family: sans-serif; + box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.4); + z-index: 9999; + overflow: auto; +} + +.pysssss-autocomplete-item { + cursor: pointer; + padding: 3px 7px; + display: flex; + border-left: 3px solid transparent; + align-items: center; +} + +.pysssss-autocomplete-item--selected { + border-left-color: dodgerblue; +} + +.pysssss-autocomplete-highlight { + font-weight: bold; + text-decoration: underline; + text-decoration-color: dodgerblue; +} + +.pysssss-autocomplete-pill { + margin-left: auto; + font-size: 10px; + color: #fff; + padding: 2px 4px 2px 14px; + position: relative; +} + +.pysssss-autocomplete-pill::after { + content: ""; + display: block; + background: rgba(255, 255, 255, 0.25); + width: calc(100% - 10px); + height: 100%; + position: absolute; + left: 10px; + top: 0; + border-radius: 5px; +} + +.pysssss-autocomplete-pill + .pysssss-autocomplete-pill { + margin-left: 0; +} + +.pysssss-autocomplete-item-info { + margin-left: auto; + transition: filter 0.2s; + will-change: filter; + text-decoration: none; + padding-left: 10px; +} +.pysssss-autocomplete-item-info:hover { + filter: invert(1); +} diff --git a/comfyui-custom-scripts/web/js/common/autocomplete.js b/comfyui-custom-scripts/web/js/common/autocomplete.js new file mode 100644 index 0000000000000000000000000000000000000000..ac5fb1d006bad80c67870655ccfc82a120ddc4a7 --- /dev/null +++ b/comfyui-custom-scripts/web/js/common/autocomplete.js @@ -0,0 +1,692 @@ +import { $el } from "../../../../scripts/ui.js"; +import { addStylesheet } from "./utils.js"; + +addStylesheet(import.meta.url); + +/* + https://github.com/component/textarea-caret-position + The MIT License (MIT) + + Copyright (c) 2015 Jonathan Ong me@jongleberry.com + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +const getCaretCoordinates = (function () { + // We'll copy the properties below into the mirror div. + // Note that some browsers, such as Firefox, do not concatenate properties + // into their shorthand (e.g. padding-top, padding-bottom etc. -> padding), + // so we have to list every single property explicitly. + var properties = [ + "direction", // RTL support + "boxSizing", + "width", // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does + "height", + "overflowX", + "overflowY", // copy the scrollbar for IE + + "borderTopWidth", + "borderRightWidth", + "borderBottomWidth", + "borderLeftWidth", + "borderStyle", + + "paddingTop", + "paddingRight", + "paddingBottom", + "paddingLeft", + + // https://developer.mozilla.org/en-US/docs/Web/CSS/font + "fontStyle", + "fontVariant", + "fontWeight", + "fontStretch", + "fontSize", + "fontSizeAdjust", + "lineHeight", + "fontFamily", + + "textAlign", + "textTransform", + "textIndent", + "textDecoration", // might not make a difference, but better be safe + + "letterSpacing", + "wordSpacing", + + "tabSize", + "MozTabSize", + ]; + + var isBrowser = typeof window !== "undefined"; + var isFirefox = isBrowser && window.mozInnerScreenX != null; + + return function getCaretCoordinates(element, position, options) { + if (!isBrowser) { + throw new Error("textarea-caret-position#getCaretCoordinates should only be called in a browser"); + } + + var debug = (options && options.debug) || false; + if (debug) { + var el = document.querySelector("#input-textarea-caret-position-mirror-div"); + if (el) el.parentNode.removeChild(el); + } + + // The mirror div will replicate the textarea's style + var div = document.createElement("div"); + div.id = "input-textarea-caret-position-mirror-div"; + document.body.appendChild(div); + + var style = div.style; + var computed = window.getComputedStyle ? window.getComputedStyle(element) : element.currentStyle; // currentStyle for IE < 9 + var isInput = element.nodeName === "INPUT"; + + // Default textarea styles + style.whiteSpace = "pre-wrap"; + if (!isInput) style.wordWrap = "break-word"; // only for textarea-s + + // Position off-screen + style.position = "absolute"; // required to return coordinates properly + if (!debug) style.visibility = "hidden"; // not 'display: none' because we want rendering + + // Transfer the element's properties to the div + properties.forEach(function (prop) { + if (isInput && prop === "lineHeight") { + // Special case for s because text is rendered centered and line height may be != height + if (computed.boxSizing === "border-box") { + var height = parseInt(computed.height); + var outerHeight = + parseInt(computed.paddingTop) + + parseInt(computed.paddingBottom) + + parseInt(computed.borderTopWidth) + + parseInt(computed.borderBottomWidth); + var targetHeight = outerHeight + parseInt(computed.lineHeight); + if (height > targetHeight) { + style.lineHeight = height - outerHeight + "px"; + } else if (height === targetHeight) { + style.lineHeight = computed.lineHeight; + } else { + style.lineHeight = 0; + } + } else { + style.lineHeight = computed.height; + } + } else { + style[prop] = computed[prop]; + } + }); + + if (isFirefox) { + // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275 + if (element.scrollHeight > parseInt(computed.height)) style.overflowY = "scroll"; + } else { + style.overflow = "hidden"; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll' + } + + div.textContent = element.value.substring(0, position); + // The second special handling for input type="text" vs textarea: + // spaces need to be replaced with non-breaking spaces - http://stackoverflow.com/a/13402035/1269037 + if (isInput) div.textContent = div.textContent.replace(/\s/g, "\u00a0"); + + var span = document.createElement("span"); + // Wrapping must be replicated *exactly*, including when a long word gets + // onto the next line, with whitespace at the end of the line before (#7). + // The *only* reliable way to do that is to copy the *entire* rest of the + // textarea's content into the created at the caret position. + // For inputs, just '.' would be enough, but no need to bother. + span.textContent = element.value.substring(position) || "."; // || because a completely empty faux span doesn't render at all + div.appendChild(span); + + var coordinates = { + top: span.offsetTop + parseInt(computed["borderTopWidth"]), + left: span.offsetLeft + parseInt(computed["borderLeftWidth"]), + height: parseInt(computed["lineHeight"]), + }; + + if (debug) { + span.style.backgroundColor = "#aaa"; + } else { + document.body.removeChild(div); + } + + return coordinates; + }; +})(); + +/* + Key functions from: + https://github.com/yuku/textcomplete + © Yuku Takahashi - This software is licensed under the MIT license. + + The MIT License (MIT) + + Copyright (c) 2015 Jonathan Ong me@jongleberry.com + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +const CHAR_CODE_ZERO = "0".charCodeAt(0); +const CHAR_CODE_NINE = "9".charCodeAt(0); + +class TextAreaCaretHelper { + constructor(el, getScale) { + this.el = el; + this.getScale = getScale; + } + + #calculateElementOffset() { + const rect = this.el.getBoundingClientRect(); + const owner = this.el.ownerDocument; + if (owner == null) { + throw new Error("Given element does not belong to document"); + } + const { defaultView, documentElement } = owner; + if (defaultView == null) { + throw new Error("Given element does not belong to window"); + } + const offset = { + top: rect.top + defaultView.pageYOffset, + left: rect.left + defaultView.pageXOffset, + }; + if (documentElement) { + offset.top -= documentElement.clientTop; + offset.left -= documentElement.clientLeft; + } + return offset; + } + + #isDigit(charCode) { + return CHAR_CODE_ZERO <= charCode && charCode <= CHAR_CODE_NINE; + } + + #getLineHeightPx() { + const computedStyle = getComputedStyle(this.el); + const lineHeight = computedStyle.lineHeight; + // If the char code starts with a digit, it is either a value in pixels, + // or unitless, as per: + // https://drafts.csswg.org/css2/visudet.html#propdef-line-height + // https://drafts.csswg.org/css2/cascade.html#computed-value + if (this.#isDigit(lineHeight.charCodeAt(0))) { + const floatLineHeight = parseFloat(lineHeight); + // In real browsers the value is *always* in pixels, even for unit-less + // line-heights. However, we still check as per the spec. + return this.#isDigit(lineHeight.charCodeAt(lineHeight.length - 1)) + ? floatLineHeight * parseFloat(computedStyle.fontSize) + : floatLineHeight; + } + // Otherwise, the value is "normal". + // If the line-height is "normal", calculate by font-size + return this.#calculateLineHeightPx(this.el.nodeName, computedStyle); + } + + /** + * Returns calculated line-height of the given node in pixels. + */ + #calculateLineHeightPx(nodeName, computedStyle) { + const body = document.body; + if (!body) return 0; + + const tempNode = document.createElement(nodeName); + tempNode.innerHTML = " "; + Object.assign(tempNode.style, { + fontSize: computedStyle.fontSize, + fontFamily: computedStyle.fontFamily, + padding: "0", + position: "absolute", + }); + body.appendChild(tempNode); + + // Make sure textarea has only 1 row + if (tempNode instanceof HTMLTextAreaElement) { + tempNode.rows = 1; + } + + // Assume the height of the element is the line-height + const height = tempNode.offsetHeight; + body.removeChild(tempNode); + + return height; + } + + getCursorOffset() { + const scale = this.getScale(); + const elOffset = this.#calculateElementOffset(); + const elScroll = this.#getElScroll(); + const cursorPosition = this.#getCursorPosition(); + const lineHeight = this.#getLineHeightPx(); + const top = elOffset.top - (elScroll.top * scale) + (cursorPosition.top + lineHeight) * scale; + const left = elOffset.left - elScroll.left + cursorPosition.left; + const clientTop = this.el.getBoundingClientRect().top; + if (this.el.dir !== "rtl") { + return { top, left, lineHeight, clientTop }; + } else { + const right = document.documentElement ? document.documentElement.clientWidth - left : 0; + return { top, right, lineHeight, clientTop }; + } + } + + #getElScroll() { + return { top: this.el.scrollTop, left: this.el.scrollLeft }; + } + + #getCursorPosition() { + return getCaretCoordinates(this.el, this.el.selectionEnd); + } + + getBeforeCursor() { + return this.el.selectionStart !== this.el.selectionEnd ? null : this.el.value.substring(0, this.el.selectionEnd); + } + + getAfterCursor() { + return this.el.value.substring(this.el.selectionEnd); + } + + insertAtCursor(value, offset, finalOffset) { + if (this.el.selectionStart != null) { + const startPos = this.el.selectionStart; + const endPos = this.el.selectionEnd; + + // Move selection to beginning of offset + this.el.selectionStart = this.el.selectionStart + offset; + + // Using execCommand to support undo, but since it's officially + // 'deprecated' we need a backup solution, but it won't support undo :( + let pasted = true; + try { + if (!document.execCommand("insertText", false, value)) { + pasted = false; + } + } catch (e) { + console.error("Error caught during execCommand:", e); + pasted = false; + } + + if (!pasted) { + console.error( + "execCommand unsuccessful; not supported. Adding text manually, no undo support."); + textarea.setRangeText(modifiedText, this.el.selectionStart, this.el.selectionEnd, 'end'); + } + + this.el.selectionEnd = this.el.selectionStart = startPos + value.length + offset + (finalOffset ?? 0); + } else { + // Using execCommand to support undo, but since it's officially + // 'deprecated' we need a backup solution, but it won't support undo :( + let pasted = true; + try { + if (!document.execCommand("insertText", false, value)) { + pasted = false; + } + } catch (e) { + console.error("Error caught during execCommand:", e); + pasted = false; + } + + if (!pasted) { + console.error( + "execCommand unsuccessful; not supported. Adding text manually, no undo support."); + this.el.value += value; + } + } + } +} + +/*********************/ + +/** + * @typedef {{ + * text: string, + * priority?: number, + * info?: Function, + * hint?: string, + * showValue?: boolean, + * caretOffset?: number + * }} AutoCompleteEntry + */ +export class TextAreaAutoComplete { + static globalSeparator = ""; + static enabled = true; + static insertOnTab = true; + static insertOnEnter = true; + static replacer = undefined; + static lorasEnabled = false; + static suggestionCount = 20; + + /** @type {Record>} */ + static groups = {}; + /** @type {Set} */ + static globalGroups = new Set(); + /** @type {Record} */ + static globalWords = {}; + /** @type {Record} */ + static globalWordsExclLoras = {}; + + /** @type {HTMLTextAreaElement} */ + el; + + /** @type {Record} */ + overrideWords; + overrideSeparator = ""; + + get words() { + return this.overrideWords ?? TextAreaAutoComplete.globalWords; + } + + get separator() { + return this.overrideSeparator ?? TextAreaAutoComplete.globalSeparator; + } + + /** + * @param {HTMLTextAreaElement} el + */ + constructor(el, words = null, separator = null) { + this.el = el; + this.helper = new TextAreaCaretHelper(el, () => app.canvas.ds.scale); + this.dropdown = $el("div.pysssss-autocomplete"); + this.overrideWords = words; + this.overrideSeparator = separator; + + this.#setup(); + } + + #setup() { + this.el.addEventListener("keydown", this.#keyDown.bind(this)); + this.el.addEventListener("keypress", this.#keyPress.bind(this)); + this.el.addEventListener("keyup", this.#keyUp.bind(this)); + this.el.addEventListener("click", this.#hide.bind(this)); + this.el.addEventListener("blur", () => setTimeout(() => this.#hide(), 150)); + } + + /** + * @param {KeyboardEvent} e + */ + #keyDown(e) { + if (!TextAreaAutoComplete.enabled) return; + + if (this.dropdown.parentElement) { + // We are visible + switch (e.key) { + case "ArrowUp": + e.preventDefault(); + if (this.selected.index) { + this.#setSelected(this.currentWords[this.selected.index - 1].wordInfo); + } else { + this.#setSelected(this.currentWords[this.currentWords.length - 1].wordInfo); + } + break; + case "ArrowDown": + e.preventDefault(); + if (this.selected.index === this.currentWords.length - 1) { + this.#setSelected(this.currentWords[0].wordInfo); + } else { + this.#setSelected(this.currentWords[this.selected.index + 1].wordInfo); + } + break; + case "Tab": + if (TextAreaAutoComplete.insertOnTab) { + this.#insertItem(); + e.preventDefault(); + } + break; + } + } + } + + /** + * @param {KeyboardEvent} e + */ + #keyPress(e) { + if (!TextAreaAutoComplete.enabled) return; + if (this.dropdown.parentElement) { + // We are visible + switch (e.key) { + case "Enter": + if (!e.ctrlKey) { + if (TextAreaAutoComplete.insertOnEnter) { + this.#insertItem(); + e.preventDefault(); + } + } + break; + } + } + + if (!e.defaultPrevented) { + this.#update(); + } + } + + #keyUp(e) { + if (!TextAreaAutoComplete.enabled) return; + if (this.dropdown.parentElement) { + // We are visible + switch (e.key) { + case "Escape": + e.preventDefault(); + this.#hide(); + break; + } + } else if (e.key.length > 1 && e.key != "Delete" && e.key != "Backspace") { + return; + } + if (!e.defaultPrevented) { + this.#update(); + } + } + + #setSelected(item) { + if (this.selected) { + this.selected.el.classList.remove("pysssss-autocomplete-item--selected"); + } + + this.selected = item; + this.selected.el.classList.add("pysssss-autocomplete-item--selected"); + } + + #insertItem() { + if (!this.selected) return; + this.selected.el.click(); + } + + #getFilteredWords(term) { + term = term.toLocaleLowerCase(); + + const priorityMatches = []; + const prefixMatches = []; + const includesMatches = []; + for (const word of Object.keys(this.words)) { + const lowerWord = word.toLocaleLowerCase(); + if (lowerWord === term) { + // Dont include exact matches + continue; + } + + const pos = lowerWord.indexOf(term); + if (pos === -1) { + // No match + continue; + } + + const wordInfo = this.words[word]; + if (wordInfo.priority) { + priorityMatches.push({ pos, wordInfo }); + } else if (pos) { + includesMatches.push({ pos, wordInfo }); + } else { + prefixMatches.push({ pos, wordInfo }); + } + } + + priorityMatches.sort( + (a, b) => + b.wordInfo.priority - a.wordInfo.priority || + a.wordInfo.text.length - b.wordInfo.text.length || + a.wordInfo.text.localeCompare(b.wordInfo.text) + ); + + const top = priorityMatches.length * 0.2; + return priorityMatches.slice(0, top).concat(prefixMatches, priorityMatches.slice(top), includesMatches).slice(0, TextAreaAutoComplete.suggestionCount); + } + + #update() { + let before = this.helper.getBeforeCursor(); + if (before?.length) { + const m = before.match(/([^,;"|{}()\n]+)$/); + if (m) { + before = m[0] + .replace(/^\s+/, "") + .replace(/\s/g, "_") || null; + } else { + before = null; + } + } + + if (!before) { + this.#hide(); + return; + } + + this.currentWords = this.#getFilteredWords(before); + if (!this.currentWords.length) { + this.#hide(); + return; + } + + this.dropdown.style.display = ""; + + let hasSelected = false; + const items = this.currentWords.map(({ wordInfo, pos }, i) => { + const parts = [ + $el("span", { + textContent: wordInfo.text.substr(0, pos), + }), + $el("span.pysssss-autocomplete-highlight", { + textContent: wordInfo.text.substr(pos, before.length), + }), + $el("span", { + textContent: wordInfo.text.substr(pos + before.length), + }), + ]; + + if (wordInfo.hint) { + parts.push( + $el("span.pysssss-autocomplete-pill", { + textContent: wordInfo.hint, + }) + ); + } + + if (wordInfo.priority) { + parts.push( + $el("span.pysssss-autocomplete-pill", { + textContent: wordInfo.priority, + }) + ); + } + + if (wordInfo.value && wordInfo.text !== wordInfo.value && wordInfo.showValue !== false) { + parts.push( + $el("span.pysssss-autocomplete-pill", { + textContent: wordInfo.value, + }) + ); + } + + if (wordInfo.info) { + parts.push( + $el("a.pysssss-autocomplete-item-info", { + textContent: "ℹ️", + title: "View info...", + onclick: (e) => { + e.stopPropagation(); + wordInfo.info(); + e.preventDefault(); + }, + }) + ); + } + const item = $el( + "div.pysssss-autocomplete-item", + { + onclick: () => { + this.el.focus(); + let value = wordInfo.value ?? wordInfo.text; + const use_replacer = wordInfo.use_replacer ?? true; + if (TextAreaAutoComplete.replacer && use_replacer) { + value = TextAreaAutoComplete.replacer(value); + } + value = this.#escapeParentheses(value); + + const afterCursor = this.helper.getAfterCursor(); + const shouldAddSeparator = !afterCursor.trim().startsWith(this.separator.trim()); + this.helper.insertAtCursor( + value + (shouldAddSeparator ? this.separator : ''), + -before.length, + wordInfo.caretOffset + ); + setTimeout(() => { + this.#update(); + }, 150); + }, + }, + parts + ); + + if (wordInfo === this.selected) { + hasSelected = true; + } + + wordInfo.index = i; + wordInfo.el = item; + + return item; + }); + + this.#setSelected(hasSelected ? this.selected : this.currentWords[0].wordInfo); + this.dropdown.replaceChildren(...items); + + if (!this.dropdown.parentElement) { + document.body.append(this.dropdown); + } + + const position = this.helper.getCursorOffset(); + this.dropdown.style.left = (position.left ?? 0) + "px"; + this.dropdown.style.top = (position.top ?? 0) + "px"; + this.dropdown.style.maxHeight = (window.innerHeight - position.top) + "px"; + } + + #escapeParentheses(text) { + return text.replace(/\(/g, '\\(').replace(/\)/g, '\\)'); + } + + #hide() { + this.selected = null; + this.dropdown.remove(); + } + + static updateWords(id, words, addGlobal = true) { + const isUpdate = id in TextAreaAutoComplete.groups; + TextAreaAutoComplete.groups[id] = words; + if (addGlobal) { + TextAreaAutoComplete.globalGroups.add(id); + } + + if (isUpdate) { + // Remerge all words + TextAreaAutoComplete.globalWords = Object.assign( + {}, + ...Object.keys(TextAreaAutoComplete.groups) + .filter((k) => TextAreaAutoComplete.globalGroups.has(k)) + .map((k) => TextAreaAutoComplete.groups[k]) + ); + } else if (addGlobal) { + // Just insert the new words + Object.assign(TextAreaAutoComplete.globalWords, words); + } + } +} diff --git a/comfyui-custom-scripts/web/js/common/binding.js b/comfyui-custom-scripts/web/js/common/binding.js new file mode 100644 index 0000000000000000000000000000000000000000..7533e7e5e93beee798123a8ed84d36a50d2a4702 --- /dev/null +++ b/comfyui-custom-scripts/web/js/common/binding.js @@ -0,0 +1,244 @@ +// @ts-check +// @ts-ignore +import { ComfyWidgets } from "../../../../scripts/widgets.js"; +// @ts-ignore +import { api } from "../../../../scripts/api.js"; +// @ts-ignore +import { app } from "../../../../scripts/app.js"; + +const PathHelper = { + get(obj, path) { + if (typeof path !== "string") { + // Hardcoded value + return path; + } + + if (path[0] === '"' && path[path.length - 1] === '"') { + // Hardcoded string + return JSON.parse(path); + } + + // Evaluate the path + path = path.split(".").filter(Boolean); + for (const p of path) { + const k = isNaN(+p) ? p : +p; + obj = obj[k]; + } + + return obj; + }, + set(obj, path, value) { + // https://stackoverflow.com/a/54733755 + if (Object(obj) !== obj) return obj; // When obj is not an object + // If not yet an array, get the keys from the string-path + if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || []; + path.slice(0, -1).reduce( + ( + a, + c, + i // Iterate all of them except the last one + ) => + Object(a[c]) === a[c] // Does the key exist and is its value an object? + ? // Yes: then follow that path + a[c] + : // No: create the key. Is the next key a potential array-index? + (a[c] = + Math.abs(path[i + 1]) >> 0 === +path[i + 1] + ? [] // Yes: assign a new array object + : {}), // No: assign a new plain object + obj + )[path[path.length - 1]] = value; // Finally assign the value to the last key + return obj; // Return the top-level object to allow chaining + }, +}; + +/*** + @typedef { { + left: string; + op: "eq" | "ne", + right: string + } } IfCondition + + @typedef { { + type: "if", + condition: Array, + true?: Array, + false?: Array + } } IfCallback + + @typedef { { + type: "fetch", + url: string, + then: Array + } } FetchCallback + + @typedef { { + type: "set", + target: string, + value: string + } } SetCallback + + @typedef { { + type: "validate-combo", + } } ValidateComboCallback + + @typedef { IfCallback | FetchCallback | SetCallback | ValidateComboCallback } BindingCallback + + @typedef { { + source: string, + callback: Array + } } Binding +***/ + +/** + * @param {IfCondition} condition + */ +function evaluateCondition(condition, state) { + const left = PathHelper.get(state, condition.left); + const right = PathHelper.get(state, condition.right); + + let r; + if (condition.op === "eq") { + r = left === right; + } else { + r = left !== right; + } + + return r; +} + +/** + * @type { Record) => Promise> } + */ +const callbacks = { + /** + * @param {IfCallback} cb + */ + async if(cb, state) { + // For now only support ANDs + let success = true; + for (const condition of cb.condition) { + const r = evaluateCondition(condition, state); + if (!r) { + success = false; + break; + } + } + + for (const m of cb[success + ""] ?? []) { + await invokeCallback(m, state); + } + }, + /** + * @param {FetchCallback} cb + */ + async fetch(cb, state) { + const url = cb.url.replace(/\{([^\}]+)\}/g, (m, v) => { + return PathHelper.get(state, v); + }); + const res = await (await api.fetchApi(url)).json(); + state["$result"] = res; + for (const m of cb.then) { + await invokeCallback(m, state); + } + }, + /** + * @param {SetCallback} cb + */ + async set(cb, state) { + const value = PathHelper.get(state, cb.value); + PathHelper.set(state, cb.target, value); + }, + async "validate-combo"(cb, state) { + const w = state["$this"]; + const valid = w.options.values.includes(w.value); + if (!valid) { + w.value = w.options.values[0]; + } + }, +}; + +async function invokeCallback(callback, state) { + if (callback.type in callbacks) { + // @ts-ignore + await callbacks[callback.type](callback, state); + } else { + console.warn( + "%c[🐍 pysssss]", + "color: limegreen", + `[binding ${state.$node.comfyClass}.${state.$this.name}]`, + "unsupported binding callback type:", + callback.type + ); + } +} + +app.registerExtension({ + name: "pysssss.Binding", + beforeRegisterNodeDef(node, nodeData) { + const hasBinding = (v) => { + if (!v) return false; + return Object.values(v).find((c) => c[1]?.["pysssss.binding"]); + }; + const inputs = { ...nodeData.input?.required, ...nodeData.input?.optional }; + if (hasBinding(inputs)) { + const onAdded = node.prototype.onAdded; + node.prototype.onAdded = function () { + const r = onAdded?.apply(this, arguments); + + for (const widget of this.widgets || []) { + const bindings = inputs[widget.name][1]?.["pysssss.binding"]; + if (!bindings) continue; + + for (const binding of bindings) { + /** + * @type {import("../../../../../web/types/litegraph.d.ts").IWidget} + */ + const source = this.widgets.find((w) => w.name === binding.source); + if (!source) { + console.warn( + "%c[🐍 pysssss]", + "color: limegreen", + `[binding ${node.comfyClass}.${widget.name}]`, + "unable to find source binding widget:", + binding.source, + binding + ); + continue; + } + + let lastValue; + async function valueChanged() { + const state = { + $this: widget, + $source: source, + $node: node, + }; + + for (const callback of binding.callback) { + await invokeCallback(callback, state); + } + + app.graph.setDirtyCanvas(true, false); + } + + const cb = source.callback; + source.callback = function () { + const v = cb?.apply(this, arguments) ?? source.value; + if (v !== lastValue) { + lastValue = v; + valueChanged(); + } + return v; + }; + + lastValue = source.value; + valueChanged(); + } + } + + return r; + }; + } + }, +}); diff --git a/comfyui-custom-scripts/web/js/common/lightbox.css b/comfyui-custom-scripts/web/js/common/lightbox.css new file mode 100644 index 0000000000000000000000000000000000000000..c4307fd0a201f6ae396e0cb9e2b5e00dba8fc285 --- /dev/null +++ b/comfyui-custom-scripts/web/js/common/lightbox.css @@ -0,0 +1,102 @@ +.pysssss-lightbox { + width: 100vw; + height: 100vh; + position: fixed; + top: 0; + left: 0; + z-index: 1001; + background: rgba(0, 0, 0, 0.6); + display: flex; + align-items: center; + transition: opacity 0.2s; +} + +.pysssss-lightbox-prev, +.pysssss-lightbox-next { + height: 60px; + display: flex; + align-items: center; +} + +.pysssss-lightbox-prev:after, +.pysssss-lightbox-next:after { + border-style: solid; + border-width: 0.25em 0.25em 0 0; + display: inline-block; + height: 0.45em; + left: 0.15em; + position: relative; + top: 0.15em; + transform: rotate(-135deg) scale(0.75); + vertical-align: top; + width: 0.45em; + padding: 10px; + font-size: 20px; + margin: 0 10px 0 20px; + transition: color 0.2s; + flex-shrink: 0; + content: ""; +} + +.pysssss-lightbox-next:after { + transform: rotate(45deg) scale(0.75); + margin: 0 20px 0 0px; +} + +.pysssss-lightbox-main { + display: grid; + flex: auto; + place-content: center; + text-align: center; +} + +.pysssss-lightbox-link { + display: flex; + justify-content: center; + align-items: center; + position: relative; +} + +.pysssss-lightbox .lds-ring { + position: absolute; + left: 50%; + top: 50%; + transform: translate(-50%, -50%); +} + +.pysssss-lightbox-img { + max-height: 90vh; + max-width: calc(100vw - 130px); + height: auto; + object-fit: contain; + border: 3px solid white; + border-radius: 4px; + transition: opacity 0.2s; + user-select: none; +} + +.pysssss-lightbox-img:hover { + border-color: dodgerblue; +} + +.pysssss-lightbox-close { + font-size: 80px; + line-height: 1ch; + height: 1ch; + width: 1ch; + position: absolute; + right: 10px; + top: 10px; + padding: 5px; +} + +.pysssss-lightbox-close:after { + content: "\00d7"; +} + +.pysssss-lightbox-close:hover, +.pysssss-lightbox-prev:hover, +.pysssss-lightbox-next:hover { + color: dodgerblue; + cursor: pointer; +} diff --git a/comfyui-custom-scripts/web/js/common/lightbox.js b/comfyui-custom-scripts/web/js/common/lightbox.js new file mode 100644 index 0000000000000000000000000000000000000000..5c9079067f6fd26ab8e392e55add76d52a885858 --- /dev/null +++ b/comfyui-custom-scripts/web/js/common/lightbox.js @@ -0,0 +1,149 @@ +import { $el } from "../../../../scripts/ui.js"; +import { addStylesheet, getUrl, loadImage } from "./utils.js"; +import { createSpinner } from "./spinner.js"; + +addStylesheet(getUrl("lightbox.css", import.meta.url)); + +const $$el = (tag, name, ...args) => { + if (name) name = "-" + name; + return $el(tag + ".pysssss-lightbox" + name, ...args); +}; + +const ani = async (a, t, b) => { + a(); + await new Promise((r) => setTimeout(r, t)); + b(); +}; + +export class Lightbox { + constructor() { + this.el = $$el("div", "", { + parent: document.body, + onclick: (e) => { + e.stopImmediatePropagation(); + this.close(); + }, + style: { + display: "none", + opacity: 0, + }, + }); + this.closeBtn = $$el("div", "close", { + parent: this.el, + }); + this.prev = $$el("div", "prev", { + parent: this.el, + onclick: (e) => { + this.update(-1); + e.stopImmediatePropagation(); + }, + }); + this.main = $$el("div", "main", { + parent: this.el, + }); + this.next = $$el("div", "next", { + parent: this.el, + onclick: (e) => { + this.update(1); + e.stopImmediatePropagation(); + }, + }); + this.link = $$el("a", "link", { + parent: this.main, + target: "_blank", + }); + this.spinner = createSpinner(); + this.link.appendChild(this.spinner); + this.img = $$el("img", "img", { + style: { + opacity: 0, + }, + parent: this.link, + onclick: (e) => { + e.stopImmediatePropagation(); + }, + onwheel: (e) => { + if (!(e instanceof WheelEvent) || e.ctrlKey) { + return; + } + const direction = Math.sign(e.deltaY); + this.update(direction); + }, + }); + } + + close() { + ani( + () => (this.el.style.opacity = 0), + 200, + () => (this.el.style.display = "none") + ); + } + + async show(images, index) { + this.images = images; + this.index = index || 0; + await this.update(0); + } + + async update(shift) { + if (shift < 0 && this.index <= 0) { + return; + } + if (shift > 0 && this.index >= this.images.length - 1) { + return; + } + this.index += shift; + + this.prev.style.visibility = this.index ? "unset" : "hidden"; + this.next.style.visibility = this.index === this.images.length - 1 ? "hidden" : "unset"; + + const img = this.images[this.index]; + this.el.style.display = "flex"; + this.el.clientWidth; // Force a reflow + this.el.style.opacity = 1; + this.img.style.opacity = 0; + this.spinner.style.display = "inline-block"; + try { + await loadImage(img); + } catch (err) { + console.error('failed to load image', img, err); + } + this.spinner.style.display = "none"; + this.link.href = img; + this.img.src = img; + this.img.style.opacity = 1; + } + + async updateWithNewImage(img, feedDirection) { + // No-op if lightbox is not open + if (this.el.style.display === "none" || this.el.style.opacity === "0") return; + + // Ensure currently shown image does not change + const [method, shift] = feedDirection === "newest first" ? ["unshift", 1] : ["push", 0]; + this.images[method](img); + await this.update(shift); + } +} + +export const lightbox = new Lightbox(); + +addEventListener('keydown', (event) => { + if (lightbox.el.style.display === 'none') { + return; + } + const { key } = event; + switch (key) { + case 'ArrowLeft': + case 'a': + lightbox.update(-1); + break; + case 'ArrowRight': + case 'd': + lightbox.update(1); + break; + case 'Escape': + lightbox.close(); + break; + } +}); \ No newline at end of file diff --git a/comfyui-custom-scripts/web/js/common/modelInfoDialog.css b/comfyui-custom-scripts/web/js/common/modelInfoDialog.css new file mode 100644 index 0000000000000000000000000000000000000000..a5b9f627fc348ca17db78e5b28bc43a86e46560a --- /dev/null +++ b/comfyui-custom-scripts/web/js/common/modelInfoDialog.css @@ -0,0 +1,119 @@ +.pysssss-model-info { + color: white; + font-family: sans-serif; + max-width: 90vw; +} +.pysssss-model-content { + display: flex; + flex-direction: column; + overflow: hidden; +} +.pysssss-model-info h2 { + text-align: center; + margin: 0 0 10px 0; +} +.pysssss-model-info p { + margin: 5px 0; +} +.pysssss-model-info a { + color: dodgerblue; +} +.pysssss-model-info a:hover { + text-decoration: underline; +} +.pysssss-model-tags-list { + display: flex; + flex-wrap: wrap; + list-style: none; + gap: 10px; + max-height: 200px; + overflow: auto; + margin: 10px 0; + padding: 0; +} +.pysssss-model-tag { + background-color: rgb(128, 213, 247); + color: #000; + display: flex; + align-items: center; + gap: 5px; + border-radius: 5px; + padding: 2px 5px; + cursor: pointer; +} +.pysssss-model-tag--selected span::before { + content: "✅"; + position: absolute; + background-color: dodgerblue; + left: 0; + top: 0; + right: 0; + bottom: 0; + text-align: center; +} +.pysssss-model-tag:hover { + outline: 2px solid dodgerblue; +} +.pysssss-model-tag p { + margin: 0; +} +.pysssss-model-tag span { + text-align: center; + border-radius: 5px; + background-color: dodgerblue; + color: #fff; + padding: 2px; + position: relative; + min-width: 20px; + overflow: hidden; +} + +.pysssss-model-metadata .comfy-modal-content { + max-width: 100%; +} +.pysssss-model-metadata label { + margin-right: 1ch; + color: #ccc; +} + +.pysssss-model-metadata span { + color: dodgerblue; +} + +.pysssss-preview { + max-width: 50%; + margin-left: 10px; + position: relative; +} +.pysssss-preview img { + max-height: 300px; +} +.pysssss-preview button { + position: absolute; + font-size: 12px; + bottom: 10px; + right: 10px; +} +.pysssss-preview button+button { + bottom: 34px; +} + +.pysssss-preview button.pysssss-preview-nav { + bottom: unset; + right: 30px; + top: 10px; + font-size: 14px; + line-height: 14px; +} + +.pysssss-preview button.pysssss-preview-nav+.pysssss-preview-nav { + right: 10px; +} +.pysssss-model-notes { + background-color: rgba(0, 0, 0, 0.25); + padding: 5px; + margin-top: 5px; +} +.pysssss-model-notes:empty { + display: none; +} diff --git a/comfyui-custom-scripts/web/js/common/modelInfoDialog.js b/comfyui-custom-scripts/web/js/common/modelInfoDialog.js new file mode 100644 index 0000000000000000000000000000000000000000..032767da17bfc12f60ac8c6f926d8366a3b436e6 --- /dev/null +++ b/comfyui-custom-scripts/web/js/common/modelInfoDialog.js @@ -0,0 +1,358 @@ +import { $el, ComfyDialog } from "../../../../scripts/ui.js"; +import { api } from "../../../../scripts/api.js"; +import { addStylesheet } from "./utils.js"; + +addStylesheet(import.meta.url); + +class MetadataDialog extends ComfyDialog { + constructor() { + super(); + + this.element.classList.add("pysssss-model-metadata"); + } + show(metadata) { + super.show( + $el( + "div", + Object.keys(metadata).map((k) => + $el("div", [ + $el("label", { textContent: k }), + $el("span", { textContent: typeof metadata[k] === "object" ? JSON.stringify(metadata[k]) : metadata[k] }), + ]) + ) + ) + ); + } +} + +export class ModelInfoDialog extends ComfyDialog { + constructor(name, node) { + super(); + this.name = name; + this.node = node; + this.element.classList.add("pysssss-model-info"); + } + + get customNotes() { + return this.metadata["pysssss.notes"]; + } + + set customNotes(v) { + this.metadata["pysssss.notes"] = v; + } + + get hash() { + return this.metadata["pysssss.sha256"]; + } + + async show(type, value) { + this.type = type; + + const req = api.fetchApi("/pysssss/metadata/" + encodeURIComponent(`${type}/${value}`)); + this.info = $el("div", { style: { flex: "auto" } }); + this.img = $el("img", { style: { display: "none" } }); + this.imgWrapper = $el("div.pysssss-preview", [this.img]); + this.main = $el("main", { style: { display: "flex" } }, [this.info, this.imgWrapper]); + this.content = $el("div.pysssss-model-content", [$el("h2", { textContent: this.name }), this.main]); + + const loading = $el("div", { textContent: "ℹ️ Loading...", parent: this.content }); + + super.show(this.content); + + this.metadata = await (await req).json(); + this.viewMetadata.style.cursor = this.viewMetadata.style.opacity = ""; + this.viewMetadata.removeAttribute("disabled"); + + loading.remove(); + this.addInfo(); + } + + createButtons() { + const btns = super.createButtons(); + this.viewMetadata = $el("button", { + type: "button", + textContent: "View raw metadata", + disabled: "disabled", + style: { + opacity: 0.5, + cursor: "not-allowed", + }, + onclick: (e) => { + if (this.metadata) { + new MetadataDialog().show(this.metadata); + } + }, + }); + + btns.unshift(this.viewMetadata); + return btns; + } + + getNoteInfo() { + function parseNote() { + if (!this.customNotes) return []; + + let notes = []; + // Extract links from notes + const r = new RegExp("(\\bhttps?:\\/\\/[^\\s]+)", "g"); + let end = 0; + let m; + do { + m = r.exec(this.customNotes); + let pos; + let fin = 0; + if (m) { + pos = m.index; + fin = m.index + m[0].length; + } else { + pos = this.customNotes.length; + } + + let pre = this.customNotes.substring(end, pos); + if (pre) { + pre = pre.replaceAll("\n", "
"); + notes.push( + $el("span", { + innerHTML: pre, + }) + ); + } + if (m) { + notes.push( + $el("a", { + href: m[0], + textContent: m[0], + target: "_blank", + }) + ); + } + + end = fin; + } while (m); + return notes; + } + + let textarea; + let notesContainer; + const editText = "✏️ Edit"; + const edit = $el("a", { + textContent: editText, + href: "#", + style: { + float: "right", + color: "greenyellow", + textDecoration: "none", + }, + onclick: async (e) => { + e.preventDefault(); + + if (textarea) { + this.customNotes = textarea.value; + + const resp = await api.fetchApi("/pysssss/metadata/notes/" + encodeURIComponent(`${this.type}/${this.name}`), { + method: "POST", + body: this.customNotes, + }); + + if (resp.status !== 200) { + console.error(resp); + alert(`Error saving notes (${req.status}) ${req.statusText}`); + return; + } + + e.target.textContent = editText; + textarea.remove(); + textarea = null; + + notesContainer.replaceChildren(...parseNote.call(this)); + this.node?.["pysssss.updateExamples"]?.(); + } else { + e.target.textContent = "💾 Save"; + textarea = $el("textarea", { + style: { + width: "100%", + minWidth: "200px", + minHeight: "50px", + }, + textContent: this.customNotes, + }); + e.target.after(textarea); + notesContainer.replaceChildren(); + textarea.style.height = Math.min(textarea.scrollHeight, 300) + "px"; + } + }, + }); + + notesContainer = $el("div.pysssss-model-notes", parseNote.call(this)); + return $el( + "div", + { + style: { display: "contents" }, + }, + [edit, notesContainer] + ); + } + + addInfo() { + const usageHint = this.metadata["modelspec.usage_hint"]; + if (usageHint) { + this.addInfoEntry("Usage Hint", usageHint); + } + this.addInfoEntry("Notes", this.getNoteInfo()); + } + + addInfoEntry(name, value) { + return $el( + "p", + { + parent: this.info, + }, + [ + typeof name === "string" ? $el("label", { textContent: name + ": " }) : name, + typeof value === "string" ? $el("span", { textContent: value }) : value, + ] + ); + } + + async getCivitaiDetails() { + const req = await fetch("https://civitai.com/api/v1/model-versions/by-hash/" + this.hash); + if (req.status === 200) { + return await req.json(); + } else if (req.status === 404) { + throw new Error("Model not found"); + } else { + throw new Error(`Error loading info (${req.status}) ${req.statusText}`); + } + } + + addCivitaiInfo() { + const promise = this.getCivitaiDetails(); + const content = $el("span", { textContent: "ℹ️ Loading..." }); + + this.addInfoEntry( + $el("label", [ + $el("img", { + style: { + width: "18px", + position: "relative", + top: "3px", + margin: "0 5px 0 0", + }, + src: "https://civitai.com/favicon.ico", + }), + $el("span", { textContent: "Civitai: " }), + ]), + content + ); + + return promise + .then((info) => { + content.replaceChildren( + $el("a", { + href: "https://civitai.com/models/" + info.modelId, + textContent: "View " + info.model.name, + target: "_blank", + }) + ); + + const allPreviews = info.images?.filter((i) => i.type === "image"); + const previews = allPreviews?.filter((i) => i.nsfwLevel <= ModelInfoDialog.nsfwLevel); + if (previews?.length) { + let previewIndex = 0; + let preview; + const updatePreview = () => { + preview = previews[previewIndex]; + this.img.src = preview.url; + }; + + updatePreview(); + this.img.style.display = ""; + + this.img.title = `${previews.length} previews.`; + if (allPreviews.length !== previews.length) { + this.img.title += ` ${allPreviews.length - previews.length} images hidden due to NSFW level.`; + } + + this.imgSave = $el("button", { + textContent: "Use as preview", + parent: this.imgWrapper, + onclick: async () => { + // Convert the preview to a blob + const blob = await (await fetch(this.img.src)).blob(); + + // Store it in temp + const name = "temp_preview." + new URL(this.img.src).pathname.split(".")[1]; + const body = new FormData(); + body.append("image", new File([blob], name)); + body.append("overwrite", "true"); + body.append("type", "temp"); + + const resp = await api.fetchApi("/upload/image", { + method: "POST", + body, + }); + + if (resp.status !== 200) { + console.error(resp); + alert(`Error saving preview (${req.status}) ${req.statusText}`); + return; + } + + // Use as preview + await api.fetchApi("/pysssss/save/" + encodeURIComponent(`${this.type}/${this.name}`), { + method: "POST", + body: JSON.stringify({ + filename: name, + type: "temp", + }), + headers: { + "content-type": "application/json", + }, + }); + app.refreshComboInNodes(); + }, + }); + + $el("button", { + textContent: "Show metadata", + parent: this.imgWrapper, + onclick: async () => { + if (preview.meta && Object.keys(preview.meta).length) { + new MetadataDialog().show(preview.meta); + } else { + alert("No image metadata found"); + } + }, + }); + + const addNavButton = (icon, direction) => { + $el("button.pysssss-preview-nav", { + textContent: icon, + parent: this.imgWrapper, + onclick: async () => { + previewIndex += direction; + if (previewIndex < 0) { + previewIndex = previews.length - 1; + } else if (previewIndex >= previews.length) { + previewIndex = 0; + } + updatePreview(); + }, + }); + }; + + if (previews.length > 1) { + addNavButton("‹", -1); + addNavButton("›", 1); + } + } else if (info.images?.length) { + $el("span", { style: { opacity: 0.6 }, textContent: "⚠️ All images hidden due to NSFW level setting.", parent: this.imgWrapper }); + } + + return info; + }) + .catch((err) => { + content.textContent = "⚠️ " + err.message; + }); + } +} diff --git a/comfyui-custom-scripts/web/js/common/spinner.css b/comfyui-custom-scripts/web/js/common/spinner.css new file mode 100644 index 0000000000000000000000000000000000000000..cfb7a0d961de791e721f5351476a0d014285736e --- /dev/null +++ b/comfyui-custom-scripts/web/js/common/spinner.css @@ -0,0 +1,35 @@ +.pysssss-lds-ring { + display: inline-block; + position: absolute; + width: 80px; + height: 80px; +} +.pysssss-lds-ring div { + box-sizing: border-box; + display: block; + position: absolute; + width: 64px; + height: 64px; + margin: 8px; + border: 5px solid #fff; + border-radius: 50%; + animation: lds-ring 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite; + border-color: #fff transparent transparent transparent; +} +.pysssss-lds-ring div:nth-child(1) { + animation-delay: -0.45s; +} +.pysssss-lds-ring div:nth-child(2) { + animation-delay: -0.3s; +} +.pysssss-lds-ring div:nth-child(3) { + animation-delay: -0.15s; +} +@keyframes lds-ring { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(360deg); + } +} diff --git a/comfyui-custom-scripts/web/js/common/spinner.js b/comfyui-custom-scripts/web/js/common/spinner.js new file mode 100644 index 0000000000000000000000000000000000000000..407599017aab85cddf6edab18afe91c3013c3cf0 --- /dev/null +++ b/comfyui-custom-scripts/web/js/common/spinner.js @@ -0,0 +1,9 @@ +import { addStylesheet } from "./utils.js"; + +addStylesheet(import.meta.url); + +export function createSpinner() { + const div = document.createElement("div"); + div.innerHTML = `
`; + return div.firstElementChild; +} diff --git a/comfyui-custom-scripts/web/js/common/utils.js b/comfyui-custom-scripts/web/js/common/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..cd7539d449a2ac85672fb36da4be725f352b86f8 --- /dev/null +++ b/comfyui-custom-scripts/web/js/common/utils.js @@ -0,0 +1,30 @@ +import { $el } from "../../../../scripts/ui.js"; + +export function addStylesheet(url) { + if (url.endsWith(".js")) { + url = url.substr(0, url.length - 2) + "css"; + } + $el("link", { + parent: document.head, + rel: "stylesheet", + type: "text/css", + href: url.startsWith("http") ? url : getUrl(url), + }); +} + +export function getUrl(path, baseUrl) { + if (baseUrl) { + return new URL(path, baseUrl).toString(); + } else { + return new URL("../" + path, import.meta.url).toString(); + } +} + +export async function loadImage(url) { + return new Promise((res, rej) => { + const img = new Image(); + img.onload = res; + img.onerror = rej; + img.src = url; + }); +} diff --git a/comfyui-custom-scripts/web/js/contextMenuHook.js b/comfyui-custom-scripts/web/js/contextMenuHook.js new file mode 100644 index 0000000000000000000000000000000000000000..0fd35b41a4a4f6b7110c417d76235e07b22e7ce4 --- /dev/null +++ b/comfyui-custom-scripts/web/js/contextMenuHook.js @@ -0,0 +1,90 @@ +import { app } from "../../../scripts/app.js"; +app.registerExtension({ + name: "pysssss.ContextMenuHook", + init() { + const getOrSet = (target, name, create) => { + if (name in target) return target[name]; + return (target[name] = create()); + }; + const symbol = getOrSet(window, "__pysssss__", () => Symbol("__pysssss__")); + const store = getOrSet(window, symbol, () => ({})); + const contextMenuHook = getOrSet(store, "contextMenuHook", () => ({})); + for (const e of ["ctor", "preAddItem", "addItem"]) { + if (!contextMenuHook[e]) { + contextMenuHook[e] = []; + } + } + + // Big ol' hack to get allow customizing the context menu + // Replace the addItem function with our own that wraps the context of "this" with a proxy + // That proxy then replaces the constructor with another proxy + // That proxy then calls the custom ContextMenu that supports filters + const ctorProxy = new Proxy(LiteGraph.ContextMenu, { + construct(target, args) { + return new LiteGraph.ContextMenu(...args); + }, + }); + + function triggerCallbacks(name, getArgs, handler) { + const callbacks = contextMenuHook[name]; + if (callbacks && callbacks instanceof Array) { + for (const cb of callbacks) { + const r = cb(...getArgs()); + handler?.call(this, r); + } + } else { + console.warn("[pysssss 🐍]", `invalid ${name} callbacks`, callbacks, name in contextMenuHook); + } + } + + const addItem = LiteGraph.ContextMenu.prototype.addItem; + LiteGraph.ContextMenu.prototype.addItem = function () { + const proxy = new Proxy(this, { + get(target, prop) { + if (prop === "constructor") { + return ctorProxy; + } + return target[prop]; + }, + }); + proxy.__target__ = this; + + let el; + let args = arguments; + triggerCallbacks( + "preAddItem", + () => [el, this, args], + (r) => { + if (r !== undefined) el = r; + } + ); + + if (el === undefined) { + el = addItem.apply(proxy, arguments); + } + + triggerCallbacks( + "addItem", + () => [el, this, args], + (r) => { + if (r !== undefined) el = r; + } + ); + return el; + }; + + // We also need to patch the ContextMenu constructor to unwrap the parent else it fails a LiteGraph type check + const ctxMenu = LiteGraph.ContextMenu; + LiteGraph.ContextMenu = function (values, options) { + if (options?.parentMenu) { + if (options.parentMenu.__target__) { + options.parentMenu = options.parentMenu.__target__; + } + } + + triggerCallbacks("ctor", () => [values, options]); + return ctxMenu.call(this, values, options); + }; + LiteGraph.ContextMenu.prototype = ctxMenu.prototype; + }, +}); diff --git a/comfyui-custom-scripts/web/js/customColors.js b/comfyui-custom-scripts/web/js/customColors.js new file mode 100644 index 0000000000000000000000000000000000000000..2b0fefca7aa86b48d4e81126a6549e4b5fe16505 --- /dev/null +++ b/comfyui-custom-scripts/web/js/customColors.js @@ -0,0 +1,98 @@ +import { app } from "../../../scripts/app.js"; +import { $el } from "../../../scripts/ui.js"; + +const colorShade = (col, amt) => { + col = col.replace(/^#/, ""); + if (col.length === 3) col = col[0] + col[0] + col[1] + col[1] + col[2] + col[2]; + + let [r, g, b] = col.match(/.{2}/g); + [r, g, b] = [parseInt(r, 16) + amt, parseInt(g, 16) + amt, parseInt(b, 16) + amt]; + + r = Math.max(Math.min(255, r), 0).toString(16); + g = Math.max(Math.min(255, g), 0).toString(16); + b = Math.max(Math.min(255, b), 0).toString(16); + + const rr = (r.length < 2 ? "0" : "") + r; + const gg = (g.length < 2 ? "0" : "") + g; + const bb = (b.length < 2 ? "0" : "") + b; + + return `#${rr}${gg}${bb}`; +}; + +app.registerExtension({ + name: "pysssss.CustomColors", + setup() { + let picker; + let activeNode; + const onMenuNodeColors = LGraphCanvas.onMenuNodeColors; + LGraphCanvas.onMenuNodeColors = function (value, options, e, menu, node) { + const r = onMenuNodeColors.apply(this, arguments); + requestAnimationFrame(() => { + const menus = document.querySelectorAll(".litecontextmenu"); + for (let i = menus.length - 1; i >= 0; i--) { + if (menus[i].firstElementChild.textContent.includes("No color") || menus[i].firstElementChild.value?.content?.includes("No color")) { + $el( + "div.litemenu-entry.submenu", + { + parent: menus[i], + $: (el) => { + el.onclick = () => { + LiteGraph.closeAllContextMenus(); + if (!picker) { + picker = $el("input", { + type: "color", + parent: document.body, + style: { + display: "none", + }, + }); + picker.onchange = () => { + if (activeNode) { + const fApplyColor = function(node){ + if (picker.value) { + if (node.constructor === LiteGraph.LGraphGroup) { + node.color = picker.value; + } else { + node.color = colorShade(picker.value, 20); + node.bgcolor = picker.value; + } + } + } + const graphcanvas = LGraphCanvas.active_canvas; + if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1){ + fApplyColor(activeNode); + } else { + for (let i in graphcanvas.selected_nodes) { + fApplyColor(graphcanvas.selected_nodes[i]); + } + } + + activeNode.setDirtyCanvas(true, true); + } + }; + } + activeNode = null; + picker.value = node.bgcolor; + activeNode = node; + picker.click(); + }; + }, + }, + [ + $el("span", { + style: { + paddingLeft: "4px", + display: "block", + }, + textContent: "🎨 Custom", + }), + ] + ); + break; + } + } + }); + return r; + }; + }, +}); diff --git a/comfyui-custom-scripts/web/js/faviconStatus.js b/comfyui-custom-scripts/web/js/faviconStatus.js new file mode 100644 index 0000000000000000000000000000000000000000..3dcd196bcbc83082144faef0d247ef5eac3d668c --- /dev/null +++ b/comfyui-custom-scripts/web/js/faviconStatus.js @@ -0,0 +1,58 @@ +import { api } from "../../../scripts/api.js"; +import { app } from "../../../scripts/app.js"; + +// Simple script that adds the current queue size to the window title +// Adds a favicon that changes color while active + +app.registerExtension({ + name: "pysssss.FaviconStatus", + async setup() { + let link = document.querySelector("link[rel~='icon']"); + if (!link) { + link = document.createElement("link"); + link.rel = "icon"; + document.head.appendChild(link); + } + + const getUrl = (active, user) => new URL(`assets/favicon${active ? "-active" : ""}${user ? ".user" : ""}.ico`, import.meta.url); + const testUrl = async (active) => { + const url = getUrl(active, true); + const r = await fetch(url, { + method: "HEAD", + }); + if (r.status === 200) { + return url; + } + return getUrl(active, false); + }; + const activeUrl = await testUrl(true); + const idleUrl = await testUrl(false); + + let executing = false; + const update = () => (link.href = executing ? activeUrl : idleUrl); + + for (const e of ["execution_start", "progress"]) { + api.addEventListener(e, () => { + executing = true; + update(); + }); + } + + api.addEventListener("executing", ({ detail }) => { + // null will be sent when it's finished + executing = !!detail; + update(); + }); + + api.addEventListener("status", ({ detail }) => { + let title = "ComfyUI"; + if (detail && detail.exec_info.queue_remaining) { + title = `(${detail.exec_info.queue_remaining}) ${title}`; + } + document.title = title; + update(); + executing = false; + }); + update(); + }, +}); diff --git a/comfyui-custom-scripts/web/js/graphArrange.js b/comfyui-custom-scripts/web/js/graphArrange.js new file mode 100644 index 0000000000000000000000000000000000000000..8f25e241a2b91a01ca95a376385bdbe572994752 --- /dev/null +++ b/comfyui-custom-scripts/web/js/graphArrange.js @@ -0,0 +1,91 @@ +import { app } from "../../../scripts/app.js"; + +app.registerExtension({ + name: "pysssss.GraphArrange", + setup(app) { + const orig = LGraphCanvas.prototype.getCanvasMenuOptions; + LGraphCanvas.prototype.getCanvasMenuOptions = function () { + const options = orig.apply(this, arguments); + options.push({ content: "Arrange (float left)", callback: () => graph.arrange() }); + options.push({ + content: "Arrange (float right)", + callback: () => { + (function () { + var margin = 50; + var layout; + + const nodes = this.computeExecutionOrder(false, true); + const columns = []; + + // Find node first use + for (let i = nodes.length - 1; i >= 0; i--) { + const node = nodes[i]; + let max = null; + for (const out of node.outputs || []) { + if (out.links) { + for (const link of out.links) { + const outNode = app.graph.getNodeById(app.graph.links[link].target_id); + if (!outNode) continue; + var l = outNode._level - 1; + if (max === null) max = l; + else if (l < max) max = l; + } + } + } + if (max != null) node._level = max; + } + + for (let i = 0; i < nodes.length; ++i) { + const node = nodes[i]; + const col = node._level || 1; + if (!columns[col]) { + columns[col] = []; + } + columns[col].push(node); + } + + let x = margin; + + for (let i = 0; i < columns.length; ++i) { + const column = columns[i]; + if (!column) { + continue; + } + column.sort((a, b) => { + var as = !(a.type === "SaveImage" || a.type === "PreviewImage"); + var bs = !(b.type === "SaveImage" || b.type === "PreviewImage"); + var r = as - bs; + if (r === 0) r = (a.inputs?.length || 0) - (b.inputs?.length || 0); + if (r === 0) r = (a.outputs?.length || 0) - (b.outputs?.length || 0); + return r; + }); + let max_size = 100; + let y = margin + LiteGraph.NODE_TITLE_HEIGHT; + for (let j = 0; j < column.length; ++j) { + const node = column[j]; + node.pos[0] = layout == LiteGraph.VERTICAL_LAYOUT ? y : x; + node.pos[1] = layout == LiteGraph.VERTICAL_LAYOUT ? x : y; + const max_size_index = layout == LiteGraph.VERTICAL_LAYOUT ? 1 : 0; + if (node.size[max_size_index] > max_size) { + max_size = node.size[max_size_index]; + } + const node_size_index = layout == LiteGraph.VERTICAL_LAYOUT ? 0 : 1; + y += node.size[node_size_index] + margin + LiteGraph.NODE_TITLE_HEIGHT + j; + } + + // Right align in column + for (let j = 0; j < column.length; ++j) { + const node = column[j]; + node.pos[0] += max_size - node.size[0]; + } + x += max_size + margin; + } + + this.setDirtyCanvas(true, true); + }).apply(app.graph); + }, + }); + return options; + }; + }, +}); diff --git a/comfyui-custom-scripts/web/js/imageFeed.js b/comfyui-custom-scripts/web/js/imageFeed.js new file mode 100644 index 0000000000000000000000000000000000000000..4afdc066b023a43dccaf91884c8910b1fc470961 --- /dev/null +++ b/comfyui-custom-scripts/web/js/imageFeed.js @@ -0,0 +1,604 @@ +import { api } from "../../../scripts/api.js"; +import { app } from "../../../scripts/app.js"; +import { $el } from "../../../scripts/ui.js"; +import { lightbox } from "./common/lightbox.js"; + +$el("style", { + textContent: ` + .pysssss-image-feed { + position: absolute; + background: var(--comfy-menu-bg); + color: var(--fg-color); + z-index: 99; + font-family: sans-serif; + font-size: 12px; + display: flex; + flex-direction: column; + } + div > .pysssss-image-feed { + position: static; + } + .pysssss-image-feed--top, .pysssss-image-feed--bottom { + width: 100vw; + min-height: 30px; + max-height: calc(var(--max-size, 20) * 1vh); + } + .pysssss-image-feed--top { + top: 0; + } + .pysssss-image-feed--bottom { + bottom: 0; + flex-direction: column-reverse; + padding-top: 5px; + } + .pysssss-image-feed--left, .pysssss-image-feed--right { + top: 0; + height: 100vh; + min-width: 200px; + max-width: calc(var(--max-size, 10) * 1vw); + } + .comfyui-body-left .pysssss-image-feed--left, .comfyui-body-right .pysssss-image-feed--right { + height: 100%; + } + .pysssss-image-feed--left { + left: 0; + } + .pysssss-image-feed--right { + right: 0; + } + + .pysssss-image-feed--left .pysssss-image-feed-menu, .pysssss-image-feed--right .pysssss-image-feed-menu { + flex-direction: column; + } + + .pysssss-image-feed-menu { + position: relative; + flex: 0 1 min-content; + display: flex; + gap: 5px; + padding: 5px; + justify-content: space-between; + } + .pysssss-image-feed-btn-group { + align-items: stretch; + display: flex; + gap: .5rem; + flex: 0 1 fit-content; + justify-content: flex-end; + } + .pysssss-image-feed-btn { + background-color:var(--comfy-input-bg); + border-radius:5px; + border:2px solid var(--border-color); + color: var(--fg-color); + cursor:pointer; + display:inline-block; + flex: 0 1 fit-content; + text-decoration:none; + } + .pysssss-image-feed-btn.sizing-btn:checked { + filter: invert(); + } + .pysssss-image-feed-btn.clear-btn { + padding: 5px 20px; + } + .pysssss-image-feed-btn.hide-btn { + padding: 5px; + aspect-ratio: 1 / 1; + } + .pysssss-image-feed-btn:hover { + filter: brightness(1.2); + } + .pysssss-image-feed-btn:active { + position:relative; + top:1px; + } + + .pysssss-image-feed-menu section { + border-radius: 5px; + background: rgba(0,0,0,0.6); + padding: 0 5px; + display: flex; + gap: 5px; + align-items: center; + position: relative; + } + .pysssss-image-feed-menu section span { + white-space: nowrap; + } + .pysssss-image-feed-menu section input { + flex: 1 1 100%; + background: rgba(0,0,0,0.6); + border-radius: 5px; + overflow: hidden; + z-index: 100; + } + + .sizing-menu { + position: relative; + } + + .size-controls-flyout { + position: absolute; + transform: scaleX(0%); + transition: 200ms ease-out; + transition-delay: 500ms; + z-index: 101; + width: 300px; + } + + .sizing-menu:hover .size-controls-flyout { + transform: scale(1, 1); + transition: 200ms linear; + transition-delay: 0; + } + .pysssss-image-feed--bottom .size-controls-flyout { + transform: scale(1,0); + transform-origin: bottom; + bottom: 0; + left: 0; + } + .pysssss-image-feed--top .size-controls-flyout { + transform: scale(1,0); + transform-origin: top; + top: 0; + left: 0; + } + .pysssss-image-feed--left .size-controls-flyout { + transform: scale(0, 1); + transform-origin: left; + top: 0; + left: 0; + } + .pysssss-image-feed--right .size-controls-flyout { + transform: scale(0, 1); + transform-origin: right; + top: 0; + right: 0; + } + + .pysssss-image-feed-menu > * { + min-height: 24px; + } + .pysssss-image-feed-list { + flex: 1 1 auto; + overflow-y: auto; + display: grid; + align-items: center; + justify-content: center; + gap: 4px; + grid-auto-rows: min-content; + grid-template-columns: repeat(var(--img-sz, 3), 1fr); + transition: 100ms linear; + scrollbar-gutter: stable both-edges; + padding: 5px; + background: var(--comfy-input-bg); + border-radius: 5px; + margin: 5px; + margin-top: 0px; + } + .pysssss-image-feed-list:empty { + display: none; + } + .pysssss-image-feed-list div { + height: 100%; + text-align: center; + } + .pysssss-image-feed-list::-webkit-scrollbar { + background: var(--comfy-input-bg); + border-radius: 5px; + } + .pysssss-image-feed-list::-webkit-scrollbar-thumb { + background:var(--comfy-menu-bg); + border: 5px solid transparent; + border-radius: 8px; + background-clip: content-box; + } + .pysssss-image-feed-list::-webkit-scrollbar-thumb:hover { + background: var(--border-color); + background-clip: content-box; + } + .pysssss-image-feed-list img { + object-fit: var(--img-fit, contain); + max-width: 100%; + max-height: calc(var(--max-size) * 1vh); + border-radius: 4px; + } + .pysssss-image-feed-list img:hover { + filter: brightness(1.2); + }`, + parent: document.body, +}); + +app.registerExtension({ + name: "pysssss.ImageFeed", + async setup() { + let visible = true; + const seenImages = new Map(); + const showButton = $el("button.comfy-settings-btn", { + textContent: "🖼️", + style: { + right: "16px", + cursor: "pointer", + display: "none", + }, + }); + let showMenuButton; + if (!app.menu?.element.style.display && app.menu?.settingsGroup) { + showMenuButton = new (await import("../../../scripts/ui/components/button.js")).ComfyButton({ + icon: "image-multiple", + action: () => showButton.click(), + tooltip: "Show Image Feed 🐍", + content: "Show Image Feed 🐍", + }); + showMenuButton.enabled = false; + showMenuButton.element.style.display = "none"; + app.menu.settingsGroup.append(showMenuButton); + } + + const getVal = (n, d) => { + const v = localStorage.getItem("pysssss.ImageFeed." + n); + if (v && !isNaN(+v)) { + return v; + } + return d; + }; + + const saveVal = (n, v) => { + localStorage.setItem("pysssss.ImageFeed." + n, v); + }; + + const imageFeed = $el("div.pysssss-image-feed"); + const imageList = $el("div.pysssss-image-feed-list"); + + function updateMenuParent(location) { + if (showMenuButton) { + const el = document.querySelector(".comfyui-body-" + location); + if (!el) return; + el.append(imageFeed); + } else { + if (!imageFeed.parent) { + document.body.append(imageFeed); + } + } + } + + const feedLocation = app.ui.settings.addSetting({ + id: "pysssss.ImageFeed.Location", + name: "🐍 Image Feed Location", + defaultValue: "bottom", + type: () => { + return $el("tr", [ + $el("td", [ + $el("label", { + textContent: "🐍 Image Feed Location:", + }), + ]), + $el("td", [ + $el( + "select", + { + style: { + fontSize: "14px", + }, + oninput: (e) => { + feedLocation.value = e.target.value; + imageFeed.className = `pysssss-image-feed pysssss-image-feed--${feedLocation.value}`; + updateMenuParent(feedLocation.value); + saveVal("Location", feedLocation.value); + window.dispatchEvent(new Event("resize")); + }, + }, + ["left", "top", "right", "bottom", "hidden"].map((m) => + $el("option", { + value: m, + textContent: m, + selected: feedLocation.value === m, + }) + ) + ), + ]), + ]); + }, + onChange(value) { + if (value === "hidden") { + imageFeed.remove(); + if (showMenuButton) { + requestAnimationFrame(() => { + showMenuButton.element.style.display = "none"; + }); + } + showButton.style.display = "none"; + } else { + showMenuButton.element.style.display = "unset"; + showButton.style.display = visible ? "none" : "unset"; + imageFeed.className = `pysssss-image-feed pysssss-image-feed--${value}`; + updateMenuParent(value); + } + }, + }); + + const feedDirection = app.ui.settings.addSetting({ + id: "pysssss.ImageFeed.Direction", + name: "🐍 Image Feed Direction", + defaultValue: "newest first", + type: () => { + return $el("tr", [ + $el("td", [ + $el("label", { + textContent: "🐍 Image Feed Direction:", + }), + ]), + $el("td", [ + $el( + "select", + { + style: { + fontSize: "14px", + }, + oninput: (e) => { + feedDirection.value = e.target.value; + imageList.replaceChildren(...[...imageList.childNodes].reverse()); + }, + }, + ["newest first", "oldest first"].map((m) => + $el("option", { + value: m, + textContent: m, + selected: feedDirection.value === m, + }) + ) + ), + ]), + ]); + }, + }); + + const deduplicateFeed = app.ui.settings.addSetting({ + id: "pysssss.ImageFeed.Deduplication", + name: "🐍 Image Feed Deduplication", + tooltip: `Ensures unique images in the image feed but at the cost of CPU-bound performance impact \ +(from hundreds of milliseconds to seconds per image, depending on byte size). For workflows that produce duplicate images, turning this setting on may yield overall client-side performance improvements \ +by reducing the number of images in the feed. + +Recommended: "enabled (max performance)" uness images are erroneously deduplicated.`, + defaultValue: 0, + type: "combo", + options: (value) => { + let dedupeOptions = { disabled: 0, "enabled (slow)": 1, "enabled (performance)": 0.5, "enabled (max performance)": 0.25 }; + return Object.entries(dedupeOptions).map(([k, v]) => ({ + value: v, + text: k, + selected: k === value, + })); + }, + }); + + const maxImages = app.ui.settings.addSetting({ + id: "pysssss.ImageFeed.MaxImages", + name: "🐍 Image Feed Max Images", + tooltip: `Limits the number of images in the feed to a maximum, removing the oldest images as new ones are added.`, + defaultValue: 0, + type: "number", + }); + + const saveNodeOnly = app.ui.settings.addSetting({ + id: "pysssss.ImageFeed.SaveNodeOnly", + name: "🐍 Image Feed Display 'SaveImage' Only", + tooltip: `Only show images from 'SaveImage' nodes. This prevents 'PreviewImage' node outputs from appearing in the feed.`, + defaultValue: false, + type: "boolean", + }); + + const clearButton = $el("button.pysssss-image-feed-btn.clear-btn", { + textContent: "Clear", + onclick: () => { + imageList.replaceChildren(); + window.dispatchEvent(new Event("resize")); + }, + }); + + const hideButton = $el("button.pysssss-image-feed-btn.hide-btn", { + textContent: "❌", + onclick: () => { + imageFeed.style.display = "none"; + showButton.style.display = feedLocation.value === "hidden" ? "none" : "unset"; + if (showMenuButton) { + showMenuButton.enabled = true; + showMenuButton.element.style.display = ""; + } + saveVal("Visible", 0); + visible = false; + window.dispatchEvent(new Event("resize")); + }, + }); + + let columnInput; + function updateColumnCount(v) { + columnInput.parentElement.title = `Controls the number of columns in the feed (${v} columns).\nClick label to set custom value.`; + imageFeed.style.setProperty("--img-sz", v); + saveVal("ImageSize", v); + columnInput.max = Math.max(10, v, columnInput.max); + columnInput.value = v; + window.dispatchEvent(new Event("resize")); + } + + function addImageToFeed(href) { + const method = feedDirection.value === "newest first" ? "prepend" : "append"; + + if (maxImages.value > 0 && imageList.children.length >= maxImages.value) { + imageList.children[method === "prepend" ? imageList.children.length - 1 : 0].remove(); + } + + imageList[method]( + $el("div", [ + $el( + "a", + { + target: "_blank", + href, + onclick: (e) => { + const imgs = [...imageList.querySelectorAll("img")].map((img) => img.getAttribute("src")); + lightbox.show(imgs, imgs.indexOf(href)); + e.preventDefault(); + }, + }, + [$el("img", { src: href })] + ), + ]) + ); + // If lightbox is open, update it with new image + lightbox.updateWithNewImage(href, feedDirection.value); + } + + imageFeed.append( + $el("div.pysssss-image-feed-menu", [ + $el("section.sizing-menu", {}, [ + $el("label.size-control-handle", { textContent: "↹ Resize Feed" }), + $el("div.size-controls-flyout", {}, [ + $el("section.size-control.feed-size-control", {}, [ + $el("span", { + textContent: "Feed Size...", + }), + $el("input", { + type: "range", + min: 10, + max: 80, + oninput: (e) => { + e.target.parentElement.title = `Controls the maximum size of the image feed panel (${e.target.value}vh)`; + imageFeed.style.setProperty("--max-size", e.target.value); + saveVal("FeedSize", e.target.value); + window.dispatchEvent(new Event("resize")); + }, + $: (el) => { + requestAnimationFrame(() => { + el.value = getVal("FeedSize", 25); + el.oninput({ target: el }); + }); + }, + }), + ]), + $el("section.size-control.image-size-control", {}, [ + $el("a", { + textContent: "Column count...", + style: { + cursor: "pointer", + textDecoration: "underline", + }, + onclick: () => { + const v = +prompt("Enter custom column count", 20); + if (!isNaN(v)) { + updateColumnCount(v); + } + }, + }), + $el("input", { + type: "range", + min: 1, + max: 10, + step: 1, + oninput: (e) => { + updateColumnCount(e.target.value); + }, + $: (el) => { + columnInput = el; + requestAnimationFrame(() => { + updateColumnCount(getVal("ImageSize", 4)); + }); + }, + }), + ]), + ]), + ]), + $el("div.pysssss-image-feed-btn-group", {}, [clearButton, hideButton]), + ]), + imageList + ); + showButton.onclick = () => { + imageFeed.style.display = "flex"; + showButton.style.display = "none"; + if (showMenuButton) { + showMenuButton.enabled = false; + showMenuButton.element.style.display = "none"; + } + + saveVal("Visible", 1); + visible = true; + window.dispatchEvent(new Event("resize")); + }; + document.querySelector(".comfy-settings-btn").after(showButton); + window.dispatchEvent(new Event("resize")); + + if (!+getVal("Visible", 1)) { + hideButton.onclick(); + } + + api.addEventListener("executed", ({ detail }) => { + if (visible && detail?.output?.images) { + if (detail.node?.includes?.(":")) { + // Ignore group nodes + const n = app.graph.getNodeById(detail.node.split(":")[0]); + if (n?.getInnerNodes) return; + } + + // Apply "Display Save Image Node Only" filter if setting is enabled + const nodeName = detail.node?.split(":")?.[0]; + if (nodeName) { + const node = app.graph.getNodeById(nodeName); + + if (saveNodeOnly.value && node?.type !== "SaveImage") return; + } + + for (const src of detail.output.images) { + const href = `./view?filename=${encodeURIComponent(src.filename)}&type=${src.type}& + subfolder=${encodeURIComponent(src.subfolder)}&t=${+new Date()}`; + + // deduplicateFeed.value is essentially the scaling factor used for image hashing + // but when deduplication is disabled, this value is "0" + if (deduplicateFeed.value > 0) { + // deduplicate by ignoring images with the same filename/type/subfolder + const fingerprint = JSON.stringify({ filename: src.filename, type: src.type, subfolder: src.subfolder }); + if (seenImages.has(fingerprint)) { + // NOOP: image is a duplicate + } else { + seenImages.set(fingerprint, true); + let img = $el("img", { src: href }); + img.onerror = () => { + // fall back to default behavior + addImageToFeed(href); + }; + img.onload = () => { + // redraw the image onto a canvas to strip metadata (resize if performance mode) + let imgCanvas = document.createElement("canvas"); + let imgScalar = deduplicateFeed.value; + imgCanvas.width = imgScalar * img.width; + imgCanvas.height = imgScalar * img.height; + + let imgContext = imgCanvas.getContext("2d"); + imgContext.drawImage(img, 0, 0, imgCanvas.width, imgCanvas.height); + const data = imgContext.getImageData(0, 0, imgCanvas.width, imgCanvas.height); + + // calculate fast hash of the image data + let hash = 0; + for (const b of data.data) { + hash = (hash << 5) - hash + b; + } + + // add image to feed if we've never seen the hash before + if (seenImages.has(hash)) { + // NOOP: image is a duplicate + } else { + // if we got to here, then the image is unique--so add to feed + seenImages.set(hash, true); + addImageToFeed(href); + } + }; + } + } else { + addImageToFeed(href); + } + } + } + }); + }, +}); diff --git a/comfyui-custom-scripts/web/js/kSamplerAdvDenoise.js b/comfyui-custom-scripts/web/js/kSamplerAdvDenoise.js new file mode 100644 index 0000000000000000000000000000000000000000..7b92d4f1d6596a6d9679d3ef4c7dffe9ea297327 --- /dev/null +++ b/comfyui-custom-scripts/web/js/kSamplerAdvDenoise.js @@ -0,0 +1,54 @@ +import { app } from "../../../scripts/app.js"; +app.registerExtension({ + name: "pysssss.KSamplerAdvDenoise", + async beforeRegisterNodeDef(nodeType) { + // Add menu options to conver to/from widgets + const origGetExtraMenuOptions = nodeType.prototype.getExtraMenuOptions; + nodeType.prototype.getExtraMenuOptions = function (_, options) { + const r = origGetExtraMenuOptions?.apply?.(this, arguments); + + let stepsWidget = null; + let startAtWidget = null; + let endAtWidget = null; + for (const w of this.widgets || []) { + if (w.name === "steps") { + stepsWidget = w; + } else if (w.name === "start_at_step") { + startAtWidget = w; + } else if (w.name === "end_at_step") { + endAtWidget = w; + } + } + + if (stepsWidget && startAtWidget && endAtWidget) { + options.push( + { + content: "Set Denoise", + callback: () => { + const steps = +prompt("How many steps do you want?", 15); + if (isNaN(steps)) { + return; + } + const denoise = +prompt("How much denoise? (0-1)", 0.5); + if (isNaN(denoise)) { + return; + } + + stepsWidget.value = Math.floor(steps / Math.max(0, Math.min(1, denoise))); + stepsWidget.callback?.(stepsWidget.value); + + startAtWidget.value = stepsWidget.value - steps; + startAtWidget.callback?.(startAtWidget.value); + + endAtWidget.value = stepsWidget.value; + endAtWidget.callback?.(endAtWidget.value); + }, + }, + null + ); + } + + return r; + }; + }, +}); diff --git a/comfyui-custom-scripts/web/js/linkRenderMode.js b/comfyui-custom-scripts/web/js/linkRenderMode.js new file mode 100644 index 0000000000000000000000000000000000000000..010de6ee1085e3fbb4e5b3d3a381e38e261b53c7 --- /dev/null +++ b/comfyui-custom-scripts/web/js/linkRenderMode.js @@ -0,0 +1,57 @@ +import { app } from "../../../scripts/app.js"; +import { $el } from "../../../scripts/ui.js"; + +const id = "pysssss.LinkRenderMode"; +const ext = { + name: id, + async setup(app) { + if (app.extensions.find((ext) => ext.name === "Comfy.LinkRenderMode")) { + console.log("%c[🐍 pysssss]", "color: limegreen", "Skipping LinkRenderMode as core extension found"); + return; + } + const setting = app.ui.settings.addSetting({ + id, + name: "🐍 Link Render Mode", + defaultValue: 2, + type: () => { + return $el("tr", [ + $el("td", [ + $el("label", { + for: id.replaceAll(".", "-"), + textContent: "🐍 Link Render Mode:", + }), + ]), + $el("td", [ + $el( + "select", + { + textContent: "Manage", + style: { + fontSize: "14px", + }, + oninput: (e) => { + setting.value = e.target.value; + app.canvas.links_render_mode = +e.target.value; + app.graph.setDirtyCanvas(true, true); + }, + }, + LiteGraph.LINK_RENDER_MODES.map((m, i) => + $el("option", { + value: i, + textContent: m, + selected: i == app.canvas.links_render_mode, + }) + ) + ), + ]), + ]); + }, + onChange(value) { + app.canvas.links_render_mode = +value; + app.graph.setDirtyCanvas(true); + }, + }); + }, +}; + +app.registerExtension(ext); diff --git a/comfyui-custom-scripts/web/js/mathExpression.js b/comfyui-custom-scripts/web/js/mathExpression.js new file mode 100644 index 0000000000000000000000000000000000000000..d0dde50ec2fa00a556b56baa17ec2be340035ef3 --- /dev/null +++ b/comfyui-custom-scripts/web/js/mathExpression.js @@ -0,0 +1,44 @@ +import { app } from "../../../scripts/app.js"; +import { ComfyWidgets } from "../../../scripts/widgets.js"; + +app.registerExtension({ + name: "pysssss.MathExpression", + init() { + const STRING = ComfyWidgets.STRING; + ComfyWidgets.STRING = function (node, inputName, inputData) { + const r = STRING.apply(this, arguments); + r.widget.dynamicPrompts = inputData?.[1].dynamicPrompts; + return r; + }; + }, + beforeRegisterNodeDef(nodeType) { + if (nodeType.comfyClass === "MathExpression|pysssss") { + const onDrawForeground = nodeType.prototype.onDrawForeground; + + nodeType.prototype.onNodeCreated = function() { + // These are typed as any to bypass backend validation + // update frontend to restrict types + for(const input of this.inputs) { + input.type = "INT,FLOAT,IMAGE,LATENT"; + } + } + + nodeType.prototype.onDrawForeground = function (ctx) { + const r = onDrawForeground?.apply?.(this, arguments); + + const v = app.nodeOutputs?.[this.id + ""]; + if (!this.flags.collapsed && v) { + const text = v.value[0] + ""; + ctx.save(); + ctx.font = "bold 12px sans-serif"; + ctx.fillStyle = "dodgerblue"; + const sz = ctx.measureText(text); + ctx.fillText(text, this.size[0] - sz.width - 5, LiteGraph.NODE_SLOT_HEIGHT * 3); + ctx.restore(); + } + + return r; + }; + } + }, +}); diff --git a/comfyui-custom-scripts/web/js/middleClickAddDefaultNode.js b/comfyui-custom-scripts/web/js/middleClickAddDefaultNode.js new file mode 100644 index 0000000000000000000000000000000000000000..43f944f2835f56357b7701c2ef987261ceff9a8b --- /dev/null +++ b/comfyui-custom-scripts/web/js/middleClickAddDefaultNode.js @@ -0,0 +1,49 @@ +import { app } from "../../../scripts/app.js"; + +const id = "pysssss.MiddleClickAddDefaultNode"; +const ext = { + name: id, + async setup(app) { + app.ui.settings.addSetting({ + id, + name: "🐍 Middle click slot to add", + defaultValue: "Reroute", + type: "combo", + options: (value) => + [ + ...Object.keys(LiteGraph.registered_node_types) + .filter((k) => k.includes("Reroute")) + .sort((a, b) => { + if (a === "Reroute") return -1; + if (b === "Reroute") return 1; + return a.localeCompare(b); + }), + "[None]", + ].map((m) => ({ + value: m, + text: m, + selected: !value ? m === "[None]" : m === value, + })), + onChange(value) { + const enable = value && value !== "[None]"; + if (value === true) { + value = "Reroute"; + } + LiteGraph.middle_click_slot_add_default_node = enable; + if (enable) { + for (const arr of Object.values(LiteGraph.slot_types_default_in).concat( + Object.values(LiteGraph.slot_types_default_out) + )) { + const idx = arr.indexOf(value); + if (idx !== 0) { + arr.splice(idx, 1); + } + arr.unshift(value); + } + } + }, + }); + }, +}; + +app.registerExtension(ext); diff --git a/comfyui-custom-scripts/web/js/modelInfo.js b/comfyui-custom-scripts/web/js/modelInfo.js new file mode 100644 index 0000000000000000000000000000000000000000..b5db20a113fdb8f75b820306985fbf743e5f6bcc --- /dev/null +++ b/comfyui-custom-scripts/web/js/modelInfo.js @@ -0,0 +1,412 @@ +import { app } from "../../../scripts/app.js"; +import { api } from "../../../scripts/api.js"; +import { $el } from "../../../scripts/ui.js"; +import { ModelInfoDialog } from "./common/modelInfoDialog.js"; + +const MAX_TAGS = 500; +const NsfwLevel = { + PG: 1, + PG13: 2, + R: 4, + X: 8, + XXX: 16, + Blocked: 32, +}; + +export class LoraInfoDialog extends ModelInfoDialog { + getTagFrequency() { + if (!this.metadata.ss_tag_frequency) return []; + + const datasets = JSON.parse(this.metadata.ss_tag_frequency); + const tags = {}; + for (const setName in datasets) { + const set = datasets[setName]; + for (const t in set) { + if (t in tags) { + tags[t] += set[t]; + } else { + tags[t] = set[t]; + } + } + } + + return Object.entries(tags).sort((a, b) => b[1] - a[1]); + } + + getResolutions() { + let res = []; + if (this.metadata.ss_bucket_info) { + const parsed = JSON.parse(this.metadata.ss_bucket_info); + if (parsed?.buckets) { + for (const { resolution, count } of Object.values(parsed.buckets)) { + res.push([count, `${resolution.join("x")} * ${count}`]); + } + } + } + res = res.sort((a, b) => b[0] - a[0]).map((a) => a[1]); + let r = this.metadata.ss_resolution; + if (r) { + const s = r.split(","); + const w = s[0].replace("(", ""); + const h = s[1].replace(")", ""); + res.push(`${w.trim()}x${h.trim()} (Base res)`); + } else if ((r = this.metadata["modelspec.resolution"])) { + res.push(r + " (Base res"); + } + if (!res.length) { + res.push("⚠️ Unknown"); + } + return res; + } + + getTagList(tags) { + return tags.map((t) => + $el( + "li.pysssss-model-tag", + { + dataset: { + tag: t[0], + }, + $: (el) => { + el.onclick = () => { + el.classList.toggle("pysssss-model-tag--selected"); + }; + }, + }, + [ + $el("p", { + textContent: t[0], + }), + $el("span", { + textContent: t[1], + }), + ] + ) + ); + } + + addTags() { + let tags = this.getTagFrequency(); + if (!tags?.length) { + tags = this.metadata["modelspec.tags"]?.split(",").map((t) => [t.trim(), 1]); + } + let hasMore; + if (tags?.length) { + const c = tags.length; + let list; + if (c > MAX_TAGS) { + tags = tags.slice(0, MAX_TAGS); + hasMore = $el("p", [ + $el("span", { textContent: `⚠️ Only showing first ${MAX_TAGS} tags ` }), + $el("a", { + href: "#", + textContent: `Show all ${c}`, + onclick: () => { + list.replaceChildren(...this.getTagList(this.getTagFrequency())); + hasMore.remove(); + }, + }), + ]); + } + list = $el("ol.pysssss-model-tags-list", this.getTagList(tags)); + this.tags = $el("div", [list]); + } else { + this.tags = $el("p", { textContent: "⚠️ No tag frequency metadata found" }); + } + + this.content.append(this.tags); + + if (hasMore) { + this.content.append(hasMore); + } + } + + addExample(title, value, name) { + const textArea = $el("textarea", { + textContent: value, + style: { + whiteSpace: "pre-wrap", + margin: "10px 0", + color: "#fff", + background: "#222", + padding: "5px", + borderRadius: "5px", + maxHeight: "250px", + overflow: "auto", + display: "block", + border: "none", + width: "calc(100% - 10px)", + }, + }); + $el( + "p", + { + parent: this.content, + textContent: `${title}: `, + }, + [ + textArea, + $el("button", { + onclick: async () => { + await this.saveAsExample(textArea.value, `${name}.txt`); + }, + textContent: "Save as Example", + style: { + fontSize: "14px", + }, + }), + $el("hr"), + ] + ); + } + + async addInfo() { + this.addInfoEntry("Name", this.metadata.ss_output_name || "⚠️ Unknown"); + this.addInfoEntry("Base Model", this.metadata.ss_sd_model_name || "⚠️ Unknown"); + this.addInfoEntry("Clip Skip", this.metadata.ss_clip_skip || "⚠️ Unknown"); + + this.addInfoEntry( + "Resolution", + $el( + "select", + this.getResolutions().map((r) => $el("option", { textContent: r })) + ) + ); + + super.addInfo(); + const p = this.addCivitaiInfo(); + this.addTags(); + + const info = await p; + this.addExample("Trained Words", info?.trainedWords?.join(", ") ?? "", "trainedwords"); + + const triggerPhrase = this.metadata["modelspec.trigger_phrase"]; + if (triggerPhrase) { + this.addExample("Trigger Phrase", triggerPhrase, "triggerphrase"); + } + + $el("div", { + parent: this.content, + innerHTML: info?.description ?? this.metadata["modelspec.description"] ?? "[No description provided]", + style: { + maxHeight: "250px", + overflow: "auto", + }, + }); + } + + async saveAsExample(example, name = "example.txt") { + if (!example.length) { + return; + } + try { + name = prompt("Enter example name", name); + if (!name) return; + + await api.fetchApi("/pysssss/examples/" + encodeURIComponent(`${this.type}/${this.name}`), { + method: "POST", + body: JSON.stringify({ + name, + example, + }), + headers: { + "content-type": "application/json", + }, + }); + this.node?.["pysssss.updateExamples"]?.(); + alert("Saved!"); + } catch (error) { + console.error(error); + alert("Error saving: " + error); + } + } + + createButtons() { + const btns = super.createButtons(); + function tagsToCsv(tags) { + return tags.map((el) => el.dataset.tag).join(", "); + } + function copyTags(e, tags) { + const textarea = $el("textarea", { + parent: document.body, + style: { + position: "fixed", + }, + textContent: tagsToCsv(tags), + }); + textarea.select(); + try { + document.execCommand("copy"); + if (!e.target.dataset.text) { + e.target.dataset.text = e.target.textContent; + } + e.target.textContent = "Copied " + tags.length + " tags"; + setTimeout(() => { + e.target.textContent = e.target.dataset.text; + }, 1000); + } catch (ex) { + prompt("Copy to clipboard: Ctrl+C, Enter", text); + } finally { + document.body.removeChild(textarea); + } + } + + btns.unshift( + $el("button", { + type: "button", + textContent: "Save Selected as Example", + onclick: async (e) => { + const tags = tagsToCsv([...this.tags.querySelectorAll(".pysssss-model-tag--selected")]); + await this.saveAsExample(tags); + }, + }), + $el("button", { + type: "button", + textContent: "Copy Selected", + onclick: (e) => { + copyTags(e, [...this.tags.querySelectorAll(".pysssss-model-tag--selected")]); + }, + }), + $el("button", { + type: "button", + textContent: "Copy All", + onclick: (e) => { + copyTags(e, [...this.tags.querySelectorAll(".pysssss-model-tag")]); + }, + }) + ); + + return btns; + } +} + +class CheckpointInfoDialog extends ModelInfoDialog { + async addInfo() { + super.addInfo(); + const info = await this.addCivitaiInfo(); + if (info) { + this.addInfoEntry("Base Model", info.baseModel || "⚠️ Unknown"); + + $el("div", { + parent: this.content, + innerHTML: info.description, + style: { + maxHeight: "250px", + overflow: "auto", + }, + }); + } + } +} + +const lookups = {}; + +function addInfoOption(node, type, infoClass, widgetNamePattern, opts) { + const widgets = widgetNamePattern + ? node.widgets.filter((w) => w.name === widgetNamePattern || w.name.match(`^${widgetNamePattern}$`)) + : [node.widgets[0]]; + for (const widget of widgets) { + let value = widget.value; + if (value?.content) { + value = value.content; + } + if (!value || value === "None") { + return; + } + let optName; + const split = value.split(/[.\\/]/); + optName = split[split.length - 2]; + opts.push({ + content: optName, + callback: async () => { + new infoClass(value, node).show(type, value); + }, + }); + } +} + +function addTypeOptions(node, typeName, options) { + const type = typeName.toLowerCase() + "s"; + const values = lookups[typeName][node.type]; + if (!values) return; + + const widgets = Object.keys(values); + const cls = type === "loras" ? LoraInfoDialog : CheckpointInfoDialog; + + const opts = []; + for (const w of widgets) { + addInfoOption(node, type, cls, w, opts); + } + + if (!opts.length) return; + + if (opts.length === 1) { + opts[0].content = `View ${typeName} info...`; + options.unshift(opts[0]); + } else { + options.unshift({ + title: `View ${typeName} info...`, + has_submenu: true, + submenu: { + options: opts, + }, + }); + } +} + +app.registerExtension({ + name: "pysssss.ModelInfo", + setup() { + const addSetting = (type, defaultValue) => { + app.ui.settings.addSetting({ + id: `pysssss.ModelInfo.${type}Nodes`, + name: `🐍 Model Info - ${type} Nodes/Widgets`, + type: "text", + defaultValue, + tooltip: `Comma separated list of NodeTypeName or NodeTypeName.WidgetName that contain ${type} node names that should have the View Info option available.\nIf no widget name is specifed the first widget will be used. Regex matches (e.g. NodeName..*lora_\\d+) are supported in the widget name.`, + onChange(value) { + lookups[type] = value.split(",").reduce((p, n) => { + n = n.trim(); + const pos = n.indexOf("."); + const split = pos === -1 ? [n] : [n.substring(0, pos), n.substring(pos + 1)]; + p[split[0]] ??= {}; + p[split[0]][split[1] ?? ""] = true; + return p; + }, {}); + }, + }); + }; + addSetting( + "Lora", + ["LoraLoader.lora_name", "LoraLoader|pysssss", "LoraLoaderModelOnly.lora_name", "LoRA Stacker.lora_name.*"].join(",") + ); + addSetting( + "Checkpoint", + ["CheckpointLoader.ckpt_name", "CheckpointLoaderSimple", "CheckpointLoader|pysssss", "Efficient Loader", "Eff. Loader SDXL"].join(",") + ); + + app.ui.settings.addSetting({ + id: `pysssss.ModelInfo.NsfwLevel`, + name: `🐍 Model Info - Image Preview Max NSFW Level`, + type: "combo", + defaultValue: "PG13", + options: Object.keys(NsfwLevel), + tooltip: `Hides preview images that are tagged as a higher NSFW level`, + onChange(value) { + ModelInfoDialog.nsfwLevel = NsfwLevel[value] ?? NsfwLevel.PG; + }, + }); + }, + beforeRegisterNodeDef(nodeType) { + const getExtraMenuOptions = nodeType.prototype.getExtraMenuOptions; + nodeType.prototype.getExtraMenuOptions = function (_, options) { + if (this.widgets) { + for (const type in lookups) { + addTypeOptions(this, type, options); + } + } + + return getExtraMenuOptions?.apply(this, arguments); + }; + }, +}); diff --git a/comfyui-custom-scripts/web/js/nodeFinder.js b/comfyui-custom-scripts/web/js/nodeFinder.js new file mode 100644 index 0000000000000000000000000000000000000000..d3727724b4ad09454aa77736115d81d6426be9ef --- /dev/null +++ b/comfyui-custom-scripts/web/js/nodeFinder.js @@ -0,0 +1,82 @@ +import { app } from "../../../scripts/app.js"; +import { api } from "../../../scripts/api.js"; + +// Adds a menu option to toggle follow the executing node +// Adds a menu option to go to the currently executing node +// Adds a menu option to go to a node by type + +app.registerExtension({ + name: "pysssss.NodeFinder", + setup() { + let followExecution = false; + + const centerNode = (id) => { + if (!followExecution || !id) return; + const node = app.graph.getNodeById(id); + if (!node) return; + app.canvas.centerOnNode(node); + }; + + api.addEventListener("executing", ({ detail }) => centerNode(detail)); + + // Add canvas menu options + const orig = LGraphCanvas.prototype.getCanvasMenuOptions; + LGraphCanvas.prototype.getCanvasMenuOptions = function () { + const options = orig.apply(this, arguments); + options.push(null, { + content: followExecution ? "Stop following execution" : "Follow execution", + callback: () => { + if ((followExecution = !followExecution)) { + centerNode(app.runningNodeId); + } + }, + }); + if (app.runningNodeId) { + options.push({ + content: "Show executing node", + callback: () => { + const node = app.graph.getNodeById(app.runningNodeId); + if (!node) return; + app.canvas.centerOnNode(node); + }, + }); + } + + const nodes = app.graph._nodes; + const types = nodes.reduce((p, n) => { + if (n.type in p) { + p[n.type].push(n); + } else { + p[n.type] = [n]; + } + return p; + }, {}); + options.push({ + content: "Go to node", + has_submenu: true, + submenu: { + options: Object.keys(types) + .sort() + .map((t) => ({ + content: t, + has_submenu: true, + submenu: { + options: types[t] + .sort((a, b) => { + return a.pos[0] - b.pos[0]; + }) + .map((n) => ({ + content: `${n.getTitle()} - #${n.id} (${n.pos[0]}, ${n.pos[1]})`, + callback: () => { + app.canvas.centerOnNode(n); + }, + })), + }, + })), + }, + }); + + return options; + }; + }, +}); diff --git a/comfyui-custom-scripts/web/js/playSound.js b/comfyui-custom-scripts/web/js/playSound.js new file mode 100644 index 0000000000000000000000000000000000000000..de71058989079786807ad4b66ca6853c4b0b0ac7 --- /dev/null +++ b/comfyui-custom-scripts/web/js/playSound.js @@ -0,0 +1,36 @@ +import { app } from "../../../scripts/app.js"; + +app.registerExtension({ + name: "pysssss.PlaySound", + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name === "PlaySound|pysssss") { + const onExecuted = nodeType.prototype.onExecuted; + nodeType.prototype.onExecuted = async function () { + onExecuted?.apply(this, arguments); + if (this.widgets[0].value === "on empty queue") { + if (app.ui.lastQueueSize !== 0) { + await new Promise((r) => setTimeout(r, 500)); + } + if (app.ui.lastQueueSize !== 0) { + return; + } + } + let file = this.widgets[2].value; + if (!file) { + file = "notify.mp3"; + } + if (!file.startsWith("http")) { + if (!file.includes("/")) { + file = "assets/" + file; + } + file = new URL(file, import.meta.url) + } + + const url = new URL(file); + const audio = new Audio(url); + audio.volume = this.widgets[1].value; + audio.play(); + }; + } + }, +}); diff --git a/comfyui-custom-scripts/web/js/presetText.js b/comfyui-custom-scripts/web/js/presetText.js new file mode 100644 index 0000000000000000000000000000000000000000..472f11bef9caa382703f6144c32d48c647b2443d --- /dev/null +++ b/comfyui-custom-scripts/web/js/presetText.js @@ -0,0 +1,257 @@ +import { app } from "../../../scripts/app.js"; + +// Allows you to manage preset tags for e.g. common negative prompt +// Also performs replacements on any text field e.g. allowing you to use preset text in CLIP Text encode fields + +let replaceRegex; +const id = "pysssss.PresetText.Presets"; +const MISSING = Symbol(); + +const getPresets = () => { + let items; + try { + items = JSON.parse(localStorage.getItem(id)); + } catch (error) {} + if (!items || !items.length) { + items = [{ name: "default negative", value: "worst quality" }]; + } + return items; +}; + +let presets = getPresets(); + +app.registerExtension({ + name: "pysssss.PresetText", + setup() { + app.ui.settings.addSetting({ + id: "pysssss.PresetText.ReplacementRegex", + name: "🐍 Preset Text Replacement Regex", + type: "text", + defaultValue: "(?:^|[^\\w])(?@(?[\\w-]+))", + tooltip: + "The regex should return two named capture groups: id (the name of the preset text to use), replace (the matched text to replace)", + attrs: { + style: { + fontFamily: "monospace", + }, + }, + onChange(value) { + if (!value) { + replaceRegex = null; + return; + } + try { + replaceRegex = new RegExp(value, "g"); + } catch (error) { + alert("Error creating regex for preset text replacement, no replacements will be performed."); + replaceRegex = null; + } + }, + }); + + const drawNodeWidgets = LGraphCanvas.prototype.drawNodeWidgets + LGraphCanvas.prototype.drawNodeWidgets = function(node) { + const c = LiteGraph.WIDGET_BGCOLOR; + try { + if(node[MISSING]) { + LiteGraph.WIDGET_BGCOLOR = "red" + } + return drawNodeWidgets.apply(this, arguments); + } finally { + LiteGraph.WIDGET_BGCOLOR = c; + } + } + }, + registerCustomNodes() { + class PresetTextNode extends LiteGraph.LGraphNode { + constructor() { + super(); + this.title = "Preset Text 🐍"; + this.isVirtualNode = true; + this.serialize_widgets = true; + this.addOutput("text", "STRING"); + + const widget = this.addWidget("combo", "value", presets[0].name, () => {}, { + values: presets.map((p) => p.name), + }); + this.addWidget("button", "Manage", "Manage", () => { + const container = document.createElement("div"); + Object.assign(container.style, { + display: "grid", + gridTemplateColumns: "1fr 1fr", + gap: "10px", + }); + + const addNew = document.createElement("button"); + addNew.textContent = "Add New"; + addNew.classList.add("pysssss-presettext-addnew"); + Object.assign(addNew.style, { + fontSize: "13px", + gridColumn: "1 / 3", + color: "dodgerblue", + width: "auto", + textAlign: "center", + }); + addNew.onclick = () => { + addRow({ name: "", value: "" }); + }; + container.append(addNew); + + function addRow(p) { + const name = document.createElement("input"); + const nameLbl = document.createElement("label"); + name.value = p.name; + nameLbl.textContent = "Name:"; + nameLbl.append(name); + + const value = document.createElement("input"); + const valueLbl = document.createElement("label"); + value.value = p.value; + valueLbl.textContent = "Value:"; + valueLbl.append(value); + + addNew.before(nameLbl, valueLbl); + } + for (const p of presets) { + addRow(p); + } + + const help = document.createElement("span"); + help.textContent = "To remove a preset set the name or value to blank"; + help.style.gridColumn = "1 / 3"; + container.append(help); + + dialog.show(""); + dialog.textElement.append(container); + }); + + const dialog = new app.ui.dialog.constructor(); + dialog.element.classList.add("comfy-settings"); + + const closeButton = dialog.element.querySelector("button"); + closeButton.textContent = "CANCEL"; + const saveButton = document.createElement("button"); + saveButton.textContent = "SAVE"; + saveButton.onclick = function () { + const inputs = dialog.element.querySelectorAll("input"); + const p = []; + for (let i = 0; i < inputs.length; i += 2) { + const n = inputs[i]; + const v = inputs[i + 1]; + if (!n.value.trim() || !v.value.trim()) { + continue; + } + p.push({ name: n.value, value: v.value }); + } + + widget.options.values = p.map((p) => p.name); + if (!widget.options.values.includes(widget.value)) { + widget.value = widget.options.values[0]; + } + + presets = p; + localStorage.setItem(id, JSON.stringify(presets)); + + dialog.close(); + }; + + closeButton.before(saveButton); + + this.applyToGraph = function (workflow) { + // For each output link copy our value over the original widget value + if (this.outputs[0].links && this.outputs[0].links.length) { + for (const l of this.outputs[0].links) { + const link_info = app.graph.links[l]; + const outNode = app.graph.getNodeById(link_info.target_id); + const outIn = outNode && outNode.inputs && outNode.inputs[link_info.target_slot]; + if (outIn.widget) { + const w = outNode.widgets.find((w) => w.name === outIn.widget.name); + if (!w) continue; + const preset = presets.find((p) => p.name === widget.value); + if (!preset) { + this[MISSING] = true; + app.graph.setDirtyCanvas(true, true); + const msg = `Preset text '${widget.value}' not found. Please fix this and queue again.`; + throw new Error(msg); + } + delete this[MISSING]; + w.value = preset.value; + } + } + } + }; + } + } + + LiteGraph.registerNodeType( + "PresetText|pysssss", + Object.assign(PresetTextNode, { + title: "Preset Text 🐍", + }) + ); + + PresetTextNode.category = "utils"; + }, + nodeCreated(node) { + if (node.widgets) { + // Locate dynamic prompt text widgets + const widgets = node.widgets.filter((n) => n.type === "customtext" || n.type === "text"); + for (const widget of widgets) { + const callbacks = [ + () => { + let prompt = widget.value; + if (replaceRegex && typeof prompt.replace !== 'undefined') { + prompt = prompt.replace(replaceRegex, (match, p1, p2, index, text, groups) => { + if (!groups.replace || !groups.id) return match; // No match, bad regex? + + const preset = presets.find((p) => p.name.replaceAll(/\s/g, "-") === groups.id); + if (!preset) return match; // Invalid name + + const pos = match.indexOf(groups.replace); + return match.substring(0, pos) + preset.value; + }); + } + return prompt; + }, + ]; + let inheritedSerializeValue = widget.serializeValue || null; + + let called = false; + const serializeValue = async (workflowNode, widgetIndex) => { + const origWidgetValue = widget.value; + if (called) return origWidgetValue; + called = true; + + let allCallbacks = [...callbacks]; + if (inheritedSerializeValue) { + allCallbacks.push(inheritedSerializeValue) + } + let valueIsUndefined = false; + + for (const cb of allCallbacks) { + let value = await cb(workflowNode, widgetIndex); + // Need to check the callback return value before it is set on widget.value as it coerces it to a string (even for undefined) + if (value === undefined) valueIsUndefined = true; + widget.value = value; + } + + const prompt = valueIsUndefined ? undefined : widget.value; + widget.value = origWidgetValue; + + called = false; + + return prompt; + }; + + Object.defineProperty(widget, "serializeValue", { + get() { + return serializeValue; + }, + set(cb) { + inheritedSerializeValue = cb; + }, + }); + } + } + }, +}); diff --git a/comfyui-custom-scripts/web/js/quickNodes.js b/comfyui-custom-scripts/web/js/quickNodes.js new file mode 100644 index 0000000000000000000000000000000000000000..a52581b32ed9cc6af01f016774518d17693b2132 --- /dev/null +++ b/comfyui-custom-scripts/web/js/quickNodes.js @@ -0,0 +1,196 @@ +import { app } from "../../../scripts/app.js"; + +// Adds a bunch of context menu entries for quickly adding common steps + +function addMenuHandler(nodeType, cb) { + const getOpts = nodeType.prototype.getExtraMenuOptions; + nodeType.prototype.getExtraMenuOptions = function () { + const r = getOpts.apply(this, arguments); + cb.apply(this, arguments); + return r; + }; +} + +function getOrAddVAELoader(node) { + let vaeNode = app.graph._nodes.find((n) => n.type === "VAELoader"); + if (!vaeNode) { + vaeNode = addNode("VAELoader", node); + } + return vaeNode; +} + +function addNode(name, nextTo, options) { + options = { select: true, shiftY: 0, before: false, ...(options || {}) }; + const node = LiteGraph.createNode(name); + app.graph.add(node); + node.pos = [ + options.before ? nextTo.pos[0] - node.size[0] - 30 : nextTo.pos[0] + nextTo.size[0] + 30, + nextTo.pos[1] + options.shiftY, + ]; + if (options.select) { + app.canvas.selectNode(node, false); + } + return node; +} + +app.registerExtension({ + name: "pysssss.QuickNodes", + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.input && nodeData.input.required) { + const keys = Object.keys(nodeData.input.required); + for (let i = 0; i < keys.length; i++) { + if (nodeData.input.required[keys[i]][0] === "VAE") { + addMenuHandler(nodeType, function (_, options) { + options.unshift({ + content: "Use VAE", + callback: () => { + getOrAddVAELoader(this).connect(0, this, i); + }, + }); + }); + break; + } + } + } + + if (nodeData.name === "KSampler") { + addMenuHandler(nodeType, function (_, options) { + options.unshift( + { + content: "Add Blank Input", + callback: () => { + const imageNode = addNode("EmptyLatentImage", this, { before: true }); + imageNode.connect(0, this, 3); + }, + }, + { + content: "Add Hi-res Fix", + callback: () => { + const upscaleNode = addNode("LatentUpscale", this); + this.connect(0, upscaleNode, 0); + + const sampleNode = addNode("KSampler", upscaleNode); + + for (let i = 0; i < 3; i++) { + const l = this.getInputLink(i); + if (l) { + app.graph.getNodeById(l.origin_id).connect(l.origin_slot, sampleNode, i); + } + } + + upscaleNode.connect(0, sampleNode, 3); + }, + }, + { + content: "Add 2nd Pass", + callback: () => { + const upscaleNode = addNode("LatentUpscale", this); + this.connect(0, upscaleNode, 0); + + const ckptNode = addNode("CheckpointLoaderSimple", this); + const sampleNode = addNode("KSampler", ckptNode); + + const positiveLink = this.getInputLink(1); + const negativeLink = this.getInputLink(2); + const positiveNode = positiveLink + ? app.graph.add(app.graph.getNodeById(positiveLink.origin_id).clone()) + : addNode("CLIPTextEncode"); + const negativeNode = negativeLink + ? app.graph.add(app.graph.getNodeById(negativeLink.origin_id).clone()) + : addNode("CLIPTextEncode"); + + ckptNode.connect(0, sampleNode, 0); + ckptNode.connect(1, positiveNode, 0); + ckptNode.connect(1, negativeNode, 0); + positiveNode.connect(0, sampleNode, 1); + negativeNode.connect(0, sampleNode, 2); + upscaleNode.connect(0, sampleNode, 3); + }, + }, + { + content: "Add Save Image", + callback: () => { + const decodeNode = addNode("VAEDecode", this); + this.connect(0, decodeNode, 0); + + getOrAddVAELoader(decodeNode).connect(0, decodeNode, 1); + + const saveNode = addNode("SaveImage", decodeNode); + decodeNode.connect(0, saveNode, 0); + }, + } + ); + }); + } + + if (nodeData.name === "CheckpointLoaderSimple") { + addMenuHandler(nodeType, function (_, options) { + options.unshift({ + content: "Add Clip Skip", + callback: () => { + const clipSkipNode = addNode("CLIPSetLastLayer", this); + const clipLinks = this.outputs[1].links ? this.outputs[1].links.map((l) => ({ ...graph.links[l] })) : []; + + this.disconnectOutput(1); + this.connect(1, clipSkipNode, 0); + + for (const clipLink of clipLinks) { + clipSkipNode.connect(0, clipLink.target_id, clipLink.target_slot); + } + }, + }); + }); + } + + if ( + nodeData.name === "CheckpointLoaderSimple" || + nodeData.name === "CheckpointLoader" || + nodeData.name === "CheckpointLoader|pysssss" || + nodeData.name === "LoraLoader" || + nodeData.name === "LoraLoader|pysssss" + ) { + addMenuHandler(nodeType, function (_, options) { + function addLora(type) { + const loraNode = addNode(type, this); + + const modelLinks = this.outputs[0].links ? this.outputs[0].links.map((l) => ({ ...graph.links[l] })) : []; + const clipLinks = this.outputs[1].links ? this.outputs[1].links.map((l) => ({ ...graph.links[l] })) : []; + + this.disconnectOutput(0); + this.disconnectOutput(1); + + this.connect(0, loraNode, 0); + this.connect(1, loraNode, 1); + + for (const modelLink of modelLinks) { + loraNode.connect(0, modelLink.target_id, modelLink.target_slot); + } + + for (const clipLink of clipLinks) { + loraNode.connect(1, clipLink.target_id, clipLink.target_slot); + } + } + options.unshift( + { + content: "Add LoRA", + callback: () => addLora.call(this, "LoraLoader"), + }, + { + content: "Add 🐍 LoRA", + callback: () => addLora.call(this, "LoraLoader|pysssss"), + }, + { + content: "Add Prompts", + callback: () => { + const positiveNode = addNode("CLIPTextEncode", this); + const negativeNode = addNode("CLIPTextEncode", this, { shiftY: positiveNode.size[1] + 30 }); + + this.connect(1, positiveNode, 0); + this.connect(1, negativeNode, 0); + }, + } + ); + }); + } + }, +}); diff --git a/comfyui-custom-scripts/web/js/repeater.js b/comfyui-custom-scripts/web/js/repeater.js new file mode 100644 index 0000000000000000000000000000000000000000..23432c4d4fa89f899312a7fa4bd83a04c635a6b5 --- /dev/null +++ b/comfyui-custom-scripts/web/js/repeater.js @@ -0,0 +1,123 @@ +import { app } from "../../../scripts/app.js"; + +const REPEATER = "Repeater|pysssss"; + +app.registerExtension({ + name: "pysssss.Repeater", + init() { + const graphToPrompt = app.graphToPrompt; + app.graphToPrompt = async function () { + const res = await graphToPrompt.apply(this, arguments); + + const id = Date.now() + "_"; + let u = 0; + + let newNodes = {}; + const newRepeaters = {}; + for (const nodeId in res.output) { + let output = res.output[nodeId]; + if (output.class_type === REPEATER) { + const isMulti = output.inputs.output === "multi"; + if (output.inputs.node_mode === "create") { + // We need to clone the input for every repeat + const orig = res.output[output.inputs.source[0]]; + if (isMulti) { + if (!newRepeaters[nodeId]) { + newRepeaters[nodeId] = []; + newRepeaters[nodeId][output.inputs.repeats - 1] = nodeId; + } + } + for (let i = 0; i < output.inputs.repeats - 1; i++) { + const clonedInputId = id + ++u; + + if (isMulti) { + // If multi create we need to clone the repeater too + newNodes[clonedInputId] = structuredClone(orig); + + output = structuredClone(output); + + const clonedRepeaterId = id + ++u; + newNodes[clonedRepeaterId] = output; + output.inputs["source"][0] = clonedInputId; + + newRepeaters[nodeId][i] = clonedRepeaterId; + } else { + newNodes[clonedInputId] = orig; + } + output.inputs[clonedInputId] = [clonedInputId, output.inputs.source[1]]; + } + } else if (isMulti) { + newRepeaters[nodeId] = Array(output.inputs.repeats).fill(nodeId); + } + } + } + + Object.assign(res.output, newNodes); + newNodes = {}; + + for (const nodeId in res.output) { + const output = res.output[nodeId]; + for (const k in output.inputs) { + const v = output.inputs[k]; + if (v instanceof Array) { + const repeaterId = v[0]; + const source = newRepeaters[repeaterId]; + if (source) { + v[0] = source.pop(); + v[1] = 0; + } + } + } + } + + // Object.assign(res.output, newNodes); + + return res; + }; + }, + beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name === REPEATER) { + const SETUP_OUTPUTS = Symbol(); + nodeType.prototype[SETUP_OUTPUTS] = function (repeats) { + if (repeats == null) { + repeats = this.widgets[0].value; + } + while (this.outputs.length > repeats) { + this.removeOutput(repeats); + } + const id = Date.now() + "_"; + let u = 0; + while (this.outputs.length < repeats) { + this.addOutput(id + ++u, "*", { label: "*" }); + } + }; + + const onAdded = nodeType.prototype.onAdded; + nodeType.prototype.onAdded = function () { + const self = this; + const repeatsCb = this.widgets[0].callback; + this.widgets[0].callback = async function () { + const v = (await repeatsCb?.apply(this, arguments)) ?? this.value; + if (self.widgets[1].value === "multi") { + self[SETUP_OUTPUTS](v); + } + return v; + }; + + const outputCb = this.widgets[1].callback; + this.widgets[1].callback = async function () { + const v = (await outputCb?.apply(this, arguments)) ?? this.value; + if (v === "single") { + self.outputs[0].shape = 6; + self[SETUP_OUTPUTS](1); + } else { + delete self.outputs[0].shape; + self[SETUP_OUTPUTS](); + } + return v; + }; + return onAdded?.apply(this, arguments); + }; + } + }, +}); diff --git a/comfyui-custom-scripts/web/js/reroutePrimitive.js b/comfyui-custom-scripts/web/js/reroutePrimitive.js new file mode 100644 index 0000000000000000000000000000000000000000..7b934d717073b3b4dc210a48356580c615802375 --- /dev/null +++ b/comfyui-custom-scripts/web/js/reroutePrimitive.js @@ -0,0 +1,348 @@ +import { app } from "../../../scripts/app.js"; +import { ComfyWidgets } from "../../../scripts/widgets.js"; + +const REROUTE_PRIMITIVE = "ReroutePrimitive|pysssss"; +const MULTI_PRIMITIVE = "MultiPrimitive|pysssss"; +const LAST_TYPE = Symbol("LastType"); + +app.registerExtension({ + name: "pysssss.ReroutePrimitive", + init() { + // On graph configure, fire onGraphConfigured to create widgets + const graphConfigure = LGraph.prototype.configure; + LGraph.prototype.configure = function () { + const r = graphConfigure.apply(this, arguments); + for (const n of app.graph._nodes) { + if (n.type === REROUTE_PRIMITIVE) { + n.onGraphConfigured(); + } + } + + return r; + }; + + // Hide this node as it is no longer supported + const getNodeTypesCategories = LiteGraph.getNodeTypesCategories; + LiteGraph.getNodeTypesCategories = function() { + return getNodeTypesCategories.apply(this, arguments).filter(c => !c.startsWith("__hidden__")); + } + + const graphToPrompt = app.graphToPrompt; + app.graphToPrompt = async function () { + const res = await graphToPrompt.apply(this, arguments); + + const multiOutputs = []; + for (const nodeId in res.output) { + const output = res.output[nodeId]; + if (output.class_type === MULTI_PRIMITIVE) { + multiOutputs.push({ id: nodeId, inputs: output.inputs }); + } + } + + function permute(outputs) { + function generatePermutations(inputs, currentIndex, currentPermutation, result) { + if (currentIndex === inputs.length) { + result.push({ ...currentPermutation }); + return; + } + + const input = inputs[currentIndex]; + + for (const k in input) { + currentPermutation[currentIndex] = input[k]; + generatePermutations(inputs, currentIndex + 1, currentPermutation, result); + } + } + + const inputs = outputs.map((output) => output.inputs); + const result = []; + const current = new Array(inputs.length); + + generatePermutations(inputs, 0, current, result); + + return outputs.map((output, index) => ({ + ...output, + inputs: result.reduce((p, permutation) => { + const count = Object.keys(p).length; + p["value" + (count || "")] = permutation[index]; + return p; + }, {}), + })); + } + + const permutations = permute(multiOutputs); + for (let i = 0; i < permutations.length; i++) { + res.output[multiOutputs[i].id].inputs = permutations[i].inputs; + } + + return res; + }; + }, + async beforeRegisterNodeDef(nodeType, nodeData, app) { + function addOutputHandler() { + // Finds the first non reroute output node down the chain + nodeType.prototype.getFirstReroutedOutput = function (slot) { + if (nodeData.name === MULTI_PRIMITIVE) { + slot = 0; + } + const links = this.outputs[slot].links; + if (!links) return null; + + const search = []; + for (const l of links) { + const link = app.graph.links[l]; + if (!link) continue; + + const node = app.graph.getNodeById(link.target_id); + if (node.type !== REROUTE_PRIMITIVE && node.type !== MULTI_PRIMITIVE) { + return { node, link }; + } + search.push({ node, link }); + } + + for (const { link, node } of search) { + const r = node.getFirstReroutedOutput(link.target_slot); + if (r) { + return r; + } + } + }; + } + + if (nodeData.name === REROUTE_PRIMITIVE) { + const configure = nodeType.prototype.configure || LGraphNode.prototype.configure; + const onConnectionsChange = nodeType.prototype.onConnectionsChange; + const onAdded = nodeType.prototype.onAdded; + + nodeType.title_mode = LiteGraph.NO_TITLE; + + function hasAnyInput(node) { + for (const input of node.inputs) { + if (input.link) { + return true; + } + } + return false; + } + + // Remove input text + nodeType.prototype.onAdded = function () { + onAdded?.apply(this, arguments); + this.inputs[0].label = ""; + this.outputs[0].label = "value"; + this.setSize(this.computeSize()); + }; + + // Restore any widgets + nodeType.prototype.onGraphConfigured = function () { + if (hasAnyInput(this)) return; + + const outputNode = this.getFirstReroutedOutput(0); + if (outputNode) { + this.checkPrimitiveWidget(outputNode); + } + }; + + // Check if we need to create (or remove) a widget on the node + nodeType.prototype.checkPrimitiveWidget = function ({ node, link }) { + let widgetType = link.type; + let targetLabel = widgetType; + const input = node.inputs[link.target_slot]; + if (input.widget?.config?.[0] instanceof Array) { + targetLabel = input.widget.name; + widgetType = "COMBO"; + } + + if (widgetType in ComfyWidgets) { + if (!this.widgets?.length) { + let v; + if (this.widgets_values?.length) { + v = this.widgets_values[0]; + } + let config = [link.type, {}]; + if (input.widget?.config) { + config = input.widget.config; + } + const { widget } = ComfyWidgets[widgetType](this, "value", config, app); + if (v !== undefined && (!this[LAST_TYPE] || this[LAST_TYPE] === widgetType)) { + widget.value = v; + } + this[LAST_TYPE] = widgetType; + } + } else if (this.widgets) { + this.widgets.length = 0; + } + + return targetLabel; + }; + + // Finds all input nodes from the current reroute + nodeType.prototype.getReroutedInputs = function (slot) { + let nodes = [{ node: this }]; + let node = this; + while (node?.type === REROUTE_PRIMITIVE) { + const input = node.inputs[slot]; + if (input.link) { + const link = app.graph.links[input.link]; + node = app.graph.getNodeById(link.origin_id); + slot = link.origin_slot; + nodes.push({ + node, + link, + }); + } else { + node = null; + } + } + + return nodes; + }; + + addOutputHandler(); + + // Update the type of all reroutes in a chain + nodeType.prototype.changeRerouteType = function (slot, type, label) { + const color = LGraphCanvas.link_type_colors[type]; + const output = this.outputs[slot]; + this.inputs[slot].label = " "; + output.label = label || (type === "*" ? "value" : type); + output.type = type; + + // Process all linked outputs + for (const linkId of output.links || []) { + const link = app.graph.links[linkId]; + if (!link) continue; + link.color = color; + const node = app.graph.getNodeById(link.target_id); + if (node.changeRerouteType) { + // Recursively update reroutes + node.changeRerouteType(link.target_slot, type, label); + } else { + // Validate links to 'real' nodes + const theirType = node.inputs[link.target_slot].type; + if (theirType !== type && theirType !== "*") { + node.disconnectInput(link.target_slot); + } + } + } + + if (this.inputs[slot].link) { + const link = app.graph.links[this.inputs[slot].link]; + if (link) link.color = color; + } + }; + + // Override configure so we can flag that we are configuring to avoid link validation breaking + let configuring = false; + nodeType.prototype.configure = function () { + configuring = true; + const r = configure?.apply(this, arguments); + configuring = false; + + return r; + }; + + Object.defineProperty(nodeType, "title_mode", { + get() { + return app.canvas.current_node?.widgets?.length ? LiteGraph.NORMAL_TITLE : LiteGraph.NO_TITLE; + }, + }); + + nodeType.prototype.onConnectionsChange = function (type, _, connected, link_info) { + // If configuring treat everything as OK as links may not be set by litegraph yet + if (configuring) return; + + const isInput = type === LiteGraph.INPUT; + const slot = isInput ? link_info.target_slot : link_info.origin_slot; + + let targetLabel = null; + let targetNode = null; + let targetType = "*"; + let targetSlot = slot; + + const inputPath = this.getReroutedInputs(slot); + const rootInput = inputPath[inputPath.length - 1]; + const outputNode = this.getFirstReroutedOutput(slot); + if (rootInput.node.type === REROUTE_PRIMITIVE) { + // Our input node is a reroute, so see if we have an output + if (outputNode) { + targetType = outputNode.link.type; + } else if (rootInput.node.widgets) { + rootInput.node.widgets.length = 0; + } + targetNode = rootInput; + targetSlot = rootInput.link?.target_slot ?? slot; + } else { + // We have a real input, so we want to use that type + targetNode = inputPath[inputPath.length - 2]; + targetType = rootInput.node.outputs[rootInput.link.origin_slot].type; + targetSlot = rootInput.link.target_slot; + } + + if (this.widgets && inputPath.length > 1) { + // We have an input node so remove our widget + this.widgets.length = 0; + } + + if (outputNode && rootInput.node.checkPrimitiveWidget) { + // We have an output, check if we need to create a widget + targetLabel = rootInput.node.checkPrimitiveWidget(outputNode); + } + + // Trigger an update of the type to all child nodes + targetNode.node.changeRerouteType(targetSlot, targetType, targetLabel); + + return onConnectionsChange?.apply(this, arguments); + }; + + // When collapsed fix the size to just the dot + const computeSize = nodeType.prototype.computeSize || LGraphNode.prototype.computeSize; + nodeType.prototype.computeSize = function () { + const r = computeSize.apply(this, arguments); + if (this.flags?.collapsed) { + return [1, 25]; + } else if (this.widgets?.length) { + return r; + } else { + let w = 75; + if (this.outputs?.[0]?.label) { + const t = LiteGraph.NODE_TEXT_SIZE * this.outputs[0].label.length * 0.6 + 30; + if (t > w) { + w = t; + } + } + return [w, r[1]]; + } + }; + + // On collapse shrink the node to just a dot + const collapse = nodeType.prototype.collapse || LGraphNode.prototype.collapse; + nodeType.prototype.collapse = function () { + collapse.apply(this, arguments); + this.setSize(this.computeSize()); + requestAnimationFrame(() => { + this.setDirtyCanvas(true, true); + }); + }; + + // Shift the bounding area up slightly as LiteGraph miscalculates it for collapsed nodes + nodeType.prototype.onBounding = function (area) { + if (this.flags?.collapsed) { + area[1] -= 15; + } + }; + } else if (nodeData.name === MULTI_PRIMITIVE) { + addOutputHandler(); + nodeType.prototype.onConnectionsChange = function (type, _, connected, link_info) { + for (let i = 0; i < this.inputs.length - 1; i++) { + if (!this.inputs[i].link) { + this.removeInput(i--); + } + } + if (this.inputs[this.inputs.length - 1].link) { + this.addInput("v" + +new Date(), this.inputs[0].type).label = "value"; + } + }; + } + }, +}); diff --git a/comfyui-custom-scripts/web/js/showImageOnMenu.js b/comfyui-custom-scripts/web/js/showImageOnMenu.js new file mode 100644 index 0000000000000000000000000000000000000000..4fed9de92e333270f1c2066e7667e34fd40e539b --- /dev/null +++ b/comfyui-custom-scripts/web/js/showImageOnMenu.js @@ -0,0 +1,81 @@ +import { app } from "../../../scripts/app.js"; +import { api } from "../../../scripts/api.js"; +import { $el } from "../../../scripts/ui.js"; + +const id = "pysssss.ShowImageOnMenu"; +const ext = { + name: id, + async setup(app) { + let enabled = true; + let nodeId = null; + const img = $el("img", { + style: { + width: "100%", + height: "150px", + objectFit: "contain", + }, + }); + const link = $el( + "a", + { + style: { + width: "100%", + height: "150px", + marginTop: "10px", + order: 100, // Place this item last (until someone else has a higher order) + display: "none", + }, + href: "#", + onclick: (e) => { + e.stopPropagation(); + e.preventDefault(); + const node = app.graph.getNodeById(nodeId); + if (!node) return; + app.canvas.centerOnNode(node); + app.canvas.setZoom(1); + }, + }, + [img] + ); + + app.ui.menuContainer.append(link); + + const show = (src, node) => { + img.src = src; + nodeId = Number(node); + link.style.display = "unset"; + }; + + api.addEventListener("executed", ({ detail }) => { + if (!enabled) return; + const images = detail?.output?.images; + if (!images || !images.length) return; + const format = app.getPreviewFormatParam(); + const src = [ + `./view?filename=${encodeURIComponent(images[0].filename)}`, + `type=${images[0].type}`, + `subfolder=${encodeURIComponent(images[0].subfolder)}`, + `t=${+new Date()}${format}`,].join('&'); + show(src, detail.node); + }); + + api.addEventListener("b_preview", ({ detail }) => { + if (!enabled) return; + show(URL.createObjectURL(detail), app.runningNodeId); + }); + + app.ui.settings.addSetting({ + id, + name: "🐍 Show Image On Menu", + defaultValue: true, + type: "boolean", + onChange(value) { + enabled = value; + + if (!enabled) link.style.display = "none"; + }, + }); + }, +}; + +app.registerExtension(ext); diff --git a/comfyui-custom-scripts/web/js/showText.js b/comfyui-custom-scripts/web/js/showText.js new file mode 100644 index 0000000000000000000000000000000000000000..464fd404632397e26c2af1d2297970da6c726920 --- /dev/null +++ b/comfyui-custom-scripts/web/js/showText.js @@ -0,0 +1,78 @@ +import { app } from "../../../scripts/app.js"; +import { ComfyWidgets } from "../../../scripts/widgets.js"; + +// Displays input text on a node + +// TODO: This should need to be so complicated. Refactor at some point. + +app.registerExtension({ + name: "pysssss.ShowText", + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name === "ShowText|pysssss") { + function populate(text) { + if (this.widgets) { + // On older frontend versions there is a hidden converted-widget + const isConvertedWidget = +!!this.inputs?.[0].widget; + for (let i = isConvertedWidget; i < this.widgets.length; i++) { + this.widgets[i].onRemove?.(); + } + this.widgets.length = isConvertedWidget; + } + + const v = [...text]; + if (!v[0]) { + v.shift(); + } + for (let list of v) { + // Force list to be an array, not sure why sometimes it is/isn't + if (!(list instanceof Array)) list = [list]; + for (const l of list) { + const w = ComfyWidgets["STRING"](this, "text_" + this.widgets?.length ?? 0, ["STRING", { multiline: true }], app).widget; + w.inputEl.readOnly = true; + w.inputEl.style.opacity = 0.6; + w.value = l; + } + } + + requestAnimationFrame(() => { + const sz = this.computeSize(); + if (sz[0] < this.size[0]) { + sz[0] = this.size[0]; + } + if (sz[1] < this.size[1]) { + sz[1] = this.size[1]; + } + this.onResize?.(sz); + app.graph.setDirtyCanvas(true, false); + }); + } + + // When the node is executed we will be sent the input text, display this in the widget + const onExecuted = nodeType.prototype.onExecuted; + nodeType.prototype.onExecuted = function (message) { + onExecuted?.apply(this, arguments); + populate.call(this, message.text); + }; + + const VALUES = Symbol(); + const configure = nodeType.prototype.configure; + nodeType.prototype.configure = function () { + // Store unmodified widget values as they get removed on configure by new frontend + this[VALUES] = arguments[0]?.widgets_values; + return configure?.apply(this, arguments); + }; + + const onConfigure = nodeType.prototype.onConfigure; + nodeType.prototype.onConfigure = function () { + onConfigure?.apply(this, arguments); + const widgets_values = this[VALUES]; + if (widgets_values?.length) { + // In newer frontend there seems to be a delay in creating the initial widget + requestAnimationFrame(() => { + populate.call(this, widgets_values.slice(+(widgets_values.length > 1 && this.inputs?.[0].widget))); + }); + } + }; + } + }, +}); diff --git a/comfyui-custom-scripts/web/js/snapToGrid.js b/comfyui-custom-scripts/web/js/snapToGrid.js new file mode 100644 index 0000000000000000000000000000000000000000..07d5aa8c7bec97e2e14a8470fc8df2e82c14c39d --- /dev/null +++ b/comfyui-custom-scripts/web/js/snapToGrid.js @@ -0,0 +1,73 @@ +import { app } from "../../../scripts/app.js"; + +let setting; +const id = "pysssss.SnapToGrid"; + +/** Wraps the provided function call to set/reset shiftDown when setting is enabled. */ +function wrapCallInSettingCheck(fn) { + if (setting?.value) { + const shift = app.shiftDown; + app.shiftDown = true; + const r = fn(); + app.shiftDown = shift; + return r; + } + return fn(); +} + +const ext = { + name: id, + init() { + setting = app.ui.settings.addSetting({ + id, + name: "🐍 Always snap to grid", + defaultValue: false, + type: "boolean", + onChange(value) { + app.canvas.align_to_grid = value; + }, + }); + + // We need to register our hooks after the core snap to grid extension runs + // Do this from the graph configure function so we still get onNodeAdded calls + const configure = LGraph.prototype.configure; + LGraph.prototype.configure = function () { + // Override drawNode to draw the drop position + const drawNode = LGraphCanvas.prototype.drawNode; + LGraphCanvas.prototype.drawNode = function () { + wrapCallInSettingCheck(() => drawNode.apply(this, arguments)); + }; + + // Override node added to add a resize handler to force grid alignment + const onNodeAdded = app.graph.onNodeAdded; + app.graph.onNodeAdded = function (node) { + const r = onNodeAdded?.apply(this, arguments); + const onResize = node.onResize; + node.onResize = function () { + wrapCallInSettingCheck(() => onResize?.apply(this, arguments)); + }; + return r; + }; + + + const groupMove = LGraphGroup.prototype.move; + LGraphGroup.prototype.move = function(deltax, deltay, ignore_nodes) { + wrapCallInSettingCheck(() => groupMove.apply(this, arguments)); + } + + const canvasDrawGroups = LGraphCanvas.prototype.drawGroups; + LGraphCanvas.prototype.drawGroups = function (canvas, ctx) { + wrapCallInSettingCheck(() => canvasDrawGroups.apply(this, arguments)); + } + + const canvasOnGroupAdd = LGraphCanvas.onGroupAdd; + LGraphCanvas.onGroupAdd = function() { + wrapCallInSettingCheck(() => canvasOnGroupAdd.apply(this, arguments)); + } + + return configure.apply(this, arguments); + }; + }, +}; + +app.registerExtension(ext); diff --git a/comfyui-custom-scripts/web/js/snapToGridGuide.js b/comfyui-custom-scripts/web/js/snapToGridGuide.js new file mode 100644 index 0000000000000000000000000000000000000000..54a8a0c70b2705620be0c63c2cecdb3ea032420f --- /dev/null +++ b/comfyui-custom-scripts/web/js/snapToGridGuide.js @@ -0,0 +1,163 @@ +import { app } from "../../../scripts/app.js"; +import { $el } from "../../../scripts/ui.js"; + +let guide_config; +const id = "pysssss.SnapToGrid.Guide"; +const guide_config_default = { + lines: { + enabled: false, + fillStyle: "rgba(255, 0, 0, 0.5)", + }, + block: { + enabled: false, + fillStyle: "rgba(0, 0, 255, 0.5)", + }, +} + +const ext = { + name: id, + init() { + if (localStorage.getItem(id) === null) { + localStorage.setItem(id, JSON.stringify(guide_config_default)); + } + guide_config = JSON.parse(localStorage.getItem(id)); + + app.ui.settings.addSetting({ + id, + name: "🐍 Display drag-and-drop guides", + type: (name, setter, value) => { + return $el("tr", [ + $el("td", [ + $el("label", { + for: id.replaceAll(".", "-"), + textContent: name, + }), + ]), + $el("td", [ + $el( + "label", + { + textContent: "Lines: ", + style: { + display: "inline-block", + }, + }, + [ + $el("input", { + id: id.replaceAll(".", "-") + "-line-text", + type: "text", + value: guide_config.lines.fillStyle, + onchange: (event) => { + guide_config.lines.fillStyle = event.target.value; + localStorage.setItem(id, JSON.stringify(guide_config)); + } + }), + $el("input", { + id: id.replaceAll(".", "-") + "-line-checkbox", + type: "checkbox", + checked: guide_config.lines.enabled, + onchange: (event) => { + guide_config.lines.enabled = !!event.target.checked; + localStorage.setItem(id, JSON.stringify(guide_config)); + }, + }), + ] + ), + $el( + "label", + { + textContent: "Block: ", + style: { + display: "inline-block", + }, + }, + [ + $el("input", { + id: id.replaceAll(".", "-") + "-block-text", + type: "text", + value: guide_config.block.fillStyle, + onchange: (event) => { + guide_config.block.fillStyle = event.target.value; + localStorage.setItem(id, JSON.stringify(guide_config)); + } + }), + $el("input", { + id: id.replaceAll(".", "-") + '-block-checkbox', + type: "checkbox", + checked: guide_config.block.enabled, + onchange: (event) => { + guide_config.block.enabled = !!event.target.checked; + localStorage.setItem(id, JSON.stringify(guide_config)); + }, + }), + ] + ), + ]), + ]); + } + }); + + const alwaysSnapToGrid = () => + app.ui.settings.getSettingValue("pysssss.SnapToGrid", /* default=*/ false); + const snapToGridEnabled = () => + app.shiftDown || alwaysSnapToGrid(); + + // Override drag-and-drop behavior to show orthogonal guide lines around selected node(s) and preview of where the node(s) will be placed + const origDrawNode = LGraphCanvas.prototype.drawNode; + LGraphCanvas.prototype.drawNode = function (node, ctx) { + const enabled = guide_config.lines.enabled || guide_config.block.enabled; + if (enabled && this.node_dragged && node.id in this.selected_nodes && snapToGridEnabled()) { + // discretize the canvas into grid + let x = LiteGraph.CANVAS_GRID_SIZE * Math.round(node.pos[0] / LiteGraph.CANVAS_GRID_SIZE); + let y = LiteGraph.CANVAS_GRID_SIZE * Math.round(node.pos[1] / LiteGraph.CANVAS_GRID_SIZE); + + // calculate the width and height of the node + // (also need to shift the y position of the node, depending on whether the title is visible) + x -= node.pos[0]; + y -= node.pos[1]; + let w, h; + if (node.flags.collapsed) { + w = node._collapsed_width; + h = LiteGraph.NODE_TITLE_HEIGHT; + y -= LiteGraph.NODE_TITLE_HEIGHT; + } else { + w = node.size[0]; + h = node.size[1]; + let titleMode = node.constructor.title_mode; + if (titleMode !== LiteGraph.TRANSPARENT_TITLE && titleMode !== LiteGraph.NO_TITLE) { + h += LiteGraph.NODE_TITLE_HEIGHT; + y -= LiteGraph.NODE_TITLE_HEIGHT; + } + } + + // save the original fill style + const f = ctx.fillStyle; + + // draw preview for drag-and-drop (rectangle to show where the node will be placed) + if (guide_config.block.enabled) { + ctx.fillStyle = guide_config.block.fillStyle; + ctx.fillRect(x, y, w, h); + } + + // add guide lines around node (arbitrarily long enough to span most workflows) + if (guide_config.lines.enabled) { + const xd = 10000; + const yd = 10000; + const thickness = 3; + ctx.fillStyle = guide_config.lines.fillStyle; + ctx.fillRect(x - xd, y, 2*xd, thickness); + ctx.fillRect(x, y - yd, thickness, 2*yd); + ctx.fillRect(x - xd, y + h, 2*xd, thickness); + ctx.fillRect(x + w, y - yd, thickness, 2*yd); + } + + // restore the original fill style + ctx.fillStyle = f; + } + + return origDrawNode.apply(this, arguments); + }; + }, +}; + +app.registerExtension(ext); diff --git a/comfyui-custom-scripts/web/js/stringFunction.js b/comfyui-custom-scripts/web/js/stringFunction.js new file mode 100644 index 0000000000000000000000000000000000000000..cc150dff04a2e94b9bc768f6331964c13a96ddbe --- /dev/null +++ b/comfyui-custom-scripts/web/js/stringFunction.js @@ -0,0 +1,33 @@ +import { app } from "../../../scripts/app.js"; +import { ComfyWidgets } from "../../../scripts/widgets.js"; + +// Displays input text on a node + +app.registerExtension({ + name: "pysssss.StringFunction", + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name === "StringFunction|pysssss") { + const onExecuted = nodeType.prototype.onExecuted; + nodeType.prototype.onExecuted = function (message) { + onExecuted?.apply(this, arguments); + + if (this.widgets) { + const pos = this.widgets.findIndex((w) => w.name === "result"); + if (pos !== -1) { + for (let i = pos; i < this.widgets.length; i++) { + this.widgets[i].onRemove?.(); + } + this.widgets.length = pos; + } + } + + const w = ComfyWidgets["STRING"](this, "result", ["STRING", { multiline: true }], app).widget; + w.inputEl.readOnly = true; + w.inputEl.style.opacity = 0.6; + w.value = message.text; + + this.onResize?.(this.size); + }; + } + }, +}); diff --git a/comfyui-custom-scripts/web/js/swapResolution.js b/comfyui-custom-scripts/web/js/swapResolution.js new file mode 100644 index 0000000000000000000000000000000000000000..40f6dcc851780077c79e7e142fd0f97104e85a09 --- /dev/null +++ b/comfyui-custom-scripts/web/js/swapResolution.js @@ -0,0 +1,30 @@ +import { app } from "../../../scripts/app.js"; +app.registerExtension({ + name: "pysssss.SwapResolution", + async beforeRegisterNodeDef(nodeType, nodeData) { + const inputs = { ...nodeData.input?.required, ...nodeData.input?.optional }; + if (inputs.width && inputs.height) { + const origGetExtraMenuOptions = nodeType.prototype.getExtraMenuOptions; + nodeType.prototype.getExtraMenuOptions = function (_, options) { + const r = origGetExtraMenuOptions?.apply?.(this, arguments); + + options.push( + { + content: "Swap width/height", + callback: () => { + const w = this.widgets.find((w) => w.name === "width"); + const h = this.widgets.find((w) => w.name === "height"); + const a = w.value; + w.value = h.value; + h.value = a; + app.graph.setDirtyCanvas(true); + }, + }, + null + ); + + return r; + }; + } + }, +}); diff --git a/comfyui-custom-scripts/web/js/systemNotification.js b/comfyui-custom-scripts/web/js/systemNotification.js new file mode 100644 index 0000000000000000000000000000000000000000..803b8c90629f6722efd090e0bf5839e395c4402b --- /dev/null +++ b/comfyui-custom-scripts/web/js/systemNotification.js @@ -0,0 +1,47 @@ +import { app } from "../../../scripts/app.js"; + +const notificationSetup = () => { + if (!("Notification" in window)) { + console.log("This browser does not support notifications."); + alert("This browser does not support notifications."); + return; + } + if (Notification.permission === "denied") { + console.log("Notifications are blocked. Please enable them in your browser settings."); + alert("Notifications are blocked. Please enable them in your browser settings."); + return; + } + if (Notification.permission !== "granted") { + Notification.requestPermission(); + } + return true; +}; + +app.registerExtension({ + name: "pysssss.SystemNotification", + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name === "SystemNotification|pysssss") { + const onExecuted = nodeType.prototype.onExecuted; + nodeType.prototype.onExecuted = async function ({ message, mode }) { + onExecuted?.apply(this, arguments); + + if (mode === "on empty queue") { + if (app.ui.lastQueueSize !== 0) { + await new Promise((r) => setTimeout(r, 500)); + } + if (app.ui.lastQueueSize !== 0) { + return; + } + } + if (!notificationSetup()) return; + const notification = new Notification("ComfyUI", { body: message ?? "Your notification has triggered." }); + }; + + const onNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function () { + onNodeCreated?.apply(this, arguments); + notificationSetup(); + }; + } + }, +}); diff --git a/comfyui-custom-scripts/web/js/useNumberInputPrompt.js b/comfyui-custom-scripts/web/js/useNumberInputPrompt.js new file mode 100644 index 0000000000000000000000000000000000000000..a92aa51095bc474b3cf80697aa238ad8814b4c3d --- /dev/null +++ b/comfyui-custom-scripts/web/js/useNumberInputPrompt.js @@ -0,0 +1,36 @@ +import { app } from "../../../scripts/app.js"; + +const id = "pysssss.UseNumberInputPrompt"; +const ext = { + name: id, + async setup(app) { + const prompt = LGraphCanvas.prototype.prompt; + + const setting = app.ui.settings.addSetting({ + id, + name: "🐍 Use number input on value entry", + defaultValue: false, + type: "boolean", + }); + + LGraphCanvas.prototype.prompt = function () { + const dialog = prompt.apply(this, arguments); + if (setting.value && typeof arguments[1] === "number") { + // If this should be a number then update the imput + const input = dialog.querySelector("input"); + input.type = "number"; + + // Add constraints + const widget = app.canvas.node_widget?.[1]; + if (widget?.options) { + for (const prop of ["min", "max", "step"]) { + if (widget.options[prop]) input[prop] = widget.options[prop]; + } + } + } + return dialog; + }; + }, +}; + +app.registerExtension(ext); diff --git a/comfyui-custom-scripts/web/js/widgetDefaults.js b/comfyui-custom-scripts/web/js/widgetDefaults.js new file mode 100644 index 0000000000000000000000000000000000000000..859749d16fda455bcdfb4a6fba89a7340c839183 --- /dev/null +++ b/comfyui-custom-scripts/web/js/widgetDefaults.js @@ -0,0 +1,297 @@ +import { app } from "../../../scripts/app.js"; +import { $el, ComfyDialog } from "../../../scripts/ui.js"; + +// Allows you to specify custom default values for any widget on any node + +const id = "pysssss.WidgetDefaults"; +const nodeDataKey = Symbol(); + +app.registerExtension({ + name: id, + beforeRegisterNodeDef(nodeType, nodeData) { + nodeType[nodeDataKey] = nodeData; + }, + setup() { + let defaults; + let regexDefaults; + let setting; + + const getNodeDefaults = (node, defaults) => { + const nodeDefaults = defaults[node.type] ?? {}; + const propSetBy = {}; + + Object.keys(regexDefaults) + .filter((r) => new RegExp(r).test(node.type)) + .reduce((p, n) => { + const props = regexDefaults[n]; + for (const k in props) { + // Use the longest matching key as its probably the most specific + if (!(k in nodeDefaults) || (k in propSetBy && n.length > propSetBy[k].length)) { + propSetBy[k] = n; + nodeDefaults[k] = props[k]; + } + } + return p; + }, nodeDefaults); + + return nodeDefaults; + }; + + const applyDefaults = (defaults) => { + for (const node of Object.values(LiteGraph.registered_node_types)) { + const nodeData = node[nodeDataKey]; + if (!nodeData) continue; + const nodeDefaults = getNodeDefaults(node, defaults); + if (!nodeDefaults) continue; + const inputs = { ...(nodeData.input?.required || {}), ...(nodeData.input?.optional || {}) }; + + for (const w in nodeDefaults) { + const widgetDef = inputs[w]; + if (widgetDef) { + let v = nodeDefaults[w]; + if (widgetDef[0] === "INT" || widgetDef[0] === "FLOAT") { + v = +v; + } + if (widgetDef[1]) { + widgetDef[1].default = v; + } else { + widgetDef[1] = { default: v }; + } + } + } + } + }; + + const getDefaults = () => { + let items; + regexDefaults = {}; + try { + items = JSON.parse(setting.value); + items = items.reduce((p, n) => { + if (n.node.startsWith("/") && n.node.endsWith("/")) { + const name = n.node.substring(1, n.node.length - 1); + try { + // Validate regex + new RegExp(name); + + if (!regexDefaults[name]) regexDefaults[name] = {}; + regexDefaults[name][n.widget] = n.value; + } catch (error) {} + } + + if (!p[n.node]) p[n.node] = {}; + p[n.node][n.widget] = n.value; + return p; + }, {}); + } catch (error) {} + if (!items) { + items = {}; + } + applyDefaults(items); + return items; + }; + + const onNodeAdded = app.graph.onNodeAdded; + app.graph.onNodeAdded = function (node) { + onNodeAdded?.apply?.(this, arguments); + + // See if we have any defaults for this type of node + const nodeDefaults = getNodeDefaults(node.constructor, defaults); + if (!nodeDefaults) return; + + // Dont run if they are pre-configured nodes from load/pastes + const stack = new Error().stack; + if (stack.includes("pasteFromClipboard") || stack.includes("loadGraphData")) { + return; + } + + for (const k in nodeDefaults) { + if (k.startsWith("property.")) { + const name = k.substring(9); + let v = nodeDefaults[k]; + // Special handling for some built in values + if (name in node || ["color", "bgcolor", "title"].includes(name)) { + node[name] = v; + } else { + // Try using the correct type + if (!node.properties) node.properties = {}; + if (typeof node.properties[name] === "number") v = +v; + else if (typeof node.properties[name] === "boolean") v = v === "true"; + else if (v === "true") v = true; + + node.properties[name] = v; + } + } + } + }; + + class WidgetDefaultsDialog extends ComfyDialog { + constructor() { + super(); + this.element.classList.add("comfy-manage-templates"); + this.grid = $el( + "div", + { + style: { + display: "grid", + gridTemplateColumns: "1fr auto auto auto", + gap: "5px", + }, + className: "pysssss-widget-defaults", + }, + [ + $el("label", { + textContent: "Node Class", + }), + $el("label", { + textContent: "Widget Name", + }), + $el("label", { + textContent: "Default Value", + }), + $el("label"), + (this.rows = $el("div", { + style: { + display: "contents", + }, + })), + ] + ); + } + + createButtons() { + const btns = super.createButtons(); + btns[0].textContent = "Cancel"; + btns.unshift( + $el("button", { + type: "button", + textContent: "Add New", + onclick: () => this.addRow(), + }), + $el("button", { + type: "button", + textContent: "Save", + onclick: () => this.save(), + }) + ); + return btns; + } + + addRow(node = "", widget = "", value = "") { + let nameInput; + this.rows.append( + $el( + "div", + { + style: { + display: "contents", + }, + className: "pysssss-widget-defaults-row", + }, + [ + $el("input", { + placeholder: "e.g. CheckpointLoaderSimple", + value: node, + }), + $el("input", { + placeholder: "e.g. ckpt_name", + value: widget, + $: (el) => (nameInput = el), + }), + $el("input", { + placeholder: "e.g. myBestModel.safetensors", + value, + }), + $el("button", { + textContent: "Delete", + style: { + fontSize: "12px", + color: "red", + fontWeight: "normal", + }, + onclick: (e) => { + nameInput.value = ""; + e.target.parentElement.style.display = "none"; + }, + }), + ] + ) + ); + } + + save() { + const rows = this.rows.children; + const items = []; + + for (const row of rows) { + const inputs = row.querySelectorAll("input"); + const node = inputs[0].value.trim(); + const widget = inputs[1].value.trim(); + const value = inputs[2].value; + if (node && widget) { + items.push({ node, widget, value }); + } + } + + setting.value = JSON.stringify(items); + defaults = getDefaults(); + + this.close(); + } + + show() { + this.rows.replaceChildren(); + for (const nodeName in defaults) { + const node = defaults[nodeName]; + for (const widgetName in node) { + this.addRow(nodeName, widgetName, node[widgetName]); + } + } + + this.addRow(); + super.show(this.grid); + } + } + + setting = app.ui.settings.addSetting({ + id, + name: "🐍 Widget Defaults", + type: () => { + return $el("tr", [ + $el("td", [ + $el("label", { + for: id.replaceAll(".", "-"), + textContent: "🐍 Widget & Property Defaults:", + }), + ]), + $el("td", [ + $el("button", { + textContent: "Manage", + onclick: () => { + try { + // Try closing old settings window + if (typeof app.ui.settings.element?.close === "function") { + app.ui.settings.element.close(); + } + } catch (error) {} + try { + // Try closing new vue dialog + document.querySelector(".p-dialog-close-button").click(); + } catch (error) { + // Fallback to just hiding the element + app.ui.settings.element.style.display = "none"; + } + const dialog = new WidgetDefaultsDialog(); + dialog.show(); + }, + style: { + fontSize: "14px", + }, + }), + ]), + ]); + }, + }); + defaults = getDefaults(); + }, +}); diff --git a/comfyui-custom-scripts/web/js/workflowImage.js b/comfyui-custom-scripts/web/js/workflowImage.js new file mode 100644 index 0000000000000000000000000000000000000000..37c3ad06c6272c1a8b1cab264515285412cec0d2 --- /dev/null +++ b/comfyui-custom-scripts/web/js/workflowImage.js @@ -0,0 +1,640 @@ +import { app } from "../../../scripts/app.js"; +import { importA1111 } from "../../../scripts/pnginfo.js"; +import { ComfyWidgets } from "../../../scripts/widgets.js"; + +let getDrawTextConfig = null; +let fileInput; + +class WorkflowImage { + static accept = ""; + + getBounds() { + // Calculate the min max bounds for the nodes on the graph + const bounds = app.graph._nodes.reduce( + (p, n) => { + if (n.pos[0] < p[0]) p[0] = n.pos[0]; + if (n.pos[1] < p[1]) p[1] = n.pos[1]; + const bounds = n.getBounding(); + const r = n.pos[0] + bounds[2]; + const b = n.pos[1] + bounds[3]; + if (r > p[2]) p[2] = r; + if (b > p[3]) p[3] = b; + return p; + }, + [99999, 99999, -99999, -99999] + ); + + bounds[0] -= 100; + bounds[1] -= 100; + bounds[2] += 100; + bounds[3] += 100; + return bounds; + } + + saveState() { + this.state = { + scale: app.canvas.ds.scale, + width: app.canvas.canvas.width, + height: app.canvas.canvas.height, + offset: app.canvas.ds.offset, + transform: app.canvas.canvas.getContext("2d").getTransform(), // Save the original transformation matrix + }; + } + + restoreState() { + app.canvas.ds.scale = this.state.scale; + app.canvas.canvas.width = this.state.width; + app.canvas.canvas.height = this.state.height; + app.canvas.ds.offset = this.state.offset; + app.canvas.canvas.getContext("2d").setTransform(this.state.transform); // Reapply the original transformation matrix + } + + updateView(bounds) { + const scale = window.devicePixelRatio || 1; + app.canvas.ds.scale = 1; + app.canvas.canvas.width = (bounds[2] - bounds[0]) * scale; + app.canvas.canvas.height = (bounds[3] - bounds[1]) * scale; + app.canvas.ds.offset = [-bounds[0], -bounds[1]]; + app.canvas.canvas.getContext("2d").setTransform(scale, 0, 0, scale, 0, 0); + } + + getDrawTextConfig(_, widget) { + return { + x: 10, + y: widget.last_y + 10, + resetTransform: false, + }; + } + + async export(includeWorkflow) { + // Save the current state of the canvas + this.saveState(); + // Update to render the whole workflow + this.updateView(this.getBounds()); + + // Flag that we are saving and render the canvas + getDrawTextConfig = this.getDrawTextConfig; + app.canvas.draw(true, true); + getDrawTextConfig = null; + + // Generate a blob of the image containing the workflow + const blob = await this.getBlob(includeWorkflow ? JSON.stringify(app.graph.serialize()) : undefined); + + // Restore initial state and redraw + this.restoreState(); + app.canvas.draw(true, true); + + // Download the generated image + this.download(blob); + } + + download(blob) { + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + Object.assign(a, { + href: url, + download: "workflow." + this.extension, + style: "display: none", + }); + document.body.append(a); + a.click(); + setTimeout(function () { + a.remove(); + window.URL.revokeObjectURL(url); + }, 0); + } + + static import() { + if (!fileInput) { + fileInput = document.createElement("input"); + Object.assign(fileInput, { + type: "file", + style: "display: none", + onchange: () => { + app.handleFile(fileInput.files[0]); + }, + }); + document.body.append(fileInput); + } + fileInput.accept = WorkflowImage.accept; + fileInput.click(); + } +} + +class PngWorkflowImage extends WorkflowImage { + static accept = ".png,image/png"; + extension = "png"; + + n2b(n) { + return new Uint8Array([(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]); + } + + joinArrayBuffer(...bufs) { + const result = new Uint8Array(bufs.reduce((totalSize, buf) => totalSize + buf.byteLength, 0)); + bufs.reduce((offset, buf) => { + result.set(buf, offset); + return offset + buf.byteLength; + }, 0); + return result; + } + + crc32(data) { + const crcTable = + PngWorkflowImage.crcTable || + (PngWorkflowImage.crcTable = (() => { + let c; + const crcTable = []; + for (let n = 0; n < 256; n++) { + c = n; + for (let k = 0; k < 8; k++) { + c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + } + crcTable[n] = c; + } + return crcTable; + })()); + let crc = 0 ^ -1; + for (let i = 0; i < data.byteLength; i++) { + crc = (crc >>> 8) ^ crcTable[(crc ^ data[i]) & 0xff]; + } + return (crc ^ -1) >>> 0; + } + + async getBlob(workflow) { + return new Promise((r) => { + app.canvasEl.toBlob(async (blob) => { + if (workflow) { + // If we have a workflow embed it in the PNG + const buffer = await blob.arrayBuffer(); + const typedArr = new Uint8Array(buffer); + const view = new DataView(buffer); + + const data = new TextEncoder().encode(`tEXtworkflow\0${workflow}`); + const chunk = this.joinArrayBuffer(this.n2b(data.byteLength - 4), data, this.n2b(this.crc32(data))); + + const sz = view.getUint32(8) + 20; + const result = this.joinArrayBuffer(typedArr.subarray(0, sz), chunk, typedArr.subarray(sz)); + + blob = new Blob([result], { type: "image/png" }); + } + + r(blob); + }); + }); + } +} + +class DataReader { + /** @type {DataView} */ + view; + /** @type {boolean | undefined} */ + littleEndian; + offset = 0; + + /** + * @param {DataView} view + */ + constructor(view) { + this.view = view; + } + + /** + * Reads N bytes and increments the offset + * @param {1 | 2 | 4 | 8} size + */ + read(size, signed = false, littleEndian = undefined) { + const v = this.peek(size, signed, littleEndian); + this.offset += size; + return v; + } + + /** + * Reads N bytes + * @param {1 | 2 | 4 | 8} size + */ + peek(size, signed = false, littleEndian = undefined) { + this.view.getBigInt64; + let m = ""; + if (size === 8) m += "Big"; + m += signed ? "Int" : "Uint"; + m += size * 8; + m = "get" + m; + if (!this.view[m]) { + throw new Error("Method not found: " + m); + } + + return this.view[m](this.offset, littleEndian == null ? this.littleEndian : littleEndian); + } + + /** + * Seeks to the specified position or by the number of bytes specified relative to the current offset + * @param {number} pos + * @param {boolean} relative + */ + seek(pos, relative = true) { + if (relative) { + this.offset += pos; + } else { + this.offset = pos; + } + } +} + +class Tiff { + /** @type {DataReader} */ + #reader; + #start; + + readExif(reader) { + const TIFF_MARKER = 0x2a; + const EXIF_IFD = 0x8769; + + this.#reader = reader; + this.#start = this.#reader.offset; + this.#readEndianness(); + + if (!this.#reader.read(2) === TIFF_MARKER) { + throw new Error("Invalid TIFF: Marker not found."); + } + + const dirOffset = this.#reader.read(4); + this.#reader.seek(this.#start + dirOffset, false); + + for (const t of this.#readTags()) { + if (t.id === EXIF_IFD) { + return this.#readExifTag(t); + } + } + throw new Error("No EXIF: TIFF Exif IFD tag not found"); + } + + #readUserComment(tag) { + this.#reader.seek(this.#start + tag.offset, false); + const encoding = this.#reader.read(8); + if (encoding !== 0x45444f43494e55n) { + throw new Error("Unable to read non-Unicode data"); + } + const decoder = new TextDecoder("utf-16be"); + return decoder.decode(new DataView(this.#reader.view.buffer, this.#reader.offset, tag.count - 8)); + } + + #readExifTag(exifTag) { + const EXIF_USER_COMMENT = 0x9286; + + this.#reader.seek(this.#start + exifTag.offset, false); + for (const t of this.#readTags()) { + if (t.id === EXIF_USER_COMMENT) { + return this.#readUserComment(t); + } + } + throw new Error("No embedded data: UserComment Exif tag not found"); + } + + *#readTags() { + const count = this.#reader.read(2); + for (let i = 0; i < count; i++) { + yield { + id: this.#reader.read(2), + type: this.#reader.read(2), + count: this.#reader.read(4), + offset: this.#reader.read(4), + }; + } + } + + #readEndianness() { + const II = 0x4949; + const MM = 0x4d4d; + const endianness = this.#reader.read(2); + if (endianness === II) { + this.#reader.littleEndian = true; + } else if (endianness === MM) { + this.#reader.littleEndian = false; + } else { + throw new Error("Invalid JPEG: Endianness marker not found."); + } + } +} + +class Jpeg { + /** @type {DataReader} */ + #reader; + + /** + * @param {ArrayBuffer} buffer + */ + readExif(buffer) { + const JPEG_MARKER = 0xffd8; + const EXIF_SIG = 0x45786966; + + this.#reader = new DataReader(new DataView(buffer)); + if (!this.#reader.read(2) === JPEG_MARKER) { + throw new Error("Invalid JPEG: SOI not found."); + } + + const app0 = this.#readAppMarkerId(); + if (app0 !== 0) { + throw new Error(`Invalid JPEG: APP0 not found [found: ${app0}].`); + } + + this.#consumeAppSegment(); + const app1 = this.#readAppMarkerId(); + if (app1 !== 1) { + throw new Error(`No EXIF: APP1 not found [found: ${app0}].`); + } + + // Skip size + this.#reader.seek(2); + + if (this.#reader.read(4) !== EXIF_SIG) { + throw new Error(`No EXIF: Invalid EXIF header signature.`); + } + if (this.#reader.read(2) !== 0) { + throw new Error(`No EXIF: Invalid EXIF header.`); + } + + return new Tiff().readExif(this.#reader); + } + + #readAppMarkerId() { + const APP0_MARKER = 0xffe0; + return this.#reader.read(2) - APP0_MARKER; + } + + #consumeAppSegment() { + this.#reader.seek(this.#reader.read(2) - 2); + } +} + +class SvgWorkflowImage extends WorkflowImage { + static accept = ".svg,image/svg+xml"; + extension = "svg"; + + static init() { + // Override file handling to allow drag & drop of SVG + const handleFile = app.handleFile; + app.handleFile = async function (file) { + if (file && (file.type === "image/svg+xml" || file.name?.endsWith(".svg"))) { + const reader = new FileReader(); + reader.onload = () => { + // Extract embedded workflow from desc tags + const descEnd = reader.result.lastIndexOf(""); + if (descEnd !== -1) { + const descStart = reader.result.lastIndexOf("", descEnd); + if (descStart !== -1) { + const json = reader.result.substring(descStart + 6, descEnd); + this.loadGraphData(JSON.parse(SvgWorkflowImage.unescapeXml(json))); + } + } + }; + reader.readAsText(file); + return; + } else if (file && (file.type === "image/jpeg" || file.name?.endsWith(".jpg") || file.name?.endsWith(".jpeg"))) { + if ( + await new Promise((resolve) => { + try { + // This shouldnt go in here but it's easier than refactoring handleFile + const reader = new FileReader(); + reader.onload = async () => { + try { + const value = new Jpeg().readExif(reader.result); + importA1111(app.graph, value); + resolve(true); + } catch (error) { + resolve(false); + } + }; + reader.onerror = () => resolve(false); + reader.readAsArrayBuffer(file); + } catch (error) { + resolve(false); + } + }) + ) { + return; + } + } + return handleFile.apply(this, arguments); + }; + } + + static escapeXml(unsafe) { + return unsafe.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">"); + } + + static unescapeXml(safe) { + return safe.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">"); + } + + getDrawTextConfig(_, widget) { + const domWrapper = widget.inputEl.closest(".dom-widget") ?? widget.inputEl; + return { + x: parseInt(domWrapper.style.left), + y: parseInt(domWrapper.style.top), + resetTransform: true, + }; + } + + saveState() { + super.saveState(); + this.state.ctx = app.canvas.ctx; + } + + restoreState() { + super.restoreState(); + app.canvas.ctx = this.state.ctx; + } + + updateView(bounds) { + super.updateView(bounds); + this.createSvgCtx(bounds); + } + + createSvgCtx(bounds) { + const ctx = this.state.ctx; + const svgCtx = (this.svgCtx = new C2S(bounds[2] - bounds[0], bounds[3] - bounds[1])); + svgCtx.canvas.getBoundingClientRect = function () { + return { width: svgCtx.width, height: svgCtx.height }; + }; + + // Override the c2s handling of images to draw images as canvases + const drawImage = svgCtx.drawImage; + svgCtx.drawImage = function (...args) { + const image = args[0]; + // If we are an image node and not a datauri then we need to replace with a canvas + // we cant convert to data uri here as it is an async process + if (image.nodeName === "IMG" && !image.src.startsWith("data:image/")) { + const canvas = document.createElement("canvas"); + canvas.width = image.width; + canvas.height = image.height; + const imgCtx = canvas.getContext("2d"); + imgCtx.drawImage(image, 0, 0); + args[0] = canvas; + } + + return drawImage.apply(this, args); + }; + + // Implement missing required functions + svgCtx.getTransform = function () { + return ctx.getTransform(); + }; + svgCtx.resetTransform = function () { + return ctx.resetTransform(); + }; + svgCtx.roundRect = svgCtx.rect; + app.canvas.ctx = svgCtx; + } + + getBlob(workflow) { + let svg = this.svgCtx.getSerializedSvg(true).replace("", `${SvgWorkflowImage.escapeXml(workflow)}`); + } + + return new Blob([svg], { type: "image/svg+xml" }); + } +} + +app.registerExtension({ + name: "pysssss.WorkflowImage", + init() { + // https://codepen.io/peterhry/pen/nbMaYg + function wrapText(context, text, x, y, maxWidth, lineHeight) { + var words = text.split(" "), + line = "", + i, + test, + metrics; + + for (i = 0; i < words.length; i++) { + test = words[i]; + metrics = context.measureText(test); + while (metrics.width > maxWidth) { + // Determine how much of the word will fit + test = test.substring(0, test.length - 1); + metrics = context.measureText(test); + } + if (words[i] != test) { + words.splice(i + 1, 0, words[i].substr(test.length)); + words[i] = test; + } + + test = line + words[i] + " "; + metrics = context.measureText(test); + + if (metrics.width > maxWidth && i > 0) { + context.fillText(line, x, y); + line = words[i] + " "; + y += lineHeight; + } else { + line = test; + } + } + + context.fillText(line, x, y); + } + + const stringWidget = ComfyWidgets.STRING; + // Override multiline string widgets to draw text using canvas while saving as svg + ComfyWidgets.STRING = function () { + const w = stringWidget.apply(this, arguments); + if (w.widget && w.widget.type === "customtext") { + const draw = w.widget.draw; + w.widget.draw = function (ctx) { + draw.apply(this, arguments); + if (this.inputEl.hidden) return; + + if (getDrawTextConfig) { + const config = getDrawTextConfig(ctx, this); + const t = ctx.getTransform(); + ctx.save(); + if (config.resetTransform) { + ctx.resetTransform(); + } + + const style = document.defaultView.getComputedStyle(this.inputEl, null); + const x = config.x; + const y = config.y; + const domWrapper = this.inputEl.closest(".dom-widget") ?? widget.inputEl; + let w = parseInt(domWrapper.style.width); + if (w === 0) { + w = this.node.size[0] - 20; + } + const h = parseInt(domWrapper.style.height); + ctx.fillStyle = style.getPropertyValue("background-color"); + ctx.fillRect(x, y, w, h); + + ctx.fillStyle = style.getPropertyValue("color"); + ctx.font = style.getPropertyValue("font"); + + const line = t.d * 12; + const split = this.inputEl.value.split("\n"); + let start = y; + for (const l of split) { + start += line; + wrapText(ctx, l, x + 4, start, w, line); + } + + ctx.restore(); + } + }; + } + return w; + }; + }, + setup() { + const script = document.createElement("script"); + script.onload = function () { + const formats = [SvgWorkflowImage, PngWorkflowImage]; + for (const f of formats) { + f.init?.call(); + WorkflowImage.accept += (WorkflowImage.accept ? "," : "") + f.accept; + } + + // Add canvas menu options + const orig = LGraphCanvas.prototype.getCanvasMenuOptions; + LGraphCanvas.prototype.getCanvasMenuOptions = function () { + const options = orig.apply(this, arguments); + + options.push(null, { + content: "Workflow Image", + submenu: { + options: [ + { + content: "Import", + callback: () => { + WorkflowImage.import(); + }, + }, + { + content: "Export", + submenu: { + options: formats.flatMap((f) => [ + { + content: f.name.replace("WorkflowImage", "").toLocaleLowerCase(), + callback: () => { + new f().export(true); + }, + }, + { + content: f.name.replace("WorkflowImage", "").toLocaleLowerCase() + " (no embedded workflow)", + callback: () => { + new f().export(); + }, + }, + ]), + }, + }, + ], + }, + }); + return options; + }; + }; + + script.src = new URL(`assets/canvas2svg.js`, import.meta.url); + document.body.append(script); + }, +}); diff --git a/comfyui-custom-scripts/web/js/workflows.js b/comfyui-custom-scripts/web/js/workflows.js new file mode 100644 index 0000000000000000000000000000000000000000..0225260ae7cc6b420c272ab3f54e389910a93815 --- /dev/null +++ b/comfyui-custom-scripts/web/js/workflows.js @@ -0,0 +1,343 @@ +import { app } from "../../../scripts/app.js"; +import { api } from "../../../scripts/api.js"; +import { $el } from "../../../scripts/ui.js"; + +// Adds workflow management +// Original implementation by https://github.com/i-h4x +// Thanks for permission to reimplement as an extension + +const style = ` +#comfy-save-button, #comfy-load-button { + position: relative; + overflow: hidden; +} +.pysssss-workflow-arrow { + position: absolute; + top: 0; + bottom: 0; + right: 0; + font-size: 12px; + display: flex; + align-items: center; + width: 24px; + justify-content: center; + background: rgba(255,255,255,0.1); +} +.pysssss-workflow-arrow:after { + content: "▼"; +} +.pysssss-workflow-arrow:hover { + filter: brightness(1.6); + background-color: var(--comfy-menu-bg); +} +.pysssss-workflow-load .litemenu-entry:not(.has_submenu):before, +.pysssss-workflow-load ~ .litecontextmenu .litemenu-entry:not(.has_submenu):before { + content: "🎛️"; + padding-right: 5px; +} +.pysssss-workflow-load .litemenu-entry.has_submenu:before, +.pysssss-workflow-load ~ .litecontextmenu .litemenu-entry.has_submenu:before { + content: "📂"; + padding-right: 5px; + position: relative; + top: -1px; +} +.pysssss-workflow-popup ~ .litecontextmenu { + transform: scale(1.3); +} +`; + +async function getWorkflows() { + const response = await api.fetchApi("/pysssss/workflows", { cache: "no-store" }); + return await response.json(); +} + +async function getWorkflow(name) { + const response = await api.fetchApi(`/pysssss/workflows/${encodeURIComponent(name)}`, { cache: "no-store" }); + return await response.json(); +} + +async function saveWorkflow(name, workflow, overwrite) { + try { + const response = await api.fetchApi("/pysssss/workflows", { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ name, workflow, overwrite }), + }); + if (response.status === 201) { + return true; + } + if (response.status === 409) { + return false; + } + throw new Error(response.statusText); + } catch (error) { + console.error(error); + } +} + +class PysssssWorkflows { + async load() { + this.workflows = await getWorkflows(); + if(this.workflows.length) { + this.workflows.sort(); + } + this.loadMenu.style.display = this.workflows.length ? "flex" : "none"; + } + + getMenuOptions(callback) { + const menu = []; + const directories = new Map(); + for (const workflow of this.workflows || []) { + const path = workflow.split("/"); + let parent = menu; + let currentPath = ""; + for (let i = 0; i < path.length - 1; i++) { + currentPath += "/" + path[i]; + let newParent = directories.get(currentPath); + if (!newParent) { + newParent = { + title: path[i], + has_submenu: true, + submenu: { + options: [], + }, + }; + parent.push(newParent); + newParent = newParent.submenu.options; + directories.set(currentPath, newParent); + } + parent = newParent; + } + parent.push({ + title: path[path.length - 1], + callback: () => callback(workflow), + }); + } + return menu; + } + + constructor() { + function addWorkflowMenu(type, getOptions) { + return $el("div.pysssss-workflow-arrow", { + parent: document.getElementById(`comfy-${type}-button`), + onclick: (e) => { + e.preventDefault(); + e.stopPropagation(); + + LiteGraph.closeAllContextMenus(); + const menu = new LiteGraph.ContextMenu( + getOptions(), + { + event: e, + scale: 1.3, + }, + window + ); + menu.root.classList.add("pysssss-workflow-popup"); + menu.root.classList.add(`pysssss-workflow-${type}`); + }, + }); + } + + this.loadMenu = addWorkflowMenu("load", () => + this.getMenuOptions(async (workflow) => { + const json = await getWorkflow(workflow); + app.loadGraphData(json); + }) + ); + addWorkflowMenu("save", () => { + return [ + { + title: "Save as", + callback: () => { + let filename = prompt("Enter filename", this.workflowName || "workflow"); + if (filename) { + if (!filename.toLowerCase().endsWith(".json")) { + filename += ".json"; + } + + this.workflowName = filename; + + const json = JSON.stringify(app.graph.serialize(), null, 2); // convert the data to a JSON string + const blob = new Blob([json], { type: "application/json" }); + const url = URL.createObjectURL(blob); + const a = $el("a", { + href: url, + download: filename, + style: { display: "none" }, + parent: document.body, + }); + a.click(); + setTimeout(function () { + a.remove(); + window.URL.revokeObjectURL(url); + }, 0); + } + }, + }, + { + title: "Save to workflows", + callback: async () => { + const name = prompt("Enter filename", this.workflowName || "workflow"); + if (name) { + this.workflowName = name; + + const data = app.graph.serialize(); + if (!(await saveWorkflow(name, data))) { + if (confirm("A workspace with this name already exists, do you want to overwrite it?")) { + await saveWorkflow(name, app.graph.serialize(), true); + } else { + return; + } + } + await this.load(); + } + }, + }, + ]; + }); + this.load(); + + const handleFile = app.handleFile; + const self = this; + app.handleFile = function (file) { + if (file?.name?.endsWith(".json")) { + self.workflowName = file.name; + } else { + self.workflowName = null; + } + return handleFile.apply(this, arguments); + }; + } +} + +const refreshComboInNodes = app.refreshComboInNodes; +let workflows; + +async function sendToWorkflow(img, workflow) { + const graph = !workflow ? app.graph.serialize() : await getWorkflow(workflow); + const nodes = graph.nodes.filter((n) => n.type === "LoadImage"); + let targetNode; + if (nodes.length === 0) { + alert("To send the image to another workflow, that workflow must have a LoadImage node."); + return; + } else if (nodes.length > 1) { + targetNode = nodes.find((n) => n.title?.toLowerCase().includes("input")); + if (!targetNode) { + targetNode = nodes[0]; + alert( + "The target workflow has multiple LoadImage nodes, include 'input' in the name of the one you want to use. The first one will be used here." + ); + } + } else { + targetNode = nodes[0]; + } + + const blob = await (await fetch(img.src)).blob(); + const name = + (workflow || "sendtoworkflow").replace(/\//g, "_") + + "-" + + +new Date() + + new URLSearchParams(img.src.split("?")[1]).get("filename"); + const body = new FormData(); + body.append("image", new File([blob], name)); + + const resp = await api.fetchApi("/upload/image", { + method: "POST", + body, + }); + + if (resp.status === 200) { + await refreshComboInNodes.call(app); + targetNode.widgets_values[0] = name; + app.loadGraphData(graph); + app.graph.getNodeById(targetNode.id); + } else { + alert(resp.status + " - " + resp.statusText); + } +} + +app.registerExtension({ + name: "pysssss.Workflows", + init() { + $el("style", { + textContent: style, + parent: document.head, + }); + }, + + async refreshComboInNodes() { + workflows.load() + }, + + async setup() { + workflows = new PysssssWorkflows(); + + const comfyDefault = "[ComfyUI Default]"; + const defaultWorkflow = app.ui.settings.addSetting({ + id: "pysssss.Workflows.Default", + name: "🐍 Default Workflow", + defaultValue: comfyDefault, + type: "combo", + options: (value) => + [comfyDefault, ...workflows.workflows].map((m) => ({ + value: m, + text: m, + selected: m === value, + })), + }); + + document.getElementById("comfy-load-default-button").onclick = async function () { + if ( + localStorage["Comfy.Settings.Comfy.ConfirmClear"] === "false" || + confirm(`Load default workflow (${defaultWorkflow.value})?`) + ) { + if (defaultWorkflow.value === comfyDefault) { + app.loadGraphData(); + } else { + const json = await getWorkflow(defaultWorkflow.value); + app.loadGraphData(json); + } + } + }; + }, + async beforeRegisterNodeDef(nodeType, nodeData, app) { + const getExtraMenuOptions = nodeType.prototype.getExtraMenuOptions; + nodeType.prototype.getExtraMenuOptions = function (_, options) { + const r = getExtraMenuOptions?.apply?.(this, arguments); + let img; + if (this.imageIndex != null) { + // An image is selected so select that + img = this.imgs[this.imageIndex]; + } else if (this.overIndex != null) { + // No image is selected but one is hovered + img = this.imgs[this.overIndex]; + } + + if (img) { + let pos = options.findIndex((o) => o.content === "Save Image"); + if (pos === -1) { + pos = 0; + } else { + pos++; + } + + options.splice(pos, 0, { + content: "Send to workflow", + has_submenu: true, + submenu: { + options: [ + { callback: () => sendToWorkflow(img), title: "[Current workflow]" }, + ...workflows.getMenuOptions(sendToWorkflow.bind(null, img)), + ], + }, + }); + } + + return r; + }; + }, +});