Compare commits

...
14 Commits
Author SHA1 Message Date
Dr.Lt.Data 8f04714145 fixed: inversed_switch - If the select is pointing to an out-of-range output, remove the input connection instead of the output.
https://github.com/ltdrdata/ComfyUI-Impact-Pack/issues/851#issuecomment-2543353847
2024-12-19 23:29:34 +09:00
Dr.Lt.Data a311f9278d fixed: sam detector - invalid position
https://github.com/ltdrdata/ComfyUI-Impact-Pack/issues/853
2024-12-19 23:06:49 +09:00
Dr.Lt.Data 0ec21f1a4b version marker 2024-12-19 22:03:11 +09:00
Andrés Zsögön 40a3df3acd Added Mask Rect Area and Mask Rect Area (Advanced) nodes (#861)
Added nodes for simple rectangular masks of arbitrary size and position with built-in preview canvas. Closes issue #856.
2024-12-19 22:02:40 +09:00
Dr.Lt.Data 9ba92862c4 update README.md 2024-12-17 11:03:02 +09:00
Dr.Lt.Data 2c2e148205 update README.md 2024-12-17 10:58:17 +09:00
Dr.Lt.Data ff9c30787c Robustly remove legacy subpack directories. 2024-12-11 23:24:00 +09:00
Dr.Lt.Data 64f709741a The Impact Subpack must now be installed separately. 2024-12-11 21:56:33 +09:00
Dr.Lt.Data 455e993354 Merge branch 'Main' into refactor/subpack 2024-12-11 21:54:51 +09:00
Dr.Lt.Data ce23d436fc improve: switch - disconnect output connection instead of input connection if select_on_prompt 2024-12-11 05:25:01 +09:00
Dr.Lt.Data 5f630466fb fixed: block if empty slot is selected and select_on_prompt
https://github.com/ltdrdata/ComfyUI-Impact-Pack/issues/846
2024-12-11 03:36:12 +09:00
Dr.Lt.Data 66bf101341 Merge branch 'Main' into refactor/subpack 2024-11-02 05:39:28 +09:00
Dr.Lt.Data 5c0535942a Merge branch 'Main' into refactor/subpack 2024-11-01 02:31:49 +09:00
Dr.Lt.Data 6be257254e Separate Impact Pack and Impact Subpack 2024-11-01 02:25:14 +09:00
12 changed files with 954 additions and 314 deletions
+17 -62
View File
@@ -2,11 +2,13 @@
# ComfyUI-Impact-Pack
**Custom nodes pack for ComfyUI**
This custom node helps to conveniently enhance images through Detector, Detailer, Upscaler, Pipe, and more.
**Custom node pack for ComfyUI**
This node pack helps to conveniently enhance images through Detector, Detailer, Upscaler, Pipe, and more.
NOTE: The UltralyticsDetectorProvider node is not part of the ComfyUI-Impact-Pack. To use the UltralyticsDetectorProvider node, please install the ComfyUI-Impact-Subpack separately.
## NOTICE
* V8.0: The `Impact Subpack` is no longer installed automatically. To use `UltralyticsDetectorProvider` nodes, please install the `Impact Subpack` separately.
* V7.6: Automatic installation is no longer supported. Please install using ComfyUI-Manager, or manually install requirements.txt and run install.py to complete the installation.
* V7.0: Supports Switch based on Execution Model Inversion.
* V6.0: Supports FLUX.1 model in Impact KSampler, Detailers, PreviewBridgeLatent
@@ -33,9 +35,6 @@ This custom node helps to conveniently enhance images through Detector, Detailer
## Custom Nodes
### [Detector nodes](https://github.com/ltdrdata/ComfyUI-extension-tutorials/blob/Main/ComfyUI-Impact-Pack/tutorial/detectors.md)
* `SAMLoader` - Loads the SAM model.
* `UltralyticsDetectorProvider` - Loads the Ultralystics model to provide SEGM_DETECTOR, BBOX_DETECTOR.
- Unlike `MMDetDetectorProvider`, for segm models, `BBOX_DETECTOR` is also provided.
- The various models available in UltralyticsDetectorProvider can be downloaded through **ComfyUI-Manager**.
* `ONNXDetectorProvider` - Loads the ONNX model to provide BBOX_DETECTOR.
* `CLIPSegDetectorProvider` - Wrapper for CLIPSeg to provide BBOX_DETECTOR.
* You need to install the ComfyUI-CLIPSeg node extension.
@@ -69,6 +68,8 @@ This custom node helps to conveniently enhance images through Detector, Detailer
* `Dilate Mask` - Dilate Mask.
* Support erosion for negative value.
* `Gaussian Blur Mask` - Apply Gaussian Blur to Mask. You can utilize this for mask feathering.
* `Mask Rect Area` - Create a rectangular mask defined by percentages with preview canvas.
* `Mask Rect Area (Advanced)` - Create a rectangular mask defined by pixels and image size.
### [Detailer nodes](https://github.com/ltdrdata/ComfyUI-extension-tutorials/blob/Main/ComfyUI-Impact-Pack/tutorial/detailers.md)
* `Detailer (SEGS)` - Refines the image based on SEGS.
@@ -274,6 +275,7 @@ This custom node helps to conveniently enhance images through Detector, Detailer
* For supported labels, please refer to the `config.json` of the respective HuggingFace repository.
* `#Female` and `#Male` are symbols that group multiple labels such as `Female, women, woman, ...`, for convenience, rather than being single labels.
### Etc nodes
* `Impact Scheduler Adapter` - With the addition of AYS to the scheduler of the Impact Pack and Inspire Pack, there is an issue of incompatibility when the existing scheduler widget is converted to input. The Impact Scheduler Adapter allows for an indirect connection to be possible.
* `StringListToString` - Convert String List to String
@@ -289,66 +291,25 @@ This custom node helps to conveniently enhance images through Detector, Detailer
* `List Bridge` - When passing the list output through this node, it collects and organizes the data before forwarding it, which ensures that the previous stage's sub-workflow has been completed.
## MMDet nodes (DEPRECATED) - Don't use these nodes
* MMDetDetectorProvider - Loads the MMDet model to provide BBOX_DETECTOR and SEGM_DETECTOR.
* To use the existing MMDetDetectorProvider, you need to enable the MMDet usage configuration.
## Feature
* `Interactive SAM Detector (Clipspace)` - When you right-click on a node that has 'MASK' and 'IMAGE' outputs, a context menu will open. From this menu, you can either open a dialog to create a SAM Mask using 'Open in SAM Detector', or copy the content (likely mask data) using 'Copy (Clipspace)' and generate a mask using 'Impact SAM Detector' from the clipspace menu, and then paste it using 'Paste (Clipspace)'.
* Providing a feature to detect errors that occur when mixing models and clips from checkpoints such as `SDXL Base`, `SDXL Refiner`, `SD1.x`, `SD2.x` during sample execution, and reporting appropriate errors.
## Deprecated
* The following nodes have been kept only for compatibility with existing workflows, and are no longer supported. Please replace them with new nodes.
* ONNX Detector (SEGS) - BBOX Detector (SEGS)
* MMDetLoader -> MMDetDetectorProvider
* SegsMaskCombine -> SEGS to MASK (combined)
* BboxDetectorForEach -> BBOX Detector (SEGS)
* SegmDetectorForEach -> SEGM Detector (SEGS)
* BboxDetectorCombined -> BBOX Detector (combined)
* SegmDetectorCombined -> SEGM Detector (combined)
* MaskPainter -> PreviewBridge
* To use the existing deprecated legacy nodes, you need to enable the MMDet usage configuration.
## Ultralytics models
* When using ultralytics models, save them separately in `models/ultralytics/bbox` and `models/ultralytics/segm` depending on the type of model. Many models can be downloaded by searching for `ultralytics` in the Model Manager of ComfyUI-Manager.
* huggingface.co/Bingsu/[adetailer](https://huggingface.co/Bingsu/adetailer/tree/main) - You can download face, people detection models, and clothing detection models.
* ultralytics/[assets](https://github.com/ultralytics/assets/releases/) - You can download various types of detection models other than faces or people.
* civitai/[adetailer](https://civitai.com/search/models?sortBy=models_v5&query=adetailer) - You can download various types detection models....Many models are associated with NSFW content.
## How to activate 'MMDet usage' (DEPRECATED)
* Upon the initial execution, an `impact-pack.ini` file will be generated in the custom_nodes/ComfyUI-Impact-Pack directory.
```
[default]
dependency_version = 2
mmdet_skip = True
```
* Change `mmdet_skip = True` to `mmdet_skip = False`
```
[default]
dependency_version = 2
mmdet_skip = False
```
* Restart ComfyUI
## Installation
## How To Install?
### Install via ComfyUI-Manager (Recommended)
* Search `ComfyUI Impact Pack` in ComfyUI-Manager and click `Install` button.
### Manual Install (Not Recommended)
1. `cd custom_nodes`
2. `git clone https://github.com/ltdrdata/ComfyUI-Impact-Pack.git`
2. `git clone https://github.com/ltdrdata/ComfyUI-Impact-Pack`
3. `cd ComfyUI-Impact-Pack`
4. (optional) `git clone https://github.com/ltdrdata/ComfyUI-Impact-Subpack impact_subpack`
* Impact Pack will automatically download subpack during its initial launch.
5. (optional) `python install-manual.py`
* Impact Pack will automatically install its dependencies during its initial launch.
* For the portable version, you should execute the command `..\..\..\python_embeded\python.exe install-manual.py` to run the installation script.
6. Restart ComfyUI
4. `pip install -r requirements.txt`
* **IMPORTANT**:
* You must install it within the Python environment where ComfyUI is running.
* For the portable version, use `<installed path>\python_embeded\python.exe -m pip` instead of `pip`. For a `venv`, activate the `venv` first and then use `pip`.
5. Restart ComfyUI
* NOTE1: If an error occurs during the installation process, please refer to [Troubleshooting Page](troubleshooting/TROUBLESHOOTING.md) for assistance.
* NOTE2: You can use this colab notebook [colab notebook](https://colab.research.google.com/github/ltdrdata/ComfyUI-Impact-Pack/blob/Main/notebook/comfyui_colab_impact_pack.ipynb) to launch it. This notebook automatically downloads the impact pack to the custom_nodes directory, installs the tested dependencies, and runs it.
@@ -359,11 +320,9 @@ mmdet_skip = False
* pip install
* segment-anything
* ultralytics
* scikit-image
* piexif
* opencv-python
* GitPython
* scipy
* numpy<2
* dill
@@ -372,9 +331,6 @@ mmdet_skip = False
* (deprecated) openmim # for mim
* (deprecated) pycocotools # for mim
* mim install (deprecated)
* mmcv==2.0.0, mmdet==3.0.0, mmengine==0.7.2
* linux packages (ubuntu)
* libgl1-mesa-glx
* libglib2.0-0
@@ -397,17 +353,16 @@ sam_editor_model = sam_vit_b_01ec64.pth
```
## Other Materials (auto-download on initial startup)
## Other Materials (auto-download when installing)
* ComfyUI/models/mmdets/bbox <= https://huggingface.co/dustysys/ddetailer/resolve/main/mmdet/bbox/mmdet_anime-face_yolov3.pth
* ComfyUI/models/mmdets/bbox <= https://raw.githubusercontent.com/Bing-su/dddetailer/master/config/mmdet_anime-face_yolov3.py
* ComfyUI/models/sams <= https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth
## Troubleshooting page
* [Troubleshooting Page](troubleshooting/TROUBLESHOOTING.md)
## How to use (DDetailer feature)
## How To Use (DDetailer feature)
#### 1. Basic auto face detection and refine exapmle.
![simple](https://github.com/ltdrdata/ComfyUI-extension-tutorials/raw/Main/ComfyUI-Impact-Pack/images/simple.png)
+4 -19
View File
@@ -13,7 +13,6 @@ import traceback
comfy_path = os.path.dirname(folder_paths.__file__)
impact_path = os.path.join(os.path.dirname(__file__))
subpack_path = os.path.join(os.path.dirname(__file__), "impact_subpack")
modules_path = os.path.join(os.path.dirname(__file__), "modules")
sys.path.append(modules_path)
@@ -22,14 +21,9 @@ import impact.config
import impact.sample_error_enhancer
print(f"### Loading: ComfyUI-Impact-Pack ({impact.config.version})")
sys.path.append(subpack_path)
# Core
# recheck dependencies for colab
try:
import impact.subpack_nodes # This import must be done before cv2.
import folder_paths
import torch
import cv2
@@ -143,6 +137,8 @@ NODE_CLASS_MAPPINGS = {
"BitwiseAndMask": BitwiseAndMask,
"SubtractMask": SubtractMask,
"AddMask": AddMask,
"MaskRectArea": MaskRectArea,
"MaskRectAreaAdvanced": MaskRectAreaAdvanced,
"ImpactSegsAndMask": SegsBitwiseAndMask,
"ImpactSegsAndMaskForEach": SegsBitwiseAndMaskForEach,
"EmptySegs": EmptySEGS,
@@ -324,6 +320,8 @@ NODE_DISPLAY_NAME_MAPPINGS = {
"BitwiseAndMask": "Pixelwise(MASK & MASK)",
"SubtractMask": "Pixelwise(MASK - MASK)",
"AddMask": "Pixelwise(MASK + MASK)",
"MaskRectArea": "Mask Rect Area",
"MaskRectAreaAdvanced": "Mask Rect Area (Advanced)",
"ImpactFlattenMask": "Flatten Mask Batch",
"DetailerForEach": "Detailer (SEGS)",
"DetailerForEachPipe": "Detailer (SEGS/pipe)",
@@ -465,19 +463,6 @@ if not impact.config.get_config()['mmdet_skip']:
"SegmDetectorCombined": "SegmDetectorCombined (Legacy)",
})
try:
import impact.subpack_nodes
NODE_CLASS_MAPPINGS.update(impact.subpack_nodes.NODE_CLASS_MAPPINGS)
NODE_DISPLAY_NAME_MAPPINGS.update(impact.subpack_nodes.NODE_DISPLAY_NAME_MAPPINGS)
except Exception as e:
print("### ComfyUI-Impact-Pack: (IMPORT FAILED) Subpack\n")
print(" The module at the `custom_nodes/ComfyUI-Impact-Pack/impact_subpack` path appears to be incomplete.")
print(" Recommended to delete the path and restart ComfyUI.")
print(" If the issue persists, please report it to https://github.com/ltdrdata/ComfyUI-Impact-Pack/issues.")
print("\n---------------------------------")
traceback.print_exc()
print("---------------------------------\n")
# NOTE: Inject directly into EXTENSION_WEB_DIRS instead of WEB_DIRECTORY
# Provide the js path fixed as ComfyUI-Impact-Pack instead of the path name, making it available for external use
-183
View File
@@ -1,183 +0,0 @@
import functools
import os
import re
import shutil
import sys
import subprocess
import threading
import locale
import traceback
from typing import Set
if sys.argv[0] == 'install.py':
sys.path.append('.') # for portable version
impact_path = os.path.join(os.path.dirname(__file__), "modules")
subpack_path = os.path.join(os.path.dirname(__file__), "impact_subpack")
subpack_repo = "https://github.com/ltdrdata/ComfyUI-Impact-Subpack"
comfy_path = os.environ.get('COMFYUI_PATH')
if comfy_path is None:
print(f"\n[bold yellow]WARN: The `COMFYUI_PATH` environment variable is not set. Assuming `{os.path.dirname(__file__)}/../../` as the ComfyUI path.[/bold yellow]", file=sys.stderr)
comfy_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
model_path = os.environ.get('COMFYUI_MODEL_PATH')
if model_path is None:
try:
import folder_paths
model_path = folder_paths.models_dir
except:
pass
if model_path is None:
model_path = os.path.abspath(os.path.join(comfy_path, 'models'))
print(f"\n[bold yellow]WARN: The `COMFYUI_MODEL_PATH` environment variable is not set. Assuming `{model_path}` as the ComfyUI path.[/bold yellow]", file=sys.stderr)
sys.path.append(impact_path)
sys.path.append(comfy_path)
# ---
def handle_stream(stream, is_stdout):
stream.reconfigure(encoding=locale.getpreferredencoding(), errors='replace')
for msg in stream:
if is_stdout:
print(msg, end="", file=sys.stdout)
else:
print(msg, end="", file=sys.stderr)
def process_wrap(cmd_str, cwd=None, handler=None, env=None):
print(f"[Impact Pack] EXECUTE: {cmd_str} in '{cwd}'")
process = subprocess.Popen(cmd_str, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, text=True, bufsize=1)
if handler is None:
handler = handle_stream
stdout_thread = threading.Thread(target=handler, args=(process.stdout, True))
stderr_thread = threading.Thread(target=handler, args=(process.stderr, False))
stdout_thread.start()
stderr_thread.start()
stdout_thread.join()
stderr_thread.join()
return process.wait()
@functools.cache
def get_installed_packages() -> Set[str]:
try:
result = subprocess.check_output([sys.executable, '-m', 'pip', 'list'], universal_newlines=True)
pip_list = set([line.split()[0].lower() for line in result.split('\n') if line.strip()])
return pip_list
except subprocess.CalledProcessError as e:
raise Exception(f"[ComfyUI-Impact-Pack] Failed to retrieve the information of installed pip packages.")
def is_package_installed(name: str) -> bool:
name = name.strip()
pattern = r'([^<>!=]+)([<>!=]=?)'
match = re.search(pattern, name)
if match:
name = match.group(1)
result = name.lower() in get_installed_packages()
return result
def is_requirements_installed(file_path: str) -> bool:
print(f"Requirements file: {file_path}")
if os.path.exists(file_path):
with open(file_path, "r") as file:
lines = file.readlines()
for line in lines:
if not is_package_installed(line):
return False
pip_install = [sys.executable, "-m", "pip", "install", "-U"]
# ---
try:
import platform
import folder_paths
from torchvision.datasets.utils import download_url
import impact.config
print("### ComfyUI-Impact-Pack: Check dependencies")
def ensure_subpack():
import git
if os.path.exists(subpack_path):
try:
repo = git.Repo(subpack_path)
repo.remotes.origin.pull()
except:
traceback.print_exc()
if platform.system() == 'Windows':
print(f"[ComfyUI-Impact-Pack] Please turn off ComfyUI and remove '{subpack_path}' and restart ComfyUI.")
else:
shutil.rmtree(subpack_path)
git.Repo.clone_from(subpack_repo, subpack_path)
else:
git.Repo.clone_from(subpack_repo, subpack_path)
def install():
subpack_install_script = os.path.join(subpack_path, "install.py")
print(f"### ComfyUI-Impact-Pack: Updating subpack")
ensure_subpack() # The installation of the subpack must take place before ensure_pip. cv2 triggers a permission error.
new_env = os.environ.copy()
new_env["COMFYUI_PATH"] = comfy_path
new_env["COMFYUI_MODEL_PATH"] = model_path
if os.path.exists(subpack_install_script):
if not is_requirements_installed(os.path.join(subpack_path, 'requirements.txt')):
process_wrap(pip_install + ['-r', 'requirements.txt'], cwd=subpack_path)
process_wrap([sys.executable, 'install.py'], cwd=subpack_path, env=new_env)
else:
print(f"### ComfyUI-Impact-Pack: (Install Failed) Subpack\nFile not found: `{subpack_install_script}`")
# Download model
print("### ComfyUI-Impact-Pack: Check basic models")
sam_path = os.path.join(model_path, "sams")
onnx_path = os.path.join(model_path, "onnx")
if not os.path.exists(os.path.join(os.path.dirname(__file__), '..', 'skip_download_model')):
if not impact.config.get_config()['mmdet_skip']:
bbox_path = os.path.join(model_path, "mmdets", "bbox")
if not os.path.exists(bbox_path):
os.makedirs(bbox_path)
if not os.path.exists(os.path.join(bbox_path, "mmdet_anime-face_yolov3.pth")):
download_url("https://huggingface.co/dustysys/ddetailer/resolve/main/mmdet/bbox/mmdet_anime-face_yolov3.pth", bbox_path)
if not os.path.exists(os.path.join(bbox_path, "mmdet_anime-face_yolov3.py")):
download_url("https://raw.githubusercontent.com/Bing-su/dddetailer/master/config/mmdet_anime-face_yolov3.py", bbox_path)
if not os.path.exists(os.path.join(sam_path, "sam_vit_b_01ec64.pth")):
download_url("https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth", sam_path)
if not os.path.exists(onnx_path):
print(f"### ComfyUI-Impact-Pack: onnx model directory created ({onnx_path})")
os.mkdir(onnx_path)
impact.config.write_config()
install()
except Exception as e:
print("[ERROR] ComfyUI-Impact-Pack: Dependency installation has failed. Please install manually.")
traceback.print_exc()
+13 -31
View File
@@ -12,13 +12,11 @@ if sys.argv[0] == 'install.py':
impact_path = os.path.join(os.path.dirname(__file__), "modules")
subpack_path = os.path.join(os.path.dirname(__file__), "impact_subpack")
subpack_repo = "https://github.com/ltdrdata/ComfyUI-Impact-Subpack"
comfy_path = os.environ.get('COMFYUI_PATH')
if comfy_path is None:
print(f"\n[bold yellow]WARN: The `COMFYUI_PATH` environment variable is not set. Assuming `{os.path.dirname(__file__)}/../../` as the ComfyUI path.[/bold yellow]", file=sys.stderr)
print(f"\nWARN: The `COMFYUI_PATH` environment variable is not set. Assuming `{os.path.dirname(__file__)}/../../` as the ComfyUI path.", file=sys.stderr)
comfy_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
model_path = os.environ.get('COMFYUI_MODEL_PATH')
@@ -31,7 +29,7 @@ if model_path is None:
if model_path is None:
model_path = os.path.abspath(os.path.join(comfy_path, 'models'))
print(f"\n[bold yellow]WARN: The `COMFYUI_MODEL_PATH` environment variable is not set. Assuming `{model_path}` as the ComfyUI path.[/bold yellow]", file=sys.stderr)
print(f"\nWARN: The `COMFYUI_MODEL_PATH` environment variable is not set. Assuming `{model_path}` as the ComfyUI path.", file=sys.stderr)
sys.path.append(impact_path)
@@ -76,38 +74,11 @@ try:
import impact.config
print("### ComfyUI-Impact-Pack: Check dependencies")
def ensure_subpack():
import git
if os.path.exists(subpack_path):
try:
repo = git.Repo(subpack_path)
repo.remotes.origin.pull()
except:
traceback.print_exc()
if platform.system() == 'Windows':
print(f"[ComfyUI-Impact-Pack] Please turn off ComfyUI and remove '{subpack_path}' and restart ComfyUI.")
else:
shutil.rmtree(subpack_path)
git.Repo.clone_from(subpack_repo, subpack_path)
else:
git.Repo.clone_from(subpack_repo, subpack_path)
def install():
subpack_install_script = os.path.join(subpack_path, "install.py")
print(f"### ComfyUI-Impact-Pack: Updating subpack")
ensure_subpack() # The installation of the subpack must take place before ensure_pip. cv2 triggers a permission error.
new_env = os.environ.copy()
new_env["COMFYUI_PATH"] = comfy_path
new_env["COMFYUI_MODEL_PATH"] = model_path
if os.path.exists(subpack_install_script):
process_wrap([sys.executable, 'install.py'], cwd=subpack_path, env=new_env)
else:
print(f"### ComfyUI-Impact-Pack: (Install Failed) Subpack\nFile not found: `{subpack_install_script}`")
# Download model
print("### ComfyUI-Impact-Pack: Check basic models")
sam_path = os.path.join(model_path, "sams")
@@ -137,6 +108,17 @@ try:
impact.config.write_config()
# Remove legacy subpack
subpack_path = os.path.join(os.path.dirname(__file__), 'impact_subpack')
if os.path.exists(subpack_path):
shutil.rmtree(subpack_path)
print(f"Legacy subpack is detected. '{subpack_path}' is removed.")
subpack_path = os.path.join(os.path.dirname(__file__), 'subpack')
if os.path.exists(subpack_path):
shutil.rmtree(subpack_path)
print(f"Legacy subpack is detected. '{subpack_path}' is removed.")
install()
except Exception as e:
+9 -8
View File
@@ -262,7 +262,7 @@ class ImpactSamEditorDialog extends ComfyDialog {
const pointsCanvas = document.createElement('canvas');
imgCanvas.id = "imageCanvas";
maskCanvas.id = "maskCanvas";
maskCanvas.id = "samEditorMaskCanvas";
pointsCanvas.id = "pointsCanvas";
this.setlayout(imgCanvas, maskCanvas, pointsCanvas);
@@ -356,13 +356,13 @@ class ImpactSamEditorDialog extends ComfyDialog {
let w = (drawWidth * imgCanvas.clientWidth/imgCanvas.width) + "px";
let h = (drawHeight * imgCanvas.clientHeight/imgCanvas.height) + "px";
pointsCanvas.width = drawWidth;
pointsCanvas.height = drawHeight;
pointsCanvas.width = drawWidth * imgCanvas.clientWidth/imgCanvas.width;
pointsCanvas.height = drawHeight * imgCanvas.clientHeight/imgCanvas.height;
pointsCanvas.style.top = imgCanvas.offsetTop + "px";
pointsCanvas.style.left = imgCanvas.offsetLeft + "px";
maskCanvas.style.width = w;
maskCanvas.style.height = h;
maskCanvas.width = pointsCanvas.width;
maskCanvas.height = pointsCanvas.height;
maskCanvas.style.top = imgCanvas.offsetTop + "px";
maskCanvas.style.left = imgCanvas.offsetLeft + "px";
@@ -476,8 +476,9 @@ class ImpactSamEditorDialog extends ComfyDialog {
for(const i in self.prompt_points) {
const [is_positive, x, y] = self.prompt_points[i];
const point = [x,y];
if(is_positive)
if(is_positive) {
positive_points.push(point);
}
else
negative_points.push(point);
}
@@ -511,8 +512,8 @@ class ImpactSamEditorDialog extends ComfyDialog {
const x = event.offsetX || event.targetTouches[0].clientX - maskRect.left;
const y = event.offsetY || event.targetTouches[0].clientY - maskRect.top;
const originalX = x * self.image.width / self.pointsCanvas.width;
const originalY = y * self.image.height / self.pointsCanvas.height;
const originalX = x * self.image.width / self.pointsCanvas.clientWidth;
const originalY = y * self.image.height / self.pointsCanvas.clientHeight;
var point = null;
if (event.button == 0) {
+381
View File
@@ -0,0 +1,381 @@
import { app } from "/scripts/app.js";
function showPreviewCanvas(node, app) {
const widget = {
type: "customCanvas",
name: "mask-rect-area-canvas",
get value() {
return this.canvas.value;
},
set value(x) {
this.canvas.value = x;
},
draw: function (ctx, node, widgetWidth, widgetY) {
// If we are initially offscreen when created we wont have received a resize event
// Calculate it here instead
if (!node.canvasHeight) {
computeCanvasSize(node, node.size);
}
const visible = true;
const t = ctx.getTransform();
const margin = 12;
const border = 2;
const widgetHeight = node.canvasHeight;
const width = Math.round(node.properties["width"]);
const height = Math.round(node.properties["height"]);
const scale = Math.min((widgetWidth - margin * 3) / width, (widgetHeight - margin * 3) / height);
const blurRadius = node.properties["blur_radius"] || 0;
const index = 0;
Object.assign(this.canvas.style, {
left: `${t.e}px`,
top: `${t.f + (widgetY * t.d)}px`,
width: `${widgetWidth * t.a}px`,
height: `${widgetHeight * t.d}px`,
position: "absolute",
zIndex: 1,
fontSize: `${t.d * 10.0}px`,
pointerEvents: "none"
});
this.canvas.hidden = !visible;
let backgroundWidth = width * scale;
let backgroundHeight = height * scale;
let xOffset = margin;
if (backgroundWidth < widgetWidth) {
xOffset += (widgetWidth - backgroundWidth) / 2 - margin;
}
let yOffset = (margin / 2);
if (backgroundHeight < widgetHeight) {
yOffset += (widgetHeight - backgroundHeight) / 2 - margin;
}
let widgetX = xOffset;
widgetY = widgetY + yOffset;
// Draw the background border
ctx.fillStyle = globalThis.LiteGraph.WIDGET_OUTLINE_COLOR;
ctx.fillRect(widgetX - border, widgetY - border, backgroundWidth + border * 2, backgroundHeight + border * 2)
// Draw the main background area
ctx.fillStyle = globalThis.LiteGraph.WIDGET_BGCOLOR;
ctx.fillRect(widgetX, widgetY, backgroundWidth, backgroundHeight);
// Draw the conditioning zone
let [x, y, w, h] = getDrawArea(node, backgroundWidth, backgroundHeight);
ctx.fillStyle = getDrawColor(0, "80");
ctx.fillRect(widgetX + x, widgetY + y, w, h);
ctx.beginPath();
ctx.lineWidth = 1;
// Draw grid lines
for (let x = 0; x <= width / 64; x += 1) {
ctx.moveTo(widgetX + x * 64 * scale, widgetY);
ctx.lineTo(widgetX + x * 64 * scale, widgetY + backgroundHeight);
}
for (let y = 0; y <= height / 64; y += 1) {
ctx.moveTo(widgetX, widgetY + y * 64 * scale);
ctx.lineTo(widgetX + backgroundWidth, widgetY + y * 64 * scale);
}
ctx.strokeStyle = "#66666650";
ctx.stroke();
ctx.closePath();
// Draw current zone
let [sx, sy, sw, sh] = getDrawArea(node, backgroundWidth, backgroundHeight);
ctx.fillStyle = getDrawColor(0, "80");
ctx.fillRect(widgetX + sx, widgetY + sy, sw, sh);
ctx.fillStyle = getDrawColor(0, "40");
ctx.fillRect(widgetX + sx + border, widgetY + sy + border, sw - border * 2, sh - border * 2);
// Draw white border around the current zone
ctx.strokeStyle = globalThis.LiteGraph.NODE_SELECTED_TITLE_COLOR;
ctx.lineWidth = 2;
ctx.strokeRect(widgetX + sx, widgetY + sy, sw, sh);
// Display
ctx.beginPath();
ctx.arc(LiteGraph.NODE_SLOT_HEIGHT * 0.5, LiteGraph.NODE_SLOT_HEIGHT * (index + 0.5) + 4, 4, 0, Math.PI * 2);
ctx.fill();
ctx.lineWidth = 1;
ctx.strokeStyle = "white";
ctx.stroke();
ctx.lineWidth = 1;
ctx.closePath();
// Draw progress bar canvas
if (backgroundWidth < widgetWidth) {
xOffset += (widgetWidth - backgroundWidth) / 2 - margin;
}
// Ajustar las coordenadas X e Y
const barHeight = 8;
let widgetYBar = widgetY + backgroundHeight + margin;
// Dibujar el borde negro alrededor de la barra
ctx.fillStyle = globalThis.LiteGraph.WIDGET_OUTLINE_COLOR;
ctx.fillRect(
widgetX - border,
widgetYBar - border,
backgroundWidth + border * 2,
barHeight + border * 2
);
// Dibujar el área principal de la barra (fondo)
ctx.fillStyle = globalThis.LiteGraph.WIDGET_BGCOLOR; // Mismo color de fondo que el canvas
ctx.fillRect(
widgetX,
widgetYBar,
backgroundWidth,
barHeight
);
// Draw progress bar grid
ctx.beginPath();
ctx.lineWidth = 1;
ctx.strokeStyle = "#66666650";
// Calcular el número de líneas en función del tamaño de la barra
const numLines = Math.floor(backgroundWidth / 64);
// Dibujar líneas del grid
for (let x = 0; x <= width / 64; x += 1) {
ctx.moveTo(widgetX + x * 64 * scale, widgetYBar);
ctx.lineTo(widgetX + x * 64 * scale, widgetYBar + barHeight);
}
ctx.stroke();
ctx.closePath();
// Dibujar progreso (basado en blur_radius)
const progress = Math.min(blurRadius / 255, 1);
ctx.fillStyle = "rgba(0, 120, 255, 0.5)";
ctx.fillRect(
widgetX,
widgetYBar,
backgroundWidth * progress,
barHeight
);
}
};
widget.canvas = document.createElement("canvas");
widget.canvas.className = "mask-rect-area-canvas";
widget.parent = node;
document.body.appendChild(widget.canvas);
node.addCustomWidget(widget);
app.canvas.onDrawBackground = function () {
// Draw node isnt fired once the node is off the screen
// if it goes off screen quickly, the input may not be removed
// this shifts it off screen so it can be moved back if the node is visible.
for (let n in app.graph._nodes) {
n = app.graph._nodes[n];
for (let w in n.widgets) {
let wid = n.widgets[w];
if (Object.hasOwn(wid, "canvas")) {
wid.canvas.style.left = -8000 + "px";
wid.canvas.style.position = "absolute";
}
}
}
};
node.onResize = function (size) {
computeCanvasSize(node, size);
};
return {minWidth: 200, minHeight: 200, widget};
}
app.registerExtension({
name: 'drltdata.MaskRectAreaAdvanced',
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name === "MaskRectAreaAdvanced") {
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined;
this.setProperty("width", 512);
this.setProperty("height", 512);
this.setProperty("x", 0);
this.setProperty("y", 0);
this.setProperty("w", 256);
this.setProperty("h", 256);
this.setProperty("blur_radius", 0);
this.selected = false;
this.index = 3;
this.serialize_widgets = true;
CUSTOM_INT(this, "x", 0, function (v, _, node) {
const s = this.options.step / 10;
this.value = Math.round(v / s) * s;
node.properties["x"] = this.value;
});
CUSTOM_INT(this, "y", 0, function (v, _, node) {
const s = this.options.step / 10;
this.value = Math.round(v / s) * s;
node.properties["y"] = this.value;
});
CUSTOM_INT(this, "width", 256, function (v, _, node) {
const s = this.options.step / 10;
this.value = Math.round(v / s) * s;
node.properties["w"] = this.value;
});
CUSTOM_INT(this, "height", 256, function (v, _, node) {
const s = this.options.step / 10;
this.value = Math.round(v / s) * s;
node.properties["h"] = this.value;
});
CUSTOM_INT(this, "image_width", 512, function (v, _, node) {
const s = this.options.step / 10;
this.value = Math.round(v / s) * s;
node.properties["width"] = this.value;
});
CUSTOM_INT(this, "image_height", 512, function (v, _, node) {
const s = this.options.step / 10;
this.value = Math.round(v / s) * s;
node.properties["height"] = this.value;
});
CUSTOM_INT(this, "blur_radius", 0, function (v, _, node) {
this.value = Math.round(v) || 0;
node.properties["blur_radius"] = this.value;
},
{"min": 0, "max": 255, "step": 10}
);
showPreviewCanvas(this, app);
this.onSelected = function () {
this.selected = true;
};
this.onDeselected = function () {
this.selected = false;
};
return r;
};
}
}
});
// Calculate the drawing area using individual properties.
function getDrawArea(node, backgroundWidth, backgroundHeight) {
let x = node.properties["x"] * backgroundWidth / node.properties["width"];
let y = node.properties["y"] * backgroundHeight / node.properties["height"];
let w = node.properties["w"] * backgroundWidth / node.properties["width"];
let h = node.properties["h"] * backgroundHeight / node.properties["height"];
if (x > backgroundWidth) {
x = backgroundWidth;
}
if (y > backgroundHeight) {
y = backgroundHeight;
}
if (x + w > backgroundWidth) {
w = Math.max(0, backgroundWidth - x);
}
if (y + h > backgroundHeight) {
h = Math.max(0, backgroundHeight - y);
}
return [x, y, w, h];
}
function CUSTOM_INT(node, inputName, val, func, config = {}) {
return {
widget: node.addWidget(
"number",
inputName,
val,
func,
Object.assign({}, {min: 0, max: 4096, step: 640, precision: 0}, config)
)
};
}
function getDrawColor(percent, alpha) {
let h = 360 * percent;
let s = 50;
let l = 50;
l /= 100;
const a = s * Math.min(l, 1 - l) / 100;
const f = n => {
const k = (n + h / 30) % 12;
const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
return Math.round(255 * color).toString(16).padStart(2, '0'); // convert to Hex and prefix "0" if needed
};
return `#${f(0)}${f(8)}${f(4)}${alpha}`;
}
function computeCanvasSize(node, size) {
if (node.widgets[0].last_y == null) {
return;
}
const MIN_HEIGHT = 220;
const MIN_WIDTH = 240;
let y = LiteGraph.NODE_WIDGET_HEIGHT * Math.max(node.inputs.length, node.outputs.length) + 5;
let freeSpace = size[1] - y;
// Compute the height of all non-customCanvas widgets
let widgetHeight = 0;
for (let i = 0; i < node.widgets.length; i++) {
const w = node.widgets[i];
if (w.type !== "customCanvas") {
if (w.computeSize) {
widgetHeight += w.computeSize()[1] + 4;
} else {
widgetHeight += LiteGraph.NODE_WIDGET_HEIGHT + 5;
}
}
}
// Ensure there is enough vertical space
freeSpace -= widgetHeight;
// Adjust the height of the node if needed
if (freeSpace < MIN_HEIGHT) {
freeSpace = MIN_HEIGHT;
node.size[1] = y + widgetHeight + freeSpace;
node.graph.setDirtyCanvas(true);
}
// Ensure the node width meets the minimum width requirement
if (node.size[0] < MIN_WIDTH) {
node.size[0] = MIN_WIDTH;
node.graph.setDirtyCanvas(true);
}
// Position each of the widgets
for (const w of node.widgets) {
w.y = y;
if (w.type === "customCanvas") {
y += freeSpace;
} else if (w.computeSize) {
y += w.computeSize()[1] + 4;
} else {
y += LiteGraph.NODE_WIDGET_HEIGHT + 4;
}
}
node.canvasHeight = freeSpace;
}
+366
View File
@@ -0,0 +1,366 @@
import { app } from "/scripts/app.js";
function showPreviewCanvas(node, app) {
const widget = {
type: "customCanvas",
name: "mask-rect-area-canvas",
get value() {
return this.canvas.value;
},
set value(x) {
this.canvas.value = x;
},
draw: function (ctx, node, widgetWidth, widgetY) {
// If we are initially offscreen when created we wont have received a resize event
// Calculate it here instead
if (!node.canvasHeight) {
computeCanvasSize(node, node.size);
}
const visible = true;
const t = ctx.getTransform();
const margin = 12;
const border = 2;
const widgetHeight = node.canvasHeight;
const width = 512;
const height = 512;
const scale = Math.min((widgetWidth - margin * 3) / width, (widgetHeight - margin * 3) / height);
const blurRadius = node.properties["blur_radius"] || 0;
const index = 0;
Object.assign(this.canvas.style, {
left: `${t.e}px`,
top: `${t.f + (widgetY * t.d)}px`,
width: `${widgetWidth * t.a}px`,
height: `${widgetHeight * t.d}px`,
position: "absolute",
zIndex: 1,
fontSize: `${t.d * 10.0}px`,
pointerEvents: "none"
});
this.canvas.hidden = !visible;
let backgroundWidth = width * scale;
let backgroundHeight = height * scale;
let xOffset = margin;
if (backgroundWidth < widgetWidth) {
xOffset += (widgetWidth - backgroundWidth) / 2 - margin;
}
let yOffset = (margin / 2);
if (backgroundHeight < widgetHeight) {
yOffset += (widgetHeight - backgroundHeight) / 2 - margin;
}
let widgetX = xOffset;
widgetY = widgetY + yOffset;
// Draw the background border
ctx.fillStyle = globalThis.LiteGraph.WIDGET_OUTLINE_COLOR;
ctx.fillRect(widgetX - border, widgetY - border, backgroundWidth + border * 2, backgroundHeight + border * 2);
// Draw the main background area
ctx.fillStyle = globalThis.LiteGraph.WIDGET_BGCOLOR;
ctx.fillRect(widgetX, widgetY, backgroundWidth, backgroundHeight);
// Draw the conditioning zone
let [x, y, w, h] = getDrawArea(node, backgroundWidth, backgroundHeight);
ctx.fillStyle = getDrawColor(0, "80");
ctx.fillRect(widgetX + x, widgetY + y, w, h);
ctx.beginPath();
ctx.lineWidth = 1;
// Draw grid lines
for (let x = 0; x <= width / 64; x += 1) {
ctx.moveTo(widgetX + x * 64 * scale, widgetY);
ctx.lineTo(widgetX + x * 64 * scale, widgetY + backgroundHeight);
}
for (let y = 0; y <= height / 64; y += 1) {
ctx.moveTo(widgetX, widgetY + y * 64 * scale);
ctx.lineTo(widgetX + backgroundWidth, widgetY + y * 64 * scale);
}
ctx.strokeStyle = "#66666650";
ctx.stroke();
ctx.closePath();
// Draw current zone
let [sx, sy, sw, sh] = getDrawArea(node, backgroundWidth, backgroundHeight);
ctx.fillStyle = getDrawColor(0, "80");
ctx.fillRect(widgetX + sx, widgetY + sy, sw, sh);
ctx.fillStyle = getDrawColor(0, "40");
ctx.fillRect(widgetX + sx + border, widgetY + sy + border, sw - border * 2, sh - border * 2);
// Draw white border around the current zone
ctx.strokeStyle = globalThis.LiteGraph.NODE_SELECTED_TITLE_COLOR;
ctx.lineWidth = 2;
ctx.strokeRect(widgetX + sx, widgetY + sy, sw, sh);
//ctx.strokeRect(finalSX, finalSY, finalSW, finalSH);
// Display
ctx.beginPath();
ctx.arc(LiteGraph.NODE_SLOT_HEIGHT * 0.5, LiteGraph.NODE_SLOT_HEIGHT * (index + 0.5) + 4, 4, 0, Math.PI * 2);
ctx.fill();
ctx.lineWidth = 1;
ctx.strokeStyle = "white";
ctx.stroke();
ctx.lineWidth = 1;
ctx.closePath();
// Draw progress bar canvas
if (backgroundWidth < widgetWidth) {
xOffset += (widgetWidth - backgroundWidth) / 2 - margin;
}
const barHeight = 8;
let widgetYBar = widgetY + backgroundHeight + margin;
// Draw progress bar border
ctx.fillStyle = globalThis.LiteGraph.WIDGET_OUTLINE_COLOR;
ctx.fillRect(
widgetX - border,
widgetYBar - border,
backgroundWidth + border * 2,
barHeight + border * 2
);
// Draw progress bar area
ctx.fillStyle = globalThis.LiteGraph.WIDGET_BGCOLOR; // Mismo color de fondo que el canvas
ctx.fillRect(
widgetX,
widgetYBar,
backgroundWidth,
barHeight
);
// Draw progress bar grid
ctx.beginPath();
ctx.lineWidth = 1;
ctx.strokeStyle = "#66666650";
// Determine max lines
const numLines = Math.floor(backgroundWidth / 64);
// Draw progress bar grid
for (let x = 0; x <= width / 64; x += 1) {
ctx.moveTo(widgetX + x * 64 * scale, widgetYBar);
ctx.lineTo(widgetX + x * 64 * scale, widgetYBar + barHeight);
}
ctx.stroke();
ctx.closePath();
// Draw progress bar
const progress = Math.min(blurRadius / 255, 1);
ctx.fillStyle = "rgba(0, 120, 255, 0.5)";
ctx.fillRect(
widgetX,
widgetYBar,
backgroundWidth * progress,
barHeight
);
}
};
widget.canvas = document.createElement("canvas");
widget.canvas.className = "mask-rect-area-canvas";
widget.parent = node;
document.body.appendChild(widget.canvas);
node.addCustomWidget(widget);
app.canvas.onDrawBackground = function () {
// Draw node isnt fired once the node is off the screen
// if it goes off screen quickly, the input may not be removed
// this shifts it off screen so it can be moved back if the node is visible.
for (let n in app.graph._nodes) {
n = app.graph._nodes[n];
for (let w in n.widgets) {
let wid = n.widgets[w];
if (Object.hasOwn(wid, "canvas")) {
wid.canvas.style.left = -8000 + "px";
wid.canvas.style.position = "absolute";
}
}
}
};
node.onResize = function (size) {
computeCanvasSize(node, size);
};
return {minWidth: 200, minHeight: 200, widget};
}
app.registerExtension({
name: 'drltdata.MaskRectArea',
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name === "MaskRectArea") {
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined;
this.setProperty("width", 512);
this.setProperty("height", 512);
this.setProperty("x", 0);
this.setProperty("y", 0);
this.setProperty("w", 50);
this.setProperty("h", 50);
this.setProperty("blur_radius", 0);
this.selected = false;
this.index = 3;
this.serialize_widgets = true;
CUSTOM_INT(this, "x", 0, function (v, _, node) {
this.value = Math.max(0, Math.min(100, Math.round(v))); // Limitar entre 0 y 100
node.properties["x"] = this.value;
});
CUSTOM_INT(this, "y", 0, function (v, _, node) {
this.value = Math.max(0, Math.min(100, Math.round(v)));
node.properties["y"] = this.value;
});
CUSTOM_INT(this, "w", 50, function (v, _, node) {
this.value = Math.max(0, Math.min(100, Math.round(v)));
node.properties["w"] = this.value;
});
CUSTOM_INT(this, "h", 50, function (v, _, node) {
this.value = Math.max(0, Math.min(100, Math.round(v)));
node.properties["h"] = this.value;
});
CUSTOM_INT(this, "blur_radius", 0, function (v, _, node) {
this.value = Math.round(v) || 0;
node.properties["blur_radius"] = this.value;
},
{"min": 0, "max": 255, "step": 10}
);
showPreviewCanvas(this, app);
this.onSelected = function () {
this.selected = true;
};
this.onDeselected = function () {
this.selected = false;
};
return r;
};
}
}
});
// Calculate the drawing area using percentage-based properties.
function getDrawArea(node, backgroundWidth, backgroundHeight) {
// Convert percentages to actual pixel values based on the background dimensions
let x = (node.properties["x"] / 100) * backgroundWidth;
let y = (node.properties["y"] / 100) * backgroundHeight;
let w = (node.properties["w"] / 100) * backgroundWidth;
let h = (node.properties["h"] / 100) * backgroundHeight;
// Ensure the values do not exceed the background boundaries
if (x > backgroundWidth) {
x = backgroundWidth;
}
if (y > backgroundHeight) {
y = backgroundHeight;
}
// Adjust width and height to fit within the background dimensions
if (x + w > backgroundWidth) {
w = Math.max(0, backgroundWidth - x);
}
if (y + h > backgroundHeight) {
h = Math.max(0, backgroundHeight - y);
}
return [x, y, w, h];
}
function CUSTOM_INT(node, inputName, val, func, config = {}) {
return {
widget: node.addWidget(
"number",
inputName,
val,
func,
Object.assign({}, {min: 0, max: 100, step: 10, precision: 0}, config)
)
};
}
function getDrawColor(percent, alpha) {
let h = 360 * percent;
let s = 50;
let l = 50;
l /= 100;
const a = s * Math.min(l, 1 - l) / 100;
const f = n => {
const k = (n + h / 30) % 12;
const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
return Math.round(255 * color).toString(16).padStart(2, '0'); // convert to Hex and prefix "0" if needed
};
return `#${f(0)}${f(8)}${f(4)}${alpha}`;
}
function computeCanvasSize(node, size) {
if (node.widgets[0].last_y == null) {
return;
}
const MIN_HEIGHT = 200;
const MIN_WIDTH = 200;
let y = LiteGraph.NODE_WIDGET_HEIGHT * Math.max(node.inputs.length, node.outputs.length) + 5;
let freeSpace = size[1] - y;
// Compute the height of all non-customCanvas widgets
let widgetHeight = 0;
for (let i = 0; i < node.widgets.length; i++) {
const w = node.widgets[i];
if (w.type !== "customCanvas") {
if (w.computeSize) {
widgetHeight += w.computeSize()[1] + 4;
} else {
widgetHeight += LiteGraph.NODE_WIDGET_HEIGHT + 5;
}
}
}
// Ensure there is enough vertical space
freeSpace -= widgetHeight;
// Adjust the height of the node if needed
if (freeSpace < MIN_HEIGHT) {
freeSpace = MIN_HEIGHT;
node.size[1] = y + widgetHeight + freeSpace;
node.graph.setDirtyCanvas(true);
}
// Ensure the node width meets the minimum width requirement
if (node.size[0] < MIN_WIDTH) {
node.size[0] = MIN_WIDTH;
node.graph.setDirtyCanvas(true);
}
// Position each of the widgets
for (const w of node.widgets) {
w.y = y;
if (w.type === "customCanvas") {
y += freeSpace;
} else if (w.computeSize) {
y += w.computeSize()[1] + 4;
} else {
y += LiteGraph.NODE_WIDGET_HEIGHT + 4;
}
}
node.canvasHeight = freeSpace;
}
+1 -1
View File
@@ -1,7 +1,7 @@
import configparser
import os
version_code = [7, 14, 1]
version_code = [8, 1, 2]
version = f"V{version_code[0]}.{version_code[1]}" + (f'.{version_code[2]}' if len(version_code) > 2 else '')
dependency_version = 24
+133
View File
@@ -225,6 +225,10 @@ class DetailerForEach:
CATEGORY = "ImpactPack/Detailer"
@staticmethod
def get_core_module():
return core
@staticmethod
def do_detail(image, segs, model, clip, vae, guide_size, guide_size_for_bbox, max_size, seed, steps, cfg, sampler_name, scheduler,
positive, negative, denoise, feather, noise_mask, force_inpaint, wildcard_opt=None, detailer_hook=None,
@@ -1830,6 +1834,135 @@ def get_file_item(base_type, path):
}
class MaskRectArea:
# Creates a rectangle mask using percentage.
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
},
"hidden": {"extra_pnginfo": "EXTRA_PNGINFO", "unique_id": "UNIQUE_ID"}
}
RETURN_TYPES = ("MASK",)
CATEGORY = "ImpactPack/Operation"
FUNCTION = "create_mask"
def create_mask(self, extra_pnginfo, unique_id, **kwargs):
# search for node
node_found = False
for node in extra_pnginfo["workflow"]["nodes"]:
if node["id"] == int(unique_id):
min_x = node["properties"].get("x", 0) / 100
min_y = node["properties"].get("y", 0) / 100
width = node["properties"].get("w", 0) / 100
height = node["properties"].get("h", 0) / 100
blur_radius = node["properties"].get("blur_radius", 0)
node_found = True
break
if not node_found:
raise ValueError(f"No node found with unique_id {unique_id}.")
# Create a mask with standard resolution (e.g., 512x512)
resolution = 512
mask = torch.zeros((resolution, resolution))
# Calculate pixel coordinates
min_x_px = int(min_x * resolution)
min_y_px = int(min_y * resolution)
max_x_px = int((min_x + width) * resolution)
max_y_px = int((min_y + height) * resolution)
# Draw the rectangle on the mask
mask[min_y_px:max_y_px, min_x_px:max_x_px] = 1
# Apply blur if the radii are greater than 0
if blur_radius > 0:
dx = blur_radius * 2 + 1
dy = blur_radius * 2 + 1
# Convert the mask to a format compatible with OpenCV (numpy array)
mask_np = mask.cpu().numpy().astype("float32")
# Apply Gaussian Blur
blurred_mask = cv2.GaussianBlur(mask_np, (dx, dy), 0)
# Convert back to tensor
mask = torch.from_numpy(blurred_mask)
# Return the mask as a tensor with an additional channel
return (mask.unsqueeze(0),)
class MaskRectAreaAdvanced:
# Creates a rectangle mask using pixels relative to image size.
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
},
"hidden": {"extra_pnginfo": "EXTRA_PNGINFO", "unique_id": "UNIQUE_ID"}
}
RETURN_TYPES = ("MASK",)
CATEGORY = "ImpactPack/Operation"
FUNCTION = "create_mask_advanced"
def create_mask_advanced(self, extra_pnginfo, unique_id, **kwargs):
# search for node
node_found = False
for node in extra_pnginfo["workflow"]["nodes"]:
if node["id"] == int(unique_id):
min_x = node["properties"]["x"]
min_y = node["properties"]["y"]
width = node["properties"]["w"]
height = node["properties"]["h"]
image_width = node["properties"]["width"]
image_height = node["properties"]["height"]
blur_radius = node["properties"]["blur_radius"]
node_found = True
break
if not node_found:
raise ValueError(f"No node found with unique_id {unique_id}.")
# Calculate maximum coordinates
max_x = min_x + width
max_y = min_y + height
# Create a mask with the image dimensions
mask = torch.zeros((image_height, image_width))
# Draw the rectangle on the mask
mask[int(min_y):int(max_y), int(min_x):int(max_x)] = 1
# Apply blur if the radii are greater than 0
if blur_radius > 0:
dx = blur_radius * 2 + 1
dy = blur_radius * 2 + 1
# Convert the mask to a format compatible with OpenCV (numpy array)
mask_np = mask.cpu().numpy().astype("float32")
# Apply Gaussian Blur
blurred_mask = cv2.GaussianBlur(mask_np, (dx, dy), 0)
# Convert back to tensor
mask = torch.from_numpy(blurred_mask)
# Return the mask as a tensor with an additional channel
return (mask.unsqueeze(0),)
class ImageReceiver:
@classmethod
def INPUT_TYPES(s):
+28 -7
View File
@@ -22,6 +22,7 @@ import comfy
from io import BytesIO
import random
from server import PromptServer
import logging
sam_predictor = None
@@ -79,7 +80,7 @@ async def sam_prepare(request):
model_name = os.path.join(impact_pack.model_path, "sams", model_name)
print(f"[INFO] ComfyUI-Impact-Pack: Loading SAM model '{impact_pack.model_path}'")
logging.info(f"[Impact Pack] Loading SAM model '{impact_pack.model_path}'")
filename, image_dir = folder_paths.annotated_filepath(data["filename"])
@@ -95,7 +96,7 @@ async def sam_prepare(request):
thread = threading.Thread(target=async_prepare_sam, args=(image_dir, model_name, filename,))
thread.start()
print(f"[INFO] ComfyUI-Impact-Pack: SAM model loaded. ")
logging.info("[Impact Pack] SAM model loaded. ")
return web.Response(status=200)
@@ -107,7 +108,7 @@ async def release_sam(request):
del sam_predictor
sam_predictor = None
print(f"[INFO] ComfyUI-Impact-Pack: unloading SAM model")
logging.info("[Impact Pack]: unloading SAM model")
@PromptServer.instance.routes.post("/sam/detect")
@@ -315,6 +316,8 @@ def onprompt_for_switch(json_data):
inversed_switch_info = {}
onprompt_switch_info = {}
onprompt_cond_branch_info = {}
disabled_switch = set()
for k, v in json_data['prompt'].items():
if 'class_type' not in v:
@@ -322,20 +325,24 @@ def onprompt_for_switch(json_data):
cls = v['class_type']
if cls == 'ImpactInversedSwitch':
# if 'sel_mode' is 'select_on_prompt'
if 'sel_mode' in v['inputs'] and v['inputs']['sel_mode'] and 'select' in v['inputs']:
select_input = v['inputs']['select']
# if 'select' is converted input
if isinstance(select_input, list) and len(select_input) == 2:
input_node = json_data['prompt'][select_input[0]]
if input_node['class_type'] == 'ImpactInt' and 'inputs' in input_node and 'value' in input_node['inputs']:
inversed_switch_info[k] = input_node['inputs']['value']
else:
print(f"\n##### ##### #####\n[WARN] {cls}: For the 'select' operation, only 'select_index' of the 'ImpactInversedSwitch', which is not an input, or 'ImpactInt' and 'Primitive' are allowed as inputs if 'select_on_prompt' is selected.\n##### ##### #####\n")
logging.warning(f"\n##### ##### #####\n[Impact Pack] {cls}: For the 'select' operation, only 'select_index' of the 'ImpactInversedSwitch', which is not an input, or 'ImpactInt' and 'Primitive' are allowed as inputs if 'select_on_prompt' is selected.\n##### ##### #####\n")
else:
inversed_switch_info[k] = select_input
elif cls in ['ImpactSwitch', 'LatentSwitch', 'SEGSSwitch', 'ImpactMakeImageList']:
# if 'sel_mode' is 'select_on_prompt'
if 'sel_mode' in v['inputs'] and v['inputs']['sel_mode'] and 'select' in v['inputs']:
select_input = v['inputs']['select']
# if 'select' is converted input
if isinstance(select_input, list) and len(select_input) == 2:
input_node = json_data['prompt'][select_input[0]]
if input_node['class_type'] == 'ImpactInt' and 'inputs' in input_node and 'value' in input_node['inputs']:
@@ -344,10 +351,14 @@ def onprompt_for_switch(json_data):
if isinstance(input_node['inputs']['select'], int):
onprompt_switch_info[k] = input_node['inputs']['select']
else:
print(f"\n##### ##### #####\n[WARN] {cls}: For the 'select' operation, only 'select_index' of the 'ImpactSwitch', which is not an input, or 'ImpactInt' and 'Primitive' are allowed as inputs if 'select_on_prompt' is selected.\n##### ##### #####\n")
logging.warning(f"\n##### ##### #####\n[Impact Pack] {cls}: For the 'select' operation, only 'select_index' of the 'ImpactSwitch', which is not an input, or 'ImpactInt' and 'Primitive' are allowed as inputs if 'select_on_prompt' is selected.\n##### ##### #####\n")
else:
onprompt_switch_info[k] = select_input
if k in onprompt_switch_info and f'input{onprompt_switch_info[k]}' not in v['inputs']:
# disconnect output
disabled_switch.add(k)
elif cls == 'ImpactConditionalBranchSelMode':
if 'sel_mode' in v['inputs'] and v['inputs']['sel_mode'] and 'cond' in v['inputs']:
cond_input = v['inputs']['cond']
@@ -371,6 +382,11 @@ def onprompt_for_switch(json_data):
if vv[0] in inversed_switch_info:
if vv[1] + 1 != inversed_switch_info[vv[0]]:
disable_targets.add(kk)
else:
del inversed_switch_info[k]
if vv[0] in disabled_switch:
disable_targets.add(kk)
if k in onprompt_switch_info:
selected_slot_name = f"input{onprompt_switch_info[k]}"
@@ -387,6 +403,11 @@ def onprompt_for_switch(json_data):
for kk in disable_targets:
del v['inputs'][kk]
# inversed_switch - select out of range
for target in inversed_switch_info.keys():
del json_data['prompt'][target]['inputs']['input']
def onprompt_for_pickers(json_data):
detected_pickers = set()
@@ -470,7 +491,7 @@ def onprompt_populate_wildcards(json_data):
if not isinstance(input_seed, int):
continue
else:
print(f"[Impact Pack] Only `ImpactInt`, `Seed (rgthree)` and `Primitive` Node are allowed as the seed for '{v['class_type']}'. It will be ignored. ")
logging.info(f"[Impact Pack] Only `ImpactInt`, `Seed (rgthree)` and `Primitive` Node are allowed as the seed for '{v['class_type']}'. It will be ignored. ")
continue
except:
continue
@@ -533,7 +554,7 @@ def onprompt(json_data):
regional_sampler_seed_update(json_data)
core.current_prompt = json_data
except Exception as e:
print(f"[WARN] ComfyUI-Impact-Pack: Error on prompt - several features will not work.\n{e}")
logging.warning(f"[Impact Pack] ComfyUI-Impact-Pack: Error on prompt - several features will not work.\n{e}")
return json_data
+2 -2
View File
@@ -1,7 +1,7 @@
[project]
name = "comfyui-impact-pack"
description = "This extension offers various detector nodes and detailer nodes that allow you to configure a workflow that automatically enhances facial details. And provide iterative upscaler."
version = "7.14.1"
description = "This node pack offers various detector nodes and detailer nodes that allow you to configure a workflow that automatically enhances facial details. And provide iterative upscaler."
version = "8.1.2"
license = { file = "LICENSE.txt" }
dependencies = ["segment-anything", "scikit-image", "piexif", "transformers", "opencv-python-headless", "GitPython", "scipy>=1.11.4"]
-1
View File
@@ -3,7 +3,6 @@ scikit-image
piexif
transformers
opencv-python-headless
GitPython
scipy>=1.11.4
numpy<2
dill