V1.2 - start

This commit is contained in:
Leslie Perjes
2023-12-17 21:48:58 +01:00
commit 50ed73aebd
42 changed files with 82767 additions and 0 deletions
+8
View File
@@ -0,0 +1,8 @@
.idea
/!Examples/
wildcards
stylecsv
consoletests
*.safetensors
reqgen.py
front_end/images
+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>.
+925
View File
@@ -0,0 +1,925 @@
from custom_nodes.ComfyUI_Primere_Nodes.components.tree import TREE_DASHBOARD
from custom_nodes.ComfyUI_Primere_Nodes.components.tree import PRIMERE_ROOT
import comfy.samplers
import folder_paths
import nodes
import torch
import torch.nn.functional as F
from .modules.latent_noise import PowerLawNoise
import random
import os
import tomli
from .modules.adv_encode import advanced_encode, advanced_encode_XL
from nodes import MAX_RESOLUTION
from custom_nodes.ComfyUI_Primere_Nodes.components import utility
from pathlib import Path
import re
import requests
from custom_nodes.ComfyUI_Primere_Nodes.components import hypernetwork
import comfy.sd
import comfy.utils
class PrimereSamplers:
CATEGORY = TREE_DASHBOARD
RETURN_TYPES = (comfy.samplers.KSampler.SAMPLERS, comfy.samplers.KSampler.SCHEDULERS)
RETURN_NAMES = ("SAMPLER_NAME", "SCHEDULER_NAME")
FUNCTION = "get_sampler"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"sampler_name": (comfy.samplers.KSampler.SAMPLERS,),
"scheduler_name": (comfy.samplers.KSampler.SCHEDULERS,)
}
}
def get_sampler(self, sampler_name, scheduler_name):
return sampler_name, scheduler_name
class PrimereVAE:
RETURN_TYPES = ("VAE_NAME",)
RETURN_NAMES = ("VAE_NAME",)
FUNCTION = "load_vae_list"
CATEGORY = TREE_DASHBOARD
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"vae_model": (folder_paths.get_filename_list("vae"),)
},
}
def load_vae_list(self, vae_model):
return vae_model,
class PrimereCKPT:
RETURN_TYPES = ("CHECKPOINT_NAME", "STRING",)
RETURN_NAMES = ("MODEL_NAME", "MODEL_VERSION",)
FUNCTION = "load_ckpt_list"
CATEGORY = TREE_DASHBOARD
def __init__(self):
self.chkp_loader = nodes.CheckpointLoaderSimple()
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"base_model": (folder_paths.get_filename_list("checkpoints"),),
},
}
def load_ckpt_list(self, base_model):
LOADED_CHECKPOINT = self.chkp_loader.load_checkpoint(base_model)
model_version = utility.getCheckpointVersion(LOADED_CHECKPOINT[0])
return (base_model, model_version)
class PrimereVAELoader:
RETURN_TYPES = ("VAE",)
RETURN_NAMES = ("VAE",)
FUNCTION = "load_primere_vae"
CATEGORY = TREE_DASHBOARD
def __init__(self):
self.vae_loader = nodes.VAELoader()
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"vae_name": ("VAE_NAME",)
},
}
def load_primere_vae(self, vae_name, ):
return self.vae_loader.load_vae(vae_name)
class PrimereLCMSelector:
RETURN_TYPES = (comfy.samplers.KSampler.SAMPLERS, comfy.samplers.KSampler.SCHEDULERS, "INT", "FLOAT", "INT")
RETURN_NAMES = ("SAMPLER_NAME", "SCHEDULER_NAME", "STEPS", "CFG", "IS_LCM")
FUNCTION = "select_lcm_mode"
CATEGORY = TREE_DASHBOARD
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"use_lcm": ("BOOLEAN", {"default": False}),
"sampler_name": (comfy.samplers.KSampler.SAMPLERS, {"forceInput": True, "default": "euler"}),
"scheduler_name": (comfy.samplers.KSampler.SCHEDULERS, {"forceInput": True, "default": "normal"}),
"lcm_sampler_name": (comfy.samplers.KSampler.SAMPLERS, {"forceInput": True, "default": "lcm"}),
"lcm_scheduler_name": (comfy.samplers.KSampler.SCHEDULERS, {"forceInput": True, "default": "sgm_uniform"}),
"cfg_scale": ('FLOAT', {"forceInput": True, "default": 7}),
"steps": ('INT', {"forceInput": True, "default": 12}),
"lcm_cfg_scale": ('FLOAT', {"forceInput": True, "default": 1.2}),
"lcm_steps": ('INT', {"forceInput": True, "default": 6}),
},
}
def select_lcm_mode(self, use_lcm = False, sampler_name = 'euler', scheduler_name = 'normal', lcm_sampler_name = 'lcm', lcm_scheduler_name = 'sgm_uniform', cfg_scale = 7, steps = 12, lcm_cfg_scale = 1.2, lcm_steps = 6):
lcm_mode = 0
if use_lcm == True:
sampler_name = lcm_sampler_name
scheduler_name = lcm_scheduler_name
steps = lcm_steps
cfg_scale = lcm_cfg_scale
lcm_mode = 1
return (sampler_name, scheduler_name, steps, cfg_scale, lcm_mode,)
class PrimereCKPTLoader:
RETURN_TYPES = ("MODEL", "CLIP", "VAE", "STRING",)
RETURN_NAMES = ("MODEL", "CLIP", "VAE", "MODEL_VERSION")
FUNCTION = "load_primere_ckpt"
CATEGORY = TREE_DASHBOARD
def __init__(self):
self.chkp_loader = nodes.CheckpointLoaderSimple()
self.loaded_lora = None
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"ckpt_name": ("CHECKPOINT_NAME",),
"use_yaml": ("BOOLEAN", {"default": False}),
"is_lcm": ("INT", {"default": 0, "forceInput": True}),
"strength_lcm_model": ("FLOAT", {"default": 1.0, "min": -20.0, "max": 20.0, "step": 0.01}),
"strength_lcm_clip": ("FLOAT", {"default": 1.0, "min": -20.0, "max": 20.0, "step": 0.01}),
},
}
def load_primere_ckpt(self, ckpt_name, use_yaml, is_lcm, strength_lcm_model, strength_lcm_clip):
path = Path(ckpt_name)
ModelName = path.stem
ModelConfigPath = path.parent.joinpath(ModelName + '.yaml')
ModelConfigFullPath = Path(folder_paths.models_dir).joinpath('checkpoints').joinpath(ModelConfigPath)
if (os.path.isfile(ModelConfigFullPath) and use_yaml == True):
ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
print(ModelName + '.yaml file found and loading...')
try:
LOADED_CHECKPOINT = comfy.sd.load_checkpoint(ModelConfigFullPath, ckpt_path, True, True, None, None, None)
except Exception:
LOADED_CHECKPOINT = self.chkp_loader.load_checkpoint(ckpt_name)
else:
LOADED_CHECKPOINT = self.chkp_loader.load_checkpoint(ckpt_name)
OUTPUT_MODEL = LOADED_CHECKPOINT[0]
OUTPUT_CLIP = LOADED_CHECKPOINT[1]
MODEL_VERSION = utility.getCheckpointVersion(OUTPUT_MODEL)
def lcm(self, model, zsnr=False):
m = model.clone()
sampling_base = comfy.model_sampling.ModelSamplingDiscrete
sampling_type = utility.LCM
sampling_base = utility.ModelSamplingDiscreteLCM
class ModelSamplingAdvanced(sampling_base, sampling_type):
pass
model_sampling = ModelSamplingAdvanced()
if zsnr:
model_sampling.set_sigmas(utility.rescale_zero_terminal_snr_sigmas(model_sampling.sigmas))
m.add_object_patch("model_sampling", model_sampling)
return m
is_sdxl = 0
match MODEL_VERSION:
case 'SDXL_2048':
is_sdxl = 1
if is_lcm == 1:
SDXL_LORA = 'https://huggingface.co/latent-consistency/lcm-lora-sdxl/resolve/main/pytorch_lora_weights.safetensors?download=true'
SD_LORA = 'https://huggingface.co/latent-consistency/lcm-lora-sdv1-5/resolve/main/pytorch_lora_weights.safetensors?download=true'
DOWNLOADED_SD_LORA = os.path.join(PRIMERE_ROOT, 'Nodes', 'Downloads', 'lcm_lora_sd.safetensors')
DOWNLOADED_SDXL_LORA = os.path.join(PRIMERE_ROOT, 'Nodes', 'Downloads', 'lcm_lora_sdxl.safetensors')
if os.path.exists(DOWNLOADED_SD_LORA) == False:
print('Downloading SD LCM LORA....')
reqsdlcm = requests.get(SD_LORA, allow_redirects=True)
if reqsdlcm.status_code == 200 and reqsdlcm.ok == True:
open(DOWNLOADED_SD_LORA, 'wb').write(reqsdlcm.content)
else:
print('ERROR: Cannot dowload SD LCM Lora')
if os.path.exists(DOWNLOADED_SDXL_LORA) == False:
print('Downloading SDXL LCM LORA....')
reqsdxllcm = requests.get(SDXL_LORA, allow_redirects=True)
if reqsdxllcm.status_code == 200 and reqsdxllcm.ok == True:
open(DOWNLOADED_SDXL_LORA, 'wb').write(reqsdxllcm.content)
else:
print('ERROR: Cannot dowload SDXL LCM Lora')
if is_sdxl == 0:
LORA_PATH = DOWNLOADED_SD_LORA
else:
LORA_PATH = DOWNLOADED_SDXL_LORA
if os.path.exists(LORA_PATH) == True:
if strength_lcm_model > 0 or strength_lcm_clip > 0:
print('LCM mode on')
lora = None
if self.loaded_lora is not None:
if self.loaded_lora[0] == LORA_PATH:
lora = self.loaded_lora[1]
else:
temp = self.loaded_lora
self.loaded_lora = None
del temp
if lora is None:
lora = comfy.utils.load_torch_file(LORA_PATH, safe_load=True)
self.loaded_lora = (LORA_PATH, lora)
MODEL_LORA, CLIP_LORA = comfy.sd.load_lora_for_models(OUTPUT_MODEL, OUTPUT_CLIP, lora, strength_lcm_model, strength_lcm_clip)
OUTPUT_MODEL = lcm(self, MODEL_LORA, False)
OUTPUT_CLIP = CLIP_LORA
return (OUTPUT_MODEL,) + (OUTPUT_CLIP,) + (LOADED_CHECKPOINT[2],) + (MODEL_VERSION,)
class AnyType(str):
def __ne__(self, __value: object) -> bool:
return False
class PrimerePromptSwitch:
any_typ = AnyType("*")
RETURN_TYPES = (any_typ, any_typ, any_typ, any_typ, any_typ, "INT")
RETURN_NAMES = ("PROMPT+", "PROMPT-", "SUBPATH", "MODEL", "ORIENTATION", "SELECTED_INDEX")
FUNCTION = "promptswitch"
CATEGORY = TREE_DASHBOARD
@classmethod
def INPUT_TYPES(cls):
any_typ = AnyType("*")
return {
"required": {
"select": ("INT", {"default": 1, "min": 1, "max": 20, "step": 1}),
},
"optional": {
"prompt_pos_1": (any_typ,),
"prompt_neg_1": (any_typ,),
"subpath_1": (any_typ,),
"model_1": (any_typ,),
"orientation_1": (any_typ,),
},
}
def promptswitch(self, *args, **kwargs):
selected_index = int(kwargs['select'])
input_namep = f"prompt_pos_{selected_index}"
input_namen = f"prompt_neg_{selected_index}"
input_subpath = f"subpath_{selected_index}"
input_model = f"model_{selected_index}"
input_orientation = f"orientation_{selected_index}"
if input_subpath not in kwargs:
kwargs[input_subpath] = None
if input_model not in kwargs:
kwargs[input_model] = None
if input_orientation not in kwargs:
kwargs[input_orientation] = None
if input_namep in kwargs:
return (kwargs[input_namep], kwargs[input_namen], kwargs[input_subpath], kwargs[input_model], kwargs[input_orientation], selected_index)
else:
print(f"PrimerePromptSwitch: invalid select index (ignored)")
return (None, None, None, None, None, selected_index)
class PrimereSeed:
RETURN_TYPES = ("INT",)
RETURN_NAMES = ("SEED",)
FUNCTION = "seed"
CATEGORY = TREE_DASHBOARD
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"seed": ("INT", {
"default": -1,
"min": -18446744073709551615, # -1125899906842624,
"max": 18446744073709551615, # 1125899906842624
}),
},
}
def seed(self, seed = 0):
return (seed,)
class PrimereFractalLatent:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
pln = PowerLawNoise('cpu')
return {
"required": {
# "batch_size": ("INT", {"default": 1, "max": 64, "min": 1, "step": 1}),
"width": ("INT", {"default": 512, "max": 8192, "min": 64, "forceInput": True}),
"height": ("INT", {"default": 512, "max": 8192, "min": 64, "forceInput": True}),
# "resampling": (["nearest-exact", "bilinear", "area", "bicubic", "bislerp"],),
"rand_noise_type": ("BOOLEAN", {"default": False}),
"noise_type": (pln.get_noise_types(),),
# "scale": ("FLOAT", {"default": 1.0, "max": 1024.0, "min": 0.01, "step": 0.001}),
"rand_alpha_exponent": ("BOOLEAN", {"default": True}),
"alpha_exponent": ("FLOAT", {"default": 1.0, "max": 12.0, "min": -12.0, "step": 0.001}),
"alpha_exp_rand_min": ("FLOAT", {"default": 0.5, "max": 12.0, "min": -12.0, "step": 0.001}),
"alpha_exp_rand_max": ("FLOAT", {"default": 1.5, "max": 12.0, "min": -12.0, "step": 0.001}),
"rand_modulator": ("BOOLEAN", {"default": True}),
"modulator": ("FLOAT", {"default": 1.0, "max": 2.0, "min": 0.1, "step": 0.01}),
"modulator_rand_min": ("FLOAT", {"default": 0.8, "max": 2.0, "min": 0.1, "step": 0.01}),
"modulator_rand_max": ("FLOAT", {"default": 1.4, "max": 2.0, "min": 0.1, "step": 0.01}),
"seed": ("INT", {"default": 0, "min": -18446744073709551615, "max": 18446744073709551615, "forceInput": True}),
"rand_device": ("BOOLEAN", {"default": False}),
"device": (["cpu", "cuda"],),
},
"optional": {
"optional_vae": ("VAE",),
}
}
RETURN_TYPES = ("LATENT", "IMAGE")
RETURN_NAMES = ("LATENTS", "PREVIEWS")
FUNCTION = "primere_latent_noise"
CATEGORY = TREE_DASHBOARD
def primere_latent_noise(self, width, height, rand_noise_type, noise_type, rand_alpha_exponent, alpha_exponent, alpha_exp_rand_min, alpha_exp_rand_max, rand_modulator, modulator, modulator_rand_min, modulator_rand_max, seed, rand_device, device, optional_vae = None):
if rand_device == True:
device = random.choice(["cpu", "cuda"])
power_law = PowerLawNoise(device = device)
if rand_alpha_exponent == True:
alpha_exponent = round(random.uniform(alpha_exp_rand_min, alpha_exp_rand_max), 3)
if rand_modulator == True:
modulator = round(random.uniform(modulator_rand_min, modulator_rand_max), 2)
if rand_noise_type == True:
pln = PowerLawNoise(device)
noise_type = random.choice(pln.get_noise_types())
tensors = power_law(1, width, height, scale = 1, alpha = alpha_exponent, modulator = modulator, noise_type = noise_type, seed = seed)
alpha_channel = torch.ones((1, height, width, 1), dtype = tensors.dtype, device = "cpu")
tensors = torch.cat((tensors, alpha_channel), dim = 3)
if optional_vae is None:
latents = tensors.permute(0, 3, 1, 2)
latents = F.interpolate(latents, size=((height // 8), (width // 8)), mode = 'nearest-exact')
return {'samples': latents}, tensors
encoder = nodes.VAEEncode()
latents = []
for tensor in tensors:
tensor = tensor.unsqueeze(0)
latents.append(encoder.encode(optional_vae, tensor)[0]['samples'])
latents = torch.cat(latents)
return {'samples': latents}, tensors
class PrimereCLIP:
RETURN_TYPES = ("CONDITIONING", "CONDITIONING", "STRING", "STRING", "STRING", "STRING")
RETURN_NAMES = ("COND+", "COND-", "PROMPT+", "PROMPT-", "PROMPT L+", "PROMPT L-")
FUNCTION = "clip_encode"
CATEGORY = TREE_DASHBOARD
@staticmethod
def get_default_neg(toml_path: str):
with open(toml_path, "rb") as f:
style_def_neg = tomli.load(f)
return style_def_neg
@ classmethod
def INPUT_TYPES(cls):
DEF_TOML_DIR = os.path.join(PRIMERE_ROOT, 'Toml')
cls.default_neg = cls.get_default_neg(os.path.join(DEF_TOML_DIR, "default_neg.toml"))
cls.default_pos = cls.get_default_neg(os.path.join(DEF_TOML_DIR, "default_pos.toml"))
return {
"required": {
"clip": ("CLIP", ),
"model_version": ("STRING", {"default": 'BaseModel_1024', "forceInput": True}),
"positive_prompt": ("STRING", {"forceInput": True}),
"negative_prompt": ("STRING", {"forceInput": True}),
"negative_strength": ("FLOAT", {"default": 1.2, "min": 0.0, "max": 10.0, "step": 0.01}),
"use_int_style": ("BOOLEAN", {"default": False}),
"int_style_pos": (['None'] + sorted(list(cls.default_pos.keys())),),
"int_style_pos_strength": ("FLOAT", {"default": 1, "min": 0.0, "max": 10.0, "step": 0.01}),
"int_style_neg": (['None'] + sorted(list(cls.default_neg.keys())),),
"int_style_neg_strength": ("FLOAT", {"default": 1, "min": 0.0, "max": 10.0, "step": 0.01}),
"adv_encode": ("BOOLEAN", {"default": False}),
"token_normalization": (["none", "mean", "length", "length+mean"],),
"weight_interpretation": (["comfy", "A1111", "compel", "comfy++", "down_weight"],),
# "affect_pooled": ("BOOLEAN", {"default": False}),
},
"optional": {
"model_keywords": ("MODEL_KEYWORD", {"forceInput": True}),
"lora_keywords": ("MODEL_KEYWORD", {"forceInput": True}),
"embedding_pos": ("EMBEDDING", {"forceInput": True}),
"embedding_neg": ("EMBEDDING", {"forceInput": True}),
"opt_pos_prompt": ("STRING", {"forceInput": True}),
"opt_pos_strength": ("FLOAT", {"default": 1, "min": 0.0, "max": 10.0, "step": 0.01}),
"opt_neg_prompt": ("STRING", {"forceInput": True}),
"opt_neg_strength": ("FLOAT", {"default": 1, "min": 0.0, "max": 10.0, "step": 0.01}),
"style_pos_prompt": ("STRING", {"forceInput": True}),
"style_pos_strength": ("FLOAT", {"default": 1, "min": 0.0, "max": 10.0, "step": 0.01}),
"style_neg_prompt": ("STRING", {"forceInput": True}),
"style_neg_strength": ("FLOAT", {"default": 1, "min": 0.0, "max": 10.0, "step": 0.01}),
"sdxl_positive_l": ("STRING", {"forceInput": True}),
"sdxl_negative_l": ("STRING", {"forceInput": True}),
"copy_prompt_to_l": ("BOOLEAN", {"default": True}),
"sdxl_l_strength": ("FLOAT", {"default": 1, "min": 0.0, "max": 10.0, "step": 0.01}),
"width": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION, "forceInput": True}),
"height": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION, "forceInput": True}),
}
}
def clip_encode(self, clip, negative_strength, int_style_pos_strength, int_style_neg_strength, opt_pos_strength, opt_neg_strength, style_pos_strength, style_neg_strength, int_style_pos, int_style_neg, adv_encode, token_normalization, weight_interpretation, sdxl_l_strength, copy_prompt_to_l = True, width = 1024, height = 1024, positive_prompt = "", negative_prompt = "", model_keywords = None, lora_keywords = None, embedding_pos = None, embedding_neg = None, opt_pos_prompt = "", opt_neg_prompt = "", style_neg_prompt = "", style_pos_prompt = "", sdxl_positive_l = "", sdxl_negative_l = "", use_int_style = False, model_version = "BaseModel_1024"):
is_sdxl = 0
match model_version:
case 'SDXL_2048':
is_sdxl = 1
additional_positive = int_style_pos
additional_negative = int_style_neg
if int_style_pos == 'None' or use_int_style == False:
additional_positive = None
if int_style_neg == 'None' or use_int_style == False:
additional_negative = None
if use_int_style == True:
if int_style_pos != 'None':
additional_positive = self.default_pos[int_style_pos]['positive'].strip(' ,;')
if int_style_neg != 'None':
additional_negative = self.default_neg[int_style_neg]['negative'].strip(' ,;')
additional_positive = f'({additional_positive}:{int_style_pos_strength:.2f})' if additional_positive is not None and additional_positive != '' else ''
additional_negative = f'({additional_negative}:{int_style_neg_strength:.2f})' if additional_negative is not None and additional_negative != '' else ''
negative_prompt = f'({negative_prompt}:{negative_strength:.2f})' if negative_prompt is not None and negative_prompt.strip(' ,;') != '' else ''
if copy_prompt_to_l == True:
sdxl_positive_l = positive_prompt
sdxl_negative_l = negative_prompt
opt_pos_prompt = f'({opt_pos_prompt}:{opt_pos_strength:.2f})' if opt_pos_prompt is not None and opt_pos_prompt.strip(' ,;') != '' else ''
opt_neg_prompt = f'({opt_neg_prompt}:{opt_neg_strength:.2f})' if opt_neg_prompt is not None and opt_neg_prompt.strip(' ,;') != '' else ''
style_pos_prompt = f'({style_pos_prompt}:{style_pos_strength:.2f})' if style_pos_prompt is not None and style_pos_prompt.strip(' ,;') != '' else ''
style_neg_prompt = f'({style_neg_prompt}:{style_neg_strength:.2f})' if style_neg_prompt is not None and style_neg_prompt.strip(' ,;') != '' else ''
sdxl_positive_l = f'({sdxl_positive_l}:{sdxl_l_strength:.2f})'.replace(":1.00", "") if sdxl_positive_l is not None and sdxl_positive_l.strip(' ,;') != '' else ''
sdxl_negative_l = f'({sdxl_negative_l}:{sdxl_l_strength:.2f})'.replace(":1.00", "") if sdxl_negative_l is not None and sdxl_negative_l.strip(' ,;') != '' else ''
positive_text = f'{positive_prompt}, {opt_pos_prompt}, {style_pos_prompt}, {additional_positive}'.strip(' ,;').replace(", , ", ", ").replace(", , ", ", ").replace(":1.00", "")
negative_text = f'{negative_prompt}, {opt_neg_prompt}, {style_neg_prompt}, {additional_negative}'.strip(' ,;').replace(", , ", ", ").replace(", , ", ", ").replace(":1.00", "")
if model_keywords is not None:
mkw_list = list(filter(None, model_keywords))
if len(mkw_list) == 2:
model_keyword = mkw_list[0]
mplacement = mkw_list[1]
if (mplacement == 'First'):
positive_text = model_keyword + ', ' + positive_text
else:
positive_text = positive_text + ', ' + model_keyword
if lora_keywords is not None:
lkw_list = list(filter(None, lora_keywords))
if len(lkw_list) == 2:
lora_keyword = lkw_list[0]
lplacement = lkw_list[1]
if (lplacement == 'First'):
positive_text = lora_keyword + ', ' + positive_text
else:
positive_text = positive_text + ', ' + lora_keyword
if embedding_pos is not None:
embp_list = list(filter(None, embedding_pos))
if len(embp_list) == 2:
embp_keyword = embp_list[0]
embp_placement = embp_list[1]
if (embp_placement == 'First'):
positive_text = embp_keyword + ', ' + positive_text
else:
positive_text = positive_text + ', ' + embp_keyword
if embedding_neg is not None:
embn_list = list(filter(None, embedding_neg))
if len(embn_list) == 2:
embn_keyword = embn_list[0]
embn_placement = embn_list[1]
if (embn_placement == 'First'):
negative_text = embn_keyword + ', ' + negative_text
else:
negative_text = negative_text + ', ' + embn_keyword
if (model_version == 'BaseModel_1024'):
adv_encode = False
if (adv_encode == True):
if (is_sdxl == 0):
embeddings_final_pos, pooled_pos = advanced_encode(clip, positive_text, token_normalization, weight_interpretation, w_max = 1.0, apply_to_pooled = True)
embeddings_final_neg, pooled_neg = advanced_encode(clip, negative_text, token_normalization, weight_interpretation, w_max = 1.0, apply_to_pooled = True)
return ([[embeddings_final_pos, {"pooled_output": pooled_pos}]], [[embeddings_final_neg, {"pooled_output": pooled_neg}]], positive_text, negative_text, "", "")
else:
# embeddings_final_pos, pooled_pos = advanced_encode_XL(clip, sdxl_positive_l, positive_text, token_normalization, weight_interpretation, w_max = 1.0, clip_balance = sdxl_balance_l, apply_to_pooled = True)
# embeddings_final_neg, pooled_neg = advanced_encode_XL(clip, sdxl_negative_l, negative_text, token_normalization, weight_interpretation, w_max = 1.0, clip_balance = sdxl_balance_l, apply_to_pooled = True)
# return ([[embeddings_final_pos, {"pooled_output": pooled_pos}]],[[embeddings_final_neg, {"pooled_output": pooled_neg}]], positive_text, negative_text, sdxl_positive_l, sdxl_negative_l)
tokens_p = clip.tokenize(positive_text)
tokens_p["l"] = clip.tokenize(sdxl_positive_l)["l"]
if len(tokens_p["l"]) != len(tokens_p["g"]):
empty = clip.tokenize("")
while len(tokens_p["l"]) < len(tokens_p["g"]):
tokens_p["l"] += empty["l"]
while len(tokens_p["l"]) > len(tokens_p["g"]):
tokens_p["g"] += empty["g"]
tokens_n = clip.tokenize(negative_text)
tokens_n["l"] = clip.tokenize(sdxl_negative_l)["l"]
if len(tokens_n["l"]) != len(tokens_n["g"]):
empty = clip.tokenize("")
while len(tokens_n["l"]) < len(tokens_n["g"]):
tokens_n["l"] += empty["l"]
while len(tokens_n["l"]) > len(tokens_n["g"]):
tokens_n["g"] += empty["g"]
cond_p, pooled_p = clip.encode_from_tokens(tokens_p, return_pooled = True)
cond_n, pooled_n = clip.encode_from_tokens(tokens_n, return_pooled = True)
return ([[cond_p, {"pooled_output": pooled_p, "width": width, "height": height, "crop_w": 0, "crop_h": 0, "target_width": width, "target_height": height}]], [[cond_n, {"pooled_output": pooled_n, "width": width, "height": height, "crop_w": 0, "crop_h": 0, "target_width": width, "target_height": height}]], positive_text, negative_text, sdxl_positive_l, sdxl_negative_l)
else:
tokens = clip.tokenize(positive_text)
cond_pos, pooled_pos = clip.encode_from_tokens(tokens, return_pooled = True)
tokens = clip.tokenize(negative_text)
cond_neg, pooled_neg = clip.encode_from_tokens(tokens, return_pooled = True)
return ([[cond_pos, {"pooled_output": pooled_pos}]], [[cond_neg, {"pooled_output": pooled_neg}]], positive_text, negative_text, "", "")
class PrimereResolution:
RETURN_TYPES = ("INT", "INT",)
RETURN_NAMES = ("WIDTH", "HEIGHT",)
FUNCTION = "calculate_imagesize"
CATEGORY = TREE_DASHBOARD
@staticmethod
def get_ratios(toml_path: str):
with open(toml_path, "rb") as f:
image_ratios = tomli.load(f)
return image_ratios
@ classmethod
def INPUT_TYPES(cls):
DEF_TOML_DIR = os.path.join(PRIMERE_ROOT, 'Toml')
cls.sd_ratios = cls.get_ratios(os.path.join(DEF_TOML_DIR, "resolution_ratios.toml"))
namelist = {}
for sd_ratio_key in cls.sd_ratios:
rationName = cls.sd_ratios[sd_ratio_key]['name']
namelist[rationName] = sd_ratio_key
cls.ratioNames = namelist
return {
"required": {
"ratio": (list(namelist.keys()),),
# "force_768_SD1x": ("BOOLEAN", {"default": True}),
"basemodel_res": ([512, 768, 1024, 1280], {"default": 768}),
"rnd_orientation": ("BOOLEAN", {"default": False}),
"orientation": (["Horizontal", "Vertical"], {"default": "Horizontal"}),
"round_to_standard": ("BOOLEAN", {"default": False}),
"model_version": ("STRING", {"default": 'BaseModel_1024', "forceInput": True}),
"seed": ("INT", {"default": 0, "min": -18446744073709551615, "max": 18446744073709551615, "forceInput": True}),
"calculate_by_custom": ("BOOLEAN", {"default": False}),
"custom_side_a": ("FLOAT", {"default": 1.6, "min": 1.0, "max": 100.0, "step": 0.1}),
"custom_side_b": ("FLOAT", {"default": 2.8, "min": 1.0, "max": 100.0, "step": 0.1}),
},
}
def calculate_imagesize(self, ratio: str, basemodel_res: int, rnd_orientation: bool, orientation: str, round_to_standard: bool, model_version: str, seed: int, calculate_by_custom: bool, custom_side_a: float, custom_side_b: float):
if rnd_orientation == True:
if (seed % 2) == 0:
orientation = "Horizontal"
else:
orientation = "Vertical"
# if force_768_SD1x == True and model_version == 'BaseModel_768':
# model_version = 'BaseModel_1024'
if model_version == 'BaseModel_768':
match basemodel_res:
case 512:
model_version = 'BaseModel_768'
case 768:
model_version = 'BaseModel_1024'
case 1024:
model_version = 'BaseModel_mod_1024'
case 1280:
model_version = 'BaseModel_mod_1280'
dimensions = utility.calculate_dimensions(self, ratio, orientation, round_to_standard, model_version, calculate_by_custom, custom_side_a, custom_side_b)
dimension_x = dimensions[0]
dimension_y = dimensions[1]
return (dimension_x, dimension_y,)
class PrimereResolutionMultiplier:
RETURN_TYPES = ("INT", "INT", "FLOAT")
RETURN_NAMES = ("WIDTH", "HEIGHT", "UPSCALE_RATIO")
FUNCTION = "multiply_imagesize"
CATEGORY = TREE_DASHBOARD
@ classmethod
def INPUT_TYPES(cls):
return {
"required": {
"width": ('INT', {"forceInput": True, "default": 512}),
"height": ('INT', {"forceInput": True, "default": 512}),
"model_version": ("STRING", {"default": 'BaseModel_1024', "forceInput": True}),
"use_multiplier": ("BOOLEAN", {"default": True}),
"multiply_sd": ("FLOAT", {"default": 2.0, "min": 0.1, "max": 8.0, "step": 0.1}),
"multiply_sdxl": ("FLOAT", {"default": 2.0, "min": 0.1, "max": 8.0, "step": 0.1}),
},
}
def multiply_imagesize(self, width: int, height: int, use_multiplier: bool, multiply_sd: float, multiply_sdxl: float, model_version: str):
is_sdxl = 0
match model_version:
case 'SDXL_2048':
is_sdxl = 1
if use_multiplier == False:
multiply_sd = 1
multiply_sdxl = 1
if (is_sdxl == 1):
dimension_x = round(width * multiply_sdxl)
dimension_y = round(height * multiply_sdxl)
ratio = round(multiply_sdxl, 2)
else:
dimension_x = round(width * multiply_sd)
dimension_y = round(height * multiply_sd)
ratio = round(multiply_sd, 2)
return (dimension_x, dimension_y, ratio)
class PrimereStepsCfg:
RETURN_TYPES = ("INT", "FLOAT")
RETURN_NAMES = ("STEPS", "CFG")
FUNCTION = "steps_cfg"
CATEGORY = TREE_DASHBOARD
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"steps": ("INT", {"default": 12, "min": 1, "max": 1000, "step": 1}),
"cfg": ("FLOAT", {"default": 7, "min": 0.1, "max": 100, "step": 0.01}),
},
}
def steps_cfg(self, steps = 12, cfg = 7):
return (steps, cfg,)
class PrimereClearPrompt:
RETURN_TYPES = ("STRING", "STRING")
RETURN_NAMES = ("PROMPT+", "PROMPT-")
FUNCTION = "clean_prompt"
CATEGORY = TREE_DASHBOARD
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"model_version": ("STRING", {"default": 'BaseModel_1024', "forceInput": True}),
"positive_prompt": ("STRING", {"forceInput": True}),
"negative_prompt": ("STRING", {"forceInput": True}),
"remove_only_if_sdxl": ("BOOLEAN", {"default": False}),
"remove_comfy_embedding": ("BOOLEAN", {"default": False}),
"remove_a1111_embedding": ("BOOLEAN", {"default": False}),
"remove_lora": ("BOOLEAN", {"default": False}),
"remove_hypernetwork": ("BOOLEAN", {"default": False}),
},
}
def clean_prompt(self, positive_prompt, negative_prompt, remove_comfy_embedding, remove_a1111_embedding, remove_lora, remove_hypernetwork, remove_only_if_sdxl, model_version = 'BaseModel_1024'):
NETWORK_START = []
is_sdxl = 0
match model_version:
case 'SDXL_2048':
is_sdxl = 1
if remove_only_if_sdxl == True and is_sdxl == 0:
return (positive_prompt, negative_prompt,)
if remove_comfy_embedding == True:
NETWORK_START.append('embedding:')
if remove_lora == True:
NETWORK_START.append('<lora:')
if remove_hypernetwork == True:
NETWORK_START.append('<hypernet:')
if remove_a1111_embedding == True:
positive_prompt = positive_prompt.replace('embedding:', '')
negative_prompt = negative_prompt.replace('embedding:', '')
EMBEDDINGS = folder_paths.get_filename_list("embeddings")
for embeddings_path in EMBEDDINGS:
path = Path(embeddings_path)
embedding_name = path.stem
positive_prompt = re.sub("(\(" + embedding_name + ":\d+\.\d+\))|(\(" + embedding_name + ":\d+\))|(" + embedding_name + ":\d+\.\d+)|(" + embedding_name + ":\d+)|(" + embedding_name + ":)|(\(" + embedding_name + "\))|(" + embedding_name + ")", "", positive_prompt)
negative_prompt = re.sub("(\(" + embedding_name + ":\d+\.\d+\))|(\(" + embedding_name + ":\d+\))|(" + embedding_name + ":\d+\.\d+)|(" + embedding_name + ":\d+)|(" + embedding_name + ":)|(\(" + embedding_name + "\))|(" + embedding_name + ")", "", negative_prompt)
positive_prompt = re.sub(r'(, )\1+', r', ', positive_prompt).strip(', ').replace(' ,', ',')
negative_prompt = re.sub(r'(, )\1+', r', ', negative_prompt).strip(', ').replace(' ,', ',')
if len(NETWORK_START) > 0:
NETWORK_END = ['\n', '>', ' ', ',', '}', ')', '|'] + NETWORK_START
positive_prompt = utility.clear_prompt(NETWORK_START, NETWORK_END, positive_prompt)
negative_prompt = utility.clear_prompt(NETWORK_START, NETWORK_END, negative_prompt)
return (positive_prompt, negative_prompt,)
class PrimereNetworkTagLoader:
RETURN_TYPES = ("MODEL", "CLIP", "LORA_STACK", "HYPERNETWORK_STACK", "MODEL_KEYWORD")
RETURN_NAMES = ("MODEL", "CLIP", "LORA_STACK", "HYPERNETWORK_STACK", "LORA_KEYWORD")
FUNCTION = "load_networks"
CATEGORY = TREE_DASHBOARD
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model": ("MODEL",),
"clip": ("CLIP",),
"positive_prompt": ("STRING", {"forceInput": True}),
"process_lora": ("BOOLEAN", {"default": True}),
"process_hypernetwork": ("BOOLEAN", {"default": True}),
"copy_weight_to_clip": ("BOOLEAN", {"default": False}),
"lora_clip_custom_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_lora_keyword": ("BOOLEAN", {"default": False}),
"lora_keyword_placement": (["First", "Last"], {"default": "Last"}),
"lora_keyword_selection": (["Select in order", "Random select"], {"default": "Select in order"}),
"lora_keywords_num": ("INT", {"default": 1, "min": 1, "max": 50, "step": 1}),
"lora_keyword_weight": ("FLOAT", {"default": 1.0, "min": 0, "max": 10.0, "step": 0.1}),
}
}
def load_networks(self, model, clip, positive_prompt, process_lora, process_hypernetwork, copy_weight_to_clip, lora_clip_custom_weight, use_lora_keyword, lora_keyword_placement, lora_keyword_selection, lora_keywords_num, lora_keyword_weight):
NETWORK_START = []
cloned_model = model
cloned_clip = clip
list_of_keyword_items = []
lora_keywords_num_set = lora_keywords_num
model_keyword = [None, None]
lora_stack = []
hnet_stack = []
HypernetworkList = folder_paths.get_filename_list("hypernetworks")
LoraList = folder_paths.get_filename_list("loras")
if process_lora == True:
NETWORK_START.append('<lora:')
if process_hypernetwork == True:
NETWORK_START.append('<hypernet:')
if len(NETWORK_START) == 0:
return (model, clip, lora_stack, hnet_stack, model_keyword)
else:
NETWORK_END = ['>'] + NETWORK_START
NETWORK_TUPLE = utility.get_networks_prompt(NETWORK_START, NETWORK_END, positive_prompt)
if (len(NETWORK_TUPLE) == 0):
return (model, clip, lora_stack, hnet_stack, model_keyword)
else:
for NETWORK_DATA in NETWORK_TUPLE:
NetworkName = NETWORK_DATA[0]
try:
NetworkStrenght = float(NETWORK_DATA[1])
except ValueError:
NetworkStrenght = 1
NetworkType = NETWORK_DATA[2]
if (process_lora == True and NetworkType == 'LORA'):
lora_name = utility.get_closest_element(NetworkName, LoraList)
if lora_name is not None:
lora_path = folder_paths.get_full_path("loras", lora_name)
lora = comfy.utils.load_torch_file(lora_path, safe_load=True)
if (copy_weight_to_clip == True):
lora_clip_custom_weight = NetworkStrenght
lora_stack.append([lora_name, NetworkStrenght, lora_clip_custom_weight])
cloned_model, cloned_clip = comfy.sd.load_lora_for_models(cloned_model, cloned_clip, lora, NetworkStrenght, lora_clip_custom_weight)
if use_lora_keyword == True:
ModelKvHash = utility.get_model_hash(lora_path)
if ModelKvHash is not None:
KEYWORD_PATH = os.path.join(PRIMERE_ROOT, 'front_end', 'keywords', 'lora-keyword.txt')
keywords = utility.get_model_keywords(KEYWORD_PATH, ModelKvHash, lora_name)
if keywords is not None and keywords != "":
if keywords.find('|') > 1:
keyword_list = [word.strip() for word in keywords.split('|')]
keyword_list = list(filter(None, keyword_list))
if (len(keyword_list) > 0):
lora_keywords_num = lora_keywords_num_set
keyword_qty = len(keyword_list)
if (lora_keywords_num > keyword_qty):
lora_keywords_num = keyword_qty
if lora_keyword_selection == 'Select in order':
list_of_keyword_items.extend(keyword_list[:lora_keywords_num])
else:
list_of_keyword_items.extend(random.sample(keyword_list, lora_keywords_num))
else:
list_of_keyword_items.append(keywords)
if len(list_of_keyword_items) > 0:
if lora_keyword_selection != 'Select in order':
random.shuffle(list_of_keyword_items)
list_of_keyword_items = list(set(list_of_keyword_items))
keywords = ", ".join(list_of_keyword_items)
if (lora_keyword_weight != 1):
keywords = '(' + keywords + ':' + str(lora_keyword_weight) + ')'
model_keyword = [keywords, lora_keyword_placement]
if (process_hypernetwork == True and NetworkType == 'HYPERNET'):
hyper_name = utility.get_closest_element(NetworkName, HypernetworkList)
if hyper_name is not None:
hypernetwork_path = folder_paths.get_full_path("hypernetworks", hyper_name)
model_hypernetwork = cloned_model.clone()
patch = hypernetwork.load_hypernetwork_patch(hypernetwork_path, NetworkStrenght, False)
if patch is not None:
model_hypernetwork.set_model_attn1_patch(patch)
model_hypernetwork.set_model_attn2_patch(patch)
hnet_stack.append([hyper_name, NetworkStrenght])
cloned_model = model_hypernetwork
return (cloned_model, cloned_clip, lora_stack, hnet_stack, model_keyword)
class PrimereModelKeyword:
RETURN_TYPES = ("MODEL_KEYWORD",)
RETURN_NAMES = ("MODEL_KEYWORD",)
FUNCTION = "load_ckpt_keyword"
CATEGORY = TREE_DASHBOARD
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model_name": ('CHECKPOINT_NAME', {"forceInput": True, "default": ""}),
"use_model_keyword": ("BOOLEAN", {"default": False}),
"model_keyword_placement": (["First", "Last"], {"default": "Last"}),
"model_keyword_selection": (["Select in order", "Random select"], {"default": "Select in order"}),
"model_keywords_num": ("INT", {"default": 1, "min": 1, "max": 50, "step": 1}),
"model_keyword_weight": ("FLOAT", {"default": 1.0, "min": 0, "max": 10.0, "step": 0.1}),
},
}
def load_ckpt_keyword(self, model_name, use_model_keyword, model_keyword_placement, model_keyword_selection, model_keywords_num, model_keyword_weight):
model_keyword = [None, None]
if use_model_keyword == True:
ckpt_path = folder_paths.get_full_path("checkpoints", model_name)
ModelKvHash = utility.get_model_hash(ckpt_path)
if ModelKvHash is not None:
KEYWORD_PATH = os.path.join(PRIMERE_ROOT, 'front_end', 'keywords', 'model-keyword.txt')
keywords = utility.get_model_keywords(KEYWORD_PATH, ModelKvHash, model_name)
if keywords is not None:
if keywords.find('|') > 1:
keyword_list = keywords.split("|")
if (len(keyword_list) > 0):
keyword_qty = len(keyword_list)
if (model_keywords_num > keyword_qty):
model_keywords_num = keyword_qty
if model_keyword_selection == 'Select in order':
list_of_keyword_items = keyword_list[:model_keywords_num]
else:
list_of_keyword_items = random.sample(keyword_list, model_keywords_num)
keywords = ", ".join(list_of_keyword_items)
if (model_keyword_weight != 1):
keywords = '(' + keywords + ':' + str(model_keyword_weight) + ')'
model_keyword = [keywords, model_keyword_placement]
return (model_keyword,)
View File
+704
View File
@@ -0,0 +1,704 @@
from custom_nodes.ComfyUI_Primere_Nodes.components.tree import TREE_INPUTS
from custom_nodes.ComfyUI_Primere_Nodes.components.tree import PRIMERE_ROOT
import os
import re
from dynamicprompts.parser.parse import ParserConfig
from dynamicprompts.wildcards.wildcard_manager import WildcardManager
import chardet
import pandas
import comfy.samplers
import folder_paths
import hashlib
from .modules.image_meta_reader import ImageExifReader
from .modules import exif_data_checker
import nodes
from custom_nodes.ComfyUI_Primere_Nodes.components import utility
from pathlib import Path
import random
import string
class PrimereDoublePrompt:
RETURN_TYPES = ("STRING", "STRING", "STRING", "STRING", "STRING")
RETURN_NAMES = ("PROMPT+", "PROMPT-", "SUBPATH", "MODEL", "ORIENTATION")
FUNCTION = "get_prompt"
CATEGORY = TREE_INPUTS
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"positive_prompt": ("STRING", {"default": "", "multiline": True}),
"negative_prompt": ("STRING", {"default": "", "multiline": True}),
},
"optional": {
"subpath": ("STRING", {"default": "", "multiline": False}),
"model": (["None"] + folder_paths.get_filename_list("checkpoints"), {"default": "None"}),
"orientation": (["None", "Random", "Horizontal", "Vertical"], {"default": "None"}),
},
"hidden": {
"extra_pnginfo": "EXTRA_PNGINFO",
"id": "UNIQUE_ID",
},
}
def get_prompt(self, positive_prompt, negative_prompt, extra_pnginfo, id, subpath="", model="", orientation=""):
def debug_state(self, extra_pnginfo, id):
workflow = extra_pnginfo["workflow"]
for node in workflow["nodes"]:
node_id = str(node["id"])
name = node["type"]
if node_id == id and name == 'PrimerePrompt':
if "Debug" in name or "Show" in name or "Function" in name or "Evaluate" in name:
continue
return node['widgets_values']
rawResult = debug_state(self, extra_pnginfo, id)
if not rawResult:
rawResult = (positive_prompt, negative_prompt)
if len(subpath.strip()) < 1 or subpath.strip() == 'None':
subpath = None
if len(model.strip()) < 1 or model.strip() == 'None':
model = None
if len(orientation.strip()) < 1 or orientation.strip() == 'None':
orientation = None
if orientation == 'Random':
orientations = ["Horizontal", "Vertical"]
orientation = random.choice(orientations)
return (rawResult[0].replace('\n', ' '), rawResult[1].replace('\n', ' '), subpath, model, orientation)
class PrimereStyleLoader:
RETURN_TYPES = ("STRING", "STRING", "STRING", "STRING", "STRING")
RETURN_NAMES = ("PROMPT+", "PROMPT-", "SUBPATH", "MODEL", "ORIENTATION")
FUNCTION = "load_csv"
CATEGORY = TREE_INPUTS
@staticmethod
def load_styles_csv(styles_path: str):
fileTest = open(styles_path, 'rb').readline()
result = chardet.detect(fileTest)
ENCODING = result['encoding']
if ENCODING == 'ascii':
ENCODING = 'UTF-8'
with open(styles_path, "r", newline = '', encoding = ENCODING) as csv_file:
try:
return pandas.read_csv(csv_file)
except pandas.errors.ParserError as e:
errorstring = repr(e)
matchre = re.compile('Expected (\d+) fields in line (\d+), saw (\d+)')
(expected, line, saw) = map(int, matchre.search(errorstring).groups())
print(f'Error at line {line}. Fields added : {saw - expected}.')
@classmethod
def INPUT_TYPES(cls):
STYLE_DIR = os.path.join(PRIMERE_ROOT, 'stylecsv')
cls.styles_csv = cls.load_styles_csv(os.path.join(STYLE_DIR, "styles.csv"))
return {
"required": {
"styles": (sorted(list(cls.styles_csv['name'])),),
"use_subpath": ("BOOLEAN", {"default": False}),
"use_model": ("BOOLEAN", {"default": False}),
"use_orientation": ("BOOLEAN", {"default": False}),
},
}
def load_csv(self, styles, use_subpath, use_model, use_orientation):
try:
positive_prompt = self.styles_csv[self.styles_csv['name'] == styles]['prompt'].values[0]
except Exception:
positive_prompt = ''
try:
negative_prompt = self.styles_csv[self.styles_csv['name'] == styles]['negative_prompt'].values[0]
except Exception:
negative_prompt = ''
try:
prefered_subpath = self.styles_csv[self.styles_csv['name'] == styles]['prefered_subpath'].values[0]
except Exception:
prefered_subpath = ''
try:
prefered_model = self.styles_csv[self.styles_csv['name'] == styles]['prefered_model'].values[0]
except Exception:
prefered_model = ''
try:
prefered_orientation = self.styles_csv[self.styles_csv['name'] == styles]['prefered_orientation'].values[0]
except Exception:
prefered_orientation = ''
pos_type = type(positive_prompt).__name__
neg_type = type(negative_prompt).__name__
subp_type = type(prefered_subpath).__name__
model_type = type(prefered_model).__name__
orientation_type = type(prefered_orientation).__name__
if (pos_type != 'str'):
positive_prompt = ''
if (neg_type != 'str'):
negative_prompt = ''
if (subp_type != 'str'):
prefered_subpath = ''
if (model_type != 'str'):
prefered_model = ''
if (orientation_type != 'str'):
prefered_orientation = ''
if len(prefered_subpath.strip()) < 1:
prefered_subpath = None
if len(prefered_model.strip()) < 1:
prefered_model = None
if len(prefered_orientation.strip()) < 1:
prefered_orientation = None
if use_subpath == False:
prefered_subpath = None
if use_model == False:
prefered_model = None
if use_orientation == False:
prefered_orientation = None
return (positive_prompt, negative_prompt, prefered_subpath, prefered_model, prefered_orientation)
class PrimereDynParser:
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("PROMPT",)
FUNCTION = "dyndecoder"
CATEGORY = TREE_INPUTS
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"dyn_prompt": ("STRING", {"multiline": True, "forceInput": True}),
"seed": ("INT", {"default": 0, "min": -18446744073709551615, "max": 18446744073709551615, "forceInput": True}),
}
}
def __init__(self):
wildcard_dir = os.path.join(PRIMERE_ROOT, 'wildcards')
self._wildcard_manager = WildcardManager(wildcard_dir)
self._parser_config = ParserConfig(
variant_start = "{",
variant_end = "}",
wildcard_wrap = "__"
)
def dyndecoder(self, dyn_prompt, seed):
prompt = utility.DynPromptDecoder(self, dyn_prompt, seed)
return (prompt, )
class PrimereEmbeddingHandler:
RETURN_TYPES = ("STRING", "STRING",)
RETURN_NAMES = ("PROMPT+", "PROMPT-",)
FUNCTION = "embedding_handler"
CATEGORY = TREE_INPUTS
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"positive_prompt": ("STRING", {"multiline": True, "forceInput": True}),
"negative_prompt": ("STRING", {"multiline": True, "forceInput": True}),
}
}
def embedding_handler(self, positive_prompt, negative_prompt):
return (self.EmbeddingConverter(positive_prompt), self.EmbeddingConverter(negative_prompt),)
def EmbeddingConverter(self, text):
word_list = text.split()
new_word_list = [i.strip(string.punctuation) if type(i) == str else str(i) for i in word_list]
EMBEDDINGS = folder_paths.get_filename_list("embeddings")
text = text.replace('embedding:', '')
reg = re.compile(".*:\d")
matchlist = list(filter(reg.match, new_word_list))
for embeddings_path in EMBEDDINGS:
path = Path(embeddings_path)
embedding_name = path.stem
if (embedding_name in new_word_list):
text = text.replace(embedding_name, 'embedding:' + embedding_name)
if any((reg.match(item)) for item in new_word_list):
if any(item for item in matchlist if item.startswith(embedding_name)) == True:
text = text.replace(embedding_name, 'embedding:' + embedding_name)
return text
class PrimereVAESelector:
RETURN_TYPES = ("VAE",)
RETURN_NAMES = ("VAE",)
FUNCTION = "primere_vae_selector"
CATEGORY = TREE_INPUTS
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"vae_sd": ("VAE",),
"vae_sdxl": ("VAE",),
"model_version": ("STRING", {"default": 'BaseModel_1024', "forceInput": True}),
}
}
def primere_vae_selector(self, vae_sd, vae_sdxl, model_version = "BaseModel_1024"):
if model_version == 'SDXL_2048':
return (vae_sdxl, )
else:
return (vae_sd, )
class PrimereMetaRead:
CATEGORY = TREE_INPUTS
RETURN_TYPES = ("STRING", "STRING", "STRING", "STRING", "STRING", "STRING", "CHECKPOINT_NAME", comfy.samplers.KSampler.SAMPLERS, comfy.samplers.KSampler.SCHEDULERS, "INT", "INT", "INT", "FLOAT", "INT", "VAE_NAME", "VAE", "TUPLE")
RETURN_NAMES = ("PROMPT+", "PROMPT-", "PROMPT L+", "PROMPT L-", "REFINER+", "REFINER-", "MODEL_NAME", "SAMPLER_NAME", "SCHEDULER_NAME", "SEED", "WIDTH", "HEIGHT", "CFG", "STEPS", "VAE_NAME", "VAE", "METADATA")
FUNCTION = "load_image_meta"
def __init__(self):
self.chkp_loader = nodes.CheckpointLoaderSimple()
self.vae_loader = nodes.VAELoader()
wildcard_dir = os.path.join(PRIMERE_ROOT, 'wildcards')
self._wildcard_manager = WildcardManager(wildcard_dir)
self._parser_config = ParserConfig(
variant_start = "{",
variant_end = "}",
wildcard_wrap = "__"
)
@classmethod
def INPUT_TYPES(s):
input_dir = folder_paths.get_input_directory()
files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
return {
"required": {
"use_exif": ("BOOLEAN", {"default": True}),
"use_decoded_dyn": ("BOOLEAN", {"default": False}),
"use_model": ("BOOLEAN", {"default": True}),
"model_hash_check": ("BOOLEAN", {"default": False}),
"use_sampler": ("BOOLEAN", {"default": True}),
"use_seed": ("BOOLEAN", {"default": True}),
"use_size": ("BOOLEAN", {"default": True}),
"recount_size": ("BOOLEAN", {"default": False}),
"use_cfg_scale": ("BOOLEAN", {"default": True}),
"use_steps": ("BOOLEAN", {"default": True}),
"use_exif_vae": ("BOOLEAN", {"default": True}),
"force_model_vae": ("BOOLEAN", {"default": False}),
"image": (sorted(files),),
},
"optional": {
"positive": ('STRING', {"forceInput": True, "default": ""}),
"negative": ('STRING', {"forceInput": True, "default": ""}),
"positive_l": ('STRING', {"forceInput": True, "default": ""}),
"negative_l": ('STRING', {"forceInput": True, "default": ""}),
"positive_r": ('STRING', {"forceInput": True, "default": ""}),
"negative_r": ('STRING', {"forceInput": True, "default": ""}),
"model_name": ('CHECKPOINT_NAME', {"forceInput": True, "default": ""}),
"model_version": ("STRING", {"default": 'BaseModel_1024', "forceInput": True}),
"sampler_name": (comfy.samplers.KSampler.SAMPLERS, {"forceInput": True, "default": "euler"}),
"scheduler_name": (comfy.samplers.KSampler.SCHEDULERS, {"forceInput": True, "default": "normal"}),
"seed": ('INT', {"forceInput": True, "default": 1}),
"width": ('INT', {"forceInput": True, "default": 512}),
"height": ('INT', {"forceInput": True, "default": 512}),
"cfg_scale": ('FLOAT', {"forceInput": True, "default": 7}),
"steps": ('INT', {"forceInput": True, "default": 12}),
"vae_name_sd": ('VAE_NAME', {"forceInput": True, "default": ""}),
"vae_name_sdxl": ('VAE_NAME', {"forceInput": True, "default": ""}),
"is_lcm": ("INT", {"default": 0, "forceInput": True}),
"prefered_model": ("STRING", {"default": "", "forceInput": True}),
"prefered_orientation": ("STRING", {"default": "", "forceInput": True}),
},
}
def load_image_meta(self, use_exif, use_decoded_dyn, use_model, model_hash_check, use_sampler, use_seed, use_size, recount_size, use_cfg_scale, use_steps, use_exif_vae, force_model_vae, image,
positive="", negative="", positive_l="", negative_l="", positive_r="", negative_r="",
model_hash="", model_name="", model_version="BaseModel_1024", sampler_name="euler", scheduler_name="normal", seed=1, width=512, height=512, cfg_scale=7, steps=12, vae_name_sd="", vae_name_sdxl="", is_lcm=0, prefered_model="", prefered_orientation=""):
if prefered_orientation == 'Random':
if (seed % 2) == 0:
prefered_orientation = "Horizontal"
else:
prefered_orientation = "Vertical"
data_json = {}
data_json['positive'] = positive.replace('ADDROW ', '').replace('ADDCOL ', '').replace('ADDCOMM ', '').replace('\n', ' ')
data_json['negative'] = negative.replace('\n', ' ')
data_json['positive_l'] = positive_l
data_json['negative_l'] = negative_l
data_json['positive_r'] = positive_r
data_json['negative_r'] = negative_r
data_json['model_hash'] = model_hash
data_json['model_name'] = model_name
data_json['sampler_name'] = sampler_name
data_json['scheduler_name'] = scheduler_name
data_json['seed'] = seed
data_json['width'] = width
data_json['height'] = height
data_json['cfg_scale'] = cfg_scale
data_json['steps'] = steps
data_json['model_version'] = model_version
data_json['is_lcm'] = is_lcm
data_json['vae_name'] = vae_name_sd
data_json['force_model_vae'] = force_model_vae
data_json['prefered_model'] = prefered_model
data_json['prefered_orientation'] = prefered_orientation
LOADED_CHECKPOINT = None
is_sdxl = 0
match model_version:
case 'SDXL_2048':
is_sdxl = 1
data_json['is_sdxl'] = is_sdxl
if (is_sdxl == 1):
data_json['vae_name'] = vae_name_sdxl
else:
data_json['vae_name'] = vae_name_sd
if (data_json['vae_name'] == ""):
data_json['vae_name'] = folder_paths.get_filename_list("vae")[0]
if use_exif:
image_path = folder_paths.get_annotated_filepath(image)
if os.path.isfile(image_path):
readerResult = ImageExifReader(image_path)
if (type(readerResult.parser).__name__ == 'dict'):
print('Reader tool return empty, using node input')
if (force_model_vae == True):
LOADED_CHECKPOINT = self.chkp_loader.load_checkpoint(model_name)
realvae = LOADED_CHECKPOINT[2]
else:
realvae = self.vae_loader.load_vae(data_json['vae_name'])[0]
return (positive, negative, positive_l, negative_l, positive_r, negative_r, model_name, sampler_name, scheduler_name, seed, width, height, cfg_scale, steps, data_json['vae_name'], realvae, data_json)
reader = readerResult.parser
if 'positive' in reader.parameter:
data_json['positive'] = reader.parameter["positive"].replace('ADDROW ', '').replace('ADDCOL ', '').replace('ADDCOMM ', '').replace('\n', ' ')
else:
data_json['positive'] = ""
if 'negative' in reader.parameter:
data_json['negative'] = reader.parameter["negative"].replace('\n', ' ')
else:
data_json['negative'] = ""
data_json['dynamic_positive'] = utility.DynPromptDecoder(self, data_json['positive'], seed)
data_json['dynamic_negative'] = utility.DynPromptDecoder(self, data_json['negative'], seed)
if (readerResult.tool == ''):
print('Reader tool return empty, using node input')
if (force_model_vae == True):
LOADED_CHECKPOINT = self.chkp_loader.load_checkpoint(model_name)
realvae = LOADED_CHECKPOINT[2]
else:
realvae = self.vae_loader.load_vae(data_json['vae_name'])[0]
return (positive, negative, positive_l, negative_l, positive_r, negative_r, model_name, sampler_name, scheduler_name, seed, width, height, cfg_scale, steps, data_json['vae_name'], realvae, data_json)
try:
if use_model == True:
if 'model_hash' in reader.parameter:
data_json['model_hash'] = reader.parameter["model_hash"]
else:
checkpointpaths = folder_paths.get_folder_paths("checkpoints")[0]
model_full_path = checkpointpaths + os.sep + model_name
if os.path.isfile(model_full_path):
data_json['model_hash'] = exif_data_checker.get_model_hash(model_full_path)
else:
data_json['model_hash'] = 'no_hash_data'
if 'model_name' in reader.parameter:
model_name_exif = reader.parameter["model_name"]
data_json['model_name'] = exif_data_checker.check_model_from_exif(data_json['model_hash'], model_name_exif, model_name, model_hash_check)
else:
data_json['model_name'] = folder_paths.get_filename_list("checkpoints")[0]
if (data_json['model_name'] != model_name):
is_sdxl = 0
LOADED_CHECKPOINT = self.chkp_loader.load_checkpoint(data_json['model_name'])
model_version = utility.getCheckpointVersion(LOADED_CHECKPOINT[0])
data_json['model_version'] = model_version
match model_version:
case 'SDXL_2048':
is_sdxl = 1
data_json['is_sdxl'] = is_sdxl
if use_sampler == True and data_json['is_lcm'] == 0 and (reader.parameter["cfg_scale"] >= 3 and reader.parameter["steps"] >= 9):
if 'sampler' in reader.parameter:
sampler_name_exif = reader.parameter["sampler"]
samplers = exif_data_checker.check_sampler_from_exif(sampler_name_exif.lower(), sampler_name, scheduler_name)
data_json['sampler_name'] = samplers['sampler']
data_json['scheduler_name'] = samplers['scheduler']
elif ('sampler_name' in reader.parameter and 'scheduler_name' in reader.parameter):
data_json['sampler_name'] = reader.parameter["sampler_name"]
data_json['scheduler_name'] = reader.parameter["scheduler_name"]
if use_seed == True:
if 'seed' in reader.parameter:
data_json['seed'] = reader.parameter["seed"]
if use_cfg_scale == True and data_json['is_lcm'] == 0 and reader.parameter["cfg_scale"] >= 3:
if 'cfg_scale' in reader.parameter:
data_json['cfg_scale'] = reader.parameter["cfg_scale"]
if use_steps == True and data_json['is_lcm'] == 0 and reader.parameter["steps"] >= 9:
if 'steps' in reader.parameter:
data_json['steps'] = reader.parameter["steps"]
if (is_sdxl == 1):
data_json['vae_name'] = vae_name_sdxl
else:
data_json['vae_name'] = vae_name_sd
if (data_json['vae_name'] == ""):
data_json['vae_name'] = folder_paths.get_filename_list("vae")[0]
if force_model_vae == True:
if LOADED_CHECKPOINT is not None:
realvae = LOADED_CHECKPOINT[2]
else:
realvae = self.chkp_loader.load_checkpoint(data_json['model_name'])[2]
else:
if use_exif_vae == True:
if 'vae' in reader.parameter:
vae_name_exif = reader.parameter["vae"]
vae = exif_data_checker.check_vae_exif(vae_name_exif.lower(), data_json['vae_name'])
data_json['vae_name'] = vae
realvae = self.vae_loader.load_vae(data_json['vae_name'])[0]
if use_size == True:
if 'size_string' in reader.parameter or ('width' in reader.parameter and 'height' in reader.parameter):
data_json['width'] = reader.parameter["width"]
data_json['height'] = reader.parameter["height"]
if recount_size == True:
if (data_json['width'] > data_json['height']):
orientation = 'Horizontal'
else:
orientation = 'Vertical'
image_sides = sorted([data_json['width'], data_json['height']])
custom_side_b = round((image_sides[1] / image_sides[0]), 4)
dimensions = utility.calculate_dimensions(self, "Square [1:1]", orientation, 1, model_version, True, 1, custom_side_b)
data_json['width'] = dimensions[0]
data_json['height'] = dimensions[1]
if use_decoded_dyn == True:
if 'dynamic_positive' in reader.parameter:
data_json['positive'] = reader.parameter['dynamic_positive']
data_json['dynamic_positive'] = reader.parameter['dynamic_positive']
if 'dynamic_negative' in reader.parameter:
data_json['negative'] = reader.parameter['dynamic_negative']
data_json['dynamic_negative'] = reader.parameter['dynamic_negative']
return (data_json['positive'], data_json['negative'], data_json['positive_l'], data_json['negative_l'], data_json['positive_r'], data_json['negative_r'], data_json['model_name'], data_json['sampler_name'], data_json['scheduler_name'], data_json['seed'], data_json['width'], data_json['height'], data_json['cfg_scale'], data_json['steps'], data_json['vae_name'], realvae, data_json)
except ValueError as VE:
print(VE)
if (force_model_vae == True):
if LOADED_CHECKPOINT is not None:
realvae = LOADED_CHECKPOINT[2]
else:
realvae = self.chkp_loader.load_checkpoint(data_json['model_name'])[2]
else:
realvae = self.vae_loader.load_vae(data_json['vae_name'])[0]
return (data_json['positive'], data_json['negative'], data_json['positive_l'], data_json['negative_l'], data_json['positive_r'], data_json['negative_r'], data_json['model_name'], data_json['sampler_name'], data_json['scheduler_name'], data_json['seed'], data_json['width'], data_json['height'], data_json['cfg_scale'], data_json['steps'], data_json['vae_name'], realvae, data_json)
else:
print('No source image loaded')
if (force_model_vae == True):
if LOADED_CHECKPOINT is not None:
realvae = LOADED_CHECKPOINT[2]
else:
realvae = self.chkp_loader.load_checkpoint(data_json['model_name'])[2]
else:
realvae = self.vae_loader.load_vae(data_json['vae_name'])[0]
return (data_json['positive'], data_json['negative'], data_json['positive_l'], data_json['negative_l'], data_json['positive_r'], data_json['negative_r'], data_json['model_name'], data_json['sampler_name'], data_json['scheduler_name'], data_json['seed'], data_json['width'], data_json['height'], data_json['cfg_scale'], data_json['steps'], data_json['vae_name'], realvae, data_json)
else:
print('Exif reader off')
if prefered_model is not None and len(prefered_model.strip()) > 0:
data_json['model_name'] = exif_data_checker.check_model_from_exif("no_hash_data", prefered_model, prefered_model, False)
is_sdxl = 0
LOADED_CHECKPOINT = self.chkp_loader.load_checkpoint(data_json['model_name'])
model_version = utility.getCheckpointVersion(LOADED_CHECKPOINT[0])
data_json['model_version'] = model_version
match model_version:
case 'SDXL_2048':
is_sdxl = 1
data_json['is_sdxl'] = is_sdxl
if (force_model_vae == True):
if LOADED_CHECKPOINT is not None:
realvae = LOADED_CHECKPOINT[2]
else:
realvae = self.chkp_loader.load_checkpoint(data_json['model_name'])[2]
else:
if (is_sdxl == 1):
data_json['vae_name'] = vae_name_sdxl
else:
data_json['vae_name'] = vae_name_sd
realvae = self.vae_loader.load_vae(data_json['vae_name'])[0]
data_json['dynamic_positive'] = utility.DynPromptDecoder(self, data_json['positive'], seed)
data_json['dynamic_negative'] = utility.DynPromptDecoder(self, data_json['negative'], seed)
if prefered_orientation is not None and len(prefered_orientation.strip()) > 0:
# image_sides = sorted([data_json['width'], data_json['height']])
# custom_side_b = round((image_sides[1] / image_sides[0]), 4)
# dimensions = utility.calculate_dimensions(self, "Square [1:1]", prefered_orientation, 1, model_version, True, 1, custom_side_b)
# data_json['width'] = dimensions[0]
# data_json['height'] = dimensions[1]
# width = dimensions[0]
# height = dimensions[1]
if prefered_orientation == 'Vertical' and (data_json['width'] > data_json['height']):
data_json['width'] = height
data_json['height'] = width
if prefered_orientation == 'Horizontal' and (data_json['height'] > data_json['width']):
data_json['width'] = height
data_json['height'] = width
return (data_json['positive'], data_json['negative'], data_json['positive_l'], data_json['negative_l'], data_json['positive_r'], data_json['negative_r'], data_json['model_name'], data_json['sampler_name'], data_json['scheduler_name'], data_json['seed'], data_json['width'], data_json['height'], data_json['cfg_scale'], data_json['steps'], data_json['vae_name'], realvae, data_json)
@classmethod
def IS_CHANGED(cls, image):
image_path = folder_paths.get_annotated_filepath(image)
m = hashlib.sha256()
with open(image_path, 'rb') as f:
m.update(f.read())
return m.digest().hex()
class PrimereLoraStackMerger:
RETURN_TYPES = ("LORA_STACK",)
RETURN_NAMES = ("LORA_STACK",)
FUNCTION = "lora_stack_merger"
CATEGORY = TREE_INPUTS
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"lora_stack_1": ("LORA_STACK",),
"lora_stack_2": ("LORA_STACK",),
}
}
def lora_stack_merger(self, lora_stack_1, lora_stack_2):
if lora_stack_1 is not None and lora_stack_2 is not None:
return (lora_stack_1 + lora_stack_2, )
else:
return ([], )
class PrimereLoraKeywordMerger:
RETURN_TYPES = ("MODEL_KEYWORD",)
RETURN_NAMES = ("LORA_KEYWORD",)
FUNCTION = "lora_keyword_merger"
CATEGORY = TREE_INPUTS
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"lora_keyword_SD": ("MODEL_KEYWORD",),
"lora_keyword_SDXL": ("MODEL_KEYWORD",),
},
"optional": {
"lora_keyword_tagloader": ("MODEL_KEYWORD",),
},
}
def lora_keyword_merger(self, lora_keyword_SD, lora_keyword_SDXL, lora_keyword_tagloader):
model_keyword = [None, None]
if lora_keyword_SD is not None:
mkw_list_1 = list(filter(None, lora_keyword_SD))
if len(mkw_list_1) == 2:
model_keyword_1 = mkw_list_1[0]
placement = mkw_list_1[1]
model_keyword = [model_keyword_1, placement]
if lora_keyword_SDXL is not None:
mkw_list_2 = list(filter(None, lora_keyword_SDXL))
if len(mkw_list_2) == 2:
model_keyword_2 = mkw_list_2[0]
placement = mkw_list_2[1]
model_keyword = [model_keyword_2, placement]
if lora_keyword_tagloader is not None:
mkw_list_3 = list(filter(None, lora_keyword_tagloader))
if len(mkw_list_3) == 2:
model_keyword_3 = mkw_list_3[0]
placement = mkw_list_3[1]
model_keyword = [model_keyword_3, placement]
return (model_keyword,)
class PrimereEmbeddingKeywordMerger:
RETURN_TYPES = ("EMBEDDING", "EMBEDDING",)
RETURN_NAMES = ("EMBEDDING+", "EMBEDDING-")
FUNCTION = "embedding_keyword_merger"
CATEGORY = TREE_INPUTS
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"embedding_pos_SD": ("EMBEDDING",),
"embedding_pos_SDXL": ("EMBEDDING",),
"embedding_neg_SD": ("EMBEDDING",),
"embedding_neg_SDXL": ("EMBEDDING",),
},
}
def embedding_keyword_merger(self, embedding_pos_SD, embedding_pos_SDXL, embedding_neg_SD, embedding_neg_SDXL):
embedding_pos = []
embedding_neg = []
if embedding_pos_SD is not None:
mkw_list_1 = list(filter(None, embedding_pos_SD))
if len(mkw_list_1) == 2:
model_keyword_1 = mkw_list_1[0]
placement = mkw_list_1[1]
embedding_pos.append([model_keyword_1, placement])
if embedding_pos_SDXL is not None:
mkw_list_1 = list(filter(None, embedding_pos_SDXL))
if len(mkw_list_1) == 2:
model_keyword_1 = mkw_list_1[0]
placement = mkw_list_1[1]
embedding_pos.append([model_keyword_1, placement])
if embedding_neg_SD is not None:
mkw_list_1 = list(filter(None, embedding_neg_SD))
if len(mkw_list_1) == 2:
model_keyword_1 = mkw_list_1[0]
placement = mkw_list_1[1]
embedding_neg.append([model_keyword_1, placement])
if embedding_neg_SDXL is not None:
mkw_list_1 = list(filter(None, embedding_neg_SDXL))
if len(mkw_list_1) == 2:
model_keyword_1 = mkw_list_1[0]
placement = mkw_list_1[1]
embedding_neg.append([model_keyword_1, placement])
if (len(embedding_pos) == 0):
embedding_pos = [None, None]
if (len(embedding_neg) == 0):
embedding_neg = [None, None]
return (embedding_pos, embedding_neg,)
+314
View File
@@ -0,0 +1,314 @@
from custom_nodes.ComfyUI_Primere_Nodes.components.tree import TREE_NETWORKS
from custom_nodes.ComfyUI_Primere_Nodes.components.tree import PRIMERE_ROOT
import folder_paths
from custom_nodes.ComfyUI_Primere_Nodes.components import utility
from custom_nodes.ComfyUI_Primere_Nodes.components import hypernetwork
import comfy.sd
import comfy.utils
import os
import random
from pathlib import Path
# import comfy_extras.nodes_hypernetwork as comfy_extras
class PrimereLORA:
RETURN_TYPES = ("MODEL", "CLIP", "LORA_STACK", "MODEL_KEYWORD")
RETURN_NAMES = ("MODEL", "CLIP", "LORA_STACK", "LORA_KEYWORD")
FUNCTION = "primere_lora_stacker"
CATEGORY = TREE_NETWORKS
LORASCOUNT = 6
@classmethod
def INPUT_TYPES(cls):
LoraList = folder_paths.get_filename_list("loras")
return {
"required": {
"model": ("MODEL",),
"clip": ("CLIP",),
"model_version": ("STRING", {"default": 'BaseModel_1024', "forceInput": True}),
"stack_version": (["SD", "SDXL", "Any"], {"default": "Any"}),
"use_only_model_weight": ("BOOLEAN", {"default": True}),
"use_lora_1": ("BOOLEAN", {"default": False}),
"lora_1": (LoraList,),
"lora_1_model_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"lora_1_clip_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_lora_2": ("BOOLEAN", {"default": False}),
"lora_2": (LoraList,),
"lora_2_model_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"lora_2_clip_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_lora_3": ("BOOLEAN", {"default": False}),
"lora_3": (LoraList,),
"lora_3_model_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"lora_3_clip_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_lora_4": ("BOOLEAN", {"default": False}),
"lora_4": (LoraList,),
"lora_4_model_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"lora_4_clip_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_lora_5": ("BOOLEAN", {"default": False}),
"lora_5": (LoraList,),
"lora_5_model_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"lora_5_clip_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_lora_6": ("BOOLEAN", {"default": False}),
"lora_6": (LoraList,),
"lora_6_model_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"lora_6_clip_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_lora_keyword": ("BOOLEAN", {"default": False}),
"lora_keyword_placement": (["First", "Last"], {"default": "Last"}),
"lora_keyword_selection": (["Select in order", "Random select"], {"default": "Select in order"}),
"lora_keywords_num": ("INT", {"default": 1, "min": 1, "max": 50, "step": 1}),
"lora_keyword_weight": ("FLOAT", {"default": 1.0, "min": 0, "max": 10.0, "step": 0.1}),
},
}
def primere_lora_stacker(self, model, clip, use_only_model_weight, use_lora_keyword, lora_keyword_placement, lora_keyword_selection, lora_keywords_num, lora_keyword_weight, stack_version = 'Any', model_version = "BaseModel_1024", **kwargs):
model_keyword = [None, None]
if model_version == 'SDXL_2048' and stack_version == 'SD':
return (model, clip, [], model_keyword)
if model_version != 'SDXL_2048' and stack_version == 'SDXL':
return (model, clip, [], model_keyword)
loras = [kwargs.get(f"lora_{i}") for i in range(1, self.LORASCOUNT + 1)]
model_weight = [kwargs.get(f"lora_{i}_model_weight") for i in range(1, self.LORASCOUNT + 1)]
if use_only_model_weight == True:
clip_weight =[kwargs.get(f"lora_{i}_model_weight") for i in range(1, self.LORASCOUNT + 1)]
else:
clip_weight =[kwargs.get(f"lora_{i}_clip_weight") for i in range(1, self.LORASCOUNT + 1)]
uses = [kwargs.get(f"use_lora_{i}") for i in range(1, self.LORASCOUNT + 1)]
lora_stack = [(lora_name, lora_model_weight, lora_clip_weight) for lora_name, lora_model_weight, lora_clip_weight, lora_uses in zip(loras, model_weight, clip_weight, uses) if lora_uses == True]
lora_params = list()
if lora_stack and len(lora_stack) > 0:
lora_params.extend(lora_stack)
else:
return (model, clip, lora_stack, model_keyword)
model_lora = model
clip_lora = clip
list_of_keyword_items = []
lora_keywords_num_set = lora_keywords_num
for tup in lora_params:
lora_name, strength_model, strength_clip = tup
lora_path = folder_paths.get_full_path("loras", lora_name)
lora = comfy.utils.load_torch_file(lora_path, safe_load=True)
model_lora, clip_lora = comfy.sd.load_lora_for_models(model_lora, clip_lora, lora, strength_model, strength_clip)
if use_lora_keyword == True:
ModelKvHash = utility.get_model_hash(lora_path)
if ModelKvHash is not None:
KEYWORD_PATH = os.path.join(PRIMERE_ROOT, 'front_end', 'keywords', 'lora-keyword.txt')
keywords = utility.get_model_keywords(KEYWORD_PATH, ModelKvHash, lora_name)
if keywords is not None and keywords != "":
if keywords.find('|') > 1:
keyword_list = [word.strip() for word in keywords.split('|')]
keyword_list = list(filter(None, keyword_list))
if (len(keyword_list) > 0):
lora_keywords_num = lora_keywords_num_set
keyword_qty = len(keyword_list)
if (lora_keywords_num > keyword_qty):
lora_keywords_num = keyword_qty
if lora_keyword_selection == 'Select in order':
list_of_keyword_items.extend(keyword_list[:lora_keywords_num])
else:
list_of_keyword_items.extend(random.sample(keyword_list, lora_keywords_num))
else:
list_of_keyword_items.append(keywords)
if len(list_of_keyword_items) > 0:
if lora_keyword_selection != 'Select in order':
random.shuffle(list_of_keyword_items)
list_of_keyword_items = list(set(list_of_keyword_items))
keywords = ", ".join(list_of_keyword_items)
if (lora_keyword_weight != 1):
keywords = '(' + keywords + ':' + str(lora_keyword_weight) + ')'
model_keyword = [keywords, lora_keyword_placement]
return (model_lora, clip_lora, lora_stack, model_keyword)
class PrimereEmbedding:
RETURN_TYPES = ("EMBEDDING", "EMBEDDING", "EMBEDDING_STACK")
RETURN_NAMES = ("EMBEDDING+", "EMBEDDING-", "EMBEDDING_STACK")
FUNCTION = "primere_embedding"
CATEGORY = TREE_NETWORKS
EMBCOUNT = 6
@classmethod
def INPUT_TYPES(self):
EmbeddingList =folder_paths.get_filename_list("embeddings")
return {
"required": {
"model_version": ("STRING", {"default": 'BaseModel_1024', "forceInput": True}),
"stack_version": (["SD", "SDXL", "Any"], {"default": "Any"}),
"use_embedding_1": ("BOOLEAN", {"default": False}),
"embedding_1": (EmbeddingList,),
"embedding_1_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01,},),
"is_negative_1": ("BOOLEAN", {"default": False}),
"use_embedding_2": ("BOOLEAN", {"default": False}),
"embedding_2": (EmbeddingList,),
"embedding_2_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01, },),
"is_negative_2": ("BOOLEAN", {"default": False}),
"use_embedding_3": ("BOOLEAN", {"default": False}),
"embedding_3": (EmbeddingList,),
"embedding_3_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01, },),
"is_negative_3": ("BOOLEAN", {"default": False}),
"use_embedding_4": ("BOOLEAN", {"default": False}),
"embedding_4": (EmbeddingList,),
"embedding_4_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01, },),
"is_negative_4": ("BOOLEAN", {"default": False}),
"use_embedding_5": ("BOOLEAN", {"default": False}),
"embedding_5": (EmbeddingList,),
"embedding_5_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01, },),
"is_negative_5": ("BOOLEAN", {"default": False}),
"use_embedding_6": ("BOOLEAN", {"default": False}),
"embedding_6": (EmbeddingList,),
"embedding_6_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01, },),
"is_negative_6": ("BOOLEAN", {"default": False}),
"embedding_placement_pos": (["First", "Last"], {"default": "Last"}),
"embedding_placement_neg": (["First", "Last"], {"default": "Last"}),
},
}
def primere_embedding(self, embedding_placement_pos, embedding_placement_neg, stack_version = 'Any', model_version = "BaseModel_1024", **kwargs):
if model_version == 'SDXL_2048' and stack_version == 'SD':
return ([None, None], [None, None], [])
if model_version != 'SDXL_2048' and stack_version == 'SDXL':
return ([None, None], [None, None], [])
embedding_pos_list = []
embedding_neg_list = []
embeddings = [kwargs.get(f"embedding_{i}") for i in range(1, self.EMBCOUNT + 1)]
use_embeddings = [kwargs.get(f"use_embedding_{i}") for i in range(1, self.EMBCOUNT + 1)]
embedding_weight = [kwargs.get(f"embedding_{i}_weight") for i in range(1, self.EMBCOUNT + 1)]
neg_embedding = [kwargs.get(f"is_negative_{i}") for i in range(1, self.EMBCOUNT + 1)]
embedding_stack = [(emb_name, emb_weight, is_emb_neg) for emb_name, emb_weight, is_emb_neg, emb_uses in zip(embeddings, embedding_weight, neg_embedding, use_embeddings) if emb_uses == True]
if embedding_stack is not None and len(embedding_stack) > 0:
for embedding_tuple in embedding_stack:
embedd_name_path = embedding_tuple[0]
embedd_weight = embedding_tuple[1]
embedd_neg = embedding_tuple[2]
embedd_name = Path(embedd_name_path).stem
if (embedd_weight != 1):
embedding_sting = '(embedding:' + embedd_name + ':' + str(embedd_weight) + ')'
else:
embedding_sting = 'embedding:' + embedd_name
if embedd_neg == False:
embedding_pos_list.append(embedding_sting)
else:
embedding_neg_list.append(embedding_sting)
else:
return ([None, None], [None, None], [])
embedding_pos_list = list(set(embedding_pos_list))
embedding_neg_list = list(set(embedding_neg_list))
if len(embedding_pos_list) > 0:
embedding_pos = ", ".join(embedding_pos_list)
else:
embedding_pos = None
embedding_placement_pos = None
if len(embedding_neg_list) > 0:
embedding_neg = ", ".join(embedding_neg_list)
else:
embedding_neg = None
embedding_placement_neg = None
return ([embedding_pos, embedding_placement_pos], [embedding_neg, embedding_placement_neg], embedding_stack)
class PrimereHypernetwork:
RETURN_TYPES = ("MODEL", "HYPERNETWORK_STACK")
RETURN_NAMES = ("MODEL", "HYPERNETWORK_STACK")
FUNCTION = "primere_hypernetwork"
CATEGORY = TREE_NETWORKS
EMBCOUNT = 6
@classmethod
def INPUT_TYPES(s):
HypernetworkList = folder_paths.get_filename_list("hypernetworks")
return {"required": {
"model": ("MODEL",),
"model_version": ("STRING", {"default": 'BaseModel_1024', "forceInput": True}),
"stack_version": (["SD", "SDXL", "Any"], {"default": "Any"}),
"use_hypernetwork_1": ("BOOLEAN", {"default": False}),
"hypernetwork_1": (HypernetworkList, ),
"hypernetwork_1_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_hypernetwork_2": ("BOOLEAN", {"default": False}),
"hypernetwork_2": (HypernetworkList,),
"hypernetwork_2_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_hypernetwork_3": ("BOOLEAN", {"default": False}),
"hypernetwork_3": (HypernetworkList,),
"hypernetwork_3_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_hypernetwork_4": ("BOOLEAN", {"default": False}),
"hypernetwork_4": (HypernetworkList,),
"hypernetwork_4_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_hypernetwork_5": ("BOOLEAN", {"default": False}),
"hypernetwork_5": (HypernetworkList,),
"hypernetwork_5_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_hypernetwork_6": ("BOOLEAN", {"default": False}),
"hypernetwork_6": (HypernetworkList,),
"hypernetwork_6_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
}
}
def primere_hypernetwork(self, model, model_version, stack_version = 'Any', **kwargs):
model_hypernetwork = model
if model_version == 'SDXL_2048' and stack_version == 'SD':
return (model, [],)
if model_version != 'SDXL_2048' and stack_version == 'SDXL':
return (model, [],)
hnetworks = [kwargs.get(f"hypernetwork_{i}") for i in range(1, self.EMBCOUNT + 1)]
use_hnetworks = [kwargs.get(f"use_hypernetwork_{i}") for i in range(1, self.EMBCOUNT + 1)]
hnetworks_weight = [kwargs.get(f"hypernetwork_{i}_weight") for i in range(1, self.EMBCOUNT + 1)]
hnetwork_stack = [(hn_name, hn_weight) for hn_name, hn_weight, hn_uses in zip(hnetworks, hnetworks_weight, use_hnetworks) if hn_uses == True]
if hnetwork_stack is not None and len(hnetwork_stack) > 0:
cloned_model = model
for hn_tuple in hnetwork_stack:
hypernetwork_path = folder_paths.get_full_path("hypernetworks", hn_tuple[0])
model_hypernetwork = cloned_model.clone()
patch = hypernetwork.load_hypernetwork_patch(hypernetwork_path, hn_tuple[1], False)
if patch is not None:
model_hypernetwork.set_model_attn1_patch(patch)
model_hypernetwork.set_model_attn2_patch(patch)
cloned_model = model_hypernetwork
else:
return (model, [],)
return (model_hypernetwork, hnetwork_stack,)
+329
View File
@@ -0,0 +1,329 @@
from custom_nodes.ComfyUI_Primere_Nodes.components.tree import TREE_OUTPUTS
import os
import folder_paths
import re
import json
import time
import numpy as np
import pyexiv2
from PIL.PngImagePlugin import PngInfo
from PIL import Image
from pathlib import Path
import datetime
ALLOWED_EXT = ('.jpeg', '.jpg', '.png', '.tiff', '.gif', '.bmp', '.webp')
class PrimereMetaSave:
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("SAVED_INFO",)
FUNCTION = "save_images_meta"
OUTPUT_NODE = True
CATEGORY = TREE_OUTPUTS
NODE_FILE = os.path.abspath(__file__)
NODE_ROOT = os.path.dirname(NODE_FILE)
def __init__(self):
self.output_dir = folder_paths.output_directory
self.type = 'output'
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"images": ("IMAGE",),
"output_path": ("STRING", {"default": '[time(%Y-%m-%d)]', "multiline": False}),
"subpath": (["None", "Dev", "Test", "Production", "Preview", "NewModel", "Project", "Portfolio", "Character", "Style", "Product", "Fun", "SFW", "NSFW"], {"default": "Project"}),
"prefered_subpath": ("STRING", {"default": "", "forceInput": True}),
"add_modelname_to_path": ("BOOLEAN", {"default": False}),
"filename_prefix": ("STRING", {"default": "ComfyUI"}),
"filename_delimiter": ("STRING", {"default": "_"}),
"add_date_to_filename": ("BOOLEAN", {"default": True}),
"add_time_to_filename": ("BOOLEAN", {"default": True}),
"add_seed_to_filename": ("BOOLEAN", {"default": True}),
"add_size_to_filename": ("BOOLEAN", {"default": True}),
"filename_number_padding": ("INT", {"default": 2, "min": 1, "max": 9, "step": 1}),
"filename_number_start": ("BOOLEAN", {"default":False}),
"extension": (['png', 'jpeg', 'jpg', 'gif', 'tiff', 'webp'], {"default": "jpg"}),
"png_embed_workflow": ("BOOLEAN", {"default":False}),
"image_embed_exif": ("BOOLEAN", {"default":False}),
"quality": ("INT", {"default": 95, "min": 1, "max": 100, "step": 1}),
"overwrite_mode": (["false", "prefix_as_filename"],),
"save_mata_to_json": ("BOOLEAN", {"default": False}),
"save_info_to_txt": ("BOOLEAN", {"default": False}),
},
"optional": {
"prefered_subpath": ("STRING", {"default": "", "forceInput": True}),
"image_metadata": ('TUPLE', {"forceInput": True}),
},
"hidden": {
"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"
},
}
def save_images_meta(self, images, add_date_to_filename, add_time_to_filename, add_seed_to_filename, add_size_to_filename, save_mata_to_json, save_info_to_txt, image_metadata=None,
output_path='[time(%Y-%m-%d)]', subpath='Project', add_modelname_to_path = False, filename_prefix="ComfyUI", filename_delimiter='_',
extension='jpg', quality=95, prompt=None, extra_pnginfo=None,
overwrite_mode='false', filename_number_padding=2, filename_number_start=False,
png_embed_workflow=False, image_embed_exif=False, prefered_subpath=""):
delimiter = filename_delimiter
number_padding = filename_number_padding
tokens = TextTokens()
original_output = self.output_dir
filename_prefix = tokens.parseTokens(filename_prefix)
nowdate = datetime.datetime.now()
if len(images) < 1:
return
image_metadata['saved_image_width'] = images[0].shape[1]
image_metadata['saved_image_heigth'] = images[0].shape[0]
# image_metadata['upscaler_ratio'] = round(image_metadata['saved_image_width'] / image_metadata['width'], 2)
image_metadata['upscaler_ratio'] = 'From: ' + str(image_metadata['width']) + 'x' + str(image_metadata['height']) + ' to: ' + str(image_metadata['saved_image_width']) + 'x' + str(image_metadata['saved_image_heigth']) + ' Ratio: ' + str(round(round(image_metadata['saved_image_width'] / image_metadata['width'] / 0.05) * 0.05, 2))
if add_date_to_filename:
filename_prefix = filename_prefix + '_' + nowdate.strftime("%Y%d%m")
if add_time_to_filename:
filename_prefix = filename_prefix + '_' + nowdate.strftime("%H%M%S")
if add_seed_to_filename:
if 'seed' in image_metadata:
filename_prefix = filename_prefix + '_' + str(image_metadata['seed'])
if add_size_to_filename:
if 'width' in image_metadata:
filename_prefix = filename_prefix + '_' + str(image_metadata['saved_image_width']) + 'x' + str(image_metadata['saved_image_heigth'])
if output_path in [None, '', "none", "."]:
output_path = self.output_dir
else:
output_path = tokens.parseTokens(output_path)
if not os.path.isabs(output_path):
output_path = os.path.join(self.output_dir, output_path)
base_output = os.path.basename(output_path)
if output_path.endswith("ComfyUI/output") or output_path.endswith("ComfyUI\output"):
base_output = ""
if add_modelname_to_path == True:
path = Path(output_path)
ModelStartPath = output_path.replace(path.stem, '')
ModelPath = Path(image_metadata['model_name'])
if prefered_subpath is not None and len(prefered_subpath.strip()) > 0:
subpath = prefered_subpath
if subpath is not None and subpath != 'None' and len(subpath.strip()) > 0:
output_path = ModelStartPath + ModelPath.stem.upper() + os.sep + subpath + os.sep + path.stem
else:
output_path = ModelStartPath + ModelPath.stem.upper() + os.sep + path.stem
if output_path.strip() != '':
if not os.path.isabs(output_path):
output_path = os.path.join(folder_paths.output_directory, output_path)
if not os.path.exists(output_path.strip()):
print(f'The path `{output_path.strip()}` specified doesn\'t exist! Creating directory.')
os.makedirs(output_path, exist_ok=True)
if filename_number_start == 'true':
pattern = f"(\\d{{{filename_number_padding}}}){re.escape(delimiter)}{re.escape(filename_prefix)}"
else:
pattern = f"{re.escape(filename_prefix)}{re.escape(delimiter)}(\\d{{{filename_number_padding}}})"
existing_counters = [int(re.search(pattern, filename).group(1)) for filename in os.listdir(output_path) if re.match(pattern, os.path.basename(filename))]
existing_counters.sort(reverse=True)
if existing_counters:
counter = existing_counters[0] + 1
else:
counter = 1
file_extension = '.' + extension
if file_extension not in ALLOWED_EXT:
# print(f"The extension `{extension}` is not valid. The valid formats are: {', '.join(sorted(ALLOWED_EXT))}")
file_extension = "jpg"
results = list()
# for image in images:
image = images[0]
i = 255. * image.cpu().numpy()
img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
metadata = PngInfo()
if png_embed_workflow == 'true':
if prompt is not None:
metadata.add_text("prompt", json.dumps(prompt))
if extra_pnginfo is not None:
for x in extra_pnginfo:
metadata.add_text(x, json.dumps(extra_pnginfo[x]))
if overwrite_mode == 'prefix_as_filename':
file = f"{filename_prefix}{file_extension}"
else:
if filename_number_start == 'true':
file = f"{counter:0{number_padding}}{delimiter}{filename_prefix}{file_extension}"
else:
file = f"{filename_prefix}{delimiter}{counter:0{number_padding}}{file_extension}"
if os.path.exists(os.path.join(output_path, file)):
counter += 1
try:
output_file = os.path.abspath(os.path.join(output_path, file))
exif_metadata_A11 = f"""{image_metadata['positive']}
Negative prompt: {image_metadata['negative']}
Steps: {str(image_metadata['steps'])}, Sampler: {image_metadata['sampler_name'] + ' ' + image_metadata['scheduler_name']}, CFG scale: {str(image_metadata['cfg_scale'])}, Seed: {str(image_metadata['seed'])}, Size: {str(image_metadata['width'])}x{str(image_metadata['height'])}, Model hash: {image_metadata['model_hash']}, Model: {image_metadata['model_name']}, VAE: {image_metadata['vae_name']}"""
exif_metadata_json = image_metadata
if extension == 'png':
img.save(output_file, pnginfo=metadata, optimize=True)
elif extension == 'webp':
img.save(output_file, quality=quality, exif=metadata)
else:
img.save(output_file, quality=quality, optimize=True)
if image_embed_exif == True:
metadata = pyexiv2.Image(output_file)
metadata.modify_exif({'Exif.Photo.UserComment': 'charset=Unicode ' + exif_metadata_A11})
metadata.modify_exif({'Exif.Image.ImageDescription': json.dumps(exif_metadata_json)})
print(f"Image file saved with exif: {output_file}")
else:
if extension == 'webp':
img.save(output_file, quality=quality, exif=metadata)
else:
img.save(output_file, quality=quality, optimize=True)
print(f"Image file saved without exif: {output_file}")
if save_mata_to_json:
jsonfile = os.path.splitext(output_file)[0] + '.json'
with open(jsonfile, 'w', encoding='utf-8') as jf:
json.dump(exif_metadata_json, jf, ensure_ascii=False, indent=4)
except OSError as e:
print(f'Unable to save file to: {output_file}')
print(e)
except Exception as e:
print('Unable to save file due to the to the following error:')
print(e)
if overwrite_mode == 'false':
counter += 1
filtered_paths = []
if filtered_paths:
for image_path in filtered_paths:
subfolder = self.get_subfolder_path(image_path, self.output_dir)
image_data = {
"filename": os.path.basename(image_path),
"subfolder": subfolder,
"type": self.type
}
results.append(image_data)
metastring = ""
if image_metadata is not None:
for key, val in image_metadata.items():
if len(str(val).strip( '"')) > 0:
metastring = metastring + ':: ' + key.upper() + ': ' + str(val).strip( '"') + '\n'
saved_info = f""":: Time to save: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
:: Output file: {output_file}
:: PROCESS INFO ::
------------------
{metastring}"""
if save_info_to_txt:
infofile = os.path.splitext(output_file)[0] + '.txt'
with open(infofile, 'w', encoding='utf-8', newline="") as infofile:
infofile.write(saved_info)
return saved_info, {"ui": {"images": []}}
def get_subfolder_path(self, image_path, output_path):
output_parts = output_path.strip(os.sep).split(os.sep)
image_parts = image_path.strip(os.sep).split(os.sep)
common_parts = os.path.commonprefix([output_parts, image_parts])
subfolder_parts = image_parts[len(common_parts):]
subfolder_path = os.sep.join(subfolder_parts[:-1])
return subfolder_path
class TextTokens:
def __init__(self):
self.tokens = {
'[time]': str(time.time()).replace('.', '_')
}
if '.' in self.tokens['[time]']: self.tokens['[time]'] = self.tokens['[time]'].split('.')[0]
def format_time(self, format_code):
return time.strftime(format_code, time.localtime(time.time()))
def parseTokens(self, text):
tokens = self.tokens.copy()
# Update time
tokens['[time]'] = str(time.time())
if '.' in tokens['[time]']:
tokens['[time]'] = tokens['[time]'].split('.')[0]
for token, value in tokens.items():
if token.startswith('[time('):
continue
text = text.replace(token, value)
def replace_custom_time(match):
format_code = match.group(1)
return self.format_time(format_code)
text = re.sub(r'\[time\((.*?)\)\]', replace_custom_time, text)
return text
class AnyType(str):
def __ne__(self, __value: object) -> bool:
return False
any = AnyType("*")
class PrimereAnyOutput:
RETURN_TYPES = ()
FUNCTION = "show_output"
OUTPUT_NODE = True
CATEGORY = TREE_OUTPUTS
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"input": (any, {}),
},
}
def show_output(self, input = None):
value = 'None'
if input is not None:
try:
value = json.dumps(input, indent=4)
except Exception:
try:
value = str(input)
except Exception:
value = 'Input data exists, but could not be serialized.'
return {"ui": {"text": (value.strip( '"'),)}}
class PrimereTextOutput:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"text": ("STRING", {"forceInput": True}),
},
}
INPUT_IS_LIST = True
RETURN_TYPES = ()
FUNCTION = "notify"
OUTPUT_NODE = True
OUTPUT_IS_LIST = (True,)
CATEGORY = TREE_OUTPUTS
def notify(self, text):
return {"ui": {"text": text}}
+74
View File
@@ -0,0 +1,74 @@
from custom_nodes.ComfyUI_Primere_Nodes.components.tree import TREE_STYLES
from custom_nodes.ComfyUI_Primere_Nodes.components.tree import PRIMERE_ROOT
import os
import tomli
class PrimereStylePile:
RETURN_TYPES = ("STRING", "STRING")
RETURN_NAMES = ("STYLE+", "STYLE-")
FUNCTION = "styleple"
CATEGORY = TREE_STYLES
@staticmethod
def get_all_styles(toml_path: str):
with open(toml_path, "rb") as f:
style_def_neg = tomli.load(f)
return style_def_neg
@ classmethod
def INPUT_TYPES(cls):
DEF_TOML_DIR = os.path.join(PRIMERE_ROOT, 'Toml')
STYLE = cls.get_all_styles(os.path.join(DEF_TOML_DIR, "stylepile.toml"))
cls.ART_TYPES = STYLE['art-type']
cls.CONCEPTS = ['None'] + sorted(STYLE['concepts']['concepts'])
cls.ARTISTS = ['None'] + sorted(STYLE['artists']['artists'])
cls.ART_MOVEMENTS = ['None'] + sorted(STYLE['art-movements']['art-movements'])
cls.COLORS = ['None'] + sorted(STYLE['colors']['colors'])
cls.DIRECTIONS = ['None'] + sorted(STYLE['directions']['directions'])
cls.MOODS = ['None'] + sorted(STYLE['moods']['moods'])
return {
"required": {
"art_type": (list(cls.ART_TYPES.keys()),),
"art_type_strength": ("FLOAT", {"default": 1, "min": 0.0, "max": 10.0, "step": 0.01}),
"color": (cls.COLORS,),
"color_strength": ("FLOAT", {"default": 1, "min": 0.0, "max": 10.0, "step": 0.01}),
"mood": (cls.MOODS,),
"mood_strength": ("FLOAT", {"default": 1, "min": 0.0, "max": 10.0, "step": 0.01}),
"direction": (cls.DIRECTIONS,),
"direction_strength": ("FLOAT", {"default": 1, "min": 0.0, "max": 10.0, "step": 0.01}),
"concept": (cls.CONCEPTS,),
"concept_strength": ("FLOAT", {"default": 1, "min": 0.0, "max": 10.0, "step": 0.01}),
"artist": (cls.ARTISTS,),
"artist_strength": ("FLOAT", {"default": 1, "min": 0.0, "max": 10.0, "step": 0.01}),
"movement": (cls.ART_MOVEMENTS,),
"movement_strength": ("FLOAT", {"default": 1, "min": 0.0, "max": 10.0, "step": 0.01}),
},
"optional": {
"opt_pos_style": ("STRING", {"forceInput": True}),
"opt_neg_style": ("STRING", {"forceInput": True}),
}
}
def styleple(self, concept, concept_strength, art_type, art_type_strength, artist, artist_strength, movement, movement_strength, color, color_strength, mood, mood_strength, direction, direction_strength, opt_pos_style = '', opt_neg_style = ''):
opt_pos_style = f'({opt_pos_style})' if opt_pos_style is not None and opt_pos_style.strip(' ,;') != '' else ''
opt_neg_style = f'({opt_neg_style})' if opt_neg_style is not None and opt_neg_style.strip(' ,;') != '' else ''
art_type_positive = self.ART_TYPES[art_type]['positive']
art_type_negative = self.ART_TYPES[art_type]['negative']
art_type_pos_str = f'({art_type_positive}:{art_type_strength:.2f})' if art_type_positive is not None and art_type_positive != 'None' and art_type_positive.strip(' ,;') != '' else ''
art_type_neg_str = f'({art_type_negative}:{art_type_strength:.2f})' if art_type_negative is not None and art_type_negative != 'None' and art_type_negative.strip(' ,;') != '' else ''
color = f'({color}:{color_strength:.2f})' if color is not None and color != 'None' and color.strip(' ,;') != '' else ''
mood = f'({mood}:{mood_strength:.2f})' if mood is not None and mood != 'None' and mood.strip(' ,;') != '' else ''
direction = f'({direction}:{direction_strength:.2f})' if direction is not None and direction != 'None' and direction.strip(' ,;') != '' else ''
concept = f'({concept}:{concept_strength:.2f})' if concept is not None and concept != 'None' and concept.strip(' ,;') != '' else ''
artist = f'({artist}:{artist_strength:.2f})' if artist is not None and artist != 'None' and artist.strip(' ,;') != '' else ''
movement = f'({movement}:{movement_strength:.2f})' if movement is not None and movement != 'None' and movement.strip(' ,;') != '' else ''
positive_text = f'{opt_pos_style}, {art_type_pos_str}, {color}, {mood}, {direction}, {concept}, {artist}, {movement}'.strip(' ,;').replace(", , ", ", ").replace(", , ", ", ").replace(", , ", ", ")
negative_text = f'{opt_neg_style}, {art_type_neg_str}'.strip(' ,;').replace(", , ", ", ").replace(", , ", ", ")
return (positive_text, negative_text,)
+446
View File
@@ -0,0 +1,446 @@
import nodes
from custom_nodes.ComfyUI_Primere_Nodes.components.tree import TREE_VISUALS
from custom_nodes.ComfyUI_Primere_Nodes.components.tree import PRIMERE_ROOT
import folder_paths
from custom_nodes.ComfyUI_Primere_Nodes.components import utility
from custom_nodes.ComfyUI_Primere_Nodes.components import hypernetwork
import comfy.sd
import comfy.utils
import os
import random
from pathlib import Path
import chardet
import pandas
import re
# import comfy_extras.nodes_hypernetwork as comfy_extras
class PrimereVisualCKPT:
RETURN_TYPES = ("CHECKPOINT_NAME", "STRING")
RETURN_NAMES = ("MODEL_NAME", "MODEL_VERSION")
FUNCTION = "load_ckpt_visual_list"
CATEGORY = TREE_VISUALS
def __init__(self):
self.chkp_loader = nodes.CheckpointLoaderSimple()
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"base_model": (folder_paths.get_filename_list("checkpoints"),),
"show_modal": ("BOOLEAN", {"default": True}),
"show_hidden": ("BOOLEAN", {"default": True}),
},
}
def load_ckpt_visual_list(self, base_model, show_hidden, show_modal):
LOADED_CHECKPOINT = self.chkp_loader.load_checkpoint(base_model)
model_version = utility.getCheckpointVersion(LOADED_CHECKPOINT[0])
return (base_model, model_version)
class PrimereVisualLORA:
RETURN_TYPES = ("MODEL", "CLIP", "LORA_STACK", "MODEL_KEYWORD")
RETURN_NAMES = ("MODEL", "CLIP", "LORA_STACK", "LORA_KEYWORD")
FUNCTION = "visual_lora_stacker"
CATEGORY = TREE_VISUALS
LORASCOUNT = 6
@classmethod
def INPUT_TYPES(cls):
LoraList = folder_paths.get_filename_list("loras")
return {
"required": {
"model": ("MODEL",),
"clip": ("CLIP",),
"model_version": ("STRING", {"default": 'BaseModel_1024', "forceInput": True}),
"stack_version": (["SD", "SDXL", "Any"], {"default": "Any"}),
"show_modal": ("BOOLEAN", {"default": True}),
"show_hidden": ("BOOLEAN", {"default": True}),
"use_only_model_weight": ("BOOLEAN", {"default": True}),
"use_lora_1": ("BOOLEAN", {"default": False}),
"lora_1": (LoraList,),
"lora_1_model_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"lora_1_clip_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_lora_2": ("BOOLEAN", {"default": False}),
"lora_2": (LoraList,),
"lora_2_model_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"lora_2_clip_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_lora_3": ("BOOLEAN", {"default": False}),
"lora_3": (LoraList,),
"lora_3_model_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"lora_3_clip_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_lora_4": ("BOOLEAN", {"default": False}),
"lora_4": (LoraList,),
"lora_4_model_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"lora_4_clip_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_lora_5": ("BOOLEAN", {"default": False}),
"lora_5": (LoraList,),
"lora_5_model_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"lora_5_clip_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_lora_6": ("BOOLEAN", {"default": False}),
"lora_6": (LoraList,),
"lora_6_model_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"lora_6_clip_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_lora_keyword": ("BOOLEAN", {"default": False}),
"lora_keyword_placement": (["First", "Last"], {"default": "Last"}),
"lora_keyword_selection": (["Select in order", "Random select"], {"default": "Select in order"}),
"lora_keywords_num": ("INT", {"default": 1, "min": 1, "max": 50, "step": 1}),
"lora_keyword_weight": ("FLOAT", {"default": 1.0, "min": 0, "max": 10.0, "step": 0.1}),
},
}
def visual_lora_stacker(self, model, clip, use_only_model_weight, use_lora_keyword, lora_keyword_placement, lora_keyword_selection, lora_keywords_num, lora_keyword_weight, stack_version = 'Any', model_version = "BaseModel_1024", **kwargs):
model_keyword = [None, None]
if model_version == 'SDXL_2048' and stack_version == 'SD':
return (model, clip, [], model_keyword)
if model_version != 'SDXL_2048' and stack_version == 'SDXL':
return (model, clip, [], model_keyword)
loras = [kwargs.get(f"lora_{i}") for i in range(1, self.LORASCOUNT + 1)]
model_weight = [kwargs.get(f"lora_{i}_model_weight") for i in range(1, self.LORASCOUNT + 1)]
if use_only_model_weight == True:
clip_weight =[kwargs.get(f"lora_{i}_model_weight") for i in range(1, self.LORASCOUNT + 1)]
else:
clip_weight =[kwargs.get(f"lora_{i}_clip_weight") for i in range(1, self.LORASCOUNT + 1)]
uses = [kwargs.get(f"use_lora_{i}") for i in range(1, self.LORASCOUNT + 1)]
lora_stack = [(lora_name, lora_model_weight, lora_clip_weight) for lora_name, lora_model_weight, lora_clip_weight, lora_uses in zip(loras, model_weight, clip_weight, uses) if lora_uses == True]
lora_params = list()
if lora_stack and len(lora_stack) > 0:
lora_params.extend(lora_stack)
else:
return (model, clip, lora_stack, model_keyword)
model_lora = model
clip_lora = clip
list_of_keyword_items = []
lora_keywords_num_set = lora_keywords_num
for tup in lora_params:
lora_name, strength_model, strength_clip = tup
lora_path = folder_paths.get_full_path("loras", lora_name)
lora = comfy.utils.load_torch_file(lora_path, safe_load=True)
model_lora, clip_lora = comfy.sd.load_lora_for_models(model_lora, clip_lora, lora, strength_model, strength_clip)
if use_lora_keyword == True:
ModelKvHash = utility.get_model_hash(lora_path)
if ModelKvHash is not None:
KEYWORD_PATH = os.path.join(PRIMERE_ROOT, 'front_end', 'keywords', 'lora-keyword.txt')
keywords = utility.get_model_keywords(KEYWORD_PATH, ModelKvHash, lora_name)
if keywords is not None and keywords != "":
if keywords.find('|') > 1:
keyword_list = [word.strip() for word in keywords.split('|')]
keyword_list = list(filter(None, keyword_list))
if (len(keyword_list) > 0):
lora_keywords_num = lora_keywords_num_set
keyword_qty = len(keyword_list)
if (lora_keywords_num > keyword_qty):
lora_keywords_num = keyword_qty
if lora_keyword_selection == 'Select in order':
list_of_keyword_items.extend(keyword_list[:lora_keywords_num])
else:
list_of_keyword_items.extend(random.sample(keyword_list, lora_keywords_num))
else:
list_of_keyword_items.append(keywords)
if len(list_of_keyword_items) > 0:
if lora_keyword_selection != 'Select in order':
random.shuffle(list_of_keyword_items)
list_of_keyword_items = list(set(list_of_keyword_items))
keywords = ", ".join(list_of_keyword_items)
if (lora_keyword_weight != 1):
keywords = '(' + keywords + ':' + str(lora_keyword_weight) + ')'
model_keyword = [keywords, lora_keyword_placement]
return (model_lora, clip_lora, lora_stack, model_keyword)
class PrimereVisualEmbedding:
RETURN_TYPES = ("EMBEDDING", "EMBEDDING", "EMBEDDING_STACK")
RETURN_NAMES = ("EMBEDDING+", "EMBEDDING-", "EMBEDDING_STACK")
FUNCTION = "primere_visual_embedding"
CATEGORY = TREE_VISUALS
EMBCOUNT = 6
@classmethod
def INPUT_TYPES(self):
EmbeddingList = folder_paths.get_filename_list("embeddings")
return {
"required": {
"model_version": ("STRING", {"default": 'BaseModel_1024', "forceInput": True}),
"stack_version": (["SD", "SDXL", "Any"], {"default": "Any"}),
"show_modal": ("BOOLEAN", {"default": True}),
"show_hidden": ("BOOLEAN", {"default": True}),
"use_embedding_1": ("BOOLEAN", {"default": False}),
"embedding_1": (EmbeddingList,),
"embedding_1_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01, },),
"is_negative_1": ("BOOLEAN", {"default": False}),
"use_embedding_2": ("BOOLEAN", {"default": False}),
"embedding_2": (EmbeddingList,),
"embedding_2_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01, },),
"is_negative_2": ("BOOLEAN", {"default": False}),
"use_embedding_3": ("BOOLEAN", {"default": False}),
"embedding_3": (EmbeddingList,),
"embedding_3_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01, },),
"is_negative_3": ("BOOLEAN", {"default": False}),
"use_embedding_4": ("BOOLEAN", {"default": False}),
"embedding_4": (EmbeddingList,),
"embedding_4_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01, },),
"is_negative_4": ("BOOLEAN", {"default": False}),
"use_embedding_5": ("BOOLEAN", {"default": False}),
"embedding_5": (EmbeddingList,),
"embedding_5_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01, },),
"is_negative_5": ("BOOLEAN", {"default": False}),
"use_embedding_6": ("BOOLEAN", {"default": False}),
"embedding_6": (EmbeddingList,),
"embedding_6_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01, },),
"is_negative_6": ("BOOLEAN", {"default": False}),
"embedding_placement_pos": (["First", "Last"], {"default": "Last"}),
"embedding_placement_neg": (["First", "Last"], {"default": "Last"}),
},
}
def primere_visual_embedding(self, embedding_placement_pos, embedding_placement_neg, stack_version='Any', model_version="BaseModel_1024", **kwargs):
if model_version == 'SDXL_2048' and stack_version == 'SD':
return ([None, None], [None, None], [])
if model_version != 'SDXL_2048' and stack_version == 'SDXL':
return ([None, None], [None, None], [])
embedding_pos_list = []
embedding_neg_list = []
embeddings = [kwargs.get(f"embedding_{i}") for i in range(1, self.EMBCOUNT + 1)]
use_embeddings = [kwargs.get(f"use_embedding_{i}") for i in range(1, self.EMBCOUNT + 1)]
embedding_weight = [kwargs.get(f"embedding_{i}_weight") for i in range(1, self.EMBCOUNT + 1)]
neg_embedding = [kwargs.get(f"is_negative_{i}") for i in range(1, self.EMBCOUNT + 1)]
embedding_stack = [(emb_name, emb_weight, is_emb_neg) for emb_name, emb_weight, is_emb_neg, emb_uses in zip(embeddings, embedding_weight, neg_embedding, use_embeddings) if emb_uses == True]
if embedding_stack is not None and len(embedding_stack) > 0:
for embedding_tuple in embedding_stack:
embedd_name_path = embedding_tuple[0]
embedd_weight = embedding_tuple[1]
embedd_neg = embedding_tuple[2]
embedd_name = Path(embedd_name_path).stem
if (embedd_weight != 1):
embedding_sting = '(embedding:' + embedd_name + ':' + str(embedd_weight) + ')'
else:
embedding_sting = 'embedding:' + embedd_name
if embedd_neg == False:
embedding_pos_list.append(embedding_sting)
else:
embedding_neg_list.append(embedding_sting)
else:
return ([None, None], [None, None], [])
embedding_pos_list = list(set(embedding_pos_list))
embedding_neg_list = list(set(embedding_neg_list))
if len(embedding_pos_list) > 0:
embedding_pos = ", ".join(embedding_pos_list)
else:
embedding_pos = None
embedding_placement_pos = None
if len(embedding_neg_list) > 0:
embedding_neg = ", ".join(embedding_neg_list)
else:
embedding_neg = None
embedding_placement_neg = None
return ([embedding_pos, embedding_placement_pos], [embedding_neg, embedding_placement_neg], embedding_stack,)
class PrimereVisualHypernetwork:
RETURN_TYPES = ("MODEL", "HYPERNETWORK_STACK")
RETURN_NAMES = ("MODEL", "HYPERNETWORK_STACK")
FUNCTION = "visual_hypernetwork"
CATEGORY = TREE_VISUALS
EMBCOUNT = 6
@classmethod
def INPUT_TYPES(s):
HypernetworkList = folder_paths.get_filename_list("hypernetworks")
return {"required": {
"model": ("MODEL",),
"model_version": ("STRING", {"default": 'BaseModel_1024', "forceInput": True}),
"stack_version": (["SD", "SDXL", "Any"], {"default": "Any"}),
"show_modal": ("BOOLEAN", {"default": True}),
"show_hidden": ("BOOLEAN", {"default": True}),
"use_hypernetwork_1": ("BOOLEAN", {"default": False}),
"hypernetwork_1": (HypernetworkList, ),
"hypernetwork_1_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_hypernetwork_2": ("BOOLEAN", {"default": False}),
"hypernetwork_2": (HypernetworkList,),
"hypernetwork_2_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_hypernetwork_3": ("BOOLEAN", {"default": False}),
"hypernetwork_3": (HypernetworkList,),
"hypernetwork_3_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_hypernetwork_4": ("BOOLEAN", {"default": False}),
"hypernetwork_4": (HypernetworkList,),
"hypernetwork_4_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_hypernetwork_5": ("BOOLEAN", {"default": False}),
"hypernetwork_5": (HypernetworkList,),
"hypernetwork_5_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"use_hypernetwork_6": ("BOOLEAN", {"default": False}),
"hypernetwork_6": (HypernetworkList,),
"hypernetwork_6_weight": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
}
}
def visual_hypernetwork(self, model, model_version, stack_version = "Any", **kwargs):
model_hypernetwork = model
if model_version == 'SDXL_2048' and stack_version == 'SD':
return (model, [],)
if model_version != 'SDXL_2048' and stack_version == 'SDXL':
return (model, [],)
hnetworks = [kwargs.get(f"hypernetwork_{i}") for i in range(1, self.EMBCOUNT + 1)]
use_hnetworks = [kwargs.get(f"use_hypernetwork_{i}") for i in range(1, self.EMBCOUNT + 1)]
hnetworks_weight = [kwargs.get(f"hypernetwork_{i}_weight") for i in range(1, self.EMBCOUNT + 1)]
hnetwork_stack = [(hn_name, hn_weight) for hn_name, hn_weight, hn_uses in zip(hnetworks, hnetworks_weight, use_hnetworks) if hn_uses == True]
if hnetwork_stack is not None and len(hnetwork_stack) > 0:
cloned_model = model
for hn_tuple in hnetwork_stack:
hypernetwork_path = folder_paths.get_full_path("hypernetworks", hn_tuple[0])
model_hypernetwork = cloned_model.clone()
patch = hypernetwork.load_hypernetwork_patch(hypernetwork_path, hn_tuple[1], False)
if patch is not None:
model_hypernetwork.set_model_attn1_patch(patch)
model_hypernetwork.set_model_attn2_patch(patch)
cloned_model = model_hypernetwork
else:
return (model, [],)
return (model_hypernetwork, hnetwork_stack,)
class PrimereVisualStyle:
RETURN_TYPES = ("STRING", "STRING", "STRING", "STRING", "STRING")
RETURN_NAMES = ("PROMPT+", "PROMPT-", "SUBPATH", "MODEL", "ORIENTATION")
FUNCTION = "load_visual_csv"
CATEGORY = TREE_VISUALS
@staticmethod
def load_styles_csv(styles_path: str):
fileTest = open(styles_path, 'rb').readline()
result = chardet.detect(fileTest)
ENCODING = result['encoding']
if ENCODING == 'ascii':
ENCODING = 'UTF-8'
with open(styles_path, "r", newline = '', encoding = ENCODING) as csv_file:
try:
return pandas.read_csv(csv_file)
except pandas.errors.ParserError as e:
errorstring = repr(e)
matchre = re.compile('Expected (\d+) fields in line (\d+), saw (\d+)')
(expected, line, saw) = map(int, matchre.search(errorstring).groups())
print(f'Error at line {line}. Fields added : {saw - expected}.')
@classmethod
def INPUT_TYPES(cls):
STYLE_DIR = os.path.join(PRIMERE_ROOT, 'stylecsv')
cls.styles_csv = cls.load_styles_csv(os.path.join(STYLE_DIR, "styles.csv"))
return {
"required": {
"styles": (sorted(list(cls.styles_csv['name'])),),
"show_modal": ("BOOLEAN", {"default": True}),
"show_hidden": ("BOOLEAN", {"default": True}),
"use_subpath": ("BOOLEAN", {"default": False}),
"use_model": ("BOOLEAN", {"default": False}),
"use_orientation": ("BOOLEAN", {"default": False}),
},
}
def load_visual_csv(self, styles, show_modal, show_hidden, use_subpath, use_model, use_orientation):
try:
positive_prompt = self.styles_csv[self.styles_csv['name'] == styles]['prompt'].values[0]
except Exception:
positive_prompt = ''
try:
negative_prompt = self.styles_csv[self.styles_csv['name'] == styles]['negative_prompt'].values[0]
except Exception:
negative_prompt = ''
try:
prefered_subpath = self.styles_csv[self.styles_csv['name'] == styles]['prefered_subpath'].values[0]
except Exception:
prefered_subpath = ''
try:
prefered_model = self.styles_csv[self.styles_csv['name'] == styles]['prefered_model'].values[0]
except Exception:
prefered_model = ''
try:
prefered_orientation = self.styles_csv[self.styles_csv['name'] == styles]['prefered_orientation'].values[0]
except Exception:
prefered_orientation = ''
pos_type = type(positive_prompt).__name__
neg_type = type(negative_prompt).__name__
subp_type = type(prefered_subpath).__name__
model_type = type(prefered_model).__name__
orientation_type = type(prefered_orientation).__name__
if (pos_type != 'str'):
positive_prompt = ''
if (neg_type != 'str'):
negative_prompt = ''
if (subp_type != 'str'):
prefered_subpath = ''
if (model_type != 'str'):
prefered_model = ''
if (orientation_type != 'str'):
prefered_orientation = ''
if len(prefered_subpath.strip()) < 1:
prefered_subpath = None
if len(prefered_model.strip()) < 1:
prefered_model = None
if len(prefered_orientation.strip()) < 1:
prefered_orientation = None
if use_subpath == False:
prefered_subpath = None
if use_model == False:
prefered_model = None
if use_orientation == False:
prefered_orientation = None
return (positive_prompt, negative_prompt, prefered_subpath, prefered_model, prefered_orientation)
+290
View File
@@ -0,0 +1,290 @@
import torch
import numpy as np
import itertools
from math import gcd
from comfy import model_management
from comfy.sdxl_clip import SDXLClipModel, SDXLRefinerClipModel, SDXLClipG
def _grouper(n, iterable):
it = iter(iterable)
while True:
chunk = list(itertools.islice(it, n))
if not chunk:
return
yield chunk
def _norm_mag(w, n):
d = w - 1
return 1 + np.sign(d) * np.sqrt(np.abs(d)**2 / n)
#return np.sign(w) * np.sqrt(np.abs(w)**2 / n)
def divide_length(word_ids, weights):
sums = dict(zip(*np.unique(word_ids, return_counts=True)))
sums[0] = 1
weights = [[_norm_mag(w, sums[id]) if id != 0 else 1.0
for w, id in zip(x, y)] for x, y in zip(weights, word_ids)]
return weights
def shift_mean_weight(word_ids, weights):
delta = 1 - np.mean([w for x, y in zip(weights, word_ids) for w, id in zip(x,y) if id != 0])
weights = [[w if id == 0 else w+delta
for w, id in zip(x, y)] for x, y in zip(weights, word_ids)]
return weights
def scale_to_norm(weights, word_ids, w_max):
top = np.max(weights)
w_max = min(top, w_max)
weights = [[w_max if id == 0 else (w/top) * w_max
for w, id in zip(x, y)] for x, y in zip(weights, word_ids)]
return weights
def from_zero(weights, base_emb):
weight_tensor = torch.tensor(weights, dtype=base_emb.dtype, device=base_emb.device)
weight_tensor = weight_tensor.reshape(1,-1,1).expand(base_emb.shape)
return base_emb * weight_tensor
def mask_word_id(tokens, word_ids, target_id, mask_token):
new_tokens = [[mask_token if wid == target_id else t
for t, wid in zip(x,y)] for x,y in zip(tokens, word_ids)]
mask = np.array(word_ids) == target_id
return (new_tokens, mask)
def batched_clip_encode(tokens, length, encode_func, num_chunks):
embs = []
for e in _grouper(32, tokens):
enc, pooled = encode_func(e)
enc = enc.reshape((len(e), length, -1))
embs.append(enc)
embs = torch.cat(embs)
embs = embs.reshape((len(tokens) // num_chunks, length * num_chunks, -1))
return embs
def from_masked(tokens, weights, word_ids, base_emb, length, encode_func, m_token=266):
pooled_base = base_emb[0,length-1:length,:]
wids, inds = np.unique(np.array(word_ids).reshape(-1), return_index=True)
weight_dict = dict((id,w)
for id,w in zip(wids ,np.array(weights).reshape(-1)[inds])
if w != 1.0)
if len(weight_dict) == 0:
return torch.zeros_like(base_emb), base_emb[0,length-1:length,:]
weight_tensor = torch.tensor(weights, dtype=base_emb.dtype, device=base_emb.device)
weight_tensor = weight_tensor.reshape(1,-1,1).expand(base_emb.shape)
#m_token = (clip.tokenizer.end_token, 1.0) if clip.tokenizer.pad_with_end else (0,1.0)
#TODO: find most suitable masking token here
m_token = (m_token, 1.0)
ws = []
masked_tokens = []
masks = []
#create prompts
for id, w in weight_dict.items():
masked, m = mask_word_id(tokens, word_ids, id, m_token)
masked_tokens.extend(masked)
m = torch.tensor(m, dtype=base_emb.dtype, device=base_emb.device)
m = m.reshape(1,-1,1).expand(base_emb.shape)
masks.append(m)
ws.append(w)
#batch process prompts
embs = batched_clip_encode(masked_tokens, length, encode_func, len(tokens))
masks = torch.cat(masks)
embs = (base_emb.expand(embs.shape) - embs)
pooled = embs[0,length-1:length,:]
embs *= masks
embs = embs.sum(axis=0, keepdim=True)
pooled_start = pooled_base.expand(len(ws), -1)
ws = torch.tensor(ws).reshape(-1,1).expand(pooled_start.shape)
pooled = (pooled - pooled_start) * (ws - 1)
pooled = pooled.mean(axis=0, keepdim=True)
return ((weight_tensor - 1) * embs), pooled_base + pooled
def mask_inds(tokens, inds, mask_token):
clip_len = len(tokens[0])
inds_set = set(inds)
new_tokens = [[mask_token if i*clip_len + j in inds_set else t
for j, t in enumerate(x)] for i, x in enumerate(tokens)]
return new_tokens
def down_weight(tokens, weights, word_ids, base_emb, length, encode_func, m_token=266):
w, w_inv = np.unique(weights,return_inverse=True)
if np.sum(w < 1) == 0:
return base_emb, tokens, base_emb[0,length-1:length,:]
#m_token = (clip.tokenizer.end_token, 1.0) if clip.tokenizer.pad_with_end else (0,1.0)
#using the comma token as a masking token seems to work better than aos tokens for SD 1.x
m_token = (m_token, 1.0)
masked_tokens = []
masked_current = tokens
for i in range(len(w)):
if w[i] >= 1:
continue
masked_current = mask_inds(masked_current, np.where(w_inv == i)[0], m_token)
masked_tokens.extend(masked_current)
embs = batched_clip_encode(masked_tokens, length, encode_func, len(tokens))
embs = torch.cat([base_emb, embs])
w = w[w<=1.0]
w_mix = np.diff([0] + w.tolist())
w_mix = torch.tensor(w_mix, dtype=embs.dtype, device=embs.device).reshape((-1,1,1))
weighted_emb = (w_mix * embs).sum(axis=0, keepdim=True)
return weighted_emb, masked_current, weighted_emb[0,length-1:length,:]
def scale_emb_to_mag(base_emb, weighted_emb):
norm_base = torch.linalg.norm(base_emb)
norm_weighted = torch.linalg.norm(weighted_emb)
embeddings_final = (norm_base / norm_weighted) * weighted_emb
return embeddings_final
def recover_dist(base_emb, weighted_emb):
fixed_std = (base_emb.std() / weighted_emb.std()) * (weighted_emb - weighted_emb.mean())
embeddings_final = fixed_std + (base_emb.mean() - fixed_std.mean())
return embeddings_final
def A1111_renorm(base_emb, weighted_emb):
embeddings_final = (base_emb.mean() / weighted_emb.mean()) * weighted_emb
return embeddings_final
def advanced_encode_from_tokens(tokenized, token_normalization, weight_interpretation, encode_func, m_token=266, length=77, w_max=1.0, return_pooled=False, apply_to_pooled=False):
tokens = [[t for t,_,_ in x] for x in tokenized]
weights = [[w for _,w,_ in x] for x in tokenized]
word_ids = [[wid for _,_,wid in x] for x in tokenized]
#weight normalization
#====================
#distribute down/up weights over word lengths
if token_normalization.startswith("length"):
weights = divide_length(word_ids, weights)
#make mean of word tokens 1
if token_normalization.endswith("mean"):
weights = shift_mean_weight(word_ids, weights)
#weight interpretation
#=====================
pooled = None
if weight_interpretation == "comfy":
weighted_tokens = [[(t,w) for t, w in zip(x, y)] for x, y in zip(tokens, weights)]
weighted_emb, pooled_base = encode_func(weighted_tokens)
pooled = pooled_base
else:
unweighted_tokens = [[(t,1.0) for t, _,_ in x] for x in tokenized]
base_emb, pooled_base = encode_func(unweighted_tokens)
if weight_interpretation == "A1111":
weighted_emb = from_zero(weights, base_emb)
weighted_emb = A1111_renorm(base_emb, weighted_emb)
pooled = pooled_base
if weight_interpretation == "compel":
pos_tokens = [[(t,w) if w >= 1.0 else (t,1.0) for t, w in zip(x, y)] for x, y in zip(tokens, weights)]
weighted_emb, _ = encode_func(pos_tokens)
weighted_emb, _, pooled = down_weight(pos_tokens, weights, word_ids, weighted_emb, length, encode_func)
if weight_interpretation == "comfy++":
weighted_emb, tokens_down, _ = down_weight(unweighted_tokens, weights, word_ids, base_emb, length, encode_func)
weights = [[w if w > 1.0 else 1.0 for w in x] for x in weights]
#unweighted_tokens = [[(t,1.0) for t, _,_ in x] for x in tokens_down]
embs, pooled = from_masked(unweighted_tokens, weights, word_ids, base_emb, length, encode_func)
weighted_emb += embs
if weight_interpretation == "down_weight":
weights = scale_to_norm(weights, word_ids, w_max)
weighted_emb, _, pooled = down_weight(unweighted_tokens, weights, word_ids, base_emb, length, encode_func)
if return_pooled:
if apply_to_pooled:
return weighted_emb, pooled
else:
return weighted_emb, pooled_base
return weighted_emb, None
def encode_token_weights_g(model, token_weight_pairs):
return model.clip_g.encode_token_weights(token_weight_pairs)
def encode_token_weights_l(model, token_weight_pairs):
l_out, _ = model.clip_l.encode_token_weights(token_weight_pairs)
return l_out, None
def encode_token_weights(model, token_weight_pairs, encode_func):
if model.layer_idx is not None:
model.cond_stage_model.clip_layer(model.layer_idx)
model_management.load_model_gpu(model.patcher)
return encode_func(model.cond_stage_model, token_weight_pairs)
def prepareXL(embs_l, embs_g, pooled, clip_balance):
l_w = 1 - max(0, clip_balance - .5) * 2
g_w = 1 - max(0, .5 - clip_balance) * 2
if embs_l is not None:
return torch.cat([embs_l * l_w, embs_g * g_w], dim=-1), pooled
else:
return embs_g, pooled
def advanced_encode(clip, text, token_normalization, weight_interpretation, w_max=1.0, clip_balance=.5, apply_to_pooled=True):
tokenized = clip.tokenize(text, return_word_ids=True)
if isinstance(clip.cond_stage_model, (SDXLClipModel, SDXLRefinerClipModel, SDXLClipG)):
embs_l = None
embs_g = None
pooled = None
if 'l' in tokenized and isinstance(clip.cond_stage_model, SDXLClipModel):
embs_l, _ = advanced_encode_from_tokens(tokenized['l'],
token_normalization,
weight_interpretation,
lambda x: encode_token_weights(clip, x, encode_token_weights_l),
w_max=w_max,
return_pooled=False)
if 'g' in tokenized:
embs_g, pooled = advanced_encode_from_tokens(tokenized['g'],
token_normalization,
weight_interpretation,
lambda x: encode_token_weights(clip, x, encode_token_weights_g),
w_max=w_max,
return_pooled=True,
apply_to_pooled=apply_to_pooled)
return prepareXL(embs_l, embs_g, pooled, clip_balance)
else:
return advanced_encode_from_tokens(tokenized['l'],
token_normalization,
weight_interpretation,
lambda x: (clip.encode_from_tokens({'l': x}), None),
w_max=w_max)
def advanced_encode_XL(clip, text1, text2, token_normalization, weight_interpretation, w_max=1.0, clip_balance=.5, apply_to_pooled=True):
tokenized1 = clip.tokenize(text1, return_word_ids=True)
tokenized2 = clip.tokenize(text2, return_word_ids=True)
embs_l, _ = advanced_encode_from_tokens(tokenized1['l'],
token_normalization,
weight_interpretation,
lambda x: encode_token_weights(clip, x, encode_token_weights_l),
w_max=w_max,
return_pooled=False)
embs_g, pooled = advanced_encode_from_tokens(tokenized2['g'],
token_normalization,
weight_interpretation,
lambda x: encode_token_weights(clip, x, encode_token_weights_g),
w_max=w_max,
return_pooled=True,
apply_to_pooled=apply_to_pooled)
gcd_num = gcd(embs_l.shape[1], embs_g.shape[1])
repeat_l = int((embs_g.shape[1] / gcd_num) * embs_l.shape[1])
repeat_g = int((embs_l.shape[1] / gcd_num) * embs_g.shape[1])
return prepareXL(embs_l.expand((-1,repeat_l,-1)), embs_g.expand((-1,repeat_g,-1)), pooled, clip_balance)
+132
View File
@@ -0,0 +1,132 @@
from ..exif.base_format import BaseFormat
import re
class Automatic1111(BaseFormat):
def __init__(self, info: dict = None, raw: str = ""):
super().__init__(info, raw)
if not self._raw:
self._raw = self._info.get("parameters")
self.ProcessExif()
def ProcessExif(self):
exif_string = self._raw
# print(exif_string)
EXIF_LABELS = {
"positive":'Positive prompt',
"negative":'Negative prompt',
"steps":'Steps',
"sampler":'Sampler',
"seed":'Seed',
"variation_seed":'Variation seed',
"variation_seed_strength":'Variation seed strength',
"size_string":'Size',
"model_hash":'Model hash',
'model_name':'Model',
"vae_hash":'VAE hash',
"vae":'VAE',
"lora_hashes":'Lora hashes',
"cfg_scale":'CFG scale',
"cfg_rescale":'CFG Rescale φ',
"cfg_rescale_phi":'CFG Rescale phi',
"rp_active":'RP Active',
"rp_divide_mode":'RP Divide mode',
"rp_matrix_submode":'RP Matrix submode',
"rp_mask_submode":'RP Mask submode',
"rp_prompt_submode":'RP Prompt submode',
"rp_calc_mode":'RP Calc Mode',
"rp_ratios":'RP Ratios',
"rp_base_ratios":'RP Base Ratios',
"rp_use_base":'RP Use Base',
"rp_use_common":'RP Use Common',
"rp_use_ncommon":'RP Use Ncommon',
"rp_change_and":'RP Change AND',
"rp_lora_neg_te_ratios":'RP LoRA Neg Te Ratios',
"rp_lora_neg_u_ratios":'RP LoRA Neg U Ratios',
"rp_threshold":'RP threshold',
"npw_weight":'NPW_weight',
"antiburn":'AntiBurn',
"version":'Version',
"template":'Template',
"negative_template":'Negative Template',
"face_restoration":'Face restoration',
"postprocess_upscaler":'Postprocess upscaler',
"postprocess_upscale_by":'Postprocess upscale by'
}
LABEL_END = ['\n', ',']
STRIP_FROM_VALUE = ' ";\n'
FORCE_STRING = ['model_hash', 'vae_hash', 'lora_hashes']
FORCE_FLOAT = ['cfg_scale', 'cfg_rescale', 'cfg_rescale_phi', 'npw_weight']
# FIRST_ROW = exif_string.split('\n', 1)[0]
exif_string = 'Positive prompt: ' + exif_string
SORTED_BY_STRING = dict(sorted(EXIF_LABELS.items(), key=lambda pos: exif_string.find(pos[1] + ':')))
SORTED_KEYLIST = list(SORTED_BY_STRING.keys())
FINAL_DICT = {}
FLOAT_PATTERN = r'^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$'
for LABEL_KEY, LABEL in SORTED_BY_STRING.items():
NextValue = '\n'
RealLabel = LABEL + ':'
CurrentKeyIndex = (SORTED_KEYLIST.index(LABEL_KEY))
NextKeyIndex = CurrentKeyIndex + 1
if len(SORTED_KEYLIST) > NextKeyIndex:
NextKey = SORTED_KEYLIST[NextKeyIndex]
NextValue = SORTED_BY_STRING[NextKey] + ':'
if RealLabel in exif_string:
LabelStart = exif_string.find(RealLabel)
NextLabelStart = exif_string.find(NextValue)
LabelLength = len(RealLabel)
ValueStart = exif_string.find(exif_string[(LabelStart + LabelLength):NextLabelStart])
ValueLength = len(exif_string[(LabelStart + LabelLength):NextLabelStart])
ValueRaw = exif_string[(LabelStart + LabelLength):NextLabelStart]
FirstMatch = next((x for x in LABEL_END if x in exif_string[(ValueStart + ValueLength - 2):(ValueStart + ValueLength + 1)]), False)
if CurrentKeyIndex >= 2 and FirstMatch == ',':
isUnknownValue = all(x in ValueRaw for x in [':', ','])
if isUnknownValue:
FirstMatchOfFaliled = ValueRaw.find(FirstMatch)
NextLabelStart = ValueStart
if FirstMatch:
LabelEnd = exif_string.find(FirstMatch, NextLabelStart - 2)
LabelValue = exif_string[(LabelStart + LabelLength):LabelEnd]
else:
LabelEnd = None
if CurrentKeyIndex >= 2 and FirstMatch == '\n' or FirstMatch == False:
badValue = exif_string[(LabelStart + LabelLength):LabelEnd]
isUnknownValue = all(x in badValue for x in [':', '\n'])
if isUnknownValue:
FirstMatchOfFaliled = badValue.find('\n')
LabelEnd = exif_string.find('\n', LabelStart + LabelLength + FirstMatchOfFaliled + 2)
LabelValue = exif_string[(LabelStart + LabelLength):LabelEnd]
LabelValue = LabelValue.replace('Count=', '').strip(STRIP_FROM_VALUE)
if not LabelValue:
LabelValue = None
elif LabelValue == 'False':
LabelValue = False
elif LabelValue.isdigit():
LabelValue = int(LabelValue)
elif bool(re.match(FLOAT_PATTERN, LabelValue)):
LabelValue = float(LabelValue)
if LABEL_KEY in FORCE_STRING:
LabelValue = str(LabelValue)
if LABEL_KEY in FORCE_FLOAT:
LabelValue = float(LabelValue)
if LABEL_KEY == 'size_string':
width, height = LabelValue.split("x")
FINAL_DICT['width'] = int(width)
FINAL_DICT['height'] = int(height)
FINAL_DICT[LABEL_KEY] = LabelValue
self._parameter = FINAL_DICT
+17
View File
@@ -0,0 +1,17 @@
class BaseFormat:
def __init__(self, info: dict = None, raw: str = ""):
self._info = info
self._raw = raw
self._parameter = {}
@property
def info(self):
return self._info
@property
def raw(self):
return self._raw
@property
def parameter(self):
return self._parameter
+333
View File
@@ -0,0 +1,333 @@
import json
from ..exif.base_format import BaseFormat
from custom_nodes.ComfyUI_Primere_Nodes.components import utility
# comfyui node types
KSAMPLER_TYPES = ["KSampler", "KSamplerAdvanced"]
VAE_ENCODE_TYPE = ["VAEEncode", "VAEEncodeForInpaint"]
CHECKPOINT_LOADER_TYPE = [
"CheckpointLoader",
"CheckpointLoaderSimple",
"unCLIPCheckpointLoader",
"Checkpoint Loader (Simple)",
]
CLIP_TEXT_ENCODE_TYPE = [
"CLIPTextEncode",
"CLIPTextEncodeSDXL",
"CLIPTextEncodeSDXLRefiner",
]
SAVE_IMAGE_TYPE = ["SaveImage", "Image Save"]
class ComfyUI(BaseFormat):
def __init__(self, info: dict = None, raw: str = ""):
super().__init__(info, raw)
self._comfy_png()
def _comfy_png(self):
prompt = self._info.get("prompt") or {}
workflow = self._info.get("workflow") or {}
prompt_json = json.loads(prompt)
# find end node of each flow
end_nodes = list(filter( lambda item: item[-1].get("class_type") in ["SaveImage"] + KSAMPLER_TYPES, prompt_json.items(),))
longest_flow = {}
longest_nodes = []
longest_flow_len = 0
for end_node in end_nodes:
flow, nodes = self._comfy_traverse(prompt_json, str(end_node[0]))
if len(nodes) > longest_flow_len:
longest_flow = flow
longest_nodes = nodes
longest_flow_len = len(nodes)
SizeID = None
ModelID = None
PositiveID = None
NegativeID = None
if 'latent_image' in flow:
SizeID = flow['latent_image'][0]
if 'model' in flow:
ModelID = flow['model'][0]
if 'positive' in flow:
PositiveID = flow['positive'][0]
if 'negative' in flow:
NegativeID = flow['negative'][0]
FINAL_DICT = {}
FINAL_DICT['negative'] = ""
FINAL_DICT['positive'] = ""
if PositiveID and NegativeID and 'text_g' in prompt_json[PositiveID]['inputs']:
FINAL_DICT['positive'] = prompt_json[PositiveID]['inputs']['text_g']
FINAL_DICT['negative'] = prompt_json[NegativeID]['inputs']['text_g']
if PositiveID and NegativeID and 'text' in prompt_json[PositiveID]['inputs']:
FINAL_DICT['positive'] = prompt_json[PositiveID]['inputs']['text']
FINAL_DICT['negative'] = prompt_json[NegativeID]['inputs']['text']
if PositiveID == None or ('text_g' not in prompt_json[PositiveID]['inputs'] and 'text' not in prompt_json[PositiveID]['inputs']):
if hasattr(self, '_positive'):
FINAL_DICT['positive'] = self._positive
if hasattr(self, '_negative'):
FINAL_DICT['negative'] = self._negative
if 'steps' in flow and type(flow['steps']) == int:
FINAL_DICT['steps'] = flow['steps']
if 'sampler_name' in flow and 'scheduler' in flow and type(flow['sampler_name']) == str and type(flow['scheduler']) == str:
FINAL_DICT['sampler'] = flow['sampler_name'] + ' ' + flow['scheduler']
if 'seed' in flow and type(flow['seed']) == int:
FINAL_DICT['seed'] = flow['seed']
if 'cfg' in flow and (type(flow['cfg']) == int or type(flow['cfg']) == float):
FINAL_DICT['cfg_scale'] = flow['cfg']
if ModelID and 'ckpt_name' in prompt_json[ModelID]['inputs'] and type(prompt_json[ModelID]['inputs']['ckpt_name']) == str:
FINAL_DICT['model_name'] = prompt_json[ModelID]['inputs']['ckpt_name'] # flow['ckpt_name']
elif 'ckpt_name' in flow and type(flow['ckpt_name']) == str:
FINAL_DICT['model_name'] = flow['ckpt_name']
if SizeID and 'width' in prompt_json[SizeID]['inputs'] and 'height' in prompt_json[SizeID]['inputs'] and type(prompt_json[SizeID]['inputs']['width']) == int:
origwidth = str(prompt_json[SizeID]['inputs']['width'])
origheight = str(prompt_json[SizeID]['inputs']['height'])
FINAL_DICT['width'] = int(origwidth)
FINAL_DICT['height'] = int(origheight)
FINAL_DICT['size_string'] = origwidth + 'x' + origheight
self._parameter = FINAL_DICT
def _comfy_traverse(self, prompt, end_node):
flow = {}
node = [end_node]
inputs = {}
try:
inputs = prompt[end_node]["inputs"]
except:
print("node error")
return flow, node
match prompt[end_node]["class_type"]:
case node_type if node_type in SAVE_IMAGE_TYPE:
try:
last_flow, last_node = self._comfy_traverse(
prompt, inputs["images"][0]
)
flow = utility.merge_dict(flow, last_flow)
node += last_node
except:
print("comfyUI SaveImage error")
case node_type if node_type in KSAMPLER_TYPES:
try:
flow = inputs
last_flow1, last_node1 = self._comfy_traverse(
prompt, inputs["model"][0]
)
last_flow2, last_node2 = self._comfy_traverse(
prompt, inputs["latent_image"][0]
)
positive = self._comfy_traverse(prompt, inputs["positive"][0])
if isinstance(positive, str):
self._positive = positive
elif isinstance(positive, dict):
self._positive_sdxl.update(positive)
negative = self._comfy_traverse(prompt, inputs["negative"][0])
if isinstance(negative, str):
self._negative = negative
elif isinstance(negative, dict):
self._negative_sdxl.update(negative)
seed = None
# handle "CR Seed"
if inputs.get("seed") and isinstance(inputs.get("seed"), list):
seed = {"seed": self._comfy_traverse(prompt, inputs["seed"][0])}
elif inputs.get("noise_seed") and isinstance(
inputs.get("noise_seed"), list
):
seed = {
"noise_seed": self._comfy_traverse(
prompt, inputs["noise_seed"][0]
)
}
if seed:
flow.update(seed)
flow = utility.merge_dict(flow, last_flow1)
flow = utility.merge_dict(flow, last_flow2)
node += last_node1 + last_node2
except:
print("comfyUI KSampler error")
case node_type if node_type in CLIP_TEXT_ENCODE_TYPE:
try:
match node_type:
case "CLIPTextEncode":
# SDXLPromptStyler
if isinstance(inputs["text"], list):
text = int(inputs["text"][0])
prompt_styler = self._comfy_traverse(prompt, str(text))
self._positive = prompt_styler[0]
self._negative = prompt_styler[1]
return
elif isinstance(inputs["text"], str):
return inputs.get("text")
case "CLIPTextEncodeSDXL":
# SDXLPromptStyler
self._is_sdxl = True
if isinstance(inputs["text_g"], list):
text_g = int(inputs["text_g"][0])
text_l = int(inputs["text_l"][0])
prompt_styler_g = self._comfy_traverse(
prompt, str(text_g)
)
prompt_styler_l = self._comfy_traverse(
prompt, str(text_l)
)
self._positive_sdxl["Clip G"] = prompt_styler_g[0]
self._positive_sdxl["Clip L"] = prompt_styler_l[0]
self._negative_sdxl["Clip G"] = prompt_styler_g[1]
self._negative_sdxl["Clip L"] = prompt_styler_l[1]
return
elif isinstance(inputs["text_g"], str):
return {
"Clip G": inputs.get("text_g"),
"Clip L": inputs.get("text_l"),
}
case "CLIPTextEncodeSDXLRefiner":
self._is_sdxl = True
if isinstance(inputs["text"], list):
# SDXLPromptStyler
text = int(inputs["text"][0])
prompt_styler = self._comfy_traverse(prompt, str(text))
self._positive_sdxl["Refiner"] = prompt_styler[0]
self._negative_sdxl["Refiner"] = prompt_styler[1]
return
elif isinstance(inputs["text"], str):
return {"Refiner": inputs.get("text")}
except:
print("comfyUI CLIPText error")
case "LoraLoader":
try:
flow = inputs
last_flow, last_node = self._comfy_traverse(
prompt, inputs["model"][0]
)
flow = utility.merge_dict(flow, last_flow)
node += last_node
except:
print("comfyUI LoraLoader error")
case node_type if node_type in CHECKPOINT_LOADER_TYPE:
try:
return inputs, node
except:
print("comfyUI CheckpointLoader error")
case node_type if node_type in VAE_ENCODE_TYPE:
try:
last_flow, last_node = self._comfy_traverse(
prompt, inputs["pixels"][0]
)
flow = utility.merge_dict(flow, last_flow)
node += last_node
except:
print("comfyUI VAE error")
case "ControlNetApplyAdvanced":
try:
positive = self._comfy_traverse(prompt, inputs["positive"][0])
if isinstance(positive, str):
self._positive = positive
elif isinstance(positive, dict):
self._positive_sdxl.update(positive)
negative = self._comfy_traverse(prompt, inputs["negative"][0])
if isinstance(negative, str):
self._negative = negative
elif isinstance(negative, dict):
self._negative_sdxl.update(negative)
last_flow, last_node = self._comfy_traverse(
prompt, inputs["image"][0]
)
flow = utility.merge_dict(flow, last_flow)
node += last_node
except:
print("comfyUI ControlNetApply error")
case "ImageScale":
try:
flow = inputs
last_flow, last_node = self._comfy_traverse(
prompt, inputs["image"][0]
)
flow = utility.merge_dict(flow, last_flow)
node += last_node
except:
print("comfyUI ImageScale error")
case "UpscaleModelLoader":
try:
return {"upscaler": inputs["model_name"]}
except:
print("comfyUI UpscaleLoader error")
case "ImageUpscaleWithModel":
try:
flow = inputs
last_flow, last_node = self._comfy_traverse(
prompt, inputs["image"][0]
)
model = self._comfy_traverse(prompt, inputs["upscale_model"][0])
flow = utility.merge_dict(flow, last_flow)
flow = utility.merge_dict(flow, model)
node += last_node
except:
print("comfyUI UpscaleModel error")
case "ConditioningCombine":
try:
last_flow1, last_node1 = self._comfy_traverse(
prompt, inputs["conditioning_1"][0]
)
last_flow2, last_node2 = self._comfy_traverse(
prompt, inputs["conditioning_2"][0]
)
flow = utility.merge_dict(flow, last_flow1)
flow = utility.merge_dict(flow, last_flow2)
node += last_node1 + last_node2
except:
print("comfyUI ConditioningCombine error")
# custom nodes
case "SDXLPromptStyler":
try:
return inputs.get("text_positive"), inputs.get("text_negative")
except:
print("comfyUI SDXLPromptStyler error")
case "CR Seed":
try:
return inputs.get("seed")
except:
print("comfyUI CR Seed error")
case _:
try:
last_flow = {}
last_node = []
if inputs.get("samples"):
last_flow, last_node = self._comfy_traverse(
prompt, inputs["samples"][0]
)
elif inputs.get("image") and isinstance(inputs.get("image"), list):
last_flow, last_node = self._comfy_traverse(
prompt, inputs["image"][0]
)
elif inputs.get("model"):
last_flow, last_node = self._comfy_traverse(
prompt, inputs["model"][0]
)
elif inputs.get("clip"):
last_flow, last_node = self._comfy_traverse(
prompt, inputs["clip"][0]
)
elif inputs.get("samples_from"):
last_flow, last_node = self._comfy_traverse(
prompt, inputs["samples_from"][0]
)
elif inputs.get("conditioning"):
result = self._comfy_traverse(prompt, inputs["conditioning"][0])
if isinstance(result, str):
return result
elif isinstance(result, list):
last_flow, last_node = result
flow = utility.merge_dict(flow, last_flow)
node += last_node
except:
print("comfyUI bridging node error")
return flow, node
+9
View File
@@ -0,0 +1,9 @@
from ..exif.base_format import BaseFormat
class Primere(BaseFormat):
def __init__(self, info: dict = None, raw: str = ""):
super().__init__(info, raw)
self._pri_format()
def _pri_format(self):
self._parameter = self._info
+115
View File
@@ -0,0 +1,115 @@
import hashlib
import difflib
import folder_paths
import comfy.samplers
import os
def get_model_hash(filename):
hash_sha256 = hashlib.sha256()
blksize = 1024 * 1024
with open(filename, "rb") as f:
for chunk in iter(lambda: f.read(blksize), b""):
hash_sha256.update(chunk)
return hash_sha256.hexdigest()[0:10]
def check_model_from_exif(model_hash_exif, model_name_exif, model_name, model_hash_check):
checkpointpaths = folder_paths.get_folder_paths("checkpoints")[0]
allcheckpoints = folder_paths.get_filename_list("checkpoints")
source_model_name = model_name_exif.split('_', 1)[-1]
cutoff_list = [1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1]
is_found = []
for trycut in cutoff_list:
is_found = difflib.get_close_matches(model_name_exif, allcheckpoints, cutoff=trycut)
if len(is_found) == 1:
break
if len(is_found) != 1:
for trycut in cutoff_list:
is_found = difflib.get_close_matches(source_model_name, allcheckpoints, cutoff=trycut)
if len(is_found) == 1:
break
if len(is_found) == 1:
valid_model = is_found[0]
model_full_path = checkpointpaths + os.sep + valid_model
if model_hash_check == True:
match_model_hash = get_model_hash(model_full_path)
if match_model_hash == model_hash_exif:
model_name = valid_model
else:
print(
'Model name:' + model_name_exif + ' not available by hashcheck, using system source: ' + model_name)
else:
model_name = valid_model
else:
print('Model name:' + model_name_exif + ' not available by diffcheck, using system source: ' + model_name)
return model_name
def change_exif_samplers(sampler_name_exif, comfy_schedulers):
lastchars = sampler_name_exif[-2:]
if lastchars == ' a':
sampler_name_exif = sampler_name_exif.rsplit(' a', 1)[0] + ' ancestral'
sampler_name_exif = sampler_name_exif.replace(' a ', ' ancestral ').replace(' ', '_').replace('++', 'pp').replace('dpm2', 'dpm_2').replace('unipc', 'uni_pc')
for comfy_scheduler in comfy_schedulers:
sampler_name_exif = sampler_name_exif.removesuffix(comfy_scheduler).removesuffix('_')
return sampler_name_exif
def check_sampler_from_exif(sampler_name_exif, sampler_name, scheduler_name):
comfy_samplers = comfy.samplers.KSampler.SAMPLERS
comfy_schedulers = comfy.samplers.KSampler.SCHEDULERS
sampler_name_exif_for_cutoff = change_exif_samplers(sampler_name_exif, comfy_schedulers)
is_found_sampler = []
is_found_scheduler = []
cutoff_list_samplers = [1, 0.9, 0.8, 0.7, 0.6]
for trycut in cutoff_list_samplers:
is_found_sampler = difflib.get_close_matches(sampler_name_exif_for_cutoff, comfy_samplers, cutoff=trycut)
if len(is_found_sampler) >= 1:
sampler_name = is_found_sampler[0]
if " " in sampler_name_exif:
if any((match := substring) in sampler_name_exif for substring in comfy_schedulers):
scheduler_name = match
else:
cutoff_list_schedulers = [0.7, 0.6, 0.5, 0.4]
for trycut in cutoff_list_schedulers:
is_found_scheduler = difflib.get_close_matches(sampler_name_exif, comfy_schedulers, cutoff=trycut)
if len(is_found_scheduler) >= 1:
scheduler_name = is_found_scheduler[0]
if sampler_name not in comfy_samplers:
sampler_name = comfy_samplers[0]
if scheduler_name not in comfy_schedulers:
scheduler_name = comfy_schedulers[0]
return {'sampler': sampler_name, 'scheduler': scheduler_name}
def check_vae_exif(vae_name_exif, vae_name):
comfy_vaes = folder_paths.get_filename_list("vae")
cutoff_list = [1, 0.9, 0.8, 0.7]
is_found = []
for trycut in cutoff_list:
is_found = difflib.get_close_matches(vae_name_exif, comfy_vaes, cutoff=trycut)
if len(is_found) == 1:
break
if len(is_found) == 1:
vae_name = is_found[0]
return vae_name
+66
View File
@@ -0,0 +1,66 @@
import json
import piexif
import pyexiv2
import piexif.helper
from PIL import Image
from .exif.automatic1111 import Automatic1111
from .exif.primere import Primere
from .exif.comfyui import ComfyUI
# OopCompanion:suppressRename
class ImageExifReader:
def __init__(self, file):
self._raw = ""
self._parser = {}
self._parameter = {}
self._tool = ""
self.read_data(file)
def read_data(self, file):
def is_json(jsoninput):
try:
json.loads(jsoninput)
except ValueError as e:
return False
return True
with Image.open(file) as f:
p2metadata = pyexiv2.Image(file)
is_primere = p2metadata.read_exif()
if 'Exif.Image.ImageDescription' in is_primere:
primere_exif_string = is_primere.get('Exif.Image.ImageDescription').strip()
if is_json(primere_exif_string) == True:
json_object = json.loads(primere_exif_string)
# keysList = {'positive', 'negative', 'positive_l', 'negative_l', 'positive_r', 'negative_r', 'seed', 'model_hash', 'model_name', 'sampler_name'}
# if not (keysList - json_object.keys()):
self._tool = "Primere"
self._parser = Primere(info=json_object)
else:
if f.format == "PNG":
if "parameters" in f.info:
print('A11')
self._tool = "Automatic1111"
self._parser = Automatic1111(info=f.info)
elif "prompt" in f.info:
print('Comfy')
self._tool = "ComfyUI"
self._parser = ComfyUI(info=f.info)
elif f.format == "JPEG" or f.format == "WEBP":
exif = piexif.load(f.info.get("exif")) or {}
self._raw = piexif.helper.UserComment.load(
exif.get("Exif").get(piexif.ExifIFD.UserComment)
)
if is_json(self._raw) != True:
self._tool = "Automatic1111"
self._parser = Automatic1111(raw=self._raw)
@property
def parser(self):
return self._parser
@property
def tool(self):
return self._tool
+148
View File
@@ -0,0 +1,148 @@
import torch
import torch.nn.functional as F
import torch.nn as nn
import torch.fft as fft
import random
from .latent_util import normalize
class PowerLawNoise(nn.Module):
def __init__(self, device='cpu'):
super(PowerLawNoise, self).__init__()
self.device = device
@staticmethod
def get_noise_types():
return ["white", "blue", "brownian_fractal", "violet"]
def get_generator(self, noise_type):
if noise_type in self.get_noise_types():
if noise_type == "white":
return self.white_noise
elif noise_type == "blue":
return self.blue_noise
elif noise_type == "violet":
return self.violet_noise
elif noise_type == "brownian_fractal":
return self.brownian_fractal_noise
else:
raise ValueError(f"`noise_type` is invalid. Valid types are {', '.join(self.get_noise_types())}")
def set_seed(self, seed):
if seed is not None:
torch.manual_seed(seed)
def white_noise(self, batch_size, width, height, scale, seed, alpha=0.0, **kwargs):
self.set_seed(seed)
scale = scale
noise_real = torch.randn((batch_size, 1, height, width), device=self.device)
noise_power_law = torch.sign(noise_real) * torch.abs(noise_real) ** alpha
noise_power_law *= scale
return noise_power_law.to(self.device)
def blue_noise(self, batch_size, width, height, scale, seed, alpha=2.0, **kwargs):
self.set_seed(seed)
noise = torch.randn(batch_size, 1, height, width, device=self.device)
freq_x = fft.fftfreq(width, 1.0)
freq_y = fft.fftfreq(height, 1.0)
Fx, Fy = torch.meshgrid(freq_x, freq_y, indexing="ij")
power = (Fx**2 + Fy**2)**(alpha / 2.0)
power[0, 0] = 1.0
power = power.unsqueeze(0).expand(batch_size, 1, width, height).permute(0, 1, 3, 2).to(device=self.device)
noise_fft = fft.fftn(noise)
power = power.to(noise_fft)
noise_fft = noise_fft / torch.sqrt(power)
noise_real = fft.ifftn(noise_fft).real
noise_real = noise_real - noise_real.min()
noise_real = noise_real / noise_real.max()
noise_real = noise_real * scale
return noise_real.to(self.device)
def violet_noise(self, batch_size, width, height, alpha=1.0, device='cpu', **kwargs):
white_noise = torch.randn((batch_size, 1, height, width), device=device)
violet_noise = torch.sign(white_noise) * torch.abs(white_noise) ** (alpha / 2.0)
violet_noise /= torch.max(torch.abs(violet_noise))
return violet_noise
def brownian_fractal_noise(self, batch_size, width, height, scale, seed, alpha=1.0, modulator=1.0, **kwargs):
def add_particles_to_grid(grid, particle_x, particle_y):
for x, y in zip(particle_x, particle_y):
grid[y, x] = 1
def move_particles(particle_x, particle_y):
dx = torch.randint(-1, 2, (batch_size, n_particles), device=self.device)
dy = torch.randint(-1, 2, (batch_size, n_particles), device=self.device)
particle_x = torch.clamp(particle_x + dx, 0, width - 1)
particle_y = torch.clamp(particle_y + dy, 0, height - 1)
return particle_x, particle_y
self.set_seed(seed)
n_iterations = int(5000 * modulator)
fy = fft.fftfreq(height).unsqueeze(1) ** 2
fx = fft.fftfreq(width) ** 2
f = fy + fx
power = torch.sqrt(f) ** alpha
power[0, 0] = 1.0
grid = torch.zeros(height, width, dtype=torch.uint8, device=self.device)
n_particles = n_iterations // 10
particle_x = torch.randint(0, int(width), (batch_size, n_particles), device=self.device)
particle_y = torch.randint(0, int(height), (batch_size, n_particles), device=self.device)
neighborhood = torch.tensor([[1, 1, 1],
[1, 0, 1],
[1, 1, 1]], dtype=torch.uint8, device=self.device)
for _ in range(n_iterations):
add_particles_to_grid(grid, particle_x, particle_y)
particle_x, particle_y = move_particles(particle_x, particle_y)
brownian_tree = grid.clone().detach().float().to(self.device)
brownian_tree = brownian_tree / brownian_tree.max()
brownian_tree = F.interpolate(brownian_tree.unsqueeze(0).unsqueeze(0), size=(height, width), mode='bilinear', align_corners=False)
brownian_tree = brownian_tree.squeeze(0).squeeze(0)
fy = fft.fftfreq(height).unsqueeze(1) ** 2
fx = fft.fftfreq(width) ** 2
f = fy + fx
power = torch.sqrt(f) ** alpha
power[0, 0] = 1.0
noise_real = brownian_tree * scale
amplitude = 1.0 / (scale ** (alpha / 2.0))
noise_real *= amplitude
noise_fft = fft.fftn(noise_real.to(self.device))
noise_fft = noise_fft / power.to(self.device)
noise_real = fft.ifftn(noise_fft).real
noise_real *= scale
return noise_real.unsqueeze(0).unsqueeze(0)
def forward(self, batch_size, width, height, alpha=2.0, scale=1.0, modulator=1.0, noise_type="white", seed=None):
if noise_type not in self.get_noise_types():
raise ValueError(f"`noise_type` is invalid. Valid types are {', '.join(self.get_noise_types())}")
if seed is None:
seed = torch.randint(0, 2**32 - 1, (1,)).item()
channels = []
for i in range(3):
gen_seed = seed + i
random.seed(gen_seed)
noise = normalize(self.get_generator(noise_type)(batch_size, width, height, scale=scale, seed=gen_seed, alpha=alpha, modulator=modulator))
channels.append(noise)
noise_image = torch.cat((channels[0], channels[1], channels[2]), dim=1)
noise_image = (noise_image - noise_image.min()) / (noise_image.max() - noise_image.min())
noise_image = noise_image.permute(0, 2, 3, 1).float()
return noise_image.to(device="cpu")
+12
View File
@@ -0,0 +1,12 @@
def normalize(latent, target_min=None, target_max=None):
min_val = latent.min()
max_val = latent.max()
if target_min is None:
target_min = min_val
if target_max is None:
target_max = max_val
normalized = (latent - min_val) / (max_val - min_val)
scaled = normalized * (target_max - target_min) + target_min
return scaled
+212
View File
@@ -0,0 +1,212 @@
# Primere nodes for ComfyUI
## Do it before first run, or the workflow will be failed in your environment:
1; Install missing Python libraries if not start for first try. Activate Comfy venv and use 'pip install -r requirements.txt' at the root folder of Primere nodes (or check error messages and install missing libs manually)
2; If started, use the last workflow on the 'Workflow' folder for first try, all nodes visible under the 'Primere Nodes' submenu if you need custom workflow later. If some other nodes missing and red in workflow, download or delete unloaded nodes.
3; Set the right path for image saving in the node 'Primere Image Meta Saver' on 'output_path' input
4; Rename 'styles.example.csv' on the 'stylecsv' folder to 'syles.csv' or copy here your own A1111 style .csv file if you want to use 'Primere Styles' node. If you keep the renamed 'styles.example.csv', you will see image previews for 4 example prompts included.
5; **Set all selectors from your own environment.** Checkpoint, Lora, Embedding and Hypernetwork selectors will be failed if not choose right values from your own environment.
6; Choose image from your machine to the 'Primere Exif Reader'.
7; If the workflow failed, read the message in terminal.
8; Update your Comfy to lates version, I always do it before development, so my nodes compatible with lates Comfy version.
9; I develop my nodes and workflow continously, so do git pull once a week.
## Special features:
- Automatically detect if SD or SDXL checkpoint loaded, and control the whole process (e.g. resolution) by the result
- No need to switch nodes or workflow between SD and SDXL mode
- You can select model, subpath and orientation under the prompt input overwrite the system settings, same settings under the Styles loader node
- You can randomize the orientation if using batch mode
- One button LCM mode (see example workflow)
- Save .json and/or .txt file with process details, but these details saved to image as EXIF
- Read original A1111 style.csv file, handle dynamic prompts, example csv included
- Random noise generator for latent image
- Important and easy editable styles included in the text encoder as list
- Resolution selector by side ratios only, editable ratio source in external file, and auto detect checkpoint version for right final size
- Image size can be convert to "standard" values, fully customizable side ratios at the bottom of the resolution selector node
- Original image size multiplied to upscaler by two several ratios, one for SD and another one for SDXL models
- Remove previously included networks from prompts (Embedding, Lora, and Hypernetwork), use it if the used model incompatible with them, or if you want to try your prompt without included additional networks, or different networks
- Embedding handler for A1111 compatible prompts (or .csv styles), this node convert A1111 Embeddings to ComfyUI
- Use more than one prompt or style inputs for testing, and select any by 'Prompt Switch' node
- Special image meta/EXIF reader, which handle model name and samplers from A1111 .png or .jpg, never was easier to recycle your older A1111 or Comfy images using same or several settings, with switches you can change the original seed/model/size/etc... to workflow settings
- Check/debug generation details
- (As I see, Comfy doesn't handle SD2.x checkpoints, always geting black image, but this is not my feature :-) )
# Nodes in the pack by submenus:
## Inputs:
### Primere Prompt:
2 input fileds within one node for positive and negative prompts. 3 additional fields appear under the text inputs:
- **Subpath**: the prefered subpath for final image saving. This can be use for example the subject of the generated image, like 'sci-fi' 'art' or 'interior'.
- **Use model**: the prefered checkpoint for image rendering. If your prompt need special checkpoint, for example because product design or architechture, here you can force apply this model to the prompt rendering process.
- **Use orientation**: if you prefer vertical or horizontal orientation depending on your prompt, your rendering process will be use this setting instead of global setting from 'Primere Resolution' node. Useful for example for portraits, what usually better in vertical orientation. Random settings available here, use with batch mode if you need several orientations for same prompt.
If you set these fields, (where 'None' mean not set and use system settings) the workflow will use all of these settings for rendering your prompt instead of settings in 'Dashboard' group.
### Primere Styles:
Style (.csv) file reader, compatible with A1111 syle.csv, but little more than the original concept. The file must be copied/symlinked to the 'stylecsv' folder. Rename included 'style.example.csv' to 'style.csv' for first working example, and later edit this file manually.
- **A1111 compatible CSV headers required for this file**: 'name,prompt,negative_prompt'. But this version have more 3 required headers: 'prefered_subpath,prefered_model,prefered_orientation'. These new headers working like additional fields in the simple prompt input.
- If you fill these 3 optional columns in the style.csv, the rendering process will use them. **These last 3 fields are optional**, if you leave empty the style will be rendering with system 'dashboard' settings, if fill and enable to use at the bottom switches of node, dashboard settings will be overwritten.
- You can enable/disable these additional settings by switches if already entered to csv but want to use system settings instead, no need to delete if you failed or want to try with dashboard settings.
### Primere Dynamic:
- This node render A1111 compatible dynamic prompts, including external wildcard files of A1111 dynamic prompt plugin. External files must be copied/symlinked to the 'wildcards' folder and use the '__filepath/of/file__' keyword within your prompt. Use this to decode all style.csv and double prompt inputs, because the output of prompt/style nodes not resolved by other comfy dynamic decoder/resolver.
- Check the included workflow how to use this node.
### Primere exif reader:
- This node read prompt-exif (called meta) from loaded image. Compatible with A1111 jpg and png, and usually with ComfyUI, but not with all workflows.
- This is very important (the most important) node in the example workflow, it has a central settings distribution role, not just read the exif data.
- The reader is tested with A1111 'jpg' and 'png' and Comfy 'jpg' and 'png'. Another exif parsers will be included soon, but if you send me AI generated image contains metadata what failed to read, I will do parser/debug for that.
This node output sending lot of data to the workflow from exif/meta or pnginfo if it's included to selected image, like model name, vae and sampler. Use this node to distribute settings, and simple off the 'use_exif' switch if you don't want to render image by this node, then you can use your own prompts and dashboard settings.
**Use several settings of switches what exif/meta data you want/don't want to use for image rendering.** If switch off something, dashboard settings (this is why must be connected this node input) will be used instead of image exif/meta.
#### For this node inputs connect all of your dashboard settings, like in the example workflow. If you switch off the exif reader with 'use_exif' switch, or ignore specified data for example the model, the input values will be used instead of image meta. The example workflow help to analize how to use this node.
### Primere Embedding Handler:
This node convert A1111 embeddings to Comfy embeddings. Use after dynamically decoded prompts (booth text and style). **No need to modify manually styles.csv from A1111 if you use this node.**
### Primere Lora Stack Merger:
This node merge two different Lora stacks, SD and SDXL. The output is useful to store Lora settings to the image meta.
### Primere Lora Keyword Merger:
With Lora stackers you can read model keywords. This node merge all selected Lora keywords to one string, and send to prompt encoder.
### Primere Embedding Keyword Merger:
This node merge positive and negative SD and SDXL embedding tags, to send them to the prompt encoder.
## Dashboard:
### Primere Sampler Selector:
Select sampler and scheduler in separated node, and wire outputs to the sampler (through exif reader input in the example workflow). This is very useful to separate from other non-setting nodes, and for LCM mode you need two several sampler settings. (see the example workflow, and try to undestand LCM setting)
### Primere Steps & Cfg:
Use this separated node for sampler/meta reader inputs. If you use LCM mode, you need 2 settings of this node. See and test the attached example workflow.
### Primere LCM Selector:
Use this node to switch on/off LCM mode in whole rendering process. Wire two sampler and cfg/steps setting to the inputs (one of them must be compatible with LCM settings), and connect this node output to the sampler/exif reader, like in the example workflow. The 'IS_LCM' output important for CKPT loader and the Exif reader for correct rendering.
### Primere VAE Selector:
This node is a simple VAE selector. Use 2 nodes in workflow, 1 for SD, 1 for SDXL compatible VAE for autimatized selection. The checkpoint selector and loader get the loaded checkpoint version.
### Primere CKPT Selector:
Simple checkpoint selector, but with extras:
- This node automatically detect if the selected model SD or SDXL. Use this output for automatic VAE or size selection and for prompt encoding, see example workflow for details. In Comfy SD2.x checkpoints not working well, use only SD1.x and SDXL.
- Check the "visual" version of this node, if you have previews for checkpoints, easier to select the best for your prompt. How to create preview for visual selection, read more this file.
### Primere VAE loader:
Use this node to convert VAE name to VAE.
### Primere CKPT Loader:
Use this node to convert checkpoint name to 'MODEL', 'CLIP' and 'VAE'. Use 'is_lcm' input for detect LCM mode, see the example workflow.
If you have downloaded .yaml file, and copied to the checkpoint directory with same filename, set use_yaml to true, and the loader will use your config file. No need to swithc off if .yaml file missing. If you find some problem or error, simply set it to false.
Play with 'strength_lcm_model' and 'strength_lcm_clip' values if set LCM mode on.
### Primere Prompt Switch:
Use this node if you have more than one prompt input (for example several half-ready test prompts). Connect prompt/style node outputs to this node inputs and set the right index at the bottom. To connect 'subpath', 'model', and 'orientation' inputs are optional, only the positive and negative prompt required.
**Very important:** don't remove the connected node from the middle or from the top of inputs. Connect nodes in right queue, and disconnect them only from the last to first. If you getting js error becuase disconnected inputs in wrong gueue, just reload your browser and use 'reload node' menu with right click on node.
### Primere Seed:
Use only one seed input for all. A1111 look node, connect this one node to all other seed inputs.
### Primere Noise Latent
This node generate 'empty' latent image, but with several noise settings. **You can randomize these setting between min. and max. values using switches**, this cause small difference between generated images for same seed and settings, but you can freeze your noise and image if you disable variations of random noise generation.
### Primere Prompt Encoder:
- This node compatible booth SD and SDXL models, important to use 'model_version' input for correct working. Try several settings, you will get several results.
- Use included positive and negative styles, and check the best result in prompt and image outputs.
- If you getting error if use SD basemodel, you must update (git pull) your ComfyUI.
- The style source of this node is external file at 'Toml/default_neg.toml' and 'Toml/default_pos.toml' files, what you can edit if you need changes.
- Comfy internal encoders not compatible with SD2.x version, you will get black image if select this SD2.x checkpoint version from model selector.
### Primere Resolution:
- Select image size by side ratios only, and use 'model_version' input for correct SD or SDXL size on the output.
- You can calculate image size by really custom ratios at the bottom float inputs (and set switch on), or just edit the ratio source file.
- The ratios of this node stored in external file at 'Toml/resolution_ratios.toml', what you can edit if you need changes.
- Use 'round_to_standard' switch if you want to modify the exactly calculated size to the 'officially' recommended SD / SDXL values. This is usually very small modification.
- Not sure what orientation the best for your prompt and want to test in batch image generation? Just set batch value on the Comfy menu and switch 'rnd_orientation' to randomize vertical and horizontal images.
- Set the base model (SD1.x not SDXL) resolution to 512, 768, 1024, or 1280. The official setting is 512, but I like 768 instead.
### Primere Resolution Multiplier:
Multiply the base image size for upscaling. Important to use 'model_version' if you want to use several multipliers for SD and SDXL models. Just switch off 'use_multiplier' on this node if you don't need to resize original image.
### Primere Prompt Cleaner:
This node remove Lora, Hypernetwork and Embedding (booth A1111 and Comfy) from the prompt and style inputs. Use switches what netowok(s) you want to remove or keep in the final prompt. Use 'remove_only_if_sdxl' if you want keep all of these networks for all SD models, and remove only if SDXL checkpoint selected.
**Important notice:** for loras and hypernetworks you don't need original tags in the prompt (for example: \<lora:your_lora_name>). If you keep original lora and hypernetwork tags you cant sure your image result use the lora only, or use the tag string in the prompt. I recommend always to remove lora and hypernetwork tags, but you can try what happan if keep.
The another thing, that you must remove original tags after 'Primere Network Tag Loader', because after prompt cleaner non tags for tag loader.
### Primere Network Tag Loader
This node loads addtional networks (Lora and Hypernetwork) to the CLIP and MODEL. You can read and use Lora keywords to send to prompt encoder or the keyword merger like in the example workflow.
### Primere Model Keyword
This node loads model keyword. You can read and use model keywords to send directly to prompt encoder like in the example workflow.
## Outputs:
### Primere Meta Saver:
This node save the image, but with/without metadata, and save meta to .json file if you want. Wire metadata from the Exif reader node only, and use optional 'prefered_subpath' input if you want to overwrite the node settings by several prompt input nodes. Set 'output_path' input correctly, depending your system.
### Primere Any Debug:
Use this node to display 'any' output values of several nodes like prompts or metadata (**metadata is formatted**). See the example workflow for details.
### Primere Text Output
Use this node to diaplay text.
## Styles:
### Primere Style Pile:
Style collection for generated images. Set and connect this node to the 'Prompt Encoder'. No forget to set and play with style strenght. The source of this node is external file at 'Toml/stylepile.toml', what you can edit if you need changes.
## Networks:
### Primere LORA
Lora stack for 6 loras. Important to use 'stack_version' list. Here you can select how you want to load selected Lora-s, for SD models only, for SDXL models only, or for booth (Any) what not recommended. Use 2 separated Lora stack for SD/SDXL checkpoints, and wire 'model_version' input for correct use.
- You can switch on/off loras, no need to choose 'None' from the list.
- If you use 'use_only_model_weight', the model_weight input values will be copied to clip_weight.
- If you switch off 'use_only_model_weight', you can set model_weight and clip_weight to several values.
- You can load and send to Prompt Encoder the Lora keyword if available. This is similar but not exactly same function that "Model Keyword" plugin in the A1111
- You can choose Lora keyword placement, which and how many keywords select if more than one available, how many keyword use of more than one available, and select in queue or random, and set the keyword weight in the prompt.
- Lora keyword is much better than to keep lora tag in the prompt.
### Primere Embedding
Select textual inversion called Embedding for your prompt. You have to use 2 several versions of this one, one for SD, and another one for SDXL checkpoints. Important to use 'model_version' input and 'stack_version' list, working similar than in the Lora stack.
You can choose embedding placement in the prompt.
### Primere Hypernetwork
Use hypernetwork if you already have by this node. **Hypernetwork is harmful, because can run any code on your computer, so ignore/delete this node or download them from reliable source only**
Hypernetworks don't need seperated SD and SDXL sources, use only one stack for all, and set 'stack_version' to 'Any'.
## Visuals:
Here are same functions like upper, but the selection (for example checkpoints, loras, embeddings, styles from style.csv and hypernetworks) **possible by image previews on modal**. Very similar than in several themes of A1111.
You must save images as preview to the right path and name, deails later. Preview can be **only .jpg** format with only .jpg extension.
### Primere Visual CKPT selector:
**Visual selector for checkpoints**. You must copy your original checkpoint subdirs to ComfyUI\custom_nodes\ComfyUI_Primere_Nodes\front_end\images\checkpoints\ path but only the preview images needed, same name as the checkpoint but with .jpg only extension.
As extra features you can enable/disable modal with 'show_modal' switch, and exclude files and paths from modal starts with . (point) character if show_hidden switch is off.
### Primere Visual Lora selector:
Same as than the 'Primere LORA' node, but with preview images of selection modal.
You must copy your original lora subdirs to ComfyUI\custom_nodes\ComfyUI_Primere_Nodes\front_end\images\loras\ path but only the preview images needed, same name as the checkpoint but with .jpg only extension.
### Primere Visual Embedding selector:
Same as than the 'Primere Embedding' node, but with preview images of selection modal.
You must copy your original embedding subdirs to ComfyUI\custom_nodes\ComfyUI_Primere_Nodes\front_end\images\embeddings\ path but only the preview images needed, same name as the embedding file but with .jpg only extension.
### Primere Visual Hypernetwork selector:
Same as than the 'Primere Hypernetwork' node, but with preview images of selection modal.
You must copy your original hypernetwork subdirs to ComfyUI\custom_nodes\ComfyUI_Primere_Nodes\front_end\images\hypernetworks\ path but only the preview images needed, same name as the hypernetwork file but with .jpg only extension.
### Primere Visual Style selector:
Same as than the 'Primere Styles' node, but with preview images of selection modal.
You must create .jpg images as preview with same name as the style name in the list, but **space characters must be changed to _.** For example if your style in the list is 'Architechture Exterior', you must save Architechture_Exterior.jpg to the path: ComfyUI\custom_nodes\ComfyUI_Primere_Nodes\front_end\images\styles\
Example style.csv included, if rename you will see 4 example previews.
# Contact:
#### Discord name: primere -> ask email if you need
# Licence:
#### Use these nodes for your own risk
+36
View File
@@ -0,0 +1,36 @@
[SHORT]
positive=''
negative='worst quality, low quality, lowres, low res, bad anatomy, bad hands, missing hands, missing fingers, cropped, blurry, heavily cropped, watermark, text,'
[LOWTOKEN]
positive=''
negative='lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry,'
[LONG]
positive=''
negative='bad anatomy, bad proportions, blurry, cloned face, cropped, deformed, dehydrated, disfigured, duplicate, error, extra arms, extra fingers, extra legs, extra limbs, fused fingers, gross proportions, jpeg artifacts, long neck, low quality, lowres, malformed limbs, missing arms, missing legs, morbid, mutated hands, mutation, mutilated, out of frame, poorly drawn face, poorly drawn hands, signature, text, too many fingers, ugly, username, watermark, worst quality,'
[LONG_SFW]
positive=''
negative='NSFW, add_nsfw, Cleavage, Pubic Hair, Nudity, Naked, Au naturel, Watermark, Text, censored, deformed, bad anatomy, disfigured, poorly drawn face, mutated, extra limb, ugly, poorly drawn hands, missing limb, floating limbs, disconnected limbs, disconnected head, malformed hands, long neck, mutated hands and fingers, bad hands, missing fingers, cropped, worst quality, low quality, mutation, poorly drawn, huge calf, bad hands, fused hand, missing hand, disappearing arms, disappearing thigh, disappearing calf, disappearing legs, missing fingers, fused fingers, abnormal eye proportion, Abnormal hands, abnormal legs, abnormal feet, abnormal fingers,'
[BETTER_IMAGES]
positive=''
negative='Amputee, Autograph, Bad anatomy, Bad illustration, Bad proportions, Beyond the borders, Blank background, Blurry, Body out of frame, Boring background, Branding, Cropped, Cut off, Deformed, Disfigured, Dismembered, Disproportioned, Distorted, Draft, Duplicate, Duplicated features, Extra arms, Extra fingers, Extra hands, Extra legs, Extra limbs, Fault, Flaw, Fused fingers, Grains, Grainy, Gross proportions, Hazy, Identifying mark, Improper scale, Incorrect physiology, Incorrect ratio, Indistinct, Kitsch, Logo, Long neck, Low quality, Low resolution, Macabre, Malformed, Mark, Misshapen, Missing arms, Missing fingers, Missing hands, Missing legs, Mistake, Morbid, Mutated hands, Mutation, Mutilated, Off-screen, Out of frame, Outside the picture, Pixelated, Poorly drawn face, Poorly drawn feet, Poorly drawn hands, Printed words, Render, Repellent, Replicate, Reproduce, Revolting dimensions, Script, Shortened, Sign, Signature, Split image, Squint, Storyboard, Text, Tiling, Trimmed, Ugly, Unfocused, Unattractive, Unnatural pose, Unreal engine, Unsightly, Watermark, Written language,'
[LANDSCAPES]
positive=''
negative='Blurry, Boring, Close-up, Dark (optional), Details are low, Distorted details, Eerie, Foggy (optional), Gloomy (optional), Grains, Grainy, Grayscale (optional), Homogenous, Low contrast, Low quality, Lowres, Macro, Monochrome (optional), Multiple angles, Multiple views, Opaque, Overexposed, Oversaturated, Plain, Plain background, Portrait, Simple background, Standard, Surreal, Unattractive, Uncreative, Underexposed,'
[CITYSCAPES]
positive=''
negative='Animals (optional), Asymmetrical buildings, Blurry, Cars (optional), Close-up, Creepy, Deformed structures, Grainy, Jpeg artifacts, Low contrast, Low quality, Lowres, Macro, Multiple angles, Multiple views, Overexposed, Oversaturated, People (optional), Pets (optional), Plain background, Scary, Solid background, Surreal, Underexposed, Unreal architecture, Unreal sky, Weird colors,'
[PORTRAITS_PETS]
positive=''
negative='3D, Absent limbs, Additional appendages, Additional digits, Additional limbs, Altered appendages, Amputee, Asymmetric, Asymmetric ears, Bad anatomy, Bad ears, Bad eyes, Bad face, Bad proportions, Beard (optional), Broken finger, Broken hand, Broken leg, Broken wrist, Cartoon, Childish (optional), Cloned face, Cloned head, Collapsed eyeshadow, Combined appendages, Conjoined, Copied visage, Corpse, Cripple, Cropped head, Cross-eyed, Depressed, Desiccated, Disconnected limb, Disfigured, Dismembered, Disproportionate, Double face, Duplicated features, Eerie, Elongated throat,'
[INANIMATE_OBJ]
positive=''
negative='absent, parts, added, components, asymmetrical, design, broken, cartoonish, cloned, collapsed, complex, background, distorted, distorted, perspective, extra, pieces, faded, color, flawed, shape, flipped, folded, improper, proportion, incomplete, incorrect, geometry, inverted, kitsch, low, quality, low, resolution, macabre, misaligned, parts, misshapen, missing, parts, mutated, off-center, out, of, focus, over-saturated, color, overexposed, oversized, poorly, rendered, replica, surreal, tilted, underexposed, unrealistic, upside, down,'
[NATURE_WILD]
positive=''
negative='abstract, amputated, animal, face, anime, artificial, asymmetrical, bad, anatomy, cartoon, cgi, cloned, collapsed, deformed, distorted, extra, limbs, fantasy, foggy, grainy, human, face, incomplete, low, quality, low, resolution, lowres, malformed, missing, parts, monochrome, mutated, over-saturated, color, overexposed, photoshopped, scary, silhouette, sketch, surreal, twisted, underexposed, unfocused, unreal, engine,'
[ABSTRACT_ART]
positive=''
negative='3d, render, anatomically, correct, animals, body, parts, buildings, cartoon, characters, cityscape, concrete, detailed, faces, figurative, human, figure, landscape, literal, low, resolution, lowres, monochrome, people, photorealistic, portrait, realistic, scenery, sharp, edges, sketch, symmetrical, text,'
[FOOD_DRINK]
positive=''
negative='asymmetrical, badly, cooked, black, and, white, blurry, burnt, cartoon, cgi, cold, dark, distorted, expired, grainy, human, parts, incomplete, low, resolution, lowres, moldy, mutated, overcooked, oversaturated, rotten, sculpture, sketch, soggy, sour, stale, undercooked, unfocused, unrealistic, upside, down,'
+30
View File
@@ -0,0 +1,30 @@
[GHIBLI]
positive='(Studio ghibli style, Art by Hayao Miyazaki:1.2), Anime Style, Manga Style, Hand drawn, cinematic sensual, Sharp focus, humorous illustration, big depth of field, Masterpiece, concept art, trending on artstation, Vivid colors, Simplified style, trending on ArtStation, trending on CGSociety, Intricate, Vibrant colors, Soft Shading, Simplistic Features, Sharp Angles, Playful,'
negative=''
[SKIN_ENHANCER]
positive='detailed skin texture, (blush:0.5), (goosebumps:0.5), subsurface scattering,'
negative=''
[SKIN_ENHANCER_CLEAN]
positive='detailed skin texture, (blush:0.2), (goosebumps:0.3), subsurface scattering,'
negative=''
[VECTOR_ART]
positive='Vector art, Vivid colors, Clean lines, Sharp edges, Minimalist, Precise geometry, Simplistic, Smooth curves, Bold outlines, Crisp shapes, Flat colors, Illustration art piece, High contrast shadows, Technical illustration, Graphic design, Vector graphics, High contrast, Precision artwork, Linear compositions, Scalable artwork, Digital art,'
negative=''
[DIGIT_OIL_PAINT]
positive='(Extremely Detailed Oil Painting:1.2), glow effects, godrays, Hand drawn, render, 8k, octane render, cinema 4d, blender, dark, atmospheric 4k ultra detailed, cinematic sensual, Sharp focus, humorous illustration, big depth of field, Masterpiece, colors, 3d octane render, 4k, concept art, trending on artstation, hyperrealistic, Vivid colors, extremely detailed CG unity 8k wallpaper, trending on ArtStation, trending on CGSociety, Intricate, High Detail, dramatic,'
negative=''
[INDIE_GAME]
positive='Indie game art,({prompt}), (Vector Art, Borderlands style, Arcane style, Cartoon style), Line art, Disctinct features, Hand drawn, Technical illustration, Graphic design, Vector graphics, High contrast, Precision artwork, Linear compositions, Scalable artwork, Digital art, cinematic sensual, Sharp focus, humorous illustration, big depth of field, Masterpiece, trending on artstation, Vivid colors, trending on ArtStation, trending on CGSociety, Intricate, Low Detail, dramatic,'
negative=''
[PHOTO]
positive='Photorealistic, Hyperrealistic, Hyperdetailed, analog style, hip cocked, demure, low cut, black lace, detailed skin, matte skin, soft lighting, subsurface scattering, realistic, heavy shadow, masterpiece, best quality, ultra realistic, 8k, golden ratio, Intricate, High Detail, film photography, soft focus,'
negative=''
[BW_FILM_NOIR]
positive='(b&w, Monochromatic, Film Photography:1.3), Photorealistic, Hyperrealistic, Hyperdetailed, film noir, analog style, hip cocked, demure, low cut, soft lighting, subsurface scattering, realistic, heavy shadow, masterpiece, best quality, ultra realistic, 8k, golden ratio, Intricate, High Detail, film photography, soft focus,'
negative=''
[MANGA]
positive='(Manga Style, Yusuke Murata, Satoshi Kon, Ken Sugimori, Hiromu Arakawa), Pencil drawing, (B&W:1.2), Low detail, sketch, concept art, Anime style, line art, webtoon, manhua, chalk, hand drawn, defined lines, simple shades, simplistic, manga page, minimalistic, High contrast, Precision artwork, Linear compositions, Scalable artwork, Digital art, High Contrast Shadows,'
negative=''
[ANIME]
positive='(Anime Scene, Toonshading, Satoshi Kon, Ken Sugimori, Hiromu Arakawa:1.2), (Anime Style, Manga Style:1.3), Low detail, sketch, concept art, line art, webtoon, manhua, hand drawn, defined lines, simple shades, minimalistic, High contrast, Linear compositions, Scalable artwork, Digital art, High Contrast Shadows, glow effects, humorous illustration, big depth of field, Masterpiece, colors, concept art, trending on artstation, Vivid colors, dramatic,'
negative=''
+52
View File
@@ -0,0 +1,52 @@
[RATIO_1_1]
name = "Square [1:1]"
side_x = 1
side_y = 1
[RATIO_19_13]
name = "Photo [19:13]"
side_x = 19
side_y = 13
[RATIO_9_7]
name = "Portrait [9:7]"
side_x = 9
side_y = 7
[RATIO_7_4]
name = "Wildscreen [7:4]"
side_x = 7
side_y = 4
[RATIO_12_5]
name = "Cinema [12:5]"
side_x = 12
side_y = 5
[RATIO_4_3]
name = "Old TV screen [4:3]"
side_x = 4
side_y = 3
[RATIO_16_9]
name = "HD screen [16:9]"
side_x = 16
side_y = 9
[RATIO_16_10]
name = "HD+ screen [16:10]"
side_x = 16
side_y = 10
[RATIO_2_1]
name = "Half side [2:1]"
side_x = 2
side_y = 1
[RATIO_9_8]
name = "Dual screen [9:8]"
side_x = 9
side_y = 8
[RATIO_17_9]
name = "DCI screen [17:9]"
side_x = 17
side_y = 9
[RATIO_21_9]
name = "G5 screen [21:9]"
side_x = 21
side_y = 9
[RATIO_32_9]
name = "G9 screen [32:9]"
side_x = 32
side_y = 9
+634
View File
@@ -0,0 +1,634 @@
[art-type.None]
positive = ''
negative = ''
[art-type.3d-rendering]
positive = 'Professional 3D rendering,CGSociety,ArtStation'
negative = '((Wireframe)),Polygons,Screenshot,Character design,Software,UI'
[art-type.digital-artwork]
positive = 'Digital Artwork,CGSociety,ArtStation'
negative = 'Scribbles,Low quality,Low rated,Mediocre,3D rendering,Screenshot,Software,UI'
[art-type.drawing]
positive = 'Drawing'
negative = 'Low quality,Photo,Artifacts,Table,Paper,Pencils,Pages,Wall'
[art-type.painting]
positive = 'Painting'
negative = 'Low quality,Bad composition,Faded,(Photo:1.5),(Frame:1.3)'
[art-type.photo]
positive = 'Photo,Highly Detailed'
negative = 'Low rated,Phone,Wedding,Frame,Painting,tumblr'
[art-type.vector-art]
positive = 'Vector art'
negative = '(Watermark:1.5),(Text:1.3)'
[concepts]
concepts = [
"Acclaimed",
"Alternative",
"Amateur",
"Artificial",
"Award Winning",
"Basic",
"Beginner",
"Bipolar",
"Boyish",
"Childish",
"Cinematic",
"Clever",
"Clumsy",
"Cognitive",
"Complex",
"Compressed",
"Controllable",
"Corrupted",
"Damaged",
"Destroyed",
"Disgusting",
"Divisive",
"Dramatic",
"Dumb",
"Eliminated",
"Excessive",
"Exciting",
"Extreme",
"Feminine",
"Filtered",
"Fixated",
"Fixed",
"Foolish",
"Fragile",
"Girlish",
"Gorgeous",
"Groundbreaking",
"Hated",
"Hidden",
"Highly Rated",
"Horrifying",
"Imaginary",
"Imaginative",
"Imitated",
"Jaded",
"Light hearted",
"Loved",
"Low Rated",
"Magical",
"Masculine",
"Masterful",
"Masterpiece",
"Maximalist",
"Methodological",
"Misunderstood",
"Mundane",
"Overprocessed",
"Pathetic",
"Photoshopped",
"Preview",
"Raw",
"Recycled",
"Religious",
"Rough",
"Sacrificial",
"Sacrilegious",
"Schematic",
"Simple",
"Sophisticated",
"Stupid",
"Trustworthy",
"Unbelievable",
"Understandable",
"Unearthed",
"Unfiltered",
"Unfinished",
"Unhinged",
"Universal",
"Unsuccessful",
"Venerable",
"Visionary",
"Vivacious"
]
[artists]
artists = [
"Adam Hughes",
"Adi Granov",
"Adolf Kosarek",
"Adolph Von Menzel",
"Akihiko Yoshida",
"Al Williamson",
"Albert Lynch",
"Alberto Seveso",
"Alberto Vargas",
"Alena Aenami",
"Alex Andreev",
"Alex Grey",
"Alex Ross",
"Alex Toth",
"Alexander Archipenko",
"Alexander Jansson",
"Alfred Steiglitz",
"Alphonse Mucha",
"Alvar Aalto",
"Anato Finnstark",
"Andre Masson",
"Andrew Loomis",
"Andy Fairhurst",
"Anna Dittman",
"Apollonia Saintclair",
"Artgerm",
"Arthur Adams",
"Arthur Rackham",
"Aubrey Beardsley",
"Austin Briggs",
"Ayami Kojima",
"Barbara Kruger",
"Bastien Lecouffe Deharme",
"Beeple",
"Bill Sienkiewicz",
"Bill Ward",
"Bo Bartlett",
"Bob Byerley",
"Bob Eggleton",
"Bob Haberfield",
"Bob Peak",
"Boris Vallejo",
"Brandon Woelfel",
"Brian Bolland",
"Brian Froud",
"Bruce Pennington",
"Bryan Hitch",
"Butcher Billy",
"Camille Walala",
"Carel Willink",
"Carmine Infantino",
"Carrie Ann Baade",
"Casey Baugh",
"Casey Weldon",
"Cedric Peyravernay",
"Charles Adams",
"Charlie Bowater",
"Chesley Bonestell",
"Chris Foss",
"Christopher Balaskas",
"Claude Monet",
"Clive Barker",
"Coles Phillips",
"Conrad Roset",
"Curt Swan",
"Dan Mumford",
"Diego Rivera",
"Don Bergland",
"Donato Giancola",
"Dorina Costras",
"E.H. Shepard",
"Earl Norem",
"Earle Bergey",
"Earnst Haeckel",
"Ed Emshwiller",
"Ed Mell",
"Edith Head",
"Edmund Dulac",
"Edvard Munch",
"Ellen Jewett",
"Emily Balivet",
"Enki Bilal",
"Eric Kennington",
"Erin Hanson",
"Ernie Barnes",
"Esao Andrews",
"Esteban Maroto",
"Ethan Van Sciver",
"Eve Ventrue",
"Eyvind Earle",
"F. Scott Hess",
"Fernand Khnopff",
"Filippino Lippi",
"Frank Bowling",
"Frank Cadogan Cowper",
"Frank Frazetta",
"Frank Tenney Johnson",
"Frank Xavier",
"Franklin Booth",
"Fred Calleri",
"Fujishima Takeji",
"Gabriel Von Max",
"Gediminas Pranckevicius",
"Gene Colan",
"Geof Darrow",
"Georgia O’Keeffe",
"Georgy Kurasov",
"Gerald Brom",
"Gertrude Abercrombie",
"Gil Elvgren",
"Gil Kane",
"Greg Manchess",
"Greg Rutkowski",
"Gustaf Tenggren",
"Gustav Klimt",
"H.P. Lovecraft",
"H.R. Giger",
"Hannah Yata",
"Harrison Fisher",
"Harry Clarke",
"Henri Matisse",
"Henry Clive",
"Herbert James Gunn",
"Hikari Shimoda",
"Hiroshi Nagai",
"Hiroshi Yoshida",
"Hsiao-Ron Cheng",
"Huang Guangjian",
"Ian Kennedy",
"Igor Morski",
"Igor Zenin",
"Ilya Kuvshinov",
"Ilya Repin",
"Ivan Aivazovsky",
"Ivan Bilibin",
"J.C. Leyendecker",
"Jacek Yerka",
"Jack Kirby",
"Jackson Pollock",
"James C. Christensen",
"James Gilleard",
"James Gurney",
"James Jean",
"Jan Hendrik Weissenbruch",
"Jan Urschel",
"Jasmine Becket-Griffith",
"Jason Edmiston",
"Jay Anacleto",
"Jean Giraud",
"Jeannette Guichard-Bunel",
"Jeffrey Smith",
"Jeremiah Ketner",
"Jeremy Lipking",
"Jian Chong Min",
"Jim Burns",
"Jim Holland",
"Joao Ruas",
"Joe Jusko",
"Joe Kubert",
"Johan Heinrich Fussli",
"John Howe",
"John Lavery",
"John Philip Falter",
"John Romita Jr",
"John Singer Sargent",
"John T. Biggers",
"Jon Whitcomb",
"Joop Polder",
"Joseph Leyendecker",
"Juan Gris",
"Julian Onderdonk",
"Junji Ito",
"Kadir Nelson",
"Karel Thole",
"Karol Bak",
"Kawase Hasui",
"Kaws",
"Kehinde Wiley",
"Kelly McKernan",
"Koho Shoda",
"Krenz Cushart",
"Lee Bogle",
"Leonardo Coccorante",
"Leonid Afremov",
"Lisa Frank",
"Loish",
"Lyubov Popova",
"M.C. Escher",
"Makoto Shinkai",
"Marc Chagall",
"Marc Simonetti",
"Mark Ryden",
"Martin Ansin",
"Martin Schongauer",
"Mary Jane Ansell",
"Masamune Shirow",
"Mati Klarwein",
"Maxfield Parrish",
"Mead Schaeffer",
"Michael Cheval",
"Michael Whelan",
"Miho Hirano",
"Mike Allred",
"Mike Mignola",
"Mike Winkelmann",
"Miles Aldridge",
"Milton Caniff",
"Moebius",
"Mort Kunstler",
"Neal Adams",
"Nikolai Astrup",
"Njideka Akunyili Crosby",
"Norman Rockwell",
"P.A. Works",
"Pang Xunqin",
"Paul Cadmus",
"Paul Lehr",
"Paul Signac",
"Peter Elson",
"Peter Gric",
"Peter Mohrbacher",
"Peter Wileman",
"Petros Afshar",
"Phil Noto",
"Philippe Druillet",
"Rafael Albuquerque",
"Ralph Gibson",
"Raymond Swanland",
"RHADS",
"Richard Avedon",
"Richard Corben",
"Richard Lindner",
"Rob Gonsalves",
"Robert Bissell",
"Robert McCall",
"Roberto Matta",
"Rolf Armstrong",
"Romero Britto",
"Ron Miller",
"Ross Tran",
"RossDraws",
"Roy Lichtenstein",
"Ruan Jia",
"Ryan Pancoast",
"Ryohei Hase",
"Sabbas Apterus",
"Sachin Teng",
"Salvador Dali",
"Sam bosma",
"Sam Gilliam",
"Scott Listfield",
"Shigenori Soejima",
"Shinji Aramaki",
"Simon Bisley",
"Simon Stalenhag",
"Siya Oum",
"Stanhope Forbes",
"Stanislaw Wyspianski",
"Stephan Martinière",
"Steve Ditko",
"Syd Mead",
"Takashi Murakami",
"Tara McPherson",
"Tarsila do Amaral",
"Ted Nasmith",
"Theo Van Rysselberghe",
"Thomas Blackshear",
"Thomas Kinkade",
"Thomas Shotter Boys",
"Todd McFarlane",
"Tom Bagshaw",
"Tom Lovell",
"Tom Whalen",
"Tomer Hanuka",
"Trevor Brown",
"Trina Robbins",
"Tsutomu Nihei",
"Ulisse Aldrovandi",
"Umberto Boccioni",
"Vasily Vereschagin",
"Victo Ngai",
"Victor Nizovtsev",
"Vincent DiFate",
"Vittorio Reggianini",
"W. Heath Robinson",
"Wadim Kashin",
"Walter Crane",
"Wangechi Mutu",
"Warwick Goble",
"Wayne Barlowe",
"Will Barnet",
"William Dodge",
"William Eggleston",
"William Holbrook Beard",
"William McGregor Paxton",
"WLOP",
"Yanjun Cheng",
"Yoji Shinkawa",
"Yoshitaka Amano",
"Zdzislaw Beksinski"
]
[art-movements]
art-movements = [
"50s Art",
"60s Art",
"70s Art",
"80s Art",
"Abstract Art",
"Abstract Expressionism",
"Abstract Illusionism",
"Academism",
"Action Painting",
"Aestheticism",
"Afrofuturism",
"American Impressionism",
"American Scene Painting",
"Art Brut",
"Art Deco",
"Art Nouveau",
"Art Photography",
"Arts and Crafts Movement",
"Ascii Art",
"Ashcan School",
"Australian Tonalism",
"Baroque Art",
"Bauhaus Art",
"Berlin Secession",
"CGI Art",
"Classical Realism",
"Classicism Art",
"Cloisonnism",
"Computer Art",
"Conceptual Art",
"Constructivism Art",
"Crystal Cubism",
"Cubism",
"Cubo-Futurism",
"Cutester Art",
"Cybergoth Art",
"Cyberpunk Art",
"Dada Art",
"Dark Wave Art",
"Digital Art",
"Emo Art",
"Expressionism",
"Fauvism",
"Figurative Art",
"Fluxus Art",
"Folk Art",
"Funk Art",
"Futurism",
"Geometric Abstract Art",
"Glitch Art",
"Graffiti Street Art",
"Grunge Art",
"Gutai Group",
"Hardcore Art",
"Harlem Renaissance",
"Health Goth Art",
"Heidelberg School",
"Hippie Art",
"Hipster Art",
"Hyperrealism",
"Impressionism",
"Industrial Art",
"Kinetic Pointillism",
"Land Art",
"Lowbrow Art",
"Lyrical Abstraction",
"Magical Realism",
"Mannerism Art",
"Memecore Art",
"Metaphysical Painting",
"Mingei",
"Minimalism Art",
"Modern Art",
"Modern European Ink Painting",
"Modernism Art",
"Naive Art",
"Neo Dada Art",
"Neo",
"Neo-Dadaism Art",
"Neo-Expressionism",
"Neo-Fauvism",
"Neo-Primitivism",
"Neoclassicism",
"Neogothic Art",
"New Wave Art",
"Normcore Art",
"Nu Goth Art",
"Orphism",
"Panfuturism",
"Pastel Goth Art",
"Photorealism",
"Pixel Art",
"Pointillism",
"Pop Art",
"Post-Impressionism",
"Pre-Raphaelitism",
"Primitivism Art",
"Primitivism",
"Private Press",
"Process Art",
"Psychedelic Art",
"Psytrance Art",
"Qajar Art",
"Queercore Art",
"Realism",
"Remodernism",
"Renaissance",
"Retrofuturism",
"Rococo",
"Seapunk Art",
"Serial Art",
"Shin Hanga",
"Solarpunk Art",
"Steampunk Art",
"Street Art",
"Suprematism",
"Surrealism Art",
"Synthetism",
"Sōsaku Hanga",
"Temp",
"Tonalism",
"Toyism Art",
"Ukiyo-E",
"Vanitas",
"Vaporwave Art",
"Victorian Gothic Art",
"Vorticism Art",
"Yuccie Art"
]
[colors]
colors=[
"Agfacolor",
"Blue hue",
"BW",
"Cathode tube",
"CineColor",
"CMYK Colors",
"Cold Colors",
"Colorful",
"Colorless",
"Cyan hue",
"Dark hue",
"Desaturated",
"Dichromatic",
"Electric Colors",
"Fujifilm Superia",
"Grayscale",
"Green hue",
"High Contrast",
"Hypersaturated",
"Infrared",
"Kinemacolor",
"Kodachrome",
"Kodak Ektar",
"Kodak Portra",
"Low Contrast",
"Magenta hue",
"Mono Color",
"Muted Colors",
"Offset print",
"One Color",
"Oversaturated",
"Pastel Colors",
"Polychromatic",
"Primary Colors",
"Provia",
"Purple hue",
"Red hue",
"Saturated",
"Single Color",
"Technicolor",
"Velvia",
"Vivid Colors",
"Warm Colors",
"Yellow hue"
]
[directions]
directions=[
"Cel shaded",
"Cel shading",
"Detailed illustration",
"Graphic novel",
"Illustration",
"Masterpiece",
"Realistic",
"Rough sketch",
"Screen print",
"Simple illustration",
"Sketch",
"Sketched",
"Technical illustration",
"Ultra detailed",
"Ultrarealistic",
"Visual novel"
]
[moods]
moods=[
"Amusing",
"Angry",
"Cosy",
"Depressing",
"Disgusting",
"Embarrassing",
"Energetic",
"Evil",
"Fearful",
"Frightening",
"Grim",
"Guilty",
"Happy",
"Hopeful",
"Hopeless",
"Lonely",
"Lustful",
"Peaceful",
"Proud",
"Relieving",
"Romantic",
"Sad",
"Satisfying",
"Shameful",
"Surprising"
]
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+211
View File
@@ -0,0 +1,211 @@
{
"last_node_id": 18,
"last_link_id": 15,
"nodes": [
{
"id": 3,
"type": "Debug Extra",
"pos": [
2450,
347
],
"size": {
"0": 210,
"1": 66
},
"flags": {},
"order": 0,
"mode": 0,
"outputs": [
{
"name": "extra_pnginfo",
"type": "STRING",
"links": [],
"shape": 3,
"slot_index": 0
},
{
"name": "prompt",
"type": "STRING",
"links": [],
"shape": 3,
"slot_index": 1
},
{
"name": "state",
"type": "STRING",
"links": [
13
],
"shape": 3,
"slot_index": 2
}
],
"properties": {
"Node name for S&R": "Debug Extra"
}
},
{
"id": 5,
"type": "Display Any (rgthree)",
"pos": [
2141,
456
],
"size": {
"0": 463,
"1": 279
},
"flags": {},
"order": 3,
"mode": 0,
"inputs": [
{
"name": "source",
"type": "*",
"link": 14,
"dir": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "Display Any (rgthree)"
},
"widgets_values": [
"\"{aaa|bbb|ccc}\""
]
},
{
"id": 6,
"type": "Display Any (rgthree)",
"pos": [
2150,
771
],
"size": {
"0": 334,
"1": 224
},
"flags": {},
"order": 4,
"mode": 0,
"inputs": [
{
"name": "source",
"type": "*",
"link": 15,
"dir": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "Display Any (rgthree)"
},
"widgets_values": [
"\"{ddd|eee|fff}\""
]
},
{
"id": 9,
"type": "Display Any (rgthree)",
"pos": [
2843,
333
],
"size": {
"0": 517,
"1": 210
},
"flags": {},
"order": 2,
"mode": 0,
"inputs": [
{
"name": "source",
"type": "*",
"link": 13,
"dir": 3,
"slot_index": 0
}
],
"properties": {
"Node name for S&R": "Display Any (rgthree)"
},
"widgets_values": [
"\"{'Display Any (rgthree)(Display Any (rgthree)).5': {'output': ''},\\n 'Display Any (rgthree)(Display Any (rgthree)).6': {'output': ''},\\n 'Display Any (rgthree)(Display Any (rgthree)).9': {'output': ''},\\n 'PrimerePrompt(PrimerePrompt).18': ['{aaa|bbb|ccc}', '{ddd|eee|fff}']}\""
]
},
{
"id": 18,
"type": "PrimerePrompt",
"pos": [
1288,
271
],
"size": {
"0": 705,
"1": 681
},
"flags": {},
"order": 1,
"mode": 0,
"outputs": [
{
"name": "positive_prompt",
"type": "STRING",
"links": [
14
],
"shape": 3,
"slot_index": 0
},
{
"name": "negative_prompt",
"type": "STRING",
"links": [
15
],
"shape": 3,
"slot_index": 1
}
],
"properties": {
"Node name for S&R": "PrimerePrompt"
},
"widgets_values": [
"{aaa|bbb|ccc}",
"{ddd|eee|fff}"
]
}
],
"links": [
[
13,
3,
2,
9,
0,
"*"
],
[
14,
18,
0,
5,
0,
"*"
],
[
15,
18,
1,
6,
0,
"*"
]
],
"groups": [],
"config": {},
"extra": {},
"version": 0.4
}
File diff suppressed because it is too large Load Diff
+136
View File
@@ -0,0 +1,136 @@
import os
from .utils import comfy_dir
from .utils import here
__version__ = "0.1.0"
comfy_frontend = comfy_dir/"web"/"extensions"
frontend_target = comfy_frontend/"Primere"
if frontend_target.exists() == False:
# print(f"Primere front-end folder found at {frontend_target}")
# if not os.path.islink(frontend_target.as_posix()):
# print(f"Primere front-end folder at {frontend_target} is not a symlink, if updating please delete it before")
# elif comfy_frontend.exists():
frontend_source = here/"front_end"
src = frontend_source.as_posix()
dst = frontend_target.as_posix()
try:
if os.name == "nt":
import _winapi
_winapi.CreateJunction(src, dst)
else:
os.symlink(frontend_source.as_posix(), frontend_target.as_posix())
print(f"Primere front-end folder symlinked to {frontend_target}")
except OSError:
print(f"Failed to create frint-end symlink to {frontend_target}, trying to copy it")
try:
import shutil
shutil.copytree(frontend_source, frontend_target)
print(f"Successfully copied {frontend_source} to {frontend_target}")
except Exception as e:
print(f"Failed to symlink and copy {frontend_source} to {frontend_target}. Please copy the folder manually.")
except Exception as e:
print(f"Failed to create symlink to {frontend_target}. Please copy the folder manually.")
# else:
# print(f"Comfy root probably not found automatically, please copy the folder {frontend_target} manually in the web/extensions folder of ComfyUI")
import custom_nodes.ComfyUI_Primere_Nodes.Nodes.Dashboard as Dashboard
import custom_nodes.ComfyUI_Primere_Nodes.Nodes.Inputs as Inputs
import custom_nodes.ComfyUI_Primere_Nodes.Nodes.Styles as Styles
import custom_nodes.ComfyUI_Primere_Nodes.Nodes.Outputs as Outputs
import custom_nodes.ComfyUI_Primere_Nodes.Nodes.Visuals as Visuals
import custom_nodes.ComfyUI_Primere_Nodes.Nodes.Networks as Networks
NODE_CLASS_MAPPINGS = {
"PrimereSamplers": Dashboard.PrimereSamplers,
"PrimereVAE": Dashboard.PrimereVAE,
"PrimereCKPT": Dashboard.PrimereCKPT,
"PrimereVAELoader": Dashboard.PrimereVAELoader,
"PrimereCKPTLoader": Dashboard.PrimereCKPTLoader,
"PrimerePromptSwitch": Dashboard.PrimerePromptSwitch,
"PrimereSeed": Dashboard.PrimereSeed,
"PrimereLatentNoise": Dashboard.PrimereFractalLatent,
"PrimereCLIPEncoder": Dashboard.PrimereCLIP,
"PrimereResolution": Dashboard.PrimereResolution,
"PrimereStepsCfg": Dashboard.PrimereStepsCfg,
"PrimereClearPrompt": Dashboard.PrimereClearPrompt,
"PrimereLCMSelector": Dashboard.PrimereLCMSelector,
"PrimereResolutionMultiplier": Dashboard.PrimereResolutionMultiplier,
"PrimereNetworkTagLoader": Dashboard.PrimereNetworkTagLoader,
"PrimereModelKeyword": Dashboard.PrimereModelKeyword,
"PrimerePrompt": Inputs.PrimereDoublePrompt,
"PrimereStyleLoader": Inputs.PrimereStyleLoader,
"PrimereDynamicParser": Inputs.PrimereDynParser,
"PrimereVAESelector": Inputs.PrimereVAESelector,
"PrimereMetaRead": Inputs.PrimereMetaRead,
"PrimereEmbeddingHandler": Inputs.PrimereEmbeddingHandler,
"PrimereLoraStackMerger": Inputs.PrimereLoraStackMerger,
"PrimereLoraKeywordMerger": Inputs.PrimereLoraKeywordMerger,
"PrimereEmbeddingKeywordMerger": Inputs.PrimereEmbeddingKeywordMerger,
"PrimereMetaSave": Outputs.PrimereMetaSave,
"PrimereAnyOutput": Outputs.PrimereAnyOutput,
"PrimereTextOutput": Outputs.PrimereTextOutput,
"PrimereStylePile": Styles.PrimereStylePile,
"PrimereVisualCKPT": Visuals.PrimereVisualCKPT,
"PrimereVisualLORA": Visuals.PrimereVisualLORA,
"PrimereVisualEmbedding": Visuals.PrimereVisualEmbedding,
"PrimereVisualHypernetwork": Visuals.PrimereVisualHypernetwork,
"PrimereVisualStyle": Visuals.PrimereVisualStyle,
"PrimereLORA": Networks.PrimereLORA,
"PrimereEmbedding": Networks.PrimereEmbedding,
"PrimereHypernetwork": Networks.PrimereHypernetwork,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"PrimereSamplers": "Primere Sampler Selector",
"PrimereVAE": "Primere VAE Selector",
"PrimereCKPT": "Primere CKPT Selector",
"PrimereVAELoader": "Primere VAE Loader",
"PrimereCKPTLoader": "Primere CKPT Loader",
"PrimerePromptSwitch": "Primere Prompt Switch",
"PrimereSeed": 'Primere Seed',
"PrimereLatentNoise": "Primere Noise Latent",
"PrimereCLIPEncoder": "Primere Prompt Encoder",
"PrimereResolution": "Primere Resolution",
"PrimereStepsCfg": "Primere Steps & Cfg",
"PrimereClearPrompt": "Primere Prompt Cleaner",
"PrimereLCMSelector": "Primere LCM selector",
"PrimereResolutionMultiplier": "Primere Resolution Multiplier",
"PrimereNetworkTagLoader": 'Primere Network Tag Loader',
"PrimereModelKeyword": "Primere Model Keyword",
"PrimerePrompt": "Primere Prompt",
"PrimereStyleLoader": "Primere Styles",
"PrimereDynamicParser": "Primere Dynamic",
"PrimereVAESelector": "Primere VAE Selector",
"PrimereMetaRead": "Primere Exif Reader",
"PrimereEmbeddingHandler": "Primere Embedding Handler",
"PrimereLoraStackMerger": "Primere Lora Stack Merger",
"PrimereLoraKeywordMerger": 'Primere Lora Keyword Merger',
"PrimereEmbeddingKeywordMerger": "Primere Embedding Keyword Merger",
"PrimereMetaSave": "Primere Image Meta Saver",
"PrimereAnyOutput": "Primere Any Debug",
"PrimereTextOutput": "Primere Text Ouput",
"PrimereStylePile": "Primere Style Pile",
"PrimereVisualCKPT": "Primere Visual CKPT Selector",
"PrimereVisualLORA": "Primere Visual LORA Selector",
"PrimereVisualEmbedding": 'Primere Visual Embedding Selector',
"PrimereVisualHypernetwork": 'Primere Visual Hypernetwork Selector',
"PrimereVisualStyle": 'Primere Visual Style Selector',
"PrimereLORA": 'Primere LORA',
"PrimereEmbedding": 'Primere Embedding',
"PrimereHypernetwork": 'Primere Hypernetwork',
}
+93
View File
@@ -0,0 +1,93 @@
import comfy.utils
import torch
def load_hypernetwork_patch(path, strength, load_torch_safemode = True):
sd = comfy.utils.load_torch_file(path, safe_load = load_torch_safemode)
activation_func = sd.get('activation_func', 'linear')
is_layer_norm = sd.get('is_layer_norm', False)
use_dropout = sd.get('use_dropout', False)
activate_output = sd.get('activate_output', False)
last_layer_dropout = sd.get('last_layer_dropout', False)
valid_activation = {
"linear": torch.nn.Identity,
"relu": torch.nn.ReLU,
"leakyrelu": torch.nn.LeakyReLU,
"elu": torch.nn.ELU,
"swish": torch.nn.Hardswish,
"tanh": torch.nn.Tanh,
"sigmoid": torch.nn.Sigmoid,
"softsign": torch.nn.Softsign,
"mish": torch.nn.Mish,
}
if activation_func not in valid_activation:
print("Unsupported Hypernetwork format, if you report it I might implement it.", path, " ", activation_func, is_layer_norm, use_dropout, activate_output, last_layer_dropout)
return None
out = {}
for d in sd:
try:
dim = int(d)
except:
continue
output = []
for index in [0, 1]:
attn_weights = sd[dim][index]
keys = attn_weights.keys()
linears = filter(lambda a: a.endswith(".weight"), keys)
linears = list(map(lambda a: a[:-len(".weight")], linears))
layers = []
i = 0
while i < len(linears):
lin_name = linears[i]
last_layer = (i == (len(linears) - 1))
penultimate_layer = (i == (len(linears) - 2))
lin_weight = attn_weights['{}.weight'.format(lin_name)]
lin_bias = attn_weights['{}.bias'.format(lin_name)]
layer = torch.nn.Linear(lin_weight.shape[1], lin_weight.shape[0])
layer.load_state_dict({"weight": lin_weight, "bias": lin_bias})
layers.append(layer)
if activation_func != "linear":
if (not last_layer) or (activate_output):
layers.append(valid_activation[activation_func]())
if is_layer_norm:
i += 1
ln_name = linears[i]
ln_weight = attn_weights['{}.weight'.format(ln_name)]
ln_bias = attn_weights['{}.bias'.format(ln_name)]
ln = torch.nn.LayerNorm(ln_weight.shape[0])
ln.load_state_dict({"weight": ln_weight, "bias": ln_bias})
layers.append(ln)
if use_dropout:
if (not last_layer) and (not penultimate_layer or last_layer_dropout):
layers.append(torch.nn.Dropout(p=0.3))
i += 1
output.append(torch.nn.Sequential(*layers))
out[dim] = torch.nn.ModuleList(output)
class hypernetwork_patch:
def __init__(self, hypernet, strength):
self.hypernet = hypernet
self.strength = strength
def __call__(self, q, k, v, extra_options):
dim = k.shape[-1]
if dim in self.hypernet:
hn = self.hypernet[dim]
k = k + hn[0](k) * self.strength
v = v + hn[1](v) * self.strength
return q, k, v
def to(self, device):
for d in self.hypernet.keys():
self.hypernet[d] = self.hypernet[d].to(device)
return self
return hypernetwork_patch(out, strength)
+12
View File
@@ -0,0 +1,12 @@
from pathlib import Path
TREE_MAIN = "Primere Nodes"
COMPONENTS = Path(__file__).parent.absolute()
PRIMERE_ROOT = COMPONENTS.parent
TREE_DASHBOARD = TREE_MAIN + "/Dashboard"
TREE_INPUTS = TREE_MAIN + "/Inputs"
TREE_STYLES = TREE_MAIN + "/Styles"
TREE_OUTPUTS = TREE_MAIN + "/Outputs"
TREE_VISUALS = TREE_MAIN + "/Visuals"
TREE_NETWORKS = TREE_MAIN + "/Networks"
+340
View File
@@ -0,0 +1,340 @@
import math
import comfy.model_sampling
import torch
from dynamicprompts.generators import RandomPromptGenerator
import hashlib
import chardet
import pandas
import re
from pathlib import Path
import difflib
SUPPORTED_FORMATS = [".png", ".jpg", ".jpeg", ".webp"]
STANDARD_SIDES = [64, 80, 96, 128, 144, 160, 192, 256, 320, 368, 400, 480, 512, 560, 640, 704, 768, 832, 896, 960, 1024, 1088, 1152, 1216, 1280, 1344, 1408, 1472, 1536, 1600, 1664, 1728, 1792, 1856, 1920, 1984, 2048]
def merge_str_to_tuple(item1, item2):
if not isinstance(item1, tuple):
item1 = (item1,)
if not isinstance(item2, tuple):
item2 = (item2,)
return item1 + item2
def merge_dict(dict1, dict2):
dict3 = dict1.copy()
for k, v in dict2.items():
dict3[k] = merge_str_to_tuple(v, dict3[k]) if k in dict3 else v
return dict3
def remove_quotes(string):
return str(string).replace('"', "").replace("'", "")
def add_quotes(string):
return '"' + str(string) + '"'
def calculate_dimensions(self, ratio: str, orientation: str, round_to_standard: bool, model_version: str, calculate_by_custom: bool, custom_side_a: float, custom_side_b: float):
SD_1 = 512
SD_2 = 768
SD_1024 = 1024
SD_1280 = 1280
SDXL_1 = 1024
DEFAULT_RES = SD_2
match model_version:
case 'BaseModel_768':
DEFAULT_RES = SD_1
case 'BaseModel_1024':
DEFAULT_RES = SD_2
case 'BaseModel_mod_1024':
DEFAULT_RES = SD_1024
case 'BaseModel_mod_1280':
DEFAULT_RES = SD_1280
case 'SDXL_2048':
DEFAULT_RES = SDXL_1
def calculate(ratio_1: float, ratio_2: float, side: int):
FullPixels = side ** 2
result_x = FullPixels / ratio_2
result_y = result_x / ratio_1
side_base = round(math.sqrt(result_y))
side_a = round(ratio_1 * side_base)
if round_to_standard == True:
side_a = min(STANDARD_SIDES, key=lambda x: abs(side_a - x))
side_b = round(FullPixels / side_a)
return sorted([side_a, side_b], reverse=True)
if (calculate_by_custom == True and isinstance(custom_side_a, (int, float)) and isinstance(custom_side_b, (int, float)) and custom_side_a >= 1 and custom_side_b >= 1):
ratio_x = custom_side_a
ratio_y = custom_side_b
else:
RatioLabel = self.ratioNames[ratio]
ratio_x = self.sd_ratios[RatioLabel]['side_x']
ratio_y = self.sd_ratios[RatioLabel]['side_y']
dimensions = calculate(ratio_x, ratio_y, DEFAULT_RES)
if (orientation == 'Vertical'):
dimensions = sorted(dimensions)
dimension_x = dimensions[0]
dimension_y = dimensions[1]
return (dimension_x, dimension_y,)
def clear_prompt(NETWORK_START, NETWORK_END, promptstring):
promptstring_temp = promptstring
for LABEL in NETWORK_START:
if LABEL in promptstring:
LabelStartIndexes = [n for n in range(len(promptstring)) if promptstring.find(LABEL, n) == n]
for LabelStartIndex in LabelStartIndexes:
Matches = []
for endString in NETWORK_END:
Match = promptstring.find(endString, (LabelStartIndex + 1))
if (Match > 0):
Matches.append(Match)
LabelEndIndex = sorted(Matches)[0]
MatchedString = promptstring[LabelStartIndex:(LabelEndIndex + 1)]
if len(MatchedString) > 0:
if '<' in MatchedString:
endString = '>'
Match = promptstring.find(endString, (LabelStartIndex + 1))
if (Match > 0):
LabelEndIndex = Match
MatchedString = promptstring[LabelStartIndex:(LabelEndIndex + 1)]
promptstring_temp = promptstring_temp.replace(MatchedString, "")
if '{' in MatchedString:
endString = '}'
Match = promptstring.find(endString, (LabelStartIndex + 1))
if (Match > 0):
LabelEndIndex = Match
MatchedString = promptstring[LabelStartIndex:(LabelEndIndex + 1)]
promptstring_temp = promptstring_temp.replace(MatchedString, "")
if ')' in MatchedString:
MatchedString = promptstring[(LabelStartIndex - 1):(LabelEndIndex + 1)]
promptstring_temp = promptstring_temp.replace(MatchedString, "")
promptstring_temp = promptstring_temp.replace(MatchedString, "")
return promptstring_temp.replace('()', '').replace(' , ,', ',').replace('||', '').replace('{,', '').replace(' ', ' ').replace(', ,', ',').strip(', ')
def get_networks_prompt(NETWORK_START, NETWORK_END, promptstring):
valid_networks = []
for LABEL in NETWORK_START:
if LABEL in promptstring:
LabelStartIndexes = [n for n in range(len(promptstring)) if promptstring.find(LABEL, n) == n]
for LabelStartIndex in LabelStartIndexes:
Matches = []
for endString in NETWORK_END:
Match = promptstring.find(endString, (LabelStartIndex + 1))
if (Match > 0):
Matches.append(Match)
LabelEndIndex = sorted(Matches)[0]
MatchedString = promptstring[(LabelStartIndex + len(LABEL)):(LabelEndIndex)]
if len(MatchedString) > 0:
networkdata = MatchedString.split(":")
if len(networkdata) == 1:
networkdata.append('1')
if LABEL == '<lora:':
networkdata.append('LORA')
if LABEL == '<hypernet:':
networkdata.append('HYPERNET')
valid_networks.append(networkdata)
return valid_networks
def rescale_zero_terminal_snr_sigmas(sigmas):
alphas_cumprod = 1 / ((sigmas * sigmas) + 1)
alphas_bar_sqrt = alphas_cumprod.sqrt()
alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone()
alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone()
alphas_bar_sqrt -= (alphas_bar_sqrt_T)
alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T)
alphas_bar = alphas_bar_sqrt ** 2 # Revert sqrt
alphas_bar[-1] = 4.8973451890853435e-08
return ((1 - alphas_bar) / alphas_bar) ** 0.5
class ModelSamplingDiscreteLCM(torch.nn.Module):
def __init__(self):
super().__init__()
self.sigma_data = 1.0
timesteps = 1000
beta_start = 0.00085
beta_end = 0.012
betas = torch.linspace(beta_start**0.5, beta_end**0.5, timesteps, dtype=torch.float32) ** 2
alphas = 1.0 - betas
alphas_cumprod = torch.cumprod(alphas, dim=0)
original_timesteps = 50
self.skip_steps = timesteps // original_timesteps
alphas_cumprod_valid = torch.zeros((original_timesteps), dtype=torch.float32)
for x in range(original_timesteps):
alphas_cumprod_valid[original_timesteps - 1 - x] = alphas_cumprod[timesteps - 1 - x * self.skip_steps]
sigmas = ((1 - alphas_cumprod_valid) / alphas_cumprod_valid) ** 0.5
self.set_sigmas(sigmas)
def set_sigmas(self, sigmas):
self.register_buffer('sigmas', sigmas)
self.register_buffer('log_sigmas', sigmas.log())
@property
def sigma_min(self):
return self.sigmas[0]
@property
def sigma_max(self):
return self.sigmas[-1]
def timestep(self, sigma):
log_sigma = sigma.log()
dists = log_sigma.to(self.log_sigmas.device) - self.log_sigmas[:, None]
return dists.abs().argmin(dim=0).view(sigma.shape) * self.skip_steps + (self.skip_steps - 1)
def sigma(self, timestep):
t = torch.clamp(((timestep - (self.skip_steps - 1)) / self.skip_steps).float(), min=0, max=(len(self.sigmas) - 1))
low_idx = t.floor().long()
high_idx = t.ceil().long()
w = t.frac()
log_sigma = (1 - w) * self.log_sigmas[low_idx] + w * self.log_sigmas[high_idx]
return log_sigma.exp()
def percent_to_sigma(self, percent):
return self.sigma(torch.tensor(percent * 999.0))
class LCM(comfy.model_sampling.EPS):
def calculate_denoised(self, sigma, model_output, model_input):
timestep = self.timestep(sigma).view(sigma.shape[:1] + (1,) * (model_output.ndim - 1))
sigma = sigma.view(sigma.shape[:1] + (1,) * (model_output.ndim - 1))
x0 = model_input - model_output * sigma
sigma_data = 0.5
scaled_timestep = timestep * 10.0 #timestep_scaling
c_skip = sigma_data**2 / (scaled_timestep**2 + sigma_data**2)
c_out = scaled_timestep / (scaled_timestep**2 + sigma_data**2) ** 0.5
return c_out * x0 + c_skip * model_input
def DynPromptDecoder(self, dyn_prompt, seed):
prompt_generator = RandomPromptGenerator(
self._wildcard_manager,
seed = seed,
parser_config = self._parser_config,
unlink_seed_from_prompt = False,
ignore_whitespace = False
)
dyn_type = type(dyn_prompt).__name__
if (dyn_type != 'str'):
dyn_prompt = ''
try:
all_prompts = prompt_generator.generate(dyn_prompt, 1) or [""]
except Exception:
all_prompts = [""]
prompt = all_prompts[0]
return prompt
def ModelObjectParser(modelobject):
for key in modelobject:
Suboject_1 = modelobject[key]
Suboject_2 = Suboject_1._modules
for key1 in Suboject_2:
sub_2_typename = type(Suboject_2[key1]).__name__
if sub_2_typename == 'SpatialTransformer':
VersionObject = Suboject_2[key1]._modules['transformer_blocks']._modules['0']._modules['attn2']._modules['to_k'].in_features
if VersionObject <= 768:
VersionObject = 768
if 1024 >= VersionObject > 768:
VersionObject = 1024
if VersionObject > 1024:
VersionObject = 2048
return VersionObject
def getCheckpointVersion(modelobject):
ckpt_type = type(modelobject.__dict__['model']).__name__
try:
ModelVersion = ModelObjectParser(modelobject.model._modules['diffusion_model']._modules['input_blocks']._modules)
except:
ModelVersion = 1024
return ckpt_type + '_' + str(ModelVersion)
def get_model_hash(filename):
try:
with open(filename, "rb") as file:
m = hashlib.sha256()
file.seek(0x100000)
m.update(file.read(0x10000))
hash = m.hexdigest()[0:8]
return hash
except FileNotFoundError:
return None
def load_external_csv(csv_full_path: str, header_cols: int):
fileTest = open(csv_full_path, 'rb').readline()
result = chardet.detect(fileTest)
ENCODING = result['encoding']
if ENCODING == 'ascii':
ENCODING = 'UTF-8'
with open(csv_full_path, "r", newline = '', encoding = ENCODING) as csv_file:
try:
return pandas.read_csv(csv_file, header = header_cols, index_col = False, skipinitialspace = True)
except pandas.errors.ParserError as e:
errorstring = repr(e)
matchre = re.compile('Expected (\d+) fields in line (\d+), saw (\d+)')
(expected, line, saw) = map(int, matchre.search(errorstring).groups())
print(f'Error at line {line}. Fields added : {saw - expected}.')
return None
def get_model_keywords(filename, modelhash, model_name):
keywords = load_external_csv(filename, 3)
if keywords is not None:
selected_kv = keywords[keywords['#model_hash'] == modelhash]['keyword'].values
if (len(selected_kv) > 1):
selected_ckpt = keywords[keywords['#model_hash'] == modelhash]['filename.ckpt'].values
basename = Path(model_name).stem
cutoff_list = [1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1]
is_found = []
model_name_kw = None
for trycut in cutoff_list:
is_found = difflib.get_close_matches(basename, selected_ckpt, cutoff=trycut)
if len(is_found) >= 1:
model_name_kw = is_found[0]
break
if len(is_found) >= 0:
if model_name_kw is not None:
selected_kv = keywords[keywords['filename.ckpt'] == model_name_kw]['keyword'].values
if (len(selected_kv) > 0):
return selected_kv[0]
else:
return None
else:
return None
def get_closest_element(value, list):
cutoff_list = [1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1]
is_found = None
for trycut in cutoff_list:
is_found = difflib.get_close_matches(value, list, cutoff=trycut)
if len(is_found) >= 1:
return is_found[0]
return is_found
+113
View File
@@ -0,0 +1,113 @@
/* Primere css for visual selectors */
#primere_visual_modal {
align-content: start;
text-align: left;
}
#primere_visual_modal .visual_modal_title {
text-align: center;
padding: 0px;
margin-top: -1em;
color: var(--input-text);
text-transform: capitalize;
font-style: normal;
font-size: 28px;
/* line-height: 0px; */
height: 10px;
}
#primere_visual_modal button.modal-closer {
text-align: center;
padding: 5px;
margin-top: -1em;
font-style: normal;
width: 200px;
box-shadow: inset 1px 1px 3px #bdbdbd;
}
#primere_visual_modal .primere-modal-content {
z-index: 10000;
overflow: auto;
height: 90%;
}
#primere_visual_modal .visual-ckpt {
width: min-content;
display: inline-grid;
margin-right: 10px;
border: white solid 1px;
margin-bottom: 8px;
cursor: pointer;
box-shadow: 2px 2px 6px #909090;
position: relative;
background: white;
color: black;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius:5px;
}
#primere_visual_modal .visual-ckpt.visual-ckpt-selected {
background: #672727;
color: white;
border: #ff5151 solid 2px;
cursor: not-allowed;
pointer-events: none;
}
#primere_visual_modal .visual-ckpt:hover {
box-shadow: unset;
left: 2px;
top: 2px;
border: #949494 solid 1px;
background: #444444;
color: white;
}
#primere_visual_modal .visual-ckpt img {
height: 220px;
display: block;
-moz-border-bottom-left-radius: 5px;
-webkit-border-bottom-left-radius: 5px;
border-bottom-left-radius:5px;
-moz-border-bottom-right-radius: 5px;
-webkit-border-bottom-right-radius: 5px;
border-bottom-right-radius:5px;
}
#primere_visual_modal .checkpoint-name {
overflow: hidden;
display: inline-block;
width: 99%;
font-size: 12px;
font-weight: bold;
padding: 1px;
text-align: center;
white-space: nowrap;
}
#primere_visual_modal .subdirtab {
background: #656565;
vertical-align: middle;
display: block;
padding: 10px;
margin-bottom: 10px;
border-bottom: #aeaeae solid 1px;
border-top: #aeaeae solid 1px;
}
#primere_visual_modal .subdirtab button {
min-width: 80px;
margin-right: 5px;
padding-left: 9px;
padding-right: 10px;
font-size: 16px;
box-shadow: inset 1px 1px 3px #bdbdbd;
}
#primere_visual_modal .subdirtab label {
color: var(--input-text);
}
.selected_path {
color: #626262 !important;
background: white !important;
border: white solid 2px !important;
}
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+161
View File
@@ -0,0 +1,161 @@
import { ComfyApp, app } from "/scripts/app.js";
app.registerExtension({
name: "Primere.Promptswitch",
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name == 'PrimerePromptSwitch') {
var input_name_pos = "prompt_pos_";
var input_name_neg = "prompt_neg_";
var input_name_sub = "subpath_";
var input_name_mod = "model_";
var input_name_ori = "orientation_";
var n = 0;
const onConnectionsChange = nodeType.prototype.onConnectionsChange;
nodeType.prototype.onConnectionsChange = function(type, index, connected, link_info) {
if(!link_info)
return;
if (type == 2) {
if (connected && index == 0){
if (this.outputs[0].type == '*'){
if (link_info.type == '*') {
app.graph._nodes_by_id[link_info.target_id].disconnectInput(link_info.target_slot);
} else {
this.outputs[0].type = link_info.type;
this.outputs[1].type = origin_type;
this.outputs[2].type = origin_type;
this.outputs[3].type = origin_type;
this.outputs[4].type = origin_type;
for (let i in this.inputs) {
n = parseInt(i);
if (this.inputs[i].name.includes(input_name_pos) === true) {
let input_i_pos = this.inputs[n];
let input_i_neg = this.inputs[(n + 1)];
let input_i_sub = this.inputs[(n + 2)];
let input_i_mod = this.inputs[(n + 3)];
let input_i_ori = this.inputs[(n + 4)];
input_i_pos.type = link_info.type;
input_i_neg.type = link_info.type;
input_i_sub.type = link_info.type;
input_i_mod.type = link_info.type;
input_i_ori.type = link_info.type;
}
}
}
}
}
return;
} else {
//if (this.inputs[index].name.includes(input_name_neg) === true)
//return;
if (this.inputs[index].name == 'select')
return;
if (this.inputs[0].type == '*') {
const node = app.graph.getNodeById(link_info.origin_id);
let origin_type = node.outputs[link_info.origin_slot].type;
if (origin_type == '*') {
this.disconnectInput(link_info.target_slot);
return;
}
for (let i in this.inputs) {
n = parseInt(i);
if (this.inputs[i].name.includes(input_name_pos) === true) {
let input_i_pos = this.inputs[n];
let input_i_neg = this.inputs[(n + 1)];
let input_i_sub = this.inputs[(n + 2)];
let input_i_mod = this.inputs[(n + 3)];
let input_i_ori = this.inputs[(n + 4)];
input_i_pos.type = origin_type;
input_i_neg.type = origin_type;
input_i_sub.type = origin_type;
input_i_mod.type = origin_type;
input_i_ori.type = origin_type;
}
}
this.outputs[0].type = origin_type;
this.outputs[1].type = origin_type;
this.outputs[2].type = origin_type;
this.outputs[3].type = origin_type;
this.outputs[4].type = origin_type;
}
}
let select_slot = this.inputs.find(x => x.name == "select");
let converted_count = 0;
converted_count += select_slot ? 1 : 0;
if (!connected && (this.inputs.length > 5 + converted_count)) {
const stackTrace = new Error().stack;
if (!stackTrace.includes('LGraphNode.prototype.connect') && // for touch device
!stackTrace.includes('LGraphNode.connect') && // for mouse device
!stackTrace.includes('loadGraphData') &&
this.inputs[index].name != 'select') {
let last_pos_slot = this.inputs[this.inputs.length - 2];
let last_neg_slot = this.inputs[this.inputs.length - 1];
if (last_pos_slot.link == undefined && last_neg_slot.link == undefined) {
this.removeInput(this.inputs.length - 1);
this.removeInput(this.inputs.length - 1);
this.removeInput(this.inputs.length - 1);
this.removeInput(this.inputs.length - 1);
this.removeInput(this.inputs.length - 1);
}
}
}
let slot_i = 1;
for (let i = 0; i < this.inputs.length; i++) {
if (this.inputs[i].name.includes(input_name_pos) === true) {
let input_i_pos = this.inputs[i];
let input_i_neg = this.inputs[(i + 1)];
let input_i_sub = this.inputs[(i + 2)];
let input_i_mod = this.inputs[(i + 3)];
let input_i_ori = this.inputs[(i + 4)];
input_i_pos.name = `${input_name_pos}${slot_i}`
input_i_neg.name = `${input_name_neg}${slot_i}`
input_i_sub.name = `${input_name_sub}${slot_i}`;
input_i_mod.name = `${input_name_mod}${slot_i}`;
input_i_ori.name = `${input_name_ori}${slot_i}`;
slot_i++;
}
}
let last_pos_slot = this.inputs[this.inputs.length - 5];
let last_neg_slot = this.inputs[this.inputs.length - 4];
if (last_pos_slot.name.includes(input_name_pos) === true && last_neg_slot.link != undefined && last_pos_slot.link != undefined) {
this.addInput(`${input_name_pos}${slot_i}`, this.outputs[0].type);
this.addInput(`${input_name_neg}${slot_i}`, this.outputs[1].type);
this.addInput(`${input_name_sub}${slot_i}`, this.outputs[2].type);
this.addInput(`${input_name_mod}${slot_i}`, this.outputs[3].type);
this.addInput(`${input_name_ori}${slot_i}`, this.outputs[4].type);
}
if (this.widgets) {
let last_pos_slot = this.inputs[this.inputs.length - 5];
let last_neg_slot = this.inputs[this.inputs.length - 4];
var additionalMax = 0;
if (last_pos_slot.link == undefined && last_neg_slot.link == undefined) {
additionalMax = -1;
}
var selectMax = Math.round((this.inputs.length / 5) + additionalMax);
this.widgets[0].value = Math.min(this.widgets[0].value, this.widgets[0].options.max);
this.widgets[0].options.max = selectMax;
if (this.widgets[0].options.max > 0 && this.widgets[0].value <= 0)
this.widgets[0].value = 1;
if (this.widgets[0].value > selectMax)
this.widgets[0].value = selectMax;
}
}
}
},
});
+11
View File
@@ -0,0 +1,11 @@
import { app } from "/scripts/app.js";
// Adds an upload button to the nodes
app.registerExtension({
name: "Primere.PrimereMetaRead",
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name === "PrimereMetaRead") {
nodeData.input.required.upload = ["IMAGEUPLOAD"];
}
},
});
+26
View File
@@ -0,0 +1,26 @@
import { app } from "/scripts/app.js";
import { ComfyWidgets } from "/scripts/widgets.js";
let hasShownAlertForUpdatingInt = false;
app.registerExtension({
name: "Primere.PrimereOutputs",
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name === "PrimereAnyOutput" || nodeData.name === "PrimereTextOutput") {
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
onNodeCreated ? onNodeCreated.apply(this, []) : undefined;
this.showValueWidget = ComfyWidgets["STRING"](this, "output", ["STRING", { multiline: true }], app).widget;
this.showValueWidget.inputEl.readOnly = true;
this.showValueWidget.serializeValue = async (node, index) => {
node.widgets_values[index] = "";
return "";
};
};
const onExecuted = nodeType.prototype.onExecuted;
nodeType.prototype.onExecuted = function (message) {
onExecuted === null || onExecuted === void 0 ? void 0 : onExecuted.apply(this, [message]);
this.showValueWidget.value = message.text[0];
};
}
},
});
+395
View File
@@ -0,0 +1,395 @@
import { app } from "/scripts/app.js";
const realPath = "extensions/Primere";
const validClasses = ['PrimereVisualCKPT', 'PrimereVisualLORA', 'PrimereVisualEmbedding', 'PrimereVisualHypernetwork', 'PrimereVisualStyle'];
let defaultSubdir = 'All';
function createCardElement(checkpoint, container, SelectedModel, ModelType) {
let checkpoint_new = checkpoint.replaceAll('\\', '/');
let dotLastIndex = checkpoint_new.lastIndexOf('.');
if (dotLastIndex > 1) {
var finalName = checkpoint_new.substring(0, dotLastIndex);
} else {
var finalName = checkpoint_new;
}
finalName = finalName.replaceAll(' ', "_");
let previewName = finalName + '.jpg';
console.log(previewName);
let pathLastIndex = finalName.lastIndexOf('/');
let ckptName = finalName.substring(pathLastIndex + 1);
var card_html = '<div class="checkpoint-name">' + ckptName.replaceAll('_', " ") + '</div>';
var imgsrc = realPath + '/images/' + ModelType + '/' + previewName;
var missingimgsrc = realPath + '/images/missing.jpg';
var card = document.createElement("div");
card.classList.add('visual-ckpt');
if (SelectedModel === checkpoint) {
card.classList.add('visual-ckpt-selected');
}
const img = new Image();
img.src = imgsrc;
img.onload = () => {
const width = img.width;
if (width > 0) {
card_html += '<img src="' + imgsrc + '" title="' + checkpoint_new + '" data-ckptname="' + checkpoint + '">';
card.innerHTML = card_html;
container.appendChild(card);
}
};
img.onerror = () => {
card_html += '<img src="' + missingimgsrc + '" title="' + checkpoint_new + '" data-ckptname="' + checkpoint + '">';
card.innerHTML = card_html;
container.appendChild(card);
};
}
app.registerExtension({
name: "Primere.VisualMenu",
init() {
/* Promise.all([
fetch('extensions/Primere/keywords/lora-keyword.txt').then(x => x.text()),
fetch('extensions/Primere/keywords/model-keyword.txt').then(x => x.text())
]).then(([Lora, Model]) => {
console.log(Lora);
console.log(Model);
}); */
let callbackfunct = null;
function ModalHandler() {
let head = document.getElementsByTagName('HEAD')[0];
let link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = realPath + '/css/visual.css';
head.appendChild(link);
let js = document.createElement("script");
js.src = realPath + "/jquery/jquery-1.9.0.min.js";
head.appendChild(js);
js.onload = function(e) {
$(document).ready(function () {
var modal = null;
$('body').on("click", 'button.modal-closer', function() {
modal = document.getElementById("primere_visual_modal");
modal.setAttribute('style','display: none; width: 60%; height: 70%;')
});
$('body').on("click", 'div.primere-modal-content div.visual-ckpt img', function() {
var ckptName = $(this).data('ckptname');
modal = document.getElementById("primere_visual_modal");
modal.setAttribute('style','display: none; width: 60%; height: 70%;')
apply_modal(ckptName);
});
var subdirName ='All';
var filteredCheckpoints = 0;
$('body').on("click", 'div.subdirtab button.subdirfilter', function() {
$('div.subdirtab input').val('');
subdirName = $(this).data('ckptsubdir');
defaultSubdir = subdirName;
var imageContainers = $('div.primere-modal-content div.visual-ckpt');
filteredCheckpoints = 0;
$(imageContainers).find('img').each(function (img_index, img_obj) {
var ImageCheckpoint = $(img_obj).data('ckptname');
if (subdirName === 'Root') {
let isSubdirExist = ImageCheckpoint.lastIndexOf('\\');
if (isSubdirExist > 1 && $(img_obj).parent().closest(".visual-ckpt-selected").length === 0) {
$(img_obj).parent().hide();
} else {
$(img_obj).parent().show();
filteredCheckpoints++;
}
} else {
if (!ImageCheckpoint.startsWith(subdirName) && subdirName !== 'All' && $(img_obj).parent().closest(".visual-ckpt-selected").length === 0) {
$(img_obj).parent().hide();
} else {
$(img_obj).parent().show();
filteredCheckpoints++;
}
}
});
$('div#primere_visual_modal div.modal_header label.ckpt-name').text(subdirName);
$('div#primere_visual_modal div.modal_header label.ckpt-counter').text(filteredCheckpoints - 1);
$('div.subdirtab button.subdirfilter').removeClass("selected_path");
$(this).addClass('selected_path');
$(".visual-ckpt-selected").prependTo(".primere-modal-content");
});
$('body').on("keyup", 'div.subdirtab input', function() {
var filter = $(this).val();
var imageContainers = $('div.primere-modal-content div.visual-ckpt');
filteredCheckpoints = 0;
$(imageContainers).find('img').each(function (img_index, img_obj) {
var ImageCheckpoint = $(img_obj).data('ckptname');
let dotLastIndex = ImageCheckpoint.lastIndexOf('.');
if (dotLastIndex > 1) {
var finalFilter = ImageCheckpoint.substring(0, dotLastIndex);
} else {
var finalFilter = ImageCheckpoint;
}
if (!ImageCheckpoint.startsWith(subdirName) && subdirName !== 'All' && $(img_obj).parent().closest(".visual-ckpt-selected").length === 0) {
$(img_obj).parent().hide();
} else {
if (finalFilter.toLowerCase().indexOf(filter.toLowerCase()) >= 0 || $(img_obj).parent().closest(".visual-ckpt-selected").length > 0) {
$(img_obj).parent().show();
filteredCheckpoints++;
} else {
$(img_obj).parent().hide();
}
}
});
$('div#primere_visual_modal div.modal_header label.ckpt-counter').text(filteredCheckpoints - 1);
$(".visual-ckpt-selected").prependTo(".primere-modal-content");
});
$('body').on("click", 'div.subdirtab button.filter_clear', function() {
$('div.subdirtab input').val('');
var imageContainers = $('div.primere-modal-content div.visual-ckpt');
filteredCheckpoints = 0;
$(imageContainers).find('img').each(function (img_index, img_obj) {
var ImageCheckpoint = $(img_obj).data('ckptname');
if (!ImageCheckpoint.startsWith(subdirName) && subdirName !== 'All' && $(img_obj).parent().closest(".visual-ckpt-selected").length === 0) {
$(img_obj).parent().hide();
} else {
$(img_obj).parent().show();
filteredCheckpoints++;
}
});
$('div#primere_visual_modal div.modal_header label.ckpt-counter').text(filteredCheckpoints - 1);
$(".visual-ckpt-selected").prependTo(".primere-modal-content");
});
});
};
}
function apply_modal(Selected) {
if (Selected && typeof callbackfunct == 'function') {
callbackfunct(Selected);
return false;
}
}
function setup_visual_modal(combo_name, AllModels, ShowHidden, SelectedModel, ModelType, node) {
var container = null;
var modal = null;
var modalExist = true;
modal = document.getElementById("primere_visual_modal");
if (!modal) {
modalExist = false;
modal = document.createElement("div");
modal.classList.add("comfy-modal");
modal.setAttribute("id","primere_visual_modal");
modal.innerHTML='<div class="modal_header"><button type="button" class="modal-closer">Close modal</button> <h3 class="visual_modal_title">' + combo_name.replace("_"," ") + ' :: <label class="ckpt-name">All</label> :: <label class="ckpt-counter"></label></h3></div>';
let subdir_container = document.createElement("div");
subdir_container.classList.add("subdirtab");
let container = document.createElement("div");
container.classList.add("primere-modal-content", "ckpt-container", "ckpt-grid-layout");
modal.appendChild(subdir_container);
modal.appendChild(container);
document.body.appendChild(modal);
} else {
$('div#primere_visual_modal div.modal_header h3.visual_modal_title').html(combo_name.replace("_"," ") + ' :: <label class="ckpt-name">All</label> :: <label class="ckpt-counter"></label>');
}
container = modal.getElementsByClassName("ckpt-container")[0];
container.innerHTML = "";
var subdirArray = ['All'];
for (var checkpoints of AllModels) {
let pathLastIndex = checkpoints.lastIndexOf('\\');
let ckptSubdir = checkpoints.substring(0, pathLastIndex);
if (ckptSubdir === '') {
ckptSubdir = 'Root';
}
if (subdirArray.indexOf(ckptSubdir) === -1) {
subdirArray.push(ckptSubdir);
}
}
var subdir_tabs = modal.getElementsByClassName("subdirtab")[0];
var menu_html = '';
console.log(node.type + ' - ' + defaultSubdir);
for (var subdir of subdirArray) {
var addWhiteClass = '';
let firstletter = subdir.charAt(0);
var subdirName = subdir;
if (firstletter === '.') {
subdirName = subdir.substring(1);
}
if ((firstletter === '.' && ShowHidden === true) || firstletter !== '.') {
if (subdirName == 'All') {
addWhiteClass = ' selected_path';
}
menu_html += '<button type="button" data-ckptsubdir="' + subdir + '" class="subdirfilter' + addWhiteClass + '">' + subdirName + '</button>';
}
}
subdir_tabs.innerHTML = menu_html + '<label> | </label> <input type="text" name="ckptfilter" placeholder="filter"> <button type="button" class="filter_clear">Clear filter</button>';
var CKPTElements = 0;
for (var checkpoint of AllModels) {
let firstletter = checkpoint.charAt(0);
if (((firstletter === '.' && ShowHidden === true) || firstletter !== '.') && ((checkpoint.match('^NSFW') && ShowHidden === true) || !checkpoint.match('^NSFW'))) {
CKPTElements++;
createCardElement(checkpoint, container, SelectedModel, ModelType)
}
}
modal.setAttribute('style','display: block; width: 60%; height: 70%;');
var TimingBase =AllModels.length;
var mtimeout = TimingBase * 3;
if (modalExist === false) {
mtimeout = TimingBase * 18;
}
setTimeout(function(mtimeout) {
$('div#primere_visual_modal div.modal_header label.ckpt-name').text('All');
$('div#primere_visual_modal div.modal_header label.ckpt-counter').text(CKPTElements - 1);
$(".visual-ckpt-selected").prependTo(".primere-modal-content");
}, mtimeout);
}
ModalHandler();
let subdirname = '';
let modaltitle = '';
let nodematch = '';
let isnumeric_end = true;
const lcg = LGraphCanvas.prototype.processNodeWidgets;
LGraphCanvas.prototype.processNodeWidgets = function(node, pos, event, active_widget) {
//console.log(node);
if (!validClasses.includes(node.type)) {
return lcg.call(this, node, pos, event, active_widget);
}
if (node.type == 'PrimereVisualCKPT') {
subdirname = 'checkpoints';
modaltitle = 'Select checkpoint';
nodematch = '^base_model';
isnumeric_end = false;
}
if (node.type == 'PrimereVisualLORA') {
subdirname = 'loras';
modaltitle = 'Select LoRA';
nodematch = '^lora_';
isnumeric_end = true;
}
if (node.type == 'PrimereVisualEmbedding') {
subdirname = 'embeddings';
modaltitle = 'Select embedding';
nodematch = '^embedding_';
isnumeric_end = true;
}
if (node.type == 'PrimereVisualHypernetwork') {
subdirname = 'hypernetworks';
modaltitle = 'Select hypernetwork';
nodematch = '^hypernetwork_';
isnumeric_end = true;
}
if (node.type == 'PrimereVisualStyle') {
subdirname = 'styles';
modaltitle = 'Select style';
nodematch = '^styles';
isnumeric_end = false;
}
if (event.type != LiteGraph.pointerevents_method + "down") {
return lcg.call(this, node, pos, event, active_widget);
}
if (!node.widgets || !node.widgets.length || (!this.allow_interaction && !node.flags.allow_interaction)) {
return lcg.call(this, node, pos, event, active_widget);
}
var x = pos[0] - node.pos[0];
var y = pos[1] - node.pos[1];
var width = node.size[0];
var that = this;
var ShowHidden = false;
var ShowModal = false;
for (var p = 0; p < node.widgets.length; ++p) {
if (node.widgets[p].name == 'show_hidden') {
ShowHidden = node.widgets[p].value;
}
if (node.widgets[p].name == 'show_modal') {
ShowModal = node.widgets[p].value;
}
}
if (ShowModal === false) {
return lcg.call(this, node, pos, event, active_widget);
}
for (var i = 0; i < node.widgets.length; ++i) {
var w = node.widgets[i];
if (!w || w.disabled)
continue;
if (w.type != "combo")
continue
var widget_height = w.computeSize ? w.computeSize(width)[1] : LiteGraph.NODE_WIDGET_HEIGHT;
var widget_width = w.width || width;
var widget_name = node.widgets[i].name;
if (w != active_widget && (x < 6 || x > widget_width - 12 || y < w.last_y || y > w.last_y + widget_height || w.last_y === undefined))
continue
if (w == active_widget || (x > 6 && x < widget_width - 12 && y > w.last_y && y < w.last_y + widget_height)) {
var delta = x < 40 ? -1 : x > widget_width - 40 ? 1 : 0;
if (delta)
continue;
if (widget_name.match(nodematch) && $.isNumeric(widget_name.substr(-1)) === isnumeric_end) {
var AllModels = node.widgets[i].options.values;
var SelectedModel = node.widgets[i].value;
callbackfunct = inner_clicked.bind(w);
setup_visual_modal(modaltitle, AllModels, ShowHidden, SelectedModel, subdirname, node);
function inner_clicked(v, option, event) {
inner_value_change(this, v);
that.dirty_canvas = true;
return false;
}
function inner_value_change(widget, value) {
if (widget.type == "number") {
value = Number(value);
}
widget.value = value;
if (widget.options && widget.options.property && node.properties[widget.options.property] !== undefined) {
node.setProperty(widget.options.property, value);
}
if (widget.callback) {
widget.callback(widget.value, that, node, pos, event);
}
}
return null;
}
}
}
return lcg.call(this, node, pos, event, active_widget);
}
},
async beforeRegisterNodeDef(nodeType, nodeData, app) {
},
});
+155
View File
@@ -0,0 +1,155 @@
import { app } from "../../scripts/app.js";
import { ComfyWidgets } from "../../scripts/widgets.js";
const LAST_SEED_BUTTON_LABEL = "♻️ (Use Last Queued Seed)";
const SPECIAL_SEED_RANDOM = -1;
const SPECIAL_SEED_INCREMENT = -2;
const SPECIAL_SEED_DECREMENT = -3;
const SPECIAL_SEEDS = [SPECIAL_SEED_RANDOM, SPECIAL_SEED_INCREMENT, SPECIAL_SEED_DECREMENT];
class SeedControl {
constructor(node) {
this.lastSeed = undefined;
this.serializedCtx = {};
this.lastSeedValue = null;
this.node = node;
this.node.constructor.exposedActions = ["Randomize Each Time", "Use Last Queued Seed"];
const handleAction = this.node.handleAction;
this.node.handleAction = async (action) => {
handleAction && handleAction.call(this.node, action);
if (action === "Randomize Each Time") {
this.seedWidget.value = SPECIAL_SEED_RANDOM;
}
else if (action === "Use Last Queued Seed") {
this.seedWidget.value = this.lastSeed != null ? this.lastSeed : this.seedWidget.value;
this.lastSeedButton.name = LAST_SEED_BUTTON_LABEL;
this.lastSeedButton.disabled = true;
}
};
this.node.properties = this.node.properties || {};
for (const [i, w] of this.node.widgets.entries()) {
if (w.name === "seed") {
this.seedWidget = w;
}
else if (w.name === "control_after_generate") {
this.node.widgets.splice(i, 1);
}
}
if (!this.seedWidget) {
throw new Error("Something's wrong; expected seed widget");
}
const randMax = Math.min(1125899906842624, this.seedWidget.options.max);
const randMin = Math.max(0, this.seedWidget.options.min);
const randomRange = (randMax - Math.max(0, randMin)) / (this.seedWidget.options.step / 10);
this.node.addWidget("button", "🎲 Randomize Each Time", null, () => {
this.seedWidget.value = SPECIAL_SEED_RANDOM;
}, { serialize: false });
this.node.addWidget("button", "🎲 New Fixed Random", null, () => {
this.seedWidget.value = Math.floor(Math.random() * randomRange) * (this.seedWidget.options.step / 10) + randMin;
}, { serialize: false });
this.lastSeedButton = this.node.addWidget("button", LAST_SEED_BUTTON_LABEL, null, () => {
this.seedWidget.value = this.lastSeed != null ? this.lastSeed : this.seedWidget.value;
this.lastSeedButton.name = LAST_SEED_BUTTON_LABEL;
this.lastSeedButton.disabled = true;
}, { width: 50, serialize: false });
this.lastSeedButton.disabled = true;
this.seedWidget.serializeValue = async (node, index) => {
const inputSeed = this.seedWidget.value;
this.serializedCtx = {
inputSeed: this.seedWidget.value,
};
if (SPECIAL_SEEDS.includes(this.serializedCtx.inputSeed)) {
if (typeof this.lastSeed === "number" && !SPECIAL_SEEDS.includes(this.lastSeed)) {
if (inputSeed === SPECIAL_SEED_INCREMENT) {
this.serializedCtx.seedUsed = this.lastSeed + 1;
}
else if (inputSeed === SPECIAL_SEED_INCREMENT) {
this.serializedCtx.seedUsed = this.lastSeed - 1;
}
}
if (!this.serializedCtx.seedUsed || SPECIAL_SEEDS.includes(this.serializedCtx.seedUsed)) {
this.serializedCtx.seedUsed = Math.floor(Math.random() * randomRange) * (this.seedWidget.options.step / 10) + randMin;
}
} else {
this.serializedCtx.seedUsed = this.seedWidget.value;
}
node.widgets_values[index] = this.serializedCtx.seedUsed;
this.seedWidget.value = this.serializedCtx.seedUsed;
this.lastSeed = this.serializedCtx.seedUsed;
if (SPECIAL_SEEDS.includes(this.serializedCtx.inputSeed)) {
this.lastSeedButton.name = `♻️ ${this.serializedCtx.seedUsed}`;
this.lastSeedButton.disabled = false;
if (this.lastSeedValue) {
this.lastSeedValue.value = `Last Seed: ${this.serializedCtx.seedUsed}`;
}
} else {
this.lastSeedButton.name = LAST_SEED_BUTTON_LABEL;
this.lastSeedButton.disabled = true;
}
return this.serializedCtx.seedUsed;
};
this.seedWidget.afterQueued = () => {
if (this.serializedCtx.inputSeed) {
this.seedWidget.value = this.serializedCtx.inputSeed;
}
this.serializedCtx = {};
};
this.node.getExtraMenuOptions = (_, options) => {
options.splice(options.length - 1, 0, {
content: "Show/Hide Last Seed Value",
callback: (_value, _options, _event, _parentMenu, _node) => {
this.node.properties["showLastSeed"] = !this.node.properties["showLastSeed"];
if (this.node.properties["showLastSeed"]) {
this.addLastSeedValue();
} else {
this.removeLastSeedValue();
}
},
});
};
}
addLastSeedValue() {
if (this.lastSeedValue)
return;
this.lastSeedValue = ComfyWidgets["STRING"](this.node, "last_seed", ["STRING", { multiline: true }], app).widget;
this.lastSeedValue.inputEl.readOnly = true;
this.lastSeedValue.inputEl.style.fontSize = "0.75rem";
this.lastSeedValue.inputEl.style.textAlign = "center";
this.lastSeedValue.serializeValue = async (node, index) => {
node.widgets_values[index] = "";
return "";
};
this.node.computeSize();
}
removeLastSeedValue() {
if (!this.lastSeedValue)
return;
this.lastSeedValue.inputEl.remove();
this.node.widgets.splice(this.node.widgets.indexOf(this.lastSeedValue), 1);
this.lastSeedValue = null;
this.node.computeSize();
}
}
app.registerExtension({
name: "Primere.Seed",
async beforeRegisterNodeDef(nodeType, nodeData, _app) {
if (nodeData.name === "PrimereSeed") {
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
onNodeCreated ? onNodeCreated.apply(this, []) : undefined;
this.seedControl = new SeedControl(this);
};
}
},
});
+12
View File
@@ -0,0 +1,12 @@
chardet
dynamicprompts
nodes
numpy
pandas
pefile
piexif
Pillow
pyexiv2
Requests
tomli
torch
+23
View File
@@ -0,0 +1,23 @@
import sys
from pathlib import Path
def add_path(path, prepend=False):
if isinstance(path, list):
for p in path:
add_path(p, prepend)
return
if isinstance(path, Path):
path = path.resolve().as_posix()
if path not in sys.path:
if prepend:
sys.path.insert(0, path)
else:
sys.path.append(path)
here = Path(__file__).parent.absolute()
comfy_dir = here.parent.parent
add_path(comfy_dir)
add_path((comfy_dir/"custom_nodes"))