Merge branch 'dev': v0.0.1

This commit is contained in:
Lex Darlog (DRL)
2025-07-05 18:22:11 +05:00
10 changed files with 649 additions and 7 deletions
+80 -7
View File
@@ -1,10 +1,7 @@
# Organized+extended by Lex-DRL: https://github.com/Lex-DRL/git-template-gamedev
# OS-generated
# ------------
.DS_Store*
[Tt]humbs.db
[Dd]esktop.ini
# Common
# ----------------------------
# Temp files/folders:
*.tmp
@@ -15,6 +12,38 @@
# Programming - general
*.log
# OS-generated - Windows
# ----------------------------
[Tt]humbs.db
[Dd]esktop.ini
# OS-generated - Apple
# ----------------------------
.DS_Store*
.AppleDouble
.LSOverride
# ... and thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# =========================================================================== #
# IDEs
@@ -22,6 +51,15 @@
# JetBrains IDEs: PyCharm / Rider
.idea/
*.iml
*.ipr
*.iws
# vscode
.vscode/
.claude/
.history/
*.code-workspace
# =========================================================================== #
@@ -61,7 +99,13 @@ share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
# 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
*.manifest
*.spec
# Installer logs
pip-log.txt
@@ -77,15 +121,44 @@ htmlcov/
nosetests.xml
coverage.xml
*.cover
*.py,cover
*,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Cookiecutter
output/
python_boilerplate/
cookiecutter-pypackage-env/
# Frontend extension
node_modules/
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
node.zip
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# =========================================================================== #
# Repo-specific
# =========================================================================== #
# add here
example_node.py
+157
View File
@@ -0,0 +1,157 @@
### GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates the
terms and conditions of version 3 of the GNU General Public License,
supplemented by the additional permissions listed below.
#### 0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the
GNU General Public License.
"The Library" refers to a covered work governed by this License, other
than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
#### 1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
#### 2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
- a) under this License, provided that you make a good faith effort
to ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
- b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
#### 3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from a
header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
- a) Give prominent notice with each copy of the object code that
the Library is used in it and that the Library and its use are
covered by this License.
- b) Accompany the object code with a copy of the GNU GPL and this
license document.
#### 4. Combined Works.
You may convey a Combined Work under terms of your choice that, taken
together, effectively do not restrict modification of the portions of
the Library contained in the Combined Work and reverse engineering for
debugging such modifications, if you also do each of the following:
- a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
- b) Accompany the Combined Work with a copy of the GNU GPL and this
license document.
- c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
- d) Do one of the following:
- 0) Convey the Minimal Corresponding Source under the terms of
this License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
- 1) Use a suitable shared library mechanism for linking with
the Library. A suitable mechanism is one that (a) uses at run
time a copy of the Library already present on the user's
computer system, and (b) will operate properly with a modified
version of the Library that is interface-compatible with the
Linked Version.
- e) Provide Installation Information, but only if you would
otherwise be required to provide such information under section 6
of the GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the Application
with a modified version of the Linked Version. (If you use option
4d0, the Installation Information must accompany the Minimal
Corresponding Source and Corresponding Application Code. If you
use option 4d1, you must provide the Installation Information in
the manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.)
#### 5. Combined Libraries.
You may place library facilities that are a work based on the Library
side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
- a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities, conveyed under the terms of this License.
- b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
#### 6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
as you received it specifies that a certain numbered version of the
GNU Lesser General Public License "or any later version" applies to
it, you have the option of following the terms and conditions either
of that published version or of any later version published by the
Free Software Foundation. If the Library as you received it does not
specify a version number of the GNU Lesser General Public License, you
may choose any version of the GNU Lesser General Public License ever
published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
+32
View File
@@ -0,0 +1,32 @@
# ComfyUI-BestResolution
QoL Nodes for semi-automatic calculation of the best (most optimal) resolution:
- compatible with ANY model (from now or the future),
- accounting for upscale (**TODO**, planned soon)
- ... and (the required) pixel-step.
![image](img/screenshot1.png)
In case you didn't know, you can't just choose **any** arbitrary resolution for sampling. You need to ensure:
- both width and height are divisible by pre-defined latent scale factor (8 for both SD1.5 and SDXL);
- the overall resolution (aka megapixels) is as close to training dataset as possible.
This pack lets you forget about crunching numbers and handles the calculation of optimal width/height for you, while still leaving control to you. It provides 3 main nodes:
### Simple
Just rounds width/height to the given step, ensuring the image **CAN** be converted to latent - both in initial generation and after some upscales.
### From Aspect-Ratio
You specify the desired aspect ratio, one of the sides, and orientation (landscape/portrait). The node detects the actual width/height.
### From Area
To my taste, **THE** safest and easiest approach to selecting the optimal sampling resolution.
All you need to know is a side of square images the model was trained on (512 for SD1.5, 1024 for SDXL). The node handles the rest to ensure the total resolution (i.e., number of pixels) is as close to the training data as possible, while still respecting aspect ratio and step size.
## Tooltips
Each parameter is self-documented in detail - just hover mouse over it. If you're new to Comfy and Stable Diffusion, this might be especially helpful.
+18
View File
@@ -0,0 +1,18 @@
# encoding: utf-8
"""
"""
from .nodes import *
NODE_CLASS_MAPPINGS = {
"BestResolutionFromArea": BestResolutionFromArea,
"BestResolutionFromAspectRatio": BestResolutionFromAspectRatio,
"BestResolutionSimple": BestResolutionSimple,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"BestResolutionFromArea": "Best-Res (area)",
"BestResolutionFromAspectRatio": "Best-Res (ratio)",
"BestResolutionSimple": "Best-Res (simple)",
}
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
+102
View File
@@ -0,0 +1,102 @@
# encoding: utf-8
"""
Internal utility functions. They're intended to be used only by the methods within nodes,
so they might expect the input arguments to already be pre-validated.
"""
import typing as _t
from math import sqrt as _sqrt
from server import PromptServer as _PromptServer
_t_number = _t.Union[int, float]
def aspect_ratios_sorted(aspect_a: float, aspect_b: float, min_clamp: float = 1.0):
"""Return aspect ratio in a standard form: 2 floats, both 1+, in descending order (16:9, not 9:16)."""
aspect_a = float(max(abs(aspect_a), min_clamp))
aspect_b = float(max(abs(aspect_b), min_clamp))
return (aspect_b, aspect_a) if aspect_b > aspect_a else (aspect_a, aspect_b)
def number_to_int(value: _t.Union[int, float], min: int = 1) -> int:
if not isinstance(value, int):
if isinstance(value, float):
sign = -1 if value < 0.0 else 1
value = int(value * sign + 0.5) * sign
else:
value = int(value)
return max(value, min)
def round_abs(abs_value: _t_number, step: int):
"""
Assuming both args are positive and ``step`` is already an int, detect the closest positive (non-zero) value
which is also divisible by step.
"""
n_steps = int(float(abs_value) / step + 0.5)
n_steps = max(n_steps, 1)
return step * n_steps, n_steps
def round_width_and_height_closest_to_the_ratio(width_f: _t_number, height_f: _t_number, step: int):
"""3-pass detection of the best rounded resolution. Best = closest to the desired ratio."""
desired_width_to_height_ratio = float(width_f) / height_f
# First pass: directly from width_f and height_f
width, n_steps_x = round_abs(width_f, step)
height, n_steps_y = round_abs(height_f, step)
# Second pass: try calculating one side from already rounded another one:
height_from_width, n_steps_y_from_x = round_abs(float(width) / desired_width_to_height_ratio, step)
width_from_height, n_steps_x_from_y = round_abs(float(height) * desired_width_to_height_ratio, step)
# ... and select one of three options, closest to the perfect ratio:
closest_delta = abs((float(width) / height) - desired_width_to_height_ratio)
for w, n_x, h, n_y in [
(width, n_steps_x, height_from_width, n_steps_y_from_x),
(width_from_height, n_steps_x_from_y, height, n_steps_y),
]:
cur_delta = abs((float(w) / h) - desired_width_to_height_ratio)
if cur_delta < closest_delta:
closest_delta = cur_delta
width, n_steps_x = w, n_x
height, n_steps_y = h, n_y
return width, n_steps_x, height, n_steps_y
def simple_result_from_approx_wh(width_f: float, height_f: _t_number, step: int, unique_id: str = None):
"""Final part of the main func for simple (non-upscale) nodes - when desired float/height are already calculated"""
step = number_to_int(step)
width, n_steps_x, height, n_steps_y = round_width_and_height_closest_to_the_ratio(width_f, height_f, step)
square_side_f = _sqrt(float(width * height))
square_side = int(square_side_f + 0.5)
square_side_text = (
f"={square_side}x{square_side}"
if (square_side * square_side == width * height)
else f"~{square_side}x{square_side}"
)
ar_desired = width_f / height_f
ar_real = float(width) / height
ar_text = (
"AR: perfect match"
if abs(ar_desired - ar_real) < 0.0005
else f"AR goal/real: {ar_desired:.3f}/{ar_real:.3f}"
)
text = (
f"{width} x {height} ({square_side_text})\n"
f"{n_steps_x} * {step} x {n_steps_y} * {step}\n"
f"{ar_text}"
)
if unique_id:
# Snatched from: https://github.com/comfyanonymous/ComfyUI/blob/27870ec3c30e56be9707d89a120eb7f0e2836be1/comfy_extras/nodes_images.py#L581-L582
_PromptServer.instance.send_progress_text(text, unique_id)
return width, height
Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

+25
View File
@@ -0,0 +1,25 @@
# encoding: utf-8
"""
Pre-defined dictionaries for nice input types.
"""
import typing as _t
import sys as _sys
def number_type_dict(default: int = 512, min: int = 1, max: int = _sys.maxsize, step: int = 1) -> _t.Dict[str, int]:
"""Prepare type-dict for an input int/float parameter."""
# sys.maxsize is Py3's closest equivalent to 'sys.maxint' from Py2
return {
"default": default,
"min": min,
"max": max,
"step": step
}
type_dict_step_init = number_type_dict(48)
type_dict_step_upscale1 = number_type_dict(128)
type_dict_res = number_type_dict(1024)
+215
View File
@@ -0,0 +1,215 @@
# encoding: utf-8
"""
The actual nodes defined by the package.
"""
import typing as _t
from inspect import cleandoc as _cleandoc
from math import sqrt as _sqrt
import sys as _sys
from frozendict import deepfreeze
from comfy.comfy_types.node_typing import IO as _IO
from .node_types import *
from ._funcs import (
aspect_ratios_sorted as _aspect_ratios_sorted,
number_to_int as _number_to_int,
simple_result_from_approx_wh as _simple_result_from_approx_wh
)
# Tiny optimization by reusing the same immutable dict:
_input_types_simple = deepfreeze({
"required": {
"width": (_IO.INT, dict(type_dict_res, **{"tooltip": "Approximate width"})),
"height": (_IO.INT, dict(type_dict_res, **{"tooltip": "Approximate height"})),
"step": (_IO.INT, dict(type_dict_step_init, **{"tooltip": (
"Both width and height will be divisible by this value - by rounding them "
"to the closest appropriate resolution.\n\n"
"The default 48 is (8 * 3 * 2), so it's a safe choice because:\n"
"- it's compatible with SD1.5/XL downsampling factor (divisible by 8),\n"
"- it can be upscaled by x1.5 or x1.333 at the first iteration, which is optimal for latent-upscale,\n"
"- after x1.5 upscale, if you only do x2 later (it's OK for already high resolutions) - it will be divisible "
"by 3 AND 9, which might become handy at that point, where you'll probably use UltimateSDUpscale.\n\n"
"Other values worth trying first: 64, 96, 128."
)})),
},
"hidden": {
"unique_id": "UNIQUE_ID", # used for text display at the bottom of the node
},
# "optional": {},
})
# _return_types_simple = (_IO.INT, _IO.INT, _IO.STRING)
# _return_names_simple = ("width", "height", "report")
_return_types_simple = (_IO.INT, _IO.INT)
_return_names_simple = ("width", "height")
class BestResolutionSimple:
"""
The simplest node for easier selection of an optimal resolution:
only rounding performed, desired image size specified directly.
"""
NODE_NAME = "BestResolutionSimple"
CATEGORY = "utils/resolution"
DESCRIPTION = _cleandoc(__doc__)
OUTPUT_NODE = True
FUNCTION = "main"
RETURN_TYPES = _return_types_simple
# RETURN_TYPES_TOOLTIPS = {}
RETURN_NAMES = _return_names_simple
@classmethod
def INPUT_TYPES(cls):
return _input_types_simple
def main(self, width: int, height: int, step: int, unique_id: str = None):
return _simple_result_from_approx_wh(float(width), height, step, unique_id)
_tooltip_aspect = (
"Two aspects together define an aspect ratio (16:9, 4:3, etc).\n"
"Order doesn't matter: image orientation is defined by the 'landscape' toggle.\n\n"
"The specified aspect ratio is APPROXIMATE: step parameter has priority over the exact image proportions."
)
_input_types_orient = deepfreeze({
"required": {
"size": (_IO.INT, dict(type_dict_res, **{"tooltip": (
"Approximate size of one of the image sides.\nWhich one - see the 'size_is_big' and 'landscape' toggles."
)})),
"step": _input_types_simple["required"]["step"],
"size_is_big": (_IO.BOOLEAN, {
"default": True, "label_on": "bigger", "label_off": "smaller",
"tooltip": "When ON, size parameter represents the bigger image side.\nWhen OFF, it specifies the smaller one."
}),
"landscape": (_IO.BOOLEAN, {
"default": True, "label_on": "landscape", "label_off": "portrait",
"tooltip": (
"Specifies image orientation:\n\n"
"When ON, width is bigger (image is horizontal).\n"
"When OFF, height is bigger (image is vertical)."
)
}),
"aspect_a": (_IO.FLOAT, {
"default": 16.0, "min": 1.0, "max": _sys.float_info.max, "step": 1.0, "round": 0.001,
"tooltip": _tooltip_aspect
}),
"aspect_b": (_IO.FLOAT, {
"default": 9.0, "min": 1.0, "max": _sys.float_info.max, "step": 1.0, "round": 0.001,
"tooltip": _tooltip_aspect
}),
},
"hidden": {
"unique_id": "UNIQUE_ID",
},
# "optional": {},
})
class BestResolutionFromAspectRatio:
"""
A more advanced node for easier selection of an optimal resolution:
image size selected indirectly - by one of the sides + aspect ratio.
"""
NODE_NAME = "BestResolutionFromAspectRatio"
CATEGORY = "utils/resolution"
DESCRIPTION = _cleandoc(__doc__)
OUTPUT_NODE = True
FUNCTION = "main"
RETURN_TYPES = _return_types_simple
RETURN_NAMES = _return_names_simple
@classmethod
def INPUT_TYPES(cls):
return _input_types_orient
def main(self, size: int, step: int, size_is_big: bool, landscape: bool, aspect_a: float, aspect_b: float, unique_id: str = None):
aspect_big, aspect_small = _aspect_ratios_sorted(aspect_a, aspect_b)
side_main_f = float(size)
side_other_f = side_main_f * (
(aspect_small / aspect_big) if size_is_big else (aspect_big / aspect_small)
)
width_f, height_f = (side_other_f, side_main_f) if side_other_f > side_main_f else (side_main_f, side_other_f)
if not landscape:
# The opposite: height is bigger
width_f, height_f = height_f, width_f
return _simple_result_from_approx_wh(width_f, height_f, step, unique_id)
_input_types_area = deepfreeze({
"required": {
"square_size": (_IO.INT, dict(type_dict_res, **{"tooltip": (
"The total resolution of the image would be the same as of a square with this side.\n"
"The width and height would be such to respect aspect ratio, but also be as close as possible to the "
"total number of pixels as in this square image.\n\n"
"- 512x512 square (SD 1.5): ~0.25 megapixels\n"
"- 1024x1024 square (SDXL): ~1 megapixel"
)})),
"step": _input_types_simple["required"]["step"],
"landscape": _input_types_orient["required"]["landscape"],
"aspect_a": _input_types_orient["required"]["aspect_a"],
"aspect_b": _input_types_orient["required"]["aspect_b"],
},
"hidden": {
"unique_id": "UNIQUE_ID",
},
# "optional": {},
})
class BestResolutionFromArea:
"""
The most efficient way of selecting an optimal resolution:
image size selected indirectly - by the total desired resolution (area) + aspect ratio.
Desired resolution (aka image area/megapixels/pixel count) is specified with a side of a square image. This isn't
accidental: most models disclose what image resolution they're trained on, and usually they're square:
- SD 1.5 - 512x512 pixels
- SDXL - 1024x1024 pixels
By simply providing this single number and setting your aspect ratio/orientation, you get the width and height to
produce the closest total resolution to the training set, while also respecting image proportions and step-rounding.
"""
NODE_NAME = "BestResolutionFromArea"
CATEGORY = "utils/resolution"
DESCRIPTION = _cleandoc(__doc__)
OUTPUT_NODE = True
FUNCTION = "main"
RETURN_TYPES = _return_types_simple
RETURN_NAMES = _return_names_simple
@classmethod
def INPUT_TYPES(cls):
return _input_types_area
def main(self, square_size: int, step: int, landscape: bool, aspect_a: float, aspect_b: float, unique_id: str = None):
# square_size = 1024; step = 48; landscape = True; aspect_a = 9.0; aspect_b = 16.0
aspect_big, aspect_small = _aspect_ratios_sorted(aspect_a, aspect_b)
aspect_x, aspect_y = (aspect_big, aspect_small) if landscape else (aspect_small, aspect_big)
aspect_area = aspect_x * aspect_y
aspect_norm_scale = 1.0 / _sqrt(aspect_area)
aspect_x *= aspect_norm_scale
aspect_y *= aspect_norm_scale
# Now the two aspects produce a normalized rectangle - i.e., it's area is 1
square_size = _number_to_int(square_size)
width_f = aspect_x * square_size
height_f = aspect_y * square_size
return _simple_result_from_approx_wh(width_f, height_f, step, unique_id)
+19
View File
@@ -0,0 +1,19 @@
[project]
name = "comfyui-best-resolution"
description = "QoL nodes for semi-automatic calculation of the best (most optimal) sampling resolution, compatible with ANY model (from now or in the future), accounting for upscale and pixel-step."
version = "0.0.1"
authors = [
{name = "Lex Darlog"}
]
license = {file = "LICENSE.md"}
readme = "README.md"
dependencies = ["frozendict"]
[project.urls]
Repository = "https://github.com/Lex-DRL/ComfyUI-BestResolution"
# Used by Comfy Registry https://comfyregistry.org
[tool.comfy]
PublisherId = "lex-drl"
DisplayName = "Best Resolution"
Icon = ""
+1
View File
@@ -0,0 +1 @@
frozendict