almost done

This commit is contained in:
ducido
2024-08-24 23:44:11 +07:00
commit de00645abc
62 changed files with 7846 additions and 0 deletions
+4
View File
@@ -0,0 +1,4 @@
from . import crop
NODE_CLASS_MAPPINGS = {**crop.NODE_CLASS_MAPPINGS}
NODE_DISPLAY_NAME_MAPPINGS = {**crop.NODE_DISPLAY_NAME_MAPPINGS}
Binary file not shown.
Binary file not shown.
+49
View File
@@ -0,0 +1,49 @@
import numpy as np
from PIL import Image
from torchvision import transforms
class ObjectCrop:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"Original_image": ("IMAGE",),
"Chosen_ID": ("INT", {
"default": 0,
}),
"BBOX": ("STRING", {
"multiline": True,
})
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("Chosen_Obj",)
FUNCTION = "run"
CATEGORY = "CROP_OBJECT"
def run(self, Original_image, Chosen_ID, BBOX):
try:
bboxes = BBOX.split(';\n')[Chosen_ID].split(' - ')[-1].split(',')
bboxes = list(map(float, bboxes))
cropped = Original_image[:, int(bboxes[1]):int(bboxes[3]), int(bboxes[0]):int(bboxes[2]), :]
except:
cropped = Original_image
return (cropped, )
# A dictionary that contains all nodes you want to export with their names
# NOTE: names should be globally unique
NODE_CLASS_MAPPINGS = {
"ObjectCrop": ObjectCrop
}
# A dictionary that contains the friendly/humanly readable titles for the nodes
NODE_DISPLAY_NAME_MAPPINGS = {
"ObjectCrop": "Object Cropping"
}
+128
View File
@@ -0,0 +1,128 @@
class Example:
"""
A example node
Class methods
-------------
INPUT_TYPES (dict):
Tell the main program input parameters of nodes.
IS_CHANGED:
optional method to control when the node is re executed.
Attributes
----------
RETURN_TYPES (`tuple`):
The type of each element in the output tuple.
RETURN_NAMES (`tuple`):
Optional: The name of each output in the output tuple.
FUNCTION (`str`):
The name of the entry-point method. For example, if `FUNCTION = "execute"` then it will run Example().execute()
OUTPUT_NODE ([`bool`]):
If this node is an output node that outputs a result/image from the graph. The SaveImage node is an example.
The backend iterates on these output nodes and tries to execute all their parents if their parent graph is properly connected.
Assumed to be False if not present.
CATEGORY (`str`):
The category the node should appear in the UI.
execute(s) -> tuple || None:
The entry point method. The name of this method must be the same as the value of property `FUNCTION`.
For example, if `FUNCTION = "execute"` then this method's name must be `execute`, if `FUNCTION = "foo"` then it must be `foo`.
"""
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
"""
Return a dictionary which contains config for all input fields.
Some types (string): "MODEL", "VAE", "CLIP", "CONDITIONING", "LATENT", "IMAGE", "INT", "STRING", "FLOAT".
Input types "INT", "STRING" or "FLOAT" are special values for fields on the node.
The type can be a list for selection.
Returns: `dict`:
- Key input_fields_group (`string`): Can be either required, hidden or optional. A node class must have property `required`
- Value input_fields (`dict`): Contains input fields config:
* Key field_name (`string`): Name of a entry-point method's argument
* Value field_config (`tuple`):
+ First value is a string indicate the type of field or a list for selection.
+ Second value is a config for type "INT", "STRING" or "FLOAT".
"""
return {
"required": {
"image": ("IMAGE",),
"int_field": ("INT", {
"default": 0,
"min": 0, #Minimum value
"max": 4096, #Maximum value
"step": 64, #Slider's step
"display": "number" # Cosmetic only: display as "number" or "slider"
}),
"float_field": ("FLOAT", {
"default": 1.0,
"min": 0.0,
"max": 10.0,
"step": 0.01,
"round": 0.001, #The value representing the precision to round to, will be set to the step value by default. Can be set to False to disable rounding.
"display": "number"}),
"print_to_screen": (["enable", "disable"],),
"string_field": ("STRING", {
"multiline": False, #True if you want the field to look like the one on the ClipTextEncode node
"default": "Hello World!"
}),
},
}
RETURN_TYPES = ("IMAGE",)
#RETURN_NAMES = ("image_output_name",)
FUNCTION = "test"
#OUTPUT_NODE = False
CATEGORY = "Example"
def test(self, image, string_field, int_field, float_field, print_to_screen):
if print_to_screen == "enable":
print(f"""Your input contains:
string_field aka input text: {string_field}
int_field: {int_field}
float_field: {float_field}
""")
#do some processing on the image, in this example I just invert it
image = 1.0 - image
return (image,)
"""
The node will always be re executed if any of the inputs change but
this method can be used to force the node to execute again even when the inputs don't change.
You can make this node return a number or a string. This value will be compared to the one returned the last time the node was
executed, if it is different the node will be executed again.
This method is used in the core repo for the LoadImage node where they return the image hash as a string, if the image hash
changes between executions the LoadImage node is executed again.
"""
#@classmethod
#def IS_CHANGED(s, image, string_field, int_field, float_field, print_to_screen):
# return ""
# Set the web directory, any .js file in that directory will be loaded by the frontend as a frontend extension
# WEB_DIRECTORY = "./somejs"
# Add custom API routes, using router
from aiohttp import web
from server import PromptServer
@PromptServer.instance.routes.get("/hello")
async def get_hello(request):
return web.json_response("hello")
# A dictionary that contains all nodes you want to export with their names
# NOTE: names should be globally unique
NODE_CLASS_MAPPINGS = {
"Example": Example
}
# A dictionary that contains the friendly/humanly readable titles for the nodes
NODE_DISPLAY_NAME_MAPPINGS = {
"Example": "Example Node"
}
+162
View File
@@ -0,0 +1,162 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$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/
+674
View File
@@ -0,0 +1,674 @@
GNU 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.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+40
View File
@@ -0,0 +1,40 @@
# ComfyUI-SD3-nodes
Nodes that support Stable Diffusion 3 Medium and are a little bit easier to understand. They are a wrapper of ComfyUI's built-in nodes.
![SD3 Default Workflow](workflows/sd3-default-workflow.png)
Download the [JSON format workflow](workflows/sd3-default-workflow.json)
## Requirements
- Upgrade `ComfyUI` to the latest version. You can either use `ComfyUI-Manager` to update, or run `git pull` in the `ComfyUI` folder.
## Node List:
### 1. SD3 Load Checkpoint
Load the SD3 models.
- `ckpt_name`: Choose the SD3 model. If you don't have the model, please go to [Huggingface](https://huggingface.co/stabilityai/stable-diffusion-3-medium/blob/main/sd3_medium.safetensors), provide personal information and download it.
- `shift`: A hyperparameter. According to the [SD3 paper](https://arxiv.org/pdf/2403.03206), it works best at 3.0 and 6.0.
### 2. SD3 Load CLIPs
Load the three CLIPs SD3 borrows:
[CLIP-G](https://huggingface.co/stabilityai/stable-diffusion-3-medium/blob/main/text_encoders/clip_g.safetensors),
[CLIP-L](https://huggingface.co/stabilityai/stable-diffusion-3-medium/blob/main/text_encoders/clip_l.safetensors),
[T5 XXL](https://huggingface.co/stabilityai/stable-diffusion-3-medium/blob/main/text_encoders/t5xxl_fp8_e4m3fn.safetensors)
- `clip-g`: Choose the CLIP-G model.
- `clip-l`: Choose the CLIP-L model.
- `t5xxl`: Choose the T5 XXL model.
### 3. SD3 Empty Latent
- `resolution`: Choose a resolution from the recommended presets. It follows this guideline: "Resolution should be around 1 megapixel and width/height must be multiples of 64".
- `batch_size`: The number of images that will be generated in one batch.
+15
View File
@@ -0,0 +1,15 @@
from .nodes.sd3_load_checkpoint import *
from .nodes.sd3_load_clips import *
from .nodes.sd3_empty_latent import *
NODE_CLASS_MAPPINGS = {
"SD3LoadCheckpoint": SD3LoadCheckpoint,
"SD3LoadCLIPs": SD3LoadCLIPs,
"SD3EmptyLatent": SD3EmptyLatent,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"SD3LoadCheckpoint": "SD3 Load Checkpoint",
"SD3LoadCLIPs": "SD3 Load CLIPs",
"SD3EmptyLatent": "SD3 Empty Latent",
}
@@ -0,0 +1,26 @@
import torch
import comfy.model_management
class SD3EmptyLatent:
def __init__(self):
self.device = comfy.model_management.intermediate_device()
@classmethod
def INPUT_TYPES(s):
resolution = []
# Generate resolutions following this guideline: "Resolution should be around 1 megapixel and width/height must be multiple of 64"
for width in range(512, 1921, 64):
height = int(1024 * 1024 / width / 64) * 64
resolution.append(f"{width}x{height}")
return {"required": {"resolution": (resolution, {"default": "1024x1024"}),
"batch_size": ("INT", {"default": 1, "min": 1, "max": 16})}}
RETURN_TYPES = ("LATENT",)
FUNCTION = "main"
CATEGORY = "latent/sd3"
def main(self, resolution, batch_size=1):
width, height = map(int, resolution.split('x'))
latent = torch.zeros([batch_size, 16, height // 8, width // 8], device=self.device)
return ({"samples":latent}, )
@@ -0,0 +1,31 @@
import folder_paths
import comfy.sd
from nodes import CheckpointLoaderSimple
class SD3LoadCheckpoint (CheckpointLoaderSimple):
@classmethod
def INPUT_TYPES(s):
return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"), ),
"shift": ("FLOAT", {"default": 3.0, "min": 0.0, "max": 100.0, "step":0.01}),
}}
RETURN_TYPES = ("MODEL", "VAE")
FUNCTION = "main"
CATEGORY = "sd3"
def main(self, ckpt_name, shift):
ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
model, _, vae, _ = comfy.sd.load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=False, embedding_directory=folder_paths.get_folder_paths("embeddings"))
m = model.clone()
sampling_base = comfy.model_sampling.ModelSamplingDiscreteFlow
sampling_type = comfy.model_sampling.CONST
class ModelSamplingAdvanced(sampling_base, sampling_type):
pass
model_sampling = ModelSamplingAdvanced(model.model.model_config)
model_sampling.set_parameters(shift=shift)
m.add_object_patch("model_sampling", model_sampling)
return (m, vae)
+12
View File
@@ -0,0 +1,12 @@
import folder_paths
from comfy_extras.nodes_sd3 import TripleCLIPLoader
class SD3LoadCLIPs(TripleCLIPLoader):
@classmethod
def INPUT_TYPES(s):
return {"required": { "clip_g": (folder_paths.get_filename_list("clip"), ), "clip_l": (folder_paths.get_filename_list("clip"), ), "t5xxl": (folder_paths.get_filename_list("clip"), )}}
FUNCTION = "main"
def main(self, clip_g, clip_l, t5xxl):
return self.load_clip(clip_g, clip_l, t5xxl)
@@ -0,0 +1,416 @@
{
"last_node_id": 8,
"last_link_id": 10,
"nodes": [
{
"id": 6,
"type": "KSampler",
"pos": [
1662,
343
],
"size": {
"0": 315,
"1": 474
},
"flags": {},
"order": 5,
"mode": 0,
"inputs": [
{
"name": "model",
"type": "MODEL",
"link": 5
},
{
"name": "positive",
"type": "CONDITIONING",
"link": 4
},
{
"name": "negative",
"type": "CONDITIONING",
"link": 6,
"slot_index": 2
},
{
"name": "latent_image",
"type": "LATENT",
"link": 7,
"slot_index": 3
}
],
"outputs": [
{
"name": "LATENT",
"type": "LATENT",
"links": [
8
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "KSampler"
},
"widgets_values": [
0,
"fixed",
28,
4.5,
"dpmpp_2m",
"sgm_uniform",
1
]
},
{
"id": 2,
"type": "SD3LoadCLIPs",
"pos": [
703,
516
],
"size": {
"0": 315,
"1": 106
},
"flags": {},
"order": 0,
"mode": 0,
"outputs": [
{
"name": "CLIP",
"type": "CLIP",
"links": [
2,
3
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "SD3LoadCLIPs"
},
"widgets_values": [
"SD3/clip_g.safetensors",
"SD3/clip_l.safetensors",
"SD3/t5xxl_fp8_e4m3fn.safetensors"
],
"color": "#223",
"bgcolor": "#335"
},
{
"id": 7,
"type": "VAEDecode",
"pos": [
2024,
222
],
"size": {
"0": 210,
"1": 46
},
"flags": {},
"order": 6,
"mode": 0,
"inputs": [
{
"name": "samples",
"type": "LATENT",
"link": 8
},
{
"name": "vae",
"type": "VAE",
"link": 10,
"slot_index": 1
}
],
"outputs": [
{
"name": "IMAGE",
"type": "IMAGE",
"links": [
9
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "VAEDecode"
}
},
{
"id": 4,
"type": "CLIPTextEncode",
"pos": [
1156,
311
],
"size": {
"0": 400,
"1": 200
},
"flags": {},
"order": 3,
"mode": 0,
"inputs": [
{
"name": "clip",
"type": "CLIP",
"link": 2
}
],
"outputs": [
{
"name": "CONDITIONING",
"type": "CONDITIONING",
"links": [
4
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "CLIPTextEncode"
},
"widgets_values": [
"a male character with red eyes and long, flowing hair that appears to be made of ethereal, swirling patterns resembling the Northern Lights or Aurora Borealis. The background is dominated by deep blues and purples, creating a mysterious and dramatic atmosphere. The character's face is serene, with pale skin and striking features. He wears a dark-colored outfit with subtle patterns. The overall style of the artwork is reminiscent of fantasy or supernatural genres"
],
"color": "#232",
"bgcolor": "#353"
},
{
"id": 5,
"type": "CLIPTextEncode",
"pos": [
1151,
560
],
"size": {
"0": 409.60009765625,
"1": 111.199951171875
},
"flags": {},
"order": 4,
"mode": 0,
"inputs": [
{
"name": "clip",
"type": "CLIP",
"link": 3
}
],
"outputs": [
{
"name": "CONDITIONING",
"type": "CONDITIONING",
"links": [
6
],
"shape": 3
}
],
"properties": {
"Node name for S&R": "CLIPTextEncode"
},
"widgets_values": [
"bad quality, poor quality, doll, disfigured, jpg, toy, bad anatomy, missing limbs, missing fingers, 3d, cgi"
],
"color": "#322",
"bgcolor": "#533"
},
{
"id": 3,
"type": "SD3EmptyLatent",
"pos": [
1245,
732
],
"size": {
"0": 315,
"1": 82
},
"flags": {},
"order": 1,
"mode": 0,
"outputs": [
{
"name": "LATENT",
"type": "LATENT",
"links": [
7
],
"shape": 3
}
],
"properties": {
"Node name for S&R": "SD3EmptyLatent"
},
"widgets_values": [
"1280x768",
1
],
"color": "#223",
"bgcolor": "#335"
},
{
"id": 8,
"type": "PreviewImage",
"pos": [
2028,
338
],
"size": {
"0": 765.6002197265625,
"1": 482.199951171875
},
"flags": {},
"order": 7,
"mode": 0,
"inputs": [
{
"name": "images",
"type": "IMAGE",
"link": 9
}
],
"properties": {
"Node name for S&R": "PreviewImage"
}
},
{
"id": 1,
"type": "SD3LoadCheckpoint",
"pos": [
704,
217
],
"size": {
"0": 315,
"1": 102
},
"flags": {},
"order": 2,
"mode": 0,
"outputs": [
{
"name": "MODEL",
"type": "MODEL",
"links": [
5
],
"shape": 3,
"slot_index": 0
},
{
"name": "VAE",
"type": "VAE",
"links": [
10
],
"shape": 3
}
],
"properties": {
"Node name for S&R": "SD3LoadCheckpoint"
},
"widgets_values": [
"SD3/sd3_medium.safetensors",
3
],
"color": "#223",
"bgcolor": "#335"
}
],
"links": [
[
2,
2,
0,
4,
0,
"CLIP"
],
[
3,
2,
0,
5,
0,
"CLIP"
],
[
4,
4,
0,
6,
1,
"CONDITIONING"
],
[
5,
1,
0,
6,
0,
"MODEL"
],
[
6,
5,
0,
6,
2,
"CONDITIONING"
],
[
7,
3,
0,
6,
3,
"LATENT"
],
[
8,
6,
0,
7,
0,
"LATENT"
],
[
9,
7,
0,
8,
0,
"IMAGE"
],
[
10,
1,
1,
7,
1,
"VAE"
]
],
"groups": [],
"config": {},
"extra": {
"ds": {
"scale": 1,
"offset": [
-406.4000244140625,
-23.999969482421875
]
}
},
"version": 0.4
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

@@ -0,0 +1,3 @@
**/__pycache__
*.jit
*.pt
@@ -0,0 +1,674 @@
GNU 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.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
@@ -0,0 +1,160 @@
![ywes_](https://github.com/ZHO-ZHO-ZHO/ComfyUI-YoloWorld-EfficientSAM/assets/140084057/fff48236-8feb-48d6-946e-ba429111427f)
# ComfyUI YoloWorld-EfficientSAM
Unofficial implementation of [YOLO-World + EfficientSAM](https://huggingface.co/spaces/SkalskiP/YOLO-World) & [YOLO-World](https://github.com/AILab-CVC/YOLO-World) for ComfyUI
![Dingtalk_20240220201311](https://github.com/ZHO-ZHO-ZHO/ComfyUI-YoloWorld-EfficientSAM/assets/140084057/765c7b7b-1224-48f1-8a98-d05d438304d0)
## 项目介绍 | Info
- 对[YOLO-World + EfficientSAM](https://huggingface.co/spaces/SkalskiP/YOLO-World)的非官方实现
- 利用全新的 [YOLO-World](https://github.com/AILab-CVC/YOLO-World) 与 [EfficientSAM](https://github.com/yformer/EfficientSAM) 实现高效的对象检测 + 分割
- 版本:V2.0 新增蒙版分离 + 提取功能,支持选择指定蒙版单独输出,同时支持图像和视频(V1.0工作流已弃用)
<!---
同时支持图像与视频,还支持输出 mask 蒙版,增加了 [ltdrdata](https://github.com/ltdrdata) 提供的 YOLO_WORLD_SEGS 新节点
--->
# 视频演示
V2.0
https://github.com/ZHO-ZHO-ZHO/ComfyUI-YoloWorld-EfficientSAM/assets/140084057/c7803084-8864-4bc5-a23f-20a47cf66925
V1.0
https://github.com/ZHO-ZHO-ZHO/ComfyUI-YoloWorld-EfficientSAM/assets/140084057/ed51a9c7-0e06-4026-8946-04dd78aa712c
## 节点说明 | Features
- YOLO-World 模型加载 | 🔎Yoloworld Model Loader
- 支持 3 种官方模型:yolo_world/l, yolo_world/m, yolo_world/s,会自动下载并加载
- EfficientSAM 模型加载 | 🔎ESAM Model Loader
- 支持 CUDA 或 CPU
- 🆕检测 + 分割 | 🔎Yoloworld ESAM
- yolo_world_model:接入 YOLO-World 模型
- esam_model:接入 EfficientSAM 模型
- image:接入图像
- categories:检测 + 分割内容
- confidence_threshold:置信度阈值,降低可减少误检,增强模型对所需对象的敏感性。增加可最小化误报,防止模型识别不应识别的对象
- iou_threshold:IoU 阈值,降低数值可减少边界框的重叠,使检测过程更严格。增加数值将会允许更多的边界框重叠,适应更广泛的检测范围
- box_thickness:检测框厚度
- text_thickness:文字厚度
- text_scale:文字缩放
- with_confidence:是否显示检测对象的置信度
- with_class_agnostic_nms:是否抑制类别之间的重叠边界框
- with_segmentation:是否开启 EfficientSAM 进行实例分割
- mask_combined:是否合并(叠加)蒙版 mask,"是"则将所有 mask 叠加在一张图上输出,"否"则会将所有的蒙版单独输出
- mask_extracted:是否提取选定蒙版 mask,"是"则会将按照 mask_extracted_index 将所选序号的蒙版单独输出
- mask_extracted_index:选择蒙版 mask 序号
![Dingtalk_20240224154535](https://github.com/ZHO-ZHO-ZHO/ComfyUI-YoloWorld-EfficientSAM/assets/140084057/c23e6a1a-28e7-4612-afde-256f9b782051)
<!---
![Dingtalk_20240220175722](https://github.com/ZHO-ZHO-ZHO/ComfyUI-YoloWorld-EfficientSAM/assets/140084057/17b106a2-9b7f-4534-ae3d-b1e97501bc2e)
--->
- 🆕检测 + 分割 | 🔎Yoloworld ESAM Detector Provider (由 [ltdrdata](https://github.com/ltdrdata) 提供,感谢!)
- 可配合 Impact-Pack 一起使用
- yolo_world_model:接入 YOLO-World 模型
- esam_model:接入 EfficientSAM 模型
- categories:检测 + 分割内容
- iou_threshold:IoU 阈值
- with_class_agnostic_nms:是否抑制类别之间的重叠边界框
![306523112-ea37dfd0-7019-4207-af2a-aa3c9355b63e](https://github.com/ZHO-ZHO-ZHO/ComfyUI-YoloWorld-EfficientSAM/assets/140084057/b3124f33-2e6c-475d-8603-644d8e54a8c7)
## 安装 | Install
- 推荐使用管理器 ComfyUI Manager 安装(On the Way)
- 手动安装:
1. `cd custom_nodes`
2. `git clone https://github.com/ZHO-ZHO-ZHO/ComfyUI-YoloWorld-EfficientSAM`
3. `cd custom_nodes/ComfyUI-YoloWorld-EfficientSAM`
4. `pip install -r requirements.txt`
5. 重启 ComfyUI
- 模型下载:将 [EfficientSAM](https://huggingface.co/camenduru/YoloWorld-EfficientSAM/tree/main) 中的 efficient_sam_s_cpu.jit 和 efficient_sam_s_gpu.jit 下载到 custom_nodes/ComfyUI-YoloWorld-EfficientSAM 中
## 工作流 | Workflows
V2.0
- [V2.0 图片检测+分割](https://github.com/ZHO-ZHO-ZHO/ComfyUI-YoloWorld-EfficientSAM/blob/main/YOLO_World_EfficientSAM_WORKFLOWS/YoloWorld-EfficientSAM%20V2.0%20IMG%20%E3%80%90Zho%E3%80%91.json)
- [V2.0 视频检测+分割](https://github.com/ZHO-ZHO-ZHO/ComfyUI-YoloWorld-EfficientSAM/blob/main/YOLO_World_EfficientSAM_WORKFLOWS/YoloWorld-EfficientSAM%20V2.0%20VIDEO%20%E3%80%90Zho%E3%80%91.json)
V1.0
- 注意:V1.0 工作流不适用于 V2.0
- [V1.0 图片检测+分割](https://github.com/ZHO-ZHO-ZHO/ComfyUI-YoloWorld-EfficientSAM/blob/main/YOLO_World_EfficientSAM_WORKFLOWS/YoloWorld-EfficientSAM%20V1.0%20IMG%20%E3%80%90Zho%E3%80%91.json)
- [V1.0 视频检测+分割](https://github.com/ZHO-ZHO-ZHO/ComfyUI-YoloWorld-EfficientSAM/blob/main/YOLO_World_EfficientSAM_WORKFLOWS/YoloWorld-EfficientSAM%20V1.0%20VIDEO%20%E3%80%90Zho%E3%80%91.json)
## 更新日志
- 20240224
V2.0 新增蒙版分离 + 提取功能,支持选择指定蒙版单独输出,同时支持图像和视频
- 20240221
合并了由 [ltdrdata](https://github.com/ltdrdata) 提供的 🔎Yoloworld ESAM Detector Provider 节点
- 20240220
创建项目
V1.0 同时支持图像与视频的检测与分割,还支持输出 mask 蒙版
## Stars
[![Star History Chart](https://api.star-history.com/svg?repos=ZHO-ZHO-ZHO/ComfyUI-YoloWorld-EfficientSAM&type=Date)](https://star-history.com/#ZHO-ZHO-ZHO/ComfyUI-YoloWorld-EfficientSAM&Date)
## 关于我 | About me
📬 **联系我**:
- 邮箱:zhozho3965@gmail.com
- QQ 群:839821928
🔗 **社交媒体**:
- 个人页:[-Zho-](https://jike.city/zho)
- Bilibili:[我的B站主页](https://space.bilibili.com/484366804)
- X(Twitter):[我的Twitter](https://twitter.com/ZHOZHO672070)
- 小红书:[我的小红书主页](https://www.xiaohongshu.com/user/profile/63f11530000000001001e0c8?xhsshare=CopyLink&appuid=63f11530000000001001e0c8&apptime=1690528872)
💡 **支持我**:
- B站:[B站充电](https://space.bilibili.com/484366804)
- 爱发电:[为我充电](https://afdian.net/a/ZHOZHO)
## Credits
[YOLO-World + EfficientSAM](https://huggingface.co/spaces/SkalskiP/YOLO-World)
[YOLO-World](https://github.com/AILab-CVC/YOLO-World)
[EfficientSAM](https://github.com/yformer/EfficientSAM)
代码还参考了 [@camenduru](https://twitter.com/camenduru) 感谢!
[ltdrdata](https://github.com/ltdrdata) 提供了 🔎Yoloworld ESAM Detector Provider 节点,感谢!
@@ -0,0 +1,216 @@
from typing import List
import folder_paths
import os
import cv2
import numpy as np
import supervision as sv
import torch
from tqdm import tqdm
from inference.models import YOLOWorld
from ultralytics import YOLO
from .utils.efficient_sam import load, inference_with_boxes
from .utils.video import generate_file_name, calculate_end_frame_index, create_directory
current_directory = os.path.dirname(os.path.abspath(__file__))
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
BOUNDING_BOX_ANNOTATOR = sv.BoundingBoxAnnotator()
MASK_ANNOTATOR = sv.MaskAnnotator()
LABEL_ANNOTATOR = sv.LabelAnnotator()
folder_paths.folder_names_and_paths["yolo_world"] = ([os.path.join(folder_paths.models_dir, "yolo_world")], folder_paths.supported_pt_extensions)
def process_categories(categories: str) -> List[str]:
return [category.strip() for category in categories.split(',')]
def annotate_image(
input_image: np.ndarray,
detections: sv.Detections,
categories: List[str],
with_confidence: bool = False,
thickness: int = 2,
text_thickness: int = 2,
text_scale: float = 1.0,
) -> np.ndarray:
labels = [
(
f"{bbox_id}-{categories[class_id]}: {confidence:.3f}"
if with_confidence
else f"{bbox_id}-{categories[class_id]}"
)
for bbox_id, class_id, confidence in
zip(range(len(detections.class_id)), detections.class_id, detections.confidence)
]
BOUNDING_BOX_ANNOTATOR = sv.BoundingBoxAnnotator(thickness=thickness)
LABEL_ANNOTATOR = sv.LabelAnnotator(text_thickness=text_thickness, text_scale=text_scale)
output_image = MASK_ANNOTATOR.annotate(input_image, detections)
output_image = BOUNDING_BOX_ANNOTATOR.annotate(output_image, detections)
output_image = LABEL_ANNOTATOR.annotate(output_image, detections, labels=labels)
return output_image
class Yoloworld_ModelLoader_Zho:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"yolo_world_model": (["yolo_world/l", "yolo_world/m", "yolo_world/s"], ),
}
}
RETURN_TYPES = ("YOLOWORLDMODEL",)
RETURN_NAMES = ("yolo_world_model",)
FUNCTION = "load_yolo_world_model"
CATEGORY = "🔎YOLOWORLD_ESAM"
def load_yolo_world_model(self, yolo_world_model):
YOLO_WORLD_MODEL = YOLOWorld(model_id=yolo_world_model)
return [YOLO_WORLD_MODEL]
class ESAM_ModelLoader_Zho:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"device": (["CUDA", "CPU"], ),
}
}
RETURN_TYPES = ("ESAMMODEL",)
RETURN_NAMES = ("esam_model",)
FUNCTION = "load_esam_model"
CATEGORY = "🔎YOLOWORLD_ESAM"
def load_esam_model(self, device):
if device == "CUDA":
model_path = os.path.join(current_directory, "efficient_sam_s_gpu.jit")
else:
model_path = os.path.join(current_directory, "efficient_sam_s_cpu.jit")
EFFICIENT_SAM_MODEL = torch.jit.load(model_path)
return [EFFICIENT_SAM_MODEL]
class Yoloworld_ESAM_Zho:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"yolo_world_model": ("YOLOWORLDMODEL",),
"esam_model": ("ESAMMODEL",),
"image": ("IMAGE",),
"categories": ("STRING", {"default": "person, bicycle, car, motorcycle, airplane, bus, train, truck, boat", "multiline": True}),
"confidence_threshold": ("FLOAT", {"default": 0.1, "min": 0, "max": 1, "step":0.01}),
"iou_threshold": ("FLOAT", {"default": 0.1, "min": 0, "max": 1, "step":0.01}),
"box_thickness": ("INT", {"default": 2, "min": 1, "max": 5}),
"text_thickness": ("INT", {"default": 2, "min": 1, "max": 5}),
"text_scale": ("FLOAT", {"default": 1.0, "min": 0, "max": 1, "step":0.01}),
"with_confidence": ("BOOLEAN", {"default": True}),
"with_class_agnostic_nms": ("BOOLEAN", {"default": False}),
"with_segmentation": ("BOOLEAN", {"default": True}),
"mask_combined": ("BOOLEAN", {"default": True}),
"mask_extracted": ("BOOLEAN", {"default": True}),
"mask_extracted_index": ("INT", {"default": 0, "min": 0, "max": 1000}),
}
}
RETURN_TYPES = ("IMAGE", "MASK", "STRING", "STRING")
RETURN_NAMES = ("IMAGE", "MASK", "BBOX", "CATEGORIES")
FUNCTION = "yoloworld_esam_image"
CATEGORY = "🔎YOLOWORLD_ESAM"
def yoloworld_esam_image(self, image, yolo_world_model, esam_model, categories, confidence_threshold, iou_threshold, box_thickness, text_thickness, text_scale, with_segmentation, mask_combined, with_confidence, with_class_agnostic_nms, mask_extracted, mask_extracted_index):
categories = process_categories(categories)
processed_images = []
processed_masks = []
for img in image:
img = np.clip(255. * img.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)
YOLO_WORLD_MODEL = yolo_world_model
YOLO_WORLD_MODEL.set_classes(categories)
results = YOLO_WORLD_MODEL.infer(img, confidence=confidence_threshold)
detections = sv.Detections.from_inference(results)
detections = detections.with_nms(
class_agnostic=with_class_agnostic_nms,
threshold=iou_threshold
)
combined_mask = None
if with_segmentation:
detections.mask = inference_with_boxes(
image=img,
xyxy=detections.xyxy,
model=esam_model,
device=DEVICE
)
if mask_combined:
combined_mask = np.zeros(img.shape[:2], dtype=np.uint8)
det_mask = detections.mask
for mask in det_mask:
combined_mask = np.logical_or(combined_mask, mask).astype(np.uint8)
masks_tensor = torch.tensor(combined_mask, dtype=torch.float32)
processed_masks.append(masks_tensor)
else:
det_mask = detections.mask
if mask_extracted:
mask_index = mask_extracted_index
selected_mask = det_mask[mask_index]
masks_tensor = torch.tensor(selected_mask, dtype=torch.float32)
else:
masks_tensor = torch.tensor(det_mask, dtype=torch.float32)
processed_masks.append(masks_tensor)
output_image = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
bbox_string = ""
for i in range(len(detections.xyxy)):
bbox_string += f"ID: {i} - " + ",".join(map(str, detections.xyxy[i])) + ';\n'
output_image = annotate_image(
input_image=output_image,
detections=detections,
categories=categories,
with_confidence=with_confidence,
thickness=box_thickness,
text_thickness=text_thickness,
text_scale=text_scale,
)
output_image = cv2.cvtColor(output_image, cv2.COLOR_BGR2RGB)
output_image = torch.from_numpy(output_image.astype(np.float32) / 255.0).unsqueeze(0)
processed_images.append(output_image)
new_ims = torch.cat(processed_images, dim=0)
if processed_masks:
new_masks = torch.stack(processed_masks, dim=0)
else:
new_masks = torch.empty(0)
return new_ims, new_masks, bbox_string, categories
NODE_CLASS_MAPPINGS = {
"Yoloworld_ModelLoader_Zho": Yoloworld_ModelLoader_Zho,
"ESAM_ModelLoader_Zho": ESAM_ModelLoader_Zho,
"Yoloworld_ESAM_Zho": Yoloworld_ESAM_Zho,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"Yoloworld_ModelLoader_Zho": "🔎Yoloworld Model Loader",
"ESAM_ModelLoader_Zho": "🔎ESAM Model Loader",
"Yoloworld_ESAM_Zho": "🔎Yoloworld ESAM",
}
@@ -0,0 +1,322 @@
from .YOLO_WORLD_EfficientSAM import *
from collections import namedtuple
from PIL import Image
SEG = namedtuple("SEG",
['cropped_image', 'cropped_mask', 'confidence', 'crop_region', 'bbox', 'label', 'control_net_wrapper'],
defaults=[None])
def crop_ndarray4(npimg, crop_region):
x1 = crop_region[0]
y1 = crop_region[1]
x2 = crop_region[2]
y2 = crop_region[3]
cropped = npimg[:, y1:y2, x1:x2, :]
return cropped
def crop_ndarray2(npimg, crop_region):
x1 = crop_region[0]
y1 = crop_region[1]
x2 = crop_region[2]
y2 = crop_region[3]
cropped = npimg[y1:y2, x1:x2]
return cropped
crop_tensor4 = crop_ndarray4
def crop_image(image, crop_region):
return crop_tensor4(image, crop_region)
def create_segmasks(results):
bboxs = results[1]
segms = results[2]
confidence = results[3]
results = []
for i in range(len(segms)):
item = (bboxs[i], segms[i].astype(np.float32), confidence[i])
results.append(item)
return results
def dilate_masks(segmasks, dilation_factor, iter=1):
if dilation_factor == 0:
return segmasks
dilated_masks = []
kernel = np.ones((abs(dilation_factor), abs(dilation_factor)), np.uint8)
for i in range(len(segmasks)):
cv2_mask = segmasks[i][1]
if dilation_factor > 0:
dilated_mask = cv2.dilate(cv2_mask, kernel, iter)
else:
dilated_mask = cv2.erode(cv2_mask, kernel, iter)
item = (segmasks[i][0], dilated_mask, segmasks[i][2])
dilated_masks.append(item)
return dilated_masks
def make_crop_region(w, h, bbox, crop_factor, crop_min_size=None):
x1 = bbox[0]
y1 = bbox[1]
x2 = bbox[2]
y2 = bbox[3]
bbox_w = x2 - x1
bbox_h = y2 - y1
crop_w = bbox_w * crop_factor
crop_h = bbox_h * crop_factor
if crop_min_size is not None:
crop_w = max(crop_min_size, crop_w)
crop_h = max(crop_min_size, crop_h)
kernel_x = x1 + bbox_w / 2
kernel_y = y1 + bbox_h / 2
new_x1 = int(kernel_x - crop_w / 2)
new_y1 = int(kernel_y - crop_h / 2)
# make sure position in (w,h)
new_x1, new_x2 = normalize_region(w, new_x1, crop_w)
new_y1, new_y2 = normalize_region(h, new_y1, crop_h)
return [new_x1, new_y1, new_x2, new_y2]
def normalize_region(limit, startp, size):
if startp < 0:
new_endp = min(limit, size)
new_startp = 0
elif startp + size > limit:
new_startp = max(0, limit - size)
new_endp = limit
else:
new_startp = startp
new_endp = min(limit, startp+size)
return int(new_startp), int(new_endp)
def combine_masks(masks):
if len(masks) == 0:
return None
else:
initial_cv2_mask = np.array(masks[0][1])
combined_cv2_mask = initial_cv2_mask
for i in range(1, len(masks)):
cv2_mask = np.array(masks[i][1])
if combined_cv2_mask.shape == cv2_mask.shape:
combined_cv2_mask = cv2.bitwise_or(combined_cv2_mask, cv2_mask)
else:
# do nothing - incompatible mask
pass
mask = torch.from_numpy(combined_cv2_mask)
return mask
def inference_bbox(yolo_world_model, categories, iou_threshold, with_class_agnostic_nms, image, confidence):
img = np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)
yolo_world_model.set_classes(categories)
results = yolo_world_model.infer(img, confidence=confidence)
detections = sv.Detections.from_inference(results)
detections = detections.with_nms(class_agnostic=with_class_agnostic_nms, threshold=iou_threshold)
bboxes = detections.xyxy
cv2_image = np.array(img)
if len(cv2_image.shape) == 3:
cv2_image = cv2_image[:, :, ::-1].copy() # Convert RGB to BGR for cv2 processing
else:
# Handle the grayscale image here
# For example, you might want to convert it to a 3-channel grayscale image for consistency:
cv2_image = cv2.cvtColor(cv2_image, cv2.COLOR_GRAY2BGR)
cv2_gray = cv2.cvtColor(cv2_image, cv2.COLOR_BGR2GRAY)
segms = []
for x0, y0, x1, y1 in bboxes:
cv2_mask = np.zeros(cv2_gray.shape, np.uint8)
cv2.rectangle(cv2_mask, (int(x0), int(y0)), (int(x1), int(y1)), 255, -1)
cv2_mask_bool = cv2_mask.astype(bool)
segms.append(cv2_mask_bool)
n, m = bboxes.shape
if n == 0:
return [[], [], [], []]
results = [[], [], [], []]
for i in range(len(bboxes)):
results[0].append(detections.data['class_name'][i])
results[1].append(bboxes[i])
results[2].append(segms[i])
results[3].append(detections.confidence[i])
return results
def inference_segm(yolo_world_model, esam_model, categories, iou_threshold, with_class_agnostic_nms, image, confidence):
img = np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)
yolo_world_model.set_classes(categories)
results = yolo_world_model.infer(img, confidence=confidence)
detections = sv.Detections.from_inference(results)
detections = detections.with_nms(class_agnostic=with_class_agnostic_nms, threshold=iou_threshold)
segms = inference_with_boxes(
image=img,
xyxy=detections.xyxy,
model=esam_model,
device=DEVICE
)
bboxes = detections.xyxy
n, m = bboxes.shape
if n == 0:
return [[], [], [], []]
results = [[], [], [], []]
for i in range(len(bboxes)):
results[0].append(detections.data['class_name'][i])
results[1].append(bboxes[i])
mask = torch.from_numpy(segms[i])
scaled_mask = torch.nn.functional.interpolate(mask.float().unsqueeze(0).unsqueeze(0), size=(img.shape[0], img.shape[1]), mode='bilinear', align_corners=False)
scaled_mask = scaled_mask.squeeze().squeeze()
results[2].append(scaled_mask.numpy())
results[3].append(detections.confidence[i])
return results
class YoloworldBboxDetector:
def __init__(self, yolo_world_model, categories, iou_threshold, with_class_agnostic_nms):
self.yolo_world_model = yolo_world_model
self.categories = process_categories(categories)
self.iou_threshold = iou_threshold
self.with_class_agnostic_nms = with_class_agnostic_nms
def detect(self, image, threshold, dilation, crop_factor, drop_size=1, detailer_hook=None, esam_model=None):
drop_size = max(drop_size, 1)
if esam_model is None:
detected_results = inference_bbox(self.yolo_world_model, self.categories, self.iou_threshold, self.with_class_agnostic_nms, image, threshold)
else:
detected_results = inference_segm(self.yolo_world_model, esam_model, self.categories, self.iou_threshold, self.with_class_agnostic_nms, image, threshold)
segmasks = create_segmasks(detected_results)
if dilation > 0:
segmasks = dilate_masks(segmasks, dilation)
items = []
h = image.shape[1]
w = image.shape[2]
for x, label in zip(segmasks, detected_results[0]):
item_bbox = x[0]
item_mask = x[1]
y1, x1, y2, x2 = item_bbox
if x2 - x1 > drop_size and y2 - y1 > drop_size: # minimum dimension must be (2,2) to avoid squeeze issue
crop_region = make_crop_region(w, h, item_bbox, crop_factor)
if detailer_hook is not None:
crop_region = detailer_hook.post_crop_region(w, h, item_bbox, crop_region)
cropped_image = crop_image(image, crop_region)
cropped_mask = crop_ndarray2(item_mask, crop_region)
confidence = x[2]
item = SEG(cropped_image, cropped_mask, confidence, crop_region, item_bbox, label, None)
items.append(item)
shape = image.shape[1], image.shape[2]
segs = shape, items
if detailer_hook is not None and hasattr(detailer_hook, "post_detection"):
segs = detailer_hook.post_detection(segs)
return segs
def detect_combined(self, image, threshold, dilation):
detected_results = inference_bbox(self.yolo_world_model, self.categories, self.iou_threshold, self.with_class_agnostic_nms, image, threshold)
segmasks = create_segmasks(detected_results)
if dilation > 0:
segmasks = dilate_masks(segmasks, dilation)
return combine_masks(segmasks)
class YoloworldSegmDetector:
def __init__(self, bbox_detector, esam_model):
self.bbox_detector = bbox_detector
self.esam_model = esam_model
def detect(self, image, threshold, dilation, crop_factor, drop_size=1, detailer_hook=None):
return self.bbox_detector.detect(image, threshold, dilation, crop_factor, drop_size, detailer_hook=detailer_hook, esam_model=self.esam_model)
def detect_combined(self, image, threshold, dilation):
bb = self.bbox_detector
detected_results = inference_segm(bb.yolo_world_model, self.esam_model, bb.categories, bb.iou_threshold, bb.with_class_agnostic_nms, image, threshold)
segmasks = create_segmasks(detected_results)
if dilation > 0:
segmasks = dilate_masks(segmasks, dilation)
return combine_masks(segmasks)
class Yoloworld_ESAM_DetectorProvider_Zho:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"yolo_world_model": ("YOLOWORLDMODEL",),
"categories": ("STRING", {"default": "", "placeholder": "Please enter the objects to be detected separated by commas.", "multiline": True}),
"iou_threshold": ("FLOAT", {"default": 0.1, "min": 0, "max": 1, "step": 0.01}),
"with_class_agnostic_nms": ("BOOLEAN", {"default": False}),
},
"optional": {
"esam_model_opt": ("ESAMMODEL",),
}
}
RETURN_TYPES = ("BBOX_DETECTOR", "SEGM_DETECTOR")
FUNCTION = "doit"
CATEGORY = "🔎YOLOWORLD_ESAM"
def doit(self, yolo_world_model, categories, iou_threshold, with_class_agnostic_nms, esam_model_opt=None):
bbox_detector = YoloworldBboxDetector(yolo_world_model, categories, iou_threshold, with_class_agnostic_nms)
if esam_model_opt is not None:
segm_detector = YoloworldSegmDetector(bbox_detector, esam_model_opt)
else:
segm_detector = None
return bbox_detector, segm_detector
NODE_CLASS_MAPPINGS = {
"Yoloworld_ESAM_DetectorProvider_Zho": Yoloworld_ESAM_DetectorProvider_Zho,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"Yoloworld_ESAM_DetectorProvider_Zho": "🔎Yoloworld ESAM Detector Provider",
}
@@ -0,0 +1,316 @@
{
"last_node_id": 26,
"last_link_id": 37,
"nodes": [
{
"id": 21,
"type": "LoadImage",
"pos": [
530,
330
],
"size": {
"0": 440,
"1": 380
},
"flags": {},
"order": 0,
"mode": 0,
"outputs": [
{
"name": "IMAGE",
"type": "IMAGE",
"links": [
35
],
"shape": 3
},
{
"name": "MASK",
"type": "MASK",
"links": null,
"shape": 3
}
],
"properties": {
"Node name for S&R": "LoadImage"
},
"widgets_values": [
"2109241Z5045350-0-lp.jpg",
"image"
]
},
{
"id": 11,
"type": "PreviewImage",
"pos": [
1080,
760
],
"size": {
"0": 440,
"1": 320
},
"flags": {},
"order": 6,
"mode": 0,
"inputs": [
{
"name": "images",
"type": "IMAGE",
"link": 13
}
],
"properties": {
"Node name for S&R": "PreviewImage"
}
},
{
"id": 25,
"type": "Yoloworld_ESAM_Zho",
"pos": [
800,
760
],
"size": {
"0": 260,
"1": 320
},
"flags": {},
"order": 3,
"mode": 0,
"inputs": [
{
"name": "yolo_world_model",
"type": "YOLOWORLDMODEL",
"link": 33
},
{
"name": "esam_model",
"type": "ESAMMODEL",
"link": 34,
"slot_index": 1
},
{
"name": "image",
"type": "IMAGE",
"link": 35,
"slot_index": 2
}
],
"outputs": [
{
"name": "IMAGE",
"type": "IMAGE",
"links": [
36
],
"shape": 3,
"slot_index": 0
},
{
"name": "MASK",
"type": "MASK",
"links": [
37
],
"shape": 3,
"slot_index": 1
}
],
"properties": {
"Node name for S&R": "Yoloworld_ESAM_Zho"
},
"widgets_values": [
"man, woman, bag, dog, car, glass, light,building\n",
0.01,
0.1,
2,
2,
1,
true,
true,
false
]
},
{
"id": 10,
"type": "MaskToImage",
"pos": [
530,
1020
],
"size": {
"0": 250,
"1": 60
},
"flags": {},
"order": 5,
"mode": 0,
"inputs": [
{
"name": "mask",
"type": "MASK",
"link": 37,
"slot_index": 0
}
],
"outputs": [
{
"name": "IMAGE",
"type": "IMAGE",
"links": [
13
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "MaskToImage"
}
},
{
"id": 26,
"type": "ESAM_ModelLoader_Zho",
"pos": [
530,
890
],
"size": {
"0": 250,
"1": 80
},
"flags": {},
"order": 1,
"mode": 0,
"outputs": [
{
"name": "esam_model",
"type": "ESAMMODEL",
"links": [
34
],
"shape": 3
}
],
"properties": {
"Node name for S&R": "ESAM_ModelLoader_Zho"
},
"widgets_values": [
"CUDA"
]
},
{
"id": 24,
"type": "Yoloworld_ModelLoader_Zho",
"pos": [
530,
760
],
"size": {
"0": 250,
"1": 80
},
"flags": {},
"order": 2,
"mode": 0,
"outputs": [
{
"name": "yolo_world_model",
"type": "YOLOWORLDMODEL",
"links": [
33
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "Yoloworld_ModelLoader_Zho"
},
"widgets_values": [
"yolo_world/l"
]
},
{
"id": 9,
"type": "PreviewImage",
"pos": [
990,
330
],
"size": {
"0": 530,
"1": 380
},
"flags": {},
"order": 4,
"mode": 0,
"inputs": [
{
"name": "images",
"type": "IMAGE",
"link": 36
}
],
"properties": {
"Node name for S&R": "PreviewImage"
}
}
],
"links": [
[
13,
10,
0,
11,
0,
"IMAGE"
],
[
33,
24,
0,
25,
0,
"YOLOWORLDMODEL"
],
[
34,
26,
0,
25,
1,
"ESAMMODEL"
],
[
35,
21,
0,
25,
2,
"IMAGE"
],
[
36,
25,
0,
9,
0,
"IMAGE"
],
[
37,
25,
1,
10,
0,
"MASK"
]
],
"groups": [],
"config": {},
"extra": {},
"version": 0.4
}
@@ -0,0 +1,427 @@
{
"last_node_id": 26,
"last_link_id": 37,
"nodes": [
{
"id": 18,
"type": "VHS_VideoCombine",
"pos": [
950,
1610
],
"size": [
1340,
1046.5
],
"flags": {},
"order": 6,
"mode": 0,
"inputs": [
{
"name": "images",
"type": "IMAGE",
"link": 25
},
{
"name": "audio",
"type": "VHS_AUDIO",
"link": null
},
{
"name": "batch_manager",
"type": "VHS_BatchManager",
"link": null
}
],
"outputs": [
{
"name": "Filenames",
"type": "VHS_FILENAMES",
"links": null,
"shape": 3
}
],
"properties": {
"Node name for S&R": "VHS_VideoCombine"
},
"widgets_values": {
"frame_rate": 30,
"loop_count": 0,
"filename_prefix": "YWES",
"format": "video/h264-mp4",
"pix_fmt": "yuv420p",
"crf": 19,
"save_metadata": true,
"pingpong": false,
"save_output": true,
"videopreview": {
"hidden": false,
"paused": false,
"params": {
"filename": "YWES_00010.mp4",
"subfolder": "",
"type": "output",
"format": "video/h264-mp4"
}
}
}
},
{
"id": 15,
"type": "VHS_LoadVideo",
"pos": [
660,
510
],
"size": [
270.17620849609375,
396.72411727905273
],
"flags": {},
"order": 0,
"mode": 0,
"inputs": [
{
"name": "batch_manager",
"type": "VHS_BatchManager",
"link": null
}
],
"outputs": [
{
"name": "IMAGE",
"type": "IMAGE",
"links": [
36
],
"shape": 3,
"slot_index": 0
},
{
"name": "frame_count",
"type": "INT",
"links": null,
"shape": 3
},
{
"name": "audio",
"type": "VHS_AUDIO",
"links": null,
"shape": 3
}
],
"properties": {
"Node name for S&R": "VHS_LoadVideo"
},
"widgets_values": {
"video": "tokyo-walk.mp4",
"force_rate": 0,
"force_size": "Disabled",
"custom_width": 512,
"custom_height": 512,
"frame_load_cap": 90,
"skip_first_frames": 0,
"select_every_nth": 1,
"choose video to upload": "image",
"videopreview": {
"hidden": false,
"paused": false,
"params": {
"frame_load_cap": 90,
"skip_first_frames": 0,
"force_rate": 0,
"select_every_nth": 1,
"filename": "tokyo-walk.mp4",
"type": "input",
"format": "video/mp4"
}
}
}
},
{
"id": 24,
"type": "Yoloworld_ESAM_Zho",
"pos": [
660,
1250
],
"size": [
270,
307.9999542236328
],
"flags": {},
"order": 3,
"mode": 0,
"inputs": [
{
"name": "yolo_world_model",
"type": "YOLOWORLDMODEL",
"link": 33,
"slot_index": 0
},
{
"name": "esam_model",
"type": "ESAMMODEL",
"link": 34,
"slot_index": 1
},
{
"name": "image",
"type": "IMAGE",
"link": 36
}
],
"outputs": [
{
"name": "IMAGE",
"type": "IMAGE",
"links": [
35
],
"shape": 3,
"slot_index": 0
},
{
"name": "MASK",
"type": "MASK",
"links": [
37
],
"shape": 3,
"slot_index": 1
}
],
"properties": {
"Node name for S&R": "Yoloworld_ESAM_Zho"
},
"widgets_values": [
"person, bag",
0.01,
0.1,
2,
2,
1,
true,
true,
false
]
},
{
"id": 25,
"type": "Yoloworld_ModelLoader_Zho",
"pos": [
660,
950
],
"size": [
270,
60
],
"flags": {},
"order": 1,
"mode": 0,
"outputs": [
{
"name": "yolo_world_model",
"type": "YOLOWORLDMODEL",
"links": [
33
],
"shape": 3
}
],
"properties": {
"Node name for S&R": "Yoloworld_ModelLoader_Zho"
},
"widgets_values": [
"yolo_world/l"
]
},
{
"id": 26,
"type": "ESAM_ModelLoader_Zho",
"pos": [
660,
1060
],
"size": [
270,
60
],
"flags": {},
"order": 2,
"mode": 0,
"outputs": [
{
"name": "esam_model",
"type": "ESAMMODEL",
"links": [
34
],
"shape": 3
}
],
"properties": {
"Node name for S&R": "ESAM_ModelLoader_Zho"
},
"widgets_values": [
"CUDA"
]
},
{
"id": 6,
"type": "MaskToImage",
"pos": [
660,
1170
],
"size": {
"0": 270,
"1": 30
},
"flags": {},
"order": 5,
"mode": 0,
"inputs": [
{
"name": "mask",
"type": "MASK",
"link": 37,
"slot_index": 0
}
],
"outputs": [
{
"name": "IMAGE",
"type": "IMAGE",
"links": [
25
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "MaskToImage"
}
},
{
"id": 14,
"type": "VHS_VideoCombine",
"pos": [
950,
510
],
"size": [
1340,
1046.5
],
"flags": {},
"order": 4,
"mode": 0,
"inputs": [
{
"name": "images",
"type": "IMAGE",
"link": 35
},
{
"name": "audio",
"type": "VHS_AUDIO",
"link": null
},
{
"name": "batch_manager",
"type": "VHS_BatchManager",
"link": null
}
],
"outputs": [
{
"name": "Filenames",
"type": "VHS_FILENAMES",
"links": null,
"shape": 3
}
],
"properties": {
"Node name for S&R": "VHS_VideoCombine"
},
"widgets_values": {
"frame_rate": 30,
"loop_count": 0,
"filename_prefix": "YWES",
"format": "video/h264-mp4",
"pix_fmt": "yuv420p",
"crf": 19,
"save_metadata": true,
"pingpong": false,
"save_output": true,
"videopreview": {
"hidden": false,
"paused": false,
"params": {
"filename": "YWES_00009.mp4",
"subfolder": "",
"type": "output",
"format": "video/h264-mp4"
}
}
}
}
],
"links": [
[
25,
6,
0,
18,
0,
"IMAGE"
],
[
33,
25,
0,
24,
0,
"YOLOWORLDMODEL"
],
[
34,
26,
0,
24,
1,
"ESAMMODEL"
],
[
35,
24,
0,
14,
0,
"IMAGE"
],
[
36,
15,
0,
24,
2,
"IMAGE"
],
[
37,
24,
1,
6,
0,
"MASK"
]
],
"groups": [],
"config": {},
"extra": {},
"version": 0.4
}
@@ -0,0 +1,319 @@
{
"last_node_id": 24,
"last_link_id": 29,
"nodes": [
{
"id": 4,
"type": "LoadImage",
"pos": [
600,
-120
],
"size": {
"0": 480,
"1": 420
},
"flags": {},
"order": 0,
"mode": 0,
"outputs": [
{
"name": "IMAGE",
"type": "IMAGE",
"links": [
3
],
"shape": 3
},
{
"name": "MASK",
"type": "MASK",
"links": null,
"shape": 3
}
],
"properties": {
"Node name for S&R": "LoadImage"
},
"widgets_values": [
"u=1154228993,2450352963&fm=253&fmt=auto&app=138&f=JPEG.webp",
"image"
]
},
{
"id": 5,
"type": "PreviewImage",
"pos": [
1100,
-120
],
"size": {
"0": 590,
"1": 420
},
"flags": {},
"order": 4,
"mode": 0,
"inputs": [
{
"name": "images",
"type": "IMAGE",
"link": 4
}
],
"properties": {
"Node name for S&R": "PreviewImage"
}
},
{
"id": 6,
"type": "MaskToImage",
"pos": [
600,
660
],
"size": {
"0": 260,
"1": 80
},
"flags": {},
"order": 5,
"mode": 0,
"inputs": [
{
"name": "mask",
"type": "MASK",
"link": 5,
"slot_index": 0
}
],
"outputs": [
{
"name": "IMAGE",
"type": "IMAGE",
"links": [
6
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "MaskToImage"
}
},
{
"id": 3,
"type": "ESAM_ModelLoader_Zho",
"pos": [
600,
510
],
"size": {
"0": 260,
"1": 100
},
"flags": {},
"order": 1,
"mode": 0,
"outputs": [
{
"name": "esam_model",
"type": "ESAMMODEL",
"links": [
2
],
"shape": 3
}
],
"properties": {
"Node name for S&R": "ESAM_ModelLoader_Zho"
},
"widgets_values": [
"CUDA"
]
},
{
"id": 1,
"type": "Yoloworld_ModelLoader_Zho",
"pos": [
600,
350
],
"size": {
"0": 260,
"1": 110
},
"flags": {},
"order": 2,
"mode": 0,
"outputs": [
{
"name": "yolo_world_model",
"type": "YOLOWORLDMODEL",
"links": [
1
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "Yoloworld_ModelLoader_Zho"
},
"widgets_values": [
"yolo_world/l"
]
},
{
"id": 7,
"type": "PreviewImage",
"pos": [
1190,
350
],
"size": {
"0": 500,
"1": 390
},
"flags": {},
"order": 6,
"mode": 0,
"inputs": [
{
"name": "images",
"type": "IMAGE",
"link": 6
}
],
"properties": {
"Node name for S&R": "PreviewImage"
}
},
{
"id": 2,
"type": "Yoloworld_ESAM_Zho",
"pos": [
880,
350
],
"size": {
"0": 290,
"1": 390
},
"flags": {},
"order": 3,
"mode": 0,
"inputs": [
{
"name": "yolo_world_model",
"type": "YOLOWORLDMODEL",
"link": 1
},
{
"name": "esam_model",
"type": "ESAMMODEL",
"link": 2,
"slot_index": 1
},
{
"name": "image",
"type": "IMAGE",
"link": 3,
"slot_index": 2
}
],
"outputs": [
{
"name": "IMAGE",
"type": "IMAGE",
"links": [
4
],
"shape": 3,
"slot_index": 0
},
{
"name": "MASK",
"type": "MASK",
"links": [
5
],
"shape": 3,
"slot_index": 1
}
],
"properties": {
"Node name for S&R": "Yoloworld_ESAM_Zho"
},
"widgets_values": [
"glasses, bag, person, bicycle, car, motorcycle, bus, train, truck",
0.1,
0.1,
1,
1,
0.8,
true,
false,
true,
false,
false,
4
]
}
],
"links": [
[
1,
1,
0,
2,
0,
"YOLOWORLDMODEL"
],
[
2,
3,
0,
2,
1,
"ESAMMODEL"
],
[
3,
4,
0,
2,
2,
"IMAGE"
],
[
4,
2,
0,
5,
0,
"IMAGE"
],
[
5,
2,
1,
6,
0,
"MASK"
],
[
6,
6,
0,
7,
0,
"IMAGE"
]
],
"groups": [],
"config": {},
"extra": {},
"version": 0.4
}
@@ -0,0 +1,431 @@
{
"last_node_id": 27,
"last_link_id": 42,
"nodes": [
{
"id": 18,
"type": "VHS_VideoCombine",
"pos": [
950,
1610
],
"size": [
1340,
1046.5
],
"flags": {},
"order": 6,
"mode": 0,
"inputs": [
{
"name": "images",
"type": "IMAGE",
"link": 25
},
{
"name": "audio",
"type": "VHS_AUDIO",
"link": null
},
{
"name": "batch_manager",
"type": "VHS_BatchManager",
"link": null
}
],
"outputs": [
{
"name": "Filenames",
"type": "VHS_FILENAMES",
"links": null,
"shape": 3
}
],
"properties": {
"Node name for S&R": "VHS_VideoCombine"
},
"widgets_values": {
"frame_rate": 30,
"loop_count": 0,
"filename_prefix": "YWES",
"format": "video/h264-mp4",
"pix_fmt": "yuv420p",
"crf": 19,
"save_metadata": true,
"pingpong": false,
"save_output": true,
"videopreview": {
"hidden": false,
"paused": false,
"params": {
"filename": "YWES_00010.mp4",
"subfolder": "",
"type": "output",
"format": "video/h264-mp4"
}
}
}
},
{
"id": 15,
"type": "VHS_LoadVideo",
"pos": [
660,
510
],
"size": [
270.17620849609375,
242
],
"flags": {},
"order": 0,
"mode": 0,
"inputs": [
{
"name": "batch_manager",
"type": "VHS_BatchManager",
"link": null
}
],
"outputs": [
{
"name": "IMAGE",
"type": "IMAGE",
"links": [
40
],
"shape": 3,
"slot_index": 0
},
{
"name": "frame_count",
"type": "INT",
"links": null,
"shape": 3
},
{
"name": "audio",
"type": "VHS_AUDIO",
"links": null,
"shape": 3
}
],
"properties": {
"Node name for S&R": "VHS_LoadVideo"
},
"widgets_values": {
"video": "tokyo-walk.mp4",
"force_rate": 0,
"force_size": "Disabled",
"custom_width": 512,
"custom_height": 512,
"frame_load_cap": 90,
"skip_first_frames": 0,
"select_every_nth": 1,
"choose video to upload": "image",
"videopreview": {
"hidden": false,
"paused": false,
"params": {
"frame_load_cap": 90,
"skip_first_frames": 0,
"force_rate": 0,
"select_every_nth": 1,
"filename": "tokyo-walk.mp4",
"type": "input",
"format": "video/mp4"
}
}
}
},
{
"id": 6,
"type": "MaskToImage",
"pos": [
660,
1170
],
"size": {
"0": 270,
"1": 30
},
"flags": {},
"order": 5,
"mode": 0,
"inputs": [
{
"name": "mask",
"type": "MASK",
"link": 42,
"slot_index": 0
}
],
"outputs": [
{
"name": "IMAGE",
"type": "IMAGE",
"links": [
25
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "MaskToImage"
}
},
{
"id": 14,
"type": "VHS_VideoCombine",
"pos": [
950,
510
],
"size": [
1340,
1046.5
],
"flags": {},
"order": 4,
"mode": 0,
"inputs": [
{
"name": "images",
"type": "IMAGE",
"link": 41
},
{
"name": "audio",
"type": "VHS_AUDIO",
"link": null
},
{
"name": "batch_manager",
"type": "VHS_BatchManager",
"link": null
}
],
"outputs": [
{
"name": "Filenames",
"type": "VHS_FILENAMES",
"links": null,
"shape": 3
}
],
"properties": {
"Node name for S&R": "VHS_VideoCombine"
},
"widgets_values": {
"frame_rate": 30,
"loop_count": 0,
"filename_prefix": "YWES",
"format": "video/h264-mp4",
"pix_fmt": "yuv420p",
"crf": 19,
"save_metadata": true,
"pingpong": false,
"save_output": true,
"videopreview": {
"hidden": false,
"paused": false,
"params": {
"filename": "YWES_00009.mp4",
"subfolder": "",
"type": "output",
"format": "video/h264-mp4"
}
}
}
},
{
"id": 26,
"type": "ESAM_ModelLoader_Zho",
"pos": [
660,
1060
],
"size": {
"0": 270,
"1": 60
},
"flags": {},
"order": 1,
"mode": 0,
"outputs": [
{
"name": "esam_model",
"type": "ESAMMODEL",
"links": [
38
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "ESAM_ModelLoader_Zho"
},
"widgets_values": [
"CUDA"
]
},
{
"id": 25,
"type": "Yoloworld_ModelLoader_Zho",
"pos": [
660,
950
],
"size": {
"0": 270,
"1": 60
},
"flags": {},
"order": 2,
"mode": 0,
"outputs": [
{
"name": "yolo_world_model",
"type": "YOLOWORLDMODEL",
"links": [
39
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "Yoloworld_ModelLoader_Zho"
},
"widgets_values": [
"yolo_world/l"
]
},
{
"id": 27,
"type": "Yoloworld_ESAM_Zho",
"pos": [
660,
1250
],
"size": [
270,
400
],
"flags": {},
"order": 3,
"mode": 0,
"inputs": [
{
"name": "yolo_world_model",
"type": "YOLOWORLDMODEL",
"link": 39
},
{
"name": "esam_model",
"type": "ESAMMODEL",
"link": 38
},
{
"name": "image",
"type": "IMAGE",
"link": 40,
"slot_index": 2
}
],
"outputs": [
{
"name": "IMAGE",
"type": "IMAGE",
"links": [
41
],
"shape": 3,
"slot_index": 0
},
{
"name": "MASK",
"type": "MASK",
"links": [
42
],
"shape": 3,
"slot_index": 1
}
],
"properties": {
"Node name for S&R": "Yoloworld_ESAM_Zho"
},
"widgets_values": [
"person, bicycle, car, motorcycle, airplane, bus, train, truck, boat",
0.1,
0.1,
2,
2,
1,
true,
false,
true,
true,
true,
0
]
}
],
"links": [
[
25,
6,
0,
18,
0,
"IMAGE"
],
[
38,
26,
0,
27,
1,
"ESAMMODEL"
],
[
39,
25,
0,
27,
0,
"YOLOWORLDMODEL"
],
[
40,
15,
0,
27,
2,
"IMAGE"
],
[
41,
27,
0,
14,
0,
"IMAGE"
],
[
42,
27,
1,
6,
0,
"MASK"
]
],
"groups": [],
"config": {},
"extra": {},
"version": 0.4
}
@@ -0,0 +1,5 @@
from . import YOLO_WORLD_EfficientSAM
from . import YOLO_WORLD_SEGS
NODE_CLASS_MAPPINGS = {**YOLO_WORLD_EfficientSAM.NODE_CLASS_MAPPINGS, **YOLO_WORLD_SEGS.NODE_CLASS_MAPPINGS}
NODE_DISPLAY_NAME_MAPPINGS = {**YOLO_WORLD_EfficientSAM.NODE_DISPLAY_NAME_MAPPINGS, **YOLO_WORLD_SEGS.NODE_DISPLAY_NAME_MAPPINGS}
@@ -0,0 +1,183 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"from ultralytics import YOLO\n",
"\n",
"# Initialize a YOLO-World model\n",
"model = YOLO(\"yolov8l-world.pt\") # or choose yolov8m/l-world.pt"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"image 1/1 /home/minhducnguyen/WORK/ComfyUI/custom_nodes/ComfyUI-YoloWorld-EfficientSAM/manycups.jpg: 384x640 4 there is 3 cups in the image, detect the cup at the left mosts, 43.9ms\n",
"Speed: 5.3ms preprocess, 43.9ms inference, 2.7ms postprocess per image at shape (1, 3, 384, 640)\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"perl: warning: Setting locale failed.\n",
"perl: warning: Please check that your locale settings:\n",
"\tLANGUAGE = (unset),\n",
"\tLC_ALL = (unset),\n",
"\tLC_TIME = \"vi_VN\",\n",
"\tLC_MONETARY = \"vi_VN\",\n",
"\tLC_ADDRESS = \"vi_VN\",\n",
"\tLC_TELEPHONE = \"vi_VN\",\n",
"\tLC_NAME = \"vi_VN\",\n",
"\tLC_MEASUREMENT = \"vi_VN\",\n",
"\tLC_IDENTIFICATION = \"vi_VN\",\n",
"\tLC_NUMERIC = \"vi_VN\",\n",
"\tLC_PAPER = \"vi_VN\",\n",
"\tLANG = \"en_US.UTF-8\"\n",
" are supported and installed on your system.\n",
"perl: warning: Falling back to a fallback locale (\"en_US.UTF-8\").\n"
]
}
],
"source": [
"# Define custom classes\n",
"model.set_classes([\"there is 3 cups in the image, detect the cup at the left most\"])\n",
"\n",
"# Execute prediction for specified categories on an image\n",
"results = model.predict(\"manycups.jpg\")\n",
"\n",
"# Show results\n",
"results[0].show()"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"perl: warning: Setting locale failed.\n",
"perl: warning: Please check that your locale settings:\n",
"\tLANGUAGE = (unset),\n",
"\tLC_ALL = (unset),\n",
"\tLC_TIME = \"vi_VN\",\n",
"\tLC_MONETARY = \"vi_VN\",\n",
"\tLC_ADDRESS = \"vi_VN\",\n",
"\tLC_TELEPHONE = \"vi_VN\",\n",
"\tLC_NAME = \"vi_VN\",\n",
"\tLC_MEASUREMENT = \"vi_VN\",\n",
"\tLC_IDENTIFICATION = \"vi_VN\",\n",
"\tLC_NUMERIC = \"vi_VN\",\n",
"\tLC_PAPER = \"vi_VN\",\n",
"\tLANG = \"en_US.UTF-8\"\n",
" are supported and installed on your system.\n",
"perl: warning: Falling back to a fallback locale (\"en_US.UTF-8\").\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Creating inference sessions\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"UserWarning: Specified provider 'OpenVINOExecutionProvider' is not in available provider names.Available providers: 'TensorrtExecutionProvider, CUDAExecutionProvider, AzureExecutionProvider, CPUExecutionProvider'\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"CLIP model loaded in 2.09 seconds\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"\u001b[0;93m2024-08-22 12:23:42.474786966 [W:onnxruntime:, transformer_memcpy.cc:74 ApplyImpl] 3 Memcpy nodes are added to the graph torch_jit for CUDAExecutionProvider. It might have negative impact on performance (including unable to run CUDA graph). Set session_options.log_severity_level=1 to see the detail logs before this message.\u001b[m\n"
]
}
],
"source": [
"from inference.models import YOLOWorld\n",
"YOLO_WORLD_MODEL = YOLOWorld(model_id=\"yolo_world/l\")\n"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"YOLO_WORLD_MODEL.set_classes('person')\n",
"results = YOLO_WORLD_MODEL.infer(\"holland_.jpg\", confidence=0.001)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"ObjectDetectionInferenceResponse(visualization=None, frame_id=None, time=1.3525681463070214, image=InferenceResponseImage(width=1500, height=1000), predictions=[])"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"results"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "comfyui_clone",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.14"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 478 KiB

@@ -0,0 +1 @@
inference-gpu[yolo-world]==0.9.13
@@ -0,0 +1,61 @@
import torch
import numpy as np
from torchvision.transforms import ToTensor
GPU_EFFICIENT_SAM_CHECKPOINT = "efficient_sam_s_gpu.jit"
CPU_EFFICIENT_SAM_CHECKPOINT = "efficient_sam_s_cpu.jit"
def load(device: torch.device) -> torch.jit.ScriptModule:
if device.type == "cuda":
model = torch.jit.load(GPU_EFFICIENT_SAM_CHECKPOINT)
else:
model = torch.jit.load(CPU_EFFICIENT_SAM_CHECKPOINT)
model.eval()
return model
def inference_with_box(
image: np.ndarray,
box: np.ndarray,
model: torch.jit.ScriptModule,
device: torch.device
) -> np.ndarray:
bbox = torch.reshape(torch.tensor(box), [1, 1, 2, 2])
bbox_labels = torch.reshape(torch.tensor([2, 3]), [1, 1, 2])
img_tensor = ToTensor()(image)
predicted_logits, predicted_iou = model(
img_tensor[None, ...].to(device),
bbox.to(device),
bbox_labels.to(device),
)
predicted_logits = predicted_logits.cpu()
all_masks = torch.ge(torch.sigmoid(predicted_logits[0, 0, :, :, :]), 0.5).numpy()
predicted_iou = predicted_iou[0, 0, ...].cpu().detach().numpy()
max_predicted_iou = -1
selected_mask_using_predicted_iou = None
for m in range(all_masks.shape[0]):
curr_predicted_iou = predicted_iou[m]
if (
curr_predicted_iou > max_predicted_iou
or selected_mask_using_predicted_iou is None
):
max_predicted_iou = curr_predicted_iou
selected_mask_using_predicted_iou = all_masks[m]
return selected_mask_using_predicted_iou
def inference_with_boxes(
image: np.ndarray,
xyxy: np.ndarray,
model: torch.jit.ScriptModule,
device: torch.device
) -> np.ndarray:
masks = []
for [x_min, y_min, x_max, y_max] in xyxy:
box = np.array([[x_min, y_min], [x_max, y_max]])
mask = inference_with_box(image, box, model, device)
masks.append(mask)
return np.array(masks)
@@ -0,0 +1,27 @@
import os
import datetime
import uuid
import supervision as sv
MAX_VIDEO_LENGTH_SEC = 3
def generate_file_name(extension="mp4"):
current_datetime = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
unique_id = uuid.uuid4()
return f"{current_datetime}_{unique_id}.{extension}"
def calculate_end_frame_index(source_video_path: str) -> int:
video_info = sv.VideoInfo.from_video_path(source_video_path)
return min(
video_info.total_frames,
video_info.fps * MAX_VIDEO_LENGTH_SEC
)
def create_directory(directory_path: str) -> None:
if not os.path.exists(directory_path):
os.makedirs(directory_path)
+21
View File
@@ -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 }}
+3
View File
@@ -0,0 +1,3 @@
/.venv
# /config.yaml
/__pycache__
+343
View File
@@ -0,0 +1,343 @@
from .utils import *
class GenerateStableDiffsutionPromptLLM:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
data = load_config()
template_system = ""
template_user = ""
models = []
if data:
_prompt = data["default_generate_stable_diffsution_prompt"]
if _prompt:
_system = _prompt["system"]
_user = _prompt["user"]
if _system:
template_system = _system
if _user:
template_user = _user
_models = data["models"]
if isinstance(_models, list) and len(_models) > 0:
models = _models
default_model = data["default_model"]
if default_model and len(_models) > 0:
default_model_index = models.index(default_model)
if default_model_index > 0:
models.pop(default_model_index)
models.insert(0, default_model)
return {
"required": {
"object1": ("STRING", {
"dynamicPrompts": False,
"multiline": True,
"default": ""
}),
"desc_obj1": ("STRING", {
"dynamicPrompts": False,
"multiline": True,
"default": ""
}),
"object2": ("STRING", {
"dynamicPrompts": False,
"multiline": True,
"default": ""
}),
"desc_obj2": ("STRING", {
"dynamicPrompts": False,
"multiline": True,
"default": ""
}),
"template_system": ("STRING", {
"dynamicPrompts": False,
"multiline": True,
"default": template_system,
"display": "textarea",
}),
"template_user": ("STRING", {
"dynamicPrompts": False,
"multiline": True,
"default": template_user,
"display": "textarea"
}),
"stop": ("STRING", {
"dynamicPrompts": False,
"multiline": False,
"default": None
}),
"response_pattern": ("STRING", {
"dynamicPrompts": False,
"multiline": False,
"default": None
}),
"temperature": ("FLOAT", {
"default": 1.0,
"min": 0.0,
"max": 1.0,
"step": 0.01,
"round": 0.01,
"display": "number"
}),
"max_tokens": ("INT", {
"default": 300,
"min": -1,
"max": 2048,
"display": "number"
}),
"model_name": (models, {
"default": default_model,
"display": "select"
})
}
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("stable diffsution prompt",)
FUNCTION = "generateStableDiffsutionPrompt"
CATEGORY = "LLM"
def generateStableDiffsutionPrompt(self, object1, desc_obj1, object2, desc_obj2 ,template_system, template_user, stop, response_pattern, temperature, max_tokens, model_name):
config = load_config()
openai_config = config["openai"]
if openai_config is None:
return (object,)
api_base = openai_config["api_base"]
api_key = openai_config["api_key"]
if not (is_valid_string(api_base) and is_valid_string(api_key)):
return (object,)
_object = object
if is_valid_string(template_user):
_object = template_user.format(desc_obj1, object1, desc_obj2, object2)
response = get_completion(_object, response_pattern, api_base, api_key, temperature, template_system,
max_tokens, stop, model_name)
return (response,)
class TranslateTextLLM:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
data = load_config()
template_system = ""
template_user = ""
models = []
if data:
_prompt = data["default_translate_prompt"]
if _prompt:
_system = _prompt["system"]
_user = _prompt["user"]
if _system:
template_system = _system
if _user:
template_user = _user
_models = data["models"]
if isinstance(_models, list) and len(_models) > 0:
models = _models
default_model = data["default_model"]
if default_model and len(_models) > 0:
default_model_index = models.index(default_model)
if default_model_index > 0:
models.pop(default_model_index)
models.insert(0, default_model)
return {
"required": {
"prompt": ("STRING", {
"dynamicPrompts": False,
"multiline": True,
"default": ""
}),
"template_system": ("STRING", {
"dynamicPrompts": False,
"multiline": True,
"default": template_system,
"display": "textarea",
}),
"template_user": ("STRING", {
"dynamicPrompts": False,
"multiline": True,
"default": template_user,
"display": "textarea"
}),
"stop": ("STRING", {
"dynamicPrompts": False,
"multiline": False,
"default": None
}),
"response_pattern": ("STRING", {
"dynamicPrompts": False,
"multiline": False,
"default": None
}),
"temperature": ("FLOAT", {
"default": 1.0,
"min": 0.0,
"max": 1.0,
"step": 0.01,
"round": 0.01,
"display": "number"
}),
"max_tokens": ("INT", {
"default": 300,
"min": -1,
"max": 2048,
"display": "number"
}),
"model_name": (models, {
"default": default_model,
"display": "select"
})
}
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("text",)
FUNCTION = "translateText"
CATEGORY = "LLM"
def translateText(self, prompt, template_system, template_user, stop, response_pattern, temperature, max_tokens, model_name):
config = load_config()
openai_config = config["openai"]
if openai_config is None:
return (prompt,)
api_base = openai_config["api_base"]
api_key = openai_config["api_key"]
if not (is_valid_string(api_base) and is_valid_string(api_key)):
return (prompt,)
_prompt = prompt
if is_valid_string(template_user):
_prompt = template_user.format(prompt)
response = get_completion(_prompt, response_pattern, api_base, api_key, temperature, template_system,
max_tokens, stop, model_name)
return (response,)
class ChatWithLLM:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
data = load_config()
template_system = ""
template_user = ""
models = []
if data:
_prompt = data["default_chat_prompt"]
if _prompt:
_system = _prompt["system"]
_user = _prompt["user"]
if _system:
template_system = _system
if _user:
template_user = _user
_models = data["models"]
if isinstance(_models, list) and len(_models) > 0:
models = _models
default_model = data["default_model"]
if default_model and len(_models) > 0:
default_model_index = models.index(default_model)
if default_model_index > 0:
models.pop(default_model_index)
models.insert(0, default_model)
return {
"required": {
"prompt": ("STRING", {
"dynamicPrompts": False,
"multiline": True,
"default": ""
}),
"template_system": ("STRING", {
"dynamicPrompts": False,
"multiline": True,
"default": template_system,
"display": "textarea"
}),
"template_user": ("STRING", {
"dynamicPrompts": False,
"multiline": True,
"default": template_user,
"display": "textarea"
}),
"stop": ("STRING", {
"dynamicPrompts": False,
"multiline": False,
"default": None
}),
"response_pattern": ("STRING", {
"dynamicPrompts": False,
"multiline": False,
"default": None
}),
"temperature": ("FLOAT", {
"default": 1.0,
"min": 0.0,
"max": 1.0,
"step": 0.01,
"round": 0.01,
"display": "number"
}),
"max_tokens": ("INT", {
"default": 300,
"min": -1,
"max": 2048,
"display": "number"
}),
"model_name": (models, {
"default": default_model,
"display": "select"
})
}
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("text",)
FUNCTION = "chatLLM"
CATEGORY = "LLM"
def chatLLM(self, prompt, template_system, template_user, stop, response_pattern, temperature, max_tokens, model_name):
config = load_config()
openai_config = config["openai"]
if openai_config is None:
return (prompt,)
api_base = openai_config["api_base"]
api_key = openai_config["api_key"]
if not (is_valid_string(api_base) and is_valid_string(api_key)):
return (prompt,)
_prompt = prompt
if is_valid_string(template_user):
_prompt = template_user.format(prompt)
response = get_completion(_prompt, response_pattern, api_base, api_key, temperature, template_system,
max_tokens, stop, model_name)
return (response,)
NODE_CLASS_MAPPINGS = {
"Generate Stable Diffsution Prompt With LLM": GenerateStableDiffsutionPromptLLM,
"Translate Text With LLM": TranslateTextLLM,
"Chat With LLM": ChatWithLLM,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"Generate Stable Diffsution Prompt With LLM": "Generate Stable Diffsution Prompt With LLM",
"Translate Text With LLM": "Translate Text With LLM",
"Chat With LLM": "Chat With LLM",
}
+8
View File
@@ -0,0 +1,8 @@
# comfyui-llm-assistant
## Installation
1. use `ComfyUI-Manager` or put this code into `custom_nodes`
2. `pip install -r requirements.txt`
3. add `config.yaml`. config your api key and other info.
+3
View File
@@ -0,0 +1,3 @@
from .AssistantNodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS']
+35
View File
@@ -0,0 +1,35 @@
openai:
api_base: "https://openrouter.ai/api/v1"
api_key: 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
default_generate_stable_diffsution_prompt:
system : "You are an assistant bot designed to generate creative and detailed descriptions for a Diffusion model to generate realistic image"
user: "Read these 2 descriptions, really understand them and think about the context where both of them happens together. Then, generate smooth and meaning prompt for diffusion\nThe description for {} is:\n \"{}\"\n The description for {} is:\n \"{}\""
default_translate_prompt:
system: "You are an assistant bot."
user: "I want you to act as an English translator, Your answer is concise without any meaningless text, do not write explanations, now, translate the following sentence:\n \"{}\""
default_chat_prompt:
system: "You are an assistant bot."
user: ""
default_model: "mistralai/mistral-7b-instruct:free"
models:
- "nousresearch/nous-capybara-7b:free"
- "mistralai/mistral-7b-instruct:free"
- "gryphe/mythomist-7b:free"
- "undi95/toppy-m-7b:free"
- "openrouter/cinematika-7b:free"
- "google/gemma-7b-it:free"
- "neversleep/noromaid-mixtral-8x7b-instruct"
- "nousresearch/nous-hermes-llama2-13b"
- "nousresearch/nous-hermes-2-mixtral-8x7b-dpo"
- "nousresearch/nous-hermes-2-mixtral-8x7b-sft"
- "gryphe/mythomax-l2-13b"
- "nousresearch/nous-capybara-7b"
- "teknium/openhermes-2-mistral-7b"
- "open-orca/mistral-7b-openorca"
- "huggingfaceh4/zephyr-7b-beta"
- "openai/gpt-3.5-turbo-0125"
- "google/gemini-pro"
- "perplexity/sonar-small-chat"
- "perplexity/sonar-medium-chat"
- "cognitivecomputations/dolphin-mixtral-8x7b"
- "anthropic/claude-instant-1.2"
+15
View File
@@ -0,0 +1,15 @@
[project]
name = "comfyui-llm-assistant"
description = "Nodes:Generate Stable Diffsution Prompt With LLM, Translate Text With LLM, Chat With LLM"
version = "1.0.0"
license = "LICENSE"
dependencies = ["pyyaml", "openai"]
[project.urls]
Repository = "https://github.com/longgui0318/comfyui-llm-assistant"
# Used by Comfy Registry https://comfyregistry.org
[tool.comfy]
PublisherId = "longgui0318"
DisplayName = "comfyui-llm-assistant"
Icon = ""
+2
View File
@@ -0,0 +1,2 @@
pyyaml
openai
+56
View File
@@ -0,0 +1,56 @@
from openai import OpenAI,types
import re
import os
import yaml
def is_valid_string(s):
return s is not None and s.strip() != ""
def get_completion(prompt, response_pattern, api_url, api_key, temperature, sys_prefix, max_tokens,stop, model="local model"):
try:
client = OpenAI(api_key=api_key, base_url=api_url)
messages = [{"role": "system", "content": sys_prefix},
{"role": "user", "content": prompt}]
if not is_valid_string(stop):
stop = None
response = client.chat.completions.create(
model=model,
messages=messages,
temperature=temperature,
max_tokens=max_tokens,
stop=stop,
)
response_str = response.choices[0].message.content
print(f"{model} \nrequest:{prompt}\nresponse:{response_str}")
if response_pattern:
try:
response_str_t = re.search(
response_pattern, response_str).group(0)
if response_str_t:
response_str = response_str_t
except:
pass
return response_str
except Exception as e:
error_message = f"Error: {str(e)}"
print(error_message)
return prompt
config_data = None
def load_config():
global config_data
if config_data:
return config_data
my_path = os.path.dirname(__file__)
with open(os.path.join(my_path, "config.yaml"), 'r') as file:
# 使用yaml.load()解析YAML文件内容
config_data = yaml.load(file, Loader=yaml.FullLoader)
return config_data
+21
View File
@@ -0,0 +1,21 @@
name: Publish to Comfy registry
on:
workflow_dispatch:
push:
branches:
- 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 }}
+10
View File
@@ -0,0 +1,10 @@
.python-version
**/*.pyc
**/__pycache__/
**/__pycache__
temp/**
temp.txt
demo-workflows
test-temp
**/venv
todo.md
+95
View File
@@ -0,0 +1,95 @@
**Auto-generate caption (BLIP Only)**:
![alt text](wiki/demo-pics/Selection_003.png)
**Using to automate img2img process (BLIP and Llava)**
![alt text](wiki/demo-pics/Selection_002.png)
## Requirements/Dependencies
- Shared with ComfyUI
- Pillow>=8.3.2
- torch>=2.2.1
- torchvision>=0.17.1
- For Llava model
- bitsandbytes>=0.43.0
- accelerate>=0.3.0
- For MiniCPM model
- transformers>=4.36.0
- timm==0.9.10
- sentencepiece==0.1.99
- Python 3.10+
## Installation
- `cd` into `ComfyUI/custom_nodes` directory
- `git clone` this repo
- `cd img2txt-comfyui-nodes`
- `pip install -r requirements.txt`
- Models will be automatically downloaded per-use. If you never toggle a model on in the UI, it will never be downloaded.
- To ask a list of specific questions about the image, use the Llava or MiniPCM models. The questions are separated by line in the multiline text input box.
## Support for Chinese
- The `MiniCPM` model works with Chinese text input without any additional configuration. The output will also be in Chinese.
- "MiniCPM-V 2.0 supports strong bilingual multimodal capabilities in both English and Chinese. This is enabled by generalizing multimodal capabilities across languages, a technique from VisCPM"
<!-- - Here are the input field descriptions in Chinese, translated by -->
## Tips
- The multi-line input can be used to ask any type of questions. You can even ask very specific or complex questions about images.
- To get best results for a prompt that will be fed back into a txt2img or img2img prompt, usually it's best to only ask one or two questions, asking for a general description of the image and the most salient features and styles.
## Model Locations/Paths
- Models are downloaded automatically using the Huggingface cache system and the transformers `from_pretrained` method so no manual installation of models is necessary.
- If you really want to manually download the models, please refer to [Huggingface's documentation concerning the cache system](https://huggingface.co/docs/transformers/main/en/installation#cache-setup). Here is the relevant except:
- Pretrained models are downloaded and locally cached at `~/.cache/huggingface/hub`. This is the default directory given by the shell environment variable TRANSFORMERS_CACHE. On Windows, the default directory is given by `C:\Users\username\.cache\huggingface\hub`. You can change the shell environment variables shown below - in order of priority - to specify a different cache directory:
- Shell environment variable (default): HUGGINGFACE_HUB_CACHE or TRANSFORMERS_CACHE.
- Shell environment variable: HF_HOME.
- Shell environment variable: XDG_CACHE_HOME + /huggingface.
## Models Implemented (so far)
- [MiniCPM](https://huggingface.co/openbmb/MiniCPM-V-2/tree/main) (Chinese & English)
- **Title**: MiniCPM-V-2 - Strong multimodal large language model for efficient end-side deployment
- **Datasets**: HuggingFaceM4VQAv2, RLHF-V-Dataset, LLaVA-Instruct-150K
- **Size**: ~ 6.8GB
- [Salesforce - blip-image-captioning-base](https://huggingface.co/Salesforce/blip-image-captioning-base)
- **Title**: BLIP: Bootstrapping Language-Image Pre-training for Unified Vision-Language Understanding and Generation
- **Size**: ~ 2GB
- **Dataset**: COCO (The MS COCO dataset is a large-scale object detection, image segmentation, and captioning dataset published by Microsoft)
- [llava - llava-1.5-7b-hf](https://huggingface.co/llava-hf/llava-1.5-7b-hf)
- **Title**: LLava: Large Language Models for Vision and Language Tasks
- **Size**: ~ 15GB
- **Dataset**: 558K filtered image-text pairs from LAION/CC/SBU, captioned by BLIP, 158K GPT-generated multimodal instruction-following data, 450K academic-task-oriented VQA data mixture, 40K ShareGPT data.
- Coming Soon: [Microsoft - Git Large coco](https://huggingface.co/microsoft/git-large-coco)
- **Title**: GIT (short for GenerativeImage2Text) mode
- **Size**: ~ 3GB
- **Dataset**: COCO
- [More - to do](https://huggingface.co/models?pipeline_tag=image-to-text&sort=trending)
## Prompts
This is the guide for the format of an "ideal" txt2img prompt (using BLIP). Use as the basis for the questions to ask the img2txt models.
- **Subject** - you can specify region, write the most about the subject
- **Medium** - material used to make artwork. Some examples are illustration, oil painting, 3D rendering, and photography. Medium has a strong effect because one keyword alone can dramatically change the style.
- **Style** - artistic style of the image. Examples include impressionist, surrealist, pop art, etc.
- **Artists** - Artist names are strong modifiers. They allow you to dial in the exact style using a particular artist as a reference. It is also common to use multiple artist names to blend their styles. Now let’s add Stanley Artgerm Lau, a superhero comic artist, and Alphonse Mucha, a portrait painter in the 19th century.
- **Website** - Niche graphic websites such as Artstation and Deviant Art aggregate many images of distinct genres. Using them in a prompt is a sure way to steer the image toward these styles.
- **Resolution** - Resolution represents how sharp and detailed the image is. Let’s add keywords highly detailed and sharp focus
- **Enviornment**
- **Additional** Details and objects - Additional details are sweeteners added to modify an image. We will add sci-fi, stunningly beautiful and dystopian to add some vibe to the image.
- **Composition** - camera type, detail, cinematography, blur, depth-of-field
- **Color/Warmth** - You can control the overall color of the image by adding color keywords. The colors you specified may appear as a tone or in objects.
- **Lighting** - Any photographer would tell you lighting is a key factor in creating successful images. Lighting keywords can have a huge effect on how the image looks. Let’s add cinematic lighting and dark to the prompt.
+9
View File
@@ -0,0 +1,9 @@
from .src.img2txt_node import Img2TxtNode
NODE_CLASS_MAPPINGS = {
"img2txt BLIP/Llava Multimodel Tagger": Img2TxtNode,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"img2txt BLIP/Llava Multimodel Tagger": "Image to Text - Auto Caption"
}
WEB_DIRECTORY = "./web"
+15
View File
@@ -0,0 +1,15 @@
[project]
name = "img2txt-comfyui-nodes"
description = "Get general description or specify questions to ask about images (medium, art style, background, etc.). Supports Chinese 🇨🇳 questions via MiniCPM model."
version = "1.1.4"
license = "LICENSE"
dependencies = ["transformers>=4.36.0", "bitsandbytes>=0.43.0", "timm>=1.0.7", "sentencepiece==0.1.99", "accelerate>=0.3.0", "deepspeed"]
[project.urls]
Repository = "https://github.com/christian-byrne/img2txt-comfyui-nodes"
# Used by Comfy Registry https://comfyregistry.org
[tool.comfy]
PublisherId = "christian-byrne"
DisplayName = "Img2txt - Auto Caption"
Icon = "https://img.icons8.com/?size=100&id=49374&format=png&color=000000"
+6
View File
@@ -0,0 +1,6 @@
transformers>=4.36.0
bitsandbytes>=0.43.0
timm>=1.0.7
sentencepiece
accelerate>=0.3.0
deepspeed
+81
View File
@@ -0,0 +1,81 @@
from PIL import Image
from transformers import (
BlipProcessor,
BlipForConditionalGeneration,
BlipConfig,
BlipTextConfig,
BlipVisionConfig,
)
import torch
import model_management
class BLIPImg2Txt:
def __init__(
self,
conditional_caption: str,
min_words: int,
max_words: int,
temperature: float,
repetition_penalty: float,
search_beams: int,
model_id: str = "Salesforce/blip-image-captioning-large",
):
self.conditional_caption = conditional_caption
self.model_id = model_id
# Determine do_sample and num_beams
if temperature > 1.1 or temperature < 0.90:
do_sample = True
num_beams = 1 # Sampling does not use beam search
else:
do_sample = False
num_beams = (
search_beams if search_beams > 1 else 1
) # Use beam search if num_beams > 1
# Initialize text config kwargs
self.text_config_kwargs = {
"do_sample": do_sample,
"max_length": max_words,
"min_length": min_words,
"repetition_penalty": repetition_penalty,
"padding": "max_length",
}
if not do_sample:
self.text_config_kwargs["temperature"] = temperature
self.text_config_kwargs["num_beams"] = num_beams
def generate_caption(self, image: Image.Image) -> str:
if image.mode != "RGB":
image = image.convert("RGB")
processor = BlipProcessor.from_pretrained(self.model_id)
# Update and apply configurations
config_text = BlipTextConfig.from_pretrained(self.model_id)
config_text.update(self.text_config_kwargs)
config_vision = BlipVisionConfig.from_pretrained(self.model_id)
config = BlipConfig.from_text_vision_configs(config_text, config_vision)
model = BlipForConditionalGeneration.from_pretrained(
self.model_id,
config=config,
torch_dtype=torch.float16,
).to(model_management.get_torch_device())
inputs = processor(
image,
self.conditional_caption,
return_tensors="pt",
).to(model_management.get_torch_device(), torch.float16)
with torch.no_grad():
out = model.generate(**inputs)
ret = processor.decode(out[0], skip_special_tokens=True)
del model
torch.cuda.empty_cache()
return ret
@@ -0,0 +1,8 @@
#!pip install transformers[sentencepiece]
# from transformers import pipeline
# text = "Angela Merkel is a politician in Germany and leader of the CDU"
# hypothesis_template = "This text is about {}"
# classes_verbalized = ["politics", "economy", "entertainment", "environment"]
# zeroshot_classifier = pipeline("zero-shot-classification", model="MoritzLaurer/deberta-v3-large-zeroshot-v2.0") # change the model identifier here
# output = zeroshot_classifier(text, classes_verbalized, hypothesis_template=hypothesis_template, multi_label=False)
# print(output)
+209
View File
@@ -0,0 +1,209 @@
"""
@author: christian-byrne
@title: Img2Txt auto captioning. Choose from models: BLIP, Llava, MiniCPM, MS-GIT. Use model combos and merge results. Specify questions to ask about images (medium, art style, background). Supports Chinese 🇨🇳 questions via MiniCPM.
@nickname: Image to Text - Auto Caption
"""
import torch
from torchvision import transforms
from .img_tensor_utils import TensorImgUtils
from .llava_img2txt import LlavaImg2Txt
from .blip_img2txt import BLIPImg2Txt
from .mini_cpm_img2txt import MiniPCMImg2Txt
from typing import Tuple
class Img2TxtNode:
CATEGORY = "img2txt"
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"input_image": ("IMAGE",),
},
"optional": {
"use_blip_model": (
"BOOLEAN",
{
"default": True,
"label_on": "Use BLIP (Requires 2Gb Disk)",
"label_off": "Don't use BLIP",
},
),
"use_llava_model": (
"BOOLEAN",
{
"default": False,
"label_on": "Use Llava (Requires 15Gb Disk)",
"label_off": "Don't use Llava",
},
),
"use_mini_pcm_model": (
"BOOLEAN",
{
"default": False,
"label_on": "Use MiniCPM (Requires 6Gb Disk)",
"label_off": "Don't use MiniCPM",
},
),
"use_all_models": (
"BOOLEAN",
{
"default": False,
"label_on": "Use all models and combine outputs (Total Size: 20+Gb)",
"label_off": "Use selected models only",
},
),
"blip_caption_prefix": (
"STRING",
{
"default": "a photograph of",
},
),
"prompt_questions": (
"STRING",
{
"default": "What is the subject of this image?\nWhat are the mediums used to make this?\nWhat are the artistic styles this is reminiscent of?\nWhich famous artists is this reminiscent of?\nHow sharp or detailed is this image?\nWhat is the environment and background of this image?\nWhat are the objects in this image?\nWhat is the composition of this image?\nWhat is the color palette in this image?\nWhat is the lighting in this image?",
"multiline": True,
},
),
"temperature": (
"FLOAT",
{
"default": 0.8,
"min": 0.1,
"max": 2.0,
"step": 0.01,
"display": "slider",
},
),
"repetition_penalty": (
"FLOAT",
{
"default": 1.2,
"min": 0.1,
"max": 2.0,
"step": 0.01,
"display": "slider",
},
),
"min_words": ("INT", {"default": 36}),
"max_words": ("INT", {"default": 128}),
"search_beams": ("INT", {"default": 5}),
"exclude_terms": (
"STRING",
{
"default": "watermark, text, writing",
},
),
},
"hidden": {
"unique_id": "UNIQUE_ID",
"extra_pnginfo": "EXTRA_PNGINFO",
"output_text": (
"STRING",
{
"default": "",
},
),
},
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("caption",)
FUNCTION = "main"
OUTPUT_NODE = True
def main(
self,
input_image: torch.Tensor, # [Batch_n, H, W, 3-channel]
use_blip_model: bool,
use_llava_model: bool,
use_all_models: bool,
use_mini_pcm_model: bool,
blip_caption_prefix: str,
prompt_questions: str,
temperature: float,
repetition_penalty: float,
min_words: int,
max_words: int,
search_beams: int,
exclude_terms: str,
output_text: str = "",
unique_id=None,
extra_pnginfo=None,
) -> Tuple[str, ...]:
raw_image = transforms.ToPILImage()(
TensorImgUtils.convert_to_type(input_image, "CHW")
).convert("RGB")
if blip_caption_prefix == "":
blip_caption_prefix = "a photograph of"
captions = []
if use_all_models or use_blip_model:
blip = BLIPImg2Txt(
conditional_caption=blip_caption_prefix,
min_words=min_words,
max_words=max_words,
temperature=temperature,
repetition_penalty=repetition_penalty,
search_beams=search_beams,
)
captions.append(blip.generate_caption(raw_image))
if use_all_models or use_llava_model:
llava_questions = prompt_questions.split("\n")
llava_questions = [
q
for q in llava_questions
if q != "" and q != " " and q != "\n" and q != "\n\n"
]
if len(llava_questions) > 0:
llava = LlavaImg2Txt(
question_list=llava_questions,
model_id="llava-hf/llava-1.5-7b-hf",
use_4bit_quantization=True,
use_low_cpu_mem=True,
use_flash2_attention=False,
max_tokens_per_chunk=300,
)
captions.append(llava.generate_caption(raw_image))
if use_all_models or use_mini_pcm_model:
mini_pcm = MiniPCMImg2Txt(
question_list=prompt_questions.split("\n"),
temperature=temperature,
)
captions.append(mini_pcm.generate_captions(raw_image))
out_string = self.exclude(exclude_terms, self.merge_captions(captions))
return {"ui": {"text": out_string}, "result": (out_string,)}
def merge_captions(self, captions: list) -> str:
"""Merge captions from multiple models into one string.
Necessary because we can expect the generated captions will generally
be comma-separated fragments ordered by relevance - so combine
fragments in an alternating order."""
merged_caption = ""
captions = [c.split(",") for c in captions]
for i in range(max(len(c) for c in captions)):
for j in range(len(captions)):
if i < len(captions[j]) and captions[j][i].strip() != "":
merged_caption += captions[j][i].strip() + ", "
return merged_caption
def exclude(self, exclude_terms: str, out_string: str) -> str:
# https://huggingface.co/Salesforce/blip-image-captioning-large/discussions/20
exclude_terms = "arafed," + exclude_terms
exclude_terms = [
term.strip().lower() for term in exclude_terms.split(",") if term != ""
]
for term in exclude_terms:
out_string = out_string.replace(term, "")
return out_string
@@ -0,0 +1,129 @@
import torch
from typing import Tuple
class TensorImgUtils:
@staticmethod
def from_to(from_type: list[str], to_type: list[str]):
"""Return a function that converts a tensor from one type to another. Args can be lists of strings or just strings (e.g., ["C", "H", "W"] or just "CHW")."""
if isinstance(from_type, list):
from_type = "".join(from_type)
if isinstance(to_type, list):
to_type = "".join(to_type)
permute_arg = [from_type.index(c) for c in to_type]
def convert(tensor: torch.Tensor) -> torch.Tensor:
return tensor.permute(permute_arg)
return convert
@staticmethod
def convert_to_type(tensor: torch.Tensor, to_type: str) -> torch.Tensor:
"""Convert a tensor to a specific type."""
from_type = TensorImgUtils.identify_type(tensor)[0]
if from_type == list(to_type):
return tensor
if len(from_type) == 4 and len(to_type) == 3:
# If converting from a batched tensor to a non-batched tensor, squeeze the batch dimension
tensor = tensor.squeeze(0)
from_type = from_type[1:]
if len(from_type) == 3 and len(to_type) == 4:
# If converting from a non-batched tensor to a batched tensor, unsqueeze the batch dimension
tensor = tensor.unsqueeze(0)
from_type = ["B"] + from_type
return TensorImgUtils.from_to(from_type, list(to_type))(tensor)
@staticmethod
def identify_type(tensor: torch.Tensor) -> Tuple[list[str], str]:
"""Identify the type of image tensor. Doesn't currently check for BHW. Returns one of the following:"""
dim_n = tensor.dim()
if dim_n == 2:
return (["H", "W"], "HW")
elif dim_n == 3: # HWA, AHW, HWC, or CHW
if tensor.size(2) == 3:
return (["H", "W", "C"], "HWRGB")
elif tensor.size(2) == 4:
return (["H", "W", "C"], "HWRGBA")
elif tensor.size(0) == 3:
return (["C", "H", "W"], "RGBHW")
elif tensor.size(0) == 4:
return (["C", "H", "W"], "RGBAHW")
elif tensor.size(2) == 1:
return (["H", "W", "C"], "HWA")
elif tensor.size(0) == 1:
return (["C", "H", "W"], "AHW")
elif dim_n == 4: # BHWC or BCHW
if tensor.size(3) >= 3: # BHWRGB or BHWRGBA
if tensor.size(3) == 3:
return (["B", "H", "W", "C"], "BHWRGB")
elif tensor.size(3) == 4:
return (["B", "H", "W", "C"], "BHWRGBA")
elif tensor.size(1) >= 3:
if tensor.size(1) == 3:
return (["B", "C", "H", "W"], "BRGBHW")
elif tensor.size(1) == 4:
return (["B", "C", "H", "W"], "BRGBAHW")
else:
raise ValueError(
f"{dim_n} dimensions is not a valid number of dimensions for an image tensor."
)
raise ValueError(
f"Could not determine shape of Tensor with {dim_n} dimensions and {tensor.shape} shape."
)
@staticmethod
def test_squeeze_batch(tensor: torch.Tensor, strict=False) -> torch.Tensor:
# Check if the tensor has a batch dimension (size 4)
if tensor.dim() == 4:
if tensor.size(0) == 1 or not strict:
# If it has a batch dimension with size 1, remove it. It represents a single image.
return tensor.squeeze(0)
else:
raise ValueError(
f"This is not a single image. It's a batch of {tensor.size(0)} images."
)
else:
# Otherwise, it doesn't have a batch dimension, so just return the tensor as is.
return tensor
@staticmethod
def test_unsqueeze_batch(tensor: torch.Tensor) -> torch.Tensor:
# Check if the tensor has a batch dimension (size 4)
if tensor.dim() == 3:
# If it doesn't have a batch dimension, add one. It represents a single image.
return tensor.unsqueeze(0)
else:
# Otherwise, it already has a batch dimension, so just return the tensor as is.
return tensor
@staticmethod
def most_pixels(img_tensors: list[torch.Tensor]) -> torch.Tensor:
sizes = [
TensorImgUtils.height_width(img)[0] * TensorImgUtils.height_width(img)[1]
for img in img_tensors
]
return img_tensors[sizes.index(max(sizes))]
@staticmethod
def height_width(image: torch.Tensor) -> Tuple[int, int]:
"""Like torchvision.transforms methods, this method assumes Tensor to
have [..., H, W] shape, where ... means an arbitrary number of leading
dimensions
"""
return image.shape[-2:]
@staticmethod
def smaller_axis(image: torch.Tensor) -> int:
h, w = TensorImgUtils.height_width(image)
return 2 if h < w else 3
@staticmethod
def larger_axis(image: torch.Tensor) -> int:
h, w = TensorImgUtils.height_width(image)
return 2 if h > w else 3
@@ -0,0 +1,114 @@
import torch
from transformers import AutoTokenizer, AutoModelForTokenClassification
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk import pos_tag
from nltk.tokenize import word_tokenize
import nltk
def nltk_speach_tag(sentence):
nltk.download("punkt")
nltk.download("averaged_perceptron_tagger")
nltk.download("stopwords")
# Tokenize the sentence
tokens = word_tokenize(sentence)
# Filter out stopwords and punctuation
stop_words = set(stopwords.words("english"))
filtered_tokens = [
word for word in tokens if word.lower() not in stop_words and word.isalnum()
]
# Perform Part-of-Speech tagging
tagged_tokens = pos_tag(filtered_tokens)
# Extract nouns and proper nouns
salient_tokens = [
token
for token, pos in tagged_tokens
if pos in ["NN", "NNP", "NNS", "NNPS", "ADJ", "JJ", "FW"]
]
salient_tokens = list(set(salient_tokens))
# Re-add commas or periods relative to the original sentence
comma_period_indices = [i for i, char in enumerate(sentence) if char in [",", "."]]
salient_tokens_indices = [sentence.index(token) for token in salient_tokens]
# Add commas or periods between words if there was one in the original sentence
out = ""
for i, index in enumerate(salient_tokens_indices):
out += salient_tokens[i]
distance_between_next = (
salient_tokens_indices[i + 1] - index
if i + 1 < len(salient_tokens_indices)
else None
)
puncuated = False
if not distance_between_next:
puncuated = True
else:
for i in range(index, index + distance_between_next):
if i in comma_period_indices:
puncuated = True
break
if not puncuated:
# IF the previous word was an adjective, and current is a noun, add a space
if (
i > 0
and tagged_tokens[i - 1][1] in ["JJ", "ADJ"]
and tagged_tokens[i][1] in ["NN", "NNP", "NNS", "NNPS"]
):
out += " "
else:
out += ", "
else:
out += ". "
# Add the last token
out += sentence[-1]
# Print the salient tokens
return out.strip().strip(",").strip(".").strip()
def extract_keywords(text: str) -> str:
tokenizer = AutoTokenizer.from_pretrained("yanekyuk/bert-keyword-extractor")
model = AutoModelForTokenClassification.from_pretrained(
"yanekyuk/bert-keyword-extractor"
)
"""Return keywords from text using a BERT model trained for keyword extraction as
a comma-separated string."""
print(f"Extracting keywords from text: {text}")
for char in ["\n", "\t", "\r"]:
text = text.replace(char, " ")
sentences = text.split(".")
result = ""
for sentence in sentences:
print(f"Extracting keywords from sentence: {sentence}")
inputs = tokenizer(sentence, return_tensors="pt", padding=True, truncation=True)
with torch.no_grad():
logits = model(**inputs).logits
predicted_token_class_ids = logits.argmax(dim=-1)
predicted_keywords = []
for token_id, token in zip(
predicted_token_class_ids[0],
tokenizer.convert_ids_to_tokens(inputs["input_ids"][0]),
):
if token_id == 1:
predicted_keywords.append(token)
print(f"Extracted keywords: {predicted_keywords}")
result += ", ".join(predicted_keywords) + ", "
print(f"All Keywords: {result}")
return result
+131
View File
@@ -0,0 +1,131 @@
from PIL import Image
import torch
import model_management
from transformers import AutoProcessor, LlavaForConditionalGeneration, BitsAndBytesConfig
class LlavaImg2Txt:
"""
A class to generate text captions for images using the Llava model.
Args:
question_list (list[str]): A list of questions to ask the model about the image.
model_id (str): The model's name in the Hugging Face model hub.
use_4bit_quantization (bool): Whether to use 4-bit quantization to reduce memory usage. 4-bit quantization reduces the precision of model parameters, potentially affecting the quality of generated outputs. Use if VRAM is limited. Default is True.
use_low_cpu_mem (bool): In low_cpu_mem_usage mode, the model is initialized with optimizations aimed at reducing CPU memory consumption. This can be beneficial when working with large models or limited computational resources. Default is True.
use_flash2_attention (bool): Whether to use Flash-Attention 2. Flash-Attention 2 focuses on optimizing attention mechanisms, which are crucial for the model's performance during generation. Use if computational resources are abundant. Default is False.
max_tokens_per_chunk (int): The maximum number of tokens to generate per prompt chunk. Default is 300.
"""
def __init__(
self,
question_list,
model_id: str = "llava-hf/llava-1.5-7b-hf",
use_4bit_quantization: bool = True,
use_low_cpu_mem: bool = True,
use_flash2_attention: bool = False,
max_tokens_per_chunk: int = 300,
):
self.question_list = question_list
self.model_id = model_id
self.use_4bit = use_4bit_quantization
self.use_flash2 = use_flash2_attention
self.use_low_cpu_mem = use_low_cpu_mem
self.max_tokens_per_chunk = max_tokens_per_chunk
def generate_caption(
self,
raw_image: Image.Image,
) -> str:
"""
Generate a caption for an image using the Llava model.
Args:
raw_image (Image): Image to generate caption for
"""
# Convert Image to RGB first
if raw_image.mode != "RGB":
raw_image = raw_image.convert("RGB")
dtype = torch.float16
quant_config = BitsAndBytesConfig(
load_in_4bit=self.use_4bit,
bnb_4bit_compute_dtype=dtype,
bnb_4bit_quant_type="fp4"
)
model = LlavaForConditionalGeneration.from_pretrained(
self.model_id,
torch_dtype=dtype,
low_cpu_mem_usage=self.use_low_cpu_mem,
use_flash_attention_2=self.use_flash2,
quantization_config=quant_config,
)
# model.to() is not supported for 4-bit or 8-bit bitsandbytes models. With 4-bit quantization, use the model as it is, since the model will already be set to the correct devices and casted to the correct `dtype`.
if torch.cuda.is_available() and not self.use_4bit:
model = model.to(model_management.get_torch_device(), torch.float16)
processor = AutoProcessor.from_pretrained(self.model_id)
prompt_chunks = self.__get_prompt_chunks(chunk_size=4)
caption = ""
with torch.no_grad():
for prompt_list in prompt_chunks:
prompt = self.__get_single_answer_prompt(prompt_list)
inputs = processor(prompt, raw_image, return_tensors="pt").to(
model_management.get_torch_device(), torch.float16
)
output = model.generate(
**inputs, max_new_tokens=self.max_tokens_per_chunk, do_sample=False
)
decoded = processor.decode(output[0][2:])
cleaned = self.clean_output(decoded)
caption += cleaned
del model
torch.cuda.empty_cache()
return caption
def clean_output(self, decoded_output, delimiter=","):
output_only = decoded_output.split("ASSISTANT: ")[1]
lines = output_only.split("\n")
cleaned_output = ""
for line in lines:
cleaned_output += self.__replace_delimiter(line, ".", delimiter)
return cleaned_output
def __get_single_answer_prompt(self, questions):
"""
For multiple turns conversation:
"USER: <image>\n<prompt1> ASSISTANT: <answer1></s>USER: <prompt2> ASSISTANT: <answer2></s>USER: <prompt3> ASSISTANT:"
From: https://huggingface.co/docs/transformers/en/model_doc/llava#usage-tips
Not sure how the formatting works for multi-turn but those are the docs.
"""
prompt = "USER: <image>\n"
for index, question in enumerate(questions):
if index != 0:
prompt += "USER: "
prompt += f"{question} </s >"
prompt += "ASSISTANT: "
return prompt
def __replace_delimiter(self, text: str, old, new=","):
"""Replace only the LAST instance of old with new"""
if old not in text:
return text.strip() + " "
last_old_index = text.rindex(old)
replaced = text[:last_old_index] + new + text[last_old_index + len(old) :]
return replaced.strip() + " "
def __get_prompt_chunks(self, chunk_size=4):
prompt_chunks = []
for index, feature in enumerate(self.question_list):
if index % chunk_size == 0:
prompt_chunks.append([feature])
else:
prompt_chunks[-1].append(feature)
return prompt_chunks
@@ -0,0 +1,53 @@
import torch
from PIL import Image
from transformers import AutoModel, AutoTokenizer
import model_management
class MiniPCMImg2Txt:
def __init__(self, question_list: list[str], temperature: float = 0.7):
self.model_id = "openbmb/MiniCPM-V-2"
self.question_list = question_list
self.question_list = self.__create_question_list()
self.temperature = temperature
def __create_question_list(self) -> list:
ret = []
for q in self.question_list:
ret.append({"role": "user", "content": q})
return ret
def generate_captions(self, raw_image: Image.Image) -> str:
device = model_management.get_torch_device()
# For Nvidia GPUs support BF16 (like A100, H100, RTX3090)
# For Nvidia GPUs do NOT support BF16 (like V100, T4, RTX2080)
torch_dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
model = AutoModel.from_pretrained(
"openbmb/MiniCPM-V-2", trust_remote_code=True, torch_dtype=torch_dtype
)
model = model.to(device=device, dtype=torch_dtype)
tokenizer = AutoTokenizer.from_pretrained(
self.model_id, trust_remote_code=True
)
model.eval()
if raw_image.mode != "RGB":
raw_image = raw_image.convert("RGB")
with torch.no_grad():
res, _, _ = model.chat(
image=raw_image,
msgs=self.question_list,
context=None,
tokenizer=tokenizer,
sampling=True,
temperature=self.temperature,
)
del model
torch.cuda.empty_cache()
return res
@@ -0,0 +1,51 @@
import { app } from "../../../scripts/app.js";
import { ComfyWidgets } from "../../../scripts/widgets.js";
// Displays output caption text
app.registerExtension({
name: "Img2TxtNode",
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name === "img2txt BLIP/Llava Multimodel Tagger") {
function populate(message) {
console.log("message", message);
console.log("message.text", message.text);
const insertIndex = this.widgets.findIndex((w) => w.name === "output_text");
if (insertIndex !== -1) {
for (let i = insertIndex; i < this.widgets.length; i++) {
this.widgets[i].onRemove?.();
}
this.widgets.length = insertIndex;
}
const outputWidget = ComfyWidgets["STRING"](
this,
"output_text",
["STRING", { multiline: true }],
app
).widget;
outputWidget.inputEl.readOnly = true;
outputWidget.inputEl.style.opacity = 0.6;
outputWidget.value = message.text.join("");
requestAnimationFrame(() => {
const size_ = this.computeSize();
if (size_[0] < this.size[0]) {
size_[0] = this.size[0];
}
if (size_[1] < this.size[1]) {
size_[1] = this.size[1];
}
this.onResize?.(size_);
app.graph.setDirtyCanvas(true, false);
});
}
const onExecuted = nodeType.prototype.onExecuted;
nodeType.prototype.onExecuted = function (message) {
onExecuted?.apply(this, arguments);
populate.call(this, message);
};
}
},
});
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 MiB

@@ -0,0 +1,523 @@
{
"last_node_id": 51,
"last_link_id": 60,
"nodes": [
{
"id": 41,
"type": "CLIPTextEncode",
"pos": [
1055,
571
],
"size": {
"0": 348.9403381347656,
"1": 56.439388275146484
},
"flags": {},
"order": 5,
"mode": 0,
"inputs": [
{
"name": "clip",
"type": "CLIP",
"link": 50
},
{
"name": "text",
"type": "STRING",
"link": 60,
"widget": {
"name": "text"
}
}
],
"outputs": [
{
"name": "CONDITIONING",
"type": "CONDITIONING",
"links": [
44
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "CLIPTextEncode"
},
"widgets_values": [
""
]
},
{
"id": 39,
"type": "KSampler",
"pos": [
1587,
982
],
"size": {
"0": 315,
"1": 262
},
"flags": {},
"order": 6,
"mode": 0,
"inputs": [
{
"name": "model",
"type": "MODEL",
"link": 42
},
{
"name": "positive",
"type": "CONDITIONING",
"link": 44
},
{
"name": "negative",
"type": "CONDITIONING",
"link": 45
},
{
"name": "latent_image",
"type": "LATENT",
"link": 58
}
],
"outputs": [
{
"name": "LATENT",
"type": "LATENT",
"links": [
48
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "KSampler"
},
"widgets_values": [
290872458059323,
"randomize",
20,
8,
"euler",
"normal",
1
]
},
{
"id": 45,
"type": "VAEDecode",
"pos": [
1998,
1018
],
"size": {
"0": 210,
"1": 46
},
"flags": {},
"order": 7,
"mode": 0,
"inputs": [
{
"name": "samples",
"type": "LATENT",
"link": 48
},
{
"name": "vae",
"type": "VAE",
"link": 49
}
],
"outputs": [
{
"name": "IMAGE",
"type": "IMAGE",
"links": [
55
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "VAEDecode"
}
},
{
"id": 48,
"type": "PreviewImage",
"pos": [
2039,
1262
],
"size": {
"0": 210,
"1": 246
},
"flags": {},
"order": 8,
"mode": 0,
"inputs": [
{
"name": "images",
"type": "IMAGE",
"link": 55
}
],
"properties": {
"Node name for S&R": "PreviewImage"
}
},
{
"id": 42,
"type": "CLIPTextEncode",
"pos": [
1056,
683
],
"size": {
"0": 352.9139404296875,
"1": 113.16606140136719
},
"flags": {},
"order": 3,
"mode": 0,
"inputs": [
{
"name": "clip",
"type": "CLIP",
"link": 51
}
],
"outputs": [
{
"name": "CONDITIONING",
"type": "CONDITIONING",
"links": [
45
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "CLIPTextEncode"
},
"widgets_values": [
"text, watermark"
]
},
{
"id": 50,
"type": "VAEEncode",
"pos": [
1119,
1329
],
"size": {
"0": 201.4841766357422,
"1": 55.59581756591797
},
"flags": {},
"order": 4,
"mode": 0,
"inputs": [
{
"name": "pixels",
"type": "IMAGE",
"link": 56
},
{
"name": "vae",
"type": "VAE",
"link": 57
}
],
"outputs": [
{
"name": "LATENT",
"type": "LATENT",
"links": [
58
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "VAEEncode"
}
},
{
"id": 11,
"type": "LoadImage",
"pos": [
-135,
907
],
"size": {
"0": 670,
"1": 460
},
"flags": {},
"order": 0,
"mode": 0,
"outputs": [
{
"name": "IMAGE",
"type": "IMAGE",
"links": [
56,
59
],
"shape": 3,
"slot_index": 0
},
{
"name": "MASK",
"type": "MASK",
"links": [],
"shape": 3,
"slot_index": 1
}
],
"properties": {
"Node name for S&R": "LoadImage"
},
"widgets_values": [
"example.png",
"image"
]
},
{
"id": 40,
"type": "CheckpointLoaderSimple",
"pos": [
1124,
1019
],
"size": {
"0": 315,
"1": 98
},
"flags": {},
"order": 1,
"mode": 0,
"outputs": [
{
"name": "MODEL",
"type": "MODEL",
"links": [
42
],
"shape": 3,
"slot_index": 0
},
{
"name": "CLIP",
"type": "CLIP",
"links": [
50,
51
],
"shape": 3,
"slot_index": 1
},
{
"name": "VAE",
"type": "VAE",
"links": [
49,
57
],
"shape": 3,
"slot_index": 2
}
],
"properties": {
"Node name for S&R": "CheckpointLoaderSimple"
},
"widgets_values": [
"dreamshaper_8.safetensors"
]
},
{
"id": 51,
"type": "img2txt BLIP/Llava Multimodel Tagger",
"pos": [
605,
881
],
"size": {
"0": 427.2057800292969,
"1": 476.26934814453125
},
"flags": {},
"order": 2,
"mode": 0,
"inputs": [
{
"name": "input_image",
"type": "IMAGE",
"link": 59
}
],
"outputs": [
{
"name": "caption",
"type": "STRING",
"links": [
60
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "img2txt BLIP/Llava Multimodel Tagger"
},
"widgets_values": [
true,
false,
false,
false,
"a photograph of",
"What is the subject and background of this image?",
0.7000000000000001,
1.26,
36,
128,
5,
"watermark, text, writing",
"a photograph of a girl dressed up, in pink dress and bright blue eyes poses in the grass with arms spread out in front of her face, holding an umbrella on a sky, "
],
"color": "#322",
"bgcolor": "#533"
}
],
"links": [
[
42,
40,
0,
39,
0,
"MODEL"
],
[
44,
41,
0,
39,
1,
"CONDITIONING"
],
[
45,
42,
0,
39,
2,
"CONDITIONING"
],
[
48,
39,
0,
45,
0,
"LATENT"
],
[
49,
40,
2,
45,
1,
"VAE"
],
[
50,
40,
1,
41,
0,
"CLIP"
],
[
51,
40,
1,
42,
0,
"CLIP"
],
[
55,
45,
0,
48,
0,
"IMAGE"
],
[
56,
11,
0,
50,
0,
"IMAGE"
],
[
57,
40,
2,
50,
1,
"VAE"
],
[
58,
50,
0,
39,
3,
"LATENT"
],
[
59,
11,
0,
51,
0,
"IMAGE"
],
[
60,
51,
0,
41,
1,
"STRING"
]
],
"groups": [],
"config": {},
"extra": {
"ds": {
"scale": 0.9090909090909091,
"offset": {
"0": 304.575645264068,
"1": -258.56908735931404
}
}
},
"version": 0.4
}
@@ -0,0 +1,705 @@
{
"last_node_id": 61,
"last_link_id": 80,
"nodes": [
{
"id": 45,
"type": "VAEDecode",
"pos": [
1998,
1018
],
"size": {
"0": 210,
"1": 46
},
"flags": {},
"order": 10,
"mode": 0,
"inputs": [
{
"name": "samples",
"type": "LATENT",
"link": 71
},
{
"name": "vae",
"type": "VAE",
"link": 49
}
],
"outputs": [
{
"name": "IMAGE",
"type": "IMAGE",
"links": [
55
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "VAEDecode"
}
},
{
"id": 42,
"type": "CLIPTextEncode",
"pos": [
1056,
683
],
"size": {
"0": 352.9139404296875,
"1": 113.16606140136719
},
"flags": {},
"order": 2,
"mode": 0,
"inputs": [
{
"name": "clip",
"type": "CLIP",
"link": 51
}
],
"outputs": [
{
"name": "CONDITIONING",
"type": "CONDITIONING",
"links": [
63
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "CLIPTextEncode"
},
"widgets_values": [
"text, watermark"
]
},
{
"id": 41,
"type": "CLIPTextEncode",
"pos": [
1055,
571
],
"size": {
"0": 348.9403381347656,
"1": 56.439388275146484
},
"flags": {},
"order": 6,
"mode": 0,
"inputs": [
{
"name": "clip",
"type": "CLIP",
"link": 50
},
{
"name": "text",
"type": "STRING",
"link": 80,
"widget": {
"name": "text"
}
}
],
"outputs": [
{
"name": "CONDITIONING",
"type": "CONDITIONING",
"links": [
64
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "CLIPTextEncode"
},
"widgets_values": [
""
]
},
{
"id": 58,
"type": "PreviewImage",
"pos": [
616,
1631
],
"size": {
"0": 401.17840576171875,
"1": 246
},
"flags": {},
"order": 7,
"mode": 0,
"inputs": [
{
"name": "images",
"type": "IMAGE",
"link": 73
}
],
"properties": {
"Node name for S&R": "PreviewImage"
}
},
{
"id": 57,
"type": "MaskToImage",
"pos": [
617,
1543
],
"size": {
"0": 210,
"1": 26
},
"flags": {},
"order": 5,
"mode": 0,
"inputs": [
{
"name": "mask",
"type": "MASK",
"link": 78
}
],
"outputs": [
{
"name": "IMAGE",
"type": "IMAGE",
"links": [
73
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "MaskToImage"
}
},
{
"id": 40,
"type": "CheckpointLoaderSimple",
"pos": [
1044,
1032
],
"size": {
"0": 315,
"1": 98
},
"flags": {},
"order": 0,
"mode": 0,
"outputs": [
{
"name": "MODEL",
"type": "MODEL",
"links": [
68
],
"shape": 3,
"slot_index": 0
},
{
"name": "CLIP",
"type": "CLIP",
"links": [
50,
51
],
"shape": 3,
"slot_index": 1
},
{
"name": "VAE",
"type": "VAE",
"links": [
49,
69
],
"shape": 3,
"slot_index": 2
}
],
"properties": {
"Node name for S&R": "CheckpointLoaderSimple"
},
"widgets_values": [
"experience_70-inpainting.safetensors"
]
},
{
"id": 48,
"type": "PreviewImage",
"pos": [
2039,
1262
],
"size": {
"0": 295.2332458496094,
"1": 293.2945251464844
},
"flags": {},
"order": 11,
"mode": 0,
"inputs": [
{
"name": "images",
"type": "IMAGE",
"link": 55
}
],
"properties": {
"Node name for S&R": "PreviewImage"
}
},
{
"id": 56,
"type": "KSampler",
"pos": [
1642,
820
],
"size": {
"0": 315,
"1": 262
},
"flags": {},
"order": 9,
"mode": 0,
"inputs": [
{
"name": "model",
"type": "MODEL",
"link": 68
},
{
"name": "positive",
"type": "CONDITIONING",
"link": 66
},
{
"name": "negative",
"type": "CONDITIONING",
"link": 67
},
{
"name": "latent_image",
"type": "LATENT",
"link": 65
}
],
"outputs": [
{
"name": "LATENT",
"type": "LATENT",
"links": [
71
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "KSampler"
},
"widgets_values": [
492464952856155,
"randomize",
30,
7,
"dpmpp_2m_sde_gpu",
"normal",
0.8
]
},
{
"id": 55,
"type": "ImageColorToMask",
"pos": [
610,
1425
],
"size": {
"0": 315,
"1": 58
},
"flags": {},
"order": 3,
"mode": 0,
"inputs": [
{
"name": "image",
"type": "IMAGE",
"link": 61
}
],
"outputs": [
{
"name": "MASK",
"type": "MASK",
"links": [
77,
78
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "ImageColorToMask"
},
"widgets_values": [
6198527
]
},
{
"id": 54,
"type": "InpaintModelConditioning",
"pos": [
1289,
1377
],
"size": {
"0": 216.59999084472656,
"1": 106
},
"flags": {},
"order": 8,
"mode": 0,
"inputs": [
{
"name": "positive",
"type": "CONDITIONING",
"link": 64
},
{
"name": "negative",
"type": "CONDITIONING",
"link": 63
},
{
"name": "vae",
"type": "VAE",
"link": 69
},
{
"name": "pixels",
"type": "IMAGE",
"link": 70
},
{
"name": "mask",
"type": "MASK",
"link": 77
}
],
"outputs": [
{
"name": "positive",
"type": "CONDITIONING",
"links": [
66
],
"shape": 3,
"slot_index": 0
},
{
"name": "negative",
"type": "CONDITIONING",
"links": [
67
],
"shape": 3,
"slot_index": 1
},
{
"name": "latent",
"type": "LATENT",
"links": [
65
],
"shape": 3,
"slot_index": 2
}
],
"properties": {
"Node name for S&R": "InpaintModelConditioning"
}
},
{
"id": 11,
"type": "LoadImage",
"pos": [
-135,
907
],
"size": {
"0": 670,
"1": 460
},
"flags": {},
"order": 1,
"mode": 0,
"outputs": [
{
"name": "IMAGE",
"type": "IMAGE",
"links": [
61,
70,
79
],
"shape": 3,
"slot_index": 0
},
{
"name": "MASK",
"type": "MASK",
"links": [],
"shape": 3,
"slot_index": 1
}
],
"properties": {
"Node name for S&R": "LoadImage"
},
"widgets_values": [
"example.png",
"image"
]
},
{
"id": 61,
"type": "img2txt BLIP/Llava Multimodel Tagger",
"pos": [
599,
886
],
"size": [
414.8329491017887,
453.3791344354013
],
"flags": {},
"order": 4,
"mode": 0,
"inputs": [
{
"name": "input_image",
"type": "IMAGE",
"link": 79
}
],
"outputs": [
{
"name": "caption",
"type": "STRING",
"links": [
80
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "img2txt BLIP/Llava Multimodel Tagger"
},
"widgets_values": [
true,
false,
false,
false,
"a photograph of",
"What is the subject of this image?\n",
0.8,
1.2,
36,
128,
5,
"watermark, text, writing"
],
"color": "#322",
"bgcolor": "#533"
}
],
"links": [
[
49,
40,
2,
45,
1,
"VAE"
],
[
50,
40,
1,
41,
0,
"CLIP"
],
[
51,
40,
1,
42,
0,
"CLIP"
],
[
55,
45,
0,
48,
0,
"IMAGE"
],
[
61,
11,
0,
55,
0,
"IMAGE"
],
[
63,
42,
0,
54,
1,
"CONDITIONING"
],
[
64,
41,
0,
54,
0,
"CONDITIONING"
],
[
65,
54,
2,
56,
3,
"LATENT"
],
[
66,
54,
0,
56,
1,
"CONDITIONING"
],
[
67,
54,
1,
56,
2,
"CONDITIONING"
],
[
68,
40,
0,
56,
0,
"MODEL"
],
[
69,
40,
2,
54,
2,
"VAE"
],
[
70,
11,
0,
54,
3,
"IMAGE"
],
[
71,
56,
0,
45,
0,
"LATENT"
],
[
73,
57,
0,
58,
0,
"IMAGE"
],
[
77,
55,
0,
54,
4,
"MASK"
],
[
78,
55,
0,
57,
0,
"MASK"
],
[
79,
11,
0,
61,
0,
"IMAGE"
],
[
80,
61,
0,
41,
1,
"STRING"
]
],
"groups": [],
"config": {},
"extra": {
"ds": {
"scale": 0.8264462809917354,
"offset": {
"0": 478.9515963527572,
"1": -472.76124333876595
}
}
},
"version": 0.4
}
@@ -0,0 +1,498 @@
{
"last_node_id": 53,
"last_link_id": 61,
"nodes": [
{
"id": 41,
"type": "CLIPTextEncode",
"pos": [
1055,
571
],
"size": {
"0": 348.9403381347656,
"1": 56.439388275146484
},
"flags": {},
"order": 5,
"mode": 0,
"inputs": [
{
"name": "clip",
"type": "CLIP",
"link": 50
},
{
"name": "text",
"type": "STRING",
"link": 61,
"widget": {
"name": "text"
}
}
],
"outputs": [
{
"name": "CONDITIONING",
"type": "CONDITIONING",
"links": [
44
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "CLIPTextEncode"
},
"widgets_values": [
""
]
},
{
"id": 39,
"type": "KSampler",
"pos": [
1587,
982
],
"size": {
"0": 315,
"1": 262
},
"flags": {},
"order": 6,
"mode": 0,
"inputs": [
{
"name": "model",
"type": "MODEL",
"link": 42
},
{
"name": "positive",
"type": "CONDITIONING",
"link": 44
},
{
"name": "negative",
"type": "CONDITIONING",
"link": 45
},
{
"name": "latent_image",
"type": "LATENT",
"link": 59
}
],
"outputs": [
{
"name": "LATENT",
"type": "LATENT",
"links": [
48
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "KSampler"
},
"widgets_values": [
438454791536393,
"randomize",
20,
8,
"euler",
"normal",
1
]
},
{
"id": 45,
"type": "VAEDecode",
"pos": [
1998,
1018
],
"size": {
"0": 210,
"1": 46
},
"flags": {},
"order": 7,
"mode": 0,
"inputs": [
{
"name": "samples",
"type": "LATENT",
"link": 48
},
{
"name": "vae",
"type": "VAE",
"link": 49
}
],
"outputs": [
{
"name": "IMAGE",
"type": "IMAGE",
"links": [
55
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "VAEDecode"
}
},
{
"id": 48,
"type": "PreviewImage",
"pos": [
2039,
1262
],
"size": {
"0": 210,
"1": 246
},
"flags": {},
"order": 8,
"mode": 0,
"inputs": [
{
"name": "images",
"type": "IMAGE",
"link": 55
}
],
"properties": {
"Node name for S&R": "PreviewImage"
}
},
{
"id": 42,
"type": "CLIPTextEncode",
"pos": [
1056,
683
],
"size": {
"0": 352.9139404296875,
"1": 113.16606140136719
},
"flags": {},
"order": 4,
"mode": 0,
"inputs": [
{
"name": "clip",
"type": "CLIP",
"link": 51
}
],
"outputs": [
{
"name": "CONDITIONING",
"type": "CONDITIONING",
"links": [
45
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "CLIPTextEncode"
},
"widgets_values": [
"text, watermark"
]
},
{
"id": 52,
"type": "EmptyLatentImage",
"pos": [
1126,
1189
],
"size": {
"0": 315,
"1": 106
},
"flags": {},
"order": 0,
"mode": 0,
"outputs": [
{
"name": "LATENT",
"type": "LATENT",
"links": [
59
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "EmptyLatentImage"
},
"widgets_values": [
512,
512,
1
]
},
{
"id": 11,
"type": "LoadImage",
"pos": [
-135,
907
],
"size": {
"0": 670,
"1": 460
},
"flags": {},
"order": 1,
"mode": 0,
"outputs": [
{
"name": "IMAGE",
"type": "IMAGE",
"links": [
60
],
"shape": 3,
"slot_index": 0
},
{
"name": "MASK",
"type": "MASK",
"links": [],
"shape": 3,
"slot_index": 1
}
],
"properties": {
"Node name for S&R": "LoadImage"
},
"widgets_values": [
"example.png",
"image"
]
},
{
"id": 40,
"type": "CheckpointLoaderSimple",
"pos": [
1124,
1019
],
"size": {
"0": 315,
"1": 98
},
"flags": {},
"order": 2,
"mode": 0,
"outputs": [
{
"name": "MODEL",
"type": "MODEL",
"links": [
42
],
"shape": 3,
"slot_index": 0
},
{
"name": "CLIP",
"type": "CLIP",
"links": [
50,
51
],
"shape": 3,
"slot_index": 1
},
{
"name": "VAE",
"type": "VAE",
"links": [
49
],
"shape": 3,
"slot_index": 2
}
],
"properties": {
"Node name for S&R": "CheckpointLoaderSimple"
},
"widgets_values": [
"dreamshaper_8.safetensors"
]
},
{
"id": 53,
"type": "img2txt BLIP/Llava Multimodel Tagger",
"pos": [
584,
865
],
"size": [
462.2727684830322,
532.8236759410865
],
"flags": {},
"order": 3,
"mode": 0,
"inputs": [
{
"name": "input_image",
"type": "IMAGE",
"link": 60
}
],
"outputs": [
{
"name": "caption",
"type": "STRING",
"links": [
61
],
"shape": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "img2txt BLIP/Llava Multimodel Tagger"
},
"widgets_values": [
false,
false,
true,
false,
"a photograph of",
"What is a detailed description of this image?\nWhat is the background of this image?",
0.8,
1.2,
36,
128,
5,
"watermark, text, writing",
"The image features a cartoon character standing against an abstract background consisting of green, blue, and white elements. The main focus is on the woman with bright yellow wings wearing pink attire while smiling at something off-frame in front of her that seems to be representing \"clouds\" or possibly another object within view but not clearly visible due to its distance from us as viewers., "
],
"color": "#322",
"bgcolor": "#533"
}
],
"links": [
[
42,
40,
0,
39,
0,
"MODEL"
],
[
44,
41,
0,
39,
1,
"CONDITIONING"
],
[
45,
42,
0,
39,
2,
"CONDITIONING"
],
[
48,
39,
0,
45,
0,
"LATENT"
],
[
49,
40,
2,
45,
1,
"VAE"
],
[
50,
40,
1,
41,
0,
"CLIP"
],
[
51,
40,
1,
42,
0,
"CLIP"
],
[
55,
45,
0,
48,
0,
"IMAGE"
],
[
59,
52,
0,
39,
3,
"LATENT"
],
[
60,
11,
0,
53,
0,
"IMAGE"
],
[
61,
53,
0,
41,
1,
"STRING"
]
],
"groups": [],
"config": {},
"extra": {
"ds": {
"scale": 0.9090909090909091,
"offset": {
"0": 278.52736579431155,
"1": -323.6237095104226
}
}
},
"version": 0.4
}