diff --git a/ComfyLiterals/js/operation-node.js b/ComfyLiterals/js/operation-node.js new file mode 100644 index 0000000000000000000000000000000000000000..89376b0242a64eb2411f1508c7a4d1b70673e5fa --- /dev/null +++ b/ComfyLiterals/js/operation-node.js @@ -0,0 +1,83 @@ +import {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} + */ + 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; +} diff --git a/ComfyUI-Crystools/docs/menu.png b/ComfyUI-Crystools/docs/menu.png new file mode 100644 index 0000000000000000000000000000000000000000..9dab29a03352998b96fbc20094e9268ad31b1835 Binary files /dev/null and b/ComfyUI-Crystools/docs/menu.png differ diff --git a/ComfyUI-Crystools/docs/monitor-settings.png b/ComfyUI-Crystools/docs/monitor-settings.png new file mode 100644 index 0000000000000000000000000000000000000000..1c5078258ba6a03cc20a412e305b98d06c3bd238 Binary files /dev/null and b/ComfyUI-Crystools/docs/monitor-settings.png differ diff --git a/ComfyUI-Crystools/docs/monitor.png b/ComfyUI-Crystools/docs/monitor.png new file mode 100644 index 0000000000000000000000000000000000000000..1c1ca80680867d897a25fdd62b9aea80e1191100 Binary files /dev/null and b/ComfyUI-Crystools/docs/monitor.png differ diff --git a/ComfyUI-Crystools/docs/primitives.png b/ComfyUI-Crystools/docs/primitives.png new file mode 100644 index 0000000000000000000000000000000000000000..373a913ef671edb3570594434961c0f5159cf477 Binary files /dev/null and b/ComfyUI-Crystools/docs/primitives.png differ diff --git a/ComfyUI-Crystools/docs/progress-bar.png b/ComfyUI-Crystools/docs/progress-bar.png new file mode 100644 index 0000000000000000000000000000000000000000..7ed6050f22c69db39632a121f3c89202e8a39df8 Binary files /dev/null and b/ComfyUI-Crystools/docs/progress-bar.png differ diff --git a/ComfyUI-Crystools/docs/screwdriver.png b/ComfyUI-Crystools/docs/screwdriver.png new file mode 100644 index 0000000000000000000000000000000000000000..61a05747f309e5839bc3eab633be3153f06a23fe Binary files /dev/null and b/ComfyUI-Crystools/docs/screwdriver.png differ diff --git a/ComfyUI-Crystools/docs/shortcut.png b/ComfyUI-Crystools/docs/shortcut.png new file mode 100644 index 0000000000000000000000000000000000000000..a1941639e58861d0aa9eda5e8e0ded52a6c4368f Binary files /dev/null and b/ComfyUI-Crystools/docs/shortcut.png differ diff --git a/ComfyUI-Crystools/docs/switches.png b/ComfyUI-Crystools/docs/switches.png new file mode 100644 index 0000000000000000000000000000000000000000..dfc6aca18e6341fe6c88954e3a46993103b1ac3c Binary files /dev/null and b/ComfyUI-Crystools/docs/switches.png differ diff --git a/ComfyUI-Crystools/general/__init__.py b/ComfyUI-Crystools/general/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..572455122938729d93223ec2a4218f27900be17d --- /dev/null +++ b/ComfyUI-Crystools/general/__init__.py @@ -0,0 +1,3 @@ +from .monitor import * +from .hdd import * +from .gpu import * diff --git a/ComfyUI-Crystools/general/__pycache__/__init__.cpython-310.pyc b/ComfyUI-Crystools/general/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa20d930e4ce9c3bb5193681dd1e5fb8c06dc523 Binary files /dev/null and b/ComfyUI-Crystools/general/__pycache__/__init__.cpython-310.pyc differ diff --git a/ComfyUI-Crystools/general/__pycache__/gpu.cpython-310.pyc b/ComfyUI-Crystools/general/__pycache__/gpu.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..993eae7394f121c7575b84e0648c68783d611272 Binary files /dev/null and b/ComfyUI-Crystools/general/__pycache__/gpu.cpython-310.pyc differ diff --git a/ComfyUI-Crystools/general/__pycache__/hardware.cpython-310.pyc b/ComfyUI-Crystools/general/__pycache__/hardware.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d445700734c236c951e22131ff81a0fb3ac9ebb7 Binary files /dev/null and b/ComfyUI-Crystools/general/__pycache__/hardware.cpython-310.pyc differ diff --git a/ComfyUI-Crystools/general/__pycache__/hdd.cpython-310.pyc b/ComfyUI-Crystools/general/__pycache__/hdd.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e0c2fe2809ef112b50e0b6248a3133e9f308883 Binary files /dev/null and b/ComfyUI-Crystools/general/__pycache__/hdd.cpython-310.pyc differ diff --git a/ComfyUI-Crystools/general/__pycache__/monitor.cpython-310.pyc b/ComfyUI-Crystools/general/__pycache__/monitor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6aea9013e222e48fa73c62256902f8ca8a246db8 Binary files /dev/null and b/ComfyUI-Crystools/general/__pycache__/monitor.cpython-310.pyc differ diff --git a/ComfyUI-Crystools/general/gpu.py b/ComfyUI-Crystools/general/gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..f080bfd94521391d42e888157336f7e5c1030bd7 --- /dev/null +++ b/ComfyUI-Crystools/general/gpu.py @@ -0,0 +1,300 @@ +import 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() diff --git a/ComfyUI-Crystools/general/hardware.py b/ComfyUI-Crystools/general/hardware.py new file mode 100644 index 0000000000000000000000000000000000000000..f7430a74b22fb5fed40831488817230762790650 --- /dev/null +++ b/ComfyUI-Crystools/general/hardware.py @@ -0,0 +1,132 @@ +import 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'], + } diff --git a/ComfyUI-Crystools/general/hdd.py b/ComfyUI-Crystools/general/hdd.py new file mode 100644 index 0000000000000000000000000000000000000000..420d1dae8273b3b420351fc982154c7577b1e0a4 --- /dev/null +++ b/ComfyUI-Crystools/general/hdd.py @@ -0,0 +1,10 @@ +import psutil +from ..core import logger + +def getDrivesInfo(): + hdds = [] + logger.debug('Getting HDDs info...') + for partition in psutil.disk_partitions(): + hdds.append(partition.mountpoint) + + return hdds diff --git a/ComfyUI-Crystools/general/monitor.py b/ComfyUI-Crystools/general/monitor.py new file mode 100644 index 0000000000000000000000000000000000000000..58b7cac9adf49f1b36248dad635400f9d03a53c0 --- /dev/null +++ b/ComfyUI-Crystools/general/monitor.py @@ -0,0 +1,67 @@ +import 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) + diff --git a/ComfyUI-Crystools/nodes/__init__.py b/ComfyUI-Crystools/nodes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..39dff2cc94a3b752cf8ba2cfb50524a1933065a5 --- /dev/null +++ b/ComfyUI-Crystools/nodes/__init__.py @@ -0,0 +1 @@ +# intentionally left blank diff --git a/ComfyUI-Crystools/nodes/__pycache__/debugger.cpython-310.pyc b/ComfyUI-Crystools/nodes/__pycache__/debugger.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fca966c5f0091e79d59771745aa702c6fecce82a Binary files /dev/null and b/ComfyUI-Crystools/nodes/__pycache__/debugger.cpython-310.pyc differ diff --git a/ComfyUI-Crystools/nodes/__pycache__/image.cpython-310.pyc b/ComfyUI-Crystools/nodes/__pycache__/image.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea0e4d16839391347dc8ed4ef8a32487b4d0f1ba Binary files /dev/null and b/ComfyUI-Crystools/nodes/__pycache__/image.cpython-310.pyc differ diff --git a/ComfyUI-Crystools/nodes/__pycache__/list.cpython-310.pyc b/ComfyUI-Crystools/nodes/__pycache__/list.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53322ed4b9090fa09ca79d65752e0fd23715293c Binary files /dev/null and b/ComfyUI-Crystools/nodes/__pycache__/list.cpython-310.pyc differ diff --git a/ComfyUI-Crystools/nodes/__pycache__/metadata.cpython-310.pyc b/ComfyUI-Crystools/nodes/__pycache__/metadata.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bd23a2816a4db2a394c44a3282325953656473c Binary files /dev/null and b/ComfyUI-Crystools/nodes/__pycache__/metadata.cpython-310.pyc differ diff --git a/ComfyUI-Crystools/nodes/__pycache__/parameters.cpython-310.pyc b/ComfyUI-Crystools/nodes/__pycache__/parameters.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b3046cb0a01dbfa4566b39601ae14e5fc3f5122 Binary files /dev/null and b/ComfyUI-Crystools/nodes/__pycache__/parameters.cpython-310.pyc differ diff --git a/ComfyUI-Crystools/nodes/__pycache__/pipe.cpython-310.pyc b/ComfyUI-Crystools/nodes/__pycache__/pipe.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d162704b6d6e0656af924b3dd06174220c06ce4 Binary files /dev/null and b/ComfyUI-Crystools/nodes/__pycache__/pipe.cpython-310.pyc differ diff --git a/ComfyUI-Crystools/nodes/__pycache__/primitive.cpython-310.pyc b/ComfyUI-Crystools/nodes/__pycache__/primitive.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f421b627f84013c05c3779fa4b18c641f72c351 Binary files /dev/null and b/ComfyUI-Crystools/nodes/__pycache__/primitive.cpython-310.pyc differ diff --git a/ComfyUI-Crystools/nodes/__pycache__/utils.cpython-310.pyc b/ComfyUI-Crystools/nodes/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f481e06f3318dc4b4f288335bb3d2bcc3090b105 Binary files /dev/null and b/ComfyUI-Crystools/nodes/__pycache__/utils.cpython-310.pyc differ diff --git a/ComfyUI-Crystools/nodes/_names.py b/ComfyUI-Crystools/nodes/_names.py new file mode 100644 index 0000000000000000000000000000000000000000..a53faeaf0e629fd5c1dbec6478eb93326cbe705b --- /dev/null +++ b/ComfyUI-Crystools/nodes/_names.py @@ -0,0 +1,80 @@ +from 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)' diff --git a/ComfyUI-Crystools/nodes/debugger.py b/ComfyUI-Crystools/nodes/debugger.py new file mode 100644 index 0000000000000000000000000000000000000000..6b0cd3b3924311837cfa2f759efccbb97b486944 --- /dev/null +++ b/ComfyUI-Crystools/nodes/debugger.py @@ -0,0 +1,123 @@ +import 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,)} diff --git a/ComfyUI-Crystools/nodes/image.py b/ComfyUI-Crystools/nodes/image.py new file mode 100644 index 0000000000000000000000000000000000000000..10caabc07db7094eca5929b0b25af6ce29aaa6fb --- /dev/null +++ b/ComfyUI-Crystools/nodes/image.py @@ -0,0 +1,517 @@ +import 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 text diff --git a/ComfyUI-Crystools/nodes/list.py b/ComfyUI-Crystools/nodes/list.py new file mode 100644 index 0000000000000000000000000000000000000000..9f3b432863258d328f1c4e1fce79b23ed64e03e7 --- /dev/null +++ b/ComfyUI-Crystools/nodes/list.py @@ -0,0 +1,149 @@ +from ..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] diff --git a/ComfyUI-Crystools/nodes/metadata.py b/ComfyUI-Crystools/nodes/metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..26eb80d6872af10bff1d6c522362be2bdfd2387f --- /dev/null +++ b/ComfyUI-Crystools/nodes/metadata.py @@ -0,0 +1,164 @@ +import 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,)} diff --git a/ComfyUI-Crystools/nodes/parameters.py b/ComfyUI-Crystools/nodes/parameters.py new file mode 100644 index 0000000000000000000000000000000000000000..e6bfdb8f97e36a2ed5c9405cca7412351002a06d --- /dev/null +++ b/ComfyUI-Crystools/nodes/parameters.py @@ -0,0 +1,170 @@ +import 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 + } diff --git a/ComfyUI-Crystools/nodes/pipe.py b/ComfyUI-Crystools/nodes/pipe.py new file mode 100644 index 0000000000000000000000000000000000000000..22bf4135e570b45d4679e7da4f91b4a301223802 --- /dev/null +++ b/ComfyUI-Crystools/nodes/pipe.py @@ -0,0 +1,74 @@ +from ..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_6 diff --git a/ComfyUI-Crystools/nodes/primitive.py b/ComfyUI-Crystools/nodes/primitive.py new file mode 100644 index 0000000000000000000000000000000000000000..ae4d4d684b5a1ca4cd3b9bf2b9aafb9f5f61fa0a --- /dev/null +++ b/ComfyUI-Crystools/nodes/primitive.py @@ -0,0 +1,111 @@ +from ..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,) diff --git a/ComfyUI-Crystools/nodes/utils.py b/ComfyUI-Crystools/nodes/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..051896afddc63984dc4609d86f34d71185085330 --- /dev/null +++ b/ComfyUI-Crystools/nodes/utils.py @@ -0,0 +1,55 @@ +from ..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,)} diff --git a/comfyui-art-venture/.github/workflows/publish.yml b/comfyui-art-venture/.github/workflows/publish.yml new file mode 100644 index 0000000000000000000000000000000000000000..6856479645e83018523f9bd71422ad8e2ee24d28 --- /dev/null +++ b/comfyui-art-venture/.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 == '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 }} diff --git a/comfyui-art-venture/.tracking b/comfyui-art-venture/.tracking new file mode 100644 index 0000000000000000000000000000000000000000..13f0cc5d2f086b851a5988d0732cfbda9d28d285 --- /dev/null +++ b/comfyui-art-venture/.tracking @@ -0,0 +1,69 @@ +.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.js \ No newline at end of file diff --git a/comfyui-art-venture/README.md b/comfyui-art-venture/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8f473bce9adc2da3e386432e2d032573bee81478 --- /dev/null +++ b/comfyui-art-venture/README.md @@ -0,0 +1,217 @@ +# 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. + +![load image from url](https://github.com/user-attachments/assets/9da4840c-925e-4e0c-984a-5412282aee79) + +### 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. + +![get data from json](https://github.com/user-attachments/assets/a71793d6-9661-441c-a15c-66b2dcaa7972) + +### 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 + +![text random multiline](https://github.com/user-attachments/assets/86f811e3-579e-4ccc-81a3-e216cd851d3c) + +#### 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 `casevalue`, 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. + +![text switch case](https://github.com/user-attachments/assets/4c5450a8-6a3a-4d3c-8c2a-c6e3a33cb95f) + +### 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) + +![inpaiting prepare](https://github.com/user-attachments/assets/38e87c04-7a64-4a62-a462-054396b3de14) + +#### 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. + +![lama remove object](https://github.com/user-attachments/assets/c28bbd8b-d55f-4fa5-bbc9-ace267382bd0) + +### 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 + +![Screenshot 2024-10-30 at 11 20 12](https://github.com/user-attachments/assets/45b8d4fd-57cd-4bd9-8274-d3e6ac4ef938) diff --git a/comfyui-art-venture/__init__.py b/comfyui-art-venture/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7938a3f024a4df66cf3b78574b65b0e08497bb7c --- /dev/null +++ b/comfyui-art-venture/__init__.py @@ -0,0 +1,17 @@ +import sys +import 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"] diff --git a/comfyui-art-venture/config.py b/comfyui-art-venture/config.py new file mode 100644 index 0000000000000000000000000000000000000000..541aab54b0dac9e072250b20616477e55c3d9701 --- /dev/null +++ b/comfyui-art-venture/config.py @@ -0,0 +1,68 @@ +import os +import json +import inspect +from 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() diff --git a/comfyui-art-venture/modules/animatediff/__init__.py b/comfyui-art-venture/modules/animatediff/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b976c3947ed61ae9be94101d98e0663d01cd0203 --- /dev/null +++ b/comfyui-art-venture/modules/animatediff/__init__.py @@ -0,0 +1,89 @@ +import os +from 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) diff --git a/comfyui-art-venture/modules/animatediff/__pycache__/__init__.cpython-310.pyc b/comfyui-art-venture/modules/animatediff/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93d9a9b1626d8026f42c666d08ee73f6d3325e02 Binary files /dev/null and b/comfyui-art-venture/modules/animatediff/__pycache__/__init__.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/controlnet/__init__.py b/comfyui-art-venture/modules/controlnet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c273faace57bc502257fc6591328c25894de64ef --- /dev/null +++ b/comfyui-art-venture/modules/controlnet/__init__.py @@ -0,0 +1,337 @@ +from typing import List + +import folder_paths +from nodes import ControlNetLoader, ControlNetApply, ControlNetApplyAdvanced + +from .preprocessor import preprocessors, apply_preprocessor +from .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", +} diff --git a/comfyui-art-venture/modules/controlnet/__pycache__/__init__.cpython-310.pyc b/comfyui-art-venture/modules/controlnet/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd157c6d9370f47226c57513305e0f8216b49b8d Binary files /dev/null and b/comfyui-art-venture/modules/controlnet/__pycache__/__init__.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/controlnet/__pycache__/advanced.cpython-310.pyc b/comfyui-art-venture/modules/controlnet/__pycache__/advanced.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6968cf8204e0dac1ed3168108d859ac8055a8a75 Binary files /dev/null and b/comfyui-art-venture/modules/controlnet/__pycache__/advanced.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/controlnet/__pycache__/preprocessor.cpython-310.pyc b/comfyui-art-venture/modules/controlnet/__pycache__/preprocessor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60f96c0867426ac1af5051047f15030b5b838c09 Binary files /dev/null and b/comfyui-art-venture/modules/controlnet/__pycache__/preprocessor.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/controlnet/advanced.py b/comfyui-art-venture/modules/controlnet/advanced.py new file mode 100644 index 0000000000000000000000000000000000000000..d8b4a4eb8f02d5de911e24e0f2cb05b6a6bb1c22 --- /dev/null +++ b/comfyui-art-venture/modules/controlnet/advanced.py @@ -0,0 +1,44 @@ +import os +from typing import Dict + +import folder_paths +import comfy.sd +import 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) diff --git a/comfyui-art-venture/modules/controlnet/preprocessor.py b/comfyui-art-venture/modules/controlnet/preprocessor.py new file mode 100644 index 0000000000000000000000000000000000000000..cdcace03365ee3f0faef25ed8e17d3216ab4c6c6 --- /dev/null +++ b/comfyui-art-venture/modules/controlnet/preprocessor.py @@ -0,0 +1,106 @@ +import os +from 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) diff --git a/comfyui-art-venture/modules/fooocus/__init__.py b/comfyui-art-venture/modules/fooocus/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e500a77b63742ce966a030a5f2d6baea2b84d254 --- /dev/null +++ b/comfyui-art-venture/modules/fooocus/__init__.py @@ -0,0 +1,67 @@ +from nodes import KSampler, KSamplerAdvanced + +from .patch import patch_all, unpatch_all +from .efficient import ( + NODE_CLASS_MAPPINGS as EFFICIENCY_NODE_CLASS_MAPPINGS, + NODE_DISPLAY_NAME_MAPPINGS as EFFICIENCY_NODE_DISPLAY_NAME_MAPPINGS, +) + + +class KSamplerWithSharpness(KSampler): + @classmethod + def INPUT_TYPES(cls): + inputs = KSampler.INPUT_TYPES() + inputs["optional"] = { + "sharpness": ( + "FLOAT", + {"default": 2.0, "min": 0.0, "max": 100.0, "step": 0.01}, + ) + } + + return inputs + + CATEGORY = "Art Venture/Sampling" + + def sample(self, *args, sharpness=2.0, **kwargs): + patch.sharpness = sharpness + patch_all() + results = super().sample(*args, **kwargs) + unpatch_all() + return results + + +class KSamplerAdvancedWithSharpness(KSamplerAdvanced): + @classmethod + def INPUT_TYPES(cls): + inputs = KSamplerAdvanced.INPUT_TYPES() + inputs["optional"] = { + "sharpness": ( + "FLOAT", + {"default": 2.0, "min": 0.0, "max": 100.0, "step": 0.01}, + ) + } + + return inputs + + CATEGORY = "Art Venture/Sampling" + + def sample(self, *args, sharpness=2.0, **kwargs): + patch.sharpness = sharpness + patch_all() + results = super().sample(*args, **kwargs) + unpatch_all() + return results + + +NODE_CLASS_MAPPINGS = { + "Fooocus_KSampler": KSamplerWithSharpness, + "Fooocus_KSamplerAdvanced": KSamplerAdvancedWithSharpness, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "Fooocus_KSampler": "KSampler Fooocus", + "Fooocus_KSamplerAdvanced": "KSampler Adv. Fooocus", +} + +NODE_CLASS_MAPPINGS.update(EFFICIENCY_NODE_CLASS_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(EFFICIENCY_NODE_DISPLAY_NAME_MAPPINGS) diff --git a/comfyui-art-venture/modules/fooocus/__pycache__/__init__.cpython-310.pyc b/comfyui-art-venture/modules/fooocus/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10d6e2babd2e4bcaa1a921c0b9364f9e665e60b9 Binary files /dev/null and b/comfyui-art-venture/modules/fooocus/__pycache__/__init__.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/fooocus/__pycache__/anisotropic.cpython-310.pyc b/comfyui-art-venture/modules/fooocus/__pycache__/anisotropic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ed837962c951426bae4d2c7134120413fd60638 Binary files /dev/null and b/comfyui-art-venture/modules/fooocus/__pycache__/anisotropic.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/fooocus/__pycache__/efficient.cpython-310.pyc b/comfyui-art-venture/modules/fooocus/__pycache__/efficient.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b76e415fce8852748687151d3b0732b5a34a0842 Binary files /dev/null and b/comfyui-art-venture/modules/fooocus/__pycache__/efficient.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/fooocus/__pycache__/patch.cpython-310.pyc b/comfyui-art-venture/modules/fooocus/__pycache__/patch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cdf1eb517c762a254ae86a85713bcede4b962898 Binary files /dev/null and b/comfyui-art-venture/modules/fooocus/__pycache__/patch.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/fooocus/anisotropic.py b/comfyui-art-venture/modules/fooocus/anisotropic.py new file mode 100644 index 0000000000000000000000000000000000000000..5771d036bcc0eeac0ba9d0773dc34fae488ddd63 --- /dev/null +++ b/comfyui-art-venture/modules/fooocus/anisotropic.py @@ -0,0 +1,223 @@ +import torch + + +Tensor = torch.Tensor +Device = torch.DeviceObjType +Dtype = torch.Type +pad = torch.nn.functional.pad + + +def _compute_zero_padding(kernel_size: tuple[int, int] | int) -> tuple[int, int]: + ky, kx = _unpack_2d_ks(kernel_size) + return (ky - 1) // 2, (kx - 1) // 2 + + +def _unpack_2d_ks(kernel_size: tuple[int, int] | int) -> tuple[int, int]: + if isinstance(kernel_size, int): + ky = kx = kernel_size + else: + assert len(kernel_size) == 2, "2D Kernel size should have a length of 2." + ky, kx = kernel_size + + ky = int(ky) + kx = int(kx) + return ky, kx + + +def gaussian( + window_size: int, + sigma: Tensor | float, + *, + device: Device | None = None, + dtype: Dtype | None = None, +) -> Tensor: + batch_size = sigma.shape[0] + + x = ( + torch.arange(window_size, device=sigma.device, dtype=sigma.dtype) + - window_size // 2 + ).expand(batch_size, -1) + + if window_size % 2 == 0: + x = x + 0.5 + + gauss = torch.exp(-x.pow(2.0) / (2 * sigma.pow(2.0))) + + return gauss / gauss.sum(-1, keepdim=True) + + +def get_gaussian_kernel1d( + kernel_size: int, + sigma: float | Tensor, + force_even: bool = False, + *, + device: Device | None = None, + dtype: Dtype | None = None, +) -> Tensor: + return gaussian(kernel_size, sigma, device=device, dtype=dtype) + + +def get_gaussian_kernel2d( + kernel_size: tuple[int, int] | int, + sigma: tuple[float, float] | Tensor, + force_even: bool = False, + *, + device: Device | None = None, + dtype: Dtype | None = None, +) -> Tensor: + sigma = torch.Tensor([[sigma, sigma]]).to(device=device, dtype=dtype) + + ksize_y, ksize_x = _unpack_2d_ks(kernel_size) + sigma_y, sigma_x = sigma[:, 0, None], sigma[:, 1, None] + + kernel_y = get_gaussian_kernel1d( + ksize_y, sigma_y, force_even, device=device, dtype=dtype + )[..., None] + kernel_x = get_gaussian_kernel1d( + ksize_x, sigma_x, force_even, device=device, dtype=dtype + )[..., None] + + return kernel_y * kernel_x.view(-1, 1, ksize_x) + + +def _bilateral_blur( + input: Tensor, + guidance: Tensor | None, + kernel_size: tuple[int, int] | int, + sigma_color: float | Tensor, + sigma_space: tuple[float, float] | Tensor, + border_type: str = "reflect", + color_distance_type: str = "l1", +) -> Tensor: + if isinstance(sigma_color, Tensor): + sigma_color = sigma_color.to(device=input.device, dtype=input.dtype).view( + -1, 1, 1, 1, 1 + ) + + ky, kx = _unpack_2d_ks(kernel_size) + pad_y, pad_x = _compute_zero_padding(kernel_size) + + padded_input = pad(input, (pad_x, pad_x, pad_y, pad_y), mode=border_type) + unfolded_input = ( + padded_input.unfold(2, ky, 1).unfold(3, kx, 1).flatten(-2) + ) # (B, C, H, W, Ky x Kx) + + if guidance is None: + guidance = input + unfolded_guidance = unfolded_input + else: + padded_guidance = pad(guidance, (pad_x, pad_x, pad_y, pad_y), mode=border_type) + unfolded_guidance = ( + padded_guidance.unfold(2, ky, 1).unfold(3, kx, 1).flatten(-2) + ) # (B, C, H, W, Ky x Kx) + + diff = unfolded_guidance - guidance.unsqueeze(-1) + if color_distance_type == "l1": + color_distance_sq = diff.abs().sum(1, keepdim=True).square() + elif color_distance_type == "l2": + color_distance_sq = diff.square().sum(1, keepdim=True) + else: + raise ValueError("color_distance_type only acceps l1 or l2") + color_kernel = ( + -0.5 / sigma_color**2 * color_distance_sq + ).exp() # (B, 1, H, W, Ky x Kx) + + space_kernel = get_gaussian_kernel2d( + kernel_size, sigma_space, device=input.device, dtype=input.dtype + ) + space_kernel = space_kernel.view(-1, 1, 1, 1, kx * ky) + + kernel = space_kernel * color_kernel + out = (unfolded_input * kernel).sum(-1) / kernel.sum(-1) + return out + + +def bilateral_blur( + input: Tensor, + kernel_size: tuple[int, int] | int = (13, 13), + sigma_color: float | Tensor = 3.0, + sigma_space: tuple[float, float] | Tensor = 3.0, + border_type: str = "reflect", + color_distance_type: str = "l1", +) -> Tensor: + return _bilateral_blur( + input, + None, + kernel_size, + sigma_color, + sigma_space, + border_type, + color_distance_type, + ) + + +def joint_bilateral_blur( + input: Tensor, + guidance: Tensor, + kernel_size: tuple[int, int] | int, + sigma_color: float | Tensor, + sigma_space: tuple[float, float] | Tensor, + border_type: str = "reflect", + color_distance_type: str = "l1", +) -> Tensor: + return _bilateral_blur( + input, + guidance, + kernel_size, + sigma_color, + sigma_space, + border_type, + color_distance_type, + ) + + +class _BilateralBlur(torch.nn.Module): + def __init__( + self, + kernel_size: tuple[int, int] | int, + sigma_color: float | Tensor, + sigma_space: tuple[float, float] | Tensor, + border_type: str = "reflect", + color_distance_type: str = "l1", + ) -> None: + super().__init__() + self.kernel_size = kernel_size + self.sigma_color = sigma_color + self.sigma_space = sigma_space + self.border_type = border_type + self.color_distance_type = color_distance_type + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}" + f"(kernel_size={self.kernel_size}, " + f"sigma_color={self.sigma_color}, " + f"sigma_space={self.sigma_space}, " + f"border_type={self.border_type}, " + f"color_distance_type={self.color_distance_type})" + ) + + +class BilateralBlur(_BilateralBlur): + def forward(self, input: Tensor) -> Tensor: + return bilateral_blur( + input, + self.kernel_size, + self.sigma_color, + self.sigma_space, + self.border_type, + self.color_distance_type, + ) + + +class JointBilateralBlur(_BilateralBlur): + def forward(self, input: Tensor, guidance: Tensor) -> Tensor: + return joint_bilateral_blur( + input, + guidance, + self.kernel_size, + self.sigma_color, + self.sigma_space, + self.border_type, + self.color_distance_type, + ) diff --git a/comfyui-art-venture/modules/fooocus/efficient.py b/comfyui-art-venture/modules/fooocus/efficient.py new file mode 100644 index 0000000000000000000000000000000000000000..9cd31364b07b4cf35709f0e17ee7e032e3e67a0d --- /dev/null +++ b/comfyui-art-venture/modules/fooocus/efficient.py @@ -0,0 +1,132 @@ +import os +from typing import Dict + +import folder_paths + +from . import patch +from ..utils import load_module + +custom_nodes = folder_paths.get_folder_paths("custom_nodes") +efficieny_dir_names = ["Efficiency", "efficiency-nodes-comfyui"] + +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 efficieny_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 efficiency nodes") + + module = load_module(module_path) + print("Loaded Efficiency nodes from", module_path) + + nodes: Dict = getattr(module, "NODE_CLASS_MAPPINGS") + + TSC_KSampler = nodes["KSampler (Efficient)"] + TSC_KSamplerAdvanced = nodes["KSampler Adv. (Efficient)"] + TSC_EfficientLoader = nodes["Efficient Loader"] + + class KSamplerEfficientWithSharpness(TSC_KSampler): + @classmethod + def INPUT_TYPES(cls): + inputs = TSC_KSampler.INPUT_TYPES() + inputs["optional"]["sharpness"] = ( + "FLOAT", + {"default": 2.0, "min": 0.0, "max": 100.0, "step": 0.01}, + ) + + return inputs + + CATEGORY = "Art Venture/Sampling" + + def sample(self, *args, sharpness=2.0, **kwargs): + patch.sharpness = sharpness + patch.patch_all() + results = super().sample(*args, **kwargs) + patch.unpatch_all() + return results + + class KSamplerEfficientAdvancedWithSharpness(TSC_KSamplerAdvanced): + @classmethod + def INPUT_TYPES(cls): + inputs = TSC_KSampler.INPUT_TYPES() + inputs["optional"]["sharpness"] = ( + "FLOAT", + {"default": 2.0, "min": 0.0, "max": 100.0, "step": 0.01}, + ) + + return inputs + + CATEGORY = "Art Venture/Sampling" + + def sampleadv(self, *args, sharpness=2.0, **kwargs): + patch.sharpness = sharpness + patch.patch_all() + results = super().sampleadv(*args, **kwargs) + patch.unpatch_all() + return results + + class AVCheckpointLoader(TSC_EfficientLoader): + @classmethod + def INPUT_TYPES(cls): + inputs = TSC_EfficientLoader.INPUT_TYPES() + inputs["optional"]["ckpt_override"] = ("STRING", {"default": "None"}) + inputs["optional"]["vae_override"] = ("STRING", {"default": "None"}) + inputs["optional"]["lora_override"] = ("STRING", {"default": "None"}) + return inputs + + CATEGORY = "Art Venture/Loaders" + + def efficientloader( + self, + ckpt_name, + vae_name, + clip_skip, + lora_name, + *args, + ckpt_override="None", + vae_override="None", + lora_override="None", + **kwargs + ): + if ckpt_override != "None": + ckpt_name = ckpt_override + if vae_override != "None": + vae_name = vae_override + if lora_override != "None": + lora_name = lora_override + + return super().efficientloader( + ckpt_name, vae_name, clip_skip, lora_name, *args, **kwargs + ) + + NODE_CLASS_MAPPINGS.update( + { + "Fooocus_KSamplerEfficient": KSamplerEfficientWithSharpness, + "Fooocus_KSamplerEfficientAdvanced": KSamplerEfficientAdvancedWithSharpness, + "AV_CheckpointLoader": AVCheckpointLoader, + } + ) + NODE_DISPLAY_NAME_MAPPINGS.update( + { + "Fooocus_KSamplerEfficient": "KSampler Efficient Fooocus", + "Fooocus_KSamplerEfficientAdvanced": "KSampler Adv. Efficient Fooocus", + "AV_CheckpointLoader": "Checkpoint Loader", + } + ) + + +except Exception as e: + print(e) diff --git a/comfyui-art-venture/modules/fooocus/patch.py b/comfyui-art-venture/modules/fooocus/patch.py new file mode 100644 index 0000000000000000000000000000000000000000..073457281ce3920f61715c07ee2c7c63fb1fb7b8 --- /dev/null +++ b/comfyui-art-venture/modules/fooocus/patch.py @@ -0,0 +1,77 @@ +import torch +import comfy.model_base +import comfy.ldm.modules.diffusionmodules.openaimodel +import comfy.samplers + + +from .anisotropic import bilateral_blur + +sharpness = 2.0 + +original_unet_forward = comfy.ldm.modules.diffusionmodules.openaimodel.UNetModel.forward +original_sdxl_encode_adm = comfy.model_base.SDXL.encode_adm + + +def unet_forward_patched( + self, x, timesteps=None, context=None, y=None, control=None, transformer_options={}, **kwargs +): + x0 = original_unet_forward( + self, + x, + timesteps=timesteps, + context=context, + y=y, + control=control, + transformer_options=transformer_options, + **kwargs + ) + uc_mask = torch.Tensor(transformer_options["cond_or_uncond"]).to(x0).float()[:, None, None, None] + + alpha = 1.0 - (timesteps / 999.0)[:, None, None, None].clone() + alpha *= 0.001 * sharpness + degraded_x0 = bilateral_blur(x0) * alpha + x0 * (1.0 - alpha) + + # FIX: uc_mask is not always the same size as x0 + if uc_mask.shape[0] < x0.shape[0]: + uc_mask = uc_mask.repeat(int(x0.shape[0] / uc_mask.shape[0]), 1, 1, 1) + + x0 = x0 * uc_mask + degraded_x0 * (1.0 - uc_mask) + + return x0 + + +def sdxl_encode_adm_patched(self, **kwargs): + clip_pooled = kwargs["pooled_output"] + width = kwargs.get("width", 768) + height = kwargs.get("height", 768) + crop_w = kwargs.get("crop_w", 0) + crop_h = kwargs.get("crop_h", 0) + target_width = kwargs.get("target_width", width) + target_height = kwargs.get("target_height", height) + + if kwargs.get("prompt_type", "") == "negative": + width *= 0.8 + height *= 0.8 + elif kwargs.get("prompt_type", "") == "positive": + width *= 1.5 + height *= 1.5 + + out = [] + out.append(self.embedder(torch.Tensor([height]))) + out.append(self.embedder(torch.Tensor([width]))) + out.append(self.embedder(torch.Tensor([crop_h]))) + out.append(self.embedder(torch.Tensor([crop_w]))) + out.append(self.embedder(torch.Tensor([target_height]))) + out.append(self.embedder(torch.Tensor([target_width]))) + flat = torch.flatten(torch.cat(out))[None,] + return torch.cat((clip_pooled.to(flat.device), flat), dim=1) + + +def patch_all(): + comfy.model_base.SDXL.encode_adm = sdxl_encode_adm_patched + comfy.ldm.modules.diffusionmodules.openaimodel.UNetModel.forward = unet_forward_patched + + +def unpatch_all(): + comfy.model_base.SDXL.encode_adm = original_sdxl_encode_adm + comfy.ldm.modules.diffusionmodules.openaimodel.UNetModel.forward = original_unet_forward diff --git a/comfyui-art-venture/modules/image_utils.py b/comfyui-art-venture/modules/image_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d88e9a837eff712ffded3fea8cd071700d41873e --- /dev/null +++ b/comfyui-art-venture/modules/image_utils.py @@ -0,0 +1,82 @@ +from enum import Enum +from PIL import Image + + +class ResizeMode(Enum): + RESIZE = 0 # just resize + RESIZE_TO_FILL = 1 # crop and resize + RESIZE_TO_FIT = 2 # resize and fill + + +def resize_image(im: Image.Image, width: int, height: int, resize_mode=ResizeMode.RESIZE_TO_FIT): + """ + Resizes an image with the specified resize_mode, width, and height. + + Args: + resize_mode: The mode to use when resizing the image. + 0: Resize the image to the specified width and height. + 1: Resize the image to fill the specified width and height, maintaining the aspect ratio, and then center the image within the dimensions, cropping the excess. + 2: Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image within the dimensions, filling empty with data from image. + im: The image to resize. + width: The width to resize the image to. + height: The height to resize the image to. + upscaler_name: The name of the upscaler to use. If not provided, defaults to opts.upscaler_for_img2img. + """ + + def resize(im: Image.Image, w, h): + return im.resize((w, h), resample=Image.LANCZOS) + + if resize_mode == ResizeMode.RESIZE: + res = resize(im, width, height) + + elif resize_mode == ResizeMode.RESIZE_TO_FILL: + ratio = width / height + src_ratio = im.width / im.height + + src_w = width if ratio > src_ratio else im.width * height // im.height + src_h = height if ratio <= src_ratio else im.height * width // im.width + + resized = resize(im, src_w, src_h) + res = Image.new("RGB", (width, height)) + res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2)) + + else: + ratio = width / height + src_ratio = im.width / im.height + + src_w = width if ratio < src_ratio else im.width * height // im.height + src_h = height if ratio >= src_ratio else im.height * width // im.width + + resized = resize(im, src_w, src_h) + res = Image.new("RGB", (width, height)) + res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2)) + + if ratio < src_ratio: + fill_height = height // 2 - src_h // 2 + if fill_height > 0: + res.paste(resized.resize((width, fill_height), box=(0, 0, width, 0)), box=(0, 0)) + res.paste( + resized.resize((width, fill_height), box=(0, resized.height, width, resized.height)), + box=(0, fill_height + src_h), + ) + elif ratio > src_ratio: + fill_width = width // 2 - src_w // 2 + if fill_width > 0: + res.paste(resized.resize((fill_width, height), box=(0, 0, 0, height)), box=(0, 0)) + res.paste( + resized.resize((fill_width, height), box=(resized.width, 0, resized.width, height)), + box=(fill_width + src_w, 0), + ) + + return res + + +def flatten_image(im: Image.Image, bgcolor="#ffffff"): + """replaces transparency with bgcolor (example: "#ffffff"), returning an RGB mode image with no transparency""" + + if im.mode == "RGBA": + background = Image.new("RGBA", im.size, bgcolor) + background.paste(im, mask=im) + im = background + + return im.convert("RGB") diff --git a/comfyui-art-venture/modules/impact/__init__.py b/comfyui-art-venture/modules/impact/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bab50c2ac0a89ace806d694203ffa69f35c3a7b4 --- /dev/null +++ b/comfyui-art-venture/modules/impact/__init__.py @@ -0,0 +1,12 @@ +from .facedetailer import ( + NODE_CLASS_MAPPINGS as FACE_DETAILER_NODE_CLASS_MAPPINGS, + NODE_DISPLAY_NAME_MAPPINGS as FACE_DETAILER_NODE_DISPLAY_NAME_MAPPINGS, +) + +NODE_CLASS_MAPPINGS = {} +NODE_DISPLAY_NAME_MAPPINGS = {} + +NODE_CLASS_MAPPINGS.update(FACE_DETAILER_NODE_CLASS_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(FACE_DETAILER_NODE_DISPLAY_NAME_MAPPINGS) + +__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"] diff --git a/comfyui-art-venture/modules/impact/__pycache__/__init__.cpython-310.pyc b/comfyui-art-venture/modules/impact/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..887d6f672b937caa88edbe7d075eedaed0e29926 Binary files /dev/null and b/comfyui-art-venture/modules/impact/__pycache__/__init__.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/impact/__pycache__/facedetailer.cpython-310.pyc b/comfyui-art-venture/modules/impact/__pycache__/facedetailer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb97bcedc549a4d5eab8243fc1c1e577d361a174 Binary files /dev/null and b/comfyui-art-venture/modules/impact/__pycache__/facedetailer.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/impact/facedetailer.py b/comfyui-art-venture/modules/impact/facedetailer.py new file mode 100644 index 0000000000000000000000000000000000000000..5f337fbbeae2e38da1c99a770202206b47f11374 --- /dev/null +++ b/comfyui-art-venture/modules/impact/facedetailer.py @@ -0,0 +1,108 @@ +import os +from typing import Dict + +import folder_paths + +from ..utils import load_module + +custom_nodes = folder_paths.get_folder_paths("custom_nodes") +efficieny_dir_names = ["ImpactPack", "ComfyUI-Impact-Pack"] + +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 efficieny_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 ImpactPack nodes") + + module = load_module(module_path) + print("Loaded ImpactPack nodes from", module_path) + + nodes: Dict = getattr(module, "NODE_CLASS_MAPPINGS") + FaceDetailer = nodes["FaceDetailer"] + FaceDetailerPipe = nodes["FaceDetailerPipe"] + + class AV_FaceDetailer(FaceDetailer): + @classmethod + def INPUT_TYPES(s): + inputs = FaceDetailer.INPUT_TYPES() + if not "optional" in inputs: + inputs["optional"] = {} + + inputs["optional"]["enabled"] = ( + "BOOLEAN", + {"default": True, "label_on": "enabled", "label_off": "disabled"}, + ) + return inputs + + CATEGORY = "ArtVenture/Detailer" + + def args_to_pipe(self, args: dict): + hook_args = [ + "model", + "clip", + "vae", + "positive", + "negative", + "wildcard", + "bbox_detector", + "segm_detector_opt", + "sam_model_opt", + "detailer_hook", + ] + + pipe_args = [] + for arg in hook_args: + pipe_args.append(args.get(arg, None)) + + return tuple(pipe_args + [None, None, None, None]) + + def doit(self, image, *args, enabled=True, **kwargs): + if enabled: + return super().doit(image, *args, **kwargs) + else: + pipe = self.args_to_pipe(kwargs) + return (image, [], [], None, pipe, []) + + class AV_FaceDetailerPipe(FaceDetailerPipe): + @classmethod + def INPUT_TYPES(s): + inputs = FaceDetailerPipe.INPUT_TYPES() + if not "optional" in inputs: + inputs["optional"] = {} + + inputs["optional"]["enabled"] = ( + "BOOLEAN", + {"default": True, "label_on": "enabled", "label_off": "disabled"}, + ) + return inputs + + CATEGORY = "ArtVenture/Detailer" + + def doit(self, image, detailer_pipe, *args, enabled=True, **kwargs): + if enabled: + return super().doit(image, detailer_pipe, *args, **kwargs) + else: + return (image, [], [], None, detailer_pipe, []) + + NODE_CLASS_MAPPINGS.update( + { + "AV_FaceDetailer": AV_FaceDetailer, + "AV_FaceDetailerPipe": AV_FaceDetailerPipe, + } + ) + NODE_DISPLAY_NAME_MAPPINGS.update( + {"AV_FaceDetailer": "FaceDetailer (AV)", "AV_FaceDetailerPipe": "FaceDetailerPipe (AV)"} + ) + +except Exception as e: + print("Could not load ImpactPack nodes", e) diff --git a/comfyui-art-venture/modules/inpaint/__init__.py b/comfyui-art-venture/modules/inpaint/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..acbaf5f7d165c808bc45be3194b792f854f4a5fc --- /dev/null +++ b/comfyui-art-venture/modules/inpaint/__init__.py @@ -0,0 +1 @@ +from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS \ No newline at end of file diff --git a/comfyui-art-venture/modules/inpaint/__pycache__/__init__.cpython-310.pyc b/comfyui-art-venture/modules/inpaint/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd511feea4f198ba5fbfdbcf6dcc317bc5563bbe Binary files /dev/null and b/comfyui-art-venture/modules/inpaint/__pycache__/__init__.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/inpaint/__pycache__/nodes.cpython-310.pyc b/comfyui-art-venture/modules/inpaint/__pycache__/nodes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95885dfaa4f4c2e5c58477b0279b0073378a2eb7 Binary files /dev/null and b/comfyui-art-venture/modules/inpaint/__pycache__/nodes.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/inpaint/lama/__init__.py b/comfyui-art-venture/modules/inpaint/lama/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a4b90f712cc72a86d85e6cbe76990943b3b98cfc --- /dev/null +++ b/comfyui-art-venture/modules/inpaint/lama/__init__.py @@ -0,0 +1,131 @@ +# https://github.com/advimman/lama +import os +import torch +import torch.nn.functional as F +import logging + +import folder_paths +import comfy.model_management as model_management + +from ...model_utils import download_file + + +model_dir = os.path.join(folder_paths.models_dir, "lama") + +if "lama" not in folder_paths.folder_names_and_paths: + folder_paths.folder_names_and_paths["lama"] = ([model_dir], folder_paths.supported_pt_extensions) + +gpu = model_management.get_torch_device() +cpu = torch.device("cpu") + +_models = { + "big-lama.pt": { + "url": "https://github.com/Sanster/models/releases/download/add_big_lama/big-lama.pt", + "sha": "344c77bbcb158f17dd143070d1e789f38a66c04202311ae3a258ef66667a9ea9", + }, + "anime-manga-big-lama.pt": { + "url": "https://github.com/Sanster/models/releases/download/AnimeMangaInpainting/anime-manga-big-lama.pt", + "sha": "479d3afdcb7ed2fd944ed4ebcc39ca45b33491f0f2e43eb1000bd623cfb41823", + }, +} + + +def ceil_modulo(x, mod): + if x % mod == 0: + return x + return (x // mod + 1) * mod + + +def pad_tensor_to_modulo(img, mod): + height, width = img.shape[-2:] + out_height = ceil_modulo(height, mod) + out_width = ceil_modulo(width, mod) + return F.pad(img, pad=(0, out_width - width, 0, out_height - height), mode="reflect") + + +class LoadLaMaModel: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model_name": ( + list(set(["big-lama.pt", "anime-manga-big-lama.pt"] + folder_paths.get_filename_list("lama"))), + ), + } + } + + RETURN_TYPES = ("LAMA",) + CATEGORY = "Art Venture/Inpainting" + FUNCTION = "load_model" + + def load_model(self, model_name: str): + model_path = folder_paths.get_full_path("lama", model_name) + if model_path is None: + if model_name in _models: + model_url = _models[model_name]["url"] + model_sha = _models[model_name]["sha"] + logging.info(f"Downloading {model_name} into {model_dir}") + model_path = os.path.join(model_dir, model_name) + download_file(model_url, model_path, model_sha) + else: + raise Exception(f"Not found model {model_name}") + + lama = torch.jit.load(model_path, map_location="cpu") + lama.eval() + + return (lama,) + + +class LaMaInpaint(LoadLaMaModel): + def __init__(self): + self.model_name = "big-lama.pt" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "image": ("IMAGE",), + "mask": ("MASK",), + }, + "optional": { + "device_mode": (["AUTO", "Prefer GPU", "CPU"],), + "lama_model": ("LAMA",), + }, + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "lama_inpaint" + + def lama_inpaint(self, image: torch.Tensor, mask: torch.Tensor, device_mode="AUTO", lama_model=None): + if image.shape[0] != mask.shape[0]: + raise Exception("Image and mask must have the same batch size") + + device = gpu if device_mode != "CPU" else cpu + + model = lama_model or self.load_model(self.model_name) + model.to(device) + + try: + inpainted = [] + orig_w = image.shape[2] + orig_h = image.shape[1] + + for i, img in enumerate(image): + img = img.permute(2, 0, 1).unsqueeze(0) + msk = mask[i].detach().cpu() + msk = (msk > 0) * 1.0 + msk = msk.unsqueeze(0).unsqueeze(0) + + src_image = pad_tensor_to_modulo(img, 8).to(device) + src_mask = pad_tensor_to_modulo(msk, 8).to(device) + + res = model(src_image, src_mask) + res = res[0].permute(1, 2, 0).detach().cpu() + res = res[:orig_h, :orig_w] + + inpainted.append(res) + + return (torch.stack(inpainted),) + finally: + if device_mode == "AUTO": + model.to(cpu) diff --git a/comfyui-art-venture/modules/inpaint/lama/__pycache__/__init__.cpython-310.pyc b/comfyui-art-venture/modules/inpaint/lama/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..627670da3245617a67010eacb763266587f89782 Binary files /dev/null and b/comfyui-art-venture/modules/inpaint/lama/__pycache__/__init__.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/inpaint/nodes.py b/comfyui-art-venture/modules/inpaint/nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..c343c0699d33986eda8e2a5448851990dea37eed --- /dev/null +++ b/comfyui-art-venture/modules/inpaint/nodes.py @@ -0,0 +1,257 @@ +import cv2 +import torch +import numpy as np +from PIL import Image, ImageOps +from typing import Dict + +from .sam.nodes import SAMLoader, GetSAMEmbedding, SAMEmbeddingToImage +from .lama import LoadLaMaModel, LaMaInpaint + +from ..masking import get_crop_region, expand_crop_region +from ..image_utils import ResizeMode, resize_image +from ..utils import numpy2pil, tensor2pil, pil2tensor + + +class PrepareImageAndMaskForInpaint: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "image": ("IMAGE",), + "mask": ("MASK",), + "mask_blur": ("INT", {"default": 4, "min": 0, "max": 64}), + "inpaint_masked": ("BOOLEAN", {"default": False}), + "mask_padding": ("INT", {"default": 32, "min": 0, "max": 1024}), + "width": ("INT", {"default": 0, "min": 0, "max": 2048}), + "height": ("INT", {"default": 0, "min": 0, "max": 2048}), + }, + "optional": { + "controlnet_image": ("IMAGE",), + } + } + + RETURN_TYPES = ("IMAGE", "MASK", "IMAGE", "CROP_REGION", "IMAGE") + RETURN_NAMES = ("inpaint_image", "inpaint_mask", "overlay_image", "crop_region", "controlnet_image") + CATEGORY = "Art Venture/Inpainting" + FUNCTION = "prepare" + + def prepare( + self, + image: torch.Tensor, + mask: torch.Tensor, + mask_blur: int, + inpaint_masked: bool, + mask_padding: int, + width: int, + height: int, + controlnet_image: torch.Tensor = None, + ): + if image.shape[0] != mask.shape[0]: + raise ValueError("image and mask must have same batch size") + + if controlnet_image is not None and image.shape[0] != controlnet_image.shape[0]: + raise ValueError("image and controlnet_image must have same batch size") + + if image.shape[1] != mask.shape[1] or image.shape[2] != mask.shape[2]: + raise ValueError("image and mask must have same dimensions") + + # These are only used if inpaint_masked is True + out_width, out_height = width, height + if inpaint_masked and out_width == 0 and out_height == 0: + out_height, out_width = image.shape[1:3] + + source_height, source_width = image.shape[1:3] + + images = [] + masks = [] + overlay_images = [] + crop_regions = [] + processed_controlnet_images = [] + + for idx, (img, msk) in enumerate(zip(image, mask)): + np_mask: np.ndarray = msk.cpu().numpy() + + if mask_blur > 0: + kernel_size = 2 * int(2.5 * mask_blur + 0.5) + 1 + np_mask = cv2.GaussianBlur(np_mask, (kernel_size, kernel_size), mask_blur) + + pil_mask = numpy2pil(np_mask, "L") + pil_img = tensor2pil(img) + + # --- LOGIC SEPARATION --- + + if inpaint_masked: + # --- MODE 1: CROP AND RESIZE --- + crop_region = get_crop_region(np_mask, mask_padding) + crop_region = expand_crop_region(crop_region, out_width, out_height, source_width, source_height) + + cropped_img = pil_img.crop(crop_region) + cropped_mask = pil_mask.crop(crop_region) + + final_pil_img = resize_image(cropped_img, out_width, out_height, ResizeMode.RESIZE_TO_FIT) + final_pil_mask = resize_image(cropped_mask, out_width, out_height, ResizeMode.RESIZE_TO_FIT).convert("L") + + if controlnet_image is not None: + pil_cimg = tensor2pil(controlnet_image[idx]) + cn_source_width, cn_source_height = pil_cimg.size + scale_x = cn_source_width / source_width + scale_y = cn_source_height / source_height + + cn_target_width = int(out_width * scale_x) + cn_target_height = int(out_height * scale_y) + + x1, y1, x2, y2 = crop_region + cn_crop_region = (int(x1 * scale_x), int(y1 * scale_y), int(x2 * scale_x), int(y2 * scale_y)) + cropped_cn_img = pil_cimg.crop(cn_crop_region) + final_cn_img = resize_image(cropped_cn_img, cn_target_width, cn_target_height, ResizeMode.RESIZE_TO_FIT) + processed_controlnet_images.append(pil2tensor(final_cn_img)) + + else: + # --- MODE 2: PASS-THROUGH (NO RESIZING) --- + final_pil_img = pil_img + final_pil_mask = pil_mask # Already blurred if requested + crop_region = (0, 0, source_width, source_height) + + if controlnet_image is not None: + # Simply pass the original controlnet image through + final_cn_img = tensor2pil(controlnet_image[idx]) + processed_controlnet_images.append(pil2tensor(final_cn_img)) + + # --- COMMON LOGIC FOR BOTH MODES --- + + # The overlay/preview should always be based on the original full-size image + image_masked = Image.new("RGBa", (pil_img.width, pil_img.height)) + # The mask used here is the potentially blurred one, but before any cropping/resizing + image_masked.paste(pil_img.convert("RGBA").convert("RGBa"), mask=ImageOps.invert(pil_mask)) + overlay_images.append(pil2tensor(image_masked.convert("RGBA"))) + + images.append(pil2tensor(final_pil_img)) + masks.append(pil2tensor(final_pil_mask)) + crop_regions.append(torch.tensor(crop_region, dtype=torch.int64)) + + + if processed_controlnet_images: + final_controlnet_tensor = torch.cat(processed_controlnet_images, dim=0) + else: + # If no controlnet image is provided, create a black 64x64 placeholder + batch_size = image.shape[0] + final_controlnet_tensor = torch.zeros((batch_size, 64, 64, 3), dtype=torch.float32, device=image.device) + + return ( + torch.cat(images, dim=0), + torch.cat(masks, dim=0), + torch.cat(overlay_images, dim=0), + torch.stack(crop_regions, dim=0), + final_controlnet_tensor, + ) + + +class OverlayInpaintedLatent: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "original": ("LATENT",), + "inpainted": ("LATENT",), + "mask": ("MASK",), + } + } + + RETURN_TYPES = ("LATENT",) + CATEGORY = "Art Venture/Inpainting" + FUNCTION = "overlay" + + def overlay(self, original: Dict, inpainted: Dict, mask: torch.Tensor): + s_original: torch.Tensor = original["samples"] + s_inpainted: torch.Tensor = inpainted["samples"] + + if s_original.shape[0] != s_inpainted.shape[0]: + raise ValueError("original and inpainted must have same batch size") + + if s_original.shape[0] != mask.shape[0]: + raise ValueError("original and mask must have same batch size") + + overlays = [] + + for org, inp, msk in zip(s_original, s_inpainted, mask): + latmask = tensor2pil(msk.unsqueeze(0), "L").convert("RGB").resize((org.shape[2], org.shape[1])) + latmask = np.moveaxis(np.array(latmask, dtype=np.float32), 2, 0) / 255 + latmask = latmask[0] + latmask = np.around(latmask) + latmask = np.tile(latmask[None], (4, 1, 1)) + + msk = torch.asarray(1.0 - latmask) + nmask = torch.asarray(latmask) + + overlayed = inp * nmask + org * msk + overlays.append(overlayed) + + samples = torch.stack(overlays) + return ({"samples": samples},) + + +class OverlayInpaintedImage: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "inpainted": ("IMAGE",), + "overlay_image": ("IMAGE",), + "crop_region": ("CROP_REGION",), + } + } + + RETURN_TYPES = ("IMAGE",) + CATEGORY = "Art Venture/Inpainting" + FUNCTION = "overlay" + + def overlay(self, inpainted: torch.Tensor, overlay_image: torch.Tensor, crop_region: torch.Tensor): + if inpainted.shape[0] != overlay_image.shape[0]: + raise ValueError("inpainted and overlay_image must have same batch size") + if inpainted.shape[0] != crop_region.shape[0]: + raise ValueError("inpainted and crop_region must have same batch size") + + images = [] + for image, overlay, region in zip(inpainted, overlay_image, crop_region): + image = tensor2pil(image.unsqueeze(0)) + overlay = tensor2pil(overlay.unsqueeze(0), mode="RGBA") + + x1, y1, x2, y2 = region.tolist() + if (x1, y1, x2, y2) == (0, 0, 0, 0): + pass + else: + base_image = Image.new("RGBA", (overlay.width, overlay.height)) + image = resize_image(image, x2 - x1, y2 - y1, ResizeMode.RESIZE_TO_FILL) + base_image.paste(image, (x1, y1)) + image = base_image + + image = image.convert("RGBA") + image.alpha_composite(overlay) + image = image.convert("RGB") + + images.append(pil2tensor(image)) + + return (torch.cat(images, dim=0),) + + +NODE_CLASS_MAPPINGS = { + "AV_SAMLoader": SAMLoader, + "GetSAMEmbedding": GetSAMEmbedding, + "SAMEmbeddingToImage": SAMEmbeddingToImage, + "LoadLaMaModel": LoadLaMaModel, + "LaMaInpaint": LaMaInpaint, + "PrepareImageAndMaskForInpaint": PrepareImageAndMaskForInpaint, + "OverlayInpaintedLatent": OverlayInpaintedLatent, + "OverlayInpaintedImage": OverlayInpaintedImage, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "AV_SAMLoader": "SAM Loader", + "GetSAMEmbedding": "Get SAM Embedding", + "SAMEmbeddingToImage": "SAM Embedding to Image", + "LoadLaMaModel": "LaMa Loader", + "LaMaInpaint": "LaMa Remove Object", + "PrepareImageAndMaskForInpaint": "Prepare Image & Mask for Inpaint", + "OverlayInpaintedLatent": "Overlay Inpainted Latent", + "OverlayInpaintedImage": "Overlay Inpainted Image", +} diff --git a/comfyui-art-venture/modules/inpaint/sam/__pycache__/nodes.cpython-310.pyc b/comfyui-art-venture/modules/inpaint/sam/__pycache__/nodes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f365e9c7053411dcec8f568e4edb3dc17dde245e Binary files /dev/null and b/comfyui-art-venture/modules/inpaint/sam/__pycache__/nodes.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/inpaint/sam/nodes.py b/comfyui-art-venture/modules/inpaint/sam/nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..e722bd291556de906409591cbad7ad4ec64bf095 --- /dev/null +++ b/comfyui-art-venture/modules/inpaint/sam/nodes.py @@ -0,0 +1,119 @@ +import os +import torch +import numpy as np +from PIL import Image + +import folder_paths +import comfy.model_management as model_management +import comfy.utils + +from ...utils import ensure_package, tensor2pil, pil2tensor + +if "sams" not in folder_paths.folder_names_and_paths: + folder_paths.folder_names_and_paths["sams"] = ( + [ + os.path.join(folder_paths.models_dir, "sams"), + ], + folder_paths.supported_pt_extensions, + ) + +gpu = model_management.get_torch_device() +cpu = torch.device("cpu") + + +class SAMLoader: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "model_name": (folder_paths.get_filename_list("sams"),), + } + } + + RETURN_TYPES = ("AV_SAM_MODEL",) + RETURN_NAMES = ("sam_model",) + FUNCTION = "load_model" + CATEGORY = "Art Venture/Segmentation" + + def load_model(self, model_name): + modelname = folder_paths.get_full_path("sams", model_name) + + state_dict = comfy.utils.load_torch_file(modelname) + encoder_size = state_dict["image_encoder.patch_embed.proj.bias"].shape[0] + + if encoder_size == 1280: + model_kind = "vit_h" + elif encoder_size == 1024: + model_kind = "vit_l" + else: + model_kind = "vit_b" + + ensure_package("segment_anything") + from segment_anything import sam_model_registry + + sam = sam_model_registry[model_kind]() + sam.load_state_dict(state_dict) + + return (sam,) + + +class GetSAMEmbedding: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "sam_model": ("AV_SAM_MODEL",), + "image": ("IMAGE",), + }, + "optional": {"device_mode": (["AUTO", "Prefer GPU", "CPU"],)}, + } + + RETURN_TYPES = ("SAM_EMBEDDING",) + CATEGORY = "Art Venture/Segmentation" + FUNCTION = "get_sam_embedding" + + def get_sam_embedding(self, image, sam_model, device_mode="AUTO"): + device = gpu if device_mode != "CPU" else cpu + sam_model.to(device) + + ensure_package("segment_anything") + from segment_anything import SamPredictor + + try: + predictor = SamPredictor(sam_model) + image = tensor2pil(image) + image = image.convert("RGB") + image = np.array(image) + predictor.set_image(image, "RGB") + embedding = predictor.get_image_embedding().cpu().numpy() + + return (embedding,) + finally: + if device_mode == "AUTO": + sam_model.to(cpu) + + +class SAMEmbeddingToImage: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "embedding": ("SAM_EMBEDDING",), + }, + } + + RETURN_TYPES = ("IMAGE",) + CATEGORY = "Art Venture/Segmentation" + FUNCTION = "sam_embedding_to_noise_image" + + def sam_embedding_to_noise_image(self, embedding: np.ndarray): + # Flatten the array to a 1D array + flat_arr = embedding.flatten() + # Convert the 1D array to bytes + bytes_arr = flat_arr.astype(np.float32).tobytes() + # Convert bytes to RGBA PIL Image + size = (embedding.shape[1] * 4, int(embedding.shape[2] * embedding.shape[3] / 4)) + + img = Image.frombytes("RGBA", size, bytes_arr) + + return (pil2tensor(img),) diff --git a/comfyui-art-venture/modules/interrogate/.gitignore b/comfyui-art-venture/modules/interrogate/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..bb4b6a12616273ac4799320baa3e38334226b50c --- /dev/null +++ b/comfyui-art-venture/modules/interrogate/.gitignore @@ -0,0 +1,4 @@ +__pycache__/ +models/__pycache__/ +*.pyc +*.pth \ No newline at end of file diff --git a/comfyui-art-venture/modules/interrogate/__init__.py b/comfyui-art-venture/modules/interrogate/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a8a27d38390c74741163101773bd959078869df9 --- /dev/null +++ b/comfyui-art-venture/modules/interrogate/__init__.py @@ -0,0 +1,17 @@ +from .blip_node import BlipLoader, BlipCaption, DownloadAndLoadBlip +from .danbooru import DeepDanbooruCaption + +NODE_CLASS_MAPPINGS = { + "BLIPLoader": BlipLoader, + "BLIPCaption": BlipCaption, + "DownloadAndLoadBlip": DownloadAndLoadBlip, + "DeepDanbooruCaption": DeepDanbooruCaption, +} +NODE_DISPLAY_NAME_MAPPINGS = { + "BLIPLoader": "BLIP Loader", + "BLIPCaption": "BLIP Caption", + "DownloadAndLoadBlip": "Download and Load BLIP Model", + "DeepDanbooruCaption": "Deep Danbooru Caption", +} + +__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"] diff --git a/comfyui-art-venture/modules/interrogate/__pycache__/__init__.cpython-310.pyc b/comfyui-art-venture/modules/interrogate/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..658f754cdc5aff51ba0abcb5abf91b4439d9e70d Binary files /dev/null and b/comfyui-art-venture/modules/interrogate/__pycache__/__init__.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/interrogate/__pycache__/blip_node.cpython-310.pyc b/comfyui-art-venture/modules/interrogate/__pycache__/blip_node.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..843a22d674188adb165b8ed54b3871605c7ecf7e Binary files /dev/null and b/comfyui-art-venture/modules/interrogate/__pycache__/blip_node.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/interrogate/__pycache__/danbooru.cpython-310.pyc b/comfyui-art-venture/modules/interrogate/__pycache__/danbooru.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70aaed917c6c8456627483c41713874b01ea5a02 Binary files /dev/null and b/comfyui-art-venture/modules/interrogate/__pycache__/danbooru.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/interrogate/blip_node.py b/comfyui-art-venture/modules/interrogate/blip_node.py new file mode 100644 index 0000000000000000000000000000000000000000..601dc1fa222c1a06e6064f384c34d126eab3f73f --- /dev/null +++ b/comfyui-art-venture/modules/interrogate/blip_node.py @@ -0,0 +1,232 @@ +import os + +import torch +from torchvision import transforms +from torchvision.transforms.functional import InterpolationMode + +import folder_paths +from comfy.model_management import text_encoder_device, text_encoder_offload_device, soft_empty_cache + +from ..model_utils import download_file +from ..utils import tensor2pil + +blips = {} +blip_size = 384 +gpu = text_encoder_device() +cpu = text_encoder_offload_device() +model_dir = os.path.join(folder_paths.models_dir, "blip") +models = { + "model_base_caption_capfilt_large.pth": { + "url": "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_caption_capfilt_large.pth", + "sha": "96ac8749bd0a568c274ebe302b3a3748ab9be614c737f3d8c529697139174086", + }, + "model_base_capfilt_large.pth": { + "url": "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth", + "sha": "8f5187458d4d47bb87876faf3038d5947eff17475edf52cf47b62e84da0b235f", + }, +} + + +folder_paths.folder_names_and_paths["blip"] = ( + [model_dir], + folder_paths.supported_pt_extensions, +) + + +def packages(versions=False): + import subprocess + import sys + + return [ + (r.decode().split("==")[0] if not versions else r.decode()) + for r in subprocess.check_output([sys.executable, "-m", "pip", "freeze"]).split() + ] + + +def transformImage(input_image): + raw_image = input_image.convert("RGB") + raw_image = raw_image.resize((blip_size, blip_size)) + transform = transforms.Compose( + [ + transforms.Resize(raw_image.size, interpolation=InterpolationMode.BICUBIC), + transforms.ToTensor(), + transforms.Normalize( + (0.48145466, 0.4578275, 0.40821073), + (0.26862954, 0.26130258, 0.27577711), + ), + ] + ) + image = transform(raw_image).unsqueeze(0).to(gpu) + return image.view(1, -1, blip_size, blip_size) # Change the shape of the output tensor + + +def load_blip(model_name): + if model_name not in blips: + blip_path = folder_paths.get_full_path("blip", model_name) + + from .models.blip import blip_decoder + + current_dir = os.path.dirname(os.path.realpath(__file__)) + med_config = os.path.join(current_dir, "configs", "med_config.json") + blip = blip_decoder( + pretrained=blip_path, + image_size=blip_size, + vit="base", + med_config=med_config, + ) + blip.eval() + blips[model_name] = blip + + return blips[model_name] + + +def unload_blip(): + global blips + if blips is not None and blips.is_auto_mode: + blips = blips.to(cpu) + + soft_empty_cache() + + +def join_caption(caption, prefix, suffix): + if prefix: + caption = prefix + ", " + caption + if suffix: + caption = caption + ", " + suffix + return caption + + +def blip_caption(model, image, min_length, max_length): + image = tensor2pil(image) + tensor = transformImage(image) + + with torch.no_grad(): + caption = model.generate( + tensor, + sample=False, + num_beams=1, + min_length=min_length, + max_length=max_length, + ) + return caption[0] + + +class BlipLoader: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model_name": (folder_paths.get_filename_list("blip"),), + }, + } + + RETURN_TYPES = ("BLIP_MODEL",) + FUNCTION = "load_blip" + CATEGORY = "Art Venture/Captioning" + + def load_blip(self, model_name): + return (load_blip(model_name),) + + +class DownloadAndLoadBlip: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model_name": (list(models.keys()),), + }, + } + + RETURN_TYPES = ("BLIP_MODEL",) + FUNCTION = "download_and_load_blip" + CATEGORY = "Art Venture/Captioning" + + def download_and_load_blip(self, model_name): + if model_name not in folder_paths.get_filename_list("blip"): + model_info = models[model_name] + download_file( + model_info["url"], + os.path.join(model_dir, model_name), + model_info["sha"], + ) + + return (load_blip(model_name),) + + +class BlipCaption: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "image": ("IMAGE",), + "min_length": ( + "INT", + { + "default": 24, + "min": 0, # minimum value + "max": 200, # maximum value + "step": 1, # slider's step + }, + ), + "max_length": ( + "INT", + { + "default": 48, + "min": 0, # minimum value + "max": 200, # maximum value + "step": 1, # slider's step + }, + ), + }, + "optional": { + "device_mode": (["AUTO", "Prefer GPU", "CPU"],), + "prefix": ("STRING", {"default": ""}), + "suffix": ("STRING", {"default": ""}), + "enabled": ("BOOLEAN", {"default": True}), + "blip_model": ("BLIP_MODEL",), + }, + } + + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("caption",) + OUTPUT_IS_LIST = (True,) + FUNCTION = "blip_caption" + CATEGORY = "Art Venture/Captioning" + + def blip_caption( + self, image, min_length, max_length, device_mode="AUTO", prefix="", suffix="", enabled=True, blip_model=None + ): + if not enabled: + return ([join_caption("", prefix, suffix)],) + + if blip_model is None: + downloader = DownloadAndLoadBlip() + blip_model = downloader.download_and_load_blip("model_base_caption_capfilt_large.pth")[0] + + device = gpu if device_mode != "CPU" else cpu + blip_model = blip_model.to(device) + + try: + captions = [] + + with torch.no_grad(): + for img in image: + img = tensor2pil(img) + tensor = transformImage(img) + caption = blip_model.generate( + tensor, + sample=False, + num_beams=1, + min_length=min_length, + max_length=max_length, + ) + + caption = join_caption(caption[0], prefix, suffix) + captions.append(caption) + + return (captions,) + except: + raise + finally: + if device_mode == "AUTO": + blip_model = blip_model.to(cpu) diff --git a/comfyui-art-venture/modules/interrogate/configs/med_config.json b/comfyui-art-venture/modules/interrogate/configs/med_config.json new file mode 100644 index 0000000000000000000000000000000000000000..0ffad0a6f3c2f9f11b8faa84529d9860bb70327a --- /dev/null +++ b/comfyui-art-venture/modules/interrogate/configs/med_config.json @@ -0,0 +1,21 @@ +{ + "architectures": [ + "BertModel" + ], + "attention_probs_dropout_prob": 0.1, + "hidden_act": "gelu", + "hidden_dropout_prob": 0.1, + "hidden_size": 768, + "initializer_range": 0.02, + "intermediate_size": 3072, + "layer_norm_eps": 1e-12, + "max_position_embeddings": 512, + "model_type": "bert", + "num_attention_heads": 12, + "num_hidden_layers": 12, + "pad_token_id": 0, + "type_vocab_size": 2, + "vocab_size": 30524, + "encoder_width": 768, + "add_cross_attention": true +} diff --git a/comfyui-art-venture/modules/interrogate/danbooru.py b/comfyui-art-venture/modules/interrogate/danbooru.py new file mode 100644 index 0000000000000000000000000000000000000000..ec15ac1df02105c2dad11928b222413128b50ff4 --- /dev/null +++ b/comfyui-art-venture/modules/interrogate/danbooru.py @@ -0,0 +1,151 @@ +import os +import re +import torch +import numpy as np + +import folder_paths +from comfy.model_management import text_encoder_device, text_encoder_offload_device, soft_empty_cache + +from ..image_utils import resize_image +from ..model_utils import download_file +from ..utils import is_junction, tensor2pil +from .blip_node import join_caption + +danbooru = None +blip_size = 384 +gpu = text_encoder_device() +cpu = text_encoder_offload_device() +model_dir = os.path.join(folder_paths.models_dir, "blip") +model_url = "https://github.com/AUTOMATIC1111/TorchDeepDanbooru/releases/download/v1/model-resnet_custom_v3.pt" +model_sha = "3841542cda4dd037da12a565e854b3347bb2eec8fbcd95ea3941b2c68990a355" +re_special = re.compile(r"([\\()])") + + +def load_danbooru(device_mode): + global danbooru + if danbooru is None: + if not os.path.exists(model_dir) and not is_junction(model_dir): + os.makedirs(model_dir, exist_ok=True) + + model_path = os.path.join(model_dir, "model-resnet_custom_v3.pt") + download_file(model_url, model_path, model_sha) + + from .models.deepbooru_model import DeepDanbooruModel + + danbooru = DeepDanbooruModel() + danbooru.load_state_dict(torch.load(model_path, map_location="cpu")) + danbooru.eval() + + if device_mode != "CPU": + danbooru = danbooru.to(gpu) + + danbooru.is_auto_mode = device_mode == "AUTO" + + return danbooru + + +def unload_danbooru(): + global danbooru + if danbooru is not None and danbooru.is_auto_mode: + danbooru = danbooru.to(cpu) + + soft_empty_cache() + + +class DeepDanbooruCaption: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "image": ("IMAGE",), + "threshold": ("FLOAT", {"default": 0.5, "min": 0, "max": 1, "step": 0.01}), + "sort_alpha": ("BOOLEAN", {"default": True}), + "use_spaces": ("BOOLEAN", {"default": True}), + "escape": ("BOOLEAN", {"default": True}), + "filter_tags": ("STRING", {"default": "blacklist", "multiline": True}), + }, + "optional": { + "device_mode": (["AUTO", "Prefer GPU", "CPU"],), + "prefix": ("STRING", {"default": ""}), + "suffix": ("STRING", {"default": ""}), + "enabled": ("BOOLEAN", {"default": True}), + }, + } + + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("caption",) + OUTPUT_IS_LIST = (True,) + FUNCTION = "caption" + CATEGORY = "Art Venture/Utils" + + def caption( + self, + image, + threshold, + sort_alpha, + use_spaces, + escape, + filter_tags, + device_mode="AUTO", + prefix="", + suffix="", + enabled=True, + ): + if not enabled: + return ([join_caption("", prefix, suffix)],) + + model = load_danbooru(device_mode) + + try: + captions = [] + + for img in image: + img = tensor2pil(img) + img = resize_image(img.convert("RGB"), 512, 512, resize_mode=2) + arr = np.expand_dims(np.array(img, dtype=np.float32), 0) / 255 + + with torch.no_grad(): + x = torch.from_numpy(arr).to(gpu) + y = model(x)[0].detach().cpu().numpy() + + probability_dict = {} + + for tag, probability in zip(model.tags, y): + if probability < threshold: + continue + + if tag.startswith("rating:"): + continue + + probability_dict[tag] = probability + + if sort_alpha: + tags = sorted(probability_dict) + else: + tags = [tag for tag, _ in sorted(probability_dict.items(), key=lambda x: -x[1])] + + res = [] + filtertags = {x.strip().replace(" ", "_") for x in filter_tags.split(",")} + + for tag in [x for x in tags if x not in filtertags]: + probability = probability_dict[tag] + tag_outformat = tag + if use_spaces: + tag_outformat = tag_outformat.replace("_", " ") + if escape: + tag_outformat = re.sub(re_special, r"\\\1", tag_outformat) + + res.append(tag_outformat) + + caption = ", ".join(res) + caption = join_caption(caption, prefix, suffix) + captions.append(caption) + + return (captions,) + except: + raise + finally: + unload_danbooru() diff --git a/comfyui-art-venture/modules/interrogate/models/__init__.py b/comfyui-art-venture/modules/interrogate/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/comfyui-art-venture/modules/interrogate/models/blip.py b/comfyui-art-venture/modules/interrogate/models/blip.py new file mode 100644 index 0000000000000000000000000000000000000000..bf2d78ca8906d12f007cd64f1c110d976bd59c23 --- /dev/null +++ b/comfyui-art-venture/modules/interrogate/models/blip.py @@ -0,0 +1,303 @@ +""" + * Copyright (c) 2022, salesforce.com, inc. + * All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause + * By Junnan Li +""" +import warnings + +warnings.filterwarnings("ignore") + +import os +from urllib.parse import urlparse + +import torch +from torch import nn +from timm.models.hub import download_cached_file +from transformers import BertTokenizer + +from .med import BertConfig, BertLMHeadModel, BertModel +from .vit import VisionTransformer, interpolate_pos_embed + + +class BLIP_Base(nn.Module): + def __init__( + self, + med_config="configs/med_config.json", + image_size=224, + vit="base", + vit_grad_ckpt=False, + vit_ckpt_layer=0, + ): + """ + Args: + med_config (str): path for the mixture of encoder-decoder model's configuration file + image_size (int): input image size + vit (str): model size of vision transformer + """ + super().__init__() + + self.visual_encoder, vision_width = create_vit( + vit, image_size, vit_grad_ckpt, vit_ckpt_layer + ) + self.tokenizer = init_tokenizer() + med_config = BertConfig.from_json_file(med_config) + med_config.encoder_width = vision_width + self.text_encoder = BertModel(config=med_config, add_pooling_layer=False) + + def forward(self, image, caption, mode): + assert mode in [ + "image", + "text", + "multimodal", + ], "mode parameter must be image, text, or multimodal" + text = self.tokenizer(caption, return_tensors="pt").to(image.device) + + if mode == "image": + # return image features + image_embeds = self.visual_encoder(image) + return image_embeds + + elif mode == "text": + # return text features + text_output = self.text_encoder( + text.input_ids, + attention_mask=text.attention_mask, + return_dict=True, + mode="text", + ) + return text_output.last_hidden_state + + elif mode == "multimodal": + # return multimodel features + image_embeds = self.visual_encoder(image) + image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to( + image.device + ) + + text.input_ids[:, 0] = self.tokenizer.enc_token_id + output = self.text_encoder( + text.input_ids, + attention_mask=text.attention_mask, + encoder_hidden_states=image_embeds, + encoder_attention_mask=image_atts, + return_dict=True, + ) + return output.last_hidden_state + + +class BLIP_Decoder(nn.Module): + def __init__( + self, + med_config="configs/med_config.json", + image_size=384, + vit="base", + vit_grad_ckpt=False, + vit_ckpt_layer=0, + prompt="a picture of ", + ): + """ + Args: + med_config (str): path for the mixture of encoder-decoder model's configuration file + image_size (int): input image size + vit (str): model size of vision transformer + """ + super().__init__() + + self.visual_encoder, vision_width = create_vit( + vit, image_size, vit_grad_ckpt, vit_ckpt_layer + ) + self.tokenizer = init_tokenizer() + med_config = BertConfig.from_json_file(med_config) + med_config.encoder_width = vision_width + self.text_decoder = BertLMHeadModel(config=med_config) + + self.prompt = prompt + self.prompt_length = len(self.tokenizer(self.prompt).input_ids) - 1 + + def forward(self, image, caption): + image_embeds = self.visual_encoder(image) + image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to( + image.device + ) + + text = self.tokenizer( + caption, + padding="longest", + truncation=True, + max_length=40, + return_tensors="pt", + ).to(image.device) + + text.input_ids[:, 0] = self.tokenizer.bos_token_id + + decoder_targets = text.input_ids.masked_fill( + text.input_ids == self.tokenizer.pad_token_id, -100 + ) + decoder_targets[:, : self.prompt_length] = -100 + + decoder_output = self.text_decoder( + text.input_ids, + attention_mask=text.attention_mask, + encoder_hidden_states=image_embeds, + encoder_attention_mask=image_atts, + labels=decoder_targets, + return_dict=True, + ) + loss_lm = decoder_output.loss + + return loss_lm + + def generate( + self, + image, + sample=False, + num_beams=3, + max_length=30, + min_length=10, + top_p=0.9, + repetition_penalty=1.0, + ): + image_embeds = self.visual_encoder(image) + + if not sample: + image_embeds = image_embeds.repeat_interleave(num_beams, dim=0) + + image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to( + image.device + ) + model_kwargs = { + "encoder_hidden_states": image_embeds, + "encoder_attention_mask": image_atts, + } + + prompt = [self.prompt] * image.size(0) + input_ids = self.tokenizer(prompt, return_tensors="pt").input_ids.to( + image.device + ) + input_ids[:, 0] = self.tokenizer.bos_token_id + input_ids = input_ids[:, :-1] + + if sample: + # nucleus sampling + outputs = self.text_decoder.generate( + input_ids=input_ids, + max_length=max_length, + min_length=min_length, + do_sample=True, + top_p=top_p, + num_return_sequences=1, + eos_token_id=self.tokenizer.sep_token_id, + pad_token_id=self.tokenizer.pad_token_id, + repetition_penalty=1.1, + **model_kwargs + ) + else: + # beam search + outputs = self.text_decoder.generate( + input_ids=input_ids, + max_length=max_length, + min_length=min_length, + num_beams=num_beams, + eos_token_id=self.tokenizer.sep_token_id, + pad_token_id=self.tokenizer.pad_token_id, + repetition_penalty=repetition_penalty, + **model_kwargs + ) + + captions = [] + for output in outputs: + caption = self.tokenizer.decode(output, skip_special_tokens=True) + captions.append(caption[len(self.prompt) :]) + return captions + + +def blip_decoder(pretrained="", **kwargs): + model = BLIP_Decoder(**kwargs) + if pretrained: + model, msg = load_checkpoint(model, pretrained) + assert len(msg.missing_keys) == 0 + return model + + +def blip_feature_extractor(pretrained="", **kwargs): + model = BLIP_Base(**kwargs) + if pretrained: + model, msg = load_checkpoint(model, pretrained) + assert len(msg.missing_keys) == 0 + return model + + +def init_tokenizer(): + tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") + tokenizer.add_special_tokens({"bos_token": "[DEC]"}) + tokenizer.add_special_tokens({"additional_special_tokens": ["[ENC]"]}) + tokenizer.enc_token_id = tokenizer.additional_special_tokens_ids[0] + return tokenizer + + +def create_vit( + vit, image_size, use_grad_checkpointing=False, ckpt_layer=0, drop_path_rate=0 +): + assert vit in ["base", "large"], "vit parameter must be base or large" + if vit == "base": + vision_width = 768 + visual_encoder = VisionTransformer( + img_size=image_size, + patch_size=16, + embed_dim=vision_width, + depth=12, + num_heads=12, + use_grad_checkpointing=use_grad_checkpointing, + ckpt_layer=ckpt_layer, + drop_path_rate=0 or drop_path_rate, + ) + elif vit == "large": + vision_width = 1024 + visual_encoder = VisionTransformer( + img_size=image_size, + patch_size=16, + embed_dim=vision_width, + depth=24, + num_heads=16, + use_grad_checkpointing=use_grad_checkpointing, + ckpt_layer=ckpt_layer, + drop_path_rate=0.1 or drop_path_rate, + ) + return visual_encoder, vision_width + + +def is_url(url_or_filename): + parsed = urlparse(url_or_filename) + return parsed.scheme in ("http", "https") + + +def load_checkpoint(model, url_or_filename): + if is_url(url_or_filename): + cached_file = download_cached_file( + url_or_filename, check_hash=False, progress=True + ) + checkpoint = torch.load(cached_file, map_location="cpu") + elif os.path.isfile(url_or_filename): + checkpoint = torch.load(url_or_filename, map_location="cpu") + else: + raise RuntimeError("checkpoint url or path is invalid") + + state_dict = checkpoint["model"] + + state_dict["visual_encoder.pos_embed"] = interpolate_pos_embed( + state_dict["visual_encoder.pos_embed"], model.visual_encoder + ) + if "visual_encoder_m.pos_embed" in model.state_dict().keys(): + state_dict["visual_encoder_m.pos_embed"] = interpolate_pos_embed( + state_dict["visual_encoder_m.pos_embed"], model.visual_encoder_m + ) + for key in model.state_dict().keys(): + if key in state_dict.keys(): + if state_dict[key].shape != model.state_dict()[key].shape: + del state_dict[key] + + msg = model.load_state_dict(state_dict, strict=False) + print("load checkpoint from %s" % url_or_filename) + return model, msg diff --git a/comfyui-art-venture/modules/interrogate/models/blip_itm.py b/comfyui-art-venture/modules/interrogate/models/blip_itm.py new file mode 100644 index 0000000000000000000000000000000000000000..2d05b1cc341686e5b0ea3aac0c75467eceda3ed6 --- /dev/null +++ b/comfyui-art-venture/modules/interrogate/models/blip_itm.py @@ -0,0 +1,89 @@ +import torch +import torch.nn.functional as F +from torch import nn + + +from .blip import create_vit, init_tokenizer, load_checkpoint +from .med import BertConfig, BertModel + + +class BLIP_ITM(nn.Module): + def __init__( + self, + med_config="configs/med_config.json", + image_size=384, + vit="base", + vit_grad_ckpt=False, + vit_ckpt_layer=0, + embed_dim=256, + ): + """ + Args: + med_config (str): path for the mixture of encoder-decoder model's configuration file + image_size (int): input image size + vit (str): model size of vision transformer + """ + super().__init__() + + self.visual_encoder, vision_width = create_vit( + vit, image_size, vit_grad_ckpt, vit_ckpt_layer + ) + self.tokenizer = init_tokenizer() + med_config = BertConfig.from_json_file(med_config) + med_config.encoder_width = vision_width + self.text_encoder = BertModel(config=med_config, add_pooling_layer=False) + + text_width = self.text_encoder.config.hidden_size + + self.vision_proj = nn.Linear(vision_width, embed_dim) + self.text_proj = nn.Linear(text_width, embed_dim) + + self.itm_head = nn.Linear(text_width, 2) + + def forward(self, image, caption, match_head="itm"): + image_embeds = self.visual_encoder(image) + image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to( + image.device + ) + + text = self.tokenizer( + caption, + padding="max_length", + truncation=True, + max_length=35, + return_tensors="pt", + ).to(image.device) + + if match_head == "itm": + output = self.text_encoder( + text.input_ids, + attention_mask=text.attention_mask, + encoder_hidden_states=image_embeds, + encoder_attention_mask=image_atts, + return_dict=True, + ) + itm_output = self.itm_head(output.last_hidden_state[:, 0, :]) + return itm_output + + elif match_head == "itc": + text_output = self.text_encoder( + text.input_ids, + attention_mask=text.attention_mask, + return_dict=True, + mode="text", + ) + image_feat = F.normalize(self.vision_proj(image_embeds[:, 0, :]), dim=-1) + text_feat = F.normalize( + self.text_proj(text_output.last_hidden_state[:, 0, :]), dim=-1 + ) + + sim = image_feat @ text_feat.t() + return sim + + +def blip_itm(pretrained="", **kwargs): + model = BLIP_ITM(**kwargs) + if pretrained: + model, msg = load_checkpoint(model, pretrained) + assert len(msg.missing_keys) == 0 + return model diff --git a/comfyui-art-venture/modules/interrogate/models/blip_nlvr.py b/comfyui-art-venture/modules/interrogate/models/blip_nlvr.py new file mode 100644 index 0000000000000000000000000000000000000000..b60f26a6671388ebda8146d60f8d500db7e19687 --- /dev/null +++ b/comfyui-art-venture/modules/interrogate/models/blip_nlvr.py @@ -0,0 +1,118 @@ +import torch +import torch.nn.functional as F +from torch import nn +from timm.models.hub import download_cached_file + + +from .med import BertConfig +from .nlvr_encoder import BertModel +from .vit import interpolate_pos_embed +from .blip import create_vit, init_tokenizer, is_url + + +class BLIP_NLVR(nn.Module): + def __init__( + self, + med_config="configs/med_config.json", + image_size=480, + vit="base", + vit_grad_ckpt=False, + vit_ckpt_layer=0, + ): + """ + Args: + med_config (str): path for the mixture of encoder-decoder model's configuration file + image_size (int): input image size + vit (str): model size of vision transformer + """ + super().__init__() + + self.visual_encoder, vision_width = create_vit( + vit, image_size, vit_grad_ckpt, vit_ckpt_layer, drop_path_rate=0.1 + ) + self.tokenizer = init_tokenizer() + med_config = BertConfig.from_json_file(med_config) + med_config.encoder_width = vision_width + self.text_encoder = BertModel(config=med_config, add_pooling_layer=False) + + self.cls_head = nn.Sequential( + nn.Linear( + self.text_encoder.config.hidden_size, + self.text_encoder.config.hidden_size, + ), + nn.ReLU(), + nn.Linear(self.text_encoder.config.hidden_size, 2), + ) + + def forward(self, image, text, targets, train=True): + image_embeds = self.visual_encoder(image) + image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to( + image.device + ) + image0_embeds, image1_embeds = torch.split(image_embeds, targets.size(0)) + + text = self.tokenizer(text, padding="longest", return_tensors="pt").to( + image.device + ) + text.input_ids[:, 0] = self.tokenizer.enc_token_id + + output = self.text_encoder( + text.input_ids, + attention_mask=text.attention_mask, + encoder_hidden_states=[image0_embeds, image1_embeds], + encoder_attention_mask=[ + image_atts[: image0_embeds.size(0)], + image_atts[image0_embeds.size(0) :], + ], + return_dict=True, + ) + hidden_state = output.last_hidden_state[:, 0, :] + prediction = self.cls_head(hidden_state) + + if train: + loss = F.cross_entropy(prediction, targets) + return loss + else: + return prediction + + +def blip_nlvr(pretrained="", **kwargs): + model = BLIP_NLVR(**kwargs) + if pretrained: + model, msg = load_checkpoint(model, pretrained) + print("missing keys:") + print(msg.missing_keys) + return model + + +def load_checkpoint(model, url_or_filename): + if is_url(url_or_filename): + cached_file = download_cached_file( + url_or_filename, check_hash=False, progress=True + ) + checkpoint = torch.load(cached_file, map_location="cpu") + elif os.path.isfile(url_or_filename): + checkpoint = torch.load(url_or_filename, map_location="cpu") + else: + raise RuntimeError("checkpoint url or path is invalid") + state_dict = checkpoint["model"] + + state_dict["visual_encoder.pos_embed"] = interpolate_pos_embed( + state_dict["visual_encoder.pos_embed"], model.visual_encoder + ) + + for key in list(state_dict.keys()): + if "crossattention.self." in key: + new_key0 = key.replace("self", "self0") + new_key1 = key.replace("self", "self1") + state_dict[new_key0] = state_dict[key] + state_dict[new_key1] = state_dict[key] + elif "crossattention.output.dense." in key: + new_key0 = key.replace("dense", "dense0") + new_key1 = key.replace("dense", "dense1") + state_dict[new_key0] = state_dict[key] + state_dict[new_key1] = state_dict[key] + + msg = model.load_state_dict(state_dict, strict=False) + print("load checkpoint from %s" % url_or_filename) + return model, msg diff --git a/comfyui-art-venture/modules/interrogate/models/blip_pretrain.py b/comfyui-art-venture/modules/interrogate/models/blip_pretrain.py new file mode 100644 index 0000000000000000000000000000000000000000..d5d61e3c9274a515a4af80afda8cad6a277ed570 --- /dev/null +++ b/comfyui-art-venture/modules/interrogate/models/blip_pretrain.py @@ -0,0 +1,339 @@ +''' + * Copyright (c) 2022, salesforce.com, inc. + * All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause + * By Junnan Li +''' +from .med import BertConfig, BertModel, BertLMHeadModel +from transformers import BertTokenizer +import transformers +transformers.logging.set_verbosity_error() + +import torch +from torch import nn +import torch.nn.functional as F + +from .blip import create_vit, init_tokenizer, load_checkpoint + +class BLIP_Pretrain(nn.Module): + def __init__(self, + med_config = 'configs/bert_config.json', + image_size = 224, + vit = 'base', + vit_grad_ckpt = False, + vit_ckpt_layer = 0, + embed_dim = 256, + queue_size = 57600, + momentum = 0.995, + ): + """ + Args: + med_config (str): path for the mixture of encoder-decoder model's configuration file + image_size (int): input image size + vit (str): model size of vision transformer + """ + super().__init__() + + self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer, 0) + + if vit=='base': + checkpoint = torch.hub.load_state_dict_from_url( + url="https://dl.fbaipublicfiles.com/deit/deit_base_patch16_224-b5f2ef4d.pth", + map_location="cpu", check_hash=True) + state_dict = checkpoint["model"] + msg = self.visual_encoder.load_state_dict(state_dict,strict=False) + elif vit=='large': + from timm.models.helpers import load_custom_pretrained + from timm.models.vision_transformer import default_cfgs + load_custom_pretrained(self.visual_encoder,default_cfgs['vit_large_patch16_224_in21k']) + + self.tokenizer = init_tokenizer() + encoder_config = BertConfig.from_json_file(med_config) + encoder_config.encoder_width = vision_width + self.text_encoder = BertModel.from_pretrained('bert-base-uncased',config=encoder_config, add_pooling_layer=False) + self.text_encoder.resize_token_embeddings(len(self.tokenizer)) + + text_width = self.text_encoder.config.hidden_size + + self.vision_proj = nn.Linear(vision_width, embed_dim) + self.text_proj = nn.Linear(text_width, embed_dim) + + self.itm_head = nn.Linear(text_width, 2) + + # create momentum encoders + self.visual_encoder_m, vision_width = create_vit(vit,image_size) + self.vision_proj_m = nn.Linear(vision_width, embed_dim) + self.text_encoder_m = BertModel(config=encoder_config, add_pooling_layer=False) + self.text_proj_m = nn.Linear(text_width, embed_dim) + + self.model_pairs = [[self.visual_encoder,self.visual_encoder_m], + [self.vision_proj,self.vision_proj_m], + [self.text_encoder,self.text_encoder_m], + [self.text_proj,self.text_proj_m], + ] + self.copy_params() + + # create the queue + self.register_buffer("image_queue", torch.randn(embed_dim, queue_size)) + self.register_buffer("text_queue", torch.randn(embed_dim, queue_size)) + self.register_buffer("queue_ptr", torch.zeros(1, dtype=torch.long)) + + self.image_queue = nn.functional.normalize(self.image_queue, dim=0) + self.text_queue = nn.functional.normalize(self.text_queue, dim=0) + + self.queue_size = queue_size + self.momentum = momentum + self.temp = nn.Parameter(0.07*torch.ones([])) + + # create the decoder + decoder_config = BertConfig.from_json_file(med_config) + decoder_config.encoder_width = vision_width + self.text_decoder = BertLMHeadModel.from_pretrained('bert-base-uncased',config=decoder_config) + self.text_decoder.resize_token_embeddings(len(self.tokenizer)) + tie_encoder_decoder_weights(self.text_encoder,self.text_decoder.bert,'','/attention') + + + def forward(self, image, caption, alpha): + with torch.no_grad(): + self.temp.clamp_(0.001,0.5) + + image_embeds = self.visual_encoder(image) + image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device) + image_feat = F.normalize(self.vision_proj(image_embeds[:,0,:]),dim=-1) + + text = self.tokenizer(caption, padding='max_length', truncation=True, max_length=30, + return_tensors="pt").to(image.device) + text_output = self.text_encoder(text.input_ids, attention_mask = text.attention_mask, + return_dict = True, mode = 'text') + text_feat = F.normalize(self.text_proj(text_output.last_hidden_state[:,0,:]),dim=-1) + + # get momentum features + with torch.no_grad(): + self._momentum_update() + image_embeds_m = self.visual_encoder_m(image) + image_feat_m = F.normalize(self.vision_proj_m(image_embeds_m[:,0,:]),dim=-1) + image_feat_all = torch.cat([image_feat_m.t(),self.image_queue.clone().detach()],dim=1) + + text_output_m = self.text_encoder_m(text.input_ids, attention_mask = text.attention_mask, + return_dict = True, mode = 'text') + text_feat_m = F.normalize(self.text_proj_m(text_output_m.last_hidden_state[:,0,:]),dim=-1) + text_feat_all = torch.cat([text_feat_m.t(),self.text_queue.clone().detach()],dim=1) + + sim_i2t_m = image_feat_m @ text_feat_all / self.temp + sim_t2i_m = text_feat_m @ image_feat_all / self.temp + + sim_targets = torch.zeros(sim_i2t_m.size()).to(image.device) + sim_targets.fill_diagonal_(1) + + sim_i2t_targets = alpha * F.softmax(sim_i2t_m, dim=1) + (1 - alpha) * sim_targets + sim_t2i_targets = alpha * F.softmax(sim_t2i_m, dim=1) + (1 - alpha) * sim_targets + + sim_i2t = image_feat @ text_feat_all / self.temp + sim_t2i = text_feat @ image_feat_all / self.temp + + loss_i2t = -torch.sum(F.log_softmax(sim_i2t, dim=1)*sim_i2t_targets,dim=1).mean() + loss_t2i = -torch.sum(F.log_softmax(sim_t2i, dim=1)*sim_t2i_targets,dim=1).mean() + + loss_ita = (loss_i2t+loss_t2i)/2 + + self._dequeue_and_enqueue(image_feat_m, text_feat_m) + + ###============== Image-text Matching ===================### + encoder_input_ids = text.input_ids.clone() + encoder_input_ids[:,0] = self.tokenizer.enc_token_id + + # forward the positve image-text pair + bs = image.size(0) + output_pos = self.text_encoder(encoder_input_ids, + attention_mask = text.attention_mask, + encoder_hidden_states = image_embeds, + encoder_attention_mask = image_atts, + return_dict = True, + ) + with torch.no_grad(): + weights_t2i = F.softmax(sim_t2i[:,:bs],dim=1)+1e-4 + weights_t2i.fill_diagonal_(0) + weights_i2t = F.softmax(sim_i2t[:,:bs],dim=1)+1e-4 + weights_i2t.fill_diagonal_(0) + + # select a negative image for each text + image_embeds_neg = [] + for b in range(bs): + neg_idx = torch.multinomial(weights_t2i[b], 1).item() + image_embeds_neg.append(image_embeds[neg_idx]) + image_embeds_neg = torch.stack(image_embeds_neg,dim=0) + + # select a negative text for each image + text_ids_neg = [] + text_atts_neg = [] + for b in range(bs): + neg_idx = torch.multinomial(weights_i2t[b], 1).item() + text_ids_neg.append(encoder_input_ids[neg_idx]) + text_atts_neg.append(text.attention_mask[neg_idx]) + + text_ids_neg = torch.stack(text_ids_neg,dim=0) + text_atts_neg = torch.stack(text_atts_neg,dim=0) + + text_ids_all = torch.cat([encoder_input_ids, text_ids_neg],dim=0) + text_atts_all = torch.cat([text.attention_mask, text_atts_neg],dim=0) + + image_embeds_all = torch.cat([image_embeds_neg,image_embeds],dim=0) + image_atts_all = torch.cat([image_atts,image_atts],dim=0) + + output_neg = self.text_encoder(text_ids_all, + attention_mask = text_atts_all, + encoder_hidden_states = image_embeds_all, + encoder_attention_mask = image_atts_all, + return_dict = True, + ) + + vl_embeddings = torch.cat([output_pos.last_hidden_state[:,0,:], output_neg.last_hidden_state[:,0,:]],dim=0) + vl_output = self.itm_head(vl_embeddings) + + itm_labels = torch.cat([torch.ones(bs,dtype=torch.long),torch.zeros(2*bs,dtype=torch.long)], + dim=0).to(image.device) + loss_itm = F.cross_entropy(vl_output, itm_labels) + + ##================= LM ========================## + decoder_input_ids = text.input_ids.clone() + decoder_input_ids[:,0] = self.tokenizer.bos_token_id + decoder_targets = decoder_input_ids.masked_fill(decoder_input_ids == self.tokenizer.pad_token_id, -100) + + decoder_output = self.text_decoder(decoder_input_ids, + attention_mask = text.attention_mask, + encoder_hidden_states = image_embeds, + encoder_attention_mask = image_atts, + labels = decoder_targets, + return_dict = True, + ) + + loss_lm = decoder_output.loss + return loss_ita, loss_itm, loss_lm + + + + @torch.no_grad() + def copy_params(self): + for model_pair in self.model_pairs: + for param, param_m in zip(model_pair[0].parameters(), model_pair[1].parameters()): + param_m.data.copy_(param.data) # initialize + param_m.requires_grad = False # not update by gradient + + + @torch.no_grad() + def _momentum_update(self): + for model_pair in self.model_pairs: + for param, param_m in zip(model_pair[0].parameters(), model_pair[1].parameters()): + param_m.data = param_m.data * self.momentum + param.data * (1. - self.momentum) + + + @torch.no_grad() + def _dequeue_and_enqueue(self, image_feat, text_feat): + # gather keys before updating queue + image_feats = concat_all_gather(image_feat) + text_feats = concat_all_gather(text_feat) + + batch_size = image_feats.shape[0] + + ptr = int(self.queue_ptr) + assert self.queue_size % batch_size == 0 # for simplicity + + # replace the keys at ptr (dequeue and enqueue) + self.image_queue[:, ptr:ptr + batch_size] = image_feats.T + self.text_queue[:, ptr:ptr + batch_size] = text_feats.T + ptr = (ptr + batch_size) % self.queue_size # move pointer + + self.queue_ptr[0] = ptr + + +def blip_pretrain(**kwargs): + model = BLIP_Pretrain(**kwargs) + return model + + +@torch.no_grad() +def concat_all_gather(tensor): + """ + Performs all_gather operation on the provided tensors. + *** Warning ***: torch.distributed.all_gather has no gradient. + """ + tensors_gather = [torch.ones_like(tensor) + for _ in range(torch.distributed.get_world_size())] + torch.distributed.all_gather(tensors_gather, tensor, async_op=False) + + output = torch.cat(tensors_gather, dim=0) + return output + + +from typing import List +def tie_encoder_decoder_weights(encoder: nn.Module, decoder: nn.Module, base_model_prefix: str, skip_key:str): + uninitialized_encoder_weights: List[str] = [] + if decoder.__class__ != encoder.__class__: + logger.info( + f"{decoder.__class__} and {encoder.__class__} are not equal. In this case make sure that all encoder weights are correctly initialized." + ) + + def tie_encoder_to_decoder_recursively( + decoder_pointer: nn.Module, + encoder_pointer: nn.Module, + module_name: str, + uninitialized_encoder_weights: List[str], + skip_key: str, + depth=0, + ): + assert isinstance(decoder_pointer, nn.Module) and isinstance( + encoder_pointer, nn.Module + ), f"{decoder_pointer} and {encoder_pointer} have to be of type torch.nn.Module" + if hasattr(decoder_pointer, "weight") and skip_key not in module_name: + assert hasattr(encoder_pointer, "weight") + encoder_pointer.weight = decoder_pointer.weight + if hasattr(decoder_pointer, "bias"): + assert hasattr(encoder_pointer, "bias") + encoder_pointer.bias = decoder_pointer.bias + print(module_name+' is tied') + return + + encoder_modules = encoder_pointer._modules + decoder_modules = decoder_pointer._modules + if len(decoder_modules) > 0: + assert ( + len(encoder_modules) > 0 + ), f"Encoder module {encoder_pointer} does not match decoder module {decoder_pointer}" + + all_encoder_weights = set([module_name + "/" + sub_name for sub_name in encoder_modules.keys()]) + encoder_layer_pos = 0 + for name, module in decoder_modules.items(): + if name.isdigit(): + encoder_name = str(int(name) + encoder_layer_pos) + decoder_name = name + if not isinstance(decoder_modules[decoder_name], type(encoder_modules[encoder_name])) and len( + encoder_modules + ) != len(decoder_modules): + # this can happen if the name corresponds to the position in a list module list of layers + # in this case the decoder has added a cross-attention that the encoder does not have + # thus skip this step and subtract one layer pos from encoder + encoder_layer_pos -= 1 + continue + elif name not in encoder_modules: + continue + elif depth > 500: + raise ValueError( + "Max depth of recursive function `tie_encoder_to_decoder` reached. It seems that there is a circular dependency between two or more `nn.Modules` of your model." + ) + else: + decoder_name = encoder_name = name + tie_encoder_to_decoder_recursively( + decoder_modules[decoder_name], + encoder_modules[encoder_name], + module_name + "/" + name, + uninitialized_encoder_weights, + skip_key, + depth=depth + 1, + ) + all_encoder_weights.remove(module_name + "/" + encoder_name) + + uninitialized_encoder_weights += list(all_encoder_weights) + + # tie weights recursively + tie_encoder_to_decoder_recursively(decoder, encoder, base_model_prefix, uninitialized_encoder_weights, skip_key) diff --git a/comfyui-art-venture/modules/interrogate/models/blip_retrieval.py b/comfyui-art-venture/modules/interrogate/models/blip_retrieval.py new file mode 100644 index 0000000000000000000000000000000000000000..8961bed11ed925d8a4daae97ffce6faf939e56a0 --- /dev/null +++ b/comfyui-art-venture/modules/interrogate/models/blip_retrieval.py @@ -0,0 +1,367 @@ +import torch +import torch.nn.functional as F +from torch import nn + +from .blip import create_vit, init_tokenizer, load_checkpoint +from .med import BertConfig, BertModel + + +class BLIP_Retrieval(nn.Module): + def __init__( + self, + med_config="configs/med_config.json", + image_size=384, + vit="base", + vit_grad_ckpt=False, + vit_ckpt_layer=0, + embed_dim=256, + queue_size=57600, + momentum=0.995, + negative_all_rank=False, + ): + """ + Args: + med_config (str): path for the mixture of encoder-decoder model's configuration file + image_size (int): input image size + vit (str): model size of vision transformer + """ + super().__init__() + + self.visual_encoder, vision_width = create_vit( + vit, image_size, vit_grad_ckpt, vit_ckpt_layer + ) + self.tokenizer = init_tokenizer() + med_config = BertConfig.from_json_file(med_config) + med_config.encoder_width = vision_width + self.text_encoder = BertModel(config=med_config, add_pooling_layer=False) + + text_width = self.text_encoder.config.hidden_size + + self.vision_proj = nn.Linear(vision_width, embed_dim) + self.text_proj = nn.Linear(text_width, embed_dim) + + self.itm_head = nn.Linear(text_width, 2) + + # create momentum encoders + self.visual_encoder_m, vision_width = create_vit(vit, image_size) + self.vision_proj_m = nn.Linear(vision_width, embed_dim) + self.text_encoder_m = BertModel(config=med_config, add_pooling_layer=False) + self.text_proj_m = nn.Linear(text_width, embed_dim) + + self.model_pairs = [ + [self.visual_encoder, self.visual_encoder_m], + [self.vision_proj, self.vision_proj_m], + [self.text_encoder, self.text_encoder_m], + [self.text_proj, self.text_proj_m], + ] + self.copy_params() + + # create the queue + self.register_buffer("image_queue", torch.randn(embed_dim, queue_size)) + self.register_buffer("text_queue", torch.randn(embed_dim, queue_size)) + self.register_buffer("idx_queue", torch.full((1, queue_size), -100)) + self.register_buffer("ptr_queue", torch.zeros(1, dtype=torch.long)) + + self.image_queue = nn.functional.normalize(self.image_queue, dim=0) + self.text_queue = nn.functional.normalize(self.text_queue, dim=0) + + self.queue_size = queue_size + self.momentum = momentum + self.temp = nn.Parameter(0.07 * torch.ones([])) + + self.negative_all_rank = negative_all_rank + + def forward(self, image, caption, alpha, idx): + with torch.no_grad(): + self.temp.clamp_(0.001, 0.5) + + image_embeds = self.visual_encoder(image) + image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to( + image.device + ) + image_feat = F.normalize(self.vision_proj(image_embeds[:, 0, :]), dim=-1) + + text = self.tokenizer( + caption, + padding="max_length", + truncation=True, + max_length=35, + return_tensors="pt", + ).to(image.device) + + text_output = self.text_encoder( + text.input_ids, + attention_mask=text.attention_mask, + return_dict=True, + mode="text", + ) + text_feat = F.normalize( + self.text_proj(text_output.last_hidden_state[:, 0, :]), dim=-1 + ) + + ###============== Image-text Contrastive Learning ===================### + idx = idx.view(-1, 1) + idx_all = torch.cat([idx.t(), self.idx_queue.clone().detach()], dim=1) + pos_idx = torch.eq(idx, idx_all).float() + sim_targets = pos_idx / pos_idx.sum(1, keepdim=True) + + # get momentum features + with torch.no_grad(): + self._momentum_update() + image_embeds_m = self.visual_encoder_m(image) + image_feat_m = F.normalize( + self.vision_proj_m(image_embeds_m[:, 0, :]), dim=-1 + ) + image_feat_m_all = torch.cat( + [image_feat_m.t(), self.image_queue.clone().detach()], dim=1 + ) + + text_output_m = self.text_encoder_m( + text.input_ids, + attention_mask=text.attention_mask, + return_dict=True, + mode="text", + ) + text_feat_m = F.normalize( + self.text_proj_m(text_output_m.last_hidden_state[:, 0, :]), dim=-1 + ) + text_feat_m_all = torch.cat( + [text_feat_m.t(), self.text_queue.clone().detach()], dim=1 + ) + + sim_i2t_m = image_feat_m @ text_feat_m_all / self.temp + sim_t2i_m = text_feat_m @ image_feat_m_all / self.temp + + sim_i2t_targets = ( + alpha * F.softmax(sim_i2t_m, dim=1) + (1 - alpha) * sim_targets + ) + sim_t2i_targets = ( + alpha * F.softmax(sim_t2i_m, dim=1) + (1 - alpha) * sim_targets + ) + + sim_i2t = image_feat @ text_feat_m_all / self.temp + sim_t2i = text_feat @ image_feat_m_all / self.temp + + loss_i2t = -torch.sum( + F.log_softmax(sim_i2t, dim=1) * sim_i2t_targets, dim=1 + ).mean() + loss_t2i = -torch.sum( + F.log_softmax(sim_t2i, dim=1) * sim_t2i_targets, dim=1 + ).mean() + + loss_ita = (loss_i2t + loss_t2i) / 2 + + idxs = concat_all_gather(idx) + self._dequeue_and_enqueue(image_feat_m, text_feat_m, idxs) + + ###============== Image-text Matching ===================### + encoder_input_ids = text.input_ids.clone() + encoder_input_ids[:, 0] = self.tokenizer.enc_token_id + + # forward the positve image-text pair + bs = image.size(0) + output_pos = self.text_encoder( + encoder_input_ids, + attention_mask=text.attention_mask, + encoder_hidden_states=image_embeds, + encoder_attention_mask=image_atts, + return_dict=True, + ) + + if self.negative_all_rank: + # compute sample similarity + with torch.no_grad(): + mask = torch.eq(idx, idxs.t()) + + image_feat_world = concat_all_gather(image_feat) + text_feat_world = concat_all_gather(text_feat) + + sim_i2t = image_feat @ text_feat_world.t() / self.temp + sim_t2i = text_feat @ image_feat_world.t() / self.temp + + weights_i2t = F.softmax(sim_i2t, dim=1) + weights_i2t.masked_fill_(mask, 0) + + weights_t2i = F.softmax(sim_t2i, dim=1) + weights_t2i.masked_fill_(mask, 0) + + image_embeds_world = all_gather_with_grad(image_embeds) + + # select a negative image (from all ranks) for each text + image_embeds_neg = [] + for b in range(bs): + neg_idx = torch.multinomial(weights_t2i[b], 1).item() + image_embeds_neg.append(image_embeds_world[neg_idx]) + image_embeds_neg = torch.stack(image_embeds_neg, dim=0) + + # select a negative text (from all ranks) for each image + input_ids_world = concat_all_gather(encoder_input_ids) + att_mask_world = concat_all_gather(text.attention_mask) + + text_ids_neg = [] + text_atts_neg = [] + for b in range(bs): + neg_idx = torch.multinomial(weights_i2t[b], 1).item() + text_ids_neg.append(input_ids_world[neg_idx]) + text_atts_neg.append(att_mask_world[neg_idx]) + + else: + with torch.no_grad(): + mask = torch.eq(idx, idx.t()) + + sim_i2t = image_feat @ text_feat.t() / self.temp + sim_t2i = text_feat @ image_feat.t() / self.temp + + weights_i2t = F.softmax(sim_i2t, dim=1) + weights_i2t.masked_fill_(mask, 0) + + weights_t2i = F.softmax(sim_t2i, dim=1) + weights_t2i.masked_fill_(mask, 0) + + # select a negative image (from same rank) for each text + image_embeds_neg = [] + for b in range(bs): + neg_idx = torch.multinomial(weights_t2i[b], 1).item() + image_embeds_neg.append(image_embeds[neg_idx]) + image_embeds_neg = torch.stack(image_embeds_neg, dim=0) + + # select a negative text (from same rank) for each image + text_ids_neg = [] + text_atts_neg = [] + for b in range(bs): + neg_idx = torch.multinomial(weights_i2t[b], 1).item() + text_ids_neg.append(encoder_input_ids[neg_idx]) + text_atts_neg.append(text.attention_mask[neg_idx]) + + text_ids_neg = torch.stack(text_ids_neg, dim=0) + text_atts_neg = torch.stack(text_atts_neg, dim=0) + + text_ids_all = torch.cat([encoder_input_ids, text_ids_neg], dim=0) + text_atts_all = torch.cat([text.attention_mask, text_atts_neg], dim=0) + + image_embeds_all = torch.cat([image_embeds_neg, image_embeds], dim=0) + image_atts_all = torch.cat([image_atts, image_atts], dim=0) + + output_neg = self.text_encoder( + text_ids_all, + attention_mask=text_atts_all, + encoder_hidden_states=image_embeds_all, + encoder_attention_mask=image_atts_all, + return_dict=True, + ) + + vl_embeddings = torch.cat( + [ + output_pos.last_hidden_state[:, 0, :], + output_neg.last_hidden_state[:, 0, :], + ], + dim=0, + ) + vl_output = self.itm_head(vl_embeddings) + + itm_labels = torch.cat( + [torch.ones(bs, dtype=torch.long), torch.zeros(2 * bs, dtype=torch.long)], + dim=0, + ).to(image.device) + loss_itm = F.cross_entropy(vl_output, itm_labels) + + return loss_ita, loss_itm + + @torch.no_grad() + def copy_params(self): + for model_pair in self.model_pairs: + for param, param_m in zip( + model_pair[0].parameters(), model_pair[1].parameters() + ): + param_m.data.copy_(param.data) # initialize + param_m.requires_grad = False # not update by gradient + + @torch.no_grad() + def _momentum_update(self): + for model_pair in self.model_pairs: + for param, param_m in zip( + model_pair[0].parameters(), model_pair[1].parameters() + ): + param_m.data = param_m.data * self.momentum + param.data * ( + 1.0 - self.momentum + ) + + @torch.no_grad() + def _dequeue_and_enqueue(self, image_feat, text_feat, idxs): + # gather keys before updating queue + image_feats = concat_all_gather(image_feat) + text_feats = concat_all_gather(text_feat) + + batch_size = image_feats.shape[0] + + ptr = int(self.ptr_queue) + assert self.queue_size % batch_size == 0 # for simplicity + + # replace the keys at ptr (dequeue and enqueue) + self.image_queue[:, ptr : ptr + batch_size] = image_feats.T + self.text_queue[:, ptr : ptr + batch_size] = text_feats.T + self.idx_queue[:, ptr : ptr + batch_size] = idxs.T + ptr = (ptr + batch_size) % self.queue_size # move pointer + + self.ptr_queue[0] = ptr + + +def blip_retrieval(pretrained="", **kwargs): + model = BLIP_Retrieval(**kwargs) + if pretrained: + model, msg = load_checkpoint(model, pretrained) + print("missing keys:") + print(msg.missing_keys) + return model + + +@torch.no_grad() +def concat_all_gather(tensor): + """ + Performs all_gather operation on the provided tensors. + *** Warning ***: torch.distributed.all_gather has no gradient. + """ + tensors_gather = [ + torch.ones_like(tensor) for _ in range(torch.distributed.get_world_size()) + ] + torch.distributed.all_gather(tensors_gather, tensor, async_op=False) + + output = torch.cat(tensors_gather, dim=0) + return output + + +class GatherLayer(torch.autograd.Function): + """ + Gather tensors from all workers with support for backward propagation: + This implementation does not cut the gradients as torch.distributed.all_gather does. + """ + + @staticmethod + def forward(ctx, x): + output = [ + torch.zeros_like(x) for _ in range(torch.distributed.get_world_size()) + ] + torch.distributed.all_gather(output, x) + return tuple(output) + + @staticmethod + def backward(ctx, *grads): + all_gradients = torch.stack(grads) + torch.distributed.all_reduce(all_gradients) + return all_gradients[torch.distributed.get_rank()] + + +def all_gather_with_grad(tensors): + """ + Performs all_gather operation on the provided tensors. + Graph remains connected for backward grad computation. + """ + # Queue the gathered tensors + world_size = torch.distributed.get_world_size() + # There is no need for reduction in the single-proc case + if world_size == 1: + return tensors + + tensor_all = GatherLayer.apply(tensors) + + return torch.cat(tensor_all, dim=0) diff --git a/comfyui-art-venture/modules/interrogate/models/blip_vqa.py b/comfyui-art-venture/modules/interrogate/models/blip_vqa.py new file mode 100644 index 0000000000000000000000000000000000000000..f3fd94b08c49cfc9cee97d8ea6305ba97d7b3c24 --- /dev/null +++ b/comfyui-art-venture/modules/interrogate/models/blip_vqa.py @@ -0,0 +1,236 @@ +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn + + +from .med import BertConfig, BertModel, BertLMHeadModel +from .blip import create_vit, init_tokenizer, load_checkpoint + + +class BLIP_VQA(nn.Module): + def __init__( + self, + med_config="configs/med_config.json", + image_size=480, + vit="base", + vit_grad_ckpt=False, + vit_ckpt_layer=0, + ): + """ + Args: + med_config (str): path for the mixture of encoder-decoder model's configuration file + image_size (int): input image size + vit (str): model size of vision transformer + """ + super().__init__() + + self.visual_encoder, vision_width = create_vit( + vit, image_size, vit_grad_ckpt, vit_ckpt_layer, drop_path_rate=0.1 + ) + self.tokenizer = init_tokenizer() + + encoder_config = BertConfig.from_json_file(med_config) + encoder_config.encoder_width = vision_width + self.text_encoder = BertModel(config=encoder_config, add_pooling_layer=False) + + decoder_config = BertConfig.from_json_file(med_config) + self.text_decoder = BertLMHeadModel(config=decoder_config) + + def forward( + self, + image, + question, + answer=None, + n=None, + weights=None, + train=True, + inference="rank", + k_test=128, + ): + image_embeds = self.visual_encoder(image) + image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to( + image.device + ) + + question = self.tokenizer( + question, + padding="longest", + truncation=True, + max_length=35, + return_tensors="pt", + ).to(image.device) + question.input_ids[:, 0] = self.tokenizer.enc_token_id + + if train: + """ + n: number of answers for each question + weights: weight for each answer + """ + answer = self.tokenizer(answer, padding="longest", return_tensors="pt").to( + image.device + ) + answer.input_ids[:, 0] = self.tokenizer.bos_token_id + answer_targets = answer.input_ids.masked_fill( + answer.input_ids == self.tokenizer.pad_token_id, -100 + ) + + question_output = self.text_encoder( + question.input_ids, + attention_mask=question.attention_mask, + encoder_hidden_states=image_embeds, + encoder_attention_mask=image_atts, + return_dict=True, + ) + + question_states = [] + question_atts = [] + for b, n in enumerate(n): + question_states += [question_output.last_hidden_state[b]] * n + question_atts += [question.attention_mask[b]] * n + question_states = torch.stack(question_states, 0) + question_atts = torch.stack(question_atts, 0) + + answer_output = self.text_decoder( + answer.input_ids, + attention_mask=answer.attention_mask, + encoder_hidden_states=question_states, + encoder_attention_mask=question_atts, + labels=answer_targets, + return_dict=True, + reduction="none", + ) + + loss = weights * answer_output.loss + loss = loss.sum() / image.size(0) + + return loss + + else: + question_output = self.text_encoder( + question.input_ids, + attention_mask=question.attention_mask, + encoder_hidden_states=image_embeds, + encoder_attention_mask=image_atts, + return_dict=True, + ) + + if inference == "generate": + num_beams = 3 + question_states = question_output.last_hidden_state.repeat_interleave( + num_beams, dim=0 + ) + question_atts = torch.ones( + question_states.size()[:-1], dtype=torch.long + ).to(question_states.device) + model_kwargs = { + "encoder_hidden_states": question_states, + "encoder_attention_mask": question_atts, + } + + bos_ids = torch.full( + (image.size(0), 1), + fill_value=self.tokenizer.bos_token_id, + device=image.device, + ) + + outputs = self.text_decoder.generate( + input_ids=bos_ids, + max_length=10, + min_length=1, + num_beams=num_beams, + eos_token_id=self.tokenizer.sep_token_id, + pad_token_id=self.tokenizer.pad_token_id, + **model_kwargs + ) + + answers = [] + for output in outputs: + answer = self.tokenizer.decode(output, skip_special_tokens=True) + answers.append(answer) + return answers + + elif inference == "rank": + max_ids = self.rank_answer( + question_output.last_hidden_state, + question.attention_mask, + answer.input_ids, + answer.attention_mask, + k_test, + ) + return max_ids + + def rank_answer(self, question_states, question_atts, answer_ids, answer_atts, k): + num_ques = question_states.size(0) + start_ids = answer_ids[0, 0].repeat(num_ques, 1) # bos token + + start_output = self.text_decoder( + start_ids, + encoder_hidden_states=question_states, + encoder_attention_mask=question_atts, + return_dict=True, + reduction="none", + ) + logits = start_output.logits[:, 0, :] # first token's logit + + # topk_probs: top-k probability + # topk_ids: [num_question, k] + answer_first_token = answer_ids[:, 1] + prob_first_token = F.softmax(logits, dim=1).index_select( + dim=1, index=answer_first_token + ) + topk_probs, topk_ids = prob_first_token.topk(k, dim=1) + + # answer input: [num_question*k, answer_len] + input_ids = [] + input_atts = [] + for b, topk_id in enumerate(topk_ids): + input_ids.append(answer_ids.index_select(dim=0, index=topk_id)) + input_atts.append(answer_atts.index_select(dim=0, index=topk_id)) + input_ids = torch.cat(input_ids, dim=0) + input_atts = torch.cat(input_atts, dim=0) + + targets_ids = input_ids.masked_fill( + input_ids == self.tokenizer.pad_token_id, -100 + ) + + # repeat encoder's output for top-k answers + question_states = tile(question_states, 0, k) + question_atts = tile(question_atts, 0, k) + + output = self.text_decoder( + input_ids, + attention_mask=input_atts, + encoder_hidden_states=question_states, + encoder_attention_mask=question_atts, + labels=targets_ids, + return_dict=True, + reduction="none", + ) + + log_probs_sum = -output.loss + log_probs_sum = log_probs_sum.view(num_ques, k) + + max_topk_ids = log_probs_sum.argmax(dim=1) + max_ids = topk_ids[max_topk_ids >= 0, max_topk_ids] + + return max_ids + + +def blip_vqa(pretrained="", **kwargs): + model = BLIP_VQA(**kwargs) + if pretrained: + model, msg = load_checkpoint(model, pretrained) + # assert(len(msg.missing_keys)==0) + return model + + +def tile(x, dim, n_tile): + init_dim = x.size(dim) + repeat_idx = [1] * x.dim() + repeat_idx[dim] = n_tile + x = x.repeat(*(repeat_idx)) + order_index = torch.LongTensor( + np.concatenate([init_dim * np.arange(n_tile) + i for i in range(init_dim)]) + ) + return torch.index_select(x, dim, order_index.to(x.device)) diff --git a/comfyui-art-venture/modules/interrogate/models/deepbooru_model.py b/comfyui-art-venture/modules/interrogate/models/deepbooru_model.py new file mode 100644 index 0000000000000000000000000000000000000000..c9311e71a0ae1f8070dbab126e832bfb3f6fb204 --- /dev/null +++ b/comfyui-art-venture/modules/interrogate/models/deepbooru_model.py @@ -0,0 +1,678 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + +unet_needs_upcast = False + +# see https://github.com/AUTOMATIC1111/TorchDeepDanbooru for more + + +class DeepDanbooruModel(nn.Module): + def __init__(self): + super(DeepDanbooruModel, self).__init__() + + self.tags = [] + + self.n_Conv_0 = nn.Conv2d(kernel_size=(7, 7), in_channels=3, out_channels=64, stride=(2, 2)) + self.n_MaxPool_0 = nn.MaxPool2d(kernel_size=(3, 3), stride=(2, 2)) + self.n_Conv_1 = nn.Conv2d(kernel_size=(1, 1), in_channels=64, out_channels=256) + self.n_Conv_2 = nn.Conv2d(kernel_size=(1, 1), in_channels=64, out_channels=64) + self.n_Conv_3 = nn.Conv2d(kernel_size=(3, 3), in_channels=64, out_channels=64) + self.n_Conv_4 = nn.Conv2d(kernel_size=(1, 1), in_channels=64, out_channels=256) + self.n_Conv_5 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=64) + self.n_Conv_6 = nn.Conv2d(kernel_size=(3, 3), in_channels=64, out_channels=64) + self.n_Conv_7 = nn.Conv2d(kernel_size=(1, 1), in_channels=64, out_channels=256) + self.n_Conv_8 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=64) + self.n_Conv_9 = nn.Conv2d(kernel_size=(3, 3), in_channels=64, out_channels=64) + self.n_Conv_10 = nn.Conv2d(kernel_size=(1, 1), in_channels=64, out_channels=256) + self.n_Conv_11 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=512, stride=(2, 2)) + self.n_Conv_12 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=128) + self.n_Conv_13 = nn.Conv2d(kernel_size=(3, 3), in_channels=128, out_channels=128, stride=(2, 2)) + self.n_Conv_14 = nn.Conv2d(kernel_size=(1, 1), in_channels=128, out_channels=512) + self.n_Conv_15 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=128) + self.n_Conv_16 = nn.Conv2d(kernel_size=(3, 3), in_channels=128, out_channels=128) + self.n_Conv_17 = nn.Conv2d(kernel_size=(1, 1), in_channels=128, out_channels=512) + self.n_Conv_18 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=128) + self.n_Conv_19 = nn.Conv2d(kernel_size=(3, 3), in_channels=128, out_channels=128) + self.n_Conv_20 = nn.Conv2d(kernel_size=(1, 1), in_channels=128, out_channels=512) + self.n_Conv_21 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=128) + self.n_Conv_22 = nn.Conv2d(kernel_size=(3, 3), in_channels=128, out_channels=128) + self.n_Conv_23 = nn.Conv2d(kernel_size=(1, 1), in_channels=128, out_channels=512) + self.n_Conv_24 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=128) + self.n_Conv_25 = nn.Conv2d(kernel_size=(3, 3), in_channels=128, out_channels=128) + self.n_Conv_26 = nn.Conv2d(kernel_size=(1, 1), in_channels=128, out_channels=512) + self.n_Conv_27 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=128) + self.n_Conv_28 = nn.Conv2d(kernel_size=(3, 3), in_channels=128, out_channels=128) + self.n_Conv_29 = nn.Conv2d(kernel_size=(1, 1), in_channels=128, out_channels=512) + self.n_Conv_30 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=128) + self.n_Conv_31 = nn.Conv2d(kernel_size=(3, 3), in_channels=128, out_channels=128) + self.n_Conv_32 = nn.Conv2d(kernel_size=(1, 1), in_channels=128, out_channels=512) + self.n_Conv_33 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=128) + self.n_Conv_34 = nn.Conv2d(kernel_size=(3, 3), in_channels=128, out_channels=128) + self.n_Conv_35 = nn.Conv2d(kernel_size=(1, 1), in_channels=128, out_channels=512) + self.n_Conv_36 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=1024, stride=(2, 2)) + self.n_Conv_37 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=256) + self.n_Conv_38 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256, stride=(2, 2)) + self.n_Conv_39 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_40 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_41 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_42 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_43 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_44 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_45 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_46 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_47 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_48 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_49 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_50 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_51 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_52 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_53 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_54 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_55 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_56 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_57 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_58 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_59 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_60 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_61 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_62 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_63 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_64 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_65 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_66 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_67 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_68 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_69 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_70 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_71 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_72 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_73 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_74 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_75 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_76 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_77 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_78 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_79 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_80 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_81 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_82 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_83 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_84 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_85 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_86 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_87 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_88 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_89 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_90 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_91 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_92 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_93 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_94 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_95 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_96 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_97 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_98 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256, stride=(2, 2)) + self.n_Conv_99 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_100 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=1024, stride=(2, 2)) + self.n_Conv_101 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_102 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_103 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_104 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_105 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_106 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_107 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_108 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_109 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_110 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_111 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_112 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_113 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_114 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_115 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_116 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_117 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_118 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_119 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_120 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_121 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_122 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_123 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_124 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_125 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_126 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_127 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_128 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_129 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_130 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_131 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_132 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_133 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_134 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_135 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_136 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_137 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_138 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_139 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_140 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_141 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_142 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_143 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_144 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_145 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_146 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_147 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_148 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_149 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_150 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_151 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_152 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_153 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_154 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_155 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=256) + self.n_Conv_156 = nn.Conv2d(kernel_size=(3, 3), in_channels=256, out_channels=256) + self.n_Conv_157 = nn.Conv2d(kernel_size=(1, 1), in_channels=256, out_channels=1024) + self.n_Conv_158 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=2048, stride=(2, 2)) + self.n_Conv_159 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=512) + self.n_Conv_160 = nn.Conv2d(kernel_size=(3, 3), in_channels=512, out_channels=512, stride=(2, 2)) + self.n_Conv_161 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=2048) + self.n_Conv_162 = nn.Conv2d(kernel_size=(1, 1), in_channels=2048, out_channels=512) + self.n_Conv_163 = nn.Conv2d(kernel_size=(3, 3), in_channels=512, out_channels=512) + self.n_Conv_164 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=2048) + self.n_Conv_165 = nn.Conv2d(kernel_size=(1, 1), in_channels=2048, out_channels=512) + self.n_Conv_166 = nn.Conv2d(kernel_size=(3, 3), in_channels=512, out_channels=512) + self.n_Conv_167 = nn.Conv2d(kernel_size=(1, 1), in_channels=512, out_channels=2048) + self.n_Conv_168 = nn.Conv2d(kernel_size=(1, 1), in_channels=2048, out_channels=4096, stride=(2, 2)) + self.n_Conv_169 = nn.Conv2d(kernel_size=(1, 1), in_channels=2048, out_channels=1024) + self.n_Conv_170 = nn.Conv2d(kernel_size=(3, 3), in_channels=1024, out_channels=1024, stride=(2, 2)) + self.n_Conv_171 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=4096) + self.n_Conv_172 = nn.Conv2d(kernel_size=(1, 1), in_channels=4096, out_channels=1024) + self.n_Conv_173 = nn.Conv2d(kernel_size=(3, 3), in_channels=1024, out_channels=1024) + self.n_Conv_174 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=4096) + self.n_Conv_175 = nn.Conv2d(kernel_size=(1, 1), in_channels=4096, out_channels=1024) + self.n_Conv_176 = nn.Conv2d(kernel_size=(3, 3), in_channels=1024, out_channels=1024) + self.n_Conv_177 = nn.Conv2d(kernel_size=(1, 1), in_channels=1024, out_channels=4096) + self.n_Conv_178 = nn.Conv2d(kernel_size=(1, 1), in_channels=4096, out_channels=9176, bias=False) + + def forward(self, *inputs): + t_358, = inputs + t_359 = t_358.permute(*[0, 3, 1, 2]) + t_359_padded = F.pad(t_359, [2, 3, 2, 3], value=0) + t_360 = self.n_Conv_0(t_359_padded.to(self.n_Conv_0.bias.dtype) if unet_needs_upcast else t_359_padded) + t_361 = F.relu(t_360) + t_361 = F.pad(t_361, [0, 1, 0, 1], value=float('-inf')) + t_362 = self.n_MaxPool_0(t_361) + t_363 = self.n_Conv_1(t_362) + t_364 = self.n_Conv_2(t_362) + t_365 = F.relu(t_364) + t_365_padded = F.pad(t_365, [1, 1, 1, 1], value=0) + t_366 = self.n_Conv_3(t_365_padded) + t_367 = F.relu(t_366) + t_368 = self.n_Conv_4(t_367) + t_369 = torch.add(t_368, t_363) + t_370 = F.relu(t_369) + t_371 = self.n_Conv_5(t_370) + t_372 = F.relu(t_371) + t_372_padded = F.pad(t_372, [1, 1, 1, 1], value=0) + t_373 = self.n_Conv_6(t_372_padded) + t_374 = F.relu(t_373) + t_375 = self.n_Conv_7(t_374) + t_376 = torch.add(t_375, t_370) + t_377 = F.relu(t_376) + t_378 = self.n_Conv_8(t_377) + t_379 = F.relu(t_378) + t_379_padded = F.pad(t_379, [1, 1, 1, 1], value=0) + t_380 = self.n_Conv_9(t_379_padded) + t_381 = F.relu(t_380) + t_382 = self.n_Conv_10(t_381) + t_383 = torch.add(t_382, t_377) + t_384 = F.relu(t_383) + t_385 = self.n_Conv_11(t_384) + t_386 = self.n_Conv_12(t_384) + t_387 = F.relu(t_386) + t_387_padded = F.pad(t_387, [0, 1, 0, 1], value=0) + t_388 = self.n_Conv_13(t_387_padded) + t_389 = F.relu(t_388) + t_390 = self.n_Conv_14(t_389) + t_391 = torch.add(t_390, t_385) + t_392 = F.relu(t_391) + t_393 = self.n_Conv_15(t_392) + t_394 = F.relu(t_393) + t_394_padded = F.pad(t_394, [1, 1, 1, 1], value=0) + t_395 = self.n_Conv_16(t_394_padded) + t_396 = F.relu(t_395) + t_397 = self.n_Conv_17(t_396) + t_398 = torch.add(t_397, t_392) + t_399 = F.relu(t_398) + t_400 = self.n_Conv_18(t_399) + t_401 = F.relu(t_400) + t_401_padded = F.pad(t_401, [1, 1, 1, 1], value=0) + t_402 = self.n_Conv_19(t_401_padded) + t_403 = F.relu(t_402) + t_404 = self.n_Conv_20(t_403) + t_405 = torch.add(t_404, t_399) + t_406 = F.relu(t_405) + t_407 = self.n_Conv_21(t_406) + t_408 = F.relu(t_407) + t_408_padded = F.pad(t_408, [1, 1, 1, 1], value=0) + t_409 = self.n_Conv_22(t_408_padded) + t_410 = F.relu(t_409) + t_411 = self.n_Conv_23(t_410) + t_412 = torch.add(t_411, t_406) + t_413 = F.relu(t_412) + t_414 = self.n_Conv_24(t_413) + t_415 = F.relu(t_414) + t_415_padded = F.pad(t_415, [1, 1, 1, 1], value=0) + t_416 = self.n_Conv_25(t_415_padded) + t_417 = F.relu(t_416) + t_418 = self.n_Conv_26(t_417) + t_419 = torch.add(t_418, t_413) + t_420 = F.relu(t_419) + t_421 = self.n_Conv_27(t_420) + t_422 = F.relu(t_421) + t_422_padded = F.pad(t_422, [1, 1, 1, 1], value=0) + t_423 = self.n_Conv_28(t_422_padded) + t_424 = F.relu(t_423) + t_425 = self.n_Conv_29(t_424) + t_426 = torch.add(t_425, t_420) + t_427 = F.relu(t_426) + t_428 = self.n_Conv_30(t_427) + t_429 = F.relu(t_428) + t_429_padded = F.pad(t_429, [1, 1, 1, 1], value=0) + t_430 = self.n_Conv_31(t_429_padded) + t_431 = F.relu(t_430) + t_432 = self.n_Conv_32(t_431) + t_433 = torch.add(t_432, t_427) + t_434 = F.relu(t_433) + t_435 = self.n_Conv_33(t_434) + t_436 = F.relu(t_435) + t_436_padded = F.pad(t_436, [1, 1, 1, 1], value=0) + t_437 = self.n_Conv_34(t_436_padded) + t_438 = F.relu(t_437) + t_439 = self.n_Conv_35(t_438) + t_440 = torch.add(t_439, t_434) + t_441 = F.relu(t_440) + t_442 = self.n_Conv_36(t_441) + t_443 = self.n_Conv_37(t_441) + t_444 = F.relu(t_443) + t_444_padded = F.pad(t_444, [0, 1, 0, 1], value=0) + t_445 = self.n_Conv_38(t_444_padded) + t_446 = F.relu(t_445) + t_447 = self.n_Conv_39(t_446) + t_448 = torch.add(t_447, t_442) + t_449 = F.relu(t_448) + t_450 = self.n_Conv_40(t_449) + t_451 = F.relu(t_450) + t_451_padded = F.pad(t_451, [1, 1, 1, 1], value=0) + t_452 = self.n_Conv_41(t_451_padded) + t_453 = F.relu(t_452) + t_454 = self.n_Conv_42(t_453) + t_455 = torch.add(t_454, t_449) + t_456 = F.relu(t_455) + t_457 = self.n_Conv_43(t_456) + t_458 = F.relu(t_457) + t_458_padded = F.pad(t_458, [1, 1, 1, 1], value=0) + t_459 = self.n_Conv_44(t_458_padded) + t_460 = F.relu(t_459) + t_461 = self.n_Conv_45(t_460) + t_462 = torch.add(t_461, t_456) + t_463 = F.relu(t_462) + t_464 = self.n_Conv_46(t_463) + t_465 = F.relu(t_464) + t_465_padded = F.pad(t_465, [1, 1, 1, 1], value=0) + t_466 = self.n_Conv_47(t_465_padded) + t_467 = F.relu(t_466) + t_468 = self.n_Conv_48(t_467) + t_469 = torch.add(t_468, t_463) + t_470 = F.relu(t_469) + t_471 = self.n_Conv_49(t_470) + t_472 = F.relu(t_471) + t_472_padded = F.pad(t_472, [1, 1, 1, 1], value=0) + t_473 = self.n_Conv_50(t_472_padded) + t_474 = F.relu(t_473) + t_475 = self.n_Conv_51(t_474) + t_476 = torch.add(t_475, t_470) + t_477 = F.relu(t_476) + t_478 = self.n_Conv_52(t_477) + t_479 = F.relu(t_478) + t_479_padded = F.pad(t_479, [1, 1, 1, 1], value=0) + t_480 = self.n_Conv_53(t_479_padded) + t_481 = F.relu(t_480) + t_482 = self.n_Conv_54(t_481) + t_483 = torch.add(t_482, t_477) + t_484 = F.relu(t_483) + t_485 = self.n_Conv_55(t_484) + t_486 = F.relu(t_485) + t_486_padded = F.pad(t_486, [1, 1, 1, 1], value=0) + t_487 = self.n_Conv_56(t_486_padded) + t_488 = F.relu(t_487) + t_489 = self.n_Conv_57(t_488) + t_490 = torch.add(t_489, t_484) + t_491 = F.relu(t_490) + t_492 = self.n_Conv_58(t_491) + t_493 = F.relu(t_492) + t_493_padded = F.pad(t_493, [1, 1, 1, 1], value=0) + t_494 = self.n_Conv_59(t_493_padded) + t_495 = F.relu(t_494) + t_496 = self.n_Conv_60(t_495) + t_497 = torch.add(t_496, t_491) + t_498 = F.relu(t_497) + t_499 = self.n_Conv_61(t_498) + t_500 = F.relu(t_499) + t_500_padded = F.pad(t_500, [1, 1, 1, 1], value=0) + t_501 = self.n_Conv_62(t_500_padded) + t_502 = F.relu(t_501) + t_503 = self.n_Conv_63(t_502) + t_504 = torch.add(t_503, t_498) + t_505 = F.relu(t_504) + t_506 = self.n_Conv_64(t_505) + t_507 = F.relu(t_506) + t_507_padded = F.pad(t_507, [1, 1, 1, 1], value=0) + t_508 = self.n_Conv_65(t_507_padded) + t_509 = F.relu(t_508) + t_510 = self.n_Conv_66(t_509) + t_511 = torch.add(t_510, t_505) + t_512 = F.relu(t_511) + t_513 = self.n_Conv_67(t_512) + t_514 = F.relu(t_513) + t_514_padded = F.pad(t_514, [1, 1, 1, 1], value=0) + t_515 = self.n_Conv_68(t_514_padded) + t_516 = F.relu(t_515) + t_517 = self.n_Conv_69(t_516) + t_518 = torch.add(t_517, t_512) + t_519 = F.relu(t_518) + t_520 = self.n_Conv_70(t_519) + t_521 = F.relu(t_520) + t_521_padded = F.pad(t_521, [1, 1, 1, 1], value=0) + t_522 = self.n_Conv_71(t_521_padded) + t_523 = F.relu(t_522) + t_524 = self.n_Conv_72(t_523) + t_525 = torch.add(t_524, t_519) + t_526 = F.relu(t_525) + t_527 = self.n_Conv_73(t_526) + t_528 = F.relu(t_527) + t_528_padded = F.pad(t_528, [1, 1, 1, 1], value=0) + t_529 = self.n_Conv_74(t_528_padded) + t_530 = F.relu(t_529) + t_531 = self.n_Conv_75(t_530) + t_532 = torch.add(t_531, t_526) + t_533 = F.relu(t_532) + t_534 = self.n_Conv_76(t_533) + t_535 = F.relu(t_534) + t_535_padded = F.pad(t_535, [1, 1, 1, 1], value=0) + t_536 = self.n_Conv_77(t_535_padded) + t_537 = F.relu(t_536) + t_538 = self.n_Conv_78(t_537) + t_539 = torch.add(t_538, t_533) + t_540 = F.relu(t_539) + t_541 = self.n_Conv_79(t_540) + t_542 = F.relu(t_541) + t_542_padded = F.pad(t_542, [1, 1, 1, 1], value=0) + t_543 = self.n_Conv_80(t_542_padded) + t_544 = F.relu(t_543) + t_545 = self.n_Conv_81(t_544) + t_546 = torch.add(t_545, t_540) + t_547 = F.relu(t_546) + t_548 = self.n_Conv_82(t_547) + t_549 = F.relu(t_548) + t_549_padded = F.pad(t_549, [1, 1, 1, 1], value=0) + t_550 = self.n_Conv_83(t_549_padded) + t_551 = F.relu(t_550) + t_552 = self.n_Conv_84(t_551) + t_553 = torch.add(t_552, t_547) + t_554 = F.relu(t_553) + t_555 = self.n_Conv_85(t_554) + t_556 = F.relu(t_555) + t_556_padded = F.pad(t_556, [1, 1, 1, 1], value=0) + t_557 = self.n_Conv_86(t_556_padded) + t_558 = F.relu(t_557) + t_559 = self.n_Conv_87(t_558) + t_560 = torch.add(t_559, t_554) + t_561 = F.relu(t_560) + t_562 = self.n_Conv_88(t_561) + t_563 = F.relu(t_562) + t_563_padded = F.pad(t_563, [1, 1, 1, 1], value=0) + t_564 = self.n_Conv_89(t_563_padded) + t_565 = F.relu(t_564) + t_566 = self.n_Conv_90(t_565) + t_567 = torch.add(t_566, t_561) + t_568 = F.relu(t_567) + t_569 = self.n_Conv_91(t_568) + t_570 = F.relu(t_569) + t_570_padded = F.pad(t_570, [1, 1, 1, 1], value=0) + t_571 = self.n_Conv_92(t_570_padded) + t_572 = F.relu(t_571) + t_573 = self.n_Conv_93(t_572) + t_574 = torch.add(t_573, t_568) + t_575 = F.relu(t_574) + t_576 = self.n_Conv_94(t_575) + t_577 = F.relu(t_576) + t_577_padded = F.pad(t_577, [1, 1, 1, 1], value=0) + t_578 = self.n_Conv_95(t_577_padded) + t_579 = F.relu(t_578) + t_580 = self.n_Conv_96(t_579) + t_581 = torch.add(t_580, t_575) + t_582 = F.relu(t_581) + t_583 = self.n_Conv_97(t_582) + t_584 = F.relu(t_583) + t_584_padded = F.pad(t_584, [0, 1, 0, 1], value=0) + t_585 = self.n_Conv_98(t_584_padded) + t_586 = F.relu(t_585) + t_587 = self.n_Conv_99(t_586) + t_588 = self.n_Conv_100(t_582) + t_589 = torch.add(t_587, t_588) + t_590 = F.relu(t_589) + t_591 = self.n_Conv_101(t_590) + t_592 = F.relu(t_591) + t_592_padded = F.pad(t_592, [1, 1, 1, 1], value=0) + t_593 = self.n_Conv_102(t_592_padded) + t_594 = F.relu(t_593) + t_595 = self.n_Conv_103(t_594) + t_596 = torch.add(t_595, t_590) + t_597 = F.relu(t_596) + t_598 = self.n_Conv_104(t_597) + t_599 = F.relu(t_598) + t_599_padded = F.pad(t_599, [1, 1, 1, 1], value=0) + t_600 = self.n_Conv_105(t_599_padded) + t_601 = F.relu(t_600) + t_602 = self.n_Conv_106(t_601) + t_603 = torch.add(t_602, t_597) + t_604 = F.relu(t_603) + t_605 = self.n_Conv_107(t_604) + t_606 = F.relu(t_605) + t_606_padded = F.pad(t_606, [1, 1, 1, 1], value=0) + t_607 = self.n_Conv_108(t_606_padded) + t_608 = F.relu(t_607) + t_609 = self.n_Conv_109(t_608) + t_610 = torch.add(t_609, t_604) + t_611 = F.relu(t_610) + t_612 = self.n_Conv_110(t_611) + t_613 = F.relu(t_612) + t_613_padded = F.pad(t_613, [1, 1, 1, 1], value=0) + t_614 = self.n_Conv_111(t_613_padded) + t_615 = F.relu(t_614) + t_616 = self.n_Conv_112(t_615) + t_617 = torch.add(t_616, t_611) + t_618 = F.relu(t_617) + t_619 = self.n_Conv_113(t_618) + t_620 = F.relu(t_619) + t_620_padded = F.pad(t_620, [1, 1, 1, 1], value=0) + t_621 = self.n_Conv_114(t_620_padded) + t_622 = F.relu(t_621) + t_623 = self.n_Conv_115(t_622) + t_624 = torch.add(t_623, t_618) + t_625 = F.relu(t_624) + t_626 = self.n_Conv_116(t_625) + t_627 = F.relu(t_626) + t_627_padded = F.pad(t_627, [1, 1, 1, 1], value=0) + t_628 = self.n_Conv_117(t_627_padded) + t_629 = F.relu(t_628) + t_630 = self.n_Conv_118(t_629) + t_631 = torch.add(t_630, t_625) + t_632 = F.relu(t_631) + t_633 = self.n_Conv_119(t_632) + t_634 = F.relu(t_633) + t_634_padded = F.pad(t_634, [1, 1, 1, 1], value=0) + t_635 = self.n_Conv_120(t_634_padded) + t_636 = F.relu(t_635) + t_637 = self.n_Conv_121(t_636) + t_638 = torch.add(t_637, t_632) + t_639 = F.relu(t_638) + t_640 = self.n_Conv_122(t_639) + t_641 = F.relu(t_640) + t_641_padded = F.pad(t_641, [1, 1, 1, 1], value=0) + t_642 = self.n_Conv_123(t_641_padded) + t_643 = F.relu(t_642) + t_644 = self.n_Conv_124(t_643) + t_645 = torch.add(t_644, t_639) + t_646 = F.relu(t_645) + t_647 = self.n_Conv_125(t_646) + t_648 = F.relu(t_647) + t_648_padded = F.pad(t_648, [1, 1, 1, 1], value=0) + t_649 = self.n_Conv_126(t_648_padded) + t_650 = F.relu(t_649) + t_651 = self.n_Conv_127(t_650) + t_652 = torch.add(t_651, t_646) + t_653 = F.relu(t_652) + t_654 = self.n_Conv_128(t_653) + t_655 = F.relu(t_654) + t_655_padded = F.pad(t_655, [1, 1, 1, 1], value=0) + t_656 = self.n_Conv_129(t_655_padded) + t_657 = F.relu(t_656) + t_658 = self.n_Conv_130(t_657) + t_659 = torch.add(t_658, t_653) + t_660 = F.relu(t_659) + t_661 = self.n_Conv_131(t_660) + t_662 = F.relu(t_661) + t_662_padded = F.pad(t_662, [1, 1, 1, 1], value=0) + t_663 = self.n_Conv_132(t_662_padded) + t_664 = F.relu(t_663) + t_665 = self.n_Conv_133(t_664) + t_666 = torch.add(t_665, t_660) + t_667 = F.relu(t_666) + t_668 = self.n_Conv_134(t_667) + t_669 = F.relu(t_668) + t_669_padded = F.pad(t_669, [1, 1, 1, 1], value=0) + t_670 = self.n_Conv_135(t_669_padded) + t_671 = F.relu(t_670) + t_672 = self.n_Conv_136(t_671) + t_673 = torch.add(t_672, t_667) + t_674 = F.relu(t_673) + t_675 = self.n_Conv_137(t_674) + t_676 = F.relu(t_675) + t_676_padded = F.pad(t_676, [1, 1, 1, 1], value=0) + t_677 = self.n_Conv_138(t_676_padded) + t_678 = F.relu(t_677) + t_679 = self.n_Conv_139(t_678) + t_680 = torch.add(t_679, t_674) + t_681 = F.relu(t_680) + t_682 = self.n_Conv_140(t_681) + t_683 = F.relu(t_682) + t_683_padded = F.pad(t_683, [1, 1, 1, 1], value=0) + t_684 = self.n_Conv_141(t_683_padded) + t_685 = F.relu(t_684) + t_686 = self.n_Conv_142(t_685) + t_687 = torch.add(t_686, t_681) + t_688 = F.relu(t_687) + t_689 = self.n_Conv_143(t_688) + t_690 = F.relu(t_689) + t_690_padded = F.pad(t_690, [1, 1, 1, 1], value=0) + t_691 = self.n_Conv_144(t_690_padded) + t_692 = F.relu(t_691) + t_693 = self.n_Conv_145(t_692) + t_694 = torch.add(t_693, t_688) + t_695 = F.relu(t_694) + t_696 = self.n_Conv_146(t_695) + t_697 = F.relu(t_696) + t_697_padded = F.pad(t_697, [1, 1, 1, 1], value=0) + t_698 = self.n_Conv_147(t_697_padded) + t_699 = F.relu(t_698) + t_700 = self.n_Conv_148(t_699) + t_701 = torch.add(t_700, t_695) + t_702 = F.relu(t_701) + t_703 = self.n_Conv_149(t_702) + t_704 = F.relu(t_703) + t_704_padded = F.pad(t_704, [1, 1, 1, 1], value=0) + t_705 = self.n_Conv_150(t_704_padded) + t_706 = F.relu(t_705) + t_707 = self.n_Conv_151(t_706) + t_708 = torch.add(t_707, t_702) + t_709 = F.relu(t_708) + t_710 = self.n_Conv_152(t_709) + t_711 = F.relu(t_710) + t_711_padded = F.pad(t_711, [1, 1, 1, 1], value=0) + t_712 = self.n_Conv_153(t_711_padded) + t_713 = F.relu(t_712) + t_714 = self.n_Conv_154(t_713) + t_715 = torch.add(t_714, t_709) + t_716 = F.relu(t_715) + t_717 = self.n_Conv_155(t_716) + t_718 = F.relu(t_717) + t_718_padded = F.pad(t_718, [1, 1, 1, 1], value=0) + t_719 = self.n_Conv_156(t_718_padded) + t_720 = F.relu(t_719) + t_721 = self.n_Conv_157(t_720) + t_722 = torch.add(t_721, t_716) + t_723 = F.relu(t_722) + t_724 = self.n_Conv_158(t_723) + t_725 = self.n_Conv_159(t_723) + t_726 = F.relu(t_725) + t_726_padded = F.pad(t_726, [0, 1, 0, 1], value=0) + t_727 = self.n_Conv_160(t_726_padded) + t_728 = F.relu(t_727) + t_729 = self.n_Conv_161(t_728) + t_730 = torch.add(t_729, t_724) + t_731 = F.relu(t_730) + t_732 = self.n_Conv_162(t_731) + t_733 = F.relu(t_732) + t_733_padded = F.pad(t_733, [1, 1, 1, 1], value=0) + t_734 = self.n_Conv_163(t_733_padded) + t_735 = F.relu(t_734) + t_736 = self.n_Conv_164(t_735) + t_737 = torch.add(t_736, t_731) + t_738 = F.relu(t_737) + t_739 = self.n_Conv_165(t_738) + t_740 = F.relu(t_739) + t_740_padded = F.pad(t_740, [1, 1, 1, 1], value=0) + t_741 = self.n_Conv_166(t_740_padded) + t_742 = F.relu(t_741) + t_743 = self.n_Conv_167(t_742) + t_744 = torch.add(t_743, t_738) + t_745 = F.relu(t_744) + t_746 = self.n_Conv_168(t_745) + t_747 = self.n_Conv_169(t_745) + t_748 = F.relu(t_747) + t_748_padded = F.pad(t_748, [0, 1, 0, 1], value=0) + t_749 = self.n_Conv_170(t_748_padded) + t_750 = F.relu(t_749) + t_751 = self.n_Conv_171(t_750) + t_752 = torch.add(t_751, t_746) + t_753 = F.relu(t_752) + t_754 = self.n_Conv_172(t_753) + t_755 = F.relu(t_754) + t_755_padded = F.pad(t_755, [1, 1, 1, 1], value=0) + t_756 = self.n_Conv_173(t_755_padded) + t_757 = F.relu(t_756) + t_758 = self.n_Conv_174(t_757) + t_759 = torch.add(t_758, t_753) + t_760 = F.relu(t_759) + t_761 = self.n_Conv_175(t_760) + t_762 = F.relu(t_761) + t_762_padded = F.pad(t_762, [1, 1, 1, 1], value=0) + t_763 = self.n_Conv_176(t_762_padded) + t_764 = F.relu(t_763) + t_765 = self.n_Conv_177(t_764) + t_766 = torch.add(t_765, t_760) + t_767 = F.relu(t_766) + t_768 = self.n_Conv_178(t_767) + t_769 = F.avg_pool2d(t_768, kernel_size=t_768.shape[-2:]) + t_770 = torch.squeeze(t_769, 3) + t_770 = torch.squeeze(t_770, 2) + t_771 = torch.sigmoid(t_770) + return t_771 + + def load_state_dict(self, state_dict, **kwargs): + self.tags = state_dict.get('tags', []) + + super(DeepDanbooruModel, self).load_state_dict({k: v for k, v in state_dict.items() if k != 'tags'}) + diff --git a/comfyui-art-venture/modules/interrogate/models/med.py b/comfyui-art-venture/modules/interrogate/models/med.py new file mode 100644 index 0000000000000000000000000000000000000000..58f95f16d53c8f86c5b28e3a06278bb09fe10412 --- /dev/null +++ b/comfyui-art-venture/modules/interrogate/models/med.py @@ -0,0 +1,1067 @@ +""" + * Copyright (c) 2022, salesforce.com, inc. + * All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause + * By Junnan Li + * Based on huggingface code base + * https://github.com/huggingface/transformers/blob/v4.15.0/src/transformers/models/bert +""" + +import math +from typing import Tuple + +import torch +from torch import Tensor, device, nn +import torch.utils.checkpoint +from torch import nn +from torch.nn import CrossEntropyLoss + +from transformers.activations import ACT2FN +from transformers.modeling_outputs import ( + BaseModelOutputWithPastAndCrossAttentions, + BaseModelOutputWithPoolingAndCrossAttentions, + CausalLMOutputWithCrossAttentions, +) +from transformers.modeling_utils import ( + PreTrainedModel, + apply_chunking_to_forward, + find_pruneable_heads_and_indices, + prune_linear_layer, +) +from transformers.utils import logging +from transformers.models.bert.configuration_bert import BertConfig + + +logger = logging.get_logger(__name__) + + +class BertEmbeddings(nn.Module): + """Construct the embeddings from word and position embeddings.""" + + def __init__(self, config): + super().__init__() + self.word_embeddings = nn.Embedding( + config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id + ) + self.position_embeddings = nn.Embedding( + config.max_position_embeddings, config.hidden_size + ) + + # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load + # any TensorFlow checkpoint file + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + # position_ids (1, len position emb) is contiguous in memory and exported when serialized + self.register_buffer( + "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)) + ) + self.position_embedding_type = getattr( + config, "position_embedding_type", "absolute" + ) + + self.config = config + + def forward( + self, + input_ids=None, + position_ids=None, + inputs_embeds=None, + past_key_values_length=0, + ): + if input_ids is not None: + input_shape = input_ids.size() + else: + input_shape = inputs_embeds.size()[:-1] + + seq_length = input_shape[1] + + if position_ids is None: + position_ids = self.position_ids[ + :, past_key_values_length : seq_length + past_key_values_length + ] + + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + + embeddings = inputs_embeds + + if self.position_embedding_type == "absolute": + position_embeddings = self.position_embeddings(position_ids) + embeddings += position_embeddings + embeddings = self.LayerNorm(embeddings) + embeddings = self.dropout(embeddings) + return embeddings + + +class BertSelfAttention(nn.Module): + def __init__(self, config, is_cross_attention): + super().__init__() + self.config = config + if config.hidden_size % config.num_attention_heads != 0 and not hasattr( + config, "embedding_size" + ): + raise ValueError( + "The hidden size (%d) is not a multiple of the number of attention " + "heads (%d)" % (config.hidden_size, config.num_attention_heads) + ) + + self.num_attention_heads = config.num_attention_heads + self.attention_head_size = int(config.hidden_size / config.num_attention_heads) + self.all_head_size = self.num_attention_heads * self.attention_head_size + + self.query = nn.Linear(config.hidden_size, self.all_head_size) + if is_cross_attention: + self.key = nn.Linear(config.encoder_width, self.all_head_size) + self.value = nn.Linear(config.encoder_width, self.all_head_size) + else: + self.key = nn.Linear(config.hidden_size, self.all_head_size) + self.value = nn.Linear(config.hidden_size, self.all_head_size) + + self.dropout = nn.Dropout(config.attention_probs_dropout_prob) + self.position_embedding_type = getattr( + config, "position_embedding_type", "absolute" + ) + if ( + self.position_embedding_type == "relative_key" + or self.position_embedding_type == "relative_key_query" + ): + self.max_position_embeddings = config.max_position_embeddings + self.distance_embedding = nn.Embedding( + 2 * config.max_position_embeddings - 1, self.attention_head_size + ) + self.save_attention = False + + def save_attn_gradients(self, attn_gradients): + self.attn_gradients = attn_gradients + + def get_attn_gradients(self): + return self.attn_gradients + + def save_attention_map(self, attention_map): + self.attention_map = attention_map + + def get_attention_map(self): + return self.attention_map + + def transpose_for_scores(self, x): + new_x_shape = x.size()[:-1] + ( + self.num_attention_heads, + self.attention_head_size, + ) + x = x.view(*new_x_shape) + return x.permute(0, 2, 1, 3) + + def forward( + self, + hidden_states, + attention_mask=None, + head_mask=None, + encoder_hidden_states=None, + encoder_attention_mask=None, + past_key_value=None, + output_attentions=False, + ): + mixed_query_layer = self.query(hidden_states) + + # If this is instantiated as a cross-attention module, the keys + # and values come from an encoder; the attention mask needs to be + # such that the encoder's padding tokens are not attended to. + is_cross_attention = encoder_hidden_states is not None + + if is_cross_attention: + key_layer = self.transpose_for_scores(self.key(encoder_hidden_states)) + value_layer = self.transpose_for_scores(self.value(encoder_hidden_states)) + attention_mask = encoder_attention_mask + elif past_key_value is not None: + key_layer = self.transpose_for_scores(self.key(hidden_states)) + value_layer = self.transpose_for_scores(self.value(hidden_states)) + key_layer = torch.cat([past_key_value[0], key_layer], dim=2) + value_layer = torch.cat([past_key_value[1], value_layer], dim=2) + else: + key_layer = self.transpose_for_scores(self.key(hidden_states)) + value_layer = self.transpose_for_scores(self.value(hidden_states)) + + query_layer = self.transpose_for_scores(mixed_query_layer) + + past_key_value = (key_layer, value_layer) + + # Take the dot product between "query" and "key" to get the raw attention scores. + attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) + + if ( + self.position_embedding_type == "relative_key" + or self.position_embedding_type == "relative_key_query" + ): + seq_length = hidden_states.size()[1] + position_ids_l = torch.arange( + seq_length, dtype=torch.long, device=hidden_states.device + ).view(-1, 1) + position_ids_r = torch.arange( + seq_length, dtype=torch.long, device=hidden_states.device + ).view(1, -1) + distance = position_ids_l - position_ids_r + positional_embedding = self.distance_embedding( + distance + self.max_position_embeddings - 1 + ) + positional_embedding = positional_embedding.to( + dtype=query_layer.dtype + ) # fp16 compatibility + + if self.position_embedding_type == "relative_key": + relative_position_scores = torch.einsum( + "bhld,lrd->bhlr", query_layer, positional_embedding + ) + attention_scores = attention_scores + relative_position_scores + elif self.position_embedding_type == "relative_key_query": + relative_position_scores_query = torch.einsum( + "bhld,lrd->bhlr", query_layer, positional_embedding + ) + relative_position_scores_key = torch.einsum( + "bhrd,lrd->bhlr", key_layer, positional_embedding + ) + attention_scores = ( + attention_scores + + relative_position_scores_query + + relative_position_scores_key + ) + + attention_scores = attention_scores / math.sqrt(self.attention_head_size) + if attention_mask is not None: + # Apply the attention mask is (precomputed for all layers in BertModel forward() function) + attention_scores = attention_scores + attention_mask + + # Normalize the attention scores to probabilities. + attention_probs = nn.Softmax(dim=-1)(attention_scores) + + if is_cross_attention and self.save_attention: + self.save_attention_map(attention_probs) + attention_probs.register_hook(self.save_attn_gradients) + + # This is actually dropping out entire tokens to attend to, which might + # seem a bit unusual, but is taken from the original Transformer paper. + attention_probs_dropped = self.dropout(attention_probs) + + # Mask heads if we want to + if head_mask is not None: + attention_probs_dropped = attention_probs_dropped * head_mask + + context_layer = torch.matmul(attention_probs_dropped, value_layer) + + context_layer = context_layer.permute(0, 2, 1, 3).contiguous() + new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) + context_layer = context_layer.view(*new_context_layer_shape) + + outputs = ( + (context_layer, attention_probs) if output_attentions else (context_layer,) + ) + + outputs = outputs + (past_key_value,) + return outputs + + +class BertSelfOutput(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states, input_tensor): + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + hidden_states = self.LayerNorm(hidden_states + input_tensor) + return hidden_states + + +class BertAttention(nn.Module): + def __init__(self, config, is_cross_attention=False): + super().__init__() + self.self = BertSelfAttention(config, is_cross_attention) + self.output = BertSelfOutput(config) + self.pruned_heads = set() + + def prune_heads(self, heads): + if len(heads) == 0: + return + heads, index = find_pruneable_heads_and_indices( + heads, + self.self.num_attention_heads, + self.self.attention_head_size, + self.pruned_heads, + ) + + # Prune linear layers + self.self.query = prune_linear_layer(self.self.query, index) + self.self.key = prune_linear_layer(self.self.key, index) + self.self.value = prune_linear_layer(self.self.value, index) + self.output.dense = prune_linear_layer(self.output.dense, index, dim=1) + + # Update hyper params and store pruned heads + self.self.num_attention_heads = self.self.num_attention_heads - len(heads) + self.self.all_head_size = ( + self.self.attention_head_size * self.self.num_attention_heads + ) + self.pruned_heads = self.pruned_heads.union(heads) + + def forward( + self, + hidden_states, + attention_mask=None, + head_mask=None, + encoder_hidden_states=None, + encoder_attention_mask=None, + past_key_value=None, + output_attentions=False, + ): + self_outputs = self.self( + hidden_states, + attention_mask, + head_mask, + encoder_hidden_states, + encoder_attention_mask, + past_key_value, + output_attentions, + ) + attention_output = self.output(self_outputs[0], hidden_states) + outputs = (attention_output,) + self_outputs[ + 1: + ] # add attentions if we output them + return outputs + + +class BertIntermediate(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.intermediate_size) + if isinstance(config.hidden_act, str): + self.intermediate_act_fn = ACT2FN[config.hidden_act] + else: + self.intermediate_act_fn = config.hidden_act + + def forward(self, hidden_states): + hidden_states = self.dense(hidden_states) + hidden_states = self.intermediate_act_fn(hidden_states) + return hidden_states + + +class BertOutput(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.intermediate_size, config.hidden_size) + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states, input_tensor): + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + hidden_states = self.LayerNorm(hidden_states + input_tensor) + return hidden_states + + +class BertLayer(nn.Module): + def __init__(self, config, layer_num): + super().__init__() + self.config = config + self.chunk_size_feed_forward = config.chunk_size_feed_forward + self.seq_len_dim = 1 + self.attention = BertAttention(config) + self.layer_num = layer_num + if self.config.add_cross_attention: + self.crossattention = BertAttention( + config, is_cross_attention=self.config.add_cross_attention + ) + self.intermediate = BertIntermediate(config) + self.output = BertOutput(config) + + def forward( + self, + hidden_states, + attention_mask=None, + head_mask=None, + encoder_hidden_states=None, + encoder_attention_mask=None, + past_key_value=None, + output_attentions=False, + mode=None, + ): + # decoder uni-directional self-attention cached key/values tuple is at positions 1,2 + self_attn_past_key_value = ( + past_key_value[:2] if past_key_value is not None else None + ) + self_attention_outputs = self.attention( + hidden_states, + attention_mask, + head_mask, + output_attentions=output_attentions, + past_key_value=self_attn_past_key_value, + ) + attention_output = self_attention_outputs[0] + + outputs = self_attention_outputs[1:-1] + present_key_value = self_attention_outputs[-1] + + if mode == "multimodal": + assert ( + encoder_hidden_states is not None + ), "encoder_hidden_states must be given for cross-attention layers" + + cross_attention_outputs = self.crossattention( + attention_output, + attention_mask, + head_mask, + encoder_hidden_states, + encoder_attention_mask, + output_attentions=output_attentions, + ) + attention_output = cross_attention_outputs[0] + outputs = ( + outputs + cross_attention_outputs[1:-1] + ) # add cross attentions if we output attention weights + layer_output = apply_chunking_to_forward( + self.feed_forward_chunk, + self.chunk_size_feed_forward, + self.seq_len_dim, + attention_output, + ) + outputs = (layer_output,) + outputs + + outputs = outputs + (present_key_value,) + + return outputs + + def feed_forward_chunk(self, attention_output): + intermediate_output = self.intermediate(attention_output) + layer_output = self.output(intermediate_output, attention_output) + return layer_output + + +class BertEncoder(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.layer = nn.ModuleList( + [BertLayer(config, i) for i in range(config.num_hidden_layers)] + ) + self.gradient_checkpointing = False + + def forward( + self, + hidden_states, + attention_mask=None, + head_mask=None, + encoder_hidden_states=None, + encoder_attention_mask=None, + past_key_values=None, + use_cache=None, + output_attentions=False, + output_hidden_states=False, + return_dict=True, + mode="multimodal", + ): + all_hidden_states = () if output_hidden_states else None + all_self_attentions = () if output_attentions else None + all_cross_attentions = ( + () if output_attentions and self.config.add_cross_attention else None + ) + + next_decoder_cache = () if use_cache else None + + for i in range(self.config.num_hidden_layers): + layer_module = self.layer[i] + if output_hidden_states: + all_hidden_states = all_hidden_states + (hidden_states,) + + layer_head_mask = head_mask[i] if head_mask is not None else None + past_key_value = past_key_values[i] if past_key_values is not None else None + + if self.gradient_checkpointing and self.training: + if use_cache: + logger.warn( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs, past_key_value, output_attentions) + + return custom_forward + + layer_outputs = torch.utils.checkpoint.checkpoint( + create_custom_forward(layer_module), + hidden_states, + attention_mask, + layer_head_mask, + encoder_hidden_states, + encoder_attention_mask, + mode=mode, + ) + else: + layer_outputs = layer_module( + hidden_states, + attention_mask, + layer_head_mask, + encoder_hidden_states, + encoder_attention_mask, + past_key_value, + output_attentions, + mode=mode, + ) + + hidden_states = layer_outputs[0] + if use_cache: + next_decoder_cache += (layer_outputs[-1],) + if output_attentions: + all_self_attentions = all_self_attentions + (layer_outputs[1],) + + if output_hidden_states: + all_hidden_states = all_hidden_states + (hidden_states,) + + if not return_dict: + return tuple( + v + for v in [ + hidden_states, + next_decoder_cache, + all_hidden_states, + all_self_attentions, + all_cross_attentions, + ] + if v is not None + ) + return BaseModelOutputWithPastAndCrossAttentions( + last_hidden_state=hidden_states, + past_key_values=next_decoder_cache, + hidden_states=all_hidden_states, + attentions=all_self_attentions, + cross_attentions=all_cross_attentions, + ) + + +class BertPooler(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + self.activation = nn.Tanh() + + def forward(self, hidden_states): + # We "pool" the model by simply taking the hidden state corresponding + # to the first token. + first_token_tensor = hidden_states[:, 0] + pooled_output = self.dense(first_token_tensor) + pooled_output = self.activation(pooled_output) + return pooled_output + + +class BertPredictionHeadTransform(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + if isinstance(config.hidden_act, str): + self.transform_act_fn = ACT2FN[config.hidden_act] + else: + self.transform_act_fn = config.hidden_act + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + + def forward(self, hidden_states): + hidden_states = self.dense(hidden_states) + hidden_states = self.transform_act_fn(hidden_states) + hidden_states = self.LayerNorm(hidden_states) + return hidden_states + + +class BertLMPredictionHead(nn.Module): + def __init__(self, config): + super().__init__() + self.transform = BertPredictionHeadTransform(config) + + # The output weights are the same as the input embeddings, but there is + # an output-only bias for each token. + self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + + self.bias = nn.Parameter(torch.zeros(config.vocab_size)) + + # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` + self.decoder.bias = self.bias + + def forward(self, hidden_states): + hidden_states = self.transform(hidden_states) + hidden_states = self.decoder(hidden_states) + return hidden_states + + +class BertOnlyMLMHead(nn.Module): + def __init__(self, config): + super().__init__() + self.predictions = BertLMPredictionHead(config) + + def forward(self, sequence_output): + prediction_scores = self.predictions(sequence_output) + return prediction_scores + + +class BertPreTrainedModel(PreTrainedModel): + """ + An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained + models. + """ + + config_class = BertConfig + base_model_prefix = "bert" + _keys_to_ignore_on_load_missing = [r"position_ids"] + + def _init_weights(self, module): + """Initialize the weights""" + if isinstance(module, (nn.Linear, nn.Embedding)): + # Slightly different from the TF version which uses truncated_normal for initialization + # cf https://github.com/pytorch/pytorch/pull/5617 + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + elif isinstance(module, nn.LayerNorm): + module.bias.data.zero_() + module.weight.data.fill_(1.0) + if isinstance(module, nn.Linear) and module.bias is not None: + module.bias.data.zero_() + + +class BertModel(BertPreTrainedModel): + """ + The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of + cross-attention is added between the self-attention layers, following the architecture described in `Attention is + all you need `__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, + Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. + argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an + input to the forward pass. + """ + + def __init__(self, config, add_pooling_layer=True): + super().__init__(config) + self.config = config + + self.embeddings = BertEmbeddings(config) + + self.encoder = BertEncoder(config) + + self.pooler = BertPooler(config) if add_pooling_layer else None + + self.init_weights() + + def get_input_embeddings(self): + return self.embeddings.word_embeddings + + def set_input_embeddings(self, value): + self.embeddings.word_embeddings = value + + def _prune_heads(self, heads_to_prune): + """ + Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base + class PreTrainedModel + """ + for layer, heads in heads_to_prune.items(): + self.encoder.layer[layer].attention.prune_heads(heads) + + def get_extended_attention_mask( + self, + attention_mask: Tensor, + input_shape: Tuple[int], + device: device, + is_decoder: bool, + ) -> Tensor: + """ + Makes broadcastable attention and causal masks so that future and masked tokens are ignored. + + Arguments: + attention_mask (:obj:`torch.Tensor`): + Mask with ones indicating tokens to attend to, zeros for tokens to ignore. + input_shape (:obj:`Tuple[int]`): + The shape of the input to the model. + device: (:obj:`torch.device`): + The device of the input to the model. + + Returns: + :obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`. + """ + # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] + # ourselves in which case we just need to make it broadcastable to all heads. + if attention_mask.dim() == 3: + extended_attention_mask = attention_mask[:, None, :, :] + elif attention_mask.dim() == 2: + # Provided a padding mask of dimensions [batch_size, seq_length] + # - if the model is a decoder, apply a causal mask in addition to the padding mask + # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length] + if is_decoder: + batch_size, seq_length = input_shape + + seq_ids = torch.arange(seq_length, device=device) + causal_mask = ( + seq_ids[None, None, :].repeat(batch_size, seq_length, 1) + <= seq_ids[None, :, None] + ) + # in case past_key_values are used we need to add a prefix ones mask to the causal mask + # causal and attention masks must have same type with pytorch version < 1.3 + causal_mask = causal_mask.to(attention_mask.dtype) + + if causal_mask.shape[1] < attention_mask.shape[1]: + prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1] + causal_mask = torch.cat( + [ + torch.ones( + (batch_size, seq_length, prefix_seq_len), + device=device, + dtype=causal_mask.dtype, + ), + causal_mask, + ], + axis=-1, + ) + + extended_attention_mask = ( + causal_mask[:, None, :, :] * attention_mask[:, None, None, :] + ) + else: + extended_attention_mask = attention_mask[:, None, None, :] + else: + raise ValueError( + "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format( + input_shape, attention_mask.shape + ) + ) + + # Since attention_mask is 1.0 for positions we want to attend and 0.0 for + # masked positions, this operation will create a tensor which is 0.0 for + # positions we want to attend and -10000.0 for masked positions. + # Since we are adding it to the raw scores before the softmax, this is + # effectively the same as removing these entirely. + extended_attention_mask = extended_attention_mask.to( + dtype=self.dtype + ) # fp16 compatibility + extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0 + return extended_attention_mask + + def forward( + self, + input_ids=None, + attention_mask=None, + position_ids=None, + head_mask=None, + inputs_embeds=None, + encoder_embeds=None, + encoder_hidden_states=None, + encoder_attention_mask=None, + past_key_values=None, + use_cache=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + is_decoder=False, + mode="multimodal", + ): + r""" + encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): + Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if + the model is configured as a decoder. + encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): + Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in + the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``: + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): + Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. + If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` + (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` + instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`. + use_cache (:obj:`bool`, `optional`): + If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up + decoding (see :obj:`past_key_values`). + """ + output_attentions = ( + output_attentions + if output_attentions is not None + else self.config.output_attentions + ) + output_hidden_states = ( + output_hidden_states + if output_hidden_states is not None + else self.config.output_hidden_states + ) + return_dict = ( + return_dict if return_dict is not None else self.config.use_return_dict + ) + + if is_decoder: + use_cache = use_cache if use_cache is not None else self.config.use_cache + else: + use_cache = False + + if input_ids is not None and inputs_embeds is not None: + raise ValueError( + "You cannot specify both input_ids and inputs_embeds at the same time" + ) + elif input_ids is not None: + input_shape = input_ids.size() + batch_size, seq_length = input_shape + device = input_ids.device + elif inputs_embeds is not None: + input_shape = inputs_embeds.size()[:-1] + batch_size, seq_length = input_shape + device = inputs_embeds.device + elif encoder_embeds is not None: + input_shape = encoder_embeds.size()[:-1] + batch_size, seq_length = input_shape + device = encoder_embeds.device + else: + raise ValueError( + "You have to specify either input_ids or inputs_embeds or encoder_embeds" + ) + + # past_key_values_length + past_key_values_length = ( + past_key_values[0][0].shape[2] if past_key_values is not None else 0 + ) + + if attention_mask is None: + attention_mask = torch.ones( + ((batch_size, seq_length + past_key_values_length)), device=device + ) + + # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] + # ourselves in which case we just need to make it broadcastable to all heads. + extended_attention_mask: torch.Tensor = self.get_extended_attention_mask( + attention_mask, input_shape, device, is_decoder + ) + + # If a 2D or 3D attention mask is provided for the cross-attention + # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] + if encoder_hidden_states is not None: + if type(encoder_hidden_states) == list: + encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[ + 0 + ].size() + else: + ( + encoder_batch_size, + encoder_sequence_length, + _, + ) = encoder_hidden_states.size() + encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) + + if type(encoder_attention_mask) == list: + encoder_extended_attention_mask = [ + self.invert_attention_mask(mask) for mask in encoder_attention_mask + ] + elif encoder_attention_mask is None: + encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) + encoder_extended_attention_mask = self.invert_attention_mask( + encoder_attention_mask + ) + else: + encoder_extended_attention_mask = self.invert_attention_mask( + encoder_attention_mask + ) + else: + encoder_extended_attention_mask = None + + # Prepare head mask if needed + # 1.0 in head_mask indicate we keep the head + # attention_probs has shape bsz x n_heads x N x N + # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] + # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] + head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) + + if encoder_embeds is None: + embedding_output = self.embeddings( + input_ids=input_ids, + position_ids=position_ids, + inputs_embeds=inputs_embeds, + past_key_values_length=past_key_values_length, + ) + else: + embedding_output = encoder_embeds + + encoder_outputs = self.encoder( + embedding_output, + attention_mask=extended_attention_mask, + head_mask=head_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_extended_attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + mode=mode, + ) + sequence_output = encoder_outputs[0] + pooled_output = ( + self.pooler(sequence_output) if self.pooler is not None else None + ) + + if not return_dict: + return (sequence_output, pooled_output) + encoder_outputs[1:] + + return BaseModelOutputWithPoolingAndCrossAttentions( + last_hidden_state=sequence_output, + pooler_output=pooled_output, + past_key_values=encoder_outputs.past_key_values, + hidden_states=encoder_outputs.hidden_states, + attentions=encoder_outputs.attentions, + cross_attentions=encoder_outputs.cross_attentions, + ) + + +class BertLMHeadModel(BertPreTrainedModel): + _keys_to_ignore_on_load_unexpected = [r"pooler"] + _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"] + + def __init__(self, config): + super().__init__(config) + + self.bert = BertModel(config, add_pooling_layer=False) + self.cls = BertOnlyMLMHead(config) + + self.init_weights() + + def get_output_embeddings(self): + return self.cls.predictions.decoder + + def set_output_embeddings(self, new_embeddings): + self.cls.predictions.decoder = new_embeddings + + def forward( + self, + input_ids=None, + attention_mask=None, + position_ids=None, + head_mask=None, + inputs_embeds=None, + encoder_hidden_states=None, + encoder_attention_mask=None, + labels=None, + past_key_values=None, + use_cache=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + return_logits=False, + is_decoder=True, + reduction="mean", + mode="multimodal", + ): + r""" + encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): + Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if + the model is configured as a decoder. + encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): + Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in + the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``: + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): + Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in + ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are + ignored (masked), the loss is only computed for the tokens with labels n ``[0, ..., config.vocab_size]`` + past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): + Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. + If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` + (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` + instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`. + use_cache (:obj:`bool`, `optional`): + If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up + decoding (see :obj:`past_key_values`). + Returns: + Example:: + >>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig + >>> import torch + >>> tokenizer = BertTokenizer.from_pretrained('bert-base-cased') + >>> config = BertConfig.from_pretrained("bert-base-cased") + >>> model = BertLMHeadModel.from_pretrained('bert-base-cased', config=config) + >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") + >>> outputs = model(**inputs) + >>> prediction_logits = outputs.logits + """ + return_dict = ( + return_dict if return_dict is not None else self.config.use_return_dict + ) + if labels is not None: + use_cache = False + + outputs = self.bert( + input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + is_decoder=is_decoder, + mode=mode, + ) + + sequence_output = outputs[0] + prediction_scores = self.cls(sequence_output) + + if return_logits: + return prediction_scores[:, :-1, :].contiguous() + + lm_loss = None + if labels is not None: + # we are doing next-token prediction; shift prediction scores and input ids by one + shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous() + labels = labels[:, 1:].contiguous() + loss_fct = CrossEntropyLoss(reduction=reduction, label_smoothing=0.1) + lm_loss = loss_fct( + shifted_prediction_scores.view(-1, self.config.vocab_size), + labels.view(-1), + ) + if reduction == "none": + lm_loss = lm_loss.view(prediction_scores.size(0), -1).sum(1) + + if not return_dict: + output = (prediction_scores,) + outputs[2:] + return ((lm_loss,) + output) if lm_loss is not None else output + + return CausalLMOutputWithCrossAttentions( + loss=lm_loss, + logits=prediction_scores, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + cross_attentions=outputs.cross_attentions, + ) + + def prepare_inputs_for_generation( + self, input_ids, past=None, attention_mask=None, **model_kwargs + ): + input_shape = input_ids.shape + # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly + if attention_mask is None: + attention_mask = input_ids.new_ones(input_shape) + + # cut decoder_input_ids if past is used + if past is not None: + input_ids = input_ids[:, -1:] + + return { + "input_ids": input_ids, + "attention_mask": attention_mask, + "past_key_values": past, + "encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None), + "encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None), + "is_decoder": True, + } + + def _reorder_cache(self, past, beam_idx): + reordered_past = () + for layer_past in past: + reordered_past += ( + tuple( + past_state.index_select(0, beam_idx) for past_state in layer_past + ), + ) + return reordered_past diff --git a/comfyui-art-venture/modules/interrogate/models/nlvr_encoder.py b/comfyui-art-venture/modules/interrogate/models/nlvr_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..611eb69921aea2f137fa01ed22a968974281def4 --- /dev/null +++ b/comfyui-art-venture/modules/interrogate/models/nlvr_encoder.py @@ -0,0 +1,955 @@ +import math +from typing import Tuple + +import torch +from torch import Tensor, device, nn +import torch.utils.checkpoint +from torch import nn + +from transformers.activations import ACT2FN +from transformers.modeling_outputs import ( + BaseModelOutputWithPastAndCrossAttentions, + BaseModelOutputWithPoolingAndCrossAttentions, +) +from transformers.modeling_utils import ( + PreTrainedModel, + apply_chunking_to_forward, + find_pruneable_heads_and_indices, + prune_linear_layer, +) +from transformers.utils import logging +from transformers.models.bert.configuration_bert import BertConfig + + +logger = logging.get_logger(__name__) + + +class BertEmbeddings(nn.Module): + """Construct the embeddings from word and position embeddings.""" + + def __init__(self, config): + super().__init__() + self.word_embeddings = nn.Embedding( + config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id + ) + self.position_embeddings = nn.Embedding( + config.max_position_embeddings, config.hidden_size + ) + + # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load + # any TensorFlow checkpoint file + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + # position_ids (1, len position emb) is contiguous in memory and exported when serialized + self.register_buffer( + "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)) + ) + self.position_embedding_type = getattr( + config, "position_embedding_type", "absolute" + ) + + self.config = config + + def forward( + self, + input_ids=None, + position_ids=None, + inputs_embeds=None, + past_key_values_length=0, + ): + if input_ids is not None: + input_shape = input_ids.size() + else: + input_shape = inputs_embeds.size()[:-1] + + seq_length = input_shape[1] + + if position_ids is None: + position_ids = self.position_ids[ + :, past_key_values_length : seq_length + past_key_values_length + ] + + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + + embeddings = inputs_embeds + + if self.position_embedding_type == "absolute": + position_embeddings = self.position_embeddings(position_ids) + embeddings += position_embeddings + embeddings = self.LayerNorm(embeddings) + embeddings = self.dropout(embeddings) + return embeddings + + +class BertSelfAttention(nn.Module): + def __init__(self, config, is_cross_attention): + super().__init__() + self.config = config + if config.hidden_size % config.num_attention_heads != 0 and not hasattr( + config, "embedding_size" + ): + raise ValueError( + "The hidden size (%d) is not a multiple of the number of attention " + "heads (%d)" % (config.hidden_size, config.num_attention_heads) + ) + + self.num_attention_heads = config.num_attention_heads + self.attention_head_size = int(config.hidden_size / config.num_attention_heads) + self.all_head_size = self.num_attention_heads * self.attention_head_size + + self.query = nn.Linear(config.hidden_size, self.all_head_size) + if is_cross_attention: + self.key = nn.Linear(config.encoder_width, self.all_head_size) + self.value = nn.Linear(config.encoder_width, self.all_head_size) + else: + self.key = nn.Linear(config.hidden_size, self.all_head_size) + self.value = nn.Linear(config.hidden_size, self.all_head_size) + + self.dropout = nn.Dropout(config.attention_probs_dropout_prob) + self.position_embedding_type = getattr( + config, "position_embedding_type", "absolute" + ) + if ( + self.position_embedding_type == "relative_key" + or self.position_embedding_type == "relative_key_query" + ): + self.max_position_embeddings = config.max_position_embeddings + self.distance_embedding = nn.Embedding( + 2 * config.max_position_embeddings - 1, self.attention_head_size + ) + self.save_attention = False + + def save_attn_gradients(self, attn_gradients): + self.attn_gradients = attn_gradients + + def get_attn_gradients(self): + return self.attn_gradients + + def save_attention_map(self, attention_map): + self.attention_map = attention_map + + def get_attention_map(self): + return self.attention_map + + def transpose_for_scores(self, x): + new_x_shape = x.size()[:-1] + ( + self.num_attention_heads, + self.attention_head_size, + ) + x = x.view(*new_x_shape) + return x.permute(0, 2, 1, 3) + + def forward( + self, + hidden_states, + attention_mask=None, + head_mask=None, + encoder_hidden_states=None, + encoder_attention_mask=None, + past_key_value=None, + output_attentions=False, + ): + mixed_query_layer = self.query(hidden_states) + + # If this is instantiated as a cross-attention module, the keys + # and values come from an encoder; the attention mask needs to be + # such that the encoder's padding tokens are not attended to. + is_cross_attention = encoder_hidden_states is not None + + if is_cross_attention: + key_layer = self.transpose_for_scores(self.key(encoder_hidden_states)) + value_layer = self.transpose_for_scores(self.value(encoder_hidden_states)) + attention_mask = encoder_attention_mask + elif past_key_value is not None: + key_layer = self.transpose_for_scores(self.key(hidden_states)) + value_layer = self.transpose_for_scores(self.value(hidden_states)) + key_layer = torch.cat([past_key_value[0], key_layer], dim=2) + value_layer = torch.cat([past_key_value[1], value_layer], dim=2) + else: + key_layer = self.transpose_for_scores(self.key(hidden_states)) + value_layer = self.transpose_for_scores(self.value(hidden_states)) + + query_layer = self.transpose_for_scores(mixed_query_layer) + + past_key_value = (key_layer, value_layer) + + # Take the dot product between "query" and "key" to get the raw attention scores. + attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) + + if ( + self.position_embedding_type == "relative_key" + or self.position_embedding_type == "relative_key_query" + ): + seq_length = hidden_states.size()[1] + position_ids_l = torch.arange( + seq_length, dtype=torch.long, device=hidden_states.device + ).view(-1, 1) + position_ids_r = torch.arange( + seq_length, dtype=torch.long, device=hidden_states.device + ).view(1, -1) + distance = position_ids_l - position_ids_r + positional_embedding = self.distance_embedding( + distance + self.max_position_embeddings - 1 + ) + positional_embedding = positional_embedding.to( + dtype=query_layer.dtype + ) # fp16 compatibility + + if self.position_embedding_type == "relative_key": + relative_position_scores = torch.einsum( + "bhld,lrd->bhlr", query_layer, positional_embedding + ) + attention_scores = attention_scores + relative_position_scores + elif self.position_embedding_type == "relative_key_query": + relative_position_scores_query = torch.einsum( + "bhld,lrd->bhlr", query_layer, positional_embedding + ) + relative_position_scores_key = torch.einsum( + "bhrd,lrd->bhlr", key_layer, positional_embedding + ) + attention_scores = ( + attention_scores + + relative_position_scores_query + + relative_position_scores_key + ) + + attention_scores = attention_scores / math.sqrt(self.attention_head_size) + if attention_mask is not None: + # Apply the attention mask is (precomputed for all layers in BertModel forward() function) + attention_scores = attention_scores + attention_mask + + # Normalize the attention scores to probabilities. + attention_probs = nn.Softmax(dim=-1)(attention_scores) + + if is_cross_attention and self.save_attention: + self.save_attention_map(attention_probs) + attention_probs.register_hook(self.save_attn_gradients) + + # This is actually dropping out entire tokens to attend to, which might + # seem a bit unusual, but is taken from the original Transformer paper. + attention_probs_dropped = self.dropout(attention_probs) + + # Mask heads if we want to + if head_mask is not None: + attention_probs_dropped = attention_probs_dropped * head_mask + + context_layer = torch.matmul(attention_probs_dropped, value_layer) + + context_layer = context_layer.permute(0, 2, 1, 3).contiguous() + new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) + context_layer = context_layer.view(*new_context_layer_shape) + + outputs = ( + (context_layer, attention_probs) if output_attentions else (context_layer,) + ) + + outputs = outputs + (past_key_value,) + return outputs + + +class BertSelfOutput(nn.Module): + def __init__(self, config, twin=False, merge=False): + super().__init__() + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + if twin: + self.dense0 = nn.Linear(config.hidden_size, config.hidden_size) + self.dense1 = nn.Linear(config.hidden_size, config.hidden_size) + else: + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + if merge: + self.act = ACT2FN[config.hidden_act] + self.merge_layer = nn.Linear(config.hidden_size * 2, config.hidden_size) + self.merge = True + else: + self.merge = False + + def forward(self, hidden_states, input_tensor): + if type(hidden_states) == list: + hidden_states0 = self.dense0(hidden_states[0]) + hidden_states1 = self.dense1(hidden_states[1]) + if self.merge: + # hidden_states = self.merge_layer(self.act(torch.cat([hidden_states0,hidden_states1],dim=-1))) + hidden_states = self.merge_layer( + torch.cat([hidden_states0, hidden_states1], dim=-1) + ) + else: + hidden_states = (hidden_states0 + hidden_states1) / 2 + else: + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + hidden_states = self.LayerNorm(hidden_states + input_tensor) + return hidden_states + + +class BertAttention(nn.Module): + def __init__(self, config, is_cross_attention=False, layer_num=-1): + super().__init__() + if is_cross_attention: + self.self0 = BertSelfAttention(config, is_cross_attention) + self.self1 = BertSelfAttention(config, is_cross_attention) + else: + self.self = BertSelfAttention(config, is_cross_attention) + self.output = BertSelfOutput( + config, + twin=is_cross_attention, + merge=(is_cross_attention and layer_num >= 6), + ) + self.pruned_heads = set() + + def prune_heads(self, heads): + if len(heads) == 0: + return + heads, index = find_pruneable_heads_and_indices( + heads, + self.self.num_attention_heads, + self.self.attention_head_size, + self.pruned_heads, + ) + + # Prune linear layers + self.self.query = prune_linear_layer(self.self.query, index) + self.self.key = prune_linear_layer(self.self.key, index) + self.self.value = prune_linear_layer(self.self.value, index) + self.output.dense = prune_linear_layer(self.output.dense, index, dim=1) + + # Update hyper params and store pruned heads + self.self.num_attention_heads = self.self.num_attention_heads - len(heads) + self.self.all_head_size = ( + self.self.attention_head_size * self.self.num_attention_heads + ) + self.pruned_heads = self.pruned_heads.union(heads) + + def forward( + self, + hidden_states, + attention_mask=None, + head_mask=None, + encoder_hidden_states=None, + encoder_attention_mask=None, + past_key_value=None, + output_attentions=False, + ): + if type(encoder_hidden_states) == list: + self_outputs0 = self.self0( + hidden_states, + attention_mask, + head_mask, + encoder_hidden_states[0], + encoder_attention_mask[0], + past_key_value, + output_attentions, + ) + self_outputs1 = self.self1( + hidden_states, + attention_mask, + head_mask, + encoder_hidden_states[1], + encoder_attention_mask[1], + past_key_value, + output_attentions, + ) + attention_output = self.output( + [self_outputs0[0], self_outputs1[0]], hidden_states + ) + + outputs = (attention_output,) + self_outputs0[ + 1: + ] # add attentions if we output them + else: + self_outputs = self.self( + hidden_states, + attention_mask, + head_mask, + encoder_hidden_states, + encoder_attention_mask, + past_key_value, + output_attentions, + ) + attention_output = self.output(self_outputs[0], hidden_states) + outputs = (attention_output,) + self_outputs[ + 1: + ] # add attentions if we output them + return outputs + + +class BertIntermediate(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.intermediate_size) + if isinstance(config.hidden_act, str): + self.intermediate_act_fn = ACT2FN[config.hidden_act] + else: + self.intermediate_act_fn = config.hidden_act + + def forward(self, hidden_states): + hidden_states = self.dense(hidden_states) + hidden_states = self.intermediate_act_fn(hidden_states) + return hidden_states + + +class BertOutput(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.intermediate_size, config.hidden_size) + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states, input_tensor): + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + hidden_states = self.LayerNorm(hidden_states + input_tensor) + return hidden_states + + +class BertLayer(nn.Module): + def __init__(self, config, layer_num): + super().__init__() + self.config = config + self.chunk_size_feed_forward = config.chunk_size_feed_forward + self.seq_len_dim = 1 + self.attention = BertAttention(config) + self.layer_num = layer_num + if self.config.add_cross_attention: + self.crossattention = BertAttention( + config, + is_cross_attention=self.config.add_cross_attention, + layer_num=layer_num, + ) + self.intermediate = BertIntermediate(config) + self.output = BertOutput(config) + + def forward( + self, + hidden_states, + attention_mask=None, + head_mask=None, + encoder_hidden_states=None, + encoder_attention_mask=None, + past_key_value=None, + output_attentions=False, + mode=None, + ): + # decoder uni-directional self-attention cached key/values tuple is at positions 1,2 + self_attn_past_key_value = ( + past_key_value[:2] if past_key_value is not None else None + ) + self_attention_outputs = self.attention( + hidden_states, + attention_mask, + head_mask, + output_attentions=output_attentions, + past_key_value=self_attn_past_key_value, + ) + attention_output = self_attention_outputs[0] + + outputs = self_attention_outputs[1:-1] + present_key_value = self_attention_outputs[-1] + + if mode == "multimodal": + assert ( + encoder_hidden_states is not None + ), "encoder_hidden_states must be given for cross-attention layers" + cross_attention_outputs = self.crossattention( + attention_output, + attention_mask, + head_mask, + encoder_hidden_states, + encoder_attention_mask, + output_attentions=output_attentions, + ) + attention_output = cross_attention_outputs[0] + outputs = ( + outputs + cross_attention_outputs[1:-1] + ) # add cross attentions if we output attention weights + layer_output = apply_chunking_to_forward( + self.feed_forward_chunk, + self.chunk_size_feed_forward, + self.seq_len_dim, + attention_output, + ) + outputs = (layer_output,) + outputs + + outputs = outputs + (present_key_value,) + + return outputs + + def feed_forward_chunk(self, attention_output): + intermediate_output = self.intermediate(attention_output) + layer_output = self.output(intermediate_output, attention_output) + return layer_output + + +class BertEncoder(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.layer = nn.ModuleList( + [BertLayer(config, i) for i in range(config.num_hidden_layers)] + ) + self.gradient_checkpointing = False + + def forward( + self, + hidden_states, + attention_mask=None, + head_mask=None, + encoder_hidden_states=None, + encoder_attention_mask=None, + past_key_values=None, + use_cache=None, + output_attentions=False, + output_hidden_states=False, + return_dict=True, + mode="multimodal", + ): + all_hidden_states = () if output_hidden_states else None + all_self_attentions = () if output_attentions else None + all_cross_attentions = ( + () if output_attentions and self.config.add_cross_attention else None + ) + + next_decoder_cache = () if use_cache else None + + for i in range(self.config.num_hidden_layers): + layer_module = self.layer[i] + if output_hidden_states: + all_hidden_states = all_hidden_states + (hidden_states,) + + layer_head_mask = head_mask[i] if head_mask is not None else None + past_key_value = past_key_values[i] if past_key_values is not None else None + + if self.gradient_checkpointing and self.training: + if use_cache: + logger.warn( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs, past_key_value, output_attentions) + + return custom_forward + + layer_outputs = torch.utils.checkpoint.checkpoint( + create_custom_forward(layer_module), + hidden_states, + attention_mask, + layer_head_mask, + encoder_hidden_states, + encoder_attention_mask, + mode=mode, + ) + else: + layer_outputs = layer_module( + hidden_states, + attention_mask, + layer_head_mask, + encoder_hidden_states, + encoder_attention_mask, + past_key_value, + output_attentions, + mode=mode, + ) + + hidden_states = layer_outputs[0] + if use_cache: + next_decoder_cache += (layer_outputs[-1],) + if output_attentions: + all_self_attentions = all_self_attentions + (layer_outputs[1],) + + if output_hidden_states: + all_hidden_states = all_hidden_states + (hidden_states,) + + if not return_dict: + return tuple( + v + for v in [ + hidden_states, + next_decoder_cache, + all_hidden_states, + all_self_attentions, + all_cross_attentions, + ] + if v is not None + ) + return BaseModelOutputWithPastAndCrossAttentions( + last_hidden_state=hidden_states, + past_key_values=next_decoder_cache, + hidden_states=all_hidden_states, + attentions=all_self_attentions, + cross_attentions=all_cross_attentions, + ) + + +class BertPooler(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + self.activation = nn.Tanh() + + def forward(self, hidden_states): + # We "pool" the model by simply taking the hidden state corresponding + # to the first token. + first_token_tensor = hidden_states[:, 0] + pooled_output = self.dense(first_token_tensor) + pooled_output = self.activation(pooled_output) + return pooled_output + + +class BertPredictionHeadTransform(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + if isinstance(config.hidden_act, str): + self.transform_act_fn = ACT2FN[config.hidden_act] + else: + self.transform_act_fn = config.hidden_act + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + + def forward(self, hidden_states): + hidden_states = self.dense(hidden_states) + hidden_states = self.transform_act_fn(hidden_states) + hidden_states = self.LayerNorm(hidden_states) + return hidden_states + + +class BertLMPredictionHead(nn.Module): + def __init__(self, config): + super().__init__() + self.transform = BertPredictionHeadTransform(config) + + # The output weights are the same as the input embeddings, but there is + # an output-only bias for each token. + self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + + self.bias = nn.Parameter(torch.zeros(config.vocab_size)) + + # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` + self.decoder.bias = self.bias + + def forward(self, hidden_states): + hidden_states = self.transform(hidden_states) + hidden_states = self.decoder(hidden_states) + return hidden_states + + +class BertOnlyMLMHead(nn.Module): + def __init__(self, config): + super().__init__() + self.predictions = BertLMPredictionHead(config) + + def forward(self, sequence_output): + prediction_scores = self.predictions(sequence_output) + return prediction_scores + + +class BertPreTrainedModel(PreTrainedModel): + """ + An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained + models. + """ + + config_class = BertConfig + base_model_prefix = "bert" + _keys_to_ignore_on_load_missing = [r"position_ids"] + + def _init_weights(self, module): + """Initialize the weights""" + if isinstance(module, (nn.Linear, nn.Embedding)): + # Slightly different from the TF version which uses truncated_normal for initialization + # cf https://github.com/pytorch/pytorch/pull/5617 + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + elif isinstance(module, nn.LayerNorm): + module.bias.data.zero_() + module.weight.data.fill_(1.0) + if isinstance(module, nn.Linear) and module.bias is not None: + module.bias.data.zero_() + + +class BertModel(BertPreTrainedModel): + """ + The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of + cross-attention is added between the self-attention layers, following the architecture described in `Attention is + all you need `__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, + Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. + argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an + input to the forward pass. + """ + + def __init__(self, config, add_pooling_layer=True): + super().__init__(config) + self.config = config + + self.embeddings = BertEmbeddings(config) + + self.encoder = BertEncoder(config) + + self.pooler = BertPooler(config) if add_pooling_layer else None + + self.init_weights() + + def get_input_embeddings(self): + return self.embeddings.word_embeddings + + def set_input_embeddings(self, value): + self.embeddings.word_embeddings = value + + def _prune_heads(self, heads_to_prune): + """ + Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base + class PreTrainedModel + """ + for layer, heads in heads_to_prune.items(): + self.encoder.layer[layer].attention.prune_heads(heads) + + def get_extended_attention_mask( + self, + attention_mask: Tensor, + input_shape: Tuple[int], + device: device, + is_decoder: bool, + ) -> Tensor: + """ + Makes broadcastable attention and causal masks so that future and masked tokens are ignored. + + Arguments: + attention_mask (:obj:`torch.Tensor`): + Mask with ones indicating tokens to attend to, zeros for tokens to ignore. + input_shape (:obj:`Tuple[int]`): + The shape of the input to the model. + device: (:obj:`torch.device`): + The device of the input to the model. + + Returns: + :obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`. + """ + # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] + # ourselves in which case we just need to make it broadcastable to all heads. + if attention_mask.dim() == 3: + extended_attention_mask = attention_mask[:, None, :, :] + elif attention_mask.dim() == 2: + # Provided a padding mask of dimensions [batch_size, seq_length] + # - if the model is a decoder, apply a causal mask in addition to the padding mask + # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length] + if is_decoder: + batch_size, seq_length = input_shape + + seq_ids = torch.arange(seq_length, device=device) + causal_mask = ( + seq_ids[None, None, :].repeat(batch_size, seq_length, 1) + <= seq_ids[None, :, None] + ) + # in case past_key_values are used we need to add a prefix ones mask to the causal mask + # causal and attention masks must have same type with pytorch version < 1.3 + causal_mask = causal_mask.to(attention_mask.dtype) + + if causal_mask.shape[1] < attention_mask.shape[1]: + prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1] + causal_mask = torch.cat( + [ + torch.ones( + (batch_size, seq_length, prefix_seq_len), + device=device, + dtype=causal_mask.dtype, + ), + causal_mask, + ], + axis=-1, + ) + + extended_attention_mask = ( + causal_mask[:, None, :, :] * attention_mask[:, None, None, :] + ) + else: + extended_attention_mask = attention_mask[:, None, None, :] + else: + raise ValueError( + "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format( + input_shape, attention_mask.shape + ) + ) + + # Since attention_mask is 1.0 for positions we want to attend and 0.0 for + # masked positions, this operation will create a tensor which is 0.0 for + # positions we want to attend and -10000.0 for masked positions. + # Since we are adding it to the raw scores before the softmax, this is + # effectively the same as removing these entirely. + extended_attention_mask = extended_attention_mask.to( + dtype=self.dtype + ) # fp16 compatibility + extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0 + return extended_attention_mask + + def forward( + self, + input_ids=None, + attention_mask=None, + position_ids=None, + head_mask=None, + inputs_embeds=None, + encoder_embeds=None, + encoder_hidden_states=None, + encoder_attention_mask=None, + past_key_values=None, + use_cache=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + is_decoder=False, + mode="multimodal", + ): + r""" + encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): + Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if + the model is configured as a decoder. + encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): + Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in + the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``: + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): + Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. + If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` + (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` + instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`. + use_cache (:obj:`bool`, `optional`): + If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up + decoding (see :obj:`past_key_values`). + """ + output_attentions = ( + output_attentions + if output_attentions is not None + else self.config.output_attentions + ) + output_hidden_states = ( + output_hidden_states + if output_hidden_states is not None + else self.config.output_hidden_states + ) + return_dict = ( + return_dict if return_dict is not None else self.config.use_return_dict + ) + + if is_decoder: + use_cache = use_cache if use_cache is not None else self.config.use_cache + else: + use_cache = False + + if input_ids is not None and inputs_embeds is not None: + raise ValueError( + "You cannot specify both input_ids and inputs_embeds at the same time" + ) + elif input_ids is not None: + input_shape = input_ids.size() + batch_size, seq_length = input_shape + device = input_ids.device + elif inputs_embeds is not None: + input_shape = inputs_embeds.size()[:-1] + batch_size, seq_length = input_shape + device = inputs_embeds.device + elif encoder_embeds is not None: + input_shape = encoder_embeds.size()[:-1] + batch_size, seq_length = input_shape + device = encoder_embeds.device + else: + raise ValueError( + "You have to specify either input_ids or inputs_embeds or encoder_embeds" + ) + + # past_key_values_length + past_key_values_length = ( + past_key_values[0][0].shape[2] if past_key_values is not None else 0 + ) + + if attention_mask is None: + attention_mask = torch.ones( + ((batch_size, seq_length + past_key_values_length)), device=device + ) + + # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] + # ourselves in which case we just need to make it broadcastable to all heads. + extended_attention_mask: torch.Tensor = self.get_extended_attention_mask( + attention_mask, input_shape, device, is_decoder + ) + + # If a 2D or 3D attention mask is provided for the cross-attention + # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] + if encoder_hidden_states is not None: + if type(encoder_hidden_states) == list: + encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[ + 0 + ].size() + else: + ( + encoder_batch_size, + encoder_sequence_length, + _, + ) = encoder_hidden_states.size() + encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) + + if type(encoder_attention_mask) == list: + encoder_extended_attention_mask = [ + self.invert_attention_mask(mask) for mask in encoder_attention_mask + ] + elif encoder_attention_mask is None: + encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) + encoder_extended_attention_mask = self.invert_attention_mask( + encoder_attention_mask + ) + else: + encoder_extended_attention_mask = self.invert_attention_mask( + encoder_attention_mask + ) + else: + encoder_extended_attention_mask = None + + # Prepare head mask if needed + # 1.0 in head_mask indicate we keep the head + # attention_probs has shape bsz x n_heads x N x N + # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] + # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] + head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) + + if encoder_embeds is None: + embedding_output = self.embeddings( + input_ids=input_ids, + position_ids=position_ids, + inputs_embeds=inputs_embeds, + past_key_values_length=past_key_values_length, + ) + else: + embedding_output = encoder_embeds + + encoder_outputs = self.encoder( + embedding_output, + attention_mask=extended_attention_mask, + head_mask=head_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_extended_attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + mode=mode, + ) + sequence_output = encoder_outputs[0] + pooled_output = ( + self.pooler(sequence_output) if self.pooler is not None else None + ) + + if not return_dict: + return (sequence_output, pooled_output) + encoder_outputs[1:] + + return BaseModelOutputWithPoolingAndCrossAttentions( + last_hidden_state=sequence_output, + pooler_output=pooled_output, + past_key_values=encoder_outputs.past_key_values, + hidden_states=encoder_outputs.hidden_states, + attentions=encoder_outputs.attentions, + cross_attentions=encoder_outputs.cross_attentions, + ) diff --git a/comfyui-art-venture/modules/interrogate/models/vit.py b/comfyui-art-venture/modules/interrogate/models/vit.py new file mode 100644 index 0000000000000000000000000000000000000000..cec3d8e08ed4451d65392feb2e9f4848d1ef3899 --- /dev/null +++ b/comfyui-art-venture/modules/interrogate/models/vit.py @@ -0,0 +1,305 @@ +''' + * Copyright (c) 2022, salesforce.com, inc. + * All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause + * By Junnan Li + * Based on timm code base + * https://github.com/rwightman/pytorch-image-models/tree/master/timm +''' + +import torch +import torch.nn as nn +import torch.nn.functional as F +from functools import partial + +from timm.models.vision_transformer import _cfg, PatchEmbed +from timm.models.registry import register_model +from timm.models.layers import trunc_normal_, DropPath +from timm.models.helpers import named_apply, adapt_input_conv + +from fairscale.nn.checkpoint.checkpoint_activations import checkpoint_wrapper + +class Mlp(nn.Module): + """ MLP as used in Vision Transformer, MLP-Mixer and related networks + """ + def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +class Attention(nn.Module): + def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.): + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + # NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights + self.scale = qk_scale or head_dim ** -0.5 + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + self.attn_gradients = None + self.attention_map = None + + def save_attn_gradients(self, attn_gradients): + self.attn_gradients = attn_gradients + + def get_attn_gradients(self): + return self.attn_gradients + + def save_attention_map(self, attention_map): + self.attention_map = attention_map + + def get_attention_map(self): + return self.attention_map + + def forward(self, x, register_hook=False): + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) + q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) + + attn = (q @ k.transpose(-2, -1)) * self.scale + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + + if register_hook: + self.save_attention_map(attn) + attn.register_hook(self.save_attn_gradients) + + x = (attn @ v).transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class Block(nn.Module): + + def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., + drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, use_grad_checkpointing=False): + super().__init__() + self.norm1 = norm_layer(dim) + self.attn = Attention( + dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) + # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here + self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) + + if use_grad_checkpointing: + self.attn = checkpoint_wrapper(self.attn) + self.mlp = checkpoint_wrapper(self.mlp) + + def forward(self, x, register_hook=False): + x = x + self.drop_path(self.attn(self.norm1(x), register_hook=register_hook)) + x = x + self.drop_path(self.mlp(self.norm2(x))) + return x + + +class VisionTransformer(nn.Module): + """ Vision Transformer + A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale` - + https://arxiv.org/abs/2010.11929 + """ + def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12, + num_heads=12, mlp_ratio=4., qkv_bias=True, qk_scale=None, representation_size=None, + drop_rate=0., attn_drop_rate=0., drop_path_rate=0., norm_layer=None, + use_grad_checkpointing=False, ckpt_layer=0): + """ + Args: + img_size (int, tuple): input image size + patch_size (int, tuple): patch size + in_chans (int): number of input channels + num_classes (int): number of classes for classification head + embed_dim (int): embedding dimension + depth (int): depth of transformer + num_heads (int): number of attention heads + mlp_ratio (int): ratio of mlp hidden dim to embedding dim + qkv_bias (bool): enable bias for qkv if True + qk_scale (float): override default qk scale of head_dim ** -0.5 if set + representation_size (Optional[int]): enable and set representation layer (pre-logits) to this value if set + drop_rate (float): dropout rate + attn_drop_rate (float): attention dropout rate + drop_path_rate (float): stochastic depth rate + norm_layer: (nn.Module): normalization layer + """ + super().__init__() + self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models + norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6) + + self.patch_embed = PatchEmbed( + img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) + + num_patches = self.patch_embed.num_patches + + self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) + self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim)) + self.pos_drop = nn.Dropout(p=drop_rate) + + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule + self.blocks = nn.ModuleList([ + Block( + dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, + drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, + use_grad_checkpointing=(use_grad_checkpointing and i>=depth-ckpt_layer) + ) + for i in range(depth)]) + self.norm = norm_layer(embed_dim) + + trunc_normal_(self.pos_embed, std=.02) + trunc_normal_(self.cls_token, std=.02) + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + @torch.jit.ignore + def no_weight_decay(self): + return {'pos_embed', 'cls_token'} + + def forward(self, x, register_blk=-1): + B = x.shape[0] + x = self.patch_embed(x) + + cls_tokens = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks + x = torch.cat((cls_tokens, x), dim=1) + + x = x + self.pos_embed[:,:x.size(1),:] + x = self.pos_drop(x) + + for i,blk in enumerate(self.blocks): + x = blk(x, register_blk==i) + x = self.norm(x) + + return x + + @torch.jit.ignore() + def load_pretrained(self, checkpoint_path, prefix=''): + _load_weights(self, checkpoint_path, prefix) + + +@torch.no_grad() +def _load_weights(model: VisionTransformer, checkpoint_path: str, prefix: str = ''): + """ Load weights from .npz checkpoints for official Google Brain Flax implementation + """ + import numpy as np + + def _n2p(w, t=True): + if w.ndim == 4 and w.shape[0] == w.shape[1] == w.shape[2] == 1: + w = w.flatten() + if t: + if w.ndim == 4: + w = w.transpose([3, 2, 0, 1]) + elif w.ndim == 3: + w = w.transpose([2, 0, 1]) + elif w.ndim == 2: + w = w.transpose([1, 0]) + return torch.from_numpy(w) + + w = np.load(checkpoint_path) + if not prefix and 'opt/target/embedding/kernel' in w: + prefix = 'opt/target/' + + if hasattr(model.patch_embed, 'backbone'): + # hybrid + backbone = model.patch_embed.backbone + stem_only = not hasattr(backbone, 'stem') + stem = backbone if stem_only else backbone.stem + stem.conv.weight.copy_(adapt_input_conv(stem.conv.weight.shape[1], _n2p(w[f'{prefix}conv_root/kernel']))) + stem.norm.weight.copy_(_n2p(w[f'{prefix}gn_root/scale'])) + stem.norm.bias.copy_(_n2p(w[f'{prefix}gn_root/bias'])) + if not stem_only: + for i, stage in enumerate(backbone.stages): + for j, block in enumerate(stage.blocks): + bp = f'{prefix}block{i + 1}/unit{j + 1}/' + for r in range(3): + getattr(block, f'conv{r + 1}').weight.copy_(_n2p(w[f'{bp}conv{r + 1}/kernel'])) + getattr(block, f'norm{r + 1}').weight.copy_(_n2p(w[f'{bp}gn{r + 1}/scale'])) + getattr(block, f'norm{r + 1}').bias.copy_(_n2p(w[f'{bp}gn{r + 1}/bias'])) + if block.downsample is not None: + block.downsample.conv.weight.copy_(_n2p(w[f'{bp}conv_proj/kernel'])) + block.downsample.norm.weight.copy_(_n2p(w[f'{bp}gn_proj/scale'])) + block.downsample.norm.bias.copy_(_n2p(w[f'{bp}gn_proj/bias'])) + embed_conv_w = _n2p(w[f'{prefix}embedding/kernel']) + else: + embed_conv_w = adapt_input_conv( + model.patch_embed.proj.weight.shape[1], _n2p(w[f'{prefix}embedding/kernel'])) + model.patch_embed.proj.weight.copy_(embed_conv_w) + model.patch_embed.proj.bias.copy_(_n2p(w[f'{prefix}embedding/bias'])) + model.cls_token.copy_(_n2p(w[f'{prefix}cls'], t=False)) + pos_embed_w = _n2p(w[f'{prefix}Transformer/posembed_input/pos_embedding'], t=False) + if pos_embed_w.shape != model.pos_embed.shape: + pos_embed_w = resize_pos_embed( # resize pos embedding when different size from pretrained weights + pos_embed_w, model.pos_embed, getattr(model, 'num_tokens', 1), model.patch_embed.grid_size) + model.pos_embed.copy_(pos_embed_w) + model.norm.weight.copy_(_n2p(w[f'{prefix}Transformer/encoder_norm/scale'])) + model.norm.bias.copy_(_n2p(w[f'{prefix}Transformer/encoder_norm/bias'])) +# if isinstance(model.head, nn.Linear) and model.head.bias.shape[0] == w[f'{prefix}head/bias'].shape[-1]: +# model.head.weight.copy_(_n2p(w[f'{prefix}head/kernel'])) +# model.head.bias.copy_(_n2p(w[f'{prefix}head/bias'])) +# if isinstance(getattr(model.pre_logits, 'fc', None), nn.Linear) and f'{prefix}pre_logits/bias' in w: +# model.pre_logits.fc.weight.copy_(_n2p(w[f'{prefix}pre_logits/kernel'])) +# model.pre_logits.fc.bias.copy_(_n2p(w[f'{prefix}pre_logits/bias'])) + for i, block in enumerate(model.blocks.children()): + block_prefix = f'{prefix}Transformer/encoderblock_{i}/' + mha_prefix = block_prefix + 'MultiHeadDotProductAttention_1/' + block.norm1.weight.copy_(_n2p(w[f'{block_prefix}LayerNorm_0/scale'])) + block.norm1.bias.copy_(_n2p(w[f'{block_prefix}LayerNorm_0/bias'])) + block.attn.qkv.weight.copy_(torch.cat([ + _n2p(w[f'{mha_prefix}{n}/kernel'], t=False).flatten(1).T for n in ('query', 'key', 'value')])) + block.attn.qkv.bias.copy_(torch.cat([ + _n2p(w[f'{mha_prefix}{n}/bias'], t=False).reshape(-1) for n in ('query', 'key', 'value')])) + block.attn.proj.weight.copy_(_n2p(w[f'{mha_prefix}out/kernel']).flatten(1)) + block.attn.proj.bias.copy_(_n2p(w[f'{mha_prefix}out/bias'])) + for r in range(2): + getattr(block.mlp, f'fc{r + 1}').weight.copy_(_n2p(w[f'{block_prefix}MlpBlock_3/Dense_{r}/kernel'])) + getattr(block.mlp, f'fc{r + 1}').bias.copy_(_n2p(w[f'{block_prefix}MlpBlock_3/Dense_{r}/bias'])) + block.norm2.weight.copy_(_n2p(w[f'{block_prefix}LayerNorm_2/scale'])) + block.norm2.bias.copy_(_n2p(w[f'{block_prefix}LayerNorm_2/bias'])) + + +def interpolate_pos_embed(pos_embed_checkpoint, visual_encoder): + # interpolate position embedding + embedding_size = pos_embed_checkpoint.shape[-1] + num_patches = visual_encoder.patch_embed.num_patches + num_extra_tokens = visual_encoder.pos_embed.shape[-2] - num_patches + # height (== width) for the checkpoint position embedding + orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5) + # height (== width) for the new position embedding + new_size = int(num_patches ** 0.5) + + if orig_size!=new_size: + # class_token and dist_token are kept unchanged + extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens] + # only the position tokens are interpolated + pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:] + pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2) + pos_tokens = torch.nn.functional.interpolate( + pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False) + pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2) + new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1) + print('reshape position embedding from %d to %d'%(orig_size ** 2,new_size ** 2)) + + return new_pos_embed + else: + return pos_embed_checkpoint \ No newline at end of file diff --git a/comfyui-art-venture/modules/interrogate/transform/randaugment.py b/comfyui-art-venture/modules/interrogate/transform/randaugment.py new file mode 100644 index 0000000000000000000000000000000000000000..094d9f4cacc93146d2bab7311d9dc04feb07032c --- /dev/null +++ b/comfyui-art-venture/modules/interrogate/transform/randaugment.py @@ -0,0 +1,340 @@ +import cv2 +import numpy as np + + +## aug functions +def identity_func(img): + return img + + +def autocontrast_func(img, cutoff=0): + ''' + same output as PIL.ImageOps.autocontrast + ''' + n_bins = 256 + + def tune_channel(ch): + n = ch.size + cut = cutoff * n // 100 + if cut == 0: + high, low = ch.max(), ch.min() + else: + hist = cv2.calcHist([ch], [0], None, [n_bins], [0, n_bins]) + low = np.argwhere(np.cumsum(hist) > cut) + low = 0 if low.shape[0] == 0 else low[0] + high = np.argwhere(np.cumsum(hist[::-1]) > cut) + high = n_bins - 1 if high.shape[0] == 0 else n_bins - 1 - high[0] + if high <= low: + table = np.arange(n_bins) + else: + scale = (n_bins - 1) / (high - low) + offset = -low * scale + table = np.arange(n_bins) * scale + offset + table[table < 0] = 0 + table[table > n_bins - 1] = n_bins - 1 + table = table.clip(0, 255).astype(np.uint8) + return table[ch] + + channels = [tune_channel(ch) for ch in cv2.split(img)] + out = cv2.merge(channels) + return out + + +def equalize_func(img): + ''' + same output as PIL.ImageOps.equalize + PIL's implementation is different from cv2.equalize + ''' + n_bins = 256 + + def tune_channel(ch): + hist = cv2.calcHist([ch], [0], None, [n_bins], [0, n_bins]) + non_zero_hist = hist[hist != 0].reshape(-1) + step = np.sum(non_zero_hist[:-1]) // (n_bins - 1) + if step == 0: return ch + n = np.empty_like(hist) + n[0] = step // 2 + n[1:] = hist[:-1] + table = (np.cumsum(n) // step).clip(0, 255).astype(np.uint8) + return table[ch] + + channels = [tune_channel(ch) for ch in cv2.split(img)] + out = cv2.merge(channels) + return out + + +def rotate_func(img, degree, fill=(0, 0, 0)): + ''' + like PIL, rotate by degree, not radians + ''' + H, W = img.shape[0], img.shape[1] + center = W / 2, H / 2 + M = cv2.getRotationMatrix2D(center, degree, 1) + out = cv2.warpAffine(img, M, (W, H), borderValue=fill) + return out + + +def solarize_func(img, thresh=128): + ''' + same output as PIL.ImageOps.posterize + ''' + table = np.array([el if el < thresh else 255 - el for el in range(256)]) + table = table.clip(0, 255).astype(np.uint8) + out = table[img] + return out + + +def color_func(img, factor): + ''' + same output as PIL.ImageEnhance.Color + ''' + ## implementation according to PIL definition, quite slow + # degenerate = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)[:, :, np.newaxis] + # out = blend(degenerate, img, factor) + # M = ( + # np.eye(3) * factor + # + np.float32([0.114, 0.587, 0.299]).reshape(3, 1) * (1. - factor) + # )[np.newaxis, np.newaxis, :] + M = ( + np.float32([ + [0.886, -0.114, -0.114], + [-0.587, 0.413, -0.587], + [-0.299, -0.299, 0.701]]) * factor + + np.float32([[0.114], [0.587], [0.299]]) + ) + out = np.matmul(img, M).clip(0, 255).astype(np.uint8) + return out + + +def contrast_func(img, factor): + """ + same output as PIL.ImageEnhance.Contrast + """ + mean = np.sum(np.mean(img, axis=(0, 1)) * np.array([0.114, 0.587, 0.299])) + table = np.array([( + el - mean) * factor + mean + for el in range(256) + ]).clip(0, 255).astype(np.uint8) + out = table[img] + return out + + +def brightness_func(img, factor): + ''' + same output as PIL.ImageEnhance.Contrast + ''' + table = (np.arange(256, dtype=np.float32) * factor).clip(0, 255).astype(np.uint8) + out = table[img] + return out + + +def sharpness_func(img, factor): + ''' + The differences the this result and PIL are all on the 4 boundaries, the center + areas are same + ''' + kernel = np.ones((3, 3), dtype=np.float32) + kernel[1][1] = 5 + kernel /= 13 + degenerate = cv2.filter2D(img, -1, kernel) + if factor == 0.0: + out = degenerate + elif factor == 1.0: + out = img + else: + out = img.astype(np.float32) + degenerate = degenerate.astype(np.float32)[1:-1, 1:-1, :] + out[1:-1, 1:-1, :] = degenerate + factor * (out[1:-1, 1:-1, :] - degenerate) + out = out.astype(np.uint8) + return out + + +def shear_x_func(img, factor, fill=(0, 0, 0)): + H, W = img.shape[0], img.shape[1] + M = np.float32([[1, factor, 0], [0, 1, 0]]) + out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8) + return out + + +def translate_x_func(img, offset, fill=(0, 0, 0)): + ''' + same output as PIL.Image.transform + ''' + H, W = img.shape[0], img.shape[1] + M = np.float32([[1, 0, -offset], [0, 1, 0]]) + out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8) + return out + + +def translate_y_func(img, offset, fill=(0, 0, 0)): + ''' + same output as PIL.Image.transform + ''' + H, W = img.shape[0], img.shape[1] + M = np.float32([[1, 0, 0], [0, 1, -offset]]) + out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8) + return out + + +def posterize_func(img, bits): + ''' + same output as PIL.ImageOps.posterize + ''' + out = np.bitwise_and(img, np.uint8(255 << (8 - bits))) + return out + + +def shear_y_func(img, factor, fill=(0, 0, 0)): + H, W = img.shape[0], img.shape[1] + M = np.float32([[1, 0, 0], [factor, 1, 0]]) + out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8) + return out + + +def cutout_func(img, pad_size, replace=(0, 0, 0)): + replace = np.array(replace, dtype=np.uint8) + H, W = img.shape[0], img.shape[1] + rh, rw = np.random.random(2) + pad_size = pad_size // 2 + ch, cw = int(rh * H), int(rw * W) + x1, x2 = max(ch - pad_size, 0), min(ch + pad_size, H) + y1, y2 = max(cw - pad_size, 0), min(cw + pad_size, W) + out = img.copy() + out[x1:x2, y1:y2, :] = replace + return out + + +### level to args +def enhance_level_to_args(MAX_LEVEL): + def level_to_args(level): + return ((level / MAX_LEVEL) * 1.8 + 0.1,) + return level_to_args + + +def shear_level_to_args(MAX_LEVEL, replace_value): + def level_to_args(level): + level = (level / MAX_LEVEL) * 0.3 + if np.random.random() > 0.5: level = -level + return (level, replace_value) + + return level_to_args + + +def translate_level_to_args(translate_const, MAX_LEVEL, replace_value): + def level_to_args(level): + level = (level / MAX_LEVEL) * float(translate_const) + if np.random.random() > 0.5: level = -level + return (level, replace_value) + + return level_to_args + + +def cutout_level_to_args(cutout_const, MAX_LEVEL, replace_value): + def level_to_args(level): + level = int((level / MAX_LEVEL) * cutout_const) + return (level, replace_value) + + return level_to_args + + +def solarize_level_to_args(MAX_LEVEL): + def level_to_args(level): + level = int((level / MAX_LEVEL) * 256) + return (level, ) + return level_to_args + + +def none_level_to_args(level): + return () + + +def posterize_level_to_args(MAX_LEVEL): + def level_to_args(level): + level = int((level / MAX_LEVEL) * 4) + return (level, ) + return level_to_args + + +def rotate_level_to_args(MAX_LEVEL, replace_value): + def level_to_args(level): + level = (level / MAX_LEVEL) * 30 + if np.random.random() < 0.5: + level = -level + return (level, replace_value) + + return level_to_args + + +func_dict = { + 'Identity': identity_func, + 'AutoContrast': autocontrast_func, + 'Equalize': equalize_func, + 'Rotate': rotate_func, + 'Solarize': solarize_func, + 'Color': color_func, + 'Contrast': contrast_func, + 'Brightness': brightness_func, + 'Sharpness': sharpness_func, + 'ShearX': shear_x_func, + 'TranslateX': translate_x_func, + 'TranslateY': translate_y_func, + 'Posterize': posterize_func, + 'ShearY': shear_y_func, +} + +translate_const = 10 +MAX_LEVEL = 10 +replace_value = (128, 128, 128) +arg_dict = { + 'Identity': none_level_to_args, + 'AutoContrast': none_level_to_args, + 'Equalize': none_level_to_args, + 'Rotate': rotate_level_to_args(MAX_LEVEL, replace_value), + 'Solarize': solarize_level_to_args(MAX_LEVEL), + 'Color': enhance_level_to_args(MAX_LEVEL), + 'Contrast': enhance_level_to_args(MAX_LEVEL), + 'Brightness': enhance_level_to_args(MAX_LEVEL), + 'Sharpness': enhance_level_to_args(MAX_LEVEL), + 'ShearX': shear_level_to_args(MAX_LEVEL, replace_value), + 'TranslateX': translate_level_to_args( + translate_const, MAX_LEVEL, replace_value + ), + 'TranslateY': translate_level_to_args( + translate_const, MAX_LEVEL, replace_value + ), + 'Posterize': posterize_level_to_args(MAX_LEVEL), + 'ShearY': shear_level_to_args(MAX_LEVEL, replace_value), +} + + +class RandomAugment(object): + + def __init__(self, N=2, M=10, isPIL=False, augs=[]): + self.N = N + self.M = M + self.isPIL = isPIL + if augs: + self.augs = augs + else: + self.augs = list(arg_dict.keys()) + + def get_random_ops(self): + sampled_ops = np.random.choice(self.augs, self.N) + return [(op, 0.5, self.M) for op in sampled_ops] + + def __call__(self, img): + if self.isPIL: + img = np.array(img) + ops = self.get_random_ops() + for name, prob, level in ops: + if np.random.random() > prob: + continue + args = arg_dict[name](level) + img = func_dict[name](img, *args) + return img + + +if __name__ == '__main__': + a = RandomAugment() + img = np.random.randn(32, 32, 3) + a(img) \ No newline at end of file diff --git a/comfyui-art-venture/modules/ip_adapter_nodes.py b/comfyui-art-venture/modules/ip_adapter_nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..27cef9afe684b3293e2cd4895e56ec5280cb51f2 --- /dev/null +++ b/comfyui-art-venture/modules/ip_adapter_nodes.py @@ -0,0 +1,148 @@ +import os +from typing import Dict, Tuple + +import folder_paths +import comfy.clip_vision +import comfy.controlnet +import comfy.utils +import comfy.model_management + +from .utils import load_module + +custom_nodes = folder_paths.get_folder_paths("custom_nodes") +ip_adapter_dir_names = ["IPAdapter", "ComfyUI_IPAdapter_plus"] + +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 ip_adapter_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 IPAdapter nodes") + + module = load_module(module_path) + print("Loaded IPAdapter nodes from", module_path) + + nodes: Dict = getattr(module, "NODE_CLASS_MAPPINGS") + IPAdapterModelLoader = nodes.get("IPAdapterModelLoader") + IPAdapterSimple = nodes.get("IPAdapter") + + loader = IPAdapterModelLoader() + apply = IPAdapterSimple() + + class AV_IPAdapterPipe: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "ip_adapter_name": (folder_paths.get_filename_list("ipadapter"),), + "clip_name": (folder_paths.get_filename_list("clip_vision"),), + } + } + + RETURN_TYPES = ("IPADAPTER",) + RETURN_NAMES = ("pipeline",) + CATEGORY = "Art Venture/IP Adapter" + FUNCTION = "load_ip_adapter" + + def load_ip_adapter(self, ip_adapter_name, clip_name): + ip_adapter = loader.load_ipadapter_model(ip_adapter_name)[0] + + clip_path = folder_paths.get_full_path("clip_vision", clip_name) + clip_vision = comfy.clip_vision.load(clip_path) + + pipeline = {"ipadapter": {"model": ip_adapter}, "clipvision": {"model": clip_vision}} + return (pipeline,) + + class AV_IPAdapter: + @classmethod + def INPUT_TYPES(cls): + inputs = IPAdapterSimple.INPUT_TYPES() + + return { + "required": { + "ip_adapter_name": (["None"] + folder_paths.get_filename_list("ipadapter"),), + "clip_name": (["None"] + folder_paths.get_filename_list("clip_vision"),), + "model": ("MODEL",), + "image": ("IMAGE",), + "weight": ("FLOAT", {"default": 1.0, "min": -1, "max": 3, "step": 0.05}), + }, + "optional": { + "ip_adapter_opt": ("IPADAPTER",), + "clip_vision_opt": ("CLIP_VISION",), + "attn_mask": ("MASK",), + "start_at": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}), + "end_at": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}), + "weight_type": inputs["required"]["weight_type"], + "enabled": ("BOOLEAN", {"default": True}), + }, + } + + RETURN_TYPES = ("MODEL", "IPADAPTER", "CLIP_VISION") + RETURN_NAMES = ("model", "pipeline", "clip_vision") + CATEGORY = "Art Venture/IP Adapter" + FUNCTION = "apply_ip_adapter" + + def apply_ip_adapter( + self, + ip_adapter_name, + clip_name, + model, + image, + weight, + ip_adapter_opt=None, + clip_vision_opt=None, + enabled=True, + **kwargs, + ): + if not enabled: + return (model, None, None) + + if ip_adapter_opt: + if "ipadapter" in ip_adapter_opt: + ip_adapter = ip_adapter_opt["ipadapter"]["model"] + else: + ip_adapter = ip_adapter_opt + else: + assert ip_adapter_name != "None", "IP Adapter name must be specified" + ip_adapter = loader.load_ipadapter_model(ip_adapter_name)[0] + + if clip_vision_opt: + clip_vision = clip_vision_opt + elif ip_adapter_opt and "clipvision" in ip_adapter_opt: + clip_vision = ip_adapter_opt["clipvision"]["model"] + else: + assert clip_name != "None", "Clip vision name must be specified" + clip_path = folder_paths.get_full_path("clip_vision", clip_name) + clip_vision = comfy.clip_vision.load(clip_path) + + pipeline = {"ipadapter": {"model": ip_adapter}, "clipvision": {"model": clip_vision}} + + res: Tuple = apply.apply_ipadapter(model, pipeline, image=image, weight=weight, **kwargs) + res += (pipeline, clip_vision) + + return res + + NODE_CLASS_MAPPINGS.update( + { + "AV_IPAdapter": AV_IPAdapter, + "AV_IPAdapterPipe": AV_IPAdapterPipe, + } + ) + NODE_DISPLAY_NAME_MAPPINGS.update( + { + "AV_IPAdapter": "IP Adapter Apply", + "AV_IPAdapterPipe": "IP Adapter Pipe", + } + ) + +except Exception as e: + print(e) diff --git a/comfyui-art-venture/modules/isnet/__init__.py b/comfyui-art-venture/modules/isnet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..59b9abebd8c75739fdf02b0a088a8d9a91e702bf --- /dev/null +++ b/comfyui-art-venture/modules/isnet/__init__.py @@ -0,0 +1,14 @@ +from .segmenter import ISNetLoader, ISNetSegment, DownloadISNetModel + +NODE_CLASS_MAPPINGS = { + "ISNetLoader": ISNetLoader, + "ISNetSegment": ISNetSegment, + "DownloadISNetModel": DownloadISNetModel, +} +NODE_DISPLAY_NAME_MAPPINGS = { + "ISNetLoader": "ISNet Loader", + "ISNetSegment": "ISNet Segment", + "DownloadISNetModel": "Download and Load ISNet Model", +} + +__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"] diff --git a/comfyui-art-venture/modules/isnet/__pycache__/__init__.cpython-310.pyc b/comfyui-art-venture/modules/isnet/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..539ef03f602103d24e6e240a80c304f4aa645461 Binary files /dev/null and b/comfyui-art-venture/modules/isnet/__pycache__/__init__.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/isnet/__pycache__/segmenter.cpython-310.pyc b/comfyui-art-venture/modules/isnet/__pycache__/segmenter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3052b1319d014910efef0ee06d2fa6c61ab1fc10 Binary files /dev/null and b/comfyui-art-venture/modules/isnet/__pycache__/segmenter.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/isnet/models/__init__.py b/comfyui-art-venture/modules/isnet/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d88e4103611dca3d8d2623465902b26ac3737a71 --- /dev/null +++ b/comfyui-art-venture/modules/isnet/models/__init__.py @@ -0,0 +1,2 @@ +from .isnet import ISNetBase +from .isnet_dis import ISNetDIS diff --git a/comfyui-art-venture/modules/isnet/models/isnet.py b/comfyui-art-venture/modules/isnet/models/isnet.py new file mode 100644 index 0000000000000000000000000000000000000000..3ba26e489d0b6283fc3cbf95dd04e6869fc3f567 --- /dev/null +++ b/comfyui-art-venture/modules/isnet/models/isnet.py @@ -0,0 +1,454 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + + +bce_loss = nn.BCELoss(size_average=True) +fea_loss = nn.MSELoss(size_average=True) +kl_loss = nn.KLDivLoss(size_average=True) +l1_loss = nn.L1Loss(size_average=True) +smooth_l1_loss = nn.SmoothL1Loss(size_average=True) + + +def muti_loss_fusion(preds, target): + loss0 = 0.0 + loss = 0.0 + + for i in range(0, len(preds)): + # print("i: ", i, preds[i].shape) + if preds[i].shape[2] != target.shape[2] or preds[i].shape[3] != target.shape[3]: + # tmp_target = _upsample_like(target,preds[i]) + tmp_target = F.interpolate(target, size=preds[i].size()[2:], mode="bilinear", align_corners=True) + loss = loss + bce_loss(preds[i], tmp_target) + else: + loss = loss + bce_loss(preds[i], target) + if i == 0: + loss0 = loss + return loss0, loss + + +def muti_loss_fusion_kl(preds, target, dfs, fs, mode="MSE"): + loss0 = 0.0 + loss = 0.0 + + for i in range(0, len(preds)): + # print("i: ", i, preds[i].shape) + if preds[i].shape[2] != target.shape[2] or preds[i].shape[3] != target.shape[3]: + # tmp_target = _upsample_like(target,preds[i]) + tmp_target = F.interpolate(target, size=preds[i].size()[2:], mode="bilinear", align_corners=True) + loss = loss + bce_loss(preds[i], tmp_target) + else: + loss = loss + bce_loss(preds[i], target) + if i == 0: + loss0 = loss + + for i in range(0, len(dfs)): + if mode == "MSE": + loss = loss + fea_loss(dfs[i], fs[i]) ### add the mse loss of features as additional constraints + # print("fea_loss: ", fea_loss(dfs[i],fs[i]).item()) + elif mode == "KL": + loss = loss + kl_loss(F.log_softmax(dfs[i], dim=1), F.softmax(fs[i], dim=1)) + # print("kl_loss: ", kl_loss(F.log_softmax(dfs[i],dim=1),F.softmax(fs[i],dim=1)).item()) + elif mode == "MAE": + loss = loss + l1_loss(dfs[i], fs[i]) + # print("ls_loss: ", l1_loss(dfs[i],fs[i])) + elif mode == "SmoothL1": + loss = loss + smooth_l1_loss(dfs[i], fs[i]) + # print("SmoothL1: ", smooth_l1_loss(dfs[i],fs[i]).item()) + + return loss0, loss + + +## upsample tensor 'src' to have the same spatial size with tensor 'tar' +def _upsample_like(src, tar): + src = F.upsample(src, size=tar.shape[2:], mode="bilinear") + + return src + + +class REBNCONV(nn.Module): + def __init__(self, in_ch=3, out_ch=3, dirate=1, stride=1): + super(REBNCONV, self).__init__() + + self.conv_s1 = nn.Conv2d(in_ch, out_ch, 3, padding=1 * dirate, dilation=1 * dirate, stride=stride) + self.bn_s1 = nn.BatchNorm2d(out_ch) + self.relu_s1 = nn.ReLU(inplace=True) + + def forward(self, x): + hx = x + xout = self.relu_s1(self.bn_s1(self.conv_s1(hx))) + + return xout + + +### RSU-7 ### +class RSU7(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3, img_size=512): + super(RSU7, self).__init__() + + self.in_ch = in_ch + self.mid_ch = mid_ch + self.out_ch = out_ch + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) ## 1 -> 1/2 + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool4 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool5 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv6 = REBNCONV(mid_ch, mid_ch, dirate=1) + + self.rebnconv7 = REBNCONV(mid_ch, mid_ch, dirate=2) + + self.rebnconv6d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv5d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + b, c, h, w = x.shape + + hx = x + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + hx = self.pool3(hx3) + + hx4 = self.rebnconv4(hx) + hx = self.pool4(hx4) + + hx5 = self.rebnconv5(hx) + hx = self.pool5(hx5) + + hx6 = self.rebnconv6(hx) + + hx7 = self.rebnconv7(hx6) + + hx6d = self.rebnconv6d(torch.cat((hx7, hx6), 1)) + hx6dup = _upsample_like(hx6d, hx5) + + hx5d = self.rebnconv5d(torch.cat((hx6dup, hx5), 1)) + hx5dup = _upsample_like(hx5d, hx4) + + hx4d = self.rebnconv4d(torch.cat((hx5dup, hx4), 1)) + hx4dup = _upsample_like(hx4d, hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1)) + + return hx1d + hxin + + +### RSU-6 ### +class RSU6(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU6, self).__init__() + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool4 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=1) + + self.rebnconv6 = REBNCONV(mid_ch, mid_ch, dirate=2) + + self.rebnconv5d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + hx = self.pool3(hx3) + + hx4 = self.rebnconv4(hx) + hx = self.pool4(hx4) + + hx5 = self.rebnconv5(hx) + + hx6 = self.rebnconv6(hx5) + + hx5d = self.rebnconv5d(torch.cat((hx6, hx5), 1)) + hx5dup = _upsample_like(hx5d, hx4) + + hx4d = self.rebnconv4d(torch.cat((hx5dup, hx4), 1)) + hx4dup = _upsample_like(hx4d, hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1)) + + return hx1d + hxin + + +### RSU-5 ### +class RSU5(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU5, self).__init__() + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1) + + self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=2) + + self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + hx = self.pool3(hx3) + + hx4 = self.rebnconv4(hx) + + hx5 = self.rebnconv5(hx4) + + hx4d = self.rebnconv4d(torch.cat((hx5, hx4), 1)) + hx4dup = _upsample_like(hx4d, hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1)) + + return hx1d + hxin + + +### RSU-4 ### +class RSU4(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU4, self).__init__() + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=2) + + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + + hx4 = self.rebnconv4(hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1)) + + return hx1d + hxin + + +### RSU-4F ### +class RSU4F(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU4F, self).__init__() + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=2) + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=4) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=8) + + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=4) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=2) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx2 = self.rebnconv2(hx1) + hx3 = self.rebnconv3(hx2) + + hx4 = self.rebnconv4(hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4, hx3), 1)) + hx2d = self.rebnconv2d(torch.cat((hx3d, hx2), 1)) + hx1d = self.rebnconv1d(torch.cat((hx2d, hx1), 1)) + + return hx1d + hxin + + +class ISNetBase(nn.Module): + def __init__(self, in_ch=3, out_ch=1): + super(ISNetBase, self).__init__() + + self.conv_in = nn.Conv2d(in_ch, 64, 3, stride=2, padding=1) + self.pool_in = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage1 = RSU7(64, 32, 64) + self.pool12 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage2 = RSU6(64, 32, 128) + self.pool23 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage3 = RSU5(128, 64, 256) + self.pool34 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage4 = RSU4(256, 128, 512) + self.pool45 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage5 = RSU4F(512, 256, 512) + self.pool56 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage6 = RSU4F(512, 256, 512) + + # decoder + self.stage5d = RSU4F(1024, 256, 512) + self.stage4d = RSU4(1024, 128, 256) + self.stage3d = RSU5(512, 64, 128) + self.stage2d = RSU6(256, 32, 64) + self.stage1d = RSU7(128, 16, 64) + + self.side1 = nn.Conv2d(64, out_ch, 3, padding=1) + + def forward(self, x): + hx = x + + hxin = self.conv_in(hx) + # hx = self.pool_in(hxin) + + # stage 1 + hx1 = self.stage1(hxin) + hx = self.pool12(hx1) + + # stage 2 + hx2 = self.stage2(hx) + hx = self.pool23(hx2) + + # stage 3 + hx3 = self.stage3(hx) + hx = self.pool34(hx3) + + # stage 4 + hx4 = self.stage4(hx) + hx = self.pool45(hx4) + + # stage 5 + hx5 = self.stage5(hx) + hx = self.pool56(hx5) + + # stage 6 + hx6 = self.stage6(hx) + hx6up = _upsample_like(hx6, hx5) + + # -------------------- decoder -------------------- + hx5d = self.stage5d(torch.cat((hx6up, hx5), 1)) + hx5dup = _upsample_like(hx5d, hx4) + + hx4d = self.stage4d(torch.cat((hx5dup, hx4), 1)) + hx4dup = _upsample_like(hx4d, hx3) + + hx3d = self.stage3d(torch.cat((hx4dup, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.stage2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.stage1d(torch.cat((hx2dup, hx1), 1)) + + # side output + d1 = self.side1(hx1d) + d1 = _upsample_like(d1, x) + + return d1.sigmoid() diff --git a/comfyui-art-venture/modules/isnet/models/isnet_dis.py b/comfyui-art-venture/modules/isnet/models/isnet_dis.py new file mode 100644 index 0000000000000000000000000000000000000000..ec1b414c7bc84deb91e663954ebff9fd96f9241c --- /dev/null +++ b/comfyui-art-venture/modules/isnet/models/isnet_dis.py @@ -0,0 +1,153 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + +from .isnet import RSU4, RSU4F, RSU5, RSU6, RSU7, _upsample_like, ISNetBase + + +bce_loss = nn.BCELoss(size_average=True) +fea_loss = nn.MSELoss(size_average=True) +kl_loss = nn.KLDivLoss(size_average=True) +l1_loss = nn.L1Loss(size_average=True) +smooth_l1_loss = nn.SmoothL1Loss(size_average=True) + + +def muti_loss_fusion(preds, target): + loss0 = 0.0 + loss = 0.0 + + for i in range(0, len(preds)): + # print("i: ", i, preds[i].shape) + if preds[i].shape[2] != target.shape[2] or preds[i].shape[3] != target.shape[3]: + # tmp_target = _upsample_like(target,preds[i]) + tmp_target = F.interpolate(target, size=preds[i].size()[2:], mode="bilinear", align_corners=True) + loss = loss + bce_loss(preds[i], tmp_target) + else: + loss = loss + bce_loss(preds[i], target) + if i == 0: + loss0 = loss + return loss0, loss + + +def muti_loss_fusion_kl(preds, target, dfs, fs, mode="MSE"): + loss0 = 0.0 + loss = 0.0 + + for i in range(0, len(preds)): + # print("i: ", i, preds[i].shape) + if preds[i].shape[2] != target.shape[2] or preds[i].shape[3] != target.shape[3]: + # tmp_target = _upsample_like(target,preds[i]) + tmp_target = F.interpolate(target, size=preds[i].size()[2:], mode="bilinear", align_corners=True) + loss = loss + bce_loss(preds[i], tmp_target) + else: + loss = loss + bce_loss(preds[i], target) + if i == 0: + loss0 = loss + + for i in range(0, len(dfs)): + if mode == "MSE": + loss = loss + fea_loss(dfs[i], fs[i]) ### add the mse loss of features as additional constraints + # print("fea_loss: ", fea_loss(dfs[i],fs[i]).item()) + elif mode == "KL": + loss = loss + kl_loss(F.log_softmax(dfs[i], dim=1), F.softmax(fs[i], dim=1)) + # print("kl_loss: ", kl_loss(F.log_softmax(dfs[i],dim=1),F.softmax(fs[i],dim=1)).item()) + elif mode == "MAE": + loss = loss + l1_loss(dfs[i], fs[i]) + # print("ls_loss: ", l1_loss(dfs[i],fs[i])) + elif mode == "SmoothL1": + loss = loss + smooth_l1_loss(dfs[i], fs[i]) + # print("SmoothL1: ", smooth_l1_loss(dfs[i],fs[i]).item()) + + return loss0, loss + + +class ISNetDIS(ISNetBase): + def __init__(self, in_ch=3, out_ch=1): + super(ISNetDIS, self).__init__(in_ch=in_ch, out_ch=out_ch) + + self.side2 = nn.Conv2d(64, out_ch, 3, padding=1) + self.side3 = nn.Conv2d(128, out_ch, 3, padding=1) + self.side4 = nn.Conv2d(256, out_ch, 3, padding=1) + self.side5 = nn.Conv2d(512, out_ch, 3, padding=1) + self.side6 = nn.Conv2d(512, out_ch, 3, padding=1) + + def compute_loss_kl(self, preds, targets, dfs, fs, mode="MSE"): + # return muti_loss_fusion(preds,targets) + return muti_loss_fusion_kl(preds, targets, dfs, fs, mode=mode) + + def compute_loss(self, preds, targets): + # return muti_loss_fusion(preds,targets) + return muti_loss_fusion(preds, targets) + + def forward(self, x): + hx = x + + hxin = self.conv_in(hx) + # hx = self.pool_in(hxin) + + # stage 1 + hx1 = self.stage1(hxin) + hx = self.pool12(hx1) + + # stage 2 + hx2 = self.stage2(hx) + hx = self.pool23(hx2) + + # stage 3 + hx3 = self.stage3(hx) + hx = self.pool34(hx3) + + # stage 4 + hx4 = self.stage4(hx) + hx = self.pool45(hx4) + + # stage 5 + hx5 = self.stage5(hx) + hx = self.pool56(hx5) + + # stage 6 + hx6 = self.stage6(hx) + hx6up = _upsample_like(hx6, hx5) + + # -------------------- decoder -------------------- + hx5d = self.stage5d(torch.cat((hx6up, hx5), 1)) + hx5dup = _upsample_like(hx5d, hx4) + + hx4d = self.stage4d(torch.cat((hx5dup, hx4), 1)) + hx4dup = _upsample_like(hx4d, hx3) + + hx3d = self.stage3d(torch.cat((hx4dup, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.stage2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.stage1d(torch.cat((hx2dup, hx1), 1)) + + # side output + d1 = self.side1(hx1d) + d1 = _upsample_like(d1, x) + + d2 = self.side2(hx2d) + d2 = _upsample_like(d2, x) + + d3 = self.side3(hx3d) + d3 = _upsample_like(d3, x) + + d4 = self.side4(hx4d) + d4 = _upsample_like(d4, x) + + d5 = self.side5(hx5d) + d5 = _upsample_like(d5, x) + + d6 = self.side6(hx6) + d6 = _upsample_like(d6, x) + + return [F.sigmoid(d1), F.sigmoid(d2), F.sigmoid(d3), F.sigmoid(d4), F.sigmoid(d5), F.sigmoid(d6)], [ + hx1d, + hx2d, + hx3d, + hx4d, + hx5d, + hx6, + ] diff --git a/comfyui-art-venture/modules/isnet/segmenter.py b/comfyui-art-venture/modules/isnet/segmenter.py new file mode 100644 index 0000000000000000000000000000000000000000..d322f519a7182b53feb5619fd8b9348d98b403cf --- /dev/null +++ b/comfyui-art-venture/modules/isnet/segmenter.py @@ -0,0 +1,233 @@ +import os +import torch +import torch.nn.functional as F +import numpy as np +from PIL import Image +from torch import nn +from torch.autograd import Variable +from torchvision import transforms +from torchvision.transforms.functional import normalize + +import folder_paths +import comfy.model_management as model_management +import comfy.utils + +from ..model_utils import download_file +from ..utils import pil2tensor, tensor2pil +from ..logger import logger + + +isnets = {} +cache_size = [1024, 1024] +gpu = model_management.get_torch_device() +cpu = torch.device("cpu") +model_dir = os.path.join(folder_paths.models_dir, "isnet") +models = { + "isnet-general-use.pth": { + "url": "https://huggingface.co/NimaBoscarino/IS-Net_DIS-general-use/resolve/main/isnet-general-use.pth", + "sha": "9e1aafea58f0b55d0c35077e0ceade6ba1ba2bce372fd4f8f77215391f3fac13", + }, + "isnetis.pth": { + "url": "https://github.com/Sanster/models/releases/download/isnetis/isnetis.pth", + "sha": "90a970badbd99ca7839b4e0beb09a36565d24edba7e4a876de23c761981e79e0", + }, + "RMBG-1.4.bin": { + "url": "https://huggingface.co/briaai/RMBG-1.4/resolve/main/pytorch_model.bin", + "sha": "59569acdb281ac9fc9f78f9d33b6f9f17f68e25086b74f9025c35bb5f2848967", + }, +} + +folder_paths.folder_names_and_paths["isnet"] = ( + [model_dir], + folder_paths.supported_pt_extensions, +) + + +class GOSNormalize(object): + def __init__(self, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]): + self.mean = mean + self.std = std + + def __call__(self, image): + image = normalize(image, self.mean, self.std) + return image + + +transform = transforms.Compose([GOSNormalize([0.5, 0.5, 0.5], [1.0, 1.0, 1.0])]) + + +def load_isnet_model(model_name): + if model_name not in isnets: + isnet_path = folder_paths.get_full_path("isnet", model_name) + state_dict = comfy.utils.load_torch_file(isnet_path) + + from .models import ISNetBase, ISNetDIS + + if "side2.weight" in state_dict: + isnet = ISNetDIS() + else: + isnet = ISNetBase() + + # convert to half precision + isnet.is_fp16 = model_management.should_use_fp16() + if isnet.is_fp16: + isnet.half() + for layer in isnet.modules(): + if isinstance(layer, nn.BatchNorm2d): + layer.float() + + isnet.load_state_dict(state_dict) + isnet.eval() + isnets[model_name] = isnet + + return isnets[model_name] + + +def im_preprocess(im: torch.Tensor, size): + im = im.clone() + + # Ensure the image has three channels + if len(im.shape) < 3: + im = im.unsqueeze(2) + if im.shape[2] == 1: + im = im.repeat(1, 1, 3) + + # Permute dimensions to match the model input format (C, H, W) + im_tensor = im.permute(2, 0, 1) + + # Resize the image + im_tensor = F.interpolate(im_tensor.unsqueeze(0), size=size, mode="bilinear").squeeze(0) + + # Normalize the image + im_tensor = normalize(im_tensor, [0.5, 0.5, 0.5], [1.0, 1.0, 1.0]) + + # Return the processed image tensor with a batch dimension and original size + return im_tensor.unsqueeze(0), im.shape[0:2] + + +def predict(model, im: torch.Tensor, device): + image, orig_size = im_preprocess(im, cache_size) + + if model.is_fp16: + image = image.type(torch.HalfTensor) + else: + image = image.type(torch.FloatTensor) + + image_v = Variable(image, requires_grad=False).to(device) + ds_val = model(image_v) # list of 6 results + + if isinstance(ds_val, tuple): + ds_val = ds_val[0] + + if isinstance(ds_val, list): + ds_val = ds_val[0] + + if len(ds_val.shape) < 4: + ds_val = torch.unsqueeze(ds_val, 0) + + # B x 1 x H x W # we want the first one which is the most accurate prediction + pred_val = ds_val[0, :, :, :] + + # recover the prediction spatial size to the orignal image size + # pred_val = torch.squeeze(F.interpolate(pred_val, size=orig_size, mode='bilinear'), 0) + # pred_val = torch.squeeze(F.upsample(torch.unsqueeze(pred_val, 0), (orig_size[0], orig_size[1]), mode="bilinear")) + pred_val = F.interpolate(pred_val.unsqueeze(0), size=orig_size, mode="bilinear").squeeze(0) + + ma = torch.max(pred_val) + mi = torch.min(pred_val) + pred_val = (pred_val - mi) / (ma - mi) # max = 1 + + # it is the mask we need + return pred_val.detach().cpu() + + +class ISNetLoader: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model_name": (folder_paths.get_filename_list("isnet"),), + }, + } + + RETURN_TYPES = ("ISNET_MODEL",) + FUNCTION = "load_isnet" + CATEGORY = "Art Venture/Segmentation" + + def load_isnet(self, model_name): + return (load_isnet_model(model_name),) + + +class DownloadISNetModel: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model_name": (list(models.keys()),), + }, + } + + RETURN_TYPES = ("ISNET_MODEL",) + FUNCTION = "download_isnet" + CATEGORY = "Art Venture/Segmentation" + + def download_isnet(self, model_name): + if model_name not in folder_paths.get_filename_list("isnet"): + model_info = models[model_name] + download_file( + model_info["url"], + os.path.join(model_dir, model_name), + model_info["sha"], + ) + + return (load_isnet_model(model_name),) + + +class ISNetSegment: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "images": ("IMAGE",), + "threshold": ("FLOAT", {"default": 0.5, "min": 0, "max": 1, "step": 0.001}), + }, + "optional": { + "device_mode": (["AUTO", "Prefer GPU", "CPU"],), + "enabled": ("BOOLEAN", {"default": True}), + "isnet_model": ("ISNET_MODEL",), + }, + } + + RETURN_TYPES = ("IMAGE", "MASK") + RETURN_NAMES = ("segmented", "mask") + CATEGORY = "Art Venture/Segmentation" + FUNCTION = "segment_isnet" + + def segment_isnet(self, images: torch.Tensor, threshold, device_mode="AUTO", enabled=True, isnet_model=None): + if not enabled: + masks = torch.zeros((len(images), 64, 64), dtype=torch.float32) + return (images, masks) + + if isnet_model is None: + downloader = DownloadISNetModel() + isnet_model = downloader.download_isnet("isnet-general-use.pth")[0] + + device = gpu if device_mode != "CPU" else cpu + isnet_model = isnet_model.to(device) + + try: + segments = [] + masks = [] + for image in images: + mask = predict(isnet_model, image, device) + mask_im = tensor2pil(mask.permute(1, 2, 0)) + cropped = Image.new("RGBA", mask_im.size, (0, 0, 0, 0)) + cropped.paste(tensor2pil(image), mask=mask_im) + + masks.append(mask) + segments.append(pil2tensor(cropped)) + + return (torch.cat(segments, dim=0), torch.stack(masks)) + finally: + if device_mode == "AUTO": + isnet_model = isnet_model.to(cpu) diff --git a/comfyui-art-venture/modules/llm/__init__.py b/comfyui-art-venture/modules/llm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6bcdc997fa310249495f05dbc8a7546057b28301 --- /dev/null +++ b/comfyui-art-venture/modules/llm/__init__.py @@ -0,0 +1,3 @@ +from .chat import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS + +__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"] diff --git a/comfyui-art-venture/modules/llm/__pycache__/__init__.cpython-310.pyc b/comfyui-art-venture/modules/llm/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f670bec75de9d9d901251588964c78c61db702c7 Binary files /dev/null and b/comfyui-art-venture/modules/llm/__pycache__/__init__.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/llm/__pycache__/chat.cpython-310.pyc b/comfyui-art-venture/modules/llm/__pycache__/chat.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f61e58582a60e436ff2467ac88d2e9116296bba Binary files /dev/null and b/comfyui-art-venture/modules/llm/__pycache__/chat.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/llm/chat.py b/comfyui-art-venture/modules/llm/chat.py new file mode 100644 index 0000000000000000000000000000000000000000..9b87ba790633a7949ac8d755ae6e4103cd4757a6 --- /dev/null +++ b/comfyui-art-venture/modules/llm/chat.py @@ -0,0 +1,607 @@ +import os +import json +import requests +from enum import Enum +from torch import Tensor +from pydantic import BaseModel +from typing import List, Dict, Union, Optional, Any + +from ..utils import ensure_package, tensor2pil, pil2base64 + + +gpt_vision_models = [ + "gpt-4o", + "gpt-4o-mini", + "gpt-4.1", + "gpt-4.1-mini", + "gpt-4.1-nano", + "gpt-4-turbo", + "gpt-4-turbo-preview", + "gpt-4-vision-preview", + "o1", + "o1-mini", + "o1-preview", + "o1-pro", + "o3", + "o3-mini", + "o3-pro", + "o4-mini", +] + +gpt_models = [ + *gpt_vision_models, + "gpt-4", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", +] + + +claude3_models = [ + "claude-sonnet-4-20250514", + "claude-opus-4-20250514", + "claude-3-7-sonnet-latest", + "claude-3-7-sonnet-20250219", + "claude-3-5-sonnet-latest", + "claude-3-5-sonnet-20241022", + "claude-3-5-haiku-20241022", + "claude-3-opus-latest", + "claude-3-opus-20240229", + "claude-3-sonnet-20240229", + "claude-3-haiku-20240307", +] +claude2_models = ["claude-2.1"] + +aws_regions = [ + "us-east-1", + "us-west-2", + "ap-southeast-1", + "ap-southeast-2", + "ap-northeast-1", + "eu-central-1", + "eu-west-3", + "eu-west-1", + "ap-south-3", +] + +bedrock_anthropic_versions = ["bedrock-2023-05-31"] + +bedrock_claude3_models = [ + "anthropic.claude-opus-4-20250514-v1:0", + "anthropic.claude-sonnet-4-20250514-v1:0", + "anthropic.claude-3-7-sonnet-20250219-v1:0", + "anthropic.claude-3-5-sonnet-20241022-v2:0", + "anthropic.claude-3-5-haiku-20241022-v1:0", + "anthropic.claude-3-haiku-20240307-v1:0", + "anthropic.claude-3-sonnet-20240229-v1:0", + "anthropic.claude-3-opus-20240229-v1:0", +] + +bedrock_claude2_models = [ + "anthropic.claude-v2", + "anthropic.claude-v2.1", +] + +bedrock_mistral_models = [ + "mistral.mistral-7b-instruct-v0:2", + "mistral.mixtral-8x7b-instruct-v0:1", + "mistral.mistral-large-2402-v1:0", +] + +default_system_prompt = "You are a useful AI agent." + + +class LLMConfig(BaseModel): + model: str + max_token: int + temperature: float + + +class LLMMessageRole(str, Enum): + system = "system" + user = "user" + assistant = "assistant" + + +class LLMMessage(BaseModel): + role: LLMMessageRole = LLMMessageRole.user + text: str + images: Optional[List[str]] = None # list of base64 encoded images + + def to_openai_message(self): + content = [{"type": "text", "text": self.text}] + + if self.images: + for img in self.images: + content.append({"type": "image_url", "image_url": {"url": f"data:image/png;base64,{img}"}}) + + return { + "role": self.role, + "content": content, + } + + def to_claude_message(self): + content = [{"type": "text", "text": self.text}] + + if self.images: + for img in reversed(self.images): + content.append( + { + "type": "image", + "source": {"type": "base64", "media_type": "image/png", "data": img}, + } + ) + + return { + "role": self.role, + "content": content, + } + + +class OpenAIApi(BaseModel): + api_key: str + endpoint: Optional[str] = "https://api.openai.com/v1" + timeout: Optional[int] = 60 + + def chat(self, messages: List[LLMMessage], config: LLMConfig, seed=None): + if config.model not in gpt_models: + raise Exception(f"Must provide an OpenAI model, got {config.model}") + + formated_messages = [m.to_openai_message() for m in messages] + + url = f"{self.endpoint}/chat/completions" + data = { + "messages": formated_messages, + "model": config.model, + "max_tokens": config.max_token, + "temperature": config.temperature, + # "seed": seed, + } + headers = {"Authorization": f"Bearer {self.api_key}"} + + response = requests.post(url, json=data, headers=headers, timeout=self.timeout) + data: Dict = response.json() + + if data.get("error", None) is not None: + raise Exception(data.get("error").get("message")) + + return data["choices"][0]["message"]["content"] + + def complete(self, prompt: str, config: LLMConfig, seed=None): + messages = [LLMMessage(role=LLMMessageRole.user, text=prompt)] + + return self.chat(messages, config, seed) + + +class ClaudeApi(BaseModel): + api_key: str + endpoint: Optional[str] = "https://api.anthropic.com/v1" + version: Optional[str] = "2023-06-01" + timeout: Optional[int] = 60 + + def chat(self, messages: List[LLMMessage], config: LLMConfig, seed=None): + if config.model not in claude3_models: + raise Exception(f"Must provide a Claude v3 model, got {config.model}") + + system_message = [m for m in messages if m.role == "system"] + user_messages = [m for m in messages if m.role != "system"] + formated_messages = [m.to_claude_message() for m in user_messages] + + url = f"{self.endpoint}/messages" + data = { + "messages": formated_messages, + "model": config.model, + "max_tokens": config.max_token, + "temperature": config.temperature, + "system": system_message[0].text if len(system_message) > 0 else None, + } + headers = {"x-api-key": self.api_key, "anthropic-version": self.version} + + response = requests.post(url, json=data, headers=headers, timeout=self.timeout) + data: Dict = response.json() + + if data.get("error", None) is not None: + raise Exception(data.get("error").get("message")) + + return data["content"][0]["text"] + + def complete(self, prompt: str, config: LLMConfig, seed=None): + if config.model not in claude2_models: + raise Exception(f"Must provide a Claude v2 model, got {config.model}") + + prompt = f"\n\nHuman: {prompt}\n\nAssistant:" + url = f"{self.endpoint}/complete" + data = { + "prompt": prompt, + "max_tokens_to_sample": config.max_token, + "temperature": config.temperature, + } + headers = {"x-api-key": self.api_key, "anthropic-version": self.version} + + response = requests.post(url, json=data, headers=headers, timeout=self.timeout) + data: Dict = response.json() + + if data.get("error", None) is not None: + raise Exception(data.get("error").get("message")) + + return data["completion"] + + +class AwsBedrockMistralApi(BaseModel): + aws_access_key_id: str + aws_secret_access_key: str + aws_session_token: Optional[str] = None + region: Optional[str] = aws_regions[0] + timeout: Optional[int] = 60 + bedrock_runtime: Any = None + + def __init__(self, **data): + super().__init__(**data) + + ensure_package("boto3", required_version=">=1.34.101") + import boto3 + + self.bedrock_runtime = boto3.client( + service_name="bedrock-runtime", + aws_access_key_id=self.aws_access_key_id, + aws_secret_access_key=self.aws_secret_access_key, + aws_session_token=self.aws_session_token, + region_name=self.region, + ) + + def chat(self, messages: List[LLMMessage], config: LLMConfig, seed=None): + raise Exception("Mistral doesn't support chat API") + + def complete(self, prompt: str, config: LLMConfig, seed=None): + if config.model not in bedrock_mistral_models: + raise Exception(f"Must provide a Mistral model, got {config.model}") + + prompt = f"[INST]{prompt}[/INST]" + data = { + "prompt": prompt, + "max_tokens": config.max_token, + "temperature": config.temperature, + } + + response = self.bedrock_runtime.invoke_model(body=json.dumps(data), modelId=config.model) + data: Dict = json.loads(response.get("body").read()) + + if data.get("error", None) is not None: + raise Exception(data.get("error").get("message")) + + return data["outputs"][0]["text"] + + +class AwsBedrockClaudeApi(BaseModel): + aws_access_key_id: str + aws_secret_access_key: str + aws_session_token: Optional[str] = None + region: Optional[str] = aws_regions[0] + version: Optional[str] = bedrock_anthropic_versions[0] + timeout: Optional[int] = 60 + bedrock_runtime: Any = None + + def __init__(self, **data): + super().__init__(**data) + + ensure_package("boto3", required_version=">=1.34.101") + import boto3 + + self.bedrock_runtime = boto3.client( + service_name="bedrock-runtime", + aws_access_key_id=self.aws_access_key_id, + aws_secret_access_key=self.aws_secret_access_key, + aws_session_token=self.aws_session_token, + region_name=self.region, + ) + + def chat(self, messages: List[LLMMessage], config: LLMConfig, seed=None): + if config.model not in bedrock_claude3_models: + raise Exception(f"Must provide a Claude v3 model, got {config.model}") + + system_message = [m for m in messages if m.role == "system"] + user_messages = [m for m in messages if m.role != "system"] + formated_messages = [m.to_claude_message() for m in user_messages] + + data = { + "anthropic_version": self.version, + "messages": formated_messages, + "max_tokens": config.max_token, + "temperature": config.temperature, + "system": system_message[0].text if len(system_message) > 0 else None, + } + + response = self.bedrock_runtime.invoke_model(body=json.dumps(data), modelId=config.model) + data: Dict = json.loads(response.get("body").read()) + + if data.get("error", None) is not None: + raise Exception(data.get("error").get("message")) + + return data["content"][0]["text"] + + def complete(self, prompt: str, config: LLMConfig, seed=None): + if config.model not in bedrock_claude2_models: + raise Exception(f"Must provide a Claude v2 model, got {config.model}") + + prompt = f"\n\nHuman: {prompt}\n\nAssistant:" + data = { + "prompt": prompt, + "max_tokens_to_sample": config.max_token, + "temperature": config.temperature, + } + + response = self.bedrock_runtime.invoke_model(body=json.dumps(data), modelId=config.model) + data: Dict = json.loads(response.get("body").read()) + + if data.get("error", None) is not None: + raise Exception(data.get("error").get("message")) + + return data["completion"] + + +LLMApi = Union[OpenAIApi, ClaudeApi] + + +class OpenAIApiNode: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "openai_api_key": ("STRING", {"multiline": False}), + "endpoint": ("STRING", {"multiline": False, "default": "https://api.openai.com/v1"}), + }, + } + + RETURN_TYPES = ("LLM_API",) + FUNCTION = "create_api" + CATEGORY = "ArtVenture/LLM" + + def create_api(self, openai_api_key, endpoint): + if not openai_api_key or openai_api_key == "": + openai_api_key = os.environ.get("OPENAI_API_KEY") + if not openai_api_key: + raise Exception("OpenAI API key is required.") + + return (OpenAIApi(api_key=openai_api_key, endpoint=endpoint),) + + +class ClaudeApiNode: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "claude_api_key": ("STRING", {"multiline": False}), + "endpoint": ("STRING", {"multiline": False, "default": "https://api.anthropic.com/v1"}), + "version": (["2023-06-01"], {"default": "2023-06-01"}), + }, + } + + RETURN_TYPES = ("LLM_API",) + RETURN_NAMES = ("llm_api",) + FUNCTION = "create_api" + CATEGORY = "ArtVenture/LLM" + + def create_api(self, claude_api_key, endpoint, version): + if not claude_api_key or claude_api_key == "": + claude_api_key = os.environ.get("ANTHROPIC_API_KEY", os.environ.get("CLAUDE_API_KEY")) + if not claude_api_key: + raise Exception("Anthropic API key is required.") + + return (ClaudeApi(api_key=claude_api_key, endpoint=endpoint, version=version),) + + +class AwsBedrockMistralApiNode: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "aws_access_key_id": ("STRING", {"multiline": False}), + "aws_secret_access_key": ("STRING", {"multiline": False}), + "aws_session_token": ("STRING", {"multiline": False}), + "region": (aws_regions, {"default": aws_regions[0]}), + }, + } + + RETURN_TYPES = ("LLM_API",) + RETURN_NAMES = ("llm_api",) + FUNCTION = "create_api" + CATEGORY = "ArtVenture/LLM" + + def create_api(self, aws_access_key_id, aws_secret_access_key, aws_session_token, region): + if not aws_access_key_id or aws_access_key_id == "": + aws_access_key_id = os.environ.get("AWS_ACCESS_KEY_ID", None) + if not aws_secret_access_key or aws_secret_access_key == "": + aws_secret_access_key = os.environ.get("AWS_SECRET_ACCESS_KEY", None) + if not aws_session_token or aws_session_token == "": + aws_session_token = os.environ.get("AWS_SESSION_TOKEN", None) + + if not aws_access_key_id or not aws_secret_access_key: + raise Exception("AWS credentials is required.") + + return ( + AwsBedrockMistralApi( + aws_access_key_id=aws_access_key_id, + aws_secret_access_key=aws_secret_access_key, + aws_session_token=aws_session_token, + region=region, + ), + ) + + +class AwsBedrockClaudeApiNode: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "aws_access_key_id": ("STRING", {"multiline": False}), + "aws_secret_access_key": ("STRING", {"multiline": False}), + "aws_session_token": ("STRING", {"multiline": False}), + "region": (aws_regions, {"default": aws_regions[0]}), + "version": (bedrock_anthropic_versions, {"default": bedrock_anthropic_versions[0]}), + }, + } + + RETURN_TYPES = ("LLM_API",) + RETURN_NAMES = ("llm_api",) + FUNCTION = "create_api" + CATEGORY = "ArtVenture/LLM" + + def create_api(self, aws_access_key_id, aws_secret_access_key, aws_session_token, region, version): + if not aws_access_key_id or aws_access_key_id == "": + aws_access_key_id = os.environ.get("AWS_ACCESS_KEY_ID", None) + if not aws_secret_access_key or aws_secret_access_key == "": + aws_secret_access_key = os.environ.get("AWS_SECRET_ACCESS_KEY", None) + if not aws_session_token or aws_session_token == "": + aws_session_token = os.environ.get("AWS_SESSION_TOKEN", None) + + if not aws_access_key_id or not aws_secret_access_key: + raise Exception("AWS credentials is required.") + + return ( + AwsBedrockClaudeApi( + aws_access_key_id=aws_access_key_id, + aws_secret_access_key=aws_secret_access_key, + aws_session_token=aws_session_token, + region=region, + version=version, + ), + ) + + +class LLMApiConfigNode: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "model": ( + gpt_models + + claude3_models + + claude2_models + + bedrock_claude3_models + + bedrock_claude2_models + + bedrock_mistral_models, + {"default": gpt_vision_models[0]}, + ), + "max_token": ("INT", {"default": 1024}), + "temperature": ("FLOAT", {"default": 0, "min": 0, "max": 1.0, "step": 0.001}), + } + } + + RETURN_TYPES = ("LLM_CONFIG",) + RETURN_NAMES = ("llm_config",) + FUNCTION = "make_config" + CATEGORY = "ArtVenture/LLM" + + def make_config(self, max_token, model, temperature): + return (LLMConfig(model=model, max_token=max_token, temperature=temperature),) + + +class LLMMessageNode: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "role": (["system", "user", "assistant"],), + "text": ("STRING", {"multiline": True}), + }, + "optional": {"image": ("IMAGE",), "messages": ("LLM_MESSAGE",)}, + } + + RETURN_TYPES = ("LLM_MESSAGE",) + RETURN_NAMES = ("messages",) + FUNCTION = "make_message" + CATEGORY = "ArtVenture/LLM" + + def make_message(self, role, text, image: Optional[Tensor] = None, messages: Optional[List[LLMMessage]] = None): + messages = [] if messages is None else messages.copy() + + if role == "system": + if isinstance(image, Tensor): + raise Exception("System prompt does not support image.") + + system_message = [m for m in messages if m.role == "system"] + if len(system_message) > 0: + raise Exception("Only one system prompt is allowed.") + + if isinstance(image, Tensor): + if len(image.shape) == 4: # Batch of images + images = [] + for i in range(image.shape[0]): + pil = tensor2pil(image[i]) + content = pil2base64(pil) + images.append(content) + messages.append(LLMMessage(role=role, text=text, images=images)) + else: # Single image + pil = tensor2pil(image) + content = pil2base64(pil) + messages.append(LLMMessage(role=role, text=text, images=[content])) + else: + messages.append(LLMMessage(role=role, text=text)) + + return (messages,) + + +class LLMChatNode: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "messages": ("LLM_MESSAGE",), + "api": ("LLM_API",), + "config": ("LLM_CONFIG",), + "seed": ("INT", {"default": 0, "min": 0, "max": 0x1FFFFFFFFFFFFF}), + }, + } + + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("response",) + FUNCTION = "chat" + CATEGORY = "ArtVenture/LLM" + + def chat(self, messages: List[LLMMessage], api: LLMApi, config: LLMConfig, seed): + response = api.chat(messages, config, seed) + return (response,) + + +class LLMCompletionNode: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "prompt": ("STRING", {"multiline": True, "dynamicPrompts": False}), + "api": ("LLM_API",), + "config": ("LLM_CONFIG",), + "seed": ("INT", {"default": 0, "min": 0, "max": 0x1FFFFFFFFFFFFF}), + }, + } + + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("response",) + FUNCTION = "chat" + CATEGORY = "ArtVenture/LLM" + + def chat(self, prompt: str, api: LLMApi, config: LLMConfig, seed): + response = api.complete(prompt, config, seed) + return (response,) + + +NODE_CLASS_MAPPINGS = { + "AV_OpenAIApi": OpenAIApiNode, + "AV_ClaudeApi": ClaudeApiNode, + "AV_AwsBedrockClaudeApi": AwsBedrockClaudeApiNode, + "AV_AwsBedrockMistralApi": AwsBedrockMistralApiNode, + "AV_LLMApiConfig": LLMApiConfigNode, + "AV_LLMMessage": LLMMessageNode, + "AV_LLMChat": LLMChatNode, + "AV_LLMCompletion": LLMCompletionNode, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "AV_OpenAIApi": "OpenAI API", + "AV_ClaudeApi": "Claude API", + "AV_AwsBedrockClaudeApi": "AWS Bedrock Claude API", + "AV_AwsBedrockMistralApi": "AWS Bedrock Mistral API", + "AV_LLMApiConfig": "LLM API Config", + "AV_LLMMessage": "LLM Message", + "AV_LLMChat": "LLM Chat", + "AV_LLMCompletion": "LLM Completion", +} diff --git a/comfyui-art-venture/modules/logger.py b/comfyui-art-venture/modules/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..9983e14b8e6967506ba653af8253df4b86ee53dd --- /dev/null +++ b/comfyui-art-venture/modules/logger.py @@ -0,0 +1,36 @@ +import sys +import copy +import logging + + +class ColoredFormatter(logging.Formatter): + COLORS = { + "DEBUG": "\033[0;36m", # CYAN + "INFO": "\033[0;32m", # GREEN + "WARNING": "\033[0;33m", # YELLOW + "ERROR": "\033[0;31m", # RED + "CRITICAL": "\033[0;37;41m", # WHITE ON RED + "RESET": "\033[0m", # RESET COLOR + } + + def format(self, record): + colored_record = copy.copy(record) + levelname = colored_record.levelname + seq = self.COLORS.get(levelname, self.COLORS["RESET"]) + colored_record.levelname = f"{seq}{levelname}{self.COLORS['RESET']}" + return super().format(colored_record) + + +# Create a new logger +logger = logging.getLogger("ArtVenture") +logger.propagate = False + +# Add handler if we don't have one. +if not logger.handlers: + handler = logging.StreamHandler(sys.stdout) + handler.setFormatter(ColoredFormatter("[%(name)s] - %(levelname)s - %(message)s")) + logger.addHandler(handler) + +# Configure logger +loglevel = logging.INFO +logger.setLevel(loglevel) diff --git a/comfyui-art-venture/modules/masking.py b/comfyui-art-venture/modules/masking.py new file mode 100644 index 0000000000000000000000000000000000000000..1d723a8dbb2c6d3cdebe37990a57d1064c34c86e --- /dev/null +++ b/comfyui-art-venture/modules/masking.py @@ -0,0 +1,100 @@ +import numpy as np +from PIL import Image, ImageFilter, ImageOps + + +def get_crop_region(mask: np.ndarray, pad=0): + """finds a rectangular region that contains all masked ares in an image. Returns (x1, y1, x2, y2) coordinates of the rectangle. + For example, if a user has painted the top-right part of a 512x512 image", the result may be (256, 0, 512, 256)""" + + h, w = mask.shape + + crop_left = 0 + for i in range(w): + if not (mask[:, i] == 0).all(): + break + crop_left += 1 + + crop_right = 0 + for i in reversed(range(w)): + if not (mask[:, i] == 0).all(): + break + crop_right += 1 + + crop_top = 0 + for i in range(h): + if not (mask[i] == 0).all(): + break + crop_top += 1 + + crop_bottom = 0 + for i in reversed(range(h)): + if not (mask[i] == 0).all(): + break + crop_bottom += 1 + + return ( + int(max(crop_left - pad, 0)), + int(max(crop_top - pad, 0)), + int(min(w - crop_right + pad, w)), + int(min(h - crop_bottom + pad, h)), + ) + + +def expand_crop_region(crop_region: np.ndarray, processing_width, processing_height, image_width, image_height): + """expands crop region get_crop_region() to match the ratio of the image the region will processed in; returns expanded region + for example, if user drew mask in a 128x32 region, and the dimensions for processing are 512x512, the region will be expanded to 128x128. + """ + + x1, y1, x2, y2 = crop_region + + ratio_crop_region = (x2 - x1) / (y2 - y1) + ratio_processing = processing_width / processing_height + + if ratio_crop_region > ratio_processing: + desired_height = (x2 - x1) / ratio_processing + desired_height_diff = int(desired_height - (y2 - y1)) + y1 -= desired_height_diff // 2 + y2 += desired_height_diff - desired_height_diff // 2 + if y2 >= image_height: + diff = y2 - image_height + y2 -= diff + y1 -= diff + if y1 < 0: + y2 -= y1 + y1 -= y1 + if y2 >= image_height: + y2 = image_height + else: + desired_width = (y2 - y1) * ratio_processing + desired_width_diff = int(desired_width - (x2 - x1)) + x1 -= desired_width_diff // 2 + x2 += desired_width_diff - desired_width_diff // 2 + if x2 >= image_width: + diff = x2 - image_width + x2 -= diff + x1 -= diff + if x1 < 0: + x2 -= x1 + x1 -= x1 + if x2 >= image_width: + x2 = image_width + + return x1, y1, x2, y2 + + +def fill(image, mask): + """fills masked regions with colors from image using blur. Not extremely effective.""" + + image_mod = Image.new("RGBA", (image.width, image.height)) + + image_masked = Image.new("RGBa", (image.width, image.height)) + image_masked.paste(image.convert("RGBA").convert("RGBa"), mask=ImageOps.invert(mask.convert("L"))) + + image_masked = image_masked.convert("RGBa") + + for radius, repeats in [(256, 1), (64, 1), (16, 2), (4, 4), (2, 2), (0, 1)]: + blurred = image_masked.filter(ImageFilter.GaussianBlur(radius)).convert("RGBA") + for _ in range(repeats): + image_mod.alpha_composite(blurred) + + return image_mod.convert("RGB") diff --git a/comfyui-art-venture/modules/model_utils.py b/comfyui-art-venture/modules/model_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c4eaee40da137361790d06a33c21c2bbe8d79e5f --- /dev/null +++ b/comfyui-art-venture/modules/model_utils.py @@ -0,0 +1,152 @@ +import os +import re +import torch +import hashlib +import urllib.request +import urllib.error +from tqdm import tqdm +from urllib.parse import urlparse +from typing import Dict, Optional + + +def natural_sort_key(s, regex=re.compile("([0-9]+)")): + return [int(text) if text.isdigit() else text.lower() for text in regex.split(s)] + + +def walk_files(path, allowed_extensions=None): + if not os.path.exists(path): + return + + if allowed_extensions is not None: + allowed_extensions = set(allowed_extensions) + + items = list(os.walk(path, followlinks=True)) + items = sorted(items, key=lambda x: natural_sort_key(x[0])) + + for root, _, files in items: + for filename in sorted(files, key=natural_sort_key): + if allowed_extensions is not None: + _, ext = os.path.splitext(filename) + if ext not in allowed_extensions: + continue + + # Skip hidden files + if "/." in root or "\\." in root: + continue + + yield os.path.join(root, filename) + + +def load_file_from_url( + url: str, + *, + model_dir: str, + progress: bool = True, + file_name: str | None = None, +) -> str: + """Download a file from `url` into `model_dir`, using the file present if possible. + + Returns the path to the downloaded file. + """ + os.makedirs(model_dir, exist_ok=True) + if not file_name: + parts = urlparse(url) + file_name = os.path.basename(parts.path) + cached_file = os.path.abspath(os.path.join(model_dir, file_name)) + if not os.path.exists(cached_file): + print(f'Downloading: "{url}" to {cached_file}\n') + from torch.hub import download_url_to_file + + download_url_to_file(url, cached_file, progress=progress) + return cached_file + + +def calculate_sha(file: str, force=False) -> Optional[str]: + sha_file = f"{file}.sha" + + # Check if the .sha file exists + if not force and os.path.exists(sha_file): + try: + with open(sha_file, "r") as f: + stored_hash = f.read().strip() + if stored_hash: + return stored_hash + except IOError as e: + print(f"Failed to read hash: {e}") + + # Calculate the hash if the .sha file doesn't exist or is empty + try: + with open(file, "rb") as fp: + file_hash = hashlib.sha256() + while chunk := fp.read(8192): + file_hash.update(chunk) + calculated_hash = file_hash.hexdigest() + + # Write the calculated hash to the .sha file + try: + with open(sha_file, "w") as f: + f.write(calculated_hash) + except IOError as e: + print(f"Failed to write hash to {sha_file}: {e}") + + return calculated_hash + except IOError as e: + print(f"Failed to read file {file}: {e}") + return None + + +def download_file(url: str, dst: str, sha256sum: Optional[str] = None) -> Dict[str, Optional[str]]: + """ + Downloads a file from a URL to a destination path, optionally verifying its SHA-256 checksum. + + :param url: URL of the file to download + :param dst: Destination path to save the downloaded file + :param sha256sum: Optional SHA-256 checksum to verify the downloaded file + :return: Dictionary with file path, download status, calculated checksum, and checksum match status + """ + # Ensure the directory exists + os.makedirs(os.path.dirname(dst), exist_ok=True) + + file_exists = os.path.isfile(dst) + file_checksum = None + checksum_match = None + downloaded = False + + try: + if file_exists: + file_checksum = calculate_sha(dst) + if sha256sum: + checksum_match = file_checksum == sha256sum + if not checksum_match: + os.remove(dst) + + if not file_exists or checksum_match == False: + with tqdm(unit="B", unit_scale=True, unit_divisor=1024, miniters=1, desc=dst.split("/")[-1]) as t: + + def reporthook(blocknum, blocksize, totalsize): + if t.total is None and totalsize > 0: + t.total = totalsize + read_so_far = blocknum * blocksize + t.update(max(0, read_so_far - t.n)) + + urllib.request.urlretrieve(url, dst, reporthook=reporthook) + downloaded = True + + file_checksum = calculate_sha(dst, force=True) + if sha256sum: + checksum_match = file_checksum == sha256sum + + except urllib.error.URLError as ex: + print("Download failed:", ex) + if os.path.isfile(dst): + os.remove(dst) + except Exception as ex: + print("An error occurred:", ex) + finally: + return {"file": dst, "downloaded": downloaded, "sha": file_checksum, "match": checksum_match} + + +def load_jit_torch_file(model_path: str): + model = torch.jit.load(model_path, map_location="cpu") + model.eval() + return model diff --git a/comfyui-art-venture/modules/nodes.py b/comfyui-art-venture/modules/nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..b831d076ea99236eec8c9bc25ffaec1e134a4e91 --- /dev/null +++ b/comfyui-art-venture/modules/nodes.py @@ -0,0 +1,507 @@ +import json +import torch +from typing import Dict + +import folder_paths +import comfy.sd +from nodes import LoraLoader, VAELoader +from comfy_extras.nodes_model_merging import CheckpointSave + +from .logger import logger + +from .utility_nodes import ( + NODE_CLASS_MAPPINGS as UTIL_NODE_CLASS_MAPPINGS, + NODE_DISPLAY_NAME_MAPPINGS as UTIL_NODE_DISPLAY_NAME_MAPPINGS, +) +from .sdxl_prompt_styler import ( + NODE_CLASS_MAPPINGS as SDXL_STYLER_NODE_CLASS_MAPPINGS, + NODE_DISPLAY_NAME_MAPPINGS as SDXL_STYLER_NODE_DISPLAY_NAME_MAPPINGS, +) +from .interrogate import ( + NODE_CLASS_MAPPINGS as INTERROGATE_NODE_CLASS_MAPPINGS, + NODE_DISPLAY_NAME_MAPPINGS as INTERROGATE_NODE_DISPLAY_NAME_MAPPINGS, +) +from .fooocus import ( + NODE_CLASS_MAPPINGS as FOOOCUS_NODE_CLASS_MAPPINGS, + NODE_DISPLAY_NAME_MAPPINGS as FOOOCUS_NODE_DISPLAY_NAME_MAPPINGS, +) +from .postprocessing import ( + NODE_CLASS_MAPPINGS as PP_NODE_CLASS_MAPPINGS, + NODE_DISPLAY_NAME_MAPPINGS as PP_NODE_DISPLAY_NAME_MAPPINGS, +) +from .controlnet import ( + NODE_CLASS_MAPPINGS as CONTROLNET_NODE_CLASS_MAPPINGS, + NODE_DISPLAY_NAME_MAPPINGS as CONTROLNET_NODE_DISPLAY_NAME_MAPPINGS, +) +from .animatediff import ( + NODE_CLASS_MAPPINGS as ANIMATEDIFF_NODE_CLASS_MAPPINGS, + NODE_DISPLAY_NAME_MAPPINGS as ANIMATEDIFF_NODE_DISPLAY_NAME_MAPPINGS, +) +from .ip_adapter_nodes import ( + NODE_CLASS_MAPPINGS as IP_ADAPTER_NODE_CLASS_MAPPINGS, + NODE_DISPLAY_NAME_MAPPINGS as IP_ADAPTER_NODE_DISPLAY_NAME_MAPPINGS, +) +from .isnet import ( + NODE_CLASS_MAPPINGS as ISNET_NODE_CLASS_MAPPINGS, + NODE_DISPLAY_NAME_MAPPINGS as ISNET_NODE_DISPLAY_NAME_MAPPINGS, +) +from .inpaint import ( + NODE_CLASS_MAPPINGS as INPAINT_NODE_CLASS_MAPPINGS, + NODE_DISPLAY_NAME_MAPPINGS as INPAINT_NODE_DISPLAY_NAME_MAPPINGS, +) +from .video import ( + NODE_CLASS_MAPPINGS as VIDEO_NODE_CLASS_MAPPINGS, + NODE_DISPLAY_NAME_MAPPINGS as VIDEO_NODE_DISPLAY_NAME_MAPPINGS, +) +from .impact import ( + NODE_CLASS_MAPPINGS as IMPACT_NODE_CLASS_MAPPINGS, + NODE_DISPLAY_NAME_MAPPINGS as IMPACT_NODE_DISPLAY_NAME_MAPPINGS, +) +from .llm import ( + NODE_CLASS_MAPPINGS as LLM_NODE_CLASS_MAPPINGS, + NODE_DISPLAY_NAME_MAPPINGS as LLM_NODE_DISPLAY_NAME_MAPPINGS, +) + + +class AVVAELoader(VAELoader): + @classmethod + def INPUT_TYPES(s): + inputs = VAELoader.INPUT_TYPES() + inputs["optional"] = {"vae_override": ("STRING", {"default": "None"})} + return inputs + + CATEGORY = "Art Venture/Loaders" + + def load_vae(self, vae_name, vae_override="None"): + if vae_override != "None": + if vae_override not in folder_paths.get_filename_list("vae"): + print(f"Warning: Not found VAE model {vae_override}. Use {vae_name} instead.") + else: + vae_name = vae_override + + return super().load_vae(vae_name) + + +class AVLoraLoader(LoraLoader): + @classmethod + def INPUT_TYPES(s): + inputs = LoraLoader.INPUT_TYPES() + inputs["optional"] = { + "lora_override": ("STRING", {"default": "None"}), + "enabled": ("BOOLEAN", {"default": True}), + } + return inputs + + CATEGORY = "Art Venture/Loaders" + + def load_lora(self, model, clip, lora_name, *args, lora_override="None", enabled=True, **kwargs): + if not enabled: + return (model, clip) + + if lora_override != "None": + if lora_override not in folder_paths.get_filename_list("loras"): + print(f"Warning: Not found Lora model {lora_override}. Use {lora_name} instead.") + else: + lora_name = lora_override + + return super().load_lora(model, clip, lora_name, *args, **kwargs) + + +class AVLoraListStacker: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "data": ("STRING", {"default": "", "multiline": True, "dynamicPrompts": False}), + }, + "optional": {"lora_stack": ("LORA_STACK",)}, + } + + RETURN_TYPES = ("LORA_STACK",) + FUNCTION = "load_list_lora" + CATEGORY = "Art Venture/Loaders" + + def parse_lora_list(self, data: str): + # data is a list of lora model (lora_name, strength_model, strength_clip, url) in json format + # trim data + data = data.strip() + if data == "" or data == "[]" or data is None: + return [] + + print(f"Loading lora list: {data}") + + lora_list = json.loads(data) + if len(lora_list) == 0: + return [] + + available_loras = folder_paths.get_filename_list("loras") + + lora_params = [] + for lora in lora_list: + lora_name = lora["name"] + strength_model = lora["strength"] + strength_clip = lora["strength"] + + if strength_model == 0 and strength_clip == 0: + continue + + if lora_name not in available_loras: + print(f"Not found lora {lora_name}, skipping") + continue + + lora_params.append((lora_name, strength_model, strength_clip)) + + return lora_params + + def load_list_lora(self, data, lora_stack=None): + loras = self.parse_lora_list(data) + + if lora_stack is not None: + loras.extend([l for l in lora_stack if l[0] != "None"]) + + return (loras,) + + +class AVLoraListLoader(AVLoraListStacker): + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model": ("MODEL",), + "clip": ("CLIP",), + "data": ("STRING", {"default": "", "multiline": True, "dynamicPrompts": False}), + } + } + + RETURN_TYPES = ("MODEL", "CLIP") + + def load_list_lora(self, model, clip, data): + lora_params = self.parse_lora_list(data) + + if len(lora_params) == 0: + return (model, clip) + + def load_loras(lora_params, model, clip): + for lora_name, strength_model, strength_clip in lora_params: + lora_path = folder_paths.get_full_path("loras", lora_name) + lora_file = comfy.utils.load_torch_file(lora_path) + model, clip = comfy.sd.load_lora_for_models(model, clip, lora_file, strength_model, strength_clip) + return model, clip + + lora_model, lora_clip = load_loras(lora_params, model, clip) + + return (lora_model, lora_clip) + + +class AVCheckpointModelsToParametersPipe: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "ckpt_name": (folder_paths.get_filename_list("checkpoints"),), + }, + "optional": { + "pipe": ("PIPE",), + "secondary_ckpt_name": (["None"] + folder_paths.get_filename_list("checkpoints"),), + "vae_name": (["None"] + folder_paths.get_filename_list("vae"),), + "upscaler_name": (["None"] + folder_paths.get_filename_list("upscale_models"),), + "secondary_upscaler_name": (["None"] + folder_paths.get_filename_list("upscale_models"),), + "lora_1_name": (["None"] + folder_paths.get_filename_list("loras"),), + "lora_2_name": (["None"] + folder_paths.get_filename_list("loras"),), + "lora_3_name": (["None"] + folder_paths.get_filename_list("loras"),), + }, + } + + RETURN_TYPES = ("PIPE",) + CATEGORY = "Art Venture/Parameters" + FUNCTION = "checkpoint_models_to_parameter_pipe" + + def checkpoint_models_to_parameter_pipe( + self, + ckpt_name, + pipe: Dict = {}, + secondary_ckpt_name="None", + vae_name="None", + upscaler_name="None", + secondary_upscaler_name="None", + lora_1_name="None", + lora_2_name="None", + lora_3_name="None", + ): + pipe["ckpt_name"] = ckpt_name if ckpt_name != "None" else None + pipe["secondary_ckpt_name"] = secondary_ckpt_name if secondary_ckpt_name != "None" else None + pipe["vae_name"] = vae_name if vae_name != "None" else None + pipe["upscaler_name"] = upscaler_name if upscaler_name != "None" else None + pipe["secondary_upscaler_name"] = secondary_upscaler_name if secondary_upscaler_name != "None" else None + pipe["lora_1_name"] = lora_1_name if lora_1_name != "None" else None + pipe["lora_2_name"] = lora_2_name if lora_2_name != "None" else None + pipe["lora_3_name"] = lora_3_name if lora_3_name != "None" else None + return (pipe,) + + +class AVPromptsToParametersPipe: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "positive": ("STRING", {"multiline": True, "default": "Positive"}), + "negative": ("STRING", {"multiline": True, "default": "Negative"}), + }, + "optional": { + "pipe": ("PIPE",), + "image": ("IMAGE",), + "mask": ("MASK",), + }, + } + + RETURN_TYPES = ("PIPE",) + CATEGORY = "Art Venture/Parameters" + FUNCTION = "prompt_to_parameter_pipe" + + def prompt_to_parameter_pipe(self, positive, negative, pipe: Dict = {}, image=None, mask=None): + pipe["positive"] = positive + pipe["negative"] = negative + pipe["image"] = image + pipe["mask"] = mask + return (pipe,) + + +class AVParametersPipeToCheckpointModels: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "pipe": ("PIPE",), + }, + } + + RETURN_TYPES = ( + "PIPE", + "CHECKPOINT_NAME", + "CHECKPOINT_NAME", + "VAE_NAME", + "UPSCALER_NAME", + "UPSCALER_NAME", + "LORA_NAME", + "LORA_NAME", + "LORA_NAME", + ) + RETURN_NAMES = ( + "pipe", + "ckpt_name", + "secondary_ckpt_name", + "vae_name", + "upscaler_name", + "secondary_upscaler_name", + "lora_1_name", + "lora_2_name", + "lora_3_name", + ) + CATEGORY = "Art Venture/Parameters" + FUNCTION = "parameter_pipe_to_checkpoint_models" + + def parameter_pipe_to_checkpoint_models(self, pipe: Dict = {}): + ckpt_name = pipe.get("ckpt_name", None) + secondary_ckpt_name = pipe.get("secondary_ckpt_name", None) + vae_name = pipe.get("vae_name", None) + upscaler_name = pipe.get("upscaler_name", None) + secondary_upscaler_name = pipe.get("secondary_upscaler_name", None) + lora_1_name = pipe.get("lora_1_name", None) + lora_2_name = pipe.get("lora_2_name", None) + lora_3_name = pipe.get("lora_3_name", None) + + return ( + pipe, + ckpt_name, + secondary_ckpt_name, + vae_name, + upscaler_name, + secondary_upscaler_name, + lora_1_name, + lora_2_name, + lora_3_name, + ) + + +class AVParametersPipeToPrompts: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "pipe": ("PIPE",), + }, + } + + RETURN_TYPES = ( + "PIPE", + "STRING", + "STRING", + "IMAGE", + "MASK", + ) + RETURN_NAMES = ( + "pipe", + "positive", + "negative", + "image", + "mask", + ) + CATEGORY = "Art Venture/Parameters" + FUNCTION = "parameter_pipe_to_prompt" + + def parameter_pipe_to_prompt(self, pipe: Dict = {}): + positive = pipe.get("positive", None) + negative = pipe.get("negative", None) + image = pipe.get("image", None) + mask = pipe.get("mask", None) + + return ( + pipe, + positive, + negative, + image, + mask, + ) + + +class AVCheckpointMerge: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model1": ("MODEL",), + "model2": ("MODEL",), + "model1_weight": ("FLOAT", {"default": 1.0, "min": -1.0, "max": 1.0, "step": 0.01}), + "model2_weight": ("FLOAT", {"default": 1.0, "min": -1.0, "max": 1.0, "step": 0.01}), + } + } + + RETURN_TYPES = ("MODEL",) + FUNCTION = "merge" + + CATEGORY = "Art Venture/Model Merging" + + def merge(self, model1, model2, model1_weight, model2_weight): + m = model1.clone() + k1 = model1.get_key_patches("diffusion_model.") + k2 = model2.get_key_patches("diffusion_model.") + for k in k1: + if k in k2: + a = k1[k][0] + b = k2[k][0] + + if a.shape != b.shape and a.shape[0:1] + a.shape[2:] == b.shape[0:1] + b.shape[2:]: + if a.shape[1] == 4 and b.shape[1] == 9: + raise RuntimeError( + "When merging inpainting model with a normal one, model1 must be the inpainting model." + ) + if a.shape[1] == 4 and b.shape[1] == 8: + raise RuntimeError( + "When merging instruct-pix2pix model with a normal one, model1 must be the instruct-pix2pix model." + ) + + c = torch.zeros_like(a) + c[:, 0:4, :, :] = b + b = c + + m.add_patches({k: (b,)}, model2_weight, model1_weight) + else: + logger.warn(f"Key {k} not found in model2") + m.add_patches({k: k1[k]}, -1.0, 1.0) # zero out + + return (m,) + + +class AVCheckpointSave(CheckpointSave): + CATEGORY = "Art Venture/Model Merging" + + @classmethod + def INPUT_TYPES(s): + inputs = CheckpointSave.INPUT_TYPES() + inputs["optional"] = { + "dtype": (["float16", "float32"], {"default": "float16"}), + } + + return inputs + + def save(self, *args, dtype="float16", **kwargs): + comfy_save_checkpoint = comfy.sd.save_checkpoint + + if dtype == "float16": + + def save_checkpoint(output_path, model, clip, vae, metadata=None): + model.model.half() + return comfy_save_checkpoint(output_path, model, clip, vae, metadata) + + comfy.sd.save_checkpoint = save_checkpoint + + try: + return super().save(*args, **kwargs) + finally: + comfy.sd.save_checkpoint = comfy_save_checkpoint + + +NODE_CLASS_MAPPINGS = { + "AV_CheckpointModelsToParametersPipe": AVCheckpointModelsToParametersPipe, + "AV_PromptsToParametersPipe": AVPromptsToParametersPipe, + "AV_ParametersPipeToCheckpointModels": AVParametersPipeToCheckpointModels, + "AV_ParametersPipeToPrompts": AVParametersPipeToPrompts, + "AV_VAELoader": AVVAELoader, + "AV_LoraLoader": AVLoraLoader, + "AV_LoraListLoader": AVLoraListLoader, + "AV_LoraListStacker": AVLoraListStacker, + "AV_CheckpointMerge": AVCheckpointMerge, + "AV_CheckpointSave": AVCheckpointSave, +} +NODE_DISPLAY_NAME_MAPPINGS = { + "AV_CheckpointModelsToParametersPipe": "Checkpoint Models to Pipe", + "AV_PromptsToParametersPipe": "Prompts to Pipe", + "AV_ParametersPipeToCheckpointModels": "Pipe to Checkpoint Models", + "AV_ParametersPipeToPrompts": "Pipe to Prompts", + "AV_VAELoader": "VAE Loader", + "AV_LoraLoader": "Lora Loader", + "AV_LoraListLoader": "Lora List Loader", + "AV_LoraListStacker": "Lora List Stacker", + "AV_CheckpointMerge": "Checkpoint Merge", + "AV_CheckpointSave": "Checkpoint Save", +} + + +NODE_CLASS_MAPPINGS.update(UTIL_NODE_CLASS_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(UTIL_NODE_DISPLAY_NAME_MAPPINGS) + +NODE_CLASS_MAPPINGS.update(SDXL_STYLER_NODE_CLASS_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(SDXL_STYLER_NODE_DISPLAY_NAME_MAPPINGS) + +NODE_CLASS_MAPPINGS.update(INTERROGATE_NODE_CLASS_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(INTERROGATE_NODE_DISPLAY_NAME_MAPPINGS) + +NODE_CLASS_MAPPINGS.update(FOOOCUS_NODE_CLASS_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(FOOOCUS_NODE_DISPLAY_NAME_MAPPINGS) + +NODE_CLASS_MAPPINGS.update(PP_NODE_CLASS_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(PP_NODE_DISPLAY_NAME_MAPPINGS) + +NODE_CLASS_MAPPINGS.update(CONTROLNET_NODE_CLASS_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(CONTROLNET_NODE_DISPLAY_NAME_MAPPINGS) + +NODE_CLASS_MAPPINGS.update(ANIMATEDIFF_NODE_CLASS_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(ANIMATEDIFF_NODE_DISPLAY_NAME_MAPPINGS) + +NODE_CLASS_MAPPINGS.update(IP_ADAPTER_NODE_CLASS_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(IP_ADAPTER_NODE_DISPLAY_NAME_MAPPINGS) + +NODE_CLASS_MAPPINGS.update(ISNET_NODE_CLASS_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(ISNET_NODE_DISPLAY_NAME_MAPPINGS) + +NODE_CLASS_MAPPINGS.update(INPAINT_NODE_CLASS_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(INPAINT_NODE_DISPLAY_NAME_MAPPINGS) + +NODE_CLASS_MAPPINGS.update(VIDEO_NODE_CLASS_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(VIDEO_NODE_DISPLAY_NAME_MAPPINGS) + +NODE_CLASS_MAPPINGS.update(IMPACT_NODE_CLASS_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(IMPACT_NODE_DISPLAY_NAME_MAPPINGS) + +NODE_CLASS_MAPPINGS.update(LLM_NODE_CLASS_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(LLM_NODE_DISPLAY_NAME_MAPPINGS) diff --git a/comfyui-art-venture/modules/postprocessing/__init__.py b/comfyui-art-venture/modules/postprocessing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d15984ce21ba4cb65272ab2483d9898eaae5df3b --- /dev/null +++ b/comfyui-art-venture/modules/postprocessing/__init__.py @@ -0,0 +1,12 @@ +from .color_blend import ColorBlend +from .color_correct import ColorCorrect + +NODE_CLASS_MAPPINGS = { + "ColorBlend": ColorBlend, + "ColorCorrect": ColorCorrect, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "ColorBlend": "Color Blend", + "ColorCorrect": "Color Correct", +} diff --git a/comfyui-art-venture/modules/postprocessing/__pycache__/__init__.cpython-310.pyc b/comfyui-art-venture/modules/postprocessing/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ddfe5c7f585b684fa54311240841233488df66a Binary files /dev/null and b/comfyui-art-venture/modules/postprocessing/__pycache__/__init__.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/postprocessing/__pycache__/color_blend.cpython-310.pyc b/comfyui-art-venture/modules/postprocessing/__pycache__/color_blend.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae70ddb9427db3b948d01a871d224af6f384a274 Binary files /dev/null and b/comfyui-art-venture/modules/postprocessing/__pycache__/color_blend.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/postprocessing/__pycache__/color_correct.cpython-310.pyc b/comfyui-art-venture/modules/postprocessing/__pycache__/color_correct.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af0291740955b5c7c33c16e9b07fad5ff64ad69b Binary files /dev/null and b/comfyui-art-venture/modules/postprocessing/__pycache__/color_correct.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/postprocessing/color_blend.py b/comfyui-art-venture/modules/postprocessing/color_blend.py new file mode 100644 index 0000000000000000000000000000000000000000..38d800841e96f0f2b5e4d7e0b3bfd86285a29762 --- /dev/null +++ b/comfyui-art-venture/modules/postprocessing/color_blend.py @@ -0,0 +1,77 @@ +# Adapt from https://github.com/Stability-AI/stability-ComfyUI-nodes/blob/master/color_blend.py + +# Color blend node by Yam Levi +# Property of Stability AI +import cv2 +import torch +import numpy as np + +import comfy.utils + + +def color_blend(bw_layer, color_layer): + # Convert the color layer to LAB color space + color_lab = cv2.cvtColor(color_layer, cv2.COLOR_BGR2Lab) + # Convert the black and white layer to grayscale + bw_layer_gray = cv2.cvtColor(bw_layer, cv2.COLOR_BGR2GRAY) + # Replace the luminosity (L) channel in the color image with the black and white luminosity + _, color_a, color_b = cv2.split(color_lab) + blended_lab = cv2.merge((bw_layer_gray, color_a, color_b)) + # Convert the blended LAB image back to BGR color space + blended_result = cv2.cvtColor(blended_lab, cv2.COLOR_Lab2BGR) + return blended_result + + +class ColorBlend: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "bw_layer": ("IMAGE",), + "color_layer": ("IMAGE",), + }, + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "color_blending_mode" + CATEGORY = "Art Venture/Post Processing" + + def color_blending_mode(self, bw_layer, color_layer): + if bw_layer.shape[0] < color_layer.shape[0]: + bw_layer = bw_layer.repeat(color_layer.shape[0], 1, 1, 1)[ + : color_layer.shape[0] + ] + if bw_layer.shape[0] > color_layer.shape[0]: + color_layer = color_layer.repeat(bw_layer.shape[0], 1, 1, 1)[ + : bw_layer.shape[0] + ] + + batch_size, *_ = bw_layer.shape + tensor_output = torch.empty_like(bw_layer) + + image1 = bw_layer.cpu() + image2 = color_layer.cpu() + if image1.shape != image2.shape: + image2 = image2.permute(0, 3, 1, 2) + image2 = comfy.utils.common_upscale( + image2, + image1.shape[2], + image1.shape[1], + upscale_method="bicubic", + crop="center", + ) + image2 = image2.permute(0, 2, 3, 1) + image1 = (image1 * 255).to(torch.uint8).numpy() + image2 = (image2 * 255).to(torch.uint8).numpy() + + for i in range(batch_size): + blend = color_blend(image1[i], image2[i]) + blend = np.stack([blend]) + tensor_output[i : i + 1] = ( + torch.from_numpy(blend.transpose(0, 3, 1, 2)) / 255.0 + ).permute(0, 2, 3, 1) + + return (tensor_output,) diff --git a/comfyui-art-venture/modules/postprocessing/color_correct.py b/comfyui-art-venture/modules/postprocessing/color_correct.py new file mode 100644 index 0000000000000000000000000000000000000000..08af1bb2b5ace5454ca66a33b7cbfaa2b9a5187e --- /dev/null +++ b/comfyui-art-venture/modules/postprocessing/color_correct.py @@ -0,0 +1,101 @@ +# Adapt from https://github.com/EllangoK/ComfyUI-post-processing-nodes/blob/master/post_processing/color_correct.py + +import cv2 +import numpy as np +import torch +from PIL import Image, ImageEnhance + + +class ColorCorrect: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "image": ("IMAGE",), + "temperature": ( + "FLOAT", + {"default": 0, "min": -100, "max": 100, "step": 5}, + ), + "hue": ("FLOAT", {"default": 0, "min": -90, "max": 90, "step": 5}), + "brightness": ( + "FLOAT", + {"default": 0, "min": -100, "max": 100, "step": 5}, + ), + "contrast": ( + "FLOAT", + {"default": 0, "min": -100, "max": 100, "step": 5}, + ), + "saturation": ( + "FLOAT", + {"default": 0, "min": -100, "max": 100, "step": 5}, + ), + "gamma": ("FLOAT", {"default": 1, "min": 0.2, "max": 2.2, "step": 0.1}), + }, + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "color_correct" + + CATEGORY = "Art Venture/Post Processing" + + def color_correct( + self, + image: torch.Tensor, + temperature: float, + hue: float, + brightness: float, + contrast: float, + saturation: float, + gamma: float, + ): + batch_size, height, width, _ = image.shape + result = torch.zeros_like(image) + + brightness /= 100 + contrast /= 100 + saturation /= 100 + temperature /= 100 + + brightness = 1 + brightness + contrast = 1 + contrast + saturation = 1 + saturation + + for b in range(batch_size): + tensor_image = image[b].numpy() + + modified_image = Image.fromarray((tensor_image * 255).astype(np.uint8)) + + # brightness + modified_image = ImageEnhance.Brightness(modified_image).enhance(brightness) + + # contrast + modified_image = ImageEnhance.Contrast(modified_image).enhance(contrast) + modified_image = np.array(modified_image).astype(np.float32) + + # temperature + if temperature > 0: + modified_image[:, :, 0] *= 1 + temperature + modified_image[:, :, 1] *= 1 + temperature * 0.4 + elif temperature < 0: + modified_image[:, :, 2] *= 1 - temperature + modified_image = np.clip(modified_image, 0, 255) / 255 + + # gamma + modified_image = np.clip(np.power(modified_image, gamma), 0, 1) + + # saturation + hls_img = cv2.cvtColor(modified_image, cv2.COLOR_RGB2HLS) + hls_img[:, :, 2] = np.clip(saturation * hls_img[:, :, 2], 0, 1) + modified_image = cv2.cvtColor(hls_img, cv2.COLOR_HLS2RGB) * 255 + + # hue + hsv_img = cv2.cvtColor(modified_image, cv2.COLOR_RGB2HSV) + hsv_img[:, :, 0] = (hsv_img[:, :, 0] + hue) % 360 + modified_image = cv2.cvtColor(hsv_img, cv2.COLOR_HSV2RGB) + + modified_image = modified_image.astype(np.uint8) + modified_image = modified_image / 255 + modified_image = torch.from_numpy(modified_image).unsqueeze(0) + result[b] = modified_image + + return (result,) diff --git a/comfyui-art-venture/modules/sdxl_prompt_styler/.gitignore b/comfyui-art-venture/modules/sdxl_prompt_styler/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ba0430d26c996e7f078385407f959c96c271087c --- /dev/null +++ b/comfyui-art-venture/modules/sdxl_prompt_styler/.gitignore @@ -0,0 +1 @@ +__pycache__/ \ No newline at end of file diff --git a/comfyui-art-venture/modules/sdxl_prompt_styler/LICENSE b/comfyui-art-venture/modules/sdxl_prompt_styler/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..81f6e9bec2a378e711d5c2c8d884b7fddb59c4de --- /dev/null +++ b/comfyui-art-venture/modules/sdxl_prompt_styler/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 twri + +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-art-venture/modules/sdxl_prompt_styler/README.md b/comfyui-art-venture/modules/sdxl_prompt_styler/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7b5622962df54c77383f19a1aca5505144e10777 --- /dev/null +++ b/comfyui-art-venture/modules/sdxl_prompt_styler/README.md @@ -0,0 +1,79 @@ +SDXL Prompt Styler +======= +Custom node for ComfyUI +----------- +![SDXL Prompt Styler Screenshot](examples/sdxl_prompt_styler.png) + +SDXL Prompt Styler is a node that enables you to style prompts based on predefined templates stored in multiple JSON files. The node specifically replaces a {prompt} placeholder in the 'prompt' field of each template with provided positive text. + +The node also effectively manages negative prompts. If negative text is provided, the node combines this with the 'negative_prompt' field from the template. If no negative text is supplied, the system defaults to using the 'negative_prompt' from the JSON template. This flexibility enables the creation of a diverse and specific range of negative prompts. + +## Important Update: +With the latest changes, the file structure and naming convention for style JSONs have been modified. If you've added or made changes to the `sdxl_styles.json` file in the past, follow these steps to ensure your styles remain intact: + +1. **Backup**: Before pulling the latest changes, back up your `sdxl_styles.json` to a safe location. +2. **Migration**: After updating the repository, create a new JSON file in the styles directory. Move your custom styles from the backup of `sdxl_styles.json` into this new file. +3. **Unique Style Names**: While the system now detects duplicates and appends a suffix to ensure uniqueness, it's a best practice to ensure your style names are originally unique to prevent any potential confusion. +4. **Managing Included JSON Files**: If you prefer not to load specific included JSON files, consider renaming or moving them to a different location outside of the styles directory. The system will load all JSON files present in the specified directory. + +## New Features: + +1. **Loading from Multiple JSON Files:** The system can now load styles from multiple JSON files present in the specified directory, ensuring the uniqueness of style names by appending a suffix to duplicates. +2. **Enhanced Error Handling:** Improved error handling for file reading, data validity, and template replacement functions. + +--- + +### Usage Example with SDXL Prompt Styler + +Template example from a JSON file: + +```json +[ + { + "name": "base", + "prompt": "{prompt}", + "negative_prompt": "" + }, + { + "name": "enhance", + "prompt": "breathtaking {prompt} . award-winning, professional, highly detailed", + "negative_prompt": "ugly, deformed, noisy, blurry, distorted, grainy" + } +] +``` + +```python +style = "enhance" +positive_prompt = "a futuristic pop up tent in a forest" +negative_prompt = "dark" +``` + +This will generate the following styled prompts as outputs: + +``` +breathtaking a futuristic pop up tent in a forest . award-winning, professional, highly detailed +ugly, deformed, noisy, blurry, distorted, grainy, dark +``` + +### Installation + +To install and use the SDXL Prompt Styler nodes, follow these steps: + +1. Open a terminal or command line interface. +2. Navigate to the `ComfyUI/custom_nodes/` directory. +3. Run the following command: +```git clone https://github.com/twri/sdxl_prompt_styler.git``` +4. Restart ComfyUI. + +This command clones the SDXL Prompt Styler repository into your `ComfyUI/custom_nodes/` directory. You should now be able to access and use the nodes from this repository. + +### Inputs + +* **text_positive** - text for the positive base prompt G +* **text_negative** - text for the negative base prompt G +* **log_prompt** - print inputs and outputs to stdout + +### Outputs + +* **positive_prompt_text_g** - combined prompt with style for positive promt G +* **negative_prompt_text_g** - combined prompt with style for negative promt G \ No newline at end of file diff --git a/comfyui-art-venture/modules/sdxl_prompt_styler/__pycache__/__init__.cpython-310.pyc b/comfyui-art-venture/modules/sdxl_prompt_styler/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12de03d760a5fde1ea652b0efe50e9d0f0c06e1f Binary files /dev/null and b/comfyui-art-venture/modules/sdxl_prompt_styler/__pycache__/__init__.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/sdxl_prompt_styler/__pycache__/sdxl_prompt_styler.cpython-310.pyc b/comfyui-art-venture/modules/sdxl_prompt_styler/__pycache__/sdxl_prompt_styler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72a4ab298656b29c0da8464301ec451bbc31ad7d Binary files /dev/null and b/comfyui-art-venture/modules/sdxl_prompt_styler/__pycache__/sdxl_prompt_styler.cpython-310.pyc differ diff --git a/comfyui-art-venture/modules/sdxl_prompt_styler/sdxl_styles_base.json b/comfyui-art-venture/modules/sdxl_prompt_styler/sdxl_styles_base.json new file mode 100644 index 0000000000000000000000000000000000000000..44bff525fc602b6a89e3d5c59d6e1d4fd02f5f0b --- /dev/null +++ b/comfyui-art-venture/modules/sdxl_prompt_styler/sdxl_styles_base.json @@ -0,0 +1,7 @@ +[ + { + "name": "base", + "prompt": "{prompt}", + "negative_prompt": "" + } +] \ No newline at end of file diff --git a/comfyui-art-venture/modules/sdxl_prompt_styler/sdxl_styles_sai.json b/comfyui-art-venture/modules/sdxl_prompt_styler/sdxl_styles_sai.json new file mode 100644 index 0000000000000000000000000000000000000000..51306eb40198c99eb50d7f608ed9c1fc0d599738 --- /dev/null +++ b/comfyui-art-venture/modules/sdxl_prompt_styler/sdxl_styles_sai.json @@ -0,0 +1,87 @@ +[ + { + "name": "3d-model", + "prompt": "professional 3d model {prompt} . octane render, highly detailed, volumetric, dramatic lighting", + "negative_prompt": "ugly, deformed, noisy, low poly, blurry, painting" + }, + { + "name": "analog film", + "prompt": "analog film photo {prompt} . faded film, desaturated, 35mm photo, grainy, vignette, vintage, Kodachrome, Lomography, stained, highly detailed, found footage", + "negative_prompt": "painting, drawing, illustration, glitch, deformed, mutated, cross-eyed, ugly, disfigured" + }, + { + "name": "anime", + "prompt": "anime artwork {prompt} . anime style, key visual, vibrant, studio anime, highly detailed", + "negative_prompt": "photo, deformed, black and white, realism, disfigured, low contrast" + }, + { + "name": "cinematic", + "prompt": "cinematic film still {prompt} . shallow depth of field, vignette, highly detailed, high budget, bokeh, cinemascope, moody, epic, gorgeous, film grain, grainy", + "negative_prompt": "anime, cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured" + }, + { + "name": "comic book", + "prompt": "comic {prompt} . graphic illustration, comic art, graphic novel art, vibrant, highly detailed", + "negative_prompt": "photograph, deformed, glitch, noisy, realistic, stock photo" + }, + { + "name": "craft clay", + "prompt": "play-doh style {prompt} . sculpture, clay art, centered composition, Claymation", + "negative_prompt": "sloppy, messy, grainy, highly detailed, ultra textured, photo" + }, + { + "name": "digital art", + "prompt": "concept art {prompt} . digital artwork, illustrative, painterly, matte painting, highly detailed", + "negative_prompt": "photo, photorealistic, realism, ugly" + }, + { + "name": "enhance", + "prompt": "breathtaking {prompt} . award-winning, professional, highly detailed", + "negative_prompt": "ugly, deformed, noisy, blurry, distorted, grainy" + }, + { + "name": "fantasy art", + "prompt": "ethereal fantasy concept art of {prompt} . magnificent, celestial, ethereal, painterly, epic, majestic, magical, fantasy art, cover art, dreamy", + "negative_prompt": "photographic, realistic, realism, 35mm film, dslr, cropped, frame, text, deformed, glitch, noise, noisy, off-center, deformed, cross-eyed, closed eyes, bad anatomy, ugly, disfigured, sloppy, duplicate, mutated, black and white" + }, + { + "name": "isometric", + "prompt": "isometric style {prompt} . vibrant, beautiful, crisp, detailed, ultra detailed, intricate", + "negative_prompt": "deformed, mutated, ugly, disfigured, blur, blurry, noise, noisy, realistic, photographic" + }, + { + "name": "line art", + "prompt": "line art drawing {prompt} . professional, sleek, modern, minimalist, graphic, line art, vector graphics", + "negative_prompt": "anime, photorealistic, 35mm film, deformed, glitch, blurry, noisy, off-center, deformed, cross-eyed, closed eyes, bad anatomy, ugly, disfigured, mutated, realism, realistic, impressionism, expressionism, oil, acrylic" + }, + { + "name": "lowpoly", + "prompt": "low-poly style {prompt} . low-poly game art, polygon mesh, jagged, blocky, wireframe edges, centered composition", + "negative_prompt": "noisy, sloppy, messy, grainy, highly detailed, ultra textured, photo" + }, + { + "name": "neonpunk", + "prompt": "neonpunk style {prompt} . cyberpunk, vaporwave, neon, vibes, vibrant, stunningly beautiful, crisp, detailed, sleek, ultramodern, magenta highlights, dark purple shadows, high contrast, cinematic, ultra detailed, intricate, professional", + "negative_prompt": "painting, drawing, illustration, glitch, deformed, mutated, cross-eyed, ugly, disfigured" + }, + { + "name": "origami", + "prompt": "origami style {prompt} . paper art, pleated paper, folded, origami art, pleats, cut and fold, centered composition", + "negative_prompt": "noisy, sloppy, messy, grainy, highly detailed, ultra textured, photo" + }, + { + "name": "photographic", + "prompt": "cinematic photo {prompt} . 35mm photograph, film, bokeh, professional, 4k, highly detailed", + "negative_prompt": "drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly" + }, + { + "name": "pixel art", + "prompt": "pixel-art {prompt} . low-res, blocky, pixel art style, 8-bit graphics", + "negative_prompt": "sloppy, messy, blurry, noisy, highly detailed, ultra textured, photo, realistic" + }, + { + "name": "texture", + "prompt": "texture {prompt} top down close-up", + "negative_prompt": "ugly, deformed, noisy, blurry" + } +] \ No newline at end of file diff --git a/comfyui-art-venture/modules/utility_nodes.py b/comfyui-art-venture/modules/utility_nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..c08b3fc86431a2a2f418b7b825f5a8e78cee2e49 --- /dev/null +++ b/comfyui-art-venture/modules/utility_nodes.py @@ -0,0 +1,1327 @@ +import io +import os +import json +import torch +import base64 +import random +import requests +from typing import List, Dict, Tuple, Optional + +from PIL import Image, ImageOps, ImageFilter +import numpy as np + +import folder_paths +import comfy.utils +from comfy_extras.nodes_upscale_model import ImageUpscaleWithModel + +from .utils import pil2tensor, tensor2pil, ensure_package, get_dict_attribute + + +MAX_RESOLUTION = 8192 + + +class AnyType(str): + """A special class that is always equal in not equal comparisons. Credit to pythongosssss""" + + def __ne__(self, __value: object) -> bool: + return False + + +class FlexibleOptionalInputType(dict): + """A special class to make flexible nodes that pass data to our python handlers. + + Enables both flexible/dynamic input types (like for Any Switch) or a dynamic number of inputs + (like for Any Switch, Context Switch, Context Merge, Power Lora Loader, etc). + + Note, for ComfyUI, all that's needed is the `__contains__` override below, which tells ComfyUI + that our node will handle the input, regardless of what it is. + + However, with https://github.com/comfyanonymous/ComfyUI/pull/2666 a large change would occur + requiring more details on the input itself. There, we need to return a list/tuple where the first + item is the type. This can be a real type, or use the AnyType for additional flexibility. + + This should be forwards compatible unless more changes occur in the PR. + """ + + def __init__(self, type): + self.type = type + + def __getitem__(self, key): + return (self.type,) + + def __contains__(self, key): + return True + + +any_type = AnyType("*") + + +def prepare_image_for_preview(image: Image.Image, output_dir: str, prefix=None): + if prefix is None: + prefix = "preview_" + "".join(random.choice("abcdefghijklmnopqrstupvxyz") for x in range(5)) + + # save image to temp folder + ( + outdir, + filename, + counter, + subfolder, + _, + ) = folder_paths.get_save_image_path(prefix, output_dir, image.width, image.height) + file = f"{filename}_{counter:05}_.png" + image.save(os.path.join(outdir, file), format="PNG", compress_level=4) + + return { + "filename": file, + "subfolder": subfolder, + "type": "temp", + } + + +def load_images_from_url(urls: List[str], keep_alpha_channel=False): + images: List[Image.Image] = [] + masks: List[Optional[Image.Image]] = [] + + for url in urls: + if url.startswith("data:image/"): + i = Image.open(io.BytesIO(base64.b64decode(url.split(",")[1]))) + elif url.startswith("file://"): + url = url[7:] + if not os.path.isfile(url): + raise Exception(f"File {url} does not exist") + + i = Image.open(url) + elif url.startswith("http://") or url.startswith("https://"): + response = requests.get(url, timeout=5) + if response.status_code != 200: + raise Exception(response.text) + + i = Image.open(io.BytesIO(response.content)) + 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"]) + if dirtype[0] == "input": + url = os.path.join(folder_paths.get_input_directory(), filename) + elif dirtype[0] == "output": + url = os.path.join(folder_paths.get_output_directory(), filename) + elif dirtype[0] == "temp": + url = os.path.join(folder_paths.get_temp_directory(), filename) + else: + raise Exception(f"Invalid url: {url}") + + i = Image.open(url) + elif url == "": + continue + else: + url = folder_paths.get_annotated_filepath(url) + if not os.path.isfile(url): + raise Exception(f"Invalid url: {url}") + + i = Image.open(url) + + i = ImageOps.exif_transpose(i) + has_alpha = "A" in i.getbands() + mask = None + + if "RGB" not in i.mode: + i = i.convert("RGBA") if has_alpha else i.convert("RGB") + + if has_alpha: + mask = i.getchannel("A") + + if not keep_alpha_channel: + image = i.convert("RGB") + else: + image = i + + images.append(image) + masks.append(mask) + + return (images, masks) + + +class UtilLoadImageFromUrl: + def __init__(self) -> None: + self.output_dir = folder_paths.get_temp_directory() + self.filename_prefix = "TempImageFromUrl" + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "image": ("STRING", { + "default": "", + "placeholder": "Input image paths or URLS one per line. Eg:\nhttps://example.com/image.png\nfile:///path/to/local/image.jpg\ndata:image/png;base64,...", + "multiline": True, + "dynamicPrompts": False, + }), + }, + "optional": { + "keep_alpha_channel": ( + "BOOLEAN", + {"default": False, "label_on": "enabled", "label_off": "disabled"}, + ), + "output_mode": ( + "BOOLEAN", + {"default": False, "label_on": "list", "label_off": "batch"}, + ), + }, + } + + RETURN_TYPES = ("IMAGE", "MASK", "BOOLEAN") + OUTPUT_IS_LIST = (True, True, False) + RETURN_NAMES = ("images", "masks", "has_image") + CATEGORY = "Art Venture/Image" + FUNCTION = "load_image" + + def load_image(self, image: str, keep_alpha_channel=False, output_mode=False): + urls = image.strip().split("\n") + pil_images, pil_masks = load_images_from_url(urls, keep_alpha_channel) + has_image = len(pil_images) > 0 + if not has_image: + i = torch.zeros((1, 64, 64, 3), dtype=torch.float32, device="cpu") + m = torch.zeros((64, 64), dtype=torch.float32, device="cpu") + pil_images = [tensor2pil(i)] + pil_masks = [tensor2pil(m, mode="L")] + + previews = [] + np_images: list[torch.Tensor] = [] + np_masks: list[torch.Tensor] = [] + + for pil_image, pil_mask in zip(pil_images, pil_masks): + if pil_mask is not None: + preview_image = Image.new("RGB", pil_image.size) + preview_image.paste(pil_image, (0, 0)) + preview_image.putalpha(pil_mask) + else: + preview_image = pil_image + + previews.append(prepare_image_for_preview(preview_image, self.output_dir, self.filename_prefix)) + + np_image = pil2tensor(pil_image) + if pil_mask: + np_mask = np.array(pil_mask).astype(np.float32) / 255.0 + np_mask = 1.0 - torch.from_numpy(np_mask) + else: + np_mask = torch.zeros((64, 64), dtype=torch.float32, device="cpu") + + np_images.append(np_image) + np_masks.append(np_mask.unsqueeze(0)) + + if output_mode: + result = (np_images, np_masks, has_image) + else: + has_size_mismatch = False + if len(np_images) > 1: + for np_image in np_images[1:]: + if np_image.shape[1] != np_images[0].shape[1] or np_image.shape[2] != np_images[0].shape[2]: + has_size_mismatch = True + break + + if has_size_mismatch: + raise Exception("To output as batch, images must have the same size. Use list output mode instead.") + + result = ([torch.cat(np_images)], [torch.cat(np_masks)], has_image) + + return {"ui": {"images": previews}, "result": result} + + +class UtilLoadImageAsMaskFromUrl(UtilLoadImageFromUrl): + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "image": ("STRING", { + "default": "", + "placeholder": "Input image paths or URLS one per line. Eg:\nhttps://example.com/image.png\nfile:///path/to/local/image.jpg\ndata:image/png;base64,...", + "multiline": True, + "dynamicPrompts": False, + }), + "channel": (["alpha", "red", "green", "blue"],), + }, + "optional": { + "output_mode": ( + "BOOLEAN", + {"default": False, "label_on": "list", "label_off": "batch"}, + ), + }, + } + + RETURN_TYPES = ("MASK",) + RETURN_NAMES = ("masks",) + OUTPUT_IS_LIST = (True,) + + def load_image(self, image: str, channel: str, output_mode=False, url=""): + if not image or image == "": + image = url + + urls = image.strip().split("\n") + pil_images, pil_alphas = load_images_from_url(urls, True) + + masks: List[torch.Tensor] = [] + + for img, alpha in zip(pil_images, pil_alphas): + if channel == "alpha": + mask = alpha + elif channel == "red": + mask = img.getchannel("R") + elif channel == "green": + mask = img.getchannel("G") + elif channel == "blue": + mask = img.getchannel("B") + + if mask: + mask = np.array(mask, dtype=np.float32) / 255.0 + mask = torch.from_numpy(mask) + if channel == "alpha": + mask = 1.0 - mask + else: + mask = torch.zeros((64, 64), dtype=torch.float32, device="cpu") + + masks.append(mask.unsqueeze(0)) + + if output_mode: + return (masks,) + + if len(masks) > 1: + for mask in masks[1:]: + if mask.shape[0] != masks[0].shape[0] or mask.shape[1] != masks[0].shape[1]: + raise Exception("To output as batch, masks must have the same size. Use list output mode instead.") + + return ([torch.cat(masks)],) + + +class UtilLoadJsonFromText: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "data": ( + "STRING", + {"multiline": True, "dynamicPrompts": False, "placeholder": "JSON object. Eg: {'key': 'value'}"}, + ), + } + } + + RETURN_TYPES = ("JSON",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "load_json" + + def load_json(self, data: str): + return (json.loads(data),) + + +class UtilLoadJsonFromUrl: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "url": ("STRING", {"default": ""}), + }, + "optional": { + "print_to_console": ("BOOLEAN", {"default": False}), + }, + } + + RETURN_TYPES = ("JSON",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "load_json" + + def load_json(self, url: str, print_to_console=False): + response = requests.get(url, timeout=5) + if response.status_code != 200: + raise Exception(response.text) + + res = response.json() + if print_to_console: + print("JSON content:", json.dumps(res)) + + return (res,) + + +class UtilGetObjectFromJson: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "json": ("JSON",), + "key": ("STRING", {"default": ""}), + } + } + + RETURN_TYPES = ("JSON",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "get_objects_from_json" + OUTPUT_NODE = True + + def get_objects_from_json(self, json: Dict, key: str): + return (get_dict_attribute(json, key, {}),) + + +class UtilGetTextFromJson: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "json": ("JSON",), + "key": ("STRING", {"default": ""}), + } + } + + RETURN_TYPES = ("STRING",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "get_string_from_json" + OUTPUT_NODE = True + + def get_string_from_json(self, json: Dict, key: str): + return (str(get_dict_attribute(json, key, "")),) + + +class UtilGetFloatFromJson: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "json": ("JSON",), + "key": ("STRING", {"default": ""}), + } + } + + RETURN_TYPES = ("FLOAT",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "get_float_from_json" + OUTPUT_NODE = True + + def get_float_from_json(self, json: Dict, key: str): + return (float(get_dict_attribute(json, key, 0.0)),) + + +class UtilGetIntFromJson: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "json": ("JSON",), + "key": ("STRING", {"default": ""}), + } + } + + RETURN_TYPES = ("INT",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "get_int_from_json" + OUTPUT_NODE = True + + def get_int_from_json(self, json: Dict, key: str): + return (int(get_dict_attribute(json, key, 0)),) + + +class UtilGetBoolFromJson: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "json": ("JSON",), + "key": ("STRING", {"default": ""}), + } + } + + RETURN_TYPES = ("BOOLEAN",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "get_bool_from_json" + OUTPUT_NODE = True + + def get_bool_from_json(self, json: Dict, key: str): + return (get_dict_attribute(json, key, False),) + + +class UtilRandomInt: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "min": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFFFFFFFFFFFF}), + "max": ("INT", {"default": 100, "min": 0, "max": 0xFFFFFFFFFFFFFFFF}), + } + } + + RETURN_TYPES = ("INT", "STRING") + CATEGORY = "Art Venture/Utils" + FUNCTION = "random_int" + + @classmethod + def IS_CHANGED(cls, *args, **kwargs): + return torch.rand(1).item() + + def random_int(self, min: int, max: int): + num = torch.randint(min, max, (1,)).item() + return (num, str(num)) + + +class UtilRandomFloat: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "min": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 0xFFFFFFFFFFFFFFFF}), + "max": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 0xFFFFFFFFFFFFFFFF}), + } + } + + RETURN_TYPES = ("FLOAT", "STRING") + CATEGORY = "Art Venture/Utils" + FUNCTION = "random_float" + + @classmethod + def IS_CHANGED(cls, *args, **kwargs): + return torch.rand(1).item() + + def random_float(self, min: float, max: float): + num = torch.rand(1).item() * (max - min) + min + return (num, str(num)) + + +class UtilStringToInt: + @classmethod + def INPUT_TYPES(cls): + return { + "required": {"string": ("STRING", {"default": "0"})}, + } + + RETURN_TYPES = ("INT",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "string_to_int" + + def string_to_int(self, string: str): + return (int(string),) + + +class UtilStringToNumber: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "string": ("STRING", {"default": "0"}), + "rounding": (["round", "floor", "ceil"], {"default": "round"}), + }, + } + + RETURN_TYPES = ("INT", "FLOAT") + CATEGORY = "Art Venture/Utils" + FUNCTION = "string_to_numbers" + + def string_to_numbers(self, string: str, rounding): + f = float(string) + + if rounding == "floor": + return (int(np.floor(f)), f) + elif rounding == "ceil": + return (int(np.ceil(f)), f) + else: + return (int(round(f)), f) + + +class UtilNumberScaler: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "min": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 0xFFFFFFFFFFFFFFFF}), + "max": ("FLOAT", {"default": 10.0, "min": 0.0, "max": 0xFFFFFFFFFFFFFFFF}), + "scale_to_min": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 0xFFFFFFFFFFFFFFFF}), + "scale_to_max": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 0xFFFFFFFFFFFFFFFF}), + "value": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 0xFFFFFFFFFFFFFFFF}), + } + } + + RETURN_TYPES = ("FLOAT",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "scale_number" + + def scale_number(self, min: float, max: float, scale_to_min: float, scale_to_max: float, value: float): + num = (value - min) / (max - min) * (scale_to_max - scale_to_min) + scale_to_min + return (num,) + + +class UtilBooleanPrimitive: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "value": ("BOOLEAN", {"default": False}), + "reverse": ("BOOLEAN", {"default": False}), + } + } + + RETURN_TYPES = ("BOOLEAN", "STRING") + CATEGORY = "Art Venture/Utils" + FUNCTION = "boolean_primitive" + + def boolean_primitive(self, value: bool, reverse: bool): + if reverse: + value = not value + + return (value, str(value)) + + +class UtilTextSwitchCase: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "switch_cases": ( + "STRING", + { + "default": "", + "multiline": True, + "dynamicPrompts": False, + "placeholder": "case_1:output_1\ncase_2:output_2\nthat span multiple lines\ncase_3:output_3", + }, + ), + "condition": ("STRING", {"default": ""}), + "default_value": ("STRING", {"default": ""}), + "delimiter": ("STRING", {"default": ":"}), + } + } + + RETURN_TYPES = ("STRING",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "text_switch_case" + + def text_switch_case(self, switch_cases: str, condition: str, default_value: str, delimiter: str = ":"): + # Split into cases first + cases = switch_cases.split("\n") + current_case = None + current_output = [] + + for line in cases: + if delimiter in line: + # Process previous case if exists + if current_case is not None and condition == current_case: + return ("\n".join(current_output),) + + # Start new case + current_case, output = line.split(delimiter, 1) + current_output = [output] + elif current_case is not None: + current_output.append(line) + + # Check last case + if current_case is not None and condition == current_case: + return ("\n".join(current_output),) + + return (default_value,) + + +class UtilImageMuxer: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "image_1": ("IMAGE",), + "image_2": ("IMAGE",), + "input_selector": ("INT", {"default": 0}), + }, + "optional": {"image_3": ("IMAGE",), "image_4": ("IMAGE",)}, + } + + RETURN_TYPES = ("IMAGE",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "image_muxer" + + def image_muxer(self, image_1, image_2, input_selector, image_3=None, image_4=None): + images = [image_1, image_2, image_3, image_4] + return (images[input_selector],) + + +class UtilSDXLAspectRatioSelector: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "aspect_ratio": ( + [ + "1:1", + "2:3", + "3:4", + "5:8", + "9:16", + "9:19", + "9:21", + "3:2", + "4:3", + "8:5", + "16:9", + "19:9", + "21:9", + ], + ), + } + } + + RETURN_TYPES = ("STRING", "INT", "INT") + RETURN_NAMES = ("ratio", "width", "height") + FUNCTION = "get_aspect_ratio" + CATEGORY = "Art Venture/Utils" + + def get_aspect_ratio(self, aspect_ratio): + width, height = 1024, 1024 + + if aspect_ratio == "1:1": + width, height = 1024, 1024 + elif aspect_ratio == "2:3": + width, height = 832, 1216 + elif aspect_ratio == "3:4": + width, height = 896, 1152 + elif aspect_ratio == "5:8": + width, height = 768, 1216 + elif aspect_ratio == "9:16": + width, height = 768, 1344 + elif aspect_ratio == "9:19": + width, height = 704, 1472 + elif aspect_ratio == "9:21": + width, height = 640, 1536 + elif aspect_ratio == "3:2": + width, height = 1216, 832 + elif aspect_ratio == "4:3": + width, height = 1152, 896 + elif aspect_ratio == "8:5": + width, height = 1216, 768 + elif aspect_ratio == "16:9": + width, height = 1344, 768 + elif aspect_ratio == "19:9": + width, height = 1472, 704 + elif aspect_ratio == "21:9": + width, height = 1536, 640 + + return (aspect_ratio, width, height) + + +class UtilAspectRatioSelector(UtilSDXLAspectRatioSelector): + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "aspect_ratio": ( + [ + "1:1", + "2:3", + "3:4", + "9:16", + "3:2", + "4:3", + "16:9", + ], + ), + } + } + + def get_aspect_ratio(self, aspect_ratio): + ratio, width, height = super().get_aspect_ratio(aspect_ratio) + + scale_ratio = 768 / max(width, height) + + width = int(scale_ratio * width / 8) * 8 + height = int(scale_ratio * height / 8) * 8 + + return (ratio, width, height) + + +class UtilDependenciesEdit: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "dependencies": ("DEPENDENCIES",), + }, + "optional": { + "ckpt_name": ( + [ + "Original", + ] + + folder_paths.get_filename_list("checkpoints"), + ), + "vae_name": (["Original", "Baked VAE"] + folder_paths.get_filename_list("vae"),), + "clip": ("CLIP",), + "clip_skip": ( + "INT", + {"default": 0, "min": -24, "max": 0, "step": 1}, + ), + "positive": ("STRING", {"default": "Original", "multiline": True}), + "negative": ("STRING", {"default": "Original", "multiline": True}), + "lora_stack": ("LORA_STACK",), + "cnet_stack": ("CONTROL_NET_STACK",), + }, + } + + RETURN_TYPES = ("DEPENDENCIES",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "edit_dependencies" + + def edit_dependencies( + self, + dependencies: Tuple, + vae_name="Original", + ckpt_name="Original", + clip=None, + clip_skip=0, + positive="Original", + negative="Original", + lora_stack=None, + cnet_stack=None, + ): + ( + _vae_name, + _ckpt_name, + _clip, + _clip_skip, + _positive_prompt, + _negative_prompt, + _lora_stack, + _cnet_stack, + ) = dependencies + + if vae_name != "Original": + _vae_name = vae_name + if ckpt_name != "Original": + _ckpt_name = ckpt_name + if clip is not None: + _clip = clip + if clip_skip < 0: + _clip_skip = clip_skip + if positive != "Original": + _positive_prompt = positive + if negative != "Original": + _negative_prompt = negative + if lora_stack is not None: + _lora_stack = lora_stack + if cnet_stack is not None: + _cnet_stack = cnet_stack + + dependencies = ( + _vae_name, + _ckpt_name, + _clip, + _clip_skip, + _positive_prompt, + _negative_prompt, + _lora_stack, + _cnet_stack, + ) + + print("Dependencies:", dependencies) + + return (dependencies,) + + +class UtilImageScaleDown: + crop_methods = ["disabled", "center"] + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "images": ("IMAGE",), + "width": ( + "INT", + {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}, + ), + "height": ( + "INT", + {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}, + ), + "crop": (cls.crop_methods,), + } + } + + RETURN_TYPES = ("IMAGE",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "image_scale_down" + + def image_scale_down(self, images, width, height, crop): + if crop == "center": + old_width = images.shape[2] + old_height = images.shape[1] + old_aspect = old_width / old_height + new_aspect = width / height + x = 0 + y = 0 + if old_aspect > new_aspect: + x = round((old_width - old_width * (new_aspect / old_aspect)) / 2) + elif old_aspect < new_aspect: + y = round((old_height - old_height * (old_aspect / new_aspect)) / 2) + s = images[:, y : old_height - y, x : old_width - x, :] + else: + s = images + + results = [] + for image in s: + img = tensor2pil(image).convert("RGB") + img = img.resize((width, height), Image.Resampling.LANCZOS) + results.append(pil2tensor(img)) + + return (torch.cat(results, dim=0),) + + +class UtilImageScaleDownBy(UtilImageScaleDown): + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "images": ("IMAGE",), + "scale_by": ( + "FLOAT", + {"default": 0.5, "min": 0.01, "max": 1.0, "step": 0.01}, + ), + } + } + + RETURN_TYPES = ("IMAGE",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "image_scale_down_by" + + def image_scale_down_by(self, images, scale_by): + width = images.shape[2] + height = images.shape[1] + new_width = int(width * scale_by) + new_height = int(height * scale_by) + return self.image_scale_down(images, new_width, new_height, "center") + + +class UtilImageScaleDownToSize(UtilImageScaleDownBy): + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "images": ("IMAGE",), + "size": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}), + "mode": ("BOOLEAN", {"default": True, "label_on": "max", "label_off": "min"}), + } + } + + RETURN_TYPES = ("IMAGE",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "image_scale_down_to_size" + + def image_scale_down_to_size(self, images, size, mode): + width = images.shape[2] + height = images.shape[1] + + if mode: + scale_by = size / max(width, height) + else: + scale_by = size / min(width, height) + + scale_by = min(scale_by, 1.0) + return self.image_scale_down_by(images, scale_by) + + +class UtilImageScaleToTotalPixels(UtilImageScaleDownBy, ImageUpscaleWithModel): + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "images": ("IMAGE",), + "megapixels": ("FLOAT", {"default": 1, "min": 0.1, "max": 100, "step": 0.05}), + }, + "optional": { + "upscale_model_opt": ("UPSCALE_MODEL",), + }, + } + + RETURN_TYPES = ("IMAGE",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "image_scale_down_to_total_pixels" + + def image_scale_up_by(self, images: torch.Tensor, scale_by, upscale_model_opt): + width = round(images.shape[2] * scale_by) + height = round(images.shape[1] * scale_by) + + if scale_by < 1.2 or upscale_model_opt is None: + s = images.movedim(-1, 1) + s = comfy.utils.common_upscale(s, width, height, "bicubic", "disabled") + s = s.movedim(1, -1) + return (s,) + else: + s = self.upscale(upscale_model_opt, images)[0] + return self.image_scale_down(s, width, height, "center") + + def image_scale_down_to_total_pixels(self, images, megapixels, upscale_model_opt=None): + width = images.shape[2] + height = images.shape[1] + scale_by = np.sqrt((megapixels * 1024 * 1024) / (width * height)) + + if scale_by <= 1.0: + return self.image_scale_down_by(images, scale_by) + else: + return self.image_scale_up_by(images, scale_by, upscale_model_opt) + + +class UtilImageAlphaComposite: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "image_1": ("IMAGE",), + "image_2": ("IMAGE",), + } + } + + RETURN_TYPES = ("IMAGE",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "image_alpha_composite" + + def image_alpha_composite(self, image_1: torch.Tensor, image_2: torch.Tensor): + if image_1.shape[0] != image_2.shape[0]: + raise Exception("Images must have the same amount") + + if image_1.shape[1] != image_2.shape[1] or image_1.shape[2] != image_2.shape[2]: + raise Exception("Images must have the same size") + + composited_images = [] + for i, im1 in enumerate(image_1): + composited = Image.alpha_composite( + tensor2pil(im1).convert("RGBA"), + tensor2pil(image_2[i]).convert("RGBA"), + ) + composited_images.append(pil2tensor(composited)) + + return (torch.cat(composited_images, dim=0),) + + +class UtilImageGaussianBlur: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "images": ("IMAGE",), + "radius": ("INT", {"default": 1, "min": 1, "max": 100}), + } + } + + RETURN_TYPES = ("IMAGE",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "image_gaussian_blur" + + def image_gaussian_blur(self, images, radius): + blured_images = [] + for image in images: + img = tensor2pil(image) + img = img.filter(ImageFilter.GaussianBlur(radius=radius)) + blured_images.append(pil2tensor(img)) + + return (torch.cat(blured_images, dim=0),) + + +class UtilImageExtractChannel: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "images": ("IMAGE",), + "channel": (["R", "G", "B", "A"],), + } + } + + RETURN_TYPES = ("MASK",) + RETURN_NAMES = ("channel_data",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "image_extract_alpha" + + def image_extract_alpha(self, images: torch.Tensor, channel): + # images in shape (N, H, W, C) + + if len(images.shape) < 4: + images = images.unsqueeze(3).repeat(1, 1, 1, 3) + + if channel == "A" and images.shape[3] < 4: + raise Exception("Image does not have an alpha channel") + + channel_index = ["R", "G", "B", "A"].index(channel) + mask = images[:, :, :, channel_index].cpu().clone() + + return (mask,) + + +class UtilImageApplyChannel: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "images": ("IMAGE",), + "channel_data": ("MASK",), + "channel": (["R", "G", "B", "A"],), + } + } + + RETURN_TYPES = ("IMAGE",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "image_apply_channel" + + def image_apply_channel(self, images: torch.Tensor, channel_data: torch.Tensor, channel): + merged_images = [] + + for image in images: + image = image.cpu().clone() + + if channel == "A": + if image.shape[2] < 4: + image = torch.cat([image, torch.ones((image.shape[0], image.shape[1], 1))], dim=2) + + image[:, :, 3] = channel_data + elif channel == "R": + image[:, :, 0] = channel_data + elif channel == "G": + image[:, :, 1] = channel_data + else: + image[:, :, 2] = channel_data + + merged_images.append(image) + + return (torch.stack(merged_images),) + + +class UtillQRCodeGenerator: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "text": ("STRING", {"multiline": True}), + "size": ("INT", {"default": 512, "min": 64, "max": 4096, "step": 64}), + "qr_version": ("INT", {"default": 1, "min": 1, "max": 40, "step": 1}), + "error_correction": (["L", "M", "Q", "H"], {"default": "H"}), + "box_size": ("INT", {"default": 10, "min": 1, "max": 100, "step": 1}), + "border": ("INT", {"default": 4, "min": 0, "max": 100, "step": 1}), + }, + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "create_qr_code" + CATEGORY = "Art Venture/Utils" + + def create_qr_code(self, text, size, qr_version, error_correction, box_size, border): + ensure_package("qrcode", install_package_name="qrcode[pil]") + import qrcode + + if error_correction == "L": + error_level = qrcode.ERROR_CORRECT_L + elif error_correction == "M": + error_level = qrcode.ERROR_CORRECT_M + elif error_correction == "Q": + error_level = qrcode.ERROR_CORRECT_Q + else: + error_level = qrcode.ERROR_CORRECT_H + + qr = qrcode.QRCode(version=qr_version, error_correction=error_level, box_size=box_size, border=border) + qr.add_data(text) + qr.make(fit=True) + img = qr.make_image(fill_color="black", back_color="white") + img = img.resize((size, size)).convert("RGB") + + return (pil2tensor(img),) + + +class UtilRepeatImages: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "images": ("IMAGE",), + "amount": ("INT", {"default": 1, "min": 1, "max": 1024}), + } + } + + RETURN_TYPES = ("IMAGE",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "rebatch" + + def rebatch(self, images: torch.Tensor, amount): + return (images.repeat(amount, 1, 1, 1),) + + +class UtilSeedSelector: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "mode": ("BOOLEAN", {"default": True, "label_on": "random", "label_off": "fixed"}), + "seed": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFFFFFFFFFFFF}), + "fixed_seed": ( + "INT", + {"default": 0, "min": 0, "max": 0xFFFFFFFFFFFFFFFF}, + ), + } + } + + RETURN_TYPES = ("INT",) + RETURN_NAMES = ("seed",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "get_seed" + + def get_seed(self, mode, seed, fixed_seed): + return (fixed_seed if not mode else seed,) + + +class UtilCheckpointSelector: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "ckpt_name": (folder_paths.get_filename_list("checkpoints"),), + } + } + + RETURN_TYPES = (folder_paths.get_filename_list("checkpoints"), "STRING") + RETURN_NAMES = ("ckpt_name", "ckpt_name_str") + CATEGORY = "Art Venture/Utils" + FUNCTION = "get_ckpt_name" + + @classmethod + def IS_CHANGED(cls, *args, **kwargs): + return torch.rand(1).item() + + def get_ckpt_name(self, ckpt_name): + return (ckpt_name, ckpt_name) + + +class UtilModelMerge: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "model1": ("MODEL",), + "model2": ("MODEL",), + "ratio": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}), + } + } + + RETURN_TYPES = ("MODEL",) + CATEGORY = "Art Venture/Utils" + FUNCTION = "merge_models" + + def merge_models(self, model1, model2, ratio=1.0): + m = model1.clone() + kp = model2.get_key_patches("diffusion_model.") + + for k in kp: + k_unet = k[len("diffusion_model.") :] + if k_unet == "input_blocks.0.0.weight": + w = kp[k][0] + if w.shape[1] == 9: + w = w[:, 0:4, :, :] + m.add_patches({k: (w,)}, 1.0 - ratio, ratio) + else: + m.add_patches({k: kp[k]}, 1.0 - ratio, ratio) + + return (m,) + + +class UtilTextRandomMultiline: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "text": ("STRING", {"multiline": True, "dynamicPrompts": False}), + "amount": ("INT", {"default": 1, "min": 1, "max": 1024}), + "seed": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFFFFFFFFFFFF}), + }, + } + + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("lines",) + OUTPUT_IS_LIST = (True,) + CATEGORY = "Art Venture/Utils" + FUNCTION = "random_multiline" + + def random_multiline(self, text: str, amount=1, seed=0): + lines = text.strip().split("\n") + lines = [line.strip() for line in lines if line.strip()] + + custom_random = random.Random(seed) + custom_random.shuffle(lines) + return (lines[:amount],) + + +NODE_CLASS_MAPPINGS = { + "LoadImageFromUrl": UtilLoadImageFromUrl, + "LoadImageAsMaskFromUrl": UtilLoadImageAsMaskFromUrl, + "StringToInt": UtilStringToInt, + "StringToNumber": UtilStringToNumber, + "BooleanPrimitive": UtilBooleanPrimitive, + "ImageMuxer": UtilImageMuxer, + "ImageScaleDown": UtilImageScaleDown, + "ImageScaleDownBy": UtilImageScaleDownBy, + "ImageScaleDownToSize": UtilImageScaleDownToSize, + "ImageScaleToMegapixels": UtilImageScaleToTotalPixels, + "ImageAlphaComposite": UtilImageAlphaComposite, + "ImageGaussianBlur": UtilImageGaussianBlur, + "ImageRepeat": UtilRepeatImages, + "ImageExtractChannel": UtilImageExtractChannel, + "ImageApplyChannel": UtilImageApplyChannel, + "QRCodeGenerator": UtillQRCodeGenerator, + "DependenciesEdit": UtilDependenciesEdit, + "AspectRatioSelector": UtilAspectRatioSelector, + "SDXLAspectRatioSelector": UtilSDXLAspectRatioSelector, + "SeedSelector": UtilSeedSelector, + "CheckpointNameSelector": UtilCheckpointSelector, + "LoadJsonFromUrl": UtilLoadJsonFromUrl, + "LoadJsonFromText": UtilLoadJsonFromText, + "GetObjectFromJson": UtilGetObjectFromJson, + "GetTextFromJson": UtilGetTextFromJson, + "GetFloatFromJson": UtilGetFloatFromJson, + "GetIntFromJson": UtilGetIntFromJson, + "GetBoolFromJson": UtilGetBoolFromJson, + "RandomInt": UtilRandomInt, + "RandomFloat": UtilRandomFloat, + "NumberScaler": UtilNumberScaler, + "MergeModels": UtilModelMerge, + "TextRandomMultiline": UtilTextRandomMultiline, + "TextSwitchCase": UtilTextSwitchCase, +} +NODE_DISPLAY_NAME_MAPPINGS = { + "LoadImageFromUrl": "Load Image From URL", + "LoadImageAsMaskFromUrl": "Load Image (as Mask) From URL", + "StringToInt": "String to Int", + "StringToNumber": "String to Number", + "BooleanPrimitive": "Boolean", + "ImageMuxer": "Image Muxer", + "ImageScaleDown": "Scale Down", + "ImageScaleDownBy": "Scale Down By", + "ImageScaleDownToSize": "Scale Down To Size", + "ImageScaleToMegapixels": "Scale To Megapixels", + "ImageAlphaComposite": "Image Alpha Composite", + "ImageGaussianBlur": "Image Gaussian Blur", + "ImageRepeat": "Repeat Images", + "ImageExtractChannel": "Image Extract Channel", + "ImageApplyChannel": "Image Apply Channel", + "QRCodeGenerator": "QR Code Generator", + "DependenciesEdit": "Dependencies Edit", + "AspectRatioSelector": "Aspect Ratio", + "SDXLAspectRatioSelector": "SDXL Aspect Ratio", + "SeedSelector": "Seed Selector", + "CheckpointNameSelector": "Checkpoint Name Selector", + "LoadJsonFromUrl": "Load JSON From URL", + "LoadJsonFromText": "Load JSON From Text", + "GetObjectFromJson": "Get Object From JSON", + "GetTextFromJson": "Get Text From JSON", + "GetFloatFromJson": "Get Float From JSON", + "GetIntFromJson": "Get Int From JSON", + "GetBoolFromJson": "Get Bool From JSON", + "RandomInt": "Random Int", + "RandomFloat": "Random Float", + "NumberScaler": "Number Scaler", + "MergeModels": "Merge Models", + "TextRandomMultiline": "Text Random Multiline", + "TextSwitchCase": "Text Switch Case", +} diff --git a/comfyui-art-venture/modules/utils.py b/comfyui-art-venture/modules/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..096be866a043181b4f9165dc8198f77e708b4d71 --- /dev/null +++ b/comfyui-art-venture/modules/utils.py @@ -0,0 +1,201 @@ +import os +import io +import sys +import torch +import base64 +import numpy as np +import importlib +import importlib.metadata +import subprocess +from packaging import version +from packaging.specifiers import SpecifierSet +from PIL import Image + +from .logger import logger + + +class AnyType(str): + def __ne__(self, __value: object) -> bool: + return False + + +any_type = AnyType("*") + + +def ensure_package(package, required_version=None, install_package_name=None): + # Try to import the package + try: + module = importlib.import_module(package) + except ImportError: + logger.info(f"Package {package} is not installed. Installing now...") + install_command = _construct_pip_command(install_package_name or package, required_version) + subprocess.check_call(install_command) + else: + # If a specific version is required, check the version + if required_version: + try: + installed_version = importlib.metadata.version(package) + + # Parse version specifier (e.g., ">=1.1.1", "==1.1.1", "<=1.1.1") + if any(op in required_version for op in ['>=', '<=', '==', '!=', '>', '<', '~=']): + spec = SpecifierSet(required_version) + if installed_version not in spec: + logger.info( + f"Package {package} version constraint not satisfied (installed: {installed_version}, required: {required_version}). Installing now..." + ) + install_command = _construct_pip_command(install_package_name or package, required_version) + subprocess.check_call(install_command) + else: + # Fallback to simple version comparison for backwards compatibility + if version.parse(installed_version) < version.parse(required_version): + logger.info( + f"Package {package} is outdated (installed: {installed_version}, required: {required_version}). Upgrading now..." + ) + install_command = _construct_pip_command(install_package_name or package, required_version) + subprocess.check_call(install_command) + except importlib.metadata.PackageNotFoundError: + logger.info(f"Package {package} version information not found. Installing required version {required_version}...") + install_command = _construct_pip_command(install_package_name or package, required_version) + subprocess.check_call(install_command) + + +def _construct_pip_command(package_name, version=None): + if "python_embeded" in sys.executable or "python_embedded" in sys.executable: + pip_install = [sys.executable, "-s", "-m", "pip", "install"] + else: + pip_install = [sys.executable, "-m", "pip", "install"] + + # Include the version in the package name if specified + if version: + package_name = f"{package_name}=={version}" + + return pip_install + [package_name] + + +def get_dict_attribute(dict_inst: dict, name_string: str, default=None): + nested_keys = name_string.split(".") + value = dict_inst + + for key in nested_keys: + # Handle array indexing + if key.startswith("[") and key.endswith("]"): + try: + index = int(key[1:-1]) + if not isinstance(value, (list, tuple)) or index >= len(value): + return default + value = value[index] + except (ValueError, TypeError): + return default + else: + if not isinstance(value, dict): + return default + value = value.get(key, None) + + if value is None: + return default + + return value + + +def set_dict_attribute(dict_inst: dict, name_string: str, value): + """ + Set an attribute to a dictionary using dot notation. + If the attribute does not already exist, it will create a nested dictionary. + + Parameters: + - dict_inst: the dictionary instance to set the attribute + - name_string: the attribute name in dot notation (ex: 'attributes[1].name') + - value: the value to set for the attribute + + Returns: + None + """ + # Split the attribute names by dot + name_list = name_string.split(".") + + # Traverse the dictionary and create a nested dictionary if necessary + current_dict = dict_inst + for name in name_list[:-1]: + is_array = name.endswith("]") + if is_array: + open_bracket_index = name.index("[") + idx = int(name[open_bracket_index + 1 : -1]) + name = name[:open_bracket_index] + + if name not in current_dict: + current_dict[name] = [] if is_array else {} + + current_dict = current_dict[name] + if is_array: + while len(current_dict) <= idx: + current_dict.append({}) + current_dict = current_dict[idx] + + # Set the final attribute to its value + name = name_list[-1] + if name.endswith("]"): + open_bracket_index = name.index("[") + idx = int(name[open_bracket_index + 1 : -1]) + name = name[:open_bracket_index] + + if name not in current_dict: + current_dict[name] = [] + + while len(current_dict[name]) <= idx: + current_dict[name].append(None) + + current_dict[name][idx] = value + else: + current_dict[name] = value + + +def is_junction(src: str) -> bool: + import subprocess + + child = subprocess.Popen('fsutil reparsepoint query "{}"'.format(src), stdout=subprocess.PIPE) + streamdata = child.communicate()[0] + rc = child.returncode + return rc == 0 + + +def load_module(module_path, module_name=None): + import importlib.util + + if module_name is None: + module_name = os.path.basename(module_path) + if os.path.isdir(module_path): + module_path = os.path.join(module_path, "__init__.py") + + module_spec = importlib.util.spec_from_file_location(module_name, module_path) + + module = importlib.util.module_from_spec(module_spec) + module_spec.loader.exec_module(module) + + return module + + +def pil2numpy(image: Image.Image): + return np.array(image).astype(np.float32) / 255.0 + + +def numpy2pil(image: np.ndarray, mode=None): + return Image.fromarray(np.clip(255.0 * image, 0, 255).astype(np.uint8), mode) + + +def pil2tensor(image: Image.Image): + return torch.from_numpy(pil2numpy(image)).unsqueeze(0) + + +def tensor2pil(image: torch.Tensor, mode=None): + return numpy2pil(image.cpu().numpy().squeeze(), mode=mode) + + +def tensor2bytes(image: torch.Tensor) -> bytes: + return tensor2pil(image).tobytes() + + +def pil2base64(image: Image.Image): + buffered = io.BytesIO() + image.save(buffered, format="PNG") + img_str = base64.b64encode(buffered.getvalue()).decode("utf-8") + return img_str diff --git a/comfyui-art-venture/modules/video/__pycache__/__init__.cpython-310.pyc b/comfyui-art-venture/modules/video/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e973180944b888316bd64136b06c8047275f43eb Binary files /dev/null and b/comfyui-art-venture/modules/video/__pycache__/__init__.cpython-310.pyc differ diff --git a/comfyui-art-venture/pyproject.toml b/comfyui-art-venture/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..8d925056198976c99394bd141fab75ffd048bc2f --- /dev/null +++ b/comfyui-art-venture/pyproject.toml @@ -0,0 +1,15 @@ +[project] +name = "comfyui-art-venture" +description = "A comprehensive set of custom nodes for ComfyUI, focusing on utilities for image processing, JSON manipulation, model operations and working with object via URLs" +version = "1.1.1" +license = "LICENSE" +dependencies = ["timm==0.6.13", "transformers", "fairscale", "pycocoevalcap", "opencv-python", "qrcode[pil]", "pytorch_lightning", "kornia", "pydantic", "segment_anything", "boto3>=1.34.101"] + +[project.urls] +Repository = "https://github.com/sipherxyz/comfyui-art-venture" +# Used by Comfy Registry https://comfyregistry.org + +[tool.comfy] +PublisherId = "protogaia" +DisplayName = "ComfyUI ArtVenture" +Icon = "https://cdn.protogaia.com/assets/gaia.png" diff --git a/comfyui-art-venture/requirements.txt b/comfyui-art-venture/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..c9ef820009f14536b493cf941eeb8f4a47eb4d12 --- /dev/null +++ b/comfyui-art-venture/requirements.txt @@ -0,0 +1,12 @@ +timm +transformers +fairscale +pycocoevalcap +opencv-python +qrcode[pil] +pytorch_lightning +kornia +pydantic +segment_anything +omegaconf +boto3>=1.34.101