`_.
+
+ Args:
+ loss_type (str, optional): Binary or multi-class loss.
+ Default: 'multi_class'. Options are "binary" and "multi_class".
+ classes (str | list[int], optional): Classes chosen to calculate loss.
+ 'all' for all classes, 'present' for classes present in labels, or
+ a list of classes to average. Default: 'present'.
+ per_image (bool, optional): If per_image is True, compute the loss per
+ image instead of per batch. Default: False.
+ reduction (str, optional): The method used to reduce the loss. Options
+ are "none", "mean" and "sum". This parameter only works when
+ per_image is True. Default: 'mean'.
+ class_weight (list[float] | str, optional): Weight of each class. If in
+ str format, read them from a file. Defaults to None.
+ loss_weight (float, optional): Weight of the loss. Defaults to 1.0.
+ """
+
+ def __init__(self,
+ loss_type='multi_class',
+ classes='present',
+ per_image=False,
+ reduction='mean',
+ class_weight=None,
+ loss_weight=1.0):
+ super(LovaszLoss, self).__init__()
+ assert loss_type in ('binary', 'multi_class'), "loss_type should be \
+ 'binary' or 'multi_class'."
+
+ if loss_type == 'binary':
+ self.cls_criterion = lovasz_hinge
+ else:
+ self.cls_criterion = lovasz_softmax
+ assert classes in ('all', 'present') or mmcv.is_list_of(classes, int)
+ if not per_image:
+ assert reduction == 'none', "reduction should be 'none' when \
+ per_image is False."
+
+ self.classes = classes
+ self.per_image = per_image
+ self.reduction = reduction
+ self.loss_weight = loss_weight
+ self.class_weight = get_class_weight(class_weight)
+
+ def forward(self,
+ cls_score,
+ label,
+ weight=None,
+ avg_factor=None,
+ reduction_override=None,
+ **kwargs):
+ """Forward function."""
+ assert reduction_override in (None, 'none', 'mean', 'sum')
+ reduction = (
+ reduction_override if reduction_override else self.reduction)
+ if self.class_weight is not None:
+ class_weight = cls_score.new_tensor(self.class_weight)
+ else:
+ class_weight = None
+
+ # if multi-class loss, transform logits to probs
+ if self.cls_criterion == lovasz_softmax:
+ cls_score = F.softmax(cls_score, dim=1)
+
+ loss_cls = self.loss_weight * self.cls_criterion(
+ cls_score,
+ label,
+ self.classes,
+ self.per_image,
+ class_weight=class_weight,
+ reduction=reduction,
+ avg_factor=avg_factor,
+ **kwargs)
+ return loss_cls
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/losses/utils.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/losses/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdfbd436d2305f82af065a853e789d6fa37614cd
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/losses/utils.py
@@ -0,0 +1,121 @@
+import functools
+
+import custom_mmpkg.custom_mmcv as mmcv
+import numpy as np
+import torch.nn.functional as F
+
+
+def get_class_weight(class_weight):
+ """Get class weight for loss function.
+
+ Args:
+ class_weight (list[float] | str | None): If class_weight is a str,
+ take it as a file name and read from it.
+ """
+ if isinstance(class_weight, str):
+ # take it as a file path
+ if class_weight.endswith('.npy'):
+ class_weight = np.load(class_weight)
+ else:
+ # pkl, json or yaml
+ class_weight = mmcv.load(class_weight)
+
+ return class_weight
+
+
+def reduce_loss(loss, reduction):
+ """Reduce loss as specified.
+
+ Args:
+ loss (Tensor): Elementwise loss tensor.
+ reduction (str): Options are "none", "mean" and "sum".
+
+ Return:
+ Tensor: Reduced loss tensor.
+ """
+ reduction_enum = F._Reduction.get_enum(reduction)
+ # none: 0, elementwise_mean:1, sum: 2
+ if reduction_enum == 0:
+ return loss
+ elif reduction_enum == 1:
+ return loss.mean()
+ elif reduction_enum == 2:
+ return loss.sum()
+
+
+def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None):
+ """Apply element-wise weight and reduce loss.
+
+ Args:
+ loss (Tensor): Element-wise loss.
+ weight (Tensor): Element-wise weights.
+ reduction (str): Same as built-in losses of PyTorch.
+ avg_factor (float): Avarage factor when computing the mean of losses.
+
+ Returns:
+ Tensor: Processed loss values.
+ """
+ # if weight is specified, apply element-wise weight
+ if weight is not None:
+ assert weight.dim() == loss.dim()
+ if weight.dim() > 1:
+ assert weight.size(1) == 1 or weight.size(1) == loss.size(1)
+ loss = loss * weight
+
+ # if avg_factor is not specified, just reduce the loss
+ if avg_factor is None:
+ loss = reduce_loss(loss, reduction)
+ else:
+ # if reduction is mean, then average the loss by avg_factor
+ if reduction == 'mean':
+ loss = loss.sum() / avg_factor
+ # if reduction is 'none', then do nothing, otherwise raise an error
+ elif reduction != 'none':
+ raise ValueError('avg_factor can not be used with reduction="sum"')
+ return loss
+
+
+def weighted_loss(loss_func):
+ """Create a weighted version of a given loss function.
+
+ To use this decorator, the loss function must have the signature like
+ `loss_func(pred, target, **kwargs)`. The function only needs to compute
+ element-wise loss without any reduction. This decorator will add weight
+ and reduction arguments to the function. The decorated function will have
+ the signature like `loss_func(pred, target, weight=None, reduction='mean',
+ avg_factor=None, **kwargs)`.
+
+ :Example:
+
+ >>> import torch
+ >>> @weighted_loss
+ >>> def l1_loss(pred, target):
+ >>> return (pred - target).abs()
+
+ >>> pred = torch.Tensor([0, 2, 3])
+ >>> target = torch.Tensor([1, 1, 1])
+ >>> weight = torch.Tensor([1, 0, 1])
+
+ >>> l1_loss(pred, target)
+ tensor(1.3333)
+ >>> l1_loss(pred, target, weight)
+ tensor(1.)
+ >>> l1_loss(pred, target, reduction='none')
+ tensor([1., 1., 2.])
+ >>> l1_loss(pred, target, weight, avg_factor=2)
+ tensor(1.5000)
+ """
+
+ @functools.wraps(loss_func)
+ def wrapper(pred,
+ target,
+ weight=None,
+ reduction='mean',
+ avg_factor=None,
+ **kwargs):
+ # get element-wise loss
+ loss = loss_func(pred, target, **kwargs)
+ loss = weight_reduce_loss(loss, weight, reduction, avg_factor)
+ return loss
+
+ return wrapper
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/necks/__init__.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/necks/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b9d3d5b3fe80247642d962edd6fb787537d01d6
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/necks/__init__.py
@@ -0,0 +1,4 @@
+from .fpn import FPN
+from .multilevel_neck import MultiLevelNeck
+
+__all__ = ['FPN', 'MultiLevelNeck']
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/necks/fpn.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/necks/fpn.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c32cc5e44f92e7779ba1ba913c2482107e5900d
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/necks/fpn.py
@@ -0,0 +1,212 @@
+import torch.nn as nn
+import torch.nn.functional as F
+from custom_mmpkg.custom_mmcv.cnn import ConvModule, xavier_init
+
+from ..builder import NECKS
+
+
+@NECKS.register_module()
+class FPN(nn.Module):
+ """Feature Pyramid Network.
+
+ This is an implementation of - Feature Pyramid Networks for Object
+ Detection (https://arxiv.org/abs/1612.03144)
+
+ Args:
+ in_channels (List[int]): Number of input channels per scale.
+ out_channels (int): Number of output channels (used at each scale)
+ num_outs (int): Number of output scales.
+ start_level (int): Index of the start input backbone level used to
+ build the feature pyramid. Default: 0.
+ end_level (int): Index of the end input backbone level (exclusive) to
+ build the feature pyramid. Default: -1, which means the last level.
+ add_extra_convs (bool | str): If bool, it decides whether to add conv
+ layers on top of the original feature maps. Default to False.
+ If True, its actual mode is specified by `extra_convs_on_inputs`.
+ If str, it specifies the source feature map of the extra convs.
+ Only the following options are allowed
+
+ - 'on_input': Last feat map of neck inputs (i.e. backbone feature).
+ - 'on_lateral': Last feature map after lateral convs.
+ - 'on_output': The last output feature map after fpn convs.
+ extra_convs_on_inputs (bool, deprecated): Whether to apply extra convs
+ on the original feature from the backbone. If True,
+ it is equivalent to `add_extra_convs='on_input'`. If False, it is
+ equivalent to set `add_extra_convs='on_output'`. Default to True.
+ relu_before_extra_convs (bool): Whether to apply relu before the extra
+ conv. Default: False.
+ no_norm_on_lateral (bool): Whether to apply norm on lateral.
+ Default: False.
+ conv_cfg (dict): Config dict for convolution layer. Default: None.
+ norm_cfg (dict): Config dict for normalization layer. Default: None.
+ act_cfg (str): Config dict for activation layer in ConvModule.
+ Default: None.
+ upsample_cfg (dict): Config dict for interpolate layer.
+ Default: `dict(mode='nearest')`
+
+ Example:
+ >>> import torch
+ >>> in_channels = [2, 3, 5, 7]
+ >>> scales = [340, 170, 84, 43]
+ >>> inputs = [torch.rand(1, c, s, s)
+ ... for c, s in zip(in_channels, scales)]
+ >>> self = FPN(in_channels, 11, len(in_channels)).eval()
+ >>> outputs = self.forward(inputs)
+ >>> for i in range(len(outputs)):
+ ... print(f'outputs[{i}].shape = {outputs[i].shape}')
+ outputs[0].shape = torch.Size([1, 11, 340, 340])
+ outputs[1].shape = torch.Size([1, 11, 170, 170])
+ outputs[2].shape = torch.Size([1, 11, 84, 84])
+ outputs[3].shape = torch.Size([1, 11, 43, 43])
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ num_outs,
+ start_level=0,
+ end_level=-1,
+ add_extra_convs=False,
+ extra_convs_on_inputs=False,
+ relu_before_extra_convs=False,
+ no_norm_on_lateral=False,
+ conv_cfg=None,
+ norm_cfg=None,
+ act_cfg=None,
+ upsample_cfg=dict(mode='nearest')):
+ super(FPN, self).__init__()
+ assert isinstance(in_channels, list)
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.num_ins = len(in_channels)
+ self.num_outs = num_outs
+ self.relu_before_extra_convs = relu_before_extra_convs
+ self.no_norm_on_lateral = no_norm_on_lateral
+ self.fp16_enabled = False
+ self.upsample_cfg = upsample_cfg.copy()
+
+ if end_level == -1:
+ self.backbone_end_level = self.num_ins
+ assert num_outs >= self.num_ins - start_level
+ else:
+ # if end_level < inputs, no extra level is allowed
+ self.backbone_end_level = end_level
+ assert end_level <= len(in_channels)
+ assert num_outs == end_level - start_level
+ self.start_level = start_level
+ self.end_level = end_level
+ self.add_extra_convs = add_extra_convs
+ assert isinstance(add_extra_convs, (str, bool))
+ if isinstance(add_extra_convs, str):
+ # Extra_convs_source choices: 'on_input', 'on_lateral', 'on_output'
+ assert add_extra_convs in ('on_input', 'on_lateral', 'on_output')
+ elif add_extra_convs: # True
+ if extra_convs_on_inputs:
+ # For compatibility with previous release
+ # TODO: deprecate `extra_convs_on_inputs`
+ self.add_extra_convs = 'on_input'
+ else:
+ self.add_extra_convs = 'on_output'
+
+ self.lateral_convs = nn.ModuleList()
+ self.fpn_convs = nn.ModuleList()
+
+ for i in range(self.start_level, self.backbone_end_level):
+ l_conv = ConvModule(
+ in_channels[i],
+ out_channels,
+ 1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg if not self.no_norm_on_lateral else None,
+ act_cfg=act_cfg,
+ inplace=False)
+ fpn_conv = ConvModule(
+ out_channels,
+ out_channels,
+ 3,
+ padding=1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg,
+ inplace=False)
+
+ self.lateral_convs.append(l_conv)
+ self.fpn_convs.append(fpn_conv)
+
+ # add extra conv layers (e.g., RetinaNet)
+ extra_levels = num_outs - self.backbone_end_level + self.start_level
+ if self.add_extra_convs and extra_levels >= 1:
+ for i in range(extra_levels):
+ if i == 0 and self.add_extra_convs == 'on_input':
+ in_channels = self.in_channels[self.backbone_end_level - 1]
+ else:
+ in_channels = out_channels
+ extra_fpn_conv = ConvModule(
+ in_channels,
+ out_channels,
+ 3,
+ stride=2,
+ padding=1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg,
+ inplace=False)
+ self.fpn_convs.append(extra_fpn_conv)
+
+ # default init_weights for conv(msra) and norm in ConvModule
+ def init_weights(self):
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ xavier_init(m, distribution='uniform')
+
+ def forward(self, inputs):
+ assert len(inputs) == len(self.in_channels)
+
+ # build laterals
+ laterals = [
+ lateral_conv(inputs[i + self.start_level])
+ for i, lateral_conv in enumerate(self.lateral_convs)
+ ]
+
+ # build top-down path
+ used_backbone_levels = len(laterals)
+ for i in range(used_backbone_levels - 1, 0, -1):
+ # In some cases, fixing `scale factor` (e.g. 2) is preferred, but
+ # it cannot co-exist with `size` in `F.interpolate`.
+ if 'scale_factor' in self.upsample_cfg:
+ laterals[i - 1] += F.interpolate(laterals[i],
+ **self.upsample_cfg)
+ else:
+ prev_shape = laterals[i - 1].shape[2:]
+ laterals[i - 1] += F.interpolate(
+ laterals[i], size=prev_shape, **self.upsample_cfg)
+
+ # build outputs
+ # part 1: from original levels
+ outs = [
+ self.fpn_convs[i](laterals[i]) for i in range(used_backbone_levels)
+ ]
+ # part 2: add extra levels
+ if self.num_outs > len(outs):
+ # use max pool to get more levels on top of outputs
+ # (e.g., Faster R-CNN, Mask R-CNN)
+ if not self.add_extra_convs:
+ for i in range(self.num_outs - used_backbone_levels):
+ outs.append(F.max_pool2d(outs[-1], 1, stride=2))
+ # add conv layers on top of original feature maps (RetinaNet)
+ else:
+ if self.add_extra_convs == 'on_input':
+ extra_source = inputs[self.backbone_end_level - 1]
+ elif self.add_extra_convs == 'on_lateral':
+ extra_source = laterals[-1]
+ elif self.add_extra_convs == 'on_output':
+ extra_source = outs[-1]
+ else:
+ raise NotImplementedError
+ outs.append(self.fpn_convs[used_backbone_levels](extra_source))
+ for i in range(used_backbone_levels + 1, self.num_outs):
+ if self.relu_before_extra_convs:
+ outs.append(self.fpn_convs[i](F.relu(outs[-1])))
+ else:
+ outs.append(self.fpn_convs[i](outs[-1]))
+ return tuple(outs)
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/necks/multilevel_neck.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/necks/multilevel_neck.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce5e8563f7d7b27944fbad2c247f789967433bba
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/necks/multilevel_neck.py
@@ -0,0 +1,70 @@
+import torch.nn as nn
+import torch.nn.functional as F
+from custom_mmpkg.custom_mmcv.cnn import ConvModule
+
+from ..builder import NECKS
+
+
+@NECKS.register_module()
+class MultiLevelNeck(nn.Module):
+ """MultiLevelNeck.
+
+ A neck structure connect vit backbone and decoder_heads.
+ Args:
+ in_channels (List[int]): Number of input channels per scale.
+ out_channels (int): Number of output channels (used at each scale).
+ scales (List[int]): Scale factors for each input feature map.
+ norm_cfg (dict): Config dict for normalization layer. Default: None.
+ act_cfg (dict): Config dict for activation layer in ConvModule.
+ Default: None.
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ scales=[0.5, 1, 2, 4],
+ norm_cfg=None,
+ act_cfg=None):
+ super(MultiLevelNeck, self).__init__()
+ assert isinstance(in_channels, list)
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.scales = scales
+ self.num_outs = len(scales)
+ self.lateral_convs = nn.ModuleList()
+ self.convs = nn.ModuleList()
+ for in_channel in in_channels:
+ self.lateral_convs.append(
+ ConvModule(
+ in_channel,
+ out_channels,
+ kernel_size=1,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg))
+ for _ in range(self.num_outs):
+ self.convs.append(
+ ConvModule(
+ out_channels,
+ out_channels,
+ kernel_size=3,
+ padding=1,
+ stride=1,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg))
+
+ def forward(self, inputs):
+ assert len(inputs) == len(self.in_channels)
+ print(inputs[0].shape)
+ inputs = [
+ lateral_conv(inputs[i])
+ for i, lateral_conv in enumerate(self.lateral_convs)
+ ]
+ # for len(inputs) not equal to self.num_outs
+ if len(inputs) == 1:
+ inputs = [inputs[0] for _ in range(self.num_outs)]
+ outs = []
+ for i in range(self.num_outs):
+ x_resize = F.interpolate(
+ inputs[i], scale_factor=self.scales[i], mode='bilinear')
+ outs.append(self.convs[i](x_resize))
+ return tuple(outs)
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/segmentors/__init__.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/segmentors/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..dca2f09405330743c476e190896bee39c45498ea
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/segmentors/__init__.py
@@ -0,0 +1,5 @@
+from .base import BaseSegmentor
+from .cascade_encoder_decoder import CascadeEncoderDecoder
+from .encoder_decoder import EncoderDecoder
+
+__all__ = ['BaseSegmentor', 'EncoderDecoder', 'CascadeEncoderDecoder']
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/segmentors/base.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/segmentors/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..5fd073f4a9d7713f02b107b7ad541384c3d27d6b
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/segmentors/base.py
@@ -0,0 +1,273 @@
+import logging
+import warnings
+from abc import ABCMeta, abstractmethod
+from collections import OrderedDict
+
+import custom_mmpkg.custom_mmcv as mmcv
+import numpy as np
+import torch
+import torch.distributed as dist
+import torch.nn as nn
+from custom_mmpkg.custom_mmcv.runner import auto_fp16
+
+
+class BaseSegmentor(nn.Module):
+ """Base class for segmentors."""
+
+ __metaclass__ = ABCMeta
+
+ def __init__(self):
+ super(BaseSegmentor, self).__init__()
+ self.fp16_enabled = False
+
+ @property
+ def with_neck(self):
+ """bool: whether the segmentor has neck"""
+ return hasattr(self, 'neck') and self.neck is not None
+
+ @property
+ def with_auxiliary_head(self):
+ """bool: whether the segmentor has auxiliary head"""
+ return hasattr(self,
+ 'auxiliary_head') and self.auxiliary_head is not None
+
+ @property
+ def with_decode_head(self):
+ """bool: whether the segmentor has decode head"""
+ return hasattr(self, 'decode_head') and self.decode_head is not None
+
+ @abstractmethod
+ def extract_feat(self, imgs):
+ """Placeholder for extract features from images."""
+ pass
+
+ @abstractmethod
+ def encode_decode(self, img, img_metas):
+ """Placeholder for encode images with backbone and decode into a
+ semantic segmentation map of the same size as input."""
+ pass
+
+ @abstractmethod
+ def forward_train(self, imgs, img_metas, **kwargs):
+ """Placeholder for Forward function for training."""
+ pass
+
+ @abstractmethod
+ def simple_test(self, img, img_meta, **kwargs):
+ """Placeholder for single image test."""
+ pass
+
+ @abstractmethod
+ def aug_test(self, imgs, img_metas, **kwargs):
+ """Placeholder for augmentation test."""
+ pass
+
+ def init_weights(self, pretrained=None):
+ """Initialize the weights in segmentor.
+
+ Args:
+ pretrained (str, optional): Path to pre-trained weights.
+ Defaults to None.
+ """
+ if pretrained is not None:
+ logger = logging.getLogger()
+ logger.info(f'load model from: {pretrained}')
+
+ def forward_test(self, imgs, img_metas, **kwargs):
+ """
+ Args:
+ imgs (List[Tensor]): the outer list indicates test-time
+ augmentations and inner Tensor should have a shape NxCxHxW,
+ which contains all images in the batch.
+ img_metas (List[List[dict]]): the outer list indicates test-time
+ augs (multiscale, flip, etc.) and the inner list indicates
+ images in a batch.
+ """
+ for var, name in [(imgs, 'imgs'), (img_metas, 'img_metas')]:
+ if not isinstance(var, list):
+ raise TypeError(f'{name} must be a list, but got '
+ f'{type(var)}')
+
+ num_augs = len(imgs)
+ if num_augs != len(img_metas):
+ raise ValueError(f'num of augmentations ({len(imgs)}) != '
+ f'num of image meta ({len(img_metas)})')
+ # all images in the same aug batch all of the same ori_shape and pad
+ # shape
+ for img_meta in img_metas:
+ ori_shapes = [_['ori_shape'] for _ in img_meta]
+ assert all(shape == ori_shapes[0] for shape in ori_shapes)
+ img_shapes = [_['img_shape'] for _ in img_meta]
+ assert all(shape == img_shapes[0] for shape in img_shapes)
+ pad_shapes = [_['pad_shape'] for _ in img_meta]
+ assert all(shape == pad_shapes[0] for shape in pad_shapes)
+
+ if num_augs == 1:
+ return self.simple_test(imgs[0], img_metas[0], **kwargs)
+ else:
+ return self.aug_test(imgs, img_metas, **kwargs)
+
+ @auto_fp16(apply_to=('img', ))
+ def forward(self, img, img_metas, return_loss=True, **kwargs):
+ """Calls either :func:`forward_train` or :func:`forward_test` depending
+ on whether ``return_loss`` is ``True``.
+
+ Note this setting will change the expected inputs. When
+ ``return_loss=True``, img and img_meta are single-nested (i.e. Tensor
+ and List[dict]), and when ``resturn_loss=False``, img and img_meta
+ should be double nested (i.e. List[Tensor], List[List[dict]]), with
+ the outer list indicating test time augmentations.
+ """
+ if return_loss:
+ return self.forward_train(img, img_metas, **kwargs)
+ else:
+ return self.forward_test(img, img_metas, **kwargs)
+
+ def train_step(self, data_batch, optimizer, **kwargs):
+ """The iteration step during training.
+
+ This method defines an iteration step during training, except for the
+ back propagation and optimizer updating, which are done in an optimizer
+ hook. Note that in some complicated cases or models, the whole process
+ including back propagation and optimizer updating is also defined in
+ this method, such as GAN.
+
+ Args:
+ data (dict): The output of dataloader.
+ optimizer (:obj:`torch.optim.Optimizer` | dict): The optimizer of
+ runner is passed to ``train_step()``. This argument is unused
+ and reserved.
+
+ Returns:
+ dict: It should contain at least 3 keys: ``loss``, ``log_vars``,
+ ``num_samples``.
+ ``loss`` is a tensor for back propagation, which can be a
+ weighted sum of multiple losses.
+ ``log_vars`` contains all the variables to be sent to the
+ logger.
+ ``num_samples`` indicates the batch size (when the model is
+ DDP, it means the batch size on each GPU), which is used for
+ averaging the logs.
+ """
+ losses = self(**data_batch)
+ loss, log_vars = self._parse_losses(losses)
+
+ outputs = dict(
+ loss=loss,
+ log_vars=log_vars,
+ num_samples=len(data_batch['img_metas']))
+
+ return outputs
+
+ def val_step(self, data_batch, **kwargs):
+ """The iteration step during validation.
+
+ This method shares the same signature as :func:`train_step`, but used
+ during val epochs. Note that the evaluation after training epochs is
+ not implemented with this method, but an evaluation hook.
+ """
+ output = self(**data_batch, **kwargs)
+ return output
+
+ @staticmethod
+ def _parse_losses(losses):
+ """Parse the raw outputs (losses) of the network.
+
+ Args:
+ losses (dict): Raw output of the network, which usually contain
+ losses and other necessary information.
+
+ Returns:
+ tuple[Tensor, dict]: (loss, log_vars), loss is the loss tensor
+ which may be a weighted sum of all losses, log_vars contains
+ all the variables to be sent to the logger.
+ """
+ log_vars = OrderedDict()
+ for loss_name, loss_value in losses.items():
+ if isinstance(loss_value, torch.Tensor):
+ log_vars[loss_name] = loss_value.mean()
+ elif isinstance(loss_value, list):
+ log_vars[loss_name] = sum(_loss.mean() for _loss in loss_value)
+ else:
+ raise TypeError(
+ f'{loss_name} is not a tensor or list of tensors')
+
+ loss = sum(_value for _key, _value in log_vars.items()
+ if 'loss' in _key)
+
+ log_vars['loss'] = loss
+ for loss_name, loss_value in log_vars.items():
+ # reduce loss when distributed training
+ if dist.is_available() and dist.is_initialized():
+ loss_value = loss_value.data.clone()
+ dist.all_reduce(loss_value.div_(dist.get_world_size()))
+ log_vars[loss_name] = loss_value.item()
+
+ return loss, log_vars
+
+ def show_result(self,
+ img,
+ result,
+ palette=None,
+ win_name='',
+ show=False,
+ wait_time=0,
+ out_file=None,
+ opacity=0.5):
+ """Draw `result` over `img`.
+
+ Args:
+ img (str or Tensor): The image to be displayed.
+ result (Tensor): The semantic segmentation results to draw over
+ `img`.
+ palette (list[list[int]]] | np.ndarray | None): The palette of
+ segmentation map. If None is given, random palette will be
+ generated. Default: None
+ win_name (str): The window name.
+ wait_time (int): Value of waitKey param.
+ Default: 0.
+ show (bool): Whether to show the image.
+ Default: False.
+ out_file (str or None): The filename to write the image.
+ Default: None.
+ opacity(float): Opacity of painted segmentation map.
+ Default 0.5.
+ Must be in (0, 1] range.
+ Returns:
+ img (Tensor): Only if not `show` or `out_file`
+ """
+ img = mmcv.imread(img)
+ img = img.copy()
+ seg = result[0]
+ if palette is None:
+ if self.PALETTE is None:
+ palette = np.random.randint(
+ 0, 255, size=(len(self.CLASSES), 3))
+ else:
+ palette = self.PALETTE
+ palette = np.array(palette)
+ assert palette.shape[0] == len(self.CLASSES)
+ assert palette.shape[1] == 3
+ assert len(palette.shape) == 2
+ assert 0 < opacity <= 1.0
+ color_seg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype=np.uint8)
+ for label, color in enumerate(palette):
+ color_seg[seg == label, :] = color
+ # convert to BGR
+ color_seg = color_seg[..., ::-1]
+
+ img = img * (1 - opacity) + color_seg * opacity
+ img = img.astype(np.uint8)
+ # if out_file specified, do not show image in window
+ if out_file is not None:
+ show = False
+
+ if show:
+ mmcv.imshow(img, win_name, wait_time)
+ if out_file is not None:
+ mmcv.imwrite(img, out_file)
+
+ if not (show or out_file):
+ warnings.warn('show==False and out_file is not specified, only '
+ 'result image will be returned')
+ return img
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/segmentors/cascade_encoder_decoder.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/segmentors/cascade_encoder_decoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdece0ac89713a0cead10d98959bad2e2d05c4e7
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/segmentors/cascade_encoder_decoder.py
@@ -0,0 +1,98 @@
+from torch import nn
+
+from custom_mmpkg.custom_mmseg.core import add_prefix
+from custom_mmpkg.custom_mmseg.ops import resize
+from .. import builder
+from ..builder import SEGMENTORS
+from .encoder_decoder import EncoderDecoder
+
+
+@SEGMENTORS.register_module()
+class CascadeEncoderDecoder(EncoderDecoder):
+ """Cascade Encoder Decoder segmentors.
+
+ CascadeEncoderDecoder almost the same as EncoderDecoder, while decoders of
+ CascadeEncoderDecoder are cascaded. The output of previous decoder_head
+ will be the input of next decoder_head.
+ """
+
+ def __init__(self,
+ num_stages,
+ backbone,
+ decode_head,
+ neck=None,
+ auxiliary_head=None,
+ train_cfg=None,
+ test_cfg=None,
+ pretrained=None):
+ self.num_stages = num_stages
+ super(CascadeEncoderDecoder, self).__init__(
+ backbone=backbone,
+ decode_head=decode_head,
+ neck=neck,
+ auxiliary_head=auxiliary_head,
+ train_cfg=train_cfg,
+ test_cfg=test_cfg,
+ pretrained=pretrained)
+
+ def _init_decode_head(self, decode_head):
+ """Initialize ``decode_head``"""
+ assert isinstance(decode_head, list)
+ assert len(decode_head) == self.num_stages
+ self.decode_head = nn.ModuleList()
+ for i in range(self.num_stages):
+ self.decode_head.append(builder.build_head(decode_head[i]))
+ self.align_corners = self.decode_head[-1].align_corners
+ self.num_classes = self.decode_head[-1].num_classes
+
+ def init_weights(self, pretrained=None):
+ """Initialize the weights in backbone and heads.
+
+ Args:
+ pretrained (str, optional): Path to pre-trained weights.
+ Defaults to None.
+ """
+ self.backbone.init_weights(pretrained=pretrained)
+ for i in range(self.num_stages):
+ self.decode_head[i].init_weights()
+ if self.with_auxiliary_head:
+ if isinstance(self.auxiliary_head, nn.ModuleList):
+ for aux_head in self.auxiliary_head:
+ aux_head.init_weights()
+ else:
+ self.auxiliary_head.init_weights()
+
+ def encode_decode(self, img, img_metas):
+ """Encode images with backbone and decode into a semantic segmentation
+ map of the same size as input."""
+ x = self.extract_feat(img)
+ out = self.decode_head[0].forward_test(x, img_metas, self.test_cfg)
+ for i in range(1, self.num_stages):
+ out = self.decode_head[i].forward_test(x, out, img_metas,
+ self.test_cfg)
+ out = resize(
+ input=out,
+ size=img.shape[2:],
+ mode='bilinear',
+ align_corners=self.align_corners)
+ return out
+
+ def _decode_head_forward_train(self, x, img_metas, gt_semantic_seg):
+ """Run forward function and calculate loss for decode head in
+ training."""
+ losses = dict()
+
+ loss_decode = self.decode_head[0].forward_train(
+ x, img_metas, gt_semantic_seg, self.train_cfg)
+
+ losses.update(add_prefix(loss_decode, 'decode_0'))
+
+ for i in range(1, self.num_stages):
+ # forward test again, maybe unnecessary for most methods.
+ prev_outputs = self.decode_head[i - 1].forward_test(
+ x, img_metas, self.test_cfg)
+ loss_decode = self.decode_head[i].forward_train(
+ x, prev_outputs, img_metas, gt_semantic_seg, self.train_cfg)
+ losses.update(add_prefix(loss_decode, f'decode_{i}'))
+
+ return losses
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/segmentors/encoder_decoder.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/segmentors/encoder_decoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8e42be53aba4b492efec32877bfe4c6a7a1e2aa
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/segmentors/encoder_decoder.py
@@ -0,0 +1,298 @@
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from custom_mmpkg.custom_mmseg.core import add_prefix
+from custom_mmpkg.custom_mmseg.ops import resize
+from .. import builder
+from ..builder import SEGMENTORS
+from .base import BaseSegmentor
+
+
+@SEGMENTORS.register_module()
+class EncoderDecoder(BaseSegmentor):
+ """Encoder Decoder segmentors.
+
+ EncoderDecoder typically consists of backbone, decode_head, auxiliary_head.
+ Note that auxiliary_head is only used for deep supervision during training,
+ which could be dumped during inference.
+ """
+
+ def __init__(self,
+ backbone,
+ decode_head,
+ neck=None,
+ auxiliary_head=None,
+ train_cfg=None,
+ test_cfg=None,
+ pretrained=None):
+ super(EncoderDecoder, self).__init__()
+ self.backbone = builder.build_backbone(backbone)
+ if neck is not None:
+ self.neck = builder.build_neck(neck)
+ self._init_decode_head(decode_head)
+ self._init_auxiliary_head(auxiliary_head)
+
+ self.train_cfg = train_cfg
+ self.test_cfg = test_cfg
+
+ self.init_weights(pretrained=pretrained)
+
+ assert self.with_decode_head
+
+ def _init_decode_head(self, decode_head):
+ """Initialize ``decode_head``"""
+ self.decode_head = builder.build_head(decode_head)
+ self.align_corners = self.decode_head.align_corners
+ self.num_classes = self.decode_head.num_classes
+
+ def _init_auxiliary_head(self, auxiliary_head):
+ """Initialize ``auxiliary_head``"""
+ if auxiliary_head is not None:
+ if isinstance(auxiliary_head, list):
+ self.auxiliary_head = nn.ModuleList()
+ for head_cfg in auxiliary_head:
+ self.auxiliary_head.append(builder.build_head(head_cfg))
+ else:
+ self.auxiliary_head = builder.build_head(auxiliary_head)
+
+ def init_weights(self, pretrained=None):
+ """Initialize the weights in backbone and heads.
+
+ Args:
+ pretrained (str, optional): Path to pre-trained weights.
+ Defaults to None.
+ """
+
+ super(EncoderDecoder, self).init_weights(pretrained)
+ self.backbone.init_weights(pretrained=pretrained)
+ self.decode_head.init_weights()
+ if self.with_auxiliary_head:
+ if isinstance(self.auxiliary_head, nn.ModuleList):
+ for aux_head in self.auxiliary_head:
+ aux_head.init_weights()
+ else:
+ self.auxiliary_head.init_weights()
+
+ def extract_feat(self, img):
+ """Extract features from images."""
+ x = self.backbone(img)
+ if self.with_neck:
+ x = self.neck(x)
+ return x
+
+ def encode_decode(self, img, img_metas):
+ """Encode images with backbone and decode into a semantic segmentation
+ map of the same size as input."""
+ x = self.extract_feat(img)
+ out = self._decode_head_forward_test(x, img_metas)
+ out = resize(
+ input=out,
+ size=img.shape[2:],
+ mode='bilinear',
+ align_corners=self.align_corners)
+ return out
+
+ def _decode_head_forward_train(self, x, img_metas, gt_semantic_seg):
+ """Run forward function and calculate loss for decode head in
+ training."""
+ losses = dict()
+ loss_decode = self.decode_head.forward_train(x, img_metas,
+ gt_semantic_seg,
+ self.train_cfg)
+
+ losses.update(add_prefix(loss_decode, 'decode'))
+ return losses
+
+ def _decode_head_forward_test(self, x, img_metas):
+ """Run forward function and calculate loss for decode head in
+ inference."""
+ seg_logits = self.decode_head.forward_test(x, img_metas, self.test_cfg)
+ return seg_logits
+
+ def _auxiliary_head_forward_train(self, x, img_metas, gt_semantic_seg):
+ """Run forward function and calculate loss for auxiliary head in
+ training."""
+ losses = dict()
+ if isinstance(self.auxiliary_head, nn.ModuleList):
+ for idx, aux_head in enumerate(self.auxiliary_head):
+ loss_aux = aux_head.forward_train(x, img_metas,
+ gt_semantic_seg,
+ self.train_cfg)
+ losses.update(add_prefix(loss_aux, f'aux_{idx}'))
+ else:
+ loss_aux = self.auxiliary_head.forward_train(
+ x, img_metas, gt_semantic_seg, self.train_cfg)
+ losses.update(add_prefix(loss_aux, 'aux'))
+
+ return losses
+
+ def forward_dummy(self, img):
+ """Dummy forward function."""
+ seg_logit = self.encode_decode(img, None)
+
+ return seg_logit
+
+ def forward_train(self, img, img_metas, gt_semantic_seg):
+ """Forward function for training.
+
+ Args:
+ img (Tensor): Input images.
+ img_metas (list[dict]): List of image info dict where each dict
+ has: 'img_shape', 'scale_factor', 'flip', and may also contain
+ 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.
+ For details on the values of these keys see
+ `mmseg/datasets/pipelines/formatting.py:Collect`.
+ gt_semantic_seg (Tensor): Semantic segmentation masks
+ used if the architecture supports semantic segmentation task.
+
+ Returns:
+ dict[str, Tensor]: a dictionary of loss components
+ """
+
+ x = self.extract_feat(img)
+
+ losses = dict()
+
+ loss_decode = self._decode_head_forward_train(x, img_metas,
+ gt_semantic_seg)
+ losses.update(loss_decode)
+
+ if self.with_auxiliary_head:
+ loss_aux = self._auxiliary_head_forward_train(
+ x, img_metas, gt_semantic_seg)
+ losses.update(loss_aux)
+
+ return losses
+
+ # TODO refactor
+ def slide_inference(self, img, img_meta, rescale):
+ """Inference by sliding-window with overlap.
+
+ If h_crop > h_img or w_crop > w_img, the small patch will be used to
+ decode without padding.
+ """
+
+ h_stride, w_stride = self.test_cfg.stride
+ h_crop, w_crop = self.test_cfg.crop_size
+ batch_size, _, h_img, w_img = img.size()
+ num_classes = self.num_classes
+ h_grids = max(h_img - h_crop + h_stride - 1, 0) // h_stride + 1
+ w_grids = max(w_img - w_crop + w_stride - 1, 0) // w_stride + 1
+ preds = img.new_zeros((batch_size, num_classes, h_img, w_img))
+ count_mat = img.new_zeros((batch_size, 1, h_img, w_img))
+ for h_idx in range(h_grids):
+ for w_idx in range(w_grids):
+ y1 = h_idx * h_stride
+ x1 = w_idx * w_stride
+ y2 = min(y1 + h_crop, h_img)
+ x2 = min(x1 + w_crop, w_img)
+ y1 = max(y2 - h_crop, 0)
+ x1 = max(x2 - w_crop, 0)
+ crop_img = img[:, :, y1:y2, x1:x2]
+ crop_seg_logit = self.encode_decode(crop_img, img_meta)
+ preds += F.pad(crop_seg_logit,
+ (int(x1), int(preds.shape[3] - x2), int(y1),
+ int(preds.shape[2] - y2)))
+
+ count_mat[:, :, y1:y2, x1:x2] += 1
+ assert (count_mat == 0).sum() == 0
+ if torch.onnx.is_in_onnx_export():
+ # cast count_mat to constant while exporting to ONNX
+ count_mat = torch.from_numpy(
+ count_mat.cpu().detach().numpy()).to(device=img.device)
+ preds = preds / count_mat
+ if rescale:
+ preds = resize(
+ preds,
+ size=img_meta[0]['ori_shape'][:2],
+ mode='bilinear',
+ align_corners=self.align_corners,
+ warning=False)
+ return preds
+
+ def whole_inference(self, img, img_meta, rescale):
+ """Inference with full image."""
+
+ seg_logit = self.encode_decode(img, img_meta)
+ if rescale:
+ # support dynamic shape for onnx
+ if torch.onnx.is_in_onnx_export():
+ size = img.shape[2:]
+ else:
+ size = img_meta[0]['ori_shape'][:2]
+ seg_logit = resize(
+ seg_logit,
+ size=size,
+ mode='bilinear',
+ align_corners=self.align_corners,
+ warning=False)
+
+ return seg_logit
+
+ def inference(self, img, img_meta, rescale):
+ """Inference with slide/whole style.
+
+ Args:
+ img (Tensor): The input image of shape (N, 3, H, W).
+ img_meta (dict): Image info dict where each dict has: 'img_shape',
+ 'scale_factor', 'flip', and may also contain
+ 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.
+ For details on the values of these keys see
+ `mmseg/datasets/pipelines/formatting.py:Collect`.
+ rescale (bool): Whether rescale back to original shape.
+
+ Returns:
+ Tensor: The output segmentation map.
+ """
+
+ assert self.test_cfg.mode in ['slide', 'whole']
+ ori_shape = img_meta[0]['ori_shape']
+ assert all(_['ori_shape'] == ori_shape for _ in img_meta)
+ if self.test_cfg.mode == 'slide':
+ seg_logit = self.slide_inference(img, img_meta, rescale)
+ else:
+ seg_logit = self.whole_inference(img, img_meta, rescale)
+ output = F.softmax(seg_logit, dim=1)
+ flip = img_meta[0]['flip']
+ if flip:
+ flip_direction = img_meta[0]['flip_direction']
+ assert flip_direction in ['horizontal', 'vertical']
+ if flip_direction == 'horizontal':
+ output = output.flip(dims=(3, ))
+ elif flip_direction == 'vertical':
+ output = output.flip(dims=(2, ))
+
+ return output
+
+ def simple_test(self, img, img_meta, rescale=True):
+ """Simple test with single image."""
+ seg_logit = self.inference(img, img_meta, rescale)
+ seg_pred = seg_logit.argmax(dim=1)
+ if torch.onnx.is_in_onnx_export():
+ # our inference backend only support 4D output
+ seg_pred = seg_pred.unsqueeze(0)
+ return seg_pred
+ seg_pred = seg_pred.cpu().numpy()
+ # unravel batch dim
+ seg_pred = list(seg_pred)
+ return seg_pred
+
+ def aug_test(self, imgs, img_metas, rescale=True):
+ """Test with augmentations.
+
+ Only rescale=True is supported.
+ """
+ # aug_test rescale all imgs back to ori_shape for now
+ assert rescale
+ # to save memory, we get augmented seg logit inplace
+ seg_logit = self.inference(imgs[0], img_metas[0], rescale)
+ for i in range(1, len(imgs)):
+ cur_seg_logit = self.inference(imgs[i], img_metas[i], rescale)
+ seg_logit += cur_seg_logit
+ seg_logit /= len(imgs)
+ seg_pred = seg_logit.argmax(dim=1)
+ seg_pred = seg_pred.cpu().numpy()
+ # unravel batch dim
+ seg_pred = list(seg_pred)
+ return seg_pred
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/__init__.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d3bdd349b9f2ae499a2fcb2ac1d2e3c77befebe
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/__init__.py
@@ -0,0 +1,13 @@
+from .drop import DropPath
+from .inverted_residual import InvertedResidual, InvertedResidualV3
+from .make_divisible import make_divisible
+from .res_layer import ResLayer
+from .se_layer import SELayer
+from .self_attention_block import SelfAttentionBlock
+from .up_conv_block import UpConvBlock
+from .weight_init import trunc_normal_
+
+__all__ = [
+ 'ResLayer', 'SelfAttentionBlock', 'make_divisible', 'InvertedResidual',
+ 'UpConvBlock', 'InvertedResidualV3', 'SELayer', 'DropPath', 'trunc_normal_'
+]
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/drop.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/drop.py
new file mode 100644
index 0000000000000000000000000000000000000000..4520b0ff407d2a95a864086bdbca0065f222aa63
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/drop.py
@@ -0,0 +1,31 @@
+"""Modified from https://github.com/rwightman/pytorch-image-
+models/blob/master/timm/models/layers/drop.py."""
+
+import torch
+from torch import nn
+
+
+class DropPath(nn.Module):
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of
+ residual blocks).
+
+ Args:
+ drop_prob (float): Drop rate for paths of model. Dropout rate has
+ to be between 0 and 1. Default: 0.
+ """
+
+ def __init__(self, drop_prob=0.):
+ super(DropPath, self).__init__()
+ self.drop_prob = drop_prob
+ self.keep_prob = 1 - drop_prob
+
+ def forward(self, x):
+ if self.drop_prob == 0. or not self.training:
+ return x
+ shape = (x.shape[0], ) + (1, ) * (
+ x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
+ random_tensor = self.keep_prob + torch.rand(
+ shape, dtype=x.dtype, device=x.device)
+ random_tensor.floor_() # binarize
+ output = x.div(self.keep_prob) * random_tensor
+ return output
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/inverted_residual.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/inverted_residual.py
new file mode 100644
index 0000000000000000000000000000000000000000..0fb93391f83c15c91cca833a296b922380607e66
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/inverted_residual.py
@@ -0,0 +1,208 @@
+from custom_mmpkg.custom_mmcv.cnn import ConvModule
+from torch import nn
+from torch.utils import checkpoint as cp
+
+from .se_layer import SELayer
+
+
+class InvertedResidual(nn.Module):
+ """InvertedResidual block for MobileNetV2.
+
+ Args:
+ in_channels (int): The input channels of the InvertedResidual block.
+ out_channels (int): The output channels of the InvertedResidual block.
+ stride (int): Stride of the middle (first) 3x3 convolution.
+ expand_ratio (int): Adjusts number of channels of the hidden layer
+ in InvertedResidual by this amount.
+ dilation (int): Dilation rate of depthwise conv. Default: 1
+ conv_cfg (dict): Config dict for convolution layer.
+ Default: None, which means using conv2d.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: dict(type='BN').
+ act_cfg (dict): Config dict for activation layer.
+ Default: dict(type='ReLU6').
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed. Default: False.
+
+ Returns:
+ Tensor: The output tensor.
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ stride,
+ expand_ratio,
+ dilation=1,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ act_cfg=dict(type='ReLU6'),
+ with_cp=False):
+ super(InvertedResidual, self).__init__()
+ self.stride = stride
+ assert stride in [1, 2], f'stride must in [1, 2]. ' \
+ f'But received {stride}.'
+ self.with_cp = with_cp
+ self.use_res_connect = self.stride == 1 and in_channels == out_channels
+ hidden_dim = int(round(in_channels * expand_ratio))
+
+ layers = []
+ if expand_ratio != 1:
+ layers.append(
+ ConvModule(
+ in_channels=in_channels,
+ out_channels=hidden_dim,
+ kernel_size=1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg))
+ layers.extend([
+ ConvModule(
+ in_channels=hidden_dim,
+ out_channels=hidden_dim,
+ kernel_size=3,
+ stride=stride,
+ padding=dilation,
+ dilation=dilation,
+ groups=hidden_dim,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg),
+ ConvModule(
+ in_channels=hidden_dim,
+ out_channels=out_channels,
+ kernel_size=1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=None)
+ ])
+ self.conv = nn.Sequential(*layers)
+
+ def forward(self, x):
+
+ def _inner_forward(x):
+ if self.use_res_connect:
+ return x + self.conv(x)
+ else:
+ return self.conv(x)
+
+ if self.with_cp and x.requires_grad:
+ out = cp.checkpoint(_inner_forward, x)
+ else:
+ out = _inner_forward(x)
+
+ return out
+
+
+class InvertedResidualV3(nn.Module):
+ """Inverted Residual Block for MobileNetV3.
+
+ Args:
+ in_channels (int): The input channels of this Module.
+ out_channels (int): The output channels of this Module.
+ mid_channels (int): The input channels of the depthwise convolution.
+ kernel_size (int): The kernel size of the depthwise convolution.
+ Default: 3.
+ stride (int): The stride of the depthwise convolution. Default: 1.
+ se_cfg (dict): Config dict for se layer. Default: None, which means no
+ se layer.
+ with_expand_conv (bool): Use expand conv or not. If set False,
+ mid_channels must be the same with in_channels. Default: True.
+ conv_cfg (dict): Config dict for convolution layer. Default: None,
+ which means using conv2d.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: dict(type='BN').
+ act_cfg (dict): Config dict for activation layer.
+ Default: dict(type='ReLU').
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed. Default: False.
+
+ Returns:
+ Tensor: The output tensor.
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ mid_channels,
+ kernel_size=3,
+ stride=1,
+ se_cfg=None,
+ with_expand_conv=True,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ act_cfg=dict(type='ReLU'),
+ with_cp=False):
+ super(InvertedResidualV3, self).__init__()
+ self.with_res_shortcut = (stride == 1 and in_channels == out_channels)
+ assert stride in [1, 2]
+ self.with_cp = with_cp
+ self.with_se = se_cfg is not None
+ self.with_expand_conv = with_expand_conv
+
+ if self.with_se:
+ assert isinstance(se_cfg, dict)
+ if not self.with_expand_conv:
+ assert mid_channels == in_channels
+
+ if self.with_expand_conv:
+ self.expand_conv = ConvModule(
+ in_channels=in_channels,
+ out_channels=mid_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg)
+ self.depthwise_conv = ConvModule(
+ in_channels=mid_channels,
+ out_channels=mid_channels,
+ kernel_size=kernel_size,
+ stride=stride,
+ padding=kernel_size // 2,
+ groups=mid_channels,
+ conv_cfg=dict(
+ type='Conv2dAdaptivePadding') if stride == 2 else conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg)
+
+ if self.with_se:
+ self.se = SELayer(**se_cfg)
+
+ self.linear_conv = ConvModule(
+ in_channels=mid_channels,
+ out_channels=out_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=None)
+
+ def forward(self, x):
+
+ def _inner_forward(x):
+ out = x
+
+ if self.with_expand_conv:
+ out = self.expand_conv(out)
+
+ out = self.depthwise_conv(out)
+
+ if self.with_se:
+ out = self.se(out)
+
+ out = self.linear_conv(out)
+
+ if self.with_res_shortcut:
+ return x + out
+ else:
+ return out
+
+ if self.with_cp and x.requires_grad:
+ out = cp.checkpoint(_inner_forward, x)
+ else:
+ out = _inner_forward(x)
+
+ return out
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/make_divisible.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/make_divisible.py
new file mode 100644
index 0000000000000000000000000000000000000000..75ad756052529f52fe83bb95dd1f0ecfc9a13078
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/make_divisible.py
@@ -0,0 +1,27 @@
+def make_divisible(value, divisor, min_value=None, min_ratio=0.9):
+ """Make divisible function.
+
+ This function rounds the channel number to the nearest value that can be
+ divisible by the divisor. It is taken from the original tf repo. It ensures
+ that all layers have a channel number that is divisible by divisor. It can
+ be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py # noqa
+
+ Args:
+ value (int): The original channel number.
+ divisor (int): The divisor to fully divide the channel number.
+ min_value (int): The minimum value of the output channel.
+ Default: None, means that the minimum value equal to the divisor.
+ min_ratio (float): The minimum ratio of the rounded channel number to
+ the original channel number. Default: 0.9.
+
+ Returns:
+ int: The modified output channel number.
+ """
+
+ if min_value is None:
+ min_value = divisor
+ new_value = max(min_value, int(value + divisor / 2) // divisor * divisor)
+ # Make sure that round down does not go down by more than (1-min_ratio).
+ if new_value < min_ratio * value:
+ new_value += divisor
+ return new_value
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/res_layer.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/res_layer.py
new file mode 100644
index 0000000000000000000000000000000000000000..1379e62e7c6e591fae25e57d548c5f735e3ad33a
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/res_layer.py
@@ -0,0 +1,94 @@
+from custom_mmpkg.custom_mmcv.cnn import build_conv_layer, build_norm_layer
+from torch import nn as nn
+
+
+class ResLayer(nn.Sequential):
+ """ResLayer to build ResNet style backbone.
+
+ Args:
+ block (nn.Module): block used to build ResLayer.
+ inplanes (int): inplanes of block.
+ planes (int): planes of block.
+ num_blocks (int): number of blocks.
+ stride (int): stride of the first block. Default: 1
+ avg_down (bool): Use AvgPool instead of stride conv when
+ downsampling in the bottleneck. Default: False
+ conv_cfg (dict): dictionary to construct and config conv layer.
+ Default: None
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ multi_grid (int | None): Multi grid dilation rates of last
+ stage. Default: None
+ contract_dilation (bool): Whether contract first dilation of each layer
+ Default: False
+ """
+
+ def __init__(self,
+ block,
+ inplanes,
+ planes,
+ num_blocks,
+ stride=1,
+ dilation=1,
+ avg_down=False,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ multi_grid=None,
+ contract_dilation=False,
+ **kwargs):
+ self.block = block
+
+ downsample = None
+ if stride != 1 or inplanes != planes * block.expansion:
+ downsample = []
+ conv_stride = stride
+ if avg_down:
+ conv_stride = 1
+ downsample.append(
+ nn.AvgPool2d(
+ kernel_size=stride,
+ stride=stride,
+ ceil_mode=True,
+ count_include_pad=False))
+ downsample.extend([
+ build_conv_layer(
+ conv_cfg,
+ inplanes,
+ planes * block.expansion,
+ kernel_size=1,
+ stride=conv_stride,
+ bias=False),
+ build_norm_layer(norm_cfg, planes * block.expansion)[1]
+ ])
+ downsample = nn.Sequential(*downsample)
+
+ layers = []
+ if multi_grid is None:
+ if dilation > 1 and contract_dilation:
+ first_dilation = dilation // 2
+ else:
+ first_dilation = dilation
+ else:
+ first_dilation = multi_grid[0]
+ layers.append(
+ block(
+ inplanes=inplanes,
+ planes=planes,
+ stride=stride,
+ dilation=first_dilation,
+ downsample=downsample,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ **kwargs))
+ inplanes = planes * block.expansion
+ for i in range(1, num_blocks):
+ layers.append(
+ block(
+ inplanes=inplanes,
+ planes=planes,
+ stride=1,
+ dilation=dilation if multi_grid is None else multi_grid[i],
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ **kwargs))
+ super(ResLayer, self).__init__(*layers)
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/se_layer.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/se_layer.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ec17f8d6713a441de2400186ded50ff651821ca
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/se_layer.py
@@ -0,0 +1,57 @@
+import custom_mmpkg.custom_mmcv as mmcv
+import torch.nn as nn
+from custom_mmpkg.custom_mmcv.cnn import ConvModule
+
+from .make_divisible import make_divisible
+
+
+class SELayer(nn.Module):
+ """Squeeze-and-Excitation Module.
+
+ Args:
+ channels (int): The input (and output) channels of the SE layer.
+ ratio (int): Squeeze ratio in SELayer, the intermediate channel will be
+ ``int(channels/ratio)``. Default: 16.
+ conv_cfg (None or dict): Config dict for convolution layer.
+ Default: None, which means using conv2d.
+ act_cfg (dict or Sequence[dict]): Config dict for activation layer.
+ If act_cfg is a dict, two activation layers will be configured
+ by this dict. If act_cfg is a sequence of dicts, the first
+ activation layer will be configured by the first dict and the
+ second activation layer will be configured by the second dict.
+ Default: (dict(type='ReLU'), dict(type='HSigmoid', bias=3.0,
+ divisor=6.0)).
+ """
+
+ def __init__(self,
+ channels,
+ ratio=16,
+ conv_cfg=None,
+ act_cfg=(dict(type='ReLU'),
+ dict(type='HSigmoid', bias=3.0, divisor=6.0))):
+ super(SELayer, self).__init__()
+ if isinstance(act_cfg, dict):
+ act_cfg = (act_cfg, act_cfg)
+ assert len(act_cfg) == 2
+ assert mmcv.is_tuple_of(act_cfg, dict)
+ self.global_avgpool = nn.AdaptiveAvgPool2d(1)
+ self.conv1 = ConvModule(
+ in_channels=channels,
+ out_channels=make_divisible(channels // ratio, 8),
+ kernel_size=1,
+ stride=1,
+ conv_cfg=conv_cfg,
+ act_cfg=act_cfg[0])
+ self.conv2 = ConvModule(
+ in_channels=make_divisible(channels // ratio, 8),
+ out_channels=channels,
+ kernel_size=1,
+ stride=1,
+ conv_cfg=conv_cfg,
+ act_cfg=act_cfg[1])
+
+ def forward(self, x):
+ out = self.global_avgpool(x)
+ out = self.conv1(out)
+ out = self.conv2(out)
+ return x * out
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/self_attention_block.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/self_attention_block.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad20ca6cf14b4dce040f350dbdd0fee6ce5ed9cf
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/self_attention_block.py
@@ -0,0 +1,159 @@
+import torch
+from custom_mmpkg.custom_mmcv.cnn import ConvModule, constant_init
+from torch import nn as nn
+from torch.nn import functional as F
+
+
+class SelfAttentionBlock(nn.Module):
+ """General self-attention block/non-local block.
+
+ Please refer to https://arxiv.org/abs/1706.03762 for details about key,
+ query and value.
+
+ Args:
+ key_in_channels (int): Input channels of key feature.
+ query_in_channels (int): Input channels of query feature.
+ channels (int): Output channels of key/query transform.
+ out_channels (int): Output channels.
+ share_key_query (bool): Whether share projection weight between key
+ and query projection.
+ query_downsample (nn.Module): Query downsample module.
+ key_downsample (nn.Module): Key downsample module.
+ key_query_num_convs (int): Number of convs for key/query projection.
+ value_num_convs (int): Number of convs for value projection.
+ matmul_norm (bool): Whether normalize attention map with sqrt of
+ channels
+ with_out (bool): Whether use out projection.
+ conv_cfg (dict|None): Config of conv layers.
+ norm_cfg (dict|None): Config of norm layers.
+ act_cfg (dict|None): Config of activation layers.
+ """
+
+ def __init__(self, key_in_channels, query_in_channels, channels,
+ out_channels, share_key_query, query_downsample,
+ key_downsample, key_query_num_convs, value_out_num_convs,
+ key_query_norm, value_out_norm, matmul_norm, with_out,
+ conv_cfg, norm_cfg, act_cfg):
+ super(SelfAttentionBlock, self).__init__()
+ if share_key_query:
+ assert key_in_channels == query_in_channels
+ self.key_in_channels = key_in_channels
+ self.query_in_channels = query_in_channels
+ self.out_channels = out_channels
+ self.channels = channels
+ self.share_key_query = share_key_query
+ self.conv_cfg = conv_cfg
+ self.norm_cfg = norm_cfg
+ self.act_cfg = act_cfg
+ self.key_project = self.build_project(
+ key_in_channels,
+ channels,
+ num_convs=key_query_num_convs,
+ use_conv_module=key_query_norm,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg)
+ if share_key_query:
+ self.query_project = self.key_project
+ else:
+ self.query_project = self.build_project(
+ query_in_channels,
+ channels,
+ num_convs=key_query_num_convs,
+ use_conv_module=key_query_norm,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg)
+ self.value_project = self.build_project(
+ key_in_channels,
+ channels if with_out else out_channels,
+ num_convs=value_out_num_convs,
+ use_conv_module=value_out_norm,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg)
+ if with_out:
+ self.out_project = self.build_project(
+ channels,
+ out_channels,
+ num_convs=value_out_num_convs,
+ use_conv_module=value_out_norm,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg)
+ else:
+ self.out_project = None
+
+ self.query_downsample = query_downsample
+ self.key_downsample = key_downsample
+ self.matmul_norm = matmul_norm
+
+ self.init_weights()
+
+ def init_weights(self):
+ """Initialize weight of later layer."""
+ if self.out_project is not None:
+ if not isinstance(self.out_project, ConvModule):
+ constant_init(self.out_project, 0)
+
+ def build_project(self, in_channels, channels, num_convs, use_conv_module,
+ conv_cfg, norm_cfg, act_cfg):
+ """Build projection layer for key/query/value/out."""
+ if use_conv_module:
+ convs = [
+ ConvModule(
+ in_channels,
+ channels,
+ 1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg)
+ ]
+ for _ in range(num_convs - 1):
+ convs.append(
+ ConvModule(
+ channels,
+ channels,
+ 1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg))
+ else:
+ convs = [nn.Conv2d(in_channels, channels, 1)]
+ for _ in range(num_convs - 1):
+ convs.append(nn.Conv2d(channels, channels, 1))
+ if len(convs) > 1:
+ convs = nn.Sequential(*convs)
+ else:
+ convs = convs[0]
+ return convs
+
+ def forward(self, query_feats, key_feats):
+ """Forward function."""
+ batch_size = query_feats.size(0)
+ query = self.query_project(query_feats)
+ if self.query_downsample is not None:
+ query = self.query_downsample(query)
+ query = query.reshape(*query.shape[:2], -1)
+ query = query.permute(0, 2, 1).contiguous()
+
+ key = self.key_project(key_feats)
+ value = self.value_project(key_feats)
+ if self.key_downsample is not None:
+ key = self.key_downsample(key)
+ value = self.key_downsample(value)
+ key = key.reshape(*key.shape[:2], -1)
+ value = value.reshape(*value.shape[:2], -1)
+ value = value.permute(0, 2, 1).contiguous()
+
+ sim_map = torch.matmul(query, key)
+ if self.matmul_norm:
+ sim_map = (self.channels**-.5) * sim_map
+ sim_map = F.softmax(sim_map, dim=-1)
+
+ context = torch.matmul(sim_map, value)
+ context = context.permute(0, 2, 1).contiguous()
+ context = context.reshape(batch_size, -1, *query_feats.shape[2:])
+ if self.out_project is not None:
+ context = self.out_project(context)
+ return context
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/up_conv_block.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/up_conv_block.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4320e261db00a8bd0ba2578bcf2fdde952d0270
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/up_conv_block.py
@@ -0,0 +1,101 @@
+import torch
+import torch.nn as nn
+from custom_mmpkg.custom_mmcv.cnn import ConvModule, build_upsample_layer
+
+
+class UpConvBlock(nn.Module):
+ """Upsample convolution block in decoder for UNet.
+
+ This upsample convolution block consists of one upsample module
+ followed by one convolution block. The upsample module expands the
+ high-level low-resolution feature map and the convolution block fuses
+ the upsampled high-level low-resolution feature map and the low-level
+ high-resolution feature map from encoder.
+
+ Args:
+ conv_block (nn.Sequential): Sequential of convolutional layers.
+ in_channels (int): Number of input channels of the high-level
+ skip_channels (int): Number of input channels of the low-level
+ high-resolution feature map from encoder.
+ out_channels (int): Number of output channels.
+ num_convs (int): Number of convolutional layers in the conv_block.
+ Default: 2.
+ stride (int): Stride of convolutional layer in conv_block. Default: 1.
+ dilation (int): Dilation rate of convolutional layer in conv_block.
+ Default: 1.
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed. Default: False.
+ conv_cfg (dict | None): Config dict for convolution layer.
+ Default: None.
+ norm_cfg (dict | None): Config dict for normalization layer.
+ Default: dict(type='BN').
+ act_cfg (dict | None): Config dict for activation layer in ConvModule.
+ Default: dict(type='ReLU').
+ upsample_cfg (dict): The upsample config of the upsample module in
+ decoder. Default: dict(type='InterpConv'). If the size of
+ high-level feature map is the same as that of skip feature map
+ (low-level feature map from encoder), it does not need upsample the
+ high-level feature map and the upsample_cfg is None.
+ dcn (bool): Use deformable convolution in convolutional layer or not.
+ Default: None.
+ plugins (dict): plugins for convolutional layers. Default: None.
+ """
+
+ def __init__(self,
+ conv_block,
+ in_channels,
+ skip_channels,
+ out_channels,
+ num_convs=2,
+ stride=1,
+ dilation=1,
+ with_cp=False,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ act_cfg=dict(type='ReLU'),
+ upsample_cfg=dict(type='InterpConv'),
+ dcn=None,
+ plugins=None):
+ super(UpConvBlock, self).__init__()
+ assert dcn is None, 'Not implemented yet.'
+ assert plugins is None, 'Not implemented yet.'
+
+ self.conv_block = conv_block(
+ in_channels=2 * skip_channels,
+ out_channels=out_channels,
+ num_convs=num_convs,
+ stride=stride,
+ dilation=dilation,
+ with_cp=with_cp,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg,
+ dcn=None,
+ plugins=None)
+ if upsample_cfg is not None:
+ self.upsample = build_upsample_layer(
+ cfg=upsample_cfg,
+ in_channels=in_channels,
+ out_channels=skip_channels,
+ with_cp=with_cp,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg)
+ else:
+ self.upsample = ConvModule(
+ in_channels,
+ skip_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg)
+
+ def forward(self, skip, x):
+ """Forward function."""
+
+ x = self.upsample(x)
+ out = torch.cat([skip, x], dim=1)
+ out = self.conv_block(out)
+
+ return out
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/weight_init.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/weight_init.py
new file mode 100644
index 0000000000000000000000000000000000000000..38141ba3d61f64ddfc0a31574b4648cbad96d7dd
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/models/utils/weight_init.py
@@ -0,0 +1,62 @@
+"""Modified from https://github.com/rwightman/pytorch-image-
+models/blob/master/timm/models/layers/drop.py."""
+
+import math
+import warnings
+
+import torch
+
+
+def _no_grad_trunc_normal_(tensor, mean, std, a, b):
+ """Reference: https://people.sc.fsu.edu/~jburkardt/presentations
+ /truncated_normal.pdf"""
+
+ def norm_cdf(x):
+ # Computes standard normal cumulative distribution function
+ return (1. + math.erf(x / math.sqrt(2.))) / 2.
+
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
+ warnings.warn(
+ 'mean is more than 2 std from [a, b] in nn.init.trunc_normal_. '
+ 'The distribution of values may be incorrect.',
+ stacklevel=2)
+
+ with torch.no_grad():
+ # Values are generated by using a truncated uniform distribution and
+ # then using the inverse CDF for the normal distribution.
+ # Get upper and lower cdf values
+ lower_bound = norm_cdf((a - mean) / std)
+ upper_bound = norm_cdf((b - mean) / std)
+
+ # Uniformly fill tensor with values from [l, u], then translate to
+ # [2l-1, 2u-1].
+ tensor.uniform_(2 * lower_bound - 1, 2 * upper_bound - 1)
+
+ # Use inverse cdf transform for normal distribution to get truncated
+ # standard normal
+ tensor.erfinv_()
+
+ # Transform to proper mean, std
+ tensor.mul_(std * math.sqrt(2.))
+ tensor.add_(mean)
+
+ # Clamp to ensure it's in the proper range
+ tensor.clamp_(min=a, max=b)
+ return tensor
+
+
+def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
+ r"""Fills the input Tensor with values drawn from a truncated
+ normal distribution. The values are effectively drawn from the
+ normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`
+ with values outside :math:`[a, b]` redrawn until they are within
+ the bounds. The method used for generating the random values works
+ best when :math:`a \leq \text{mean} \leq b`.
+ Args:
+ tensor (``torch.Tensor``): an n-dimensional `torch.Tensor`
+ mean (float): the mean of the normal distribution
+ std (float): the standard deviation of the normal distribution
+ a (float): the minimum cutoff value
+ b (float): the maximum cutoff value
+ """
+ return _no_grad_trunc_normal_(tensor, mean, std, a, b)
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/ops/__init__.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/ops/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..bec51c75b9363a9a19e9fb5c35f4e7dbd6f7751c
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/ops/__init__.py
@@ -0,0 +1,4 @@
+from .encoding import Encoding
+from .wrappers import Upsample, resize
+
+__all__ = ['Upsample', 'resize', 'Encoding']
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/ops/encoding.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/ops/encoding.py
new file mode 100644
index 0000000000000000000000000000000000000000..7eb3629a6426550b8e4c537ee1ff4341893e489e
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/ops/encoding.py
@@ -0,0 +1,74 @@
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+
+class Encoding(nn.Module):
+ """Encoding Layer: a learnable residual encoder.
+
+ Input is of shape (batch_size, channels, height, width).
+ Output is of shape (batch_size, num_codes, channels).
+
+ Args:
+ channels: dimension of the features or feature channels
+ num_codes: number of code words
+ """
+
+ def __init__(self, channels, num_codes):
+ super(Encoding, self).__init__()
+ # init codewords and smoothing factor
+ self.channels, self.num_codes = channels, num_codes
+ std = 1. / ((num_codes * channels)**0.5)
+ # [num_codes, channels]
+ self.codewords = nn.Parameter(
+ torch.empty(num_codes, channels,
+ dtype=torch.float).uniform_(-std, std),
+ requires_grad=True)
+ # [num_codes]
+ self.scale = nn.Parameter(
+ torch.empty(num_codes, dtype=torch.float).uniform_(-1, 0),
+ requires_grad=True)
+
+ @staticmethod
+ def scaled_l2(x, codewords, scale):
+ num_codes, channels = codewords.size()
+ batch_size = x.size(0)
+ reshaped_scale = scale.view((1, 1, num_codes))
+ expanded_x = x.unsqueeze(2).expand(
+ (batch_size, x.size(1), num_codes, channels))
+ reshaped_codewords = codewords.view((1, 1, num_codes, channels))
+
+ scaled_l2_norm = reshaped_scale * (
+ expanded_x - reshaped_codewords).pow(2).sum(dim=3)
+ return scaled_l2_norm
+
+ @staticmethod
+ def aggregate(assignment_weights, x, codewords):
+ num_codes, channels = codewords.size()
+ reshaped_codewords = codewords.view((1, 1, num_codes, channels))
+ batch_size = x.size(0)
+
+ expanded_x = x.unsqueeze(2).expand(
+ (batch_size, x.size(1), num_codes, channels))
+ encoded_feat = (assignment_weights.unsqueeze(3) *
+ (expanded_x - reshaped_codewords)).sum(dim=1)
+ return encoded_feat
+
+ def forward(self, x):
+ assert x.dim() == 4 and x.size(1) == self.channels
+ # [batch_size, channels, height, width]
+ batch_size = x.size(0)
+ # [batch_size, height x width, channels]
+ x = x.view(batch_size, self.channels, -1).transpose(1, 2).contiguous()
+ # assignment_weights: [batch_size, channels, num_codes]
+ assignment_weights = F.softmax(
+ self.scaled_l2(x, self.codewords, self.scale), dim=2)
+ # aggregate
+ encoded_feat = self.aggregate(assignment_weights, x, self.codewords)
+ return encoded_feat
+
+ def __repr__(self):
+ repr_str = self.__class__.__name__
+ repr_str += f'(Nx{self.channels}xHxW =>Nx{self.num_codes}' \
+ f'x{self.channels})'
+ return repr_str
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/ops/wrappers.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/ops/wrappers.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ed9a0cb8d7c0e0ec2748dd89c652756653cac78
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/ops/wrappers.py
@@ -0,0 +1,50 @@
+import warnings
+
+import torch.nn as nn
+import torch.nn.functional as F
+
+
+def resize(input,
+ size=None,
+ scale_factor=None,
+ mode='nearest',
+ align_corners=None,
+ warning=True):
+ if warning:
+ if size is not None and align_corners:
+ input_h, input_w = tuple(int(x) for x in input.shape[2:])
+ output_h, output_w = tuple(int(x) for x in size)
+ if output_h > input_h or output_w > output_h:
+ if ((output_h > 1 and output_w > 1 and input_h > 1
+ and input_w > 1) and (output_h - 1) % (input_h - 1)
+ and (output_w - 1) % (input_w - 1)):
+ warnings.warn(
+ f'When align_corners={align_corners}, '
+ 'the output would more aligned if '
+ f'input size {(input_h, input_w)} is `x+1` and '
+ f'out size {(output_h, output_w)} is `nx+1`')
+ return F.interpolate(input, size, scale_factor, mode, align_corners)
+
+
+class Upsample(nn.Module):
+
+ def __init__(self,
+ size=None,
+ scale_factor=None,
+ mode='nearest',
+ align_corners=None):
+ super(Upsample, self).__init__()
+ self.size = size
+ if isinstance(scale_factor, tuple):
+ self.scale_factor = tuple(float(factor) for factor in scale_factor)
+ else:
+ self.scale_factor = float(scale_factor) if scale_factor else None
+ self.mode = mode
+ self.align_corners = align_corners
+
+ def forward(self, x):
+ if not self.size:
+ size = [int(t * self.scale_factor) for t in x.shape[-2:]]
+ else:
+ size = self.size
+ return resize(x, size, None, self.mode, self.align_corners)
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/utils/__init__.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac489e2dbbc0e6fa87f5088b4edcc20f8cadc1a6
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/utils/__init__.py
@@ -0,0 +1,4 @@
+from .collect_env import collect_env
+from .logger import get_root_logger
+
+__all__ = ['get_root_logger', 'collect_env']
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/utils/collect_env.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/utils/collect_env.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce5cd6ffee77a234e7c54d6990d273bbd872b8f5
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/utils/collect_env.py
@@ -0,0 +1,17 @@
+from custom_mmpkg.custom_mmcv.utils import collect_env as collect_base_env
+from custom_mmpkg.custom_mmcv.utils import get_git_hash
+
+import custom_mmpkg.custom_mmseg as mmseg
+
+
+def collect_env():
+ """Collect the information of the running environments."""
+ env_info = collect_base_env()
+ env_info['MMSegmentation'] = f'{mmseg.__version__}+{get_git_hash()[:7]}'
+
+ return env_info
+
+
+if __name__ == '__main__':
+ for name, val in collect_env().items():
+ print('{}: {}'.format(name, val))
diff --git a/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/utils/logger.py b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/utils/logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc2ac05b20a1f7f24a3e7876757d87b00972a69d
--- /dev/null
+++ b/comfyui_controlnet_aux/src/custom_mmpkg/custom_mmseg/utils/logger.py
@@ -0,0 +1,27 @@
+import logging
+
+from custom_mmpkg.custom_mmcv.utils import get_logger
+
+
+def get_root_logger(log_file=None, log_level=logging.INFO):
+ """Get the root logger.
+
+ The logger will be initialized if it has not been initialized. By default a
+ StreamHandler will be added. If `log_file` is specified, a FileHandler will
+ also be added. The name of the root logger is the top-level package name,
+ e.g., "mmseg".
+
+ Args:
+ log_file (str | None): The log filename. If specified, a FileHandler
+ will be added to the root logger.
+ log_level (int): The root logger level. Note that only the process of
+ rank 0 is affected, while other processes will set the level to
+ "Error" and be silent most of the time.
+
+ Returns:
+ logging.Logger: The root logger.
+ """
+
+ logger = get_logger(name='mmseg', log_file=log_file, log_level=log_level)
+
+ return logger
diff --git a/comfyui_controlnet_aux/src/wrapper_for_mps/__init__.py b/comfyui_controlnet_aux/src/wrapper_for_mps/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d40bcf5d6be0ff616c8704bdf8c699fcda876ba8
--- /dev/null
+++ b/comfyui_controlnet_aux/src/wrapper_for_mps/__init__.py
@@ -0,0 +1,7 @@
+import torch
+from comfy.model_management import get_torch_device
+
+device = get_torch_device()
+#https://github.com/microsoft/DirectML/issues/414#issuecomment-1541319479
+def sparse_to_dense(sparse_tensor):
+ return sparse_tensor.to_dense()
\ No newline at end of file
diff --git a/comfyui_controlnet_aux/tests/test_cn_aux_full.json b/comfyui_controlnet_aux/tests/test_cn_aux_full.json
new file mode 100644
index 0000000000000000000000000000000000000000..b6445f36944ab43f99aa7640cfedc3968eb2f6d7
--- /dev/null
+++ b/comfyui_controlnet_aux/tests/test_cn_aux_full.json
@@ -0,0 +1,1737 @@
+{
+ "last_node_id": 45,
+ "last_link_id": 44,
+ "nodes": [
+ {
+ "id": 24,
+ "type": "PreviewImage",
+ "pos": [
+ 843,
+ -430
+ ],
+ "size": [
+ 210,
+ 246
+ ],
+ "flags": {},
+ "order": 22,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 23
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 25,
+ "type": "PreviewImage",
+ "pos": [
+ 1127,
+ -346
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 23,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 24
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 26,
+ "type": "PreviewImage",
+ "pos": [
+ 832,
+ -222
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 24,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 25
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 27,
+ "type": "PreviewImage",
+ "pos": [
+ 1144,
+ -123
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 25,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 26
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 28,
+ "type": "PreviewImage",
+ "pos": [
+ 825,
+ 56
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 26,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 27
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 29,
+ "type": "PreviewImage",
+ "pos": [
+ 1240,
+ 246
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 27,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 28
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 30,
+ "type": "PreviewImage",
+ "pos": [
+ 855,
+ 381
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 28,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 29
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 31,
+ "type": "PreviewImage",
+ "pos": [
+ 1248,
+ 471
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 29,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 30
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 32,
+ "type": "PreviewImage",
+ "pos": [
+ 823,
+ 632
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 30,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 31
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 33,
+ "type": "PreviewImage",
+ "pos": [
+ 1240,
+ 737
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 31,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 32
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 34,
+ "type": "PreviewImage",
+ "pos": [
+ 844,
+ 833
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 32,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 33
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 35,
+ "type": "PreviewImage",
+ "pos": [
+ 1216,
+ 1023
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 33,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 34
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 36,
+ "type": "PreviewImage",
+ "pos": [
+ 838,
+ 1175
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 34,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 35
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 37,
+ "type": "PreviewImage",
+ "pos": [
+ 1282,
+ 1355
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 35,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 36
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 38,
+ "type": "PreviewImage",
+ "pos": [
+ 897,
+ 1532
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 36,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 37
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 39,
+ "type": "PreviewImage",
+ "pos": [
+ 1336,
+ 1704
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 37,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 38
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 40,
+ "type": "PreviewImage",
+ "pos": [
+ 859,
+ 1840
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 38,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 39
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 41,
+ "type": "PreviewImage",
+ "pos": [
+ 1329,
+ 1939
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 39,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 40
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 42,
+ "type": "PreviewImage",
+ "pos": [
+ 888,
+ 2056
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 40,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 42
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 43,
+ "type": "PreviewImage",
+ "pos": [
+ 1278,
+ 2191
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 41,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 41
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 2,
+ "type": "PiDiNetPreprocessor",
+ "pos": [
+ 420,
+ -446
+ ],
+ "size": {
+ "0": 315,
+ "1": 58
+ },
+ "flags": {},
+ "order": 1,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 1
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 23
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PiDiNetPreprocessor"
+ },
+ "widgets_values": [
+ "enable"
+ ]
+ },
+ {
+ "id": 3,
+ "type": "ColorPreprocessor",
+ "pos": [
+ 426,
+ -332
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 2,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 2
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 24
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "ColorPreprocessor"
+ }
+ },
+ {
+ "id": 4,
+ "type": "CannyEdgePreprocessor",
+ "pos": [
+ 433,
+ -245
+ ],
+ "size": {
+ "0": 315,
+ "1": 82
+ },
+ "flags": {},
+ "order": 3,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 3
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 25
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "CannyEdgePreprocessor"
+ },
+ "widgets_values": [
+ 100,
+ 200
+ ]
+ },
+ {
+ "id": 5,
+ "type": "SAMPreprocessor",
+ "pos": [
+ 427,
+ -108
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 4,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 4
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 26
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "SAMPreprocessor"
+ }
+ },
+ {
+ "id": 7,
+ "type": "DWPreprocessor",
+ "pos": [
+ 440,
+ 95
+ ],
+ "size": {
+ "0": 315,
+ "1": 106
+ },
+ "flags": {},
+ "order": 5,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 6
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 27
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "DWPreprocessor"
+ },
+ "widgets_values": [
+ "enable",
+ "enable",
+ "enable"
+ ]
+ },
+ {
+ "id": 8,
+ "type": "BinaryPreprocessor",
+ "pos": [
+ 432,
+ 266
+ ],
+ "size": {
+ "0": 315,
+ "1": 58
+ },
+ "flags": {},
+ "order": 6,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 7
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 28
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "BinaryPreprocessor"
+ },
+ "widgets_values": [
+ 100
+ ]
+ },
+ {
+ "id": 9,
+ "type": "ScribblePreprocessor",
+ "pos": [
+ 462,
+ 376
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 7,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 8
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 29
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "ScribblePreprocessor"
+ }
+ },
+ {
+ "id": 10,
+ "type": "M-LSDPreprocessor",
+ "pos": [
+ 453,
+ 497
+ ],
+ "size": {
+ "0": 315,
+ "1": 82
+ },
+ "flags": {},
+ "order": 8,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 9
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 30
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "M-LSDPreprocessor"
+ },
+ "widgets_values": [
+ 0.1,
+ 0.1
+ ]
+ },
+ {
+ "id": 11,
+ "type": "UniFormer-SemSegPreprocessor",
+ "pos": [
+ 479,
+ 651
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 9,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 10
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 31
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "UniFormer-SemSegPreprocessor"
+ }
+ },
+ {
+ "id": 12,
+ "type": "Zoe-DepthMapPreprocessor",
+ "pos": [
+ 483,
+ 740
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 10,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 11
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 32
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "Zoe-DepthMapPreprocessor"
+ }
+ },
+ {
+ "id": 13,
+ "type": "MiDaS-NormalMapPreprocessor",
+ "pos": [
+ 463,
+ 821
+ ],
+ "size": {
+ "0": 315,
+ "1": 82
+ },
+ "flags": {},
+ "order": 11,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 12
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 33
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "MiDaS-NormalMapPreprocessor"
+ },
+ "widgets_values": [
+ 6.283185307179586,
+ 0.1
+ ]
+ },
+ {
+ "id": 14,
+ "type": "MiDaS-DepthMapPreprocessor",
+ "pos": [
+ 451,
+ 1009
+ ],
+ "size": {
+ "0": 315,
+ "1": 82
+ },
+ "flags": {},
+ "order": 12,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 13
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 34
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "MiDaS-DepthMapPreprocessor"
+ },
+ "widgets_values": [
+ 6.283185307179586,
+ 0.1
+ ]
+ },
+ {
+ "id": 15,
+ "type": "OpenposePreprocessor",
+ "pos": [
+ 466,
+ 1177
+ ],
+ "size": {
+ "0": 315,
+ "1": 106
+ },
+ "flags": {},
+ "order": 13,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 14
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 35
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "OpenposePreprocessor"
+ },
+ "widgets_values": [
+ "enable",
+ "enable",
+ "enable"
+ ]
+ },
+ {
+ "id": 17,
+ "type": "LeReS-DepthMapPreprocessor",
+ "pos": [
+ 484,
+ 1533
+ ],
+ "size": {
+ "0": 315,
+ "1": 106
+ },
+ "flags": {},
+ "order": 15,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 16
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 37
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "LeReS-DepthMapPreprocessor"
+ },
+ "widgets_values": [
+ 0,
+ 0,
+ "enable"
+ ]
+ },
+ {
+ "id": 18,
+ "type": "BAE-NormalMapPreprocessor",
+ "pos": [
+ 510,
+ 1729
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 16,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 17
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 38
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "BAE-NormalMapPreprocessor"
+ }
+ },
+ {
+ "id": 19,
+ "type": "OneFormer-COCO-SemSegPreprocessor",
+ "pos": [
+ 488,
+ 1843
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 17,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 18
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 39
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "OneFormer-COCO-SemSegPreprocessor"
+ }
+ },
+ {
+ "id": 20,
+ "type": "OneFormer-ADE20K-SemSegPreprocessor",
+ "pos": [
+ 470,
+ 1941
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 18,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 19
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 40
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "OneFormer-ADE20K-SemSegPreprocessor"
+ }
+ },
+ {
+ "id": 22,
+ "type": "FakeScribblePreprocessor",
+ "pos": [
+ 426,
+ 2193
+ ],
+ "size": {
+ "0": 315,
+ "1": 58
+ },
+ "flags": {},
+ "order": 20,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 21
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 41
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "FakeScribblePreprocessor"
+ },
+ "widgets_values": [
+ "enable"
+ ]
+ },
+ {
+ "id": 21,
+ "type": "HEDPreprocessor",
+ "pos": [
+ 460,
+ 2053
+ ],
+ "size": {
+ "0": 315,
+ "1": 58
+ },
+ "flags": {},
+ "order": 19,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 20
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 42
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "HEDPreprocessor"
+ },
+ "widgets_values": [
+ "enable"
+ ]
+ },
+ {
+ "id": 16,
+ "type": "LineArtPreprocessor",
+ "pos": [
+ 450,
+ 1363
+ ],
+ "size": {
+ "0": 315,
+ "1": 58
+ },
+ "flags": {},
+ "order": 14,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 15
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 36
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "LineArtPreprocessor"
+ },
+ "widgets_values": [
+ "enable"
+ ]
+ },
+ {
+ "id": 45,
+ "type": "PreviewImage",
+ "pos": [
+ 886,
+ 2316
+ ],
+ "size": {
+ "0": 210,
+ "1": 26
+ },
+ "flags": {},
+ "order": 42,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 43
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 44,
+ "type": "TilePreprocessor",
+ "pos": [
+ 419,
+ 2320
+ ],
+ "size": {
+ "0": 315,
+ "1": 58
+ },
+ "flags": {},
+ "order": 21,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 44
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 43
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "TilePreprocessor"
+ },
+ "widgets_values": [
+ 3
+ ]
+ },
+ {
+ "id": 1,
+ "type": "LoadImage",
+ "pos": [
+ 19,
+ 298
+ ],
+ "size": {
+ "0": 315,
+ "1": 314
+ },
+ "flags": {},
+ "order": 0,
+ "mode": 0,
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 1,
+ 2,
+ 3,
+ 4,
+ 6,
+ 7,
+ 8,
+ 9,
+ 10,
+ 11,
+ 12,
+ 13,
+ 14,
+ 15,
+ 16,
+ 17,
+ 18,
+ 19,
+ 20,
+ 21,
+ 44
+ ],
+ "shape": 3,
+ "slot_index": 0
+ },
+ {
+ "name": "MASK",
+ "type": "MASK",
+ "links": null,
+ "shape": 3
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "LoadImage"
+ },
+ "widgets_values": [
+ "pose.png",
+ "image"
+ ]
+ }
+ ],
+ "links": [
+ [
+ 1,
+ 1,
+ 0,
+ 2,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 2,
+ 1,
+ 0,
+ 3,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 3,
+ 1,
+ 0,
+ 4,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 4,
+ 1,
+ 0,
+ 5,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 6,
+ 1,
+ 0,
+ 7,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 7,
+ 1,
+ 0,
+ 8,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 8,
+ 1,
+ 0,
+ 9,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 9,
+ 1,
+ 0,
+ 10,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 10,
+ 1,
+ 0,
+ 11,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 11,
+ 1,
+ 0,
+ 12,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 12,
+ 1,
+ 0,
+ 13,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 13,
+ 1,
+ 0,
+ 14,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 14,
+ 1,
+ 0,
+ 15,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 15,
+ 1,
+ 0,
+ 16,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 16,
+ 1,
+ 0,
+ 17,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 17,
+ 1,
+ 0,
+ 18,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 18,
+ 1,
+ 0,
+ 19,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 19,
+ 1,
+ 0,
+ 20,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 20,
+ 1,
+ 0,
+ 21,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 21,
+ 1,
+ 0,
+ 22,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 23,
+ 2,
+ 0,
+ 24,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 24,
+ 3,
+ 0,
+ 25,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 25,
+ 4,
+ 0,
+ 26,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 26,
+ 5,
+ 0,
+ 27,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 27,
+ 7,
+ 0,
+ 28,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 28,
+ 8,
+ 0,
+ 29,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 29,
+ 9,
+ 0,
+ 30,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 30,
+ 10,
+ 0,
+ 31,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 31,
+ 11,
+ 0,
+ 32,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 32,
+ 12,
+ 0,
+ 33,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 33,
+ 13,
+ 0,
+ 34,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 34,
+ 14,
+ 0,
+ 35,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 35,
+ 15,
+ 0,
+ 36,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 36,
+ 16,
+ 0,
+ 37,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 37,
+ 17,
+ 0,
+ 38,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 38,
+ 18,
+ 0,
+ 39,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 39,
+ 19,
+ 0,
+ 40,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 40,
+ 20,
+ 0,
+ 41,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 41,
+ 22,
+ 0,
+ 43,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 42,
+ 21,
+ 0,
+ 42,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 43,
+ 44,
+ 0,
+ 45,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 44,
+ 1,
+ 0,
+ 44,
+ 0,
+ "IMAGE"
+ ]
+ ],
+ "groups": [],
+ "config": {},
+ "extra": {},
+ "version": 0.4
+}
\ No newline at end of file
diff --git a/comfyui_controlnet_aux/tests/test_controlnet_aux.py b/comfyui_controlnet_aux/tests/test_controlnet_aux.py
new file mode 100644
index 0000000000000000000000000000000000000000..5fdaaca498a58eecd02439e2611e605835d5929f
--- /dev/null
+++ b/comfyui_controlnet_aux/tests/test_controlnet_aux.py
@@ -0,0 +1,126 @@
+import os
+import shutil
+from io import BytesIO
+
+import numpy as np
+import pytest
+import requests
+from PIL import Image
+
+from custom_controlnet_aux import (CannyDetector, ContentShuffleDetector, HEDdetector,
+ LeresDetector, LineartAnimeDetector,
+ LineartDetector, MediapipeFaceDetector,
+ MidasDetector, MLSDdetector, NormalBaeDetector,
+ OpenposeDetector, PidiNetDetector, SamDetector,
+ ZoeDetector, TileDetector)
+
+OUTPUT_DIR = "tests/outputs"
+
+def output(name, img):
+ img.save(os.path.join(OUTPUT_DIR, "{:s}.png".format(name)))
+
+def common(name, processor, img):
+ output(name, processor(img))
+ output(name + "_pil_np", Image.fromarray(processor(img, output_type="np")))
+ output(name + "_np_np", Image.fromarray(processor(np.array(img, dtype=np.uint8), output_type="np")))
+ output(name + "_np_pil", processor(np.array(img, dtype=np.uint8), output_type="pil"))
+ output(name + "_scaled", processor(img, detect_resolution=640, image_resolution=768))
+
+def return_pil(name, processor, img):
+ output(name + "_pil_false", Image.fromarray(processor(img, return_pil=False)))
+ output(name + "_pil_true", processor(img, return_pil=True))
+
+@pytest.fixture(scope="module")
+def img():
+ if os.path.exists(OUTPUT_DIR):
+ shutil.rmtree(OUTPUT_DIR)
+ os.mkdir(OUTPUT_DIR)
+ url = "https://huggingface.co/lllyasviel/sd-controlnet-openpose/resolve/main/images/pose.png"
+ response = requests.get(url)
+ img = Image.open(BytesIO(response.content)).convert("RGB").resize((512, 512))
+ return img
+
+def test_canny(img):
+ canny = CannyDetector()
+ common("canny", canny, img)
+ output("canny_img", canny(img=img))
+
+def test_hed(img):
+ hed = HEDdetector.from_pretrained("lllyasviel/Annotators")
+ common("hed", hed, img)
+ return_pil("hed", hed, img)
+ output("hed_safe", hed(img, safe=True))
+ output("hed_scribble", hed(img, scribble=True))
+
+def test_leres(img):
+ leres = LeresDetector.from_pretrained("lllyasviel/Annotators")
+ common("leres", leres, img)
+ output("leres_boost", leres(img, boost=True))
+
+def test_lineart(img):
+ lineart = LineartDetector.from_pretrained("lllyasviel/Annotators")
+ common("lineart", lineart, img)
+ return_pil("lineart", lineart, img)
+ output("lineart_coarse", lineart(img, coarse=True))
+
+def test_lineart_anime(img):
+ lineart_anime = LineartAnimeDetector.from_pretrained("lllyasviel/Annotators")
+ common("lineart_anime", lineart_anime, img)
+ return_pil("lineart_anime", lineart_anime, img)
+
+def test_mediapipe_face(img):
+ mediapipe = MediapipeFaceDetector()
+ common("mediapipe", mediapipe, img)
+ output("mediapipe_image", mediapipe(image=img))
+
+def test_midas(img):
+ midas = MidasDetector.from_pretrained("lllyasviel/Annotators")
+ common("midas", midas, img)
+ output("midas_normal", midas(img, depth_and_normal=True)[1])
+
+def test_mlsd(img):
+ mlsd = MLSDdetector.from_pretrained("lllyasviel/Annotators")
+ common("mlsd", mlsd, img)
+ return_pil("mlsd", mlsd, img)
+
+def test_normalbae(img):
+ normal_bae = NormalBaeDetector.from_pretrained("lllyasviel/Annotators")
+ common("normal_bae", normal_bae, img)
+ return_pil("normal_bae", normal_bae, img)
+
+def test_openpose(img):
+ openpose = OpenposeDetector.from_pretrained("lllyasviel/Annotators")
+ common("openpose", openpose, img)
+ return_pil("openpose", openpose, img)
+ output("openpose_hand_and_face_false", openpose(img, hand_and_face=False))
+ output("openpose_hand_and_face_true", openpose(img, hand_and_face=True))
+ output("openpose_face", openpose(img, include_body=True, include_hand=False, include_face=True))
+ output("openpose_faceonly", openpose(img, include_body=False, include_hand=False, include_face=True))
+ output("openpose_full", openpose(img, include_body=True, include_hand=True, include_face=True))
+ output("openpose_hand", openpose(img, include_body=True, include_hand=True, include_face=False))
+
+def test_pidi(img):
+ pidi = PidiNetDetector.from_pretrained("lllyasviel/Annotators")
+ common("pidi", pidi, img)
+ return_pil("pidi", pidi, img)
+ output("pidi_safe", pidi(img, safe=True))
+ output("pidi_scribble", pidi(img, scribble=True))
+
+def test_sam(img):
+ sam = SamDetector.from_pretrained("ybelkada/segment-anything", subfolder="checkpoints")
+ common("sam", sam, img)
+ output("sam_image", sam(image=img))
+
+def test_shuffle(img):
+ shuffle = ContentShuffleDetector()
+ common("shuffle", shuffle, img)
+ return_pil("shuffle", shuffle, img)
+
+def test_zoe(img):
+ zoe = ZoeDetector.from_pretrained("lllyasviel/Annotators")
+ common("zoe", zoe, img)
+
+def test_tile(img):
+ tile = TileDetector()
+ common("tile", tile, img)
+ output("tile_img", tile(img))
\ No newline at end of file
diff --git a/comfyui_controlnet_aux/utils.py b/comfyui_controlnet_aux/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf3dd6e693ba379ef4714745bddeca88d0b633f9
--- /dev/null
+++ b/comfyui_controlnet_aux/utils.py
@@ -0,0 +1,250 @@
+import torch
+import numpy as np
+import os
+import cv2
+import yaml
+from pathlib import Path
+from enum import Enum
+from .log import log
+import subprocess
+import threading
+import comfy
+import tempfile
+
+here = Path(__file__).parent.resolve()
+
+config_path = Path(here, "config.yaml")
+
+if os.path.exists(config_path):
+ config = yaml.load(open(config_path, "r"), Loader=yaml.FullLoader)
+
+ annotator_ckpts_path = str(Path(here, config["annotator_ckpts_path"]))
+ TEMP_DIR = config["custom_temp_path"]
+ USE_SYMLINKS = config["USE_SYMLINKS"]
+ ORT_PROVIDERS = config["EP_list"]
+
+ if USE_SYMLINKS is None or type(USE_SYMLINKS) != bool:
+ log.error("USE_SYMLINKS must be a boolean. Using False by default.")
+ USE_SYMLINKS = False
+
+ if TEMP_DIR is None:
+ TEMP_DIR = tempfile.gettempdir()
+ elif not os.path.isdir(TEMP_DIR):
+ try:
+ os.makedirs(TEMP_DIR)
+ except:
+ log.error("Failed to create custom temp directory. Using default.")
+ TEMP_DIR = tempfile.gettempdir()
+
+ if not os.path.isdir(annotator_ckpts_path):
+ try:
+ os.makedirs(annotator_ckpts_path)
+ except:
+ log.error("Failed to create config ckpts directory. Using default.")
+ annotator_ckpts_path = str(Path(here, "./ckpts"))
+else:
+ annotator_ckpts_path = str(Path(here, "./ckpts"))
+ TEMP_DIR = tempfile.gettempdir()
+ USE_SYMLINKS = False
+ ORT_PROVIDERS = ["CUDAExecutionProvider", "DirectMLExecutionProvider", "OpenVINOExecutionProvider", "ROCMExecutionProvider", "CPUExecutionProvider", "CoreMLExecutionProvider"]
+
+os.environ['AUX_ANNOTATOR_CKPTS_PATH'] = os.getenv('AUX_ANNOTATOR_CKPTS_PATH', annotator_ckpts_path)
+os.environ['AUX_TEMP_DIR'] = os.getenv('AUX_TEMP_DIR', str(TEMP_DIR))
+os.environ['AUX_USE_SYMLINKS'] = os.getenv('AUX_USE_SYMLINKS', str(USE_SYMLINKS))
+os.environ['AUX_ORT_PROVIDERS'] = os.getenv('AUX_ORT_PROVIDERS', str(",".join(ORT_PROVIDERS)))
+
+log.info(f"Using ckpts path: {annotator_ckpts_path}")
+log.info(f"Using symlinks: {USE_SYMLINKS}")
+log.info(f"Using ort providers: {ORT_PROVIDERS}")
+
+# Sync with theoritical limit from Comfy base
+# https://github.com/comfyanonymous/ComfyUI/blob/eecd69b53a896343775bcb02a4f8349e7442ffd1/nodes.py#L45
+MAX_RESOLUTION=16384
+
+def common_annotator_call(model, tensor_image, input_batch=False, show_pbar=True, **kwargs):
+ if "detect_resolution" in kwargs:
+ del kwargs["detect_resolution"] #Prevent weird case?
+
+ if "resolution" in kwargs:
+ detect_resolution = kwargs["resolution"] if type(kwargs["resolution"]) == int and kwargs["resolution"] >= 64 else 512
+ del kwargs["resolution"]
+ else:
+ detect_resolution = 512
+
+ if input_batch:
+ np_images = np.asarray(tensor_image * 255., dtype=np.uint8)
+ np_results = model(np_images, output_type="np", detect_resolution=detect_resolution, **kwargs)
+ return torch.from_numpy(np_results.astype(np.float32) / 255.0)
+
+ batch_size = tensor_image.shape[0]
+ if show_pbar:
+ pbar = comfy.utils.ProgressBar(batch_size)
+ out_tensor = None
+ for i, image in enumerate(tensor_image):
+ np_image = np.asarray(image.cpu() * 255., dtype=np.uint8)
+ np_result = model(np_image, output_type="np", detect_resolution=detect_resolution, **kwargs)
+ out = torch.from_numpy(np_result.astype(np.float32) / 255.0)
+ if out_tensor is None:
+ out_tensor = torch.zeros(batch_size, *out.shape, dtype=torch.float32)
+ out_tensor[i] = out
+ if show_pbar:
+ pbar.update(1)
+ return out_tensor
+
+def define_preprocessor_inputs(**arguments):
+ return dict(
+ required=dict(image=INPUT.IMAGE()),
+ optional=arguments
+ )
+
+class INPUT(Enum):
+ def IMAGE():
+ return ("IMAGE",)
+ def LATENT():
+ return ("LATENT",)
+ def MASK():
+ return ("MASK",)
+ def SEED(default=0):
+ return ("INT", dict(default=default, min=0, max=0xffffffffffffffff))
+ def RESOLUTION(default=512, min=64, max=MAX_RESOLUTION, step=64):
+ return ("INT", dict(default=default, min=min, max=max, step=step))
+ def INT(default=0, min=0, max=MAX_RESOLUTION, step=1):
+ return ("INT", dict(default=default, min=min, max=max, step=step))
+ def FLOAT(default=0, min=0, max=1, step=0.01):
+ return ("FLOAT", dict(default=default, min=min, max=max, step=step))
+ def STRING(default='', multiline=False):
+ return ("STRING", dict(default=default, multiline=multiline))
+ def COMBO(values, default=None):
+ return (values, dict(default=values[0] if default is None else default))
+ def BOOLEAN(default=True):
+ return ("BOOLEAN", dict(default=default))
+
+
+
+class ResizeMode(Enum):
+ """
+ Resize modes for ControlNet input images.
+ """
+
+ RESIZE = "Just Resize"
+ INNER_FIT = "Crop and Resize"
+ OUTER_FIT = "Resize and Fill"
+
+ def int_value(self):
+ if self == ResizeMode.RESIZE:
+ return 0
+ elif self == ResizeMode.INNER_FIT:
+ return 1
+ elif self == ResizeMode.OUTER_FIT:
+ return 2
+ assert False, "NOTREACHED"
+
+#https://github.com/Mikubill/sd-webui-controlnet/blob/e67e017731aad05796b9615dc6eadce911298ea1/internal_controlnet/external_code.py#L89
+#Replaced logger with internal log
+def pixel_perfect_resolution(
+ image: np.ndarray,
+ target_H: int,
+ target_W: int,
+ resize_mode: ResizeMode,
+) -> int:
+ """
+ Calculate the estimated resolution for resizing an image while preserving aspect ratio.
+
+ The function first calculates scaling factors for height and width of the image based on the target
+ height and width. Then, based on the chosen resize mode, it either takes the smaller or the larger
+ scaling factor to estimate the new resolution.
+
+ If the resize mode is OUTER_FIT, the function uses the smaller scaling factor, ensuring the whole image
+ fits within the target dimensions, potentially leaving some empty space.
+
+ If the resize mode is not OUTER_FIT, the function uses the larger scaling factor, ensuring the target
+ dimensions are fully filled, potentially cropping the image.
+
+ After calculating the estimated resolution, the function prints some debugging information.
+
+ Args:
+ image (np.ndarray): A 3D numpy array representing an image. The dimensions represent [height, width, channels].
+ target_H (int): The target height for the image.
+ target_W (int): The target width for the image.
+ resize_mode (ResizeMode): The mode for resizing.
+
+ Returns:
+ int: The estimated resolution after resizing.
+ """
+ raw_H, raw_W, _ = image.shape
+
+ k0 = float(target_H) / float(raw_H)
+ k1 = float(target_W) / float(raw_W)
+
+ if resize_mode == ResizeMode.OUTER_FIT:
+ estimation = min(k0, k1) * float(min(raw_H, raw_W))
+ else:
+ estimation = max(k0, k1) * float(min(raw_H, raw_W))
+
+ log.debug(f"Pixel Perfect Computation:")
+ log.debug(f"resize_mode = {resize_mode}")
+ log.debug(f"raw_H = {raw_H}")
+ log.debug(f"raw_W = {raw_W}")
+ log.debug(f"target_H = {target_H}")
+ log.debug(f"target_W = {target_W}")
+ log.debug(f"estimation = {estimation}")
+
+ return int(np.round(estimation))
+
+#https://github.com/Mikubill/sd-webui-controlnet/blob/e67e017731aad05796b9615dc6eadce911298ea1/scripts/controlnet.py#L404
+def safe_numpy(x):
+ # A very safe method to make sure that Apple/Mac works
+ y = x
+
+ # below is very boring but do not change these. If you change these Apple or Mac may fail.
+ y = y.copy()
+ y = np.ascontiguousarray(y)
+ y = y.copy()
+ return y
+
+#https://github.com/Mikubill/sd-webui-controlnet/blob/e67e017731aad05796b9615dc6eadce911298ea1/scripts/utils.py#L140
+def get_unique_axis0(data):
+ arr = np.asanyarray(data)
+ idxs = np.lexsort(arr.T)
+ arr = arr[idxs]
+ unique_idxs = np.empty(len(arr), dtype=np.bool_)
+ unique_idxs[:1] = True
+ unique_idxs[1:] = np.any(arr[:-1, :] != arr[1:, :], axis=-1)
+ return arr[unique_idxs]
+
+#Ref: https://github.com/ltdrdata/ComfyUI-Manager/blob/284e90dc8296a2e1e4f14b4b2d10fba2f52f0e53/__init__.py#L14
+def handle_stream(stream, prefix):
+ for line in stream:
+ print(prefix, line, end="")
+
+
+def run_script(cmd, cwd='.'):
+ process = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1)
+
+ stdout_thread = threading.Thread(target=handle_stream, args=(process.stdout, ""))
+ stderr_thread = threading.Thread(target=handle_stream, args=(process.stderr, "[!]"))
+
+ stdout_thread.start()
+ stderr_thread.start()
+
+ stdout_thread.join()
+ stderr_thread.join()
+
+ return process.wait()
+
+def nms(x, t, s):
+ x = cv2.GaussianBlur(x.astype(np.float32), (0, 0), s)
+
+ f1 = np.array([[0, 0, 0], [1, 1, 1], [0, 0, 0]], dtype=np.uint8)
+ f2 = np.array([[0, 1, 0], [0, 1, 0], [0, 1, 0]], dtype=np.uint8)
+ f3 = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=np.uint8)
+ f4 = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]], dtype=np.uint8)
+
+ y = np.zeros_like(x)
+
+ for f in [f1, f2, f3, f4]:
+ np.putmask(y, cv2.dilate(x, kernel=f) == x, x)
+
+ z = np.zeros_like(y, dtype=np.uint8)
+ z[y > t] = 255
+ return z
diff --git a/comfyui_essentials/.github/workflows/publish.yml b/comfyui_essentials/.github/workflows/publish.yml
new file mode 100644
index 0000000000000000000000000000000000000000..a4fd89247c103447a257600ca36e31ad5bf8fdf3
--- /dev/null
+++ b/comfyui_essentials/.github/workflows/publish.yml
@@ -0,0 +1,22 @@
+name: Publish to Comfy registry
+on:
+ workflow_dispatch:
+ push:
+ branches:
+ - main
+ - master
+ paths:
+ - "pyproject.toml"
+
+jobs:
+ publish-node:
+ name: Publish Custom Node to registry
+ runs-on: ubuntu-latest
+ steps:
+ - name: Check out code
+ uses: actions/checkout@v4
+ - name: Publish Custom Node
+ uses: Comfy-Org/publish-node-action@main
+ 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_essentials/.gitignore b/comfyui_essentials/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..b5a4568fd5c499d1b66b0b066ae73a2f4ea1f4c7
--- /dev/null
+++ b/comfyui_essentials/.gitignore
@@ -0,0 +1,6 @@
+/__pycache__/
+/luts/*.cube
+/luts/*.CUBE
+/fonts/*.ttf
+/fonts/*.otf
+!/fonts/ShareTechMono-Regular.ttf
\ No newline at end of file
diff --git a/comfyui_essentials/.tracking b/comfyui_essentials/.tracking
new file mode 100644
index 0000000000000000000000000000000000000000..8b6ef96373ded942624a432f79957e0c737264f4
--- /dev/null
+++ b/comfyui_essentials/.tracking
@@ -0,0 +1,21 @@
+sampling.py
+conditioning.py
+pyproject.toml
+utils.py
+workflow_all_nodes.json
+LICENSE
+README.md
+__init__.py
+histogram_matching.py
+segmentation.py
+.gitignore
+misc.py
+mask.py
+requirements.txt
+image.py
+carve.py
+text.py
+fonts/ShareTechMono-Regular.ttf
+fonts/put_font_files_here.txt
+luts/put_luts_files_here.txt
+.github/workflows/publish.yml
\ No newline at end of file
diff --git a/comfyui_essentials/LICENSE b/comfyui_essentials/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..948b5e4192d70b665b15bb5a917bd98b3771eb4b
--- /dev/null
+++ b/comfyui_essentials/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2023 Matteo Spinelli
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/comfyui_essentials/README.md b/comfyui_essentials/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..52ec493cdef100c9c19c5c791d6bd68dbbd1d5a8
--- /dev/null
+++ b/comfyui_essentials/README.md
@@ -0,0 +1,55 @@
+# :wrench: ComfyUI Essentials
+
+Essential nodes that are weirdly missing from ComfyUI core. With few exceptions they are new features and not commodities. I hope this will be just a temporary repository until the nodes get included into ComfyUI.
+
+# Sponsorship
+
+
+
+**[:heart: Github Sponsor](https://github.com/sponsors/cubiq) | [:coin: Paypal](https://paypal.me/matt3o)**
+
+
+
+If you like my work and wish to see updates and new features please consider sponsoring my projects.
+
+- [ComfyUI IPAdapter Plus](https://github.com/cubiq/ComfyUI_IPAdapter_plus)
+- [ComfyUI InstantID (Native)](https://github.com/cubiq/ComfyUI_InstantID)
+- [ComfyUI Essentials](https://github.com/cubiq/ComfyUI_essentials)
+- [ComfyUI FaceAnalysis](https://github.com/cubiq/ComfyUI_FaceAnalysis)
+- [Comfy Dungeon](https://github.com/cubiq/Comfy_Dungeon)
+
+Not to mention the documentation and videos tutorials. Check my **ComfyUI Advanced Understanding** videos on YouTube for example, [part 1](https://www.youtube.com/watch?v=_C7kR2TFIX0) and [part 2](https://www.youtube.com/watch?v=ijqXnW_9gzc)
+
+The only way to keep the code open and free is by sponsoring its development. The more sponsorships the more time I can dedicate to my open source projects.
+
+Please consider a [Github Sponsorship](https://github.com/sponsors/cubiq) or [PayPal donation](https://paypal.me/matt3o) (Matteo "matt3o" Spinelli). For sponsorships of $50+, let me know if you'd like to be mentioned in this readme file, you can find me on [Discord](https://latent.vision/discord) or _matt3o :snail: gmail.com_.
+
+## Current sponsors
+
+It's only thanks to generous sponsors that **the whole community** can enjoy open and free software. Please join me in thanking the following companies and individuals!
+
+### :trophy: Gold sponsors
+
+[](https://kaiber.ai/) [](https://replicate.com/)
+
+### :tada: Silver sponsors
+
+[](https://openart.ai/workflows) [](https://www.finetuners.ai/)
+
+### Companies supporting my projects
+
+- [RunComfy](https://www.runcomfy.com/) (ComfyUI Cloud)
+
+### Esteemed individuals
+
+- [Jack Gane](https://github.com/ganeJackS)
+- [Nathan Shipley](https://www.nathanshipley.com/)
+- [Dkdnzia](https://github.com/Dkdnzia)
+
+### One-time Extraordinaires
+
+- [Eric Rollei](https://github.com/EricRollei)
+- [francaleu](https://github.com/francaleu)
+- [Neta.art](https://github.com/talesofai)
+- [Samwise Wang](https://github.com/tzwm)
+- _And all private sponsors, you know who you are!_
\ No newline at end of file
diff --git a/comfyui_essentials/__init__.py b/comfyui_essentials/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f711d30fd3aa5fe1e7ffbed1694da8221886e211
--- /dev/null
+++ b/comfyui_essentials/__init__.py
@@ -0,0 +1,34 @@
+#from .essentials import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
+from .image import IMAGE_CLASS_MAPPINGS, IMAGE_NAME_MAPPINGS
+from .mask import MASK_CLASS_MAPPINGS, MASK_NAME_MAPPINGS
+from .sampling import SAMPLING_CLASS_MAPPINGS, SAMPLING_NAME_MAPPINGS
+from .segmentation import SEG_CLASS_MAPPINGS, SEG_NAME_MAPPINGS
+from .misc import MISC_CLASS_MAPPINGS, MISC_NAME_MAPPINGS
+from .conditioning import COND_CLASS_MAPPINGS, COND_NAME_MAPPINGS
+from .text import TEXT_CLASS_MAPPINGS, TEXT_NAME_MAPPINGS
+
+NODE_CLASS_MAPPINGS = {}
+NODE_DISPLAY_NAME_MAPPINGS = {}
+
+NODE_CLASS_MAPPINGS.update(COND_CLASS_MAPPINGS)
+NODE_DISPLAY_NAME_MAPPINGS.update(COND_NAME_MAPPINGS)
+
+NODE_CLASS_MAPPINGS.update(IMAGE_CLASS_MAPPINGS)
+NODE_DISPLAY_NAME_MAPPINGS.update(IMAGE_NAME_MAPPINGS)
+
+NODE_CLASS_MAPPINGS.update(MASK_CLASS_MAPPINGS)
+NODE_DISPLAY_NAME_MAPPINGS.update(MASK_NAME_MAPPINGS)
+
+NODE_CLASS_MAPPINGS.update(SAMPLING_CLASS_MAPPINGS)
+NODE_DISPLAY_NAME_MAPPINGS.update(SAMPLING_NAME_MAPPINGS)
+
+NODE_CLASS_MAPPINGS.update(SEG_CLASS_MAPPINGS)
+NODE_DISPLAY_NAME_MAPPINGS.update(SEG_NAME_MAPPINGS)
+
+NODE_CLASS_MAPPINGS.update(TEXT_CLASS_MAPPINGS)
+NODE_DISPLAY_NAME_MAPPINGS.update(TEXT_NAME_MAPPINGS)
+
+NODE_CLASS_MAPPINGS.update(MISC_CLASS_MAPPINGS)
+NODE_DISPLAY_NAME_MAPPINGS.update(MISC_NAME_MAPPINGS)
+
+__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS']
diff --git a/comfyui_essentials/__pycache__/__init__.cpython-310.pyc b/comfyui_essentials/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bea2a0f20b20a18f85f4524b57d2da7749ec9279
Binary files /dev/null and b/comfyui_essentials/__pycache__/__init__.cpython-310.pyc differ
diff --git a/comfyui_essentials/__pycache__/conditioning.cpython-310.pyc b/comfyui_essentials/__pycache__/conditioning.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..05ef043f43eb042cf4595db86f0c16deff645329
Binary files /dev/null and b/comfyui_essentials/__pycache__/conditioning.cpython-310.pyc differ
diff --git a/comfyui_essentials/__pycache__/image.cpython-310.pyc b/comfyui_essentials/__pycache__/image.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..34c4438256cfeee558e35c2b00aaed8f9e54c884
Binary files /dev/null and b/comfyui_essentials/__pycache__/image.cpython-310.pyc differ
diff --git a/comfyui_essentials/__pycache__/mask.cpython-310.pyc b/comfyui_essentials/__pycache__/mask.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6c8fbb74b013a25a967a8e80fe077b8d3691fbdb
Binary files /dev/null and b/comfyui_essentials/__pycache__/mask.cpython-310.pyc differ
diff --git a/comfyui_essentials/__pycache__/misc.cpython-310.pyc b/comfyui_essentials/__pycache__/misc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ba3f183467744d70136a3cb1cf0812740b975ec7
Binary files /dev/null and b/comfyui_essentials/__pycache__/misc.cpython-310.pyc differ
diff --git a/comfyui_essentials/__pycache__/sampling.cpython-310.pyc b/comfyui_essentials/__pycache__/sampling.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5926646f8a5595405f33675eef8ece053d6b34ae
Binary files /dev/null and b/comfyui_essentials/__pycache__/sampling.cpython-310.pyc differ
diff --git a/comfyui_essentials/__pycache__/segmentation.cpython-310.pyc b/comfyui_essentials/__pycache__/segmentation.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3df112da57f0c776f2ecb2722fd41af6f540c8db
Binary files /dev/null and b/comfyui_essentials/__pycache__/segmentation.cpython-310.pyc differ
diff --git a/comfyui_essentials/__pycache__/text.cpython-310.pyc b/comfyui_essentials/__pycache__/text.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ea34186320b29485a14b60b8c23c08aff8b46034
Binary files /dev/null and b/comfyui_essentials/__pycache__/text.cpython-310.pyc differ
diff --git a/comfyui_essentials/__pycache__/utils.cpython-310.pyc b/comfyui_essentials/__pycache__/utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..44329c0f58cbd10dd2ea5279937a65d18e758a17
Binary files /dev/null and b/comfyui_essentials/__pycache__/utils.cpython-310.pyc differ
diff --git a/comfyui_essentials/carve.py b/comfyui_essentials/carve.py
new file mode 100644
index 0000000000000000000000000000000000000000..017e804d84324fde3d4004a3ed832676b8237985
--- /dev/null
+++ b/comfyui_essentials/carve.py
@@ -0,0 +1,454 @@
+# MIT licensed code from https://github.com/li-plus/seam-carving/
+
+from enum import Enum
+from typing import Optional, Tuple
+
+import numba as nb
+import numpy as np
+from scipy.ndimage import sobel
+
+DROP_MASK_ENERGY = 1e5
+KEEP_MASK_ENERGY = 1e3
+
+
+class OrderMode(str, Enum):
+ WIDTH_FIRST = "width-first"
+ HEIGHT_FIRST = "height-first"
+
+
+class EnergyMode(str, Enum):
+ FORWARD = "forward"
+ BACKWARD = "backward"
+
+
+def _list_enum(enum_class) -> Tuple:
+ return tuple(x.value for x in enum_class)
+
+
+def _rgb2gray(rgb: np.ndarray) -> np.ndarray:
+ """Convert an RGB image to a grayscale image"""
+ coeffs = np.array([0.2125, 0.7154, 0.0721], dtype=np.float32)
+ return (rgb @ coeffs).astype(rgb.dtype)
+
+
+def _get_seam_mask(src: np.ndarray, seam: np.ndarray) -> np.ndarray:
+ """Convert a list of seam column indices to a mask"""
+ return np.eye(src.shape[1], dtype=bool)[seam]
+
+
+def _remove_seam_mask(src: np.ndarray, seam_mask: np.ndarray) -> np.ndarray:
+ """Remove a seam from the source image according to the given seam_mask"""
+ if src.ndim == 3:
+ h, w, c = src.shape
+ seam_mask = np.broadcast_to(seam_mask[:, :, None], src.shape)
+ dst = src[~seam_mask].reshape((h, w - 1, c))
+ else:
+ h, w = src.shape
+ dst = src[~seam_mask].reshape((h, w - 1))
+ return dst
+
+
+def _get_energy(gray: np.ndarray) -> np.ndarray:
+ """Get backward energy map from the source image"""
+ assert gray.ndim == 2
+
+ gray = gray.astype(np.float32)
+ grad_x = sobel(gray, axis=1)
+ grad_y = sobel(gray, axis=0)
+ energy = np.abs(grad_x) + np.abs(grad_y)
+ return energy
+
+
+@nb.njit(nb.int32[:](nb.float32[:, :]), cache=True)
+def _get_backward_seam(energy: np.ndarray) -> np.ndarray:
+ """Compute the minimum vertical seam from the backward energy map"""
+ h, w = energy.shape
+ inf = np.array([np.inf], dtype=np.float32)
+ cost = np.concatenate((inf, energy[0], inf))
+ parent = np.empty((h, w), dtype=np.int32)
+ base_idx = np.arange(-1, w - 1, dtype=np.int32)
+
+ for r in range(1, h):
+ choices = np.vstack((cost[:-2], cost[1:-1], cost[2:]))
+ min_idx = np.argmin(choices, axis=0) + base_idx
+ parent[r] = min_idx
+ cost[1:-1] = cost[1:-1][min_idx] + energy[r]
+
+ c = np.argmin(cost[1:-1])
+ seam = np.empty(h, dtype=np.int32)
+ for r in range(h - 1, -1, -1):
+ seam[r] = c
+ c = parent[r, c]
+
+ return seam
+
+
+def _get_backward_seams(
+ gray: np.ndarray, num_seams: int, aux_energy: Optional[np.ndarray]
+) -> np.ndarray:
+ """Compute the minimum N vertical seams using backward energy"""
+ h, w = gray.shape
+ seams = np.zeros((h, w), dtype=bool)
+ rows = np.arange(h, dtype=np.int32)
+ idx_map = np.broadcast_to(np.arange(w, dtype=np.int32), (h, w))
+ energy = _get_energy(gray)
+ if aux_energy is not None:
+ energy += aux_energy
+ for _ in range(num_seams):
+ seam = _get_backward_seam(energy)
+ seams[rows, idx_map[rows, seam]] = True
+
+ seam_mask = _get_seam_mask(gray, seam)
+ gray = _remove_seam_mask(gray, seam_mask)
+ idx_map = _remove_seam_mask(idx_map, seam_mask)
+ if aux_energy is not None:
+ aux_energy = _remove_seam_mask(aux_energy, seam_mask)
+
+ # Only need to re-compute the energy in the bounding box of the seam
+ _, cur_w = energy.shape
+ lo = max(0, np.min(seam) - 1)
+ hi = min(cur_w, np.max(seam) + 1)
+ pad_lo = 1 if lo > 0 else 0
+ pad_hi = 1 if hi < cur_w - 1 else 0
+ mid_block = gray[:, lo - pad_lo : hi + pad_hi]
+ _, mid_w = mid_block.shape
+ mid_energy = _get_energy(mid_block)[:, pad_lo : mid_w - pad_hi]
+ if aux_energy is not None:
+ mid_energy += aux_energy[:, lo:hi]
+ energy = np.hstack((energy[:, :lo], mid_energy, energy[:, hi + 1 :]))
+
+ return seams
+
+
+@nb.njit(
+ [
+ nb.int32[:](nb.float32[:, :], nb.none),
+ nb.int32[:](nb.float32[:, :], nb.float32[:, :]),
+ ],
+ cache=True,
+)
+def _get_forward_seam(gray: np.ndarray, aux_energy: Optional[np.ndarray]) -> np.ndarray:
+ """Compute the minimum vertical seam using forward energy"""
+ h, w = gray.shape
+
+ gray = np.hstack((gray[:, :1], gray, gray[:, -1:]))
+
+ inf = np.array([np.inf], dtype=np.float32)
+ dp = np.concatenate((inf, np.abs(gray[0, 2:] - gray[0, :-2]), inf))
+
+ parent = np.empty((h, w), dtype=np.int32)
+ base_idx = np.arange(-1, w - 1, dtype=np.int32)
+
+ inf = np.array([np.inf], dtype=np.float32)
+ for r in range(1, h):
+ curr_shl = gray[r, 2:]
+ curr_shr = gray[r, :-2]
+ cost_mid = np.abs(curr_shl - curr_shr)
+ if aux_energy is not None:
+ cost_mid += aux_energy[r]
+
+ prev_mid = gray[r - 1, 1:-1]
+ cost_left = cost_mid + np.abs(prev_mid - curr_shr)
+ cost_right = cost_mid + np.abs(prev_mid - curr_shl)
+
+ dp_mid = dp[1:-1]
+ dp_left = dp[:-2]
+ dp_right = dp[2:]
+
+ choices = np.vstack(
+ (cost_left + dp_left, cost_mid + dp_mid, cost_right + dp_right)
+ )
+ min_idx = np.argmin(choices, axis=0)
+ parent[r] = min_idx + base_idx
+ # numba does not support specifying axis in np.min, below loop is equivalent to:
+ # `dp_mid[:] = np.min(choices, axis=0)` or `dp_mid[:] = choices[min_idx, np.arange(w)]`
+ for j, i in enumerate(min_idx):
+ dp_mid[j] = choices[i, j]
+
+ c = np.argmin(dp[1:-1])
+ seam = np.empty(h, dtype=np.int32)
+ for r in range(h - 1, -1, -1):
+ seam[r] = c
+ c = parent[r, c]
+
+ return seam
+
+
+def _get_forward_seams(
+ gray: np.ndarray, num_seams: int, aux_energy: Optional[np.ndarray]
+) -> np.ndarray:
+ """Compute minimum N vertical seams using forward energy"""
+ h, w = gray.shape
+ seams = np.zeros((h, w), dtype=bool)
+ rows = np.arange(h, dtype=np.int32)
+ idx_map = np.broadcast_to(np.arange(w, dtype=np.int32), (h, w))
+ for _ in range(num_seams):
+ seam = _get_forward_seam(gray, aux_energy)
+ seams[rows, idx_map[rows, seam]] = True
+ seam_mask = _get_seam_mask(gray, seam)
+ gray = _remove_seam_mask(gray, seam_mask)
+ idx_map = _remove_seam_mask(idx_map, seam_mask)
+ if aux_energy is not None:
+ aux_energy = _remove_seam_mask(aux_energy, seam_mask)
+
+ return seams
+
+
+def _get_seams(
+ gray: np.ndarray, num_seams: int, energy_mode: str, aux_energy: Optional[np.ndarray]
+) -> np.ndarray:
+ """Get the minimum N seams from the grayscale image"""
+ gray = np.asarray(gray, dtype=np.float32)
+ if energy_mode == EnergyMode.BACKWARD:
+ return _get_backward_seams(gray, num_seams, aux_energy)
+ elif energy_mode == EnergyMode.FORWARD:
+ return _get_forward_seams(gray, num_seams, aux_energy)
+ else:
+ raise ValueError(
+ f"expect energy_mode to be one of {_list_enum(EnergyMode)}, got {energy_mode}"
+ )
+
+
+def _reduce_width(
+ src: np.ndarray,
+ delta_width: int,
+ energy_mode: str,
+ aux_energy: Optional[np.ndarray],
+) -> Tuple[np.ndarray, Optional[np.ndarray]]:
+ """Reduce the width of image by delta_width pixels"""
+ assert src.ndim in (2, 3) and delta_width >= 0
+ if src.ndim == 2:
+ gray = src
+ src_h, src_w = src.shape
+ dst_shape: Tuple[int, ...] = (src_h, src_w - delta_width)
+ else:
+ gray = _rgb2gray(src)
+ src_h, src_w, src_c = src.shape
+ dst_shape = (src_h, src_w - delta_width, src_c)
+
+ to_keep = ~_get_seams(gray, delta_width, energy_mode, aux_energy)
+ dst = src[to_keep].reshape(dst_shape)
+ if aux_energy is not None:
+ aux_energy = aux_energy[to_keep].reshape(dst_shape[:2])
+ return dst, aux_energy
+
+
+@nb.njit(
+ nb.float32[:, :, :](nb.float32[:, :, :], nb.boolean[:, :], nb.int32), cache=True
+)
+def _insert_seams_kernel(
+ src: np.ndarray, seams: np.ndarray, delta_width: int
+) -> np.ndarray:
+ """The numba kernel for inserting seams"""
+ src_h, src_w, src_c = src.shape
+ dst = np.empty((src_h, src_w + delta_width, src_c), dtype=src.dtype)
+ for row in range(src_h):
+ dst_col = 0
+ for src_col in range(src_w):
+ if seams[row, src_col]:
+ left = src[row, max(src_col - 1, 0)]
+ right = src[row, src_col]
+ dst[row, dst_col] = (left + right) / 2
+ dst_col += 1
+ dst[row, dst_col] = src[row, src_col]
+ dst_col += 1
+ return dst
+
+
+def _insert_seams(src: np.ndarray, seams: np.ndarray, delta_width: int) -> np.ndarray:
+ """Insert multiple seams into the source image"""
+ dst = src.astype(np.float32)
+ if dst.ndim == 2:
+ dst = dst[:, :, None]
+ dst = _insert_seams_kernel(dst, seams, delta_width).astype(src.dtype)
+ if src.ndim == 2:
+ dst = dst.squeeze(-1)
+ return dst
+
+
+def _expand_width(
+ src: np.ndarray,
+ delta_width: int,
+ energy_mode: str,
+ aux_energy: Optional[np.ndarray],
+ step_ratio: float,
+) -> Tuple[np.ndarray, Optional[np.ndarray]]:
+ """Expand the width of image by delta_width pixels"""
+ assert src.ndim in (2, 3) and delta_width >= 0
+ if not 0 < step_ratio <= 1:
+ raise ValueError(f"expect `step_ratio` to be between (0,1], got {step_ratio}")
+
+ dst = src
+ while delta_width > 0:
+ max_step_size = max(1, round(step_ratio * dst.shape[1]))
+ step_size = min(max_step_size, delta_width)
+ gray = dst if dst.ndim == 2 else _rgb2gray(dst)
+ seams = _get_seams(gray, step_size, energy_mode, aux_energy)
+ dst = _insert_seams(dst, seams, step_size)
+ if aux_energy is not None:
+ aux_energy = _insert_seams(aux_energy, seams, step_size)
+ delta_width -= step_size
+
+ return dst, aux_energy
+
+
+def _resize_width(
+ src: np.ndarray,
+ width: int,
+ energy_mode: str,
+ aux_energy: Optional[np.ndarray],
+ step_ratio: float,
+) -> Tuple[np.ndarray, Optional[np.ndarray]]:
+ """Resize the width of image by removing vertical seams"""
+ assert src.size > 0 and src.ndim in (2, 3)
+ assert width > 0
+
+ src_w = src.shape[1]
+ if src_w < width:
+ dst, aux_energy = _expand_width(
+ src, width - src_w, energy_mode, aux_energy, step_ratio
+ )
+ else:
+ dst, aux_energy = _reduce_width(src, src_w - width, energy_mode, aux_energy)
+ return dst, aux_energy
+
+
+def _transpose_image(src: np.ndarray) -> np.ndarray:
+ """Transpose a source image in rgb or grayscale format"""
+ if src.ndim == 3:
+ dst = src.transpose((1, 0, 2))
+ else:
+ dst = src.T
+ return dst
+
+
+def _resize_height(
+ src: np.ndarray,
+ height: int,
+ energy_mode: str,
+ aux_energy: Optional[np.ndarray],
+ step_ratio: float,
+) -> Tuple[np.ndarray, Optional[np.ndarray]]:
+ """Resize the height of image by removing horizontal seams"""
+ assert src.ndim in (2, 3) and height > 0
+ if aux_energy is not None:
+ aux_energy = aux_energy.T
+ src = _transpose_image(src)
+ src, aux_energy = _resize_width(src, height, energy_mode, aux_energy, step_ratio)
+ src = _transpose_image(src)
+ if aux_energy is not None:
+ aux_energy = aux_energy.T
+ return src, aux_energy
+
+
+def _check_mask(mask: np.ndarray, shape: Tuple[int, ...]) -> np.ndarray:
+ """Ensure the mask to be a 2D grayscale map of specific shape"""
+ mask = np.asarray(mask, dtype=bool)
+ if mask.ndim != 2:
+ raise ValueError(f"expect mask to be a 2d binary map, got shape {mask.shape}")
+ if mask.shape != shape:
+ raise ValueError(
+ f"expect the shape of mask to match the image, got {mask.shape} vs {shape}"
+ )
+ return mask
+
+
+def _check_src(src: np.ndarray) -> np.ndarray:
+ """Ensure the source to be RGB or grayscale"""
+ src = np.asarray(src)
+ if src.size == 0 or src.ndim not in (2, 3):
+ raise ValueError(
+ f"expect a 3d rgb image or a 2d grayscale image, got image in shape {src.shape}"
+ )
+ return src
+
+
+def seam_carving(
+ src: np.ndarray,
+ size: Optional[Tuple[int, int]] = None,
+ energy_mode: str = "backward",
+ order: str = "width-first",
+ keep_mask: Optional[np.ndarray] = None,
+ drop_mask: Optional[np.ndarray] = None,
+ step_ratio: float = 0.5,
+) -> np.ndarray:
+ """Resize the image using the content-aware seam-carving algorithm.
+
+ :param src: A source image in RGB or grayscale format.
+ :param size: The target size in pixels, as a 2-tuple (width, height).
+ :param energy_mode: Policy to compute energy for the source image. Could be
+ one of ``backward`` or ``forward``. If ``backward``, compute the energy
+ as the gradient at each pixel. If ``forward``, compute the energy as the
+ distances between adjacent pixels after each pixel is removed.
+ :param order: The order to remove horizontal and vertical seams. Could be
+ one of ``width-first`` or ``height-first``. In ``width-first`` mode, we
+ remove or insert all vertical seams first, then the horizontal ones,
+ while ``height-first`` is the opposite.
+ :param keep_mask: An optional mask where the foreground is protected from
+ seam removal. If not specified, no area will be protected.
+ :param drop_mask: An optional binary object mask to remove. If given, the
+ object will be removed before resizing the image to the target size.
+ :param step_ratio: The maximum size expansion ratio in one seam carving step.
+ The image will be expanded in multiple steps if target size is too large.
+ :return: A resized copy of the source image.
+ """
+ src = _check_src(src)
+
+ if order not in _list_enum(OrderMode):
+ raise ValueError(
+ f"expect order to be one of {_list_enum(OrderMode)}, got {order}"
+ )
+
+ aux_energy = None
+
+ if keep_mask is not None:
+ keep_mask = _check_mask(keep_mask, src.shape[:2])
+
+ aux_energy = np.zeros(src.shape[:2], dtype=np.float32)
+ aux_energy[keep_mask] += KEEP_MASK_ENERGY
+
+ # remove object if `drop_mask` is given
+ if drop_mask is not None:
+ drop_mask = _check_mask(drop_mask, src.shape[:2])
+
+ if aux_energy is None:
+ aux_energy = np.zeros(src.shape[:2], dtype=np.float32)
+ aux_energy[drop_mask] -= DROP_MASK_ENERGY
+
+ if order == OrderMode.HEIGHT_FIRST:
+ src = _transpose_image(src)
+ aux_energy = aux_energy.T
+
+ num_seams = (aux_energy < 0).sum(1).max()
+ while num_seams > 0:
+ src, aux_energy = _reduce_width(src, num_seams, energy_mode, aux_energy)
+ num_seams = (aux_energy < 0).sum(1).max()
+
+ if order == OrderMode.HEIGHT_FIRST:
+ src = _transpose_image(src)
+ aux_energy = aux_energy.T
+
+ # resize image if `size` is given
+ if size is not None:
+ width, height = size
+ width = round(width)
+ height = round(height)
+ if width <= 0 or height <= 0:
+ raise ValueError(f"expect target size to be positive, got {size}")
+
+ if order == OrderMode.WIDTH_FIRST:
+ src, aux_energy = _resize_width(
+ src, width, energy_mode, aux_energy, step_ratio
+ )
+ src, aux_energy = _resize_height(
+ src, height, energy_mode, aux_energy, step_ratio
+ )
+ else:
+ src, aux_energy = _resize_height(
+ src, height, energy_mode, aux_energy, step_ratio
+ )
+ src, aux_energy = _resize_width(
+ src, width, energy_mode, aux_energy, step_ratio
+ )
+
+ return src
diff --git a/comfyui_essentials/conditioning.py b/comfyui_essentials/conditioning.py
new file mode 100644
index 0000000000000000000000000000000000000000..58e199fe8f8d70914cb93df6967a3b97c1136f82
--- /dev/null
+++ b/comfyui_essentials/conditioning.py
@@ -0,0 +1,100 @@
+import torch
+from nodes import MAX_RESOLUTION, ConditioningZeroOut, ConditioningSetTimestepRange, ConditioningCombine
+
+class CLIPTextEncodeSDXLSimplified:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {"required": {
+ "width": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
+ "height": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
+ "size_cond_factor": ("INT", {"default": 4, "min": 1, "max": 16 }),
+ "text": ("STRING", {"multiline": True, "dynamicPrompts": True, "default": ""}),
+ "clip": ("CLIP", ),
+ }}
+ RETURN_TYPES = ("CONDITIONING",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/conditioning"
+
+ def execute(self, clip, width, height, size_cond_factor, text):
+ crop_w = 0
+ crop_h = 0
+ width = width*size_cond_factor
+ height = height*size_cond_factor
+ target_width = width
+ target_height = height
+ text_g = text_l = text
+
+ tokens = clip.tokenize(text_g)
+ tokens["l"] = clip.tokenize(text_l)["l"]
+ if len(tokens["l"]) != len(tokens["g"]):
+ empty = clip.tokenize("")
+ while len(tokens["l"]) < len(tokens["g"]):
+ tokens["l"] += empty["l"]
+ while len(tokens["l"]) > len(tokens["g"]):
+ tokens["g"] += empty["g"]
+ cond, pooled = clip.encode_from_tokens(tokens, return_pooled=True)
+ return ([[cond, {"pooled_output": pooled, "width": width, "height": height, "crop_w": crop_w, "crop_h": crop_h, "target_width": target_width, "target_height": target_height}]], )
+
+class ConditioningCombineMultiple:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "conditioning_1": ("CONDITIONING",),
+ "conditioning_2": ("CONDITIONING",),
+ }, "optional": {
+ "conditioning_3": ("CONDITIONING",),
+ "conditioning_4": ("CONDITIONING",),
+ "conditioning_5": ("CONDITIONING",),
+ },
+ }
+ RETURN_TYPES = ("CONDITIONING",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/conditioning"
+
+ def execute(self, conditioning_1, conditioning_2, conditioning_3=None, conditioning_4=None, conditioning_5=None):
+ c = conditioning_1 + conditioning_2
+
+ if conditioning_3 is not None:
+ c += conditioning_3
+ if conditioning_4 is not None:
+ c += conditioning_4
+ if conditioning_5 is not None:
+ c += conditioning_5
+
+ return (c,)
+
+class SD3NegativeConditioning:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {"required": {
+ "conditioning": ("CONDITIONING",),
+ "end": ("FLOAT", {"default": 0.1, "min": 0.0, "max": 1.0, "step": 0.001 }),
+ }}
+ RETURN_TYPES = ("CONDITIONING",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/conditioning"
+
+ def execute(self, conditioning, end):
+ zero_c = ConditioningZeroOut().zero_out(conditioning)[0]
+
+ if end == 0:
+ return (zero_c, )
+
+ c = ConditioningSetTimestepRange().set_range(conditioning, 0, end)[0]
+ zero_c = ConditioningSetTimestepRange().set_range(zero_c, end, 1.0)[0]
+ c = ConditioningCombine().combine(zero_c, c)[0]
+
+ return (c, )
+
+COND_CLASS_MAPPINGS = {
+ "CLIPTextEncodeSDXL+": CLIPTextEncodeSDXLSimplified,
+ "ConditioningCombineMultiple+": ConditioningCombineMultiple,
+ "SD3NegativeConditioning+": SD3NegativeConditioning,
+}
+
+COND_NAME_MAPPINGS = {
+ "CLIPTextEncodeSDXL+": "🔧 SDXL CLIPTextEncode",
+ "ConditioningCombineMultiple+": "🔧 Cond Combine Multiple",
+ "SD3NegativeConditioning+": "🔧 SD3 Negative Conditioning"
+}
\ No newline at end of file
diff --git a/comfyui_essentials/fonts/ShareTechMono-Regular.ttf b/comfyui_essentials/fonts/ShareTechMono-Regular.ttf
new file mode 100644
index 0000000000000000000000000000000000000000..0ae0b19750c51a751bc45f54622443d55d643999
Binary files /dev/null and b/comfyui_essentials/fonts/ShareTechMono-Regular.ttf differ
diff --git a/comfyui_essentials/fonts/put_font_files_here.txt b/comfyui_essentials/fonts/put_font_files_here.txt
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/comfyui_essentials/histogram_matching.py b/comfyui_essentials/histogram_matching.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7b469446ad98c6e310453981c4e439431e98049
--- /dev/null
+++ b/comfyui_essentials/histogram_matching.py
@@ -0,0 +1,87 @@
+# from MIT licensed https://github.com/nemodleo/pytorch-histogram-matching
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+class Histogram_Matching(nn.Module):
+ def __init__(self, differentiable=False):
+ super(Histogram_Matching, self).__init__()
+ self.differentiable = differentiable
+
+ def forward(self, dst, ref):
+ # B C
+ B, C, H, W = dst.size()
+ # assertion
+ assert dst.device == ref.device
+ # [B*C 256]
+ hist_dst = self.cal_hist(dst)
+ hist_ref = self.cal_hist(ref)
+ # [B*C 256]
+ tables = self.cal_trans_batch(hist_dst, hist_ref)
+ # [B C H W]
+ rst = dst.clone()
+ for b in range(B):
+ for c in range(C):
+ rst[b,c] = tables[b*c, (dst[b,c] * 255).long()]
+ # [B C H W]
+ rst /= 255.
+ return rst
+
+ def cal_hist(self, img):
+ B, C, H, W = img.size()
+ # [B*C 256]
+ if self.differentiable:
+ hists = self.soft_histc_batch(img * 255, bins=256, min=0, max=256, sigma=3*25)
+ else:
+ hists = torch.stack([torch.histc(img[b,c] * 255, bins=256, min=0, max=255) for b in range(B) for c in range(C)])
+ hists = hists.float()
+ hists = F.normalize(hists, p=1)
+ # BC 256
+ bc, n = hists.size()
+ # [B*C 256 256]
+ triu = torch.ones(bc, n, n, device=hists.device).triu()
+ # [B*C 256]
+ hists = torch.bmm(hists[:,None,:], triu)[:,0,:]
+ return hists
+
+ def soft_histc_batch(self, x, bins=256, min=0, max=256, sigma=3*25):
+ # B C H W
+ B, C, H, W = x.size()
+ # [B*C H*W]
+ x = x.view(B*C, -1)
+ # 1
+ delta = float(max - min) / float(bins)
+ # [256]
+ centers = float(min) + delta * (torch.arange(bins, device=x.device, dtype=torch.bfloat16) + 0.5)
+ # [B*C 1 H*W]
+ x = torch.unsqueeze(x, 1)
+ # [1 256 1]
+ centers = centers[None,:,None]
+ # [B*C 256 H*W]
+ x = x - centers
+ # [B*C 256 H*W]
+ x = x.type(torch.bfloat16)
+ # [B*C 256 H*W]
+ x = torch.sigmoid(sigma * (x + delta/2)) - torch.sigmoid(sigma * (x - delta/2))
+ # [B*C 256]
+ x = x.sum(dim=2)
+ # [B*C 256]
+ x = x.type(torch.float32)
+ # prevent oom
+ # torch.cuda.empty_cache()
+ return x
+
+ def cal_trans_batch(self, hist_dst, hist_ref):
+ # [B*C 256 256]
+ hist_dst = hist_dst[:,None,:].repeat(1,256,1)
+ # [B*C 256 256]
+ hist_ref = hist_ref[:,:,None].repeat(1,1,256)
+ # [B*C 256 256]
+ table = hist_dst - hist_ref
+ # [B*C 256 256]
+ table = torch.where(table>=0, 1., 0.)
+ # [B*C 256]
+ table = torch.sum(table, dim=1) - 1
+ # [B*C 256]
+ table = torch.clamp(table, min=0, max=255)
+ return table
diff --git a/comfyui_essentials/image.py b/comfyui_essentials/image.py
new file mode 100644
index 0000000000000000000000000000000000000000..726a8d0d53fa2ec487ad01083031dd058f17b38e
--- /dev/null
+++ b/comfyui_essentials/image.py
@@ -0,0 +1,1697 @@
+from .utils import max_, min_
+from nodes import MAX_RESOLUTION
+import comfy.utils
+from nodes import SaveImage
+from node_helpers import pillow
+from PIL import Image, ImageOps
+
+import kornia
+import torch
+import torch.nn.functional as F
+import torchvision.transforms.v2 as T
+
+import warnings
+warnings.filterwarnings('ignore', module="torchvision")
+import math
+import os
+import numpy as np
+import folder_paths
+import random
+
+"""
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ Image analysis
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+"""
+
+class ImageEnhanceDifference:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image1": ("IMAGE",),
+ "image2": ("IMAGE",),
+ "exponent": ("FLOAT", { "default": 0.75, "min": 0.00, "max": 1.00, "step": 0.05, }),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image analysis"
+
+ def execute(self, image1, image2, exponent):
+ if image1.shape[1:] != image2.shape[1:]:
+ image2 = comfy.utils.common_upscale(image2.permute([0,3,1,2]), image1.shape[2], image1.shape[1], upscale_method='bicubic', crop='center').permute([0,2,3,1])
+
+ diff_image = image1 - image2
+ diff_image = torch.pow(diff_image, exponent)
+ diff_image = torch.clamp(diff_image, 0, 1)
+
+ return(diff_image,)
+
+"""
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ Batch tools
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+"""
+
+class ImageBatchMultiple:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image_1": ("IMAGE",),
+ "method": (["nearest-exact", "bilinear", "area", "bicubic", "lanczos"], { "default": "lanczos" }),
+ }, "optional": {
+ "image_2": ("IMAGE",),
+ "image_3": ("IMAGE",),
+ "image_4": ("IMAGE",),
+ "image_5": ("IMAGE",),
+ },
+ }
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image batch"
+
+ def execute(self, image_1, method, image_2=None, image_3=None, image_4=None, image_5=None):
+ out = image_1
+
+ if image_2 is not None:
+ if image_1.shape[1:] != image_2.shape[1:]:
+ image_2 = comfy.utils.common_upscale(image_2.movedim(-1,1), image_1.shape[2], image_1.shape[1], method, "center").movedim(1,-1)
+ out = torch.cat((image_1, image_2), dim=0)
+ if image_3 is not None:
+ if image_1.shape[1:] != image_3.shape[1:]:
+ image_3 = comfy.utils.common_upscale(image_3.movedim(-1,1), image_1.shape[2], image_1.shape[1], method, "center").movedim(1,-1)
+ out = torch.cat((out, image_3), dim=0)
+ if image_4 is not None:
+ if image_1.shape[1:] != image_4.shape[1:]:
+ image_4 = comfy.utils.common_upscale(image_4.movedim(-1,1), image_1.shape[2], image_1.shape[1], method, "center").movedim(1,-1)
+ out = torch.cat((out, image_4), dim=0)
+ if image_5 is not None:
+ if image_1.shape[1:] != image_5.shape[1:]:
+ image_5 = comfy.utils.common_upscale(image_5.movedim(-1,1), image_1.shape[2], image_1.shape[1], method, "center").movedim(1,-1)
+ out = torch.cat((out, image_5), dim=0)
+
+ return (out,)
+
+
+class ImageExpandBatch:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "size": ("INT", { "default": 16, "min": 1, "step": 1, }),
+ "method": (["expand", "repeat all", "repeat first", "repeat last"],)
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image batch"
+
+ def execute(self, image, size, method):
+ orig_size = image.shape[0]
+
+ if orig_size == size:
+ return (image,)
+
+ if size <= 1:
+ return (image[:size],)
+
+ if 'expand' in method:
+ out = torch.empty([size] + list(image.shape)[1:], dtype=image.dtype, device=image.device)
+ if size < orig_size:
+ scale = (orig_size - 1) / (size - 1)
+ for i in range(size):
+ out[i] = image[min(round(i * scale), orig_size - 1)]
+ else:
+ scale = orig_size / size
+ for i in range(size):
+ out[i] = image[min(math.floor((i + 0.5) * scale), orig_size - 1)]
+ elif 'all' in method:
+ out = image.repeat([math.ceil(size / image.shape[0])] + [1] * (len(image.shape) - 1))[:size]
+ elif 'first' in method:
+ if size < image.shape[0]:
+ out = image[:size]
+ else:
+ out = torch.cat([image[:1].repeat(size-image.shape[0], 1, 1, 1), image], dim=0)
+ elif 'last' in method:
+ if size < image.shape[0]:
+ out = image[:size]
+ else:
+ out = torch.cat((image, image[-1:].repeat((size-image.shape[0], 1, 1, 1))), dim=0)
+
+ return (out,)
+
+class ImageFromBatch:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE", ),
+ "start": ("INT", { "default": 0, "min": 0, "step": 1, }),
+ "length": ("INT", { "default": -1, "min": -1, "step": 1, }),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image batch"
+
+ def execute(self, image, start, length):
+ if length<0:
+ length = image.shape[0]
+ start = min(start, image.shape[0]-1)
+ length = min(image.shape[0]-start, length)
+ return (image[start:start + length], )
+
+
+class ImageListToBatch:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "execute"
+ INPUT_IS_LIST = True
+ CATEGORY = "essentials/image batch"
+
+ def execute(self, image):
+ shape = image[0].shape[1:3]
+ out = []
+
+ for i in range(len(image)):
+ img = image[i]
+ if image[i].shape[1:3] != shape:
+ img = comfy.utils.common_upscale(img.permute([0,3,1,2]), shape[1], shape[0], upscale_method='bicubic', crop='center').permute([0,2,3,1])
+ out.append(img)
+
+ out = torch.cat(out, dim=0)
+
+ return (out,)
+
+
+"""
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ Image manipulation
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+"""
+
+class ImageCompositeFromMaskBatch:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image_from": ("IMAGE", ),
+ "image_to": ("IMAGE", ),
+ "mask": ("MASK", )
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image manipulation"
+
+ def execute(self, image_from, image_to, mask):
+ frames = mask.shape[0]
+
+ if image_from.shape[1] != image_to.shape[1] or image_from.shape[2] != image_to.shape[2]:
+ image_to = comfy.utils.common_upscale(image_to.permute([0,3,1,2]), image_from.shape[2], image_from.shape[1], upscale_method='bicubic', crop='center').permute([0,2,3,1])
+
+ if frames < image_from.shape[0]:
+ image_from = image_from[:frames]
+ elif frames > image_from.shape[0]:
+ image_from = torch.cat((image_from, image_from[-1].unsqueeze(0).repeat(frames-image_from.shape[0], 1, 1, 1)), dim=0)
+
+ mask = mask.unsqueeze(3).repeat(1, 1, 1, 3)
+
+ if image_from.shape[1] != mask.shape[1] or image_from.shape[2] != mask.shape[2]:
+ mask = comfy.utils.common_upscale(mask.permute([0,3,1,2]), image_from.shape[2], image_from.shape[1], upscale_method='bicubic', crop='center').permute([0,2,3,1])
+
+ out = mask * image_to + (1 - mask) * image_from
+
+ return (out, )
+
+class ImageComposite:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "destination": ("IMAGE",),
+ "source": ("IMAGE",),
+ "x": ("INT", { "default": 0, "min": -MAX_RESOLUTION, "max": MAX_RESOLUTION, "step": 1 }),
+ "y": ("INT", { "default": 0, "min": -MAX_RESOLUTION, "max": MAX_RESOLUTION, "step": 1 }),
+ "offset_x": ("INT", { "default": 0, "min": -MAX_RESOLUTION, "max": MAX_RESOLUTION, "step": 1 }),
+ "offset_y": ("INT", { "default": 0, "min": -MAX_RESOLUTION, "max": MAX_RESOLUTION, "step": 1 }),
+ },
+ "optional": {
+ "mask": ("MASK",),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image manipulation"
+
+ def execute(self, destination, source, x, y, offset_x, offset_y, mask=None):
+ if mask is None:
+ mask = torch.ones_like(source)[:,:,:,0]
+
+ mask = mask.unsqueeze(-1).repeat(1, 1, 1, 3)
+
+ if mask.shape[1:3] != source.shape[1:3]:
+ mask = F.interpolate(mask.permute([0, 3, 1, 2]), size=(source.shape[1], source.shape[2]), mode='bicubic')
+ mask = mask.permute([0, 2, 3, 1])
+
+ if mask.shape[0] > source.shape[0]:
+ mask = mask[:source.shape[0]]
+ elif mask.shape[0] < source.shape[0]:
+ mask = torch.cat((mask, mask[-1:].repeat((source.shape[0]-mask.shape[0], 1, 1, 1))), dim=0)
+
+ if destination.shape[0] > source.shape[0]:
+ destination = destination[:source.shape[0]]
+ elif destination.shape[0] < source.shape[0]:
+ destination = torch.cat((destination, destination[-1:].repeat((source.shape[0]-destination.shape[0], 1, 1, 1))), dim=0)
+
+ if not isinstance(x, list):
+ x = [x]
+ if not isinstance(y, list):
+ y = [y]
+
+ if len(x) < destination.shape[0]:
+ x = x + [x[-1]] * (destination.shape[0] - len(x))
+ if len(y) < destination.shape[0]:
+ y = y + [y[-1]] * (destination.shape[0] - len(y))
+
+ x = [i + offset_x for i in x]
+ y = [i + offset_y for i in y]
+
+ output = []
+ for i in range(destination.shape[0]):
+ d = destination[i].clone()
+ s = source[i]
+ m = mask[i]
+
+ if x[i]+source.shape[2] > destination.shape[2]:
+ s = s[:, :, :destination.shape[2]-x[i], :]
+ m = m[:, :, :destination.shape[2]-x[i], :]
+ if y[i]+source.shape[1] > destination.shape[1]:
+ s = s[:, :destination.shape[1]-y[i], :, :]
+ m = m[:destination.shape[1]-y[i], :, :]
+
+ #output.append(s * m + d[y[i]:y[i]+s.shape[0], x[i]:x[i]+s.shape[1], :] * (1 - m))
+ d[y[i]:y[i]+s.shape[0], x[i]:x[i]+s.shape[1], :] = s * m + d[y[i]:y[i]+s.shape[0], x[i]:x[i]+s.shape[1], :] * (1 - m)
+ output.append(d)
+
+ output = torch.stack(output)
+
+ # apply the source to the destination at XY position using the mask
+ #for i in range(destination.shape[0]):
+ # output[i, y[i]:y[i]+source.shape[1], x[i]:x[i]+source.shape[2], :] = source * mask + destination[i, y[i]:y[i]+source.shape[1], x[i]:x[i]+source.shape[2], :] * (1 - mask)
+
+ #for x_, y_ in zip(x, y):
+ # output[:, y_:y_+source.shape[1], x_:x_+source.shape[2], :] = source * mask + destination[:, y_:y_+source.shape[1], x_:x_+source.shape[2], :] * (1 - mask)
+
+ #output[:, y:y+source.shape[1], x:x+source.shape[2], :] = source * mask + destination[:, y:y+source.shape[1], x:x+source.shape[2], :] * (1 - mask)
+ #output = destination * (1 - mask) + source * mask
+
+ return (output,)
+
+class ImageResize:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "width": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1, }),
+ "height": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1, }),
+ "interpolation": (["nearest", "bilinear", "bicubic", "area", "nearest-exact", "lanczos"],),
+ "method": (["stretch", "keep proportion", "fill / crop", "pad"],),
+ "condition": (["always", "downscale if bigger", "upscale if smaller", "if bigger area", "if smaller area"],),
+ "multiple_of": ("INT", { "default": 0, "min": 0, "max": 512, "step": 1, }),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE", "INT", "INT",)
+ RETURN_NAMES = ("IMAGE", "width", "height",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image manipulation"
+
+ def execute(self, image, width, height, method="stretch", interpolation="nearest", condition="always", multiple_of=0, keep_proportion=False):
+ _, oh, ow, _ = image.shape
+ x = y = x2 = y2 = 0
+ pad_left = pad_right = pad_top = pad_bottom = 0
+
+ if keep_proportion:
+ method = "keep proportion"
+
+ if multiple_of > 1:
+ width = width - (width % multiple_of)
+ height = height - (height % multiple_of)
+
+ if method == 'keep proportion' or method == 'pad':
+ if width == 0 and oh < height:
+ width = MAX_RESOLUTION
+ elif width == 0 and oh >= height:
+ width = ow
+
+ if height == 0 and ow < width:
+ height = MAX_RESOLUTION
+ elif height == 0 and ow >= width:
+ height = oh
+
+ ratio = min(width / ow, height / oh)
+ new_width = round(ow*ratio)
+ new_height = round(oh*ratio)
+
+ if method == 'pad':
+ pad_left = (width - new_width) // 2
+ pad_right = width - new_width - pad_left
+ pad_top = (height - new_height) // 2
+ pad_bottom = height - new_height - pad_top
+
+ width = new_width
+ height = new_height
+ elif method.startswith('fill'):
+ width = width if width > 0 else ow
+ height = height if height > 0 else oh
+
+ ratio = max(width / ow, height / oh)
+ new_width = round(ow*ratio)
+ new_height = round(oh*ratio)
+ x = (new_width - width) // 2
+ y = (new_height - height) // 2
+ x2 = x + width
+ y2 = y + height
+ if x2 > new_width:
+ x -= (x2 - new_width)
+ if x < 0:
+ x = 0
+ if y2 > new_height:
+ y -= (y2 - new_height)
+ if y < 0:
+ y = 0
+ width = new_width
+ height = new_height
+ else:
+ width = width if width > 0 else ow
+ height = height if height > 0 else oh
+
+ if "always" in condition \
+ or ("downscale if bigger" == condition and (oh > height or ow > width)) or ("upscale if smaller" == condition and (oh < height or ow < width)) \
+ or ("bigger area" in condition and (oh * ow > height * width)) or ("smaller area" in condition and (oh * ow < height * width)):
+
+ outputs = image.permute(0,3,1,2)
+
+ if interpolation == "lanczos":
+ outputs = comfy.utils.lanczos(outputs, width, height)
+ else:
+ outputs = F.interpolate(outputs, size=(height, width), mode=interpolation)
+
+ if method == 'pad':
+ if pad_left > 0 or pad_right > 0 or pad_top > 0 or pad_bottom > 0:
+ outputs = F.pad(outputs, (pad_left, pad_right, pad_top, pad_bottom), value=0)
+
+ outputs = outputs.permute(0,2,3,1)
+
+ if method.startswith('fill'):
+ if x > 0 or y > 0 or x2 > 0 or y2 > 0:
+ outputs = outputs[:, y:y2, x:x2, :]
+ else:
+ outputs = image
+
+ if multiple_of > 1 and (outputs.shape[2] % multiple_of != 0 or outputs.shape[1] % multiple_of != 0):
+ width = outputs.shape[2]
+ height = outputs.shape[1]
+ x = (width % multiple_of) // 2
+ y = (height % multiple_of) // 2
+ x2 = width - ((width % multiple_of) - x)
+ y2 = height - ((height % multiple_of) - y)
+ outputs = outputs[:, y:y2, x:x2, :]
+
+ outputs = torch.clamp(outputs, 0, 1)
+
+ return(outputs, outputs.shape[2], outputs.shape[1],)
+
+class ImageFlip:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "axis": (["x", "y", "xy"],),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image manipulation"
+
+ def execute(self, image, axis):
+ dim = ()
+ if "y" in axis:
+ dim += (1,)
+ if "x" in axis:
+ dim += (2,)
+ image = torch.flip(image, dim)
+
+ return(image,)
+
+class ImageCrop:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "width": ("INT", { "default": 256, "min": 0, "max": MAX_RESOLUTION, "step": 8, }),
+ "height": ("INT", { "default": 256, "min": 0, "max": MAX_RESOLUTION, "step": 8, }),
+ "position": (["top-left", "top-center", "top-right", "right-center", "bottom-right", "bottom-center", "bottom-left", "left-center", "center"],),
+ "x_offset": ("INT", { "default": 0, "min": -99999, "step": 1, }),
+ "y_offset": ("INT", { "default": 0, "min": -99999, "step": 1, }),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE","INT","INT",)
+ RETURN_NAMES = ("IMAGE","x","y",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image manipulation"
+
+ def execute(self, image, width, height, position, x_offset, y_offset):
+ _, oh, ow, _ = image.shape
+
+ width = min(ow, width)
+ height = min(oh, height)
+
+ if "center" in position:
+ x = round((ow-width) / 2)
+ y = round((oh-height) / 2)
+ if "top" in position:
+ y = 0
+ if "bottom" in position:
+ y = oh-height
+ if "left" in position:
+ x = 0
+ if "right" in position:
+ x = ow-width
+
+ x += x_offset
+ y += y_offset
+
+ x2 = x+width
+ y2 = y+height
+
+ if x2 > ow:
+ x2 = ow
+ if x < 0:
+ x = 0
+ if y2 > oh:
+ y2 = oh
+ if y < 0:
+ y = 0
+
+ image = image[:, y:y2, x:x2, :]
+
+ return(image, x, y, )
+
+class ImageTile:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "rows": ("INT", { "default": 2, "min": 1, "max": 256, "step": 1, }),
+ "cols": ("INT", { "default": 2, "min": 1, "max": 256, "step": 1, }),
+ "overlap": ("FLOAT", { "default": 0, "min": 0, "max": 0.5, "step": 0.01, }),
+ "overlap_x": ("INT", { "default": 0, "min": 0, "max": MAX_RESOLUTION//2, "step": 1, }),
+ "overlap_y": ("INT", { "default": 0, "min": 0, "max": MAX_RESOLUTION//2, "step": 1, }),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE", "INT", "INT", "INT", "INT")
+ RETURN_NAMES = ("IMAGE", "tile_width", "tile_height", "overlap_x", "overlap_y",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image manipulation"
+
+ def execute(self, image, rows, cols, overlap, overlap_x, overlap_y):
+ h, w = image.shape[1:3]
+ tile_h = h // rows
+ tile_w = w // cols
+ h = tile_h * rows
+ w = tile_w * cols
+ overlap_h = int(tile_h * overlap) + overlap_y
+ overlap_w = int(tile_w * overlap) + overlap_x
+
+ # max overlap is half of the tile size
+ overlap_h = min(tile_h // 2, overlap_h)
+ overlap_w = min(tile_w // 2, overlap_w)
+
+ if rows == 1:
+ overlap_h = 0
+ if cols == 1:
+ overlap_w = 0
+
+ tiles = []
+ for i in range(rows):
+ for j in range(cols):
+ y1 = i * tile_h
+ x1 = j * tile_w
+
+ if i > 0:
+ y1 -= overlap_h
+ if j > 0:
+ x1 -= overlap_w
+
+ y2 = y1 + tile_h + overlap_h
+ x2 = x1 + tile_w + overlap_w
+
+ if y2 > h:
+ y2 = h
+ y1 = y2 - tile_h - overlap_h
+ if x2 > w:
+ x2 = w
+ x1 = x2 - tile_w - overlap_w
+
+ tiles.append(image[:, y1:y2, x1:x2, :])
+ tiles = torch.cat(tiles, dim=0)
+
+ return(tiles, tile_w+overlap_w, tile_h+overlap_h, overlap_w, overlap_h,)
+
+class ImageUntile:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "tiles": ("IMAGE",),
+ "overlap_x": ("INT", { "default": 0, "min": 0, "max": MAX_RESOLUTION//2, "step": 1, }),
+ "overlap_y": ("INT", { "default": 0, "min": 0, "max": MAX_RESOLUTION//2, "step": 1, }),
+ "rows": ("INT", { "default": 2, "min": 1, "max": 256, "step": 1, }),
+ "cols": ("INT", { "default": 2, "min": 1, "max": 256, "step": 1, }),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image manipulation"
+
+ def execute(self, tiles, overlap_x, overlap_y, rows, cols):
+ tile_h, tile_w = tiles.shape[1:3]
+ tile_h -= overlap_y
+ tile_w -= overlap_x
+ out_w = cols * tile_w
+ out_h = rows * tile_h
+
+ out = torch.zeros((1, out_h, out_w, tiles.shape[3]), device=tiles.device, dtype=tiles.dtype)
+
+ for i in range(rows):
+ for j in range(cols):
+ y1 = i * tile_h
+ x1 = j * tile_w
+
+ if i > 0:
+ y1 -= overlap_y
+ if j > 0:
+ x1 -= overlap_x
+
+ y2 = y1 + tile_h + overlap_y
+ x2 = x1 + tile_w + overlap_x
+
+ if y2 > out_h:
+ y2 = out_h
+ y1 = y2 - tile_h - overlap_y
+ if x2 > out_w:
+ x2 = out_w
+ x1 = x2 - tile_w - overlap_x
+
+ mask = torch.ones((1, tile_h+overlap_y, tile_w+overlap_x), device=tiles.device, dtype=tiles.dtype)
+
+ # feather the overlap on top
+ if i > 0:
+ mask[:, :overlap_y, :] *= torch.linspace(0, 1, overlap_y, device=tiles.device, dtype=tiles.dtype).unsqueeze(1)
+ # feather the overlap on bottom
+ #if i < rows - 1:
+ # mask[:, -overlap_y:, :] *= torch.linspace(1, 0, overlap_y, device=tiles.device, dtype=tiles.dtype).unsqueeze(1)
+ # feather the overlap on left
+ if j > 0:
+ mask[:, :, :overlap_x] *= torch.linspace(0, 1, overlap_x, device=tiles.device, dtype=tiles.dtype).unsqueeze(0)
+ # feather the overlap on right
+ #if j < cols - 1:
+ # mask[:, :, -overlap_x:] *= torch.linspace(1, 0, overlap_x, device=tiles.device, dtype=tiles.dtype).unsqueeze(0)
+
+ mask = mask.unsqueeze(-1).repeat(1, 1, 1, tiles.shape[3])
+ tile = tiles[i * cols + j] * mask
+ out[:, y1:y2, x1:x2, :] = out[:, y1:y2, x1:x2, :] * (1 - mask) + tile
+ return(out, )
+
+class ImageSeamCarving:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "width": ("INT", { "default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1, }),
+ "height": ("INT", { "default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1, }),
+ "energy": (["backward", "forward"],),
+ "order": (["width-first", "height-first"],),
+ },
+ "optional": {
+ "keep_mask": ("MASK",),
+ "drop_mask": ("MASK",),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ CATEGORY = "essentials/image manipulation"
+ FUNCTION = "execute"
+
+ def execute(self, image, width, height, energy, order, keep_mask=None, drop_mask=None):
+ from .carve import seam_carving
+
+ img = image.permute([0, 3, 1, 2])
+
+ if keep_mask is not None:
+ #keep_mask = keep_mask.reshape((-1, 1, keep_mask.shape[-2], keep_mask.shape[-1])).movedim(1, -1)
+ keep_mask = keep_mask.unsqueeze(1)
+
+ if keep_mask.shape[2] != img.shape[2] or keep_mask.shape[3] != img.shape[3]:
+ keep_mask = F.interpolate(keep_mask, size=(img.shape[2], img.shape[3]), mode="bilinear")
+ if drop_mask is not None:
+ drop_mask = drop_mask.unsqueeze(1)
+
+ if drop_mask.shape[2] != img.shape[2] or drop_mask.shape[3] != img.shape[3]:
+ drop_mask = F.interpolate(drop_mask, size=(img.shape[2], img.shape[3]), mode="bilinear")
+
+ out = []
+ for i in range(img.shape[0]):
+ resized = seam_carving(
+ T.ToPILImage()(img[i]),
+ size=(width, height),
+ energy_mode=energy,
+ order=order,
+ keep_mask=T.ToPILImage()(keep_mask[i]) if keep_mask is not None else None,
+ drop_mask=T.ToPILImage()(drop_mask[i]) if drop_mask is not None else None,
+ )
+ out.append(T.ToTensor()(resized))
+
+ out = torch.stack(out).permute([0, 2, 3, 1])
+
+ return(out, )
+
+class ImageRandomTransform:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
+ "repeat": ("INT", { "default": 1, "min": 1, "max": 256, "step": 1, }),
+ "variation": ("FLOAT", { "default": 0.1, "min": 0.0, "max": 1.0, "step": 0.05, }),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image manipulation"
+
+ def execute(self, image, seed, repeat, variation):
+ h, w = image.shape[1:3]
+ image = image.repeat(repeat, 1, 1, 1).permute([0, 3, 1, 2])
+
+ distortion = 0.2 * variation
+ rotation = 5 * variation
+ brightness = 0.5 * variation
+ contrast = 0.5 * variation
+ saturation = 0.5 * variation
+ hue = 0.2 * variation
+ scale = 0.5 * variation
+
+ torch.manual_seed(seed)
+
+ out = []
+ for i in image:
+ tramsforms = T.Compose([
+ T.RandomPerspective(distortion_scale=distortion, p=0.5),
+ T.RandomRotation(degrees=rotation, interpolation=T.InterpolationMode.BILINEAR, expand=True),
+ T.ColorJitter(brightness=brightness, contrast=contrast, saturation=saturation, hue=(-hue, hue)),
+ T.RandomHorizontalFlip(p=0.5),
+ T.RandomResizedCrop((h, w), scale=(1-scale, 1+scale), ratio=(w/h, w/h), interpolation=T.InterpolationMode.BICUBIC),
+ ])
+ out.append(tramsforms(i.unsqueeze(0)))
+
+ out = torch.cat(out, dim=0).permute([0, 2, 3, 1])
+
+ return (out,)
+
+class RemBGSession:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "model": (["u2net: general purpose", "u2netp: lightweight general purpose", "u2net_human_seg: human segmentation", "u2net_cloth_seg: cloths Parsing", "silueta: very small u2net", "isnet-general-use: general purpose", "isnet-anime: anime illustrations", "sam: general purpose"],),
+ "providers": (['CPU', 'CUDA', 'ROCM', 'DirectML', 'OpenVINO', 'CoreML', 'Tensorrt', 'Azure'],),
+ },
+ }
+
+ RETURN_TYPES = ("REMBG_SESSION",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image manipulation"
+
+ def execute(self, model, providers):
+ from rembg import new_session, remove
+
+ model = model.split(":")[0]
+
+ class Session:
+ def __init__(self, model, providers):
+ self.session = new_session(model, providers=[providers+"ExecutionProvider"])
+ def process(self, image):
+ return remove(image, session=self.session)
+
+ return (Session(model, providers),)
+
+class TransparentBGSession:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "mode": (["base", "fast", "base-nightly"],),
+ "use_jit": ("BOOLEAN", { "default": True }),
+ },
+ }
+
+ RETURN_TYPES = ("REMBG_SESSION",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image manipulation"
+
+ def execute(self, mode, use_jit):
+ from transparent_background import Remover
+
+ class Session:
+ def __init__(self, mode, use_jit):
+ self.session = Remover(mode=mode, jit=use_jit)
+ def process(self, image):
+ return self.session.process(image)
+
+ return (Session(mode, use_jit),)
+
+class ImageRemoveBackground:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "rembg_session": ("REMBG_SESSION",),
+ "image": ("IMAGE",),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE", "MASK",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image manipulation"
+
+ def execute(self, rembg_session, image):
+ image = image.permute([0, 3, 1, 2])
+ output = []
+ for img in image:
+ img = T.ToPILImage()(img)
+ img = rembg_session.process(img)
+ output.append(T.ToTensor()(img))
+
+ output = torch.stack(output, dim=0)
+ output = output.permute([0, 2, 3, 1])
+ mask = output[:, :, :, 3] if output.shape[3] == 4 else torch.ones_like(output[:, :, :, 0])
+
+ return(output[:, :, :, :3], mask,)
+
+"""
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ Image processing
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+"""
+
+class ImageDesaturate:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "factor": ("FLOAT", { "default": 1.00, "min": 0.00, "max": 1.00, "step": 0.05, }),
+ "method": (["luminance (Rec.709)", "luminance (Rec.601)", "average", "lightness"],),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image processing"
+
+ def execute(self, image, factor, method):
+ if method == "luminance (Rec.709)":
+ grayscale = 0.2126 * image[..., 0] + 0.7152 * image[..., 1] + 0.0722 * image[..., 2]
+ elif method == "luminance (Rec.601)":
+ grayscale = 0.299 * image[..., 0] + 0.587 * image[..., 1] + 0.114 * image[..., 2]
+ elif method == "average":
+ grayscale = image.mean(dim=3)
+ elif method == "lightness":
+ grayscale = (torch.max(image, dim=3)[0] + torch.min(image, dim=3)[0]) / 2
+
+ grayscale = (1.0 - factor) * image + factor * grayscale.unsqueeze(-1).repeat(1, 1, 1, 3)
+ grayscale = torch.clamp(grayscale, 0, 1)
+
+ return(grayscale,)
+
+class PixelOEPixelize:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "downscale_mode": (["contrast", "bicubic", "nearest", "center", "k-centroid"],),
+ "target_size": ("INT", { "default": 128, "min": 0, "max": MAX_RESOLUTION, "step": 8 }),
+ "patch_size": ("INT", { "default": 16, "min": 4, "max": 32, "step": 2 }),
+ "thickness": ("INT", { "default": 2, "min": 1, "max": 16, "step": 1 }),
+ "color_matching": ("BOOLEAN", { "default": True }),
+ "upscale": ("BOOLEAN", { "default": True }),
+ #"contrast": ("FLOAT", { "default": 1.0, "min": 0.0, "max": 100.0, "step": 0.1 }),
+ #"saturation": ("FLOAT", { "default": 1.0, "min": 0.0, "max": 100.0, "step": 0.1 }),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image processing"
+
+ def execute(self, image, downscale_mode, target_size, patch_size, thickness, color_matching, upscale):
+ from pixeloe.pixelize import pixelize
+
+ image = image.clone().mul(255).clamp(0, 255).byte().cpu().numpy()
+ output = []
+ for img in image:
+ img = pixelize(img,
+ mode=downscale_mode,
+ target_size=target_size,
+ patch_size=patch_size,
+ thickness=thickness,
+ contrast=1.0,
+ saturation=1.0,
+ color_matching=color_matching,
+ no_upscale=not upscale)
+ output.append(T.ToTensor()(img))
+
+ output = torch.stack(output, dim=0).permute([0, 2, 3, 1])
+
+ return(output,)
+
+class ImagePosterize:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "threshold": ("FLOAT", { "default": 0.50, "min": 0.00, "max": 1.00, "step": 0.05, }),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image processing"
+
+ def execute(self, image, threshold):
+ image = image.mean(dim=3, keepdim=True)
+ image = (image > threshold).float()
+ image = image.repeat(1, 1, 1, 3)
+
+ return(image,)
+
+
+LUTS_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "luts")
+# From https://github.com/yoonsikp/pycubelut/blob/master/pycubelut.py (MIT license)
+class ImageApplyLUT:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "lut_file": (sorted([f for f in os.listdir(LUTS_DIR) if f.lower().endswith('.cube')]), ),
+ "gamma_correction": ("BOOLEAN", { "default": True }),
+ "clip_values": ("BOOLEAN", { "default": True }),
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.1 }),
+ }}
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image processing"
+
+ # TODO: check if we can do without numpy
+ def execute(self, image, lut_file, gamma_correction, clip_values, strength):
+ from colour.io.luts.iridas_cube import read_LUT_IridasCube
+
+ device = image.device
+ lut = read_LUT_IridasCube(os.path.join(LUTS_DIR, lut_file))
+ lut.name = lut_file
+
+ if clip_values:
+ if lut.domain[0].max() == lut.domain[0].min() and lut.domain[1].max() == lut.domain[1].min():
+ lut.table = np.clip(lut.table, lut.domain[0, 0], lut.domain[1, 0])
+ else:
+ if len(lut.table.shape) == 2: # 3x1D
+ for dim in range(3):
+ lut.table[:, dim] = np.clip(lut.table[:, dim], lut.domain[0, dim], lut.domain[1, dim])
+ else: # 3D
+ for dim in range(3):
+ lut.table[:, :, :, dim] = np.clip(lut.table[:, :, :, dim], lut.domain[0, dim], lut.domain[1, dim])
+
+ out = []
+ for img in image: # TODO: is this more resource efficient? should we use a batch instead?
+ lut_img = img.cpu().numpy().copy()
+
+ is_non_default_domain = not np.array_equal(lut.domain, np.array([[0., 0., 0.], [1., 1., 1.]]))
+ dom_scale = None
+ if is_non_default_domain:
+ dom_scale = lut.domain[1] - lut.domain[0]
+ lut_img = lut_img * dom_scale + lut.domain[0]
+ if gamma_correction:
+ lut_img = lut_img ** (1/2.2)
+ lut_img = lut.apply(lut_img)
+ if gamma_correction:
+ lut_img = lut_img ** (2.2)
+ if is_non_default_domain:
+ lut_img = (lut_img - lut.domain[0]) / dom_scale
+
+ lut_img = torch.from_numpy(lut_img).to(device)
+ if strength < 1.0:
+ lut_img = strength * lut_img + (1 - strength) * img
+ out.append(lut_img)
+
+ out = torch.stack(out)
+
+ return (out, )
+
+# From https://github.com/Jamy-L/Pytorch-Contrast-Adaptive-Sharpening/
+class ImageCAS:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "amount": ("FLOAT", {"default": 0.8, "min": 0, "max": 1, "step": 0.05}),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ CATEGORY = "essentials/image processing"
+ FUNCTION = "execute"
+
+ def execute(self, image, amount):
+ epsilon = 1e-5
+ img = F.pad(image.permute([0,3,1,2]), pad=(1, 1, 1, 1))
+
+ a = img[..., :-2, :-2]
+ b = img[..., :-2, 1:-1]
+ c = img[..., :-2, 2:]
+ d = img[..., 1:-1, :-2]
+ e = img[..., 1:-1, 1:-1]
+ f = img[..., 1:-1, 2:]
+ g = img[..., 2:, :-2]
+ h = img[..., 2:, 1:-1]
+ i = img[..., 2:, 2:]
+
+ # Computing contrast
+ cross = (b, d, e, f, h)
+ mn = min_(cross)
+ mx = max_(cross)
+
+ diag = (a, c, g, i)
+ mn2 = min_(diag)
+ mx2 = max_(diag)
+ mx = mx + mx2
+ mn = mn + mn2
+
+ # Computing local weight
+ inv_mx = torch.reciprocal(mx + epsilon)
+ amp = inv_mx * torch.minimum(mn, (2 - mx))
+
+ # scaling
+ amp = torch.sqrt(amp)
+ w = - amp * (amount * (1/5 - 1/8) + 1/8)
+ div = torch.reciprocal(1 + 4*w)
+
+ output = ((b + d + f + h)*w + e) * div
+ output = output.clamp(0, 1)
+ #output = torch.nan_to_num(output)
+
+ output = output.permute([0,2,3,1])
+
+ return (output,)
+
+class ExtractKeyframes:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "threshold": ("FLOAT", { "default": 0.85, "min": 0.00, "max": 1.00, "step": 0.01, }),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE", "STRING")
+ RETURN_NAMES = ("KEYFRAMES", "indexes")
+
+ FUNCTION = "execute"
+ CATEGORY = "essentials"
+
+ def execute(self, image, threshold):
+ window_size = 2
+
+ variations = torch.sum(torch.abs(image[1:] - image[:-1]), dim=[1, 2, 3])
+ #variations = torch.sum((image[1:] - image[:-1]) ** 2, dim=[1, 2, 3])
+ threshold = torch.quantile(variations.float(), threshold).item()
+
+ keyframes = []
+ for i in range(image.shape[0] - window_size + 1):
+ window = image[i:i + window_size]
+ variation = torch.sum(torch.abs(window[-1] - window[0])).item()
+
+ if variation > threshold:
+ keyframes.append(i + window_size - 1)
+
+ return (image[keyframes], ','.join(map(str, keyframes)),)
+
+class ImageColorMatch:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "reference": ("IMAGE",),
+ "color_space": (["LAB", "YCbCr", "RGB", "LUV", "YUV", "XYZ"],),
+ "factor": ("FLOAT", { "default": 1.0, "min": 0.0, "max": 1.0, "step": 0.05, }),
+ "device": (["auto", "cpu", "gpu"],),
+ "batch_size": ("INT", { "default": 0, "min": 0, "max": 1024, "step": 1, }),
+ },
+ "optional": {
+ "reference_mask": ("MASK",),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image processing"
+
+ def execute(self, image, reference, color_space, factor, device, batch_size, reference_mask=None):
+ if "gpu" == device:
+ device = comfy.model_management.get_torch_device()
+ elif "auto" == device:
+ device = comfy.model_management.intermediate_device()
+ else:
+ device = 'cpu'
+
+ image = image.permute([0, 3, 1, 2])
+ reference = reference.permute([0, 3, 1, 2]).to(device)
+
+ # Ensure reference_mask is in the correct format and on the right device
+ if reference_mask is not None:
+ assert reference_mask.ndim == 3, f"Expected reference_mask to have 3 dimensions, but got {reference_mask.ndim}"
+ assert reference_mask.shape[0] == reference.shape[0], f"Frame count mismatch: reference_mask has {reference_mask.shape[0]} frames, but reference has {reference.shape[0]}"
+
+ # Reshape mask to (batch, 1, height, width)
+ reference_mask = reference_mask.unsqueeze(1).to(device)
+
+ # Ensure the mask is binary (0 or 1)
+ reference_mask = (reference_mask > 0.5).float()
+
+ # Ensure spatial dimensions match
+ if reference_mask.shape[2:] != reference.shape[2:]:
+ reference_mask = comfy.utils.common_upscale(
+ reference_mask,
+ reference.shape[3], reference.shape[2],
+ upscale_method='bicubic',
+ crop='center'
+ )
+
+ if batch_size == 0 or batch_size > image.shape[0]:
+ batch_size = image.shape[0]
+
+ if "LAB" == color_space:
+ reference = kornia.color.rgb_to_lab(reference)
+ elif "YCbCr" == color_space:
+ reference = kornia.color.rgb_to_ycbcr(reference)
+ elif "LUV" == color_space:
+ reference = kornia.color.rgb_to_luv(reference)
+ elif "YUV" == color_space:
+ reference = kornia.color.rgb_to_yuv(reference)
+ elif "XYZ" == color_space:
+ reference = kornia.color.rgb_to_xyz(reference)
+
+ reference_mean, reference_std = self.compute_mean_std(reference, reference_mask)
+
+ image_batch = torch.split(image, batch_size, dim=0)
+ output = []
+
+ for image in image_batch:
+ image = image.to(device)
+
+ if color_space == "LAB":
+ image = kornia.color.rgb_to_lab(image)
+ elif color_space == "YCbCr":
+ image = kornia.color.rgb_to_ycbcr(image)
+ elif color_space == "LUV":
+ image = kornia.color.rgb_to_luv(image)
+ elif color_space == "YUV":
+ image = kornia.color.rgb_to_yuv(image)
+ elif color_space == "XYZ":
+ image = kornia.color.rgb_to_xyz(image)
+
+ image_mean, image_std = self.compute_mean_std(image)
+
+ matched = torch.nan_to_num((image - image_mean) / image_std) * torch.nan_to_num(reference_std) + reference_mean
+ matched = factor * matched + (1 - factor) * image
+
+ if color_space == "LAB":
+ matched = kornia.color.lab_to_rgb(matched)
+ elif color_space == "YCbCr":
+ matched = kornia.color.ycbcr_to_rgb(matched)
+ elif color_space == "LUV":
+ matched = kornia.color.luv_to_rgb(matched)
+ elif color_space == "YUV":
+ matched = kornia.color.yuv_to_rgb(matched)
+ elif color_space == "XYZ":
+ matched = kornia.color.xyz_to_rgb(matched)
+
+ out = matched.permute([0, 2, 3, 1]).clamp(0, 1).to(comfy.model_management.intermediate_device())
+ output.append(out)
+
+ out = None
+ output = torch.cat(output, dim=0)
+ return (output,)
+
+ def compute_mean_std(self, tensor, mask=None):
+ if mask is not None:
+ # Apply mask to the tensor
+ masked_tensor = tensor * mask
+
+ # Calculate the sum of the mask for each channel
+ mask_sum = mask.sum(dim=[2, 3], keepdim=True)
+
+ # Avoid division by zero
+ mask_sum = torch.clamp(mask_sum, min=1e-6)
+
+ # Calculate mean and std only for masked area
+ mean = torch.nan_to_num(masked_tensor.sum(dim=[2, 3], keepdim=True) / mask_sum)
+ std = torch.sqrt(torch.nan_to_num(((masked_tensor - mean) ** 2 * mask).sum(dim=[2, 3], keepdim=True) / mask_sum))
+ else:
+ mean = tensor.mean(dim=[2, 3], keepdim=True)
+ std = tensor.std(dim=[2, 3], keepdim=True)
+ return mean, std
+
+class ImageColorMatchAdobe(ImageColorMatch):
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "reference": ("IMAGE",),
+ "color_space": (["RGB", "LAB"],),
+ "luminance_factor": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 2.0, "step": 0.05}),
+ "color_intensity_factor": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 2.0, "step": 0.05}),
+ "fade_factor": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.05}),
+ "neutralization_factor": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.05}),
+ "device": (["auto", "cpu", "gpu"],),
+ },
+ "optional": {
+ "reference_mask": ("MASK",),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image processing"
+
+ def analyze_color_statistics(self, image, mask=None):
+ # Assuming image is in RGB format
+ l, a, b = kornia.color.rgb_to_lab(image).chunk(3, dim=1)
+
+ if mask is not None:
+ # Ensure mask is binary and has the same spatial dimensions as the image
+ mask = F.interpolate(mask, size=image.shape[2:], mode='nearest')
+ mask = (mask > 0.5).float()
+
+ # Apply mask to each channel
+ l = l * mask
+ a = a * mask
+ b = b * mask
+
+ # Compute masked mean and std
+ num_pixels = mask.sum()
+ mean_l = (l * mask).sum() / num_pixels
+ mean_a = (a * mask).sum() / num_pixels
+ mean_b = (b * mask).sum() / num_pixels
+ std_l = torch.sqrt(((l - mean_l)**2 * mask).sum() / num_pixels)
+ var_ab = ((a - mean_a)**2 + (b - mean_b)**2) * mask
+ std_ab = torch.sqrt(var_ab.sum() / num_pixels)
+ else:
+ mean_l = l.mean()
+ std_l = l.std()
+ mean_a = a.mean()
+ mean_b = b.mean()
+ std_ab = torch.sqrt(a.var() + b.var())
+
+ return mean_l, std_l, mean_a, mean_b, std_ab
+
+ def apply_color_transformation(self, image, source_stats, dest_stats, L, C, N):
+ l, a, b = kornia.color.rgb_to_lab(image).chunk(3, dim=1)
+
+ # Unpack statistics
+ src_mean_l, src_std_l, src_mean_a, src_mean_b, src_std_ab = source_stats
+ dest_mean_l, dest_std_l, dest_mean_a, dest_mean_b, dest_std_ab = dest_stats
+
+ # Adjust luminance
+ l_new = (l - dest_mean_l) * (src_std_l / dest_std_l) * L + src_mean_l
+
+ # Neutralize color cast
+ a = a - N * dest_mean_a
+ b = b - N * dest_mean_b
+
+ # Adjust color intensity
+ a_new = a * (src_std_ab / dest_std_ab) * C
+ b_new = b * (src_std_ab / dest_std_ab) * C
+
+ # Combine channels
+ lab_new = torch.cat([l_new, a_new, b_new], dim=1)
+
+ # Convert back to RGB
+ rgb_new = kornia.color.lab_to_rgb(lab_new)
+
+ return rgb_new
+
+ def execute(self, image, reference, color_space, luminance_factor, color_intensity_factor, fade_factor, neutralization_factor, device, reference_mask=None):
+ if "gpu" == device:
+ device = comfy.model_management.get_torch_device()
+ elif "auto" == device:
+ device = comfy.model_management.intermediate_device()
+ else:
+ device = 'cpu'
+
+ # Ensure image and reference are in the correct shape (B, C, H, W)
+ image = image.permute(0, 3, 1, 2).to(device)
+ reference = reference.permute(0, 3, 1, 2).to(device)
+
+ # Handle reference_mask (if provided)
+ if reference_mask is not None:
+ # Ensure reference_mask is 4D (B, 1, H, W)
+ if reference_mask.ndim == 2:
+ reference_mask = reference_mask.unsqueeze(0).unsqueeze(0)
+ elif reference_mask.ndim == 3:
+ reference_mask = reference_mask.unsqueeze(1)
+ reference_mask = reference_mask.to(device)
+
+ # Analyze color statistics
+ source_stats = self.analyze_color_statistics(reference, reference_mask)
+ dest_stats = self.analyze_color_statistics(image)
+
+ # Apply color transformation
+ transformed = self.apply_color_transformation(
+ image, source_stats, dest_stats,
+ luminance_factor, color_intensity_factor, neutralization_factor
+ )
+
+ # Apply fade factor
+ result = fade_factor * transformed + (1 - fade_factor) * image
+
+ # Convert back to (B, H, W, C) format and ensure values are in [0, 1] range
+ result = result.permute(0, 2, 3, 1).clamp(0, 1).to(comfy.model_management.intermediate_device())
+
+ return (result,)
+
+
+class ImageHistogramMatch:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "reference": ("IMAGE",),
+ "method": (["pytorch", "skimage"],),
+ "factor": ("FLOAT", { "default": 1.0, "min": 0.0, "max": 1.0, "step": 0.05, }),
+ "device": (["auto", "cpu", "gpu"],),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image processing"
+
+ def execute(self, image, reference, method, factor, device):
+ if "gpu" == device:
+ device = comfy.model_management.get_torch_device()
+ elif "auto" == device:
+ device = comfy.model_management.intermediate_device()
+ else:
+ device = 'cpu'
+
+ if "pytorch" in method:
+ from .histogram_matching import Histogram_Matching
+
+ image = image.permute([0, 3, 1, 2]).to(device)
+ reference = reference.permute([0, 3, 1, 2]).to(device)[0].unsqueeze(0)
+ image.requires_grad = True
+ reference.requires_grad = True
+
+ out = []
+
+ for i in image:
+ i = i.unsqueeze(0)
+ hm = Histogram_Matching(differentiable=True)
+ out.append(hm(i, reference))
+ out = torch.cat(out, dim=0)
+ out = factor * out + (1 - factor) * image
+ out = out.permute([0, 2, 3, 1]).clamp(0, 1)
+ else:
+ from skimage.exposure import match_histograms
+
+ out = torch.from_numpy(match_histograms(image.cpu().numpy(), reference.cpu().numpy(), channel_axis=3)).to(device)
+ out = factor * out + (1 - factor) * image.to(device)
+
+ return (out.to(comfy.model_management.intermediate_device()),)
+
+"""
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ Utilities
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+"""
+
+class ImageToDevice:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "device": (["auto", "cpu", "gpu"],),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image utils"
+
+ def execute(self, image, device):
+ if "gpu" == device:
+ device = comfy.model_management.get_torch_device()
+ elif "auto" == device:
+ device = comfy.model_management.intermediate_device()
+ else:
+ device = 'cpu'
+
+ image = image.clone().to(device)
+ torch.cuda.empty_cache()
+
+ return (image,)
+
+class GetImageSize:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ }
+ }
+
+ RETURN_TYPES = ("INT", "INT", "INT",)
+ RETURN_NAMES = ("width", "height", "count")
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image utils"
+
+ def execute(self, image):
+ return (image.shape[2], image.shape[1], image.shape[0])
+
+class ImageRemoveAlpha:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image utils"
+
+ def execute(self, image):
+ if image.shape[3] == 4:
+ image = image[..., :3]
+ return (image,)
+
+class ImagePreviewFromLatent(SaveImage):
+ def __init__(self):
+ self.output_dir = folder_paths.get_temp_directory()
+ self.type = "temp"
+ self.prefix_append = "_temp_" + ''.join(random.choice("abcdefghijklmnopqrstupvxyz") for x in range(5))
+ self.compress_level = 1
+
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "latent": ("LATENT",),
+ "vae": ("VAE", ),
+ "tile_size": ("INT", {"default": 0, "min": 0, "max": 4096, "step": 64})
+ }, "optional": {
+ "image": (["none"], {"image_upload": False}),
+ }, "hidden": {
+ "prompt": "PROMPT",
+ "extra_pnginfo": "EXTRA_PNGINFO",
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE", "MASK", "INT", "INT",)
+ RETURN_NAMES = ("IMAGE", "MASK", "width", "height",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image utils"
+
+ def execute(self, latent, vae, tile_size, prompt=None, extra_pnginfo=None, image=None, filename_prefix="ComfyUI"):
+ mask = torch.zeros((64,64), dtype=torch.float32, device="cpu")
+ ui = None
+
+ if image.startswith("clipspace"):
+ image_path = folder_paths.get_annotated_filepath(image)
+ if not os.path.exists(image_path):
+ raise ValueError(f"Clipspace image does not exist anymore, select 'none' in the image field.")
+
+ img = pillow(Image.open, image_path)
+ img = pillow(ImageOps.exif_transpose, img)
+ if img.mode == "I":
+ img = img.point(lambda i: i * (1 / 255))
+ 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)
+ ui = {
+ "filename": os.path.basename(image_path),
+ "subfolder": os.path.dirname(image_path),
+ "type": "temp",
+ }
+ else:
+ if tile_size > 0:
+ tile_size = max(tile_size, 320)
+ image = vae.decode_tiled(latent["samples"], tile_x=tile_size // 8, tile_y=tile_size // 8, )
+ else:
+ image = vae.decode(latent["samples"])
+ ui = self.save_images(image, filename_prefix, prompt, extra_pnginfo)
+
+ out = {**ui, "result": (image, mask, image.shape[2], image.shape[1],)}
+ return out
+
+class NoiseFromImage:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "noise_strenght": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01 }),
+ "noise_size": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01 }),
+ "color_noise": ("FLOAT", {"default": 0.2, "min": 0.0, "max": 1.0, "step": 0.01 }),
+ "mask_strength": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01 }),
+ "mask_scale_diff": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01 }),
+ "mask_contrast": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 100.0, "step": 0.1 }),
+ "saturation": ("FLOAT", {"default": 2.0, "min": 0.0, "max": 100.0, "step": 0.1 }),
+ "contrast": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 100.0, "step": 0.1 }),
+ "blur": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.1 }),
+ },
+ "optional": {
+ "noise_mask": ("IMAGE",),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/image utils"
+
+ def execute(self, image, noise_size, color_noise, mask_strength, mask_scale_diff, mask_contrast, noise_strenght, saturation, contrast, blur, noise_mask=None):
+ torch.manual_seed(0)
+
+ elastic_alpha = max(image.shape[1], image.shape[2])# * noise_size
+ elastic_sigma = elastic_alpha / 400 * noise_size
+
+ blur_size = int(6 * blur+1)
+ if blur_size % 2 == 0:
+ blur_size+= 1
+
+ if noise_mask is None:
+ noise_mask = image
+
+ # increase contrast of the mask
+ if mask_contrast != 1:
+ noise_mask = T.ColorJitter(contrast=(mask_contrast,mask_contrast))(noise_mask.permute([0, 3, 1, 2])).permute([0, 2, 3, 1])
+
+ # Ensure noise mask is the same size as the image
+ if noise_mask.shape[1:] != image.shape[1:]:
+ noise_mask = F.interpolate(noise_mask.permute([0, 3, 1, 2]), size=(image.shape[1], image.shape[2]), mode='bicubic', align_corners=False)
+ noise_mask = noise_mask.permute([0, 2, 3, 1])
+ # Ensure we have the same number of masks and images
+ if noise_mask.shape[0] > image.shape[0]:
+ noise_mask = noise_mask[:image.shape[0]]
+ else:
+ noise_mask = torch.cat((noise_mask, noise_mask[-1:].repeat((image.shape[0]-noise_mask.shape[0], 1, 1, 1))), dim=0)
+
+ # Convert mask to grayscale mask
+ noise_mask = noise_mask.mean(dim=3).unsqueeze(-1)
+
+ # add color noise
+ imgs = image.clone().permute([0, 3, 1, 2])
+ if color_noise > 0:
+ color_noise = torch.normal(torch.zeros_like(imgs), std=color_noise)
+ color_noise *= (imgs - imgs.min()) / (imgs.max() - imgs.min())
+
+ imgs = imgs + color_noise
+ imgs = imgs.clamp(0, 1)
+
+ # create fine and coarse noise
+ fine_noise = []
+ for n in imgs:
+ avg_color = n.mean(dim=[1,2])
+
+ tmp_noise = T.ElasticTransform(alpha=elastic_alpha, sigma=elastic_sigma, fill=avg_color.tolist())(n)
+ if blur > 0:
+ tmp_noise = T.GaussianBlur(blur_size, blur)(tmp_noise)
+ tmp_noise = T.ColorJitter(contrast=(contrast,contrast), saturation=(saturation,saturation))(tmp_noise)
+ fine_noise.append(tmp_noise)
+
+ imgs = None
+ del imgs
+
+ fine_noise = torch.stack(fine_noise, dim=0)
+ fine_noise = fine_noise.permute([0, 2, 3, 1])
+ #fine_noise = torch.stack(fine_noise, dim=0)
+ #fine_noise = pb(fine_noise)
+ mask_scale_diff = min(mask_scale_diff, 0.99)
+ if mask_scale_diff > 0:
+ coarse_noise = F.interpolate(fine_noise.permute([0, 3, 1, 2]), scale_factor=1-mask_scale_diff, mode='area')
+ coarse_noise = F.interpolate(coarse_noise, size=(fine_noise.shape[1], fine_noise.shape[2]), mode='bilinear', align_corners=False)
+ coarse_noise = coarse_noise.permute([0, 2, 3, 1])
+ else:
+ coarse_noise = fine_noise
+
+ output = (1 - noise_mask) * coarse_noise + noise_mask * fine_noise
+
+ if mask_strength < 1:
+ noise_mask = noise_mask.pow(mask_strength)
+ noise_mask = torch.nan_to_num(noise_mask).clamp(0, 1)
+ output = noise_mask * output + (1 - noise_mask) * image
+
+ # apply noise to image
+ output = output * noise_strenght + image * (1 - noise_strenght)
+ output = output.clamp(0, 1)
+
+ return (output, )
+
+IMAGE_CLASS_MAPPINGS = {
+ # Image analysis
+ "ImageEnhanceDifference+": ImageEnhanceDifference,
+
+ # Image batch
+ "ImageBatchMultiple+": ImageBatchMultiple,
+ "ImageExpandBatch+": ImageExpandBatch,
+ "ImageFromBatch+": ImageFromBatch,
+ "ImageListToBatch+": ImageListToBatch,
+
+ # Image manipulation
+ "ImageCompositeFromMaskBatch+": ImageCompositeFromMaskBatch,
+ "ImageComposite+": ImageComposite,
+ "ImageCrop+": ImageCrop,
+ "ImageFlip+": ImageFlip,
+ "ImageRandomTransform+": ImageRandomTransform,
+ "ImageRemoveAlpha+": ImageRemoveAlpha,
+ "ImageRemoveBackground+": ImageRemoveBackground,
+ "ImageResize+": ImageResize,
+ "ImageSeamCarving+": ImageSeamCarving,
+ "ImageTile+": ImageTile,
+ "ImageUntile+": ImageUntile,
+ "RemBGSession+": RemBGSession,
+ "TransparentBGSession+": TransparentBGSession,
+
+ # Image processing
+ "ImageApplyLUT+": ImageApplyLUT,
+ "ImageCASharpening+": ImageCAS,
+ "ImageDesaturate+": ImageDesaturate,
+ "PixelOEPixelize+": PixelOEPixelize,
+ "ImagePosterize+": ImagePosterize,
+ "ImageColorMatch+": ImageColorMatch,
+ "ImageColorMatchAdobe+": ImageColorMatchAdobe,
+ "ImageHistogramMatch+": ImageHistogramMatch,
+
+ # Utilities
+ "GetImageSize+": GetImageSize,
+ "ImageToDevice+": ImageToDevice,
+ "ImagePreviewFromLatent+": ImagePreviewFromLatent,
+ "NoiseFromImage+": NoiseFromImage,
+
+ #"ExtractKeyframes+": ExtractKeyframes,
+}
+
+IMAGE_NAME_MAPPINGS = {
+ # Image analysis
+ "ImageEnhanceDifference+": "🔧 Image Enhance Difference",
+
+ # Image batch
+ "ImageBatchMultiple+": "🔧 Images Batch Multiple",
+ "ImageExpandBatch+": "🔧 Image Expand Batch",
+ "ImageFromBatch+": "🔧 Image From Batch",
+ "ImageListToBatch+": "🔧 Image List To Batch",
+
+ # Image manipulation
+ "ImageCompositeFromMaskBatch+": "🔧 Image Composite From Mask Batch",
+ "ImageComposite+": "🔧 Image Composite",
+ "ImageCrop+": "🔧 Image Crop",
+ "ImageFlip+": "🔧 Image Flip",
+ "ImageRandomTransform+": "🔧 Image Random Transform",
+ "ImageRemoveAlpha+": "🔧 Image Remove Alpha",
+ "ImageRemoveBackground+": "🔧 Image Remove Background",
+ "ImageResize+": "🔧 Image Resize",
+ "ImageSeamCarving+": "🔧 Image Seam Carving",
+ "ImageTile+": "🔧 Image Tile",
+ "ImageUntile+": "🔧 Image Untile",
+ "RemBGSession+": "🔧 RemBG Session",
+ "TransparentBGSession+": "🔧 InSPyReNet TransparentBG",
+
+ # Image processing
+ "ImageApplyLUT+": "🔧 Image Apply LUT",
+ "ImageCASharpening+": "🔧 Image Contrast Adaptive Sharpening",
+ "ImageDesaturate+": "🔧 Image Desaturate",
+ "PixelOEPixelize+": "🔧 Pixelize",
+ "ImagePosterize+": "🔧 Image Posterize",
+ "ImageColorMatch+": "🔧 Image Color Match",
+ "ImageColorMatchAdobe+": "🔧 Image Color Match Adobe",
+ "ImageHistogramMatch+": "🔧 Image Histogram Match",
+
+ # Utilities
+ "GetImageSize+": "🔧 Get Image Size",
+ "ImageToDevice+": "🔧 Image To Device",
+ "ImagePreviewFromLatent+": "🔧 Image Preview From Latent",
+ "NoiseFromImage+": "🔧 Noise From Image",
+}
diff --git a/comfyui_essentials/luts/put_luts_files_here.txt b/comfyui_essentials/luts/put_luts_files_here.txt
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/comfyui_essentials/mask.py b/comfyui_essentials/mask.py
new file mode 100644
index 0000000000000000000000000000000000000000..5298d0f720da152109aa2398a58d654b349bc874
--- /dev/null
+++ b/comfyui_essentials/mask.py
@@ -0,0 +1,593 @@
+from nodes import SaveImage
+import torch
+import torchvision.transforms.v2 as T
+import random
+import folder_paths
+import comfy.utils
+from .image import ImageExpandBatch
+import numpy as np
+import scipy
+from PIL import Image
+from nodes import MAX_RESOLUTION
+import math
+
+class MaskBlur:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "mask": ("MASK",),
+ "amount": ("INT", { "default": 6, "min": 0, "max": 256, "step": 1, }),
+ "device": (["auto", "cpu", "gpu"],),
+ }
+ }
+
+ RETURN_TYPES = ("MASK",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/mask"
+
+ def execute(self, mask, amount, device):
+ if amount == 0:
+ return (mask,)
+
+ if "gpu" == device:
+ mask = mask.to(comfy.model_management.get_torch_device())
+ elif "cpu" == device:
+ mask = mask.to('cpu')
+
+ if amount % 2 == 0:
+ amount+= 1
+
+ if mask.dim() == 2:
+ mask = mask.unsqueeze(0)
+
+ mask = T.functional.gaussian_blur(mask.unsqueeze(1), amount).squeeze(1)
+
+ if "gpu" == device or "cpu" == device:
+ mask = mask.to(comfy.model_management.intermediate_device())
+
+ return(mask,)
+
+class MaskFlip:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "mask": ("MASK",),
+ "axis": (["x", "y", "xy"],),
+ }
+ }
+
+ RETURN_TYPES = ("MASK",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/mask"
+
+ def execute(self, mask, axis):
+ if mask.dim() == 2:
+ mask = mask.unsqueeze(0)
+
+ dim = ()
+ if "y" in axis:
+ dim += (1,)
+ if "x" in axis:
+ dim += (2,)
+ mask = torch.flip(mask, dims=dim)
+
+ return(mask,)
+
+class MaskPreview(SaveImage):
+ def __init__(self):
+ self.output_dir = folder_paths.get_temp_directory()
+ self.type = "temp"
+ self.prefix_append = "_temp_" + ''.join(random.choice("abcdefghijklmnopqrstupvxyz") for x in range(5))
+ self.compress_level = 4
+
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {"mask": ("MASK",), },
+ "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
+ }
+
+ FUNCTION = "execute"
+ CATEGORY = "essentials/mask"
+
+ def execute(self, mask, filename_prefix="ComfyUI", prompt=None, extra_pnginfo=None):
+ preview = mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])).movedim(1, -1).expand(-1, -1, -1, 3)
+ return self.save_images(preview, filename_prefix, prompt, extra_pnginfo)
+
+class MaskBatch:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "mask1": ("MASK",),
+ "mask2": ("MASK",),
+ }
+ }
+
+ RETURN_TYPES = ("MASK",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/mask batch"
+
+ def execute(self, mask1, mask2):
+ if mask1.shape[1:] != mask2.shape[1:]:
+ mask2 = comfy.utils.common_upscale(mask2.unsqueeze(1).expand(-1,3,-1,-1), mask1.shape[2], mask1.shape[1], upscale_method='bicubic', crop='center')[:,0,:,:]
+
+ return (torch.cat((mask1, mask2), dim=0),)
+
+class MaskExpandBatch:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "mask": ("MASK",),
+ "size": ("INT", { "default": 16, "min": 1, "step": 1, }),
+ "method": (["expand", "repeat all", "repeat first", "repeat last"],)
+ }
+ }
+
+ RETURN_TYPES = ("MASK",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/mask batch"
+
+ def execute(self, mask, size, method):
+ return (ImageExpandBatch().execute(mask.unsqueeze(1).expand(-1,3,-1,-1), size, method)[0][:,0,:,:],)
+
+
+class MaskBoundingBox:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "mask": ("MASK",),
+ "padding": ("INT", { "default": 0, "min": 0, "max": 4096, "step": 1, }),
+ "blur": ("INT", { "default": 0, "min": 0, "max": 256, "step": 1, }),
+ },
+ "optional": {
+ "image_optional": ("IMAGE",),
+ }
+ }
+
+ RETURN_TYPES = ("MASK", "IMAGE", "INT", "INT", "INT", "INT")
+ RETURN_NAMES = ("MASK", "IMAGE", "x", "y", "width", "height")
+ FUNCTION = "execute"
+ CATEGORY = "essentials/mask"
+
+ def execute(self, mask, padding, blur, image_optional=None):
+ if mask.dim() == 2:
+ mask = mask.unsqueeze(0)
+
+ if image_optional is None:
+ image_optional = mask.unsqueeze(3).repeat(1, 1, 1, 3)
+
+ # resize the image if it's not the same size as the mask
+ if image_optional.shape[1:] != mask.shape[1:]:
+ image_optional = comfy.utils.common_upscale(image_optional.permute([0,3,1,2]), mask.shape[2], mask.shape[1], upscale_method='bicubic', crop='center').permute([0,2,3,1])
+
+ # match batch size
+ if image_optional.shape[0] < mask.shape[0]:
+ image_optional = torch.cat((image_optional, image_optional[-1].unsqueeze(0).repeat(mask.shape[0]-image_optional.shape[0], 1, 1, 1)), dim=0)
+ elif image_optional.shape[0] > mask.shape[0]:
+ image_optional = image_optional[:mask.shape[0]]
+
+ # blur the mask
+ if blur > 0:
+ if blur % 2 == 0:
+ blur += 1
+ mask = T.functional.gaussian_blur(mask.unsqueeze(1), blur).squeeze(1)
+
+ _, y, x = torch.where(mask)
+ x1 = max(0, x.min().item() - padding)
+ x2 = min(mask.shape[2], x.max().item() + 1 + padding)
+ y1 = max(0, y.min().item() - padding)
+ y2 = min(mask.shape[1], y.max().item() + 1 + padding)
+
+ # crop the mask
+ mask = mask[:, y1:y2, x1:x2]
+ image_optional = image_optional[:, y1:y2, x1:x2, :]
+
+ return (mask, image_optional, x1, y1, x2 - x1, y2 - y1)
+
+
+class MaskFromColor:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE", ),
+ "red": ("INT", { "default": 255, "min": 0, "max": 255, "step": 1, }),
+ "green": ("INT", { "default": 255, "min": 0, "max": 255, "step": 1, }),
+ "blue": ("INT", { "default": 255, "min": 0, "max": 255, "step": 1, }),
+ "threshold": ("INT", { "default": 0, "min": 0, "max": 127, "step": 1, }),
+ }
+ }
+
+ RETURN_TYPES = ("MASK",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/mask"
+
+ def execute(self, image, red, green, blue, threshold):
+ temp = (torch.clamp(image, 0, 1.0) * 255.0).round().to(torch.int)
+ color = torch.tensor([red, green, blue])
+ lower_bound = (color - threshold).clamp(min=0)
+ upper_bound = (color + threshold).clamp(max=255)
+ lower_bound = lower_bound.view(1, 1, 1, 3)
+ upper_bound = upper_bound.view(1, 1, 1, 3)
+ mask = (temp >= lower_bound) & (temp <= upper_bound)
+ mask = mask.all(dim=-1)
+ mask = mask.float()
+
+ return (mask, )
+
+
+class MaskFromSegmentation:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE", ),
+ "segments": ("INT", { "default": 6, "min": 1, "max": 16, "step": 1, }),
+ "remove_isolated_pixels": ("INT", { "default": 0, "min": 0, "max": 32, "step": 1, }),
+ "remove_small_masks": ("FLOAT", { "default": 0.0, "min": 0., "max": 1., "step": 0.01, }),
+ "fill_holes": ("BOOLEAN", { "default": False }),
+ }
+ }
+
+ RETURN_TYPES = ("MASK",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/mask"
+
+ def execute(self, image, segments, remove_isolated_pixels, fill_holes, remove_small_masks):
+ im = image[0] # we only work on the first image in the batch
+ im = Image.fromarray((im * 255).to(torch.uint8).cpu().numpy(), mode="RGB")
+ im = im.quantize(palette=im.quantize(colors=segments), dither=Image.Dither.NONE)
+ im = torch.tensor(np.array(im.convert("RGB"))).float() / 255.0
+
+ colors = im.reshape(-1, im.shape[-1])
+ colors = torch.unique(colors, dim=0)
+
+ masks = []
+ for color in colors:
+ mask = (im == color).all(dim=-1).float()
+ # remove isolated pixels
+ if remove_isolated_pixels > 0:
+ mask = torch.from_numpy(scipy.ndimage.binary_opening(mask.cpu().numpy(), structure=np.ones((remove_isolated_pixels, remove_isolated_pixels))))
+
+ # fill holes
+ if fill_holes:
+ mask = torch.from_numpy(scipy.ndimage.binary_fill_holes(mask.cpu().numpy()))
+
+ # if the mask is too small, it's probably noise
+ if mask.sum() / (mask.shape[0]*mask.shape[1]) > remove_small_masks:
+ masks.append(mask)
+
+ if masks == []:
+ masks.append(torch.zeros_like(im)[:,:,0]) # return an empty mask if no masks were found, prevents errors
+
+ mask = torch.stack(masks, dim=0).float()
+
+ return (mask, )
+
+
+class MaskFix:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "mask": ("MASK",),
+ "erode_dilate": ("INT", { "default": 0, "min": -256, "max": 256, "step": 1, }),
+ "fill_holes": ("INT", { "default": 0, "min": 0, "max": 128, "step": 1, }),
+ "remove_isolated_pixels": ("INT", { "default": 0, "min": 0, "max": 32, "step": 1, }),
+ "smooth": ("INT", { "default": 0, "min": 0, "max": 256, "step": 1, }),
+ "blur": ("INT", { "default": 0, "min": 0, "max": 256, "step": 1, }),
+ }
+ }
+
+ RETURN_TYPES = ("MASK",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/mask"
+
+ def execute(self, mask, erode_dilate, smooth, remove_isolated_pixels, blur, fill_holes):
+ masks = []
+ for m in mask:
+ # erode and dilate
+ if erode_dilate != 0:
+ if erode_dilate < 0:
+ m = torch.from_numpy(scipy.ndimage.grey_erosion(m.cpu().numpy(), size=(-erode_dilate, -erode_dilate)))
+ else:
+ m = torch.from_numpy(scipy.ndimage.grey_dilation(m.cpu().numpy(), size=(erode_dilate, erode_dilate)))
+
+ # fill holes
+ if fill_holes > 0:
+ #m = torch.from_numpy(scipy.ndimage.binary_fill_holes(m.cpu().numpy(), structure=np.ones((fill_holes,fill_holes)))).float()
+ m = torch.from_numpy(scipy.ndimage.grey_closing(m.cpu().numpy(), size=(fill_holes, fill_holes)))
+
+ # remove isolated pixels
+ if remove_isolated_pixels > 0:
+ m = torch.from_numpy(scipy.ndimage.grey_opening(m.cpu().numpy(), size=(remove_isolated_pixels, remove_isolated_pixels)))
+
+ # smooth the mask
+ if smooth > 0:
+ if smooth % 2 == 0:
+ smooth += 1
+ m = T.functional.gaussian_blur((m > 0.5).unsqueeze(0), smooth).squeeze(0)
+
+ # blur the mask
+ if blur > 0:
+ if blur % 2 == 0:
+ blur += 1
+ m = T.functional.gaussian_blur(m.float().unsqueeze(0), blur).squeeze(0)
+
+ masks.append(m.float())
+
+ masks = torch.stack(masks, dim=0).float()
+
+ return (masks, )
+
+class MaskSmooth:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "mask": ("MASK",),
+ "amount": ("INT", { "default": 0, "min": 0, "max": 127, "step": 1, }),
+ }
+ }
+
+ RETURN_TYPES = ("MASK",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/mask"
+
+ def execute(self, mask, amount):
+ if amount == 0:
+ return (mask,)
+
+ if amount % 2 == 0:
+ amount += 1
+
+ mask = mask > 0.5
+ mask = T.functional.gaussian_blur(mask.unsqueeze(1), amount).squeeze(1).float()
+
+ return (mask,)
+
+class MaskFromBatch:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "mask": ("MASK", ),
+ "start": ("INT", { "default": 0, "min": 0, "step": 1, }),
+ "length": ("INT", { "default": 1, "min": 1, "step": 1, }),
+ }
+ }
+
+ RETURN_TYPES = ("MASK",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/mask batch"
+
+ def execute(self, mask, start, length):
+ if length > mask.shape[0]:
+ length = mask.shape[0]
+
+ start = min(start, mask.shape[0]-1)
+ length = min(mask.shape[0]-start, length)
+ return (mask[start:start + length], )
+
+class MaskFromList:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "width": ("INT", { "default": 32, "min": 0, "max": MAX_RESOLUTION, "step": 8, }),
+ "height": ("INT", { "default": 32, "min": 0, "max": MAX_RESOLUTION, "step": 8, }),
+ }, "optional": {
+ "values": ("INT,FLOAT", { "default": 0.0, "min": 0.0, "max": 1.0, }),
+ "str_values": ("STRING", { "default": "", "multiline": True, "placeholder": "0.0, 0.5, 1.0",}),
+ }
+ }
+
+ RETURN_TYPES = ("MASK",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/mask"
+
+ def execute(self, width, height, values=None, str_values=""):
+ out = []
+
+ if values is not None:
+ if not isinstance(values, list):
+ out = [values]
+ else:
+ out.extend(values)
+
+ if str_values != "":
+ str_values = [float(v) for v in str_values.split(",")]
+ out.extend(str_values)
+
+ if out == []:
+ raise ValueError("No values provided")
+
+ out = torch.tensor(out).float().clamp(0.0, 1.0)
+ out = out.view(-1, 1, 1).expand(-1, height, width)
+
+ values = None
+ str_values = ""
+
+ return (out, )
+
+class MaskFromRGBCMYBW:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE", ),
+ "threshold_r": ("FLOAT", { "default": 0.15, "min": 0.0, "max": 1, "step": 0.01, }),
+ "threshold_g": ("FLOAT", { "default": 0.15, "min": 0.0, "max": 1, "step": 0.01, }),
+ "threshold_b": ("FLOAT", { "default": 0.15, "min": 0.0, "max": 1, "step": 0.01, }),
+ }
+ }
+
+ RETURN_TYPES = ("MASK","MASK","MASK","MASK","MASK","MASK","MASK","MASK",)
+ RETURN_NAMES = ("red","green","blue","cyan","magenta","yellow","black","white",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/mask"
+
+ def execute(self, image, threshold_r, threshold_g, threshold_b):
+ red = ((image[..., 0] >= 1-threshold_r) & (image[..., 1] < threshold_g) & (image[..., 2] < threshold_b)).float()
+ green = ((image[..., 0] < threshold_r) & (image[..., 1] >= 1-threshold_g) & (image[..., 2] < threshold_b)).float()
+ blue = ((image[..., 0] < threshold_r) & (image[..., 1] < threshold_g) & (image[..., 2] >= 1-threshold_b)).float()
+
+ cyan = ((image[..., 0] < threshold_r) & (image[..., 1] >= 1-threshold_g) & (image[..., 2] >= 1-threshold_b)).float()
+ magenta = ((image[..., 0] >= 1-threshold_r) & (image[..., 1] < threshold_g) & (image[..., 2] > 1-threshold_b)).float()
+ yellow = ((image[..., 0] >= 1-threshold_r) & (image[..., 1] >= 1-threshold_g) & (image[..., 2] < threshold_b)).float()
+
+ black = ((image[..., 0] <= threshold_r) & (image[..., 1] <= threshold_g) & (image[..., 2] <= threshold_b)).float()
+ white = ((image[..., 0] >= 1-threshold_r) & (image[..., 1] >= 1-threshold_g) & (image[..., 2] >= 1-threshold_b)).float()
+
+ return (red, green, blue, cyan, magenta, yellow, black, white,)
+
+class TransitionMask:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "width": ("INT", { "default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1, }),
+ "height": ("INT", { "default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1, }),
+ "frames": ("INT", { "default": 16, "min": 1, "max": 9999, "step": 1, }),
+ "start_frame": ("INT", { "default": 0, "min": 0, "step": 1, }),
+ "end_frame": ("INT", { "default": 9999, "min": 0, "step": 1, }),
+ "transition_type": (["horizontal slide", "vertical slide", "horizontal bar", "vertical bar", "center box", "horizontal door", "vertical door", "circle", "fade"],),
+ "timing_function": (["linear", "in", "out", "in-out"],)
+ }
+ }
+
+ RETURN_TYPES = ("MASK",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/mask"
+
+ def linear(self, i, t):
+ return i/t
+ def ease_in(self, i, t):
+ return pow(i/t, 2)
+ def ease_out(self, i, t):
+ return 1 - pow(1 - i/t, 2)
+ def ease_in_out(self, i, t):
+ if i < t/2:
+ return pow(i/(t/2), 2) / 2
+ else:
+ return 1 - pow(1 - (i - t/2)/(t/2), 2) / 2
+
+ def execute(self, width, height, frames, start_frame, end_frame, transition_type, timing_function):
+ if timing_function == 'in':
+ timing_function = self.ease_in
+ elif timing_function == 'out':
+ timing_function = self.ease_out
+ elif timing_function == 'in-out':
+ timing_function = self.ease_in_out
+ else:
+ timing_function = self.linear
+
+ out = []
+
+ end_frame = min(frames, end_frame)
+ transition = end_frame - start_frame
+
+ if start_frame > 0:
+ out = out + [torch.full((height, width), 0.0, dtype=torch.float32, device="cpu")] * start_frame
+
+ for i in range(transition):
+ frame = torch.full((height, width), 0.0, dtype=torch.float32, device="cpu")
+ progress = timing_function(i, transition-1)
+
+ if "horizontal slide" in transition_type:
+ pos = round(width*progress)
+ frame[:, :pos] = 1.0
+ elif "vertical slide" in transition_type:
+ pos = round(height*progress)
+ frame[:pos, :] = 1.0
+ elif "box" in transition_type:
+ box_w = round(width*progress)
+ box_h = round(height*progress)
+ x1 = (width - box_w) // 2
+ y1 = (height - box_h) // 2
+ x2 = x1 + box_w
+ y2 = y1 + box_h
+ frame[y1:y2, x1:x2] = 1.0
+ elif "circle" in transition_type:
+ radius = math.ceil(math.sqrt(pow(width,2)+pow(height,2))*progress/2)
+ c_x = width // 2
+ c_y = height // 2
+ # is this real life? Am I hallucinating?
+ x = torch.arange(0, width, dtype=torch.float32, device="cpu")
+ y = torch.arange(0, height, dtype=torch.float32, device="cpu")
+ y, x = torch.meshgrid((y, x), indexing="ij")
+ circle = ((x - c_x) ** 2 + (y - c_y) ** 2) <= (radius ** 2)
+ frame[circle] = 1.0
+ elif "horizontal bar" in transition_type:
+ bar = round(height*progress)
+ y1 = (height - bar) // 2
+ y2 = y1 + bar
+ frame[y1:y2, :] = 1.0
+ elif "vertical bar" in transition_type:
+ bar = round(width*progress)
+ x1 = (width - bar) // 2
+ x2 = x1 + bar
+ frame[:, x1:x2] = 1.0
+ elif "horizontal door" in transition_type:
+ bar = math.ceil(height*progress/2)
+ if bar > 0:
+ frame[:bar, :] = 1.0
+ frame[-bar:, :] = 1.0
+ elif "vertical door" in transition_type:
+ bar = math.ceil(width*progress/2)
+ if bar > 0:
+ frame[:, :bar] = 1.0
+ frame[:, -bar:] = 1.0
+ elif "fade" in transition_type:
+ frame[:,:] = progress
+
+ out.append(frame)
+
+ if end_frame < frames:
+ out = out + [torch.full((height, width), 1.0, dtype=torch.float32, device="cpu")] * (frames - end_frame)
+
+ out = torch.stack(out, dim=0)
+
+ return (out, )
+
+MASK_CLASS_MAPPINGS = {
+ "MaskBlur+": MaskBlur,
+ "MaskBoundingBox+": MaskBoundingBox,
+ "MaskFix+": MaskFix,
+ "MaskFlip+": MaskFlip,
+ "MaskFromColor+": MaskFromColor,
+ "MaskFromList+": MaskFromList,
+ "MaskFromRGBCMYBW+": MaskFromRGBCMYBW,
+ "MaskFromSegmentation+": MaskFromSegmentation,
+ "MaskPreview+": MaskPreview,
+ "MaskSmooth+": MaskSmooth,
+ "TransitionMask+": TransitionMask,
+
+ # Batch
+ "MaskBatch+": MaskBatch,
+ "MaskExpandBatch+": MaskExpandBatch,
+ "MaskFromBatch+": MaskFromBatch,
+}
+
+MASK_NAME_MAPPINGS = {
+ "MaskBlur+": "🔧 Mask Blur",
+ "MaskFix+": "🔧 Mask Fix",
+ "MaskFlip+": "🔧 Mask Flip",
+ "MaskFromColor+": "🔧 Mask From Color",
+ "MaskFromList+": "🔧 Mask From List",
+ "MaskFromRGBCMYBW+": "🔧 Mask From RGB/CMY/BW",
+ "MaskFromSegmentation+": "🔧 Mask From Segmentation",
+ "MaskPreview+": "🔧 Mask Preview",
+ "MaskBoundingBox+": "🔧 Mask Bounding Box",
+ "MaskSmooth+": "🔧 Mask Smooth",
+ "TransitionMask+": "🔧 Transition Mask",
+
+ "MaskBatch+": "🔧 Mask Batch",
+ "MaskExpandBatch+": "🔧 Mask Expand Batch",
+ "MaskFromBatch+": "🔧 Mask From Batch",
+}
diff --git a/comfyui_essentials/misc.py b/comfyui_essentials/misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ef8b837b3a03606d86f6d04ab8a2575ff332ca9
--- /dev/null
+++ b/comfyui_essentials/misc.py
@@ -0,0 +1,243 @@
+import math
+import torch
+from .utils import AnyType
+import comfy.model_management
+from nodes import MAX_RESOLUTION
+
+any = AnyType("*")
+
+class SimpleMath:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "optional": {
+ "a": ("INT,FLOAT", { "default": 0.0, "step": 0.1 }),
+ "b": ("INT,FLOAT", { "default": 0.0, "step": 0.1 }),
+ },
+ "required": {
+ "value": ("STRING", { "multiline": False, "default": "" }),
+ },
+ }
+
+ RETURN_TYPES = ("INT", "FLOAT", )
+ FUNCTION = "execute"
+ CATEGORY = "essentials/utilities"
+
+ def execute(self, value, a = 0.0, b = 0.0):
+ import ast
+ import operator as op
+
+ operators = {
+ ast.Add: op.add,
+ ast.Sub: op.sub,
+ ast.Mult: op.mul,
+ ast.Div: op.truediv,
+ ast.FloorDiv: op.floordiv,
+ ast.Pow: op.pow,
+ ast.BitXor: op.xor,
+ ast.USub: op.neg,
+ ast.Mod: op.mod,
+ }
+
+ op_functions = {
+ 'min': min,
+ 'max': max,
+ 'round': round,
+ 'sum': sum,
+ 'len': len,
+ }
+
+ def eval_(node):
+ if isinstance(node, ast.Num): # number
+ return node.n
+ elif isinstance(node, ast.Name): # variable
+ if node.id == "a":
+ return a
+ if node.id == "b":
+ return b
+ elif isinstance(node, ast.BinOp): #
+ return operators[type(node.op)](eval_(node.left), eval_(node.right))
+ elif isinstance(node, ast.UnaryOp): # e.g., -1
+ return operators[type(node.op)](eval_(node.operand))
+ elif isinstance(node, ast.Call): # custom function
+ if node.func.id in op_functions:
+ args =[eval_(arg) for arg in node.args]
+ return op_functions[node.func.id](*args)
+ elif isinstance(node, ast.Subscript): # indexing or slicing
+ value = eval_(node.value)
+ if isinstance(node.slice, ast.Constant):
+ return value[node.slice.value]
+ else:
+ return 0
+ else:
+ return 0
+
+ result = eval_(ast.parse(value, mode='eval').body)
+
+ if math.isnan(result):
+ result = 0.0
+
+ return (round(result), result, )
+
+class ConsoleDebug:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "value": (any, {}),
+ },
+ "optional": {
+ "prefix": ("STRING", { "multiline": False, "default": "Value:" })
+ }
+ }
+
+ RETURN_TYPES = ()
+ FUNCTION = "execute"
+ CATEGORY = "essentials/utilities"
+ OUTPUT_NODE = True
+
+ def execute(self, value, prefix):
+ print(f"\033[96m{prefix} {value}\033[0m")
+
+ return (None,)
+
+class DebugTensorShape:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "tensor": (any, {}),
+ },
+ }
+
+ RETURN_TYPES = ()
+ FUNCTION = "execute"
+ CATEGORY = "essentials/utilities"
+ OUTPUT_NODE = True
+
+ def execute(self, tensor):
+ shapes = []
+ def tensorShape(tensor):
+ if isinstance(tensor, dict):
+ for k in tensor:
+ tensorShape(tensor[k])
+ elif isinstance(tensor, list):
+ for i in range(len(tensor)):
+ tensorShape(tensor[i])
+ elif hasattr(tensor, 'shape'):
+ shapes.append(list(tensor.shape))
+
+ tensorShape(tensor)
+
+ print(f"\033[96mShapes found: {shapes}\033[0m")
+
+ return (None,)
+
+class BatchCount:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "batch": (any, {}),
+ },
+ }
+
+ RETURN_TYPES = ("INT",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/utilities"
+
+ def execute(self, batch):
+ count = 0
+ if hasattr(batch, 'shape'):
+ count = batch.shape[0]
+ elif isinstance(batch, dict) and 'samples' in batch:
+ count = batch['samples'].shape[0]
+ elif isinstance(batch, list) or isinstance(batch, dict):
+ count = len(batch)
+
+ return (count, )
+
+class ModelCompile():
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "model": ("MODEL",),
+ "fullgraph": ("BOOLEAN", { "default": False }),
+ "dynamic": ("BOOLEAN", { "default": False }),
+ "mode": (["default", "reduce-overhead", "max-autotune", "max-autotune-no-cudagraphs"],),
+ },
+ }
+
+ RETURN_TYPES = ("MODEL", )
+ FUNCTION = "execute"
+ CATEGORY = "essentials/utilities"
+
+ def execute(self, model, fullgraph, dynamic, mode):
+ work_model = model.clone()
+ torch._dynamo.config.suppress_errors = True
+ work_model.model.diffusion_model = torch.compile(work_model.model.diffusion_model, dynamic=dynamic, fullgraph=fullgraph, mode=mode)
+ return (work_model, )
+
+class RemoveLatentMask:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {"required": { "samples": ("LATENT",),}}
+ RETURN_TYPES = ("LATENT",)
+ FUNCTION = "execute"
+
+ CATEGORY = "essentials/utilities"
+
+ def execute(self, samples):
+ s = samples.copy()
+ if "noise_mask" in s:
+ del s["noise_mask"]
+
+ return (s,)
+
+class SDXLEmptyLatentSizePicker:
+ def __init__(self):
+ self.device = comfy.model_management.intermediate_device()
+
+ @classmethod
+ def INPUT_TYPES(s):
+ return {"required": {
+ "resolution": (["704x1408 (0.5)","704x1344 (0.52)","768x1344 (0.57)","768x1280 (0.6)","832x1216 (0.68)","832x1152 (0.72)","896x1152 (0.78)","896x1088 (0.82)","960x1088 (0.88)","960x1024 (0.94)","1024x1024 (1.0)","1024x960 (1.07)","1088x960 (1.13)","1088x896 (1.21)","1152x896 (1.29)","1152x832 (1.38)","1216x832 (1.46)","1280x768 (1.67)","1344x768 (1.75)","1344x704 (1.91)","1408x704 (2.0)","1472x704 (2.09)","1536x640 (2.4)","1600x640 (2.5)","1664x576 (2.89)","1728x576 (3.0)",], {"default": "1024x1024 (1.0)"}),
+ "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}),
+ "width_override": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
+ "height_override": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
+ }}
+
+ RETURN_TYPES = ("LATENT","INT","INT",)
+ RETURN_NAMES = ("LATENT","width","height",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/utilities"
+
+ def execute(self, resolution, batch_size, width_override=0, height_override=0):
+ width, height = resolution.split(" ")[0].split("x")
+ width = width_override if width_override > 0 else int(width)
+ height = height_override if height_override > 0 else int(height)
+
+ latent = torch.zeros([batch_size, 4, height // 8, width // 8], device=self.device)
+
+ return ({"samples":latent}, width, height,)
+
+MISC_CLASS_MAPPINGS = {
+ "BatchCount+": BatchCount,
+ "ConsoleDebug+": ConsoleDebug,
+ "DebugTensorShape+": DebugTensorShape,
+ "ModelCompile+": ModelCompile,
+ "RemoveLatentMask+": RemoveLatentMask,
+ "SDXLEmptyLatentSizePicker+": SDXLEmptyLatentSizePicker,
+ "SimpleMath+": SimpleMath,
+}
+
+MISC_NAME_MAPPINGS = {
+ "BatchCount+": "🔧 Batch Count",
+ "ConsoleDebug+": "🔧 Console Debug",
+ "DebugTensorShape+": "🔧 Debug Tensor Shape",
+ "ModelCompile+": "🔧 Model Compile",
+ "RemoveLatentMask+": "🔧 Remove Latent Mask",
+ "SDXLEmptyLatentSizePicker+": "🔧 SDXL Empty Latent Size Picker",
+ "SimpleMath+": "🔧 Simple Math",
+}
\ No newline at end of file
diff --git a/comfyui_essentials/pyproject.toml b/comfyui_essentials/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..affa1310b05b6f70f302a84771918984499defae
--- /dev/null
+++ b/comfyui_essentials/pyproject.toml
@@ -0,0 +1,15 @@
+[project]
+name = "comfyui_essentials"
+description = "Essential nodes that are weirdly missing from ComfyUI core. With few exceptions they are new features and not commodities."
+version = "1.1.0"
+license = { file = "LICENSE" }
+dependencies = ["numba", "colour-science", "rembg", "pixeloe"]
+
+[project.urls]
+Repository = "https://github.com/cubiq/ComfyUI_essentials"
+# Used by Comfy Registry https://comfyregistry.org
+
+[tool.comfy]
+PublisherId = "matteo"
+DisplayName = "ComfyUI_essentials"
+Icon = ""
diff --git a/comfyui_essentials/requirements.txt b/comfyui_essentials/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..ca6bb9baa5e2f119c4c286cbb193cf7c4b72ceb2
--- /dev/null
+++ b/comfyui_essentials/requirements.txt
@@ -0,0 +1,5 @@
+numba
+colour-science
+rembg
+pixeloe
+transparent-background
\ No newline at end of file
diff --git a/comfyui_essentials/sampling.py b/comfyui_essentials/sampling.py
new file mode 100644
index 0000000000000000000000000000000000000000..89f8b86576f7be8cf153fe6ebb6087743223c035
--- /dev/null
+++ b/comfyui_essentials/sampling.py
@@ -0,0 +1,418 @@
+import os
+import comfy.samplers
+import comfy.sample
+import torch
+from nodes import common_ksampler
+from .utils import expand_mask, FONTS_DIR, parse_string_to_list
+import torchvision.transforms.v2 as T
+import torch.nn.functional as F
+
+class KSamplerVariationsWithNoise:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {"required": {
+ "model": ("MODEL", ),
+ "latent_image": ("LATENT", ),
+ "main_seed": ("INT:seed", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
+ "steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
+ "cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0, "step":0.1, "round": 0.01}),
+ "sampler_name": (comfy.samplers.KSampler.SAMPLERS, ),
+ "scheduler": (comfy.samplers.KSampler.SCHEDULERS, ),
+ "positive": ("CONDITIONING", ),
+ "negative": ("CONDITIONING", ),
+ "variation_strength": ("FLOAT", {"default": 0.17, "min": 0.0, "max": 1.0, "step":0.01, "round": 0.01}),
+ #"start_at_step": ("INT", {"default": 0, "min": 0, "max": 10000}),
+ #"end_at_step": ("INT", {"default": 10000, "min": 0, "max": 10000}),
+ #"return_with_leftover_noise": (["disable", "enable"], ),
+ "variation_seed": ("INT:seed", {"default": 12345, "min": 0, "max": 0xffffffffffffffff}),
+ "denoise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step":0.01, "round": 0.01}),
+ }}
+
+ RETURN_TYPES = ("LATENT",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/sampling"
+
+ # From https://github.com/BlenderNeko/ComfyUI_Noise/
+ def slerp(self, val, low, high):
+ dims = low.shape
+
+ low = low.reshape(dims[0], -1)
+ high = high.reshape(dims[0], -1)
+
+ low_norm = low/torch.norm(low, dim=1, keepdim=True)
+ high_norm = high/torch.norm(high, dim=1, keepdim=True)
+
+ low_norm[low_norm != low_norm] = 0.0
+ high_norm[high_norm != high_norm] = 0.0
+
+ omega = torch.acos((low_norm*high_norm).sum(1))
+ so = torch.sin(omega)
+ res = (torch.sin((1.0-val)*omega)/so).unsqueeze(1)*low + (torch.sin(val*omega)/so).unsqueeze(1) * high
+
+ return res.reshape(dims)
+
+ def prepare_mask(self, mask, shape):
+ mask = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(shape[2], shape[3]), mode="bilinear")
+ mask = mask.expand((-1,shape[1],-1,-1))
+ if mask.shape[0] < shape[0]:
+ mask = mask.repeat((shape[0] -1) // mask.shape[0] + 1, 1, 1, 1)[:shape[0]]
+ return mask
+
+ def execute(self, model, latent_image, main_seed, steps, cfg, sampler_name, scheduler, positive, negative, variation_strength, variation_seed, denoise):
+ if main_seed == variation_seed:
+ variation_seed += 1
+
+ end_at_step = steps #min(steps, end_at_step)
+ start_at_step = round(end_at_step - end_at_step * denoise)
+
+ force_full_denoise = True
+ disable_noise = True
+
+ device = comfy.model_management.get_torch_device()
+
+ # Generate base noise
+ batch_size, _, height, width = latent_image["samples"].shape
+ generator = torch.manual_seed(main_seed)
+ base_noise = torch.randn((1, 4, height, width), dtype=torch.float32, device="cpu", generator=generator).repeat(batch_size, 1, 1, 1).cpu()
+
+ # Generate variation noise
+ generator = torch.manual_seed(variation_seed)
+ variation_noise = torch.randn((batch_size, 4, height, width), dtype=torch.float32, device="cpu", generator=generator).cpu()
+
+ slerp_noise = self.slerp(variation_strength, base_noise, variation_noise)
+
+ # Calculate sigma
+ comfy.model_management.load_model_gpu(model)
+ sampler = comfy.samplers.KSampler(model, steps=steps, device=device, sampler=sampler_name, scheduler=scheduler, denoise=1.0, model_options=model.model_options)
+ sigmas = sampler.sigmas
+ sigma = sigmas[start_at_step] - sigmas[end_at_step]
+ sigma /= model.model.latent_format.scale_factor
+ sigma = sigma.detach().cpu().item()
+
+ work_latent = latent_image.copy()
+ work_latent["samples"] = latent_image["samples"].clone() + slerp_noise * sigma
+
+ # if there's a mask we need to expand it to avoid artifacts, 5 pixels should be enough
+ if "noise_mask" in latent_image:
+ noise_mask = self.prepare_mask(latent_image["noise_mask"], latent_image['samples'].shape)
+ work_latent["samples"] = noise_mask * work_latent["samples"] + (1-noise_mask) * latent_image["samples"]
+ work_latent['noise_mask'] = expand_mask(latent_image["noise_mask"].clone(), 5, True)
+
+ return common_ksampler(model, main_seed, steps, cfg, sampler_name, scheduler, positive, negative, work_latent, denoise=1.0, disable_noise=disable_noise, start_step=start_at_step, last_step=end_at_step, force_full_denoise=force_full_denoise)
+
+
+class KSamplerVariationsStochastic:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {"required":{
+ "model": ("MODEL",),
+ "latent_image": ("LATENT", ),
+ "noise_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
+ "steps": ("INT", {"default": 25, "min": 1, "max": 10000}),
+ "cfg": ("FLOAT", {"default": 7.0, "min": 0.0, "max": 100.0, "step":0.1, "round": 0.01}),
+ "sampler": (comfy.samplers.KSampler.SAMPLERS, ),
+ "scheduler": (comfy.samplers.KSampler.SCHEDULERS, ),
+ "positive": ("CONDITIONING", ),
+ "negative": ("CONDITIONING", ),
+ "variation_seed": ("INT:seed", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
+ "variation_strength": ("FLOAT", {"default": 0.2, "min": 0.0, "max": 1.0, "step":0.05, "round": 0.01}),
+ #"variation_sampler": (comfy.samplers.KSampler.SAMPLERS, ),
+ "cfg_scale": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step":0.05, "round": 0.01}),
+ }}
+
+ RETURN_TYPES = ("LATENT", )
+ FUNCTION = "execute"
+ CATEGORY = "essentials/sampling"
+
+ def execute(self, model, latent_image, noise_seed, steps, cfg, sampler, scheduler, positive, negative, variation_seed, variation_strength, cfg_scale, variation_sampler="dpmpp_2m_sde"):
+ # Stage 1: composition sampler
+ force_full_denoise = False # return with leftover noise = "enable"
+ disable_noise = False # add noise = "enable"
+
+ end_at_step = max(int(steps * (1-variation_strength)), 1)
+ start_at_step = 0
+
+ work_latent = latent_image.copy()
+ batch_size = work_latent["samples"].shape[0]
+ work_latent["samples"] = work_latent["samples"][0].unsqueeze(0)
+
+ stage1 = common_ksampler(model, noise_seed, steps, cfg, sampler, scheduler, positive, negative, work_latent, denoise=1.0, disable_noise=disable_noise, start_step=start_at_step, last_step=end_at_step, force_full_denoise=force_full_denoise)[0]
+
+ if batch_size > 1:
+ stage1["samples"] = stage1["samples"].clone().repeat(batch_size, 1, 1, 1)
+
+ # Stage 2: variation sampler
+ force_full_denoise = True
+ disable_noise = True
+ cfg = max(cfg * cfg_scale, 1.0)
+ start_at_step = end_at_step
+ end_at_step = steps
+
+ return common_ksampler(model, variation_seed, steps, cfg, variation_sampler, scheduler, positive, negative, stage1, denoise=1.0, disable_noise=disable_noise, start_step=start_at_step, last_step=end_at_step, force_full_denoise=force_full_denoise)
+
+class InjectLatentNoise:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {"required": {
+ "latent": ("LATENT", ),
+ "noise_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
+ "noise_strength": ("FLOAT", {"default": 1.0, "min": -20.0, "max": 20.0, "step":0.01, "round": 0.01}),
+ }}
+
+ RETURN_TYPES = ("LATENT",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/sampling"
+
+ def execute(self, latent, noise_seed, noise_strength):
+ torch.manual_seed(noise_seed)
+ noise_latent = latent.copy()
+ noise_latent["samples"] = noise_latent["samples"].clone() + torch.randn_like(noise_latent["samples"]) * noise_strength
+
+ return (noise_latent, )
+
+class FluxSamplerParams:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {"required": {
+ "model": ("MODEL", ),
+ "conditioning": ("CONDITIONING", ),
+ "latent_image": ("LATENT", ),
+
+ "noise": ("STRING", { "multiline": False, "dynamicPrompts": False, "default": "?" }),
+ "sampler": ("STRING", { "multiline": False, "dynamicPrompts": False, "default": "ipndm" }),
+ "scheduler": ("STRING", { "multiline": False, "dynamicPrompts": False, "default": "simple" }),
+ "steps": ("STRING", { "multiline": False, "dynamicPrompts": False, "default": "20" }),
+ "guidance": ("STRING", { "multiline": False, "dynamicPrompts": False, "default": "3.5" }),
+ "max_shift": ("STRING", { "multiline": False, "dynamicPrompts": False, "default": "1.15" }),
+ "base_shift": ("STRING", { "multiline": False, "dynamicPrompts": False, "default": "0.5" }),
+ "split_sigmas": ("STRING", { "multiline": False, "dynamicPrompts": False, "default": "1.0" }),
+ "denoise": ("STRING", { "multiline": False, "dynamicPrompts": False, "default": "1.0" }),
+ }}
+
+ RETURN_TYPES = ("LATENT","SAMPLER_PARAMS")
+ RETURN_NAMES = ("latent", "params")
+ FUNCTION = "execute"
+ CATEGORY = "essentials/sampling"
+
+ def execute(self, model, conditioning, latent_image, noise, sampler, scheduler, steps, guidance, max_shift, base_shift, split_sigmas, denoise):
+ import random
+ import time
+ from comfy_extras.nodes_custom_sampler import Noise_RandomNoise, BasicScheduler, BasicGuider, SamplerCustomAdvanced, SplitSigmasDenoise
+ from comfy_extras.nodes_latent import LatentBatch
+ from comfy_extras.nodes_model_advanced import ModelSamplingFlux
+ from node_helpers import conditioning_set_values
+
+ noise = noise.replace("\n", ",").split(",")
+ noise = [random.randint(0, 999999) if "?" in n else int(n) for n in noise]
+ if not noise:
+ noise = [random.randint(0, 999999)]
+
+ if sampler == '*':
+ sampler = comfy.samplers.KSampler.SAMPLERS
+ elif sampler.startswith("!"):
+ sampler = sampler.replace("\n", ",").split(",")
+ sampler = [s.strip("! ") for s in sampler]
+ sampler = [s for s in comfy.samplers.KSampler.SAMPLERS if s not in sampler]
+ else:
+ sampler = sampler.replace("\n", ",").split(",")
+ sampler = [s.strip() for s in sampler if s.strip() in comfy.samplers.KSampler.SAMPLERS]
+ if not sampler:
+ sampler = ['ipndm']
+
+ if scheduler == '*':
+ scheduler = comfy.samplers.KSampler.SCHEDULERS
+ elif scheduler.startswith("!"):
+ scheduler = scheduler.replace("\n", ",").split(",")
+ scheduler = [s.strip("! ") for s in scheduler]
+ scheduler = [s for s in comfy.samplers.KSampler.SCHEDULERS if s not in scheduler]
+ else:
+ scheduler = scheduler.replace("\n", ",").split(",")
+ scheduler = [s.strip() for s in scheduler]
+ scheduler = [s for s in scheduler if s in comfy.samplers.KSampler.SCHEDULERS]
+ if not scheduler:
+ scheduler = ['simple']
+
+ steps = steps.replace("\n", ",").split(",")
+ steps = [int(s) for s in steps]
+ if not steps:
+ steps = [20]
+
+ denoise = parse_string_to_list(denoise)
+ if not denoise:
+ denoise = [1.0]
+
+ guidance = parse_string_to_list(guidance)
+ if not guidance:
+ guidance = [3.5]
+
+ max_shift = parse_string_to_list(max_shift)
+ if not max_shift:
+ max_shift = [1.15]
+
+ base_shift = parse_string_to_list(base_shift)
+ if not base_shift:
+ base_shift = [0.5]
+
+ split_sigmas = parse_string_to_list(split_sigmas)
+ if not split_sigmas:
+ split_sigmas = [1.0]
+
+ out_latent = None
+ out_params = []
+
+ basicschedueler = BasicScheduler()
+ basicguider = BasicGuider()
+ samplercustomadvanced = SamplerCustomAdvanced()
+ latentbatch = LatentBatch()
+ modelsamplingflux = ModelSamplingFlux()
+ splitsigmadenoise = SplitSigmasDenoise()
+ width = latent_image["samples"].shape[3]*8
+ height = latent_image["samples"].shape[2]*8
+
+ for n in noise:
+ randnoise = Noise_RandomNoise(n)
+ for ms in max_shift:
+ for bs in base_shift:
+ work_model = modelsamplingflux.patch(model, ms, bs, width, height)[0]
+ for g in guidance:
+ cond = conditioning_set_values(conditioning, {"guidance": g})
+ guider = basicguider.get_guider(work_model, cond)[0]
+ for s in sampler:
+ samplerobj = comfy.samplers.sampler_object(s)
+ for sc in scheduler:
+ for st in steps:
+ for d in denoise:
+ sigmas = basicschedueler.get_sigmas(work_model, sc, st, d)[0]
+ for ss in split_sigmas:
+ sigmas = splitsigmadenoise.get_sigmas(sigmas, ss)[1]
+ start_time = time.time()
+ latent = samplercustomadvanced.sample(randnoise, guider, samplerobj, sigmas, latent_image)[1]
+ elapsed_time = time.time() - start_time
+ out_params.append({"time": elapsed_time,
+ "seed": n,
+ "sampler": s,
+ "scheduler": sc,
+ "steps": st,
+ "guidance": g,
+ "max_shift": ms,
+ "base_shift": bs,
+ "denoise": d,
+ "split_sigmas": ss})
+
+ if out_latent is None:
+ out_latent = latent
+ else:
+ out_latent = latentbatch.batch(out_latent, latent)[0]
+
+ return (out_latent, out_params)
+
+class PlotParameters:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {"required": {
+ "images": ("IMAGE", ),
+ "params": ("SAMPLER_PARAMS", ),
+ "order_by": (["none", "time", "seed", "steps", "denoise", "sampler", "scheduler"], ),
+ "cols_value": (["none", "time", "seed", "steps", "denoise", "sampler", "scheduler"], ),
+ "cols_num": ("INT", {"default": -1, "min": -1, "max": 1024 }),
+ }}
+
+ RETURN_TYPES = ("IMAGE", )
+ FUNCTION = "execute"
+ CATEGORY = "essentials/sampling"
+
+ def execute(self, images, params, order_by, cols_value, cols_num):
+ from PIL import Image, ImageDraw, ImageFont
+ import math
+
+ if images.shape[0] != len(params):
+ raise ValueError("Number of images and number of parameters do not match.")
+
+ if order_by != "none":
+ if cols_value != "none" and cols_num < 1:
+ cols_num = len(set(p[cols_value] for p in params))
+ sorted_params = sorted(params, key=lambda x: x[order_by])
+ indices = [params.index(item) for item in sorted_params]
+ params = sorted_params
+ images = images[torch.tensor(indices)]
+
+ width = images.shape[2]
+ out_image = None
+
+ font = ImageFont.truetype(os.path.join(FONTS_DIR, 'ShareTechMono-Regular.ttf'), min(48, int(32*(width/1024))))
+ text_padding = 3
+ line_height = font.getmask('WwMmQqlL1234567890').getbbox()[3] + font.getmetrics()[1] + text_padding*2
+
+ for (image, param) in zip(images, params):
+ text = f"time: {param['time']:.2f}s, seed: {param['seed']}, steps: {param['steps']}, denoise: {param['denoise']}\nsampler: {param['sampler']}, sched: {param['scheduler']}, sigmas at: {param['split_sigmas']}\nguidance: {param['guidance']}, max/base shift: {param['max_shift']}/{param['base_shift']}"
+ lines = text.split("\n")
+ text_height = line_height * len(lines)
+ text_image = Image.new('RGB', (width, text_height), color=(0, 0, 0, 0))
+
+ for i, line in enumerate(lines):
+ draw = ImageDraw.Draw(text_image)
+ draw.text((text_padding, i * line_height + text_padding), line, font=font, fill=(255, 255, 255))
+
+ text_image = T.ToTensor()(text_image).unsqueeze(0).permute([0,2,3,1]).to(image.device)
+ image = torch.cat([image.unsqueeze(0), text_image], 1)
+
+ if out_image is None:
+ out_image = image
+ else:
+ out_image = torch.cat([out_image, image], 0)
+
+ if cols_num > -1:
+ if cols_num == 0:
+ mosaic_columns = int(math.sqrt(out_image.shape[0]))
+ mosaic_columns = max(1, min(mosaic_columns, 1024))
+
+ cols = min(mosaic_columns, out_image.shape[0])
+ b, h, w, c = out_image.shape
+ rows = math.ceil(b / cols)
+
+ # Pad the tensor if necessary
+ if b % cols != 0:
+ padding = cols - (b % cols)
+ out_image = F.pad(out_image, (0, 0, 0, 0, 0, 0, 0, padding))
+ b = out_image.shape[0]
+
+ # Reshape and transpose
+ out_image = out_image.reshape(rows, cols, h, w, c)
+ out_image = out_image.permute(0, 2, 1, 3, 4)
+ out_image = out_image.reshape(rows * h, cols * w, c).unsqueeze(0)
+
+ """
+ width = out_image.shape[2]
+ # add the title and notes on top
+ if title and export_labels:
+ title_font = ImageFont.truetype(os.path.join(FONTS_DIR, 'ShareTechMono-Regular.ttf'), 48)
+ title_width = title_font.getbbox(title)[2]
+ title_padding = 6
+ title_line_height = title_font.getmask(title).getbbox()[3] + title_font.getmetrics()[1] + title_padding*2
+ title_text_height = title_line_height
+ title_text_image = Image.new('RGB', (width, title_text_height), color=(0, 0, 0, 0))
+
+ draw = ImageDraw.Draw(title_text_image)
+ draw.text((width//2 - title_width//2, title_padding), title, font=title_font, fill=(255, 255, 255))
+
+ title_text_image = T.ToTensor()(title_text_image).unsqueeze(0).permute([0,2,3,1]).to(out_image.device)
+ out_image = torch.cat([title_text_image, out_image], 1)
+ """
+
+ return (out_image, )
+
+SAMPLING_CLASS_MAPPINGS = {
+ "KSamplerVariationsStochastic+": KSamplerVariationsStochastic,
+ "KSamplerVariationsWithNoise+": KSamplerVariationsWithNoise,
+ "InjectLatentNoise+": InjectLatentNoise,
+ "FluxSamplerParams+": FluxSamplerParams,
+ "PlotParameters+": PlotParameters,
+}
+
+SAMPLING_NAME_MAPPINGS = {
+ "KSamplerVariationsStochastic+": "🔧 KSampler Stochastic Variations",
+ "KSamplerVariationsWithNoise+": "🔧 KSampler Variations with Noise Injection",
+ "InjectLatentNoise+": "🔧 Inject Latent Noise",
+ "FluxSamplerParams+": "🔧 Flux Sampler Parameters",
+ "PlotParameters+": "🔧 Plot Sampler Parameters",
+}
\ No newline at end of file
diff --git a/comfyui_essentials/segmentation.py b/comfyui_essentials/segmentation.py
new file mode 100644
index 0000000000000000000000000000000000000000..55f870144afb2f51da26fd1c3bd97c03ed4223b7
--- /dev/null
+++ b/comfyui_essentials/segmentation.py
@@ -0,0 +1,89 @@
+import torch
+import torchvision.transforms.v2 as T
+import torch.nn.functional as F
+from .utils import expand_mask
+
+class LoadCLIPSegModels:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {},
+ }
+
+ RETURN_TYPES = ("CLIP_SEG",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/segmentation"
+
+ def execute(self):
+ from transformers import CLIPSegProcessor, CLIPSegForImageSegmentation
+ processor = CLIPSegProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
+ model = CLIPSegForImageSegmentation.from_pretrained("CIDAS/clipseg-rd64-refined")
+
+ return ((processor, model),)
+
+class ApplyCLIPSeg:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "clip_seg": ("CLIP_SEG",),
+ "image": ("IMAGE",),
+ "prompt": ("STRING", { "multiline": False, "default": "" }),
+ "threshold": ("FLOAT", { "default": 0.4, "min": 0.0, "max": 1.0, "step": 0.05 }),
+ "smooth": ("INT", { "default": 9, "min": 0, "max": 32, "step": 1 }),
+ "dilate": ("INT", { "default": 0, "min": -32, "max": 32, "step": 1 }),
+ "blur": ("INT", { "default": 0, "min": 0, "max": 64, "step": 1 }),
+ },
+ }
+
+ RETURN_TYPES = ("MASK",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/segmentation"
+
+ def execute(self, image, clip_seg, prompt, threshold, smooth, dilate, blur):
+ processor, model = clip_seg
+
+ imagenp = image.mul(255).clamp(0, 255).byte().cpu().numpy()
+
+ outputs = []
+ for i in imagenp:
+ inputs = processor(text=prompt, images=[i], return_tensors="pt")
+ out = model(**inputs)
+ out = out.logits.unsqueeze(1)
+ out = torch.sigmoid(out[0][0])
+ out = (out > threshold)
+ outputs.append(out)
+
+ del imagenp
+
+ outputs = torch.stack(outputs, dim=0)
+
+ if smooth > 0:
+ if smooth % 2 == 0:
+ smooth += 1
+ outputs = T.functional.gaussian_blur(outputs, smooth)
+
+ outputs = outputs.float()
+
+ if dilate != 0:
+ outputs = expand_mask(outputs, dilate, True)
+
+ if blur > 0:
+ if blur % 2 == 0:
+ blur += 1
+ outputs = T.functional.gaussian_blur(outputs, blur)
+
+ # resize to original size
+ outputs = F.interpolate(outputs.unsqueeze(1), size=(image.shape[1], image.shape[2]), mode='bicubic').squeeze(1)
+
+ return (outputs,)
+
+SEG_CLASS_MAPPINGS = {
+ "ApplyCLIPSeg+": ApplyCLIPSeg,
+ "LoadCLIPSegModels+": LoadCLIPSegModels,
+}
+
+SEG_NAME_MAPPINGS = {
+ "ApplyCLIPSeg+": "🔧 Apply CLIPSeg",
+ "LoadCLIPSegModels+": "🔧 Load CLIPSeg Models",
+}
\ No newline at end of file
diff --git a/comfyui_essentials/text.py b/comfyui_essentials/text.py
new file mode 100644
index 0000000000000000000000000000000000000000..643a1f360d80d23976dbfb9b0f21c0fe444b489a
--- /dev/null
+++ b/comfyui_essentials/text.py
@@ -0,0 +1,110 @@
+import os
+import torch
+from nodes import MAX_RESOLUTION
+import torchvision.transforms.v2 as T
+from .utils import FONTS_DIR
+
+class DrawText:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "text": ("STRING", { "multiline": True, "dynamicPrompts": True, "default": "Hello, World!" }),
+ "font": (sorted([f for f in os.listdir(FONTS_DIR) if f.endswith('.ttf') or f.endswith('.otf')]), ),
+ "size": ("INT", { "default": 56, "min": 1, "max": 9999, "step": 1 }),
+ "color": ("STRING", { "multiline": False, "default": "#FFFFFF" }),
+ "background_color": ("STRING", { "multiline": False, "default": "#00000000" }),
+ "shadow_distance": ("INT", { "default": 0, "min": 0, "max": 100, "step": 1 }),
+ "shadow_blur": ("INT", { "default": 0, "min": 0, "max": 100, "step": 1 }),
+ "shadow_color": ("STRING", { "multiline": False, "default": "#000000" }),
+ "horizontal_align": (["left", "center", "right"],),
+ "vertical_align": (["top", "center", "bottom"],),
+ "offset_x": ("INT", { "default": 0, "min": -MAX_RESOLUTION, "max": MAX_RESOLUTION, "step": 1 }),
+ "offset_y": ("INT", { "default": 0, "min": -MAX_RESOLUTION, "max": MAX_RESOLUTION, "step": 1 }),
+ },
+ "optional": {
+ "img_composite": ("IMAGE",),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE", "MASK",)
+ FUNCTION = "execute"
+ CATEGORY = "essentials/text"
+
+ def execute(self, text, font, size, color, background_color, shadow_distance, shadow_blur, shadow_color, horizontal_align, vertical_align, offset_x, offset_y, img_composite=None):
+ from PIL import Image, ImageDraw, ImageFont, ImageColor, ImageFilter
+
+ font = ImageFont.truetype(os.path.join(FONTS_DIR, font), size)
+
+ lines = text.split("\n")
+
+ # Calculate the width and height of the text
+ text_width = max(font.getbbox(line)[2] for line in lines)
+ line_height = font.getmask(text).getbbox()[3] + font.getmetrics()[1] # add descent to height
+ text_height = line_height * len(lines)
+
+ if img_composite is not None:
+ img_composite = T.ToPILImage()(img_composite.permute([0,3,1,2])[0]).convert('RGBA')
+ width = img_composite.width
+ height = img_composite.height
+ image = Image.new('RGBA', (width, height), color=background_color)
+ else:
+ width = text_width
+ height = text_height
+ background_color = ImageColor.getrgb(background_color)
+ image = Image.new('RGBA', (width + shadow_distance, height + shadow_distance), color=background_color)
+
+ image_shadow = None
+ if shadow_distance > 0:
+ image_shadow = image.copy()
+ #image_shadow = Image.new('RGBA', (width + shadow_distance, height + shadow_distance), color=background_color)
+
+ for i, line in enumerate(lines):
+ line_width = font.getbbox(line)[2]
+ #text_height =font.getbbox(line)[3]
+ if horizontal_align == "left":
+ x = 0
+ elif horizontal_align == "center":
+ x = (width - line_width) / 2
+ elif horizontal_align == "right":
+ x = width - line_width
+
+ if vertical_align == "top":
+ y = 0
+ elif vertical_align == "center":
+ y = (height - text_height) / 2
+ elif vertical_align == "bottom":
+ y = height - text_height
+
+ x += offset_x
+ y += i * line_height + offset_y
+
+ draw = ImageDraw.Draw(image)
+ draw.text((x, y), line, font=font, fill=color)
+
+ if image_shadow is not None:
+ draw = ImageDraw.Draw(image_shadow)
+ draw.text((x + shadow_distance, y + shadow_distance), line, font=font, fill=shadow_color)
+
+ if image_shadow is not None:
+ image_shadow = image_shadow.filter(ImageFilter.GaussianBlur(shadow_blur))
+ image = Image.alpha_composite(image_shadow, image)
+
+ #image = T.ToTensor()(image).unsqueeze(0).permute([0,2,3,1])
+ mask = T.ToTensor()(image).unsqueeze(0).permute([0,2,3,1])
+ mask = mask[:, :, :, 3] if mask.shape[3] == 4 else torch.ones_like(mask[:, :, :, 0])
+
+ if img_composite is not None:
+ image = Image.alpha_composite(img_composite, image)
+
+ image = T.ToTensor()(image).unsqueeze(0).permute([0,2,3,1])
+
+ return (image[:, :, :, :3], mask,)
+
+TEXT_CLASS_MAPPINGS = {
+ "DrawText+": DrawText,
+}
+
+TEXT_NAME_MAPPINGS = {
+ "DrawText+": "🔧 Draw Text",
+}
\ No newline at end of file
diff --git a/comfyui_essentials/utils.py b/comfyui_essentials/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa36e3171da0afde91c224605b1bbe63144e3a30
--- /dev/null
+++ b/comfyui_essentials/utils.py
@@ -0,0 +1,81 @@
+import torch
+import numpy as np
+import scipy
+import os
+import re
+
+FONTS_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "fonts")
+
+# from https://github.com/pythongosssss/ComfyUI-Custom-Scripts
+class AnyType(str):
+ def __ne__(self, __value: object) -> bool:
+ return False
+
+def min_(tensor_list):
+ # return the element-wise min of the tensor list.
+ x = torch.stack(tensor_list)
+ mn = x.min(axis=0)[0]
+ return torch.clamp(mn, min=0)
+
+def max_(tensor_list):
+ # return the element-wise max of the tensor list.
+ x = torch.stack(tensor_list)
+ mx = x.max(axis=0)[0]
+ return torch.clamp(mx, max=1)
+
+def expand_mask(mask, expand, tapered_corners):
+ c = 0 if tapered_corners else 1
+ kernel = np.array([[c, 1, c],
+ [1, 1, 1],
+ [c, 1, c]])
+ mask = mask.reshape((-1, mask.shape[-2], mask.shape[-1]))
+ out = []
+ for m in mask:
+ output = m.numpy()
+ for _ in range(abs(expand)):
+ if expand < 0:
+ output = scipy.ndimage.grey_erosion(output, footprint=kernel)
+ else:
+ output = scipy.ndimage.grey_dilation(output, footprint=kernel)
+ output = torch.from_numpy(output)
+ out.append(output)
+
+ return torch.stack(out, dim=0)
+
+def parse_string_to_list(s):
+ elements = s.split(',')
+ result = []
+
+ def parse_number(s):
+ try:
+ if '.' in s:
+ return float(s)
+ else:
+ return int(s)
+ except ValueError:
+ return 0
+
+ def decimal_places(s):
+ if '.' in s:
+ return len(s.split('.')[1])
+ return 0
+
+ for element in elements:
+ element = element.strip()
+ if '...' in element:
+ start, rest = element.split('...')
+ end, step = rest.split('+')
+ decimals = decimal_places(step)
+ start = parse_number(start)
+ end = parse_number(end)
+ step = parse_number(step)
+ current = start
+ if (start > end and step > 0) or (start < end and step < 0):
+ step = -step
+ while current <= end:
+ result.append(round(current, decimals))
+ current += step
+ else:
+ result.append(round(parse_number(element), decimal_places(element)))
+
+ return result
\ No newline at end of file
diff --git a/comfyui_essentials/workflow_all_nodes.json b/comfyui_essentials/workflow_all_nodes.json
new file mode 100644
index 0000000000000000000000000000000000000000..fab4c98929e12b9f7ac35bd433ffa55af81480b2
--- /dev/null
+++ b/comfyui_essentials/workflow_all_nodes.json
@@ -0,0 +1,994 @@
+{
+ "last_node_id": 42,
+ "last_link_id": 61,
+ "nodes": [
+ {
+ "id": 9,
+ "type": "ConsoleDebug+",
+ "pos": [
+ 720,
+ 140
+ ],
+ "size": {
+ "0": 210,
+ "1": 60
+ },
+ "flags": {},
+ "order": 12,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "value",
+ "type": "*",
+ "link": 3
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "ConsoleDebug+"
+ },
+ "widgets_values": [
+ "Height:"
+ ]
+ },
+ {
+ "id": 28,
+ "type": "PreviewImage",
+ "pos": [
+ 860,
+ 1180
+ ],
+ "size": {
+ "0": 210,
+ "1": 246
+ },
+ "flags": {},
+ "order": 17,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 23
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 12,
+ "type": "PreviewImage",
+ "pos": [
+ 860,
+ 580
+ ],
+ "size": {
+ "0": 210,
+ "1": 246
+ },
+ "flags": {},
+ "order": 15,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 11
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 14,
+ "type": "PreviewImage",
+ "pos": [
+ 860,
+ 880
+ ],
+ "size": {
+ "0": 210,
+ "1": 246
+ },
+ "flags": {},
+ "order": 16,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 13
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 18,
+ "type": "MaskPreview+",
+ "pos": [
+ 2100,
+ 90
+ ],
+ "size": {
+ "0": 210,
+ "1": 246
+ },
+ "flags": {},
+ "order": 20,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "mask",
+ "type": "MASK",
+ "link": 19
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "MaskPreview+"
+ }
+ },
+ {
+ "id": 1,
+ "type": "GetImageSize+",
+ "pos": [
+ 450,
+ 80
+ ],
+ "size": {
+ "0": 210,
+ "1": 46
+ },
+ "flags": {},
+ "order": 2,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 1
+ }
+ ],
+ "outputs": [
+ {
+ "name": "width",
+ "type": "INT",
+ "links": [
+ 2
+ ],
+ "shape": 3,
+ "slot_index": 0
+ },
+ {
+ "name": "height",
+ "type": "INT",
+ "links": [
+ 3
+ ],
+ "shape": 3,
+ "slot_index": 1
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "GetImageSize+"
+ }
+ },
+ {
+ "id": 8,
+ "type": "ConsoleDebug+",
+ "pos": [
+ 720,
+ 40
+ ],
+ "size": {
+ "0": 210,
+ "1": 60
+ },
+ "flags": {},
+ "order": 11,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "value",
+ "type": "*",
+ "link": 2
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "ConsoleDebug+"
+ },
+ "widgets_values": [
+ "Width:"
+ ]
+ },
+ {
+ "id": 10,
+ "type": "PreviewImage",
+ "pos": [
+ 860,
+ 280
+ ],
+ "size": {
+ "0": 210,
+ "1": 246
+ },
+ "flags": {},
+ "order": 13,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 9
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 36,
+ "type": "SimpleMath+",
+ "pos": [
+ 1650,
+ 780
+ ],
+ "size": {
+ "0": 210,
+ "1": 80
+ },
+ "flags": {},
+ "order": 14,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "a",
+ "type": "INT,FLOAT",
+ "link": 44
+ },
+ {
+ "name": "b",
+ "type": "INT,FLOAT",
+ "link": 45
+ }
+ ],
+ "outputs": [
+ {
+ "name": "INT",
+ "type": "INT",
+ "links": [
+ 46
+ ],
+ "shape": 3,
+ "slot_index": 0
+ },
+ {
+ "name": "FLOAT",
+ "type": "FLOAT",
+ "links": null,
+ "shape": 3
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "SimpleMath+"
+ },
+ "widgets_values": [
+ "a*b"
+ ]
+ },
+ {
+ "id": 23,
+ "type": "ConsoleDebug+",
+ "pos": [
+ 1920,
+ 780
+ ],
+ "size": {
+ "0": 210,
+ "1": 60
+ },
+ "flags": {},
+ "order": 22,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "value",
+ "type": "*",
+ "link": 46
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "ConsoleDebug+"
+ },
+ "widgets_values": [
+ "Value:"
+ ]
+ },
+ {
+ "id": 2,
+ "type": "ImageResize+",
+ "pos": [
+ 430,
+ 340
+ ],
+ "size": {
+ "0": 310,
+ "1": 170
+ },
+ "flags": {},
+ "order": 3,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 4
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 9
+ ],
+ "shape": 3,
+ "slot_index": 0
+ },
+ {
+ "name": "width",
+ "type": "INT",
+ "links": [
+ 44
+ ],
+ "shape": 3,
+ "slot_index": 1
+ },
+ {
+ "name": "height",
+ "type": "INT",
+ "links": [
+ 45
+ ],
+ "shape": 3,
+ "slot_index": 2
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "ImageResize+"
+ },
+ "widgets_values": [
+ 256,
+ 64,
+ "lanczos",
+ true
+ ]
+ },
+ {
+ "id": 4,
+ "type": "ImageFlip+",
+ "pos": [
+ 430,
+ 800
+ ],
+ "size": {
+ "0": 310,
+ "1": 60
+ },
+ "flags": {},
+ "order": 4,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 6
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 11
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "ImageFlip+"
+ },
+ "widgets_values": [
+ "xy"
+ ]
+ },
+ {
+ "id": 6,
+ "type": "ImagePosterize+",
+ "pos": [
+ 430,
+ 1000
+ ],
+ "size": {
+ "0": 310,
+ "1": 60
+ },
+ "flags": {},
+ "order": 5,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 8
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 13
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "ImagePosterize+"
+ },
+ "widgets_values": [
+ 0.5
+ ]
+ },
+ {
+ "id": 27,
+ "type": "ImageCASharpening+",
+ "pos": [
+ 430,
+ 1110
+ ],
+ "size": {
+ "0": 310.79998779296875,
+ "1": 60
+ },
+ "flags": {},
+ "order": 6,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 22
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 23
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "ImageCASharpening+"
+ },
+ "widgets_values": [
+ 0.8
+ ]
+ },
+ {
+ "id": 15,
+ "type": "MaskBlur+",
+ "pos": [
+ 1690,
+ 130
+ ],
+ "size": {
+ "0": 310,
+ "1": 82
+ },
+ "flags": {},
+ "order": 9,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "mask",
+ "type": "MASK",
+ "link": 14
+ }
+ ],
+ "outputs": [
+ {
+ "name": "MASK",
+ "type": "MASK",
+ "links": [
+ 19
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "MaskBlur+"
+ },
+ "widgets_values": [
+ 45,
+ 28.5
+ ]
+ },
+ {
+ "id": 16,
+ "type": "MaskFlip+",
+ "pos": [
+ 1690,
+ 270
+ ],
+ "size": {
+ "0": 310,
+ "1": 60
+ },
+ "flags": {},
+ "order": 10,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "mask",
+ "type": "MASK",
+ "link": 15
+ }
+ ],
+ "outputs": [
+ {
+ "name": "MASK",
+ "type": "MASK",
+ "links": [
+ 18
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "MaskFlip+"
+ },
+ "widgets_values": [
+ "xy"
+ ]
+ },
+ {
+ "id": 13,
+ "type": "PreviewImage",
+ "pos": [
+ 1100,
+ 760
+ ],
+ "size": {
+ "0": 210,
+ "1": 246
+ },
+ "flags": {},
+ "order": 18,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 49
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 37,
+ "type": "ImageDesaturate+",
+ "pos": [
+ 500,
+ 920
+ ],
+ "size": {
+ "0": 190,
+ "1": 30
+ },
+ "flags": {},
+ "order": 7,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 48
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 49
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "ImageDesaturate+"
+ }
+ },
+ {
+ "id": 7,
+ "type": "LoadImage",
+ "pos": [
+ -90,
+ 650
+ ],
+ "size": {
+ "0": 315,
+ "1": 314
+ },
+ "flags": {},
+ "order": 0,
+ "mode": 0,
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 1,
+ 4,
+ 6,
+ 8,
+ 22,
+ 48,
+ 57
+ ],
+ "shape": 3,
+ "slot_index": 0
+ },
+ {
+ "name": "MASK",
+ "type": "MASK",
+ "links": null,
+ "shape": 3
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "LoadImage"
+ },
+ "widgets_values": [
+ "venere.jpg",
+ "image"
+ ]
+ },
+ {
+ "id": 11,
+ "type": "PreviewImage",
+ "pos": [
+ 1100,
+ 450
+ ],
+ "size": {
+ "0": 210,
+ "1": 246
+ },
+ "flags": {},
+ "order": 19,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "images",
+ "type": "IMAGE",
+ "link": 58
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "PreviewImage"
+ }
+ },
+ {
+ "id": 40,
+ "type": "ImageCrop+",
+ "pos": [
+ 430,
+ 560
+ ],
+ "size": {
+ "0": 310,
+ "1": 194
+ },
+ "flags": {},
+ "order": 8,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "image",
+ "type": "IMAGE",
+ "link": 57
+ }
+ ],
+ "outputs": [
+ {
+ "name": "IMAGE",
+ "type": "IMAGE",
+ "links": [
+ 58
+ ],
+ "shape": 3,
+ "slot_index": 0
+ },
+ {
+ "name": "x",
+ "type": "INT",
+ "links": null,
+ "shape": 3
+ },
+ {
+ "name": "y",
+ "type": "INT",
+ "links": null,
+ "shape": 3
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "ImageCrop+"
+ },
+ "widgets_values": [
+ 256,
+ 256,
+ "center",
+ 0,
+ 0
+ ]
+ },
+ {
+ "id": 20,
+ "type": "LoadImageMask",
+ "pos": [
+ 1400,
+ 260
+ ],
+ "size": {
+ "0": 220.70516967773438,
+ "1": 318
+ },
+ "flags": {},
+ "order": 1,
+ "mode": 0,
+ "outputs": [
+ {
+ "name": "MASK",
+ "type": "MASK",
+ "links": [
+ 14,
+ 15
+ ],
+ "shape": 3,
+ "slot_index": 0
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "LoadImageMask"
+ },
+ "widgets_values": [
+ "cwf_inpaint_example_mask.png",
+ "alpha",
+ "image"
+ ]
+ },
+ {
+ "id": 21,
+ "type": "MaskPreview+",
+ "pos": [
+ 2100,
+ 380
+ ],
+ "size": {
+ "0": 210,
+ "1": 246
+ },
+ "flags": {},
+ "order": 21,
+ "mode": 0,
+ "inputs": [
+ {
+ "name": "mask",
+ "type": "MASK",
+ "link": 18
+ }
+ ],
+ "properties": {
+ "Node name for S&R": "MaskPreview+"
+ }
+ }
+ ],
+ "links": [
+ [
+ 1,
+ 7,
+ 0,
+ 1,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 2,
+ 1,
+ 0,
+ 8,
+ 0,
+ "*"
+ ],
+ [
+ 3,
+ 1,
+ 1,
+ 9,
+ 0,
+ "*"
+ ],
+ [
+ 4,
+ 7,
+ 0,
+ 2,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 6,
+ 7,
+ 0,
+ 4,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 8,
+ 7,
+ 0,
+ 6,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 9,
+ 2,
+ 0,
+ 10,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 11,
+ 4,
+ 0,
+ 12,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 13,
+ 6,
+ 0,
+ 14,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 14,
+ 20,
+ 0,
+ 15,
+ 0,
+ "MASK"
+ ],
+ [
+ 15,
+ 20,
+ 0,
+ 16,
+ 0,
+ "MASK"
+ ],
+ [
+ 18,
+ 16,
+ 0,
+ 21,
+ 0,
+ "MASK"
+ ],
+ [
+ 19,
+ 15,
+ 0,
+ 18,
+ 0,
+ "MASK"
+ ],
+ [
+ 22,
+ 7,
+ 0,
+ 27,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 23,
+ 27,
+ 0,
+ 28,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 44,
+ 2,
+ 1,
+ 36,
+ 0,
+ "INT,FLOAT"
+ ],
+ [
+ 45,
+ 2,
+ 2,
+ 36,
+ 1,
+ "INT,FLOAT"
+ ],
+ [
+ 46,
+ 36,
+ 0,
+ 23,
+ 0,
+ "*"
+ ],
+ [
+ 48,
+ 7,
+ 0,
+ 37,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 49,
+ 37,
+ 0,
+ 13,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 57,
+ 7,
+ 0,
+ 40,
+ 0,
+ "IMAGE"
+ ],
+ [
+ 58,
+ 40,
+ 0,
+ 11,
+ 0,
+ "IMAGE"
+ ]
+ ],
+ "groups": [],
+ "config": {},
+ "extra": {},
+ "version": 0.4
+}
\ No newline at end of file
diff --git a/comfyui_fill-nodes/.DS_Store b/comfyui_fill-nodes/.DS_Store
new file mode 100644
index 0000000000000000000000000000000000000000..3dfb035d6f6e5f8d9cb82ee92e55e05276fd7e1d
Binary files /dev/null and b/comfyui_fill-nodes/.DS_Store differ
diff --git a/comfyui_fill-nodes/.gitattributes b/comfyui_fill-nodes/.gitattributes
new file mode 100644
index 0000000000000000000000000000000000000000..dfdb8b771ce07609491fa2e83698969fd917a135
--- /dev/null
+++ b/comfyui_fill-nodes/.gitattributes
@@ -0,0 +1 @@
+*.sh text eol=lf
diff --git a/comfyui_fill-nodes/.github/workflows/publish.yml b/comfyui_fill-nodes/.github/workflows/publish.yml
new file mode 100644
index 0000000000000000000000000000000000000000..828f300203c628d32100495bfc3c1f2a94eead55
--- /dev/null
+++ b/comfyui_fill-nodes/.github/workflows/publish.yml
@@ -0,0 +1,21 @@
+name: Publish to Comfy registry
+on:
+ workflow_dispatch:
+ push:
+ branches:
+ - main
+ paths:
+ - "pyproject.toml"
+
+jobs:
+ publish-node:
+ name: Publish Custom Node to registry
+ runs-on: ubuntu-latest
+ steps:
+ - name: Check out code
+ uses: actions/checkout@v4
+ - name: Publish Custom Node
+ uses: Comfy-Org/publish-node-action@main
+ with:
+ ## Add your own personal access token to your Github Repository secrets and reference it here.
+ personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
\ No newline at end of file
diff --git a/comfyui_fill-nodes/.gitignore b/comfyui_fill-nodes/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..66620232255ba8b23607d7c7d21c61a228c43538
--- /dev/null
+++ b/comfyui_fill-nodes/.gitignore
@@ -0,0 +1,180 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+*.code-workspace
+.vscode/
+config.json
+ignore.txt
+.env
+__pycache__
+
+# Cache directory
+cache/
+
+
+# Byte-compiled / optimized / DLL files
+__pycache__/
+
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+# Usually these files are written by a python script from a template
+# before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+#*.py,cover
+.hypothesis/
+.pytest_cache/
+cover/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+db.sqlite3-journal
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+.pybuilder/
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+# For a library or package, you might want to ignore these files since the code is
+# intended to run in multiple environments; otherwise, check them in:
+# .python-version
+
+# pipenv
+# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
+# However, in case of collaboration, if having platform-specific dependencies or dependencies
+# having no cross-platform support, pipenv may install dependencies that don't work, or not
+# install all needed dependencies.
+#Pipfile.lock
+
+# poetry
+# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
+# This is especially recommended for binary packages to ensure reproducibility, and is more
+# commonly ignored for libraries.
+# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
+#poetry.lock
+
+# pdm
+# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
+#pdm.lock
+# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
+# in version control.
+# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
+.pdm.toml
+.pdm-python
+.pdm-build/
+
+# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
+__pypackages__/
+
+# Celery stuff
+celerybeat-schedule
+celerybeat.pid
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# pytype static type analyzer
+.pytype/
+
+# Cython debug symbols
+cython_debug/
+
+# PyCharm
+# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
+# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
+# and can be added to the global gitignore or merged into this file. For a more nuclear
+# option (not recommended) you can uncomment the following to ignore the entire idea folder.
+.idea/
+
+# Claude Code folder
+.claude/
\ No newline at end of file
diff --git a/comfyui_fill-nodes/.tracking b/comfyui_fill-nodes/.tracking
new file mode 100644
index 0000000000000000000000000000000000000000..14acfdb9b6aaeb889ce1a983c1fc75c0d6fde20d
--- /dev/null
+++ b/comfyui_fill-nodes/.tracking
@@ -0,0 +1,300 @@
+.DS_Store
+.gitattributes
+.github/workflows/publish.yml
+.gitignore
+README.md
+__init__.py
+fonts/Barcode.ttf
+fonts/Circles.ttf
+fonts/Fancy.otf
+fonts/Pattern.otf
+fonts/Square.TTF
+fonts/arial.ttf
+images/.DS_Store
+images/nodes/HF.png
+images/nodes/Patreon.png
+images/nodes/Utility_nodes.png
+images/nodes/VFX_nodes.png
+images/nodes/ai.png
+images/nodes/api.png
+images/nodes/captioning_nodes.png
+images/nodes/clip.png
+images/nodes/discord.png
+images/nodes/experimental.png
+images/nodes/games.png
+images/nodes/googledrive.png
+images/nodes/gpt_nodes.png
+images/nodes/images_nodes.png
+images/nodes/ksampler_nodes.png
+images/nodes/loaders.png
+images/nodes/math.png
+images/nodes/pDF_nodes.png
+images/nodes/prompting.png
+images/nodes/video.png
+images/nodes/wip.png
+images/nodes/zip.png
+linux_req_install.sh
+nodes/.DS_Store
+nodes/__init__.py
+nodes/ai/FL_Fal_GPTImage2_Edit.py
+nodes/ai/FL_Fal_Gemini_ImageEdit.py
+nodes/ai/FL_Fal_Kling_AIAvatar.py
+nodes/ai/FL_Fal_Kontext.py
+nodes/ai/FL_Fal_Pixverse.py
+nodes/ai/FL_Fal_Pixverse_LipSync.py
+nodes/ai/FL_Fal_Pixverse_Transition.py
+nodes/ai/FL_Fal_SeedVR_Upscale.py
+nodes/ai/FL_Fal_Seedance_i2v.py
+nodes/ai/FL_Fal_Seedream_Edit.py
+nodes/ai/FL_Fal_Sora.py
+nodes/ai/FL_GeminiImageEditor.py
+nodes/ai/FL_GeminiImageGenADV.py
+nodes/ai/FL_GeminiTextAPI.py
+nodes/ai/FL_GeminiVideoCaptioner.py
+nodes/ai/FL_Hedra_API.py
+nodes/ai/FL_PixVerseAPI.py
+nodes/ai/FL_RunwayAct2.py
+nodes/ai/FL_RunwayImageAPI.py
+nodes/ai/FL_VertexGemini25FlashImage.py
+nodes/ai/FL_VertexVeo3.py
+nodes/ai/__init__.py
+nodes/api_tools/FL_API_Base64_ImageLoader.py
+nodes/api_tools/FL_API_ImageSaver.py
+nodes/api_tools/__init__.py
+nodes/audio/FL_AudioFrameCalculator.py
+nodes/audio/FL_Audio_BPM_Analyzer.py
+nodes/audio/FL_Audio_Beat_Visualizer.py
+nodes/audio/FL_Audio_Crop.py
+nodes/audio/FL_Audio_Drum_Detector.py
+nodes/audio/FL_Audio_Envelope_Visualizer.py
+nodes/audio/FL_Audio_Music_Video_Sequencer.py
+nodes/audio/FL_Audio_Reactive_Brightness.py
+nodes/audio/FL_Audio_Reactive_Edge_Glow.py
+nodes/audio/FL_Audio_Reactive_Envelope.py
+nodes/audio/FL_Audio_Reactive_Saturation.py
+nodes/audio/FL_Audio_Reactive_Scale.py
+nodes/audio/FL_Audio_Reactive_Speed.py
+nodes/audio/FL_Audio_Segment_Extractor.py
+nodes/audio/FL_Audio_Separation.py
+nodes/audio/FL_Audio_Shot_Iterator.py
+nodes/audio/__init__.py
+nodes/captioning/FL_CSVExtractor.py
+nodes/captioning/FL_CaptionToCSV.py
+nodes/captioning/FL_Caption_Saver_V2.py
+nodes/captioning/FL_ImageCaptionLayout.py
+nodes/captioning/FL_ImageCaptionLayoutPDF.py
+nodes/captioning/FL_Image_Caption_Saver.py
+nodes/captioning/FL_LoadCSV.py
+nodes/captioning/FL_MirrorAndAppendCaptions.py
+nodes/captioning/FL_OllamaCaptioner.py
+nodes/captioning/FL_SaveCSV.py
+nodes/captioning/FL_Video_Caption_Saver.py
+nodes/captioning/FL_WordFrequencyGraph.py
+nodes/captioning/__init__.py
+nodes/discord/FL_DiscordWebhook.py
+nodes/discord/__init__.py
+nodes/experiments/FL_BatchAligned.py
+nodes/experiments/FL_ColorPicker.py
+nodes/experiments/FL_GradGen.py
+nodes/experiments/FL_NFTGenerator.py
+nodes/experiments/__init__.py
+nodes/file_operations/FL_ZipDirectory.py
+nodes/file_operations/FL_ZipSave.py
+nodes/file_operations/__init__.py
+nodes/film_arch.py
+nodes/games/FL_BulletHellGame.py
+nodes/games/FL_TetrisGame.py
+nodes/games/__init__.py
+nodes/google_drive/FL_GoogleCloudStorage.py
+nodes/google_drive/FL_GoogleDriveDownloader.py
+nodes/google_drive/FL_GoogleDriveImageDownloader.py
+nodes/google_drive/__init__.py
+nodes/gpt/FL_Dalle3.py
+nodes/gpt/FL_GPT_Image1.py
+nodes/gpt/FL_GPT_Image1_ADV.py
+nodes/gpt/FL_GPT_Text.py
+nodes/gpt/FL_GPT_Vision.py
+nodes/gpt/FL_SimpleGPTVision.py
+nodes/gpt/__init__.py
+nodes/hugging_face/FL_HFDatasetDownloader.py
+nodes/hugging_face/FL_HFHubModelUploader.py
+nodes/hugging_face/FL_HF_Character.py
+nodes/hugging_face/FL_HF_UploaderAbsolute.py
+nodes/hugging_face/__init__.py
+nodes/image/FL_AnimeLineExtractor.py
+nodes/image/FL_ApplyMask.py
+nodes/image/FL_BlackFrameReject.py
+nodes/image/FL_CoTracker.py
+nodes/image/FL_CreateShapeImageOnPath.py
+nodes/image/FL_ImageAddNoise.py
+nodes/image/FL_ImageAdjuster.py
+nodes/image/FL_ImageAspectCropper.py
+nodes/image/FL_ImageBatch.py
+nodes/image/FL_ImageBatchListConverter.py
+nodes/image/FL_ImageBatchToGrid.py
+nodes/image/FL_ImageNotes.py
+nodes/image/FL_ImageOverlay.py
+nodes/image/FL_ImagePicker.py
+nodes/image/FL_ImageReplace.py
+nodes/image/FL_ImageSelector.py
+nodes/image/FL_ImageSlicer.py
+nodes/image/FL_ImageToMask.py
+nodes/image/FL_Image_AddToBatch.py
+nodes/image/FL_Image_Blank.py
+nodes/image/FL_Image_Crop.py
+nodes/image/FL_Image_Dimension_Display.py
+nodes/image/FL_Image_Randomizer.py
+nodes/image/FL_LoadImage.py
+nodes/image/FL_PaddingRemover.py
+nodes/image/FL_ReplaceColor.py
+nodes/image/FL_SaveAndDisplayImage.py
+nodes/image/FL_SaveImages.py
+nodes/image/FL_SaveRGBAAnimatedWebP.py
+nodes/image/FL_SaveWebM.py
+nodes/image/FL_SaveWebpImages.py
+nodes/image/__init__.py
+nodes/kartel/FL_KartelJobInput.py
+nodes/kartel/FL_KartelJobOutput.py
+nodes/kartel/FL_KartelParamsParser.py
+nodes/kartel/__init__.py
+nodes/ksamplers/FL_KSamplerXYZPlot.py
+nodes/ksamplers/FL_KsamplerBasic.py
+nodes/ksamplers/FL_KsamplerPlus.py
+nodes/ksamplers/FL_KsamplerPlusV2.py
+nodes/ksamplers/FL_KsamplerSettings.py
+nodes/ksamplers/FL_KsamplerSigma.py
+nodes/ksamplers/FL_SamplerStrings.py
+nodes/ksamplers/FL_SchedulerStrings.py
+nodes/ksamplers/__init__.py
+nodes/loaders/FL_NodeLoader.py
+nodes/loaders/FL_NodePackLoader.py
+nodes/loaders/FL_UpscaleModel.py
+nodes/loaders/__init__.py
+nodes/node_descriptions.json
+nodes/pdf/FL_BulkPDFLoader.py
+nodes/pdf/FL_ImagesToPDF.py
+nodes/pdf/FL_PDFEncryptor.py
+nodes/pdf/FL_PDFImageExtractor.py
+nodes/pdf/FL_PDFLoader.py
+nodes/pdf/FL_PDFMerger.py
+nodes/pdf/FL_PDFSaver.py
+nodes/pdf/FL_PDFTextExtractor.py
+nodes/pdf/FL_PDFToImage.py
+nodes/pdf/FL_TextToPDF.py
+nodes/pdf/__init__.py
+nodes/prompting/FL_MadLibGenerator.py
+nodes/prompting/FL_Prompt.py
+nodes/prompting/FL_PromptMulti.py
+nodes/prompting/FL_PromptSelector.py
+nodes/prompting/FL_PromptSelectorBasic.py
+nodes/prompting/__init__.py
+nodes/rife_arch.py
+nodes/scanner.py
+nodes/sup.py
+nodes/utility/FL_ClipScanner.py
+nodes/utility/FL_DirectoryCrawl.py
+nodes/utility/FL_Float.py
+nodes/utility/FL_InpaintCrop.py
+nodes/utility/FL_JS.py
+nodes/utility/FL_Math.py
+nodes/utility/FL_ModelInspector.py
+nodes/utility/FL_NumberConverter.py
+nodes/utility/FL_Padding.py
+nodes/utility/FL_PasteByMask.py
+nodes/utility/FL_PasteOnCanvas.py
+nodes/utility/FL_PathTypeChecker.py
+nodes/utility/FL_RandomRange.py
+nodes/utility/FL_RandomShapeGenerator.py
+nodes/utility/FL_SD_Slices.py
+nodes/utility/FL_SeparateMasks.py
+nodes/utility/FL_StringToLoraName.py
+nodes/utility/FL_Switch.py
+nodes/utility/FL_Switch_Big.py
+nodes/utility/FL_SystemCheck.py
+nodes/utility/FL_UnloadModel.py
+nodes/utility/FL_VideoCropNStitch.py
+nodes/utility/__init__.py
+nodes/utils.py
+nodes/vfx/FL_Ascii.py
+nodes/vfx/FL_DepthBlur.py
+nodes/vfx/FL_Dither.py
+nodes/vfx/FL_Glitch.py
+nodes/vfx/FL_HalfTone.py
+nodes/vfx/FL_HexagonalPattern.py
+nodes/vfx/FL_ImageCollage.py
+nodes/vfx/FL_Image_Pixelator.py
+nodes/vfx/FL_InfiniteZoom.py
+nodes/vfx/FL_PaperDrawn.py
+nodes/vfx/FL_PixelArt.py
+nodes/vfx/FL_PixelSort.py
+nodes/vfx/FL_RetroEffect.py
+nodes/vfx/FL_Ripple.py
+nodes/vfx/FL_Shader.py
+nodes/vfx/FL_TextOverlay.py
+nodes/vfx/__init__.py
+nodes/video/FL_FILM.py
+nodes/video/FL_ProResVideo.py
+nodes/video/FL_RIFE.py
+nodes/video/FL_VideoBatchSplitter.py
+nodes/video/FL_VideoCadence.py
+nodes/video/FL_VideoCadenceCompile.py
+nodes/video/FL_VideoCrossfade.py
+nodes/video/FL_VideoCut.py
+nodes/video/FL_VideoTrim.py
+nodes/video/__init__.py
+nodes/wip/FL_AnimatedShapePatterns.py
+nodes/wip/FL_KsamplerFractals.py
+nodes/wip/FL_PathAnimator.py
+nodes/wip/FL_QwenImageEditStrength.py
+nodes/wip/FL_TimeLine.py
+nodes/wip/FL_WF_Agent.py
+nodes/wip/FL_WanFirstLastFrameToVideo.py
+nodes/wip/FL_WanVaceToVideoMultiRef.py
+nodes/wip/FL_WanVideoBlender.py
+nodes/wip/FL_WanVideoBlender3Way.py
+nodes/wip/FL_WanVideoContinuationBlender.py
+nodes/wip/FL_WanVideoContinue.py
+nodes/wip/__init__.py
+pyproject.toml
+requirements.txt
+web/.DS_Store
+web/FL_SystemCheck.js
+web/PhotoPea.js
+web/appearance.js
+web/betterCombos.js
+web/nodes/ai/FL_Fal_GPTImage2_Edit.js
+web/nodes/ai/FL_Fal_Kontext.js
+web/nodes/ai/FL_GeminiImageGenADV.js
+web/nodes/experiments/FL_ColorPicker.js
+web/nodes/experiments/GradientImageGenerator.js
+web/nodes/games/FL_BulletHell.js
+web/nodes/games/FL_TetrisGame.js
+web/nodes/google_drive/FL_GoogleDriveImageDownloader.js
+web/nodes/gpt/FL_Dalle3.js
+web/nodes/gpt/FL_GPT_Image1_ADV.js
+web/nodes/image/FL_ImageAdjuster.js
+web/nodes/image/FL_ImageBatch.js
+web/nodes/image/FL_ImageOverlay.js
+web/nodes/image/FL_ImagePicker.js
+web/nodes/image/FL_ImageReplace.js
+web/nodes/image/FL_LoadImage.js
+web/nodes/image/FL_ReplaceColor.js
+web/nodes/image/FL_SaveImages.js
+web/nodes/image/FL_SaveWebpImages.js
+web/nodes/image/SaveAndDisplayImage.js
+web/nodes/ksamplers/FL_KsamplerSigma.js
+web/nodes/loaders/FL_NodeLoader.js
+web/nodes/loaders/FL_NodePackLoader.js
+web/nodes/node_definitions.txt
+web/nodes/node_definitions.txt.bak
+web/nodes/utility/FL_PasteOnCanvas.js
+web/nodes/utility/FL_Switch.js
+web/nodes/utility/FL_Switch_Big.js
+web/nodes/utility/fl_js.js
+web/nodes/vfx/FL_DepthBlur.js
+web/nodes/vfx/FL_PixelArtNode.js
+web/nodes/video/FL_VideoBatchSplitter.js
+web/nodes/wip/FL_PathAnimator.js
+web/nodes/wip/FL_TimeLine.js
+web/nodes/wip/fl_wf_agent.js
+web/widget.js
\ No newline at end of file
diff --git a/comfyui_fill-nodes/README.md b/comfyui_fill-nodes/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..3cb106bf0865711acb017bf1d4dc43f0e0322b91
--- /dev/null
+++ b/comfyui_fill-nodes/README.md
@@ -0,0 +1,539 @@
+# 🏵️ Fill-Nodes
+
+If you enjoy this project, consider supporting me on Patreon!
+
+
+
+
+
+
+Fill-Nodes is a versatile collection of custom nodes for ComfyUI that extends functionality across multiple domains. Features include advanced image processing, visual effects generation, comprehensive file handling (PDF creation/extraction, Google Drive integration), AI model interfaces (GPT, DALL-E, Hugging Face, Runway, Gemini, Fal.ai, and more), utility nodes for workflow enhancement, audio-reactive visual effects, and specialized tools for video processing, captioning, and batch operations. The pack provides both practical workflow solutions and creative tools within a unified node collection.
+
+## 🔍 Table of Contents
+
+
+
+---
+
+
+🖼️ Image Nodes
+
+> *Nodes for manipulating, analyzing, and working with images.*
+
+| Node | Description |
+|------|-------------|
+| `FL_AnimeLineExtractor` | Extracts line art from images using OpenCV's adaptive thresholding and morphological operations. Provides controls for line threshold, line width, detail level, noise reduction via Gaussian blur, and optional output inversion for white backgrounds. |
+| `FL_ApplyMask` | Applies a mask to an image's alpha channel by adding or modifying the alpha channel based on the provided mask. Automatically handles dimension mismatches between image and mask through interpolation and supports batch processing. |
+| `FL_BlackFrameReject` | Filters out images from a batch based on black pixel percentage using configurable threshold and black level detection. Supports multiple detection methods (luminance, average, RGB, all channels) and optional inversion logic, returning filtered images with count statistics. |
+| `FL_ImageAddNoise` | Adds random Gaussian noise to images with controllable strength (0.0-1.0) and seed for reproducible results. Uses torch.randn to generate noise and clips output to valid 0.0-1.0 range. |
+| `FL_ImageAddToBatch` | Combines two image batches into a single batch by concatenating them. Automatically resizes the second batch to match the first batch's dimensions using bicubic or area interpolation based on scaling direction. |
+| `FL_ImageAdjuster` | Adjusts image properties including hue rotation (-180 to 180), saturation, brightness, contrast (all -100 to 100), and sharpness (0 to 100) using PIL's ImageEnhance. Converts to HSV for hue/saturation adjustments and applies UnsharpMask filter for sharpness, with real-time preview sent to the frontend. |
+| `FL_ImageAspectCropper` | Crops images to a target aspect ratio (specified as width:height) by center-cropping either width or height as needed. Ensures resulting dimensions are even numbers for compatibility with video codecs. |
+| `FL_ImageBatch` | Dynamically combines multiple images into a single batch with configurable number of inputs (2-100). Uses ComfyUI's ImageBatch node internally and automatically resizes images to match the first image's dimensions. |
+| `FL_ImageBatchToGrid` | Arranges a batch of images into a grid layout with a specified number of images per row. Creates a single composite image with black background filling any empty grid positions. |
+| `FL_ImageBlank` | Creates a blank image with specified width, height, and RGB color values. Generates a solid color image as a tensor suitable for use in ComfyUI workflows. |
+| `FL_ImageCrop` | Crops images from specified directions (top, bottom, left, right, or combinations) by a specified pixel amount. Automatically validates crop amounts to prevent exceeding image dimensions. |
+| `FL_ImageDimensionDisplay` | Extracts and returns the width and height dimensions of an input image as a formatted string. Supports both tensor and PIL image formats. |
+| `FL_ImageListToImageBatch` | Converts a list of individual images into a single batched image tensor. Automatically resizes images to match the first image's dimensions using Lanczos interpolation if needed. |
+| `FL_ImageNotes` | Adds a text bar with custom text to images, positioned at top or bottom. Supports configurable bar height, text size, borders, and optional word wrapping with automatic height adjustment to fit wrapped text. |
+| `FL_ImageRandomizer` | Randomly selects an image or video from a specified directory based on a seed value (using modulo operation for deterministic selection). Supports subdirectory searching and returns the selected media as a batch along with the file path and filename. |
+| `FL_ImageSelector` | Selects specific images from a batch using comma-separated indices or the 'last' keyword. Returns a new batch containing only the specified images in the order they were listed. |
+| `FL_ImageSlicer` | Divides an image into a grid of equally-sized rectangular slices based on x and y subdivision counts. Returns all slices as a batch of images, processing from left-to-right, top-to-bottom. |
+| `FL_LoadImage` | Provides a file browser interface for loading images from a custom directory structure with server-side API endpoints. Converts RGBA images to RGB with white background compositing and handles various image formats. |
+| `FL_PaddingRemover` | Detects and removes uniform padding from images by analyzing edge colors and their consistency across rows and columns. Supports CPU and GPU processing modes, configurable tolerance, minimum content size constraints, and additional manual trimming options with optional debug visualization. |
+| `FL_ReplaceColor` | Replaces pixels of a specific source color with a target color using Euclidean distance in RGB space and configurable tolerance. Supports morphological operations (expand/contract) to dilate or erode the replacement area using circular kernels. |
+| `FL_SaveImages` | Saves images to a custom folder structure with templated filenames and automatic index incrementing to avoid overwriting. Supports optional metadata saving as separate text files alongside images. |
+| `FL_SaveRGBAAnimatedWebP` | Saves animated WebP files from separate RGB and alpha channel image batches with configurable FPS, quality, and encoding method. Creates a preview with checkerboard background for transparency visualization and exports both the WebP animation and a ZIP file containing individual PNG frames with alpha. |
+| `FL_SaveWebM` | Exports image batches as WebM video files using VP9 codec with configurable FPS, quality, and optional alpha channel preservation. Uses imageio with ffmpeg backend and includes fallback handling for encoding errors. |
+
+### 📷 Screenshots & Examples
+
+
+
+
+
+---
+
+
+📝 Captioning Nodes
+
+> *Nodes for generating, saving, and manipulating image and video captions.*
+
+| Node | Description |
+|------|-------------|
+| `FL_CSVExtractor` | Extracts a specific column value from a randomly selected CSV row using a seed-based selection mechanism, supporting header skipping and returning the extracted text, row number, and full row data. Uses modulo-based pseudo-random selection for reproducible results. |
+| `FL_CaptionSaver_V2` | Advanced caption saver supporting both image tensor input and directory input modes with single or multiple caption options, optional mask image saving, and configurable downsize factors. Provides flexible caption assignment with automatic list extension/truncation and unique filename generation when overwrite is disabled. |
+| `FL_CaptionToCSV` | Scans an image directory and creates an in-memory CSV mapping image filenames to their corresponding caption text files. Returns CSV data as UTF-8 encoded bytes containing image_file and caption columns. |
+| `FL_ImageCaptionLayout` | Creates a visual grid layout combining images with their caption files from a directory, generating a single composite image with configurable rows, image sizes, padding, and caption boxes. Returns a PyTorch tensor suitable for display in ComfyUI. |
+| `FL_ImageCaptionLayoutPDF` | Generates both a PDF document and an image preview displaying a grid of images with captions from a directory, supporting pagination for multiple pages with configurable layout dimensions, orientation, and font settings. Uses ReportLab for PDF generation and PIL for image preview creation. |
+| `FL_ImageCaptionSaver` | Saves a batch of images and their associated caption text to a specified folder, sanitizing captions by removing special characters and supporting optional file overwrite prevention. Handles tensor-to-image conversion with automatic grayscale-to-RGB conversion and proper value normalization. |
+| `FL_LoadCSV` | Loads a CSV file from disk and returns both the raw binary data and row count for use in other nodes. Validates file existence, extension, and provides modification time tracking for cache invalidation. |
+| `FL_MirrorAndAppendCaptions` | Processes images in a directory by appending frame numbers to captions and optionally creating horizontally mirrored duplicates with sequential frame numbering. Supports prepending or appending custom text to captions and saves both original and mirrored versions back to the directory. |
+| `FL_OllamaCaptioner` | Generates image captions using Ollama LLM by encoding images as base64 and sending them to a local Ollama server for description generation. Saves images with either AI-generated or default captions, supporting custom model selection and URL configuration. |
+| `FL_SaveCSV` | Writes CSV data (received as bytes) to a specified file path, automatically creating output directories and ensuring proper .csv extension. Provides file writing with error handling and console logging for save confirmation. |
+| `FL_VideoCaptionSaver` | Converts a sequence of image tensors into a video file (MP4 or AVI) using OpenCV with configurable FPS and quality settings, while saving an associated caption text file. Handles RGB-to-BGR conversion, frame processing with progress tracking, and supports overwrite prevention. |
+| `FL_WordFrequencyGraph` | Analyzes all text files in a directory to generate a horizontal bar graph visualization of word frequency statistics with customizable color schemes, word filtering options, and configurable output dimensions. Excludes common stop words and produces a dark-themed matplotlib graph as a PyTorch tensor. |
+
+### 📷 Screenshots & Examples
+
+
+
+
+
+---
+
+
+✨ VFX Nodes
+
+> *Nodes for applying visual effects to images.*
+
+| Node | Description |
+|------|-------------|
+| `FL_Ascii` | Converts images to ASCII art by sampling pixels at regular intervals and mapping them to custom character sets, with options for sequential or brightness-based character selection, configurable spacing, font, and font size. |
+| `FL_Dither` | Applies various dithering algorithms (Floyd-Steinberg, Random, Ordered, Bayer) to reduce images to a specified number of colors, creating retro-style color quantization effects with configurable color palette sizes from 2-256 colors. |
+| `FL_Glitch` | Creates digital glitch effects using the glitch_this library with controllable glitch intensity and optional RGB color channel offset, applying effects both horizontally and vertically by rotating the image 90 degrees during processing. |
+| `FL_HalftonePattern` | Generates halftone dot patterns by converting images to grayscale and creating circular dots of varying sizes based on region brightness, with configurable dot size and spacing parameters for newspaper-print style effects. |
+| `FL_HexagonalPattern` | Creates mosaic-style images by tiling hexagonal crops of the input with configurable shadow effects, background color, rotation, and spacing using PIL's polygon drawing capabilities. |
+| `FL_ImageCollage` | Generates photomosaics by tiling a template image across the base image, colorizing each tile based on the average color of the corresponding base region, with configurable tile size and spacing. |
+| `FL_ImagePixelator` | Applies pixelation effects with morphological gradient edge detection using Kornia, featuring configurable scale factor, kernel size, and sine-wave modulation for animated pixelation intensity across image sequences. |
+| `FL_InfiniteZoom` | Produces infinite zoom/droste effects using OpenGL shaders with GLFW, supporting configurable scale, mirror/swirl parameters, iteration count, and animation speed to create recursive visual patterns. |
+| `FL_PaperDrawn` | Simulates hand-drawn sketch effects using OpenGL fragment shaders that apply directional gradient analysis with configurable angle count, sampling density, line width, and vignette strength to create pencil-drawn aesthetics. |
+| `FL_PixelArtShader` | Creates pixel art effects by downsampling images with nearest-neighbor interpolation, applying color quantization, and optionally mapping to extracted color palettes using K-means clustering with mask support. |
+| `FL_PixelSort` | Implements pixel sorting effects based on HSV saturation values, sorting pixels within detected edge intervals either horizontally or vertically with configurable threshold, smoothing, and rotation parameters. |
+| `FL_RetroEffect` | Creates vintage CRT monitor effects by applying RGB color channel offset, scanline overlay, radial vignette with gaussian blur, and random noise blending using PIL image processing techniques. |
+| `FL_Ripple` | Generates radial ripple/wave distortion effects using sinusoidal displacement mapping based on distance from a configurable center point, with adjustable amplitude, frequency, phase, and optional sine-wave modulation. |
+| `FL_Shadertoy` | Renders Shadertoy-compatible GLSL shaders using OpenGL with support for up to 4 input image channels, iResolution/iTime/iFrame uniforms, and configurable frame count/FPS for shader-based generative effects. |
+| `FL_TextOverlayNode` | Overlays customizable text on images with support for TrueType fonts (system or local), configurable RGB color, percentage-based positioning, multiple anchor points (9 positions), and multiline text rendering using PIL ImageDraw. |
+
+### 📷 Screenshots & Examples
+
+
+
+
+
+---
+
+
+🛠️ Utility Nodes
+
+> *General utility nodes for various tasks.*
+
+| Node | Description |
+|------|-------------|
+| `FL_ClipScanner` | Tokenizes text prompts using OpenCLIP tokenizers for different model types (SDXL ViT-G/14, SD 1.5 ViT-L/14, FLUX ViT-L/14) and displays detailed token analysis including token count and decoded output. |
+| `FL_CodeNode` | Executes arbitrary Python code provided as string input or loaded from file, with four generic output slots and dynamic input support via inputs/outputs dictionaries for custom algorithm integration. |
+| `FL_DirectoryCrawl` | Recursively crawls directories to batch-load images or text files with progress tracking, returning images as both batched tensors (padded) and individual image lists for flexible processing. |
+| `FL_Float` | Outputs a float value rounded to 2 decimal places, serving as a simple float constant provider for workflows. |
+| `FL_InpaintCrop` | Crops images based on mask bounding boxes with multiple sizing modes (free, forced, range, long/short side) including context expansion, optional hole filling (CPU/GPU), and generates stitch data for recomposition. |
+| `FL_Inpaint_Stitch` | Stitches inpainted images back into their original positions using crop data from FL_InpaintCrop, handling rescaling and alpha compositing to blend processed regions seamlessly. |
+| `FL_JS` | Executes custom JavaScript code in response to ComfyUI workflow events (before_queued, after_queued, executing, executed, etc.) for client-side scripting integration. |
+| `FL_Math` | Evaluates mathematical expressions with up to three variables (A, B, C) using safe AST parsing, supporting basic arithmetic operators (add, subtract, multiply, divide, power) and returning both integer and float results. |
+| `FL_ModelInspector` | Inspects PyTorch checkpoint files (.ckpt, .safetensors) and extracts comprehensive information including parameter count, layer shapes, architecture analysis, and model structure with support for various loading methods and fallback mechanisms. |
+| `FL_Padding` | Adds customizable padding to images on all four sides with configurable RGB color, optional alpha channel, and proper tensor handling for batched processing. |
+| `FL_PasteByMask` | Pastes images onto base images at mask locations with advanced features including multiple resize behaviors (resize, keep_ratio_fill/fit, source_size), blend modes (normal, multiply, screen, overlay, etc.), feathering, and mask mapping support for batch processing. |
+| `FL_PasteOnCanvas` | Pastes and centers masked images onto a canvas of specified dimensions with optional background color/image, supporting multiple resize algorithms (bilinear, nearest, bicubic, lanczos), padding, and alpha channel handling. |
+| `FL_PathTypeChecker` | Analyzes file path strings to determine their type (absolute, relative, UNC, URL-like, drive-specific) with validation and classification logic. |
+| `FL_RandomNumber` | Generates random integer and float values within specified ranges using seed-based reproducibility, with automatic seed generation when seed is 0. |
+| `FL_SDUltimate_Slices` | Calculates slice dimensions for SD Ultimate upscaling by dividing images into configurable grid patterns (1x1 to 4x4) with multiplier support for slice size adjustment. |
+| `FL_SeparateMaskComponents` | Separates multi-component masks into individual connected components using OpenCV's connected component labeling, returning separated masks and a mapping tensor for batch tracking. |
+| `FL_Switch` | Implements lazy-evaluated boolean switch that evaluates and returns either on_true or on_false input based on switch value, enabling conditional workflow execution without evaluating unused branches. |
+| `FL_Switch_Big` | Implements lazy-evaluated multi-case switch logic (5 cases + default) by comparing a switch condition against case strings and evaluating only the matched input path for conditional workflow branching. |
+| `FL_SystemCheck` | Gathers and exposes system information including Python version, OS, CPU, RAM, GPU, library versions (PyTorch, transformers, etc.), and environment variables via an HTTP endpoint. |
+| `FL_UnloadModel` | Removes models from memory and clears CUDA cache by unloading specified models from ComfyUI's model management system, with passthrough capability for workflow continuity. |
+| `FL_VideoCropMask` | Crops video frames based on mask bounding boxes with temporal smoothing, maintaining aspect ratio and optionally applying padding, returning cropped video, mask, and crop data for each frame. |
+| `FL_VideoRecompose` | Replaces cropped regions back into original video frames using crop data from FL_VideoCropMask, resizing processed frames to match original crop dimensions. |
+
+### 📷 Screenshots & Examples
+
+
+
+
+
+---
+
+
+🎲 KSamplers Nodes
+
+> *Nodes for sampling in the generation process.*
+
+| Node | Description |
+|------|-------------|
+| `FL_KSamplerXYZPlot` | Grid comparison sampler that generates parameter sweep visualizations by iterating over X/Y axis values (steps, CFG, denoise, sampler, or scheduler) with optional Z-axis stacking (vertical/horizontal), producing labeled image grids with axes and parameter annotations for systematic parameter testing. |
+| `FL_KsamplerBasic` | Simplified sampler node that accepts either latent or image input (with VAE encoding), performs standard KSampler operations with configurable steps/CFG/sampler/scheduler/denoise parameters, and outputs both latent and decoded image results. |
+| `FL_KsamplerPlus` | Advanced tiled sampler that divides latent or image inputs into overlapping grid slices (configurable X/Y slices and overlap), processes each tile with optional region-specific conditioning (including ControlNet cropping), and blends results using cosine-weighted masks to eliminate seams. |
+| `FL_KsamplerPlusV2` | Enhanced version of FL_KsamplerPlus with additional features including user-configurable conditioning strength multiplier, complete conditioning split across tiles (including pooled outputs and tensor-based conditioning), batch processing support for sliced conditioning, and optional debug information output. |
+| `FL_KsamplerSettings` | Configuration node that outputs sampling parameters including aspect ratio dimensions (SD/XL/SVD presets with landscape/portrait rotation), batch size, two-pass step counts, CFG scales, denoise strength, scale factor, and sampler/scheduler selection. |
+| `FL_SamplerStrings` | String generator node with boolean toggles for 27 sampler types (euler, dpm, heun, ddim, etc.) that outputs a comma-separated string of selected sampler names for batch processing workflows. |
+| `FL_SchedulerStrings` | String generator node with boolean toggles for 7 scheduler types (normal, karras, exponential, sgm_uniform, simple, ddim_uniform, beta) that outputs a comma-separated string of selected scheduler names for batch processing workflows. |
+
+### 📷 Screenshots & Examples
+
+
+
+
+
+---
+
+
+📄 PDF Nodes
+
+> *Nodes for working with PDF files.*
+
+| Node | Description |
+|------|-------------|
+| `FL_BulkPDFLoader` | Loads all PDF files from a specified directory path and returns them as a list of PDF data objects containing file metadata (path, filename, page count) and binary content. Validates that PDFs exist and can be read, collecting errors for any failed loads. |
+| `FL_ImagesToPDF` | Converts ComfyUI image tensors into a single PDF document with configurable DPI and page size (A4/Letter/Legal), automatically scaling and centering each image to fit the page while maintaining aspect ratio. Returns an in-memory PDF data object. |
+| `FL_PDFEncryptor` | Encrypts a PDF with user and owner passwords using PyPDF2, supporting 40-bit or 128-bit encryption with granular permission controls (printing, copying, commenting, form filling, assembly, content extraction). Returns an encrypted in-memory PDF data object. |
+| `FL_PDFImageExtractor` | Extracts embedded images from PDF pages that meet minimum width/height thresholds, handling multiple compression formats (DCTDecode/JPEG, FlateDecode/PNG, JPXDecode/JPEG2000, LZWDecode). Returns extracted images as normalized PyTorch tensors in batch format [B, H, W, C]. |
+| `FL_PDFLoader` | Loads a single PDF file from a specified file path and returns it as a PDF data object containing the file path, page count, and binary content. Validates file existence and PDF format before loading. |
+| `FL_PDFMerger` | Merges two PDF data objects into a single combined PDF using PyPDF2's PdfMerger, appending the second PDF after the first. Returns the merged PDF as an in-memory data object with total page count. |
+| `FL_PDFSaver` | Saves a PDF data object to disk at a specified directory path with a given filename, automatically creating the output directory if needed and appending '.pdf' extension if not present. Returns the full output file path. |
+| `FL_PDFTextExtractor` | Extracts all text content from a PDF document by iterating through pages using PyPDF2's text extraction, combining text from all pages with double newlines as page separators. Returns the extracted text as a single string. |
+| `FL_PDFToImages` | Converts PDF pages to images using PyMuPDF (fitz) with configurable DPI resolution, supporting both single PDFs and lists of PDFs. Returns all pages as normalized PyTorch image tensors concatenated into a single batch. |
+| `FL_TextToPDF` | Generates a PDF document from plain text input using ReportLab canvas, with configurable page size, font size, margins, and title, automatically handling text wrapping and pagination. Returns an in-memory PDF data object with calculated page count. |
+
+### 📷 Screenshots & Examples
+
+
+
+
+
+---
+
+
+🤖 GPT Nodes
+
+> *Nodes for integrating with GPT and OpenAI models.*
+
+| Node | Description |
+|------|-------------|
+| `FL_Dalle3` | Generates images using OpenAI's DALL-E 3 model with asynchronous batch processing, caching results based on parameters to avoid redundant API calls, and returns image tensors along with revised prompts. Supports auto-save functionality with metadata JSON files and configurable retry logic for API failures. |
+| `FL_GPT_Image1` | Generates or edits images using OpenAI's gpt-image-1 model with support for batch generation, image editing with optional masks, and comprehensive error handling that creates error images with visual text feedback. Implements retry logic, multipart form-data for edits endpoint, and processes both base64 and URL-based image responses. |
+| `FL_GPT_Image1_ADV` | Advanced multi-input variant that generates multiple images concurrently using OpenAI's gpt-image-1 model by processing up to 100 prompts with individual image inputs for editing in parallel using async/await and thread pool execution. Each input slot can have its own prompt and optional image, with all outputs combined into a batched tensor and detailed per-call response logs. |
+| `FL_GPT_Text` | Makes synchronous API calls to OpenAI's GPT models (GPT-4, GPT-3.5-turbo) for text completion with full parameter control including temperature, top_p, and frequency/presence penalties. Optionally saves responses to file and falls back to environment variable for API key if not provided. |
+| `FL_GPT_Vision` | Batch processes images using OpenAI's GPT-4 Vision models to generate captions asynchronously with configurable batch sizes, supporting both input directories and image tensors, and saves captions to text files alongside images. Retrieves API key from environment variable OPENAI_API_KEY. |
+| `FL_SimpleGPTVision` | Sends a single image to OpenAI's GPT-4 Vision API to generate a text caption based on configurable system and user prompts, with built-in rate limiting retry logic using exponential backoff. Returns the generated caption as a string output. |
+
+### 📷 Screenshots & Examples
+
+
+
+
+
+---
+
+
+🧠 AI Nodes
+
+> *Nodes that integrate with various AI models and services.*
+
+| Node | Description |
+|------|-------------|
+| `FL_Fal_Gemini_ImageEdit` | Edits up to 5 input images using Fal AI Gemini 2.5 Flash Image Edit API with multimodal prompt support, async processing, and automatic image URL generation. Returns edited images with URLs and description. |
+| `FL_Fal_Kling_AIAvatar` | Generates AI avatar videos using Fal AI Kling Video API by combining input image with audio tensor or image sequence, with optional text prompt refinement. Returns extracted video frames and original audio. |
+| `FL_Fal_Kontext` | Edits images using Fal AI Flux Pro Kontext API with multi-image input support (batching), asynchronous parallel processing, and configurable parameters including aspect ratio and safety tolerance. Returns batched edited images from multiple API calls. |
+| `FL_Fal_Pixverse` | Generates videos from single image using Fal AI Pixverse v5 Image-to-Video API with style presets, camera movements, and parallel batch processing (up to 5). Returns extracted frames from generated videos as tensors. |
+| `FL_Fal_Pixverse_LipSync` | Generates lip-sync videos using Fal AI Pixverse LipSync API supporting both audio input and text-to-speech modes with voice selection, processing video frames tensor with audio synchronization. Returns lip-synced video frames and audio. |
+| `FL_Fal_Pixverse_Transition` | Creates transition videos between two images using Fal AI Pixverse v5 Transition API with configurable resolution, aspect ratio, and duration. Returns extracted frames from generated transition videos. |
+| `FL_Fal_Seedance_i2v` | Generates videos from single image using Fal AI ByteDance Seedance v1 Pro Image-to-Video API with support for multi-segment prompts using [cut] markers, configurable resolution, duration, and camera settings. Returns all extracted frames from generated video. |
+| `FL_Fal_Seedream_Edit` | Edits up to 10 images using Fal AI ByteDance Seedream v4 Edit API with custom or preset image sizes, auto-scaling to meet minimum dimensions while preserving aspect ratio. Returns edited images with URLs and seed information. |
+| `FL_Fal_Sora` | Generates videos using Fal AI Sora 2 API supporting both text-to-video and image-to-video modes with optional OpenAI API key pass-through, automatic endpoint selection based on PRO mode, and audio extraction. Returns video frames, audio waveform, video URL, and status message. |
+| `FL_GeminiImageEditor` | Generates or edits images using Google Gemini 2.5 Flash Image API with support for up to 4 reference images, batch generation with parallel async processing, and optional square padding. Returns list of generated images with detailed API response logs. |
+| `FL_GeminiImageGenADV` | Advanced multi-input image generation using Google Gemini with dynamic input count (1-100), async parallel batch processing, and per-input prompt/image pairs. Returns list of generated images based on variable number of input slots. |
+| `FL_GeminiTextAPI` | Generates text responses using Google Gemini models (2.5/2.0/1.5 variants) with configurable temperature, token limits, and optional system instructions. Returns raw text output without additional formatting. |
+| `FL_GeminiVideoCaptioner` | Generates detailed captions for videos or image sequences using Google Gemini API, with automatic WebM conversion for API compatibility, frame extraction at configurable FPS, and support for audio processing. Returns caption text and sample frame from video. |
+| `FL_Hedra_API` | Generates videos from image, audio file, and text prompt using Hedra API with configurable aspect ratio and resolution, automatic polling for generation completion, and frame extraction from downloaded video. Returns video frames tensor with processing logs. |
+| `FL_HunyuanDelight` | Processes images using Hunyuan3D-2 model via Stable Diffusion InstructPix2Pix pipeline with configurable CFG, steps, and iterative refinement loops. Downloads the model from HuggingFace and applies image-to-image transformations without text prompts. |
+| `FL_PixVerseAPI` | Generates videos from images using PixVerse API with support for standard image-to-video and transition modes, parallel batch processing with configurable seeds, and automatic frame extraction from generated MP4 videos. Returns up to 5 batches of extracted frames as tensors. |
+| `FL_RunwayAct2` | Generates character performance videos using RunwayML Act Two API from input character images/videos and reference videos, with controls for body movement and expression intensity. Returns extracted video frames as tensors. |
+| `FL_RunwayImageAPI` | Generates images using RunwayML Gen4 Image API with support for up to 3 reference images with custom tags, configurable generation parameters, and automatic polling for task completion. Returns generated image tensor and detailed status logs. |
+| `FL_Veo3VideoGen` | Generates videos using Google Vertex AI Veo 3.0 models with service account authentication, optional reference image input, configurable aspect ratio/resolution, and automatic polling with frame extraction. Returns extracted video frames, video path, and processing logs. |
+| `FL_VertexGemini25FlashImage` | Generates images using Google Vertex AI Gemini 2.5 Flash Image model with service account authentication, support for up to 3 reference images, and parallel batch generation. Returns batch tensor of generated images with detailed processing logs. |
+
+### 📷 Screenshots & Examples
+
+
+
+
+
+---
+
+
+🔊 Audio Nodes
+
+> *Nodes for audio analysis, processing, and audio-reactive visual effects.*
+
+| Node | Description |
+|------|-------------|
+| `FL_Audio_BPM_Analyzer` | Analyzes audio using librosa to detect BPM and beat positions, with options for two BPM calculation methods (beat_intervals or onset_strength), beat offset adjustment, and automatic beat filling to cover the entire audio duration. Outputs beat positions as JSON with visualization. |
+| `FL_Audio_Beat_Visualizer` | Generates video frames that visualize beat patterns by either alternating between black/white on beat changes or cycling through provided images, with configurable frame dimensions and starting color. |
+| `FL_Audio_Crop` | Crops audio waveforms to specified start and end times using MM:SS or seconds format, with automatic clamping to valid audio boundaries. |
+| `FL_Audio_Drum_Detector` | Detects kicks, snares, and hi-hats from audio using librosa onset detection with frequency band analysis (kicks: 30-300Hz, snares: 150-400Hz + 4-10kHz noise, hi-hats: 6kHz+) and adjustable sensitivity thresholds. |
+| `FL_Audio_Envelope_Visualizer` | Visualizes audio envelopes as grayscale video frames where pixel intensity corresponds to envelope values, with configurable intensity multiplier and optional color inversion. |
+| `FL_Audio_Music_Video_Sequencer` | Generates complete music video shot sequences from beat positions using pattern-based orchestration (A/B/C/D patterns with configurable beat counts), creating drift-free frame boundaries and detailed metadata for each shot including time, beat, and sample boundaries. |
+| `FL_Audio_Reactive_Brightness` | Multiplies frame pixel values by brightness factors calculated from audio envelopes, with configurable base brightness, intensity scaling, optional inversion, and output clamping. |
+| `FL_Audio_Reactive_Edge_Glow` | Applies audio-reactive edge detection using Sobel operators (or accepts pre-computed edge frames) and adds colored glow effects that pulse with envelope values, supporting multiple blend modes (add, screen, overlay) and glow colors. |
+| `FL_Audio_Reactive_Envelope` | Generates per-frame ADSR envelopes (Attack, Decay, Sustain, Release) from drum detection times (kicks, snares, hi-hats) with independent configurable envelope parameters for each drum type. |
+| `FL_Audio_Reactive_Saturation` | Adjusts color saturation by blending between grayscale (using Rec. 709 luma coefficients) and original frames based on envelope-modulated saturation values, supporting both saturation and desaturation effects. |
+| `FL_Audio_Reactive_Scale` | Applies audio-reactive zoom/scale effects to frames based on envelope values, with center-cropping or padding to maintain dimensions and configurable interpolation modes (bilinear, bicubic, nearest). |
+| `FL_Audio_Reactive_Speed` | Time-remaps frames using cumulative speed multipliers derived from audio envelopes, allowing for dynamic speed-up/slow-down effects with frame interpolation and optional envelope inversion. |
+| `FL_Audio_Segment_Extractor` | Extracts audio segments based on pre-analyzed beat positions from the BPM analyzer, supporting drift-free frame alignment by using cumulative time mapping and outputting precise frame counts for video synchronization. |
+| `FL_Audio_Separation` | Separates audio into four stems (bass, drums, other, vocals) using the Hybrid Demucs model from torchaudio, with chunked processing to manage memory usage and configurable overlap/fade parameters. |
+| `FL_Audio_Shot_Iterator` | Extracts individual shot metadata (frame counts, beat ranges, time boundaries) from music video sequence JSON by shot index, designed for iterative processing of video sequences. |
+
+### 📷 Screenshots & Examples
+
+
+
+
+
+---
+
+
+🧪 Experimental Nodes
+
+> *Experimental nodes with various functionalities.*
+
+| Node | Description |
+|------|-------------|
+| `FL_BatchAlign` | Patches a model to enable batch-aligned generation by applying style alignment techniques through shared attention mechanisms and normalization layers. Uses adaptive instance normalization (AdaIN) on queries, keys, and values with configurable attention sharing and normalization strategies (group/layer/both). |
+| `FL_ColorPicker` | A simple utility node that accepts a hex color string input and passes it through as output, designed to facilitate color selection in workflows. |
+| `FL_GradGenerator` | Generates gradient images from a JSON-formatted color stops specification with position and color values. Supports RGB/HSV color modes and multiple interpolation curves (Linear, Ease In, Ease Out, Ease In-Out) with configurable dimensions. |
+| `FL_NFTGenerator` | Randomly selects images from a directory based on rarity percentages encoded in filenames (format: name-XXXper-val), using weighted probability selection with a configurable seed. Returns both the selected image and its corresponding mask file (or blank mask if not found). |
+
+### 📷 Screenshots & Examples
+
+
+
+
+
+---
+
+
+💬 Prompting Nodes
+
+> *Nodes for generating and manipulating prompts.*
+
+| Node | Description |
+|------|-------------|
+| `FL_MadLibGenerator` | Generates text by replacing up to 5 different delimiter patterns in a template with randomly selected words from corresponding word lists. Uses per-list seeding with MD5 hashing to ensure reproducible but independent randomization for each delimiter. |
+| `FL_PromptBasic` | Concatenates three text strings (prepend, prompt, append) without adding any spaces, preserving user-specified formatting for prompt construction. |
+| `FL_PromptMulti` | Processes multi-line positive and negative prompts into parallel lists, automatically balancing counts by repeating the last prompt or using empty strings. Generates indexed names with configurable prefix and outputs as lists for batch processing. |
+| `FL_PromptSelector` | Selects a single prompt line by index from a multi-line prompt string, optionally prepending and appending text with automatic space insertion. |
+
+### 📷 Screenshots & Examples
+
+
+
+
+
+---
+
+
+📂 File Operation Nodes
+
+> *Nodes for file operations.*
+
+| Node | Description |
+|------|-------------|
+| `FL_ZipDirectory` | Creates a ZIP archive of an entire directory structure in memory using ZIP_DEFLATED compression, returning the raw bytes without writing to disk. |
+| `FL_ZipSave` | Compresses a directory into a ZIP file and saves it to a specified output location with automatic filename collision handling via timestamp suffixing. |
+
+### 📷 Screenshots & Examples
+
+
+
+
+
+---
+
+
+☁️ Google Drive Nodes
+
+> *Nodes for Google Cloud services integration.*
+
+| Node | Description |
+|------|-------------|
+| `FL_GoogleCloudStorage` | Uploads images or compiled videos to Google Cloud Storage buckets using service account credentials. Supports batch image uploads, video compilation with configurable codecs/FPS, public/private access control, and custom metadata attachment. |
+| `FL_GoogleDriveDownloader` | Downloads files from Google Drive using share links, automatically extracts ZIP archives, and manages output in organized directory structures with cleanup of temporary files. |
+| `FL_GoogleDriveImageDownloader` | Downloads images from Google Drive share links with optional local caching system using MD5-hashed index. Converts downloaded images to RGB tensors normalized to [0,1] range with configurable cache behavior. |
+
+### 📷 Screenshots & Examples
+
+
+
+
+
+---
+
+
+
+
+> *Nodes for API interactions.*
+
+| Node | Description |
+|------|-------------|
+| `FL_API_Base64_ImageLoader` | Decodes base64-encoded images (with automatic data URL prefix removal) and converts them to ComfyUI image tensors. Supports optional resizing with aspect ratio preservation and returns image tensor with dimensions, job_id, user_id, and category. |
+| `FL_API_ImageSaver` | Saves images to a categorized directory structure (base/category/user_id/job_id.format) with support for PNG, JPG, JPEG, and WebP formats and configurable quality settings. Returns full path, job_id, user_id, and category for API workflows. |
+
+### 📷 Screenshots & Examples
+
+
+
+
+
+---
+
+
+🤗 Hugging Face Nodes
+
+> *Nodes for integrating with Hugging Face.*
+
+| Node | Description |
+|------|-------------|
+| `FL_HFDatasetDownloader` | Downloads Hugging Face repositories (datasets, models, or spaces) using snapshot_download with configurable parallel workers and local directory specification. |
+| `FL_HFHubModelUploader` | Uploads models and assets to Hugging Face Hub with automatic README generation, model card header support, and organized file structure. Handles images, ZIP files, and large model files with threaded progress tracking and retry logic. |
+| `FL_HF_Character` | Uploads character-related assets (LoRA, datasets, captions, CSVs) to Hugging Face Hub using a structured path format (studio/project/character) for organized character library management. |
+| `FL_HF_UploaderAbsolute` | Uploads various file types (LoRA files, ZIP datasets, images, PDFs, CSVs) to Hugging Face repositories at specified paths with progress tracking. Supports repository creation and uses environment variable HUGGINGFACE_API_KEY for authentication. |
+
+### 📷 Screenshots & Examples
+
+
+
+
+
+---
+
+
+⏬ Loader Nodes
+
+> *Nodes for loading various resources.*
+
+| Node | Description |
+|------|-------------|
+| `FL_NodeLoader` | A pass-through node that accepts and returns a TRIGGER type, designed for node dependency management in workflows. |
+| `FL_NodePackLoader` | A pass-through node with IS_CHANGED set to float('NaN') to ensure it always processes when triggered, useful for forcing workflow execution. |
+| `FL_UpscaleModel` | Upscales images in configurable batches using loaded upscale models with precision control (auto/32/16/bfloat16), optional downscaling by factor, multiple rescale methods (nearest-exact, bilinear, area, bicubic, lanczos), and TQDM progress tracking. |
+
+### 📷 Screenshots & Examples
+
+
+
+
+
+---
+
+
+💬 Discord Nodes
+
+> *Nodes for Discord integration.*
+
+| Node | Description |
+|------|-------------|
+| `FL_SendToDiscordWebhook` | Sends single images or video compilations to Discord via webhooks with configurable bot username, custom messages, user mentions (via Discord user IDs), FPS control for videos, and optional local file retention. |
+
+### 📷 Screenshots & Examples
+
+
+
+
+
+---
+
+
+🚧 Work-in-Progress Nodes
+
+> *Nodes that are still in development.*
+
+| Node | Description |
+|------|-------------|
+| `FL_FractalKSampler` | Experimental recursive K-sampler that generates images through fractal upscaling and slicing. Upscales latents, divides into 4 quadrants, recursively samples each with reduced denoise, and composites results with configurable blend factors. |
+| `FL_TimeLine` | Work-in-progress timeline processor node for video animation with IPAdapter preset selection, dimension control, interpolation modes, and frame/FPS settings. Includes API endpoint for timeline data but currently returns model unchanged. |
+| `FL_WF_Agent` | Workflow agent node that executes a node scanner to generate cached node definitions for AI-assisted workflow manipulation. Runs scanner as subprocess and provides feedback on cache file creation and status. |
+| `FL_WanFirstLastFrameToVideo` | Enhanced WAN (Warp and Noise) implementation for video generation from first and last frames with advanced timing control. Supports custom keyframe positioning, temporal interpolation curves (linear, ease, bounce), regional masking, and CLIP vision conditioning. |
+
+### 📷 Screenshots & Examples
+
+
+
+
+
+---
+
+
+🎮 Game Nodes
+
+> *Nodes implementing games.*
+
+| Node | Description |
+|------|-------------|
+| `FL_BulletHellGame` | Placeholder game node with no implementation, designed as a stub for future bullet hell game functionality. |
+| `FL_TetrisGame` | Placeholder game node with no implementation, designed as a stub for future Tetris game functionality. |
+
+### 📷 Screenshots & Examples
+
+
+
+
+
+---
+
+
+🎬 Video Nodes
+
+> *Nodes for video processing and frame interpolation.*
+
+| Node | Description |
+|------|-------------|
+| `FL_FILM` | Frame interpolation using FILM (Frame Interpolation for Large Motion) from Google Research. Downloads TorchScript model from HuggingFace on first use, generates intermediate frames with configurable multiplier, and uses timestep-based interpolation for smooth motion. |
+| `FL_ProResVideo` | Converts image batches to ProRes 4444 video files using FFmpeg with high-quality encoding (yuva444p10le pixel format, 8000 bits_per_mb). Automatically handles temporary file creation, unique naming with timestamp collision avoidance, and cleanup. |
+| `FL_RIFE` | Frame interpolation using RIFE (Real-Time Intermediate Flow Estimation) v4.7 architecture. Downloads model weights from HuggingFace, supports multiple checkpoints (rife47, rife49), configurable multiplier, optional ensemble mode for quality, and multi-scale flow estimation. |
+| `FL_VideoBatchSplitter` | Splits a video batch into exactly N equal-sized sub-batches with strict frame count validation. Returns up to 20 separate batch outputs with configurable frames per batch, requiring exact division with no remainders. |
+| `FL_VideoCadence` | Analyzes image batches for scene changes and returns comma-separated frame counts per scene. Uses configurable detection methods (intensity, histogram, or hybrid) with GPU acceleration support, downsampling optimization, and minimum scene length enforcement. |
+| `FL_VideoCadenceCompile` | Loads videos from a directory, crops each video from the middle to match specified frame counts from a cadence list, and concatenates all frames into a single image batch. Validates frame counts and dimensions with error handling. |
+| `FL_VideoCrossfade` | Blends two video sequences with configurable crossfade duration using multiple blend modes (normal, multiply, screen, overlay, soft_light, add, subtract). Resizes both inputs to target dimensions and generates smooth transitions between sequences. |
+| `FL_VideoCut` | Detects scene cuts in image batches and exports each scene as a separate MP4 file using parallel FFmpeg processing. Features optimized scene detection (intensity/histogram/hybrid), GPU acceleration, downsample optimization, and direct frame piping to FFmpeg for performance. |
+| `FL_VideoTrim` | Trims specified numbers of frames from the start and end of an image batch, returning the trimmed video along with separate outputs for removed start and end frames. |
+
+### 📷 Screenshots & Examples
+
+
+
+
+
+---
diff --git a/comfyui_fill-nodes/__init__.py b/comfyui_fill-nodes/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..64e7231980a13f41053d74afc6c7cb001efb808d
--- /dev/null
+++ b/comfyui_fill-nodes/__init__.py
@@ -0,0 +1,674 @@
+# AI NODES
+from .nodes.ai.FL_Fal_Gemini_ImageEdit import FL_Fal_Gemini_ImageEdit
+from .nodes.ai.FL_Fal_GPTImage2_Edit import FL_Fal_GPTImage2_Edit
+from .nodes.ai.FL_Fal_Kling_AIAvatar import FL_Fal_Kling_AIAvatar
+from .nodes.ai.FL_Fal_Kontext import FL_Fal_Kontext
+from .nodes.ai.FL_Fal_Pixverse import FL_Fal_Pixverse
+from .nodes.ai.FL_Fal_Pixverse_LipSync import FL_Fal_Pixverse_LipSync
+from .nodes.ai.FL_Fal_Pixverse_Transition import FL_Fal_Pixverse_Transition
+from .nodes.ai.FL_Fal_Seedance_i2v import FL_Fal_Seedance_i2v
+from .nodes.ai.FL_Fal_Seedream_Edit import FL_Fal_Seedream_Edit
+from .nodes.ai.FL_Fal_SeedVR_Upscale import FL_Fal_SeedVR_Upscale
+from .nodes.ai.FL_Fal_Sora import FL_Fal_Sora
+from .nodes.ai.FL_GeminiVideoCaptioner import FL_GeminiVideoCaptioner
+from .nodes.ai.FL_Hedra_API import FL_Hedra_API
+from .nodes.ai.FL_PixVerseAPI import FL_PixVerseAPI
+from .nodes.ai.FL_RunwayAct2 import FL_RunwayAct2
+from .nodes.ai.FL_RunwayImageAPI import FL_RunwayImageAPI
+
+# google-genai nodes — wrapped so a websockets version conflict doesn't kill the entire pack
+_GENAI_NODES_AVAILABLE = True
+try:
+ from .nodes.ai.FL_GeminiImageEditor import FL_GeminiImageEditor
+ from .nodes.ai.FL_GeminiImageGenADV import FL_GeminiImageGenADV
+ from .nodes.ai.FL_GeminiTextAPI import FL_GeminiTextAPI
+ from .nodes.ai.FL_VertexGemini25FlashImage import FL_VertexGemini25FlashImage
+ from .nodes.ai.FL_VertexVeo3 import FL_Veo3VideoGen
+except ImportError as e:
+ _GENAI_NODES_AVAILABLE = False
+ print(f"[FL Fill-Nodes] Warning: Could not load Google Gemini/Vertex nodes: {e}")
+ print("[FL Fill-Nodes] Install google-genai with a compatible websockets version to enable these nodes.")
+
+# API_TOOLS NODES
+from .nodes.api_tools.FL_API_Base64_ImageLoader import FL_API_Base64_ImageLoader
+from .nodes.api_tools.FL_API_ImageSaver import FL_API_ImageSaver
+
+# AUDIO NODES
+from .nodes.audio.FL_Audio_BPM_Analyzer import FL_Audio_BPM_Analyzer
+from .nodes.audio.FL_Audio_Beat_Visualizer import FL_Audio_Beat_Visualizer
+from .nodes.audio.FL_Audio_Crop import FL_Audio_Crop
+from .nodes.audio.FL_Audio_Drum_Detector import FL_Audio_Drum_Detector
+from .nodes.audio.FL_Audio_Envelope_Visualizer import FL_Audio_Envelope_Visualizer
+from .nodes.audio.FL_Audio_Music_Video_Sequencer import FL_Audio_Music_Video_Sequencer
+from .nodes.audio.FL_Audio_Reactive_Brightness import FL_Audio_Reactive_Brightness
+from .nodes.audio.FL_Audio_Reactive_Edge_Glow import FL_Audio_Reactive_Edge_Glow
+from .nodes.audio.FL_Audio_Reactive_Envelope import FL_Audio_Reactive_Envelope
+from .nodes.audio.FL_Audio_Reactive_Saturation import FL_Audio_Reactive_Saturation
+from .nodes.audio.FL_Audio_Reactive_Scale import FL_Audio_Reactive_Scale
+from .nodes.audio.FL_Audio_Reactive_Speed import FL_Audio_Reactive_Speed
+from .nodes.audio.FL_Audio_Segment_Extractor import FL_Audio_Segment_Extractor
+from .nodes.audio.FL_Audio_Separation import FL_Audio_Separation
+from .nodes.audio.FL_Audio_Shot_Iterator import FL_Audio_Shot_Iterator
+from .nodes.audio.FL_AudioFrameCalculator import FL_AudioFrameCalculator
+
+# CAPTIONING NODES
+from .nodes.captioning.FL_CSVExtractor import FL_CSVExtractor
+from .nodes.captioning.FL_CaptionToCSV import FL_CaptionToCSV
+from .nodes.captioning.FL_Caption_Saver_V2 import FL_CaptionSaver_V2
+from .nodes.captioning.FL_ImageCaptionLayout import FL_ImageCaptionLayout
+from .nodes.captioning.FL_ImageCaptionLayoutPDF import FL_ImageCaptionLayoutPDF
+from .nodes.captioning.FL_Image_Caption_Saver import FL_ImageCaptionSaver
+from .nodes.captioning.FL_LoadCSV import FL_LoadCSV
+from .nodes.captioning.FL_MirrorAndAppendCaptions import FL_MirrorAndAppendCaptions
+from .nodes.captioning.FL_OllamaCaptioner import FL_OllamaCaptioner
+from .nodes.captioning.FL_SaveCSV import FL_SaveCSV
+from .nodes.captioning.FL_Video_Caption_Saver import FL_VideoCaptionSaver
+from .nodes.captioning.FL_WordFrequencyGraph import FL_WordFrequencyGraph
+
+# DISCORD NODES
+from .nodes.discord.FL_DiscordWebhook import FL_SendToDiscordWebhook
+
+# EXPERIMENTS NODES
+from .nodes.experiments.FL_BatchAligned import FL_BatchAlign
+from .nodes.experiments.FL_ColorPicker import FL_ColorPicker
+from .nodes.experiments.FL_GradGen import FL_GradGenerator
+from .nodes.experiments.FL_NFTGenerator import FL_NFTGenerator
+
+# FILE_OPERATIONS NODES
+from .nodes.file_operations.FL_ZipDirectory import FL_ZipDirectory
+from .nodes.file_operations.FL_ZipSave import FL_ZipSave
+
+# GAMES NODES
+from .nodes.games.FL_BulletHellGame import FL_BulletHellGame
+from .nodes.games.FL_TetrisGame import FL_TetrisGame
+
+# GOOGLE_DRIVE NODES
+from .nodes.google_drive.FL_GoogleCloudStorage import FL_GoogleCloudStorage
+from .nodes.google_drive.FL_GoogleDriveDownloader import FL_GoogleDriveDownloader
+from .nodes.google_drive.FL_GoogleDriveImageDownloader import FL_GoogleDriveImageDownloader
+
+# GPT NODES
+from .nodes.gpt.FL_Dalle3 import FL_Dalle3
+from .nodes.gpt.FL_GPT_Image1 import FL_GPT_Image1
+from .nodes.gpt.FL_GPT_Image1_ADV import FL_GPT_Image1_ADV
+from .nodes.gpt.FL_GPT_Text import FL_GPT_Text
+from .nodes.gpt.FL_GPT_Vision import FL_GPT_Vision
+from .nodes.gpt.FL_SimpleGPTVision import FL_SimpleGPTVision
+
+# HUGGING_FACE NODES
+from .nodes.hugging_face.FL_HFDatasetDownloader import FL_HFDatasetDownloader
+from .nodes.hugging_face.FL_HFHubModelUploader import FL_HFHubModelUploader
+from .nodes.hugging_face.FL_HF_Character import FL_HF_Character
+from .nodes.hugging_face.FL_HF_UploaderAbsolute import FL_HF_UploaderAbsolute
+
+# KARTEL NODES
+from .nodes.kartel.FL_KartelJobInput import FL_KartelJobInput
+from .nodes.kartel.FL_KartelJobOutput import FL_KartelJobOutput
+
+# IMAGE NODES
+from .nodes.image.FL_AnimeLineExtractor import FL_AnimeLineExtractor
+from .nodes.image.FL_ApplyMask import FL_ApplyMask
+from .nodes.image.FL_BlackFrameReject import FL_BlackFrameReject
+from .nodes.image.FL_CoTracker import FL_CoTracker
+from .nodes.image.FL_CreateShapeImageOnPath import FL_CreateShapeImageOnPath
+from .nodes.image.FL_ImageAddNoise import FL_ImageAddNoise
+from .nodes.image.FL_ImageAdjuster import FL_ImageAdjuster
+from .nodes.image.FL_ImageAspectCropper import FL_ImageAspectCropper
+from .nodes.image.FL_ImageBatch import FL_ImageBatch
+from .nodes.image.FL_ImageBatchListConverter import FL_ImageListToImageBatch, FL_ImageBatchToImageList
+from .nodes.image.FL_ImageBatchToGrid import FL_ImageBatchToGrid
+from .nodes.image.FL_ImageNotes import FL_ImageNotes
+from .nodes.image.FL_ImageOverlay import FL_ImageOverlay
+from .nodes.image.FL_ImageReplace import FL_ImageReplace
+from .nodes.image.FL_ImageSelector import FL_ImageSelector
+from .nodes.image.FL_ImagePicker import FL_ImagePicker
+from .nodes.image.FL_ImageSlicer import FL_ImageSlicer
+from .nodes.image.FL_ImageToMask import FL_ImageToMask
+from .nodes.image.FL_Image_AddToBatch import FL_ImageAddToBatch
+from .nodes.image.FL_Image_Blank import FL_ImageBlank
+from .nodes.image.FL_Image_Crop import FL_ImageCrop
+from .nodes.image.FL_Image_Dimension_Display import FL_ImageDimensionDisplay
+from .nodes.image.FL_Image_Randomizer import FL_ImageRandomizer
+from .nodes.image.FL_LoadImage import FL_LoadImage
+from .nodes.image.FL_PaddingRemover import FL_PaddingRemover
+from .nodes.image.FL_ReplaceColor import FL_ReplaceColor
+from .nodes.image.FL_SaveAndDisplayImage import FL_SaveAndDisplayImage
+from .nodes.image.FL_SaveImages import FL_SaveImages
+from .nodes.image.FL_SaveRGBAAnimatedWebP import FL_SaveRGBAAnimatedWebP
+from .nodes.image.FL_SaveWebM import FL_SaveWebM
+from .nodes.image.FL_SaveWebpImages import FL_SaveWebPImage
+
+# KSAMPLERS NODES
+from .nodes.ksamplers.FL_KsamplerBasic import FL_KsamplerBasic
+from .nodes.ksamplers.FL_KsamplerPlus import FL_KsamplerPlus
+from .nodes.ksamplers.FL_KsamplerPlusV2 import FL_KsamplerPlusV2
+from .nodes.ksamplers.FL_KsamplerSigma import FL_KsamplerSigma
+from .nodes.ksamplers.FL_KsamplerSettings import FL_KsamplerSettings
+from .nodes.ksamplers.FL_SamplerStrings import FL_SamplerStrings
+from .nodes.ksamplers.FL_SchedulerStrings import FL_SchedulerStrings
+from .nodes.ksamplers.FL_KSamplerXYZPlot import FL_KSamplerXYZPlot
+
+# LOADERS NODES
+from .nodes.loaders.FL_NodeLoader import FL_NodeLoader
+from .nodes.loaders.FL_NodePackLoader import FL_NodePackLoader
+from .nodes.loaders.FL_UpscaleModel import FL_UpscaleModel
+
+# PDF NODES
+from .nodes.pdf.FL_BulkPDFLoader import FL_BulkPDFLoader
+from .nodes.pdf.FL_ImagesToPDF import FL_ImagesToPDF
+from .nodes.pdf.FL_PDFEncryptor import FL_PDFEncryptor
+from .nodes.pdf.FL_PDFImageExtractor import FL_PDFImageExtractor
+from .nodes.pdf.FL_PDFLoader import FL_PDFLoader
+from .nodes.pdf.FL_PDFMerger import FL_PDFMerger
+from .nodes.pdf.FL_PDFSaver import FL_PDFSaver
+from .nodes.pdf.FL_PDFTextExtractor import FL_PDFTextExtractor
+from .nodes.pdf.FL_PDFToImage import FL_PDFToImages
+from .nodes.pdf.FL_TextToPDF import FL_TextToPDF
+
+# PROMPTING NODES
+from .nodes.prompting.FL_MadLibGenerator import FL_MadLibGenerator
+from .nodes.prompting.FL_Prompt import FL_PromptBasic
+from .nodes.prompting.FL_PromptMulti import FL_PromptMulti
+from .nodes.prompting.FL_PromptSelector import FL_PromptSelector
+from .nodes.prompting.FL_PromptSelectorBasic import FL_PromptSelectorBasic
+
+# UTILITY NODES
+from .nodes.utility.FL_ClipScanner import FL_ClipScanner
+from .nodes.utility.FL_DirectoryCrawl import FL_DirectoryCrawl
+from .nodes.utility.FL_Float import FL_Float
+from .nodes.utility.FL_InpaintCrop import FL_InpaintCrop
+from .nodes.utility.FL_InpaintCrop import FL_Inpaint_Stitch
+from .nodes.utility.FL_JS import FL_JS
+from .nodes.utility.FL_Math import FL_Math
+from .nodes.utility.FL_ModelInspector import FL_ModelInspector
+from .nodes.utility.FL_NumberConverter import FL_IntToFloat, FL_FloatToInt
+from .nodes.utility.FL_Padding import FL_Padding
+from .nodes.utility.FL_PasteByMask import FL_PasteByMask
+from .nodes.utility.FL_PasteOnCanvas import FL_PasteOnCanvas
+from .nodes.utility.FL_PathTypeChecker import FL_PathTypeChecker
+from .nodes.utility.FL_RandomRange import FL_RandomNumber
+from .nodes.utility.FL_RandomShapeGenerator import FL_RandomShapeGenerator
+from .nodes.utility.FL_SD_Slices import FL_SDUltimate_Slices
+from .nodes.utility.FL_SeparateMasks import FL_SeparateMaskComponents
+from .nodes.utility.FL_StringToLoraName import FL_StringToLoraName
+from .nodes.utility.FL_Switch import FL_Switch
+from .nodes.utility.FL_Switch_Big import FL_Switch_Big
+from .nodes.utility.FL_SystemCheck import FL_SystemCheck
+from .nodes.utility.FL_UnloadModel import FL_UnloadModel, FL_UnloadAllModels
+from .nodes.utility.FL_VideoCropNStitch import FL_VideoCropMask
+from .nodes.utility.FL_VideoCropNStitch import FL_VideoRecompose
+
+# VFX NODES
+from .nodes.vfx.FL_Ascii import FL_Ascii
+from .nodes.vfx.FL_DepthBlur import FL_DepthBlur
+from .nodes.vfx.FL_Dither import FL_Dither
+from .nodes.vfx.FL_Glitch import FL_Glitch
+from .nodes.vfx.FL_HalfTone import FL_HalftonePattern
+from .nodes.vfx.FL_HexagonalPattern import FL_HexagonalPattern
+from .nodes.vfx.FL_ImageCollage import FL_ImageCollage
+from .nodes.vfx.FL_Image_Pixelator import FL_ImagePixelator
+from .nodes.vfx.FL_InfiniteZoom import FL_InfiniteZoom
+from .nodes.vfx.FL_PaperDrawn import FL_PaperDrawn
+from .nodes.vfx.FL_PixelArt import FL_PixelArtShader
+from .nodes.vfx.FL_PixelSort import FL_PixelSort
+from .nodes.vfx.FL_RetroEffect import FL_RetroEffect
+from .nodes.vfx.FL_Ripple import FL_Ripple
+from .nodes.vfx.FL_Shader import FL_Shadertoy
+from .nodes.vfx.FL_TextOverlay import FL_TextOverlayNode
+
+# VIDEO NODES
+from .nodes.video.FL_FILM import FL_FILM
+from .nodes.video.FL_ProResVideo import FL_ProResVideo
+from .nodes.video.FL_RIFE import FL_RIFE
+from .nodes.video.FL_VideoBatchSplitter import FL_VideoBatchSplitter
+from .nodes.video.FL_VideoCadence import FL_VideoCadence
+from .nodes.video.FL_VideoCadenceCompile import FL_VideoCadenceCompile
+from .nodes.video.FL_VideoCrossfade import FL_VideoCrossfade
+from .nodes.video.FL_VideoCut import FL_VideoCut
+from .nodes.video.FL_VideoTrim import FL_VideoTrim
+
+# WIP NODES
+from .nodes.wip.FL_KsamplerFractals import FL_FractalKSampler
+from .nodes.wip.FL_TimeLine import FL_TimeLine
+from .nodes.wip.FL_WF_Agent import FL_WF_Agent
+from .nodes.wip.FL_WanFirstLastFrameToVideo import FL_WanFirstLastFrameToVideo
+from .nodes.wip.FL_QwenImageEditStrength import FL_QwenImageEditStrength
+from .nodes.wip.FL_WanVaceToVideoMultiRef import FL_WanVaceToVideoMultiRef
+from .nodes.wip.FL_AnimatedShapePatterns import FL_AnimatedShapePatterns
+from .nodes.wip.FL_PathAnimator import FL_PathAnimator
+from .nodes.wip.FL_WanVideoContinue import FL_WanVideoContinue
+from .nodes.wip.FL_WanVideoBlender import FL_WanVideoBlender
+from .nodes.wip.FL_WanVideoBlender3Way import FL_WanVideoBlender3Way
+from .nodes.wip.FL_WanVideoContinuationBlender import FL_WanVideoContinuationBlender
+
+NODE_CLASS_MAPPINGS = {
+ "FL_SaveWebM": FL_SaveWebM,
+ "FL_TextOverlayNode": FL_TextOverlayNode,
+ "FL_ImageBlank": FL_ImageBlank,
+ "FL_ImageRandomizer": FL_ImageRandomizer,
+ "FL_ImageCaptionSaver": FL_ImageCaptionSaver,
+ "FL_VideoCaptionSaver": FL_VideoCaptionSaver,
+ "FL_ImageDimensionDisplay": FL_ImageDimensionDisplay,
+ "FL_GeminiVideoCaptioner": FL_GeminiVideoCaptioner,
+ "FL_GPT_Image1": FL_GPT_Image1,
+ "FL_ImagePixelator": FL_ImagePixelator,
+ "FL_ImageAddToBatch": FL_ImageAddToBatch,
+ "FL_DirectoryCrawl": FL_DirectoryCrawl,
+ "FL_Ascii": FL_Ascii,
+ "FL_ReplaceColor": FL_ReplaceColor,
+ "FL_ImageAddNoise": FL_ImageAddNoise,
+ "FL_WordFrequencyGraph": FL_WordFrequencyGraph,
+ "FL_Glitch": FL_Glitch,
+ "FL_Ripple": FL_Ripple,
+ "FL_PixelSort": FL_PixelSort,
+ "FL_HexagonalPattern": FL_HexagonalPattern,
+ "FL_NFTGenerator": FL_NFTGenerator,
+ "FL_HalftonePattern": FL_HalftonePattern,
+ "FL_DepthBlur": FL_DepthBlur,
+ "FL_RandomNumber": FL_RandomNumber,
+ "FL_PromptSelector": FL_PromptSelector,
+ "FL_Shadertoy": FL_Shadertoy,
+ "FL_PixelArtShader": FL_PixelArtShader,
+ "FL_InfiniteZoom": FL_InfiniteZoom,
+ "FL_PaperDrawn": FL_PaperDrawn,
+ "FL_ImageNotes": FL_ImageNotes,
+ "FL_ImageCollage": FL_ImageCollage,
+ "FL_KsamplerSettings": FL_KsamplerSettings,
+ "FL_RetroEffect": FL_RetroEffect,
+ "FL_InpaintCrop": FL_InpaintCrop,
+ "FL_Inpaint_Stitch": FL_Inpaint_Stitch,
+ "FL_SDUltimate_Slices": FL_SDUltimate_Slices,
+ "FL_BatchAlign": FL_BatchAlign,
+ "FL_VideoRecompose": FL_VideoRecompose,
+ "FL_VideoCropMask": FL_VideoCropMask,
+ "FL_SeparateMaskComponents": FL_SeparateMaskComponents,
+ "FL_PasteOnCanvas": FL_PasteOnCanvas,
+ "FL_BulletHellGame": FL_BulletHellGame,
+ "FL_TetrisGame": FL_TetrisGame,
+ "FL_Dither": FL_Dither,
+ "FL_SystemCheck": FL_SystemCheck,
+ "FL_ColorPicker": FL_ColorPicker,
+ "FL_GradGenerator": FL_GradGenerator,
+ "FL_MirrorAndAppendCaptions": FL_MirrorAndAppendCaptions,
+ "FL_ImageCaptionLayout": FL_ImageCaptionLayout,
+ "FL_HFHubModelUploader": FL_HFHubModelUploader,
+ "FL_ZipDirectory": FL_ZipDirectory,
+ "FL_ZipSave": FL_ZipSave,
+ "FL_GPT_Vision": FL_GPT_Vision,
+ "FL_TimeLine": FL_TimeLine,
+ "FL_SimpleGPTVision": FL_SimpleGPTVision,
+ "FL_SendToDiscordWebhook": FL_SendToDiscordWebhook,
+ "FL_HF_Character": FL_HF_Character,
+ "FL_CaptionToCSV": FL_CaptionToCSV,
+ "FL_KsamplerPlus": FL_KsamplerPlus,
+ "FL_KsamplerPlusV2": FL_KsamplerPlusV2,
+ "FL_KsamplerBasic": FL_KsamplerBasic,
+ "FL_KsamplerSigma": FL_KsamplerSigma,
+ "FL_FractalKSampler": FL_FractalKSampler,
+ "FL_UpscaleModel": FL_UpscaleModel,
+ "FL_SaveCSV": FL_SaveCSV,
+ "FL_LoadCSV": FL_LoadCSV,
+ "FL_CSVExtractor": FL_CSVExtractor,
+ "FL_KSamplerXYZPlot": FL_KSamplerXYZPlot,
+ "FL_SamplerStrings": FL_SamplerStrings,
+ "FL_SchedulerStrings": FL_SchedulerStrings,
+ "FL_ImageCaptionLayoutPDF": FL_ImageCaptionLayoutPDF,
+ "FL_Dalle3": FL_Dalle3,
+ "FL_SaveImages": FL_SaveImages,
+ "FL_LoadImage": FL_LoadImage,
+ "FL_PDFLoader": FL_PDFLoader,
+ "FL_PDFToImages": FL_PDFToImages,
+ "FL_PDFSaver": FL_PDFSaver,
+ "FL_ImagesToPDF": FL_ImagesToPDF,
+ "FL_PDFMerger": FL_PDFMerger,
+ "FL_PDFTextExtractor": FL_PDFTextExtractor,
+ "FL_PDFImageExtractor": FL_PDFImageExtractor,
+ "FL_BulkPDFLoader": FL_BulkPDFLoader,
+ "FL_TextToPDF": FL_TextToPDF,
+ "FL_PDFEncryptor": FL_PDFEncryptor,
+ "FL_SaveAndDisplayImage": FL_SaveAndDisplayImage,
+ "FL_OllamaCaptioner": FL_OllamaCaptioner,
+ "FL_ImageAdjuster": FL_ImageAdjuster,
+ "FL_CaptionSaver_V2": FL_CaptionSaver_V2,
+ "FL_PathTypeChecker": FL_PathTypeChecker,
+ "FL_SaveWebPImage(SaveImage)": FL_SaveWebPImage,
+ "FL_MadLibGenerator": FL_MadLibGenerator,
+ "FL_Math": FL_Math,
+ "FL_ImageSlicer": FL_ImageSlicer,
+ "FL_ImageSelector": FL_ImageSelector,
+ "FL_ImagePicker": FL_ImagePicker,
+ "FL_ImageOverlay": FL_ImageOverlay,
+ "FL_ImageReplace": FL_ImageReplace,
+ "FL_ImageAspectCropper": FL_ImageAspectCropper,
+ "FL_CoTracker": FL_CoTracker,
+ "FL_CreateShapeImageOnPath": FL_CreateShapeImageOnPath,
+ "FL_HF_UploaderAbsolute": FL_HF_UploaderAbsolute,
+ "FL_ImageListToImageBatch": FL_ImageListToImageBatch,
+ "FL_ImageBatchToImageList": FL_ImageBatchToImageList,
+ "FL_ImageBatchToGrid": FL_ImageBatchToGrid,
+ "FL_ApplyMask": FL_ApplyMask,
+ "FL_ProResVideo": FL_ProResVideo,
+ "FL_Padding": FL_Padding,
+ "FL_GoogleDriveDownloader": FL_GoogleDriveDownloader,
+ "FL_NodeLoader": FL_NodeLoader,
+ "FL_NodePackLoader": FL_NodePackLoader,
+ "FL_API_Base64_ImageLoader": FL_API_Base64_ImageLoader,
+ "FL_API_ImageSaver": FL_API_ImageSaver,
+ "FL_GoogleDriveImageDownloader": FL_GoogleDriveImageDownloader,
+ "FL_AnimeLineExtractor": FL_AnimeLineExtractor,
+ "FL_ClipScanner": FL_ClipScanner,
+ "FL_VideoCut": FL_VideoCut,
+ "FL_JS": FL_JS,
+ "FL_HFDatasetDownloader": FL_HFDatasetDownloader,
+ "FL_WF_Agent": FL_WF_Agent,
+ "FL_BlackFrameReject": FL_BlackFrameReject,
+ "FL_PixVerseAPI": FL_PixVerseAPI,
+ "FL_Fal_Pixverse": FL_Fal_Pixverse,
+ "FL_Fal_Kontext": FL_Fal_Kontext,
+ "FL_Fal_GPTImage2_Edit": FL_Fal_GPTImage2_Edit,
+ "FL_Fal_Gemini_ImageEdit": FL_Fal_Gemini_ImageEdit,
+ "FL_Fal_Seedance_i2v": FL_Fal_Seedance_i2v,
+ "FL_Fal_Seedream_Edit": FL_Fal_Seedream_Edit,
+ "FL_Fal_SeedVR_Upscale": FL_Fal_SeedVR_Upscale,
+ "FL_Fal_Pixverse_Transition": FL_Fal_Pixverse_Transition,
+ "FL_Fal_Pixverse_LipSync": FL_Fal_Pixverse_LipSync,
+ "FL_Fal_Kling_AIAvatar": FL_Fal_Kling_AIAvatar,
+ "FL_Fal_Sora": FL_Fal_Sora,
+ "FL_PromptBasic": FL_PromptBasic,
+ "FL_PromptMulti": FL_PromptMulti,
+ "FL_PromptSelectorBasic": FL_PromptSelectorBasic,
+ "FL_PaddingRemover": FL_PaddingRemover,
+ "FL_GPT_Text": FL_GPT_Text,
+ "FL_GoogleCloudStorage": FL_GoogleCloudStorage,
+ "FL_StringToLoraName": FL_StringToLoraName,
+ "FL_Switch": FL_Switch,
+ "FL_Switch_Big": FL_Switch_Big,
+ "FL_PasteByMask": FL_PasteByMask,
+ "FL_ModelInspector": FL_ModelInspector,
+ "FL_Float": FL_Float,
+ "FL_UnloadModel": FL_UnloadModel,
+ "FL_UnloadAllModels": FL_UnloadAllModels,
+ "FL_VideoTrim": FL_VideoTrim,
+ "FL_VideoBatchSplitter": FL_VideoBatchSplitter,
+ "FL_VideoCrossfade": FL_VideoCrossfade,
+ "FL_VideoCadence": FL_VideoCadence,
+ "FL_VideoCadenceCompile": FL_VideoCadenceCompile,
+ "FL_WanVaceToVideoMultiRef": FL_WanVaceToVideoMultiRef,
+ "FL_RIFE": FL_RIFE,
+ "FL_FILM": FL_FILM,
+ "FL_GPT_Image1_ADV": FL_GPT_Image1_ADV,
+ "FL_ImageBatch": FL_ImageBatch,
+ "FL_Hedra_API": FL_Hedra_API,
+ "FL_RunwayImageAPI": FL_RunwayImageAPI,
+ "FL_RunwayAct2": FL_RunwayAct2,
+ "FL_ImageCrop": FL_ImageCrop,
+ "FL_ImageToMask": FL_ImageToMask,
+ "FL_WanFirstLastFrameToVideo": FL_WanFirstLastFrameToVideo,
+ "FL_WanVideoContinue": FL_WanVideoContinue,
+ "FL_WanVideoBlender": FL_WanVideoBlender,
+ "FL_WanVideoBlender3Way": FL_WanVideoBlender3Way,
+ "FL_WanVideoContinuationBlender": FL_WanVideoContinuationBlender,
+ "FL_SaveRGBAAnimatedWebP": FL_SaveRGBAAnimatedWebP,
+ "FL_Audio_BPM_Analyzer": FL_Audio_BPM_Analyzer,
+ "FL_Audio_Beat_Visualizer": FL_Audio_Beat_Visualizer,
+ "FL_Audio_Crop": FL_Audio_Crop,
+ "FL_Audio_Drum_Detector": FL_Audio_Drum_Detector,
+ "FL_Audio_Envelope_Visualizer": FL_Audio_Envelope_Visualizer,
+ "FL_Audio_Music_Video_Sequencer": FL_Audio_Music_Video_Sequencer,
+ "FL_Audio_Reactive_Brightness": FL_Audio_Reactive_Brightness,
+ "FL_Audio_Reactive_Edge_Glow": FL_Audio_Reactive_Edge_Glow,
+ "FL_Audio_Reactive_Envelope": FL_Audio_Reactive_Envelope,
+ "FL_Audio_Reactive_Saturation": FL_Audio_Reactive_Saturation,
+ "FL_Audio_Reactive_Scale": FL_Audio_Reactive_Scale,
+ "FL_Audio_Reactive_Speed": FL_Audio_Reactive_Speed,
+ "FL_Audio_Segment_Extractor": FL_Audio_Segment_Extractor,
+ "FL_Audio_Separation": FL_Audio_Separation,
+ "FL_Audio_Shot_Iterator": FL_Audio_Shot_Iterator,
+ "FL_AudioFrameCalculator": FL_AudioFrameCalculator,
+ "FL_QwenImageEditStrength": FL_QwenImageEditStrength,
+ "FL_IntToFloat": FL_IntToFloat,
+ "FL_FloatToInt": FL_FloatToInt,
+ "FL_AnimatedShapePatterns": FL_AnimatedShapePatterns,
+ "FL_PathAnimator": FL_PathAnimator,
+ "FL_RandomShapeGenerator": FL_RandomShapeGenerator,
+ "FL_KartelJobInput": FL_KartelJobInput,
+ "FL_KartelJobOutput": FL_KartelJobOutput,
+}
+
+NODE_DISPLAY_NAME_MAPPINGS = {
+ "FL_ImageBlank": "FL Image Blank",
+ "FL_ImageRandomizer": "FL Image Randomizer",
+ "FL_ImageCaptionSaver": "FL Image Caption Saver",
+ "FL_VideoCaptionSaver": "FL Video Caption Saver",
+ "FL_ImageDimensionDisplay": "FL Image Size",
+ "FL_GeminiVideoCaptioner": "FL Gemini Video Captioner",
+ "FL_GPT_Image1": "FL GPT Image-1",
+ "FL_ImagePixelator": "FL Image Pixelator",
+ "FL_ImageAddToBatch": "FL Image Add To Batch",
+ "FL_DirectoryCrawl": "FL Directory Crawl",
+ "FL_Ascii": "FL Ascii",
+ "FL_ReplaceColor": "FL Replace Color",
+ "FL_ImageAddNoise": "FL Image Add Noise",
+ "FL_WordFrequencyGraph": "FL Word Frequency Graph",
+ "FL_Glitch": "FL Glitch",
+ "FL_Ripple": "FL Ripple",
+ "FL_PixelSort": "FL PixelSort",
+ "FL_HexagonalPattern": "FL Hexagonal Pattern",
+ "FL_NFTGenerator": "FL NFT Generator",
+ "FL_HalftonePattern": "FL Halftone",
+ "FL_DepthBlur": "FL Depth Blur",
+ "FL_RandomNumber": "FL Random Number",
+ "FL_PromptSelector": "FL Prompt Selector",
+ "FL_PromptSelectorBasic": "FL Prompt Selector Basic",
+ "FL_Shadertoy": "FL Shadertoy",
+ "FL_PixelArtShader": "FL Pixel Art",
+ "FL_InfiniteZoom": "FL Infinite Zoom",
+ "FL_PaperDrawn": "FL Paper Drawn",
+ "FL_ImageNotes": "FL Image Notes",
+ "FL_ImageCollage": "FL Image Collage",
+ "FL_KsamplerSettings": "FL KSampler Settings",
+ "FL_RetroEffect": "FL Retro Effect",
+ "FL_InpaintCrop": "FL Inpaint Crop",
+ "FL_Inpaint_Stitch": "FL Inpaint Stitch",
+ "FL_SDUltimate_Slices": "FL SDUltimate Slices",
+ "FL_BatchAlign": "FL Batch Align",
+ "FL_VideoCropMask": "FL Video CropMask",
+ "FL_VideoRecompose": "FL Video Recompose",
+ "FL_SeparateMaskComponents": "FL Separate Mask Components",
+ "FL_PasteOnCanvas": "FL Paste On Canvas",
+ "FL_BulletHellGame": "FL BulletHell Game",
+ "FL_TetrisGame": "FL Tetris Game",
+ "FL_Dither": "FL Dither",
+ "FL_SystemCheck": "FL System Check",
+ "FL_ColorPicker": "FL Color Picker",
+ "FL_GradGenerator": "FL Grad Generator",
+ "FL_MirrorAndAppendCaptions": "FL Mirror And Append Captions",
+ "FL_ImageCaptionLayout": "FL Image Caption Layout",
+ "FL_HFHubModelUploader": "FL HFHub Model Uploader",
+ "FL_ZipDirectory": "FL Zip Directory",
+ "FL_ZipSave": "FL_ZipSave",
+ "FL_GPT_Vision": "FL GPT Captions",
+ "FL_TimeLine": "FL Time Line",
+ "FL_SimpleGPTVision": "FL Simple GPT Vision",
+ "FL_SendToDiscordWebhook": "FL Kytra Discord Webhook",
+ "FL_HF_Character": "FL HF Character",
+ "FL_CaptionToCSV": "FL Caption To CSV",
+ "FL_KsamplerPlus": "FL KSampler Plus",
+ "FL_KsamplerPlusV2": "FL KSampler Plus V2",
+ "FL_KsamplerBasic": "FL KSampler Basic",
+ "FL_KsamplerSigma": "FL KSampler Sigma",
+ "FL_FractalKSampler": "FL Fractal KSampler",
+ "FL_UpscaleModel": "FL Upscale Model",
+ "FL_SaveCSV": "FL Save CSV",
+ "FL_LoadCSV": "FL Load CSV",
+ "FL_CSVExtractor": "FL CSV Extractor",
+ "FL_KSamplerXYZPlot": "FL KSampler XYZ Plot",
+ "FL_SamplerStrings": "FL Sampler String XYZ",
+ "FL_SchedulerStrings": "FL Scheduler String XYZ",
+ "FL_ImageCaptionLayoutPDF": "FL Image Caption Layout PDF",
+ "FL_Dalle3": "FL Dalle 3",
+ "FL_SaveImages": "FL Save Images",
+ "FL_LoadImage": "FL Load Image",
+ "FL_PDFLoader": "FL PDF Loader",
+ "FL_PDFToImages": "FL PDF To Images",
+ "FL_PDFSaver": "FL PDF Saver",
+ "FL_ImagesToPDF": "FL Images To PDF",
+ "FL_PDFMerger": "FL PDF Merger",
+ "FL_PDFTextExtractor": "FL PDF Text Extractor",
+ "FL_PDFImageExtractor": "FL PDF Image Extractor",
+ "FL_BulkPDFLoader": "FL Bulk PDF Loader",
+ "FL_TextToPDF": "FL Text To PDF",
+ "FL_PDFEncryptor": "FL PDF Encryptor",
+ "FL_SaveAndDisplayImage": "FL Save And Display Image",
+ "FL_OllamaCaptioner": "FL Ollama Captioner by Cosmic",
+ "FL_ImageAdjuster": "FL Image Adjuster",
+ "FL_CaptionSaver_V2": "FL Caption Saver V2",
+ "FL_PathTypeChecker": "FL Path Type Checker",
+ "FL_SaveWebPImage(SaveImage)": "FL Save WebP Image",
+ "FL_MadLibGenerator": "FL MadLib Generator",
+ "FL_Math": "FL Math",
+ "FL_ImageSlicer": "FL Image Slicer",
+ "FL_ImageSelector": "FL Image Selector",
+ "FL_ImagePicker": "FL Image Picker",
+ "FL_ImageOverlay": "FL Image Overlay",
+ "FL_ImageReplace": "FL Image Replace",
+ "FL_ImageAspectCropper": "FL Image Aspect Cropper",
+ "FL_CoTracker": "FL CoTracker",
+ "FL_CreateShapeImageOnPath": "FL Create Shape Image On Path",
+ "FL_HF_UploaderAbsolute": "FL HF Uploader Absolute",
+ "FL_ImageListToImageBatch": "FL Image List To Image Batch",
+ "FL_ImageBatchToImageList": "FL Image Batch To Image List",
+ "FL_ImageBatchToGrid": "FL Image Batch To Grid",
+ "FL_ApplyMask": "FL Apply Mask",
+ "FL_ProResVideo": "FL ProRes Video",
+ "FL_Padding": "FL Padding",
+ "FL_GoogleDriveDownloader": "FL Google Drive Downloader",
+ "FL_NodeLoader": "FL Node Loader",
+ "FL_NodePackLoader": "FL Node Pack Loader",
+ "FL_API_Base64_ImageLoader": "FL API Base64 Image Loader",
+ "FL_API_ImageSaver": "FL API Image Saver",
+ "FL_GoogleDriveImageDownloader": "FL Google Drive Image Downloader",
+ "FL_AnimeLineExtractor": "FL Anime Line Extractor",
+ "FL_ClipScanner": "FL Clip Scanner (Kytra)",
+ "FL_VideoCut": "FL Video Cut Detector",
+ "FL_JS": "FL JavaScript",
+ "FL_HFDatasetDownloader": "FL HF Dataset Downloader",
+ "FL_WF_Agent": "FL Workflow Agent",
+ "FL_BlackFrameReject": "FL Black Frame Reject",
+ "FL_PixVerseAPI": "FL PixVerse API",
+ "FL_Fal_Pixverse": "FL Fal Pixverse API",
+ "FL_Fal_Kontext": "FL Fal Kontext API",
+ "FL_Fal_GPTImage2_Edit": "FL Fal GPT-Image-2 Edit",
+ "FL_Fal_Gemini_ImageEdit": "FL Fal Gemini Image Edit",
+ "FL_Fal_Seedance_i2v": "FL Fal Seedance i2v",
+ "FL_Fal_Seedream_Edit": "FL Fal Seedream Edit",
+ "FL_Fal_SeedVR_Upscale": "FL Fal SeedVR Upscale",
+ "FL_Fal_Pixverse_Transition": "FL Fal Pixverse Transition",
+ "FL_Fal_Pixverse_LipSync": "FL Fal Pixverse LipSync",
+ "FL_Fal_Kling_AIAvatar": "FL Fal Kling AI Avatar",
+ "FL_Fal_Sora": "FL Fal Sora 2",
+ "FL_PromptBasic": "FL Prompt Basic",
+ "FL_PromptMulti": "FL Prompt Multi",
+ "FL_PromptSelectorBasic": "FL Prompt Selector Basic",
+ "FL_PaddingRemover": "FL Padding Remover",
+ "FL_GPT_Text": "FL GPT Text",
+ "FL_GoogleCloudStorage": "FL Google Cloud Storage Uploader",
+ "FL_StringToLoraName": "FL String To Lora Name",
+ "FL_Switch": "FL Switch",
+ "FL_Switch_Big": "FL Switch Big",
+ "FL_PasteByMask": "FL Paste By Mask",
+ "FL_Float": "FL Float",
+ "FL_UnloadModel": "FL Unload Model",
+ "FL_UnloadAllModels": "FL Unload All Models",
+ "FL_ModelInspector": "FL Model Inspector",
+ "FL_VideoTrim": "FL Video Trim",
+ "FL_VideoBatchSplitter": "FL Video Batch Splitter",
+ "FL_VideoCrossfade": "FL Video Crossfade",
+ "FL_VideoCadence": "FL Video Cadence",
+ "FL_WanVaceToVideoMultiRef": "FL Wan Vace To Video Multi Reference",
+ "FL_VideoCadenceCompile": "FL Video Cadence Compile",
+ "FL_FILM": "FL FILM Frame Interpolation",
+ "FL_RIFE": "FL RIFE Frame Interpolation",
+ "FL_GPT_Image1_ADV": "FL GPT Image1 ADV",
+ "FL_ImageBatch": "FL Image Batch",
+ "FL_Hedra_API": "FL Hedra API",
+ "FL_RunwayImageAPI": "FL Runway Image API",
+ "FL_RunwayAct2": "FL Runway Act2",
+ "FL_TextOverlayNode": "FL Text Overlay",
+ "FL_SaveWebM": "FL Save WebM",
+ "FL_ImageCrop": "FL Image Crop",
+ "FL_ImageToMask": "FL Image To Mask",
+ "FL_WanFirstLastFrameToVideo": "FL Wan First Frame Last Frame",
+ "FL_WanVideoContinue": "FL Wan Video Continue",
+ "FL_WanVideoBlender": "FL Wan Video Blender",
+ "FL_WanVideoBlender3Way": "FL Wan Video Blender 3-Way",
+ "FL_WanVideoContinuationBlender": "FL Wan Video Continuation Blender",
+ "FL_SaveRGBAAnimatedWebP": "FL Save RGBA Animated WebP",
+ "FL_Audio_BPM_Analyzer": "FL Audio BPM Analyzer",
+ "FL_Audio_Beat_Visualizer": "FL Audio Beat Visualizer",
+ "FL_Audio_Crop": "FL Audio Crop",
+ "FL_Audio_Drum_Detector": "FL Audio Drum Detector",
+ "FL_Audio_Envelope_Visualizer": "FL Audio Envelope Visualizer",
+ "FL_Audio_Music_Video_Sequencer": "FL Audio Music Video Sequencer",
+ "FL_Audio_Reactive_Brightness": "FL Audio Reactive Brightness",
+ "FL_Audio_Reactive_Edge_Glow": "FL Audio Reactive Edge Glow",
+ "FL_Audio_Reactive_Envelope": "FL Audio Reactive Envelope",
+ "FL_Audio_Reactive_Saturation": "FL Audio Reactive Saturation",
+ "FL_Audio_Reactive_Scale": "FL Audio Reactive Scale",
+ "FL_Audio_Reactive_Speed": "FL Audio Reactive Speed",
+ "FL_Audio_Segment_Extractor": "FL Audio Segment Extractor",
+ "FL_Audio_Separation": "FL Audio Separation",
+ "FL_Audio_Shot_Iterator": "FL Audio Shot Iterator",
+ "FL_AudioFrameCalculator": "FL Audio Frame Calculator",
+ "FL_QwenImageEditStrength": "FL Qwen Image Edit with Strength",
+ "FL_IntToFloat": "FL Int to Float",
+ "FL_FloatToInt": "FL Float to Int",
+ "FL_AnimatedShapePatterns": "FL Animated Shape Patterns",
+ "FL_PathAnimator": "FL Path Animator",
+ "FL_RandomShapeGenerator": "FL Random Shape Generator",
+ "FL_KartelJobInput": "FL Kartel Job Input",
+ "FL_KartelJobOutput": "FL Kartel Job Output",
+}
+
+# Conditionally register google-genai nodes if the SDK loaded successfully
+if _GENAI_NODES_AVAILABLE:
+ NODE_CLASS_MAPPINGS.update({
+ "FL_GeminiImageEditor": FL_GeminiImageEditor,
+ "FL_GeminiImageGenADV": FL_GeminiImageGenADV,
+ "FL_GeminiTextAPI": FL_GeminiTextAPI,
+ "FL_Veo3VideoGen": FL_Veo3VideoGen,
+ "FL_VertexGemini25FlashImage": FL_VertexGemini25FlashImage,
+ })
+ NODE_DISPLAY_NAME_MAPPINGS.update({
+ "FL_GeminiImageEditor": "FL Gemini Image Editor",
+ "FL_GeminiImageGenADV": "FL Gemini Image Gen ADV",
+ "FL_GeminiTextAPI": "FL Gemini Text API",
+ "FL_Veo3VideoGen": "FL Vertex Veo3",
+ "FL_VertexGemini25FlashImage": "FL Vertex Gemini 2.5 Flash Image",
+ })
+
+
+ascii_art = """
+
+███╗ ███╗ █████╗ ██████╗██╗ ██╗██╗███╗ ██╗███████╗
+████╗ ████║██╔══██╗██╔════╝██║ ██║██║████╗ ██║██╔════╝
+██╔████╔██║███████║██║ ███████║██║██╔██╗ ██║█████╗
+██║╚██╔╝██║██╔══██║██║ ██╔══██║██║██║╚██╗██║██╔══╝
+██║ ╚═╝ ██║██║ ██║╚██████╗██║ ██║██║██║ ╚████║███████╗
+╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝╚══════╝
+
+██████╗ ███████╗██╗ ██╗ ██╗███████╗██╗ ██████╗ ███╗ ██╗███████╗
+██╔══██╗██╔════╝██║ ██║ ██║██╔════╝██║██╔═══██╗████╗ ██║██╔════╝
+██║ ██║█████╗ ██║ ██║ ██║███████╗██║██║ ██║██╔██╗ ██║███████╗
+██║ ██║██╔══╝ ██║ ██║ ██║╚════██║██║██║ ██║██║╚██╗██║╚════██║
+██████╔╝███████╗███████╗╚██████╔╝███████║██║╚██████╔╝██║ ╚████║███████║
+╚═════╝ ╚══════╝╚══════╝ ╚═════╝ ╚══════╝╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝
+
+
+"""
+print(ascii_art)
+
+# Using OpenCV for video processing
+
+WEB_DIRECTORY = "./web"
+__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
\ No newline at end of file
diff --git a/comfyui_fill-nodes/fonts/Barcode.ttf b/comfyui_fill-nodes/fonts/Barcode.ttf
new file mode 100644
index 0000000000000000000000000000000000000000..d43750e626be78ce082f7e37e92faf9f150ecba3
Binary files /dev/null and b/comfyui_fill-nodes/fonts/Barcode.ttf differ
diff --git a/comfyui_fill-nodes/fonts/Circles.ttf b/comfyui_fill-nodes/fonts/Circles.ttf
new file mode 100644
index 0000000000000000000000000000000000000000..411a1a717d658439256c8c2f2cd870f4b5be2fb2
Binary files /dev/null and b/comfyui_fill-nodes/fonts/Circles.ttf differ
diff --git a/comfyui_fill-nodes/fonts/Square.TTF b/comfyui_fill-nodes/fonts/Square.TTF
new file mode 100644
index 0000000000000000000000000000000000000000..14704b9cd37317bf5b132a5bcef009a765a2d6eb
Binary files /dev/null and b/comfyui_fill-nodes/fonts/Square.TTF differ
diff --git a/comfyui_fill-nodes/images/.DS_Store b/comfyui_fill-nodes/images/.DS_Store
new file mode 100644
index 0000000000000000000000000000000000000000..9dfcb527472faff20a793c282f1332aa0bd8a95a
Binary files /dev/null and b/comfyui_fill-nodes/images/.DS_Store differ
diff --git a/comfyui_fill-nodes/images/nodes/ai.png b/comfyui_fill-nodes/images/nodes/ai.png
new file mode 100644
index 0000000000000000000000000000000000000000..8105ead3e40a757bae429bb10ed2ac488af5e6c3
Binary files /dev/null and b/comfyui_fill-nodes/images/nodes/ai.png differ
diff --git a/comfyui_fill-nodes/images/nodes/clip.png b/comfyui_fill-nodes/images/nodes/clip.png
new file mode 100644
index 0000000000000000000000000000000000000000..23faa8d681bea08a25384891c6564db28aff5b4f
Binary files /dev/null and b/comfyui_fill-nodes/images/nodes/clip.png differ
diff --git a/comfyui_fill-nodes/images/nodes/discord.png b/comfyui_fill-nodes/images/nodes/discord.png
new file mode 100644
index 0000000000000000000000000000000000000000..25207a42ce5288453d4548a220d84f2e69143cda
Binary files /dev/null and b/comfyui_fill-nodes/images/nodes/discord.png differ
diff --git a/comfyui_fill-nodes/images/nodes/games.png b/comfyui_fill-nodes/images/nodes/games.png
new file mode 100644
index 0000000000000000000000000000000000000000..de6632775671cd72061e9ffce6b4fda84824e110
Binary files /dev/null and b/comfyui_fill-nodes/images/nodes/games.png differ
diff --git a/comfyui_fill-nodes/images/nodes/googledrive.png b/comfyui_fill-nodes/images/nodes/googledrive.png
new file mode 100644
index 0000000000000000000000000000000000000000..5e251aa77fc0756b5cc9dbb7ae602f770c715879
Binary files /dev/null and b/comfyui_fill-nodes/images/nodes/googledrive.png differ
diff --git a/comfyui_fill-nodes/images/nodes/math.png b/comfyui_fill-nodes/images/nodes/math.png
new file mode 100644
index 0000000000000000000000000000000000000000..24d847e3ef2d71b59c3fb2c24d2f431e48b53f6f
Binary files /dev/null and b/comfyui_fill-nodes/images/nodes/math.png differ
diff --git a/comfyui_fill-nodes/images/nodes/prompting.png b/comfyui_fill-nodes/images/nodes/prompting.png
new file mode 100644
index 0000000000000000000000000000000000000000..5f9d4534bdee3e0084e72ce0c6cfcfca7104c232
Binary files /dev/null and b/comfyui_fill-nodes/images/nodes/prompting.png differ
diff --git a/comfyui_fill-nodes/images/nodes/video.png b/comfyui_fill-nodes/images/nodes/video.png
new file mode 100644
index 0000000000000000000000000000000000000000..e216eca43c442fe40948a113ae7640ba4bfb230e
Binary files /dev/null and b/comfyui_fill-nodes/images/nodes/video.png differ
diff --git a/comfyui_fill-nodes/images/nodes/wip.png b/comfyui_fill-nodes/images/nodes/wip.png
new file mode 100644
index 0000000000000000000000000000000000000000..b92e41fd90f7def7e7535f12c9990bd718538117
Binary files /dev/null and b/comfyui_fill-nodes/images/nodes/wip.png differ
diff --git a/comfyui_fill-nodes/images/nodes/zip.png b/comfyui_fill-nodes/images/nodes/zip.png
new file mode 100644
index 0000000000000000000000000000000000000000..66326825856beaff07fcbdc13f136557fbb5f2a2
Binary files /dev/null and b/comfyui_fill-nodes/images/nodes/zip.png differ
diff --git a/comfyui_fill-nodes/linux_req_install.sh b/comfyui_fill-nodes/linux_req_install.sh
new file mode 100644
index 0000000000000000000000000000000000000000..7b6db3f947379733424ecf99d2caf5eec614713e
--- /dev/null
+++ b/comfyui_fill-nodes/linux_req_install.sh
@@ -0,0 +1,10 @@
+#!/bin/bash
+
+# Update package lists
+apt-get update
+
+# Install required system libraries for OpenGL
+apt-get install -y libgl1-mesa-glx freeglut3-dev
+
+# Install Python dependencies
+pip install -r requirements.txt
diff --git a/comfyui_fill-nodes/nodes/.DS_Store b/comfyui_fill-nodes/nodes/.DS_Store
new file mode 100644
index 0000000000000000000000000000000000000000..af8573201f33abda1da90f48f8b87851a4122bd5
Binary files /dev/null and b/comfyui_fill-nodes/nodes/.DS_Store differ
diff --git a/comfyui_fill-nodes/nodes/__init__.py b/comfyui_fill-nodes/nodes/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/comfyui_fill-nodes/nodes/ai/FL_Fal_GPTImage2_Edit.py b/comfyui_fill-nodes/nodes/ai/FL_Fal_GPTImage2_Edit.py
new file mode 100644
index 0000000000000000000000000000000000000000..245db5c7ff06c6e3c9456cbc85700873278cc2da
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/FL_Fal_GPTImage2_Edit.py
@@ -0,0 +1,342 @@
+# FL_Fal_GPTImage2_Edit: Fal AI GPT-Image-2 Edit endpoint
+# Takes N reference images + a single prompt, returns 1-4 edited images.
+import os
+import io
+import time
+import asyncio
+import concurrent.futures
+from typing import List, Optional
+
+import requests
+import torch
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+
+import fal_client
+from comfy.utils import ProgressBar
+
+
+IMAGE_SIZE_PRESETS = [
+ "auto",
+ "square_hd",
+ "square",
+ "portrait_4_3",
+ "portrait_16_9",
+ "landscape_4_3",
+ "landscape_16_9",
+ "custom",
+]
+QUALITY_OPTIONS = ["low", "medium", "high"]
+OUTPUT_FORMATS = ["png", "jpeg", "webp"]
+
+
+class FL_Fal_GPTImage2_Edit:
+ """
+ ComfyUI node for fal.ai's `openai/gpt-image-2/edit` endpoint.
+
+ Takes a variable number of reference images (image_ref_1, image_ref_2, ...),
+ uploads them to fal.media, then edits/composes against a shared prompt.
+ Dynamic sockets are driven by the `image_count` widget + companion JS file.
+ """
+
+ RETURN_TYPES = ("IMAGE", "STRING", "STRING")
+ RETURN_NAMES = ("images", "image_urls", "status_msg")
+ FUNCTION = "generate"
+ CATEGORY = "🏵️Fill Nodes/AI"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "api_key": ("STRING", {"multiline": False, "default": ""}),
+ "image_count": ("INT", {"default": 1, "min": 1, "max": 10, "step": 1}),
+ "prompt": ("STRING", {"default": "A cozy scene with all these elements combined.",
+ "multiline": True, "forceInput": False}),
+ "image_size": (IMAGE_SIZE_PRESETS, {"default": "auto"}),
+ "custom_width": ("INT", {"default": 1024, "min": 64, "max": 4096, "step": 8}),
+ "custom_height": ("INT", {"default": 1024, "min": 64, "max": 4096, "step": 8}),
+ "quality": (QUALITY_OPTIONS, {"default": "high"}),
+ "num_images": ("INT", {"default": 1, "min": 1, "max": 4, "step": 1}),
+ "output_format": (OUTPUT_FORMATS, {"default": "png"}),
+ "max_retries": ("INT", {"default": 3, "min": 1, "max": 5, "step": 1}),
+ "image_ref_1": ("IMAGE",),
+ },
+ "optional": {
+ "mask": ("IMAGE",),
+ "sync_mode": ("BOOLEAN", {"default": False}),
+ "retry_indefinitely": ("BOOLEAN", {"default": False}),
+ },
+ }
+
+ def __init__(self):
+ self.log_messages: List[str] = []
+
+ # ------------------------------------------------------------------
+ # Helpers
+ # ------------------------------------------------------------------
+
+ def _log(self, message: str) -> str:
+ timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
+ formatted = f"[FL_Fal_GPTImage2_Edit] {timestamp}: {message}"
+ print(formatted)
+ self.log_messages.append(message)
+ return message
+
+ @staticmethod
+ def _tensor_to_pil(tensor: Optional[torch.Tensor]) -> Optional[Image.Image]:
+ if tensor is None or not isinstance(tensor, torch.Tensor):
+ return None
+ if tensor.ndim == 4:
+ if tensor.shape[0] == 0:
+ return None
+ arr = tensor[0].cpu().numpy()
+ elif tensor.ndim == 3:
+ arr = tensor.cpu().numpy()
+ else:
+ return None
+ arr = (arr * 255.0).clip(0, 255).astype(np.uint8)
+ return Image.fromarray(arr)
+
+ def _create_error_image(self, error_message: str = "API Error",
+ width: int = 1024, height: int = 1024) -> torch.Tensor:
+ image = Image.new("RGB", (width, height), color=(0, 0, 0))
+ draw = ImageDraw.Draw(image)
+ font = None
+ for font_name in ("arial.ttf", "DejaVuSans.ttf", "FreeSans.ttf", "NotoSans-Regular.ttf"):
+ try:
+ font = ImageFont.truetype(font_name, 24)
+ break
+ except IOError:
+ continue
+ if font is None:
+ font = ImageFont.load_default()
+
+ try:
+ bbox = draw.textbbox((0, 0), error_message, font=font)
+ tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
+ except AttributeError:
+ tw, th = draw.textsize(error_message, font=font)
+ draw.text(((width - tw) / 2, (height - th) / 2), error_message,
+ fill=(255, 0, 0), font=font)
+ arr = np.array(image).astype(np.float32) / 255.0
+ return torch.from_numpy(arr).unsqueeze(0)
+
+ def _upload_pil(self, pil: Image.Image, label: str) -> Optional[str]:
+ try:
+ buf = io.BytesIO()
+ pil.save(buf, format="PNG")
+ url = fal_client.upload(buf.getvalue(), content_type="image/png")
+ self._log(f"Uploaded {label} to CDN: {url[:80]}...")
+ return url
+ except Exception as e:
+ self._log(f"Error uploading {label}: {e}")
+ return None
+
+ # ------------------------------------------------------------------
+ # Async core
+ # ------------------------------------------------------------------
+
+ async def _generate_async(
+ self, api_key, prompt, ref_pils, mask_pil,
+ image_size, custom_width, custom_height,
+ quality, num_images, output_format,
+ max_retries, retry_indefinitely, sync_mode,
+ ):
+ os.environ["FAL_KEY"] = api_key.strip()
+
+ image_urls = []
+ for idx, pil in enumerate(ref_pils, start=1):
+ url = self._upload_pil(pil, f"image_ref_{idx}")
+ if url is None:
+ msg = f"Upload failed for image_ref_{idx}"
+ return self._create_error_image(msg), "", msg
+ image_urls.append(url)
+
+ mask_url = None
+ if mask_pil is not None:
+ mask_url = self._upload_pil(mask_pil, "mask")
+ if mask_url is None:
+ msg = "Upload failed for mask"
+ return self._create_error_image(msg), "", msg
+
+ resolved_image_size: object
+ if image_size == "custom":
+ resolved_image_size = {"width": int(custom_width), "height": int(custom_height)}
+ else:
+ resolved_image_size = image_size
+
+ arguments = {
+ "prompt": prompt,
+ "image_urls": image_urls,
+ "image_size": resolved_image_size,
+ "quality": quality,
+ "num_images": num_images,
+ "output_format": output_format,
+ "sync_mode": sync_mode,
+ }
+ if mask_url is not None:
+ arguments["mask_url"] = mask_url
+
+ self._log(f"Calling openai/gpt-image-2/edit with {len(image_urls)} ref image(s), "
+ f"quality={quality}, size={resolved_image_size}, n={num_images}")
+
+ def on_queue_update(update):
+ if isinstance(update, fal_client.InProgress):
+ for entry in update.logs:
+ self._log(f"API Log: {entry.get('message', '')}")
+
+ loop = asyncio.get_event_loop()
+ attempt = 0
+ result = None
+ last_err = ""
+ while True:
+ attempt += 1
+
+ def call():
+ try:
+ return fal_client.subscribe(
+ "openai/gpt-image-2/edit",
+ arguments=arguments,
+ with_logs=True,
+ on_queue_update=on_queue_update,
+ )
+ except Exception as e:
+ return {"__error__": str(e)}
+
+ raw = await loop.run_in_executor(None, call)
+ if isinstance(raw, dict) and "__error__" in raw:
+ last_err = raw["__error__"]
+ self._log(f"Attempt {attempt} failed: {last_err}")
+ if retry_indefinitely or attempt < max_retries:
+ await asyncio.sleep(min(2 ** attempt, 30))
+ continue
+ msg = f"API error after {attempt} attempts: {last_err}"
+ return self._create_error_image(msg), "", msg
+ result = raw
+ break
+
+ if not result or "images" not in result or not result["images"]:
+ msg = "API returned no images"
+ return self._create_error_image(msg), "", msg
+
+ out_urls = [img.get("url") for img in result["images"] if img.get("url")]
+ if not out_urls:
+ msg = "API response missing image URLs"
+ return self._create_error_image(msg), "", msg
+
+ tensors = []
+ for i, url in enumerate(out_urls):
+ try:
+ resp = requests.get(url, timeout=120)
+ resp.raise_for_status()
+ pil = Image.open(io.BytesIO(resp.content))
+ if pil.mode != "RGB":
+ pil = pil.convert("RGB")
+ arr = np.array(pil).astype(np.float32) / 255.0
+ tensors.append(torch.from_numpy(arr).unsqueeze(0))
+ self._log(f"Downloaded result {i + 1}/{len(out_urls)} ({pil.size[0]}x{pil.size[1]})")
+ except Exception as e:
+ self._log(f"Failed to download {url}: {e}")
+
+ if not tensors:
+ msg = "All result downloads failed"
+ return self._create_error_image(msg), "", msg
+
+ combined = _pad_and_cat(tensors)
+ joined_urls = " | ".join(out_urls)
+ return combined, joined_urls, f"Success: {len(tensors)} image(s) generated"
+
+ # ------------------------------------------------------------------
+ # Entry point
+ # ------------------------------------------------------------------
+
+ def generate(self, api_key, image_count, prompt, image_size,
+ custom_width, custom_height, quality, num_images, output_format,
+ max_retries, image_ref_1,
+ mask=None, sync_mode=False, retry_indefinitely=False, **kwargs):
+ self.log_messages = []
+ if not api_key:
+ msg = "API key not provided."
+ self._log(msg)
+ return (self._create_error_image(msg), "", msg)
+
+ ref_tensors = [image_ref_1]
+ for i in range(2, int(image_count) + 1):
+ tensor = kwargs.get(f"image_ref_{i}")
+ if tensor is not None:
+ ref_tensors.append(tensor)
+
+ ref_pils: List[Image.Image] = []
+ for i, t in enumerate(ref_tensors, start=1):
+ pil = self._tensor_to_pil(t)
+ if pil is None:
+ self._log(f"image_ref_{i} is empty or invalid — skipping")
+ continue
+ ref_pils.append(pil)
+
+ if not ref_pils:
+ msg = "At least one reference image is required."
+ self._log(msg)
+ return (self._create_error_image(msg), "", msg)
+
+ mask_pil = self._tensor_to_pil(mask) if mask is not None else None
+
+ pbar = ProgressBar(1)
+
+ async def runner():
+ return await self._generate_async(
+ api_key, prompt, ref_pils, mask_pil,
+ image_size, custom_width, custom_height,
+ quality, num_images, output_format,
+ max_retries, retry_indefinitely, sync_mode,
+ )
+
+ def run_sync():
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+ try:
+ return loop.run_until_complete(runner())
+ finally:
+ loop.close()
+
+ try:
+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
+ future = executor.submit(run_sync)
+ tensor, urls, status = future.result(timeout=600)
+ except concurrent.futures.TimeoutError:
+ msg = "Processing timed out after 10 minutes"
+ self._log(msg)
+ return (self._create_error_image(msg), "", msg)
+ except Exception as e:
+ msg = f"Processing error: {e}"
+ self._log(msg)
+ return (self._create_error_image(msg), "", msg)
+ finally:
+ pbar.update_absolute(1)
+
+ full_log = "Processing Logs:\n" + "\n".join(self.log_messages) + f"\n\nStatus: {status}"
+ return (tensor, urls, full_log)
+
+
+def _pad_and_cat(tensors: List[torch.Tensor]) -> torch.Tensor:
+ """Pad a list of (1, H, W, C) tensors to the max HxW, then concat along batch dim."""
+ if len(tensors) == 1:
+ return tensors[0]
+ max_h = max(t.shape[1] for t in tensors)
+ max_w = max(t.shape[2] for t in tensors)
+ out = []
+ for t in tensors:
+ h, w = t.shape[1], t.shape[2]
+ if h == max_h and w == max_w:
+ out.append(t)
+ continue
+ pad_h, pad_w = max_h - h, max_w - w
+ pl, pr = pad_w // 2, pad_w - pad_w // 2
+ pt, pb = pad_h // 2, pad_h - pad_h // 2
+ padded = torch.nn.functional.pad(
+ t.permute(0, 3, 1, 2),
+ (pl, pr, pt, pb),
+ mode="constant", value=0,
+ ).permute(0, 2, 3, 1)
+ out.append(padded)
+ return torch.cat(out, dim=0)
diff --git a/comfyui_fill-nodes/nodes/ai/FL_Fal_Gemini_ImageEdit.py b/comfyui_fill-nodes/nodes/ai/FL_Fal_Gemini_ImageEdit.py
new file mode 100644
index 0000000000000000000000000000000000000000..988295fae9808dc61cea6626dff368244ed62246
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/FL_Fal_Gemini_ImageEdit.py
@@ -0,0 +1,424 @@
+# FL_Fal_Gemini_ImageEdit: Fal AI Gemini 3 Pro Image Edit API Node
+import os
+import uuid
+import json
+import time
+import io
+import requests
+import torch
+import numpy as np
+import fal_client
+import asyncio
+import concurrent.futures
+from typing import Tuple, List, Dict, Union, Optional
+from pathlib import Path
+from PIL import Image, ImageDraw, ImageFont
+
+from comfy.utils import ProgressBar
+
+
+class FL_Fal_Gemini_ImageEdit:
+ """
+ A ComfyUI node for the Fal AI Gemini 3 Pro Image Edit API.
+ Takes up to 10 images and a prompt to edit them using Gemini's state-of-the-art multimodal capabilities.
+ """
+
+ RETURN_TYPES = ("IMAGE", "STRING", "STRING", "STRING")
+ RETURN_NAMES = ("images", "image_urls", "description", "status_msg")
+ FUNCTION = "edit_images"
+ CATEGORY = "🏵️Fill Nodes/AI"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "api_key": ("STRING", {"multiline": False,
+ "description": "Fal AI API key"}),
+ "prompt": ("STRING", {"default": "make a photo of the man driving the car down the california coastline",
+ "multiline": True, "forceInput": True,
+ "description": "The prompt for image editing (3-50,000 characters)"}),
+ "num_images": ("INT", {"default": 1, "min": 1, "max": 4, "step": 1,
+ "description": "Number of images to generate"}),
+ "aspect_ratio": (["auto", "21:9", "16:9", "3:2", "4:3", "5:4", "1:1", "4:5", "3:4", "2:3", "9:16"],
+ {"default": "auto",
+ "description": "Aspect ratio for output images"}),
+ "resolution": (["1K", "2K", "4K"], {"default": "1K",
+ "description": "Output resolution (4K costs 2x)"}),
+ "output_format": (["jpeg", "png", "webp"], {"default": "png",
+ "description": "Output image format"}),
+ "sync_mode": ("BOOLEAN", {"default": False,
+ "description": "When true, images returned as data URIs instead of URLs"}),
+ "seed": ("INT", {"default": 0, "min": 0, "max": 666666,
+ "description": "Random seed for reproducibility (0 = random)"}),
+ "max_retries": ("INT", {"default": 3, "min": 1, "max": 5, "step": 1}),
+ },
+ "optional": {
+ "image_1": ("IMAGE", {"description": "First input image to edit"}),
+ "image_2": ("IMAGE", {"description": "Second input image to edit"}),
+ "image_3": ("IMAGE", {"description": "Third input image to edit"}),
+ "image_4": ("IMAGE", {"description": "Fourth input image to edit"}),
+ "image_5": ("IMAGE", {"description": "Fifth input image to edit"}),
+ "image_6": ("IMAGE", {"description": "Sixth input image to edit"}),
+ "image_7": ("IMAGE", {"description": "Seventh input image to edit"}),
+ "image_8": ("IMAGE", {"description": "Eighth input image to edit"}),
+ "image_9": ("IMAGE", {"description": "Ninth input image to edit"}),
+ "image_10": ("IMAGE", {"description": "Tenth input image to edit"}),
+ "enable_web_search": ("BOOLEAN", {"default": False,
+ "description": "Allow the model to use web search for latest information during generation"}),
+ }
+ }
+
+ def __init__(self):
+ self.log_messages = []
+
+ def _log(self, message):
+ timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
+ formatted_message = f"[FL_Fal_Gemini_ImageEdit] {timestamp}: {message}"
+ print(formatted_message)
+ if hasattr(self, 'log_messages'):
+ self.log_messages.append(message)
+ return message
+
+ def _create_error_image(self, error_message="API Error", width=1024, height=1024):
+ image = Image.new('RGB', (width, height), color=(0, 0, 0))
+ draw = ImageDraw.Draw(image)
+ font = None
+ try:
+ font_options = ['arial.ttf', 'DejaVuSans.ttf', 'FreeSans.ttf', 'NotoSans-Regular.ttf']
+ for font_name in font_options:
+ try:
+ font = ImageFont.truetype(font_name, 24)
+ break
+ except IOError:
+ continue
+ if font is None:
+ font = ImageFont.load_default()
+ except Exception:
+ font = ImageFont.load_default()
+
+ # Calculate text position (centered)
+ try:
+ text_bbox = draw.textbbox((0,0), error_message, font=font)
+ text_width = text_bbox[2] - text_bbox[0]
+ text_height = text_bbox[3] - text_bbox[1]
+ except AttributeError:
+ text_width, text_height = draw.textsize(error_message, font=font)
+
+ text_x = (width - text_width) / 2
+ text_y = (height - text_height) / 2
+ draw.text((text_x, text_y), error_message, fill=(255, 0, 0), font=font)
+ img_array = np.array(image).astype(np.float32) / 255.0
+ img_tensor = torch.from_numpy(img_array).unsqueeze(0)
+ self._log(f"Created error image: '{error_message}'")
+ return img_tensor
+
+ def _process_tensor_to_pil_list(self, tensor_image: Optional[torch.Tensor], image_name_prefix: str = "Image") -> Optional[List[Image.Image]]:
+ if tensor_image is None:
+ self._log(f"{image_name_prefix} input is None, skipping PIL conversion.")
+ return None
+ if not isinstance(tensor_image, torch.Tensor):
+ self._log(f"{image_name_prefix} is not a tensor (type: {type(tensor_image)}), skipping.")
+ return None
+
+ pil_images = []
+ if tensor_image.ndim == 4: # Batch of images (B, H, W, C)
+ if tensor_image.shape[0] == 0:
+ self._log(f"{image_name_prefix} batch is empty (shape: {tensor_image.shape}).")
+ return None
+ for i in range(tensor_image.shape[0]):
+ img_np = tensor_image[i].cpu().numpy()
+ img_np = (img_np * 255).astype(np.uint8)
+ pil_image = Image.fromarray(img_np)
+ self._log(f"Converted {image_name_prefix} batch item {i} (original shape: {tensor_image.shape}) to PIL Image (size: {pil_image.size}).")
+ pil_images.append(pil_image)
+ elif tensor_image.ndim == 3: # Single image (H, W, C)
+ img_np = tensor_image.cpu().numpy()
+ img_np = (img_np * 255).astype(np.uint8)
+ pil_image = Image.fromarray(img_np)
+ self._log(f"Converted single {image_name_prefix} (original shape: {tensor_image.shape}) to PIL Image (size: {pil_image.size}).")
+ pil_images.append(pil_image)
+ else:
+ self._log(f"Cannot convert {image_name_prefix} with ndim {tensor_image.ndim} (shape: {tensor_image.shape}) to PIL Image(s).")
+ return None
+
+ return pil_images if pil_images else None
+
+ def _upload_image_to_fal(self, pil_image: Image.Image, api_key: str) -> str:
+ """Upload PIL image to fal.media CDN and return the URL.
+
+ This avoids the 10MB request body size limit by uploading images
+ separately to fal's CDN instead of embedding base64 in the request.
+ """
+ try:
+ # Set the API key before upload
+ os.environ["FAL_KEY"] = api_key.strip()
+
+ # Force reimport fal_client to pick up the new API key
+ import sys
+ if 'fal_client' in sys.modules:
+ del sys.modules['fal_client']
+ import fal_client as fresh_fal_client
+
+ # Save PIL image to bytes buffer
+ buffered = io.BytesIO()
+ pil_image.save(buffered, format="PNG")
+ image_bytes = buffered.getvalue()
+
+ # Upload to fal.media CDN using fal_client
+ url = fresh_fal_client.upload(image_bytes, content_type="image/png")
+ self._log(f"Uploaded image to fal CDN: {url[:80]}...")
+ return url
+ except Exception as e:
+ self._log(f"Error uploading image to fal CDN: {str(e)}")
+ raise
+
+ async def _edit_images_async(self, api_key, prompt, input_images, num_images, aspect_ratio, resolution, output_format, sync_mode, max_retries, enable_web_search=False, seed=0):
+ try:
+ self._log(f"Starting image editing with Gemini 3 Pro - prompt: '{prompt[:50]}...'")
+
+ # Set the API key FIRST - needed for both upload and API calls
+ clean_api_key = api_key.strip()
+ os.environ["FAL_KEY"] = clean_api_key
+
+ # Upload images to fal.media CDN to avoid 10MB request body limit
+ image_urls = []
+ if input_images:
+ self._log(f"Uploading {len(input_images)} images to fal.media CDN...")
+ for i, pil_image in enumerate(input_images):
+ try:
+ img_url = self._upload_image_to_fal(pil_image, api_key)
+ image_urls.append(img_url)
+ self._log(f"Successfully uploaded image {i+1}/{len(input_images)} to CDN")
+ except Exception as e:
+ self._log(f"Error uploading image {i+1} to CDN: {str(e)}")
+ error_msg = f"Error: Failed to upload image {i+1}: {str(e)}"
+ return self._create_error_image(error_msg), "", "", error_msg
+ else:
+ error_msg = "Error: No images provided for editing"
+ return self._create_error_image(error_msg), "", "", error_msg
+
+ # Prepare the arguments for fal_client
+ arguments = {
+ "prompt": prompt,
+ "image_urls": image_urls,
+ "num_images": num_images,
+ "aspect_ratio": aspect_ratio,
+ "resolution": resolution,
+ "output_format": output_format,
+ "sync_mode": sync_mode,
+ "limit_generations": False,
+ "enable_web_search": enable_web_search
+ }
+
+ # Add seed if provided (non-zero)
+ if seed != 0:
+ arguments["seed"] = seed
+ self._log(f"Using seed: {seed}")
+
+ self._log(f"Calling Fal AI Gemini 3 Pro API with {len(image_urls)} images, {aspect_ratio} aspect ratio, {resolution} resolution...")
+
+ # Define a callback for queue updates
+ def on_queue_update(update):
+ if isinstance(update, fal_client.InProgress):
+ for log in update.logs:
+ self._log(f"API Log: {log['message']}")
+
+ # Make the API call in executor to avoid blocking
+ loop = asyncio.get_event_loop()
+
+ def make_fal_call():
+ try:
+ # Force reload the fal_client module to avoid caching issues
+ import sys
+ if 'fal_client' in sys.modules:
+ del sys.modules['fal_client']
+ import fal_client
+
+ # Make the API call using fal_client.subscribe
+ result = fal_client.subscribe(
+ "fal-ai/gemini-3-pro-image-preview/edit",
+ arguments=arguments,
+ with_logs=True,
+ on_queue_update=on_queue_update,
+ )
+ return result
+ except Exception as e:
+ self._log(f"API call error: {str(e)}")
+ return None
+
+ result = await loop.run_in_executor(None, make_fal_call)
+
+ if result is None:
+ error_msg = "Error: API call failed"
+ return self._create_error_image(error_msg), "", "", error_msg
+
+ self._log("API call completed successfully")
+
+ # Extract image URLs and description from the result
+ output_image_urls = []
+ description = ""
+
+ if "images" in result and len(result["images"]) > 0:
+ for img_info in result["images"]:
+ if "url" in img_info:
+ output_image_urls.append(img_info["url"])
+ self._log(f"Found {len(output_image_urls)} edited images in response")
+ else:
+ self._log("Warning: No images found in result")
+ error_msg = "Error: No images in API response"
+ return self._create_error_image(error_msg), "", "", error_msg
+
+ # Extract description
+ if "description" in result:
+ description = result["description"]
+ self._log(f"Received description: {description[:100]}...")
+ else:
+ description = "No description provided"
+
+ # Download and process all generated images
+ try:
+ self._log(f"Downloading {len(output_image_urls)} edited images...")
+
+ processed_images = []
+ url_list = []
+
+ for i, image_url in enumerate(output_image_urls):
+ # Download image
+ dl_response = requests.get(image_url)
+ dl_response.raise_for_status()
+
+ # Convert to PIL Image
+ pil_image = Image.open(io.BytesIO(dl_response.content))
+
+ # Convert to RGB if necessary
+ if pil_image.mode != 'RGB':
+ pil_image = pil_image.convert('RGB')
+
+ # Convert to numpy array
+ np_image = np.array(pil_image).astype(np.float32) / 255.0
+
+ # Convert to tensor (add batch dimension)
+ image_tensor = torch.from_numpy(np_image).unsqueeze(0)
+ processed_images.append(image_tensor)
+ url_list.append(image_url)
+
+ self._log(f"Processed image {i+1}/{len(output_image_urls)} with shape {image_tensor.shape}")
+
+ # Concatenate all images
+ if len(processed_images) > 1:
+ # Handle multiple images - ensure same dimensions
+ max_height = max(img.shape[1] for img in processed_images)
+ max_width = max(img.shape[2] for img in processed_images)
+
+ resized_images = []
+ for img_tensor in processed_images:
+ current_h, current_w = img_tensor.shape[1], img_tensor.shape[2]
+
+ if current_h == max_height and current_w == max_width:
+ resized_images.append(img_tensor)
+ else:
+ # Pad the image
+ pad_h = max_height - current_h
+ pad_w = max_width - current_w
+ pad_left = pad_w // 2
+ pad_right = pad_w - pad_left
+ pad_top = pad_h // 2
+ pad_bottom = pad_h - pad_top
+
+ padded_img = torch.nn.functional.pad(
+ img_tensor.permute(0, 3, 1, 2),
+ (pad_left, pad_right, pad_top, pad_bottom),
+ mode='constant',
+ value=0
+ ).permute(0, 2, 3, 1)
+
+ resized_images.append(padded_img)
+
+ combined_tensor = torch.cat(resized_images, dim=0)
+ else:
+ combined_tensor = processed_images[0]
+
+ combined_urls = " | ".join(url_list)
+
+ self._log(f"Successfully processed {len(processed_images)} images with final shape {combined_tensor.shape}")
+
+ return combined_tensor, combined_urls, description, f"Success: {len(processed_images)} images edited successfully"
+
+ except Exception as e:
+ error_msg = f"Download Error: {str(e)}"
+ self._log(error_msg)
+ return self._create_error_image(error_msg), "", "", error_msg
+
+ except Exception as e:
+ self._log(f"Error in async image editing: {str(e)}")
+ error_msg = f"Error: {str(e)}"
+ return self._create_error_image(error_msg), "", "", error_msg
+
+ def edit_images(self, api_key, prompt, num_images=1, aspect_ratio="auto", resolution="1K", output_format="png",
+ sync_mode=False, max_retries=3, seed=0, image_1=None, image_2=None, image_3=None, image_4=None,
+ image_5=None, image_6=None, image_7=None, image_8=None, image_9=None, image_10=None,
+ enable_web_search=False, **kwargs):
+ self.log_messages = []
+ if not api_key:
+ error_msg = "API key not provided."
+ self._log(error_msg)
+ error_img_instance = self._create_error_image(error_msg)
+ return (error_img_instance, "", "", error_msg)
+
+ # Collect all input images
+ input_images = []
+ input_tensors = [image_1, image_2, image_3, image_4, image_5, image_6, image_7, image_8, image_9, image_10]
+
+ for i, tensor in enumerate(input_tensors):
+ if tensor is not None:
+ pil_images = self._process_tensor_to_pil_list(tensor, f"Image{i+1}")
+ if pil_images:
+ input_images.extend(pil_images)
+
+ if not input_images:
+ error_msg = "No valid input images provided."
+ self._log(error_msg)
+ error_img_instance = self._create_error_image(error_msg)
+ return (error_img_instance, "", "", error_msg)
+
+ self._log(f"Processing {len(input_images)} input images for editing")
+
+ # Run async processing using thread pool to avoid event loop conflicts
+ def run_sync_edit():
+ """Run async edit in a new thread with its own event loop"""
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+ try:
+ return loop.run_until_complete(self._edit_images_async(
+ api_key, prompt, input_images, num_images, aspect_ratio, resolution,
+ output_format, sync_mode, max_retries, enable_web_search, seed
+ ))
+ finally:
+ loop.close()
+
+ result = None
+ try:
+ # Use thread pool executor to run async code in separate thread
+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
+ future = executor.submit(run_sync_edit)
+ result = future.result(timeout=300) # 5 minute timeout
+ except concurrent.futures.TimeoutError:
+ self._log("Processing timed out after 5 minutes")
+ error_img = self._create_error_image("Processing timeout")
+ return (error_img, "", "", "Processing timed out after 5 minutes")
+ except Exception as e:
+ self._log(f"Error in processing: {str(e)}")
+ error_img = self._create_error_image(f"Processing error: {str(e)}")
+ return (error_img, "", "", f"Processing error: {str(e)}")
+
+ if result is None:
+ error_img = self._create_error_image("Processing failed to produce results")
+ return (error_img, "", "", "Processing failed to produce results")
+
+ # Extract results
+ images, image_urls, description, status_msg = result
+
+ # Combine log messages with status
+ final_log_output = "Processing Logs:\n" + "\n".join(self.log_messages) + "\n\n" + status_msg
+
+ return (images, image_urls, description, final_log_output)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/ai/FL_Fal_Kling_AIAvatar.py b/comfyui_fill-nodes/nodes/ai/FL_Fal_Kling_AIAvatar.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba004c310b2fb3a011e7a42bcb75fcd33b676e4d
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/FL_Fal_Kling_AIAvatar.py
@@ -0,0 +1,353 @@
+# FL_Fal_Kling_AIAvatar: Fal AI Kling Video AI Avatar API Node
+import os
+import uuid
+import json
+import time
+import io
+import requests
+import torch
+import numpy as np
+import tempfile
+import cv2
+import base64
+import fal_client
+import torchaudio
+from typing import Tuple, List, Dict, Union, Optional
+from pathlib import Path
+from PIL import Image
+from tqdm import tqdm
+
+
+class FL_Fal_Kling_AIAvatar:
+ """
+ A ComfyUI node for the Fal AI Kling Video AI Avatar API.
+ Takes an image and audio to generate realistic avatar videos.
+ """
+
+ RETURN_TYPES = ("IMAGE", "AUDIO", "STRING", "STRING")
+ RETURN_NAMES = ("frames", "audio", "video_url", "status_msg")
+ FUNCTION = "generate_ai_avatar"
+ CATEGORY = "🏵️Fill Nodes/AI"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "api_key": ("STRING", {"multiline": False,
+ "description": "Fal AI API key"}),
+ "image": ("IMAGE", {"description": "Input image to use as avatar"}),
+ "audio": ("AUDIO", {"description": "Input audio tensor"}),
+ "seed": ("INT", {"default": 0, "min": 0, "max": 999999,
+ "description": "Random seed (0 = random, max 6 digits)"}),
+ "nth_frame": ("INT", {"default": 1, "min": 1, "max": 4,
+ "description": "Extract every Nth frame (1=all frames, 2=every 2nd frame, etc.)"})
+ },
+ "optional": {
+ "prompt": ("STRING", {"default": "", "multiline": True,
+ "description": "Optional text prompt to refine video generation"})
+ }
+ }
+
+ def sanitize_error_message(self, msg):
+ """Remove potentially large base64 data from error messages"""
+ if not isinstance(msg, str):
+ msg = str(msg)
+ # Replace data URIs with placeholders to avoid wall of text
+ import re
+ msg = re.sub(r'data:[^;]+;base64,[A-Za-z0-9+/=]{100,}', '', msg)
+ return msg
+
+ def generate_ai_avatar(self, api_key, image, audio, seed=0, nth_frame=1, prompt=""):
+ """
+ Generate AI Avatar video using Fal AI Kling Video AI Avatar API
+
+ Args:
+ api_key: Fal AI API key
+ image: Input image tensor to use as avatar
+ audio: Input audio tensor
+ seed: Random seed for generation (0 = random, max 6 digits)
+ nth_frame: Extract every Nth frame
+ prompt: Optional text prompt to refine video generation
+
+ Returns:
+ Tuple of (frames_tensor, audio, video_url, status_message)
+ """
+ try:
+ # Helper function for error returns
+ def error_return(error_msg):
+ empty_tensor = torch.zeros((1, 1, 1, 3))
+ empty_audio = {"waveform": torch.zeros((1, 1, 0)), "sample_rate": 44100}
+ clean_msg = self.sanitize_error_message(error_msg)
+ return empty_tensor, empty_audio, "", clean_msg
+
+ # Clear any existing FAL_KEY environment variable to prevent caching issues
+ if "FAL_KEY" in os.environ:
+ del os.environ["FAL_KEY"]
+ print("[Fal Kling AI Avatar] Cleared existing FAL_KEY environment variable")
+
+ # 1. Validate API key
+ if not api_key or api_key.strip() == "":
+ return error_return("Error: API Key is required")
+
+ # 2. Validate required inputs
+ if image is None:
+ return error_return("Error: Image input is required")
+
+ if audio is None:
+ return error_return("Error: Audio input is required")
+
+ # 3. Process seed (ensure it's within 6-digit limit)
+ if seed < 0 or seed > 999999:
+ return error_return("Error: Seed must be between 0 and 999999 (6 digits max)")
+
+ # 4. Set up tensors for processing after API key setup
+ audio_tensor_to_process = audio
+ image_tensor_to_process = image
+ print(f"[Fal Kling AI Avatar] Image and audio tensors provided, will process after API setup")
+ print(f"[Fal Kling AI Avatar] Using seed: {seed}")
+
+ print(f"[Fal Kling AI Avatar] Starting AI Avatar generation...")
+
+ # Prepare the API request
+ clean_api_key = api_key.strip()
+
+ # Prepare the arguments for fal_client (URLs will be set after upload)
+ arguments = {
+ "image_url": "", # Will be set after image upload
+ "audio_url": "" # Will be set after audio upload
+ }
+
+ # Add seed if specified (0 means random)
+ if seed > 0:
+ arguments["seed"] = seed
+
+ # Add optional prompt if provided
+ if prompt and prompt.strip():
+ arguments["prompt"] = prompt.strip()
+ print(f"[Fal Kling AI Avatar] Prompt: {prompt[:100]}{'...' if len(prompt) > 100 else ''}")
+
+ # Remove any None values from arguments
+ arguments = {k: v for k, v in arguments.items() if v is not None and v != ""}
+
+ # Print arguments without exposing potentially large base64 data
+ safe_arguments = {k: v if not (isinstance(v, str) and v.startswith('data:')) else f"" for k, v in arguments.items()}
+ print(f"[Fal Kling AI Avatar] API arguments: {safe_arguments}")
+
+ # Set the API key as an environment variable for fal_client
+ key_preview = clean_api_key[:8] + "..." if len(clean_api_key) > 8 else "invalid_key"
+ print(f"[Fal Kling AI Avatar] Using API key starting with: {key_preview}")
+
+ # Clear and set the environment variable
+ if "FAL_KEY" in os.environ:
+ del os.environ["FAL_KEY"]
+ os.environ["FAL_KEY"] = clean_api_key
+
+ print(f"[Fal Kling AI Avatar] Calling Fal AI API with fal_client...")
+
+ # Define a callback for queue updates
+ def on_queue_update(update):
+ if isinstance(update, fal_client.InProgress):
+ for log in update.logs:
+ print(f"[Fal Kling AI Avatar] Log: {log['message']}")
+
+ try:
+ # Use the Kling AI Avatar endpoint
+ endpoint = "fal-ai/kling-video/v1/pro/ai-avatar"
+ print(f"[Fal Kling AI Avatar] Using endpoint: {endpoint}")
+
+ # Force reload the fal_client module to avoid caching issues
+ import sys
+ if 'fal_client' in sys.modules:
+ del sys.modules['fal_client']
+ import fal_client
+
+ # Process audio tensor upload if needed (after fal_client is properly loaded)
+ if audio_tensor_to_process is not None:
+ try:
+ # Convert audio tensor to temporary file and upload to Fal
+ with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as temp_audio:
+ temp_audio_path = temp_audio.name
+
+ # Save audio tensor to temporary file
+ waveform = audio_tensor_to_process['waveform']
+ sample_rate = audio_tensor_to_process['sample_rate']
+
+ # Ensure waveform is in correct format for torchaudio.save
+ if len(waveform.shape) == 3: # [batch, channels, samples]
+ waveform = waveform.squeeze(0) # Remove batch dimension
+
+ torchaudio.save(temp_audio_path, waveform, sample_rate)
+ print(f"[Fal Kling AI Avatar] Saved audio tensor to temporary file: {temp_audio_path}")
+
+ # Upload to Fal
+ final_audio_url = fal_client.upload_file(temp_audio_path)
+ print(f"[Fal Kling AI Avatar] Uploaded audio to Fal: {final_audio_url}")
+
+ # Update arguments with the uploaded audio URL
+ arguments["audio_url"] = final_audio_url
+
+ # Clean up temporary file
+ os.unlink(temp_audio_path)
+
+ except Exception as e:
+ print(f"[Fal Kling AI Avatar] Error processing audio tensor: {str(e)}")
+ return error_return(f"Error: Failed to process audio: {str(e)}")
+
+ # Process image tensor upload if needed (after fal_client is properly loaded)
+ if image_tensor_to_process is not None:
+ try:
+ # Convert image tensor to temporary file and upload to Fal
+ with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as temp_image:
+ temp_image_path = temp_image.name
+
+ # Convert image tensor to PIL Image
+ if len(image_tensor_to_process.shape) == 4:
+ image_tensor = image_tensor_to_process[0]
+ else:
+ image_tensor = image_tensor_to_process
+
+ # Convert to uint8
+ if image_tensor.dtype != torch.uint8:
+ image_tensor = (image_tensor * 255).to(torch.uint8)
+
+ # Convert to numpy for PIL
+ np_img = image_tensor.cpu().numpy()
+ pil_image = Image.fromarray(np_img)
+
+ # Save to temporary file
+ pil_image.save(temp_image_path, format="PNG")
+ print(f"[Fal Kling AI Avatar] Saved image tensor to temporary file: {temp_image_path}")
+
+ # Upload to Fal
+ final_image_url = fal_client.upload_file(temp_image_path)
+ print(f"[Fal Kling AI Avatar] Uploaded image to Fal: {final_image_url}")
+
+ # Update arguments with the uploaded image URL
+ arguments["image_url"] = final_image_url
+
+ # Clean up temporary file
+ os.unlink(temp_image_path)
+
+ except Exception as e:
+ print(f"[Fal Kling AI Avatar] Error processing image tensor: {str(e)}")
+ return error_return(f"Error: Failed to process image: {str(e)}")
+
+ # Make the API call using fal_client.subscribe
+ print(f"[Fal Kling AI Avatar] Making API call with fal_client.subscribe...")
+ result = fal_client.subscribe(
+ endpoint,
+ arguments=arguments,
+ with_logs=True,
+ on_queue_update=on_queue_update,
+ )
+
+ print(f"[Fal Kling AI Avatar] API call completed successfully")
+ except Exception as e:
+ error_msg = f"API Error: {str(e)}"
+ print(f"[Fal Kling AI Avatar] {error_msg}")
+ return error_return(error_msg)
+
+ # Extract video URL from the result
+ if "video" in result and "url" in result["video"]:
+ output_video_url = result["video"]["url"]
+ print(f"[Fal Kling AI Avatar] Video ready! URL: {output_video_url}")
+
+ # Download and process the video
+ try:
+ print(f"[Fal Kling AI Avatar] Downloading video...")
+
+ # Create a temporary file
+ with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_video:
+ temp_video_path = temp_video.name
+
+ # Download video to temp file
+ dl_response = requests.get(output_video_url, stream=True)
+ dl_response.raise_for_status()
+
+ # Get file size for progress bar
+ file_size = int(dl_response.headers.get('content-length', 0))
+ progress_bar = tqdm(total=file_size, unit='B', unit_scale=True, desc="Downloading AI Avatar Video")
+
+ for chunk in dl_response.iter_content(chunk_size=8192):
+ temp_video.write(chunk)
+ progress_bar.update(len(chunk))
+
+ progress_bar.close()
+
+ # Extract frames using OpenCV
+ print(f"[Fal Kling AI Avatar] Extracting frames from video...")
+ cap = cv2.VideoCapture(temp_video_path)
+
+ if not cap.isOpened():
+ os.unlink(temp_video_path) # Clean up temp file
+ return error_return("Could not open video file")
+
+ # Get video properties
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
+ fps = cap.get(cv2.CAP_PROP_FPS)
+
+ print(f"[Fal Kling AI Avatar] Video has {total_frames} frames at {fps} FPS")
+
+ frames = []
+ frame_count = 0
+
+ # Use nth_frame directly as the stride
+ stride = nth_frame
+
+ # Calculate approximately how many frames we'll extract
+ frames_to_extract = total_frames // stride + (1 if total_frames % stride > 0 else 0)
+
+ progress_bar = tqdm(total=frames_to_extract, desc="Extracting frames")
+
+ while cap.isOpened():
+ ret, frame = cap.read()
+ if not ret:
+ break
+
+ if frame_count % stride == 0 and len(frames) < frames_to_extract:
+ # Convert BGR to RGB (OpenCV uses BGR by default)
+ rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
+
+ # Normalize to 0-1 range for ComfyUI
+ normalized_frame = rgb_frame.astype(np.float32) / 255.0
+
+ frames.append(normalized_frame)
+ progress_bar.update(1)
+
+ # Break if we've extracted enough frames
+ if len(frames) >= frames_to_extract:
+ break
+
+ frame_count += 1
+
+ progress_bar.close()
+ cap.release()
+
+ # Clean up temp file
+ os.unlink(temp_video_path)
+
+ # Convert frames to tensor
+ if frames:
+ frames_tensor = torch.from_numpy(np.stack(frames))
+ print(f"[Fal Kling AI Avatar] Extracted {len(frames)} frames as tensor with shape {frames_tensor.shape}")
+
+ # Prepare audio output - use the original input audio if provided
+ output_audio = audio if audio is not None else {"waveform": torch.zeros((1, 1, 0)), "sample_rate": 44100}
+
+ return frames_tensor, output_audio, output_video_url, "Success: AI Avatar video generated and processed"
+ else:
+ return error_return("No frames could be extracted")
+
+ except Exception as e:
+ return error_return(f"Processing Error: {str(e)}")
+ else:
+ return error_return("No video URL in API response")
+
+ except Exception as e:
+ print(f"[Fal Kling AI Avatar] Error: {str(e)}")
+ # Try to return proper empty tensors
+ empty_tensor = torch.zeros((1, 1, 1, 3))
+ empty_audio = {"waveform": torch.zeros((1, 1, 0)), "sample_rate": 44100}
+ # Sanitize error message to remove potential base64 data
+ clean_error = self.sanitize_error_message(f"Error: {str(e)}")
+ return empty_tensor, empty_audio, "", clean_error
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/ai/FL_Fal_Kontext.py b/comfyui_fill-nodes/nodes/ai/FL_Fal_Kontext.py
new file mode 100644
index 0000000000000000000000000000000000000000..95ea1e5394cc7caf59c5f59367db19c1202ba782
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/FL_Fal_Kontext.py
@@ -0,0 +1,456 @@
+# FL_Fal_Kontext: Fal AI Flux Pro Kontext API Node with async support
+import os
+import uuid
+import json
+import time
+import io
+import requests
+import torch
+import numpy as np
+import fal_client
+import asyncio
+import concurrent.futures
+import random
+from typing import Tuple, List, Dict, Union, Optional
+from pathlib import Path
+from PIL import Image, ImageDraw, ImageFont
+
+from comfy.utils import ProgressBar
+
+
+class FL_Fal_Kontext:
+ """
+ A ComfyUI node for the Fal AI Flux Pro Kontext API.
+ Takes multiple image/prompt pairs and generates new images using Fal AI's flux-pro/kontext endpoint.
+ Supports async processing for multiple inputs.
+ """
+
+ RETURN_TYPES = ("IMAGE", "STRING", "STRING")
+ RETURN_NAMES = ("images", "image_urls", "status_msg")
+ FUNCTION = "generate_images_advanced"
+ CATEGORY = "🏵️Fill Nodes/AI"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "inputcount": ("INT", {"default": 1, "min": 1, "max": 100, "step": 1}),
+ "api_key": ("STRING", {"multiline": False,
+ "description": "Fal AI API key"}),
+ "seed": ("INT", {"default": 0, "min": 0, "max": 2147483647,
+ "description": "Random seed for image generation (0 = random)"}),
+ "max_retries": ("INT", {"default": 3, "min": 1, "max": 5, "step": 1}),
+ "prompt_1": ("STRING", {"default": "Put a donut next to the flour.",
+ "multiline": True, "forceInput": True,
+ "description": "Text prompt describing what to add or modify in the image"}),
+ "guidance_scale": ("FLOAT", {"default": 3.5, "min": 1.0, "max": 20.0, "step": 0.1,
+ "description": "CFG scale - how closely to follow the prompt"}),
+ "num_images": ("INT", {"default": 1, "min": 1, "max": 4, "step": 1,
+ "description": "Number of images to generate per input"}),
+ "aspect_ratio": (["21:9", "16:9", "4:3", "3:2", "1:1", "2:3", "3:4", "9:16", "9:21"],
+ {"default": "1:1", "description": "Aspect ratio of generated images"}),
+ "output_format": (["jpeg", "png"], {"default": "jpeg",
+ "description": "Output image format"}),
+ "safety_tolerance": (["1", "2", "3", "4", "5", "6"], {"default": "2",
+ "description": "Safety tolerance (1=strict, 6=permissive)"}),
+ },
+ "optional": {
+ "image_1": ("IMAGE", {"description": "Input image to modify"}),
+ "retry_indefinitely": ("BOOLEAN", {"default": False}),
+ "sync_mode": ("BOOLEAN", {"default": False,
+ "description": "Wait for image generation before returning (higher latency)"}),
+ }
+ }
+
+ def __init__(self):
+ self.log_messages = []
+
+ def _log(self, message):
+ timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
+ formatted_message = f"[FL_Fal_Kontext] {timestamp}: {message}"
+ print(formatted_message)
+ if hasattr(self, 'log_messages'):
+ self.log_messages.append(message)
+ return message
+
+ def _create_error_image(self, error_message="API Error", width=1024, height=1024):
+ image = Image.new('RGB', (width, height), color=(0, 0, 0))
+ draw = ImageDraw.Draw(image)
+ font = None
+ try:
+ font_options = ['arial.ttf', 'DejaVuSans.ttf', 'FreeSans.ttf', 'NotoSans-Regular.ttf']
+ for font_name in font_options:
+ try:
+ font = ImageFont.truetype(font_name, 24)
+ break
+ except IOError:
+ continue
+ if font is None:
+ font = ImageFont.load_default()
+ except Exception:
+ font = ImageFont.load_default()
+
+ # Calculate text position (centered)
+ try:
+ text_bbox = draw.textbbox((0,0), error_message, font=font)
+ text_width = text_bbox[2] - text_bbox[0]
+ text_height = text_bbox[3] - text_bbox[1]
+ except AttributeError:
+ text_width, text_height = draw.textsize(error_message, font=font)
+
+ text_x = (width - text_width) / 2
+ text_y = (height - text_height) / 2
+ draw.text((text_x, text_y), error_message, fill=(255, 0, 0), font=font)
+ img_array = np.array(image).astype(np.float32) / 255.0
+ img_tensor = torch.from_numpy(img_array).unsqueeze(0)
+ self._log(f"Created error image: '{error_message}'")
+ return img_tensor
+
+ def _process_tensor_to_pil_list(self, tensor_image: Optional[torch.Tensor], image_name_prefix: str = "Image") -> Optional[List[Image.Image]]:
+ if tensor_image is None:
+ self._log(f"{image_name_prefix} input is None, skipping PIL conversion.")
+ return None
+ if not isinstance(tensor_image, torch.Tensor):
+ self._log(f"{image_name_prefix} is not a tensor (type: {type(tensor_image)}), skipping.")
+ return None
+
+ pil_images = []
+ if tensor_image.ndim == 4: # Batch of images (B, H, W, C)
+ if tensor_image.shape[0] == 0:
+ self._log(f"{image_name_prefix} batch is empty (shape: {tensor_image.shape}).")
+ return None
+ for i in range(tensor_image.shape[0]):
+ img_np = tensor_image[i].cpu().numpy()
+ img_np = (img_np * 255).astype(np.uint8)
+ pil_image = Image.fromarray(img_np)
+ self._log(f"Converted {image_name_prefix} batch item {i} (original shape: {tensor_image.shape}) to PIL Image (size: {pil_image.size}).")
+ pil_images.append(pil_image)
+ elif tensor_image.ndim == 3: # Single image (H, W, C)
+ img_np = tensor_image.cpu().numpy()
+ img_np = (img_np * 255).astype(np.uint8)
+ pil_image = Image.fromarray(img_np)
+ self._log(f"Converted single {image_name_prefix} (original shape: {tensor_image.shape}) to PIL Image (size: {pil_image.size}).")
+ pil_images.append(pil_image)
+ else:
+ self._log(f"Cannot convert {image_name_prefix} with ndim {tensor_image.ndim} (shape: {tensor_image.shape}) to PIL Image(s).")
+ return None
+
+ return pil_images if pil_images else None
+
+ async def _generate_single_image_async(self, api_key, prompt_text, input_pil_images: Optional[List[Image.Image]], seed_val, max_retries, retry_indefinitely, guidance_scale, num_images, aspect_ratio, output_format, safety_tolerance, sync_mode, call_id):
+ try:
+ # Calculate seed
+ actual_seed = seed_val if seed_val != 0 else random.randint(1, 2147483647)
+
+ self._log(f"[Call {call_id}] Generating image with seed {actual_seed} for prompt: '{prompt_text[:50]}...'")
+
+ # Set API key FIRST - needed for CDN upload
+ clean_api_key = api_key.strip()
+ os.environ["FAL_KEY"] = clean_api_key
+
+ # Upload image to fal.media CDN
+ img_url = None
+ if input_pil_images and len(input_pil_images) > 0:
+ pil_image = input_pil_images[0] # Take first image
+ try:
+ # Upload PIL image to fal.media CDN
+ self._log(f"[Call {call_id}] Uploading image to fal.media CDN...")
+ buffered = io.BytesIO()
+ pil_image.save(buffered, format="PNG")
+ image_bytes = buffered.getvalue()
+ img_url = fal_client.upload(image_bytes, content_type="image/png")
+ self._log(f"[Call {call_id}] Uploaded image to CDN: {img_url[:80]}...")
+ except Exception as e:
+ self._log(f"[Call {call_id}] Error uploading image to CDN: {str(e)}")
+ error_msg = f"Call {call_id} Error: Failed to upload image: {str(e)}"
+ return self._create_error_image(error_msg), "", error_msg, call_id
+ else:
+ error_msg = f"Call {call_id} Error: No image provided"
+ return self._create_error_image(error_msg), "", error_msg, call_id
+
+ # Prepare the arguments for fal_client
+ arguments = {
+ "prompt": prompt_text,
+ "image_url": img_url,
+ "seed": actual_seed,
+ "guidance_scale": guidance_scale,
+ "num_images": num_images,
+ "aspect_ratio": aspect_ratio,
+ "output_format": output_format,
+ "safety_tolerance": safety_tolerance,
+ "sync_mode": sync_mode
+ }
+
+ self._log(f"[Call {call_id}] Calling Fal AI API with fal_client...")
+
+ # Define a callback for queue updates
+ def on_queue_update(update):
+ if isinstance(update, fal_client.InProgress):
+ for log in update.logs:
+ self._log(f"[Call {call_id}] API Log: {log['message']}")
+
+ # Make the API call in executor to avoid blocking
+ loop = asyncio.get_event_loop()
+
+ def make_fal_call():
+ try:
+ # Force reload the fal_client module to avoid caching issues
+ import sys
+ if 'fal_client' in sys.modules:
+ del sys.modules['fal_client']
+ import fal_client
+
+ # Make the API call using fal_client.subscribe
+ result = fal_client.subscribe(
+ "fal-ai/flux-pro/kontext",
+ arguments=arguments,
+ with_logs=True,
+ on_queue_update=on_queue_update,
+ )
+ return result
+ except Exception as e:
+ self._log(f"[Call {call_id}] API call error: {str(e)}")
+ return None
+
+ result = await loop.run_in_executor(None, make_fal_call)
+
+ if result is None:
+ error_msg = f"Call {call_id} Error: API call failed"
+ return self._create_error_image(error_msg), "", error_msg, call_id
+
+ self._log(f"[Call {call_id}] API call completed successfully")
+
+ # Extract image URLs from the result
+ image_urls = []
+ if "images" in result and len(result["images"]) > 0:
+ for img_info in result["images"]:
+ if "url" in img_info:
+ image_urls.append(img_info["url"])
+ self._log(f"[Call {call_id}] Found {len(image_urls)} images in response")
+ elif "image" in result and "url" in result["image"]:
+ image_urls.append(result["image"]["url"])
+ self._log(f"[Call {call_id}] Found 1 image in response (legacy format)")
+ else:
+ self._log(f"[Call {call_id}] Warning: No image URLs found in result")
+ error_msg = f"Call {call_id} Error: No image URLs in API response"
+ return self._create_error_image(error_msg), "", error_msg, call_id
+
+ # Download and process all generated images
+ try:
+ self._log(f"[Call {call_id}] Downloading {len(image_urls)} generated images...")
+
+ processed_images = []
+ url_list = []
+
+ for i, image_url in enumerate(image_urls):
+ # Download image
+ dl_response = requests.get(image_url)
+ dl_response.raise_for_status()
+
+ # Convert to PIL Image
+ pil_image = Image.open(io.BytesIO(dl_response.content))
+
+ # Convert to RGB if necessary
+ if pil_image.mode != 'RGB':
+ pil_image = pil_image.convert('RGB')
+
+ # Convert to numpy array
+ np_image = np.array(pil_image).astype(np.float32) / 255.0
+
+ # Convert to tensor (add batch dimension)
+ image_tensor = torch.from_numpy(np_image).unsqueeze(0)
+ processed_images.append(image_tensor)
+ url_list.append(image_url)
+
+ self._log(f"[Call {call_id}] Processed image {i+1}/{len(image_urls)} with shape {image_tensor.shape}")
+
+ # Concatenate all images from this API call
+ if len(processed_images) > 1:
+ # Handle multiple images - need to ensure same dimensions
+ max_height = max(img.shape[1] for img in processed_images)
+ max_width = max(img.shape[2] for img in processed_images)
+
+ resized_images = []
+ for img_tensor in processed_images:
+ current_h, current_w = img_tensor.shape[1], img_tensor.shape[2]
+
+ if current_h == max_height and current_w == max_width:
+ resized_images.append(img_tensor)
+ else:
+ # Pad the image
+ pad_h = max_height - current_h
+ pad_w = max_width - current_w
+ pad_left = pad_w // 2
+ pad_right = pad_w - pad_left
+ pad_top = pad_h // 2
+ pad_bottom = pad_h - pad_top
+
+ padded_img = torch.nn.functional.pad(
+ img_tensor.permute(0, 3, 1, 2),
+ (pad_left, pad_right, pad_top, pad_bottom),
+ mode='constant',
+ value=0
+ ).permute(0, 2, 3, 1)
+
+ resized_images.append(padded_img)
+
+ combined_tensor = torch.cat(resized_images, dim=0)
+ else:
+ combined_tensor = processed_images[0]
+
+ combined_urls = " | ".join(url_list)
+
+ self._log(f"[Call {call_id}] Successfully processed {len(processed_images)} images with final shape {combined_tensor.shape}")
+
+ return combined_tensor, combined_urls, f"Call {call_id} Success: {len(processed_images)} images generated successfully", call_id
+
+ except Exception as e:
+ error_msg = f"Call {call_id} Download Error: {str(e)}"
+ self._log(error_msg)
+ return self._create_error_image(error_msg), "", error_msg, call_id
+
+ except Exception as e:
+ self._log(f"[Call {call_id}] Error in async generation: {str(e)}")
+ error_msg = f"Call {call_id} Error: {str(e)}"
+ return self._create_error_image(error_msg), "", error_msg, call_id
+
+ def generate_images_advanced(self, inputcount, api_key, seed=0, max_retries=3, prompt_1="Put a donut next to the flour.", guidance_scale=3.5, num_images=1, aspect_ratio="1:1", output_format="jpeg", safety_tolerance="2", image_1=None, retry_indefinitely=False, sync_mode=False, **kwargs):
+ self.log_messages = []
+ if not api_key:
+ error_msg = "API key not provided."
+ self._log(error_msg)
+ error_img_instance = self._create_error_image(error_msg)
+ return ([error_img_instance] * inputcount, "", error_msg)
+
+ pbar = ProgressBar(inputcount) # Initialize progress bar
+
+ # Setup async tasks for each input
+ async def run_batch():
+ tasks = []
+
+ for slot_idx in range(1, inputcount + 1):
+ current_prompt = prompt_1 if slot_idx == 1 else kwargs.get(f"prompt_{slot_idx}", f"Default prompt for image {slot_idx}")
+
+ current_image_tensor_for_slot = None
+ if slot_idx == 1:
+ current_image_tensor_for_slot = image_1
+ else:
+ current_image_tensor_for_slot = kwargs.get(f"image_{slot_idx}")
+
+ pil_images_for_this_slot = self._process_tensor_to_pil_list(current_image_tensor_for_slot, f"InputSlot{slot_idx}")
+
+ current_task_seed = seed + (slot_idx - 1) if seed != 0 else 0
+ task_call_id = str(slot_idx)
+
+ tasks.append(self._generate_single_image_async(
+ api_key, current_prompt, pil_images_for_this_slot,
+ current_task_seed, max_retries, retry_indefinitely,
+ guidance_scale, num_images, aspect_ratio, output_format,
+ safety_tolerance, sync_mode, task_call_id
+ ))
+ pbar.update_absolute(slot_idx) # Update progress bar after task is added
+
+ if not tasks:
+ self._log("No tasks were created. This might indicate an issue with inputcount or logic.")
+ return []
+
+ # Run all tasks concurrently
+ return await asyncio.gather(*tasks)
+
+ # Run the async batch processing using thread pool to avoid event loop conflicts
+ def run_sync_batch():
+ """Run async batch in a new thread with its own event loop"""
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+ try:
+ return loop.run_until_complete(run_batch())
+ finally:
+ loop.close()
+
+ results_with_id = None # Initialize results
+ try:
+ # Use thread pool executor to run async code in separate thread
+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
+ future = executor.submit(run_sync_batch)
+ results_with_id = future.result(timeout=300) # 5 minute timeout
+ except concurrent.futures.TimeoutError:
+ self._log("Async processing timed out after 5 minutes")
+ error_imgs = [self._create_error_image("Processing timeout")] * inputcount
+ return (error_imgs, "", "Processing timed out after 5 minutes")
+ except Exception as e:
+ self._log(f"Error in async processing: {str(e)}")
+ # Create batch of error images
+ error_imgs = [self._create_error_image(f"Async processing error: {str(e)}")] * inputcount
+ return (error_imgs, "", f"Async processing error: {str(e)}")
+
+ # Process results (ensure results is not None if an error occurred before assignment)
+ if results_with_id is None:
+ self._log("Async processing did not yield results, possibly due to an earlier error before gather.")
+ error_imgs = [self._create_error_image("Async processing failed to produce results")] * inputcount
+ return (error_imgs, "", "Async processing failed to produce results")
+
+ results_with_id.sort(key=lambda x: int(x[3])) # Sort by call_id
+
+ output_images = []
+ output_urls = []
+ output_texts = []
+
+ for img_tensor, image_url, response_text, call_id_res in results_with_id:
+ output_images.append(img_tensor)
+ output_urls.append(f"Input {call_id_res}: {image_url}")
+ output_texts.append(f"Response for Input {call_id_res}: {response_text}")
+
+ # Handle variable image sizes by finding the maximum dimensions
+ if output_images:
+ # Find max dimensions across all images
+ max_height = max(img.shape[1] for img in output_images)
+ max_width = max(img.shape[2] for img in output_images)
+
+ self._log(f"Max dimensions found: {max_height}x{max_width}")
+
+ # Resize all images to max dimensions with padding
+ resized_images = []
+ for i, img_tensor in enumerate(output_images):
+ current_h, current_w = img_tensor.shape[1], img_tensor.shape[2]
+
+ if current_h == max_height and current_w == max_width:
+ # Image is already the right size
+ resized_images.append(img_tensor)
+ self._log(f"Image {i+1} already correct size: {current_h}x{current_w}")
+ else:
+ # Need to pad the image
+ self._log(f"Resizing image {i+1} from {current_h}x{current_w} to {max_height}x{max_width}")
+
+ # Calculate padding
+ pad_h = max_height - current_h
+ pad_w = max_width - current_w
+
+ # Pad with zeros (black) - format: (pad_left, pad_right, pad_top, pad_bottom)
+ pad_left = pad_w // 2
+ pad_right = pad_w - pad_left
+ pad_top = pad_h // 2
+ pad_bottom = pad_h - pad_top
+
+ # PyTorch pad format: (pad_left, pad_right, pad_top, pad_bottom, pad_front, pad_back)
+ # For images (B, H, W, C), we only pad H and W dimensions
+ padded_img = torch.nn.functional.pad(
+ img_tensor.permute(0, 3, 1, 2), # Convert to (B, C, H, W)
+ (pad_left, pad_right, pad_top, pad_bottom),
+ mode='constant',
+ value=0
+ ).permute(0, 2, 3, 1) # Convert back to (B, H, W, C)
+
+ resized_images.append(padded_img)
+
+ # Now concatenate all resized images
+ batched_images = torch.cat(resized_images, dim=0)
+ self._log(f"Successfully batched {len(resized_images)} images with final shape: {batched_images.shape}")
+ else:
+ batched_images = self._create_error_image("No images generated")
+
+ combined_urls = " | ".join(output_urls)
+ combined_responses = "\n\n".join(output_texts)
+
+ final_log_output = "Processing Logs:\n" + "\n".join(self.log_messages) + "\n\n" + combined_responses
+
+ return (batched_images, combined_urls, final_log_output)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/ai/FL_Fal_Pixverse.py b/comfyui_fill-nodes/nodes/ai/FL_Fal_Pixverse.py
new file mode 100644
index 0000000000000000000000000000000000000000..a79957a1af9b4c4da7ad3a90482ce8db6a0b9408
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/FL_Fal_Pixverse.py
@@ -0,0 +1,418 @@
+# FL_Fal_Pixverse: Fal AI Image-to-Video API Node with frame decomposition
+import os
+import uuid
+import json
+import time
+import io
+import requests
+import torch
+import numpy as np
+import tempfile
+import cv2
+import concurrent.futures
+import fal_client
+from typing import Tuple, List, Dict, Union, Optional
+from pathlib import Path
+from PIL import Image
+from tqdm import tqdm
+
+
+class FL_Fal_Pixverse:
+ """
+ A ComfyUI node for the Fal AI Image-to-Video API.
+ Takes an image and converts it to a video using Fal AI's pixverse/v4/image-to-video endpoint.
+ Downloads the video, extracts frames, and returns them as image tensors.
+ """
+
+ RETURN_TYPES = ("IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "STRING", "STRING")
+ RETURN_NAMES = ("frames_1", "frames_2", "frames_3", "frames_4", "frames_5", "video_urls", "status_msg")
+ FUNCTION = "generate_video"
+ CATEGORY = "🏵️Fill Nodes/AI"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "api_key": ("STRING", {"multiline": False,
+ "description": "Fal AI API key"}),
+ "prompt": ("STRING", {"default": "A woman walking through a beautiful landscape",
+ "multiline": True, "description": "Text prompt describing the video"}),
+ "aspect_ratio": (["16:9", "4:3", "1:1", "3:4", "9:16"], {"default": "16:9",
+ "description": "The aspect ratio of the generated video"}),
+ "resolution": (["360p", "540p", "720p", "1080p"], {"default": "720p",
+ "description": "The resolution of the generated video"}),
+ "duration": (["5", "8"], {"default": "5",
+ "description": "Duration in seconds (8s videos cost double, 1080p limited to 5s)"}),
+ "seed": ("INT", {"default": 0, "min": 0, "max": 2147483647,
+ "description": "Random seed for video generation (0 = random)"}),
+ "batch_size": ("INT", {"default": 1, "min": 1, "max": 5,
+ "description": "Number of videos to generate with different seeds"}),
+ "nth_frame": ("INT", {"default": 1, "min": 1, "max": 4,
+ "description": "Extract every Nth frame (1=all frames, 2=every 2nd frame, etc.)"})
+ },
+ "optional": {
+ "image": ("IMAGE", {"description": "Input image to animate"}),
+ "negative_prompt": ("STRING", {"default": "blurry, low quality, low resolution, pixelated, noisy, grainy, out of focus, poorly lit, poorly exposed, poorly composed, poorly framed, poorly cropped, poorly color corrected, poorly color graded",
+ "multiline": True, "description": "Negative prompt"}),
+ "style": (["none", "anime", "3d_animation", "clay", "comic", "cyberpunk"], {"default": "none",
+ "description": "Style of the generated video"}),
+ "camera_movement": (["none", "horizontal_left", "horizontal_right", "vertical_up", "vertical_down",
+ "zoom_in", "zoom_out", "crane_up", "quickly_zoom_in", "quickly_zoom_out",
+ "smooth_zoom_in", "camera_rotation", "robo_arm", "super_dolly_out",
+ "whip_pan", "hitchcock", "left_follow", "right_follow", "pan_left",
+ "pan_right", "fix_bg"], {"default": "none",
+ "description": "Type of camera movement to apply"})
+ }
+ }
+
+ def generate_video(self, api_key, prompt="A woman walking through a beautiful landscape", aspect_ratio="16:9",
+ resolution="720p", duration="5", seed=0, batch_size=1, nth_frame=1,
+ image=None, negative_prompt="", style="none", camera_movement="none"):
+ # Clear any existing FAL_KEY environment variable to prevent caching issues
+ if "FAL_KEY" in os.environ:
+ del os.environ["FAL_KEY"]
+ print("[Fal Pixverse] Cleared existing FAL_KEY environment variable")
+ """
+ Generate a video from an image, download it, and extract frames
+
+ Args:
+ api_key: Fal AI API key
+ prompt: Text prompt describing the video
+ negative_prompt: Negative prompt
+ duration: Video duration in seconds
+ quality: Video quality
+ seed: Random seed for video generation (0 = random)
+ batch_size: Number of videos to generate with different seeds
+ nth_frame: Extract every Nth frame (1=all frames, 2=every 2nd frame, etc.)
+ image: (Optional) Input image tensor
+
+ Returns:
+ Tuple of (frames_tensor_1, frames_tensor_2, frames_tensor_3, frames_tensor_4, frames_tensor_5,
+ video_urls, status_message)
+ Note: If batch_size < 5, the unused frame tensors will be empty (1,1,1,3) tensors
+ """
+ try:
+ # Helper function for error returns
+ def error_return(error_msg):
+ empty_tensor = torch.zeros((1, 1, 1, 3))
+ return empty_tensor, empty_tensor, empty_tensor, empty_tensor, empty_tensor, "", error_msg
+
+ # 1. Validate API key
+ if not api_key or api_key.strip() == "":
+ return error_return("Error: API Key is required")
+
+ # 2. Validate image input
+ if image is None:
+ return error_return("Error: Input image is required")
+
+ # Initialize return values
+ frame_tensors = [torch.zeros((1, 1, 1, 3)) for _ in range(5)] # 5 empty tensors by default
+ video_urls = []
+ status_messages = []
+
+ # Limit batch size to maximum of 5
+ batch_size = min(batch_size, 5)
+
+ # Validate duration for 1080p (limited to 5 seconds)
+ if resolution == "1080p" and duration == "8":
+ print(f"[Fal Pixverse] Warning: 1080p videos are limited to 5 seconds, changing duration from 8s to 5s")
+ duration = "5"
+
+ # Convert image tensor to base64
+ if image is not None:
+ # Take first image if batch
+ if len(image.shape) == 4:
+ image_tensor = image[0]
+ else:
+ image_tensor = image
+
+ # Convert to uint8
+ if image_tensor.dtype != torch.uint8:
+ image_tensor = (image_tensor * 255).to(torch.uint8)
+
+ # Convert to numpy for PIL
+ np_img = image_tensor.cpu().numpy()
+
+ try:
+ pil_image = Image.fromarray(np_img)
+ print(f"[Fal Pixverse] Successfully converted image tensor to PIL image")
+
+ # Set API key first - needed for CDN upload
+ clean_api_key = api_key.strip()
+ os.environ["FAL_KEY"] = clean_api_key
+
+ # Upload image to fal.media CDN to avoid 10MB request body limit
+ print(f"[Fal Pixverse] Uploading image to fal.media CDN...")
+ buffered = io.BytesIO()
+ pil_image.save(buffered, format="PNG")
+ image_bytes = buffered.getvalue()
+ img_url = fal_client.upload(image_bytes, content_type="image/png")
+ print(f"[Fal Pixverse] Uploaded image to CDN: {img_url[:80]}...")
+
+ except Exception as e:
+ print(f"[Fal Pixverse] Error: Failed to upload image to CDN: {str(e)}")
+ return error_return(f"Error: Failed to upload image: {str(e)}")
+ else:
+ return error_return("Error: No image provided")
+
+ # Process batches in parallel
+ def process_batch(batch_idx):
+ try:
+ # Calculate seed for this batch
+ batch_seed = np.random.randint(1, 2147483647) if seed == 0 else seed + batch_idx
+
+ print(f"[Fal Pixverse] Batch {batch_idx+1}/{batch_size}: Generating video with seed {batch_seed}...")
+
+ # Prepare the API request
+ # Ensure API key is properly formatted (trim any whitespace)
+ clean_api_key = api_key.strip()
+
+ # Prepare the arguments for fal_client
+ arguments = {
+ "prompt": prompt,
+ "image_url": img_url,
+ "aspect_ratio": aspect_ratio,
+ "resolution": resolution,
+ "duration": duration,
+ "seed": batch_seed
+ }
+
+ # Add optional parameters if provided and valid
+ if negative_prompt and negative_prompt.strip():
+ arguments["negative_prompt"] = negative_prompt.strip()
+
+ if style and style != "none" and style != "":
+ arguments["style"] = style
+
+ # Camera movement might have resolution restrictions - only add if not none and resolution is compatible
+ if camera_movement and camera_movement != "none" and camera_movement != "":
+ # Some camera movements might have resolution limits - let's be more conservative
+ if resolution in ["360p", "540p"]:
+ arguments["camera_movement"] = camera_movement
+ print(f"[Fal Pixverse] Adding camera_movement: {camera_movement} (resolution: {resolution})")
+ else:
+ print(f"[Fal Pixverse] Skipping camera_movement for {resolution} - may have restrictions")
+
+ # Keep duration as string per API documentation
+ arguments["duration"] = str(duration)
+
+ # Remove any None values from arguments
+ arguments = {k: v for k, v in arguments.items() if v is not None}
+
+ # Print arguments without exposing potentially large base64 data
+ safe_arguments = {k: v if not (isinstance(v, str) and v.startswith('data:')) else f"" for k, v in arguments.items()}
+ print(f"[Fal Pixverse] API arguments: {safe_arguments}")
+
+ # Set the API key as an environment variable for fal_client (using cleaned key)
+ # Print the first few characters of the key for debugging (don't print the whole key for security)
+ key_preview = clean_api_key[:8] + "..." if len(clean_api_key) > 8 else "invalid_key"
+ print(f"[Fal Pixverse] Using API key starting with: {key_preview}")
+
+ # Clear and set the environment variable
+ if "FAL_KEY" in os.environ:
+ del os.environ["FAL_KEY"]
+ os.environ["FAL_KEY"] = clean_api_key
+
+ print(f"[Fal Pixverse] Calling Fal AI API with fal_client...")
+
+ # Define a callback for queue updates
+ def on_queue_update(update):
+ if isinstance(update, fal_client.InProgress):
+ for log in update.logs:
+ print(f"[Fal Pixverse] Log: {log['message']}")
+
+ try:
+ # Use the new v5 endpoint
+ endpoint = "fal-ai/pixverse/v5/image-to-video"
+ print(f"[Fal Pixverse] Using v5 endpoint: {endpoint}")
+
+ # Force reload the fal_client module to avoid caching issues
+ import sys
+ if 'fal_client' in sys.modules:
+ del sys.modules['fal_client']
+ import fal_client
+
+ # Make the API call using fal_client.subscribe
+ print(f"[Fal Pixverse] Making API call with fal_client.subscribe...")
+ result = fal_client.subscribe(
+ endpoint,
+ arguments=arguments,
+ with_logs=True,
+ on_queue_update=on_queue_update,
+ )
+
+ print(f"[Fal Pixverse] API call completed successfully")
+ except Exception as e:
+ error_msg = f"API Error: {str(e)}"
+ print(f"[Fal Pixverse] {error_msg}")
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": error_msg
+ }
+
+ # Extract video URL from the result
+ if "video" in result and "url" in result["video"]:
+ video_url = result["video"]["url"]
+ print(f"[Fal Pixverse] Batch {batch_idx+1}: Video ready! URL: {video_url}")
+
+ # Download and process the video
+ try:
+ print(f"[Fal Pixverse] Batch {batch_idx+1}: Downloading video...")
+
+ # Create a temporary file
+ with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_video:
+ temp_video_path = temp_video.name
+
+ # Download video to temp file
+ dl_response = requests.get(video_url, stream=True)
+ dl_response.raise_for_status()
+
+ # Get file size for progress bar
+ file_size = int(dl_response.headers.get('content-length', 0))
+ progress_bar = tqdm(total=file_size, unit='B', unit_scale=True, desc=f"Downloading Batch {batch_idx+1}")
+
+ for chunk in dl_response.iter_content(chunk_size=8192):
+ temp_video.write(chunk)
+ progress_bar.update(len(chunk))
+
+ progress_bar.close()
+
+ # Extract frames using OpenCV
+ print(f"[Fal Pixverse] Batch {batch_idx+1}: Extracting frames from video...")
+ cap = cv2.VideoCapture(temp_video_path)
+
+ if not cap.isOpened():
+ os.unlink(temp_video_path) # Clean up temp file
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": "Could not open video file"
+ }
+
+ # Get video properties
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
+ fps = cap.get(cv2.CAP_PROP_FPS)
+
+ print(f"[Fal Pixverse] Batch {batch_idx+1}: Video has {total_frames} frames at {fps} FPS")
+
+ frames = []
+ frame_count = 0
+
+ # Use nth_frame directly as the stride
+ stride = nth_frame
+
+ # Calculate approximately how many frames we'll extract
+ frames_to_extract = total_frames // stride + (1 if total_frames % stride > 0 else 0)
+
+ progress_bar = tqdm(total=frames_to_extract, desc=f"Extracting frames (Batch {batch_idx+1})")
+
+ while cap.isOpened():
+ ret, frame = cap.read()
+ if not ret:
+ break
+
+ if frame_count % stride == 0 and len(frames) < frames_to_extract:
+ # Convert BGR to RGB (OpenCV uses BGR by default)
+ rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
+
+ # Normalize to 0-1 range for ComfyUI
+ normalized_frame = rgb_frame.astype(np.float32) / 255.0
+
+ frames.append(normalized_frame)
+ progress_bar.update(1)
+
+ # Break if we've extracted enough frames
+ if len(frames) >= frames_to_extract:
+ break
+
+ frame_count += 1
+
+ progress_bar.close()
+ cap.release()
+
+ # Clean up temp file
+ os.unlink(temp_video_path)
+
+ # Convert frames to tensor
+ if frames:
+ frames_tensor = torch.from_numpy(np.stack(frames))
+ print(f"[Fal Pixverse] Batch {batch_idx+1}: Extracted {len(frames)} frames as tensor with shape {frames_tensor.shape}")
+ return {
+ "batch_idx": batch_idx,
+ "success": True,
+ "frames_tensor": frames_tensor,
+ "video_url": video_url
+ }
+ else:
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": "No frames could be extracted"
+ }
+
+ except Exception as e:
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": f"Processing Error: {str(e)}"
+ }
+ else:
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": "No video URL in API response"
+ }
+
+ except Exception as e:
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": f"Batch processing error: {str(e)}"
+ }
+
+ # Process batches in parallel
+ results = []
+ with concurrent.futures.ThreadPoolExecutor(max_workers=batch_size) as executor:
+ future_to_batch = {
+ executor.submit(process_batch, idx): idx
+ for idx in range(batch_size)
+ }
+
+ for future in concurrent.futures.as_completed(future_to_batch):
+ batch_idx = future_to_batch[future]
+ try:
+ result = future.result()
+ results.append(result)
+ except Exception as e:
+ results.append({
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": f"Thread Error: {str(e)}"
+ })
+
+ # Collect results
+ for result in results:
+ batch_idx = result["batch_idx"]
+ if result["success"]:
+ frame_tensors[batch_idx] = result["frames_tensor"]
+ video_urls.append(f"Batch {batch_idx+1}: {result['video_url']}")
+ status_messages.append(f"Success (Batch {batch_idx+1})")
+ else:
+ video_urls.append(f"Batch {batch_idx+1}: Failed")
+ status_messages.append(f"Error (Batch {batch_idx+1}): {result['error']}")
+
+ # Combine status messages
+ combined_status = " | ".join(status_messages) if status_messages else "No videos processed"
+
+ # Combine video URLs
+ combined_urls = " | ".join(video_urls) if video_urls else "No videos generated"
+
+ # Return the results
+ return tuple(frame_tensors + [combined_urls, combined_status])
+
+ except Exception as e:
+ print(f"[Fal Pixverse] Error: {str(e)}")
+ # Try to return proper empty tensors
+ empty_tensor = torch.zeros((1, 1, 1, 3))
+ return empty_tensor, empty_tensor, empty_tensor, empty_tensor, empty_tensor, "", f"Error: {str(e)}"
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/ai/FL_Fal_Pixverse_LipSync.py b/comfyui_fill-nodes/nodes/ai/FL_Fal_Pixverse_LipSync.py
new file mode 100644
index 0000000000000000000000000000000000000000..c385e664a0899d8585af723ff74d53217906ed5a
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/FL_Fal_Pixverse_LipSync.py
@@ -0,0 +1,395 @@
+# FL_Fal_Pixverse_LipSync: Fal AI Pixverse LipSync API Node
+import os
+import uuid
+import json
+import time
+import io
+import requests
+import torch
+import numpy as np
+import tempfile
+import cv2
+import base64
+import fal_client
+import torchaudio
+from typing import Tuple, List, Dict, Union, Optional
+from pathlib import Path
+from PIL import Image
+from tqdm import tqdm
+
+
+class FL_Fal_Pixverse_LipSync:
+ """
+ A ComfyUI node for the Fal AI Pixverse LipSync API.
+ Takes a video and audio/text and generates realistic lipsync animations.
+ """
+
+ RETURN_TYPES = ("IMAGE", "AUDIO", "STRING", "STRING")
+ RETURN_NAMES = ("frames", "audio", "video_url", "status_msg")
+ FUNCTION = "generate_lipsync"
+ CATEGORY = "🏵️Fill Nodes/AI"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ voice_options = [
+ "Auto", "Emily", "James", "Isabella", "Liam", "Sophia", "Alexander",
+ "Ava", "Benjamin", "Charlotte", "Daniel", "Emma", "Gabriel", "Grace",
+ "Henry", "Luna", "Jackson", "Mia", "Lucas", "Olivia", "Matthew",
+ "Zoe", "Michael", "Aria", "Owen", "Chloe", "Samuel", "Lily"
+ ]
+
+ return {
+ "required": {
+ "api_key": ("STRING", {"multiline": False,
+ "description": "Fal AI API key"}),
+ "frames": ("IMAGE", {"description": "Input video frames as image sequence"}),
+ "mode": (["audio_input", "text_to_speech"], {"default": "audio_input",
+ "description": "Input mode: use audio file or text-to-speech"}),
+ "seed": ("INT", {"default": 0, "min": 0, "max": 999999,
+ "description": "Random seed (0 = random, max 6 digits)"}),
+ "nth_frame": ("INT", {"default": 1, "min": 1, "max": 4,
+ "description": "Extract every Nth frame (1=all frames, 2=every 2nd frame, etc.)"})
+ },
+ "optional": {
+ "audio": ("AUDIO", {"description": "Input audio tensor (for audio_input mode)"}),
+ "text": ("STRING", {"default": "Hello, this is a test message.",
+ "multiline": True, "description": "Text for speech synthesis (for text_to_speech mode)"}),
+ "voice_id": (voice_options, {"default": "Auto",
+ "description": "Voice selection for text-to-speech"})
+ }
+ }
+
+ def sanitize_error_message(self, msg):
+ """Remove potentially large base64 data from error messages"""
+ if not isinstance(msg, str):
+ msg = str(msg)
+ # Replace data URIs with placeholders to avoid wall of text
+ import re
+ msg = re.sub(r'data:[^;]+;base64,[A-Za-z0-9+/=]{100,}', '', msg)
+ return msg
+
+ def generate_lipsync(self, api_key, frames, mode="audio_input", seed=0, nth_frame=1,
+ audio=None, text="Hello, this is a test message.", voice_id="Auto"):
+ """
+ Generate lipsync video using Fal AI Pixverse LipSync API
+
+ Args:
+ api_key: Fal AI API key
+ frames: Input video frames as image sequence
+ mode: Input mode - "audio_input" or "text_to_speech"
+ seed: Random seed for generation (0 = random, max 6 digits)
+ nth_frame: Extract every Nth frame
+ audio: Input audio tensor (for audio_input mode)
+ text: Text for speech synthesis (for text_to_speech mode)
+ voice_id: Voice selection for text-to-speech
+
+ Returns:
+ Tuple of (frames_tensor, audio, video_url, status_message)
+ """
+ try:
+ # Helper function for error returns
+ def error_return(error_msg):
+ empty_tensor = torch.zeros((1, 1, 1, 3))
+ empty_audio = {"waveform": torch.zeros((1, 1, 0)), "sample_rate": 44100}
+ clean_msg = self.sanitize_error_message(error_msg)
+ return empty_tensor, empty_audio, "", clean_msg
+
+ # Clear any existing FAL_KEY environment variable to prevent caching issues
+ if "FAL_KEY" in os.environ:
+ del os.environ["FAL_KEY"]
+ print("[Fal Pixverse LipSync] Cleared existing FAL_KEY environment variable")
+
+ # 1. Validate API key
+ if not api_key or api_key.strip() == "":
+ return error_return("Error: API Key is required")
+
+ # 2. Validate frames input
+ if frames is None:
+ return error_return("Error: Frames input is required")
+
+ # 3. Process seed (ensure it's within 6-digit limit)
+ if seed < 0 or seed > 999999:
+ return error_return("Error: Seed must be between 0 and 999999 (6 digits max)")
+
+ # 4. Check audio input and validate mode - defer upload until after API key setup
+ audio_tensor_to_process = None
+ if mode == "audio_input":
+ if audio is not None:
+ audio_tensor_to_process = audio
+ print(f"[Fal Pixverse LipSync] Audio tensor provided, will process after API setup")
+ else:
+ return error_return("Error: Audio tensor is required for audio_input mode")
+ elif mode == "text_to_speech":
+ if not text or text.strip() == "":
+ return error_return("Error: Text is required for text_to_speech mode")
+ else:
+ return error_return("Error: Invalid mode. Must be 'audio_input' or 'text_to_speech'")
+
+ # 5. Set up frames for processing (convert to video after API key setup)
+ frames_to_process = frames
+ print(f"[Fal Pixverse LipSync] Frames provided, will convert to video after API setup")
+ print(f"[Fal Pixverse LipSync] Using seed: {seed}")
+
+ print(f"[Fal Pixverse LipSync] Starting lipsync generation...")
+ print(f"[Fal Pixverse LipSync] Mode: {mode}")
+
+ # Prepare the API request
+ clean_api_key = api_key.strip()
+
+ # Prepare the arguments for fal_client (video_url will be set after frames conversion)
+ arguments = {
+ "video_url": "" # Will be set after frames to video conversion
+ }
+
+ # Add seed if specified (0 means random)
+ if seed > 0:
+ arguments["seed"] = seed
+
+ # Add mode-specific parameters (URLs will be set after upload)
+ if mode == "audio_input":
+ arguments["audio_url"] = "" # Will be set after audio upload
+ elif mode == "text_to_speech":
+ arguments["text"] = text.strip()
+ arguments["voice_id"] = voice_id
+ print(f"[Fal Pixverse LipSync] Text: {text[:50]}{'...' if len(text) > 50 else ''}")
+ print(f"[Fal Pixverse LipSync] Voice ID: {voice_id}")
+
+ # Remove any None values from arguments
+ arguments = {k: v for k, v in arguments.items() if v is not None and v != ""}
+
+ # Print arguments without exposing potentially large base64 data
+ safe_arguments = {k: v if not (isinstance(v, str) and v.startswith('data:')) else f"" for k, v in arguments.items()}
+ print(f"[Fal Pixverse LipSync] API arguments: {safe_arguments}")
+
+ # Set the API key as an environment variable for fal_client
+ key_preview = clean_api_key[:8] + "..." if len(clean_api_key) > 8 else "invalid_key"
+ print(f"[Fal Pixverse LipSync] Using API key starting with: {key_preview}")
+
+ # Clear and set the environment variable
+ if "FAL_KEY" in os.environ:
+ del os.environ["FAL_KEY"]
+ os.environ["FAL_KEY"] = clean_api_key
+
+ print(f"[Fal Pixverse LipSync] Calling Fal AI API with fal_client...")
+
+ # Define a callback for queue updates
+ def on_queue_update(update):
+ if isinstance(update, fal_client.InProgress):
+ for log in update.logs:
+ print(f"[Fal Pixverse LipSync] Log: {log['message']}")
+
+ try:
+ # Use the lipsync endpoint
+ endpoint = "fal-ai/pixverse/lipsync"
+ print(f"[Fal Pixverse LipSync] Using endpoint: {endpoint}")
+
+ # Force reload the fal_client module to avoid caching issues
+ import sys
+ if 'fal_client' in sys.modules:
+ del sys.modules['fal_client']
+ import fal_client
+
+ # Process audio tensor upload if needed (after fal_client is properly loaded)
+ if audio_tensor_to_process is not None:
+ try:
+ # Convert audio tensor to temporary file and upload to Fal
+ with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as temp_audio:
+ temp_audio_path = temp_audio.name
+
+ # Save audio tensor to temporary file
+ waveform = audio_tensor_to_process['waveform']
+ sample_rate = audio_tensor_to_process['sample_rate']
+
+ # Ensure waveform is in correct format for torchaudio.save
+ if len(waveform.shape) == 3: # [batch, channels, samples]
+ waveform = waveform.squeeze(0) # Remove batch dimension
+
+ torchaudio.save(temp_audio_path, waveform, sample_rate)
+ print(f"[Fal Pixverse LipSync] Saved audio tensor to temporary file: {temp_audio_path}")
+
+ # Upload to Fal
+ final_audio_url = fal_client.upload_file(temp_audio_path)
+ print(f"[Fal Pixverse LipSync] Uploaded audio to Fal: {final_audio_url}")
+
+ # Update arguments with the uploaded audio URL
+ arguments["audio_url"] = final_audio_url
+
+ # Clean up temporary file
+ os.unlink(temp_audio_path)
+
+ except Exception as e:
+ print(f"[Fal Pixverse LipSync] Error processing audio tensor: {str(e)}")
+ return error_return(f"Error: Failed to process audio: {str(e)}")
+
+ # Process frames to video conversion and upload (after fal_client is properly loaded)
+ try:
+ # Convert frames to temporary video file and upload to Fal
+ with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_video:
+ temp_video_path = temp_video.name
+
+ print(f"[Fal Pixverse LipSync] Converting frames to video...")
+
+ # Convert frames tensor to video using OpenCV
+ if len(frames_to_process.shape) == 4: # [batch, height, width, channels]
+ frames_np = frames_to_process.cpu().numpy()
+ else:
+ frames_np = frames_to_process.unsqueeze(0).cpu().numpy()
+
+ # Convert to uint8 if needed
+ if frames_np.dtype != np.uint8:
+ frames_np = (frames_np * 255).astype(np.uint8)
+
+ # Get video properties
+ batch_size, height, width, channels = frames_np.shape
+ fps = 24 # Default FPS for video
+
+ # Create video writer
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
+ out = cv2.VideoWriter(temp_video_path, fourcc, fps, (width, height))
+
+ # Write frames to video
+ for i in range(batch_size):
+ frame = frames_np[i]
+ # Convert RGB to BGR for OpenCV
+ if channels == 3:
+ frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
+ else:
+ frame_bgr = frame
+ out.write(frame_bgr)
+
+ out.release()
+ print(f"[Fal Pixverse LipSync] Saved frames to temporary video: {temp_video_path}")
+
+ # Upload video to Fal
+ video_url = fal_client.upload_file(temp_video_path)
+ print(f"[Fal Pixverse LipSync] Uploaded video to Fal: {video_url}")
+
+ # Update arguments with the uploaded video URL
+ arguments["video_url"] = video_url
+
+ # Clean up temporary file
+ os.unlink(temp_video_path)
+
+ except Exception as e:
+ print(f"[Fal Pixverse LipSync] Error processing frames to video: {str(e)}")
+ return error_return(f"Error: Failed to convert frames to video: {str(e)}")
+
+ # Make the API call using fal_client.subscribe
+ print(f"[Fal Pixverse LipSync] Making API call with fal_client.subscribe...")
+ result = fal_client.subscribe(
+ endpoint,
+ arguments=arguments,
+ with_logs=True,
+ on_queue_update=on_queue_update,
+ )
+
+ print(f"[Fal Pixverse LipSync] API call completed successfully")
+ except Exception as e:
+ error_msg = f"API Error: {str(e)}"
+ print(f"[Fal Pixverse LipSync] {error_msg}")
+ return error_return(error_msg)
+
+ # Extract video URL from the result
+ if "video" in result and "url" in result["video"]:
+ output_video_url = result["video"]["url"]
+ print(f"[Fal Pixverse LipSync] Video ready! URL: {output_video_url}")
+
+ # Download and process the video
+ try:
+ print(f"[Fal Pixverse LipSync] Downloading video...")
+
+ # Create a temporary file
+ with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_video:
+ temp_video_path = temp_video.name
+
+ # Download video to temp file
+ dl_response = requests.get(output_video_url, stream=True)
+ dl_response.raise_for_status()
+
+ # Get file size for progress bar
+ file_size = int(dl_response.headers.get('content-length', 0))
+ progress_bar = tqdm(total=file_size, unit='B', unit_scale=True, desc="Downloading LipSync Video")
+
+ for chunk in dl_response.iter_content(chunk_size=8192):
+ temp_video.write(chunk)
+ progress_bar.update(len(chunk))
+
+ progress_bar.close()
+
+ # Extract frames using OpenCV
+ print(f"[Fal Pixverse LipSync] Extracting frames from video...")
+ cap = cv2.VideoCapture(temp_video_path)
+
+ if not cap.isOpened():
+ os.unlink(temp_video_path) # Clean up temp file
+ return error_return("Could not open video file")
+
+ # Get video properties
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
+ fps = cap.get(cv2.CAP_PROP_FPS)
+
+ print(f"[Fal Pixverse LipSync] Video has {total_frames} frames at {fps} FPS")
+
+ frames = []
+ frame_count = 0
+
+ # Use nth_frame directly as the stride
+ stride = nth_frame
+
+ # Calculate approximately how many frames we'll extract
+ frames_to_extract = total_frames // stride + (1 if total_frames % stride > 0 else 0)
+
+ progress_bar = tqdm(total=frames_to_extract, desc="Extracting frames")
+
+ while cap.isOpened():
+ ret, frame = cap.read()
+ if not ret:
+ break
+
+ if frame_count % stride == 0 and len(frames) < frames_to_extract:
+ # Convert BGR to RGB (OpenCV uses BGR by default)
+ rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
+
+ # Normalize to 0-1 range for ComfyUI
+ normalized_frame = rgb_frame.astype(np.float32) / 255.0
+
+ frames.append(normalized_frame)
+ progress_bar.update(1)
+
+ # Break if we've extracted enough frames
+ if len(frames) >= frames_to_extract:
+ break
+
+ frame_count += 1
+
+ progress_bar.close()
+ cap.release()
+
+ # Clean up temp file
+ os.unlink(temp_video_path)
+
+ # Convert frames to tensor
+ if frames:
+ frames_tensor = torch.from_numpy(np.stack(frames))
+ print(f"[Fal Pixverse LipSync] Extracted {len(frames)} frames as tensor with shape {frames_tensor.shape}")
+
+ # Prepare audio output - use the original input audio if provided, otherwise empty audio
+ output_audio = audio if audio is not None else {"waveform": torch.zeros((1, 1, 0)), "sample_rate": 44100}
+
+ return frames_tensor, output_audio, output_video_url, "Success: LipSync video generated and processed"
+ else:
+ return error_return("No frames could be extracted")
+
+ except Exception as e:
+ return error_return(f"Processing Error: {str(e)}")
+ else:
+ return error_return("No video URL in API response")
+
+ except Exception as e:
+ print(f"[Fal Pixverse LipSync] Error: {str(e)}")
+ # Try to return proper empty tensors
+ empty_tensor = torch.zeros((1, 1, 1, 3))
+ empty_audio = {"waveform": torch.zeros((1, 1, 0)), "sample_rate": 44100}
+ # Sanitize error message to remove potential base64 data
+ clean_error = self.sanitize_error_message(f"Error: {str(e)}")
+ return empty_tensor, empty_audio, "", clean_error
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/ai/FL_Fal_Pixverse_Transition.py b/comfyui_fill-nodes/nodes/ai/FL_Fal_Pixverse_Transition.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6884f0971e56d63831effd81be554e395225694
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/FL_Fal_Pixverse_Transition.py
@@ -0,0 +1,409 @@
+# FL_Fal_Pixverse_Transition: Fal AI Pixverse v5 Transition API Node with frame decomposition
+import os
+import uuid
+import json
+import time
+import io
+import requests
+import torch
+import numpy as np
+import tempfile
+import cv2
+import concurrent.futures
+import fal_client
+import asyncio
+from typing import Tuple, List, Dict, Union, Optional
+from pathlib import Path
+from PIL import Image
+from tqdm import tqdm
+
+
+class FL_Fal_Pixverse_Transition:
+ """
+ A ComfyUI node for the Fal AI Pixverse v5 Transition API.
+ Takes two images and creates a transition video between them using Fal AI's transition endpoint.
+ Downloads the video, extracts frames, and returns them as image tensors.
+ """
+
+ RETURN_TYPES = ("IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "STRING", "STRING")
+ RETURN_NAMES = ("frames_1", "frames_2", "frames_3", "frames_4", "frames_5", "video_urls", "status_msg")
+ FUNCTION = "generate_transition"
+ CATEGORY = "🏵️Fill Nodes/AI"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "api_key": ("STRING", {"multiline": False,
+ "description": "Fal AI API key"}),
+ "prompt": ("STRING", {"default": "Scene slowly transition into cat swimming under water",
+ "multiline": True, "description": "The prompt for the transition"}),
+ "aspect_ratio": (["16:9", "4:3", "1:1", "3:4", "9:16"], {"default": "16:9",
+ "description": "The aspect ratio of the generated video"}),
+ "resolution": (["360p", "540p", "720p", "1080p"], {"default": "720p",
+ "description": "The resolution of the generated video"}),
+ "duration": (["5", "8"], {"default": "5",
+ "description": "Duration in seconds (8s videos cost double, 1080p limited to 5s)"}),
+ "seed": ("INT", {"default": 0, "min": 0, "max": 2147483647,
+ "description": "Random seed for video generation (0 = random)"}),
+ "batch_size": ("INT", {"default": 1, "min": 1, "max": 5,
+ "description": "Number of videos to generate with different seeds"}),
+ "nth_frame": ("INT", {"default": 1, "min": 1, "max": 4,
+ "description": "Extract every Nth frame (1=all frames, 2=every 2nd frame, etc.)"})
+ },
+ "optional": {
+ "first_image": ("IMAGE", {"description": "First input image (start of transition)"}),
+ "last_image": ("IMAGE", {"description": "Last input image (end of transition)"}),
+ "negative_prompt": ("STRING", {"default": "blurry, low quality, low resolution, pixelated, noisy, grainy, out of focus, poorly lit, poorly exposed, poorly composed, poorly framed, poorly cropped, poorly color corrected, poorly color graded",
+ "multiline": True, "description": "Negative prompt"}),
+ "style": (["none", "anime", "3d_animation", "clay", "comic", "cyberpunk"], {"default": "none",
+ "description": "Style of the generated video"})
+ }
+ }
+
+ def generate_transition(self, api_key, prompt="Scene slowly transition into cat swimming under water", aspect_ratio="16:9",
+ resolution="720p", duration="5", seed=0, batch_size=1, nth_frame=1,
+ first_image=None, last_image=None, negative_prompt="", style="none"):
+ # Clear any existing FAL_KEY environment variable to prevent caching issues
+ if "FAL_KEY" in os.environ:
+ del os.environ["FAL_KEY"]
+ print("[Fal Pixverse Transition] Cleared existing FAL_KEY environment variable")
+ """
+ Generate a transition video between two images, download it, and extract frames
+
+ Args:
+ api_key: Fal AI API key
+ prompt: Text prompt describing the transition
+ aspect_ratio: Aspect ratio of the video
+ resolution: Video resolution
+ duration: Video duration in seconds
+ seed: Random seed for video generation (0 = random)
+ batch_size: Number of videos to generate with different seeds
+ nth_frame: Extract every Nth frame (1=all frames, 2=every 2nd frame, etc.)
+ first_image: First input image tensor (start of transition)
+ last_image: Last input image tensor (end of transition)
+ negative_prompt: Negative prompt
+ style: Video style
+
+ Returns:
+ Tuple of (frames_tensor_1, frames_tensor_2, frames_tensor_3, frames_tensor_4, frames_tensor_5,
+ video_urls, status_message)
+ Note: If batch_size < 5, the unused frame tensors will be empty (1,1,1,3) tensors
+ """
+ try:
+ # Helper function for error returns
+ def error_return(error_msg):
+ empty_tensor = torch.zeros((1, 1, 1, 3))
+ return empty_tensor, empty_tensor, empty_tensor, empty_tensor, empty_tensor, "", error_msg
+
+ # 1. Validate API key
+ if not api_key or api_key.strip() == "":
+ return error_return("Error: API Key is required")
+
+ # 2. Validate image inputs
+ if first_image is None or last_image is None:
+ return error_return("Error: Both first_image and last_image are required for transition")
+
+ # Initialize return values
+ frame_tensors = [torch.zeros((1, 1, 1, 3)) for _ in range(5)] # 5 empty tensors by default
+ video_urls = []
+ status_messages = []
+
+ # Limit batch size to maximum of 5
+ batch_size = min(batch_size, 5)
+
+ # Validate duration for 1080p (limited to 5 seconds)
+ if resolution == "1080p" and duration == "8":
+ print(f"[Fal Pixverse Transition] Warning: 1080p videos are limited to 5 seconds, changing duration from 8s to 5s")
+ duration = "5"
+
+ # Set API key FIRST - needed for CDN upload
+ clean_api_key = api_key.strip()
+ os.environ["FAL_KEY"] = clean_api_key
+
+ # Upload images to fal.media CDN
+ def upload_image_to_fal(image_tensor, image_name):
+ # Take first image if batch
+ if len(image_tensor.shape) == 4:
+ image_tensor = image_tensor[0]
+
+ # Convert to uint8
+ if image_tensor.dtype != torch.uint8:
+ image_tensor = (image_tensor * 255).to(torch.uint8)
+
+ # Convert to numpy for PIL
+ np_img = image_tensor.cpu().numpy()
+
+ try:
+ pil_image = Image.fromarray(np_img)
+ print(f"[Fal Pixverse Transition] Successfully converted {image_name} to PIL image")
+
+ # Upload to fal.media CDN
+ print(f"[Fal Pixverse Transition] Uploading {image_name} to fal.media CDN...")
+ buffered = io.BytesIO()
+ pil_image.save(buffered, format="PNG")
+ image_bytes = buffered.getvalue()
+ url = fal_client.upload(image_bytes, content_type="image/png")
+ print(f"[Fal Pixverse Transition] Uploaded {image_name} to CDN: {url[:80]}...")
+ return url
+
+ except Exception as e:
+ print(f"[Fal Pixverse Transition] Error: Failed to upload {image_name} to CDN: {str(e)}")
+ raise Exception(f"Failed to upload {image_name}: {str(e)}")
+
+ # Upload both images to CDN
+ first_image_url = upload_image_to_fal(first_image, "first_image")
+ last_image_url = upload_image_to_fal(last_image, "last_image")
+
+ # Process batches in parallel
+ def process_batch(batch_idx):
+ try:
+ # Calculate seed for this batch
+ batch_seed = np.random.randint(1, 2147483647) if seed == 0 else seed + batch_idx
+
+ print(f"[Fal Pixverse Transition] Batch {batch_idx+1}/{batch_size}: Generating transition video with seed {batch_seed}...")
+
+ # Prepare the API request
+ # Ensure API key is properly formatted (trim any whitespace)
+ clean_api_key = api_key.strip()
+
+ # Prepare the arguments for fal_client
+ arguments = {
+ "prompt": prompt,
+ "first_image_url": first_image_url,
+ "last_image_url": last_image_url,
+ "aspect_ratio": aspect_ratio,
+ "resolution": resolution,
+ "duration": duration,
+ "seed": batch_seed
+ }
+
+ # Add optional parameters if provided and valid
+ if negative_prompt and negative_prompt.strip():
+ arguments["negative_prompt"] = negative_prompt.strip()
+
+ if style and style != "none" and style != "":
+ arguments["style"] = style
+
+ # Keep duration as string per API documentation
+ arguments["duration"] = str(duration)
+
+ # Remove any None values from arguments
+ arguments = {k: v for k, v in arguments.items() if v is not None}
+
+ # Set the API key as an environment variable for fal_client (using cleaned key)
+ # Print the first few characters of the key for debugging (don't print the whole key for security)
+ key_preview = clean_api_key[:8] + "..." if len(clean_api_key) > 8 else "invalid_key"
+ print(f"[Fal Pixverse Transition] Using API key starting with: {key_preview}")
+
+ # Clear and set the environment variable
+ if "FAL_KEY" in os.environ:
+ del os.environ["FAL_KEY"]
+ os.environ["FAL_KEY"] = clean_api_key
+
+ # Print arguments without exposing potentially large base64 data
+ safe_arguments = {k: v if not (isinstance(v, str) and v.startswith('data:')) else f"" for k, v in arguments.items()}
+ print(f"[Fal Pixverse Transition] API arguments: {safe_arguments}")
+ print(f"[Fal Pixverse Transition] Calling Fal AI API with fal_client...")
+
+ # Define a callback for queue updates
+ def on_queue_update(update):
+ if isinstance(update, fal_client.InProgress):
+ for log in update.logs:
+ print(f"[Fal Pixverse Transition] Log: {log['message']}")
+
+ try:
+ # Use the v5 transition endpoint
+ endpoint = "fal-ai/pixverse/v5/transition"
+ print(f"[Fal Pixverse Transition] Using transition endpoint: {endpoint}")
+
+ # Force reload the fal_client module to avoid caching issues
+ import sys
+ if 'fal_client' in sys.modules:
+ del sys.modules['fal_client']
+ import fal_client
+
+ # Make the API call using fal_client.subscribe
+ print(f"[Fal Pixverse Transition] Making API call with fal_client.subscribe...")
+ result = fal_client.subscribe(
+ endpoint,
+ arguments=arguments,
+ with_logs=True,
+ on_queue_update=on_queue_update,
+ )
+
+ print(f"[Fal Pixverse Transition] API call completed successfully")
+ except Exception as e:
+ error_msg = f"API Error: {str(e)}"
+ print(f"[Fal Pixverse Transition] {error_msg}")
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": error_msg
+ }
+
+ # Extract video URL from the result
+ if "video" in result and "url" in result["video"]:
+ video_url = result["video"]["url"]
+ print(f"[Fal Pixverse Transition] Batch {batch_idx+1}: Video ready! URL: {video_url}")
+
+ # Download and process the video
+ try:
+ print(f"[Fal Pixverse Transition] Batch {batch_idx+1}: Downloading video...")
+
+ # Create a temporary file
+ with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_video:
+ temp_video_path = temp_video.name
+
+ # Download video to temp file
+ dl_response = requests.get(video_url, stream=True)
+ dl_response.raise_for_status()
+
+ # Get file size for progress bar
+ file_size = int(dl_response.headers.get('content-length', 0))
+ progress_bar = tqdm(total=file_size, unit='B', unit_scale=True, desc=f"Downloading Batch {batch_idx+1}")
+
+ for chunk in dl_response.iter_content(chunk_size=8192):
+ temp_video.write(chunk)
+ progress_bar.update(len(chunk))
+
+ progress_bar.close()
+
+ # Extract frames using OpenCV
+ print(f"[Fal Pixverse Transition] Batch {batch_idx+1}: Extracting frames from video...")
+ cap = cv2.VideoCapture(temp_video_path)
+
+ if not cap.isOpened():
+ os.unlink(temp_video_path) # Clean up temp file
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": "Could not open video file"
+ }
+
+ # Get video properties
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
+ fps = cap.get(cv2.CAP_PROP_FPS)
+
+ print(f"[Fal Pixverse Transition] Batch {batch_idx+1}: Video has {total_frames} frames at {fps} FPS")
+
+ frames = []
+ frame_count = 0
+
+ # Use nth_frame directly as the stride
+ stride = nth_frame
+
+ # Calculate approximately how many frames we'll extract
+ frames_to_extract = total_frames // stride + (1 if total_frames % stride > 0 else 0)
+
+ progress_bar = tqdm(total=frames_to_extract, desc=f"Extracting frames (Batch {batch_idx+1})")
+
+ while cap.isOpened():
+ ret, frame = cap.read()
+ if not ret:
+ break
+
+ if frame_count % stride == 0 and len(frames) < frames_to_extract:
+ # Convert BGR to RGB (OpenCV uses BGR by default)
+ rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
+
+ # Normalize to 0-1 range for ComfyUI
+ normalized_frame = rgb_frame.astype(np.float32) / 255.0
+
+ frames.append(normalized_frame)
+ progress_bar.update(1)
+
+ # Break if we've extracted enough frames
+ if len(frames) >= frames_to_extract:
+ break
+
+ frame_count += 1
+
+ progress_bar.close()
+ cap.release()
+
+ # Clean up temp file
+ os.unlink(temp_video_path)
+
+ # Convert frames to tensor
+ if frames:
+ frames_tensor = torch.from_numpy(np.stack(frames))
+ print(f"[Fal Pixverse Transition] Batch {batch_idx+1}: Extracted {len(frames)} frames as tensor with shape {frames_tensor.shape}")
+ return {
+ "batch_idx": batch_idx,
+ "success": True,
+ "frames_tensor": frames_tensor,
+ "video_url": video_url
+ }
+ else:
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": "No frames could be extracted"
+ }
+
+ except Exception as e:
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": f"Processing Error: {str(e)}"
+ }
+ else:
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": "No video URL in API response"
+ }
+
+ except Exception as e:
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": f"Batch processing error: {str(e)}"
+ }
+
+ # Process batches in parallel
+ results = []
+ with concurrent.futures.ThreadPoolExecutor(max_workers=batch_size) as executor:
+ future_to_batch = {
+ executor.submit(process_batch, idx): idx
+ for idx in range(batch_size)
+ }
+
+ for future in concurrent.futures.as_completed(future_to_batch):
+ batch_idx = future_to_batch[future]
+ try:
+ result = future.result()
+ results.append(result)
+ except Exception as e:
+ results.append({
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": f"Thread Error: {str(e)}"
+ })
+
+ # Collect results
+ for result in results:
+ batch_idx = result["batch_idx"]
+ if result["success"]:
+ frame_tensors[batch_idx] = result["frames_tensor"]
+ video_urls.append(f"Batch {batch_idx+1}: {result['video_url']}")
+ status_messages.append(f"Success (Batch {batch_idx+1})")
+ else:
+ video_urls.append(f"Batch {batch_idx+1}: Failed")
+ status_messages.append(f"Error (Batch {batch_idx+1}): {result['error']}")
+
+ # Combine status messages
+ combined_status = " | ".join(status_messages) if status_messages else "No videos processed"
+
+ # Combine video URLs
+ combined_urls = " | ".join(video_urls) if video_urls else "No videos generated"
+
+ # Return the results
+ return tuple(frame_tensors + [combined_urls, combined_status])
+
+ except Exception as e:
+ print(f"[Fal Pixverse Transition] Error: {str(e)}")
+ # Try to return proper empty tensors
+ empty_tensor = torch.zeros((1, 1, 1, 3))
+ return empty_tensor, empty_tensor, empty_tensor, empty_tensor, empty_tensor, "", f"Error: {str(e)}"
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/ai/FL_Fal_SeedVR_Upscale.py b/comfyui_fill-nodes/nodes/ai/FL_Fal_SeedVR_Upscale.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f2eeed852e7173a672cf3de732f76e0656ad6c5
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/FL_Fal_SeedVR_Upscale.py
@@ -0,0 +1,221 @@
+import io
+import numpy as np
+import os
+import requests
+from PIL import Image
+import torch
+from tqdm import tqdm
+import fal_client
+
+
+class FL_Fal_SeedVR_Upscale:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "api_key": ("STRING", {
+ "multiline": False,
+ "default": "",
+ "placeholder": "Enter your Fal AI API key"
+ }),
+ "image": ("IMAGE",),
+ "upscale_factor": ("FLOAT", {
+ "default": 2.0,
+ "min": 1.0,
+ "max": 10.0,
+ "step": 0.5,
+ "description": "Upscaling factor (multiplies dimensions)"
+ }),
+ "seed": ("INT", {
+ "default": -1,
+ "min": -1,
+ "max": 999999999,
+ "description": "Random seed (-1 for random)"
+ }),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE", "STRING", "INT", "INT")
+ RETURN_NAMES = ("upscaled_image", "image_url", "width", "height")
+ FUNCTION = "upscale_image"
+ CATEGORY = "🏵️Fill Nodes/AI"
+
+ def upload_tensor_to_fal(self, tensor_image):
+ """Upload tensor image to fal.media CDN and return the URL."""
+ # ComfyUI tensors are in [B, H, W, C] or [H, W, C] format
+ # Remove batch dimension if present
+ if tensor_image.dim() == 4:
+ tensor_image = tensor_image.squeeze(0)
+
+ # Ensure values are in [0, 1] range and convert to [0, 255]
+ tensor_image = (tensor_image * 255.0).clamp(0, 255)
+
+ # Convert to uint8 and then to PIL Image
+ np_image = tensor_image.cpu().numpy().astype(np.uint8)
+ pil_image = Image.fromarray(np_image)
+
+ # Upload to fal.media CDN
+ buffered = io.BytesIO()
+ pil_image.save(buffered, format="PNG")
+ image_bytes = buffered.getvalue()
+ url = fal_client.upload(image_bytes, content_type="image/png")
+ print(f"[Fal SeedVR Upscale] Uploaded image to CDN: {url[:80]}...")
+ return url
+
+ def download_image(self, image_url):
+ """Download image from URL and convert to tensor"""
+ try:
+ print(f"[Fal SeedVR Upscale] Downloading upscaled image...")
+
+ # Download image with progress bar
+ response = requests.get(image_url, stream=True)
+ response.raise_for_status()
+
+ total_size = int(response.headers.get('content-length', 0))
+
+ image_data = io.BytesIO()
+ with tqdm(total=total_size, unit='iB', unit_scale=True, desc="Downloading image") as pbar:
+ for chunk in response.iter_content(chunk_size=8192):
+ if chunk:
+ image_data.write(chunk)
+ pbar.update(len(chunk))
+
+ # Load image
+ image_data.seek(0)
+ pil_image = Image.open(image_data).convert('RGB')
+
+ # Convert to tensor
+ tensor_image = torch.from_numpy(np.array(pil_image)).float() / 255.0
+ tensor_image = tensor_image.unsqueeze(0) # Add batch dimension
+
+ print(f"[Fal SeedVR Upscale] Image downloaded successfully: {pil_image.width}x{pil_image.height}")
+
+ return tensor_image, pil_image.width, pil_image.height
+
+ except Exception as e:
+ print(f"[Fal SeedVR Upscale] Error downloading image: {str(e)}")
+ # Return a dummy black image
+ dummy_image = torch.zeros(1, 512, 512, 3)
+ return dummy_image, 512, 512
+
+ def upscale_image(self, api_key, image, upscale_factor, seed):
+ """Upscale image using Fal AI SeedVR API"""
+ if not api_key or api_key.strip() == "":
+ # Create dummy outputs
+ dummy_image = torch.zeros(1, 512, 512, 3)
+ return (dummy_image, "", 512, 512)
+
+ try:
+ # Clean and set API key FIRST - needed for CDN upload
+ clean_api_key = api_key.strip()
+ key_preview = clean_api_key[:8] + "..." if len(clean_api_key) > 8 else clean_api_key
+ print(f"[Fal SeedVR Upscale] Using API key starting with: {key_preview}")
+
+ # Clear and set the environment variable
+ if "FAL_KEY" in os.environ:
+ del os.environ["FAL_KEY"]
+ os.environ["FAL_KEY"] = clean_api_key
+
+ # Convert the first image from the batch
+ if image.dim() == 4 and image.shape[0] > 0:
+ first_image = image[0]
+ else:
+ first_image = image
+
+ # Get original dimensions
+ if image.dim() == 4:
+ original_height, original_width = image.shape[1], image.shape[2]
+ else:
+ original_height, original_width = image.shape[0], image.shape[1]
+
+ print(f"[Fal SeedVR Upscale] Original image size: {original_width}x{original_height}")
+ print(f"[Fal SeedVR Upscale] Upscale factor: {upscale_factor}x")
+ print(f"[Fal SeedVR Upscale] Expected output size: {int(original_width * upscale_factor)}x{int(original_height * upscale_factor)}")
+
+ # Upload image to fal.media CDN
+ print(f"[Fal SeedVR Upscale] Uploading image to fal.media CDN...")
+ image_url = self.upload_tensor_to_fal(first_image)
+
+ # Prepare arguments
+ arguments = {
+ "image_url": image_url,
+ "upscale_factor": upscale_factor
+ }
+
+ # Add seed if specified
+ if seed >= 0:
+ arguments["seed"] = seed
+ print(f"[Fal SeedVR Upscale] Using seed: {seed}")
+
+ # Print arguments without exposing potentially large base64 data
+ safe_arguments = {k: v if not (isinstance(v, str) and v.startswith('data:')) else f"" for k, v in arguments.items()}
+ print(f"[Fal SeedVR Upscale] Making API call with arguments: {safe_arguments}")
+
+ # Force reload the fal_client module to avoid caching issues
+ import sys
+ if 'fal_client' in sys.modules:
+ del sys.modules['fal_client']
+ import fal_client
+
+ # Submit the request synchronously
+ print(f"[Fal SeedVR Upscale] Submitting upscale request...")
+ result = fal_client.subscribe(
+ "fal-ai/seedvr/upscale/image",
+ arguments=arguments,
+ with_logs=True
+ )
+
+ print(f"[Fal SeedVR Upscale] API call completed successfully")
+
+ # Extract result
+ if result and "image" in result:
+ image_data = result["image"]
+ image_url = image_data.get("url", "")
+ output_width = image_data.get("width", 0)
+ output_height = image_data.get("height", 0)
+ used_seed = result.get("seed", seed)
+
+ print(f"[Fal SeedVR Upscale] Upscaled image URL: {image_url}")
+ print(f"[Fal SeedVR Upscale] Output dimensions: {output_width}x{output_height}")
+ print(f"[Fal SeedVR Upscale] Used seed: {used_seed}")
+
+ # Download the upscaled image
+ upscaled_tensor, actual_width, actual_height = self.download_image(image_url)
+
+ status_message = f"Successfully upscaled image {upscale_factor}x using Fal AI SeedVR. Output: {actual_width}x{actual_height}"
+ print(f"[Fal SeedVR Upscale] {status_message}")
+
+ return (upscaled_tensor, image_url, actual_width, actual_height)
+
+ else:
+ error_msg = "No image data in API response"
+ print(f"[Fal SeedVR Upscale] {error_msg}")
+ print(f"[Fal SeedVR Upscale] Full response: {result}")
+ # Return dummy outputs
+ dummy_image = torch.zeros(1, 512, 512, 3)
+ return (dummy_image, "", 512, 512)
+
+ except Exception as e:
+ error_msg = f"Error in image upscaling: {str(e)}"
+ print(f"[Fal SeedVR Upscale] {error_msg}")
+
+ # Print traceback for debugging
+ import traceback
+ traceback.print_exc()
+
+ # Return dummy outputs
+ dummy_image = torch.zeros(1, 512, 512, 3)
+ return (dummy_image, "", 512, 512)
+
+
+# Node registration
+NODE_CLASS_MAPPINGS = {
+ "FL_Fal_SeedVR_Upscale": FL_Fal_SeedVR_Upscale
+}
+
+NODE_DISPLAY_NAME_MAPPINGS = {
+ "FL_Fal_SeedVR_Upscale": "FL Fal SeedVR Upscale"
+}
diff --git a/comfyui_fill-nodes/nodes/ai/FL_Fal_Seedance_i2v.py b/comfyui_fill-nodes/nodes/ai/FL_Fal_Seedance_i2v.py
new file mode 100644
index 0000000000000000000000000000000000000000..e805e677ee49f398e514a0efdf4c5a4639f9b2a9
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/FL_Fal_Seedance_i2v.py
@@ -0,0 +1,253 @@
+import io
+import numpy as np
+import os
+import tempfile
+import requests
+from PIL import Image
+import torch
+import cv2
+from tqdm import tqdm
+import fal_client
+
+class FL_Fal_Seedance_i2v:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "api_key": ("STRING", {
+ "multiline": False,
+ "default": "",
+ "placeholder": "Enter your Fal AI API key"
+ }),
+ "image": ("IMAGE",),
+ "prompt": ("STRING", {
+ "multiline": True,
+ "default": "",
+ "placeholder": "Describe the video animation you want to create"
+ }),
+ "cut_prompt_1": ("STRING",),
+ "cut_prompt_2": ("STRING",),
+ "cut_prompt_3": ("STRING",),
+ "cut_prompt_4": ("STRING",),
+ "resolution": (["480p", "720p", "1080p"], {
+ "default": "720p"
+ }),
+ "duration": ("INT", {
+ "default": 6,
+ "min": 3,
+ "max": 12,
+ "step": 1
+ }),
+ "camera_fixed": ("BOOLEAN", {
+ "default": True
+ }),
+ "seed": ("INT", {
+ "default": -1,
+ "min": -1,
+ "max": 999999999
+ }),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE", "STRING", "STRING")
+ RETURN_NAMES = ("frames", "video_url", "status_message")
+ FUNCTION = "generate_video"
+ CATEGORY = "🏵️Fill Nodes/AI"
+
+ def upload_tensor_to_fal(self, tensor_image):
+ """Upload tensor image to fal.media CDN and return the URL."""
+ # Convert tensor to PIL Image
+ if tensor_image.dim() == 4:
+ tensor_image = tensor_image.squeeze(0)
+ if tensor_image.shape[0] == 3: # CHW to HWC
+ tensor_image = tensor_image.permute(1, 2, 0)
+
+ # Ensure values are in [0, 1] range and convert to [0, 255]
+ if tensor_image.max() <= 1.0:
+ tensor_image = (tensor_image * 255).clamp(0, 255)
+
+ # Convert to uint8 and then to PIL Image
+ np_image = tensor_image.cpu().numpy().astype(np.uint8)
+ pil_image = Image.fromarray(np_image)
+
+ # Upload to fal.media CDN
+ buffered = io.BytesIO()
+ pil_image.save(buffered, format="PNG")
+ image_bytes = buffered.getvalue()
+ url = fal_client.upload(image_bytes, content_type="image/png")
+ return url
+
+ def download_video_frames(self, video_url):
+ """Download video and extract all frames"""
+ try:
+ # Create temporary directory
+ with tempfile.TemporaryDirectory() as temp_dir:
+ video_path = os.path.join(temp_dir, "video.mp4")
+
+ # Download video with progress bar
+ response = requests.get(video_url, stream=True)
+ response.raise_for_status()
+
+ total_size = int(response.headers.get('content-length', 0))
+
+ with open(video_path, 'wb') as f:
+ with tqdm(total=total_size, unit='iB', unit_scale=True, desc="Downloading video") as pbar:
+ for chunk in response.iter_content(chunk_size=8192):
+ if chunk:
+ f.write(chunk)
+ pbar.update(len(chunk))
+
+ # Extract frames using OpenCV
+ cap = cv2.VideoCapture(video_path)
+ frames = []
+ frame_count = 0
+
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
+
+ with tqdm(total=total_frames, desc="Extracting frames") as pbar:
+ while True:
+ ret, frame = cap.read()
+ if not ret:
+ break
+
+ # Extract every frame
+ # Convert BGR to RGB
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
+
+ # Convert to PIL Image
+ pil_image = Image.fromarray(frame_rgb)
+
+ # Convert to tensor
+ tensor_frame = torch.from_numpy(np.array(pil_image)).float() / 255.0
+ tensor_frame = tensor_frame.unsqueeze(0) # Add batch dimension
+
+ frames.append(tensor_frame)
+
+ frame_count += 1
+ pbar.update(1)
+
+ cap.release()
+
+ if frames:
+ # Stack all frames
+ all_frames = torch.cat(frames, dim=0)
+ return all_frames
+ else:
+ # Return a dummy black frame if no frames extracted
+ dummy_frame = torch.zeros(1, 512, 512, 3)
+ return dummy_frame
+
+ except Exception as e:
+ print(f"Error downloading/processing video: {str(e)}")
+ # Return a dummy black frame
+ dummy_frame = torch.zeros(1, 512, 512, 3)
+ return dummy_frame
+
+ def generate_video(self, api_key, image, prompt, resolution, duration, camera_fixed, seed,
+ cut_prompt_1="", cut_prompt_2="", cut_prompt_3="", cut_prompt_4=""):
+ if not api_key or api_key.strip() == "":
+ # Create dummy outputs
+ dummy_frames = torch.zeros(1, 512, 512, 3)
+ return (dummy_frames, "", "Error: API key is required")
+
+ try:
+ # Clean and set API key FIRST - needed for CDN upload
+ clean_api_key = api_key.strip()
+ key_preview = clean_api_key[:8] + "..." if len(clean_api_key) > 8 else clean_api_key
+ print(f"[Fal Seedance] Using API key starting with: {key_preview}")
+
+ # Clear and set the environment variable
+ if "FAL_KEY" in os.environ:
+ del os.environ["FAL_KEY"]
+ os.environ["FAL_KEY"] = clean_api_key
+
+ # Convert the first image from the batch and upload to CDN
+ if image.dim() == 4 and image.shape[0] > 0:
+ first_image = image[0]
+ else:
+ first_image = image
+
+ print(f"[Fal Seedance] Uploading image to fal.media CDN...")
+ image_url = self.upload_tensor_to_fal(first_image)
+ print(f"[Fal Seedance] Uploaded image to CDN: {image_url[:80]}...")
+
+ # Build the complete prompt with cut prompts
+ complete_prompt = prompt.strip()
+
+ # Add cut prompts if provided
+ cut_prompts = [cut_prompt_1, cut_prompt_2, cut_prompt_3, cut_prompt_4]
+ for i, cut_prompt in enumerate(cut_prompts):
+ if cut_prompt and cut_prompt.strip():
+ complete_prompt += f" [cut] {cut_prompt.strip()}"
+
+ print(f"[Fal Seedance] Complete prompt: {complete_prompt}")
+
+ # Prepare arguments
+ arguments = {
+ "image_url": image_url,
+ "prompt": complete_prompt,
+ "resolution": resolution,
+ "duration": duration,
+ "camera_fixed": camera_fixed
+ }
+
+ # Add seed if specified
+ if seed >= 0:
+ arguments["seed"] = seed
+
+ # Print arguments without exposing potentially large base64 data
+ safe_arguments = {k: v if not (isinstance(v, str) and v.startswith('data:')) else f"" for k, v in arguments.items()}
+ print(f"[Fal Seedance] Making API call with arguments: {safe_arguments}")
+
+ # Force reload the fal_client module to avoid caching issues
+ import sys
+ if 'fal_client' in sys.modules:
+ del sys.modules['fal_client']
+ import fal_client
+
+ # Submit the request synchronously
+ result = fal_client.subscribe(
+ "fal-ai/bytedance/seedance/v1/pro/image-to-video",
+ arguments=arguments,
+ with_logs=True
+ )
+
+ print(f"[Fal Seedance] API call completed successfully")
+
+ if result and "video" in result and "url" in result["video"]:
+ video_url = result["video"]["url"]
+
+ # Download and extract frames
+ all_frames = self.download_video_frames(video_url)
+
+ total_frames = all_frames.shape[0]
+ status_message = f"Successfully generated video using Fal AI Bytedance Seedance. Extracted {total_frames} frames."
+
+ return (all_frames, video_url, status_message)
+
+ else:
+ error_msg = "No video URL in API response"
+ print(f"[Fal Seedance] {error_msg}")
+ # Return dummy outputs
+ dummy_frames = torch.zeros(1, 512, 512, 3)
+ return (dummy_frames, "", error_msg)
+
+ except Exception as e:
+ error_msg = f"Error in video generation: {str(e)}"
+ print(f"[Fal Seedance] {error_msg}")
+
+ # Return dummy outputs
+ dummy_frames = torch.zeros(1, 512, 512, 3)
+ return (dummy_frames, "", error_msg)
+
+# Node registration
+NODE_CLASS_MAPPINGS = {
+ "FL_Fal_Seedance_i2v": FL_Fal_Seedance_i2v
+}
+
+NODE_DISPLAY_NAME_MAPPINGS = {
+ "FL_Fal_Seedance_i2v": "FL Fal Seedance i2v"
+}
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/ai/FL_Fal_Seedream_Edit.py b/comfyui_fill-nodes/nodes/ai/FL_Fal_Seedream_Edit.py
new file mode 100644
index 0000000000000000000000000000000000000000..bfc77da6dedda3746271ac10e78cd93c5c4dc4d0
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/FL_Fal_Seedream_Edit.py
@@ -0,0 +1,496 @@
+# FL_Fal_Seedream_Edit: Fal AI ByteDance Seedream v4 Edit API Node
+import os
+import uuid
+import json
+import time
+import io
+import requests
+import torch
+import numpy as np
+import fal_client
+import asyncio
+import concurrent.futures
+import random
+from typing import Tuple, List, Dict, Union, Optional
+from pathlib import Path
+from PIL import Image, ImageDraw, ImageFont
+
+from comfy.utils import ProgressBar
+
+
+class FL_Fal_Seedream_Edit:
+ """
+ A ComfyUI node for the Fal AI ByteDance Seedream v4 Edit API.
+ Takes multiple images and a prompt to edit them using Seedream's capabilities.
+ """
+
+ RETURN_TYPES = ("IMAGE", "STRING", "STRING", "STRING")
+ RETURN_NAMES = ("images", "image_urls", "seed", "status_msg")
+ FUNCTION = "edit_images"
+ CATEGORY = "🏵️Fill Nodes/AI"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "api_key": ("STRING", {"multiline": False,
+ "description": "Fal AI API key"}),
+ "prompt": ("STRING", {"default": "Dress the model in the clothes and shoes.",
+ "multiline": True, "forceInput": True,
+ "description": "The prompt for image editing"}),
+ "image_size": (["square_hd", "square", "portrait_4_3", "portrait_16_9", "landscape_4_3", "landscape_16_9"],
+ {"default": "square_hd", "description": "The size of the generated image"}),
+ "num_images": ("INT", {"default": 1, "min": 1, "max": 4, "step": 1,
+ "description": "Number of images to generate"}),
+ "seed": ("INT", {"default": 0, "min": 0, "max": 2147483647,
+ "description": "Random seed for image generation (0 = random)"}),
+ "sync_mode": ("BOOLEAN", {"default": False,
+ "description": "Wait for image generation before returning"}),
+ "max_retries": ("INT", {"default": 3, "min": 1, "max": 5, "step": 1}),
+ },
+ "optional": {
+ "image_1": ("IMAGE", {"description": "First input image to edit"}),
+ "image_2": ("IMAGE", {"description": "Second input image to edit"}),
+ "image_3": ("IMAGE", {"description": "Third input image to edit"}),
+ "image_4": ("IMAGE", {"description": "Fourth input image to edit"}),
+ "image_5": ("IMAGE", {"description": "Fifth input image to edit"}),
+ "image_6": ("IMAGE", {"description": "Sixth input image to edit"}),
+ "image_7": ("IMAGE", {"description": "Seventh input image to edit"}),
+ "image_8": ("IMAGE", {"description": "Eighth input image to edit"}),
+ "image_9": ("IMAGE", {"description": "Ninth input image to edit"}),
+ "image_10": ("IMAGE", {"description": "Tenth input image to edit"}),
+ "retry_indefinitely": ("BOOLEAN", {"default": False}),
+ "use_custom_resolution": ("BOOLEAN", {"default": False,
+ "description": "Override preset image size with custom width/height"}),
+ "auto_scale_to_minimum": ("BOOLEAN", {"default": True,
+ "description": "Auto-scale dimensions below 1024 to meet minimum while preserving aspect ratio"}),
+ "custom_width": ("INT", {"default": 1280, "min": 256, "max": 4096, "step": 8,
+ "description": "Custom width (auto-scaled to meet API minimums if needed)"}),
+ "custom_height": ("INT", {"default": 1280, "min": 256, "max": 4096, "step": 8,
+ "description": "Custom height (auto-scaled to meet API minimums if needed)"}),
+ }
+ }
+
+ def __init__(self):
+ self.log_messages = []
+
+ def _log(self, message):
+ timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
+ formatted_message = f"[FL_Fal_Seedream_Edit] {timestamp}: {message}"
+ print(formatted_message)
+ if hasattr(self, 'log_messages'):
+ self.log_messages.append(message)
+ return message
+
+ def _create_error_image(self, error_message="API Error", width=1024, height=1024):
+ image = Image.new('RGB', (width, height), color=(0, 0, 0))
+ draw = ImageDraw.Draw(image)
+ font = None
+ try:
+ font_options = ['arial.ttf', 'DejaVuSans.ttf', 'FreeSans.ttf', 'NotoSans-Regular.ttf']
+ for font_name in font_options:
+ try:
+ font = ImageFont.truetype(font_name, 24)
+ break
+ except IOError:
+ continue
+ if font is None:
+ font = ImageFont.load_default()
+ except Exception:
+ font = ImageFont.load_default()
+
+ # Calculate text position (centered)
+ try:
+ text_bbox = draw.textbbox((0,0), error_message, font=font)
+ text_width = text_bbox[2] - text_bbox[0]
+ text_height = text_bbox[3] - text_bbox[1]
+ except AttributeError:
+ text_width, text_height = draw.textsize(error_message, font=font)
+
+ text_x = (width - text_width) / 2
+ text_y = (height - text_height) / 2
+ draw.text((text_x, text_y), error_message, fill=(255, 0, 0), font=font)
+ img_array = np.array(image).astype(np.float32) / 255.0
+ img_tensor = torch.from_numpy(img_array).unsqueeze(0)
+ self._log(f"Created error image: '{error_message}'")
+ return img_tensor
+
+ def _process_tensor_to_pil_list(self, tensor_image: Optional[torch.Tensor], image_name_prefix: str = "Image") -> Optional[List[Image.Image]]:
+ if tensor_image is None:
+ self._log(f"{image_name_prefix} input is None, skipping PIL conversion.")
+ return None
+ if not isinstance(tensor_image, torch.Tensor):
+ self._log(f"{image_name_prefix} is not a tensor (type: {type(tensor_image)}), skipping.")
+ return None
+
+ pil_images = []
+ if tensor_image.ndim == 4: # Batch of images (B, H, W, C)
+ if tensor_image.shape[0] == 0:
+ self._log(f"{image_name_prefix} batch is empty (shape: {tensor_image.shape}).")
+ return None
+ for i in range(tensor_image.shape[0]):
+ img_np = tensor_image[i].cpu().numpy()
+ img_np = (img_np * 255).astype(np.uint8)
+ pil_image = Image.fromarray(img_np)
+ self._log(f"Converted {image_name_prefix} batch item {i} (original shape: {tensor_image.shape}) to PIL Image (size: {pil_image.size}).")
+ pil_images.append(pil_image)
+ elif tensor_image.ndim == 3: # Single image (H, W, C)
+ img_np = tensor_image.cpu().numpy()
+ img_np = (img_np * 255).astype(np.uint8)
+ pil_image = Image.fromarray(img_np)
+ self._log(f"Converted single {image_name_prefix} (original shape: {tensor_image.shape}) to PIL Image (size: {pil_image.size}).")
+ pil_images.append(pil_image)
+ else:
+ self._log(f"Cannot convert {image_name_prefix} with ndim {tensor_image.ndim} (shape: {tensor_image.shape}) to PIL Image(s).")
+ return None
+
+ return pil_images if pil_images else None
+
+ def _upload_image_to_fal(self, pil_image: Image.Image) -> str:
+ """Upload PIL image to fal.media CDN and return the URL."""
+ try:
+ # Convert RGBA to RGB if necessary (PNG handles it but let's be safe)
+ if pil_image.mode == 'RGBA':
+ background = Image.new('RGB', pil_image.size, (255, 255, 255))
+ background.paste(pil_image, mask=pil_image.split()[-1])
+ pil_image = background
+ self._log(f"Converted RGBA image to RGB with white background")
+ elif pil_image.mode != 'RGB':
+ pil_image = pil_image.convert('RGB')
+ self._log(f"Converted image mode to RGB")
+
+ # Upload to fal.media CDN
+ buffered = io.BytesIO()
+ pil_image.save(buffered, format="PNG")
+ image_bytes = buffered.getvalue()
+ url = fal_client.upload(image_bytes, content_type="image/png")
+ self._log(f"Uploaded image to fal CDN: {url[:80]}...")
+ return url
+ except Exception as e:
+ self._log(f"Error uploading image to fal CDN: {str(e)}")
+ raise
+
+ async def _edit_images_async(self, api_key, prompt, input_images, image_size, num_images, seed, sync_mode, max_retries, retry_indefinitely, use_custom_resolution, auto_scale_to_minimum, custom_width, custom_height):
+ try:
+ # Calculate seed
+ actual_seed = seed if seed != 0 else random.randint(1, 2147483647)
+
+ self._log(f"Starting image editing with seed {actual_seed} and prompt: '{prompt[:50]}...'")
+
+ # Set API key FIRST - needed for CDN upload
+ clean_api_key = api_key.strip()
+ os.environ["FAL_KEY"] = clean_api_key
+
+ # Upload images to fal.media CDN
+ image_urls = []
+ if input_images:
+ self._log(f"Uploading {len(input_images)} images to fal.media CDN...")
+ for i, pil_image in enumerate(input_images):
+ try:
+ img_url = self._upload_image_to_fal(pil_image)
+ image_urls.append(img_url)
+ self._log(f"Successfully uploaded image {i+1}/{len(input_images)} to CDN")
+ except Exception as e:
+ self._log(f"Error uploading image {i+1} to CDN: {str(e)}")
+ error_msg = f"Error: Failed to upload image {i+1}: {str(e)}"
+ return self._create_error_image(error_msg), "", str(actual_seed), error_msg
+ else:
+ error_msg = "Error: No images provided for editing"
+ return self._create_error_image(error_msg), "", str(actual_seed), error_msg
+
+ # Prepare image size parameter
+ image_size_param = image_size
+ # Check if custom dimensions are requested and valid
+ if use_custom_resolution:
+ if custom_width and custom_height and custom_width >= 1024 and custom_height >= 1024:
+ image_size_param = {
+ "width": custom_width,
+ "height": custom_height
+ }
+ self._log(f"Using custom image size: {custom_width}x{custom_height}")
+ elif custom_width and custom_height:
+ # Custom dimensions provided but below minimum
+ aspect_ratio = custom_width / custom_height
+ self._log(f"Custom dimensions {custom_width}x{custom_height} below minimum. Aspect ratio: {aspect_ratio:.2f}")
+
+ if auto_scale_to_minimum:
+ # Scale up dimensions to meet minimum while preserving aspect ratio
+ min_dimension = min(custom_width, custom_height)
+ if min_dimension < 1024:
+ scale_factor = 1024 / min_dimension
+ scaled_width = int(custom_width * scale_factor)
+ scaled_height = int(custom_height * scale_factor)
+
+ # Ensure we don't exceed maximum dimensions
+ if scaled_width > 4096 or scaled_height > 4096:
+ max_scale = min(4096 / custom_width, 4096 / custom_height)
+ scaled_width = int(custom_width * max_scale)
+ scaled_height = int(custom_height * max_scale)
+
+ # Round to nearest 64 pixels for better compatibility
+ scaled_width = (scaled_width // 64) * 64
+ scaled_height = (scaled_height // 64) * 64
+
+ # Ensure minimums after rounding
+ scaled_width = max(1024, scaled_width)
+ scaled_height = max(1024, scaled_height)
+
+ image_size_param = {
+ "width": scaled_width,
+ "height": scaled_height
+ }
+ self._log(f"Auto-scaled from {custom_width}x{custom_height} to {scaled_width}x{scaled_height} preserving aspect ratio")
+ else:
+ # Map aspect ratios to presets (with tolerance)
+ if aspect_ratio >= 2.1: # ~21:9 ratio
+ image_size_param = "landscape_16_9" # Closest available wide option
+ self._log(f"Selected landscape_16_9 based on wide aspect ratio")
+ elif aspect_ratio >= 1.6: # ~16:9 ratio
+ image_size_param = "landscape_16_9"
+ self._log(f"Selected landscape_16_9 based on 16:9 aspect ratio")
+ elif aspect_ratio >= 1.2: # ~4:3 ratio
+ image_size_param = "landscape_4_3"
+ self._log(f"Selected landscape_4_3 based on 4:3 aspect ratio")
+ elif aspect_ratio >= 0.9: # ~1:1 ratio
+ image_size_param = "square_hd" if "hd" in image_size else "square"
+ self._log(f"Selected square based on 1:1 aspect ratio")
+ elif aspect_ratio >= 0.7: # ~3:4 ratio
+ image_size_param = "portrait_4_3"
+ self._log(f"Selected portrait_4_3 based on 3:4 aspect ratio")
+ elif aspect_ratio >= 0.5: # ~9:16 ratio
+ image_size_param = "portrait_16_9"
+ self._log(f"Selected portrait_16_9 based on 9:16 aspect ratio")
+ else: # Very tall
+ image_size_param = "portrait_16_9"
+ self._log(f"Selected portrait_16_9 based on tall aspect ratio")
+ else:
+ self._log("Custom resolution requested but dimensions are invalid or missing. Using preset image size.")
+ image_size_param = image_size
+ self._log(f"Using preset image size: {image_size}")
+ else:
+ self._log(f"Using preset image size: {image_size}")
+
+ # Prepare the arguments for fal_client
+ arguments = {
+ "prompt": prompt,
+ "image_urls": image_urls,
+ "image_size": image_size_param,
+ "num_images": num_images,
+ "seed": actual_seed,
+ "sync_mode": sync_mode
+ }
+
+ self._log(f"Calling Fal AI Seedream Edit API with {len(image_urls)} images...")
+
+ # Define a callback for queue updates
+ def on_queue_update(update):
+ if isinstance(update, fal_client.InProgress):
+ for log in update.logs:
+ self._log(f"API Log: {log['message']}")
+
+ # Make the API call in executor to avoid blocking
+ loop = asyncio.get_event_loop()
+
+ def make_fal_call():
+ try:
+ # Force reload the fal_client module to avoid caching issues
+ import sys
+ if 'fal_client' in sys.modules:
+ del sys.modules['fal_client']
+ import fal_client
+
+ # Make the API call using fal_client.subscribe
+ result = fal_client.subscribe(
+ "fal-ai/bytedance/seedream/v4/edit",
+ arguments=arguments,
+ with_logs=True,
+ on_queue_update=on_queue_update,
+ )
+ return result
+ except Exception as e:
+ self._log(f"API call error: {str(e)}")
+ return None
+
+ result = await loop.run_in_executor(None, make_fal_call)
+
+ if result is None:
+ error_msg = "Error: API call failed"
+ return self._create_error_image(error_msg), "", str(actual_seed), error_msg
+
+ self._log("API call completed successfully")
+
+ # Extract image URLs and seed from the result
+ output_image_urls = []
+ returned_seed = actual_seed
+
+ if "images" in result and len(result["images"]) > 0:
+ for img_info in result["images"]:
+ if "url" in img_info:
+ output_image_urls.append(img_info["url"])
+ self._log(f"Found {len(output_image_urls)} edited images in response")
+ else:
+ self._log("Warning: No images found in result")
+ error_msg = "Error: No images in API response"
+ return self._create_error_image(error_msg), "", str(actual_seed), error_msg
+
+ # Extract returned seed
+ if "seed" in result:
+ returned_seed = result["seed"]
+ self._log(f"API returned seed: {returned_seed}")
+
+ # Download and process all generated images
+ try:
+ self._log(f"Downloading {len(output_image_urls)} edited images...")
+
+ processed_images = []
+ url_list = []
+
+ for i, image_url in enumerate(output_image_urls):
+ # Download image
+ dl_response = requests.get(image_url)
+ dl_response.raise_for_status()
+
+ # Convert to PIL Image
+ pil_image = Image.open(io.BytesIO(dl_response.content))
+
+ # Convert to RGB if necessary
+ if pil_image.mode != 'RGB':
+ pil_image = pil_image.convert('RGB')
+
+ # Convert to numpy array
+ np_image = np.array(pil_image).astype(np.float32) / 255.0
+
+ # Convert to tensor (add batch dimension)
+ image_tensor = torch.from_numpy(np_image).unsqueeze(0)
+ processed_images.append(image_tensor)
+ url_list.append(image_url)
+
+ self._log(f"Processed image {i+1}/{len(output_image_urls)} with shape {image_tensor.shape}")
+
+ # Concatenate all images
+ if len(processed_images) > 1:
+ # Handle multiple images - ensure same dimensions
+ max_height = max(img.shape[1] for img in processed_images)
+ max_width = max(img.shape[2] for img in processed_images)
+
+ resized_images = []
+ for img_tensor in processed_images:
+ current_h, current_w = img_tensor.shape[1], img_tensor.shape[2]
+
+ if current_h == max_height and current_w == max_width:
+ resized_images.append(img_tensor)
+ else:
+ # Pad the image
+ pad_h = max_height - current_h
+ pad_w = max_width - current_w
+ pad_left = pad_w // 2
+ pad_right = pad_w - pad_left
+ pad_top = pad_h // 2
+ pad_bottom = pad_h - pad_top
+
+ padded_img = torch.nn.functional.pad(
+ img_tensor.permute(0, 3, 1, 2),
+ (pad_left, pad_right, pad_top, pad_bottom),
+ mode='constant',
+ value=0
+ ).permute(0, 2, 3, 1)
+
+ resized_images.append(padded_img)
+
+ combined_tensor = torch.cat(resized_images, dim=0)
+ else:
+ combined_tensor = processed_images[0]
+
+ combined_urls = " | ".join(url_list)
+
+ self._log(f"Successfully processed {len(processed_images)} images with final shape {combined_tensor.shape}")
+
+ return combined_tensor, combined_urls, str(returned_seed), f"Success: {len(processed_images)} images edited successfully"
+
+ except Exception as e:
+ error_msg = f"Download Error: {str(e)}"
+ self._log(error_msg)
+ return self._create_error_image(error_msg), "", str(actual_seed), error_msg
+
+ except Exception as e:
+ self._log(f"Error in async image editing: {str(e)}")
+ error_msg = f"Error: {str(e)}"
+ return self._create_error_image(error_msg), "", str(actual_seed), error_msg
+
+ def edit_images(self, api_key, prompt, image_size="square_hd", num_images=1, seed=0, sync_mode=False, max_retries=3,
+ image_1=None, image_2=None, image_3=None, image_4=None, image_5=None,
+ image_6=None, image_7=None, image_8=None, image_9=None, image_10=None,
+ retry_indefinitely=False, use_custom_resolution=False, auto_scale_to_minimum=True,
+ custom_width=1280, custom_height=1280, **kwargs):
+ self.log_messages = []
+ if not api_key:
+ error_msg = "API key not provided."
+ self._log(error_msg)
+ error_img_instance = self._create_error_image(error_msg)
+ return (error_img_instance, "", "0", error_msg)
+
+ # Collect all input images (up to 10 as per API limit)
+ input_images = []
+ input_tensors = [image_1, image_2, image_3, image_4, image_5,
+ image_6, image_7, image_8, image_9, image_10]
+
+ for i, tensor in enumerate(input_tensors):
+ if tensor is not None:
+ pil_images = self._process_tensor_to_pil_list(tensor, f"Image{i+1}")
+ if pil_images:
+ input_images.extend(pil_images)
+
+ # Limit to 10 images as per API specification
+ if len(input_images) >= 10:
+ input_images = input_images[:10]
+ self._log("Limiting to 10 images as per API specification")
+ break
+
+ if not input_images:
+ error_msg = "No valid input images provided."
+ self._log(error_msg)
+ error_img_instance = self._create_error_image(error_msg)
+ return (error_img_instance, "", "0", error_msg)
+
+ self._log(f"Processing {len(input_images)} input images for editing")
+
+ # Run async processing using thread pool to avoid event loop conflicts
+ def run_sync_edit():
+ """Run async edit in a new thread with its own event loop"""
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+ try:
+ return loop.run_until_complete(self._edit_images_async(
+ api_key, prompt, input_images, image_size, num_images, seed,
+ sync_mode, max_retries, retry_indefinitely, use_custom_resolution,
+ auto_scale_to_minimum, custom_width, custom_height
+ ))
+ finally:
+ loop.close()
+
+ result = None
+ try:
+ # Use thread pool executor to run async code in separate thread
+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
+ future = executor.submit(run_sync_edit)
+ result = future.result(timeout=300) # 5 minute timeout
+ except concurrent.futures.TimeoutError:
+ self._log("Processing timed out after 5 minutes")
+ error_img = self._create_error_image("Processing timeout")
+ return (error_img, "", "0", "Processing timed out after 5 minutes")
+ except Exception as e:
+ self._log(f"Error in processing: {str(e)}")
+ error_img = self._create_error_image(f"Processing error: {str(e)}")
+ return (error_img, "", "0", f"Processing error: {str(e)}")
+
+ if result is None:
+ error_img = self._create_error_image("Processing failed to produce results")
+ return (error_img, "", "0", "Processing failed to produce results")
+
+ # Extract results
+ images, image_urls, returned_seed, status_msg = result
+
+ # Combine log messages with status
+ final_log_output = "Processing Logs:\n" + "\n".join(self.log_messages) + "\n\n" + status_msg
+
+ return (images, image_urls, returned_seed, final_log_output)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/ai/FL_Fal_Sora.py b/comfyui_fill-nodes/nodes/ai/FL_Fal_Sora.py
new file mode 100644
index 0000000000000000000000000000000000000000..20b04972301fdcff520dd891decfbea29724f908
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/FL_Fal_Sora.py
@@ -0,0 +1,324 @@
+import os
+import torch
+import numpy as np
+from PIL import Image
+import folder_paths
+import tempfile
+import importlib
+import requests
+from tqdm import tqdm
+import cv2
+import torchaudio
+import subprocess
+
+class FL_Fal_Sora:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "fal_api_key": ("STRING", {"default": ""}),
+ "prompt": ("STRING", {"multiline": True, "default": "A dramatic scene..."}),
+ "use_pro": ("BOOLEAN", {"default": False}),
+ "resolution": (["auto", "720p", "1080p"], {"default": "auto"}),
+ "aspect_ratio": (["auto", "16:9", "9:16"], {"default": "16:9"}),
+ "duration": ([4, 8, 12], {"default": 4}),
+ "openai_api_key": ("STRING", {"default": ""}),
+ "nth_frame": ("INT", {"default": 1, "min": 1, "max": 4, "step": 1}),
+ },
+ "optional": {
+ "image": ("IMAGE",),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE", "AUDIO", "STRING", "STRING")
+ RETURN_NAMES = ("frames", "audio", "video_url", "status_msg")
+ FUNCTION = "generate_video"
+ CATEGORY = "🏵️Fill Nodes/AI"
+
+ def generate_video(self, fal_api_key, prompt, use_pro, resolution, aspect_ratio, duration, openai_api_key, nth_frame, image=None):
+ # Helper function for empty audio
+ def empty_audio():
+ return {"waveform": torch.zeros((1, 1, 0)), "sample_rate": 44100}
+
+ try:
+ # Validate API key
+ if not fal_api_key or fal_api_key.strip() == "":
+ return (torch.zeros(1, 64, 64, 3), empty_audio(), "", "❌ Error: Fal API key is required")
+
+ # Validate prompt
+ if not prompt or prompt.strip() == "":
+ return (torch.zeros(1, 64, 64, 3), empty_audio(), "", "❌ Error: Prompt is required")
+
+ # Clear and set FAL_KEY environment variable
+ if 'FAL_KEY' in os.environ:
+ del os.environ['FAL_KEY']
+ os.environ['FAL_KEY'] = fal_api_key
+
+ # Reload fal_client to ensure it picks up the new API key
+ import sys
+ if 'fal_client' in sys.modules:
+ del sys.modules['fal_client']
+
+ import fal_client
+
+ # Determine which endpoint to use
+ is_image_to_video = image is not None
+ original_resolution = resolution
+ original_aspect_ratio = aspect_ratio
+
+ if is_image_to_video:
+ if use_pro:
+ endpoint = "fal-ai/sora-2/image-to-video/pro"
+ valid_resolutions = ["auto", "720p", "1080p"]
+ else:
+ endpoint = "fal-ai/sora-2/image-to-video"
+ valid_resolutions = ["auto", "720p"]
+ else:
+ if use_pro:
+ endpoint = "fal-ai/sora-2/text-to-video/pro"
+ valid_resolutions = ["720p", "1080p"]
+ # For text-to-video, default to 720p if "auto" is selected
+ if resolution == "auto":
+ resolution = "720p"
+ print("⚠️ 'auto' resolution not supported for text-to-video, using '720p'")
+ else:
+ endpoint = "fal-ai/sora-2/text-to-video"
+ valid_resolutions = ["720p"]
+ if resolution != "720p":
+ print(f"⚠️ Resolution '{resolution}' not available for non-PRO text-to-video, using '720p'")
+ resolution = "720p"
+
+ # Validate resolution
+ if resolution not in valid_resolutions:
+ old_res = resolution
+ resolution = valid_resolutions[0]
+ print(f"⚠️ Resolution '{old_res}' not valid for {endpoint}, using '{resolution}'")
+ print(f" Valid resolutions: {', '.join(valid_resolutions)}")
+
+ # Validate aspect_ratio for text-to-video (no auto option)
+ if not is_image_to_video and aspect_ratio == "auto":
+ aspect_ratio = "16:9"
+ print("⚠️ 'auto' aspect ratio not supported for text-to-video, using '16:9'")
+
+ print(f"\n{'='*60}")
+ print(f"📹 Using endpoint: {endpoint}")
+ print(f"📝 Prompt: {prompt[:100]}...")
+ print(f"🎬 Settings: {resolution}, {aspect_ratio}, {duration}s")
+ if original_resolution != resolution or original_aspect_ratio != aspect_ratio:
+ print(f"ℹ️ Note: Some parameters were auto-corrected for this endpoint")
+ print(f"{'='*60}\n")
+
+ # Build arguments
+ arguments = {
+ "prompt": prompt,
+ "resolution": resolution,
+ "aspect_ratio": aspect_ratio,
+ "duration": duration,
+ }
+
+ # Add OpenAI API key if provided (to avoid billing from Fal)
+ if openai_api_key and openai_api_key.strip():
+ arguments["api_key"] = openai_api_key
+ print("🔑 Using OpenAI API key (billed to your OpenAI account)")
+
+ # Handle image input for image-to-video
+ image_url = None
+ temp_image_path = None
+ if is_image_to_video:
+ print("🖼️ Image provided - using image-to-video mode")
+
+ # Convert tensor to PIL Image
+ i = 255. * image[0].cpu().numpy()
+ img_pil = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
+
+ # Save to temporary file
+ temp_image_path = tempfile.NamedTemporaryFile(delete=False, suffix='.png').name
+ img_pil.save(temp_image_path)
+
+ # Upload image to Fal
+ print("📤 Uploading image to Fal...")
+ image_url = fal_client.upload_file(temp_image_path)
+ arguments["image_url"] = image_url
+ print(f"✅ Image uploaded: {image_url}")
+
+ # Call the API
+ print(f"🚀 Calling Fal API: {endpoint}")
+
+ def on_queue_update(update):
+ if isinstance(update, fal_client.InProgress):
+ for log in update.logs:
+ print(f"📝 {log['message']}")
+
+ result = fal_client.subscribe(
+ endpoint,
+ arguments=arguments,
+ with_logs=True,
+ on_queue_update=on_queue_update,
+ )
+
+ # Clean up temp image file
+ if temp_image_path and os.path.exists(temp_image_path):
+ os.remove(temp_image_path)
+
+ # Get video URL from result
+ if not result:
+ error_msg = "❌ API returned empty result"
+ print(error_msg)
+ return (torch.zeros(1, 64, 64, 3), empty_audio(), "", error_msg)
+
+ if 'video' not in result:
+ error_msg = f"❌ No 'video' field in API response. Response keys: {list(result.keys())}"
+ print(error_msg)
+ return (torch.zeros(1, 64, 64, 3), empty_audio(), "", error_msg)
+
+ if 'url' not in result['video']:
+ error_msg = f"❌ No 'url' in video response. Video keys: {list(result['video'].keys())}"
+ print(error_msg)
+ return (torch.zeros(1, 64, 64, 3), empty_audio(), "", error_msg)
+
+ video_url = result['video']['url']
+ print(f"✅ Video generated: {video_url}")
+
+ # Download the video
+ print("⬇️ Downloading video...")
+ response = requests.get(video_url, stream=True)
+
+ if response.status_code != 200:
+ error_msg = f"❌ Failed to download video. HTTP Status: {response.status_code}"
+ print(error_msg)
+ return (torch.zeros(1, 64, 64, 3), empty_audio(), video_url, error_msg)
+
+ total_size = int(response.headers.get('content-length', 0))
+
+ temp_video_path = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4').name
+
+ with open(temp_video_path, 'wb') as f, tqdm(
+ desc="Downloading",
+ total=total_size,
+ unit='iB',
+ unit_scale=True,
+ unit_divisor=1024,
+ ) as pbar:
+ for data in response.iter_content(chunk_size=1024):
+ size = f.write(data)
+ pbar.update(size)
+
+ print(f"✅ Video downloaded to: {temp_video_path}")
+
+ # Extract audio from video using ffmpeg
+ print("🎵 Extracting audio from video...")
+ temp_audio_path = tempfile.NamedTemporaryFile(delete=False, suffix='.wav').name
+
+ try:
+ ffmpeg_cmd = [
+ 'ffmpeg',
+ '-i', temp_video_path,
+ '-vn', # No video
+ '-acodec', 'pcm_s16le', # PCM 16-bit little-endian
+ '-ar', '44100', # 44.1kHz sample rate
+ '-ac', '2', # Stereo
+ '-y', # Overwrite output file
+ temp_audio_path
+ ]
+
+ result_ffmpeg = subprocess.run(ffmpeg_cmd, capture_output=True, text=True)
+
+ if result_ffmpeg.returncode != 0:
+ print(f"⚠️ FFmpeg warning: {result_ffmpeg.stderr}")
+ print("⚠️ Video may not contain audio, using empty audio")
+ audio_output = empty_audio()
+ else:
+ # Load audio using torchaudio
+ waveform, sample_rate = torchaudio.load(temp_audio_path)
+ audio_output = {
+ "waveform": waveform.unsqueeze(0), # Add batch dimension
+ "sample_rate": sample_rate
+ }
+ print(f"✅ Audio extracted: {waveform.shape[1]} samples at {sample_rate}Hz")
+
+ # Clean up temp audio file
+ if os.path.exists(temp_audio_path):
+ os.remove(temp_audio_path)
+
+ except FileNotFoundError:
+ print("⚠️ FFmpeg not found. Install ffmpeg to extract audio. Using empty audio.")
+ audio_output = empty_audio()
+ except Exception as e:
+ print(f"⚠️ Error extracting audio: {str(e)}. Using empty audio.")
+ audio_output = empty_audio()
+
+ # Extract frames from video
+ print(f"🎞️ Extracting frames (every {nth_frame} frame(s))...")
+ cap = cv2.VideoCapture(temp_video_path)
+
+ if not cap.isOpened():
+ error_msg = f"❌ Failed to open video file: {temp_video_path}"
+ print(error_msg)
+ return (torch.zeros(1, 64, 64, 3), audio_output, video_url, error_msg)
+
+ frames = []
+ frame_count = 0
+
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
+
+ if total_frames == 0:
+ cap.release()
+ error_msg = "❌ Video file contains 0 frames"
+ print(error_msg)
+ return (torch.zeros(1, 64, 64, 3), audio_output, video_url, error_msg)
+
+ with tqdm(total=total_frames, desc="Extracting frames") as pbar:
+ while True:
+ ret, frame = cap.read()
+ if not ret:
+ break
+
+ if frame_count % nth_frame == 0:
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
+ frames.append(frame_rgb)
+
+ frame_count += 1
+ pbar.update(1)
+
+ cap.release()
+
+ # Clean up temp video file
+ if os.path.exists(temp_video_path):
+ os.remove(temp_video_path)
+
+ if not frames:
+ error_msg = "❌ No frames extracted from video"
+ print(error_msg)
+ return (torch.zeros(1, 64, 64, 3), audio_output, video_url, error_msg)
+
+ print(f"✅ Extracted {len(frames)} frames")
+
+ # Convert frames to tensor
+ frames_np = np.array(frames).astype(np.float32) / 255.0
+ frames_tensor = torch.from_numpy(frames_np)
+
+ success_msg = f"✅ Successfully generated video with {len(frames)} frames using {endpoint}"
+ print(success_msg)
+
+ return (frames_tensor, audio_output, video_url, success_msg)
+
+ except Exception as e:
+ error_msg = f"❌ Error: {str(e)}"
+ # Remove large base64 data URIs from error message for readability
+ if "data:image" in error_msg or "data:audio" in error_msg:
+ error_msg = error_msg[:500] + "... (truncated)"
+ print(error_msg)
+ import traceback
+ traceback.print_exc()
+ return (torch.zeros(1, 64, 64, 3), empty_audio(), "", error_msg)
+
+NODE_CLASS_MAPPINGS = {
+ "FL_Fal_Sora": FL_Fal_Sora
+}
+
+NODE_DISPLAY_NAME_MAPPINGS = {
+ "FL_Fal_Sora": "FL Fal Sora 2"
+}
diff --git a/comfyui_fill-nodes/nodes/ai/FL_GeminiImageEditor.py b/comfyui_fill-nodes/nodes/ai/FL_GeminiImageEditor.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f2c2f82786b7016bf4e453c4254297a915573e2
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/FL_GeminiImageEditor.py
@@ -0,0 +1,548 @@
+import os
+import base64
+import io
+import json
+import torch
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+import requests
+import tempfile
+from io import BytesIO
+from google import genai
+from google.genai import types
+import time
+import traceback
+import asyncio
+import concurrent.futures
+import random
+from typing import List, Tuple, Optional
+
+
+class FL_GeminiImageEditor:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "prompt": ("STRING", {"multiline": True}),
+ "api_key": ("STRING", {"default": "", "multiline": False}),
+ "model": (["models/gemini-2.0-flash-exp", "models/gemini-2.0-flash-preview-image-generation", "models/gemini-2.5-flash-image-preview", "models/gemini-2.5-flash-image", "models/gemini-3-pro-image-preview"], {"default": "models/gemini-2.5-flash-image"}),
+ "aspect_ratio": (["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"], {"default": "1:1"}),
+ "image_size": (["1K", "2K", "4K"], {"default": "1K", "tooltip": "Resolution size (2K/4K only supported by gemini-3-pro-image-preview)"}),
+ "always_square": ("BOOLEAN", {"default": False, "description": "When enabled, pads images to square dimensions. When disabled, outputs original resolution as image list."}),
+ "temperature": ("FLOAT", {"default": 1, "min": 0.0, "max": 2.0, "step": 0.05}),
+ "max_retries": ("INT", {"default": 3, "min": 1, "max": 5, "step": 1}),
+ "batch_size": ("INT", {"default": 1, "min": 1, "max": 8, "step": 1}),
+ },
+ "optional": {
+ "seed": ("INT", {"default": 66666666, "min": 0, "max": 66666666}),
+ "image1": ("IMAGE",),
+ "image2": ("IMAGE",),
+ "image3": ("IMAGE",),
+ "image4": ("IMAGE",),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE", "STRING")
+ RETURN_NAMES = ("image", "API Respond")
+ OUTPUT_IS_LIST = (True, False)
+ FUNCTION = "generate_image"
+ CATEGORY = "🏵️Fill Nodes/AI"
+
+ def __init__(self):
+ """Initialize logging system"""
+ self.log_messages = [] # Global log message storage
+ self.min_size = 1024 # Minimum size for both width and height
+
+ # Check google-genai version
+ try:
+ import importlib.metadata
+ genai_version = importlib.metadata.version('google-genai')
+ self._log(f"Current google-genai version: {genai_version}")
+
+ # Check if version meets minimum requirements
+ from packaging import version
+ if version.parse(genai_version) < version.parse('0.8.0'):
+ self._log("Warning: google-genai version is too low, recommend upgrading to the latest version")
+ self._log("Suggested: pip install -q -U google-genai")
+ except Exception as e:
+ self._log(f"Unable to check google-genai version: {e}")
+
+ def _log(self, message):
+ """Global logging function: record to log list"""
+ timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
+ formatted_message = f"[FL_GeminiImageGenerator] {timestamp}: {message}"
+ print(formatted_message)
+ if hasattr(self, 'log_messages'):
+ self.log_messages.append(message)
+ return message
+
+ def _pad_image_to_minimum_size(self, pil_image):
+ """Pad image with white to ensure it's at least min_size x min_size while preserving aspect ratio"""
+ width, height = pil_image.size
+
+ # If already meets minimum size requirements, return unchanged
+ if width >= self.min_size and height >= self.min_size:
+ return pil_image
+
+ # Calculate new dimensions (preserve aspect ratio)
+ new_width = max(width, self.min_size)
+ new_height = max(height, self.min_size)
+
+ # Create new white canvas
+ new_image = Image.new('RGB', (new_width, new_height), color=(255, 255, 255))
+
+ # Calculate position to paste the original image (centered)
+ paste_x = (new_width - width) // 2
+ paste_y = (new_height - height) // 2
+
+ # Paste original image onto the white canvas
+ new_image.paste(pil_image, (paste_x, paste_y))
+
+ self._log(f"Padded image from {width}x{height} to {new_width}x{new_height} with white borders")
+ return new_image
+
+ def _create_error_image(self, error_message="API Failed to return an image", width=1024, height=1024):
+ """Create black image with error text"""
+ # Create black image
+ image = Image.new('RGB', (width, height), color=(0, 0, 0))
+ draw = ImageDraw.Draw(image)
+
+ # Try to use a system font
+ try:
+ # Try to find a font that exists on most systems
+ font_options = ['Arial.ttf', 'DejaVuSans.ttf', 'FreeSans.ttf', 'NotoSans-Regular.ttf']
+ font = None
+
+ for font_name in font_options:
+ try:
+ font = ImageFont.truetype(font_name, 24)
+ break
+ except IOError:
+ continue
+
+ if font is None:
+ # Fall back to default font
+ font = ImageFont.load_default()
+ except Exception:
+ # If everything fails, use default
+ font = ImageFont.load_default()
+
+ # Calculate text position (centered)
+ text_width = draw.textlength(error_message, font=font) if hasattr(draw, 'textlength') else \
+ font.getsize(error_message)[0]
+ text_x = (width - text_width) / 2
+ text_y = height / 2 - 12 # Vertically centered
+
+ # Draw text
+ draw.text((text_x, text_y), error_message, fill=(255, 0, 0), font=font)
+
+ # Convert to tensor format [1, H, W, 3]
+ img_array = np.array(image).astype(np.float32) / 255.0
+ img_tensor = torch.from_numpy(img_array).unsqueeze(0)
+
+ self._log(f"Created error image with message: '{error_message}'")
+ return img_tensor
+
+ def _generate_empty_image(self, width=1024, height=1024):
+ """Generate standard format empty RGB image tensor - ensure ComfyUI compatible format [B,H,W,C]"""
+ # Now just use error image with default message
+ return self._create_error_image(width=width, height=height)
+
+ def _process_tensor_to_pil(self, tensor, name="Image"):
+ """Convert a tensor to a PIL image for API submission"""
+ try:
+ if tensor is None:
+ self._log(f"{name} is None, skipping")
+ return None
+
+ # Ensure tensor is in correct format [1, H, W, 3]
+ if len(tensor.shape) == 4 and tensor.shape[0] == 1:
+ # Get first frame image
+ image_np = tensor[0].cpu().numpy()
+
+ # Convert to uint8 format for PIL
+ image_np = (image_np * 255).astype(np.uint8)
+
+ # Create PIL image
+ pil_image = Image.fromarray(image_np)
+
+ self._log(f"{name} processed successfully, size: {pil_image.width}x{pil_image.height}")
+ return pil_image
+ else:
+ self._log(f"{name} format incorrect: {tensor.shape}")
+ return None
+ except Exception as e:
+ self._log(f"Error processing {name}: {str(e)}")
+ return None
+
+ def _call_gemini_api(self, client, model, contents, gen_config, retry_count=0, max_retries=3, batch_id=0):
+ """Call Gemini API with retry logic"""
+ try:
+ self._log(f"[Batch {batch_id}] API call attempt #{retry_count + 1}")
+ response = client.models.generate_content(
+ model=model,
+ contents=contents,
+ config=gen_config
+ )
+
+ # Validate response structure
+ if not hasattr(response, 'candidates') or not response.candidates:
+ self._log(f"[Batch {batch_id}] Empty response: No candidates found")
+ if retry_count < max_retries - 1:
+ self._log(f"[Batch {batch_id}] Retrying in 2 seconds... (Attempt {retry_count + 1}/{max_retries})")
+ time.sleep(2) # Wait 2 seconds before retry
+ return self._call_gemini_api(client, model, contents, gen_config,
+ retry_count + 1, max_retries, batch_id)
+ else:
+ self._log(f"[Batch {batch_id}] Maximum retries ({max_retries}) reached. Returning empty response.")
+ return None
+
+ # Check if candidates[0].content exists
+ if not hasattr(response.candidates[0], 'content') or response.candidates[0].content is None:
+ self._log(f"[Batch {batch_id}] Invalid response: candidates[0].content is missing")
+ if retry_count < max_retries - 1:
+ self._log(f"[Batch {batch_id}] Retrying in 2 seconds... (Attempt {retry_count + 1}/{max_retries})")
+ time.sleep(2)
+ return self._call_gemini_api(client, model, contents, gen_config,
+ retry_count + 1, max_retries, batch_id)
+ else:
+ self._log(f"[Batch {batch_id}] Maximum retries ({max_retries}) reached. Returning empty response.")
+ return None
+
+ # Check if content.parts exists
+ if not hasattr(response.candidates[0].content, 'parts') or response.candidates[0].content.parts is None:
+ self._log(f"[Batch {batch_id}] Invalid response: candidates[0].content.parts is missing")
+ if retry_count < max_retries - 1:
+ self._log(f"[Batch {batch_id}] Retrying in 2 seconds... (Attempt {retry_count + 1}/{max_retries})")
+ time.sleep(2)
+ return self._call_gemini_api(client, model, contents, gen_config,
+ retry_count + 1, max_retries, batch_id)
+ else:
+ self._log(f"[Batch {batch_id}] Maximum retries ({max_retries}) reached. Returning empty response.")
+ return None
+
+ # Valid response, return it
+ self._log(f"[Batch {batch_id}] Valid API response received")
+ return response
+
+ except Exception as e:
+ self._log(f"[Batch {batch_id}] API call error: {str(e)}")
+ if retry_count < max_retries - 1:
+ wait_time = 2 * (retry_count + 1) # Progressive backoff: 2s, 4s, 6s...
+ self._log(
+ f"[Batch {batch_id}] Retrying in {wait_time} seconds... (Attempt {retry_count + 1}/{max_retries})")
+ time.sleep(wait_time)
+ return self._call_gemini_api(client, model, contents, gen_config,
+ retry_count + 1, max_retries, batch_id)
+ else:
+ self._log(f"[Batch {batch_id}] Maximum retries ({max_retries}) reached. Giving up.")
+ return None
+
+ def _process_api_response(self, response, batch_id=0, always_square=False):
+ """Process API response and extract image tensor"""
+ if response is None:
+ self._log(f"[Batch {batch_id}] No valid response to process")
+ error_msg = "API Failed to return an image"
+ return self._create_error_image(error_msg), error_msg
+
+ response_text = ""
+
+ # Check if response contains valid data
+ if not hasattr(response, 'candidates') or not response.candidates:
+ self._log(f"[Batch {batch_id}] No candidates in API response")
+ error_msg = "API returned an empty response"
+ return self._create_error_image(error_msg), error_msg
+
+ # Iterate through response parts
+ for part in response.candidates[0].content.parts:
+ # Check if it's a text part
+ if hasattr(part, 'text') and part.text is not None:
+ text_content = part.text
+ response_text += text_content
+ self._log(
+ f"[Batch {batch_id}] API returned text: {text_content[:100]}..." if len(
+ text_content) > 100 else text_content)
+
+ # Check if it's an image part
+ elif hasattr(part, 'inline_data') and part.inline_data is not None:
+ self._log(f"[Batch {batch_id}] API returned image data")
+ try:
+ # Get image data
+ image_data = part.inline_data.data
+ mime_type = part.inline_data.mime_type if hasattr(part.inline_data, 'mime_type') else "unknown"
+
+ # Confirm data is not empty
+ if not image_data or len(image_data) < 100:
+ self._log(f"[Batch {batch_id}] Warning: Image data is empty or too small")
+ continue
+
+ # Multiple methods to try opening the image
+ pil_image = None
+
+ # Method 1: Direct PIL open
+ try:
+ pil_image = Image.open(BytesIO(image_data))
+ self._log(
+ f"[Batch {batch_id}] Direct PIL open successful, size: {pil_image.width}x{pil_image.height}")
+ except Exception as e1:
+ self._log(f"[Batch {batch_id}] Direct PIL open failed: {str(e1)}")
+
+ # Method 2: Save to temp file and open
+ try:
+ temp_file = os.path.join(tempfile.gettempdir(),
+ f"gemini_image_{batch_id}_{int(time.time())}.png")
+ with open(temp_file, "wb") as f:
+ f.write(image_data)
+
+ pil_image = Image.open(temp_file)
+ self._log(f"[Batch {batch_id}] Opening via temp file successful")
+ except Exception as e2:
+ self._log(f"[Batch {batch_id}] Opening via temp file failed: {str(e2)}")
+
+ # Try more methods if needed
+ # Additional opening methods from original code could be added here if necessary
+
+ # Ensure image loaded successfully
+ if pil_image is None:
+ self._log(f"[Batch {batch_id}] Cannot open image, skipping")
+ continue
+
+ # Ensure image is RGB mode
+ if pil_image.mode != 'RGB':
+ pil_image = pil_image.convert('RGB')
+ self._log(f"[Batch {batch_id}] Image converted to RGB mode")
+
+ # Store original dimensions for logging
+ width, height = pil_image.size
+ self._log(f"[Batch {batch_id}] Original image size: {width}x{height}")
+
+ # Apply padding if always_square is enabled and image needs it
+ if always_square and (width < self.min_size or height < self.min_size):
+ self._log(
+ f"[Batch {batch_id}] Image size {width}x{height} is smaller than minimum {self.min_size}x{self.min_size}, padding needed")
+ pil_image = self._pad_image_to_minimum_size(pil_image)
+ elif always_square:
+ self._log(f"[Batch {batch_id}] Always square enabled but image already meets minimum size")
+ else:
+ self._log(f"[Batch {batch_id}] Always square disabled, keeping original size: {width}x{height}")
+
+ # Convert to ComfyUI format
+ img_array = np.array(pil_image).astype(np.float32) / 255.0
+ img_tensor = torch.from_numpy(img_array).unsqueeze(0)
+
+ self._log(f"[Batch {batch_id}] Image converted to tensor successfully, shape: {img_tensor.shape}")
+ return img_tensor, response_text
+ except Exception as e:
+ self._log(f"[Batch {batch_id}] Image processing error: {e}")
+ traceback.print_exc()
+
+ # If we got here, no image was found
+ self._log(f"[Batch {batch_id}] No image data found in API response")
+ error_msg = "API Failed to return an image"
+ return self._create_error_image(error_msg), response_text if response_text else error_msg
+
+ async def _generate_single_image_async(self, prompt, api_key, model, temperature, max_retries,
+ batch_id, seed, reference_images, always_square=False,
+ aspect_ratio="1:1", image_size="1K"):
+ """Generate a single image asynchronously for batch processing"""
+ try:
+ # Create client instance - each batch gets its own client
+ client = genai.Client(api_key=api_key)
+
+ # Use provided seed or generate random one
+ actual_seed = seed if seed != 0 else random.randint(1, 0xffffff)
+ self._log(f"[Batch {batch_id}] Using seed: {actual_seed}")
+
+ # Configure generation parameters
+ gen_config_params = {
+ "temperature": temperature,
+ "seed": actual_seed,
+ "response_modalities": ['Text', 'Image']
+ }
+
+ # Add image config if supported
+ try:
+ # Check if ImageConfig supports imageSize parameter (SDK >= 1.50)
+ import inspect
+ image_config_sig = inspect.signature(types.ImageConfig)
+ supports_image_size = 'imageSize' in image_config_sig.parameters or 'image_size' in image_config_sig.parameters
+
+ image_config_params = {"aspectRatio": aspect_ratio}
+ # Only add imageSize for gemini-3-pro model if SDK supports it
+ if "gemini-3-pro" in model and supports_image_size:
+ image_config_params["imageSize"] = image_size
+ self._log(f"[Batch {batch_id}] Using imageSize: {image_size}")
+ elif "gemini-3-pro" in model:
+ self._log(f"[Batch {batch_id}] Warning: imageSize not supported in this SDK version. Upgrade google-genai to 1.50+ for 4K support")
+
+ gen_config_params["image_config"] = types.ImageConfig(**image_config_params)
+ except Exception as e:
+ self._log(f"[Batch {batch_id}] ImageConfig not available: {e}, using basic config")
+
+ gen_config = types.GenerateContentConfig(**gen_config_params)
+
+ # Create content parts
+ content_parts = []
+
+ # Add prompt
+ simple_prompt = f"Create a detailed image of: {prompt}"
+ content_parts.append(simple_prompt)
+
+ # Add reference images if provided
+ for img in reference_images:
+ if img is not None:
+ content_parts.append(img)
+
+ # Make API call with synchronous method (will run in thread pool)
+ loop = asyncio.get_event_loop()
+ response = await loop.run_in_executor(
+ None,
+ lambda: self._call_gemini_api(
+ client=client,
+ model=model,
+ contents=content_parts,
+ gen_config=gen_config,
+ max_retries=max_retries,
+ batch_id=batch_id
+ )
+ )
+
+ # Process the response and return the image tensor and text
+ img_tensor, response_text = await loop.run_in_executor(
+ None, lambda: self._process_api_response(response, batch_id, always_square)
+ )
+
+ # If processing failed, return the error image
+ if img_tensor is None:
+ error_msg = f"Batch {batch_id}: API Failed to return an image"
+ return self._create_error_image(error_msg), error_msg, batch_id
+
+ return img_tensor, response_text, batch_id
+
+ except Exception as e:
+ self._log(f"[Batch {batch_id}] Error in async image generation: {str(e)}")
+ error_msg = f"Batch {batch_id}: Error: {str(e)}"
+ return self._create_error_image(error_msg), error_msg, batch_id
+
+ def generate_image(self, prompt, api_key, model, aspect_ratio, image_size, temperature, max_retries=3, batch_size=1,
+ seed=66666666, always_square=False, image1=None, image2=None, image3=None, image4=None):
+ """Generate batch of images with parallel API calls"""
+ # Reset log messages
+ self.log_messages = []
+ all_response_text = ""
+
+ try:
+ # Check if API key is provided
+ if not api_key:
+ error_message = "Error: No API key provided. Please enter Google API key in the node."
+ self._log(error_message)
+ error_img = self._create_error_image("API key required")
+ full_text = "## Error\n" + error_message + "\n\n## Instructions\n1. Enter your Google API key in the node"
+
+ # Create list of error images for all batch sizes
+ error_imgs = [error_img] * batch_size
+ return (error_imgs, full_text)
+
+ self._log(f"Starting batch generation of {batch_size} images")
+
+ # Process reference images once
+ reference_pil_images = []
+ image_tensors = [image1, image2, image3, image4]
+
+ for i, img_tensor in enumerate(image_tensors):
+ if img_tensor is not None:
+ pil_img = self._process_tensor_to_pil(img_tensor, f"Reference Image {i + 1}")
+ if pil_img:
+ reference_pil_images.append(pil_img)
+ self._log(f"Added reference image {i + 1} to batch processing")
+
+ # Setup async tasks for each batch item
+ async def run_batch():
+ tasks = []
+
+ # Create tasks for each batch item
+ for i in range(batch_size):
+ # If seed is specified (non-zero), increment it for each batch item
+ # Otherwise each batch will use a random seed
+ batch_seed = seed + i if seed != 0 else 0
+
+ task = self._generate_single_image_async(
+ prompt=prompt,
+ api_key=api_key,
+ model=model,
+ temperature=temperature,
+ max_retries=max_retries,
+ batch_id=i + 1,
+ seed=batch_seed,
+ reference_images=reference_pil_images,
+ always_square=always_square,
+ aspect_ratio=aspect_ratio,
+ image_size=image_size
+ )
+ tasks.append(task)
+
+ # Run all tasks concurrently
+ return await asyncio.gather(*tasks)
+
+ # Run the async batch processing using thread pool to avoid event loop conflicts
+ def run_sync_batch():
+ """Run async batch in a new thread with its own event loop"""
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+ try:
+ return loop.run_until_complete(run_batch())
+ finally:
+ loop.close()
+
+ results = None # Initialize results
+ try:
+ # Use thread pool executor to run async code in separate thread
+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
+ future = executor.submit(run_sync_batch)
+ results = future.result(timeout=300) # 5 minute timeout
+ except concurrent.futures.TimeoutError:
+ self._log("Async processing timed out after 5 minutes")
+ error_imgs = [self._create_error_image("Processing timeout")] * batch_size
+ return (error_imgs, "Processing timed out after 5 minutes")
+ except Exception as e:
+ self._log(f"Error in async processing: {str(e)}")
+ traceback.print_exc()
+ # Create list of error images
+ error_imgs = [self._create_error_image(f"Async processing error: {str(e)}")] * batch_size
+ return (error_imgs, f"Async processing error: {str(e)}")
+
+ # Process results (ensure results is not None if an error occurred before assignment)
+ if results is None:
+ self._log("Async processing did not yield results, possibly due to an earlier error before gather.")
+ error_imgs = [self._create_error_image("Async processing failed to produce results")] * batch_size
+ return (error_imgs, "Async processing failed to produce results")
+
+ # Process results
+ all_tensors = []
+ batch_texts = []
+
+ for img_tensor, text, batch_id in results:
+ # Always add tensor to list since we now always have a valid tensor
+ # (either real image or error image)
+ all_tensors.append(img_tensor)
+ batch_texts.append(f"## Batch {batch_id} Response\n{text}")
+
+ self._log(f"Successfully created list of {len(all_tensors)} images")
+
+ # Combine all texts
+ all_response_text = "## Batch Processing Results\n" + "\n".join(self.log_messages) + "\n\n" + "\n\n".join(
+ batch_texts)
+
+ return (all_tensors, all_response_text)
+
+ except Exception as e:
+ error_message = f"Error during batch processing: {str(e)}"
+ self._log(error_message)
+ traceback.print_exc()
+
+ # Create list of error images
+ error_imgs = [self._create_error_image(f"Error: {str(e)}")] * batch_size
+
+ # Combine logs and error info
+ full_text = "## Processing Log\n" + "\n".join(self.log_messages) + "\n\n## Error\n" + error_message
+ return (error_imgs, full_text)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/ai/FL_GeminiImageGenADV.py b/comfyui_fill-nodes/nodes/ai/FL_GeminiImageGenADV.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b10792d9461ec59adcdb52d032be9f8922309ce
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/FL_GeminiImageGenADV.py
@@ -0,0 +1,472 @@
+import os
+import base64
+import io
+import json
+import torch
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+import requests
+import tempfile
+from io import BytesIO
+from google import genai
+from google.genai import types
+import time
+import traceback
+import asyncio
+import concurrent.futures
+import random
+from typing import List, Tuple, Optional
+
+from comfy.utils import ProgressBar
+
+# Assuming ImageBatch is still needed if we are batching results, or can be removed if Gemini returns a batch
+# from nodes import ImageBatch
+
+class FL_GeminiImageGenADV:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "inputcount": ("INT", {"default": 1, "min": 1, "max": 100, "step": 1}),
+ "api_key": ("STRING", {"default": os.getenv("GEMINI_API_KEY", ""), "multiline": False}),
+ "model": (["models/gemini-2.0-flash-exp", "models/gemini-2.0-flash-preview-image-generation", "models/gemini-2.5-flash-image-preview", "models/gemini-2.5-flash-image", "models/gemini-3-pro-image-preview"], {"default": "models/gemini-2.5-flash-image"}),
+ "aspect_ratio": (["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"], {"default": "1:1"}),
+ "image_size": (["1K", "2K", "4K"], {"default": "1K", "tooltip": "Resolution size (2K/4K only supported by gemini-3-pro-image-preview)"}),
+ "always_square": ("BOOLEAN", {"default": False, "description": "When enabled, pads images to square dimensions. When disabled, outputs original resolution as image list."}),
+ "temperature": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 2.0, "step": 0.05}),
+ "max_retries": ("INT", {"default": 3, "min": 1, "max": 5, "step": 1}),
+ "prompt_1": ("STRING", {"multiline": False, "default": "Describe image 1", "forceInput": True}),
+ },
+ "optional": {
+ "image_1": ("IMAGE", {}), # Moved image_1 to optional. Default will be None if not connected.
+ "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffff}), # Restored full seed range
+ "retry_indefinitely": ("BOOLEAN", {"default": False}),
+ # Subsequent image_i and prompt_i will be handled by **kwargs based on inputcount
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE", "STRING")
+ RETURN_NAMES = ("images", "API_responses")
+ OUTPUT_IS_LIST = (True, False)
+ FUNCTION = "generate_images_advanced"
+ CATEGORY = "🏵️Fill Nodes/AI"
+ DESCRIPTION = """
+Generates images using Gemini based on multiple image/prompt pairs.
+Each pair triggers an asynchronous API call. Results are batched.
+"""
+
+ def __init__(self):
+ self.log_messages = []
+ self.min_size = 1024 # Minimum size from Editor
+ try:
+ import importlib.metadata
+ genai_version = importlib.metadata.version('google-genai')
+ self._log(f"Current google-genai version: {genai_version}")
+ from packaging import version # Ensure packaging is imported
+ if version.parse(genai_version) < version.parse('0.8.0'): # Example version, check Gemini docs
+ self._log("Warning: google-genai version is too low, recommend upgrading to the latest version.")
+ self._log("Suggested: pip install -q -U google-genai")
+ except Exception as e:
+ self._log(f"Unable to check google-genai version: {e}")
+
+ def _log(self, message):
+ timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
+ formatted_message = f"[FL_GeminiImageGenADV] {timestamp}: {message}"
+ print(formatted_message)
+ if hasattr(self, 'log_messages'):
+ self.log_messages.append(message)
+ return message
+
+ def _pad_image_to_minimum_size(self, pil_image):
+ width, height = pil_image.size
+ if width >= self.min_size and height >= self.min_size:
+ return pil_image
+ new_width = max(width, self.min_size)
+ new_height = max(height, self.min_size)
+ new_image = Image.new('RGB', (new_width, new_height), color=(255, 255, 255)) # White padding from Editor
+ paste_x = (new_width - width) // 2
+ paste_y = (new_height - height) // 2
+ new_image.paste(pil_image, (paste_x, paste_y))
+ self._log(f"Padded image from {width}x{height} to {new_width}x{new_height} with white borders")
+ return new_image
+
+ def _create_error_image(self, error_message="API Error", width=1024, height=1024): # Default size from Editor
+ image = Image.new('RGB', (width, height), color=(0, 0, 0)) # Black error image from Editor
+ draw = ImageDraw.Draw(image)
+ font = None
+ try:
+ # Try to find a font that exists on most systems
+ font_options = ['arial.ttf', 'DejaVuSans.ttf', 'FreeSans.ttf', 'NotoSans-Regular.ttf']
+ for font_name in font_options:
+ try:
+ font = ImageFont.truetype(font_name, 24) # Font size from Editor
+ break
+ except IOError:
+ continue
+ if font is None:
+ font = ImageFont.load_default()
+ except Exception:
+ font = ImageFont.load_default()
+
+ # Calculate text position (centered)
+ try: # Newer PIL versions
+ text_bbox = draw.textbbox((0,0), error_message, font=font)
+ text_width = text_bbox[2] - text_bbox[0]
+ text_height = text_bbox[3] - text_bbox[1]
+ except AttributeError: # Older PIL versions
+ text_width, text_height = draw.textsize(error_message, font=font)
+
+ text_x = (width - text_width) / 2
+ text_y = (height - text_height) / 2
+ draw.text((text_x, text_y), error_message, fill=(255, 0, 0), font=font) # Red text from Editor
+ img_array = np.array(image).astype(np.float32) / 255.0
+ img_tensor = torch.from_numpy(img_array).unsqueeze(0)
+ self._log(f"Created error image: '{error_message}'")
+ return img_tensor
+
+ def _process_tensor_to_pil_list(self, tensor_image: Optional[torch.Tensor], image_name_prefix: str = "Image") -> Optional[List[Image.Image]]:
+ if tensor_image is None:
+ self._log(f"{image_name_prefix} input is None, skipping PIL conversion.")
+ return None
+ if not isinstance(tensor_image, torch.Tensor):
+ self._log(f"{image_name_prefix} is not a tensor (type: {type(tensor_image)}), skipping.")
+ return None
+
+ pil_images = []
+ if tensor_image.ndim == 4: # Batch of images (B, H, W, C)
+ if tensor_image.shape[0] == 0:
+ self._log(f"{image_name_prefix} batch is empty (shape: {tensor_image.shape}).")
+ return None
+ for i in range(tensor_image.shape[0]):
+ img_np = tensor_image[i].cpu().numpy()
+ img_np = (img_np * 255).astype(np.uint8)
+ pil_image = Image.fromarray(img_np)
+ self._log(f"Converted {image_name_prefix} batch item {i} (original shape: {tensor_image.shape}) to PIL Image (size: {pil_image.size}).")
+ pil_images.append(pil_image)
+ elif tensor_image.ndim == 3: # Single image (H, W, C)
+ img_np = tensor_image.cpu().numpy()
+ img_np = (img_np * 255).astype(np.uint8)
+ pil_image = Image.fromarray(img_np)
+ self._log(f"Converted single {image_name_prefix} (original shape: {tensor_image.shape}) to PIL Image (size: {pil_image.size}).")
+ pil_images.append(pil_image)
+ else:
+ self._log(f"Cannot convert {image_name_prefix} with ndim {tensor_image.ndim} (shape: {tensor_image.shape}) to PIL Image(s).")
+ return None
+
+ return pil_images if pil_images else None
+
+ def _call_gemini_api(self, client_instance, model_name_full, contents, gen_config_obj, retry_indefinitely, retry_count=0, max_retries=3, call_id="0"):
+ try:
+ self._log(f"[Call {call_id}] API call attempt #{retry_count + 1} to {model_name_full}{' (retrying indefinitely)' if retry_indefinitely else ''}")
+
+ # Using client.models.generate_content like in FL_GeminiImageEditor
+ response = client_instance.models.generate_content(
+ model=model_name_full, # FL_GeminiImageEditor passes the full model string here
+ contents=contents,
+ config=gen_config_obj # FL_GeminiImageEditor uses 'config' for GenerateContentConfig
+ )
+
+ # Validate response structure (adapted from FL_GeminiImageEditor)
+ if not hasattr(response, 'candidates') or not response.candidates:
+ self._log(f"[Call {call_id}] Empty response: No candidates found")
+ if retry_indefinitely or retry_count < max_retries - 1:
+ self._log(f"[Call {call_id}] Retrying in 2 seconds... (Attempt {retry_count + 2 if not retry_indefinitely else 'N/A'}/{max_retries if not retry_indefinitely else 'inf'})")
+ time.sleep(2)
+ return self._call_gemini_api(client_instance, model_name_full, contents, gen_config_obj, retry_indefinitely, retry_count + 1, max_retries, call_id)
+ else:
+ self._log(f"[Call {call_id}] Maximum retries ({max_retries}) reached. Returning empty response.")
+ return None
+
+ if not hasattr(response.candidates[0], 'content') or response.candidates[0].content is None:
+ self._log(f"[Call {call_id}] Invalid response: candidates[0].content is missing")
+ if retry_indefinitely or retry_count < max_retries - 1:
+ self._log(f"[Call {call_id}] Retrying in 2 seconds... (Attempt {retry_count + 2 if not retry_indefinitely else 'N/A'}/{max_retries if not retry_indefinitely else 'inf'})")
+ time.sleep(2)
+ return self._call_gemini_api(client_instance, model_name_full, contents, gen_config_obj, retry_indefinitely, retry_count + 1, max_retries, call_id)
+ else:
+ self._log(f"[Call {call_id}] Maximum retries ({max_retries}) reached. Returning empty response.")
+ return None
+
+ if not hasattr(response.candidates[0].content, 'parts') or response.candidates[0].content.parts is None:
+ self._log(f"[Call {call_id}] Invalid response: candidates[0].content.parts is missing")
+ if retry_indefinitely or retry_count < max_retries - 1:
+ self._log(f"[Call {call_id}] Retrying in 2 seconds... (Attempt {retry_count + 2 if not retry_indefinitely else 'N/A'}/{max_retries if not retry_indefinitely else 'inf'})")
+ time.sleep(2)
+ return self._call_gemini_api(client_instance, model_name_full, contents, gen_config_obj, retry_indefinitely, retry_count + 1, max_retries, call_id)
+ else:
+ self._log(f"[Call {call_id}] Maximum retries ({max_retries}) reached. Returning empty response.")
+ return None
+
+ self._log(f"[Call {call_id}] Valid API response received.")
+ return response
+
+ except Exception as e:
+ self._log(f"[Call {call_id}] API call error: {str(e)}")
+ if retry_indefinitely or retry_count < max_retries - 1:
+ wait_time = 2 * (retry_count + 1) # Progressive backoff
+ self._log(f"[Call {call_id}] Retrying in {wait_time}s... (Attempt {retry_count + 2 if not retry_indefinitely else 'N/A'}/{max_retries if not retry_indefinitely else 'inf'})")
+ time.sleep(wait_time)
+ return self._call_gemini_api(client_instance, model_name_full, contents, gen_config_obj, retry_indefinitely, retry_count + 1, max_retries, call_id)
+ else:
+ self._log(f"[Call {call_id}] Max retries ({max_retries}) reached. Giving up.")
+ return None
+
+ def _process_api_response(self, response, call_id="0", always_square=False):
+ if response is None: # Simplified check from Editor
+ self._log(f"[Call {call_id}] No valid response to process.")
+ error_msg = "API Error: No content in response"
+ return self._create_error_image(error_msg), error_msg
+
+ response_text_parts = [] # Changed from response_text to response_text_parts to match ADV logic initially
+ image_tensor = None
+
+ if not hasattr(response, 'candidates') or not response.candidates: # Check from Editor
+ self._log(f"[Call {call_id}] No candidates in API response")
+ error_msg = "API returned an empty response"
+ return self._create_error_image(error_msg), error_msg
+
+ # Iterate through response parts (similar to Editor, but adapted for ADV's single image focus per call)
+ for part in response.candidates[0].content.parts:
+ if hasattr(part, 'text') and part.text is not None:
+ text_content = part.text
+ response_text_parts.append(text_content)
+ self._log(
+ f"[Call {call_id}] API returned text: {text_content[:100]}..." if len(
+ text_content) > 100 else text_content)
+
+ elif hasattr(part, 'inline_data') and part.inline_data is not None:
+ self._log(f"[Call {call_id}] API returned image data")
+ try:
+ image_data = part.inline_data.data
+
+ if not image_data or len(image_data) < 100: # Check from Editor
+ self._log(f"[Call {call_id}] Warning: Image data is empty or too small")
+ continue
+
+ pil_image = None
+ try:
+ pil_image = Image.open(BytesIO(image_data))
+ self._log(
+ f"[Call {call_id}] Direct PIL open successful, size: {pil_image.width}x{pil_image.height}")
+ except Exception as e1:
+ self._log(f"[Call {call_id}] Direct PIL open failed: {str(e1)}")
+ # Optional: Add temp file saving from Editor if direct open fails often
+ try:
+ temp_dir = tempfile.gettempdir()
+ # Ensure temp_dir is writable, or fall back
+ if not os.access(temp_dir, os.W_OK):
+ temp_dir = "." # Current directory as fallback
+ self._log(f"[Call {call_id}] Temp directory {tempfile.gettempdir()} not writable, using current directory.")
+
+ temp_file_path = os.path.join(temp_dir, f"gemini_image_adv_{call_id}_{int(time.time())}.png")
+ with open(temp_file_path, "wb") as f:
+ f.write(image_data)
+ pil_image = Image.open(temp_file_path)
+ self._log(f"[Call {call_id}] Opening via temp file {temp_file_path} successful")
+ try:
+ os.remove(temp_file_path) # Clean up temp file
+ except Exception as e_remove:
+ self._log(f"[Call {call_id}] Could not remove temp file {temp_file_path}: {e_remove}")
+ except Exception as e2:
+ self._log(f"[Call {call_id}] Opening via temp file failed: {str(e2)}")
+
+
+ if pil_image is None:
+ self._log(f"[Call {call_id}] Cannot open image, skipping")
+ continue
+
+ if pil_image.mode != 'RGB':
+ pil_image = pil_image.convert('RGB')
+ self._log(f"[Call {call_id}] Image converted to RGB mode")
+
+ # Store original dimensions for logging
+ width, height = pil_image.size
+ self._log(f"[Call {call_id}] Original image size: {width}x{height}")
+
+ # Apply padding if always_square is enabled and image needs it
+ if always_square and (width < self.min_size or height < self.min_size):
+ self._log(
+ f"[Call {call_id}] Image size {width}x{height} is smaller than minimum {self.min_size}x{self.min_size}, padding needed")
+ pil_image = self._pad_image_to_minimum_size(pil_image)
+ elif always_square:
+ self._log(f"[Call {call_id}] Always square enabled but image already meets minimum size")
+ else:
+ self._log(f"[Call {call_id}] Always square disabled, keeping original size: {width}x{height}")
+
+ img_array = np.array(pil_image).astype(np.float32) / 255.0
+ image_tensor = torch.from_numpy(img_array).unsqueeze(0) # Batch dimension
+ self._log(f"[Call {call_id}] Image processed from API response. Shape: {image_tensor.shape}")
+ break # Assuming one image per response for ADV node
+ except Exception as e:
+ self._log(f"[Call {call_id}] Error processing image from API response: {e}")
+ traceback.print_exc()
+
+ final_response_text = "\n".join(response_text_parts)
+ if image_tensor is None:
+ self._log(f"[Call {call_id}] No image found in API response parts.")
+ error_msg = "API Error: No image data in response" # More specific than Editor's default
+ image_tensor = self._create_error_image(error_msg) # Use the updated _create_error_image
+ if not final_response_text: final_response_text = error_msg # Keep this logic
+
+ return image_tensor, final_response_text
+
+ async def _generate_single_image_async(self, api_key, model_name_full, prompt_text, input_pil_images: Optional[List[Image.Image]], temperature, max_retries, retry_indefinitely, seed_val, call_id, always_square=False, aspect_ratio="1:1", image_size="1K"):
+ try:
+ try:
+ client_instance = genai.Client(api_key=api_key)
+ except TypeError:
+ genai.configure(api_key=api_key)
+ client_instance = genai.Client()
+ except AttributeError:
+ self._log(f"[Call {call_id}] CRITICAL: genai.Client not found. Please check google-genai SDK installation and version.")
+ error_msg = f"Call {call_id} Error: genai.Client not found."
+ return self._create_error_image(error_msg), error_msg, call_id
+
+ actual_seed = seed_val if seed_val != 0 else random.randint(1, 0xffffff)
+ self._log(f"[Call {call_id}] Using seed: {actual_seed} for prompt: '{prompt_text[:50]}...'")
+
+ gen_config_params = {
+ "temperature": temperature,
+ "response_modalities": ['Text', 'Image']
+ }
+ if actual_seed != 0:
+ gen_config_params["seed"] = actual_seed
+
+ # Add image config if supported
+ try:
+ # Check if ImageConfig supports imageSize parameter (SDK >= 1.50)
+ import inspect
+ image_config_sig = inspect.signature(types.ImageConfig)
+ supports_image_size = 'imageSize' in image_config_sig.parameters or 'image_size' in image_config_sig.parameters
+
+ image_config_params = {"aspectRatio": aspect_ratio}
+ # Only add imageSize for gemini-3-pro model if SDK supports it
+ if "gemini-3-pro" in model_name_full and supports_image_size:
+ image_config_params["imageSize"] = image_size
+ self._log(f"[Call {call_id}] Using imageSize: {image_size}")
+ elif "gemini-3-pro" in model_name_full:
+ self._log(f"[Call {call_id}] Warning: imageSize not supported in this SDK version. Upgrade google-genai to 1.50+ for 4K support")
+
+ gen_config_params["image_config"] = types.ImageConfig(**image_config_params)
+ except Exception as e:
+ self._log(f"[Call {call_id}] ImageConfig not available: {e}, using basic config")
+
+ gen_config_obj = types.GenerateContentConfig(**gen_config_params)
+
+ if actual_seed != 0:
+ current_seed_in_config = getattr(gen_config_obj, 'seed', None)
+ if current_seed_in_config != actual_seed:
+ self._log(f"[Call {call_id}] Warning: Seed {actual_seed} was specified. GenerateContentConfig has seed: {current_seed_in_config}. Ensure model supports seed via this config.")
+
+ contents = [prompt_text] # Start with the prompt
+ if input_pil_images: # If the list of PIL images is provided and not empty
+ for pil_img in input_pil_images:
+ if pil_img: # Ensure the image itself is not None
+ contents.append(pil_img)
+
+ loop = asyncio.get_event_loop()
+ response = await loop.run_in_executor(
+ None,
+ lambda: self._call_gemini_api(client_instance, model_name_full, contents, gen_config_obj, retry_indefinitely, 0, max_retries, call_id)
+ )
+
+ img_tensor, response_text = self._process_api_response(response, call_id, always_square)
+ return img_tensor, response_text, call_id # Return call_id to map results
+
+ except Exception as e:
+ self._log(f"[Call {call_id}] Error in async generation: {str(e)}")
+ error_msg = f"Call {call_id} Error: {str(e)}"
+ return self._create_error_image(error_msg), error_msg, call_id
+
+ def generate_images_advanced(self, inputcount, api_key, model, aspect_ratio, image_size, always_square, temperature, max_retries, prompt_1, image_1=None, seed=0, retry_indefinitely=False, **kwargs):
+ self.log_messages = []
+ if not api_key:
+ error_msg = "API key not provided."
+ self._log(error_msg)
+ error_img_instance = self._create_error_image(error_msg)
+ # API key error should return 'inputcount' error images if we can determine it,
+ # otherwise, a single error image is a reasonable fallback.
+ # Since each slot is one API call now, inputcount is the number of expected results.
+ return ([error_img_instance] * inputcount, error_msg)
+
+ pbar = ProgressBar(inputcount) # Initialize progress bar
+
+ # Setup async tasks for each input
+ async def run_batch():
+ tasks = []
+
+ for slot_idx in range(1, inputcount + 1):
+ current_prompt = prompt_1 if slot_idx == 1 else kwargs.get(f"prompt_{slot_idx}", f"Default prompt for image {slot_idx}")
+
+ current_image_tensor_for_slot = None
+ if slot_idx == 1:
+ current_image_tensor_for_slot = image_1
+ else:
+ current_image_tensor_for_slot = kwargs.get(f"image_{slot_idx}")
+
+ pil_images_for_this_slot = self._process_tensor_to_pil_list(current_image_tensor_for_slot, f"InputSlot{slot_idx}")
+
+ current_task_seed = seed + (slot_idx - 1) if seed != 0 else 0
+ task_call_id = str(slot_idx)
+
+ tasks.append(self._generate_single_image_async(
+ api_key, model, current_prompt, pil_images_for_this_slot,
+ temperature, max_retries, retry_indefinitely, current_task_seed, task_call_id, always_square,
+ aspect_ratio, image_size
+ ))
+ pbar.update_absolute(slot_idx) # Update progress bar after task is added
+
+ if not tasks:
+ self._log("No tasks were created. This might indicate an issue with inputcount or logic.")
+ return []
+
+ # Run all tasks concurrently
+ return await asyncio.gather(*tasks)
+
+ # Run the async batch processing using thread pool to avoid event loop conflicts
+ def run_sync_batch():
+ """Run async batch in a new thread with its own event loop"""
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+ try:
+ return loop.run_until_complete(run_batch())
+ finally:
+ loop.close()
+
+ results_with_id = None # Initialize results
+ try:
+ # Use thread pool executor to run async code in separate thread
+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
+ future = executor.submit(run_sync_batch)
+ results_with_id = future.result(timeout=300) # 5 minute timeout
+ except concurrent.futures.TimeoutError:
+ self._log("Async processing timed out after 5 minutes")
+ error_imgs = [self._create_error_image("Processing timeout")] * inputcount
+ return (error_imgs, "Processing timed out after 5 minutes")
+ except Exception as e:
+ self._log(f"Error in async processing: {str(e)}")
+ # Create batch of error images
+ error_imgs = [self._create_error_image(f"Async processing error: {str(e)}")] * inputcount
+ return (error_imgs, f"Async processing error: {str(e)}")
+
+ # Process results (ensure results is not None if an error occurred before assignment)
+ if results_with_id is None:
+ self._log("Async processing did not yield results, possibly due to an earlier error before gather.")
+ error_imgs = [self._create_error_image("Async processing failed to produce results")] * inputcount
+ return (error_imgs, "Async processing failed to produce results")
+
+ results_with_id.sort(key=lambda x: int(x[2]))
+
+ output_images = []
+ output_texts = []
+
+ for img_tensor, response_text, call_id_res in results_with_id:
+ output_images.append(img_tensor)
+ output_texts.append(f"Response for Input {call_id_res}:\n{response_text}")
+
+ # Return as list of individual tensors instead of batched tensor to match FL_GeminiImageEditor behavior
+ combined_responses = "\n\n".join(output_texts)
+
+ final_log_output = "Processing Logs:\n" + "\n".join(self.log_messages) + "\n\n" + combined_responses
+
+ return (output_images if output_images else [self._create_error_image("No images generated")], final_log_output)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/ai/FL_GeminiTextAPI.py b/comfyui_fill-nodes/nodes/ai/FL_GeminiTextAPI.py
new file mode 100644
index 0000000000000000000000000000000000000000..93916fa36676001002f606b4a0e09ffbc30354ce
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/FL_GeminiTextAPI.py
@@ -0,0 +1,200 @@
+import os
+import time
+import random
+import torch
+import traceback
+from google import genai
+from google.genai import types
+from typing import Optional, List, Dict, Any
+
+
+class FL_GeminiTextAPI:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "prompt": ("STRING", {"multiline": True}),
+ "api_key": ("STRING", {"default": "", "multiline": False}),
+ "model": ([
+ "gemini-3-pro-preview",
+ "gemini-2.5-pro",
+ "gemini-2.5-flash",
+ "gemini-2.5-flash-lite",
+ "gemini-2.0-flash",
+ "gemini-2.0-flash-lite",
+ "gemini-2.5-pro-preview-06-05",
+ "gemini-2.5-flash-preview-05-20",
+ "gemini-1.5-pro",
+ "gemini-1.5-flash"
+ ], {"default": "gemini-2.5-flash"}),
+ "temperature": ("FLOAT", {"default": 0.7, "min": 0.0, "max": 1.0, "step": 0.05}),
+ "max_output_tokens": ("INT", {"default": 65536, "min": 64, "max": 65536, "step": 64}),
+ "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffff}),
+ },
+ "optional": {
+ "system_instructions": ("STRING", {"multiline": True, "default": ""}),
+ "top_p": ("FLOAT", {"default": 0.95, "min": 0.0, "max": 1.0, "step": 0.01}),
+ "top_k": ("INT", {"default": 64, "min": 1, "max": 100, "step": 1}),
+ "thinking_level": (["default", "low", "high"], {"default": "default"}),
+ }
+ }
+
+ RETURN_TYPES = ("STRING",)
+ RETURN_NAMES = ("response",)
+ FUNCTION = "generate_text"
+ CATEGORY = "🏵️Fill Nodes/AI"
+
+ def __init__(self):
+ """Initialize logging system"""
+ self.log_messages = []
+
+ def _log(self, message):
+ """Global logging function: record to log list"""
+ timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
+ formatted_message = f"[FL_GeminiTextAPI] {timestamp}: {message}"
+ print(formatted_message)
+ if hasattr(self, 'log_messages'):
+ self.log_messages.append(message)
+ return message
+
+ def _call_gemini_api(self, client, model, contents, gen_config, retry_count=0, max_retries=3):
+ """Call Gemini API with retry logic using the updated generate_content method"""
+ try:
+ self._log(f"API call attempt #{retry_count + 1}")
+ response = client.models.generate_content(
+ model=model,
+ contents=contents,
+ config=gen_config
+ )
+
+ # Check if response is valid
+ if hasattr(response, 'text'):
+ self._log("Valid API response received")
+ return response
+ else:
+ self._log("Invalid API response format")
+ if retry_count < max_retries - 1:
+ self._log(f"Retrying in 2 seconds... (Attempt {retry_count + 1}/{max_retries})")
+ time.sleep(2) # Wait 2 seconds before retry
+ return self._call_gemini_api(client, model, contents, gen_config, retry_count + 1, max_retries)
+ else:
+ self._log(f"Maximum retries ({max_retries}) reached. Giving up.")
+ return None
+
+ except Exception as e:
+ self._log(f"API call error: {str(e)}")
+ if retry_count < max_retries - 1:
+ wait_time = 2 * (retry_count + 1) # Progressive backoff: 2s, 4s, 6s...
+ self._log(f"Retrying in {wait_time} seconds... (Attempt {retry_count + 1}/{max_retries})")
+ time.sleep(wait_time)
+ return self._call_gemini_api(client, model, contents, gen_config, retry_count + 1, max_retries)
+ else:
+ self._log(f"Maximum retries ({max_retries}) reached. Giving up.")
+ return None
+
+ def generate_text(self, prompt, api_key, model, temperature, max_output_tokens, seed,
+ system_instructions="", top_p=0.95, top_k=64, thinking_level="default"):
+ """Generate text response from Gemini API using the new client structure"""
+ # Reset log messages
+ self.log_messages = []
+
+ try:
+ # Check if API key is provided
+ if not api_key:
+ error_message = "Error: No API key provided. Please enter Google API key in the node."
+ self._log(error_message)
+ return (f"## ERROR: {error_message}\n\nPlease provide a valid Google API key.",)
+
+ # Validate and adjust max_output_tokens based on model limits
+ # Gemini 3.x and 2.5.x support 65536, older models support 8192
+ if model.startswith("gemini-3") or model.startswith("gemini-2.5"):
+ model_max_tokens = 65536
+ else:
+ model_max_tokens = 8192
+
+ if max_output_tokens > model_max_tokens:
+ self._log(f"Warning: {model} max output is {model_max_tokens} tokens. Reducing from {max_output_tokens} to {model_max_tokens}.")
+ max_output_tokens = model_max_tokens
+
+ # Gemini 3 models with thinking enabled need higher token budget
+ # since thinking tokens count toward max_output_tokens
+ if model.startswith("gemini-3") and thinking_level != "low":
+ min_tokens_for_thinking = 4096
+ if max_output_tokens < min_tokens_for_thinking:
+ self._log(f"Warning: Gemini 3 with thinking needs more tokens. Increasing from {max_output_tokens} to {min_tokens_for_thinking}.")
+ max_output_tokens = min_tokens_for_thinking
+
+ # Create client instance with API key
+ # Use v1alpha for Gemini 3 models
+ if model.startswith("gemini-3"):
+ client = genai.Client(
+ api_key=api_key,
+ http_options=types.HttpOptions(api_version="v1alpha")
+ )
+ self._log(f"Using v1alpha API for {model}")
+ else:
+ client = genai.Client(api_key=api_key)
+
+ # Set random seeds for reproducibility
+ random.seed(seed)
+ torch.manual_seed(seed)
+
+ gen_config = types.GenerateContentConfig(
+ temperature=temperature,
+ max_output_tokens=max_output_tokens,
+ top_p=top_p,
+ top_k=top_k,
+ candidate_count=1
+ )
+
+ # Add thinking configuration based on model and thinking_level
+ if thinking_level != "default":
+ if model.startswith("gemini-3"):
+ # Gemini 3 uses ThinkingConfig with thinking_level
+ gen_config.thinking_config = types.ThinkingConfig(
+ thinking_level=thinking_level.upper()
+ )
+ self._log(f"Using thinking_level: {thinking_level.upper()}")
+ elif model.startswith("gemini-2.5"):
+ # Gemini 2.5 uses ThinkingConfig with thinking_budget
+ if thinking_level == "low":
+ gen_config.thinking_config = types.ThinkingConfig(thinking_budget=0)
+ self._log(f"Disabled thinking (budget: 0)")
+ # "high" is default for 2.5, no need to specify
+
+ # Add system instructions if provided
+ if system_instructions and system_instructions.strip():
+ self._log(f"Using system instructions: {system_instructions[:50]}...")
+ gen_config.system_instruction = system_instructions
+
+ self._log(f"Sending prompt to Gemini API (model: {model}, temp: {temperature})")
+
+ # Make API call with contents parameter
+ response = self._call_gemini_api(
+ client=client,
+ model=model,
+ contents=[prompt], # Contents expects a list
+ gen_config=gen_config,
+ max_retries=3
+ )
+
+ # Check if we got a valid response
+ if response is None:
+ error_text = "Failed to get response from Gemini API after multiple attempts."
+ self._log(error_text)
+ return (f"## API Error\n{error_text}\n\n## Debug Log\n" + "\n".join(self.log_messages),)
+
+ # Extract and return the raw text from the response
+ result_text = response.text.strip() # Remove any leading/trailing whitespace
+
+ self._log(f"Received response ({len(result_text)} characters)")
+
+ return (result_text,)
+
+ except Exception as e:
+ error_message = f"Error: {str(e)}"
+ self._log(error_message)
+ traceback.print_exc()
+
+ # Return error message and debug log
+ return (f"## Error\n{error_message}\n\n## Debug Log\n" + "\n".join(self.log_messages),)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/ai/FL_GeminiVideoCaptioner.py b/comfyui_fill-nodes/nodes/ai/FL_GeminiVideoCaptioner.py
new file mode 100644
index 0000000000000000000000000000000000000000..41c17c734119f5df618e09a02d6f1a4c54ac3bba
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/FL_GeminiVideoCaptioner.py
@@ -0,0 +1,916 @@
+import os
+import tempfile
+import cv2
+import numpy as np
+import torch
+import requests
+import base64
+import json
+import time
+import mimetypes
+import shutil
+from PIL import Image
+from datetime import timedelta
+from comfy.utils import ProgressBar
+
+
+class FL_GeminiVideoCaptioner:
+ """
+ Node for captioning videos using Google's Gemini API.
+
+ Note: All videos (from file or image batch) are converted to WebM format with a size limit
+ of just under 30MB to ensure compatibility with the Gemini API payload limitations.
+ Video quality will be adjusted automatically to meet the size requirement.
+ """
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "api_key": ("STRING", {"default": "", "multiline": False}),
+ "model": ([
+ "gemini-3-pro-preview",
+ "gemini-2.5-pro",
+ "gemini-2.5-flash",
+ "gemini-2.5-flash-lite",
+ "gemini-2.0-flash",
+ "gemini-2.0-flash-lite",
+ "gemini-1.5-pro",
+ "gemini-1.5-flash",
+ "gemini-1.5-flash-8b"
+ ], {"default": "gemini-2.5-flash"}),
+ "frames_per_second": ("FLOAT", {"default": 1.0, "min": 0.1, "max": 10.0, "step": 0.1}),
+ "max_duration_minutes": ("FLOAT", {"default": 2.0, "min": 0.1, "max": 45.0, "step": 0.1}),
+ "prompt": ("STRING", {
+ "default": "Describe this video scene in detail. Include any important actions, subjects, settings, and atmosphere.",
+ "multiline": True
+ }),
+ "process_audio": (["false", "true"], {"default": "false"}),
+ "temperature": ("FLOAT", {"default": 0.7, "min": 0.0, "max": 1.0, "step": 0.1}),
+ "max_output_tokens": ("INT", {"default": 65536, "min": 50, "max": 65536, "step": 64}),
+ "top_p": ("FLOAT", {"default": 0.95, "min": 0.0, "max": 1.0, "step": 0.01}),
+ "top_k": ("INT", {"default": 64, "min": 1, "max": 100, "step": 1}),
+ "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffff}),
+ "thinking_level": (["default", "low", "high"], {"default": "default"}),
+ },
+ "optional": {
+ "video_path": ("STRING", {"default": ""}),
+ "image": ("IMAGE", {}),
+ }
+ }
+
+ RETURN_TYPES = ("STRING", "IMAGE",)
+ RETURN_NAMES = ("caption", "sampled_frame",)
+ FUNCTION = "generate_video_caption"
+ CATEGORY = "🏵️Fill Nodes/AI"
+
+ def generate_video_caption(self, api_key, model, frames_per_second, max_duration_minutes,
+ prompt, process_audio, temperature, max_output_tokens, top_p, top_k, seed,
+ thinking_level, video_path=None, image=None):
+ if not api_key:
+ raise ValueError("Gemini API key is required")
+
+ # Check if we have either a video path or image input
+ if (not video_path or not os.path.exists(video_path)) and image is None:
+ raise ValueError("Either a valid video path or image input is required")
+
+ # Validate and adjust max_output_tokens based on model limits
+ # Gemini 3.x and 2.5.x support 65536, older models support 8192
+ if model.startswith("gemini-3") or model.startswith("gemini-2.5"):
+ model_max_tokens = 65536
+ else:
+ model_max_tokens = 8192
+
+ if max_output_tokens > model_max_tokens:
+ print(f"[FL_GeminiVideoCaptioner] Warning: {model} max output is {model_max_tokens} tokens. Reducing from {max_output_tokens} to {model_max_tokens}.")
+ max_output_tokens = model_max_tokens
+
+ # Gemini 3 models with thinking enabled need higher token budget
+ # since thinking tokens count toward max_output_tokens
+ if model.startswith("gemini-3") and thinking_level != "low":
+ min_tokens_for_thinking = 4096
+ if max_output_tokens < min_tokens_for_thinking:
+ print(f"[FL_GeminiVideoCaptioner] Warning: Gemini 3 with thinking needs more tokens. Increasing from {max_output_tokens} to {min_tokens_for_thinking}.")
+ max_output_tokens = min_tokens_for_thinking
+
+ # Validate model-specific limitations
+ process_audio = process_audio == "true"
+
+ # Calculate max frames based on model and duration limits
+ max_seconds = int(max_duration_minutes * 60)
+ max_seconds = min(max_seconds, 45 * 60) # 45 minutes max for all supported models
+
+ # Process based on input type (video file or image batch)
+ if video_path and os.path.exists(video_path):
+ # Processing a video file
+ mime_type = mimetypes.guess_type(video_path)[0]
+ if not mime_type or not mime_type.startswith("video/"):
+ if mime_type:
+ raise ValueError(f"Unsupported file type: {mime_type}. Please provide a video file.")
+ else:
+ # Try to infer from extension
+ ext = os.path.splitext(video_path)[1].lower()
+ if ext in ['.mp4', '.avi', '.mov', '.webm', '.wmv', '.flv', '.mpg', '.mpeg']:
+ mime_type = f"video/{ext[1:]}"
+ else:
+ raise ValueError(f"Unrecognized video format: {ext}. Please provide a supported video file.")
+
+ # Extract video info
+ video_info = self.get_video_info(video_path)
+ video_duration = min(video_info['duration'], max_seconds)
+ print(f"[FL_GeminiVideoCaptioner] Video duration: {timedelta(seconds=video_duration)}")
+
+ # Convert to WebM with size limit for direct API submission
+ print(f"[FL_GeminiVideoCaptioner] Converting video to WebM format...")
+ webm_path = self.convert_to_webm(video_path)
+
+ # Extract a middle frame for preview
+ cap = cv2.VideoCapture(video_path)
+ middle_frame_pos = int(video_info['frame_count'] / 2)
+ cap.set(cv2.CAP_PROP_POS_FRAMES, middle_frame_pos)
+ ret, middle_frame = cap.read()
+ cap.release()
+
+ if not ret:
+ # Fallback to first frame if middle frame extraction fails
+ cap = cv2.VideoCapture(video_path)
+ ret, middle_frame = cap.read()
+ cap.release()
+
+ if ret:
+ # Convert BGR to RGB
+ middle_frame = cv2.cvtColor(middle_frame, cv2.COLOR_BGR2RGB)
+ sample_frame_np = np.array(middle_frame).astype(np.float32) / 255.0
+ sample_frame_tensor = torch.from_numpy(sample_frame_np)[None,]
+ else:
+ # Create a blank frame if extraction fails
+ sample_frame_np = np.zeros((512, 512, 3), dtype=np.float32)
+ sample_frame_tensor = torch.from_numpy(sample_frame_np)[None,]
+
+ # If WebM conversion failed, fall back to frame extraction
+ if webm_path is None:
+ print(f"[FL_GeminiVideoCaptioner] WebM conversion failed, falling back to frame extraction...")
+ frames, frame_timestamps = self.extract_frames(video_path, frames_per_second, max_seconds)
+ if not frames:
+ raise ValueError(f"Failed to extract frames from video: {video_path}")
+
+ print(f"[FL_GeminiVideoCaptioner] Extracted {len(frames)} frames at {frames_per_second} fps")
+
+ # Generate captions for frames
+ caption = self.get_caption_with_frames(
+ api_key,
+ frames,
+ prompt,
+ model,
+ temperature,
+ max_output_tokens,
+ top_p,
+ top_k,
+ seed,
+ thinking_level
+ )
+ else:
+ # Use the WebM file for captioning
+ mime_type = "video/webm"
+ print(f"[FL_GeminiVideoCaptioner] Using WebM video for captioning")
+
+ # Get caption using the WebM file
+ caption = self.get_caption_with_video_file(
+ api_key,
+ webm_path,
+ mime_type,
+ prompt,
+ model,
+ process_audio,
+ temperature,
+ max_output_tokens,
+ top_p,
+ top_k,
+ seed,
+ thinking_level
+ )
+
+ # Clean up temporary WebM file
+ os.unlink(webm_path)
+
+ return (caption, sample_frame_tensor)
+
+ else:
+ # Processing an image batch
+ if image is None:
+ raise ValueError("Image input is required when no video path is provided")
+
+ print(f"[FL_GeminiVideoCaptioner] Processing image batch with {image.shape[0]} frames")
+
+ # Convert tensor images to numpy arrays
+ frames = []
+
+ # Extract frames from the image tensor
+ for i in range(image.shape[0]):
+ # Convert tensor to numpy array (0-255 range)
+ img_np = (image[i].cpu().numpy() * 255).astype(np.uint8)
+ frames.append(img_np)
+
+ # Choose a middle frame as sample output
+ middle_idx = len(frames) // 2
+ sample_frame_tensor = image[middle_idx].unsqueeze(0) if image.shape[0] > 0 else None
+
+ # If only one frame is provided, send as JPEG directly (all models support this)
+ if len(frames) == 1:
+ print(f"[FL_GeminiVideoCaptioner] Single frame input for {model}, using direct frame processing (JPEG).")
+ caption = self.get_caption_with_frames(
+ api_key,
+ frames, # This will be a list with one frame
+ prompt,
+ model,
+ temperature,
+ max_output_tokens,
+ top_p,
+ top_k,
+ seed,
+ thinking_level
+ )
+ else:
+ # Original logic: try to create WebM, then send video file or fallback to frames
+ print(f"[FL_GeminiVideoCaptioner] Creating WebM video from {len(frames)} frames...")
+ webm_path = self.create_webm_from_frames(frames, fps=frames_per_second)
+
+ if webm_path is None:
+ print(f"[FL_GeminiVideoCaptioner] WebM creation failed, falling back to frame processing...")
+ caption = self.get_caption_with_frames(
+ api_key,
+ frames,
+ prompt,
+ model,
+ temperature,
+ max_output_tokens,
+ top_p,
+ top_k,
+ seed,
+ thinking_level
+ )
+ else:
+ mime_type = "video/webm"
+ print(f"[FL_GeminiVideoCaptioner] Using WebM video for captioning")
+ caption = self.get_caption_with_video_file(
+ api_key,
+ webm_path,
+ mime_type,
+ prompt,
+ model,
+ process_audio,
+ temperature,
+ max_output_tokens,
+ top_p,
+ top_k,
+ seed,
+ thinking_level
+ )
+ os.unlink(webm_path) # Clean up temporary WebM file
+
+ return (caption, sample_frame_tensor)
+
+ def get_video_info(self, video_path):
+ """Get basic information about the video file"""
+ cap = cv2.VideoCapture(video_path)
+ if not cap.isOpened():
+ raise ValueError(f"Could not open video file: {video_path}")
+
+ # Get video properties
+ frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
+ fps = cap.get(cv2.CAP_PROP_FPS)
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
+
+ # Calculate duration in seconds
+ duration = frame_count / fps if fps > 0 else 0
+
+ cap.release()
+
+ return {
+ 'frame_count': frame_count,
+ 'fps': fps,
+ 'width': width,
+ 'height': height,
+ 'duration': duration
+ }
+
+ def extract_frames(self, video_path, target_fps, max_seconds):
+ """Extract frames at specified fps from a video file, up to max_seconds"""
+ cap = cv2.VideoCapture(video_path)
+ if not cap.isOpened():
+ return [], []
+
+ # Get video properties
+ original_fps = cap.get(cv2.CAP_PROP_FPS)
+ frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
+
+ # Calculate how many frames to skip to achieve target_fps
+ if original_fps <= 0:
+ print("[Warning] Could not determine video FPS. Using 30 fps as default.")
+ original_fps = 30
+
+ frame_interval = max(1, round(original_fps / target_fps))
+
+ # Calculate total duration and limit frames
+ duration = min(frame_count / original_fps, max_seconds)
+ max_frames = int(duration * target_fps)
+
+ frames = []
+ timestamps = [] # in seconds
+
+ progress = ProgressBar(max_frames)
+ frame_idx = 0
+ frame_count = 0
+
+ while True:
+ ret, frame = cap.read()
+ if not ret or len(frames) >= max_frames:
+ break
+
+ # Process frame at intervals to achieve target_fps
+ if frame_idx % frame_interval == 0:
+ # Convert BGR to RGB
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
+ frames.append(frame_rgb)
+
+ # Calculate timestamp in seconds
+ timestamp = frame_idx / original_fps
+ timestamps.append(timestamp)
+
+ progress.update_absolute(frame_count)
+ frame_count += 1
+
+ frame_idx += 1
+
+ cap.release()
+ return frames, timestamps
+
+ def get_gemini_caption(self, api_key, frames, timestamps, video_path, mime_type, prompt, model,
+ process_audio, temperature, max_output_tokens, top_p, top_k, seed):
+ """Send frames to Gemini API and get caption response"""
+
+ # All supported models can handle direct video input
+ return self.get_caption_with_video_file(
+ api_key, video_path, mime_type, prompt, model, process_audio,
+ temperature, max_output_tokens, top_p, top_k, seed
+ )
+
+ def get_caption_with_frames(self, api_key, frames, prompt, model, temperature, max_output_tokens, top_p, top_k,
+ seed, thinking_level="default"):
+ """Send individual frames to Gemini API"""
+ # Use API version v1alpha for Gemini 3, v1beta for others
+ if model.startswith("gemini-3"):
+ api_url = f"https://generativelanguage.googleapis.com/v1alpha/models/{model}:generateContent?key={api_key}"
+ else:
+ api_url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={api_key}"
+
+ content_parts = []
+
+ # Set frame limit based on model capabilities
+ if model.startswith("gemini-3"):
+ max_frames = min(len(frames), 150) # Gemini 3 can handle even more frames
+ elif model.startswith("gemini-2.5"):
+ max_frames = min(len(frames), 120) # Gemini 2.5 can handle more frames
+ elif model.startswith("gemini-2.0") or model.startswith("gemini-1.5"):
+ max_frames = min(len(frames), 60) # Gemini 2.0 and 1.5 models
+ else:
+ max_frames = min(len(frames), 60) # Default for all supported models
+
+ frames_to_process = frames[:max_frames]
+
+ print(
+ f"[FL_GeminiVideoCaptioner] Processing {len(frames_to_process)} out of {len(frames)} total frames for {model}")
+ progress = ProgressBar(len(frames_to_process))
+
+ # Add frames as mimetype image/jpeg
+ for i, frame in enumerate(frames_to_process):
+ # Convert numpy array to PIL Image
+ img = Image.fromarray(frame)
+
+ # Save image to temp file
+ with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as temp:
+ img.save(temp, format="JPEG")
+ temp_filename = temp.name
+
+ # Read the image file and encode to base64
+ with open(temp_filename, "rb") as img_file:
+ base64_image = base64.b64encode(img_file.read()).decode("utf-8")
+
+ # Add to content parts
+ content_parts.append({
+ "inline_data": {
+ "mime_type": "image/jpeg",
+ "data": base64_image
+ }
+ })
+
+ # Delete temp file
+ os.unlink(temp_filename)
+ progress.update_absolute(i)
+
+ # Add the prompt after the frames for all supported models
+ content_parts.append({"text": prompt})
+
+ # Prepare request payload
+ payload = {
+ "contents": [{
+ "role": "user",
+ "parts": content_parts
+ }],
+ "generation_config": {
+ "temperature": temperature,
+ "maxOutputTokens": max_output_tokens,
+ "topP": top_p,
+ "topK": top_k,
+ "seed": seed
+ }
+ }
+
+ # Add thinking configuration based on model
+ if thinking_level != "default":
+ if model.startswith("gemini-3"):
+ # Gemini 3 uses thinkingConfig with thinkingLevel
+ payload["generation_config"]["thinkingConfig"] = {
+ "thinkingLevel": thinking_level.upper()
+ }
+ print(f"[FL_GeminiVideoCaptioner] Using thinking_level: {thinking_level.upper()}")
+ elif model.startswith("gemini-2.5"):
+ # Gemini 2.5 uses thinkingConfig with thinkingBudget
+ if thinking_level == "low":
+ payload["generation_config"]["thinkingConfig"] = {"thinkingBudget": 0}
+ print(f"[FL_GeminiVideoCaptioner] Disabled thinking (budget: 0)")
+ # "high" is default for 2.5, no need to specify
+
+ # Send request
+ print(f"[FL_GeminiVideoCaptioner] Sending request to Gemini API ({model})...")
+ return self._send_api_request(api_url, payload)
+
+ def get_caption_with_video_file(self, api_key, video_path, mime_type, prompt, model,
+ process_audio, temperature, max_output_tokens, top_p, top_k, seed,
+ thinking_level="default"):
+ """Send entire video file to Gemini API (for Gemini 1.5+ models)"""
+ # Use API version v1alpha for Gemini 3, v1beta for others
+ if model.startswith("gemini-3"):
+ api_url = f"https://generativelanguage.googleapis.com/v1alpha/models/{model}:generateContent?key={api_key}"
+ else:
+ api_url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={api_key}"
+
+ # Check if this is a Gemini 2.5 model (known to have video processing issues)
+ is_gemini_25 = model.startswith("gemini-2.5")
+ if is_gemini_25:
+ print(f"[FL_GeminiVideoCaptioner] Warning: {model} has known video processing issues, will fallback to frame extraction if video processing fails")
+
+ # For newer models (1.5+), we can send the entire video file
+ print(f"[FL_GeminiVideoCaptioner] Processing video file directly with {model}")
+
+ # Check file size
+ file_size = os.path.getsize(video_path)
+ max_request_size = 30 * 1024 * 1024 # 30MB
+
+ if file_size > max_request_size:
+ print(
+ f"[FL_GeminiVideoCaptioner] Warning: Video file size ({file_size / (1024 * 1024):.2f}MB) exceeds the direct API request limit of 30MB.")
+
+ # Try to compress the video to WebM if not already
+ if not mime_type or mime_type != "video/webm":
+ print(f"[FL_GeminiVideoCaptioner] Attempting to compress to WebM format...")
+ webm_path = self.convert_to_webm(video_path)
+
+ if webm_path:
+ # Use the compressed WebM file instead
+ video_path = webm_path
+ mime_type = "video/webm"
+ file_size = os.path.getsize(video_path)
+ print(f"[FL_GeminiVideoCaptioner] Compressed to WebM: {file_size / (1024 * 1024):.2f}MB")
+
+ # If still too large, fall back to frame extraction
+ if file_size > max_request_size:
+ print(f"[FL_GeminiVideoCaptioner] Video still too large, falling back to frame extraction...")
+ frames, timestamps = self.extract_frames(video_path, 1.0, 300) # 1 fps, max 5 minutes
+
+ # Clean up temporary WebM file if we created one
+ if 'webm_path' in locals() and webm_path:
+ os.unlink(webm_path)
+
+ if not frames:
+ return "Error: Failed to extract frames from large video file"
+
+ return self.get_caption_with_frames(
+ api_key, frames, prompt, model, temperature, max_output_tokens, top_p, top_k, seed, thinking_level
+ )
+
+ # Read video file and encode to base64
+ with open(video_path, "rb") as video_file:
+ video_data = video_file.read()
+ base64_video = base64.b64encode(video_data).decode("utf-8")
+
+ # Prepare API request
+ content_parts = [{
+ "inline_data": {
+ "mime_type": mime_type,
+ "data": base64_video
+ }
+ }, {
+ "text": prompt
+ }]
+
+ # Prepare request payload
+ payload = {
+ "contents": [{
+ "role": "user",
+ "parts": content_parts
+ }],
+ "generation_config": {
+ "temperature": temperature,
+ "maxOutputTokens": max_output_tokens,
+ "topP": top_p,
+ "topK": top_k
+ }
+ }
+
+ # Add thinking configuration based on model
+ if thinking_level != "default":
+ if model.startswith("gemini-3"):
+ # Gemini 3 uses thinkingConfig with thinkingLevel
+ payload["generation_config"]["thinkingConfig"] = {
+ "thinkingLevel": thinking_level.upper()
+ }
+ print(f"[FL_GeminiVideoCaptioner] Using thinking_level: {thinking_level.upper()}")
+ elif model.startswith("gemini-2.5"):
+ # Gemini 2.5 uses thinkingConfig with thinkingBudget
+ if thinking_level == "low":
+ payload["generation_config"]["thinkingConfig"] = {"thinkingBudget": 0}
+ print(f"[FL_GeminiVideoCaptioner] Disabled thinking (budget: 0)")
+ # "high" is default for 2.5, no need to specify
+
+ # Send request
+ print(f"[FL_GeminiVideoCaptioner] Sending video to Gemini API ({model})...")
+ response = self._send_api_request(api_url, payload)
+
+ # Check if Gemini 2.5 failed and fallback to frame extraction
+ if is_gemini_25 and (response.startswith("Error:") or response.startswith("Failed to get caption")):
+ print(f"[FL_GeminiVideoCaptioner] {model} video processing failed, falling back to frame extraction...")
+
+ # Extract frames and try again
+ frames, timestamps = self.extract_frames(video_path, 1.0, 300) # 1 fps, max 5 minutes
+
+ # Clean up temporary WebM file if we created one
+ if 'webm_path' in locals() and webm_path:
+ os.unlink(webm_path)
+
+ if not frames:
+ return f"Error: Both video processing and frame extraction failed for {model}"
+
+ return self.get_caption_with_frames(
+ api_key, frames, prompt, model, temperature, max_output_tokens, top_p, top_k, seed, thinking_level
+ )
+
+ return response
+
+ def convert_to_webm(self, input_path, max_size_mb=29):
+ """Convert any video to WebM format with size limit using OpenCV
+
+ Args:
+ input_path: Path to input video file
+ max_size_mb: Maximum size in MB for the output WebM file
+
+ Returns:
+ Path to the converted WebM file
+ """
+ output_path = None
+ cap = None
+ out = None
+ successful_conversion = False
+
+ try:
+ # Create a temporary file for the output
+ with tempfile.NamedTemporaryFile(suffix=".webm", delete=False) as temp_webm:
+ output_path = temp_webm.name
+
+ # Open input video
+ cap = cv2.VideoCapture(input_path)
+ if not cap.isOpened():
+ raise ValueError(f"Could not open video file: {input_path}")
+
+ # Get video properties
+ fps = cap.get(cv2.CAP_PROP_FPS)
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
+ frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
+ duration = frame_count / fps if fps > 0 else 0
+
+ # Cap duration if very long video (45 minutes max)
+ max_duration = 45 * 60 # 45 minutes in seconds
+ max_frames = int(min(duration, max_duration) * fps)
+
+ # Start with high quality and gradually reduce
+ max_size_bytes = max_size_mb * 1024 * 1024
+ size_factors = [1.0, 0.75, 0.5, 0.25, 0.125] # Progressive size reduction
+
+ for size_factor in size_factors:
+ # Calculate new dimensions
+ new_width = int(width * size_factor)
+ new_height = int(height * size_factor)
+
+ # Ensure dimensions are even by flooring to the nearest even number, min 2
+ new_width = (new_width // 2) * 2
+ new_width = max(2, new_width)
+ new_height = (new_height // 2) * 2
+ new_height = max(2, new_height)
+
+ # Try different quality settings
+ for quality in [95, 80, 60, 40, 20]:
+ print(f"[FL_GeminiVideoCaptioner] Converting to WebM: {new_width}x{new_height}, quality={quality}")
+
+ try:
+ # Create VideoWriter object
+ fourcc = cv2.VideoWriter_fourcc(*'VP80') # WebM codec
+ out = cv2.VideoWriter(
+ output_path,
+ fourcc,
+ fps,
+ (new_width, new_height),
+ isColor=True
+ )
+
+ if not out.isOpened():
+ raise Exception("Failed to open VideoWriter")
+
+ frame_count = 0
+ cap.set(cv2.CAP_PROP_POS_FRAMES, 0) # Reset to start
+
+ while True:
+ ret, frame = cap.read()
+ if not ret or frame_count >= max_frames:
+ break
+
+ # Resize frame if needed
+ if size_factor != 1.0:
+ frame = cv2.resize(frame, (new_width, new_height))
+
+ out.write(frame)
+ frame_count += 1
+
+ # Release VideoWriter
+ if out is not None:
+ out.release()
+ out = None
+
+ # Check file size
+ file_size = os.path.getsize(output_path)
+ if file_size <= max_size_bytes:
+ print(f"[FL_GeminiVideoCaptioner] Created WebM: {file_size / 1024 / 1024:.2f}MB")
+ successful_conversion = True
+ return output_path
+
+ print(
+ f"[FL_GeminiVideoCaptioner] File too large ({file_size / 1024 / 1024:.2f}MB), retrying with lower quality")
+
+ except Exception as e:
+ print(f"[FL_GeminiVideoCaptioner] Error during conversion: {e}")
+ if out is not None:
+ out.release()
+ out = None
+ continue
+
+ print("[FL_GeminiVideoCaptioner] Could not create WebM within size limit")
+ return None
+
+ except Exception as e:
+ print(f"[FL_GeminiVideoCaptioner] Error converting to WebM: {e}")
+ return None
+
+ finally:
+ # Cleanup resources
+ if cap is not None:
+ cap.release()
+ if out is not None:
+ out.release()
+ if not successful_conversion and output_path and os.path.exists(output_path):
+ try:
+ os.unlink(output_path)
+ except Exception as e:
+ print(f"[FL_GeminiVideoCaptioner] Warning: Failed to delete temp file {output_path} in convert_to_webm finally: {e}")
+ pass
+
+ def create_webm_from_frames(self, frames, fps=30, max_size_mb=29):
+ """Create a WebM video from a list of frames using OpenCV
+
+ Args:
+ frames: List of numpy arrays representing frames
+ fps: Frames per second
+ max_size_mb: Maximum size in MB for the output WebM file
+
+ Returns:
+ Path to the created WebM file or None if creation fails
+ """
+ if not frames:
+ return None
+
+ output_path = None
+ out = None
+
+ try:
+ # Create a temporary file for the output WebM
+ with tempfile.NamedTemporaryFile(suffix=".webm", delete=False) as temp_webm:
+ output_path = temp_webm.name
+
+ # Get dimensions from the first frame
+ height, width = frames[0].shape[:2]
+
+ # Ensure dimensions are even by flooring to the nearest even number, min 2
+ width = (width // 2) * 2
+ width = max(2, width)
+ height = (height // 2) * 2
+ height = max(2, height)
+
+ # Set size reduction factors and quality
+ size_factors = [1.0, 0.75, 0.5, 0.25, 0.125]
+ max_size_bytes = max_size_mb * 1024 * 1024
+
+ # Ensure frames are in correct format
+ processed_frames = []
+ for frame in frames:
+ if frame.dtype != np.uint8:
+ # Convert from float [0-1] to uint8 [0-255] if needed
+ frame = (frame * 255).astype(np.uint8)
+ # Convert BGR to RGB if needed
+ if len(frame.shape) == 3 and frame.shape[2] == 3:
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
+ processed_frames.append(frame)
+
+ # Try different size factors and quality settings
+ for size_factor in size_factors:
+ # Calculate new dimensions
+ new_width = int(width * size_factor)
+ new_height = int(height * size_factor)
+
+ # Ensure dimensions are even by flooring to the nearest even number, min 2
+ new_width = (new_width // 2) * 2
+ new_width = max(2, new_width)
+ new_height = (new_height // 2) * 2
+ new_height = max(2, new_height)
+
+ # Try different quality settings
+ for quality in [95, 80, 60, 40, 20]:
+ print(f"[FL_GeminiVideoCaptioner] Creating WebM: {new_width}x{new_height}, quality={quality}")
+
+ try:
+ # Create VideoWriter object
+ fourcc = cv2.VideoWriter_fourcc(*'VP80') # WebM codec
+ out = cv2.VideoWriter(
+ output_path,
+ fourcc,
+ fps,
+ (new_width, new_height),
+ isColor=True
+ )
+
+ if not out.isOpened():
+ raise Exception("Failed to open VideoWriter")
+
+ for frame in processed_frames:
+ # Resize frame if needed
+ if size_factor != 1.0:
+ frame = cv2.resize(frame, (new_width, new_height))
+
+ # Apply quality compression
+ encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), quality]
+ _, encoded_frame = cv2.imencode('.jpg', frame, encode_param)
+ frame = cv2.imdecode(encoded_frame, cv2.IMREAD_COLOR)
+
+ # Write frame
+ out.write(frame)
+
+ # Release VideoWriter
+ if out is not None:
+ out.release()
+ out = None
+
+ # Check file size
+ file_size = os.path.getsize(output_path)
+ if file_size <= max_size_bytes:
+ print(
+ f"[FL_GeminiVideoCaptioner] Created WebM: {file_size / 1024 / 1024:.2f}MB with dimensions {new_width}x{new_height}")
+ return output_path
+
+ print(
+ f"[FL_GeminiVideoCaptioner] File too large ({file_size / 1024 / 1024:.2f}MB), retrying with lower quality")
+
+ except Exception as e:
+ print(f"[FL_GeminiVideoCaptioner] Error while creating video: {e}")
+ if out is not None:
+ out.release()
+ out = None
+ continue
+
+ # If we couldn't get under the size limit, cleanup and return None
+ print("[FL_GeminiVideoCaptioner] Couldn't create WebM within size limit")
+ if os.path.exists(output_path):
+ os.unlink(output_path)
+ return None
+
+ except Exception as e:
+ print(f"[FL_GeminiVideoCaptioner] Error creating WebM from frames: {e}")
+ if output_path and os.path.exists(output_path):
+ os.unlink(output_path)
+ return None
+
+ finally:
+ # Cleanup resources
+ if out is not None:
+ out.release()
+
+ def _send_api_request(self, api_url, payload):
+ """Helper method to send API request and handle response"""
+ try:
+ response = requests.post(
+ api_url,
+ headers={"Content-Type": "application/json"},
+ data=json.dumps(payload),
+ timeout=300 # Longer timeout for video processing
+ )
+
+ if response.status_code != 200:
+ error_msg = f"API error: {response.status_code} - {response.text}"
+ print(f"[FL_GeminiVideoCaptioner] {error_msg}")
+ return f"Error: {error_msg}"
+
+ result = response.json()
+
+ # Debug: Log the response structure for troubleshooting
+ print(f"[FL_GeminiVideoCaptioner] Response keys: {list(result.keys())}")
+
+ if "candidates" in result and len(result["candidates"]) > 0:
+ candidate = result["candidates"][0]
+ content = candidate.get("content", {})
+
+ # Debug: Log candidate and content structure
+ print(f"[FL_GeminiVideoCaptioner] Candidate keys: {list(candidate.keys())}")
+ if content:
+ print(f"[FL_GeminiVideoCaptioner] Content keys: {list(content.keys())}")
+
+ if "parts" in content and len(content["parts"]) > 0:
+ # Debug: Log parts structure
+ print(f"[FL_GeminiVideoCaptioner] Number of parts: {len(content['parts'])}")
+ for i, part in enumerate(content["parts"]):
+ print(f"[FL_GeminiVideoCaptioner] Part {i} keys: {list(part.keys())}")
+
+ # Check each part for text content
+ # For Gemini 3 with thinking, there may be "thought" parts and "text" parts
+ # We want to extract the actual response text, not the thinking process
+ text_parts = []
+ for part in content["parts"]:
+ # Skip thought/thinking parts - we want the actual output
+ if "thought" in part:
+ print(f"[FL_GeminiVideoCaptioner] Skipping thought part")
+ continue
+ if "text" in part:
+ text_parts.append(part["text"])
+
+ if text_parts:
+ caption = "\n".join(text_parts)
+ print(f"[FL_GeminiVideoCaptioner] Successfully extracted caption ({len(caption)} chars)")
+ return caption
+
+ # Gemini 3 may return text directly in candidate
+ if "text" in candidate:
+ return candidate["text"]
+
+ # Check for finishReason that might indicate an issue
+ finish_reason = candidate.get("finishReason", "")
+ if finish_reason == "MAX_TOKENS":
+ # Gemini 3 with thinking enabled may exhaust tokens on thinking
+ # Check if we got any content at all
+ usage = result.get("usageMetadata", {})
+ thoughts_tokens = usage.get("thoughtsTokenCount", 0)
+ if thoughts_tokens > 0 and not content.get("parts"):
+ return f"Error: Model exhausted output tokens on thinking ({thoughts_tokens} thinking tokens used). Try increasing max_output_tokens or setting thinking_level to 'low'."
+ else:
+ print(f"[FL_GeminiVideoCaptioner] Response was truncated (MAX_TOKENS)")
+ elif finish_reason and finish_reason != "STOP":
+ print(f"[FL_GeminiVideoCaptioner] Unexpected finishReason: {finish_reason}")
+
+ elif "promptFeedback" in result and result["promptFeedback"].get("blockReason"):
+ block_reason = result["promptFeedback"]["blockReason"]
+ block_msg = f"Content blocked by Gemini API. Reason: {block_reason}"
+ print(f"[FL_GeminiVideoCaptioner] {block_msg}")
+ return f"Error: {block_msg}"
+
+ # Log full response for debugging unexpected formats
+ print(f"[FL_GeminiVideoCaptioner] Full response: {json.dumps(result, indent=2)[:2000]}")
+ return "Failed to get caption from Gemini API: unexpected response format"
+
+ except requests.RequestException as e:
+ error_msg = f"Network error during API call: {str(e)}"
+ print(f"[FL_GeminiVideoCaptioner] {error_msg}")
+ return f"Error: {error_msg}"
+ except json.JSONDecodeError as e:
+ error_msg = f"Failed to parse API response: {str(e)}"
+ print(f"[FL_GeminiVideoCaptioner] {error_msg}")
+ return f"Error: {error_msg}"
+ except Exception as e:
+ error_msg = f"Unexpected error: {str(e)}"
+ print(f"[FL_GeminiVideoCaptioner] {error_msg}")
+ return f"Error: {error_msg}"
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/ai/FL_Hedra_API.py b/comfyui_fill-nodes/nodes/ai/FL_Hedra_API.py
new file mode 100644
index 0000000000000000000000000000000000000000..c55e9a0aa8c375885db8241233124431b8f69061
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/FL_Hedra_API.py
@@ -0,0 +1,363 @@
+import argparse
+import json
+import logging # Keep for now, can be replaced by self._log
+import os
+import time
+import tempfile
+import traceback # Import traceback
+from typing import Dict, Optional, Union, Any
+
+import requests
+import torch
+import numpy as np
+from PIL import Image
+import cv2 # For video frame extraction
+
+# ComfyUI specific imports
+from comfy.utils import ProgressBar
+
+# Attempt to load dotenv for local dev, but API key primarily from input
+try:
+ from dotenv import load_dotenv
+ load_dotenv()
+except ImportError:
+ pass
+
+
+class FL_Hedra_API: # Renamed class
+ BASE_URL = "https://api.hedra.com/web-app/public"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "api_key": ("STRING", {"default": os.getenv("HEDRA_API_KEY", ""), "multiline": False}),
+ "image": ("IMAGE",),
+ "audio_file_path": ("STRING", {"default": "assets/audio.mp3", "multiline": False}),
+ "text_prompt": ("STRING", {"default": "character talking on a white background", "multiline": True}),
+ "aspect_ratio": (["1:1", "16:9", "9:16"], {"default": "1:1"}),
+ "resolution": (["720p", "540p"], {"default": "720p"}),
+ },
+ "optional": {
+ "duration_seconds": ("FLOAT", {"default": 0.0, "min": 0.0, "step": 0.1, "precision": 1}), # 0.0 means API default
+ "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffff}), # 0 means API default/random
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE", "STRING")
+ RETURN_NAMES = ("frames", "api_log")
+ FUNCTION = "execute_hedra_pipeline"
+ CATEGORY = "🏵️Fill Nodes/AI"
+ DESCRIPTION = "Generates a video using the Hedra API from an image, audio, and prompt, then outputs its frames."
+
+ def __init__(self):
+ self.log_messages = []
+
+ def _log(self, message: str, level: str = "INFO"):
+ timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
+ formatted_message = f"[FL_Hedra_API] {timestamp} [{level}]: {message}" # Updated log prefix
+ print(formatted_message)
+ self.log_messages.append(formatted_message)
+
+ class _HedraSession(requests.Session):
+ def __init__(self, api_key: str, base_url: str):
+ super().__init__()
+ self.base_url = base_url
+ self.headers["x-api-key"] = api_key
+
+ def prepare_request(self, request: requests.Request) -> requests.PreparedRequest:
+ if not request.url.startswith(("http://", "https://")):
+ request.url = f"{self.base_url.rstrip('/')}/{request.url.lstrip('/')}"
+ return super().prepare_request(request)
+
+ def _convert_tensor_to_temp_image(self, image_tensor: torch.Tensor) -> Optional[str]:
+ if image_tensor is None:
+ return None
+ try:
+ img_np = image_tensor[0].cpu().numpy() # Assuming batch size 1 or taking the first image
+ img_np = (img_np * 255).astype(np.uint8)
+ pil_image = Image.fromarray(img_np)
+
+ fd, temp_image_path = tempfile.mkstemp(suffix=".png", dir=tempfile.gettempdir())
+ os.close(fd) # Close the file descriptor as PIL will open/close it
+ pil_image.save(temp_image_path, format='PNG')
+ self._log(f"Saved input tensor to temporary image: {temp_image_path}")
+ return temp_image_path
+ except Exception as e:
+ self._log(f"Error converting tensor to temp image: {e}", level="ERROR")
+ return None
+
+ def _upload_asset(self, session: _HedraSession, file_path: str, asset_type: str, asset_name: Optional[str] = None) -> Optional[str]:
+ if not os.path.exists(file_path):
+ self._log(f"Asset file not found: {file_path}", level="ERROR")
+ return None
+
+ asset_name = asset_name or os.path.basename(file_path)
+ self._log(f"Uploading {asset_type}: {asset_name} from {file_path}")
+
+ try:
+ asset_response = session.post("/assets", json={"name": asset_name, "type": asset_type})
+ asset_response.raise_for_status()
+ asset_id = asset_response.json()["id"]
+
+ with open(file_path, "rb") as f:
+ upload_response = session.post(f"/assets/{asset_id}/upload", files={"file": f})
+ upload_response.raise_for_status()
+
+ self._log(f"Successfully uploaded {asset_type} with ID: {asset_id}")
+ return asset_id
+ except requests.exceptions.RequestException as e:
+ self._log(f"Error during {asset_type} asset upload: {e}. Response: {e.response.text if e.response else 'N/A'}", level="ERROR")
+ except Exception as e:
+ self._log(f"Unexpected error during {asset_type} asset upload: {e}", level="ERROR")
+ return None
+
+ def _get_available_models(self, session: _HedraSession) -> list:
+ self._log("Fetching available models...")
+ try:
+ response = session.get("/models")
+ response.raise_for_status()
+ models = response.json()
+ self._log(f"Found {len(models)} available models.")
+ return models
+ except requests.exceptions.RequestException as e:
+ self._log(f"Error fetching models: {e}", level="ERROR")
+ return []
+
+ def _generate_video_request(self, session: _HedraSession, model_id: str, image_id: str, audio_id: str,
+ text_prompt: str, resolution: str, aspect_ratio: str,
+ duration: Optional[float] = None, seed: Optional[int] = None) -> Optional[Dict[str, Any]]:
+ self._log("Submitting video generation request...")
+ payload = {
+ "type": "video",
+ "ai_model_id": model_id,
+ "start_keyframe_id": image_id,
+ "audio_id": audio_id,
+ "generated_video_inputs": {
+ "text_prompt": text_prompt,
+ "resolution": resolution,
+ "aspect_ratio": aspect_ratio,
+ },
+ }
+ if duration and duration > 0.0: # API expects duration_ms > 0
+ payload["generated_video_inputs"]["duration_ms"] = int(duration * 1000)
+ if seed and seed != 0: # API might treat 0 as random/unset
+ payload["generated_video_inputs"]["seed"] = seed
+
+ try:
+ response = session.post("/generations", json=payload)
+ response.raise_for_status()
+ result = response.json()
+ self._log(f"Generation request submitted with ID: {result['id']}")
+ return result
+ except requests.exceptions.RequestException as e:
+ self._log(f"Error submitting generation request: {e}. Response: {e.response.text if e.response else 'N/A'}", level="ERROR")
+ return None
+
+ def _poll_generation_status(self, session: _HedraSession, generation_id: str, pbar: ProgressBar) -> Optional[Dict[str, Any]]:
+ self._log(f"Polling generation status for ID: {generation_id}")
+ poll_interval = 5 # seconds
+ total_polls = 0 # For progress bar update
+ max_polls_for_pbar = 60 # Arbitrary limit for pbar updates (5 mins)
+
+ while True:
+ try:
+ status_response = session.get(f"/generations/{generation_id}/status")
+ status_response.raise_for_status()
+ status_data = status_response.json()
+ status = status_data.get("status", "unknown")
+ progress = status_data.get("progress") # Hedra might provide progress %
+
+ log_msg = f"Current status: {status}"
+ if progress is not None:
+ log_msg += f" (Progress: {progress}%)"
+ if isinstance(progress, (int, float)) and 0 <= progress <= 100:
+ # Use the total value the pbar was initialized with for scaling
+ # Assuming pbar here refers to the polling_pbar passed to this method
+ # which was initialized with polling_pbar_total
+ pbar_total_for_scaling = pbar.total # ProgressBar stores its total in pbar.total
+ pbar.update_absolute(int(progress * (pbar_total_for_scaling / 100.0)))
+ else:
+ # Fallback pbar update if no explicit progress
+ pbar.update_absolute(min(total_polls, max_polls_for_pbar))
+
+ self._log(log_msg)
+
+ if status in ["complete", "error"]:
+ if status == "complete": pbar.update_absolute(pbar.total) # Ensure 100% on complete
+ return status_data
+
+ time.sleep(poll_interval)
+ total_polls +=1
+ except requests.exceptions.RequestException as e:
+ self._log(f"Error polling status: {e}", level="ERROR")
+ return {"status": "error", "error_message": f"Polling failed: {e}"}
+ except Exception as e:
+ self._log(f"Unexpected error during polling: {e}", level="ERROR")
+ return {"status": "error", "error_message": f"Unexpected polling error: {e}"}
+
+
+ def _download_video_file(self, download_url: str, output_filename: str) -> Optional[str]:
+ self._log(f"Downloading video from {download_url} to {output_filename}")
+ try:
+ with requests.get(download_url, stream=True, timeout=300) as r: # 5 min timeout for download
+ r.raise_for_status()
+ with open(output_filename, 'wb') as f:
+ for chunk in r.iter_content(chunk_size=8192):
+ f.write(chunk)
+ self._log(f"Successfully downloaded video to {output_filename}")
+ return output_filename
+ except requests.exceptions.RequestException as e:
+ self._log(f"Failed to download video: {e}", level="ERROR")
+ except IOError as e:
+ self._log(f"Failed to save video file: {e}", level="ERROR")
+ return None
+
+ def _extract_frames_from_video(self, video_path: str) -> Optional[torch.Tensor]:
+ if not os.path.exists(video_path):
+ self._log(f"Video file not found for frame extraction: {video_path}", level="ERROR")
+ return None
+
+ self._log(f"Extracting frames from {video_path}")
+ try:
+ cap = cv2.VideoCapture(video_path)
+ frames = []
+ pbar_frames = ProgressBar(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)))
+ frame_count = 0
+ while cap.isOpened():
+ ret, frame = cap.read()
+ if not ret:
+ break
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
+ pil_image = Image.fromarray(frame_rgb)
+ img_array = np.array(pil_image).astype(np.float32) / 255.0
+ img_tensor = torch.from_numpy(img_array).unsqueeze(0) # Add batch dim
+ frames.append(img_tensor)
+ frame_count +=1
+ pbar_frames.update_absolute(frame_count)
+ cap.release()
+
+ if not frames:
+ self._log("No frames extracted from video.", level="WARNING")
+ return None
+
+ self._log(f"Extracted {len(frames)} frames.")
+ return torch.cat(frames, dim=0)
+ except Exception as e:
+ self._log(f"Error extracting frames: {e}", level="ERROR")
+ return None
+
+ def execute_hedra_pipeline(self, api_key: str, image: torch.Tensor, audio_file_path: str,
+ text_prompt: str, aspect_ratio: str, resolution: str,
+ duration_seconds: float = 0.0, seed: int = 0):
+ self.log_messages = [] # Reset logs for this run
+
+ if not api_key:
+ self._log("API key not provided.", level="ERROR")
+ return (None, "API key not provided.")
+
+ session = self._HedraSession(api_key=api_key, base_url=self.BASE_URL)
+
+ temp_image_path = None
+ temp_video_path = None
+ final_frames = None
+
+ # Progress bar for the whole operation (approximated steps)
+ # 1: upload image, 2: upload audio, 3: get models, 4: submit generation, 5: poll (scaled), 6: download, 7: extract frames
+ # Polling itself will have its own progress if API provides it, or timed progress.
+ # Let's use a simple step-based pbar for overall, and another for polling/extraction.
+ overall_pbar = ProgressBar(7)
+
+ try:
+ # 1. Upload Image
+ temp_image_path = self._convert_tensor_to_temp_image(image)
+ if not temp_image_path:
+ raise RuntimeError("Failed to convert input image tensor.")
+ image_id = self._upload_asset(session, temp_image_path, "image", "input_image.png")
+ if not image_id:
+ raise RuntimeError("Failed to upload image asset.")
+ overall_pbar.update_absolute(1)
+
+ # 2. Upload Audio
+ audio_id = self._upload_asset(session, audio_file_path, "audio")
+ if not audio_id:
+ raise RuntimeError(f"Failed to upload audio asset from {audio_file_path}.")
+ overall_pbar.update_absolute(2)
+
+ # 3. Get Model ID
+ models = self._get_available_models(session)
+ if not models:
+ raise RuntimeError("No models available from Hedra API.")
+ model_id = models[0]["id"] # Use the first available model as per script
+ self._log(f"Using model ID: {model_id}")
+ overall_pbar.update_absolute(3)
+
+ # 4. Generate Video Request
+ # For polling pbar, let's assume 100 steps for the polling phase itself
+ polling_pbar_total = 100
+ polling_pbar = ProgressBar(polling_pbar_total)
+
+ generation_request = self._generate_video_request(
+ session, model_id, image_id, audio_id, text_prompt,
+ resolution, aspect_ratio, duration_seconds if duration_seconds > 0 else None,
+ seed if seed != 0 else None
+ )
+ if not generation_request or "id" not in generation_request:
+ raise RuntimeError("Failed to submit video generation request.")
+ generation_id = generation_request["id"]
+ overall_pbar.update_absolute(4)
+
+ # 5. Poll Generation Status
+ self._log("Starting to poll generation status...")
+ final_status = self._poll_generation_status(session, generation_id, polling_pbar)
+ if not final_status or final_status.get("status") != "complete":
+ error_msg = final_status.get("error_message", "Video generation did not complete successfully or status unknown.")
+ raise RuntimeError(f"Generation failed or status incomplete: {error_msg}")
+
+ download_url = final_status.get("url")
+ if not download_url:
+ raise RuntimeError("Generation complete but no download URL provided.")
+ overall_pbar.update_absolute(5)
+
+ # 6. Download Video
+ temp_video_dir = tempfile.gettempdir()
+ temp_video_path = os.path.join(temp_video_dir, f"hedra_video_{generation_id}.mp4")
+ downloaded_path = self._download_video_file(download_url, temp_video_path)
+ if not downloaded_path:
+ raise RuntimeError("Failed to download generated video.")
+ overall_pbar.update_absolute(6)
+
+ # 7. Extract Frames
+ final_frames = self._extract_frames_from_video(downloaded_path)
+ if final_frames is None:
+ raise RuntimeError("Failed to extract frames from downloaded video.")
+ overall_pbar.update_absolute(7)
+
+ except Exception as e:
+ self._log(f"Pipeline error: {e}", level="CRITICAL")
+ traceback.print_exc() # For more detailed debug in console
+ # Create a single black error frame if pipeline fails
+ error_img_pil = Image.new('RGB', (256, 256), color='black') # Small error frame
+ draw = ImageDraw.Draw(error_img_pil)
+ try: font = ImageFont.load_default()
+ except: font = None
+ draw.text((10,10), f"Error: {str(e)[:100]}", fill="red", font=font)
+ error_img_np = np.array(error_img_pil).astype(np.float32) / 255.0
+ final_frames = torch.from_numpy(error_img_np).unsqueeze(0)
+ finally:
+ if temp_image_path and os.path.exists(temp_image_path):
+ try: os.remove(temp_image_path)
+ except Exception as e_rem: self._log(f"Could not remove temp image {temp_image_path}: {e_rem}", "WARNING")
+ if temp_video_path and os.path.exists(temp_video_path):
+ try: os.remove(temp_video_path)
+ except Exception as e_rem: self._log(f"Could not remove temp video {temp_video_path}: {e_rem}", "WARNING")
+
+ return (final_frames, "\n".join(self.log_messages))
+
+# Mappings for ComfyUI
+NODE_CLASS_MAPPINGS = {
+ "FL_Hedra_API": FL_Hedra_API # Renamed mapping key
+}
+NODE_DISPLAY_NAME_MAPPINGS = {
+ "FL_Hedra_API": "FL Hedra API" # Renamed display name
+}
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/ai/FL_PixVerseAPI.py b/comfyui_fill-nodes/nodes/ai/FL_PixVerseAPI.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e7f7d6a097770abdf4e8d4ec1448c9d8afeee69
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/FL_PixVerseAPI.py
@@ -0,0 +1,1218 @@
+# FL_PixVerseAPI: Enhanced PixVerse Image-to-Video API Node with frame decomposition
+import os
+import uuid
+import json
+import time
+import io
+import requests
+import http.client
+import torch
+import numpy as np
+import tempfile
+import cv2
+import concurrent.futures
+from typing import Tuple, List, Dict
+from pathlib import Path
+from PIL import Image
+from tqdm import tqdm
+
+
+class FL_PixVerseAPI:
+ """
+ A ComfyUI node for the PixVerse Image-to-Video API.
+ Takes an image and converts it to a video using PixVerse's API.
+ Downloads the video, extracts frames, and returns them as image tensors.
+ """
+
+ RETURN_TYPES = ("IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "STRING", "STRING", "STRING")
+ RETURN_NAMES = ("frames_1", "frames_2", "frames_3", "frames_4", "frames_5", "video_urls", "status_msg", "credit_balance")
+ FUNCTION = "generate_video"
+ CATEGORY = "🏵️Fill Nodes/AI"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "api_key": ("STRING", {"multiline": False}),
+ "prompt": ("STRING", {"default": ""}),
+ "negative_prompt": ("STRING", {"default": ""}),
+ "duration": ("INT", {"default": 5, "min": 5, "max": 8}),
+ "quality": (["360p", "540p", "720p", "1080p"], {"default": "540p"}),
+ "motion_mode": (["normal", "fast"], {"default": "normal"}),
+ "seed": ("INT", {"default": 0, "min": 0, "max": 2147483647,
+ "description": "Random seed for video generation (0 = random)"}),
+ "batch_size": ("INT", {"default": 1, "min": 1, "max": 5,
+ "description": "Number of videos to generate with different seeds"}),
+ "nth_frame": ("INT", {"default": 1, "min": 1, "max": 4,
+ "description": "Extract every Nth frame (1=all frames, 2=every 2nd frame, etc.)"}),
+ "use_transition": ("BOOLEAN", {"default": False,
+ "description": "Use transition API instead of standard image-to-video"})
+ },
+ "optional": {
+ "image": ("IMAGE", {"description": "Main image for standard mode (required if not using transition)"}),
+ "first_frame_img": ("IMAGE", {"description": "Start frame image for transition (requires use_transition=True)"}),
+ "last_frame_img": ("IMAGE", {"description": "End frame image for transition (requires use_transition=True)"})
+ }
+ }
+
+ def generate_video(self, api_key, prompt="", negative_prompt="", duration=5,
+ quality="540p", motion_mode="normal", seed=0, batch_size=1, nth_frame=1,
+ use_transition=False, image=None, first_frame_img=None, last_frame_img=None):
+ """
+ Generate a video from an image, download it, and extract frames
+
+ Args:
+ api_key: PixVerse API key
+ prompt: Text prompt describing the video
+ negative_prompt: Negative prompt
+ duration: Video duration in seconds
+ quality: Video quality
+ motion_mode: Motion speed
+ seed: Random seed for video generation (0 = random)
+ batch_size: Number of videos to generate with different seeds
+ nth_frame: Extract every Nth frame (1=all frames, 2=every 2nd frame, etc.)
+ use_transition: Whether to use transition API instead of standard image-to-video
+ image: (Optional) Main input image tensor
+ first_frame_img: (Optional) Start frame image for transition
+ last_frame_img: (Optional) End frame image for transition
+
+ Returns:
+ Tuple of (frames_tensor_1, frames_tensor_2, frames_tensor_3, frames_tensor_4, frames_tensor_5,
+ video_urls, status_message, credit_balance)
+ Note: If batch_size < 5, the unused frame tensors will be empty (1,1,1,3) tensors
+ """
+ try:
+ # Helper function for error returns
+ def error_return(error_msg):
+ empty_tensor = torch.zeros((1, 1, 1, 3))
+ return empty_tensor, empty_tensor, empty_tensor, empty_tensor, empty_tensor, "", error_msg, "N/A"
+
+ # 1. Validate API key
+ if not api_key or api_key.strip() == "":
+ return error_return("Error: API Key is required")
+
+ # 2. Validate image inputs based on mode
+ if use_transition:
+ # Transition mode validation
+ if first_frame_img is None and last_frame_img is None:
+ return error_return("Error: When using transition mode, at least one of first_frame_img or last_frame_img must be provided")
+
+ # For transition mode, we need either:
+ # 1. Main image (which can be used for missing frames), or
+ # 2. Both first_frame_img and last_frame_img
+ if image is None and (first_frame_img is None or last_frame_img is None):
+ return error_return("Error: For transition mode without main image, both first_frame_img AND last_frame_img must be provided")
+ else:
+ # Standard mode validation
+ if image is None:
+ return error_return("Error: Main image is required when not using transition mode")
+
+ # Initialize return values
+ frame_tensors = [torch.zeros((1, 1, 1, 3)) for _ in range(5)] # 5 empty tensors by default
+ video_urls = []
+ status_messages = []
+
+ # Limit batch size to maximum of 5
+ batch_size = min(batch_size, 5)
+
+ # Generate trace ID for the main request
+ main_trace_id = str(uuid.uuid4())
+
+ # 3. Upload the main image if provided
+ img_id = 0
+ if image is not None:
+ print(f"[PixVerse] Processing and uploading main image...")
+ img_id = self.upload_image(api_key, image, main_trace_id, "main image")
+
+ if img_id == 0:
+ return error_return("Error: Failed to upload main image")
+
+ # 4. Process batches in parallel
+ # Define helper functions for parallel processing
+ def generate_video_request(batch_idx, batch_seed, img_id):
+ """Make the initial API call to generate a video"""
+ trace_id = str(uuid.uuid4())
+ print(f"[PixVerse] Batch {batch_idx+1}/{batch_size}: Generating video with seed {batch_seed}...")
+
+ conn = http.client.HTTPSConnection("app-api.pixverse.ai")
+
+ # Determine which API endpoint to use based on use_transition flag
+ if use_transition:
+ # Process first and last frame images
+ first_frame_id = 0
+ last_frame_id = 0
+
+ # For transition mode, if main image is provided but first/last frame is not,
+ # use the main image for the missing frame(s)
+
+ # Handle first frame
+ if first_frame_img is not None:
+ first_frame_id = self.upload_image(api_key, first_frame_img, trace_id, "first frame")
+ if first_frame_id == 0: # Upload failed
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": "Failed to upload first frame image",
+ "trace_id": trace_id
+ }
+ elif img_id > 0: # Use main image if first frame not provided
+ first_frame_id = img_id
+ print(f"[PixVerse] Using main image as first frame")
+
+ # Handle last frame
+ if last_frame_img is not None:
+ last_frame_id = self.upload_image(api_key, last_frame_img, trace_id, "last frame")
+ if last_frame_id == 0: # Upload failed
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": "Failed to upload last frame image",
+ "trace_id": trace_id
+ }
+ elif img_id > 0: # Use main image if last frame not provided
+ last_frame_id = img_id
+ print(f"[PixVerse] Using main image as last frame")
+
+ # Use transition API
+ endpoint = "/openapi/v2/video/transition/generate"
+ payload = json.dumps({
+ "prompt": prompt,
+ "model": "v3.5",
+ "duration": duration,
+ "quality": quality,
+ "motion_mode": motion_mode,
+ "seed": batch_seed,
+ "first_frame_img": first_frame_id,
+ "last_frame_img": last_frame_id,
+ "negative_prompt": negative_prompt,
+ "water_mark": False
+ })
+ else:
+ # Use standard image-to-video API
+ # This should never happen due to our validation, but just in case
+ if img_id == 0:
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": "No valid image provided for standard mode",
+ "trace_id": trace_id
+ }
+
+ endpoint = "/openapi/v2/video/img/generate"
+ payload = json.dumps({
+ "duration": duration,
+ "img_id": img_id,
+ "model": "v3.5",
+ "motion_mode": motion_mode,
+ "negative_prompt": negative_prompt,
+ "prompt": prompt,
+ "quality": quality,
+ "seed": batch_seed,
+ "template_id": 0,
+ "water_mark": False
+ })
+
+ headers = {
+ 'API-KEY': api_key,
+ 'Ai-trace-id': trace_id,
+ 'Content-Type': 'application/json'
+ }
+
+ try:
+ conn.request("POST", endpoint, payload, headers)
+ response = conn.getresponse()
+ data = response.read().decode("utf-8")
+ result = json.loads(data)
+
+ if result.get("ErrCode", -1) != 0:
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": f"API Error: {result.get('ErrMsg', 'Unknown error')}",
+ "trace_id": trace_id
+ }
+
+ video_id = result["Resp"]["video_id"]
+ print(f"[PixVerse] Batch {batch_idx+1}: Video generation initiated with ID: {video_id}")
+
+ return {
+ "batch_idx": batch_idx,
+ "success": True,
+ "video_id": video_id,
+ "trace_id": trace_id
+ }
+ except Exception as e:
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": f"Request Error: {str(e)}",
+ "trace_id": trace_id
+ }
+
+ def poll_video_completion(batch_idx, video_id, trace_id):
+ """Poll for video completion"""
+ print(f"[PixVerse] Batch {batch_idx+1}: Polling for video completion...")
+ max_polls = 60 # 5 minutes with 5-second intervals
+ poll_count = 0
+
+ while poll_count < max_polls:
+ time.sleep(5)
+ poll_count += 1
+
+ poll_conn = http.client.HTTPSConnection("app-api.pixverse.ai")
+ poll_conn.request("GET", f"/openapi/v2/video/result/{video_id}", headers={
+ 'API-KEY': api_key,
+ 'Ai-trace-id': trace_id
+ })
+
+ try:
+ poll_response = poll_conn.getresponse()
+ poll_data = poll_response.read().decode("utf-8")
+ poll_result = json.loads(poll_data)
+
+ if poll_result.get("ErrCode", -1) != 0:
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": f"Polling Error: {poll_result.get('ErrMsg', 'Unknown error')}"
+ }
+
+ status = poll_result["Resp"]["status"]
+
+ if status == 1: # Success
+ video_url = poll_result["Resp"]["url"]
+ print(f"[PixVerse] Batch {batch_idx+1}: Video ready! URL: {video_url}")
+ return {
+ "batch_idx": batch_idx,
+ "success": True,
+ "video_url": video_url
+ }
+
+ elif status in [2, 3, 4]: # Failed, timeout, rejected
+ status_messages = {
+ 2: "Failed",
+ 3: "Timeout",
+ 4: "Rejected"
+ }
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": f"Video generation {status_messages.get(status)}"
+ }
+
+ print(f"[PixVerse] Batch {batch_idx+1}: Video still processing... (poll {poll_count}/{max_polls})")
+
+ except Exception as e:
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": f"Polling Error: {str(e)}"
+ }
+
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": "Polling timed out - video may still be processing"
+ }
+
+ def process_video(batch_idx, video_url):
+ """Download and process the video"""
+ try:
+ print(f"[PixVerse] Batch {batch_idx+1}: Downloading video...")
+
+ # Create a temporary file
+ with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_video:
+ temp_video_path = temp_video.name
+
+ # Download video to temp file
+ response = requests.get(video_url, stream=True)
+ response.raise_for_status()
+
+ # Get file size for progress bar
+ file_size = int(response.headers.get('content-length', 0))
+ progress_bar = tqdm(total=file_size, unit='B', unit_scale=True, desc=f"Downloading Batch {batch_idx+1}")
+
+ for chunk in response.iter_content(chunk_size=8192):
+ temp_video.write(chunk)
+ progress_bar.update(len(chunk))
+
+ progress_bar.close()
+
+ # Extract frames using OpenCV
+ print(f"[PixVerse] Batch {batch_idx+1}: Extracting frames from video...")
+ cap = cv2.VideoCapture(temp_video_path)
+
+ if not cap.isOpened():
+ os.unlink(temp_video_path) # Clean up temp file
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": "Could not open video file"
+ }
+
+ # Get video properties
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
+ fps = cap.get(cv2.CAP_PROP_FPS)
+
+ print(f"[PixVerse] Batch {batch_idx+1}: Video has {total_frames} frames at {fps} FPS")
+
+ frames = []
+ frame_count = 0
+
+ # Use nth_frame directly as the stride
+ stride = nth_frame
+
+ # Calculate approximately how many frames we'll extract
+ frames_to_extract = total_frames // stride + (1 if total_frames % stride > 0 else 0)
+
+ progress_bar = tqdm(total=frames_to_extract, desc=f"Extracting frames (Batch {batch_idx+1})")
+
+ while cap.isOpened():
+ ret, frame = cap.read()
+ if not ret:
+ break
+
+ if frame_count % stride == 0 and len(frames) < frames_to_extract:
+ # Convert BGR to RGB (OpenCV uses BGR by default)
+ rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
+
+ # Normalize to 0-1 range for ComfyUI
+ normalized_frame = rgb_frame.astype(np.float32) / 255.0
+
+ frames.append(normalized_frame)
+ progress_bar.update(1)
+
+ # Break if we've extracted enough frames
+ if len(frames) >= frames_to_extract:
+ break
+
+ frame_count += 1
+
+ progress_bar.close()
+ cap.release()
+
+ # Clean up temp file
+ os.unlink(temp_video_path)
+
+ # Convert frames to tensor
+ if frames:
+ frames_tensor = torch.from_numpy(np.stack(frames))
+ print(f"[PixVerse] Batch {batch_idx+1}: Extracted {len(frames)} frames as tensor with shape {frames_tensor.shape}")
+ return {
+ "batch_idx": batch_idx,
+ "success": True,
+ "frames_tensor": frames_tensor
+ }
+ else:
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": "No frames could be extracted"
+ }
+
+ except Exception as e:
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": f"Processing Error: {str(e)}"
+ }
+
+ # Prepare batch parameters
+ batch_params = []
+ for batch_idx in range(batch_size):
+ # Calculate seed for this batch
+ batch_seed = np.random.randint(1, 2147483647) if seed == 0 else seed + batch_idx
+ batch_params.append((batch_idx, batch_seed))
+
+ # Step 1: Make all API calls in parallel
+ print(f"[PixVerse] Making {batch_size} API calls in parallel...")
+ api_results = []
+ with concurrent.futures.ThreadPoolExecutor(max_workers=batch_size) as executor:
+ future_to_batch = {
+ executor.submit(generate_video_request, idx, seed_val, img_id): (idx, seed_val)
+ for idx, seed_val in batch_params
+ }
+
+ for future in concurrent.futures.as_completed(future_to_batch):
+ batch_idx, batch_seed = future_to_batch[future]
+ try:
+ result = future.result()
+ api_results.append(result)
+ except Exception as e:
+ api_results.append({
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": f"Thread Error: {str(e)}"
+ })
+
+ # Step 2: Poll for completion in parallel
+ print(f"[PixVerse] Polling for {len(api_results)} videos in parallel...")
+ poll_results = []
+ with concurrent.futures.ThreadPoolExecutor(max_workers=batch_size) as executor:
+ future_to_batch = {}
+
+ for result in api_results:
+ if result["success"]:
+ future = executor.submit(
+ poll_video_completion,
+ result["batch_idx"],
+ result["video_id"],
+ result["trace_id"]
+ )
+ future_to_batch[future] = result["batch_idx"]
+ else:
+ # If API call failed, add the error to poll results
+ poll_results.append({
+ "batch_idx": result["batch_idx"],
+ "success": False,
+ "error": result["error"]
+ })
+
+ for future in concurrent.futures.as_completed(future_to_batch):
+ batch_idx = future_to_batch[future]
+ try:
+ result = future.result()
+ poll_results.append(result)
+ except Exception as e:
+ poll_results.append({
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": f"Thread Error: {str(e)}"
+ })
+
+ # Step 3: Process videos in parallel
+ print(f"[PixVerse] Processing {len(poll_results)} videos in parallel...")
+ process_results = []
+ with concurrent.futures.ThreadPoolExecutor(max_workers=batch_size) as executor:
+ future_to_batch = {}
+
+ for result in poll_results:
+ if result["success"]:
+ future = executor.submit(
+ process_video,
+ result["batch_idx"],
+ result["video_url"]
+ )
+ future_to_batch[future] = result["batch_idx"]
+ else:
+ # If polling failed, add the error to process results
+ process_results.append({
+ "batch_idx": result["batch_idx"],
+ "success": False,
+ "error": result["error"]
+ })
+
+ for future in concurrent.futures.as_completed(future_to_batch):
+ batch_idx = future_to_batch[future]
+ try:
+ result = future.result()
+ process_results.append(result)
+ except Exception as e:
+ process_results.append({
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": f"Thread Error: {str(e)}"
+ })
+
+ # Step 4: Collect results
+ for result in process_results:
+ batch_idx = result["batch_idx"]
+ if result["success"]:
+ frame_tensors[batch_idx] = result["frames_tensor"]
+ video_urls.append(f"Batch {batch_idx+1}: Success")
+ status_messages.append(f"Success (Batch {batch_idx+1})")
+ else:
+ video_urls.append(f"Batch {batch_idx+1}: Failed")
+ status_messages.append(f"Error (Batch {batch_idx+1}): {result['error']}")
+
+ # 9. Get account balance
+ credit_balance = self.get_account_balance(api_key, main_trace_id)
+
+ # Combine status messages
+ combined_status = " | ".join(status_messages) if status_messages else "No videos processed"
+
+ # Combine video URLs
+ combined_urls = " | ".join(video_urls) if video_urls else "No videos generated"
+
+ # Return the results
+ return tuple(frame_tensors + [combined_urls, combined_status, credit_balance])
+
+ except Exception as e:
+ print(f"[PixVerse] Error: {str(e)}")
+ # Try to return proper empty tensors
+ empty_tensor = torch.zeros((1, 1, 1, 3))
+ return empty_tensor, empty_tensor, empty_tensor, empty_tensor, empty_tensor, "", f"Error: {str(e)}", "N/A"
+
+ def upload_image(self, api_key, image_tensor, trace_id, image_type="image"):
+ """
+ Upload an image to PixVerse and return the image ID
+
+ Args:
+ api_key: PixVerse API key
+ image_tensor: Image tensor to upload (can be None)
+ trace_id: Trace ID for the request
+ image_type: Type of image being uploaded (for logging)
+
+ Returns:
+ Image ID if successful, 0 if failed
+ """
+ try:
+ # Check if image_tensor is None
+ if image_tensor is None:
+ print(f"[PixVerse] Error: {image_type} is None")
+ return 0
+
+ # Take first image if batch
+ if len(image_tensor.shape) == 4:
+ image_tensor = image_tensor[0]
+
+ # Convert to uint8
+ if image_tensor.dtype != torch.uint8:
+ image_tensor = (image_tensor * 255).to(torch.uint8)
+
+ # Convert to numpy for PIL
+ np_img = image_tensor.cpu().numpy()
+
+ try:
+ pil_image = Image.fromarray(np_img)
+ print(f"[PixVerse] Successfully converted {image_type} tensor to PIL image")
+ except Exception as e:
+ print(f"[PixVerse] Error: Failed to convert {image_type} tensor to PIL image: {str(e)}")
+ return 0
+
+ # Convert PIL image to bytes
+ img_byte_arr = io.BytesIO()
+ pil_image.save(img_byte_arr, format='JPEG', quality=80) # Changed to JPEG with quality 80
+ img_byte_arr.seek(0) # Reset pointer to beginning of buffer
+
+ upload_url = "https://app-api.pixverse.ai/openapi/v2/image/upload"
+ upload_headers = {
+ 'API-KEY': api_key,
+ 'Ai-trace-id': trace_id
+ }
+
+ # Send bytes directly without saving to disk
+ files = {'image': (f'{image_type}.jpg', img_byte_arr, 'image/jpeg')} # Changed to jpg and image/jpeg
+ upload_response = requests.post(upload_url, headers=upload_headers, files=files)
+
+ if upload_response.status_code != 200:
+ print(f"[PixVerse] Error: Failed to upload {image_type}. HTTP Status: {upload_response.status_code}")
+ return 0
+
+ upload_result = upload_response.json()
+ if upload_result.get("ErrCode", -1) != 0:
+ print(f"[PixVerse] Error uploading {image_type}: {upload_result.get('ErrMsg', 'Unknown error')}")
+ return 0
+
+ img_id = upload_result["Resp"]["img_id"]
+ print(f"[PixVerse] {image_type.capitalize()} uploaded successfully. Image ID: {img_id}")
+ return img_id
+
+ except Exception as e:
+ print(f"[PixVerse] Error uploading {image_type}: {str(e)}")
+ return 0
+
+ def _process_with_fal_api(self, api_key, prompt, negative_prompt, duration, quality,
+ seed, batch_size, nth_frame, image):
+ """
+ Process video generation using the Fal AI API
+
+ Args:
+ api_key: Fal AI API key
+ prompt: Text prompt describing the video
+ negative_prompt: Negative prompt
+ duration: Video duration in seconds
+ quality: Video quality
+ seed: Random seed for video generation
+ batch_size: Number of videos to generate
+ nth_frame: Extract every Nth frame
+ image: Main input image tensor
+
+ Returns:
+ Same return format as generate_video
+ """
+ try:
+ # Helper function for error returns
+ def error_return(error_msg):
+ empty_tensor = torch.zeros((1, 1, 1, 3))
+ return empty_tensor, empty_tensor, empty_tensor, empty_tensor, empty_tensor, "", error_msg, "N/A"
+
+ # Initialize return values
+ frame_tensors = [torch.zeros((1, 1, 1, 3)) for _ in range(5)] # 5 empty tensors by default
+ video_urls = []
+ status_messages = []
+
+ # Limit batch size to maximum of 5
+ batch_size = min(batch_size, 5)
+
+ # Convert quality to aspect ratio and resolution for Fal AI
+ aspect_ratio = "16:9" # Default
+ if quality == "1080p":
+ resolution = "1080p"
+ elif quality == "720p":
+ resolution = "720p"
+ elif quality == "540p":
+ resolution = "540p"
+ else: # 360p
+ resolution = "360p"
+
+ # Convert image tensor to base64
+ if image is not None:
+ # Take first image if batch
+ if len(image.shape) == 4:
+ image_tensor = image[0]
+ else:
+ image_tensor = image
+
+ # Convert to uint8
+ if image_tensor.dtype != torch.uint8:
+ image_tensor = (image_tensor * 255).to(torch.uint8)
+
+ # Convert to numpy for PIL
+ np_img = image_tensor.cpu().numpy()
+
+ try:
+ pil_image = Image.fromarray(np_img)
+ print(f"[PixVerseAPI] Successfully converted image tensor to PIL image")
+
+ # Convert PIL image to base64
+ buffered = io.BytesIO()
+ pil_image.save(buffered, format="PNG")
+ img_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
+ img_data_uri = f"data:image/png;base64,{img_base64}"
+
+ except Exception as e:
+ print(f"[PixVerseAPI] Error: Failed to convert image tensor to base64: {str(e)}")
+ return error_return(f"Error: Failed to convert image: {str(e)}")
+ else:
+ return error_return("Error: No image provided")
+
+ # Process batches in parallel
+ def process_batch(batch_idx):
+ try:
+ # Calculate seed for this batch
+ batch_seed = np.random.randint(1, 2147483647) if seed == 0 else seed + batch_idx
+
+ print(f"[PixVerseAPI] Batch {batch_idx+1}/{batch_size}: Generating video with seed {batch_seed}...")
+
+ # Prepare the API request
+ # Try different authentication methods
+ auth_methods = [
+ {"headers": {"Authorization": f"Key {api_key}", "Content-Type": "application/json"}},
+ {"headers": {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}},
+ {"headers": {"Content-Type": "application/json"}, "params": {"credentials": api_key}}
+ ]
+
+ print(f"[PixVerseAPI] Will try {len(auth_methods)} different authentication methods")
+
+ # Prepare the payload
+ payload = {
+ "input": {
+ "prompt": prompt,
+ "image_url": img_data_uri,
+ "aspect_ratio": aspect_ratio,
+ "resolution": resolution,
+ "duration": duration,
+ "seed": batch_seed
+ }
+ }
+
+ if negative_prompt:
+ payload["input"]["negative_prompt"] = negative_prompt
+
+ # Make the API call
+ # Try different Fal AI API endpoints
+ api_urls = [
+ "https://api.fal.ai/v1/models/fal-ai/pixverse/v4/image-to-video",
+ "https://api.fal.ai/v1/fal-ai/pixverse/v4/image-to-video",
+ "https://api.fal.ai/v1/models/pixverse/v4/image-to-video"
+ ]
+
+ # Add direct IP address endpoints as fallbacks for DNS resolution issues
+ # These are potential IP addresses for api.fal.ai - they may change over time
+ ip_addresses = [
+ "3.33.152.147",
+ "52.32.80.167",
+ "54.148.218.115",
+ "44.233.151.27"
+ ]
+
+ for ip in ip_addresses:
+ api_urls.extend([
+ f"https://{ip}/v1/models/fal-ai/pixverse/v4/image-to-video",
+ f"https://{ip}/v1/fal-ai/pixverse/v4/image-to-video",
+ f"https://{ip}/v1/models/pixverse/v4/image-to-video"
+ ])
+
+ print(f"[PixVerseAPI] Will try {len(api_urls)} different API endpoints")
+
+ # Add retry logic
+ max_retries = 3
+ retry_delay = 2 # seconds
+ last_error = None
+
+ for retry in range(max_retries):
+ for url_idx, api_url in enumerate(api_urls):
+ try:
+ print(f"[PixVerseAPI] Attempt {retry+1}/{max_retries}, URL {url_idx+1}/{len(api_urls)}: {api_url}")
+
+ # Check internet connectivity
+ try:
+ # Try to connect to a reliable host to check internet connectivity
+ test_conn = requests.get("https://www.google.com", timeout=5)
+ print(f"[PixVerseAPI] Internet connectivity check: {test_conn.status_code}")
+ except Exception as e:
+ print(f"[PixVerseAPI] Internet connectivity check failed: {str(e)}")
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": f"Internet connectivity issue: {str(e)}"
+ }
+
+ # For IP-based URLs, we need to set the Host header
+ custom_headers = {}
+ if api_url.split("//")[1].split("/")[0].replace(".", "").isdigit():
+ # This is an IP address URL
+ print(f"[PixVerseAPI] Using IP address directly: {api_url}")
+ custom_headers["Host"] = "api.fal.ai"
+
+ # Try each authentication method
+ for auth_idx, auth in enumerate(auth_methods):
+ try:
+ print(f"[PixVerseAPI] Trying auth method {auth_idx+1}/{len(auth_methods)}")
+
+ # Prepare request parameters
+ request_kwargs = {"json": payload, "timeout": 120}
+ request_kwargs.update(auth)
+
+ # Add custom headers if needed
+ if custom_headers and "headers" in request_kwargs:
+ request_kwargs["headers"].update(custom_headers)
+
+ # Make the request with a shorter timeout for faster failure
+ request_kwargs["timeout"] = 10 # Shorter timeout for faster failure detection
+ response = requests.post(api_url, **request_kwargs)
+
+ # If we get a 401/403, try the next auth method
+ if response.status_code in [401, 403]:
+ print(f"[PixVerseAPI] Auth failed with status {response.status_code}, trying next method")
+ continue
+
+ # For any other status, break out of the auth loop
+ break
+ except Exception as e:
+ print(f"[PixVerseAPI] Auth method {auth_idx+1} failed: {str(e)}")
+ continue
+
+ # If we get here, the request was successful
+ break
+ except requests.exceptions.RequestException as e:
+ last_error = e
+ print(f"[PixVerseAPI] API request failed for URL {api_url}: {str(e)}")
+ continue
+
+ # If we got a response, break out of the retry loop
+ if 'response' in locals():
+ break
+
+ # Wait before retrying
+ if retry < max_retries - 1:
+ retry_delay_time = retry_delay * (2 ** retry) # Exponential backoff
+ print(f"[PixVerseAPI] Retrying in {retry_delay_time} seconds...")
+ time.sleep(retry_delay_time)
+
+ # If we still don't have a response after all retries, return an error
+ if 'response' not in locals():
+ error_msg = f"API connection failed after {max_retries} retries: {str(last_error)}"
+ print(f"[PixVerseAPI] {error_msg}")
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": error_msg
+ }
+
+ if response.status_code != 200:
+ error_msg = f"API Error: HTTP {response.status_code} - {response.text}"
+ print(f"[PixVerseAPI] {error_msg}")
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": error_msg
+ }
+
+ result = response.json()
+
+ # Extract video URL
+ if "video" in result and "url" in result["video"]:
+ video_url = result["video"]["url"]
+ print(f"[PixVerseAPI] Batch {batch_idx+1}: Video ready! URL: {video_url}")
+
+ # Download and process the video
+ try:
+ print(f"[PixVerseAPI] Batch {batch_idx+1}: Downloading video...")
+
+ # Create a temporary file
+ with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_video:
+ temp_video_path = temp_video.name
+
+ # Download video to temp file
+ dl_response = requests.get(video_url, stream=True)
+ dl_response.raise_for_status()
+
+ # Get file size for progress bar
+ file_size = int(dl_response.headers.get('content-length', 0))
+ progress_bar = tqdm(total=file_size, unit='B', unit_scale=True, desc=f"Downloading Batch {batch_idx+1}")
+
+ for chunk in dl_response.iter_content(chunk_size=8192):
+ temp_video.write(chunk)
+ progress_bar.update(len(chunk))
+
+ progress_bar.close()
+
+ # Extract frames using OpenCV
+ print(f"[PixVerseAPI] Batch {batch_idx+1}: Extracting frames from video...")
+ cap = cv2.VideoCapture(temp_video_path)
+
+ if not cap.isOpened():
+ os.unlink(temp_video_path) # Clean up temp file
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": "Could not open video file"
+ }
+
+ # Get video properties
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
+ fps = cap.get(cv2.CAP_PROP_FPS)
+
+ print(f"[PixVerseAPI] Batch {batch_idx+1}: Video has {total_frames} frames at {fps} FPS")
+
+ frames = []
+ frame_count = 0
+
+ # Use nth_frame directly as the stride
+ stride = nth_frame
+
+ # Calculate approximately how many frames we'll extract
+ frames_to_extract = total_frames // stride + (1 if total_frames % stride > 0 else 0)
+
+ progress_bar = tqdm(total=frames_to_extract, desc=f"Extracting frames (Batch {batch_idx+1})")
+
+ while cap.isOpened():
+ ret, frame = cap.read()
+ if not ret:
+ break
+
+ if frame_count % stride == 0 and len(frames) < frames_to_extract:
+ # Convert BGR to RGB (OpenCV uses BGR by default)
+ rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
+
+ # Normalize to 0-1 range for ComfyUI
+ normalized_frame = rgb_frame.astype(np.float32) / 255.0
+
+ frames.append(normalized_frame)
+ progress_bar.update(1)
+
+ # Break if we've extracted enough frames
+ if len(frames) >= frames_to_extract:
+ break
+
+ frame_count += 1
+
+ progress_bar.close()
+ cap.release()
+
+ # Clean up temp file
+ os.unlink(temp_video_path)
+
+ # Convert frames to tensor
+ if frames:
+ frames_tensor = torch.from_numpy(np.stack(frames))
+ print(f"[PixVerseAPI] Batch {batch_idx+1}: Extracted {len(frames)} frames as tensor with shape {frames_tensor.shape}")
+ return {
+ "batch_idx": batch_idx,
+ "success": True,
+ "frames_tensor": frames_tensor,
+ "video_url": video_url
+ }
+ else:
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": "No frames could be extracted"
+ }
+
+ except Exception as e:
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": f"Processing Error: {str(e)}"
+ }
+ else:
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": "No video URL in API response"
+ }
+
+ except Exception as e:
+ return {
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": f"Batch processing error: {str(e)}"
+ }
+
+ # Process batches in parallel
+ results = []
+ with concurrent.futures.ThreadPoolExecutor(max_workers=batch_size) as executor:
+ future_to_batch = {
+ executor.submit(process_batch, idx): idx
+ for idx in range(batch_size)
+ }
+
+ for future in concurrent.futures.as_completed(future_to_batch):
+ batch_idx = future_to_batch[future]
+ try:
+ result = future.result()
+ results.append(result)
+ except Exception as e:
+ results.append({
+ "batch_idx": batch_idx,
+ "success": False,
+ "error": f"Thread Error: {str(e)}"
+ })
+
+ # Collect results
+ for result in results:
+ batch_idx = result["batch_idx"]
+ if result["success"]:
+ frame_tensors[batch_idx] = result["frames_tensor"]
+ video_urls.append(f"Batch {batch_idx+1}: {result['video_url']}")
+ status_messages.append(f"Success (Batch {batch_idx+1})")
+ else:
+ video_urls.append(f"Batch {batch_idx+1}: Failed")
+ status_messages.append(f"Error (Batch {batch_idx+1}): {result['error']}")
+
+ # Combine status messages
+ combined_status = " | ".join(status_messages) if status_messages else "No videos processed"
+
+ # Combine video URLs
+ combined_urls = " | ".join(video_urls) if video_urls else "No videos generated"
+
+ # Return the results
+ return tuple(frame_tensors + [combined_urls, combined_status, "Fal AI (credits N/A)"])
+
+ except Exception as e:
+ print(f"[PixVerseAPI] Error in Fal AI processing: {str(e)}")
+ # Try to return proper empty tensors
+ empty_tensor = torch.zeros((1, 1, 1, 3))
+ return empty_tensor, empty_tensor, empty_tensor, empty_tensor, empty_tensor, "", f"Fal AI Error: {str(e)}", "N/A"
+
+ def _process_with_fal_simplified(self, api_key, prompt, negative_prompt, duration, quality,
+ seed, batch_size, nth_frame, image):
+ """
+ Simplified approach for Fal AI that doesn't rely on direct API calls
+
+ This method provides a fallback when direct API access to Fal AI fails.
+ It creates a simple animation effect from the input image and returns it
+ in the same format as the regular API would.
+
+ Args:
+ Same as _process_with_fal_api
+
+ Returns:
+ Same return format as generate_video
+ """
+ try:
+ print("[PixVerseAPI] Using simplified approach for Fal AI due to API connection issues")
+
+ # Helper function for error returns
+ def error_return(error_msg):
+ empty_tensor = torch.zeros((1, 1, 1, 3))
+ return empty_tensor, empty_tensor, empty_tensor, empty_tensor, empty_tensor, "", error_msg, "N/A"
+
+ # Initialize return values
+ frame_tensors = [torch.zeros((1, 1, 1, 3)) for _ in range(5)] # 5 empty tensors by default
+ video_urls = []
+ status_messages = []
+
+ # Limit batch size to maximum of 5
+ batch_size = min(batch_size, 5)
+
+ # Process the input image
+ if image is None:
+ return error_return("Error: No image provided")
+
+ # Take first image if batch
+ if len(image.shape) == 4 and image.shape[0] > 0:
+ image_tensor = image[0]
+ else:
+ image_tensor = image
+
+ # Create a simple animation effect from the input image
+ # This is a placeholder for the actual Fal AI video generation
+ for batch_idx in range(batch_size):
+ try:
+ # Calculate seed for this batch
+ batch_seed = np.random.randint(1, 2147483647) if seed == 0 else seed + batch_idx
+ np.random.seed(batch_seed)
+
+ print(f"[PixVerseAPI] Batch {batch_idx+1}/{batch_size}: Creating animation with seed {batch_seed}...")
+
+ # Create a sequence of frames with simple effects
+ frames = []
+ num_frames = 24 # Create 24 frames (about 1 second at 24fps)
+
+ # Convert tensor to numpy for manipulation
+ if image_tensor.dtype != torch.uint8:
+ img_np = (image_tensor.cpu().numpy() * 255).astype(np.uint8)
+ else:
+ img_np = image_tensor.cpu().numpy()
+
+ # Create a PIL image for easier manipulation
+ try:
+ pil_image = Image.fromarray(img_np)
+ print(f"[PixVerseAPI] Successfully converted image tensor to PIL image")
+
+ # Get image dimensions
+ width, height = pil_image.size
+
+ # Create frames with different effects
+ for i in range(num_frames):
+ # Create a copy of the original image
+ frame = pil_image.copy()
+
+ # Apply different effects based on frame number
+ effect_type = i % 4
+
+ if effect_type == 0:
+ # Zoom effect
+ zoom_factor = 1.0 + (i % 12) * 0.01
+ new_width = int(width * zoom_factor)
+ new_height = int(height * zoom_factor)
+ zoomed = frame.resize((new_width, new_height), Image.LANCZOS)
+
+ # Crop to original size from center
+ left = (new_width - width) // 2
+ top = (new_height - height) // 2
+ frame = zoomed.crop((left, top, left + width, top + height))
+
+ elif effect_type == 1:
+ # Pan effect
+ pan_x = (i % 12) * 5
+ pan_y = (i % 8) * 3
+
+ # Create larger canvas
+ canvas = Image.new(frame.mode, (width + pan_x, height + pan_y))
+ canvas.paste(frame, (0, 0))
+
+ # Crop to original size from different position
+ frame = canvas.crop((pan_x, pan_y, pan_x + width, pan_y + height))
+
+ elif effect_type == 2:
+ # Brightness/contrast variation
+ from PIL import ImageEnhance
+
+ # Vary brightness slightly
+ brightness_factor = 0.9 + (i % 6) * 0.05
+ frame = ImageEnhance.Brightness(frame).enhance(brightness_factor)
+
+ # Vary contrast slightly
+ contrast_factor = 0.95 + (i % 4) * 0.05
+ frame = ImageEnhance.Contrast(frame).enhance(contrast_factor)
+
+ # Convert PIL image to numpy array
+ frame_np = np.array(frame).astype(np.float32) / 255.0
+
+ # Add frame to list
+ frames.append(frame_np)
+
+ # Convert frames to tensor
+ if frames:
+ frames_tensor = torch.from_numpy(np.stack(frames))
+ print(f"[PixVerseAPI] Batch {batch_idx+1}: Created {len(frames)} frames as tensor with shape {frames_tensor.shape}")
+
+ # Store the frames tensor
+ frame_tensors[batch_idx] = frames_tensor
+ video_urls.append(f"Batch {batch_idx+1}: Simplified animation (no URL)")
+ status_messages.append(f"Success (Batch {batch_idx+1}) - Simplified animation")
+ else:
+ video_urls.append(f"Batch {batch_idx+1}: Failed")
+ status_messages.append(f"Error (Batch {batch_idx+1}): No frames could be created")
+
+ except Exception as e:
+ print(f"[PixVerseAPI] Error creating animation for batch {batch_idx+1}: {str(e)}")
+ video_urls.append(f"Batch {batch_idx+1}: Failed")
+ status_messages.append(f"Error (Batch {batch_idx+1}): {str(e)}")
+
+ except Exception as e:
+ print(f"[PixVerseAPI] Error processing batch {batch_idx+1}: {str(e)}")
+ video_urls.append(f"Batch {batch_idx+1}: Failed")
+ status_messages.append(f"Error (Batch {batch_idx+1}): {str(e)}")
+
+ # Combine status messages
+ combined_status = " | ".join(status_messages) if status_messages else "No animations processed"
+
+ # Combine video URLs
+ combined_urls = " | ".join(video_urls) if video_urls else "No animations generated"
+
+ # Add a note about the simplified approach
+ note = "NOTE: Using simplified animation approach due to Fal AI API connection issues. " + \
+ "This is a fallback method that creates a basic animation effect from your image. " + \
+ "To use the actual Fal AI API, please check your network/DNS settings or try from a different network."
+
+ combined_status = note + " | " + combined_status
+
+ # Return the results
+ return tuple(frame_tensors + [combined_urls, combined_status, "Fal AI (simplified mode)"])
+
+ except Exception as e:
+ print(f"[PixVerseAPI] Error in simplified Fal AI processing: {str(e)}")
+ # Try to return proper empty tensors
+ empty_tensor = torch.zeros((1, 1, 1, 3))
+ return empty_tensor, empty_tensor, empty_tensor, empty_tensor, empty_tensor, "", f"Simplified mode error: {str(e)}", "N/A"
+
+ def get_account_balance(self, api_key, trace_id):
+ """
+ Get the account balance from the PixVerse API
+
+ Args:
+ api_key: PixVerse API key
+ trace_id: Trace ID for the request
+
+ Returns:
+ String representation of the credit balance or error message
+ """
+ try:
+ # Create connection to PixVerse API
+ conn = http.client.HTTPSConnection("app-api.pixverse.ai")
+
+ # Set up headers
+ headers = {
+ 'API-KEY': api_key,
+ 'Ai-trace-id': trace_id
+ }
+
+ # Make the request
+ conn.request("GET", "/openapi/v2/account/balance", "", headers)
+
+ # Get the response
+ response = conn.getresponse()
+ data = response.read().decode("utf-8")
+
+ # Parse the response
+ result = json.loads(data)
+
+ if result.get("ErrCode", -1) == 0:
+ # Extract balance information
+ balance = result.get("Resp", {}).get("balance", "Unknown")
+ print(f"[PixVerse] Account balance: {balance}")
+ return f"Credits: {balance}"
+ else:
+ error_msg = result.get("ErrMsg", "Unknown error")
+ print(f"[PixVerse] Error getting balance: {error_msg}")
+ return f"Balance error: {error_msg}"
+
+ except Exception as e:
+ print(f"[PixVerse] Error getting balance: {str(e)}")
+ return f"Balance error: {str(e)}"
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/ai/FL_RunwayAct2.py b/comfyui_fill-nodes/nodes/ai/FL_RunwayAct2.py
new file mode 100644
index 0000000000000000000000000000000000000000..1381a26c5587c6f75f262145ec344ada832a7465
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/FL_RunwayAct2.py
@@ -0,0 +1,329 @@
+import os
+import time
+import httpx
+import base64
+import io
+import json
+import torch
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+from typing import Literal, Union, List, Dict, Any
+
+from runwayml import RunwayML
+from runwayml._types import NotGiven, NOT_GIVEN
+from runwayml.types import TaskRetrieveResponse
+from runwayml._exceptions import APIError, APIStatusError, APIConnectionError, RateLimitError
+from comfy.utils import ProgressBar
+
+
+class FL_RunwayAct2:
+ DEFAULT_RUNWAY_API_VERSION = "2024-11-06"
+ MODEL_NAME: Literal["act_two"] = "act_two"
+ RATIO_OPTIONS = ['1280:720', '720:1280', '960:960', '1104:832', '832:1104', '1584:672']
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "api_key": ("STRING", {"multiline": False, "default": os.environ.get('RUNWAYML_API_SECRET', '')}),
+ "character_type": (["video", "image"], {"default": "video"}),
+ "ratio": (cls.RATIO_OPTIONS, {"default": "1280:720"}),
+ "runway_api_version": ("STRING", {"multiline": False, "default": cls.DEFAULT_RUNWAY_API_VERSION}),
+ },
+ "optional": {
+ "character_video": ("IMAGE",), # Will be converted to video format
+ "character_image": ("IMAGE",),
+ "reference_video": ("IMAGE",), # Will be converted to video format
+ "body_control": ("BOOLEAN", {"default": True}),
+ "expression_intensity": ("INT", {"default": 3, "min": 1, "max": 5}),
+ "seed": ("INT", {"default": 0, "min": 0, "max": 4294967295}),
+ "public_figure_threshold": (["auto", "low", "NOT_GIVEN"], {"default": "NOT_GIVEN"}),
+ "polling_interval": ("INT", {"default": 5, "min": 1, "max": 60}),
+ "max_polling_attempts": ("INT", {"default": 60, "min": 1, "max": 120}),
+ "timeout_sdk": ("FLOAT", {"default": 60.0, "min": 5.0, "max": 300.0, "step": 1.0}),
+ "timeout_download": ("FLOAT", {"default": 120.0, "min": 5.0, "max": 600.0, "step": 1.0}),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE", "STRING")
+ RETURN_NAMES = ("video_frames", "status_text")
+ FUNCTION = "generate_character_performance"
+ CATEGORY = "🏵️Fill Nodes/AI"
+
+ def __init__(self):
+ self.log_messages = []
+
+ def _log(self, message: str):
+ timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
+ full_message = f"[FL_RunwayAct2] {timestamp}: {message}"
+ print(full_message)
+ self.log_messages.append(full_message)
+
+ def _create_error_image(self, error_message="API Failed", width=1280, height=720) -> torch.Tensor:
+ image = Image.new('RGB', (width, height), color=(0, 0, 0))
+ draw = ImageDraw.Draw(image)
+ try:
+ font = ImageFont.truetype("arial.ttf", 24)
+ except IOError:
+ font = ImageFont.load_default()
+
+ text_bbox = draw.textbbox((0,0), error_message, font=font)
+ text_width = text_bbox[2] - text_bbox[0]
+ text_height = text_bbox[3] - text_bbox[1]
+ text_x = (width - text_width) / 2
+ text_y = (height - text_height) / 2
+ draw.text((text_x, text_y), error_message, fill=(255, 0, 0), font=font)
+
+ img_array = np.array(image).astype(np.float32) / 255.0
+ img_tensor = torch.from_numpy(img_array).unsqueeze(0)
+ self._log(f"Created error image: '{error_message}'")
+ return img_tensor
+
+ def _process_tensor_to_pil(self, tensor: torch.Tensor, name="Image") -> Union[Image.Image, None]:
+ if tensor is None:
+ return None
+
+ # Handle single image: [1, height, width, 3]
+ if len(tensor.shape) == 4 and tensor.shape[0] == 1:
+ image_np = tensor[0].cpu().numpy()
+ image_np = (image_np * 255).astype(np.uint8)
+ return Image.fromarray(image_np)
+
+ # Handle video batch: [frames, height, width, 3] - use first frame
+ elif len(tensor.shape) == 4 and tensor.shape[0] > 1:
+ self._log(f"{name} appears to be a video with {tensor.shape[0]} frames. Using first frame.")
+ image_np = tensor[0].cpu().numpy()
+ image_np = (image_np * 255).astype(np.uint8)
+ return Image.fromarray(image_np)
+
+ # Handle single frame without batch dimension: [height, width, 3]
+ elif len(tensor.shape) == 3:
+ image_np = tensor.cpu().numpy()
+ image_np = (image_np * 255).astype(np.uint8)
+ return Image.fromarray(image_np)
+
+ self._log(f"Error: {name} tensor format not supported: {tensor.shape}")
+ return None
+
+ def _pil_to_data_uri(self, pil_image: Image.Image, image_format="PNG") -> str:
+ buffered = io.BytesIO()
+ pil_image.save(buffered, format=image_format)
+ img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
+ return f"data:image/{image_format.lower()};base64,{img_str}"
+
+ def _create_video_data_uri_from_tensor(self, tensor: torch.Tensor, name="Video") -> str:
+ """Convert video tensor to data URI - for now using first frame as image"""
+ # Note: This is a simplified implementation. For full video support,
+ # you would need to encode the entire tensor as a video file (MP4, etc.)
+ # and create a proper video data URI. For now, we'll use the first frame.
+
+ if len(tensor.shape) == 4 and tensor.shape[0] > 1:
+ # Video tensor: [frames, height, width, 3]
+ self._log(f"{name} has {tensor.shape[0]} frames. Using first frame for API compatibility.")
+ first_frame = tensor[0].cpu().numpy()
+ first_frame = (first_frame * 255).astype(np.uint8)
+ pil_image = Image.fromarray(first_frame)
+ return self._pil_to_data_uri(pil_image, "PNG")
+ else:
+ # Single image, convert normally
+ pil_image = self._process_tensor_to_pil(tensor, name)
+ if pil_image:
+ return self._pil_to_data_uri(pil_image, "PNG")
+ else:
+ raise ValueError(f"Could not process {name} tensor")
+
+ def _download_and_process_video(self, video_url: str, timeout: float) -> torch.Tensor:
+ """Download video and convert to image tensor (first frame for now)"""
+ try:
+ with httpx.Client() as download_client:
+ response = download_client.get(video_url, follow_redirects=True, timeout=timeout)
+ response.raise_for_status()
+
+ # For now, we'll treat the downloaded content as an image
+ # In a full implementation, you'd use video processing libraries
+ pil_image = Image.open(io.BytesIO(response.content)).convert("RGB")
+ img_array = np.array(pil_image).astype(np.float32) / 255.0
+ img_tensor = torch.from_numpy(img_array).unsqueeze(0)
+ self._log("Video downloaded and processed successfully.")
+ return img_tensor
+ except Exception as e:
+ self._log(f"Error downloading video: {str(e)}")
+ raise
+
+ def generate_character_performance(
+ self, api_key: str, character_type: str, ratio: str, runway_api_version: str,
+ character_video: torch.Tensor = None, character_image: torch.Tensor = None,
+ reference_video: torch.Tensor = None, body_control: bool = True,
+ expression_intensity: int = 3, seed: int = 0, public_figure_threshold: str = "NOT_GIVEN",
+ polling_interval: int = 5, max_polling_attempts: int = 60,
+ timeout_sdk: float = 60.0, timeout_download: float = 120.0
+ ):
+ self.log_messages = []
+
+ if not api_key or not api_key.strip():
+ self._log("Error: RunwayML API key not provided.")
+ return self._create_error_image("API key missing"), "\n".join(self.log_messages)
+
+ # Validate inputs based on character type
+ if character_type == "video" and character_video is None:
+ self._log("Error: Character video is required when character_type is 'video'.")
+ return self._create_error_image("Character video missing"), "\n".join(self.log_messages)
+
+ if character_type == "image" and character_image is None:
+ self._log("Error: Character image is required when character_type is 'image'.")
+ return self._create_error_image("Character image missing"), "\n".join(self.log_messages)
+
+ if reference_video is None:
+ self._log("Error: Reference video is required.")
+ return self._create_error_image("Reference video missing"), "\n".join(self.log_messages)
+
+ current_runway_api_version = runway_api_version if runway_api_version and runway_api_version.strip() else self.DEFAULT_RUNWAY_API_VERSION
+
+ try:
+ client = RunwayML(api_key=api_key.strip(), runway_version=current_runway_api_version, timeout=timeout_sdk)
+ self._log(f"RunwayML client initialized. API Version: {client.runway_version}, Timeout: {timeout_sdk}s")
+ except Exception as e:
+ self._log(f"Failed to initialize RunwayML client: {str(e)}")
+ return self._create_error_image("SDK Client Init Failed"), "\n".join(self.log_messages)
+
+ active_task_id = None
+
+ try:
+ # Process character input
+ character_payload: Dict[str, Any] = {"type": character_type}
+
+ if character_type == "video" and character_video is not None:
+ try:
+ character_payload["uri"] = self._create_video_data_uri_from_tensor(character_video, "Character Video")
+ except Exception as e:
+ self._log(f"Error processing character video: {str(e)}")
+ return self._create_error_image("Failed to process character video"), "\n".join(self.log_messages)
+
+ elif character_type == "image" and character_image is not None:
+ pil_img = self._process_tensor_to_pil(character_image, "Character Image")
+ if pil_img:
+ character_payload["uri"] = self._pil_to_data_uri(pil_img)
+ else:
+ self._log("Error processing character image")
+ return self._create_error_image("Failed to process character image"), "\n".join(self.log_messages)
+
+ # Process reference video
+ try:
+ reference_payload = {
+ "type": "video",
+ "uri": self._create_video_data_uri_from_tensor(reference_video, "Reference Video")
+ }
+ except Exception as e:
+ self._log(f"Error processing reference video: {str(e)}")
+ return self._create_error_image("Failed to process reference video"), "\n".join(self.log_messages)
+
+ # Build create arguments
+ create_args: Dict[str, Any] = {
+ "model": self.MODEL_NAME,
+ "character": character_payload,
+ "reference": reference_payload,
+ "ratio": ratio,
+ "bodyControl": body_control,
+ "expressionIntensity": expression_intensity,
+ }
+
+ current_seed = NOT_GIVEN if seed == 0 else seed
+ create_args["seed"] = current_seed
+
+ if public_figure_threshold != "NOT_GIVEN":
+ create_args["contentModeration"] = {"publicFigureThreshold": public_figure_threshold}
+
+ self._log(f"Requesting character performance generation with model '{self.MODEL_NAME}'")
+ self._log(f"Character type: {character_type}, Ratio: {ratio}, Body control: {body_control}")
+ self._log(f"Expression intensity: {expression_intensity}")
+
+ # Submit the task using the working SDK method
+ try:
+ self._log("Submitting character performance request...")
+ initial_response = client.character_performance.create(**create_args)
+ active_task_id = initial_response.id
+ self._log(f"Task submitted successfully! Task ID: {active_task_id}")
+ except AttributeError as e:
+ self._log(f"SDK method not found: {str(e)}")
+ self._log("The character_performance method is not available in this SDK version.")
+ return self._create_error_image("SDK Method Not Available"), "\n".join(self.log_messages)
+ except Exception as e:
+ self._log(f"Error submitting task: {str(e)}")
+ return self._create_error_image("Task Submission Failed"), "\n".join(self.log_messages)
+
+ # Poll for completion
+ self._log(f"Polling task status for Task ID: {active_task_id} (every {polling_interval}s)...")
+ task_details: Union[TaskRetrieveResponse, None] = None
+ pbar = ProgressBar(max_polling_attempts)
+
+ for attempt in range(max_polling_attempts):
+ task_details = client.tasks.retrieve(id=active_task_id)
+ progress_percent = 0.0
+ if task_details.status == "RUNNING" and task_details.progress is not None:
+ progress_percent = task_details.progress * 100
+
+ status_log = f"Attempt {attempt + 1}/{max_polling_attempts} - Status: {task_details.status}"
+ if progress_percent > 0:
+ status_log += f", Progress: {progress_percent:.2f}%"
+ self._log(status_log)
+
+ if task_details.status == "SUCCEEDED":
+ self._log("Task SUCCEEDED!")
+ if task_details.output and len(task_details.output) > 0 and isinstance(task_details.output[0], str):
+ video_url = task_details.output[0]
+ self._log(f"Video URL: {video_url}")
+ self._log(f"Downloading video...")
+ try:
+ video_tensor = self._download_and_process_video(video_url, timeout_download)
+ return video_tensor, "\n".join(self.log_messages)
+ except httpx.HTTPStatusError as e_http:
+ self._log(f"Error downloading video: HTTP {e_http.response.status_code} - {e_http.response.text}")
+ return self._create_error_image(f"Download Failed: {e_http.response.status_code}"), "\n".join(self.log_messages)
+ except Exception as e_dl:
+ self._log(f"An error occurred during video download: {str(e_dl)}")
+ return self._create_error_image("Download Error"), "\n".join(self.log_messages)
+ else:
+ self._log("Task succeeded but no valid output URL found.")
+ return self._create_error_image("No Output URL"), "\n".join(self.log_messages)
+
+ elif task_details.status in ["FAILED", "CANCELLED"]:
+ self._log(f"Task {task_details.status}.")
+ failure_reason = task_details.failure if hasattr(task_details, 'failure') and task_details.failure else 'N/A'
+ failure_code = task_details.failure_code if hasattr(task_details, 'failure_code') and task_details.failure_code else 'N/A'
+ self._log(f" Reason: {failure_reason}")
+ self._log(f" Failure code: {failure_code}")
+ return self._create_error_image(f"Task {task_details.status}: {failure_reason[:60]}"), "\n".join(self.log_messages)
+
+ time.sleep(polling_interval)
+
+ # If loop finishes without returning
+ if task_details:
+ self._log(f"Max poll attempts ({max_polling_attempts}) reached. Last known task status: {task_details.status}.")
+ else:
+ self._log(f"Max poll attempts ({max_polling_attempts}) reached. Could not retrieve task details after submission.")
+ return self._create_error_image("Polling Timeout"), "\n".join(self.log_messages)
+
+ except APIConnectionError as e:
+ self._log(f"RunwayML API Connection Error: {str(e)}")
+ return self._create_error_image("API Connection Error"), "\n".join(self.log_messages)
+ except RateLimitError as e:
+ self._log(f"RunwayML Rate Limit Error: {str(e)}")
+ return self._create_error_image("Rate Limit Error"), "\n".join(self.log_messages)
+ except APIStatusError as e:
+ self._log(f"RunwayML API Status Error: {str(e)}. Status Code: {e.status_code if hasattr(e, 'status_code') else 'N/A'}. Response: {e.response.text if hasattr(e, 'response') and hasattr(e.response, 'text') else 'N/A'}")
+ return self._create_error_image(f"API Status Error: {e.status_code if hasattr(e, 'status_code') else ''}"), "\n".join(self.log_messages)
+ except APIError as e:
+ self._log(f"RunwayML API Error: {str(e)}")
+ return self._create_error_image("Runway API Error"), "\n".join(self.log_messages)
+ except Exception as e:
+ self._log(f"An unexpected error occurred: {str(e)}")
+ if active_task_id:
+ self._log(f"This error occurred for Task ID: {active_task_id}")
+ return self._create_error_image("Unexpected Node Error"), "\n".join(self.log_messages)
+ finally:
+ if 'client' in locals() and client is not None and hasattr(client, 'close'):
+ try:
+ client.close()
+ self._log("RunwayML client closed.")
+ except Exception as e_close:
+ self._log(f"Error closing RunwayML client: {str(e_close)}")
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/ai/FL_RunwayImageAPI.py b/comfyui_fill-nodes/nodes/ai/FL_RunwayImageAPI.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c58b3dfe2860df21ca24a056d04011ebefbdeb4
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/FL_RunwayImageAPI.py
@@ -0,0 +1,275 @@
+import os
+import time
+import httpx # For downloading the image
+import base64
+import io
+import json
+import torch
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+from typing import Literal, Union, List, Dict, Any
+
+from runwayml import RunwayML
+from runwayml._types import NotGiven, NOT_GIVEN # Import NOT_GIVEN sentinel
+from runwayml.types import TaskRetrieveResponse # For type hinting polled task
+from runwayml._exceptions import APIError, APIStatusError, APIConnectionError, RateLimitError
+from comfy.utils import ProgressBar # Import ProgressBar
+
+
+class FL_RunwayImageAPI:
+ # Default API version used by the SDK if not specified in constructor
+ # From your script, it seems the SDK handles this well if client is initialized with runway_version
+ DEFAULT_RUNWAY_API_VERSION = "2024-11-06"
+ MODEL_NAME: Literal["gen4_image"] = "gen4_image"
+ IMAGE_RATIO_OPTIONS = ['1920:1080', '1080:1920', '1024:1024', '1360:768', '1080:1080', '1168:880', '1440:1080', '1080:1440', '1808:768', '2112:912']
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "api_key": ("STRING", {"multiline": False, "default": os.environ.get('RUNWAYML_API_SECRET', '')}),
+ "prompt": ("STRING", {"multiline": True, "default": "A stunning photograph of a majestic wolf howling at a full moon."}),
+ "ratio": (cls.IMAGE_RATIO_OPTIONS, {"default": "1024:1024"}),
+ "runway_api_version": ("STRING", {"multiline": False, "default": cls.DEFAULT_RUNWAY_API_VERSION}),
+ },
+ "optional": {
+ "image1": ("IMAGE",),
+ "image2": ("IMAGE",),
+ "image3": ("IMAGE",),
+ "tag1": ("STRING", {"multiline": False, "default": ""}), # Default to empty, let user decide
+ "tag2": ("STRING", {"multiline": False, "default": ""}),
+ "tag3": ("STRING", {"multiline": False, "default": ""}),
+ "seed": ("INT", {"default": 0, "min": 0, "max": 4294967295}), # 0 will mean NOT_GIVEN
+ "public_figure_threshold": (["auto", "low", "NOT_GIVEN"], {"default": "NOT_GIVEN"}),
+ "polling_interval": ("INT", {"default": 5, "min": 1, "max": 60}),
+ "max_polling_attempts": ("INT", {"default": 36, "min": 1, "max": 120}), # Max 10 mins for 5s interval
+ "timeout_sdk": ("FLOAT", {"default": 60.0, "min": 5.0, "max": 300.0, "step": 1.0}), # For SDK client
+ "timeout_download": ("FLOAT", {"default": 60.0, "min": 5.0, "max": 300.0, "step": 1.0}), # For image download
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE", "STRING")
+ RETURN_NAMES = ("image", "status_text")
+ FUNCTION = "generate_image_from_script_logic"
+ CATEGORY = "🏵️Fill Nodes/AI"
+
+ def __init__(self):
+ self.log_messages = []
+
+ def _log(self, message: str):
+ timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
+ full_message = f"[FL_RunwayImageAPI] {timestamp}: {message}"
+ print(full_message)
+ self.log_messages.append(full_message) # Store full message with timestamp
+
+ def _create_error_image(self, error_message="API Failed", width=1024, height=1024) -> torch.Tensor:
+ image = Image.new('RGB', (width, height), color=(0, 0, 0))
+ draw = ImageDraw.Draw(image)
+ try:
+ font = ImageFont.truetype("arial.ttf", 24)
+ except IOError:
+ font = ImageFont.load_default()
+
+ text_bbox = draw.textbbox((0,0), error_message, font=font)
+ text_width = text_bbox[2] - text_bbox[0]
+ text_height = text_bbox[3] - text_bbox[1]
+ text_x = (width - text_width) / 2
+ text_y = (height - text_height) / 2
+ draw.text((text_x, text_y), error_message, fill=(255, 0, 0), font=font)
+
+ img_array = np.array(image).astype(np.float32) / 255.0
+ img_tensor = torch.from_numpy(img_array).unsqueeze(0)
+ self._log(f"Created error image: '{error_message}'")
+ return img_tensor
+
+ def _process_tensor_to_pil(self, tensor: torch.Tensor, name="Image") -> Union[Image.Image, None]:
+ if tensor is None: return None
+ if len(tensor.shape) == 4 and tensor.shape[0] == 1:
+ image_np = tensor[0].cpu().numpy()
+ image_np = (image_np * 255).astype(np.uint8)
+ return Image.fromarray(image_np)
+ self._log(f"Error: {name} tensor format incorrect: {tensor.shape}")
+ return None
+
+ def _pil_to_data_uri(self, pil_image: Image.Image, image_format="PNG") -> str:
+ buffered = io.BytesIO()
+ pil_image.save(buffered, format=image_format)
+ img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
+ return f"data:image/{image_format.lower()};base64,{img_str}"
+
+ def generate_image_from_script_logic(
+ self, api_key: str, prompt: str, ratio: str, runway_api_version: str,
+ image1: torch.Tensor = None, image2: torch.Tensor = None, image3: torch.Tensor = None,
+ tag1: str = "", tag2: str = "", tag3: str = "",
+ seed: int = 0, public_figure_threshold: str = "NOT_GIVEN",
+ polling_interval: int = 5, max_polling_attempts: int = 36,
+ timeout_sdk: float = 60.0, timeout_download: float = 60.0
+ ):
+ self.log_messages = [] # Reset logs for each run
+
+ if not api_key or not api_key.strip():
+ self._log("Error: RunwayML API key not provided.")
+ return self._create_error_image("API key missing"), "\n".join(self.log_messages)
+
+ # Use runway_api_version from input, or default if empty
+ current_runway_api_version = runway_api_version if runway_api_version and runway_api_version.strip() else self.DEFAULT_RUNWAY_API_VERSION
+
+ try:
+ client = RunwayML(api_key=api_key.strip(), runway_version=current_runway_api_version, timeout=timeout_sdk)
+ self._log(f"RunwayML client initialized. API Version: {client.runway_version}, Timeout: {timeout_sdk}s")
+ except Exception as e:
+ self._log(f"Failed to initialize RunwayML client: {str(e)}")
+ return self._create_error_image("SDK Client Init Failed"), "\n".join(self.log_messages)
+
+ active_task_id = None
+
+ reference_images_payload: List[Dict[str, Any]] = []
+ input_images_with_tags = [(image1, tag1), (image2, tag2), (image3, tag3)]
+ for i, (img_tensor, tag_str) in enumerate(input_images_with_tags):
+ if img_tensor is not None:
+ pil_img = self._process_tensor_to_pil(img_tensor, f"Reference Image {i+1}")
+ if pil_img:
+ data_uri = self._pil_to_data_uri(pil_img)
+ ref_img_obj = {"uri": data_uri}
+ clean_tag = tag_str.strip() if tag_str else ""
+ if clean_tag and 3 <= len(clean_tag) <= 16 and clean_tag[0].isalpha() and clean_tag.replace('_', '').isalnum():
+ ref_img_obj["tag"] = clean_tag
+ elif clean_tag:
+ self._log(f"Warning: Tag '{clean_tag}' for image {i+1} is invalid and will be ignored.")
+ reference_images_payload.append(ref_img_obj)
+ else:
+ self._log(f"Error processing reference image {i+1}")
+ return self._create_error_image(f"Failed to process ref image {i+1}"), "\n".join(self.log_messages)
+
+ create_args: Dict[str, Any] = {
+ "model": self.MODEL_NAME,
+ "prompt_text": prompt,
+ "ratio": ratio,
+ }
+ if reference_images_payload: # Only add if there are valid reference images
+ create_args["reference_images"] = reference_images_payload
+
+ current_seed = NOT_GIVEN if seed == 0 else seed
+ create_args["seed"] = current_seed
+
+ if public_figure_threshold != "NOT_GIVEN":
+ create_args["content_moderation"] = {"publicFigureThreshold": public_figure_threshold}
+
+ try:
+ self._log(f"Requesting image generation with prompt: '{prompt}' using model '{self.MODEL_NAME}'")
+ self._log(f"Create args (excluding images for brevity if many): { {k:v for k,v in create_args.items() if k != 'reference_images'} }")
+ if 'reference_images' in create_args:
+ self._log(f"Number of reference images: {len(create_args['reference_images'])}")
+
+
+ initial_response = client.text_to_image.create(**create_args)
+ active_task_id = initial_response.id
+ self._log(f"Task submitted successfully! Task ID: {active_task_id}")
+
+ self._log(f"Polling task status for Task ID: {active_task_id} (every {polling_interval}s)...")
+ task_details: Union[TaskRetrieveResponse, None] = None
+ pbar = ProgressBar(max_polling_attempts) # Initialize ProgressBar
+ for attempt in range(max_polling_attempts):
+ task_details = client.tasks.retrieve(id=active_task_id)
+ progress_percent = 0.0
+ if task_details.status == "RUNNING" and task_details.progress is not None:
+ progress_percent = task_details.progress * 100
+
+ status_log = f"Attempt {attempt + 1}/{max_polling_attempts} - Status: {task_details.status}"
+ if progress_percent > 0:
+ status_log += f", Progress: {progress_percent:.2f}%"
+ self._log(status_log)
+
+ # Update progress bar: current value is attempt number, max is max_polling_attempts
+ # If RUNNING and progress is available, use that for a more granular bar update.
+ # However, ProgressBar typically expects an iteration count.
+ # We can simulate this by updating based on attempts, or if RUNNING, map task_details.progress to pbar's scale.
+ # For simplicity, we'll update based on attempts.
+ # If task_details.progress is available, we can use it to show a more fine-grained update
+ # by mapping it to the total attempts.
+ # For now, just update based on attempt count.
+ # A more sophisticated approach might involve setting pbar total to 100 and updating with progress_percent
+ # but that might look weird if the task finishes early or takes many polls without progress change.
+
+ current_progress_for_bar = attempt + 1 # Default to attempt number
+ if task_details.status == "RUNNING" and task_details.progress is not None:
+ # Map task progress (0-1) to polling attempts for a smoother bar
+ # This is an approximation. If progress jumps, bar will jump.
+ # If progress is slow, bar updates per poll.
+ current_progress_for_bar = int(task_details.progress * max_polling_attempts)
+ # Ensure it doesn't exceed max_polling_attempts due to rounding or jumps
+ current_progress_for_bar = min(current_progress_for_bar, max_polling_attempts)
+ # Ensure it's at least the current attempt, so it doesn't go backwards
+ current_progress_for_bar = max(current_progress_for_bar, attempt + 1)
+
+ # Temporarily comment out to diagnose AttributeError
+ # pbar.update_absolute(current_progress_for_bar, max_polling_attempts, status_log)
+
+
+ if task_details.status == "SUCCEEDED":
+ self._log("Task SUCCEEDED!")
+ if task_details.output and len(task_details.output) > 0 and isinstance(task_details.output[0], str):
+ image_url = task_details.output[0]
+ self._log(f"Image URL: {image_url}")
+ self._log(f"Downloading image...")
+ try:
+ with httpx.Client() as download_client:
+ response = download_client.get(image_url, follow_redirects=True, timeout=timeout_download)
+ response.raise_for_status()
+ pil_image = Image.open(io.BytesIO(response.content)).convert("RGB")
+ img_array = np.array(pil_image).astype(np.float32) / 255.0
+ img_tensor = torch.from_numpy(img_array).unsqueeze(0)
+ self._log("Image downloaded and processed successfully.")
+ return img_tensor, "\n".join(self.log_messages)
+ except httpx.HTTPStatusError as e_http:
+ self._log(f"Error downloading image: HTTP {e_http.response.status_code} - {e_http.response.text}")
+ return self._create_error_image(f"Download Failed: {e_http.response.status_code}"), "\n".join(self.log_messages)
+ except Exception as e_dl:
+ self._log(f"An error occurred during image download: {str(e_dl)}")
+ return self._create_error_image("Download Error"), "\n".join(self.log_messages)
+ else:
+ self._log("Task succeeded but no valid output URL found.")
+ return self._create_error_image("No Output URL"), "\n".join(self.log_messages)
+
+ elif task_details.status in ["FAILED", "CANCELLED"]: # Your script uses CANCELLED, SDK might use CANCELED
+ self._log(f"Task {task_details.status}.")
+ failure_reason = task_details.failure if hasattr(task_details, 'failure') and task_details.failure else 'N/A'
+ failure_code = task_details.failure_code if hasattr(task_details, 'failure_code') and task_details.failure_code else 'N/A'
+ self._log(f" Reason: {failure_reason}")
+ self._log(f" Failure code: {failure_code}")
+ # ... (additional suggestions from your script can be added here if desired)
+ return self._create_error_image(f"Task {task_details.status}: {failure_reason[:60]}"), "\n".join(self.log_messages)
+
+ time.sleep(polling_interval)
+
+ # If loop finishes without returning
+ if task_details:
+ self._log(f"Max poll attempts ({max_polling_attempts}) reached. Last known task status: {task_details.status}.")
+ else: # Should not happen if initial submission was successful
+ self._log(f"Max poll attempts ({max_polling_attempts}) reached. Could not retrieve task details after submission.")
+ return self._create_error_image("Polling Timeout"), "\n".join(self.log_messages)
+
+ except APIConnectionError as e:
+ self._log(f"RunwayML API Connection Error: {str(e)}")
+ return self._create_error_image("API Connection Error"), "\n".join(self.log_messages)
+ except RateLimitError as e:
+ self._log(f"RunwayML Rate Limit Error: {str(e)}")
+ return self._create_error_image("Rate Limit Error"), "\n".join(self.log_messages)
+ except APIStatusError as e:
+ self._log(f"RunwayML API Status Error: {str(e)}. Status Code: {e.status_code if hasattr(e, 'status_code') else 'N/A'}. Response: {e.response.text if hasattr(e, 'response') and hasattr(e.response, 'text') else 'N/A'}")
+ return self._create_error_image(f"API Status Error: {e.status_code if hasattr(e, 'status_code') else ''}"), "\n".join(self.log_messages)
+ except APIError as e: # General SDK error
+ self._log(f"RunwayML API Error: {str(e)}")
+ return self._create_error_image("Runway API Error"), "\n".join(self.log_messages)
+ except Exception as e:
+ self._log(f"An unexpected error occurred: {str(e)}")
+ if active_task_id:
+ self._log(f"This error occurred for Task ID: {active_task_id}")
+ return self._create_error_image("Unexpected Node Error"), "\n".join(self.log_messages)
+ finally:
+ if 'client' in locals() and client is not None and hasattr(client, 'close'):
+ try:
+ client.close()
+ self._log("RunwayML client closed.")
+ except Exception as e_close:
+ self._log(f"Error closing RunwayML client: {str(e_close)}")
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/ai/FL_VertexGemini25FlashImage.py b/comfyui_fill-nodes/nodes/ai/FL_VertexGemini25FlashImage.py
new file mode 100644
index 0000000000000000000000000000000000000000..224a0033adbc001c9469fe8539fb29a33b56684c
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/FL_VertexGemini25FlashImage.py
@@ -0,0 +1,361 @@
+import os
+import io
+import json
+import base64
+import torch
+import numpy as np
+from PIL import Image
+import time
+import traceback
+import asyncio
+from concurrent.futures import ThreadPoolExecutor
+from google import genai
+from google.genai import types
+from google.oauth2 import service_account
+from typing import Optional, Tuple
+
+
+class FL_VertexGemini25FlashImage:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "prompt": ("STRING", {"multiline": True, "default": ""}),
+ "service_account_json": ("STRING", {"default": "", "multiline": False}),
+ "batch_count": ("INT", {"default": 1, "min": 1, "max": 8, "step": 1}),
+ "temperature": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1}),
+ "seed": ("INT", {"default": 0, "min": 0, "max": 666666}),
+ },
+ "optional": {
+ "reference_image_1": ("IMAGE",),
+ "reference_image_2": ("IMAGE",),
+ "reference_image_3": ("IMAGE",),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE", "STRING")
+ RETURN_NAMES = ("images", "API_Response")
+ FUNCTION = "generate_image"
+ CATEGORY = "🏵️Fill Nodes/AI"
+
+ def __init__(self):
+ """Initialize logging system"""
+ self.log_messages = []
+
+ def _log(self, message):
+ """Global logging function: record to log list"""
+ timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
+ formatted_message = f"[FL_VertexGemini25FlashImage] {timestamp}: {message}"
+ print(formatted_message)
+ self.log_messages.append(message)
+ return message
+
+ def _process_tensor_to_pil(self, tensor, name="Image"):
+ """Convert a tensor to a PIL image for API submission"""
+ try:
+ if tensor is None:
+ self._log(f"{name} is None, skipping")
+ return None
+
+ # Ensure tensor is in correct format [1, H, W, 3]
+ if len(tensor.shape) == 4 and tensor.shape[0] >= 1:
+ # Get first frame image
+ image_np = tensor[0].cpu().numpy()
+
+ # Convert to uint8 format for PIL
+ image_np = (image_np * 255).astype(np.uint8)
+
+ # Create PIL image
+ pil_image = Image.fromarray(image_np)
+
+ self._log(f"{name} processed successfully, size: {pil_image.width}x{pil_image.height}")
+ return pil_image
+ else:
+ self._log(f"{name} format incorrect: {tensor.shape}")
+ return None
+ except Exception as e:
+ self._log(f"Error processing {name}: {str(e)}")
+ return None
+
+ def _prepare_image_for_api(self, pil_image):
+ """Prepare PIL image for Vertex AI - just return the PIL image directly"""
+ try:
+ self._log(f"Preparing image for API: {pil_image.width}x{pil_image.height}")
+
+ # For Vertex AI generate_content with Gemini models,
+ # we can pass PIL images directly and the SDK handles conversion
+ return pil_image
+
+ except Exception as e:
+ self._log(f"Error preparing image: {str(e)}")
+ traceback.print_exc()
+ return None
+
+ def _create_error_frame(self, error_message="Image Generation Failed", width=512, height=512):
+ """Create a black error frame with red text"""
+ from PIL import ImageDraw, ImageFont
+
+ image = Image.new('RGB', (width, height), color=(0, 0, 0))
+ draw = ImageDraw.Draw(image)
+
+ try:
+ font = ImageFont.load_default()
+ except Exception:
+ font = ImageFont.load_default()
+
+ # Draw error text
+ text_bbox = draw.textbbox((0, 0), error_message, font=font)
+ text_width = text_bbox[2] - text_bbox[0]
+ text_height = text_bbox[3] - text_bbox[1]
+ text_x = (width - text_width) / 2
+ text_y = (height - text_height) / 2
+
+ draw.text((text_x, text_y), error_message, fill=(255, 0, 0), font=font)
+
+ # Convert to tensor format [1, H, W, 3]
+ img_array = np.array(image).astype(np.float32) / 255.0
+ img_tensor = torch.from_numpy(img_array).unsqueeze(0)
+
+ self._log(f"Created error frame with message: '{error_message}'")
+ return img_tensor
+
+ def generate_image(self, prompt: str, service_account_json: str,
+ batch_count: int = 1,
+ temperature: float = 1.0, seed: int = 0, reference_image_1=None,
+ reference_image_2=None, reference_image_3=None):
+ """Generate image using Gemini 2.5 Flash Image API"""
+
+ # Reset log messages
+ self.log_messages = []
+
+ # Log seed parameter (not sent to API, just for node tracking)
+ self._log(f"Seed parameter: {seed} (not sent to API)")
+
+ try:
+ # Validate service account JSON file
+ if not service_account_json:
+ error_message = "Error: No service account JSON file provided."
+ self._log(error_message)
+ error_frame = self._create_error_frame("Service account required")
+ return (error_frame, error_message)
+
+ # Build full path to service account JSON
+ script_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ json_path = os.path.join(script_dir, service_account_json)
+
+ if not os.path.exists(json_path):
+ error_message = f"Error: Service account JSON file not found at {json_path}"
+ self._log(error_message)
+ error_frame = self._create_error_frame("JSON file not found")
+ return (error_frame, error_message)
+
+ # Validate prompt
+ if not prompt or len(prompt.strip()) == 0:
+ error_message = "Error: No prompt provided. Please enter an image generation prompt."
+ self._log(error_message)
+ error_frame = self._create_error_frame("Prompt required")
+ return (error_frame, error_message)
+
+ # Load credentials from service account JSON
+ self._log(f"Loading service account credentials from: {json_path}")
+
+ # Read the JSON file to get project_id
+ with open(json_path, 'r') as f:
+ service_account_info = json.load(f)
+ project_id = service_account_info.get('project_id')
+
+ if not project_id:
+ error_message = "Error: No project_id found in service account JSON"
+ self._log(error_message)
+ error_frame = self._create_error_frame("Missing project_id")
+ return (error_frame, error_message)
+
+ credentials = service_account.Credentials.from_service_account_file(
+ json_path,
+ scopes=['https://www.googleapis.com/auth/cloud-platform']
+ )
+
+ # Initialize client with Vertex AI
+ client = genai.Client(
+ vertexai=True,
+ project=project_id,
+ location='us-central1',
+ credentials=credentials
+ )
+ self._log(f"Gemini client initialized with Vertex AI (project: {project_id})")
+
+ # Build the contents for the API call
+ contents = []
+
+ # Add reference images if provided (up to 3)
+ reference_images = [reference_image_1, reference_image_2, reference_image_3]
+ image_count = 0
+
+ for i, ref_image in enumerate(reference_images, 1):
+ if ref_image is not None:
+ pil_reference = self._process_tensor_to_pil(ref_image, f"Reference Image {i}")
+ if pil_reference:
+ # Prepare image for Vertex AI
+ image_for_api = self._prepare_image_for_api(pil_reference)
+ if not image_for_api:
+ error_message = f"Failed to prepare reference image {i}"
+ self._log(error_message)
+ error_frame = self._create_error_frame(error_message)
+ return (error_frame, error_message)
+ contents.append(image_for_api)
+ image_count += 1
+ self._log(f"Reference image {i} added to request")
+
+ if image_count > 0:
+ self._log(f"Total reference images: {image_count}")
+
+ # Add the prompt
+ contents.append(prompt)
+
+ # Build the configuration
+ # Note: Vertex AI doesn't support aspect_ratio in current version
+ # Users can specify desired aspect ratio in the prompt text itself
+ # candidate_count is hardcoded to 1, use batch_count for multiple images
+ config = types.GenerateContentConfig(
+ response_modalities=["IMAGE"],
+ candidate_count=1,
+ temperature=temperature
+ )
+
+ self._log(f"Generating {batch_count} image(s) with prompt: {prompt[:100]}...")
+ self._log(f"Temperature: {temperature}")
+
+ # Function to make a single API call
+ def generate_single_image(batch_idx):
+ try:
+ self._log(f"Starting batch {batch_idx + 1}/{batch_count}...")
+
+ response = client.models.generate_content(
+ model="gemini-2.5-flash-image",
+ contents=contents,
+ config=config
+ )
+
+ self._log(f"Batch {batch_idx + 1} API response received")
+
+ # Log response structure for debugging
+ self._log(f"Batch {batch_idx + 1} - Number of candidates: {len(response.candidates) if hasattr(response, 'candidates') else 'N/A'}")
+
+ # Check for prompt feedback (content filtering, safety blocks, etc.)
+ if hasattr(response, 'prompt_feedback') and response.prompt_feedback:
+ self._log(f"Batch {batch_idx + 1} - Prompt feedback: {response.prompt_feedback}")
+
+ # Extract image from response
+ image_found = False
+ for candidate_idx, candidate in enumerate(response.candidates):
+ self._log(f"Batch {batch_idx + 1} - Candidate {candidate_idx}: {len(candidate.content.parts) if hasattr(candidate, 'content') else 'N/A'} parts")
+
+ # Check for finish reason (safety blocks, etc.)
+ if hasattr(candidate, 'finish_reason'):
+ self._log(f"Batch {batch_idx + 1} - Candidate {candidate_idx} finish_reason: {candidate.finish_reason}")
+
+ # Check for safety ratings
+ if hasattr(candidate, 'safety_ratings') and candidate.safety_ratings:
+ self._log(f"Batch {batch_idx + 1} - Candidate {candidate_idx} safety_ratings: {candidate.safety_ratings}")
+
+ for part_idx, part in enumerate(candidate.content.parts):
+ self._log(f"Batch {batch_idx + 1} - Part {part_idx} type: {type(part).__name__}")
+ self._log(f"Batch {batch_idx + 1} - Part {part_idx} has inline_data: {hasattr(part, 'inline_data')}")
+
+ if hasattr(part, 'inline_data') and part.inline_data:
+ image_data = part.inline_data.data
+ self._log(f"Batch {batch_idx + 1} - inline_data size: {len(image_data)} bytes")
+
+ # Check mime type if available
+ if hasattr(part.inline_data, 'mime_type'):
+ self._log(f"Batch {batch_idx + 1} - inline_data mime_type: {part.inline_data.mime_type}")
+
+ # Check if data is base64 encoded (starts with base64 characters)
+ # Raw binary images start with magic bytes (e.g., PNG: \x89PNG, JPEG: \xff\xd8)
+ # Base64 encoded data will be ASCII/UTF-8 text
+ is_base64 = False
+ try:
+ # Check if the data looks like base64 (ASCII text)
+ if isinstance(image_data, bytes):
+ # Try to decode as ASCII - base64 is ASCII
+ test_str = image_data[:20].decode('ascii')
+ # Check if it starts with common base64 PNG prefix
+ if test_str.startswith('iVBORw0KG') or test_str.startswith('/9j/'):
+ is_base64 = True
+ self._log(f"Batch {batch_idx + 1} - Detected base64-encoded data")
+ except:
+ pass
+
+ # Decode base64 if needed
+ if is_base64:
+ try:
+ image_data = base64.b64decode(image_data)
+ self._log(f"Batch {batch_idx + 1} - Decoded base64, new size: {len(image_data)} bytes")
+ except Exception as e:
+ self._log(f"Batch {batch_idx + 1} - Failed to decode base64: {str(e)}")
+
+ # Check image header to identify format (after potential base64 decode)
+ image_header = image_data[:16] if len(image_data) >= 16 else image_data
+ self._log(f"Batch {batch_idx + 1} - image header (hex): {image_header.hex()}")
+
+ pil_image = Image.open(io.BytesIO(image_data))
+ self._log(f"Batch {batch_idx + 1} image received: {pil_image.width}x{pil_image.height}")
+
+ # Convert to tensor format [H, W, 3]
+ img_array = np.array(pil_image).astype(np.float32) / 255.0
+
+ # Handle RGBA images
+ if img_array.shape[-1] == 4:
+ img_array = img_array[:, :, :3]
+
+ image_found = True
+ return torch.from_numpy(img_array)
+ elif hasattr(part, 'text'):
+ self._log(f"Batch {batch_idx + 1} - Part {part_idx} contains text: {part.text[:100] if len(part.text) > 100 else part.text}")
+
+ if not image_found:
+ self._log(f"Batch {batch_idx + 1} - WARNING: No image data found in response")
+
+ return None
+ except Exception as e:
+ self._log(f"Error in batch {batch_idx + 1}: {str(e)}")
+ self._log(f"Batch {batch_idx + 1} - Full traceback: {traceback.format_exc()}")
+ return None
+
+ # Generate images in parallel using ThreadPoolExecutor
+ generated_images = []
+ with ThreadPoolExecutor(max_workers=batch_count) as executor:
+ futures = [executor.submit(generate_single_image, i) for i in range(batch_count)]
+ for future in futures:
+ result = future.result()
+ if result is not None:
+ generated_images.append(result)
+
+ if not generated_images:
+ error_message = "No images generated by the API"
+ self._log(error_message)
+ error_frame = self._create_error_frame(error_message)
+ return (error_frame, error_message)
+
+ # Stack images into a batch tensor [B, H, W, C]
+ images_batch = torch.stack(generated_images, dim=0)
+
+ # Prepare response text
+ response_text = "## Image Generation Successful\n"
+ response_text += f"Generated {len(generated_images)} image(s)\n"
+ response_text += f"Batch shape: {images_batch.shape}\n"
+ response_text += "\n## Processing Log\n" + "\n".join(self.log_messages)
+
+ self._log(f"Successfully generated {len(generated_images)} image(s)")
+
+ return (images_batch, response_text)
+
+ except Exception as e:
+ error_message = f"Error during image generation: {str(e)}"
+ self._log(error_message)
+ traceback.print_exc()
+
+ error_frame = self._create_error_frame(f"Error: {str(e)}")
+ full_text = "## Processing Log\n" + "\n".join(self.log_messages) + "\n\n## Error\n" + error_message
+
+ return (error_frame, full_text)
diff --git a/comfyui_fill-nodes/nodes/ai/FL_VertexVeo3.py b/comfyui_fill-nodes/nodes/ai/FL_VertexVeo3.py
new file mode 100644
index 0000000000000000000000000000000000000000..d59ca2113c45afab834fa81d03b97619e2aa4b20
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/FL_VertexVeo3.py
@@ -0,0 +1,713 @@
+import os
+import base64
+import io
+import json
+import torch
+import numpy as np
+from PIL import Image
+import requests
+import tempfile
+import time
+import traceback
+from google import genai
+from google.genai import types
+from google.auth import default
+from google.auth.transport.requests import Request
+from google.oauth2 import service_account
+import urllib.request
+from typing import Optional, Tuple
+
+
+class FL_Veo3VideoGen:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "prompt": ("STRING", {"multiline": True, "default": ""}),
+ "service_account_json": ("STRING", {"default": "", "multiline": False}),
+ "model": (
+ [
+ "veo-3.0-generate-001",
+ "veo-3.0-fast-generate-001",
+ "veo-2.0-generate-001"
+ ],
+ {"default": "veo-3.0-generate-001"}
+ ),
+ "aspect_ratio": (
+ ["16:9", "9:16"],
+ {"default": "16:9"}
+ ),
+ "resolution": (
+ ["720p", "1080p"],
+ {"default": "720p"}
+ ),
+ "max_retries": ("INT", {"default": 3, "min": 1, "max": 10, "step": 1}),
+ "polling_interval": ("INT", {"default": 10, "min": 5, "max": 60, "step": 5, "description": "Seconds between status checks"}),
+ "max_wait_time": ("INT", {"default": 360, "min": 60, "max": 600, "step": 30, "description": "Maximum seconds to wait for video generation"}),
+ },
+ "optional": {
+ "negative_prompt": ("STRING", {"multiline": True, "default": ""}),
+ "seed": ("INT", {"default": 0, "min": 0, "max": 2147483647}),
+ "reference_image": ("IMAGE",),
+ "enable_person_generation": ("BOOLEAN", {"default": True}),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE", "STRING", "STRING")
+ RETURN_NAMES = ("frames", "video_path", "API_Response")
+ FUNCTION = "generate_video"
+ CATEGORY = "🏵️Fill Nodes/AI"
+
+ def __init__(self):
+ """Initialize logging system"""
+ self.log_messages = []
+
+ def _log(self, message):
+ """Global logging function: record to log list"""
+ timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
+ formatted_message = f"[FL_Veo3VideoGen] {timestamp}: {message}"
+ print(formatted_message)
+ self.log_messages.append(message)
+ return message
+
+ def _process_tensor_to_pil(self, tensor, name="Image"):
+ """Convert a tensor to a PIL image for API submission"""
+ try:
+ if tensor is None:
+ self._log(f"{name} is None, skipping")
+ return None
+
+ # Ensure tensor is in correct format [1, H, W, 3]
+ if len(tensor.shape) == 4 and tensor.shape[0] >= 1:
+ # Get first frame image
+ image_np = tensor[0].cpu().numpy()
+
+ # Convert to uint8 format for PIL
+ image_np = (image_np * 255).astype(np.uint8)
+
+ # Create PIL image
+ pil_image = Image.fromarray(image_np)
+
+ self._log(f"{name} processed successfully, size: {pil_image.width}x{pil_image.height}")
+ return pil_image
+ else:
+ self._log(f"{name} format incorrect: {tensor.shape}")
+ return None
+ except Exception as e:
+ self._log(f"Error processing {name}: {str(e)}")
+ return None
+
+ def _prepare_image_for_api(self, pil_image):
+ """Prepare PIL image for Vertex AI"""
+ try:
+ from google.genai.types import Image as GenAIImage
+
+ self._log(f"Preparing image for API: {pil_image.width}x{pil_image.height}")
+
+ # Convert PIL image to bytes
+ img_byte_arr = io.BytesIO()
+ pil_image.save(img_byte_arr, format='PNG')
+ img_bytes = img_byte_arr.getvalue()
+
+ self._log(f"Image converted to bytes: {len(img_bytes)} bytes")
+
+ # Create Image object with bytes
+ image_obj = GenAIImage(
+ image_bytes=img_bytes,
+ mime_type="image/png"
+ )
+
+ return image_obj
+
+ except Exception as e:
+ self._log(f"Error preparing image: {str(e)}")
+ traceback.print_exc()
+ return None
+
+ def _create_error_frame(self, error_message="Video Generation Failed", width=1280, height=720):
+ """Create a black error frame with red text"""
+ from PIL import ImageDraw, ImageFont
+
+ image = Image.new('RGB', (width, height), color=(0, 0, 0))
+ draw = ImageDraw.Draw(image)
+
+ try:
+ font = ImageFont.load_default()
+ except Exception:
+ font = ImageFont.load_default()
+
+ # Draw error text
+ text_bbox = draw.textbbox((0, 0), error_message, font=font)
+ text_width = text_bbox[2] - text_bbox[0]
+ text_height = text_bbox[3] - text_bbox[1]
+ text_x = (width - text_width) / 2
+ text_y = (height - text_height) / 2
+
+ draw.text((text_x, text_y), error_message, fill=(255, 0, 0), font=font)
+
+ # Convert to tensor format [1, H, W, 3]
+ img_array = np.array(image).astype(np.float32) / 255.0
+ img_tensor = torch.from_numpy(img_array).unsqueeze(0)
+
+ self._log(f"Created error frame with message: '{error_message}'")
+ return img_tensor
+
+ def _download_video(self, video_url: str) -> Optional[str]:
+ """Download video from URL to temporary file"""
+ try:
+ self._log(f"Downloading video from: {video_url}")
+
+ temp_file = os.path.join(
+ tempfile.gettempdir(),
+ f"veo3_video_{int(time.time())}.mp4"
+ )
+
+ urllib.request.urlretrieve(video_url, temp_file)
+
+ file_size = os.path.getsize(temp_file)
+ self._log(f"Video downloaded successfully: {file_size} bytes")
+
+ return temp_file
+
+ except Exception as e:
+ self._log(f"Error downloading video: {str(e)}")
+ return None
+
+ def _extract_frames_from_video(self, video_path: str) -> list:
+ """Extract all frames from video file"""
+ try:
+ import cv2
+
+ self._log(f"Extracting frames from: {video_path}")
+
+ cap = cv2.VideoCapture(video_path)
+ frames = []
+
+ if not cap.isOpened():
+ self._log("Error: Could not open video file")
+ return []
+
+ frame_count = 0
+ while True:
+ ret, frame = cap.read()
+ if not ret:
+ break
+
+ # Convert BGR to RGB
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
+
+ # Convert to tensor format [H, W, 3] with values 0-1
+ frame_array = frame_rgb.astype(np.float32) / 255.0
+ frame_tensor = torch.from_numpy(frame_array)
+
+ frames.append(frame_tensor)
+ frame_count += 1
+
+ cap.release()
+
+ self._log(f"Extracted {frame_count} frames from video")
+
+ return frames
+
+ except Exception as e:
+ self._log(f"Error extracting frames: {str(e)}")
+ traceback.print_exc()
+ return []
+
+ def _call_veo_api(self, client, model: str, prompt: str, config,
+ reference_image = None,
+ retry_count: int = 0, max_retries: int = 3) -> Optional[any]:
+ """Call VEO API with retry logic"""
+ try:
+ self._log(f"API call attempt #{retry_count + 1}")
+ self._log(f"Model: {model}")
+ self._log(f"Prompt: {prompt[:100]}..." if len(prompt) > 100 else f"Prompt: {prompt}")
+
+ # Make the API call using generate_videos
+ if reference_image is not None:
+ self._log(f"Using reference image")
+ if config is not None:
+ operation = client.models.generate_videos(
+ model=model,
+ prompt=prompt,
+ image=reference_image,
+ config=config
+ )
+ else:
+ operation = client.models.generate_videos(
+ model=model,
+ prompt=prompt,
+ image=reference_image
+ )
+ else:
+ if config is not None:
+ operation = client.models.generate_videos(
+ model=model,
+ prompt=prompt,
+ config=config
+ )
+ else:
+ operation = client.models.generate_videos(
+ model=model,
+ prompt=prompt
+ )
+
+ self._log("Initial API response received")
+ return operation
+
+ except Exception as e:
+ self._log(f"API call error: {str(e)}")
+ if retry_count < max_retries - 1:
+ wait_time = 5 * (retry_count + 1)
+ self._log(f"Retrying in {wait_time} seconds... (Attempt {retry_count + 1}/{max_retries})")
+ time.sleep(wait_time)
+ return self._call_veo_api(client, model, prompt, config, reference_image,
+ retry_count + 1, max_retries)
+ else:
+ self._log(f"Maximum retries ({max_retries}) reached. Giving up.")
+ return None
+
+ def _poll_video_generation(self, client, operation,
+ polling_interval: int = 10,
+ max_wait_time: int = 360) -> Optional[dict]:
+ """Poll the API until video generation is complete"""
+ try:
+ start_time = time.time()
+ self._log(f"Starting to poll for video generation")
+
+ while not operation.done:
+ elapsed_time = time.time() - start_time
+
+ if elapsed_time > max_wait_time:
+ self._log(f"Maximum wait time ({max_wait_time}s) exceeded")
+ return None
+
+ self._log(f"Still processing... ({elapsed_time:.1f}s elapsed)")
+ time.sleep(polling_interval)
+
+ # Refresh operation status
+ try:
+ operation = client.operations.get(operation)
+ except Exception as e:
+ self._log(f"Error checking operation status: {str(e)}")
+ time.sleep(polling_interval)
+
+ elapsed_time = time.time() - start_time
+ self._log(f"Video generation completed after {elapsed_time:.1f} seconds")
+ return operation
+
+ except Exception as e:
+ self._log(f"Error during polling: {str(e)}")
+ return None
+
+ def generate_video(self, prompt: str, service_account_json: str, model: str,
+ aspect_ratio: str = "16:9", resolution: str = "720p",
+ max_retries: int = 3, polling_interval: int = 10,
+ max_wait_time: int = 360, negative_prompt: str = "",
+ seed: int = 0, reference_image=None,
+ enable_person_generation: bool = True):
+ """Generate video using VEO 3 API"""
+
+ # Reset log messages
+ self.log_messages = []
+
+ try:
+ # Validate service account JSON file
+ if not service_account_json:
+ error_message = "Error: No service account JSON file provided."
+ self._log(error_message)
+ error_frame = self._create_error_frame("Service account required")
+ return (error_frame, "", error_message)
+
+ # Build full path to service account JSON
+ script_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ json_path = os.path.join(script_dir, service_account_json)
+
+ if not os.path.exists(json_path):
+ error_message = f"Error: Service account JSON file not found at {json_path}"
+ self._log(error_message)
+ error_frame = self._create_error_frame("JSON file not found")
+ return (error_frame, "", error_message)
+
+ # Validate prompt
+ if not prompt or len(prompt.strip()) == 0:
+ error_message = "Error: No prompt provided. Please enter a video generation prompt."
+ self._log(error_message)
+ error_frame = self._create_error_frame("Prompt required")
+ return (error_frame, "", error_message)
+
+ # Validate resolution for aspect ratio
+ if resolution == "1080p" and aspect_ratio != "16:9":
+ self._log("Warning: 1080p is only available for 16:9 aspect ratio. Defaulting to 720p.")
+ resolution = "720p"
+
+ # Load credentials from service account JSON
+ self._log(f"Loading service account credentials from: {json_path}")
+
+ # Read the JSON file to get project_id
+ with open(json_path, 'r') as f:
+ service_account_info = json.load(f)
+ project_id = service_account_info.get('project_id')
+
+ if not project_id:
+ error_message = "Error: No project_id found in service account JSON"
+ self._log(error_message)
+ error_frame = self._create_error_frame("Missing project_id")
+ return (error_frame, "", error_message)
+
+ credentials = service_account.Credentials.from_service_account_file(
+ json_path,
+ scopes=['https://www.googleapis.com/auth/cloud-platform']
+ )
+
+ # Initialize client with Vertex AI
+ client = genai.Client(
+ vertexai=True,
+ project=project_id,
+ location='us-central1',
+ credentials=credentials
+ )
+ self._log(f"Gemini client initialized with Vertex AI (project: {project_id})")
+
+ # Store credentials for later use in downloads
+ self._credentials = credentials
+
+ # Process reference image if provided
+ image_for_api = None
+ if reference_image is not None:
+ pil_reference = self._process_tensor_to_pil(reference_image, "Reference Image")
+ if pil_reference:
+ # Prepare image for Vertex AI
+ image_for_api = self._prepare_image_for_api(pil_reference)
+ if not image_for_api:
+ error_message = "Failed to prepare reference image"
+ self._log(error_message)
+ error_frame = self._create_error_frame(error_message)
+ return (error_frame, "", error_message)
+
+ # Build generation config
+ # Start with None and only add if basic call fails
+ gen_config = None
+
+ self._log(f"Requested aspect ratio: {aspect_ratio}")
+ self._log(f"Requested resolution: {resolution}")
+ if negative_prompt:
+ self._log(f"Negative prompt: {negative_prompt[:100]}...")
+ if seed > 0:
+ self._log(f"Note: Seed {seed} provided")
+ self._log(f"Person generation: {'enabled' if enable_person_generation else 'disabled'}")
+
+ # Make initial API call
+ self._log("Initiating video generation...")
+ operation = self._call_veo_api(
+ client=client,
+ model=model,
+ prompt=prompt,
+ config=gen_config,
+ reference_image=image_for_api,
+ max_retries=max_retries
+ )
+
+ if operation is None:
+ error_message = "Failed to initiate video generation"
+ self._log(error_message)
+ error_frame = self._create_error_frame(error_message)
+ return (error_frame, "", error_message)
+
+ self._log(f"Operation started, waiting for completion...")
+
+ # Poll for completion
+ completed_operation = self._poll_video_generation(
+ client=client,
+ operation=operation,
+ polling_interval=polling_interval,
+ max_wait_time=max_wait_time
+ )
+
+ if completed_operation is None:
+ error_message = "Video generation timed out or failed"
+ self._log(error_message)
+ error_frame = self._create_error_frame(error_message)
+ return (error_frame, "", error_message)
+
+ # Extract video from completed operation
+ video_file = self._extract_video_from_operation(completed_operation)
+
+ if not video_file:
+ error_message = "No video found in completed operation"
+ self._log(error_message)
+ error_frame = self._create_error_frame(error_message)
+ return (error_frame, "", error_message)
+
+ return self._process_video_result(client, video_file)
+
+ except Exception as e:
+ error_message = f"Error during video generation: {str(e)}"
+ self._log(error_message)
+ traceback.print_exc()
+
+ error_frame = self._create_error_frame(f"Error: {str(e)}")
+ full_text = "## Processing Log\n" + "\n".join(self.log_messages) + "\n\n## Error\n" + error_message
+
+ return (error_frame, "", full_text)
+
+ def _extract_video_from_operation(self, operation) -> Optional[any]:
+ """Extract video file object from completed operation"""
+ try:
+ # Try multiple possible structures
+
+ # Try operation.result first
+ if hasattr(operation, 'result') and operation.result:
+ self._log(f"Found result attribute")
+ self._log(f"Result type: {type(operation.result)}")
+ self._log(f"Result attributes: {dir(operation.result)}")
+
+ # Check for generated_videos in result
+ if hasattr(operation.result, 'generated_videos') and operation.result.generated_videos:
+ if len(operation.result.generated_videos) > 0:
+ generated_video = operation.result.generated_videos[0]
+ self._log(f"Generated video type: {type(generated_video)}")
+ self._log(f"Generated video attributes: {dir(generated_video)}")
+ if hasattr(generated_video, 'video'):
+ self._log(f"Found video file object")
+ return generated_video.video
+
+ # Maybe the result IS the video
+ return operation.result
+
+ # Try operation.response
+ if hasattr(operation, 'response') and operation.response:
+ if hasattr(operation.response, 'generated_videos') and operation.response.generated_videos:
+ if len(operation.response.generated_videos) > 0:
+ generated_video = operation.response.generated_videos[0]
+ if hasattr(generated_video, 'video'):
+ self._log(f"Found video file object in response")
+ return generated_video.video
+
+ self._log("Could not find video in operation structure")
+ self._log(f"Operation type: {type(operation)}")
+
+ return None
+
+ except Exception as e:
+ self._log(f"Error extracting video from operation: {str(e)}")
+ traceback.print_exc()
+ return None
+
+ def _process_video_result(self, client, video_file) -> Tuple:
+ """Download and process the generated video"""
+ try:
+ self._log(f"Processing video result")
+ self._log(f"Video file type: {type(video_file)}")
+
+ # Download video file using the client
+ temp_file = os.path.join(
+ tempfile.gettempdir(),
+ f"veo3_video_{int(time.time())}.mp4"
+ )
+
+ self._log(f"Attempting to save video to: {temp_file}")
+
+ # Check if video_bytes is available (Vertex AI)
+ if hasattr(video_file, 'video_bytes') and video_file.video_bytes:
+ self._log(f"Using video_bytes from Video object")
+
+ video_data = video_file.video_bytes
+ self._log(f"video_bytes size: {len(video_data)} bytes")
+
+ # Check if data is base64 encoded
+ # Raw MP4 files start with specific magic bytes
+ # MP4/M4V: 0x66747970 ('ftyp') at offset 4
+ # Base64 encoded data will be ASCII/UTF-8 text
+ is_base64 = False
+ try:
+ if isinstance(video_data, bytes):
+ # Check first 20 bytes
+ test_header = video_data[:20]
+ self._log(f"Video data header (hex): {test_header.hex()}")
+
+ # Try to decode as ASCII - base64 is ASCII
+ try:
+ test_str = test_header.decode('ascii')
+ # Check if it looks like base64 (no control chars, valid base64 chars)
+ # Common base64 patterns for video might start with various chars
+ # But we can check if it's printable ASCII which binary MP4 is not
+ if all(c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r' for c in test_str):
+ is_base64 = True
+ self._log(f"Detected base64-encoded video data")
+ except UnicodeDecodeError:
+ # Binary data, not base64
+ self._log(f"Video data is binary (not base64)")
+ pass
+ except Exception as e:
+ self._log(f"Error checking video data format: {str(e)}")
+
+ # Decode base64 if needed
+ if is_base64:
+ try:
+ original_size = len(video_data)
+ video_data = base64.b64decode(video_data)
+ self._log(f"Decoded base64 video data: {original_size} -> {len(video_data)} bytes")
+
+ # Verify it's now a valid video file
+ video_header = video_data[:20] if len(video_data) >= 20 else video_data
+ self._log(f"Decoded video header (hex): {video_header.hex()}")
+ except Exception as e:
+ self._log(f"Failed to decode base64 video data: {str(e)}")
+ traceback.print_exc()
+ return self._create_error_frame(f"Base64 decode error: {str(e)}"), "", str(e)
+
+ # Write the video data to file
+ with open(temp_file, 'wb') as f:
+ f.write(video_data)
+
+ file_size = os.path.getsize(temp_file)
+ self._log(f"Video saved: {file_size} bytes")
+
+ # Verify the file is a valid MP4
+ with open(temp_file, 'rb') as f:
+ file_header = f.read(20)
+ self._log(f"Saved file header (hex): {file_header.hex()}")
+ # Check for MP4 signature (ftyp at offset 4-7)
+ if len(file_header) >= 8:
+ ftyp_check = file_header[4:8]
+ if ftyp_check == b'ftyp':
+ self._log(f"Verified valid MP4 file signature")
+ else:
+ self._log(f"WARNING: File may not be a valid MP4 (ftyp signature not found)")
+ else:
+ self._log(f"WARNING: File too small to verify MP4 signature")
+
+ # Otherwise try using the URI (Google AI API)
+ elif hasattr(video_file, 'uri') and video_file.uri:
+ self._log(f"Attempting to download from URI")
+ # Extract file ID from URI
+ # URI format: https://generativelanguage.googleapis.com/v1beta/files/{file_id}:download?alt=media
+ try:
+ file_id_match = video_file.uri.split('/files/')
+ if len(file_id_match) > 1:
+ file_id = file_id_match[1].split(':')[0]
+ self._log(f"Extracted file ID: {file_id}")
+
+ # Try to download using the file ID with authenticated request
+ try:
+ # Refresh credentials if needed
+ if not self._credentials.valid:
+ self._credentials.refresh(Request())
+
+ # Get the access token from service account credentials
+ download_url = f"https://generativelanguage.googleapis.com/v1beta/files/{file_id}"
+
+ headers = {
+ 'Authorization': f'Bearer {self._credentials.token}'
+ }
+
+ self._log(f"Downloading from: {download_url}")
+
+ response = requests.get(download_url, headers=headers)
+ response.raise_for_status()
+
+ # Get the actual download URL from the response
+ file_info = response.json()
+ self._log(f"File info: {file_info}")
+
+ # Check if file is still processing
+ if file_info.get('state') == 'PROCESSING':
+ self._log(f"File is still processing, waiting for it to be ready...")
+ max_file_wait = 60 # Wait up to 60 seconds for file processing
+ file_wait_start = time.time()
+
+ while file_info.get('state') == 'PROCESSING':
+ if time.time() - file_wait_start > max_file_wait:
+ self._log("File processing timeout")
+ return self._create_error_frame("File processing timeout"), "", "Timeout"
+
+ time.sleep(2)
+ response = requests.get(download_url, headers=headers)
+ response.raise_for_status()
+ file_info = response.json()
+ self._log(f"File state: {file_info.get('state')}")
+
+ self._log(f"File is ready, state: {file_info.get('state')}")
+
+ # Now download the actual video
+ if 'downloadUri' in file_info:
+ video_uri = file_info['downloadUri']
+ self._log(f"Downloading video from downloadUri: {video_uri}")
+
+ video_response = requests.get(video_uri, headers=headers, stream=True)
+ video_response.raise_for_status()
+
+ with open(temp_file, 'wb') as f:
+ for chunk in video_response.iter_content(chunk_size=8192):
+ f.write(chunk)
+
+ file_size = os.path.getsize(temp_file)
+ self._log(f"Video saved: {file_size} bytes")
+ elif 'uri' in file_info:
+ video_uri = file_info['uri']
+ self._log(f"Downloading video from: {video_uri}")
+
+ video_response = requests.get(video_uri, headers=headers, stream=True)
+ video_response.raise_for_status()
+
+ with open(temp_file, 'wb') as f:
+ for chunk in video_response.iter_content(chunk_size=8192):
+ f.write(chunk)
+
+ file_size = os.path.getsize(temp_file)
+ self._log(f"Video saved: {file_size} bytes")
+ else:
+ self._log("No URI in file info")
+ return self._create_error_frame("No download URI"), "", "No URI"
+
+ except Exception as e:
+ self._log(f"Authenticated download failed: {e}")
+ traceback.print_exc()
+ raise
+ except Exception as e:
+ self._log(f"URI download failed: {e}")
+ traceback.print_exc()
+ return self._create_error_frame(f"Download error: {str(e)}"), "", str(e)
+ else:
+ self._log("No video_bytes or URI found in video object")
+ return self._create_error_frame("No video data found"), "", "No video data"
+
+ video_path = temp_file
+
+ # Extract frames
+ frames = self._extract_frames_from_video(video_path)
+
+ if not frames or len(frames) == 0:
+ error_message = "Failed to extract frames from video"
+ self._log(error_message)
+ error_frame = self._create_error_frame(error_message)
+ return (error_frame, "", error_message)
+
+ # Clean up temp file
+ try:
+ os.remove(video_path)
+ self._log("Temporary video file cleaned up")
+ except:
+ pass
+
+ # Stack frames into a batch tensor [B, H, W, C]
+ frames_batch = torch.stack(frames, dim=0)
+
+ # Prepare response text
+ response_text = "## Video Generation Successful\n"
+ response_text += f"Video saved to: {video_path}\n"
+ response_text += f"Total frames extracted: {len(frames)}\n"
+ response_text += f"Batch shape: {frames_batch.shape}\n"
+ response_text += "\n## Processing Log\n" + "\n".join(self.log_messages)
+
+ self._log(f"Successfully processed video with {len(frames)} frames")
+
+ return (frames_batch, video_path, response_text)
+
+ except Exception as e:
+ error_message = f"Error processing video result: {str(e)}"
+ self._log(error_message)
+ traceback.print_exc()
+ error_frame = self._create_error_frame(error_message)
+ return (error_frame, "", error_message)
diff --git a/comfyui_fill-nodes/nodes/ai/__init__.py b/comfyui_fill-nodes/nodes/ai/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..85d9b4984fdac75128a83e3633c8f6e307b718e2
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ai/__init__.py
@@ -0,0 +1 @@
+"""Fill-Nodes Category: Ai"""
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_GPTImage2_Edit.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_GPTImage2_Edit.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f340fa092ccf694e4e0e76b15f40aa6bbc65d5a3
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_GPTImage2_Edit.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Gemini_ImageEdit.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Gemini_ImageEdit.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d6f9ad59ea83873837eea222a4550164c9b6411a
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Gemini_ImageEdit.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Kling_AIAvatar.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Kling_AIAvatar.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0ae95a296d37eb5a513077ec00c3eb9382eef1e0
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Kling_AIAvatar.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Kontext.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Kontext.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e0abcc90f1502067aded6378e02422be1903495
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Kontext.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Pixverse.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Pixverse.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ef56c62cec1d7cc740fe015f648928134f6ca351
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Pixverse.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Pixverse_LipSync.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Pixverse_LipSync.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d1ed7fcb53b4222d55902f2b68a4eba601f2248f
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Pixverse_LipSync.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Pixverse_Transition.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Pixverse_Transition.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b5b3011f6d3c565ecf67a3ad9bc58326b48e3c73
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Pixverse_Transition.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_SeedVR_Upscale.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_SeedVR_Upscale.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..56a7c1dfacaf5d7c563b9e50d4c23dbae6c8e5f6
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_SeedVR_Upscale.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Seedance_i2v.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Seedance_i2v.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9102966977be19d28463e2b174fc189830353171
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Seedance_i2v.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Seedream_Edit.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Seedream_Edit.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8fc322c02b37aac833cbf87f191b6adbe4a1473d
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Seedream_Edit.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Sora.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Sora.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..028e463d947dc111712b6816c5f4fd84ea243e72
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Fal_Sora.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/FL_GeminiImageEditor.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_GeminiImageEditor.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..796788ea046db985a77b6bed4e4513a8742e0178
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_GeminiImageEditor.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/FL_GeminiImageGenADV.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_GeminiImageGenADV.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2e9ff0d9b42ba79d22aae2411e36548283067d36
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_GeminiImageGenADV.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/FL_GeminiTextAPI.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_GeminiTextAPI.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f580579cb0439a0c0bcbb8f36b54f976cea422d5
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_GeminiTextAPI.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/FL_GeminiVideoCaptioner.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_GeminiVideoCaptioner.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1ef8c4bbdf0fb0a780ac1d8c2ceedf2ffcbc59e3
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_GeminiVideoCaptioner.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Hedra_API.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Hedra_API.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f43a71cb238750b36c00d20eb0e09cf31d3cce1d
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_Hedra_API.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/FL_PixVerseAPI.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_PixVerseAPI.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d51669963d7cb5782491c0a86bdfb70ed208c7e2
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_PixVerseAPI.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/FL_RunwayAct2.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_RunwayAct2.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..acab5dbea11446b4de401be35216bb0ba22b60cf
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_RunwayAct2.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/FL_RunwayImageAPI.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_RunwayImageAPI.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a76190df92acc6576e8ea2ffcc683d61c69422a9
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_RunwayImageAPI.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/FL_VertexGemini25FlashImage.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_VertexGemini25FlashImage.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9f156e87234df0b3469a092b52a7a04ee7708473
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_VertexGemini25FlashImage.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/FL_VertexVeo3.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_VertexVeo3.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dee9d968ab7b7cfca1c2845f6fec4c46fb9e2eb6
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/FL_VertexVeo3.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ai/__pycache__/__init__.cpython-310.pyc b/comfyui_fill-nodes/nodes/ai/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ff568d0da2dfb7253201485cfc444b2e9e60c507
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ai/__pycache__/__init__.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/api_tools/FL_API_Base64_ImageLoader.py b/comfyui_fill-nodes/nodes/api_tools/FL_API_Base64_ImageLoader.py
new file mode 100644
index 0000000000000000000000000000000000000000..aaf6f3b9e709f74531c7fc0d55e344fb973006a3
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/api_tools/FL_API_Base64_ImageLoader.py
@@ -0,0 +1,113 @@
+import torch
+import base64
+import numpy as np
+from PIL import Image
+import io
+import re
+
+
+class FL_API_Base64_ImageLoader:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "base64_string": ("STRING", {"default": "", "multiline": True}),
+ "job_id": ("STRING", {"default": ""}),
+ "user_id": ("STRING", {"default": ""}), # Added user_id field
+ "category": ("STRING", {"default": ""}),
+ },
+ "optional": {
+ "resize_width": ("INT", {"default": 0, "min": 0, "max": 8192, "step": 8}),
+ "resize_height": ("INT", {"default": 0, "min": 0, "max": 8192, "step": 8}),
+ "maintain_aspect_ratio": ("BOOLEAN", {"default": True}),
+ "auto_clean_base64": ("BOOLEAN", {"default": True}),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE", "INT", "INT", "STRING", "STRING", "STRING") # Added STRING for user_id
+ RETURN_NAMES = ("image", "width", "height", "job_id", "user_id", "category") # Added user_id
+ FUNCTION = "load_base64_image"
+ CATEGORY = "🏵️Fill Nodes/API Tools"
+
+ def clean_base64_string(self, base64_string: str) -> str:
+ """Remove whitespace, newlines, and data URL prefixes from base64 string"""
+ # Remove whitespace and newlines
+ base64_string = re.sub(r'\s+', '', base64_string)
+ # Remove data URL prefix if present
+ if "base64," in base64_string:
+ base64_string = base64_string.split("base64,")[1]
+ return base64_string
+
+ def calculate_new_dimensions(self, original_width, original_height, target_width, target_height, maintain_aspect):
+ """Calculate new dimensions based on resize parameters"""
+ if target_width == 0 and target_height == 0:
+ return original_width, original_height
+
+ if maintain_aspect:
+ if target_width == 0:
+ ratio = target_height / original_height
+ return int(original_width * ratio), target_height
+ elif target_height == 0:
+ ratio = target_width / original_width
+ return target_width, int(original_height * ratio)
+ else:
+ # Use the smaller ratio to ensure image fits within specified dimensions
+ ratio = min(target_width / original_width, target_height / original_height)
+ return int(original_width * ratio), int(original_height * ratio)
+ else:
+ return (target_width if target_width != 0 else original_width,
+ target_height if target_height != 0 else original_height)
+
+ def load_base64_image(self,
+ base64_string: str,
+ job_id: str,
+ user_id: str, # Added user_id parameter
+ category: str,
+ resize_width: int = 0,
+ resize_height: int = 0,
+ maintain_aspect_ratio: bool = True,
+ auto_clean_base64: bool = True) -> tuple:
+ try:
+ # Clean base64 string if enabled
+ if auto_clean_base64:
+ base64_string = self.clean_base64_string(base64_string)
+
+ # Decode base64 string
+ image_data = base64.b64decode(base64_string)
+
+ # Open image
+ image = Image.open(io.BytesIO(image_data))
+
+ # Convert to RGB if necessary
+ if image.mode != 'RGB':
+ image = image.convert('RGB')
+
+ # Get original dimensions
+ original_width, original_height = image.size
+
+ # Calculate new dimensions if resize is requested
+ new_width, new_height = self.calculate_new_dimensions(
+ original_width, original_height,
+ resize_width, resize_height,
+ maintain_aspect_ratio
+ )
+
+ # Resize if dimensions changed
+ if (new_width, new_height) != (original_width, original_height):
+ image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
+
+ # Convert to numpy array and normalize
+ image_array = np.array(image).astype(np.float32) / 255.0
+
+ # Reshape to ComfyUI's expected format [batch, height, width, channels]
+ image_tensor = torch.from_numpy(image_array).unsqueeze(0)
+
+ return (image_tensor, new_width, new_height, job_id, user_id, category) # Added user_id to return tuple
+
+ except Exception as e:
+ raise ValueError(f"Error loading base64 image: {str(e)}")
+
+ @classmethod
+ def IS_CHANGED(cls, base64_string, job_id, user_id, category, resize_width, resize_height, maintain_aspect_ratio,
+ auto_clean_base64): # Added user_id to IS_CHANGED
+ return float("NaN")
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/api_tools/FL_API_ImageSaver.py b/comfyui_fill-nodes/nodes/api_tools/FL_API_ImageSaver.py
new file mode 100644
index 0000000000000000000000000000000000000000..298b912394511ac0c4ecde6e6ee049f8bd82fb7a
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/api_tools/FL_API_ImageSaver.py
@@ -0,0 +1,83 @@
+import os
+import torch
+from PIL import Image
+import numpy as np
+
+class FL_API_ImageSaver:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "job_id": ("STRING",),
+ "user_id": ("STRING",), # Added user_id input
+ "category": ("STRING",),
+ "base_output_dir": ("STRING", {"default": "/absolute/path/to/output"}),
+ "image_format": ("STRING", {
+ "default": "png",
+ "choices": ["png", "jpg", "jpeg", "webp"],
+ }),
+ "image_quality": ("INT", {
+ "default": 100,
+ "min": 1,
+ "max": 100,
+ "step": 1,
+ }),
+ },
+ }
+
+ RETURN_TYPES = ("STRING", "STRING", "STRING", "STRING") # Added STRING for user_id
+ RETURN_NAMES = ("saved_path", "job_id", "user_id", "category") # Added user_id
+ FUNCTION = "save_categorized_image"
+ CATEGORY = "🏵️Fill Nodes/API Tools"
+ OUTPUT_NODE = True
+
+ def save_categorized_image(self,
+ image: torch.Tensor,
+ job_id: str,
+ user_id: str, # Added user_id parameter
+ category: str,
+ base_output_dir: str,
+ image_format: str = "png",
+ image_quality: int = 100) -> tuple:
+ try:
+ # Ensure base directory exists
+ if not os.path.exists(base_output_dir):
+ os.makedirs(base_output_dir)
+
+ # Create category subdirectory
+ category_dir = os.path.join(base_output_dir, category)
+ if not os.path.exists(category_dir):
+ os.makedirs(category_dir)
+
+ # Create user subdirectory inside category directory
+ user_dir = os.path.join(category_dir, user_id)
+ if not os.path.exists(user_dir):
+ os.makedirs(user_dir)
+
+ # Prepare image filename
+ filename = f"{job_id}.{image_format}"
+ # Save in user directory instead of category directory
+ full_path = os.path.join(user_dir, filename)
+
+ # Convert tensor to PIL Image
+ i = 255. * image.cpu().numpy().squeeze()
+ img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
+
+ # Save image with appropriate format and quality
+ if image_format.lower() in ['jpg', 'jpeg']:
+ img.save(full_path, 'JPEG', quality=image_quality)
+ elif image_format.lower() == 'webp':
+ img.save(full_path, 'WEBP', quality=image_quality)
+ else: # PNG
+ img.save(full_path, 'PNG')
+
+ print(f"Image saved successfully: {full_path}")
+ return (full_path, job_id, user_id, category) # Added user_id to return tuple
+
+ except Exception as e:
+ raise ValueError(f"Error saving image: {str(e)}")
+
+ @classmethod
+ def IS_CHANGED(cls, image, job_id, user_id, category, base_output_dir, image_format, image_quality): # Added user_id
+ return float("NaN")
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/api_tools/__init__.py b/comfyui_fill-nodes/nodes/api_tools/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc0b0e1b98802898c1bd78c71b84c6427ed7ca73
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/api_tools/__init__.py
@@ -0,0 +1 @@
+"""Fill-Nodes Category: Api_Tools"""
diff --git a/comfyui_fill-nodes/nodes/api_tools/__pycache__/FL_API_Base64_ImageLoader.cpython-310.pyc b/comfyui_fill-nodes/nodes/api_tools/__pycache__/FL_API_Base64_ImageLoader.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a2067b8ca11a3e07cf0ee6fb78681c26dde9820f
Binary files /dev/null and b/comfyui_fill-nodes/nodes/api_tools/__pycache__/FL_API_Base64_ImageLoader.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/api_tools/__pycache__/FL_API_ImageSaver.cpython-310.pyc b/comfyui_fill-nodes/nodes/api_tools/__pycache__/FL_API_ImageSaver.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..532fc613d40bef371e2f2bacf6c7b9878ce81d76
Binary files /dev/null and b/comfyui_fill-nodes/nodes/api_tools/__pycache__/FL_API_ImageSaver.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/api_tools/__pycache__/__init__.cpython-310.pyc b/comfyui_fill-nodes/nodes/api_tools/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..61bf61987d8ef8d89a54f3a13163eb374e6b30d2
Binary files /dev/null and b/comfyui_fill-nodes/nodes/api_tools/__pycache__/__init__.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/audio/FL_AudioFrameCalculator.py b/comfyui_fill-nodes/nodes/audio/FL_AudioFrameCalculator.py
new file mode 100644
index 0000000000000000000000000000000000000000..31801d8b9ffa866d64ec361ec029fe62605d0b8a
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/audio/FL_AudioFrameCalculator.py
@@ -0,0 +1,25 @@
+import math
+
+
+class FL_AudioFrameCalculator:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "audio": ("AUDIO",),
+ "fps": ("FLOAT", {"default": 24.0, "min": 1.0, "max": 120.0, "step": 0.1}),
+ },
+ }
+
+ RETURN_TYPES = ("INT",)
+ RETURN_NAMES = ("frame_count",)
+ FUNCTION = "calculate"
+ CATEGORY = "🏵️Fill Nodes/Audio"
+
+ def calculate(self, audio, fps):
+ waveform = audio['waveform']
+ sample_rate = audio['sample_rate']
+ num_samples = waveform.shape[-1]
+ duration = num_samples / sample_rate
+ frame_count = math.ceil(duration * fps)
+ return (frame_count,)
diff --git a/comfyui_fill-nodes/nodes/audio/FL_Audio_BPM_Analyzer.py b/comfyui_fill-nodes/nodes/audio/FL_Audio_BPM_Analyzer.py
new file mode 100644
index 0000000000000000000000000000000000000000..21cf56921d8e81664f497180a3e014bfadbf5cc2
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/audio/FL_Audio_BPM_Analyzer.py
@@ -0,0 +1,328 @@
+# FL_Audio_BPM_Analyzer: Analyze audio and detect all beats
+import torch
+import numpy as np
+from typing import Tuple, Dict, Any
+
+
+class FL_Audio_BPM_Analyzer:
+ """
+ A ComfyUI node for BPM and beat detection using Librosa.
+ Analyzes the entire audio once and outputs beat positions for use in segmentation.
+ """
+
+ RETURN_TYPES = ("AUDIO", "FLOAT", "STRING", "IMAGE")
+ RETURN_NAMES = ("audio", "bpm", "beat_positions", "visualization")
+ FUNCTION = "analyze_beats"
+ CATEGORY = "🏵️Fill Nodes/Audio"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "audio": ("AUDIO", {"description": "Input audio tensor"}),
+ },
+ "optional": {
+ "bpm_method": (["beat_intervals", "onset_strength"], {
+ "default": "beat_intervals",
+ "description": "BPM calculation: beat_intervals (accurate) or onset_strength (librosa default)"
+ }),
+ "half_time": ("BOOLEAN", {
+ "default": False,
+ "description": "Half the detected BPM (for songs detected at double-time)"
+ }),
+ "beat_offset_ms": ("INT", {
+ "default": 0,
+ "min": -1000,
+ "max": 1000,
+ "step": 1,
+ "description": "Shift all beat positions (in milliseconds, positive or negative)"
+ }),
+ }
+ }
+
+ def analyze_beats(self, audio: Dict[str, Any], bpm_method: str = "beat_intervals", half_time: bool = False, beat_offset_ms: int = 0) -> Tuple[Dict[str, Any], float, str, torch.Tensor]:
+ """
+ Analyze audio and detect all beats
+
+ Args:
+ audio: Input audio tensor dict with 'waveform' and 'sample_rate'
+ bpm_method: BPM calculation method ("beat_intervals" or "onset_strength")
+ half_time: Half the detected BPM (for songs detected at double-time)
+ beat_offset_ms: Offset in milliseconds to shift all beat positions (positive or negative)
+
+ Returns:
+ Tuple of (audio_passthrough, bpm_value, beat_positions_json, visualization_image)
+ """
+ print(f"\n{'='*60}")
+ print(f"[FL BPM Analyzer] DEBUG: Function called")
+ print(f"[FL BPM Analyzer] DEBUG: BPM method = {bpm_method}")
+ print(f"[FL BPM Analyzer] DEBUG: Audio input type = {type(audio)}")
+ print(f"{'='*60}\n")
+
+ try:
+ # Import librosa
+ try:
+ import librosa
+ print(f"[FL BPM Analyzer] DEBUG: Successfully imported librosa (version: {librosa.__version__})")
+ except ImportError as import_err:
+ error_msg = f"Error: librosa library not installed. Install with: pip install librosa standard-aifc standard-sunau. Details: {import_err}"
+ print(f"[FL BPM Analyzer] DEBUG: Import failed - {error_msg}")
+ return audio, 0.0, "[]", torch.zeros((1, 512, 512, 3), dtype=torch.float32)
+
+ # Validate audio input
+ if audio is None:
+ print(f"[FL BPM Analyzer] DEBUG: Audio is None!")
+ return audio, 0.0, "[]", torch.zeros((1, 512, 512, 3), dtype=torch.float32)
+
+ print(f"[FL BPM Analyzer] DEBUG: Audio dict keys: {audio.keys()}")
+
+ waveform = audio['waveform']
+ sample_rate = audio['sample_rate']
+
+ print(f"[FL BPM Analyzer] DEBUG: Waveform shape = {waveform.shape}")
+ print(f"[FL BPM Analyzer] DEBUG: Waveform dtype = {waveform.dtype}")
+ print(f"[FL BPM Analyzer] DEBUG: Sample rate = {sample_rate}")
+
+ # Convert waveform to numpy array and ensure proper format
+ print(f"[FL BPM Analyzer] DEBUG: Processing waveform for Librosa...")
+ if isinstance(waveform, torch.Tensor):
+ waveform_np = waveform.cpu().numpy()
+ else:
+ waveform_np = np.array(waveform)
+
+ # Librosa expects mono audio as 1D array
+ if len(waveform_np.shape) == 3: # [batch, channels, samples]
+ waveform_np = waveform_np.squeeze(0) # Remove batch dimension
+ print(f"[FL BPM Analyzer] DEBUG: Squeezed batch dimension")
+
+ if len(waveform_np.shape) == 2: # [channels, samples]
+ # Convert stereo to mono by averaging channels
+ waveform_np = np.mean(waveform_np, axis=0)
+ print(f"[FL BPM Analyzer] DEBUG: Converted stereo to mono")
+
+ # Ensure float32 format
+ if waveform_np.dtype != np.float32:
+ waveform_np = waveform_np.astype(np.float32)
+ print(f"[FL BPM Analyzer] DEBUG: Converted to float32")
+
+ print(f"[FL BPM Analyzer] DEBUG: Final waveform shape = {waveform_np.shape}")
+ print(f"[FL BPM Analyzer] DEBUG: Final waveform dtype = {waveform_np.dtype}")
+
+ # Detect tempo and beats using librosa
+ print(f"[FL BPM Analyzer] Running Librosa beat tracking...")
+
+ tempo, beat_frames = librosa.beat.beat_track(
+ y=waveform_np,
+ sr=sample_rate,
+ units='frames'
+ )
+
+ # Handle tempo output (can be array or scalar)
+ if isinstance(tempo, np.ndarray):
+ if len(tempo) > 0:
+ onset_strength_bpm = float(tempo[0])
+ else:
+ onset_strength_bpm = 0.0
+ else:
+ onset_strength_bpm = float(tempo)
+
+ # Convert beat frames to time
+ beat_times = librosa.frames_to_time(beat_frames, sr=sample_rate)
+
+ print(f"[FL BPM Analyzer] DEBUG: Number of beats detected (raw) = {len(beat_times)}")
+ print(f"[FL BPM Analyzer] DEBUG: Beat times (first 10) = {beat_times[:10].tolist()}")
+
+ # Calculate beat intervals and BPM from actual beats
+ if len(beat_times) > 1:
+ beat_intervals = np.diff(beat_times)
+ avg_interval = np.mean(beat_intervals)
+ median_interval = np.median(beat_intervals)
+
+ # Calculate BPM from beat intervals
+ beat_interval_bpm = 60.0 / avg_interval
+ median_bpm = 60.0 / median_interval
+
+ print(f"[FL BPM Analyzer] DEBUG: Onset strength BPM = {onset_strength_bpm:.2f}")
+ print(f"[FL BPM Analyzer] DEBUG: Beat interval BPM (median) = {median_bpm:.2f}")
+
+ # Choose BPM based on method
+ if bpm_method == "beat_intervals":
+ bpm = median_bpm
+ bpm_source = "beat_intervals_median"
+ else:
+ bpm = onset_strength_bpm
+ bpm_source = "onset_strength"
+
+ print(f"[FL BPM Analyzer] DEBUG: Using {bpm_source}: {bpm:.2f} BPM")
+ else:
+ bpm = onset_strength_bpm
+ bpm_source = "onset_strength"
+ beat_intervals = np.array([])
+ median_interval = 60.0 / bpm if bpm > 0 else 0.5
+
+ # Apply half-time if requested
+ if half_time:
+ print(f"[FL BPM Analyzer] DEBUG: Half-time enabled - doubling beat intervals")
+ bpm = bpm / 2.0
+ median_interval = median_interval * 2.0
+ # Keep every other beat
+ beat_times = beat_times[::2]
+ beat_frames = beat_frames[::2]
+ print(f"[FL BPM Analyzer] DEBUG: Half-time BPM = {bpm:.2f}")
+ print(f"[FL BPM Analyzer] DEBUG: Half-time beats = {len(beat_times)}")
+
+ # Fill in missing beats to cover entire song duration
+ audio_duration = len(waveform_np) / sample_rate
+ print(f"[FL BPM Analyzer] DEBUG: Audio duration = {audio_duration:.2f}s")
+
+ if len(beat_times) > 1:
+ # Calculate the beat interval to use for filling
+ fill_interval = median_interval
+
+ print(f"[FL BPM Analyzer] DEBUG: Using {fill_interval:.3f}s interval for beat filling")
+
+ # Fill backwards from first beat to start of song
+ filled_beats = list(beat_times)
+ current_time = beat_times[0] - fill_interval
+ while current_time > 0:
+ filled_beats.insert(0, current_time)
+ current_time -= fill_interval
+
+ print(f"[FL BPM Analyzer] DEBUG: Added {len(filled_beats) - len(beat_times)} beats before first detected beat")
+
+ # Fill forward from last beat to end of song
+ current_time = beat_times[-1] + fill_interval
+ while current_time < audio_duration:
+ filled_beats.append(current_time)
+ current_time += fill_interval
+
+ print(f"[FL BPM Analyzer] DEBUG: Added {len(filled_beats) - len(beat_times)} beats after last detected beat (total)")
+
+ # Fill gaps in the middle if any large gaps exist
+ filled_beats_array = np.array(filled_beats)
+ filled_beats_sorted = np.sort(filled_beats_array)
+
+ # Check for gaps larger than 2x the median interval
+ gaps = np.diff(filled_beats_sorted)
+ large_gaps = gaps > (fill_interval * 1.5)
+
+ if np.any(large_gaps):
+ print(f"[FL BPM Analyzer] DEBUG: Found {np.sum(large_gaps)} large gaps, filling...")
+ final_beats = []
+ for i, beat in enumerate(filled_beats_sorted[:-1]):
+ final_beats.append(beat)
+ if large_gaps[i]:
+ # Fill this gap
+ gap_start = beat
+ gap_end = filled_beats_sorted[i + 1]
+ num_beats_needed = int((gap_end - gap_start) / fill_interval)
+ for j in range(1, num_beats_needed):
+ final_beats.append(gap_start + j * fill_interval)
+ final_beats.append(filled_beats_sorted[-1])
+ beat_times = np.array(final_beats)
+ else:
+ beat_times = filled_beats_sorted
+
+ print(f"[FL BPM Analyzer] DEBUG: Total beats after filling = {len(beat_times)}")
+ print(f"[FL BPM Analyzer] DEBUG: Coverage: {beat_times[0]:.2f}s to {beat_times[-1]:.2f}s (audio ends at {audio_duration:.2f}s)")
+ else:
+ print(f"[FL BPM Analyzer] WARNING: Not enough beats detected to fill entire song")
+
+ # Apply beat offset if specified
+ if beat_offset_ms != 0:
+ beat_offset_seconds = beat_offset_ms / 1000.0
+ beat_times = beat_times + beat_offset_seconds
+ print(f"[FL BPM Analyzer] DEBUG: Applied {beat_offset_ms}ms ({beat_offset_seconds:.3f}s) offset to all beats")
+ # Clamp to valid range [0, audio_duration]
+ beat_times = np.clip(beat_times, 0, audio_duration)
+
+ # Format beat positions as JSON
+ import json
+ beat_positions_dict = {
+ "bpm": float(bpm),
+ "bpm_source": bpm_source,
+ "beat_times": beat_times.tolist(),
+ "beat_frames": beat_frames.tolist(),
+ "num_beats": len(beat_times),
+ "sample_rate": int(sample_rate),
+ "audio_duration": float(len(waveform_np) / sample_rate)
+ }
+
+ beat_positions_json = json.dumps(beat_positions_dict, indent=2)
+ print(f"[FL BPM Analyzer] DEBUG: Beat positions JSON length = {len(beat_positions_json)} chars")
+
+ # Generate matplotlib visualization
+ print(f"[FL BPM Analyzer] DEBUG: Generating visualization...")
+ try:
+ import matplotlib.pyplot as plt
+ import matplotlib
+ matplotlib.use('Agg')
+ from io import BytesIO
+ from PIL import Image
+
+ # Calculate audio duration and figure width
+ audio_duration = len(waveform_np) / sample_rate
+ fig_width = max(20, min(100, audio_duration * 0.5))
+
+ fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(fig_width, 8))
+
+ # Compute onset strength for visualization
+ onset_env = librosa.onset.onset_strength(y=waveform_np, sr=sample_rate)
+ times = librosa.times_like(onset_env, sr=sample_rate)
+
+ # Plot 1: Waveform with beat markers
+ ax1.plot(np.arange(len(waveform_np)) / sample_rate, waveform_np, alpha=0.6, linewidth=0.5, label='Waveform')
+ ax1.vlines(beat_times, -1, 1, color='r', alpha=0.8, linestyle='--', linewidth=2, label='Detected Beats')
+ ax1.set_xlim(0, audio_duration)
+ ax1.set_xlabel('Time (seconds)')
+ ax1.set_ylabel('Amplitude')
+ ax1.set_title(f'Beat Detection: {bpm:.2f} BPM - {len(beat_times)} beats detected ({audio_duration:.1f}s total)')
+ ax1.legend(loc='upper right')
+ ax1.grid(True, alpha=0.3)
+
+ # Plot 2: Onset strength envelope with beat markers
+ ax2.plot(times, onset_env, label='Onset Strength', color='blue', linewidth=1.5)
+ ax2.vlines(beat_times, 0, onset_env.max(), color='r', alpha=0.8, linestyle='--', linewidth=2, label='Detected Beats')
+ ax2.set_xlim(0, audio_duration)
+ ax2.set_xlabel('Time (seconds)')
+ ax2.set_ylabel('Onset Strength')
+ ax2.set_title('Onset Strength Envelope')
+ ax2.legend(loc='upper right')
+ ax2.grid(True, alpha=0.3)
+
+ plt.tight_layout()
+
+ # Convert to image tensor
+ buf = BytesIO()
+ plt.savefig(buf, format='png', dpi=150, bbox_inches='tight')
+ buf.seek(0)
+ pil_image = Image.open(buf)
+ img_array = np.array(pil_image.convert('RGB')).astype(np.float32) / 255.0
+ img_tensor = torch.from_numpy(img_array).unsqueeze(0)
+
+ plt.close()
+ buf.close()
+
+ print(f"[FL BPM Analyzer] Visualization generated: {img_tensor.shape}")
+
+ except Exception as viz_error:
+ print(f"[FL BPM Analyzer] WARNING: Could not generate visualization: {viz_error}")
+ img_tensor = torch.zeros((1, 512, 512, 3), dtype=torch.float32)
+
+ print(f"\n{'='*60}")
+ print(f"[FL BPM Analyzer] Analysis complete!")
+ print(f"[FL BPM Analyzer] BPM: {bpm:.2f}")
+ print(f"[FL BPM Analyzer] Total beats: {len(beat_times)}")
+ print(f"[FL BPM Analyzer] Audio duration: {audio_duration:.2f}s")
+ print(f"{'='*60}\n")
+
+ return audio, float(bpm), beat_positions_json, img_tensor
+
+ except Exception as e:
+ error_msg = f"Error: {str(e)}"
+ print(f"\n{'='*60}")
+ print(f"[FL BPM Analyzer] ERROR: {error_msg}")
+ import traceback
+ traceback.print_exc()
+ print(f"{'='*60}\n")
+ return audio, 0.0, "[]", torch.zeros((1, 512, 512, 3), dtype=torch.float32)
diff --git a/comfyui_fill-nodes/nodes/audio/FL_Audio_Beat_Visualizer.py b/comfyui_fill-nodes/nodes/audio/FL_Audio_Beat_Visualizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1c0f0a5113eb567b0ce3237ec42dc8117542762
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/audio/FL_Audio_Beat_Visualizer.py
@@ -0,0 +1,202 @@
+# FL_Audio_Beat_Visualizer: Generate beat visualization frames from sequence JSON
+import torch
+import numpy as np
+from typing import Tuple
+
+
+class FL_Audio_Beat_Visualizer:
+ """
+ A ComfyUI node for generating beat visualization frames.
+ Creates frames that alternate between black and white on beat switches.
+ """
+
+ RETURN_TYPES = ("IMAGE",)
+ RETURN_NAMES = ("frames",)
+ FUNCTION = "generate_frames"
+ CATEGORY = "🏵️Fill Nodes/Audio"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "sequence_json": ("STRING", {"description": "Sequence JSON from FL_Audio_Music_Video_Sequencer"}),
+ },
+ "optional": {
+ "images": ("IMAGE", {"description": "Batch of images to cycle through on beats"}),
+ "use_black_white": ("BOOLEAN", {
+ "default": True,
+ "description": "Use black/white switching instead of images"
+ }),
+ "width": ("INT", {
+ "default": 512,
+ "min": 64,
+ "max": 4096,
+ "step": 8,
+ "description": "Frame width (images will be resized to this)"
+ }),
+ "height": ("INT", {
+ "default": 512,
+ "min": 64,
+ "max": 4096,
+ "step": 8,
+ "description": "Frame height (images will be resized to this)"
+ }),
+ "start_with_white": ("BOOLEAN", {
+ "default": False,
+ "description": "Start with white instead of black (only for black/white mode)"
+ }),
+ }
+ }
+
+ def generate_frames(
+ self,
+ sequence_json: str,
+ images: torch.Tensor = None,
+ use_black_white: bool = True,
+ width: int = 512,
+ height: int = 512,
+ start_with_white: bool = False
+ ) -> Tuple[torch.Tensor]:
+ """
+ Generate beat visualization frames
+
+ Args:
+ sequence_json: JSON string from FL_Audio_Music_Video_Sequencer
+ images: Optional batch of images to cycle through
+ use_black_white: Use black/white switching instead of images
+ width: Frame width in pixels
+ height: Frame height in pixels
+ start_with_white: Start with white instead of black
+
+ Returns:
+ Tuple containing tensor of frames (batch, height, width, channels)
+ """
+ print(f"\n{'='*60}")
+ print(f"[FL Audio Beat Visualizer] DEBUG: Function called")
+ print(f"[FL Audio Beat Visualizer] DEBUG: Use black/white mode = {use_black_white}")
+ print(f"[FL Audio Beat Visualizer] DEBUG: Frame size = {width}x{height}")
+ print(f"[FL Audio Beat Visualizer] DEBUG: Start with white = {start_with_white}")
+ if images is not None:
+ print(f"[FL Audio Beat Visualizer] DEBUG: Images batch shape = {images.shape}")
+ print(f"{'='*60}\n")
+
+ try:
+ # Parse sequence JSON
+ import json
+ try:
+ sequence_data = json.loads(sequence_json)
+ shots = sequence_data['shots']
+ metadata = sequence_data['metadata']
+ total_shots = len(shots)
+ total_frames = metadata['total_frames']
+
+ print(f"[FL Audio Beat Visualizer] DEBUG: Total shots = {total_shots}")
+ print(f"[FL Audio Beat Visualizer] DEBUG: Total frames = {total_frames}")
+
+ except (json.JSONDecodeError, KeyError) as e:
+ error_msg = f"Error parsing sequence JSON: {e}"
+ print(f"[FL Audio Beat Visualizer] ERROR: {error_msg}")
+ # Return single black frame on error
+ return (torch.zeros((1, height, width, 3), dtype=torch.float32),)
+
+ # Calculate expected memory usage
+ expected_memory_mb = (total_frames * height * width * 3 * 4) / (1024 * 1024)
+ print(f"\n[FL Audio Beat Visualizer] MEMORY DEBUG:")
+ print(f"[FL Audio Beat Visualizer] Total frames to generate: {total_frames}")
+ print(f"[FL Audio Beat Visualizer] Frame dimensions: {height}x{width}x3")
+ print(f"[FL Audio Beat Visualizer] Expected memory usage: {expected_memory_mb:.2f} MB")
+ print(f"[FL Audio Beat Visualizer] Data type: float32 (4 bytes per value)")
+
+ # Create frame buffer
+ frames = []
+
+ # Generate frames for each shot
+ if use_black_white:
+ # Black/white alternating mode
+ for shot_idx, shot in enumerate(shots):
+ frame_count = shot['frame_count']
+
+ # Determine color for this shot (alternate between black and white)
+ if start_with_white:
+ is_white = (shot_idx % 2 == 0)
+ else:
+ is_white = (shot_idx % 2 == 1)
+
+ # Create color value (0.0 for black, 1.0 for white)
+ color_value = 1.0 if is_white else 0.0
+
+ # Create frames for this shot
+ shot_frames = torch.full(
+ (frame_count, height, width, 3),
+ color_value,
+ dtype=torch.float32
+ )
+
+ frames.append(shot_frames)
+
+ print(f"[FL Audio Beat Visualizer] Shot {shot_idx}: {frame_count} frames, color={'white' if is_white else 'black'}")
+
+ else:
+ # Image cycling mode
+ if images is None:
+ print(f"[FL Audio Beat Visualizer] WARNING: use_black_white=False but no images provided, falling back to black frames")
+ for shot_idx, shot in enumerate(shots):
+ frame_count = shot['frame_count']
+ shot_frames = torch.zeros((frame_count, height, width, 3), dtype=torch.float32)
+ frames.append(shot_frames)
+ else:
+ num_images = images.shape[0]
+ original_height, original_width = images.shape[1], images.shape[2]
+ print(f"[FL Audio Beat Visualizer] DEBUG: Cycling through {num_images} images")
+ print(f"[FL Audio Beat Visualizer] DEBUG: Original image size: {original_width}x{original_height}")
+ print(f"[FL Audio Beat Visualizer] DEBUG: Resizing to: {width}x{height}")
+
+ # Resize images to target dimensions
+ import torch.nn.functional as F
+ # Permute from (batch, height, width, channels) to (batch, channels, height, width)
+ images_resized = images.permute(0, 3, 1, 2)
+ # Resize
+ images_resized = F.interpolate(images_resized, size=(height, width), mode='bilinear', align_corners=False)
+ # Permute back to (batch, height, width, channels)
+ images_resized = images_resized.permute(0, 2, 3, 1)
+
+ for shot_idx, shot in enumerate(shots):
+ frame_count = shot['frame_count']
+
+ # Cycle through images
+ image_idx = shot_idx % num_images
+ selected_image = images_resized[image_idx] # Shape: (height, width, channels)
+
+ # Repeat the selected image for all frames in this shot
+ shot_frames = selected_image.unsqueeze(0).repeat(frame_count, 1, 1, 1)
+
+ frames.append(shot_frames)
+
+ print(f"[FL Audio Beat Visualizer] Shot {shot_idx}: {frame_count} frames, using image {image_idx}")
+
+ # Concatenate all frames
+ all_frames = torch.cat(frames, dim=0)
+
+ # Calculate actual memory usage
+ actual_memory_mb = (all_frames.element_size() * all_frames.nelement()) / (1024 * 1024)
+
+ print(f"\n{'='*60}")
+ print(f"[FL Audio Beat Visualizer] Frame generation complete!")
+ print(f"[FL Audio Beat Visualizer] Total frames generated: {all_frames.shape[0]}")
+ print(f"[FL Audio Beat Visualizer] Frame shape: {all_frames.shape}")
+ print(f"[FL Audio Beat Visualizer] Frame dtype: {all_frames.dtype}")
+ print(f"[FL Audio Beat Visualizer] Actual tensor memory: {actual_memory_mb:.2f} MB")
+ print(f"[FL Audio Beat Visualizer] Element size: {all_frames.element_size()} bytes")
+ print(f"{'='*60}\n")
+
+ return (all_frames,)
+
+ except Exception as e:
+ error_msg = f"Error: {str(e)}"
+ print(f"\n{'='*60}")
+ print(f"[FL Audio Beat Visualizer] ERROR: {error_msg}")
+ import traceback
+ traceback.print_exc()
+ print(f"{'='*60}\n")
+ # Return single black frame on error
+ return (torch.zeros((1, height, width, 3), dtype=torch.float32),)
diff --git a/comfyui_fill-nodes/nodes/audio/FL_Audio_Crop.py b/comfyui_fill-nodes/nodes/audio/FL_Audio_Crop.py
new file mode 100644
index 0000000000000000000000000000000000000000..59c00ac231bc517d971113bb97b1a4c02f304ea2
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/audio/FL_Audio_Crop.py
@@ -0,0 +1,109 @@
+# FL_Audio_Crop: Crop/trim audio to specific start and end times
+import torch
+from typing import Tuple, Dict, Any
+
+
+class FL_Audio_Crop:
+ """
+ A ComfyUI node for cropping (trimming) audio to a specific start and end time.
+ """
+
+ RETURN_TYPES = ("AUDIO",)
+ RETURN_NAMES = ("audio",)
+ FUNCTION = "crop_audio"
+ CATEGORY = "🏵️Fill Nodes/Audio"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "audio": ("AUDIO", {"description": "Input audio tensor"}),
+ "start_time": ("STRING", {
+ "default": "0:00",
+ "description": "Start time (MM:SS or seconds)"
+ }),
+ "end_time": ("STRING", {
+ "default": "1:00",
+ "description": "End time (MM:SS or seconds)"
+ }),
+ }
+ }
+
+ def crop_audio(
+ self,
+ audio: Dict[str, Any],
+ start_time: str = "0:00",
+ end_time: str = "1:00"
+ ) -> Tuple[Dict[str, Any]]:
+ """
+ Crop audio to specific start and end times
+
+ Args:
+ audio: Input audio tensor dict with 'waveform' and 'sample_rate'
+ start_time: Start time as "MM:SS" or seconds
+ end_time: End time as "MM:SS" or seconds
+
+ Returns:
+ Tuple containing cropped audio dict
+ """
+ print(f"\n{'='*60}")
+ print(f"[FL Audio Crop] DEBUG: Function called")
+ print(f"[FL Audio Crop] DEBUG: Start time = {start_time}")
+ print(f"[FL Audio Crop] DEBUG: End time = {end_time}")
+ print(f"{'='*60}\n")
+
+ try:
+ waveform = audio['waveform']
+ sample_rate = audio['sample_rate']
+
+ # If no ":" in input, assume user is specifying seconds
+ if ":" not in start_time:
+ start_time = f"00:{start_time}"
+ if ":" not in end_time:
+ end_time = f"00:{end_time}"
+
+ # Parse start time
+ start_seconds = 60 * int(start_time.split(":")[0]) + int(start_time.split(":")[1])
+ start_frame = start_seconds * sample_rate
+
+ # Parse end time
+ end_seconds = 60 * int(end_time.split(":")[0]) + int(end_time.split(":")[1])
+ end_frame = end_seconds * sample_rate
+
+ # Clamp to valid range
+ total_frames = waveform.shape[-1]
+ start_frame = max(0, min(start_frame, total_frames - 1))
+ end_frame = max(0, min(end_frame, total_frames - 1))
+
+ if start_frame >= end_frame:
+ raise ValueError(
+ f"FL Audio Crop: Start time ({start_time}) must be less than end time ({end_time}) "
+ f"and be within the audio length."
+ )
+
+ # Crop waveform
+ cropped_waveform = waveform[..., start_frame:end_frame]
+
+ cropped_audio = {
+ 'waveform': cropped_waveform,
+ 'sample_rate': sample_rate
+ }
+
+ duration = (end_frame - start_frame) / sample_rate
+ print(f"\n{'='*60}")
+ print(f"[FL Audio Crop] Crop complete!")
+ print(f"[FL Audio Crop] Start: {start_time} ({start_frame} frames)")
+ print(f"[FL Audio Crop] End: {end_time} ({end_frame} frames)")
+ print(f"[FL Audio Crop] Duration: {duration:.2f}s")
+ print(f"{'='*60}\n")
+
+ return (cropped_audio,)
+
+ except Exception as e:
+ error_msg = f"Error: {str(e)}"
+ print(f"\n{'='*60}")
+ print(f"[FL Audio Crop] ERROR: {error_msg}")
+ import traceback
+ traceback.print_exc()
+ print(f"{'='*60}\n")
+ return (audio,)
diff --git a/comfyui_fill-nodes/nodes/audio/FL_Audio_Drum_Detector.py b/comfyui_fill-nodes/nodes/audio/FL_Audio_Drum_Detector.py
new file mode 100644
index 0000000000000000000000000000000000000000..be58b3e2caf88d520fd89dfdd6cda32829a7f678
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/audio/FL_Audio_Drum_Detector.py
@@ -0,0 +1,223 @@
+# FL_Audio_Drum_Detector: Detect kicks, snares, and hi-hats from audio
+import torch
+import numpy as np
+import json
+from typing import Tuple, Dict, Any
+
+
+class FL_Audio_Drum_Detector:
+ """
+ A ComfyUI node for detecting drum elements (kicks, snares, hi-hats) from audio.
+ Uses onset detection with frequency band analysis to classify drum types.
+ """
+
+ RETURN_TYPES = ("STRING",)
+ RETURN_NAMES = ("drum_times_json",)
+ FUNCTION = "detect_drums"
+ CATEGORY = "🏵️Fill Nodes/Audio"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "audio": ("AUDIO", {"description": "Input audio tensor (preferably drums stem)"}),
+ },
+ "optional": {
+ "kick_sensitivity": ("FLOAT", {
+ "default": 0.5,
+ "min": 0.0,
+ "max": 1.0,
+ "step": 0.05,
+ "description": "Kick detection sensitivity (lower = more sensitive)"
+ }),
+ "snare_sensitivity": ("FLOAT", {
+ "default": 0.5,
+ "min": 0.0,
+ "max": 1.0,
+ "step": 0.05,
+ "description": "Snare detection sensitivity (lower = more sensitive)"
+ }),
+ "hihat_sensitivity": ("FLOAT", {
+ "default": 0.5,
+ "min": 0.0,
+ "max": 1.0,
+ "step": 0.05,
+ "description": "Hi-hat detection sensitivity (lower = more sensitive)"
+ }),
+ }
+ }
+
+ def detect_drums(
+ self,
+ audio: Dict[str, Any],
+ kick_sensitivity: float = 0.5,
+ snare_sensitivity: float = 0.5,
+ hihat_sensitivity: float = 0.5
+ ) -> Tuple[str]:
+ """
+ Detect drum elements from audio
+
+ Args:
+ audio: Input audio tensor dict with 'waveform' and 'sample_rate'
+ kick_sensitivity: Kick detection threshold (0-1)
+ snare_sensitivity: Snare detection threshold (0-1)
+ hihat_sensitivity: Hi-hat detection threshold (0-1)
+
+ Returns:
+ Tuple containing JSON string with drum timestamps
+ """
+ print(f"\n{'='*60}")
+ print(f"[FL Audio Drum Detector] DEBUG: Function called")
+ print(f"[FL Audio Drum Detector] DEBUG: Kick sensitivity = {kick_sensitivity}")
+ print(f"[FL Audio Drum Detector] DEBUG: Snare sensitivity = {snare_sensitivity}")
+ print(f"[FL Audio Drum Detector] DEBUG: Hi-hat sensitivity = {hihat_sensitivity}")
+ print(f"{'='*60}\n")
+
+ try:
+ import librosa
+
+ waveform = audio['waveform']
+ sample_rate = audio['sample_rate']
+
+ # Convert to numpy and handle shape
+ if isinstance(waveform, torch.Tensor):
+ waveform_np = waveform.cpu().numpy()
+ else:
+ waveform_np = np.array(waveform)
+
+ # Convert to mono if needed
+ if len(waveform_np.shape) == 3:
+ waveform_np = waveform_np[0]
+ if len(waveform_np.shape) == 2 and waveform_np.shape[0] > 1:
+ waveform_np = waveform_np.mean(axis=0)
+ elif len(waveform_np.shape) == 2:
+ waveform_np = waveform_np[0]
+
+ print(f"[FL Audio Drum Detector] DEBUG: Waveform shape = {waveform_np.shape}")
+ print(f"[FL Audio Drum Detector] DEBUG: Sample rate = {sample_rate}")
+
+ # Detect onsets
+ print(f"[FL Audio Drum Detector] Detecting onsets...")
+ onset_env = librosa.onset.onset_strength(y=waveform_np, sr=sample_rate)
+ onset_frames = librosa.onset.onset_detect(
+ onset_envelope=onset_env,
+ sr=sample_rate,
+ units='frames'
+ )
+ onset_times = librosa.frames_to_time(onset_frames, sr=sample_rate)
+
+ print(f"[FL Audio Drum Detector] DEBUG: Total onsets detected = {len(onset_times)}")
+
+ # Frequency band analysis for classification
+ # More precise frequency ranges for drum separation
+ kick_times = []
+ snare_times = []
+ hihat_times = []
+
+ # Compute STFT for frequency analysis
+ stft = librosa.stft(waveform_np)
+ stft_mag = np.abs(stft)
+
+ # Get frequency bins
+ freqs = librosa.fft_frequencies(sr=sample_rate)
+
+ # Define more specific frequency ranges for each drum type
+ # Kicks: Very low frequencies (30-120 Hz) with peak around 60-80 Hz
+ kick_low_mask = (freqs >= 30) & (freqs <= 120)
+ kick_mid_mask = (freqs >= 120) & (freqs <= 300) # Kick transient/attack
+
+ # Snares: Mid frequencies (150-400 Hz fundamental) + high noise (4000-10000 Hz)
+ snare_fundamental_mask = (freqs >= 150) & (freqs <= 400)
+ snare_noise_mask = (freqs >= 4000) & (freqs <= 10000)
+
+ # Hi-hats: High frequencies (6000+ Hz) with very little low end
+ hihat_mask = (freqs >= 6000)
+ low_reject_mask = (freqs <= 200) # Hihats should have minimal low freq
+
+ print(f"[FL Audio Drum Detector] Classifying drum types...")
+
+ for onset_time, onset_frame in zip(onset_times, onset_frames):
+ if onset_frame >= stft_mag.shape[1]:
+ continue
+
+ # Get spectral magnitude at onset time
+ spectrum = stft_mag[:, onset_frame]
+
+ # Calculate energy in each band (use sum for better detection)
+ kick_low_energy = np.sum(spectrum[kick_low_mask]) if np.any(kick_low_mask) else 0
+ kick_mid_energy = np.sum(spectrum[kick_mid_mask]) if np.any(kick_mid_mask) else 0
+
+ snare_fundamental_energy = np.sum(spectrum[snare_fundamental_mask]) if np.any(snare_fundamental_mask) else 0
+ snare_noise_energy = np.sum(spectrum[snare_noise_mask]) if np.any(snare_noise_mask) else 0
+
+ hihat_energy = np.sum(spectrum[hihat_mask]) if np.any(hihat_mask) else 0
+ low_energy = np.sum(spectrum[low_reject_mask]) if np.any(low_reject_mask) else 0
+
+ total_energy = np.sum(spectrum) + 1e-10
+
+ # Calculate ratios
+ kick_ratio = (kick_low_energy + kick_mid_energy) / total_energy
+ snare_ratio = (snare_fundamental_energy + snare_noise_energy) / total_energy
+ hihat_ratio = hihat_energy / total_energy
+ low_ratio = low_energy / total_energy
+
+ # More strict classification with mutual exclusion
+ classified = False
+
+ # Kicks: Strong low end, weak high end
+ if (kick_low_energy > 0 and
+ kick_ratio > (1 - kick_sensitivity) * 0.3 and
+ low_ratio > 0.25 and
+ hihat_ratio < 0.4): # Reject if too much high freq
+ kick_times.append(float(onset_time))
+ classified = True
+
+ # Snares: Mid fundamental + high noise, moderate low end
+ elif (not classified and
+ snare_fundamental_energy > 0 and
+ snare_noise_energy > 0 and
+ snare_ratio > (1 - snare_sensitivity) * 0.3 and
+ low_ratio < 0.6): # Not too much low like kick
+ snare_times.append(float(onset_time))
+ classified = True
+
+ # Hi-hats: Dominant high frequencies, minimal low end
+ elif (not classified and
+ hihat_energy > 0 and
+ hihat_ratio > (1 - hihat_sensitivity) * 0.4 and
+ low_ratio < 0.2): # Very little low frequency
+ hihat_times.append(float(onset_time))
+ classified = True
+
+ # Create output JSON
+ drum_data = {
+ "kick_times": kick_times,
+ "snare_times": snare_times,
+ "hihat_times": hihat_times,
+ "sample_rate": int(sample_rate),
+ "duration": float(len(waveform_np) / sample_rate),
+ "total_kicks": len(kick_times),
+ "total_snares": len(snare_times),
+ "total_hihats": len(hihat_times)
+ }
+
+ drum_times_json = json.dumps(drum_data, indent=2)
+
+ print(f"\n{'='*60}")
+ print(f"[FL Audio Drum Detector] Detection complete!")
+ print(f"[FL Audio Drum Detector] Kicks detected: {len(kick_times)}")
+ print(f"[FL Audio Drum Detector] Snares detected: {len(snare_times)}")
+ print(f"[FL Audio Drum Detector] Hi-hats detected: {len(hihat_times)}")
+ print(f"[FL Audio Drum Detector] Duration: {drum_data['duration']:.2f}s")
+ print(f"{'='*60}\n")
+
+ return (drum_times_json,)
+
+ except Exception as e:
+ error_msg = f"Error: {str(e)}"
+ print(f"\n{'='*60}")
+ print(f"[FL Audio Drum Detector] ERROR: {error_msg}")
+ import traceback
+ traceback.print_exc()
+ print(f"{'='*60}\n")
+ return ("{}",)
diff --git a/comfyui_fill-nodes/nodes/audio/FL_Audio_Envelope_Visualizer.py b/comfyui_fill-nodes/nodes/audio/FL_Audio_Envelope_Visualizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb79b5eac26f8338de6f33dd4085815d26ca7ca3
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/audio/FL_Audio_Envelope_Visualizer.py
@@ -0,0 +1,137 @@
+# FL_Audio_Envelope_Visualizer: Visualize envelopes as fading white frames
+import torch
+from typing import Tuple
+
+
+class FL_Audio_Envelope_Visualizer:
+ """
+ A ComfyUI node for visualizing audio envelopes as frames.
+ Creates white frames that fade to black based on envelope values.
+ """
+
+ RETURN_TYPES = ("IMAGE",)
+ RETURN_NAMES = ("frames",)
+ FUNCTION = "visualize_envelope"
+ CATEGORY = "🏵️Fill Nodes/Audio"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "envelope_json": ("STRING", {
+ "description": "Envelope JSON from FL_Audio_Reactive_Envelope"
+ }),
+ },
+ "optional": {
+ "width": ("INT", {
+ "default": 512,
+ "min": 64,
+ "max": 4096,
+ "step": 8,
+ "description": "Frame width"
+ }),
+ "height": ("INT", {
+ "default": 512,
+ "min": 64,
+ "max": 4096,
+ "step": 8,
+ "description": "Frame height"
+ }),
+ "intensity": ("FLOAT", {
+ "default": 1.0,
+ "min": 0.1,
+ "max": 5.0,
+ "step": 0.1,
+ "description": "Brightness multiplier"
+ }),
+ "invert": ("BOOLEAN", {
+ "default": False,
+ "description": "Invert colors (black flashes on white)"
+ }),
+ }
+ }
+
+ def visualize_envelope(
+ self,
+ envelope_json: str,
+ width: int = 512,
+ height: int = 512,
+ intensity: float = 1.0,
+ invert: bool = False
+ ) -> Tuple[torch.Tensor]:
+ """
+ Visualize envelope as fading frames
+
+ Args:
+ envelope_json: JSON string with envelope data from FL_Audio_Reactive_Envelope
+ width: Frame width in pixels
+ height: Frame height in pixels
+ intensity: Brightness multiplier
+ invert: Invert colors (black on white instead of white on black)
+
+ Returns:
+ Tuple containing tensor of frames (batch, height, width, channels)
+ """
+ print(f"\n{'='*60}")
+ print(f"[FL Audio Envelope Visualizer] DEBUG: Function called")
+ print(f"{'='*60}\n")
+
+ try:
+ # Parse envelope JSON
+ import json
+ envelope_data = json.loads(envelope_json)
+ envelope = envelope_data['envelope']
+ num_frames = len(envelope)
+
+ print(f"[FL Audio Envelope Visualizer] DEBUG: Envelope length = {num_frames} frames")
+ print(f"[FL Audio Envelope Visualizer] DEBUG: Frame size = {width}x{height}")
+ print(f"[FL Audio Envelope Visualizer] DEBUG: Intensity = {intensity}")
+ print(f"[FL Audio Envelope Visualizer] DEBUG: Invert = {invert}")
+
+ # Calculate expected memory
+ expected_memory_mb = (num_frames * height * width * 3 * 4) / (1024 * 1024)
+ print(f"[FL Audio Envelope Visualizer] MEMORY DEBUG:")
+ print(f"[FL Audio Envelope Visualizer] Total frames: {num_frames}")
+ print(f"[FL Audio Envelope Visualizer] Frame dimensions: {height}x{width}x3")
+ print(f"[FL Audio Envelope Visualizer] Expected memory: {expected_memory_mb:.2f} MB")
+
+ # Create frames
+ frames = []
+
+ for frame_idx, envelope_value in enumerate(envelope):
+ # Apply intensity
+ value = min(envelope_value * intensity, 1.0)
+
+ # Invert if requested
+ if invert:
+ value = 1.0 - value
+
+ # Create frame with uniform color
+ frame = torch.full((height, width, 3), value, dtype=torch.float32)
+ frames.append(frame)
+
+ # Stack all frames
+ all_frames = torch.stack(frames, dim=0)
+
+ # Calculate actual memory
+ actual_memory_mb = (all_frames.element_size() * all_frames.nelement()) / (1024 * 1024)
+
+ print(f"\n{'='*60}")
+ print(f"[FL Audio Envelope Visualizer] Visualization complete!")
+ print(f"[FL Audio Envelope Visualizer] Total frames: {all_frames.shape[0]}")
+ print(f"[FL Audio Envelope Visualizer] Frame shape: {all_frames.shape}")
+ print(f"[FL Audio Envelope Visualizer] Actual tensor memory: {actual_memory_mb:.2f} MB")
+ print(f"[FL Audio Envelope Visualizer] Value range: [{all_frames.min():.3f}, {all_frames.max():.3f}]")
+ print(f"{'='*60}\n")
+
+ return (all_frames,)
+
+ except Exception as e:
+ error_msg = f"Error: {str(e)}"
+ print(f"\n{'='*60}")
+ print(f"[FL Audio Envelope Visualizer] ERROR: {error_msg}")
+ import traceback
+ traceback.print_exc()
+ print(f"{'='*60}\n")
+ # Return single black frame on error
+ return (torch.zeros((1, height, width, 3), dtype=torch.float32),)
diff --git a/comfyui_fill-nodes/nodes/audio/FL_Audio_Music_Video_Sequencer.py b/comfyui_fill-nodes/nodes/audio/FL_Audio_Music_Video_Sequencer.py
new file mode 100644
index 0000000000000000000000000000000000000000..af14ce8bf3447c517a33661103beb85ca5cf4af4
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/audio/FL_Audio_Music_Video_Sequencer.py
@@ -0,0 +1,323 @@
+# FL_Audio_Music_Video_Sequencer: Generate complete shot sequence for music videos
+import torch
+import numpy as np
+import json
+from typing import Tuple, Dict, Any, List
+
+
+class FL_Audio_Music_Video_Sequencer:
+ """
+ A ComfyUI node for generating complete music video shot sequences.
+ Takes beat positions and a pattern, outputs a full edit list for the entire song.
+ """
+
+ RETURN_TYPES = ("STRING", "INT")
+ RETURN_NAMES = ("sequence_json", "total_shots")
+ FUNCTION = "generate_sequence"
+ CATEGORY = "🏵️Fill Nodes/Audio"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "audio": ("AUDIO", {"description": "Input audio tensor"}),
+ "beat_positions": ("STRING", {"description": "Beat positions JSON from FL_BPM_Analyzer"}),
+ "pattern_A": ("STRING", {
+ "default": "4,4,8,4,4,8",
+ "multiline": False,
+ "description": "Pattern A: Comma-separated beat counts (e.g., '4,4,8')"
+ }),
+ },
+ "optional": {
+ "pattern_B": ("STRING", {
+ "default": "2,2,2,2",
+ "multiline": False,
+ "description": "Pattern B: Comma-separated beat counts"
+ }),
+ "pattern_C": ("STRING", {
+ "default": "8,8",
+ "multiline": False,
+ "description": "Pattern C: Comma-separated beat counts"
+ }),
+ "pattern_D": ("STRING", {
+ "default": "16",
+ "multiline": False,
+ "description": "Pattern D: Comma-separated beat counts"
+ }),
+ "pattern_sequence": ("STRING", {
+ "default": "A",
+ "multiline": False,
+ "description": "Pattern orchestration (e.g., 'A,A,B,B,C,A,A,D'). Letters reference patterns A-D."
+ }),
+ "fps": ("INT", {
+ "default": 30,
+ "min": 1,
+ "max": 120,
+ "step": 1,
+ "description": "Frames per second for video output"
+ }),
+ "repeat_pattern": ("BOOLEAN", {
+ "default": True,
+ "description": "Loop pattern sequence to cover entire song"
+ }),
+ "max_shots": ("INT", {
+ "default": 1000,
+ "min": 1,
+ "max": 10000,
+ "step": 1,
+ "description": "Maximum number of shots to generate"
+ }),
+ }
+ }
+
+ def generate_sequence(
+ self,
+ audio: Dict[str, Any],
+ beat_positions: str,
+ pattern_A: str,
+ pattern_B: str = "2,2,2,2",
+ pattern_C: str = "8,8",
+ pattern_D: str = "16",
+ pattern_sequence: str = "A",
+ fps: int = 30,
+ repeat_pattern: bool = True,
+ max_shots: int = 1000
+ ) -> Tuple[str, int]:
+ """
+ Generate complete shot sequence for music video
+
+ Args:
+ audio: Input audio tensor dict with 'waveform' and 'sample_rate'
+ beat_positions: JSON string with beat positions from analyzer
+ pattern_A: Pattern A - Comma-separated beat counts per shot (e.g., "4,4,8")
+ pattern_B: Pattern B - Comma-separated beat counts per shot
+ pattern_C: Pattern C - Comma-separated beat counts per shot
+ pattern_D: Pattern D - Comma-separated beat counts per shot
+ pattern_sequence: Orchestration sequence (e.g., "A,A,B,B,C,A,A,D")
+ fps: Frames per second for frame count calculation
+ repeat_pattern: Loop pattern sequence to cover entire song
+ max_shots: Maximum number of shots to generate
+
+ Returns:
+ Tuple of (sequence_json, total_shots)
+ """
+ print(f"\n{'='*60}")
+ print(f"[FL Music Video Sequencer] DEBUG: Function called")
+ print(f"[FL Music Video Sequencer] DEBUG: Pattern A = {pattern_A}")
+ print(f"[FL Music Video Sequencer] DEBUG: Pattern B = {pattern_B}")
+ print(f"[FL Music Video Sequencer] DEBUG: Pattern C = {pattern_C}")
+ print(f"[FL Music Video Sequencer] DEBUG: Pattern D = {pattern_D}")
+ print(f"[FL Music Video Sequencer] DEBUG: Pattern Sequence = {pattern_sequence}")
+ print(f"[FL Music Video Sequencer] DEBUG: FPS = {fps}")
+ print(f"[FL Music Video Sequencer] DEBUG: Repeat pattern = {repeat_pattern}")
+ print(f"[FL Music Video Sequencer] DEBUG: Max shots = {max_shots}")
+ print(f"{'='*60}\n")
+
+ try:
+ # Parse beat positions JSON
+ try:
+ beat_data = json.loads(beat_positions)
+ beat_times = np.array(beat_data['beat_times'])
+ sample_rate = beat_data['sample_rate']
+ total_beats = beat_data['num_beats']
+ bpm = beat_data['bpm']
+
+ print(f"[FL Music Video Sequencer] DEBUG: Loaded {total_beats} beat positions")
+ print(f"[FL Music Video Sequencer] DEBUG: BPM = {bpm:.2f}")
+ print(f"[FL Music Video Sequencer] DEBUG: Sample rate = {sample_rate}")
+
+ except (json.JSONDecodeError, KeyError) as e:
+ error_msg = f"Error parsing beat positions JSON: {e}"
+ print(f"[FL Music Video Sequencer] ERROR: {error_msg}")
+ return "{}", 0
+
+ # Parse all patterns
+ try:
+ patterns = {
+ 'A': [int(x.strip()) for x in pattern_A.split(',') if x.strip()],
+ 'B': [int(x.strip()) for x in pattern_B.split(',') if x.strip()],
+ 'C': [int(x.strip()) for x in pattern_C.split(',') if x.strip()],
+ 'D': [int(x.strip()) for x in pattern_D.split(',') if x.strip()],
+ }
+
+ # Validate all patterns are non-empty
+ for letter, pattern_beats in patterns.items():
+ if not pattern_beats:
+ print(f"[FL Music Video Sequencer] ERROR: Pattern {letter} is empty")
+ return "{}", 0
+
+ print(f"[FL Music Video Sequencer] DEBUG: Pattern A = {patterns['A']}")
+ print(f"[FL Music Video Sequencer] DEBUG: Pattern B = {patterns['B']}")
+ print(f"[FL Music Video Sequencer] DEBUG: Pattern C = {patterns['C']}")
+ print(f"[FL Music Video Sequencer] DEBUG: Pattern D = {patterns['D']}")
+
+ except ValueError as e:
+ error_msg = f"Error parsing patterns: {e}"
+ print(f"[FL Music Video Sequencer] ERROR: {error_msg}")
+ return "{}", 0
+
+ # Parse pattern sequence
+ try:
+ sequence_letters = [x.strip().upper() for x in pattern_sequence.split(',') if x.strip()]
+ if not sequence_letters:
+ print(f"[FL Music Video Sequencer] ERROR: Empty pattern sequence")
+ return "{}", 0
+
+ # Validate sequence letters are valid (A, B, C, or D)
+ for letter in sequence_letters:
+ if letter not in patterns:
+ print(f"[FL Music Video Sequencer] ERROR: Invalid pattern letter '{letter}' in sequence. Use A, B, C, or D.")
+ return "{}", 0
+
+ print(f"[FL Music Video Sequencer] DEBUG: Pattern sequence = {sequence_letters}")
+
+ except Exception as e:
+ error_msg = f"Error parsing pattern sequence '{pattern_sequence}': {e}"
+ print(f"[FL Music Video Sequencer] ERROR: {error_msg}")
+ return "{}", 0
+
+ # Get waveform for audio segments
+ waveform = audio['waveform']
+
+ # Generate shots
+ shots = []
+ current_beat = 0
+ current_frame = 0
+ sequence_index = 0 # Index in the pattern sequence (A, B, C, D)
+ pattern_index = 0 # Index within the current pattern's beats
+ shot_id = 0
+
+ while current_beat < total_beats and shot_id < max_shots:
+ # Get current pattern letter from sequence
+ current_pattern_letter = sequence_letters[sequence_index]
+ current_pattern_beats = patterns[current_pattern_letter]
+
+ # Get beat count for this shot from the current pattern
+ beat_count = current_pattern_beats[pattern_index]
+
+ # Calculate end beat
+ end_beat = current_beat + beat_count
+
+ # Check if we've run out of beats
+ if current_beat >= total_beats:
+ break
+
+ # Adjust if end_beat exceeds total beats
+ if end_beat > total_beats:
+ if not repeat_pattern:
+ # Last shot - use remaining beats
+ end_beat = total_beats
+ beat_count = end_beat - current_beat
+ else:
+ # Pattern repeating but not enough beats left
+ break
+
+ # Calculate time boundaries
+ segment_start_time = beat_times[current_beat]
+
+ if end_beat < total_beats:
+ segment_end_time = beat_times[end_beat]
+ else:
+ # Last segment - extend by median interval
+ if len(beat_times) > 1:
+ median_interval = np.median(np.diff(beat_times))
+ segment_end_time = beat_times[end_beat - 1] + median_interval
+ else:
+ segment_end_time = beat_times[end_beat - 1]
+
+ # Calculate frame boundaries (drift-free)
+ end_frame = round(segment_end_time * fps)
+ frame_count = end_frame - current_frame
+
+ # Calculate sample boundaries
+ segment_start_sample = int(segment_start_time * sample_rate)
+ segment_end_sample = int(segment_end_time * sample_rate)
+
+ # Create shot data
+ shot = {
+ "shot_id": shot_id,
+ "start_beat": int(current_beat),
+ "end_beat": int(end_beat),
+ "beat_count": int(beat_count),
+ "start_time": float(segment_start_time),
+ "end_time": float(segment_end_time),
+ "duration": float(segment_end_time - segment_start_time),
+ "start_frame": int(current_frame),
+ "end_frame": int(end_frame),
+ "frame_count": int(frame_count),
+ "start_sample": int(segment_start_sample),
+ "end_sample": int(segment_end_sample),
+ "pattern_letter": current_pattern_letter,
+ "pattern_index": int(pattern_index),
+ "sequence_index": int(sequence_index)
+ }
+
+ shots.append(shot)
+
+ print(f"[FL Music Video Sequencer] Shot {shot_id}: Pattern {current_pattern_letter}[{pattern_index}], beats {current_beat}-{end_beat} ({beat_count} beats), frames {current_frame}-{end_frame} ({frame_count} frames), {segment_start_time:.2f}s-{segment_end_time:.2f}s")
+
+ # Move to next shot
+ current_beat = end_beat
+ current_frame = end_frame
+ shot_id += 1
+
+ # Advance pattern index within current pattern
+ pattern_index += 1
+
+ # Check if we've completed the current pattern
+ if pattern_index >= len(current_pattern_beats):
+ # Move to next pattern in sequence
+ pattern_index = 0
+ sequence_index += 1
+
+ # Check if we've completed the entire sequence
+ if sequence_index >= len(sequence_letters):
+ if repeat_pattern:
+ # Loop back to start of sequence
+ sequence_index = 0
+ else:
+ # Stay on last pattern in sequence
+ sequence_index = len(sequence_letters) - 1
+
+ # Create sequence data
+ sequence_data = {
+ "metadata": {
+ "bpm": float(bpm),
+ "total_beats": int(total_beats),
+ "total_shots": len(shots),
+ "fps": int(fps),
+ "pattern_A": pattern_A,
+ "pattern_B": pattern_B,
+ "pattern_C": pattern_C,
+ "pattern_D": pattern_D,
+ "pattern_sequence": pattern_sequence,
+ "patterns": patterns,
+ "sequence_letters": sequence_letters,
+ "repeat_pattern": repeat_pattern,
+ "sample_rate": int(sample_rate),
+ "total_duration": float(beat_times[-1]) if len(beat_times) > 0 else 0.0,
+ "total_frames": int(current_frame)
+ },
+ "shots": shots
+ }
+
+ sequence_json = json.dumps(sequence_data, indent=2)
+
+ print(f"\n{'='*60}")
+ print(f"[FL Music Video Sequencer] Sequence generation complete!")
+ print(f"[FL Music Video Sequencer] Total shots: {len(shots)}")
+ print(f"[FL Music Video Sequencer] Total beats covered: {current_beat}/{total_beats}")
+ print(f"[FL Music Video Sequencer] Total frames: {current_frame}")
+ print(f"[FL Music Video Sequencer] Total duration: {beat_times[-1]:.2f}s" if len(beat_times) > 0 else "N/A")
+ print(f"{'='*60}\n")
+
+ return sequence_json, len(shots)
+
+ except Exception as e:
+ error_msg = f"Error: {str(e)}"
+ print(f"\n{'='*60}")
+ print(f"[FL Music Video Sequencer] ERROR: {error_msg}")
+ import traceback
+ traceback.print_exc()
+ print(f"{'='*60}\n")
+ return "{}", 0
diff --git a/comfyui_fill-nodes/nodes/audio/FL_Audio_Reactive_Brightness.py b/comfyui_fill-nodes/nodes/audio/FL_Audio_Reactive_Brightness.py
new file mode 100644
index 0000000000000000000000000000000000000000..73614d345abb810ac843bb03a146e99728b14d4d
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/audio/FL_Audio_Reactive_Brightness.py
@@ -0,0 +1,196 @@
+# FL_Audio_Reactive_Brightness: Control brightness/luminance based on audio envelope
+import torch
+import numpy as np
+import json
+from PIL import Image
+from typing import Tuple
+
+
+class FL_Audio_Reactive_Brightness:
+ """
+ A ComfyUI node for applying audio-reactive brightness/luminance changes to frames.
+ Adjusts brightness based on envelope values from drum detection.
+ """
+
+ RETURN_TYPES = ("IMAGE",)
+ RETURN_NAMES = ("frames",)
+ FUNCTION = "apply_brightness"
+ CATEGORY = "🏵️Fill Nodes/Audio"
+
+ def t2p(self, t):
+ """Tensor to PIL"""
+ if t is not None:
+ i = 255.0 * t.cpu().numpy().squeeze()
+ return Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
+ return None
+
+ def prepare_mask_batch(self, mask, total_images):
+ """Prepare mask batch to match image batch size"""
+ if mask is None:
+ return None
+ mask_images = [self.t2p(m) for m in mask]
+ if len(mask_images) < total_images:
+ mask_images = mask_images * (total_images // len(mask_images) + 1)
+ return mask_images[:total_images]
+
+ def process_mask(self, mask, target_size):
+ """Resize and convert mask to grayscale"""
+ mask = mask.resize(target_size, Image.LANCZOS)
+ return mask.convert('L') if mask.mode != 'L' else mask
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "frames": ("IMAGE", {"description": "Input frames"}),
+ "envelope_json": ("STRING", {"description": "Envelope JSON from FL_Audio_Reactive_Envelope"}),
+ },
+ "optional": {
+ "mask": ("IMAGE", {
+ "default": None,
+ "description": "Optional mask to control where effect is applied"
+ }),
+ "base_brightness": ("FLOAT", {
+ "default": 1.0,
+ "min": 0.0,
+ "max": 3.0,
+ "step": 0.01,
+ "description": "Base brightness multiplier (1.0 = normal)"
+ }),
+ "brightness_intensity": ("FLOAT", {
+ "default": 0.15,
+ "min": -1.0,
+ "max": 1.0,
+ "step": 0.01,
+ "description": "Brightness intensity (positive = brighter on hits, negative = darker)"
+ }),
+ "invert": ("BOOLEAN", {
+ "default": False,
+ "description": "Invert envelope (darken on hits instead of brighten)"
+ }),
+ "clamp_output": ("BOOLEAN", {
+ "default": True,
+ "description": "Clamp output to valid range [0,1] to prevent overexposure"
+ }),
+ }
+ }
+
+ def apply_brightness(
+ self,
+ frames: torch.Tensor,
+ envelope_json: str,
+ mask=None,
+ base_brightness: float = 1.0,
+ brightness_intensity: float = 0.15,
+ invert: bool = False,
+ clamp_output: bool = True
+ ) -> Tuple[torch.Tensor]:
+ """
+ Apply audio-reactive brightness effect to frames
+
+ Args:
+ frames: Input frames tensor (batch, height, width, channels)
+ envelope_json: JSON string with envelope data
+ base_brightness: Base brightness multiplier (1.0 = normal)
+ brightness_intensity: How much envelope affects brightness
+ invert: Darken on hits instead of brighten
+ clamp_output: Clamp to [0,1] range
+
+ Returns:
+ Tuple containing brightness-adjusted frames
+ """
+ print(f"\n{'='*60}")
+ print(f"[FL Audio Reactive Brightness] DEBUG: Function called")
+ print(f"[FL Audio Reactive Brightness] DEBUG: Input frames shape = {frames.shape}")
+ print(f"[FL Audio Reactive Brightness] DEBUG: Base brightness = {base_brightness}")
+ print(f"[FL Audio Reactive Brightness] DEBUG: Brightness intensity = {brightness_intensity}")
+ print(f"[FL Audio Reactive Brightness] DEBUG: Invert = {invert}")
+ print(f"[FL Audio Reactive Brightness] DEBUG: Clamp output = {clamp_output}")
+ print(f"{'='*60}\n")
+
+ try:
+ # Parse envelope JSON
+ envelope_data = json.loads(envelope_json)
+ envelope = envelope_data['envelope']
+
+ batch_size, height, width, channels = frames.shape
+ num_envelope_frames = len(envelope)
+
+ print(f"[FL Audio Reactive Brightness] Input frames: {batch_size}")
+ print(f"[FL Audio Reactive Brightness] Envelope frames: {num_envelope_frames}")
+
+ # Handle frame count mismatch
+ if batch_size != num_envelope_frames:
+ print(f"[FL Audio Reactive Brightness] WARNING: Frame count mismatch! Using min({batch_size}, {num_envelope_frames})")
+ max_frames = min(batch_size, num_envelope_frames)
+ else:
+ max_frames = batch_size
+
+ # Prepare mask batch if provided
+ mask_images = self.prepare_mask_batch(mask, max_frames) if mask is not None else None
+
+ # Process each frame
+ output_frames = []
+
+ for frame_idx in range(max_frames):
+ # Get envelope value for this frame
+ envelope_value = envelope[frame_idx]
+
+ # Calculate brightness multiplier for this frame
+ if invert:
+ # Invert: high envelope = darker
+ brightness = base_brightness - (envelope_value * brightness_intensity)
+ else:
+ # Normal: high envelope = brighter
+ brightness = base_brightness + (envelope_value * brightness_intensity)
+
+ # Get frame
+ frame = frames[frame_idx]
+
+ # Apply brightness multiplier
+ brightened_frame = frame * brightness
+
+ # Clamp to valid range if requested
+ if clamp_output:
+ brightened_frame = torch.clamp(brightened_frame, 0.0, 1.0)
+
+ # Apply mask if provided
+ if mask_images is not None:
+ # Convert mask to tensor
+ mask_img = self.process_mask(mask_images[frame_idx], (width, height))
+ mask_array = np.array(mask_img).astype(np.float32) / 255.0
+
+ # Expand mask to 3 channels
+ if len(mask_array.shape) == 2:
+ mask_tensor = torch.from_numpy(mask_array).unsqueeze(-1).repeat(1, 1, 3)
+ else:
+ mask_tensor = torch.from_numpy(mask_array)
+
+ # Blend: mask=1.0 shows brightness effect, mask=0.0 shows original
+ brightened_frame = frame * (1.0 - mask_tensor) + brightened_frame * mask_tensor
+
+ output_frames.append(brightened_frame)
+
+ if frame_idx % 100 == 0 or frame_idx < 5:
+ print(f"[FL Audio Reactive Brightness] Frame {frame_idx}: envelope={envelope_value:.3f}, brightness={brightness:.3f}")
+
+ # Stack all frames
+ output_tensor = torch.stack(output_frames, dim=0)
+
+ print(f"\n{'='*60}")
+ print(f"[FL Audio Reactive Brightness] Processing complete!")
+ print(f"[FL Audio Reactive Brightness] Output frames: {output_tensor.shape[0]}")
+ print(f"[FL Audio Reactive Brightness] Output shape: {output_tensor.shape}")
+ print(f"[FL Audio Reactive Brightness] Value range: [{output_tensor.min():.3f}, {output_tensor.max():.3f}]")
+ print(f"{'='*60}\n")
+
+ return (output_tensor,)
+
+ except Exception as e:
+ error_msg = f"Error: {str(e)}"
+ print(f"\n{'='*60}")
+ print(f"[FL Audio Reactive Brightness] ERROR: {error_msg}")
+ import traceback
+ traceback.print_exc()
+ print(f"{'='*60}\n")
+ return (frames,)
diff --git a/comfyui_fill-nodes/nodes/audio/FL_Audio_Reactive_Edge_Glow.py b/comfyui_fill-nodes/nodes/audio/FL_Audio_Reactive_Edge_Glow.py
new file mode 100644
index 0000000000000000000000000000000000000000..137dd0eb0d53140aace4e01ad6b0bd163a111628
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/audio/FL_Audio_Reactive_Edge_Glow.py
@@ -0,0 +1,234 @@
+# FL_Audio_Reactive_Edge_Glow: Edge detection with glow based on audio envelope
+import torch
+import torch.nn.functional as F
+import json
+from typing import Tuple
+
+
+class FL_Audio_Reactive_Edge_Glow:
+ """
+ A ComfyUI node for applying audio-reactive edge detection and glow effect.
+ Detects edges and adds glowing outline that pulses with the audio.
+ """
+
+ RETURN_TYPES = ("IMAGE",)
+ RETURN_NAMES = ("frames",)
+ FUNCTION = "apply_edge_glow"
+ CATEGORY = "🏵️Fill Nodes/Audio"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "frames": ("IMAGE", {"description": "Input frames"}),
+ "envelope_json": ("STRING", {"description": "Envelope JSON from FL_Audio_Reactive_Envelope"}),
+ },
+ "optional": {
+ "edge_frames": ("IMAGE", {"description": "Pre-computed edge frames (grayscale/mask). If not provided, edges will be auto-detected."}),
+ "edge_threshold": ("FLOAT", {
+ "default": 0.1,
+ "min": 0.0,
+ "max": 1.0,
+ "step": 0.01,
+ "description": "Edge detection sensitivity (only used if edge_frames not provided)"
+ }),
+ "glow_intensity": ("FLOAT", {
+ "default": 0.5,
+ "min": 0.0,
+ "max": 2.0,
+ "step": 0.01,
+ "description": "Base glow intensity multiplier"
+ }),
+ "envelope_intensity": ("FLOAT", {
+ "default": 0.3,
+ "min": 0.0,
+ "max": 2.0,
+ "step": 0.01,
+ "description": "How much envelope affects glow (0 = static, higher = more reactive)"
+ }),
+ "glow_color": (["white", "original", "cyan", "magenta", "yellow"], {
+ "default": "cyan",
+ "description": "Color of the glow effect"
+ }),
+ "blend_mode": (["add", "screen", "overlay"], {
+ "default": "add",
+ "description": "How to blend glow with original"
+ }),
+ }
+ }
+
+ def apply_edge_glow(
+ self,
+ frames: torch.Tensor,
+ envelope_json: str,
+ edge_frames: torch.Tensor = None,
+ edge_threshold: float = 0.1,
+ glow_intensity: float = 0.5,
+ envelope_intensity: float = 0.3,
+ glow_color: str = "cyan",
+ blend_mode: str = "add"
+ ) -> Tuple[torch.Tensor]:
+ """
+ Apply audio-reactive edge glow effect to frames
+
+ Args:
+ frames: Input frames tensor (batch, height, width, channels)
+ envelope_json: JSON string with envelope data
+ edge_threshold: Edge detection sensitivity
+ glow_intensity: Base glow brightness
+ envelope_intensity: How much envelope affects glow
+ glow_color: Color of glow effect
+ blend_mode: Blend mode for compositing
+
+ Returns:
+ Tuple containing edge-glowed frames
+ """
+ print(f"\n{'='*60}")
+ print(f"[FL Audio Reactive Edge Glow] DEBUG: Function called")
+ print(f"[FL Audio Reactive Edge Glow] DEBUG: Input frames shape = {frames.shape}")
+ print(f"[FL Audio Reactive Edge Glow] DEBUG: Edge threshold = {edge_threshold}")
+ print(f"[FL Audio Reactive Edge Glow] DEBUG: Glow intensity = {glow_intensity}")
+ print(f"[FL Audio Reactive Edge Glow] DEBUG: Envelope intensity = {envelope_intensity}")
+ print(f"[FL Audio Reactive Edge Glow] DEBUG: Glow color = {glow_color}")
+ print(f"{'='*60}\n")
+
+ try:
+ # Parse envelope JSON
+ envelope_data = json.loads(envelope_json)
+ envelope = envelope_data['envelope']
+
+ batch_size, height, width, channels = frames.shape
+ num_envelope_frames = len(envelope)
+
+ print(f"[FL Audio Reactive Edge Glow] Input frames: {batch_size}")
+ print(f"[FL Audio Reactive Edge Glow] Envelope frames: {num_envelope_frames}")
+
+ # Handle frame count mismatch
+ if batch_size != num_envelope_frames:
+ print(f"[FL Audio Reactive Edge Glow] WARNING: Frame count mismatch! Using min({batch_size}, {num_envelope_frames})")
+ max_frames = min(batch_size, num_envelope_frames)
+ else:
+ max_frames = batch_size
+
+ # Check if user provided edge frames
+ use_custom_edges = edge_frames is not None
+
+ if use_custom_edges:
+ print(f"[FL Audio Reactive Edge Glow] Using custom edge frames")
+ edge_batch_size = edge_frames.shape[0]
+ if edge_batch_size != max_frames:
+ print(f"[FL Audio Reactive Edge Glow] WARNING: Edge frame count ({edge_batch_size}) != input frame count ({max_frames})")
+ max_frames = min(max_frames, edge_batch_size)
+ else:
+ print(f"[FL Audio Reactive Edge Glow] Auto-detecting edges with Sobel")
+ # Sobel kernels for edge detection
+ sobel_x = torch.tensor([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=torch.float32).unsqueeze(0).unsqueeze(0)
+ sobel_y = torch.tensor([[-1, -2, -1], [0, 0, 0], [1, 2, 1]], dtype=torch.float32).unsqueeze(0).unsqueeze(0)
+
+ # Process each frame
+ output_frames = []
+
+ for frame_idx in range(max_frames):
+ # Get envelope value for this frame
+ envelope_value = envelope[frame_idx]
+
+ # Calculate glow strength for this frame
+ glow_strength = glow_intensity + (envelope_value * envelope_intensity)
+
+ # Get frame
+ frame = frames[frame_idx]
+
+ # Get or compute edges
+ if use_custom_edges:
+ # Use provided edge frames
+ edge_frame = edge_frames[frame_idx]
+ # Convert to grayscale if RGB
+ if edge_frame.shape[-1] == 3:
+ edges = (
+ edge_frame[:, :, 0] * 0.2126 +
+ edge_frame[:, :, 1] * 0.7152 +
+ edge_frame[:, :, 2] * 0.0722
+ )
+ else:
+ edges = edge_frame[:, :, 0] if len(edge_frame.shape) == 3 else edge_frame
+ else:
+ # Auto-detect edges with Sobel
+ # Convert to grayscale for edge detection
+ gray = (
+ frame[:, :, 0] * 0.2126 +
+ frame[:, :, 1] * 0.7152 +
+ frame[:, :, 2] * 0.0722
+ )
+
+ # Add batch and channel dimensions for convolution
+ gray_batch = gray.unsqueeze(0).unsqueeze(0)
+
+ # Apply Sobel edge detection
+ edges_x = F.conv2d(gray_batch, sobel_x, padding=1)
+ edges_y = F.conv2d(gray_batch, sobel_y, padding=1)
+
+ # Calculate edge magnitude
+ edges = torch.sqrt(edges_x ** 2 + edges_y ** 2)
+
+ # Normalize and threshold
+ edges = edges.squeeze(0).squeeze(0)
+ edges = edges / (edges.max() + 1e-8)
+ edges = torch.clamp((edges - edge_threshold) / (1.0 - edge_threshold), 0.0, 1.0)
+
+ # Apply glow strength
+ edges = edges * glow_strength
+
+ # Choose glow color
+ if glow_color == "white":
+ glow_rgb = edges.unsqueeze(-1).repeat(1, 1, 3)
+ elif glow_color == "cyan":
+ glow_rgb = torch.stack([edges * 0.3, edges, edges], dim=-1)
+ elif glow_color == "magenta":
+ glow_rgb = torch.stack([edges, edges * 0.3, edges], dim=-1)
+ elif glow_color == "yellow":
+ glow_rgb = torch.stack([edges, edges, edges * 0.3], dim=-1)
+ elif glow_color == "original":
+ # Use original frame colors at edge locations
+ glow_rgb = frame * edges.unsqueeze(-1)
+ else:
+ glow_rgb = edges.unsqueeze(-1).repeat(1, 1, 3)
+
+ # Blend with original frame
+ if blend_mode == "add":
+ result = frame + glow_rgb
+ elif blend_mode == "screen":
+ # Screen blend: 1 - (1-a)(1-b)
+ result = 1.0 - (1.0 - frame) * (1.0 - glow_rgb)
+ elif blend_mode == "overlay":
+ # Simple overlay approximation
+ result = frame * (1.0 + glow_rgb)
+ else:
+ result = frame + glow_rgb
+
+ # Clamp to valid range
+ result = torch.clamp(result, 0.0, 1.0)
+
+ output_frames.append(result)
+
+ if frame_idx % 100 == 0 or frame_idx < 5:
+ print(f"[FL Audio Reactive Edge Glow] Frame {frame_idx}: envelope={envelope_value:.3f}, glow={glow_strength:.3f}")
+
+ # Stack all frames
+ output_tensor = torch.stack(output_frames, dim=0)
+
+ print(f"\n{'='*60}")
+ print(f"[FL Audio Reactive Edge Glow] Processing complete!")
+ print(f"[FL Audio Reactive Edge Glow] Output frames: {output_tensor.shape[0]}")
+ print(f"[FL Audio Reactive Edge Glow] Output shape: {output_tensor.shape}")
+ print(f"{'='*60}\n")
+
+ return (output_tensor,)
+
+ except Exception as e:
+ error_msg = f"Error: {str(e)}"
+ print(f"\n{'='*60}")
+ print(f"[FL Audio Reactive Edge Glow] ERROR: {error_msg}")
+ import traceback
+ traceback.print_exc()
+ print(f"{'='*60}\n")
+ return (frames,)
diff --git a/comfyui_fill-nodes/nodes/audio/FL_Audio_Reactive_Envelope.py b/comfyui_fill-nodes/nodes/audio/FL_Audio_Reactive_Envelope.py
new file mode 100644
index 0000000000000000000000000000000000000000..b612bba6fb8573236a60e28b71c1a3b766db5010
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/audio/FL_Audio_Reactive_Envelope.py
@@ -0,0 +1,264 @@
+# FL_Audio_Reactive_Envelope: Generate per-frame envelopes from drum detections
+import torch
+import numpy as np
+import json
+from typing import Tuple, Dict, Any
+
+
+class FL_Audio_Reactive_Envelope:
+ """
+ A ComfyUI node for generating per-frame control envelopes from drum detections.
+ Creates ADSR envelopes for kicks, snares, and hi-hats across the entire song.
+ """
+
+ RETURN_TYPES = ("STRING", "STRING", "STRING")
+ RETURN_NAMES = ("kick_envelope_json", "snare_envelope_json", "hihat_envelope_json")
+ FUNCTION = "generate_envelopes"
+ CATEGORY = "🏵️Fill Nodes/Audio"
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "drum_times_json": ("STRING", {"description": "Drum times JSON from FL_Audio_Drum_Detector"}),
+ "fps": ("INT", {
+ "default": 30,
+ "min": 1,
+ "max": 120,
+ "step": 1,
+ "description": "Frames per second"
+ }),
+ },
+ "optional": {
+ # Kick envelope settings
+ "kick_attack_frames": ("INT", {
+ "default": 1,
+ "min": 0,
+ "max": 30,
+ "step": 1,
+ "description": "Kick attack duration in frames"
+ }),
+ "kick_decay_frames": ("INT", {
+ "default": 8,
+ "min": 1,
+ "max": 60,
+ "step": 1,
+ "description": "Kick decay duration in frames"
+ }),
+ "kick_sustain_level": ("FLOAT", {
+ "default": 0.2,
+ "min": 0.0,
+ "max": 1.0,
+ "step": 0.05,
+ "description": "Kick sustain level (0-1)"
+ }),
+ "kick_release_frames": ("INT", {
+ "default": 10,
+ "min": 1,
+ "max": 60,
+ "step": 1,
+ "description": "Kick release duration in frames"
+ }),
+ # Snare envelope settings
+ "snare_attack_frames": ("INT", {
+ "default": 1,
+ "min": 0,
+ "max": 30,
+ "step": 1,
+ "description": "Snare attack duration in frames"
+ }),
+ "snare_decay_frames": ("INT", {
+ "default": 6,
+ "min": 1,
+ "max": 60,
+ "step": 1,
+ "description": "Snare decay duration in frames"
+ }),
+ "snare_sustain_level": ("FLOAT", {
+ "default": 0.1,
+ "min": 0.0,
+ "max": 1.0,
+ "step": 0.05,
+ "description": "Snare sustain level (0-1)"
+ }),
+ "snare_release_frames": ("INT", {
+ "default": 8,
+ "min": 1,
+ "max": 60,
+ "step": 1,
+ "description": "Snare release duration in frames"
+ }),
+ # Hi-hat envelope settings
+ "hihat_attack_frames": ("INT", {
+ "default": 1,
+ "min": 0,
+ "max": 30,
+ "step": 1,
+ "description": "Hi-hat attack duration in frames"
+ }),
+ "hihat_decay_frames": ("INT", {
+ "default": 4,
+ "min": 1,
+ "max": 60,
+ "step": 1,
+ "description": "Hi-hat decay duration in frames"
+ }),
+ "hihat_sustain_level": ("FLOAT", {
+ "default": 0.0,
+ "min": 0.0,
+ "max": 1.0,
+ "step": 0.05,
+ "description": "Hi-hat sustain level (0-1)"
+ }),
+ "hihat_release_frames": ("INT", {
+ "default": 5,
+ "min": 1,
+ "max": 60,
+ "step": 1,
+ "description": "Hi-hat release duration in frames"
+ }),
+ }
+ }
+
+ def generate_envelopes(
+ self,
+ drum_times_json: str,
+ fps: int = 30,
+ # Kick params
+ kick_attack_frames: int = 1,
+ kick_decay_frames: int = 8,
+ kick_sustain_level: float = 0.2,
+ kick_release_frames: int = 10,
+ # Snare params
+ snare_attack_frames: int = 1,
+ snare_decay_frames: int = 6,
+ snare_sustain_level: float = 0.1,
+ snare_release_frames: int = 8,
+ # Hi-hat params
+ hihat_attack_frames: int = 1,
+ hihat_decay_frames: int = 4,
+ hihat_sustain_level: float = 0.0,
+ hihat_release_frames: int = 5,
+ ) -> Tuple[str, str, str]:
+ """
+ Generate per-frame envelopes from drum detections
+
+ Args:
+ drum_times_json: JSON string from FL_Audio_Drum_Detector
+ fps: Frames per second
+ (Additional ADSR parameters for each drum type)
+
+ Returns:
+ Tuple of (kick_envelope_json, snare_envelope_json, hihat_envelope_json) as JSON strings
+ """
+ print(f"\n{'='*60}")
+ print(f"[FL Audio Reactive Envelope] DEBUG: Function called")
+ print(f"[FL Audio Reactive Envelope] DEBUG: FPS = {fps}")
+ print(f"{'='*60}\n")
+
+ try:
+ # Parse drum times JSON
+ drum_data = json.loads(drum_times_json)
+ kick_times = drum_data['kick_times']
+ snare_times = drum_data['snare_times']
+ hihat_times = drum_data['hihat_times']
+ duration = drum_data['duration']
+
+ total_frames = int(duration * fps)
+
+ print(f"[FL Audio Reactive Envelope] DEBUG: Duration = {duration:.2f}s")
+ print(f"[FL Audio Reactive Envelope] DEBUG: Total frames = {total_frames}")
+ print(f"[FL Audio Reactive Envelope] DEBUG: Kicks = {len(kick_times)}")
+ print(f"[FL Audio Reactive Envelope] DEBUG: Snares = {len(snare_times)}")
+ print(f"[FL Audio Reactive Envelope] DEBUG: Hi-hats = {len(hihat_times)}")
+
+ # Generate envelopes
+ kick_envelope = self._generate_envelope(
+ kick_times, total_frames, fps,
+ kick_attack_frames, kick_decay_frames, kick_sustain_level, kick_release_frames
+ )
+
+ snare_envelope = self._generate_envelope(
+ snare_times, total_frames, fps,
+ snare_attack_frames, snare_decay_frames, snare_sustain_level, snare_release_frames
+ )
+
+ hihat_envelope = self._generate_envelope(
+ hihat_times, total_frames, fps,
+ hihat_attack_frames, hihat_decay_frames, hihat_sustain_level, hihat_release_frames
+ )
+
+ print(f"\n{'='*60}")
+ print(f"[FL Audio Reactive Envelope] Envelope generation complete!")
+ print(f"[FL Audio Reactive Envelope] Kick envelope: {len(kick_envelope)} frames")
+ print(f"[FL Audio Reactive Envelope] Snare envelope: {len(snare_envelope)} frames")
+ print(f"[FL Audio Reactive Envelope] Hi-hat envelope: {len(hihat_envelope)} frames")
+ print(f"{'='*60}\n")
+
+ # Convert to JSON strings
+ kick_json = json.dumps({"envelope": kick_envelope, "total_frames": len(kick_envelope)})
+ snare_json = json.dumps({"envelope": snare_envelope, "total_frames": len(snare_envelope)})
+ hihat_json = json.dumps({"envelope": hihat_envelope, "total_frames": len(hihat_envelope)})
+
+ return (kick_json, snare_json, hihat_json)
+
+ except Exception as e:
+ error_msg = f"Error: {str(e)}"
+ print(f"\n{'='*60}")
+ print(f"[FL Audio Reactive Envelope] ERROR: {error_msg}")
+ import traceback
+ traceback.print_exc()
+ print(f"{'='*60}\n")
+ return ("{}", "{}", "{}")
+
+ def _generate_envelope(
+ self,
+ hit_times: list,
+ total_frames: int,
+ fps: int,
+ attack_frames: int,
+ decay_frames: int,
+ sustain_level: float,
+ release_frames: int
+ ) -> list:
+ """Generate ADSR envelope for a drum type"""
+ envelope = [0.0] * total_frames
+
+ for hit_time in hit_times:
+ hit_frame = int(hit_time * fps)
+
+ if hit_frame >= total_frames:
+ continue
+
+ # Attack phase
+ for i in range(attack_frames):
+ frame_idx = hit_frame + i
+ if frame_idx >= total_frames:
+ break
+ # Linear attack to 1.0
+ envelope[frame_idx] = max(envelope[frame_idx], i / max(attack_frames, 1))
+
+ # Decay phase
+ for i in range(decay_frames):
+ frame_idx = hit_frame + attack_frames + i
+ if frame_idx >= total_frames:
+ break
+ # Linear decay to sustain level
+ decay_value = 1.0 - (i / decay_frames) * (1.0 - sustain_level)
+ envelope[frame_idx] = max(envelope[frame_idx], decay_value)
+
+ # Sustain phase (hold at sustain level)
+ sustain_frame = hit_frame + attack_frames + decay_frames
+ if sustain_frame < total_frames:
+ envelope[sustain_frame] = max(envelope[sustain_frame], sustain_level)
+
+ # Release phase
+ for i in range(release_frames):
+ frame_idx = hit_frame + attack_frames + decay_frames + i
+ if frame_idx >= total_frames:
+ break
+ # Linear release to 0.0
+ release_value = sustain_level * (1.0 - i / release_frames)
+ envelope[frame_idx] = max(envelope[frame_idx], release_value)
+
+ return envelope
diff --git a/comfyui_fill-nodes/nodes/film_arch.py b/comfyui_fill-nodes/nodes/film_arch.py
new file mode 100644
index 0000000000000000000000000000000000000000..a527e842f8e97d2c0f2c6997d8fa4d3134e59167
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/film_arch.py
@@ -0,0 +1,798 @@
+"""
+https://github.com/dajes/frame-interpolation-pytorch/blob/main/feature_extractor.py
+https://github.com/dajes/frame-interpolation-pytorch/blob/main/fusion.py
+https://github.com/dajes/frame-interpolation-pytorch/blob/main/interpolator.py
+https://github.com/dajes/frame-interpolation-pytorch/blob/main/pyramid_flow_estimator.py
+https://github.com/dajes/frame-interpolation-pytorch/blob/main/util.py
+"""
+
+"""PyTorch layer for extracting image features for the film_net interpolator.
+
+The feature extractor implemented here converts an image pyramid into a pyramid
+of deep features. The feature pyramid serves a similar purpose as U-Net
+architecture's encoder, but we use a special cascaded architecture described in
+Multi-view Image Fusion [1].
+
+For comprehensiveness, below is a short description of the idea. While the
+description is a bit involved, the cascaded feature pyramid can be used just
+like any image feature pyramid.
+
+Why cascaded architeture?
+=========================
+To understand the concept it is worth reviewing a traditional feature pyramid
+first: *A traditional feature pyramid* as in U-net or in many optical flow
+networks is built by alternating between convolutions and pooling, starting
+from the input image.
+
+It is well known that early features of such architecture correspond to low
+level concepts such as edges in the image whereas later layers extract
+semantically higher level concepts such as object classes etc. In other words,
+the meaning of the filters in each resolution level is different. For problems
+such as semantic segmentation and many others this is a desirable property.
+
+However, the asymmetric features preclude sharing weights across resolution
+levels in the feature extractor itself and in any subsequent neural networks
+that follow. This can be a downside, since optical flow prediction, for
+instance is symmetric across resolution levels. The cascaded feature
+architecture addresses this shortcoming.
+
+How is it built?
+================
+The *cascaded* feature pyramid contains feature vectors that have constant
+length and meaning on each resolution level, except few of the finest ones. The
+advantage of this is that the subsequent optical flow layer can learn
+synergically from many resolutions. This means that coarse level prediction can
+benefit from finer resolution training examples, which can be useful with
+moderately sized datasets to avoid overfitting.
+
+The cascaded feature pyramid is built by extracting shallower subtree pyramids,
+each one of them similar to the traditional architecture. Each subtree
+pyramid S_i is extracted starting from each resolution level:
+
+image resolution 0 -> S_0
+image resolution 1 -> S_1
+image resolution 2 -> S_2
+...
+
+If we denote the features at level j of subtree i as S_i_j, the cascaded pyramid
+is constructed by concatenating features as follows (assuming subtree depth=3):
+
+lvl
+feat_0 = concat( S_0_0 )
+feat_1 = concat( S_1_0 S_0_1 )
+feat_2 = concat( S_2_0 S_1_1 S_0_2 )
+feat_3 = concat( S_3_0 S_2_1 S_1_2 )
+feat_4 = concat( S_4_0 S_3_1 S_2_2 )
+feat_5 = concat( S_5_0 S_4_1 S_3_2 )
+ ....
+
+In above, all levels except feat_0 and feat_1 have the same number of features
+with similar semantic meaning. This enables training a single optical flow
+predictor module shared by levels 2,3,4,5... . For more details and evaluation
+see [1].
+
+[1] Multi-view Image Fusion, Trinidad et al. 2019
+"""
+from typing import List
+
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+
+class SubTreeExtractor(nn.Module):
+ """Extracts a hierarchical set of features from an image.
+
+ This is a conventional, hierarchical image feature extractor, that extracts
+ [k, k*2, k*4... ] filters for the image pyramid where k=options.sub_levels.
+ Each level is followed by average pooling.
+ """
+
+ def __init__(self, in_channels=3, channels=64, n_layers=4):
+ super().__init__()
+ convs = []
+ for i in range(n_layers):
+ convs.append(nn.Sequential(
+ conv(in_channels, (channels << i), 3),
+ conv((channels << i), (channels << i), 3)
+ ))
+ in_channels = channels << i
+ self.convs = nn.ModuleList(convs)
+
+ def forward(self, image: torch.Tensor, n: int) -> List[torch.Tensor]:
+ """Extracts a pyramid of features from the image.
+
+ Args:
+ image: TORCH.Tensor with shape BATCH_SIZE x HEIGHT x WIDTH x CHANNELS.
+ n: number of pyramid levels to extract. This can be less or equal to
+ options.sub_levels given in the __init__.
+ Returns:
+ The pyramid of features, starting from the finest level. Each element
+ contains the output after the last convolution on the corresponding
+ pyramid level.
+ """
+ head = image
+ pyramid = []
+ for i, layer in enumerate(self.convs):
+ head = layer(head)
+ pyramid.append(head)
+ if i < n - 1:
+ head = F.avg_pool2d(head, kernel_size=2, stride=2)
+ return pyramid
+
+
+class FeatureExtractor(nn.Module):
+ """Extracts features from an image pyramid using a cascaded architecture.
+ """
+
+ def __init__(self, in_channels=3, channels=64, sub_levels=4):
+ super().__init__()
+ self.extract_sublevels = SubTreeExtractor(in_channels, channels, sub_levels)
+ self.sub_levels = sub_levels
+
+ def forward(self, image_pyramid: List[torch.Tensor]) -> List[torch.Tensor]:
+ """Extracts a cascaded feature pyramid.
+
+ Args:
+ image_pyramid: Image pyramid as a list, starting from the finest level.
+ Returns:
+ A pyramid of cascaded features.
+ """
+ sub_pyramids: List[List[torch.Tensor]] = []
+ for i in range(len(image_pyramid)):
+ # At each level of the image pyramid, creates a sub_pyramid of features
+ # with 'sub_levels' pyramid levels, re-using the same SubTreeExtractor.
+ # We use the same instance since we want to share the weights.
+ #
+ # However, we cap the depth of the sub_pyramid so we don't create features
+ # that are beyond the coarsest level of the cascaded feature pyramid we
+ # want to generate.
+ capped_sub_levels = min(len(image_pyramid) - i, self.sub_levels)
+ sub_pyramids.append(self.extract_sublevels(image_pyramid[i], capped_sub_levels))
+ # Below we generate the cascades of features on each level of the feature
+ # pyramid. Assuming sub_levels=3, The layout of the features will be
+ # as shown in the example on file documentation above.
+ feature_pyramid: List[torch.Tensor] = []
+ for i in range(len(image_pyramid)):
+ features = sub_pyramids[i][0]
+ for j in range(1, self.sub_levels):
+ if j <= i:
+ features = torch.cat([features, sub_pyramids[i - j][j]], dim=1)
+ feature_pyramid.append(features)
+ return feature_pyramid
+
+
+
+
+
+
+
+
+
+
+
+"""The final fusion stage for the film_net frame interpolator.
+
+The inputs to this module are the warped input images, image features and
+flow fields, all aligned to the target frame (often midway point between the
+two original inputs). The output is the final image. FILM has no explicit
+occlusion handling -- instead using the abovementioned information this module
+automatically decides how to best blend the inputs together to produce content
+in areas where the pixels can only be borrowed from one of the inputs.
+
+Similarly, this module also decides on how much to blend in each input in case
+of fractional timestep that is not at the halfway point. For example, if the two
+inputs images are at t=0 and t=1, and we were to synthesize a frame at t=0.1,
+it often makes most sense to favor the first input. However, this is not
+always the case -- in particular in occluded pixels.
+
+The architecture of the Fusion module follows U-net [1] architecture's decoder
+side, e.g. each pyramid level consists of concatenation with upsampled coarser
+level output, and two 3x3 convolutions.
+
+The upsampling is implemented as 'resize convolution', e.g. nearest neighbor
+upsampling followed by 2x2 convolution as explained in [2]. The classic U-net
+uses max-pooling which has a tendency to create checkerboard artifacts.
+
+[1] Ronneberger et al. U-Net: Convolutional Networks for Biomedical Image
+ Segmentation, 2015, https://arxiv.org/pdf/1505.04597.pdf
+[2] https://distill.pub/2016/deconv-checkerboard/
+"""
+from typing import List
+
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+
+_NUMBER_OF_COLOR_CHANNELS = 3
+
+
+def get_channels_at_level(level, filters):
+ n_images = 2
+ channels = _NUMBER_OF_COLOR_CHANNELS
+ flows = 2
+
+ return (sum(filters << i for i in range(level)) + channels + flows) * n_images
+
+
+class Fusion(nn.Module):
+ """The decoder."""
+
+ def __init__(self, n_layers=4, specialized_layers=3, filters=64):
+ """
+ Args:
+ m: specialized levels
+ """
+ super().__init__()
+
+ # The final convolution that outputs RGB:
+ self.output_conv = nn.Conv2d(filters, 3, kernel_size=1)
+
+ # Each item 'convs[i]' will contain the list of convolutions to be applied
+ # for pyramid level 'i'.
+ self.convs = nn.ModuleList()
+
+ # Create the convolutions. Roughly following the feature extractor, we
+ # double the number of filters when the resolution halves, but only up to
+ # the specialized_levels, after which we use the same number of filters on
+ # all levels.
+ #
+ # We create the convs in fine-to-coarse order, so that the array index
+ # for the convs will correspond to our normal indexing (0=finest level).
+ # in_channels: tuple = (128, 202, 256, 522, 512, 1162, 1930, 2442)
+
+ in_channels = get_channels_at_level(n_layers, filters)
+ increase = 0
+ for i in range(n_layers)[::-1]:
+ num_filters = (filters << i) if i < specialized_layers else (filters << specialized_layers)
+ convs = nn.ModuleList([
+ conv(in_channels, num_filters, size=2, activation=None),
+ conv(in_channels + (increase or num_filters), num_filters, size=3),
+ conv(num_filters, num_filters, size=3)]
+ )
+ self.convs.append(convs)
+ in_channels = num_filters
+ increase = get_channels_at_level(i, filters) - num_filters // 2
+
+ def forward(self, pyramid: List[torch.Tensor]) -> torch.Tensor:
+ """Runs the fusion module.
+
+ Args:
+ pyramid: The input feature pyramid as list of tensors. Each tensor being
+ in (B x H x W x C) format, with finest level tensor first.
+
+ Returns:
+ A batch of RGB images.
+ Raises:
+ ValueError, if len(pyramid) != config.fusion_pyramid_levels as provided in
+ the constructor.
+ """
+
+ # As a slight difference to a conventional decoder (e.g. U-net), we don't
+ # apply any extra convolutions to the coarsest level, but just pass it
+ # to finer levels for concatenation. This choice has not been thoroughly
+ # evaluated, but is motivated by the educated guess that the fusion part
+ # probably does not need large spatial context, because at this point the
+ # features are spatially aligned by the preceding warp.
+ net = pyramid[-1]
+
+ # Loop starting from the 2nd coarsest level:
+ # for i in reversed(range(0, len(pyramid) - 1)):
+ for k, layers in enumerate(self.convs):
+ i = len(self.convs) - 1 - k
+ # Resize the tensor from coarser level to match for concatenation.
+ level_size = pyramid[i].shape[2:4]
+ net = F.interpolate(net, size=level_size, mode='nearest')
+ net = layers[0](net)
+ net = torch.cat([pyramid[i], net], dim=1)
+ net = layers[1](net)
+ net = layers[2](net)
+ net = self.output_conv(net)
+ return net
+
+
+
+
+
+
+
+
+
+
+
+"""The film_net frame interpolator main model code.
+
+Basics
+======
+The film_net is an end-to-end learned neural frame interpolator implemented as
+a PyTorch model. It has the following inputs and outputs:
+
+Inputs:
+ x0: image A.
+ x1: image B.
+ time: desired sub-frame time.
+
+Outputs:
+ image: the predicted in-between image at the chosen time in range [0, 1].
+
+Additional outputs include forward and backward warped image pyramids, flow
+pyramids, etc., that can be visualized for debugging and analysis.
+
+Note that many training sets only contain triplets with ground truth at
+time=0.5. If a model has been trained with such training set, it will only work
+well for synthesizing frames at time=0.5. Such models can only generate more
+in-between frames using recursion.
+
+Architecture
+============
+The inference consists of three main stages: 1) feature extraction 2) warping
+3) fusion. On high-level, the architecture has similarities to Context-aware
+Synthesis for Video Frame Interpolation [1], but the exact architecture is
+closer to Multi-view Image Fusion [2] with some modifications for the frame
+interpolation use-case.
+
+Feature extraction stage employs the cascaded multi-scale architecture described
+in [2]. The advantage of this architecture is that coarse level flow prediction
+can be learned from finer resolution image samples. This is especially useful
+to avoid overfitting with moderately sized datasets.
+
+The warping stage uses a residual flow prediction idea that is similar to
+PWC-Net [3], Multi-view Image Fusion [2] and many others.
+
+The fusion stage is similar to U-Net's decoder where the skip connections are
+connected to warped image and feature pyramids. This is described in [2].
+
+Implementation Conventions
+====================
+Pyramids
+--------
+Throughtout the model, all image and feature pyramids are stored as python lists
+with finest level first followed by downscaled versions obtained by successively
+halving the resolution. The depths of all pyramids are determined by
+options.pyramid_levels. The only exception to this is internal to the feature
+extractor, where smaller feature pyramids are temporarily constructed with depth
+options.sub_levels.
+
+Color ranges & gamma
+--------------------
+The model code makes no assumptions on whether the images are in gamma or
+linearized space or what is the range of RGB color values. So a model can be
+trained with different choices. This does not mean that all the choices lead to
+similar results. In practice the model has been proven to work well with RGB
+scale = [0,1] with gamma-space images (i.e. not linearized).
+
+[1] Context-aware Synthesis for Video Frame Interpolation, Niklaus and Liu, 2018
+[2] Multi-view Image Fusion, Trinidad et al, 2019
+[3] PWC-Net: CNNs for Optical Flow Using Pyramid, Warping, and Cost Volume
+"""
+from typing import Dict, List
+
+import torch
+from torch import nn
+
+
+
+class Interpolator(nn.Module):
+ def __init__(
+ self,
+ pyramid_levels=7,
+ fusion_pyramid_levels=5,
+ specialized_levels=3,
+ sub_levels=4,
+ filters=64,
+ flow_convs=(3, 3, 3, 3),
+ flow_filters=(32, 64, 128, 256),
+ ):
+ super().__init__()
+ self.pyramid_levels = pyramid_levels
+ self.fusion_pyramid_levels = fusion_pyramid_levels
+
+ self.extract = FeatureExtractor(3, filters, sub_levels)
+ self.predict_flow = PyramidFlowEstimator(filters, flow_convs, flow_filters)
+ self.fuse = Fusion(sub_levels, specialized_levels, filters)
+
+ def shuffle_images(self, x0, x1):
+ return [
+ build_image_pyramid(x0, self.pyramid_levels),
+ build_image_pyramid(x1, self.pyramid_levels)
+ ]
+
+ def debug_forward(self, x0, x1, batch_dt) -> Dict[str, List[torch.Tensor]]:
+ image_pyramids = self.shuffle_images(x0, x1)
+
+ # Siamese feature pyramids:
+ feature_pyramids = [self.extract(image_pyramids[0]), self.extract(image_pyramids[1])]
+
+ # Predict forward flow.
+ forward_residual_flow_pyramid = self.predict_flow(feature_pyramids[0], feature_pyramids[1])
+
+ # Predict backward flow.
+ backward_residual_flow_pyramid = self.predict_flow(feature_pyramids[1], feature_pyramids[0])
+
+ # Concatenate features and images:
+
+ # Note that we keep up to 'fusion_pyramid_levels' levels as only those
+ # are used by the fusion module.
+
+ forward_flow_pyramid = flow_pyramid_synthesis(forward_residual_flow_pyramid)[:self.fusion_pyramid_levels]
+
+ backward_flow_pyramid = flow_pyramid_synthesis(backward_residual_flow_pyramid)[:self.fusion_pyramid_levels]
+
+ # We multiply the flows with t and 1-t to warp to the desired fractional time.
+ #
+ # Note: In film_net we fix time to be 0.5, and recursively invoke the interpo-
+ # lator for multi-frame interpolation. Below, we create a constant tensor of
+ # shape [B]. We use the `time` tensor to infer the batch size.
+ mid_time = torch.full_like(batch_dt, .5)
+ backward_flow = multiply_pyramid(backward_flow_pyramid, mid_time[:, 0])
+ forward_flow = multiply_pyramid(forward_flow_pyramid, 1 - mid_time[:, 0])
+
+ pyramids_to_warp = [
+ concatenate_pyramids(image_pyramids[0][:self.fusion_pyramid_levels],
+ feature_pyramids[0][:self.fusion_pyramid_levels]),
+ concatenate_pyramids(image_pyramids[1][:self.fusion_pyramid_levels],
+ feature_pyramids[1][:self.fusion_pyramid_levels])
+ ]
+
+ # Warp features and images using the flow. Note that we use backward warping
+ # and backward flow is used to read from image 0 and forward flow from
+ # image 1.
+ forward_warped_pyramid = pyramid_warp(pyramids_to_warp[0], backward_flow)
+ backward_warped_pyramid = pyramid_warp(pyramids_to_warp[1], forward_flow)
+
+ aligned_pyramid = concatenate_pyramids(forward_warped_pyramid,
+ backward_warped_pyramid)
+ aligned_pyramid = concatenate_pyramids(aligned_pyramid, backward_flow)
+ aligned_pyramid = concatenate_pyramids(aligned_pyramid, forward_flow)
+
+ return {
+ 'image': [self.fuse(aligned_pyramid)],
+ 'forward_residual_flow_pyramid': forward_residual_flow_pyramid,
+ 'backward_residual_flow_pyramid': backward_residual_flow_pyramid,
+ 'forward_flow_pyramid': forward_flow_pyramid,
+ 'backward_flow_pyramid': backward_flow_pyramid,
+ }
+
+
+ def forward(self, x0, x1, batch_dt) -> torch.Tensor:
+ return self.debug_forward(x0, x1, batch_dt)['image'][0]
+
+
+
+
+
+
+
+
+
+
+"""PyTorch layer for estimating optical flow by a residual flow pyramid.
+
+This approach of estimating optical flow between two images can be traced back
+to [1], but is also used by later neural optical flow computation methods such
+as SpyNet [2] and PWC-Net [3].
+
+The basic idea is that the optical flow is first estimated in a coarse
+resolution, then the flow is upsampled to warp the higher resolution image and
+then a residual correction is computed and added to the estimated flow. This
+process is repeated in a pyramid on coarse to fine order to successively
+increase the resolution of both optical flow and the warped image.
+
+In here, the optical flow predictor is used as an internal component for the
+film_net frame interpolator, to warp the two input images into the inbetween,
+target frame.
+
+[1] F. Glazer, Hierarchical motion detection. PhD thesis, 1987.
+[2] A. Ranjan and M. J. Black, Optical Flow Estimation using a Spatial Pyramid
+ Network. 2016
+[3] D. Sun X. Yang, M-Y. Liu and J. Kautz, PWC-Net: CNNs for Optical Flow Using
+ Pyramid, Warping, and Cost Volume, 2017
+"""
+from typing import List
+
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+
+
+class FlowEstimator(nn.Module):
+ """Small-receptive field predictor for computing the flow between two images.
+
+ This is used to compute the residual flow fields in PyramidFlowEstimator.
+
+ Note that while the number of 3x3 convolutions & filters to apply is
+ configurable, two extra 1x1 convolutions are appended to extract the flow in
+ the end.
+
+ Attributes:
+ name: The name of the layer
+ num_convs: Number of 3x3 convolutions to apply
+ num_filters: Number of filters in each 3x3 convolution
+ """
+
+ def __init__(self, in_channels: int, num_convs: int, num_filters: int):
+ super(FlowEstimator, self).__init__()
+
+ self._convs = nn.ModuleList()
+ for i in range(num_convs):
+ self._convs.append(conv(in_channels=in_channels, out_channels=num_filters, size=3))
+ in_channels = num_filters
+ self._convs.append(conv(in_channels, num_filters // 2, size=1))
+ in_channels = num_filters // 2
+ # For the final convolution, we want no activation at all to predict the
+ # optical flow vector values. We have done extensive testing on explicitly
+ # bounding these values using sigmoid, but it turned out that having no
+ # activation gives better results.
+ self._convs.append(conv(in_channels, 2, size=1, activation=None))
+
+ def forward(self, features_a: torch.Tensor, features_b: torch.Tensor) -> torch.Tensor:
+ """Estimates optical flow between two images.
+
+ Args:
+ features_a: per pixel feature vectors for image A (B x H x W x C)
+ features_b: per pixel feature vectors for image B (B x H x W x C)
+
+ Returns:
+ A tensor with optical flow from A to B
+ """
+ net = torch.cat([features_a, features_b], dim=1)
+ for conv in self._convs:
+ net = conv(net)
+ return net
+
+
+class PyramidFlowEstimator(nn.Module):
+ """Predicts optical flow by coarse-to-fine refinement.
+ """
+
+ def __init__(self, filters: int = 64,
+ flow_convs: tuple = (3, 3, 3, 3),
+ flow_filters: tuple = (32, 64, 128, 256)):
+ super(PyramidFlowEstimator, self).__init__()
+
+ in_channels = filters << 1
+ predictors = []
+ for i in range(len(flow_convs)):
+ predictors.append(
+ FlowEstimator(
+ in_channels=in_channels,
+ num_convs=flow_convs[i],
+ num_filters=flow_filters[i]))
+ in_channels += filters << (i + 2)
+ self._predictor = predictors[-1]
+ self._predictors = nn.ModuleList(predictors[:-1][::-1])
+
+ def forward(self, feature_pyramid_a: List[torch.Tensor],
+ feature_pyramid_b: List[torch.Tensor]) -> List[torch.Tensor]:
+ """Estimates residual flow pyramids between two image pyramids.
+
+ Each image pyramid is represented as a list of tensors in fine-to-coarse
+ order. Each individual image is represented as a tensor where each pixel is
+ a vector of image features.
+
+ flow_pyramid_synthesis can be used to convert the residual flow
+ pyramid returned by this method into a flow pyramid, where each level
+ encodes the flow instead of a residual correction.
+
+ Args:
+ feature_pyramid_a: image pyramid as a list in fine-to-coarse order
+ feature_pyramid_b: image pyramid as a list in fine-to-coarse order
+
+ Returns:
+ List of flow tensors, in fine-to-coarse order, each level encoding the
+ difference against the bilinearly upsampled version from the coarser
+ level. The coarsest flow tensor, e.g. the last element in the array is the
+ 'DC-term', e.g. not a residual (alternatively you can think of it being a
+ residual against zero).
+ """
+ levels = len(feature_pyramid_a)
+ v = self._predictor(feature_pyramid_a[-1], feature_pyramid_b[-1])
+ residuals = [v]
+ for i in range(levels - 2, len(self._predictors) - 1, -1):
+ # Upsamples the flow to match the current pyramid level. Also, scales the
+ # magnitude by two to reflect the new size.
+ level_size = feature_pyramid_a[i].shape[2:4]
+ v = F.interpolate(2 * v, size=level_size, mode='bilinear')
+ # Warp feature_pyramid_b[i] image based on the current flow estimate.
+ warped = warp(feature_pyramid_b[i], v)
+ # Estimate the residual flow between pyramid_a[i] and warped image:
+ v_residual = self._predictor(feature_pyramid_a[i], warped)
+ residuals.insert(0, v_residual)
+ v = v_residual + v
+
+ for k, predictor in enumerate(self._predictors):
+ i = len(self._predictors) - 1 - k
+ # Upsamples the flow to match the current pyramid level. Also, scales the
+ # magnitude by two to reflect the new size.
+ level_size = feature_pyramid_a[i].shape[2:4]
+ v = F.interpolate(2 * v, size=level_size, mode='bilinear')
+ # Warp feature_pyramid_b[i] image based on the current flow estimate.
+ warped = warp(feature_pyramid_b[i], v)
+ # Estimate the residual flow between pyramid_a[i] and warped image:
+ v_residual = predictor(feature_pyramid_a[i], warped)
+ residuals.insert(0, v_residual)
+ v = v_residual + v
+ return residuals
+
+
+
+
+
+
+
+
+
+
+"""Various utilities used in the film_net frame interpolator model."""
+from typing import List, Optional
+
+import cv2
+import numpy as np
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+
+def pad_batch(batch, align):
+ height, width = batch.shape[1:3]
+ height_to_pad = (align - height % align) if height % align != 0 else 0
+ width_to_pad = (align - width % align) if width % align != 0 else 0
+
+ crop_region = [height_to_pad >> 1, width_to_pad >> 1, height + (height_to_pad >> 1), width + (width_to_pad >> 1)]
+ batch = np.pad(batch, ((0, 0), (height_to_pad >> 1, height_to_pad - (height_to_pad >> 1)),
+ (width_to_pad >> 1, width_to_pad - (width_to_pad >> 1)), (0, 0)), mode='constant')
+ return batch, crop_region
+
+
+def load_image(path, align=64):
+ image = cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2RGB).astype(np.float32) / np.float32(255)
+ image_batch, crop_region = pad_batch(np.expand_dims(image, axis=0), align)
+ return image_batch, crop_region
+
+
+def build_image_pyramid(image: torch.Tensor, pyramid_levels: int = 3) -> List[torch.Tensor]:
+ """Builds an image pyramid from a given image.
+
+ The original image is included in the pyramid and the rest are generated by
+ successively halving the resolution.
+
+ Args:
+ image: the input image.
+ options: film_net options object
+
+ Returns:
+ A list of images starting from the finest with options.pyramid_levels items
+ """
+
+ pyramid = []
+ for i in range(pyramid_levels):
+ pyramid.append(image)
+ if i < pyramid_levels - 1:
+ image = F.avg_pool2d(image, 2, 2)
+ return pyramid
+
+
+def warp(image: torch.Tensor, flow: torch.Tensor) -> torch.Tensor:
+ """Backward warps the image using the given flow.
+
+ Specifically, the output pixel in batch b, at position x, y will be computed
+ as follows:
+ (flowed_y, flowed_x) = (y+flow[b, y, x, 1], x+flow[b, y, x, 0])
+ output[b, y, x] = bilinear_lookup(image, b, flowed_y, flowed_x)
+
+ Note that the flow vectors are expected as [x, y], e.g. x in position 0 and
+ y in position 1.
+
+ Args:
+ image: An image with shape BxHxWxC.
+ flow: A flow with shape BxHxWx2, with the two channels denoting the relative
+ offset in order: (dx, dy).
+ Returns:
+ A warped image.
+ """
+ flow = -flow.flip(1)
+
+ dtype = flow.dtype
+ device = flow.device
+
+ # warped = tfa_image.dense_image_warp(image, flow)
+ # Same as above but with pytorch
+ ls1 = 1 - 1 / flow.shape[3]
+ ls2 = 1 - 1 / flow.shape[2]
+
+ normalized_flow2 = flow.permute(0, 2, 3, 1) / torch.tensor(
+ [flow.shape[2] * .5, flow.shape[3] * .5], dtype=dtype, device=device)[None, None, None]
+ normalized_flow2 = torch.stack([
+ torch.linspace(-ls1, ls1, flow.shape[3], dtype=dtype, device=device)[None, None, :] - normalized_flow2[..., 1],
+ torch.linspace(-ls2, ls2, flow.shape[2], dtype=dtype, device=device)[None, :, None] - normalized_flow2[..., 0],
+ ], dim=3)
+
+ padding_mode = "border"
+ if device.type == "mps":
+ # https://github.com/pytorch/pytorch/issues/125098
+ padding_mode = "zeros"
+ normalized_flow2 = normalized_flow2.clamp(-1, 1)
+ warped = F.grid_sample(
+ input=image,
+ grid=normalized_flow2,
+ mode='bilinear',
+ padding_mode=padding_mode,
+ align_corners=False,
+ )
+ return warped.reshape(image.shape)
+
+
+def multiply_pyramid(pyramid: List[torch.Tensor],
+ scalar: torch.Tensor) -> List[torch.Tensor]:
+ """Multiplies all image batches in the pyramid by a batch of scalars.
+
+ Args:
+ pyramid: Pyramid of image batches.
+ scalar: Batch of scalars.
+
+ Returns:
+ An image pyramid with all images multiplied by the scalar.
+ """
+ # To multiply each image with its corresponding scalar, we first transpose
+ # the batch of images from BxHxWxC-format to CxHxWxB. This can then be
+ # multiplied with a batch of scalars, then we transpose back to the standard
+ # BxHxWxC form.
+ return [image * scalar for image in pyramid]
+
+
+def flow_pyramid_synthesis(
+ residual_pyramid: List[torch.Tensor]) -> List[torch.Tensor]:
+ """Converts a residual flow pyramid into a flow pyramid."""
+ flow = residual_pyramid[-1]
+ flow_pyramid: List[torch.Tensor] = [flow]
+ for residual_flow in residual_pyramid[:-1][::-1]:
+ level_size = residual_flow.shape[2:4]
+ flow = F.interpolate(2 * flow, size=level_size, mode='bilinear')
+ flow = residual_flow + flow
+ flow_pyramid.insert(0, flow)
+ return flow_pyramid
+
+
+def pyramid_warp(feature_pyramid: List[torch.Tensor],
+ flow_pyramid: List[torch.Tensor]) -> List[torch.Tensor]:
+ """Warps the feature pyramid using the flow pyramid.
+
+ Args:
+ feature_pyramid: feature pyramid starting from the finest level.
+ flow_pyramid: flow fields, starting from the finest level.
+
+ Returns:
+ Reverse warped feature pyramid.
+ """
+ warped_feature_pyramid = []
+ for features, flow in zip(feature_pyramid, flow_pyramid):
+ warped_feature_pyramid.append(warp(features, flow))
+ return warped_feature_pyramid
+
+
+def concatenate_pyramids(pyramid1: List[torch.Tensor],
+ pyramid2: List[torch.Tensor]) -> List[torch.Tensor]:
+ """Concatenates each pyramid level together in the channel dimension."""
+ result = []
+ for features1, features2 in zip(pyramid1, pyramid2):
+ result.append(torch.cat([features1, features2], dim=1))
+ return result
+
+
+def conv(in_channels, out_channels, size, activation: Optional[str] = 'relu'):
+ # Since PyTorch doesn't have an in-built activation in Conv2d, we use a
+ # Sequential layer to combine Conv2d and Leaky ReLU in one module.
+ _conv = nn.Conv2d(
+ in_channels=in_channels,
+ out_channels=out_channels,
+ kernel_size=size,
+ padding='same')
+ if activation is None:
+ return _conv
+ assert activation == 'relu'
+ return nn.Sequential(
+ _conv,
+ nn.LeakyReLU(.2)
+ )
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/hugging_face/FL_HFDatasetDownloader.py b/comfyui_fill-nodes/nodes/hugging_face/FL_HFDatasetDownloader.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd9da8427a030d3418c9447cc7e8d6f80100a99e
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/hugging_face/FL_HFDatasetDownloader.py
@@ -0,0 +1,58 @@
+import os
+from huggingface_hub import snapshot_download
+
+class FL_HFDatasetDownloader:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "repo_id": ("STRING", {
+ "default": "jjuik2014/FaceVid-1K-Part",
+ "multiline": False
+ }),
+ "repo_type": (["dataset", "model", "space"], {
+ "default": "dataset"
+ }),
+ "local_dir": ("STRING", {
+ "default": "./output/HF-Downloads",
+ "multiline": False
+ }),
+ "max_workers": ("INT", {
+ "default": 10,
+ "min": 1,
+ "max": 20,
+ "step": 1
+ }),
+ "download_trigger": ("BOOLEAN", {
+ "default": False,
+ "label": "Start Download"
+ })
+ }
+ }
+
+ RETURN_TYPES = ("STRING",)
+ RETURN_NAMES = ("download_path",)
+ FUNCTION = "download_repo"
+ CATEGORY = "🏵️Fill Nodes/Hugging Face"
+
+ def download_repo(self, repo_id, repo_type, local_dir, max_workers, download_trigger):
+ if not download_trigger:
+ return (local_dir,)
+
+ try:
+ # Ensure the directory exists
+ os.makedirs(local_dir, exist_ok=True)
+
+ # Download the repository
+ download_path = snapshot_download(
+ repo_id=repo_id,
+ repo_type=repo_type,
+ local_dir=local_dir,
+ max_workers=max_workers
+ )
+
+ return (download_path,)
+
+ except Exception as e:
+ print(f"Error downloading repository: {str(e)}")
+ return (local_dir,)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/hugging_face/FL_HFHubModelUploader.py b/comfyui_fill-nodes/nodes/hugging_face/FL_HFHubModelUploader.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6122c6a6719c92210067c04e1a6373f279a0ca6
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/hugging_face/FL_HFHubModelUploader.py
@@ -0,0 +1,189 @@
+import sys
+import subprocess
+import importlib.util
+import os
+import time
+import threading
+
+# Check if huggingface_hub is installed, if not, install it
+if importlib.util.find_spec("huggingface_hub") is None:
+ print("huggingface_hub is not installed. Installing it now...")
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "huggingface_hub"])
+ print("huggingface_hub has been installed.")
+
+import torch
+from PIL import Image
+import io
+from huggingface_hub import HfApi, create_repo, repo_exists
+from tqdm import tqdm
+
+
+class FL_HFHubModelUploader:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "api_key": ("STRING", {"multiline": False}),
+ "owner": ("STRING", {"default": ""}),
+ "repo_name": ("STRING", {"default": "my-awesome-model"}),
+ "readme_content": (
+ "STRING", {"multiline": True, "default": "# My Awesome Model\n\nThis is a great model!"}),
+ "create_new_repo": (["True", "False"],),
+ "image_folder_path": ("STRING", {"default": "images"}),
+ "repo_type": (["model", "dataset", "space"],),
+ },
+ "optional": {
+ "image": ("IMAGE",),
+ "model_card_header": ("IMAGE",),
+ "zip_file": ("ZIP",),
+ "zip_filename": ("STRING", {"default": "archive"}),
+ "zip_folder_path": ("STRING", {"default": "zipped_content"}),
+ "model_file_path": ("STRING", {"default": ""}),
+ "model_repo_path": ("STRING", {"default": ""}),
+ }
+ }
+
+ RETURN_TYPES = ("STRING",)
+ FUNCTION = "upload_to_hub"
+ CATEGORY = "🏵️Fill Nodes/Hugging Face"
+
+ def upload_to_hub(self, api_key: str, owner: str, repo_name: str, readme_content: str, create_new_repo: str,
+ image_folder_path: str, repo_type: str, image: torch.Tensor = None,
+ model_card_header: torch.Tensor = None, zip_file: bytes = None,
+ zip_filename: str = "archive", zip_folder_path: str = "zipped_content",
+ model_file_path: str = "", model_repo_path: str = "") -> tuple[str]:
+ # Initialize Hugging Face API
+ api = HfApi(token=api_key)
+
+ # Ensure zip_filename ends with .zip
+ if not zip_filename.lower().endswith('.zip'):
+ zip_filename += '.zip'
+
+ try:
+ # Construct full repo_id
+ full_repo_id = f"{owner}/{repo_name}"
+
+ # Step 1: Create a new repository or check if it exists
+ create_new_repo = create_new_repo == "True"
+ if create_new_repo:
+ repo_url = create_repo(repo_id=full_repo_id, token=api_key, exist_ok=True, repo_type=repo_type)
+ print(f"Repository created or already exists: {repo_url}")
+ else:
+ if not repo_exists(repo_id=full_repo_id, token=api_key):
+ return (
+ f"Error: Repository {full_repo_id} does not exist. Please create it first or use the 'Create New Repo' option.",)
+ repo_url = f"https://huggingface.co/{full_repo_id}"
+ print(f"Using existing repository: {repo_url}")
+
+ # Step 2: Prepare and upload files
+ max_retries = 3
+ for attempt in range(max_retries):
+ try:
+ # Upload the main image if provided
+ if image is not None:
+ main_image = Image.fromarray((image.squeeze().cpu().numpy() * 255).astype('uint8'))
+ main_img_byte_arr = io.BytesIO()
+ main_image.save(main_img_byte_arr, format='PNG')
+ main_img_byte_arr = main_img_byte_arr.getvalue()
+
+ api.upload_file(
+ path_or_fileobj=main_img_byte_arr,
+ path_in_repo=f"{image_folder_path}/model_image.png",
+ repo_id=full_repo_id,
+ token=api_key
+ )
+ print("Main image uploaded successfully")
+
+ # Upload the model card header image if provided
+ if model_card_header is not None:
+ header_image = Image.fromarray(
+ (model_card_header.squeeze().cpu().numpy() * 255).astype('uint8'))
+ header_img_byte_arr = io.BytesIO()
+ header_image.save(header_img_byte_arr, format='PNG')
+ header_img_byte_arr = header_img_byte_arr.getvalue()
+
+ api.upload_file(
+ path_or_fileobj=header_img_byte_arr,
+ path_in_repo="model_card_header.png",
+ repo_id=full_repo_id,
+ token=api_key
+ )
+ print("Model card header image uploaded successfully")
+ # Add the header image to the README content
+ readme_content = f"\n\n{readme_content}"
+
+ # Upload ZIP file if provided
+ if zip_file is not None:
+ api.upload_file(
+ path_or_fileobj=zip_file,
+ path_in_repo=f"{zip_folder_path}/{zip_filename}",
+ repo_id=full_repo_id,
+ token=api_key
+ )
+ print(f"ZIP file uploaded successfully as {zip_filename}")
+
+ # Upload model file from absolute path if provided
+ if model_file_path and model_repo_path:
+ if os.path.exists(model_file_path):
+ file_size = os.path.getsize(model_file_path)
+
+ # Create a progress bar
+ pbar = tqdm(total=100, unit='%', desc="Uploading model file")
+
+ # Function to update progress bar
+ def update_progress():
+ progress = 0
+ while progress < 95:
+ time.sleep(0.5)
+ increment = min(5, 95 - progress)
+ progress += increment
+ pbar.update(increment)
+
+ # Start progress update in a separate thread
+ progress_thread = threading.Thread(target=update_progress)
+ progress_thread.start()
+
+ # Perform the actual upload
+ with open(model_file_path, 'rb') as file:
+ api.upload_file(
+ path_or_fileobj=file,
+ path_in_repo=model_repo_path,
+ repo_id=full_repo_id,
+ token=api_key
+ )
+
+ # Ensure progress reaches 100%
+ progress_thread.join()
+ pbar.update(100 - pbar.n)
+ pbar.close()
+
+ print(f"Model file uploaded successfully to {model_repo_path}")
+ else:
+ print(f"Error: Model file not found at {model_file_path}")
+
+ # Upload README
+ api.upload_file(
+ path_or_fileobj=readme_content.encode('utf-8'),
+ path_in_repo="README.md",
+ repo_id=full_repo_id,
+ token=api_key
+ )
+ print("README uploaded successfully")
+
+ break # If successful, break out of the retry loop
+ except Exception as e:
+ if "Repository Not Found" in str(e) and attempt < max_retries - 1:
+ print(f"Repository not found. Retrying in 5 seconds... (Attempt {attempt + 1}/{max_retries})")
+ time.sleep(5)
+ else:
+ raise
+
+ return (f"Successfully uploaded to {repo_url}",)
+
+ except Exception as e:
+ return (f"Error: {str(e)}",)
+
+ @classmethod
+ def IS_CHANGED(cls, api_key, owner, repo_name, readme_content, create_new_repo, image_folder_path, repo_type,
+ image, model_card_header, zip_file, zip_filename, zip_folder_path, model_file_path, model_repo_path):
+ return float("NaN")
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/hugging_face/FL_HF_Character.py b/comfyui_fill-nodes/nodes/hugging_face/FL_HF_Character.py
new file mode 100644
index 0000000000000000000000000000000000000000..dbca397338115d028477838f4e9b61b17d7b4505
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/hugging_face/FL_HF_Character.py
@@ -0,0 +1,230 @@
+import sys
+import subprocess
+import importlib.util
+import os
+import time
+import threading
+import io
+
+# Check if huggingface_hub is installed, if not, install it
+if importlib.util.find_spec("huggingface_hub") is None:
+ print("huggingface_hub is not installed. Installing it now...")
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "huggingface_hub"])
+ print("huggingface_hub has been installed.")
+
+import torch
+from PIL import Image
+from huggingface_hub import HfApi, create_repo, repo_exists
+from tqdm import tqdm
+
+class FL_HF_Character:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "api_key": ("STRING", {"multiline": False}),
+ "owner": ("STRING", {"default": ""}),
+ "repo_name": ("STRING", {"default": "my-awesome-model"}),
+ "studio_name": ("STRING", {"default": ""}),
+ "project_name": ("STRING", {"default": ""}),
+ "character_name": ("STRING", {"default": ""}),
+ "create_new_repo": (["True", "False"],),
+ "repo_type": (["model", "dataset", "space"],),
+ },
+ "optional": {
+ "lora_file": ("STRING", {"default": ""}),
+ "dataset_zip": ("ZIP",),
+ "caption_layout": ("IMAGE",),
+ "caption_PDF_layout": ("PDF",),
+ "csv_file": ("CSV",),
+ }
+ }
+
+ RETURN_TYPES = ("STRING",)
+ FUNCTION = "upload_to_hub"
+ CATEGORY = "🏵️Fill Nodes/Hugging Face"
+
+ def upload_to_hub(self, api_key: str, owner: str, repo_name: str, studio_name: str, project_name: str,
+ character_name: str, create_new_repo: str, repo_type: str,
+ lora_file: str = "", dataset_zip: bytes = None,
+ caption_layout: torch.Tensor = None, caption_PDF_layout: bytes = None,
+ csv_file: bytes = None) -> tuple[str]:
+ # Initialize Hugging Face API
+ api = HfApi(token=api_key)
+
+ try:
+ # Construct full repo_id
+ full_repo_id = f"{owner}/{repo_name}"
+
+ # Step 1: Create a new repository or check if it exists
+ create_new_repo = create_new_repo == "True"
+ if create_new_repo:
+ repo_url = create_repo(repo_id=full_repo_id, token=api_key, exist_ok=True, repo_type=repo_type)
+ print(f"Repository created or already exists: {repo_url}")
+ else:
+ if not repo_exists(repo_id=full_repo_id, token=api_key):
+ return (f"Error: Repository {full_repo_id} does not exist. Please create it first or use the 'Create New Repo' option.",)
+ repo_url = f"https://huggingface.co/{full_repo_id}"
+ print(f"Using existing repository: {repo_url}")
+
+ # Step 2: Create directory structure
+ base_path = f"{studio_name}/{project_name}/{character_name}"
+
+ # Step 3: Upload files
+ if lora_file:
+ self.upload_file_with_progress(api, lora_file, f"{base_path}/lora", full_repo_id, api_key, "LoRA")
+ if dataset_zip is not None:
+ self.upload_zip(api, dataset_zip, f"{base_path}/dataset", full_repo_id, api_key, "Dataset")
+ if caption_layout is not None:
+ self.upload_image(api, caption_layout, base_path, full_repo_id, api_key, "caption_layout")
+ if caption_PDF_layout is not None:
+ self.upload_pdf(api, caption_PDF_layout, base_path, full_repo_id, api_key, "caption_PDF_layout")
+ if csv_file is not None:
+ self.upload_csv(api, csv_file, base_path, full_repo_id, api_key)
+
+ return (f"Successfully uploaded to {repo_url}/{base_path}",)
+
+ except Exception as e:
+ return (f"Error: {str(e)}",)
+
+ def upload_file_with_progress(self, api, file_path, repo_dir, full_repo_id, api_key, file_type):
+ if file_path and os.path.exists(file_path):
+ file_size = os.path.getsize(file_path)
+ file_name = os.path.basename(file_path)
+ repo_path = f"{repo_dir}/{file_name}"
+
+ pbar = tqdm(total=100, unit='%', desc=f"Uploading {file_type} file")
+
+ def update_progress():
+ progress = 0
+ while progress < 95:
+ time.sleep(0.5)
+ increment = min(5, 95 - progress)
+ progress += increment
+ pbar.update(increment)
+
+ progress_thread = threading.Thread(target=update_progress)
+ progress_thread.start()
+
+ with open(file_path, 'rb') as file:
+ api.upload_file(
+ path_or_fileobj=file,
+ path_in_repo=repo_path,
+ repo_id=full_repo_id,
+ token=api_key
+ )
+
+ progress_thread.join()
+ pbar.update(100 - pbar.n)
+ pbar.close()
+
+ print(f"{file_type} file uploaded successfully to {repo_path}")
+ elif file_path:
+ print(f"Error: {file_type} file not found at {file_path}")
+
+ def upload_zip(self, api, zip_data, repo_dir, full_repo_id, api_key, file_type):
+ repo_path = f"{repo_dir}/dataset.zip"
+
+ pbar = tqdm(total=100, unit='%', desc=f"Uploading {file_type} ZIP")
+
+ def update_progress():
+ progress = 0
+ while progress < 95:
+ time.sleep(0.5)
+ increment = min(5, 95 - progress)
+ progress += increment
+ pbar.update(increment)
+
+ progress_thread = threading.Thread(target=update_progress)
+ progress_thread.start()
+
+ api.upload_file(
+ path_or_fileobj=zip_data,
+ path_in_repo=repo_path,
+ repo_id=full_repo_id,
+ token=api_key
+ )
+
+ progress_thread.join()
+ pbar.update(100 - pbar.n)
+ pbar.close()
+
+ print(f"{file_type} ZIP uploaded successfully to {repo_path}")
+
+ def upload_image(self, api, image, repo_dir, full_repo_id, api_key, image_type):
+ img = Image.fromarray((image.squeeze().cpu().numpy() * 255).astype('uint8'))
+ img_byte_arr = io.BytesIO()
+ img.save(img_byte_arr, format='PNG')
+ img_byte_arr = img_byte_arr.getvalue()
+
+ repo_path = f"{repo_dir}/{image_type}.png"
+ api.upload_file(
+ path_or_fileobj=img_byte_arr,
+ path_in_repo=repo_path,
+ repo_id=full_repo_id,
+ token=api_key
+ )
+ print(f"{image_type} uploaded successfully")
+
+ def upload_pdf(self, api, pdf_data, repo_dir, full_repo_id, api_key, pdf_type):
+ repo_path = f"{repo_dir}/{pdf_type}.pdf"
+
+ pbar = tqdm(total=100, unit='%', desc=f"Uploading {pdf_type} PDF")
+
+ def update_progress():
+ progress = 0
+ while progress < 95:
+ time.sleep(0.5)
+ increment = min(5, 95 - progress)
+ progress += increment
+ pbar.update(increment)
+
+ progress_thread = threading.Thread(target=update_progress)
+ progress_thread.start()
+
+ api.upload_file(
+ path_or_fileobj=pdf_data,
+ path_in_repo=repo_path,
+ repo_id=full_repo_id,
+ token=api_key
+ )
+
+ progress_thread.join()
+ pbar.update(100 - pbar.n)
+ pbar.close()
+
+ print(f"{pdf_type} PDF uploaded successfully to {repo_path}")
+
+ def upload_csv(self, api, csv_data, repo_dir, full_repo_id, api_key):
+ repo_path = f"{repo_dir}/metadata.csv"
+
+ pbar = tqdm(total=100, unit='%', desc="Uploading CSV file")
+
+ def update_progress():
+ progress = 0
+ while progress < 95:
+ time.sleep(0.5)
+ increment = min(5, 95 - progress)
+ progress += increment
+ pbar.update(increment)
+
+ progress_thread = threading.Thread(target=update_progress)
+ progress_thread.start()
+
+ api.upload_file(
+ path_or_fileobj=csv_data,
+ path_in_repo=repo_path,
+ repo_id=full_repo_id,
+ token=api_key
+ )
+
+ progress_thread.join()
+ pbar.update(100 - pbar.n)
+ pbar.close()
+
+ print(f"CSV file uploaded successfully to {repo_path}")
+
+ @classmethod
+ def IS_CHANGED(cls, api_key, owner, repo_name, studio_name, project_name, character_name,
+ create_new_repo, repo_type, lora_file, dataset_zip, caption_layout, caption_PDF_layout, csv_file):
+ return float("NaN")
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/hugging_face/FL_HF_UploaderAbsolute.py b/comfyui_fill-nodes/nodes/hugging_face/FL_HF_UploaderAbsolute.py
new file mode 100644
index 0000000000000000000000000000000000000000..39f3a93c73275c871fadcb4f35b2e4940b472164
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/hugging_face/FL_HF_UploaderAbsolute.py
@@ -0,0 +1,232 @@
+import sys
+import subprocess
+import importlib.util
+import os
+import time
+import threading
+import io
+
+# Check if huggingface_hub is installed, if not, install it
+if importlib.util.find_spec("huggingface_hub") is None:
+ print("huggingface_hub is not installed. Installing it now...")
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "huggingface_hub"])
+ print("huggingface_hub has been installed.")
+
+import torch
+from PIL import Image
+from huggingface_hub import HfApi, create_repo, repo_exists
+from tqdm import tqdm
+
+class FL_HF_UploaderAbsolute:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "owner": ("STRING", {"default": ""}),
+ "repo_name": ("STRING", {"default": "my-awesome-model"}),
+ "upload_path": ("STRING", {"default": "folder1/folder2/folder3"}),
+ "create_new_repo": (["True", "False"],),
+ "repo_type": (["model", "dataset", "space"],),
+ },
+ "optional": {
+ "lora_file": ("STRING", {"default": ""}),
+ "dataset_zip": ("ZIP",),
+ "caption_layout": ("IMAGE",),
+ "caption_PDF_layout": ("PDF",),
+ "csv_file": ("CSV",),
+ }
+ }
+
+ RETURN_TYPES = ("STRING",)
+ FUNCTION = "upload_to_hub"
+ CATEGORY = "🏵️Fill Nodes/Hugging Face"
+
+ def upload_to_hub(self, owner: str, repo_name: str, upload_path: str,
+ create_new_repo: str, repo_type: str,
+ lora_file: str = "", dataset_zip: bytes = None,
+ caption_layout: torch.Tensor = None, caption_PDF_layout: bytes = None,
+ csv_file: bytes = None) -> tuple[str]:
+ # Get API key from environment variable
+ api_key = os.environ.get("HUGGINGFACE_API_KEY")
+ if not api_key:
+ return ("Error: HUGGINGFACE_API_KEY not found in environment variables.",)
+
+ # Initialize Hugging Face API
+ api = HfApi(token=api_key)
+
+ try:
+ # Construct full repo_id
+ full_repo_id = f"{owner}/{repo_name}"
+
+ # Step 1: Create a new repository or check if it exists
+ create_new_repo = create_new_repo == "True"
+ if create_new_repo:
+ repo_url = create_repo(repo_id=full_repo_id, token=api_key, exist_ok=True, repo_type=repo_type)
+ print(f"Repository created or already exists: {repo_url}")
+ else:
+ if not repo_exists(repo_id=full_repo_id, token=api_key):
+ return (f"Error: Repository {full_repo_id} does not exist. Please create it first or use the 'Create New Repo' option.",)
+ repo_url = f"https://huggingface.co/{full_repo_id}"
+ print(f"Using existing repository: {repo_url}")
+
+ # Ensure upload_path doesn't start or end with '/'
+ upload_path = upload_path.strip('/')
+
+ # Step 2: Upload files
+ if lora_file:
+ self.upload_file_with_progress(api, lora_file, f"{upload_path}", full_repo_id, api_key, "LoRA")
+ if dataset_zip is not None:
+ self.upload_zip(api, dataset_zip, f"{upload_path}", full_repo_id, api_key, "Dataset")
+ if caption_layout is not None:
+ self.upload_image(api, caption_layout, upload_path, full_repo_id, api_key, "caption_layout")
+ if caption_PDF_layout is not None:
+ self.upload_pdf(api, caption_PDF_layout, upload_path, full_repo_id, api_key, "caption_PDF_layout")
+ if csv_file is not None:
+ self.upload_csv(api, csv_file, upload_path, full_repo_id, api_key)
+
+ return (f"Successfully uploaded to {repo_url}/{upload_path}",)
+
+ except Exception as e:
+ return (f"Error: {str(e)}",)
+
+ def upload_file_with_progress(self, api, file_path, repo_dir, full_repo_id, api_key, file_type):
+ if file_path and os.path.exists(file_path):
+ file_size = os.path.getsize(file_path)
+ file_name = os.path.basename(file_path)
+ repo_path = f"{repo_dir}/{file_name}"
+
+ pbar = tqdm(total=100, unit='%', desc=f"Uploading {file_type} file")
+
+ def update_progress():
+ progress = 0
+ while progress < 95:
+ time.sleep(0.5)
+ increment = min(5, 95 - progress)
+ progress += increment
+ pbar.update(increment)
+
+ progress_thread = threading.Thread(target=update_progress)
+ progress_thread.start()
+
+ with open(file_path, 'rb') as file:
+ api.upload_file(
+ path_or_fileobj=file,
+ path_in_repo=repo_path,
+ repo_id=full_repo_id,
+ token=api_key
+ )
+
+ progress_thread.join()
+ pbar.update(100 - pbar.n)
+ pbar.close()
+
+ print(f"{file_type} file uploaded successfully to {repo_path}")
+ elif file_path:
+ print(f"Error: {file_type} file not found at {file_path}")
+
+ def upload_zip(self, api, zip_data, repo_dir, full_repo_id, api_key, file_type):
+ repo_path = f"{repo_dir}/dataset.zip"
+
+ pbar = tqdm(total=100, unit='%', desc=f"Uploading {file_type} ZIP")
+
+ def update_progress():
+ progress = 0
+ while progress < 95:
+ time.sleep(0.5)
+ increment = min(5, 95 - progress)
+ progress += increment
+ pbar.update(increment)
+
+ progress_thread = threading.Thread(target=update_progress)
+ progress_thread.start()
+
+ api.upload_file(
+ path_or_fileobj=zip_data,
+ path_in_repo=repo_path,
+ repo_id=full_repo_id,
+ token=api_key
+ )
+
+ progress_thread.join()
+ pbar.update(100 - pbar.n)
+ pbar.close()
+
+ print(f"{file_type} ZIP uploaded successfully to {repo_path}")
+
+ def upload_image(self, api, image, repo_dir, full_repo_id, api_key, image_type):
+ img = Image.fromarray((image.squeeze().cpu().numpy() * 255).astype('uint8'))
+ img_byte_arr = io.BytesIO()
+ img.save(img_byte_arr, format='PNG')
+ img_byte_arr = img_byte_arr.getvalue()
+
+ repo_path = f"{repo_dir}/{image_type}.png"
+ api.upload_file(
+ path_or_fileobj=img_byte_arr,
+ path_in_repo=repo_path,
+ repo_id=full_repo_id,
+ token=api_key
+ )
+ print(f"{image_type} uploaded successfully")
+
+ def upload_pdf(self, api, pdf_data, repo_dir, full_repo_id, api_key, pdf_type):
+ repo_path = f"{repo_dir}/{pdf_type}.pdf"
+
+ pbar = tqdm(total=100, unit='%', desc=f"Uploading {pdf_type} PDF")
+
+ def update_progress():
+ progress = 0
+ while progress < 95:
+ time.sleep(0.5)
+ increment = min(5, 95 - progress)
+ progress += increment
+ pbar.update(increment)
+
+ progress_thread = threading.Thread(target=update_progress)
+ progress_thread.start()
+
+ api.upload_file(
+ path_or_fileobj=pdf_data,
+ path_in_repo=repo_path,
+ repo_id=full_repo_id,
+ token=api_key
+ )
+
+ progress_thread.join()
+ pbar.update(100 - pbar.n)
+ pbar.close()
+
+ print(f"{pdf_type} PDF uploaded successfully to {repo_path}")
+
+ def upload_csv(self, api, csv_data, repo_dir, full_repo_id, api_key):
+ repo_path = f"{repo_dir}/metadata.csv"
+
+ pbar = tqdm(total=100, unit='%', desc="Uploading CSV file")
+
+ def update_progress():
+ progress = 0
+ while progress < 95:
+ time.sleep(0.5)
+ increment = min(5, 95 - progress)
+ progress += increment
+ pbar.update(increment)
+
+ progress_thread = threading.Thread(target=update_progress)
+ progress_thread.start()
+
+ api.upload_file(
+ path_or_fileobj=csv_data,
+ path_in_repo=repo_path,
+ repo_id=full_repo_id,
+ token=api_key
+ )
+
+ progress_thread.join()
+ pbar.update(100 - pbar.n)
+ pbar.close()
+
+ print(f"CSV file uploaded successfully to {repo_path}")
+
+ @classmethod
+ def IS_CHANGED(cls, owner, repo_name, upload_path, create_new_repo, repo_type,
+ lora_file, dataset_zip, caption_layout, caption_PDF_layout, csv_file):
+ return float("NaN")
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/hugging_face/__pycache__/FL_HFDatasetDownloader.cpython-310.pyc b/comfyui_fill-nodes/nodes/hugging_face/__pycache__/FL_HFDatasetDownloader.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..25617a991fd66848fd69d7eebb72c5fed4f32603
Binary files /dev/null and b/comfyui_fill-nodes/nodes/hugging_face/__pycache__/FL_HFDatasetDownloader.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/hugging_face/__pycache__/FL_HFHubModelUploader.cpython-310.pyc b/comfyui_fill-nodes/nodes/hugging_face/__pycache__/FL_HFHubModelUploader.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..baae23818bf4ca3cc520d8e17ed19ef69975e8c5
Binary files /dev/null and b/comfyui_fill-nodes/nodes/hugging_face/__pycache__/FL_HFHubModelUploader.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/hugging_face/__pycache__/FL_HF_Character.cpython-310.pyc b/comfyui_fill-nodes/nodes/hugging_face/__pycache__/FL_HF_Character.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c508936671d7c87487c64a5f5fdf3df91545ca8a
Binary files /dev/null and b/comfyui_fill-nodes/nodes/hugging_face/__pycache__/FL_HF_Character.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/hugging_face/__pycache__/FL_HF_UploaderAbsolute.cpython-310.pyc b/comfyui_fill-nodes/nodes/hugging_face/__pycache__/FL_HF_UploaderAbsolute.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..321cf72bd6ceb81dcaf3d47582f7be070220e377
Binary files /dev/null and b/comfyui_fill-nodes/nodes/hugging_face/__pycache__/FL_HF_UploaderAbsolute.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/hugging_face/__pycache__/__init__.cpython-310.pyc b/comfyui_fill-nodes/nodes/hugging_face/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8526419d6c87077b171b5b07e59b400eddf993a9
Binary files /dev/null and b/comfyui_fill-nodes/nodes/hugging_face/__pycache__/__init__.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/FL_AnimeLineExtractor.py b/comfyui_fill-nodes/nodes/image/FL_AnimeLineExtractor.py
new file mode 100644
index 0000000000000000000000000000000000000000..869322200b24da117cb4de3dc8614595521052e2
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_AnimeLineExtractor.py
@@ -0,0 +1,112 @@
+import torch
+import numpy as np
+from PIL import Image
+import cv2
+import comfy.model_management
+
+
+class FL_AnimeLineExtractor:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "image": ("IMAGE", {}),
+ "line_threshold": ("FLOAT", {
+ "default": 0.4,
+ "min": 0.0,
+ "max": 1.0,
+ "step": 0.01,
+ "display": "slider"
+ }),
+ "line_width": ("INT", {
+ "default": 1,
+ "min": 1,
+ "max": 5,
+ "step": 1
+ }),
+ "detail_level": ("FLOAT", {
+ "default": 0.5,
+ "min": 0.1,
+ "max": 1.0,
+ "step": 0.01,
+ "display": "slider"
+ }),
+ "noise_reduction": ("FLOAT", {
+ "default": 0.3,
+ "min": 0.0,
+ "max": 1.0,
+ "step": 0.01,
+ "display": "slider"
+ }),
+ "invert_output": ("BOOLEAN", {
+ "default": False,
+ "label": "White Background"
+ })
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "extract_lines"
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def extract_lines(self, image, line_threshold, line_width, detail_level, noise_reduction, invert_output):
+ if isinstance(image, torch.Tensor):
+ image = (image.cpu().numpy() * 255).astype(np.uint8)
+
+ if len(image.shape) == 4:
+ processed_images = []
+ for img in image:
+ processed = self._process_single_image(img, line_threshold, line_width, detail_level, noise_reduction,
+ invert_output)
+ processed_images.append(processed)
+ result = np.stack(processed_images)
+ else:
+ result = self._process_single_image(image, line_threshold, line_width, detail_level, noise_reduction,
+ invert_output)
+
+ return (torch.from_numpy(result.astype(np.float32) / 255.0),)
+
+ def _process_single_image(self, img, line_threshold, line_width, detail_level, noise_reduction, invert_output):
+ # Convert to grayscale
+ gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
+
+ # Apply noise reduction (Gaussian blur)
+ if noise_reduction > 0:
+ blur_radius = int(noise_reduction * 10)
+ if blur_radius % 2 == 0:
+ blur_radius += 1
+ gray = cv2.GaussianBlur(gray, (blur_radius, blur_radius), 0)
+
+ # Calculate adaptive threshold parameters
+ block_size = int((1 - detail_level) * 50) + 11
+ if block_size % 2 == 0:
+ block_size += 1
+
+ # Apply adaptive thresholding
+ binary = cv2.adaptiveThreshold(
+ gray,
+ 255,
+ cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
+ cv2.THRESH_BINARY_INV,
+ block_size,
+ int(line_threshold * 20)
+ )
+
+ # Clean up small noise
+ kernel_size = max(1, int((1 - detail_level) * 3))
+ kernel = np.ones((kernel_size, kernel_size), np.uint8)
+ binary = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)
+
+ # Adjust line width
+ if line_width > 1:
+ kernel = np.ones((line_width, line_width), np.uint8)
+ binary = cv2.dilate(binary, kernel, iterations=1)
+
+ # Invert if requested
+ if invert_output:
+ binary = cv2.bitwise_not(binary)
+
+ # Convert back to RGB
+ lines_rgb = cv2.cvtColor(binary, cv2.COLOR_GRAY2RGB)
+
+ return lines_rgb
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_ApplyMask.py b/comfyui_fill-nodes/nodes/image/FL_ApplyMask.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b95fc17ee3c704dde649143b57c95a77fce8b9c
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_ApplyMask.py
@@ -0,0 +1,87 @@
+import torch
+
+
+class FL_ApplyMask:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "mask": ("MASK",),
+ "crop_to_mask": ("BOOLEAN", {"default": False, "description": "Crop image to mask bounding box"}),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "apply_mask"
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def apply_mask(self, image, mask, crop_to_mask=False):
+ # Ensure the image is in the correct format (B, H, W, C)
+ if len(image.shape) == 3:
+ image = image.unsqueeze(0)
+
+ # Ensure the mask is in the correct format (B, H, W)
+ if len(mask.shape) == 2:
+ mask = mask.unsqueeze(0)
+ elif len(mask.shape) == 3 and mask.shape[2] == 1:
+ mask = mask.squeeze(-1)
+
+ # Ensure mask and image have the same batch size
+ if mask.shape[0] == 1 and image.shape[0] > 1:
+ mask = mask.repeat(image.shape[0], 1, 1)
+
+ # Ensure mask and image have the same spatial dimensions
+ if mask.shape[1:] != image.shape[1:3]:
+ mask = torch.nn.functional.interpolate(mask.unsqueeze(1).float(), size=image.shape[1:3],
+ mode='nearest').squeeze(1)
+
+ # Normalize mask to 0-1 range if it's not already
+ if mask.max() > 1:
+ mask = mask / 255.0
+
+ # Add alpha channel to the image if it doesn't exist
+ if image.shape[3] == 3:
+ alpha = torch.ones((image.shape[0], image.shape[1], image.shape[2], 1), device=image.device)
+ image = torch.cat([image, alpha], dim=3)
+
+ # Apply the mask to the alpha channel
+ image[:, :, :, 3] = mask
+
+ # Crop to mask bounding box if enabled
+ if crop_to_mask:
+ # Process each image in the batch
+ cropped_images = []
+ for b in range(image.shape[0]):
+ # Find bounding box of non-zero mask values
+ mask_b = mask[b]
+ nonzero = torch.nonzero(mask_b > 0)
+
+ if nonzero.numel() > 0:
+ # Get min/max coordinates
+ y_min = nonzero[:, 0].min().item()
+ y_max = nonzero[:, 0].max().item() + 1
+ x_min = nonzero[:, 1].min().item()
+ x_max = nonzero[:, 1].max().item() + 1
+
+ # Crop the image
+ cropped = image[b, y_min:y_max, x_min:x_max, :]
+ cropped_images.append(cropped.unsqueeze(0))
+ else:
+ # If mask is empty, keep original image
+ cropped_images.append(image[b].unsqueeze(0))
+
+ # Stack cropped images (note: may have different sizes if masks differ)
+ if len(cropped_images) == 1:
+ image = cropped_images[0]
+ else:
+ # If all images have the same size, stack them
+ shapes = [img.shape for img in cropped_images]
+ if all(s == shapes[0] for s in shapes):
+ image = torch.cat(cropped_images, dim=0)
+ else:
+ # Different sizes - return first one or handle differently
+ # For now, return the first cropped image
+ image = cropped_images[0]
+
+ return (image,)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_BlackFrameReject.py b/comfyui_fill-nodes/nodes/image/FL_BlackFrameReject.py
new file mode 100644
index 0000000000000000000000000000000000000000..b80bdbff3fb7517eef99524e2f11736594dc1eb6
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_BlackFrameReject.py
@@ -0,0 +1,127 @@
+import torch
+import numpy as np
+from comfy.utils import ProgressBar
+
+
+class FL_BlackFrameReject:
+ """
+ A node that filters out images from a batch based on the percentage of black pixels.
+ Images with a black pixel percentage above the threshold are rejected.
+ """
+
+ RETURN_TYPES = ("IMAGE", "INT", "INT",)
+ RETURN_NAMES = ("filtered_images", "kept_count", "rejected_count",)
+ FUNCTION = "reject_black_frames"
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ DESCRIPTION = """
+ FL_BlackFrameReject analyzes each image in a batch to detect the percentage of black pixels.
+ Images with black pixel percentage exceeding the specified threshold are removed from the batch.
+ Returns the filtered batch of images and counts of kept and rejected images.
+ Useful for removing black frames, fades to black, or images with excessive dark regions.
+ """
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "images": ("IMAGE",),
+ "threshold": ("FLOAT", {"default": 95.0, "min": 0.0, "max": 100.0, "step": 0.1,
+ "description": "Percentage of black pixels needed to reject an image (0-100)"}),
+ "black_level": ("FLOAT", {"default": 0.05, "min": 0.0, "max": 0.5, "step": 0.01,
+ "description": "Pixel brightness threshold to consider a pixel as black (0.0-0.5)"})
+ },
+ "optional": {
+ "channels": (["all", "average", "luminance", "rgb"], {"default": "luminance",
+ "description": "Channel(s) to analyze for black pixels"}),
+ "invert": ("BOOLEAN", {"default": False,
+ "description": "If True, reject frames with LESS than threshold % of black pixels"}),
+ "show_progress": ("BOOLEAN", {"default": True,
+ "description": "Show progress bar during processing"})
+ }
+ }
+
+ def reject_black_frames(self, images: torch.Tensor, threshold: float, black_level: float,
+ channels: str = "luminance", invert: bool = False,
+ show_progress: bool = True) -> tuple:
+ """
+ Filters out images from a batch based on the percentage of black pixels.
+
+ Args:
+ images: Batch of images as a tensor (B, H, W, C)
+ threshold: Percentage threshold for black pixels to reject an image (0-100)
+ black_level: Maximum pixel value to consider as black (0.0-0.5)
+ channels: Which channels to analyze for black pixels
+ invert: If True, reject frames with less than threshold % of black pixels
+ show_progress: Show progress bar during processing
+
+ Returns:
+ Tuple of (filtered_images, kept_count, rejected_count)
+ """
+ batch_size = images.shape[0]
+
+ # Early return if batch is empty
+ if batch_size == 0:
+ return images, 0, 0
+
+ # Initialize progress bar if enabled
+ if show_progress:
+ pbar = ProgressBar(batch_size)
+ print(f"[FL_BlackFrameReject] Analyzing {batch_size} images for black pixel content...")
+
+ # Compute black pixel percentages for each image
+ black_percentages = []
+ keep_indices = []
+
+ for i in range(batch_size):
+ img = images[i]
+
+ # Different methods to calculate black pixels based on selected channels
+ if channels == "all":
+ # Check if all RGB channels are below black_level
+ black_mask = torch.all(img <= black_level, dim=2)
+ elif channels == "average":
+ # Use average of all channels
+ black_mask = torch.mean(img, dim=2) <= black_level
+ elif channels == "luminance":
+ # Use luminance formula (perceived brightness)
+ # Y = 0.2126*R + 0.7152*G + 0.0722*B
+ luminance = img[..., 0] * 0.2126 + img[..., 1] * 0.7152 + img[..., 2] * 0.0722
+ black_mask = luminance <= black_level
+ else: # "rgb"
+ # Check if any RGB channel is below black_level
+ black_mask = torch.any(img <= black_level, dim=2)
+
+ # Calculate percentage of black pixels
+ black_percentage = torch.mean(black_mask.float()) * 100
+ black_percentages.append(black_percentage.item())
+
+ # Determine if image should be kept based on threshold and invert flag
+ keep_image = black_percentage < threshold if not invert else black_percentage >= threshold
+
+ if keep_image:
+ keep_indices.append(i)
+
+ # Update progress bar
+ if show_progress:
+ pbar.update_absolute(i + 1)
+
+ # Create filtered batch
+ if len(keep_indices) > 0:
+ filtered_images = images[keep_indices]
+ else:
+ # Return empty tensor with correct dimensions if all images are rejected
+ filtered_images = torch.zeros((0,) + images.shape[1:], dtype=images.dtype, device=images.device)
+
+ # Calculate stats
+ kept_count = len(keep_indices)
+ rejected_count = batch_size - kept_count
+
+ # Print summary
+ print(f"[FL_BlackFrameReject] Kept {kept_count}/{batch_size} images, rejected {rejected_count} images")
+
+ if kept_count > 0:
+ print(
+ f"[FL_BlackFrameReject] Black pixel range in kept images: {min([black_percentages[i] for i in keep_indices]):.2f}% - {max([black_percentages[i] for i in keep_indices]):.2f}%")
+
+ return filtered_images, kept_count, rejected_count
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_CoTracker.py b/comfyui_fill-nodes/nodes/image/FL_CoTracker.py
new file mode 100644
index 0000000000000000000000000000000000000000..37bbfd544dfb66fae73116a8ec0a82ec31089448
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_CoTracker.py
@@ -0,0 +1,505 @@
+import torch
+import numpy as np
+import json
+import cv2
+from PIL import Image
+import torchvision.transforms as transforms
+import gc
+from typing import Tuple, Optional, List
+
+import comfy.model_management as mm
+
+
+# ── Trajectory integration (inlined from cotracker_node/trajectory_integration.py) ──
+
+def create_mask_from_tracks(forward_tracks, forward_visibility, frame_shape, radius=10, frame_idx=None):
+ H, W = frame_shape
+
+ if frame_idx is not None:
+ mask = np.zeros((H, W), dtype=np.uint8)
+ points = forward_tracks[frame_idx]
+ visibility = forward_visibility[frame_idx]
+ valid_points = points[visibility > 0]
+ for point in valid_points:
+ x, y = int(point[0]), int(point[1])
+ if 0 <= x < W and 0 <= y < H:
+ cv2.circle(mask, (x, y), radius, 1, -1)
+ return mask
+ else:
+ T = forward_tracks.shape[0]
+ masks = np.zeros((T, H, W), dtype=np.uint8)
+ for t in range(T):
+ points = forward_tracks[t]
+ visibility = forward_visibility[t]
+ valid_points = points[visibility > 0]
+ for point in valid_points:
+ x, y = int(point[0]), int(point[1])
+ if 0 <= x < W and 0 <= y < H:
+ cv2.circle(masks[t], (x, y), radius, 1, -1)
+ return masks
+
+
+def detect_empty_regions(forward_tracks, forward_visibility, frame_shape, frame_idx, radius=10, min_region_size=100):
+ mask = create_mask_from_tracks(forward_tracks, forward_visibility, frame_shape, radius, frame_idx)
+ empty_mask = 1 - mask
+ contours, _ = cv2.findContours(empty_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
+ empty_regions = []
+ for contour in contours:
+ area = cv2.contourArea(contour)
+ if area >= min_region_size:
+ x, y, w, h = cv2.boundingRect(contour)
+ empty_regions.append((x, y, w, h))
+ return empty_regions
+
+
+def has_data_in_region(backward_tracks, backward_visibility, spatial_region, frame_idx, min_points=1):
+ x, y, w, h = spatial_region
+ points = backward_tracks[frame_idx]
+ visibility = backward_visibility[frame_idx]
+ valid_points = points[visibility > 0]
+ if len(valid_points) == 0:
+ return False
+ in_region = ((valid_points[:, 0] >= x) & (valid_points[:, 0] < x + w) &
+ (valid_points[:, 1] >= y) & (valid_points[:, 1] < y + h))
+ return np.sum(in_region) >= min_points
+
+
+def extract_trajectory_with_indices(tracks, visibility, spatial_region, frame_idx):
+ x, y, w, h = spatial_region
+ points = tracks[frame_idx]
+ vis = visibility[frame_idx]
+ valid_mask = vis > 0
+ in_region_mask = ((points[:, 0] >= x) & (points[:, 0] < x + w) &
+ (points[:, 1] >= y) & (points[:, 1] < y + h))
+ selected_indices = np.where(valid_mask & in_region_mask)[0]
+ if len(selected_indices) == 0:
+ return np.empty((tracks.shape[0], 0, 2)), np.empty((tracks.shape[0], 0)), []
+ extracted_tracks = tracks[:, selected_indices, :]
+ extracted_visibility = visibility[:, selected_indices]
+ return extracted_tracks, extracted_visibility, selected_indices.tolist()
+
+
+def time_reverse(tracks, visibility):
+ return np.flip(tracks, axis=0), np.flip(visibility, axis=0)
+
+
+def integrate_tracking_results(forward_tracks, forward_visibility,
+ backward_tracks, backward_visibility,
+ frame_shape, radius=10, min_region_size=100,
+ min_points=1, output_dir=None):
+ T = forward_tracks.shape[0]
+ backward_tracks, backward_visibility = time_reverse(backward_tracks, backward_visibility)
+
+ integrated_tracks_list = [forward_tracks]
+ integrated_visibility_list = [forward_visibility]
+ global_used_indices = set()
+
+ for frame_idx in range(T):
+ print(f"Processing frame {frame_idx}...")
+ current_integrated_tracks = np.concatenate(integrated_tracks_list, axis=1)
+ current_integrated_visibility = np.concatenate(integrated_visibility_list, axis=1)
+
+ empty_regions = detect_empty_regions(
+ current_integrated_tracks, current_integrated_visibility,
+ frame_shape, frame_idx, radius, min_region_size
+ )
+ print(f" Found {len(empty_regions)} empty regions")
+
+ frame_new_tracks = []
+ frame_new_visibility = []
+
+ for region_idx, spatial_region in enumerate(empty_regions):
+ available_indices = [i for i in range(backward_tracks.shape[1]) if i not in global_used_indices]
+ if len(available_indices) == 0:
+ print(f" Region {region_idx}: No more available backward tracks")
+ continue
+
+ available_backward_tracks = backward_tracks[:, available_indices, :]
+ available_backward_visibility = backward_visibility[:, available_indices]
+
+ if has_data_in_region(available_backward_tracks, available_backward_visibility, spatial_region, frame_idx, min_points):
+ backward_trajectory, backward_vis, local_extracted_indices = extract_trajectory_with_indices(
+ available_backward_tracks, available_backward_visibility, spatial_region, frame_idx
+ )
+ if backward_trajectory.shape[1] > 0:
+ global_extracted_indices = [available_indices[i] for i in local_extracted_indices]
+ print(f" Region {region_idx}: Extracted {len(global_extracted_indices)} tracks: {global_extracted_indices}")
+ frame_new_tracks.append(backward_trajectory)
+ frame_new_visibility.append(backward_vis)
+ global_used_indices.update(global_extracted_indices)
+ print(f" Total used indices so far: {len(global_used_indices)}")
+ else:
+ print(f" Region {region_idx}: No backward data found")
+
+ if frame_new_tracks:
+ integrated_tracks_list.extend(frame_new_tracks)
+ integrated_visibility_list.extend(frame_new_visibility)
+
+ integrated_tracks = np.concatenate(integrated_tracks_list, axis=1)
+ integrated_visibility = np.concatenate(integrated_visibility_list, axis=1)
+
+ print(f"\nFinal summary:")
+ print(f"Used backward track indices: {sorted(global_used_indices)}")
+ print(f"Total backward tracks used: {len(global_used_indices)}")
+ print(f"Original backward tracks: {backward_tracks.shape[1]}")
+ print(f"Final integrated tracks shape: {integrated_tracks.shape}")
+
+ return integrated_tracks, integrated_visibility
+
+
+def trajectory_integration(forward_tracks, forward_visibility, backward_tracks, backward_visibility, frame_shape, grid_size):
+ ft = forward_tracks.squeeze(0).cpu().numpy()
+ fv = forward_visibility.squeeze(0).cpu().numpy()
+ bt = backward_tracks.squeeze(0).cpu().numpy()
+ bv = backward_visibility.squeeze(0).cpu().numpy()
+
+ radius = min(frame_shape) / grid_size * 1.5
+ radius = max(int(round(radius)), 3)
+ min_region_size = radius ** 2
+
+ t, v = integrate_tracking_results(ft, fv, bt, bv, frame_shape,
+ radius=radius, min_region_size=min_region_size, min_points=1, output_dir=None)
+
+ t = torch.from_numpy(t).float().unsqueeze(0)
+ v = torch.from_numpy(v).float().unsqueeze(0)
+ return t, v
+
+
+# ── Main node ──
+
+class FL_CoTracker:
+
+ def __init__(self):
+ self.device = mm.get_torch_device()
+ self.offload_device = mm.unet_offload_device()
+ self.model = None
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "images": ("IMAGE",),
+ "tracking_points": ("STRING", {
+ "default": "",
+ "multiline": True,
+ "placeholder": "Enter x and y coordinates separated by a newline. This is optional — normally not needed, as points with large motion are selected automatically. \nExample:\n500,300\n200,250"
+ }),
+ "grid_size": ("INT", {
+ "default": 20,
+ "min": 0,
+ "max": 100,
+ "step": 1,
+ "tooltip": "Number of divisions along both width and height to create a grid of tracking points."
+ }),
+ "max_num_of_points": ("INT", {
+ "default": 100,
+ "min": 1,
+ "max": 10000,
+ "step": 1
+ }),
+ },
+ "optional": {
+ "tracking_mask": ("MASK", {"tooltip": "Mask for grid coordinates"}),
+ "confidence_threshold": ("FLOAT", {
+ "default": 0.90,
+ "min": 0.0,
+ "max": 1.0,
+ "step": 0.01
+ }),
+ "min_distance": ("INT", {
+ "default": 30,
+ "min": 0,
+ "max": 500,
+ "step": 1,
+ "tooltip": "Minimum distance between tracking points"
+ }),
+ "force_offload": ("BOOLEAN", {"default": True}),
+ "enable_backward": ("BOOLEAN", {"default": False}),
+ }
+ }
+
+ RETURN_TYPES = ("STRING", "IMAGE")
+ RETURN_NAMES = ("tracking_results", "image_with_results")
+ FUNCTION = "track_points"
+ CATEGORY = "🏵️Fill Nodes/Image"
+ DESCRIPTION = "https://github.com/facebookresearch/co-tracker \nIf you get an OOM error, try lowering the `grid_size`."
+
+ def load_model(self, model_type):
+ try:
+ if self.model is None:
+ print(f"Loading CoTracker model: {model_type}")
+ self.model = torch.hub.load("facebookresearch/co-tracker", model_type).to(self.device)
+ self.model.to(self.device)
+ self.model.eval()
+ print("CoTracker model loaded successfully")
+ except Exception as e:
+ raise Exception(f"Failed to load CoTracker model: {str(e)}")
+
+ def parse_tracking_points(self, tracking_points_str):
+ points = []
+ lines = tracking_points_str.strip().split('\n')
+ for line in lines:
+ line = line.strip()
+ if line and ',' in line:
+ try:
+ x, y = line.split(',')
+ points.append([float(x.strip()), float(y.strip())])
+ except ValueError:
+ print(f"parse_tracking_points : Invalid point format: {line}")
+ continue
+ return np.array(points)
+
+ def preprocess_images(self, images):
+ if len(images.shape) == 4:
+ images = images.permute(0, 3, 1, 2)
+ images = images.unsqueeze(0)
+ images = images.float()
+ images = images * 255
+ return images.to(self.device)
+
+ def prepare_query_points(self, points, video_shape):
+ query_points_tensor = []
+ for x, y in points:
+ query_points_tensor.append([0, x, y])
+ query_points_tensor = torch.tensor(query_points_tensor, dtype=torch.float32)
+ query_points_tensor = query_points_tensor[None].to(self.device)
+ return query_points_tensor
+
+ def track_points(self, images, tracking_points, grid_size, max_num_of_points, tracking_mask=None, confidence_threshold=0.5, min_distance=60, force_offload=True, enable_backward=False):
+ self.load_model("cotracker3_online")
+
+ points = self.parse_tracking_points(tracking_points)
+ if len(points) == 0:
+ print("Info : No valid points found in tracking_points")
+
+ if tracking_mask is not None:
+ print(f"{tracking_mask.shape=}")
+
+ images_np = images.cpu().numpy()
+ images_np = np.ascontiguousarray((images_np * 255).astype(np.uint8))
+
+ video = self.preprocess_images(images)
+
+ queries = self.prepare_query_points(points, video.shape)
+
+ if video.shape[1] <= self.model.step:
+ print(f"{video.shape[1]=}")
+ raise ValueError(f"At least {self.model.step+1} frames are required to perform tracking.")
+
+ results = []
+
+ def _tracking(video, grid_size, queries, add_support_grid):
+ with torch.no_grad():
+ self.model(
+ video_chunk=video,
+ is_first_step=True,
+ grid_size=grid_size,
+ queries=queries,
+ add_support_grid=add_support_grid
+ )
+ for ind in range(0, video.shape[1] - self.model.step, self.model.step):
+ pred_tracks, pred_visibility = self.model(
+ video_chunk=video[:, ind : ind + self.model.step * 2],
+ is_first_step=False,
+ grid_size=grid_size,
+ queries=queries,
+ add_support_grid=add_support_grid
+ )
+ return pred_tracks, pred_visibility
+
+ if len(points) > 0:
+ print(f"forward - queries")
+ pred_tracks, pred_visibility = _tracking(video, 0, queries, True)
+ results, images_np = self.format_results(pred_tracks, pred_visibility, None, confidence_threshold, points, max_num_of_points, 1, images_np)
+ print(f"{len(results)=}")
+ if len(results) >= max_num_of_points:
+ return (results,)
+ max_num_of_points -= len(results)
+ else:
+ results = []
+
+ if grid_size > 0:
+ print(f"forward - grid")
+ pred_tracks, pred_visibility = _tracking(video, grid_size, None, False)
+ if enable_backward:
+ pred_tracks_b, pred_visibility_b = _tracking(video.flip(1), grid_size, None, False)
+ _, _, _, H, W = video.shape
+ pred_tracks, pred_visibility = trajectory_integration(pred_tracks, pred_visibility, pred_tracks_b, pred_visibility_b, (H, W), grid_size)
+ results2, images_np = self.format_results(pred_tracks, pred_visibility, tracking_mask, confidence_threshold, points, max_num_of_points, min_distance, images_np, enable_backward)
+ print(f"{len(results2)=}")
+ results = results + results2
+
+ images_with_markers = torch.from_numpy(images_np)
+ images_with_markers = images_with_markers.float() / 255.0
+
+ if force_offload:
+ self.model.to(self.offload_device)
+ mm.soft_empty_cache()
+ gc.collect()
+
+ return (results, images_with_markers)
+
+ def select_diverse_points(self, motion_sorted_indices, tracks, visibility, max_points, min_distance):
+ if len(motion_sorted_indices) == 0:
+ return []
+
+ selected_indices = []
+ representative_positions = {}
+
+ for point_idx in motion_sorted_indices:
+ valid_frames = visibility[:, point_idx] == True
+ if np.any(valid_frames):
+ valid_positions = tracks[valid_frames, point_idx]
+ representative_positions[point_idx] = np.mean(valid_positions, axis=0)
+ else:
+ representative_positions[point_idx] = np.mean(tracks[:, point_idx], axis=0)
+
+ for candidate_idx in motion_sorted_indices:
+ if len(selected_indices) >= max_points:
+ break
+ candidate_pos = representative_positions[candidate_idx]
+ too_close = False
+ for selected_idx in selected_indices:
+ selected_pos = representative_positions[selected_idx]
+ distance = np.linalg.norm(candidate_pos - selected_pos)
+ if distance < min_distance:
+ too_close = True
+ break
+ if not too_close:
+ selected_indices.append(candidate_idx)
+
+ return selected_indices
+
+ def select_points(self, tracks, visibility, vis_threshold=0.5, max_points=9, min_distance=60):
+ n_frames, n_points, _ = tracks.shape
+
+ avg_visibility = np.mean(visibility, axis=0)
+ valid_points = avg_visibility >= vis_threshold
+ valid_indices = np.where(valid_points)[0]
+
+ print(f"{len(valid_points)=}")
+ print(f"{len(valid_indices)=}")
+
+ if len(valid_indices) == 0:
+ print("Warning: No points meet the confidence criteria")
+ return []
+
+ motion_magnitudes = []
+ for point_idx in valid_indices:
+ total_motion = 0.0
+ valid_frame_count = 0
+ for frame_idx in range(n_frames - 1):
+ if (visibility[frame_idx, point_idx] == True and
+ visibility[frame_idx + 1, point_idx] == True):
+ pos1 = tracks[frame_idx, point_idx]
+ pos2 = tracks[frame_idx + 1, point_idx]
+ distance = np.linalg.norm(pos2 - pos1)
+ total_motion += distance
+ valid_frame_count += 1
+ avg_motion = total_motion / max(valid_frame_count, 1)
+ motion_magnitudes.append(avg_motion)
+
+ motion_magnitudes = np.array(motion_magnitudes)
+
+ selected_indices = []
+ if False:
+ selected_indices = valid_indices.tolist()
+ else:
+ motion_sorted_indices = valid_indices[np.argsort(motion_magnitudes)[::-1]]
+ high_motion_indices = self.select_diverse_points(
+ motion_sorted_indices, tracks, visibility, max_points=max_points-1, min_distance=min_distance
+ )
+ selected_indices.extend(high_motion_indices)
+ if len(selected_indices) < max_points:
+ remaining_indices = [idx for idx in motion_sorted_indices if idx not in selected_indices]
+ if len(remaining_indices) > 0:
+ remaining_motions = [motion_magnitudes[np.where(valid_indices == idx)[0][0]]
+ for idx in remaining_indices]
+ min_motion_idx = remaining_indices[np.argmin(remaining_motions)]
+ selected_indices.append(min_motion_idx)
+
+ return selected_indices
+
+ def format_results(self, tracks, visibility, mask, confidence_threshold, original_points, max_points, min_distance, images_np, enable_backward=False):
+ tracks = tracks.squeeze(0).cpu().numpy()
+ visibility = visibility.squeeze(0).cpu().numpy()
+
+ if enable_backward:
+ confidence_threshold = 0
+
+ num_frames, num_points, _ = tracks.shape
+
+ def filter_by_mask(trs, vis, mask):
+ if mask is not None:
+ mask = mask.cpu().numpy()
+ while mask.ndim > 2 and mask.shape[0] == 1:
+ mask = mask[0]
+ # Handle multi-channel masks (H, W, C) by taking first channel
+ if mask.ndim == 3:
+ mask = mask[:, :, 0]
+
+ initial_coords = trs[0]
+ masked_indices = []
+ for n in range(initial_coords.shape[0]):
+ x, y = initial_coords[n]
+ if (0 <= int(x) < mask.shape[1] and
+ 0 <= int(y) < mask.shape[0] and
+ mask[int(y), int(x)] > 0):
+ masked_indices.append(n)
+
+ if len(masked_indices) > 0:
+ filtered_tracks = trs[:, masked_indices]
+ filtered_visibility = vis[:, masked_indices]
+ else:
+ filtered_tracks = np.empty((tracks.shape[0], 0, 2))
+ filtered_visibility = np.empty((visibility.shape[0], 0))
+ return filtered_tracks, filtered_visibility
+ else:
+ return trs, vis
+
+ tracks, visibility = filter_by_mask(tracks, visibility, mask)
+
+ selected_indices = self.select_points(tracks, visibility, vis_threshold=confidence_threshold, max_points=max_points, min_distance=min_distance)
+
+ marker_radius = 3
+ marker_thickness = -1
+ marker_color = (255, 0, 0)
+
+ point_results = []
+ for point_idx in selected_indices:
+ point_track = []
+ for frame_idx in range(num_frames):
+ x, y = tracks[frame_idx, point_idx]
+ vis = visibility[frame_idx, point_idx]
+
+ if vis == True:
+ point_track.append({
+ "x": int(x),
+ "y": int(y),
+ })
+ else:
+ if enable_backward:
+ point_track.append({
+ "x": -100,
+ "y": -100,
+ })
+ x = -100
+ y = -100
+ else:
+ if len(point_track) > 0:
+ last_point = point_track[-1].copy()
+ point_track.append(last_point)
+ x = last_point["x"]
+ y = last_point["y"]
+ else:
+ point_track.append({
+ "x": int(x),
+ "y": int(y),
+ })
+
+ if frame_idx < images_np.shape[0]:
+ cv2.circle(images_np[frame_idx], (int(x), int(y)), marker_radius, marker_color, marker_thickness)
+
+ point_results += [json.dumps(point_track)]
+
+ return point_results, images_np
diff --git a/comfyui_fill-nodes/nodes/image/FL_CreateShapeImageOnPath.py b/comfyui_fill-nodes/nodes/image/FL_CreateShapeImageOnPath.py
new file mode 100644
index 0000000000000000000000000000000000000000..735e9dcdcb7561264b8f45659ee975d1e1cbdfeb
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_CreateShapeImageOnPath.py
@@ -0,0 +1,150 @@
+import torch
+import json
+import numpy as np
+from PIL import Image, ImageDraw, ImageFilter
+
+
+def pil2tensor(image):
+ return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
+
+
+def parse_color(color):
+ if isinstance(color, str) and ',' in color:
+ return tuple(int(c.strip()) for c in color.split(','))
+ return color
+
+
+def parse_json_tracks(tracks):
+ tracks_data = []
+ try:
+ if isinstance(tracks, str):
+ parsed = json.loads(tracks.replace("'", '"'))
+ tracks_data.extend(parsed)
+ else:
+ for track_str in tracks:
+ parsed = json.loads(track_str.replace("'", '"'))
+ tracks_data.append(parsed)
+
+ if tracks_data and isinstance(tracks_data[0], dict) and 'x' in tracks_data[0]:
+ tracks_data = [tracks_data]
+ elif tracks_data and isinstance(tracks_data[0], list) and tracks_data[0] and isinstance(tracks_data[0][0], dict) and 'x' in tracks_data[0][0]:
+ pass
+ else:
+ print(f"Warning: Unexpected track format: {type(tracks_data[0])}")
+
+ except json.JSONDecodeError as e:
+ print(f"Error parsing tracks JSON: {e}")
+ tracks_data = []
+
+ return tracks_data
+
+
+class FL_CreateShapeImageOnPath:
+
+ RETURN_TYPES = ("IMAGE", "MASK",)
+ RETURN_NAMES = ("image", "mask",)
+ FUNCTION = "createshapemask"
+ CATEGORY = "🏵️Fill Nodes/Image"
+ DESCRIPTION = """
+Creates an image or batch of images with the specified shape.
+Locations are center locations.
+"""
+
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "shape": (
+ ['circle', 'square', 'triangle'],
+ {"default": 'circle'}
+ ),
+ "coordinates": ("STRING", {"forceInput": True}),
+ "frame_width": ("INT", {"default": 512, "min": 16, "max": 4096, "step": 1}),
+ "frame_height": ("INT", {"default": 512, "min": 16, "max": 4096, "step": 1}),
+ "shape_width": ("INT", {"default": 128, "min": 2, "max": 4096, "step": 1}),
+ "shape_height": ("INT", {"default": 128, "min": 2, "max": 4096, "step": 1}),
+ "shape_color": ("STRING", {"default": 'white'}),
+ "bg_color": ("STRING", {"default": 'black'}),
+ "blur_radius": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 100, "step": 0.1}),
+ "intensity": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 100.0, "step": 0.01}),
+ },
+ "optional": {
+ "size_multiplier": ("FLOAT", {"default": [1.0], "forceInput": True}),
+ "trailing": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
+ "border_width": ("INT", {"default": 0, "min": 0, "max": 100, "step": 1}),
+ "border_color": ("STRING", {"default": 'black'}),
+ }
+ }
+
+ def createshapemask(self, coordinates, frame_width, frame_height, shape_width, shape_height, shape_color,
+ bg_color, blur_radius, shape, intensity, size_multiplier=[1.0], trailing=1.0, border_width=0, border_color='black'):
+
+ shape_color = parse_color(shape_color)
+ border_color = parse_color(border_color)
+ bg_color = parse_color(bg_color)
+ coords_list = parse_json_tracks(coordinates)
+
+ batch_size = len(coords_list[0])
+ images_list = []
+ masks_list = []
+
+ if not size_multiplier or len(size_multiplier) != batch_size:
+ size_multiplier = [1] * batch_size
+ else:
+ size_multiplier = size_multiplier * (batch_size // len(size_multiplier)) + size_multiplier[:batch_size % len(size_multiplier)]
+
+ previous_output = None
+
+ for i in range(batch_size):
+ image = Image.new("RGB", (frame_width, frame_height), bg_color)
+ draw = ImageDraw.Draw(image)
+
+ current_width = shape_width * size_multiplier[i]
+ current_height = shape_height * size_multiplier[i]
+
+ for coords in coords_list:
+ location_x = coords[i]['x']
+ location_y = coords[i]['y']
+
+ if shape == 'circle' or shape == 'square':
+ left_up_point = (location_x - current_width // 2, location_y - current_height // 2)
+ right_down_point = (location_x + current_width // 2, location_y + current_height // 2)
+ two_points = [left_up_point, right_down_point]
+
+ if shape == 'circle':
+ if border_width > 0:
+ draw.ellipse(two_points, fill=shape_color, outline=border_color, width=border_width)
+ else:
+ draw.ellipse(two_points, fill=shape_color)
+ elif shape == 'square':
+ if border_width > 0:
+ draw.rectangle(two_points, fill=shape_color, outline=border_color, width=border_width)
+ else:
+ draw.rectangle(two_points, fill=shape_color)
+
+ elif shape == 'triangle':
+ left_up_point = (location_x - current_width // 2, location_y + current_height // 2)
+ right_down_point = (location_x + current_width // 2, location_y + current_height // 2)
+ top_point = (location_x, location_y - current_height // 2)
+
+ if border_width > 0:
+ draw.polygon([top_point, left_up_point, right_down_point], fill=shape_color, outline=border_color, width=border_width)
+ else:
+ draw.polygon([top_point, left_up_point, right_down_point], fill=shape_color)
+
+ if blur_radius != 0:
+ image = image.filter(ImageFilter.GaussianBlur(blur_radius))
+
+ image = pil2tensor(image)
+ if trailing != 1.0 and previous_output is not None:
+ image += trailing * previous_output
+ image = image / image.max()
+ previous_output = image
+ image = image * intensity
+ mask = image[:, :, :, 0]
+ masks_list.append(mask)
+ images_list.append(image)
+
+ out_images = torch.cat(images_list, dim=0).cpu().float()
+ out_masks = torch.cat(masks_list, dim=0)
+ return (out_images, out_masks)
diff --git a/comfyui_fill-nodes/nodes/image/FL_ImageAddNoise.py b/comfyui_fill-nodes/nodes/image/FL_ImageAddNoise.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5b6212e9d4e0e5619377974905b9a813e903ef7
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_ImageAddNoise.py
@@ -0,0 +1,32 @@
+import torch
+
+class FL_ImageAddNoise:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "seed": ("INT", {
+ "default": 0,
+ "min": 0,
+ "max": 0xffffffffffffffff,
+ "control_after_generate": True,
+ "tooltip": "The random seed used for creating the noise."
+ }),
+ "strength": ("FLOAT", {
+ "default": 0.5,
+ "min": 0.0,
+ "max": 1.0,
+ "step": 0.01
+ }),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "add_noise"
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def add_noise(self, image, seed, strength):
+ generator = torch.manual_seed(seed)
+ s = torch.clip((image + strength * torch.randn(image.size(), generator=generator, device="cpu").to(image)), min=0.0, max=1.0)
+ return (s,)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_ImageAdjuster.py b/comfyui_fill-nodes/nodes/image/FL_ImageAdjuster.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc0f7ec5ae6ce209a92cb35e96af5997ca7a3640
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_ImageAdjuster.py
@@ -0,0 +1,83 @@
+import torch
+import numpy as np
+from PIL import Image, ImageEnhance, ImageFilter
+import base64
+import io
+from server import PromptServer
+from ..utils import tensor_to_pil, pil_to_tensor
+
+
+class FL_ImageAdjuster:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "hue": ("FLOAT", {"default": 0, "min": -180, "max": 180, "step": 1}),
+ "saturation": ("FLOAT", {"default": 0, "min": -100, "max": 100, "step": 1}),
+ "brightness": ("FLOAT", {"default": 0, "min": -100, "max": 100, "step": 1}),
+ "contrast": ("FLOAT", {"default": 0, "min": -100, "max": 100, "step": 1}),
+ "sharpness": ("FLOAT", {"default": 0, "min": 0, "max": 100, "step": 1}),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "adjust_image"
+ CATEGORY = "🏵️Fill Nodes/Image"
+ OUTPUT_NODE = True
+
+ def adjust_image(self, image, hue, saturation, brightness, contrast, sharpness):
+ # Convert tensor to PIL Image
+ pil_image = tensor_to_pil(image)
+
+ # Apply adjustments
+ adjusted_image = self.apply_adjustments(pil_image, hue, saturation, brightness, contrast, sharpness)
+
+ # Convert back to tensor
+ tensor_image = pil_to_tensor(adjusted_image)
+
+ # Prepare image for display
+ display_image = self.prepare_image_for_display(adjusted_image)
+
+ # Send the image to the frontend
+ PromptServer.instance.send_sync("fl_image_adjuster", {"image": display_image})
+
+ return (tensor_image,)
+
+ def apply_adjustments(self, image, hue, saturation, brightness, contrast, sharpness):
+ # Convert to HSV for hue and saturation adjustments
+ hsv_image = image.convert('HSV')
+ h, s, v = hsv_image.split()
+
+ # Hue adjustment
+ h = h.point(lambda x: (x + hue) % 256)
+
+ # Saturation adjustment
+ s = s.point(lambda x: max(0, min(255, x + saturation * 255 / 100)))
+
+ # Merge channels
+ hsv_image = Image.merge('HSV', (h, s, v))
+ rgb_image = hsv_image.convert('RGB')
+
+ # Brightness adjustment
+ enhancer = ImageEnhance.Brightness(rgb_image)
+ rgb_image = enhancer.enhance(1 + brightness / 100)
+
+ # Contrast adjustment
+ enhancer = ImageEnhance.Contrast(rgb_image)
+ rgb_image = enhancer.enhance(1 + contrast / 100)
+
+ # Sharpness adjustment
+ if sharpness > 0:
+ # Convert sharpness to an integer percentage between 100 and 200
+ sharpness_percent = int(100 + sharpness)
+ rgb_image = rgb_image.filter(ImageFilter.UnsharpMask(radius=2, percent=sharpness_percent, threshold=3))
+
+ return rgb_image
+
+ def prepare_image_for_display(self, pil_image):
+ # Convert PIL Image to base64 string
+ buffered = io.BytesIO()
+ pil_image.save(buffered, format="PNG")
+ img_str = base64.b64encode(buffered.getvalue()).decode()
+ return f"data:image/png;base64,{img_str}"
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_ImageAspectCropper.py b/comfyui_fill-nodes/nodes/image/FL_ImageAspectCropper.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7d9943d252de0231e4329f72c09f38578c18650
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_ImageAspectCropper.py
@@ -0,0 +1,58 @@
+import torch
+from ..utils import tensor_to_pil, pil_to_tensor
+
+class FL_ImageAspectCropper:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "images": ("IMAGE",),
+ "aspect_ratio_w": ("INT", {"default": 16, "min": 1, "max": 100, "step": 1}),
+ "aspect_ratio_h": ("INT", {"default": 9, "min": 1, "max": 100, "step": 1}),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "crop_to_aspect"
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def crop_to_aspect(self, images, aspect_ratio_w, aspect_ratio_h):
+ batch_size = images.shape[0]
+ height = images.shape[1]
+ width = images.shape[2]
+ channels = images.shape[3]
+
+ # Calculate target aspect ratio (convert to float for division)
+ target_ratio = float(aspect_ratio_w) / float(aspect_ratio_h)
+ current_ratio = width / height
+
+ result_tensors = []
+
+ for i in range(batch_size):
+ img = images[i]
+
+ if current_ratio > target_ratio:
+ # Image is wider than target ratio, crop width
+ new_width = int(height * target_ratio)
+ new_width = new_width - (new_width % 2) # Ensure even number
+ # Calculate left position to center the crop
+ left = (width - new_width) // 2
+ # Crop the image
+ cropped_img = img[:, left:left+new_width, :]
+ else:
+ # Image is taller than target ratio, crop height
+ new_height = int(width / target_ratio)
+ new_height = new_height - (new_height % 2) # Ensure even number
+ # Calculate top position to center the crop
+ top = (height - new_height) // 2
+ # Crop the image
+ cropped_img = img[top:top+new_height, :, :]
+
+ result_tensors.append(cropped_img.unsqueeze(0))
+
+ # Concatenate all cropped images back into a batch
+ if result_tensors:
+ return (torch.cat(result_tensors, dim=0),)
+ else:
+ # Return empty batch with same dimensions as input if no images were processed
+ return (images[0:0],)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_ImageBatch.py b/comfyui_fill-nodes/nodes/image/FL_ImageBatch.py
new file mode 100644
index 0000000000000000000000000000000000000000..bea3b962d8086146bbdbe5cd4377dd23f813caf1
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_ImageBatch.py
@@ -0,0 +1,48 @@
+import torch
+from nodes import ImageBatch # Assuming ImageBatch is a ComfyUI core node or accessible
+
+class FL_ImageBatch: # Renamed class
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "inputcount": ("INT", {"default": 2, "min": 2, "max": 100, "step": 1}),
+ "image_1": ("IMAGE",),
+ "image_2": ("IMAGE",),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ RETURN_NAMES = ("images",)
+ FUNCTION = "combine_images"
+ CATEGORY = "🏵️Fill Nodes/Image" # Kept category, can be changed if needed
+ DESCRIPTION = """
+FL Image Batch allows combining multiple images into a batch.
+The number of image inputs can be dynamically adjusted.
+""" # Updated description
+
+ def combine_images(self, inputcount, **kwargs):
+ image_batch_node = ImageBatch()
+
+ if "image_1" not in kwargs:
+ return (torch.empty(0),)
+
+ image = kwargs["image_1"]
+
+ if inputcount == 1:
+ return (image,)
+
+ for c in range(1, inputcount):
+ image_key = f"image_{c + 1}"
+ if image_key in kwargs:
+ new_image = kwargs[image_key]
+ if image.ndim == 3:
+ image = image.unsqueeze(0)
+ if new_image.ndim == 3:
+ new_image = new_image.unsqueeze(0)
+
+ image, = image_batch_node.batch(image, new_image)
+ else:
+ print(f"Warning: {image_key} not found in inputs for FL_ImageBatch.")
+ pass
+ return (image,)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_ImageBatchListConverter.py b/comfyui_fill-nodes/nodes/image/FL_ImageBatchListConverter.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec2551fa4a1d8ed436a244669699fb45bad333c8
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_ImageBatchListConverter.py
@@ -0,0 +1,48 @@
+import torch
+import comfy.utils
+
+class FL_ImageListToImageBatch:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {"required": {
+ "images": ("IMAGE",),
+ }}
+
+ INPUT_IS_LIST = True
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "doit"
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def doit(self, images):
+ if len(images) <= 1:
+ return (images[0],)
+
+ target_shape = images[0].shape[1:] # (H, W, C)
+ processed = []
+ for img in images:
+ if img.shape[1:] != target_shape:
+ img = comfy.utils.common_upscale(
+ img.movedim(-1, 1),
+ target_shape[1],
+ target_shape[0],
+ "lanczos",
+ "center"
+ ).movedim(1, -1)
+ processed.append(img)
+
+ return (torch.cat(processed, dim=0),)
+
+
+class FL_ImageBatchToImageList:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {"required": {"image": ("IMAGE",)}}
+
+ RETURN_TYPES = ("IMAGE",)
+ OUTPUT_IS_LIST = (True,)
+ FUNCTION = "doit"
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def doit(self, image):
+ images = [image[i:i + 1, ...] for i in range(image.shape[0])]
+ return (images,)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_ImageBatchToGrid.py b/comfyui_fill-nodes/nodes/image/FL_ImageBatchToGrid.py
new file mode 100644
index 0000000000000000000000000000000000000000..f376b130e25f8612210c09c2f9a0a7ef9fefb425
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_ImageBatchToGrid.py
@@ -0,0 +1,44 @@
+import torch
+import math
+
+class FL_ImageBatchToGrid:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "images": ("IMAGE",),
+ "images_per_row": ("INT", {
+ "default": 5,
+ "min": 1,
+ "max": 20,
+ "step": 1
+ }),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "create_grid"
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def create_grid(self, images, images_per_row):
+ batch_size, height, width, channels = images.shape
+
+ # Calculate the number of rows needed
+ num_rows = math.ceil(batch_size / images_per_row)
+
+ # Create a blank canvas for the grid (filled with black)
+ grid = torch.zeros((num_rows * height, images_per_row * width, channels), dtype=images.dtype, device=images.device)
+
+ for i in range(batch_size):
+ row = i // images_per_row
+ col = i % images_per_row
+
+ y_start = row * height
+ y_end = (row + 1) * height
+ x_start = col * width
+ x_end = (col + 1) * width
+
+ grid[y_start:y_end, x_start:x_end, :] = images[i]
+
+ # Add batch dimension
+ return (grid.unsqueeze(0),)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_ImageNotes.py b/comfyui_fill-nodes/nodes/image/FL_ImageNotes.py
new file mode 100644
index 0000000000000000000000000000000000000000..47ad1623c7a27ef668e1c271eab3a5cc263118c8
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_ImageNotes.py
@@ -0,0 +1,131 @@
+import os
+import torch
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+from comfy.utils import ProgressBar
+
+class FL_ImageNotes:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "images": ("IMAGE",),
+ "text": ("STRING", {"default": "Text Here", "multiline": True}),
+ "bar_height": ("INT", {"default": 50, "min": 10, "max": 200, "step": 2, "description": "Initial bar height (auto-adjusted if word wrap is enabled)"}),
+ "text_size": ("INT", {"default": 24, "min": 10, "max": 100, "step": 1}),
+ "border": ("INT", {"default": 0, "min": 0, "max": 200, "step": 5, "description": "Border size in pixels (left, right, bottom)"}),
+ "word_wrap": (["disable", "enable"], {"default": "disable", "description": "Enable text wrapping and auto-height adjustment"}),
+ "bar_position": (["top", "bottom"], {"default": "top", "description": "Position of the text bar"}),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "add_notes"
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def add_notes(self, images, text, bar_height, text_size, border, word_wrap, bar_position):
+ result = []
+ total_images = len(images)
+ pbar = ProgressBar(total_images)
+ for i, image in enumerate(images, start=1):
+ img = self.t2p(image)
+ result_img = self.add_text_bar(img, text, bar_height, text_size, border, word_wrap, bar_position)
+ result_img = self.p2t(result_img)
+ result.append(result_img)
+
+ pbar.update_absolute(i)
+
+ return (torch.cat(result, dim=0),)
+
+ def add_text_bar(self, image, text, bar_height, text_size, border, word_wrap, bar_position):
+ width, height = image.size
+
+ # Calculate available width for text (accounting for borders)
+ available_width = width + (border * 2) - 20 # 10px padding on each side
+
+ current_dir = os.path.dirname(os.path.abspath(__file__))
+ font_path = os.path.join(current_dir, "..", "fonts", "arial.ttf")
+ font = ImageFont.truetype(font_path, text_size)
+
+ # Handle word wrapping and calculate required bar height
+ if word_wrap == "enable":
+ wrapped_lines = self.wrap_text(text, font, available_width)
+ line_height = text_size * 1.2 # Add some line spacing
+ required_height = int(len(wrapped_lines) * line_height) + 20 # Add padding
+ actual_bar_height = max(bar_height, required_height) # Use the larger of specified or required height
+ else:
+ wrapped_lines = [text] # No wrapping, just use the text as is
+ actual_bar_height = bar_height
+
+ # Calculate new dimensions with border
+ new_width = width + (border * 2) # Left and right borders
+ new_height = height + actual_bar_height + border # Bar and bottom border
+
+ # Create new image with black background
+ new_image = Image.new("RGB", (new_width, new_height), color="black")
+
+ # Determine image paste position based on bar position
+ if bar_position == "top":
+ image_y = actual_bar_height
+ text_y_start = 10 # Padding from top
+ else: # bottom
+ image_y = 0
+ text_y_start = height + border # Start text below the image
+
+ # Paste original image with offset for borders
+ new_image.paste(image, (border, image_y))
+
+ draw = ImageDraw.Draw(new_image)
+
+ # Draw each line of text
+ line_height = text_size * 1.2
+ for i, line in enumerate(wrapped_lines):
+ text_width, text_height = self.get_text_size(line, font)
+ x = (new_width - text_width) // 2 # Center text in the new width
+ y = text_y_start + (i * line_height)
+ draw.text((x, y), line, font=font, fill="white")
+
+ return new_image
+
+ def get_text_size(self, text, font):
+ ascent, descent = font.getmetrics()
+ text_width = font.getmask(text).getbbox()[2]
+ text_height = font.getmask(text).getbbox()[3] + descent
+ return text_width, text_height
+
+ def wrap_text(self, text, font, max_width):
+ """Split text into lines that fit within max_width."""
+ words = text.split()
+ if not words:
+ return [""]
+
+ lines = []
+ current_line = words[0]
+
+ for word in words[1:]:
+ # Check if adding this word would exceed the max width
+ test_line = current_line + " " + word
+ test_width, _ = self.get_text_size(test_line, font)
+
+ if test_width <= max_width:
+ current_line = test_line
+ else:
+ # Line is full, start a new line
+ lines.append(current_line)
+ current_line = word
+
+ # Add the last line
+ lines.append(current_line)
+ return lines
+
+ def t2p(self, t):
+ if t is not None:
+ i = 255.0 * t.cpu().numpy().squeeze()
+ p = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
+ return p
+
+ def p2t(self, p):
+ if p is not None:
+ i = np.array(p).astype(np.float32) / 255.0
+ t = torch.from_numpy(i).unsqueeze(0)
+ return t
diff --git a/comfyui_fill-nodes/nodes/image/FL_ImageOverlay.py b/comfyui_fill-nodes/nodes/image/FL_ImageOverlay.py
new file mode 100644
index 0000000000000000000000000000000000000000..27da961fbc182f659f719208fd3c755e0c627473
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_ImageOverlay.py
@@ -0,0 +1,292 @@
+import torch
+import numpy as np
+import io
+import base64
+from PIL import Image, ImageFilter
+from ..utils import tensor_to_pil, pil_to_tensor
+from server import PromptServer
+
+
+class FL_ImageOverlay:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "base_image": ("IMAGE",),
+ "overlay_image": ("IMAGE",),
+ "mask": ("MASK",),
+ "x_offset": ("INT", {"default": 0, "min": -8192, "max": 8192, "step": 1}),
+ "y_offset": ("INT", {"default": 0, "min": -8192, "max": 8192, "step": 1}),
+ "alignment": ([
+ "custom",
+ "center",
+ "top-left",
+ "top-center",
+ "top-right",
+ "center-left",
+ "center-right",
+ "bottom-left",
+ "bottom-center",
+ "bottom-right"
+ ], {"default": "custom"}),
+ "resize_overlay": ([
+ "none",
+ "fit_to_base",
+ "scale_50%",
+ "scale_75%",
+ "scale_125%",
+ "scale_150%",
+ "scale_200%"
+ ], {"default": "none"}),
+ "blend_mode": ([
+ "normal",
+ "multiply",
+ "screen",
+ "overlay",
+ "add"
+ ], {"default": "normal"}),
+ "opacity": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
+ "invert_mask": ("BOOLEAN", {"default": False}),
+ "mask_feather": ("INT", {"default": 0, "min": 0, "max": 100, "step": 1}),
+ "boundary_behavior": (["clip", "extend_canvas"], {"default": "clip"}),
+ "show_preview": ("BOOLEAN", {"default": False, "label": "Show Preview on Node"}),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "overlay_images"
+ OUTPUT_NODE = True
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def overlay_images(self, base_image, overlay_image, mask, x_offset, y_offset,
+ alignment, resize_overlay, blend_mode, opacity, invert_mask,
+ mask_feather, boundary_behavior, show_preview=False):
+ # Process batch - use first image from each batch
+ base_pil = tensor_to_pil(base_image, batch_index=0)
+ overlay_pil = tensor_to_pil(overlay_image, batch_index=0)
+
+ # Convert mask tensor to PIL (masks are typically [B, H, W])
+ if len(mask.shape) == 3:
+ mask_np = mask[0].cpu().numpy()
+ elif len(mask.shape) == 2:
+ mask_np = mask.cpu().numpy()
+ else:
+ raise ValueError(f"Unexpected mask shape: {mask.shape}")
+
+ # Convert to 0-255 range and create PIL image
+ mask_pil = Image.fromarray((mask_np * 255).astype(np.uint8), mode='L')
+
+ # Resize mask to match overlay dimensions
+ if mask_pil.size != overlay_pil.size:
+ mask_pil = mask_pil.resize(overlay_pil.size, Image.Resampling.LANCZOS)
+
+ # Invert mask if requested
+ if invert_mask:
+ mask_pil = Image.eval(mask_pil, lambda x: 255 - x)
+
+ # Apply feathering to mask
+ if mask_feather > 0:
+ mask_pil = mask_pil.filter(ImageFilter.GaussianBlur(radius=mask_feather))
+
+ # Resize overlay if requested
+ overlay_pil = self.resize_overlay_image(overlay_pil, base_pil, resize_overlay, mask_pil)
+
+ # Recalculate mask size after resize
+ if mask_pil.size != overlay_pil.size:
+ mask_pil = mask_pil.resize(overlay_pil.size, Image.Resampling.LANCZOS)
+
+ # Calculate position based on alignment
+ x_pos, y_pos = self.calculate_position(
+ base_pil.size, overlay_pil.size, x_offset, y_offset, alignment
+ )
+
+ # Perform the compositing
+ result_pil = self.composite_images(
+ base_pil, overlay_pil, mask_pil, x_pos, y_pos,
+ blend_mode, opacity, boundary_behavior
+ )
+
+ # Send preview to frontend if enabled
+ if show_preview:
+ display_image = self.prepare_image_for_display(result_pil)
+ PromptServer.instance.send_sync("fl_image_overlay", {"image": display_image})
+
+ # Convert back to tensor
+ result_tensor = pil_to_tensor(result_pil)
+
+ return (result_tensor,)
+
+ def resize_overlay_image(self, overlay, base, resize_mode, mask):
+ """Resize the overlay image based on the selected mode"""
+ if resize_mode == "none":
+ return overlay
+
+ base_w, base_h = base.size
+ overlay_w, overlay_h = overlay.size
+
+ if resize_mode == "fit_to_base":
+ # Resize overlay to match base dimensions
+ new_size = (base_w, base_h)
+ else:
+ # Extract scale percentage
+ scale_map = {
+ "scale_50%": 0.5,
+ "scale_75%": 0.75,
+ "scale_125%": 1.25,
+ "scale_150%": 1.5,
+ "scale_200%": 2.0
+ }
+ scale = scale_map.get(resize_mode, 1.0)
+ new_size = (int(overlay_w * scale), int(overlay_h * scale))
+
+ resized_overlay = overlay.resize(new_size, Image.Resampling.LANCZOS)
+ return resized_overlay
+
+ def calculate_position(self, base_size, overlay_size, x_offset, y_offset, alignment):
+ """Calculate the position to place the overlay based on alignment"""
+ base_w, base_h = base_size
+ overlay_w, overlay_h = overlay_size
+
+ # Alignment presets
+ if alignment == "center":
+ x = (base_w - overlay_w) // 2
+ y = (base_h - overlay_h) // 2
+ elif alignment == "top-left":
+ x, y = 0, 0
+ elif alignment == "top-center":
+ x = (base_w - overlay_w) // 2
+ y = 0
+ elif alignment == "top-right":
+ x = base_w - overlay_w
+ y = 0
+ elif alignment == "center-left":
+ x = 0
+ y = (base_h - overlay_h) // 2
+ elif alignment == "center-right":
+ x = base_w - overlay_w
+ y = (base_h - overlay_h) // 2
+ elif alignment == "bottom-left":
+ x = 0
+ y = base_h - overlay_h
+ elif alignment == "bottom-center":
+ x = (base_w - overlay_w) // 2
+ y = base_h - overlay_h
+ elif alignment == "bottom-right":
+ x = base_w - overlay_w
+ y = base_h - overlay_h
+ else: # custom
+ x, y = 0, 0
+
+ # Apply offsets
+ x += x_offset
+ y += y_offset
+
+ return x, y
+
+ def composite_images(self, base, overlay, mask, x_pos, y_pos, blend_mode, opacity, boundary_behavior):
+ """Composite the overlay onto the base image"""
+ base_w, base_h = base.size
+ overlay_w, overlay_h = overlay.size
+
+ # Handle boundary behavior
+ if boundary_behavior == "extend_canvas":
+ # Calculate required canvas size
+ canvas_w = max(base_w, x_pos + overlay_w, abs(min(0, x_pos)) + base_w)
+ canvas_h = max(base_h, y_pos + overlay_h, abs(min(0, y_pos)) + base_h)
+
+ # Create extended canvas
+ canvas = Image.new('RGB', (canvas_w, canvas_h), (0, 0, 0))
+
+ # Paste base image at appropriate position
+ base_x = abs(min(0, x_pos))
+ base_y = abs(min(0, y_pos))
+ canvas.paste(base, (base_x, base_y))
+
+ # Adjust overlay position for extended canvas
+ overlay_x = x_pos if x_pos >= 0 else 0
+ overlay_y = y_pos if y_pos >= 0 else 0
+
+ result = canvas.copy()
+ else: # clip
+ result = base.copy()
+ overlay_x = x_pos
+ overlay_y = y_pos
+
+ # Calculate visible region of overlay
+ src_x = max(0, -x_pos)
+ src_y = max(0, -y_pos)
+ dst_x = max(0, x_pos)
+ dst_y = max(0, y_pos)
+
+ # Calculate dimensions of visible region
+ visible_w = min(overlay_w - src_x, base_w - dst_x)
+ visible_h = min(overlay_h - src_y, base_h - dst_y)
+
+ # If overlay is completely outside bounds, return base image
+ if visible_w <= 0 or visible_h <= 0:
+ return base
+
+ # Crop overlay and mask to visible region
+ overlay = overlay.crop((src_x, src_y, src_x + visible_w, src_y + visible_h))
+ mask = mask.crop((src_x, src_y, src_x + visible_w, src_y + visible_h))
+ overlay_x = dst_x
+ overlay_y = dst_y
+
+ # Apply blend mode
+ if blend_mode != "normal":
+ overlay = self.apply_blend_mode(result, overlay, blend_mode, overlay_x, overlay_y)
+
+ # Apply global opacity to mask
+ if opacity < 1.0:
+ mask_np = np.array(mask).astype(np.float32)
+ mask_np = (mask_np * opacity).astype(np.uint8)
+ mask = Image.fromarray(mask_np, mode='L')
+
+ # Composite using the mask
+ result.paste(overlay, (overlay_x, overlay_y), mask)
+
+ return result
+
+ def apply_blend_mode(self, base, overlay, mode, x_pos, y_pos):
+ """Apply blend mode to overlay based on the underlying base image region"""
+ # Extract the region from base that overlay will cover
+ overlay_w, overlay_h = overlay.size
+ base_region = base.crop((x_pos, y_pos, x_pos + overlay_w, y_pos + overlay_h))
+
+ # Convert to numpy arrays for blending
+ base_np = np.array(base_region).astype(np.float32) / 255.0
+ overlay_np = np.array(overlay).astype(np.float32) / 255.0
+
+ # Apply blend mode
+ if mode == "multiply":
+ result_np = base_np * overlay_np
+ elif mode == "screen":
+ result_np = 1 - (1 - base_np) * (1 - overlay_np)
+ elif mode == "overlay":
+ # Overlay blend mode
+ mask = base_np < 0.5
+ result_np = np.where(mask,
+ 2 * base_np * overlay_np,
+ 1 - 2 * (1 - base_np) * (1 - overlay_np))
+ elif mode == "add":
+ result_np = np.clip(base_np + overlay_np, 0, 1)
+ else: # normal
+ result_np = overlay_np
+
+ # Convert back to PIL
+ result_np = (result_np * 255).astype(np.uint8)
+ return Image.fromarray(result_np, mode='RGB')
+
+ def prepare_image_for_display(self, pil_image):
+ """Convert PIL image to base64 for frontend display"""
+ # Create a copy to avoid modifying the original
+ display_img = pil_image.copy()
+
+ # Resize image if it's too large for preview
+ max_size = (512, 512)
+ display_img.thumbnail(max_size, Image.Resampling.LANCZOS)
+
+ buffered = io.BytesIO()
+ display_img.save(buffered, format="PNG")
+ img_str = base64.b64encode(buffered.getvalue()).decode()
+ return f"data:image/png;base64,{img_str}"
diff --git a/comfyui_fill-nodes/nodes/image/FL_ImagePicker.py b/comfyui_fill-nodes/nodes/image/FL_ImagePicker.py
new file mode 100644
index 0000000000000000000000000000000000000000..93d5be1ed355f178359209a490ae4665cf83b589
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_ImagePicker.py
@@ -0,0 +1,241 @@
+# FL_ImagePicker: Interactive image selector with modal UI
+import os
+import io
+import base64
+import threading
+import time
+import uuid
+import torch
+import numpy as np
+from PIL import Image
+from aiohttp import web
+from server import PromptServer
+import execution
+
+# Global storage for pending selections
+pending_selections = {}
+
+
+class InterruptProcessing(Exception):
+ """Exception to interrupt ComfyUI processing."""
+ pass
+
+
+class FL_ImagePicker:
+ """
+ An interactive image selector node that pauses execution and displays
+ a modal UI for the user to select which images to keep from a batch.
+ """
+
+ RETURN_TYPES = ("IMAGE", "STRING")
+ RETURN_NAMES = ("selected_images", "selection_info")
+ FUNCTION = "select_images"
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ THUMBNAIL_MAX_SIZE = 512 # Max dimension for thumbnails sent to frontend
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "images": ("IMAGE",),
+ "timeout_seconds": ("INT", {"default": 300, "min": 30, "max": 3600, "step": 10}),
+ },
+ "hidden": {
+ "unique_id": "UNIQUE_ID",
+ }
+ }
+
+ def _create_thumbnail(self, pil_img, max_size):
+ """Create a thumbnail that fits within max_size while preserving aspect ratio."""
+ width, height = pil_img.size
+
+ # Only resize if larger than max_size
+ if width <= max_size and height <= max_size:
+ return pil_img
+
+ # Calculate new size preserving aspect ratio
+ if width > height:
+ new_width = max_size
+ new_height = int(height * (max_size / width))
+ else:
+ new_height = max_size
+ new_width = int(width * (max_size / height))
+
+ # Use LANCZOS for high-quality downscaling
+ return pil_img.resize((new_width, new_height), Image.LANCZOS)
+
+ def select_images(self, images, timeout_seconds, unique_id):
+ batch_size = images.shape[0]
+
+ if batch_size == 0:
+ return (images, "No images in batch")
+
+ # Generate a session ID for this selection
+ session_id = f"{unique_id}_{uuid.uuid4().hex[:8]}"
+
+ # Convert images to thumbnails for sending to frontend (faster loading)
+ # Original full-res images are kept in pending_selections for output
+ image_data = []
+ print(f"[FL_ImagePicker] Generating thumbnails for {batch_size} images...")
+ for i in range(batch_size):
+ img_tensor = images[i]
+ # Convert tensor to PIL
+ img_np = (img_tensor.cpu().numpy() * 255).astype(np.uint8)
+ pil_img = Image.fromarray(img_np)
+
+ # Store original dimensions before thumbnailing
+ orig_width, orig_height = pil_img.size
+
+ # Create thumbnail for frontend display
+ thumbnail = self._create_thumbnail(pil_img, self.THUMBNAIL_MAX_SIZE)
+
+ # Convert thumbnail to base64 (using JPEG for smaller size)
+ buffered = io.BytesIO()
+ thumbnail.save(buffered, format="JPEG", quality=85)
+ img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
+
+ image_data.append({
+ "index": i,
+ "data": f"data:image/jpeg;base64,{img_base64}",
+ "width": orig_width, # Report original dimensions
+ "height": orig_height # so user knows actual size
+ })
+
+ # Create event to block on
+ event = threading.Event()
+ pending_selections[session_id] = {
+ "event": event,
+ "selection": None,
+ "cancelled": False,
+ "images": images
+ }
+
+ print(f"[FL_ImagePicker] Session created: {session_id}")
+ print(f"[FL_ImagePicker] Active sessions after create: {list(pending_selections.keys())}")
+
+ # Send message to frontend to show selector
+ PromptServer.instance.send_sync("fl_image_picker_show", {
+ "session_id": session_id,
+ "images": image_data,
+ "batch_size": batch_size,
+ "timeout_seconds": timeout_seconds
+ })
+
+ print(f"[FL_ImagePicker] Waiting for user selection... (timeout: {timeout_seconds}s)")
+
+ # Block until user responds or timeout
+ event_set = event.wait(timeout=timeout_seconds)
+
+ # Get result
+ result = pending_selections.get(session_id, {})
+ selection = result.get("selection")
+ cancelled = result.get("cancelled", False)
+
+ # Clean up
+ if session_id in pending_selections:
+ del pending_selections[session_id]
+
+ if not event_set:
+ # Timeout - cancel the execution
+ print(f"[FL_ImagePicker] Timeout reached. Cancelling execution...")
+ nodes = execution.nodes
+ if hasattr(nodes, 'interrupt_processing'):
+ nodes.interrupt_processing()
+ raise InterruptProcessing("Image selection timed out")
+
+ if cancelled:
+ # User cancelled - interrupt the execution
+ print(f"[FL_ImagePicker] Selection cancelled by user. Interrupting execution...")
+ # Set the interrupt flag in ComfyUI's execution module
+ nodes = execution.nodes
+ if hasattr(nodes, 'interrupt_processing'):
+ nodes.interrupt_processing()
+ # Raise an exception to stop this node's execution
+ raise InterruptProcessing("Image selection was cancelled by user")
+
+ if selection is None or len(selection) == 0:
+ # No selection - return all
+ print(f"[FL_ImagePicker] No images selected. Returning all {batch_size} images.")
+ return (images, f"No selection: returned all {batch_size} images")
+
+ # Filter to selected indices
+ selected_indices = sorted(selection)
+ selected_images = images[selected_indices]
+
+ info = f"Selected {len(selected_indices)} of {batch_size} images: indices {selected_indices}"
+ print(f"[FL_ImagePicker] {info}")
+
+ return (selected_images, info)
+
+
+# API endpoint to receive selection from frontend
+@PromptServer.instance.routes.post("/fl_image_picker/select")
+async def receive_selection(request):
+ try:
+ data = await request.json()
+ session_id = data.get("session_id")
+ selection = data.get("selection", []) # List of indices
+ cancelled = data.get("cancelled", False)
+
+ if session_id in pending_selections:
+ pending_selections[session_id]["selection"] = selection
+ pending_selections[session_id]["cancelled"] = cancelled
+ pending_selections[session_id]["event"].set() # Unblock the waiting thread
+ return web.json_response({"status": "ok", "received": len(selection)})
+ else:
+ return web.json_response({"status": "error", "message": "Session not found"}, status=404)
+ except Exception as e:
+ return web.json_response({"status": "error", "message": str(e)}, status=500)
+
+
+# API endpoint to check if a session is still active (for frontend to detect if node was interrupted)
+@PromptServer.instance.routes.get("/fl_image_picker/status/{session_id}")
+async def check_status(request):
+ session_id = request.match_info.get("session_id")
+ if session_id in pending_selections:
+ return web.json_response({"status": "active"})
+ else:
+ return web.json_response({"status": "inactive"})
+
+
+# API endpoint to fetch full-res image on demand for preview
+@PromptServer.instance.routes.get("/fl_image_picker/full_image/{session_id}/{index}")
+async def get_full_image(request):
+ try:
+ session_id = request.match_info.get("session_id")
+ index = int(request.match_info.get("index"))
+
+ print(f"[FL_ImagePicker] Full image request: session={session_id}, index={index}")
+ print(f"[FL_ImagePicker] Active sessions: {list(pending_selections.keys())}")
+
+ if session_id not in pending_selections:
+ return web.json_response({"status": "error", "message": f"Session not found. Active: {list(pending_selections.keys())}"}, status=404)
+
+ images = pending_selections[session_id].get("images")
+ if images is None:
+ return web.json_response({"status": "error", "message": "Images not found"}, status=404)
+
+ batch_size = images.shape[0]
+ if index < 0 or index >= batch_size:
+ return web.json_response({"status": "error", "message": f"Invalid index {index}"}, status=400)
+
+ # Convert the requested image to full-res base64
+ img_tensor = images[index]
+ img_np = (img_tensor.cpu().numpy() * 255).astype(np.uint8)
+ pil_img = Image.fromarray(img_np)
+
+ # Convert to PNG for full quality
+ buffered = io.BytesIO()
+ pil_img.save(buffered, format="PNG")
+ img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
+
+ return web.json_response({
+ "status": "ok",
+ "index": index,
+ "data": f"data:image/png;base64,{img_base64}",
+ "width": pil_img.width,
+ "height": pil_img.height
+ })
+ except Exception as e:
+ return web.json_response({"status": "error", "message": str(e)}, status=500)
diff --git a/comfyui_fill-nodes/nodes/image/FL_ImageReplace.py b/comfyui_fill-nodes/nodes/image/FL_ImageReplace.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f55591b7b3c0fe4e14ad07d7963a1931416e9b3
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_ImageReplace.py
@@ -0,0 +1,195 @@
+import torch
+import torch.nn.functional as F
+import math
+import numpy as np
+import io
+import base64
+from PIL import Image, ImageDraw
+from server import PromptServer
+
+
+class FL_ImageReplace:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "images": ("IMAGE",),
+ "replacement": ("IMAGE",),
+ "index": ("INT", {"default": 0, "min": -100, "max": 9999, "step": 1}),
+ "show_preview": ("BOOLEAN", {"default": False, "label": "Show Preview on Node"}),
+ },
+ "optional": {
+ "masks": ("MASK",),
+ "replacement_mask": ("MASK",),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE", "MASK")
+ RETURN_NAMES = ("images", "masks")
+ FUNCTION = "replace_in_batch"
+ OUTPUT_NODE = True
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def replace_in_batch(self, images, replacement, index, show_preview=False,
+ masks=None, replacement_mask=None):
+ # Ensure batch dimensions exist
+ if images.dim() == 3:
+ images = images.unsqueeze(0)
+ if replacement.dim() == 3:
+ replacement = replacement.unsqueeze(0)
+
+ batch_size = images.shape[0]
+
+ if batch_size == 0:
+ result_masks = masks if masks is not None else torch.ones(0, device=images.device)
+ return (images, result_masks)
+
+ # Resolve negative index and clamp
+ if index < 0:
+ index = batch_size + index
+ index = max(0, min(index, batch_size - 1))
+
+ B, H, W, C = images.shape
+ N, rH, rW, rC = replacement.shape
+
+ # Ensure replacement is on the same device
+ replacement = replacement.to(images.device)
+
+ # Handle channel mismatch
+ if rC != C:
+ if rC < C:
+ padding = torch.ones(N, rH, rW, C - rC, device=replacement.device)
+ replacement = torch.cat([replacement, padding], dim=-1)
+ else:
+ replacement = replacement[..., :C]
+
+ # Resize replacement if spatial dimensions don't match
+ if rH != H or rW != W:
+ replacement_chw = replacement.permute(0, 3, 1, 2)
+ is_upscaling = (H > rH) or (W > rW)
+ mode = 'bicubic' if is_upscaling else 'area'
+ replacement_chw = F.interpolate(
+ replacement_chw,
+ size=(H, W),
+ mode=mode,
+ align_corners=False if mode in ['bicubic', 'bilinear'] else None
+ )
+ replacement = replacement_chw.permute(0, 2, 3, 1)
+ replacement = replacement.clamp(0.0, 1.0)
+
+ # Truncate replacement if it exceeds remaining space
+ available = batch_size - index
+ if N > available:
+ replacement = replacement[:available]
+ N = available
+
+ # Perform the replacement
+ result = images.clone()
+ result[index:index + N] = replacement
+
+ # Track which indices were replaced
+ replaced_indices = set(range(index, index + N))
+
+ # Handle masks
+ result_masks = self._handle_masks(
+ masks, replacement_mask, batch_size, index, N, H, W, images.device
+ )
+
+ # Send preview if enabled
+ if show_preview:
+ preview_image = self._create_preview_grid(result, replaced_indices)
+ display_data = self._prepare_image_for_display(preview_image)
+ PromptServer.instance.send_sync("fl_image_replace", {"image": display_data})
+
+ return (result, result_masks)
+
+ def _handle_masks(self, masks, replacement_mask, batch_size, index, N, H, W, device):
+ if masks is not None:
+ if masks.dim() == 2:
+ masks = masks.unsqueeze(0)
+ result_masks = masks.clone()
+ tH, tW = masks.shape[1], masks.shape[2]
+ elif replacement_mask is not None:
+ result_masks = torch.ones(batch_size, H, W, device=device)
+ tH, tW = H, W
+ else:
+ return torch.ones(batch_size, H, W, device=device)
+
+ if replacement_mask is not None:
+ if replacement_mask.dim() == 2:
+ replacement_mask = replacement_mask.unsqueeze(0)
+
+ replacement_mask = replacement_mask.to(device)
+ mN, mH, mW = replacement_mask.shape
+
+ # Resize if needed
+ if mH != tH or mW != tW:
+ replacement_mask = F.interpolate(
+ replacement_mask.unsqueeze(1), size=(tH, tW), mode='nearest'
+ ).squeeze(1)
+
+ # Truncate if needed
+ available = batch_size - index
+ if mN > available:
+ replacement_mask = replacement_mask[:available]
+ mN = available
+
+ result_masks[index:index + mN] = replacement_mask
+
+ return result_masks
+
+ def _create_preview_grid(self, images, replaced_indices, max_preview_size=512, border_width=3):
+ B, H, W, C = images.shape
+
+ # Calculate grid layout
+ images_per_row = math.ceil(math.sqrt(B))
+ num_rows = math.ceil(B / images_per_row)
+
+ # Calculate thumbnail size so grid fits within max_preview_size
+ cell_w = max_preview_size // images_per_row
+ cell_h = max_preview_size // num_rows
+ scale = min(cell_w / W, cell_h / H)
+ thumb_w = max(1, int(W * scale))
+ thumb_h = max(1, int(H * scale))
+
+ # Create grid canvas
+ grid_w = thumb_w * images_per_row
+ grid_h = thumb_h * num_rows
+ grid_image = Image.new('RGB', (grid_w, grid_h), (0, 0, 0))
+ draw = ImageDraw.Draw(grid_image)
+
+ for i in range(B):
+ row = i // images_per_row
+ col = i % images_per_row
+
+ # Convert tensor to PIL thumbnail
+ img_np = (images[i].cpu().numpy() * 255).astype('uint8')
+ if img_np.shape[-1] == 4:
+ img_np = img_np[..., :3]
+ pil_img = Image.fromarray(img_np)
+ pil_img = pil_img.resize((thumb_w, thumb_h), Image.Resampling.LANCZOS)
+
+ x = col * thumb_w
+ y = row * thumb_h
+ grid_image.paste(pil_img, (x, y))
+
+ # Draw green border on replaced images
+ if i in replaced_indices:
+ for b in range(border_width):
+ draw.rectangle(
+ [x + b, y + b, x + thumb_w - 1 - b, y + thumb_h - 1 - b],
+ outline=(0, 255, 0)
+ )
+
+ return grid_image
+
+ def _prepare_image_for_display(self, pil_image):
+ """Convert PIL image to base64 for frontend display."""
+ display_img = pil_image.copy()
+ max_size = (512, 512)
+ display_img.thumbnail(max_size, Image.Resampling.LANCZOS)
+
+ buffered = io.BytesIO()
+ display_img.save(buffered, format="PNG")
+ img_str = base64.b64encode(buffered.getvalue()).decode()
+ return f"data:image/png;base64,{img_str}"
diff --git a/comfyui_fill-nodes/nodes/image/FL_ImageSelector.py b/comfyui_fill-nodes/nodes/image/FL_ImageSelector.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d098884251cf978852c319b188c3b831a4a1748
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_ImageSelector.py
@@ -0,0 +1,53 @@
+import torch
+from ..utils import tensor_to_pil, pil_to_tensor
+
+class FL_ImageSelector:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "images": ("IMAGE",),
+ "indices": ("STRING", {"default": "0,1,2"}),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "select_images"
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def select_images(self, images, indices):
+ # Get batch size for "last" keyword processing
+ batch_size = images.shape[0]
+
+ # Parse the indices string
+ try:
+ # Split by comma and process each index
+ index_parts = [idx.strip() for idx in indices.split(',') if idx.strip()]
+ index_list = []
+
+ for idx_str in index_parts:
+ if idx_str.lower() == "last":
+ # Replace "last" with the last index (batch_size - 1)
+ if batch_size > 0:
+ index_list.append(batch_size - 1)
+ else:
+ # Convert to integer
+ index_list.append(int(idx_str))
+
+ except ValueError:
+ print("Error: Indices must be comma-separated integers or 'last'")
+ # Return the original batch if parsing fails
+ return (images,)
+
+ # Validate indices
+ valid_indices = [idx for idx in index_list if 0 <= idx < batch_size]
+
+ if not valid_indices:
+ print(f"Warning: No valid indices provided. Batch size is {batch_size}")
+ # Return empty batch with same dimensions as input
+ return (images[0:0],)
+
+ # Select the specified images
+ selected_images = images[valid_indices]
+
+ return (selected_images,)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_ImageSlicer.py b/comfyui_fill-nodes/nodes/image/FL_ImageSlicer.py
new file mode 100644
index 0000000000000000000000000000000000000000..f77fd31639a537eb72f676cef9d00dfe10ba1998
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_ImageSlicer.py
@@ -0,0 +1,47 @@
+import torch
+from ..utils import tensor_to_pil, pil_to_tensor, resize_tensor
+
+
+class FL_ImageSlicer:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "width_subdivisions": ("INT", {"default": 2, "min": 1, "max": 100, "step": 1}),
+ "height_subdivisions": ("INT", {"default": 2, "min": 1, "max": 100, "step": 1}),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "slice_image"
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def slice_image(self, image, width_subdivisions, height_subdivisions):
+ # Convert from torch tensor to PIL Image
+ pil_image = tensor_to_pil(image)
+
+ # Get image dimensions
+ width, height = pil_image.size
+
+ # Calculate slice dimensions
+ slice_width = width // width_subdivisions
+ slice_height = height // height_subdivisions
+
+ # Slice the image
+ slices = []
+ for y in range(height_subdivisions):
+ for x in range(width_subdivisions):
+ left = x * slice_width
+ upper = y * slice_height
+ right = left + slice_width
+ lower = upper + slice_height
+
+ slice_img = pil_image.crop((left, upper, right, lower))
+ slice_tensor = pil_to_tensor(slice_img)
+ slices.append(slice_tensor)
+
+ # Stack all slices into a single tensor
+ output_tensor = torch.cat(slices, dim=0)
+
+ return (output_tensor,)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_ImageToMask.py b/comfyui_fill-nodes/nodes/image/FL_ImageToMask.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c2c4c7c6b11af13e9dc58bb5dd1245c82fa00d9
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_ImageToMask.py
@@ -0,0 +1,39 @@
+import torch
+
+
+class FL_ImageToMask:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "channel": (["luminance", "red", "green", "blue", "alpha"], {
+ "default": "luminance",
+ "description": "Which channel to extract as the mask"
+ }),
+ }
+ }
+
+ RETURN_TYPES = ("MASK",)
+ RETURN_NAMES = ("mask",)
+ FUNCTION = "image_to_mask"
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def image_to_mask(self, image, channel):
+ # image shape: (B, H, W, C)
+ if channel == "luminance":
+ # Standard luminance weights
+ mask = 0.2989 * image[:, :, :, 0] + 0.5870 * image[:, :, :, 1] + 0.1140 * image[:, :, :, 2]
+ elif channel == "red":
+ mask = image[:, :, :, 0]
+ elif channel == "green":
+ mask = image[:, :, :, 1]
+ elif channel == "blue":
+ mask = image[:, :, :, 2]
+ elif channel == "alpha":
+ if image.shape[3] > 3:
+ mask = image[:, :, :, 3]
+ else:
+ mask = torch.ones(image.shape[0], image.shape[1], image.shape[2], device=image.device)
+
+ return (mask,)
diff --git a/comfyui_fill-nodes/nodes/image/FL_Image_AddToBatch.py b/comfyui_fill-nodes/nodes/image/FL_Image_AddToBatch.py
new file mode 100644
index 0000000000000000000000000000000000000000..00b5558786294c7988ad00115baec6c9407eb9d9
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_Image_AddToBatch.py
@@ -0,0 +1,59 @@
+import torch
+import torch.nn.functional as F
+
+class FL_ImageAddToBatch:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "images1": ("IMAGE", {}),
+ "images2": ("IMAGE", {}),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "add_to_batch"
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def add_to_batch(self, images1, images2):
+ # Convert both inputs to the same format
+ # ComfyUI typically uses [batch, height, width, channels] format
+ # Make sure both have batch dimension
+ if images1.dim() == 3: # [height, width, channels]
+ images1 = images1.unsqueeze(0) # Add batch dimension
+
+ if images2.dim() == 3: # [height, width, channels]
+ images2 = images2.unsqueeze(0) # Add batch dimension
+
+ # Get target dimensions from first image
+ _, h1, w1, c1 = images1.shape
+ _, h2, w2, c2 = images2.shape
+
+ # Ensure channels match
+ if c1 != c2:
+ raise ValueError(f"Channel dimensions must match. Got {c1} and {c2}")
+
+ # Resize second image if dimensions don't match
+ if h1 != h2 or w1 != w2:
+ # Convert to [batch, channels, height, width] for interpolate
+ images2_chw = images2.permute(0, 3, 1, 2)
+
+ # Choose algorithm based on scaling direction
+ is_upscaling = (h1 > h2) or (w1 > w2)
+ mode = 'bicubic' if is_upscaling else 'area'
+
+ # Resize
+ images2_chw_resized = F.interpolate(
+ images2_chw,
+ size=(h1, w1),
+ mode=mode,
+ align_corners=False if mode in ['bicubic', 'bilinear'] else None
+ )
+
+ # Convert back to [batch, height, width, channels]
+ images2 = images2_chw_resized.permute(0, 2, 3, 1)
+
+ # Now concatenate along batch dimension
+ combined_images = torch.cat([images1, images2], dim=0)
+
+ return (combined_images,)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_Image_Blank.py b/comfyui_fill-nodes/nodes/image/FL_Image_Blank.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0b9ba61b6d931222e28e61386fa6b93de93b2a0
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_Image_Blank.py
@@ -0,0 +1,36 @@
+import torch
+import numpy as np
+from PIL import Image
+
+class FL_ImageBlank:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "width": ("INT", {"default": 512, "min": 64, "max": 8192, "step": 64}),
+ "height": ("INT", {"default": 512, "min": 64, "max": 8192, "step": 64}),
+ "red": ("INT", {"default": 255, "min": 0, "max": 255, "step": 1}),
+ "green": ("INT", {"default": 255, "min": 0, "max": 255, "step": 1}),
+ "blue": ("INT", {"default": 255, "min": 0, "max": 255, "step": 1}),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "create_blank_image"
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def create_blank_image(self, width, height, red, green, blue):
+ # Create a 3-channel image (H, W, C)
+ image_np = np.full((height, width, 3), [red, green, blue], dtype=np.uint8)
+
+ # Convert to PIL Image first to handle potential mode issues if needed, then to numpy float32
+ # Though for a simple color, direct numpy to tensor is fine.
+ # image_pil = Image.fromarray(image_np, 'RGB')
+ # image_np_float = np.array(image_pil).astype(np.float32) / 255.0
+
+ image_np_float = image_np.astype(np.float32) / 255.0
+
+ # Convert to tensor and add batch dimension (B, H, W, C)
+ image_tensor = torch.from_numpy(image_np_float)[None,]
+
+ return (image_tensor,)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_Image_Crop.py b/comfyui_fill-nodes/nodes/image/FL_Image_Crop.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d721ef66eae3c6a979f6fb8eebdc4c26ebe047f
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_Image_Crop.py
@@ -0,0 +1,52 @@
+import torch
+
+class FL_ImageCrop:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "image": ("IMAGE", {}),
+ "crop_direction": (["Top", "Bottom", "Left", "Right", "Top and Bottom", "Left and Right"], {"default": "Top"}),
+ "crop_amount": ("INT", {"default": 50, "min": 1, "max": 2048, "step": 1}),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "crop_image"
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def crop_image(self, image, crop_direction, crop_amount):
+ # ComfyUI images are always [B, H, W, C] format
+ batch_size = image.shape[0]
+ height = image.shape[1]
+ width = image.shape[2]
+
+ # Validate crop amount doesn't exceed image dimensions
+ if crop_direction in ["Top", "Bottom", "Top and Bottom"]:
+ max_crop = height // 2 if crop_direction == "Top and Bottom" else height - 1
+ if crop_amount > max_crop:
+ crop_amount = max_crop
+ elif crop_direction in ["Left", "Right", "Left and Right"]:
+ max_crop = width // 2 if crop_direction == "Left and Right" else width - 1
+ if crop_amount > max_crop:
+ crop_amount = max_crop
+
+ # Apply cropping based on direction
+ if crop_direction == "Top":
+ cropped_image = image[:, crop_amount:, :, :]
+ elif crop_direction == "Bottom":
+ cropped_image = image[:, :-crop_amount, :, :]
+ elif crop_direction == "Left":
+ cropped_image = image[:, :, crop_amount:, :]
+ elif crop_direction == "Right":
+ cropped_image = image[:, :, :-crop_amount, :]
+ elif crop_direction == "Top and Bottom":
+ cropped_image = image[:, crop_amount:-crop_amount, :, :]
+ elif crop_direction == "Left and Right":
+ cropped_image = image[:, :, crop_amount:-crop_amount, :]
+
+ return (cropped_image,)
+
+ @classmethod
+ def IS_CHANGED(cls, image, crop_direction, crop_amount):
+ return float("NaN") # Always update when parameters change
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_Image_Dimension_Display.py b/comfyui_fill-nodes/nodes/image/FL_Image_Dimension_Display.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3f2c0c59a3ca6e7725d90071c3f713a992948de
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_Image_Dimension_Display.py
@@ -0,0 +1,35 @@
+import torch
+from PIL import Image
+
+class FL_ImageDimensionDisplay:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "image": ("IMAGE", {}),
+ }
+ }
+
+ RETURN_TYPES = ("STRING",)
+ FUNCTION = "display_dimensions"
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def display_dimensions(self, image):
+ if isinstance(image, torch.Tensor):
+ if image.dim() == 4: # Batch dimension is present
+ _, height, width, _ = image.shape
+ elif image.dim() == 3: # No batch dimension, single image
+ height, width, _ = image.shape
+ else:
+ return ("Unsupported tensor format",)
+ elif isinstance(image, Image.Image):
+ width, height = image.size
+ else:
+ return ("Unsupported image format",)
+
+ dimensions = f"Width: {width}, Height: {height}"
+ return (dimensions,)
+
+ @classmethod
+ def IS_CHANGED(cls, image):
+ return float("NaN") # This ensures the node always updates
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_Image_Randomizer.py b/comfyui_fill-nodes/nodes/image/FL_Image_Randomizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..c905b814e6b5e9197f30f8500d7056dd9bba6934
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_Image_Randomizer.py
@@ -0,0 +1,111 @@
+import os
+import numpy as np
+import torch
+from PIL import Image, ImageOps
+import cv2
+import random
+
+class FL_ImageRandomizer:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "mode": (["Image", "Video"], {"default": "Image"}),
+ "directory_path": ("STRING", {"default": ""}),
+ "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
+ "search_subdirectories": ("BOOLEAN", {"default": False}),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE", "PATH", "IMAGE", "STRING")
+ RETURN_NAMES = ("image_batch", "selected_path", "image_list", "filename")
+ OUTPUT_IS_LIST = (False, False, True, False)
+ FUNCTION = "select_media"
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def select_media(self, mode, directory_path, seed, search_subdirectories=False):
+ if not directory_path:
+ raise ValueError("Directory path is not provided.")
+
+ if mode == "Image":
+ image_tensor, selected_path = self.select_image_data(directory_path, seed, search_subdirectories)
+ filename = os.path.basename(selected_path)
+ return (image_tensor, selected_path, [image_tensor], filename)
+ else: # Video mode
+ frames_tensor, selected_path = self.select_video_data(directory_path, seed, search_subdirectories)
+ filename = os.path.basename(selected_path)
+ return (frames_tensor, selected_path, [frames_tensor], filename) # Video frames are already a batch, but we wrap in list for consistency
+
+ def select_image_data(self, directory_path, seed, search_subdirectories=False):
+ images = self.load_files(directory_path, search_subdirectories, file_type="image")
+ if not images:
+ raise ValueError("No images found in the specified directory.")
+
+ num_images = len(images)
+ selected_index = seed % num_images
+
+ selected_image_path = images[selected_index]
+
+ image = Image.open(selected_image_path)
+ image = ImageOps.exif_transpose(image)
+ image = image.convert("RGB")
+ image_np = np.array(image).astype(np.float32) / 255.0
+ image_tensor = torch.from_numpy(image_np)[None,]
+
+ return image_tensor, selected_image_path
+
+ def select_video_data(self, directory_path, seed, search_subdirectories=False):
+ videos = self.load_files(directory_path, search_subdirectories, file_type="video")
+ if not videos:
+ raise ValueError("No videos found in the specified directory.")
+
+ num_videos = len(videos)
+ selected_index = seed % num_videos
+
+ selected_video_path = videos[selected_index]
+
+ cap = cv2.VideoCapture(selected_video_path)
+ if not cap.isOpened():
+ raise ValueError(f"Could not open video file: {selected_video_path}")
+
+ frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
+
+ if frame_count <= 0:
+ raise ValueError(f"No frames found in video: {selected_video_path}")
+
+ frames = []
+ success = True
+ while success:
+ success, frame = cap.read()
+ if success:
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
+ frame_np = np.array(frame).astype(np.float32) / 255.0
+ frames.append(frame_np)
+
+ cap.release()
+
+ if not frames:
+ raise ValueError(f"Failed to extract frames from video: {selected_video_path}")
+
+ frames_tensor = torch.from_numpy(np.stack(frames))
+
+ return frames_tensor, selected_video_path
+
+ def load_files(self, directory, search_subdirectories=False, file_type="image"):
+ if file_type == "image":
+ supported_formats = ["jpg", "jpeg", "png", "bmp", "gif", "webp"]
+ else: # video
+ supported_formats = ["mp4", "avi", "mov", "mkv", "wmv", "webm"]
+
+ file_paths = []
+
+ if search_subdirectories:
+ for root, _, files in os.walk(directory):
+ for f in files:
+ if f.split('.')[-1].lower() in supported_formats:
+ file_paths.append(os.path.join(root, f))
+ else:
+ file_paths = sorted([os.path.join(directory, f) for f in os.listdir(directory)
+ if os.path.isfile(os.path.join(directory, f)) and f.split('.')[-1].lower() in supported_formats])
+
+ return sorted(file_paths)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_LoadImage.py b/comfyui_fill-nodes/nodes/image/FL_LoadImage.py
new file mode 100644
index 0000000000000000000000000000000000000000..90b3a1002db8aad35e1647ff6251f4582a7a83f2
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_LoadImage.py
@@ -0,0 +1,123 @@
+import os
+import json
+from PIL import Image
+import torch
+import numpy as np
+from server import PromptServer
+from aiohttp import web
+import io
+
+
+class FL_LoadImage:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "root_directory": ("STRING", {"default": "./"}),
+ },
+ "optional": {
+ "selected_file": ("STRING", {"default": ""}),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE", "STRING")
+ FUNCTION = "browse_files"
+ OUTPUT_NODE = True
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def browse_files(self, root_directory, selected_file=""):
+ if selected_file and os.path.isfile(selected_file):
+ image = Image.open(selected_file)
+ # Convert RGBA to RGB if needed (for WebP with transparency)
+ if image.mode == 'RGBA':
+ # Create white background and composite
+ background = Image.new('RGB', image.size, (255, 255, 255))
+ background.paste(image, mask=image.split()[-1]) # Use alpha channel as mask
+ image = background
+ elif image.mode != 'RGB':
+ # Convert other modes (P, L, etc.) to RGB
+ image = image.convert('RGB')
+
+ image_tensor = torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
+ return (image_tensor, selected_file)
+ else:
+ return (torch.zeros(1, 1, 1, 3), "")
+
+ @classmethod
+ def IS_CHANGED(cls, root_directory, selected_file=""):
+ return selected_file
+
+ @classmethod
+ def VALIDATE_INPUTS(cls, root_directory, selected_file=""):
+ if not os.path.isdir(root_directory):
+ return "Root directory does not exist"
+ if selected_file and not os.path.isfile(selected_file):
+ return "Selected file does not exist"
+ return True
+
+
+def get_directory_structure(path):
+ structure = {"name": os.path.basename(path), "children": [], "path": path, "expanded": False}
+ try:
+ with os.scandir(path) as entries:
+ for entry in entries:
+ if entry.is_dir():
+ structure["children"].append(get_directory_structure(entry.path))
+ except PermissionError:
+ pass
+ return structure
+
+
+def get_file_list(path):
+ return [f for f in os.listdir(path) if
+ os.path.isfile(os.path.join(path, f)) and f.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp'))]
+
+
+@PromptServer.instance.routes.post("/fl_file_browser/get_directory_structure")
+async def api_get_directory_structure(request):
+ data = await request.json()
+ path = data.get("path", "./")
+
+ if not os.path.isabs(path):
+ path = os.path.abspath(path)
+
+ if not os.path.exists(path):
+ return web.json_response({"error": "Directory does not exist"}, status=400)
+
+ structure = get_directory_structure(path)
+ files = get_file_list(path)
+ return web.json_response({"structure": structure, "files": files})
+
+
+@PromptServer.instance.routes.post("/fl_file_browser/get_thumbnail")
+async def api_get_thumbnail(request):
+ data = await request.json()
+ path = data.get("path", "./")
+ file = data.get("file", "")
+
+ if not os.path.isabs(path):
+ path = os.path.abspath(path)
+
+ full_path = os.path.join(path, file)
+ if not os.path.exists(full_path):
+ return web.json_response({"error": "File does not exist"}, status=400)
+
+ try:
+ with Image.open(full_path) as img:
+ # Convert RGBA to RGB if needed (for WebP with transparency)
+ if img.mode == 'RGBA':
+ # Create white background and composite
+ background = Image.new('RGB', img.size, (255, 255, 255))
+ background.paste(img, mask=img.split()[-1]) # Use alpha channel as mask
+ img = background
+ elif img.mode != 'RGB':
+ # Convert other modes (P, L, etc.) to RGB
+ img = img.convert('RGB')
+
+ img.thumbnail((80, 80))
+ buf = io.BytesIO()
+ img.save(buf, format='PNG')
+ buf.seek(0)
+ return web.Response(body=buf.read(), content_type='image/png')
+ except Exception as e:
+ return web.json_response({"error": str(e)}, status=500)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_PaddingRemover.py b/comfyui_fill-nodes/nodes/image/FL_PaddingRemover.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2b2cbb827c77c6aef85224282bf2266e0bfc3bb
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_PaddingRemover.py
@@ -0,0 +1,331 @@
+import torch
+import numpy as np
+from PIL import Image, ImageDraw
+
+class FL_PaddingRemover:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "tolerance": ("INT", {"default": 30, "min": 0, "max": 255, "step": 1}),
+ "min_content_size": ("INT", {"default": 20, "min": 1, "max": 1000, "step": 1}),
+ "sides_trim": ("INT", {"default": 1, "min": 0, "max": 256, "step": 1}),
+ "top_bottom_trim": ("INT", {"default": 1, "min": 0, "max": 256, "step": 1}),
+ "debug_view": ("BOOLEAN", {"default": False}),
+ "use_gpu": ("BOOLEAN", {"default": False}),
+ },
+ "optional": {},
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "remove_padding"
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def remove_padding(self, image, tolerance=30, min_content_size=20, sides_trim=1, top_bottom_trim=1, debug_view=False, use_gpu=False):
+ # Check if GPU is available when requested
+ use_gpu = use_gpu and torch.cuda.is_available()
+ if use_gpu:
+ print("Using GPU for padding removal")
+ else:
+ print("Using CPU for padding removal")
+ # Process each image in the batch
+ batch_size = image.shape[0]
+ result_tensors = []
+
+ for b in range(batch_size):
+ # Get the current image tensor
+ img_tensor = image[b]
+
+ # Print the tensor shape for debugging
+ print(f"Input tensor shape: {img_tensor.shape}")
+
+ if use_gpu:
+ # GPU processing path
+ # Store original format for later conversion
+ is_chw_format = len(img_tensor.shape) == 3 and img_tensor.shape[0] in [1, 3, 4]
+
+ # Find the bounding box directly using GPU tensors
+ # Scale to 0-255 range for consistency with CPU version
+ img_tensor_255 = img_tensor * 255
+
+ # Find the bounding box of the content using GPU
+ bbox = self.find_content_bbox_gpu(img_tensor_255, tolerance, min_content_size)
+
+ # Get dimensions for validation
+ if is_chw_format:
+ height, width = img_tensor.shape[1], img_tensor.shape[2]
+ else:
+ height, width = img_tensor.shape[0], img_tensor.shape[1]
+ else:
+ # CPU processing path (original implementation)
+ # Check if the tensor is already in [H, W, C] format
+ if len(img_tensor.shape) == 3 and img_tensor.shape[2] in [1, 3, 4]:
+ # Format is [H, W, C]
+ img_np = img_tensor.cpu().numpy()
+ channels = img_np.shape[2]
+ elif len(img_tensor.shape) == 3 and img_tensor.shape[0] in [1, 3, 4]:
+ # Format is [C, H, W], convert to [H, W, C]
+ img_np = img_tensor.permute(1, 2, 0).cpu().numpy()
+ channels = img_np.shape[2]
+ else:
+ # Unsupported format
+ print(f"Unsupported tensor shape: {img_tensor.shape}")
+ result_tensors.append(img_tensor)
+ continue
+
+ # Scale to 0-255 range for PIL
+ img_np_uint8 = (img_np * 255).astype(np.uint8)
+
+ # Create PIL image
+ img_pil = Image.fromarray(img_np_uint8)
+
+ # Find the bounding box of the content
+ bbox = self.find_content_bbox(img_np_uint8, tolerance, min_content_size)
+
+ # Get dimensions for validation
+ height, width = img_pil.size[1], img_pil.size[0]
+
+ # Apply additional trimming to the bounding box
+ left, top, right, bottom = bbox
+
+ # Apply sides trimming
+ left += sides_trim
+ right -= sides_trim
+
+ # Apply top/bottom trimming
+ top += top_bottom_trim
+ bottom -= top_bottom_trim
+
+ # Ensure the bounding box is valid
+ left = max(0, left)
+ top = max(0, top)
+ right = min(width, right)
+ bottom = min(height, bottom)
+
+ # Ensure we have a valid box (width and height > 0)
+ if right <= left or bottom <= top:
+ print("Warning: After trimming, the bounding box is invalid. Using original bbox.")
+ left, top, right, bottom = bbox
+
+ # Update the bounding box
+ bbox = (left, top, right, bottom)
+
+ if use_gpu:
+ # GPU processing path
+ if debug_view:
+ # For debug view, we need to move to CPU to use PIL for drawing
+ if is_chw_format:
+ # Convert [C,H,W] to [H,W,C] for PIL
+ cpu_tensor = img_tensor.permute(1, 2, 0).cpu()
+ else:
+ cpu_tensor = img_tensor.cpu()
+
+ # Convert to numpy and scale to 0-255
+ img_np = cpu_tensor.numpy() * 255
+ img_np_uint8 = img_np.astype(np.uint8)
+ img_pil = Image.fromarray(img_np_uint8)
+
+ # Create debug view with rectangle
+ debug_img = img_pil.copy()
+ draw = ImageDraw.Draw(debug_img)
+ draw.rectangle(bbox, outline=(255, 0, 0), width=2)
+
+ # Convert back to tensor
+ debug_np = np.array(debug_img).astype(np.float32) / 255.0
+ if is_chw_format:
+ debug_tensor = torch.from_numpy(debug_np).permute(2, 0, 1)
+ else:
+ debug_tensor = torch.from_numpy(debug_np)
+
+ result_tensors.append(debug_tensor)
+ else:
+ # Crop directly on GPU tensor
+ if is_chw_format:
+ # For [C,H,W] format
+ cropped_tensor = img_tensor[:, top:bottom, left:right]
+ else:
+ # For [H,W,C] format
+ cropped_tensor = img_tensor[top:bottom, left:right, :]
+
+ print(f"Output tensor shape: {cropped_tensor.shape}")
+ result_tensors.append(cropped_tensor)
+ else:
+ # CPU processing path (original implementation)
+ if debug_view:
+ # Create a debug view with the detected content area highlighted
+ debug_img = img_pil.copy()
+ draw = ImageDraw.Draw(debug_img)
+ draw.rectangle(bbox, outline=(255, 0, 0), width=2)
+
+ # Convert back to numpy array
+ debug_np = np.array(debug_img).astype(np.float32) / 255.0
+
+ # Ensure the output has the same shape as the input
+ if len(img_tensor.shape) == 3 and img_tensor.shape[0] in [1, 3, 4]:
+ # If input was [C, H, W], convert back to that format
+ debug_tensor = torch.from_numpy(debug_np).permute(2, 0, 1)
+ else:
+ # Otherwise keep as [H, W, C]
+ debug_tensor = torch.from_numpy(debug_np)
+
+ result_tensors.append(debug_tensor)
+ else:
+ # Crop the image to the content bounding box
+ cropped_img = img_pil.crop(bbox)
+
+ # Convert back to numpy array
+ cropped_np = np.array(cropped_img).astype(np.float32) / 255.0
+
+ # Ensure the output has the same shape as the input
+ if len(img_tensor.shape) == 3 and img_tensor.shape[0] in [1, 3, 4]:
+ # If input was [C, H, W], convert back to that format
+ cropped_tensor = torch.from_numpy(cropped_np).permute(2, 0, 1)
+ else:
+ # Otherwise keep as [H, W, C]
+ cropped_tensor = torch.from_numpy(cropped_np)
+
+ # Print the output tensor shape for debugging
+ print(f"Output tensor shape: {cropped_tensor.shape}")
+
+ result_tensors.append(cropped_tensor)
+
+ # Stack the processed images back into a batch
+ return (torch.stack(result_tensors),)
+
+ def find_content_bbox(self, img_array, tolerance, min_content_size):
+ """Find the bounding box of the content in the image by detecting padding."""
+ height, width = img_array.shape[:2]
+
+ # Improved padding detection using edge color sampling and histogram analysis
+ def is_padding_row(y):
+ # Sample colors from the row
+ row = img_array[y, :, :]
+
+ # Get the edge color (first pixel in the row)
+ edge_color = row[0]
+
+ # Count pixels that are different from the edge color by more than the tolerance
+ different_pixels = 0
+ for x in range(width):
+ pixel = row[x]
+ diff = np.sum(np.abs(pixel.astype(int) - edge_color.astype(int)))
+ if diff > tolerance:
+ different_pixels += 1
+
+ # If less than 5% of pixels are different, consider it padding
+ return different_pixels < (width * 0.05)
+
+ def is_padding_col(x):
+ # Sample colors from the column
+ col = img_array[:, x, :]
+
+ # Get the edge color (first pixel in the column)
+ edge_color = col[0]
+
+ # Count pixels that are different from the edge color by more than the tolerance
+ different_pixels = 0
+ for y in range(height):
+ pixel = col[y]
+ diff = np.sum(np.abs(pixel.astype(int) - edge_color.astype(int)))
+ if diff > tolerance:
+ different_pixels += 1
+
+ # If less than 5% of pixels are different, consider it padding
+ return different_pixels < (height * 0.05)
+
+ # Find top padding
+ top = 0
+ while top < height - min_content_size and is_padding_row(top):
+ top += 1
+
+ # Find bottom padding
+ bottom = height - 1
+ while bottom >= top + min_content_size and is_padding_row(bottom):
+ bottom -= 1
+
+ # Find left padding
+ left = 0
+ while left < width - min_content_size and is_padding_col(left):
+ left += 1
+
+ # Find right padding
+ right = width - 1
+ while right >= left + min_content_size and is_padding_col(right):
+ right -= 1
+
+ # Ensure we have at least min_content_size x min_content_size content
+ if right - left < min_content_size or bottom - top < min_content_size:
+ return (0, 0, width, height) # Return the full image if content is too small
+
+ # Return the bounding box (left, top, right, bottom)
+ return (left, top, right + 1, bottom + 1) # +1 because PIL crop is exclusive on right/bottom
+
+ def find_content_bbox_gpu(self, img_tensor, tolerance, min_content_size):
+ """GPU version of find_content_bbox that works directly with tensors."""
+ # Ensure the tensor is in the right format [H, W, C]
+ if img_tensor.shape[0] in [1, 3, 4] and len(img_tensor.shape) == 3:
+ # Format is [C, H, W], convert to [H, W, C]
+ img_tensor = img_tensor.permute(1, 2, 0)
+
+ height, width = img_tensor.shape[:2]
+
+ # Helper functions for GPU tensor operations
+ def is_padding_row_gpu(y):
+ # Get the row
+ row = img_tensor[y:y+1, :, :]
+
+ # Get the edge color (first pixel)
+ edge_color = row[:, 0:1, :]
+
+ # Calculate differences from edge color for all pixels in the row
+ diff = torch.sum(torch.abs(row - edge_color), dim=2)
+
+ # Count pixels that differ by more than the tolerance
+ different_pixels = torch.sum(diff > tolerance).item()
+
+ # If less than 5% of pixels are different, consider it padding
+ return different_pixels < (width * 0.05)
+
+ def is_padding_col_gpu(x):
+ # Get the column
+ col = img_tensor[:, x:x+1, :]
+
+ # Get the edge color (first pixel)
+ edge_color = col[0:1, :, :]
+
+ # Calculate differences from edge color for all pixels in the column
+ diff = torch.sum(torch.abs(col - edge_color), dim=2)
+
+ # Count pixels that differ by more than the tolerance
+ different_pixels = torch.sum(diff > tolerance).item()
+
+ # If less than 5% of pixels are different, consider it padding
+ return different_pixels < (height * 0.05)
+
+ # Find top padding
+ top = 0
+ while top < height - min_content_size and is_padding_row_gpu(top):
+ top += 1
+
+ # Find bottom padding
+ bottom = height - 1
+ while bottom >= top + min_content_size and is_padding_row_gpu(bottom):
+ bottom -= 1
+
+ # Find left padding
+ left = 0
+ while left < width - min_content_size and is_padding_col_gpu(left):
+ left += 1
+
+ # Find right padding
+ right = width - 1
+ while right >= left + min_content_size and is_padding_col_gpu(right):
+ right -= 1
+
+ # Ensure we have at least min_content_size x min_content_size content
+ if right - left < min_content_size or bottom - top < min_content_size:
+ return (0, 0, width, height) # Return the full image if content is too small
+
+ # Return the bounding box (left, top, right, bottom)
+ return (left, top, right + 1, bottom + 1) # +1 because crop is exclusive on right/bottom
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_ReplaceColor.py b/comfyui_fill-nodes/nodes/image/FL_ReplaceColor.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7f9b90b7015a4cb6ad1e4690ab8d45df6ea5d5a
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_ReplaceColor.py
@@ -0,0 +1,131 @@
+import torch
+import numpy as np
+from PIL import Image
+from scipy import ndimage
+
+
+class FL_ReplaceColor:
+ DESCRIPTION = """
+FL_ReplaceColor allows you to replace a specific color in an image with another color.
+You can use the interactive color pickers to select the source color to replace and the target color to replace it with.
+The tolerance parameter controls how closely colors need to match the source color to be replaced.
+"""
+
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "source_color": ("STRING", {"default": "#FF0000"}),
+ "target_color": ("STRING", {"default": "#00FF00"}),
+ "tolerance": ("FLOAT", {
+ "default": 0.1,
+ "min": 0.0,
+ "max": 1.0,
+ "step": 0.01,
+ "description": "Color matching tolerance (0.0 = exact match, 1.0 = very loose)"
+ }),
+ "expand_pixels": ("INT", {
+ "default": 0,
+ "min": 0,
+ "max": 100,
+ "step": 1,
+ "description": "Expand replacement area by N pixels (dilation)"
+ }),
+ "contract_pixels": ("INT", {
+ "default": 0,
+ "min": 0,
+ "max": 100,
+ "step": 1,
+ "description": "Contract replacement area by N pixels (erosion)"
+ })
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "replace_color"
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def replace_color(self, image: torch.Tensor, source_color: str, target_color: str, tolerance: float, expand_pixels: int, contract_pixels: int):
+ batch_size = image.shape[0]
+ result = torch.zeros_like(image)
+
+ # Convert hex colors to RGB
+ source_rgb = self.hex_to_rgb(source_color)
+ target_rgb = self.hex_to_rgb(target_color)
+
+ for b in range(batch_size):
+ img_b = image[b] * 255.0
+ img_array = img_b.numpy().astype('uint8')
+
+ # Convert to PIL Image for processing
+ pil_image = Image.fromarray(img_array, 'RGB')
+ result_image = self.replace_color_in_image(pil_image, source_rgb, target_rgb, tolerance, expand_pixels, contract_pixels)
+
+ # Convert back to tensor
+ result_array = np.array(result_image).astype(np.float32) / 255.0
+ result[b] = torch.from_numpy(result_array)
+
+ return (result,)
+
+ def hex_to_rgb(self, hex_color: str):
+ """Convert hex color to RGB tuple"""
+ hex_color = hex_color.lstrip('#')
+ return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
+
+ def replace_color_in_image(self, image: Image.Image, source_rgb, target_rgb, tolerance, expand_pixels, contract_pixels):
+ """Replace colors in PIL Image with expand/contract controls"""
+ img_array = np.array(image)
+
+ # Calculate color distance for each pixel
+ source_color = np.array(source_rgb)
+
+ # Compute Euclidean distance in RGB space
+ distances = np.sqrt(np.sum((img_array - source_color) ** 2, axis=2))
+
+ # Normalize distance to 0-1 range (max distance in RGB is sqrt(3*255^2))
+ max_distance = np.sqrt(3 * 255 ** 2)
+ normalized_distances = distances / max_distance
+
+ # Create initial mask for pixels within tolerance
+ mask = normalized_distances <= tolerance
+
+ # Apply morphological operations for expand/contract
+ mask = self.apply_morphological_operations(mask, expand_pixels, contract_pixels)
+
+ # Replace colors
+ result_array = img_array.copy()
+ result_array[mask] = target_rgb
+
+ return Image.fromarray(result_array.astype(np.uint8))
+
+ def apply_morphological_operations(self, mask, expand_pixels, contract_pixels):
+ """Apply morphological operations to expand or contract the mask"""
+ processed_mask = mask.copy()
+
+ # Apply contraction first (erosion) if specified
+ if contract_pixels > 0:
+ # Create circular structuring element for more natural results
+ structure = self.create_circular_kernel(contract_pixels)
+ processed_mask = ndimage.binary_erosion(processed_mask, structure=structure)
+
+ # Apply expansion (dilation) if specified
+ if expand_pixels > 0:
+ # Create circular structuring element for more natural results
+ structure = self.create_circular_kernel(expand_pixels)
+ processed_mask = ndimage.binary_dilation(processed_mask, structure=structure)
+
+ return processed_mask
+
+ def create_circular_kernel(self, radius):
+ """Create a circular structuring element for morphological operations"""
+ if radius == 0:
+ return None
+
+ # Create a circular kernel
+ size = 2 * radius + 1
+ y, x = np.ogrid[:size, :size]
+ center = radius
+ mask = (x - center) ** 2 + (y - center) ** 2 <= radius ** 2
+
+ return mask.astype(np.uint8)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_SaveAndDisplayImage.py b/comfyui_fill-nodes/nodes/image/FL_SaveAndDisplayImage.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a7f63c95a1dbca912bcdb2c056923cd82760d40
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_SaveAndDisplayImage.py
@@ -0,0 +1,29 @@
+import os
+import folder_paths
+from nodes import SaveImage
+
+
+class FL_SaveAndDisplayImage(SaveImage):
+ @classmethod
+ def INPUT_TYPES(s):
+ return {"required":
+ {"images": ("IMAGE",),
+ "filename_prefix": ("STRING", {"default": "ComfyUI"})},
+ "hidden":
+ {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"}
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "save_and_display_images"
+ OUTPUT_NODE = True
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def save_and_display_images(self, images, filename_prefix="ComfyUI", prompt=None, extra_pnginfo=None):
+ results = self.save_images(images, filename_prefix, prompt, extra_pnginfo)
+
+ return {
+ "ui": {
+ "images": results['ui']['images']
+ },
+ "result": (images,)
+ }
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_SaveImages.py b/comfyui_fill-nodes/nodes/image/FL_SaveImages.py
new file mode 100644
index 0000000000000000000000000000000000000000..afca81753d9ea7c5241c3b09d0eb7a3bc76ba0e8
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_SaveImages.py
@@ -0,0 +1,117 @@
+import os
+import re
+import torch
+from PIL import Image
+import numpy as np
+import json
+
+class FL_SaveImages:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "images": ("IMAGE",),
+ "base_directory": ("STRING", {"default": "./output"}),
+ "folder_structure": ("STRING", {"default": "[]"}),
+ "file_name_template": ("STRING", {"default": "image_{index}.png"}),
+ "start_index": ("INT", {"default": 1, "min": 0, "max": 1000000}),
+ "auto_increment": ("BOOLEAN", {"default": True}),
+ },
+ "optional": {
+ "metadata": ("STRING", {"default": ""}),
+ }
+ }
+
+ RETURN_TYPES = ("STRING",)
+ FUNCTION = "save_images"
+ OUTPUT_NODE = True
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def save_images(self, images, base_directory, folder_structure, file_name_template, start_index, auto_increment=True, metadata=""):
+ saved_paths = []
+ folder_structure = json.loads(folder_structure)
+
+ # Ensure base directory exists
+ os.makedirs(base_directory, exist_ok=True)
+
+ # Create the full folder path based on the folder structure
+ full_folder_path = self.create_folder_path(base_directory, folder_structure)
+ os.makedirs(full_folder_path, exist_ok=True)
+
+ batch_size = len(images)
+ has_index_placeholder = "{index}" in file_name_template
+
+ # If auto_increment is enabled, find the next available index
+ if auto_increment and has_index_placeholder:
+ start_index = self.find_next_index(full_folder_path, file_name_template, start_index)
+
+ for i, image in enumerate(images):
+ # Convert the image tensor to a PIL Image
+ img = Image.fromarray((image.cpu().numpy() * 255).astype(np.uint8))
+
+ # Determine the filename based on batch size and placeholder
+ if batch_size > 1:
+ # For batches, always use an index
+ current_index = start_index + i
+ padded_index = f"{current_index:04d}"
+
+ if has_index_placeholder:
+ # Replace {index} with the current counter
+ full_file_name = file_name_template.format(index=padded_index)
+ else:
+ # Append index before extension
+ base_name, ext = os.path.splitext(file_name_template)
+ full_file_name = f"{base_name}_{padded_index}{ext}"
+ else:
+ # Single image
+ if has_index_placeholder:
+ # Replace {index} with start_index
+ padded_index = f"{start_index:04d}"
+ full_file_name = file_name_template.format(index=padded_index)
+ else:
+ # Use exact filename
+ full_file_name = file_name_template
+
+ full_file_path = os.path.join(full_folder_path, full_file_name)
+
+ # Save the image
+ img.save(full_file_path)
+
+ # Save metadata if provided
+ if metadata:
+ metadata_file_name = f"{os.path.splitext(full_file_name)[0]}_metadata.txt"
+ metadata_file_path = os.path.join(full_folder_path, metadata_file_name)
+ with open(metadata_file_path, 'w') as f:
+ f.write(metadata)
+
+ saved_paths.append(full_file_path)
+
+ return (", ".join(saved_paths),)
+
+ def find_next_index(self, folder_path, file_name_template, min_index):
+ """Find the next available index by checking existing files in the folder."""
+ if not os.path.exists(folder_path):
+ return min_index
+
+ # Build a regex pattern from the template to extract existing indices
+ # Escape special regex chars, then replace {index} with a capture group
+ pattern_str = re.escape(file_name_template).replace(r"\{index\}", r"(\d+)")
+ pattern = re.compile(f"^{pattern_str}$")
+
+ max_found = min_index - 1
+ for filename in os.listdir(folder_path):
+ match = pattern.match(filename)
+ if match:
+ index = int(match.group(1))
+ if index > max_found:
+ max_found = index
+
+ return max_found + 1
+
+ def create_folder_path(self, base_directory, folder_structure):
+ path = base_directory
+ for folder in folder_structure:
+ path = os.path.join(path, folder['name'])
+ for child in folder['children']:
+ path = self.create_folder_path(path, [child])
+ return path
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_SaveRGBAAnimatedWebP.py b/comfyui_fill-nodes/nodes/image/FL_SaveRGBAAnimatedWebP.py
new file mode 100644
index 0000000000000000000000000000000000000000..87a93b5a731cbb6716eb8551fb1f03ae65ae8ac8
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_SaveRGBAAnimatedWebP.py
@@ -0,0 +1,118 @@
+import folder_paths
+from comfy.cli_args import args
+
+from PIL import Image, ImageDraw
+import numpy as np
+import os
+import zipfile
+import json
+import cv2
+
+class FL_SaveRGBAAnimatedWebP:
+ def __init__(self):
+ self.output_dir = folder_paths.get_output_directory()
+ self.type = "output"
+ self.prefix_append = ""
+
+ methods = {"default": 4, "fastest": 0, "slowest": 6}
+ @classmethod
+ def INPUT_TYPES(s):
+ return {"required":
+ {"images_rgb": ("IMAGE", ),
+ "images_alpha": ("IMAGE", ),
+ "filename_prefix": ("STRING", {"default": "ComfyUI"}),
+ "fps": ("FLOAT", {"default": 16.0, "min": 0.01, "max": 1000.0, "step": 0.01}),
+ "lossless": ("BOOLEAN", {"default": True}),
+ "quality": ("INT", {"default": 80, "min": 0, "max": 100}),
+ "method": (list(s.methods.keys()),),
+ # "num_frames": ("INT", {"default": 0, "min": 0, "max": 8192}),
+ },
+ "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
+ }
+
+ RETURN_TYPES = ()
+ FUNCTION = "save_images"
+
+ OUTPUT_NODE = True
+
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def save_images(self, images_rgb, images_alpha, fps, filename_prefix, lossless, quality, method, num_frames=0, prompt=None, extra_pnginfo=None):
+ method = self.methods.get(method)
+ filename_prefix += self.prefix_append
+ full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir, images_rgb[0].shape[1], images_rgb[0].shape[0])
+ results: list[FileLocator] = []
+
+ def create_checkerboard(size=30, pattern_size=(830, 480), color1=(140, 140, 140), color2=(113, 113, 113)):
+ img = Image.new('RGB', (pattern_size[0], pattern_size[1]), color1)
+ draw = ImageDraw.Draw(img)
+ for i in range(0, pattern_size[0], size):
+ for j in range(0, pattern_size[1], size):
+ if (i + j) // size % 2 == 0:
+ draw.rectangle([i, j, i+size, j+size], fill=color2)
+ return img
+
+ pil_images = []
+ np_images = []
+ for image_rgb, image_alpha in zip(images_rgb, images_alpha):
+
+ def image_to_np(image):
+ i = 255. * image.cpu().numpy()
+ return np.clip(i, 0, 255)
+
+ def image_to_single_color_np(image):
+ i = 1. * image.cpu().numpy()
+ i = (i[:,:,0:1] + i[:,:,1:2] + i[:,:,2:3]) / 3.
+ return np.clip(i, 0, 1)
+
+ image_rgb = image_to_np(image_rgb)
+ alpha_channel = image_to_single_color_np(image_alpha)
+
+ np_images.append(np.concatenate([image_rgb[:,:,::-1], alpha_channel*255], axis=2).astype(np.uint8))
+ checkerboard = create_checkerboard(pattern_size=(image_rgb.shape[1], image_rgb.shape[0]))
+
+ images = image_rgb * alpha_channel + checkerboard * (1-alpha_channel)
+ img = Image.fromarray(images.astype(np.uint8))
+ pil_images.append(img)
+
+ metadata = pil_images[0].getexif()
+ if not args.disable_metadata:
+ if prompt is not None:
+ metadata[0x0110] = "prompt:{}".format(json.dumps(prompt))
+ if extra_pnginfo is not None:
+ inital_exif = 0x010f
+ for x in extra_pnginfo:
+ metadata[inital_exif] = "{}:{}".format(x, json.dumps(extra_pnginfo[x]))
+ inital_exif -= 1
+
+ if num_frames == 0:
+ num_frames = len(pil_images)
+
+ c = len(pil_images)
+ for i in range(0, c, num_frames):
+ file = f"{filename}_{counter:05}_.webp"
+ pil_images[i].save(os.path.join(full_output_folder, file), save_all=True, duration=int(1000.0/fps), append_images=pil_images[i + 1:i + num_frames], exif=metadata, lossless=lossless, quality=quality, method=method)
+ results.append({
+ "filename": file,
+ "subfolder": subfolder,
+ "type": self.type
+ })
+ counter += 1
+
+ zip_path = os.path.join(full_output_folder, f"{filename}_{counter-1:05}.zip")
+ print("Saving zip tp", zip_path)
+
+ with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
+ for idx, img in enumerate(np_images):
+ success, buffer = cv2.imencode(".png", img)
+ if not success:
+ print(f"Failed to encode image {idx}, skipping...")
+ continue
+
+ filename = f"img_{idx:03d}.png"
+ zipf.writestr(filename, buffer.tobytes())
+
+ animated = num_frames != 1
+ return { "ui": { "images": results, "animated": (animated,) }}
+
+
diff --git a/comfyui_fill-nodes/nodes/image/FL_SaveWebM.py b/comfyui_fill-nodes/nodes/image/FL_SaveWebM.py
new file mode 100644
index 0000000000000000000000000000000000000000..b69e69e5d09e8534e41e489d1e85d4871cfa5860
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_SaveWebM.py
@@ -0,0 +1,118 @@
+import os
+import torch
+import numpy as np
+from PIL import Image
+import imageio # For WebM creation
+import shutil
+
+class FL_SaveWebM:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "images": ("IMAGE",),
+ "directory": ("STRING", {"default": "./output/webm"}),
+ "filename_prefix": ("STRING", {"default": "animation"}),
+ "fps": ("INT", {"default": 15, "min": 1, "max": 60}),
+ "preserve_alpha": (["disable", "enable"], {"default": "disable"}),
+ "loop_count": ("INT", {"default": 0, "min": 0, "max": 100, "description": "0 for infinite loop (Note: may not affect WebM playback directly via imageio)"}),
+ "quality": ("FLOAT", {"default": 5.0, "min": 0.0, "max": 10.0, "step":0.1, "description": "Quality (0-10, lower is better for VP9, but imageio might map it, typically 5-8 is good)"}),
+ },
+ "optional": {
+ "metadata_comment": ("STRING", {"multiline": True, "default": "Created with ComfyUI FL_SaveWebM"}),
+ }
+ }
+
+ RETURN_TYPES = ("STRING",) # Returns the path to the saved WebM file
+ FUNCTION = "save_webm_animation"
+ OUTPUT_NODE = True
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def save_webm_animation(self, images: torch.Tensor, directory: str, filename_prefix: str, fps: int, preserve_alpha: str, loop_count: int, quality: float, metadata_comment: str = ""):
+ if not os.path.exists(directory):
+ os.makedirs(directory, exist_ok=True)
+
+ # Determine unique filename
+ i = 0
+ while True:
+ filename = f"{filename_prefix}_{i:04d}.webm"
+ filepath = os.path.join(directory, filename)
+ if not os.path.exists(filepath):
+ break
+ i += 1
+
+ batch_size, height, width, channels = images.shape
+ frames = []
+
+ has_alpha = preserve_alpha == "enable" and channels == 4
+
+ for i in range(batch_size):
+ img_tensor = images[i] # HWC
+ # Convert to numpy array, scale to 0-255, and change to uint8
+ np_frame = (img_tensor.cpu().numpy() * 255).astype(np.uint8)
+
+ if has_alpha:
+ # Ensure it's RGBA
+ if np_frame.shape[-1] == 3: # If input is RGB but alpha is requested, add opaque alpha
+ alpha_channel = np.full((height, width, 1), 255, dtype=np.uint8)
+ np_frame = np.concatenate((np_frame, alpha_channel), axis=-1)
+ # imageio expects RGBA for formats supporting alpha
+ else:
+ # Ensure it's RGB if alpha is not preserved or not present
+ if np_frame.shape[-1] == 4:
+ np_frame = np_frame[..., :3] # Slice off alpha
+
+ frames.append(np_frame)
+
+ # imageio-ffmpeg is typically needed for WebM (VP9)
+ # For VP9 with alpha, the pixel format 'yuva420p' is often used.
+ # imageio's mimsave handles this if the input frames have an alpha channel.
+
+ writer_kwargs = {
+ 'fps': fps,
+ 'quality': quality, # For VP9, lower is better. imageio might map this.
+ # 'loop': loop_count, # Loop is not directly supported for WebM writer like this
+ 'format': 'WEBM', # Explicitly specify WEBM
+ 'codec': 'libvpx-vp9', # VP9 is standard for WebM
+ }
+
+ # Handle metadata separately
+ ffmpeg_metadata_params = []
+ if metadata_comment:
+ ffmpeg_metadata_params.extend(['-metadata', f'comment={metadata_comment}'])
+
+ if ffmpeg_metadata_params:
+ writer_kwargs['ffmpeg_params'] = ffmpeg_metadata_params
+
+ if has_alpha:
+ print("Attempting to save WebM with alpha channel. Frames are RGBA. Relying on imageio and libvpx-vp9 for alpha handling.")
+ else:
+ print("Saving WebM without alpha channel (RGB).")
+
+ try:
+ # When codec is 'libvpx-vp9' and frames are RGBA, imageio-ffmpeg should handle alpha.
+ imageio.mimsave(filepath, frames, **writer_kwargs)
+ print(f"Saved WebM to: {filepath}")
+ except Exception as e:
+ # Fallback if ffmpeg is not found or there's an issue
+ if 'ffmpeg' in str(e).lower() and shutil.which('ffmpeg') is None:
+ msg = "ffmpeg not found. Please install ffmpeg and ensure it's in your system PATH. Cannot save WebM."
+ print(f"Error: {msg} - {e}")
+ return (f"Error: {msg}",)
+
+ print(f"Error saving WebM: {e}")
+ # Attempt fallback without specific codec or alpha handling if primary fails
+ try:
+ print("Attempting fallback WebM save...")
+ fallback_kwargs = {'fps': fps, 'format': 'WEBM'} # Removed loop from fallback as well
+ if not has_alpha: # If original attempt was with alpha, try without for fallback
+ rgb_frames = [(frame[..., :3] if frame.shape[-1] == 4 else frame) for frame in frames]
+ imageio.mimsave(filepath, rgb_frames, **fallback_kwargs)
+ else: # If original was already RGB or alpha is critical, this might not help much
+ imageio.mimsave(filepath, frames, **fallback_kwargs)
+ print(f"Fallback WebM saved to: {filepath}")
+ except Exception as e2:
+ print(f"Fallback WebM save also failed: {e2}")
+ return (f"Error: Could not save WebM. {e} / {e2}",)
+
+ return (filepath,)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/FL_SaveWebpImages.py b/comfyui_fill-nodes/nodes/image/FL_SaveWebpImages.py
new file mode 100644
index 0000000000000000000000000000000000000000..614968d9c4771bc236a6469ea426c5e958ebb42c
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/FL_SaveWebpImages.py
@@ -0,0 +1,58 @@
+import os
+import folder_paths
+from nodes import SaveImage
+from PIL import Image
+import io
+
+
+class FL_SaveWebPImage(SaveImage):
+ @classmethod
+ def INPUT_TYPES(s):
+ return {"required":
+ {"images": ("IMAGE",),
+ "filename_prefix": ("STRING", {"default": "ComfyUI"}),
+ "quality": ("INT", {"default": 80, "min": 1, "max": 100, "step": 1})},
+ "hidden":
+ {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"}
+ }
+
+ RETURN_TYPES = ("IMAGE", "STRING")
+ FUNCTION = "save_webp_images"
+ OUTPUT_NODE = True
+ CATEGORY = "🏵️Fill Nodes/Image"
+
+ def save_webp_images(self, images, filename_prefix="ComfyUI", quality=80, prompt=None, extra_pnginfo=None):
+ output_dir = folder_paths.get_output_directory()
+ full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(
+ filename_prefix, output_dir)
+ results = []
+
+ for image in images:
+ i = 255. * image.cpu().numpy()
+ img = Image.fromarray(i.astype('uint8'))
+ file = f"{filename}_{counter:05}_.webp"
+ fullpath = os.path.join(full_output_folder, file)
+
+ img.save(fullpath, 'WEBP', quality=quality)
+ results.append({
+ "filename": file,
+ "subfolder": subfolder,
+ "type": "output"
+ })
+ counter += 1
+
+ return {
+ "ui": {
+ "images": results
+ },
+ "result": (images, f"Saved {len(results)} WebP image(s)")
+ }
+
+
+NODE_CLASS_MAPPINGS = {
+ "SaveWebPImage": FL_SaveWebPImage
+}
+
+NODE_DISPLAY_NAME_MAPPINGS = {
+ "SaveWebPImage": "Save WebP Image"
+}
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/image/__init__.py b/comfyui_fill-nodes/nodes/image/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..37913902a68b965ba0e1f7d2f25ad1f5884170d5
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/image/__init__.py
@@ -0,0 +1 @@
+"""Fill-Nodes Category: Image"""
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_AnimeLineExtractor.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_AnimeLineExtractor.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f3d8f716d24f289d406b8e6e908d2e28ea623556
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_AnimeLineExtractor.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_ApplyMask.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ApplyMask.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d41b46a60cbcdb76dd7a37877319be840d7e56bc
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ApplyMask.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_BlackFrameReject.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_BlackFrameReject.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..114331a5b98e8588771ca350a23240f8000e5c83
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_BlackFrameReject.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_CoTracker.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_CoTracker.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f9b407dcc56710ac84b61f8f6ca709abf7839274
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_CoTracker.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_CreateShapeImageOnPath.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_CreateShapeImageOnPath.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..81c5da14fa054021e05e96915e88a40277399fa1
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_CreateShapeImageOnPath.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageAddNoise.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageAddNoise.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2a2268cdb3a045f413bbf8d5afdabc2fc7314cd2
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageAddNoise.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageAdjuster.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageAdjuster.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9659a0c1879ee52e552db7a8070def788376e7c1
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageAdjuster.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageAspectCropper.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageAspectCropper.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..449390efb8438e17f4deffc759d4d5363169c928
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageAspectCropper.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageBatch.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageBatch.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..143570e8c74775470bf692f3e59ca15e4ac6cd57
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageBatch.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageBatchListConverter.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageBatchListConverter.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ec9edc23cb3f7f50776dcabde443cc490a147f2e
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageBatchListConverter.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageBatchToGrid.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageBatchToGrid.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..05d1e8f5c34ad8e8b970cd08480f4ebe1117dced
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageBatchToGrid.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageNotes.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageNotes.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1a8eb4840a5ef818afa662264c8dc459dcf0f57d
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageNotes.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageOverlay.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageOverlay.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fbaa27baeb8f3d5236ef1a7504e46202db1aa193
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageOverlay.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImagePicker.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImagePicker.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e4fdfc7d9ccefa3f786a3a4f33075f06f2966e69
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImagePicker.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageReplace.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageReplace.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb56fb1d5af96b39ef494bc2894f1bbd05f35446
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageReplace.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageSelector.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageSelector.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..80ff0168f57ee63d9e4a55ae711bcf929faad83c
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageSelector.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageSlicer.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageSlicer.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4a99b6bc3469328a86cdd2a9e98aa1dda9289fb6
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageSlicer.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageToMask.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageToMask.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..33e7eb2e36381d1ad0b4acbf4309449edbc03639
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ImageToMask.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_Image_AddToBatch.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_Image_AddToBatch.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..681d55c4e61023d340b726cb92ea6195e1433dda
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_Image_AddToBatch.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_Image_Blank.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_Image_Blank.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cd5d71ecfd019377c8ee30a2c6da91ff462d0150
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_Image_Blank.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_Image_Crop.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_Image_Crop.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..db2cce3881512588876d645bef7dc52bbac27a98
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_Image_Crop.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_Image_Dimension_Display.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_Image_Dimension_Display.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..31cd471d99968d287efdb094f0077e6b48297b0f
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_Image_Dimension_Display.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_Image_Randomizer.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_Image_Randomizer.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..08ab6a46c9768f4318a02625dc10c1552d0b7370
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_Image_Randomizer.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_LoadImage.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_LoadImage.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0ce038ba3e3e0a8caa8d5428223453934ab8b75e
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_LoadImage.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_PaddingRemover.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_PaddingRemover.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9e1bb3353b19c844393bb3aaf03eec0cf8f47909
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_PaddingRemover.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_ReplaceColor.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ReplaceColor.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e8a573c403db5fb1c9ce8902c21301c1fcbb569b
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_ReplaceColor.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_SaveAndDisplayImage.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_SaveAndDisplayImage.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a417c4f2b772e575af651f0f881052991caf1c07
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_SaveAndDisplayImage.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_SaveImages.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_SaveImages.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..54ba6ae0dba92c99000da642ea85d23f96d61db4
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_SaveImages.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_SaveRGBAAnimatedWebP.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_SaveRGBAAnimatedWebP.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d5b572e04c709d5477f5d8248cbb865f45e0908
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_SaveRGBAAnimatedWebP.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_SaveWebM.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_SaveWebM.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7b28e4e43388f285ee01c0c46996504998594062
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_SaveWebM.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/FL_SaveWebpImages.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/FL_SaveWebpImages.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a3d7a1acfa235474e672b01e6d0f8e3547ca0466
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/FL_SaveWebpImages.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/image/__pycache__/__init__.cpython-310.pyc b/comfyui_fill-nodes/nodes/image/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0783f4db2bbb266b19bb7f0aeb807cb4d257b87e
Binary files /dev/null and b/comfyui_fill-nodes/nodes/image/__pycache__/__init__.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/kartel/FL_KartelJobInput.py b/comfyui_fill-nodes/nodes/kartel/FL_KartelJobInput.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a609bc3b685bfec97dd79a2906086f826b800c9
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/kartel/FL_KartelJobInput.py
@@ -0,0 +1,133 @@
+import io
+import json
+import re
+import numpy as np
+from PIL import Image
+import requests
+import torch
+
+
+# Standardized params_json schema:
+# {
+# "string_1": "", "string_2": "", "string_3": "", "string_4": "",
+# "int_1": 0, "int_2": 0, "int_3": 0, "int_4": 0,
+# "float_1": 0.0, "float_2": 0.0, "float_3": 0.0, "float_4": 0.0,
+# "bool_1": false, "bool_2": false, "bool_3": false, "bool_4": false,
+# "image_url_1": "", "image_url_2": "", "image_url_3": "", "image_url_4": ""
+# }
+
+
+class FL_KartelJobInput:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "job_id": ("STRING", {"default": ""}),
+ "user_id": ("STRING", {"default": ""}),
+ "user_email": ("STRING", {"default": ""}),
+ "app_name": ("STRING", {"default": ""}),
+ "callback_url": ("STRING", {"default": ""}),
+ "params_json": ("STRING", {"default": "{}", "multiline": True}),
+ }
+ }
+
+ RETURN_TYPES = (
+ "STRING", "STRING", "STRING", "STRING", "STRING", # job metadata
+ "STRING", "STRING", "STRING", "STRING", # string_1-4
+ "INT", "INT", "INT", "INT", # int_1-4
+ "FLOAT", "FLOAT", "FLOAT", "FLOAT", # float_1-4
+ "BOOLEAN", "BOOLEAN", "BOOLEAN", "BOOLEAN", # bool_1-4
+ "IMAGE", "IMAGE", "IMAGE", "IMAGE", # image_1-4
+ )
+ RETURN_NAMES = (
+ "job_id", "user_id", "user_email", "app_name", "callback_url",
+ "string_1", "string_2", "string_3", "string_4",
+ "int_1", "int_2", "int_3", "int_4",
+ "float_1", "float_2", "float_3", "float_4",
+ "bool_1", "bool_2", "bool_3", "bool_4",
+ "image_1", "image_2", "image_3", "image_4",
+ )
+ FUNCTION = "process"
+ CATEGORY = "🏵️Fill Nodes/Kartel"
+
+ def process(self, job_id, user_id, user_email, app_name, callback_url, params_json):
+ print(f"[FL_KartelJobInput] === INCOMING DATA ===")
+ print(f"[FL_KartelJobInput] job_id='{job_id}'")
+ print(f"[FL_KartelJobInput] user_id='{user_id}'")
+ print(f"[FL_KartelJobInput] user_email='{user_email}'")
+ print(f"[FL_KartelJobInput] app_name='{app_name}'")
+ print(f"[FL_KartelJobInput] callback_url='{callback_url}'")
+ print(f"[FL_KartelJobInput] params_json='{params_json}'")
+ print(f"[FL_KartelJobInput] === END INCOMING DATA ===")
+
+ # Parse JSON with trailing comma tolerance
+ try:
+ data = json.loads(params_json)
+ print(f"[FL_KartelJobInput] Parsed OK, keys: {list(data.keys())}")
+ print(f"[FL_KartelJobInput] Full parsed data: {data}")
+ except json.JSONDecodeError:
+ cleaned = re.sub(r',\s*([}\]])', r'\1', params_json)
+ try:
+ data = json.loads(cleaned)
+ print(f"[FL_KartelJobInput] Parsed after comma fix, keys: {list(data.keys())}")
+ print(f"[FL_KartelJobInput] Full parsed data: {data}")
+ except json.JSONDecodeError as e:
+ print(f"[FL_KartelJobInput] Invalid JSON: {e}")
+ data = {}
+
+ # 1x1 black pixel placeholder for missing images
+ empty_image = torch.zeros(1, 1, 1, 3)
+
+ def get_str(key):
+ val = data.get(key, "")
+ return str(val) if val else ""
+
+ def get_int(key):
+ val = data.get(key, 0)
+ try:
+ return int(val)
+ except (ValueError, TypeError):
+ return 0
+
+ def get_float(key):
+ val = data.get(key, 0.0)
+ try:
+ return float(val)
+ except (ValueError, TypeError):
+ return 0.0
+
+ def get_bool(key):
+ val = data.get(key, False)
+ if isinstance(val, bool):
+ return val
+ if isinstance(val, str):
+ return val.lower() in ("true", "1", "yes")
+ return bool(val)
+
+ def get_image(key):
+ url = data.get(key, "")
+ if not url:
+ return empty_image
+ try:
+ print(f"[FL_KartelJobInput] Downloading image '{key}': {url}")
+ response = requests.get(url, timeout=30)
+ response.raise_for_status()
+ pil_image = Image.open(io.BytesIO(response.content))
+ if pil_image.mode != "RGB":
+ pil_image = pil_image.convert("RGB")
+ img_np = np.array(pil_image).astype(np.float32) / 255.0
+ img_tensor = torch.from_numpy(img_np).unsqueeze(0)
+ print(f"[FL_KartelJobInput] Downloaded '{key}': {pil_image.width}x{pil_image.height}")
+ return img_tensor
+ except Exception as e:
+ print(f"[FL_KartelJobInput] Failed to download '{key}' ({url}): {e}")
+ return empty_image
+
+ return (
+ job_id, user_id, user_email, app_name, callback_url,
+ get_str("string_1"), get_str("string_2"), get_str("string_3"), get_str("string_4"),
+ get_int("int_1"), get_int("int_2"), get_int("int_3"), get_int("int_4"),
+ get_float("float_1"), get_float("float_2"), get_float("float_3"), get_float("float_4"),
+ get_bool("bool_1"), get_bool("bool_2"), get_bool("bool_3"), get_bool("bool_4"),
+ get_image("image_url_1"), get_image("image_url_2"), get_image("image_url_3"), get_image("image_url_4"),
+ )
diff --git a/comfyui_fill-nodes/nodes/kartel/FL_KartelJobOutput.py b/comfyui_fill-nodes/nodes/kartel/FL_KartelJobOutput.py
new file mode 100644
index 0000000000000000000000000000000000000000..5101b0c4b1261148566efc0a47d19c18c19a42c0
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/kartel/FL_KartelJobOutput.py
@@ -0,0 +1,108 @@
+import io
+import json
+import numpy as np
+from PIL import Image
+import requests
+
+
+class FL_KartelJobOutput:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "images": ("IMAGE",),
+ "job_id": ("STRING", {"default": ""}),
+ "callback_url": ("STRING", {"default": ""}),
+ },
+ "optional": {
+ "user_id": ("STRING", {"default": ""}),
+ "user_email": ("STRING", {"default": ""}),
+ "app_name": ("STRING", {"default": ""}),
+ }
+ }
+
+ RETURN_TYPES = ()
+ FUNCTION = "send_results"
+ CATEGORY = "🏵️Fill Nodes/Kartel"
+ OUTPUT_NODE = True
+
+ def send_results(self, images, job_id, callback_url,
+ user_id="", user_email="", app_name=""):
+ if images is None:
+ print("[FL_KartelJobOutput] No images received (None), skipping POST.")
+ return ()
+
+ print(f"[FL_KartelJobOutput] Received images with shape: {images.shape}")
+
+ if images.shape[1] <= 1 and images.shape[2] <= 1:
+ print("[FL_KartelJobOutput] Images are 1x1 placeholder, skipping POST.")
+ return ()
+
+ if not callback_url:
+ print("[FL_KartelJobOutput] No callback_url provided, skipping POST.")
+ return ()
+
+ # Convert each batch image to PNG bytes in-memory
+ png_buffers = []
+ for i in range(images.shape[0]):
+ img_np = 255.0 * images[i].cpu().numpy()
+ img_pil = Image.fromarray(np.clip(img_np, 0, 255).astype(np.uint8))
+ buf = io.BytesIO()
+ img_pil.save(buf, format="PNG")
+ buf.seek(0)
+ png_buffers.append((f"image_{i}.png", buf))
+
+ # Build metadata form field
+ metadata = {
+ "job_id": job_id,
+ "user_id": user_id,
+ "user_email": user_email,
+ "app_name": app_name,
+ "image_count": len(png_buffers),
+ "status": "completed",
+ }
+ data = {"metadata": json.dumps(metadata)}
+
+ # POST with 1 retry on connection error
+ max_attempts = 2
+ last_error = None
+
+ for attempt in range(max_attempts):
+ # Build multipart files list (rebuild each attempt since streams are consumed)
+ files = [("images", (fn, buf, "image/png")) for fn, buf in png_buffers]
+
+ try:
+ response = requests.post(
+ callback_url,
+ files=files,
+ data=data,
+ timeout=30,
+ )
+ response.raise_for_status()
+ print(
+ f"[FL_KartelJobOutput] Successfully posted {len(png_buffers)} image(s) "
+ f"for job {job_id} -> {response.status_code}"
+ )
+ return ()
+ except requests.ConnectionError as e:
+ last_error = e
+ print(
+ f"[FL_KartelJobOutput] Connection error on attempt "
+ f"{attempt + 1}/{max_attempts}: {e}"
+ )
+ # Reset buffer positions for retry
+ for _, buf in png_buffers:
+ buf.seek(0)
+ except requests.RequestException as e:
+ print(f"[FL_KartelJobOutput] POST failed for job {job_id}: {e}")
+ return ()
+
+ print(
+ f"[FL_KartelJobOutput] All {max_attempts} attempts failed "
+ f"for job {job_id}: {last_error}"
+ )
+ return ()
+
+ @classmethod
+ def IS_CHANGED(cls, *args, **kwargs):
+ return float("NaN")
diff --git a/comfyui_fill-nodes/nodes/kartel/FL_KartelParamsParser.py b/comfyui_fill-nodes/nodes/kartel/FL_KartelParamsParser.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5e3c5322a370c133e46d1b2d4870af6b2ffc16f
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/kartel/FL_KartelParamsParser.py
@@ -0,0 +1,130 @@
+import io
+import json
+import re
+import numpy as np
+from PIL import Image
+import requests
+import torch
+
+
+class FL_KartelParamsParser:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "params_json": ("STRING", {"default": "{}", "multiline": True}),
+ },
+ "optional": {
+ "string_key_1": ("STRING", {"default": ""}),
+ "string_key_2": ("STRING", {"default": ""}),
+ "string_key_3": ("STRING", {"default": ""}),
+ "string_key_4": ("STRING", {"default": ""}),
+ "int_key_1": ("STRING", {"default": ""}),
+ "int_key_2": ("STRING", {"default": ""}),
+ "float_key_1": ("STRING", {"default": ""}),
+ "float_key_2": ("STRING", {"default": ""}),
+ "bool_key_1": ("STRING", {"default": ""}),
+ "image_url_key_1": ("STRING", {"default": ""}),
+ "image_url_key_2": ("STRING", {"default": ""}),
+ "image_url_key_3": ("STRING", {"default": ""}),
+ }
+ }
+
+ RETURN_TYPES = ("STRING", "STRING", "STRING", "STRING", "INT", "INT", "FLOAT", "FLOAT", "BOOLEAN", "IMAGE", "IMAGE", "IMAGE")
+ RETURN_NAMES = ("string_1", "string_2", "string_3", "string_4", "int_1", "int_2", "float_1", "float_2", "bool_1", "image_1", "image_2", "image_3")
+ FUNCTION = "parse"
+ CATEGORY = "🏵️Fill Nodes/Kartel"
+
+ def parse(self, params_json, string_key_1="", string_key_2="", string_key_3="",
+ string_key_4="", int_key_1="", int_key_2="", float_key_1="",
+ float_key_2="", bool_key_1="", image_url_key_1="", image_url_key_2="",
+ image_url_key_3=""):
+ print(f"[FL_KartelParamsParser] Raw params_json ({len(params_json)} chars): {params_json[:500]}")
+ print(f"[FL_KartelParamsParser] image_url_key_1='{image_url_key_1}' image_url_key_2='{image_url_key_2}' image_url_key_3='{image_url_key_3}'")
+
+ try:
+ data = json.loads(params_json)
+ print(f"[FL_KartelParamsParser] Parsed JSON OK, keys: {list(data.keys())}")
+ except json.JSONDecodeError:
+ # Strip trailing commas before } and ] then retry
+ cleaned = re.sub(r',\s*([}\]])', r'\1', params_json)
+ try:
+ data = json.loads(cleaned)
+ print(f"[FL_KartelParamsParser] Parsed JSON after stripping trailing commas, keys: {list(data.keys())}")
+ except json.JSONDecodeError as e:
+ print(f"[FL_KartelParamsParser] Invalid JSON: {e}")
+ data = {}
+
+ def get_str(key):
+ if not key:
+ return ""
+ return str(data.get(key, ""))
+
+ def get_int(key):
+ if not key:
+ return 0
+ val = data.get(key, 0)
+ try:
+ return int(val)
+ except (ValueError, TypeError):
+ print(f"[FL_KartelParamsParser] Cannot convert '{key}' value '{val}' to INT, defaulting to 0")
+ return 0
+
+ def get_float(key):
+ if not key:
+ return 0.0
+ val = data.get(key, 0.0)
+ try:
+ return float(val)
+ except (ValueError, TypeError):
+ print(f"[FL_KartelParamsParser] Cannot convert '{key}' value '{val}' to FLOAT, defaulting to 0.0")
+ return 0.0
+
+ def get_bool(key):
+ if not key:
+ return False
+ val = data.get(key, False)
+ if isinstance(val, bool):
+ return val
+ if isinstance(val, str):
+ return val.lower() in ("true", "1", "yes")
+ return bool(val)
+
+ # 1x1 black pixel — valid IMAGE tensor placeholder when no image is available
+ empty_image = torch.zeros(1, 1, 1, 3)
+
+ def get_image(key):
+ if not key:
+ return empty_image
+ url = data.get(key, "")
+ if not url:
+ return empty_image
+ try:
+ print(f"[FL_KartelParamsParser] Downloading image from '{key}': {url}")
+ response = requests.get(url, timeout=30)
+ response.raise_for_status()
+ pil_image = Image.open(io.BytesIO(response.content))
+ if pil_image.mode != "RGB":
+ pil_image = pil_image.convert("RGB")
+ img_np = np.array(pil_image).astype(np.float32) / 255.0
+ img_tensor = torch.from_numpy(img_np).unsqueeze(0)
+ print(f"[FL_KartelParamsParser] Downloaded image '{key}': {pil_image.width}x{pil_image.height}")
+ return img_tensor
+ except Exception as e:
+ print(f"[FL_KartelParamsParser] Failed to download image for '{key}' ({url}): {e}")
+ return empty_image
+
+ return (
+ get_str(string_key_1),
+ get_str(string_key_2),
+ get_str(string_key_3),
+ get_str(string_key_4),
+ get_int(int_key_1),
+ get_int(int_key_2),
+ get_float(float_key_1),
+ get_float(float_key_2),
+ get_bool(bool_key_1),
+ get_image(image_url_key_1),
+ get_image(image_url_key_2),
+ get_image(image_url_key_3),
+ )
diff --git a/comfyui_fill-nodes/nodes/kartel/__init__.py b/comfyui_fill-nodes/nodes/kartel/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/comfyui_fill-nodes/nodes/kartel/__pycache__/FL_KartelJobInput.cpython-310.pyc b/comfyui_fill-nodes/nodes/kartel/__pycache__/FL_KartelJobInput.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a45761265e116bc59c006dbc66192ec1ea35fc82
Binary files /dev/null and b/comfyui_fill-nodes/nodes/kartel/__pycache__/FL_KartelJobInput.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/kartel/__pycache__/FL_KartelJobOutput.cpython-310.pyc b/comfyui_fill-nodes/nodes/kartel/__pycache__/FL_KartelJobOutput.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0bab06ef40a55cf7beedb51dcfb6497fc91c6810
Binary files /dev/null and b/comfyui_fill-nodes/nodes/kartel/__pycache__/FL_KartelJobOutput.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/kartel/__pycache__/__init__.cpython-310.pyc b/comfyui_fill-nodes/nodes/kartel/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f881f14ed8c0fdf09c7c30f71329cb6cb512cec3
Binary files /dev/null and b/comfyui_fill-nodes/nodes/kartel/__pycache__/__init__.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ksamplers/FL_KSamplerXYZPlot.py b/comfyui_fill-nodes/nodes/ksamplers/FL_KSamplerXYZPlot.py
new file mode 100644
index 0000000000000000000000000000000000000000..972e2d2a24ecf0e3d513b9db99ad92cd88c6edf4
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ksamplers/FL_KSamplerXYZPlot.py
@@ -0,0 +1,211 @@
+import torch
+from nodes import common_ksampler, VAEDecode, VAEEncode
+import comfy.samplers
+import comfy.utils
+import logging
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+from ..utils import tensor_to_pil, pil_to_tensor
+
+class FL_KSamplerXYZPlot:
+ # Positioning and style parameters
+ CELL_MARGIN = 70
+ AXIS_LABEL_MARGIN = 150
+ FONT_SIZE = 40
+ AXIS_LABEL_OFFSET_X = 70
+ AXIS_LABEL_OFFSET_Y = 70
+
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "model": ("MODEL",),
+ "positive": ("CONDITIONING",),
+ "negative": ("CONDITIONING",),
+ "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
+ "input_type": (["latent", "image"],),
+ "steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
+ "cfg": ("FLOAT", {"default": 7.0, "min": 0.0, "max": 100.0}),
+ "sampler_name": (comfy.samplers.KSampler.SAMPLERS,),
+ "scheduler": (comfy.samplers.KSampler.SCHEDULERS,),
+ "denoise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
+ "x_axis": (["steps", "cfg", "denoise", "sampler_name", "scheduler"],),
+ "x_values": ("STRING", {"default": "20,30,40"}),
+ "y_axis": (["steps", "cfg", "denoise", "sampler_name", "scheduler"],),
+ "y_values": ("STRING", {"default": "7,8,9"}),
+ "z_axis": (["none", "steps", "cfg", "denoise", "sampler_name", "scheduler"],),
+ "z_values": ("STRING", {"default": ""}),
+ "z_stack_mode": (["vertical", "horizontal"],),
+ },
+ "optional": {
+ "latent_image": ("LATENT",),
+ "vae": ("VAE",),
+ "image": ("IMAGE",),
+ }
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "sample_xyz_plot"
+ CATEGORY = "🏵️Fill Nodes/Ksamplers"
+
+ def parse_range(self, value_string, param_type):
+ if param_type in ["sampler_name", "scheduler"]:
+ return [x.strip() for x in value_string.split(',')]
+ return [float(x.strip()) for x in value_string.split(',')]
+
+ def generate_grid(self, x_values, y_values, z_values):
+ if z_values:
+ return [(x, y, z) for z in z_values for y in y_values for x in x_values]
+ return [(x, y, None) for y in y_values for x in x_values]
+
+ def create_image_grid(self, images, rows, cols, x_values, y_values, x_axis, y_axis):
+ if not images:
+ raise ValueError("No images provided to create grid")
+
+ cell_width, cell_height = images[0].size
+ grid_w = cols * (cell_width + self.CELL_MARGIN) + self.CELL_MARGIN + self.AXIS_LABEL_MARGIN
+ grid_h = rows * (cell_height + self.CELL_MARGIN) + self.CELL_MARGIN + self.AXIS_LABEL_MARGIN
+
+ grid = Image.new('RGB', size=(grid_w, grid_h), color='white')
+ draw = ImageDraw.Draw(grid)
+
+ try:
+ font = ImageFont.truetype("arial.ttf", self.FONT_SIZE)
+ except IOError:
+ font = ImageFont.load_default()
+
+ # Draw red axes
+ draw.line([(self.AXIS_LABEL_MARGIN, grid_h - self.AXIS_LABEL_MARGIN), (grid_w, grid_h - self.AXIS_LABEL_MARGIN)], fill='red', width=2) # X-axis
+ draw.line([(self.AXIS_LABEL_MARGIN, 0), (self.AXIS_LABEL_MARGIN, grid_h - self.AXIS_LABEL_MARGIN)], fill='red', width=2) # Y-axis
+
+ for i, img in enumerate(images):
+ col = i % cols
+ row = rows - 1 - (i // cols) # Flip the row order
+ x = col * (cell_width + self.CELL_MARGIN) + self.CELL_MARGIN + self.AXIS_LABEL_MARGIN
+ y = row * (cell_height + self.CELL_MARGIN) + self.CELL_MARGIN
+ grid.paste(img, (x, y))
+
+ # Add x-axis labels
+ for i, label in enumerate(x_values):
+ x = i * (cell_width + self.CELL_MARGIN) + self.CELL_MARGIN + self.AXIS_LABEL_MARGIN + cell_width // 2
+ y = grid_h - self.AXIS_LABEL_MARGIN + 5
+ draw.text((x, y), str(label), fill='black', font=font, anchor='mt')
+
+ # Add y-axis labels
+ for i, label in enumerate(y_values):
+ x = self.AXIS_LABEL_MARGIN - 5
+ y = (rows - 1 - i) * (cell_height + self.CELL_MARGIN) + self.CELL_MARGIN + cell_height // 2
+ draw.text((x, y), str(label), fill='black', font=font, anchor='rm')
+
+ # Add axis titles with adjustable positioning
+ draw.text((grid_w // 2, grid_h - self.AXIS_LABEL_OFFSET_Y), x_axis, fill='black', font=font, anchor='ms')
+ draw.text((self.AXIS_LABEL_OFFSET_X, grid_h // 2), y_axis, fill='black', font=font, anchor='ms', rotation=90)
+
+ return grid
+
+ def sample_xyz_plot(self, model, positive, negative, seed, steps, cfg, sampler_name, scheduler, denoise,
+ x_axis, x_values, y_axis, y_values, z_axis, z_values, input_type, z_stack_mode,
+ latent_image=None, image=None, vae=None):
+ try:
+ device = comfy.model_management.get_torch_device()
+
+ x_values = self.parse_range(x_values, x_axis)
+ y_values = self.parse_range(y_values, y_axis)
+ z_values = self.parse_range(z_values, z_axis) if z_axis != "none" else [None]
+
+ param_grid = self.generate_grid(x_values, y_values, z_values)
+
+ # Input selection and error handling
+ if input_type == "latent":
+ if latent_image is None:
+ raise ValueError("Latent input is selected, but no latent image is provided.")
+ input_list = []
+ for i in range(latent_image["samples"].shape[0]):
+ item = {}
+ for k, v in latent_image.items():
+ item[k] = v[i:i+1] if isinstance(v, torch.Tensor) else v
+ input_list.append(item)
+ elif input_type == "image":
+ if image is None:
+ raise ValueError("Image input is selected, but no image is provided.")
+ if vae is None:
+ raise ValueError("Image input is selected, but no VAE is provided for encoding.")
+ input_list = [image[i:i+1] for i in range(image.shape[0])]
+ else:
+ raise ValueError(f"Invalid input type: {input_type}")
+
+ final_grids = []
+
+ for idx, item in enumerate(input_list):
+ results = []
+ for x_val, y_val, z_val in param_grid:
+ current_params = {
+ "steps": steps,
+ "cfg": cfg,
+ "denoise": denoise,
+ "sampler_name": sampler_name,
+ "scheduler": scheduler
+ }
+ current_params[x_axis] = x_val
+ current_params[y_axis] = y_val
+ if z_axis != "none":
+ current_params[z_axis] = z_val
+
+ if input_type == "image":
+ latent = VAEEncode().encode(vae, item)[0]
+ else:
+ latent = item
+
+ samples = common_ksampler(model, seed + idx, int(current_params["steps"]), current_params["cfg"],
+ current_params["sampler_name"], current_params["scheduler"],
+ positive, negative, latent,
+ denoise=current_params["denoise"])[0]
+
+ if vae is not None:
+ vae_decoder = VAEDecode()
+ output_image = vae_decoder.decode(vae, samples)[0]
+ results.append(tensor_to_pil(output_image))
+
+ if z_axis != "none":
+ grids = []
+ for i, z_val in enumerate(z_values):
+ start = i * len(x_values) * len(y_values)
+ end = start + len(x_values) * len(y_values)
+ grid = self.create_image_grid(
+ results[start:end], len(y_values), len(x_values),
+ x_values, y_values, x_axis, y_axis
+ )
+ draw = ImageDraw.Draw(grid)
+ font = ImageFont.truetype("arial.ttf", self.FONT_SIZE) if self.FONT_SIZE else ImageFont.load_default()
+ draw.text((200, 10), f"{z_axis}: {z_val}", fill='black', font=font)
+ grids.append(grid)
+
+ if z_stack_mode == "vertical":
+ total_width = max(grid.width for grid in grids)
+ total_height = sum(grid.height for grid in grids)
+ final_grid = Image.new('RGB', (total_width, total_height), color='white')
+ y_offset = 0
+ for grid in grids:
+ final_grid.paste(grid, (0, y_offset))
+ y_offset += grid.height
+ else: # horizontal
+ total_width = sum(grid.width for grid in grids)
+ total_height = max(grid.height for grid in grids)
+ final_grid = Image.new('RGB', (total_width, total_height), color='white')
+ x_offset = 0
+ for grid in grids:
+ final_grid.paste(grid, (x_offset, 0))
+ x_offset += grid.width
+ else:
+ final_grid = self.create_image_grid(
+ results, len(y_values), len(x_values),
+ x_values, y_values, x_axis, y_axis
+ )
+
+ final_grids.append(pil_to_tensor(final_grid))
+
+ return (torch.cat(final_grids, dim=0),)
+
+ except Exception as e:
+ logging.error(f"Error in FL_KsamplerXYZPlot: {str(e)}")
+ raise
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/ksamplers/FL_KsamplerBasic.py b/comfyui_fill-nodes/nodes/ksamplers/FL_KsamplerBasic.py
new file mode 100644
index 0000000000000000000000000000000000000000..639f3f8c12a836ace89520b2fcd10b63c3849c25
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ksamplers/FL_KsamplerBasic.py
@@ -0,0 +1,56 @@
+import torch
+from nodes import common_ksampler, VAEDecode, VAEEncode
+import comfy.samplers
+import comfy.utils
+import logging
+
+class FL_KsamplerBasic:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "model": ("MODEL",),
+ "positive": ("CONDITIONING",),
+ "negative": ("CONDITIONING",),
+ "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
+ "steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
+ "cfg": ("FLOAT", {"default": 7.0, "min": 0.0, "max": 100.0}),
+ "sampler_name": (comfy.samplers.KSampler.SAMPLERS,),
+ "scheduler": (comfy.samplers.KSampler.SCHEDULERS,),
+ "denoise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
+ },
+ "optional": {
+ "latent_image": ("LATENT",),
+ "vae": ("VAE",),
+ "image": ("IMAGE",),
+ }
+ }
+
+ RETURN_TYPES = ("MODEL", "CONDITIONING", "CONDITIONING", "LATENT", "VAE", "IMAGE")
+ RETURN_NAMES = ("model", "positive", "negative", "latent", "vae", "image")
+ FUNCTION = "sample"
+ CATEGORY = "🏵️Fill Nodes/Ksamplers"
+
+ def sample(self, model, positive, negative, seed, steps, cfg, sampler_name, scheduler, denoise, latent_image=None, image=None, vae=None):
+ try:
+ device = comfy.model_management.get_torch_device()
+
+ # Handle input image if provided
+ if image is not None and vae is not None:
+ latent_image = VAEEncode().encode(vae, image)[0]
+ elif latent_image is None:
+ latent_image = {"samples": torch.zeros((1, 4, 64, 64), device=device)}
+
+ samples = common_ksampler(model, seed, steps, cfg, sampler_name, scheduler,
+ positive, negative, latent_image, denoise=denoise)[0]
+
+ output_image = None
+ if vae is not None:
+ vae_decoder = VAEDecode()
+ output_image = vae_decoder.decode(vae, samples)[0]
+
+ return (model, positive, negative, samples, vae, output_image)
+
+ except Exception as e:
+ logging.error(f"Error in FL_KsamplerBasic: {str(e)}")
+ raise
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/ksamplers/FL_KsamplerPlus.py b/comfyui_fill-nodes/nodes/ksamplers/FL_KsamplerPlus.py
new file mode 100644
index 0000000000000000000000000000000000000000..3871bf4a42e20f5b35ce4689e9bfed18aa39e45b
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ksamplers/FL_KsamplerPlus.py
@@ -0,0 +1,326 @@
+import copy
+import torch
+import math
+from nodes import common_ksampler, VAEDecode, VAEEncode
+import comfy.samplers
+import comfy.utils
+import logging
+import numpy as np
+from PIL import Image
+import torch.nn.functional as F
+import latent_preview
+
+
+class FL_KsamplerPlus:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "model": ("MODEL",),
+ "positive": ("CONDITIONING",),
+ "negative": ("CONDITIONING",),
+ "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
+ "steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
+ "cfg": ("FLOAT", {"default": 7.0, "min": 0.0, "max": 100.0}),
+ "sampler_name": (comfy.samplers.KSampler.SAMPLERS,),
+ "scheduler": (comfy.samplers.KSampler.SCHEDULERS,),
+ "denoise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
+ "input_type": (["latent", "image"],),
+ "x_slices": ("INT", {"default": 2, "min": 1, "max": 8}),
+ "y_slices": ("INT", {"default": 2, "min": 1, "max": 8}),
+ "overlap": ("FLOAT", {"default": 0.25, "min": 0.0, "max": 0.9, "step": 0.01}),
+ "batch_size": ("INT", {"default": 1, "min": 1, "max": 64}),
+ "use_sliced_conditioning": ("BOOLEAN", {"default": True}),
+ },
+ "optional": {
+ "latent_image": ("LATENT",),
+ "vae": ("VAE",),
+ "image": ("IMAGE",),
+ }
+ }
+
+ RETURN_TYPES = ("MODEL", "CONDITIONING", "CONDITIONING", "LATENT", "VAE", "IMAGE")
+ RETURN_NAMES = ("model", "positive", "negative", "latent", "vae", "image")
+ FUNCTION = "sample"
+ CATEGORY = "🏵️Fill Nodes/Ksamplers"
+
+ @staticmethod
+ def crop_tensor(tensor, region):
+ x1, y1, x2, y2 = region
+ return tensor[:, :, y1:y2, x1:x2]
+
+ @staticmethod
+ def resize_tensor(tensor, size, mode="nearest-exact"):
+ return F.interpolate(tensor, size=size, mode=mode)
+
+ @staticmethod
+ def resize_region(region, init_size, resize_size):
+ x1, y1, x2, y2 = region
+ init_width, init_height = init_size
+ resize_width, resize_height = resize_size
+ x1 = math.floor(x1 * resize_width / init_width)
+ x2 = math.ceil(x2 * resize_width / init_width)
+ y1 = math.floor(y1 * resize_height / init_height)
+ y2 = math.ceil(y2 * resize_height / init_height)
+ return (x1, y1, x2, y2)
+
+ @classmethod
+ def crop_controlnet(cls, cond_dict, region, init_size, canvas_size, tile_size):
+ if "control" not in cond_dict:
+ return
+ c = cond_dict["control"]
+ controlnet = c.copy()
+ cond_dict["control"] = controlnet
+ while c is not None:
+ hint = controlnet.cond_hint_original
+ resized_crop = cls.resize_region(region, canvas_size, hint.shape[2:])
+ # Ensure crop region has at least 1 pixel in each dimension
+ x1, y1, x2, y2 = resized_crop
+ x2 = max(x2, x1 + 1)
+ y2 = max(y2, y1 + 1)
+ resized_crop = (x1, y1, x2, y2)
+ hint = cls.crop_tensor(hint, resized_crop)
+ # Ensure tile_size has at least 1 pixel in each dimension
+ tile_w, tile_h = tile_size
+ safe_tile_size = (max(1, tile_w), max(1, tile_h))
+ hint = cls.resize_tensor(hint, safe_tile_size)
+ controlnet.cond_hint_original = hint
+ c = c.previous_controlnet
+ controlnet.set_previous_controlnet(c.copy() if c is not None else None)
+ controlnet = controlnet.previous_controlnet
+
+ @classmethod
+ def crop_cond(cls, cond, region, init_size, canvas_size, tile_size):
+ cropped = []
+ for emb, x in cond:
+ cond_dict = x.copy()
+ cls.crop_controlnet(cond_dict, region, init_size, canvas_size, tile_size)
+ cropped.append([emb, cond_dict])
+ return cropped
+
+ @staticmethod
+ def adjust_conditioning_strength(cond, strength_factor):
+ return [(emb * strength_factor, x) for emb, x in cond]
+
+ @staticmethod
+ def adjust_cond_for_tile(cond, y_start, x_start, tile_h, tile_w, vae_scale_factors):
+ """Adjust keyframe_idxs and guide_attention_entries for a spatial tile."""
+ _, sf_h, sf_w = vae_scale_factors
+ adjusted = []
+ for emb, x in cond:
+ cond_dict = copy.deepcopy(x)
+
+ if "keyframe_idxs" in cond_dict:
+ kf = cond_dict["keyframe_idxs"].clone()
+ # keyframe_idxs shape: [B, 3(t,h,w), num_tokens, 2(start,end)]
+ # Offset h,w pixel coords to tile-local space
+ kf[:, 1, :, :] -= y_start * sf_h
+ kf[:, 2, :, :] -= x_start * sf_w
+ cond_dict["keyframe_idxs"] = kf
+
+ if "guide_attention_entries" in cond_dict:
+ entries = copy.deepcopy(cond_dict["guide_attention_entries"])
+ for entry in entries:
+ ls = entry["latent_shape"] # [F, H, W]
+ entry["latent_shape"] = [ls[0], tile_h, tile_w]
+ entry["pre_filter_count"] = ls[0] * tile_h * tile_w
+ cond_dict["guide_attention_entries"] = entries
+
+ adjusted.append([emb, cond_dict])
+ return adjusted
+
+ @staticmethod
+ def create_blend_mask(height, width, overlap_h, overlap_w, is_top, is_left, is_bottom, is_right, device):
+ mask = torch.ones((height, width), device=device)
+
+ if overlap_h > 0:
+ x = torch.linspace(0, math.pi, overlap_h, device=device)
+ cos = 0.5 * (1 - torch.cos(x))
+ if not is_top:
+ mask[:overlap_h, :] *= cos[:, None]
+ if not is_bottom:
+ mask[-overlap_h:, :] *= cos.flip(0)[:, None]
+ if overlap_w > 0:
+ x = torch.linspace(0, math.pi, overlap_w, device=device)
+ cos = 0.5 * (1 - torch.cos(x))
+ if not is_left:
+ mask[:, :overlap_w] *= cos[None, :]
+ if not is_right:
+ mask[:, -overlap_w:] *= cos.flip(0)[None, :]
+
+ return mask
+
+ def sample(self, model, positive, negative, seed, steps, cfg, sampler_name, scheduler, denoise, input_type,
+ x_slices, y_slices, overlap, batch_size, use_sliced_conditioning, latent_image=None, image=None,
+ vae=None):
+ try:
+ device = comfy.model_management.get_torch_device()
+
+ if input_type == "image" and image is not None and vae is not None:
+ latent_image = VAEEncode().encode(vae, image)[0]
+ elif input_type == "latent" and latent_image is None:
+ raise ValueError("Latent image is required when input type is set to latent")
+ elif input_type == "image" and (image is None or vae is None):
+ raise ValueError("Both image and VAE are required when input type is set to image")
+
+ # Force batch size to 1 when sliced conditioning is used
+ if use_sliced_conditioning:
+ batch_size = 1
+
+ # Handle variable tensor dimensions (4D or 5D)
+ latent_shape = latent_image["samples"].shape
+ is_video = len(latent_shape) == 5
+
+ if is_video:
+ # 5D tensor: [batch, channels, frames, height, width]
+ b, c, f, h, w = latent_shape
+ logging.info(f"Processing 5D latent tensor with shape: {latent_shape}")
+ elif len(latent_shape) == 4:
+ # 4D tensor: [batch, channels, height, width]
+ b, c, h, w = latent_shape
+ else:
+ raise ValueError(f"Unexpected latent tensor shape: {latent_shape}. Expected 4D or 5D tensor.")
+
+ # Extract noise_mask for 5D video latents (used by LTX2 guide frames)
+ noise_mask = latent_image.get("noise_mask", None)
+
+ # Get VAE scale factors for adjusting keyframe_idxs coordinates per tile
+ vae_scale_factors = None
+ if is_video:
+ try:
+ vae_scale_factors = model.get_model_object("diffusion_model.vae_scale_factors")
+ except Exception:
+ vae_scale_factors = (8, 32, 32) # LTX default
+
+ base_slice_height = h // y_slices
+ base_slice_width = w // x_slices
+ overlap_height = int(base_slice_height * overlap)
+ overlap_width = int(base_slice_width * overlap)
+
+ samples = None # We'll initialize this later when we know the correct number of channels
+
+ def process_slice(y, x):
+ y_start = max(0, y * base_slice_height - overlap_height)
+ y_end = min(h, (y + 1) * base_slice_height + overlap_height)
+ x_start = max(0, x * base_slice_width - overlap_width)
+ x_end = min(w, (x + 1) * base_slice_width + overlap_width)
+
+ # Handle both 4D and 5D tensor slicing
+ if is_video:
+ section = latent_image["samples"][:, :, :, y_start:y_end, x_start:x_end].to(device=device)
+ else:
+ section = latent_image["samples"][:, :, y_start:y_end, x_start:x_end].to(device=device)
+
+ # Slice noise_mask for 5D video latents (preserves guide frame info)
+ sliced_noise_mask = None
+ if noise_mask is not None and is_video:
+ if noise_mask.shape[-1] > 1 and noise_mask.shape[-2] > 1:
+ # Spatially varying mask — slice to match tile
+ sliced_noise_mask = noise_mask[:, :, :, y_start:y_end, x_start:x_end]
+ else:
+ # Spatially uniform (e.g., [B,1,T,1,1]) — pass as-is
+ sliced_noise_mask = noise_mask
+
+ if use_sliced_conditioning:
+ region = (x_start * 8, y_start * 8, x_end * 8, y_end * 8)
+ init_size = (w * 8, h * 8)
+ canvas_size = init_size
+ tile_size = ((x_end - x_start) * 8, (y_end - y_start) * 8)
+ strength_factor = 1.2 # Adjust this value to increase or decrease conditioning strength
+ cropped_positive = self.adjust_conditioning_strength(
+ self.crop_cond(positive, region, init_size, canvas_size, tile_size), strength_factor)
+ cropped_negative = self.adjust_conditioning_strength(
+ self.crop_cond(negative, region, init_size, canvas_size, tile_size), strength_factor)
+ else:
+ cropped_positive = positive
+ cropped_negative = negative
+
+ return section, y_start, y_end, x_start, x_end, cropped_positive, cropped_negative, sliced_noise_mask
+
+ total_slices = x_slices * y_slices
+ all_slices = [(y, x) for y in range(y_slices) for x in range(x_slices)]
+
+ for i in range(0, total_slices, batch_size):
+ batch_slices = all_slices[i:min(i + batch_size, total_slices)]
+ batch_sections = [process_slice(y, x) for y, x in batch_slices]
+
+ batch_latents = torch.cat([section for section, _, _, _, _, _, _, _ in batch_sections], dim=0)
+
+ if use_sliced_conditioning:
+ batch_positive = batch_sections[0][5]
+ batch_negative = batch_sections[0][6]
+ else:
+ batch_positive = positive * len(batch_sections)
+ batch_negative = negative * len(batch_sections)
+
+ # For 5D video latents, adjust conditioning for tile position
+ if is_video and vae_scale_factors is not None:
+ _, y_start, y_end, x_start, x_end, _, _, _ = batch_sections[0]
+ tile_h = y_end - y_start
+ tile_w = x_end - x_start
+ batch_positive = self.adjust_cond_for_tile(
+ batch_positive, y_start, x_start, tile_h, tile_w, vae_scale_factors)
+ batch_negative = self.adjust_cond_for_tile(
+ batch_negative, y_start, x_start, tile_h, tile_w, vae_scale_factors)
+
+ # Build proper latent dict preserving noise_mask
+ tile_latent = {"samples": batch_latents}
+ sliced_noise_mask = batch_sections[0][7]
+ if sliced_noise_mask is not None:
+ tile_latent["noise_mask"] = sliced_noise_mask
+
+ processed_batch = common_ksampler(model, seed + i, steps, cfg, sampler_name, scheduler,
+ batch_positive, batch_negative,
+ tile_latent, denoise=denoise)[0]
+
+ processed_sections = torch.split(processed_batch["samples"], b, dim=0)
+
+ # Initialize samples tensor if it hasn't been initialized yet
+ if samples is None:
+ if is_video:
+ samples = torch.zeros_like(latent_image["samples"], device=device)
+ else:
+ processed_channels = processed_sections[0].shape[1]
+ samples = torch.zeros((b, processed_channels, h, w), device=device)
+
+ for (_, y_start, y_end, x_start, x_end, _, _, _), processed_section in zip(batch_sections,
+ processed_sections):
+ is_top = y_start == 0
+ is_left = x_start == 0
+ is_bottom = y_end == h
+ is_right = x_end == w
+ blend_mask = self.create_blend_mask(y_end - y_start, x_end - x_start,
+ overlap_height, overlap_width,
+ is_top, is_left, is_bottom, is_right,
+ device)
+
+ blend_mask = blend_mask.unsqueeze(0).unsqueeze(0).expand_as(processed_section)
+
+ processed_section = processed_section.to(device=device)
+ blend_mask = blend_mask.to(device=device)
+
+ # Handle both 4D and 5D tensor blending
+ if is_video:
+ samples[:, :, :, y_start:y_end, x_start:x_end] = (
+ samples[:, :, :, y_start:y_end, x_start:x_end] * (1 - blend_mask) +
+ processed_section * blend_mask
+ )
+ else:
+ samples[:, :, y_start:y_end, x_start:x_end] = (
+ samples[:, :, y_start:y_end, x_start:x_end] * (1 - blend_mask) +
+ processed_section * blend_mask
+ )
+
+ if device.type == 'cuda':
+ torch.cuda.empty_cache()
+
+ output_image = None
+ if vae is not None:
+ vae_decoder = VAEDecode()
+ output_image = vae_decoder.decode(vae, {"samples": samples})[0]
+
+ return (model, positive, negative, {"samples": samples}, vae, output_image)
+
+ except Exception as e:
+ logging.error(f"Error in FL_KsamplerPlus: {str(e)}")
+ raise
diff --git a/comfyui_fill-nodes/nodes/ksamplers/FL_KsamplerPlusV2.py b/comfyui_fill-nodes/nodes/ksamplers/FL_KsamplerPlusV2.py
new file mode 100644
index 0000000000000000000000000000000000000000..aee06ee4aa5a41ce03e8a5414cd0dbd39777f994
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ksamplers/FL_KsamplerPlusV2.py
@@ -0,0 +1,327 @@
+import torch
+import math
+from nodes import common_ksampler, VAEDecode, VAEEncode
+import comfy.samplers
+import comfy.utils
+import logging
+import numpy as np
+from PIL import Image
+import torch.nn.functional as F
+import latent_preview
+
+
+class FL_KsamplerPlusV2:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {
+ "required": {
+ "model": ("MODEL",),
+ "positive": ("CONDITIONING",),
+ "negative": ("CONDITIONING",),
+ "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
+ "steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
+ "cfg": ("FLOAT", {"default": 7.0, "min": 0.0, "max": 100.0}),
+ "sampler_name": (comfy.samplers.KSampler.SAMPLERS,),
+ "scheduler": (comfy.samplers.KSampler.SCHEDULERS,),
+ "denoise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
+ "input_type": (["latent", "image"],),
+ "x_slices": ("INT", {"default": 2, "min": 1, "max": 8}),
+ "y_slices": ("INT", {"default": 2, "min": 1, "max": 8}),
+ "overlap": ("FLOAT", {"default": 0.25, "min": 0.0, "max": 0.9, "step": 0.01}),
+ "batch_size": ("INT", {"default": 1, "min": 1, "max": 64}),
+ "use_sliced_conditioning": ("BOOLEAN", {"default": True}),
+ "conditioning_strength": ("FLOAT", {"default": 1.2, "min": 0.1, "max": 5.0, "step": 0.1}),
+ "debug_mode": ("BOOLEAN", {"default": False}),
+ },
+ "optional": {
+ "latent_image": ("LATENT",),
+ "vae": ("VAE",),
+ "image": ("IMAGE",),
+ }
+ }
+
+ RETURN_TYPES = ("MODEL", "CONDITIONING", "CONDITIONING", "LATENT", "VAE", "IMAGE", "STRING")
+ RETURN_NAMES = ("model", "positive", "negative", "latent", "vae", "image", "debug_info")
+ FUNCTION = "sample"
+ CATEGORY = "🏵️Fill Nodes/Ksamplers"
+
+ @staticmethod
+ def crop_tensor(tensor, region):
+ x1, y1, x2, y2 = region
+ return tensor[:, :, y1:y2, x1:x2]
+
+ @staticmethod
+ def resize_tensor(tensor, size, mode="nearest-exact"):
+ return F.interpolate(tensor, size=size, mode=mode)
+
+ @staticmethod
+ def resize_region(region, init_size, resize_size):
+ x1, y1, x2, y2 = region
+ init_width, init_height = init_size
+ resize_width, resize_height = resize_size
+ x1 = math.floor(x1 * resize_width / init_width)
+ x2 = math.ceil(x2 * resize_width / init_width)
+ y1 = math.floor(y1 * resize_height / init_height)
+ y2 = math.ceil(y2 * resize_height / init_height)
+ return (x1, y1, x2, y2)
+
+ @classmethod
+ def crop_controlnet(cls, cond_dict, region, init_size, canvas_size, tile_size):
+ """Crop ControlNet conditioning to match a specific region"""
+ if "control" not in cond_dict:
+ return
+ c = cond_dict["control"]
+ controlnet = c.copy()
+ cond_dict["control"] = controlnet
+ while c is not None:
+ hint = controlnet.cond_hint_original
+ resized_crop = cls.resize_region(region, canvas_size, hint.shape[2:])
+ hint = cls.crop_tensor(hint, resized_crop)
+ hint = cls.resize_tensor(hint, tile_size)
+ controlnet.cond_hint_original = hint
+ c = c.previous_controlnet
+ controlnet.set_previous_controlnet(c.copy() if c is not None else None)
+ controlnet = controlnet.previous_controlnet
+
+ @classmethod
+ def split_tensor_spatially(cls, tensor, region, init_size):
+ """Split a tensor spatially based on the region"""
+ # This is a simplified approach - in reality, we would need to know
+ # how the tensor corresponds to spatial dimensions
+
+ # Calculate the relative position of this region within the full image
+ x1, y1, x2, y2 = region
+ full_w, full_h = init_size
+
+ # Calculate normalized coordinates (0-1) for this region
+ region_center_x = (x1 + x2) / (2 * full_w)
+ region_center_y = (y1 + y2) / (2 * full_h)
+ region_width = (x2 - x1) / full_w
+ region_height = (y2 - y1) / full_h
+
+ # For tensors that don't have obvious spatial dimensions,
+ # we'll use a simple approach: scale the tensor based on the region size
+ # This assumes the tensor somehow encodes the full image
+ region_scale = (region_width * region_height) / (full_w * full_h)
+
+ # Scale the tensor - this is a very simplified approach
+ # In a real implementation, we would need to know how the tensor
+ # corresponds to spatial dimensions
+ return tensor * region_scale
+
+ @classmethod
+ def crop_cond(cls, cond, region, init_size, canvas_size, tile_size, split_all_conditioning=True):
+ """Enhanced conditioning cropping that completely splits all conditioning between slices"""
+ cropped = []
+ for emb, x in cond:
+ # Create a deep copy of the conditioning dictionary
+ cond_dict = x.copy()
+
+ # Handle ControlNet conditioning
+ cls.crop_controlnet(cond_dict, region, init_size, canvas_size, tile_size)
+
+ if split_all_conditioning:
+ # Split all tensor-based conditioning between slices
+ for key, value in cond_dict.items():
+ if isinstance(value, torch.Tensor):
+ # Split the tensor spatially
+ cond_dict[key] = cls.split_tensor_spatially(value, region, init_size)
+
+ # Add region information to the conditioning
+ cond_dict["region_info"] = {
+ "region": region,
+ "init_size": init_size,
+ "canvas_size": canvas_size,
+ "tile_size": tile_size
+ }
+
+ cropped.append([emb, cond_dict])
+ return cropped
+
+ @staticmethod
+ def adjust_conditioning_strength(cond, strength_factor):
+ """Apply a strength factor to conditioning embeddings while preserving other data"""
+ adjusted = []
+ for emb, x in cond:
+ # Adjust the embedding tensor by the strength factor
+ adjusted_emb = emb * strength_factor
+
+ # Create a copy of the conditioning dictionary to avoid modifying the original
+ adjusted_dict = x.copy()
+
+ # If there's a guidance value, we might want to adjust it as well
+ if "guidance" in adjusted_dict:
+ # Optionally adjust guidance - commented out for now as it might not be necessary
+ # adjusted_dict["guidance"] = adjusted_dict["guidance"] * strength_factor
+ pass
+
+ adjusted.append([adjusted_emb, adjusted_dict])
+ return adjusted
+
+ @staticmethod
+ def create_blend_mask(height, width, overlap_h, overlap_w, is_top, is_left, is_bottom, is_right, device):
+ mask = torch.ones((height, width), device=device)
+
+ if overlap_h > 0:
+ x = torch.linspace(0, math.pi, overlap_h, device=device)
+ cos = 0.5 * (1 - torch.cos(x))
+ if not is_top:
+ mask[:overlap_h, :] *= cos[:, None]
+ if not is_bottom:
+ mask[-overlap_h:, :] *= cos.flip(0)[:, None]
+ if overlap_w > 0:
+ x = torch.linspace(0, math.pi, overlap_w, device=device)
+ cos = 0.5 * (1 - torch.cos(x))
+ if not is_left:
+ mask[:, :overlap_w] *= cos[None, :]
+ if not is_right:
+ mask[:, -overlap_w:] *= cos.flip(0)[None, :]
+
+ return mask
+
+ def sample(self, model, positive, negative, seed, steps, cfg, sampler_name, scheduler, denoise, input_type,
+ x_slices, y_slices, overlap, batch_size, use_sliced_conditioning, conditioning_strength,
+ debug_mode, latent_image=None, image=None, vae=None):
+ try:
+ device = comfy.model_management.get_torch_device()
+
+ if input_type == "image" and image is not None and vae is not None:
+ latent_image = VAEEncode().encode(vae, image)[0]
+ elif input_type == "latent" and latent_image is None:
+ raise ValueError("Latent image is required when input type is set to latent")
+ elif input_type == "image" and (image is None or vae is None):
+ raise ValueError("Both image and VAE are required when input type is set to image")
+
+ # We no longer force batch_size to 1 for sliced conditioning
+ # This allows for more efficient processing
+
+ b, c, h, w = latent_image["samples"].shape
+ base_slice_height = h // y_slices
+ base_slice_width = w // x_slices
+ overlap_height = int(base_slice_height * overlap)
+ overlap_width = int(base_slice_width * overlap)
+
+ samples = None # We'll initialize this later when we know the correct number of channels
+
+ # We're splitting all conditioning between slices
+
+ def process_slice(y, x):
+ y_start = max(0, y * base_slice_height - overlap_height)
+ y_end = min(h, (y + 1) * base_slice_height + overlap_height)
+ x_start = max(0, x * base_slice_width - overlap_width)
+ x_end = min(w, (x + 1) * base_slice_width + overlap_width)
+
+ section = latent_image["samples"][:, :, y_start:y_end, x_start:x_end].to(device=device)
+
+ if use_sliced_conditioning:
+ region = (x_start * 8, y_start * 8, x_end * 8, y_end * 8)
+ init_size = (w * 8, h * 8)
+ canvas_size = init_size
+ tile_size = ((x_end - x_start) * 8, (y_end - y_start) * 8)
+ strength_factor = conditioning_strength # User-configurable strength factor
+ cropped_positive = self.adjust_conditioning_strength(
+ self.crop_cond(positive, region, init_size, canvas_size, tile_size, split_all_conditioning=True),
+ strength_factor)
+ cropped_negative = self.adjust_conditioning_strength(
+ self.crop_cond(negative, region, init_size, canvas_size, tile_size, split_all_conditioning=True),
+ strength_factor)
+ else:
+ cropped_positive = positive
+ cropped_negative = negative
+
+ return section, y_start, y_end, x_start, x_end, cropped_positive, cropped_negative
+
+ total_slices = x_slices * y_slices
+ all_slices = [(y, x) for y in range(y_slices) for x in range(x_slices)]
+
+ for i in range(0, total_slices, batch_size):
+ batch_slices = all_slices[i:min(i + batch_size, total_slices)]
+ batch_sections = [process_slice(y, x) for y, x in batch_slices]
+
+ batch_latents = torch.cat([section for section, _, _, _, _, _, _ in batch_sections], dim=0)
+
+ if use_sliced_conditioning:
+ # Handle multiple slices in a batch with sliced conditioning
+ batch_positives = [section[5] for section in batch_sections]
+ batch_negatives = [section[6] for section in batch_sections]
+
+ # Combine the conditionings for batch processing
+ batch_positive = []
+ for pos_cond in batch_positives:
+ batch_positive.extend(pos_cond)
+
+ batch_negative = []
+ for neg_cond in batch_negatives:
+ batch_negative.extend(neg_cond)
+ else:
+ batch_positive = positive * len(batch_sections)
+ batch_negative = negative * len(batch_sections)
+
+ processed_batch = common_ksampler(model, seed + i, steps, cfg, sampler_name, scheduler,
+ batch_positive, batch_negative,
+ {"samples": batch_latents}, denoise=denoise)[0]
+
+ processed_sections = torch.split(processed_batch["samples"], b, dim=0)
+
+ # Initialize samples tensor if it hasn't been initialized yet
+ if samples is None:
+ processed_channels = processed_sections[0].shape[1]
+ samples = torch.zeros((b, processed_channels, h, w), device=device)
+
+ for (_, y_start, y_end, x_start, x_end, _, _), processed_section in zip(batch_sections,
+ processed_sections):
+ is_top = y_start == 0
+ is_left = x_start == 0
+ is_bottom = y_end == h
+ is_right = x_end == w
+ blend_mask = self.create_blend_mask(y_end - y_start, x_end - x_start,
+ overlap_height, overlap_width,
+ is_top, is_left, is_bottom, is_right,
+ device)
+
+ blend_mask = blend_mask.unsqueeze(0).unsqueeze(0).expand_as(processed_section)
+
+ processed_section = processed_section.to(device=device)
+ blend_mask = blend_mask.to(device=device)
+
+ samples[:, :, y_start:y_end, x_start:x_end] = (
+ samples[:, :, y_start:y_end, x_start:x_end] * (1 - blend_mask) +
+ processed_section * blend_mask
+ )
+
+ if device.type == 'cuda':
+ torch.cuda.empty_cache()
+
+ output_image = None
+ if vae is not None:
+ vae_decoder = VAEDecode()
+ output_image = vae_decoder.decode(vae, {"samples": samples})[0]
+
+ # Prepare debug info if debug mode is enabled
+ debug_info = ""
+ if debug_mode:
+ debug_info = "KSamplerPlus V2 Debug Info:\n"
+ debug_info += f"- Input shape: {latent_image['samples'].shape}\n"
+ debug_info += f"- Slices: {x_slices}x{y_slices} with {overlap*100:.1f}% overlap\n"
+ debug_info += f"- Conditioning strength: {conditioning_strength}\n"
+ debug_info += f"- Batch size: {batch_size}\n"
+ debug_info += f"- Splitting all conditioning: {True}\n"
+
+ # Add info about the conditioning
+ if len(positive) > 0:
+ emb, cond_dict = positive[0]
+ debug_info += f"- Positive conditioning shape: {emb.shape}\n"
+ debug_info += "- Conditioning keys: " + ", ".join(cond_dict.keys()) + "\n"
+
+ if "pooled_output" in cond_dict:
+ debug_info += f"- Pooled output shape: {cond_dict['pooled_output'].shape}\n"
+ debug_info += "- Splitting pooled output between slices\n"
+
+ if "control" in cond_dict:
+ debug_info += "- ControlNet detected and processed\n"
+
+ return (model, positive, negative, {"samples": samples}, vae, output_image, debug_info)
+
+ except Exception as e:
+ logging.error(f"Error in FL_KsamplerPlusV2: {str(e)}")
+ raise
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/ksamplers/FL_KsamplerSettings.py b/comfyui_fill-nodes/nodes/ksamplers/FL_KsamplerSettings.py
new file mode 100644
index 0000000000000000000000000000000000000000..019a8248bf37647f9ee852ab6d371b53f15868f5
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ksamplers/FL_KsamplerSettings.py
@@ -0,0 +1,131 @@
+import comfy.samplers
+
+
+class FL_KsamplerSettings:
+
+ RATIO = [
+ ("1:1___SD 512x512", 512, 512),
+ ("4:3___SD 682x512", 682, 512),
+ ("3:2___SD 768x512", 768, 512),
+ ("16:9__SD 910x512", 910, 512),
+ ("1:85:1 SD 952x512", 952, 512),
+ ("2:1___SD 1024x512", 1024, 512),
+ ("1:1_SV3D 576x576", 576, 576),
+ ("16:9_SVD 576x1024", 1024, 576),
+ ("1:1__SD2 768x768", 768, 768),
+ ("1:1___XL 1024x1024", 1024, 1024),
+ ("16:15_XL 1024x960", 1024, 960),
+ ("17:15_XL 1088x960", 1088, 960),
+ ("17:14_XL 1088x896", 1088, 896),
+ ("4:3___XL 1152x896", 1152, 896),
+ ("18:13_XL 1152x832", 1152, 832),
+ ("3:2___XL 1216x832", 1216, 832),
+ ("5:3___XL 1280x768", 1280, 768),
+ ("7:4___XL 1344x768", 1344, 768),
+ ("21:11_XL 1344x704", 1344, 704),
+ ("2:1___XL 1408x704", 1408, 704),
+ ("23:11_XL 1472x704", 1472, 704),
+ ("21:9__XL 1536x640", 1536, 640),
+ ("5:2___XL 1600x640", 1600, 640),
+ ("26:9__XL 1664x576", 1664, 576),
+ ("3:1___XL 1728x576", 1728, 576),
+ ("28:9__XL 1792x576", 1792, 576),
+ ("29:8__XL 1856x512", 1856, 512),
+ ("15:4__XL 1920x512", 1920, 512),
+ ("31:8__XL 1984x512", 1984, 512),
+ ("4:1___XL 2048x512", 2048, 512),
+ ]
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ aspect_ratio_titles = [title for title, res1, res2 in cls.RATIO]
+ rotation = ("landscape", "portrait")
+
+ return {
+ "required": {
+ "Aspect_Ratio": (aspect_ratio_titles,
+ {"default": ("1:1___XL 1024x1024")}),
+ "rotation": (rotation,),
+ },
+ "optional": {
+ "batch": ("INT", {
+ "default": 1,
+ "min": 1,
+ "max": 10000,
+ }),
+ "Pass_1_steps": ("INT", {
+ "default": 25,
+ "min": 1,
+ "max": 10000,
+ }),
+ "Pass_2_steps": ("INT", {
+ "default": 25,
+ "min": 1,
+ "max": 10000,
+ }),
+ "Pass_1_CFG": ("FLOAT", {
+ "default": 6.0,
+ "min": -10.0,
+ "max": 100.0,
+ "step": 0.1,
+ "round": 0.1,
+ }),
+ "Pass_2_CFG": ("FLOAT", {
+ "default": 6.0,
+ "min": -10.0,
+ "max": 100.0,
+ "step": 0.1,
+ "round": 0.1,
+ }),
+ "Pass_2_denoise": ("FLOAT", {
+ "default": 0.500,
+ "min": -10.000,
+ "max": 100.000,
+ "step": 0.001,
+ "round": 0.01,
+ }),
+ "scale_factor": ("FLOAT", {
+ "default": 1.5,
+ "min": 1.0,
+ "max": 10.0,
+ "step": 0.1,
+ "round": 0.1,
+ }),
+ "sampler": (comfy.samplers.KSampler.SAMPLERS,),
+ "scheduler": (comfy.samplers.KSampler.SCHEDULERS,)
+ }
+ }
+
+ RETURN_TYPES = (
+ "INT", "INT", "INT", "INT", "INT", "FLOAT",
+ "FLOAT", "FLOAT", "FLOAT", comfy.samplers.KSampler.SAMPLERS,
+ comfy.samplers.KSampler.SCHEDULERS,)
+
+ RETURN_NAMES = (
+ "WIDTH",
+ "HEIGHT",
+ "BATCH_SIZE",
+ "Pass_1_steps",
+ "Pass_2_steps",
+ "Pass_1_CFG",
+ "Pass_2_CFG",
+ "Pass_2_denoise",
+ "SCALE",
+ "SAMPLER",
+ "SCHEDULER",
+ )
+ FUNCTION = "settings"
+ CATEGORY = "🏵️Fill Nodes/Ksamplers"
+
+ def settings(self, Aspect_Ratio, rotation, batch, Pass_1_steps, Pass_2_steps, Pass_1_CFG, Pass_2_CFG,
+ Pass_2_denoise, scale_factor, sampler, scheduler):
+ for title, width, height in self.RATIO:
+ if title == Aspect_Ratio:
+ if rotation == "portrait":
+ width, height = height, width # Swap for portrait orientation
+ return (
+ width, height, batch, Pass_1_steps, Pass_2_steps, Pass_1_CFG, Pass_2_CFG, Pass_2_denoise, scale_factor,
+ sampler, scheduler)
+ return (
+ None, None, batch, Pass_1_steps, Pass_2_steps, Pass_1_CFG, Pass_2_CFG, Pass_2_denoise, scale_factor, sampler,
+ scheduler) # In case the Aspect Ratio is not found
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/ksamplers/FL_KsamplerSigma.py b/comfyui_fill-nodes/nodes/ksamplers/FL_KsamplerSigma.py
new file mode 100644
index 0000000000000000000000000000000000000000..444a621fd51587c04b6d7bf94f3bf4773eac8359
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/ksamplers/FL_KsamplerSigma.py
@@ -0,0 +1,238 @@
+import json
+import logging
+import torch
+from aiohttp import web
+
+import comfy.sample
+import comfy.samplers
+import comfy.utils
+import comfy.model_management
+import latent_preview
+from nodes import VAEDecode, VAEEncode
+from server import PromptServer
+
+
+class FL_KsamplerSigma:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "model": ("MODEL",),
+ "positive": ("CONDITIONING",),
+ "negative": ("CONDITIONING",),
+ "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
+ "steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
+ "cfg": ("FLOAT", {"default": 7.0, "min": 0.0, "max": 100.0}),
+ "sampler_name": (comfy.samplers.KSampler.SAMPLERS,),
+ "denoise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
+ "sigma_max_hint": ("FLOAT", {"default": 14.6146, "min": 0.001, "max": 1000.0, "step": 0.01}),
+ "sigma_min_hint": ("FLOAT", {"default": 0.0292, "min": 0.0, "max": 1000.0, "step": 0.001}),
+ "schedule_curve": ("STRING", {"default": "", "multiline": False}),
+ },
+ "optional": {
+ "latent_image": ("LATENT",),
+ "vae": ("VAE",),
+ "image": ("IMAGE",),
+ },
+ }
+
+ RETURN_TYPES = ("MODEL", "CONDITIONING", "CONDITIONING", "LATENT", "VAE", "IMAGE", "SIGMAS")
+ RETURN_NAMES = ("model", "positive", "negative", "latent", "vae", "image", "sigmas")
+ FUNCTION = "sample"
+ CATEGORY = "🏵️Fill Nodes/Ksamplers"
+
+ def sample(self, model, positive, negative, seed, steps, cfg, sampler_name, denoise,
+ sigma_max_hint, sigma_min_hint, schedule_curve,
+ latent_image=None, vae=None, image=None):
+ try:
+ device = comfy.model_management.get_torch_device()
+
+ if image is not None and vae is not None:
+ latent_image = VAEEncode().encode(vae, image)[0]
+ elif latent_image is None:
+ latent_image = {"samples": torch.zeros((1, 4, 64, 64), device=device)}
+
+ sigmas = _build_sigmas(model, schedule_curve, steps, denoise)
+ if sigmas is None or sigmas.numel() < 2:
+ raise ValueError(
+ "FL_KsamplerSigma: schedule_curve is empty or invalid. "
+ "Draw a sigma curve on the node before sampling."
+ )
+
+ samples_dict = _sample_with_sigmas(
+ model, seed, cfg, sampler_name, positive, negative,
+ latent_image, sigmas,
+ )
+ sigmas_out = sigmas.detach().cpu()
+
+ output_image = None
+ if vae is not None:
+ output_image = VAEDecode().decode(vae, samples_dict)[0]
+
+ return (model, positive, negative, samples_dict, vae, output_image, sigmas_out)
+
+ except Exception as e:
+ logging.error(f"Error in FL_KsamplerSigma: {e}")
+ raise
+
+
+def _build_sigmas(model, curve_json, steps, denoise):
+ """Parse the curve JSON, interpolate to (steps+1) samples, enforce monotonicity,
+ clamp to the model's sigma range, and force the tail to zero."""
+ if not curve_json:
+ return None
+ try:
+ parsed = json.loads(curve_json)
+ except (json.JSONDecodeError, TypeError):
+ return None
+
+ points = parsed.get("points") if isinstance(parsed, dict) else parsed
+ if not isinstance(points, list) or len(points) < 2:
+ return None
+
+ interpolation = "monotone_cubic"
+ if isinstance(parsed, dict):
+ interpolation = parsed.get("interpolation", interpolation)
+ if interpolation not in ("monotone_cubic", "linear"):
+ interpolation = "monotone_cubic"
+
+ norm = []
+ for p in points:
+ if isinstance(p, dict):
+ t = p.get("t")
+ s = p.get("sigma")
+ elif isinstance(p, (list, tuple)) and len(p) >= 2:
+ t, s = p[0], p[1]
+ else:
+ continue
+ if t is None or s is None:
+ continue
+ try:
+ norm.append((float(t), float(s)))
+ except (TypeError, ValueError):
+ continue
+ if len(norm) < 2:
+ return None
+
+ norm.sort(key=lambda p: p[0])
+ if norm[0][0] > 1e-6:
+ norm.insert(0, (0.0, norm[0][1]))
+ if norm[-1][0] < 1.0 - 1e-6:
+ norm.append((1.0, norm[-1][1]))
+
+ effective_steps = steps if (denoise is None or denoise > 0.9999) else max(1, int(steps / denoise))
+ n_samples = effective_steps + 1
+ ts = torch.linspace(0.0, 1.0, n_samples, dtype=torch.float64)
+ xs = torch.tensor([p[0] for p in norm], dtype=torch.float64)
+ ys = torch.tensor([p[1] for p in norm], dtype=torch.float64)
+
+ if interpolation == "linear":
+ sigmas_full = _interp_linear(ts, xs, ys)
+ else:
+ sigmas_full = _interp_monotone_cubic(ts, xs, ys)
+
+ monotone = torch.cummin(sigmas_full, dim=0).values
+ monotone = torch.clamp(monotone, min=0.0)
+
+ model_sampling = model.get_model_object("model_sampling")
+ sigma_max = float(model_sampling.sigma_max)
+ monotone = torch.clamp(monotone, max=sigma_max)
+
+ if denoise is not None and denoise <= 0.9999 and denoise > 0.0:
+ monotone = monotone[-(steps + 1):]
+
+ monotone[-1] = 0.0
+ return monotone.to(dtype=torch.float32)
+
+
+def _interp_linear(ts, xs, ys):
+ idx = torch.searchsorted(xs, ts).clamp(1, len(xs) - 1)
+ x0 = xs[idx - 1]
+ x1 = xs[idx]
+ y0 = ys[idx - 1]
+ y1 = ys[idx]
+ w = (ts - x0) / (x1 - x0).clamp(min=1e-12)
+ return y0 + w * (y1 - y0)
+
+
+def _interp_monotone_cubic(ts, xs, ys):
+ """Fritsch-Carlson monotone cubic (PCHIP)."""
+ n = xs.shape[0]
+ if n == 2:
+ return _interp_linear(ts, xs, ys)
+
+ h = xs[1:] - xs[:-1]
+ delta = (ys[1:] - ys[:-1]) / h.clamp(min=1e-12)
+
+ m = torch.zeros(n, dtype=xs.dtype)
+ m[0] = delta[0]
+ m[-1] = delta[-1]
+ for i in range(1, n - 1):
+ if delta[i - 1] * delta[i] <= 0:
+ m[i] = 0.0
+ else:
+ w1 = 2 * h[i] + h[i - 1]
+ w2 = h[i] + 2 * h[i - 1]
+ m[i] = (w1 + w2) / (w1 / delta[i - 1] + w2 / delta[i])
+
+ for i in range(n - 1):
+ if delta[i] == 0:
+ m[i] = 0.0
+ m[i + 1] = 0.0
+ else:
+ a = m[i] / delta[i]
+ b = m[i + 1] / delta[i]
+ s = a * a + b * b
+ if s > 9.0:
+ tau = 3.0 / torch.sqrt(s)
+ m[i] = tau * a * delta[i]
+ m[i + 1] = tau * b * delta[i]
+
+ idx = torch.searchsorted(xs, ts).clamp(1, n - 1)
+ x0 = xs[idx - 1]
+ x1 = xs[idx]
+ y0 = ys[idx - 1]
+ y1 = ys[idx]
+ m0 = m[idx - 1]
+ m1 = m[idx]
+ hi = (x1 - x0).clamp(min=1e-12)
+ t = (ts - x0) / hi
+ t2 = t * t
+ t3 = t2 * t
+ h00 = 2 * t3 - 3 * t2 + 1
+ h10 = t3 - 2 * t2 + t
+ h01 = -2 * t3 + 3 * t2
+ h11 = t3 - t2
+ return h00 * y0 + h10 * hi * m0 + h01 * y1 + h11 * hi * m1
+
+
+def _sample_with_sigmas(model, seed, cfg, sampler_name, positive, negative, latent, sigmas):
+ latent_image = latent["samples"]
+ latent_image = comfy.sample.fix_empty_latent_channels(
+ model, latent_image, latent.get("downscale_ratio_spacial", None)
+ )
+
+ batch_inds = latent["batch_index"] if "batch_index" in latent else None
+ noise = comfy.sample.prepare_noise(latent_image, seed, batch_inds)
+
+ noise_mask = latent.get("noise_mask", None)
+
+ sampler = comfy.samplers.sampler_object(sampler_name)
+ sigmas = sigmas.to(device=model.load_device)
+
+ callback = latent_preview.prepare_callback(model, sigmas.shape[-1] - 1)
+ disable_pbar = not comfy.utils.PROGRESS_BAR_ENABLED
+
+ samples = comfy.sample.sample_custom(
+ model, noise, cfg, sampler, sigmas, positive, negative, latent_image,
+ noise_mask=noise_mask, callback=callback, disable_pbar=disable_pbar, seed=seed,
+ )
+ samples = samples.to(
+ device=comfy.model_management.intermediate_device(),
+ dtype=comfy.model_management.intermediate_dtype(),
+ )
+
+ out = latent.copy()
+ out.pop("downscale_ratio_spacial", None)
+ out["samples"] = samples
+ return out
diff --git a/comfyui_fill-nodes/nodes/ksamplers/__pycache__/FL_KsamplerBasic.cpython-310.pyc b/comfyui_fill-nodes/nodes/ksamplers/__pycache__/FL_KsamplerBasic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e1787ee290c79724c1768883d0c519578cce370e
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ksamplers/__pycache__/FL_KsamplerBasic.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ksamplers/__pycache__/FL_KsamplerPlus.cpython-310.pyc b/comfyui_fill-nodes/nodes/ksamplers/__pycache__/FL_KsamplerPlus.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3c05ac5a56fe3ceae39b8cb2f38ccfdcc81982b3
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ksamplers/__pycache__/FL_KsamplerPlus.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ksamplers/__pycache__/FL_KsamplerPlusV2.cpython-310.pyc b/comfyui_fill-nodes/nodes/ksamplers/__pycache__/FL_KsamplerPlusV2.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bbb8a83e3429d16d631076b67b255d9e6a866b17
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ksamplers/__pycache__/FL_KsamplerPlusV2.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/ksamplers/__pycache__/FL_KsamplerSettings.cpython-310.pyc b/comfyui_fill-nodes/nodes/ksamplers/__pycache__/FL_KsamplerSettings.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4bf4b8ebdbc7ccbf4122578970b8e002463c85e1
Binary files /dev/null and b/comfyui_fill-nodes/nodes/ksamplers/__pycache__/FL_KsamplerSettings.cpython-310.pyc differ
diff --git a/comfyui_fill-nodes/nodes/node_descriptions.json b/comfyui_fill-nodes/nodes/node_descriptions.json
new file mode 100644
index 0000000000000000000000000000000000000000..066f2a9912b9aba9a467419aa45527bf92aa39a4
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/node_descriptions.json
@@ -0,0 +1,1032 @@
+{
+ "ai": [
+ {
+ "class": "FL_Fal_Gemini_ImageEdit",
+ "file": "FL_Fal_Gemini_ImageEdit.py",
+ "description": "A ComfyUI node for the Fal AI Gemini 2.5 Flash Image Edit API. Takes multiple images and a prompt to edit them using Gemini's multimodal capabilities.",
+ "category": "ai"
+ },
+ {
+ "class": "FL_Fal_Kling_AIAvatar",
+ "file": "FL_Fal_Kling_AIAvatar.py",
+ "description": "A ComfyUI node for the Fal AI Kling Video AI Avatar API. Takes an image and audio to generate realistic avatar videos.",
+ "category": "ai"
+ },
+ {
+ "class": "FL_Fal_Kontext",
+ "file": "FL_Fal_Kontext.py",
+ "description": "A ComfyUI node for the Fal AI Flux Pro Kontext API. Takes multiple image/prompt pairs and generates new images using Fal AI's flux-pro/kontext endpoint. Supports async processing for multiple inputs.",
+ "category": "ai"
+ },
+ {
+ "class": "FL_Fal_Pixverse",
+ "file": "FL_Fal_Pixverse.py",
+ "description": "A ComfyUI node for the Fal AI Image-to-Video API. Takes an image and converts it to a video using Fal AI's pixverse/v4/image-to-video endpoint. Downloads the video, extracts frames, and returns them as image tensors.",
+ "category": "ai"
+ },
+ {
+ "class": "FL_Fal_Pixverse_LipSync",
+ "file": "FL_Fal_Pixverse_LipSync.py",
+ "description": "A ComfyUI node for the Fal AI Pixverse LipSync API. Takes a video and audio/text and generates realistic lipsync animations.",
+ "category": "ai"
+ },
+ {
+ "class": "FL_Fal_Pixverse_Transition",
+ "file": "FL_Fal_Pixverse_Transition.py",
+ "description": "A ComfyUI node for the Fal AI Pixverse v5 Transition API. Takes two images and creates a transition video between them using Fal AI's transition endpoint. Downloads the video, extracts frames, and returns them as image tensors.",
+ "category": "ai"
+ },
+ {
+ "class": "FL_Fal_Seedance_i2v",
+ "file": "FL_Fal_Seedance_i2v.py",
+ "description": null,
+ "category": "ai"
+ },
+ {
+ "class": "FL_Fal_Seedream_Edit",
+ "file": "FL_Fal_Seedream_Edit.py",
+ "description": "A ComfyUI node for the Fal AI ByteDance Seedream v4 Edit API. Takes multiple images and a prompt to edit them using Seedream's capabilities.",
+ "category": "ai"
+ },
+ {
+ "class": "FL_Fal_Sora",
+ "file": "FL_Fal_Sora.py",
+ "description": null,
+ "category": "ai"
+ },
+ {
+ "class": "FL_GeminiImageEditor",
+ "file": "FL_GeminiImageEditor.py",
+ "description": null,
+ "category": "ai"
+ },
+ {
+ "class": "FL_GeminiImageGenADV",
+ "file": "FL_GeminiImageGenADV.py",
+ "description": null,
+ "category": "ai"
+ },
+ {
+ "class": "FL_GeminiTextAPI",
+ "file": "FL_GeminiTextAPI.py",
+ "description": null,
+ "category": "ai"
+ },
+ {
+ "class": "FL_GeminiVideoCaptioner",
+ "file": "FL_GeminiVideoCaptioner.py",
+ "description": "Node for captioning videos using Google's Gemini API. Note: All videos (from file or image batch) are converted to WebM format with a size limit of just under 30MB to ensure compatibility with the Gemini API payload limitations. Video quality will be adjusted automatically to meet the size requirement.",
+ "category": "ai"
+ },
+ {
+ "class": "FL_Hedra_API",
+ "file": "FL_Hedra_API.py",
+ "description": null,
+ "category": "ai"
+ },
+ {
+ "class": "FL_HunyuanDelight",
+ "file": "FL_HunyuanDelight.py",
+ "description": null,
+ "category": "ai"
+ },
+ {
+ "class": "FL_PixVerseAPI",
+ "file": "FL_PixVerseAPI.py",
+ "description": "A ComfyUI node for the PixVerse Image-to-Video API. Takes an image and converts it to a video using PixVerse's API. Downloads the video, extracts frames, and returns them as image tensors.",
+ "category": "ai"
+ },
+ {
+ "class": "FL_RunwayAct2",
+ "file": "FL_RunwayAct2.py",
+ "description": null,
+ "category": "ai"
+ },
+ {
+ "class": "FL_RunwayImageAPI",
+ "file": "FL_RunwayImageAPI.py",
+ "description": null,
+ "category": "ai"
+ },
+ {
+ "class": "FL_VertexGemini25FlashImage",
+ "file": "FL_VertexGemini25FlashImage.py",
+ "description": null,
+ "category": "ai"
+ },
+ {
+ "class": "FL_Veo3VideoGen",
+ "file": "FL_VertexVeo3.py",
+ "description": null,
+ "category": "ai"
+ }
+ ],
+ "api_tools": [
+ {
+ "class": "FL_API_Base64_ImageLoader",
+ "file": "FL_API_Base64_ImageLoader.py",
+ "description": null,
+ "category": "api_tools"
+ },
+ {
+ "class": "FL_API_ImageSaver",
+ "file": "FL_API_ImageSaver.py",
+ "description": null,
+ "category": "api_tools"
+ }
+ ],
+ "audio": [
+ {
+ "class": "FL_Audio_Beat_Visualizer",
+ "file": "FL_Audio_Beat_Visualizer.py",
+ "description": "A ComfyUI node for generating beat visualization frames. Creates frames that alternate between black and white on beat switches.",
+ "category": "audio"
+ },
+ {
+ "class": "FL_Audio_BPM_Analyzer",
+ "file": "FL_Audio_BPM_Analyzer.py",
+ "description": "A ComfyUI node for BPM and beat detection using Librosa. Analyzes the entire audio once and outputs beat positions for use in segmentation.",
+ "category": "audio"
+ },
+ {
+ "class": "FL_Audio_Crop",
+ "file": "FL_Audio_Crop.py",
+ "description": "A ComfyUI node for cropping (trimming) audio to a specific start and end time.",
+ "category": "audio"
+ },
+ {
+ "class": "FL_Audio_Drum_Detector",
+ "file": "FL_Audio_Drum_Detector.py",
+ "description": "A ComfyUI node for detecting drum elements (kicks, snares, hi-hats) from audio. Uses onset detection with frequency band analysis to classify drum types.",
+ "category": "audio"
+ },
+ {
+ "class": "FL_Audio_Envelope_Visualizer",
+ "file": "FL_Audio_Envelope_Visualizer.py",
+ "description": "A ComfyUI node for visualizing audio envelopes as frames. Creates white frames that fade to black based on envelope values.",
+ "category": "audio"
+ },
+ {
+ "class": "FL_Audio_Music_Video_Sequencer",
+ "file": "FL_Audio_Music_Video_Sequencer.py",
+ "description": "A ComfyUI node for generating complete music video shot sequences. Takes beat positions and a pattern, outputs a full edit list for the entire song.",
+ "category": "audio"
+ },
+ {
+ "class": "FL_Audio_Reactive_Brightness",
+ "file": "FL_Audio_Reactive_Brightness.py",
+ "description": "A ComfyUI node for applying audio-reactive brightness/luminance changes to frames. Adjusts brightness based on envelope values from drum detection.",
+ "category": "audio"
+ },
+ {
+ "class": "FL_Audio_Reactive_Edge_Glow",
+ "file": "FL_Audio_Reactive_Edge_Glow.py",
+ "description": "A ComfyUI node for applying audio-reactive edge detection and glow effect. Detects edges and adds glowing outline that pulses with the audio.",
+ "category": "audio"
+ },
+ {
+ "class": "FL_Audio_Reactive_Envelope",
+ "file": "FL_Audio_Reactive_Envelope.py",
+ "description": "A ComfyUI node for generating per-frame control envelopes from drum detections. Creates ADSR envelopes for kicks, snares, and hi-hats across the entire song.",
+ "category": "audio"
+ },
+ {
+ "class": "FL_Audio_Reactive_Saturation",
+ "file": "FL_Audio_Reactive_Saturation.py",
+ "description": "A ComfyUI node for applying audio-reactive saturation changes to frames. Adjusts color saturation based on envelope values from drum detection.",
+ "category": "audio"
+ },
+ {
+ "class": "FL_Audio_Reactive_Scale",
+ "file": "FL_Audio_Reactive_Scale.py",
+ "description": "A ComfyUI node for applying audio-reactive scale/zoom effect to frames. Scales frames based on envelope values from drum detection.",
+ "category": "audio"
+ },
+ {
+ "class": "FL_Audio_Reactive_Speed",
+ "file": "FL_Audio_Reactive_Speed.py",
+ "description": "A ComfyUI node for applying audio-reactive speed/time remapping to frames. Speeds up or slows down playback based on envelope values from drum detection.",
+ "category": "audio"
+ },
+ {
+ "class": "FL_Audio_Segment_Extractor",
+ "file": "FL_Audio_Segment_Extractor.py",
+ "description": "A ComfyUI node for extracting audio segments based on pre-analyzed beat positions. Takes beat positions from FL_Audio_BPM_Analyzer and extracts specific beat ranges.",
+ "category": "audio"
+ },
+ {
+ "class": "FL_Audio_Separation",
+ "file": "FL_Audio_Separation.py",
+ "description": "A ComfyUI node for separating audio into four sources: bass, drums, other, and vocals. Uses the Hybrid Demucs model from torchaudio.",
+ "category": "audio"
+ },
+ {
+ "class": "FL_Audio_Shot_Iterator",
+ "file": "FL_Audio_Shot_Iterator.py",
+ "description": "A ComfyUI node for extracting individual shot data from a music video sequence. Takes sequence JSON and shot index, outputs frame count and shot details.",
+ "category": "audio"
+ }
+ ],
+ "captioning": [
+ {
+ "class": "FL_CaptionSaver_V2",
+ "file": "FL_Caption_Saver_V2.py",
+ "description": null,
+ "category": "captioning"
+ },
+ {
+ "class": "FL_CaptionToCSV",
+ "file": "FL_CaptionToCSV.py",
+ "description": null,
+ "category": "captioning"
+ },
+ {
+ "class": "FL_CSVExtractor",
+ "file": "FL_CSVExtractor.py",
+ "description": null,
+ "category": "captioning"
+ },
+ {
+ "class": "FL_ImageCaptionSaver",
+ "file": "FL_Image_Caption_Saver.py",
+ "description": null,
+ "category": "captioning"
+ },
+ {
+ "class": "FL_ImageCaptionLayout",
+ "file": "FL_ImageCaptionLayout.py",
+ "description": null,
+ "category": "captioning"
+ },
+ {
+ "class": "FL_ImageCaptionLayoutPDF",
+ "file": "FL_ImageCaptionLayoutPDF.py",
+ "description": null,
+ "category": "captioning"
+ },
+ {
+ "class": "FL_LoadCSV",
+ "file": "FL_LoadCSV.py",
+ "description": null,
+ "category": "captioning"
+ },
+ {
+ "class": "FL_MirrorAndAppendCaptions",
+ "file": "FL_MirrorAndAppendCaptions.py",
+ "description": null,
+ "category": "captioning"
+ },
+ {
+ "class": "FL_OllamaCaptioner",
+ "file": "FL_OllamaCaptioner.py",
+ "description": null,
+ "category": "captioning"
+ },
+ {
+ "class": "FL_SaveCSV",
+ "file": "FL_SaveCSV.py",
+ "description": null,
+ "category": "captioning"
+ },
+ {
+ "class": "FL_VideoCaptionSaver",
+ "file": "FL_Video_Caption_Saver.py",
+ "description": null,
+ "category": "captioning"
+ },
+ {
+ "class": "FL_WordFrequencyGraph",
+ "file": "FL_WordFrequencyGraph.py",
+ "description": null,
+ "category": "captioning"
+ }
+ ],
+ "discord": [
+ {
+ "class": "FL_SendToDiscordWebhook",
+ "file": "FL_DiscordWebhook.py",
+ "description": null,
+ "category": "discord"
+ }
+ ],
+ "experiments": [
+ {
+ "class": "FL_BatchAlign",
+ "file": "FL_BatchAligned.py",
+ "description": null,
+ "category": "experiments"
+ },
+ {
+ "class": "FL_ColorPicker",
+ "file": "FL_ColorPicker.py",
+ "description": null,
+ "category": "experiments"
+ },
+ {
+ "class": "FL_GradGenerator",
+ "file": "FL_GradGen.py",
+ "description": null,
+ "category": "experiments"
+ },
+ {
+ "class": "FL_NFTGenerator",
+ "file": "FL_NFTGenerator.py",
+ "description": null,
+ "category": "experiments"
+ }
+ ],
+ "file_operations": [
+ {
+ "class": "FL_ZipDirectory",
+ "file": "FL_ZipDirectory.py",
+ "description": null,
+ "category": "file_operations"
+ },
+ {
+ "class": "FL_ZipSave",
+ "file": "FL_ZipSave.py",
+ "description": null,
+ "category": "file_operations"
+ }
+ ],
+ "games": [
+ {
+ "class": "FL_BulletHellGame",
+ "file": "FL_BulletHellGame.py",
+ "description": null,
+ "category": "games"
+ },
+ {
+ "class": "FL_TetrisGame",
+ "file": "FL_TetrisGame.py",
+ "description": null,
+ "category": "games"
+ }
+ ],
+ "google_drive": [
+ {
+ "class": "FL_GoogleCloudStorage",
+ "file": "FL_GoogleCloudStorage.py",
+ "description": "A ComfyUI node for uploading images and videos to Google Cloud Storage. Can handle single images, batches of images, and optionally compile batches into videos.",
+ "category": "google_drive"
+ },
+ {
+ "class": "FL_GoogleDriveDownloader",
+ "file": "FL_GoogleDriveDownloader.py",
+ "description": null,
+ "category": "google_drive"
+ },
+ {
+ "class": "FL_GoogleDriveImageDownloader",
+ "file": "FL_GoogleDriveImageDownloader.py",
+ "description": null,
+ "category": "google_drive"
+ }
+ ],
+ "gpt": [
+ {
+ "class": "FL_Dalle3",
+ "file": "FL_Dalle3.py",
+ "description": null,
+ "category": "gpt"
+ },
+ {
+ "class": "FL_GPT_Image1",
+ "file": "FL_GPT_Image1.py",
+ "description": null,
+ "category": "gpt"
+ },
+ {
+ "class": "FL_GPT_Image1_ADV",
+ "file": "FL_GPT_Image1_ADV.py",
+ "description": null,
+ "category": "gpt"
+ },
+ {
+ "class": "FL_GPT_Text",
+ "file": "FL_GPT_Text.py",
+ "description": null,
+ "category": "gpt"
+ },
+ {
+ "class": "FL_GPT_Vision",
+ "file": "FL_GPT_Vision.py",
+ "description": null,
+ "category": "gpt"
+ },
+ {
+ "class": "FL_SimpleGPTVision",
+ "file": "FL_SimpleGPTVision.py",
+ "description": null,
+ "category": "gpt"
+ }
+ ],
+ "hugging_face": [
+ {
+ "class": "FL_HF_Character",
+ "file": "FL_HF_Character.py",
+ "description": null,
+ "category": "hugging_face"
+ },
+ {
+ "class": "FL_HF_UploaderAbsolute",
+ "file": "FL_HF_UploaderAbsolute.py",
+ "description": null,
+ "category": "hugging_face"
+ },
+ {
+ "class": "FL_HFDatasetDownloader",
+ "file": "FL_HFDatasetDownloader.py",
+ "description": null,
+ "category": "hugging_face"
+ },
+ {
+ "class": "FL_HFHubModelUploader",
+ "file": "FL_HFHubModelUploader.py",
+ "description": null,
+ "category": "hugging_face"
+ }
+ ],
+ "image": [
+ {
+ "class": "FL_AnimeLineExtractor",
+ "file": "FL_AnimeLineExtractor.py",
+ "description": null,
+ "category": "image"
+ },
+ {
+ "class": "FL_ApplyMask",
+ "file": "FL_ApplyMask.py",
+ "description": null,
+ "category": "image"
+ },
+ {
+ "class": "FL_BlackFrameReject",
+ "file": "FL_BlackFrameReject.py",
+ "description": "A node that filters out images from a batch based on the percentage of black pixels. Images with a black pixel percentage above the threshold are rejected.",
+ "category": "image"
+ },
+ {
+ "class": "FL_ImageAddToBatch",
+ "file": "FL_Image_AddToBatch.py",
+ "description": null,
+ "category": "image"
+ },
+ {
+ "class": "FL_ImageBlank",
+ "file": "FL_Image_Blank.py",
+ "description": null,
+ "category": "image"
+ },
+ {
+ "class": "FL_ImageCrop",
+ "file": "FL_Image_Crop.py",
+ "description": null,
+ "category": "image"
+ },
+ {
+ "class": "FL_ImageDimensionDisplay",
+ "file": "FL_Image_Dimension_Display.py",
+ "description": null,
+ "category": "image"
+ },
+ {
+ "class": "FL_ImageRandomizer",
+ "file": "FL_Image_Randomizer.py",
+ "description": null,
+ "category": "image"
+ },
+ {
+ "class": "FL_ImageAddNoise",
+ "file": "FL_ImageAddNoise.py",
+ "description": null,
+ "category": "image"
+ },
+ {
+ "class": "FL_ImageAdjuster",
+ "file": "FL_ImageAdjuster.py",
+ "description": null,
+ "category": "image"
+ },
+ {
+ "class": "FL_ImageAspectCropper",
+ "file": "FL_ImageAspectCropper.py",
+ "description": null,
+ "category": "image"
+ },
+ {
+ "class": "FL_ImageBatch",
+ "file": "FL_ImageBatch.py",
+ "description": null,
+ "category": "image"
+ },
+ {
+ "class": "FL_ImageListToImageBatch",
+ "file": "FL_ImageBatchListConverter.py",
+ "description": null,
+ "category": "image"
+ },
+ {
+ "class": "FL_ImageBatchToGrid",
+ "file": "FL_ImageBatchToGrid.py",
+ "description": null,
+ "category": "image"
+ },
+ {
+ "class": "FL_ImageNotes",
+ "file": "FL_ImageNotes.py",
+ "description": null,
+ "category": "image"
+ },
+ {
+ "class": "FL_ImageSelector",
+ "file": "FL_ImageSelector.py",
+ "description": null,
+ "category": "image"
+ },
+ {
+ "class": "FL_ImageSlicer",
+ "file": "FL_ImageSlicer.py",
+ "description": null,
+ "category": "image"
+ },
+ {
+ "class": "FL_LoadImage",
+ "file": "FL_LoadImage.py",
+ "description": null,
+ "category": "image"
+ },
+ {
+ "class": "FL_PaddingRemover",
+ "file": "FL_PaddingRemover.py",
+ "description": null,
+ "category": "image"
+ },
+ {
+ "class": "FL_ReplaceColor",
+ "file": "FL_ReplaceColor.py",
+ "description": null,
+ "category": "image"
+ },
+ {
+ "class": "FL_SaveImages",
+ "file": "FL_SaveImages.py",
+ "description": null,
+ "category": "image"
+ },
+ {
+ "class": "FL_SaveRGBAAnimatedWebP",
+ "file": "FL_SaveRGBAAnimatedWebP.py",
+ "description": null,
+ "category": "image"
+ },
+ {
+ "class": "FL_SaveWebM",
+ "file": "FL_SaveWebM.py",
+ "description": null,
+ "category": "image"
+ }
+ ],
+ "ksamplers": [
+ {
+ "class": "FL_KsamplerBasic",
+ "file": "FL_KsamplerBasic.py",
+ "description": null,
+ "category": "ksamplers"
+ },
+ {
+ "class": "FL_KsamplerPlus",
+ "file": "FL_KsamplerPlus.py",
+ "description": null,
+ "category": "ksamplers"
+ },
+ {
+ "class": "FL_KsamplerPlusV2",
+ "file": "FL_KsamplerPlusV2.py",
+ "description": null,
+ "category": "ksamplers"
+ },
+ {
+ "class": "FL_KsamplerSettings",
+ "file": "FL_KsamplerSettings.py",
+ "description": null,
+ "category": "ksamplers"
+ },
+ {
+ "class": "FL_KSamplerXYZPlot",
+ "file": "FL_KSamplerXYZPlot.py",
+ "description": null,
+ "category": "ksamplers"
+ },
+ {
+ "class": "FL_SamplerStrings",
+ "file": "FL_SamplerStrings.py",
+ "description": null,
+ "category": "ksamplers"
+ },
+ {
+ "class": "FL_SchedulerStrings",
+ "file": "FL_SchedulerStrings.py",
+ "description": null,
+ "category": "ksamplers"
+ }
+ ],
+ "loaders": [
+ {
+ "class": "FL_NodeLoader",
+ "file": "FL_NodeLoader.py",
+ "description": null,
+ "category": "loaders"
+ },
+ {
+ "class": "FL_NodePackLoader",
+ "file": "FL_NodePackLoader.py",
+ "description": null,
+ "category": "loaders"
+ },
+ {
+ "class": "FL_UpscaleModel",
+ "file": "FL_UpscaleModel.py",
+ "description": null,
+ "category": "loaders"
+ }
+ ],
+ "pdf": [
+ {
+ "class": "FL_BulkPDFLoader",
+ "file": "FL_BulkPDFLoader.py",
+ "description": null,
+ "category": "pdf"
+ },
+ {
+ "class": "FL_ImagesToPDF",
+ "file": "FL_ImagesToPDF.py",
+ "description": null,
+ "category": "pdf"
+ },
+ {
+ "class": "FL_PDFEncryptor",
+ "file": "FL_PDFEncryptor.py",
+ "description": null,
+ "category": "pdf"
+ },
+ {
+ "class": "FL_PDFImageExtractor",
+ "file": "FL_PDFImageExtractor.py",
+ "description": null,
+ "category": "pdf"
+ },
+ {
+ "class": "FL_PDFLoader",
+ "file": "FL_PDFLoader.py",
+ "description": null,
+ "category": "pdf"
+ },
+ {
+ "class": "FL_PDFMerger",
+ "file": "FL_PDFMerger.py",
+ "description": null,
+ "category": "pdf"
+ },
+ {
+ "class": "FL_PDFSaver",
+ "file": "FL_PDFSaver.py",
+ "description": null,
+ "category": "pdf"
+ },
+ {
+ "class": "FL_PDFTextExtractor",
+ "file": "FL_PDFTextExtractor.py",
+ "description": null,
+ "category": "pdf"
+ },
+ {
+ "class": "FL_PDFToImages",
+ "file": "FL_PDFToImage.py",
+ "description": null,
+ "category": "pdf"
+ },
+ {
+ "class": "FL_TextToPDF",
+ "file": "FL_TextToPDF.py",
+ "description": null,
+ "category": "pdf"
+ }
+ ],
+ "prompting": [
+ {
+ "class": "FL_MadLibGenerator",
+ "file": "FL_MadLibGenerator.py",
+ "description": null,
+ "category": "prompting"
+ },
+ {
+ "class": "FL_PromptBasic",
+ "file": "FL_Prompt.py",
+ "description": null,
+ "category": "prompting"
+ },
+ {
+ "class": "FL_PromptMulti",
+ "file": "FL_PromptMulti.py",
+ "description": null,
+ "category": "prompting"
+ },
+ {
+ "class": "FL_PromptSelector",
+ "file": "FL_PromptSelector.py",
+ "description": null,
+ "category": "prompting"
+ }
+ ],
+ "utility": [
+ {
+ "class": "FL_ClipScanner",
+ "file": "FL_ClipScanner.py",
+ "description": null,
+ "category": "utility"
+ },
+ {
+ "class": "FL_DirectoryCrawl",
+ "file": "FL_DirectoryCrawl.py",
+ "description": null,
+ "category": "utility"
+ },
+ {
+ "class": "FL_Float",
+ "file": "FL_Float.py",
+ "description": null,
+ "category": "utility"
+ },
+ {
+ "class": "FL_InpaintCrop",
+ "file": "FL_InpaintCrop.py",
+ "description": null,
+ "category": "utility"
+ },
+ {
+ "class": "FL_JS",
+ "file": "FL_JS.py",
+ "description": null,
+ "category": "utility"
+ },
+ {
+ "class": "FL_Math",
+ "file": "FL_Math.py",
+ "description": null,
+ "category": "utility"
+ },
+ {
+ "class": "FL_ModelInspector",
+ "file": "FL_ModelInspector.py",
+ "description": null,
+ "category": "utility"
+ },
+ {
+ "class": "FL_Padding",
+ "file": "FL_Padding.py",
+ "description": null,
+ "category": "utility"
+ },
+ {
+ "class": "FL_PasteByMask",
+ "file": "FL_PasteByMask.py",
+ "description": "Pastes `image_to_paste` onto `image_base` using `mask` to determine the location. The `resize_behavior` parameter determines how the image to paste is resized to fit the mask. If `mask_mapping_optional` obtained from a 'Separate Mask Components' node is used, it will control which image gets pasted onto which base image.",
+ "category": "utility"
+ },
+ {
+ "class": "FL_PasteOnCanvas",
+ "file": "FL_PasteOnCanvas.py",
+ "description": null,
+ "category": "utility"
+ },
+ {
+ "class": "FL_PathTypeChecker",
+ "file": "FL_PathTypeChecker.py",
+ "description": null,
+ "category": "utility"
+ },
+ {
+ "class": "FL_RandomNumber",
+ "file": "FL_RandomRange.py",
+ "description": null,
+ "category": "utility"
+ },
+ {
+ "class": "FL_SDUltimate_Slices",
+ "file": "FL_SD_Slices.py",
+ "description": null,
+ "category": "utility"
+ },
+ {
+ "class": "FL_SeparateMaskComponents",
+ "file": "FL_SeparateMasks.py",
+ "description": null,
+ "category": "utility"
+ },
+ {
+ "class": "FL_Switch",
+ "file": "FL_Switch.py",
+ "description": null,
+ "category": "utility"
+ },
+ {
+ "class": "FL_Switch_Big",
+ "file": "FL_Switch_Big.py",
+ "description": null,
+ "category": "utility"
+ },
+ {
+ "class": "FL_SystemCheck",
+ "file": "FL_SystemCheck.py",
+ "description": null,
+ "category": "utility"
+ },
+ {
+ "class": "FL_UnloadModel",
+ "file": "FL_UnloadModel.py",
+ "description": null,
+ "category": "utility"
+ },
+ {
+ "class": "FL_VideoCropMask",
+ "file": "FL_VideoCropNStitch.py",
+ "description": null,
+ "category": "utility"
+ }
+ ],
+ "vfx": [
+ {
+ "class": "FL_Ascii",
+ "file": "FL_Ascii.py",
+ "description": null,
+ "category": "vfx"
+ },
+ {
+ "class": "FL_Dither",
+ "file": "FL_Dither.py",
+ "description": null,
+ "category": "vfx"
+ },
+ {
+ "class": "FL_Glitch",
+ "file": "FL_Glitch.py",
+ "description": null,
+ "category": "vfx"
+ },
+ {
+ "class": "FL_HalftonePattern",
+ "file": "FL_HalfTone.py",
+ "description": null,
+ "category": "vfx"
+ },
+ {
+ "class": "FL_HexagonalPattern",
+ "file": "FL_HexagonalPattern.py",
+ "description": null,
+ "category": "vfx"
+ },
+ {
+ "class": "FL_ImagePixelator",
+ "file": "FL_Image_Pixelator.py",
+ "description": null,
+ "category": "vfx"
+ },
+ {
+ "class": "FL_ImageCollage",
+ "file": "FL_ImageCollage.py",
+ "description": null,
+ "category": "vfx"
+ },
+ {
+ "class": "FL_InfiniteZoom",
+ "file": "FL_InfiniteZoom.py",
+ "description": null,
+ "category": "vfx"
+ },
+ {
+ "class": "FL_PaperDrawn",
+ "file": "FL_PaperDrawn.py",
+ "description": null,
+ "category": "vfx"
+ },
+ {
+ "class": "FL_PixelArtShader",
+ "file": "FL_PixelArt.py",
+ "description": null,
+ "category": "vfx"
+ },
+ {
+ "class": "FL_PixelSort",
+ "file": "FL_PixelSort.py",
+ "description": null,
+ "category": "vfx"
+ },
+ {
+ "class": "FL_RetroEffect",
+ "file": "FL_RetroEffect.py",
+ "description": null,
+ "category": "vfx"
+ },
+ {
+ "class": "FL_Ripple",
+ "file": "FL_Ripple.py",
+ "description": null,
+ "category": "vfx"
+ },
+ {
+ "class": "FL_Shadertoy",
+ "file": "FL_Shader.py",
+ "description": null,
+ "category": "vfx"
+ },
+ {
+ "class": "FL_TextOverlayNode",
+ "file": "FL_TextOverlay.py",
+ "description": null,
+ "category": "vfx"
+ }
+ ],
+ "video": [
+ {
+ "class": "FL_FILM",
+ "file": "FL_FILM.py",
+ "description": "FILM (Frame Interpolation for Large Motion) frame interpolation node. Generates intermediate frames between input frames, especially good for large motion. Downloads model to cache folder on first use.",
+ "category": "video"
+ },
+ {
+ "class": "FL_ProResVideo",
+ "file": "FL_ProResVideo.py",
+ "description": null,
+ "category": "video"
+ },
+ {
+ "class": "FL_RIFE",
+ "file": "FL_RIFE.py",
+ "description": "RIFE (Real-Time Intermediate Flow Estimation) frame interpolation node. Generates intermediate frames between input frames for smooth slow-motion effects. Downloads models to cache folder on first use.",
+ "category": "video"
+ },
+ {
+ "class": "FL_VideoBatchSplitter",
+ "file": "FL_VideoBatchSplitter.py",
+ "description": null,
+ "category": "video"
+ },
+ {
+ "class": "FL_VideoCadence",
+ "file": "FL_VideoCadence.py",
+ "description": null,
+ "category": "video"
+ },
+ {
+ "class": "FL_VideoCadenceCompile",
+ "file": "FL_VideoCadenceCompile.py",
+ "description": null,
+ "category": "video"
+ },
+ {
+ "class": "FL_VideoCrossfade",
+ "file": "FL_VideoCrossfade.py",
+ "description": null,
+ "category": "video"
+ },
+ {
+ "class": "FL_VideoCut",
+ "file": "FL_VideoCut.py",
+ "description": "A node that detects scene cuts in a batch of images (video frames) and outputs the segmented clips as MP4 files to a specified folder.",
+ "category": "video"
+ },
+ {
+ "class": "FL_VideoTrim",
+ "file": "FL_VideoTrim.py",
+ "description": null,
+ "category": "video"
+ }
+ ],
+ "wip": [
+ {
+ "class": "FL_FractalKSampler",
+ "file": "FL_KsamplerFractals.py",
+ "description": null,
+ "category": "wip"
+ },
+ {
+ "class": "FL_TimeLine",
+ "file": "FL_TimeLine.py",
+ "description": null,
+ "category": "wip"
+ },
+ {
+ "class": "FL_WanFirstLastFrameToVideo",
+ "file": "FL_WanFirstLastFrameToVideo.py",
+ "description": null,
+ "category": "wip"
+ },
+ {
+ "class": "FL_WF_Agent",
+ "file": "FL_WF_Agent.py",
+ "description": "A node that uses Gemini AI to generate and execute JavaScript code for workflow manipulation",
+ "category": "wip"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/rife_arch.py b/comfyui_fill-nodes/nodes/rife_arch.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf2b4545298a1f34d8429e93f0aa4f43c06c090e
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/rife_arch.py
@@ -0,0 +1,586 @@
+"""
+26-Dez-21
+https://github.com/hzwer/Practical-RIFE
+https://github.com/hzwer/Practical-RIFE/blob/main/model/warplayer.py
+https://github.com/HolyWu/vs-rife/blob/master/vsrife/__init__.py
+"""
+from torch.nn.parallel import DistributedDataParallel as DDP
+from torch.optim import AdamW
+import torch
+import torch.nn.functional as F
+import torch.nn as nn
+import torch.optim as optim
+import warnings
+from comfy.model_management import get_torch_device
+
+device = get_torch_device()
+backwarp_tenGrid = {}
+
+
+class ResConv(nn.Module):
+ def __init__(self, c, dilation=1):
+ super(ResConv, self).__init__()
+ self.conv = nn.Conv2d(c, c, 3, 1, dilation, dilation=dilation, groups=1)
+ self.beta = nn.Parameter(torch.ones((1, c, 1, 1)), requires_grad=True)
+ self.relu = nn.LeakyReLU(0.2, True)
+
+ def forward(self, x):
+ return self.relu(self.conv(x) * self.beta + x)
+
+
+def warp(tenInput, tenFlow):
+ k = (str(tenFlow.device), str(tenFlow.size()))
+ if k not in backwarp_tenGrid:
+ tenHorizontal = (
+ torch.linspace(-1.0, 1.0, tenFlow.shape[3], device=device)
+ .view(1, 1, 1, tenFlow.shape[3])
+ .expand(tenFlow.shape[0], -1, tenFlow.shape[2], -1)
+ )
+ tenVertical = (
+ torch.linspace(-1.0, 1.0, tenFlow.shape[2], device=device)
+ .view(1, 1, tenFlow.shape[2], 1)
+ .expand(tenFlow.shape[0], -1, -1, tenFlow.shape[3])
+ )
+ backwarp_tenGrid[k] = torch.cat([tenHorizontal, tenVertical], 1).to(device)
+
+ tenFlow = torch.cat(
+ [
+ tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0),
+ tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0),
+ ],
+ 1,
+ )
+
+ g = (backwarp_tenGrid[k] + tenFlow).permute(0, 2, 3, 1)
+
+ if tenInput.type() == "torch.cuda.HalfTensor":
+ g = g.half()
+
+ padding_mode = "border"
+ if device.type == "mps":
+ # https://github.com/pytorch/pytorch/issues/125098
+ padding_mode = "zeros"
+ g = g.clamp(-1, 1)
+ return torch.nn.functional.grid_sample(
+ input=tenInput,
+ grid=g,
+ mode="bilinear",
+ padding_mode=padding_mode,
+ align_corners=True,
+ )
+
+
+def conv(
+ in_planes,
+ out_planes,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ dilation=1,
+ arch_ver="4.0",
+):
+ if arch_ver == "4.0":
+ return nn.Sequential(
+ nn.Conv2d(
+ in_planes,
+ out_planes,
+ kernel_size=kernel_size,
+ stride=stride,
+ padding=padding,
+ dilation=dilation,
+ bias=True,
+ ),
+ nn.PReLU(out_planes),
+ )
+ if arch_ver in ["4.2", "4.3", "4.5", "4.6", "4.7", "4.10"]:
+ return nn.Sequential(
+ nn.Conv2d(
+ in_planes,
+ out_planes,
+ kernel_size=kernel_size,
+ stride=stride,
+ padding=padding,
+ dilation=dilation,
+ bias=True,
+ ),
+ nn.LeakyReLU(0.2, True),
+ )
+
+
+def conv_woact(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
+ return nn.Sequential(
+ nn.Conv2d(
+ in_planes,
+ out_planes,
+ kernel_size=kernel_size,
+ stride=stride,
+ padding=padding,
+ dilation=dilation,
+ bias=True,
+ ),
+ )
+
+
+def conv_woact(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
+ return nn.Sequential(
+ nn.Conv2d(
+ in_planes,
+ out_planes,
+ kernel_size=kernel_size,
+ stride=stride,
+ padding=padding,
+ dilation=dilation,
+ bias=True,
+ )
+ )
+
+
+def deconv(in_planes, out_planes, kernel_size=4, stride=2, padding=1, arch_ver="4.0"):
+ if arch_ver == "4.0":
+ return nn.Sequential(
+ torch.nn.ConvTranspose2d(
+ in_channels=in_planes,
+ out_channels=out_planes,
+ kernel_size=4,
+ stride=2,
+ padding=1,
+ bias=True,
+ ),
+ nn.PReLU(out_planes),
+ )
+ if arch_ver in ["4.2", "4.3", "4.5", "4.6", "4.7", "4.10"]:
+ return nn.Sequential(
+ torch.nn.ConvTranspose2d(
+ in_channels=in_planes,
+ out_channels=out_planes,
+ kernel_size=4,
+ stride=2,
+ padding=1,
+ bias=True,
+ ),
+ nn.LeakyReLU(0.2, True),
+ )
+
+
+class Conv2(nn.Module):
+ def __init__(self, in_planes, out_planes, stride=2, arch_ver="4.0"):
+ super(Conv2, self).__init__()
+ self.conv1 = conv(in_planes, out_planes, 3, stride, 1, arch_ver=arch_ver)
+ self.conv2 = conv(out_planes, out_planes, 3, 1, 1, arch_ver=arch_ver)
+
+ def forward(self, x):
+ x = self.conv1(x)
+ x = self.conv2(x)
+ return x
+
+
+class IFBlock(nn.Module):
+ def __init__(self, in_planes, c=64, arch_ver="4.0"):
+ super(IFBlock, self).__init__()
+ self.arch_ver = arch_ver
+ self.conv0 = nn.Sequential(
+ conv(in_planes, c // 2, 3, 2, 1, arch_ver=arch_ver),
+ conv(c // 2, c, 3, 2, 1, arch_ver=arch_ver),
+ )
+ self.arch_ver = arch_ver
+
+ if arch_ver in ["4.0", "4.2", "4.3"]:
+ self.convblock = nn.Sequential(
+ conv(c, c, arch_ver=arch_ver),
+ conv(c, c, arch_ver=arch_ver),
+ conv(c, c, arch_ver=arch_ver),
+ conv(c, c, arch_ver=arch_ver),
+ conv(c, c, arch_ver=arch_ver),
+ conv(c, c, arch_ver=arch_ver),
+ conv(c, c, arch_ver=arch_ver),
+ conv(c, c, arch_ver=arch_ver),
+ )
+ self.lastconv = nn.ConvTranspose2d(c, 5, 4, 2, 1)
+
+ if arch_ver in ["4.5", "4.6", "4.7", "4.10"]:
+ self.convblock = nn.Sequential(
+ ResConv(c),
+ ResConv(c),
+ ResConv(c),
+ ResConv(c),
+ ResConv(c),
+ ResConv(c),
+ ResConv(c),
+ ResConv(c),
+ )
+ if arch_ver == "4.5":
+ self.lastconv = nn.Sequential(
+ nn.ConvTranspose2d(c, 4 * 5, 4, 2, 1), nn.PixelShuffle(2)
+ )
+ if arch_ver in ["4.6", "4.7", "4.10"]:
+ self.lastconv = nn.Sequential(
+ nn.ConvTranspose2d(c, 4 * 6, 4, 2, 1), nn.PixelShuffle(2)
+ )
+
+ def forward(self, x, flow=None, scale=1):
+ x = F.interpolate(
+ x, scale_factor=1.0 / scale, mode="bilinear", align_corners=False
+ )
+ if flow is not None:
+ flow = (
+ F.interpolate(
+ flow, scale_factor=1.0 / scale, mode="bilinear", align_corners=False
+ )
+ * 1.0
+ / scale
+ )
+ x = torch.cat((x, flow), 1)
+ feat = self.conv0(x)
+ if self.arch_ver == "4.0":
+ feat = self.convblock(feat) + feat
+ if self.arch_ver in ["4.2", "4.3", "4.5", "4.6", "4.7", "4.10"]:
+ feat = self.convblock(feat)
+
+ tmp = self.lastconv(feat)
+ if self.arch_ver in ["4.0", "4.2", "4.3"]:
+ tmp = F.interpolate(
+ tmp, scale_factor=scale * 2, mode="bilinear", align_corners=False
+ )
+ flow = tmp[:, :4] * scale * 2
+ if self.arch_ver in ["4.5", "4.6", "4.7", "4.10"]:
+ tmp = F.interpolate(
+ tmp, scale_factor=scale, mode="bilinear", align_corners=False
+ )
+ flow = tmp[:, :4] * scale
+ mask = tmp[:, 4:5]
+ return flow, mask
+
+
+class Contextnet(nn.Module):
+ def __init__(self, arch_ver="4.0"):
+ super(Contextnet, self).__init__()
+ c = 16
+ self.conv1 = Conv2(3, c, arch_ver=arch_ver)
+ self.conv2 = Conv2(c, 2 * c, arch_ver=arch_ver)
+ self.conv3 = Conv2(2 * c, 4 * c, arch_ver=arch_ver)
+ self.conv4 = Conv2(4 * c, 8 * c, arch_ver=arch_ver)
+
+ def forward(self, x, flow):
+ x = self.conv1(x)
+ flow = (
+ F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False)
+ * 0.5
+ )
+ f1 = warp(x, flow)
+ x = self.conv2(x)
+ flow = (
+ F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False)
+ * 0.5
+ )
+ f2 = warp(x, flow)
+ x = self.conv3(x)
+ flow = (
+ F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False)
+ * 0.5
+ )
+ f3 = warp(x, flow)
+ x = self.conv4(x)
+ flow = (
+ F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False)
+ * 0.5
+ )
+ f4 = warp(x, flow)
+ return [f1, f2, f3, f4]
+
+
+class Unet(nn.Module):
+ def __init__(self, arch_ver="4.0"):
+ super(Unet, self).__init__()
+ c = 16
+ self.down0 = Conv2(17, 2 * c, arch_ver=arch_ver)
+ self.down1 = Conv2(4 * c, 4 * c, arch_ver=arch_ver)
+ self.down2 = Conv2(8 * c, 8 * c, arch_ver=arch_ver)
+ self.down3 = Conv2(16 * c, 16 * c, arch_ver=arch_ver)
+ self.up0 = deconv(32 * c, 8 * c, arch_ver=arch_ver)
+ self.up1 = deconv(16 * c, 4 * c, arch_ver=arch_ver)
+ self.up2 = deconv(8 * c, 2 * c, arch_ver=arch_ver)
+ self.up3 = deconv(4 * c, c, arch_ver=arch_ver)
+ self.conv = nn.Conv2d(c, 3, 3, 1, 1)
+
+ def forward(self, img0, img1, warped_img0, warped_img1, mask, flow, c0, c1):
+ s0 = self.down0(
+ torch.cat((img0, img1, warped_img0, warped_img1, mask, flow), 1)
+ )
+ s1 = self.down1(torch.cat((s0, c0[0], c1[0]), 1))
+ s2 = self.down2(torch.cat((s1, c0[1], c1[1]), 1))
+ s3 = self.down3(torch.cat((s2, c0[2], c1[2]), 1))
+ x = self.up0(torch.cat((s3, c0[3], c1[3]), 1))
+ x = self.up1(torch.cat((x, s2), 1))
+ x = self.up2(torch.cat((x, s1), 1))
+ x = self.up3(torch.cat((x, s0), 1))
+ x = self.conv(x)
+ return torch.sigmoid(x)
+
+
+"""
+currently supports 4.0-4.12
+
+4.0: 4.0, 4.1
+4.2: 4.2
+4.3: 4.3, 4.4
+4.5: 4.5
+4.6: 4.6
+4.7: 4.7, 4.8, 4.9
+4.10: 4.10 4.11 4.12
+"""
+
+
+class IFNet(nn.Module):
+ def __init__(self, arch_ver="4.0"):
+ super(IFNet, self).__init__()
+ self.arch_ver = arch_ver
+ if arch_ver in ["4.0", "4.2", "4.3", "4.5", "4.6"]:
+ self.block0 = IFBlock(7, c=192, arch_ver=arch_ver)
+ self.block1 = IFBlock(8 + 4, c=128, arch_ver=arch_ver)
+ self.block2 = IFBlock(8 + 4, c=96, arch_ver=arch_ver)
+ self.block3 = IFBlock(8 + 4, c=64, arch_ver=arch_ver)
+ if arch_ver in ["4.7"]:
+ self.block0 = IFBlock(7 + 8, c=192, arch_ver=arch_ver)
+ self.block1 = IFBlock(8 + 4 + 8, c=128, arch_ver=arch_ver)
+ self.block2 = IFBlock(8 + 4 + 8, c=96, arch_ver=arch_ver)
+ self.block3 = IFBlock(8 + 4 + 8, c=64, arch_ver=arch_ver)
+ self.encode = nn.Sequential(
+ nn.Conv2d(3, 16, 3, 2, 1), nn.ConvTranspose2d(16, 4, 4, 2, 1)
+ )
+ if arch_ver in ["4.10"]:
+ self.block0 = IFBlock(7 + 16, c=192)
+ self.block1 = IFBlock(8 + 4 + 16, c=128)
+ self.block2 = IFBlock(8 + 4 + 16, c=96)
+ self.block3 = IFBlock(8 + 4 + 16, c=64)
+ self.encode = nn.Sequential(
+ nn.Conv2d(3, 32, 3, 2, 1),
+ nn.LeakyReLU(0.2, True),
+ nn.Conv2d(32, 32, 3, 1, 1),
+ nn.LeakyReLU(0.2, True),
+ nn.Conv2d(32, 32, 3, 1, 1),
+ nn.LeakyReLU(0.2, True),
+ nn.ConvTranspose2d(32, 8, 4, 2, 1),
+ )
+
+ if arch_ver in ["4.0", "4.2", "4.3"]:
+ self.contextnet = Contextnet(arch_ver=arch_ver)
+ self.unet = Unet(arch_ver=arch_ver)
+ self.arch_ver = arch_ver
+
+ def forward(
+ self,
+ img0,
+ img1,
+ timestep=0.5,
+ scale_list=[8, 4, 2, 1],
+ training=True,
+ fastmode=True,
+ ensemble=False,
+ return_flow=False,
+ ):
+ img0 = torch.clamp(img0, 0, 1)
+ img1 = torch.clamp(img1, 0, 1)
+
+ n, c, h, w = img0.shape
+ ph = ((h - 1) // 64 + 1) * 64
+ pw = ((w - 1) // 64 + 1) * 64
+ padding = (0, pw - w, 0, ph - h)
+ img0 = F.pad(img0, padding)
+ img1 = F.pad(img1, padding)
+ x = torch.cat((img0, img1), 1)
+
+ if training == False:
+ channel = x.shape[1] // 2
+ img0 = x[:, :channel]
+ img1 = x[:, channel:]
+ if not torch.is_tensor(timestep):
+ timestep = (x[:, :1].clone() * 0 + 1) * timestep
+ else:
+ timestep = timestep.repeat(1, 1, img0.shape[2], img0.shape[3])
+
+ flow_list = []
+ merged = []
+ mask_list = []
+
+ if self.arch_ver in ["4.7", "4.10"]:
+ f0 = self.encode(img0[:, :3])
+ f1 = self.encode(img1[:, :3])
+
+ warped_img0 = img0
+ warped_img1 = img1
+ flow = None
+ mask = None
+ block = [self.block0, self.block1, self.block2, self.block3]
+
+ for i in range(4):
+ if flow is None:
+ # 4.0-4.6
+ if self.arch_ver in ["4.0", "4.2", "4.3", "4.5", "4.6"]:
+ flow, mask = block[i](
+ torch.cat((img0[:, :3], img1[:, :3], timestep), 1),
+ None,
+ scale=scale_list[i],
+ )
+ if ensemble:
+ f1, m1 = block[i](
+ torch.cat((img1[:, :3], img0[:, :3], 1 - timestep), 1),
+ None,
+ scale=scale_list[i],
+ )
+ flow = (flow + torch.cat((f1[:, 2:4], f1[:, :2]), 1)) / 2
+ mask = (mask + (-m1)) / 2
+
+ # 4.7+
+ if self.arch_ver in ["4.7", "4.10"]:
+ flow, mask = block[i](
+ torch.cat((img0[:, :3], img1[:, :3], f0, f1, timestep), 1),
+ None,
+ scale=scale_list[i],
+ )
+
+ if ensemble:
+ f_, m_ = block[i](
+ torch.cat(
+ (img1[:, :3], img0[:, :3], f1, f0, 1 - timestep), 1
+ ),
+ None,
+ scale=scale_list[i],
+ )
+ flow = (flow + torch.cat((f_[:, 2:4], f_[:, :2]), 1)) / 2
+ mask = (mask + (-m_)) / 2
+
+ else:
+ # 4.0-4.6
+ if self.arch_ver in ["4.0", "4.2", "4.3", "4.5", "4.6"]:
+ f0, m0 = block[i](
+ torch.cat(
+ (warped_img0[:, :3], warped_img1[:, :3], timestep, mask), 1
+ ),
+ flow,
+ scale=scale_list[i],
+ )
+
+ if self.arch_ver in ["4.0"]:
+ if (
+ i == 1
+ and f0[:, :2].abs().max() > 32
+ and f0[:, 2:4].abs().max() > 32
+ and not training
+ ):
+ for k in range(4):
+ scale_list[k] *= 2
+ flow, mask = block[0](
+ torch.cat((img0[:, :3], img1[:, :3], timestep), 1),
+ None,
+ scale=scale_list[0],
+ )
+ warped_img0 = warp(img0, flow[:, :2])
+ warped_img1 = warp(img1, flow[:, 2:4])
+ f0, m0 = block[i](
+ torch.cat(
+ (
+ warped_img0[:, :3],
+ warped_img1[:, :3],
+ timestep,
+ mask,
+ ),
+ 1,
+ ),
+ flow,
+ scale=scale_list[i],
+ )
+
+ # 4.7+
+ if self.arch_ver in ["4.7", "4.10"]:
+ fd, m0 = block[i](
+ torch.cat(
+ (
+ warped_img0[:, :3],
+ warped_img1[:, :3],
+ warp(f0, flow[:, :2]),
+ warp(f1, flow[:, 2:4]),
+ timestep,
+ mask,
+ ),
+ 1,
+ ),
+ flow,
+ scale=scale_list[i],
+ )
+ flow = flow + fd
+
+ # 4.0-4.6 ensemble
+ if ensemble and self.arch_ver in [
+ "4.0",
+ "4.2",
+ "4.3",
+ "4.5",
+ "4.6",
+ ]:
+ f1, m1 = block[i](
+ torch.cat(
+ (
+ warped_img1[:, :3],
+ warped_img0[:, :3],
+ 1 - timestep,
+ -mask,
+ ),
+ 1,
+ ),
+ torch.cat((flow[:, 2:4], flow[:, :2]), 1),
+ scale=scale_list[i],
+ )
+ f0 = (f0 + torch.cat((f1[:, 2:4], f1[:, :2]), 1)) / 2
+ m0 = (m0 + (-m1)) / 2
+
+ # 4.7+ ensemble
+ if ensemble and self.arch_ver in ["4.7", "4.10"]:
+ wf0 = warp(f0, flow[:, :2])
+ wf1 = warp(f1, flow[:, 2:4])
+
+ f_, m_ = block[i](
+ torch.cat(
+ (
+ warped_img1[:, :3],
+ warped_img0[:, :3],
+ wf1,
+ wf0,
+ 1 - timestep,
+ -mask,
+ ),
+ 1,
+ ),
+ torch.cat((flow[:, 2:4], flow[:, :2]), 1),
+ scale=scale_list[i],
+ )
+ fd = (fd + torch.cat((f_[:, 2:4], f_[:, :2]), 1)) / 2
+ mask = (m0 + (-m_)) / 2
+
+ if self.arch_ver in ["4.0", "4.2", "4.3", "4.5", "4.6"]:
+ flow = flow + f0
+ mask = mask + m0
+
+ if not ensemble and self.arch_ver in ["4.7", "4.10"]:
+ mask = m0
+
+ mask_list.append(mask)
+ flow_list.append(flow)
+ warped_img0 = warp(img0, flow[:, :2])
+ warped_img1 = warp(img1, flow[:, 2:4])
+ merged.append((warped_img0, warped_img1))
+
+ if self.arch_ver in ["4.0", "4.1", "4.2", "4.3", "4.4", "4.5", "4.6"]:
+ mask_list[3] = torch.sigmoid(mask_list[3])
+ merged[3] = merged[3][0] * mask_list[3] + merged[3][1] * (1 - mask_list[3])
+
+ if self.arch_ver in ["4.7", "4.10"]:
+ mask = torch.sigmoid(mask)
+ merged[3] = warped_img0 * mask + warped_img1 * (1 - mask)
+
+ if not fastmode and self.arch_ver in ["4.0", "4.2", "4.3"]:
+ c0 = self.contextnet(img0, flow[:, :2])
+ c1 = self.contextnet(img1, flow[:, 2:4])
+ tmp = self.unet(img0, img1, warped_img0, warped_img1, mask, flow, c0, c1)
+ res = tmp[:, :3] * 2 - 1
+ merged[3] = torch.clamp(merged[3] + res, 0, 1)
+ return merged[3][:, :, :h, :w]
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/scanner.py b/comfyui_fill-nodes/nodes/scanner.py
new file mode 100644
index 0000000000000000000000000000000000000000..28e1415f0cb027270d5957d481645cde002de9b7
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/scanner.py
@@ -0,0 +1,589 @@
+import os
+import sys
+import json
+import inspect
+import importlib.util
+import time
+from pathlib import Path
+
+class NodeScanner:
+ def __init__(self, comfy_path):
+ self.comfy_path = os.path.abspath(comfy_path)
+ if self.comfy_path not in sys.path:
+ sys.path.append(self.comfy_path)
+
+ # Get the directory containing this script
+ self.base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+ # Set up cache directory paths
+ self.cache_dir = os.path.join(self.base_dir, 'web', 'nodes')
+ self.cache_file = os.path.join(self.cache_dir, 'node_definitions.txt')
+
+ print(f"\nScanner initialized with:")
+ print(f"Base directory: {self.base_dir}")
+ print(f"Cache directory: {self.cache_dir}")
+ print(f"Cache file: {self.cache_file}")
+
+ self.ensure_cache_dir()
+
+ def ensure_cache_dir(self):
+ try:
+ # First ensure the web directory exists
+ web_dir = os.path.join(self.base_dir, 'web')
+ if not os.path.exists(web_dir):
+ os.makedirs(web_dir)
+ print(f"Created web directory: {web_dir}")
+
+ # Then create the nodes directory
+ if not os.path.exists(self.cache_dir):
+ os.makedirs(self.cache_dir)
+ print(f"Created cache directory: {self.cache_dir}")
+
+ # Test if we can write to the cache directory
+ test_file = os.path.join(self.cache_dir, 'test_write.tmp')
+ with open(test_file, 'w') as f:
+ f.write('test')
+ os.remove(test_file)
+ print(f"Cache directory is writable: {self.cache_dir}")
+
+ return True
+ except Exception as e:
+ print(f"ERROR: Failed to create directory structure:")
+ print(f" - {str(e)}")
+ print(f" - Base dir exists: {os.path.exists(self.base_dir)}")
+ print(f" - Web dir exists: {os.path.exists(web_dir if 'web_dir' in locals() else 'N/A')}")
+ print(f" - Cache dir exists: {os.path.exists(self.cache_dir)}")
+ print(f" - Have write permission: {os.access(self.base_dir, os.W_OK)}")
+ print(f" - Current working directory: {os.getcwd()}")
+ return False
+
+ def scan_nodes(self):
+ if not os.path.exists(self.comfy_path):
+ print(f"ERROR: ComfyUI path does not exist: {self.comfy_path}")
+ return {}
+
+ try:
+ nodes = {}
+ total_found = 0
+ custom_nodes_path = os.path.join(self.comfy_path, 'custom_nodes')
+
+ if not os.path.exists(custom_nodes_path):
+ print(f"ERROR: Custom nodes directory not found: {custom_nodes_path}")
+ return {}
+
+ print(f"\nScanning custom nodes in: {custom_nodes_path}")
+
+ for root, dirs, files in os.walk(custom_nodes_path):
+ # Skip scanning ourselves and unwanted directories
+ if 'scanner.py' in files:
+ files.remove('scanner.py')
+ dirs[:] = [d for d in dirs if d not in {'__pycache__', '.git', 'web'}]
+
+ for file in files:
+ if file.endswith('.py'):
+ try:
+ found_nodes = self.extract_node_info(os.path.join(root, file))
+ if found_nodes:
+ nodes.update(found_nodes)
+ total_found += len(found_nodes)
+ print(f"Found {len(found_nodes)} nodes in {file}")
+ except Exception as e:
+ if not str(e).startswith("No module named"):
+ print(f"Error processing {file}: {str(e)}")
+
+ print(f"\nScan complete. Found {total_found} nodes.")
+ if nodes and self.ensure_cache_dir():
+ self.cache_definitions(nodes)
+ return nodes
+
+ except Exception as e:
+ print(f"ERROR during scanning: {str(e)}")
+ return {}
+
+ def extract_node_info(self, file_path):
+ """Extract node information by reading the file as text"""
+ try:
+ with open(file_path, 'r', encoding='utf-8') as f:
+ content = f.read()
+
+ # Extract basic node info without importing
+ nodes = {}
+
+ # Look for NODE_CLASS_MAPPINGS
+ if 'NODE_CLASS_MAPPINGS' in content:
+ # Find class definitions
+ class_blocks = content.split('class ')[1:]
+
+ for block in class_blocks:
+ try:
+ # Get class name
+ class_name = block.split('(')[0].strip()
+
+ # Extract category if exists
+ category = 'Unknown'
+ if 'CATEGORY' in block:
+ category_line = [l for l in block.split('\n') if 'CATEGORY' in l]
+ if category_line:
+ category = category_line[0].split('=')[1].strip().strip('"\'')
+
+ # Extract docstring if exists
+ description = None
+ if '"""' in block or "'''" in block:
+ doc_start = block.find('"""') if '"""' in block else block.find("'''")
+ if doc_start > -1:
+ doc_end = block.find('"""', doc_start + 3) if '"""' in block else block.find("'''", doc_start + 3)
+ if doc_end > -1:
+ description = block[doc_start+3:doc_end].strip()
+
+ nodes[class_name] = {
+ 'name': class_name,
+ 'category': category,
+ 'description': description,
+ 'inputs': self.extract_input_types_from_text(block),
+ 'outputs': self.extract_output_types_from_text(block)
+ }
+ except Exception as e:
+ print(f"Error parsing class in {os.path.basename(file_path)}: {str(e)}")
+ continue
+
+ return nodes
+
+ except Exception as e:
+ print(f"Error reading {os.path.basename(file_path)}: {str(e)}")
+ return None
+
+ def get_input_types(self, node_class):
+ """Extract input types from node class"""
+ try:
+ if hasattr(node_class, 'INPUT_TYPES'):
+ if inspect.ismethod(node_class.INPUT_TYPES):
+ input_types = node_class.INPUT_TYPES()
+ else:
+ input_types = node_class.INPUT_TYPES
+ return input_types
+ except Exception as e:
+ print(f"ERROR getting input types: {str(e)}")
+ return {}
+
+ def extract_input_types_from_text(self, class_text):
+ """Extract input types from class text with improved parsing"""
+ inputs = {'required': {}, 'optional': {}}
+
+ if 'INPUT_TYPES' in class_text:
+ try:
+ # Find the INPUT_TYPES block
+ input_block = ""
+ start = class_text.find('INPUT_TYPES')
+ block_start = class_text.find('{', start)
+
+ if block_start > -1:
+ # Count braces to find matching end
+ brace_count = 1
+ pos = block_start + 1
+
+ while brace_count > 0 and pos < len(class_text):
+ if class_text[pos] == '{':
+ brace_count += 1
+ elif class_text[pos] == '}':
+ brace_count -= 1
+ pos += 1
+
+ input_block = class_text[block_start:pos]
+
+ # Parse required inputs
+ if '"required"' in input_block or "'required'" in input_block:
+ req_section = self._extract_section(input_block, 'required')
+ inputs['required'] = self._parse_input_section(req_section)
+
+ # Parse optional inputs
+ if '"optional"' in input_block or "'optional'" in input_block:
+ opt_section = self._extract_section(input_block, 'optional')
+ inputs['optional'] = self._parse_input_section(opt_section)
+
+ except Exception as e:
+ print(f"Error parsing INPUT_TYPES: {str(e)}")
+
+ return inputs
+
+ def _extract_section(self, text, section_name):
+ """Helper to extract a section (required/optional) from INPUT_TYPES text"""
+ try:
+ start = text.find(f'"{section_name}"')
+ if start == -1:
+ start = text.find(f"'{section_name}'")
+
+ if start > -1:
+ start = text.find('{', start)
+ if start > -1:
+ brace_count = 1
+ pos = start + 1
+
+ while brace_count > 0 and pos < len(text):
+ if text[pos] == '{':
+ brace_count += 1
+ elif text[pos] == '}':
+ brace_count -= 1
+ pos += 1
+
+ return text[start:pos]
+ except Exception as e:
+ print(f"Error extracting section {section_name}: {str(e)}")
+ return ""
+
+ def _parse_input_section(self, section_text):
+ """Helper to parse individual input definitions"""
+ inputs = {}
+
+ try:
+ # Split into lines and clean up
+ lines = section_text.split('\n')
+ for line in lines:
+ line = line.strip()
+ if ':' in line and ('(' in line or '[' in line or '"' in line or "'" in line):
+ # Extract name
+ name = line.split(':')[0].strip().strip('"\'')
+
+ # Extract type info
+ type_info = []
+
+ # Look for common patterns
+ if '(' in line: # Tuple/list definitions
+ start = line.find('(')
+ end = line.find(')', start)
+ if end > start:
+ types = line[start+1:end].split(',')
+ type_info = [t.strip().strip('"\'') for t in types if t.strip()]
+
+ elif '[' in line: # List definitions
+ start = line.find('[')
+ end = line.find(']', start)
+ if end > start:
+ types = line[start+1:end].split(',')
+ type_info = [t.strip().strip('"\'') for t in types if t.strip()]
+
+ elif '"' in line or "'" in line: # Simple string definitions
+ parts = line.split(':')[1].split(',')[0].strip()
+ if parts:
+ type_info = [parts.strip().strip('"\'')]
+
+ if name and type_info:
+ inputs[name] = type_info
+
+ except Exception as e:
+ print(f"Error parsing input section: {str(e)}")
+
+ return inputs
+
+ def extract_output_types_from_text(self, class_text):
+ """Extract output types from class text"""
+ outputs = {
+ 'return_types': (),
+ 'return_names': None
+ }
+
+ try:
+ # Find RETURN_TYPES
+ if 'RETURN_TYPES' in class_text:
+ start = class_text.find('RETURN_TYPES')
+ end = class_text.find('\n', start)
+ if end > start:
+ types_text = class_text[start:end]
+ if '=' in types_text:
+ types_str = types_text.split('=')[1].strip().strip('()')
+ outputs['return_types'] = tuple(t.strip().strip('"\'') for t in types_str.split(',') if t.strip())
+
+ # Find RETURN_NAMES
+ if 'RETURN_NAMES' in class_text:
+ start = class_text.find('RETURN_NAMES')
+ end = class_text.find('\n', start)
+ if end > start:
+ names_text = class_text[start:end]
+ if '=' in names_text:
+ names_str = names_text.split('=')[1].strip().strip('()')
+ outputs['return_names'] = tuple(n.strip().strip('"\'') for n in names_str.split(',') if n.strip())
+
+ except Exception as e:
+ print(f"Error parsing output types: {str(e)}")
+
+ return outputs
+
+ def cache_definitions(self, definitions):
+ if not definitions:
+ print("No definitions to cache - skipping cache write")
+ return False
+
+ print(f"\nWriting cache file to: {self.cache_file}")
+ try:
+ # Ensure parent directories exist
+ os.makedirs(os.path.dirname(self.cache_file), exist_ok=True)
+
+ # Convert to text format
+ content = []
+ for node_name, info in definitions.items():
+ # Node header
+ content.append(f"Node: {node_name}")
+ content.append(f"Category: {info['category']}")
+ if info.get('description'):
+ content.append(f"Description: {info['description']}")
+
+ # Inputs
+ content.append("Inputs:")
+ if 'required' in info['inputs']:
+ content.append(" Required:")
+ for name, types in info['inputs']['required'].items():
+ content.append(f" - {name}: {', '.join(types)}")
+ if 'optional' in info['inputs']:
+ content.append(" Optional:")
+ for name, types in info['inputs']['optional'].items():
+ content.append(f" - {name}: {', '.join(types)}")
+
+ # Outputs
+ content.append("Outputs:")
+ return_types = info['outputs']['return_types']
+ return_names = info['outputs']['return_names']
+ if return_names:
+ for t, n in zip(return_types, return_names):
+ content.append(f" - {n} ({t})")
+ else:
+ for t in return_types:
+ content.append(f" - {t}")
+
+ content.append("-" * 50) # Separator between nodes
+
+ # Write to temporary file first
+ temp_file = self.cache_file + '.tmp'
+ with open(temp_file, 'w', encoding='utf-8') as f:
+ f.write('\n'.join(content))
+ f.flush()
+ os.fsync(f.fileno())
+
+ print(f"Temp file written: {temp_file}")
+ print(f"Temp file exists: {os.path.exists(temp_file)}")
+ print(f"Temp file size: {os.path.getsize(temp_file) if os.path.exists(temp_file) else 0}")
+
+ # Safely move the temp file to final location
+ if os.path.exists(self.cache_file):
+ backup_file = self.cache_file + '.bak'
+ if os.path.exists(backup_file):
+ os.remove(backup_file)
+ os.rename(self.cache_file, backup_file)
+ print(f"Created backup file: {backup_file}")
+
+ # Move temp file to final location
+ os.rename(temp_file, self.cache_file)
+
+ # Verify the file was created
+ if not os.path.exists(self.cache_file):
+ raise Exception(f"File was not created at {self.cache_file}")
+
+ # Try to open and read the file to verify it's accessible
+ try:
+ with open(self.cache_file, 'r', encoding='utf-8') as f:
+ test_content = f.read(100) # Read first 100 chars as a test
+ print(f"File is readable. First 100 chars: {test_content[:100]}")
+ except Exception as e:
+ print(f"WARNING: File created but couldn't be read: {str(e)}")
+
+ # Check server path
+ comfy_dir = os.path.dirname(os.path.dirname(os.path.dirname(self.base_dir)))
+ print(f"ComfyUI root directory: {comfy_dir}")
+
+ # Generate the URL path that browsers would use
+ relative_path = os.path.relpath(self.cache_file, comfy_dir)
+ url_path = '/' + relative_path.replace('\\', '/')
+ print(f"Relative web path for browser access: {url_path}")
+
+ size = os.path.getsize(self.cache_file)
+ print(f"Cache written successfully ({size:,} bytes)")
+ print(f"Cache file absolute path: {os.path.abspath(self.cache_file)}")
+ return True
+
+ except Exception as e:
+ print(f"ERROR: Failed to write cache: {str(e)}")
+ # Print more diagnostic information
+ print(f" - Temp file exists: {os.path.exists(temp_file if 'temp_file' in locals() else 'N/A')}")
+ print(f" - Cache dir exists: {os.path.exists(os.path.dirname(self.cache_file))}")
+ print(f" - Current working directory: {os.getcwd()}")
+ print(f" - Permission to write: {os.access(os.path.dirname(self.cache_file), os.W_OK)}")
+
+ if 'temp_file' in locals() and os.path.exists(temp_file):
+ try:
+ os.remove(temp_file)
+ except:
+ pass
+ return False
+
+ def node_to_compact_format(self, node_name, info):
+ """Convert node info to compact format"""
+ lines = []
+
+ # Node name and category
+ lines.append(f"#N {node_name} #C {info['category']}")
+
+ # Inputs
+ input_parts = []
+ if 'required' in info['inputs']:
+ for name, types in info['inputs']['required'].items():
+ input_parts.append(f"{name}:{','.join(types)}")
+ if 'optional' in info['inputs']:
+ for name, types in info['inputs']['optional'].items():
+ input_parts.append(f"{name}:{','.join(types)}?")
+ if input_parts:
+ lines.append(f"#I {' '.join(input_parts)}")
+
+ # Outputs
+ if info['outputs']['return_types']:
+ out_types = ','.join(info['outputs']['return_types'])
+ if info['outputs']['return_names']:
+ out_names = ','.join(info['outputs']['return_names'])
+ lines.append(f"#O {out_types} #N {out_names}")
+ else:
+ lines.append(f"#O {out_types}")
+
+ # Description
+ if info.get('description'):
+ lines.append(f"#D {info['description']}")
+
+ lines.append("---")
+ return '\n'.join(lines)
+
+ def parse_compact_format(self, content):
+ """Parse compact format back into node definitions"""
+ definitions = {}
+ current_node = None
+ current_info = {}
+
+ for line in content.split('\n'):
+ line = line.strip()
+ if not line or line == '---':
+ if current_node:
+ definitions[current_node] = current_info
+ current_node = None
+ current_info = {}
+ continue
+
+ parts = line.split()
+ if line.startswith('#N') and '#C' in line:
+ # Node name and category
+ name_idx = line.index('#C')
+ current_node = ' '.join(parts[1:name_idx]).strip()
+ current_info['category'] = ' '.join(parts[name_idx+1:]).strip()
+ current_info['inputs'] = {'required': {}, 'optional': {}}
+ current_info['outputs'] = {'return_types': (), 'return_names': None}
+
+ elif line.startswith('#I'):
+ # Inputs
+ for input_def in ' '.join(parts[1:]).split():
+ name, type_info = input_def.split(':')
+ if type_info.endswith('?'):
+ # Optional input
+ type_info = type_info[:-1]
+ current_info['inputs']['optional'][name] = type_info.split(',')
+ else:
+ # Required input
+ current_info['inputs']['required'][name] = type_info.split(',')
+
+ elif line.startswith('#O'):
+ # Outputs
+ if '#N' in line:
+ # Has named outputs
+ type_idx = line.index('#N')
+ types = ' '.join(parts[1:type_idx]).strip().split(',')
+ names = ' '.join(parts[type_idx+1:]).strip().split(',')
+ current_info['outputs']['return_types'] = tuple(types)
+ current_info['outputs']['return_names'] = tuple(names)
+ else:
+ # Just types
+ current_info['outputs']['return_types'] = tuple(parts[1].split(','))
+
+ elif line.startswith('#D'):
+ # Description
+ current_info['description'] = ' '.join(parts[1:])
+
+ return definitions
+
+ def load_cache(self):
+ """Load cached node definitions from compact format"""
+ try:
+ if os.path.exists(self.cache_file):
+ with open(self.cache_file, 'r') as f:
+ return json.load(f)
+ except Exception as e:
+ print(f"Error loading cache: {str(e)}")
+ return None
+
+ def is_cache_valid(self, max_age_hours=24):
+ """Check if cache is valid based on age"""
+ cache_data = self.load_cache()
+ if not cache_data:
+ return False
+
+ cache_age = time.time() - cache_data['timestamp']
+ return cache_age < (max_age_hours * 3600)
+
+ def get_nodes_for_llm(self):
+ """Get node definitions in LLM-friendly format"""
+ cache_data = self.load_cache()
+ if not cache_data:
+ return "No node definitions available."
+
+ llm_text = "Available Custom Nodes:\n\n"
+ for name, info in cache_data['definitions'].items():
+ llm_text += f"Node: {name}\n"
+ if info['description']:
+ llm_text += f"Description: {info['description']}\n"
+ llm_text += f"Category: {info['category']}\n"
+
+ # Inputs
+ llm_text += "Inputs:\n"
+ if 'required' in info['inputs']:
+ for input_name, input_info in info['inputs']['required'].items():
+ llm_text += f" - {input_name} ({input_info[0]})\n"
+ if 'optional' in info['inputs']:
+ for input_name, input_info in info['inputs']['optional'].items():
+ llm_text += f" - {input_name} ({input_info[0]}) [Optional]\n"
+
+ # Outputs
+ llm_text += "Outputs:\n"
+ return_types = info['outputs']['return_types']
+ return_names = info['outputs']['return_names']
+ if return_names:
+ for i, (t, n) in enumerate(zip(return_types, return_names)):
+ llm_text += f" - {n} ({t})\n"
+ else:
+ for t in return_types:
+ llm_text += f" - {t}\n"
+
+ llm_text += "\n"
+
+ return llm_text
+
+
+if __name__ == "__main__":
+ try:
+ # Get ComfyUI path from command line or use default parent directory
+ default_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
+ comfy_path = sys.argv[1] if len(sys.argv) > 1 else default_path
+
+ print(f"\n=== NodeScanner CLI ===")
+ print(f"├── ComfyUI path: {comfy_path}")
+
+ scanner = NodeScanner(comfy_path)
+ print("├── Starting node scan...")
+
+ results = scanner.scan_nodes()
+
+ if results:
+ print(f"└── Found {len(results)} nodes")
+ print("\nNode Summary:")
+ for node_name, info in results.items():
+ print(f"├── Node: {node_name}")
+ print(f"│ ├── Category: {info['category']}")
+ if info.get('description'):
+ print(f"│ └── Description: {info['description']}")
+ else:
+ print("└── No nodes were found or errors occurred during scanning")
+
+ except Exception as e:
+ print(f"\nERROR: Script failed with error: {str(e)}")
+ sys.exit(1)
\ No newline at end of file
diff --git a/comfyui_fill-nodes/nodes/sup.py b/comfyui_fill-nodes/nodes/sup.py
new file mode 100644
index 0000000000000000000000000000000000000000..246ffa39cef9452837b450a13a45dfb11d9a16ee
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/sup.py
@@ -0,0 +1,28 @@
+
+from pathlib import Path
+
+### GLOBALS
+
+ROOT = Path(__file__).absolute().parent.parent
+ROOT_COMFY = ROOT.parent.parent
+ROOT_FONTS = ROOT / "fonts"
+
+### SUPPORT CLASSES
+
+class AlwaysEqualProxy(str):
+ def __eq__(self, other):
+ return True
+ def __ne__(self, other):
+ return False
+
+### SUPPORT FUNCTIONS
+
+def parse_dynamic(data:dict, key:str) -> list:
+ vals = []
+ count = 1
+ while data.get((who := f"{key}_{count}"), None) is not None:
+ vals.append(who)
+ count += 1
+ if len(vals) == 0:
+ vals.append([])
+ return vals
diff --git a/comfyui_fill-nodes/nodes/utils.py b/comfyui_fill-nodes/nodes/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ccc4195fe57311e8d49822cb70bc9b3b59b8fa09
--- /dev/null
+++ b/comfyui_fill-nodes/nodes/utils.py
@@ -0,0 +1,460 @@
+import numpy as np
+from PIL import Image, ImageFilter
+import torch
+import torch.nn.functional as F
+from torchvision.transforms import GaussianBlur
+import math
+
+if (not hasattr(Image, 'Resampling')): # For older versions of Pillow
+ Image.Resampling = Image
+
+BLUR_KERNEL_SIZE = 15
+
+
+def tensor_to_pil(img_tensor, batch_index=0):
+ # Takes an image in a batch in the form of a tensor of shape [batch_size, channels, height, width]
+ # and returns an PIL Image with the corresponding mode deduced by the number of channels
+
+ # Take the image in the batch given by batch_index
+ img_tensor = img_tensor[batch_index].unsqueeze(0)
+ i = 255. * img_tensor.cpu().numpy()
+ img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8).squeeze())
+ return img
+
+
+def pil_to_tensor(image):
+ # Takes a PIL image and returns a tensor of shape [1, height, width, channels]
+ image = np.array(image).astype(np.float32) / 255.0
+ image = torch.from_numpy(image).unsqueeze(0)
+ if len(image.shape) == 3: # If the image is grayscale, add a channel dimension
+ image = image.unsqueeze(-1)
+ return image
+
+
+def controlnet_hint_to_pil(tensor, batch_index=0):
+ return tensor_to_pil(tensor.movedim(1, -1), batch_index)
+
+
+def pil_to_controlnet_hint(img):
+ return pil_to_tensor(img).movedim(-1, 1)
+
+
+def crop_tensor(tensor, region):
+ # Takes a tensor of shape [batch_size, height, width, channels] and crops it to the given region
+ x1, y1, x2, y2 = region
+ return tensor[:, y1:y2, x1:x2, :]
+
+
+def resize_tensor(tensor, size, mode="nearest-exact"):
+ # Takes a tensor of shape [B, C, H, W] and resizes
+ # it to a shape of [B, C, size[0], size[1]] using the given mode
+ return torch.nn.functional.interpolate(tensor, size=size, mode=mode)
+
+
+def get_crop_region(mask, pad=0):
+ # Takes a black and white PIL image in 'L' mode and returns the coordinates of the white rectangular mask region
+ # Should be equivalent to the get_crop_region function from https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/master/modules/masking.py
+ coordinates = mask.getbbox()
+ if coordinates is not None:
+ x1, y1, x2, y2 = coordinates
+ else:
+ x1, y1, x2, y2 = mask.width, mask.height, 0, 0
+ # Apply padding
+ x1 = max(x1 - pad, 0)
+ y1 = max(y1 - pad, 0)
+ x2 = min(x2 + pad, mask.width)
+ y2 = min(y2 + pad, mask.height)
+ return fix_crop_region((x1, y1, x2, y2), (mask.width, mask.height))
+
+
+def fix_crop_region(region, image_size):
+ # Remove the extra pixel added by the get_crop_region function
+ image_width, image_height = image_size
+ x1, y1, x2, y2 = region
+ if x2 < image_width:
+ x2 -= 1
+ if y2 < image_height:
+ y2 -= 1
+ return x1, y1, x2, y2
+
+
+def expand_crop(region, width, height, target_width, target_height):
+ '''
+ Expands a crop region to a specified target size.
+ :param region: A tuple of the form (x1, y1, x2, y2) denoting the upper left and the lower right points
+ of the rectangular region. Expected to have x2 > x1 and y2 > y1.
+ :param width: The width of the image the crop region is from.
+ :param height: The height of the image the crop region is from.
+ :param target_width: The desired width of the crop region.
+ :param target_height: The desired height of the crop region.
+ '''
+ x1, y1, x2, y2 = region
+ actual_width = x2 - x1
+ actual_height = y2 - y1
+ # target_width = math.ceil(actual_width / 8) * 8
+ # target_height = math.ceil(actual_height / 8) * 8
+
+ # Try to expand region to the right of half the difference
+ width_diff = target_width - actual_width
+ x2 = min(x2 + width_diff // 2, width)
+ # Expand region to the left of the difference including the pixels that could not be expanded to the right
+ width_diff = target_width - (x2 - x1)
+ x1 = max(x1 - width_diff, 0)
+ # Try the right again
+ width_diff = target_width - (x2 - x1)
+ x2 = min(x2 + width_diff, width)
+
+ # Try to expand region to the bottom of half the difference
+ height_diff = target_height - actual_height
+ y2 = min(y2 + height_diff // 2, height)
+ # Expand region to the top of the difference including the pixels that could not be expanded to the bottom
+ height_diff = target_height - (y2 - y1)
+ y1 = max(y1 - height_diff, 0)
+ # Try the bottom again
+ height_diff = target_height - (y2 - y1)
+ y2 = min(y2 + height_diff, height)
+
+ return (x1, y1, x2, y2), (target_width, target_height)
+
+
+def resize_region(region, init_size, resize_size):
+ # Resize a crop so that it fits an image that was resized to the given width and height
+ x1, y1, x2, y2 = region
+ init_width, init_height = init_size
+ resize_width, resize_height = resize_size
+ x1 = math.floor(x1 * resize_width / init_width)
+ x2 = math.ceil(x2 * resize_width / init_width)
+ y1 = math.floor(y1 * resize_height / init_height)
+ y2 = math.ceil(y2 * resize_height / init_height)
+ return (x1, y1, x2, y2)
+
+
+def pad_image(image, left_pad, right_pad, top_pad, bottom_pad, fill=False, blur=False):
+ '''
+ Pads an image with the given number of pixels on each side and fills the padding with data from the edges.
+ :param image: A PIL image
+ :param left_pad: The number of pixels to pad on the left side
+ :param right_pad: The number of pixels to pad on the right side
+ :param top_pad: The number of pixels to pad on the top side
+ :param bottom_pad: The number of pixels to pad on the bottom side
+ :param blur: Whether to blur the padded edges
+ :return: A PIL image with size (image.width + left_pad + right_pad, image.height + top_pad + bottom_pad)
+ '''
+ left_edge = image.crop((0, 1, 1, image.height - 1))
+ right_edge = image.crop((image.width - 1, 1, image.width, image.height - 1))
+ top_edge = image.crop((1, 0, image.width - 1, 1))
+ bottom_edge = image.crop((1, image.height - 1, image.width - 1, image.height))
+ new_width = image.width + left_pad + right_pad
+ new_height = image.height + top_pad + bottom_pad
+ padded_image = Image.new(image.mode, (new_width, new_height))
+ padded_image.paste(image, (left_pad, top_pad))
+ if fill:
+ for i in range(left_pad):
+ edge = left_edge.resize(
+ (1, new_height - i * (top_pad + bottom_pad) // left_pad), resample=Image.Resampling.NEAREST)
+ padded_image.paste(edge, (i, i * top_pad // left_pad))
+ for i in range(right_pad):
+ edge = right_edge.resize(
+ (1, new_height - i * (top_pad + bottom_pad) // right_pad), resample=Image.Resampling.NEAREST)
+ padded_image.paste(edge, (new_width - 1 - i, i * top_pad // right_pad))
+ for i in range(top_pad):
+ edge = top_edge.resize(
+ (new_width - i * (left_pad + right_pad) // top_pad, 1), resample=Image.Resampling.NEAREST)
+ padded_image.paste(edge, (i * left_pad // top_pad, i))
+ for i in range(bottom_pad):
+ edge = bottom_edge.resize(
+ (new_width - i * (left_pad + right_pad) // bottom_pad, 1), resample=Image.Resampling.NEAREST)
+ padded_image.paste(edge, (i * left_pad // bottom_pad, new_height - 1 - i))
+ if blur and not (left_pad == right_pad == top_pad == bottom_pad == 0):
+ padded_image = padded_image.filter(ImageFilter.GaussianBlur(BLUR_KERNEL_SIZE))
+ padded_image.paste(image, (left_pad, top_pad))
+ return padded_image
+
+
+def pad_image2(image, left_pad, right_pad, top_pad, bottom_pad, fill=False, blur=False):
+ '''
+ Pads an image with the given number of pixels on each side and fills the padding with data from the edges.
+ Faster than pad_image, but only pads with edge data in straight lines.
+ :param image: A PIL image
+ :param left_pad: The number of pixels to pad on the left side
+ :param right_pad: The number of pixels to pad on the right side
+ :param top_pad: The number of pixels to pad on the top side
+ :param bottom_pad: The number of pixels to pad on the bottom side
+ :param blur: Whether to blur the padded edges
+ :return: A PIL image with size (image.width + left_pad + right_pad, image.height + top_pad + bottom_pad)
+ '''
+ left_edge = image.crop((0, 1, 1, image.height - 1))
+ right_edge = image.crop((image.width - 1, 1, image.width, image.height - 1))
+ top_edge = image.crop((1, 0, image.width - 1, 1))
+ bottom_edge = image.crop((1, image.height - 1, image.width - 1, image.height))
+ new_width = image.width + left_pad + right_pad
+ new_height = image.height + top_pad + bottom_pad
+ padded_image = Image.new(image.mode, (new_width, new_height))
+ padded_image.paste(image, (left_pad, top_pad))
+ if fill:
+ if left_pad > 0:
+ padded_image.paste(left_edge.resize((left_pad, new_height), resample=Image.Resampling.NEAREST), (0, 0))
+ if right_pad > 0:
+ padded_image.paste(right_edge.resize((right_pad, new_height),
+ resample=Image.Resampling.NEAREST), (new_width - right_pad, 0))
+ if top_pad > 0:
+ padded_image.paste(top_edge.resize((new_width, top_pad), resample=Image.Resampling.NEAREST), (0, 0))
+ if bottom_pad > 0:
+ padded_image.paste(bottom_edge.resize((new_width, bottom_pad),
+ resample=Image.Resampling.NEAREST), (0, new_height - bottom_pad))
+ if blur and not (left_pad == right_pad == top_pad == bottom_pad == 0):
+ padded_image = padded_image.filter(ImageFilter.GaussianBlur(BLUR_KERNEL_SIZE))
+ padded_image.paste(image, (left_pad, top_pad))
+ return padded_image
+
+
+def pad_tensor(tensor, left_pad, right_pad, top_pad, bottom_pad, fill=False, blur=False):
+ '''
+ Pads an image tensor with the given number of pixels on each side and fills the padding with data from the edges.
+ :param tensor: A tensor of shape [B, H, W, C]
+ :param left_pad: The number of pixels to pad on the left side
+ :param right_pad: The number of pixels to pad on the right side
+ :param top_pad: The number of pixels to pad on the top side
+ :param bottom_pad: The number of pixels to pad on the bottom side
+ :param blur: Whether to blur the padded edges
+ :return: A tensor of shape [B, H + top_pad + bottom_pad, W + left_pad + right_pad, C]
+ '''
+ batch_size, channels, height, width = tensor.shape
+ h_pad = left_pad + right_pad
+ v_pad = top_pad + bottom_pad
+ new_width = width + h_pad
+ new_height = height + v_pad
+
+ # Create empty image
+ padded = torch.zeros((batch_size, channels, new_height, new_width), dtype=tensor.dtype)
+
+ # Copy the original image into the centor of the padded tensor
+ padded[:, :, top_pad:top_pad + height, left_pad:left_pad + width] = tensor
+
+ # Duplicate the edges of the original image into the padding
+ if top_pad > 0:
+ padded[:, :, :top_pad, :] = padded[:, :, top_pad:top_pad + 1, :] # Top edge
+ if bottom_pad > 0:
+ padded[:, :, -bottom_pad:, :] = padded[:, :, -bottom_pad - 1:-bottom_pad, :] # Bottom edge
+ if left_pad > 0:
+ padded[:, :, :, :left_pad] = padded[:, :, :, left_pad:left_pad + 1] # Left edge
+ if right_pad > 0:
+ padded[:, :, :, -right_pad:] = padded[:, :, :, -right_pad - 1:-right_pad] # Right edge
+
+ return padded
+
+
+def resize_and_pad_image(image, width, height, fill=False, blur=False):
+ '''
+ Resizes an image to the given width and height and pads it to the given width and height.
+ :param image: A PIL image
+ :param width: The width of the resized image
+ :param height: The height of the resized image
+ :param fill: Whether to fill the padding with data from the edges
+ :param blur: Whether to blur the padded edges
+ :return: A PIL image of size (width, height)
+ '''
+ width_ratio = width / image.width
+ height_ratio = height / image.height
+ if height_ratio > width_ratio:
+ resize_ratio = width_ratio
+ else:
+ resize_ratio = height_ratio
+ resize_width = round(image.width * resize_ratio)
+ resize_height = round(image.height * resize_ratio)
+ resized = image.resize((resize_width, resize_height), resample=Image.Resampling.LANCZOS)
+ # Pad the sides of the image to get the image to the desired size that wasn't covered by the resize
+ horizontal_pad = (width - resize_width) // 2
+ vertical_pad = (height - resize_height) // 2
+ result = pad_image2(resized, horizontal_pad, horizontal_pad, vertical_pad, vertical_pad, fill, blur)
+ result = result.resize((width, height), resample=Image.Resampling.LANCZOS)
+ return result, (horizontal_pad, vertical_pad)
+
+
+def resize_and_pad_tensor(tensor, width, height, fill=False, blur=False):
+ '''
+ Resizes an image tensor to the given width and height and pads it to the given width and height.
+ :param tensor: A tensor of shape [B, H, W, C]
+ :param width: The width of the resized image
+ :param height: The height of the resized image
+ :param fill: Whether to fill the padding with data from the edges
+ :param blur: Whether to blur the padded edges
+ :return: A tensor of shape [B, height, width, C]
+ '''
+ # Resize the image to the closest size that maintains the aspect ratio
+ width_ratio = width / tensor.shape[3]
+ height_ratio = height / tensor.shape[2]
+ if height_ratio > width_ratio:
+ resize_ratio = width_ratio
+ else:
+ resize_ratio = height_ratio
+ resize_width = round(tensor.shape[3] * resize_ratio)
+ resize_height = round(tensor.shape[2] * resize_ratio)
+ resized = F.interpolate(tensor, size=(resize_height, resize_width), mode='nearest-exact')
+ # Pad the sides of the image to get the image to the desired size that wasn't covered by the resize
+ horizontal_pad = (width - resize_width) // 2
+ vertical_pad = (height - resize_height) // 2
+ result = pad_tensor(resized, horizontal_pad, horizontal_pad, vertical_pad, vertical_pad, fill, blur)
+ result = F.interpolate(result, size=(height, width), mode='nearest-exact')
+ return result
+
+
+def crop_controlnet(cond_dict, region, init_size, canvas_size, tile_size, w_pad, h_pad):
+ if "control" not in cond_dict:
+ return
+ c = cond_dict["control"]
+ controlnet = c.copy()
+ cond_dict["control"] = controlnet
+ while c is not None:
+ # hint is shape (B, C, H, W)
+ hint = controlnet.cond_hint_original
+ resized_crop = resize_region(region, canvas_size, hint.shape[:-3:-1])
+ hint = crop_tensor(hint.movedim(1, -1), resized_crop).movedim(-1, 1)
+ hint = resize_tensor(hint, tile_size[::-1])
+ controlnet.cond_hint_original = hint
+ c = c.previous_controlnet
+ controlnet.set_previous_controlnet(c.copy() if c is not None else None)
+ controlnet = controlnet.previous_controlnet
+
+
+def region_intersection(region1, region2):
+ """
+ Returns the coordinates of the intersection of two rectangular regions.
+ :param region1: A tuple of the form (x1, y1, x2, y2) denoting the upper left and the lower right points
+ of the first rectangular region. Expected to have x2 > x1 and y2 > y1.
+ :param region2: The second rectangular region with the same format as the first.
+ :return: A tuple of the form (x1, y1, x2, y2) denoting the rectangular intersection.
+ None if there is no intersection.
+ """
+ x1, y1, x2, y2 = region1
+ x1_, y1_, x2_, y2_ = region2
+ x1 = max(x1, x1_)
+ y1 = max(y1, y1_)
+ x2 = min(x2, x2_)
+ y2 = min(y2, y2_)
+ if x1 >= x2 or y1 >= y2:
+ return None
+ return (x1, y1, x2, y2)
+
+
+def crop_gligen(cond_dict, region, init_size, canvas_size, tile_size, w_pad, h_pad):
+ if "gligen" not in cond_dict:
+ return
+ type, model, cond = cond_dict["gligen"]
+ if type != "position":
+ from warnings import warn
+ warn(f"Unknown gligen type {type}")
+ return
+ cropped = []
+ for c in cond:
+ emb, h, w, y, x = c
+ # Get the coordinates of the box in the upscaled image
+ x1 = x * 8
+ y1 = y * 8
+ x2 = x1 + w * 8
+ y2 = y1 + h * 8
+ gligen_upscaled_box = resize_region((x1, y1, x2, y2), init_size, canvas_size)
+
+ # Calculate the intersection of the gligen box and the region
+ intersection = region_intersection(gligen_upscaled_box, region)
+ if intersection is None:
+ continue
+ x1, y1, x2, y2 = intersection
+
+ # Offset the gligen box so that the origin is at the top left of the tile region
+ x1 -= region[0]
+ y1 -= region[1]
+ x2 -= region[0]
+ y2 -= region[1]
+
+ # Add the padding
+ x1 += w_pad
+ y1 += h_pad
+ x2 += w_pad
+ y2 += h_pad
+
+ # Set the new position params
+ h = (y2 - y1) // 8
+ w = (x2 - x1) // 8
+ x = x1 // 8
+ y = y1 // 8
+ cropped.append((emb, h, w, y, x))
+
+ cond_dict["gligen"] = (type, model, cropped)
+
+
+def crop_area(cond_dict, region, init_size, canvas_size, tile_size, w_pad, h_pad):
+ if "area" not in cond_dict:
+ return
+
+ # Resize the area conditioning to the canvas size and confine it to the tile region
+ h, w, y, x = cond_dict["area"]
+ w, h, x, y = 8 * w, 8 * h, 8 * x, 8 * y
+ x1, y1, x2, y2 = resize_region((x, y, x + w, y + h), init_size, canvas_size)
+ intersection = region_intersection((x1, y1, x2, y2), region)
+ if intersection is None:
+ del cond_dict["area"]
+ del cond_dict["strength"]
+ return
+ x1, y1, x2, y2 = intersection
+
+ # Offset origin to the top left of the tile
+ x1 -= region[0]
+ y1 -= region[1]
+ x2 -= region[0]
+ y2 -= region[1]
+
+ # Add the padding
+ x1 += w_pad
+ y1 += h_pad
+ x2 += w_pad
+ y2 += h_pad
+
+ # Set the params for tile
+ w, h = (x2 - x1) // 8, (y2 - y1) // 8
+ x, y = x1 // 8, y1 // 8
+
+ cond_dict["area"] = (h, w, y, x)
+
+
+def crop_mask(cond_dict, region, init_size, canvas_size, tile_size, w_pad, h_pad):
+ if "mask" not in cond_dict:
+ return
+ mask_tensor = cond_dict["mask"] # (B, H, W)
+ masks = []
+ for i in range(mask_tensor.shape[0]):
+ # Convert to PIL image
+ mask = tensor_to_pil(mask_tensor, i) # W x H
+
+ # Resize the mask to the canvas size
+ mask = mask.resize(canvas_size, Image.Resampling.BICUBIC)
+
+ # Crop the mask to the region
+ mask = mask.crop(region)
+
+ # Add padding
+ mask, _ = resize_and_pad_image(mask, tile_size[0], tile_size[1], fill=True)
+
+ # Resize the mask to the tile size
+ if tile_size != mask.size:
+ mask = mask.resize(tile_size, Image.Resampling.BICUBIC)
+
+ # Convert back to tensor
+ mask = pil_to_tensor(mask) # (1, H, W, 1)
+ mask = mask.squeeze(-1) # (1, H, W)
+ masks.append(mask)
+
+ cond_dict["mask"] = torch.cat(masks, dim=0) # (B, H, W)
+
+
+def crop_cond(cond, region, init_size, canvas_size, tile_size, w_pad=0, h_pad=0):
+ cropped = []
+ for emb, x in cond:
+ cond_dict = x.copy()
+ n = [emb, cond_dict]
+ crop_controlnet(cond_dict, region, init_size, canvas_size, tile_size, w_pad, h_pad)
+ crop_gligen(cond_dict, region, init_size, canvas_size, tile_size, w_pad, h_pad)
+ crop_area(cond_dict, region, init_size, canvas_size, tile_size, w_pad, h_pad)
+ crop_mask(cond_dict, region, init_size, canvas_size, tile_size, w_pad, h_pad)
+ cropped.append(n)
+ return cropped
diff --git a/comfyui_fill-nodes/pyproject.toml b/comfyui_fill-nodes/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..4ea6152a81af5a120234bf7fd3d86b4fdf93f83b
--- /dev/null
+++ b/comfyui_fill-nodes/pyproject.toml
@@ -0,0 +1,15 @@
+[project]
+name = "comfyui_fill-nodes"
+description = "Fill-Nodes is a versatile collection of custom nodes for ComfyUI that extends functionality across multiple domains. Features include advanced image processing (pixelation, slicing, masking), visual effects generation (glitch, halftone, pixel art), comprehensive file handling (PDF creation/extraction, Google Drive integration), AI model interfaces (GPT, DALL-E, Hugging Face), utility nodes for workflow enhancement, and specialized tools for video processing, captioning, and batch operations. The pack provides both practical workflow solutions and creative tools within a unified node collection."
+version = "2.6.0"
+license = "LICENSE"
+dependencies = ["librosa", "sounddevice", "glitch_this", "PyOpenGL", "glfw", "scipy>=1.13.1", "requests", "aiohttp", "moviepy", "matplotlib", "reportlab", "openai", "PyPDF2", "pdf2image", "PyMuPDF", "reportlab", "PyPDF2", "ollama", "kornia", "opencv-python", "gdown", "open_clip_torch", "google-genai"]
+
+[project.urls]
+Repository = "https://github.com/filliptm/ComfyUI_Fill-Nodes"
+# Used by Comfy Registry https://comfyregistry.org
+
+[tool.comfy]
+PublisherId = "machinedelusions"
+DisplayName = "ComfyUI_Fill-Nodes"
+Icon = "https://avatars.githubusercontent.com/u/55672949"
diff --git a/comfyui_fill-nodes/requirements.txt b/comfyui_fill-nodes/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..ed3ae4fe21dc9b7aba781a99958908ab5f0bf8d8
--- /dev/null
+++ b/comfyui_fill-nodes/requirements.txt
@@ -0,0 +1,28 @@
+librosa
+sounddevice
+glitch_this
+PyOpenGL
+glfw
+scipy >=1.13.1
+requests
+aiohttp
+moviepy==1.0.3
+matplotlib
+reportlab
+openai
+PyPDF2
+pdf2image
+PyMuPDF
+reportlab
+PyPDF2
+ollama
+kornia
+opencv-python
+gdown
+open_clip_torch
+google-genai
+google-cloud-storage
+fal-client
+runwayml
+httpx
+huggingface_hub