Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- ComfyLiterals/js/operation-node.jsAdded+83
- ComfyUI-Crystools/docs/menu.pngAdded
- ComfyUI-Crystools/docs/monitor-settings.pngAdded
- ComfyUI-Crystools/docs/monitor.pngAdded
- ComfyUI-Crystools/docs/primitives.pngAdded
- ComfyUI-Crystools/docs/progress-bar.pngAdded
- ComfyUI-Crystools/docs/screwdriver.pngAdded
- ComfyUI-Crystools/docs/shortcut.pngAdded
- ComfyUI-Crystools/docs/switches.pngAdded
- ComfyUI-Crystools/general/__init__.pyAdded+3
- ComfyUI-Crystools/general/__pycache__/__init__.cpython-310.pycAdded
- ComfyUI-Crystools/general/__pycache__/gpu.cpython-310.pycAdded
- ComfyUI-Crystools/general/__pycache__/hardware.cpython-310.pycAdded
- ComfyUI-Crystools/general/__pycache__/hdd.cpython-310.pycAdded
- ComfyUI-Crystools/general/__pycache__/monitor.cpython-310.pycAdded
- ComfyUI-Crystools/general/gpu.pyAdded+300
- ComfyUI-Crystools/general/hardware.pyAdded+132
- ComfyUI-Crystools/general/hdd.pyAdded+10
- ComfyUI-Crystools/general/monitor.pyAdded+67
- ComfyUI-Crystools/nodes/__init__.pyAdded+1
- ComfyUI-Crystools/nodes/__pycache__/debugger.cpython-310.pycAdded
- ComfyUI-Crystools/nodes/__pycache__/image.cpython-310.pycAdded
- ComfyUI-Crystools/nodes/__pycache__/list.cpython-310.pycAdded
- ComfyUI-Crystools/nodes/__pycache__/metadata.cpython-310.pycAdded
- ComfyUI-Crystools/nodes/__pycache__/parameters.cpython-310.pycAdded
- ComfyUI-Crystools/nodes/__pycache__/pipe.cpython-310.pycAdded
- ComfyUI-Crystools/nodes/__pycache__/primitive.cpython-310.pycAdded
- ComfyUI-Crystools/nodes/__pycache__/utils.cpython-310.pycAdded
- ComfyUI-Crystools/nodes/_names.pyAdded+80
- ComfyUI-Crystools/nodes/debugger.pyAdded+123
- ComfyUI-Crystools/nodes/image.pyAdded+517
- ComfyUI-Crystools/nodes/list.pyAdded+149
- ComfyUI-Crystools/nodes/metadata.pyAdded+164
- ComfyUI-Crystools/nodes/parameters.pyAdded+170
- ComfyUI-Crystools/nodes/pipe.pyAdded+74
- ComfyUI-Crystools/nodes/primitive.pyAdded+111
- ComfyUI-Crystools/nodes/utils.pyAdded+55
- comfyui-art-venture/.github/workflows/publish.ymlAdded+25
- comfyui-art-venture/.trackingAdded+69
- comfyui-art-venture/README.mdAdded+217
- comfyui-art-venture/__init__.pyAdded+17
- comfyui-art-venture/config.pyAdded+68
- comfyui-art-venture/modules/animatediff/__init__.pyAdded+89
- comfyui-art-venture/modules/animatediff/__pycache__/__init__.cpython-310.pycAdded
- comfyui-art-venture/modules/controlnet/__init__.pyAdded+337
- comfyui-art-venture/modules/controlnet/__pycache__/__init__.cpython-310.pycAdded
- comfyui-art-venture/modules/controlnet/__pycache__/advanced.cpython-310.pycAdded
- comfyui-art-venture/modules/controlnet/__pycache__/preprocessor.cpython-310.pycAdded
- comfyui-art-venture/modules/controlnet/advanced.pyAdded+44
- comfyui-art-venture/modules/controlnet/preprocessor.pyAdded+106
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283import {app} from "/scripts/app.js";
app.registerExtension({
name: "ComfyLiterals.OperationNode",
nodeCreated(node, app) {
if (node['comfyClass'] === 'Operation') {
const onAdded = node.onAdded
node.onAdded = function (graph) {
console.log("OperationNode onAdded")
const firstCallbackResp = onAdded ? onAdded.apply(this, arguments) : undefined;
/**
* @type {Record<string, INodeInputSlot>}
*/
const inputCache = {
"A": node.inputs[1],
"B": node.inputs[3]
}
if (this.widgets_values) {
const aType = this.widgets_values[0]
const bType = this.widgets_values[1]
// [IntA, FloatA, IntB, FloatB]
const aIdxToDelete = aType === "INT" ? 1 : 0
// [*A, IntB, FloatB]
const bIdxToDelete = bType === "INT" ? 3 : 1
inputCache["A"] = node.inputs[aIdxToDelete]
this.removeInput(aIdxToDelete)
inputCache["B"] = node.inputs[bIdxToDelete]
this.removeInput(bIdxToDelete)
} else {
// Nodes being restored/pasted don't have widget_values
// Node has 4 inputs(IntA, FloatA, IntB, FloatB)
// Remove both float inputs, Float B moves to index 2 after Float A is removed
this.removeInput(1)
this.removeInput(2)
}
// Add a toggle widget to the node
this.widgets[0].callback = function (v, canvas, node) {
addInputAtIndex(node, inputCache["A"], 0)
inputCache["A"] = node.inputs[1]
node.removeInput(1)
}
this.widgets[1].callback = function (v, canvas, node) {
addInputAtIndex(node, inputCache["B"], 2)
inputCache["B"] = node.inputs[1]
node.removeInput(1)
}
}
}
}
})
/**
* Adds an input to a node at the given index.
* @param node {LGraphNode}
* @param input {INodeInputSlot}
* @param index {number}
* @returns {INodeInputSlot}
*/
function addInputAtIndex(node, input, index) {
if (!node.inputs) {
node.inputs = [];
}
if (index > node.inputs.length) {
console.warn("LiteGraph: Warning adding port index: " + index + " of node " + node.id + ", it doesnt have so many inputs");
node.inputs.push(input);
} else {
node.inputs.splice(index, 0, input);
}
if (node.onInputAdded) {
node.onInputAdded(input);
}
node.setSize(node.computeSize());
LiteGraph.registerNodeAndSlotType(node, input.type || 0);
node.setDirtyCanvas(true, true);
return input;
}123from .monitor import *
from .hdd import *
from .gpu import *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300import torch
import comfy.model_management
from ..core import logger
import os
import platform
def is_jetson() -> bool:
"""
Determines if the Python environment is running on a Jetson device by checking the device model
information or the platform release.
"""
PROC_DEVICE_MODEL = ''
try:
with open('/proc/device-tree/model', 'r') as f:
PROC_DEVICE_MODEL = f.read().strip()
logger.info(f"Device model: {PROC_DEVICE_MODEL}")
return "NVIDIA" in PROC_DEVICE_MODEL
except Exception as e:
# logger.warning(f"JETSON: Could not read /proc/device-tree/model: {e} (If you're not using Jetson, ignore this warning)")
# If /proc/device-tree/model is not available, check platform.release()
platform_release = platform.release()
logger.info(f"Platform release: {platform_release}")
if 'tegra' in platform_release.lower():
logger.info("Detected 'tegra' in platform release. Assuming Jetson device.")
return True
else:
logger.info("JETSON: Not detected.")
return False
IS_JETSON = is_jetson()
class CGPUInfo:
"""
This class is responsible for getting information from GPU (ONLY).
"""
cuda = False
pynvmlLoaded = False
jtopLoaded = False
cudaAvailable = False
torchDevice = 'cpu'
cudaDevice = 'cpu'
cudaDevicesFound = 0
switchGPU = True
switchVRAM = True
switchTemperature = True
gpus = []
gpusUtilization = []
gpusVRAM = []
gpusTemperature = []
def __init__(self):
if IS_JETSON:
# Try to import jtop for Jetson devices
try:
from jtop import jtop
self.jtopInstance = jtop()
self.jtopInstance.start()
self.jtopLoaded = True
logger.info('jtop initialized on Jetson device.')
except ImportError as e:
logger.error('jtop is not installed. ' + str(e))
except Exception as e:
logger.error('Could not initialize jtop. ' + str(e))
else:
# Try to import pynvml for non-Jetson devices
try:
import pynvml
self.pynvml = pynvml
self.pynvml.nvmlInit()
self.pynvmlLoaded = True
logger.info('pynvml (NVIDIA) initialized.')
except ImportError as e:
logger.error('pynvml is not installed. ' + str(e))
except Exception as e:
logger.error('Could not init pynvml (NVIDIA). ' + str(e))
self.anygpuLoaded = self.pynvmlLoaded or self.jtopLoaded
try:
self.torchDevice = comfy.model_management.get_torch_device_name(comfy.model_management.get_torch_device())
except Exception as e:
logger.error('Could not pick default device. ' + str(e))
if self.pynvmlLoaded and not self.jtopLoaded and not self.deviceGetCount():
logger.warning('No GPU detected, disabling GPU monitoring.')
self.anygpuLoaded = False
self.pynvmlLoaded = False
self.jtopLoaded = False
if self.anygpuLoaded:
if self.deviceGetCount() > 0:
self.cudaDevicesFound = self.deviceGetCount()
logger.info(f"GPU/s:")
for deviceIndex in range(self.cudaDevicesFound):
deviceHandle = self.deviceGetHandleByIndex(deviceIndex)
gpuName = self.deviceGetName(deviceHandle, deviceIndex)
logger.info(f"{deviceIndex}) {gpuName}")
self.gpus.append({
'index': deviceIndex,
'name': gpuName,
})
# Same index as gpus, with default values
self.gpusUtilization.append(True)
self.gpusVRAM.append(True)
self.gpusTemperature.append(True)
self.cuda = True
logger.info(self.systemGetDriverVersion())
else:
logger.warning('No GPU with CUDA detected.')
else:
logger.warning('No GPU monitoring libraries available.')
self.cudaDevice = 'cpu' if self.torchDevice == 'cpu' else 'cuda'
self.cudaAvailable = torch.cuda.is_available()
if self.cuda and self.cudaAvailable and self.torchDevice == 'cpu':
logger.warning('CUDA is available, but torch is using CPU.')
def getInfo(self):
logger.debug('Getting GPUs info...')
return self.gpus
def getStatus(self):
gpuUtilization = -1
gpuTemperature = -1
vramUsed = -1
vramTotal = -1
vramPercent = -1
gpuType = ''
gpus = []
if self.cudaDevice == 'cpu':
gpuType = 'cpu'
gpus.append({
'gpu_utilization': -1,
'gpu_temperature': -1,
'vram_total': -1,
'vram_used': -1,
'vram_used_percent': -1,
})
else:
gpuType = self.cudaDevice
if self.anygpuLoaded and self.cuda and self.cudaAvailable:
for deviceIndex in range(self.cudaDevicesFound):
deviceHandle = self.deviceGetHandleByIndex(deviceIndex)
gpuUtilization = -1
vramPercent = -1
vramUsed = -1
vramTotal = -1
gpuTemperature = -1
# GPU Utilization
if self.switchGPU and self.gpusUtilization[deviceIndex]:
try:
gpuUtilization = self.deviceGetUtilizationRates(deviceHandle)
except Exception as e:
logger.error('Could not get GPU utilization. ' + str(e))
logger.error('Monitor of GPU is turning off.')
self.switchGPU = False
if self.switchVRAM and self.gpusVRAM[deviceIndex]:
try:
memory = self.deviceGetMemoryInfo(deviceHandle)
vramUsed = memory['used']
vramTotal = memory['total']
# Check if vramTotal is not zero or None
if vramTotal and vramTotal != 0:
vramPercent = vramUsed / vramTotal * 100
except Exception as e:
logger.error('Could not get GPU memory info. ' + str(e))
self.switchVRAM = False
# Temperature
if self.switchTemperature and self.gpusTemperature[deviceIndex]:
try:
gpuTemperature = self.deviceGetTemperature(deviceHandle)
except Exception as e:
logger.error('Could not get GPU temperature. Turning off this feature. ' + str(e))
self.switchTemperature = False
gpus.append({
'gpu_utilization': gpuUtilization,
'gpu_temperature': gpuTemperature,
'vram_total': vramTotal,
'vram_used': vramUsed,
'vram_used_percent': vramPercent,
})
return {
'device_type': gpuType,
'gpus': gpus,
}
def deviceGetCount(self):
if self.pynvmlLoaded:
return self.pynvml.nvmlDeviceGetCount()
elif self.jtopLoaded:
# For Jetson devices, we assume there's one GPU
return 1
else:
return 0
def deviceGetHandleByIndex(self, index):
if self.pynvmlLoaded:
return self.pynvml.nvmlDeviceGetHandleByIndex(index)
elif self.jtopLoaded:
return index # On Jetson, index acts as handle
else:
return 0
def deviceGetName(self, deviceHandle, deviceIndex):
if self.pynvmlLoaded:
gpuName = 'Unknown GPU'
try:
gpuName = self.pynvml.nvmlDeviceGetName(deviceHandle)
try:
gpuName = gpuName.decode('utf-8', errors='ignore')
except AttributeError:
pass
except UnicodeDecodeError as e:
gpuName = 'Unknown GPU (decoding error)'
logger.error(f"UnicodeDecodeError: {e}")
return gpuName
elif self.jtopLoaded:
# Access the GPU name from self.jtopInstance.gpu
try:
gpu_info = self.jtopInstance.gpu
gpu_name = next(iter(gpu_info.keys()))
return gpu_name
except Exception as e:
logger.error('Could not get GPU name. ' + str(e))
return 'Unknown GPU'
else:
return ''
def systemGetDriverVersion(self):
if self.pynvmlLoaded:
return f'NVIDIA Driver: {self.pynvml.nvmlSystemGetDriverVersion()}'
elif self.jtopLoaded:
# No direct method to get driver version from jtop
return 'NVIDIA Driver: unknown'
else:
return 'Driver unknown'
def deviceGetUtilizationRates(self, deviceHandle):
if self.pynvmlLoaded:
return self.pynvml.nvmlDeviceGetUtilizationRates(deviceHandle).gpu
elif self.jtopLoaded:
# GPU utilization from jtop stats
try:
gpu_util = self.jtopInstance.stats.get('GPU', -1)
return gpu_util
except Exception as e:
logger.error('Could not get GPU utilization. ' + str(e))
return -1
else:
return 0
def deviceGetMemoryInfo(self, deviceHandle):
if self.pynvmlLoaded:
mem = self.pynvml.nvmlDeviceGetMemoryInfo(deviceHandle)
return {'total': mem.total, 'used': mem.used}
elif self.jtopLoaded:
mem_data = self.jtopInstance.memory['RAM']
total = mem_data['tot']
used = mem_data['used']
return {'total': total, 'used': used}
else:
return {'total': 1, 'used': 1}
def deviceGetTemperature(self, deviceHandle):
if self.pynvmlLoaded:
return self.pynvml.nvmlDeviceGetTemperature(deviceHandle, self.pynvml.NVML_TEMPERATURE_GPU)
elif self.jtopLoaded:
try:
temperature = self.jtopInstance.stats.get('Temp gpu', -1)
return temperature
except Exception as e:
logger.error('Could not get GPU temperature. ' + str(e))
return -1
else:
return 0
def close(self):
if self.jtopLoaded and self.jtopInstance is not None:
self.jtopInstance.close()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132import platform
import re
import cpuinfo
from cpuinfo import DataSource
import psutil
from .gpu import CGPUInfo
from .hdd import getDrivesInfo
from ..core import logger
class CHardwareInfo:
"""
This is only class to get information from hardware.
Specially for share it to other software.
"""
switchCPU = False
switchHDD = False
switchRAM = False
whichHDD = '/' # breaks linux
@property
def switchGPU(self):
return self.GPUInfo.switchGPU
@switchGPU.setter
def switchGPU(self, value):
self.GPUInfo.switchGPU = value
@property
def switchVRAM(self):
return self.GPUInfo.switchVRAM
@switchVRAM.setter
def switchVRAM(self, value):
self.GPUInfo.switchVRAM = value
def __init__(self, switchCPU=False, switchGPU=False, switchHDD=False, switchRAM=False, switchVRAM=False):
self.switchCPU = switchCPU
self.switchHDD = switchHDD
self.switchRAM = switchRAM
self.print_sys_info()
self.GPUInfo = CGPUInfo()
self.switchGPU = switchGPU
self.switchVRAM = switchVRAM
def print_sys_info(self):
brand = None
if DataSource.is_windows: # Windows
brand = DataSource.winreg_processor_brand().strip()
elif DataSource.has_proc_cpuinfo(): # Linux
return_code, output = DataSource.cat_proc_cpuinfo()
if return_code == 0 and output is not None:
for line in output.splitlines():
r = re.search(r'model name\s*:\s*(.+)', line)
if r:
brand = r.group(1)
break
elif DataSource.has_sysctl(): # macOS
return_code, output = DataSource.sysctl_machdep_cpu_hw_cpufrequency()
if return_code == 0 and output is not None:
for line in output.splitlines():
r = re.search(r'machdep\.cpu\.brand_string\s*:\s*(.+)', line)
if r:
brand = r.group(1)
break
# fallback to use cpuinfo.get_cpu_info()
if not brand:
brand = cpuinfo.get_cpu_info().get('brand_raw', "Unknown")
arch_string_raw = 'Arch unknown'
try:
arch_string_raw = DataSource.arch_string_raw
except:
pass
specName = 'CPU: ' + brand
specArch = 'Arch: ' + arch_string_raw
specOs = 'OS: ' + str(platform.system()) + ' ' + str(platform.release())
logger.info(f"{specName} - {specArch} - {specOs}")
def getHDDsInfo(self):
return getDrivesInfo()
def getGPUInfo(self):
return self.GPUInfo.getInfo()
def getStatus(self):
cpu = -1
ramTotal = -1
ramUsed = -1
ramUsedPercent = -1
hddTotal = -1
hddUsed = -1
hddUsedPercent = -1
if self.switchCPU:
cpu = psutil.cpu_percent()
if self.switchRAM:
ram = psutil.virtual_memory()
ramTotal = ram.total
ramUsed = ram.used
ramUsedPercent = ram.percent
if self.switchHDD:
try:
hdd = psutil.disk_usage(self.whichHDD)
hddTotal = hdd.total
hddUsed = hdd.used
hddUsedPercent = hdd.percent
except Exception as e:
logger.error(f"Error getting disk usage for {self.whichHDD}: {e}")
hddTotal = -1
hddUsed = -1
hddUsedPercent = -1
getStatus = self.GPUInfo.getStatus()
return {
'cpu_utilization': cpu,
'ram_total': ramTotal,
'ram_used': ramUsed,
'ram_used_percent': ramUsedPercent,
'hdd_total': hddTotal,
'hdd_used': hddUsed,
'hdd_used_percent': hddUsedPercent,
'device_type': getStatus['device_type'],
'gpus': getStatus['gpus'],
}12345678910import psutil
from ..core import logger
def getDrivesInfo():
hdds = []
logger.debug('Getting HDDs info...')
for partition in psutil.disk_partitions():
hdds.append(partition.mountpoint)
return hdds12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import asyncio
import server
import time
import threading
from .hardware import CHardwareInfo
from ..core import logger
lock = threading.Lock()
class CMonitor:
monitorThread = None
threadController = threading.Event()
rate = 0
hardwareInfo = None
def __init__(self, rate=5, switchCPU=False, switchGPU=False, switchHDD=False, switchRAM=False, switchVRAM=False):
self.rate = rate
self.hardwareInfo = CHardwareInfo(switchCPU, switchGPU, switchHDD, switchRAM, switchVRAM)
self.startMonitor()
async def send_message(self, data) -> None:
# I'm not sure if it is ok, but works ¯\_(ツ)_/¯
# I tried to use async with send_json, but eventually that don't send the message
server.PromptServer.instance.send_sync('crystools.monitor', data)
def startMonitorLoop(self):
# logger.debug('Starting monitor loop...')
asyncio.run(self.MonitorLoop())
async def MonitorLoop(self):
while self.rate > 0 and not self.threadController.is_set():
data = self.hardwareInfo.getStatus()
# logger.debug('data to send' + str(data))
await self.send_message(data)
await asyncio.sleep(self.rate)
def startMonitor(self):
if self.monitorThread is not None:
self.stopMonitor()
logger.debug('Restarting monitor...')
else:
if self.rate == 0:
logger.debug('Monitor rate is 0, not starting monitor.')
return None
logger.debug('Starting monitor...')
self.threadController.clear()
if self.monitorThread is None or not self.monitorThread.is_alive():
lock.acquire()
self.monitorThread = threading.Thread(target=self.startMonitorLoop)
lock.release()
self.monitorThread.daemon = True
self.monitorThread.start()
def stopMonitor(self):
logger.debug('Stopping monitor...')
self.threadController.set()
cmonitor = CMonitor(1, True, True, True, True, True)
1# intentionally left blank1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980from enum import Enum
prefix = '🪛 '
# IMPORTANT DON'T CHANGE THE 'NAME' AND 'TYPE' OF THE ENUMS, IT WILL BREAK THE COMPATIBILITY!
# remember: NAME is for search, DESC is for contextual
class CLASSES(Enum):
CBOOLEAN_NAME = 'Primitive boolean [Crystools]'
CBOOLEAN_DESC = prefix + 'Primitive boolean'
CTEXT_NAME = 'Primitive string [Crystools]'
CTEXT_DESC = prefix + 'Primitive string'
CTEXTML_NAME = 'Primitive string multiline [Crystools]'
CTEXTML_DESC = prefix + 'Primitive string multiline'
CINTEGER_NAME = 'Primitive integer [Crystools]'
CINTEGER_DESC = prefix + 'Primitive integer'
CFLOAT_NAME = 'Primitive float [Crystools]'
CFLOAT_DESC = prefix + 'Primitive float'
CDEBUGGER_CONSOLE_ANY_NAME = 'Show any [Crystools]'
CDEBUGGER_ANY_DESC = prefix + 'Show any value to console/display'
CDEBUGGER_CONSOLE_ANY_TO_JSON_NAME = 'Show any to JSON [Crystools]'
CDEBUGGER_CONSOLE_ANY_TO_JSON_DESC = prefix + 'Show any to JSON'
CLIST_ANY_TYPE = 'ListAny'
CLIST_ANY_NAME = 'List of any [Crystools]'
CLIST_ANY_DESC = prefix + 'List of any'
CLIST_STRING_TYPE = 'ListString'
CLIST_STRING_NAME = 'List of strings [Crystools]'
CLIST_STRING_DESC = prefix + 'List of strings'
CSWITCH_FROM_ANY_NAME = 'Switch from any [Crystools]'
CSWITCH_FROM_ANY_DESC = prefix + 'Switch from any'
CSWITCH_ANY_NAME = 'Switch any [Crystools]'
CSWITCH_ANY_DESC = prefix + 'Switch any'
CSWITCH_STRING_NAME = 'Switch string [Crystools]'
CSWITCH_STRING_DESC = prefix + 'Switch string'
CSWITCH_CONDITIONING_NAME = 'Switch conditioning [Crystools]'
CSWITCH_CONDITIONING_DESC = prefix + 'Switch conditioning'
CSWITCH_IMAGE_NAME = 'Switch image [Crystools]'
CSWITCH_IMAGE_DESC = prefix + 'Switch image'
CSWITCH_MASK_NAME = 'Switch mask [Crystools]'
CSWITCH_MASK_DESC = prefix + 'Switch mask'
CSWITCH_LATENT_NAME = 'Switch latent [Crystools]'
CSWITCH_LATENT_DESC = prefix + 'Switch latent'
CPIPE_ANY_TYPE = 'CPipeAny'
CPIPE_TO_ANY_NAME = 'Pipe to/edit any [Crystools]'
CPIPE_TO_ANY_DESC = prefix + 'Pipe to/edit any'
CPIPE_FROM_ANY_NAME = 'Pipe from any [Crystools]'
CPIPE_FROM_ANY_DESC = prefix + 'Pipe from any'
CIMAGE_LOAD_METADATA_NAME = 'Load image with metadata [Crystools]'
CIMAGE_LOAD_METADATA_DESC = prefix + 'Load image with metadata'
CIMAGE_GET_RESOLUTION_NAME = 'Get resolution [Crystools]'
CIMAGE_GET_RESOLUTION_DESC = prefix + 'Get resolution'
CIMAGE_PREVIEW_IMAGE_NAME = 'Preview from image [Crystools]'
CIMAGE_PREVIEW_IMAGE_DESC = prefix + 'Preview from image'
CIMAGE_PREVIEW_METADATA_NAME = 'Preview from metadata [Crystools]'
CIMAGE_PREVIEW_METADATA_DESC = prefix + 'Preview from metadata'
CIMAGE_SAVE_METADATA_NAME = 'Save image with extra metadata [Crystools]'
CIMAGE_SAVE_METADATA_DESC = prefix + 'Save image with extra metadata'
CMETADATA_EXTRACTOR_NAME = 'Metadata extractor [Crystools]'
CMETADATA_EXTRACTOR_DESC = prefix + 'Metadata extractor'
CMETADATA_COMPARATOR_NAME = 'Metadata comparator [Crystools]'
CMETADATA_COMPARATOR_DESC = prefix + 'Metadata comparator'
CUTILS_JSON_COMPARATOR_NAME = 'JSON comparator [Crystools]'
CUTILS_JSON_COMPARATOR_DESC = prefix + 'JSON comparator'
CUTILS_STAT_SYSTEM_NAME = 'Stats system [Crystools]'
CUTILS_STAT_SYSTEM_DESC = prefix + 'Stats system (powered by WAS)'
# CPARAMETERS_NAME = 'External parameter from JSON file [Crystools]'
# CPARAMETERS_DESC = prefix + 'External parameters from JSON file'
CJSONFILE_NAME = 'Read JSON file [Crystools]'
CJSONFILE_DESC = prefix + 'Read JSON file (BETA)'
CJSONEXTRACTOR_NAME = 'JSON extractor [Crystools]'
CJSONEXTRACTOR_DESC = prefix + 'JSON extractor (BETA)'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123import json
from ..core import CONFIG, CATEGORY, BOOLEAN, BOOLEAN_FALSE, KEYS, TEXTS, STRING, logger, any
class CConsoleAny:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
},
"optional": {
"any_value": (any,),
"console": BOOLEAN_FALSE,
"display": BOOLEAN,
KEYS.PREFIX.value: STRING,
},
"hidden": {
# "unique_id": "UNIQUE_ID",
# "extra_pnginfo": "EXTRA_PNGINFO",
},
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.DEBUGGER.value
INPUT_IS_LIST = True
RETURN_TYPES = ()
OUTPUT_NODE = True
FUNCTION = "execute"
def execute(self, any_value=None, console=False, display=True, prefix=None):
console = console[0]
display = display[0]
prefix = prefix[0]
text = ""
textToDisplay = TEXTS.INACTIVE_MSG.value
if any_value is not None:
try:
if type(any_value) == list:
for item in any_value:
try:
text += str(item)
except Exception as e:
text += "source exists, but could not be serialized.\n"
logger.warn(e)
else:
logger.warn("any_value is not a list")
except Exception:
try:
text = json.dumps(any_value)[1:-1]
except Exception:
text = 'source exists, but could not be serialized.'
logger.debug(f"Show any to console is running...")
if console:
if prefix is not None and prefix != "":
print(f"{prefix}: {text}")
else:
print(text)
if display:
textToDisplay = text
value = [console, display, prefix, textToDisplay]
# setWidgetValues(value, unique_id, extra_pnginfo)
return {"ui": {"text": value}}
class CConsoleAnyToJson:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
},
"optional": {
"any_value": (any,),
},
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.DEBUGGER.value
INPUT_IS_LIST = True
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("string",)
OUTPUT_NODE = True
FUNCTION = "execute"
def execute(self, any_value=None):
text = TEXTS.INACTIVE_MSG.value
if any_value is not None and isinstance(any_value, list):
item = any_value[0]
if isinstance(item, dict):
try:
text = json.dumps(item, indent=CONFIG["indent"])
except Exception as e:
text = "The input is a dict, but could not be serialized.\n"
logger.warn(e)
elif isinstance(item, list):
try:
text = json.dumps(item, indent=CONFIG["indent"])
except Exception as e:
text = "The input is a list, but could not be serialized.\n"
logger.warn(e)
else:
text = str(item)
logger.debug(f"Show any-json to console is running...")
return {"ui": {"text": [text]}, "result": (text,)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517import fnmatch
import os
import random
import sys
import json
import piexif
import hashlib
from datetime import datetime
import torch
import numpy as np
from pathlib import Path
from PIL import Image, ImageOps
from PIL.ExifTags import TAGS, GPSTAGS, IFD
from PIL.PngImagePlugin import PngImageFile
from PIL.JpegImagePlugin import JpegImageFile
from nodes import PreviewImage, SaveImage
import folder_paths
from ..core import CATEGORY, CONFIG, BOOLEAN, METADATA_RAW,TEXTS, setWidgetValues, logger, getResolutionByTensor, get_size
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy"))
class CImagePreviewFromImage(PreviewImage):
def __init__(self):
self.output_dir = folder_paths.get_temp_directory()
self.type = "temp"
self.prefix_append = "_" + ''.join(random.choice("abcdefghijklmnopqrstupvxyz") for x in range(5))
self.compress_level = 1
self.data_cached = None
self.data_cached_text = None
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
# if it is required, in next node does not receive any value even the cache!
},
"optional": {
"image": ("IMAGE",),
},
"hidden": {
"prompt": "PROMPT",
"extra_pnginfo": "EXTRA_PNGINFO",
},
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.IMAGE.value
RETURN_TYPES = ("METADATA_RAW",)
RETURN_NAMES = ("Metadata RAW",)
OUTPUT_NODE = True
FUNCTION = "execute"
def execute(self, image=None, prompt=None, extra_pnginfo=None):
text = ""
title = ""
data = {
"result": [''],
"ui": {
"text": [''],
"images": [],
}
}
if image is not None:
saved = self.save_images(image, "crystools/i", prompt, extra_pnginfo)
image = saved["ui"]["images"][0]
image_path = Path(self.output_dir).joinpath(image["subfolder"], image["filename"])
img, promptFromImage, metadata = buildMetadata(image_path)
images = [image]
result = metadata
data["result"] = [result]
data["ui"]["images"] = images
title = "Source: Image link \n"
text += buildPreviewText(metadata)
text += f"Current prompt (NO FROM IMAGE!):\n"
text += json.dumps(promptFromImage, indent=CONFIG["indent"])
self.data_cached_text = text
self.data_cached = data
elif image is None and self.data_cached is not None:
title = "Source: Image link - CACHED\n"
data = self.data_cached
text = self.data_cached_text
else:
logger.debug("Source: Empty on CImagePreviewFromImage")
text = "Source: Empty"
data['ui']['text'] = [title + text]
return data
class CImagePreviewFromMetadata(PreviewImage):
def __init__(self):
self.data_cached = None
self.data_cached_text = None
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
# if it is required, in next node does not receive any value even the cache!
},
"optional": {
"metadata_raw": METADATA_RAW,
},
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.IMAGE.value
RETURN_TYPES = ("METADATA_RAW",)
RETURN_NAMES = ("Metadata RAW",)
OUTPUT_NODE = True
FUNCTION = "execute"
def execute(self, metadata_raw=None):
text = ""
title = ""
data = {
"result": [''],
"ui": {
"text": [''],
"images": [],
}
}
if metadata_raw is not None and metadata_raw != '':
promptFromImage = {}
if "prompt" in metadata_raw:
promptFromImage = metadata_raw["prompt"]
title = "Source: Metadata RAW\n"
text += buildPreviewText(metadata_raw)
text += f"Prompt from image:\n"
text += json.dumps(promptFromImage, indent=CONFIG["indent"])
images = self.resolveImage(metadata_raw["fileinfo"]["filename"])
result = metadata_raw
data["result"] = [result]
data["ui"]["images"] = images
self.data_cached_text = text
self.data_cached = data
elif metadata_raw is None and self.data_cached is not None:
title = "Source: Metadata RAW - CACHED\n"
data = self.data_cached
text = self.data_cached_text
else:
logger.debug("Source: Empty on CImagePreviewFromMetadata")
text = "Source: Empty"
data["ui"]["text"] = [title + text]
return data
def resolveImage(self, filename=None):
images = []
if filename is not None:
image_input_folder = os.path.normpath(folder_paths.get_input_directory())
image_input_folder_abs = Path(image_input_folder).resolve()
image_path = os.path.normpath(filename)
image_path_abs = Path(image_path).resolve()
if Path(image_path_abs).is_file() is False:
raise Exception(TEXTS.FILE_NOT_FOUND.value)
try:
# get common path, should be input/output/temp folder
common = os.path.commonpath([image_input_folder_abs, image_path_abs])
if common != image_input_folder:
raise Exception("Path invalid (should be in the input folder)")
relative = os.path.normpath(os.path.relpath(image_path_abs, image_input_folder_abs))
images.append({
"filename": Path(relative).name,
"subfolder": os.path.dirname(relative),
"type": "input"
})
except Exception as e:
logger.warn(e)
return images
class CImageGetResolution:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
},
"hidden": {
"unique_id": "UNIQUE_ID",
"extra_pnginfo": "EXTRA_PNGINFO",
},
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.IMAGE.value
RETURN_TYPES = ("INT", "INT",)
RETURN_NAMES = ("width", "height",)
OUTPUT_NODE = True
FUNCTION = "execute"
def execute(self, image, extra_pnginfo=None, unique_id=None):
res = getResolutionByTensor(image)
text = [f"{res['x']}x{res['y']}"]
setWidgetValues(text, unique_id, extra_pnginfo)
logger.debug(f"Resolution: {text}")
return {"ui": {"text": text}, "result": (res["x"], res["y"])}
# subfolders based on: https://github.com/catscandrive/comfyui-imagesubfolders
class CImageLoadWithMetadata:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
input_dir = folder_paths.get_input_directory()
exclude_files = {"Thumbs.db", "*.DS_Store", "desktop.ini", "*.lock" }
exclude_folders = {"clipspace", ".*"}
file_list = []
for root, dirs, files in os.walk(input_dir, followlinks=True):
# Exclude specific folders
dirs[:] = [d for d in dirs if not any(fnmatch.fnmatch(d, exclude) for exclude in exclude_folders)]
files = [f for f in files if not any(fnmatch.fnmatch(f, exclude) for exclude in exclude_files)]
for file in files:
relpath = os.path.relpath(os.path.join(root, file), start=input_dir)
# fix for windows
relpath = relpath.replace("\\", "/")
file_list.append(relpath)
return {
"required": {
"image": (sorted(file_list), {"image_upload": True})
},
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.IMAGE.value
RETURN_TYPES = ("IMAGE", "MASK", "JSON", "METADATA_RAW")
RETURN_NAMES = ("image", "mask", "prompt", "Metadata RAW")
OUTPUT_NODE = True
FUNCTION = "execute"
def execute(self, image):
image_path = folder_paths.get_annotated_filepath(image)
imgF = Image.open(image_path)
img, prompt, metadata = buildMetadata(image_path)
if imgF.format == 'WEBP':
# Use piexif to extract EXIF data from WebP image
try:
exif_data = piexif.load(image_path)
prompt, metadata = self.process_exif_data(exif_data)
except ValueError:
prompt = {}
img = ImageOps.exif_transpose(img)
image = img.convert("RGB")
image = np.array(image).astype(np.float32) / 255.0
image = torch.from_numpy(image)[None,]
if 'A' in img.getbands():
mask = np.array(img.getchannel('A')).astype(np.float32) / 255.0
mask = 1. - torch.from_numpy(mask)
else:
mask = torch.zeros((64, 64), dtype=torch.float32, device="cpu")
return image, mask.unsqueeze(0), prompt, metadata
def process_exif_data(self, exif_data):
metadata = {}
# 检查 '0th' 键下的 271 值,提取 Prompt 信息
if '0th' in exif_data and 271 in exif_data['0th']:
prompt_data = exif_data['0th'][271].decode('utf-8')
# 移除可能的前缀 'Prompt:'
prompt_data = prompt_data.replace('Prompt:', '', 1)
# 假设 prompt_data 是一个字符串,尝试将其转换为 JSON 对象
try:
metadata['prompt'] = json.loads(prompt_data)
except json.JSONDecodeError:
metadata['prompt'] = prompt_data
# 检查 '0th' 键下的 270 值,提取 Workflow 信息
if '0th' in exif_data and 270 in exif_data['0th']:
workflow_data = exif_data['0th'][270].decode('utf-8')
# 移除可能的前缀 'Workflow:'
workflow_data = workflow_data.replace('Workflow:', '', 1)
try:
# 尝试将字节字符串转换为 JSON 对象
metadata['workflow'] = json.loads(workflow_data)
except json.JSONDecodeError:
# 如果转换失败,则将原始字符串存储在 metadata 中
metadata['workflow'] = workflow_data
metadata.update(exif_data)
return metadata
@classmethod
def IS_CHANGED(cls, image):
image_path = folder_paths.get_annotated_filepath(image)
m = hashlib.sha256()
with open(image_path, 'rb') as f:
m.update(f.read())
return m.digest().hex()
@classmethod
def VALIDATE_INPUTS(cls, image):
if not folder_paths.exists_annotated_filepath(image):
return "Invalid image file: {}".format(image)
return True
class CImageSaveWithExtraMetadata(SaveImage):
def __init__(self):
super().__init__()
self.data_cached = None
self.data_cached_text = None
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
# if it is required, in next node does not receive any value even the cache!
"image": ("IMAGE",),
"filename_prefix": ("STRING", {"default": "ComfyUI"}),
"with_workflow": BOOLEAN,
},
"optional": {
"metadata_extra": ("STRING", {"multiline": True, "default": json.dumps({
"Title": "Image generated by Crystian",
"Description": "More info: https:\/\/www.instagram.com\/crystian.ia",
"Author": "crystian.ia",
"Software": "ComfyUI",
"Category": "StableDiffusion",
"Rating": 5,
"UserComment": "",
"Keywords": [
""
],
"Copyrights": "",
}, indent=CONFIG["indent"]).replace("\\/", "/"),
}),
},
"hidden": {
"prompt": "PROMPT",
"extra_pnginfo": "EXTRA_PNGINFO",
},
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.IMAGE.value
RETURN_TYPES = ("METADATA_RAW",)
RETURN_NAMES = ("Metadata RAW",)
OUTPUT_NODE = True
FUNCTION = "execute"
def execute(self, image=None, filename_prefix="ComfyUI", with_workflow=True, metadata_extra=None, prompt=None, extra_pnginfo=None):
data = {
"result": [''],
"ui": {
"text": [''],
"images": [],
}
}
if image is not None:
if with_workflow is True:
extra_pnginfo_new = extra_pnginfo.copy()
prompt = prompt.copy()
else:
extra_pnginfo_new = None
prompt = None
if metadata_extra is not None and metadata_extra != 'undefined':
try:
# metadata_extra = json.loads(f"{{{metadata_extra}}}") // a fix?
metadata_extra = json.loads(metadata_extra)
except Exception as e:
logger.error(f"Error parsing metadata_extra (it will send as string), error: {e}")
metadata_extra = {"extra": str(metadata_extra)}
if isinstance(metadata_extra, dict):
for k, v in metadata_extra.items():
if extra_pnginfo_new is None:
extra_pnginfo_new = {}
extra_pnginfo_new[k] = v
saved = super().save_images(image, filename_prefix, prompt, extra_pnginfo_new)
image = saved["ui"]["images"][0]
image_path = Path(self.output_dir).joinpath(image["subfolder"], image["filename"])
img, promptFromImage, metadata = buildMetadata(image_path)
images = [image]
result = metadata
data["result"] = [result]
data["ui"]["images"] = images
else:
logger.debug("Source: Empty on CImageSaveWithExtraMetadata")
return data
def buildMetadata(image_path):
if Path(image_path).is_file() is False:
raise Exception(TEXTS.FILE_NOT_FOUND.value)
img = Image.open(image_path)
metadata = {}
prompt = {}
metadata["fileinfo"] = {
"filename": Path(image_path).as_posix(),
"resolution": f"{img.width}x{img.height}",
"date": str(datetime.fromtimestamp(os.path.getmtime(image_path))),
"size": str(get_size(image_path)),
}
# only for png files
if isinstance(img, PngImageFile):
metadataFromImg = img.info
# for all metadataFromImg convert to string (but not for workflow and prompt!)
for k, v in metadataFromImg.items():
# from ComfyUI
if k == "workflow":
try:
metadata["workflow"] = json.loads(metadataFromImg["workflow"])
except Exception as e:
logger.warn(f"Error parsing metadataFromImg 'workflow': {e}")
# from ComfyUI
elif k == "prompt":
try:
metadata["prompt"] = json.loads(metadataFromImg["prompt"])
# extract prompt to use on metadataFromImg
prompt = metadata["prompt"]
except Exception as e:
logger.warn(f"Error parsing metadataFromImg 'prompt': {e}")
else:
try:
# for all possible metadataFromImg by user
metadata[str(k)] = json.loads(v)
except Exception as e:
logger.debug(f"Error parsing {k} as json, trying as string: {e}")
try:
metadata[str(k)] = str(v)
except Exception as e:
logger.debug(f"Error parsing {k} it will be skipped: {e}")
if isinstance(img, JpegImageFile):
exif = img.getexif()
for k, v in exif.items():
tag = TAGS.get(k, k)
if v is not None:
metadata[str(tag)] = str(v)
for ifd_id in IFD:
try:
if ifd_id == IFD.GPSInfo:
resolve = GPSTAGS
else:
resolve = TAGS
ifd = exif.get_ifd(ifd_id)
ifd_name = str(ifd_id.name)
metadata[ifd_name] = {}
for k, v in ifd.items():
tag = resolve.get(k, k)
metadata[ifd_name][str(tag)] = str(v)
except KeyError:
pass
return img, prompt, metadata
def buildPreviewText(metadata):
text = f"File: {metadata['fileinfo']['filename']}\n"
text += f"Resolution: {metadata['fileinfo']['resolution']}\n"
text += f"Date: {metadata['fileinfo']['date']}\n"
text += f"Size: {metadata['fileinfo']['size']}\n"
return text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149from ..core import STRING, TEXTS, KEYS, CATEGORY, any, logger
from ._names import CLASSES
class CListAny:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
},
"optional": {
"any_1": (any,),
"any_2": (any,),
"any_3": (any,),
"any_4": (any,),
"any_5": (any,),
"any_6": (any,),
"any_7": (any,),
"any_8": (any,),
}
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.LIST.value
RETURN_TYPES = (any,),
RETURN_NAMES = ("any_list",)
OUTPUT_IS_LIST = (True,)
FUNCTION = "execute"
def execute(self,
any_1=None,
any_2=None,
any_3=None,
any_4=None,
any_5=None,
any_6=None,
any_7=None,
any_8=None):
list_any = []
if any_1 is not None:
try:
list_any.append(any_1)
except Exception as e:
logger.warn(e)
if any_2 is not None:
try:
list_any.append(any_2)
except Exception as e:
logger.warn(e)
if any_3 is not None:
try:
list_any.append(any_3)
except Exception as e:
logger.warn(e)
if any_4 is not None:
try:
list_any.append(any_4)
except Exception as e:
logger.warn(e)
if any_5 is not None:
try:
list_any.append(any_5)
except Exception as e:
logger.warn(e)
if any_6 is not None:
try:
list_any.append(any_6)
except Exception as e:
logger.warn(e)
if any_7 is not None:
try:
list_any.append(any_7)
except Exception as e:
logger.warn(e)
if any_8 is not None:
try:
list_any.append(any_8)
except Exception as e:
logger.warn(e)
# yes, double brackets are needed because of the OUTPUT_IS_LIST... ¯\_(ツ)_/¯
return [[list_any]]
class CListString:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
},
"optional": {
"string_1": STRING,
"string_2": STRING,
"string_3": STRING,
"string_4": STRING,
"string_5": STRING,
"string_6": STRING,
"string_7": STRING,
"string_8": STRING,
"delimiter": ("STRING", {"default": " "}),
}
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.LIST.value
RETURN_TYPES = ("STRING", CLASSES.CLIST_STRING_TYPE.value,)
RETURN_NAMES = (TEXTS.CONCAT.value, KEYS.LIST.value)
OUTPUT_IS_LIST = (False, True, )
FUNCTION = "execute"
def execute(self,
string_1=None,
string_2=None,
string_3=None,
string_4=None,
string_5=None,
string_6=None,
string_7=None,
string_8=None,
delimiter=""):
list_str = []
if string_1 is not None and string_1 != "":
list_str.append(string_1)
if string_2 is not None and string_2 != "":
list_str.append(string_2)
if string_3 is not None and string_3 != "":
list_str.append(string_3)
if string_4 is not None and string_4 != "":
list_str.append(string_4)
if string_5 is not None and string_5 != "":
list_str.append(string_5)
if string_6 is not None and string_6 != "":
list_str.append(string_6)
if string_7 is not None and string_7 != "":
list_str.append(string_7)
if string_8 is not None and string_8 != "":
list_str.append(string_8)
return delimiter.join(list_str), [list_str]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164import json
import re
from ..core import CATEGORY, CONFIG, METADATA_RAW, TEXTS, findJsonsDiff, logger
class CMetadataExtractor:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"metadata_raw": METADATA_RAW,
},
"optional": {
}
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.METADATA.value
RETURN_TYPES = ("JSON", "JSON", "JSON", "JSON", "STRING", "STRING")
RETURN_NAMES = ("prompt", "workflow", "file info", "raw to JSON", "raw to property", "raw to csv")
# OUTPUT_NODE = True
FUNCTION = "execute"
def execute(self, metadata_raw=None):
prompt = {}
workflow = {}
fileinfo = {}
text = ""
csv = ""
if metadata_raw is not None and isinstance(metadata_raw, dict):
try:
for key, value in metadata_raw.items():
if isinstance(value, dict):
# yes, double json.dumps is needed for jsons
value = json.dumps(json.dumps(value))
else:
value = json.dumps(value)
text += f"\"{key}\"={value}\n"
# remove spaces
# value = re.sub(' +', ' ', value)
value = re.sub('\n', ' ', value)
csv += f'"{key}"\t{value}\n'
if csv != "":
csv = '"key"\t"value"\n' + csv
except Exception as e:
logger.warn(e)
try:
if "prompt" in metadata_raw:
prompt = metadata_raw["prompt"]
else:
raise Exception("Prompt not found in metadata_raw")
except Exception as e:
logger.warn(e)
try:
if "workflow" in metadata_raw:
workflow = metadata_raw["workflow"]
else:
raise Exception("Workflow not found in metadata_raw")
except Exception as e:
logger.warn(e)
try:
if "fileinfo" in metadata_raw:
fileinfo = metadata_raw["fileinfo"]
else:
raise Exception("Fileinfo not found in metadata_raw")
except Exception as e:
logger.warn(e)
elif metadata_raw is None:
logger.debug("metadata_raw is None")
else:
logger.warn(TEXTS.INVALID_METADATA_MSG.value)
return (json.dumps(prompt, indent=CONFIG["indent"]),
json.dumps(workflow, indent=CONFIG["indent"]),
json.dumps(fileinfo, indent=CONFIG["indent"]),
json.dumps(metadata_raw, indent=CONFIG["indent"]),
text, csv)
class CMetadataCompare:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"metadata_raw_old": METADATA_RAW,
"metadata_raw_new": METADATA_RAW,
"what": (["Prompt", "Workflow", "Fileinfo"],),
},
"optional": {
}
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.METADATA.value
RETURN_TYPES = ("JSON",)
RETURN_NAMES = ("diff",)
OUTPUT_NODE = True
FUNCTION = "execute"
def execute(self, what, metadata_raw_old=None, metadata_raw_new=None):
prompt_old = {}
workflow_old = {}
fileinfo_old = {}
prompt_new = {}
workflow_new = {}
fileinfo_new = {}
diff = ""
if type(metadata_raw_old) == dict and type(metadata_raw_new) == dict:
if "prompt" in metadata_raw_old:
prompt_old = metadata_raw_old["prompt"]
else:
logger.warn("Prompt not found in metadata_raw_old")
if "workflow" in metadata_raw_old:
workflow_old = metadata_raw_old["workflow"]
else:
logger.warn("Workflow not found in metadata_raw_old")
if "fileinfo" in metadata_raw_old:
fileinfo_old = metadata_raw_old["fileinfo"]
else:
logger.warn("Fileinfo not found in metadata_raw_old")
if "prompt" in metadata_raw_new:
prompt_new = metadata_raw_new["prompt"]
else:
logger.warn("Prompt not found in metadata_raw_new")
if "workflow" in metadata_raw_new:
workflow_new = metadata_raw_new["workflow"]
else:
logger.warn("Workflow not found in metadata_raw_new")
if "fileinfo" in metadata_raw_new:
fileinfo_new = metadata_raw_new["fileinfo"]
else:
logger.warn("Fileinfo not found in metadata_raw_new")
if what == "Prompt":
diff = findJsonsDiff(prompt_old, prompt_new)
elif what == "Workflow":
diff = findJsonsDiff(workflow_old, workflow_new)
else:
diff = findJsonsDiff(fileinfo_old, fileinfo_new)
diff = json.dumps(diff, indent=CONFIG["indent"])
else:
invalid_msg = TEXTS.INVALID_METADATA_MSG.value
logger.warn(invalid_msg)
diff = invalid_msg
return {"ui": {"text": [diff]}, "result": (diff,)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170import json
from ..core import CONFIG, any, JSON_WIDGET, CATEGORY, STRING, INT, FLOAT, BOOLEAN, logger, get_nested_value
# class CParameter:
# def __init__(self):
# pass
#
# @classmethod
# def INPUT_TYPES(cls):
# return {
# "required": {
# },
# "optional": {
# "path_to_json": STRING,
# "key": STRING,
# "default": STRING,
# },
# }
#
# CATEGORY = CATEGORY.MAIN.value + CATEGORY.UTILS.value
# INPUT_IS_LIST = False
#
# RETURN_TYPES = (any,)
# RETURN_NAMES = ("any",)
#
# FUNCTION = "execute"
#
# def execute(self, path_to_json=None, key=True, default=None):
# text = default
# value = text
#
# if path_to_json is not None and path_to_json != "":
# logger.debug(f"External parameter from: '{path_to_json}'")
# try:
# with open(path_to_json, 'r') as file:
# data = json.load(file)
# logger.debug(f"File found, data: '{data}'")
#
# result = get_value(data, key, default)
# text = result["text"]
# value = result["value"]
#
# except Exception as e:
# logger.error(e)
# text = f"Error reading file: {e}\nReturning default value: '{default}'"
# value = default
#
# return {"ui": {"text": [text]}, "result": [value]}
class CJsonFile:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
},
"optional": {
"path_to_json": STRING,
},
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.UTILS.value
INPUT_IS_LIST = False
RETURN_TYPES = ("JSON",)
RETURN_NAMES = ("json",)
FUNCTION = "execute"
def IS_CHANGED(path_to_json=None):
return True
def execute(self, path_to_json=None):
text = ""
data = {}
if path_to_json is not None and path_to_json != "":
logger.debug(f"Open json file: '{path_to_json}'")
try:
with open(path_to_json, 'r') as file:
data = json.load(file)
text = json.dumps(data, indent=CONFIG["indent"])
logger.debug(f"File found, data: '{str(data)}'")
except Exception as e:
logger.error(e)
text = f"Error reading file: {e}"
return {"ui": {"text": [text]}, "result": [data]}
class CJsonExtractor:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"json": JSON_WIDGET,
},
"optional": {
"key": STRING,
"default": STRING,
},
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.UTILS.value
INPUT_IS_LIST = False
RETURN_TYPES = (any, "STRING", "INT", "FLOAT", "BOOLEAN")
RETURN_NAMES = ("any", "string", "int", "float", "boolean")
# OUTPUT_IS_LIST = (False,)
FUNCTION = "execute"
def execute(cls, json=None, key=True, default=None):
result = get_value(json, key, default)
result["any"] = result["value"]
try:
result["string"] = str(result["value"])
except Exception as e:
result["string"] = result["value"]
try:
result["int"] = int(result["value"])
except Exception as e:
result["int"] = result["value"]
try:
result["float"] = float(result["value"])
except Exception as e:
result["float"] = result["value"]
try:
result["boolean"] = result["value"].lower() == "true"
except Exception as e:
result["boolean"] = result["value"]
return {
"ui": {"text": [result["text"]]},
"result": [
result["any"],
result["string"],
result["int"],
result["float"],
result["boolean"]
]
}
def get_value(data, key, default=None):
text = ""
val = ""
if key is not None and key != "":
val = get_nested_value(data, key, default)
if default != val:
text = f"Key found, return value: '{val}'"
else:
text = f"Key no found, return default value: '{val}'"
else:
text = f"Key is empty, return default value: '{val}'"
return {
"text": text,
"value": val
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374from ..core import CATEGORY, any
from ._names import CLASSES
class CPipeToAny:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {},
"optional": {
CLASSES.CPIPE_ANY_TYPE.value: (CLASSES.CPIPE_ANY_TYPE.value,),
"any_1": (any,),
"any_2": (any,),
"any_3": (any,),
"any_4": (any,),
"any_5": (any,),
"any_6": (any,),
}
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.PIPE.value
RETURN_TYPES = (CLASSES.CPIPE_ANY_TYPE.value,)
FUNCTION = "execute"
def execute(self, CPipeAny=None, any_1=None, any_2=None, any_3=None, any_4=None, any_5=None, any_6=None):
any_1_original = None
any_2_original = None
any_3_original = None
any_4_original = None
any_5_original = None
any_6_original = None
if CPipeAny != None:
any_1_original, any_2_original, any_3_original, any_4_original, any_5_original, any_6_original = CPipeAny
CAnyPipeMod = []
CAnyPipeMod.append(any_1 if any_1 is not None else any_1_original)
CAnyPipeMod.append(any_2 if any_2 is not None else any_2_original)
CAnyPipeMod.append(any_3 if any_3 is not None else any_3_original)
CAnyPipeMod.append(any_4 if any_4 is not None else any_4_original)
CAnyPipeMod.append(any_5 if any_5 is not None else any_5_original)
CAnyPipeMod.append(any_6 if any_6 is not None else any_6_original)
return (CAnyPipeMod,)
class CPipeFromAny:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
CLASSES.CPIPE_ANY_TYPE.value: (CLASSES.CPIPE_ANY_TYPE.value,),
},
"optional": {
}
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.PIPE.value
RETURN_TYPES = (CLASSES.CPIPE_ANY_TYPE.value, any, any, any, any, any, any,)
RETURN_NAMES = (CLASSES.CPIPE_ANY_TYPE.value, "any_1", "any_2", "any_3", "any_4", "any_5", "any_6",)
FUNCTION = "execute"
def execute(self, CPipeAny=None, ):
any_1, any_2, any_3, any_4, any_5, any_6 = CPipeAny
return CPipeAny, any_1, any_2, any_3, any_4, any_5, any_6123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111from ..core import BOOLEAN, CATEGORY, STRING, INT, FLOAT, STRING_ML
class CBoolean:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"boolean": BOOLEAN,
}
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.PRIMITIVE.value
RETURN_TYPES = ("BOOLEAN",)
RETURN_NAMES = ("boolean",)
FUNCTION = "execute"
def execute(self, boolean=True):
return (boolean,)
class CText:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"string": STRING,
}
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.PRIMITIVE.value
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("string",)
FUNCTION = "execute"
def execute(self, string=""):
return (string,)
class CTextML:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"string": STRING_ML,
}
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.PRIMITIVE.value
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("string",)
FUNCTION = "execute"
def execute(self, string=""):
return (string,)
class CInteger:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"int": INT,
}
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.PRIMITIVE.value
RETURN_TYPES = ("INT",)
RETURN_NAMES = ("int",)
FUNCTION = "execute"
def execute(self, int=True):
return (int,)
class CFloat:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"float": FLOAT,
}
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.PRIMITIVE.value
RETURN_TYPES = ("FLOAT",)
RETURN_NAMES = ("float",)
FUNCTION = "execute"
def execute(self, float=True):
return (float,)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455from ..core import CATEGORY, JSON_WIDGET, findJsonStrDiff, get_system_stats, logger
class CUtilsCompareJsons:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"json_old": JSON_WIDGET,
"json_new": JSON_WIDGET,
},
"optional": {
}
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.UTILS.value
RETURN_TYPES = ("JSON",)
RETURN_NAMES = ("json_compared",)
OUTPUT_NODE = True
FUNCTION = "execute"
def execute(self, json_old, json_new):
json = findJsonStrDiff(json_old, json_new)
return (str(json),)
# Credits to: https://github.com/WASasquatch/was-node-suite-comfyui for the following node!
class CUtilsStatSystem:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"latent": ("LATENT",),
}
}
CATEGORY = CATEGORY.MAIN.value + CATEGORY.UTILS.value
RETURN_TYPES = ("LATENT",)
RETURN_NAMES = ("latent",)
FUNCTION = "execute"
def execute(self, latent):
log = "Samples Passthrough:\n"
for stat in get_system_stats():
log += stat + "\n"
logger.debug(log)
return {"ui": {"text": [log]}, "result": (latent,)}12345678910111213141516171819202122232425name: Publish to Comfy registryon: 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 == 'sipherxyz' }} 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 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869.github/workflows/publish.yml
.gitignore
.prettierrc
README.md
__init__.py
config.py
modules/animatediff/__init__.py
modules/controlnet/__init__.py
modules/controlnet/advanced.py
modules/controlnet/preprocessor.py
modules/fooocus/__init__.py
modules/fooocus/anisotropic.py
modules/fooocus/efficient.py
modules/fooocus/patch.py
modules/image_utils.py
modules/impact/__init__.py
modules/impact/facedetailer.py
modules/inpaint/__init__.py
modules/inpaint/lama/__init__.py
modules/inpaint/nodes.py
modules/inpaint/sam/nodes.py
modules/interrogate/.gitignore
modules/interrogate/__init__.py
modules/interrogate/blip_node.py
modules/interrogate/configs/med_config.json
modules/interrogate/danbooru.py
modules/interrogate/models/__init__.py
modules/interrogate/models/blip.py
modules/interrogate/models/blip_itm.py
modules/interrogate/models/blip_nlvr.py
modules/interrogate/models/blip_pretrain.py
modules/interrogate/models/blip_retrieval.py
modules/interrogate/models/blip_vqa.py
modules/interrogate/models/deepbooru_model.py
modules/interrogate/models/med.py
modules/interrogate/models/nlvr_encoder.py
modules/interrogate/models/vit.py
modules/interrogate/transform/randaugment.py
modules/ip_adapter_nodes.py
modules/isnet/__init__.py
modules/isnet/models/__init__.py
modules/isnet/models/isnet.py
modules/isnet/models/isnet_dis.py
modules/isnet/segmenter.py
modules/llm/__init__.py
modules/llm/chat.py
modules/logger.py
modules/masking.py
modules/model_utils.py
modules/nodes.py
modules/postprocessing/__init__.py
modules/postprocessing/color_blend.py
modules/postprocessing/color_correct.py
modules/sdxl_prompt_styler/.gitignore
modules/sdxl_prompt_styler/LICENSE
modules/sdxl_prompt_styler/README.md
modules/sdxl_prompt_styler/__init__.py
modules/sdxl_prompt_styler/sdxl_prompt_styler.py
modules/sdxl_prompt_styler/sdxl_styles_base.json
modules/sdxl_prompt_styler/sdxl_styles_sai.json
modules/sdxl_prompt_styler/sdxl_styles_twri.json
modules/utility_nodes.py
modules/utils.py
modules/video/__init__.py
pyproject.toml
requirements.txt
web/text-switch-case.js
web/upload.js
web/utils.js123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217# ArtVenture Custom Nodes
A comprehensive set of custom nodes for ComfyUI, focusing on utilities for image processing, JSON manipulation, model operations and working with object via URLs
### Image Nodes
#### LoadImageFromUrl
Loads images from URLs.
**Inputs:**
- `image`: List of URLs or base64 image data, separated by new lines- `keep_alpha_channel`: Preserve alpha channel- `output_mode`: List or batch output. Use `List` if you have different resolutions.

### JSON Nodes
#### LoadJsonFromUrl
Loads JSON data from URLs.
**Inputs:**
- `url`: JSON URL- `print_to_console`: Print JSON to console
#### LoadJsonFromText
Loads JSON data from text.
**Inputs:**
- `data`: JSON text- `print_to_console`: Print JSON to console
#### Get<\*>FromJson
Includes `GetObjectFromJson`, `GetTextFromJson`, `GetFloatFromJson`, `GetIntFromJson`, `GetBoolFromJson`.
Use key format `key.[index].subkey.[sub_index]` to access nested objects.

### Utility Nodes
#### StringToNumber
Converts strings to numbers.
**Inputs:**
- `string`: Input string- `rounding`: Rounding method
#### TextRandomMultiline
Randomizes the order of lines in a multiline string.
**Inputs:**
- `text`: Input text- `amount`: Number of lines to randomize- `seed`: Random seed

#### TextSwitchCase
Switch between multiple cases based on a condition.
**Inputs:**
- `switch_cases`: Switch cases, separated by new lines- `condition`: Condition to switch on- `default_value`: Default value when no condition matches- `delimiter`: Delimiter between case and value, default is `:`
The `switch_cases` format is `case<delimiter>value`, where `case` is the condition to match and `value` is the value to return when the condition matches. You can have new lines in the value to return multiple lines.

### Inpainting Nodes
#### PrepareImageAndMaskForInpaint
Prepares images and masks for inpainting operations. It's to mimic the behavior of the inpainting in A1111.
**Inputs:**
- `image`: Input image tensor- `mask`: Input mask tensor- `mask_blur`: Blur amount for mask (0-64)- `inpaint_masked`: Whether to inpaint only the masked regions, otherwise it will inpaint the whole image.- `mask_padding`: Padding around mask (0-256)- `width`: Manually set inpaint area width. Leave 0 default to the masked area plus padding. (0-2048)- `height`: Manually set inpaint area height. (0-2048)
**Outputs:**
- `inpaint_image`: Processed image for inpainting- `inpaint_mask`: Processed mask- `overlay_image`: Preview overlay- `crop_region`: Crop coordinates (input of OverlayInpaintedImage)

#### OverlayInpaintedImage
Overlays inpainted images with original images.
**Inputs:**
- `inpainted`: Inpainted image- `overlay_image`: Original image- `crop_region`: Crop region coordinates
**Outputs:**
- `IMAGE`: Final composited image
#### LaMaInpaint
Remove objects from images using LaMa model.

### LLM Nodes
#### LLMApiConfig
Configures generic LLM API parameters.
**Inputs:**
- `model`: Model name (GPT-3.5, GPT-4, etc)- `max_token`: Maximum tokens- `temperature`: Temperature parameter
#### OpenAIApi
Configures OpenAI API access.
**Inputs:**
- `openai_api_key`: OpenAI API key- `endpoint`: API endpoint URL
### Claude API Nodes
#### ClaudeApi
Configures Anthropic Claude API access.
**Inputs:**
- `claude_api_key`: Claude API key- `endpoint`: API endpoint- `version`: API version
#### AwsBedrockClaudeApi
Configures AWS Bedrock Claude API access.
**Inputs:**
- `aws_access_key_id`: AWS access key- `aws_secret_access_key`: AWS secret key- `region`: AWS region- `version`: API version
#### AwsBedrockMistralApi
Configures AWS Bedrock Mistral API access.
**Inputs:**
- `aws_access_key_id`: AWS access key- `aws_secret_access_key`: AWS secret key- `region`: AWS region
#### LLMMessage
Creates a message for LLM interaction.
**Inputs:**
- `role`: Message role (system/user/assistant)- `text`: Message content- `image`: Optional image input- `messages`: Previous message history
#### LLMChat
Handles chat interactions with LLMs.
**Inputs:**
- `messages`: Message history- `api`: LLM API configuration- `config`: Model configuration- `seed`: Random seed
#### LLMCompletion
Handles completion requests to LLMs.
**Inputs:**
- `prompt`: Input prompt- `api`: LLM API configuration- `config`: Model configuration- `seed`: Random seed
1234567891011121314151617import sysimport folder_paths
if not 'saved_prompts' in folder_paths.folder_names_and_paths: folder_paths.folder_names_and_paths['saved_prompts'] = ([], set(['.txt']))
custom_nodes = folder_paths.get_folder_paths("custom_nodes")for dir in custom_nodes: if dir not in sys.path: print("Adding", dir, "to sys.path") sys.path.append(dir)
from .modules.nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
WEB_DIRECTORY = "./web"
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import osimport jsonimport inspectfrom typing import Dict
from server import PromptServer
from .modules.logger import logger
comfy_dir = os.path.dirname(inspect.getfile(PromptServer))ext_dir = os.path.dirname(os.path.realpath(__file__))config_path = os.path.join(ext_dir, "config.json")
def __get_dir(root: str, subpath=None, mkdir=False): dir = root 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_ext_dir(subpath=None, mkdir=False): return __get_dir(ext_dir, subpath, mkdir)
def get_comfy_dir(subpath=None, mkdir=False): return __get_dir(comfy_dir, subpath, mkdir)
def write_config(config): with open(config_path, "w") as f: json.dump(config, f, indent=4)
def load_config() -> Dict: default_config = { "av_endpoint": "https://api.artventure.ai", "av_token": "", "runner_enabled": False, "remove_runner_images_after_upload": False, }
if not os.path.isfile(config_path): logger.info("Config file not found, creating...") write_config(default_config)
with open(config_path, "r") as f: config = json.load(f)
need_update = False for key, value in default_config.items(): if key not in config: config[key] = value need_update = True
if need_update: write_config(config)
logger.debug(f"Loaded config {config}") return config
config = load_config()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889import osfrom typing import Callable
import folder_paths
from ..utils import load_module
custom_nodes = folder_paths.get_folder_paths("custom_nodes")animatediff_dir_names = ["AnimateDiff", "comfyui-animatediff"]
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 animatediff_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 AnimateDiff nodes")
module_path = os.path.join(module_path, "animatediff/sliding_schedule.py") module = load_module(module_path) print("Loaded AnimateDiff from", module_path)
get_context_scheduler: Callable = module.get_context_scheduler
class AnimateDiffFrameCalculator: @classmethod def INPUT_TYPES(s): return { "required": { "frame_rate": ("INT", {"default": 8, "min": 1, "max": 24, "step": 1}), "duration": ("INT", {"default": 2, "min": 1, "max": 10000, "step": 1}), "sliding_window": ("SLIDING_WINDOW_OPTS",), } }
RETURN_TYPES = ("INT", "INT", "INT", "INT") RETURN_NAMES = ("frame_number", "_1/2-1_index", "_1/2_index", "end_index") FUNCTION = "calculate" CATEGORY = "Animate Diff"
def get_batch_count(self, frame_number, context_scheduler, ctx): batches = list( context_scheduler( 0, 0, frame_number, ctx.context_length, ctx.context_stride, ctx.context_overlap, ctx.closed_loop, ) ) batch_count = len(batches) if len(batches[-1]) == 0: batch_count -= 1
return batch_count
def calculate(self, frame_rate: int, duration: int, sliding_window): frame_number = frame_rate * duration
ctx = sliding_window context_scheduler = get_context_scheduler(ctx.context_schedule) batch_count = self.get_batch_count(frame_number, context_scheduler, ctx)
while True: next_batch_count = self.get_batch_count(frame_number + 1, context_scheduler, ctx) if next_batch_count > batch_count: break
frame_number += 1
snd_half_start = frame_number // 2 + frame_number % 2 fst_half_end = snd_half_start - 1 return (frame_number, fst_half_end, snd_half_start, frame_number - 1)
NODE_CLASS_MAPPINGS["AnimateDiffFrameCalculator"] = AnimateDiffFrameCalculator NODE_DISPLAY_NAME_MAPPINGS["AnimateDiffFrameCalculator"] = "Animate Diff Frame Calculator"
except Exception as e: print(e)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337from typing import List
import folder_pathsfrom nodes import ControlNetLoader, ControlNetApply, ControlNetApplyAdvanced
from .preprocessor import preprocessors, apply_preprocessorfrom .advanced import comfy_load_controlnet
def load_controlnet(control_net_name, control_net_override="None", timestep_keyframe=None): if control_net_override != "None": if control_net_override not in folder_paths.get_filename_list("controlnet"): print(f"Warning: Not found ControlNet model {control_net_override}. Use {control_net_name} instead.") else: control_net_name = control_net_override
if control_net_name == "None": return None
return comfy_load_controlnet(control_net_name, timestep_keyframe=timestep_keyframe)
def detect_controlnet(preprocessor: str, sd_version: str): controlnets = folder_paths.get_filename_list("controlnet") controlnets = filter(lambda x: sd_version in x, controlnets) if sd_version == "sdxl": controlnets = filter(lambda x: "t2i" not in x, controlnets) controlnets = filter(lambda x: "lllite" not in x, controlnets)
control_net_name = "None" if preprocessor in {"canny", "scribble", "mlsd"}: control_net_name = next((c for c in controlnets if preprocessor in c), "None") if preprocessor in {"scribble", "scribble_hed"}: control_net_name = next((c for c in controlnets if "scribble" in c), "None") if preprocessor in {"lineart", "lineart_coarse"}: control_net_name = next((c for c in controlnets if "lineart." in c), "None") if preprocessor in {"lineart_anime", "lineart_manga"}: control_net_name = next((c for c in controlnets if "lineart_anime" in c), "None") if preprocessor in {"hed", "hed_safe", "pidi", "pidi_safe"}: control_net_name = next((c for c in controlnets if "softedge" in c), "None") if preprocessor in {"pose", "openpose", "dwpose"}: control_net_name = next((c for c in controlnets if "openpose" in c), "None") if preprocessor in {"normalmap_bae", "normalmap_midas"}: control_net_name = next((c for c in controlnets if "normalbae" in c), "None") if preprocessor in {"depth", "depth_midas", "depth_zoe"}: control_net_name = next((c for c in controlnets if "depth" in c), "None") if preprocessor in {"seg_ofcoco", "seg_ofade20k", "seg_ufade20k"}: control_net_name = next((c for c in controlnets if "seg" in c), "None")
if preprocessor in {"tile"}: control_net_name = next((c for c in controlnets if "tile" in c), "None")
return control_net_name
class AVControlNetLoader(ControlNetLoader): @classmethod def INPUT_TYPES(s): return { "required": {"control_net_name": (folder_paths.get_filename_list("controlnet"),)}, "optional": { "control_net_override": ("STRING", {"default": "None"}), "timestep_keyframe": ("TIMESTEP_KEYFRAME",), }, }
RETURN_TYPES = ("CONTROL_NET",) FUNCTION = "load_controlnet" CATEGORY = "Art Venture/Loaders"
def load_controlnet(self, control_net_name, control_net_override="None", timestep_keyframe=None): return load_controlnet(control_net_name, control_net_override, timestep_keyframe=timestep_keyframe)
class AV_ControlNetPreprocessor: @classmethod def INPUT_TYPES(s): return { "required": { "image": ("IMAGE",), "preprocessor": (["None"] + preprocessors,), "sd_version": (["sd15", "sdxl"],), }, "optional": { "resolution": ("INT", {"default": 512, "min": 64, "max": 2048, "step": 64}), "preprocessor_override": ("STRING", {"default": "None"}), }, }
RETURN_TYPES = ("IMAGE", "STRING") RETURN_NAMES = ("IMAGE", "CNET_NAME") FUNCTION = "detect_controlnet" CATEGORY = "Art Venture/Loaders"
def detect_controlnet(self, image, preprocessor, sd_version, resolution=512, preprocessor_override="None"): if preprocessor_override != "None": if preprocessor_override not in preprocessors: print( f"Warning: Not found ControlNet preprocessor {preprocessor_override}. Use {preprocessor} instead." ) else: preprocessor = preprocessor_override
image = apply_preprocessor(image, preprocessor, resolution=resolution) control_net_name = detect_controlnet(preprocessor, sd_version)
return (image, control_net_name)
class AVControlNetEfficientStacker: controlnets = folder_paths.get_filename_list("controlnet")
@classmethod def INPUT_TYPES(s): return { "required": { "control_net_name": (["None", "Auto: sd15", "Auto: sdxl", "Auto: sdxl_t2i"] + s.controlnets,), "image": ("IMAGE",), "strength": ( "FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}, ), "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}), "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}), "preprocessor": (["None"] + preprocessors,), }, "optional": { "cnet_stack": ("CONTROL_NET_STACK",), "control_net_override": ("STRING", {"default": "None"}), "timestep_keyframe": ("TIMESTEP_KEYFRAME",), "resolution": ("INT", {"default": 512, "min": 64, "max": 2048, "step": 64}), "enabled": ("BOOLEAN", {"default": True}), }, }
RETURN_TYPES = ("CONTROL_NET_STACK",) RETURN_NAMES = ("CNET_STACK",) FUNCTION = "control_net_stacker" CATEGORY = "Art Venture/Loaders"
def control_net_stacker( self, control_net_name: str, image, strength, start_percent, end_percent, preprocessor, cnet_stack=None, control_net_override="None", timestep_keyframe=None, resolution=512, enabled=True, ): if not enabled: return (cnet_stack,)
# If control_net_stack is None, initialize as an empty list if cnet_stack is None: cnet_stack = []
if control_net_name.startswith("Auto: "): assert preprocessor != "None", "preprocessor must be set when using Auto mode"
sd_version = control_net_name[len("Auto: ") :] control_net_name = detect_controlnet(preprocessor, sd_version)
control_net = load_controlnet(control_net_name, control_net_override, timestep_keyframe=timestep_keyframe)
# Extend the control_net_stack with the new tuple if control_net is not None: image = apply_preprocessor(image, preprocessor, resolution=resolution) cnet_stack.extend([(control_net, image, strength, start_percent, end_percent)])
return (cnet_stack,)
class AVControlNetEfficientStackerSimple(AVControlNetEfficientStacker): @classmethod def INPUT_TYPES(s): return { "required": { "control_net_name": (["None", "Auto: sd15", "Auto: sdxl", "Auto: sdxl_t2i"] + s.controlnets,), "image": ("IMAGE",), "strength": ( "FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}, ), "preprocessor": (["None"] + preprocessors,), }, "optional": { "cnet_stack": ("CONTROL_NET_STACK",), "control_net_override": ("STRING", {"default": "None"}), "timestep_keyframe": ("TIMESTEP_KEYFRAME",), "resolution": ("INT", {"default": 512, "min": 64, "max": 2048, "step": 64}), "enabled": ("BOOLEAN", {"default": True}), }, }
FUNCTION = "control_net_stacker_simple"
def control_net_stacker_simple( self, *args, **kwargs, ): return self.control_net_stacker(*args, start_percent=0.0, end_percent=1.0, **kwargs)
class AVControlNetEfficientLoader(ControlNetApply): controlnets = folder_paths.get_filename_list("controlnet")
@classmethod def INPUT_TYPES(s): return { "required": { "control_net_name": (["None"] + s.controlnets,), "conditioning": ("CONDITIONING",), "image": ("IMAGE",), "strength": ( "FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}, ), "preprocessor": (["None"] + preprocessors,), }, "optional": { "control_net_override": ("STRING", {"default": "None"}), "timestep_keyframe": ("TIMESTEP_KEYFRAME",), "resolution": ("INT", {"default": 512, "min": 64, "max": 2048, "step": 64}), "enabled": ("BOOLEAN", {"default": True}), }, }
RETURN_TYPES = ("CONDITIONING",) FUNCTION = "load_controlnet" CATEGORY = "Art Venture/Loaders"
def load_controlnet( self, control_net_name, conditioning, image, strength, preprocessor, control_net_override="None", timestep_keyframe=None, resolution=512, enabled=True, ): if not enabled: return (conditioning,)
control_net = load_controlnet(control_net_name, control_net_override, timestep_keyframe=timestep_keyframe) if control_net is None: return (conditioning,)
image = apply_preprocessor(image, preprocessor, resolution=resolution)
return super().apply_controlnet(conditioning, control_net, image, strength)
class AVControlNetEfficientLoaderAdvanced(ControlNetApplyAdvanced): controlnets = folder_paths.get_filename_list("controlnet")
@classmethod def INPUT_TYPES(s): return { "required": { "control_net_name": (["None"] + s.controlnets,), "positive": ("CONDITIONING",), "negative": ("CONDITIONING",), "image": ("IMAGE",), "strength": ( "FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}, ), "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}), "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}), "preprocessor": (["None"] + preprocessors,), }, "optional": { "control_net_override": ("STRING", {"default": "None"}), "timestep_keyframe": ("TIMESTEP_KEYFRAME",), "resolution": ("INT", {"default": 512, "min": 64, "max": 2048, "step": 64}), "enabled": ("BOOLEAN", {"default": True}), }, }
RETURN_TYPES = ("CONDITIONING", "CONDITIONING") RETURN_NAMES = ("positive", "negative") FUNCTION = "load_controlnet" CATEGORY = "Art Venture/Loaders"
def load_controlnet( self, control_net_name, positive, negative, image, strength, start_percent, end_percent, preprocessor, control_net_override="None", timestep_keyframe=None, resolution=512, enabled=True, ): if not enabled: return (positive, negative)
control_net = load_controlnet(control_net_name, control_net_override, timestep_keyframe=timestep_keyframe) if control_net is None: return (positive, negative)
image = apply_preprocessor(image, preprocessor, resolution=resolution)
return super().apply_controlnet(positive, negative, control_net, image, strength, start_percent, end_percent)
NODE_CLASS_MAPPINGS = { "AV_ControlNetLoader": AVControlNetLoader, "AV_ControlNetEfficientLoader": AVControlNetEfficientLoader, "AV_ControlNetEfficientLoaderAdvanced": AVControlNetEfficientLoaderAdvanced, "AV_ControlNetEfficientStacker": AVControlNetEfficientStacker, "AV_ControlNetEfficientStackerSimple": AVControlNetEfficientStackerSimple, "AV_ControlNetPreprocessor": AV_ControlNetPreprocessor,}
NODE_DISPLAY_NAME_MAPPINGS = { "AV_ControlNetLoader": "ControlNet Loader", "AV_ControlNetEfficientLoader": "ControlNet Loader", "AV_ControlNetEfficientLoaderAdvanced": "ControlNet Loader Adv.", "AV_ControlNetEfficientStacker": "ControlNet Stacker Adv.", "AV_ControlNetEfficientStackerSimple": "ControlNet Stacker", "AV_ControlNetPreprocessor": "ControlNet Preprocessor",}1234567891011121314151617181920212223242526272829303132333435363738394041424344import osfrom typing import Dict
import folder_pathsimport comfy.sdimport comfy.controlnet
from ..utils import load_module
custom_nodes = folder_paths.get_folder_paths("custom_nodes")advanced_cnet_dir_names = ["AdvancedControlNet", "ComfyUI-Advanced-ControlNet"]
def comfy_load_controlnet(control_net_name: str, **_): controlnet_path = folder_paths.get_full_path("controlnet", control_net_name) return comfy.controlnet.load_controlnet(controlnet_path)
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 advanced_cnet_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 AdvancedControlNet nodes")
module = load_module(module_path) print("Loaded AdvancedControlNet nodes from", module_path)
nodes: Dict = getattr(module, "NODE_CLASS_MAPPINGS") ControlNetLoaderAdvanced = nodes["ControlNetLoaderAdvanced"]
loader = ControlNetLoaderAdvanced()
def comfy_load_controlnet(control_net_name: str, timestep_keyframe=None): return loader.load_controlnet(control_net_name, timestep_keyframe=timestep_keyframe)[0]
except Exception as e: print(e)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106import osfrom typing import Dict
import folder_paths
from ..utils import load_module
custom_nodes = folder_paths.get_folder_paths("custom_nodes")preprocessors_dir_names = ["ControlNetPreprocessors", "comfyui_controlnet_aux"]
preprocessors: list[str] = []_preprocessors_map = { "canny": "CannyEdgePreprocessor", "canny_pyra": "PyraCannyPreprocessor", "lineart": "LineArtPreprocessor", "lineart_anime": "AnimeLineArtPreprocessor", "lineart_manga": "Manga2Anime_LineArt_Preprocessor", "lineart_any": "AnyLineArtPreprocessor_aux", "scribble": "ScribblePreprocessor", "scribble_xdog": "Scribble_XDoG_Preprocessor", "scribble_pidi": "Scribble_PiDiNet_Preprocessor", "scribble_hed": "FakeScribblePreprocessor", "hed": "HEDPreprocessor", "pidi": "PiDiNetPreprocessor", "mlsd": "M-LSDPreprocessor", "pose": "DWPreprocessor", "openpose": "OpenposePreprocessor", "dwpose": "DWPreprocessor", "pose_dense": "DensePosePreprocessor", "pose_animal": "AnimalPosePreprocessor", "normalmap_bae": "BAE-NormalMapPreprocessor", "normalmap_dsine": "DSINE-NormalMapPreprocessor", "normalmap_midas": "MiDaS-NormalMapPreprocessor", "depth": "DepthAnythingV2Preprocessor", "depth_anything": "DepthAnythingPreprocessor", "depth_anything_v2": "DepthAnythingV2Preprocessor", "depth_anything_zoe": "Zoe_DepthAnythingPreprocessor", "depth_zoe": "Zoe-DepthMapPreprocessor", "depth_midas": "MiDaS-DepthMapPreprocessor", "depth_leres": "LeReS-DepthMapPreprocessor", "depth_metric3d": "Metric3D-DepthMapPreprocessor", "depth_meshgraphormer": "MeshGraphormer-DepthMapPreprocessor", "seg_ofcoco": "OneFormer-COCO-SemSegPreprocessor", "seg_ofade20k": "OneFormer-ADE20K-SemSegPreprocessor", "seg_ufade20k": "UniFormer-SemSegPreprocessor", "seg_animeface": "AnimeFace_SemSegPreprocessor", "shuffle": "ShufflePreprocessor", "teed": "TEEDPreprocessor", "color": "ColorPreprocessor", "sam": "SAMPreprocessor", "tile": "TilePreprocessor"}
def apply_preprocessor(image, preprocessor, resolution=512): raise NotImplementedError("apply_preprocessor is not implemented")
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 preprocessors_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 ControlNetPreprocessors nodes")
module = load_module(module_path) print("Loaded ControlNetPreprocessors nodes from", module_path)
nodes: Dict = getattr(module, "NODE_CLASS_MAPPINGS") available_preprocessors: list[str] = getattr(module, "PREPROCESSOR_OPTIONS")
AIO_Preprocessor = nodes.get("AIO_Preprocessor", None) if AIO_Preprocessor is None: raise Exception("Could not find AIO_Preprocessor node")
for name, preprocessor in _preprocessors_map.items(): if preprocessor in available_preprocessors: preprocessors.append(name)
aio_preprocessor = AIO_Preprocessor()
def apply_preprocessor(image, preprocessor, resolution=512): if preprocessor == "None": return image
if preprocessor not in preprocessors: raise Exception(f"Preprocessor {preprocessor} is not implemented")
preprocessor_cls = _preprocessors_map[preprocessor] args = {"preprocessor": preprocessor_cls, "image": image, "resolution": resolution}
function_name = AIO_Preprocessor.FUNCTION res = getattr(aio_preprocessor, function_name)(**args) if isinstance(res, dict): res = res["result"]
return res[0]
except Exception as e: print(e)ComfyLiterals/js/operation-node.jsAdded+83
ComfyUI-Crystools/docs/menu.pngAdded

ComfyUI-Crystools/docs/monitor-settings.pngAdded

ComfyUI-Crystools/docs/monitor.pngAdded

ComfyUI-Crystools/docs/primitives.pngAdded

ComfyUI-Crystools/docs/progress-bar.pngAdded

ComfyUI-Crystools/docs/screwdriver.pngAdded

ComfyUI-Crystools/docs/shortcut.pngAdded

ComfyUI-Crystools/docs/switches.pngAdded

ComfyUI-Crystools/general/__init__.pyAdded+3
ComfyUI-Crystools/general/__pycache__/__init__.cpython-310.pycAdded
ComfyUI-Crystools/general/__pycache__/gpu.cpython-310.pycAdded
ComfyUI-Crystools/general/__pycache__/hardware.cpython-310.pycAdded
ComfyUI-Crystools/general/__pycache__/hdd.cpython-310.pycAdded
ComfyUI-Crystools/general/__pycache__/monitor.cpython-310.pycAdded
ComfyUI-Crystools/general/gpu.pyAdded+300
ComfyUI-Crystools/general/hardware.pyAdded+132
ComfyUI-Crystools/general/hdd.pyAdded+10
ComfyUI-Crystools/general/monitor.pyAdded+67
ComfyUI-Crystools/nodes/__init__.pyAdded+1
ComfyUI-Crystools/nodes/__pycache__/debugger.cpython-310.pycAdded
ComfyUI-Crystools/nodes/__pycache__/image.cpython-310.pycAdded
ComfyUI-Crystools/nodes/__pycache__/list.cpython-310.pycAdded
ComfyUI-Crystools/nodes/__pycache__/metadata.cpython-310.pycAdded
ComfyUI-Crystools/nodes/__pycache__/parameters.cpython-310.pycAdded
ComfyUI-Crystools/nodes/__pycache__/pipe.cpython-310.pycAdded
ComfyUI-Crystools/nodes/__pycache__/primitive.cpython-310.pycAdded
ComfyUI-Crystools/nodes/__pycache__/utils.cpython-310.pycAdded
ComfyUI-Crystools/nodes/_names.pyAdded+80
ComfyUI-Crystools/nodes/debugger.pyAdded+123
ComfyUI-Crystools/nodes/image.pyAdded+517
ComfyUI-Crystools/nodes/list.pyAdded+149
ComfyUI-Crystools/nodes/metadata.pyAdded+164
ComfyUI-Crystools/nodes/parameters.pyAdded+170
ComfyUI-Crystools/nodes/pipe.pyAdded+74
ComfyUI-Crystools/nodes/primitive.pyAdded+111
ComfyUI-Crystools/nodes/utils.pyAdded+55
comfyui-art-venture/.github/workflows/publish.ymlAdded+25
comfyui-art-venture/.trackingAdded+69
comfyui-art-venture/README.mdAdded+217
comfyui-art-venture/__init__.pyAdded+17
comfyui-art-venture/config.pyAdded+68
comfyui-art-venture/modules/animatediff/__init__.pyAdded+89
comfyui-art-venture/modules/animatediff/__pycache__/__init__.cpython-310.pycAdded
comfyui-art-venture/modules/controlnet/__init__.pyAdded+337
comfyui-art-venture/modules/controlnet/__pycache__/__init__.cpython-310.pycAdded
comfyui-art-venture/modules/controlnet/__pycache__/advanced.cpython-310.pycAdded
comfyui-art-venture/modules/controlnet/__pycache__/preprocessor.cpython-310.pycAdded
comfyui-art-venture/modules/controlnet/advanced.pyAdded+44
comfyui-art-venture/modules/controlnet/preprocessor.pyAdded+106