diff --git a/.disabled/comfyui-kjnodes@nightly/.github/workflows/publish.yml b/.disabled/comfyui-kjnodes@nightly/.github/workflows/publish.yml new file mode 100644 index 0000000000000000000000000000000000000000..be75d38aa858e24376e02d4782290390f1f8bb88 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/.github/workflows/publish.yml @@ -0,0 +1,25 @@ +name: Publish to Comfy registry +on: + workflow_dispatch: + push: + branches: + - main + paths: + - "pyproject.toml" + +permissions: + issues: write + +jobs: + publish-node: + name: Publish Custom Node to registry + runs-on: ubuntu-latest + if: ${{ github.repository_owner == 'kijai' }} + steps: + - name: Check out code + uses: actions/checkout@v4 + - name: Publish Custom Node + uses: Comfy-Org/publish-node-action@v1 + with: + ## Add your own personal access token to your Github Repository secrets and reference it here. + personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }} diff --git a/.disabled/comfyui-kjnodes@nightly/.gitignore b/.disabled/comfyui-kjnodes@nightly/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..de69123ac62f2de629ac6133b5b9d20555b173f6 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/.gitignore @@ -0,0 +1,13 @@ +__pycache__ +/venv +*.code-workspace +.history +.vscode +*.ckpt +*.pth +types +models +jsconfig.json +custom_dimensions.json +.claude +.tests diff --git a/.disabled/comfyui-kjnodes@nightly/LICENSE b/.disabled/comfyui-kjnodes@nightly/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3877ae0a7ff6f94ac222fd704e112723db776114 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + + Copyright (C) + + 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 . + +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: + + Copyright (C) + 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 +. + + 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 +. diff --git a/.disabled/comfyui-kjnodes@nightly/README.md b/.disabled/comfyui-kjnodes@nightly/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3090f61811d3895f066908ce412af7d56c53a1a6 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/README.md @@ -0,0 +1,72 @@ +# KJNodes for ComfyUI + +At this point pretty random collection of utility, model optimization and QoL nodes, while keeping dependencies at minimum. + +Documentation is mostly in the node descriptions and tooltips. + +# Installation +1. Clone this repo into `custom_nodes` folder. +2. Install dependencies: `pip install -r requirements.txt` + or if you use the portable install, run this in ComfyUI_windows_portable -folder: + + `python_embeded\python.exe -m pip install -r ComfyUI\custom_nodes\ComfyUI-KJNodes\requirements.txt` + +### Set/Get + +# UPDATE March 19th 2026 + +Complete (backwards compatible as far as I'm aware currently) rewrite of Set/Get nodes. + +# Changelog March 19th 2026 + +## New Features + +- **Nodes 2.0 support** - Works with nodes 2.0 as well as legacy. + +- **Subgraph support** — Set/Get now works across subgraph boundaries. A Set in a parent graph is visible to all child subgraphs, and Get nodes search upward through ancestors. Cross-graph connections are resolved during prompt execution. + +- **Convert link to Set/Get** — Right-click any link midpoint to convert it into a Set/Get pair. + +- **Convert to links** — Right-click a Set or Get node to convert the pair back to direct links. + +- **Convert outputs to Set/Get** — Batch operation to convert all outputs of selected nodes into Set/Get pairs at once. + +- **Canvas right-click menu** — "Convert outputs on all selected nodes to Set/Get" and "Convert selected Set/Get to links". + +- **Keyboard shortcuts** — Ctrl+Shift+S (add Set to selected / at cursor), Ctrl+Shift+G (add Get at cursor), Ctrl+Shift+L (force-show all connections toggle). + +- **"Convert ALL Set/Get to links" setting** — One-click button in settings to replace every Set/Get pair with direct links, including across subgraph boundaries. + +- **Show links setting** — Combo setting (never / selected / always) to control when virtual links between Set/Get pairs are drawn. "Selected" mode shows links only for currently selected Set/Get nodes. Ctrl+Shift+L temporarily forces all links visible. + +- **Add Set/Get from connection menu** — When dragging from a slot, "Add SetNode" and "Add GetNode" entries appear next to "Add Reroute" in the connection menu. + +- **Shift+middle-click creates Set/Get** — Shift+middle-click on an output slot creates a connected SetNode; on an input slot creates a connected GetNode. Optional setting to override normal middle-click to also create Set/Get instead of Reroute. + +- **Add paired GetNode** — Right-click a SetNode to add a paired GetNode pre-configured with the same name. + +- **Double-click Get to jump to Set** — Double-click a GetNode to center and select its paired SetNode. + +- **Default widget value setting** — Controls the initial Constant value when a Set node is first connected: empty (default), slot name, slot name (lowercase), or slot name (UPPERCASE). + +- **Type inference from output** — If a SetNode's input is unconnected but its output is connected to a typed input, the Set adopts that type and recolors accordingly. + +- **Getters submenu navigates into subgraphs** — SetNode's getter list now includes cross-subgraph GetNodes and can navigate into subgraphs to focus them. + +## Fixes + +- **Paste rename coordination** — When pasting Set+Get pairs, GetNodes now correctly follow their SetNode's rename (e.g., `MODEL` -> `MODEL_0`). + +- **Type/color reset on disconnect** — Disconnecting input or output now correctly resets type and color, but only when neither side is still connected. + +- **Suffix stripping only on paste** — `validateName` no longer strips intentional `_N` suffixes from user-typed names. Only strips during paste to avoid `FOO_0_1_2` accumulation. + +- **Connection drawing moved to canvas level** — Visualization links remain visible even when nodes are off-screen or collapsed. + +## Settings + +- Settings are now organized under **KJNodes > Set & Get** and **KJNodes > General** categories in the settings panel. + + +--- + diff --git a/.disabled/comfyui-kjnodes@nightly/__init__.py b/.disabled/comfyui-kjnodes@nightly/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6339b348cd72534f58e13c5bc7199849ef342497 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/__init__.py @@ -0,0 +1,302 @@ +from .nodes.nodes import * +from .nodes.curve_nodes import * +from .nodes.batchcrop_nodes import * +from .nodes.audioscheduler_nodes import * +from .nodes.image_nodes import * +from .nodes.intrinsic_lora_nodes import * +from .nodes.mask_nodes import * +from .nodes.model_optimization_nodes import * +from .nodes.lora_nodes import * +from .nodes.sharpen_nodes import ImageSharpenKJ + + +NODE_CONFIG = { + #constants + "BOOLConstant": {"class": BOOLConstant, "name": "BOOL Constant"}, + "INTConstant": {"class": INTConstant, "name": "INT Constant"}, + "FloatConstant": {"class": FloatConstant, "name": "Float Constant"}, + "StringConstant": {"class": StringConstant, "name": "String Constant"}, + "StringConstantMultiline": {"class": StringConstantMultiline, "name": "String Constant Multiline"}, + #conditioning + "ConditioningMultiCombine": {"class": ConditioningMultiCombine, "name": "Conditioning Multi Combine"}, + "ConditioningSetMaskAndCombine": {"class": ConditioningSetMaskAndCombine, "name": "ConditioningSetMaskAndCombine"}, + "ConditioningSetMaskAndCombine3": {"class": ConditioningSetMaskAndCombine3, "name": "ConditioningSetMaskAndCombine3"}, + "ConditioningSetMaskAndCombine4": {"class": ConditioningSetMaskAndCombine4, "name": "ConditioningSetMaskAndCombine4"}, + "ConditioningSetMaskAndCombine5": {"class": ConditioningSetMaskAndCombine5, "name": "ConditioningSetMaskAndCombine5"}, + "CondPassThrough": {"class": CondPassThrough}, + "WanImageToVideoSVIPro": {"class": WanImageToVideoSVIPro, "name": "Wan Image To Video SVIPro"}, + #masking + "DrawMaskOnImage": {"class": DrawMaskOnImage, "name": "Draw Mask On Image"}, + "DownloadAndLoadCLIPSeg": {"class": DownloadAndLoadCLIPSeg, "name": "(Down)load CLIPSeg"}, + "BatchCLIPSeg": {"class": BatchCLIPSeg, "name": "Batch CLIPSeg"}, + "BlockifyMask": {"class": BlockifyMask, "name": "Blockify Mask"}, + "ColorToMask": {"class": ColorToMask, "name": "Color To Mask"}, + "CreateGradientMask": {"class": CreateGradientMask, "name": "Create Gradient Mask"}, + "CreateTextMask": {"class": CreateTextMask, "name": "Create Text Mask"}, + "CreateAudioMask": {"class": CreateAudioMask, "name": "Create Audio Mask"}, + "CreateFadeMask": {"class": CreateFadeMask, "name": "Create Fade Mask"}, + "CreateFadeMaskAdvanced": {"class": CreateFadeMaskAdvanced, "name": "Create Fade Mask Advanced"}, + "CreateFluidMask": {"class": CreateFluidMask, "name": "Create Fluid Mask"}, + "CreateShapeMask": {"class": CreateShapeMask, "name": "Create Shape Mask"}, + "CreateVoronoiMask": {"class": CreateVoronoiMask, "name": "Create Voronoi Mask"}, + "CreateMagicMask": {"class": CreateMagicMask, "name": "Create Magic Mask"}, + "GetMaskSizeAndCount": {"class": GetMaskSizeAndCount, "name": "Get Mask Size & Count"}, + "GrowMaskWithBlur": {"class": GrowMaskWithBlur, "name": "Grow Mask With Blur"}, + "MaskBatchMulti": {"class": MaskBatchMulti, "name": "Mask Batch Multi"}, + "OffsetMask": {"class": OffsetMask, "name": "Offset Mask"}, + "RemapMaskRange": {"class": RemapMaskRange, "name": "Remap Mask Range"}, + "ResizeMask": {"class": ResizeMask, "name": "Resize Mask"}, + "RoundMask": {"class": RoundMask, "name": "Round Mask"}, + "SeparateMasks": {"class": SeparateMasks, "name": "Separate Masks"}, + "ConsolidateMasksKJ": {"class": ConsolidateMasksKJ, "name": "Consolidate Masks"}, + #images + "AddLabel": {"class": AddLabel, "name": "Add Label"}, + "ColorMatch": {"class": ColorMatch, "name": "Color Match"}, + "ColorMatchV2": {"class": ColorMatchV2, "name": "Color Match V2"}, + "ImageTensorList": {"class": ImageTensorList, "name": "Image Tensor List"}, + "CrossFadeImages": {"class": CrossFadeImages, "name": "Cross Fade Images"}, + "CrossFadeImagesMulti": {"class": CrossFadeImagesMulti, "name": "Cross Fade Images Multi"}, + "GetImagesFromBatchIndexed": {"class": GetImagesFromBatchIndexed, "name": "Get Images From Batch Indexed"}, + "GetImageRangeFromBatch": {"class": GetImageRangeFromBatch, "name": "Get Image or Mask Range From Batch"}, + "GetLatentRangeFromBatch": {"class": GetLatentRangeFromBatch, "name": "Get Latent Range From Batch"}, + "GetLatentSizeAndCount": {"class": GetLatentSizeAndCount, "name": "Get Latent Size & Count"}, + "GetImageSizeAndCount": {"class": GetImageSizeAndCount, "name": "Get Image Size & Count"}, + "FastPreview": {"class": FastPreview, "name": "Fast Preview"}, + "ImageBatchFilter": {"class": ImageBatchFilter, "name": "Image Batch Filter"}, + "ImageAndMaskPreview": {"class": ImageAndMaskPreview}, + "ImageAddMulti": {"class": ImageAddMulti, "name": "Image Add Multi"}, + "ImageBatchJoinWithTransition": {"class": ImageBatchJoinWithTransition, "name": "Image Batch Join With Transition"}, + "ImageBatchMulti": {"class": ImageBatchMulti, "name": "Image Batch Multi"}, + "ImageBatchRepeatInterleaving": {"class": ImageBatchRepeatInterleaving}, + "ImageBatchTestPattern": {"class": ImageBatchTestPattern, "name": "Image Batch Test Pattern"}, + "ImageConcanate": {"class": ImageConcanate, "name": "Image Concatenate"}, + "ImageConcatFromBatch": {"class": ImageConcatFromBatch, "name": "Image Concatenate From Batch"}, + "ImageConcatMulti": {"class": ImageConcatMulti, "name": "Image Concatenate Multi"}, + "ImageCropByMask": {"class": ImageCropByMask, "name": "Image Crop By Mask"}, + "ImageCropByMaskAndResize": {"class": ImageCropByMaskAndResize, "name": "Image Crop By Mask And Resize"}, + "ImageCropByMaskBatch": {"class": ImageCropByMaskBatch, "name": "Image Crop By Mask Batch"}, + "ImageUncropByMask": {"class": ImageUncropByMask, "name": "Image Uncrop By Mask"}, + "ImageBatchExtendWithOverlap": {"class": ImageBatchExtendWithOverlap, "name": "Image Batch Extend With Overlap"}, + "ImageGrabPIL": {"class": ImageGrabPIL, "name": "Image Grab PIL"}, + "ImageGridComposite2x2": {"class": ImageGridComposite2x2, "name": "Image Grid Composite 2x2"}, + "ImageGridComposite3x3": {"class": ImageGridComposite3x3, "name": "Image Grid Composite 3x3"}, + "ImageGridtoBatch": {"class": ImageGridtoBatch, "name": "Image Grid To Batch"}, + "ImageNoiseAugmentation": {"class": ImageNoiseAugmentation, "name": "Image Noise Augmentation"}, + "ImageNormalize_Neg1_To_1": {"class": ImageNormalize_Neg1_To_1, "name": "Image Normalize -1 to 1"}, + "ImagePass": {"class": ImagePass}, + "ImagePadKJ": {"class": ImagePadKJ, "name": "ImagePad KJ"}, + "ImagePadForOutpaintMasked": {"class": ImagePadForOutpaintMasked, "name": "Image Pad For Outpaint Masked"}, + "ImagePadForOutpaintTargetSize": {"class": ImagePadForOutpaintTargetSize, "name": "Image Pad For Outpaint Target Size"}, + "ImagePrepForICLora": {"class": ImagePrepForICLora, "name": "Image Prep For ICLora"}, + "ImageResizeKJ": {"class": ImageResizeKJ, "name": "Resize Image (deprecated)"}, + "ImageResizeKJv2": {"class": ImageResizeKJv2, "name": "Resize Image v2"}, + "ImageUpscaleWithModelBatched": {"class": ImageUpscaleWithModelBatched, "name": "Image Upscale With Model Batched"}, + "InsertImagesToBatchIndexed": {"class": InsertImagesToBatchIndexed, "name": "Insert Images To Batch Indexed"}, + "InsertLatentToIndexed": {"class": InsertLatentToIndex, "name": "Insert Latent To Index"}, + "LoadAndResizeImage": {"class": LoadAndResizeImage, "name": "Load & Resize Image"}, + "LoadImagesFromFolderKJ": {"class": LoadImagesFromFolderKJ, "name": "Load Images From Folder (KJ)"}, + "LoadVideosFromFolder": {"class": LoadVideosFromFolder, "name": "Load Videos From Folder"}, + "MergeImageChannels": {"class": MergeImageChannels, "name": "Merge Image Channels"}, + "PadImageBatchInterleaved": {"class": PadImageBatchInterleaved, "name": "Pad Image Batch Interleaved"}, + "PreviewAnimation": {"class": PreviewAnimation, "name": "Preview Animation"}, + "RemapImageRange": {"class": RemapImageRange, "name": "Remap Image Range"}, + "ReverseImageBatch": {"class": ReverseImageBatch, "name": "Reverse Image Batch"}, + "ReplaceImagesInBatch": {"class": ReplaceImagesInBatch, "name": "Replace Images In Batch"}, + "SaveImageWithAlpha": {"class": SaveImageWithAlpha, "name": "Save Image With Alpha"}, + "SaveImageKJ": {"class": SaveImageKJ, "name": "Save Image KJ"}, + "ShuffleImageBatch": {"class": ShuffleImageBatch, "name": "Shuffle Image Batch"}, + "SplitImageChannels": {"class": SplitImageChannels, "name": "Split Image Channels"}, + "TransitionImagesMulti": {"class": TransitionImagesMulti, "name": "Transition Images Multi"}, + "TransitionImagesInBatch": {"class": TransitionImagesInBatch, "name": "Transition Images In Batch"}, + "EncodeVideoComponents": {"class": EncodeVideoComponents, "name": "Encode Video Components"}, + "DecodeAndSaveVideo": {"class": DecodeAndSaveVideo, "name": "Decode And Save Video"}, + "PreviewImageOrMask": {"class": PreviewImageOrMask, "name": "Preview Image Or Mask"}, + "ImageSharpenKJ": {"class": ImageSharpenKJ, "name": "Image Sharpen KJ"}, + #batch cropping + "BatchCropFromMask": {"class": BatchCropFromMask, "name": "Batch Crop From Mask"}, + "BatchCropFromMaskAdvanced": {"class": BatchCropFromMaskAdvanced, "name": "Batch Crop From Mask Advanced"}, + "FilterZeroMasksAndCorrespondingImages": {"class": FilterZeroMasksAndCorrespondingImages}, + "InsertImageBatchByIndexes": {"class": InsertImageBatchByIndexes, "name": "Insert Image Batch By Indexes"}, + "BatchUncrop": {"class": BatchUncrop, "name": "Batch Uncrop"}, + "BatchUncropAdvanced": {"class": BatchUncropAdvanced, "name": "Batch Uncrop Advanced"}, + "SplitBboxes": {"class": SplitBboxes, "name": "Split Bboxes"}, + "BboxToInt": {"class": BboxToInt, "name": "Bbox To Int"}, + "BboxVisualize": {"class": BboxVisualize, "name": "Bbox Visualize"}, + #noise + "GenerateNoise": {"class": GenerateNoise, "name": "Generate Noise"}, + "FlipSigmasAdjusted": {"class": FlipSigmasAdjusted, "name": "Flip Sigmas Adjusted"}, + "InjectNoiseToLatent": {"class": InjectNoiseToLatent, "name": "Inject Noise To Latent"}, + "CustomSigmas": {"class": CustomSigmas, "name": "Custom Sigmas"}, + #utility + "StringToFloatList": {"class": StringToFloatList, "name": "String to Float List"}, + "WidgetToString": {"class": WidgetToString, "name": "Widget To String"}, + "SaveStringKJ": {"class": SaveStringKJ, "name": "Save String KJ"}, + "DummyOut": {"class": DummyOut, "name": "Dummy Out"}, + "GetLatentsFromBatchIndexed": {"class": GetLatentsFromBatchIndexed, "name": "Get Latents From Batch Indexed"}, + "ScaleBatchPromptSchedule": {"class": ScaleBatchPromptSchedule, "name": "Scale Batch Prompt Schedule"}, + "CameraPoseVisualizer": {"class": CameraPoseVisualizer, "name": "Camera Pose Visualizer"}, + "AppendStringsToList": {"class": AppendStringsToList, "name": "Append Strings To List"}, + "JoinStrings": {"class": JoinStrings, "name": "Join Strings"}, + "JoinStringMulti": {"class": JoinStringMulti, "name": "Join String Multi"}, + "SimpleCalculatorKJ": {"class": SimpleCalculatorKJ, "name": "Simple Calculator KJ"}, + "SomethingToString": {"class": SomethingToString, "name": "Something To String"}, + "Sleep": {"class": Sleep, "name": "Sleep"}, + "VRAM_Debug": {"class": VRAM_Debug, "name": "VRAM Debug"}, + "EmptyLatentImagePresets": {"class": EmptyLatentImagePresets, "name": "Empty Latent Image Presets"}, + "EmptyLatentImageCustomPresets": {"class": EmptyLatentImageCustomPresets, "name": "Empty Latent Image Custom Presets"}, + "ModelPassThrough": {"class": ModelPassThrough, "name": "ModelPass"}, + "ModelSaveKJ": {"class": ModelSaveKJ, "name": "Model Save KJ"}, + "SetShakkerLabsUnionControlNetType": {"class": SetShakkerLabsUnionControlNetType, "name": "Set Shakker Labs Union ControlNet Type"}, + "StyleModelApplyAdvanced": {"class": StyleModelApplyAdvanced, "name": "Style Model Apply Advanced"}, + "DiffusionModelSelector": {"class": DiffusionModelSelector, "name": "Diffusion Model Selector"}, + "LazySwitchKJ": {"class": LazySwitchKJ, "name": "Lazy Switch KJ"}, + "VisualizeSigmasKJ": {"class": VisualizeSigmasKJ, "name": "Visualize Sigmas KJ"}, + #audioscheduler stuff + "NormalizedAmplitudeToMask": {"class": NormalizedAmplitudeToMask}, + "NormalizedAmplitudeToFloatList": {"class": NormalizedAmplitudeToFloatList}, + "OffsetMaskByNormalizedAmplitude": {"class": OffsetMaskByNormalizedAmplitude}, + "ImageTransformByNormalizedAmplitude": {"class": ImageTransformByNormalizedAmplitude}, + "AudioConcatenate": {"class": AudioConcatenate}, + #curve nodes + "SplineEditor": {"class": SplineEditor, "name": "Spline Editor"}, + "CreateShapeImageOnPath": {"class": CreateShapeImageOnPath, "name": "Create Shape Image On Path"}, + "CreateShapeMaskOnPath": {"class": CreateShapeMaskOnPath, "name": "Create Shape Mask On Path"}, + "CreateTextOnPath": {"class": CreateTextOnPath, "name": "Create Text On Path"}, + "CreateGradientFromCoords": {"class": CreateGradientFromCoords, "name": "Create Gradient From Coords"}, + "CutAndDragOnPath": {"class": CutAndDragOnPath, "name": "Cut And Drag On Path"}, + "GradientToFloat": {"class": GradientToFloat, "name": "Gradient To Float"}, + "WeightScheduleExtend": {"class": WeightScheduleExtend, "name": "Weight Schedule Extend"}, + "MaskOrImageToWeight": {"class": MaskOrImageToWeight, "name": "Mask Or Image To Weight"}, + "WeightScheduleConvert": {"class": WeightScheduleConvert, "name": "Weight Schedule Convert"}, + "FloatToMask": {"class": FloatToMask, "name": "Float To Mask"}, + "FloatToSigmas": {"class": FloatToSigmas, "name": "Float To Sigmas"}, + "SigmasToFloat": {"class": SigmasToFloat, "name": "Sigmas To Float"}, + "PlotCoordinates": {"class": PlotCoordinates, "name": "Plot Coordinates"}, + "InterpolateCoords": {"class": InterpolateCoords, "name": "Interpolate Coords"}, + "PointsEditor": {"class": PointsEditor, "name": "Points Editor"}, + #experimental + "SoundReactive": {"class": SoundReactive, "name": "Sound Reactive"}, + "StableZero123_BatchSchedule": {"class": StableZero123_BatchSchedule, "name": "Stable Zero123 Batch Schedule"}, + "SV3D_BatchSchedule": {"class": SV3D_BatchSchedule, "name": "SV3D Batch Schedule"}, + "LoadResAdapterNormalization": {"class": LoadResAdapterNormalization}, + "Superprompt": {"class": Superprompt, "name": "Superprompt"}, + "GLIGENTextBoxApplyBatchCoords": {"class": GLIGENTextBoxApplyBatchCoords}, + "Intrinsic_lora_sampling": {"class": Intrinsic_lora_sampling, "name": "Intrinsic Lora Sampling"}, + "CheckpointPerturbWeights": {"class": CheckpointPerturbWeights, "name": "CheckpointPerturbWeights"}, + "Screencap_mss": {"class": Screencap_mss, "name": "Screencap mss"}, + "ScreencapStream": {"class": ScreencapStream, "name": "Screencap Stream"}, + "WebcamCaptureCV2": {"class": WebcamCaptureCV2, "name": "Webcam Capture CV2"}, + "DifferentialDiffusionAdvanced": {"class": DifferentialDiffusionAdvanced, "name": "Differential Diffusion Advanced"}, + "DiTBlockLoraLoader": {"class": DiTBlockLoraLoader, "name": "DiT Block Lora Loader"}, + "FluxBlockLoraSelect": {"class": FluxBlockLoraSelect, "name": "Flux Block Lora Select"}, + "HunyuanVideoBlockLoraSelect": {"class": HunyuanVideoBlockLoraSelect, "name": "Hunyuan Video Block Lora Select"}, + "Wan21BlockLoraSelect": {"class": Wan21BlockLoraSelect, "name": "Wan21 Block Lora Select"}, + "LTX2BlockLoraSelect": {"class": LTX2BlockLoraSelect, "name": "LTX2 Block Lora Select"}, + "CustomControlNetWeightsFluxFromList": {"class": CustomControlNetWeightsFluxFromList, "name": "Custom ControlNet Weights Flux From List"}, + "CheckpointLoaderKJ": {"class": CheckpointLoaderKJ, "name": "CheckpointLoaderKJ"}, + "DiffusionModelLoaderKJ": {"class": DiffusionModelLoaderKJ, "name": "Diffusion Model Loader KJ"}, + "TorchCompileModelFluxAdvancedV2": {"class": TorchCompileModelFluxAdvancedV2, "name": "TorchCompileModelFluxAdvancedV2"}, + "TorchCompileVAE": {"class": TorchCompileVAE, "name": "TorchCompileVAE"}, + "TorchCompileControlNet": {"class": TorchCompileControlNet, "name": "TorchCompileControlNet"}, + "TorchCompileModelWanVideoV2": {"class": TorchCompileModelWanVideoV2, "name": "TorchCompileModelWanVideoV2"}, + "PathchSageAttentionKJ": {"class": PathchSageAttentionKJ, "name": "Patch Sage Attention KJ"}, + "LeapfusionHunyuanI2VPatcher": {"class": LeapfusionHunyuanI2V, "name": "Leapfusion Hunyuan I2V Patcher"}, + "VAELoaderKJ": {"class": VAELoaderKJ, "name": "VAELoader KJ"}, + "VAEDecodeLoopKJ": {"class": VAEDecodeLoopKJ, "name": "VAE Decode Loop KJ"}, + "ScheduledCFGGuidance": {"class": ScheduledCFGGuidance, "name": "Scheduled CFG Guidance"}, + "ApplyRifleXRoPE_HunuyanVideo": {"class": ApplyRifleXRoPE_HunuyanVideo, "name": "Apply RifleXRoPE HunuyanVideo"}, + "ApplyRifleXRoPE_WanVideo": {"class": ApplyRifleXRoPE_WanVideo, "name": "Apply RifleXRoPE WanVideo"}, + "WanVideoTeaCacheKJ": {"class": WanVideoTeaCacheKJ, "name": "WanVideo Tea Cache (native)"}, + "WanVideoEnhanceAVideoKJ": {"class": WanVideoEnhanceAVideoKJ, "name": "WanVideo Enhance A Video (native)"}, + "SkipLayerGuidanceWanVideo": {"class": SkipLayerGuidanceWanVideo, "name": "Skip Layer Guidance WanVideo"}, + "TimerNodeKJ": {"class": TimerNodeKJ, "name": "Timer Node KJ"}, + "HunyuanVideoEncodeKeyframesToCond": {"class": HunyuanVideoEncodeKeyframesToCond, "name": "HunyuanVideo Encode Keyframes To Cond"}, + "CFGZeroStarAndInit": {"class": CFGZeroStarAndInit, "name": "CFG Zero Star/Init"}, + "ModelPatchTorchSettings": {"class": ModelPatchTorchSettings, "name": "Model Patch Torch Settings"}, + "WanVideoNAG": {"class": WanVideoNAG, "name": "WanVideoNAG"}, + "GGUFLoaderKJ": {"class": GGUFLoaderKJ, "name": "GGUF Loader KJ"}, + "LatentInpaintTTM": {"class": LatentInpaintTTM, "name": "Latent Inpaint TTM"}, + "NABLA_AttentionKJ": {"class": NABLA_AttentionKJ, "name": "NABLA Attention KJ"}, + "TorchCompileModelAdvanced": {"class": TorchCompileModelAdvanced, "name": "TorchCompileModelAdvanced"}, + "StartRecordCUDAMemoryHistory": {"class": StartRecordCUDAMemoryHistory, "name": "Start Recording CUDAMemory History"}, + "EndRecordCUDAMemoryHistory": {"class": EndRecordCUDAMemoryHistory, "name": "End Recording CUDAMemory History"}, + "VisualizeCUDAMemoryHistory": {"class": VisualizeCUDAMemoryHistory, "name": "Visualize CUDAMemory History"}, + "PreviewLatentNoiseMask": {"class": PreviewLatentNoiseMask, "name": "Preview Latent Noise Mask"}, + "ModelMemoryUseReportPatch": {"class": ModelMemoryUseReportPatch, "name": "Model Memory Use Report Patch"}, + "ModelMemoryUsageFactorOverride": {"class": ModelMemoryUsageFactorOverride, "name": "Model Memory Usage Factor Override"}, + "WanChunkFeedForward": {"class": WanChunkFeedForward, "name": "Wan ChunkFeedForward"}, + "SamplerSelfRefineVideo": {"class": SamplerSelfRefineVideo, "name": "Sampler SelfRefineVideo"}, + "PlaySoundKJ": {"class": PlaySoundKJ, "name": "Play Sound KJ"}, + + #instance diffusion + "CreateInstanceDiffusionTracking": {"class": CreateInstanceDiffusionTracking}, + "AppendInstanceDiffusionTracking": {"class": AppendInstanceDiffusionTracking}, + "DrawInstanceDiffusionTracking": {"class": DrawInstanceDiffusionTracking}, + + #lora + "LoraExtractKJ": {"class": LoraExtractKJ, "name": "LoraExtractKJ"}, + "LoraReduceRankKJ": {"class": LoraReduceRank, "name": "LoraReduceRank"}, + + #tracks + "GetTrackRange": {"class": GetTrackRange, "name": "Get Track Range"}, + "AddNoiseToTrackPath": {"class": AddNoiseToTrackPath, "name": "Add Noise To Track"}, + + # deprecated + "PatchModelPatcherOrder": {"class": PatchModelPatcherOrder, "name": "Patch Model Patcher Order"}, + "TorchCompileModelFluxAdvanced": {"class": DeprecatedCompileNodeKJ, "name": "TorchCompileModelFluxAdvanced"}, + "TorchCompileLTXModel": {"class": DeprecatedCompileNodeKJ, "name": "TorchCompileLTXModel"}, + "TorchCompileCosmosModel": {"class": DeprecatedCompileNodeKJ, "name": "TorchCompileCosmosModel"}, + "TorchCompileModelHyVideo": {"class": DeprecatedCompileNodeKJ, "name": "TorchCompileModelHyVideo"}, + "TorchCompileModelQwenImage": {"class": DeprecatedCompileNodeKJ, "name": "TorchCompileModelQwenImage"}, + "TorchCompileModelWanVideo": {"class": DeprecatedCompileNodeKJ, "name": "TorchCompileModelWanVideo"}, +} + +#ltxv +try: + from .nodes.ltxv_nodes import * + NODE_CONFIG.update({ + "LTXVEnhanceAVideoKJ": {"class": LTXVEnhanceAVideoKJ, "name": "LTXV Enhance A Video KJ"}, + "LTXVAddGuideMulti": {"class": LTXVAddGuideMulti, "name": "LTXV Add Guide Multi"}, + "LTXVAddGuidesFromBatch": {"class": LTXVAddGuidesFromBatch, "name": "LTXV Add Guides From Batch"}, + "LTXVAudioVideoMask": {"class": LTXVAudioVideoMask, "name": "LTXV Audio Video Mask"}, + "LTX2_NAG": {"class": LTX2_NAG, "name": "LTX2 NAG"}, + "LTXVChunkFeedForward": {"class": LTXVChunkFeedForward, "name": "LTXV Chunk Feed Forward"}, + "LTX2SamplingPreviewOverride": {"class": LTX2SamplingPreviewOverride, "name": "LTX2 Sampling Preview Override"}, + "LTX2AudioLatentNormalizingSampling": {"class": LTX2AudioLatentNormalizingSampling, "name": "LTX2 Audio Latent Normalizing Sampling"}, + "LTXVImgToVideoInplaceKJ": {"class": LTXVImgToVideoInplaceKJ, "name": "LTXV Img To Video Inplace KJ"}, + "LTX2AttentionTunerPatch": {"class": LTX2AttentionTunerPatch, "name": "LTX2 Attention Tuner Patch"}, + "LTX2MemoryEfficientSageAttentionPatch": {"class": LTX2MemoryEfficientSageAttentionPatch, "name": "LTX2 Memory Efficient Sage Attention Patch"}, + "LTX2LoraLoaderAdvanced": {"class": LTX2LoraLoaderAdvanced, "name": "LTX2 Lora Loader Advanced"}, + }) +except Exception as e: + logging.warning(f"KJNodes: LTXV nodes could not be imported. LTXV nodes will be unavailable. Error: {e}") + +def generate_node_mappings(node_config): + node_class_mappings = {} + node_display_name_mappings = {} + + for node_name, node_info in node_config.items(): + node_class_mappings[node_name] = node_info["class"] + node_display_name_mappings[node_name] = node_info.get("name", node_info["class"].__name__) + + return node_class_mappings, node_display_name_mappings + +NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS = generate_node_mappings(NODE_CONFIG) + +__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"] + +WEB_DIRECTORY = "./web" + +from aiohttp import web +from server import PromptServer +from pathlib import Path + +if hasattr(PromptServer, "instance"): + try: + # NOTE: we add an extra static path to avoid comfy mechanism + # that loads every script in web. + PromptServer.instance.app.add_routes( + [web.static("/kjweb_async", (Path(__file__).parent.absolute() / "kjweb_async").as_posix())] + ) + except: + pass diff --git a/.disabled/comfyui-kjnodes@nightly/docs/images/319121566-05f66385-7568-4b1f-8bbc-11053660b02f.png b/.disabled/comfyui-kjnodes@nightly/docs/images/319121566-05f66385-7568-4b1f-8bbc-11053660b02f.png new file mode 100644 index 0000000000000000000000000000000000000000..e749239c1c4ffd5ab29b51695dd8d8b51ed3597f Binary files /dev/null and b/.disabled/comfyui-kjnodes@nightly/docs/images/319121566-05f66385-7568-4b1f-8bbc-11053660b02f.png differ diff --git a/.disabled/comfyui-kjnodes@nightly/docs/images/319121636-706b5081-9120-4a29-bd76-901691ada688.png b/.disabled/comfyui-kjnodes@nightly/docs/images/319121636-706b5081-9120-4a29-bd76-901691ada688.png new file mode 100644 index 0000000000000000000000000000000000000000..b53ad666ff060d87971f3962e74101f0cb2a5c3f Binary files /dev/null and b/.disabled/comfyui-kjnodes@nightly/docs/images/319121636-706b5081-9120-4a29-bd76-901691ada688.png differ diff --git a/.disabled/comfyui-kjnodes@nightly/example_workflows/leapfusion_hunyuuanvideo_i2v_native_testing.json b/.disabled/comfyui-kjnodes@nightly/example_workflows/leapfusion_hunyuuanvideo_i2v_native_testing.json new file mode 100644 index 0000000000000000000000000000000000000000..d30084c4739706174d9a5c66893d42bafb110c8f --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/example_workflows/leapfusion_hunyuuanvideo_i2v_native_testing.json @@ -0,0 +1,1188 @@ +{ + "last_node_id": 86, + "last_link_id": 144, + "nodes": [ + { + "id": 62, + "type": "FluxGuidance", + "pos": [ + -630, + -170 + ], + "size": [ + 317.4000244140625, + 58 + ], + "flags": {}, + "order": 13, + "mode": 0, + "inputs": [ + { + "name": "conditioning", + "type": "CONDITIONING", + "link": 82 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 83 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "FluxGuidance" + }, + "widgets_values": [ + 6 + ] + }, + { + "id": 51, + "type": "KSamplerSelect", + "pos": [ + -610, + -480 + ], + "size": [ + 315, + 58 + ], + "flags": {}, + "order": 0, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "SAMPLER", + "type": "SAMPLER", + "links": [ + 61 + ] + } + ], + "properties": { + "Node name for S&R": "KSamplerSelect" + }, + "widgets_values": [ + "euler" + ] + }, + { + "id": 57, + "type": "VAEDecodeTiled", + "pos": [ + -200, + 90 + ], + "size": [ + 315, + 150 + ], + "flags": {}, + "order": 20, + "mode": 0, + "inputs": [ + { + "name": "samples", + "type": "LATENT", + "link": 142 + }, + { + "name": "vae", + "type": "VAE", + "link": 74 + } + ], + "outputs": [ + { + "name": "IMAGE", + "type": "IMAGE", + "links": [ + 105 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "VAEDecodeTiled" + }, + "widgets_values": [ + 128, + 64, + 64, + 8 + ] + }, + { + "id": 65, + "type": "LoadImage", + "pos": [ + -2212.498779296875, + -632.4085083007812 + ], + "size": [ + 315, + 314 + ], + "flags": {}, + "order": 1, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "IMAGE", + "type": "IMAGE", + "links": [ + 86 + ], + "slot_index": 0 + }, + { + "name": "MASK", + "type": "MASK", + "links": null + } + ], + "properties": { + "Node name for S&R": "LoadImage" + }, + "widgets_values": [ + "Mona-Lisa-oil-wood-panel-Leonardo-da.webp", + "image" + ] + }, + { + "id": 64, + "type": "VAEEncode", + "pos": [ + -1336.7884521484375, + -492.5806884765625 + ], + "size": [ + 210, + 46 + ], + "flags": {}, + "order": 14, + "mode": 0, + "inputs": [ + { + "name": "pixels", + "type": "IMAGE", + "link": 144 + }, + { + "name": "vae", + "type": "VAE", + "link": 88 + } + ], + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "links": [ + 137 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "VAEEncode" + }, + "widgets_values": [] + }, + { + "id": 44, + "type": "UNETLoader", + "pos": [ + -2373.55029296875, + -193.91510009765625 + ], + "size": [ + 459.56060791015625, + 82 + ], + "flags": {}, + "order": 2, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [ + 135 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "UNETLoader" + }, + "widgets_values": [ + "hyvideo\\hunyuan_video_720_fp8_e4m3fn.safetensors", + "fp8_e4m3fn_fast" + ] + }, + { + "id": 49, + "type": "VAELoader", + "pos": [ + -1876.39306640625, + -35.19633865356445 + ], + "size": [ + 433.7603454589844, + 58.71116256713867 + ], + "flags": {}, + "order": 3, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "VAE", + "type": "VAE", + "links": [ + 74, + 88 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "VAELoader" + }, + "widgets_values": [ + "hyvid\\hunyuan_video_vae_bf16.safetensors" + ] + }, + { + "id": 47, + "type": "DualCLIPLoader", + "pos": [ + -2284.893798828125, + 150.4042205810547 + ], + "size": [ + 343.3958435058594, + 106.86042785644531 + ], + "flags": {}, + "order": 4, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "CLIP", + "type": "CLIP", + "links": [ + 56 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "DualCLIPLoader" + }, + "widgets_values": [ + "clip_l.safetensors", + "llava_llama3_fp16.safetensors", + "hunyuan_video", + "default" + ] + }, + { + "id": 45, + "type": "CLIPTextEncode", + "pos": [ + -1839.1649169921875, + 143.5203094482422 + ], + "size": [ + 400, + 200 + ], + "flags": {}, + "order": 8, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 56 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 69, + 82 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "CLIPTextEncode" + }, + "widgets_values": [ + "woman puts on sunglasses" + ] + }, + { + "id": 53, + "type": "EmptyHunyuanLatentVideo", + "pos": [ + -1120, + 90 + ], + "size": [ + 315, + 130 + ], + "flags": {}, + "order": 10, + "mode": 0, + "inputs": [ + { + "name": "width", + "type": "INT", + "link": 89, + "widget": { + "name": "width" + } + }, + { + "name": "height", + "type": "INT", + "link": 90, + "widget": { + "name": "height" + } + } + ], + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "links": [ + 119 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "EmptyHunyuanLatentVideo" + }, + "widgets_values": [ + 960, + 544, + 65, + 1 + ] + }, + { + "id": 55, + "type": "ConditioningZeroOut", + "pos": [ + -910, + 300 + ], + "size": [ + 251.14309692382812, + 26 + ], + "flags": { + "collapsed": true + }, + "order": 12, + "mode": 0, + "inputs": [ + { + "name": "conditioning", + "type": "CONDITIONING", + "link": 69 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": [ + 70 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "ConditioningZeroOut" + }, + "widgets_values": [] + }, + { + "id": 52, + "type": "BasicScheduler", + "pos": [ + -600, + -350 + ], + "size": [ + 315, + 106 + ], + "flags": {}, + "order": 17, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 78 + } + ], + "outputs": [ + { + "name": "SIGMAS", + "type": "SIGMAS", + "links": [ + 62 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "BasicScheduler" + }, + "widgets_values": [ + "simple", + 20, + 1 + ] + }, + { + "id": 42, + "type": "SamplerCustom", + "pos": [ + -640, + 10 + ], + "size": [ + 355.20001220703125, + 467.4666748046875 + ], + "flags": {}, + "order": 18, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 77 + }, + { + "name": "positive", + "type": "CONDITIONING", + "link": 83 + }, + { + "name": "negative", + "type": "CONDITIONING", + "link": 70 + }, + { + "name": "sampler", + "type": "SAMPLER", + "link": 61 + }, + { + "name": "sigmas", + "type": "SIGMAS", + "link": 62 + }, + { + "name": "latent_image", + "type": "LATENT", + "link": 119 + } + ], + "outputs": [ + { + "name": "output", + "type": "LATENT", + "links": null + }, + { + "name": "denoised_output", + "type": "LATENT", + "links": [ + 141 + ], + "slot_index": 1 + } + ], + "properties": { + "Node name for S&R": "SamplerCustom" + }, + "widgets_values": [ + true, + 6, + "fixed", + 1, + null + ] + }, + { + "id": 84, + "type": "GetLatentRangeFromBatch", + "pos": [ + -240, + -100 + ], + "size": [ + 340.20001220703125, + 82 + ], + "flags": {}, + "order": 19, + "mode": 0, + "inputs": [ + { + "name": "latents", + "type": "LATENT", + "link": 141 + } + ], + "outputs": [ + { + "name": "LATENT", + "type": "LATENT", + "links": [ + 142 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "GetLatentRangeFromBatch" + }, + "widgets_values": [ + 1, + -1 + ] + }, + { + "id": 50, + "type": "VHS_VideoCombine", + "pos": [ + 165.77645874023438, + -619.0606079101562 + ], + "size": [ + 1112.6898193359375, + 1076.4598388671875 + ], + "flags": {}, + "order": 21, + "mode": 0, + "inputs": [ + { + "name": "images", + "type": "IMAGE", + "link": 105 + }, + { + "name": "audio", + "type": "AUDIO", + "link": null, + "shape": 7 + }, + { + "name": "meta_batch", + "type": "VHS_BatchManager", + "link": null, + "shape": 7 + }, + { + "name": "vae", + "type": "VAE", + "link": null, + "shape": 7 + } + ], + "outputs": [ + { + "name": "Filenames", + "type": "VHS_FILENAMES", + "links": null + } + ], + "properties": { + "Node name for S&R": "VHS_VideoCombine" + }, + "widgets_values": { + "frame_rate": 24, + "loop_count": 0, + "filename_prefix": "hyvidcomfy", + "format": "video/h264-mp4", + "pix_fmt": "yuv420p", + "crf": 19, + "save_metadata": true, + "trim_to_audio": false, + "pingpong": false, + "save_output": false, + "videopreview": { + "hidden": false, + "paused": false, + "params": { + "filename": "hyvidcomfy_00001.mp4", + "subfolder": "", + "type": "temp", + "format": "video/h264-mp4", + "frame_rate": 24, + "workflow": "hyvidcomfy_00001.png", + "fullpath": "N:\\AI\\ComfyUI\\temp\\hyvidcomfy_00001.mp4" + }, + "muted": false + } + } + }, + { + "id": 54, + "type": "ModelSamplingSD3", + "pos": [ + -1079.9112548828125, + -146.69448852539062 + ], + "size": [ + 315, + 58 + ], + "flags": {}, + "order": 16, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 117 + } + ], + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [ + 77, + 78 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "ModelSamplingSD3" + }, + "widgets_values": [ + 9 + ] + }, + { + "id": 80, + "type": "PathchSageAttentionKJ", + "pos": [ + -2273.926513671875, + -36.720542907714844 + ], + "size": [ + 315, + 58 + ], + "flags": {}, + "order": 7, + "mode": 4, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 135 + } + ], + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [ + 136 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "PathchSageAttentionKJ" + }, + "widgets_values": [ + "auto" + ] + }, + { + "id": 85, + "type": "Note", + "pos": [ + -1838.572265625, + -302.1575927734375 + ], + "size": [ + 408.4594421386719, + 58 + ], + "flags": {}, + "order": 5, + "mode": 0, + "inputs": [], + "outputs": [], + "properties": {}, + "widgets_values": [ + "https://huggingface.co/Kijai/Leapfusion-image2vid-comfy/blob/main/leapfusion_img2vid544p_comfy.safetensors" + ], + "color": "#432", + "bgcolor": "#653" + }, + { + "id": 74, + "type": "LeapfusionHunyuanI2VPatcher", + "pos": [ + -1059.552978515625, + -459.34674072265625 + ], + "size": [ + 277.3238525390625, + 150 + ], + "flags": {}, + "order": 15, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 123 + }, + { + "name": "latent", + "type": "LATENT", + "link": 137 + } + ], + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [ + 117 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "LeapfusionHunyuanI2VPatcher" + }, + "widgets_values": [ + 0, + 0, + 1, + 0.8 + ] + }, + { + "id": 59, + "type": "LoraLoaderModelOnly", + "pos": [ + -1870.3748779296875, + -194.6091766357422 + ], + "size": [ + 442.8438720703125, + 82 + ], + "flags": {}, + "order": 11, + "mode": 0, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 136 + } + ], + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [ + 123 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "LoraLoaderModelOnly" + }, + "widgets_values": [ + "hyvid\\musubi-tuner\\img2vid544p.safetensors", + 1 + ] + }, + { + "id": 66, + "type": "ImageResizeKJ", + "pos": [ + -1821.1531982421875, + -632.925048828125 + ], + "size": [ + 315, + 266 + ], + "flags": {}, + "order": 6, + "mode": 0, + "inputs": [ + { + "name": "image", + "type": "IMAGE", + "link": 86 + }, + { + "name": "get_image_size", + "type": "IMAGE", + "link": null, + "shape": 7 + }, + { + "name": "width_input", + "type": "INT", + "link": null, + "widget": { + "name": "width_input" + }, + "shape": 7 + }, + { + "name": "height_input", + "type": "INT", + "link": null, + "widget": { + "name": "height_input" + }, + "shape": 7 + } + ], + "outputs": [ + { + "name": "IMAGE", + "type": "IMAGE", + "links": [ + 143 + ], + "slot_index": 0 + }, + { + "name": "width", + "type": "INT", + "links": [ + 89 + ], + "slot_index": 1 + }, + { + "name": "height", + "type": "INT", + "links": [ + 90 + ], + "slot_index": 2 + } + ], + "properties": { + "Node name for S&R": "ImageResizeKJ" + }, + "widgets_values": [ + 960, + 640, + "lanczos", + false, + 2, + 0, + 0, + "center" + ] + }, + { + "id": 86, + "type": "ImageNoiseAugmentation", + "pos": [ + -1361.111572265625, + -667.0104370117188 + ], + "size": [ + 315, + 106 + ], + "flags": {}, + "order": 9, + "mode": 0, + "inputs": [ + { + "name": "image", + "type": "IMAGE", + "link": 143 + } + ], + "outputs": [ + { + "name": "IMAGE", + "type": "IMAGE", + "links": [ + 144 + ], + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "ImageNoiseAugmentation" + }, + "widgets_values": [ + 0.05, + 123, + "fixed" + ] + } + ], + "links": [ + [ + 56, + 47, + 0, + 45, + 0, + "CLIP" + ], + [ + 61, + 51, + 0, + 42, + 3, + "SAMPLER" + ], + [ + 62, + 52, + 0, + 42, + 4, + "SIGMAS" + ], + [ + 69, + 45, + 0, + 55, + 0, + "CONDITIONING" + ], + [ + 70, + 55, + 0, + 42, + 2, + "CONDITIONING" + ], + [ + 74, + 49, + 0, + 57, + 1, + "VAE" + ], + [ + 77, + 54, + 0, + 42, + 0, + "MODEL" + ], + [ + 78, + 54, + 0, + 52, + 0, + "MODEL" + ], + [ + 82, + 45, + 0, + 62, + 0, + "CONDITIONING" + ], + [ + 83, + 62, + 0, + 42, + 1, + "CONDITIONING" + ], + [ + 86, + 65, + 0, + 66, + 0, + "IMAGE" + ], + [ + 88, + 49, + 0, + 64, + 1, + "VAE" + ], + [ + 89, + 66, + 1, + 53, + 0, + "INT" + ], + [ + 90, + 66, + 2, + 53, + 1, + "INT" + ], + [ + 105, + 57, + 0, + 50, + 0, + "IMAGE" + ], + [ + 117, + 74, + 0, + 54, + 0, + "MODEL" + ], + [ + 119, + 53, + 0, + 42, + 5, + "LATENT" + ], + [ + 123, + 59, + 0, + 74, + 0, + "MODEL" + ], + [ + 135, + 44, + 0, + 80, + 0, + "MODEL" + ], + [ + 136, + 80, + 0, + 59, + 0, + "MODEL" + ], + [ + 137, + 64, + 0, + 74, + 1, + "LATENT" + ], + [ + 141, + 42, + 1, + 84, + 0, + "LATENT" + ], + [ + 142, + 84, + 0, + 57, + 0, + "LATENT" + ], + [ + 143, + 66, + 0, + 86, + 0, + "IMAGE" + ], + [ + 144, + 86, + 0, + 64, + 0, + "IMAGE" + ] + ], + "groups": [], + "config": {}, + "extra": { + "ds": { + "scale": 0.740024994425854, + "offset": [ + 2525.036093151529, + 802.59123935694 + ] + }, + "node_versions": { + "comfy-core": "0.3.13", + "ComfyUI-KJNodes": "a8aeef670b3f288303f956bf94385cb87978ea93", + "ComfyUI-VideoHelperSuite": "c47b10ca1798b4925ff5a5f07d80c51ca80a837d" + }, + "VHS_latentpreview": true, + "VHS_latentpreviewrate": 0 + }, + "version": 0.4 +} \ No newline at end of file diff --git a/.disabled/comfyui-kjnodes@nightly/intrinsic_loras/intrinsic_loras.txt b/.disabled/comfyui-kjnodes@nightly/intrinsic_loras/intrinsic_loras.txt new file mode 100644 index 0000000000000000000000000000000000000000..11572bb08c5c0701f20a2a8eadfcbce17d045488 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/intrinsic_loras/intrinsic_loras.txt @@ -0,0 +1,4 @@ +source for the loras: +https://github.com/duxiaodan/intrinsic-lora + +Renamed and conveted to .safetensors \ No newline at end of file diff --git a/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/audioscheduler_nodes.cpython-310.pyc b/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/audioscheduler_nodes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2b60c3595a71e9e058aabab1ebe4666bad893bf Binary files /dev/null and b/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/audioscheduler_nodes.cpython-310.pyc differ diff --git a/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/batchcrop_nodes.cpython-310.pyc b/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/batchcrop_nodes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6df8919492f316a11762ea419f8519ebdafc527f Binary files /dev/null and b/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/batchcrop_nodes.cpython-310.pyc differ diff --git a/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/curve_nodes.cpython-310.pyc b/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/curve_nodes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db41ad3de43472a4c5eae0229c6b0c47f1ffc3d0 Binary files /dev/null and b/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/curve_nodes.cpython-310.pyc differ diff --git a/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/intrinsic_lora_nodes.cpython-310.pyc b/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/intrinsic_lora_nodes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23a2b53b0f3a0e60940acb0ce4532b5241a9fcb1 Binary files /dev/null and b/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/intrinsic_lora_nodes.cpython-310.pyc differ diff --git a/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/lora_nodes.cpython-310.pyc b/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/lora_nodes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c192ecd30de3f72f60cc0a93eac9587e4934333 Binary files /dev/null and b/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/lora_nodes.cpython-310.pyc differ diff --git a/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/ltxv_nodes.cpython-310.pyc b/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/ltxv_nodes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35fe8fee5fbcbb227e8c47a30562bb380e811a42 Binary files /dev/null and b/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/ltxv_nodes.cpython-310.pyc differ diff --git a/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/mask_nodes.cpython-310.pyc b/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/mask_nodes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ba4b982781cf0ba0be105e194539dd7fc85f85e Binary files /dev/null and b/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/mask_nodes.cpython-310.pyc differ diff --git a/.disabled/comfyui-kjnodes@nightly/nodes/audioscheduler_nodes.py b/.disabled/comfyui-kjnodes@nightly/nodes/audioscheduler_nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..31b65c094b24eb193ff7098e22b9d9f1ea90fc17 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/nodes/audioscheduler_nodes.py @@ -0,0 +1,251 @@ +# to be used with https://github.com/a1lazydog/ComfyUI-AudioScheduler +import torch +from torchvision.transforms import functional as TF +from PIL import Image, ImageDraw +import numpy as np +from ..utility.utility import pil2tensor +from nodes import MAX_RESOLUTION + +class NormalizedAmplitudeToMask: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "normalized_amp": ("NORMALIZED_AMPLITUDE",), + "width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "frame_offset": ("INT", {"default": 0,"min": -255, "max": 255, "step": 1}), + "location_x": ("INT", {"default": 256,"min": 0, "max": 4096, "step": 1}), + "location_y": ("INT", {"default": 256,"min": 0, "max": 4096, "step": 1}), + "size": ("INT", {"default": 128,"min": 8, "max": 4096, "step": 1}), + "shape": ( + [ + 'none', + 'circle', + 'square', + 'triangle', + ], + { + "default": 'none' + }), + "color": ( + [ + 'white', + 'amplitude', + ], + { + "default": 'amplitude' + }), + },} + + CATEGORY = "KJNodes/audio" + RETURN_TYPES = ("MASK",) + FUNCTION = "convert" + DESCRIPTION = """ +Works as a bridge to the AudioScheduler -nodes: +https://github.com/a1lazydog/ComfyUI-AudioScheduler +Creates masks based on the normalized amplitude. +""" + + def convert(self, normalized_amp, width, height, frame_offset, shape, location_x, location_y, size, color): + # Ensure normalized_amp is an array and within the range [0, 1] + normalized_amp = np.clip(normalized_amp, 0.0, 1.0) + + # Offset the amplitude values by rolling the array + normalized_amp = np.roll(normalized_amp, frame_offset) + + # Initialize an empty list to hold the image tensors + out = [] + # Iterate over each amplitude value to create an image + for amp in normalized_amp: + # Scale the amplitude value to cover the full range of grayscale values + if color == 'amplitude': + grayscale_value = int(amp * 255) + elif color == 'white': + grayscale_value = 255 + # Convert the grayscale value to an RGB format + gray_color = (grayscale_value, grayscale_value, grayscale_value) + finalsize = size * amp + + if shape == 'none': + shapeimage = Image.new("RGB", (width, height), gray_color) + else: + shapeimage = Image.new("RGB", (width, height), "black") + + draw = ImageDraw.Draw(shapeimage) + if shape == 'circle' or shape == 'square': + # Define the bounding box for the shape + left_up_point = (location_x - finalsize, location_y - finalsize) + right_down_point = (location_x + finalsize,location_y + finalsize) + two_points = [left_up_point, right_down_point] + + if shape == 'circle': + draw.ellipse(two_points, fill=gray_color) + elif shape == 'square': + draw.rectangle(two_points, fill=gray_color) + + elif shape == 'triangle': + # Define the points for the triangle + left_up_point = (location_x - finalsize, location_y + finalsize) # bottom left + right_down_point = (location_x + finalsize, location_y + finalsize) # bottom right + top_point = (location_x, location_y) # top point + draw.polygon([top_point, left_up_point, right_down_point], fill=gray_color) + + shapeimage = pil2tensor(shapeimage) + mask = shapeimage[:, :, :, 0] + out.append(mask) + + return (torch.cat(out, dim=0),) + +class NormalizedAmplitudeToFloatList: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "normalized_amp": ("NORMALIZED_AMPLITUDE",), + },} + + CATEGORY = "KJNodes/audio" + RETURN_TYPES = ("FLOAT",) + FUNCTION = "convert" + DESCRIPTION = """ +Works as a bridge to the AudioScheduler -nodes: +https://github.com/a1lazydog/ComfyUI-AudioScheduler +Creates a list of floats from the normalized amplitude. +""" + + def convert(self, normalized_amp): + # Ensure normalized_amp is an array and within the range [0, 1] + normalized_amp = np.clip(normalized_amp, 0.0, 1.0) + return (normalized_amp.tolist(),) + +class OffsetMaskByNormalizedAmplitude: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "normalized_amp": ("NORMALIZED_AMPLITUDE",), + "mask": ("MASK",), + "x": ("INT", { "default": 0, "min": -4096, "max": MAX_RESOLUTION, "step": 1, "display": "number" }), + "y": ("INT", { "default": 0, "min": -4096, "max": MAX_RESOLUTION, "step": 1, "display": "number" }), + "rotate": ("BOOLEAN", { "default": False }), + "angle_multiplier": ("FLOAT", { "default": 0.0, "min": -1.0, "max": 1.0, "step": 0.001, "display": "number" }), + } + } + + RETURN_TYPES = ("MASK",) + RETURN_NAMES = ("mask",) + FUNCTION = "offset" + CATEGORY = "KJNodes/audio" + DESCRIPTION = """ +Works as a bridge to the AudioScheduler -nodes: +https://github.com/a1lazydog/ComfyUI-AudioScheduler +Offsets masks based on the normalized amplitude. +""" + + def offset(self, mask, x, y, angle_multiplier, rotate, normalized_amp): + + # Ensure normalized_amp is an array and within the range [0, 1] + offsetmask = mask.clone() + normalized_amp = np.clip(normalized_amp, 0.0, 1.0) + + batch_size, height, width = mask.shape + + if rotate: + for i in range(batch_size): + rotation_amp = int(normalized_amp[i] * (360 * angle_multiplier)) + rotation_angle = rotation_amp + offsetmask[i] = TF.rotate(offsetmask[i].unsqueeze(0), rotation_angle).squeeze(0) + if x != 0 or y != 0: + for i in range(batch_size): + offset_amp = normalized_amp[i] * 10 + shift_x = min(x*offset_amp, width-1) + shift_y = min(y*offset_amp, height-1) + if shift_x != 0: + offsetmask[i] = torch.roll(offsetmask[i], shifts=int(shift_x), dims=1) + if shift_y != 0: + offsetmask[i] = torch.roll(offsetmask[i], shifts=int(shift_y), dims=0) + + return offsetmask, + +class ImageTransformByNormalizedAmplitude: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "normalized_amp": ("NORMALIZED_AMPLITUDE",), + "zoom_scale": ("FLOAT", { "default": 0.0, "min": -1.0, "max": 1.0, "step": 0.001, "display": "number" }), + "x_offset": ("INT", { "default": 0, "min": (1 -MAX_RESOLUTION), "max": MAX_RESOLUTION, "step": 1, "display": "number" }), + "y_offset": ("INT", { "default": 0, "min": (1 -MAX_RESOLUTION), "max": MAX_RESOLUTION, "step": 1, "display": "number" }), + "cumulative": ("BOOLEAN", { "default": False }), + "image": ("IMAGE",), + }} + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "amptransform" + CATEGORY = "KJNodes/audio" + DESCRIPTION = """ +Works as a bridge to the AudioScheduler -nodes: +https://github.com/a1lazydog/ComfyUI-AudioScheduler +Transforms image based on the normalized amplitude. +""" + + def amptransform(self, image, normalized_amp, zoom_scale, cumulative, x_offset, y_offset): + # Ensure normalized_amp is an array and within the range [0, 1] + normalized_amp = np.clip(normalized_amp, 0.0, 1.0) + transformed_images = [] + + # Initialize the cumulative zoom factor + prev_amp = 0.0 + + for i in range(image.shape[0]): + img = image[i] # Get the i-th image in the batch + amp = normalized_amp[i] # Get the corresponding amplitude value + + # Incrementally increase the cumulative zoom factor + if cumulative: + prev_amp += amp + amp += prev_amp + + # Convert the image tensor from BxHxWxC to CxHxW format expected by torchvision + img = img.permute(2, 0, 1) + + # Convert PyTorch tensor to PIL Image for processing + pil_img = TF.to_pil_image(img) + + # Calculate the crop size based on the amplitude + width, height = pil_img.size + crop_size = int(min(width, height) * (1 - amp * zoom_scale)) + crop_size = max(crop_size, 1) + + # Calculate the crop box coordinates (centered crop) + left = (width - crop_size) // 2 + top = (height - crop_size) // 2 + right = (width + crop_size) // 2 + bottom = (height + crop_size) // 2 + + # Crop and resize back to original size + cropped_img = TF.crop(pil_img, top, left, crop_size, crop_size) + resized_img = TF.resize(cropped_img, (height, width)) + + # Convert back to tensor in CxHxW format + tensor_img = TF.to_tensor(resized_img) + + # Convert the tensor back to BxHxWxC format + tensor_img = tensor_img.permute(1, 2, 0) + + # Offset the image based on the amplitude + offset_amp = amp * 10 # Calculate the offset magnitude based on the amplitude + shift_x = min(x_offset * offset_amp, img.shape[1] - 1) # Calculate the shift in x direction + shift_y = min(y_offset * offset_amp, img.shape[0] - 1) # Calculate the shift in y direction + + # Apply the offset to the image tensor + if shift_x != 0: + tensor_img = torch.roll(tensor_img, shifts=int(shift_x), dims=1) + if shift_y != 0: + tensor_img = torch.roll(tensor_img, shifts=int(shift_y), dims=0) + + # Add to the list + transformed_images.append(tensor_img) + + # Stack all transformed images into a batch + transformed_batch = torch.stack(transformed_images) + + return (transformed_batch,) \ No newline at end of file diff --git a/.disabled/comfyui-kjnodes@nightly/nodes/batchcrop_nodes.py b/.disabled/comfyui-kjnodes@nightly/nodes/batchcrop_nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..c5db2202712abc4b7c5cb28472bd19c72e6533e9 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/nodes/batchcrop_nodes.py @@ -0,0 +1,768 @@ +from ..utility.utility import tensor2pil, pil2tensor +from PIL import Image, ImageDraw, ImageFilter +import numpy as np +import torch +from torchvision.transforms import Resize, CenterCrop, InterpolationMode +import math + +#based on nodes from mtb https://github.com/melMass/comfy_mtb + +def bbox_to_region(bbox, target_size=None): + bbox = bbox_check(bbox, target_size) + return (bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3]) + +def bbox_check(bbox, target_size=None): + if not target_size: + return bbox + + new_bbox = ( + bbox[0], + bbox[1], + min(target_size[0] - bbox[0], bbox[2]), + min(target_size[1] - bbox[1], bbox[3]), + ) + return new_bbox + +class BatchCropFromMask: + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "original_images": ("IMAGE",), + "masks": ("MASK",), + "crop_size_mult": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}), + "bbox_smooth_alpha": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}), + }, + } + + RETURN_TYPES = ( + "IMAGE", + "IMAGE", + "BBOX", + "INT", + "INT", + ) + RETURN_NAMES = ( + "original_images", + "cropped_images", + "bboxes", + "width", + "height", + ) + FUNCTION = "crop" + CATEGORY = "KJNodes/masking" + + def smooth_bbox_size(self, prev_bbox_size, curr_bbox_size, alpha): + if alpha == 0: + return prev_bbox_size + return round(alpha * curr_bbox_size + (1 - alpha) * prev_bbox_size) + + def smooth_center(self, prev_center, curr_center, alpha=0.5): + if alpha == 0: + return prev_center + return ( + round(alpha * curr_center[0] + (1 - alpha) * prev_center[0]), + round(alpha * curr_center[1] + (1 - alpha) * prev_center[1]) + ) + + def crop(self, masks, original_images, crop_size_mult, bbox_smooth_alpha): + + bounding_boxes = [] + cropped_images = [] + + self.max_bbox_width = 0 + self.max_bbox_height = 0 + + # First, calculate the maximum bounding box size across all masks + curr_max_bbox_width = 0 + curr_max_bbox_height = 0 + for mask in masks: + _mask = tensor2pil(mask)[0] + non_zero_indices = np.nonzero(np.array(_mask)) + min_x, max_x = np.min(non_zero_indices[1]), np.max(non_zero_indices[1]) + min_y, max_y = np.min(non_zero_indices[0]), np.max(non_zero_indices[0]) + width = max_x - min_x + height = max_y - min_y + curr_max_bbox_width = max(curr_max_bbox_width, width) + curr_max_bbox_height = max(curr_max_bbox_height, height) + + # Smooth the changes in the bounding box size + self.max_bbox_width = self.smooth_bbox_size(self.max_bbox_width, curr_max_bbox_width, bbox_smooth_alpha) + self.max_bbox_height = self.smooth_bbox_size(self.max_bbox_height, curr_max_bbox_height, bbox_smooth_alpha) + + # Apply the crop size multiplier + self.max_bbox_width = round(self.max_bbox_width * crop_size_mult) + self.max_bbox_height = round(self.max_bbox_height * crop_size_mult) + bbox_aspect_ratio = self.max_bbox_width / self.max_bbox_height + + # Then, for each mask and corresponding image... + for i, (mask, img) in enumerate(zip(masks, original_images)): + _mask = tensor2pil(mask)[0] + non_zero_indices = np.nonzero(np.array(_mask)) + min_x, max_x = np.min(non_zero_indices[1]), np.max(non_zero_indices[1]) + min_y, max_y = np.min(non_zero_indices[0]), np.max(non_zero_indices[0]) + + # Calculate center of bounding box + center_x = np.mean(non_zero_indices[1]) + center_y = np.mean(non_zero_indices[0]) + curr_center = (round(center_x), round(center_y)) + + # If this is the first frame, initialize prev_center with curr_center + if not hasattr(self, 'prev_center'): + self.prev_center = curr_center + + # Smooth the changes in the center coordinates from the second frame onwards + if i > 0: + center = self.smooth_center(self.prev_center, curr_center, bbox_smooth_alpha) + else: + center = curr_center + + # Update prev_center for the next frame + self.prev_center = center + + # Create bounding box using max_bbox_width and max_bbox_height + half_box_width = round(self.max_bbox_width / 2) + half_box_height = round(self.max_bbox_height / 2) + min_x = max(0, center[0] - half_box_width) + max_x = min(img.shape[1], center[0] + half_box_width) + min_y = max(0, center[1] - half_box_height) + max_y = min(img.shape[0], center[1] + half_box_height) + + # Append bounding box coordinates + bounding_boxes.append((min_x, min_y, max_x - min_x, max_y - min_y)) + + # Crop the image from the bounding box + cropped_img = img[min_y:max_y, min_x:max_x, :] + + # Calculate the new dimensions while maintaining the aspect ratio + new_height = min(cropped_img.shape[0], self.max_bbox_height) + new_width = round(new_height * bbox_aspect_ratio) + + # Resize the image + resize_transform = Resize((new_height, new_width)) + resized_img = resize_transform(cropped_img.permute(2, 0, 1)) + + # Perform the center crop to the desired size + crop_transform = CenterCrop((self.max_bbox_height, self.max_bbox_width)) # swap the order here if necessary + cropped_resized_img = crop_transform(resized_img) + + cropped_images.append(cropped_resized_img.permute(1, 2, 0)) + + cropped_out = torch.stack(cropped_images, dim=0) + + return (original_images, cropped_out, bounding_boxes, self.max_bbox_width, self.max_bbox_height, ) + +class BatchUncrop: + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "original_images": ("IMAGE",), + "cropped_images": ("IMAGE",), + "bboxes": ("BBOX",), + "border_blending": ("FLOAT", {"default": 0.25, "min": 0.0, "max": 1.0, "step": 0.01}, ), + "crop_rescale": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "border_top": ("BOOLEAN", {"default": True}), + "border_bottom": ("BOOLEAN", {"default": True}), + "border_left": ("BOOLEAN", {"default": True}), + "border_right": ("BOOLEAN", {"default": True}), + } + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "uncrop" + + CATEGORY = "KJNodes/masking" + + def uncrop(self, original_images, cropped_images, bboxes, border_blending, crop_rescale, border_top, border_bottom, border_left, border_right): + def inset_border(image, border_width, border_color, border_top, border_bottom, border_left, border_right): + draw = ImageDraw.Draw(image) + width, height = image.size + if border_top: + draw.rectangle((0, 0, width, border_width), fill=border_color) + if border_bottom: + draw.rectangle((0, height - border_width, width, height), fill=border_color) + if border_left: + draw.rectangle((0, 0, border_width, height), fill=border_color) + if border_right: + draw.rectangle((width - border_width, 0, width, height), fill=border_color) + return image + + if len(original_images) != len(cropped_images): + raise ValueError(f"The number of original_images ({len(original_images)}) and cropped_images ({len(cropped_images)}) should be the same") + + # Ensure there are enough bboxes, but drop the excess if there are more bboxes than images + if len(bboxes) > len(original_images): + print(f"Warning: Dropping excess bounding boxes. Expected {len(original_images)}, but got {len(bboxes)}") + bboxes = bboxes[:len(original_images)] + elif len(bboxes) < len(original_images): + raise ValueError("There should be at least as many bboxes as there are original and cropped images") + + input_images = tensor2pil(original_images) + crop_imgs = tensor2pil(cropped_images) + + out_images = [] + for i in range(len(input_images)): + img = input_images[i] + crop = crop_imgs[i] + bbox = bboxes[i] + + # uncrop the image based on the bounding box + bb_x, bb_y, bb_width, bb_height = bbox + + paste_region = bbox_to_region((bb_x, bb_y, bb_width, bb_height), img.size) + + # scale factors + scale_x = crop_rescale + scale_y = crop_rescale + + # scaled paste_region + paste_region = (round(paste_region[0]*scale_x), round(paste_region[1]*scale_y), round(paste_region[2]*scale_x), round(paste_region[3]*scale_y)) + + # rescale the crop image to fit the paste_region + crop = crop.resize((round(paste_region[2]-paste_region[0]), round(paste_region[3]-paste_region[1]))) + crop_img = crop.convert("RGB") + + if border_blending > 1.0: + border_blending = 1.0 + elif border_blending < 0.0: + border_blending = 0.0 + + blend_ratio = (max(crop_img.size) / 2) * float(border_blending) + + blend = img.convert("RGBA") + mask = Image.new("L", img.size, 0) + + mask_block = Image.new("L", (paste_region[2]-paste_region[0], paste_region[3]-paste_region[1]), 255) + mask_block = inset_border(mask_block, round(blend_ratio / 2), (0), border_top, border_bottom, border_left, border_right) + + mask.paste(mask_block, paste_region) + blend.paste(crop_img, paste_region) + + mask = mask.filter(ImageFilter.BoxBlur(radius=blend_ratio / 4)) + mask = mask.filter(ImageFilter.GaussianBlur(radius=blend_ratio / 4)) + + blend.putalpha(mask) + img = Image.alpha_composite(img.convert("RGBA"), blend) + out_images.append(img.convert("RGB")) + + return (pil2tensor(out_images),) + +class BatchCropFromMaskAdvanced: + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "original_images": ("IMAGE",), + "masks": ("MASK",), + "crop_size_mult": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "bbox_smooth_alpha": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}), + }, + } + + RETURN_TYPES = ( + "IMAGE", + "IMAGE", + "MASK", + "IMAGE", + "MASK", + "BBOX", + "BBOX", + "INT", + "INT", + ) + RETURN_NAMES = ( + "original_images", + "cropped_images", + "cropped_masks", + "combined_crop_image", + "combined_crop_masks", + "bboxes", + "combined_bounding_box", + "bbox_width", + "bbox_height", + ) + FUNCTION = "crop" + CATEGORY = "KJNodes/masking" + + def smooth_bbox_size(self, prev_bbox_size, curr_bbox_size, alpha): + return round(alpha * curr_bbox_size + (1 - alpha) * prev_bbox_size) + + def smooth_center(self, prev_center, curr_center, alpha=0.5): + return (round(alpha * curr_center[0] + (1 - alpha) * prev_center[0]), + round(alpha * curr_center[1] + (1 - alpha) * prev_center[1])) + + def crop(self, masks, original_images, crop_size_mult, bbox_smooth_alpha): + bounding_boxes = [] + combined_bounding_box = [] + cropped_images = [] + cropped_masks = [] + cropped_masks_out = [] + combined_crop_out = [] + combined_cropped_images = [] + combined_cropped_masks = [] + + def calculate_bbox(mask): + non_zero_indices = np.nonzero(np.array(mask)) + + # handle empty masks + min_x, max_x, min_y, max_y = 0, 0, 0, 0 + if len(non_zero_indices[1]) > 0 and len(non_zero_indices[0]) > 0: + min_x, max_x = np.min(non_zero_indices[1]), np.max(non_zero_indices[1]) + min_y, max_y = np.min(non_zero_indices[0]), np.max(non_zero_indices[0]) + + width = max_x - min_x + height = max_y - min_y + bbox_size = max(width, height) + return min_x, max_x, min_y, max_y, bbox_size + + combined_mask = torch.max(masks, dim=0)[0] + _mask = tensor2pil(combined_mask)[0] + new_min_x, new_max_x, new_min_y, new_max_y, combined_bbox_size = calculate_bbox(_mask) + center_x = (new_min_x + new_max_x) / 2 + center_y = (new_min_y + new_max_y) / 2 + half_box_size = round(combined_bbox_size // 2) + new_min_x = max(0, round(center_x - half_box_size)) + new_max_x = min(original_images[0].shape[1], round(center_x + half_box_size)) + new_min_y = max(0, round(center_y - half_box_size)) + new_max_y = min(original_images[0].shape[0], round(center_y + half_box_size)) + + combined_bounding_box.append((new_min_x, new_min_y, new_max_x - new_min_x, new_max_y - new_min_y)) + + self.max_bbox_size = 0 + + # First, calculate the maximum bounding box size across all masks + curr_max_bbox_size = max(calculate_bbox(tensor2pil(mask)[0])[-1] for mask in masks) + # Smooth the changes in the bounding box size + self.max_bbox_size = self.smooth_bbox_size(self.max_bbox_size, curr_max_bbox_size, bbox_smooth_alpha) + # Apply the crop size multiplier + self.max_bbox_size = round(self.max_bbox_size * crop_size_mult) + # Make sure max_bbox_size is divisible by 16, if not, round it upwards so it is + self.max_bbox_size = math.ceil(self.max_bbox_size / 16) * 16 + + if self.max_bbox_size > original_images[0].shape[0] or self.max_bbox_size > original_images[0].shape[1]: + # max_bbox_size can only be as big as our input's width or height, and it has to be even + self.max_bbox_size = math.floor(min(original_images[0].shape[0], original_images[0].shape[1]) / 2) * 2 + + # Then, for each mask and corresponding image... + for i, (mask, img) in enumerate(zip(masks, original_images)): + _mask = tensor2pil(mask)[0] + non_zero_indices = np.nonzero(np.array(_mask)) + + # check for empty masks + if len(non_zero_indices[0]) > 0 and len(non_zero_indices[1]) > 0: + min_x, max_x = np.min(non_zero_indices[1]), np.max(non_zero_indices[1]) + min_y, max_y = np.min(non_zero_indices[0]), np.max(non_zero_indices[0]) + + # Calculate center of bounding box + center_x = np.mean(non_zero_indices[1]) + center_y = np.mean(non_zero_indices[0]) + curr_center = (round(center_x), round(center_y)) + + # If this is the first frame, initialize prev_center with curr_center + if not hasattr(self, 'prev_center'): + self.prev_center = curr_center + + # Smooth the changes in the center coordinates from the second frame onwards + if i > 0: + center = self.smooth_center(self.prev_center, curr_center, bbox_smooth_alpha) + else: + center = curr_center + + # Update prev_center for the next frame + self.prev_center = center + + # Create bounding box using max_bbox_size + half_box_size = self.max_bbox_size // 2 + min_x = max(0, center[0] - half_box_size) + max_x = min(img.shape[1], center[0] + half_box_size) + min_y = max(0, center[1] - half_box_size) + max_y = min(img.shape[0], center[1] + half_box_size) + + # Append bounding box coordinates + bounding_boxes.append((min_x, min_y, max_x - min_x, max_y - min_y)) + + # Crop the image from the bounding box + cropped_img = img[min_y:max_y, min_x:max_x, :] + cropped_mask = mask[min_y:max_y, min_x:max_x] + + # Resize the cropped image to a fixed size + new_size = max(cropped_img.shape[0], cropped_img.shape[1]) + resize_transform = Resize(new_size, interpolation=InterpolationMode.NEAREST, max_size=max(img.shape[0], img.shape[1])) + resized_mask = resize_transform(cropped_mask.unsqueeze(0).unsqueeze(0)).squeeze(0).squeeze(0) + resized_img = resize_transform(cropped_img.permute(2, 0, 1)) + # Perform the center crop to the desired size + # Constrain the crop to the smaller of our bbox or our image so we don't expand past the image dimensions. + crop_transform = CenterCrop((min(self.max_bbox_size, resized_img.shape[1]), min(self.max_bbox_size, resized_img.shape[2]))) + + cropped_resized_img = crop_transform(resized_img) + cropped_images.append(cropped_resized_img.permute(1, 2, 0)) + + cropped_resized_mask = crop_transform(resized_mask) + cropped_masks.append(cropped_resized_mask) + + combined_cropped_img = original_images[i][new_min_y:new_max_y, new_min_x:new_max_x, :] + combined_cropped_images.append(combined_cropped_img) + + combined_cropped_mask = masks[i][new_min_y:new_max_y, new_min_x:new_max_x] + combined_cropped_masks.append(combined_cropped_mask) + else: + bounding_boxes.append((0, 0, img.shape[1], img.shape[0])) + cropped_images.append(img) + cropped_masks.append(mask) + combined_cropped_images.append(img) + combined_cropped_masks.append(mask) + + cropped_out = torch.stack(cropped_images, dim=0) + combined_crop_out = torch.stack(combined_cropped_images, dim=0) + cropped_masks_out = torch.stack(cropped_masks, dim=0) + combined_crop_mask_out = torch.stack(combined_cropped_masks, dim=0) + + return (original_images, cropped_out, cropped_masks_out, combined_crop_out, combined_crop_mask_out, bounding_boxes, combined_bounding_box, self.max_bbox_size, self.max_bbox_size) + +class FilterZeroMasksAndCorrespondingImages: + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "masks": ("MASK",), + }, + "optional": { + "original_images": ("IMAGE",), + }, + } + + RETURN_TYPES = ("MASK", "IMAGE", "IMAGE", "INDEXES",) + RETURN_NAMES = ("non_zero_masks_out", "non_zero_mask_images_out", "zero_mask_images_out", "zero_mask_images_out_indexes",) + FUNCTION = "filter" + CATEGORY = "KJNodes/masking" + DESCRIPTION = """ +Filter out all the empty (i.e. all zero) mask in masks +Also filter out all the corresponding images in original_images by indexes if provide + +original_images (optional): If provided, need have same length as masks. +""" + + def filter(self, masks, original_images=None): + non_zero_masks = [] + non_zero_mask_images = [] + zero_mask_images = [] + zero_mask_images_indexes = [] + + masks_num = len(masks) + also_process_images = False + if original_images is not None: + imgs_num = len(original_images) + if len(original_images) == masks_num: + also_process_images = True + else: + print(f"[WARNING] ignore input: original_images, due to number of original_images ({imgs_num}) is not equal to number of masks ({masks_num})") + + for i in range(masks_num): + non_zero_num = np.count_nonzero(np.array(masks[i])) + if non_zero_num > 0: + non_zero_masks.append(masks[i]) + if also_process_images: + non_zero_mask_images.append(original_images[i]) + else: + zero_mask_images.append(original_images[i]) + zero_mask_images_indexes.append(i) + + non_zero_masks_out = torch.stack(non_zero_masks, dim=0) + non_zero_mask_images_out = zero_mask_images_out = zero_mask_images_out_indexes = None + + if also_process_images: + non_zero_mask_images_out = torch.stack(non_zero_mask_images, dim=0) + if len(zero_mask_images) > 0: + zero_mask_images_out = torch.stack(zero_mask_images, dim=0) + zero_mask_images_out_indexes = zero_mask_images_indexes + + return (non_zero_masks_out, non_zero_mask_images_out, zero_mask_images_out, zero_mask_images_out_indexes) + +class InsertImageBatchByIndexes: + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "images": ("IMAGE",), + "images_to_insert": ("IMAGE",), + "insert_indexes": ("INDEXES",), + }, + } + + RETURN_TYPES = ("IMAGE", ) + RETURN_NAMES = ("images_after_insert", ) + FUNCTION = "insert" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +This node is designed to be use with node FilterZeroMasksAndCorrespondingImages +It inserts the images_to_insert into images according to insert_indexes + +Returns: + images_after_insert: updated original images with origonal sequence order +""" + + def insert(self, images, images_to_insert, insert_indexes): + images_after_insert = images + + if images_to_insert is not None and insert_indexes is not None: + images_to_insert_num = len(images_to_insert) + insert_indexes_num = len(insert_indexes) + if images_to_insert_num == insert_indexes_num: + images_after_insert = [] + + i_images = 0 + for i in range(len(images) + images_to_insert_num): + if i in insert_indexes: + images_after_insert.append(images_to_insert[insert_indexes.index(i)]) + else: + images_after_insert.append(images[i_images]) + i_images += 1 + + images_after_insert = torch.stack(images_after_insert, dim=0) + + else: + print(f"[WARNING] skip this node, due to number of images_to_insert ({images_to_insert_num}) is not equal to number of insert_indexes ({insert_indexes_num})") + + + return (images_after_insert, ) + +class BatchUncropAdvanced: + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "original_images": ("IMAGE",), + "cropped_images": ("IMAGE",), + "cropped_masks": ("MASK",), + "combined_crop_mask": ("MASK",), + "bboxes": ("BBOX",), + "border_blending": ("FLOAT", {"default": 0.25, "min": 0.0, "max": 1.0, "step": 0.01}, ), + "crop_rescale": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "use_combined_mask": ("BOOLEAN", {"default": False}), + "use_square_mask": ("BOOLEAN", {"default": True}), + }, + "optional": { + "combined_bounding_box": ("BBOX", {"default": None}), + }, + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "uncrop" + CATEGORY = "KJNodes/masking" + + + def uncrop(self, original_images, cropped_images, cropped_masks, combined_crop_mask, bboxes, border_blending, crop_rescale, use_combined_mask, use_square_mask, combined_bounding_box = None): + + def inset_border(image, border_width=20, border_color=(0)): + width, height = image.size + bordered_image = Image.new(image.mode, (width, height), border_color) + bordered_image.paste(image, (0, 0)) + draw = ImageDraw.Draw(bordered_image) + draw.rectangle((0, 0, width - 1, height - 1), outline=border_color, width=border_width) + return bordered_image + + if len(original_images) != len(cropped_images): + raise ValueError(f"The number of original_images ({len(original_images)}) and cropped_images ({len(cropped_images)}) should be the same") + + # Ensure there are enough bboxes, but drop the excess if there are more bboxes than images + if len(bboxes) > len(original_images): + print(f"Warning: Dropping excess bounding boxes. Expected {len(original_images)}, but got {len(bboxes)}") + bboxes = bboxes[:len(original_images)] + elif len(bboxes) < len(original_images): + raise ValueError("There should be at least as many bboxes as there are original and cropped images") + + crop_imgs = tensor2pil(cropped_images) + input_images = tensor2pil(original_images) + out_images = [] + + for i in range(len(input_images)): + img = input_images[i] + crop = crop_imgs[i] + bbox = bboxes[i] + + if use_combined_mask: + bb_x, bb_y, bb_width, bb_height = combined_bounding_box[0] + paste_region = bbox_to_region((bb_x, bb_y, bb_width, bb_height), img.size) + mask = combined_crop_mask[i] + else: + bb_x, bb_y, bb_width, bb_height = bbox + paste_region = bbox_to_region((bb_x, bb_y, bb_width, bb_height), img.size) + mask = cropped_masks[i] + + # scale paste_region + scale_x = scale_y = crop_rescale + paste_region = (round(paste_region[0]*scale_x), round(paste_region[1]*scale_y), round(paste_region[2]*scale_x), round(paste_region[3]*scale_y)) + + # rescale the crop image to fit the paste_region + crop = crop.resize((round(paste_region[2]-paste_region[0]), round(paste_region[3]-paste_region[1]))) + crop_img = crop.convert("RGB") + + #border blending + if border_blending > 1.0: + border_blending = 1.0 + elif border_blending < 0.0: + border_blending = 0.0 + + blend_ratio = (max(crop_img.size) / 2) * float(border_blending) + blend = img.convert("RGBA") + + if use_square_mask: + mask = Image.new("L", img.size, 0) + mask_block = Image.new("L", (paste_region[2]-paste_region[0], paste_region[3]-paste_region[1]), 255) + mask_block = inset_border(mask_block, round(blend_ratio / 2), (0)) + mask.paste(mask_block, paste_region) + else: + original_mask = tensor2pil(mask)[0] + original_mask = original_mask.resize((paste_region[2]-paste_region[0], paste_region[3]-paste_region[1])) + mask = Image.new("L", img.size, 0) + mask.paste(original_mask, paste_region) + + mask = mask.filter(ImageFilter.BoxBlur(radius=blend_ratio / 4)) + mask = mask.filter(ImageFilter.GaussianBlur(radius=blend_ratio / 4)) + + blend.paste(crop_img, paste_region) + blend.putalpha(mask) + + img = Image.alpha_composite(img.convert("RGBA"), blend) + out_images.append(img.convert("RGB")) + + return (pil2tensor(out_images),) + +class SplitBboxes: + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "bboxes": ("BBOX",), + "index": ("INT", {"default": 0,"min": 0, "max": 99999999, "step": 1}), + }, + } + + RETURN_TYPES = ("BBOX","BBOX",) + RETURN_NAMES = ("bboxes_a","bboxes_b",) + FUNCTION = "splitbbox" + CATEGORY = "KJNodes/masking" + DESCRIPTION = """ +Splits the specified bbox list at the given index into two lists. +""" + + def splitbbox(self, bboxes, index): + bboxes_a = bboxes[:index] # Sub-list from the start of bboxes up to (but not including) the index + bboxes_b = bboxes[index:] # Sub-list from the index to the end of bboxes + + return (bboxes_a, bboxes_b,) + +class BboxToInt: + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "bboxes": ("BBOX",), + "index": ("INT", {"default": 0,"min": 0, "max": 99999999, "step": 1}), + }, + } + + RETURN_TYPES = ("INT","INT","INT","INT","INT","INT",) + RETURN_NAMES = ("x_min","y_min","width","height", "center_x","center_y",) + FUNCTION = "bboxtoint" + CATEGORY = "KJNodes/masking" + DESCRIPTION = """ +Returns selected index from bounding box list as integers. +""" + def bboxtoint(self, bboxes, index): + x_min, y_min, width, height = bboxes[index] + center_x = int(x_min + width / 2) + center_y = int(y_min + height / 2) + + return (x_min, y_min, width, height, center_x, center_y,) + +class BboxVisualize: + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "images": ("IMAGE",), + "bboxes": ("BBOX",), + "line_width": ("INT", {"default": 1,"min": 1, "max": 10, "step": 1}), + "bbox_format": (["xywh", "xyxy"], {"default": "xywh"}), + }, + } + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("images",) + FUNCTION = "visualizebbox" + DESCRIPTION = """ +Visualizes the specified bbox on the image. +""" + + CATEGORY = "KJNodes/masking" + + def visualizebbox(self, bboxes, images, line_width, bbox_format): + image_list = [] + for image, bbox in zip(images, bboxes): + # Ensure bbox is a sequence of 4 values + if isinstance(bbox, (list, tuple, np.ndarray)) and len(bbox) == 4: + if bbox_format == "xywh": + x_min, y_min, width, height = bbox + elif bbox_format == "xyxy": + x_min, y_min, x_max, y_max = bbox + width = x_max - x_min + height = y_max - y_min + else: + raise ValueError(f"Unknown bbox_format: {bbox_format}") + else: + print("Invalid bbox:", bbox) + continue + + # Ensure bbox coordinates are integers + x_min = int(x_min) + y_min = int(y_min) + width = int(width) + height = int(height) + + # Permute the image dimensions + image = image.permute(2, 0, 1) + + # Clone the image to draw bounding boxes + img_with_bbox = image.clone() + + # Define the color for the bbox, e.g., red + color = torch.tensor([1, 0, 0], dtype=torch.float32) + + # Ensure color tensor matches the image channels + if color.shape[0] != img_with_bbox.shape[0]: + color = color.unsqueeze(1).expand(-1, line_width) + + # Draw lines for each side of the bbox with the specified line width + for lw in range(line_width): + # Top horizontal line + if y_min + lw < img_with_bbox.shape[1]: + img_with_bbox[:, y_min + lw, x_min:x_min + width] = color[:, None] + + # Bottom horizontal line + if y_min + height - lw < img_with_bbox.shape[1]: + img_with_bbox[:, y_min + height - lw, x_min:x_min + width] = color[:, None] + + # Left vertical line + if x_min + lw < img_with_bbox.shape[2]: + img_with_bbox[:, y_min:y_min + height, x_min + lw] = color[:, None] + + # Right vertical line + if x_min + width - lw < img_with_bbox.shape[2]: + img_with_bbox[:, y_min:y_min + height, x_min + width - lw] = color[:, None] + + # Permute the image dimensions back + img_with_bbox = img_with_bbox.permute(1, 2, 0).unsqueeze(0) + image_list.append(img_with_bbox) + + return (torch.cat(image_list, dim=0),) \ No newline at end of file diff --git a/.disabled/comfyui-kjnodes@nightly/nodes/curve_nodes.py b/.disabled/comfyui-kjnodes@nightly/nodes/curve_nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..08f065e27d1b3a6cdbb663b953c91dc3ac6923f8 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/nodes/curve_nodes.py @@ -0,0 +1,1645 @@ +import torch +from torchvision import transforms +import json +from PIL import Image, ImageDraw, ImageFont, ImageFilter +import numpy as np +from ..utility.utility import pil2tensor, tensor2pil +import folder_paths +import base64 +from io import BytesIO + + +def parse_color(color): + if isinstance(color, str) and ',' in color: + return tuple(int(c.strip()) for c in color.split(',')) + return color + +def parse_json_tracks(tracks): + tracks_data = [] + try: + # If tracks is a string, try to parse it as JSON + if isinstance(tracks, str): + parsed = json.loads(tracks.replace("'", '"')) + tracks_data.extend(parsed) + else: + # If tracks is a list of strings, parse each one + for track_str in tracks: + parsed = json.loads(track_str.replace("'", '"')) + tracks_data.append(parsed) + + # Check if we have a single track (dict with x,y) or a list of tracks + if tracks_data and isinstance(tracks_data[0], dict) and 'x' in tracks_data[0]: + # Single track detected, wrap it in a list + tracks_data = [tracks_data] + elif tracks_data and isinstance(tracks_data[0], list) and tracks_data[0] and isinstance(tracks_data[0][0], dict) and 'x' in tracks_data[0][0]: + # Already a list of tracks, nothing to do + pass + else: + # Unexpected format + print(f"Warning: Unexpected track format: {type(tracks_data[0])}") + + except json.JSONDecodeError as e: + print(f"Error parsing tracks JSON: {e}") + tracks_data = [] + + return tracks_data + +def plot_coordinates_to_tensor(coordinates, height, width, bbox_height, bbox_width, size_multiplier, prompt): + import matplotlib + matplotlib.use('Agg') + from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas + text_color = '#999999' + bg_color = '#353535' + matplotlib.pyplot.rcParams['text.color'] = text_color + fig, ax = matplotlib.pyplot.subplots(figsize=(width/100, height/100), dpi=100) + fig.patch.set_facecolor(bg_color) + ax.set_facecolor(bg_color) + ax.grid(color=text_color, linestyle='-', linewidth=0.5) + ax.set_xlabel('x', color=text_color) + ax.set_ylabel('y', color=text_color) + for text in ax.get_xticklabels() + ax.get_yticklabels(): + text.set_color(text_color) + ax.set_title('position for: ' + prompt) + ax.set_xlabel('X Coordinate') + ax.set_ylabel('Y Coordinate') + #ax.legend().remove() + ax.set_xlim(0, width) # Set the x-axis to match the input latent width + ax.set_ylim(height, 0) # Set the y-axis to match the input latent height, with (0,0) at top-left + # Adjust the margins of the subplot + matplotlib.pyplot.subplots_adjust(left=0.08, right=0.95, bottom=0.05, top=0.95, wspace=0.2, hspace=0.2) + + cmap = matplotlib.pyplot.get_cmap('rainbow') + image_batch = [] + canvas = FigureCanvas(fig) + width, height = fig.get_size_inches() * fig.get_dpi() + # Draw a box at each coordinate + for i, ((x, y), size) in enumerate(zip(coordinates, size_multiplier)): + color_index = i / (len(coordinates) - 1) + color = cmap(color_index) + draw_height = bbox_height * size + draw_width = bbox_width * size + rect = matplotlib.patches.Rectangle((x - draw_width/2, y - draw_height/2), draw_width, draw_height, + linewidth=1, edgecolor=color, facecolor='none', alpha=0.5) + ax.add_patch(rect) + + # Check if there is a next coordinate to draw an arrow to + if i < len(coordinates) - 1: + x1, y1 = coordinates[i] + x2, y2 = coordinates[i + 1] + ax.annotate("", xy=(x2, y2), xytext=(x1, y1), + arrowprops=dict(arrowstyle="->", + linestyle="-", + lw=1, + color=color, + mutation_scale=20)) + canvas.draw() + try: + image_np = np.frombuffer(canvas.tostring_rgb(), dtype='uint8').reshape(int(height), int(width), 3).copy() + except: + image_np = np.frombuffer(canvas.tostring_argb(), dtype='uint8').reshape(int(height), int(width), 4) + image_np = image_np[:, :, [1, 2, 3]] # Convert ARGB to RGB + image_tensor = torch.from_numpy(image_np).float() / 255.0 + image_tensor = image_tensor.unsqueeze(0) + image_batch.append(image_tensor) + + matplotlib.pyplot.close(fig) + image_batch_tensor = torch.cat(image_batch, dim=0) + + return image_batch_tensor + +class PlotCoordinates: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "coordinates": ("STRING", {"forceInput": True}), + "text": ("STRING", {"default": 'title', "multiline": False}), + "width": ("INT", {"default": 512, "min": 8, "max": 4096, "step": 8}), + "height": ("INT", {"default": 512, "min": 8, "max": 4096, "step": 8}), + "bbox_width": ("INT", {"default": 128, "min": 8, "max": 4096, "step": 8}), + "bbox_height": ("INT", {"default": 128, "min": 8, "max": 4096, "step": 8}), + }, + "optional": {"size_multiplier": ("FLOAT", {"default": [1.0], "forceInput": True})}, + } + RETURN_TYPES = ("IMAGE", "INT", "INT", "INT", "INT",) + RETURN_NAMES = ("images", "width", "height", "bbox_width", "bbox_height",) + FUNCTION = "append" + CATEGORY = "KJNodes/experimental" + DESCRIPTION = """ +Plots coordinates to sequence of images using Matplotlib. + +""" + + def append(self, coordinates, text, width, height, bbox_width, bbox_height, size_multiplier=[1.0]): + coordinates = json.loads(coordinates.replace("'", '"')) + coordinates = [(coord['x'], coord['y']) for coord in coordinates] + batch_size = len(coordinates) + if not size_multiplier or len(size_multiplier) != batch_size: + size_multiplier = [0] * batch_size + else: + size_multiplier = size_multiplier * (batch_size // len(size_multiplier)) + size_multiplier[:batch_size % len(size_multiplier)] + + plot_image_tensor = plot_coordinates_to_tensor(coordinates, height, width, bbox_height, bbox_width, size_multiplier, text) + + return (plot_image_tensor, width, height, bbox_width, bbox_height) + +class SplineEditor: + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "points_store": ("STRING", {"multiline": False, "advanced": True}), + "coordinates": ("STRING", {"multiline": False, "advanced": True}), + "mask_width": ("INT", {"default": 512, "min": 8, "max": 4096, "step": 8}), + "mask_height": ("INT", {"default": 512, "min": 8, "max": 4096, "step": 8}), + "points_to_sample": ("INT", {"default": 16, "min": 2, "max": 1000, "step": 1}), + "sampling_method": ( + [ + 'path', + 'time', + 'controlpoints', + 'speed' + ], + { + "default": 'time' + }), + "interpolation": ( + [ + 'cardinal', + 'monotone', + 'basis', + 'linear', + 'step-before', + 'step-after', + 'polar', + 'polar-reverse', + 'bezier', + ], + { + "default": 'cardinal' + }), + "tension": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}), + "repeat_output": ("INT", {"default": 1, "min": 1, "max": 4096, "step": 1}), + "float_output_type": ( + [ + 'list', + 'pandas series', + 'tensor', + ], + { + "default": 'list' + }), + }, + "optional": { + "min_value": ("FLOAT", {"default": 0.0, "min": -10000.0, "max": 10000.0, "step": 0.01}), + "max_value": ("FLOAT", {"default": 1.0, "min": -10000.0, "max": 10000.0, "step": 0.01}), + "bg_image": ("IMAGE", ), + } + } + + RETURN_TYPES = ("MASK", "STRING", "FLOAT", "INT", "STRING",) + RETURN_NAMES = ("mask", "coord_str", "float", "count", "normalized_str",) + FUNCTION = "splinedata" + CATEGORY = "KJNodes/weights" + DESCRIPTION = """ +# WORK IN PROGRESS +Do not count on this as part of your workflow yet, +probably contains lots of bugs and stability is not +guaranteed!! + +## Graphical editor to create values for various +## schedules and/or mask batches. + +**Shift + click** to add control point at end. +**Ctrl + click** to add control point (subdivide) between two points. +**Right click on a point** to delete it. +Note that you can't delete from start/end. + +Right click on canvas for context menu: +NEW!: +- Add new spline + - Creates a new spline on same canvas, currently these paths are only outputed + as coordinates. +- Add single point + - Creates a single point that only returns it's current position coords +- Delete spline + - Deletes the currently selected spline, you can select a spline by clicking on + it's path, or cycle through them with the 'Next spline' -option. + +These are purely visual options, doesn't affect the output: + - Toggle handles visibility + - Display sample points: display the points to be returned. + +**points_to_sample** value sets the number of samples +returned from the **drawn spline itself**, this is independent from the +actual control points, so the interpolation type matters. +sampling_method: + - time: samples along the time axis, used for schedules + - path: samples along the path itself, useful for coordinates + - controlpoints: samples only the control points themselves + +output types: + - mask batch + example compatible nodes: anything that takes masks + - list of floats + example compatible nodes: IPAdapter weights + - pandas series + example compatible nodes: anything that takes Fizz' + nodes Batch Value Schedule + - torch tensor + example compatible nodes: unknown +""" + + def splinedata(self, mask_width, mask_height, coordinates, float_output_type, interpolation, + points_to_sample, sampling_method, points_store, tension, repeat_output, + min_value=0.0, max_value=1.0, bg_image=None): + + coordinates = json.loads(coordinates) + + # Handle nested list structure if present + all_normalized = [] + all_normalized_y_values = [] + + # Check if we have a nested list structure + if isinstance(coordinates, list) and len(coordinates) > 0 and isinstance(coordinates[0], list): + # Process each list of coordinates in the nested structure + coordinate_sets = coordinates + else: + # If not nested, treat as a single list of coordinates + coordinate_sets = [coordinates] + + first_spline = coordinate_sets[0] if coordinate_sets else [] + + # Process each set of coordinates + for coord_set in coordinate_sets: + normalized = [] + normalized_y_values = [] + + for coord in coord_set: + coord['x'] = int(round(coord['x'])) + coord['y'] = int(round(coord['y'])) + norm_x = (1.0 - (coord['x'] / mask_height) - 0.0) * (max_value - min_value) + min_value + norm_y = (1.0 - (coord['y'] / mask_height) - 0.0) * (max_value - min_value) + min_value + normalized_y_values.append(norm_y) + normalized.append({'x':norm_x, 'y':norm_y}) + + all_normalized.extend(normalized) + all_normalized_y_values.extend(normalized_y_values) + + # Use the combined normalized values for output + if float_output_type == 'list': + out_floats = all_normalized_y_values * repeat_output + elif float_output_type == 'pandas series': + try: + import pandas as pd + except: + raise Exception("MaskOrImageToWeight: pandas is not installed. Please install pandas to use this output_type") + out_floats = pd.Series(all_normalized_y_values * repeat_output), + elif float_output_type == 'tensor': + out_floats = torch.tensor(all_normalized_y_values * repeat_output, dtype=torch.float32) + + # Create a color map for grayscale intensities + color_map = lambda y: torch.full((mask_height, mask_width, 3), y, dtype=torch.float32) + + # Create a color map for grayscale intensities (from first spline only) + color_map = lambda y: torch.full((mask_height, mask_width, 3), y, dtype=torch.float32) + mask_tensors = [color_map(y) for y in normalized_y_values] + masks_out = torch.stack(mask_tensors) + masks_out = masks_out.repeat(repeat_output, 1, 1, 1) + masks_out = masks_out.mean(dim=-1) + + single_spline_count = len(first_spline) + + if bg_image is None: + return (masks_out, json.dumps(coordinates if len(coordinates) > 1 else coordinates[0]), out_floats, single_spline_count, json.dumps(all_normalized)) + else: + transform = transforms.ToPILImage() + image = transform(bg_image[0].permute(2, 0, 1)) + buffered = BytesIO() + image.save(buffered, format="JPEG", quality=75) + + # Encode the image bytes to a Base64 string + img_bytes = buffered.getvalue() + img_base64 = base64.b64encode(img_bytes).decode('utf-8') + + return { + "ui": {"bg_image": [img_base64]}, + "result": (masks_out, json.dumps(coordinates if len(coordinates) > 1 else coordinates[0]), out_floats, single_spline_count, json.dumps(all_normalized)) + } + + +class CreateShapeMaskOnPath: + + RETURN_TYPES = ("MASK", "MASK",) + RETURN_NAMES = ("mask", "mask_inverted",) + FUNCTION = "createshapemask" + CATEGORY = "KJNodes/masking/generate" + DESCRIPTION = """ +Creates a mask or batch of masks with the specified shape. +Locations are center locations. +""" + DEPRECATED = True + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "shape": ( + [ 'circle', + 'square', + 'triangle', + ], + { + "default": 'circle' + }), + "coordinates": ("STRING", {"forceInput": True}), + "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "shape_width": ("INT", {"default": 128,"min": 8, "max": 4096, "step": 1}), + "shape_height": ("INT", {"default": 128,"min": 8, "max": 4096, "step": 1}), + }, + "optional": { + "size_multiplier": ("FLOAT", {"default": [1.0], "forceInput": True}), + } + } + + def createshapemask(self, coordinates, frame_width, frame_height, shape_width, shape_height, shape, size_multiplier=[1.0]): + # Define the number of images in the batch + coordinates = coordinates.replace("'", '"') + coordinates = json.loads(coordinates) + + batch_size = len(coordinates) + out = [] + color = "white" + if not size_multiplier or len(size_multiplier) != batch_size: + size_multiplier = [0] * batch_size + else: + size_multiplier = size_multiplier * (batch_size // len(size_multiplier)) + size_multiplier[:batch_size % len(size_multiplier)] + for i, coord in enumerate(coordinates): + image = Image.new("RGB", (frame_width, frame_height), "black") + draw = ImageDraw.Draw(image) + + # Calculate the size for this frame and ensure it's not less than 0 + current_width = max(0, shape_width + i * size_multiplier[i]) + current_height = max(0, shape_height + i * size_multiplier[i]) + + location_x = coord['x'] + location_y = coord['y'] + + if shape == 'circle' or shape == 'square': + # Define the bounding box for the shape + left_up_point = (location_x - current_width // 2, location_y - current_height // 2) + right_down_point = (location_x + current_width // 2, location_y + current_height // 2) + two_points = [left_up_point, right_down_point] + + if shape == 'circle': + draw.ellipse(two_points, fill=color) + elif shape == 'square': + draw.rectangle(two_points, fill=color) + + elif shape == 'triangle': + # Define the points for the triangle + left_up_point = (location_x - current_width // 2, location_y + current_height // 2) # bottom left + right_down_point = (location_x + current_width // 2, location_y + current_height // 2) # bottom right + top_point = (location_x, location_y - current_height // 2) # top point + draw.polygon([top_point, left_up_point, right_down_point], fill=color) + + image = pil2tensor(image) + mask = image[:, :, :, 0] + out.append(mask) + outstack = torch.cat(out, dim=0) + return (outstack, 1.0 - outstack,) + + + +class CreateShapeImageOnPath: + + RETURN_TYPES = ("IMAGE", "MASK",) + RETURN_NAMES = ("image","mask", ) + FUNCTION = "createshapemask" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Creates an image or batch of images with the specified shape. +Locations are center locations. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "shape": ( + [ 'circle', + 'square', + 'triangle', + ], + { + "default": 'circle' + }), + "coordinates": ("STRING", {"forceInput": True}), + "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "shape_width": ("INT", {"default": 128,"min": 2, "max": 4096, "step": 1}), + "shape_height": ("INT", {"default": 128,"min": 2, "max": 4096, "step": 1}), + "shape_color": ("STRING", {"default": 'white'}), + "bg_color": ("STRING", {"default": 'black'}), + "blur_radius": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 100, "step": 0.1}), + "intensity": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 100.0, "step": 0.01}), + }, + "optional": { + "size_multiplier": ("FLOAT", {"default": [1.0], "forceInput": True}), + "trailing": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "border_width": ("INT", {"default": 0, "min": 0, "max": 100, "step": 1}), + "border_color": ("STRING", {"default": 'black'}), + } + } + + def createshapemask(self, coordinates, frame_width, frame_height, shape_width, shape_height, shape_color, + bg_color, blur_radius, shape, intensity, size_multiplier=[1.0], trailing=1.0, border_width=0, border_color='black'): + + shape_color = parse_color(shape_color) + border_color = parse_color(border_color) + bg_color = parse_color(bg_color) + coords_list = parse_json_tracks(coordinates) + + batch_size = len(coords_list[0]) + images_list = [] + masks_list = [] + + if not size_multiplier or len(size_multiplier) != batch_size: + size_multiplier = [1] * batch_size + else: + size_multiplier = size_multiplier * (batch_size // len(size_multiplier)) + size_multiplier[:batch_size % len(size_multiplier)] + + previous_output = None + + for i in range(batch_size): + image = Image.new("RGB", (frame_width, frame_height), bg_color) + draw = ImageDraw.Draw(image) + + # Calculate the size for this frame and ensure it's not less than 0 + current_width = shape_width * size_multiplier[i] + current_height = shape_height * size_multiplier[i] + + for coords in coords_list: + location_x = coords[i]['x'] + location_y = coords[i]['y'] + + if shape == 'circle' or shape == 'square': + # Define the bounding box for the shape + left_up_point = (location_x - current_width // 2, location_y - current_height // 2) + right_down_point = (location_x + current_width // 2, location_y + current_height // 2) + two_points = [left_up_point, right_down_point] + + if shape == 'circle': + if border_width > 0: + draw.ellipse(two_points, fill=shape_color, outline=border_color, width=border_width) + else: + draw.ellipse(two_points, fill=shape_color) + elif shape == 'square': + if border_width > 0: + draw.rectangle(two_points, fill=shape_color, outline=border_color, width=border_width) + else: + draw.rectangle(two_points, fill=shape_color) + + elif shape == 'triangle': + # Define the points for the triangle + left_up_point = (location_x - current_width // 2, location_y + current_height // 2) # bottom left + right_down_point = (location_x + current_width // 2, location_y + current_height // 2) # bottom right + top_point = (location_x, location_y - current_height // 2) # top point + + if border_width > 0: + draw.polygon([top_point, left_up_point, right_down_point], fill=shape_color, outline=border_color, width=border_width) + else: + draw.polygon([top_point, left_up_point, right_down_point], fill=shape_color) + + if blur_radius != 0: + image = image.filter(ImageFilter.GaussianBlur(blur_radius)) + # Blend the current image with the accumulated image + + image = pil2tensor(image) + if trailing != 1.0 and previous_output is not None: + # Add the decayed previous output to the current frame + image += trailing * previous_output + image = image / image.max() + previous_output = image + image = image * intensity + mask = image[:, :, :, 0] + masks_list.append(mask) + images_list.append(image) + out_images = torch.cat(images_list, dim=0).cpu().float() + out_masks = torch.cat(masks_list, dim=0) + return (out_images, out_masks) + +class CreateTextOnPath: + + RETURN_TYPES = ("IMAGE", "MASK", "MASK",) + RETURN_NAMES = ("image", "mask", "mask_inverted",) + FUNCTION = "createtextmask" + CATEGORY = "KJNodes/masking/generate" + DESCRIPTION = """ +Creates a mask or batch of masks with the specified text. +Locations are center locations. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "coordinates": ("STRING", {"forceInput": True}), + "text": ("STRING", {"default": 'text', "multiline": True}), + "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "font": (folder_paths.get_filename_list("kjnodes_fonts"), ), + "font_size": ("INT", {"default": 42}), + "alignment": ( + [ 'left', + 'center', + 'right' + ], + {"default": 'center'} + ), + "text_color": ("STRING", {"default": 'white'}), + }, + "optional": { + "size_multiplier": ("FLOAT", {"default": [1.0], "forceInput": True}), + } + } + + def createtextmask(self, coordinates, frame_width, frame_height, font, font_size, text, text_color, alignment, size_multiplier=[1.0]): + coordinates = coordinates.replace("'", '"') + coordinates = json.loads(coordinates) + + batch_size = len(coordinates) + mask_list = [] + image_list = [] + color = parse_color(text_color) + font_path = folder_paths.get_full_path("kjnodes_fonts", font) + + if len(size_multiplier) != batch_size: + size_multiplier = size_multiplier * (batch_size // len(size_multiplier)) + size_multiplier[:batch_size % len(size_multiplier)] + + for i, coord in enumerate(coordinates): + image = Image.new("RGB", (frame_width, frame_height), "black") + draw = ImageDraw.Draw(image) + lines = text.split('\n') # Split the text into lines + # Apply the size multiplier to the font size for this iteration + current_font_size = int(font_size * size_multiplier[i]) + current_font = ImageFont.truetype(font_path, current_font_size) + line_heights = [current_font.getbbox(line)[3] for line in lines] # List of line heights + total_text_height = sum(line_heights) # Total height of text block + + # Calculate the starting Y position to center the block of text + start_y = coord['y'] - total_text_height // 2 + for j, line in enumerate(lines): + text_width, text_height = current_font.getbbox(line)[2], line_heights[j] + if alignment == 'left': + location_x = coord['x'] + elif alignment == 'center': + location_x = int(coord['x'] - text_width // 2) + elif alignment == 'right': + location_x = int(coord['x'] - text_width) + + location_y = int(start_y + sum(line_heights[:j])) + text_position = (location_x, location_y) + # Draw the text + try: + draw.text(text_position, line, fill=color, font=current_font, features=['-liga']) + except: + draw.text(text_position, line, fill=color, font=current_font) + + image = pil2tensor(image) + non_black_pixels = (image > 0).any(dim=-1) + mask = non_black_pixels.to(image.dtype) + mask_list.append(mask) + image_list.append(image) + + out_images = torch.cat(image_list, dim=0).cpu().float() + out_masks = torch.cat(mask_list, dim=0) + return (out_images, out_masks, 1.0 - out_masks,) + +class CreateGradientFromCoords: + + RETURN_TYPES = ("IMAGE", ) + RETURN_NAMES = ("image", ) + FUNCTION = "generate" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Creates a gradient image from coordinates. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "coordinates": ("STRING", {"forceInput": True}), + "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "start_color": ("STRING", {"default": 'white'}), + "end_color": ("STRING", {"default": 'black'}), + "multiplier": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 100.0, "step": 0.01}), + }, + } + + def generate(self, coordinates, frame_width, frame_height, start_color, end_color, multiplier): + # Parse the coordinates + coordinates = json.loads(coordinates.replace("'", '"')) + + # Create an image + image = Image.new("RGB", (frame_width, frame_height)) + draw = ImageDraw.Draw(image) + + # Extract start and end points for the gradient + start_coord = coordinates[0] + end_coord = coordinates[1] + + start_color = parse_color(start_color) + end_color = parse_color(end_color) + + # Calculate the gradient direction (vector) + gradient_direction = (end_coord['x'] - start_coord['x'], end_coord['y'] - start_coord['y']) + gradient_length = (gradient_direction[0] ** 2 + gradient_direction[1] ** 2) ** 0.5 + + # Iterate over each pixel in the image + for y in range(frame_height): + for x in range(frame_width): + # Calculate the projection of the point on the gradient line + point_vector = (x - start_coord['x'], y - start_coord['y']) + projection = (point_vector[0] * gradient_direction[0] + point_vector[1] * gradient_direction[1]) / gradient_length + projection = max(min(projection, gradient_length), 0) # Clamp the projection value + + # Calculate the blend factor for the current pixel + blend = projection * multiplier / gradient_length + + # Determine the color of the current pixel + color = ( + int(start_color[0] + (end_color[0] - start_color[0]) * blend), + int(start_color[1] + (end_color[1] - start_color[1]) * blend), + int(start_color[2] + (end_color[2] - start_color[2]) * blend) + ) + + # Set the pixel color + draw.point((x, y), fill=color) + + # Convert the PIL image to a tensor (assuming such a function exists in your context) + image_tensor = pil2tensor(image) + + return (image_tensor,) + +class GradientToFloat: + + RETURN_TYPES = ("FLOAT", "FLOAT",) + RETURN_NAMES = ("float_x", "float_y", ) + FUNCTION = "sample" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Calculates list of floats from image. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "image": ("IMAGE", ), + "steps": ("INT", {"default": 10, "min": 2, "max": 10000, "step": 1}), + }, + } + + def sample(self, image, steps): + # Assuming image is a tensor with shape [B, H, W, C] + B, H, W, C = image.shape + + # Sample along the width axis (W) + w_intervals = torch.linspace(0, W - 1, steps=steps, dtype=torch.int64) + # Assuming we're sampling from the first batch and the first channel + w_sampled = image[0, :, w_intervals, 0] + + # Sample along the height axis (H) + h_intervals = torch.linspace(0, H - 1, steps=steps, dtype=torch.int64) + # Assuming we're sampling from the first batch and the first channel + h_sampled = image[0, h_intervals, :, 0] + + # Taking the mean across the height for width sampling, and across the width for height sampling + w_values = w_sampled.mean(dim=0).tolist() + h_values = h_sampled.mean(dim=1).tolist() + + return (w_values, h_values) + +class MaskOrImageToWeight: + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "output_type": ( + [ + 'list', + 'pandas series', + 'tensor', + 'string' + ], + { + "default": 'list' + }), + }, + "optional": { + "images": ("IMAGE",), + "masks": ("MASK",), + }, + + } + RETURN_TYPES = ("FLOAT", "STRING",) + FUNCTION = "execute" + CATEGORY = "KJNodes/weights" + DESCRIPTION = """ +Gets the mean values from mask or image batch +and returns that as the selected output type. +""" + + def execute(self, output_type, images=None, masks=None): + mean_values = [] + if masks is not None and images is None: + for mask in masks: + mean_values.append(mask.mean().item()) + elif masks is None and images is not None: + for image in images: + mean_values.append(image.mean().item()) + elif masks is not None and images is not None: + raise Exception("MaskOrImageToWeight: Use either mask or image input only.") + + # Convert mean_values to the specified output_type + if output_type == 'list': + out = mean_values + elif output_type == 'pandas series': + try: + import pandas as pd + except: + raise Exception("MaskOrImageToWeight: pandas is not installed. Please install pandas to use this output_type") + out = pd.Series(mean_values), + elif output_type == 'tensor': + out = torch.tensor(mean_values, dtype=torch.float32), + return (out, [str(value) for value in mean_values],) + +class WeightScheduleConvert: + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "input_values": ("FLOAT", {"default": 0.0, "forceInput": True}), + "output_type": ( + [ + 'match_input', + 'list', + 'pandas series', + 'tensor', + ], + { + "default": 'list' + }), + "invert": ("BOOLEAN", {"default": False}), + "repeat": ("INT", {"default": 1,"min": 1, "max": 255, "step": 1}), + }, + "optional": { + "remap_to_frames": ("INT", {"default": 0}), + "interpolation_curve": ("FLOAT", {"forceInput": True}), + "remap_values": ("BOOLEAN", {"default": False}), + "remap_min": ("FLOAT", {"default": 0.0, "min": -100000, "max": 100000.0, "step": 0.01}), + "remap_max": ("FLOAT", {"default": 1.0, "min": -100000, "max": 100000.0, "step": 0.01}), + }, + + } + RETURN_TYPES = ("FLOAT", "STRING", "INT",) + FUNCTION = "execute" + CATEGORY = "KJNodes/weights" + DESCRIPTION = """ +Converts different value lists/series to another type. +""" + + def detect_input_type(self, input_values): + import pandas as pd + if isinstance(input_values, list): + return 'list' + elif isinstance(input_values, pd.Series): + return 'pandas series' + elif isinstance(input_values, torch.Tensor): + return 'tensor' + else: + raise ValueError("Unsupported input type") + + def execute(self, input_values, output_type, invert, repeat, remap_to_frames=0, interpolation_curve=None, remap_min=0.0, remap_max=1.0, remap_values=False): + import pandas as pd + input_type = self.detect_input_type(input_values) + + if input_type == 'pandas series': + float_values = input_values.tolist() + elif input_type == 'tensor': + float_values = input_values + else: + float_values = input_values + + if invert: + float_values = [1 - value for value in float_values] + + if interpolation_curve is not None: + interpolated_pattern = [] + orig_float_values = float_values + for value in interpolation_curve: + min_val = min(orig_float_values) + max_val = max(orig_float_values) + # Normalize the values to [0, 1] + normalized_values = [(value - min_val) / (max_val - min_val) for value in orig_float_values] + # Interpolate the normalized values to the new frame count + remapped_float_values = np.interp(np.linspace(0, 1, int(remap_to_frames * value)), np.linspace(0, 1, len(normalized_values)), normalized_values).tolist() + interpolated_pattern.extend(remapped_float_values) + float_values = interpolated_pattern + else: + # Remap float_values to match target_frame_amount + if remap_to_frames > 0 and remap_to_frames != len(float_values): + min_val = min(float_values) + max_val = max(float_values) + # Normalize the values to [0, 1] + normalized_values = [(value - min_val) / (max_val - min_val) for value in float_values] + # Interpolate the normalized values to the new frame count + float_values = np.interp(np.linspace(0, 1, remap_to_frames), np.linspace(0, 1, len(normalized_values)), normalized_values).tolist() + + float_values = float_values * repeat + if remap_values: + float_values = self.remap_values(float_values, remap_min, remap_max) + + if output_type == 'list': + out = float_values, + elif output_type == 'pandas series': + out = pd.Series(float_values), + elif output_type == 'tensor': + if input_type == 'pandas series': + out = torch.tensor(float_values.values, dtype=torch.float32), + else: + out = torch.tensor(float_values, dtype=torch.float32), + elif output_type == 'match_input': + out = float_values, + return (out, [str(value) for value in float_values], [int(value) for value in float_values]) + + def remap_values(self, values, target_min, target_max): + # Determine the current range + current_min = min(values) + current_max = max(values) + current_range = current_max - current_min + + # Determine the target range + target_range = target_max - target_min + + # Perform the linear interpolation for each value + remapped_values = [(value - current_min) / current_range * target_range + target_min for value in values] + + return remapped_values + + +class FloatToMask: + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "input_values": ("FLOAT", {"forceInput": True, "default": 0}), + "width": ("INT", {"default": 100, "min": 1}), + "height": ("INT", {"default": 100, "min": 1}), + }, + } + RETURN_TYPES = ("MASK",) + FUNCTION = "execute" + CATEGORY = "KJNodes/masking/generate" + DESCRIPTION = """ +Generates a batch of masks based on the input float values. +The batch size is determined by the length of the input float values. +Each mask is generated with the specified width and height. +""" + + def execute(self, input_values, width, height): + import pandas as pd + # Ensure input_values is a list + if isinstance(input_values, (float, int)): + input_values = [input_values] + elif isinstance(input_values, pd.Series): + input_values = input_values.tolist() + elif isinstance(input_values, list) and all(isinstance(item, list) for item in input_values): + input_values = [item for sublist in input_values for item in sublist] + + # Generate a batch of masks based on the input_values + masks = [] + for value in input_values: + # Assuming value is a float between 0 and 1 representing the mask's intensity + mask = torch.ones((height, width), dtype=torch.float32) * value + masks.append(mask) + masks_out = torch.stack(masks, dim=0) + + return(masks_out,) +class WeightScheduleExtend: + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "input_values_1": ("FLOAT", {"default": 0.0, "forceInput": True}), + "input_values_2": ("FLOAT", {"default": 0.0, "forceInput": True}), + "output_type": ( + [ + 'match_input', + 'list', + 'pandas series', + 'tensor', + ], + { + "default": 'match_input' + }), + }, + + } + RETURN_TYPES = ("FLOAT",) + FUNCTION = "execute" + CATEGORY = "KJNodes/weights" + DESCRIPTION = """ +Extends, and converts if needed, different value lists/series +""" + + def detect_input_type(self, input_values): + import pandas as pd + if isinstance(input_values, list): + return 'list' + elif isinstance(input_values, pd.Series): + return 'pandas series' + elif isinstance(input_values, torch.Tensor): + return 'tensor' + else: + raise ValueError("Unsupported input type") + + def execute(self, input_values_1, input_values_2, output_type): + import pandas as pd + input_type_1 = self.detect_input_type(input_values_1) + input_type_2 = self.detect_input_type(input_values_2) + # Convert input_values_2 to the same format as input_values_1 if they do not match + if not input_type_1 == input_type_2: + print("Converting input_values_2 to the same format as input_values_1") + if input_type_1 == 'pandas series': + # Convert input_values_2 to a pandas Series + float_values_2 = pd.Series(input_values_2) + elif input_type_1 == 'tensor': + # Convert input_values_2 to a tensor + float_values_2 = torch.tensor(input_values_2, dtype=torch.float32) + else: + print("Input types match, no conversion needed") + # If the types match, no conversion is needed + float_values_2 = input_values_2 + + float_values = input_values_1 + float_values_2 + + if output_type == 'list': + return float_values, + elif output_type == 'pandas series': + return pd.Series(float_values), + elif output_type == 'tensor': + if input_type_1 == 'pandas series': + return torch.tensor(float_values.values, dtype=torch.float32), + else: + return torch.tensor(float_values, dtype=torch.float32), + elif output_type == 'match_input': + return float_values, + else: + raise ValueError(f"Unsupported output_type: {output_type}") + +class FloatToSigmas: + @classmethod + def INPUT_TYPES(s): + return {"required": + { + "float_list": ("FLOAT", {"default": 0.0, "forceInput": True}), + } + } + RETURN_TYPES = ("SIGMAS",) + RETURN_NAMES = ("SIGMAS",) + CATEGORY = "KJNodes/noise" + FUNCTION = "customsigmas" + DESCRIPTION = """ +Creates a sigmas tensor from list of float values. + +""" + def customsigmas(self, float_list): + return torch.tensor(float_list, dtype=torch.float32), + +class SigmasToFloat: + @classmethod + def INPUT_TYPES(s): + return {"required": + { + "sigmas": ("SIGMAS",), + } + } + RETURN_TYPES = ("FLOAT",) + RETURN_NAMES = ("float",) + CATEGORY = "KJNodes/noise" + FUNCTION = "customsigmas" + DESCRIPTION = """ +Creates a float list from sigmas tensors. + +""" + def customsigmas(self, sigmas): + return sigmas.tolist(), + +class GLIGENTextBoxApplyBatchCoords: + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning_to": ("CONDITIONING", ), + "latents": ("LATENT", ), + "clip": ("CLIP", ), + "gligen_textbox_model": ("GLIGEN", ), + "coordinates": ("STRING", {"forceInput": True}), + "text": ("STRING", {"multiline": True}), + "width": ("INT", {"default": 128, "min": 8, "max": 4096, "step": 8}), + "height": ("INT", {"default": 128, "min": 8, "max": 4096, "step": 8}), + }, + "optional": {"size_multiplier": ("FLOAT", {"default": [1.0], "forceInput": True})}, + } + RETURN_TYPES = ("CONDITIONING", "IMAGE", ) + RETURN_NAMES = ("conditioning", "coord_preview", ) + FUNCTION = "append" + CATEGORY = "KJNodes/experimental" + DESCRIPTION = """ +This node allows scheduling GLIGEN text box positions in a batch, +to be used with AnimateDiff-Evolved. Intended to pair with the +Spline Editor -node. + +GLIGEN model can be downloaded through the Manage's "Install Models" menu. +Or directly from here: +https://huggingface.co/comfyanonymous/GLIGEN_pruned_safetensors/tree/main + +Inputs: +- **latents** input is used to calculate batch size +- **clip** is your standard text encoder, use same as for the main prompt +- **gligen_textbox_model** connects to GLIGEN Loader +- **coordinates** takes a json string of points, directly compatible +with the spline editor node. +- **text** is the part of the prompt to set position for +- **width** and **height** are the size of the GLIGEN bounding box + +Outputs: +- **conditioning** goes between to clip text encode and the sampler +- **coord_preview** is an optional preview of the coordinates and +bounding boxes. + +""" + + def append(self, latents, coordinates, conditioning_to, clip, gligen_textbox_model, text, width, height, size_multiplier=[1.0]): + coordinates = json.loads(coordinates.replace("'", '"')) + coordinates = [(coord['x'], coord['y']) for coord in coordinates] + + batch_size = sum(tensor.size(0) for tensor in latents.values()) + if len(coordinates) != batch_size: + print("GLIGENTextBoxApplyBatchCoords WARNING: The number of coordinates does not match the number of latents") + + c = [] + _, cond_pooled = clip.encode_from_tokens(clip.tokenize(text), return_pooled=True) + + for t in conditioning_to: + n = [t[0], t[1].copy()] + + position_params_batch = [[] for _ in range(batch_size)] # Initialize a list of empty lists for each batch item + if len(size_multiplier) != batch_size: + size_multiplier = size_multiplier * (batch_size // len(size_multiplier)) + size_multiplier[:batch_size % len(size_multiplier)] + + for i in range(batch_size): + x_position, y_position = coordinates[i] + position_param = (cond_pooled, int((height // 8) * size_multiplier[i]), int((width // 8) * size_multiplier[i]), (y_position - height // 2) // 8, (x_position - width // 2) // 8) + position_params_batch[i].append(position_param) # Append position_param to the correct sublist + + prev = [] + if "gligen" in n[1]: + prev = n[1]['gligen'][2] + else: + prev = [[] for _ in range(batch_size)] + # Concatenate prev and position_params_batch, ensuring both are lists of lists + # and each sublist corresponds to a batch item + combined_position_params = [prev_item + batch_item for prev_item, batch_item in zip(prev, position_params_batch)] + n[1]['gligen'] = ("position_batched", gligen_textbox_model, combined_position_params) + c.append(n) + + image_height = latents['samples'].shape[-2] * 8 + image_width = latents['samples'].shape[-1] * 8 + plot_image_tensor = plot_coordinates_to_tensor(coordinates, image_height, image_width, height, width, size_multiplier, text) + + return (c, plot_image_tensor,) + +class CreateInstanceDiffusionTracking: + + RETURN_TYPES = ("TRACKING", "STRING", "INT", "INT", "INT", "INT",) + RETURN_NAMES = ("tracking", "prompt", "width", "height", "bbox_width", "bbox_height",) + FUNCTION = "tracking" + CATEGORY = "KJNodes/InstanceDiffusion" + DESCRIPTION = """ +Creates tracking data to be used with InstanceDiffusion: +https://github.com/logtd/ComfyUI-InstanceDiffusion + +InstanceDiffusion prompt format: +"class_id.class_name": "prompt", +for example: +"1.head": "((head))", +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "coordinates": ("STRING", {"forceInput": True}), + "width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "bbox_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "bbox_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "class_name": ("STRING", {"default": "class_name"}), + "class_id": ("INT", {"default": 0,"min": 0, "max": 255, "step": 1}), + "prompt": ("STRING", {"default": "prompt", "multiline": True}), + }, + "optional": { + "size_multiplier": ("FLOAT", {"default": [1.0], "forceInput": True}), + "fit_in_frame": ("BOOLEAN", {"default": True}), + } + } + + def tracking(self, coordinates, class_name, class_id, width, height, bbox_width, bbox_height, prompt, size_multiplier=[1.0], fit_in_frame=True): + # Define the number of images in the batch + coordinates = coordinates.replace("'", '"') + coordinates = json.loads(coordinates) + + tracked = {} + tracked[class_name] = {} + batch_size = len(coordinates) + # Initialize a list to hold the coordinates for the current ID + id_coordinates = [] + if not size_multiplier or len(size_multiplier) != batch_size: + size_multiplier = [0] * batch_size + else: + size_multiplier = size_multiplier * (batch_size // len(size_multiplier)) + size_multiplier[:batch_size % len(size_multiplier)] + for i, coord in enumerate(coordinates): + x = coord['x'] + y = coord['y'] + adjusted_bbox_width = bbox_width * size_multiplier[i] + adjusted_bbox_height = bbox_height * size_multiplier[i] + # Calculate the top left and bottom right coordinates + top_left_x = x - adjusted_bbox_width // 2 + top_left_y = y - adjusted_bbox_height // 2 + bottom_right_x = x + adjusted_bbox_width // 2 + bottom_right_y = y + adjusted_bbox_height // 2 + + if fit_in_frame: + # Clip the coordinates to the frame boundaries + top_left_x = max(0, top_left_x) + top_left_y = max(0, top_left_y) + bottom_right_x = min(width, bottom_right_x) + bottom_right_y = min(height, bottom_right_y) + # Ensure width and height are positive + adjusted_bbox_width = max(1, bottom_right_x - top_left_x) + adjusted_bbox_height = max(1, bottom_right_y - top_left_y) + + # Update the coordinates with the new width and height + bottom_right_x = top_left_x + adjusted_bbox_width + bottom_right_y = top_left_y + adjusted_bbox_height + + # Append the top left and bottom right coordinates to the list for the current ID + id_coordinates.append([top_left_x, top_left_y, bottom_right_x, bottom_right_y, width, height]) + + class_id = int(class_id) + # Assign the list of coordinates to the specified ID within the class_id dictionary + tracked[class_name][class_id] = id_coordinates + + prompt_string = "" + for class_name, class_data in tracked.items(): + for class_id in class_data.keys(): + class_id_str = str(class_id) + # Use the incoming prompt for each class name and ID + prompt_string += f'"{class_id_str}.{class_name}": "({prompt})",\n' + + # Remove the last comma and newline + prompt_string = prompt_string.rstrip(",\n") + + return (tracked, prompt_string, width, height, bbox_width, bbox_height) + +class AppendInstanceDiffusionTracking: + + RETURN_TYPES = ("TRACKING", "STRING",) + RETURN_NAMES = ("tracking", "prompt",) + FUNCTION = "append" + CATEGORY = "KJNodes/InstanceDiffusion" + DESCRIPTION = """ +Appends tracking data to be used with InstanceDiffusion: +https://github.com/logtd/ComfyUI-InstanceDiffusion + +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "tracking_1": ("TRACKING", {"forceInput": True}), + "tracking_2": ("TRACKING", {"forceInput": True}), + }, + "optional": { + "prompt_1": ("STRING", {"default": "", "forceInput": True}), + "prompt_2": ("STRING", {"default": "", "forceInput": True}), + } + } + + def append(self, tracking_1, tracking_2, prompt_1="", prompt_2=""): + tracking_copy = tracking_1.copy() + # Check for existing class names and class IDs, and raise an error if they exist + for class_name, class_data in tracking_2.items(): + if class_name not in tracking_copy: + tracking_copy[class_name] = class_data + else: + # If the class name exists, merge the class data from tracking_2 into tracking_copy + # This will add new class IDs under the same class name without raising an error + tracking_copy[class_name].update(class_data) + prompt_string = prompt_1 + "," + prompt_2 + return (tracking_copy, prompt_string) + +class InterpolateCoords: + + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("coordinates",) + FUNCTION = "interpolate" + CATEGORY = "KJNodes/experimental" + DESCRIPTION = """ +Interpolates coordinates based on a curve. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "coordinates": ("STRING", {"forceInput": True}), + "interpolation_curve": ("FLOAT", {"forceInput": True}), + + }, + } + + def interpolate(self, coordinates, interpolation_curve): + # Parse the JSON string to get the list of coordinates + coordinates = json.loads(coordinates.replace("'", '"')) + + # Convert the list of dictionaries to a list of (x, y) tuples for easier processing + coordinates = [(coord['x'], coord['y']) for coord in coordinates] + + # Calculate the total length of the original path + path_length = sum(np.linalg.norm(np.array(coordinates[i]) - np.array(coordinates[i-1])) + for i in range(1, len(coordinates))) + + # Initialize variables for interpolation + interpolated_coords = [] + current_length = 0 + current_index = 0 + + # Iterate over the normalized curve + for normalized_length in interpolation_curve: + target_length = normalized_length * path_length # Convert to the original scale + while current_index < len(coordinates) - 1: + segment_start, segment_end = np.array(coordinates[current_index]), np.array(coordinates[current_index + 1]) + segment_length = np.linalg.norm(segment_end - segment_start) + if current_length + segment_length >= target_length: + break + current_length += segment_length + current_index += 1 + + # Interpolate between the last two points + if current_index < len(coordinates) - 1: + p1, p2 = np.array(coordinates[current_index]), np.array(coordinates[current_index + 1]) + segment_length = np.linalg.norm(p2 - p1) + if segment_length > 0: + t = (target_length - current_length) / segment_length + interpolated_point = p1 + t * (p2 - p1) + interpolated_coords.append(interpolated_point.tolist()) + else: + interpolated_coords.append(p1.tolist()) + else: + # If the target_length is at or beyond the end of the path, add the last coordinate + interpolated_coords.append(coordinates[-1]) + + # Convert back to string format if necessary + interpolated_coords_str = "[" + ", ".join([f"{{'x': {round(coord[0])}, 'y': {round(coord[1])}}}" for coord in interpolated_coords]) + "]" + print(interpolated_coords_str) + + return (interpolated_coords_str,) + +class DrawInstanceDiffusionTracking: + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("image", ) + FUNCTION = "draw" + CATEGORY = "KJNodes/InstanceDiffusion" + DESCRIPTION = """ +Draws the tracking data from +CreateInstanceDiffusionTracking -node. + +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "image": ("IMAGE", ), + "tracking": ("TRACKING", {"forceInput": True}), + "box_line_width": ("INT", {"default": 2, "min": 1, "max": 10, "step": 1}), + "draw_text": ("BOOLEAN", {"default": True}), + "font": (folder_paths.get_filename_list("kjnodes_fonts"), ), + "font_size": ("INT", {"default": 20}), + }, + } + + def draw(self, image, tracking, box_line_width, draw_text, font, font_size): + import matplotlib.cm as cm + + modified_images = [] + + colormap = cm.get_cmap('rainbow', len(tracking)) + if draw_text: + font_path = folder_paths.get_full_path("kjnodes_fonts", font) + font = ImageFont.truetype(font_path, font_size) + + # Iterate over each image in the batch + for i in range(image.shape[0]): + # Extract the current image and convert it to a PIL image + current_image = image[i, :, :, :].permute(2, 0, 1) + pil_image = transforms.ToPILImage()(current_image) + + draw = ImageDraw.Draw(pil_image) + + # Iterate over the bounding boxes for the current image + for j, (class_name, class_data) in enumerate(tracking.items()): + for class_id, bbox_list in class_data.items(): + # Check if the current index is within the bounds of the bbox_list + if i < len(bbox_list): + bbox = bbox_list[i] + # Ensure bbox is a list or tuple before unpacking + if isinstance(bbox, (list, tuple)): + x1, y1, x2, y2, _, _ = bbox + # Convert coordinates to integers + x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2) + # Generate a color from the rainbow colormap + color = tuple(int(255 * x) for x in colormap(j / len(tracking)))[:3] + # Draw the bounding box on the image with the generated color + draw.rectangle([x1, y1, x2, y2], outline=color, width=box_line_width) + if draw_text: + # Draw the class name and ID as text above the box with the generated color + text = f"{class_id}.{class_name}" + # Calculate the width and height of the text + _, _, text_width, text_height = draw.textbbox((0, 0), text=text, font=font) + # Position the text above the top-left corner of the box + text_position = (x1, y1 - text_height) + draw.text(text_position, text, fill=color, font=font) + else: + print(f"Unexpected data type for bbox: {type(bbox)}") + + # Convert the drawn image back to a torch tensor and adjust back to (H, W, C) + modified_image_tensor = transforms.ToTensor()(pil_image).permute(1, 2, 0) + modified_images.append(modified_image_tensor) + + # Stack the modified images back into a batch + image_tensor_batch = torch.stack(modified_images).cpu().float() + + return image_tensor_batch, + +class PointsEditor: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "points_store": ("STRING", {"multiline": False, "advanced": True}), + "coordinates": ("STRING", {"multiline": False, "socketless": True, "advanced": True}), + "neg_coordinates": ("STRING", {"multiline": False, "socketless": True, "advanced": True}), + "bbox_store": ("STRING", {"multiline": False, "advanced": True}), + "bboxes": ("STRING", {"multiline": False, "socketless": True, "advanced": True}), + "bbox_format": ( + [ + 'xyxy', + 'xywh', + ], + ), + "width": ("INT", {"default": 512, "min": 8, "max": 4096, "step": 8}), + "height": ("INT", {"default": 512, "min": 8, "max": 4096, "step": 8}), + "normalize": ("BOOLEAN", {"default": False}), + }, + "optional": { + "bg_image": ("IMAGE", ), + }, + } + + RETURN_TYPES = ("STRING", "STRING", "BBOX", "MASK", "IMAGE") + RETURN_NAMES = ("positive_coords", "negative_coords", "bbox", "bbox_mask", "cropped_image") + FUNCTION = "pointdata" + CATEGORY = "KJNodes/experimental" + DESCRIPTION = """ +# WORK IN PROGRESS +Do not count on this as part of your workflow yet, +probably contains lots of bugs and stability is not +guaranteed!! + +## Graphical editor to create coordinates + +**Shift + click** to add a positive (green) point. +**Shift + right click** to add a negative (red) point. +**Right click on a point** to delete it. +**Ctrl + click** to draw a bounding box. +**Drag bbox corners** to resize, **drag inside** to move. +**Right click on bbox** to delete it. + +To add an image select the node and copy/paste or drag in the image. +Or from the bg_image input on queue (first frame of the batch). + +**THE IMAGE IS SAVED TO THE NODE AND WORKFLOW METADATA** +you can clear the image from the context menu by right clicking on the canvas + +""" + + def pointdata(self, points_store, bbox_store, width, height, coordinates, neg_coordinates, normalize, bboxes, bbox_format="xyxy", bg_image=None): + coordinates = json.loads(coordinates) + if not coordinates: + raise ValueError("No points on the canvas. Use Shift+click to add positive points or Shift+right-click to add negative points before executing.") + pos_coordinates = [] + for coord in coordinates: + coord['x'] = int(round(coord['x'])) + coord['y'] = int(round(coord['y'])) + if normalize: + norm_x = coord['x'] / width + norm_y = coord['y'] / height + pos_coordinates.append({'x': norm_x, 'y': norm_y}) + else: + pos_coordinates.append({'x': coord['x'], 'y': coord['y']}) + + if neg_coordinates: + coordinates = json.loads(neg_coordinates) + neg_coordinates = [] + for coord in coordinates: + coord['x'] = int(round(coord['x'])) + coord['y'] = int(round(coord['y'])) + if normalize: + norm_x = coord['x'] / width + norm_y = coord['y'] / height + neg_coordinates.append({'x': norm_x, 'y': norm_y}) + else: + neg_coordinates.append({'x': coord['x'], 'y': coord['y']}) + + # Create a blank mask + mask = np.zeros((height, width), dtype=np.uint8) + bboxes = json.loads(bboxes) + valid_bboxes = [] + for bbox in bboxes: + if (bbox.get("startX") is None or + bbox.get("startY") is None or + bbox.get("endX") is None or + bbox.get("endY") is None): + continue # Skip this bounding box if any value is None + else: + # Ensure that endX and endY are greater than startX and startY + x_min = min(int(bbox["startX"]), int(bbox["endX"])) + y_min = min(int(bbox["startY"]), int(bbox["endY"])) + x_max = max(int(bbox["startX"]), int(bbox["endX"])) + y_max = max(int(bbox["startY"]), int(bbox["endY"])) + + valid_bboxes.append((x_min, y_min, x_max, y_max)) + + bboxes_xyxy = [] + for bbox in valid_bboxes: + x_min, y_min, x_max, y_max = bbox + bboxes_xyxy.append((x_min, y_min, x_max, y_max)) + mask[y_min:y_max, x_min:x_max] = 1 # Fill the bounding box area with 1s + + if bbox_format == "xywh": + bboxes_xywh = [] + for bbox in valid_bboxes: + x_min, y_min, x_max, y_max = bbox + width = x_max - x_min + height = y_max - y_min + bboxes_xywh.append((x_min, y_min, width, height)) + bboxes = bboxes_xywh + else: + bboxes = bboxes_xyxy + + mask_tensor = torch.from_numpy(mask) + mask_tensor = mask_tensor.unsqueeze(0).float().cpu() + + if bg_image is not None and len(valid_bboxes) > 0: + x_min, y_min, x_max, y_max = bboxes[0] + cropped_image = bg_image[:, y_min:y_max, x_min:x_max, :] + elif bg_image is not None: + cropped_image = bg_image + else: + cropped_image = torch.zeros(1, height, width, 3, dtype=torch.float32) + + if bg_image is None: + return (json.dumps(pos_coordinates), json.dumps(neg_coordinates), bboxes, mask_tensor, cropped_image) + else: + transform = transforms.ToPILImage() + image = transform(bg_image[0].permute(2, 0, 1)) + buffered = BytesIO() + image.save(buffered, format="JPEG", quality=75) + img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8') + + return { + "ui": {"bg_image": [img_base64]}, + "result": (json.dumps(pos_coordinates), json.dumps(neg_coordinates), bboxes, mask_tensor, cropped_image) + } + +class CutAndDragOnPath: + RETURN_TYPES = ("IMAGE", "MASK",) + RETURN_NAMES = ("image","mask", ) + FUNCTION = "cutanddrag" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Cuts the masked area from the image, and drags it along the path. If inpaint is enabled, and no bg_image is provided, the cut area is filled using cv2 TELEA algorithm. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "image": ("IMAGE",), + "coordinates": ("STRING", {"forceInput": True}), + "mask": ("MASK",), + "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "inpaint": ("BOOLEAN", {"default": True}), + }, + "optional": { + "bg_image": ("IMAGE",), + } + } + + def cutanddrag(self, image, coordinates, mask, frame_width, frame_height, inpaint, bg_image=None): + # Parse coordinates + coords_list = parse_json_tracks(coordinates) + + batch_size = len(coords_list[0]) + images_list = [] + masks_list = [] + + # Convert input image and mask to PIL + input_image = tensor2pil(image)[0] + input_mask = tensor2pil(mask)[0] + + # Find masked region bounds + mask_array = np.array(input_mask) + y_indices, x_indices = np.where(mask_array > 0) + if len(x_indices) == 0 or len(y_indices) == 0: + return (image, mask) + + x_min, x_max = x_indices.min(), x_indices.max() + y_min, y_max = y_indices.min(), y_indices.max() + + # Cut out the masked region + cut_width = x_max - x_min + cut_height = y_max - y_min + cut_image = input_image.crop((x_min, y_min, x_max, y_max)) + cut_mask = input_mask.crop((x_min, y_min, x_max, y_max)) + + # Create inpainted background + if bg_image is None: + background = input_image.copy() + # Inpaint the cut area + if inpaint: + import cv2 + border = 5 # Create small border around cut area for better inpainting + fill_mask = Image.new("L", background.size, 0) + draw = ImageDraw.Draw(fill_mask) + draw.rectangle([x_min-border, y_min-border, x_max+border, y_max+border], fill=255) + background = cv2.inpaint( + np.array(background), + np.array(fill_mask), + inpaintRadius=3, + flags=cv2.INPAINT_TELEA + ) + background = Image.fromarray(background) + else: + background = tensor2pil(bg_image)[0] + + # Create batch of images with cut region at different positions + for i in range(batch_size): + # Create new image + new_image = background.copy() + new_mask = Image.new("L", (frame_width, frame_height), 0) + + # Get target position from coordinates + for coords in coords_list: + target_x = int(coords[i]['x'] - cut_width/2) + target_y = int(coords[i]['y'] - cut_height/2) + + # Paste cut region at new position + new_image.paste(cut_image, (target_x, target_y), cut_mask) + new_mask.paste(cut_mask, (target_x, target_y)) + + # Convert to tensor and append + image_tensor = pil2tensor(new_image) + mask_tensor = pil2tensor(new_mask) + + images_list.append(image_tensor) + masks_list.append(mask_tensor) + + # Stack tensors into batches + out_images = torch.cat(images_list, dim=0).cpu().float() + out_masks = torch.cat(masks_list, dim=0) + + return (out_images, out_masks) \ No newline at end of file diff --git a/.disabled/comfyui-kjnodes@nightly/nodes/image_nodes.py b/.disabled/comfyui-kjnodes@nightly/nodes/image_nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..2e2f243569b50cf1bae6b9635f4f75cdd5185b08 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/nodes/image_nodes.py @@ -0,0 +1,4802 @@ +import numpy as np +import time +import torch +import torch.nn.functional as F +import torchvision.transforms as T +import base64 +import random +import math +import os +import re +import json +import importlib +import hashlib +import pathlib +import logging +from io import BytesIO + +try: + import cv2 + HAS_CV2 = True +except: + logging.warning("OpenCV not installed") + HAS_CV2 = False + +from PIL import ImageGrab, ImageDraw, ImageFont, Image, ImageOps, ImageSequence, ImageStat +from PIL.PngImagePlugin import PngInfo + +from nodes import MAX_RESOLUTION, SaveImage +from comfy_extras.nodes_mask import composite +from comfy.cli_args import args +from comfy.utils import ProgressBar, common_upscale, tiled_scale_multidim +from comfy import model_management +from comfy_api.latest import io, InputImpl, Types, ui +from fractions import Fraction +import node_helpers +import folder_paths + +from ..utility.utility import string_to_color + +try: + from server import PromptServer, BinaryEventTypes +except: + PromptServer = None + BinaryEventTypes = None +from concurrent.futures import ThreadPoolExecutor + +script_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + +class ImagePass: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + }, + "optional": { + "image": ("IMAGE",), + }, + } + RETURN_TYPES = ("IMAGE",) + FUNCTION = "passthrough" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Passes the image through without modifying it. +""" + + def passthrough(self, image=None): + return image, + +class ColorMatch: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "image_ref": ("IMAGE",), + "image_target": ("IMAGE",), + "method": ( + [ + 'mkl', + 'hm', + 'reinhard', + 'mvgd', + 'hm-mvgd-hm', + 'hm-mkl-hm', + ], { + "default": 'mkl' + }), + }, + "optional": { + "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "multithread": ("BOOLEAN", {"default": True}), + } + } + + CATEGORY = "KJNodes/image" + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("image",) + FUNCTION = "colormatch" + DESCRIPTION = """ +color-matcher enables color transfer across images which comes in handy for automatic +color-grading of photographs, paintings and film sequences as well as light-field +and stopmotion corrections. + +The methods behind the mappings are based on the approach from Reinhard et al., +the Monge-Kantorovich Linearization (MKL) as proposed by Pitie et al. and our analytical solution +to a Multi-Variate Gaussian Distribution (MVGD) transfer in conjunction with classical histogram +matching. As shown below our HM-MVGD-HM compound outperforms existing methods. +https://github.com/hahnec/color-matcher/ + +""" + + def colormatch(self, image_ref, image_target, method, strength=1.0, multithread=True): + # Skip unnecessary processing + if strength == 0: + return (image_target,) + + try: + from color_matcher import ColorMatcher + except: + raise Exception("Can't import color-matcher, did you install requirements.txt? Manual install: pip install color-matcher") + + image_ref = image_ref.cpu() + image_target = image_target.cpu() + batch_size = image_target.size(0) + + images_target = image_target.squeeze() + images_ref = image_ref.squeeze() + + image_ref_np = images_ref.numpy() + images_target_np = images_target.numpy() + + def process(i): + cm = ColorMatcher() + image_target_np_i = images_target_np if batch_size == 1 else images_target[i].numpy() + image_ref_np_i = image_ref_np if image_ref.size(0) == 1 else images_ref[i].numpy() + try: + image_result = cm.transfer(src=image_target_np_i, ref=image_ref_np_i, method=method) # Avoid potential blur when only the fully color-matched image is used + if strength != 1: + image_result = image_target_np_i + strength * (image_result - image_target_np_i) + + return torch.from_numpy(image_result) + + except Exception as e: + logging.warning(f"Thread {i} error: {e}") + return torch.from_numpy(image_target_np_i) # fallback + + if multithread and batch_size > 1: + max_threads = min(os.cpu_count() or 1, batch_size) + with ThreadPoolExecutor(max_workers=max_threads) as executor: + out = list(executor.map(process, range(batch_size))) + else: + out = [process(i) for i in range(batch_size)] + + out = torch.stack(out, dim=0).to(torch.float32) + out.clamp_(0, 1) + return (out,) + +class ColorMatchV2(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="ColorMatchV2", + category="KJNodes/image", + description=""" +color-matcher enables color transfer across images which comes in handy for automatic +color-grading of photographs, paintings and film sequences as well as light-field +and stopmotion corrections. + +The methods behind the mappings are based on the approach from Reinhard et al., +the Monge-Kantorovich Linearization (MKL) as proposed by Pitie et al. and our analytical solution +to a Multi-Variate Gaussian Distribution (MVGD) transfer in conjunction with classical histogram +matching. As shown below our HM-MVGD-HM compound outperforms existing methods. +https://github.com/hahnec/color-matcher/ + +'reinhard_lab_gpu' method uses Kornia for GPU-accelerated color transfer in Lab color space. +""", + inputs=[ + io.Image.Input("image_target"), + io.Image.Input("image_ref"), + io.Combo.Input("method", + options=['mkl', 'hm', 'reinhard', 'mvgd', 'hm-mvgd-hm', 'hm-mkl-hm', 'reinhard_lab_gpu'], + default='mkl'), + io.Float.Input("strength", default=1.0, min=0.0, max=10.0, step=0.01), + io.Boolean.Input("multithread", default=True), + ], + outputs=[ + io.Image.Output(display_name="image"), + ], + ) + + @classmethod + def execute(cls, image_target, image_ref, method, strength=1.0, multithread=True) -> io.NodeOutput: + # Skip unnecessary processing + if strength == 0: + return io.NodeOutput(image_target) + + if method == "reinhard_lab_gpu": + import kornia + device = model_management.get_torch_device() + + B, H, W, C = image_target.shape + + src_bchw = image_target.to(device).permute(0, 3, 1, 2).contiguous() # (B, H, W, C) -> (B, C, H, W) + ref_bchw = image_ref.to(device).permute(0, 3, 1, 2).contiguous() + # RGB->Lab + src_lab = kornia.color.rgb_to_lab(src_bchw) + ref_lab = kornia.color.rgb_to_lab(ref_bchw) + + src_lab_flat = src_lab.view(B, C, -1) # (B, C, HW) + ref_lab_flat = ref_lab.view(ref_lab.shape[0], C, -1) # (B or 1, C, HW) + + src_std, src_mean = torch.std_mean(src_lab_flat, dim=-1, keepdim=True, unbiased=False) + ref_std, ref_mean = torch.std_mean(ref_lab_flat, dim=-1, keepdim=True, unbiased=False) + src_std = src_std.clamp_min_(1e-6) + + if ref_lab.shape[0] == 1 and B > 1: + ref_mean = ref_mean.expand(B, -1, -1) + ref_std = ref_std.expand(B, -1, -1) + + corrected_lab_flat = (src_lab_flat - src_mean) * (ref_std / src_std) + ref_mean + corrected_lab = corrected_lab_flat.view(B, C, H, W) + + # Lab->RGB + corrected_rgb_01 = kornia.color.lab_to_rgb(corrected_lab) + out = (1.0 - strength) * src_bchw + strength * corrected_rgb_01 + out = out.permute(0, 2, 3, 1).contiguous() # (B, C, H, W) -> (B, H, W, C) + + return io.NodeOutput(out.cpu().float().clamp_(0, 1)) + + try: + from color_matcher import ColorMatcher + except: + raise Exception("Can't import color-matcher, did you install requirements.txt? Manual install: pip install color-matcher") + + batch_size = image_target.size(0) + ref_batch_size = image_ref.size(0) + + def process(i): + cm = ColorMatcher() + image_target_np = image_target[i].cpu().numpy() + image_ref_np = image_ref[min(i, ref_batch_size - 1)].cpu().numpy() + try: + image_result = cm.transfer(src=image_target_np, ref=image_ref_np, method=method) + if strength != 1: + image_result = image_target_np + strength * (image_result - image_target_np) + + return torch.from_numpy(image_result) + + except Exception as e: + logging.error(f"Thread {i} error: {e}") + return torch.from_numpy(image_target_np) # fallback + if multithread and batch_size > 1: + max_threads = min(os.cpu_count() or 1, batch_size) + with ThreadPoolExecutor(max_workers=max_threads) as executor: + out = list(executor.map(process, range(batch_size))) + else: + out = [process(i) for i in range(batch_size)] + + out = torch.stack(out, dim=0).to(torch.float32).clamp_(0, 1) + + return io.NodeOutput(out) + +class SaveImageWithAlpha: + def __init__(self): + self.output_dir = folder_paths.get_output_directory() + self.type = "output" + self.prefix_append = "" + + @classmethod + def INPUT_TYPES(s): + return {"required": + {"images": ("IMAGE", ), + "mask": ("MASK", ), + "filename_prefix": ("STRING", {"default": "ComfyUI"})}, + "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"}, + } + + RETURN_TYPES = () + FUNCTION = "save_images_alpha" + OUTPUT_NODE = True + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Saves an image and mask as .PNG with the mask as the alpha channel. +""" + + def save_images_alpha(self, images, mask, filename_prefix="ComfyUI_image_with_alpha", prompt=None, extra_pnginfo=None): + filename_prefix += self.prefix_append + full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir, images[0].shape[1], images[0].shape[0]) + results = list() + def file_counter(): + max_counter = 0 + # Loop through the existing files + for existing_file in sorted(os.listdir(full_output_folder)): + # Check if the file matches the expected format + match = re.fullmatch(fr"{filename}_(\d+)_?\.[a-zA-Z0-9]+", existing_file) + if match: + # Extract the numeric portion of the filename + file_counter = int(match.group(1)) + # Update the maximum counter value if necessary + if file_counter > max_counter: + max_counter = file_counter + return max_counter + + for image, alpha in zip(images, mask): + i = 255. * image.cpu().numpy() + a = 255. * (1.0 - alpha.cpu().float()).numpy() + img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8)) + + # Resize the mask to match the image size + a_resized = Image.fromarray(a).resize(img.size, Image.LANCZOS) + a_resized = np.clip(a_resized, 0, 255).astype(np.uint8) + img.putalpha(Image.fromarray(a_resized, mode='L')) + metadata = None + if not args.disable_metadata: + metadata = PngInfo() + 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])) + + # Increment the counter by 1 to get the next available value + counter = file_counter() + 1 + file = f"{filename}_{counter:05}.png" + img.save(os.path.join(full_output_folder, file), pnginfo=metadata, compress_level=4) + results.append({ + "filename": file, + "subfolder": subfolder, + "type": self.type + }) + + return { "ui": { "images": results } } + +class ImageConcanate: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "image1": ("IMAGE",), + "image2": ("IMAGE",), + "direction": ( + [ 'right', + 'down', + 'left', + 'up', + ], + { + "default": 'right' + }), + "match_image_size": ("BOOLEAN", {"default": True}), + }} + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "concatenate" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Concatenates the image2 to image1 in the specified direction. +""" + + def concatenate(self, image1, image2, direction, match_image_size, first_image_shape=None): + # Check if the batch sizes are different + batch_size1 = image1.shape[0] + batch_size2 = image2.shape[0] + + if batch_size1 != batch_size2: + # Calculate the number of repetitions needed + max_batch_size = max(batch_size1, batch_size2) + repeats1 = max_batch_size - batch_size1 + repeats2 = max_batch_size - batch_size2 + + # Repeat the last image to match the largest batch size + if repeats1 > 0: + last_image1 = image1[-1].unsqueeze(0).repeat(repeats1, 1, 1, 1) + image1 = torch.cat([image1.clone(), last_image1], dim=0) + if repeats2 > 0: + last_image2 = image2[-1].unsqueeze(0).repeat(repeats2, 1, 1, 1) + image2 = torch.cat([image2.clone(), last_image2], dim=0) + + if match_image_size: + # Use first_image_shape if provided; otherwise, default to image1's shape + target_shape = first_image_shape if first_image_shape is not None else image1.shape + + original_height = image2.shape[1] + original_width = image2.shape[2] + original_aspect_ratio = original_width / original_height + + if direction in ['left', 'right']: + # Match the height and adjust the width to preserve aspect ratio + target_height = target_shape[1] # B, H, W, C format + target_width = int(target_height * original_aspect_ratio) + elif direction in ['up', 'down']: + # Match the width and adjust the height to preserve aspect ratio + target_width = target_shape[2] # B, H, W, C format + target_height = int(target_width / original_aspect_ratio) + + # Adjust image2 to the expected format for common_upscale + image2_for_upscale = image2.movedim(-1, 1) # Move C to the second position (B, C, H, W) + + # Resize image2 to match the target size while preserving aspect ratio + image2_resized = common_upscale(image2_for_upscale, target_width, target_height, "lanczos", "disabled") + + # Adjust image2 back to the original format (B, H, W, C) after resizing + image2_resized = image2_resized.movedim(1, -1) + else: + image2_resized = image2 + + # Ensure both images have the same number of channels + channels_image1 = image1.shape[-1] + channels_image2 = image2_resized.shape[-1] + + if channels_image1 != channels_image2: + if channels_image1 < channels_image2: + # Add alpha channel to image1 if image2 has it + alpha_channel = torch.ones((*image1.shape[:-1], channels_image2 - channels_image1), device=image1.device) + image1 = torch.cat((image1, alpha_channel), dim=-1) + else: + # Add alpha channel to image2 if image1 has it + alpha_channel = torch.ones((*image2_resized.shape[:-1], channels_image1 - channels_image2), device=image2_resized.device) + image2_resized = torch.cat((image2_resized, alpha_channel), dim=-1) + + + # Concatenate based on the specified direction + if direction == 'right': + concatenated_image = torch.cat((image1, image2_resized), dim=2) # Concatenate along width + elif direction == 'down': + concatenated_image = torch.cat((image1, image2_resized), dim=1) # Concatenate along height + elif direction == 'left': + concatenated_image = torch.cat((image2_resized, image1), dim=2) # Concatenate along width + elif direction == 'up': + concatenated_image = torch.cat((image2_resized, image1), dim=1) # Concatenate along height + return concatenated_image, + +class ImageConcatFromBatch: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "images": ("IMAGE",), + "num_columns": ("INT", {"default": 3, "min": 1, "max": 255, "step": 1}), + "match_image_size": ("BOOLEAN", {"default": False}), + "max_resolution": ("INT", {"default": 4096}), + }, + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "concat" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ + Concatenates images from a batch into a grid with a specified number of columns. + """ + + def concat(self, images, num_columns, match_image_size, max_resolution): + # Assuming images is a batch of images (B, H, W, C) + batch_size, height, width, channels = images.shape + num_rows = (batch_size + num_columns - 1) // num_columns # Calculate number of rows + + logging.info(f"Initial dimensions: batch_size={batch_size}, height={height}, width={width}, channels={channels}") + logging.info(f"num_rows={num_rows}, num_columns={num_columns}") + + if match_image_size: + target_shape = images[0].shape + + resized_images = [] + for image in images: + original_height = image.shape[0] + original_width = image.shape[1] + original_aspect_ratio = original_width / original_height + + if original_aspect_ratio > 1: + target_height = target_shape[0] + target_width = int(target_height * original_aspect_ratio) + else: + target_width = target_shape[1] + target_height = int(target_width / original_aspect_ratio) + + logging.info(f"Resizing image from ({original_height}, {original_width}) to ({target_height}, {target_width})") + + # Resize the image to match the target size while preserving aspect ratio + resized_image = common_upscale(image.movedim(-1, 0), target_width, target_height, "lanczos", "disabled") + resized_image = resized_image.movedim(0, -1) # Move channels back to the last dimension + resized_images.append(resized_image) + + # Convert the list of resized images back to a tensor + images = torch.stack(resized_images) + + height, width = target_shape[:2] # Update height and width + + # Initialize an empty grid + grid_height = num_rows * height + grid_width = num_columns * width + + logging.info(f"Grid dimensions before scaling: grid_height={grid_height}, grid_width={grid_width}") + + # Original scale factor calculation remains unchanged + scale_factor = min(max_resolution / grid_height, max_resolution / grid_width, 1.0) + + # Apply scale factor to height and width + scaled_height = height * scale_factor + scaled_width = width * scale_factor + + # Round scaled dimensions to the nearest number divisible by 8 + height = max(1, int(round(scaled_height / 8) * 8)) + width = max(1, int(round(scaled_width / 8) * 8)) + + if abs(scaled_height - height) > 4: + height = max(1, int(round((scaled_height + 4) / 8) * 8)) + if abs(scaled_width - width) > 4: + width = max(1, int(round((scaled_width + 4) / 8) * 8)) + + # Recalculate grid dimensions with adjusted height and width + grid_height = num_rows * height + grid_width = num_columns * width + logging.info(f"Grid dimensions after scaling: grid_height={grid_height}, grid_width={grid_width}") + logging.info(f"Final image dimensions: height={height}, width={width}") + + grid = torch.zeros((grid_height, grid_width, channels), dtype=images.dtype) + + for idx, image in enumerate(images): + resized_image = torch.nn.functional.interpolate(image.unsqueeze(0).permute(0, 3, 1, 2), size=(height, width), mode="bilinear").squeeze().permute(1, 2, 0) + row = idx // num_columns + col = idx % num_columns + grid[row*height:(row+1)*height, col*width:(col+1)*width, :] = resized_image + + return grid.unsqueeze(0), + + +class ImageGridComposite2x2: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "image1": ("IMAGE",), + "image2": ("IMAGE",), + "image3": ("IMAGE",), + "image4": ("IMAGE",), + }} + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "compositegrid" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Concatenates the 4 input images into a 2x2 grid. +""" + + def compositegrid(self, image1, image2, image3, image4): + top_row = torch.cat((image1, image2), dim=2) + bottom_row = torch.cat((image3, image4), dim=2) + grid = torch.cat((top_row, bottom_row), dim=1) + return (grid,) + +class ImageGridComposite3x3: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "image1": ("IMAGE",), + "image2": ("IMAGE",), + "image3": ("IMAGE",), + "image4": ("IMAGE",), + "image5": ("IMAGE",), + "image6": ("IMAGE",), + "image7": ("IMAGE",), + "image8": ("IMAGE",), + "image9": ("IMAGE",), + }} + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "compositegrid" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Concatenates the 9 input images into a 3x3 grid. +""" + + def compositegrid(self, image1, image2, image3, image4, image5, image6, image7, image8, image9): + top_row = torch.cat((image1, image2, image3), dim=2) + mid_row = torch.cat((image4, image5, image6), dim=2) + bottom_row = torch.cat((image7, image8, image9), dim=2) + grid = torch.cat((top_row, mid_row, bottom_row), dim=1) + return (grid,) + +class ImageBatchTestPattern: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "batch_size": ("INT", {"default": 1,"min": 1, "max": 255, "step": 1}), + "start_from": ("INT", {"default": 0,"min": 0, "max": 255, "step": 1}), + "text_x": ("INT", {"default": 256,"min": 0, "max": 4096, "step": 1}), + "text_y": ("INT", {"default": 256,"min": 0, "max": 4096, "step": 1}), + "width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "font": (folder_paths.get_filename_list("kjnodes_fonts"), ), + "font_size": ("INT", {"default": 255,"min": 8, "max": 4096, "step": 1}), + }} + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "generatetestpattern" + CATEGORY = "KJNodes/text" + + def generatetestpattern(self, batch_size, font, font_size, start_from, width, height, text_x, text_y): + out = [] + # Generate the sequential numbers for each image + numbers = np.arange(start_from, start_from + batch_size) + font_path = folder_paths.get_full_path("kjnodes_fonts", font) + + for number in numbers: + # Create a black image with the number as a random color text + image = Image.new("RGB", (width, height), color='black') + draw = ImageDraw.Draw(image) + + # Generate a random color for the text + font_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) + + font = ImageFont.truetype(font_path, font_size) + + # Get the size of the text and position it in the center + text = str(number) + + try: + draw.text((text_x, text_y), text, font=font, fill=font_color, features=['-liga']) + except: + draw.text((text_x, text_y), text, font=font, fill=font_color,) + + # Convert the image to a numpy array and normalize the pixel values + image_np = np.array(image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np).unsqueeze(0) + out.append(image_tensor) + out_tensor = torch.cat(out, dim=0) + + return (out_tensor,) + +class ImageGrabPIL: + + @classmethod + def IS_CHANGED(cls): + + return + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("image",) + FUNCTION = "screencap" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Captures an area specified by screen coordinates. +Can be used for realtime diffusion with autoqueue. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "x": ("INT", {"default": 0,"min": 0, "max": 4096, "step": 1}), + "y": ("INT", {"default": 0,"min": 0, "max": 4096, "step": 1}), + "width": ("INT", {"default": 512,"min": 0, "max": 4096, "step": 1}), + "height": ("INT", {"default": 512,"min": 0, "max": 4096, "step": 1}), + "num_frames": ("INT", {"default": 1,"min": 1, "max": 255, "step": 1}), + "delay": ("FLOAT", {"default": 0.1,"min": 0.0, "max": 10.0, "step": 0.01}), + }, + } + + def screencap(self, x, y, width, height, num_frames, delay): + start_time = time.time() + captures = [] + bbox = (x, y, x + width, y + height) + + for _ in range(num_frames): + # Capture screen + screen_capture = ImageGrab.grab(bbox=bbox) + screen_capture_torch = torch.from_numpy(np.array(screen_capture, dtype=np.float32) / 255.0).unsqueeze(0) + captures.append(screen_capture_torch) + + # Wait for a short delay if more than one frame is to be captured + if num_frames > 1: + time.sleep(delay) + + elapsed_time = time.time() - start_time + logging.info(f"screengrab took {elapsed_time} seconds.") + + return (torch.cat(captures, dim=0),) + +class Screencap_mss: + + @classmethod + def IS_CHANGED(s, **kwargs): + return float("NaN") + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("image",) + FUNCTION = "screencap" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Captures an area specified by screen coordinates. +Can be used for realtime diffusion with autoqueue. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "x": ("INT", {"default": 0,"min": 0, "max": 10000, "step": 1}), + "y": ("INT", {"default": 0,"min": 0, "max": 10000, "step": 1}), + "width": ("INT", {"default": 512,"min": 0, "max": 10000, "step": 1}), + "height": ("INT", {"default": 512,"min": 0, "max": 10000, "step": 1}), + "num_frames": ("INT", {"default": 1,"min": 1, "max": 255, "step": 1}), + "delay": ("FLOAT", {"default": 0.1,"min": 0.0, "max": 10.0, "step": 0.01}), + }, + } + + def screencap(self, x, y, width, height, num_frames, delay): + from mss import mss + captures = [] + with mss() as sct: + bbox = {'top': y, 'left': x, 'width': width, 'height': height} + + for _ in range(num_frames): + sct_img = sct.grab(bbox) + img_np = np.array(sct_img) + img_torch = torch.from_numpy(img_np[..., [2, 1, 0]]).float() / 255.0 + captures.append(img_torch) + + if num_frames > 1: + time.sleep(delay) + + return (torch.stack(captures, 0),) + +class ScreencapStream: + + @classmethod + def IS_CHANGED(s, **kwargs): + return float("NaN") + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("image",) + FUNCTION = "capture" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Captures a frame from a browser screen/window share stream. +Click 'Start capture' to select a screen or window to share. +Live preview is shown in the node. Works with auto-queue. + +Crop controls: +- Drag on preview to draw a crop box +- Drag inside the box to move it +- Drag edges or corners to resize +- Shift+drag to lock aspect ratio +- Right-click or double-click to clear crop +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "frame_data": ("STRING", {"default": "", "multiline": False}), + "crop_width": ("INT", {"default": 1, "min": 1, "max": MAX_RESOLUTION, "step": 1}), + "crop_height": ("INT", {"default": 1, "min": 1, "max": MAX_RESOLUTION, "step": 1}), + }, + } + + MAX_FRAME_BYTES = 50 * 1024 * 1024 # 50MB base64 limit (PNG is larger than JPEG) + + def capture(self, crop_width, crop_height, frame_data): + if not frame_data: + w = crop_width if crop_width > 0 else 512 + h = crop_height if crop_height > 0 else 512 + return (torch.zeros(1, h, w, 3),) + if len(frame_data) > self.MAX_FRAME_BYTES: + raise ValueError(f"Frame data exceeds {self.MAX_FRAME_BYTES // (1024*1024)}MB limit") + try: + img_bytes = base64.b64decode(frame_data.split(",", 1)[-1]) + except Exception: + raise ValueError("Invalid frame data encoding") + img = Image.open(BytesIO(img_bytes)).convert("RGB") + img_np = np.array(img).astype(np.float32) / 255.0 + img_tensor = torch.from_numpy(img_np).unsqueeze(0) + return (img_tensor,) + +class WebcamCaptureCV2: + + @classmethod + def IS_CHANGED(cls): + return + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("image",) + FUNCTION = "capture" + CATEGORY = "KJNodes/experimental" + DESCRIPTION = """ +Captures a frame from a webcam using CV2. +Can be used for realtime diffusion with autoqueue. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "x": ("INT", {"default": 0,"min": 0, "max": 4096, "step": 1}), + "y": ("INT", {"default": 0,"min": 0, "max": 4096, "step": 1}), + "width": ("INT", {"default": 512,"min": 0, "max": 4096, "step": 1}), + "height": ("INT", {"default": 512,"min": 0, "max": 4096, "step": 1}), + "cam_index": ("INT", {"default": 0,"min": 0, "max": 255, "step": 1}), + "release": ("BOOLEAN", {"default": False}), + }, + } + + def capture(self, x, y, cam_index, width, height, release): + # Check if the camera index has changed or the capture object doesn't exist + if not hasattr(self, "cap") or self.cap is None or self.current_cam_index != cam_index: + if hasattr(self, "cap") and self.cap is not None: + self.cap.release() + self.current_cam_index = cam_index + self.cap = cv2.VideoCapture(cam_index) + try: + self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, width) + self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height) + except: + pass + if not self.cap.isOpened(): + raise Exception("Could not open webcam") + + ret, frame = self.cap.read() + if not ret: + raise Exception("Failed to capture image from webcam") + + # Crop the frame to the specified bbox + frame = frame[y:y+height, x:x+width] + img_torch = torch.from_numpy(frame[..., [2, 1, 0]]).float() / 255.0 + + if release: + self.cap.release() + self.cap = None + + return (img_torch.unsqueeze(0),) + +class AddLabel: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "image":("IMAGE",), + "text_x": ("INT", {"default": 10, "min": 0, "max": 4096, "step": 1}), + "text_y": ("INT", {"default": 2, "min": 0, "max": 4096, "step": 1}), + "height": ("INT", {"default": 48, "min": -1, "max": 4096, "step": 1}), + "font_size": ("INT", {"default": 32, "min": 0, "max": 4096, "step": 1}), + "font_color": ("STRING", {"default": "white"}), + "label_color": ("STRING", {"default": "black"}), + "font": (folder_paths.get_filename_list("kjnodes_fonts"), ), + "text": ("STRING", {"default": "Text"}), + "direction": ( + [ 'up', + 'down', + 'left', + 'right', + 'overlay' + ], + { + "default": 'up' + }), + }, + "optional":{ + "caption": ("STRING", {"default": "", "forceInput": True}), + } + } + RETURN_TYPES = ("IMAGE",) + FUNCTION = "addlabel" + CATEGORY = "KJNodes/text" + DESCRIPTION = """ +Creates a new with the given text, and concatenates it to +either above or below the input image. +Note that this changes the input image's height! +Fonts are loaded from this folder: +ComfyUI/custom_nodes/ComfyUI-KJNodes/fonts +""" + + def addlabel(self, image, text_x, text_y, text, height, font_size, font_color, label_color, font, direction, caption=""): + batch_size = image.shape[0] + width = image.shape[2] + + font_path = os.path.join(script_directory, "fonts", "TTNorms-Black.otf") if font == "TTNorms-Black.otf" else folder_paths.get_full_path("kjnodes_fonts", font) + + # Parse colors using helper function + font_color_rgb = string_to_color(font_color) + label_color_rgb = string_to_color(label_color) + + # Convert to tuples for PIL + font_color_tuple = tuple(font_color_rgb[:3]) # RGB only + label_color_tuple = tuple(label_color_rgb[:3]) # RGB only + + def process_image(input_image, caption_text): + font = ImageFont.truetype(font_path, font_size) + lines = [] + for text_line in caption_text.split('\n'): + if text_line.strip() == "": + # Preserve empty lines for multiple newlines + lines.append("") + continue + words = text_line.split() + current_line = [] + for word in words: + if current_line: + test_line = " ".join(current_line + [word]) + else: + test_line = word + try: + test_line_width = font.getbbox(test_line)[2] + except Exception: + test_line_width = font.getsize(test_line)[0] + if test_line_width <= width - 2 * text_x: + current_line.append(word) + else: + lines.append(" ".join(current_line)) + current_line = [word] + if current_line: + lines.append(" ".join(current_line)) + + if direction == 'overlay': + pil_image = Image.fromarray((input_image.cpu().numpy() * 255).astype(np.uint8)) + else: + if height == -1: + # Adjust the image height automatically + margin = 8 + required_height = (text_y + len(lines) * font_size) + margin # Calculate required height + pil_image = Image.new("RGB", (width, required_height), label_color_tuple) + else: + # Initialize with a minimal height + label_image = Image.new("RGB", (width, height), label_color_tuple) + pil_image = label_image + + draw = ImageDraw.Draw(pil_image) + + + y_offset = text_y + for line in lines: + try: + draw.text((text_x, y_offset), line, font=font, fill=font_color_tuple, features=['-liga']) + except: + draw.text((text_x, y_offset), line, font=font, fill=font_color_tuple) + y_offset += font_size + + processed_image = torch.from_numpy(np.array(pil_image).astype(np.float32) / 255.0).unsqueeze(0) + return processed_image + + if caption == "": + processed_images = [process_image(img, text) for img in image] + else: + assert len(caption) == batch_size, f"Number of captions {(len(caption))} does not match number of images" + processed_images = [process_image(img, cap) for img, cap in zip(image, caption)] + processed_batch = torch.cat(processed_images, dim=0) + + # Combine images based on direction + if direction == 'down': + combined_images = torch.cat((image, processed_batch), dim=1) + elif direction == 'up': + combined_images = torch.cat((processed_batch, image), dim=1) + elif direction == 'left': + processed_batch = torch.rot90(processed_batch, 3, (2, 3)).permute(0, 3, 1, 2) + combined_images = torch.cat((processed_batch, image), dim=2) + elif direction == 'right': + processed_batch = torch.rot90(processed_batch, 3, (2, 3)).permute(0, 3, 1, 2) + combined_images = torch.cat((image, processed_batch), dim=2) + else: + combined_images = processed_batch + + return (combined_images,) + +class GetImageSizeAndCount: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "image": ("IMAGE",), + }} + + RETURN_TYPES = ("IMAGE","INT", "INT", "INT",) + RETURN_NAMES = ("image", "width", "height", "count",) + FUNCTION = "getsize" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Returns width, height and batch size of the image, +and passes it through unchanged. + +""" + + def getsize(self, image): + width = image.shape[2] + height = image.shape[1] + count = image.shape[0] + return {"ui": { + "text": [f"{count}x{width}x{height}"]}, + "result": (image, width, height, count) + } + +class GetLatentSizeAndCount: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "latent": ("LATENT",), + }} + + RETURN_TYPES = ("LATENT","INT", "INT", "INT", "INT", "INT") + RETURN_NAMES = ("latent", "batch_size", "channels", "frames", "height", "width") + FUNCTION = "getsize" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Returns latent tensor dimensions, +and passes the latent through unchanged. + +""" + def getsize(self, latent): + if len(latent["samples"].shape) == 5: + B, C, T, H, W = latent["samples"].shape + elif len(latent["samples"].shape) == 4: + B, C, H, W = latent["samples"].shape + T = 0 + else: + raise ValueError("Invalid latent shape") + + return {"ui": { + "text": [f"{B}x{C}x{T}x{H}x{W}"]}, + "result": (latent, B, C, T, H, W) + } + +class ImageBatchRepeatInterleaving: + RETURN_TYPES = ("IMAGE", "MASK",) + FUNCTION = "repeat" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Repeats each image in a batch by the specified number of times. +Example batch of 5 images: 0, 1 ,2, 3, 4 +with repeats 2 becomes batch of 10 images: 0, 0, 1, 1, 2, 2, 3, 3, 4, 4 +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "images": ("IMAGE",), + "repeats": ("INT", {"default": 1, "min": 1, "max": 4096}), + }, + "optional": { + "mask": ("MASK",), + } + } + + def repeat(self, images, repeats, mask=None): + original_count = images.shape[0] + total_count = original_count * repeats + + repeated_images = torch.repeat_interleave(images, repeats=repeats, dim=0) + if mask is not None: + mask = torch.repeat_interleave(mask, repeats=repeats, dim=0) + else: + mask = torch.zeros((total_count, images.shape[1], images.shape[2]), + device=images.device, dtype=images.dtype) + for i in range(original_count): + mask[i * repeats] = 1.0 + + return (repeated_images, mask) + +class ImageUpscaleWithModelBatched: + @classmethod + def INPUT_TYPES(s): + return {"required": { "upscale_model": ("UPSCALE_MODEL",), + "images": ("IMAGE",), + "per_batch": ("INT", {"default": 16, "min": 1, "max": 4096, "step": 1}), + }, + "optional": { + "downscale_ratio": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 1.0, "step": 0.01}), + "downscale_method": (["nearest-exact", "bilinear", "area", "bicubic", "lanczos"], {"default": "lanczos"}), + "precision": (["float32", "float16", "bfloat16"], {"default": "float32"}), + }} + RETURN_TYPES = ("IMAGE",) + FUNCTION = "upscale" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Same as ComfyUI native model upscaling node, +but allows setting sub-batches for reduced VRAM usage. +Optionally downscale the result with a ratio. +""" + def upscale(self, upscale_model, images, per_batch, downscale_ratio=1.0, downscale_method="lanczos", precision="float32"): + dtype = torch.float16 if precision == "float16" else torch.bfloat16 if precision == "bfloat16" else torch.float32 + device = model_management.get_torch_device() + upscale_model.to(device, dtype=dtype) + in_img = images.movedim(-1,-3).to(dtype) + + steps = in_img.shape[0] + pbar = ProgressBar(steps) + t = [] + + for start_idx in range(0, in_img.shape[0], per_batch): + sub_images = upscale_model(in_img[start_idx:start_idx+per_batch].to(device)) + t.append(sub_images.cpu()) + # Calculate the number of images processed in this batch + batch_count = sub_images.shape[0] + # Update the progress bar by the number of images processed in this batch + pbar.update(batch_count) + upscale_model.cpu() + + t = torch.cat(t, dim=0).permute(0, 2, 3, 1).cpu().float() + + # Apply downscaling if ratio is less than 1.0 + if downscale_ratio < 1.0: + original_height = t.shape[1] + original_width = t.shape[2] + new_height = int(original_height * downscale_ratio) + new_width = int(original_width * downscale_ratio) + t = t.movedim(-1, 1) + t = common_upscale(t, new_width, new_height, downscale_method, "disabled") + t = t.movedim(1, -1) + + return (t,) + +class ImageNormalize_Neg1_To_1: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "images": ("IMAGE",), + + }} + RETURN_TYPES = ("IMAGE",) + FUNCTION = "normalize" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Normalize the images to be in the range [-1, 1] +""" + + def normalize(self,images): + images = images * 2.0 - 1.0 + return (images,) + +class RemapImageRange: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "image": ("IMAGE",), + "min": ("FLOAT", {"default": 0.0,"min": -10.0, "max": 1.0, "step": 0.01}), + "max": ("FLOAT", {"default": 1.0,"min": 0.0, "max": 10.0, "step": 0.01}), + "clamp": ("BOOLEAN", {"default": True}), + }, + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "remap" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Remaps the image values to the specified range. +""" + + def remap(self, image, min, max, clamp): + if image.dtype == torch.float16: + image = image.to(torch.float32) + image = min + image * (max - min) + if clamp: + image = torch.clamp(image, min=0.0, max=1.0) + return (image, ) + +class SplitImageChannels: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "image": ("IMAGE",), + }, + } + + RETURN_TYPES = ("IMAGE", "IMAGE", "IMAGE", "MASK") + RETURN_NAMES = ("red", "green", "blue", "mask") + FUNCTION = "split" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Splits image channels into images where the selected channel +is repeated for all channels, and the alpha as a mask. +""" + + def split(self, image): + red = image[:, :, :, 0:1] # Red channel + green = image[:, :, :, 1:2] # Green channel + blue = image[:, :, :, 2:3] # Blue channel + if image.shape[3] == 4: + alpha = image[:, :, :, 4] # Alpha channel + else: + alpha = torch.zeros(image.shape[0], image.shape[1], image.shape[2], device=image.device) + + # Repeat the selected channel for all channels + red = torch.cat([red, red, red], dim=3) + green = torch.cat([green, green, green], dim=3) + blue = torch.cat([blue, blue, blue], dim=3) + return (red, green, blue, alpha) + +class MergeImageChannels: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "red": ("IMAGE",), + "green": ("IMAGE",), + "blue": ("IMAGE",), + + }, + "optional": { + "alpha": ("MASK", {"default": None}), + }, + } + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("image",) + FUNCTION = "merge" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Merges channel data into an image. +""" + + def merge(self, red, green, blue, alpha=None): + image = torch.stack([ + red[..., 0, None], # Red channel + green[..., 1, None], # Green channel + blue[..., 2, None] # Blue channel + ], dim=-1) + image = image.squeeze(-2) + if alpha is not None: + image = torch.cat([image, alpha.unsqueeze(-1)], dim=-1) + return (image,) + +class ImagePadForOutpaintMasked: + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "image": ("IMAGE",), + "left": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "top": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "right": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "bottom": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "feathering": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1}), + }, + "optional": { + "mask": ("MASK",), + } + } + + RETURN_TYPES = ("IMAGE", "MASK") + FUNCTION = "expand_image" + + CATEGORY = "image" + + def expand_image(self, image, left, top, right, bottom, feathering, mask=None): + if mask is not None: + if torch.allclose(mask, torch.zeros_like(mask)): + logging.warning("The incoming mask is fully black. Handling it as None.") + mask = None + B, H, W, C = image.size() + + new_image = torch.ones( + (B, H + top + bottom, W + left + right, C), + dtype=torch.float32, + ) * 0.5 + + new_image[:, top:top + H, left:left + W, :] = image + + if mask is None: + new_mask = torch.ones( + (B, H + top + bottom, W + left + right), + dtype=torch.float32, + ) + + t = torch.zeros( + (B, H, W), + dtype=torch.float32 + ) + else: + # If a mask is provided, pad it to fit the new image size + mask = F.pad(mask, (left, right, top, bottom), mode='constant', value=0) + mask = 1 - mask + t = torch.zeros_like(mask) + + if feathering > 0 and feathering * 2 < H and feathering * 2 < W: + + for i in range(H): + for j in range(W): + dt = i if top != 0 else H + db = H - i if bottom != 0 else H + + dl = j if left != 0 else W + dr = W - j if right != 0 else W + + d = min(dt, db, dl, dr) + + if d >= feathering: + continue + + v = (feathering - d) / feathering + + if mask is None: + t[:, i, j] = v * v + else: + t[:, top + i, left + j] = v * v + + if mask is None: + new_mask[:, top:top + H, left:left + W] = t + return (new_image, new_mask,) + else: + return (new_image, mask,) + +class ImagePadForOutpaintTargetSize: + upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"] + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "image": ("IMAGE",), + "target_width": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "target_height": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "feathering": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1}), + "upscale_method": (s.upscale_methods,), + }, + "optional": { + "mask": ("MASK",), + } + } + + RETURN_TYPES = ("IMAGE", "MASK") + FUNCTION = "expand_image" + + CATEGORY = "image" + + def expand_image(self, image, target_width, target_height, feathering, upscale_method, mask=None): + B, H, W, C = image.size() + new_height = H + new_width = W + # Calculate the scaling factor while maintaining aspect ratio + scaling_factor = min(target_width / W, target_height / H) + + # Check if the image needs to be downscaled + if scaling_factor < 1: + image = image.movedim(-1,1) + # Calculate the new width and height after downscaling + new_width = int(W * scaling_factor) + new_height = int(H * scaling_factor) + + # Downscale the image + image_scaled = common_upscale(image, new_width, new_height, upscale_method, "disabled").movedim(1,-1) + else: + # If downscaling is not needed, use the original image dimensions + image_scaled = image + + # Ensure mask dimensions match image dimensions + if mask is not None: + mask_scaled = mask.unsqueeze(0) # Add an extra dimension for batch size + mask_scaled = F.interpolate(mask_scaled, size=(new_height, new_width), mode="nearest") + mask_scaled = mask_scaled.squeeze(0) # Remove the extra dimension after interpolation + else: + mask_scaled = None + + # Calculate how much padding is needed to reach the target dimensions + pad_top = max(0, (target_height - new_height) // 2) + pad_bottom = max(0, target_height - new_height - pad_top) + pad_left = max(0, (target_width - new_width) // 2) + pad_right = max(0, target_width - new_width - pad_left) + + # Now call the original expand_image with the calculated padding + return ImagePadForOutpaintMasked.expand_image(self, image_scaled, pad_left, pad_top, pad_right, pad_bottom, feathering, mask_scaled) + +class ImagePrepForICLora: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "reference_image": ("IMAGE",), + "output_width": ("INT", {"default": 1024, "min": 1, "max": 4096, "step": 1}), + "output_height": ("INT", {"default": 1024, "min": 1, "max": 4096, "step": 1}), + "border_width": ("INT", {"default": 0, "min": 0, "max": 4096, "step": 1}), + }, + "optional": { + "latent_image": ("IMAGE",), + "latent_mask": ("MASK",), + "reference_mask": ("MASK",), + } + } + + RETURN_TYPES = ("IMAGE", "MASK") + FUNCTION = "expand_image" + + CATEGORY = "image" + + def expand_image(self, reference_image, output_width, output_height, border_width, latent_image=None, reference_mask=None, latent_mask=None): + + if reference_mask is not None: + if torch.allclose(reference_mask, torch.zeros_like(reference_mask)): + logging.warning("The incoming mask is fully black. Handling it as None.") + reference_mask = None + image = reference_image + if latent_image is not None: + if image.shape[0] != latent_image.shape[0]: + image = image.repeat(latent_image.shape[0], 1, 1, 1) + B, H, W, C = image.size() + + # Handle mask + if reference_mask is not None: + resized_mask = torch.nn.functional.interpolate( + reference_mask.unsqueeze(1), + size=(H, W), + mode='nearest' + ).squeeze(1) + image = image * resized_mask.unsqueeze(-1) + + # Calculate new width maintaining aspect ratio + new_width = int((W / H) * output_height) + + # Resize image to new height while maintaining aspect ratio + resized_image = common_upscale(image.movedim(-1,1), new_width, output_height, "lanczos", "disabled").movedim(1,-1) + + # Create padded image + if latent_image is None: + pad_image = torch.zeros((B, output_height, output_width, C), device=image.device) + else: + resized_latent_image = common_upscale(latent_image.movedim(-1,1), output_width, output_height, "lanczos", "disabled").movedim(1,-1) + pad_image = resized_latent_image + if latent_mask is not None: + resized_latent_mask = torch.nn.functional.interpolate( + latent_mask.unsqueeze(1), + size=(pad_image.shape[1], pad_image.shape[2]), + mode='nearest' + ).squeeze(1) + + if border_width > 0: + border = torch.zeros((B, output_height, border_width, C), device=image.device) + padded_image = torch.cat((resized_image, border, pad_image), dim=2) + if latent_mask is not None: + padded_mask = torch.zeros((B, padded_image.shape[1], padded_image.shape[2]), device=image.device) + padded_mask[:, :, (new_width + border_width):] = resized_latent_mask + else: + padded_mask = torch.ones((B, padded_image.shape[1], padded_image.shape[2]), device=image.device) + padded_mask[:, :, :new_width + border_width] = 0 + else: + padded_image = torch.cat((resized_image, pad_image), dim=2) + if latent_mask is not None: + padded_mask = torch.zeros((B, padded_image.shape[1], padded_image.shape[2]), device=image.device) + padded_mask[:, :, new_width:] = resized_latent_mask + else: + padded_mask = torch.ones((B, padded_image.shape[1], padded_image.shape[2]), device=image.device) + padded_mask[:, :, :new_width] = 0 + + return (padded_image, padded_mask) + + +class ImageAndMaskPreview(SaveImage): + def __init__(self): + self.output_dir = folder_paths.get_temp_directory() + self.type = "temp" + self.prefix_append = "_temp_" + ''.join(random.choice("abcdefghijklmnopqrstupvxyz") for x in range(5)) + self.compress_level = 4 + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "mask_opacity": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}), + "mask_color": ("STRING", {"default": "255, 255, 255", "tooltip": "RGB (255,255,255) or RGBA (255,255,255,128) or Hex (#RRGGBB / #RRGGBBAA)"}), + "pass_through": ("BOOLEAN", {"default": False}), + }, + "optional": { + "image": ("IMAGE",), + "mask": ("MASK",), + }, + "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"}, + } + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("composite",) + FUNCTION = "execute" + CATEGORY = "KJNodes/masking" + DESCRIPTION = """ +Preview an image or a mask, when both inputs are used +composites the mask on top of the image. +with pass_through on the preview is disabled and the +composite is returned from the composite slot instead, +this allows for the preview to be passed for video combine +nodes for example. Supports RGBA for mask_color to adjust transparency per color. +""" + + def execute(self, mask_opacity, mask_color, pass_through, filename_prefix="ComfyUI", image=None, mask=None, prompt=None, extra_pnginfo=None): + if mask is not None and image is None: + preview = mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])).movedim(1, -1).expand(-1, -1, -1, 3) + elif mask is None and image is not None: + preview = image + elif mask is not None and image is not None: + mask_adjusted = mask * mask_opacity + mask_image = mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])).movedim(1, -1).expand(-1, -1, -1, 3).clone() + + # Use helper function to parse color string + color_list = string_to_color(mask_color) + + # Apply RGB channels + mask_image[:, :, :, 0] = color_list[0] / 255 # Red channel + mask_image[:, :, :, 1] = color_list[1] / 255 # Green channel + mask_image[:, :, :, 2] = color_list[2] / 255 # Blue channel + + if len(color_list) == 4: # Apply Alpha channel if present + alpha_factor = color_list[3] / 255.0 + mask_adjusted = mask_adjusted * alpha_factor + + destination, source = node_helpers.image_alpha_fix(image, mask_image) + destination = destination.clone().movedim(-1, 1) + preview = composite(destination, source.movedim(-1, 1), 0, 0, mask_adjusted, 1, True).movedim(1, -1) + if pass_through: + return (preview, ) + return(self.save_images(preview, filename_prefix, prompt, extra_pnginfo)) + +def crossfade(images_1, images_2, alpha): + crossfade = (1 - alpha) * images_1 + alpha * images_2 + return crossfade +def ease_in(t): + return t * t +def ease_out(t): + return 1 - (1 - t) * (1 - t) +def ease_in_out(t): + return 3 * t * t - 2 * t * t * t +def bounce(t): + if t < 0.5: + return ease_out(t * 2) * 0.5 + else: + return ease_in((t - 0.5) * 2) * 0.5 + 0.5 +def elastic(t): + return math.sin(13 * math.pi / 2 * t) * math.pow(2, 10 * (t - 1)) +def glitchy(t): + return t + 0.1 * math.sin(40 * t) +def exponential_ease_out(t): + return 1 - (1 - t) ** 4 + +easing_functions = { + "linear": lambda t: t, + "ease_in": ease_in, + "ease_out": ease_out, + "ease_in_out": ease_in_out, + "bounce": bounce, + "elastic": elastic, + "glitchy": glitchy, + "exponential_ease_out": exponential_ease_out, +} + +class CrossFadeImages: + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "crossfadeimages" + CATEGORY = "KJNodes/image" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "images_1": ("IMAGE",), + "images_2": ("IMAGE",), + "interpolation": (["linear", "ease_in", "ease_out", "ease_in_out", "bounce", "elastic", "glitchy", "exponential_ease_out"],), + "transition_start_index": ("INT", {"default": 1,"min": -4096, "max": 4096, "step": 1}), + "transitioning_frames": ("INT", {"default": 1,"min": 0, "max": 4096, "step": 1}), + "start_level": ("FLOAT", {"default": 0.0,"min": 0.0, "max": 1.0, "step": 0.01}), + "end_level": ("FLOAT", {"default": 1.0,"min": 0.0, "max": 1.0, "step": 0.01}), + }, + } + + def crossfadeimages(self, images_1, images_2, transition_start_index, transitioning_frames, interpolation, start_level, end_level): + + crossfade_images = [] + + if transition_start_index < 0: + transition_start_index = len(images_1) + transition_start_index + if transition_start_index < 0: + raise ValueError("Transition start index is out of range for images_1.") + + transitioning_frames = min(transitioning_frames, len(images_1) - transition_start_index, len(images_2)) + + alphas = torch.linspace(start_level, end_level, transitioning_frames) + for i in range(transitioning_frames): + alpha = alphas[i] + image1 = images_1[transition_start_index + i] + image2 = images_2[i] + easing_function = easing_functions.get(interpolation) + alpha = easing_function(alpha) # Apply the easing function to the alpha value + + crossfade_image = crossfade(image1, image2, alpha) + crossfade_images.append(crossfade_image) + + # Convert crossfade_images to tensor + crossfade_images = torch.stack(crossfade_images, dim=0) + + # Append the beginning of images_1 (before the transition) + beginning_images_1 = images_1[:transition_start_index] + crossfade_images = torch.cat([beginning_images_1, crossfade_images], dim=0) + + # Append the remaining frames of images_2 (after the transition) + remaining_images_2 = images_2[transitioning_frames:] + if len(remaining_images_2) > 0: + crossfade_images = torch.cat([crossfade_images, remaining_images_2], dim=0) + + return (crossfade_images, ) + +class CrossFadeImagesMulti: + RETURN_TYPES = ("IMAGE",) + FUNCTION = "crossfadeimages" + CATEGORY = "KJNodes/image" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "inputcount": ("INT", {"default": 2, "min": 2, "max": 1000, "step": 1}), + "image_1": ("IMAGE",), + "interpolation": (["linear", "ease_in", "ease_out", "ease_in_out", "bounce", "elastic", "glitchy", "exponential_ease_out"],), + "transitioning_frames": ("INT", {"default": 1,"min": 0, "max": 4096, "step": 1}), + }, + "optional": { + "image_2": ("IMAGE",), + } + } + + def crossfadeimages(self, inputcount, transitioning_frames, interpolation, **kwargs): + + image_1 = kwargs["image_1"] + first_image_shape = image_1.shape + first_image_device = image_1.device + height = image_1.shape[1] + width = image_1.shape[2] + + easing_function = easing_functions[interpolation] + + for c in range(1, inputcount): + frames = [] + new_image = kwargs.get(f"image_{c + 1}", torch.zeros(first_image_shape)).to(first_image_device) + new_image_height = new_image.shape[1] + new_image_width = new_image.shape[2] + + if new_image_height != height or new_image_width != width: + new_image = common_upscale(new_image.movedim(-1, 1), width, height, "lanczos", "disabled") + new_image = new_image.movedim(1, -1) # Move channels back to the last dimension + + last_frame_image_1 = image_1[-1] + first_frame_image_2 = new_image[0] + + for frame in range(transitioning_frames): + t = frame / (transitioning_frames - 1) + alpha = easing_function(t) + alpha_tensor = torch.tensor(alpha, dtype=last_frame_image_1.dtype, device=last_frame_image_1.device) + frame_image = crossfade(last_frame_image_1, first_frame_image_2, alpha_tensor) + frames.append(frame_image) + + frames = torch.stack(frames) + image_1 = torch.cat((image_1, frames, new_image), dim=0) + + return image_1, + +def transition_images(images_1, images_2, alpha, transition_type, blur_radius, reverse): + width = images_1.shape[1] + height = images_1.shape[0] + + mask = torch.zeros_like(images_1, device=images_1.device) + + alpha = alpha.item() + if reverse: + alpha = 1 - alpha + + #transitions from matteo's essential nodes + if "horizontal slide" in transition_type: + pos = round(width * alpha) + mask[:, :pos, :] = 1.0 + elif "vertical slide" in transition_type: + pos = round(height * alpha) + mask[:pos, :, :] = 1.0 + elif "box" in transition_type: + box_w = round(width * alpha) + box_h = round(height * alpha) + x1 = (width - box_w) // 2 + y1 = (height - box_h) // 2 + x2 = x1 + box_w + y2 = y1 + box_h + mask[y1:y2, x1:x2, :] = 1.0 + elif "circle" in transition_type: + radius = math.ceil(math.sqrt(pow(width, 2) + pow(height, 2)) * alpha / 2) + c_x = width // 2 + c_y = height // 2 + x = torch.arange(0, width, dtype=torch.float32, device="cpu") + y = torch.arange(0, height, dtype=torch.float32, device="cpu") + y, x = torch.meshgrid((y, x), indexing="ij") + circle = ((x - c_x) ** 2 + (y - c_y) ** 2) <= (radius ** 2) + mask[circle] = 1.0 + elif "horizontal door" in transition_type: + bar = math.ceil(height * alpha / 2) + if bar > 0: + mask[:bar, :, :] = 1.0 + mask[-bar:,:, :] = 1.0 + elif "vertical door" in transition_type: + bar = math.ceil(width * alpha / 2) + if bar > 0: + mask[:, :bar,:] = 1.0 + mask[:, -bar:,:] = 1.0 + elif "fade" in transition_type: + mask[:, :, :] = alpha + + mask = gaussian_blur(mask, blur_radius) + + return images_1 * (1 - mask) + images_2 * mask + +def gaussian_blur(mask, blur_radius): + if blur_radius > 0: + kernel_size = int(blur_radius * 2) + 1 + if kernel_size % 2 == 0: + kernel_size += 1 # Ensure kernel size is odd + sigma = blur_radius / 3 + x = torch.arange(-kernel_size // 2 + 1, kernel_size // 2 + 1, dtype=torch.float32) + x = torch.exp(-0.5 * (x / sigma) ** 2) + kernel1d = x / x.sum() + kernel2d = kernel1d[:, None] * kernel1d[None, :] + kernel2d = kernel2d.to(mask.device) + kernel2d = kernel2d.expand(mask.shape[2], 1, kernel2d.shape[0], kernel2d.shape[1]) + mask = mask.permute(2, 0, 1).unsqueeze(0) # Change to [C, H, W] and add batch dimension + mask = F.conv2d(mask, kernel2d, padding=kernel_size // 2, groups=mask.shape[1]) + mask = mask.squeeze(0).permute(1, 2, 0) # Change back to [H, W, C] + return mask + +class TransitionImagesMulti: + RETURN_TYPES = ("IMAGE",) + FUNCTION = "transition" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Creates transitions between images. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "inputcount": ("INT", {"default": 2, "min": 2, "max": 1000, "step": 1}), + "image_1": ("IMAGE",), + "interpolation": (["linear", "ease_in", "ease_out", "ease_in_out", "bounce", "elastic", "glitchy", "exponential_ease_out"],), + "transition_type": (["horizontal slide", "vertical slide", "box", "circle", "horizontal door", "vertical door", "fade"],), + "transitioning_frames": ("INT", {"default": 2,"min": 2, "max": 4096, "step": 1}), + "blur_radius": ("FLOAT", {"default": 0.0,"min": 0.0, "max": 100.0, "step": 0.1}), + "reverse": ("BOOLEAN", {"default": False}), + "device": (["CPU", "GPU"], {"default": "CPU"}), + }, + "optional": { + "image_2": ("IMAGE",), + } + } + + def transition(self, inputcount, transitioning_frames, transition_type, interpolation, device, blur_radius, reverse, **kwargs): + + gpu = model_management.get_torch_device() + + image_1 = kwargs["image_1"] + height = image_1.shape[1] + width = image_1.shape[2] + first_image_shape = image_1.shape + first_image_device = image_1.device + + easing_function = easing_functions[interpolation] + + for c in range(1, inputcount): + frames = [] + new_image = kwargs.get(f"image_{c + 1}", torch.zeros(first_image_shape)).to(first_image_device) + new_image_height = new_image.shape[1] + new_image_width = new_image.shape[2] + + if new_image_height != height or new_image_width != width: + new_image = common_upscale(new_image.movedim(-1, 1), width, height, "lanczos", "disabled") + new_image = new_image.movedim(1, -1) # Move channels back to the last dimension + + last_frame_image_1 = image_1[-1] + first_frame_image_2 = new_image[0] + if device == "GPU": + last_frame_image_1 = last_frame_image_1.to(gpu) + first_frame_image_2 = first_frame_image_2.to(gpu) + + if reverse: + last_frame_image_1, first_frame_image_2 = first_frame_image_2, last_frame_image_1 + + for frame in range(transitioning_frames): + t = frame / (transitioning_frames - 1) + alpha = easing_function(t) + alpha_tensor = torch.tensor(alpha, dtype=last_frame_image_1.dtype, device=last_frame_image_1.device) + frame_image = transition_images(last_frame_image_1, first_frame_image_2, alpha_tensor, transition_type, blur_radius, reverse) + frames.append(frame_image) + + frames = torch.stack(frames).cpu() + image_1 = torch.cat((image_1, frames, new_image), dim=0) + + return image_1.cpu(), + +class TransitionImagesInBatch: + RETURN_TYPES = ("IMAGE",) + FUNCTION = "transition" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Creates transitions between images in a batch. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "images": ("IMAGE",), + "interpolation": (["linear", "ease_in", "ease_out", "ease_in_out", "bounce", "elastic", "glitchy", "exponential_ease_out"],), + "transition_type": (["horizontal slide", "vertical slide", "box", "circle", "horizontal door", "vertical door", "fade"],), + "transitioning_frames": ("INT", {"default": 1,"min": 0, "max": 4096, "step": 1}), + "blur_radius": ("FLOAT", {"default": 0.0,"min": 0.0, "max": 100.0, "step": 0.1}), + "reverse": ("BOOLEAN", {"default": False}), + "device": (["CPU", "GPU"], {"default": "CPU"}), + }, + } + + #transitions from matteo's essential nodes + def transition(self, images, transitioning_frames, transition_type, interpolation, device, blur_radius, reverse): + if images.shape[0] == 1: + return images, + + gpu = model_management.get_torch_device() + + easing_function = easing_functions[interpolation] + + images_list = [] + pbar = ProgressBar(images.shape[0] - 1) + for i in range(images.shape[0] - 1): + frames = [] + image_1 = images[i] + image_2 = images[i + 1] + + if device == "GPU": + image_1 = image_1.to(gpu) + image_2 = image_2.to(gpu) + + if reverse: + image_1, image_2 = image_2, image_1 + + for frame in range(transitioning_frames): + t = frame / (transitioning_frames - 1) + alpha = easing_function(t) + alpha_tensor = torch.tensor(alpha, dtype=image_1.dtype, device=image_1.device) + frame_image = transition_images(image_1, image_2, alpha_tensor, transition_type, blur_radius, reverse) + frames.append(frame_image) + pbar.update(1) + + frames = torch.stack(frames).cpu() + images_list.append(frames) + images = torch.cat(images_list, dim=0) + + return images.cpu(), + +class ImageBatchJoinWithTransition: + RETURN_TYPES = ("IMAGE",) + FUNCTION = "transition_batches" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Transitions between two batches of images, starting at a specified index in the first batch. +During the transition, frames from both batches are blended frame-by-frame, so the video keeps playing. +""" + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "images_1": ("IMAGE",), + "images_2": ("IMAGE",), + "start_index": ("INT", {"default": 0, "min": -10000, "max": 10000, "step": 1}), + "interpolation": (["linear", "ease_in", "ease_out", "ease_in_out", "bounce", "elastic", "glitchy", "exponential_ease_out"],), + "transition_type": (["horizontal slide", "vertical slide", "box", "circle", "horizontal door", "vertical door", "fade"],), + "transitioning_frames": ("INT", {"default": 1, "min": 1, "max": 4096, "step": 1}), + "blur_radius": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 100.0, "step": 0.1}), + "reverse": ("BOOLEAN", {"default": False}), + "device": (["CPU", "GPU"], {"default": "CPU"}), + }, + } + + def transition_batches(self, images_1, images_2, start_index, interpolation, transition_type, transitioning_frames, blur_radius, reverse, device): + if images_1.shape[0] == 0 or images_2.shape[0] == 0: + raise ValueError("Both input batches must have at least one image.") + + if start_index < 0: + start_index = images_1.shape[0] + start_index + if start_index < 0 or start_index > images_1.shape[0]: + raise ValueError("start_index is out of range.") + + gpu = model_management.get_torch_device() + easing_function = easing_functions[interpolation] + out_frames = [] + + # Add images from images_1 up to start_index + if start_index > 0: + out_frames.append(images_1[:start_index]) + + # Determine how many frames we can blend + max_transition = min(transitioning_frames, images_1.shape[0] - start_index, images_2.shape[0]) + + # Blend corresponding frames from both batches + for i in range(max_transition): + img1 = images_1[start_index + i] + img2 = images_2[i] + if device == "GPU": + img1 = img1.to(gpu) + img2 = img2.to(gpu) + if reverse: + img1, img2 = img2, img1 + t = i / (max_transition - 1) if max_transition > 1 else 1.0 + alpha = easing_function(t) + alpha_tensor = torch.tensor(alpha, dtype=img1.dtype, device=img1.device) + frame_image = transition_images(img1, img2, alpha_tensor, transition_type, blur_radius, reverse) + out_frames.append(frame_image.cpu().unsqueeze(0)) + + # Add remaining images from images_2 after transition + if images_2.shape[0] > max_transition: + out_frames.append(images_2[max_transition:]) + + # Concatenate all frames + out = torch.cat(out_frames, dim=0) + return (out.cpu(),) + +class ShuffleImageBatch: + RETURN_TYPES = ("IMAGE",) + FUNCTION = "shuffle" + CATEGORY = "KJNodes/image" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "images": ("IMAGE",), + "seed": ("INT", {"default": 123,"min": 0, "max": 0xffffffffffffffff, "step": 1}), + }, + } + + def shuffle(self, images, seed): + torch.manual_seed(seed) + B, H, W, C = images.shape + indices = torch.randperm(B) + shuffled_images = images[indices] + + return shuffled_images, + +class GetImageRangeFromBatch: + + RETURN_TYPES = ("IMAGE", "MASK", ) + FUNCTION = "imagesfrombatch" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Returns a range of images from a batch. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "start_index": ("INT", {"default": 0,"min": -1, "max": 4096, "step": 1}), + "num_frames": ("INT", {"default": 1,"min": 1, "max": 4096, "step": 1}), + }, + "optional": { + "images": ("IMAGE",), + "masks": ("MASK",), + } + } + + def imagesfrombatch(self, start_index, num_frames, images=None, masks=None): + chosen_images = None + chosen_masks = None + + # Process images if provided + if images is not None: + if start_index == -1: + start_index = max(0, len(images) - num_frames) + if start_index < 0 or start_index >= len(images): + raise ValueError("Start index is out of range") + end_index = min(start_index + num_frames, len(images)) + chosen_images = images[start_index:end_index] + + # Process masks if provided + if masks is not None: + if start_index == -1: + start_index = max(0, len(masks) - num_frames) + if start_index < 0 or start_index >= len(masks): + raise ValueError("Start index is out of range for masks") + end_index = min(start_index + num_frames, len(masks)) + chosen_masks = masks[start_index:end_index] + + return (chosen_images, chosen_masks,) + +class ImageBatchExtendWithOverlap: + + RETURN_TYPES = ("IMAGE", "IMAGE", "IMAGE", ) + RETURN_NAMES = ("source_images", "start_images", "extended_images") + OUTPUT_TOOLTIPS = ( + "The original source images (passthrough)", + "The input images used as the starting point for extension", + "The extended images with overlap, if no new images are provided this will be empty", + ) + FUNCTION = "imagesfrombatch" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Helper node for video generation extension +First input source and overlap amount to get the starting frames for the extension. +Then on another copy of the node provide the newly generated frames and choose how to overlap them. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "source_images": ("IMAGE", {"tooltip": "The source images to extend"}), + "overlap": ("INT", {"default": 13,"min": 1, "max": 4096, "step": 1, "tooltip": "Number of overlapping frames between source and new images"}), + "overlap_side": (["source", "new_images"], {"default": "source", "tooltip": "Which side to overlap on"}), + "overlap_mode": (["cut", "linear_blend", "ease_in_out", "filmic_crossfade", "perceptual_crossfade"], {"default": "linear_blend", "tooltip": "Method to use for overlapping frames"}), + }, + "optional": { + "new_images": ("IMAGE", {"tooltip": "The new images to extend with"}), + } + } + + def imagesfrombatch(self, source_images, overlap, overlap_side, overlap_mode, new_images=None): + if overlap > len(source_images): + return source_images, source_images, source_images + + if new_images is not None: + if source_images.shape[1:3] != new_images.shape[1:3]: + raise ValueError(f"Source and new images must have the same shape: {source_images.shape[1:3]} vs {new_images.shape[1:3]}") + # Determine where to place the overlap + prefix = source_images[:-overlap] + if overlap_side == "source": + blend_src = source_images[-overlap:] + blend_dst = new_images[:overlap] + elif overlap_side == "new_images": + blend_src = new_images[:overlap] + blend_dst = source_images[-overlap:] + suffix = new_images[overlap:] + + if overlap_mode == "linear_blend": + # Vectorized version - process all frames at once + alpha = torch.linspace(0, 1, overlap + 2, device=blend_src.device, dtype=blend_src.dtype)[1:-1] + alpha = alpha.view(-1, 1, 1, 1) # Shape: [overlap, 1, 1, 1] + blended_images = (1 - alpha) * blend_src + alpha * blend_dst + extended_images = torch.cat((prefix, blended_images, suffix), dim=0) + + elif overlap_mode == "filmic_crossfade": + gamma = 2.2 + alpha = torch.linspace(0, 1, overlap + 2, device=blend_src.device, dtype=blend_src.dtype)[1:-1] + alpha = alpha.view(-1, 1, 1, 1) + linear_src = torch.pow(blend_src, gamma) + linear_dst = torch.pow(blend_dst, gamma) + blended = (1 - alpha) * linear_src + alpha * linear_dst + blended_images = torch.pow(blended, 1.0 / gamma) + extended_images = torch.cat((prefix, blended_images, suffix), dim=0) + + elif overlap_mode == "perceptual_crossfade": + import kornia + alpha = torch.linspace(0, 1, overlap + 2, device=blend_src.device, dtype=blend_src.dtype)[1:-1] + + src_nchw = blend_src.movedim(-1, 1) + dst_nchw = blend_dst.movedim(-1, 1) + lab_src = kornia.color.rgb_to_lab(src_nchw) + lab_dst = kornia.color.rgb_to_lab(dst_nchw) + + # Blend in LAB space + alpha = alpha.view(-1, 1, 1, 1) # [N,1,1,1] for broadcasting + blended_lab = (1 - alpha) * lab_src + alpha * lab_dst + + # Convert back to RGB and reshape + blended_rgb = kornia.color.lab_to_rgb(blended_lab) + blended_images = blended_rgb.movedim(1, -1) # [N,C,H,W] -> [N,H,W,C] + extended_images = torch.cat((prefix, blended_images, suffix), dim=0) + + elif overlap_mode == "ease_in_out": + # Vectorized ease_in_out + t = torch.linspace(0, 1, overlap + 2, device=blend_src.device, dtype=blend_src.dtype)[1:-1] + eased_t = 3 * t * t - 2 * t * t * t # ease_in_out formula + eased_t = eased_t.view(-1, 1, 1, 1) + blended_images = (1 - eased_t) * blend_src + eased_t * blend_dst + extended_images = torch.cat((prefix, blended_images, suffix), dim=0) + + elif overlap_mode == "cut": + extended_images = torch.cat((prefix, suffix), dim=0) + if overlap_side == "new_images": + extended_images = torch.cat((source_images, new_images[overlap:]), dim=0) + elif overlap_side == "source": + extended_images = torch.cat((source_images[:-overlap], new_images), dim=0) + else: + extended_images = torch.zeros((1, 64, 64, 3), device="cpu") + + start_images = source_images[-overlap:] + + return (source_images, start_images, extended_images) + +class GetLatentRangeFromBatch: + + RETURN_TYPES = ("LATENT", ) + FUNCTION = "latentsfrombatch" + CATEGORY = "KJNodes/latents" + DESCRIPTION = """ +Returns a range of latents from a batch. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "latents": ("LATENT",), + "start_index": ("INT", {"default": 0,"min": -1, "max": 4096, "step": 1}), + "num_frames": ("INT", {"default": 1,"min": -1, "max": 4096, "step": 1}), + }, + } + + def latentsfrombatch(self, latents, start_index, num_frames): + chosen_latents = None + samples = latents["samples"] + if len(samples.shape) == 4: + B, C, H, W = samples.shape + num_latents = B + elif len(samples.shape) == 5: + B, C, T, H, W = samples.shape + num_latents = T + + if start_index == -1: + start_index = max(0, num_latents - num_frames) + if start_index < 0 or start_index >= num_latents: + raise ValueError("Start index is out of range") + + end_index = num_latents if num_frames == -1 else min(start_index + num_frames, num_latents) + + if len(samples.shape) == 4: + chosen_latents = samples[start_index:end_index] + elif len(samples.shape) == 5: + chosen_latents = samples[:, :, start_index:end_index] + + return ({"samples": chosen_latents.contiguous(),},) + +class InsertLatentToIndex: + + RETURN_TYPES = ("LATENT", ) + FUNCTION = "insert" + CATEGORY = "KJNodes/latents" + DESCRIPTION = """ +Inserts a latent at the specified index into the original latent batch. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "source": ("LATENT",), + "destination": ("LATENT",), + "index": ("INT", {"default": 0,"min": -1, "max": 4096, "step": 1}), + }, + } + + def insert(self, source, destination, index): + samples_destination = destination["samples"] + samples_source = source["samples"].to(samples_destination) + + if len(samples_source.shape) == 4: + B, C, H, W = samples_source.shape + num_latents = B + elif len(samples_source.shape) == 5: + B, C, T, H, W = samples_source.shape + num_latents = T + + if index >= num_latents or index < 0: + raise ValueError(f"Index {index} out of bounds for tensor with {num_latents} latents") + + if len(samples_source.shape) == 4: + joined_latents = torch.cat([ + samples_destination[:index], + samples_source, + samples_destination[index+1:] + ], dim=0) + else: + joined_latents = torch.cat([ + samples_destination[:, :, :index], + samples_source, + samples_destination[:, :, index+1:] + ], dim=2) + + return ({"samples": joined_latents,},) + +class ImageBatchFilter: + + RETURN_TYPES = ("IMAGE", "STRING",) + RETURN_NAMES = ("images", "removed_indices",) + FUNCTION = "filter" + CATEGORY = "KJNodes/image" + DESCRIPTION = "Removes empty images from a batch" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "images": ("IMAGE",), + "empty_color": ("STRING", {"default": "0, 0, 0"}), + "empty_threshold": ("FLOAT", {"default": 0.01,"min": 0.0, "max": 1.0, "step": 0.01}), + }, + "optional": { + "replacement_image": ("IMAGE",), + } + } + + def filter(self, images, empty_color, empty_threshold, replacement_image=None): + B, H, W, C = images.shape + + input_images = images.clone() + + empty_color_list = [int(color.strip()) for color in empty_color.split(',')] + empty_color_tensor = torch.tensor(empty_color_list, dtype=torch.float32).to(input_images.device) + + color_diff = torch.abs(input_images - empty_color_tensor) + mean_diff = color_diff.mean(dim=(1, 2, 3)) + + empty_indices = mean_diff <= empty_threshold + empty_indices_string = ', '.join([str(i) for i in range(B) if empty_indices[i]]) + + if replacement_image is not None: + B_rep, H_rep, W_rep, C_rep = replacement_image.shape + replacement = replacement_image.clone() + if (H_rep != images.shape[1]) or (W_rep != images.shape[2]) or (C_rep != images.shape[3]): + replacement = common_upscale(replacement.movedim(-1, 1), W, H, "lanczos", "center").movedim(1, -1) + input_images[empty_indices] = replacement[0] + + return (input_images, empty_indices_string,) + else: + non_empty_images = input_images[~empty_indices] + return (non_empty_images, empty_indices_string,) + +class GetImagesFromBatchIndexed: + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "indexedimagesfrombatch" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Selects and returns the images at the specified indices as an image batch. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "images": ("IMAGE",), + "indexes": ("STRING", {"default": "0, 1, 2", "multiline": True}), + }, + } + + def indexedimagesfrombatch(self, images, indexes): + + # Parse the indexes string into a list of integers + index_list = [int(index.strip()) for index in indexes.split(',')] + + # Convert list of indices to a PyTorch tensor + indices_tensor = torch.tensor(index_list, dtype=torch.long) + + # Select the images at the specified indices + chosen_images = images[indices_tensor] + + return (chosen_images,) + +class InsertImagesToBatchIndexed: + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "insertimagesfrombatch" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Inserts images at the specified indices into the original image batch. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "original_images": ("IMAGE",), + "images_to_insert": ("IMAGE",), + "indexes": ("STRING", {"default": "0, 1, 2", "multiline": True}), + }, + "optional": { + "mode": (["replace", "insert"],), + } + } + + def insertimagesfrombatch(self, original_images, images_to_insert, indexes, mode="replace"): + if indexes == "": + return (original_images,) + + input_images = original_images.clone() + + # Parse the indexes string into a list of integers + index_list = [int(index.strip()) for index in indexes.split(',')] + + # Convert list of indices to a PyTorch tensor + indices_tensor = torch.tensor(index_list, dtype=torch.long) + + # Ensure the images_to_insert is a tensor + if not isinstance(images_to_insert, torch.Tensor): + images_to_insert = torch.tensor(images_to_insert) + + if mode == "replace": + # Replace the images at the specified indices + for index, image in zip(indices_tensor, images_to_insert): + input_images[index] = image + else: + # Create a list to hold the new image sequence + new_images = [] + insert_offset = 0 + + for i in range(len(input_images) + len(indices_tensor)): + if insert_offset < len(indices_tensor) and i == indices_tensor[insert_offset]: + # Use modulo to cycle through images_to_insert + new_images.append(images_to_insert[insert_offset % len(images_to_insert)]) + insert_offset += 1 + else: + new_images.append(input_images[i - insert_offset]) + + # Convert the list back to a tensor + input_images = torch.stack(new_images, dim=0) + + return (input_images,) + +class PadImageBatchInterleaved: + + RETURN_TYPES = ("IMAGE", "MASK",) + RETURN_NAMES = ("images", "masks",) + FUNCTION = "pad" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Inserts empty frames between the images in a batch. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "images": ("IMAGE",), + "empty_frames_per_image": ("INT", {"default": 1,"min": 0, "max": 4096, "step": 1}), + "pad_frame_value": ("FLOAT", {"default": 0.0,"min": 0.0, "max": 1.0, "step": 0.01}), + "add_after_last": ("BOOLEAN", {"default": False}), + }, + } + + def pad(self, images, empty_frames_per_image, pad_frame_value, add_after_last): + B, H, W, C = images.shape + + # Handle single frame case specifically + if B == 1: + total_frames = 1 + empty_frames_per_image if add_after_last else 1 + else: + # Original B images + (B-1) sets of empty frames between them + total_frames = B + (B-1) * empty_frames_per_image + # Add additional empty frames after the last image if requested + if add_after_last: + total_frames += empty_frames_per_image + + # Create new tensor with zeros (empty frames) + padded_batch = torch.ones((total_frames, H, W, C), + dtype=images.dtype, + device=images.device) * pad_frame_value + # Create mask tensor (1 for original frames, 0 for empty frames) + mask = torch.zeros((total_frames, H, W), + dtype=images.dtype, + device=images.device) + + # Fill in original images at their new positions + for i in range(B): + if B == 1: + # For single frame, just place it at the beginning + new_pos = 0 + else: + # Each image is separated by empty_frames_per_image blank frames + new_pos = i * (empty_frames_per_image + 1) + + padded_batch[new_pos] = images[i] + mask[new_pos] = 1.0 # Mark this as an original frame + + return (padded_batch, mask) + +class ReplaceImagesInBatch: + + RETURN_TYPES = ("IMAGE", "MASK",) + FUNCTION = "replace" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Replaces the images in a batch, starting from the specified start index, +with the replacement images. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "start_index": ("INT", {"default": 1,"min": 0, "max": 4096, "step": 1}), + }, + "optional": { + "original_images": ("IMAGE",), + "replacement_images": ("IMAGE",), + "original_masks": ("MASK",), + "replacement_masks": ("MASK",), + } + } + + def replace(self, original_images=None, replacement_images=None, start_index=1, original_masks=None, replacement_masks=None): + images = None + masks = None + + if original_images is not None and replacement_images is not None: + if start_index >= len(original_images): + raise ValueError("ReplaceImagesInBatch: Start index is out of range") + end_index = start_index + len(replacement_images) + if end_index > len(original_images): + raise ValueError("ReplaceImagesInBatch: End index is out of range") + + original_images_copy = original_images.clone() + if original_images_copy.shape[2] != replacement_images.shape[2] or original_images_copy.shape[3] != replacement_images.shape[3]: + replacement_images = common_upscale(replacement_images.movedim(-1, 1), original_images_copy.shape[1], original_images_copy.shape[2], "lanczos", "center").movedim(1, -1) + + original_images_copy[start_index:end_index] = replacement_images + images = original_images_copy + else: + images = torch.zeros((1, 64, 64, 3)) + + if original_masks is not None and replacement_masks is not None: + if start_index >= len(original_masks): + raise ValueError("ReplaceImagesInBatch: Start index is out of range") + end_index = start_index + len(replacement_masks) + if end_index > len(original_masks): + raise ValueError("ReplaceImagesInBatch: End index is out of range") + + original_masks_copy = original_masks.clone() + if original_masks_copy.shape[1] != replacement_masks.shape[1] or original_masks_copy.shape[2] != replacement_masks.shape[2]: + replacement_masks = common_upscale(replacement_masks.unsqueeze(1), original_masks_copy.shape[1], original_masks_copy.shape[2], "nearest-exact", "center").squeeze(0) + + original_masks_copy[start_index:end_index] = replacement_masks + masks = original_masks_copy + else: + masks = torch.zeros((1, 64, 64)) + + return (images, masks) + + +class ReverseImageBatch: + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "reverseimagebatch" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Reverses the order of the images in a batch. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "images": ("IMAGE",), + }, + } + + def reverseimagebatch(self, images): + reversed_images = torch.flip(images, [0]) + return (reversed_images, ) + +class ImageBatchMulti: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "inputcount": ("INT", {"default": 2, "min": 2, "max": 1000, "step": 1}), + "image_1": ("IMAGE", ), + }, + "optional": { + "image_2": ("IMAGE", ), + } + } + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("images",) + FUNCTION = "combine" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Creates an image batch from multiple images. +You can set how many inputs the node has, +with the **inputcount** and clicking update. +""" + + def combine(self, inputcount, **kwargs): + first = kwargs["image_1"] + h, w = first.shape[1], first.shape[2] + + # determine output shape + max_ch = first.shape[-1] + total_frames = first.shape[0] + for c in range(1, inputcount): + img = kwargs.get(f"image_{c + 1}") + if img is not None: + max_ch = max(max_ch, img.shape[-1]) + total_frames += img.shape[0] + else: + total_frames += first.shape[0] + + # pre-allocate output + out = torch.empty((total_frames, h, w, max_ch), dtype=first.dtype) + offset = 0 + + for c in range(inputcount): + img = kwargs.get(f"image_{c + 1}", torch.zeros((first.shape[0], h, w, max_ch), dtype=first.dtype)) + + if img.shape[1:3] != (h, w): + img = common_upscale(img.movedim(-1, 1), w, h, "bilinear", "center").movedim(1, -1) + + if img.shape[-1] < max_ch: + img = torch.nn.functional.pad(img, (0, max_ch - img.shape[-1]), mode='constant', value=1.0) + + n = img.shape[0] + out[offset:offset + n].copy_(img, non_blocking=True) + offset += n + del img + + return (out.cpu(),) + + +class ImageTensorList: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "image1": ("IMAGE",), + "image2": ("IMAGE",), + }} + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "append" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Creates an image list from the input images. +""" + + def append(self, image1, image2): + image_list = [] + if isinstance(image1, torch.Tensor) and isinstance(image2, torch.Tensor): + image_list = [image1, image2] + elif isinstance(image1, list) and isinstance(image2, torch.Tensor): + image_list = image1 + [image2] + elif isinstance(image1, torch.Tensor) and isinstance(image2, list): + image_list = [image1] + image2 + elif isinstance(image1, list) and isinstance(image2, list): + image_list = image1 + image2 + return image_list, + +class ImageAddMulti: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "inputcount": ("INT", {"default": 2, "min": 2, "max": 1000, "step": 1}), + "image_1": ("IMAGE", ), + "image_2": ("IMAGE", ), + "blending": ( + [ 'add', + 'subtract', + 'multiply', + 'difference', + ], + { + "default": 'add' + }), + "blend_amount": ("FLOAT", {"default": 0.5, "min": 0, "max": 1, "step": 0.01}), + }, + } + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("images",) + FUNCTION = "add" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Add blends multiple images together. +You can set how many inputs the node has, +with the **inputcount** and clicking update. +""" + + def add(self, inputcount, blending, blend_amount, **kwargs): + image = kwargs["image_1"] + for c in range(1, inputcount): + new_image = kwargs[f"image_{c + 1}"] + if blending == "add": + image = torch.add(image * blend_amount, new_image * blend_amount) + elif blending == "subtract": + image = torch.sub(image * blend_amount, new_image * blend_amount) + elif blending == "multiply": + image = torch.mul(image * blend_amount, new_image * blend_amount) + elif blending == "difference": + image = torch.sub(image, new_image) + return (image,) + +class ImageConcatMulti: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "inputcount": ("INT", {"default": 2, "min": 2, "max": 1000, "step": 1}), + "image_1": ("IMAGE", ), + + "direction": ( + [ 'right', + 'down', + 'left', + 'up', + ], + { + "default": 'right' + }), + "match_image_size": ("BOOLEAN", {"default": False}), + }, + "optional": { + "image_2": ("IMAGE", ), + }, + } + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("images",) + FUNCTION = "combine" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Creates an image from multiple images. +You can set how many inputs the node has, +with the **inputcount** and clicking update. +""" + + def combine(self, inputcount, direction, match_image_size, **kwargs): + image = kwargs["image_1"] + first_image_shape = None + if first_image_shape is None: + first_image_shape = image.shape + for c in range(1, inputcount): + new_image = kwargs.get(f"image_{c + 1}", torch.zeros(first_image_shape)) + image, = ImageConcanate.concatenate(self, image, new_image, direction, match_image_size, first_image_shape=first_image_shape) + first_image_shape = None + return (image,) + +class PreviewAnimation: + def __init__(self): + self.output_dir = folder_paths.get_temp_directory() + self.type = "temp" + self.prefix_append = "_temp_" + ''.join(random.choice("abcdefghijklmnopqrstupvxyz") for x in range(5)) + self.compress_level = 1 + + methods = {"default": 4, "fastest": 0, "slowest": 6} + @classmethod + def INPUT_TYPES(s): + return {"required": + { + "fps": ("FLOAT", {"default": 8.0, "min": 0.01, "max": 1000.0, "step": 0.01}), + }, + "optional": { + "images": ("IMAGE", ), + "masks": ("MASK", ), + }, + } + + RETURN_TYPES = () + FUNCTION = "preview" + OUTPUT_NODE = True + CATEGORY = "KJNodes/image" + + def preview(self, fps, images=None, masks=None): + filename_prefix = "AnimPreview" + full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir) + results = list() + + pil_images = [] + + if images is not None and masks is not None: + for image in images: + i = 255. * image.cpu().numpy() + img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8)) + pil_images.append(img) + for mask in masks: + if pil_images: + mask_np = mask.cpu().numpy() + mask_np = np.clip(mask_np * 255, 0, 255).astype(np.uint8) # Convert to values between 0 and 255 + mask_img = Image.fromarray(mask_np, mode='L') + img = pil_images.pop(0) # Remove and get the first image + img = img.convert("RGBA") # Convert base image to RGBA + + # Create a new RGBA image based on the grayscale mask + rgba_mask_img = Image.new("RGBA", img.size, (255, 255, 255, 255)) + rgba_mask_img.putalpha(mask_img) # Use the mask image as the alpha channel + + # Composite the RGBA mask onto the base image + composited_img = Image.alpha_composite(img, rgba_mask_img) + pil_images.append(composited_img) # Add the composited image back + + elif images is not None and masks is None: + for image in images: + i = 255. * image.cpu().numpy() + img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8)) + pil_images.append(img) + + elif masks is not None and images is None: + for mask in masks: + mask_np = 255. * mask.cpu().numpy() + mask_img = Image.fromarray(np.clip(mask_np, 0, 255).astype(np.uint8)) + pil_images.append(mask_img) + else: + logging.warning("PreviewAnimation: No images or masks provided") + return { "ui": { "images": results, "animated": (None,), "text": "empty" }} + + num_frames = len(pil_images) + + c = len(pil_images) + for i in range(0, c, num_frames): + file = f"{filename}_{counter:05}_.webp" + pil_images[i].save(os.path.join(full_output_folder, file), save_all=True, duration=int(1000.0/fps), append_images=pil_images[i + 1:i + num_frames], lossless=False, quality=50, method=0) + results.append({ + "filename": file, + "subfolder": subfolder, + "type": self.type + }) + counter += 1 + + animated = num_frames != 1 + return { "ui": { "images": results, "animated": (animated,), "text": [f"{num_frames}x{pil_images[0].size[0]}x{pil_images[0].size[1]}"] } } + +class ImageResizeKJ: + upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"] + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "image": ("IMAGE",), + "width": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1, }), + "height": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1, }), + "upscale_method": (s.upscale_methods,), + "keep_proportion": ("BOOLEAN", { "default": False }), + "divisible_by": ("INT", { "default": 2, "min": 0, "max": 512, "step": 1, }), + }, + "optional" : { + #"width_input": ("INT", { "forceInput": True}), + #"height_input": ("INT", { "forceInput": True}), + "get_image_size": ("IMAGE",), + "crop": (["disabled","center", 0], { "tooltip": "0 will do the default center crop, this is a workaround for the widget order changing with the new frontend, as in old workflows the value of this widget becomes 0 automatically" }), + } + } + + RETURN_TYPES = ("IMAGE", "INT", "INT",) + RETURN_NAMES = ("IMAGE", "width", "height",) + FUNCTION = "resize" + CATEGORY = "KJNodes/image" + DEPRECATED = True + DESCRIPTION = """ +DEPRECATED! + +Due to ComfyUI frontend changes, this node should no longer be used, please check the +v2 of the node. This node is only kept to not completely break older workflows. + +""" + + def resize(self, image, width, height, keep_proportion, upscale_method, divisible_by, + width_input=None, height_input=None, get_image_size=None, crop="disabled"): + B, H, W, C = image.shape + + if width_input: + width = width_input + if height_input: + height = height_input + if get_image_size is not None: + _, height, width, _ = get_image_size.shape + + if keep_proportion and get_image_size is None: + # If one of the dimensions is zero, calculate it to maintain the aspect ratio + if width == 0 and height != 0: + ratio = height / H + width = round(W * ratio) + elif height == 0 and width != 0: + ratio = width / W + height = round(H * ratio) + elif width != 0 and height != 0: + # Scale based on which dimension is smaller in proportion to the desired dimensions + ratio = min(width / W, height / H) + width = round(W * ratio) + height = round(H * ratio) + else: + if width == 0: + width = W + if height == 0: + height = H + + if divisible_by > 1 and get_image_size is None: + width = width - (width % divisible_by) + height = height - (height % divisible_by) + + if crop == 0: #workaround for old workflows + crop = "center" + + image = image.movedim(-1,1) + image = common_upscale(image, width, height, upscale_method, crop) + image = image.movedim(1,-1) + + return(image, image.shape[2], image.shape[1],) + +class ImageResizeKJv2: + upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos", "nvidia_rtx_vsr"] + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "image": ("IMAGE",), + "width": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1, }), + "height": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1, }), + "upscale_method": (s.upscale_methods,), + "keep_proportion": (["stretch", "resize", "pad", "pad_edge", "pad_edge_pixel", "crop", "pillarbox_blur", "total_pixels"], { "default": False }), + "pad_color": ("STRING", { "default": "0, 0, 0", "tooltip": "Color to use for padding."}), + "crop_position": (["center", "top", "bottom", "left", "right"], { "default": "center" }), + "divisible_by": ("INT", { "default": 2, "min": 0, "max": 512, "step": 1, }), + }, + "optional" : { + "mask": ("MASK",), + "device": (["cpu", "gpu"],), + #"per_batch": ("INT", { "default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1, "tooltip": "Process images in sub-batches to reduce memory usage. 0 disables sub-batching."}), + }, + "hidden": { + "unique_id": "UNIQUE_ID", + }, + } + + RETURN_TYPES = ("IMAGE", "INT", "INT", "MASK",) + RETURN_NAMES = ("IMAGE", "width", "height", "mask",) + FUNCTION = "resize" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ +Resizes the image to the specified width and height. +Size can be retrieved from the input. + +Keep proportions keeps the aspect ratio of the image, by +highest dimension. +""" + + def resize(self, image, width, height, keep_proportion, upscale_method, divisible_by, pad_color, crop_position, unique_id, device="cpu", mask=None, per_batch=64): + B, H, W, C = image.shape + + # Treat ComfyUI's 64x64 placeholder mask as no mask + if mask is not None and mask.shape[-2:] == (64, 64) and (H != 64 or W != 64): + mask = None + + # Scale mask to match image dimensions if they differ + if mask is not None and mask.shape[-2:] != (H, W): + mask = common_upscale(mask.unsqueeze(1), W, H, "bilinear", crop="disabled").squeeze(1) + + if device == "gpu": + if upscale_method == "lanczos": + raise Exception("Lanczos is not supported on the GPU") + device = model_management.get_torch_device() + else: + device = torch.device("cpu") + + pillarbox_blur = keep_proportion == "pillarbox_blur" + + # Initialize padding variables + pad_left = pad_right = pad_top = pad_bottom = 0 + + if keep_proportion in ["resize", "total_pixels"] or keep_proportion.startswith("pad") or pillarbox_blur: + if keep_proportion == "total_pixels": + total_pixels = width * height + aspect_ratio = W / H + new_height = int(math.sqrt(total_pixels / aspect_ratio)) + new_width = int(math.sqrt(total_pixels * aspect_ratio)) + + # If one of the dimensions is zero, calculate it to maintain the aspect ratio + elif width == 0 and height == 0: + new_width = W + new_height = H + elif width == 0 and height != 0: + ratio = height / H + new_width = round(W * ratio) + new_height = height + elif height == 0 and width != 0: + ratio = width / W + new_width = width + new_height = round(H * ratio) + elif width != 0 and height != 0: + ratio = min(width / W, height / H) + new_width = round(W * ratio) + new_height = round(H * ratio) + else: + new_width = width + new_height = height + + if keep_proportion.startswith("pad") or pillarbox_blur: + # Calculate padding based on position + if crop_position == "center": + pad_left = (width - new_width) // 2 + pad_right = width - new_width - pad_left + pad_top = (height - new_height) // 2 + pad_bottom = height - new_height - pad_top + elif crop_position == "top": + pad_left = (width - new_width) // 2 + pad_right = width - new_width - pad_left + pad_top = 0 + pad_bottom = height - new_height + elif crop_position == "bottom": + pad_left = (width - new_width) // 2 + pad_right = width - new_width - pad_left + pad_top = height - new_height + pad_bottom = 0 + elif crop_position == "left": + pad_left = 0 + pad_right = width - new_width + pad_top = (height - new_height) // 2 + pad_bottom = height - new_height - pad_top + elif crop_position == "right": + pad_left = width - new_width + pad_right = 0 + pad_top = (height - new_height) // 2 + pad_bottom = height - new_height - pad_top + + width = new_width + height = new_height + else: + if width == 0: + width = W + if height == 0: + height = H + + if divisible_by > 1: + width = width - (width % divisible_by) + height = height - (height % divisible_by) + + # Preflight estimate (log-only when batching is active) + if per_batch != 0 and B > per_batch: + try: + bytes_per_elem = image.element_size() # typically 4 for float32 + est_total_bytes = B * height * width * C * bytes_per_elem + est_mb = est_total_bytes / (1024 * 1024) + msg = f"Resize v2estimated output ~{est_mb:.2f} MB; batching {per_batch}/{B}" + if unique_id and PromptServer is not None: + try: + PromptServer.instance.send_progress_text(msg, unique_id) + except: + pass + else: + logging.info(f"[ImageResizeKJv2] estimated output ~{est_mb:.2f} MB; batching {per_batch}/{B}") + except: + pass + + # NVIDIA RTX Video Super Resolution setup + nvvfx_sr = None + nvvfx_ctx = None + if upscale_method == "nvidia_rtx_vsr": + try: + import nvvfx + except: + raise ImportError("NVIDIA RTX Video Super Resolution is not available. Please install the nvidia-vfx library and ensure you have a compatible NVIDIA GPU.") + nvvfx_ctx = nvvfx.VideoSuperRes(nvvfx.effects.QualityLevel.ULTRA) + nvvfx_sr = nvvfx_ctx.__enter__() + nvvfx_sr.output_width = max(8, round(width / 8) * 8) + nvvfx_sr.output_height = max(8, round(height / 8) * 8) + nvvfx_sr.load() + + def _process_subbatch(in_image, in_mask, pad_left, pad_right, pad_top, pad_bottom): + # Avoid unnecessary clones; only move if needed + out_image = in_image if in_image.device == device else in_image.to(device) + out_mask = None if in_mask is None else (in_mask if in_mask.device == device else in_mask.to(device)) + + # Crop logic + if keep_proportion == "crop": + old_height = out_image.shape[-3] + old_width = out_image.shape[-2] + old_aspect = old_width / old_height + new_aspect = width / height + if old_aspect > new_aspect: + crop_w = round(old_height * new_aspect) + crop_h = old_height + else: + crop_w = old_width + crop_h = round(old_width / new_aspect) + if crop_position == "center": + x = (old_width - crop_w) // 2 + y = (old_height - crop_h) // 2 + elif crop_position == "top": + x = (old_width - crop_w) // 2 + y = 0 + elif crop_position == "bottom": + x = (old_width - crop_w) // 2 + y = old_height - crop_h + elif crop_position == "left": + x = 0 + y = (old_height - crop_h) // 2 + elif crop_position == "right": + x = old_width - crop_w + y = (old_height - crop_h) // 2 + out_image = out_image.narrow(-2, x, crop_w).narrow(-3, y, crop_h) + if out_mask is not None: + out_mask = out_mask.narrow(-1, x, crop_w).narrow(-2, y, crop_h) + + if upscale_method == "nvidia_rtx_vsr": + # Process each frame through RTX Video Super Resolution + frames_chw = out_image.movedim(-1, 1).cuda().contiguous() + upscaled_frames = [] + for j in range(frames_chw.shape[0]): + dlpack_out = nvvfx_sr.run(frames_chw[j]).image + upscaled_frames.append(torch.from_dlpack(dlpack_out).clone()) + out_image = torch.stack(upscaled_frames, dim=0).movedim(1, -1).cpu() + if out_mask is not None: + out_mask = common_upscale(out_mask.unsqueeze(1), width, height, "bilinear", crop="disabled").squeeze(1) + else: + out_image = common_upscale(out_image.movedim(-1,1), width, height, upscale_method, crop="disabled").movedim(1,-1) + if out_mask is not None: + if upscale_method == "lanczos": + out_mask = common_upscale(out_mask.unsqueeze(1).repeat(1, 3, 1, 1), width, height, upscale_method, crop="disabled").movedim(1,-1)[:, :, :, 0] + else: + out_mask = common_upscale(out_mask.unsqueeze(1), width, height, upscale_method, crop="disabled").squeeze(1) + + # Pad logic + if (keep_proportion.startswith("pad") or pillarbox_blur) and (pad_left > 0 or pad_right > 0 or pad_top > 0 or pad_bottom > 0): + padded_width = width + pad_left + pad_right + padded_height = height + pad_top + pad_bottom + if divisible_by > 1: + width_remainder = padded_width % divisible_by + height_remainder = padded_height % divisible_by + if width_remainder > 0: + extra_width = divisible_by - width_remainder + pad_right += extra_width + if height_remainder > 0: + extra_height = divisible_by - height_remainder + pad_bottom += extra_height + + pad_mode = ( + "pillarbox_blur" if pillarbox_blur else + "edge" if keep_proportion == "pad_edge" else + "edge_pixel" if keep_proportion == "pad_edge_pixel" else + "color" + ) + out_image, out_mask = ImagePadKJ.pad(self, out_image, pad_left, pad_right, pad_top, pad_bottom, 0, pad_color, pad_mode, mask=out_mask) + + return out_image, out_mask + + # If batching disabled (per_batch==0) or batch fits, process whole batch + if per_batch == 0 or B <= per_batch: + out_image, out_mask = _process_subbatch(image, mask, pad_left, pad_right, pad_top, pad_bottom) + else: + chunks = [] + mask_chunks = [] if mask is not None else None + total_batches = (B + per_batch - 1) // per_batch + current_batch = 0 + for start_idx in range(0, B, per_batch): + current_batch += 1 + end_idx = min(start_idx + per_batch, B) + sub_img = image[start_idx:end_idx] + sub_mask = mask[start_idx:end_idx] if mask is not None else None + sub_out_img, sub_out_mask = _process_subbatch(sub_img, sub_mask, pad_left, pad_right, pad_top, pad_bottom) + chunks.append(sub_out_img.cpu()) + if mask is not None: + mask_chunks.append(sub_out_mask.cpu() if sub_out_mask is not None else None) + # Per-batch progress update + if unique_id and PromptServer is not None: + try: + PromptServer.instance.send_progress_text( + f"Resize v2batch {current_batch}/{total_batches} · images {end_idx}/{B}", + unique_id + ) + except: + pass + else: + try: + logging.info(f"[ImageResizeKJv2] batch {current_batch}/{total_batches} · images {end_idx}/{B}") + except: + pass + out_image = torch.cat(chunks, dim=0) + if mask is not None and any(m is not None for m in mask_chunks): + out_mask = torch.cat([m for m in mask_chunks if m is not None], dim=0) + else: + out_mask = None + + # Cleanup NVIDIA RTX VSR context + if nvvfx_ctx is not None: + nvvfx_ctx.__exit__(None, None, None) + + # Progress UI + if unique_id and PromptServer is not None: + try: + num_elements = out_image.numel() + element_size = out_image.element_size() + memory_size_mb = (num_elements * element_size) / (1024 * 1024) + PromptServer.instance.send_progress_text( + f"Output: {out_image.shape[0]} x {out_image.shape[2]} x {out_image.shape[1]} | {memory_size_mb:.2f}MB", + unique_id + ) + except: + pass + + return (out_image.cpu(), out_image.shape[2], out_image.shape[1], out_mask.cpu() if out_mask is not None else torch.zeros(64,64, device=torch.device("cpu"), dtype=torch.float32)) + +class LoadAndResizeImage: + _color_channels = ["alpha", "red", "green", "blue"] + @classmethod + def INPUT_TYPES(s): + input_dir = folder_paths.get_input_directory() + files = [f.name for f in pathlib.Path(input_dir).iterdir() if f.is_file()] + return {"required": + { + "image": (sorted(files), {"image_upload": True}), + "resize": ("BOOLEAN", { "default": False }), + "width": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8, }), + "height": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8, }), + "repeat": ("INT", { "default": 1, "min": 1, "max": 4096, "step": 1, }), + "keep_proportion": ("BOOLEAN", { "default": False }), + "divisible_by": ("INT", { "default": 2, "min": 0, "max": 512, "step": 1, }), + "mask_channel": (s._color_channels, {"tooltip": "Channel to use for the mask output"}), + "background_color": ("STRING", { "default": "", "tooltip": "Fills the alpha channel with the specified color."}), + }, + } + + CATEGORY = "KJNodes/image" + RETURN_TYPES = ("IMAGE", "MASK", "INT", "INT", "STRING",) + RETURN_NAMES = ("image", "mask", "width", "height","image_path",) + FUNCTION = "load_image" + + def load_image(self, image, resize, width, height, repeat, keep_proportion, divisible_by, mask_channel, background_color): + image_path = folder_paths.get_annotated_filepath(image) + + img = node_helpers.pillow(Image.open, image_path) + img = ImageOps.exif_transpose(img) + + # Process the background_color using the helper function + if background_color: + color_list = string_to_color(background_color) + # Ensure we have RGBA (add alpha if only RGB) + if len(color_list) == 3: + bg_color_rgba = tuple(color_list) + (255,) + else: + bg_color_rgba = tuple(color_list) + else: + bg_color_rgba = None # No background color specified + + output_images = [] + output_masks = [] + w, h = None, None + + excluded_formats = ['MPO'] + + W, H = img.size + if resize: + if keep_proportion: + ratio = min(width / W, height / H) + width = round(W * ratio) + height = round(H * ratio) + else: + if width == 0: + width = W + if height == 0: + height = H + + if divisible_by > 1: + width = width - (width % divisible_by) + height = height - (height % divisible_by) + else: + width, height = W, H + + for frame in ImageSequence.Iterator(img): + frame = node_helpers.pillow(ImageOps.exif_transpose, frame) + + if frame.mode == 'I': + frame = frame.point(lambda i: i * (1 / 255)) + + if frame.mode == 'P': + frame = frame.convert("RGBA") + elif 'A' in frame.getbands(): + frame = frame.convert("RGBA") + + # Extract alpha channel if it exists + if 'A' in frame.getbands() and bg_color_rgba: + alpha_mask = np.array(frame.getchannel('A')).astype(np.float32) / 255.0 + alpha_mask = 1. - torch.from_numpy(alpha_mask) + bg_image = Image.new("RGBA", frame.size, bg_color_rgba) + # Composite the frame onto the background + frame = Image.alpha_composite(bg_image, frame) + else: + alpha_mask = torch.zeros((64, 64), dtype=torch.float32, device="cpu") + + image = frame.convert("RGB") + + if len(output_images) == 0: + w = image.size[0] + h = image.size[1] + + if image.size[0] != w or image.size[1] != h: + continue + if resize: + image = image.resize((width, height), Image.Resampling.BILINEAR) + + image = np.array(image).astype(np.float32) / 255.0 + image = torch.from_numpy(image)[None,] + + c = mask_channel[0].upper() + if c in frame.getbands(): + if resize: + frame = frame.resize((width, height), Image.Resampling.BILINEAR) + mask = np.array(frame.getchannel(c)).astype(np.float32) / 255.0 + mask = torch.from_numpy(mask) + if c == 'A' and bg_color_rgba: + mask = alpha_mask + elif c == 'A': + mask = 1. - mask + else: + mask = torch.zeros((64, 64), dtype=torch.float32, device="cpu") + + output_images.append(image) + output_masks.append(mask.unsqueeze(0)) + + if len(output_images) > 1 and img.format not in excluded_formats: + output_image = torch.cat(output_images, dim=0) + output_mask = torch.cat(output_masks, dim=0) + else: + output_image = output_images[0] + output_mask = output_masks[0] + if repeat > 1: + output_image = output_image.repeat(repeat, 1, 1, 1) + output_mask = output_mask.repeat(repeat, 1, 1) + + return (output_image, output_mask, width, height, image_path) + + + # @classmethod + # def IS_CHANGED(s, image, **kwargs): + # 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() + + @classmethod + def VALIDATE_INPUTS(s, image): + if not folder_paths.exists_annotated_filepath(image): + return "Invalid image file: {}".format(image) + + return True + +class LoadImagesFromFolderKJ: + # Dictionary to store folder hashes + folder_hashes = {} + + @classmethod + def IS_CHANGED(cls, folder, **kwargs): + if folder and not os.path.isabs(folder) and args.base_directory: + folder = os.path.join(args.base_directory, folder) + if not folder or not os.path.isdir(folder): + return float("NaN") + + valid_extensions = ['.jpg', '.jpeg', '.png', '.webp', '.tga'] + include_subfolders = kwargs.get('include_subfolders', False) + + file_data = [] + if include_subfolders: + for root, _, files in os.walk(folder): + for file in files: + if any(file.lower().endswith(ext) for ext in valid_extensions): + path = os.path.join(root, file) + try: + mtime = os.path.getmtime(path) + file_data.append((path, mtime)) + except OSError: + pass + else: + for file in sorted(os.listdir(folder)): + if any(file.lower().endswith(ext) for ext in valid_extensions): + path = os.path.join(folder, file) + try: + mtime = os.path.getmtime(path) + file_data.append((path, mtime)) + except OSError: + pass + + file_data.sort() + + combined_hash = hashlib.md5() + combined_hash.update(folder.encode('utf-8')) + combined_hash.update(str(len(file_data)).encode('utf-8')) + + for path, mtime in file_data: + combined_hash.update(f"{path}:{mtime}".encode('utf-8')) + + current_hash = combined_hash.hexdigest() + + old_hash = cls.folder_hashes.get(folder) + cls.folder_hashes[folder] = current_hash + + if old_hash == current_hash: + return old_hash + + return current_hash + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "folder": ("STRING", {"default": ""}), + "width": ("INT", {"default": 1024, "min": -1, "step": 1}), + "height": ("INT", {"default": 1024, "min": -1, "step": 1}), + "keep_aspect_ratio": (["crop", "pad", "stretch",],), + }, + "optional": { + "image_load_cap": ("INT", {"default": 0, "min": 0, "step": 1}), + "start_index": ("INT", {"default": 0, "min": 0, "step": 1}), + "include_subfolders": ("BOOLEAN", {"default": False}), + } + } + + RETURN_TYPES = ("IMAGE", "MASK", "INT", "STRING",) + RETURN_NAMES = ("image", "mask", "count", "image_path",) + FUNCTION = "load_images" + CATEGORY = "KJNodes/image" + DESCRIPTION = """Loads images from a folder into a batch, images are resized and loaded into a batch.""" + + def load_images(self, folder, width, height, image_load_cap, start_index, keep_aspect_ratio, include_subfolders=False): + if folder and not os.path.isabs(folder) and args.base_directory: + folder = os.path.join(args.base_directory, folder) + if not folder or not os.path.isdir(folder): + raise FileNotFoundError(f"Folder '{folder}' cannot be found.") + + valid_extensions = ['.jpg', '.jpeg', '.png', '.webp', '.tga'] + image_paths = [] + if include_subfolders: + for root, _, files in os.walk(folder): + for file in files: + if any(file.lower().endswith(ext) for ext in valid_extensions): + image_paths.append(os.path.join(root, file)) + else: + for file in sorted(os.listdir(folder)): + if any(file.lower().endswith(ext) for ext in valid_extensions): + image_paths.append(os.path.join(folder, file)) + + dir_files = sorted(image_paths) + + if len(dir_files) == 0: + raise FileNotFoundError(f"No files in directory '{folder}'.") + + # start at start_index + dir_files = dir_files[start_index:] + + images = [] + masks = [] + image_path_list = [] + + limit_images = False + if image_load_cap > 0: + limit_images = True + image_count = 0 + + pbar = ProgressBar(len(dir_files)) + + for image_path in dir_files: + if os.path.isdir(image_path): + continue + if limit_images and image_count >= image_load_cap: + break + i = Image.open(image_path) + i = ImageOps.exif_transpose(i) + + # Resize image to maximum dimensions + if width == -1 and height == -1: + width = i.size[0] + height = i.size[1] + if i.size != (width, height): + i = self.resize_with_aspect_ratio(i, width, height, keep_aspect_ratio) + + + image = i.convert("RGB") + image = np.array(image).astype(np.float32) / 255.0 + image = torch.from_numpy(image)[None,] + + if 'A' in i.getbands(): + mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0 + mask = 1. - torch.from_numpy(mask) + if mask.shape != (height, width): + mask = torch.nn.functional.interpolate(mask.unsqueeze(0).unsqueeze(0), + size=(height, width), + mode='bilinear', + align_corners=False).squeeze() + else: + mask = torch.zeros((height, width), dtype=torch.float32, device="cpu") + + images.append(image) + masks.append(mask) + image_path_list.append(image_path) + image_count += 1 + pbar.update(1) + + if len(images) == 1: + return (images[0], masks[0], 1, image_path_list) + + elif len(images) > 1: + image1 = images[0] + mask1 = masks[0].unsqueeze(0) + + for image2 in images[1:]: + image1 = torch.cat((image1, image2), dim=0) + + for mask2 in masks[1:]: + mask1 = torch.cat((mask1, mask2.unsqueeze(0)), dim=0) + + return (image1, mask1, len(images), image_path_list) + def resize_with_aspect_ratio(self, img, width, height, mode): + if mode == "stretch": + return img.resize((width, height), Image.Resampling.LANCZOS) + + img_width, img_height = img.size + aspect_ratio = img_width / img_height + target_ratio = width / height + + if mode == "crop": + # Calculate dimensions for center crop + if aspect_ratio > target_ratio: + # Image is wider - crop width + new_width = int(height * aspect_ratio) + img = img.resize((new_width, height), Image.Resampling.LANCZOS) + left = (new_width - width) // 2 + return img.crop((left, 0, left + width, height)) + else: + # Image is taller - crop height + new_height = int(width / aspect_ratio) + img = img.resize((width, new_height), Image.Resampling.LANCZOS) + top = (new_height - height) // 2 + return img.crop((0, top, width, top + height)) + + elif mode == "pad": + pad_color = self.get_edge_color(img) + # Calculate dimensions for padding + if aspect_ratio > target_ratio: + # Image is wider - pad height + new_height = int(width / aspect_ratio) + img = img.resize((width, new_height), Image.Resampling.LANCZOS) + padding = (height - new_height) // 2 + padded = Image.new('RGBA', (width, height), pad_color) + padded.paste(img, (0, padding)) + return padded + else: + # Image is taller - pad width + new_width = int(height * aspect_ratio) + img = img.resize((new_width, height), Image.Resampling.LANCZOS) + padding = (width - new_width) // 2 + padded = Image.new('RGBA', (width, height), pad_color) + padded.paste(img, (padding, 0)) + return padded + def get_edge_color(self, img): + """Sample edges and return dominant color""" + width, height = img.size + img = img.convert('RGBA') + + # Create 1-pixel high/wide images from edges + top = img.crop((0, 0, width, 1)) + bottom = img.crop((0, height-1, width, height)) + left = img.crop((0, 0, 1, height)) + right = img.crop((width-1, 0, width, height)) + + # Combine edges into single image + edges = Image.new('RGBA', (width*2 + height*2, 1)) + edges.paste(top, (0, 0)) + edges.paste(bottom, (width, 0)) + edges.paste(left.resize((height, 1)), (width*2, 0)) + edges.paste(right.resize((height, 1)), (width*2 + height, 0)) + + # Get median color + stat = ImageStat.Stat(edges) + median = tuple(map(int, stat.median)) + return median + +class ImageGridtoBatch: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "image": ("IMAGE", ), + "columns": ("INT", {"default": 3, "min": 1, "max": 8, "tooltip": "The number of columns in the grid."}), + "rows": ("INT", {"default": 0, "min": 1, "max": 8, "tooltip": "The number of rows in the grid. Set to 0 for automatic calculation."}), + } + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "decompose" + CATEGORY = "KJNodes/image" + DESCRIPTION = "Converts a grid of images to a batch of images." + + def decompose(self, image, columns, rows): + B, H, W, C = image.shape + + # Calculate cell width, rounding down + cell_width = W // columns + + if rows == 0: + # If rows is 0, calculate number of full rows + cell_height = H // columns + rows = H // cell_height + else: + # If rows is specified, adjust cell_height + cell_height = H // rows + + # Crop the image to fit full cells + image = image[:, :rows*cell_height, :columns*cell_width, :] + + # Reshape and permute the image to get the grid + image = image.view(B, rows, cell_height, columns, cell_width, C) + image = image.permute(0, 1, 3, 2, 4, 5).contiguous() + image = image.view(B, rows * columns, cell_height, cell_width, C) + + # Reshape to the final batch tensor + img_tensor = image.view(-1, cell_height, cell_width, C) + + return (img_tensor,) + +class SaveImageKJ: + def __init__(self): + self.type = "output" + self.prefix_append = "" + self.compress_level = 4 + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "images": ("IMAGE", {"tooltip": "The images to save."}), + "filename_prefix": ("STRING", {"default": "ComfyUI", "tooltip": "The prefix for the file to save. This may include formatting information such as %date:yyyy-MM-dd% or %Empty Latent Image.width% to include values from nodes."}), + "output_folder": ("STRING", {"default": "output", "tooltip": "The folder to save the images to."}), + }, + "optional": { + "caption_file_extension": ("STRING", {"default": ".txt", "tooltip": "The extension for the caption file."}), + "caption": ("STRING", {"forceInput": True, "tooltip": "string to save as .txt file"}), + }, + "hidden": { + "prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO" + }, + } + + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("filename",) + FUNCTION = "save_images" + + OUTPUT_NODE = True + + CATEGORY = "KJNodes/image" + DESCRIPTION = "Saves the input images to your ComfyUI output directory." + + def save_images(self, images, output_folder, filename_prefix="ComfyUI", prompt=None, extra_pnginfo=None, caption=None, caption_file_extension=".txt"): + filename_prefix += self.prefix_append + + if os.path.isabs(output_folder): + if not os.path.exists(output_folder): + os.makedirs(output_folder, exist_ok=True) + full_output_folder = output_folder + _, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, output_folder, images[0].shape[1], images[0].shape[0]) + else: + self.output_dir = folder_paths.get_output_directory() + full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir, images[0].shape[1], images[0].shape[0]) + + results = list() + for (batch_number, image) in enumerate(images): + i = 255. * image.cpu().numpy() + img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8)) + metadata = None + if not args.disable_metadata: + metadata = PngInfo() + 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])) + + filename_with_batch_num = filename.replace("%batch_num%", str(batch_number)) + base_file_name = f"{filename_with_batch_num}_{counter:05}_" + file = f"{base_file_name}.png" + img.save(os.path.join(full_output_folder, file), pnginfo=metadata, compress_level=self.compress_level) + results.append({ + "filename": file, + "subfolder": subfolder, + "type": self.type + }) + if caption is not None: + txt_file = base_file_name + caption_file_extension + file_path = os.path.join(full_output_folder, txt_file) + with open(file_path, "w", encoding="utf-8") as f: + f.write(caption) + + counter += 1 + + return file, + +class SaveStringKJ: + def __init__(self): + self.output_dir = folder_paths.get_output_directory() + self.type = "output" + self.prefix_append = "" + self.compress_level = 4 + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "string": ("STRING", {"forceInput": True, "tooltip": "string to save as .txt file"}), + "filename_prefix": ("STRING", {"default": "text", "tooltip": "The prefix for the file to save. This may include formatting information such as %date:yyyy-MM-dd% or %Empty Latent Image.width% to include values from nodes."}), + "output_folder": ("STRING", {"default": "output", "tooltip": "The folder to save the images to."}), + }, + "optional": { + "file_extension": ("STRING", {"default": ".txt", "tooltip": "The extension for the caption file."}), + }, + } + + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("filename",) + FUNCTION = "save_string" + + OUTPUT_NODE = True + + CATEGORY = "KJNodes/misc" + DESCRIPTION = "Saves the input string to your ComfyUI output directory." + + def save_string(self, string, output_folder, filename_prefix="text", file_extension=".txt"): + filename_prefix += self.prefix_append + + full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir) + if output_folder and not os.path.isabs(output_folder) and args.base_directory: + output_folder = os.path.join(args.base_directory, output_folder) + if output_folder != "output": + if not os.path.exists(output_folder): + os.makedirs(output_folder, exist_ok=True) + full_output_folder = output_folder + + base_file_name = f"{filename_prefix}_{counter:05}_" + results = list() + + txt_file = base_file_name + file_extension + file_path = os.path.join(full_output_folder, txt_file) + with open(file_path, 'w', encoding="utf-8") as f: + f.write(string) + + return results, + +class FastPreview: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "image": ("IMAGE", ), + "format": (["JPEG", "PNG"], {"default": "JPEG"}), + "max_size": ("INT", {"default": 768, "min": 128, "max": 4096, "step": 64, + "tooltip": "Maximum width or height for the preview. Images larger than this are downscaled before encoding."}), + }, + "hidden": { + "unique_id": "UNIQUE_ID", + "prompt_id": "PROMPT_ID", + }, + } + + RETURN_TYPES = () + FUNCTION = "preview" + CATEGORY = "KJNodes/experimental" + OUTPUT_NODE = True + DESCRIPTION = "Fast image preview using binary websocket, bypassing base64/JSON overhead." + + def preview(self, image, format, max_size, unique_id=None, prompt_id=None): + arr = image[0].cpu().mul(255).clamp(0, 255).byte().numpy() + h, w = arr.shape[:2] + + if HAS_CV2 and (w > max_size or h > max_size): + scale = max_size / max(w, h) + arr = cv2.resize(arr, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_LINEAR) + + pil_image = Image.fromarray(arr) + + if PromptServer is not None and unique_id is not None: + PromptServer.instance.send_sync( + BinaryEventTypes.PREVIEW_IMAGE_WITH_METADATA, + ( + (format, pil_image, None), + {"node_id": unique_id, "prompt_id": prompt_id or ""}, + ), + PromptServer.instance.client_id, + ) + + return {"ui": {"fast_preview": [True]}, "result": ()} + + +class ImageCropByMaskAndResize: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "image": ("IMAGE", ), + "mask": ("MASK", ), + "base_resolution": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8, }), + "padding": ("INT", { "default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1, }), + "min_crop_resolution": ("INT", { "default": 128, "min": 0, "max": MAX_RESOLUTION, "step": 8, }), + "max_crop_resolution": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8, }), + }, + } + + RETURN_TYPES = ("IMAGE", "MASK", "BBOX", ) + RETURN_NAMES = ("images", "masks", "bbox",) + FUNCTION = "crop" + CATEGORY = "KJNodes/image" + + def crop_by_mask(self, mask, padding=0, min_crop_resolution=None, max_crop_resolution=None): + """ + Calculate bounding box from mask with proper padding boundary protection + Ensures crop region never exceeds original image boundaries + """ + iy, ix = (mask == 1).nonzero(as_tuple=True) + h0, w0 = mask.shape + + # Handle empty mask + if iy.numel() == 0: + x_c = w0 / 2.0 + y_c = h0 / 2.0 + width = 0 + height = 0 + else: + x_min = ix.min().item() + x_max = ix.max().item() + y_min = iy.min().item() + y_max = iy.max().item() + width = x_max - x_min + 1 # Include boundary pixels + height = y_max - y_min + 1 + x_c = (x_min + x_max) / 2.0 + y_c = (y_min + y_max) / 2.0 + + # Apply min/max resolution constraints + if min_crop_resolution: + width = max(width, min_crop_resolution) + height = max(height, min_crop_resolution) + if max_crop_resolution: + width = min(width, max_crop_resolution) + height = min(height, max_crop_resolution) + + # Critical: Limit padding expansion to available image space + # Calculate maximum possible padding for each direction + max_padding_x = min((w0 - width) // 2, padding) + max_padding_y = min((h0 - height) // 2, padding) + + # Apply constrained padding + final_width = width + 2 * max_padding_x + final_height = height + 2 * max_padding_y + + # Ensure final dimensions don't exceed image bounds + final_width = min(final_width, w0) + final_height = min(final_height, h0) + + # Calculate top-left corner with boundary protection + # Center the crop while respecting image boundaries + x0 = max(0, min(int(x_c - final_width / 2), w0 - final_width)) + y0 = max(0, min(int(y_c - final_height / 2), h0 - final_height)) + + return (x0, y0, final_width, final_height) + + def crop(self, image, mask, base_resolution, padding=0, min_crop_resolution=128, max_crop_resolution=512): + """ + Main crop and resize function with uniform target dimensions for all batch items + """ + mask = mask.round() + image_list = [] + mask_list = [] + bbox_list = [] + + # Step 1: Calculate individual bounding boxes + bbox_params = [] + aspect_ratios = [] + for i in range(image.shape[0]): + x0, y0, w, h = self.crop_by_mask(mask[i], padding, min_crop_resolution, max_crop_resolution) + bbox_params.append((x0, y0, w, h)) + aspect_ratios.append(w / h) + + # Step 2: Calculate uniform target dimensions based on maximum aspect ratio + max_w = max([w for x0, y0, w, h in bbox_params]) + max_h = max([h for x0, y0, w, h in bbox_params]) + max_aspect_ratio = max(aspect_ratios) + + # Round up to nearest multiple of 16 for stable processing + max_w = (max_w + 15) // 16 * 16 + max_h = (max_h + 15) // 16 * 16 + + # Determine target dimensions maintaining aspect ratio + if max_aspect_ratio > 1: + target_width = base_resolution + target_height = int(base_resolution / max_aspect_ratio) + else: + target_height = base_resolution + target_width = int(base_resolution * max_aspect_ratio) + + # Ensure target dimensions are multiples of 16 + target_width = (target_width + 15) // 16 * 16 + target_height = (target_height + 15) // 16 * 16 + + # Step 3: Process each image with uniform crop size + for i in range(image.shape[0]): + orig_x0, orig_y0, orig_w, orig_h = bbox_params[i] + + # Calculate center of original bounding box + x_center = orig_x0 + orig_w / 2 + y_center = orig_y0 + orig_h / 2 + + # Define uniform crop region centered on each image's bounding box + # This ensures all crops have exactly the same dimensions + x0_new = max(0, min(int(x_center - max_w / 2), image.shape[2] - max_w)) + y0_new = max(0, min(int(y_center - max_h / 2), image.shape[1] - max_h)) + x1_new = x0_new + max_w + y1_new = y0_new + max_h + + # Extract cropped regions + cropped_image = image[i][y0_new:y1_new, x0_new:x1_new, :] + cropped_mask = mask[i][y0_new:y1_new, x0_new:x1_new] + + # Resize to exact target dimensions + # Image with lanczos interpolation + cropped_image = cropped_image.unsqueeze(0).movedim(-1, 1) + cropped_image = common_upscale(cropped_image, target_width, target_height, "lanczos", "disabled") + cropped_image = cropped_image.movedim(1, -1).squeeze(0) + + # Mask with bilinear interpolation + cropped_mask = cropped_mask.unsqueeze(0).unsqueeze(0) + cropped_mask = common_upscale(cropped_mask, target_width, target_height, 'bilinear', "disabled") + cropped_mask = cropped_mask.squeeze(0).squeeze(0) + + image_list.append(cropped_image) + mask_list.append(cropped_mask) + bbox_list.append((x0_new, y0_new, x1_new, y1_new)) + + return (torch.stack(image_list), torch.stack(mask_list), bbox_list) + +class ImageCropByMask: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "image": ("IMAGE", ), + "mask": ("MASK", ), + }, + } + + RETURN_TYPES = ("IMAGE", ) + RETURN_NAMES = ("image", ) + FUNCTION = "crop" + CATEGORY = "KJNodes/image" + DESCRIPTION = "Crops the input images based on the provided mask." + + def crop(self, image, mask): + B, H, W, C = image.shape + mask = mask.round() + + # Find bounding box for each batch + crops = [] + + for b in range(B): + # Get coordinates of non-zero elements + rows = torch.any(mask[min(b, mask.shape[0]-1)] > 0, dim=1) + cols = torch.any(mask[min(b, mask.shape[0]-1)] > 0, dim=0) + + # Find boundaries + y_min, y_max = torch.where(rows)[0][[0, -1]] + x_min, x_max = torch.where(cols)[0][[0, -1]] + + # Crop image and mask + crop = image[b:b+1, y_min:y_max+1, x_min:x_max+1, :] + crops.append(crop) + + # Stack results back together + cropped_images = torch.cat(crops, dim=0) + + return (cropped_images, ) + + + +class ImageUncropByMask: + + @classmethod + def INPUT_TYPES(s): + return {"required": + { + "destination": ("IMAGE",), + "source": ("IMAGE",), + "mask": ("MASK",), + "bbox": ("BBOX",), + }, + } + + CATEGORY = "KJNodes/image" + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("image",) + FUNCTION = "uncrop" + + def uncrop(self, destination, source, mask, bbox=None): + + output_list = [] + + B, H, W, C = destination.shape + + for i in range(source.shape[0]): + x0, y0, x1, y1 = bbox[i] + bbox_height = y1 - y0 + bbox_width = x1 - x0 + + # Resize source image to match the bounding box dimensions + #resized_source = F.interpolate(source[i].unsqueeze(0).movedim(-1, 1), size=(bbox_height, bbox_width), mode='bilinear', align_corners=False) + resized_source = common_upscale(source[i].unsqueeze(0).movedim(-1, 1), bbox_width, bbox_height, "lanczos", "disabled") + resized_source = resized_source.movedim(1, -1).squeeze(0) + + # Resize mask to match the bounding box dimensions + resized_mask = common_upscale(mask[i].unsqueeze(0).unsqueeze(0), bbox_width, bbox_height, "bilinear", "disabled") + resized_mask = resized_mask.squeeze(0).squeeze(0) + + # Calculate padding values + pad_left = x0 + pad_right = W - x1 + pad_top = y0 + pad_bottom = H - y1 + + # Pad the resized source image and mask to fit the destination dimensions + padded_source = F.pad(resized_source, pad=(0, 0, pad_left, pad_right, pad_top, pad_bottom), mode='constant', value=0) + padded_mask = F.pad(resized_mask, pad=(pad_left, pad_right, pad_top, pad_bottom), mode='constant', value=0) + + # Ensure the padded mask has the correct shape + padded_mask = padded_mask.unsqueeze(2).expand(-1, -1, destination[i].shape[2]) + # Ensure the padded source has the correct shape + padded_source = padded_source.unsqueeze(2).expand(-1, -1, -1, destination[i].shape[2]).squeeze(2) + + # Combine the destination and padded source images using the mask + result = destination[i] * (1.0 - padded_mask) + padded_source * padded_mask + + output_list.append(result) + + + return (torch.stack(output_list),) + +class ImageCropByMaskBatch: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "image": ("IMAGE", ), + "masks": ("MASK", ), + "width": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8, }), + "height": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8, }), + "padding": ("INT", {"default": 0, "min": 0, "max": 4096, "step": 1, }), + "preserve_size": ("BOOLEAN", {"default": False}), + "bg_color": ("STRING", {"default": "0, 0, 0", "tooltip": "Color as RGB values in range 0-255 or 0.0-1.0, or color name or hex code"}), + } + } + + RETURN_TYPES = ("IMAGE", "MASK", ) + RETURN_NAMES = ("images", "masks",) + FUNCTION = "crop" + CATEGORY = "KJNodes/image" + DESCRIPTION = "Crops the input images based on the provided masks." + + def crop(self, image, masks, width, height, bg_color, padding, preserve_size): + B, H, W, C = image.shape + BM, HM, WM = masks.shape + mask_count = BM + if HM != H or WM != W: + masks = F.interpolate(masks.unsqueeze(1), size=(H, W), mode='nearest-exact').squeeze(1) + output_images = [] + output_masks = [] + + # Parse background color using helper function + color_list = string_to_color(bg_color) + bg_color = [x / 255.0 for x in color_list] + + # For each mask + for i in range(mask_count): + curr_mask = masks[i] + + # Find bounds + y_indices, x_indices = torch.nonzero(curr_mask, as_tuple=True) + if len(y_indices) == 0 or len(x_indices) == 0: + continue + + # Get exact bounds with padding + min_y = max(0, y_indices.min().item() - padding) + max_y = min(H, y_indices.max().item() + 1 + padding) + min_x = max(0, x_indices.min().item() - padding) + max_x = min(W, x_indices.max().item() + 1 + padding) + + # Ensure mask has correct shape for multiplication + curr_mask = curr_mask.unsqueeze(-1).expand(-1, -1, C) + + # Crop image and mask together + cropped_img = image[0, min_y:max_y, min_x:max_x, :] + cropped_mask = curr_mask[min_y:max_y, min_x:max_x, :] + + crop_h, crop_w = cropped_img.shape[0:2] + new_w = crop_w + new_h = crop_h + + if not preserve_size or crop_w > width or crop_h > height: + scale = min(width/crop_w, height/crop_h) + new_w = int(crop_w * scale) + new_h = int(crop_h * scale) + + # Resize RGB + resized_img = common_upscale(cropped_img.permute(2,0,1).unsqueeze(0), new_w, new_h, "lanczos", "disabled").squeeze(0).permute(1,2,0) + resized_mask = torch.nn.functional.interpolate( + cropped_mask.permute(2,0,1).unsqueeze(0), + size=(new_h, new_w), + mode='nearest' + ).squeeze(0).permute(1,2,0) + else: + resized_img = cropped_img + resized_mask = cropped_mask + + # Create empty tensors + new_img = torch.zeros((height, width, 3), dtype=image.dtype) + new_mask = torch.zeros((height, width), dtype=image.dtype) + + # Pad both + pad_x = (width - new_w) // 2 + pad_y = (height - new_h) // 2 + new_img[pad_y:pad_y+new_h, pad_x:pad_x+new_w, :] = resized_img + if len(resized_mask.shape) == 3: + resized_mask = resized_mask[:,:,0] # Take first channel if 3D + new_mask[pad_y:pad_y+new_h, pad_x:pad_x+new_w] = resized_mask + + output_images.append(new_img) + output_masks.append(new_mask) + + if not output_images: + return (torch.zeros((0, height, width, 3), dtype=image.dtype),) + + out_rgb = torch.stack(output_images, dim=0) + out_masks = torch.stack(output_masks, dim=0) + + # Apply mask to RGB + mask_expanded = out_masks.unsqueeze(-1).expand(-1, -1, -1, 3) + background_color = torch.tensor(bg_color, dtype=torch.float32, device=image.device) + out_rgb = out_rgb * mask_expanded + background_color * (1 - mask_expanded) + + return (out_rgb, out_masks) + +class ImagePadKJ: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "image": ("IMAGE", ), + "left": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1, }), + "right": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1, }), + "top": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1, }), + "bottom": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1, }), + "extra_padding": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1, }), + "pad_mode": (["edge", "edge_pixel", "color", "pillarbox_blur"],), + "color": ("STRING", {"default": "0, 0, 0", "tooltip": "Color as RGB values in range 0-255 or 0.0-1.0, or color name or hex code"}), + }, + "optional": { + "mask": ("MASK", ), + "target_width": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1, "forceInput": True}), + "target_height": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1, "forceInput": True}), + } + } + + RETURN_TYPES = ("IMAGE", "MASK", ) + RETURN_NAMES = ("images", "masks",) + FUNCTION = "pad" + CATEGORY = "KJNodes/image" + DESCRIPTION = "Pad the input image and optionally mask with the specified padding." + + def pad(self, image, left, right, top, bottom, extra_padding, color, pad_mode, mask=None, target_width=None, target_height=None): + B, H, W, C = image.shape + # Resize masks to image dimensions if necessary + if mask is not None: + BM, HM, WM = mask.shape + if HM != H or WM != W: + mask = F.interpolate(mask.unsqueeze(1), size=(H, W), mode='nearest-exact').squeeze(1) + + # Parse background color using helper function + color_list = string_to_color(color) + bg_color = [x / 255.0 for x in color_list] + if len(bg_color) == 1: + bg_color = bg_color * 3 # Grayscale to RGB + bg_color = torch.tensor(bg_color, dtype=image.dtype, device=image.device) + + # Calculate padding sizes with extra padding + if target_width is not None and target_height is not None: + if extra_padding > 0: + image = common_upscale(image.movedim(-1, 1), W - extra_padding, H - extra_padding, "lanczos", "disabled").movedim(1, -1) + B, H, W, C = image.shape + + padded_width = target_width + padded_height = target_height + pad_left = (padded_width - W) // 2 + pad_right = padded_width - W - pad_left + pad_top = (padded_height - H) // 2 + pad_bottom = padded_height - H - pad_top + else: + pad_left = left + extra_padding + pad_right = right + extra_padding + pad_top = top + extra_padding + pad_bottom = bottom + extra_padding + + padded_width = W + pad_left + pad_right + padded_height = H + pad_top + pad_bottom + + # Pillarbox blur mode + if pad_mode == "pillarbox_blur": + def _gaussian_blur_nchw(img_nchw, sigma_px): + if sigma_px <= 0: + return img_nchw + radius = max(1, int(3.0 * float(sigma_px))) + k = 2 * radius + 1 + x = torch.arange(-radius, radius + 1, device=img_nchw.device, dtype=img_nchw.dtype) + k1 = torch.exp(-(x * x) / (2.0 * float(sigma_px) * float(sigma_px))) + k1 = k1 / k1.sum() + kx = k1.view(1, 1, 1, k) + ky = k1.view(1, 1, k, 1) + c = img_nchw.shape[1] + kx = kx.repeat(c, 1, 1, 1) + ky = ky.repeat(c, 1, 1, 1) + img_nchw = F.conv2d(img_nchw, kx, padding=(0, radius), groups=c) + img_nchw = F.conv2d(img_nchw, ky, padding=(radius, 0), groups=c) + return img_nchw + + out_image = torch.zeros((B, padded_height, padded_width, C), dtype=image.dtype, device=image.device) + for b in range(B): + scale_fill = max(padded_width / float(W), padded_height / float(H)) if (W > 0 and H > 0) else 1.0 + bg_w = max(1, int(round(W * scale_fill))) + bg_h = max(1, int(round(H * scale_fill))) + src_b = image[b].movedim(-1, 0).unsqueeze(0) + bg = common_upscale(src_b, bg_w, bg_h, "bilinear", crop="disabled") + y0 = max(0, (bg_h - padded_height) // 2) + x0 = max(0, (bg_w - padded_width) // 2) + y1 = min(bg_h, y0 + padded_height) + x1 = min(bg_w, x0 + padded_width) + bg = bg[:, :, y0:y1, x0:x1] + if bg.shape[2] != padded_height or bg.shape[3] != padded_width: + pad_h = padded_height - bg.shape[2] + pad_w = padded_width - bg.shape[3] + pad_top_fix = max(0, pad_h // 2) + pad_bottom_fix = max(0, pad_h - pad_top_fix) + pad_left_fix = max(0, pad_w // 2) + pad_right_fix = max(0, pad_w - pad_left_fix) + bg = F.pad(bg, (pad_left_fix, pad_right_fix, pad_top_fix, pad_bottom_fix), mode="replicate") + sigma = max(1.0, 0.006 * float(min(padded_height, padded_width))) + bg = _gaussian_blur_nchw(bg, sigma_px=sigma) + if C >= 3: + r, g, bch = bg[:, 0:1], bg[:, 1:2], bg[:, 2:3] + luma = 0.2126 * r + 0.7152 * g + 0.0722 * bch + gray = torch.cat([luma, luma, luma], dim=1) + desat = 0.20 + rgb = torch.cat([r, g, bch], dim=1) + rgb = rgb * (1.0 - desat) + gray * desat + bg[:, 0:3, :, :] = rgb + dim = 0.35 + bg = torch.clamp(bg * dim, 0.0, 1.0) + out_image[b] = bg.squeeze(0).movedim(0, -1) + out_image[:, pad_top:pad_top+H, pad_left:pad_left+W, :] = image + # Mask handling for pillarbox_blur + if mask is not None: + fg_mask = mask + out_masks = torch.ones((B, padded_height, padded_width), dtype=image.dtype, device=image.device) + out_masks[:, pad_top:pad_top+H, pad_left:pad_left+W] = fg_mask + else: + out_masks = torch.ones((B, padded_height, padded_width), dtype=image.dtype, device=image.device) + out_masks[:, pad_top:pad_top+H, pad_left:pad_left+W] = 0.0 + return (out_image, out_masks) + + # Standard pad logic (edge/color) + out_image = torch.zeros((B, padded_height, padded_width, C), dtype=image.dtype, device=image.device) + for b in range(B): + if pad_mode == "edge": + # Pad with edge color (mean) + top_edge = image[b, 0, :, :] + bottom_edge = image[b, H-1, :, :] + left_edge = image[b, :, 0, :] + right_edge = image[b, :, W-1, :] + out_image[b, :pad_top, :, :] = top_edge.mean(dim=0) + out_image[b, pad_top+H:, :, :] = bottom_edge.mean(dim=0) + out_image[b, :, :pad_left, :] = left_edge.mean(dim=0) + out_image[b, :, pad_left+W:, :] = right_edge.mean(dim=0) + out_image[b, pad_top:pad_top+H, pad_left:pad_left+W, :] = image[b] + elif pad_mode == "edge_pixel": + # Pad with exact edge pixel values + for y in range(pad_top): + out_image[b, y, pad_left:pad_left+W, :] = image[b, 0, :, :] + for y in range(pad_top+H, padded_height): + out_image[b, y, pad_left:pad_left+W, :] = image[b, H-1, :, :] + for x in range(pad_left): + out_image[b, pad_top:pad_top+H, x, :] = image[b, :, 0, :] + for x in range(pad_left+W, padded_width): + out_image[b, pad_top:pad_top+H, x, :] = image[b, :, W-1, :] + out_image[b, :pad_top, :pad_left, :] = image[b, 0, 0, :] + out_image[b, :pad_top, pad_left+W:, :] = image[b, 0, W-1, :] + out_image[b, pad_top+H:, :pad_left, :] = image[b, H-1, 0, :] + out_image[b, pad_top+H:, pad_left+W:, :] = image[b, H-1, W-1, :] + out_image[b, pad_top:pad_top+H, pad_left:pad_left+W, :] = image[b] + else: + # Pad with specified background color + out_image[b, :, :, :] = bg_color.unsqueeze(0).unsqueeze(0) + out_image[b, pad_top:pad_top+H, pad_left:pad_left+W, :] = image[b] + + if mask is not None: + out_masks = torch.nn.functional.pad( + mask, + (pad_left, pad_right, pad_top, pad_bottom), + mode='replicate' + ) + else: + out_masks = torch.ones((B, padded_height, padded_width), dtype=image.dtype, device=image.device) + for m in range(B): + out_masks[m, pad_top:pad_top+H, pad_left:pad_left+W] = 0.0 + + return (out_image, out_masks) + +# extends https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite +class LoadVideosFromFolder: + @classmethod + def __init__(cls): + try: + cls.vhs_nodes = importlib.import_module("ComfyUI-VideoHelperSuite.videohelpersuite") + except ImportError: + try: + cls.vhs_nodes = importlib.import_module("comfyui-videohelpersuite.videohelpersuite") + except ImportError: + # Fallback to sys.modules search for Windows compatibility + import sys + vhs_module = None + for module_name in sys.modules: + if 'videohelpersuite' in module_name and 'videohelpersuite' in sys.modules[module_name].__dict__: + vhs_module = sys.modules[module_name] + break + + if vhs_module is None: + # Try direct access to the videohelpersuite submodule + for module_name in sys.modules: + if module_name.endswith('videohelpersuite'): + vhs_module = sys.modules[module_name] + break + + if vhs_module is not None: + cls.vhs_nodes = vhs_module + else: + raise ImportError("This node requires ComfyUI-VideoHelperSuite to be installed.") + + except ImportError: + raise ImportError("This node requires ComfyUI-VideoHelperSuite to be installed.") + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "video": ("STRING", {"default": "X://insert/path/"},), + "force_rate": ("FLOAT", {"default": 0, "min": 0, "max": 60, "step": 1, "disable": 0}), + "custom_width": ("INT", {"default": 0, "min": 0, "max": 4096, 'disable': 0}), + "custom_height": ("INT", {"default": 0, "min": 0, "max": 4096, 'disable': 0}), + "frame_load_cap": ("INT", {"default": 0, "min": 0, "max": 10000, "step": 1, "disable": 0}), + "skip_first_frames": ("INT", {"default": 0, "min": 0, "max": 10000, "step": 1}), + "select_every_nth": ("INT", {"default": 1, "min": 1, "max": 1000, "step": 1}), + "output_type": (["batch", "grid"], {"default": "batch"}), + "grid_max_columns": ("INT", {"default": 4, "min": 1, "max": 16, "step": 1, "disable": 1}), + "add_label": ( "BOOLEAN", {"default": False} ), + }, + "hidden": { + "force_size": "STRING", + "unique_id": "UNIQUE_ID" + }, + } + + CATEGORY = "KJNodes/misc" + + RETURN_TYPES = ("IMAGE", ) + RETURN_NAMES = ("IMAGE", ) + + FUNCTION = "load_video" + + def load_video(self, output_type, grid_max_columns, add_label=False, **kwargs): + if kwargs.get('video') and not os.path.isabs(kwargs['video']) and args.base_directory: + kwargs['video'] = os.path.join(args.base_directory, kwargs['video']) + + if self.vhs_nodes is None: + raise ImportError("This node requires ComfyUI-VideoHelperSuite to be installed.") + videos_list = [] + filenames = [] + for f in sorted(os.listdir(kwargs['video'])): + if os.path.isfile(os.path.join(kwargs['video'], f)): + file_parts = f.split('.') + if len(file_parts) > 1 and (file_parts[-1].lower() in ['webm', 'mp4', 'mkv', 'gif', 'mov']): + videos_list.append(os.path.join(kwargs['video'], f)) + filenames.append(f) + + kwargs.pop('video') + loaded_videos = [] + for idx, video in enumerate(videos_list): + video_tensor = self.vhs_nodes.load_video_nodes.load_video(video=video, **kwargs)[0] + if add_label: + # Add filename label above video (without extension) + if video_tensor.dim() == 4: + _, h, w, c = video_tensor.shape + else: + h, w, c = video_tensor.shape + # Remove extension from filename + label_text = filenames[idx].rsplit('.', 1)[0] + font_size = max(16, w // 20) + try: + font = ImageFont.truetype("arial.ttf", font_size) + except: + font = ImageFont.load_default() + dummy_img = Image.new("RGB", (w, 10), (0,0,0)) + draw = ImageDraw.Draw(dummy_img) + text_bbox = draw.textbbox((0,0), label_text, font=font) + extra_padding = max(12, font_size // 2) # More padding under the font + label_height = text_bbox[3] - text_bbox[1] + extra_padding + label_img = Image.new("RGB", (w, label_height), (0,0,0)) + draw = ImageDraw.Draw(label_img) + draw.text((w//2 - (text_bbox[2]-text_bbox[0])//2, 4), label_text, font=font, fill=(255,255,255)) + label_np = np.asarray(label_img).astype(np.float32) / 255.0 + label_tensor = torch.from_numpy(label_np) + if c == 1: + label_tensor = label_tensor.mean(dim=2, keepdim=True) + elif c == 4: + alpha = torch.ones((label_height, w, 1), dtype=label_tensor.dtype) + label_tensor = torch.cat([label_tensor, alpha], dim=2) + if video_tensor.dim() == 4: + label_tensor = label_tensor.unsqueeze(0).expand(video_tensor.shape[0], -1, -1, -1) + video_tensor = torch.cat([label_tensor, video_tensor], dim=1) + else: + video_tensor = torch.cat([label_tensor, video_tensor], dim=0) + loaded_videos.append(video_tensor) + if output_type == "batch": + out_tensor = torch.cat(loaded_videos) + elif output_type == "grid": + rows = (len(loaded_videos) + grid_max_columns - 1) // grid_max_columns + # Pad the last row if needed + total_slots = rows * grid_max_columns + while len(loaded_videos) < total_slots: + loaded_videos.append(torch.zeros_like(loaded_videos[0])) + # Create grid by rows + row_tensors = [] + for row_idx in range(rows): + start_idx = row_idx * grid_max_columns + end_idx = start_idx + grid_max_columns + row_videos = loaded_videos[start_idx:end_idx] + # Pad all videos in this row to the same height + heights = [v.shape[1] for v in row_videos] + max_height = max(heights) + padded_row_videos = [] + for v in row_videos: + pad_height = max_height - v.shape[1] + if pad_height > 0: + # Pad (frames, H, W, C) or (H, W, C) + if v.dim() == 4: + pad = (0,0, 0,0, 0,pad_height, 0,0) # (C,W,H,F) + v = torch.nn.functional.pad(v, (0,0,0,0,0,pad_height,0,0)) + else: + v = torch.nn.functional.pad(v, (0,0,0,0,pad_height,0)) + padded_row_videos.append(v) + row_tensor = torch.cat(padded_row_videos, dim=2) # Concatenate horizontally + row_tensors.append(row_tensor) + out_tensor = torch.cat(row_tensors, dim=1) # Concatenate rows vertically + return out_tensor, + + @classmethod + def IS_CHANGED(s, video, **kwargs): + if s.vhs_nodes is not None: + return s.vhs_nodes.utils.hash_path(video) + return None + + +class EncodeVideoComponents(io.ComfyNode): + @classmethod + def define_schema(cls): + position_options = ["center", "top", "bottom", "left", "right"] + options = [ + io.DynamicCombo.Option(key="stretch", inputs=[]), + io.DynamicCombo.Option(key="resize", inputs=[]), + io.DynamicCombo.Option(key="total_pixels", inputs=[]), + io.DynamicCombo.Option(key="crop", inputs=[ + io.Combo.Input("crop_position", options=position_options, tooltip="Position to crop from."), + ]), + io.DynamicCombo.Option(key="pad", inputs=[ + io.String.Input("pad_color", default="0, 0, 0", tooltip="Color to use for padding."), + io.Combo.Input("pad_position", options=position_options, tooltip="Position to align the image within the padded area."), + ]), + io.DynamicCombo.Option(key="pad_edge", inputs=[ + io.Combo.Input("pad_position", options=position_options, tooltip="Position to align the image within the padded area."), + ]), + io.DynamicCombo.Option(key="pad_edge_pixel", inputs=[ + io.Combo.Input("pad_position", options=position_options, tooltip="Position to align the image within the padded area."), + ]), + io.DynamicCombo.Option(key="pillarbox_blur", inputs=[ + io.Combo.Input("pad_position", options=position_options, tooltip="Position to align the image within the padded area."), + ]), + ] + return io.Schema( + node_id="EncodeVideoComponents", + search_aliases=["video to latent", "encode video", "vae encode video"], + display_name="Encode Video Components", + category="KJNodes/image", + description="Extracts video frames, resizes them, and encodes with a VAE directly, avoiding storing the full image tensor.", + inputs=[ + io.Video.Input("video", tooltip="The video to extract and encode."), + io.Vae.Input("vae", tooltip="The VAE model to use for encoding."), + io.Int.Input("width", default=768, min=0, max=16384, step=2, tooltip="Target width for the frames before encoding. 0 = original width."), + io.Int.Input("height", default=512, min=0, max=16384, step=2, tooltip="Target height for the frames before encoding. 0 = original height."), + io.Int.Input("max_frames", default=0, min=0, max=999999, step=1, tooltip="Maximum number of frames. 0 = no limit."), + io.Combo.Input("upscale_method", options=["nearest-exact", "bilinear", "area", "bicubic", "lanczos"], default="lanczos", tooltip="Interpolation method for resizing."), + io.DynamicCombo.Input( + "keep_proportion", + options=options, + display_name="Keep Proportion", + tooltip="How to handle aspect ratio mismatch when resizing.", + ), + ], + outputs=[ + io.Latent.Output(display_name="latent"), + io.Audio.Output(display_name="audio"), + io.Float.Output(display_name="fps"), + io.Int.Output(display_name="frame_count", tooltip="Number pixel space frames after any possible cropping"), + ], + ) + + @staticmethod + def _compute_resize_params(mode, position, width, height, src_w, src_h): + """Compute target resize dimensions, crop region, and padding from keep_proportion mode.""" + if width == 0: + width = src_w + if height == 0: + height = src_h + pillarbox_blur = mode == "pillarbox_blur" + pad_left = pad_right = pad_top = pad_bottom = 0 + crop_region = None # (x, y, crop_w, crop_h) or None + + if mode in ["resize", "total_pixels"] or mode.startswith("pad") or pillarbox_blur: + if mode == "total_pixels": + total_pixels = width * height + aspect_ratio = src_w / src_h + new_height = int(math.sqrt(total_pixels / aspect_ratio)) + new_width = int(math.sqrt(total_pixels * aspect_ratio)) + else: + ratio = min(width / src_w, height / src_h) + new_width = round(src_w * ratio) + new_height = round(src_h * ratio) + + if mode.startswith("pad") or pillarbox_blur: + if position == "center": + pad_left = (width - new_width) // 2 + pad_right = width - new_width - pad_left + pad_top = (height - new_height) // 2 + pad_bottom = height - new_height - pad_top + elif position == "top": + pad_left = (width - new_width) // 2 + pad_right = width - new_width - pad_left + pad_top = 0 + pad_bottom = height - new_height + elif position == "bottom": + pad_left = (width - new_width) // 2 + pad_right = width - new_width - pad_left + pad_top = height - new_height + pad_bottom = 0 + elif position == "left": + pad_left = 0 + pad_right = width - new_width + pad_top = (height - new_height) // 2 + pad_bottom = height - new_height - pad_top + elif position == "right": + pad_left = width - new_width + pad_right = 0 + pad_top = (height - new_height) // 2 + pad_bottom = height - new_height - pad_top + + width = new_width + height = new_height + + if mode == "crop": + old_aspect = src_w / src_h + new_aspect = width / height + if old_aspect > new_aspect: + crop_w = round(src_h * new_aspect) + crop_h = src_h + else: + crop_w = src_w + crop_h = round(src_w / new_aspect) + if position == "center": + x = (src_w - crop_w) // 2 + y = (src_h - crop_h) // 2 + elif position == "top": + x = (src_w - crop_w) // 2 + y = 0 + elif position == "bottom": + x = (src_w - crop_w) // 2 + y = src_h - crop_h + elif position == "left": + x = 0 + y = (src_h - crop_h) // 2 + elif position == "right": + x = src_w - crop_w + y = (src_h - crop_h) // 2 + crop_region = (x, y, crop_w, crop_h) + + return width, height, crop_region, (pad_left, pad_right, pad_top, pad_bottom) + + @classmethod + def execute(cls, video, vae, width, height, max_frames, upscale_method, keep_proportion) -> io.NodeOutput: + import av + import itertools + + mode = keep_proportion["keep_proportion"] + position = keep_proportion.get("crop_position") or keep_proportion.get("pad_position", "center") + pad_color = keep_proportion.get("pad_color", "0, 0, 0") + target_dtype = vae.vae_dtype + + # Access VideoFromFile internals for efficient per-frame decode + source = video.get_stream_source() + start_time = getattr(video, '_VideoFromFile__start_time', 0) + duration = getattr(video, '_VideoFromFile__duration', 0) + + # Get frame count for progress bar, capped by max_frames + try: + total_frames = video.get_frame_count() + except (ValueError, AttributeError): + total_frames = 0 + if max_frames > 0 and total_frames > 0: + total_frames = min(total_frames, max_frames) + pbar = ProgressBar(total_frames) if total_frames > 0 else None + + # Lanczos requires PIL (CPU-only), all other methods use torch on GPU + use_gpu = upscale_method != "lanczos" + device = model_management.get_torch_device() if use_gpu else torch.device("cpu") + + # --- Decode video frames with per-frame resize + dtype cast --- + with av.open(source, mode='r') as container: + video_stream = container.streams.video[0] + start_pts = int(start_time / video_stream.time_base) + end_pts = int((start_time + duration) / video_stream.time_base) if duration else 0 + container.seek(start_pts, stream=video_stream) + + res_w, res_h, crop_region, padding = None, None, None, (0, 0, 0, 0) + frames = [] + for frame in container.decode(video_stream): + if frame.pts < start_pts: + continue + if duration and frame.pts >= end_pts: + break + if max_frames > 0 and len(frames) >= max_frames: + break + + if res_w is None: + src_h, src_w = frame.height, frame.width + res_w, res_h, crop_region, padding = cls._compute_resize_params( + mode, position, width, height, src_w, src_h + ) + + # Decode to tensor and normalize + img = torch.from_numpy(frame.to_ndarray(format='rgb24')).to(device=device, dtype=torch.float32) / 255.0 + + # Crop if needed (before resize) + if crop_region is not None: + cx, cy, cw, ch = crop_region + img = img[cy:cy+ch, cx:cx+cw, :] + + # Resize (GPU for torch-native methods, CPU/PIL for lanczos) + img = common_upscale( + img.unsqueeze(0).movedim(-1, 1), res_w, res_h, upscale_method, crop="disabled" + ).movedim(1, -1).squeeze(0).to(dtype=target_dtype, device="cpu") + + frames.append(img) + if pbar is not None: + pbar.update(1) + + frame_rate = video_stream.average_rate if video_stream.average_rate else 1 + + s = torch.stack(frames) if frames else torch.zeros(0, height, width, 3, dtype=target_dtype) + + # Pad logic (applied on the full stack since padding modes like pillarbox_blur need all frames) + pillarbox_blur = mode == "pillarbox_blur" + pad_left, pad_right, pad_top, pad_bottom = padding + if (mode.startswith("pad") or pillarbox_blur) and (pad_left > 0 or pad_right > 0 or pad_top > 0 or pad_bottom > 0): + pad_mode = ( + "pillarbox_blur" if pillarbox_blur else + "edge" if mode == "pad_edge" else + "edge_pixel" if mode == "pad_edge_pixel" else + "color" + ) + s, _ = ImagePadKJ.pad(None, s, pad_left, pad_right, pad_top, pad_bottom, 0, pad_color, pad_mode) + + # Trim frames to a count valid for the VAE's temporal compression + try: + temporal_compress = vae.downscale_ratio[0] + temporal_decompress = vae.upscale_ratio[0] + valid_frames = temporal_decompress(temporal_compress(s.shape[0])) + if valid_frames < s.shape[0]: + logging.warning(f"[EncodeVideoComponents] Trimming {s.shape[0] - valid_frames} frames ({s.shape[0]} -> {valid_frames}) to match VAE temporal compression ratio") + s = s[:valid_frames] + except (TypeError, IndexError): + pass + + t = vae.encode(s) + + # --- Extract audio in a separate pass --- + audio = None + if isinstance(source, BytesIO): + source.seek(0) + with av.open(source, mode='r') as container: + if len(container.streams.audio): + audio_stream = container.streams.audio[-1] + if start_time > 0: + audio_start_pts = int(start_time / audio_stream.time_base) + container.seek(audio_start_pts, stream=audio_stream) + audio_frames = [] + resample = av.audio.resampler.AudioResampler(format='fltp').resample + aframes = itertools.chain.from_iterable( + map(resample, container.decode(audio_stream)) + ) + has_first_frame = False + for aframe in aframes: + offset_seconds = start_time - aframe.time + to_skip = int(offset_seconds * audio_stream.sample_rate) + if to_skip < aframe.samples: + has_first_frame = True + break + if has_first_frame: + audio_frames.append(aframe.to_ndarray()[..., to_skip:]) + for aframe in aframes: + if duration and aframe.time > start_time + duration: + break + audio_frames.append(aframe.to_ndarray()) + if audio_frames: + audio_data = np.concatenate(audio_frames, axis=1) + if duration: + audio_data = audio_data[..., :int(duration * audio_stream.sample_rate)] + audio = { + "waveform": torch.from_numpy(audio_data).unsqueeze(0), + "sample_rate": int(audio_stream.sample_rate) if audio_stream.sample_rate else 1, + } + + return io.NodeOutput({"samples": t}, audio, float(frame_rate), s.shape[0]) + + +class DecodeAndSaveVideo(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="DecodeAndSaveVideo", + search_aliases=["video to latent", "decode video"], + display_name="Decode and Save Video", + category="KJNodes/image", + description="Decodes video frames and audio from latent representations, combines them, and saves as a video file, without keeping intermediate images in memory.", + inputs=[ + io.Latent.Input("video_latent", tooltip="The latent representation of the video frames."), + io.Latent.Input("audio_latent", optional=True, tooltip="The latent representation of the audio frames."), + io.Float.Input("fps", default=25.0, min=0.0, max=999.0, step=0.01, tooltip="Frame rate for the output video."), + io.String.Input("filename_prefix", default="video/ComfyUI", tooltip="The prefix for the file to save. This may include formatting information such as %date:yyyy-MM-dd% or %Empty Latent Image.width% to include values from nodes."), + io.Combo.Input("format", options=Types.VideoContainer.as_input(), default="auto", tooltip="The format to save the video as."), + io.Combo.Input("codec", options=Types.VideoCodec.as_input(), default="auto", tooltip="The codec to use for the video."), + io.Vae.Input("video_vae", tooltip="The VAE model to use for encoding."), + io.Vae.Input("audio_vae", optional=True, tooltip="The VAE model to use for decoding audio."), + io.DynamicCombo.Input("tiling", options=[ + io.DynamicCombo.Option(key="disabled", inputs=[]), + io.DynamicCombo.Option(key="enabled", inputs=[ + io.Int.Input("tile_size", default=512, min=64, max=4096, step=32, tooltip="Size of the tiles to decode. Smaller tiles use less memory but take more time."), + io.Int.Input("overlap", default=64, min=0, max=4096, step=32, tooltip="Amount of overlap between tiles. Higher overlap can improve quality at the edges of tiles but uses more memory and takes more time."), + io.Int.Input("temporal_size", default=4096, min=8, max=4096, step=4, tooltip="Only used for video VAEs: Amount of frames to decode at a time. Higher value than number of frames = disabled"), + io.Int.Input("temporal_overlap", default=16, min=4, max=4096, step=4, tooltip="Only used for video VAEs: Amount of frames to overlap. Higher overlap can improve quality at the edges of temporal tiles but uses more memory and takes more time."), + ]), + ]), + ], + hidden=[io.Hidden.prompt, io.Hidden.extra_pnginfo], + is_output_node=True, + ) + + @classmethod + def execute(cls, video_latent, video_vae, filename_prefix, format, codec, tiling, audio_latent=None, audio_vae=None, fps=25.0) -> io.NodeOutput: + if tiling["tiling"] == "enabled": + tile_size = tiling["tile_size"] + overlap = tiling["overlap"] + temporal_size = tiling["temporal_size"] + temporal_overlap = tiling["temporal_overlap"] + + if tile_size < overlap * 4: + overlap = tile_size // 4 + if temporal_size < temporal_overlap * 2: + temporal_overlap = temporal_overlap // 2 + temporal_compression = video_vae.temporal_compression_decode() + if temporal_compression is not None: + temporal_size = max(2, temporal_size // temporal_compression) + temporal_overlap = max(1, min(temporal_size // 2, temporal_overlap // temporal_compression)) + else: + temporal_size = None + temporal_overlap = None + + compression = video_vae.spacial_compression_decode() + + images = cls.decode_tiled(video_vae, video_latent["samples"], + tile_t=max(2, temporal_size), + tile_x=tile_size // compression, + tile_y=tile_size // compression, + overlap=(temporal_overlap if temporal_overlap is not None else 1, max(1, overlap // compression), max(1, overlap // compression)), + ).movedim(1, -1) + if len(images.shape) == 5: #Combine batches + images = images.reshape(-1, images.shape[-3], images.shape[-2], images.shape[-1]) + else: + images = cls.decode_video(video_vae, video_latent) + + if audio_latent is not None: + if audio_vae is None: + raise ValueError("Audio VAE must be provided if audio latent is provided.") + audio = cls.decode_audio(audio_latent, audio_vae) + else: + audio = None + + video = InputImpl.VideoFromComponents(Types.VideoComponents(images=images, audio=audio, frame_rate=Fraction(fps))) + file, subfolder = cls.save_video(video, filename_prefix, format, codec) + + return io.NodeOutput(ui=ui.PreviewVideo([ui.SavedResult(file, subfolder, io.FolderType.output)])) + + @classmethod + def decode_video(cls, vae, samples): + samples_in = samples["samples"] + if samples_in.is_nested: + samples_in = samples_in.unbind()[0] + + vae.throw_exception_if_invalid() + pixel_samples = None + do_tile = False + if vae.latent_dim == 2 and samples_in.ndim == 5: + samples_in = samples_in[:, :, 0] + try: + memory_used = vae.memory_used_decode(samples_in.shape, vae.vae_dtype) + model_management.load_models_gpu([vae.patcher], memory_required=memory_used, force_full_load=True) + free_memory = vae.patcher.get_free_memory(vae.device) + batch_number = int(free_memory / memory_used) + batch_number = max(1, batch_number) + + for x in range(0, samples_in.shape[0], batch_number): + samples = samples_in[x:x+batch_number].to(vae.vae_dtype).to(vae.device) + out = vae.process_output(vae.first_stage_model.decode(samples).to(vae.output_device).to(torch.float16)) + if pixel_samples is None: + pixel_samples = torch.empty((samples_in.shape[0],) + tuple(out.shape[1:]), device=vae.output_device, dtype=out.dtype) + pixel_samples[x:x+batch_number] = out + except Exception as e: + model_management.raise_non_oom(e) + logging.warning("Warning: Ran out of memory when regular VAE decoding, retrying with tiled VAE decoding.") + do_tile = True + + if do_tile: + dims = samples_in.ndim - 2 + if dims == 1 or cls.extra_1d_channel is not None: + pixel_samples = vae.decode_tiled_1d(samples_in) + elif dims == 2: + pixel_samples = vae.decode_tiled_2d(samples_in) + elif dims == 3: + tile = 256 // vae.spacial_compression_decode() + overlap = tile // 4 + pixel_samples = vae.decode_tiled_3d(samples_in, tile_x=tile, tile_y=tile, overlap=(1, overlap, overlap)) + + pixel_samples = pixel_samples.to(vae.output_device).movedim(1,-1) + + if len(pixel_samples.shape) == 5: #Combine batches + pixel_samples = pixel_samples.reshape(-1, pixel_samples.shape[-3], pixel_samples.shape[-2], pixel_samples.shape[-1]) + return pixel_samples + + @classmethod + def decode_tiled(cls, vae, samples, tile_t=999, tile_x=32, tile_y=32, overlap=(1, 8, 8)): + vae.throw_exception_if_invalid() + memory_used = vae.memory_used_decode(samples.shape, vae.vae_dtype) + model_management.load_models_gpu([vae.patcher], memory_required=memory_used, force_full_load=vae.disable_offload) + decode_fn = lambda a: vae.first_stage_model.decode(a.to(vae.vae_dtype).to(vae.device)).to(torch.float16) + return vae.process_output(tiled_scale_multidim(samples, decode_fn, tile=(tile_t, tile_x, tile_y), overlap=overlap, + upscale_amount=vae.upscale_ratio, out_channels=vae.output_channels, index_formulas=vae.upscale_index_formula, output_device=vae.output_device)) + + + @classmethod + def decode_audio(cls, samples, audio_vae): + audio_latent = samples["samples"] + if audio_latent.is_nested: + audio_latent = audio_latent.unbind()[-1] + audio = audio_vae.decode(audio_latent).to(audio_latent.device) + output_audio_sample_rate = audio_vae.output_sample_rate + return {"waveform": audio, "sample_rate": int(output_audio_sample_rate)} + + @classmethod + def save_video(cls, video, filename_prefix, format, codec) -> io.NodeOutput: + width, height = video.get_dimensions() + full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path( + filename_prefix, + folder_paths.get_output_directory(), + width, + height + ) + saved_metadata = None + if not args.disable_metadata: + metadata = {} + if cls.hidden.extra_pnginfo is not None: + metadata.update(cls.hidden.extra_pnginfo) + if cls.hidden.prompt is not None: + metadata["prompt"] = cls.hidden.prompt + if len(metadata) > 0: + saved_metadata = metadata + file = f"{filename}_{counter:05}_.{Types.VideoContainer.get_extension(format)}" + video.save_to( + os.path.join(full_output_folder, file), + format=Types.VideoContainer(format), + codec=codec, + metadata=saved_metadata + ) + return file, subfolder + + +class PreviewImageOrMask(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="PreviewImageOrMask", + display_name="Preview Image Or Mask", + category="KJNodes/misc", + description="Previews the input images or masks.", + search_aliases=["output"], + inputs=[ + io.MultiType.Input("input", [io.Image, io.Mask], tooltip="The image or mask to preview."), + ], + hidden=[io.Hidden.prompt, io.Hidden.extra_pnginfo], + is_output_node=True, + ) + + @classmethod + def execute(cls, input) -> io.NodeOutput: + if input.ndim == 3: + return io.NodeOutput(ui=ui.PreviewMask(input, cls=cls)) + return io.NodeOutput(ui=ui.PreviewImage(input, cls=cls)) + diff --git a/.disabled/comfyui-kjnodes@nightly/nodes/intrinsic_lora_nodes.py b/.disabled/comfyui-kjnodes@nightly/nodes/intrinsic_lora_nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..a8a90143b284db5b5705d119c5bcc9b7b3820424 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/nodes/intrinsic_lora_nodes.py @@ -0,0 +1,115 @@ +import folder_paths +import os +import torch +import torch.nn.functional as F +from comfy.utils import ProgressBar, load_torch_file +import comfy.sample +from nodes import CLIPTextEncode + +script_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +folder_paths.add_model_folder_path("intrinsic_loras", os.path.join(script_directory, "intrinsic_loras")) + +class Intrinsic_lora_sampling: + def __init__(self): + self.loaded_lora = None + + @classmethod + def INPUT_TYPES(s): + return {"required": { "model": ("MODEL",), + "lora_name": (folder_paths.get_filename_list("intrinsic_loras"), ), + "task": ( + [ + 'depth map', + 'surface normals', + 'albedo', + 'shading', + ], + { + "default": 'depth map' + }), + "text": ("STRING", {"multiline": True, "default": ""}), + "clip": ("CLIP", ), + "vae": ("VAE", ), + "per_batch": ("INT", {"default": 16, "min": 1, "max": 4096, "step": 1}), + }, + "optional": { + "image": ("IMAGE",), + "optional_latent": ("LATENT",), + }, + } + + RETURN_TYPES = ("IMAGE", "LATENT",) + FUNCTION = "onestepsample" + CATEGORY = "KJNodes/misc" + DESCRIPTION = """ +Sampler to use the intrinsic loras: +https://github.com/duxiaodan/intrinsic-lora +These LoRAs are tiny and thus included +with this node pack. +""" + + def onestepsample(self, model, lora_name, clip, vae, text, task, per_batch, image=None, optional_latent=None): + pbar = ProgressBar(3) + + if optional_latent is None: + image_list = [] + for start_idx in range(0, image.shape[0], per_batch): + sub_pixels = vae.vae_encode_crop_pixels(image[start_idx:start_idx+per_batch]) + image_list.append(vae.encode(sub_pixels[:,:,:,:3])) + sample = torch.cat(image_list, dim=0) + else: + sample = optional_latent["samples"] + noise = torch.zeros(sample.size(), dtype=sample.dtype, layout=sample.layout, device="cpu") + prompt = task + "," + text + positive, = CLIPTextEncode.encode(self, clip, prompt) + negative = positive #negative shouldn't do anything in this scenario + + pbar.update(1) + + #custom model sampling to pass latent through as it is + class X0_PassThrough(comfy.model_sampling.EPS): + def calculate_denoised(self, sigma, model_output, model_input): + return model_output + def calculate_input(self, sigma, noise): + return noise + sampling_base = comfy.model_sampling.ModelSamplingDiscrete + sampling_type = X0_PassThrough + + class ModelSamplingAdvanced(sampling_base, sampling_type): + pass + model_sampling = ModelSamplingAdvanced(model.model.model_config) + + #load lora + model_clone = model.clone() + lora_path = folder_paths.get_full_path("intrinsic_loras", lora_name) + lora = load_torch_file(lora_path, safe_load=True) + self.loaded_lora = (lora_path, lora) + + model_clone_with_lora = comfy.sd.load_lora_for_models(model_clone, None, lora, 1.0, 0)[0] + + model_clone_with_lora.add_object_patch("model_sampling", model_sampling) + + samples = {"samples": comfy.sample.sample(model_clone_with_lora, noise, 1, 1.0, "euler", "simple", positive, negative, sample, + denoise=1.0, disable_noise=True, start_step=0, last_step=1, + force_full_denoise=True, noise_mask=None, callback=None, disable_pbar=True, seed=None)} + pbar.update(1) + + decoded = [] + for start_idx in range(0, samples["samples"].shape[0], per_batch): + decoded.append(vae.decode(samples["samples"][start_idx:start_idx+per_batch])) + image_out = torch.cat(decoded, dim=0) + + pbar.update(1) + + if task == 'depth map': + imax = image_out.max() + imin = image_out.min() + image_out = (image_out-imin)/(imax-imin) + image_out = torch.max(image_out, dim=3, keepdim=True)[0].repeat(1, 1, 1, 3) + elif task == 'surface normals': + image_out = F.normalize(image_out * 2 - 1, dim=3) / 2 + 0.5 + image_out = 1.0 - image_out + else: + image_out = image_out.clamp(-1.,1.) + + return (image_out, samples,) \ No newline at end of file diff --git a/.disabled/comfyui-kjnodes@nightly/nodes/lora_nodes.py b/.disabled/comfyui-kjnodes@nightly/nodes/lora_nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..0424474b80bc6140c02d125600b0a511725f9c39 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/nodes/lora_nodes.py @@ -0,0 +1,637 @@ +import torch +import comfy.model_management +import comfy.utils +import folder_paths +import os +import logging +from tqdm import tqdm +import numpy as np +from comfy_api.latest import io + +device = comfy.model_management.get_torch_device() + +CLAMP_QUANTILE = 0.99 + +def extract_lora(diff, key, rank, algorithm, lora_type, lowrank_iters=7, adaptive_param=1.0, clamp_quantile=True): + """ + Extracts LoRA weights from a weight difference tensor using SVD. + """ + conv2d = (len(diff.shape) == 4) + kernel_size = None if not conv2d else diff.size()[2:4] + conv2d_3x3 = conv2d and kernel_size != (1, 1) + out_dim, in_dim = diff.size()[0:2] + + if conv2d: + if conv2d_3x3: + diff = diff.flatten(start_dim=1) + else: + diff = diff.squeeze() + + diff_float = diff.float() + if algorithm == "svd_lowrank": + U, S, V = torch.svd_lowrank(diff_float, q=min(rank, in_dim, out_dim), niter=lowrank_iters) + U = U @ torch.diag(S) + Vh = V.t() + else: + #torch.linalg.svdvals() + U, S, Vh = torch.linalg.svd(diff_float) + # Flexible rank selection logic like locon: https://github.com/KohakuBlueleaf/LyCORIS/blob/main/tools/extract_locon.py + if "adaptive" in lora_type: + if lora_type == "adaptive_ratio": + min_s = torch.max(S) * adaptive_param + lora_rank = torch.sum(S > min_s).item() + elif lora_type == "adaptive_energy": + energy = torch.cumsum(S**2, dim=0) + total_energy = torch.sum(S**2) + threshold = adaptive_param * total_energy # e.g., adaptive_param=0.95 for 95% + lora_rank = torch.sum(energy < threshold).item() + 1 + elif lora_type == "adaptive_quantile": + s_cum = torch.cumsum(S, dim=0) + min_cum_sum = adaptive_param * torch.sum(S) + lora_rank = torch.sum(s_cum < min_cum_sum).item() + elif lora_type == "adaptive_fro": + S_squared = S.pow(2) + S_fro_sq = float(torch.sum(S_squared)) + sum_S_squared = torch.cumsum(S_squared, dim=0) / S_fro_sq + lora_rank = int(torch.searchsorted(sum_S_squared, adaptive_param**2)) + 1 + lora_rank = max(1, min(lora_rank, len(S))) + else: + pass # Will print after capping + + # Cap adaptive rank by the specified max rank + lora_rank = min(lora_rank, rank) + + # Calculate and print actual fro percentage retained after capping + if lora_type == "adaptive_fro": + S_squared = S.pow(2) + s_fro = torch.sqrt(torch.sum(S_squared)) + s_red_fro = torch.sqrt(torch.sum(S_squared[:lora_rank])) + fro_percent = float(s_red_fro / s_fro) + logging.info(f"{key} Extracted LoRA rank: {lora_rank}, Frobenius retained: {fro_percent:.1%}") + else: + logging.info(f"{key} Extracted LoRA rank: {lora_rank}") + else: + lora_rank = rank + + lora_rank = max(1, lora_rank) + lora_rank = min(out_dim, in_dim, lora_rank) + + U = U[:, :lora_rank] + S = S[:lora_rank] + U = U @ torch.diag(S) + Vh = Vh[:lora_rank, :] + + if clamp_quantile: + dist = torch.cat([U.flatten(), Vh.flatten()]) + if dist.numel() > 100_000: + # Sample 100,000 elements for quantile estimation + idx = torch.randperm(dist.numel(), device=dist.device)[:100_000] + dist_sample = dist[idx] + hi_val = torch.quantile(dist_sample, CLAMP_QUANTILE) + else: + hi_val = torch.quantile(dist, CLAMP_QUANTILE) + low_val = -hi_val + + U = U.clamp(low_val, hi_val) + Vh = Vh.clamp(low_val, hi_val) + if conv2d: + U = U.reshape(out_dim, lora_rank, 1, 1) + Vh = Vh.reshape(lora_rank, in_dim, kernel_size[0], kernel_size[1]) + return (U, Vh) + + +def calc_lora_model(model_diff, rank, prefix_model, prefix_lora, output_sd, lora_type, algorithm, lowrank_iters, out_dtype, bias_diff=False, adaptive_param=1.0, clamp_quantile=True): + # Get key names from module structure without materializing weights + sd_keys = [] + for name, _ in model_diff.model.named_parameters(): + if prefix_model is None or name.startswith(prefix_model): + sd_keys.append(name) + for name, _ in model_diff.model.named_buffers(): + if prefix_model is None or name.startswith(prefix_model): + sd_keys.append(name) + + total_keys = len([k for k in sd_keys if k.endswith(".weight") or (bias_diff and k.endswith(".bias"))]) + progress_bar = tqdm(total=total_keys, desc=f"Extracting LoRA ({prefix_lora.strip('.')})") + comfy_pbar = comfy.utils.ProgressBar(total_keys) + + # Process one weight at a time to minimize memory usage + for k in sd_keys: + if k.endswith(".weight"): + # Patch and retrieve single weight + weight_diff = model_diff.patch_weight_to_device(k, return_weight=True) + if weight_diff is None: + progress_bar.update(1) + comfy_pbar.update(1) + continue + if weight_diff.ndim == 5: + logging.info(f"Skipping 5D tensor for key {k}") + del weight_diff + progress_bar.update(1) + comfy_pbar.update(1) + continue + if lora_type != "full": + if weight_diff.ndim < 2: + if bias_diff: + output_sd["{}{}.diff".format(prefix_lora, k[len(prefix_model):-7])] = weight_diff.contiguous().to(out_dtype).cpu() + del weight_diff + progress_bar.update(1) + comfy_pbar.update(1) + continue + try: + out = extract_lora(weight_diff.to(device), k, rank, algorithm, lora_type, lowrank_iters=lowrank_iters, adaptive_param=adaptive_param, clamp_quantile=clamp_quantile) + output_sd["{}{}.lora_up.weight".format(prefix_lora, k[len(prefix_model):-7])] = out[0].contiguous().to(out_dtype).cpu() + output_sd["{}{}.lora_down.weight".format(prefix_lora, k[len(prefix_model):-7])] = out[1].contiguous().to(out_dtype).cpu() + except Exception as e: + logging.warning(f"Could not generate lora weights for key {k}, error {e}") + else: + output_sd["{}{}.diff".format(prefix_lora, k[len(prefix_model):-7])] = weight_diff.contiguous().to(out_dtype).cpu() + del weight_diff + progress_bar.update(1) + comfy_pbar.update(1) + + elif bias_diff and k.endswith(".bias"): + weight = model_diff.patch_weight_to_device(k, return_weight=True) + if weight is not None: + output_sd["{}{}.diff_b".format(prefix_lora, k[len(prefix_model):-5])] = weight.contiguous().to(out_dtype).cpu() + del weight + progress_bar.update(1) + comfy_pbar.update(1) + + progress_bar.close() + del model_diff + comfy.model_management.soft_empty_cache() + return output_sd + + +class LoraExtractKJ(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="LoraExtractKJ", + category="KJNodes/lora", + is_output_node=True, + inputs=[ + io.MultiType.Input("finetuned", [io.Model, io.Clip], tooltip="The finetuned model or clip to extract LoRA from."), + io.MultiType.Input("original", [io.Model, io.Clip], tooltip="The original base model or clip to diff against."), + io.String.Input("filename_prefix", default="loras/ComfyUI_extracted_lora"), + io.Int.Input("rank", default=64, min=1, max=4096, step=1, tooltip="The rank to use for standard LoRA, or maximum rank limit for adaptive methods."), + io.Combo.Input("lora_type", options=["standard", "full", "adaptive_ratio", "adaptive_quantile", "adaptive_energy", "adaptive_fro"]), + io.Combo.Input("algorithm", options=["svd_linalg", "svd_lowrank"], default="svd_lowrank", tooltip="SVD algorithm to use, svd_lowrank is faster but less accurate."), + io.Int.Input("lowrank_iters", default=7, min=1, max=100, step=1, tooltip="The number of subspace iterations for lowrank SVD algorithm."), + io.Combo.Input("output_dtype", options=["fp16", "bf16", "fp32"], default="fp16"), + io.Boolean.Input("bias_diff", default=True), + io.Float.Input("adaptive_param", default=0.15, min=0.0, max=1.0, step=0.01, tooltip="For ratio mode, this is the ratio of the maximum singular value. For quantile mode, this is the quantile of the singular values. For fro mode, this is the Frobenius norm retention ratio."), + io.Boolean.Input("clamp_quantile", default=False), + ], + ) + + + @classmethod + def execute(cls, finetuned, original, filename_prefix, rank, lora_type, algorithm, lowrank_iters, output_dtype, bias_diff, adaptive_param, clamp_quantile) -> io.NodeOutput: + if algorithm == "svd_lowrank" and lora_type != "standard": + raise ValueError("svd_lowrank algorithm is only supported for standard LoRA extraction.") + + dtype = {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32}[output_dtype] + + output_dir = folder_paths.get_output_directory() + full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, output_dir) + + output_sd = {} + + is_clip = hasattr(finetuned, "patcher") + + if is_clip: + clip_diff = finetuned.clone() + kp = original.get_key_patches() + kp = {k: v for k, v in kp.items() if not k.endswith(".position_ids") and not k.endswith(".logit_scale")} + clip_diff.add_patches(kp, -1.0, 1.0) + output_sd = calc_lora_model(clip_diff.patcher, rank, "", "text_encoders.", output_sd, lora_type, algorithm, lowrank_iters, dtype, bias_diff=bias_diff, adaptive_param=adaptive_param, clamp_quantile=clamp_quantile) + else: + m = finetuned.clone() + kp = original.get_key_patches("diffusion_model.") + m.add_patches(kp, -1.0, 1.0) + output_sd = calc_lora_model(m, rank, "diffusion_model.", "diffusion_model.", output_sd, lora_type, algorithm, lowrank_iters, dtype, bias_diff=bias_diff, adaptive_param=adaptive_param, clamp_quantile=clamp_quantile) + + if "adaptive" in lora_type: + rank_str = f"{lora_type}_{adaptive_param:.2f}" + else: + rank_str = rank + output_checkpoint = f"{filename}_rank_{rank_str}_{output_dtype}_{counter:05}_.safetensors" + output_checkpoint = os.path.join(full_output_folder, output_checkpoint) + + comfy.utils.save_torch_file(output_sd, output_checkpoint, metadata=None) + return io.NodeOutput() + +class LoraReduceRank(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="LoraReduceRankKJ", + display_name="LoraReduceRank", + category="KJNodes/lora", + description="Resize a LoRA model by reducing its rank. Based on kohya's sd-scripts: https://github.com/kohya-ss/sd-scripts/blob/main/networks/resize_lora.py", + is_output_node=True, + is_experimental=True, + inputs=[ + io.Combo.Input("lora_name", options=folder_paths.get_filename_list("loras"), tooltip="The name of the LoRA."), + io.Int.Input("new_rank", default=8, min=1, max=4096, step=1, tooltip="The new rank to resize the LoRA. Acts as max rank when using dynamic_method."), + io.Combo.Input("dynamic_method", options=["disabled", "sv_ratio", "sv_cumulative", "sv_fro", "sv_knee"], default="disabled", tooltip="Method to use for dynamically determining new alphas and dims. sv_knee finds the elbow point in the singular value curve."), + io.Float.Input("dynamic_param", default=0.2, min=0.0, max=2.0, step=0.01, tooltip="Parameter for dynamic methods. For sv_knee: sensitivity (1.0=standard knee, <1.0=more aggressive/lower rank, >1.0=more conservative)."), + io.Combo.Input("output_dtype", options=["match_original", "fp16", "bf16", "fp32"], default="match_original", tooltip="Data type to save the LoRA as."), + io.Boolean.Input("verbose", default=True), + ], + ) + + @classmethod + def execute(cls, lora_name, new_rank, dynamic_method, dynamic_param, output_dtype, verbose) -> io.NodeOutput: + lora_path = folder_paths.get_full_path("loras", lora_name) + lora_sd, metadata = comfy.utils.load_torch_file(lora_path, return_metadata=True) + + if output_dtype == "fp16": + save_dtype = torch.float16 + elif output_dtype == "bf16": + save_dtype = torch.bfloat16 + elif output_dtype == "fp32": + save_dtype = torch.float32 + elif output_dtype == "match_original": + first_weight_key = next(k for k in lora_sd if k.endswith(".weight") and isinstance(lora_sd[k], torch.Tensor)) + save_dtype = lora_sd[first_weight_key].dtype + + new_lora_sd = {} + for k, v in lora_sd.items(): + new_lora_sd[k.replace(".default", "")] = v + del lora_sd + logging.info("Resizing Lora...") + output_sd, old_dim, new_alpha, rank_list = resize_lora_model(new_lora_sd, new_rank, save_dtype, device, dynamic_method, dynamic_param, verbose) + + if metadata is None: + metadata = {} + + comment = metadata.get("ss_training_comment", "") + + if dynamic_method == "disabled": + metadata["ss_training_comment"] = f"dimension is resized from {old_dim} to {new_rank}; {comment}" + metadata["ss_network_dim"] = str(new_rank) + metadata["ss_network_alpha"] = str(new_alpha) + else: + metadata["ss_training_comment"] = f"Dynamic resize with {dynamic_method}: {dynamic_param} from {old_dim}; {comment}" + metadata["ss_network_dim"] = "Dynamic" + metadata["ss_network_alpha"] = "Dynamic" + + for key in list(output_sd.keys()): + value = output_sd[key] + if type(value) == torch.Tensor and value.dtype.is_floating_point and value.dtype != save_dtype: + output_sd[key] = value.to(save_dtype) + + output_dir = folder_paths.get_output_directory() + output_filename_prefix = "loras/" + lora_name + + full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(output_filename_prefix, output_dir) + output_dtype_str = f"_{output_dtype}" if output_dtype != "match_original" else "" + average_rank = str(int(np.mean(rank_list))) + rank_str = new_rank if dynamic_method == "disabled" else f"dynamic_{average_rank}" + output_checkpoint = f"{filename.replace('.safetensors', '')}_resized_from_{old_dim}_to_{rank_str}{output_dtype_str}_{counter:05}_.safetensors" + output_checkpoint = os.path.join(full_output_folder, output_checkpoint) + logging.info(f"Saving resized LoRA to {output_checkpoint}") + + comfy.utils.save_torch_file(output_sd, output_checkpoint, metadata=metadata) + return io.NodeOutput() + +# Convert LoRA to different rank approximation (should only be used to go to lower rank) +# This code is based off the extract_lora_from_models.py file which is based on https://github.com/cloneofsimo/lora/blob/develop/lora_diffusion/cli_svd.py +# Thanks to cloneofsimo + +# This version is based on +# https://github.com/kohya-ss/sd-scripts/blob/main/networks/resize_lora.py + +MIN_SV = 1e-6 + +LORA_DOWN_UP_FORMATS = [ + ("lora_down", "lora_up"), # sd-scripts LoRA + ("lora_A", "lora_B"), # PEFT LoRA + ("down", "up"), # ControlLoRA +] + +# Indexing functions +def index_sv_cumulative(S, target): + original_sum = float(torch.sum(S)) + cumulative_sums = torch.cumsum(S, dim=0) / original_sum + index = int(torch.searchsorted(cumulative_sums, target)) + 1 + index = max(1, min(index, len(S) - 1)) + + return index + + +def index_sv_fro(S, target): + S_squared = S.pow(2) + S_fro_sq = float(torch.sum(S_squared)) + sum_S_squared = torch.cumsum(S_squared, dim=0) / S_fro_sq + index = int(torch.searchsorted(sum_S_squared, target**2)) + 1 + index = max(1, min(index, len(S) - 1)) + + return index + + +def index_sv_ratio(S, target): + max_sv = S[0] + min_sv = max_sv / target + index = int(torch.sum(S > min_sv).item()) + index = max(1, min(index, len(S) - 1)) + + return index + + +def index_sv_knee(S, sensitivity=1.0): + """Find the knee/elbow point in the singular value curve. + Uses the Kneedle method: normalizes the curve to [0,1] on both axes, + then finds the point with maximum distance from a reference line. + + sensitivity controls the aggressiveness: + 1.0 = standard knee point + < 1.0 = more aggressive (lower rank), e.g. 0.5 roughly halves the knee rank + > 1.0 = more conservative (higher rank) + The reference line tilts based on sensitivity: at lower values, + the line favors keeping fewer singular values.""" + n = len(S) + if n <= 2: + return 1 + + S_np = S.cpu().float().numpy() + + # Normalize x and y to [0, 1] + x = np.linspace(0, 1, n) + y = (S_np - S_np[-1]) / (S_np[0] - S_np[-1] + 1e-10) + + # Reference line from (0, 1) to (1, 1-sensitivity) + # At sensitivity=1.0: line goes (0,1)->(1,0), standard kneedle + # At sensitivity=0.5: line goes (0,1)->(1,0.5), steeper = more aggressive + y_line = 1.0 - sensitivity * x + + # Signed distance: positive means curve is above the line (keep) + distances = y - y_line + + # Find the point of maximum positive distance + index = int(np.argmax(distances)) + index = max(1, min(index, n - 1)) + return index + + +# Modified from Kohaku-blueleaf's extract/merge functions +def _svd_extract(weight_2d, lora_rank, dynamic_method, dynamic_param, device, scale=1): + """Shared SVD extraction for both linear and conv weights. + Dynamic mode: single full SVD (need all singular values for rank selection). + Disabled mode: svd_lowrank only (rank is known, much faster for large matrices).""" + weight_2d = weight_2d.to(device) + if weight_2d.dtype != torch.float32: + weight_2d = weight_2d.float() + + if dynamic_method and dynamic_method != "disabled": + # Full SVD: we need all singular values for dynamic rank selection, + # and we reuse U/Vh directly — one SVD, no wasted work + U, S, Vh = torch.linalg.svd(weight_2d, full_matrices=False) + param_dict = rank_resize(S, lora_rank, dynamic_method, dynamic_param, scale) + lora_rank = param_dict["new_rank"] + U = U[:, :lora_rank] + S = S[:lora_rank] + Vh = Vh[:lora_rank, :] + else: + # Randomized lowrank SVD: only compute top-k, much faster when rank << min(m,n) + U, S, V = torch.svd_lowrank(weight_2d, q=lora_rank, niter=7) + Vh = V.t() + param_dict = {"new_rank": lora_rank, "new_alpha": float(scale * lora_rank)} + del V + + sqrt_S = torch.diag(torch.sqrt(S)) + U = U @ sqrt_S + Vh = sqrt_S @ Vh + + return U, Vh, param_dict + + +def extract_conv(weight, lora_rank, dynamic_method, dynamic_param, device, scale=1): + out_size, in_size, kernel_size, _ = weight.size() + + U, Vh, param_dict = _svd_extract( + weight.reshape(out_size, -1), lora_rank, dynamic_method, dynamic_param, device, scale + ) + lora_rank = param_dict["new_rank"] + + param_dict["lora_down"] = Vh.reshape(lora_rank, in_size, kernel_size, kernel_size).cpu() + param_dict["lora_up"] = U.reshape(out_size, lora_rank, 1, 1).cpu() + del U, Vh, weight + return param_dict + + +def extract_linear(weight, lora_rank, dynamic_method, dynamic_param, device, scale=1): + out_size, in_size = weight.size() + + U, Vh, param_dict = _svd_extract( + weight, lora_rank, dynamic_method, dynamic_param, device, scale + ) + lora_rank = param_dict["new_rank"] + + param_dict["lora_down"] = Vh.reshape(lora_rank, in_size).cpu() + param_dict["lora_up"] = U.reshape(out_size, lora_rank).cpu() + del U, Vh, weight + return param_dict + + +def merge_conv(lora_down, lora_up, device): + in_rank, in_size, kernel_size, k_ = lora_down.shape + out_size, out_rank, _, _ = lora_up.shape + assert in_rank == out_rank and kernel_size == k_, f"rank {in_rank} {out_rank} or kernel {kernel_size} {k_} mismatch" + + lora_down = lora_down.to(device) + lora_up = lora_up.to(device) + + merged = lora_up.reshape(out_size, -1) @ lora_down.reshape(in_rank, -1) + weight = merged.reshape(out_size, in_size, kernel_size, kernel_size) + del lora_up, lora_down + return weight + + +def merge_linear(lora_down, lora_up, device): + in_rank, in_size = lora_down.shape + out_size, out_rank = lora_up.shape + assert in_rank == out_rank, f"rank {in_rank} {out_rank} mismatch" + + lora_down = lora_down.to(device) + lora_up = lora_up.to(device) + + weight = lora_up @ lora_down + del lora_up, lora_down + return weight + + +# Calculate new rank + + +def rank_resize(S, rank, dynamic_method, dynamic_param, scale=1): + param_dict = {} + + if dynamic_method == "sv_ratio": + # Calculate new dim and alpha based off ratio + new_rank = index_sv_ratio(S, dynamic_param) + 1 + new_alpha = float(scale * new_rank) + + elif dynamic_method == "sv_cumulative": + # Calculate new dim and alpha based off cumulative sum + new_rank = index_sv_cumulative(S, dynamic_param) + 1 + new_alpha = float(scale * new_rank) + + elif dynamic_method == "sv_fro": + # Calculate new dim and alpha based off sqrt sum of squares + new_rank = index_sv_fro(S, dynamic_param) + 1 + new_alpha = float(scale * new_rank) + + elif dynamic_method == "sv_knee": + # Knee/elbow detection in singular value curve + new_rank = index_sv_knee(S, dynamic_param) + 1 + new_alpha = float(scale * new_rank) + else: + new_rank = rank + new_alpha = float(scale * new_rank) + + if S[0] <= MIN_SV: # Zero matrix, set dim to 1 + new_rank = 1 + new_alpha = float(scale * new_rank) + elif new_rank > rank: # cap max rank at rank + new_rank = rank + new_alpha = float(scale * new_rank) + + # Calculate resize info + s_sum = torch.sum(torch.abs(S)) + s_rank = torch.sum(torch.abs(S[:new_rank])) + + S_squared = S.pow(2) + s_fro = torch.sqrt(torch.sum(S_squared)) + s_red_fro = torch.sqrt(torch.sum(S_squared[:new_rank])) + fro_percent = float(s_red_fro / s_fro) + + param_dict["new_rank"] = new_rank + param_dict["new_alpha"] = new_alpha + param_dict["sum_retained"] = (s_rank) / s_sum + param_dict["fro_retained"] = fro_percent + param_dict["max_ratio"] = S[0] / S[new_rank - 1] + + return param_dict + + +def resize_lora_model(lora_sd, new_rank, save_dtype, device, dynamic_method, dynamic_param, verbose): + max_old_rank = None + new_alpha = None + verbose_str = "\n" + fro_list = [] + rank_list = [] + + if dynamic_method: + logging.info(f"Dynamically determining new alphas and dims based off {dynamic_method}: {dynamic_param}, max rank is {new_rank}") + + lora_down_weight = None + lora_up_weight = None + + o_lora_sd = lora_sd.copy() + block_down_name = None + block_up_name = None + + total_keys = len([k for k in lora_sd if k.endswith(".weight")]) + + pbar = comfy.utils.ProgressBar(total_keys) + for key, value in tqdm(lora_sd.items(), leave=True, desc="Resizing LoRA weights"): + key_parts = key.split(".") + block_down_name = None + for _format in LORA_DOWN_UP_FORMATS: + # Currently we only match lora_down_name in the last two parts of key + # because ("down", "up") are general words and may appear in block_down_name + if len(key_parts) >= 2 and _format[0] == key_parts[-2]: + block_down_name = ".".join(key_parts[:-2]) + lora_down_name = "." + _format[0] + lora_up_name = "." + _format[1] + weight_name = "." + key_parts[-1] + break + if len(key_parts) >= 1 and _format[0] == key_parts[-1]: + block_down_name = ".".join(key_parts[:-1]) + lora_down_name = "." + _format[0] + lora_up_name = "." + _format[1] + weight_name = "" + break + + if block_down_name is None: + # This parameter is not lora_down + continue + + # Now weight_name can be ".weight" or "" + # Find corresponding lora_up and alpha + block_up_name = block_down_name + lora_down_weight = value + lora_up_weight = lora_sd.get(block_up_name + lora_up_name + weight_name, None) + lora_alpha = lora_sd.get(block_down_name + ".alpha", None) + + weights_loaded = lora_down_weight is not None and lora_up_weight is not None + + if weights_loaded: + + conv2d = len(lora_down_weight.size()) == 4 + old_rank = lora_down_weight.size()[0] + max_old_rank = max(max_old_rank or 0, old_rank) + + # Skip if merged weight would be too large (>100k elements in any dimension) + if conv2d: + in_rank, in_size, kernel_size, _ = lora_down_weight.shape + out_size, out_rank, _, _ = lora_up_weight.shape + merged_size = out_size * in_size * kernel_size * kernel_size + else: + in_rank, in_size = lora_down_weight.shape + out_size, out_rank = lora_up_weight.shape + merged_size = out_size * in_size + + if merged_size > 100_000_000: # Skip if >100M elements + logging.warning(f"Skipping {block_down_name}: merged weight too large ({merged_size:,} elements)") + tqdm.write(f"SKIPPED: {block_down_name} - too large ({merged_size:,} elements)") + pbar.update(1) + continue + + if lora_alpha is None: + scale = 1.0 + else: + scale = lora_alpha / old_rank + + if conv2d: + full_weight_matrix = merge_conv(lora_down_weight, lora_up_weight, device) + param_dict = extract_conv(full_weight_matrix, new_rank, dynamic_method, dynamic_param, device, scale) + else: + full_weight_matrix = merge_linear(lora_down_weight, lora_up_weight, device) + param_dict = extract_linear(full_weight_matrix, new_rank, dynamic_method, dynamic_param, device, scale) + + if verbose and "fro_retained" in param_dict: + max_ratio = param_dict["max_ratio"] + sum_retained = param_dict["sum_retained"] + fro_retained = param_dict["fro_retained"] + if not np.isnan(fro_retained): + fro_list.append(float(fro_retained)) + log_str = f"{block_down_name:75} | sum(S) retained: {sum_retained:.1%}, fro retained: {fro_retained:.1%}, max(S) ratio: {max_ratio:0.1f}, new dim: {param_dict['new_rank']}" + tqdm.write(log_str) + verbose_str += log_str + + if verbose and dynamic_method: + verbose_str += f", dynamic | dim: {param_dict['new_rank']}, alpha: {param_dict['new_alpha']}\n" + else: + verbose_str += "\n" + + new_alpha = param_dict["new_alpha"] + o_lora_sd[block_down_name + lora_down_name + weight_name] = param_dict["lora_down"].to(save_dtype).contiguous() + o_lora_sd[block_up_name + lora_up_name + weight_name] = param_dict["lora_up"].to(save_dtype).contiguous() + o_lora_sd[block_down_name + ".alpha"] = torch.tensor(param_dict["new_alpha"]).to(save_dtype) + + block_down_name = None + block_up_name = None + lora_down_weight = None + lora_up_weight = None + weights_loaded = False + rank_list.append(param_dict["new_rank"]) + del param_dict + pbar.update(1) + + if verbose: + logging.info(f"Average Frobenius norm retention: {np.mean(fro_list):.2%} | std: {np.std(fro_list):0.3f}") + return o_lora_sd, max_old_rank, new_alpha, rank_list diff --git a/.disabled/comfyui-kjnodes@nightly/nodes/ltxv_nodes.py b/.disabled/comfyui-kjnodes@nightly/nodes/ltxv_nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..e3faf1477018a10a4c7b1ad4f94e9ceec4e3eb4c --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/nodes/ltxv_nodes.py @@ -0,0 +1,1953 @@ +from comfy_extras.nodes_lt import get_noise_mask, LTXVAddGuide +import types +import math +from typing import Tuple +import comfy +from comfy_api.latest import io +import numpy as np +import torch +import logging +import comfy.model_management as mm +import comfy.ldm.modules.attention as _comfy_attn +from comfy.ldm.lightricks.model import apply_rotary_emb as _apply_rope +device = mm.get_torch_device() +import latent_preview + +class LTXVAddGuideMulti(LTXVAddGuide): + + @classmethod + def define_schema(cls): + options = [] + for num_guides in range(1, 21): # 1 to 20 guides + guide_inputs = [] + for i in range(1, num_guides + 1): + guide_inputs.extend([ + io.Image.Input(f"image_{i}"), + io.Int.Input( + f"frame_idx_{i}", + default=0, + min=-9999, + max=9999, + tooltip=f"Frame index for guide {i}.", + ), + io.Float.Input(f"strength_{i}", default=1.0, min=0.0, max=1.0, step=0.01, tooltip=f"Strength for guide {i}."), + ]) + options.append(io.DynamicCombo.Option( + key=str(num_guides), + inputs=guide_inputs + )) + + return io.Schema( + node_id="LTXVAddGuideMulti", + category="KJNodes/ltxv", + description="Add multiple guide images at specified frame indices with strengths, uses DynamicCombo which requires ComfyUI 0.8.1 and frontend 1.33.4 or later.", + inputs=[ + io.Conditioning.Input("positive", tooltip="Positive conditioning to which guide keyframe info will be added"), + io.Conditioning.Input("negative", tooltip="Negative conditioning to which guide keyframe info will be added"), + io.Vae.Input("vae", tooltip="Video VAE used to encode the guide images"), + io.Latent.Input("latent", tooltip="Video latent, guides are added to the end of this latent"), + io.DynamicCombo.Input( + "num_guides", + options=options, + display_name="Number of Guides", + tooltip="Select how many guide images to use", + ), + ], + outputs=[ + io.Conditioning.Output(display_name="positive"), + io.Conditioning.Output(display_name="negative"), + io.Latent.Output(display_name="latent", tooltip="Video latent with added guides"), + ], + ) + + @classmethod + def execute(cls, positive, negative, vae, latent, num_guides) -> io.NodeOutput: + scale_factors = vae.downscale_index_formula + latent_image = latent["samples"] + noise_mask = get_noise_mask(latent) + + _, _, latent_length, latent_height, latent_width = latent_image.shape + + # num_guides is a dict containing the inputs from the selected option + # e.g., {'image_1': tensor, 'frame_idx_1': 0, 'strength_1': 1.0, 'image_2': tensor, 'frame_idx_2': 20, 'strength_2': 0.8, ...} + + image_keys = sorted([k for k in num_guides.keys() if k.startswith('image_')]) + + for img_key in image_keys: + i = img_key.split('_')[1] + + img = num_guides[f"image_{i}"] + f_idx = num_guides[f"frame_idx_{i}"] + strength = num_guides[f"strength_{i}"] + + image_1, t = cls.encode(vae, latent_width, latent_height, img, scale_factors) + + frame_idx, latent_idx = cls.get_latent_index(positive, latent_length, len(image_1), f_idx, scale_factors) + assert latent_idx + t.shape[2] <= latent_length, "Conditioning frames exceed the length of the latent sequence." + + positive, negative, latent_image, noise_mask = cls.append_keyframe( + positive, + negative, + frame_idx, + latent_image, + noise_mask, + t, + strength, + scale_factors, + ) + + return io.NodeOutput(positive, negative, {"samples": latent_image, "noise_mask": noise_mask}) + +class LTXVAddGuidesFromBatch(LTXVAddGuide): + + @classmethod + def define_schema(cls): + return io.Schema( + node_id="LTXVAddGuidesFromBatch", + category="conditioning/ltxv", + description="Adds multiple guide images from a batch to the latent at corresponding frame indices. Non-black images in the batch are used as guides.", + inputs=[ + io.Conditioning.Input("positive"), + io.Conditioning.Input("negative"), + io.Vae.Input("vae"), + io.Latent.Input("latent"), + io.Image.Input("images", tooltip="Batch of images - non-black images will be used as guides"), + io.Float.Input("strength", default=1.0, min=0.0, max=1.0, step=0.01), + ], + outputs=[ + io.Conditioning.Output(display_name="positive"), + io.Conditioning.Output(display_name="negative"), + io.Latent.Output(display_name="latent"), + ], + ) + + @classmethod + def execute(cls, positive, negative, vae, latent, images, strength) -> io.NodeOutput: + scale_factors = vae.downscale_index_formula + latent_image = latent["samples"] + noise_mask = get_noise_mask(latent) + + _, _, latent_length, latent_height, latent_width = latent_image.shape + + # Process each image in the batch + batch_size = images.shape[0] + + for i in range(batch_size): + img = images[i:i+1] + + # Check if image is not black and use batch index as frame index + if img.max() > 0.001: + f_idx = i + + image_1, t = cls.encode(vae, latent_width, latent_height, img, scale_factors) + + frame_idx, latent_idx = cls.get_latent_index(positive, latent_length, len(image_1), f_idx, scale_factors) + + if latent_idx + t.shape[2] <= latent_length: + positive, negative, latent_image, noise_mask = cls.append_keyframe( + positive, + negative, + frame_idx, + latent_image, + noise_mask, + t, + strength, + scale_factors, + ) + else: + print(f"Warning: Skipping guide at index {i} - conditioning frames exceed latent sequence length") + + return io.NodeOutput(positive, negative, {"samples": latent_image, "noise_mask": noise_mask}) + + +class LTXVAudioVideoMask(io.ComfyNode): + + @classmethod + def define_schema(cls): + return io.Schema( + node_id="LTXVAudioVideoMask", + category="KJNodes/ltxv", + description="Creates noise masks for video and audio latents based on specified time ranges. New content is generated within these masked regions", + inputs=[ + io.Latent.Input("video_latent", optional=True), + io.Latent.Input("audio_latent", optional=True), + io.Float.Input("video_fps", default=25, min=0.0, max=100.0, step=0.01), + io.Float.Input("video_start_time", default=0.0, min=0.0, max=10000.0, step=0.01, tooltip="Start time in seconds for the video mask."), + io.Float.Input("video_end_time", default=5.0, min=0.0, max=10000.0, step=0.01, tooltip="End time in seconds for the video mask."), + io.Float.Input("audio_start_time", default=0.0, min=0.0, max=10000.0, step=0.01, tooltip="Start time in seconds for the audio mask."), + io.Float.Input("audio_end_time", default=5.0, min=0.0, max=10000.0, step=0.01, tooltip="End time in seconds for the audio mask."), + io.Combo.Input( + "max_length", + options=["truncate", "pad", "partial"], + default="truncate", + tooltip="'truncate': cut latent to end_time length. 'pad': extend latent to end_time. 'partial': mask range within existing latent.", + ), + io.Combo.Input("existing_mask_mode", options=["add", "subtract", "overwrite"], optional=True, default="add", tooltip="How to combine with existing noise masks if present. 'add' will take the max of existing and new mask, 'overwrite' will replace with new mask. 'subtract' will set the masked region to 0 instead of 1, effectively unmasking it."), + ], + outputs=[ + io.Latent.Output(display_name="video_latent"), + io.Latent.Output(display_name="audio_latent"), + ], + ) + + @classmethod + def execute(cls, video_fps, video_start_time, video_end_time, audio_start_time, audio_end_time, max_length="truncate", existing_mask_mode="add", video_latent=None, audio_latent=None,) -> io.NodeOutput: + + time_scale_factor = 8 + mel_hop_length = 160 + sampling_rate = 16000 + latent_downsample_factor = 4 + audio_latents_per_second = (sampling_rate / mel_hop_length / latent_downsample_factor) # 25 + + if video_latent is not None: + video_latent_frame_count = video_latent["samples"].shape[2] + + video_pixel_frame_start_raw = int(round(video_start_time * video_fps)) + video_pixel_frame_end_raw = int(round(video_end_time * video_fps)) + + # Calculate required latent frames based on end time + required_latent_frames = (video_pixel_frame_end_raw - 1) // time_scale_factor + 1 + + # Handle different max_length modes + if max_length == "pad" and required_latent_frames > video_latent_frame_count: + # Pad video latent if required frames exceed current length + pad_frames = required_latent_frames - video_latent_frame_count + padding = torch.zeros( + video_latent["samples"].shape[0], + video_latent["samples"].shape[1], + pad_frames, + video_latent["samples"].shape[3], + video_latent["samples"].shape[4], + dtype=video_latent["samples"].dtype, + device=video_latent["samples"].device + ) + video_samples = torch.cat([video_latent["samples"], padding], dim=2) + video_latent_frame_count = video_samples.shape[2] + elif max_length == "truncate": + # Truncate to the end_time + video_samples = video_latent["samples"][:, :, :required_latent_frames] + video_latent_frame_count = video_samples.shape[2] + else: # partial + video_samples = video_latent["samples"] + + # Now calculate indices based on potentially padded latent + video_pixel_frame_count = (video_latent_frame_count - 1) * time_scale_factor + 1 + xp = np.array([0] + list(range(1, video_pixel_frame_count + time_scale_factor, time_scale_factor))) + + # video_frame_index_start = index of the value in xp rounding up + video_latent_frame_index_start = np.searchsorted(xp, video_pixel_frame_start_raw, side="left") + # video_frame_index_end = index of the value in xp rounding down + video_latent_frame_index_end = np.searchsorted(xp, video_pixel_frame_end_raw, side="right") - 1 + + video_latent_frame_index_start = max(0, video_latent_frame_index_start) + video_latent_frame_index_end = min(video_latent_frame_index_end, video_latent_frame_count) + + # Get existing noise mask if present, otherwise create new one + if "noise_mask" in video_latent and video_latent["noise_mask"] is not None and existing_mask_mode != "overwrite": + video_mask = video_latent["noise_mask"].clone() + # Adjust mask size based on mode + if max_length == "pad" and video_samples.shape[2] > video_latent["samples"].shape[2]: + # Pad the mask if we padded the samples + mask_padding = torch.zeros( + video_mask.shape[0], + video_mask.shape[1], + video_samples.shape[2] - video_mask.shape[2], + video_mask.shape[3], + video_mask.shape[4], + dtype=video_mask.dtype, + device=video_mask.device + ) + video_mask = torch.cat([video_mask, mask_padding], dim=2) + elif max_length == "truncate": + # Truncate the mask to match truncated samples + video_mask = video_mask[:, :, :video_samples.shape[2]] + else: + video_mask = torch.zeros_like(video_samples)[:, :1] + + video_mask[:, :, video_latent_frame_index_start:video_latent_frame_index_end] = 1.0 if existing_mask_mode != "subtract" else 0.0 + # ensure all padded frames are also masked + if max_length == "pad" and video_samples.shape[2] > video_latent["samples"].shape[2]: + video_mask[:, :, video_latent["samples"].shape[2]:] = 1.0 if existing_mask_mode != "subtract" else 0.0 + video_latent = video_latent.copy() + video_latent["samples"] = video_samples + video_latent["noise_mask"] = video_mask + + if audio_latent is not None: + audio_latent_frame_count = audio_latent["samples"].shape[2] + + audio_latent_frame_index_start = int(round(audio_start_time * audio_latents_per_second)) + audio_latent_frame_index_end = int(round(audio_end_time * audio_latents_per_second)) + 1 + + # Handle different max_length modes + if max_length == "pad" and audio_latent_frame_index_end > audio_latent_frame_count: + # Pad audio latent if end index exceeds current length + pad_frames = audio_latent_frame_index_end - audio_latent_frame_count + padding = torch.zeros( + audio_latent["samples"].shape[0], + audio_latent["samples"].shape[1], + pad_frames, + audio_latent["samples"].shape[3], + dtype=audio_latent["samples"].dtype, + device=audio_latent["samples"].device + ) + audio_samples = torch.cat([audio_latent["samples"], padding], dim=2) + audio_latent_frame_count = audio_samples.shape[2] + elif max_length == "truncate": + # Truncate to the end_time + audio_samples = audio_latent["samples"][:, :, :audio_latent_frame_index_end] + audio_latent_frame_count = audio_samples.shape[2] + else: # partial + audio_samples = audio_latent["samples"] + + audio_latent_frame_index_start = max(0, audio_latent_frame_index_start) + audio_latent_frame_index_end = min(audio_latent_frame_index_end, audio_latent_frame_count) + + # Get existing noise mask if present, otherwise create new one + if "noise_mask" in audio_latent and audio_latent["noise_mask"] is not None and existing_mask_mode != "overwrite": + audio_mask = audio_latent["noise_mask"].clone() + # Adjust mask size based on mode + if max_length == "pad" and audio_samples.shape[2] > audio_latent["samples"].shape[2]: + # Pad the mask if we padded the samples + mask_padding = torch.zeros( + audio_mask.shape[0], + audio_mask.shape[1], + audio_samples.shape[2] - audio_mask.shape[2], + audio_mask.shape[3], + dtype=audio_mask.dtype, + device=audio_mask.device + ) + audio_mask = torch.cat([audio_mask, mask_padding], dim=2) + elif max_length == "truncate": + # Truncate the mask to match truncated samples + audio_mask = audio_mask[:, :, :audio_samples.shape[2]] + else: + audio_mask = torch.zeros_like(audio_samples) + + audio_mask[:, :, audio_latent_frame_index_start:audio_latent_frame_index_end] = 1.0 + # ensure all padded frames are also masked + if max_length == "pad" and audio_samples.shape[2] > audio_latent["samples"].shape[2]: + audio_mask[:, :, audio_latent["samples"].shape[2]:] = 1.0 + audio_latent = audio_latent.copy() + audio_latent["samples"] = audio_samples + audio_latent["noise_mask"] = audio_mask + + return io.NodeOutput(video_latent, audio_latent) + +def _compute_attention(self, query, context, attn_precision=None, transformer_options={}): + """Compute attention and return the result. Cleans up intermediate tensors.""" + k = self.k_norm(self.to_k(context)).to(query.dtype) + v = self.to_v(context).to(query.dtype) + x = comfy.ldm.modules.attention.optimized_attention(query, k, v, heads=self.heads, attn_precision=attn_precision, transformer_options=transformer_options).flatten(2) + del k, v + return x + +def nag_attention(self, query, context_positive, nag_context, attn_precision=None, transformer_options={}): + x_positive = _compute_attention(self, query, context_positive, attn_precision, transformer_options) + x_negative = _compute_attention(self, query, nag_context, attn_precision, transformer_options) + return x_positive, x_negative + +def normalized_attention_guidance(self, x_positive, x_negative): + if self.inplace: + nag_guidance = x_negative.mul_(self.nag_scale - 1).neg_().add_(x_positive, alpha=self.nag_scale) + else: + nag_guidance = x_positive * self.nag_scale - x_negative * (self.nag_scale - 1) + + del x_negative + + norm_positive = torch.norm(x_positive, p=1, dim=-1, keepdim=True) + norm_guidance = torch.norm(nag_guidance, p=1, dim=-1, keepdim=True) + + scale = norm_guidance / norm_positive + torch.nan_to_num_(scale, nan=10.0) + mask = scale > self.nag_tau + del scale + + adjustment = (norm_positive * self.nag_tau) / (norm_guidance + 1e-7) + del norm_positive, norm_guidance + + nag_guidance.mul_(torch.where(mask, adjustment, 1.0)) + del mask, adjustment + + if self.inplace: + nag_guidance.sub_(x_positive).mul_(self.nag_alpha).add_(x_positive) + else: + nag_guidance = nag_guidance * self.nag_alpha + x_positive * (1 - self.nag_alpha) + del x_positive + + return nag_guidance + +#region NAG +def ltxv_crossattn_forward_nag(self, x, context, mask=None, transformer_options={}, **kwargs): + + # Single or [pos, neg] pair + if context.shape[0] == 1: + x_pos, context_pos = x, context + x_neg, context_neg = None, None + else: + x_pos, x_neg = torch.chunk(x, 2, dim=0) + context_pos, context_neg = torch.chunk(context, 2, dim=0) + + # Positive + q_pos = self.q_norm(self.to_q(x_pos)) + del x_pos + + x_positive, x_negative = nag_attention(self, q_pos, context_pos, self.nag_context, attn_precision=self.attn_precision, transformer_options=transformer_options) + del context_pos, q_pos + + x_pos_out = normalized_attention_guidance(self, x_positive, x_negative) + del x_positive, x_negative + + # Negative + if x_neg is not None and context_neg is not None: + q_neg = self.q_norm(self.to_q(x_neg)) + k_neg = self.k_norm(self.to_k(context_neg)) + v_neg = self.to_v(context_neg) + + x_neg_out = comfy.ldm.modules.attention.optimized_attention(q_neg, k_neg, v_neg, heads=self.heads, attn_precision=self.attn_precision, transformer_options=transformer_options) + out = torch.cat([x_pos_out, x_neg_out], dim=0) + else: + out = x_pos_out + + if self.to_gate_logits is not None: + gate_logits = self.to_gate_logits(x) # (B, T, H) + b, t, _ = out.shape + out = out.view(b, t, self.heads, self.dim_head) + gates = 2.0 * torch.sigmoid(gate_logits) # zero-init -> identity + out = out * gates.unsqueeze(-1) + out = out.view(b, t, self.heads * self.dim_head) + + return self.to_out(out) + + +class LTXVCrossAttentionPatch: + def __init__(self, context, nag_scale, nag_alpha, nag_tau, inplace=True): + self.nag_context = context + self.nag_scale = nag_scale + self.nag_alpha = nag_alpha + self.nag_tau = nag_tau + self.inplace = inplace + + def __get__(self, obj, objtype=None): + # Create bound method with stored parameters + def wrapped_attention(self_module, *args, **kwargs): + self_module.nag_context = self.nag_context + self_module.nag_scale = self.nag_scale + self_module.nag_alpha = self.nag_alpha + self_module.nag_tau = self.nag_tau + self_module.inplace = self.inplace + + return ltxv_crossattn_forward_nag(self_module, *args, **kwargs) + return types.MethodType(wrapped_attention, obj) + +class LTX2_NAG(io.ComfyNode): + + @classmethod + def define_schema(cls): + return io.Schema( + node_id="LTX2_NAG", + display_name="LTX2 NAG", + category="KJNodes/ltxv", + description="https://github.com/ChenDarYen/Normalized-Attention-Guidance", + is_experimental=True, + inputs=[ + io.Model.Input("model"), + io.Float.Input("nag_scale", default=11.0, min=0.0, max=100.0, step=0.001, tooltip="Strength of negative guidance effect"), + io.Float.Input("nag_alpha", default=0.25, min=0.0, max=1.0, step=0.001, tooltip="Mixing coefficient in that controls the balance between the normalized guided representation and the original positive representation."), + io.Float.Input("nag_tau", default=2.5, min=0.0, max=10.0, step=0.001, tooltip="Clipping threshold that controls how much the guided attention can deviate from the positive attention."), + io.Conditioning.Input("nag_cond_video", optional=True), + io.Conditioning.Input("nag_cond_audio", optional=True), + io.Boolean.Input("inplace", default=True, optional=True, tooltip="If true, modifies tensors in place to save memory. Leads to different numerical results which may change the output slightly."), + ], + outputs=[ + io.Model.Output(display_name="model"), + ], + ) + + @classmethod + def execute(cls, model, nag_scale, nag_alpha, nag_tau, nag_cond_video=None, nag_cond_audio=None, inplace=True) -> io.NodeOutput: + if nag_scale == 0: + return io.NodeOutput(model) + + device = mm.get_torch_device() + offload_device = mm.unet_offload_device() + dtype = model.model.manual_cast_dtype + if dtype is None: + dtype = model.model.diffusion_model.dtype + + model_clone = model.clone() + + diffusion_model = model_clone.get_model_object("diffusion_model") + img_dim = diffusion_model.inner_dim + audio_dim = diffusion_model.audio_inner_dim + + context_video = context_audio = None + + if nag_cond_video is not None: + context_video = nag_cond_video[0][0].to(device, dtype) + vid_split = getattr(diffusion_model, "cross_attention_dim", None) + if vid_split is not None and context_video.shape[-1] == vid_split + diffusion_model.audio_cross_attention_dim: + context_video = context_video[:, :, :vid_split] + if diffusion_model.caption_proj_before_connector and diffusion_model.caption_projection_first_linear: + diffusion_model.caption_projection.to(device) + context_video = diffusion_model.caption_projection(context_video) + diffusion_model.caption_projection.to(offload_device) + if hasattr(diffusion_model, "video_embeddings_connector"): + diffusion_model.video_embeddings_connector.to(device) + context_video = diffusion_model.video_embeddings_connector(context_video)[0] + diffusion_model.video_embeddings_connector.to(offload_device) + context_video = context_video.view(1, -1, img_dim) + for idx, block in enumerate(diffusion_model.transformer_blocks): + patched_attn2 = LTXVCrossAttentionPatch(context_video, nag_scale, nag_alpha, nag_tau, inplace=inplace).__get__(block.attn2, block.__class__) + model_clone.add_object_patch(f"diffusion_model.transformer_blocks.{idx}.attn2.forward", patched_attn2) + + if nag_cond_audio is not None and diffusion_model.audio_caption_projection is not None: + context_audio = nag_cond_audio[0][0].to(device, dtype) + vid_split = getattr(diffusion_model, "cross_attention_dim", None) + if vid_split is not None and context_audio.shape[-1] == vid_split + diffusion_model.audio_cross_attention_dim: + context_audio = context_audio[:, :, vid_split:] + if diffusion_model.caption_proj_before_connector and diffusion_model.caption_projection_first_linear: + diffusion_model.audio_caption_projection.to(device) + context_audio = diffusion_model.audio_caption_projection(context_audio) + diffusion_model.audio_caption_projection.to(offload_device) + if hasattr(diffusion_model, "audio_embeddings_connector"): + diffusion_model.audio_embeddings_connector.to(device) + context_audio = diffusion_model.audio_embeddings_connector(context_audio)[0] + diffusion_model.audio_embeddings_connector.to(offload_device) + context_audio = context_audio.view(1, -1, audio_dim) + for idx, block in enumerate(diffusion_model.transformer_blocks): + patched_audio_attn2 = LTXVCrossAttentionPatch(context_audio, nag_scale, nag_alpha, nag_tau, inplace=inplace).__get__(block.audio_attn2, block.__class__) + model_clone.add_object_patch(f"diffusion_model.transformer_blocks.{idx}.audio_attn2.forward", patched_audio_attn2) + + return io.NodeOutput(model_clone) + + +def ffn_chunked_forward(self, x): + if x.shape[1] > self.dim_threshold: + chunk_size = x.shape[1] // self.num_chunks + for i in range(self.num_chunks): + start_idx = i * chunk_size + end_idx = (i + 1) * chunk_size if i < self.num_chunks - 1 else x.shape[1] + x[:, start_idx:end_idx] = self.net(x[:, start_idx:end_idx]) + return x + else: + return self.net(x) + +class LTXVffnChunkPatch: + def __init__(self, num_chunks, dim_threshold=4096): + self.num_chunks = num_chunks + self.dim_threshold = dim_threshold + + def __get__(self, obj, objtype=None): + def wrapped_forward(self_module, *args, **kwargs): + self_module.num_chunks = self.num_chunks + self_module.dim_threshold = self.dim_threshold + return ffn_chunked_forward(self_module, *args, **kwargs) + return types.MethodType(wrapped_forward, obj) + +class LTXVChunkFeedForward(io.ComfyNode): + + @classmethod + def define_schema(cls): + return io.Schema( + node_id="LTXVChunkFeedForward", + display_name="LTXV Chunk FeedForward", + category="KJNodes/ltxv", + description="EXPERIMENTAL AND MAY CHANGE THE MODEL OUTPUT!! Chunks feedforward activations to reduce peak VRAM usage.", + is_experimental=True, + inputs=[ + io.Model.Input("model"), + io.Int.Input("chunks", default=2, min=1, max=100, step=1, tooltip="Number of chunks to split the feedforward activations into to reduce peak VRAM usage."), + io.Int.Input("dim_threshold", default=4096, min=0, max=16384, step=256, tooltip="Dimension threshold above which to apply chunking."), + ], + outputs=[ + io.Model.Output(display_name="model"), + ], + ) + + @classmethod + def execute(cls, model, chunks, dim_threshold) -> io.NodeOutput: + if chunks == 1: + return io.NodeOutput(model) + + model_clone = model.clone() + diffusion_model = model_clone.get_model_object("diffusion_model") + + for idx, block in enumerate(diffusion_model.transformer_blocks): + patched_attn2 = LTXVffnChunkPatch(chunks, dim_threshold).__get__(block.ff, block.__class__) + model_clone.add_object_patch(f"diffusion_model.transformer_blocks.{idx}.ff.forward", patched_attn2) + + return io.NodeOutput(model_clone) + + + +#borrowed VideoHelperSuite https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite/blob/main/videohelpersuite/latent_preview.py +import server +from threading import Thread +import torch.nn.functional as F +import time +import struct +from PIL import Image +from io import BytesIO +serv = server.PromptServer.instance + +class WrappedPreviewer(): + def __init__(self, latent_rgb_factors, latent_rgb_factors_bias, rate=8, taeltx=None): + self.first_preview = True + self.taeltx = taeltx + self.last_time = 0 + self.c_index = 0 + self.rate = rate + self.latent_rgb_factors = torch.tensor(latent_rgb_factors, device="cpu").transpose(0, 1) + self.latent_rgb_factors_bias = torch.tensor(latent_rgb_factors_bias, device="cpu") if latent_rgb_factors_bias is not None else None + + def decode_latent_to_preview_image(self, preview_format, x0): + if x0.ndim == 5: + #Keep batch major + x0 = x0.movedim(2,1) + x0 = x0.reshape((-1,)+x0.shape[-3:]) + num_images = x0.size(0) + new_time = time.time() + num_previews = int((new_time - self.last_time) * self.rate) + self.last_time = self.last_time + num_previews/self.rate + if num_previews > num_images: + num_previews = num_images + elif num_previews <= 0: + return None + if self.first_preview: + self.first_preview = False + serv.send_sync('VHS_latentpreview', {'length':num_images, 'rate': self.rate, 'id': serv.last_node_id}) + self.last_time = new_time + 1/self.rate + if self.c_index + num_previews > num_images: + x0 = x0.roll(-self.c_index, 0)[:num_previews] + else: + x0 = x0[self.c_index:self.c_index + num_previews] + Thread(target=self.process_previews, args=(x0, self.c_index, + num_images)).run() + self.c_index = (self.c_index + num_previews) % num_images + return None + def process_previews(self, image_tensor, ind, leng): + max_size = 512 + min_size = 256 + image_tensor = self.decode_latent_to_preview(image_tensor) + + if image_tensor.size(1) < min_size or image_tensor.size(2) < min_size: + image_tensor = F.interpolate(image_tensor.movedim(-1,0), scale_factor=4, mode='nearest').movedim(0,-1) + + if image_tensor.size(1) > max_size or image_tensor.size(2) > max_size: + image_tensor = image_tensor.movedim(-1,0) + if image_tensor.size(2) < image_tensor.size(3): + height = (max_size * image_tensor.size(2)) // image_tensor.size(3) + image_tensor = F.interpolate(image_tensor, (height,max_size), mode='nearest') + else: + width = (max_size * image_tensor.size(3)) // image_tensor.size(2) + image_tensor = F.interpolate(image_tensor, (max_size, width), mode='nearest') + image_tensor = image_tensor.movedim(0,-1) + + previews_ubyte = (image_tensor.clamp(0, 1).mul(0xFF)).to(device="cpu", dtype=torch.uint8) + + # Send VHS preview + for preview in previews_ubyte: + i = Image.fromarray(preview.numpy()) + message = BytesIO() + message.write((1).to_bytes(length=4, byteorder='big')*2) + message.write(ind.to_bytes(length=4, byteorder='big')) + message.write(struct.pack('16p', serv.last_node_id.encode('ascii'))) + i.save(message, format="JPEG", quality=95, compress_level=1) + #NOTE: send sync already uses call_soon_threadsafe + serv.send_sync(server.BinaryEventTypes.PREVIEW_IMAGE, + message.getvalue(), serv.client_id) + if self.taeltx is not None: + ind = (ind + 1) % ((leng-1) * 8 + 1) + else: + ind = (ind + 1) % leng + + def decode_latent_to_preview(self, x0): + if self.taeltx is not None: + x0 = x0.unsqueeze(0).to(dtype=self.taeltx.first_stage_model.decoder[1].weight.dtype, device=device) + x_sample = self.taeltx.first_stage_model.decode(x0)[0].permute(1, 2, 3, 0) + return x_sample + else: + self.latent_rgb_factors = self.latent_rgb_factors.to(dtype=x0.dtype, device=x0.device) + if self.latent_rgb_factors_bias is not None: + self.latent_rgb_factors_bias = self.latent_rgb_factors_bias.to(dtype=x0.dtype, device=x0.device) + latent_image = F.linear(x0.movedim(1, -1), self.latent_rgb_factors, + bias=self.latent_rgb_factors_bias) + + #low = latent_image.quantile(0.01) + #high = latent_image.quantile(0.99) + #latent_image = ((latent_image - low) / (high - low)).clamp(0, 1) + latent_image = torch.sigmoid(latent_image) + return latent_image + + +def prepare_callback(model, steps, x0_output_dict=None, shape=None, latent_upscale_model=None, vae=None, rate=8, taeltx=False, num_keyframes=0, is_23=False): + if not is_23: + latent_rgb_factors = [ + [ 0.0350, 0.0159, 0.0132], + [ 0.0025, -0.0021, -0.0003], + [ 0.0286, 0.0028, 0.0020], + [ 0.0280, -0.0114, -0.0202], + [-0.0186, 0.0073, 0.0092], + [ 0.0027, 0.0097, -0.0113], + [-0.0069, -0.0032, -0.0024], + [-0.0323, -0.0370, -0.0457], + [ 0.0174, 0.0164, 0.0106], + [-0.0097, 0.0061, 0.0035], + [-0.0130, -0.0042, -0.0012], + [-0.0102, -0.0002, -0.0091], + [-0.0025, 0.0063, 0.0161], + [ 0.0003, 0.0037, 0.0108], + [ 0.0152, 0.0082, 0.0143], + [ 0.0317, 0.0203, 0.0312], + [-0.0092, -0.0233, -0.0119], + [-0.0405, -0.0226, -0.0023], + [ 0.0376, 0.0397, 0.0352], + [ 0.0171, -0.0043, -0.0095], + [ 0.0482, 0.0341, 0.0213], + [ 0.0031, -0.0046, -0.0018], + [-0.0486, -0.0383, -0.0294], + [-0.0071, -0.0272, -0.0123], + [ 0.0320, 0.0218, 0.0289], + [ 0.0327, 0.0088, -0.0116], + [-0.0098, -0.0240, -0.0111], + [ 0.0094, -0.0116, 0.0021], + [ 0.0309, 0.0092, 0.0165], + [-0.0065, -0.0077, -0.0107], + [ 0.0179, 0.0114, 0.0038], + [-0.0018, -0.0030, -0.0026], + [-0.0002, 0.0076, -0.0029], + [-0.0131, -0.0059, -0.0170], + [ 0.0055, 0.0066, -0.0038], + [ 0.0154, 0.0063, 0.0090], + [ 0.0186, 0.0175, 0.0188], + [-0.0166, -0.0381, -0.0428], + [ 0.0121, 0.0015, -0.0153], + [ 0.0118, 0.0050, 0.0019], + [ 0.0125, 0.0259, 0.0231], + [ 0.0046, 0.0130, 0.0081], + [ 0.0271, 0.0250, 0.0250], + [-0.0054, -0.0347, -0.0326], + [-0.0438, -0.0262, -0.0228], + [-0.0191, -0.0256, -0.0173], + [-0.0205, -0.0058, 0.0042], + [ 0.0404, 0.0434, 0.0346], + [-0.0242, -0.0177, -0.0146], + [ 0.0161, 0.0223, 0.0168], + [-0.0240, -0.0320, -0.0299], + [-0.0019, 0.0043, 0.0008], + [-0.0060, -0.0133, -0.0244], + [-0.0048, -0.0225, -0.0167], + [ 0.0267, 0.0133, 0.0152], + [ 0.0222, 0.0167, 0.0028], + [ 0.0015, -0.0062, 0.0013], + [-0.0241, -0.0178, -0.0079], + [ 0.0040, -0.0081, -0.0097], + [-0.0064, 0.0133, -0.0011], + [-0.0204, -0.0231, -0.0304], + [ 0.0011, -0.0011, 0.0145], + [-0.0283, -0.0259, -0.0260], + [ 0.0038, 0.0171, -0.0029], + [ 0.0637, 0.0424, 0.0409], + [ 0.0092, 0.0163, 0.0188], + [ 0.0082, 0.0055, -0.0179], + [-0.0177, -0.0286, -0.0147], + [ 0.0171, 0.0242, 0.0398], + [-0.0129, 0.0095, -0.0071], + [-0.0154, 0.0036, 0.0128], + [-0.0081, -0.0009, 0.0118], + [-0.0067, -0.0178, -0.0230], + [-0.0022, -0.0125, -0.0003], + [-0.0032, -0.0039, -0.0022], + [-0.0005, -0.0127, -0.0131], + [-0.0143, -0.0157, -0.0165], + [-0.0262, -0.0263, -0.0270], + [ 0.0063, 0.0127, 0.0178], + [ 0.0092, 0.0133, 0.0150], + [-0.0106, -0.0068, 0.0032], + [-0.0214, -0.0022, 0.0171], + [-0.0104, -0.0266, -0.0362], + [ 0.0021, 0.0048, -0.0005], + [ 0.0345, 0.0431, 0.0402], + [-0.0275, -0.0110, -0.0195], + [ 0.0203, 0.0251, 0.0224], + [ 0.0016, -0.0037, -0.0094], + [ 0.0241, 0.0198, 0.0114], + [-0.0003, 0.0027, 0.0141], + [ 0.0012, -0.0052, -0.0084], + [ 0.0057, -0.0028, -0.0163], + [-0.0488, -0.0545, -0.0509], + [-0.0076, -0.0025, -0.0014], + [-0.0249, -0.0142, -0.0367], + [ 0.0136, 0.0041, 0.0135], + [ 0.0007, 0.0034, -0.0053], + [-0.0068, -0.0109, 0.0029], + [ 0.0006, -0.0237, -0.0094], + [-0.0149, -0.0177, -0.0131], + [-0.0105, 0.0039, 0.0216], + [ 0.0242, 0.0200, 0.0180], + [-0.0339, -0.0153, -0.0195], + [ 0.0104, 0.0151, 0.0120], + [-0.0043, 0.0089, 0.0047], + [ 0.0157, -0.0030, 0.0008], + [ 0.0126, 0.0102, -0.0040], + [ 0.0040, 0.0114, 0.0137], + [ 0.0423, 0.0473, 0.0436], + [-0.0128, -0.0066, -0.0152], + [-0.0337, -0.0087, -0.0026], + [-0.0052, 0.0235, 0.0291], + [ 0.0079, 0.0154, 0.0260], + [-0.0539, -0.0377, -0.0358], + [-0.0188, 0.0062, -0.0035], + [-0.0186, 0.0041, -0.0083], + [ 0.0045, -0.0049, 0.0053], + [ 0.0172, 0.0071, 0.0042], + [-0.0003, -0.0078, -0.0096], + [-0.0209, -0.0132, -0.0135], + [-0.0074, 0.0017, 0.0099], + [-0.0038, 0.0070, 0.0014], + [-0.0013, -0.0017, 0.0073], + [ 0.0030, 0.0105, 0.0105], + [ 0.0154, -0.0168, -0.0235], + [-0.0108, -0.0038, 0.0047], + [-0.0298, -0.0347, -0.0436], + [-0.0206, -0.0189, -0.0139] + ] + latent_rgb_factors_bias = [0.2796, 0.1101, -0.0047] + else: + latent_rgb_factors = [[0.002269406570121646, -0.02110900916159153, -0.009850316680967808], [-0.016038373112678528, -0.012462412007153034, -0.01112896017730236], [0.025274179875850677, 0.011209743097424507, 0.025426799431443214], [0.04690725728869438, 0.041542328894138336, 0.03568895906209946], [-0.02388044260442257, -0.0018645941745489836, 0.01858334057033062], [0.03720448538661003, 0.0220357533544302, 0.027937663719058037], [-0.07273884862661362, -0.09326262027025223, -0.11579664051532745], [-0.063837431371212, 0.00026216846890747547, 0.03042735904455185], [0.02903873845934868, 0.042082373052835464, 0.030649805441498756], [0.03777873516082764, 0.0322984978556633, -0.005671461578458548], [-0.0075670829974114895, -0.012113905511796474, -0.01638956367969513], [0.026524530723690987, 0.060518112033605576, 0.059549521654844284], [0.10093028098344803, 0.10073262453079224, 0.0505094900727272], [0.03725508227944374, 0.015382086858153343, 0.005786076188087463], [-0.03139607608318329, -0.01690264232456684, -0.0013519978383556008], [-0.027200624346733093, -0.02517341822385788, -0.008874989114701748], [0.024963486939668655, 0.04293748363852501, 0.05582639202475548], [-0.0364827960729599, -0.026975594460964203, -0.021950015798211098], [0.027655167505145073, 0.025136707350611687, 0.043967027217149734], [0.035822272300720215, 0.013104500249028206, 0.01113432738929987], [0.05353763327002525, 0.013606574386358261, -0.018720127642154694], [-0.013587888330221176, -0.01689346879720688, -0.027842802926898003], [0.059415675699710846, 0.03734271228313446, 0.04562298208475113], [-0.02946414425969124, -0.038338612765073776, 0.001805233070626855], [0.03921474143862724, 0.0651894062757492, 0.10681862384080887], [-0.00744189927354455, 0.007951526902616024, 0.020728807896375656], [-0.04038553684949875, -0.05215264856815338, -0.07213657349348068], [-0.004655141849070787, 0.01305423304438591, 0.026104029268026352], [0.03434251993894577, 0.018448110669851303, 0.013096392154693604], [0.0022075253073126078, -0.0011812079465016723, 0.0002940484555438161], [-0.00043441299931146204, 0.02366728149354458, 0.035889431834220886], [-0.030657343566417694, -0.024926183745265007, -0.012355240061879158], [-0.018955843523144722, -0.017360301688313484, -0.008214764297008514], [-0.01113052573055029, -0.01201171800494194, -0.002986249281093478], [0.018902746960520744, 0.01758778840303421, 0.026414571329951286], [-0.019977254793047905, -0.01605399139225483, -0.019136475399136543], [-0.00300968368537724, -0.017609693109989166, -0.013655650429427624], [0.0022096361499279737, 0.017998533323407173, 0.01815750263631344], [0.05186990648508072, 0.03285299986600876, 0.016072165220975876], [0.012626334093511105, 0.0013884707586839795, -0.012077193707227707], [-0.0037861645687371492, -0.013902144506573677, -0.01911942847073078], [-0.014163163490593433, -0.00513274222612381, -0.014303527772426605], [-0.010461323894560337, 0.009658926166594028, 0.01644069515168667], [-0.008665377274155617, 0.002501955023035407, -0.009703717194497585], [-0.03404829278588295, -0.02546044997870922, -0.014914450235664845], [0.04997691139578819, 0.06592527031898499, 0.073111392557621], [0.027394814416766167, 0.024555068463087082, 0.019957970827817917], [-0.027501430362462997, -0.01673700101673603, -0.03089248389005661], [-0.018696032464504242, -0.0020940247923135757, 0.015244065783917904], [-0.0062704551964998245, -0.0067006442695856094, -0.007532030809670687], [0.014871004968881607, 0.009914354421198368, 0.020960720255970955], [0.03662937879562378, 0.04413224756717682, 0.04220828413963318], [-0.011242181062698364, -0.013539309613406658, -0.016438307240605354], [-0.014854325912892818, 0.0038217694964259863, -0.002461288822814822], [-0.014826249331235886, 0.0009719038498587906, -0.012078499421477318], [-0.029396841302514076, -0.01432017982006073, 0.013018904253840446], [0.02755064144730568, 0.028369395062327385, 0.01640605367720127], [0.12049165368080139, 0.1395745575428009, 0.14566579461097717], [0.019721267744898796, 0.009739740751683712, 0.0023876908235251904], [-0.007320966571569443, 0.0065013207495212555, 0.01603059470653534], [0.007391378283500671, -0.0073603675700724125, -0.01770283281803131], [0.02984853833913803, 0.012391146272420883, 0.010563627816736698], [-0.013479884713888168, -0.008637298829853535, -0.013457189314067364], [0.04127075523138046, 0.03032625839114189, 0.024770958349108696], [-0.06524652987718582, -0.012209279462695122, 0.02087211236357689], [-0.1179763451218605, -0.060323599725961685, -0.07592175155878067], [-0.07122819870710373, -0.04385707899928093, -0.022124603390693665], [-0.04682473465800285, -0.022610662505030632, -0.010107148438692093], [-0.0054328180849552155, -0.010368981398642063, -0.008167334832251072], [0.029181398451328278, 0.030588403344154358, 0.028090540319681168], [0.016619984060525894, 0.004931286443024874, -0.006450849585235119], [0.01035264041274786, 0.002237115055322647, 0.0013903985964134336], [-0.04313831403851509, -0.061772625893354416, -0.08946335315704346], [0.0150345079600811, 0.007781678810715675, 0.0011013159528374672], [-0.013585779815912247, 0.008117705583572388, 0.020367907360196114], [-0.172962948679924, -0.16406646370887756, -0.1668281853199005], [0.0083833709359169, 0.0015236001927405596, -0.01731627807021141], [0.021939430385828018, 0.018004458397626877, 0.014768349006772041], [0.008083095774054527, -0.013463049195706844, -0.022061636671423912], [0.024328550323843956, 0.0128010343760252, 0.014966367743909359], [0.05850301682949066, 0.027980001643300056, 0.02225641906261444], [0.09690416604280472, 0.06929530203342438, 0.03253814950585365], [0.048208240419626236, 0.025294817984104156, 0.023508133366703987], [-0.026432134211063385, -0.040383171290159225, -0.03950457274913788], [-0.021598653867840767, -0.017070941627025604, -0.010933087207376957], [0.011645167134702206, 0.002806191798299551, 0.003779367310926318], [0.10478592664003372, 0.08954174816608429, 0.06555330753326416], [0.015151776373386383, -0.016160616651177406, -0.024905217811465263], [0.019659176468849182, 0.008487952873110771, 0.002426224760711193], [-0.05173315480351448, -0.026337839663028717, -0.02127116546034813], [0.016987523064017296, 0.006270893849432468, 0.0015798212261870503], [0.007938026450574398, -0.005250005517154932, -0.020408453419804573], [0.013017759658396244, 0.01654384844005108, 0.04163840040564537], [-0.009886542335152626, -0.026848411187529564, -0.03070281818509102], [0.01108171883970499, 0.01827266439795494, -0.007332107983529568], [-0.0285995751619339, -0.031727731227874756, -0.03370537981390953], [0.005299570970237255, 0.05678633600473404, 0.02825017087161541], [-0.055322226136922836, -0.09084303677082062, -0.12999044358730316], [0.01844066195189953, 0.031044499948620796, 0.021148500964045525], [-0.004471115302294493, 0.005830412730574608, 0.00911418441683054], [-0.04053843766450882, -0.016424428671598434, -0.0010634599020704627], [0.03858831524848938, 0.007309338077902794, -0.005618985276669264], [0.01423253770917654, -0.0055681923404335976, 3.394074519746937e-05], [0.11455483734607697, 0.14653916656970978, 0.1488018035888672], [-0.005231931805610657, -0.0033921014983206987, -0.000995257287286222], [0.01449565589427948, 0.019586293026804924, 0.04565812274813652], [-0.005179048050194979, -0.011201606132090092, -0.0008710073889233172], [-0.015361929312348366, 0.00778581015765667, -0.008238887414336205], [-0.1147838830947876, -0.09109023958444595, -0.050579313188791275], [0.09037500619888306, 0.09597006440162659, 0.10811734944581985], [0.001873677596449852, -0.01772197335958481, -0.07681205868721008], [-0.020383257418870926, -0.016072455793619156, -0.01077069528400898], [-0.060444317758083344, -0.05499502643942833, -0.06153025105595589], [-0.016717270016670227, 0.026493264362215996, 0.021835654973983765], [0.008203534409403801, 0.00418612826615572, 0.013867748901247978], [0.0789225772023201, 0.05467747151851654, 0.016568133607506752], [-0.15149451792240143, -0.1526806503534317, -0.14325062930583954], [0.00538366474211216, 0.010192245244979858, -0.00449327751994133], [-0.004906965419650078, -0.005569908302277327, -0.02096559666097164], [0.024530155584216118, 0.010962833650410175, 0.0034586559049785137], [0.03551010414958, 0.017310436815023422, 0.007064413744956255], [0.11111932247877121, 0.09825586527585983, 0.08827318251132965], [-0.051722846925258636, -0.047595202922821045, -0.03763044252991676], [-0.02975175902247429, -0.02153967320919037, -0.021425534039735794], [-0.03462936729192734, -0.025198571383953094, -0.017322326079010963], [-0.016921017318964005, -0.012419789098203182, -0.0154880927875638], [-0.08035065978765488, -0.08451078832149506, -0.09623870998620987], [-0.03870908170938492, -0.04211008921265602, -0.04383759945631027]] + latent_rgb_factors_bias = [-0.6957847476005554, -0.7276281118392944, -0.7405748963356018] + + preview_format = "JPEG" + if preview_format not in ["JPEG", "PNG"]: + preview_format = "JPEG" + + previewer = WrappedPreviewer(latent_rgb_factors, latent_rgb_factors_bias, rate=rate, taeltx=vae if taeltx else None) + + pbar = comfy.utils.ProgressBar(steps) + def callback(step, x0, x, total_steps): + if x0 is not None and shape is not None: + cut = math.prod(shape[1:]) + x0 = x0[:, :, :cut].reshape([x0.shape[0]] + list(shape)[1:]) + + if num_keyframes > 0: + x0 = x0[:, :, :-num_keyframes] + + if latent_upscale_model is not None: + x0 = vae.first_stage_model.per_channel_statistics.un_normalize(x0) + x0 = latent_upscale_model(x0.to(torch.bfloat16)) + x0 = vae.first_stage_model.per_channel_statistics.normalize(x0) + + preview_bytes = None + if previewer: + preview_bytes = previewer.decode_latent_to_preview_image(preview_format, x0) + pbar.update_absolute(step + 1, total_steps, preview_bytes) + return callback + +class OuterSampleCallbackWrapper: + def __init__(self, latent_upscale_model=None, vae=None, preview_rate=8, taeltx=False): + self.latent_upscale_model = latent_upscale_model + self.vae = vae + self.preview_rate = preview_rate + self.taeltx = taeltx + self.x0_output = {} + + def __call__(self, executor, noise, latent_image, sampler, sigmas, denoise_mask, callback, disable_pbar, seed, latent_shapes): + guider = executor.class_obj + diffusion_model = guider.model_patcher.model.diffusion_model + is_23 = not diffusion_model.caption_projection_first_linear + + original_callback = callback + if self.latent_upscale_model is not None: + self.latent_upscale_model.to(device) + if self.vae is not None and self.taeltx: + self.vae.first_stage_model.to(device) + + num_keyframes = 0 + if 'positive' in guider.conds and len(guider.conds['positive']) > 0: + keyframe_idxs = guider.conds['positive'][0].get('keyframe_idxs') + if keyframe_idxs is not None: + num_keyframes = len(torch.unique(keyframe_idxs[0, 0, :, 0])) + + new_callback = prepare_callback(guider.model_patcher, len(sigmas) -1, shape=latent_shapes[0] if len(latent_shapes) > 1 else None, + x0_output_dict=self.x0_output, latent_upscale_model=self.latent_upscale_model, vae=self.vae, rate=self.preview_rate, taeltx=self.taeltx, num_keyframes=num_keyframes, is_23=is_23) + # Wrapper that calls both callbacks + def combined_callback(step, x0, x, total_steps): + new_callback(step, x0, x, total_steps) + if original_callback is not None: + original_callback(step, x0, x, total_steps) + out = executor(noise, latent_image, sampler, sigmas, denoise_mask, combined_callback, disable_pbar, seed, latent_shapes=latent_shapes) + if self.latent_upscale_model is not None: + self.latent_upscale_model.to(mm.unet_offload_device()) + return out + +class LTX2SamplingPreviewOverride(io.ComfyNode): + @classmethod + def define_schema(cls) -> io.Schema: + return io.Schema( + node_id="LTX2SamplingPreviewOverride", + display_name="LTX2 Sampling Preview Override", + description="Overrides the LTX2 preview sampling preview function, temporary measure until previews are in comfy core", + category="KJNodes/ltxv", + is_experimental=True, + inputs=[ + io.Model.Input("model", tooltip="The model to add preview override to."), + io.Int.Input("preview_rate", default=8, min=1, max=60, step=1, tooltip="Preview frame rate."), + io.LatentUpscaleModel.Input("latent_upscale_model", optional=True, tooltip="Optional upscale model to use for higher resolution previews."), + io.Vae.Input("vae", optional=True, tooltip="VAE model to use normalizing the latents for the upscale model."), + ], + outputs=[ + io.Model.Output(tooltip="The model with Sampling Preview Override."), + ], + ) + + @classmethod + def execute(cls, model, preview_rate, latent_upscale_model=None, vae=None) -> io.NodeOutput: + model = model.clone() + taeltx = False + if vae is not None: + if vae.first_stage_model.__class__.__name__ == "TAEHV": + taeltx = True + latent_upscale_model=None + model.add_wrapper_with_key(comfy.patcher_extension.WrappersMP.OUTER_SAMPLE, "sampling_preview", OuterSampleCallbackWrapper(latent_upscale_model, vae, preview_rate, taeltx)) + return io.NodeOutput(model) + + +# based on https://github.com/Lightricks/ComfyUI-LTXVideo/blob/cd5d371518afb07d6b3641be8012f644f25269fc/easy_samplers.py#L916 +class OuterSampleAudioNormalizationWrapper: + def __init__(self, audio_normalization_factors): + self.audio_normalization_factors = audio_normalization_factors + + def __call__(self, executor, noise, latent_image, sampler, sigmas, denoise_mask, callback, disable_pbar, seed, latent_shapes): + guider = executor.class_obj + ltxav = guider.model_patcher.model.diffusion_model + + x0_output = {} + self.total_steps = sigmas.shape[-1] - 1 + pbar = comfy.utils.ProgressBar(self.total_steps) + self.full_step = 0 + + previewer = latent_preview.get_previewer(guider.model_patcher.load_device, guider.model_patcher.model.latent_format) + def custom_callback(step, x0, x, total_steps): + if x0_output is not None: + x0_output["x0"] = x0 + + preview_bytes = None + if previewer: + preview_bytes = previewer.decode_latent_to_preview_image("JPEG", x0) + self.full_step += 1 + pbar.update_absolute(self.full_step, self.total_steps, preview_bytes) + + callback = custom_callback + + audio_normalization_factors = self.audio_normalization_factors.strip().split(",") + audio_normalization_factors = [float(factor) for factor in audio_normalization_factors] + + # Extend normalization factors to match the length of sigmas + sigmas_len = self.total_steps + if len(audio_normalization_factors) < sigmas_len and len(audio_normalization_factors) > 0: + audio_normalization_factors.extend([audio_normalization_factors[-1]] * (sigmas_len - len(audio_normalization_factors))) + + # Calculate indices where both normalization factors are not 1.0 + sampling_split_indices = [i + 1 for i, a in enumerate(audio_normalization_factors) if a != 1.0] + + # Split sigmas according to sampling_split_indices + def split_by_indices(arr, indices): + """ + Splits arr into chunks according to indices (split points). + Indices are treated as starting a new chunk at each index in the list. + """ + if not indices: + return [arr] + split_points = sorted(set(indices)) + chunks = [] + prev = 0 + for idx in split_points: + if prev < idx: + chunks.append(arr[prev : idx + 1]) + prev = idx + if prev < len(arr): + chunks.append(arr[prev:]) + return chunks + + sigmas_chunks = split_by_indices(sigmas, sampling_split_indices) + + i = 0 + for sigmas_chunk in sigmas_chunks: + i += len(sigmas_chunk) - 1 + latent_image = executor(noise, latent_image, sampler, sigmas_chunk, denoise_mask, callback, disable_pbar, seed, latent_shapes=latent_shapes) + + if "x0" in x0_output: + latent_image = guider.model_patcher.model.process_latent_out(x0_output["x0"]) + + if i - 1 < len(audio_normalization_factors): + vx, ax = ltxav.separate_audio_and_video_latents(comfy.utils.unpack_latents(latent_image, latent_shapes), None) + if denoise_mask is not None: + audio_mask = ltxav.separate_audio_and_video_latents(comfy.utils.unpack_latents(denoise_mask, latent_shapes), None)[1] + ax = ax * audio_mask * audio_normalization_factors[i - 1] + ax * (1 - audio_mask) + else: + ax = ax * audio_normalization_factors[i - 1] + latent_image = comfy.utils.pack_latents(ltxav.recombine_audio_and_video_latents(vx, ax))[0] + + print("After %d steps, the audio latent was normalized by %f" % (i, audio_normalization_factors[i - 1])) + + return latent_image + + +class LTX2AudioLatentNormalizingSampling(io.ComfyNode): + @classmethod + def define_schema(cls) -> io.Schema: + return io.Schema( + node_id="LTX2AudioLatentNormalizingSampling", + display_name="LTX2 Audio Latent Normalizing Sampling", + description="Improves LTX2 generated audio quality by normalizing audio latents at specified sampling steps.", + category="KJNodes/ltxv", + is_experimental=True, + inputs=[ + io.Model.Input("model", tooltip="The model to add preview override to."), + io.String.Input("audio_normalization_factors", default="1,1,0.25,1,1,0.25,1,1", tooltip="Comma-separated list of audio normalization factors to apply at each sampling step. For example, '1,1,0.25,1,1,0.25,1,1' will apply a factor of 0.25 at the 3rd and 6th steps."), + ], + outputs=[ + io.Model.Output(tooltip="The model with Audio Latent Normalizing Sampling."), + ], + ) + + @classmethod + def execute(cls, model, audio_normalization_factors) -> io.NodeOutput: + model = model.clone() + model.add_wrapper_with_key(comfy.patcher_extension.WrappersMP.OUTER_SAMPLE, "ltx2_audio_normalization", OuterSampleAudioNormalizationWrapper(audio_normalization_factors)) + return io.NodeOutput(model) + + +class LTXVImgToVideoInplaceKJ(io.ComfyNode): + @classmethod + def define_schema(cls): + options = [] + for num_images in range(1, 21): # 1 to 20 images + image_inputs = [] + for i in range(1, num_images + 1): + image_inputs.extend([ + io.Image.Input(f"image_{i}", optional=True, tooltip=f"Image {i} to insert into the video latent."), + io.Int.Input( + f"index_{i}", + default=0, + min=-9999, + max=9999, + step=1, + tooltip=f"Frame index for image {i} (in pixel space).", + optional=True, + ), + io.Float.Input(f"strength_{i}", default=1.0, min=0.0, max=1.0, step=0.01, tooltip=f"Strength for image {i}."), + ]) + options.append(io.DynamicCombo.Option( + key=str(num_images), + inputs=image_inputs + )) + + return io.Schema( + node_id="LTXVImgToVideoInplaceKJ", + category="KJNodes/ltxv", + description="Replaces video latent frames with the encoded input images, uses DynamicCombo which requires ComfyUI 0.8.1 and frontend 1.33.4 or later.", + inputs=[ + io.Vae.Input("vae", tooltip="Video VAE used to encode the images"), + io.Latent.Input("latent", tooltip="Video latent to insert images into"), + io.DynamicCombo.Input( + "num_images", + options=options, + display_name="Number of Images", + tooltip="Select how many images to insert", + ), + ], + outputs=[ + io.Latent.Output(display_name="latent", tooltip="The video latent with the images inserted and latent noise mask updated."), + ], + ) + + @classmethod + def execute(cls, vae, latent, num_images) -> io.NodeOutput: + + samples = latent["samples"].clone() + scale_factors = vae.downscale_index_formula + _, height_scale_factor, width_scale_factor = scale_factors + + batch, _, latent_frames, latent_height, latent_width = samples.shape + width = latent_width * width_scale_factor + height = latent_height * height_scale_factor + + # Get existing noise mask if present, otherwise create new one + if "noise_mask" in latent: + conditioning_latent_frames_mask = latent["noise_mask"].clone() + else: + conditioning_latent_frames_mask = torch.ones( + (batch, 1, latent_frames, 1, 1), + dtype=torch.float32, + device=samples.device, + ) + + # num_images is a dict containing the inputs from the selected option + # e.g., {'image_1': tensor, 'frame_idx_1': 0, 'strength_1': 1.0, 'image_2': tensor, 'frame_idx_2': 20, 'strength_2': 0.8, ...} + + image_keys = sorted([k for k in num_images.keys() if k.startswith('image_')]) + + for img_key in image_keys: + i = img_key.split('_')[1] + + image = num_images[f"image_{i}"] + if image is None: + continue + index = num_images.get(f"index_{i}") + if index is None: + continue + strength = num_images[f"strength_{i}"] + + if image.shape[1] != height or image.shape[2] != width: + pixels = comfy.utils.common_upscale(image.movedim(-1, 1), width, height, "bilinear", "center").movedim(1, -1) + else: + pixels = image + encode_pixels = pixels[:, :, :, :3] + t = vae.encode(encode_pixels) + + # Convert pixel frame index to latent index + time_scale_factor = scale_factors[0] + + # Handle negative indexing in pixel space + pixel_frame_count = (latent_frames - 1) * time_scale_factor + 1 + if index < 0: + index = pixel_frame_count + index + + # Convert to latent index + latent_idx = index // time_scale_factor + + # Clamp to valid range + latent_idx = max(0, min(latent_idx, latent_frames - 1)) + + # Calculate end index, ensuring we don't exceed latent_frames + end_index = min(latent_idx + t.shape[2], latent_frames) + + # Replace samples at the specified index range + samples[:, :, latent_idx:end_index] = t[:, :, :end_index - latent_idx] + + # Update mask at the specified index range + conditioning_latent_frames_mask[:, :, latent_idx:end_index] = 1.0 - strength + + return io.NodeOutput({"samples": samples, "noise_mask": conditioning_latent_frames_mask}) + +try: + import triton + import triton.language as tl + HAS_TRITON = True +except ImportError: + HAS_TRITON = False + +if HAS_TRITON: + @triton.jit + def _rms_norm_scale_shift_kernel( + X_ptr, Out_ptr, Scale_ptr, Shift_ptr, + N, scale_n_rows, # scale_n_rows: actual rows in scale/shift (handles broadcast) + eps: tl.constexpr, + BLOCK_N: tl.constexpr, + IS_BF16: tl.constexpr, + HAS_BROADCAST: tl.constexpr, # True when scale_n_rows < n_rows + ): + row = tl.program_id(0) + cols = tl.arange(0, BLOCK_N) + mask = cols < N + off = row * N + cols + + x = tl.load(X_ptr + off, mask=mask, other=0.0).to(tl.float32) + + mean_sq = tl.sum(x * x, axis=0) / N + rrms = tl.math.rsqrt(mean_sq + eps) + x_norm = x * rrms + + # Fast path: no broadcast, scale row == x row + if HAS_BROADCAST: + scale_row = row % scale_n_rows + scale_off = scale_row * N + cols + else: + scale_off = off + scale = tl.load(Scale_ptr + scale_off, mask=mask, other=0.0).to(tl.float32) + shift = tl.load(Shift_ptr + scale_off, mask=mask, other=0.0).to(tl.float32) + out = x_norm * (1.0 + scale) + shift + + if IS_BF16: + tl.store(Out_ptr + off, out.to(tl.bfloat16), mask=mask) + else: + tl.store(Out_ptr + off, out.to(tl.float16), mask=mask) + + @triton.jit + def _rope_qk_split_kernel( + Q_ptr, K_ptr, Cos_ptr, Sin_ptr, + H, T, D, # D = dim_head (full, even) + TH, # T * H, precomputed to avoid runtime multiply in index decomp + # q/k layout: [B, T, H*D] contiguous → q[b,t,h*D + d] + # cos/sin layout: [B, H, T, D//2] contiguous + IS_BF16: tl.constexpr, + BLOCK_HD: tl.constexpr, # >= D//2 + ): + # grid: (B*H*T,) + bht = tl.program_id(0) + t = bht % T + h = (bht // T) % H + b = bht // TH + + D_half = D // 2 + cols = tl.arange(0, BLOCK_HD) + mask = cols < D_half + + # offset into q/k tensor: [B, T, H*D] + qk_base = (b * T + t) * (H * D) + h * D + # offset into cos/sin: [B, H, T, D//2] + cs_base = (b * H * T + h * T + t) * D_half + + # load both halves of q and k + q_x = tl.load(Q_ptr + qk_base + cols, mask=mask, other=0.0).to(tl.float32) + q_y = tl.load(Q_ptr + qk_base + D_half + cols, mask=mask, other=0.0).to(tl.float32) + k_x = tl.load(K_ptr + qk_base + cols, mask=mask, other=0.0).to(tl.float32) + k_y = tl.load(K_ptr + qk_base + D_half + cols, mask=mask, other=0.0).to(tl.float32) + cos = tl.load(Cos_ptr + cs_base + cols, mask=mask, other=1.0).to(tl.float32) + sin = tl.load(Sin_ptr + cs_base + cols, mask=mask, other=0.0).to(tl.float32) + + # split RoPE: out_x = x*cos - y*sin, out_y = y*cos + x*sin + q_ox = q_x * cos - q_y * sin + q_oy = q_y * cos + q_x * sin + k_ox = k_x * cos - k_y * sin + k_oy = k_y * cos + k_x * sin + + if IS_BF16: + tl.store(Q_ptr + qk_base + cols, q_ox.to(tl.bfloat16), mask=mask) + tl.store(Q_ptr + qk_base + D_half + cols, q_oy.to(tl.bfloat16), mask=mask) + tl.store(K_ptr + qk_base + cols, k_ox.to(tl.bfloat16), mask=mask) + tl.store(K_ptr + qk_base + D_half + cols, k_oy.to(tl.bfloat16), mask=mask) + else: + tl.store(Q_ptr + qk_base + cols, q_ox.to(tl.float16), mask=mask) + tl.store(Q_ptr + qk_base + D_half + cols, q_oy.to(tl.float16), mask=mask) + tl.store(K_ptr + qk_base + cols, k_ox.to(tl.float16), mask=mask) + tl.store(K_ptr + qk_base + D_half + cols, k_oy.to(tl.float16), mask=mask) + + @triton.jit + def _rms_norm_dual_scale_shift_kernel( + X_ptr, Out1_ptr, Out2_ptr, + Scale1_ptr, Shift1_ptr, Scale2_ptr, Shift2_ptr, + N, scale_n_rows, + eps: tl.constexpr, + BLOCK_N: tl.constexpr, + IS_BF16: tl.constexpr, + HAS_BROADCAST: tl.constexpr, + ): + """Compute rms_norm(x) once, write two differently-scaled outputs.""" + row = tl.program_id(0) + cols = tl.arange(0, BLOCK_N) + mask = cols < N + off = row * N + cols + + x = tl.load(X_ptr + off, mask=mask, other=0.0).to(tl.float32) + mean_sq = tl.sum(x * x, axis=0) / N + x_norm = x * tl.math.rsqrt(mean_sq + eps) + + if HAS_BROADCAST: + scale_row = row % scale_n_rows + s_off = scale_row * N + cols + else: + s_off = off + + scale1 = tl.load(Scale1_ptr + s_off, mask=mask, other=0.0).to(tl.float32) + shift1 = tl.load(Shift1_ptr + s_off, mask=mask, other=0.0).to(tl.float32) + scale2 = tl.load(Scale2_ptr + s_off, mask=mask, other=0.0).to(tl.float32) + shift2 = tl.load(Shift2_ptr + s_off, mask=mask, other=0.0).to(tl.float32) + + out1 = x_norm * (1.0 + scale1) + shift1 + out2 = x_norm * (1.0 + scale2) + shift2 + + if IS_BF16: + tl.store(Out1_ptr + off, out1.to(tl.bfloat16), mask=mask) + tl.store(Out2_ptr + off, out2.to(tl.bfloat16), mask=mask) + else: + tl.store(Out1_ptr + off, out1.to(tl.float16), mask=mask) + tl.store(Out2_ptr + off, out2.to(tl.float16), mask=mask) + + +def fused_norm_scale_shift(x, scale, shift, eps=1e-6, use_triton=True): + if use_triton and HAS_TRITON and x.is_cuda: + orig_shape = x.shape + hidden = x.shape[-1] + x_2d = x.contiguous().reshape(-1, hidden) + n_rows = x_2d.shape[0] + # Flatten scale/shift without expanding — kernel handles broadcast via modulo + scale_2d = scale.contiguous().reshape(-1, hidden) + shift_2d = shift.contiguous().reshape(-1, hidden) + scale_n_rows = scale_2d.shape[0] + out = torch.empty_like(x_2d) + BLOCK_N = triton.next_power_of_2(hidden) + num_warps = min(max(BLOCK_N // 256, 1), 16) + _rms_norm_scale_shift_kernel[(n_rows,)]( + x_2d, out, scale_2d, shift_2d, + hidden, scale_n_rows, + eps=eps, BLOCK_N=BLOCK_N, + IS_BF16=(x.dtype == torch.bfloat16), + HAS_BROADCAST=(scale_n_rows < n_rows), + num_warps=num_warps, + ) + return out.view(orig_shape) + else: + return comfy.ldm.common_dit.rms_norm(x, eps=eps) * (1 + scale) + shift + + +def fused_rope_qk(q, k, freqs_cis, use_triton=True): + """Apply split RoPE to q and k in one fused kernel pass. + q, k: [B, T, H*D] contiguous + freqs_cis: (cos, sin, split_pe) where cos/sin: [B, H, T, D//2] + Falls back to original apply_rotary_emb if preconditions not met. + """ + + if not (use_triton and HAS_TRITON and q.is_cuda): + return _apply_rope(q, freqs_cis), _apply_rope(k, freqs_cis) + + cos, sin = freqs_cis[0], freqs_cis[1] + split_pe = freqs_cis[2] if len(freqs_cis) > 2 else False + + if not split_pe or cos.ndim != 4 or q.ndim != 3: + return _apply_rope(q, freqs_cis), _apply_rope(k, freqs_cis) + + B_cos, H, T_cos, D_half = cos.shape + D = D_half * 2 + if q.shape != (B_cos, T_cos, H * D) or k.shape != (B_cos, T_cos, H * D): + return _apply_rope(q, freqs_cis), _apply_rope(k, freqs_cis) + + q = q.contiguous() + k = k.contiguous() + cos_c = cos.contiguous() + sin_c = sin.contiguous() + + BLOCK_HD = triton.next_power_of_2(D_half) + num_warps = min(max(BLOCK_HD // 32, 1), 8) + _rope_qk_split_kernel[(B_cos * H * T_cos,)]( + q, k, cos_c, sin_c, + H, T_cos, D, + T_cos * H, + IS_BF16=(q.dtype == torch.bfloat16), + BLOCK_HD=BLOCK_HD, + num_warps=num_warps, + ) + return q, k + + +def fused_norm_dual_scale_shift(x, scale1, shift1, scale2, shift2, eps=1e-6, use_triton=True): + """RMS-norm x once, return two scaled outputs: (x_norm*(1+s1)+b1, x_norm*(1+s2)+b2).""" + if use_triton and HAS_TRITON and x.is_cuda: + orig_shape = x.shape + hidden = x.shape[-1] + x_2d = x.contiguous().reshape(-1, hidden) + n_rows = x_2d.shape[0] + scale1_2d = scale1.contiguous().reshape(-1, hidden) + shift1_2d = shift1.contiguous().reshape(-1, hidden) + scale2_2d = scale2.contiguous().reshape(-1, hidden) + shift2_2d = shift2.contiguous().reshape(-1, hidden) + scale_n_rows = scale1_2d.shape[0] + out1 = torch.empty_like(x_2d) + out2 = torch.empty_like(x_2d) + BLOCK_N = triton.next_power_of_2(hidden) + num_warps = min(max(BLOCK_N // 256, 1), 16) + _rms_norm_dual_scale_shift_kernel[(n_rows,)]( + x_2d, out1, out2, + scale1_2d, shift1_2d, scale2_2d, shift2_2d, + hidden, scale_n_rows, + eps=eps, BLOCK_N=BLOCK_N, + IS_BF16=(x.dtype == torch.bfloat16), + HAS_BROADCAST=(scale_n_rows < n_rows), + num_warps=num_warps, + ) + return out1.view(orig_shape), out2.view(orig_shape) + else: + x_norm = comfy.ldm.common_dit.rms_norm(x, eps=eps) + return x_norm * (1 + scale1) + shift1, x_norm * (1 + scale2) + shift2 + + +def _apply_text_cross_attention_patched( + self, x, context, attn, scale_shift_table, prompt_scale_shift_table, + timestep, prompt_timestep, attention_mask, transformer_options, +): + """Drop-in replacement for _apply_text_cross_attention with fused norm+scale+shift. + Patched onto the block instance so self._apply_text_cross_attention resolves here.""" + if self.cross_attention_adaln: + shift_q, scale_q, gate = self.get_ada_values(scale_shift_table, x.shape[0], timestep, slice(6, 9)) + batch_size = x.shape[0] + shift_kv, scale_kv = ( + prompt_scale_shift_table[None, None].to(device=x.device, dtype=x.dtype) + + prompt_timestep.reshape(batch_size, prompt_timestep.shape[1], 2, -1) + ).unbind(dim=2) + attn_input = fused_norm_scale_shift(x, scale_q, shift_q, + use_triton=getattr(self, 'use_triton_kernels', True)) + del shift_q, scale_q + encoder_hidden_states = context * (1 + scale_kv) + shift_kv + del scale_kv, shift_kv + return attn(attn_input, context=encoder_hidden_states, + mask=attention_mask, transformer_options=transformer_options) * gate + return attn( + comfy.ldm.common_dit.rms_norm(x), context=context, + mask=attention_mask, transformer_options=transformer_options, + ) + + +def ltx2_forward( + self, x: Tuple[torch.Tensor, torch.Tensor], v_context=None, a_context=None, attention_mask=None, v_timestep=None, a_timestep=None, + v_pe=None, a_pe=None, v_cross_pe=None, a_cross_pe=None, v_cross_scale_shift_timestep=None, a_cross_scale_shift_timestep=None, + v_cross_gate_timestep=None, a_cross_gate_timestep=None, transformer_options=None, self_attention_mask=None, + v_prompt_timestep=None, a_prompt_timestep=None, **kwargs + ) -> Tuple[torch.Tensor, torch.Tensor]: + run_vx = transformer_options.get("run_vx", True) + run_ax = transformer_options.get("run_ax", True) + use_triton = getattr(self, 'use_triton_kernels', True) + video_scale = getattr(self, 'video_scale', 1.0) + audio_scale = getattr(self, 'audio_scale', 1.0) + audio_to_video_scale = getattr(self, 'audio_to_video_scale', 1.0) + video_to_audio_scale = getattr(self, 'video_to_audio_scale', 1.0) + + vx, ax = x + run_ax = run_ax and ax.numel() > 0 and audio_scale != 0.0 + run_a2v = run_vx and transformer_options.get("a2v_cross_attn", True) and ax.numel() > 0 and audio_to_video_scale != 0.0 + run_v2a = run_ax and transformer_options.get("v2a_cross_attn", True) and video_to_audio_scale != 0.0 + + if run_vx: + # video self-attention + vshift_msa, vscale_msa = (self.get_ada_values(self.scale_shift_table, vx.shape[0], v_timestep, slice(0, 2))) + norm_vx = fused_norm_scale_shift(vx, vscale_msa, vshift_msa, use_triton=use_triton) + del vshift_msa, vscale_msa + # inline attn1 only when triton is active (needed to intercept q/k for fused RoPE) + if use_triton: + _a1 = self.attn1 + q = _a1.to_q(norm_vx) + k = _a1.to_k(norm_vx) + v = _a1.to_v(norm_vx) + + q = _a1.q_norm(q) + k = _a1.k_norm(k) + + if v_pe is not None: + q, k = fused_rope_qk(q, k, v_pe, use_triton=True) + + if self_attention_mask is None: + _sa_out = _comfy_attn.optimized_attention(q, k, v, _a1.heads, attn_precision=_a1.attn_precision, transformer_options=transformer_options) + else: + _sa_out = _comfy_attn.optimized_attention_masked(q, k, v, _a1.heads, self_attention_mask, attn_precision=_a1.attn_precision, transformer_options=transformer_options) + del q, k, v + if _a1.to_gate_logits is not None: + _gate = _a1.to_gate_logits(norm_vx) + _b, _t, _ = _sa_out.shape + _sa_out = _sa_out.view(_b, _t, _a1.heads, _a1.dim_head) + _sa_out = (_sa_out * (2.0 * torch.sigmoid(_gate)).unsqueeze(-1)).view(_b, _t, _a1.heads * _a1.dim_head) + del _gate + + attn1_out = _a1.to_out(_sa_out) + del _sa_out, norm_vx + else: + attn1_out = self.attn1(norm_vx, pe=v_pe, transformer_options=transformer_options) + del norm_vx + # video cross-attention + vgate_msa = self.get_ada_values(self.scale_shift_table, vx.shape[0], v_timestep, slice(2, 3))[0] + vx.addcmul_(attn1_out, vgate_msa, value=video_scale) + del vgate_msa, attn1_out + vx.add_(self._apply_text_cross_attention( + vx, v_context, self.attn2, self.scale_shift_table, + getattr(self, 'prompt_scale_shift_table', None), + v_timestep, v_prompt_timestep, attention_mask, transformer_options,), + alpha=video_scale + ) + # audio + if run_ax: + # audio self-attention + ashift_msa, ascale_msa = (self.get_ada_values(self.audio_scale_shift_table, ax.shape[0], a_timestep, slice(0, 2))) + norm_ax = fused_norm_scale_shift(ax, ascale_msa, ashift_msa, use_triton=use_triton) + del ashift_msa, ascale_msa + attn1_out = self.audio_attn1(norm_ax, pe=a_pe, transformer_options=transformer_options) + del norm_ax + # audio cross-attention + agate_msa = self.get_ada_values(self.audio_scale_shift_table, ax.shape[0], a_timestep, slice(2, 3))[0] + ax.addcmul_(attn1_out, agate_msa, value=audio_scale) + del agate_msa, attn1_out + ax.add_(self._apply_text_cross_attention( + ax, a_context, self.audio_attn2, self.audio_scale_shift_table, + getattr(self, 'audio_prompt_scale_shift_table', None), + a_timestep, a_prompt_timestep, attention_mask, transformer_options,), + alpha=audio_scale + ) + + # video - audio cross attention. + if run_a2v or run_v2a: + if run_a2v and run_v2a: + # Fetch all 4 scale/shift values per table at once (avoids two get_ada_values calls each) + # and compute rms_norm once per tensor via dual kernel. + v_ca_vals = self.get_ada_values(self.scale_shift_table_a2v_ca_video[:4, :], vx.shape[0], v_cross_scale_shift_timestep) + a_ca_vals = self.get_ada_values(self.scale_shift_table_a2v_ca_audio[:4, :], ax.shape[0], a_cross_scale_shift_timestep) + vx_a2v, vx_v2a = fused_norm_dual_scale_shift(vx, v_ca_vals[0], v_ca_vals[1], v_ca_vals[2], v_ca_vals[3], use_triton=use_triton) + ax_a2v, ax_v2a = fused_norm_dual_scale_shift(ax, a_ca_vals[0], a_ca_vals[1], a_ca_vals[2], a_ca_vals[3], use_triton=use_triton) + del v_ca_vals, a_ca_vals + elif run_a2v: + sv, bv = self.get_ada_values(self.scale_shift_table_a2v_ca_video[:4, :], vx.shape[0], v_cross_scale_shift_timestep)[:2] + sa, ba = self.get_ada_values(self.scale_shift_table_a2v_ca_audio[:4, :], ax.shape[0], a_cross_scale_shift_timestep)[:2] + vx_a2v = fused_norm_scale_shift(vx, sv, bv, use_triton=use_triton) + ax_a2v = fused_norm_scale_shift(ax, sa, ba, use_triton=use_triton) + del sv, bv, sa, ba + else: # only v2a + sv, bv = self.get_ada_values(self.scale_shift_table_a2v_ca_video[:4, :], vx.shape[0], v_cross_scale_shift_timestep)[2:4] + sa, ba = self.get_ada_values(self.scale_shift_table_a2v_ca_audio[:4, :], ax.shape[0], a_cross_scale_shift_timestep)[2:4] + vx_v2a = fused_norm_scale_shift(vx, sv, bv, use_triton=use_triton) + ax_v2a = fused_norm_scale_shift(ax, sa, ba, use_triton=use_triton) + del sv, bv, sa, ba + + # audio to video cross attention + if run_a2v: + a2v_out = self.audio_to_video_attn(vx_a2v, context=ax_a2v, pe=v_cross_pe, k_pe=a_cross_pe, transformer_options=transformer_options) + del vx_a2v, ax_a2v + gate_out_a2v = self.get_ada_values(self.scale_shift_table_a2v_ca_video[4:, :], vx.shape[0], v_cross_gate_timestep)[0] + vx.addcmul_(a2v_out, gate_out_a2v, value=audio_to_video_scale) + del gate_out_a2v, a2v_out + + # video to audio cross attention + if run_v2a: + v2a_out = self.video_to_audio_attn(ax_v2a, context=vx_v2a, pe=a_cross_pe, k_pe=v_cross_pe, transformer_options=transformer_options) + del ax_v2a, vx_v2a + gate_out_v2a = self.get_ada_values(self.scale_shift_table_a2v_ca_audio[4:, :], ax.shape[0], a_cross_gate_timestep)[0] + ax.addcmul_(v2a_out, gate_out_v2a, value=video_to_audio_scale) + del gate_out_v2a, v2a_out + + # video feedforward + if run_vx: + vshift_mlp, vscale_mlp = self.get_ada_values(self.scale_shift_table, vx.shape[0], v_timestep, slice(3, 5)) + vx_scaled = fused_norm_scale_shift(vx, vscale_mlp, vshift_mlp, use_triton=use_triton) + del vshift_mlp, vscale_mlp + + ff_out = self.ff(vx_scaled) + del vx_scaled + + vgate_mlp = self.get_ada_values(self.scale_shift_table, vx.shape[0], v_timestep, slice(5, 6))[0] + vx.addcmul_(ff_out, vgate_mlp, value=video_scale) + del vgate_mlp, ff_out + + # audio feedforward + if run_ax: + ashift_mlp, ascale_mlp = self.get_ada_values(self.audio_scale_shift_table, ax.shape[0], a_timestep, slice(3, 5)) + ax_scaled = fused_norm_scale_shift(ax, ascale_mlp, ashift_mlp, use_triton=use_triton) + del ashift_mlp, ascale_mlp + + ff_out = self.audio_ff(ax_scaled) + del ax_scaled + + agate_mlp = self.get_ada_values(self.audio_scale_shift_table, ax.shape[0], a_timestep, slice(5, 6))[0] + ax.addcmul_(ff_out, agate_mlp, value=audio_scale) + del agate_mlp, ff_out + + return vx, ax + +class LTX2ForwardPatch: + def __init__(self, video, audio, audio_to_video, video_to_audio, use_triton=True): + self.video_scale = video + self.audio_scale = audio + self.video_to_audio_scale = video_to_audio + self.audio_to_video_scale = audio_to_video + self.use_triton_kernels = use_triton + def __get__(self, obj, objtype=None): + def wrapped_forward(self_module, *args, **kwargs): + self_module.video_scale = self.video_scale + self_module.audio_scale = self.audio_scale + self_module.video_to_audio_scale = self.video_to_audio_scale + self_module.audio_to_video_scale = self.audio_to_video_scale + self_module.use_triton_kernels = self.use_triton_kernels + self_module._apply_text_cross_attention = types.MethodType( + _apply_text_cross_attention_patched, self_module) + return ltx2_forward(self_module, *args, **kwargs) + return types.MethodType(wrapped_forward, obj) + +class LTX2AttentionTunerPatch(io.ComfyNode): + + @classmethod + def define_schema(cls): + return io.Schema( + node_id="LTX2AttentionTunerPatch", + display_name="LTX2 Attention Tuner Patch", + category="KJNodes/ltxv", + description="EXPERIMENTAL! Custom LTX2 forward pass with attention scaling factors per modality, also reduces peak VRAM usage.", + is_experimental=True, + inputs=[ + io.Model.Input("model"), + io.String.Input("blocks", default="", tooltip="Comma separated list of transformer block indices to apply the patch to. Leave empty to apply to all blocks."), + io.Float.Input("video_scale", default=1.0, min=0.0, max=100, step=0.01, tooltip="Scaling factor for video attention."), + io.Float.Input("audio_scale", default=1.0, min=0.0, max=100, step=0.01, tooltip="Scaling factor for audio attention."), + io.Float.Input("audio_to_video_scale", default=1.0, min=0.0, max=100, step=0.01, tooltip="Scaling factor for video attention."), + io.Float.Input("video_to_audio_scale", default=1.0, min=0.0, max=100, step=0.01, tooltip="Scaling factor for audio attention."), + io.Boolean.Input("triton_kernels", default=True, tooltip="Use Triton fused kernels for norm+scale+shift and rope application operations, can be very slightly faster."), + ], + outputs=[ + io.Model.Output(display_name="model"), + ], + ) + + @classmethod + def execute(cls, model, blocks, video_scale, audio_scale, audio_to_video_scale, video_to_audio_scale, triton_kernels) -> io.NodeOutput: + model_clone = model.clone() + diffusion_model = model_clone.get_model_object("diffusion_model") + + # Parse selected block indices + if blocks.strip() == "": + selected_blocks = set(range(len(diffusion_model.transformer_blocks))) + else: + selected_blocks = set(int(idx) for idx in blocks.strip().split(",")) + + logging.info(f"Applying LTX2 Attention Tuner Patch with custom scales to blocks: {sorted(selected_blocks)}, triton_kernels={triton_kernels}") + + # Apply patch to all blocks, but use 1.0 scales for non-selected blocks + for idx in range(len(diffusion_model.transformer_blocks)): + block = diffusion_model.transformer_blocks[idx] + if idx in selected_blocks: + patched_forward = LTX2ForwardPatch(video_scale, audio_scale, audio_to_video_scale, video_to_audio_scale, use_triton=triton_kernels).__get__(block, block.__class__) + else: + patched_forward = LTX2ForwardPatch(1.0, 1.0, 1.0, 1.0, use_triton=triton_kernels).__get__(block, block.__class__) + model_clone.add_object_patch(f"diffusion_model.transformer_blocks.{idx}.forward", patched_forward) + + return io.NodeOutput(model_clone) + +class LTX2MemoryEfficientSageAttentionPatch(io.ComfyNode): + + @classmethod + def define_schema(cls): + return io.Schema( + node_id="LTX2MemoryEfficientSageAttentionPatch", + display_name="LTX2 Mem Eff Sage Attention Patch", + category="KJNodes/ltxv", + description="EXPERIMENTAL! Activates custom sageattention to reduce peak VRAM usage, overrides the attention mode. Requires latest sageattention version.", + is_experimental=True, + inputs=[ + io.Model.Input("model"), + io.Boolean.Input("triton_kernels", default=True, tooltip="Use Triton fused RoPE kernel on the self-attention Q/K. Requires Triton."), + ], + outputs=[ + io.Model.Output(display_name="model"), + ], + ) + + @classmethod + def execute(cls, model, triton_kernels) -> io.NodeOutput: + if _cuda_archs is None: + raise RuntimeError("sageattention is not new enough version or could not determine CUDA architecture, cannot apply LTX2 Memory Efficient Sage Attention Patch.") + model_clone = model.clone() + diffusion_model = model_clone.get_model_object("diffusion_model") + + logging.info(f"Applying LTX2 Memory Efficient Sage Attention Patch to all transformer blocks, triton_kernels={triton_kernels}") + + for idx, block in enumerate(diffusion_model.transformer_blocks): + block.attn1.use_triton_kernels = triton_kernels + model_clone.add_object_patch(f"diffusion_model.transformer_blocks.{idx}.attn1.forward", ltx2_sageattn_forward.__get__(block.attn1, block.attn1.__class__)) + + return io.NodeOutput(model_clone) + + +def get_cuda_version(): + try: + version = torch.version.cuda + if version is not None: + major, minor = version.split('.') + return int(major), int(minor) + else: + return 0, 0 + except Exception: + return 0, 0 + +sageplus_sm89_available = False +_cuda_archs = None +try: + from sageattention.core import per_thread_int8_triton, per_warp_int8_cuda, per_block_int8_triton, per_channel_fp8, get_cuda_arch_versions, attn_false + _cuda_archs = get_cuda_arch_versions() +except: + pass +try: + from sageattention.core import _qattn_sm89 + cuda_version = get_cuda_version() + sageplus_sm89_available = hasattr(_qattn_sm89, 'qk_int8_sv_f8_accum_f16_fuse_v_scale_attn_inst_buf') and cuda_version >= (12, 8) +except ImportError: + try: + from sageattention.core import sm89_compile as _qattn_sm89 + except ImportError: + _qattn_sm89 = None +try: + from sageattention.core import _qattn_sm80 +except ImportError: + try: + from sageattention.core import sm80_compile as _qattn_sm80 + except ImportError: + _qattn_sm80 = None +try: + from sageattention.core import _qattn_sm90 +except ImportError: + try: + from sageattention.core import sm90_compile as _qattn_sm90 + except ImportError: + _qattn_sm90 = None + +from comfy.ldm.lightricks.model import apply_rotary_emb + + +def ltx2_sageattn_forward(self, x, context=None, mask=None, pe=None, k_pe=None, transformer_options={}): + dtype = x.dtype + context = x if context is None else context + + # query + q = self.to_q(x) + q = self.q_norm(q) + # key + k = self.to_k(context) + k = self.k_norm(k) + # apply RoPE — fuse q+k into one kernel when both share the same pe + if pe is not None: + use_triton = getattr(self, 'use_triton_kernels', False) + if k_pe is None: + q, k = fused_rope_qk(q, k, pe, use_triton=use_triton) + else: + q = apply_rotary_emb(q, pe) + k = apply_rotary_emb(k, k_pe) + # value + v = self.to_v(context) + + # Reshape from [batch, seq_len, total_dim] to [batch, seq_len, num_heads, head_dim] + batch_size, seq_len, _ = q.shape + head_dim_og = self.dim_head + + q = q.view(batch_size, seq_len, self.heads, head_dim_og) + k = k.view(batch_size, k.shape[1], self.heads, head_dim_og) + v = v.view(batch_size, v.shape[1], self.heads, head_dim_og) + + tensor_layout="NHD" + _tensor_layout = 0 # NHD + _is_caual = 0 + _qk_quant_gran = 3 + _return_lse = 0 + sm_scale = head_dim_og**-0.5 + quant_v_scale_max = 448.0 + + if _cuda_archs[0] in {"sm80", "sm86"}: + q_int8, q_scale, k_int8, k_scale = per_thread_int8_triton(q, k, km=k.mean(dim=1, keepdim=True), tensor_layout=tensor_layout, BLKQ=128, WARPQ=32, BLKK=64, WARPK=64) + del q, k + o = torch.empty(q_int8.size(), dtype=dtype, device=q_int8.device) + v_fp16 = v.to(torch.float16).contiguous() + del v + _qattn_sm80.qk_int8_sv_f16_accum_f32_attn(q_int8, k_int8, v_fp16, o, q_scale, k_scale, _tensor_layout, _is_caual, _qk_quant_gran, sm_scale, _return_lse) + elif _cuda_archs[0] == "sm75": + q_int8, q_scale, k_int8, k_scale = per_block_int8_triton(q, k, km=k.mean(dim=1, keepdim=True), sm_scale=sm_scale, tensor_layout=tensor_layout) + del q, k + o, _ = attn_false(q_int8, k_int8, v, q_scale, k_scale, tensor_layout=tensor_layout, output_dtype=dtype, attn_mask=None, return_lse=False) + del v + elif _cuda_archs[0] == "sm89": + if not sageplus_sm89_available: + pv_accum_dtype = "fp32+fp32" + else: + pv_accum_dtype = "fp32+fp16" + quant_v_scale_max = 2.25 + q_int8, q_scale, k_int8, k_scale = per_thread_int8_triton(q, k, km=k.mean(dim=1, keepdim=True), tensor_layout=tensor_layout, BLKQ=128, WARPQ=32, BLKK=64, WARPK=64) + del q, k + v_fp8, v_scale, _ = per_channel_fp8(v, tensor_layout=tensor_layout, scale_max=quant_v_scale_max, smooth_v=False) + del v + o = torch.empty(q_int8.size(), dtype=dtype, device=q_int8.device) + if pv_accum_dtype == "fp32+fp16": + _qattn_sm89.qk_int8_sv_f8_accum_f16_fuse_v_scale_attn_inst_buf(q_int8, k_int8, v_fp8, o, q_scale, k_scale, v_scale, _tensor_layout, _is_caual, _qk_quant_gran, sm_scale, _return_lse) + elif pv_accum_dtype == "fp32+fp32": + _qattn_sm89.qk_int8_sv_f8_accum_f32_fuse_v_scale_attn_inst_buf(q_int8, k_int8, v_fp8, o, q_scale, k_scale, v_scale, _tensor_layout, _is_caual, _qk_quant_gran, sm_scale, _return_lse) + del v_fp8, v_scale + elif _cuda_archs[0] == "sm90": + q_int8, q_scale, k_int8, k_scale = per_thread_int8_triton(q, k, km=k.mean(dim=1, keepdim=True), tensor_layout=tensor_layout, BLKQ=64, WARPQ=16, BLKK=128, WARPK=128) + del q, k, + v_fp8, v_scale, _ = per_channel_fp8(v, tensor_layout=tensor_layout, smooth_v=False) + del v + o = torch.empty(q_int8.size(), dtype=dtype, device=q_int8.device) + _qattn_sm90.qk_int8_sv_f8_accum_f32_fuse_v_scale_attn_inst_buf(q_int8, k_int8, v_fp8, o, q_scale, k_scale, v_scale, _tensor_layout, _is_caual, _qk_quant_gran, sm_scale, _return_lse) + del v_fp8, v_scale + elif _cuda_archs[0] == "sm120": + if not sageplus_sm89_available: + pv_accum_dtype = "fp32" + else: + pv_accum_dtype = "fp32+fp16" + quant_v_scale_max = 2.25 + _qk_quant_gran = 2 # per warp + q_int8, q_scale, k_int8, k_scale = per_warp_int8_cuda(q, k, km=k.mean(dim=1, keepdim=True), tensor_layout=tensor_layout, BLKQ=128, WARPQ=32, BLKK=64) + del q, k + v_fp8, v_scale, _ = per_channel_fp8(v, tensor_layout=tensor_layout, scale_max=quant_v_scale_max, smooth_v=False) + del v + o = torch.empty(q_int8.size(), dtype=dtype, device=q_int8.device) + if pv_accum_dtype == "fp32": + _qattn_sm89.qk_int8_sv_f8_accum_f32_fuse_v_scale_attn(q_int8, k_int8, v_fp8, o, q_scale, k_scale, v_scale, _tensor_layout, _is_caual, _qk_quant_gran, sm_scale, _return_lse) + elif pv_accum_dtype == "fp32+fp16": + _qattn_sm89.qk_int8_sv_f8_accum_f16_fuse_v_scale_attn_inst_buf(q_int8, k_int8, v_fp8, o, q_scale, k_scale, v_scale, _tensor_layout, _is_caual, _qk_quant_gran, sm_scale, _return_lse) + del v_fp8, v_scale + + del q_int8, q_scale, k_int8, k_scale + + o = o.view(batch_size, seq_len, -1) + + if self.to_gate_logits is not None: + gate_logits = self.to_gate_logits(x) # (B, T, H) + b, t, _ = o.shape + o = o.view(b, t, self.heads, self.dim_head) + gates = 2.0 * torch.sigmoid(gate_logits) # zero-init -> identity + o = o * gates.unsqueeze(-1) + o = o.view(b, t, self.heads * self.dim_head) + + return self.to_out(o) + + +import folder_paths + +class LTX2LoraLoaderAdvanced(io.ComfyNode): + + @classmethod + def define_schema(cls): + return io.Schema( + node_id="LTX2LoraLoaderAdvanced", + display_name="LTX2 LoRA Loader Advanced", + category="KJNodes/ltxv", + description="Advanced LoRA loader with per-block strength control for LTX2 models", + is_experimental=True, + inputs=[ + io.Combo.Input("lora_name", options=folder_paths.get_filename_list("loras"), tooltip="The name of the LoRA."), + io.Model.Input("model", tooltip="The diffusion model the LoRA will be applied to."), + io.Float.Input("strength_model", default=1.0, min=-100.0, max=100.0, step=0.01, tooltip="How strongly to modify the diffusion model. This value can be negative."), + io.String.Input("opt_lora_path", optional=True, force_input=True,tooltip="Absolute path of the LoRA."), + io.Custom("SELECTEDDITBLOCKS").Input("blocks", optional=True, tooltip="Selected DiT blocks configuration"), + io.Float.Input("video", default=1.0, min=0.0, max=1.0, step=0.01, tooltip="Strength for video attention layers."), + io.Float.Input("video_to_audio", default=1.0, min=0.0, max=1.0, step=0.01, tooltip="Strength for video to audio cross-attention layers."), + io.Float.Input("audio", default=1.0, min=0.0, max=1.0, step=0.01, tooltip="Strength for audio attention layers."), + io.Float.Input("audio_to_video", default=1.0, min=0.0, max=1.0, step=0.01, tooltip="Strength for audio to video cross-attention layers."), + io.Float.Input("other", default=1.0, min=0.0, max=1.0, step=0.01, tooltip="Strength for layers not caught by other layer filters."), + ], + outputs=[ + io.Model.Output(display_name="model", tooltip="The modified diffusion model."), + io.String.Output(display_name="rank", tooltip="Possible rank of the LoRA."), + io.String.Output(display_name="loaded_keys_info", tooltip="List of loaded keys and their alpha values."), + ], + ) + + @classmethod + def execute(cls, model, lora_name, strength_model, video, video_to_audio, audio, audio_to_video, other, opt_lora_path=None, blocks=None) -> io.NodeOutput: + from comfy.utils import load_torch_file + import comfy.lora + + if opt_lora_path: + lora_path = opt_lora_path + else: + lora_path = folder_paths.get_full_path("loras", lora_name) + + lora = load_torch_file(lora_path, safe_load=True) + + # Find the first key that ends with "weight" + rank = "unknown" + weight_key = next((key for key in lora.keys() if key.endswith('weight')), None) + # Print the shape of the value corresponding to the key + if weight_key: + print(f"Shape of the first 'weight' key ({weight_key}): {lora[weight_key].shape}") + rank = str(lora[weight_key].shape[0]) + else: + print("No key ending with 'weight' found.") + rank = "Couldn't find rank" + + key_map = {} + if model is not None: + key_map = comfy.lora.model_lora_keys_unet(model.model, key_map) + + loaded = comfy.lora.load_lora(lora, key_map) + + keys_to_delete = [] + + # First apply blocks filtering if provided + if blocks is not None: + for block in blocks: + for key in list(loaded.keys()): + match = False + if isinstance(key, str) and block in key: + match = True + elif isinstance(key, tuple): + for k in key: + if block in k: + match = True + break + + if match: + ratio = blocks[block] + if ratio == 0: + keys_to_delete.append(key) + else: + # Only modify LoRA adapters, skip diff tuples + value = loaded[key] + if hasattr(value, 'weights'): + weights_list = list(value.weights) + weights_list[2] = ratio + loaded[key].weights = tuple(weights_list) + + # Then apply layer-based attention strength filtering (takes priority) + for key in list(loaded.keys()): + if key in keys_to_delete: + continue + + key_str = key if isinstance(key, str) else (key[0] if isinstance(key, tuple) else str(key)) + + # Determine the strength multiplier based on layer name + # Check more specific patterns first + strength_multiplier = None + + # Video to audio cross-attention (check first - most specific) + if "video_to_audio_attn" in key_str: + strength_multiplier = video_to_audio + # Audio to video cross-attention + elif "audio_to_video_attn" in key_str: + strength_multiplier = audio_to_video + # Audio layers + elif "audio_attn" in key_str or "audio_ff.net" in key_str: + strength_multiplier = audio + # Video layers (check last - most general) + elif "attn" in key_str or "ff.net" in key_str: + strength_multiplier = video + # Everything else not caught by above filters + else: + strength_multiplier = other + + # Apply strength or mark for deletion + if strength_multiplier is not None: + if strength_multiplier == 0: + keys_to_delete.append(key) + elif strength_multiplier != 1.0: + value = loaded[key] + if hasattr(value, 'weights'): + weights_list = list(value.weights) + # Handle case where alpha (weights[2]) might be None + current_alpha = weights_list[2] if weights_list[2] is not None else 1.0 + weights_list[2] = current_alpha * strength_multiplier + loaded[key].weights = tuple(weights_list) + + for key in keys_to_delete: + if key in loaded: + del loaded[key] + + # Build list of loaded keys and their alphas + loaded_keys_list = [] + for key, value in loaded.items(): + if hasattr(value, 'weights'): + key_str = key if isinstance(key, str) else str(key) + alpha = value.weights[2] if value.weights[2] is not None else "None" + loaded_keys_list.append(f"{key_str}: alpha={alpha}") + else: + key_str = key if isinstance(key, str) else str(key) + loaded_keys_list.append(f"{key_str}: type={type(value).__name__}") + + if model is not None: + new_modelpatcher = model.clone() + k = new_modelpatcher.add_patches(loaded, strength_model) + + # Add not loaded keys to the info + k = set(k) + not_loaded = [] + for x in loaded: + if x not in k: + key_str = x if isinstance(x, str) else str(x) + not_loaded.append(f"NOT LOADED: {key_str}") + + if not_loaded: + loaded_keys_list.extend(not_loaded) + + loaded_keys_info = "\n".join(loaded_keys_list) + + return io.NodeOutput(new_modelpatcher, rank, loaded_keys_info) diff --git a/.disabled/comfyui-kjnodes@nightly/nodes/mask_nodes.py b/.disabled/comfyui-kjnodes@nightly/nodes/mask_nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..c2784118422302f7d3654505d3916e64913d6ed2 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/nodes/mask_nodes.py @@ -0,0 +1,1689 @@ +import torch +import torch.nn.functional as F +from torchvision.transforms import functional as TF +from PIL import Image, ImageDraw, ImageFilter, ImageFont +import scipy.ndimage +import numpy as np +from contextlib import nullcontext +import os +from tqdm import tqdm +import logging + +from comfy import model_management +from comfy.utils import ProgressBar +from comfy.utils import common_upscale +from nodes import MAX_RESOLUTION + +import folder_paths + +from ..utility.utility import tensor2pil, pil2tensor + +script_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +main_device = model_management.get_torch_device() +offload_device = model_management.unet_offload_device() + +class BatchCLIPSeg: + + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(s): + + return {"required": + { + "images": ("IMAGE",), + "text": ("STRING", {"multiline": False}), + "threshold": ("FLOAT", {"default": 0.5,"min": 0.0, "max": 10.0, "step": 0.001}), + "binary_mask": ("BOOLEAN", {"default": True}), + "combine_mask": ("BOOLEAN", {"default": False}), + "use_cuda": ("BOOLEAN", {"default": True}), + }, + "optional": + { + "blur_sigma": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 100.0, "step": 0.1}), + "opt_model": ("CLIPSEGMODEL", ), + "prev_mask": ("MASK", {"default": None}), + "image_bg_level": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}), + "invert": ("BOOLEAN", {"default": False}), + } + } + + CATEGORY = "KJNodes/masking" + RETURN_TYPES = ("MASK", "IMAGE", ) + RETURN_NAMES = ("Mask", "Image", ) + FUNCTION = "segment_image" + DESCRIPTION = """ +Segments an image or batch of images using CLIPSeg. +""" + + def segment_image(self, images, text, threshold, binary_mask, combine_mask, use_cuda, blur_sigma=0.0, opt_model=None, prev_mask=None, invert= False, image_bg_level=0.5): + from transformers import CLIPSegProcessor, CLIPSegForImageSegmentation + import torchvision.transforms as transforms + offload_device = model_management.unet_offload_device() + device = model_management.get_torch_device() + if not use_cuda: + device = torch.device("cpu") + dtype = model_management.unet_dtype() + + if opt_model is None: + checkpoint_path = os.path.join(folder_paths.models_dir,'clip_seg', 'clipseg-rd64-refined-fp16') + if not hasattr(self, "model"): + try: + if not os.path.exists(checkpoint_path): + from huggingface_hub import snapshot_download + snapshot_download(repo_id="Kijai/clipseg-rd64-refined-fp16", local_dir=checkpoint_path, local_dir_use_symlinks=False) + self.model = CLIPSegForImageSegmentation.from_pretrained(checkpoint_path) + except: + checkpoint_path = "CIDAS/clipseg-rd64-refined" + self.model = CLIPSegForImageSegmentation.from_pretrained(checkpoint_path) + processor = CLIPSegProcessor.from_pretrained(checkpoint_path) + + else: + self.model = opt_model['model'] + processor = opt_model['processor'] + + self.model.to(dtype).to(device) + + B, H, W, C = images.shape + images = images.to(device) + + autocast_condition = (dtype != torch.float32) and not model_management.is_device_mps(device) + with torch.autocast(model_management.get_autocast_device(device), dtype=dtype) if autocast_condition else nullcontext(): + + PIL_images = [Image.fromarray(np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)) for image in images ] + prompt = [text] * len(images) + input_prc = processor(text=prompt, images=PIL_images, return_tensors="pt") + + for key in input_prc: + input_prc[key] = input_prc[key].to(device) + outputs = self.model(**input_prc) + + mask_tensor = torch.sigmoid(outputs.logits) + mask_tensor = (mask_tensor - mask_tensor.min()) / (mask_tensor.max() - mask_tensor.min()) + mask_tensor = torch.where(mask_tensor > (threshold), mask_tensor, torch.tensor(0, dtype=torch.float)) + + if len(mask_tensor.shape) == 2: + mask_tensor = mask_tensor.unsqueeze(0) + mask_tensor = F.interpolate(mask_tensor.unsqueeze(1), size=(H, W), mode='nearest') + mask_tensor = mask_tensor.squeeze(1) + + self.model.to(offload_device) + + if binary_mask: + mask_tensor = (mask_tensor > 0).float() + if blur_sigma > 0: + kernel_size = int(6 * int(blur_sigma) + 1) + blur = transforms.GaussianBlur(kernel_size=(kernel_size, kernel_size), sigma=(blur_sigma, blur_sigma)) + mask_tensor = blur(mask_tensor) + + if combine_mask: + mask_tensor = torch.max(mask_tensor, dim=0)[0] + mask_tensor = mask_tensor.unsqueeze(0).repeat(len(images),1,1) + + del outputs + model_management.soft_empty_cache() + + if prev_mask is not None: + if prev_mask.shape != mask_tensor.shape: + prev_mask = F.interpolate(prev_mask.unsqueeze(1), size=(H, W), mode='nearest') + mask_tensor = mask_tensor + prev_mask.to(device) + torch.clamp(mask_tensor, min=0.0, max=1.0) + + if invert: + mask_tensor = 1 - mask_tensor + + image_tensor = images * mask_tensor.unsqueeze(-1) + (1 - mask_tensor.unsqueeze(-1)) * image_bg_level + image_tensor = torch.clamp(image_tensor, min=0.0, max=1.0).cpu().float() + + mask_tensor = mask_tensor.cpu().float() + + return mask_tensor, image_tensor, + +class DownloadAndLoadCLIPSeg: + + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(s): + + return {"required": + { + "model": ( + [ 'Kijai/clipseg-rd64-refined-fp16', + 'CIDAS/clipseg-rd64-refined', + ], + ), + }, + } + + CATEGORY = "KJNodes/masking" + RETURN_TYPES = ("CLIPSEGMODEL",) + RETURN_NAMES = ("clipseg_model",) + FUNCTION = "segment_image" + DESCRIPTION = """ +Downloads and loads CLIPSeg model with huggingface_hub, +to ComfyUI/models/clip_seg +""" + + def segment_image(self, model): + from transformers import CLIPSegProcessor, CLIPSegForImageSegmentation + checkpoint_path = os.path.join(folder_paths.models_dir,'clip_seg', os.path.basename(model)) + if not hasattr(self, "model"): + if not os.path.exists(checkpoint_path): + from huggingface_hub import snapshot_download + snapshot_download(repo_id=model, local_dir=checkpoint_path, local_dir_use_symlinks=False) + self.model = CLIPSegForImageSegmentation.from_pretrained(checkpoint_path) + + processor = CLIPSegProcessor.from_pretrained(checkpoint_path) + + clipseg_model = {} + clipseg_model['model'] = self.model + clipseg_model['processor'] = processor + + return clipseg_model, + +class CreateTextMask: + + RETURN_TYPES = ("IMAGE", "MASK",) + FUNCTION = "createtextmask" + CATEGORY = "KJNodes/text" + DESCRIPTION = """ +Creates a text image and mask. +Looks for fonts from this folder: +ComfyUI/custom_nodes/ComfyUI-KJNodes/fonts + +If start_rotation and/or end_rotation are different values, +creates animation between them. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "invert": ("BOOLEAN", {"default": False}), + "frames": ("INT", {"default": 1,"min": 1, "max": 4096, "step": 1}), + "text_x": ("INT", {"default": 0,"min": 0, "max": 4096, "step": 1}), + "text_y": ("INT", {"default": 0,"min": 0, "max": 4096, "step": 1}), + "font_size": ("INT", {"default": 32,"min": 8, "max": 4096, "step": 1}), + "font_color": ("STRING", {"default": "white"}), + "text": ("STRING", {"default": "HELLO!", "multiline": True}), + "font": (folder_paths.get_filename_list("kjnodes_fonts"), ), + "width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "start_rotation": ("INT", {"default": 0,"min": 0, "max": 359, "step": 1}), + "end_rotation": ("INT", {"default": 0,"min": -359, "max": 359, "step": 1}), + }, + } + + def createtextmask(self, frames, width, height, invert, text_x, text_y, text, font_size, font_color, font, start_rotation, end_rotation): + # Define the number of images in the batch + batch_size = frames + out = [] + masks = [] + rotation = start_rotation + if start_rotation != end_rotation: + rotation_increment = (end_rotation - start_rotation) / (batch_size - 1) + + font_path = folder_paths.get_full_path("kjnodes_fonts", font) + # Generate the text + for i in range(batch_size): + image = Image.new("RGB", (width, height), "black") + draw = ImageDraw.Draw(image) + font = ImageFont.truetype(font_path, font_size) + + # Split the text into lines and wrap words to fit width + text_lines = text.split('\n') + lines = [] + for text_line in text_lines: + if text_line.strip() == "": + # Preserve empty lines for multiple newlines + lines.append("") + continue + words = text_line.split() + current_line = [] + for word in words: + if current_line: + test_line = " ".join(current_line + [word]) + else: + test_line = word + try: + test_line_width = font.getbbox(test_line)[2] + except Exception: + test_line_width = font.getsize(test_line)[0] + if test_line_width <= width - 2 * text_x: + current_line.append(word) + else: + lines.append(" ".join(current_line)) + current_line = [word] + if current_line: + lines.append(" ".join(current_line)) + + # Draw each line of text separately + y_offset = text_y + for line in lines: + text_width = font.getlength(line) + text_height = font_size + text_center_x = text_x + text_width / 2 + text_center_y = y_offset + text_height / 2 + try: + draw.text((text_x, y_offset), line, font=font, fill=font_color, features=['-liga']) + except: + draw.text((text_x, y_offset), line, font=font, fill=font_color) + y_offset += text_height # Move to the next line + + if start_rotation != end_rotation: + image = image.rotate(rotation, center=(text_center_x, text_center_y)) + rotation += rotation_increment + + image = np.array(image).astype(np.float32) / 255.0 + image = torch.from_numpy(image)[None,] + mask = image[:, :, :, 0] + masks.append(mask) + out.append(image) + + if invert: + return (1.0 - torch.cat(out, dim=0), 1.0 - torch.cat(masks, dim=0),) + return (torch.cat(out, dim=0),torch.cat(masks, dim=0),) + +class ColorToMask: + + RETURN_TYPES = ("MASK",) + FUNCTION = "clip" + CATEGORY = "KJNodes/masking" + DESCRIPTION = """ +Converts chosen RGB value to a mask. +With batch inputs, the **per_batch** +controls the number of images processed at once. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "images": ("IMAGE",), + "invert": ("BOOLEAN", {"default": False}), + "red": ("INT", {"default": 0,"min": 0, "max": 255, "step": 1}), + "green": ("INT", {"default": 0,"min": 0, "max": 255, "step": 1}), + "blue": ("INT", {"default": 0,"min": 0, "max": 255, "step": 1}), + "threshold": ("INT", {"default": 10,"min": 0, "max": 255, "step": 1}), + "per_batch": ("INT", {"default": 16, "min": 1, "max": 4096, "step": 1}), + }, + } + + def clip(self, images, red, green, blue, threshold, invert, per_batch): + + color = torch.tensor([red, green, blue], dtype=torch.uint8) + black = torch.tensor([0, 0, 0], dtype=torch.uint8) + white = torch.tensor([255, 255, 255], dtype=torch.uint8) + + if invert: + black, white = white, black + + steps = images.shape[0] + pbar = ProgressBar(steps) + tensors_out = [] + + for start_idx in range(0, images.shape[0], per_batch): + + # Calculate color distances + color_distances = torch.norm(images[start_idx:start_idx+per_batch] * 255 - color, dim=-1) + + # Create a mask based on the threshold + mask = color_distances <= threshold + + # Apply the mask to create new images + mask_out = torch.where(mask.unsqueeze(-1), white, black).float() + mask_out = mask_out.mean(dim=-1) + + tensors_out.append(mask_out.cpu()) + batch_count = mask_out.shape[0] + pbar.update(batch_count) + + tensors_out = torch.cat(tensors_out, dim=0) + tensors_out = torch.clamp(tensors_out, min=0.0, max=1.0) + return tensors_out, + +class CreateFluidMask: + + RETURN_TYPES = ("IMAGE", "MASK") + FUNCTION = "createfluidmask" + CATEGORY = "KJNodes/masking/generate" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "invert": ("BOOLEAN", {"default": False}), + "frames": ("INT", {"default": 1,"min": 1, "max": 4096, "step": 1}), + "width": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}), + "height": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}), + "inflow_count": ("INT", {"default": 3,"min": 0, "max": 255, "step": 1}), + "inflow_velocity": ("INT", {"default": 1,"min": 0, "max": 255, "step": 1}), + "inflow_radius": ("INT", {"default": 8,"min": 0, "max": 255, "step": 1}), + "inflow_padding": ("INT", {"default": 50,"min": 0, "max": 255, "step": 1}), + "inflow_duration": ("INT", {"default": 60,"min": 0, "max": 255, "step": 1}), + }, + } + #using code from https://github.com/GregTJ/stable-fluids + def createfluidmask(self, frames, width, height, invert, inflow_count, inflow_velocity, inflow_radius, inflow_padding, inflow_duration): + from ..utility.fluid import Fluid + try: + from scipy.special import erf + except: + from scipy.spatial import erf + out = [] + masks = [] + RESOLUTION = width, height + DURATION = frames + + INFLOW_PADDING = inflow_padding + INFLOW_DURATION = inflow_duration + INFLOW_RADIUS = inflow_radius + INFLOW_VELOCITY = inflow_velocity + INFLOW_COUNT = inflow_count + + logging.info('Generating fluid solver, this may take some time.') + fluid = Fluid(RESOLUTION, 'dye') + + center = np.floor_divide(RESOLUTION, 2) + r = np.min(center) - INFLOW_PADDING + + points = np.linspace(-np.pi, np.pi, INFLOW_COUNT, endpoint=False) + points = tuple(np.array((np.cos(p), np.sin(p))) for p in points) + normals = tuple(-p for p in points) + points = tuple(r * p + center for p in points) + + inflow_velocity = np.zeros_like(fluid.velocity) + inflow_dye = np.zeros(fluid.shape) + for p, n in zip(points, normals): + mask = np.linalg.norm(fluid.indices - p[:, None, None], axis=0) <= INFLOW_RADIUS + inflow_velocity[:, mask] += n[:, None] * INFLOW_VELOCITY + inflow_dye[mask] = 1 + + + for f in range(DURATION): + logging.info(f'Computing frame {f + 1} of {DURATION}.') + if f <= INFLOW_DURATION: + fluid.velocity += inflow_velocity + fluid.dye += inflow_dye + + curl = fluid.step()[1] + # Using the error function to make the contrast a bit higher. + # Any other sigmoid function e.g. smoothstep would work. + curl = (erf(curl * 2) + 1) / 4 + + color = np.dstack((curl, np.ones(fluid.shape), fluid.dye)) + color = (np.clip(color, 0, 1) * 255).astype('uint8') + image = np.array(color).astype(np.float32) / 255.0 + image = torch.from_numpy(image)[None,] + mask = image[:, :, :, 0] + masks.append(mask) + out.append(image) + + if invert: + return (1.0 - torch.cat(out, dim=0),1.0 - torch.cat(masks, dim=0),) + return (torch.cat(out, dim=0),torch.cat(masks, dim=0),) + +class CreateAudioMask: + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "createaudiomask" + CATEGORY = "KJNodes/deprecated" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "invert": ("BOOLEAN", {"default": False}), + "frames": ("INT", {"default": 16,"min": 1, "max": 255, "step": 1}), + "scale": ("FLOAT", {"default": 0.5,"min": 0.0, "max": 2.0, "step": 0.01}), + "audio_path": ("STRING", {"default": "audio.wav"}), + "width": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}), + "height": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}), + }, + } + + def createaudiomask(self, frames, width, height, invert, audio_path, scale): + try: + import librosa + except ImportError: + raise Exception("Can not import librosa. Install it with 'pip install librosa'") + batch_size = frames + out = [] + masks = [] + if audio_path == "audio.wav": #I don't know why relative path won't work otherwise... + audio_path = os.path.join(script_directory, audio_path) + audio, sr = librosa.load(audio_path) + spectrogram = np.abs(librosa.stft(audio)) + + for i in range(batch_size): + image = Image.new("RGB", (width, height), "black") + draw = ImageDraw.Draw(image) + frame = spectrogram[:, i] + circle_radius = int(height * np.mean(frame)) + circle_radius *= scale + circle_center = (width // 2, height // 2) # Calculate the center of the image + + draw.ellipse([(circle_center[0] - circle_radius, circle_center[1] - circle_radius), + (circle_center[0] + circle_radius, circle_center[1] + circle_radius)], + fill='white') + + image = np.array(image).astype(np.float32) / 255.0 + image = torch.from_numpy(image)[None,] + mask = image[:, :, :, 0] + masks.append(mask) + out.append(image) + + if invert: + return (1.0 - torch.cat(out, dim=0),) + return (torch.cat(out, dim=0),torch.cat(masks, dim=0),) + +class CreateGradientMask: + + RETURN_TYPES = ("MASK",) + FUNCTION = "createmask" + CATEGORY = "KJNodes/masking/generate" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "invert": ("BOOLEAN", {"default": False}), + "frames": ("INT", {"default": 0,"min": 0, "max": 255, "step": 1}), + "width": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}), + "height": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}), + }, + } + def createmask(self, frames, width, height, invert): + # Define the number of images in the batch + batch_size = frames + out = [] + # Create an empty array to store the image batch + image_batch = np.zeros((batch_size, height, width), dtype=np.float32) + # Generate the black to white gradient for each image + for i in range(batch_size): + gradient = np.linspace(1.0, 0.0, width, dtype=np.float32) + time = i / frames # Calculate the time variable + offset_gradient = gradient - time # Offset the gradient values based on time + image_batch[i] = offset_gradient.reshape(1, -1) + output = torch.from_numpy(image_batch) + mask = output + out.append(mask) + if invert: + return (1.0 - torch.cat(out, dim=0),) + return (torch.cat(out, dim=0),) + +class CreateFadeMask: + + RETURN_TYPES = ("MASK",) + FUNCTION = "createfademask" + CATEGORY = "KJNodes/deprecated" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "invert": ("BOOLEAN", {"default": False}), + "frames": ("INT", {"default": 2,"min": 2, "max": 10000, "step": 1}), + "width": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}), + "height": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}), + "interpolation": (["linear", "ease_in", "ease_out", "ease_in_out"],), + "start_level": ("FLOAT", {"default": 1.0,"min": 0.0, "max": 1.0, "step": 0.01}), + "midpoint_level": ("FLOAT", {"default": 0.5,"min": 0.0, "max": 1.0, "step": 0.01}), + "end_level": ("FLOAT", {"default": 0.0,"min": 0.0, "max": 1.0, "step": 0.01}), + "midpoint_frame": ("INT", {"default": 0,"min": 0, "max": 4096, "step": 1}), + }, + } + + def createfademask(self, frames, width, height, invert, interpolation, start_level, midpoint_level, end_level, midpoint_frame): + def ease_in(t): + return t * t + + def ease_out(t): + return 1 - (1 - t) * (1 - t) + + def ease_in_out(t): + return 3 * t * t - 2 * t * t * t + + batch_size = frames + out = [] + image_batch = np.zeros((batch_size, height, width), dtype=np.float32) + + if midpoint_frame == 0: + midpoint_frame = batch_size // 2 + + for i in range(batch_size): + if i <= midpoint_frame: + t = i / midpoint_frame + if interpolation == "ease_in": + t = ease_in(t) + elif interpolation == "ease_out": + t = ease_out(t) + elif interpolation == "ease_in_out": + t = ease_in_out(t) + color = start_level - t * (start_level - midpoint_level) + else: + t = (i - midpoint_frame) / (batch_size - midpoint_frame) + if interpolation == "ease_in": + t = ease_in(t) + elif interpolation == "ease_out": + t = ease_out(t) + elif interpolation == "ease_in_out": + t = ease_in_out(t) + color = midpoint_level - t * (midpoint_level - end_level) + + color = np.clip(color, 0, 255) + image = np.full((height, width), color, dtype=np.float32) + image_batch[i] = image + + output = torch.from_numpy(image_batch) + mask = output + out.append(mask) + + if invert: + return (1.0 - torch.cat(out, dim=0),) + return (torch.cat(out, dim=0),) + +class CreateFadeMaskAdvanced: + + RETURN_TYPES = ("MASK",) + FUNCTION = "createfademask" + CATEGORY = "KJNodes/masking/generate" + DESCRIPTION = """ +Create a batch of masks interpolated between given frames and values. +Uses same syntax as Fizz' BatchValueSchedule. +First value is the frame index (not that this starts from 0, not 1) +and the second value inside the brackets is the float value of the mask in range 0.0 - 1.0 + +For example the default values: +0:(0.0) +7:(1.0) +15:(0.0) + +Would create a mask batch fo 16 frames, starting from black, +interpolating with the chosen curve to fully white at the 8th frame, +and interpolating from that to fully black at the 16th frame. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "points_string": ("STRING", {"default": "0:(0.0),\n7:(1.0),\n15:(0.0)\n", "multiline": True}), + "invert": ("BOOLEAN", {"default": False}), + "frames": ("INT", {"default": 16,"min": 2, "max": 10000, "step": 1}), + "width": ("INT", {"default": 512,"min": 1, "max": 4096, "step": 1}), + "height": ("INT", {"default": 512,"min": 1, "max": 4096, "step": 1}), + "interpolation": (["linear", "ease_in", "ease_out", "ease_in_out", "none", "default_to_black"],), + }, + } + + def createfademask(self, frames, width, height, invert, points_string, interpolation): + def ease_in(t): + return t * t + + def ease_out(t): + return 1 - (1 - t) * (1 - t) + + def ease_in_out(t): + return 3 * t * t - 2 * t * t * t + + # Parse the input string into a list of tuples + points = [] + points_string = points_string.rstrip(',\n') + for point_str in points_string.split(','): + frame_str, color_str = point_str.split(':') + frame = int(frame_str.strip()) + color = float(color_str.strip()[1:-1]) # Remove parentheses around color + points.append((frame, color)) + + # Check if the last frame is already in the points + if (interpolation != "default_to_black") and (len(points) == 0 or points[-1][0] != frames - 1): + # If not, add it with the color of the last specified frame + points.append((frames - 1, points[-1][1] if points else 0)) + + # Sort the points by frame number + points.sort(key=lambda x: x[0]) + + batch_size = frames + out = [] + image_batch = np.zeros((batch_size, height, width), dtype=np.float32) + + # Index of the next point to interpolate towards + next_point = 1 + + for i in range(batch_size): + while next_point < len(points) and i > points[next_point][0]: + next_point += 1 + + # Interpolate between the previous point and the next point + prev_point = next_point - 1 + + if interpolation == "none": + exact_match = False + for p in points: + if p[0] == i: # Exact frame match + color = p[1] + exact_match = True + break + if not exact_match: + color = points[prev_point][1] + + elif interpolation == "default_to_black": + exact_match = False + for p in points: + if p[0] == i: # Exact frame match + color = p[1] + exact_match = True + break + if not exact_match: + color = 0 + else: + t = (i - points[prev_point][0]) / (points[next_point][0] - points[prev_point][0]) + if interpolation == "ease_in": + t = ease_in(t) + elif interpolation == "ease_out": + t = ease_out(t) + elif interpolation == "ease_in_out": + t = ease_in_out(t) + elif interpolation == "linear": + pass # No need to modify `t` for linear interpolation + + color = points[prev_point][1] - t * (points[prev_point][1] - points[next_point][1]) + + color = np.clip(color, 0, 255) + image = np.full((height, width), color, dtype=np.float32) + image_batch[i] = image + + output = torch.from_numpy(image_batch) + mask = output + out.append(mask) + + if invert: + return (1.0 - torch.cat(out, dim=0),) + return (torch.cat(out, dim=0),) + +class CreateMagicMask: + + RETURN_TYPES = ("MASK", "MASK",) + RETURN_NAMES = ("mask", "mask_inverted",) + FUNCTION = "createmagicmask" + CATEGORY = "KJNodes/masking/generate" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "frames": ("INT", {"default": 16,"min": 2, "max": 4096, "step": 1}), + "depth": ("INT", {"default": 12,"min": 1, "max": 500, "step": 1}), + "distortion": ("FLOAT", {"default": 1.5,"min": 0.0, "max": 100.0, "step": 0.01}), + "seed": ("INT", {"default": 123,"min": 0, "max": 99999999, "step": 1}), + "transitions": ("INT", {"default": 1,"min": 1, "max": 20, "step": 1}), + "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + }, + } + + def createmagicmask(self, frames, transitions, depth, distortion, seed, frame_width, frame_height): + from ..utility.magictex import coordinate_grid, random_transform, magic + import matplotlib.pyplot as plt + rng = np.random.default_rng(seed) + out = [] + coords = coordinate_grid((frame_width, frame_height)) + + # Calculate the number of frames for each transition + frames_per_transition = frames // transitions + + # Generate a base set of parameters + base_params = { + "coords": random_transform(coords, rng), + "depth": depth, + "distortion": distortion, + } + for t in range(transitions): + # Generate a second set of parameters that is at most max_diff away from the base parameters + params1 = base_params.copy() + params2 = base_params.copy() + + params1['coords'] = random_transform(coords, rng) + params2['coords'] = random_transform(coords, rng) + + for i in range(frames_per_transition): + # Compute the interpolation factor + alpha = i / frames_per_transition + + # Interpolate between the two sets of parameters + params = params1.copy() + params['coords'] = (1 - alpha) * params1['coords'] + alpha * params2['coords'] + + tex = magic(**params) + + dpi = frame_width / 10 + fig = plt.figure(figsize=(10, 10), dpi=dpi) + + ax = fig.add_subplot(111) + plt.subplots_adjust(left=0, right=1, bottom=0, top=1) + + ax.get_yaxis().set_ticks([]) + ax.get_xaxis().set_ticks([]) + ax.imshow(tex, aspect='auto') + + fig.canvas.draw() + img = np.array(fig.canvas.renderer._renderer) + + plt.close(fig) + + pil_img = Image.fromarray(img).convert("L") + mask = torch.tensor(np.array(pil_img)) / 255.0 + + out.append(mask) + + return (torch.stack(out, dim=0), 1.0 - torch.stack(out, dim=0),) + +class CreateShapeMask: + + RETURN_TYPES = ("MASK", "MASK",) + RETURN_NAMES = ("mask", "mask_inverted",) + FUNCTION = "createshapemask" + CATEGORY = "KJNodes/masking/generate" + DESCRIPTION = """ +Creates a mask or batch of masks with the specified shape. +Locations are center locations. +Grow value is the amount to grow the shape on each frame, creating animated masks. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "shape": ( + [ 'circle', + 'square', + 'triangle', + ], + { + "default": 'circle' + }), + "frames": ("INT", {"default": 1,"min": 1, "max": 4096, "step": 1}), + "location_x": ("INT", {"default": 256,"min": 0, "max": 4096, "step": 1}), + "location_y": ("INT", {"default": 256,"min": 0, "max": 4096, "step": 1}), + "grow": ("INT", {"default": 0, "min": -512, "max": 512, "step": 1}), + "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "shape_width": ("INT", {"default": 128,"min": 8, "max": 4096, "step": 1}), + "shape_height": ("INT", {"default": 128,"min": 8, "max": 4096, "step": 1}), + }, + } + + def createshapemask(self, frames, frame_width, frame_height, location_x, location_y, shape_width, shape_height, grow, shape): + # Define the number of images in the batch + batch_size = frames + out = [] + color = "white" + for i in range(batch_size): + image = Image.new("RGB", (frame_width, frame_height), "black") + draw = ImageDraw.Draw(image) + + # Calculate the size for this frame and ensure it's not less than 0 + current_width = max(0, shape_width + i*grow) + current_height = max(0, shape_height + i*grow) + + if shape == 'circle' or shape == 'square': + # Define the bounding box for the shape + left_up_point = (location_x - current_width // 2, location_y - current_height // 2) + right_down_point = (location_x + current_width // 2, location_y + current_height // 2) + two_points = [left_up_point, right_down_point] + + if shape == 'circle': + draw.ellipse(two_points, fill=color) + elif shape == 'square': + draw.rectangle(two_points, fill=color) + + elif shape == 'triangle': + # Define the points for the triangle + left_up_point = (location_x - current_width // 2, location_y + current_height // 2) # bottom left + right_down_point = (location_x + current_width // 2, location_y + current_height // 2) # bottom right + top_point = (location_x, location_y - current_height // 2) # top point + draw.polygon([top_point, left_up_point, right_down_point], fill=color) + + image = pil2tensor(image) + mask = image[:, :, :, 0] + out.append(mask) + outstack = torch.cat(out, dim=0) + return (outstack, 1.0 - outstack,) + +class CreateVoronoiMask: + + RETURN_TYPES = ("MASK", "MASK",) + RETURN_NAMES = ("mask", "mask_inverted",) + FUNCTION = "createvoronoi" + CATEGORY = "KJNodes/masking/generate" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "frames": ("INT", {"default": 16,"min": 2, "max": 4096, "step": 1}), + "num_points": ("INT", {"default": 15,"min": 1, "max": 4096, "step": 1}), + "line_width": ("INT", {"default": 4,"min": 1, "max": 4096, "step": 1}), + "speed": ("FLOAT", {"default": 0.5,"min": 0.0, "max": 1.0, "step": 0.01}), + "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + }, + } + + def createvoronoi(self, frames, num_points, line_width, speed, frame_width, frame_height): + from scipy.spatial import Voronoi + from matplotlib import pyplot as plt + # Define the number of images in the batch + batch_size = frames + out = [] + + # Calculate aspect ratio + aspect_ratio = frame_width / frame_height + + # Create start and end points for each point, considering the aspect ratio + start_points = np.random.rand(num_points, 2) + start_points[:, 0] *= aspect_ratio + + end_points = np.random.rand(num_points, 2) + end_points[:, 0] *= aspect_ratio + + for i in range(batch_size): + # Interpolate the points' positions based on the current frame + t = (i * speed) / (batch_size - 1) # normalize to [0, 1] over the frames + t = np.clip(t, 0, 1) # ensure t is in [0, 1] + points = (1 - t) * start_points + t * end_points # lerp + + # Adjust points for aspect ratio + points[:, 0] *= aspect_ratio + + vor = Voronoi(points) + + # Create a blank image with a white background + fig, ax = plt.subplots() + plt.subplots_adjust(left=0, right=1, bottom=0, top=1) + ax.set_xlim([0, aspect_ratio]); ax.set_ylim([0, 1]) # adjust x limits + ax.axis('off') + ax.margins(0, 0) + fig.set_size_inches(aspect_ratio * frame_height/100, frame_height/100) # adjust figure size + ax.fill_between([0, 1], [0, 1], color='white') + + # Plot each Voronoi ridge + for simplex in vor.ridge_vertices: + simplex = np.asarray(simplex) + if np.all(simplex >= 0): + plt.plot(vor.vertices[simplex, 0], vor.vertices[simplex, 1], 'k-', linewidth=line_width) + + fig.canvas.draw() + img = np.array(fig.canvas.renderer._renderer) + + plt.close(fig) + + pil_img = Image.fromarray(img).convert("L") + mask = torch.tensor(np.array(pil_img)) / 255.0 + + out.append(mask) + + return (torch.stack(out, dim=0), 1.0 - torch.stack(out, dim=0),) + +class GetMaskSizeAndCount: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "mask": ("MASK",), + }} + + RETURN_TYPES = ("MASK","INT", "INT", "INT",) + RETURN_NAMES = ("mask", "width", "height", "count",) + FUNCTION = "getsize" + CATEGORY = "KJNodes/masking" + DESCRIPTION = """ +Returns the width, height and batch size of the mask, +and passes it through unchanged. + +""" + + def getsize(self, mask): + width = mask.shape[2] + height = mask.shape[1] + count = mask.shape[0] + return {"ui": { + "text": [f"{count}x{width}x{height}"]}, + "result": (mask, width, height, count) + } + +class GrowMaskWithBlur: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "mask": ("MASK",), + "expand": ("INT", {"default": 0, "min": -MAX_RESOLUTION, "max": MAX_RESOLUTION, "step": 1}), + "incremental_expandrate": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 100.0, "step": 0.1}), + "tapered_corners": ("BOOLEAN", {"default": True}), + "flip_input": ("BOOLEAN", {"default": False}), + "blur_radius": ("FLOAT", { + "default": 0.0, + "min": 0.0, + "max": 100, + "step": 0.1 + }), + "lerp_alpha": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}), + "decay_factor": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}), + }, + "optional": { + "fill_holes": ("BOOLEAN", {"default": False}), + }, + } + + CATEGORY = "KJNodes/masking" + RETURN_TYPES = ("MASK", "MASK",) + RETURN_NAMES = ("mask", "mask_inverted",) + FUNCTION = "expand_mask" + DESCRIPTION = """ +# GrowMaskWithBlur +- mask: Input mask or mask batch +- expand: Expand or contract mask or mask batch by a given amount +- incremental_expandrate: increase expand rate by a given amount per frame +- tapered_corners: use tapered corners +- flip_input: flip input mask +- blur_radius: value higher than 0 will blur the mask +- lerp_alpha: alpha value for interpolation between frames +- decay_factor: decay value for interpolation between frames +- fill_holes: fill holes in the mask (slow)""" + + def expand_mask(self, mask, expand, tapered_corners, flip_input, blur_radius, incremental_expandrate, lerp_alpha, decay_factor, fill_holes=False): + import kornia.morphology as morph + alpha = lerp_alpha + decay = decay_factor + if flip_input: + mask = 1.0 - mask + + growmask = mask.reshape((-1, mask.shape[-2], mask.shape[-1])) + out = [] + previous_output = None + current_expand = expand + for m in tqdm(growmask, desc="Expanding/Contracting Mask"): + output = m.unsqueeze(0).unsqueeze(0).to(main_device) # Add batch and channel dims for kornia + if abs(round(current_expand)) > 0 and output.max() > 0: + # Create kernel - kornia expects kernel on same device as input + if tapered_corners: + kernel = torch.tensor([[0, 1, 0], + [1, 1, 1], + [0, 1, 0]], dtype=torch.float32, device=output.device) + else: + kernel = torch.tensor([[1, 1, 1], + [1, 1, 1], + [1, 1, 1]], dtype=torch.float32, device=output.device) + + for _ in range(abs(round(current_expand))): + if current_expand < 0: + output = morph.erosion(output, kernel) + else: + output = morph.dilation(output, kernel) + + output = output.squeeze(0).squeeze(0) # Remove batch and channel dims + + if current_expand < 0: + current_expand -= abs(incremental_expandrate) + else: + current_expand += abs(incremental_expandrate) + + if fill_holes: + binary_mask = output > 0 + output_np = binary_mask.cpu().numpy() + filled = scipy.ndimage.binary_fill_holes(output_np) + output = torch.from_numpy(filled.astype(np.float32)).to(output.device) + + if alpha < 1.0 and previous_output is not None: + output = alpha * output + (1 - alpha) * previous_output + if decay < 1.0 and previous_output is not None: + output += decay * previous_output + output = output / output.max() + previous_output = output + out.append(output.cpu()) + + if blur_radius != 0: + # Convert the tensor list to PIL images, apply blur, and convert back + for idx, tensor in enumerate(out): + # Convert tensor to PIL image + pil_image = tensor2pil(tensor.cpu().detach())[0] + # Apply Gaussian blur + pil_image = pil_image.filter(ImageFilter.GaussianBlur(blur_radius)) + # Convert back to tensor + out[idx] = pil2tensor(pil_image) + blurred = torch.cat(out, dim=0) + return (blurred, 1.0 - blurred) + else: + return (torch.stack(out, dim=0), 1.0 - torch.stack(out, dim=0),) + +class MaskBatchMulti: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "inputcount": ("INT", {"default": 2, "min": 2, "max": 1000, "step": 1}), + "mask_1": ("MASK", ), + "mask_2": ("MASK", ), + }, + } + + RETURN_TYPES = ("MASK",) + RETURN_NAMES = ("masks",) + FUNCTION = "combine" + CATEGORY = "KJNodes/masking" + DESCRIPTION = """ +Creates an image batch from multiple masks. +You can set how many inputs the node has, +with the **inputcount** and clicking update. +""" + + def combine(self, inputcount, **kwargs): + mask = kwargs["mask_1"] + for c in range(1, inputcount): + new_mask = kwargs[f"mask_{c + 1}"] + if mask.shape[1:] != new_mask.shape[1:]: + new_mask = F.interpolate(new_mask.unsqueeze(1), size=(mask.shape[1], mask.shape[2]), mode="bicubic").squeeze(1) + mask = torch.cat((mask, new_mask), dim=0) + return (mask,) + +class OffsetMask: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "mask": ("MASK",), + "x": ("INT", { "default": 0, "min": -4096, "max": MAX_RESOLUTION, "step": 1, "display": "number" }), + "y": ("INT", { "default": 0, "min": -4096, "max": MAX_RESOLUTION, "step": 1, "display": "number" }), + "angle": ("INT", { "default": 0, "min": -360, "max": 360, "step": 1, "display": "number" }), + "duplication_factor": ("INT", { "default": 1, "min": 1, "max": 1000, "step": 1, "display": "number" }), + "roll": ("BOOLEAN", { "default": False }), + "incremental": ("BOOLEAN", { "default": False }), + "padding_mode": ( + [ + 'empty', + 'border', + 'reflection', + + ], { + "default": 'empty' + }), + } + } + + RETURN_TYPES = ("MASK",) + RETURN_NAMES = ("mask",) + FUNCTION = "offset" + CATEGORY = "KJNodes/masking" + DESCRIPTION = """ +Offsets the mask by the specified amount. + - mask: Input mask or mask batch + - x: Horizontal offset + - y: Vertical offset + - angle: Angle in degrees + - roll: roll edge wrapping + - duplication_factor: Number of times to duplicate the mask to form a batch + - border padding_mode: Padding mode for the mask +""" + + def offset(self, mask, x, y, angle, roll=False, incremental=False, duplication_factor=1, padding_mode="empty"): + # Create duplicates of the mask batch + mask = mask.repeat(duplication_factor, 1, 1).clone() + + batch_size, height, width = mask.shape + + if angle != 0 and incremental: + for i in range(batch_size): + rotation_angle = angle * (i+1) + mask[i] = TF.rotate(mask[i].unsqueeze(0), rotation_angle).squeeze(0) + elif angle > 0: + for i in range(batch_size): + mask[i] = TF.rotate(mask[i].unsqueeze(0), angle).squeeze(0) + + if roll: + if incremental: + for i in range(batch_size): + shift_x = min(x*(i+1), width-1) + shift_y = min(y*(i+1), height-1) + if shift_x != 0: + mask[i] = torch.roll(mask[i], shifts=shift_x, dims=1) + if shift_y != 0: + mask[i] = torch.roll(mask[i], shifts=shift_y, dims=0) + else: + shift_x = min(x, width-1) + shift_y = min(y, height-1) + if shift_x != 0: + mask = torch.roll(mask, shifts=shift_x, dims=2) + if shift_y != 0: + mask = torch.roll(mask, shifts=shift_y, dims=1) + else: + + for i in range(batch_size): + if incremental: + temp_x = min(x * (i+1), width-1) + temp_y = min(y * (i+1), height-1) + else: + temp_x = min(x, width-1) + temp_y = min(y, height-1) + if temp_x > 0: + if padding_mode == 'empty': + mask[i] = torch.cat([torch.zeros((height, temp_x)), mask[i, :, :-temp_x]], dim=1) + elif padding_mode in ['replicate', 'reflect']: + mask[i] = F.pad(mask[i, :, :-temp_x], (0, temp_x), mode=padding_mode) + elif temp_x < 0: + if padding_mode == 'empty': + mask[i] = torch.cat([mask[i, :, :temp_x], torch.zeros((height, -temp_x))], dim=1) + elif padding_mode in ['replicate', 'reflect']: + mask[i] = F.pad(mask[i, :, -temp_x:], (temp_x, 0), mode=padding_mode) + + if temp_y > 0: + if padding_mode == 'empty': + mask[i] = torch.cat([torch.zeros((temp_y, width)), mask[i, :-temp_y, :]], dim=0) + elif padding_mode in ['replicate', 'reflect']: + mask[i] = F.pad(mask[i, :-temp_y, :], (0, temp_y), mode=padding_mode) + elif temp_y < 0: + if padding_mode == 'empty': + mask[i] = torch.cat([mask[i, :temp_y, :], torch.zeros((-temp_y, width))], dim=0) + elif padding_mode in ['replicate', 'reflect']: + mask[i] = F.pad(mask[i, -temp_y:, :], (temp_y, 0), mode=padding_mode) + + return mask, + +class RoundMask: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "mask": ("MASK",), + }} + + RETURN_TYPES = ("MASK",) + FUNCTION = "round" + CATEGORY = "KJNodes/masking" + DESCRIPTION = """ +Rounds the mask or batch of masks to a binary mask. +RoundMask example + +""" + + def round(self, mask): + mask = mask.round() + return (mask,) + +class ResizeMask: + upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"] + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "mask": ("MASK",), + "width": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1, "display": "number" }), + "height": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1, "display": "number" }), + "keep_proportions": ("BOOLEAN", { "default": False }), + "upscale_method": (s.upscale_methods,), + "crop": (["disabled","center"],), + } + } + + RETURN_TYPES = ("MASK", "INT", "INT",) + RETURN_NAMES = ("mask", "width", "height",) + FUNCTION = "resize" + CATEGORY = "KJNodes/masking" + DESCRIPTION = """ +Resizes the mask or batch of masks to the specified width and height. +""" + + def resize(self, mask, width, height, keep_proportions, upscale_method,crop): + if keep_proportions: + _, oh, ow = mask.shape + width = ow if width == 0 else width + height = oh if height == 0 else height + ratio = min(width / ow, height / oh) + width = round(ow*ratio) + height = round(oh*ratio) + + if upscale_method == "lanczos": + out_mask = common_upscale(mask.unsqueeze(1).repeat(1, 3, 1, 1), width, height, upscale_method, crop=crop).movedim(1,-1)[:, :, :, 0] + else: + out_mask = common_upscale(mask.unsqueeze(1), width, height, upscale_method, crop=crop).squeeze(1) + + return(out_mask, out_mask.shape[2], out_mask.shape[1],) + +class RemapMaskRange: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "mask": ("MASK",), + "min": ("FLOAT", {"default": 0.0,"min": -10.0, "max": 1.0, "step": 0.01}), + "max": ("FLOAT", {"default": 1.0,"min": 0.0, "max": 10.0, "step": 0.01}), + } + } + + RETURN_TYPES = ("MASK",) + RETURN_NAMES = ("mask",) + FUNCTION = "remap" + CATEGORY = "KJNodes/masking" + DESCRIPTION = """ +Sets new min and max values for the mask. +""" + + def remap(self, mask, min, max): + + # Find the maximum value in the mask + mask_max = torch.max(mask) + + # If the maximum mask value is zero, avoid division by zero by setting it to 1 + mask_max = mask_max if mask_max > 0 else 1 + + # Scale the mask values to the new range defined by min and max + # The highest pixel value in the mask will be scaled to max + scaled_mask = (mask / mask_max) * (max - min) + min + + # Clamp the values to ensure they are within [0.0, 1.0] + scaled_mask = torch.clamp(scaled_mask, min=0.0, max=1.0) + + return (scaled_mask, ) + + +def get_mask_polygon(self, mask_np): + import cv2 + """Helper function to get polygon points from mask""" + # Find contours + contours, _ = cv2.findContours(mask_np, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + + if not contours: + return None + + # Get the largest contour + largest_contour = max(contours, key=cv2.contourArea) + + # Approximate polygon + epsilon = 0.02 * cv2.arcLength(largest_contour, True) + polygon = cv2.approxPolyDP(largest_contour, epsilon, True) + + return polygon.squeeze() + +class SeparateMasks: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "mask": ("MASK", ), + "size_threshold_width" : ("INT", {"default": 256, "min": 0.0, "max": 4096, "step": 1}), + "size_threshold_height" : ("INT", {"default": 256, "min": 0.0, "max": 4096, "step": 1}), + "mode": (["convex_polygons", "area", "box"],), + "max_poly_points": ("INT", {"default": 8, "min": 3, "max": 32, "step": 1}), + + }, + } + + RETURN_TYPES = ("MASK",) + RETURN_NAMES = ("mask",) + FUNCTION = "separate" + CATEGORY = "KJNodes/masking" + OUTPUT_NODE = True + DESCRIPTION = "Separates a mask into multiple masks based on the size of the connected components." + + def polygon_to_mask(self, polygon, shape): + import cv2 + mask = np.zeros((shape[0], shape[1]), dtype=np.uint8) # Fixed shape handling + + if len(polygon.shape) == 2: # Check if polygon points are valid + polygon = polygon.astype(np.int32) + cv2.fillPoly(mask, [polygon], 1) + return mask + + def get_mask_polygon(self, mask_np, max_points): + import cv2 + contours, _ = cv2.findContours(mask_np, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + if not contours: + return None + + largest_contour = max(contours, key=cv2.contourArea) + hull = cv2.convexHull(largest_contour) + + # Initialize with smaller epsilon for more points + perimeter = cv2.arcLength(hull, True) + + min_eps = perimeter * 0.001 # Much smaller minimum + max_eps = perimeter * 0.2 # Smaller maximum + + best_approx = None + best_diff = float('inf') + max_iterations = 20 + + #print(f"Target points: {max_points}, Perimeter: {perimeter}") + + for i in range(max_iterations): + curr_eps = (min_eps + max_eps) / 2 + approx = cv2.approxPolyDP(hull, curr_eps, True) + points_diff = len(approx) - max_points + + #print(f"Iteration {i}: points={len(approx)}, eps={curr_eps:.4f}") + + if abs(points_diff) < best_diff: + best_approx = approx + best_diff = abs(points_diff) + + if len(approx) > max_points: + min_eps = curr_eps * 1.1 # More gradual adjustment + elif len(approx) < max_points: + max_eps = curr_eps * 0.9 # More gradual adjustment + else: + return approx.squeeze() + + if abs(max_eps - min_eps) < perimeter * 0.0001: # Relative tolerance + break + + # If we didn't find exact match, return best approximation + return best_approx.squeeze() if best_approx is not None else hull.squeeze() + + def separate(self, mask: torch.Tensor, size_threshold_width: int, size_threshold_height: int, max_poly_points: int, mode: str): + B, H, W = mask.shape + separated = [] + + mask = mask.round() + + for b in range(B): + mask_np = mask[b].cpu().numpy().astype(np.uint8) + structure = np.ones((3, 3), dtype=np.int8) + labeled, ncomponents = scipy.ndimage.label(mask_np, structure=structure) + pbar = ProgressBar(ncomponents) + + for component in range(1, ncomponents + 1): + component_mask_np = (labeled == component).astype(np.uint8) + + rows = np.any(component_mask_np, axis=1) + cols = np.any(component_mask_np, axis=0) + y_min, y_max = np.where(rows)[0][[0, -1]] + x_min, x_max = np.where(cols)[0][[0, -1]] + + width = x_max - x_min + 1 + height = y_max - y_min + 1 + centroid_x = (x_min + x_max) / 2 # Calculate x centroid + logging.info(f"Component {component}: width={width}, height={height}, x_pos={centroid_x}") + + if width >= size_threshold_width and height >= size_threshold_height: + if mode == "convex_polygons": + polygon = self.get_mask_polygon(component_mask_np, max_poly_points) + if polygon is not None: + poly_mask = self.polygon_to_mask(polygon, (H, W)) + poly_mask = torch.tensor(poly_mask, device=mask.device) + separated.append((centroid_x, poly_mask)) + elif mode == "box": + # Create bounding box mask + box_mask = np.zeros((H, W), dtype=np.uint8) + box_mask[y_min:y_max+1, x_min:x_max+1] = 1 + box_mask = torch.tensor(box_mask, device=mask.device) + separated.append((centroid_x, box_mask)) + else: + area_mask = torch.tensor(component_mask_np, device=mask.device) + separated.append((centroid_x, area_mask)) + pbar.update(1) + + if len(separated) > 0: + # Sort by x position and extract only the masks + separated.sort(key=lambda x: x[0]) + separated = [x[1] for x in separated] + out_masks = torch.stack(separated, dim=0) + return out_masks, + else: + return torch.empty((1, 64, 64), device=mask.device), + + +class ConsolidateMasksKJ: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "masks": ("MASK",), + "width": ("INT", {"default": 512, "min": 0, "max": 4096, "step": 64}), + "height": ("INT", {"default": 512, "min": 0, "max": 4096, "step": 64}), + "padding": ("INT", {"default": 0, "min": 0, "max": 4096, "step": 1}), + }, + } + + RETURN_TYPES = ("MASK",) + FUNCTION = "consolidate" + + CATEGORY = "KJNodes/masking" + DESCRIPTION = "Consolidates a batch of separate masks by finding the largest group of masks that fit inside a tile of the given width and height (including the padding), and repeating until no more masks can be combined." + + def consolidate(self, masks, width=512, height=512, padding=0): + B, H, W = masks.shape + + def mask_fits(coords, candidate_coords): + x_min, y_min, x_max, y_max = coords + cx_min, cy_min, cx_max, cy_max = candidate_coords + nx_min, ny_min = min(x_min, cx_min), min(y_min, cy_min) + nx_max, ny_max = max(x_max, cx_max), max(y_max, cy_max) + if nx_min + width < nx_max + padding or ny_min + height < ny_max + padding: + return False, coords + return True, (nx_min, ny_min, nx_max, ny_max) + + separated = [] + final_masks = [] + for b in range(B): + m = masks[b] + rows, cols = m.any(dim=1), m.any(dim=0) + y_min, y_max = torch.where(rows)[0][[0, -1]] + x_min, x_max = torch.where(cols)[0][[0, -1]] + w = x_max - x_min + 1 + h = y_max - y_min + 1 + separated.append(((x_min.item(), y_min.item(), x_max.item(), y_max.item()), m)) + + separated.sort(key=lambda x: x[0]) + fits = [] + for i, masks in enumerate(separated): + coord = masks[0] + fits_in_box = [] + for j, cand_mask in enumerate(separated): + if i == j: + continue + r, coord = mask_fits(coord, cand_mask[0]) + if r: + fits_in_box.append(j) + fits.append((i, fits_in_box)) + fits.sort(key=lambda x: -len(x[1])) + seen = [] + unique_fits = [] + for idx, fs in fits: + uniq = [i for i in fs if i not in seen] + unique_fits.append((idx, fs, uniq)) + seen.extend(uniq) + unique_fits.sort(key=lambda x: (-len(x[1]), -len(x[2]))) + merged = [] + for mask_idx, fitting_masks, _ in unique_fits: + if mask_idx in merged: + continue + fitting_masks = [i for i in fitting_masks if i not in merged] + combined_mask = separated[mask_idx][1].clone() + for i in fitting_masks: + combined_mask += separated[i][1] + merged.append(i) + merged.append(mask_idx) + final_masks.append(combined_mask) + + logging.info(f"Consolidated {B} masks into {len(final_masks)}") + return (torch.stack(final_masks, dim=0),) + + +class DrawMaskOnImage: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "image": ("IMAGE", ), + "mask": ("MASK", ), + "color": ("STRING", {"default": "0, 0, 0", "tooltip": "Color as RGB/RGBA values in range 0-255 or 0.0-1.0, separated by commas. Ex: 255, 0, 0, 128"}), + }, + "optional": { + "device": (["cpu", "gpu"], {"default": "cpu", "tooltip": "Device to use for processing"}), + } + } + + RETURN_TYPES = ("IMAGE", ) + RETURN_NAMES = ("images",) + FUNCTION = "apply" + CATEGORY = "KJNodes/masking" + DESCRIPTION = "Applies the provided masks to the input images with Alpha Blending support." + + def apply(self, image, mask, color, device="cpu"): + B, H, W, C = image.shape + BM, HM, WM = mask.shape + + processing_device = main_device if device == "gpu" else torch.device("cpu") + + in_masks = mask.clone().to(processing_device) + in_images = image.clone().to(processing_device) + + # Resize mask if dimensions don't match + if HM != H or WM != W: + in_masks = F.interpolate(mask.unsqueeze(1), size=(H, W), mode='nearest-exact').squeeze(1) + # Handle batch size mismatch + if B > BM: + in_masks = in_masks.repeat((B + BM - 1) // BM, 1, 1)[:B] + elif BM > B: + in_masks = in_masks[:B] + + output_images = [] + + # Parse Color String (Handle RGB, RGBA, and Hex formats) + color = color.strip() + color_values = [] + + if color.startswith('#'): + # Handle hex format (#RGB, #RGBA, #RRGGBB, #RRGGBBAA) + hex_color = color.lstrip('#') + if len(hex_color) == 3: # #RGB + color_values = [int(c*2, 16) / 255.0 for c in hex_color] + elif len(hex_color) == 4: # #RGBA + color_values = [int(c*2, 16) / 255.0 for c in hex_color] + elif len(hex_color) == 6: # #RRGGBB + color_values = [int(hex_color[i:i+2], 16) / 255.0 for i in (0, 2, 4)] + elif len(hex_color) == 8: # #RRGGBBAA + color_values = [int(hex_color[i:i+2], 16) / 255.0 for i in (0, 2, 4, 6)] + else: + raise ValueError(f"Invalid hex color format: {color}") + else: + # Handle comma-separated RGB/RGBA format + for x in color.split(","): + val = float(x.strip()) + color_values.append(val / 255.0 if val > 1.0 else val) + + rgb = color_values[:3] + alpha_val = color_values[3] if len(color_values) == 4 else 1.0 + + fill_color = torch.tensor(rgb, dtype=torch.float32, device=processing_device) + + for i in tqdm(range(B), desc="DrawMaskOnImage batch"): + curr_mask = in_masks[i] # [H, W] + img_idx = min(i, B - 1) + curr_image = in_images[img_idx] # [H, W, C] + + blend_factor = curr_mask.unsqueeze(-1) * alpha_val + img_channels = curr_image.shape[-1] + + if img_channels == 4: + img_rgb = curr_image[..., :3] + img_a = curr_image[..., 3:] + out_rgb = img_rgb * (1 - blend_factor) + fill_color * blend_factor + out_a = torch.maximum(img_a, blend_factor) + masked_image = torch.cat((out_rgb, out_a), dim=-1) + else: + masked_image = curr_image * (1 - blend_factor) + fill_color * blend_factor + output_images.append(masked_image) + + if not output_images: + return (torch.zeros((0, H, W, C), dtype=image.dtype),) + + out_tensor = torch.stack(output_images, dim=0).cpu() + + return (out_tensor, ) + +class BlockifyMask: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "masks": ("MASK",), + "block_size": ("INT", {"default": 32, "min": 8, "max": 512, "step": 1, "tooltip": "Size of blocks in pixels (smaller = smaller blocks)"}), + }, + "optional": { + "device": (["cpu", "gpu"], {"default": "cpu", "tooltip": "Device to use for processing"}), + } + } + + RETURN_TYPES = ("MASK", ) + RETURN_NAMES = ("mask",) + FUNCTION = "process" + CATEGORY = "KJNodes/masking" + DESCRIPTION = "Creates a block mask by dividing the bounding box of each mask into blocks of the specified size and filling in blocks that contain any part of the original mask." + + def process(self, masks, block_size, device="cpu"): + processing_device = main_device if device == "gpu" else torch.device("cpu") + + masks = masks.to(processing_device) + batch_size, height, width = masks.shape + + result_masks = torch.zeros_like(masks) + + for i in tqdm(range(batch_size), desc="BlockifyMask batch"): + mask = masks[i] + + # Find bounding box efficiently + mask_bool = mask > 0 + if not mask_bool.any(): + continue + + y_indices = torch.nonzero(mask_bool.any(dim=1), as_tuple=True)[0] + x_indices = torch.nonzero(mask_bool.any(dim=0), as_tuple=True)[0] + + if len(y_indices) == 0 or len(x_indices) == 0: + continue + + y_min, y_max = y_indices[0], y_indices[-1] + x_min, x_max = x_indices[0], x_indices[-1] + + bbox_width = x_max - x_min + 1 + bbox_height = y_max - y_min + 1 + + # Calculate block grid + w_divisions = max(1, bbox_width // block_size) + h_divisions = max(1, bbox_height // block_size) + + w_slice = bbox_width // w_divisions + h_slice = bbox_height // h_divisions + + # Create coordinate grids only for bbox region + y_coords = torch.arange(y_min, y_max + 1, device=processing_device).view(-1, 1) + x_coords = torch.arange(x_min, x_max + 1, device=processing_device).view(1, -1) + + # Calculate block indices for bbox region + w_block_indices = (x_coords - x_min) // w_slice + h_block_indices = (y_coords - y_min) // h_slice + + # Clamp to valid range + w_block_indices = w_block_indices.clamp(0, w_divisions - 1) + h_block_indices = h_block_indices.clamp(0, h_divisions - 1) + + # Create unique block IDs by combining h and w indices + block_ids = h_block_indices * w_divisions + w_block_indices + + # Get mask region within bbox + mask_region = mask[y_min:y_max+1, x_min:x_max+1] + + # Find which blocks have content using scatter_add + max_blocks = h_divisions * w_divisions + block_content = torch.zeros(max_blocks, device=processing_device) + block_content.scatter_add_(0, block_ids.flatten(), mask_region.flatten()) + + # Create result for blocks that have content + has_content = block_content > 0 + block_mask = has_content[block_ids] + + # Fill the result + result_masks[i, y_min:y_max+1, x_min:x_max+1] = block_mask.float() + + return (result_masks.clamp(0, 1),) diff --git a/.disabled/comfyui-kjnodes@nightly/nodes/model_optimization_nodes.py b/.disabled/comfyui-kjnodes@nightly/nodes/model_optimization_nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..d12e7c57810420649441384bf7f0d079358c9c54 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/nodes/model_optimization_nodes.py @@ -0,0 +1,2312 @@ +import os +import sys +import logging +import torch +import importlib +import math +import datetime +from tqdm import tqdm + +import folder_paths +import comfy.model_management as mm +from comfy.cli_args import args +from comfy.ldm.modules.attention import wrap_attn, optimized_attention, attention_pytorch +import comfy.utils +import comfy.sd + +try: + from comfy_api.latest import io + v3_available = True +except ImportError: + v3_available = False + logging.warning("ComfyUI v3 node API not available, please update ComfyUI to access latest v3 nodes.") + +sageattn_modes = ["disabled", "auto", "sageattn_qk_int8_pv_fp16_cuda", "sageattn_qk_int8_pv_fp16_triton", "sageattn_qk_int8_pv_fp8_cuda", "sageattn_qk_int8_pv_fp8_cuda++", "sageattn3", "sageattn3_per_block_mean"] + +def get_sage_func(sage_attention, allow_compile=False): + logging.info(f"Using sage attention mode: {sage_attention}") + from sageattention import sageattn + if sage_attention == "auto": + def sage_func(q, k, v, is_causal=False, attn_mask=None, tensor_layout="NHD"): + return sageattn(q, k, v, is_causal=is_causal, attn_mask=attn_mask, tensor_layout=tensor_layout) + elif sage_attention == "sageattn_qk_int8_pv_fp16_cuda": + from sageattention import sageattn_qk_int8_pv_fp16_cuda + def sage_func(q, k, v, is_causal=False, attn_mask=None, tensor_layout="NHD"): + return sageattn_qk_int8_pv_fp16_cuda(q, k, v, is_causal=is_causal, attn_mask=attn_mask, pv_accum_dtype="fp32", tensor_layout=tensor_layout) + elif sage_attention == "sageattn_qk_int8_pv_fp16_triton": + from sageattention import sageattn_qk_int8_pv_fp16_triton + def sage_func(q, k, v, is_causal=False, attn_mask=None, tensor_layout="NHD"): + return sageattn_qk_int8_pv_fp16_triton(q, k, v, is_causal=is_causal, attn_mask=attn_mask, tensor_layout=tensor_layout) + elif sage_attention == "sageattn_qk_int8_pv_fp8_cuda": + from sageattention import sageattn_qk_int8_pv_fp8_cuda + def sage_func(q, k, v, is_causal=False, attn_mask=None, tensor_layout="NHD"): + return sageattn_qk_int8_pv_fp8_cuda(q, k, v, is_causal=is_causal, attn_mask=attn_mask, pv_accum_dtype="fp32+fp32", tensor_layout=tensor_layout) + elif sage_attention == "sageattn_qk_int8_pv_fp8_cuda++": + from sageattention import sageattn_qk_int8_pv_fp8_cuda + def sage_func(q, k, v, is_causal=False, attn_mask=None, tensor_layout="NHD"): + return sageattn_qk_int8_pv_fp8_cuda(q, k, v, is_causal=is_causal, attn_mask=attn_mask, pv_accum_dtype="fp32+fp16", tensor_layout=tensor_layout) + elif "sageattn3" in sage_attention: + from sageattn3 import sageattn3_blackwell + def sage_func(q, k, v, is_causal=False, attn_mask=None, tensor_layout="NHD", **kwargs): + q, k, v = [x.transpose(1, 2) if tensor_layout == "NHD" else x for x in (q, k, v)] + out = sageattn3_blackwell(q, k, v, is_causal=is_causal, attn_mask=attn_mask, per_block_mean=(sage_attention == "sageattn3_per_block_mean")) + return out.transpose(1, 2) if tensor_layout == "NHD" else out + + if not allow_compile: + sage_func = torch.compiler.disable()(sage_func) + + @wrap_attn + def attention_sage(q, k, v, heads, mask=None, attn_precision=None, skip_reshape=False, skip_output_reshape=False, **kwargs): + if kwargs.get("low_precision_attention", True) is False: + return attention_pytorch(q, k, v, heads, mask=mask, skip_reshape=skip_reshape, skip_output_reshape=skip_output_reshape, **kwargs) + in_dtype = v.dtype + if q.dtype == torch.float32 or k.dtype == torch.float32 or v.dtype == torch.float32: + q, k, v = q.to(torch.float16), k.to(torch.float16), v.to(torch.float16) + if skip_reshape: + b, _, _, dim_head = q.shape + tensor_layout="HND" + else: + b, _, dim_head = q.shape + dim_head //= heads + q, k, v = map( + lambda t: t.view(b, -1, heads, dim_head), + (q, k, v), + ) + tensor_layout="NHD" + if mask is not None: + # add a batch dimension if there isn't already one + if mask.ndim == 2: + mask = mask.unsqueeze(0) + # add a heads dimension if there isn't already one + if mask.ndim == 3: + mask = mask.unsqueeze(1) + out = sage_func(q, k, v, attn_mask=mask, is_causal=False, tensor_layout=tensor_layout).to(in_dtype) + if tensor_layout == "HND": + if not skip_output_reshape: + out = ( + out.transpose(1, 2).reshape(b, -1, heads * dim_head) + ) + else: + if skip_output_reshape: + out = out.transpose(1, 2) + else: + out = out.reshape(b, -1, heads * dim_head) + return out + return attention_sage + + +from comfy.patcher_extension import CallbacksMP +class PathchSageAttentionKJ(): + @classmethod + def INPUT_TYPES(s): + return {"required": { + "model": ("MODEL",), + "sage_attention": (sageattn_modes, {"default": False, "tooltip": "Global patch comfy attention to use sageattn, once patched to revert back to normal you would need to run this node again with disabled option."}), + }, + "optional": { + "allow_compile": ("BOOLEAN", {"default": False, "tooltip": "Allow the use of torch.compile for the sage attention function, requires latest sageattn 2.2.0 or higher."}) + } + } + + RETURN_TYPES = ("MODEL", ) + FUNCTION = "patch" + DESCRIPTION = "Experimental node for patching attention mode. This doesn't use the model patching system and thus can't be disabled without running the node again with 'disabled' option." + EXPERIMENTAL = True + CATEGORY = "KJNodes/experimental" + + def patch(self, model, sage_attention, allow_compile=False): + if sage_attention == "disabled": + return model, + + model_clone = model.clone() + + new_attention = get_sage_func(sage_attention, allow_compile=allow_compile) + def attention_override_sage(func, *args, **kwargs): + return new_attention.__wrapped__(*args, **kwargs) + + # attention override + model_clone.model_options["transformer_options"]["optimized_attention_override"] = attention_override_sage + + return model_clone, + + +class CheckpointLoaderKJ(): + @classmethod + def INPUT_TYPES(s): + return {"required": { + "ckpt_name": (folder_paths.get_filename_list("checkpoints"), {"tooltip": "The name of the checkpoint (model) to load."}), + "weight_dtype": (["default", "fp8_e4m3fn", "fp8_e4m3fn_fast", "fp8_e5m2", "fp16", "bf16", "fp32"],), + "compute_dtype": (["default", "fp16", "bf16", "fp32"], {"default": "default", "tooltip": "The compute dtype to use for the model."}), + "patch_cublaslinear": ("BOOLEAN", {"default": False, "tooltip": "Enable or disable the cublas_ops arg"}), + "sage_attention": (sageattn_modes, {"default": False, "tooltip": "Patch comfy attention to use sageattn."}), + "enable_fp16_accumulation": ("BOOLEAN", {"default": False, "tooltip": "Enable torch.backends.cuda.matmul.allow_fp16_accumulation, required minimum pytorch version 2.7.1"}), + }} + + RETURN_TYPES = ("MODEL", "CLIP", "VAE") + FUNCTION = "load" + DESCRIPTION = "Experimental node for patching torch.nn.Linear with CublasLinear." + EXPERIMENTAL = True + CATEGORY = "KJNodes/model_loaders" + + def load(self, ckpt_name, weight_dtype, compute_dtype, patch_cublaslinear, sage_attention, enable_fp16_accumulation): + DTYPE_MAP = { + "fp8_e4m3fn": torch.float8_e4m3fn, + "fp8_e5m2": torch.float8_e5m2, + "fp16": torch.float16, + "bf16": torch.bfloat16, + "fp32": torch.float32 + } + model_options = {} + if dtype := DTYPE_MAP.get(weight_dtype): + model_options["dtype"] = dtype + logging.info(f"Setting {ckpt_name} weight dtype to {dtype}") + + if weight_dtype == "fp8_e4m3fn_fast": + model_options["dtype"] = torch.float8_e4m3fn + model_options["fp8_optimizations"] = True + + if patch_cublaslinear: + args.fast.add("cublas_ops") + else: + args.fast.discard("cublas_ops") + + ckpt_path = folder_paths.get_full_path_or_raise("checkpoints", ckpt_name) + sd, metadata = comfy.utils.load_torch_file(ckpt_path, return_metadata=True) + + model, clip, vae, _ = comfy.sd.load_state_dict_guess_config( + sd, + output_vae=True, + output_clip=True, + embedding_directory=folder_paths.get_folder_paths("embeddings"), + metadata=metadata, + model_options=model_options) + + if dtype := DTYPE_MAP.get(compute_dtype): + model.set_model_compute_dtype(dtype) + model.force_cast_weights = False + logging.info(f"Setting {ckpt_name} compute dtype to {dtype}") + + if enable_fp16_accumulation: + if hasattr(torch.backends.cuda.matmul, "allow_fp16_accumulation"): + torch.backends.cuda.matmul.allow_fp16_accumulation = True + else: + raise RuntimeError("Failed to set fp16 accumulation, requires pytorch version 2.7.1 or higher") + else: + if hasattr(torch.backends.cuda.matmul, "allow_fp16_accumulation"): + torch.backends.cuda.matmul.allow_fp16_accumulation = False + + if sage_attention != "disabled": + new_attention = get_sage_func(sage_attention) + def attention_override_sage(func, *args, **kwargs): + return new_attention.__wrapped__(*args, **kwargs) + + # attention override + model.model_options["transformer_options"]["optimized_attention_override"] = attention_override_sage + + return model, clip, vae + + +class DiffusionModelSelector(): + @classmethod + def INPUT_TYPES(s): + ltx2_connector_models = folder_paths.get_filename_list("text_encoders") + ltx2_connector_models = [m for m in ltx2_connector_models if "connector" in m.lower()] + return {"required": { + "model_name": (folder_paths.get_filename_list("diffusion_models") + ltx2_connector_models, {"tooltip": "The name of the checkpoint (model) to load."}), + }, + } + + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("model_path",) + FUNCTION = "get_path" + DESCRIPTION = "Returns the path to the model as a string." + EXPERIMENTAL = True + CATEGORY = "KJNodes/model_loaders" + + def get_path(self, model_name): + if "connector" in model_name.lower(): + model_path = folder_paths.get_full_path_or_raise("text_encoders", model_name) + else: + model_path = folder_paths.get_full_path_or_raise("diffusion_models", model_name) + return (model_path,) + +class DiffusionModelLoaderKJ(): + @classmethod + def INPUT_TYPES(s): + return {"required": { + "model_name": (folder_paths.get_filename_list("diffusion_models"), {"tooltip": "The name of the checkpoint (model) to load."}), + "weight_dtype": (["default", "fp8_e4m3fn", "fp8_e4m3fn_fast", "fp8_e5m2", "fp16", "bf16", "fp32"],), + "compute_dtype": (["default", "fp16", "bf16", "fp32"], {"default": "default", "tooltip": "The compute dtype to use for the model."}), + "patch_cublaslinear": ("BOOLEAN", {"default": False, "tooltip": "Enable or disable the cublas_ops arg"}), + "sage_attention": (sageattn_modes, {"default": False, "tooltip": "Patch comfy attention to use sageattn."}), + "enable_fp16_accumulation": ("BOOLEAN", {"default": False, "tooltip": "Enable torch.backends.cuda.matmul.allow_fp16_accumulation, requires pytorch 2.7.0 nightly."}), + }, + "optional": { + "extra_state_dict": ("STRING", {"forceInput": True, "tooltip": "The full path to an additional state dict to load, this will be merged with the main state dict. Useful for example to add VACE module to a WanVideoModel. You can use DiffusionModelSelector to easily get the path."}), + } + } + + RETURN_TYPES = ("MODEL",) + FUNCTION = "patch_and_load" + DESCRIPTION = "Node for patching torch.nn.Linear with CublasLinear." + EXPERIMENTAL = True + CATEGORY = "KJNodes/model_loaders" + + def patch_and_load(self, model_name, weight_dtype, compute_dtype, patch_cublaslinear, sage_attention, enable_fp16_accumulation, extra_state_dict=None): + DTYPE_MAP = { + "fp8_e4m3fn": torch.float8_e4m3fn, + "fp8_e5m2": torch.float8_e5m2, + "fp16": torch.float16, + "bf16": torch.bfloat16, + "fp32": torch.float32 + } + model_options = {} + if dtype := DTYPE_MAP.get(weight_dtype): + model_options["dtype"] = dtype + logging.info(f"Setting {model_name} weight dtype to {dtype}") + + if weight_dtype == "fp8_e4m3fn_fast": + model_options["dtype"] = torch.float8_e4m3fn + model_options["fp8_optimizations"] = True + + if enable_fp16_accumulation: + if hasattr(torch.backends.cuda.matmul, "allow_fp16_accumulation"): + torch.backends.cuda.matmul.allow_fp16_accumulation = True + else: + raise RuntimeError("Failed to set fp16 accumulation, this requires pytorch 2.7.1 or higher") + else: + if hasattr(torch.backends.cuda.matmul, "allow_fp16_accumulation"): + torch.backends.cuda.matmul.allow_fp16_accumulation = False + + if patch_cublaslinear: + args.fast.add("cublas_ops") + else: + args.fast.discard("cublas_ops") + + unet_path = folder_paths.get_full_path_or_raise("diffusion_models", model_name) + + sd, metadata = comfy.utils.load_torch_file(unet_path, return_metadata=True) + if extra_state_dict is not None: + extra_sd = comfy.utils.load_torch_file(extra_state_dict) + sd.update(extra_sd) + del extra_sd + + diffusion_model_prefix = comfy.sd.model_detection.unet_prefix_from_state_dict(sd) + sd = comfy.utils.state_dict_prefix_replace(sd, {diffusion_model_prefix: ""}, filter_keys=False) + + model = comfy.sd.load_diffusion_model_state_dict(sd, model_options=model_options, metadata=metadata) + if dtype := DTYPE_MAP.get(compute_dtype): + model.set_model_compute_dtype(dtype) + model.force_cast_weights = False + logging.info(f"Setting {model_name} compute dtype to {dtype}") + + if sage_attention != "disabled": + new_attention = get_sage_func(sage_attention) + def attention_override_sage(func, *args, **kwargs): + return new_attention.__wrapped__(*args, **kwargs) + + # attention override + model.model_options["transformer_options"]["optimized_attention_override"] = attention_override_sage + + return (model,) + +class ModelPatchTorchSettings: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "model": ("MODEL",), + "enable_fp16_accumulation": ("BOOLEAN", {"default": False, "tooltip": "Enable torch.backends.cuda.matmul.allow_fp16_accumulation, requires pytorch 2.7.0 nightly."}), + }} + + RETURN_TYPES = ("MODEL",) + FUNCTION = "patch" + DESCRIPTION = "Adds callbacks to model to set torch settings before and after running the model." + EXPERIMENTAL = True + CATEGORY = "KJNodes/experimental" + + def patch(self, model, enable_fp16_accumulation): + model_clone = model.clone() + + def patch_enable_fp16_accum(model): + logging.info("Patching torch settings: torch.backends.cuda.matmul.allow_fp16_accumulation = True") + torch.backends.cuda.matmul.allow_fp16_accumulation = True + def patch_disable_fp16_accum(model): + logging.info("Patching torch settings: torch.backends.cuda.matmul.allow_fp16_accumulation = False") + torch.backends.cuda.matmul.allow_fp16_accumulation = False + + if enable_fp16_accumulation: + if hasattr(torch.backends.cuda.matmul, "allow_fp16_accumulation"): + model_clone.add_callback(CallbacksMP.ON_PRE_RUN, patch_enable_fp16_accum) + model_clone.add_callback(CallbacksMP.ON_CLEANUP, patch_disable_fp16_accum) + else: + raise RuntimeError("Failed to set fp16 accumulation, this requires pytorch 2.7.1 or higher") + else: + if hasattr(torch.backends.cuda.matmul, "allow_fp16_accumulation"): + model_clone.add_callback(CallbacksMP.ON_PRE_RUN, patch_disable_fp16_accum) + else: + raise RuntimeError("Failed to set fp16 accumulation, this requires pytorch 2.7.1 or higher") + + return (model_clone,) + + +class PatchModelPatcherOrder: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "model": ("MODEL",), + "patch_order": (["object_patch_first", "weight_patch_first"], {"default": "weight_patch_first", "tooltip": "Patch the comfy patch_model function to load weight patches (LoRAs) before compiling the model"}), + "full_load": (["enabled", "disabled", "auto"], {"default": "auto", "tooltip": "Disabling may help with memory issues when loading large models, when changing this you should probably force model reload to avoid issues!"}), + }} + RETURN_TYPES = ("MODEL",) + FUNCTION = "patch" + CATEGORY = "KJNodes/deprecated" + DESCRIPTION = "NO LONGER NECESSARY OR FUNCTIONAL, keeping node for backwards compatibility. Use the TorchCompileModelAdvanced to use LoRA with torch.compile." + DEPRECATED = True + + def patch(self, model, patch_order, full_load): + return model, + + +class TorchCompileModelFluxAdvancedV2: + def __init__(self): + self._compiled = False + + @classmethod + def INPUT_TYPES(s): + return {"required": { + "model": ("MODEL",), + "backend": (["inductor", "cudagraphs"],), + "fullgraph": ("BOOLEAN", {"default": False, "tooltip": "Enable full graph mode"}), + "mode": (["default", "max-autotune", "max-autotune-no-cudagraphs", "reduce-overhead"], {"default": "default"}), + "double_blocks": ("BOOLEAN", {"default": True, "tooltip": "Compile double blocks"}), + "single_blocks": ("BOOLEAN", {"default": True, "tooltip": "Compile single blocks"}), + "dynamic": ("BOOLEAN", {"default": False, "tooltip": "Enable dynamic mode"}), + }, + "optional": { + "dynamo_cache_size_limit": ("INT", {"default": 64, "min": 0, "max": 1024, "step": 1, "tooltip": "torch._dynamo.config.cache_size_limit"}), + "force_parameter_static_shapes": ("BOOLEAN", {"default": True, "tooltip": "torch._dynamo.config.force_parameter_static_shapes"}), + } + } + RETURN_TYPES = ("MODEL",) + FUNCTION = "patch" + + CATEGORY = "KJNodes/torchcompile" + EXPERIMENTAL = True + DEPRECATED = True + DESCRIPTION = "Deprecated, use TorchCompileModelAdvanced instead." + + def patch(self, model, backend, mode, fullgraph, single_blocks, double_blocks, dynamic, dynamo_cache_size_limit=64, force_parameter_static_shapes=True): + from comfy_api.torch_helpers import set_torch_compile_wrapper + m = model.clone() + diffusion_model = m.get_model_object("diffusion_model") + torch._dynamo.config.cache_size_limit = dynamo_cache_size_limit + torch._dynamo.config.force_parameter_static_shapes = force_parameter_static_shapes + + compile_key_list = [] + + try: + if double_blocks: + for i, block in enumerate(diffusion_model.double_blocks): + print("Adding double block to compile list", i) + compile_key_list.append(f"diffusion_model.double_blocks.{i}") + if single_blocks: + for i, block in enumerate(diffusion_model.single_blocks): + compile_key_list.append(f"diffusion_model.single_blocks.{i}") + + set_torch_compile_wrapper(model=m, keys=compile_key_list, backend=backend, mode=mode, dynamic=dynamic, fullgraph=fullgraph) + except: + raise RuntimeError("Failed to compile model") + + return (m, ) + + +class TorchCompileModelWanVideoV2: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model": ("MODEL",), + "backend": (["inductor","cudagraphs"], {"default": "inductor"}), + "fullgraph": ("BOOLEAN", {"default": False, "tooltip": "Enable full graph mode"}), + "mode": (["default", "max-autotune", "max-autotune-no-cudagraphs", "reduce-overhead"], {"default": "default"}), + "dynamic": ("BOOLEAN", {"default": False, "tooltip": "Enable dynamic mode"}), + "compile_transformer_blocks_only": ("BOOLEAN", {"default": True, "tooltip": "Compile only transformer blocks, faster compile and less error prone"}), + "dynamo_cache_size_limit": ("INT", {"default": 64, "min": 0, "max": 1024, "step": 1, "tooltip": "torch._dynamo.config.cache_size_limit"}), + + }, + "optional": { + "force_parameter_static_shapes": ("BOOLEAN", {"default": True, "tooltip": "torch._dynamo.config.force_parameter_static_shapes"}), + }, + } + RETURN_TYPES = ("MODEL",) + FUNCTION = "patch" + + CATEGORY = "KJNodes/torchcompile" + EXPERIMENTAL = True + DEPRECATED = True + DESCRIPTION = "Deprecated, use TorchCompileModelAdvanced instead." + + def patch(self, model, backend, fullgraph, mode, dynamic, dynamo_cache_size_limit, compile_transformer_blocks_only, force_parameter_static_shapes=True): + from comfy_api.torch_helpers import set_torch_compile_wrapper + m = model.clone() + diffusion_model = m.get_model_object("diffusion_model") + torch._dynamo.config.cache_size_limit = dynamo_cache_size_limit + torch._dynamo.config.force_parameter_static_shapes = force_parameter_static_shapes + try: + if compile_transformer_blocks_only: + compile_key_list = [] + for i, block in enumerate(diffusion_model.blocks): + compile_key_list.append(f"diffusion_model.blocks.{i}") + else: + compile_key_list =["diffusion_model"] + + set_torch_compile_wrapper(model=m, keys=compile_key_list, backend=backend, mode=mode, dynamic=dynamic, fullgraph=fullgraph) + except: + raise RuntimeError("Failed to compile model") + + return (m, ) + + +class TorchCompileModelAdvanced: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model": ("MODEL",), + "backend": (["inductor","cudagraphs"], {"default": "inductor"}), + "fullgraph": ("BOOLEAN", {"default": False, "tooltip": "Enable full graph mode"}), + "mode": (["default", "max-autotune", "max-autotune-no-cudagraphs", "reduce-overhead"], {"default": "default"}), + "dynamic": ( + ["auto", "true", "false"], + {"default": "auto", "tooltip": "Use dynamic shape tracing."}, + ), + "compile_transformer_blocks_only": ("BOOLEAN", {"default": True, "tooltip": "Compile only transformer blocks, faster compile and less error prone"}), + "dynamo_cache_size_limit": ("INT", {"default": 64, "min": 0, "max": 1024, "step": 1, "tooltip": "torch._dynamo.config.cache_size_limit"}), + "debug_compile_keys": ("BOOLEAN", {"default": False, "tooltip": "Print the compile keys used for torch.compile"}), + }, + "optional": { + "disable_dynamic_vram": ("BOOLEAN", {"default": False, "tooltip": "Disable dynamic VRAM feature as it can cause issues with compile"}), + } + } + RETURN_TYPES = ("MODEL",) + FUNCTION = "patch" + CATEGORY = "KJNodes/torchcompile" + DESCRIPTION = "Advanced torch.compile patching for diffusion models." + EXPERIMENTAL = True + + def patch(self, model, backend, fullgraph, mode, dynamic, dynamo_cache_size_limit, compile_transformer_blocks_only, debug_compile_keys, disable_dynamic_vram=False): + from comfy_api.torch_helpers import set_torch_compile_wrapper + if disable_dynamic_vram: + try: + m = model.clone(disable_dynamic=True) + except TypeError: + logging.warning("This ComfyUI version do not support disabling dynamic VRAM through a node. This may cause issues with torch.compile.") + m = model.clone() + else: + m = model.clone() + + diffusion_model = m.get_model_object("diffusion_model") + torch._dynamo.config.cache_size_limit = dynamo_cache_size_limit + + try: + if compile_transformer_blocks_only: + layer_types = ["double_blocks", "single_blocks", "layers", "transformer_blocks", "blocks", "visual_transformer_blocks", "text_transformer_blocks"] + compile_key_list = [] + for layer_name in layer_types: + if hasattr(diffusion_model, layer_name): + blocks = getattr(diffusion_model, layer_name) + for i in range(len(blocks)): + compile_key_list.append(f"diffusion_model.{layer_name}.{i}") + if not compile_key_list: + logging.warning("No known transformer blocks found to compile, compiling entire diffusion model instead") + elif debug_compile_keys: + logging.info("TorchCompileModelAdvanced: Compile key list:") + for key in compile_key_list: + logging.info(f" - {key}") + if not compile_key_list: + compile_key_list =["diffusion_model"] + + dynamic_kv = {"true": True, "false": False, "auto": None} + try: + dynamic = dynamic_kv[dynamic] + except KeyError: + raise ValueError(f"Invalid dynamic arg {dynamic}") + + set_torch_compile_wrapper(model=m, keys=compile_key_list, backend=backend, mode=mode, dynamic=dynamic, fullgraph=fullgraph) + except: + raise RuntimeError("Failed to compile model") + + return (m, ) + + +class TorchCompileModelQwenImage: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model": ("MODEL",), + "backend": (["inductor","cudagraphs"], {"default": "inductor"}), + "fullgraph": ("BOOLEAN", {"default": False, "tooltip": "Enable full graph mode"}), + "mode": (["default", "max-autotune", "max-autotune-no-cudagraphs", "reduce-overhead"], {"default": "default"}), + "dynamic": ("BOOLEAN", {"default": False, "tooltip": "Enable dynamic mode"}), + "compile_transformer_blocks_only": ("BOOLEAN", {"default": True, "tooltip": "Compile only transformer blocks, faster compile and less error prone"}), + "dynamo_cache_size_limit": ("INT", {"default": 64, "min": 0, "max": 1024, "step": 1, "tooltip": "torch._dynamo.config.cache_size_limit"}), + }, + } + RETURN_TYPES = ("MODEL",) + FUNCTION = "patch" + + CATEGORY = "KJNodes/torchcompile" + EXPERIMENTAL = True + DEPRECATED = True + DESCRIPTION = "Deprecated, use TorchCompileModelAdvanced instead." + + def patch(self, model, backend, fullgraph, mode, dynamic, dynamo_cache_size_limit, compile_transformer_blocks_only): + from comfy_api.torch_helpers import set_torch_compile_wrapper + m = model.clone() + diffusion_model = m.get_model_object("diffusion_model") + torch._dynamo.config.cache_size_limit = dynamo_cache_size_limit + try: + if compile_transformer_blocks_only: + compile_key_list = [] + for i, block in enumerate(diffusion_model.transformer_blocks): + compile_key_list.append(f"diffusion_model.transformer_blocks.{i}") + else: + compile_key_list =["diffusion_model"] + + set_torch_compile_wrapper(model=m, keys=compile_key_list, backend=backend, mode=mode, dynamic=dynamic, fullgraph=fullgraph) + except: + raise RuntimeError("Failed to compile model") + + return (m, ) + +class TorchCompileVAE: + def __init__(self): + self._compiled_encoder = False + self._compiled_decoder = False + + @classmethod + def INPUT_TYPES(s): + return {"required": { + "vae": ("VAE",), + "backend": (["inductor", "cudagraphs"],), + "fullgraph": ("BOOLEAN", {"default": False, "tooltip": "Enable full graph mode"}), + "mode": (["default", "max-autotune", "max-autotune-no-cudagraphs", "reduce-overhead"], {"default": "default"}), + "compile_encoder": ("BOOLEAN", {"default": True, "tooltip": "Compile encoder"}), + "compile_decoder": ("BOOLEAN", {"default": True, "tooltip": "Compile decoder"}), + }} + RETURN_TYPES = ("VAE",) + FUNCTION = "compile" + + CATEGORY = "KJNodes/torchcompile" + EXPERIMENTAL = True + + def compile(self, vae, backend, mode, fullgraph, compile_encoder, compile_decoder): + if compile_encoder: + if not self._compiled_encoder: + encoder_name = "encoder" + if hasattr(vae.first_stage_model, "taesd_encoder"): + encoder_name = "taesd_encoder" + + try: + setattr( + vae.first_stage_model, + encoder_name, + torch.compile( + getattr(vae.first_stage_model, encoder_name), + mode=mode, + fullgraph=fullgraph, + backend=backend, + ), + ) + self._compiled_encoder = True + except: + raise RuntimeError("Failed to compile model") + if compile_decoder: + if not self._compiled_decoder: + decoder_name = "decoder" + if hasattr(vae.first_stage_model, "taesd_decoder"): + decoder_name = "taesd_decoder" + + try: + setattr( + vae.first_stage_model, + decoder_name, + torch.compile( + getattr(vae.first_stage_model, decoder_name), + mode=mode, + fullgraph=fullgraph, + backend=backend, + ), + ) + self._compiled_decoder = True + except: + raise RuntimeError("Failed to compile model") + return (vae, ) + +class TorchCompileControlNet: + def __init__(self): + self._compiled= False + + @classmethod + def INPUT_TYPES(s): + return {"required": { + "controlnet": ("CONTROL_NET",), + "backend": (["inductor", "cudagraphs"],), + "fullgraph": ("BOOLEAN", {"default": False, "tooltip": "Enable full graph mode"}), + "mode": (["default", "max-autotune", "max-autotune-no-cudagraphs", "reduce-overhead"], {"default": "default"}), + }} + RETURN_TYPES = ("CONTROL_NET",) + FUNCTION = "compile" + + CATEGORY = "KJNodes/torchcompile" + EXPERIMENTAL = True + + def compile(self, controlnet, backend, mode, fullgraph): + if not self._compiled: + try: + # for i, block in enumerate(controlnet.control_model.double_blocks): + # print("Compiling controlnet double_block", i) + # controlnet.control_model.double_blocks[i] = torch.compile(block, mode=mode, fullgraph=fullgraph, backend=backend) + controlnet.control_model = torch.compile(controlnet.control_model, mode=mode, fullgraph=fullgraph, backend=backend) + self._compiled = True + except: + self._compiled = False + raise RuntimeError("Failed to compile model") + + return (controlnet, ) + + +#teacache + +try: + from comfy.ldm.wan.model import sinusoidal_embedding_1d +except: + pass + +from unittest.mock import patch +import numpy as np + +def relative_l1_distance(last_tensor, current_tensor): + l1_distance = torch.abs(last_tensor - current_tensor).mean() + norm = torch.abs(last_tensor).mean() + relative_l1_distance = l1_distance / norm + return relative_l1_distance.to(torch.float32) + +@torch.compiler.disable() +def tea_cache(self, x, e0, e, transformer_options): + #teacache for cond and uncond separately + rel_l1_thresh = transformer_options["rel_l1_thresh"] + + is_cond = True if transformer_options["cond_or_uncond"] == [0] else False + + should_calc = True + suffix = "cond" if is_cond else "uncond" + + # Init cache dict if not exists + if not hasattr(self, 'teacache_state'): + self.teacache_state = { + 'cond': {'accumulated_rel_l1_distance': 0, 'prev_input': None, + 'teacache_skipped_steps': 0, 'previous_residual': None}, + 'uncond': {'accumulated_rel_l1_distance': 0, 'prev_input': None, + 'teacache_skipped_steps': 0, 'previous_residual': None} + } + logging.info("\nTeaCache: Initialized") + + cache = self.teacache_state[suffix] + + if cache['prev_input'] is not None: + if transformer_options["coefficients"] == []: + temb_relative_l1 = relative_l1_distance(cache['prev_input'], e0) + curr_acc_dist = cache['accumulated_rel_l1_distance'] + temb_relative_l1 + else: + rescale_func = np.poly1d(transformer_options["coefficients"]) + curr_acc_dist = cache['accumulated_rel_l1_distance'] + rescale_func(((e-cache['prev_input']).abs().mean() / cache['prev_input'].abs().mean()).cpu().item()) + try: + if curr_acc_dist < rel_l1_thresh: + should_calc = False + cache['accumulated_rel_l1_distance'] = curr_acc_dist + else: + should_calc = True + cache['accumulated_rel_l1_distance'] = 0 + except: + should_calc = True + cache['accumulated_rel_l1_distance'] = 0 + + if transformer_options["coefficients"] == []: + cache['prev_input'] = e0.clone().detach() + else: + cache['prev_input'] = e.clone().detach() + + if not should_calc: + x += cache['previous_residual'].to(x.device) + cache['teacache_skipped_steps'] += 1 + #print(f"TeaCache: Skipping {suffix} step") + return should_calc, cache + +def teacache_wanvideo_vace_forward_orig(self, x, t, context, vace_context, vace_strength, clip_fea=None, freqs=None, transformer_options={}, **kwargs): + # embeddings + x = self.patch_embedding(x.float()).to(x.dtype) + grid_sizes = x.shape[2:] + x = x.flatten(2).transpose(1, 2) + + # time embeddings + e = self.time_embedding( + sinusoidal_embedding_1d(self.freq_dim, t).to(dtype=x[0].dtype)) + e0 = self.time_projection(e).unflatten(1, (6, self.dim)) + + # context + context = self.text_embedding(context) + + context_img_len = None + if clip_fea is not None: + if self.img_emb is not None: + context_clip = self.img_emb(clip_fea) # bs x 257 x dim + context = torch.concat([context_clip, context], dim=1) + context_img_len = clip_fea.shape[-2] + + orig_shape = list(vace_context.shape) + vace_context = vace_context.movedim(0, 1).reshape([-1] + orig_shape[2:]) + c = self.vace_patch_embedding(vace_context.float()).to(vace_context.dtype) + c = c.flatten(2).transpose(1, 2) + c = list(c.split(orig_shape[0], dim=0)) + + if not transformer_options: + raise RuntimeError("Can't access transformer_options, this requires ComfyUI nightly version from Mar 14, 2025 or later") + + teacache_enabled = transformer_options.get("teacache_enabled", False) + if not teacache_enabled: + should_calc = True + else: + should_calc, cache = tea_cache(self, x, e0, e, transformer_options) + + if should_calc: + original_x = x.clone().detach() + patches_replace = transformer_options.get("patches_replace", {}) + blocks_replace = patches_replace.get("dit", {}) + for i, block in enumerate(self.blocks): + if ("double_block", i) in blocks_replace: + def block_wrap(args): + out = {} + out["img"] = block(args["img"], context=args["txt"], e=args["vec"], freqs=args["pe"], context_img_len=context_img_len) + return out + out = blocks_replace[("double_block", i)]({"img": x, "txt": context, "vec": e0, "pe": freqs}, {"original_block": block_wrap, "transformer_options": transformer_options}) + x = out["img"] + else: + x = block(x, e=e0, freqs=freqs, context=context, context_img_len=context_img_len) + + ii = self.vace_layers_mapping.get(i, None) + if ii is not None: + for iii in range(len(c)): + c_skip, c[iii] = self.vace_blocks[ii](c[iii], x=original_x, e=e0, freqs=freqs, context=context, context_img_len=context_img_len) + x += c_skip * vace_strength[iii] + del c_skip + + if teacache_enabled: + cache['previous_residual'] = (x - original_x).to(transformer_options["teacache_device"]) + + # head + x = self.head(x, e) + + # unpatchify + x = self.unpatchify(x, grid_sizes) + return x + +def teacache_wanvideo_forward_orig(self, x, t, context, clip_fea=None, freqs=None, transformer_options={}, **kwargs): + # embeddings + x = self.patch_embedding(x.float()).to(x.dtype) + grid_sizes = x.shape[2:] + x = x.flatten(2).transpose(1, 2) + + # time embeddings + e = self.time_embedding( + sinusoidal_embedding_1d(self.freq_dim, t).to(dtype=x[0].dtype)) + e0 = self.time_projection(e).unflatten(1, (6, self.dim)) + + # context + context = self.text_embedding(context) + + context_img_len = None + if clip_fea is not None: + if self.img_emb is not None: + context_clip = self.img_emb(clip_fea) # bs x 257 x dim + context = torch.concat([context_clip, context], dim=1) + context_img_len = clip_fea.shape[-2] + + + teacache_enabled = transformer_options.get("teacache_enabled", False) + if not teacache_enabled: + should_calc = True + else: + should_calc, cache = tea_cache(self, x, e0, e, transformer_options) + + if should_calc: + original_x = x.clone().detach() + patches_replace = transformer_options.get("patches_replace", {}) + blocks_replace = patches_replace.get("dit", {}) + for i, block in enumerate(self.blocks): + if ("double_block", i) in blocks_replace: + def block_wrap(args): + out = {} + out["img"] = block(args["img"], context=args["txt"], e=args["vec"], freqs=args["pe"], context_img_len=context_img_len) + return out + out = blocks_replace[("double_block", i)]({"img": x, "txt": context, "vec": e0, "pe": freqs}, {"original_block": block_wrap, "transformer_options": transformer_options}) + x = out["img"] + else: + x = block(x, e=e0, freqs=freqs, context=context, context_img_len=context_img_len) + + if teacache_enabled: + cache['previous_residual'] = (x - original_x).to(transformer_options["teacache_device"]) + + # head + x = self.head(x, e) + + # unpatchify + x = self.unpatchify(x, grid_sizes) + return x + +class WanVideoTeaCacheKJ: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model": ("MODEL",), + "rel_l1_thresh": ("FLOAT", {"default": 0.275, "min": 0.0, "max": 10.0, "step": 0.001, "tooltip": "Threshold for to determine when to apply the cache, compromise between speed and accuracy. When using coefficients a good value range is something between 0.2-0.4 for all but 1.3B model, which should be about 10 times smaller, same as when not using coefficients."}), + "start_percent": ("FLOAT", {"default": 0.1, "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "The start percentage of the steps to use with TeaCache."}), + "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "The end percentage of the steps to use with TeaCache."}), + "cache_device": (["main_device", "offload_device"], {"default": "offload_device", "tooltip": "Device to cache to"}), + "coefficients": (["disabled", "1.3B", "14B", "i2v_480", "i2v_720"], {"default": "i2v_480", "tooltip": "Coefficients for rescaling the relative l1 distance, if disabled the threshold value should be about 10 times smaller than the value used with coefficients."}), + } + } + + RETURN_TYPES = ("MODEL",) + RETURN_NAMES = ("model",) + FUNCTION = "patch_teacache" + CATEGORY = "KJNodes/deprecated" + DEPRECATED = True + DESCRIPTION = """ +Patch WanVideo model to use TeaCache. Speeds up inference by caching the output and +applying it instead of doing the step. Best results are achieved by choosing the +appropriate coefficients for the model. Early steps should never be skipped, with too +aggressive values this can happen and the motion suffers. Starting later can help with that too. +When NOT using coefficients, the threshold value should be +about 10 times smaller than the value used with coefficients. + +Official recommended values https://github.com/ali-vilab/TeaCache/tree/main/TeaCache4Wan2.1 +""" + EXPERIMENTAL = True + + def patch_teacache(self, model, rel_l1_thresh, start_percent, end_percent, cache_device, coefficients): + if rel_l1_thresh == 0: + return (model,) + + if coefficients == "disabled" and rel_l1_thresh > 0.1: + logging.warning("Threshold value is too high for TeaCache without coefficients, consider using coefficients for better results.") + if coefficients != "disabled" and rel_l1_thresh < 0.1 and "1.3B" not in coefficients: + logging.warning("Threshold value is too low for TeaCache with coefficients, consider using higher threshold value for better results.") + + # type_str = str(type(model.model.model_config).__name__) + #if model.model.diffusion_model.dim == 1536: + # model_type ="1.3B" + # else: + # if "WAN21_T2V" in type_str: + # model_type = "14B" + # elif "WAN21_I2V" in type_str: + # model_type = "i2v_480" + # else: + # model_type = "i2v_720" #how to detect this? + + + teacache_coefficients_map = { + "disabled": [], + "1.3B": [2.39676752e+03, -1.31110545e+03, 2.01331979e+02, -8.29855975e+00, 1.37887774e-01], + "14B": [-5784.54975374, 5449.50911966, -1811.16591783, 256.27178429, -13.02252404], + "i2v_480": [-3.02331670e+02, 2.23948934e+02, -5.25463970e+01, 5.87348440e+00, -2.01973289e-01], + "i2v_720": [-114.36346466, 65.26524496, -18.82220707, 4.91518089, -0.23412683], + } + coefficients = teacache_coefficients_map[coefficients] + + teacache_device = mm.get_torch_device() if cache_device == "main_device" else mm.unet_offload_device() + + model_clone = model.clone() + if 'transformer_options' not in model_clone.model_options: + model_clone.model_options['transformer_options'] = {} + model_clone.model_options["transformer_options"]["rel_l1_thresh"] = rel_l1_thresh + model_clone.model_options["transformer_options"]["teacache_device"] = teacache_device + model_clone.model_options["transformer_options"]["coefficients"] = coefficients + diffusion_model = model_clone.get_model_object("diffusion_model") + + def outer_wrapper(start_percent, end_percent): + def unet_wrapper_function(model_function, kwargs): + input = kwargs["input"] + timestep = kwargs["timestep"] + c = kwargs["c"] + sigmas = c["transformer_options"]["sample_sigmas"] + cond_or_uncond = kwargs["cond_or_uncond"] + last_step = (len(sigmas) - 1) + + matched_step_index = (sigmas == timestep[0] ).nonzero() + if len(matched_step_index) > 0: + current_step_index = matched_step_index.item() + else: + for i in range(len(sigmas) - 1): + # walk from beginning of steps until crossing the timestep + if (sigmas[i] - timestep[0]) * (sigmas[i + 1] - timestep[0]) <= 0: + current_step_index = i + break + else: + current_step_index = 0 + + if current_step_index == 0: + if (len(cond_or_uncond) == 1 and cond_or_uncond[0] == 1) or len(cond_or_uncond) == 2: + if hasattr(diffusion_model, "teacache_state"): + delattr(diffusion_model, "teacache_state") + logging.info("\nResetting TeaCache state") + + current_percent = current_step_index / (len(sigmas) - 1) + c["transformer_options"]["current_percent"] = current_percent + if start_percent <= current_percent <= end_percent: + c["transformer_options"]["teacache_enabled"] = True + + forward_function = teacache_wanvideo_vace_forward_orig if hasattr(diffusion_model, "vace_layers") else teacache_wanvideo_forward_orig + context = patch.multiple( + diffusion_model, + forward_orig=forward_function.__get__(diffusion_model, diffusion_model.__class__) + ) + + with context: + out = model_function(input, timestep, **c) + if current_step_index+1 == last_step and hasattr(diffusion_model, "teacache_state"): + if len(cond_or_uncond) == 1 and cond_or_uncond[0] == 0: + skipped_steps_cond = diffusion_model.teacache_state["cond"]["teacache_skipped_steps"] + skipped_steps_uncond = diffusion_model.teacache_state["uncond"]["teacache_skipped_steps"] + logging.info("-----------------------------------") + logging.info(f"TeaCache skipped:") + logging.info(f"{skipped_steps_cond} cond steps") + logging.info(f"{skipped_steps_uncond} uncond step") + logging.info(f"out of {last_step} steps") + logging.info("-----------------------------------") + elif len(cond_or_uncond) == 2: + skipped_steps_cond = diffusion_model.teacache_state["uncond"]["teacache_skipped_steps"] + logging.info("-----------------------------------") + logging.info(f"TeaCache skipped:") + logging.info(f"{skipped_steps_cond} cond steps") + logging.info(f"out of {last_step} steps") + logging.info("-----------------------------------") + + return out + return unet_wrapper_function + + model_clone.set_model_unet_function_wrapper(outer_wrapper(start_percent=start_percent, end_percent=end_percent)) + + return (model_clone,) + + + + +from comfy.ldm.flux.math import apply_rope + +def modified_wan_self_attention_forward(self, x, freqs, transformer_options={}): + r""" + Args: + x(Tensor): Shape [B, L, num_heads, C / num_heads] + freqs(Tensor): Rope freqs, shape [1024, C / num_heads / 2] + """ + b, s, n, d = *x.shape[:2], self.num_heads, self.head_dim + + # query, key, value function + def qkv_fn(x): + q = self.norm_q(self.q(x)).view(b, s, n, d) + k = self.norm_k(self.k(x)).view(b, s, n, d) + v = self.v(x).view(b, s, n * d) + return q, k, v + + q, k, v = qkv_fn(x) + + q, k = apply_rope(q, k, freqs) + + feta_scores = get_feta_scores(q, k, self.num_frames, self.enhance_weight) + + try: + x = comfy.ldm.modules.attention.optimized_attention( + q.view(b, s, n * d), + k.view(b, s, n * d), + v, + heads=self.num_heads, + transformer_options=transformer_options, + ) + except: + # backward compatibility for now + x = comfy.ldm.modules.attention.attention( + q.view(b, s, n * d), + k.view(b, s, n * d), + v, + heads=self.num_heads, + ) + + x = self.o(x) + + x *= feta_scores + + return x + +from einops import rearrange +def get_feta_scores(query, key, num_frames, enhance_weight, num_heads=12): + img_q, img_k = query, key #torch.Size([2, 9216, 12, 128]) + + if img_q.ndim == 4: + B, ST, num_heads, head_dim = img_q.shape + elif img_q.ndim == 3: + B, ST, hidden_dim = img_q.shape + head_dim = hidden_dim // num_heads + + # Reshape from [B, ST, hidden_dim] to [B, ST, num_heads, head_dim] + img_q = img_q.view(B, ST, num_heads, head_dim) + img_k = img_k.view(B, ST, num_heads, head_dim) + + spatial_dim = ST // num_frames + + query_image = rearrange( + img_q, "B (T S) N C -> (B S) N T C", T=num_frames, S=spatial_dim, N=num_heads, C=head_dim + ) + key_image = rearrange( + img_k, "B (T S) N C -> (B S) N T C", T=num_frames, S=spatial_dim, N=num_heads, C=head_dim + ) + + return feta_score(query_image, key_image, head_dim, num_frames, enhance_weight) + +def feta_score(query_image, key_image, head_dim, num_frames, enhance_weight): + scale = head_dim**-0.5 + query_image = query_image * scale + attn_temp = query_image @ key_image.transpose(-2, -1) # translate attn to float32 + attn_temp = attn_temp.to(torch.float32) + attn_temp = attn_temp.softmax(dim=-1) + + # Reshape to [batch_size * num_tokens, num_frames, num_frames] + attn_temp = attn_temp.reshape(-1, num_frames, num_frames) + + # Create a mask for diagonal elements + diag_mask = torch.eye(num_frames, device=attn_temp.device).bool() + diag_mask = diag_mask.unsqueeze(0).expand(attn_temp.shape[0], -1, -1) + + # Zero out diagonal elements + attn_wo_diag = attn_temp.masked_fill(diag_mask, 0) + + # Calculate mean for each token's attention matrix + # Number of off-diagonal elements per matrix is n*n - n + num_off_diag = num_frames * num_frames - num_frames + mean_scores = attn_wo_diag.sum(dim=(1, 2)) / num_off_diag + + enhance_scores = mean_scores.mean() * (num_frames + enhance_weight) + enhance_scores = enhance_scores.clamp(min=1) + return enhance_scores + +import types +class WanAttentionPatch: + def __init__(self, num_frames, weight): + self.num_frames = num_frames + self.enhance_weight = weight + + def __get__(self, obj, objtype=None): + # Create bound method with stored parameters + def wrapped_attention(self_module, *args, **kwargs): + self_module.num_frames = self.num_frames + self_module.enhance_weight = self.enhance_weight + return modified_wan_self_attention_forward(self_module, *args, **kwargs) + return types.MethodType(wrapped_attention, obj) + +class WanVideoEnhanceAVideoKJ: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model": ("MODEL",), + "latent": ("LATENT", {"tooltip": "Only used to get the latent count"}), + "weight": ("FLOAT", {"default": 2.0, "min": 0.0, "max": 10.0, "step": 0.001, "tooltip": "Strength of the enhance effect"}), + } + } + + RETURN_TYPES = ("MODEL",) + RETURN_NAMES = ("model",) + FUNCTION = "enhance" + CATEGORY = "KJNodes/wan" + DESCRIPTION = "https://github.com/NUS-HPC-AI-Lab/Enhance-A-Video" + EXPERIMENTAL = True + + def enhance(self, model, weight, latent): + if weight == 0: + return (model,) + + num_frames = latent["samples"].shape[2] + + model_clone = model.clone() + if 'transformer_options' not in model_clone.model_options: + model_clone.model_options['transformer_options'] = {} + model_clone.model_options["transformer_options"]["enhance_weight"] = weight + diffusion_model = model_clone.get_model_object("diffusion_model") + + compile_settings = getattr(model.model, "compile_settings", None) + for idx, block in enumerate(diffusion_model.blocks): + patched_attn = WanAttentionPatch(num_frames, weight).__get__(block.self_attn, block.__class__) + if compile_settings is not None: + patched_attn = torch.compile(patched_attn, mode=compile_settings["mode"], dynamic=compile_settings["dynamic"], fullgraph=compile_settings["fullgraph"], backend=compile_settings["backend"]) + + model_clone.add_object_patch(f"diffusion_model.blocks.{idx}.self_attn.forward", patched_attn) + + return (model_clone,) + +try: + from comfy.ldm.lightricks.model import apply_rotary_emb +except: + apply_rotary_emb = None + + +def ltxv_feta_forward(self, x, context=None, mask=None, pe=None, k_pe=None, transformer_options={}): + q = self.to_q(x) + context = x if context is None else context + k = self.to_k(context) + v = self.to_v(context) + + q = self.q_norm(q) + k = self.k_norm(k) + + if pe is not None: + q = apply_rotary_emb(q, pe) + k = apply_rotary_emb(k, pe if k_pe is None else k_pe) + + feta_scores = get_feta_scores(q, k, self.num_frames, self.enhance_weight, self.heads) + + if mask is None: + out = comfy.ldm.modules.attention.optimized_attention(q, k, v, self.heads, attn_precision=self.attn_precision, transformer_options=transformer_options) + else: + out = comfy.ldm.modules.attention.optimized_attention_masked(q, k, v, self.heads, mask, attn_precision=self.attn_precision, transformer_options=transformer_options) + + if self.to_gate_logits is not None: + gate_logits = self.to_gate_logits(x) # (B, T, H) + b, t, _ = out.shape + out = out.view(b, t, self.heads, self.dim_head) + gates = 2.0 * torch.sigmoid(gate_logits) # zero-init -> identity + out = out * gates.unsqueeze(-1) + out = out.view(b, t, self.heads * self.dim_head) + + return self.to_out(out) * feta_scores + + +class LTXCrossAttentionPatch: + def __init__(self, num_frames, weight): + self.num_frames = num_frames + self.enhance_weight = weight + + def __get__(self, obj, objtype=None): + # Create bound method with stored parameters + def wrapped_attention(self_module, *args, **kwargs): + self_module.num_frames = self.num_frames + self_module.enhance_weight = self.enhance_weight + return ltxv_feta_forward(self_module, *args, **kwargs) + return types.MethodType(wrapped_attention, obj) + +class LTXVEnhanceAVideoKJ: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model": ("MODEL",), + "latent": ("LATENT", {"tooltip": "Only used to get the latent count"}), + "weight": ("FLOAT", {"default": 4.0, "min": 0.0, "max": 100.0, "step": 0.001, "tooltip": "Strength of the enhance effect"}), + } + } + + RETURN_TYPES = ("MODEL",) + RETURN_NAMES = ("model",) + FUNCTION = "enhance" + CATEGORY = "KJNodes/ltxv" + DESCRIPTION = "https://github.com/NUS-HPC-AI-Lab/Enhance-A-Video" + EXPERIMENTAL = True + + def enhance(self, model, weight, latent): + if weight == 0: + return (model,) + + num_frames = latent["samples"].shape[2] + + model_clone = model.clone() + if 'transformer_options' not in model_clone.model_options: + model_clone.model_options['transformer_options'] = {} + model_clone.model_options["transformer_options"]["enhance_weight"] = weight + diffusion_model = model_clone.get_model_object("diffusion_model") + + for idx, block in enumerate(diffusion_model.transformer_blocks): + patched_attn1 = LTXCrossAttentionPatch(num_frames, weight).__get__(block.attn1, block.__class__) + model_clone.add_object_patch(f"diffusion_model.transformer_blocks.{idx}.attn1.forward", patched_attn1) + return (model_clone,) + +def normalized_attention_guidance(self, query, context_positive, context_negative, transformer_options={}): + k_positive = self.norm_k(self.k(context_positive)) + v_positive = self.v(context_positive) + k_negative = self.norm_k(self.k(context_negative)) + v_negative = self.v(context_negative) + + try: + x_positive = comfy.ldm.modules.attention.optimized_attention(query, k_positive, v_positive, heads=self.num_heads, transformer_options=transformer_options).flatten(2) + x_negative = comfy.ldm.modules.attention.optimized_attention(query, k_negative, v_negative, heads=self.num_heads, transformer_options=transformer_options).flatten(2) + except: #backwards compatibility for now + x_positive = comfy.ldm.modules.attention.optimized_attention(query, k_positive, v_positive, heads=self.num_heads).flatten(2) + x_negative = comfy.ldm.modules.attention.optimized_attention(query, k_negative, v_negative, heads=self.num_heads).flatten(2) + + nag_guidance = x_positive * self.nag_scale - x_negative * (self.nag_scale - 1) + + norm_positive = torch.norm(x_positive, p=1, dim=-1, keepdim=True).expand_as(x_positive) + norm_guidance = torch.norm(nag_guidance, p=1, dim=-1, keepdim=True).expand_as(nag_guidance) + + scale = torch.nan_to_num(norm_guidance / norm_positive, nan=10.0) + + mask = scale > self.nag_tau + adjustment = (norm_positive * self.nag_tau) / (norm_guidance + 1e-7) + nag_guidance = torch.where(mask, nag_guidance * adjustment, nag_guidance) + + x = nag_guidance * self.nag_alpha + x_positive * (1 - self.nag_alpha) + del nag_guidance + + return x + +#region NAG +def wan_crossattn_forward_nag(self, x, context, transformer_options={}, **kwargs): + r""" + Args: + x(Tensor): Shape [B, L1, C] + context(Tensor): Shape [B, L2, C] + """ + # Determine batch splitting and context handling + if self.input_type == "default": + # Single or [pos, neg] pair + if context.shape[0] == 1: + x_pos, context_pos = x, context + x_neg, context_neg = None, None + else: + x_pos, x_neg = torch.chunk(x, 2, dim=0) + context_pos, context_neg = torch.chunk(context, 2, dim=0) + elif self.input_type == "batch": + # Standard batch, no CFG + x_pos, context_pos = x, context + x_neg, context_neg = None, None + + # Positive branch + q_pos = self.norm_q(self.q(x_pos)) + nag_context = self.nag_context + if self.input_type == "batch": + nag_context = nag_context.repeat(x_pos.shape[0], 1, 1) + try: + x_pos_out = normalized_attention_guidance(self, q_pos, context_pos, nag_context, transformer_options=transformer_options) + except: #backwards compatibility for now + x_pos_out = normalized_attention_guidance(self, q_pos, context_pos, nag_context) + + # Negative branch + if x_neg is not None and context_neg is not None: + q_neg = self.norm_q(self.q(x_neg)) + k_neg = self.norm_k(self.k(context_neg)) + v_neg = self.v(context_neg) + try: + x_neg_out = comfy.ldm.modules.attention.optimized_attention(q_neg, k_neg, v_neg, heads=self.num_heads, transformer_options=transformer_options) + except: #backwards compatibility for now + x_neg_out = comfy.ldm.modules.attention.optimized_attention(q_neg, k_neg, v_neg, heads=self.num_heads) + x = torch.cat([x_pos_out, x_neg_out], dim=0) + else: + x = x_pos_out + + return self.o(x) + + +def wan_i2v_crossattn_forward_nag(self, x, context, context_img_len, transformer_options={}, **kwargs): + r""" + Args: + x(Tensor): Shape [B, L1, C] + context(Tensor): Shape [B, L2, C] + """ + context_img = context[:, :context_img_len] + context = context[:, context_img_len:] + + q_img = self.norm_q(self.q(x)) + k_img = self.norm_k_img(self.k_img(context_img)) + v_img = self.v_img(context_img) + try: + img_x = comfy.ldm.modules.attention.optimized_attention(q_img, k_img, v_img, heads=self.num_heads, transformer_options=transformer_options) + except: #backwards compatibility for now + img_x = comfy.ldm.modules.attention.optimized_attention(q_img, k_img, v_img, heads=self.num_heads) + + if context.shape[0] == 2: + x, x_real_negative = torch.chunk(x, 2, dim=0) + context_positive, context_negative = torch.chunk(context, 2, dim=0) + else: + context_positive = context + context_negative = None + + q = self.norm_q(self.q(x)) + + x = normalized_attention_guidance(self, q, context_positive, self.nag_context, transformer_options=transformer_options) + + if context_negative is not None: + q_real_negative = self.norm_q(self.q(x_real_negative)) + k_real_negative = self.norm_k(self.k(context_negative)) + v_real_negative = self.v(context_negative) + try: + x_real_negative = comfy.ldm.modules.attention.optimized_attention(q_real_negative, k_real_negative, v_real_negative, heads=self.num_heads, transformer_options=transformer_options) + except: #backwards compatibility for now + x_real_negative = comfy.ldm.modules.attention.optimized_attention(q_real_negative, k_real_negative, v_real_negative, heads=self.num_heads) + x = torch.cat([x, x_real_negative], dim=0) + + # output + x = x + img_x + x = self.o(x) + return x + +class WanCrossAttentionPatch: + def __init__(self, context, nag_scale, nag_alpha, nag_tau, i2v=False, input_type="default"): + self.nag_context = context + self.nag_scale = nag_scale + self.nag_alpha = nag_alpha + self.nag_tau = nag_tau + self.i2v = i2v + self.input_type = input_type + def __get__(self, obj, objtype=None): + # Create bound method with stored parameters + def wrapped_attention(self_module, *args, **kwargs): + self_module.nag_context = self.nag_context + self_module.nag_scale = self.nag_scale + self_module.nag_alpha = self.nag_alpha + self_module.nag_tau = self.nag_tau + self_module.input_type = self.input_type + if self.i2v: + return wan_i2v_crossattn_forward_nag(self_module, *args, **kwargs) + else: + return wan_crossattn_forward_nag(self_module, *args, **kwargs) + return types.MethodType(wrapped_attention, obj) + +class WanVideoNAG: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model": ("MODEL",), + "conditioning": ("CONDITIONING",), + "nag_scale": ("FLOAT", {"default": 11.0, "min": 0.0, "max": 100.0, "step": 0.001, "tooltip": "Strength of negative guidance effect"}), + "nag_alpha": ("FLOAT", {"default": 0.25, "min": 0.0, "max": 1.0, "step": 0.001, "tooltip": "Mixing coefficient in that controls the balance between the normalized guided representation and the original positive representation."}), + "nag_tau": ("FLOAT", {"default": 2.5, "min": 0.0, "max": 10.0, "step": 0.001, "tooltip": "Clipping threshold that controls how much the guided attention can deviate from the positive attention."}), + }, + "optional": { + "input_type": (["default", "batch"], {"tooltip": "Type of the model input"}), + }, + + } + + RETURN_TYPES = ("MODEL",) + RETURN_NAMES = ("model",) + FUNCTION = "patch" + CATEGORY = "KJNodes/wan" + DESCRIPTION = "https://github.com/ChenDarYen/Normalized-Attention-Guidance" + EXPERIMENTAL = True + + def patch(self, model, conditioning, nag_scale, nag_alpha, nag_tau, input_type="default"): + if nag_scale == 0: + return (model,) + + device = mm.get_torch_device() + dtype = mm.unet_dtype() + + model_clone = model.clone() + + diffusion_model = model_clone.get_model_object("diffusion_model") + + diffusion_model.text_embedding.to(device) + context = diffusion_model.text_embedding(conditioning[0][0].to(device, dtype)) + + type_str = str(type(model.model.model_config).__name__) + i2v = True if "WAN21_I2V" in type_str else False + + for idx, block in enumerate(diffusion_model.blocks): + patched_attn = WanCrossAttentionPatch(context, nag_scale, nag_alpha, nag_tau, i2v, input_type=input_type).__get__(block.cross_attn, block.__class__) + + model_clone.add_object_patch(f"diffusion_model.blocks.{idx}.cross_attn.forward", patched_attn) + + return (model_clone,) + +class SkipLayerGuidanceWanVideo: + @classmethod + def INPUT_TYPES(s): + return {"required": {"model": ("MODEL", ), + "blocks": ("STRING", {"default": "10", "multiline": False}), + "start_percent": ("FLOAT", {"default": 0.2, "min": 0.0, "max": 1.0, "step": 0.001}), + "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}), + }} + RETURN_TYPES = ("MODEL",) + FUNCTION = "slg" + EXPERIMENTAL = True + DESCRIPTION = "Simplified skip layer guidance that only skips the uncond on selected blocks" + DEPRECATED = True + CATEGORY = "advanced/guidance" + + def slg(self, model, start_percent, end_percent, blocks): + def skip(args, extra_args): + transformer_options = extra_args.get("transformer_options", {}) + original_block = extra_args["original_block"] + + if not transformer_options: + raise ValueError("transformer_options not found in extra_args, currently SkipLayerGuidanceWanVideo only works with TeaCacheKJ") + if start_percent <= transformer_options["current_percent"] <= end_percent: + if args["img"].shape[0] == 2: + prev_img_uncond = args["img"][0].unsqueeze(0) + + new_args = { + "img": args["img"][1].unsqueeze(0), + "txt": args["txt"][1].unsqueeze(0), + "vec": args["vec"][1].unsqueeze(0), + "pe": args["pe"][1].unsqueeze(0) + } + + block_out = original_block(new_args) + + out = { + "img": torch.cat([prev_img_uncond, block_out["img"]], dim=0), + "txt": args["txt"], + "vec": args["vec"], + "pe": args["pe"] + } + else: + if transformer_options.get("cond_or_uncond") == [0]: + out = original_block(args) + else: + out = args + else: + out = original_block(args) + return out + + block_list = [int(x.strip()) for x in blocks.split(",")] + blocks = [int(i) for i in block_list] + logging.info(f"Selected blocks to skip uncond on: {blocks}") + + m = model.clone() + + for b in blocks: + #m.set_model_patch_replace(skip, "dit", "double_block", b) + model_options = m.model_options["transformer_options"].copy() + if "patches_replace" not in model_options: + model_options["patches_replace"] = {} + else: + model_options["patches_replace"] = model_options["patches_replace"].copy() + + if "dit" not in model_options["patches_replace"]: + model_options["patches_replace"]["dit"] = {} + else: + model_options["patches_replace"]["dit"] = model_options["patches_replace"]["dit"].copy() + + block = ("double_block", b) + + model_options["patches_replace"]["dit"][block] = skip + m.model_options["transformer_options"] = model_options + + + return (m, ) + +class CFGZeroStarAndInit: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "model": ("MODEL",), + "use_zero_init": ("BOOLEAN", {"default": True}), + "zero_init_steps": ("INT", {"default": 0, "min": 0, "tooltip": "for zero init, starts from 0 so first step is always zeroed out if use_zero_init enabled"}), + }} + RETURN_TYPES = ("MODEL",) + FUNCTION = "patch" + DESCRIPTION = "https://github.com/WeichenFan/CFG-Zero-star" + CATEGORY = "KJNodes/experimental" + EXPERIMENTAL = True + + def patch(self, model, use_zero_init, zero_init_steps): + def cfg_zerostar(args): + #zero init + cond = args["cond"] + timestep = args["timestep"] + sigmas = args["model_options"]["transformer_options"]["sample_sigmas"] + matched_step_index = (sigmas == timestep[0]).nonzero() + if len(matched_step_index) > 0: + current_step_index = matched_step_index.item() + else: + for i in range(len(sigmas) - 1): + if (sigmas[i] - timestep[0]) * (sigmas[i + 1] - timestep[0]) <= 0: + current_step_index = i + break + else: + current_step_index = 0 + + if (current_step_index <= zero_init_steps) and use_zero_init: + return cond * 0 + + uncond = args["uncond"] + cond_scale = args["cond_scale"] + + batch_size = cond.shape[0] + + positive_flat = cond.view(batch_size, -1) + negative_flat = uncond.view(batch_size, -1) + + dot_product = torch.sum(positive_flat * negative_flat, dim=1, keepdim=True) + squared_norm = torch.sum(negative_flat ** 2, dim=1, keepdim=True) + 1e-8 + alpha = dot_product / squared_norm + alpha = alpha.view(batch_size, *([1] * (len(cond.shape) - 1))) + + noise_pred = uncond * alpha + cond_scale * (cond - uncond * alpha) + return noise_pred + + m = model.clone() + m.set_model_sampler_cfg_function(cfg_zerostar) + return (m, ) + +class GGUFLoaderKJ(io.ComfyNode): + @classmethod + def define_schema(cls): + # Get GGUF models safely, fallback to empty list if unet_gguf folder doesn't exist + try: + gguf_models = folder_paths.get_filename_list("unet_gguf") + ltx2_connector_models = folder_paths.get_filename_list("text_encoders") + ltx2_connector_models = [m for m in ltx2_connector_models if "connector" in m.lower()] + except KeyError: + gguf_models = [] + ltx2_connector_models = [] + + return io.Schema( + node_id="GGUFLoaderKJ", + category="KJNodes/model_loaders", + description="Loads a GGUF model with advanced options, requires [ComfyUI-GGUF](https://github.com/city96/ComfyUI-GGUF) to be installed.", + is_experimental=True, + inputs=[ + io.Combo.Input("model_name", options=gguf_models), + io.Combo.Input("extra_model_name", options=gguf_models + ltx2_connector_models + ["none"], default="none", tooltip="An extra gguf model to load and merge into the main model, for example VACE module"), + io.Combo.Input("dequant_dtype", options=["default", "target", "float32", "float16", "bfloat16"], default="default"), + io.Combo.Input("patch_dtype", options=["default", "target", "float32", "float16", "bfloat16"], default="default"), + io.Boolean.Input("patch_on_device", default=False), + io.Boolean.Input("enable_fp16_accumulation", default=False, tooltip="Enable torch.backends.cuda.matmul.allow_fp16_accumulation, required minimum pytorch version 2.7.1"), + io.Combo.Input("attention_override", options=["none", "sdpa", "sageattn", "xformers", "flashattn"], default="none", tooltip="Overrides the used attention implementation, requires the respective library to be installed"), + + ], + outputs=[io.Model.Output(),], + ) + + def attention_override_pytorch(func, *args, **kwargs): + new_attention = comfy.ldm.modules.attention.attention_pytorch + return new_attention.__wrapped__(*args, **kwargs) + def attention_override_sage(func, *args, **kwargs): + new_attention = comfy.ldm.modules.attention.attention_sage + return new_attention.__wrapped__(*args, **kwargs) + def attention_override_xformers(func, *args, **kwargs): + new_attention = comfy.ldm.modules.attention.attention_xformers + return new_attention.__wrapped__(*args, **kwargs) + def attention_override_flash(func, *args, **kwargs): + new_attention = comfy.ldm.modules.attention.attention_flash + return new_attention.__wrapped__(*args, **kwargs) + + ATTENTION_OVERRIDES = { + "sdpa": attention_override_pytorch, + "sageattn": attention_override_sage, + "xformers": attention_override_xformers, + "flashattn": attention_override_flash, + } + + + @classmethod + def _get_gguf_module(cls): + """Import GGUF module with version validation""" + for key, mod in sys.modules.items(): + if key.endswith("ComfyUI-GGUF") or key.endswith("comfyui-gguf"): + if hasattr(mod, "ops") and hasattr(mod, "nodes"): + return mod + + gguf_path = os.path.join(folder_paths.folder_names_and_paths["custom_nodes"][0][0], "ComfyUI-GGUF") + for module_name in ["ComfyUI-GGUF", "custom_nodes.ComfyUI-GGUF", "comfyui-gguf", "custom_nodes.comfyui-gguf", gguf_path, gguf_path.lower()]: + try: + module = importlib.import_module(module_name) + return module + except ImportError: + continue + + raise ImportError( + "Compatible ComfyUI-GGUF not found. " + "Please install/update from: https://github.com/city96/ComfyUI-GGUF" + ) + + @classmethod + def execute(cls, model_name, extra_model_name, dequant_dtype, patch_dtype, patch_on_device, attention_override, enable_fp16_accumulation): + gguf_nodes = cls._get_gguf_module() + ops = gguf_nodes.ops.GGMLOps() + + def set_linear_dtype(attr, value): + if value == "default": + setattr(ops.Linear, attr, None) + elif value == "target": + setattr(ops.Linear, attr, value) + else: + setattr(ops.Linear, attr, getattr(torch, value)) + + set_linear_dtype("dequant_dtype", dequant_dtype) + set_linear_dtype("patch_dtype", patch_dtype) + + # init model + extra = {} + model_path = folder_paths.get_full_path("unet", model_name) + try: + sd, extra = gguf_nodes.loader.gguf_sd_loader(model_path) + except: + sd = gguf_nodes.loader.gguf_sd_loader(model_path) + + if extra_model_name is not None and extra_model_name != "none": + if extra_model_name.endswith(".gguf"): + extra_model_full_path = folder_paths.get_full_path("unet", extra_model_name) + try: + extra_model, _ = gguf_nodes.loader.gguf_sd_loader(extra_model_full_path) + except: + extra_model = gguf_nodes.loader.gguf_sd_loader(extra_model_full_path) + elif "connector" in extra_model_name.lower(): + extra_model_full_path = folder_paths.get_full_path("text_encoders", extra_model_name) + extra_model = comfy.utils.load_torch_file(extra_model_full_path) + diffusion_model_prefix = comfy.model_detection.unet_prefix_from_state_dict(extra_model) + if diffusion_model_prefix == "model.diffusion_model.": + temp_sd = comfy.utils.state_dict_prefix_replace(extra_model, {diffusion_model_prefix: ""}, filter_keys=True) + if len(temp_sd) > 0: + extra_model = temp_sd + else: + raise ValueError("Extra model must also be a .gguf file") + sd.update(extra_model) + + model = comfy.sd.load_diffusion_model_state_dict( + sd, model_options={"custom_operations": ops}, metadata=extra.get("metadata", {}) + ) + if model is None: + raise RuntimeError(f"ERROR: Could not detect model type of: {model_path}") + + model = gguf_nodes.nodes.GGUFModelPatcher.clone(model) + model.patch_on_device = patch_on_device + + # attention override + if attention_override in cls.ATTENTION_OVERRIDES: + model.model_options["transformer_options"]["optimized_attention_override"] = cls.ATTENTION_OVERRIDES[attention_override] + + if enable_fp16_accumulation: + if hasattr(torch.backends.cuda.matmul, "allow_fp16_accumulation"): + torch.backends.cuda.matmul.allow_fp16_accumulation = True + else: + raise RuntimeError("Failed to set fp16 accumulation, requires pytorch version 2.7.1 or higher") + else: + if hasattr(torch.backends.cuda.matmul, "allow_fp16_accumulation"): + torch.backends.cuda.matmul.allow_fp16_accumulation = False + + return io.NodeOutput(model,) + +try: + from torch.nn.attention.flex_attention import flex_attention, BlockMask +except: + flex_attention = None + BlockMask = None + +class NABLA_AttentionKJ(): + @classmethod + def INPUT_TYPES(s): + return {"required": { + "model": ("MODEL",), + "latent": ("LATENT", {"tooltip": "Only used to get the latent shape"}), + "window_time": ("INT", {"default": 11, "min": 1, "tooltip": "Temporal attention window size"}), + "window_width": ("INT", {"default": 3, "min": 1, "tooltip": "Spatial attention window size"}), + "window_height": ("INT", {"default": 3, "min": 1, "tooltip": "Spatial attention window size"}), + "sparsity": ("FLOAT", {"default": 0.9, "min": 0.0, "max": 1.0, "step": 0.01}), + "torch_compile": ("BOOLEAN", {"default": True, "tooltip": "Most likely required for reasonable memory usage"}) + }, + } + + RETURN_TYPES = ("MODEL", ) + FUNCTION = "patch" + DESCRIPTION = "Experimental node for patching attention mode to use NABLA sparse attention for video models, currently only works with Kadinsky5" + CATEGORY = "KJNodes/experimental" + + def patch(self, model, latent, window_time, window_width, window_height, sparsity, torch_compile): + if flex_attention is None or BlockMask is None: + raise RuntimeError("can't import flex_attention from torch.nn.attention, requires newer pytorch version") + + model_clone = model.clone() + samples = latent["samples"] + + sparse_params = get_sparse_params(samples, window_time, window_height, window_width, sparsity) + nabla_attention = NABLA_Attention(sparse_params) + + def attention_override_nabla(func, *args, **kwargs): + return nabla_attention(*args, **kwargs) + + if torch_compile: + attention_override_nabla = torch.compile(attention_override_nabla, mode="max-autotune-no-cudagraphs", dynamic=True) + + # attention override + model_clone.model_options["transformer_options"]["optimized_attention_override"] = attention_override_nabla + + return model_clone, + + +class NABLA_Attention(): + def __init__(self, sparse_params): + self.sparse_params = sparse_params + + def __call__(self, q, k, v, heads, **kwargs): + if q.shape[-2] < 3000 or k.shape[-2] < 3000: + return optimized_attention(q, k, v, heads, **kwargs) + block_mask = self.nablaT_v2(q, k, self.sparse_params["sta_mask"], thr=self.sparse_params["P"]) + out = flex_attention(q, k, v, block_mask=block_mask).transpose(1, 2).contiguous().flatten(-2, -1) + return out + + def nablaT_v2(self, q, k, sta, thr=0.9): + # Map estimation + BLOCK_SIZE = 64 + B, h, S, D = q.shape + s1 = S // BLOCK_SIZE + qa = q.reshape(B, h, s1, BLOCK_SIZE, D).mean(-2) + ka = k.reshape(B, h, s1, BLOCK_SIZE, D).mean(-2).transpose(-2, -1) + map = qa @ ka + + map = torch.softmax(map / math.sqrt(D), dim=-1) + # Map binarization + vals, inds = map.sort(-1) + cvals = vals.cumsum_(-1) + mask = (cvals >= 1 - thr).int() + mask = mask.gather(-1, inds.argsort(-1)) + + mask = torch.logical_or(mask, sta) + + # BlockMask creation + kv_nb = mask.sum(-1).to(torch.int32) + kv_inds = mask.argsort(dim=-1, descending=True).to(torch.int32) + return BlockMask.from_kv_blocks(torch.zeros_like(kv_nb), kv_inds, kv_nb, kv_inds, BLOCK_SIZE=BLOCK_SIZE, mask_mod=None) + +def fast_sta_nabla(T, H, W, wT=3, wH=3, wW=3): + l = torch.Tensor([T, H, W]).amax() + r = torch.arange(0, l, 1, dtype=torch.int16, device=mm.get_torch_device()) + mat = (r.unsqueeze(1) - r.unsqueeze(0)).abs() + sta_t, sta_h, sta_w = ( + mat[:T, :T].flatten(), + mat[:H, :H].flatten(), + mat[:W, :W].flatten(), + ) + sta_t = sta_t <= wT // 2 + sta_h = sta_h <= wH // 2 + sta_w = sta_w <= wW // 2 + sta_hw = (sta_h.unsqueeze(1) * sta_w.unsqueeze(0)).reshape(H, H, W, W).transpose(1, 2).flatten() + sta = (sta_t.unsqueeze(1) * sta_hw.unsqueeze(0)).reshape(T, T, H * W, H * W).transpose(1, 2) + return sta.reshape(T * H * W, T * H * W) + + +def get_sparse_params(x, wT, wH, wW, sparsity=0.9): + B, C, T, H, W = x.shape + #print("x shape:", x.shape) + patch_size = (1, 2, 2) + T, H, W = ( + T // patch_size[0], + H // patch_size[1], + W // patch_size[2], + ) + sta_mask = fast_sta_nabla(T, H // 8, W // 8, wT, wH, wW) + sparse_params = { + "sta_mask": sta_mask.unsqueeze_(0).unsqueeze_(0), + "to_fractal": True, + "P": sparsity, + "wT": wT, + "wH": wH, + "wW": wW, + "add_sta": True, + "visual_shape": (T, H, W), + "method": "topcdf", + } + + return sparse_params + +from comfy.comfy_types.node_typing import IO +class StartRecordCUDAMemoryHistory(): + # @classmethod + # def IS_CHANGED(s): + # return True + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "input": (IO.ANY,), + "enabled": (["all", "state", "None"], {"default": "all", "tooltip": "None: disable, 'state': keep info for allocated memory, 'all': keep history of all alloc/free calls"}), + "context": (["all", "state", "alloc", "None"], {"default": "all", "tooltip": "None: no tracebacks, 'state': tracebacks for allocated memory, 'alloc': for alloc calls, 'all': for free calls"}), + "stacks": (["python", "all"], {"default": "all", "tooltip": "'python': Python/TorchScript/inductor frames, 'all': also C++ frames"}), + "max_entries": ("INT", {"default": 100000, "min": 1000, "max": 10000000, "tooltip": "Maximum number of entries to record"}), + }, + } + + RETURN_TYPES = (IO.ANY, ) + RETURN_NAMES = ("input", "output_path",) + FUNCTION = "start" + CATEGORY = "KJNodes/memory" + DESCRIPTION = "THIS NODE ALWAYS RUNS. Starts recording CUDA memory allocation history, can be ended and saved with EndRecordCUDAMemoryHistory. " + + def start(self, input, enabled, context, stacks, max_entries): + mm.soft_empty_cache() + torch.cuda.reset_peak_memory_stats(mm.get_torch_device()) + torch.cuda.memory._record_memory_history( + max_entries=max_entries, + enabled=enabled if enabled != "None" else None, + context=context if context != "None" else None, + stacks=stacks + ) + return input, + +class EndRecordCUDAMemoryHistory(): + @classmethod + def INPUT_TYPES(s): + return {"required": { + "input": (IO.ANY,), + "output_path": ("STRING", {"default": "comfy_cuda_memory_history"}, "Base path for saving the CUDA memory history file, timestamp and .pt extension will be added"), + }, + } + + RETURN_TYPES = (IO.ANY, "STRING",) + RETURN_NAMES = ("input", "output_path",) + FUNCTION = "end" + CATEGORY = "KJNodes/memory" + DESCRIPTION = "Records CUDA memory allocation history between start and end, saves to a file that can be analyzed here: https://docs.pytorch.org/memory_viz or with VisualizeCUDAMemoryHistory node" + + def end(self, input, output_path): + mm.soft_empty_cache() + time = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") + output_path = f"{output_path}{time}.pt" + torch.cuda.memory._dump_snapshot(output_path) + torch.cuda.memory._record_memory_history(enabled=None) + return input, output_path + + +try: + from server import PromptServer +except: + PromptServer = None + +class VisualizeCUDAMemoryHistory(): + @classmethod + def INPUT_TYPES(s): + return {"required": { + "snapshot_path": ("STRING", ), + }, + "hidden": { + "unique_id": "UNIQUE_ID", + }, + } + + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("output_path",) + FUNCTION = "visualize" + CATEGORY = "KJNodes/memory" + DESCRIPTION = "Visualizes a CUDA memory allocation history file, opens in browser" + OUTPUT_NODE = True + + def visualize(self, snapshot_path, unique_id): + import pickle + from torch.cuda import _memory_viz + import uuid + + from folder_paths import get_output_directory + output_dir = get_output_directory() + + with open(snapshot_path, "rb") as f: + snapshot = pickle.load(f) + + html = _memory_viz.trace_plot(snapshot) + html_filename = f"cuda_memory_history_{uuid.uuid4().hex}.html" + output_path = os.path.join(output_dir, "memory_history", html_filename) + os.makedirs(os.path.dirname(output_path), exist_ok=True) + + with open(output_path, "w", encoding="utf-8") as f: + f.write(html) + + api_url = f"http://localhost:8188/api/view?type=output&filename={html_filename}&subfolder=memory_history" + + # Progress UI + if unique_id and PromptServer is not None: + try: + PromptServer.instance.send_progress_text( + api_url, + unique_id + ) + except: + pass + + return api_url, + + +class ModelMemoryUseReportPatch: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "model": ("MODEL",), + }} + + RETURN_TYPES = ("MODEL",) + FUNCTION = "patch" + DESCRIPTION = "Adds callbacks to model to report memory usage during after sampling" + EXPERIMENTAL = True + CATEGORY = "KJNodes/memory" + + def patch(self, model): + model_clone = model.clone() + device = mm.get_torch_device() + + def reset_mem_usage(model): + torch.cuda.reset_peak_memory_stats(device) + def report_mem_usage(model): + max_memory = torch.cuda.max_memory_allocated(device) / 1024**3 + max_reserved = torch.cuda.max_memory_reserved(device) / 1024**3 + logging.info(f"Sampling max allocated memory: {max_memory=:.3f} GB") + logging.info(f"Sampling max reserved memory: {max_reserved=:.3f} GB") + + model_clone.add_callback(CallbacksMP.ON_PRE_RUN, reset_mem_usage) + model_clone.add_callback(CallbacksMP.ON_CLEANUP, report_mem_usage) + + return (model_clone,) + + +class MemoryUsageFactorAdjustWrapper: + def __init__(self, memory_usage_factor, original_factor): + self.memory_usage_factor = memory_usage_factor + self.original_factor = original_factor + + def __call__(self, executor, model, noise_shape: torch.Tensor, *args, **kwargs): + m = model.clone() + m.model.memory_usage_factor = self.memory_usage_factor + logging.info(f"Temporarily set memory usage factor to {self.memory_usage_factor}") + try: + result = executor(m, noise_shape, *args, **kwargs) + finally: + logging.info(f"Model memory usage calculated, restoring original memory usage factor: {self.original_factor}") + m.model.memory_usage_factor = self.original_factor + return result + +class ModelMemoryUsageFactorOverride: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "model": ("MODEL",), + "memory_usage_factor": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 100.0, "step": 0.001}), + }} + + RETURN_TYPES = ("MODEL",) + FUNCTION = "patch" + DESCRIPTION = "Overrides the memory usage factor of the model during sampling." + EXPERIMENTAL = True + CATEGORY = "KJNodes/memory" + + def patch(self, model, memory_usage_factor): + model_clone = model.clone() + original_memory_usage_factor = model_clone.model.memory_usage_factor + logging.info(f"Original memory usage factor: {original_memory_usage_factor}") + + wrapper = MemoryUsageFactorAdjustWrapper(memory_usage_factor, original_memory_usage_factor) + model_clone.add_wrapper_with_key( + comfy.patcher_extension.WrappersMP.PREPARE_SAMPLING, + "memory_usage_factor_adjust_prepare_sampling", + wrapper + ) + return (model_clone,) + +def wan_ffn_chunked_forward(self, x): + if x.shape[1] > self.dim_threshold: + chunks = torch.chunk(x, self.num_chunks, dim=1) + output_chunks = [] + for chunk in chunks: + output_chunks.append(torch.nn.Sequential.forward(self, chunk)) + chunked = torch.cat(output_chunks, dim=1) + return chunked + else: + return torch.nn.Sequential.forward(self, x) + +class WanffnChunkPatch: + def __init__(self, num_chunks, dim_threshold=4096): + self.num_chunks = num_chunks + self.dim_threshold = dim_threshold + + def __get__(self, obj, objtype=None): + def wrapped_forward(self_module, *args, **kwargs): + self_module.num_chunks = self.num_chunks + self_module.dim_threshold = self.dim_threshold + return wan_ffn_chunked_forward(self_module, *args, **kwargs) + return types.MethodType(wrapped_forward, obj) + +class WanChunkFeedForward(io.ComfyNode): + + @classmethod + def define_schema(cls): + return io.Schema( + node_id="WanChunkFeedForward", + display_name="Wan Chunk FeedForward", + category="KJNodes/wan", + description="EXPERIMENTAL AND MAY CHANGE THE MODEL OUTPUT!! Chunks feedforward activations to reduce peak VRAM usage.", + is_experimental=True, + inputs=[ + io.Model.Input("model"), + io.Int.Input("chunks", default=2, min=1, max=100, step=1, tooltip="Number of chunks to split the feedforward activations into to reduce peak VRAM usage."), + io.Int.Input("dim_threshold", default=4096, min=1024, max=16384, step=256, tooltip="Dimension threshold above which to apply chunking."), + ], + outputs=[ + io.Model.Output(display_name="model"), + ], + ) + + @classmethod + def execute(cls, model, chunks, dim_threshold) -> io.NodeOutput: + if chunks == 1: + return io.NodeOutput(model) + + model_clone = model.clone() + diffusion_model = model_clone.get_model_object("diffusion_model") + + for idx, block in enumerate(diffusion_model.blocks): + patched_ffn = WanffnChunkPatch(chunks, dim_threshold).__get__(block.ffn, block.__class__) + model_clone.add_object_patch(f"diffusion_model.blocks.{idx}.ffn.forward", patched_ffn) + + return io.NodeOutput(model_clone) + +from comfy.samplers import KSAMPLER +from comfy.k_diffusion.sampling import to_d + +def sample_selfrefinevideo(model, x, sigmas, stochastic_step_map, certain_percentage=0.999, uncertainty_threshold=0.25, extra_args=None, callback=None, disable=None, verbose=False, video_shape=None, seed=None): + extra_args = {} if extra_args is None else extra_args + sigma_in = x.new_ones([x.shape[0]]) + + if seed is not None: + generator = torch.Generator(torch.device("cpu")).manual_seed(seed) + + pbar = tqdm(total=len(sigmas) - 1, disable=disable, desc="Sampling") + + for i in range(len(sigmas) - 1): + + # Get stochastic steps for this noise level + current_num_anneal_steps = stochastic_step_map.get(i, 0) + use_stochastic = current_num_anneal_steps > 0 + m = current_num_anneal_steps + 1 if use_stochastic else 1 + + sigma, sigma_next = sigmas[i], sigmas[i + 1] + + prev_certain_mask = None + prev_denoised = None + prev_denoised_full = None + prev_x_next = None + prev_x_next_video = None + is_certain = False + + for ii in range(m): + if m > 1: + pbar.set_description(f"Step {i}/{len(sigmas)-1} (substep {ii+1}/{m})") + # Early exit if certain threshold reached + if is_certain: + x = prev_x_next + break + + # Determine input + noise = torch.randn(x.shape, device=torch.device("cpu"), generator=generator).to(x) + x_in = x if ii == 0 else (1.0 - sigma) * prev_denoised_full + sigma * noise + if ii > 0: + x = x_in + + denoised = model(x_in, sigmas[i] * sigma_in, **extra_args) + + if callback is not None: + callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised}) + + # Compute next latents + d = to_d(x, sigma, denoised) + x_next = x + (sigma_next - sigma) * d + + # Separate video and audio if joint model + if d.ndim == 3 and video_shape is not None: + cut = math.prod(video_shape[1:]) + denoised_video = denoised[:, :, :cut].reshape([denoised.shape[0]] + list(video_shape)[1:]) + x_next_video = x_next[:, :, :cut].reshape([denoised.shape[0]] + list(video_shape)[1:]) + denoised_audio = denoised[:, :, cut:] + x_next_audio = x_next[:, :, cut:] + if verbose: + tqdm.write(f"Video shape: {denoised_video.shape}, Audio shape: {denoised_audio.shape}") + else: + denoised_video = denoised + x_next_video = x_next + denoised_audio = None + x_next_audio = None + + # Stochastic sampling with uncertainty masking + if use_stochastic and prev_denoised is not None: + # Compute uncertainty and masking on video part + diff = denoised_video - prev_denoised + uncertainty = torch.sqrt(torch.sum(diff ** 2, dim=1)) / denoised_video.shape[1] + certain_mask = uncertainty < uncertainty_threshold + + if verbose: + tqdm.write(f"Step {i}/{len(sigmas)-1} substep {ii+1}/{m}:") + tqdm.write(f"Uncertainty: min {uncertainty.min():.4f}, max {uncertainty.max():.4f}, threshold {uncertainty_threshold}") + tqdm.write(f"Certain pixels: {certain_mask.sum()}/{certain_mask.numel()} = {certain_mask.sum()/certain_mask.numel():.4f}") + + # Update certain mask (union with previous) + if prev_certain_mask is not None: + certain_mask = certain_mask | prev_certain_mask + + # Check certainty threshold + if certain_mask.sum() / certain_mask.numel() > certain_percentage: + is_certain = True + if verbose: + tqdm.write(f"{ii}/{current_num_anneal_steps}: Certain region is more than {certain_percentage}, we are certain") + + # Apply masking to video + certain_mask_float = certain_mask.float().unsqueeze(1) + x_next_video = certain_mask_float * prev_x_next_video + (1.0 - certain_mask_float) * x_next_video + denoised_video = certain_mask_float * prev_denoised + (1.0 - certain_mask_float) * denoised_video + + # Reconstruct full latents by replacing the video portion + if x_next_audio is not None: + # Flatten masked video back to match original format and replace video portion + x_next = x_next.clone() + x_next[:, :, :cut] = x_next_video.reshape([x_next_video.shape[0], x_next.shape[1], -1]) + # Also reconstruct full denoised for next iteration input + denoised_full = denoised.clone() + denoised_full[:, :, :cut] = denoised_video.reshape([denoised_video.shape[0], denoised.shape[1], -1]) + else: + # No audio separation + x_next = x_next_video + denoised_full = denoised_video + + prev_certain_mask = certain_mask + prev_denoised = denoised_video + prev_denoised_full = denoised_full + prev_x_next_video = x_next_video + prev_x_next = x_next + elif use_stochastic: + # For first stochastic step, create denoised_full if we have audio + if x_next_audio is not None: + denoised_full = denoised.clone() + denoised_full[:, :, :cut] = denoised_video.reshape([denoised_video.shape[0], denoised.shape[1], -1]) + else: + denoised_full = denoised_video + + prev_certain_mask = None + prev_denoised = denoised_video + prev_denoised_full = denoised_full + prev_x_next_video = x_next_video + prev_x_next = x_next + + # Update x for final step + if use_stochastic and ii == m - 1: + x = prev_x_next + elif not use_stochastic: + x = x_next + + pbar.update(1) + if m == 1: + pbar.set_description("Sampling") + pbar.close() + return x + +class SamplerSelfRefineVideo(io.ComfyNode): + @classmethod + def define_schema(cls): + default_ranges = [ + (2, 5, 3), # Range 1 + (6, 14, 1), # Range 2 + ] + + options = [] + + # Option 1: 2 ranges + range_inputs_2 = [] + for i in range(1, 3): + start_default, end_default, steps_default = default_ranges[i - 1] + range_inputs_2.extend([ + io.Int.Input(f"start_step{i}", default=start_default, min=0, max=999, step=1, tooltip=f"Start step for range {i}"), + io.Int.Input(f"end_step{i}", default=end_default, min=0, max=999, step=1, tooltip=f"End step for range {i}"), + io.Int.Input(f"steps_{i}", default=steps_default, min=1, max=100, step=1, tooltip=f"Number of P&P steps for range {i}"), + ]) + options.append(io.DynamicCombo.Option(key="2 ranges", inputs=range_inputs_2)) + + # Option 2: 1 range + range_inputs_1 = [] + for i in range(1, 2): + start_default, end_default, steps_default = default_ranges[i - 1] + range_inputs_1.extend([ + io.Int.Input(f"start_step{i}", default=start_default, min=0, max=999, step=1, tooltip=f"Start step for range {i}"), + io.Int.Input(f"end_step{i}", default=end_default, min=0, max=999, step=1, tooltip=f"End step for range {i}"), + io.Int.Input(f"steps_{i}", default=steps_default, min=1, max=100, step=1, tooltip=f"Number of P&P steps for range {i}"), + ]) + options.append(io.DynamicCombo.Option(key="1 range", inputs=range_inputs_1)) + + # Option 3: Manual string input + options.append(io.DynamicCombo.Option( + key="from_string", + inputs=[ + io.String.Input( + "stochastic_plan", + default="2-5:3,6-14:1", + multiline=True, + tooltip="Format: 'start-end:steps,start-end:steps' e.g. '2-5:3,6-14:1'" + ) + ] + )) + return io.Schema( + node_id="SamplerSelfRefineVideo", + category="KJNodes/samplers", + description="Attempt to implement https://github.com/agwmon/self-refine-video, for testing only, MAY NOT WORK AS INTENDED.", + is_experimental=True, + inputs=[ + io.DynamicCombo.Input("input_mode", options=options, tooltip="How to configure the step plan"), + io.Float.Input("certain_percentage", default=0.999, min=0.0, max=1.0, step=0.001, round=False, tooltip="Percentage of certain pixels to consider the frame as certain and skip further refinement"), + io.Float.Input("uncertainty_threshold", default=0.2, min=0.0, max=1.0, step=0.01, round=False, tooltip="Threshold of uncertainty to consider a pixel uncertain"), + io.Boolean.Input("verbose", default=False, tooltip="Enable verbose logging during sampling"), + io.Latent.Input("latent", optional=True, tooltip="Optional latent input to get input shape for LTX2 audio/video separation"), + io.Int.Input("seed", default=0, min=0, max=0xffffffffffffffff, step=1, tooltip="Seed for stochastic sampling"), + ], + outputs=[io.Sampler.Output()] + ) + + @classmethod + def execute(cls, input_mode, certain_percentage, uncertainty_threshold, seed, verbose, latent=None) -> io.NodeOutput: + video_shape = None + if latent is not None: + video_shape = latent["samples"].shape + + range_keys = sorted([k for k in input_mode.keys() if k.startswith('start_step')]) + stochastic_step_map = {} + if "stochastic_plan" in input_mode: + # Parse manual string format: "2-5:3,6-14:1" + plan_str = input_mode["stochastic_plan"] + ranges = plan_str.split(",") + for range_spec in ranges: + range_spec = range_spec.strip() + if not range_spec: + continue + try: + range_part, steps_part = range_spec.split(":") + start, end = range_part.split("-") + start, end, steps = int(start), int(end), int(steps_part) + for idx in range(start, end + 1): + stochastic_step_map[idx] = steps + except ValueError: + raise ValueError(f"Invalid format in stochastic_plan: '{range_spec}'. Expected format: 'start-end:steps'") + else: + range_keys = [k for k in input_mode.keys() if k.startswith('start_step')] + for start_key in range_keys: + i = start_key.replace('start_step', '') + start = input_mode.get(f"start_step{i}") + end = input_mode.get(f"end_step{i}") + steps = input_mode.get(f"steps_{i}") + + if start is not None and end is not None and steps is not None: + for idx in range(start, end + 1): + stochastic_step_map[idx] = steps + + sampler = KSAMPLER(sample_selfrefinevideo, { + "stochastic_step_map": stochastic_step_map, + "certain_percentage": certain_percentage, + "uncertainty_threshold": uncertainty_threshold, + "verbose": verbose, + "video_shape": video_shape, + "seed": seed, + }) + return io.NodeOutput(sampler) diff --git a/.disabled/comfyui-kjnodes@nightly/pyproject.toml b/.disabled/comfyui-kjnodes@nightly/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..9b82eea01e0cae4d58cdc439a71335b35314ad25 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/pyproject.toml @@ -0,0 +1,15 @@ +[project] +name = "comfyui-kjnodes" +description = "Various quality of life -nodes for ComfyUI, mostly just visual stuff to improve usability." +version = "1.3.7" +license = {file = "LICENSE"} +dependencies = ["numpy", "pillow>=10.3.0", "scipy", "color-matcher", "matplotlib"] + +[project.urls] +Repository = "https://github.com/kijai/ComfyUI-KJNodes" +# Used by Comfy Registry https://comfyregistry.org + +[tool.comfy] +PublisherId = "kijai" +DisplayName = "ComfyUI-KJNodes" +Icon = "https://avatars.githubusercontent.com/u/40791699" diff --git a/.disabled/comfyui-kjnodes@nightly/requirements.txt b/.disabled/comfyui-kjnodes@nightly/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..6dd831112af1fbd7f1754ad08a9530d1cc1e7d45 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/requirements.txt @@ -0,0 +1,6 @@ +pillow>=10.3.0 +scipy +color-matcher +matplotlib +mss +opencv-python-headless diff --git a/ComfyLiterals/.gitignore b/ComfyLiterals/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..bd38df5566bbc3c69e518bad30739063f26ceb5a --- /dev/null +++ b/ComfyLiterals/.gitignore @@ -0,0 +1,2 @@ + +__pycache__/ diff --git a/ComfyLiterals/README.md b/ComfyLiterals/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9e78e62de43fab781b7022b43f1f1f6d9ea60e46 --- /dev/null +++ b/ComfyLiterals/README.md @@ -0,0 +1,2 @@ +# ComfyLiterals +![CleanShot 2023-07-22 at 00 13 13](https://github.com/M1kep/ComfyLiterals/assets/2661819/c8bdc4f0-8cf3-4403-be96-34db357520b0) diff --git a/ComfyLiterals/__init__.py b/ComfyLiterals/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d3f9d6467222fef9932865ad61e458f9629a334e --- /dev/null +++ b/ComfyLiterals/__init__.py @@ -0,0 +1,21 @@ +from .nodes import IntLiteral, FloatLiteral, StringLiteral, CheckpointListLiteral, LoraListLiteral +from .operations import Operation +from .startup_utils import symlink_web_dir + +NODE_CLASS_MAPPINGS = { + "Int": IntLiteral, + "Float": FloatLiteral, + "String": StringLiteral, + "KepStringLiteral": StringLiteral, + "Operation": Operation, + "Checkpoint": CheckpointListLiteral, + "Lora": LoraListLiteral, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "KepStringLiteral": "String", +} + +EXTENSION_NAME = "ComfyLiterals" + +symlink_web_dir("js", EXTENSION_NAME) diff --git a/ComfyLiterals/__pycache__/__init__.cpython-310.pyc b/ComfyLiterals/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b2b3ee14d4263f1e0ec40054a122d6de59c02dc Binary files /dev/null and b/ComfyLiterals/__pycache__/__init__.cpython-310.pyc differ diff --git a/ComfyLiterals/__pycache__/nodes.cpython-310.pyc b/ComfyLiterals/__pycache__/nodes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db14306fcde4fa07c075fd5e2ad877ce1828832b Binary files /dev/null and b/ComfyLiterals/__pycache__/nodes.cpython-310.pyc differ diff --git a/ComfyLiterals/__pycache__/operations.cpython-310.pyc b/ComfyLiterals/__pycache__/operations.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85bcbc7c89d8c2ff60c33a46a69fe770c7190eb7 Binary files /dev/null and b/ComfyLiterals/__pycache__/operations.cpython-310.pyc differ diff --git a/ComfyLiterals/__pycache__/startup_utils.cpython-310.pyc b/ComfyLiterals/__pycache__/startup_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ddc63ee9fc5812f5f8693289b5dfb9bf657fd2f Binary files /dev/null and b/ComfyLiterals/__pycache__/startup_utils.cpython-310.pyc differ diff --git a/ComfyLiterals/nodes.py b/ComfyLiterals/nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..94f65f4cbb78a860a206f0a72b26949bc710d602 --- /dev/null +++ b/ComfyLiterals/nodes.py @@ -0,0 +1,136 @@ +import folder_paths + +# Hack: string type that is always equal in not equal comparisons +class AnyType(str): + def __ne__(self, __value: object) -> bool: + return False + + +# Our any instance wants to be a wildcard string +ANY = AnyType("*") +class IntLiteral: + def __init__(self, ): + pass + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "Number": ("STRING", {}), + } + } + + RETURN_TYPES = ("INT",) + FUNCTION = "to_int" + + CATEGORY = "Literals" + + def to_int(self, Number): + try: + ret_val = int(Number) + except Exception: + raise Exception("Invalid value provided for INT") + return (ret_val,) + + +class FloatLiteral: + def __init__(self, ): + pass + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "Number": ("STRING", {}), + } + } + + RETURN_TYPES = ("FLOAT",) + FUNCTION = "to_float" + + CATEGORY = "Literals" + + def to_float(self, Number): + try: + ret_val = float(Number) + except Exception: + raise Exception("Invalid value provided for FLOAT") + return (ret_val,) + + +class StringLiteral: + def __init__(self, ): + pass + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "String": ("STRING", {"multiline": True}), + } + } + + RETURN_TYPES = ("STRING",) + FUNCTION = "to_string" + + CATEGORY = "Literals" + + def to_string(self, String): + return (String,) + + +class CheckpointListLiteral: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "literal": ("STRING", { + "multiline": True, + "default": "\n".join(folder_paths.get_filename_list("checkpoints")) + }), + }, + } + + RETURN_TYPES = (ANY,) + RETURN_NAMES = ("Selected Checkpoints",) + OUTPUT_IS_LIST = (True,) + FUNCTION = "parse_literal" + + # OUTPUT_NODE = False + + CATEGORY = "List Stuff" + + def parse_literal(self, literal): + split = list(filter(None, literal.split("\n"))) + return (split,) + +class LoraListLiteral: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "literal": ("STRING", { + "multiline": True, + "default": "\n".join(folder_paths.get_filename_list("loras")) + }), + }, + } + + RETURN_TYPES = (ANY,) + RETURN_NAMES = ("Selected Loras",) + OUTPUT_IS_LIST = (True,) + FUNCTION = "parse_literal" + + # OUTPUT_NODE = False + + CATEGORY = "List Stuff" + + def parse_literal(self, literal): + split = list(filter(None, literal.split("\n"))) + return (split,) diff --git a/ComfyLiterals/operations.py b/ComfyLiterals/operations.py new file mode 100644 index 0000000000000000000000000000000000000000..e533edb70b6aa841be7c332a5e07a55590373b2a --- /dev/null +++ b/ComfyLiterals/operations.py @@ -0,0 +1,54 @@ +class Operation: + def __init__(self, ): + pass + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "A Type": (["Int", "Float"],), + "B Type": (["Int", "Float"],), + "Operation": (["A+B", "A-B", "A*B", "A/B"],) + }, + "optional": { + "A - Int": ("INT", {"forceInput": True}), + "A - Float": ("FLOAT", {"forceInput": True}), + "B - Int": ("INT", {"forceInput": True}), + "B - Float": ("FLOAT", {"forceInput": True}) + } + } + + RETURN_TYPES = ("INT", "FLOAT") + FUNCTION = "do_operation" + + CATEGORY = "Literals" + + def _do_addition(self, a_val, b_val): + return (int(a_val + b_val), float(a_val + b_val)) + + def _do_subtraction(self, a_val, b_val): + return (int(a_val - b_val), float(a_val - b_val)) + + def _do_multiplication(self, a_val, b_val): + return (int(a_val * b_val), float(a_val * b_val)) + + def _do_division(self, a_val, b_val): + return (int(a_val / b_val), float(a_val / b_val)) + + def do_operation(self, **kwargs): + print(f"PrintNode: {kwargs}") + is_a_int = kwargs["A Type"] == "Int" + is_b_int = kwargs["B Type"] == "Int" + a_val = kwargs["A - Int"] if is_a_int else kwargs["A - Float"] + b_val = kwargs["B - Int"] if is_b_int else kwargs["B - Float"] + + if kwargs["Operation"] == "A+B": + return self._do_addition(a_val, b_val) + elif kwargs["Operation"] == "A-B": + return self._do_subtraction(a_val, b_val) + elif kwargs["Operation"] == "A*B": + return self._do_multiplication(a_val, b_val) + elif kwargs["Operation"] == "A/B": + return self._do_division(a_val, b_val) + else: + raise Exception("Invalid operation provided") diff --git a/ComfyLiterals/startup_utils.py b/ComfyLiterals/startup_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b7d85270df00cabd895d79e4a6caa5f81a8da9ce --- /dev/null +++ b/ComfyLiterals/startup_utils.py @@ -0,0 +1,29 @@ +import os +from pathlib import Path + +import folder_paths + + +def symlink_web_dir(local_path, extension_name): + comfy_web_ext_root = Path(os.path.join(folder_paths.base_path, "web", "extensions")) + target_dir = Path(os.path.join(comfy_web_ext_root, extension_name)) + extension_path = Path(__file__).parent.resolve() + + if target_dir.exists(): + print(f"Web extensions folder found at {target_dir}") + elif comfy_web_ext_root.exists(): + try: + os.symlink((os.path.join(extension_path, local_path)), target_dir) + except OSError as e: # OSError + print( + f"Error:\n{e}\n" + f"Failed to create symlink to {target_dir}. Please copy the folder manually.\n" + f"Source: {os.path.join(extension_path, local_path)}\n" + f"Target: {target_dir}" + ) + except Exception as e: + print(f"Unexpected error:\n{e}") + else: + print( + f"Failed to find comfy root automatically, please copy the folder {os.path.join(extension_path, 'web')} manually in the web/extensions folder of ComfyUI" + ) diff --git a/cg-use-everywhere/README-old.md b/cg-use-everywhere/README-old.md new file mode 100644 index 0000000000000000000000000000000000000000..6e5dedcd778b58490630ad67a70ef3631d8b70d5 --- /dev/null +++ b/cg-use-everywhere/README-old.md @@ -0,0 +1,335 @@ +# UE Nodes + +Love this node? [Buy me a coffee!](https://www.buymeacoffee.com/chrisgoringe) + +Getting started? Download the test workflow below and see how it works. + +Problems? Jump down to [logging and debugging](https://github.com/chrisgoringe/cg-use-everywhere/blob/main/README.md#loggingdebugging) + +Ideas for how to improve the nodes (or bug reports) - [raise an issue](https://github.com/chrisgoringe/cg-use-everywhere/issues) + +Shameless plug for my other nodes -> Check out [Image Picker](https://github.com/chrisgoringe/cg-image-filter) for another way to make some workflows smoother. And leave a star if you like something! + +--- + +# Important! + +I've merged v7 of UE to coincide with the update to ComfyUI, but the instructions below have not been updated. + +Please see [this discussion](https://github.com/chrisgoringe/cg-use-everywhere/discussions/334) (but ignore the bits about branches). + +--- + +Over the next few releases I am aiming to reduce the UE zoo down to a single node that can do everything, but is as easy (or easier) to use than the current nodes. + +The first step in this process is merging the `AnythingEverywhere` and `AnythingEverywhere?` nodes by moving the regex restrictions into a separate dialog that can be used by either. In future iterations the group and color restrictions will also move to this dialog (so people find them!) + +--- + +# 6.3 Update for ComfyUI front end (version TBC) - subgraphs + +With the addition of subgraphs, group nodes are no longer supported in UE from 6.3 onwards. + +Instead, UE 6.3 has the following support for subgraphs: + +- UE nodes can be used in the main graph and in subgraphs. +- UE nodes only broadcast within the graph or subgraph they are in. +- Subgraph nodes are just nodes. You can connect UE nodes to their outputs, and UE links will connect to their inputs. +- Within a subgraph you can connect from the input panel to a UE node. +- UE nodes within the subgraph will *not* broadcast to the output panel. +- When you convert a set of nodes to a subgraph, UE links will work as long as: + - the UE node (Control) and the node feeding it (Source) are both in the subgraph, or + - neither the Source nor Control are in the subgraph, or + - the Source is in the subgraph, and the Control is not, and no Target nodes are in the subgraph + + +## Subgraph creation + +There are three nodes involved in every UE link: +- Source (the link sending the data), +- Control (the UE node connected to the source), +- Target (the node that is receiving the data as an input) + +This is how those cases are treated: + +|Support|Source|Control|Target|| +|-|-|-|-|-| +|Yes|Graph|Graph|Graph|Nothing changes| +|Yes|Graph|Graph|Subgraph|The subgraph will have inputs for the data; in the subgraph the input panel is connected to the Target with a real link| +|No|Graph|Subgraph|Graph|Not supported| +|No*|Graph|Subgraph|Subgraph|Not supported| +|Yes|Subgraph|Graph|Graph|The subgraph will be connected to the Control| +|No|Subgraph|Graph|Subgraph|Not supported| +|Yes|Subgraph|Subgraph|Graph|The Source will be connected to the Control *and* the output panel in the subgraph, the output will be connected to the Target with a real link| +|Yes|Subgraph|Subgraph|Subgraph|All nodes will be connected in the subgraph as they were in the graph| + +No* indicates a case that does not work, but might get implemented. + +No indicates a case I'm unlikely ever to support + +--- + +## Test workflow + +|This workflow uses all five nodes, and can be used to test (and understand!) the nodes. You wouldn't build it like this, it's just an example...|Here's an image with the workflow in| +|-|-| +|![screen](docs/test-workflow-screenshot.png)|![image](docs/test-workflow.png)| + +Or [the workflow as json](docs/test-workflow.json) + +## Current known limitations + +There are some situations that UE nodes can't cope with at present. Here are some I know about, and possible workarounds. + +### Pythonssss Preset Text + +[pythonsssss](https://github.com/pythongosssss/ComfyUI-Custom-Scripts) custom nodes are great, but there are some limitations in using them with UE nodes. In particular, you can't feed the output of a Preset Text node directly into a UE node (see https://github.com/chrisgoringe/cg-use-everywhere/issues/154). + +### Group nodes + +UE nodes mostly work with group nodes. But there are a couple of important things to note: + +- when you create a group node the input names and node names can change. This might break UE? regex connections. + +## Latest updates + +6.3 June/July 2025 +- support for ComfyUI subgraphs + +6.1 (May 2025) +- Mostly some bug-fixes (#216, #217, #300) +- New option to show UE links differently without animation for better performance + +6.0 (April 2025) +- Very major rebuild to deal with latest version of Comfy + +## Installing + +Use Comfy Manager. If you really want to do it manually, just clone this repository in your custom_nodes directory. + +## Anything Everywhere (start here!) + +The `Anything Everywhere` node has a single input, initially labelled 'anything'. Connect anything to it (directly - not via a reroute), and the input name changes to match the input type. Disconnect and it goes back to 'anything'. + +When you run the prompt, any unconnected input, anywhere in the workflow, which matches that type, will act as if it were connected to the same input. + +To visualise what it's being connected to, right-click on the background canvas and select `Toggle UE Link Visibility`. + +## Anything Everywhere? - control matching with regex rules + +This node adds two widgets - title_regex and input_regex. It will only send to inputs which match. So in the example, title_regex is 'Preview' so the image is sent to the Preview Image node but not the Save Image node. Note that you can rename node and input titles, which can help! + +(From 4.6 you can also specify a group regex to only match inputs on nodes which are in groups that match the regex.) + +![regex](docs/regex.png) + +*The matches are regular expressions, not string matches.* Most simple strings will work (matching any part of the title or input name), but some characters have special meanings (including various sorts of brackets, ^, $, /, and . in particular) so just avoid them if you aren't regex-inclined. + +Using regex means you can use `^prompt` to match `prompt` at the beginning of the title only, to avoid matching `negative_prompt`. + +Regex 101 - `^` means 'the start', `$` means 'the end', `.` matches any single character, `.*` matches anything of any length (including zero). For more than that, visit [regex101](https://regex101.com/) (the flavour you want is ECMAScript, though that probably won't matter). + +### Can I make the regex an input instead of a widget? + +Sort of. + +Because the regex needs to be known before the workflow is submitted (in order to calculate the links), you can't pass a string into the `Anything Everywhere?` node and expect it to work. The *only* thing that is supported is if the input comes *directly* from a node which sets it with a string widget. The `Simple String` node that is included in this pack will work. + +|This works|This doesn't. And never will.| +|-|-| +|![Alt text](docs/image.png)|![no](docs/imagex.png)| + + +## Seed Everywhere + +Seed Everywhere connects to any unconnected INT input with `seed` in the input name (seed, noise_seed, etc), and it has the control_after_generate feature. So if you convert the seed widgets to inputs you can use the same seed everywhere. + +## Anything Everywhere3 - One node, three inputs. + +Really just three `Anything Everywhere` nodes packaged together. Designed for the outputs of Checkpoint Loader. + +![UE3](docs/UE3.png) + +## Prompts Everywhere - two strings or conditionings + +Prompt Everywhere has two inputs. They will be sent with regex matching rules of `(^prompt|^positive)` and `neg` respectively. These should match the various versions of names that get used for prompts and negative prompts or conditionings. + +|strings|conditionings| +|-|-| +|![pe](docs/PE.png)|![pe](docs/conditioning.png) + +# Primitives and COMBOs and the like + +UE nodes don't work with primitives and COMBOs (the data type used for dropdown lists, which are also a type of primitive within Comfy). It's unlikely they ever will. + +If you want to use UE to control sampler or sigma, you can do this with the built in `SamplerCustom` nodes: + +![sample and sigma](docs/sampler%20and%20sigma.png) + +For more on this, see [this discussion](https://github.com/chrisgoringe/cg-use-everywhere/issues/69) + +# Other features + +## Third Party Integration + +At the suggestion of [@fighting-tx](https://github.com/fighting-tx), +I've added a method that third party nodes can use if they want to see the prompt as generated by UE. +It's attached to the `app` object, so you can check if it is present and use it something like this: + +```js +var prompt +if (app.ue_modified_prompt) { + prompt = await app.ue_modified_prompt() +} else { + prompt = await original_graphToPrompt.apply(app) +} +``` + +Other methods could be exposed if there is interest - raise an issue if you'd like to see something. + +## Reject links + +Right click on a node and you can set it to reject UE links + +## Show links - visualisation and animation. + +If you want to see the UE links, you can turn them on and off by right-clicking on the canvas. For finer control, the main settings menu has options to show links when the mouse moves over the node at either end, or when one of those nodes is selected. + +The links can be animated to distinguish them from normal links - this animation can take the form of moving dots, a pulsing glow, or both. This may impact performance in some cases - note that the pulse animation requires less processing than the moving dots. Control this in the main settings menu. + +By default the animations turn off when the workflow is running to minimise impact on CPU/GPU - you can change this in the settings too. + +## Convert to real links + +If you want to share a workflow without UE nodes being required, or to save an API version of a workflow, you can replace the virtual links created by UE nodes with real links (and remove the UE nodes). + +This can be done for a single node by right-clicking on it and selecting `Convert to real links`, or for all UE nodes in a workflow by right-clicking the background and selecting `Convert all UEs to real links`. + +## Shift drag + +Shift click on an output node and drag then release to get an autocreate menu. This replaces the default behaviour (which gives you a search box), so you can disable it with the `Anything Everywhere replace search` setting. + +![auto](docs/auto.gif) + +## Group and color restriction + +UE nodes can be restricted to send only to nodes of the same color, or only to nodes that *aren't* the same color. + +They can also be restricted to send only to nodes in the same group (any group in common), or only to nodes that aren't in the same group. + +Right-click on the node and select `Group restrictions` or `Color restrictions`. UE nodes which are restricted (in either or both ways) have a green circle in the top-left corner. + +## Highway nodes + +Trung 0246's [Highway nodes](https://github.com/Trung0246/ComfyUI-0246) are a pretty cool way of piping data around. You can target them with an `Anything Everywhere?` node by using an `input_regex` which matches the unconnected input name with the '+', like this: +![highway](docs/highway.png) + +This is new, so please report any issues! + +## Loop checking + +By default workflows are checked for loops before they are submitted (because UE can introduce them, and a loop results in a bad python outcome). If a loop is detected you'll get a JavaScript warning showing you the node ids involved. However, especially if there are other custom nodes involved, it's possible that the check will miss a loop, or flag one that isn't real. + +If you get a warning and don't believe there is a loop (having checked the node ids listed!) you can turn loop checking off in the main settings menu. If something flagged as a loop runs fine, please [raise an issue](https://github.com/chrisgoringe/cg-use-everywhere/issues) and include the workflow in the report (save the json and zip it, because GitHub doesn't accept .json files). Likewise if a loop doesn't get caught. + +I've written code for the core Comfy backend to catch loops, maybe it'll be included - [PR for ComfyUI](https://github.com/comfyanonymous/ComfyUI/pull/1652) - or maybe they have another plan. + +## Priorities + +If there is more than one sending node that matches an input, the basic rules is that the more specific node wins. The order of priorities is: + +- `Anything Everywhere?` +- `Seed Everywhere` and `Prompts Everywhere` +- `Anything Everywhere` +- `Anything Everywhere3` + +For nodes of the same time, those with colour restrictions and group restriction are prioritised (colour+group > colour > group > none). + +If two nodes with the same priority both match *neither will connect* - better to fail fast than have an ambiguous outcome. If there are ambiguous matches you can display them using `Show UE broadcast clashes` (right-click on background - the option only appears if there are clashes). + +## See what is sent + +The nodes which only have one output can also gain a text box showing exactly what passed through the node. You need to turn this on if you want it - it's in the main settings, 'Anything Everywhere node details'. + +## Logging/Debugging + +The JavaScript console (press f12 in some browsers) has logging information about what is being connected. You can change the level of detail by finding the file `[comfy_install]/custom_nodes/cg-use-everywhere/js/use_everywhre_utilities.js` and near the top finding this bit: +```javascript + static ERROR = 0; // actual errors + static PROBLEM = 1; // things that stop the workflow working + static INFORMATION = 2; // record of good things + static DETAIL = 3; // details + + static LEVEL = Logger.PROBLEM; + static TRACE = false; // most of the method calls +``` +Change the `LEVEL` to `Logger.INFORMATION` for more, or `Logger.DETAIL` for even more; set `TRACE` to `true` for some other debugging information. + +If you have a problem, pressing f12 to see the JavaScript console can often help. The following steps are really helpful in making a good bug report: + +- update to the latest version +- restart ComfyUI +- clear the canvas +- close the browser +- open a new Comfy window (with no workflow), look in console (f12) to see if there were any errors as ComfyUI started up +- load your workflow, and look again +- run, and look again + +The other thing worth trying is clearing out all the custom node javascript from where it gets copied when ComfyUI starts: + +- stop Comfy +- go to [comfy root]/web/extensions (*not* under custom_nodes) +- remove everything there EXCEPT for `core`. Leave `core` (it's ComfyUI stuff) +- restart Comfy (all custom nodes will reinstall their javascript at startup) + +If you find a bug, please [raise an issue](https://github.com/chrisgoringe/cg-use-everywhere/issues) - if you can include the workflow, that's a huge help (you'll need to save it as .txt, or zip the .json file, because GitHub doesn't accept .json). + +## Cautions + +Bypassing and disabling nodes works, but with one catch. If you have a UE nodes that does matching (`Anything Everywhere?` and `Prompt Everywhere`) and you bypass the node it matches to, the link won't be made. So + +|If you use a ? node to send to a node...|...and bypass the recipient, it doesn't get connected | +|-|-| +|![1](docs/bypass_catch1.png)|![2](docs/bypass_catch2.png)| + +This is unlikely to be fixed, but should be fairly easy to avoid! + + +--- +# Some older information + +# Update for ComfyUI front end 1.16 and above + +ComfyUI front end 1.16 made a major change to the way that inputs and widgets work, which had a significant impact on the UE nodes. + +A widget is no longer converted to an input in order to connect to it; instead, you just connect an output to it, and it converts. + +This is quite cool - except that it meant that there was no way for UE to tell if a widget was supposed to be an empty input for UE to feed. + +So there is a new mechanism for this. Here's a picture of a node that I have right-clicked: + +![116](docs/116.png) + +Things to notice: + +- There is a new menu `UE Connectable Widgets` which lists all the widgets. Those marked as connectable have a green bar to the left of the name. + - Select a widget to toggle its value +- Next to the widget, where an input would be, the connectable widgets have a graphical indication of their state. + - The smaller dark circle (next to steps) indicate a connectable node which is not connected (widget value will be used) + - The light circle (next to cfg) and greying out the widget indicates that a UE node will provide the value + - No icon (all the other widgets) indicates that they are not UE connectable +- Other inputs still have the indications of normal connection or UE connection (here model is a UE connection) + +You'll probably find that turning the `showlinks` option on helps, and the `highlight` option is required for those widget indicators which help a lot. + +![options116](docs/options116.png) + +Hopefully old workflows will be automatically converted when you load them. Hopefully. + +## Naming widgets + +The `Prompts Everywhere`, `Seed Everywhere`, and `Anything Everywhere?` all make use of the name of an input. On some occasions this might mean you want to rename an input. + +For an input that can't be a widget, that's trivial - right click on the input dot and select `Rename Slot`. The name will be updated, and the new name displayed next to the dot. + +If an input *can* be a widget, you can rename it in the same way, but the new name *does not get displayed*. The name has changed, and the UE nodes will use the new name, but the old name is still shown. I consider this to be a bug in the Comfy front-end, and have raised an issue [here](https://github.com/Comfy-Org/ComfyUI_frontend/issues/3654). Unfortunately it appears that Comfy UI is going to remove the ability to rename a widget entirely, so best to avoid using widget input names if at all possible. diff --git a/cg-use-everywhere/README.md b/cg-use-everywhere/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3eaa17136c8ff93126df996882e61405fa731a65 --- /dev/null +++ b/cg-use-everywhere/README.md @@ -0,0 +1,516 @@ +# UE Nodes + +## Love this node? + +[Buy me a coffee!](https://www.buymeacoffee.com/chrisgoringe) + +## Shameless plug + +Check out [Image Picker](https://github.com/chrisgoringe/cg-image-filter) for another way to make some workflows smoother. + +# What is Anything Everywhere? + +The `Anything Everywhere` node takes one or more inputs and sends the data to other nodes that need it. +You can connect as many inputs to an `Anything Everywhere` node as you like, and there are a range of ways +to control where the data will be sent. + +Here's the standard ComfyUI template modified to use `AnythingEverywhere` + +|workflow|output image you can drop into Comfy| +|-|-| +|![simple](docs/simple-example.png)|![simple](docs/simple-example-image.png)| + +The `MODEL`, `CLIP`, and `VAE` are automatically broadcast to all the places they are needed. + +Doesn't make much difference in this simple case, but with complex workflows it really does. +This is what the default wan 2.2 s2v video workflow looks like: + +|before|after| +|-|-| +|![before](docs/before.png)|![after](docs/after.png)| + +# Getting started + +Drop [this workflow](docs/UE_example.json) into Comfy, and take a look at how it works. + +# Common Questions + +## How do I get positive and negative conditionings to work? + +Connect both to a single UE node, and then rename the inputs. See [here](https://github.com/chrisgoringe/cg-use-everywhere/issues/317#issuecomment-3663225670). + +Or use node broadcasting, as in the [example workflow](docs/UE_example.json) + +## Why doesn't it work with reroutes / primitives? + +Nodes which dynamically work out their data type are a real problem that isn't worth the complexity to fix. See [here](https://github.com/chrisgoringe/cg-use-everywhere/tree/main#primitives-and-reroutes) for more info. + +## Can I broadcast a COMBO, like my choice of sampler? + +Yes. See Combo Clone node [here](https://github.com/chrisgoringe/cg-use-everywhere/tree/main#special-case-nodes). + +# Recent Changes + +## 7.8 + +- Added regex match of outputs to the repeated types options +- Fixed issues with the new ComfyUI autogrow inputs +- Fixed API export to save with real links [389](https://github.com/chrisgoringe/cg-use-everywhere/issues/389) + +## 7.7 + +- Added "Apply to unrepeated output" options +- Cleaned up restrictions dialog +- Internal refactoring to conform to ComfyUI changes + +## 7.6 + +- Added visual indicators to subgraph nodes +- Added hover-over conflicted node to show conflict +- Added "Send to Any" option in restrictions + +
+Older changes + +## 7.5 + +- Added per-output granularity to any-node broadcasting +- Prompt Everywhere node deprecated and auto-replaced +- Convert to real links now works for any-node broadcasting +- Anything Everywhere nodes in a subgraph can broadcast to its output +- Inputs which have a clash of two more possible UE sources are marked with a red cross +- Couple of bug fixes, including one significant performance issue + +## 7.4 + +- Added broadcasting from [any node](#any-node-broadcasting) +- Added negative regex option +- Seed Everywhere node deprecated and auto-replaced + +## 7.3 + +Bugfixes: +[361](https://github.com/chrisgoringe/cg-use-everywhere/issues/361), +[379](https://github.com/chrisgoringe/cg-use-everywhere/issues/379), +[381](https://github.com/chrisgoringe/cg-use-everywhere/issues/381) + +## 7.2.1 and 7.2.2 + +Bugfixes: +[383](https://github.com/chrisgoringe/cg-use-everywhere/issues/383), +[384](https://github.com/chrisgoringe/cg-use-everywhere/issues/384), +[388](https://github.com/chrisgoringe/cg-use-everywhere/issues/388) + +## 7.2 + +- Added support for [Combo inputs](#combo-clone) via the `Combo Clone` helper node +- Fixed a number of issues related to subgraphs +- Improved handling of disconnect +- Added new options for handling multiple inputs of same type +- Added internationalisation options + +## 7.1 + +- Allowed individual inputs to block UE connections +- Added support for multiple inputs of the same type +- Fixed a number of minor subgraph issues +- Fixed a serious bug with UE on Safari [details](https://github.com/chrisgoringe/cg-use-everywhere/issues/359) + +
+ +# Any node broadcasting + +
+New in version 7.4 - any node can broadcast it's outputs + +As of version `7.4`, any node can be set to broadcast with `Add UE broadcasting` in the right-click menu. I find this really helpful for subgraphs especially. + +When broadcasting, the node acts like all its outputs were connected to a single UE node, so + +|This...|...does the same as this| +|-|-| +|![with](docs/broadcaston.png)|![without](docs/broadcastoff.png)| + +From `7.5`, the outputs that will broadcast can also be set (like inputs): + +![output_set](docs/output_set.png) + +
+ +# Where will the data be sent? + +The key to using Anything Everywhere nodes is understanding where the data will be sent. + +By default the data will be sent to any input of the same data type which does not have a connection, +and does not have a widget providing the value. + +
+ +At the sending end, you can constrain where the data gets send through restrictions applied to the `Anything Everywhere` node. + + +Restrictions can be accessed by double-clicking the body of the node, or through the right-click menu. + +![restrictions](docs/restrictions.png) + +The first three entries are [regex](https://regex101.com/) patterns. +The node will only send data to another node if the regex matches the receiving node title, the name of the input, or the name of a group the receiving node is in, respectively. Check the 'invert' checkbox to invert the regex (send only to things which _don't_ match). + +The Group and Colour restrictions will constrain the node to only send to nodes in (or not in) the same group, and of the same (or different) colour. + +`Repeated Types` determines behaviour when more than one input of the same type is connected to an `Anything Everywhere` node. +In this case an additional constraint is used to disambiguate which inputs match +by comparing the name of the input slot on the `Anything Everywhere` node with +either the name of the input slot on the target node, or the name of the target node. +The `match start` and `match end` options require that the input names match from the start (or end) for the full length of the shorter: +so you can match `seed` to `seed` or `noise_seed` by naming the `Anything Everywhere` input `seed` and selecting `Match end of input names`. + +You can also give the output a name which is a regex, and select `Regex match of input names` - so if your output is named `prompt|text` it +will match inputs named `prompt` or `text`. + +If `Apply to Unrepeated` is set to `Yes`, the `Repeated Types` rule will be applied to all outputs, whether or not they are repeated. + +`Send To Any`(default 'no') can be used to allow this node to send data to inputs with the `Any` type. + +`Priority` is used to resolve conflicts between multiple sending nodes. It has a default value (which generally follows the rule that the more restrictive the rules, the higher the priority), but you can override that value. + +If you select multiple restrictions, all must be satisfied for the node to send. + +If any restrictions are applied, the `Anything Everywhere` node gets a green circle in the top left hand corner, and a tooltip if you hover the mouse over it (as long as Show Links is not set to None). + +You can rename input slots by right-clicking on the input dot - but you can't rename widget inputs - this is a limitation imposed by ComfyUI ([discussion](https://github.com/Comfy-Org/ComfyUI_frontend/issues/3654)). The work-around is to rename the target node (or use multiple `Anything Everywhere` nodes with other constraints, especially color matching). + +
+ +
+ +At the receiving end: you can specify that an input should not accept data, or that one with a widget should. + + +In the `UE Connectable Inputs` menu (right-click on a node): +the green bar indicates an input is connectable. The `Reject UE links` option can be used to make this node completely reject UE links, regardless of other settings. + +![uec](docs/connectable.png) +
+ +
+ +What if two or more `Anything Everywhere` nodes can send to the same input? How are conflicts resolved? + + +Each node has an automatically calculated priority - in general the more restrictive the node, the higher the priority. +You can see this prority in the restrictions dialog, and you can choose to replace the automatically calculated value if you wish. + +If two more more `Anything Everywhere` nodes match the same input, the higher priority node is used. If there is a tie, _no connection is made_. +The input is marked with a red cross to indicate that there is a conflict. If you hover over the node, the two (or more) conflicting UE inputs +are shown as red lines. + +Alternatively, if you right-click on the canvas you will find an option to show which nodes are the problem. + +
+ +# Visual Clues + +Anything Everywhere has a number of ways to help you visualise what it is doing. + +
+Show Anything Everywhere links + +If you want to see the UE links, you can turn them on and off by right-clicking on the canvas. For finer control, the main settings menu has options to show links when the mouse moves over the node at either end, or when one of those nodes is selected. + +The links can be animated to distinguish them from normal links - this animation can take the form of moving dots, a pulsing glow, or both. This may impact performance in some cases - note that the pulse animation requires less processing than the moving dots. Control this in the main settings menu. + +Animation takes quite a lot of processing, so don't use it unless you really need to. By default the animations turn off when the workflow is running to minimise impact on CPU/GPU - you can change this in the settings too. +
+ +
+Nodes that broadcast have a badge + +Any node that is capable of broadcasting data (a UE node, or another node to which broadcasting has been added) is marked with a circle in the top left hand corner. + +If the circle is green, the node has no additional restrictions on where data will be sent; +if it is yellow, it has one or more restrictions (which you can see by hovering your mouse over it, or by editing restrictions +with the option on the right click menu, or by double clicking the node). + +If the node is actually sending data, the circle (red or yellow) is bold; if the node is capable of sending but is not actually making +and connections, it is muted. + +![redgreen](docs/yellowgreen.png) +
+ +
+Inputs and outputs have a subtle visual clue + +The state of inputs is also represented visually: a black ring and a glow on the input dot indicates it is connectable. +In the image below, `positive` has been set to not accept UE inputs, `steps` has been set to accept them, and `model` has a UE connection. + +![uec](docs/connectable2.png) + +If a widget is getting data from a UE connection, it is grayed out, like `steps` below: + +![uec](docs/connectable3.png) + +Similarly, if a node has had broadcasting added to it, the outputs that can broadcast are shown: +here `merged` can broadcast, but isn't, `x` can broadcast and is, and `y` is set to not broadcast. + +![outputs](docs/outputs.png) + +
+ +
+Conflicts show up in red + +If two (or more) broadcasters with the same priority could send to the same input, the input will be marked with a red cross. +If UE links are being shown all possible links are shown in red. Here two model loaders are broadcasting... + +![conflict](docs/conflict.png) + +
+ +# Special Case Nodes + +
+To broadcast to COMBO (dropdown menu) widgets, you can either use String to Combos (above) or a Combo Clone + +For each Combo type you want to use, add a Combo Clone node. Here we want to be able to broadcast `sampler_name` and `scheduler`. + +![CC1](docs/ComboClone1.png) + +Connect the `Combo Clone` output to a widget you want it to replicate. The `Combo Clone` copies the options from that widget, and the widget name. + +![CC2](docs/ComboClone2.png) + +Disconnect the `Combo Clone` and connect it to an `Anything Everywhere` node. The name copying means you can connect multiple Combos to a single `Anything Everywhere` node. + +![CC3](docs/ComboClone3.png) + +It can now broadcast to any node with the same input type (but remember you will have to mark the Combo widget as UE Connectable, since widgets are not connectable by default). + +
+ +
+Prompts Everywhere handles a positive and a negative prompt + + +Prompt Everywhere has two inputs. They will be sent with regex matching rules designed to match `prompt` or `positive`, and `neg`, respectively. + +The actual regexes used are `(_|\\b)pos(itive|_|\\b)|^prompt|正面` and `(_|\\b)neg(ative|_|\\b)|负面` + +|strings|conditionings| +|-|-| +|![pe](docs/PE.png)|![pe](docs/conditioning.png) + +
+ + +
+Seed Everywhere, Anything Everywhere? and Anything Everywhere3 are deprecated and will be automatically replaced + +The `Seed Everywhere` node will be replaced with a primitive int, set to broadcast, with an input regex restriction that matches the localised name of the `seed` input on the base `KSampler` node - `seed` or `随机种` being the most common. + +The `Anything Everywhere?` node will be replaced with an `Anything Everywhere` node with restrictions. + +The `Anything Everywhere3` node will be replaced with an `Anything Everywhere` node with multiple inputs and any appropriate restrictions. + +These replacements should not break any workflows. If they do... sorry. + +
+ + +# Options + +
+ +In the main settings menu, you will find the Use Everywhere options: + + +![options](docs/options.png) + +The top set, `Graphics`, modify the visual appearance only. + +The bottom set, `Options`, modify behaviour: + +- When connecting, use the output slot's name as the input name. When a new connection is made to a UE node, the default is to name the input with the type. Select this option to use the output name of the node the link is from. +- Block workflow validation. This prevents other nodes from complaining about the lack of connections, or creating them. If you turn this off, there may be unexpected consequences. +- Logging. Increase the logging level if you are asked to help debug. +- Connect to bypassed nodes. When off, Use Everywhere will not connect to a bypassed node, and will attempt to work out whether an input is connected when upstream nodes are bypassed. I recommend turning this on. + +
+ +# Primitives and Reroutes + +
+ +UE nodes work with the new primitives added in more recent versions of Comfy (in the `primitive` submenu) + + +![primitives](docs/primitives.png) + +UE nodes do not work with the old-style `Primitive` nodes (which automatically determined what data type they needed to be), +nor do they work with reroute nodes. + +In both cases that is dues to some issues that are deep within ComfyUI, related to the way that these nodes work out +the data type they represent, which makes it next to impossible for UE to correctly intereact with them. + +
+ +# Other features + +
+ +Third Party Integration - the UE API + + +At the suggestion of [@fighting-tx](https://github.com/fighting-tx), +I've added a method that third party nodes can use if they want to see the prompt as generated by UE. +It's attached to the `app` object, so you can check if it is present and use it something like this: + +```js +var prompt +if (app.ue_modified_prompt) { + prompt = await app.ue_modified_prompt() +} else { + prompt = await original_graphToPrompt.apply(app) +} +``` + +Other methods could be exposed if there is interest - raise an issue if you'd like to see something. +
+ +
+ +Convert to real links + + +If you want to share a workflow without Anything Everywhere nodes being required, or to save an API version of a workflow, you can replace the virtual links created by Anything Everywhere nodes with real links (and remove the UE nodes). + +This can be done for a single node by right-clicking on it and selecting `Convert to real links`, or for all UE nodes in a graph or subgraph by right-clicking the background and selecting `Convert all UEs to real links`. + +
+ +# Subgraphs + +Anything Everywhere works fairly well with the new subgraphs (and setting a subgraph to broadcast its outputs is very powerful!). +A couple of caveats: + +
+Data is only broadcast within a graph + +Anything Everywhere will not make links from nodes in one graph into a different graph. So you cannot broadcast data into a subgraph, nor can you broadcast it out. + +This is a deliberate design decision, reflecting the fundamental principle of subgraphs - that they are self contained. +Data can only go in or out of a subgraph through its input and output panels. +This sort of data isolation is a very good thing in terms of maintaining a workflow, and by working consistently with the expectated +behaviour of subgraphs it is far less like that future changes in the front end will break Anything Everywhere. + +This is not open for discussion. There are plenty of better ways to achieve the same end. + +An Anything Everywhere node in your main graph can send to the input of a subgraph node; +you can also connect as Anything Everywhere node to one of the inputs inside a subgraph. + +You can connect an output of the subgraph node to an Anything Everywhere node (or set the subgraph node to broadcast), +and you can broadcast from within the subgraph to the output panel of the subgraph. + +
+ +
+ +When you create a subgraph, Anything Everywhere nodes do their best... + +There are three nodes involved in every UE link: +- Source (the link sending the data), +- Control (the UE node connected to the source), +- Target (the node that is receiving the data as an input) + +This is how those cases are treated: + +|Support|Source|Control|Target|| +|-|-|-|-|-| +|Yes|Graph|Graph|Graph|Nothing changes| +|Yes|Graph|Graph|Subgraph|The subgraph will have inputs for the data; in the subgraph the input panel is connected to the Target with a real link| +|No|Graph|Subgraph|Graph|Not supported| +|No*|Graph|Subgraph|Subgraph|Not supported| +|Yes|Subgraph|Graph|Graph|The subgraph will be connected to the Control| +|No|Subgraph|Graph|Subgraph|Not supported| +|Yes|Subgraph|Subgraph|Graph|The Source will be connected to the Control *and* the output panel in the subgraph, the output will be connected to the Target with a real link| +|Yes|Subgraph|Subgraph|Subgraph|All nodes will be connected in the subgraph as they were in the graph| + +No* indicates a case that does not work, but might get implemented. + +No indicates a case I'm unlikely ever to support + +
+ +# Reporting a bug well + +If there is a bug in Anything Everywhere, I want to fix it. +But my ability to do so depends on the quality of the information I have. + +Seriously, people submit bug reports which just say "It isn't working since I updated". +Well, it's working for me, so I don't have any idea what your problem is. + +Give me good information, and if I can reproduce the problem, there's a good chance I'll fix it (or suggest a work-around). + +So if you have a problem, go to [the issues page](https://github.com/chrisgoringe/cg-use-everywhere/issues), +click on `New Issue`, select, `Bug Report`, and fill in as much of the information as you can. + +# Suggesting new features + +Go to [the issues page](https://github.com/chrisgoringe/cg-use-everywhere/issues), +click on `New Issue`, select, `Feature Request`, and tell me your idea. +If you can explain why the feature would be helpful to you, and ideally to others, I'm +much more likely to think about whether it's possible. + +# Thanks to + +The following people have contributed code or helpful discussions, without which these nodes would be less good! + +- [DrJKL](https://github.com/DrJKL) +- [fighting-tx](https://github.com/fighting-tx) +- [huchenlei](https://github.com/huchenlei) +- [fichas](https://github.com/fichas) +- [LukeG89](https://github.com/LukeG89) +- [set-soft](https://github.com/set-soft) +- [TinyTerra](https://github.com/TinyTerra) +- [bananasss00](https://github.com/bananasss00) +- [JorgeR81](https://github.com/JorgeR81) + +Feel free to [make suggestions, or implement features](https://github.com/chrisgoringe/cg-use-everywhere/issues) to get your name added here! + +--- + +# Anything Everywhere v7 + +Version 7 is a major update to the Anything Everywhere nodes, so the documentation below is all new. If you are looking for the old docs, you can find them [here](https://github.com/chrisgoringe/cg-use-everywhere/README-old). + +
+Major changes in v7 + +If you used Anything Everywhere prior to v7, the major improvements are: + +- The `Anything Everywhere3` and `Anything Everywhere?` nodes are deprecated, as their features are now part of the standard `Anything Everywhere` node. +- `Anything Everywhere` nodes now have dynamic inputs, so you can plug as many different things into them as you like. +- All the restrictions on what nodes data will be sent to are now in a restrictions editor, that can be accessed through the right click menu of the node, or by double-clicking the body of the node. + - In the restrictions editor you can set title, input, and group regexes, color restrictions, group restrictions, and priority (for when two nodes both match) + - The green circle is used to indicate that _any_ restrictions are in place; if you hover over a node with restrictions they will appear in a tooltip +- Subgraphs are supported (in the majority of cases). Yay subgraphs! Seriously, they are _so_ much better than group nodes. + - There are lots of odd cases with subgraphs, so if you find a case not covered properly, please [raise an issue](https://github.com/chrisgoringe/cg-use-everywhere/issues) + +There are a couple of features that have been removed: + +- Group nodes are no longer supported, as they are deprecated in ComfyUI in favour of the new subgraphs, which are supported (in most configurations) +- The `Simple String` mechanism to provide an input to the regex of an `Anything Everywhere?` node is no longer supported + - Other UI mechanisms to address this need are under consideration + +## Upgrade considerations + +Other than the limitations noted, old workflows _should_ load and work out of the box, +with `Anything Everywhere3` and `Anything Everywhere?` nodes automatically converted to `Anything Everywhere` nodes with the appropriate restrictions applied. + +However, there may be edge cases that don't work; if you have any problems, please [raise an issue](https://github.com/chrisgoringe/cg-use-everywhere/issues). + +You will _not_ be able to use workflows saved using v7 with older versions of ComfyUI or older versions of UE. + +**Group Nodes are no longer supported** + +
diff --git a/cg-use-everywhere/__pycache__/__init__.cpython-310.pyc b/cg-use-everywhere/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdacf99f6d5de42a4f96b7afc808d985259caa4e Binary files /dev/null and b/cg-use-everywhere/__pycache__/__init__.cpython-310.pyc differ diff --git a/cg-use-everywhere/__pycache__/use_everywhere.cpython-310.pyc b/cg-use-everywhere/__pycache__/use_everywhere.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ae8317a3226332457ba1fbccba89db71684be80 Binary files /dev/null and b/cg-use-everywhere/__pycache__/use_everywhere.cpython-310.pyc differ diff --git a/cg-use-everywhere/docs/UE_example.json b/cg-use-everywhere/docs/UE_example.json new file mode 100644 index 0000000000000000000000000000000000000000..61f16f6cabbb1eaa4aee01f9270e5523d8e06034 --- /dev/null +++ b/cg-use-everywhere/docs/UE_example.json @@ -0,0 +1 @@ +{"id":"de3849cc-8b9a-4429-9046-11182ba85065","revision":0,"last_node_id":10,"last_link_id":16,"nodes":[{"id":9,"type":"SaveImage","pos":[1451,189],"size":[210,58],"flags":{},"order":7,"mode":0,"inputs":[{"localized_name":"images","name":"images","type":"IMAGE","link":9},{"localized_name":"filename_prefix","name":"filename_prefix","type":"STRING","widget":{"name":"filename_prefix"},"link":null}],"outputs":[],"properties":{"Node name for S&R":"SaveImage","ue_properties":{"widget_ue_connectable":{},"version":"7.0.1"}},"widgets_values":["ComfyUI"]},{"id":8,"type":"VAEDecode","pos":[1209,188],"size":[210,46],"flags":{},"order":6,"mode":0,"inputs":[{"localized_name":"samples","name":"samples","type":"LATENT","link":7},{"localized_name":"vae","name":"vae","type":"VAE","link":16}],"outputs":[{"localized_name":"IMAGE","name":"IMAGE","type":"IMAGE","slot_index":0,"links":[9]}],"properties":{"Node name for S&R":"VAEDecode","ue_properties":{"widget_ue_connectable":{},"version":"7.0.1"}},"widgets_values":[]},{"id":4,"type":"CheckpointLoaderSimple","pos":[735.590087890625,-18.939699172973633],"size":[374.6396484375,98],"flags":{},"order":0,"mode":0,"inputs":[{"localized_name":"ckpt_name","name":"ckpt_name","type":"COMBO","widget":{"name":"ckpt_name"},"link":null}],"outputs":[{"localized_name":"MODEL","name":"MODEL","type":"MODEL","slot_index":0,"links":[10]},{"localized_name":"CLIP","name":"CLIP","type":"CLIP","slot_index":1,"links":[11]},{"localized_name":"VAE","name":"VAE","type":"VAE","slot_index":2,"links":[12]}],"properties":{"Node name for S&R":"CheckpointLoaderSimple","models":[{"name":"v1-5-pruned-emaonly-fp16.safetensors","url":"https://huggingface.co/Comfy-Org/stable-diffusion-v1-5-archive/resolve/main/v1-5-pruned-emaonly-fp16.safetensors?download=true","directory":"checkpoints"}],"ue_properties":{"widget_ue_connectable":{},"version":"7.0.1"}},"widgets_values":["v1-5-pruned-emaonly-fp16.safetensors"]},{"id":10,"type":"Anything Everywhere","pos":[1166.6490478515625,-18.49173927307129],"size":[181.3697265625,86],"flags":{},"order":2,"mode":0,"inputs":[{"color_on":"#B39DDB","label":"MODEL","localized_name":"anything","name":"anything","shape":7,"type":"MODEL","link":10},{"color_on":"#FFD500","label":"CLIP","name":"anything11","type":"CLIP","link":11},{"color_on":"#FF6E6E","label":"VAE","name":"anything12","type":"VAE","link":12},{"label":"anything","name":"anything13","type":"*","link":null}],"outputs":[],"properties":{"Node name for S&R":"Anything Everywhere","ue_properties":{"version":"7.0.1","group_restricted":0,"color_restricted":0,"widget_ue_connectable":{},"title_regex":null,"input_regex":null,"group_regex":null,"next_input_index":13}},"widgets_values":[]},{"id":3,"type":"KSampler","pos":[863,186],"size":[271.1831359863281,264.43426513671875],"flags":{},"order":3,"mode":0,"inputs":[{"localized_name":"model","name":"model","type":"MODEL","link":13},{"localized_name":"positive","name":"positive","type":"CONDITIONING","link":null},{"localized_name":"negative","name":"negative","type":"CONDITIONING","link":null},{"localized_name":"latent_image","name":"latent_image","type":"LATENT","link":2},{"localized_name":"seed","name":"seed","type":"INT","widget":{"name":"seed"},"link":null},{"localized_name":"steps","name":"steps","type":"INT","widget":{"name":"steps"},"link":null},{"localized_name":"cfg","name":"cfg","type":"FLOAT","widget":{"name":"cfg"},"link":null},{"localized_name":"sampler_name","name":"sampler_name","type":"COMBO","widget":{"name":"sampler_name"},"link":null},{"localized_name":"scheduler","name":"scheduler","type":"COMBO","widget":{"name":"scheduler"},"link":null},{"localized_name":"denoise","name":"denoise","type":"FLOAT","widget":{"name":"denoise"},"link":null}],"outputs":[{"localized_name":"LATENT","name":"LATENT","type":"LATENT","slot_index":0,"links":[7]}],"properties":{"Node name for S&R":"KSampler","ue_properties":{"widget_ue_connectable":{},"version":"7.0.1"}},"widgets_values":[156680208700286,"randomize",20,8,"euler","normal",1]},{"id":5,"type":"EmptyLatentImage","pos":[307.7400090644893,580.0590898977044],"size":[315,106],"flags":{},"order":1,"mode":0,"inputs":[{"localized_name":"width","name":"width","type":"INT","widget":{"name":"width"},"link":null},{"localized_name":"height","name":"height","type":"INT","widget":{"name":"height"},"link":null},{"localized_name":"batch_size","name":"batch_size","type":"INT","widget":{"name":"batch_size"},"link":null}],"outputs":[{"localized_name":"LATENT","name":"LATENT","type":"LATENT","slot_index":0,"links":[2]}],"properties":{"Node name for S&R":"EmptyLatentImage","ue_properties":{"widget_ue_connectable":{},"version":"7.0.1","input_ue_unconnectable":{}}},"widgets_values":[512,512,1]},{"id":7,"type":"CLIPTextEncode","pos":[378.6495986829062,369.525945395182],"size":[239.05628967285156,133.13778686523438],"flags":{},"order":5,"mode":0,"inputs":[{"localized_name":"clip","name":"clip","type":"CLIP","link":15},{"localized_name":"text","name":"text","type":"STRING","widget":{"name":"text"},"link":null}],"outputs":[{"localized_name":"CONDITIONING","name":"CONDITIONING","type":"CONDITIONING","slot_index":0,"links":[]}],"properties":{"Node name for S&R":"CLIPTextEncode","ue_properties":{"widget_ue_connectable":{},"version":"7.0.1","input_ue_unconnectable":{},"output_not_broadcasting":{},"input_regex":"negative"},"ue_convert":true},"widgets_values":["text, watermark"]},{"id":6,"type":"CLIPTextEncode","pos":[349.274802144649,137.44981076801105],"size":[251.2289276123047,157.01023864746094],"flags":{},"order":4,"mode":0,"inputs":[{"localized_name":"clip","name":"clip","type":"CLIP","link":14},{"localized_name":"text","name":"text","type":"STRING","widget":{"name":"text"},"link":null}],"outputs":[{"localized_name":"CONDITIONING","name":"CONDITIONING","type":"CONDITIONING","slot_index":0,"links":[]}],"properties":{"Node name for S&R":"CLIPTextEncode","ue_properties":{"widget_ue_connectable":{},"version":"7.0.1","input_ue_unconnectable":{},"output_not_broadcasting":{},"input_regex":"positive"},"ue_convert":true},"widgets_values":["beautiful scenery nature glass bottle landscape, , purple galaxy bottle,"]}],"links":[[2,5,0,3,3,"LATENT"],[7,3,0,8,0,"LATENT"],[9,8,0,9,0,"IMAGE"],[10,4,0,10,0,"MODEL"],[11,4,1,10,1,"CLIP"],[12,4,2,10,2,"VAE"]],"groups":[],"config":{},"extra":{"controller_panel":{"controllers":{},"hidden":true,"highlight":true,"version":2,"default_order":[]},"ue_links":[{"downstream":8,"downstream_slot":1,"upstream":"4","upstream_slot":2,"controller":10,"type":"VAE"},{"downstream":3,"downstream_slot":0,"upstream":"4","upstream_slot":0,"controller":10,"type":"MODEL"},{"downstream":3,"downstream_slot":1,"upstream":"6","upstream_slot":0,"controller":6,"type":"CONDITIONING"},{"downstream":3,"downstream_slot":2,"upstream":"7","upstream_slot":0,"controller":7,"type":"CONDITIONING"},{"downstream":7,"downstream_slot":0,"upstream":"4","upstream_slot":1,"controller":10,"type":"CLIP"},{"downstream":6,"downstream_slot":0,"upstream":"4","upstream_slot":1,"controller":10,"type":"CLIP"}],"cg_status_position":[85,136],"links_added_by_ue":[13,14,15,16],"ds":{"scale":0.8216012084592145,"offset":[278.090440164136,279.3643015324795]},"node_versions":{"comfy-core":"0.18.1","cg-use-everywhere":"98286cadb33486c27d87759f24b4813bbbda8799"},"frontendVersion":"1.25.9"},"version":0.4} \ No newline at end of file diff --git a/cg-use-everywhere/docs/restrictions.png b/cg-use-everywhere/docs/restrictions.png new file mode 100644 index 0000000000000000000000000000000000000000..29c50da056e950b86f81deabc50005b436b2e30d Binary files /dev/null and b/cg-use-everywhere/docs/restrictions.png differ diff --git a/cg-use-everywhere/docs/yellowgreen.png b/cg-use-everywhere/docs/yellowgreen.png new file mode 100644 index 0000000000000000000000000000000000000000..94f4e69bfe83768ba85ccf0992c595fb90370a11 Binary files /dev/null and b/cg-use-everywhere/docs/yellowgreen.png differ diff --git a/cg-use-everywhere/js/floating_window.js b/cg-use-everywhere/js/floating_window.js new file mode 100644 index 0000000000000000000000000000000000000000..2e8918eaa75a3d47f0490b9a59e5ec5a580e4397 --- /dev/null +++ b/cg-use-everywhere/js/floating_window.js @@ -0,0 +1,123 @@ +import { create } from "./use_everywhere_utilities.js" +import { settingsCache } from "./use_everywhere_cache.js" + + +export class FloatingWindow extends HTMLElement { + constructor() { + super() + this.classList.add('ue_editor') + this.header = create('div', 'ue_editor_header', this) + this.body = create('div', 'ue_editor_body', this) + this.footer = create('button', 'ue_editor_footer', this, { innerText: "Close" }) + + /** @type {HTMLElement | null} */ + this.firstFocusable = null + /** @type {HTMLElement | null} */ + this.lastFocusable = null + + this.header.addEventListener('mousedown',this.start_dragging.bind(this)) + this.addEventListener('mousemove', this.mousemovedover.bind(this)) + document.addEventListener('mousemove', this.mousemoved.bind(this)) + document.addEventListener('mouseup',this.stop_dragging.bind(this)) + document.addEventListener('mouseleave',this.stop_dragging.bind(this)) + this.footer.addEventListener('click', this.hide.bind(this)) + this.addEventListener("keydown", this.handle_keydown.bind(this)); + + this.dragging = false + this.hide() + document.body.append(this) + } + + show() { + this.style.display = 'flex'; + const tt = document.getElementById('ue_tooltip') + if (tt) tt.style.display = 'none' + this.showing = true + } + hide() { + this.style.display = 'none' + this.showing = false + } + set_title(title) { + this.header.innerText = title + } + set_body(element) { + this.body.innerHTML = "" + this.body.appendChild(element) + this.setup_focus_trap() + } + + maybe_move_to(x,y) { + if (this.position && settingsCache.getSettingValue("Use Everywhere.Graphics.preserve edit window position")) return + this.move_to(x,y) + } + + move_to(x,y) { + this.position = {x:x,y:y} + this.style.left = `${this.position.x}px` + this.style.top = `${this.position.y}px` + } + + swallow(e) { + e.stopPropagation() + e.preventDefault() + } + + start_dragging(e) { + this.dragging = true + this.swallow(e) + } + + stop_dragging(e) { + this.dragging = false + } + + mousemovedover(e) { + this.mousemoved(e) + this.swallow(e) + } + + mousemoved(e) { + if (this.dragging) this.move_to( this.position.x + e.movementX , this.position.y + e.movementY ) + } + + /** @param {KeyboardEvent} e */ + handle_keydown(e) { + if (e.key === "Escape" || e.key === "Enter") { + this.hide() + return + } + if (e.key === "Tab") { + if (e.shiftKey && document.activeElement === this.firstFocusable) { + this.lastFocusable.focus() + e.preventDefault() + return + } + if (!e.shiftKey && document.activeElement === this.lastFocusable) { + this.firstFocusable.focus() + e.preventDefault() + } + } + } + + setup_focus_trap() { + this.firstFocusable = null + this.lastFocusable = null + + const focusableEls = this.querySelectorAll('a[href]:not([disabled]), button:not([disabled]), textarea:not([disabled]), input[type="text"]:not([disabled]), input[type="radio"]:not([disabled]), input[type="checkbox"]:not([disabled]), select:not([disabled])') + if (focusableEls?.length == 0) return + + this.firstFocusable = focusableEls[0] ?? null + this.lastFocusable = focusableEls[focusableEls.length - 1] ?? null + + if (this.firstFocusable) { + setTimeout(() => { + this.firstFocusable.focus() + }, 0); + } + } +} + + +customElements.define('ue-floating', FloatingWindow) +export const edit_window = new FloatingWindow() diff --git a/cg-use-everywhere/js/i18n.js b/cg-use-everywhere/js/i18n.js new file mode 100644 index 0000000000000000000000000000000000000000..053ff1c398da9f73f1f4b07f38b8aba6c0ced400 --- /dev/null +++ b/cg-use-everywhere/js/i18n.js @@ -0,0 +1,107 @@ +import { app } from "../../scripts/app.js"; + +export var REPEATED_TYPE_OPTIONS; +export var GROUP_RESTRICTION_OPTIONS; +export var COLOR_RESTRICTION_OPTIONS; + + +var _FUNCTIONAL = null +var _FUNCTIONAL_REGEX = null + +const _DISPLAY = { + 'en' : { + + }, + 'zn' : { + + } +} + +function DISPLAY(v, lang) { return _DISPLAY[lang || current_language()]?.[v] || _DISPLAY['en'][v] || v } + +function current_language() { + return app.ui.settings.getSettingValue('Comfy.Locale') +} + +export function language_changed(is_now, was_before) { + _FUNCTIONAL = null + _FUNCTIONAL_REGEX = null + + REPEATED_TYPE_OPTIONS = [ + i18n("Exact match of input names"), + i18n("Match start of input names"), + i18n("Match end of input names"), + i18n("Inputs matches target node name"), + i18n("Regex match of input names"), + ] + + GROUP_RESTRICTION_OPTIONS = [ + i18n("No restrictions"), + i18n("Send only within group"), + i18n("Send only not within group") + ] + + COLOR_RESTRICTION_OPTIONS = [ + i18n("No restrictions"), + i18n("Send only to same color"), + i18n("Send only to different color") + ] +} + +function get_functional() { + const nd = LiteGraph.createNode('KSampler') + if (nd) { + _FUNCTIONAL = { + seed_input_regex : `seed|${nd.inputs.find((i)=>(i.name=='seed')).localized_name}`, + prompt_regex : `(_|\\b)pos(itive|_|\\b)|${nd.inputs.find((i)=>(i.name=='positive')).localized_name}`, + negative_regex : `(_|\\b)neg(ative|_|\\b)|${nd.inputs.find((i)=>(i.name=='negative')).localized_name}`, + seed : nd.inputs.find((i)=>(i.name=='seed')).localized_name, + positive : nd.inputs.find((i)=>(i.name=='positive')).localized_name, + negative : nd.inputs.find((i)=>(i.name=='negative')).localized_name, + + } + } +} + +function get_functional_regex() { + if (!_FUNCTIONAL) get_functional() + _FUNCTIONAL_REGEX = { + prompt_regex : new RegExp(_FUNCTIONAL.prompt_regex), + negative_regex : new RegExp(_FUNCTIONAL.negative_regex), + } +} + +export function i18n_functional(v) { + if (!_FUNCTIONAL) get_functional() + return _FUNCTIONAL?.[v] || v +} + +export function i18n_functional_regex(v) { + if (!_FUNCTIONAL_REGEX) get_functional_regex() + return _FUNCTIONAL_REGEX[v] +} + +const all_requested_stings = new Set() +export function i18n(v, extras) { + all_requested_stings.add(v) + var r = DISPLAY(v, extras?.language) || LANGUAGES[v] || v + if (extras?.titlecase) r = toTitleCase(r) + return r +} + +export function i18ify_settings(settings) { + settings.forEach((s)=>{ + if (s.name) s.name = i18n(s.name) + if (s.tooltip) s.tooltip = i18n(s.tooltip) + if (s.options) s.options.forEach((o) => {o.text = i18n(o.text)}) + }) + return settings +} + +const toTitleCase = (phrase) => { + return phrase + .toLowerCase() + .split(' ') + .map(word => word.charAt(0).toUpperCase() + word.slice(1)) + .join(' '); +}; diff --git a/cg-use-everywhere/js/recursive_callbacks.js b/cg-use-everywhere/js/recursive_callbacks.js new file mode 100644 index 0000000000000000000000000000000000000000..56ad15fd9297304379d3e8fe9ac93d3d44ccde35 --- /dev/null +++ b/cg-use-everywhere/js/recursive_callbacks.js @@ -0,0 +1,64 @@ +import { app } from "../../scripts/app.js"; + +class RecursiveCallbacks { + constructor() { + this.event_to_node_callbacklist = {} + this.event_to_graph_callbacklist = {} + } + + /* + Register a callback for a named event. + */ + register_allnode_callback(event, call, first) { + if (!this.event_to_node_callbacklist[event]) this.event_to_node_callbacklist[event] = [] + if (first) this.event_to_node_callbacklist[event].unshift(call) + else this.event_to_node_callbacklist[event].push(call) + } + register_allgraph_callback(event, call, first) { + if (!this.event_to_graph_callbacklist[event]) this.event_to_graph_callbacklist[event] = [] + if (first) this.event_to_graph_callbacklist[event].push(call) + else this.event_to_graph_callbacklist[event].push(call) + } + + + + /* + For every callback registered to this event, + call allnode callback once for each node, with the node as argument + call allgraph callback once for each node, with the graph as argument + */ + dispatch(event) { + if (this.event_to_node_callbacklist[event]) { + this.event_to_node_callbacklist[event].forEach((callback) => { + _node_dispatch(callback, app.graph) + }); + } + if (this.event_to_graph_callbacklist[event]) { + this.event_to_graph_callbacklist[event].forEach((callback) => { + _graph_dispatch(callback, app.graph) + }); + } + } +} + +function _node_dispatch(callback, graph) { + graph.nodes.forEach((node) => { + callback(node) + if (node.subgraph) { _node_dispatch(callback, node.subgraph) } + }) +} + +function _graph_dispatch(callback, graph) { + callback(graph) + graph.nodes.filter((node)=>(node.subgraph)).forEach((node) => { _graph_dispatch(callback, node.subgraph) }) +} + +export const ue_callbacks = new RecursiveCallbacks() + +export function for_all_graphs(callback) { + _graph_dispatch(callback, app.graph) +} + +export function for_all_nodes(callback) { + _node_dispatch(callback, app.graph) +} \ No newline at end of file diff --git a/cg-use-everywhere/js/shared.js b/cg-use-everywhere/js/shared.js new file mode 100644 index 0000000000000000000000000000000000000000..b236ef337614b48e6bab25e16fe0cc9076f0890e --- /dev/null +++ b/cg-use-everywhere/js/shared.js @@ -0,0 +1,36 @@ +export const VERSION = "7.8" + +class Shared { + constructor() { + this.graph_being_configured = 0 + this.in_queuePrompt = 0 + this.in_graphToPrompt = 0 + this.in_midst_of_change = 0 + this.graph_currently_modified = 0 + this.graphAnalyser = undefined + this.linkRenderController = undefined + this.report_keys = [ 'graph_being_configured', 'in_queuePrompt', 'in_graphToPrompt', 'in_midst_of_change', 'graph_currently_modified' ] + } +} + +class Deferred { + constructor() { + this.action_list = [] + setInterval( this.execute.bind(this), 200 ) + } + push(x) { this.action_list.push(x) } // add action of the form: { fn:function, args:array } + execute() { + if (shared.in_midst_of_change) return; + if (shared.graph_being_configured) return; + while (this.action_list.length>0) { + const action = this.action_list.pop() + try { action?.fn(...action?.args) } + catch (e) { Logger.log_error(e) } + } + } +} + +export const deferred_actions = new Deferred() + +export const shared = new Shared() + diff --git a/cg-use-everywhere/js/tooltip_window.js b/cg-use-everywhere/js/tooltip_window.js new file mode 100644 index 0000000000000000000000000000000000000000..b44428c3e18ba017e8f2b82c0a6a2b100a4699de --- /dev/null +++ b/cg-use-everywhere/js/tooltip_window.js @@ -0,0 +1,55 @@ + +import { any_restrictions, describe_restrictions } from "./ue_properties.js"; +import { app } from "../../scripts/app.js"; +import { create } from "./use_everywhere_utilities.js"; +import { edit_window } from "./floating_window.js"; +import { settingsCache } from "./use_everywhere_cache.js"; + +const HOVERTIME = 500 +var hover_node_id = null +var mouse_pos = [0,0] + +const ue_tooltip_element = create('span', 'ue_tooltip', document.body, {id:'ue_tooltip'}) + +function show_tooltip() { + ue_tooltip_element.style.display = "block" + ue_tooltip_element.style.left = `${mouse_pos[0]+10}px` + ue_tooltip_element.style.top = `${mouse_pos[1]+5}px` + ue_tooltip_element.innerHTML = "" + ue_tooltip_element.appendChild(describe_restrictions(app.canvas.node_over)) + ue_tooltip_element.showing = true +} + +function show_on_hover() { + if (!tooltipable()) return + + if (mouse_pos[0]==app.canvas.mouse[0] && mouse_pos[1]==app.canvas.mouse[1]) { + show_tooltip() + } else { + maybe_show_tooltip() + } +} + +function hide_tooltip() { + ue_tooltip_element.style.display = "none" + ue_tooltip_element.showing = false +} + +function tooltipable() { + if ( + (!app.canvas?.node_over) || + ( edit_window.showing) || + (!settingsCache.getSettingValue('Use Everywhere.Graphics.tooltips')) || + (!any_restrictions(app.canvas.node_over)) + ) return false + + return true +} + +export function maybe_show_tooltip() { + if (!tooltipable()) return hide_tooltip() + + mouse_pos = [...app.canvas.mouse] + hover_node_id = app.canvas.node_over.id + setTimeout(show_on_hover, HOVERTIME) +} \ No newline at end of file diff --git a/cg-use-everywhere/js/ue.css b/cg-use-everywhere/js/ue.css new file mode 100644 index 0000000000000000000000000000000000000000..574e16d0b95cb108773a8b9330b3da0e8fa337d8 --- /dev/null +++ b/cg-use-everywhere/js/ue.css @@ -0,0 +1,102 @@ +@layer ue { + #ue_tooltip { + z-index : 9000; + border: thin solid gray; + color:black; + position: absolute; + padding: 4px; + } + #ue_tooltip table { + border-collapse: collapse; + + } + #ue_tooltip tr:nth-child(odd) { + background-color: rgba(234, 255, 234, 0.67); + } + #ue_tooltip tr:nth-child(even) { + background-color: rgba(255, 234, 234, 0.67); + } + #ue_tooltip th { + text-align: right; + } + + .ue_editor { + z-index : 9000; + border: thin solid gray; + color:white; + position: absolute; + padding: 0px; + display: flex; + flex-direction: column; + align-items: center; + background-color: rgb(45 24 24 / 80%); + } + + .ue_properties_table { + display: flex; + flex-direction: column; + } + + .ue_editor_header { + width: 100%; + text-align: center; + background-color: rgb(45 24 24 / 80%); + background-size: 100% 14px; + background-image: repeating-linear-gradient(0deg, #636363, black 1px, rgb(45 24 24 / 80%) 1px, rgb(45 24 24 / 80%) 2px); + padding-top: 4px; + border-bottom: thin dashed #ddd; + padding-bottom: 2px; + margin-bottom: 2px; + } + + .ue_properties_row { + display: flex; + flex-direction: row; + } + + .break_below { + border-bottom: thin dashed #ddd; + padding-bottom: 2px; + } + + span.ue_properties_title { + text-align: right; + flex-grow: 1; + padding-right: 4px; + } + + .ue_properties_title::after { + content: ':'; + } + + .ue_properties_cell { + flex-grow: 0; + width: 250px + } + + + .ue_editor_footer { + margin: 8px; + border: thin solid white; + padding: 2px 30px; + background-color: rgba(0, 0, 0, 0.75); + } + + .regex_input_container { + display: flex; + width: 100%; + justify-content: space-between; + input { + flex-grow: 1; + } + span { + padding: 4px 8px 0px 0px; + font-size: 60%; + } + .checkbox { + flex-grow: 0; + margin-left: 0px; + } + } + +} diff --git a/cg-use-everywhere/js/ue_properties.js b/cg-use-everywhere/js/ue_properties.js new file mode 100644 index 0000000000000000000000000000000000000000..8d00f6ba021fcd807f2a1f9055e15629001a2459 --- /dev/null +++ b/cg-use-everywhere/js/ue_properties.js @@ -0,0 +1,158 @@ +import { version_at_least, create, is_UEnode, find_duplicate_broadcasted_types } from "./use_everywhere_utilities.js" +import { i18n, i18n_functional, GROUP_RESTRICTION_OPTIONS, COLOR_RESTRICTION_OPTIONS } from "./i18n.js"; +import { shared } from "./shared.js"; +import { fix_inputs } from "./connections.js"; +import { VERSION } from "./shared.js"; + +const ALL_REGEXES = ['title', 'input', 'prompt', 'negative', 'group'] + +function any_regex_restrictions(node) { + if (!node.properties.ue_properties) return false + var restricted = false + ALL_REGEXES.forEach((r)=>{ + const reg = node.properties.ue_properties[`${r}_regex`] + restricted = restricted || (reg && reg.length>0) + }) + return restricted +} + +export function any_restrictions(node) { + return ( + node.properties.ue_properties?.group_restricted || + node.properties.ue_properties?.color_restricted || + node.properties.ue_properties?.priority || + any_regex_restrictions(node) + ) +} + +export function describe_restrictions(node) { + const statements = [] + if (node.properties.ue_properties) { + ALL_REGEXES.forEach((r)=>{ + var reg = node.properties.ue_properties[`${r}_regex`] + if (reg && reg.length>0) { + const condition = i18n((node.properties.ue_properties[`${r}_regex_invert`]) ? i18n("not match"): i18n("match")) + statements.push([`${i18n(r)} regex`, `${condition} ${reg}`]) + } + }) + if (node.properties.ue_properties.group_restricted) statements.push([i18n('group'),i18n(GROUP_RESTRICTION_OPTIONS[node.properties.ue_properties.group_restricted])]) + if (node.properties.ue_properties.color_restricted) statements.push([i18n('color'),i18n(COLOR_RESTRICTION_OPTIONS[node.properties.ue_properties.color_restricted])]) + } + if (node.properties.ue_properties.priority !== undefined) statements.push([i18n('priority'), node.properties.ue_properties.priority]) + const table = create('table') + statements.forEach((s)=>{ + const row = create('tr', null, table) + create('th', null, row, {innerText:`${i18n(s[0], {titlecase:true})}:`}) + create('td', null, row, {innerText:s[1]}) + }) + return table +} + +export function default_priority(node) { + var p = 10 + if (node.type === "Seed Everywhere" || node.type === "Prompts Everywhere") p += 10 + if (any_regex_restrictions(node) || find_duplicate_broadcasted_types(node).size) p += 20 + if (node.properties.ue_properties.group_restricted > 0) p += 3 + if (node.properties.ue_properties.color_restricted > 0) p += 6 + return p +} + +const DEFAULT_PROPERTIES = { + version : VERSION, + group_restricted : 0, + color_restricted : 0, + widget_ue_connectable : {}, + input_ue_unconnectable : {}, + title_regex : null, + input_regex : null, + group_regex : null, + title_regex_invert : false, + input_regex_invert : false, + group_regex_invert : false, + priority : undefined, + repeated_type_rule : 0, + apply_to_unrepeated : 0, + string_to_combo : 0, + send_to_any : 0 + } + +/* +Called whenever any node is created. + +If the graph is still being configured, then that means the node is being created as part of a load. +In that case the properties need to be set later, in setup_ue_properties_onload +*/ +export function setup_ue_properties_oncreate(node) { + if (shared.graph_being_configured) return + if (!node.properties) node.properties = {} + node.properties.ue_properties = {...DEFAULT_PROPERTIES} + convert_node_types(node) +} + +/* +Convert node properties when loaded. +*/ +export function setup_ue_properties_onload(node) { + if (!node.properties?.ue_properties) node.properties.ue_properties = {} + if ( !version_at_least(node.properties?.ue_properties?.version, "7.0") ) { + if (is_UEnode(node)) { + // convert a pre 7.0 UE node + node.properties.ue_properties = { + version : VERSION, + group_restricted : node.properties.group_restricted, + color_restricted : node.properties.color_restricted, + widget_ue_connectable : node.properties.widget_ue_connectable, + input_ue_unconnectable: {}, + title_regex : node.widgets_values?.[0], + input_regex : node.widgets_values?.[1], + group_regex : node.widgets_values?.[2], + priority : undefined, + } + delete node.properties.group_restricted + delete node.properties.color_restricted + delete node.properties.widget_ue_connectable + } else { + node.properties.ue_properties.version = VERSION + node.properties.ue_properties.widget_ue_connectable = node.properties.ue_properties.widget_ue_connectable || + node.properties.widget_ue_connectable || + {} + node.properties.ue_properties.input_ue_unconnectable = {} + if (node.properties.widget_ue_connectable) delete node.properties.widget_ue_connectable + } + } + convert_node_types(node) + +} + +function convert_node_types(node) { + if (!is_UEnode(node)) return + + if (node.type=="Anything Everywhere?") { + node.widgets.forEach((w)=>{w.hidden=true}) + if (node.title=="Anything Everywhere?") node.title = "Anything Everywhere" + node.type = "Anything Everywhere" + } else if (node.type=="Anything Everywhere3") { + if (node.title=="Anything Everywhere3") node.title = "Anything Everywhere" + node.type = "Anything Everywhere" + } else if (node.type=="Seed Everywhere") { + if (node.title=="Anything Everywhere3") node.title = "PrimitiveInt" + node.type = "PrimitiveInt" + node.properties.ue_convert = true + node.properties.ue_properties.fixed_inputs = true + node.properties.ue_properties.seed_inputs = true + node.properties.ue_properties.input_regex = node.properties.ue_properties.input_regex || i18n_functional('seed_input_regex') + } else if (node.type=="Prompts Everywhere") { + if (node.title=="Prompts Everywhere") node.title = "Anything Everywhere" + node.properties.ue_properties.fixed_inputs = false + node.inputs[0].label = i18n_functional('positive') + node.inputs[1].label = i18n_functional('negative') + node.properties.ue_properties['keep_inputs'] = [0,1] + } + + ALL_REGEXES.forEach((r)=>{ + const rname = `${r}_regex` + if (node.properties.ue_properties[rname]==".*") node.properties.ue_properties[rname] = undefined + }) + + fix_inputs(node, "convert_node_types") +} diff --git a/cg-use-everywhere/js/ue_properties_editor.js b/cg-use-everywhere/js/ue_properties_editor.js new file mode 100644 index 0000000000000000000000000000000000000000..9f5b3da2c7abea5dbd7014bdd031dd6ffd9917d8 --- /dev/null +++ b/cg-use-everywhere/js/ue_properties_editor.js @@ -0,0 +1,147 @@ +import { i18n, i18n_functional, GROUP_RESTRICTION_OPTIONS, COLOR_RESTRICTION_OPTIONS, REPEATED_TYPE_OPTIONS } from "./i18n.js"; +import { app } from "../../scripts/app.js"; +import { default_priority } from "./ue_properties.js"; +import { edit_window } from "./floating_window.js"; +import { shared } from "./shared.js"; +import { Logger } from "./use_everywhere_utilities.js"; + +const REGEXES = ['title', 'input', 'group'] +const P_REGEXES = ['prompt', 'negative'] + +function create_element(tag, parent, options={}) { + const elem = document.createElement(tag) + if (parent) parent.appendChild(elem) + Object.assign(elem, options) + return elem +} + +export function edit_restrictions(a,b,c,d, node) { // a,b,c,d parameters are ignored - called from menu system + edit_window.set_body(create_editor_html(node)) + edit_window.set_title(`Restrictions for node #${node.id}`) + edit_window.maybe_move_to(app.canvas.mouse[0]+10, app.canvas.mouse[1]+10) + edit_window.show() +} + +function add_row(table, header) { + const row = document.createElement('div') + row.className = 'ue_properties_row' + table.appendChild(row) + const header_elem = document.createElement('span') + header_elem.className = 'ue_properties_title' + header_elem.innerText = header + row.appendChild(header_elem) + return row +} + +function add_cell(row, cell) { + const td = document.createElement('span') + td.className = 'ue_properties_cell' + row.appendChild(td) + td.appendChild(cell) +} + +function changed(node, property, value) { + node.properties.ue_properties[property] = value + + if (!node.properties.ue_properties.priority) { + document.getElementById('priority_value').value = `${default_priority(node)}` + } + + const elem = document.getElementById(`${property}_value`) + if (elem) elem.style.opacity = (value) ? "1" : "0.5" + + shared.linkRenderController.mark_link_list_outdated() + app.canvas.setDirty(true,true) +} + +function create_editor_html(node) { + const table = document.createElement('div') + table.className = 'ue_properties_table' + + for (var i=0; i<=2; i++) { + const name = REGEXES[i] + const row = add_row(table, `${i18n(name)} regex`) + + const contents = create_element('span', null, {'className':'regex_input_container'}) + + const checkbox_props = { + type:'checkbox', + id:`${name}_regex_invert`, + checked: (node.properties.ue_properties[`${name}_regex_invert`]) ? true : undefined, + className: 'checkbox' + } + create_element('input', contents, checkbox_props). + addEventListener('input', (e)=>{ changed(node, `${name}_regex_invert`, e.target.checked); } ) + + create_element('span', contents, {innerText:i18n('Invert'), className:'regex_checkbox_label'}) + + create_element('input', contents, {type:'text', value:node.properties.ue_properties[`${name}_regex`] || ''}). + addEventListener('input', (e)=>{ changed(node, `${name}_regex`, e.target.value)}) + + if (i==2) { row.classList.add('break_below') } + + add_cell(row,contents) + } + + const gr_row = add_row(table, i18n("Group")) + const gr_select = document.createElement('select') + add_cell(gr_row,gr_select) + add_select_options(node, gr_select, GROUP_RESTRICTION_OPTIONS, `group_restricted`) + + const col_row = add_row(table, i18n("Color")) + const col_select = document.createElement('select') + add_cell(col_row,col_select) + add_select_options(node, col_select, COLOR_RESTRICTION_OPTIONS, `color_restricted` ) + col_row.classList.add('break_below') + + const repeated_type_row = add_row(table, i18n("Repeated Types")) + const repeated_type_select = document.createElement('select') + add_cell(repeated_type_row,repeated_type_select) + add_select_options(node, repeated_type_select, REPEATED_TYPE_OPTIONS, `repeated_type_rule`) + + const apply_to_unrepeated_row = add_row(table, i18n("Apply to Unrepeated")) + const apply_to_unrepeated_select = document.createElement('select') + add_cell(apply_to_unrepeated_row, apply_to_unrepeated_select) + add_select_options(node, apply_to_unrepeated_select, ["no", "yes"], `apply_to_unrepeated`) + apply_to_unrepeated_row.classList.add('break_below') + + if (node.inputs.find((i)=>(i.type=="STRING"))) { + const send_to_combos_row = add_row(table, i18n("String to Combos")) + const send_to_combos_select = document.createElement('select') + add_cell(send_to_combos_row, send_to_combos_select) + add_select_options(node, send_to_combos_select, ["no", "yes"], `string_to_combo`) + send_to_combos_row.classList.add('break_below') + } + + const send_to_any_row = add_row(table, i18n("Send to Any")) + const send_to_any_select = document.createElement('select') + add_cell(send_to_any_row, send_to_any_select) + add_select_options(node, send_to_any_select, ["no", "yes"], `send_to_any`) + send_to_any_row.classList.add('break_below') + + const priority_row = add_row(table, i18n("Priority")) + const priority_edit = document.createElement("input") + priority_edit.value = `${node.properties.ue_properties.priority || default_priority(node)}` + priority_edit.addEventListener('input', ()=>{ + const p = parseInt(priority_edit.value) + if (p) changed(node, `priority`, p) + if (priority_edit.value=='') changed(node, `priority`, undefined) + }) + priority_edit.id = 'priority_value' + if (!node.properties.ue_properties.priority) priority_edit.style.opacity = 0.5 + add_cell(priority_row,priority_edit) + priority_row.classList.add('break_below') + + return table +} + +function add_select_options(node, select, OPTIONS, property) { + OPTIONS.forEach((txt, i)=>{ + const option = document.createElement('option') + option.value = `${i}` + option.innerText = txt + select.appendChild(option) + }) + select.value = `${node.properties.ue_properties[property] || 0}` + select.addEventListener('input', ()=>{ changed(node, property, parseInt(select.value))}) +} \ No newline at end of file diff --git a/cg-use-everywhere/js/use_everywhere.js b/cg-use-everywhere/js/use_everywhere.js new file mode 100644 index 0000000000000000000000000000000000000000..56ccaab897345508a36e75cfd2d79ebd9228509c --- /dev/null +++ b/cg-use-everywhere/js/use_everywhere.js @@ -0,0 +1,346 @@ +import { app } from "../../scripts/app.js"; +import { api } from "../../scripts/api.js"; + +import { shared, deferred_actions } from "./shared.js"; + +import { is_UEnode, inject, Logger, graphConverter, create, node_can_broadcast } from "./use_everywhere_utilities.js"; +import { title_bar_additions, LinkRenderController } from "./use_everywhere_ui.js"; +import { GraphAnalyser } from "./use_everywhere_graph_analysis.js"; +import { canvas_menu_settings, SETTINGS, add_extra_menu_items } from "./use_everywhere_settings.js"; +import { settingsCache } from "./use_everywhere_cache.js"; +import { convert_to_links } from "./use_everywhere_apply.js"; +import { visible_graph, fix_new_subgraph_node } from "./use_everywhere_subgraph_utils.js"; +import { setup_ue_properties_oncreate, setup_ue_properties_onload } from "./ue_properties.js"; +import { edit_restrictions } from "./ue_properties_editor.js"; +import { language_changed } from "./i18n.js"; +import { input_changed, fix_inputs } from "./connections.js"; +import { comboclone_on_connection, is_combo_clone } from "./combo_clone.js"; +import { ue_callbacks } from "./recursive_callbacks.js"; + +/* +All nodes need the onDrawTitleBar method so they can show if they are broadcasting UE data. +*/ +function add_methods_to_all_nodes(node) { + if (node.ue_methods_added) return Logger.log_problem(`Node ${node.id} already has UE methods added`); + + try { + add_extra_menu_items(node, inject_outdating_into_object_method) // right click menu additions + + const original_onDrawForeground = node.onDrawForeground; + node.onDrawForeground = function(ctx) { + original_onDrawForeground?.apply(this, arguments); + title_bar_additions(this, ctx, this.title_height || LiteGraph.NODE_TITLE_HEIGHT) + } + + const original_onMouseEnter = node.onMouseEnter; + node.onMouseEnter = function(e) { + original_onMouseEnter?.apply(this, arguments) + shared.linkRenderController.node_over_changed() + } + + const original_onMouseLeave = node.onMouseLeave; + node.onMouseLeave = function(e) { + original_onMouseLeave?.apply(this, arguments) + shared.linkRenderController.node_over_changed() + } + + node.ue_methods_added = true; + } catch (e) { + Logger.log_error(e); + } + +} + +/* +Inject a call to linkRenderController.mark_list_link_outdated into a method with name methodname on all objects in the array +If object is undefined, do nothing. +The injection is added at the end of the existing method (if the method didn't exist, it is created). +*/ +function inject_outdating_into_objects(array, methodname, tracetext) { + if (array) { + array.forEach((object) => { inject_outdating_into_object_method(object, methodname, tracetext); }) + } +} +function inject_outdating_into_object_method(object, methodname, tracetext) { + if (object) inject(object, methodname, tracetext, shared.linkRenderController.mark_link_list_outdated, shared.linkRenderController); +} + +app.registerExtension({ + name: "cg.customnodes.use_everywhere", + settings: SETTINGS, + + async beforeRegisterNodeDef(nodeType, nodeData, app) { + /* + When a node is connected or unconnected, the link list is dirty. + If it is a UE node, we need to update it as well + */ + const onConnectionsChange = nodeType.prototype.onConnectionsChange; + nodeType.prototype.onConnectionsChange = function (side,slot,connect,link_info,output) { + if (is_combo_clone(this) && !shared.in_queuePrompt) comboclone_on_connection(this, link_info, connect) + if (is_UEnode(this) && side==1) { // side 1 is input + input_changed(this, slot, connect, link_info) + + if (!shared.graph_being_configured) { + // do the fix at the end of graph change + deferred_actions.push( { fn:fix_inputs, args:[this,"deferred onConnectionsChange",]} ) + } + } + shared.linkRenderController?.mark_link_list_outdated(); + onConnectionsChange?.apply(this, arguments); + }; + + /* Combo Clone can connect to COMBO or to UE nodes */ + if (nodeData.name=="Combo Clone") { + const onConnectOutput = nodeType.prototype.onConnectOutput + nodeType.prototype.onConnectOutput = function(outputIndex, type, input, inputNode, inputIndex) { + if (!(type=="COMBO" || is_UEnode(inputNode))) return false; + return onConnectOutput?.apply(this,arguments) + } + } + + }, + + async nodeCreated(node) { // the node isn't part of the graph yet, so can't do anything involving id or links. + add_methods_to_all_nodes(node) + + if (shared.graph_being_configured) return + + if (is_UEnode(node)) { + setup_ue_properties_oncreate(node) + } else if (!node.properties.ue_properties) { + node.properties.ue_properties = { + widget_ue_connectable : {}, + input_ue_unconnectable : {} + } + } + }, + + // When a graph node is loaded convert it if needed + loadedGraphNode(node) { + graphConverter.convert_if_pre_116(node); + setup_ue_properties_onload(node) + }, + + async setup() { + + create('link', null, document.getElementsByTagName('HEAD')[0], + {'rel':'stylesheet', 'type':'text/css', 'href': new URL("./ue.css", import.meta.url).href } ) + + api.addEventListener("status", ({detail}) => { + if (shared.linkRenderController) shared.linkRenderController.note_queue_size(detail ? detail.exec_info.queue_remaining : 0) + }); + + /* if we are on version 1.16 or later, stash input data to convert nodes when they are loaded */ + //if (graphConverter.running_116_plus()) { + const original_loadGraphData = app.loadGraphData; + app.loadGraphData = async function (data) { + try { + graphConverter.store_node_input_map(data); + } catch (e) { Logger.log_error(e); } + const cvw_was = settingsCache.getSettingValue("Comfy.Validation.Workflows") + if (settingsCache.getSettingValue("Use Everywhere.Options.block_graph_validation")) { + app.ui.settings.setSettingValue("Comfy.Validation.Workflows", false); + } + await original_loadGraphData.apply(this, arguments); + app.ui.settings.setSettingValue("Comfy.Validation.Workflows", cvw_was); + //return v; + } + //} + + /* + When we draw a node, render the virtual connection points + */ + const original_drawNode = LGraphCanvas.prototype.drawNode; + LGraphCanvas.prototype.drawNode = function(node, ctx) { + try { + shared.linkRenderController.pause('drawFrontCanvas') + const v = original_drawNode.apply(this, arguments); + shared.linkRenderController.highlight_ue_connections(node, ctx); + if (node._last_seen_bg !== node.bgcolor) shared.linkRenderController.mark_link_list_outdated(); + node._last_seen_bg = node.bgcolor + return v + } catch (e) { + Logger.log_error(e) + } finally { + shared.linkRenderController.unpause() + } + } + + /* + Before drawing the canvas, temporarily disable all the ue connected widgets + so they get rendered as greyed out. + */ + const original_drawFrontCanvas = LGraphCanvas.prototype.drawFrontCanvas + LGraphCanvas.prototype.drawFrontCanvas = function() { + try { + shared.linkRenderController.disable_all_connected_widgets() + return original_drawFrontCanvas.apply(this, arguments); + } catch (e) { + Logger.log_error(e) + } finally { + try { + shared.linkRenderController.enable_all_disabled_widgets() + } catch (e) { + Logger.log_error(e) + } + + } + } + + /* + When we draw connections, do the ue ones as well (logic for on/off is in lrc) + */ + const drawConnections = LGraphCanvas.prototype.drawConnections; + LGraphCanvas.prototype.drawConnections = function(ctx) { + drawConnections?.apply(this, arguments); + try { + shared.linkRenderController.render_all_ue_links(ctx); + } catch (e) { + Logger.log_error(e) + } + } + + }, + + init() { + shared.graphAnalyser = new GraphAnalyser(); + shared.linkRenderController = new LinkRenderController(); + + /* + Modifications to the graph: + - track start and end of the graph being changed + - catch convertToSubgraph to try to fix UE links + */ + const original_beforeChange = app.graph.beforeChange + app.graph.beforeChange = function () { + shared.in_midst_of_change += 1 + original_beforeChange?.apply(this, arguments) + } + + const original_afterChange = app.graph.afterChange + app.graph.afterChange = function () { + original_afterChange?.apply(this, arguments) + shared.in_midst_of_change = Math.max(0, shared.in_midst_of_change-1) // afterChange gets called without a beforeChange sometimes + } + + const original_subgraph = app.graph.convertToSubgraph + app.graph.convertToSubgraph = function () { + const ctb_was = shared.graphAnalyser.connect_to_bypassed + shared.graphAnalyser.connect_to_bypassed = true + try { + const cur_list = shared.graphAnalyser.analyse_graph(visible_graph()) + if (!cur_list) Logger.log_problem('convert to subgraph failed to get ues') + const mods = convert_to_links(cur_list, null, visible_graph()); + const r = original_subgraph.apply(this, arguments); + mods.restorer() + fix_new_subgraph_node(r.node) + return r + } finally { + shared.graphAnalyser.connect_to_bypassed = ctb_was + } + } + + /* + Modifications to app + - intercept graphToPrompt and queuePrompt so we know where we are + - provide API + */ + const original_graphToPrompt = app.graphToPrompt; + app.graphToPrompt = async function () { + try { + shared.in_graphToPrompt += 1 + if (shared.in_queuePrompt || app.ui.settings.getSettingValue("Use Everywhere.Options.always_modify_graph")) { + //Logger.log_shared('In graphToPrompt (going to modify graph):') + return await shared.graphAnalyser.call_function_with_modified_graph( original_graphToPrompt, arguments ) + } else { + //Logger.log_shared('In graphToPrompt (not going to modify graph):') + return await original_graphToPrompt.apply(this, arguments) + } + } finally { + shared.in_graphToPrompt -= 1 + } + } + + const original_queuePrompt = app.queuePrompt; + app.queuePrompt = async function () { + try { + shared.in_queuePrompt += 1; + return await original_queuePrompt.apply(app, arguments); + } finally { + shared.in_queuePrompt -= 1; + } + } + + app.ue_modified_prompt = async function () { // API function + return await shared.graphAnalyser.call_function_with_modified_graph( original_graphToPrompt ) + } + + /* + Find the Export as API function and wrap it + */ + const export_workflow_api = app.extensionManager.command.commands.find((c)=>(c.id=='Comfy.ExportWorkflowAPI')) + if (export_workflow_api) { + const original = export_workflow_api.function + export_workflow_api.function = async function () { + await shared.graphAnalyser.call_function_with_modified_graph( ()=>{ original.apply(this, arguments)} ) + } + } + + + /* + Modifications to the canvas + - listen for set-graph to mark the link list as out of date when we open or close a subgraph + - catch node-double-click to open the restrictions dialog + - onDrawForeground to highlight subgraph output links + */ + + app.canvas.canvas.addEventListener('litegraph:set-graph', ()=>{ + shared.linkRenderController.mark_link_list_outdated() + setTimeout(()=>{app.canvas.setDirty(true,true)},200) + }) + + app.canvas.canvas.addEventListener('litegraph:canvas', (e)=>{ + if (e?.detail?.subType=='node-double-click') { + const node = e.detail.node + if (node_can_broadcast(node)) { + if (app.ui.settings.getSettingValue('Comfy.Node.DoubleClickTitleToEdit') && e.detail.originalEvent.canvasY { + const input_node_id = st.node.id; + const input_node = get_real_node(input_node_id, ue.graph); + const input_index = st.input_index; + if (input_node.inputs?.[input_index].link) { // why would this be happening? + const llink = ue.graph.links[input_node.inputs[input_index].link] + if (llink) removed_links.push( {...llink} ) + } + var new_link + if (input_node.io_node) { + new_link = input_node.io_node.slots[input_index].connect(output_node.outputs[output_index], output_node); + } else { + new_link = output_node.connect(output_index, input_node, input_index); + } + + if (!new_link) + console.error("Failed to connect nodes: " + + `${output_node_id}[${output_index}] -> ` + + `${input_node_id}[${input_index}].`); + else { // Memorize the links we are adding to remove them later + if (added_links) { + new_link.control_node = ue.controller; + added_links.push(new_link); + } + Logger.log_info(` -> ${display_name(st.node)}, ${st.input.name} ` + + `(${st.node.id}.${st.input_index}) (ID: ${new_link.id})`); + } + }); +} + +export function remove_comfyDynamic_autogrow(graph) { + graph.nodes.filter((node)=>(node.comfyDynamic?.autogrow)).forEach((node)=>{ + node.__ue_removed_comfyDynamic_autogrow = node.comfyDynamic.autogrow + node.comfyDynamic.autogrow = {} + }) + const restorer = function() { + graph.nodes.filter((node)=>(node.__ue_removed_comfyDynamic_autogrow)).forEach((node)=>{ + node.comfyDynamic.autogrow = node.__ue_removed_comfyDynamic_autogrow + node.__ue_removed_comfyDynamic_autogrow = undefined + }) + } + return { restorer:restorer } +} + +export function convert_to_links(ues, control_node, graph) { + if (control_node) { + if (!graph) graph = control_node.graph + return _convert_graph_to_links(graph, ues, control_node.id ); + } else { + if (!graph) graph = app.graph; + return _convert_graph_to_links(graph, ues, undefined); + } +} + +function _convert_graph_to_links(graph, ues, control_node_id) { + if (!ues?.ues) { + Logger.log_detail('no ues in _convert_graph_to_links') + return {restorer:function(){}, added_links:[]} + } + const added_links = [] + const removed_links = [] + ues.ues.forEach((ue)=> { + if (control_node_id==undefined || ue.controller.id == control_node_id) _convert_to_links(ue, added_links, removed_links); + }); + + const restorer = function() { + const links_within_graph_ids = new Set() + const links_within_subgraph_ids = new Set() + const links_into_subgraph_ids = new Set() + const links_out_of_subgraph = new Set() + const problem_links = new Set() + + const new_subgraph_node = graph.getNodeById(graph.last_node_id); + const new_subgraph = new_subgraph_node?.subgraph; + + added_links.forEach(added_link => { + var id = added_link.id + try { + if (graph.links[id]) { + links_within_graph_ids.add(id); + } else { + const link_to_subgraph_node = new_subgraph_node?.inputs.find(input => input.linkIds.includes(id))?.link + if (link_to_subgraph_node) { + links_into_subgraph_ids.add(link_to_subgraph_node) + } else { + if (new_subgraph.links[id]) { + if (new_subgraph.links[id].target_id==-20) { + links_out_of_subgraph.add(added_link) + } else { + links_within_subgraph_ids.add(id) + } + } else problem_links.add(added_link) + } + } + } catch (e) { + problem_links.add(added_link) + Logger.log_error(e); + } + }); + + links_out_of_subgraph.forEach((llink)=>{ + const control_node_id = llink.control_node?.id + const control_node_in_graph = graph.getNodeById(control_node_id) + if (control_node_in_graph) { + // the control node is outside, so we should disconnect anything else that is connected to the same output of the subgraph node + new_subgraph_node.outputs[new_subgraph.links[llink.id].target_slot].links.forEach((link_id)=>{ + if (graph.links[link_id].target_id==control_node_id) { + // leave the link to the UE node + } else { + // remove others + links_within_graph_ids.add(link_id) + } + }) + } else { + // control node is inside, leave the link, since we can't UE connect to the output panel + } + }) + + links_within_graph_ids.forEach((lid)=>{graph.removeLink(lid)}) + links_into_subgraph_ids.forEach((lid)=>{graph.removeLink(lid)}) + links_within_subgraph_ids.forEach((lid)=>{new_subgraph.removeLink(lid)}) + + if (problem_links.size>0) { + Logger.log_problem("Failed to work out how to remove some temporary links:", problem_links) + } + + removed_links.forEach(llink => { + graph.getNodeById(llink.origin_id).connect(llink.origin_slot, graph.getNodeById(llink.target_id), llink.target_slot) + }) + }; + + return {restorer:restorer, added_links:added_links} +} diff --git a/cg-use-everywhere/js/use_everywhere_cache.js b/cg-use-everywhere/js/use_everywhere_cache.js new file mode 100644 index 0000000000000000000000000000000000000000..425eaa3c1465ade852d9b7cc1129f4ffe2bf8be4 --- /dev/null +++ b/cg-use-everywhere/js/use_everywhere_cache.js @@ -0,0 +1,25 @@ +import { app } from "../../scripts/app.js"; + +class LocalSettingsCache { + constructor() { + this.local_settings = {} + this.callbacks = {} + } + getSettingValue(id) { + if (this.local_settings[id]===undefined) this.local_settings[id] = app.ui.settings.getSettingValue(id) + return this.local_settings[id] + } + onSettingChange(new_value, old_value) { + const id = this.id // this references the setting that has been changed + settingsCache.local_settings[id] = new_value + if (settingsCache.callbacks[id]) { + settingsCache.callbacks[id].forEach((c) => {c(new_value, old_value, this)}) + } + } + addCallback(id, callback) { + if (this.callbacks[id]===undefined) this.callbacks[id] = [] + this.callbacks[id].push(callback) + } +} + +export const settingsCache = new LocalSettingsCache() \ No newline at end of file diff --git a/cg-use-everywhere/js/use_everywhere_classes.js b/cg-use-everywhere/js/use_everywhere_classes.js new file mode 100644 index 0000000000000000000000000000000000000000..654d59fa75460b64fab5c7ab09877acb2840289d --- /dev/null +++ b/cg-use-everywhere/js/use_everywhere_classes.js @@ -0,0 +1,387 @@ +import { i18n_functional } from "./i18n.js"; +import { default_priority } from "./ue_properties.js"; +import { connection_from_output_as_input, visible_graph } from "./use_everywhere_subgraph_utils.js"; +import { nodes_in_my_group, nodes_not_in_my_group, nodes_my_color, nodes_not_my_color, nodes_in_groups_matching } from "./use_everywhere_ui.js"; +import { Logger, node_is_live, get_real_node, get_connection, find_duplicate_broadcasted_types, is_able_to_broadcast } from "./use_everywhere_utilities.js"; + + +export function display_name(node) { + if (node?.title) return node.title; + if (node?.type) return node.type; + if (node?.properties?.['Node name for S&R']) return node.properties['Node name for S&R']; + if (node?.id==-20) return "subgraph output node"; + if (node?.id==-10) return "subgraph input node"; + return "un-nameable node"; +} + +export function input_name(input) { + return input?.label || input?.localized_name || input?.name || ""; +} + +function regex_for(node, k) { + try { + const w0 = node.properties.ue_properties[`${k}_regex`] + return (w0 && w0!='.*') ? {regex:new RegExp(w0), invert:!!node.properties.ue_properties[`${k}_regex_invert`]} : null; + } catch (e) { + return null + } +} + + +const P_REGEXES = ['prompt', 'negative'] +const PROMPT_REGEXES = [new RegExp(i18n_functional('prompt_regex')), new RegExp(i18n_functional('negative_regex'))] + +/* +The UseEverywhere object represents a single 'broadcast'. It generally contains + controller - the UE node that controls the broadcase + control_node_input_index - the input on that node + type - the data type + output - the output that is being rebroadcast as a list (node_id, output_index) + title_regex, input_regex - the UE? matching rules + priority - priorty :) + graph - the graph or subgraph +*/ +class UseEverywhere { + constructor() { + this.sending_to = []; + Object.assign(this, arguments[0]); + if (this.priority === undefined) this.priority = 0; + if (this.graph === undefined) this.graph = visible_graph(); + this.string_to_combo = (this.controller.properties.ue_properties.string_to_combo > 0) + this.send_to_any = (this.controller.properties.ue_properties.send_to_any > 0) + + const from_node = get_real_node(this?.output[0], this.graph); + const to_node = get_real_node(this?.controller.id, this.graph) + try { + if (this.output[0]==-10) { + this.description = `source subgraph input slot ${this?.output[1]} ` + + `-> control "${display_name(to_node)}", ${to_node.inputs[this?.control_node_input_index]?.name} (${this?.controller?.id}.${this?.control_node_input_index}) ` + + `"${this.type}" <- (priority ${this.priority})`; + } + else if (this.control_node_input_index>=0) { + this.description = `source "${display_name(from_node)}", ${from_node.outputs[this?.output[1]]?.name} (${this?.output[0]}.${this?.output[1]}) ` + + `-> control "${display_name(to_node)}", ${to_node.inputs[this?.control_node_input_index]?.name} (${this?.controller.id}.${this?.control_node_input_index}) ` + + `"${this.type}" <- (priority ${this.priority})`; + } else { + this.description = `source "${display_name(from_node)}", ${from_node.outputs[this?.output[1]]?.name} (${this?.output[0]}.${this?.output[1]}) ` + + `"${this.type}" <- (priority ${this.priority})`; + } + } catch (e) { + // for breakpointing + throw e; + } + if (this.title_regex) this.description += ` - node title regex '${this.title_regex.regex?.source} ${(this.title_regex.invert) ? "(inverted)" : ""}'`; + if (this.input_regex) this.description += ` - input name regex '${this.input_regex.regex?.source} ${(this.input_regex.invert) ? "(inverted)" : ""}''`; + } + + sending_differs_from(another_ue) { + if (this.sending_to.length != another_ue.sending_to.length) return true; + for (var i=0; i n.name==input.name); + else if (node.slots) input_index = node.slots.findIndex((n) => n.name==input.name); + if (input_index===undefined) { + Logger.log_problem(`UseEverywhere.note_sending_to could not find input index for node ${node.id} input ${input.name}`); + } else { + this.sending_to.push({node:node, input:input, input_index:input_index}) + } + } + describe_sending(){ + var description = " Linked to:"; + this.sending_to.forEach((st) => description += `\n -> ${display_name(st.node)}, ${st.input.name}`); + if (this.sending_to.length===0) description += ' nothing'; + return description; + } + describe() { + return this.description + "\n" + this.describe_sending(); + } +} + +function validity_errors(params) { + if (!node_is_live(params.controller)) return `UE node ${params.controller.id} is not alive`; + if (params.output[0]!=-10 && !node_is_live(get_real_node(params.output[0], params.graph))) return `upstream node ${params.output[0]} is not alive`; + return ""; +} + +export class Ambiguity { + constructor( data ) { + Object.assign(this, data) + this.matches = [] + } +/* + name : display_name of node + id : node.id + input : input.name + graph : the graph the node is in + matches : [ + { + type : m[i].controller.type, + id : m[i].controller.id, + index : m[i].control_node_input_index + } + ] +*/ + toString() { + var m = `Node ${this.name} (${this.id}) input ${this.input} matches ${this.matches.length} sources:` + this.matches.forEach((match)=>{ + m += `\n - ${match.type} (${match.id}) slot ${match.index}` + }) + return m + } + +} + +export class UseEverywhereList { + constructor() { this.ues = []; this.unmatched_inputs = []; } + + differs_from(another_uel) { + if (!another_uel || !another_uel.ues || !this.ues) return true; + if (this.ues.length != another_uel.ues.length) return true; + for (var i=0; i ( + candidate.matches(node, input) + )); + if (matches.length==0) { + Logger.log_detail(`'${display_name(node)}' optional input '${input.name}' unmatched`) + return undefined; + } + if (matches.length>1) { + matches.sort((a,b) => b.priority-a.priority); + if(matches[0].priority == matches[1].priority) { + const msg = new Ambiguity( { name:display_name(node), id:node.id, input:input.name, graph:(node.graph || node.subgraph) } ) + + matches.filter((m)=>(m.priority == matches[0].priority)).forEach((m)=>{ + var ni = node.inputs?.findIndex((i)=>(i==input)) + if (ni==undefined) ni = node.allSlots?.findIndex((i)=>(i==input)) + msg.matches.push( { + type : m.controller.type, + id : m.controller.id, + index : m.control_node_input_index, + node : node, + node_index : ni + }) + }) + + _ambiguities.push(msg); + return undefined; + } + } + matches[0].note_sending_to(node, input); + Logger.log_detail(`'${display_name(node)}' input '${input.name}' matched to ${matches[0].description}`); + return matches[0]; + } + + all_connected_inputs(for_node) { + const ue_connections = []; + this.ues.forEach((ue) => { + ue.sending_to.forEach((st) => { + if (st.node.id == for_node.id) { + ue_connections.push({ + type : ue.type, + input_index : st.input_index, + control_node : get_real_node(ue.controller.id, ue.graph), + control_node_input_index : ue.control_node_input_index, + sending_to : st.node, + }); + } + }); + }); + return ue_connections; + } + + node_sending_anywhere(node) { + return this.ues.find((ue)=>(ue.controller?.id==node.id && ue.sending_to?.length>0)) ? true : false; + } + + all_sending_slots(for_node) { + const sending_slots = new Set() + this.ues.filter((ue)=>(ue.controller.id == for_node.id) && (ue.sending_to.length>0)).forEach((ue) => { + sending_slots.add(ue.control_node_input_index) + }); + return sending_slots; + } + + all_ue_connections() { + const ue_connections = []; + this.ues.forEach((ue) => { + ue.sending_to.forEach((st) => { + ue_connections.push({ + type : ue.type, + input_index : st.input_index, + control_node : get_real_node(ue.controller.id, ue.graph), + control_node_input_index : ue.control_node_input_index, + sending_to : st.node, + graph: ue.graph, + }); + }); + }); + return ue_connections; + } + + add_ue_from_node(node) { + + if (node.properties.ue_properties.seed_inputs) { + this.add_ue(node, -1, "INT", [node.id.toString(),0], regex_for(node, 'input') ); + } else { + var check_if_able_to_broadcast + var the_possibles + var connection_finder + if (node.properties.ue_convert) { + connection_finder = connection_from_output_as_input + the_possibles = node.outputs + check_if_able_to_broadcast = (node, i) => { + const name = node.outputs[i].name + return is_able_to_broadcast(node, name) + } + } else { + connection_finder = get_connection + the_possibles = node.inputs + check_if_able_to_broadcast = ()=>(true) + } + + const duplicated_broadcasted_types = find_duplicate_broadcasted_types(node) + + the_possibles.forEach((possible, i) => { + const connection = connection_finder(node, i); + if (connection.link && check_if_able_to_broadcast(node,i)) { + const input_regex = undefined + var additional_requirement = null + if (duplicated_broadcasted_types.has(connection.type) || node.properties.ue_properties.apply_to_unrepeated) { + const input_name = possible.label || possible.name + const rule = node.properties.ue_properties?.repeated_type_rule || 0 + if (rule == 0) { // 0 is exact match of input name + additional_requirement = (target_input) => { + const target_name = target_input.label || target_input.name + return (target_name == input_name) + } + } + if (rule == 1) { // 1 is match start of input name + additional_requirement = (target_input) => { + const target_name = target_input.label || target_input.name + const chars = Math.min( input_name.length, target_name.length ) + return (target_name.substring(0, chars) == input_name.substring(0, chars)) + } + } + if (rule == 2) { // 2 is match end of input name + additional_requirement = (target_input) => { + const target_name = target_input.label || target_input.name + const chars = Math.min( input_name.length, target_name.length ) + return (target_name.substring(target_name.length - chars) == input_name.substring(input_name.length - chars)) + } + } + if (rule == 3) { // 3 input is match of target node name + additional_requirement = (_, target_node) => { + const target_name = target_node.title + return (target_name == input_name) + } + } + if (rule == 4) { // 4 input as regex matches input + additional_requirement = (target_input, _) => { + const re = new RegExp(input_name) + const target_name = target_input.label || target_input.name + return re.exec(target_name) + } + } + + } + this.add_ue(node, i, connection.type, [connection.link.origin_id.toString(), connection.link.origin_slot], input_regex, additional_requirement); + } + }) + } + } +} + diff --git a/cg-use-everywhere/js/use_everywhere_graph_analysis.js b/cg-use-everywhere/js/use_everywhere_graph_analysis.js new file mode 100644 index 0000000000000000000000000000000000000000..bd71bde04aca2a84e5abd6ca4241f74096c33b4d --- /dev/null +++ b/cg-use-everywhere/js/use_everywhere_graph_analysis.js @@ -0,0 +1,135 @@ +import { UseEverywhereList } from "./use_everywhere_classes.js"; +import { node_is_live, is_connected, is_UEnode, Logger, Pausable, node_can_broadcast } from "./use_everywhere_utilities.js"; +import { convert_to_links, remove_comfyDynamic_autogrow } from "./use_everywhere_apply.js"; +import { app } from "../../scripts/app.js"; +import { settingsCache } from "./use_everywhere_cache.js"; +import { is_connectable } from "./use_everywhere_settings.js"; +import { for_all_graphs } from "./recursive_callbacks.js"; +import { shared } from "./shared.js"; + +class GraphAnalyser extends Pausable { + + constructor() { + super('GraphAnalyser') + this.original_graphToPrompt = app.graphToPrompt; + this.ambiguities = []; + this.latest_ues = null + this.mods = [] + } + + modify_graph(graph) { + const ues = this.analyse_graph(graph, true) + if (ues===null) { + Logger.log_problem(`modify_graph called but no ues could be obtained for ${graph.id}`) + console.trace() + } + this.mods.push( remove_comfyDynamic_autogrow(graph) ) + const modifications = convert_to_links( ues, null, graph ) + this.mods.push( modifications ); + if (!graph.extra) graph.extra = {} + graph.extra['links_added_by_ue'] = modifications.added_links.map(x=>x.id) + } + + modify_all_graphs() { + for_all_graphs(this.modify_graph.bind(this)) + } + + async call_function_with_modified_graph( func, args ) { + var result + this.mods = [] + try { + this.pause('call_function_with_modified_graph') + Logger.log_info("Modifying graphs") + this.modify_all_graphs() + shared.graph_currently_modified += 1 + result = await (args ? func(...args) : func()) + } catch (e) { + Logger.log_error(e) + } + + Logger.log_info("Unmodifying graphs") + this.mods.forEach((mod)=>{ + try {mod.restorer()} + catch (e) {Logger.log_error(e)} + }) + this.mods = [] + shared.graph_currently_modified -= 1 + this.unpause() + + return result + } + + + clean_slots(links, slots) { + slots?.forEach((slot)=>{ + if (slot.linkIds.find((lid)=>(!links[lid]))) { + slot.linkIds = slot.linkIds.filter((lid)=>{ return links[lid] !== undefined }) + } + }) + } + + analyse_graph(graph, ignore_pause) { + if (this.paused() && !ignore_pause) return null + + /* work around known bug in ComfyUI front end that doesn't clean up the linkIds + https://github.com/Comfy-Org/ComfyUI_frontend/issues/5673#issuecomment-3314310014 + + Fixed? Doesn't seems to be. + https://github.com/Comfy-Org/ComfyUI_frontend/pull/6258 */ + + + this.clean_slots(graph.links, graph.inputNode?.slots) + this.clean_slots(graph.links, graph.outputNode?.slots) + + this.ambiguities = []; + const treat_bypassed_as_live = settingsCache.getSettingValue("Use Everywhere.Options.connect_to_bypassed") || this.connect_to_bypassed + const live_nodes = graph.nodes.filter((node) => node_is_live(node, treat_bypassed_as_live)) + + // Create a UseEverywhereList and populate it from all live (not bypassed) UE nodes + const ues = new UseEverywhereList(); + live_nodes.filter((node) => node_can_broadcast(node)).filter((node)=>node_is_live(node,false)).forEach(node => { ues.add_ue_from_node(node); }) + + // List all unconnected inputs on non-UE nodes which are connectable + const connectable = [] + live_nodes.filter((node) => !is_UEnode(node)).forEach(node => { + if (node && !node.properties.rejects_ue_links) { + //if (!real_node._widget_name_map) real_node._widget_name_map = real_node.widgets?.map(w => w.name) || []; + node.inputs?.forEach((input,index) => { + if (!input) return; // NoteNode has input = [undefined,] ! + if (is_connected(input, treat_bypassed_as_live, node.graph)) return; + if (node.reject_ue_connection && node.reject_ue_connection(input)) return; + if (is_connectable(node, input.name)) connectable.push({node, input, index}); + }) + } + }) + + if (graph.outputNode) { + graph.outputNode.slots.filter((slot)=>(slot.linkIds.length==0)).forEach((slot,index)=>{ + connectable.push({node:graph.outputNode, input:slot, index}); + } + )} + + // see if we can connect them + const links_added = new Set(); + connectable.forEach(({node, input, index}) => { + var ue = ues.find_best_match(node, input, this.ambiguities); + if (ue) { + links_added.add({ + "downstream":node.id, "downstream_slot":index, + "upstream":ue.output[0], "upstream_slot":ue.output[1], + "controller":ue.controller.id, + "type":ue.type + }); + } + }); + + graph.extra['ue_links'] = Array.from(links_added) + + if (this.ambiguities.length) Logger.log_info("Ambiguous connections", this.ambiguities, true); + + this.latest_ues = ues; + return this.latest_ues; + } +} + +export { GraphAnalyser } diff --git a/cg-use-everywhere/js/use_everywhere_settings.js b/cg-use-everywhere/js/use_everywhere_settings.js new file mode 100644 index 0000000000000000000000000000000000000000..0dd3d8983e48feb870b69dfd9080fc2e3eba2e71 --- /dev/null +++ b/cg-use-everywhere/js/use_everywhere_settings.js @@ -0,0 +1,366 @@ +import { app } from "../../scripts/app.js"; +import { convert_to_links } from "./use_everywhere_apply.js"; +import { Logger, is_UEnode, node_can_broadcast, is_able_to_broadcast } from "./use_everywhere_utilities.js"; +import { settingsCache } from "./use_everywhere_cache.js"; +import { visible_graph } from "./use_everywhere_subgraph_utils.js"; +import { edit_restrictions } from "./ue_properties_editor.js"; +import { i18ify_settings } from "./i18n.js"; +import { VERSION, shared } from "./shared.js"; +import { for_all_graphs } from "./recursive_callbacks.js"; + +const _SETTINGS = [ + { + id: "Use Everywhere.About", + name: `Version ${VERSION}`, + type: () => {return document.createElement('span')}, + }, + { + id: "Use Everywhere.Graphics.showlinks", + name: "Show links", + type: "combo", + options: [ {value:0, text:"All off"}, {value:1, text:"Selected nodes"}, {value:2, text:"Mouseover node"}, {value:3, text:"Selected and mouseover nodes"}, {value:4, text:"All on"}], + defaultValue: 3, + onChange: settingsCache.onSettingChange, + }, + { + id: "Use Everywhere.Graphics.fuzzlinks", + name: "Statically distinguish UE links", + type: "boolean", + tooltip: "Render UE links, when shown, differently from normal links. Much lower performance cost than animation.", + defaultValue: true, + onChange: settingsCache.onSettingChange, + }, + { + id: "Use Everywhere.Graphics.animate", + name: "Animate UE links", + type: "combo", + options: [ {value:0, text:"Off"}, {value:1, text:"Dots"}, {value:2, text:"Pulse"}, {value:3, text:"Both"}, ], + defaultValue: 0, + onChange: settingsCache.onSettingChange, + tooltip: "Animating links may have a negative impact on UI performance. Consider using Statically distinguish UE links instead." + }, + { + id: "Use Everywhere.Graphics.stop_animation_when_running", + name: "Turn animation off when workflow is running", + type: "boolean", + defaultValue: true, + onChange: settingsCache.onSettingChange, + }, + { + id: "Use Everywhere.Graphics.highlight", + name: "Highlight connected and connectable inputs", + type: "boolean", + defaultValue: true, + onChange: settingsCache.onSettingChange, + }, + { + id: "Use Everywhere.Graphics.preserve edit window position", + name: "Save restrictions edit window position", + type: "boolean", + defaultValue: false, + onChange: settingsCache.onSettingChange, + tooltip: "If off, the edit window appears where the mouse is" + }, + { + id: "Use Everywhere.Graphics.tooltips", + name: "Show restrictions as tooltip", + type: "boolean", + defaultValue: true, + onChange: settingsCache.onSettingChange, + }, + { + id: "Use Everywhere.Options.connect_to_bypassed", + name: "Connect to bypassed nodes", + type: "boolean", + defaultValue: true, + onChange: settingsCache.onSettingChange, + tooltip: "By default UE links are made to the node downstream of bypassed nodes." + }, + { + id: "Use Everywhere.Options.logging", + name: "Logging", + type: "combo", + options: [ {value:0, text:"Errors Only"}, {value:1, text:"Problems"}, {value:2, text:"Information"}, {value:3, text:"Detail"}, ], + defaultValue: 1, + onChange: settingsCache.onSettingChange, + }, + { + id: "Use Everywhere.Options.block_graph_validation", + name: "Block workflow validation", + type: "boolean", + defaultValue: true, + tooltip: "Turn off workflow validation (which tends to replace UE links with real ones)", + onChange: settingsCache.onSettingChange, + }, + { + id: "Use Everywhere.Options.always_modify_graph", + name: "Always modify graph", + type: "boolean", + defaultValue: false, + tooltip: "If turned on, the UE modifications will apply even if the trigger is unknown. This will enable API exports, but may cause incompatibility with other nodes.", + onChange: settingsCache.onSettingChange, + }, + { + id: "Use Everywhere.Options.use_output_name", + name: "When connecting, use the output slot's name as the input name", + type: "boolean", + defaultValue: false, + tooltip: "By default the link type is used as the name", + onChange: settingsCache.onSettingChange, + }, +] + +export const SETTINGS = i18ify_settings(_SETTINGS) + +const ui_update_settings = [ + "Use Everywhere.Graphics.showlinks", + "Use Everywhere.Graphics.fuzzlinks", + "Use Everywhere.Graphics.animate", + "Use Everywhere.Graphics.stop_animation_when_running", + "Use Everywhere.Graphics.highlight", + "Use Everywhere.Language.language", +] +ui_update_settings.forEach((id) => { + settingsCache.addCallback(id, ()=>{app.graph?.change.bind(app.graph)}) +}) + +function show_connectable(submenu_root, node) { + node.inputs.forEach((input, i) => { + const current_element = submenu_root?.querySelector(`:nth-child(${i+1})`); + if (current_element) current_element.style.borderLeft = (is_connectable(node,input.name)) ? "2px solid #484" : ""; + }) +} + +export function is_connectable(node, input_name){ + if (node.properties.rejects_ue_links) return false + const input = node.inputs.find(i => i.name==input_name); + if (!input) { + Logger.log_error(`Can't find input ${input_name} on node ${node.title}`); + return false; + } + if (input.widget) { + return !!(node.properties?.ue_properties?.widget_ue_connectable?.[input_name]) + } else { + return ! (node.properties?.ue_properties?.input_ue_unconnectable?.[input_name]) + } +} + +function toggle_connectable(node, input_name){ + const input = node.inputs.find(i => i.name==input_name); + const p = node.properties.ue_properties + if (input.widget) { + p.widget_ue_connectable[input_name] = !!!p.widget_ue_connectable?.[input_name]; + } else { + p.input_ue_unconnectable[input_name] = !!!p.input_ue_unconnectable?.[input_name]; + } +} + +function widget_ue_submenu(value, options, e, menu, node) { + if (!(node.properties.ue_properties)) node.properties.ue_properties = {} + if (!(node.properties.ue_properties.widget_ue_connectable)) node.properties.ue_properties.widget_ue_connectable = {}; + if (!(node.properties.ue_properties.input_ue_unconnectable)) node.properties.ue_properties.input_ue_unconnectable = {}; + + const label_to_name = {} + node.inputs + .filter(i => !i.hidden) + .filter(i => !i.name?.includes('$$')) + .forEach((input) => { label_to_name[input.label || input.name] = input.name }); + + const submenu = new LiteGraph.ContextMenu( + Object.keys(label_to_name), + { event: e, callback: function (label) { + const name = label_to_name[label]; + toggle_connectable(node, name); + shared.linkRenderController.mark_link_list_outdated(); + show_connectable(this.parentElement, node) + return true; // keep open + }, + parentMenu: menu, node:node} + ) + show_connectable(submenu.root, node) +} + +function show_broadcasting(submenu_root, node) { + node.outputs.forEach((input, i) => { + const current_element = submenu_root?.querySelector(`:nth-child(${i+1})`); + if (current_element) current_element.style.borderLeft = (is_able_to_broadcast(node,input.name)) ? "2px solid #484" : ""; + }) +} + +function toggle_broadcasting(node, output_name){ + const p = node.properties.ue_properties + p.output_not_broadcasting[output_name] = !!!p.output_not_broadcasting[output_name] +} + +function output_ue_submenu(value, options, e, menu, node) { + if (!(node.properties.ue_properties)) node.properties.ue_properties = {} + if (!(node.properties.ue_properties.output_not_broadcasting)) node.properties.ue_properties.output_not_broadcasting = {}; + + const label_to_name = {} + node.outputs.forEach((output) => {label_to_name[output.label || output.name] = output.name}) + const submenu = new LiteGraph.ContextMenu( + Object.keys(label_to_name), + { event: e, callback: function (label) { + const name = label_to_name[label]; + toggle_broadcasting(node, name); + shared.linkRenderController.mark_link_list_outdated(); + show_broadcasting(this.parentElement, node) + return true; // keep open + }, + parentMenu: menu, node:node} + ) + show_broadcasting(submenu.root, node) +} + + + +export function add_extra_menu_items(node, ioio) { + if (node.ue_extra_menu_items_added) return + const getExtraMenuOptions = node.getExtraMenuOptions; + node.getExtraMenuOptions = function(_, options) { + getExtraMenuOptions?.apply(this, arguments); + options.push(null); + if (node_can_broadcast(this)) { + add_restrictions_and_convert(options, this); + } + if (!is_UEnode(node)) { + add_input_and_output_settings(options, node) + } + options.push(null); + ioio(options,'callback',`menu option on ${this.id}`); + } + node.ue_extra_menu_items_added = true +} + + +function add_restrictions_and_convert(options, node) { + options.push( + { + content: "Edit restrictions", + callback: edit_restrictions, + } + ) + + options.push( + { + content: "Convert to real links", + callback: async () => { + const ues = shared.graphAnalyser.analyse_graph(visible_graph()); + if (ues===null) { + Logger.log_problem("Convert to real links failed to get ues") + alert("Convert failed - press f12 to see the console log") + } else { + convert_to_links(ues, node); + if (is_UEnode(node)) { + visible_graph().remove(node); + } else { + node.properties.ue_convert = false + } + } + } + } + ) +} + +function add_input_and_output_settings(options, node) { + if (node.inputs?.length) { + options.push( + { + content: node.properties.rejects_ue_links ? "Allow UE Links" : "Reject UE Links", + has_submenu: false, + callback: () => { node.properties.rejects_ue_links = !!!node.properties.rejects_ue_links }, + } + ) + + if (!node.properties.rejects_ue_links) { + options.push( + { + content: "UE Connectable Inputs", + has_submenu: true, + callback: widget_ue_submenu, + } + ) + } + } + + if (node.outputs.length) { + options.push( + { + content: node.properties.ue_convert ? "Remove UE broadcasting" : "Add UE broadcasting", + has_submenu: false, + callback: () => { node.properties.ue_convert = !!!node.properties.ue_convert }, + } + ) + if (node.properties.ue_convert) { + options.push( + { + content: "Broadcasting Outputs", + has_submenu: true, + callback: output_ue_submenu, + } + ) + } + } +} + +function remove_ue_nodes(graph) { + graph._nodes.filter((node)=>is_UEnode(node)).forEach((node)=>{graph.remove(node)}) +} + +export function canvas_menu_settings() { + const options = [] + options.push(null); // divider + options.push( + { + content: (app.ui.settings.getSettingValue('Use Everywhere.Graphics.showlinks')>0) ? "Hide UE links" : "Show UE links", + callback: () => { + const setTo = (app.ui.settings.getSettingValue('Use Everywhere.Graphics.showlinks')>0) ? 0 : 4; + app.ui.settings.setSettingValue('Use Everywhere.Graphics.showlinks', setTo); + app.graph.change(); + } + }, + { + content: "Convert all UEs (in this graph/subgraph) to real links", + callback: async () => { + if (window.confirm("This will convert all links (in this graph/subgraph) created by Use Everywhere to real links, and delete all the Use Everywhere nodes. Is that what you want?")) { + shared.linkRenderController.pause("convert"); + try { + const graph = visible_graph() + shared.graphAnalyser.modify_graph( graph ) + remove_ue_nodes( graph ) + } finally { + app.graph.change(); + shared.linkRenderController.unpause() + } + } + } + }, + { + content: "Convert all UEs to real links", + callback: async () => { + if (window.confirm("This will convert all links created by Use Everywhere to real links, and delete all the Use Everywhere nodes. Is that what you want?")) { + shared.linkRenderController.pause("convert"); + try { + for_all_graphs(shared.graphAnalyser.modify_graph.bind(shared.graphAnalyser)) + for_all_graphs(remove_ue_nodes) + } finally { + app.graph.change(); + shared.linkRenderController.unpause() + } + + } + } + }, + ); + if (shared.graphAnalyser.ambiguities.length) { + options.push({ + content: "Show UE broadcast clashes", + callback: async () => { + alert(shared.graphAnalyser.ambiguities.join("\n")) + } + }) + } + options.push(null); // divider + return options +} + diff --git a/cg-use-everywhere/js/use_everywhere_subgraph_utils.js b/cg-use-everywhere/js/use_everywhere_subgraph_utils.js new file mode 100644 index 0000000000000000000000000000000000000000..3a7db4c1a52ef41d66b368549bcd84e1695faf99 --- /dev/null +++ b/cg-use-everywhere/js/use_everywhere_subgraph_utils.js @@ -0,0 +1,86 @@ +import { app } from "../../scripts/app.js"; +import { ue_callbacks } from "./recursive_callbacks.js"; +import { Logger } from "./use_everywhere_utilities.js"; +import { shared } from "./shared.js"; + +export function visible_graph() { return app.canvas.graph } + +export function in_visible_graph(node) { + try { + if (node.graph) return node.graph.id == app.canvas.graph.id + else if (node.subgraph) return node.subgraph.id == app.canvas.graph.id + else Logger.log_problem(`in_visible_graph: ${node.id} has no graph or subgraph`) + } catch (e) { + Logger.log_error(e) + return false + } +} + +export function get_subgraph_input_type(graph, slot) { return graph.inputNode.slots[slot].type } +export function link_is_from_subgraph_input(link) { return link.origin_id==-10 } + +export function connection_from_output_as_input(node, slot) { + try { + return { + type : node.outputs[slot].type, + link : { + origin_id : node.id, + origin_slot : slot, + }, + } + } catch (e) { + console.error(e) + return false + } +} + +export function fix_new_subgraph_node(node) { + try { + const subgraph = node.subgraph + subgraph.inputNode.slots.forEach((slot, i)=>{ + slot.linkIds.forEach((lid) => { + const link = subgraph.links[lid] + const target = subgraph.getNodeById(link.target_id) + const slot_name = target.inputs[link.target_slot].name + const ue_connectable = target.properties.ue_properties.widget_ue_connectable[slot_name] + if (ue_connectable) { + const input_name = node.inputs[i]?.name + if (slot_name!=input_name) { + Logger.log_problem("In fix_new_subgraph names don't match") + } else { + node.properties.ue_properties.widget_ue_connectable[input_name] = true + } + } + }) + }) + } catch (e) { + Logger.log_error(e, "in fix_new_subgraph") + } +} + +class WrappedIONode { + constructor(io_node) { + this.io_node = io_node; + this.graph = io_node.subgraph; + } + + connect(output_index, input_node, input_index) { + this.graph.last_link_id += 1 + this.graph.links[this.graph.last_link_id] = new LLink(this.graph.last_link_id, this.io_node.slots[output_index].type, -10, output_index, input_node.id, input_index) + input_node.inputs[input_index].link = this.graph.last_link_id; + this.io_node.slots[output_index].linkIds.push(this.graph.last_link_id) + return this.graph.links[this.graph.last_link_id] + } + + getConnectionPos(is_input, slot_number) { + if (is_input) { + return [...this.io_node.slots[slot_number].pos] + } else { + Logger.log_problem("WrappedIONode.getConnectionPos called for output - not supported"); + } + } + +} +export function wrap_input(io_node) { + return new WrappedIONode(io_node); +} \ No newline at end of file diff --git a/cg-use-everywhere/js/use_everywhere_ui.js b/cg-use-everywhere/js/use_everywhere_ui.js new file mode 100644 index 0000000000000000000000000000000000000000..b7d43652ca43bfdb4d7b880779f4a4cd53c35130 --- /dev/null +++ b/cg-use-everywhere/js/use_everywhere_ui.js @@ -0,0 +1,545 @@ +import { Logger, get_real_node, Pausable, node_can_broadcast, is_able_to_broadcast } from "./use_everywhere_utilities.js"; +import { app } from "../../scripts/app.js"; +import { settingsCache } from "./use_everywhere_cache.js"; +import { in_visible_graph, visible_graph } from "./use_everywhere_subgraph_utils.js"; +import { maybe_show_tooltip } from "./tooltip_window.js"; +import { is_connectable } from "./use_everywhere_settings.js"; +import { shared } from "./shared.js"; +import { any_restrictions } from "./ue_properties.js"; + +export function nodes_in_my_group(node) { + const nodes_in = new Set(); + node.graph._groups.forEach((group) => { + if (!app.canvas.selected_group_moving) group.recomputeInsideNodes(); + if (group._nodes?.find((nd) => { return (nd.id===node.id) } )) { + group._nodes.forEach((nd) => { nodes_in.add(nd.id) } ) + } + }); + return [...nodes_in]; +} + +export function nodes_not_in_my_group(node) { + const nid = nodes_in_my_group(node); + const nodes_not_in = []; + node.graph._nodes.forEach((nd) => { + if (!nid.includes(nd.id)) nodes_not_in.push(nd.id); + }); + return nodes_not_in; +} + +export function nodes_in_groups_matching(regex, already_limited_to) { + const nodes_in = new Set(); + app.graph._groups.forEach((group) => { + if (regex.regex.test(group.title) != regex.invert) { + if (!app.canvas.selected_group_moving) group.recomputeInsideNodes(); + /* + Note for optimisation - it would be more efficient to calculate what nodes are in what groups + once at the start of analyse_graph() rather than for every group for every UE? with a group regex. + */ + group._nodes.forEach((node) => { + if (!already_limited_to || already_limited_to.includes(node.id)) { + nodes_in.add(node.id) + } + } ); + } + }); + return [...nodes_in]; +} + + +export function nodes_my_color(node, already_limited_to) { + const nodes_in = new Set(); + const color = get_real_node(node.id, node.graph)?.color + if (already_limited_to) { + already_limited_to.forEach((nid) => { + if (get_real_node(nid, node.graph)?.color==color) nodes_in.add(nid) + }) + } else { + node.graph._nodes.forEach((nd) => { + if (nd.color==color) nodes_in.add(nd.id) + }) + } + return [...nodes_in]; +} + +export function nodes_not_my_color(node, already_limited_to) { + const nodes_in = new Set(); + const color = get_real_node(node.id)?.color; + if (already_limited_to) { + already_limited_to.forEach((nid) => { + if (get_real_node(nid, node.graph)?.color!=color) nodes_in.add(nid) + }) + } else { + node.graph._nodes.forEach((nd) => { + if (nd.color!=color) nodes_in.add(nd.id) + }) + } + return [...nodes_in]; +} + +export function title_bar_additions(node, ctx, title_height) { + if (node_can_broadcast(node)) { + const restricted = any_restrictions(node); + const sending = shared.linkRenderController.node_sending_anywhere(node); + + const color = restricted ? ( sending ? "rgba(255, 255, 72, 1)" : "rgba(255, 255, 72, 0.35)" ) : + ( sending ? "rgba(72, 255, 72, 1)" : "rgba(72, 255, 72, 0.35)" ); + + const offset_x = (node.subgraph) ? 5 : 5 + const offset_y = (node.subgraph) ? 4 : 5 + const width = (node.subgraph) ? 24 : 20 + const height = (node.subgraph) ? 23 : 20 + const radius = (node.subgraph) ? 6 : 6 + + const line_w = (node.subgraph) ? 1 : 2 + + ctx.save(); + ctx.lineWidth = line_w; + ctx.strokeStyle = color; + ctx.beginPath(); + ctx.roundRect(offset_x, offset_y-title_height, width, height, radius); + ctx.stroke(); + ctx.restore(); + } +} + +export class LinkRenderController extends Pausable { + + constructor() { + super('LinkRenderController') + this.ue_list = undefined; // the most current ue list - set to undefined if we know it is out of date + this.last_used_ue_list = undefined; // the last ue list we actually used to generate graphics + this.link_list_outdated = false; + this.widgets_disabled = [] + setInterval(this.try_to_update_link_list.bind(this), 100); + setInterval(this.mark_link_list_outdated.bind(this), 2000); + } + + queue_size = null; + note_queue_size(x) { this.queue_size = x; } + + + //on_unpause() {app.graph.change();} + + node_over_changed() { + const mode = settingsCache.getSettingValue('Use Everywhere.Graphics.showlinks'); + if (mode==2 || mode==3) app.canvas.setDirty(true,true) + } + + // memory reuse + slot_pos1 = new Float32Array(2); //to reuse + slot_pos2 = new Float32Array(2); //to reuse + + + /* + Outdating. + + Convention is that methods starting _ should only be called inside a pause()/unpause() + */ + + mark_link_list_outdated() { + this.link_list_outdated = true + } + + try_to_update_link_list() { + if (!this.link_list_outdated) return; + if (this.paused()) return; + try { + this.pause('try_to_update_link_list') + this.ue_list = undefined; + if (this._request_link_list_update()) this.link_list_outdated = false; + } finally { + this.unpause() + } + } + + _request_link_list_update() { + try { + const ues = shared.graphAnalyser.analyse_graph(visible_graph()) + if (ues==null) return false // graph analyser was paused + this.ue_list = ues; + if (this.ue_list.differs_from(this.last_used_ue_list)) app.graph.change(); + return true + } catch (e) { + Logger.log_error(e); + return false + } + } + + disable_all_connected_widgets( ) { + this.widgets_disabled = [] + app.canvas.graph.extra['ue_links']?.forEach((uel) => { + const node = app.canvas.graph.getNodeById(uel.downstream) + if (node) { + const name = node.inputs[uel.downstream_slot]?.name; + if (name) { + const widget = node.widgets?.find((w)=>(w.name==name)) + if (widget && !widget.disabled) { + try { + widget._disabled = widget.disabled; + widget.disabled = true; + this.widgets_disabled.push(widget) + } catch (e) { Logger.log_error(e, `Error disabling widget ${name} on node ${node.id}`) } + } + } + } + }) + } + + enable_all_disabled_widgets() { + this.widgets_disabled.forEach((w)=>{ + try { w.disabled=w._disabled } catch (e) { Logger.log_error(e, `Error enabling widget ${w}`) } + }) + } + + highlight_subgraph_node_connections(subgraph, ctx) { + if (!settingsCache.getSettingValue('Use Everywhere.Graphics.highlight')) return; + const node = subgraph?.outputNode + const ue_connections = this.ue_list.all_connected_inputs(subgraph.outputNode) + + ue_connections.forEach((ue_connection)=>{ + const pos2 = node.slots[ue_connection.input_index]?.pos; + if (pos2) { + drawcircle(ctx, pos2, CONNECTED_1, 5, "first", {strokeStyle:LGraphCanvas.link_type_colors[ue_connection.type]}) + drawcircle(ctx, pos2, CONNECTED_2, 4, "last") + } + }) + + shared.graphAnalyser.ambiguities.filter((ambiguity)=>(ambiguity.id==-20)).forEach((ambiguity)=>{ + const index = ambiguity.matches[0]?.node_index + const pos2 = node.slots[index]?.pos + if (pos2) { + drawcross(ctx, pos2, AMBIGUITY, 7) + } + }) + + + } + + highlight_ue_connections(node, ctx) { + if (!settingsCache.getSettingValue('Use Everywhere.Graphics.highlight')) return; + if (!node.inputs) return; + + try { + this.pause('highlight_ue_connections') + if (!this._list_ready()) return; + + // get all the inputs that can be connected and aren't + // connected with a 'real' link + const unconnected_connectable_names = new Set(node.inputs + .filter((input)=>is_connectable(node,input.name)) + .filter((input)=>(!input.link)) + .map((input)=>input.name) || []) + + if (this.ue_list.all_connected_inputs) { + this.ue_list.all_connected_inputs(node).forEach((ue_connection) => { + if (!ue_connection.control_node) return; + if (!node.inputs[ue_connection.input_index]) return + + const name_sent_to = node.inputs[ue_connection.input_index].name; + unconnected_connectable_names.delete(name_sent_to); // remove the name from the list of connectables + const pos2 = this._relative_connection_pos(node, true, ue_connection.input_index); + + drawcircle(ctx, pos2, CONNECTED_1, 6, "first", {strokeStyle:LGraphCanvas.link_type_colors[ue_connection.type]} ) + drawcircle(ctx, pos2, CONNECTED_2, 5, "last" ) + }); + } + + unconnected_connectable_names.forEach((name) => { + const index = node.inputs.findIndex((i) => i.name == name); + const pos2 = this._relative_connection_pos(node, true, index); + drawcircle(ctx, pos2, {...UNCONNECTED_CONNECTABLE}, 3) + }) + + if (node.properties.ue_convert) { + const sending_slots = this.ue_list.all_sending_slots(node) + + node.outputs.forEach((output,i) => { + if (is_able_to_broadcast(node, output.name)) { + const pos2 = this._relative_connection_pos(node, false, i); + if (sending_slots.has(i)) { + drawcircle(ctx, pos2, CONNECTED_1, 6, "first", {strokeStyle:LGraphCanvas.link_type_colors[node.outputs[i].type]}) + drawcircle(ctx, pos2, CONNECTED_2, 5, "last") + } else { + drawcircle(ctx, pos2, UNCONNECTED_CONNECTABLE, 3) + } + + } + }) + } + + shared.graphAnalyser.ambiguities.filter((ambiguity)=>(ambiguity.id==node.id)).forEach((ambiguity)=>{ + const index = node.inputs.findIndex((input)=>(input.name==ambiguity.input)) + if (index>=0) { + const pos2 = this._relative_connection_pos(node, true, index); + drawcross(ctx, pos2, AMBIGUITY, 7) + } + }) + + } catch (e) { + Logger.log_error(e); + } finally { + this.unpause() + } + } + + _relative_connection_pos(node, input, slot) { + var pos2; + if (node.getSlotPosition) { + pos2 = node.getSlotPosition(slot, input) + } else { + pos2 = node.getConnectionPos?.(input, slot, this.slot_pos1) || node.slots[slot].pos; + } + pos2[0] -= node.pos[0]; + pos2[1] -= node.pos[1]; + return pos2 + } + + _list_ready() { + if (!shared.graphAnalyser) return false; // we don't have the analyser yet (still loading) + if (!this.ue_list) { + this.mark_link_list_outdated(); + return false; + } + return true; + } + + node_sending_anywhere(node) { + if (!this._list_ready()) return false; + return this.ue_list.node_sending_anywhere(node); + } + + node_in_ueconnection(ue_connection, id) { + if (ue_connection.control_node?.id == id) return true + if (ue_connection.sending_to?.id == id) return true + } + + any_node_in_ueconnection(ue_connection, list_of_nodes) { + return (Object.values(list_of_nodes).find((node) => (this.node_in_ueconnection(ue_connection, node.id))))?true:false; + } + + render_all_ue_links(ctx) { + maybe_show_tooltip() + if (this.paused()) return; + try { + this.pause('render_all_ue_links') + this._render_all_ue_links(ctx); + } catch (e) { + console.error(e); + } finally { + this.unpause() + } + } + + _render_all_ue_links(ctx) { + if (!this._list_ready()) return; + this.last_used_ue_list = this.ue_list; + + ctx.save(); + const orig_hqr = app.canvas.highquality_render; + app.canvas.highquality_render = false; + + const mode = settingsCache.getSettingValue('Use Everywhere.Graphics.showlinks'); + var animate = settingsCache.getSettingValue('Use Everywhere.Graphics.animate'); + if (settingsCache.getSettingValue('Use Everywhere.Graphics.stop_animation_when_running') && this.queue_size>0) animate = 0; + if (animate==2 || animate==3) this.animate_step(ctx); + + var any_links_shown = false; + var any_links = false; + + shared.graphAnalyser.ambiguities.forEach((ambiguity)=>{ + ambiguity.matches.forEach((m)=>{ + if (app.canvas.node_over == m.node || ambiguity.id==-20 && ambiguity.graph.outputNode?.isPointerOver) { + this._render_ue_link( + { + graph : ambiguity.graph, + sending_to : m.node, + input_index : m.node_index, + control_node : ambiguity.graph.getNodeById(m.id), + control_node_input_index : m.index, + type : m.type, + }, ctx, 0, "#F00") + } + + }) + }) + + + this.ue_list.all_ue_connections().forEach((ue_connection) => { + any_links = true; + var show = false; + if ( mode==4 ) show = true; + if ( (mode==2 || mode==3) && app.canvas.node_over && this.node_in_ueconnection(ue_connection, app.canvas.node_over.id) ) show = true; + if ( (mode==1 || mode==3) && this.any_node_in_ueconnection(ue_connection, app.canvas.selected_nodes)) show = true; + + show = show && in_visible_graph(ue_connection.control_node) && in_visible_graph(ue_connection.sending_to); + if ( show ) { + this._render_ue_link(ue_connection, ctx, animate); + any_links_shown = true; + } + }); + + if (animate>0) { + /* + If animating, we want to mark the visuals as changed so the animation updates - but not often! + If links shown: + - If showing dots, wait 30ms + - Otherwise, wait 100ms + If no links are shown + - If there are links, and our mode is mouseover, wait 200ms + - Otherwise don't request an update (there are no links that could be shown without something else requesting a redraw) + */ + const timeout = (any_links_shown) ? ((animate%2 == 1) ? 30 : 100) : ((mode==2 || mode==3) && any_links) ? 200 : -1; + if (timeout>0) setTimeout( app.graph.change.bind(app.graph), timeout ); + } + + app.canvas.highquality_render = orig_hqr; + ctx.restore(); + + } + + _render_ue_link(ue_connection, ctx, animate, color) { + try { + const graph = ue_connection.graph + const node = get_real_node(ue_connection.sending_to.id, graph); + + /* this is the end node; get the position of the input */ + var pos2; + + if (node.getSlotPosition) { + pos2 = node.getSlotPosition(ue_connection.input_index, true) + } else { + pos2 = node.getConnectionPos(true, ue_connection.input_index, this.slot_pos1); + } + + const control_node = graph.getNodeById(ue_connection.control_node.id) + if (!control_node) { + Logger.problem(`Couldn't find position for UE link ${ue_connection}.`,null,true) + return; + } + + + /* + get the position of the *input* that is being echoed except for: + - the Seed Anywhere node: the class records control_node_input_index as -ve (-1 => 0, -2 => 1...) + - subgraph converts + those link to outputs + */ + const input_source = (ue_connection.control_node_input_index >= 0 && !control_node.properties.ue_convert); + const source_index = (ue_connection.control_node_input_index >= 0 ) ? ue_connection.control_node_input_index : -1-ue_connection.control_node_input_index; + var pos1; + + if (control_node.getSlotPosition) { + pos1 = control_node.getSlotPosition(source_index, input_source) + } else { + pos1 = control_node.getConnectionPos(input_source, source_index, this.slot_pos2); + } + + /* get the direction that we start and end */ + const delta_x = pos2[0] - pos1[0]; + const delta_y = pos2[1] - pos1[1]; + const end_direction = LiteGraph.LEFT; // always end going into an input + const sta_direction = ((Math.abs(delta_y) > Math.abs(delta_x)) && input_source) ? + ((delta_y>0) ? LiteGraph.DOWN : LiteGraph.UP) : + ((input_source && delta_x<0) ? LiteGraph.LEFT : LiteGraph.RIGHT) + + color = color || LGraphCanvas.link_type_colors[ue_connection.type] || app.canvas.default_link_color; + + ctx.save() + const rcb = app.canvas.render_connections_border; + try { + var skip_border = false + if (settingsCache.getSettingValue( "Use Everywhere.Graphics.fuzzlinks" )) { + app.canvas.render_connections_border = false + ctx.shadowColor = color; + ctx.shadowBlur = 6; + skip_border = true + } + app.canvas.renderLink(ctx, pos1, pos2, undefined, skip_border, animate%2, modify(color), sta_direction, end_direction, undefined); + } catch(e) { + Logger.log_error(e); + } finally { + ctx.restore() + app.canvas.render_connections_border = rcb; + } + + } catch (e) { + Logger.log_error(e, `Couldn't render UE link ${ue_connection}. That's ok if something just got deleted.`); + } + } + + animate_step(ctx) { + const max_blur = 8; + const speed = 0.75; + var f = (LiteGraph.getTime()*0.001*speed) % 1; + const step = Math.ceil(f*2*max_blur) % (2*max_blur); + ctx.shadowBlur = (step{ + if (DEFAULTS[k]!==undefined) ctx[k] = DEFAULTS[k] + if (properties[k]!==undefined) ctx[k] = properties[k] + if (additional && additional[k]!==undefined) ctx[k] = additional[k] + }) + ctx.beginPath(); + ctx.roundRect(position[0]-radius,position[1]-radius,2*radius,2*radius,radius); + ctx.stroke(); + if (!first_last || first_last=='last') ctx.restore() +} + +function drawcross(ctx, position, properties, radius) { + ctx.save() + PROPS.forEach((k)=>{ + if (DEFAULTS[k]) ctx[k] = DEFAULTS[k] + }) + ctx.lineWidth = properties.lineWidth + ctx.strokeStyle = properties.strokeStyle + ctx.beginPath(); + ctx.moveTo(position[0]-radius,position[1]-radius) + ctx.lineTo(position[0]+radius,position[1]+radius) + ctx.moveTo(position[0]-radius,position[1]+radius) + ctx.lineTo(position[0]+radius,position[1]-radius) + ctx.stroke(); + ctx.restore() +} + +function modify(c) { + if (c.length==4) return c + "6" + if (c.length==7) return c + "66" + return c +} diff --git a/cg-use-everywhere/js/use_everywhere_utilities.js b/cg-use-everywhere/js/use_everywhere_utilities.js new file mode 100644 index 0000000000000000000000000000000000000000..bc1637864dbb9b4fbc0d5b9fbf9663a8135aa502 --- /dev/null +++ b/cg-use-everywhere/js/use_everywhere_utilities.js @@ -0,0 +1,390 @@ +import { app } from "../../scripts/app.js"; +import { settingsCache } from "./use_everywhere_cache.js"; +import { link_is_from_subgraph_input, visible_graph, wrap_input, connection_from_output_as_input } from "./use_everywhere_subgraph_utils.js"; +import { i18n } from "./i18n.js"; +import { ue_callbacks } from "./recursive_callbacks.js"; +import { shared } from "./shared.js"; + +export function create( tag, clss, parent, properties ) { + const nd = document.createElement(tag); + if (clss) clss.split(" ").forEach((s) => nd.classList.add(s)) + if (parent) parent.appendChild(nd); + if (properties) Object.assign(nd, properties); + return nd; +} + +/* +Return 1 if x is a later version than y (or y is not defined) +Return -1 if x is an earlier version than y (or x is not defined) +Return 0 if they are the same version +*/ +function version_compare(x,y) { + if (x==y) return 0 + if (!y) return 1 + if (!x) return -1 + const xbits = x.split('.') + const ybits = y.split('.') + var result = 0 + for (var i=0; result!=0 && i parseInt(ybits[i])) result = 1 + } + if (result==0) { + if (xbits.length < ybits.length) result = -1 + if (xbits.length > ybits.length) result = 1 + } + return result +} + +export function version_at_least(x,y) { + return (version_compare(x,y) >= 0) +} + +/* +Return the node object for this node_id. +*/ +export function get_real_node(node_id, graph) { + if (!graph) graph = visible_graph() + const nid = node_id.toString(); + if (nid==-10) return wrap_input(graph.inputNode); // special case for subgraph input + if (nid==-20) return wrap_input(graph.outputNode); // special case for subgraph input + return graph.getNodeById(nid); +} + +export class Logger { + static LIMITED_LOG_BLOCKED = false; + static LIMITED_LOG_MS = 5000; + static level; // 0 for errors only, 1 activates 'log_problem', 2 activates 'log_info', 3 activates 'log_detail' + + static log_shared(message, trace, limited) { + if (limited && Logger.check_limited()) return false + console.log(message) + if (trace) console.trace() + shared.report_keys.forEach((key)=>{ + console.log( `${key.padStart(40,' ')} = ${shared[key]}` ) + }) + } + + static log_arguments(a) { + Object.keys(arguments).forEach((k)=>{console.log(arguments[k])}) + } + + static log_error(message, more) { + if (more) console.log(more) + console.error(message) + } + + static log(message, foreachable, limited) { + if (limited && Logger.check_limited()) return false + console.log(message); + foreachable?.forEach((x)=>{console.log(x)}) + return true + } + + static log_with_trace() { + if (Logger.log(arguments)) console.trace() + } + + static check_limited() { + if (Logger.LIMITED_LOG_BLOCKED) return true + Logger.LIMITED_LOG_BLOCKED = true + setTimeout( ()=>{Logger.LIMITED_LOG_BLOCKED = false}, Logger.LIMITED_LOG_MS ) + return false + } + + static null() {} + + static level_changed(new_level) { + Logger.level = new_level + Logger.log_detail = (Logger.level>=3) ? Logger.log : Logger.null + Logger.log_info = (Logger.level>=2) ? Logger.log : Logger.null + Logger.log_problem = (Logger.level>=1) ? Logger.log_with_trace : Logger.null + } + + static log_detail(){} + static log_info(){} + static log_problem(){} +} + +Logger.level_changed(settingsCache.getSettingValue('Use Everywhere.Options.logging')) +settingsCache.addCallback('Use Everywhere.Options.logging', Logger.level_changed) + +class GraphConverter { + static _instance; + static instance() { + if (!GraphConverter._instance) GraphConverter._instance = new GraphConverter(); + return GraphConverter._instance; + } + + constructor() { + this.node_input_map = {}; + this.given_message = false; + this.did_conversion = false; + } + + //running_116_plus() { + // const version = __COMFYUI_FRONTEND_VERSION__.split('.') + // return (parseInt(version[0])>=1 && (parseInt(version[0])>1 || parseInt(version[1])>=16)) + //} + + store_node_input_map(data) { + this.node_input_map = {}; + data?.nodes.filter((node)=>(node.inputs)).forEach((node) => { this.node_input_map[node.id] = node.inputs.map((input) => input.name); }) + Logger.log_detail("stored node_input_map", this.node_input_map); + } + + + clean_ue_node(node) { + var expected_inputs = 1 + if (node.type == "Seed Everywhere") expected_inputs = 0 + if (node.type == "Prompts Everywhere") expected_inputs = 2 + if (node.type == "Anything Everywhere3") expected_inputs = 3 + if (node.type == "Anything Everywhere?") expected_inputs = 4 + + // remove all the 'anything' inputs (because they may be duplicated) + const removed = node.inputs.filter(i=>(i.label==i18n('anything') || i.label=='*')) + node.inputs = node.inputs.filter(i=>(i.label!=i18n('anything') && i.label!='*')) + // add them back as required + while (node.inputs.length < expected_inputs) { node.inputs.push(removed.pop()) } + // the input comes before the regex widgets in UE? + if (expected_inputs==4) { + while(node.inputs[0].name.includes('regex')) { + node.inputs.unshift(node.inputs.pop()) + } + } + // fix the localized names + node.inputs = node.inputs.forEach((input) => { + if (input) { + if (!input.localized_name || input.localized_name.startsWith(i18n('anything'))) input.localized_name = input.name + } else { + let brteakpoint; + } + }) + + // set types to match + if (node.inputs) { + node.inputs.forEach((input) => { + if (input.type=='*') { + const graph = node.graph; + if (input.link) { + const llink = graph.links[input.link]; + if (link_is_from_subgraph_input(llink)) { + input.type = get_subgraph_input_type(graph, llink.origin_slot); + } else { + input.type = llink.type; + } + } else { + input.type = (input.label && input.label!=i18n('anything')) ? input.label : input.name + } + } + }); + + Logger.log_detail(`clean_ue_node ${node.id} (${node.type})`, node.inputs); + } + } + + convert_if_pre_116(node) { + if (!node) return; + + if (node.properties?.ue_properties?.widget_ue_connectable) return + if (node.properties?.widget_ue_connectable) return // pre 7.0 node which will be converted + + if (is_UEnode(node)) { + if (node.properties?.ue_properties?.version) return + this.clean_ue_node(node) + } + + if (!this.given_message) { + Logger.log_info(`Graph was saved with a version of ComfyUI before 1.16, so Anything Everywhere will try to work out which widgets are connectable`); + this.given_message = true; + } + + if (!node.properties.ue_properties) node.properties.ue_properties = {} + node.properties.ue_properties['widget_ue_connectable'] = {} + const widget_names = node.widgets?.map(w => w.name) || []; + + if (!(this.node_input_map[node.id])) { + Logger.log_detail(`node ${node.id} (${node.type} has no node_input_map`); + } else { + this.node_input_map[node.id].filter((input_name)=>widget_names.includes(input_name)).forEach((input_name) => { + node.properties.ue_properties['widget_ue_connectable'][input_name] = true; + this.did_conversion = true; + Logger.log_info(`node ${node.id} widget ${input_name} marked as accepting UE because it was an input when saved`); + }); + } + } + + remove_saved_ue_links(graph) { + if (graph.extra?.links_added_by_ue) { + graph.extra.links_added_by_ue.forEach((link_id) => { app.graph.links.delete(link_id); }) + } + } +} + +export const graphConverter = GraphConverter.instance(); +ue_callbacks.register_allgraph_callback('afterConfigureGraph', graphConverter.remove_saved_ue_links) + +/* +Is a node alive (ie not bypassed or set to never) +*/ +export function node_is_live(node, treat_bypassed_as_live){ + if (!node) return false; + if (node.mode===0) return true; + if (node.mode===2 || node.mode===4) return !!treat_bypassed_as_live; + Logger.log_error(`node ${node.id} has mode ${node.mode} - I only understand modes 0, 2 and 4`); + return true; +} + +function node_is_bypassed(node) { + return (node.mode===4); +} + +/* +Given a link object, and the type of the link, +go upstream, following links with the same type, until you find a parent node which isn't bypassed. +If either type or original link is null, or if the upstream thread ends, return null +*/ +function handle_bypass(original_link, type, graph) { + if (!type || !original_link) return null; + var link = original_link; + if (link_is_from_subgraph_input(link)) return link + var parent = get_real_node(link.origin_id, graph); + if (!parent) return null; + while (node_is_bypassed(parent)) { + if (!parent.inputs) return null; + var link_id; + if (parent?.inputs[link.origin_slot]?.type == type) link_id = parent.inputs[link.origin_slot].link; // try matching number first + else link_id = parent.inputs.find((input)=>input.type==type)?.link; + if (!link_id) { return null; } + link = graph.links[link_id]; + parent = get_real_node(link.origin_id, graph); + } + return link; +} + + +/* +Does this input connect upstream to a live node? +*/ +export function is_connected(input, treat_bypassed_as_live, graph) { + const link_id = input.link; + if (link_id === null) return false; // no connection + var the_link = graph.links[link_id]; + if (!the_link) return false; + if (treat_bypassed_as_live) return true; + the_link = handle_bypass(the_link, the_link.type, graph); // find the link upstream of bypasses + if (!the_link) return false; // no source for data. + return true; +} + +/* +Is this a UE node? +*/ +export function is_UEnode(node) { + const type = node.comfyClass; + if (type == "Anything Everywhere") return true; + return ((type) && (type.startsWith("Anything Everywhere") || type==="Seed Everywhere" || type==="Prompts Everywhere")) +} + +export function node_can_broadcast(node) { + return (node.properties?.ue_convert || is_UEnode(node)) +} + + + +/* +Inject a call into a method on object with name methodname. +The injection is added at the end of the existing method (if the method didn't exist, it is created) +injectionthis and injectionarguments are passed into the apply call (as the this and the arguments) +*/ +export function inject(object, methodname, tracetext, injection, injectionthis, injectionarguments) { + const original = object[methodname]; + object[methodname] = function() { + original?.apply(this, arguments); + injection.apply(injectionthis, injectionarguments); + } +} + +export class Pausable { + constructor(name) { + this.name = name + this.pause_depth = 0 + } + pause(note, ms) { + this.pause_depth += 1; + if (this.pause_depth>10) { + Logger.log_error(`${this.name} Over pausing`) + } + Logger.log_detail(`${this.name} pause ${note} with ${ms}`) + if (ms) setTimeout( this.unpause.bind(this), ms ); + } + unpause() { + this.pause_depth -= 1 + Logger.log_detail(`${this.name} unpause`) + if (this.pause_depth<0) { + Logger.log_error(`${this.name} Over unpausing`) + this.pause_depth = 0 + } + this.on_unpause() + } + paused() { + return (this.pause_depth>0) + } + on_unpause(){} +} + +export function get_connection(node, i) { + const graph = node.graph + const in_link = node?.inputs[i]?.link; + if (in_link) { + var llink = graph.links[in_link] + llink = handle_bypass(llink, llink.type, graph) + if (!llink) { + Logger.log(`handle_bypass failing - subgraph issue?`, null, true) + llink = graph.links[in_link] + } + return { link:llink, type:llink.type } + } else { + return { link:undefined, type:undefined } + } +} + +export function is_able_to_broadcast(node, output_name) { + if (!node.properties.ue_convert) return false + const output = node.outputs.find(i => i.name==output_name); + if (!output) { + Logger.log_error(`Can't find output ${output_name} on node ${node.title}`); + return false; + } + return ! (node.properties?.ue_properties?.output_not_broadcasting?.[output_name]) +} + +export function find_duplicate_broadcasted_types(node) { + var the_possibles + var connection_finder + var check_if_able_to_broadcast + + if (node.properties.ue_convert) { + the_possibles = node.outputs + connection_finder = connection_from_output_as_input + check_if_able_to_broadcast = (node, i) => { + const name = node.outputs[i].name + return is_able_to_broadcast(node, name) + } + } else { + check_if_able_to_broadcast = ()=>(true) + the_possibles = node.inputs + connection_finder = get_connection + } + + const broadcasted_types = new Set() + const duplicated_broadcasted_types = new Set() + for (var i=0; i list[str]: + img_count = 1 + paths = list() + for image in images: + i = 255. * image.cpu().numpy() + img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8)) + if images.size()[0] > 1: + filename_prefix += "_{:02d}".format(img_count) + + if extension == 'png': + metadata = PngInfo() + metadata.add_text("parameters", comment) + + 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])) + + filename = f"{filename_prefix}.png" + img.save(os.path.join(output_path, filename), pnginfo=metadata, optimize=True) + else: + filename = f"{filename_prefix}.{extension}" + file = os.path.join(output_path, filename) + img.save(file, optimize=True, quality=quality_jpeg_or_webp, lossless=lossless_webp) + exif_bytes = piexif.dump({ + "Exif": { + piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(comment, encoding="unicode") + }, + }) + piexif.insert(exif_bytes, file) + + paths.append(filename) + img_count += 1 + return paths + + +NODE_CLASS_MAPPINGS = { + "Checkpoint Selector": CheckpointSelector, + "Save Image w/Metadata": ImageSaveWithMetadata, + "Sampler Selector": SamplerSelector, + "Scheduler Selector": SchedulerSelector, + "Seed Generator": SeedGenerator, + "String Literal": StringLiteral, + "Width/Height Literal": SizeLiteral, + "Cfg Literal": CfgLiteral, + "Int Literal": IntLiteral, +} diff --git a/comfy-image-saver/requirements.txt b/comfy-image-saver/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..dfe1a52d5f0dc4df0b4709bbfa904ac4a967f416 --- /dev/null +++ b/comfy-image-saver/requirements.txt @@ -0,0 +1,2 @@ + +piexif diff --git a/comfyui-art-venture/.gitignore b/comfyui-art-venture/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ae6bf7659af9c814e520c006bffaba4d0dcd5e0b --- /dev/null +++ b/comfyui-art-venture/.gitignore @@ -0,0 +1,42 @@ +__pycache__ +*.ckpt +*.safetensors +*.pth +/ESRGAN/* +/SwinIR/* +/repositories +/venv +/tmp +/model.ckpt +/models/**/* +/GFPGANv1.3.pth +/gfpgan/weights/*.pth +/ui-config.json +/outputs +/config.json +/log +/webui.settings.bat +/embeddings +/styles.csv +/params.txt +/styles.csv.bak +/webui-user.bat +/webui-user.sh +/interrogate +/user.css +/.idea +notification.mp3 +/SwinIR +/textual_inversion +.vscode +/extensions +/test/stdout.txt +/test/stderr.txt +/cache.json +*.sql +*.db +*.sqlite +*.sqlite3 +tailwind.* +workflow.json +workflow-*.json diff --git a/comfyui-art-venture/.prettierrc b/comfyui-art-venture/.prettierrc new file mode 100644 index 0000000000000000000000000000000000000000..e747179b951ed91fdccade7e3ea0066abf24aa25 --- /dev/null +++ b/comfyui-art-venture/.prettierrc @@ -0,0 +1,9 @@ +{ + "singleQuote": true, + "jsxSingleQuote": false, + "arrowParens": "always", + "trailingComma": "all", + "semi": true, + "tabWidth": 2, + "printWidth": 100 +} diff --git a/example_node.py.example b/example_node.py.example new file mode 100644 index 0000000000000000000000000000000000000000..b5cf75eb88e03a0353e01ffea0527bf5db44220f --- /dev/null +++ b/example_node.py.example @@ -0,0 +1,130 @@ +from typing_extensions import override + +from comfy_api.latest import ComfyExtension, io + + +class Example(io.ComfyNode): + """ + An example node + + Class methods + ------------- + define_schema (io.Schema): + Tell the main program the metadata, input, output parameters of nodes. + fingerprint_inputs: + optional method to control when the node is re executed. + check_lazy_status: + optional method to control list of input names that need to be evaluated. + + """ + + @classmethod + def define_schema(cls) -> io.Schema: + """ + Return a schema which contains all information about the node. + Some types: "Model", "Vae", "Clip", "Conditioning", "Latent", "Image", "Int", "String", "Float", "Combo". + For outputs the "io.Model.Output" should be used, for inputs the "io.Model.Input" can be used. + The type can be a "Combo" - this will be a list for selection. + """ + return io.Schema( + node_id="Example", + display_name="Example Node", + category="Example", + inputs=[ + io.Image.Input("image"), + io.Int.Input( + "int_field", + min=0, + max=4096, + step=64, # Slider's step + display_mode=io.NumberDisplay.number, # Cosmetic only: display as "number" or "slider" + lazy=True, # Will only be evaluated if check_lazy_status requires it + ), + io.Float.Input( + "float_field", + default=1.0, + min=0.0, + max=10.0, + step=0.01, + round=0.001, #The value representing the precision to round to, will be set to the step value by default. Can be set to False to disable rounding. + display_mode=io.NumberDisplay.number, + lazy=True, + ), + io.Combo.Input("print_to_screen", options=["enable", "disable"]), + io.String.Input( + "string_field", + multiline=False, # True if you want the field to look like the one on the ClipTextEncode node + default="Hello world!", + lazy=True, + ) + ], + outputs=[ + io.Image.Output(), + ], + ) + + @classmethod + def check_lazy_status(cls, image, string_field, int_field, float_field, print_to_screen): + """ + Return a list of input names that need to be evaluated. + + This function will be called if there are any lazy inputs which have not yet been + evaluated. As long as you return at least one field which has not yet been evaluated + (and more exist), this function will be called again once the value of the requested + field is available. + + Any evaluated inputs will be passed as arguments to this function. Any unevaluated + inputs will have the value None. + """ + if print_to_screen == "enable": + return ["int_field", "float_field", "string_field"] + else: + return [] + + @classmethod + def execute(cls, image, string_field, int_field, float_field, print_to_screen) -> io.NodeOutput: + if print_to_screen == "enable": + print(f"""Your input contains: + string_field aka input text: {string_field} + int_field: {int_field} + float_field: {float_field} + """) + #do some processing on the image, in this example I just invert it + image = 1.0 - image + return io.NodeOutput(image) + + """ + The node will always be re executed if any of the inputs change but + this method can be used to force the node to execute again even when the inputs don't change. + You can make this node return a number or a string. This value will be compared to the one returned the last time the node was + executed, if it is different the node will be executed again. + This method is used in the core repo for the LoadImage node where they return the image hash as a string, if the image hash + changes between executions the LoadImage node is executed again. + """ + #@classmethod + #def fingerprint_inputs(s, image, string_field, int_field, float_field, print_to_screen): + # return "" + +# Set the web directory, any .js file in that directory will be loaded by the frontend as a frontend extension +# WEB_DIRECTORY = "./somejs" + + +# Add custom API routes, using router +from aiohttp import web +from server import PromptServer + +@PromptServer.instance.routes.get("/hello") +async def get_hello(request): + return web.json_response("hello") + + +class ExampleExtension(ComfyExtension): + @override + async def get_node_list(self) -> list[type[io.ComfyNode]]: + return [ + Example, + ] + + +async def comfy_entrypoint() -> ExampleExtension: # ComfyUI calls this to load your extension and its nodes. + return ExampleExtension() diff --git a/websocket_image_save.py b/websocket_image_save.py new file mode 100644 index 0000000000000000000000000000000000000000..ca56ebc8d26af278e49c506062cd3abc313ba170 --- /dev/null +++ b/websocket_image_save.py @@ -0,0 +1,44 @@ +from PIL import Image +import numpy as np +import comfy.utils +import time + +#You can use this node to save full size images through the websocket, the +#images will be sent in exactly the same format as the image previews: as +#binary images on the websocket with a 8 byte header indicating the type +#of binary message (first 4 bytes) and the image format (next 4 bytes). + +#Note that no metadata will be put in the images saved with this node. + +class SaveImageWebsocket: + @classmethod + def INPUT_TYPES(s): + return {"required": + {"images": ("IMAGE", ),} + } + + RETURN_TYPES = () + FUNCTION = "save_images" + + OUTPUT_NODE = True + + CATEGORY = "api/image" + + def save_images(self, images): + pbar = comfy.utils.ProgressBar(images.shape[0]) + step = 0 + for image in images: + i = 255. * image.cpu().numpy() + img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8)) + pbar.update_absolute(step, images.shape[0], ("PNG", img, None)) + step += 1 + + return {} + + @classmethod + def IS_CHANGED(s, images): + return time.time() + +NODE_CLASS_MAPPINGS = { + "SaveImageWebsocket": SaveImageWebsocket, +}