diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..3fb53c58cf3cd40f34c72b6ceddc690f103decaa --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +__pycache__/ +*.py[cod] +.pytest_cache/ +.coverage +.venv/ +.env +local/ + +_vendor/ +custom_nodes/ +models/ +input/ +output/ +ComfyUI_temp/ + +*.log +.DS_Store diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f288702d2fa16d3cdf0035b15a9fcbc552cd88e7 --- /dev/null +++ b/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/NOTICE.md b/NOTICE.md new file mode 100644 index 0000000000000000000000000000000000000000..e803404326599ce4780f358ff6507ec3740555e5 --- /dev/null +++ b/NOTICE.md @@ -0,0 +1,24 @@ +# 来源与修改声明 + +本仓库是下列 GPL-3.0 项目的修改与整合版本: + +- RioShiina/ImageGen,核对版本:`3622e14a8b6587699eb3e0616c167d0c35649ca7` +- Dekonstruktio/Fluxus,核对版本:`4aaca1f35ace66be1fb73de9bc46d390501f4ef6` +- 两者共同祖先:`9dbb7e3b34150ab09eaa0b83b92c7ea7e0493860` + +Fluxus 在共同祖先之后只改动 README、MCP 启用开关和界面品牌文案,未形成独立推理引擎。本修改版因此以 ImageGen 为主干,并保留 Fluxus 的 MCP 关闭选项以及 `run_imagegen`、`get_chain_schema` 兼容接口。 + +主要修改包括: + +- 将五套重复 Gradio 页面重构为一个动态工作台; +- 新增中文界面、任务说明、模型语言提示与快捷模型方案; +- 调整模型切换语义,避免覆盖用户 Prompt; +- 为 UI、Gradio API 与 MCP 增加共享的有界 GPU 调度; +- 将 MCP 裸线程改为有界执行器,并为任务表增加锁和容量限制; +- 将临时文件改为 UUID,并为下载和共享目录写入增加进程锁; +- 固定 ComfyUI/custom nodes commit,并与应用源码隔离; +- 避免重复执行 ComfyUI SaveImage; +- 增加输入/输出像素、批量和 URL 图片约束; +- 增加测试、中文部署文档和 Fluxus 接口兼容层。 + +本仓库保留原始 `LICENSE`,整体按 GPL-3.0 分发。这里列出的模型仅在运行时按需下载,其许可证与使用限制由各模型作者决定。ComfyUI、custom nodes、SageAttention 及其他第三方依赖也继续适用各自许可证;本声明不改变这些许可。 diff --git a/README.md b/README.md index 0e22e6fab223a65f914ca567586dbe6a209e366f..0eca65ef44ed89ffd061078599e4019250d8b8fc 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,343 @@ --- -title: ImageGen Studio -emoji: 📊 -colorFrom: pink -colorTo: blue +title: ImageGen Studio 中文版 +emoji: 🖼 +colorFrom: indigo +colorTo: purple sdk: gradio -sdk_version: 6.23.1 -python_version: '3.12' +sdk_version: "5.50.0" app_file: app.py -pinned: false +python_version: "3.12.12" +startup_duration_timeout: 1h +short_description: 中文优先的多任务图片生成与编辑工作台 +license: gpl-3.0 +pinned: true +models: +# This Space supports a wide variety of image generation pipelines. To maintain transparency, credit the original creators, and help users explore the Hugging Face ecosystem, we list and link several types of models in our metadata: +# 1. **Directly Run Models:** Models and checkpoints actively loaded by our pipelines (configured via `yaml/file_list.yaml`). +# 2. **Upstream Base Models:** The original foundation architectures from which our optimized ports, quantized versions, or wrappers are derived. + # Directly Run Models + - AiAF/Illustrious-XL-v0.1.safetensors + - alibaba-pai/Z-Image-Turbo-Fun-Controlnet-Union-2.1 + - black-forest-labs/FLUX.1-Redux-dev + - black-forest-labs/FLUX.2-dev-NVFP4 + - black-forest-labs/FLUX.2-klein-4b-nvfp4 + - black-forest-labs/FLUX.2-klein-9b-nvfp4 + - black-forest-labs/FLUX.2-klein-9b-kv-fp8 + - black-forest-labs/FLUX.2-klein-base-4b-nvfp4 + - black-forest-labs/FLUX.2-klein-base-9b-nvfp4 + - bluepen5805/4nima_pencil-XL + - bluepen5805/anima-models + - bluepen5805/anima_pencil-XL + - bluepen5805/blue_pencil-XL + - bluepen5805/illustrious_pencil-XL + - bluepen5805/mellow_pencil-XL + - bluepen5805/noob_v_pencil-XL + - bluepen5805/pony_pencil-XL + - cagliostrolab/animagine-xl-3.1 + - cagliostrolab/animagine-xl-4.0 + - ChenkinNoob/ChenkinNoob-XL-V0.5 + - circlestone-labs/Anima + - Clybius/Chroma-fp8-scaled + - comfyanonymous/ControlNet-v1-1_fp16_safetensors + - comfyanonymous/cosmos_1.0_text_encoder_and_VAE_ComfyUI + - comfyanonymous/flux_text_encoders + - Comfy-Org/Anima-LLLite + - Comfy-Org/Boogu-Image + - Comfy-Org/ERNIE-Image + - Comfy-Org/FLUX.1-Krea-dev_ComfyUI + - Comfy-Org/flux2-dev + - Comfy-Org/HiDream-I1_ComfyUI + - Comfy-Org/HiDream-O1-Image + - Comfy-Org/HunyuanImage_2.1_ComfyUI + - Comfy-Org/Ideogram-4 + - Comfy-Org/Krea-2 + - Comfy-Org/Lens + - Comfy-Org/LongCat-Image + - Comfy-Org/Lumina_Image_2.0_Repackaged + - Comfy-Org/Mage-Flow + - Comfy-Org/NewBie-image-Exp0.1_repackaged + - Comfy-Org/Omnigen2_ComfyUI_repackaged + - Comfy-Org/Ovis-Image + - Comfy-Org/PixelDiT + - Comfy-Org/Qwen-Image_ComfyUI + - Comfy-Org/Qwen-Image-Edit_ComfyUI + - Comfy-Org/sigclip_vision_384 + - Comfy-Org/stable-diffusion-3.5-fp8 + - Comfy-Org/vae-text-encorder-for-flux-klein-4b + - Comfy-Org/vae-text-encorder-for-flux-klein-9b + - Comfy-Org/Wan_2.1_ComfyUI_repackaged + - Comfy-Org/z_image + - Comfy-Org/z_image_turbo + - conradlocke/krea2-identity-edit + - cyberdelia/CyberRealisticPony + - diffusionmodels1254ani/hassakuAnima + - diffusionmodels1254ani/kirazuriAnima_v30AnimaBase1 + - diffusionmodels1254ani/waiANIMA + - duongve/AnimaYume + - Eugeoter/noob-sdxl-controlnet-canny + - Eugeoter/noob-sdxl-controlnet-depth + - Eugeoter/noob-sdxl-controlnet-lineart_anime + - Eugeoter/noob-sdxl-controlnet-lineart_realistic + - Eugeoter/noob-sdxl-controlnet-manga_line + - Eugeoter/noob-sdxl-controlnet-normal + - Eugeoter/noob-sdxl-controlnet-softedge_hed + - Eugeoter/noob-sdxl-controlnet-tile + - fal/AuraFlow-v0.3 + - frankjoshua/novaAnimeXL_ilV180 + - h94/IP-Adapter + - h94/IP-Adapter-FaceID + - InstantX/FLUX.1-dev-IP-Adapter + - InstantX/Qwen-Image-ControlNet-Inpainting + - InstantX/Qwen-Image-ControlNet-Union + - InstantX/SD3.5-Large-IP-Adapter + - jdopensource/JoyAI-Image-Edit-ComfyUI + - jdopensource/JoyAI-Image-Edit-Plus-ComfyUI + - kandinskylab/Kandinsky-5.0-T2I-Lite + - Kijai/flux-fp8 + - Laxhar/noob_openpose + - Laxhar/noobai-XL-1.1 + - Laxhar/noobai-XL-Vpred-1.0 + - licyk/sd_control_collection + - lightx2v/Qwen-Image-2512-Lightning + - lightx2v/Qwen-Image-Edit-2511-Lightning + - LyliaEngine/Pony_Diffusion_V6_XL + - MIC-Lab/illustriousXLv0.1_controlnet + - MIC-Lab/illustriousXLv1.1_controlnet + - misri/hassakuXLIllustrious_v30 + - nvidia/Cosmos-Predict2-2B-Text2Image + - nvidia/Cosmos-Predict2-14B-Text2Image + - OnomaAIResearch/Illustrious-XL-v1.0 + - OnomaAIResearch/Illustrious-XL-v1.1 + - OnomaAIResearch/Illustrious-XL-v2.0 + - ostris/krea2_turbo_style_reference + - Patil/Krea-2-depth-controlnet + - RedRayz/hikari_noob_v-pred_1.2.4 + - Shakker-Labs/FLUX.1-dev-ControlNet-Union-Pro-2.0 + - silveroxides/Chroma1-Radiance-fp8-scaled + - stabilityai/sdxl-turbo + - stabilityai/stable-diffusion-3.5-controlnets + - stabilityai/stable-diffusion-xl-base-1.0 + - stable-diffusion-v1-5/stable-diffusion-v1-5 + - tsukiyomi/krea2_raw-nvfp4 + - Wenaka/NoobAI_XL_Inpainting_ControlNet_Full + - xinsir/anime-painter + - xinsir/controlnet-canny-sdxl-1.0 + - xinsir/controlnet-depth-sdxl-1.0 + - xinsir/controlnet-openpose-sdxl-1.0 + - xinsir/controlnet-scribble-sdxl-1.0 + - xinsir/controlnet-tile-sdxl-1.0 + - xinsir/controlnet-union-sdxl-1.0 + - XLabs-AI/flux-controlnet-collections + - zhenshipo/waiIllustriousSDXL_v170 + # Upstream Base Models + - AIDC-AI/Ovis-Image-7B + - Alpha-VLLM/Lumina-Image-2.0 + - baidu/ERNIE-Image + - baidu/ERNIE-Image-Turbo + - black-forest-labs/FLUX.1-dev + - black-forest-labs/FLUX.1-Krea-dev + - black-forest-labs/FLUX.1-schnell + - Boogu/Boogu-Image-0.1-Turbo + - Boogu/Boogu-Image-0.1-Base + - Boogu/Boogu-Image-0.1-Edit + - Boogu/Boogu-Image-0.1-Edit-Turbo + - HiDream-ai/HiDream-I1-Dev + - HiDream-ai/HiDream-I1-Fast + - HiDream-ai/HiDream-I1-Full + - HiDream-ai/HiDream-O1-Image + - HiDream-ai/HiDream-O1-Image-Dev + - ideogram-ai/ideogram-4-fp8 + - kohya-ss/Anima-LLLite + - krea/Krea-2-Raw + - krea/Krea-2-Turbo + - lodestones/Chroma1-HD + - lodestones/Chroma1-Radiance + - mage-flow-community/Mage-Flow + - mage-flow-community/Mage-Flow-Base + - mage-flow-community/Mage-Flow-Edit + - mage-flow-community/Mage-Flow-Edit-Base + - mage-flow-community/Mage-Flow-Edit-Turbo + - mage-flow-community/Mage-Flow-Turbo + - meituan-longcat/LongCat-Image + - microsoft/Lens + - microsoft/Lens-Turbo + - NewBie-AI/NewBie-image-Exp0.1 + - nvidia/PiD + - nvidia/PixelDiT-1300M-1024px + - OmniGen2/OmniGen2 + - Qwen/Qwen-Image + - Qwen/Qwen-Image-2512 + - Qwen/Qwen-Image-Edit + - Qwen/Qwen-Image-Edit-2509 + - Qwen/Qwen-Image-Edit-2511 + - stabilityai/stable-diffusion-3.5-large + - stabilityai/stable-diffusion-3.5-medium + - tencent/HunyuanImage-2.1 + - Tongyi-MAI/Z-Image + - Tongyi-MAI/Z-Image-Turbo --- -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +# ImageGen Studio 中文版 + +这是 [RioShiina/ImageGen](https://huggingface.co/spaces/RioShiina/ImageGen) 与 [Dekonstruktio/Fluxus](https://huggingface.co/spaces/Dekonstruktio/Fluxus) 的整合重构版,保留 YAML 配方、动态工作流和 92 个模型目录,重做任务切换、并发调度、中文指导与移动端体验。 + +Fluxus 与 ImageGen 共享同一 Git 历史,Fluxus 当前版本只调整了品牌文案和 MCP 开关,没有第二套推理核心。因此本项目使用一个 ImageGen 引擎,并兼容两边的 API 契约,避免双后端、双状态和重复下载。 + +## 主要改进 + +| 项目 | 原版 | 本整合版 | +|---|---|---| +| 任务界面 | 5 个完整 Tab,重复创建全部高级控件 | 1 个共享工作台,动态切换 5 类任务 | +| 任务切换 | 模型、Prompt 和素材分散在各 Tab | 保留模型、Prompt、参数与上传素材 | +| 模型切换 | 会覆盖正负 Prompt 和推荐参数 | 保留用户 Prompt;推荐采样参数可自动跟随、关闭或一键恢复 | +| 复杂度 | 约 4,033 组件 / 506 事件 | 烟测为 881 组件 / 120 事件 | +| GPU 并发 | UI 与 MCP 可绕过彼此并发执行 | 各入口有界,最终汇合到公平的单 GPU 闸门 | +| 异步 MCP | 每次请求创建无上限 daemon 线程 | 有界线程池、队列满错误、任务表上限与锁 | +| 临时文件 | 4 位随机后缀,可能碰撞 | UUID 文件名 | +| 启动依赖 | 运行时拉取最新版并覆盖项目根 | 固定 commit,隔离在 `_vendor/ComfyUI` | +| 中文体验 | 英文界面,无模型语言提示 | 中文任务指导、模型用途说明、可操作错误信息 | +| MCP 兼容 | ImageGen 与 Fluxus 接口名不同 | 同时保留新版接口与两个 Fluxus 旧别名 | + +## 支持能力 + +- 任务:文生图、图生图、局部重绘、扩图、高清修复。 +- 模型:由 `yaml/model_list.yaml` 驱动,当前包含 30 类架构、92 个显示模型。 +- 扩展:LoRA、ControlNet、IP-Adapter、Embedding、区域提示、多图编辑、VAE、PiD 等。 +- 输出:PNG 内写入生成参数和完整 ComfyUI 工作流元数据。 +- 中文 Prompt:默认原样传递,不做隐式翻译;模型说明会区分中文自然语言和英文标签型模型。 + +## 批量、多图与模型 PK + +这些能力只增加一个有上限的顺序编排层,不创建第二套推理引擎,也不会让多个大模型同时占用显存: + +| 运行方式 | 输入语义 | 输出语义 | +|---|---|---| +| 普通生成 | 当前任务的一组输入 | 1–4 张同组变体 | +| 模型 PK | 同一 Prompt、尺寸、源图与已解析 Seed | 每个模型分别生成;默认最多 2 个模型 | +| 多图独立 | A、B、C 是互不相关的源图 | A→A′、B→B′、C→C′ | +| 多图 × 多模型 | 多张独立源图和两个模型 | 按模型分组顺序执行图片×模型组合 | +| 多图融合 | 多张图共同作为一组参考 | 由兼容的编辑模型融合为 1–4 张结果 | + +- 多图独立目前支持图生图、扩图和高清修复;局部重绘需要逐张图片配对蒙版,暂不做批量。 +- 多图融合内部固定走“文生图 + 模型专属参考链”,不会与图生图 base latent 混用。Prompt 可按“参考图 1 / 2 / 3”说明各图角色。 +- 多图融合是生成式参考,不保证无损拼接、角色逐像素保留或确定性元素替换。 +- PK 默认采用各模型推荐采样参数;关闭后才严格复用当前步数、CFG、采样器和调度器。同一 Seed 在不同架构之间只是尽量控制变量,不表示初始噪声数学等价。 +- PK V1 会关闭 LoRA、ControlNet、IP-Adapter、参考链、自定义 VAE 和 PiD,只比较所有基础 checkpoint 都具备的 Prompt / 源图能力,避免某个模型偷偷多一层条件。 +- 单进程始终一次只执行一个 GPU 任务。模型文件按需缓存在磁盘;只在 PK 的实际模型边界和 GPU 异常后释放 ComfyUI 模型状态。 +- 默认上限为 2 个 PK 模型、4 张输入图、4 个顺序任务、8 张预计输出。某一组合失败时保留已成功结果;取消会停止尚未开始的后续组合。 + +## 部署到 Hugging Face Space + +1. 新建 Gradio Space,硬件选择 ZeroGPU;README metadata 已固定 Python 3.12.12,并把冷启动上限设为 1 小时。 +2. 上传本仓库内容;Space 会按 `requirements.txt` 安装 Gradio 5.50 和 MCP 额外依赖。 +3. 按需要设置 Secret: + - `HF_TOKEN`:访问 gated/private Hugging Face 模型。 + - `CIVITAI_API_KEY`:下载需要授权的 Civitai 资源。 +4. 首次启动会按 `vendor.lock.yaml` 拉取固定版本的 ComfyUI 与 5 个 custom nodes;首次使用某个模型时才下载其权重。 + +部署边界: + +- 模型目录包含 92 个可选项,但这不等于 92 个模型可同时驻留。ZeroGPU 应使用按需磁盘缓存 + 单模型顺序执行。 +- Space 默认磁盘是临时盘,重启/重建后缓存可能消失。若需要长期保留模型,可把 Hugging Face Storage Bucket 挂载到 `/home/user/app/models`,并设置 `HF_HOME=/home/user/app/models/.hf-cache`,让权重实体和项目符号链接位于同一持久卷。 +- 下载前会读取远端文件大小并保留默认 3 GB 安全余量;空间不足时会在下载前拒绝,而不是写满磁盘。项目不自动删除 Hub cache,避免误删仍被符号链接引用的模型。 +- FLUX、SD3.5、Cosmos 等部分资源可能受访问条款限制。`HF_TOKEN` 所属账号必须先在对应模型页接受条款。 +- 公共 Space 建议精选 4–8 个常用模型,并设置 `IMAGEGEN_MAX_BATCH_SIZE=2`;完整 92 模型目录更适合挂载持久存储的专用部署。 +- ZeroGPU 单次 GPU 申请上限为 120 秒。大模型首次装载、超高分辨率或长采样仍可能超时;PK 会为每个模型分别申请 GPU,而不是占用一个超长租约。 + +完整的适配状态、推荐变量与上线实测清单见 [`docs/HF_SPACE_DEPLOYMENT.md`](docs/HF_SPACE_DEPLOYMENT.md)。 + +默认启动命令由 Space metadata 执行: + +```bash +python app.py +``` + +## 本地运行 + +需要 Python 3.12、Git,以及与目标模型相匹配的 NVIDIA GPU 环境: + +```bash +python -m venv .venv +source .venv/bin/activate +pip install -r requirements.txt +python app.py +``` + +如已有 ComfyUI,可避免再次克隆: + +```bash +COMFYUI_PATH=/absolute/path/to/ComfyUI python app.py +``` + +## 运行参数 + +| 环境变量 | 默认值 | 说明 | +|---|---:|---| +| `IMAGEGEN_GPU_CONCURRENCY` | 固定 `1` | 为兼容旧部署保留名称;单进程始终串行,扩容请增加独立副本 | +| `IMAGEGEN_QUEUE_MAX_SIZE` | `24` | Gradio 等待队列上限 | +| `IMAGEGEN_MCP_MAX_PENDING` | `16` | MCP 后台任务上限 | +| `IMAGEGEN_MCP_TASK_RETENTION` | `200` | 内存任务记录上限 | +| `IMAGEGEN_MAX_BATCH_SIZE` | `4` | 单次最大图片数 | +| `IMAGEGEN_MAX_PK_MODELS` | `2` | PK 模型总数上限(含当前模型) | +| `IMAGEGEN_MAX_MULTI_IMAGES` | `4` | 批量输入/参考图的全局上传上限 | +| `IMAGEGEN_MAX_PLAN_JOBS` | `4` | 一次提交可展开的顺序任务上限 | +| `IMAGEGEN_MAX_PLAN_OUTPUTS` | `8` | 一次提交的预计输出总数上限 | +| `IMAGEGEN_MAX_INPUT_MEGAPIXELS` | `4.2` | 输入图片/文生图画布上限 | +| `IMAGEGEN_MAX_REFERENCE_MEGAPIXELS` | `12` | 一组上传图片的累计像素上限 | +| `IMAGEGEN_MAX_REFERENCE_IMAGES` | `10` | 一次任务中全部参考图/控制图的合计上限 | +| `IMAGEGEN_MAX_OUTPUT_MEGAPIXELS` | `16` | 扩图和高清修复预计输出上限 | +| `IMAGEGEN_MIN_FREE_DISK_GB` | `3` | 模型下载后必须保留的磁盘余量 | +| `IMAGEGEN_OUTPUT_RETENTION` | `80` | 本地保留的生成 PNG 数量 | +| `IMAGEGEN_ENABLE_MCP` | `true` | 是否启动 MCP;设为 `false` 即采用 Fluxus 的关闭方式 | +| `IMAGEGEN_STARTUP_GPU_PROBE` | `false` | 是否在启动时申请一次 GPU | +| `IMAGEGEN_USE_SAGE_ATTENTION` | `auto` | `auto` / `true` / `false` | +| `IMAGEGEN_SKIP_CUSTOM_NODES` | `false` | 本地调试时跳过 custom nodes 拉取 | +| `IMAGEGEN_GIT_TIMEOUT_SECONDS` | `180` | 单次 Git clone/fetch 超时 | +| `IMAGEGEN_GIT_ATTEMPTS` | `2` | Git 网络操作尝试次数 | + +## MCP / Gradio API + +公开 7 个主接口: + +- `get_task_list` +- `get_model_architecture_list` +- `get_model_list` +- `get_feature_list` +- `get_model_features` +- `run` +- `get_task_status` + +同时保留 Fluxus 客户端兼容别名: + +- `run_imagegen(json_params)` → `run(json_params)` +- `get_chain_schema(chain_type)` → 返回单个扩展能力的完整 schema + +`get_feature_list()` 空参默认返回 Fluxus 兼容的完整 schema;如需节省 MCP token,传 `compact=true` 获取摘要。也可以传 `feature_name`,或使用 `get_chain_schema(chain_type)` 查询单项完整 schema。 + +所有 UI 原子事件均隐藏,不作为公共 API 暴露。 + +## 验证 + +```bash +python -m compileall -q . +python -m unittest discover -s tests -v +``` + +界面烟测会以 stub ComfyUI 构建完整 Gradio 配置,因此不需要下载模型或占用 GPU。 + +## 目录 + +```text +app.py # Space 入口与有界 Gradio 队列 +core/ # 生成管线、工作流装配、统一调度 +ui/shared/studio_ui.py # 单一动态工作台 +ui/events/ # 切换、模型、扩展与生成事件 +mcp_tools/ # 高层 API、兼容别名、任务状态 +yaml/ # 模型、能力、默认参数与配方注册表 +vendor.lock.yaml # ComfyUI / custom nodes 固定版本 +tests/ # 并发、注册表、MCP 与 UI 烟测 +``` + +## 许可与来源 + +本项目是 ImageGen 的修改版,整体继续采用 GPL-3.0,并保留上游署名。Fluxus 也是同一 GPL-3.0 代码谱系。模型权重、ComfyUI 与 custom nodes 各自受其上游许可证约束;本仓库不重新分发模型权重。具体版本与修改声明见 `NOTICE.md`。 diff --git a/app.py b/app.py new file mode 100644 index 0000000000000000000000000000000000000000..64032baba9cdce53d7324361b9ee4553c4ddf4f4 --- /dev/null +++ b/app.py @@ -0,0 +1,127 @@ +import spaces +import importlib.util +import os +import sys +import site + +from core.runtime_config import CONFIG + +sage_mode = os.getenv("IMAGEGEN_USE_SAGE_ATTENTION", "auto").strip().lower() +sage_available = importlib.util.find_spec("sageattention") is not None +use_sage_attention = sage_mode in {"1", "true", "yes", "on"} or ( + sage_mode == "auto" and sage_available +) +if use_sage_attention and "--use-sage-attention" not in sys.argv: + sys.argv.append("--use-sage-attention") + print("🚀 [SageAttention] Injected '--use-sage-attention' into sys.argv.") + +APP_DIR = os.path.dirname(os.path.abspath(__file__)) +if APP_DIR not in sys.path: + sys.path.insert(0, APP_DIR) + print(f"✅ Added project root '{APP_DIR}' to sys.path.") + +# Keep ComfyUI code isolated while pointing its model/input/output directories +# at this Space. These arguments are consumed when ComfyUI is imported. +if "--base-directory" not in sys.argv: + sys.argv.extend(["--base-directory", APP_DIR]) + +SAGE_PATCH_APPLIED = False + +def apply_sage_attention_patch(): + global SAGE_PATCH_APPLIED + if SAGE_PATCH_APPLIED: + return "SageAttention patch already applied." + if not use_sage_attention: + return "SageAttention disabled or unavailable; using the default attention backend." + + try: + from comfy import model_management + import sageattention + + print("--- [Runtime Patch] sageattention package found. Applying patch... ---") + model_management.sage_attention_enabled = lambda: True + model_management.pytorch_attention_enabled = lambda: False + + SAGE_PATCH_APPLIED = True + return "✅ Successfully enabled SageAttention." + except ImportError: + SAGE_PATCH_APPLIED = False + msg = "--- [Runtime Patch] ⚠️ sageattention package not found. Continuing with default attention. ---" + print(msg) + return msg + except Exception as e: + SAGE_PATCH_APPLIED = False + msg = f"--- [Runtime Patch] ❌ An error occurred while applying SageAttention patch: {e} ---" + print(msg) + return msg + +@spaces.GPU +def dummy_gpu_for_startup(): + print("--- [GPU Startup] Dummy function for startup check initiated. ---") + patch_result = apply_sage_attention_patch() + print(f"--- [GPU Startup] {patch_result} ---") + print("--- [GPU Startup] Startup check passed. ---") + return "Startup check passed." + + +def main(): + os.chdir(APP_DIR) + from comfy_integration import setup as setup_comfyui + from imagegen_utils.app_utils import load_ipadapter_presets + + print("--- [Setup] Starting ComfyUI initialization ---") + setup_comfyui.initialize_comfyui() + + print("--- [Setup] Applying SageAttention Runtime Patch ---") + patch_result = apply_sage_attention_patch() + print(f"--- [Setup] {patch_result} ---") + + print("--- [Setup] Reloading site-packages to detect newly installed packages... ---") + try: + site.main() + print("--- [Setup] ✅ Site-packages reloaded. ---") + except Exception as e: + print(f"--- [Setup] ⚠️ Warning: Could not fully reload site-packages: {e} ---") + + if CONFIG.enable_startup_gpu_probe: + print("--- Initiating optional GPU startup check ---") + try: + dummy_gpu_for_startup() + except BaseException as e: + err_msg = f"{type(e).__name__}: {str(e)}" + print(f"--- [GPU Startup] ⚠️ Warning: Startup check failed: {err_msg} ---") + + print("--- Starting Application Setup ---") + + print("--- Loading IPAdapter presets ---") + load_ipadapter_presets() + print("--- ✅ IPAdapter setup complete. ---") + + + print("--- Environment configured. Proceeding with module imports. ---") + from ui.layout import build_ui + from ui.events import attach_event_handlers + if CONFIG.enable_mcp: + import mcp_tools as mcp + print(f"✅ Loaded MCP module with tools: {[fn.__name__ for fn in mcp.MCP_FUNCTIONS]}") + else: + print("ℹ️ MCP is disabled by IMAGEGEN_ENABLE_MCP.") + + print(f"✅ Working directory is stable: {os.getcwd()}") + + demo = build_ui(attach_event_handlers) + + print( + "--- Launching Gradio Interface " + f"(GPU concurrency={CONFIG.gpu_concurrency}, queue={CONFIG.queue_max_size}, " + f"MCP={CONFIG.enable_mcp}) ---" + ) + demo.queue( + default_concurrency_limit=1, + max_size=CONFIG.queue_max_size, + status_update_rate="auto", + ).launch(mcp_server=CONFIG.enable_mcp) + + +if __name__ == "__main__": + main() diff --git a/chain_injectors/__init__.py b/chain_injectors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6514f96ab93b51be461d98c9af78049f4d7225f7 --- /dev/null +++ b/chain_injectors/__init__.py @@ -0,0 +1,50 @@ +import os +import importlib +import pkgutil + +def discover_injectors(): + injectors = {} + package_dir = os.path.dirname(__file__) + + for _, module_name, is_pkg in pkgutil.iter_modules([package_dir]): + if is_pkg or module_name.startswith('_'): + continue + + full_module_name = f"chain_injectors.{module_name}" + try: + module = importlib.import_module(full_module_name) + if hasattr(module, 'inject') and callable(module.inject): + feature_name = getattr(module, 'FEATURE_NAME', None) + if not feature_name: + feature_name = module_name[:-9] if module_name.endswith('_injector') else module_name + + chain_type = getattr(module, 'CHAIN_TYPE', None) + if not chain_type: + chain_type = f"dynamic_{feature_name}_chains" + + injectors[chain_type] = module.inject + else: + print(f"Warning: Module '{full_module_name}' does not have a callable 'inject' function.") + except Exception as e: + print(f"Error importing injector module '{full_module_name}': {e}") + + return injectors + +def get_registered_features(): + features = {} + package_dir = os.path.dirname(__file__) + + for _, module_name, is_pkg in pkgutil.iter_modules([package_dir]): + if is_pkg or module_name.startswith('_'): + continue + + feature_name = module_name[:-9] if module_name.endswith('_injector') else module_name + full_module_name = f"chain_injectors.{module_name}" + chain_type = f"dynamic_{feature_name}_chains" + + features[feature_name] = { + 'module': full_module_name, + 'chain_type': chain_type + } + + return features diff --git a/chain_injectors/anima_controlnet_lllite_injector.py b/chain_injectors/anima_controlnet_lllite_injector.py new file mode 100644 index 0000000000000000000000000000000000000000..002e9d732d74b9c31400a8b6712a4048065f59e5 --- /dev/null +++ b/chain_injectors/anima_controlnet_lllite_injector.py @@ -0,0 +1,53 @@ +def inject(assembler, chain_definition, chain_items): + if not chain_items: + return + + ksampler_name = chain_definition.get('ksampler_node', 'ksampler') + if ksampler_name not in assembler.node_map: + print(f"Warning: KSampler node '{ksampler_name}' not found for Anima LLLite chain. Skipping.") + return + + ksampler_id = assembler.node_map[ksampler_name] + + if 'model' not in assembler.workflow[ksampler_id]['inputs']: + print(f"Warning: KSampler node '{ksampler_name}' is missing 'model' input. Skipping.") + return + + current_model_connection = assembler.workflow[ksampler_id]['inputs']['model'] + + for item_data in chain_items: + image_loader_id = assembler._get_unique_id() + image_loader_node = assembler._get_node_template("LoadImage") + image_loader_node['inputs']['image'] = item_data['image'] + assembler.workflow[image_loader_id] = image_loader_node + + image_scaler_id = assembler._get_unique_id() + image_scaler_node = assembler._get_node_template("ImageScaleToTotalPixels") + image_scaler_node['inputs']['image'] = [image_loader_id, 0] + image_scaler_node['inputs']['upscale_method'] = 'nearest-exact' + image_scaler_node['inputs']['megapixels'] = 1.0 + assembler.workflow[image_scaler_id] = image_scaler_node + + patch_loader_id = assembler._get_unique_id() + patch_loader_node = assembler._get_node_template("ModelPatchLoader") + patch_loader_node['inputs']['name'] = item_data['control_net_name'] + assembler.workflow[patch_loader_id] = patch_loader_node + + apply_cn_id = assembler._get_unique_id() + apply_cn_node = assembler._get_node_template("AnimaLLLiteApply") + + apply_cn_node['inputs']['strength'] = item_data['strength'] + apply_cn_node['inputs']['start_percent'] = item_data.get('start_percent', 0.0) + apply_cn_node['inputs']['end_percent'] = item_data.get('end_percent', 1.0) + + apply_cn_node['inputs']['model'] = current_model_connection + apply_cn_node['inputs']['model_patch'] = [patch_loader_id, 0] + apply_cn_node['inputs']['image'] = [image_scaler_id, 0] + + assembler.workflow[apply_cn_id] = apply_cn_node + + current_model_connection = [apply_cn_id, 0] + + assembler.workflow[ksampler_id]['inputs']['model'] = current_model_connection + + print(f"Anima LLLite injector applied. KSampler model input re-routed through {len(chain_items)} LLLite(s).") diff --git a/chain_injectors/boogu_image_edit_injector.py b/chain_injectors/boogu_image_edit_injector.py new file mode 100644 index 0000000000000000000000000000000000000000..4725ed3179b0bff0b05e521f13059decd0da5aa0 --- /dev/null +++ b/chain_injectors/boogu_image_edit_injector.py @@ -0,0 +1,73 @@ +def create_node(assembler, class_type, title): + try: + node = assembler._get_node_template(class_type) + except Exception: + node = { + "inputs": {}, + "class_type": class_type, + "_meta": {"title": title} + } + node['_meta']['title'] = title + return node + +def inject(assembler, chain_definition, chain_items): + if not chain_items: + return + + valid_images = [] + for item in chain_items: + if not item: + continue + img_path = item + if isinstance(item, dict): + img_path = item.get('image') or item.get('filename') or item.get('path') + if img_path: + valid_images.append(img_path) + + if not valid_images: + return + + valid_images = valid_images[:10] + + boogu_prompt_name = chain_definition.get('boogu_prompt_node', 'boogu_prompt') + vae_loader_name = chain_definition.get('vae_loader_node', 'vae_loader') + + boogu_prompt_id = assembler.node_map.get(boogu_prompt_name) + if not boogu_prompt_id or boogu_prompt_id not in assembler.workflow: + for node_id, node in assembler.workflow.items(): + if isinstance(node, dict) and node.get('class_type') == 'TextEncodeBooguEdit': + boogu_prompt_id = node_id + break + + if not boogu_prompt_id: + print(f"Warning: Target node '{boogu_prompt_name}' (TextEncodeBooguEdit) for Boogu Edit chain not found. Skipping.") + return + + vae_id = assembler.node_map.get(vae_loader_name) + if not vae_id: + for node_id, node in assembler.workflow.items(): + if isinstance(node, dict) and node.get('class_type') == 'VAELoader': + vae_id = node_id + break + + if vae_id: + assembler.workflow[boogu_prompt_id]['inputs']['vae'] = [vae_id, 0] + + for i, img_filename in enumerate(valid_images): + load_id = assembler._get_unique_id() + load_node = create_node(assembler, "LoadImage", f"Load Reference Image {i+1}") + load_node['inputs']['image'] = img_filename + assembler.workflow[load_id] = load_node + + scale_id = assembler._get_unique_id() + scale_node = create_node(assembler, "ImageScaleToTotalPixels", f"Scale Reference {i+1}") + scale_node['inputs']['upscale_method'] = "nearest-exact" + scale_node['inputs']['megapixels'] = 1 + scale_node['inputs']['resolution_steps'] = 1 + scale_node['inputs']['image'] = [load_id, 0] + assembler.workflow[scale_id] = scale_node + + image_key = f"images.image_{i+1}" + assembler.workflow[boogu_prompt_id]['inputs'][image_key] = [scale_id, 0] + + print(f"Boogu Edit injector applied with {len(valid_images)} reference image(s). Connected VAE dynamically.") diff --git a/chain_injectors/conditioning_injector.py b/chain_injectors/conditioning_injector.py new file mode 100644 index 0000000000000000000000000000000000000000..6627006533a6b63c0d3f82f7e0ee9f25c187a3f1 --- /dev/null +++ b/chain_injectors/conditioning_injector.py @@ -0,0 +1,81 @@ +def inject(assembler, chain_definition, chain_items): + if not chain_items: + return + + ksampler_name = chain_definition.get('ksampler_node', 'ksampler') + + target_node_id = None + target_input_name = None + + if ksampler_name in assembler.node_map: + ksampler_id = assembler.node_map[ksampler_name] + if 'positive' in assembler.workflow[ksampler_id]['inputs']: + target_node_id = ksampler_id + target_input_name = 'positive' + print(f"Conditioning injector targeting KSampler node '{ksampler_name}'.") + else: + print(f"Warning: KSampler node '{ksampler_name}' for Conditioning chain not found. Skipping.") + return + + if not target_node_id: + print("Warning: Conditioning chain could not find a valid injection point (KSampler may be missing 'positive' input). Skipping.") + return + + clip_source_str = chain_definition.get('clip_source') + if not clip_source_str: + print("Warning: 'clip_source' definition missing in the recipe for the Conditioning chain. Skipping.") + return + clip_node_name, clip_idx_str = clip_source_str.split(':') + if clip_node_name not in assembler.node_map: + print(f"Warning: CLIP source node '{clip_node_name}' for Conditioning chain not found. Skipping.") + return + clip_connection = [assembler.node_map[clip_node_name], int(clip_idx_str)] + + original_positive_connection = assembler.workflow[target_node_id]['inputs'][target_input_name] + + area_conditioning_outputs = [] + + for item_data in chain_items: + prompt = item_data.get('prompt', '') + if not prompt or not prompt.strip(): + continue + + text_encode_id = assembler._get_unique_id() + text_encode_node = assembler._get_node_template("CLIPTextEncode") + text_encode_node['inputs']['text'] = prompt + text_encode_node['inputs']['clip'] = clip_connection + assembler.workflow[text_encode_id] = text_encode_node + + set_area_id = assembler._get_unique_id() + set_area_node = assembler._get_node_template("ConditioningSetArea") + set_area_node['inputs']['width'] = item_data.get('width', 1024) + set_area_node['inputs']['height'] = item_data.get('height', 1024) + set_area_node['inputs']['x'] = item_data.get('x', 0) + set_area_node['inputs']['y'] = item_data.get('y', 0) + set_area_node['inputs']['strength'] = item_data.get('strength', 1.0) + set_area_node['inputs']['conditioning'] = [text_encode_id, 0] + assembler.workflow[set_area_id] = set_area_node + + area_conditioning_outputs.append([set_area_id, 0]) + + if not area_conditioning_outputs: + return + + current_combined_conditioning = area_conditioning_outputs[0] + if len(area_conditioning_outputs) > 1: + for i in range(1, len(area_conditioning_outputs)): + combine_id = assembler._get_unique_id() + combine_node = assembler._get_node_template("ConditioningCombine") + combine_node['inputs']['conditioning_1'] = current_combined_conditioning + combine_node['inputs']['conditioning_2'] = area_conditioning_outputs[i] + assembler.workflow[combine_id] = combine_node + current_combined_conditioning = [combine_id, 0] + + final_combine_id = assembler._get_unique_id() + final_combine_node = assembler._get_node_template("ConditioningCombine") + final_combine_node['inputs']['conditioning_1'] = original_positive_connection + final_combine_node['inputs']['conditioning_2'] = current_combined_conditioning + assembler.workflow[final_combine_id] = final_combine_node + + assembler.workflow[target_node_id]['inputs'][target_input_name] = [final_combine_id, 0] + print(f"Conditioning injector applied. Redirected '{target_input_name}' input with {len(area_conditioning_outputs)} regional prompts.") diff --git a/chain_injectors/controlnet_injector.py b/chain_injectors/controlnet_injector.py new file mode 100644 index 0000000000000000000000000000000000000000..760a21add69123f2fd5da1add76046890af2d135 --- /dev/null +++ b/chain_injectors/controlnet_injector.py @@ -0,0 +1,60 @@ +def inject(assembler, chain_definition, chain_items): + if not chain_items: + return + + ksampler_name = chain_definition.get('ksampler_node', 'ksampler') + if ksampler_name not in assembler.node_map: + print(f"Warning: Target node '{ksampler_name}' for ControlNet chain not found. Skipping chain injection.") + return + + ksampler_id = assembler.node_map[ksampler_name] + + if 'positive' not in assembler.workflow[ksampler_id]['inputs'] or \ + 'negative' not in assembler.workflow[ksampler_id]['inputs']: + print(f"Warning: KSampler node '{ksampler_name}' is missing 'positive' or 'negative' inputs. Skipping ControlNet chain.") + return + + vae_source_str = chain_definition.get('vae_source') + if not vae_source_str: + print("Warning: 'vae_source' definition missing in the recipe for the ControlNet chain. Skipping.") + return + vae_node_name, vae_idx_str = vae_source_str.split(':') + if vae_node_name not in assembler.node_map: + print(f"Warning: VAE source node '{vae_node_name}' for ControlNet chain not found. Skipping.") + return + vae_connection = [assembler.node_map[vae_node_name], int(vae_idx_str)] + + current_positive_connection = assembler.workflow[ksampler_id]['inputs']['positive'] + current_negative_connection = assembler.workflow[ksampler_id]['inputs']['negative'] + + for item_data in chain_items: + cn_loader_id = assembler._get_unique_id() + cn_loader_node = assembler._get_node_template("ControlNetLoader") + cn_loader_node['inputs']['control_net_name'] = item_data['control_net_name'] + assembler.workflow[cn_loader_id] = cn_loader_node + + image_loader_id = assembler._get_unique_id() + image_loader_node = assembler._get_node_template("LoadImage") + image_loader_node['inputs']['image'] = item_data['image'] + assembler.workflow[image_loader_id] = image_loader_node + + apply_cn_id = assembler._get_unique_id() + apply_cn_node = assembler._get_node_template(chain_definition['template']) + + apply_cn_node['inputs']['strength'] = item_data['strength'] + + apply_cn_node['inputs']['positive'] = current_positive_connection + apply_cn_node['inputs']['negative'] = current_negative_connection + apply_cn_node['inputs']['control_net'] = [cn_loader_id, 0] + apply_cn_node['inputs']['image'] = [image_loader_id, 0] + apply_cn_node['inputs']['vae'] = vae_connection + + assembler.workflow[apply_cn_id] = apply_cn_node + + current_positive_connection = [apply_cn_id, 0] + current_negative_connection = [apply_cn_id, 1] + + assembler.workflow[ksampler_id]['inputs']['positive'] = current_positive_connection + assembler.workflow[ksampler_id]['inputs']['negative'] = current_negative_connection + + print(f"ControlNet injector applied. KSampler inputs redirected through {len(chain_items)} ControlNet nodes.") diff --git a/chain_injectors/diffsynth_controlnet_injector.py b/chain_injectors/diffsynth_controlnet_injector.py new file mode 100644 index 0000000000000000000000000000000000000000..b9453975e7cfbd624aa6b2586dd9f0a87d16bc71 --- /dev/null +++ b/chain_injectors/diffsynth_controlnet_injector.py @@ -0,0 +1,75 @@ +def inject(assembler, chain_definition, chain_items): + if not chain_items: + return + + model_sampler_name = chain_definition.get('model_sampler_node') + ksampler_name = chain_definition.get('ksampler_node', 'ksampler') + + target_node_id = None + target_input_name = 'model' + + if model_sampler_name and model_sampler_name in assembler.node_map: + model_sampler_id = assembler.node_map[model_sampler_name] + if target_input_name in assembler.workflow[model_sampler_id]['inputs']: + target_node_id = model_sampler_id + print(f"ControlNet Model Patch injector targeting ModelSamplingAuraFlow node '{model_sampler_name}'.") + + if not target_node_id: + if ksampler_name in assembler.node_map: + ksampler_id = assembler.node_map[ksampler_name] + if target_input_name in assembler.workflow[ksampler_id]['inputs']: + target_node_id = ksampler_id + print(f"ControlNet Model Patch injector targeting KSampler node '{ksampler_name}'.") + else: + print(f"Warning: Neither ModelSamplingAuraFlow node '{model_sampler_name}' nor KSampler node '{ksampler_name}' found for ControlNet patch chain. Skipping.") + return + + if not target_node_id: + print(f"Warning: Could not find a valid 'model' input on target nodes. Skipping ControlNet patch chain.") + return + + current_model_connection = assembler.workflow[target_node_id]['inputs'][target_input_name] + + vae_source_str = chain_definition.get('vae_source') + vae_connection = None + if vae_source_str: + try: + vae_node_name, vae_idx_str = vae_source_str.split(':') + if vae_node_name in assembler.node_map: + vae_connection = [assembler.node_map[vae_node_name], int(vae_idx_str)] + else: + print(f"Warning: VAE source node '{vae_node_name}' not found for ControlNet patch chain. VAE will not be connected.") + except ValueError: + print(f"Warning: Invalid 'vae_source' format '{vae_source_str}' for ControlNet patch chain. Expected 'node_name:index'. VAE will not be connected.") + else: + print(f"Warning: 'vae_source' not defined for ControlNet patch chain definition. VAE may not be connected.") + + for item_data in chain_items: + patch_loader_id = assembler._get_unique_id() + patch_loader_node = assembler._get_node_template("ModelPatchLoader") + patch_loader_node['inputs']['name'] = item_data['control_net_name'] + assembler.workflow[patch_loader_id] = patch_loader_node + + image_loader_id = assembler._get_unique_id() + image_loader_node = assembler._get_node_template("LoadImage") + image_loader_node['inputs']['image'] = item_data['image'] + assembler.workflow[image_loader_id] = image_loader_node + + apply_cn_id = assembler._get_unique_id() + apply_cn_node = assembler._get_node_template(chain_definition['template']) + + apply_cn_node['inputs']['strength'] = item_data.get('strength', 1.0) + apply_cn_node['inputs']['model'] = current_model_connection + apply_cn_node['inputs']['model_patch'] = [patch_loader_id, 0] + apply_cn_node['inputs']['image'] = [image_loader_id, 0] + + if 'vae' in apply_cn_node['inputs'] and vae_connection: + apply_cn_node['inputs']['vae'] = vae_connection + + assembler.workflow[apply_cn_id] = apply_cn_node + + current_model_connection = [apply_cn_id, 0] + + assembler.workflow[target_node_id]['inputs'][target_input_name] = current_model_connection + + print(f"ControlNet Model Patch injector applied. Target 'model' input re-routed through {len(chain_items)} patch(es).") diff --git a/chain_injectors/flux1_ipadapter_injector.py b/chain_injectors/flux1_ipadapter_injector.py new file mode 100644 index 0000000000000000000000000000000000000000..5582354c5e7186f61394d3b9ba265781e544b9e0 --- /dev/null +++ b/chain_injectors/flux1_ipadapter_injector.py @@ -0,0 +1,46 @@ +def inject(assembler, chain_definition, chain_items): + if not chain_items: + return + + ksampler_name = chain_definition.get('ksampler_node', 'ksampler') + if ksampler_name not in assembler.node_map: + print(f"Warning: KSampler node '{ksampler_name}' not found for Flux1 IPAdapter chain. Skipping.") + return + + ksampler_id = assembler.node_map[ksampler_name] + + if 'model' not in assembler.workflow[ksampler_id]['inputs']: + print(f"Warning: KSampler node '{ksampler_name}' is missing 'model' input. Skipping Flux1 IPAdapter chain.") + return + + current_model_connection = assembler.workflow[ksampler_id]['inputs']['model'] + + for item_data in chain_items: + image_loader_id = assembler._get_unique_id() + image_loader_node = assembler._get_node_template("LoadImage") + image_loader_node['inputs']['image'] = item_data['image'] + assembler.workflow[image_loader_id] = image_loader_node + + ipadapter_loader_id = assembler._get_unique_id() + ipadapter_loader_node = assembler._get_node_template("IPAdapterFluxLoader") + ipadapter_loader_node['inputs']['ipadapter'] = "ip-adapter.bin" + ipadapter_loader_node['inputs']['clip_vision'] = "google/siglip-so400m-patch14-384" + ipadapter_loader_node['inputs']['provider'] = "cuda" + assembler.workflow[ipadapter_loader_id] = ipadapter_loader_node + + apply_ipa_id = assembler._get_unique_id() + apply_ipa_node = assembler._get_node_template("ApplyIPAdapterFlux") + + apply_ipa_node['inputs']['weight'] = item_data['weight'] + apply_ipa_node['inputs']['start_percent'] = item_data.get('start_percent', 0.0) + apply_ipa_node['inputs']['end_percent'] = item_data.get('end_percent', 0.6) + + apply_ipa_node['inputs']['model'] = current_model_connection + apply_ipa_node['inputs']['ipadapter_flux'] = [ipadapter_loader_id, 0] + apply_ipa_node['inputs']['image'] = [image_loader_id, 0] + + assembler.workflow[apply_ipa_id] = apply_ipa_node + current_model_connection = [apply_ipa_id, 0] + + assembler.workflow[ksampler_id]['inputs']['model'] = current_model_connection + print(f"Flux1 IPAdapter injector applied. KSampler model input re-routed through {len(chain_items)} IPAdapter(s).") diff --git a/chain_injectors/hidream_o1_reference_injector.py b/chain_injectors/hidream_o1_reference_injector.py new file mode 100644 index 0000000000000000000000000000000000000000..fa5656490d19471372c2efcba09b3ba6f1654b17 --- /dev/null +++ b/chain_injectors/hidream_o1_reference_injector.py @@ -0,0 +1,54 @@ +def inject(assembler, chain_definition, chain_items): + if not chain_items: + return + + ksampler_name = chain_definition.get('ksampler_node', 'ksampler') + + if ksampler_name not in assembler.node_map: + print(f"Warning: KSampler node '{ksampler_name}' not found for HiDream-O1 Reference chain. Skipping.") + return + + ksampler_id = assembler.node_map[ksampler_name] + + if 'positive' not in assembler.workflow[ksampler_id]['inputs'] or 'negative' not in assembler.workflow[ksampler_id]['inputs']: + print(f"Warning: KSampler node '{ksampler_name}' missing positive/negative inputs. Skipping.") + return + + current_pos_conditioning = assembler.workflow[ksampler_id]['inputs']['positive'] + current_neg_conditioning = assembler.workflow[ksampler_id]['inputs']['negative'] + + ref_images_id = assembler._get_unique_id() + ref_images_node = assembler._get_node_template("HiDreamO1ReferenceImages") + + if 'images' in ref_images_node['inputs']: + del ref_images_node['inputs']['images'] + + ref_images_node['inputs']['positive'] = current_pos_conditioning + ref_images_node['inputs']['negative'] = current_neg_conditioning + + for i, img_filename in enumerate(chain_items): + if i >= 10: + break + + load_id = assembler._get_unique_id() + load_node = assembler._get_node_template("LoadImage") + load_node['inputs']['image'] = img_filename + load_node['_meta']['title'] = f"Load Reference Image {i+1}" + assembler.workflow[load_id] = load_node + + scale_id = assembler._get_unique_id() + scale_node = assembler._get_node_template("ImageScaleToTotalPixels") + scale_node['inputs']['megapixels'] = 1.0 + scale_node['inputs']['upscale_method'] = "lanczos" + scale_node['inputs']['image'] = [load_id, 0] + scale_node['_meta']['title'] = f"Scale Reference {i+1}" + assembler.workflow[scale_id] = scale_node + + ref_images_node['inputs'][f'images.image_{i+1}'] = [scale_id, 0] + + assembler.workflow[ref_images_id] = ref_images_node + + assembler.workflow[ksampler_id]['inputs']['positive'] = [ref_images_id, 0] + assembler.workflow[ksampler_id]['inputs']['negative'] = [ref_images_id, 1] + + print(f"HiDream-O1 Reference injector applied. Re-routed inputs through {min(len(chain_items), 10)} reference images.") diff --git a/chain_injectors/hidream_o1_smoothing_injector.py b/chain_injectors/hidream_o1_smoothing_injector.py new file mode 100644 index 0000000000000000000000000000000000000000..e8c9d8a579105ee4ca622395c5f681bea66ee848 --- /dev/null +++ b/chain_injectors/hidream_o1_smoothing_injector.py @@ -0,0 +1,39 @@ +from copy import deepcopy + +def inject(assembler, chain_definition, chain_items): + if not chain_items: + return + + target_node_name = chain_definition.get('target_node') + if not target_node_name or target_node_name not in assembler.node_map: + print(f"Warning: Target node '{target_node_name}' not found for HiDream-O1 Smoothing. Skipping.") + return + + target_node_id = assembler.node_map[target_node_name] + + if 'model' not in assembler.workflow[target_node_id]['inputs']: + print(f"Warning: Target node '{target_node_name}' has no 'model' input. Skipping.") + return + + current_model_connection = assembler.workflow[target_node_id]['inputs']['model'] + + for _ in chain_items: + template = assembler._get_node_template("HiDreamO1PatchSeamSmoothing") + node_data = deepcopy(template) + + node_data['inputs']['start_percent'] = 0.8 + node_data['inputs']['end_percent'] = 1.0 + node_data['inputs']['pattern'] = "single_shift" + node_data['inputs']['passes'] = "ramp_2_4" + node_data['inputs']['blend'] = "median" + node_data['inputs']['strength'] = 1.0 + + node_data['inputs']['model'] = current_model_connection + + new_node_id = assembler._get_unique_id() + assembler.workflow[new_node_id] = node_data + + current_model_connection = [new_node_id, 0] + + assembler.workflow[target_node_id]['inputs']['model'] = current_model_connection + print("HiDream-O1 Patch Seam Smoothing injector applied.") diff --git a/chain_injectors/ipadapter_injector.py b/chain_injectors/ipadapter_injector.py new file mode 100644 index 0000000000000000000000000000000000000000..d3135d3449abf820558e732f68f4b3fd2aed3d59 --- /dev/null +++ b/chain_injectors/ipadapter_injector.py @@ -0,0 +1,151 @@ +def inject(assembler, chain_definition, chain_items): + if not chain_items: + return + + final_settings = {} + if chain_items and isinstance(chain_items[-1], dict) and chain_items[-1].get('is_final_settings'): + final_settings = chain_items.pop() + + if not chain_items: + return + + end_node_name = chain_definition.get('end') + if not end_node_name or end_node_name not in assembler.node_map: + print(f"Warning: Target node '{end_node_name}' for IPAdapter chain not found. Skipping chain injection.") + return + + end_node_id = assembler.node_map[end_node_name] + + if 'model' not in assembler.workflow[end_node_id]['inputs']: + print(f"Warning: Target node '{end_node_name}' is missing 'model' input. Skipping IPAdapter chain.") + return + + current_model_connection = assembler.workflow[end_node_id]['inputs']['model'] + + model_type = final_settings.get('model_type', 'sdxl') + megapixels = 1.05 if model_type == 'sdxl' else 0.39 + + first_preset = chain_items[0].get('preset', '') + is_faceid_chain = 'FACEID' in first_preset.upper() + + if is_faceid_chain: + for i, item_data in enumerate(chain_items): + image_loader_id = assembler._get_unique_id() + image_loader_node = assembler._get_node_template("LoadImage") + image_loader_node['inputs']['image'] = item_data['image'] + assembler.workflow[image_loader_id] = image_loader_node + + image_scaler_id = assembler._get_unique_id() + image_scaler_node = assembler._get_node_template("ImageScaleToTotalPixels") + image_scaler_node['inputs']['image'] = [image_loader_id, 0] + image_scaler_node['inputs']['megapixels'] = megapixels + image_scaler_node['inputs']['upscale_method'] = "lanczos" + assembler.workflow[image_scaler_id] = image_scaler_node + + ipadapter_loader_id = assembler._get_unique_id() + ipadapter_loader_node = assembler._get_node_template("IPAdapterUnifiedLoaderFaceID") + ipadapter_loader_node['inputs']['model'] = current_model_connection + ipadapter_loader_node['inputs']['preset'] = item_data['preset'] + ipadapter_loader_node['inputs']['lora_strength'] = item_data.get('lora_strength', 0.6) + ipadapter_loader_node['inputs']['provider'] = "CUDA" + assembler.workflow[ipadapter_loader_id] = ipadapter_loader_node + + apply_id = assembler._get_unique_id() + apply_node = assembler._get_node_template("IPAdapterFaceID") + apply_node['inputs']['model'] = [ipadapter_loader_id, 0] + apply_node['inputs']['ipadapter'] = [ipadapter_loader_id, 1] + apply_node['inputs']['image'] = [image_scaler_id, 0] + apply_node['inputs']['weight'] = item_data['weight'] + apply_node['inputs']['weight_faceidv2'] = final_settings.get('final_lora_strength', 0.6) + apply_node['inputs']['weight_type'] = "linear" + apply_node['inputs']['combine_embeds'] = final_settings.get('final_combine_method', 'concat') + apply_node['inputs']['start_at'] = item_data.get('start_percent', 0.0) + apply_node['inputs']['end_at'] = item_data.get('end_percent', 1.0) + apply_node['inputs']['embeds_scaling'] = final_settings.get('final_embeds_scaling', 'V only') + + assembler.workflow[apply_id] = apply_node + current_model_connection = [apply_id, 0] + + assembler.workflow[end_node_id]['inputs']['model'] = current_model_connection + print(f"IPAdapter FaceID injector applied (Direct Apply). Redirected '{end_node_name}' model input through {len(chain_items)} FaceID node(s).") + return + + else: + pos_embed_outputs = [] + neg_embed_outputs = [] + + for i, item_data in enumerate(chain_items): + loader_type = 'FaceID' if 'FACEID' in item_data.get('preset', '') else 'Unified' + loader_template_name = "IPAdapterUnifiedLoader" + if loader_type == 'FaceID': + loader_template_name = "IPAdapterUnifiedLoaderFaceID" + + image_loader_id = assembler._get_unique_id() + image_loader_node = assembler._get_node_template("LoadImage") + image_loader_node['inputs']['image'] = item_data['image'] + assembler.workflow[image_loader_id] = image_loader_node + + image_scaler_id = assembler._get_unique_id() + image_scaler_node = assembler._get_node_template("ImageScaleToTotalPixels") + image_scaler_node['inputs']['image'] = [image_loader_id, 0] + image_scaler_node['inputs']['megapixels'] = megapixels + image_scaler_node['inputs']['upscale_method'] = "lanczos" + assembler.workflow[image_scaler_id] = image_scaler_node + + ipadapter_loader_id = assembler._get_unique_id() + ipadapter_loader_node = assembler._get_node_template(loader_template_name) + ipadapter_loader_node['inputs']['model'] = current_model_connection + ipadapter_loader_node['inputs']['preset'] = item_data['preset'] + if loader_type == 'FaceID': + ipadapter_loader_node['inputs']['lora_strength'] = item_data.get('lora_strength', 0.6) + assembler.workflow[ipadapter_loader_id] = ipadapter_loader_node + + encoder_id = assembler._get_unique_id() + encoder_node = assembler._get_node_template("IPAdapterEncoder") + encoder_node['inputs']['weight'] = item_data['weight'] + encoder_node['inputs']['ipadapter'] = [ipadapter_loader_id, 1] + encoder_node['inputs']['image'] = [image_scaler_id, 0] + assembler.workflow[encoder_id] = encoder_node + + pos_embed_outputs.append([encoder_id, 0]) + neg_embed_outputs.append([encoder_id, 1]) + + pos_combiner_id = assembler._get_unique_id() + pos_combiner_node = assembler._get_node_template("IPAdapterCombineEmbeds") + pos_combiner_node['inputs']['method'] = final_settings.get('final_combine_method', 'concat') + for i, conn in enumerate(pos_embed_outputs): + pos_combiner_node['inputs'][f'embed{i+1}'] = conn + assembler.workflow[pos_combiner_id] = pos_combiner_node + + neg_combiner_id = assembler._get_unique_id() + neg_combiner_node = assembler._get_node_template("IPAdapterCombineEmbeds") + neg_combiner_node['inputs']['method'] = final_settings.get('final_combine_method', 'concat') + for i, conn in enumerate(neg_embed_outputs): + neg_combiner_node['inputs'][f'embed{i+1}'] = conn + assembler.workflow[neg_combiner_id] = neg_combiner_node + + final_loader_type = 'FaceID' if 'FACEID' in final_settings.get('final_preset', '') else 'Unified' + final_loader_template_name = "IPAdapterUnifiedLoader" + if final_loader_type == 'FaceID': + final_loader_template_name = "IPAdapterUnifiedLoaderFaceID" + + final_loader_id = assembler._get_unique_id() + final_loader_node = assembler._get_node_template(final_loader_template_name) + final_loader_node['inputs']['model'] = current_model_connection + final_loader_node['inputs']['preset'] = final_settings.get('final_preset', 'STANDARD (medium strength)') + if final_loader_type == 'FaceID': + final_loader_node['inputs']['lora_strength'] = final_settings.get('final_lora_strength', 0.6) + assembler.workflow[final_loader_id] = final_loader_node + + apply_embeds_id = assembler._get_unique_id() + apply_embeds_node = assembler._get_node_template("IPAdapterEmbeds") + apply_embeds_node['inputs']['weight'] = final_settings.get('final_weight', 1.0) + apply_embeds_node['inputs']['embeds_scaling'] = final_settings.get('final_embeds_scaling', 'V only') + apply_embeds_node['inputs']['model'] = [final_loader_id, 0] + apply_embeds_node['inputs']['ipadapter'] = [final_loader_id, 1] + apply_embeds_node['inputs']['pos_embed'] = [pos_combiner_id, 0] + apply_embeds_node['inputs']['neg_embed'] = [neg_combiner_id, 0] + assembler.workflow[apply_embeds_id] = apply_embeds_node + + assembler.workflow[end_node_id]['inputs']['model'] = [apply_embeds_id, 0] + print(f"IPAdapter Unified injector applied. Redirected '{end_node_name}' model input through {len(chain_items)} reference image(s).") diff --git a/chain_injectors/joyai_image_injector.py b/chain_injectors/joyai_image_injector.py new file mode 100644 index 0000000000000000000000000000000000000000..0f09eefae268770240abb268015d3e119c0950f8 --- /dev/null +++ b/chain_injectors/joyai_image_injector.py @@ -0,0 +1,63 @@ +import os + +def inject(assembler, chain_definition, chain_items): + if not chain_items: + return + + valid_images = [] + for item in chain_items: + if not item: + continue + img_path = item + if isinstance(item, dict): + img_path = item.get('image') or item.get('filename') or item.get('path') + if img_path: + valid_images.append(img_path) + + if not valid_images: + return + + valid_images = valid_images[:2] + + pos_prompt_name = chain_definition.get('pos_prompt_node', 'pos_prompt') + neg_prompt_name = chain_definition.get('neg_prompt_node', 'neg_prompt') + vae_node_name = chain_definition.get('vae_node', 'vae_loader') + + if pos_prompt_name not in assembler.node_map: + print(f"Warning: Positive prompt node '{pos_prompt_name}' not found for JoyAI Reference chain. Skipping.") + return + + if vae_node_name not in assembler.node_map: + print(f"Warning: VAE loader node '{vae_node_name}' not found for JoyAI Reference chain. Skipping.") + return + + pos_prompt_id = assembler.node_map[pos_prompt_name] + neg_prompt_id = assembler.node_map.get(neg_prompt_name) + vae_node_id = assembler.node_map[vae_node_name] + + assembler.workflow[pos_prompt_id]['inputs']['vae'] = [vae_node_id, 0] + if neg_prompt_id and neg_prompt_id in assembler.workflow: + assembler.workflow[neg_prompt_id]['inputs']['vae'] = [vae_node_id, 0] + + for i, img_filename in enumerate(valid_images): + load_id = assembler._get_unique_id() + load_node = assembler._get_node_template("LoadImage") + load_node['inputs']['image'] = img_filename + load_node['_meta']['title'] = f"Load Reference Image {i+1}" + assembler.workflow[load_id] = load_node + + scale_id = assembler._get_unique_id() + scale_node = assembler._get_node_template("ImageScaleToTotalPixels") + scale_node['inputs']['megapixels'] = 1.0 + scale_node['inputs']['upscale_method'] = "nearest-exact" + scale_node['inputs']['resolution_steps'] = 1 + scale_node['inputs']['image'] = [load_id, 0] + scale_node['_meta']['title'] = f"Scale Reference {i+1}" + assembler.workflow[scale_id] = scale_node + + input_key = f"images.image{i}" + assembler.workflow[pos_prompt_id]['inputs'][input_key] = [scale_id, 0] + if neg_prompt_id and neg_prompt_id in assembler.workflow: + assembler.workflow[neg_prompt_id]['inputs'][input_key] = [scale_id, 0] + + print(f"JoyAI Reference injector applied. Injected {len(valid_images)} reference images to JoyAI text encoding nodes.") diff --git a/chain_injectors/krea2_controlnet_injector.py b/chain_injectors/krea2_controlnet_injector.py new file mode 100644 index 0000000000000000000000000000000000000000..c43c1f5732cf89ca04b87d557016e7f2dfdf2509 --- /dev/null +++ b/chain_injectors/krea2_controlnet_injector.py @@ -0,0 +1,78 @@ +def inject(assembler, chain_definition, chain_items): + if not chain_items: + return + + ksampler_name = chain_definition.get('ksampler_node', 'ksampler') + if ksampler_name not in assembler.node_map: + print(f"Warning: Target node '{ksampler_name}' for Krea2 ControlNet chain not found. Skipping.") + return + + ksampler_id = assembler.node_map[ksampler_name] + + if 'model' not in assembler.workflow[ksampler_id]['inputs']: + print(f"Warning: KSampler node '{ksampler_name}' is missing 'model' input. Skipping.") + return + + vae_source_str = chain_definition.get('vae_source') + vae_connection = None + if vae_source_str: + vae_node_name, vae_idx_str = vae_source_str.split(':') + if vae_node_name in assembler.node_map: + vae_connection = [assembler.node_map[vae_node_name], int(vae_idx_str)] + + latent_connection = assembler.workflow[ksampler_id]['inputs'].get('latent_image') + if not latent_connection: + print(f"Warning: KSampler node '{ksampler_name}' is missing 'latent_image' input. Krea2 ControlNet requires it. Skipping.") + return + + current_model_connection = assembler.workflow[ksampler_id]['inputs']['model'] + + for item_data in chain_items: + image_loader_id = assembler._get_unique_id() + image_loader_node = assembler._get_node_template("LoadImage") + image_loader_node['inputs']['image'] = item_data['image'] + assembler.workflow[image_loader_id] = image_loader_node + + image_scaler_id = assembler._get_unique_id() + image_scaler_node = assembler._get_node_template("ImageScaleToTotalPixels") + image_scaler_node['inputs']['image'] = [image_loader_id, 0] + image_scaler_node['inputs']['upscale_method'] = 'nearest-exact' + image_scaler_node['inputs']['megapixels'] = 1.0 + image_scaler_node['inputs']['resolution_steps'] = 1 + assembler.workflow[image_scaler_id] = image_scaler_node + + lora_loader_id = assembler._get_unique_id() + lora_loader_node = assembler._get_node_template("Krea2ControlLoRALoader") + lora_loader_node['inputs']['lora_name'] = item_data['control_net_name'] + lora_loader_node['inputs']['strength'] = item_data.get('strength', 1.0) + lora_loader_node['inputs']['model'] = current_model_connection + assembler.workflow[lora_loader_id] = lora_loader_node + + img_encode_id = assembler._get_unique_id() + img_encode_node = assembler._get_node_template("Krea2ControlImageEncode") + img_encode_node['inputs']['resize'] = "match_latent_size" + img_encode_node['inputs']['upscale_method'] = "lanczos" + img_encode_node['inputs']['crop'] = "center" + img_encode_node['inputs']['channel_mode'] = "rgb" + img_encode_node['inputs']['normalize'] = "none" + img_encode_node['inputs']['invert'] = False + img_encode_node['inputs']['batch_mode'] = "independent_images" + img_encode_node['inputs']['control_image'] = [image_scaler_id, 0] + if vae_connection: + img_encode_node['inputs']['vae'] = vae_connection + if latent_connection: + img_encode_node['inputs']['latent'] = latent_connection + assembler.workflow[img_encode_id] = img_encode_node + + apply_cn_id = assembler._get_unique_id() + apply_cn_node = assembler._get_node_template("Krea2ControlApply") + apply_cn_node['inputs']['model'] = [lora_loader_id, 0] + apply_cn_node['inputs']['control_latent'] = [img_encode_id, 0] + + assembler.workflow[apply_cn_id] = apply_cn_node + + current_model_connection = [apply_cn_id, 0] + + assembler.workflow[ksampler_id]['inputs']['model'] = current_model_connection + + print(f"Krea2 ControlNet injector applied. KSampler model input redirected through {len(chain_items)} Krea2 ControlNet nodes.") diff --git a/chain_injectors/krea2_identity_edit_injector.py b/chain_injectors/krea2_identity_edit_injector.py new file mode 100644 index 0000000000000000000000000000000000000000..3e9171e4b99baefff9e9f5069e262fdf892261a1 --- /dev/null +++ b/chain_injectors/krea2_identity_edit_injector.py @@ -0,0 +1,173 @@ +import os +from imagegen_utils.app_utils import ensure_file_downloaded + +def inject(assembler, chain_definition, chain_items): + if not chain_items: + return + + valid_images = [] + for item in chain_items: + if not item: + continue + img_path = item + if isinstance(item, dict): + img_path = item.get('image') or item.get('filename') or item.get('path') + if img_path: + valid_images.append(img_path) + + if not valid_images: + return + + valid_images = valid_images[:2] + + lora_filename = "krea2_identity_edit_v1_2.safetensors" + try: + ensure_file_downloaded(lora_filename) + except Exception as e: + print(f"Warning: Failed to ensure '{lora_filename}' downloaded: {e}") + + ksampler_name = chain_definition.get('ksampler_node', 'ksampler') + pos_prompt_name = chain_definition.get('pos_prompt_node', 'pos_prompt') + neg_prompt_name = chain_definition.get('neg_prompt_node', 'neg_prompt') + clip_loader_name = chain_definition.get('clip_loader_node', 'clip_loader') + vae_loader_name = chain_definition.get('vae_loader_node', 'vae_loader') + + if ksampler_name not in assembler.node_map: + print(f"Warning: Target node '{ksampler_name}' for Krea2 Identity Edit chain not found. Skipping.") + return + + ksampler_id = assembler.node_map[ksampler_name] + + if 'model' not in assembler.workflow[ksampler_id]['inputs']: + print(f"Warning: KSampler node '{ksampler_name}' is missing 'model' input. Skipping.") + return + + latent_connection = assembler.workflow[ksampler_id]['inputs'].get('latent_image') + if not latent_connection: + print(f"Warning: KSampler node '{ksampler_name}' is missing 'latent_image' input. Skipping.") + return + + current_model_connection = assembler.workflow[ksampler_id]['inputs']['model'] + + vae_connection = None + if vae_loader_name in assembler.node_map: + vae_connection = [assembler.node_map[vae_loader_name], 0] + + clip_connection = None + if clip_loader_name in assembler.node_map: + clip_connection = [assembler.node_map[clip_loader_name], 0] + elif pos_prompt_name in assembler.node_map: + pos_id = assembler.node_map[pos_prompt_name] + clip_connection = assembler.workflow[pos_id]['inputs'].get('clip') + + lora_loader_id = assembler._get_unique_id() + lora_loader_node = assembler._get_node_template("LoraLoaderModelOnly") + lora_loader_node['inputs']['lora_name'] = lora_filename + lora_loader_node['inputs']['strength_model'] = 1.0 + lora_loader_node['inputs']['model'] = current_model_connection + lora_loader_node['_meta']['title'] = "Load LoRA (Krea2 Identity Edit)" + assembler.workflow[lora_loader_id] = lora_loader_node + + image_ids = [] + vae_encode_ids = [] + + for i, img_filename in enumerate(valid_images): + load_id = assembler._get_unique_id() + load_node = assembler._get_node_template("LoadImage") + load_node['inputs']['image'] = img_filename + load_node['_meta']['title'] = f"Load Image (Ref {i+1})" + assembler.workflow[load_id] = load_node + image_ids.append(load_id) + + vae_enc_id = assembler._get_unique_id() + vae_enc_node = assembler._get_node_template("VAEEncode") + vae_enc_node['inputs']['pixels'] = [load_id, 0] + if vae_connection: + vae_enc_node['inputs']['vae'] = vae_connection + vae_enc_node['_meta']['title'] = f"VAE Encode (Ref {i+1})" + assembler.workflow[vae_enc_id] = vae_enc_node + vae_encode_ids.append(vae_enc_id) + + patch_id = assembler._get_unique_id() + patch_node = assembler._get_node_template("Krea2EditModelPatch") + patch_node['inputs']['ref_boost'] = 4 + patch_node['inputs']['ref_boost_a'] = 1 + patch_node['inputs']['fit_mode'] = "fit" + patch_node['inputs']['model'] = [lora_loader_id, 0] + patch_node['inputs']['source_latent'] = [vae_encode_ids[0], 0] + if vae_connection: + patch_node['inputs']['vae'] = vae_connection + patch_node['inputs']['source_image'] = [image_ids[0], 0] + patch_node['inputs']['target_latent'] = latent_connection + + if len(valid_images) > 1: + patch_node['inputs']['source_latent_b'] = [vae_encode_ids[1], 0] + patch_node['inputs']['source_image_b'] = [image_ids[1], 0] + + patch_node['_meta']['title'] = "Krea2 Edit (source patch)" + assembler.workflow[patch_id] = patch_node + + assembler.workflow[ksampler_id]['inputs']['model'] = [patch_id, 0] + + pos_prompt_id = assembler.node_map.get(pos_prompt_name) + neg_prompt_id = assembler.node_map.get(neg_prompt_name) + + pos_text = "" + if pos_prompt_id and pos_prompt_id in assembler.workflow: + pos_text = assembler.workflow[pos_prompt_id]['inputs'].get('text', '') + elif hasattr(assembler, 'ui_values') and isinstance(assembler.ui_values, dict): + pos_text = assembler.ui_values.get('positive_prompt') or assembler.ui_values.get('prompt') or '' + + if not pos_text: + for node_id, node in assembler.workflow.items(): + if isinstance(node, dict): + cls = node.get('class_type', '') + if cls in ['Krea2EditGroundedEncode', 'TextEncodeQwenImageEditPlus', 'CLIPTextEncode']: + t = node.get('inputs', {}).get('prompt') or node.get('inputs', {}).get('text') + if t: + pos_text = t + break + + neg_text = "" + if neg_prompt_id and neg_prompt_id in assembler.workflow: + neg_text = assembler.workflow[neg_prompt_id]['inputs'].get('text', '') + elif hasattr(assembler, 'ui_values') and isinstance(assembler.ui_values, dict): + neg_text = assembler.ui_values.get('negative_prompt') or assembler.ui_values.get('neg_prompt') or '' + + pos_grounded_id = assembler._get_unique_id() + pos_grounded_node = assembler._get_node_template("Krea2EditGroundedEncode") + pos_grounded_node['inputs']['prompt'] = pos_text + pos_grounded_node['inputs']['grounding_px'] = 768 + pos_grounded_node['inputs']['system_prompt'] = "" + if clip_connection: + pos_grounded_node['inputs']['clip'] = clip_connection + pos_grounded_node['inputs']['image'] = [image_ids[0], 0] + if len(valid_images) > 1: + pos_grounded_node['inputs']['image_b'] = [image_ids[1], 0] + pos_grounded_node['_meta']['title'] = "Krea2 Edit (grounded encode positive)" + assembler.workflow[pos_grounded_id] = pos_grounded_node + + assembler.workflow[ksampler_id]['inputs']['positive'] = [pos_grounded_id, 0] + + neg_grounded_id = assembler._get_unique_id() + neg_grounded_node = assembler._get_node_template("Krea2EditGroundedEncode") + neg_grounded_node['inputs']['prompt'] = neg_text + neg_grounded_node['inputs']['grounding_px'] = 768 + neg_grounded_node['inputs']['system_prompt'] = "" + if clip_connection: + neg_grounded_node['inputs']['clip'] = clip_connection + neg_grounded_node['inputs']['image'] = [image_ids[0], 0] + if len(valid_images) > 1: + neg_grounded_node['inputs']['image_b'] = [image_ids[1], 0] + neg_grounded_node['_meta']['title'] = "Krea2 Edit (grounded encode negative)" + assembler.workflow[neg_grounded_id] = neg_grounded_node + + assembler.workflow[ksampler_id]['inputs']['negative'] = [neg_grounded_id, 0] + + if pos_prompt_id and pos_prompt_id in assembler.workflow: + del assembler.workflow[pos_prompt_id] + + if neg_prompt_id and neg_prompt_id in assembler.workflow: + del assembler.workflow[neg_prompt_id] + + print(f"Krea2 Identity Edit injector applied with {len(valid_images)} reference image(s). Original CLIPTextEncode nodes removed.") diff --git a/chain_injectors/krea2_style_reference_injector.py b/chain_injectors/krea2_style_reference_injector.py new file mode 100644 index 0000000000000000000000000000000000000000..addc33343be28c2d53cf9bbee02775ba097ba815 --- /dev/null +++ b/chain_injectors/krea2_style_reference_injector.py @@ -0,0 +1,168 @@ +import os +from imagegen_utils.app_utils import ensure_file_downloaded + +def create_node(assembler, class_type, title): + try: + node = assembler._get_node_template(class_type) + except Exception: + node = { + "inputs": {}, + "class_type": class_type, + "_meta": {"title": title} + } + node['_meta']['title'] = title + return node + +def inject(assembler, chain_definition, chain_items): + if not chain_items: + return + + valid_images = [] + for item in chain_items: + if not item: + continue + img_path = item + if isinstance(item, dict): + img_path = item.get('image') or item.get('filename') or item.get('path') + if img_path: + valid_images.append(img_path) + + if not valid_images: + return + + valid_images = valid_images[:3] + + lora_filename = "krea2_style_reference.safetensors" + try: + ensure_file_downloaded(lora_filename) + except Exception as e: + print(f"Warning: Failed to ensure '{lora_filename}' downloaded: {e}") + + ksampler_name = chain_definition.get('ksampler_node', 'ksampler') + pos_prompt_name = chain_definition.get('pos_prompt_node', 'pos_prompt') + neg_prompt_name = chain_definition.get('neg_prompt_node', 'neg_prompt') + clip_loader_name = chain_definition.get('clip_loader_node', 'clip_loader') + vae_loader_name = chain_definition.get('vae_loader_node', 'vae_loader') + + if ksampler_name not in assembler.node_map: + print(f"Warning: Target node '{ksampler_name}' for Krea2 Style Reference Edit chain not found. Skipping.") + return + + ksampler_id = assembler.node_map[ksampler_name] + + if 'model' not in assembler.workflow[ksampler_id]['inputs']: + print(f"Warning: KSampler node '{ksampler_name}' is missing 'model' input. Skipping.") + return + + current_model_connection = assembler.workflow[ksampler_id]['inputs']['model'] + + vae_connection = None + if vae_loader_name in assembler.node_map: + vae_connection = [assembler.node_map[vae_loader_name], 0] + else: + for node_id, node in assembler.workflow.items(): + if isinstance(node, dict) and node.get('class_type') == 'VAELoader': + vae_connection = [node_id, 0] + break + + clip_connection = None + if clip_loader_name in assembler.node_map: + clip_connection = [assembler.node_map[clip_loader_name], 0] + elif pos_prompt_name in assembler.node_map: + pos_id = assembler.node_map[pos_prompt_name] + clip_connection = assembler.workflow[pos_id]['inputs'].get('clip') + + scaled_image_ids = [] + for i, img_filename in enumerate(valid_images): + load_id = assembler._get_unique_id() + load_node = create_node(assembler, "LoadImage", f"Load Reference Image {i+1}") + load_node['inputs']['image'] = img_filename + assembler.workflow[load_id] = load_node + + scale_id = assembler._get_unique_id() + scale_node = create_node(assembler, "ImageScaleToTotalPixels", f"Scale Reference {i+1}") + scale_node['inputs']['upscale_method'] = "nearest-exact" + scale_node['inputs']['megapixels'] = 1 + scale_node['inputs']['resolution_steps'] = 1 + scale_node['inputs']['image'] = [load_id, 0] + assembler.workflow[scale_id] = scale_node + scaled_image_ids.append(scale_id) + + lora_loader_id = assembler._get_unique_id() + lora_loader_node = create_node(assembler, "LoraLoaderModelOnly", "Load LoRA (Krea2 Style Reference)") + lora_loader_node['inputs']['lora_name'] = lora_filename + lora_loader_node['inputs']['strength_model'] = 1.0 + lora_loader_node['inputs']['model'] = current_model_connection + assembler.workflow[lora_loader_id] = lora_loader_node + + assembler.workflow[ksampler_id]['inputs']['model'] = [lora_loader_id, 0] + + pos_prompt_id = assembler.node_map.get(pos_prompt_name) + neg_prompt_id = assembler.node_map.get(neg_prompt_name) + + pos_text = "" + if pos_prompt_id and pos_prompt_id in assembler.workflow: + pos_text = assembler.workflow[pos_prompt_id]['inputs'].get('text', '') + elif hasattr(assembler, 'ui_values') and isinstance(assembler.ui_values, dict): + pos_text = assembler.ui_values.get('positive_prompt') or assembler.ui_values.get('prompt') or '' + + if not pos_text: + for node_id, node in assembler.workflow.items(): + if isinstance(node, dict): + cls = node.get('class_type', '') + if cls in ['Krea2EditGroundedEncode', 'TextEncodeQwenImageEditPlus', 'CLIPTextEncode']: + t = node.get('inputs', {}).get('prompt') or node.get('inputs', {}).get('text') + if t: + pos_text = t + break + + neg_text = "" + if neg_prompt_id and neg_prompt_id in assembler.workflow: + neg_text = assembler.workflow[neg_prompt_id]['inputs'].get('text', '') + elif hasattr(assembler, 'ui_values') and isinstance(assembler.ui_values, dict): + neg_text = assembler.ui_values.get('negative_prompt') or assembler.ui_values.get('neg_prompt') or '' + + pos_encode_id = assembler._get_unique_id() + pos_encode_node = create_node(assembler, "TextEncodeQwenImageEditPlus", "TextEncodeQwenImageEditPlus (Positive)") + pos_encode_node['inputs']['prompt'] = pos_text + if clip_connection: + pos_encode_node['inputs']['clip'] = clip_connection + if vae_connection: + pos_encode_node['inputs']['vae'] = vae_connection + for idx, s_id in enumerate(scaled_image_ids): + pos_encode_node['inputs'][f"image{idx+1}"] = [s_id, 0] + assembler.workflow[pos_encode_id] = pos_encode_node + + neg_encode_id = assembler._get_unique_id() + neg_encode_node = create_node(assembler, "TextEncodeQwenImageEditPlus", "TextEncodeQwenImageEditPlus (Negative)") + neg_encode_node['inputs']['prompt'] = neg_text + if clip_connection: + neg_encode_node['inputs']['clip'] = clip_connection + if vae_connection: + neg_encode_node['inputs']['vae'] = vae_connection + for idx, s_id in enumerate(scaled_image_ids): + neg_encode_node['inputs'][f"image{idx+1}"] = [s_id, 0] + assembler.workflow[neg_encode_id] = neg_encode_node + + pos_ref_id = assembler._get_unique_id() + pos_ref_node = create_node(assembler, "FluxKontextMultiReferenceLatentMethod", "Edit Model Reference Method") + pos_ref_node['inputs']['reference_latents_method'] = "index_timestep_zero" + pos_ref_node['inputs']['conditioning'] = [pos_encode_id, 0] + assembler.workflow[pos_ref_id] = pos_ref_node + + neg_ref_id = assembler._get_unique_id() + neg_ref_node = create_node(assembler, "FluxKontextMultiReferenceLatentMethod", "Edit Model Reference Method") + neg_ref_node['inputs']['reference_latents_method'] = "index_timestep_zero" + neg_ref_node['inputs']['conditioning'] = [neg_encode_id, 0] + assembler.workflow[neg_ref_id] = neg_ref_node + + assembler.workflow[ksampler_id]['inputs']['positive'] = [pos_ref_id, 0] + assembler.workflow[ksampler_id]['inputs']['negative'] = [neg_ref_id, 0] + + if pos_prompt_id and pos_prompt_id in assembler.workflow: + del assembler.workflow[pos_prompt_id] + + if neg_prompt_id and neg_prompt_id in assembler.workflow: + del assembler.workflow[neg_prompt_id] + + print(f"Krea2 Style Reference Edit injector applied with {len(valid_images)} reference image(s). Original CLIPTextEncode nodes replaced.") diff --git a/chain_injectors/lora_injector.py b/chain_injectors/lora_injector.py new file mode 100644 index 0000000000000000000000000000000000000000..3f8832b8a53041918257b095e73361039b4932ba --- /dev/null +++ b/chain_injectors/lora_injector.py @@ -0,0 +1,67 @@ +from copy import deepcopy + +def inject(assembler, chain_definition, chain_items): + if not chain_items: + return + + start_node_name = chain_definition.get('start') + start_node_id = None + if start_node_name: + if start_node_name not in assembler.node_map: + print(f"Warning: Start node '{start_node_name}' for dynamic LoRA chain not found. Skipping chain.") + return + start_node_id = assembler.node_map[start_node_name] + + output_map = chain_definition.get('output_map', {}) + current_connections = {} + for key, type_name in output_map.items(): + if ':' in str(key): + node_name, idx_str = key.split(':') + if node_name not in assembler.node_map: + print(f"Warning: Node '{node_name}' in chain's output_map not found. Skipping.") + continue + node_id = assembler.node_map[node_name] + start_output_idx = int(idx_str) + current_connections[type_name] = [node_id, start_output_idx] + elif start_node_id: + start_output_idx = int(key) + current_connections[type_name] = [start_node_id, start_output_idx] + else: + print(f"Warning: LoRA chain has no 'start' node defined, and an output_map key '{key}' is not in 'node:index' format. Skipping this connection.") + + + input_map = chain_definition.get('input_map', {}) + chain_output_map = chain_definition.get('template_output_map', { "0": "model", "1": "clip" }) + + for item_data in chain_items: + template_name = chain_definition['template'] + template = assembler._get_node_template(template_name) + node_data = deepcopy(template) + + for param_name, value in item_data.items(): + if param_name in node_data['inputs']: + node_data['inputs'][param_name] = value + + for type_name, input_name in input_map.items(): + if type_name in current_connections: + node_data['inputs'][input_name] = current_connections[type_name] + + new_node_id = assembler._get_unique_id() + assembler.workflow[new_node_id] = node_data + + for idx_str, type_name in chain_output_map.items(): + current_connections[type_name] = [new_node_id, int(idx_str)] + + end_input_map = chain_definition.get('end_input_map', {}) + for type_name, targets in end_input_map.items(): + if type_name in current_connections: + if not isinstance(targets, list): + targets = [targets] + + for target_str in targets: + end_node_name, end_input_name = target_str.split(':') + if end_node_name in assembler.node_map: + end_node_id = assembler.node_map[end_node_name] + assembler.workflow[end_node_id]['inputs'][end_input_name] = current_connections[type_name] + else: + print(f"Warning: End node '{end_node_name}' for dynamic chain not found. Skipping connection.") diff --git a/chain_injectors/pid_injector.py b/chain_injectors/pid_injector.py new file mode 100644 index 0000000000000000000000000000000000000000..ff39992df25e69dd074bfe87104c86e826e5d72f --- /dev/null +++ b/chain_injectors/pid_injector.py @@ -0,0 +1,292 @@ +import os +import yaml +import random + +def load_pid_config(): + project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + pid_path = os.path.join(project_root, 'yaml', 'pid.yaml') + with open(pid_path, 'r', encoding='utf-8') as f: + return yaml.safe_load(f) or {} + +def load_model_config(): + project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + model_list_path = os.path.join(project_root, 'yaml', 'model_list.yaml') + with open(model_list_path, 'r', encoding='utf-8') as f: + return yaml.safe_load(f) or {} + +def inject(assembler, chain_definition, chain_items): + if not chain_items: + return + + pid_config = {} + try: + pid_config = load_pid_config() or {} + except Exception as e: + print(f"Error loading PiD config: {e}") + + pid_items = pid_config.get("PiD", []) + architectures_settings = {} + default_settings = {"unet_name": "pid_flux1_1024_to_4096_4step_mxfp8.safetensors", "latent_format": "flux"} + + for item in pid_items: + unet_name = item.get("filepath") + latent_format = item.get("latent_format") + archs = item.get("architectures", []) + for arch in archs: + architectures_settings[arch] = { + "unet_name": unet_name, + "latent_format": latent_format + } + if arch == "flux1": + default_settings = { + "unet_name": unet_name, + "latent_format": latent_format + } + + ksampler_name = chain_definition.get('ksampler_node', 'ksampler') + if ksampler_name not in assembler.node_map: + print(f"Warning: [PiD Injector] KSampler node '{ksampler_name}' not found. Skipping.") + return + + original_ksampler_id = assembler.node_map[ksampler_name] + + original_vae_loader_id = assembler.node_map.get('vae_loader') + original_vae_decode_id = assembler.node_map.get('vae_decode') + original_pos_prompt_id = assembler.node_map.get('pos_prompt') + original_neg_prompt_id = assembler.node_map.get('neg_prompt') + + if not original_vae_loader_id: + for node_id, node_data in assembler.workflow.items(): + if node_data.get('class_type') == 'VAELoader': + original_vae_loader_id = node_id + break + + if not original_vae_decode_id: + for node_id, node_data in assembler.workflow.items(): + if node_data.get('class_type') == 'VAEDecode': + original_vae_decode_id = node_id + break + + if not original_pos_prompt_id or not original_neg_prompt_id: + for node_id, node_data in assembler.workflow.items(): + if node_data.get('class_type') == 'CLIPTextEncode': + title = node_data.get('_meta', {}).get('title', '') + if 'Positive' in title: + if not original_pos_prompt_id: + original_pos_prompt_id = node_id + elif 'Negative' in title: + if not original_neg_prompt_id: + original_neg_prompt_id = node_id + + pos_text = "" + if original_pos_prompt_id and original_pos_prompt_id in assembler.workflow: + pos_text = assembler.workflow[original_pos_prompt_id]['inputs'].get('text', '') + + neg_text = "" + if original_neg_prompt_id and original_neg_prompt_id in assembler.workflow: + neg_text = assembler.workflow[original_neg_prompt_id]['inputs'].get('text', '') + + clip_loader_id = assembler._get_unique_id() + clip_loader_node = assembler._get_node_template("CLIPLoader") + clip_loader_node['inputs']['clip_name'] = "gemma_2_2b_it_elm_fp8_scaled.safetensors" + clip_loader_node['inputs']['type'] = "pixeldit" + clip_loader_node['inputs']['device'] = "default" + assembler.workflow[clip_loader_id] = clip_loader_node + + pos_text_encode_id = assembler._get_unique_id() + pos_text_encode_node = assembler._get_node_template("CLIPTextEncode") + pos_text_encode_node['inputs']['text'] = pos_text + pos_text_encode_node['inputs']['clip'] = [clip_loader_id, 0] + assembler.workflow[pos_text_encode_id] = pos_text_encode_node + + neg_text_encode_id = assembler._get_unique_id() + neg_text_encode_node = assembler._get_node_template("CLIPTextEncode") + neg_text_encode_node['inputs']['text'] = neg_text + neg_text_encode_node['inputs']['clip'] = [clip_loader_id, 0] + assembler.workflow[neg_text_encode_id] = neg_text_encode_node + + active_model_file = None + for node_id, node_data in assembler.workflow.items(): + class_type = node_data.get('class_type') + if class_type == 'UNETLoader': + active_model_file = node_data.get('inputs', {}).get('unet_name') + if active_model_file: + break + elif class_type == 'CheckpointLoaderSimple': + active_model_file = node_data.get('inputs', {}).get('ckpt_name') + if active_model_file: + break + + architecture = None + if active_model_file: + try: + model_config = load_model_config() + checkpoints = model_config.get("Checkpoints", {}) + for arch_name, arch_data in checkpoints.items(): + models_list = arch_data.get("models", []) + for model_entry in models_list: + if model_entry.get('path') == active_model_file: + architecture = arch_name + break + components_dict = model_entry.get('components', {}) + if active_model_file in components_dict.values(): + architecture = arch_name + break + if architecture: + break + except Exception as e: + print(f"Error looking up model architecture in PiD injector: {e}") + + if architecture: + architecture = architecture.lower().replace(" ", "-").replace(".", "") + else: + file_lower = active_model_file.lower().replace("-", "").replace("_", "").replace(".", "") + for arch in sorted(architectures_settings.keys(), key=len, reverse=True): + candidates = [arch] + if "-image" in arch: + candidates.append(arch.replace("-image", "")) + if "-i1" in arch: + candidates.append(arch.replace("-i1", "")) + if "-kv" in arch: + candidates.append(arch.replace("-kv", "")) + + matched = False + for cand in candidates: + if cand.replace("-", "").replace(".", "") in file_lower: + architecture = arch + matched = True + break + if matched: + break + + unet_name = default_settings.get("unet_name") + latent_format = default_settings.get("latent_format") + + if architecture in architectures_settings: + arch_config = architectures_settings[architecture] + unet_name = arch_config.get("unet_name", unet_name) + latent_format = arch_config.get("latent_format", latent_format) + else: + print(f"[PiD Injector] Warning: Model architecture '{architecture}' (file: '{active_model_file}') not explicitly mapped. Using default settings.") + + pid_pos_id = assembler._get_unique_id() + pid_pos_node = assembler._get_node_template("PiDConditioning") + pid_pos_node['inputs']['latent_format'] = latent_format + pid_pos_node['inputs']['degrade_sigma'] = 0 + pid_pos_node['inputs']['positive'] = [pos_text_encode_id, 0] + pid_pos_node['inputs']['latent'] = [original_ksampler_id, 0] + assembler.workflow[pid_pos_id] = pid_pos_node + + pid_neg_id = assembler._get_unique_id() + pid_neg_node = assembler._get_node_template("PiDConditioning") + pid_neg_node['inputs']['latent_format'] = latent_format + pid_neg_node['inputs']['degrade_sigma'] = 0 + pid_neg_node['inputs']['positive'] = [neg_text_encode_id, 0] + pid_neg_node['inputs']['latent'] = [original_ksampler_id, 0] + assembler.workflow[pid_neg_id] = pid_neg_node + + pid_unet_loader_id = assembler._get_unique_id() + pid_unet_loader_node = assembler._get_node_template("UNETLoader") + pid_unet_loader_node['inputs']['unet_name'] = unet_name + pid_unet_loader_node['inputs']['weight_dtype'] = "default" + assembler.workflow[pid_unet_loader_id] = pid_unet_loader_node + + orig_width = 1024 + orig_height = 1024 + original_latent_source_id = assembler.node_map.get('latent_source') + if original_latent_source_id in assembler.workflow: + node_inputs = assembler.workflow[original_latent_source_id].get('inputs', {}) + if 'width' in node_inputs and 'height' in node_inputs: + orig_width = node_inputs['width'] + orig_height = node_inputs['height'] + else: + for node_data in assembler.workflow.values(): + inputs = node_data.get('inputs', {}) + if 'width' in inputs and 'height' in inputs and isinstance(inputs['width'], (int, float)) and isinstance(inputs['height'], (int, float)): + if 256 <= inputs['width'] <= 4096 and 256 <= inputs['height'] <= 4096: + orig_width = inputs['width'] + orig_height = inputs['height'] + break + else: + for node_data in assembler.workflow.values(): + inputs = node_data.get('inputs', {}) + if 'width' in inputs and 'height' in inputs and isinstance(inputs['width'], (int, float)) and isinstance(inputs['height'], (int, float)): + if 256 <= inputs['width'] <= 4096 and 256 <= inputs['height'] <= 4096: + orig_width = inputs['width'] + orig_height = inputs['height'] + break + + empty_latent_id = assembler._get_unique_id() + empty_latent_node = assembler._get_node_template("EmptyChromaRadianceLatentImage") + empty_latent_node['inputs']['width'] = int(orig_width) * 4 + empty_latent_node['inputs']['height'] = int(orig_height) * 4 + empty_latent_node['inputs']['batch_size'] = 1 + + if original_latent_source_id in assembler.workflow: + orig_batch_size = assembler.workflow[original_latent_source_id]['inputs'].get('batch_size') or assembler.workflow[original_latent_source_id]['inputs'].get('amount') + if orig_batch_size: + empty_latent_node['inputs']['batch_size'] = orig_batch_size + + assembler.workflow[empty_latent_id] = empty_latent_node + + orig_seed = 0 + if original_ksampler_id in assembler.workflow: + orig_seed = assembler.workflow[original_ksampler_id]['inputs'].get('seed', 0) + if orig_seed == -1: + orig_seed = random.randint(0, 2**32 - 1) + else: + orig_seed = (orig_seed + 1) % (2**32) + + new_ksampler_id = assembler._get_unique_id() + new_ksampler_node = assembler._get_node_template("KSampler") + new_ksampler_node['inputs']['seed'] = orig_seed + new_ksampler_node['inputs']['steps'] = 4 + new_ksampler_node['inputs']['cfg'] = 1 + new_ksampler_node['inputs']['sampler_name'] = "lcm" + new_ksampler_node['inputs']['scheduler'] = "simple" + new_ksampler_node['inputs']['denoise'] = 1.0 + new_ksampler_node['inputs']['model'] = [pid_unet_loader_id, 0] + new_ksampler_node['inputs']['positive'] = [pid_pos_id, 0] + new_ksampler_node['inputs']['negative'] = [pid_neg_id, 0] + new_ksampler_node['inputs']['latent_image'] = [empty_latent_id, 0] + assembler.workflow[new_ksampler_id] = new_ksampler_node + + pid_vae_loader_id = assembler._get_unique_id() + pid_vae_loader_node = assembler._get_node_template("VAELoader") + pid_vae_loader_node['inputs']['vae_name'] = "pixel_space" + assembler.workflow[pid_vae_loader_id] = pid_vae_loader_node + + pid_vae_decode_id = assembler._get_unique_id() + pid_vae_decode_node = assembler._get_node_template("VAEDecode") + pid_vae_decode_node['inputs']['samples'] = [new_ksampler_id, 0] + pid_vae_decode_node['inputs']['vae'] = [pid_vae_loader_id, 0] + assembler.workflow[pid_vae_decode_id] = pid_vae_decode_node + + if original_vae_decode_id: + for node_id, node_data in assembler.workflow.items(): + if 'inputs' in node_data: + for input_name, input_val in list(node_data['inputs'].items()): + if isinstance(input_val, list) and len(input_val) == 2: + if input_val[0] == original_vae_decode_id: + node_data['inputs'][input_name] = [pid_vae_decode_id, 0] + + is_vae_loader_referenced = False + if original_vae_loader_id: + for node_id, node_data in assembler.workflow.items(): + if node_id == original_vae_loader_id: + continue + for input_val in node_data.get('inputs', {}).values(): + if isinstance(input_val, list) and len(input_val) == 2: + if input_val[0] == original_vae_loader_id: + is_vae_loader_referenced = True + break + if is_vae_loader_referenced: + break + + if original_vae_loader_id in assembler.workflow and not is_vae_loader_referenced: + del assembler.workflow[original_vae_loader_id] + + if original_vae_decode_id in assembler.workflow: + del assembler.workflow[original_vae_decode_id] + + print("[PiD Injector] Successfully injected PiD pipeline and replaced VAE decode/loader.") diff --git a/chain_injectors/qwen_image_edit_injector.py b/chain_injectors/qwen_image_edit_injector.py new file mode 100644 index 0000000000000000000000000000000000000000..7dfcba736b8824fe30458da0ec80050d14c49087 --- /dev/null +++ b/chain_injectors/qwen_image_edit_injector.py @@ -0,0 +1,113 @@ +def create_node(assembler, class_type, title): + try: + node = assembler._get_node_template(class_type) + except Exception: + node = { + "inputs": {}, + "class_type": class_type, + "_meta": {"title": title} + } + node['_meta']['title'] = title + return node + +def inject(assembler, chain_definition, chain_items): + if not chain_items: + return + + valid_images = [] + for item in chain_items: + if not item: + continue + img_path = item + if isinstance(item, dict): + img_path = item.get('image') or item.get('filename') or item.get('path') + if img_path: + valid_images.append(img_path) + + if not valid_images: + return + + valid_images = valid_images[:3] + + ksampler_name = chain_definition.get('ksampler_node', 'ksampler') + pos_prompt_name = chain_definition.get('pos_prompt_node', 'pos_prompt') + neg_prompt_name = chain_definition.get('neg_prompt_node', 'neg_prompt') + vae_loader_name = chain_definition.get('vae_loader_node', 'vae_loader') + model_sampler_name = chain_definition.get('model_sampler_node', 'model_sampler') + + if ksampler_name not in assembler.node_map: + print(f"Warning: Target node '{ksampler_name}' for Qwen-Image Edit chain not found. Skipping.") + return + + ksampler_id = assembler.node_map[ksampler_name] + pos_prompt_id = assembler.node_map.get(pos_prompt_name) + neg_prompt_id = assembler.node_map.get(neg_prompt_name) + + if not pos_prompt_id or not neg_prompt_id: + print("Warning: Positive or negative prompt node not found for Qwen-Image Edit chain. Skipping.") + return + + vae_id = assembler.node_map.get(vae_loader_name) + if not vae_id: + for node_id, node in assembler.workflow.items(): + if isinstance(node, dict) and node.get('class_type') == 'VAELoader': + vae_id = node_id + break + + if vae_id: + assembler.workflow[pos_prompt_id]['inputs']['vae'] = [vae_id, 0] + assembler.workflow[neg_prompt_id]['inputs']['vae'] = [vae_id, 0] + + for i, img_filename in enumerate(valid_images): + load_id = assembler._get_unique_id() + load_node = create_node(assembler, "LoadImage", f"Load Reference Image {i+1}") + load_node['inputs']['image'] = img_filename + assembler.workflow[load_id] = load_node + + scale_id = assembler._get_unique_id() + scale_node = create_node(assembler, "ImageScaleToTotalPixels", f"Scale Reference {i+1}") + scale_node['inputs']['upscale_method'] = "lanczos" + scale_node['inputs']['megapixels'] = 1 + scale_node['inputs']['resolution_steps'] = 1 + scale_node['inputs']['image'] = [load_id, 0] + assembler.workflow[scale_id] = scale_node + + image_key = f"image{i+1}" + assembler.workflow[pos_prompt_id]['inputs'][image_key] = [scale_id, 0] + assembler.workflow[neg_prompt_id]['inputs'][image_key] = [scale_id, 0] + + pos_ref_id = assembler._get_unique_id() + pos_ref_node = create_node(assembler, "FluxKontextMultiReferenceLatentMethod", "Edit Model Reference Method") + pos_ref_node['inputs']['reference_latents_method'] = "index_timestep_zero" + pos_ref_node['inputs']['conditioning'] = [pos_prompt_id, 0] + assembler.workflow[pos_ref_id] = pos_ref_node + + neg_ref_id = assembler._get_unique_id() + neg_ref_node = create_node(assembler, "FluxKontextMultiReferenceLatentMethod", "Edit Model Reference Method") + neg_ref_node['inputs']['reference_latents_method'] = "index_timestep_zero" + neg_ref_node['inputs']['conditioning'] = [neg_prompt_id, 0] + assembler.workflow[neg_ref_id] = neg_ref_node + + assembler.workflow[ksampler_id]['inputs']['positive'] = [pos_ref_id, 0] + assembler.workflow[ksampler_id]['inputs']['negative'] = [neg_ref_id, 0] + + model_sampler_id = assembler.node_map.get(model_sampler_name) + if not model_sampler_id: + for node_id, node in assembler.workflow.items(): + if isinstance(node, dict) and node.get('class_type') == 'ModelSamplingAuraFlow': + model_sampler_id = node_id + break + + if model_sampler_id and model_sampler_id in assembler.workflow: + assembler.workflow[model_sampler_id]['inputs']['shift'] = 3 + + current_model_connection = assembler.workflow[ksampler_id]['inputs']['model'] + cfg_norm_id = assembler._get_unique_id() + cfg_norm_node = create_node(assembler, "CFGNorm", "CFGNorm") + cfg_norm_node['inputs']['strength'] = 1 + cfg_norm_node['inputs']['pre_cfg'] = False + cfg_norm_node['inputs']['model'] = current_model_connection + assembler.workflow[cfg_norm_id] = cfg_norm_node + assembler.workflow[ksampler_id]['inputs']['model'] = [cfg_norm_id, 0] + + print(f"Qwen-Image Edit injector applied with {len(valid_images)} reference image(s). Connected VAE dynamically.") diff --git a/chain_injectors/reference_image_injector.py b/chain_injectors/reference_image_injector.py new file mode 100644 index 0000000000000000000000000000000000000000..c588c1b593c0c2d84342277135014df126915ccf --- /dev/null +++ b/chain_injectors/reference_image_injector.py @@ -0,0 +1,64 @@ +import os + +def inject(assembler, chain_definition, chain_items): + if not chain_items: + return + + valid_images = [] + for item in chain_items: + if not item: + continue + img_path = item + if isinstance(item, dict): + img_path = item.get('image') or item.get('filename') or item.get('path') + if img_path: + valid_images.append(img_path) + + if not valid_images: + return + + text_encode_name = chain_definition.get('text_encode_node') + text_encode_id = None + if text_encode_name and text_encode_name in assembler.node_map: + text_encode_id = assembler.node_map[text_encode_name] + else: + for node_id, node in assembler.workflow.items(): + if isinstance(node, dict) and node.get('class_type') == 'TextEncodeMageFlowEdit': + text_encode_id = node_id + break + + if not text_encode_id or text_encode_id not in assembler.workflow: + print("Warning: TextEncodeMageFlowEdit node not found for Reference Image chain. Skipping.") + return + + vae_node_name = chain_definition.get('vae_node', 'vae_loader') + vae_node_id = assembler.node_map.get(vae_node_name) + if not vae_node_id: + for node_id, node in assembler.workflow.items(): + if isinstance(node, dict) and node.get('class_type') == 'VAELoader': + vae_node_id = node_id + break + + if vae_node_id: + assembler.workflow[text_encode_id]['inputs']['vae'] = [vae_node_id, 0] + + for i, img_filename in enumerate(valid_images): + load_id = assembler._get_unique_id() + load_node = assembler._get_node_template("LoadImage") + load_node['inputs']['image'] = img_filename + load_node['_meta']['title'] = f"Load Reference Image {i+1}" + assembler.workflow[load_id] = load_node + + scale_id = assembler._get_unique_id() + scale_node = assembler._get_node_template("ImageScaleToTotalPixels") + scale_node['inputs']['megapixels'] = 1.0 + scale_node['inputs']['upscale_method'] = "nearest-exact" + scale_node['inputs']['resolution_steps'] = 1 + scale_node['inputs']['image'] = [load_id, 0] + scale_node['_meta']['title'] = f"Scale Reference {i+1}" + assembler.workflow[scale_id] = scale_node + + input_key = f"images.image_{i+1}" + assembler.workflow[text_encode_id]['inputs'][input_key] = [scale_id, 0] + + print(f"Reference Image injector applied. Injected {len(valid_images)} reference images to TextEncodeMageFlowEdit node '{text_encode_id}'.") diff --git a/chain_injectors/reference_latent_injector.py b/chain_injectors/reference_latent_injector.py new file mode 100644 index 0000000000000000000000000000000000000000..4d17201e8120e634c7f3c14ffb1c6b98a6faf151 --- /dev/null +++ b/chain_injectors/reference_latent_injector.py @@ -0,0 +1,157 @@ +def inject(assembler, chain_definition, chain_items): + if not chain_items: + return + + guider_node_name = chain_definition.get('guider_node') + guider_target_inputs = chain_definition.get('guider_target_inputs', []) + start_connections_map = chain_definition.get('start_connections', {}) + vae_node_name = chain_definition.get('vae_node', 'vae_loader') + + if guider_node_name and guider_node_name in assembler.node_map and guider_target_inputs: + guider_id = assembler.node_map[guider_node_name] + if vae_node_name not in assembler.node_map: + print(f"Warning: VAE node '{vae_node_name}' not found for Guider chain. Skipping.") + return + vae_node_id = assembler.node_map[vae_node_name] + + print(f"ReferenceLatent injector targeting DualCFGGuider node '{guider_node_name}'.") + + current_connections = {} + for target_input in guider_target_inputs: + conn_str = start_connections_map.get(target_input) + if not conn_str: + print(f"Warning: No start connection defined for '{target_input}' in Guider chain. Skipping this input.") + continue + try: + node_name, idx_str = conn_str.split(':') + node_id = assembler.node_map[node_name] + current_connections[target_input] = [node_id, int(idx_str)] + except (ValueError, KeyError): + print(f"Warning: Invalid start connection '{conn_str}' for '{target_input}'. Skipping.") + + encoded_latents = [] + for i, img_filename in enumerate(chain_items): + load_id = assembler._get_unique_id() + load_node = assembler._get_node_template("LoadImage") + load_node['inputs']['image'] = img_filename + assembler.workflow[load_id] = load_node + + scale_id = assembler._get_unique_id() + scale_node = assembler._get_node_template("ImageScaleToTotalPixels") + scale_node['inputs']['megapixels'] = 1.0 + scale_node['inputs']['upscale_method'] = "lanczos" + scale_node['inputs']['image'] = [load_id, 0] + assembler.workflow[scale_id] = scale_node + + vae_encode_id = assembler._get_unique_id() + vae_encode_node = assembler._get_node_template("VAEEncode") + vae_encode_node['inputs']['pixels'] = [scale_id, 0] + vae_encode_node['inputs']['vae'] = [vae_node_id, 0] + assembler.workflow[vae_encode_id] = vae_encode_node + encoded_latents.append([vae_encode_id, 0]) + + for target_input_name, start_connection in current_connections.items(): + current_chain_head = start_connection + for i, latent_conn in enumerate(encoded_latents): + ref_latent_id = assembler._get_unique_id() + ref_latent_node = assembler._get_node_template("ReferenceLatent") + ref_latent_node['inputs']['conditioning'] = current_chain_head + ref_latent_node['inputs']['latent'] = latent_conn + ref_latent_node['_meta']['title'] = f"{target_input_name} RefLatent {i+1}" + assembler.workflow[ref_latent_id] = ref_latent_node + current_chain_head = [ref_latent_id, 0] + + assembler.workflow[guider_id]['inputs'][target_input_name] = current_chain_head + print(f" - Input '{target_input_name}' of node '{guider_node_name}' re-routed through {len(chain_items)} reference images.") + + return + + flux_guidance_name = chain_definition.get('flux_guidance_node') + ksampler_name = chain_definition.get('ksampler_node', 'ksampler') + + if ksampler_name not in assembler.node_map: + print(f"Warning: KSampler node '{ksampler_name}' not found for ReferenceLatent chain. Skipping.") + return + if vae_node_name not in assembler.node_map: + print(f"Warning: VAE loader node '{vae_node_name}' not found for ReferenceLatent chain. Skipping.") + return + + ksampler_id = assembler.node_map[ksampler_name] + vae_node_id = assembler.node_map[vae_node_name] + + pos_target_node_id = None + pos_target_input_name = None + if flux_guidance_name and flux_guidance_name in assembler.node_map: + flux_guidance_id = assembler.node_map[flux_guidance_name] + if 'conditioning' in assembler.workflow[flux_guidance_id]['inputs']: + pos_target_node_id = flux_guidance_id + pos_target_input_name = 'conditioning' + print(f"ReferenceLatent injector targeting FluxGuidance node '{flux_guidance_name}' for positive chain.") + + if not pos_target_node_id: + if 'positive' in assembler.workflow[ksampler_id]['inputs']: + pos_target_node_id = ksampler_id + pos_target_input_name = 'positive' + print(f"ReferenceLatent injector targeting KSampler node '{ksampler_name}' for positive chain.") + else: + print(f"Warning: Could not find a valid positive injection point for ReferenceLatent chain. Skipping.") + return + + current_pos_conditioning = assembler.workflow[pos_target_node_id]['inputs'][pos_target_input_name] + + neg_target_node_id = ksampler_id + neg_target_input_name = 'negative' + if 'negative' not in assembler.workflow[neg_target_node_id]['inputs']: + print(f"Warning: KSampler node '{ksampler_name}' has no 'negative' input. Skipping negative ReferenceLatent chain.") + neg_target_node_id = None + + current_neg_conditioning = None + if neg_target_node_id: + current_neg_conditioning = assembler.workflow[neg_target_node_id]['inputs'][neg_target_input_name] + + for i, img_filename in enumerate(chain_items): + load_id = assembler._get_unique_id() + load_node = assembler._get_node_template("LoadImage") + load_node['inputs']['image'] = img_filename + load_node['_meta']['title'] = f"Load Reference Image {i+1}" + assembler.workflow[load_id] = load_node + + scale_id = assembler._get_unique_id() + scale_node = assembler._get_node_template("ImageScaleToTotalPixels") + scale_node['inputs']['megapixels'] = 1.0 + scale_node['inputs']['upscale_method'] = "lanczos" + scale_node['inputs']['image'] = [load_id, 0] + scale_node['_meta']['title'] = f"Scale Reference {i+1}" + assembler.workflow[scale_id] = scale_node + + vae_encode_id = assembler._get_unique_id() + vae_encode_node = assembler._get_node_template("VAEEncode") + vae_encode_node['inputs']['pixels'] = [scale_id, 0] + vae_encode_node['inputs']['vae'] = [vae_node_id, 0] + vae_encode_node['_meta']['title'] = f"VAE Encode Reference {i+1}" + assembler.workflow[vae_encode_id] = vae_encode_node + + latent_conn = [vae_encode_id, 0] + + pos_ref_latent_id = assembler._get_unique_id() + pos_ref_latent_node = assembler._get_node_template("ReferenceLatent") + pos_ref_latent_node['inputs']['conditioning'] = current_pos_conditioning + pos_ref_latent_node['inputs']['latent'] = latent_conn + pos_ref_latent_node['_meta']['title'] = f"Positive ReferenceLatent {i+1}" + assembler.workflow[pos_ref_latent_id] = pos_ref_latent_node + current_pos_conditioning = [pos_ref_latent_id, 0] + + if neg_target_node_id: + neg_ref_latent_id = assembler._get_unique_id() + neg_ref_latent_node = assembler._get_node_template("ReferenceLatent") + neg_ref_latent_node['inputs']['conditioning'] = current_neg_conditioning + neg_ref_latent_node['inputs']['latent'] = latent_conn + neg_ref_latent_node['_meta']['title'] = f"Negative ReferenceLatent {i+1}" + assembler.workflow[neg_ref_latent_id] = neg_ref_latent_node + current_neg_conditioning = [neg_ref_latent_id, 0] + + assembler.workflow[pos_target_node_id]['inputs'][pos_target_input_name] = current_pos_conditioning + if neg_target_node_id: + assembler.workflow[neg_target_node_id]['inputs'][neg_target_input_name] = current_neg_conditioning + + print(f"ReferenceLatent injector applied. Re-routed inputs through {len(chain_items)} reference images.") diff --git a/chain_injectors/sd3_ipadapter_injector.py b/chain_injectors/sd3_ipadapter_injector.py new file mode 100644 index 0000000000000000000000000000000000000000..4b1496c858c7b69e6a412da546f47c1c6cae591b --- /dev/null +++ b/chain_injectors/sd3_ipadapter_injector.py @@ -0,0 +1,66 @@ +def inject(assembler, chain_definition, chain_items): + if not chain_items: + return + + ksampler_name = chain_definition.get('ksampler_node', 'ksampler') + if ksampler_name not in assembler.node_map: + print(f"Warning: KSampler node '{ksampler_name}' not found for SD3 IPAdapter chain. Skipping.") + return + + ksampler_id = assembler.node_map[ksampler_name] + + if 'model' not in assembler.workflow[ksampler_id]['inputs']: + print(f"Warning: KSampler node '{ksampler_name}' is missing 'model' input. Skipping SD3 IPAdapter chain.") + return + + current_model_connection = assembler.workflow[ksampler_id]['inputs']['model'] + + clip_vision_loader_id = assembler._get_unique_id() + clip_vision_loader_node = assembler._get_node_template("CLIPVisionLoader") + clip_vision_loader_node['inputs']['clip_name'] = "sigclip_vision_patch14_384.safetensors" + assembler.workflow[clip_vision_loader_id] = clip_vision_loader_node + + ipadapter_loader_id = assembler._get_unique_id() + ipadapter_loader_node = assembler._get_node_template("IPAdapterSD3Loader") + ipadapter_loader_node['inputs']['ipadapter'] = "ip-adapter_sd35l_instantx.bin" + ipadapter_loader_node['inputs']['provider'] = "cuda" + assembler.workflow[ipadapter_loader_id] = ipadapter_loader_node + + for item_data in chain_items: + image_loader_id = assembler._get_unique_id() + image_loader_node = assembler._get_node_template("LoadImage") + image_loader_node['inputs']['image'] = item_data['image'] + assembler.workflow[image_loader_id] = image_loader_node + + image_scaler_id = assembler._get_unique_id() + image_scaler_node = assembler._get_node_template("ImageScaleToTotalPixels") + image_scaler_node['inputs']['image'] = [image_loader_id, 0] + image_scaler_node['inputs']['upscale_method'] = 'nearest-exact' + image_scaler_node['inputs']['megapixels'] = 1.0 + assembler.workflow[image_scaler_id] = image_scaler_node + + clip_vision_encode_id = assembler._get_unique_id() + clip_vision_encode_node = assembler._get_node_template("CLIPVisionEncode") + clip_vision_encode_node['inputs']['crop'] = "center" + clip_vision_encode_node['inputs']['clip_vision'] = [clip_vision_loader_id, 0] + clip_vision_encode_node['inputs']['image'] = [image_scaler_id, 0] + assembler.workflow[clip_vision_encode_id] = clip_vision_encode_node + + apply_ipa_id = assembler._get_unique_id() + apply_ipa_node = assembler._get_node_template("ApplyIPAdapterSD3") + + apply_ipa_node['inputs']['weight'] = item_data.get('weight', 1.0) + apply_ipa_node['inputs']['start_percent'] = item_data.get('start_percent', 0.0) + apply_ipa_node['inputs']['end_percent'] = item_data.get('end_percent', 1.0) + + apply_ipa_node['inputs']['model'] = current_model_connection + apply_ipa_node['inputs']['ipadapter'] = [ipadapter_loader_id, 0] + apply_ipa_node['inputs']['image_embed'] = [clip_vision_encode_id, 0] + + assembler.workflow[apply_ipa_id] = apply_ipa_node + + current_model_connection = [apply_ipa_id, 0] + + assembler.workflow[ksampler_id]['inputs']['model'] = current_model_connection + + print(f"SD3 IPAdapter injector applied. KSampler model input re-routed through {len(chain_items)} IPAdapter(s).") diff --git a/chain_injectors/style_injector.py b/chain_injectors/style_injector.py new file mode 100644 index 0000000000000000000000000000000000000000..65f5f5522b0763248398bbce5cb71962ec674939 --- /dev/null +++ b/chain_injectors/style_injector.py @@ -0,0 +1,71 @@ +def inject(assembler, chain_definition, chain_items): + if not chain_items: + return + + flux_guidance_name = chain_definition.get('flux_guidance_node') + ksampler_name = chain_definition.get('ksampler_node', 'ksampler') + + target_node_id = None + target_input_name = None + + if flux_guidance_name and flux_guidance_name in assembler.node_map: + flux_guidance_id = assembler.node_map[flux_guidance_name] + if 'conditioning' in assembler.workflow[flux_guidance_id]['inputs']: + target_node_id = flux_guidance_id + target_input_name = 'conditioning' + + if not target_node_id: + if ksampler_name in assembler.node_map: + ksampler_id = assembler.node_map[ksampler_name] + if 'positive' in assembler.workflow[ksampler_id]['inputs']: + target_node_id = ksampler_id + target_input_name = 'positive' + else: + return + + if not target_node_id: + return + + current_conditioning = assembler.workflow[target_node_id]['inputs'][target_input_name] + + style_model_loader_id = assembler._get_unique_id() + style_model_loader_node = assembler._get_node_template("StyleModelLoader") + style_model_loader_node['inputs']['style_model_name'] = "flux1-redux-dev.safetensors" + assembler.workflow[style_model_loader_id] = style_model_loader_node + + clip_vision_loader_id = assembler._get_unique_id() + clip_vision_loader_node = assembler._get_node_template("CLIPVisionLoader") + clip_vision_loader_node['inputs']['clip_name'] = "sigclip_vision_patch14_384.safetensors" + assembler.workflow[clip_vision_loader_id] = clip_vision_loader_node + + for item_data in chain_items: + image = item_data.get('image') + strength = item_data.get('strength', 1.0) + if not image or strength is None: + continue + + load_image_id = assembler._get_unique_id() + clip_vision_encode_id = assembler._get_unique_id() + style_apply_id = assembler._get_unique_id() + + load_image_node = assembler._get_node_template("LoadImage") + clip_vision_encode_node = assembler._get_node_template("CLIPVisionEncode") + style_apply_node = assembler._get_node_template("StyleModelApply") + + load_image_node['inputs']['image'] = image + clip_vision_encode_node['inputs']['crop'] = "center" + clip_vision_encode_node['inputs']['clip_vision'] = [clip_vision_loader_id, 0] + clip_vision_encode_node['inputs']['image'] = [load_image_id, 0] + + style_apply_node['inputs']['strength'] = strength + style_apply_node['inputs']['strength_type'] = "multiply" + style_apply_node['inputs']['conditioning'] = current_conditioning + style_apply_node['inputs']['style_model'] = [style_model_loader_id, 0] + style_apply_node['inputs']['clip_vision_output'] = [clip_vision_encode_id, 0] + + assembler.workflow[load_image_id] = load_image_node + assembler.workflow[clip_vision_encode_id] = clip_vision_encode_node + assembler.workflow[style_apply_id] = style_apply_node + current_conditioning = [style_apply_id, 0] + + assembler.workflow[target_node_id]['inputs'][target_input_name] = current_conditioning diff --git a/chain_injectors/vae_injector.py b/chain_injectors/vae_injector.py new file mode 100644 index 0000000000000000000000000000000000000000..0bbad59ea5b6a04617349f45932520bc288fa786 --- /dev/null +++ b/chain_injectors/vae_injector.py @@ -0,0 +1,30 @@ +def inject(assembler, chain_definition, chain_items): + if not chain_items: + return + + vae_name = chain_items[0] if isinstance(chain_items, list) else chain_items + if not vae_name or vae_name == "None": + return + + targets = chain_definition.get('targets', []) + if not targets: + return + + vae_loader_id = assembler._get_unique_id() + vae_loader_node = assembler._get_node_template("VAELoader") + vae_loader_node['inputs']['vae_name'] = vae_name + assembler.workflow[vae_loader_id] = vae_loader_node + + injected_count = 0 + for target_str in targets: + try: + node_name, input_name = target_str.split(':') + if node_name in assembler.node_map: + node_id = assembler.node_map[node_name] + assembler.workflow[node_id]['inputs'][input_name] = [vae_loader_id, 0] + injected_count += 1 + except ValueError: + print(f"Warning: Invalid VAE injector target format '{target_str}'. Expected 'node_name:input_name'.") + + if injected_count > 0: + print(f"VAE injector applied. Rerouted {injected_count} connection(s) to new VAELoader ({vae_name}).") diff --git a/comfy_integration/__init__.py b/comfy_integration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/comfy_integration/nodes.py b/comfy_integration/nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..8e613a7fe9812963a3c1755060cadb5fef93964d --- /dev/null +++ b/comfy_integration/nodes.py @@ -0,0 +1,44 @@ +import asyncio +import execution +import server +from nodes import ( + init_extra_nodes, CheckpointLoaderSimple, EmptyLatentImage, KSampler, + VAEDecode, SaveImage, NODE_CLASS_MAPPINGS, LoadImage, VAEEncode, + VAEEncodeForInpaint, ImagePadForOutpaint, LatentUpscaleBy, RepeatLatentBatch +) + + +def import_custom_nodes() -> None: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + server_instance = server.PromptServer(loop) + execution.PromptQueue(server_instance) + + loop.run_until_complete(init_extra_nodes()) + +import_custom_nodes() + +CLIPTextEncode = NODE_CLASS_MAPPINGS['CLIPTextEncode'] +CLIPTextEncodeSDXL = NODE_CLASS_MAPPINGS['CLIPTextEncodeSDXL'] +LoraLoader = NODE_CLASS_MAPPINGS['LoraLoader'] +CLIPSetLastLayer = NODE_CLASS_MAPPINGS['CLIPSetLastLayer'] + +if 'EmptyHunyuanImageLatent' in NODE_CLASS_MAPPINGS: + EmptyHunyuanImageLatent = NODE_CLASS_MAPPINGS['EmptyHunyuanImageLatent'] +else: + print("⚠️ Warning: 'EmptyHunyuanImageLatent' not found in NODE_CLASS_MAPPINGS. HunyuanImage txt2img may fail if this node is required.") + +try: + KSamplerNode = NODE_CLASS_MAPPINGS['KSampler'] + SAMPLER_CHOICES = KSamplerNode.INPUT_TYPES()["required"]["sampler_name"][0] + SCHEDULER_CHOICES = KSamplerNode.INPUT_TYPES()["required"]["scheduler"][0] +except Exception: + print("⚠️ Could not dynamically get sampler/scheduler choices, using fallback list.") + SAMPLER_CHOICES = ['euler', 'dpmpp_2m_sde_gpu'] + SCHEDULER_CHOICES = ['normal', 'karras'] + +checkpointloadersimple = CheckpointLoaderSimple() +loraloader = LoraLoader() + + +print("✅ ComfyUI custom nodes and class mappings are ready.") diff --git a/comfy_integration/setup.py b/comfy_integration/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..3afc0cb08a3022033de82ef5d57edc7594a9b604 --- /dev/null +++ b/comfy_integration/setup.py @@ -0,0 +1,161 @@ +"""Install the pinned ComfyUI runtime without overwriting application code.""" + +from __future__ import annotations + +import os +import shutil +import subprocess +import sys +from pathlib import Path + +import yaml + +from core.settings import CATEGORY_TO_DIR_MAP, INPUT_DIR, OUTPUT_DIR + + +APP_DIR = Path(__file__).resolve().parents[1] +LOCK_FILE = APP_DIR / "vendor.lock.yaml" +VENDOR_DIR = APP_DIR / "_vendor" +CUSTOM_NODES_DIR = APP_DIR / "custom_nodes" + + +def _bounded_env_int(name: str, default: int, minimum: int, maximum: int) -> int: + try: + value = int(os.getenv(name, str(default))) + except ValueError: + value = default + return max(minimum, min(maximum, value)) + + +GIT_TIMEOUT_SECONDS = _bounded_env_int( + "IMAGEGEN_GIT_TIMEOUT_SECONDS", 180, 30, 900 +) +GIT_NETWORK_ATTEMPTS = _bounded_env_int("IMAGEGEN_GIT_ATTEMPTS", 2, 1, 5) + + +def _run_git(*args: str, cwd: Path | None = None) -> str: + attempts = GIT_NETWORK_ATTEMPTS if args and args[0] == "fetch" else 1 + for attempt in range(1, attempts + 1): + try: + completed = subprocess.run( + ["git", *args], + cwd=str(cwd) if cwd else None, + check=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + timeout=GIT_TIMEOUT_SECONDS, + ) + return completed.stdout.strip() + except subprocess.TimeoutExpired as exc: + if attempt == attempts: + raise RuntimeError( + f"Git 操作超过 {GIT_TIMEOUT_SECONDS} 秒:git {args[0]}。" + "可稍后重启,或设置 COMFYUI_PATH 使用本地 checkout。" + ) from exc + print(f"⚠️ Git {args[0]} 超时,正在重试({attempt}/{attempts})…") + except subprocess.CalledProcessError: + if attempt == attempts: + raise + print(f"⚠️ Git {args[0]} 失败,正在重试({attempt}/{attempts})…") + raise RuntimeError("Unreachable git retry state") + + +def _ensure_pinned_repo(name: str, url: str, revision: str, destination: Path) -> None: + if destination.exists() and not (destination / ".git").is_dir(): + raise RuntimeError( + f"{name} 目录已存在但不是 Git 仓库:{destination}。" + "请移走该目录后重新启动。" + ) + + if not destination.exists(): + destination.parent.mkdir(parents=True, exist_ok=True) + print(f"--- [Vendor] Cloning pinned {name} ---") + partial = destination.with_name(f"{destination.name}.partial") + last_error = None + for attempt in range(1, GIT_NETWORK_ATTEMPTS + 1): + if partial.exists(): + shutil.rmtree(partial) + try: + _run_git( + "clone", "--filter=blob:none", "--no-checkout", url, str(partial) + ) + partial.replace(destination) + last_error = None + break + except (subprocess.CalledProcessError, RuntimeError) as exc: + last_error = exc + if attempt < GIT_NETWORK_ATTEMPTS: + print(f"⚠️ {name} clone 失败,正在重试({attempt}/{GIT_NETWORK_ATTEMPTS})…") + if last_error is not None: + raise RuntimeError( + f"无法拉取 {name}。可稍后重启;本地离线运行可设置 " + "COMFYUI_PATH,并按需设置 IMAGEGEN_SKIP_CUSTOM_NODES=1。" + ) from last_error + + current = "" + try: + current = _run_git("rev-parse", "HEAD", cwd=destination) + except (subprocess.CalledProcessError, RuntimeError): + pass + + if current != revision: + print(f"--- [Vendor] Checking out {name} @ {revision[:12]} ---") + _run_git("fetch", "--depth", "1", "origin", revision, cwd=destination) + _run_git("checkout", "--detach", "--force", "FETCH_HEAD", cwd=destination) + + actual = _run_git("rev-parse", "HEAD", cwd=destination) + if actual != revision: + raise RuntimeError( + f"{name} 版本不匹配:期望 {revision},实际 {actual}。" + ) + print(f"✅ {name} ready @ {actual[:12]}") + + +def _load_lock() -> dict: + with LOCK_FILE.open("r", encoding="utf-8") as handle: + data = yaml.safe_load(handle) or {} + if "comfyui" not in data: + raise RuntimeError(f"Missing comfyui entry in {LOCK_FILE}") + return data + + +def initialize_comfyui() -> Path: + """Prepare pinned sources and make ComfyUI importable. + + Set ``COMFYUI_PATH`` to use an existing local checkout. This is the + recommended offline/local-development route. + """ + + lock = _load_lock() + configured_path = os.getenv("COMFYUI_PATH", "").strip() + + if configured_path: + comfyui_path = Path(configured_path).expanduser().resolve() + if not (comfyui_path / "nodes.py").is_file(): + raise RuntimeError(f"COMFYUI_PATH is not a ComfyUI checkout: {comfyui_path}") + else: + comfyui_path = VENDOR_DIR / "ComfyUI" + comfy = lock["comfyui"] + _ensure_pinned_repo("ComfyUI", comfy["url"], comfy["revision"], comfyui_path) + + CUSTOM_NODES_DIR.mkdir(parents=True, exist_ok=True) + if os.getenv("IMAGEGEN_SKIP_CUSTOM_NODES", "0").lower() not in {"1", "true", "yes"}: + for name, spec in (lock.get("custom_nodes") or {}).items(): + _ensure_pinned_repo(name, spec["url"], spec["revision"], CUSTOM_NODES_DIR / name) + + # ComfyUI contains a top-level `utils` package. The application uses the + # collision-free `imagegen_utils` package, so ComfyUI can safely come first. + comfyui_str = str(comfyui_path) + if comfyui_str not in sys.path: + sys.path.insert(0, comfyui_str) + + for relative_path in CATEGORY_TO_DIR_MAP.values(): + (APP_DIR / relative_path).mkdir(parents=True, exist_ok=True) + (APP_DIR / INPUT_DIR).mkdir(parents=True, exist_ok=True) + (APP_DIR / OUTPUT_DIR).mkdir(parents=True, exist_ok=True) + + import comfy.model_management # noqa: F401 + + print(f"✅ ComfyUI initialized from isolated path: {comfyui_path}") + return comfyui_path diff --git a/core/__init__.py b/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/core/execution_plan.py b/core/execution_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..64f3cb81b9ab9b74298d1e381aaa19ecc8d3606c --- /dev/null +++ b/core/execution_plan.py @@ -0,0 +1,450 @@ +"""Build small sequential generation plans for PK and multi-image workflows. + +The in-process ComfyUI runtime is intentionally single-model-at-a-time. This +module therefore expands comparisons into bounded sequential runs instead of +trying to keep several checkpoints resident on one ZeroGPU allocation. +""" + +from __future__ import annotations + +import random +from collections.abc import Callable, Iterable, Sequence +from dataclasses import dataclass +from itertools import pairwise +from pathlib import Path +from typing import Any + +from PIL import Image + +from core.model_capabilities import supports_chain_for_model +from core.runtime_config import CONFIG +from core.settings import ( + ARCHITECTURES_CONFIG, + FEATURES_CONFIG, + MODEL_DEFAULTS_CONFIG, + MODEL_MAP_CHECKPOINT, + MODEL_TYPE_MAP, +) + +MODE_SINGLE = "single" +MODE_MODEL_PK = "model_pk" +MODE_MULTI_INDEPENDENT = "multi_independent" +MODE_MULTI_MODEL_GRID = "multi_model_grid" +MODE_MULTI_REFERENCE = "multi_reference" + +RUN_MODE_CHOICES = [ + ("普通生成", MODE_SINGLE), + ("模型 PK:同一输入对比多个模型", MODE_MODEL_PK), + ("多图独立:每张图分别处理", MODE_MULTI_INDEPENDENT), + ("多图 × 多模型:组合对比", MODE_MULTI_MODEL_GRID), + ("多图融合:多张参考图生成一组结果", MODE_MULTI_REFERENCE), +] + +INDEPENDENT_IMAGE_TASK_KEYS = { + "img2img": "img2img_image", + "outpaint": "outpaint_image", + "hires_fix": "hires_image", +} + +COMPARISON_CHAIN_INPUT_KEYS = ( + "lora_data", + "controlnet_data", + "anima_controlnet_lllite_data", + "diffsynth_controlnet_data", + "krea2_controlnet_data", + "ipadapter_data", + "sd3_ipadapter_chain", + "flux1_ipadapter_data", + "style_data", + "embedding_data", + "conditioning_data", + "reference_latent_data", + "hidream_o1_reference_data", + "joyai_reference_data", + "krea2_identity_edit_data", + "krea2_reference_edit_data", + "qwen_image_edit_data", + "boogu_edit_data", + "reference_image_data", +) + +# (chain name, pipeline input key, maximum images supported by its injector) +REFERENCE_CHAIN_SPECS = { + "qwen_image_edit": ("qwen_image_edit_data", 3), + "joyai_image": ("joyai_reference_data", 2), + "boogu_image_edit": ("boogu_edit_data", 10), + "reference_image": ("reference_image_data", 10), + "reference_latent": ("reference_latent_data", 10), + "hidream_o1_reference": ("hidream_o1_reference_data", 10), + "krea2_identity_edit": ("krea2_identity_edit_data", 2), + "krea2_style_reference": ("krea2_reference_edit_data", 3), +} + + +class ExecutionPlanError(ValueError): + pass + + +@dataclass(frozen=True) +class PlannedGeneration: + inputs: dict[str, Any] + caption: str + + +def _unique(values: Iterable[str]) -> list[str]: + return list(dict.fromkeys(value for value in values if value)) + + +def _caption(label: str, values: dict[str, Any]) -> str: + seed = values.get("seed", "-") + steps = values.get("num_inference_steps", "-") + cfg = values.get("guidance_scale", "-") + return f"{label} · Seed {seed} · {steps} 步 · CFG {cfg}" + + +def _workflow_type(model_name: str) -> str: + architecture = MODEL_TYPE_MAP.get(model_name, "SDXL") + architecture_info = ARCHITECTURES_CONFIG.get("architectures", {}).get( + architecture, {} + ) + return architecture_info.get( + "model_type", architecture.lower().replace(" ", "").replace(".", "") + ) + + +def _model_defaults(model_name: str) -> dict[str, Any]: + workflow_type = _workflow_type(model_name) + defaults = { + "steps": 25, + "cfg": 7.0, + "sampler_name": "euler", + "scheduler": "simple", + } + defaults.update(MODEL_DEFAULTS_CONFIG.get("Default", {})) + type_key = next( + ( + key + for key in MODEL_DEFAULTS_CONFIG + if key.lower().replace(" ", "-").replace(".", "") + == workflow_type.lower() + ), + None, + ) + if type_key: + section = MODEL_DEFAULTS_CONFIG.get(type_key, {}) + defaults.update(section.get("_defaults", {})) + defaults.update(section.get(model_name, {})) + return defaults + + +def _for_model( + base_inputs: dict[str, Any], model_name: str, use_model_defaults: bool +) -> dict[str, Any]: + # Pipeline processing replaces and occasionally mutates chain containers. + # Copy those containers while sharing immutable/PIL payloads. + values = { + key: list(value) + if isinstance(value, list) + else dict(value) + if isinstance(value, dict) + else value + for key, value in base_inputs.items() + } + values["model_display_name"] = model_name + if use_model_defaults: + defaults = _model_defaults(model_name) + values.update( + { + "num_inference_steps": defaults.get("steps", 20), + "guidance_scale": defaults.get("cfg", 1.0), + "sampler": defaults.get("sampler_name", "euler"), + "scheduler": defaults.get("scheduler", "simple"), + } + ) + return values + + +def _make_fair_comparison(values: dict[str, Any]) -> None: + """Keep V1 comparisons to capabilities shared by every base checkpoint.""" + + for key in COMPARISON_CHAIN_INPUT_KEYS: + values[key] = [] + values["pid_settings"] = "OFF" + values["vae_source"] = None + values["vae_id"] = None + values["vae_file"] = None + + +def load_uploaded_images(uploaded_files: Sequence[Any] | None) -> list[Image.Image]: + """Materialize Gradio File values as detached PIL images.""" + + images: list[Image.Image] = [] + total_megapixels = 0.0 + for item in uploaded_files or []: + raw_path = getattr(item, "name", item) + if not raw_path: + continue + path = Path(str(raw_path)) + if not path.is_file(): + raise ExecutionPlanError(f"找不到上传图片:{path.name}") + try: + with Image.open(path) as source: + source.load() + megapixels = (source.width * source.height) / 1_000_000 + if megapixels > CONFIG.max_input_megapixels: + raise ExecutionPlanError( + f"图片“{path.name}”为 {megapixels:.1f} MP,超过单图上限 " + f"{CONFIG.max_input_megapixels:g} MP。" + ) + total_megapixels += megapixels + if total_megapixels > CONFIG.max_reference_megapixels: + raise ExecutionPlanError( + f"上传图片累计为 {total_megapixels:.1f} MP,超过上限 " + f"{CONFIG.max_reference_megapixels:g} MP;请缩小图片或减少数量。" + ) + images.append(source.convert("RGB").copy()) + except ExecutionPlanError: + raise + except Exception as exc: + raise ExecutionPlanError(f"无法读取图片“{path.name}”:{exc}") from exc + + if len(images) > CONFIG.max_multi_images: + raise ExecutionPlanError( + f"一次最多上传 {CONFIG.max_multi_images} 张图片;当前为 {len(images)} 张。" + ) + return images + + +def _pick_reference_chain(model_name: str, role: str) -> tuple[str, str, int]: + workflow_type = _workflow_type(model_name) + enabled = set( + FEATURES_CONFIG.get(workflow_type, {}).get("enabled_chains", []) + ) + + if role == "identity": + order = ["krea2_identity_edit"] + elif role == "style": + # The generic FLUX style injector has a different image/weight schema; + # keep this high-level path limited to the validated Krea reference chain. + order = ["krea2_style_reference"] + else: + order = [ + "qwen_image_edit", + "joyai_image", + "boogu_image_edit", + "reference_image", + "reference_latent", + "hidream_o1_reference", + "krea2_identity_edit", + "krea2_style_reference", + ] + + for chain_name in order: + if ( + chain_name in enabled + and chain_name in REFERENCE_CHAIN_SPECS + and supports_chain_for_model(model_name, chain_name) + ): + input_key, maximum = REFERENCE_CHAIN_SPECS[chain_name] + return chain_name, input_key, maximum + + if role in {"identity", "style"}: + raise ExecutionPlanError( + f"模型“{model_name}”不支持所选的{('身份' if role == 'identity' else '风格')}参考方式。" + ) + raise ExecutionPlanError( + f"模型“{model_name}”没有可自动使用的多图参考链;请换用编辑/多模态模型。" + ) + + +def build_execution_plan( + base_inputs: dict[str, Any], + mode: str = MODE_SINGLE, + extra_models: Sequence[str] | None = None, + images: Sequence[Image.Image] | None = None, + reference_role: str = "auto", + use_model_defaults: bool = True, +) -> list[PlannedGeneration]: + """Expand one UI submission into a bounded list of sequential runs.""" + + if mode not in {choice[1] for choice in RUN_MODE_CHOICES}: + raise ExecutionPlanError(f"未知运行模式:{mode}") + + base_model = str(base_inputs.get("model_display_name") or "") + if base_model not in MODEL_MAP_CHECKPOINT: + raise ExecutionPlanError("请先选择有效模型。") + + comparison_mode = mode in {MODE_MODEL_PK, MODE_MULTI_MODEL_GRID} + models = _unique( + [base_model, *(extra_models or [])] if comparison_mode else [base_model] + ) + unknown_models = [name for name in models if name not in MODEL_MAP_CHECKPOINT] + if unknown_models: + raise ExecutionPlanError(f"未知模型:{', '.join(unknown_models)}") + if len(models) > CONFIG.max_pk_models: + raise ExecutionPlanError( + f"模型 PK 最多 {CONFIG.max_pk_models} 个模型;当前为 {len(models)} 个。" + ) + + if mode in {MODE_MODEL_PK, MODE_MULTI_MODEL_GRID} and len(models) < 2: + raise ExecutionPlanError("模型 PK 至少需要再选择 1 个对比模型。") + + source_images = list(images or []) + shared_seed = base_inputs.get("seed", -1) + try: + shared_seed = int(shared_seed) + except (TypeError, ValueError): + shared_seed = -1 + if shared_seed < 0 and mode != MODE_SINGLE: + shared_seed = random.randint(0, 2**32 - 1) + + plan: list[PlannedGeneration] = [] + if mode == MODE_SINGLE: + plan.append(PlannedGeneration(dict(base_inputs), base_model)) + + elif mode == MODE_MODEL_PK: + for model_name in models: + values = _for_model(base_inputs, model_name, use_model_defaults) + _make_fair_comparison(values) + values["seed"] = shared_seed + plan.append( + PlannedGeneration(values, _caption(f"模型 PK · {model_name}", values)) + ) + + elif mode in {MODE_MULTI_INDEPENDENT, MODE_MULTI_MODEL_GRID}: + task_type = str(base_inputs.get("task_type") or "") + task_input_key = INDEPENDENT_IMAGE_TASK_KEYS.get(task_type) + if not task_input_key: + raise ExecutionPlanError( + "多图独立处理仅支持图生图、扩图和高清修复;局部重绘需要逐张绘制蒙版。" + ) + if not source_images: + raise ExecutionPlanError("请上传至少 1 张批量输入图片。") + target_models = models if mode == MODE_MULTI_MODEL_GRID else [base_model] + # Keep one checkpoint active for all its inputs before switching. This + # avoids needless reloads while preserving Gallery captions by source. + for model_name in target_models: + for image_index, image in enumerate(source_images, start=1): + values = _for_model( + base_inputs, + model_name, + use_model_defaults if mode == MODE_MULTI_MODEL_GRID else False, + ) + if mode == MODE_MULTI_MODEL_GRID: + _make_fair_comparison(values) + values["seed"] = shared_seed + values[task_input_key] = image + caption = _caption(f"输入 {image_index} · {model_name}", values) + plan.append(PlannedGeneration(values, caption)) + + elif mode == MODE_MULTI_REFERENCE: + if str(base_inputs.get("task_type")) != "txt2img": + raise ExecutionPlanError("多图融合请把任务切换为“文生图”;参考图会直接进入编辑模型。") + if not source_images: + raise ExecutionPlanError("多图融合需要上传至少 1 张参考图。") + chain_name, input_key, maximum = _pick_reference_chain( + base_model, reference_role + ) + if len(source_images) > maximum: + raise ExecutionPlanError( + f"当前模型的 {chain_name} 最多支持 {maximum} 张参考图。" + ) + values = _for_model(base_inputs, base_model, False) + existing = [value for value in values.get(input_key, []) if value is not None] + values[input_key] = [*existing, *source_images][:maximum] + values["seed"] = shared_seed + plan.append( + PlannedGeneration( + values, + _caption( + f"多图融合 · {base_model} · {len(source_images)} 张参考图", + values, + ), + ) + ) + + if len(plan) > CONFIG.max_plan_jobs: + raise ExecutionPlanError( + f"本次会产生 {len(plan)} 个任务,超过上限 {CONFIG.max_plan_jobs};请减少图片或模型。" + ) + batch_size = max(1, int(base_inputs.get("batch_size") or 1)) + estimated_outputs = len(plan) * batch_size + if estimated_outputs > CONFIG.max_plan_outputs: + raise ExecutionPlanError( + f"预计输出 {estimated_outputs} 张,超过上限 {CONFIG.max_plan_outputs};" + "请减少模型、输入图片或单次生成数量。" + ) + # Release Comfy's global model state only at an actual model boundary. The + # final model remains warm for a likely follow-up generation. + for current, following in pairwise(plan): + if ( + current.inputs.get("model_display_name") + != following.inputs.get("model_display_name") + ): + current.inputs["_release_models_after_run"] = True + return plan + + +class _PlanProgress: + def __init__(self, parent: Any, index: int, total: int, caption: str): + self.parent = parent + self.index = index + self.total = total + self.caption = caption + + def __call__(self, value: float = 0.0, desc: str | None = None): + if not self.parent: + return None + try: + fraction = max(0.0, min(1.0, float(value))) + except (TypeError, ValueError): + fraction = 0.0 + overall = (self.index + fraction) / self.total + detail = f"[{self.index + 1}/{self.total}] {self.caption}" + if desc: + detail += f" · {desc}" + return self.parent(overall, desc=detail) + + +def execute_generation_plan( + plan: Sequence[PlannedGeneration], + generate: Callable[[dict[str, Any], Any], Any], + progress: Any = None, + cancel_event: Any = None, +) -> tuple[list[Any], str]: + """Run the plan sequentially and retain partial successes.""" + + gallery: list[Any] = [] + summary: list[str] = [] + total = max(1, len(plan)) + for index, item in enumerate(plan): + if cancel_event is not None and cancel_event.is_set(): + if gallery: + summary.append("- ⏹️ 已取消:后续组合未执行,已保留成功结果。") + break + raise ExecutionPlanError("任务已取消,后续组合未执行。") + try: + result = generate( + item.inputs, + _PlanProgress(progress, index, total, item.caption), + ) + paths = result if isinstance(result, list) else ([result] if result else []) + for output_index, path in enumerate(paths, start=1): + caption = item.caption + if len(paths) > 1: + caption += f" · 结果 {output_index}" + gallery.append((path, caption)) + summary.append(f"- ✅ {item.caption}:{len(paths)} 张") + except Exception as exc: + if cancel_event is not None and cancel_event.is_set(): + if gallery: + summary.append("- ⏹️ 已取消:后续组合未执行,已保留成功结果。") + break + raise + summary.append(f"- ❌ {item.caption}:{exc}") + + if not gallery: + raise ExecutionPlanError("本次任务没有成功生成图片。\n" + "\n".join(summary)) + if progress: + progress(1.0, desc="全部组合执行完成。") + return gallery, "### 本次执行\n" + "\n".join(summary) diff --git a/core/generation_logic.py b/core/generation_logic.py new file mode 100644 index 0000000000000000000000000000000000000000..88c71a59af9c5cb844942416e8b9c64f59672332 --- /dev/null +++ b/core/generation_logic.py @@ -0,0 +1,10 @@ +from typing import Any, Dict +import gradio as gr + +from core.pipelines.sd_image_pipeline import SdImagePipeline + +sd_image_pipeline = SdImagePipeline() + + +def generate_image_wrapper(ui_inputs: dict, progress=gr.Progress(track_tqdm=True)): + return sd_image_pipeline.run(ui_inputs=ui_inputs, progress=progress) diff --git a/core/model_capabilities.py b/core/model_capabilities.py new file mode 100644 index 0000000000000000000000000000000000000000..e0c2661eace621b3d4d098d694549e28746fe166 --- /dev/null +++ b/core/model_capabilities.py @@ -0,0 +1,22 @@ +"""Small checkpoint-level capability guards layered over architecture YAML.""" + +from __future__ import annotations + +_EDIT_ONLY_CHAINS = { + "qwen_image_edit", + "boogu_image_edit", + "reference_image", # Mage-Flow edit checkpoints +} + + +def supports_chain_for_model(model_name: str, chain_name: str) -> bool: + """Return whether a concrete checkpoint is known to support a chain. + + Most capabilities apply to every checkpoint of an architecture. Qwen, + Boogu, and Mage-Flow register generation and edit checkpoints together, so + their reference injectors require the concrete Edit variant. + """ + + if chain_name in _EDIT_ONLY_CHAINS: + return "edit" in str(model_name).casefold() + return True diff --git a/core/model_manager.py b/core/model_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..0394e6e9e63375431493383f7d292916ab5fcaab --- /dev/null +++ b/core/model_manager.py @@ -0,0 +1,63 @@ +import gc +from typing import List +import gradio as gr +from imagegen_utils.app_utils import _ensure_model_downloaded +from core.settings import ALL_MODEL_MAP + +class ModelManager: + _instance = None + + def __new__(cls, *args, **kwargs): + if not cls._instance: + cls._instance = super(ModelManager, cls).__new__(cls, *args, **kwargs) + return cls._instance + + def __init__(self): + if hasattr(self, 'initialized'): + return + self.initialized = True + print("✅ ModelManager initialized.") + + def ensure_models_downloaded(self, required_models: List[str], progress): + print(f"--- [ModelManager] Ensuring models are downloaded: {required_models} ---") + for i, display_name in enumerate(required_models): + if progress and hasattr(progress, '__call__'): + progress(i / max(len(required_models), 1), desc=f"Checking file: {display_name}") + try: + _ensure_model_downloaded(display_name, progress) + except Exception as e: + raise gr.Error(f"模型“{display_name}”下载失败:{e}") + print(f"--- [ModelManager] ✅ All required models are present on disk. ---") + +model_manager = ModelManager() + + +def release_loaded_models() -> bool: + """Best-effort release of ComfyUI model state while GPU access is active.""" + + released = False + try: + from comfy import model_management + + unload = getattr(model_management, "unload_all_models", None) + if callable(unload): + unload() + released = True + + cleanup = getattr(model_management, "cleanup_models", None) + if callable(cleanup): + cleanup() + + gc.collect() + empty_cache = getattr(model_management, "soft_empty_cache", None) + if callable(empty_cache): + try: + empty_cache(force=True) + except TypeError: + empty_cache() + print("✅ Released ComfyUI model state after a model switch/error.") + except Exception as exc: + # Cleanup must never hide the original generation result or exception. + gc.collect() + print(f"Warning: Could not fully release ComfyUI model state: {exc}") + return released diff --git a/core/pipelines/__init__.py b/core/pipelines/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/core/pipelines/base_pipeline.py b/core/pipelines/base_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..9554e5929a6f857b49207d46892ad4f70a1d68c0 --- /dev/null +++ b/core/pipelines/base_pipeline.py @@ -0,0 +1,55 @@ +from abc import ABC, abstractmethod +from typing import List, Any, Dict +import gradio as gr +import spaces +import tempfile +import imageio +import numpy as np +import sys +import os + +class BasePipeline(ABC): + def __init__(self): + from core.model_manager import model_manager + self.model_manager = model_manager + + @abstractmethod + def get_required_models(self, **kwargs) -> List[str]: + pass + + @abstractmethod + def run(self, *args, progress: gr.Progress, **kwargs) -> Any: + pass + + def _ensure_models_downloaded(self, progress: gr.Progress, **kwargs): + """Ensures model files are downloaded before requesting GPU.""" + required_models = self.get_required_models(**kwargs) + self.model_manager.ensure_models_downloaded(required_models, progress=progress) + + def _execute_gpu_logic(self, gpu_function: callable, duration: int, default_duration: int, task_name: str, *args, **kwargs): + final_duration = default_duration + try: + if duration is not None and int(duration) > 0: + final_duration = int(duration) + except (ValueError, TypeError): + print(f"Invalid ZeroGPU duration input for {task_name}. Using default {default_duration}s.") + pass + + print(f"Requesting ZeroGPU for {task_name} with duration: {final_duration} seconds.") + gpu_runner = spaces.GPU(duration=final_duration)(gpu_function) + + return gpu_runner(*args, **kwargs) + + def _encode_video_from_frames(self, frames_tensor_cpu: 'torch.Tensor', fps: int, progress: gr.Progress) -> str: + progress(0.9, desc="Encoding video on CPU...") + frames_np = (frames_tensor_cpu.numpy() * 255.0).astype(np.uint8) + + with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as temp_video_file: + video_path = temp_video_file.name + writer = imageio.get_writer(video_path, fps=fps, codec='libx264', quality=8) + for frame in frames_np: + writer.append_data(frame) + writer.close() + + progress(1.0, desc="Done!") + return video_path diff --git a/core/pipelines/pipeline_input_processor.py b/core/pipelines/pipeline_input_processor.py new file mode 100644 index 0000000000000000000000000000000000000000..971c9820c4f81ef8c9b89e5131366c858a011bb1 --- /dev/null +++ b/core/pipelines/pipeline_input_processor.py @@ -0,0 +1,580 @@ +import os +import uuid +import numpy as np +import gradio as gr +from PIL import Image, ImageChops +from typing import Dict, Any, List + +from core.settings import INPUT_DIR, MULTIPLIERS_MAP, LORA_DIR, EMBEDDING_DIR, VAE_DIR +from core.runtime_config import CONFIG +from imagegen_utils.app_utils import ( + sanitize_filename, + get_lora_path, + get_embedding_path, + ensure_controlnet_model_downloaded, + ensure_ipadapter_models_downloaded, + _ensure_model_downloaded, + ensure_sd3_ipadapter_models_downloaded, + get_vae_path, +) + + +def _temp_png(stem: str) -> str: + return os.path.join(INPUT_DIR, f"{stem}_{uuid.uuid4().hex}.png") + + +REFERENCE_IMAGE_LIMITS = { + "controlnet_data": 5, + "anima_controlnet_lllite_data": 5, + "diffsynth_controlnet_data": 5, + "krea2_controlnet_data": 5, + "ipadapter_data": 5, + "flux1_ipadapter_data": 5, + "sd3_ipadapter_chain": 5, + "style_data": 5, + "reference_latent_data": 10, + "hidream_o1_reference_data": 10, + "joyai_reference_data": 2, + "krea2_identity_edit_data": 2, + "krea2_reference_edit_data": 3, + "qwen_image_edit_data": 3, + "boogu_edit_data": 10, + "reference_image_data": 10, +} + + +def _pil_images(value: Any): + if isinstance(value, Image.Image): + yield value + elif isinstance(value, dict): + for child in value.values(): + yield from _pil_images(child) + elif isinstance(value, (list, tuple)): + for child in value: + yield from _pil_images(child) + + +def _validate_reference_image_budget(ui_inputs: Dict[str, Any]) -> None: + """Bound decoded reference images before saving or entering a workflow.""" + + all_images = [] + for input_key, chain_limit in REFERENCE_IMAGE_LIMITS.items(): + images = list(_pil_images(ui_inputs.get(input_key))) + if len(images) > chain_limit: + raise gr.Error( + f"扩展“{input_key}”最多支持 {chain_limit} 张图片;当前为 {len(images)} 张。" + ) + all_images.extend(images) + + if len(all_images) > CONFIG.max_reference_images: + raise gr.Error( + f"一次任务最多使用 {CONFIG.max_reference_images} 张参考/控制图;" + f"当前合计 {len(all_images)} 张。" + ) + + total_megapixels = 0.0 + for index, image in enumerate(all_images, start=1): + megapixels = (image.width * image.height) / 1_000_000 + if megapixels > CONFIG.max_input_megapixels: + raise gr.Error( + f"参考图 {index} 为 {megapixels:.1f}MP,超过单图上限 " + f"{CONFIG.max_input_megapixels:g}MP。" + ) + total_megapixels += megapixels + if total_megapixels > CONFIG.max_reference_megapixels: + raise gr.Error( + f"参考/控制图累计为 {total_megapixels:.1f}MP,超过上限 " + f"{CONFIG.max_reference_megapixels:g}MP;请缩小图片或减少数量。" + ) + +def process_pipeline_inputs(ui_inputs: Dict[str, Any], progress: gr.Progress, workflow_model_type: str) -> Dict[str, Any]: + task_type = ui_inputs['task_type'] + temp_files_to_clean = [] + _validate_reference_image_budget(ui_inputs) + + multiplier = MULTIPLIERS_MAP.get(workflow_model_type, 8) + img_w, img_h = 0, 0 + if task_type == 'txt2img': + img_w = int(ui_inputs.get('width', 0)) + img_h = int(ui_inputs.get('height', 0)) + elif task_type == 'img2img': + input_image_pil = ui_inputs.get('img2img_image') + if input_image_pil: + img_w, img_h = input_image_pil.width, input_image_pil.height + elif task_type == 'inpaint': + inpaint_img = ui_inputs.get('inpaint_image') + inpaint_dict = ui_inputs.get('inpaint_image_dict') + if inpaint_img: + img_w, img_h = inpaint_img.width, inpaint_img.height + elif inpaint_dict and inpaint_dict.get('background'): + img_w, img_h = inpaint_dict['background'].width, inpaint_dict['background'].height + elif task_type == 'outpaint': + input_image_pil = ui_inputs.get('outpaint_image') + if input_image_pil: + img_w, img_h = input_image_pil.width, input_image_pil.height + elif task_type == 'hires_fix': + input_image_pil = ui_inputs.get('hires_image') + if input_image_pil: + img_w, img_h = input_image_pil.width, input_image_pil.height + + if task_type == "txt2img" and (img_w <= 0 or img_h <= 0): + raise gr.Error("文生图的宽度和高度必须为正整数。") + + if img_w > 0 and img_h > 0: + input_megapixels = (img_w * img_h) / 1_000_000 + if input_megapixels > CONFIG.max_input_megapixels: + scale = (CONFIG.max_input_megapixels / input_megapixels) ** 0.5 + suggested_w = max(multiplier, int(img_w * scale) // multiplier * multiplier) + suggested_h = max(multiplier, int(img_h * scale) // multiplier * multiplier) + raise gr.Error( + f"输入图片为 {input_megapixels:.1f}MP,超过当前上限 " + f"{CONFIG.max_input_megapixels:g}MP;建议缩小到约 " + f"{suggested_w}×{suggested_h}。" + ) + + projected_w, projected_h = img_w, img_h + if task_type == "hires_fix": + upscale = float(ui_inputs.get("hires_scale_by") or 1.5) + projected_w, projected_h = int(img_w * upscale), int(img_h * upscale) + elif task_type == "outpaint": + projected_w = img_w + int(ui_inputs.get("left") or 0) + int(ui_inputs.get("right") or 0) + projected_h = img_h + int(ui_inputs.get("top") or 0) + int(ui_inputs.get("bottom") or 0) + projected_megapixels = (projected_w * projected_h) / 1_000_000 + if projected_megapixels > CONFIG.max_output_megapixels: + raise gr.Error( + f"预计输出为 {projected_w}×{projected_h}({projected_megapixels:.1f}MP)," + f"超过当前上限 {CONFIG.max_output_megapixels:g}MP;请降低放大倍数或扩边尺寸。" + ) + + if (img_w % multiplier != 0) or (img_h % multiplier != 0): + suggested_w = max(multiplier, round(img_w / multiplier) * multiplier) + suggested_h = max(multiplier, round(img_h / multiplier) * multiplier) + warning_msg = ( + f"当前模型要求宽高均为 {multiplier} 的倍数;" + f"收到 {img_w}×{img_h},可调整为约 {suggested_w}×{suggested_h}。" + ) + raise gr.Error(warning_msg) + + lora_data = ui_inputs.get('lora_data', []) + active_loras_for_gpu, active_loras_for_meta = [], [] + if lora_data: + sources, ids, scales, files = lora_data[0::4], lora_data[1::4], lora_data[2::4], lora_data[3::4] + for i, (source, lora_id, scale, _) in enumerate(zip(sources, ids, scales, files)): + if scale > 0 and lora_id and lora_id.strip(): + lora_filename = None + if source == "File": + lora_filename = sanitize_filename(lora_id) + local_path = os.path.join(LORA_DIR, lora_filename) + if not os.path.exists(local_path): + raise gr.Error(f"已上传的 LoRA“{lora_id}”已不存在,请重新上传。") + elif source in ("Civitai", "Hugging Face"): + local_path, status = get_lora_path(source, lora_id, os.environ.get("CIVITAI_API_KEY", ""), progress) + if local_path: lora_filename = os.path.basename(local_path) + else: raise gr.Error(f"LoRA“{lora_id}”准备失败:{status}") + + if lora_filename: + active_loras_for_gpu.append({"lora_name": lora_filename, "strength_model": scale, "strength_clip": scale}) + active_loras_for_meta.append(f"{source} {lora_id}:{scale}") + + ui_inputs['denoise'] = 1.0 + if task_type == 'img2img': ui_inputs['denoise'] = ui_inputs.get('img2img_denoise', 0.7) + elif task_type == 'hires_fix': ui_inputs['denoise'] = ui_inputs.get('hires_denoise', 0.55) + elif task_type == 'inpaint': ui_inputs['denoise'] = ui_inputs.get('inpaint_denoise', 1.0) + + if not os.path.exists(INPUT_DIR): os.makedirs(INPUT_DIR) + + if task_type == 'img2img': + input_image_pil = ui_inputs.get('img2img_image') + if not input_image_pil: + raise gr.Error("图生图需要先上传源图片。") + temp_file_path = _temp_png("temp_input") + input_image_pil.save(temp_file_path, "PNG") + ui_inputs['input_image'] = os.path.basename(temp_file_path) + temp_files_to_clean.append(temp_file_path) + ui_inputs['width'] = input_image_pil.width + ui_inputs['height'] = input_image_pil.height + + elif task_type == 'inpaint': + inpaint_img = ui_inputs.get('inpaint_image') + inpaint_dict = ui_inputs.get('inpaint_image_dict') + + if inpaint_img: + temp_file_path = _temp_png("temp_inpaint") + inpaint_img.save(temp_file_path, "PNG") + ui_inputs['input_image'] = os.path.basename(temp_file_path) + temp_files_to_clean.append(temp_file_path) + ui_inputs['width'] = inpaint_img.width + ui_inputs['height'] = inpaint_img.height + elif inpaint_dict and inpaint_dict.get('background') and inpaint_dict.get('layers'): + background_img = inpaint_dict['background'].convert("RGBA") + composite_mask_pil = Image.new('L', background_img.size, 0) + for layer in inpaint_dict['layers']: + if layer: + layer_alpha = layer.split()[-1] + composite_mask_pil = ImageChops.lighter(composite_mask_pil, layer_alpha) + + inverted_mask_alpha = Image.fromarray(255 - np.array(composite_mask_pil), mode='L') + r, g, b, _ = background_img.split() + composite_image_with_mask = Image.merge('RGBA', [r, g, b, inverted_mask_alpha]) + + temp_file_path = _temp_png("temp_inpaint_composite") + composite_image_with_mask.save(temp_file_path, "PNG") + + ui_inputs['input_image'] = os.path.basename(temp_file_path) + temp_files_to_clean.append(temp_file_path) + ui_inputs.pop('inpaint_mask', None) + ui_inputs['width'] = background_img.width + ui_inputs['height'] = background_img.height + else: + raise gr.Error("局部重绘需要输入图片和有效蒙版。") + + elif task_type == 'outpaint': + input_image_pil = ui_inputs.get('outpaint_image') + if not input_image_pil: + raise gr.Error("扩图需要先上传源图片。") + temp_file_path = _temp_png("temp_input") + input_image_pil.save(temp_file_path, "PNG") + ui_inputs['input_image'] = os.path.basename(temp_file_path) + temp_files_to_clean.append(temp_file_path) + + ui_inputs['megapixels'] = 0.25 + ui_inputs['grow_mask_by'] = ui_inputs.get('feathering', 10) + ui_inputs['width'] = input_image_pil.width + int(ui_inputs.get('left') or 0) + int(ui_inputs.get('right') or 0) + ui_inputs['height'] = input_image_pil.height + int(ui_inputs.get('top') or 0) + int(ui_inputs.get('bottom') or 0) + + elif task_type == 'hires_fix': + input_image_pil = ui_inputs.get('hires_image') + if not input_image_pil: + raise gr.Error("高清修复需要先上传源图片。") + temp_file_path = _temp_png("temp_input") + input_image_pil.save(temp_file_path, "PNG") + ui_inputs['input_image'] = os.path.basename(temp_file_path) + temp_files_to_clean.append(temp_file_path) + hires_scale = float(ui_inputs.get('hires_scale_by') or 1.5) + ui_inputs['width'] = int(input_image_pil.width * hires_scale) + ui_inputs['height'] = int(input_image_pil.height * hires_scale) + + embedding_data = ui_inputs.get('embedding_data', []) + embedding_filenames = [] + if embedding_data: + emb_sources, emb_ids, emb_files = embedding_data[0::3], embedding_data[1::3], embedding_data[2::3] + for i, (source, emb_id, _) in enumerate(zip(emb_sources, emb_ids, emb_files)): + if emb_id and emb_id.strip(): + emb_filename = None + if source == "File": + emb_filename = sanitize_filename(emb_id) + local_path = os.path.join(EMBEDDING_DIR, emb_filename) + if not os.path.exists(local_path): + raise gr.Error(f"已上传的 Embedding“{emb_id}”已不存在,请重新上传。") + elif source in ("Civitai", "Hugging Face"): + local_path, status = get_embedding_path(source, emb_id, os.environ.get("CIVITAI_API_KEY", ""), progress) + if local_path: emb_filename = os.path.basename(local_path) + else: raise gr.Error(f"Embedding“{emb_id}”准备失败:{status}") + + if emb_filename: + embedding_filenames.append(emb_filename) + + controlnet_data = ui_inputs.get('controlnet_data', []) + active_controlnets = [] + if controlnet_data: + (cn_images, _, _, cn_strengths, cn_filepaths) = [controlnet_data[i::5] for i in range(5)] + for i in range(len(cn_images)): + if cn_images[i] and cn_strengths[i] > 0 and cn_filepaths[i] and cn_filepaths[i] != "None": + ensure_controlnet_model_downloaded(cn_filepaths[i], progress) + if not os.path.exists(INPUT_DIR): os.makedirs(INPUT_DIR) + cn_temp_path = _temp_png(f"temp_cn_{i}") + cn_images[i].save(cn_temp_path, "PNG") + temp_files_to_clean.append(cn_temp_path) + active_controlnets.append({ + "image": os.path.basename(cn_temp_path), "strength": cn_strengths[i], + "start_percent": 0.0, "end_percent": 1.0, "control_net_name": cn_filepaths[i] + }) + + anima_controlnet_lllite_data = ui_inputs.get('anima_controlnet_lllite_data', []) + active_anima_controlnets = [] + if anima_controlnet_lllite_data: + (cn_images, _, _, cn_strengths, cn_filepaths, cn_starts, cn_ends) = [anima_controlnet_lllite_data[i::7] for i in range(7)] + for i in range(len(cn_images)): + if cn_images[i] and cn_strengths[i] > 0 and cn_filepaths[i] and cn_filepaths[i] != "None": + _ensure_model_downloaded(cn_filepaths[i], progress) + if not os.path.exists(INPUT_DIR): os.makedirs(INPUT_DIR) + cn_temp_path = _temp_png(f"temp_anima_cn_{i}") + cn_images[i].save(cn_temp_path, "PNG") + temp_files_to_clean.append(cn_temp_path) + active_anima_controlnets.append({ + "image": os.path.basename(cn_temp_path), "strength": cn_strengths[i], + "start_percent": cn_starts[i], "end_percent": cn_ends[i], "control_net_name": cn_filepaths[i] + }) + + diffsynth_controlnet_data = ui_inputs.get('diffsynth_controlnet_data', []) + active_diffsynth_controlnets = [] + if diffsynth_controlnet_data: + (cn_images, _, _, cn_strengths, cn_filepaths) = [diffsynth_controlnet_data[i::5] for i in range(5)] + for i in range(len(cn_images)): + if cn_images[i] and cn_strengths[i] > 0 and cn_filepaths[i] and cn_filepaths[i] != "None": + ensure_controlnet_model_downloaded(cn_filepaths[i], progress) + if not os.path.exists(INPUT_DIR): os.makedirs(INPUT_DIR) + cn_temp_path = _temp_png(f"temp_diffsynth_cn_{i}") + cn_images[i].save(cn_temp_path, "PNG") + temp_files_to_clean.append(cn_temp_path) + active_diffsynth_controlnets.append({ + "image": os.path.basename(cn_temp_path), "strength": cn_strengths[i], + "control_net_name": cn_filepaths[i] + }) + + krea2_controlnet_data = ui_inputs.get('krea2_controlnet_data', []) + active_krea2_controlnets = [] + if krea2_controlnet_data: + (cn_images, _, _, cn_strengths, cn_filepaths) = [krea2_controlnet_data[i::5] for i in range(5)] + for i in range(len(cn_images)): + if cn_images[i] and cn_strengths[i] > 0 and cn_filepaths[i] and cn_filepaths[i] != "None": + ensure_controlnet_model_downloaded(cn_filepaths[i], progress) + if not os.path.exists(INPUT_DIR): os.makedirs(INPUT_DIR) + cn_temp_path = _temp_png(f"temp_krea2_cn_{i}") + cn_images[i].save(cn_temp_path, "PNG") + temp_files_to_clean.append(cn_temp_path) + active_krea2_controlnets.append({ + "image": os.path.basename(cn_temp_path), "strength": cn_strengths[i], + "control_net_name": cn_filepaths[i] + }) + + ipadapter_data = ui_inputs.get('ipadapter_data', []) + active_ipadapters = [] + if ipadapter_data: + num_ipa_units = (len(ipadapter_data) - 5) // 3 + final_preset, final_weight, final_lora_strength, final_embeds_scaling, final_combine_method = ipadapter_data[-5:] + ipa_images, ipa_weights, ipa_lora_strengths = [ipadapter_data[i*num_ipa_units:(i+1)*num_ipa_units] for i in range(3)] + all_presets_to_download = set() + for i in range(num_ipa_units): + if ipa_images[i] and ipa_weights[i] > 0 and final_preset: + all_presets_to_download.add(final_preset) + if not os.path.exists(INPUT_DIR): os.makedirs(INPUT_DIR) + ipa_temp_path = _temp_png(f"temp_ipa_{i}") + ipa_images[i].save(ipa_temp_path, "PNG") + temp_files_to_clean.append(ipa_temp_path) + active_ipadapters.append({ + "image": os.path.basename(ipa_temp_path), "preset": final_preset, + "weight": ipa_weights[i], "lora_strength": ipa_lora_strengths[i] + }) + if active_ipadapters and final_preset: + all_presets_to_download.add(final_preset) + for preset in all_presets_to_download: + ensure_ipadapter_models_downloaded(preset, progress) + + model_type_key = 'sd15' if workflow_model_type == 'sd15' else 'sdxl' + if active_ipadapters: + active_ipadapters.append({ + 'is_final_settings': True, 'model_type': model_type_key, 'final_preset': final_preset, + 'final_weight': final_weight, 'final_lora_strength': final_lora_strength, + 'final_embeds_scaling': final_embeds_scaling, 'final_combine_method': final_combine_method + }) + + flux1_ipadapter_data = ui_inputs.get('flux1_ipadapter_data', []) + active_flux1_ipadapters = [] + if flux1_ipadapter_data: + num_units = len(flux1_ipadapter_data) // 4 + f_images = flux1_ipadapter_data[0*num_units : 1*num_units] + f_weights = flux1_ipadapter_data[1*num_units : 2*num_units] + f_starts = flux1_ipadapter_data[2*num_units : 3*num_units] + f_ends = flux1_ipadapter_data[3*num_units : 4*num_units] + for i in range(len(f_images)): + if f_images[i] and f_weights[i] > 0: + for filename in ["ip-adapter.bin"]: + _ensure_model_downloaded(filename, progress) + + from huggingface_hub import snapshot_download + progress(0.5, desc="Caching HF SigLIP model...") + snapshot_download( + repo_id="google/siglip-so400m-patch14-384", + allow_patterns=["*.json", "*.safetensors", "*.txt"], + ignore_patterns=["*.msgpack", "*.h5", "*.bin"] + ) + + temp_path = _temp_png(f"temp_fipa_{i}") + f_images[i].save(temp_path, "PNG") + temp_files_to_clean.append(temp_path) + active_flux1_ipadapters.append({ + "image": os.path.basename(temp_path), + "weight": f_weights[i], "start_percent": f_starts[i], "end_percent": f_ends[i] + }) + + sd3_ipadapter_data = ui_inputs.get('sd3_ipadapter_chain', []) + active_sd3_ipadapters = [] + if sd3_ipadapter_data: + num_units = len(sd3_ipadapter_data) // 4 + s_images = sd3_ipadapter_data[0*num_units : 1*num_units] + s_weights = sd3_ipadapter_data[1*num_units : 2*num_units] + s_starts = sd3_ipadapter_data[2*num_units : 3*num_units] + s_ends = sd3_ipadapter_data[3*num_units : 4*num_units] + sd3_ipa_downloaded = False + for i in range(len(s_images)): + if s_images[i] and s_weights[i] > 0: + if not sd3_ipa_downloaded: + ensure_sd3_ipadapter_models_downloaded(progress) + sd3_ipa_downloaded = True + temp_path = _temp_png(f"temp_s3ipa_{i}") + s_images[i].save(temp_path, "PNG") + temp_files_to_clean.append(temp_path) + active_sd3_ipadapters.append({ + "image": os.path.basename(temp_path), + "weight": s_weights[i], "start_percent": s_starts[i], "end_percent": s_ends[i] + }) + + style_data = ui_inputs.get('style_data', []) + active_styles = [] + if style_data: + num_units = len(style_data) // 2 + st_images = style_data[0*num_units : 1*num_units] + st_strengths = style_data[1*num_units : 2*num_units] + style_models_downloaded = False + for i in range(len(st_images)): + if st_images[i] and st_strengths[i] > 0: + if not style_models_downloaded: + _ensure_model_downloaded("sigclip_vision_patch14_384.safetensors", progress) + _ensure_model_downloaded("flux1-redux-dev.safetensors", progress) + style_models_downloaded = True + temp_path = _temp_png(f"temp_style_{i}") + st_images[i].save(temp_path, "PNG") + temp_files_to_clean.append(temp_path) + active_styles.append({ + "image": os.path.basename(temp_path), "strength": st_strengths[i] + }) + + reference_latent_data = ui_inputs.get('reference_latent_data', []) + active_reference_latents = [] + if reference_latent_data: + for img in reference_latent_data: + if img: + if not os.path.exists(INPUT_DIR): os.makedirs(INPUT_DIR) + temp_path = _temp_png("temp_ref") + img.save(temp_path, "PNG") + temp_files_to_clean.append(temp_path) + active_reference_latents.append(os.path.basename(temp_path)) + + hidream_o1_reference_data = ui_inputs.get('hidream_o1_reference_data', []) + active_hidream_o1_reference = [] + if hidream_o1_reference_data: + for img in hidream_o1_reference_data: + if img: + if not os.path.exists(INPUT_DIR): os.makedirs(INPUT_DIR) + temp_path = _temp_png("temp_ho1_ref") + img.save(temp_path, "PNG") + temp_files_to_clean.append(temp_path) + active_hidream_o1_reference.append(os.path.basename(temp_path)) + + joyai_reference_data = ui_inputs.get('joyai_reference_data', []) + active_joyai_reference = [] + if joyai_reference_data: + for img in joyai_reference_data: + if img: + if not os.path.exists(INPUT_DIR): os.makedirs(INPUT_DIR) + temp_path = _temp_png("temp_joyai_ref") + img.save(temp_path, "PNG") + temp_files_to_clean.append(temp_path) + active_joyai_reference.append(os.path.basename(temp_path)) + + krea2_identity_edit_data = ui_inputs.get('krea2_identity_edit_data', []) + active_krea2_identity_edit = [] + if krea2_identity_edit_data: + for img in krea2_identity_edit_data: + if img: + if not os.path.exists(INPUT_DIR): os.makedirs(INPUT_DIR) + temp_path = _temp_png("temp_krea2_id_ref") + img.save(temp_path, "PNG") + temp_files_to_clean.append(temp_path) + active_krea2_identity_edit.append(os.path.basename(temp_path)) + + krea2_reference_edit_data = ui_inputs.get('krea2_reference_edit_data', []) + active_krea2_reference_edit = [] + if krea2_reference_edit_data: + for img in krea2_reference_edit_data: + if img: + if not os.path.exists(INPUT_DIR): os.makedirs(INPUT_DIR) + temp_path = _temp_png("temp_krea2_reference_ref") + img.save(temp_path, "PNG") + temp_files_to_clean.append(temp_path) + active_krea2_reference_edit.append(os.path.basename(temp_path)) + + qwen_image_edit_data = ui_inputs.get('qwen_image_edit_data', []) + active_qwen_image_edit = [] + if qwen_image_edit_data: + for img in qwen_image_edit_data: + if img: + if not os.path.exists(INPUT_DIR): os.makedirs(INPUT_DIR) + temp_path = _temp_png("temp_qwen_edit_ref") + img.save(temp_path, "PNG") + temp_files_to_clean.append(temp_path) + active_qwen_image_edit.append(os.path.basename(temp_path)) + + boogu_edit_data = ui_inputs.get('boogu_edit_data', []) + active_boogu_edit = [] + if boogu_edit_data: + for img in boogu_edit_data: + if img: + if not os.path.exists(INPUT_DIR): os.makedirs(INPUT_DIR) + temp_path = _temp_png("temp_boogu_edit_ref") + img.save(temp_path, "PNG") + temp_files_to_clean.append(temp_path) + active_boogu_edit.append(os.path.basename(temp_path)) + + reference_image_data = ui_inputs.get('reference_image_data', []) + active_reference_images = [] + if reference_image_data: + for img in reference_image_data: + if img: + if not os.path.exists(INPUT_DIR): os.makedirs(INPUT_DIR) + temp_path = _temp_png("temp_ref_img") + img.save(temp_path, "PNG") + temp_files_to_clean.append(temp_path) + active_reference_images.append(os.path.basename(temp_path)) + + vae_source = ui_inputs.get('vae_source') + vae_id = ui_inputs.get('vae_id') + vae_name_override = None + if vae_source and vae_source != "None": + if vae_source == "File": + vae_name_override = sanitize_filename(vae_id) + local_path = os.path.join(VAE_DIR, vae_name_override) + if not os.path.exists(local_path): + raise gr.Error(f"已上传的 VAE“{vae_id}”已不存在,请重新上传。") + elif vae_source in ("Civitai", "Hugging Face") and vae_id and vae_id.strip(): + local_path, status = get_vae_path(vae_source, vae_id, os.environ.get("CIVITAI_API_KEY", ""), progress) + if local_path: vae_name_override = os.path.basename(local_path) + else: raise gr.Error(f"VAE“{vae_id}”准备失败:{status}") + if vae_name_override: + ui_inputs['vae_name'] = vae_name_override + + conditioning_data = ui_inputs.get('conditioning_data', []) + active_conditioning = [] + if conditioning_data: + num_units = len(conditioning_data) // 6 + prompts, widths, heights, xs, ys, strengths = [conditioning_data[i*num_units : (i+1)*num_units] for i in range(6)] + for i in range(num_units): + if prompts[i] and prompts[i].strip(): + active_conditioning.append({ + "prompt": prompts[i], "width": int(widths[i]), "height": int(heights[i]), + "x": int(xs[i]), "y": int(ys[i]), "strength": float(strengths[i]) + }) + + return { + "active_loras_for_gpu": active_loras_for_gpu, + "active_loras_for_meta": active_loras_for_meta, + "active_controlnets": active_controlnets, + "active_anima_controlnets": active_anima_controlnets, + "active_diffsynth_controlnets": active_diffsynth_controlnets, + "active_krea2_controlnets": active_krea2_controlnets, + "active_ipadapters": active_ipadapters, + "active_flux1_ipadapters": active_flux1_ipadapters, + "active_sd3_ipadapters": active_sd3_ipadapters, + "active_styles": active_styles, + "active_reference_latents": active_reference_latents, + "active_hidream_o1_reference": active_hidream_o1_reference, + "active_joyai_reference": active_joyai_reference, + "active_krea2_identity_edit": active_krea2_identity_edit, + "active_krea2_reference_edit": active_krea2_reference_edit, + "active_qwen_image_edit": active_qwen_image_edit, + "active_boogu_edit": active_boogu_edit, + "active_reference_images": active_reference_images, + "active_conditioning": active_conditioning, + "temp_files_to_clean": temp_files_to_clean + } diff --git a/core/pipelines/sd_image_pipeline.py b/core/pipelines/sd_image_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..3ce1a34256b02675e9007145f5d4721ca56688f8 --- /dev/null +++ b/core/pipelines/sd_image_pipeline.py @@ -0,0 +1,364 @@ +import os +import random +import shutil +import torch +import uuid +import gradio as gr +from PIL import Image +from typing import List, Dict, Any + +from .base_pipeline import BasePipeline +from core.settings import * +from core.model_capabilities import supports_chain_for_model +from imagegen_utils.app_utils import sanitize_prompt +from core.workflow_assembler import WorkflowAssembler +from core.runtime_config import CONFIG, estimate_gpu_duration +from core.task_scheduler import TaskCancelledError, generation_guard +from .workflow_executor import WorkflowExecutor +from .pipeline_input_processor import process_pipeline_inputs + +class SdImagePipeline(BasePipeline): + CHAIN_INPUT_KEYS = { + "lora": ("lora_data",), + "controlnet": ("controlnet_data",), + "anima_controlnet_lllite": ("anima_controlnet_lllite_data",), + "diffsynth_controlnet": ("diffsynth_controlnet_data",), + "krea2_controlnet": ("krea2_controlnet_data",), + "ipadapter": ("ipadapter_data",), + "flux1_ipadapter": ("flux1_ipadapter_data",), + "sd3_ipadapter": ("sd3_ipadapter_chain",), + "style": ("style_data",), + "embedding": ("embedding_data",), + "conditioning": ("conditioning_data",), + "reference_latent": ("reference_latent_data",), + "hidream_o1_reference": ("hidream_o1_reference_data",), + "joyai_image": ("joyai_reference_data",), + "krea2_identity_edit": ("krea2_identity_edit_data",), + "krea2_style_reference": ("krea2_reference_edit_data",), + "qwen_image_edit": ("qwen_image_edit_data",), + "boogu_image_edit": ("boogu_edit_data",), + "reference_image": ("reference_image_data",), + } + NATIVE_REFERENCE_CHAINS = { + "reference_latent", + "hidream_o1_reference", + "joyai_image", + "krea2_identity_edit", + "krea2_style_reference", + "qwen_image_edit", + "boogu_image_edit", + "reference_image", + } + + def get_required_models(self, model_display_name: str, **kwargs) -> List[str]: + model_info = ALL_MODEL_MAP.get(model_display_name) + if not model_info: + return [model_display_name] + + path_or_components = model_info[1] + if isinstance(path_or_components, dict): + return [v for v in path_or_components.values() if v and v != "pixel_space"] + else: + return [model_display_name] + + def _gpu_logic(self, ui_inputs: Dict, loras_string: str, workflow: Dict[str, Any], assembler: WorkflowAssembler, progress=gr.Progress(track_tqdm=True)): + model_display_name = ui_inputs['model_display_name'] + succeeded = False + try: + progress(0.4, desc="正在执行工作流…") + + initial_objects = {} + decoded_images_tensor = WorkflowExecutor.execute_workflow( + workflow, initial_objects=initial_objects + ) + + output_images = [] + raw_seed = ui_inputs.get('seed') + start_seed = int(raw_seed) if (raw_seed is not None and raw_seed != -1) else random.randint(0, 2**64 - 1) + image_count = int(decoded_images_tensor.shape[0]) + for i in range(image_count): + img_tensor = decoded_images_tensor[i] + pil_image = Image.fromarray((img_tensor.cpu().numpy() * 255.0).astype("uint8")) + + width_for_meta = ui_inputs.get('width', 'N/A') + height_for_meta = ui_inputs.get('height', 'N/A') + + params_string = f"{ui_inputs['positive_prompt']}\nNegative prompt: {ui_inputs['negative_prompt']}\n" + params_string += f"Steps: {ui_inputs['num_inference_steps']}, Sampler: {ui_inputs['sampler']}, Scheduler: {ui_inputs['scheduler']}, CFG scale: {ui_inputs['guidance_scale']}, Seed: {start_seed}, Size: {width_for_meta}x{height_for_meta}, Base Model: {model_display_name}" + if image_count > 1: + params_string += f", Batch index: {i + 1}/{image_count}" + if ui_inputs['task_type'] != 'txt2img': params_string += f", Denoise: {ui_inputs['denoise']}" + if ui_inputs.get('clip_skip') and ui_inputs['clip_skip'] != 1: params_string += f", Clip skip: {abs(ui_inputs['clip_skip'])}" + if loras_string: params_string += f", {loras_string}" + + pil_image.info = {'parameters': params_string.strip()} + output_images.append(pil_image) + + succeeded = True + return output_images + finally: + if not succeeded or ui_inputs.get("_release_models_after_run"): + from core.model_manager import release_loaded_models + + release_loaded_models() + + @generation_guard + def run(self, ui_inputs: Dict, progress): + progress(0, desc="正在准备模型…") + + task_type = ui_inputs['task_type'] + model_display_name = ui_inputs['model_display_name'] + model_type = MODEL_TYPE_MAP.get(model_display_name, 'sdxl') + + architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {}) + workflow_model_type = architectures_dict.get(model_type, {}).get("model_type", model_type.lower().replace(" ", "").replace(".", "")) + + enabled_chains = set( + FEATURES_CONFIG.get(workflow_model_type, {}).get("enabled_chains", []) + ) + if task_type != "txt2img": + has_native_references = any( + any(ui_inputs.get(input_key) or []) + for chain_name in self.NATIVE_REFERENCE_CHAINS + for input_key in self.CHAIN_INPUT_KEYS[chain_name] + ) + if has_native_references: + raise gr.Error( + "原生多图参考编辑目前只支持“文生图 / 多图融合”。" + "普通逐张重绘请使用图生图;不要同时叠加源图 latent 与参考图链。" + ) + for chain_name, input_keys in self.CHAIN_INPUT_KEYS.items(): + if ( + chain_name not in enabled_chains + or not supports_chain_for_model(model_display_name, chain_name) + ): + for input_key in input_keys: + ui_inputs[input_key] = [] + if "pid" not in enabled_chains: + ui_inputs["pid_settings"] = "OFF" + if "vae" not in enabled_chains: + ui_inputs["vae_source"] = None + ui_inputs["vae_id"] = None + ui_inputs["vae_file"] = None + + try: + batch_size = int(ui_inputs.get("batch_size") or 1) + except (TypeError, ValueError): + batch_size = 1 + if batch_size < 1 or batch_size > CONFIG.max_batch_size: + raise gr.Error(f"单次生成数量需为 1–{CONFIG.max_batch_size}。") + ui_inputs["batch_size"] = batch_size + + ui_inputs['positive_prompt'] = sanitize_prompt(ui_inputs.get('positive_prompt', '')) + ui_inputs['negative_prompt'] = sanitize_prompt(ui_inputs.get('negative_prompt', '')) + + if 'clip_skip' in ui_inputs and ui_inputs['clip_skip'] is not None: + ui_inputs['clip_skip'] = -int(ui_inputs['clip_skip']) + else: + ui_inputs['clip_skip'] = -1 + + required_models = self.get_required_models(model_display_name=model_display_name) + + is_pid_enabled = (ui_inputs.get('pid_settings', 'OFF') == 'ON' and task_type == 'txt2img') + if is_pid_enabled: + import yaml + pid_config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'yaml', 'pid.yaml') + pid_unet_name = "pid_flux1_1024_to_4096_4step_mxfp8.safetensors" + try: + with open(pid_config_path, 'r', encoding='utf-8') as f: + pid_config = yaml.safe_load(f) or {} + pid_items = pid_config.get("PiD", []) + for item in pid_items: + archs = item.get("architectures", []) + if workflow_model_type in archs: + pid_unet_name = item.get("filepath") + break + except Exception as e: + print(f"Error loading PiD config for download: {e}") + + if pid_unet_name not in required_models: + required_models.append(pid_unet_name) + if "gemma_2_2b_it_elm_fp8_scaled.safetensors" not in required_models: + required_models.append("gemma_2_2b_it_elm_fp8_scaled.safetensors") + + self.model_manager.ensure_models_downloaded(required_models, progress=progress) + cancel_event = ui_inputs.get("_cancel_event") + if cancel_event is not None and cancel_event.is_set(): + raise TaskCancelledError("任务已在模型准备完成后取消,未进入 GPU 生成。") + + temp_files_to_clean = [] + try: + processed = process_pipeline_inputs(ui_inputs, progress, workflow_model_type) + temp_files_to_clean.extend(processed["temp_files_to_clean"]) + + active_loras_for_gpu = processed["active_loras_for_gpu"] + active_loras_for_meta = processed["active_loras_for_meta"] + active_controlnets = processed["active_controlnets"] + active_anima_controlnets = processed["active_anima_controlnets"] + active_diffsynth_controlnets = processed["active_diffsynth_controlnets"] + active_krea2_controlnets = processed.get("active_krea2_controlnets", []) + active_ipadapters = processed["active_ipadapters"] + active_flux1_ipadapters = processed["active_flux1_ipadapters"] + active_sd3_ipadapters = processed["active_sd3_ipadapters"] + active_styles = processed["active_styles"] + active_reference_latents = processed["active_reference_latents"] + active_hidream_o1_reference = processed["active_hidream_o1_reference"] + active_joyai_reference = processed.get("active_joyai_reference", []) + active_krea2_identity_edit = processed.get("active_krea2_identity_edit", []) + active_krea2_reference_edit = processed.get("active_krea2_reference_edit", []) + active_qwen_image_edit = processed.get("active_qwen_image_edit", []) + active_boogu_edit = processed.get("active_boogu_edit", []) + active_reference_images = processed.get("active_reference_images", []) + active_conditioning = processed["active_conditioning"] + + loras_string = f"LoRAs: [{', '.join(active_loras_for_meta)}]" if active_loras_for_meta else "" + + progress(0.8, desc="正在组装工作流…") + + seed_val = ui_inputs.get('seed') + if seed_val is None or seed_val == -1: + ui_inputs['seed'] = random.randint(0, 2**32 - 1) + + model_info = ALL_MODEL_MAP[model_display_name] + path_or_components = model_info[1] + latent_type = model_info[3] if len(model_info) > 3 and model_info[3] else 'latent' + latent_generator_template = "EmptyLatentImage" + if latent_type == 'sd3_latent': + latent_generator_template = "EmptySD3LatentImage" + elif latent_type == 'chroma_radiance_latent': + latent_generator_template = "EmptyChromaRadianceLatentImage" + elif latent_type == 'hunyuan_latent': + latent_generator_template = "EmptyHunyuanImageLatent" + + dynamic_values = { + 'task_type': ui_inputs['task_type'], + 'model_type': workflow_model_type, + 'latent_type': latent_type, + 'latent_generator_template': latent_generator_template + } + + recipe_path = os.path.join(os.path.dirname(__file__), "workflow_recipes", "unified_recipe.yaml") + assembler = WorkflowAssembler(recipe_path, dynamic_values=dynamic_values) + + hidream_o1_smoothing_data = [] + if workflow_model_type == 'hidream-o1' and model_display_name == "HiDream-O1-Image": + hidream_o1_smoothing_data.append({}) + + workflow_inputs = { + **ui_inputs, + "positive_prompt": ui_inputs['positive_prompt'], "negative_prompt": ui_inputs['negative_prompt'], + "seed": ui_inputs['seed'], "steps": ui_inputs['num_inference_steps'], "cfg": ui_inputs['guidance_scale'], + "sampler_name": ui_inputs['sampler'], "scheduler": ui_inputs['scheduler'], + "batch_size": ui_inputs['batch_size'], + "clip_skip": ui_inputs['clip_skip'], + "denoise": ui_inputs['denoise'], + "vae_name": ui_inputs.get('vae_name'), + "guidance": ui_inputs.get('guidance', 3.5), + "lora_chain": active_loras_for_gpu, + "controlnet_chain": active_controlnets if not active_anima_controlnets else [], + "anima_controlnet_lllite_chain": active_anima_controlnets, + "diffsynth_controlnet_chain": active_diffsynth_controlnets, + "krea2_controlnet_chain": active_krea2_controlnets, + "ipadapter_chain": active_ipadapters, + "flux1_ipadapter_chain": active_flux1_ipadapters, + "sd3_ipadapter_chain": active_sd3_ipadapters, + "style_chain": active_styles, + "conditioning_chain": active_conditioning, + "reference_latent_chain": active_reference_latents, + "hidream_o1_reference_chain": active_hidream_o1_reference, + "joyai_image_chain": active_joyai_reference, + "krea2_identity_edit_chain": active_krea2_identity_edit, + "krea2_style_reference_chain": active_krea2_reference_edit, + "qwen_image_edit_chain": active_qwen_image_edit, + "boogu_image_edit_chain": active_boogu_edit, + "reference_image_chain": active_reference_images, + "vae_chain": [ui_inputs.get('vae_name')] if ui_inputs.get('vae_name') else [], + "hidream_o1_smoothing_chain": hidream_o1_smoothing_data, + "pid_chain": [ui_inputs.get('pid_settings', 'OFF')] if is_pid_enabled else [], + "scheduler_width": ui_inputs.get('width', 1024), + "scheduler_height": ui_inputs.get('height', 1024), + } + + if isinstance(path_or_components, dict): + workflow_inputs.update({ + 'unet_name': path_or_components.get('unet'), + 'unet_uncond_name': path_or_components.get('unet_uncond'), + 'vae_name': ui_inputs.get('vae_name') or path_or_components.get('vae'), + 'clip_name': path_or_components.get('clip'), + 'clip1_name': path_or_components.get('clip1'), + 'clip2_name': path_or_components.get('clip2'), + 'clip3_name': path_or_components.get('clip3'), + 'clip4_name': path_or_components.get('clip4'), + 'lora_name': path_or_components.get('lora'), + }) + else: + workflow_inputs['model_name'] = path_or_components + + if task_type == 'txt2img': + workflow_inputs['width'] = ui_inputs['width'] + workflow_inputs['height'] = ui_inputs['height'] + + workflow = assembler.assemble(workflow_inputs) + + if cancel_event is not None and cancel_event.is_set(): + raise TaskCancelledError("任务已在进入 GPU 前取消。") + + gpu_duration = estimate_gpu_duration(ui_inputs) + progress(1.0, desc=f"模型已就绪,正在申请 GPU(预计上限 {gpu_duration} 秒)…") + + results = self._execute_gpu_logic( + self._gpu_logic, + duration=gpu_duration, + default_duration=60, + task_name=f"ImageGen ({task_type})", + ui_inputs=ui_inputs, + loras_string=loras_string, + workflow=workflow, + assembler=assembler, + progress=progress + ) + + import json + import glob + from PIL import PngImagePlugin + + prompt_json = json.dumps(workflow) + + out_dir = os.path.abspath(OUTPUT_DIR) + os.makedirs(out_dir, exist_ok=True) + + try: + existing_files = glob.glob(os.path.join(out_dir, "gen_*.png")) + existing_files.sort(key=os.path.getmtime) + keep_existing = max(0, CONFIG.output_retention - len(results)) + while len(existing_files) > keep_existing: + os.remove(existing_files.pop(0)) + except Exception as e: + print(f"Warning: Failed to cleanup output dir: {e}") + + final_results = [] + for img in results: + if not isinstance(img, Image.Image): + final_results.append(img) + continue + + metadata = PngImagePlugin.PngInfo() + params_string = img.info.get("parameters", "") + if params_string: + metadata.add_text("parameters", params_string) + metadata.add_text("prompt", prompt_json) + + filename = f"gen_{uuid.uuid4().hex}.png" + filepath = os.path.join(out_dir, filename) + img.save(filepath, "PNG", pnginfo=metadata) + final_results.append(filepath) + + results = final_results + + finally: + for temp_file in temp_files_to_clean: + if temp_file and os.path.exists(temp_file): + os.remove(temp_file) + print(f"✅ Cleaned up temp file: {temp_file}") + + return results diff --git a/core/pipelines/workflow_executor.py b/core/pipelines/workflow_executor.py new file mode 100644 index 0000000000000000000000000000000000000000..91c8fb71ba7baceeac985a2d49fd3840e29a2ab6 --- /dev/null +++ b/core/pipelines/workflow_executor.py @@ -0,0 +1,140 @@ +import torch +from collections import defaultdict, deque +from typing import Dict, Any, List +from comfy_integration.nodes import NODE_CLASS_MAPPINGS +from imagegen_utils.app_utils import get_value_at_index + +class WorkflowExecutor: + @staticmethod + def topological_sort(workflow: Dict[str, Any]) -> List[str]: + graph = defaultdict(list) + in_degree = {node_id: 0 for node_id in workflow} + + for node_id, node_info in workflow.items(): + for input_value in node_info.get('inputs', {}).values(): + if isinstance(input_value, list) and len(input_value) == 2 and isinstance(input_value[0], str): + source_node_id = input_value[0] + if source_node_id in workflow: + graph[source_node_id].append(node_id) + in_degree[node_id] += 1 + + queue = deque([node_id for node_id, degree in in_degree.items() if degree == 0]) + + sorted_nodes = [] + while queue: + current_node_id = queue.popleft() + sorted_nodes.append(current_node_id) + + for neighbor_node_id in graph[current_node_id]: + in_degree[neighbor_node_id] -= 1 + if in_degree[neighbor_node_id] == 0: + queue.append(neighbor_node_id) + + if len(sorted_nodes) != len(workflow): + raise RuntimeError("Workflow contains a cycle and cannot be executed.") + + return sorted_nodes + + @staticmethod + def execute_workflow(workflow: Dict[str, Any], initial_objects: Dict[str, Any]): + with torch.no_grad(): + computed_outputs = initial_objects + + try: + sorted_node_ids = WorkflowExecutor.topological_sort(workflow) + + final_node_id = None + for node_id in reversed(sorted_node_ids): + if workflow[node_id].get('class_type') == 'SaveImage': + final_node_id = node_id + break + + if final_node_id: + required_nodes = set() + nodes_to_visit = [final_node_id] + while nodes_to_visit: + curr_id = nodes_to_visit.pop() + if curr_id in required_nodes: + continue + required_nodes.add(curr_id) + curr_info = workflow.get(curr_id, {}) + for input_val in curr_info.get('inputs', {}).values(): + if isinstance(input_val, list) and len(input_val) == 2 and isinstance(input_val[0], str): + src_id = input_val[0] + if src_id in workflow and src_id not in required_nodes: + nodes_to_visit.append(src_id) + + sorted_node_ids = [nid for nid in sorted_node_ids if nid in required_nodes] + + print(f"--- [Workflow Executor] Execution order: {sorted_node_ids}") + except RuntimeError as e: + print("--- [Workflow Executor] ERROR: Failed to sort workflow. Dumping graph details. ---") + for node_id, node_info in workflow.items(): + print(f" Node {node_id} ({node_info['class_type']}):") + for input_name, input_value in node_info['inputs'].items(): + if isinstance(input_value, list) and len(input_value) == 2 and isinstance(input_value[0], str): + print(f" - {input_name} <- [{input_value[0]}, {input_value[1]}]") + raise e + + for node_id in sorted_node_ids: + if node_id in computed_outputs: + continue + + node_info = workflow[node_id] + class_type = node_info['class_type'] + + # The pipeline writes the final PNG itself so it can attach the + # canonical parameters and full workflow metadata. Executing + # ComfyUI's SaveImage here would create an untracked duplicate. + if class_type == 'SaveImage': + continue + + is_loader_with_filename = 'Loader' in class_type and any(key.endswith('_name') for key in node_info['inputs']) + if node_id in initial_objects and is_loader_with_filename: + continue + + node_class = NODE_CLASS_MAPPINGS.get(class_type) + if node_class is None: + raise RuntimeError(f"Could not find node class '{class_type}'. Is it imported in comfy_integration/nodes.py?") + + node_instance = node_class() + + kwargs = {} + for param_name, param_value in node_info['inputs'].items(): + if isinstance(param_value, list) and len(param_value) == 2 and isinstance(param_value[0], str): + source_node_id, output_index = param_value + if source_node_id not in computed_outputs: + raise RuntimeError(f"Workflow integrity error: Output of node {source_node_id} needed for {node_id} but not yet computed.") + + source_output_tuple = computed_outputs[source_node_id] + actual_value = get_value_at_index(source_output_tuple, output_index) + else: + actual_value = param_value + + if '.' in param_name: + parent_key, child_key = param_name.split('.', 1) + if parent_key not in kwargs or not isinstance(kwargs[parent_key], dict): + kwargs[parent_key] = {} + kwargs[parent_key][child_key] = actual_value + else: + kwargs[param_name] = actual_value + + function_name = getattr(node_class, 'FUNCTION') + execution_method = getattr(node_instance, function_name) + + result = execution_method(**kwargs) + computed_outputs[node_id] = result + + final_node_id = None + for node_id in reversed(sorted_node_ids): + if workflow[node_id]['class_type'] == 'SaveImage': + final_node_id = node_id + break + + if not final_node_id: + raise RuntimeError("Workflow does not contain a 'SaveImage' node as the output.") + + save_image_inputs = workflow[final_node_id]['inputs'] + image_source_node_id, image_source_index = save_image_inputs['images'] + + return get_value_at_index(computed_outputs[image_source_node_id], image_source_index) diff --git a/core/pipelines/workflow_recipes/_partials/_base_sampler.yaml b/core/pipelines/workflow_recipes/_partials/_base_sampler.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6ed23d8ace348a08c55db727cb8cd490455eed21 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/_base_sampler.yaml @@ -0,0 +1,28 @@ +nodes: + ksampler: + class_type: KSampler + title: "KSampler" + params: + denoise: 1.0 + vae_decode: + class_type: VAEDecode + title: "VAE Decode" + save_image: + class_type: SaveImage + title: "Save Image" + params: {} + +connections: + - from: "ksampler:0" + to: "vae_decode:samples" + - from: "vae_decode:0" + to: "save_image:images" + +ui_map: + seed: "ksampler:seed" + steps: "ksampler:steps" + cfg: "ksampler:cfg" + sampler_name: "ksampler:sampler_name" + scheduler: "ksampler:scheduler" + denoise: "ksampler:denoise" + filename_prefix: "save_image:filename_prefix" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/anima.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/anima.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0e04432d6d1de085e66ff88ee6a348ccf599aca4 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/anima.yaml @@ -0,0 +1,70 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + unet_loader: + class_type: UNETLoader + title: "Load Diffusion Model" + params: + weight_dtype: "default" + vae_loader: + class_type: VAELoader + title: "Load VAE" + clip_loader: + class_type: CLIPLoader + title: "Load CLIP" + params: + type: "stable_diffusion" + device: "default" + +connections: + - from: "unet_loader:0" + to: "ksampler:model" + - from: "clip_loader:0" + to: "pos_prompt:clip" + - from: "clip_loader:0" + to: "neg_prompt:clip" + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + output_map: + "unet_loader:0": "model" + "clip_loader:0": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["ksampler:model"] + "clip": ["pos_prompt:clip", "neg_prompt:clip"] + +dynamic_anima_controlnet_lllite_chains: + anima_controlnet_lllite_chain: + ksampler_node: "ksampler" + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "clip_loader:0" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + unet_name: "unet_loader:unet_name" + vae_name: "vae_loader:vae_name" + clip_name: "clip_loader:clip_name" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/auraflow.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/auraflow.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7b824cc6cd45e6ac6de42e6a970fb4f0468b4cf7 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/auraflow.yaml @@ -0,0 +1,56 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + ckpt_loader: + class_type: CheckpointLoaderSimple + title: "Load Checkpoint" + +connections: + - from: "ckpt_loader:0" + to: "ksampler:model" + - from: "ckpt_loader:1" + to: "pos_prompt:clip" + - from: "ckpt_loader:1" + to: "neg_prompt:clip" + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + - from: "ckpt_loader:2" + to: "vae_decode:vae" + - from: "ckpt_loader:2" + to: "vae_encode:vae" + +dynamic_vae_chains: + vae_chain: + targets: + - "vae_decode:vae" + - "vae_encode:vae" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + start: "ckpt_loader" + output_map: + "0": "model" + "1": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["ksampler:model"] + "clip": ["pos_prompt:clip", "neg_prompt:clip"] + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "ckpt_loader:1" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + model_name: "ckpt_loader:ckpt_name" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/boogu-image.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/boogu-image.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ef8d526211c8ec58944273d89d58fa82012937cf --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/boogu-image.yaml @@ -0,0 +1,67 @@ +nodes: + boogu_prompt: + class_type: TextEncodeBooguEdit + title: "Text Encode Boogu Edit" + unet_loader: + class_type: UNETLoader + title: "Load Diffusion Model" + params: + weight_dtype: "default" + clip_loader: + class_type: CLIPLoader + title: "Load CLIP" + params: + type: "boogu" + device: "default" + vae_loader: + class_type: VAELoader + title: "Load VAE" + +connections: + - from: "unet_loader:0" + to: "ksampler:model" + - from: "clip_loader:0" + to: "boogu_prompt:clip" + - from: "boogu_prompt:0" + to: "ksampler:positive" + - from: "boogu_prompt:1" + to: "ksampler:negative" + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + output_map: + "unet_loader:0": "model" + "clip_loader:0": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["ksampler:model"] + "clip": ["boogu_prompt:clip"] + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "clip_loader:0" + +dynamic_boogu_image_edit_chains: + boogu_image_edit_chain: + ksampler_node: "ksampler" + boogu_prompt_node: "boogu_prompt" + vae_loader_node: "vae_loader" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +ui_map: + positive_prompt: "boogu_prompt:prompt" + negative_prompt: "boogu_prompt:negative_prompt" + unet_name: "unet_loader:unet_name" + clip_name: "clip_loader:clip_name" + vae_name: "vae_loader:vae_name" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/chroma1-radiance.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/chroma1-radiance.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6315d0a26267b327db694a80a26399818dc63a02 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/chroma1-radiance.yaml @@ -0,0 +1,67 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + unet_loader: + class_type: UNETLoader + title: "Load Diffusion Model" + params: + weight_dtype: "default" + vae_loader: + class_type: VAELoader + title: "Load VAE" + params: + vae_name: "pixel_space" + clip_loader: + class_type: CLIPLoader + title: "Load CLIP" + params: + type: "chroma" + device: "default" + t5_tokenizer: + class_type: T5TokenizerOptions + title: "T5TokenizerOptions" + params: + min_padding: 0 + min_length: 3 + model_sampler: + class_type: ModelSamplingAuraFlow + params: + shift: 3.0 + +connections: + - from: "unet_loader:0" + to: "model_sampler:model" + - from: "model_sampler:0" + to: "ksampler:model" + + - from: "clip_loader:0" + to: "t5_tokenizer:clip" + - from: "t5_tokenizer:0" + to: "pos_prompt:clip" + - from: "t5_tokenizer:0" + to: "neg_prompt:clip" + + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "t5_tokenizer:0" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + unet_name: "unet_loader:unet_name" + clip_name: "clip_loader:clip_name" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/chroma1.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/chroma1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9df8f47336a8932fdb13e1e11f536a4cc26149b0 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/chroma1.yaml @@ -0,0 +1,73 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + unet_loader: + class_type: UNETLoader + title: "Load Diffusion Model" + params: + weight_dtype: "default" + vae_loader: + class_type: VAELoader + title: "Load VAE" + clip_loader: + class_type: CLIPLoader + title: "Load CLIP" + params: + type: "chroma" + device: "default" + t5_tokenizer: + class_type: T5TokenizerOptions + title: "T5TokenizerOptions" + params: + min_padding: 1 + min_length: 0 + fresca: + class_type: FreSca + title: "FreSca" + params: + scale_low: 1.0 + scale_high: 2.5 + freq_cutoff: 30 + +connections: + - from: "unet_loader:0" + to: "fresca:model" + - from: "fresca:0" + to: "ksampler:model" + + - from: "clip_loader:0" + to: "t5_tokenizer:clip" + - from: "t5_tokenizer:0" + to: "pos_prompt:clip" + - from: "t5_tokenizer:0" + to: "neg_prompt:clip" + + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "t5_tokenizer:0" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + unet_name: "unet_loader:unet_name" + vae_name: "vae_loader:vae_name" + clip_name: "clip_loader:clip_name" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/cosmos-predict2.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/cosmos-predict2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..60ba4c003c1337fe32100c1032baf5c16324e4e1 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/cosmos-predict2.yaml @@ -0,0 +1,55 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + unet_loader: + class_type: UNETLoader + title: "Load Diffusion Model" + params: + weight_dtype: "default" + vae_loader: + class_type: VAELoader + title: "Load VAE" + clip_loader: + class_type: CLIPLoader + title: "Load CLIP" + params: + type: "cosmos" + device: "default" + +connections: + - from: "unet_loader:0" + to: "ksampler:model" + - from: "clip_loader:0" + to: "pos_prompt:clip" + - from: "clip_loader:0" + to: "neg_prompt:clip" + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + +dynamic_vae_chains: + vae_chain: + targets: + - "vae_decode:vae" + - "vae_encode:vae" + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "clip_loader:0" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + unet_name: "unet_loader:unet_name" + vae_name: "vae_loader:vae_name" + clip_name: "clip_loader:clip_name" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/ernie-image.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/ernie-image.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6b544db30640b5b92786d0caaf1ca31746296826 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/ernie-image.yaml @@ -0,0 +1,66 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + unet_loader: + class_type: UNETLoader + title: "Load Diffusion Model" + params: + weight_dtype: "default" + clip_loader: + class_type: CLIPLoader + title: "Load CLIP" + params: + type: "flux2" + device: "default" + vae_loader: + class_type: VAELoader + title: "Load VAE" + +connections: + - from: "unet_loader:0" + to: "ksampler:model" + - from: "clip_loader:0" + to: "pos_prompt:clip" + - from: "clip_loader:0" + to: "neg_prompt:clip" + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + output_map: + "unet_loader:0": "model" + "clip_loader:0": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["ksampler:model"] + "clip": ["pos_prompt:clip", "neg_prompt:clip"] + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "clip_loader:0" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + unet_name: "unet_loader:unet_name" + clip_name: "clip_loader:clip_name" + vae_name: "vae_loader:vae_name" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/flux1.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/flux1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6e59b0aec5af45a30a8ccdadc490275984d075f7 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/flux1.yaml @@ -0,0 +1,76 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + unet_loader: + class_type: UNETLoader + title: "Load FLUX UNET" + params: + weight_dtype: "default" + vae_loader: + class_type: VAELoader + title: "Load FLUX VAE" + clip_loader: + class_type: DualCLIPLoader + title: "Load FLUX Dual CLIP" + params: + type: "flux" + device: "default" + flux_guidance: + class_type: FluxGuidance + title: "FluxGuidance" + +connections: + - from: "unet_loader:0" + to: "ksampler:model" + - from: "clip_loader:0" + to: "pos_prompt:clip" + - from: "clip_loader:0" + to: "neg_prompt:clip" + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + - from: "pos_prompt:0" + to: "flux_guidance:conditioning" + - from: "flux_guidance:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + +dynamic_controlnet_chains: + controlnet_chain: + template: "ControlNetApplyAdvanced" + ksampler_node: "ksampler" + vae_source: "vae_loader:0" + +dynamic_flux1_ipadapter_chains: + flux1_ipadapter_chain: + ksampler_node: "ksampler" + +dynamic_style_chains: + style_chain: + flux_guidance_node: "flux_guidance" + ksampler_node: "ksampler" + +dynamic_conditioning_chains: + conditioning_chain: + flux_guidance_node: "flux_guidance" + ksampler_node: "ksampler" + clip_source: "clip_loader:0" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + unet_name: "unet_loader:unet_name" + vae_name: "vae_loader:vae_name" + clip1_name: "clip_loader:clip_name1" + clip2_name: "clip_loader:clip_name2" + guidance: "flux_guidance:guidance" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/flux2-kv.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/flux2-kv.yaml new file mode 100644 index 0000000000000000000000000000000000000000..19e8eb25562e2c87e4398aaaadeb9360dbf40305 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/flux2-kv.yaml @@ -0,0 +1,108 @@ +nodes: + unet_loader: + class_type: UNETLoader + title: "Load Diffusion Model" + params: + weight_dtype: "default" + clip_loader: + class_type: CLIPLoader + title: "Load CLIP" + params: + type: "flux2" + device: "default" + vae_loader: + class_type: VAELoader + title: "Load VAE" + + flux_kv_cache: + class_type: FluxKVCache + title: "Flux KV Cache" + + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + + ksampler: + class_type: KSampler + title: "KSampler" + params: + denoise: 1.0 + + vae_decode: + class_type: VAEDecode + title: "VAE Decode" + + save_image: + class_type: SaveImage + title: "Save Image" + +connections: + - from: "unet_loader:0" + to: "flux_kv_cache:model" + - from: "flux_kv_cache:0" + to: "ksampler:model" + + - from: "clip_loader:0" + to: "pos_prompt:clip" + - from: "clip_loader:0" + to: "neg_prompt:clip" + + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + + - from: "latent_source:0" + to: "ksampler:latent_image" + + - from: "ksampler:0" + to: "vae_decode:samples" + - from: "vae_decode:0" + to: "save_image:images" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + output_map: + "unet_loader:0": "model" + "clip_loader:0": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["flux_kv_cache:model"] + "clip": ["pos_prompt:clip", "neg_prompt:clip"] + +dynamic_reference_latent_chains: + reference_latent_chain: + ksampler_node: "ksampler" + vae_node: "vae_loader" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +ui_map: + unet_name: "unet_loader:unet_name" + clip_name: "clip_loader:clip_name" + vae_name: "vae_loader:vae_name" + + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + + seed: "ksampler:seed" + steps: "ksampler:steps" + cfg: "ksampler:cfg" + sampler_name: "ksampler:sampler_name" + scheduler: "ksampler:scheduler" + denoise: "ksampler:denoise" + + filename_prefix: "save_image:filename_prefix" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/flux2.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/flux2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a616a4520fa1fe35ecbf1c9902811d5b4f130033 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/flux2.yaml @@ -0,0 +1,100 @@ +nodes: + unet_loader: + class_type: UNETLoader + title: "Load Diffusion Model" + params: + weight_dtype: "default" + clip_loader: + class_type: CLIPLoader + title: "Load CLIP" + params: + type: "flux2" + device: "default" + vae_loader: + class_type: VAELoader + title: "Load VAE" + + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + + ksampler: + class_type: KSampler + title: "KSampler" + params: + denoise: 1.0 + + vae_decode: + class_type: VAEDecode + title: "VAE Decode" + + save_image: + class_type: SaveImage + title: "Save Image" + +connections: + - from: "unet_loader:0" + to: "ksampler:model" + - from: "clip_loader:0" + to: "pos_prompt:clip" + - from: "clip_loader:0" + to: "neg_prompt:clip" + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + + - from: "latent_source:0" + to: "ksampler:latent_image" + + - from: "ksampler:0" + to: "vae_decode:samples" + - from: "vae_decode:0" + to: "save_image:images" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + output_map: + "unet_loader:0": "model" + "clip_loader:0": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["ksampler:model"] + "clip": ["pos_prompt:clip", "neg_prompt:clip"] + +dynamic_reference_latent_chains: + reference_latent_chain: + ksampler_node: "ksampler" + vae_node: "vae_loader" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +ui_map: + unet_name: "unet_loader:unet_name" + clip_name: "clip_loader:clip_name" + vae_name: "vae_loader:vae_name" + + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + + seed: "ksampler:seed" + steps: "ksampler:steps" + cfg: "ksampler:cfg" + sampler_name: "ksampler:sampler_name" + scheduler: "ksampler:scheduler" + denoise: "ksampler:denoise" + + filename_prefix: "save_image:filename_prefix" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/hidream-i1.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/hidream-i1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..019d5bfe63a730bfabd8894bdf33ab3bf41f8098 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/hidream-i1.yaml @@ -0,0 +1,65 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + unet_loader: + class_type: UNETLoader + title: "Load HiDream-I1 UNET" + params: + weight_dtype: "default" + vae_loader: + class_type: VAELoader + title: "Load HiDream-I1 VAE" + clip_loader: + class_type: QuadrupleCLIPLoader + title: "Load HiDream-I1 Quadruple CLIP" + + model_sampler: + class_type: ModelSamplingSD3 + title: "ModelSamplingSD3" + params: + shift: 6.0 + +connections: + - from: "unet_loader:0" + to: "model_sampler:model" + + - from: "model_sampler:0" + to: "ksampler:model" + + - from: "clip_loader:0" + to: "pos_prompt:clip" + - from: "clip_loader:0" + to: "neg_prompt:clip" + + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "clip_loader:0" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + unet_name: "unet_loader:unet_name" + vae_name: "vae_loader:vae_name" + clip1_name: "clip_loader:clip_name1" + clip2_name: "clip_loader:clip_name2" + clip3_name: "clip_loader:clip_name3" + clip4_name: "clip_loader:clip_name4" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/hidream-o1.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/hidream-o1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6b2420e92a6a2627f25b2ccc06af39377b5b125e --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/hidream-o1.yaml @@ -0,0 +1,76 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + ckpt_loader: + class_type: CheckpointLoaderSimple + title: "Load Checkpoint" + + model_noise_scale: + class_type: ModelNoiseScale + title: "ModelNoiseScale" + params: + noise_scale: 8 + +connections: + - from: "ckpt_loader:0" + to: "model_noise_scale:model" + + - from: "model_noise_scale:0" + to: "ksampler:model" + + - from: "ckpt_loader:1" + to: "pos_prompt:clip" + - from: "ckpt_loader:1" + to: "neg_prompt:clip" + + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + + - from: "ckpt_loader:2" + to: "vae_decode:vae" + - from: "ckpt_loader:2" + to: "vae_encode:vae" + +dynamic_vae_chains: + vae_chain: + targets: + - "vae_decode:vae" + - "vae_encode:vae" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + start: "ckpt_loader" + output_map: + "0": "model" + "1": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["model_noise_scale:model"] + "clip": ["pos_prompt:clip", "neg_prompt:clip"] + +dynamic_hidream_o1_smoothing_chains: + hidream_o1_smoothing_chain: + target_node: "ksampler" + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "ckpt_loader:1" + +dynamic_hidream_o1_reference_chains: + hidream_o1_reference_chain: + ksampler_node: "ksampler" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + model_name: "ckpt_loader:ckpt_name" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/hunyuanimage.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/hunyuanimage.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0208a62b6ee3f064bf87fc302a474ee726ef1996 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/hunyuanimage.yaml @@ -0,0 +1,50 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + unet_loader: + class_type: UNETLoader + title: "Load Hunyuan UNET" + params: + weight_dtype: "default" + vae_loader: + class_type: VAELoader + title: "Load Hunyuan VAE" + clip_loader: + class_type: DualCLIPLoader + title: "Load Hunyuan Dual CLIP" + params: + type: "hunyuan_image" + device: "default" + +connections: + - from: "unet_loader:0" + to: "ksampler:model" + - from: "clip_loader:0" + to: "pos_prompt:clip" + - from: "clip_loader:0" + to: "neg_prompt:clip" + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "clip_loader:0" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + unet_name: "unet_loader:unet_name" + vae_name: "vae_loader:vae_name" + clip1_name: "clip_loader:clip_name1" + clip2_name: "clip_loader:clip_name2" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/ideogram-4.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/ideogram-4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d4af47cc34f67c6ac82c6f3a128f45763c721764 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/ideogram-4.yaml @@ -0,0 +1,122 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + unet_loader: + class_type: UNETLoader + title: "Load Diffusion Model" + params: + weight_dtype: "default" + cfg_override: + class_type: CFGOverride + title: "CFG Override" + params: + start_percent: 0.9 + end_percent: 1.0 + unet_uncond_loader: + class_type: UNETLoader + title: "Load Unconditional Model" + params: + weight_dtype: "default" + guider: + class_type: DualModelGuider + title: "Dual Model CFG Guider" + clip_loader: + class_type: CLIPLoader + title: "Load CLIP" + params: + type: "ideogram4" + device: "default" + ksampler_select: + class_type: KSamplerSelect + scheduler_node: + class_type: Ideogram4Scheduler + params: + mu: 0.5 + std: 1.75 + random_noise: + class_type: RandomNoise + ksampler: + class_type: SamplerCustomAdvanced + vae_loader: + class_type: VAELoader + title: "Load VAE" + +connections: + - from: "unet_loader:0" + to: "cfg_override:model" + - from: "cfg_override:0" + to: "guider:model" + - from: "unet_uncond_loader:0" + to: "guider:model_negative" + + - from: "clip_loader:0" + to: "pos_prompt:clip" + - from: "clip_loader:0" + to: "neg_prompt:clip" + + - from: "pos_prompt:0" + to: "guider:positive" + - from: "neg_prompt:0" + to: "guider:negative" + + - from: "guider:0" + to: "ksampler:guider" + - from: "ksampler_select:0" + to: "ksampler:sampler" + - from: "scheduler_node:0" + to: "ksampler:sigmas" + - from: "random_noise:0" + to: "ksampler:noise" + + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + output_map: + "unet_loader:0": "model" + "clip_loader:0": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["cfg_override:model"] + "clip": ["pos_prompt:clip", "neg_prompt:clip"] + +dynamic_conditioning_chains: + conditioning_chain: + guider_node: "guider" + guider_target_inputs: ["positive"] + clip_source: "clip_loader:0" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + unet_name: "unet_loader:unet_name" + unet_uncond_name: "unet_uncond_loader:unet_name" + clip_name: "clip_loader:clip_name" + vae_name: "vae_loader:vae_name" + + scheduler_width: "scheduler_node:width" + scheduler_height: "scheduler_node:height" + + seed: "random_noise:noise_seed" + steps: "scheduler_node:steps" + cfg: + - "guider:cfg" + - "cfg_override:cfg" + sampler_name: "ksampler_select:sampler_name" + + scheduler: "dummy:scheduler" + denoise: "dummy:denoise" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/joyai-image.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/joyai-image.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b183543a0f3365145a09aa59531281fbfa9b921f --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/joyai-image.yaml @@ -0,0 +1,85 @@ +nodes: + unet_loader: + class_type: UNETLoader + title: "Load Diffusion Model" + params: + weight_dtype: "default" + vae_loader: + class_type: VAELoader + title: "Load VAE" + clip_loader: + class_type: CLIPLoader + title: "Load CLIP" + params: + type: "joyimage" + device: "default" + + pos_prompt: + class_type: TextEncodeJoyImageEdit + title: "TextEncodeJoyImageEdit (Positive)" + neg_prompt: + class_type: TextEncodeJoyImageEdit + title: "TextEncodeJoyImageEdit (Negative)" + + cfg_norm: + class_type: CFGNorm + title: "CFGNorm" + params: + strength: 1.0 + pre_cfg: true + +connections: + - from: "unet_loader:0" + to: "cfg_norm:model" + - from: "cfg_norm:0" + to: "ksampler:model" + + - from: "clip_loader:0" + to: "pos_prompt:clip" + - from: "clip_loader:0" + to: "neg_prompt:clip" + + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + output_map: + "unet_loader:0": "model" + "clip_loader:0": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["cfg_norm:model"] + "clip": ["pos_prompt:clip", "neg_prompt:clip"] + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "clip_loader:0" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +dynamic_joyai_image_chains: + joyai_image_chain: + pos_prompt_node: "pos_prompt" + neg_prompt_node: "neg_prompt" + vae_node: "vae_loader" + +ui_map: + unet_name: "unet_loader:unet_name" + vae_name: "vae_loader:vae_name" + clip_name: "clip_loader:clip_name" + positive_prompt: "pos_prompt:prompt" + negative_prompt: "neg_prompt:prompt" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/kandinsky-5.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/kandinsky-5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bdcac973cc6f78d8bf1d64db6155aec8cc121ee0 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/kandinsky-5.yaml @@ -0,0 +1,80 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + unet_loader: + class_type: UNETLoader + title: "Load Diffusion Model" + params: + weight_dtype: "default" + vae_loader: + class_type: VAELoader + title: "Load VAE" + clip_loader: + class_type: DualCLIPLoader + title: "DualCLIPLoader" + params: + type: "kandinsky5_image" + device: "default" + model_sampler: + class_type: ModelSamplingSD3 + title: "ModelSamplingSD3" + params: + shift: 3.0 + +connections: + - from: "unet_loader:0" + to: "model_sampler:model" + - from: "model_sampler:0" + to: "ksampler:model" + - from: "clip_loader:0" + to: "pos_prompt:clip" + - from: "clip_loader:0" + to: "neg_prompt:clip" + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + output_map: + "unet_loader:0": "model" + "clip_loader:0": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["model_sampler:model"] + "clip": ["pos_prompt:clip", "neg_prompt:clip"] + +dynamic_controlnet_chains: + controlnet_chain: + template: "ControlNetApplyAdvanced" + ksampler_node: "ksampler" + vae_source: "vae_loader:0" + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "clip_loader:0" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + unet_name: "unet_loader:unet_name" + vae_name: "vae_loader:vae_name" + clip1_name: "clip_loader:clip_name1" + clip2_name: "clip_loader:clip_name2" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/krea-2.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/krea-2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5143ef8a07672d453b54397ed72d643ea0082a3e --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/krea-2.yaml @@ -0,0 +1,87 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + unet_loader: + class_type: UNETLoader + title: "Load Diffusion Model" + params: + weight_dtype: "default" + clip_loader: + class_type: CLIPLoader + title: "Load CLIP" + params: + type: "krea2" + device: "default" + vae_loader: + class_type: VAELoader + title: "Load VAE" + +connections: + - from: "unet_loader:0" + to: "ksampler:model" + - from: "clip_loader:0" + to: "pos_prompt:clip" + - from: "clip_loader:0" + to: "neg_prompt:clip" + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + output_map: + "unet_loader:0": "model" + "clip_loader:0": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["ksampler:model"] + "clip": ["pos_prompt:clip", "neg_prompt:clip"] + +dynamic_krea2_controlnet_chains: + krea2_controlnet_chain: + ksampler_node: "ksampler" + vae_source: "vae_loader:0" + +dynamic_krea2_identity_edit_chains: + krea2_identity_edit_chain: + ksampler_node: "ksampler" + pos_prompt_node: "pos_prompt" + neg_prompt_node: "neg_prompt" + clip_loader_node: "clip_loader" + vae_loader_node: "vae_loader" + +dynamic_krea2_style_reference_chains: + krea2_style_reference_chain: + ksampler_node: "ksampler" + pos_prompt_node: "pos_prompt" + neg_prompt_node: "neg_prompt" + clip_loader_node: "clip_loader" + vae_loader_node: "vae_loader" + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "clip_loader:0" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + unet_name: "unet_loader:unet_name" + clip_name: "clip_loader:clip_name" + vae_name: "vae_loader:vae_name" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/lens.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/lens.yaml new file mode 100644 index 0000000000000000000000000000000000000000..876e104ecffe6fb21299350505a81807a1abf435 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/lens.yaml @@ -0,0 +1,66 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + unet_loader: + class_type: UNETLoader + title: "Load Diffusion Model" + params: + weight_dtype: "default" + clip_loader: + class_type: CLIPLoader + title: "Load CLIP" + params: + type: "lens" + device: "default" + vae_loader: + class_type: VAELoader + title: "Load VAE" + +connections: + - from: "unet_loader:0" + to: "ksampler:model" + - from: "clip_loader:0" + to: "pos_prompt:clip" + - from: "clip_loader:0" + to: "neg_prompt:clip" + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + output_map: + "unet_loader:0": "model" + "clip_loader:0": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["ksampler:model"] + "clip": ["pos_prompt:clip", "neg_prompt:clip"] + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "clip_loader:0" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + unet_name: "unet_loader:unet_name" + clip_name: "clip_loader:clip_name" + vae_name: "vae_loader:vae_name" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/longcat-image.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/longcat-image.yaml new file mode 100644 index 0000000000000000000000000000000000000000..04f22254637a5c926dc08a8a4d622d10bb0fd1b8 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/longcat-image.yaml @@ -0,0 +1,95 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + unet_loader: + class_type: UNETLoader + title: "Load Diffusion Model" + params: + weight_dtype: "default" + vae_loader: + class_type: VAELoader + title: "Load VAE" + clip_loader: + class_type: CLIPLoader + title: "Load CLIP" + params: + type: "longcat_image" + device: "default" + + cfg_norm: + class_type: CFGNorm + title: "CFGNorm" + params: + strength: 1.0 + + flux_guidance_pos: + class_type: FluxGuidance + title: "FluxGuidance (Positive)" + params: + guidance: 4.0 + + flux_guidance_neg: + class_type: FluxGuidance + title: "FluxGuidance (Negative)" + params: + guidance: 4.0 + +connections: + - from: "unet_loader:0" + to: "cfg_norm:model" + - from: "cfg_norm:0" + to: "ksampler:model" + + - from: "clip_loader:0" + to: "pos_prompt:clip" + - from: "clip_loader:0" + to: "neg_prompt:clip" + + - from: "pos_prompt:0" + to: "flux_guidance_pos:conditioning" + - from: "neg_prompt:0" + to: "flux_guidance_neg:conditioning" + + - from: "flux_guidance_pos:0" + to: "ksampler:positive" + - from: "flux_guidance_neg:0" + to: "ksampler:negative" + + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + output_map: + "unet_loader:0": "model" + "clip_loader:0": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["cfg_norm:model"] + "clip": ["pos_prompt:clip", "neg_prompt:clip"] + +dynamic_conditioning_chains: + conditioning_chain: + flux_guidance_node: "flux_guidance_pos" + ksampler_node: "ksampler" + clip_source: "clip_loader:0" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + unet_name: "unet_loader:unet_name" + vae_name: "vae_loader:vae_name" + clip_name: "clip_loader:clip_name" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/lumina.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/lumina.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4afa84fd455bc29b03ba40b250b7a4eae4bdbde7 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/lumina.yaml @@ -0,0 +1,69 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + ckpt_loader: + class_type: CheckpointLoaderSimple + title: "Load Checkpoint" + model_sampler: + class_type: ModelSamplingAuraFlow + title: "ModelSamplingAuraFlow" + params: + shift: 4.0 + +connections: + - from: "ckpt_loader:0" + to: "model_sampler:model" + - from: "model_sampler:0" + to: "ksampler:model" + + - from: "ckpt_loader:1" + to: "pos_prompt:clip" + - from: "ckpt_loader:1" + to: "neg_prompt:clip" + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + + - from: "ckpt_loader:2" + to: "vae_decode:vae" + - from: "ckpt_loader:2" + to: "vae_encode:vae" + +dynamic_vae_chains: + vae_chain: + targets: + - "vae_decode:vae" + - "vae_encode:vae" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + start: "ckpt_loader" + output_map: + "0": "model" + "1": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["model_sampler:model"] + "clip": ["pos_prompt:clip", "neg_prompt:clip"] + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "ckpt_loader:1" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + model_name: "ckpt_loader:ckpt_name" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/mage-flow.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/mage-flow.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ff47f667039ece6b3a3247b544292b5a9b88b024 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/mage-flow.yaml @@ -0,0 +1,77 @@ +nodes: + unet_loader: + class_type: UNETLoader + title: "Load Diffusion Model" + params: + weight_dtype: "default" + vae_loader: + class_type: VAELoader + title: "Load VAE" + clip_loader: + class_type: CLIPLoader + title: "Load CLIP" + params: + type: "mage" + device: "default" + text_encode_latent: + class_type: TextEncodeMageFlowEdit + title: "TextEncodeMageFlowEdit" + +connections: + - from: "unet_loader:0" + to: "ksampler:model" + - from: "clip_loader:0" + to: "text_encode_latent:clip" + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + - from: "text_encode_latent:0" + to: "ksampler:positive" + - from: "text_encode_latent:1" + to: "ksampler:negative" + - from: "text_encode_latent:2" + to: "ksampler:latent_image" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + output_map: + "unet_loader:0": "model" + "clip_loader:0": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["ksampler:model"] + "clip": ["text_encode_latent:clip"] + +dynamic_controlnet_chains: + controlnet_chain: + template: "ControlNetApplyAdvanced" + ksampler_node: "ksampler" + vae_source: "vae_loader:0" + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "clip_loader:0" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +dynamic_reference_image_chains: + reference_image_chain: + text_encode_node: "text_encode_latent" + vae_node: "vae_loader" + +ui_map: + unet_name: "unet_loader:unet_name" + vae_name: "vae_loader:vae_name" + clip_name: "clip_loader:clip_name" + positive_prompt: "text_encode_latent:prompt" + negative_prompt: "text_encode_latent:negative_prompt" + width: "text_encode_latent:width" + height: "text_encode_latent:height" + batch_size: "text_encode_latent:batch_size" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/newbie-image.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/newbie-image.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0546349d28859ee42eb2da788305891e3fa148e6 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/newbie-image.yaml @@ -0,0 +1,77 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + unet_loader: + class_type: UNETLoader + title: "Load Diffusion Model" + params: + weight_dtype: "default" + vae_loader: + class_type: VAELoader + title: "Load VAE" + clip_loader: + class_type: DualCLIPLoader + title: "Load Dual CLIP" + params: + type: "newbie" + device: "default" + model_sampler: + class_type: ModelSamplingAuraFlow + title: "ModelSamplingAuraFlow" + params: + shift: 6 + +connections: + - from: "unet_loader:0" + to: "model_sampler:model" + - from: "model_sampler:0" + to: "ksampler:model" + + - from: "clip_loader:0" + to: "pos_prompt:clip" + - from: "clip_loader:0" + to: "neg_prompt:clip" + + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + output_map: + "unet_loader:0": "model" + "clip_loader:0": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["model_sampler:model"] + "clip": ["pos_prompt:clip", "neg_prompt:clip"] + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "clip_loader:0" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + unet_name: "unet_loader:unet_name" + vae_name: "vae_loader:vae_name" + clip1_name: "clip_loader:clip_name1" + clip2_name: "clip_loader:clip_name2" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/omnigen2.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/omnigen2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9fd46c1af93ee738a31f76e1c5696fb0d4db0e7a --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/omnigen2.yaml @@ -0,0 +1,71 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + unet_loader: + class_type: UNETLoader + title: "Load Diffusion Model" + params: + weight_dtype: "default" + vae_loader: + class_type: VAELoader + title: "Load VAE" + clip_loader: + class_type: CLIPLoader + title: "Load CLIP" + params: + type: "omnigen2" + device: "default" + +connections: + - from: "unet_loader:0" + to: "ksampler:model" + - from: "clip_loader:0" + to: "pos_prompt:clip" + - from: "clip_loader:0" + to: "neg_prompt:clip" + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + output_map: + "unet_loader:0": "model" + "clip_loader:0": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["ksampler:model"] + "clip": ["pos_prompt:clip", "neg_prompt:clip"] + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "clip_loader:0" + +dynamic_reference_latent_chains: + reference_latent_chain: + ksampler_node: "ksampler" + vae_node: "vae_loader" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + unet_name: "unet_loader:unet_name" + vae_name: "vae_loader:vae_name" + clip_name: "clip_loader:clip_name" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/ovis-image.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/ovis-image.yaml new file mode 100644 index 0000000000000000000000000000000000000000..08de080574bd6ef52711b3349db7e959fda777a8 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/ovis-image.yaml @@ -0,0 +1,62 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + unet_loader: + class_type: UNETLoader + title: "Load Diffusion Model" + params: + weight_dtype: "default" + vae_loader: + class_type: VAELoader + title: "Load VAE" + clip_loader: + class_type: CLIPLoader + title: "Load CLIP" + params: + type: "ovis" + device: "default" + model_sampler: + class_type: ModelSamplingAuraFlow + params: + shift: 3.0 + +connections: + - from: "unet_loader:0" + to: "model_sampler:model" + - from: "model_sampler:0" + to: "ksampler:model" + + - from: "clip_loader:0" + to: "pos_prompt:clip" + - from: "clip_loader:0" + to: "neg_prompt:clip" + + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "clip_loader:0" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + unet_name: "unet_loader:unet_name" + vae_name: "vae_loader:vae_name" + clip_name: "clip_loader:clip_name" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/pixeldit.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/pixeldit.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0b8f8cd9e8f1a0c9106df7cd909bd3c15c0e3e3e --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/pixeldit.yaml @@ -0,0 +1,51 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + unet_loader: + class_type: UNETLoader + title: "Load Diffusion Model" + params: + weight_dtype: "default" + vae_loader: + class_type: VAELoader + title: "Load VAE" + params: + vae_name: "pixel_space" + clip_loader: + class_type: CLIPLoader + title: "Load CLIP" + params: + type: "pixeldit" + device: "default" + +connections: + - from: "unet_loader:0" + to: "ksampler:model" + - from: "clip_loader:0" + to: "pos_prompt:clip" + - from: "clip_loader:0" + to: "neg_prompt:clip" + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "clip_loader:0" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + unet_name: "unet_loader:unet_name" + vae_name: "vae_loader:vae_name" + clip_name: "clip_loader:clip_name" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/qwen-image.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/qwen-image.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8af1c263ce87effabaf51aaf6a8c49068bbc7f6f --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/qwen-image.yaml @@ -0,0 +1,91 @@ +nodes: + pos_prompt: + class_type: TextEncodeQwenImageEditPlus + title: "Text Encode Qwen Image Edit Plus (Positive)" + neg_prompt: + class_type: TextEncodeQwenImageEditPlus + title: "Text Encode Qwen Image Edit Plus (Negative)" + unet_loader: + class_type: UNETLoader + title: "Load Qwen UNET" + params: + weight_dtype: "default" + vae_loader: + class_type: VAELoader + title: "Load Qwen VAE" + clip_loader: + class_type: CLIPLoader + title: "Load Qwen CLIP" + params: + type: "qwen_image" + device: "default" + model_sampler: + class_type: ModelSamplingAuraFlow + title: "ModelSamplingAuraFlow" + params: + shift: 3.1 + +connections: + - from: "unet_loader:0" + to: "model_sampler:model" + + - from: "model_sampler:0" + to: "ksampler:model" + + - from: "clip_loader:0" + to: "pos_prompt:clip" + - from: "clip_loader:0" + to: "neg_prompt:clip" + + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + output_map: + "unet_loader:0": "model" + "clip_loader:0": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["model_sampler:model"] + "clip": ["pos_prompt:clip", "neg_prompt:clip"] + +dynamic_controlnet_chains: + controlnet_chain: + template: "ControlNetApplyAdvanced" + ksampler_node: "ksampler" + vae_source: "vae_loader:0" + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "clip_loader:0" + +dynamic_qwen_image_edit_chains: + qwen_image_edit_chain: + ksampler_node: "ksampler" + pos_prompt_node: "pos_prompt" + neg_prompt_node: "neg_prompt" + vae_loader_node: "vae_loader" + model_sampler_node: "model_sampler" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +ui_map: + positive_prompt: "pos_prompt:prompt" + negative_prompt: "neg_prompt:prompt" + unet_name: "unet_loader:unet_name" + vae_name: "vae_loader:vae_name" + clip_name: "clip_loader:clip_name" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/sd15.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/sd15.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cd466d7248b1634266a1b9a225da7c2232d2d606 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/sd15.yaml @@ -0,0 +1,77 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + ckpt_loader: + class_type: CheckpointLoaderSimple + title: "Load Checkpoint" + clip_set_last_layer: + class_type: CLIPSetLastLayer + title: "CLIP Set Last Layer" + +connections: + - from: "ckpt_loader:0" + to: "ksampler:model" + - from: "ckpt_loader:1" + to: "clip_set_last_layer:clip" + - from: "clip_set_last_layer:0" + to: "pos_prompt:clip" + - from: "clip_set_last_layer:0" + to: "neg_prompt:clip" + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + - from: "ckpt_loader:2" + to: "vae_decode:vae" + - from: "ckpt_loader:2" + to: "vae_encode:vae" + +dynamic_vae_chains: + vae_chain: + targets: + - "vae_decode:vae" + - "vae_encode:vae" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + start: "clip_set_last_layer" + output_map: + "ckpt_loader:0": "model" + "0": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["ksampler:model"] + "clip": ["pos_prompt:clip", "neg_prompt:clip"] + +dynamic_controlnet_chains: + controlnet_chain: + template: "ControlNetApplyAdvanced" + ksampler_node: "ksampler" + vae_source: "ckpt_loader:2" + +dynamic_ipadapter_chains: + ipadapter_chain: + end: "ksampler" + final_preset: "{{ ipadapter_final_preset }}" + final_weight: "{{ ipadapter_final_weight }}" + final_embeds_scaling: "{{ ipadapter_embeds_scaling }}" + final_loader_type: "{{ ipadapter_final_loader_type }}" + final_lora_strength: "{{ ipadapter_final_lora_strength }}" + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "clip_set_last_layer:0" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + model_name: "ckpt_loader:ckpt_name" + clip_skip: "clip_set_last_layer:stop_at_clip_layer" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/sd35.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/sd35.yaml new file mode 100644 index 0000000000000000000000000000000000000000..05b696950892f7cc5b45b94e04ddb74424102515 --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/sd35.yaml @@ -0,0 +1,70 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + ckpt_loader: + class_type: CheckpointLoaderSimple + title: "Load Checkpoint" + +connections: + - from: "ckpt_loader:0" + to: "ksampler:model" + - from: "ckpt_loader:1" + to: "pos_prompt:clip" + - from: "ckpt_loader:1" + to: "neg_prompt:clip" + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + - from: "ckpt_loader:2" + to: "vae_decode:vae" + - from: "ckpt_loader:2" + to: "vae_encode:vae" + +dynamic_vae_chains: + vae_chain: + targets: + - "vae_decode:vae" + - "vae_encode:vae" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + start: "ckpt_loader" + output_map: + "0": "model" + "1": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["ksampler:model"] + "clip": ["pos_prompt:clip", "neg_prompt:clip"] + +dynamic_controlnet_chains: + controlnet_chain: + template: "ControlNetApplyAdvanced" + ksampler_node: "ksampler" + vae_source: "ckpt_loader:2" + +dynamic_sd3_ipadapter_chains: + sd3_ipadapter_chain: + ksampler_node: "ksampler" + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "ckpt_loader:1" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + model_name: "ckpt_loader:ckpt_name" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/sdxl.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/sdxl.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3446c871180f0cdac5fa4a18f67c92ec4de70d6e --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/sdxl.yaml @@ -0,0 +1,75 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + ckpt_loader: + class_type: CheckpointLoaderSimple + title: "Load Checkpoint" + +connections: + - from: "ckpt_loader:0" + to: "ksampler:model" + - from: "ckpt_loader:1" + to: "pos_prompt:clip" + - from: "ckpt_loader:1" + to: "neg_prompt:clip" + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + - from: "ckpt_loader:2" + to: "vae_decode:vae" + - from: "ckpt_loader:2" + to: "vae_encode:vae" + +dynamic_vae_chains: + vae_chain: + targets: + - "vae_decode:vae" + - "vae_encode:vae" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + start: "ckpt_loader" + output_map: + "0": "model" + "1": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["ksampler:model"] + "clip": ["pos_prompt:clip", "neg_prompt:clip"] + +dynamic_controlnet_chains: + controlnet_chain: + template: "ControlNetApplyAdvanced" + ksampler_node: "ksampler" + vae_source: "ckpt_loader:2" + +dynamic_ipadapter_chains: + ipadapter_chain: + end: "ksampler" + final_preset: "{{ ipadapter_final_preset }}" + final_weight: "{{ ipadapter_final_weight }}" + final_embeds_scaling: "{{ ipadapter_embeds_scaling }}" + final_loader_type: "{{ ipadapter_final_loader_type }}" + final_lora_strength: "{{ ipadapter_final_lora_strength }}" + +dynamic_conditioning_chains: + conditioning_chain: + ksampler_node: "ksampler" + clip_source: "ckpt_loader:1" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + model_name: "ckpt_loader:ckpt_name" diff --git a/core/pipelines/workflow_recipes/_partials/conditioning/z-image.yaml b/core/pipelines/workflow_recipes/_partials/conditioning/z-image.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7675d6f9e50b4cf20752a86cadfad3c15bcfc42d --- /dev/null +++ b/core/pipelines/workflow_recipes/_partials/conditioning/z-image.yaml @@ -0,0 +1,77 @@ +nodes: + pos_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Positive)" + neg_prompt: + class_type: CLIPTextEncode + title: "CLIP Text Encode (Negative)" + unet_loader: + class_type: UNETLoader + title: "Load Diffusion Model" + params: + weight_dtype: "default" + vae_loader: + class_type: VAELoader + title: "Load VAE" + clip_loader: + class_type: CLIPLoader + title: "Load CLIP" + params: + type: "lumina2" + device: "default" + model_sampler: + class_type: ModelSamplingAuraFlow + params: + shift: 3.0 + +connections: + - from: "unet_loader:0" + to: "model_sampler:model" + - from: "model_sampler:0" + to: "ksampler:model" + + - from: "clip_loader:0" + to: "pos_prompt:clip" + - from: "clip_loader:0" + to: "neg_prompt:clip" + + - from: "pos_prompt:0" + to: "ksampler:positive" + - from: "neg_prompt:0" + to: "ksampler:negative" + + - from: "vae_loader:0" + to: "vae_decode:vae" + - from: "vae_loader:0" + to: "vae_encode:vae" + +dynamic_lora_chains: + lora_chain: + template: "LoraLoader" + output_map: + "unet_loader:0": "model" + "clip_loader:0": "clip" + input_map: + "model": "model" + "clip": "clip" + end_input_map: + "model": ["model_sampler:model"] + "clip": ["pos_prompt:clip", "neg_prompt:clip"] + +dynamic_diffsynth_controlnet_chains: + diffsynth_controlnet_chain: + template: "QwenImageDiffsynthControlnet" + model_sampler_node: "model_sampler" + ksampler_node: "ksampler" + vae_source: "vae_loader:0" + +dynamic_pid_chains: + pid_chain: + ksampler_node: "ksampler" + +ui_map: + positive_prompt: "pos_prompt:text" + negative_prompt: "neg_prompt:text" + unet_name: "unet_loader:unet_name" + vae_name: "vae_loader:vae_name" + clip_name: "clip_loader:clip_name" diff --git a/core/pipelines/workflow_recipes/unified_recipe.yaml b/core/pipelines/workflow_recipes/unified_recipe.yaml new file mode 100644 index 0000000000000000000000000000000000000000..83a92f516f551bee1804d3a5875315b9f7b8acb5 --- /dev/null +++ b/core/pipelines/workflow_recipes/unified_recipe.yaml @@ -0,0 +1,8 @@ +imports: + - "_partials/_base_sampler.yaml" + - "_partials/input/{{ task_type }}.yaml" + - "_partials/conditioning/{{ model_type }}.yaml" + +connections: + - from: "latent_source:0" + to: "ksampler:latent_image" diff --git a/core/runtime_config.py b/core/runtime_config.py new file mode 100644 index 0000000000000000000000000000000000000000..647def27dabc794934ddfd559bed8c36e3c21632 --- /dev/null +++ b/core/runtime_config.py @@ -0,0 +1,110 @@ +"""Runtime configuration shared by the web UI, MCP API, and engine.""" + +from __future__ import annotations + +import os +from dataclasses import dataclass + + +def _env_bool(name: str, default: bool) -> bool: + raw = os.getenv(name) + if raw is None: + return default + return raw.strip().lower() in {"1", "true", "yes", "on"} + + +def _env_int(name: str, default: int, minimum: int, maximum: int) -> int: + raw = os.getenv(name) + if raw is None: + return default + try: + value = int(raw) + except (TypeError, ValueError): + return default + return max(minimum, min(maximum, value)) + + +def _env_float(name: str, default: float, minimum: float, maximum: float) -> float: + raw = os.getenv(name) + if raw is None: + return default + try: + value = float(raw) + except (TypeError, ValueError): + return default + return max(minimum, min(maximum, value)) + + +@dataclass(frozen=True) +class RuntimeConfig: + """Bounded settings with safe defaults for one shared GPU process.""" + + # ComfyUI nodes, caches, and model state are process-global. A single + # process is therefore always serialized; scale with separate replicas. + gpu_concurrency: int = _env_int("IMAGEGEN_GPU_CONCURRENCY", 1, 1, 1) + queue_max_size: int = _env_int("IMAGEGEN_QUEUE_MAX_SIZE", 24, 1, 256) + mcp_max_pending: int = _env_int("IMAGEGEN_MCP_MAX_PENDING", 16, 1, 256) + mcp_task_retention: int = _env_int("IMAGEGEN_MCP_TASK_RETENTION", 200, 20, 5000) + max_batch_size: int = _env_int("IMAGEGEN_MAX_BATCH_SIZE", 4, 1, 16) + # ZeroGPU is best used as one bounded job at a time. The environment + # overrides are intentionally available for dedicated hardware, while the + # defaults keep the public Space predictable and affordable. + max_pk_models: int = _env_int("IMAGEGEN_MAX_PK_MODELS", 2, 2, 4) + max_multi_images: int = _env_int("IMAGEGEN_MAX_MULTI_IMAGES", 4, 1, 10) + max_plan_jobs: int = _env_int("IMAGEGEN_MAX_PLAN_JOBS", 4, 2, 12) + max_plan_outputs: int = _env_int("IMAGEGEN_MAX_PLAN_OUTPUTS", 8, 2, 16) + output_retention: int = _env_int("IMAGEGEN_OUTPUT_RETENTION", 80, 10, 1000) + max_input_megapixels: float = _env_float( + "IMAGEGEN_MAX_INPUT_MEGAPIXELS", 4.2, 0.25, 64.0 + ) + max_reference_megapixels: float = _env_float( + "IMAGEGEN_MAX_REFERENCE_MEGAPIXELS", 12.0, 1.0, 64.0 + ) + max_reference_images: int = _env_int( + "IMAGEGEN_MAX_REFERENCE_IMAGES", 10, 1, 20 + ) + max_output_megapixels: float = _env_float( + "IMAGEGEN_MAX_OUTPUT_MEGAPIXELS", 16.0, 1.0, 128.0 + ) + min_free_disk_gb: float = _env_float( + "IMAGEGEN_MIN_FREE_DISK_GB", 3.0, 0.5, 50.0 + ) + enable_mcp: bool = _env_bool("IMAGEGEN_ENABLE_MCP", True) + enable_startup_gpu_probe: bool = _env_bool("IMAGEGEN_STARTUP_GPU_PROBE", False) + default_language: str = os.getenv("IMAGEGEN_DEFAULT_LANGUAGE", "zh-CN") + + +CONFIG = RuntimeConfig() + + +def estimate_gpu_duration(inputs: dict) -> int: + """Estimate a ZeroGPU reservation without asking ordinary users to guess. + + This is deliberately conservative. A caller can still pass 60/90/120 via + ``zero_gpu_duration``; 0 or an empty value means automatic mode. + """ + + explicit = inputs.get("zero_gpu_duration") + try: + explicit_value = int(explicit or 0) + except (TypeError, ValueError): + explicit_value = 0 + if explicit_value > 0: + return max(30, min(120, explicit_value)) + + model = str(inputs.get("model_display_name", "")).lower() + steps = max(1, int(inputs.get("num_inference_steps") or 20)) + batch = max(1, int(inputs.get("batch_size") or 1)) + width = max(256, int(inputs.get("width") or 1024)) + height = max(256, int(inputs.get("height") or 1024)) + megapixels = (width * height) / 1_000_000 + + fast_tokens = ("turbo", "lightning", "fast", "distilled", "schnell", "4b") + base = 35 if any(token in model for token in fast_tokens) else 60 + work = steps * batch * max(0.5, megapixels) + + if work >= 55 or batch >= 3 or megapixels >= 2.5: + return 120 + if work >= 28: + return 90 + return max(45, base) diff --git a/core/settings.py b/core/settings.py new file mode 100644 index 0000000000000000000000000000000000000000..f9a3ae3c888fe79f9a9da1a280059b4c3791fda7 --- /dev/null +++ b/core/settings.py @@ -0,0 +1,213 @@ +import yaml +import os +from collections import OrderedDict + +_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +def _project_path(*parts): + return os.path.join(_PROJECT_ROOT, *parts) + + +CHECKPOINT_DIR = _project_path("models", "checkpoints") +LORA_DIR = _project_path("models", "loras") +EMBEDDING_DIR = _project_path("models", "embeddings") +CONTROLNET_DIR = _project_path("models", "controlnet") +MODEL_PATCHES_DIR = _project_path("models", "model_patches") +DIFFUSION_MODELS_DIR = _project_path("models", "diffusion_models") +VAE_DIR = _project_path("models", "vae") +TEXT_ENCODERS_DIR = _project_path("models", "text_encoders") +STYLE_MODELS_DIR = _project_path("models", "style_models") +CLIP_VISION_DIR = _project_path("models", "clip_vision") +IPADAPTER_DIR = _project_path("models", "ipadapter") +IPADAPTER_FLUX_DIR = _project_path("models", "ipadapter-flux") +INPUT_DIR = _project_path("input") +OUTPUT_DIR = _project_path("output") + +CATEGORY_TO_DIR_MAP = { + "diffusion_models": DIFFUSION_MODELS_DIR, + "text_encoders": TEXT_ENCODERS_DIR, + "vae": VAE_DIR, + "checkpoints": CHECKPOINT_DIR, + "loras": LORA_DIR, + "controlnet": CONTROLNET_DIR, + "model_patches": MODEL_PATCHES_DIR, + "embeddings": EMBEDDING_DIR, + "style_models": STYLE_MODELS_DIR, + "clip_vision": CLIP_VISION_DIR, + "ipadapter": IPADAPTER_DIR, + "ipadapter-flux": IPADAPTER_FLUX_DIR +} + +_MODEL_LIST_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'model_list.yaml') +_FILE_LIST_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'file_list.yaml') +_IPADAPTER_LIST_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'ipadapter.yaml') +_CONSTANTS_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'constants.yaml') +_MODEL_ARCHITECTURES_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'model_architectures.yaml') +_IMAGE_GEN_FEATURES_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'image_gen_features.yaml') +_MODEL_DEFAULTS_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'model_defaults.yaml') + +def load_constants_from_yaml(filepath=_CONSTANTS_PATH): + if not os.path.exists(filepath): + print(f"Warning: Constants file not found at {filepath}. Using fallback values.") + return {} + with open(filepath, 'r', encoding='utf-8') as f: + return yaml.safe_load(f) + +def load_architectures_config(filepath=_MODEL_ARCHITECTURES_PATH): + if not os.path.exists(filepath): + print(f"Warning: Architectures file not found at {filepath}.") + return {} + with open(filepath, 'r', encoding='utf-8') as f: + return yaml.safe_load(f) + +def load_features_config(filepath=_IMAGE_GEN_FEATURES_PATH): + if not os.path.exists(filepath): + print(f"Warning: Features file not found at {filepath}.") + return {} + with open(filepath, 'r', encoding='utf-8') as f: + return yaml.safe_load(f) + +def load_model_defaults(filepath=_MODEL_DEFAULTS_PATH): + if not os.path.exists(filepath): + print(f"Warning: Model defaults file not found at {filepath}.") + return {} + with open(filepath, 'r', encoding='utf-8') as f: + return yaml.safe_load(f) + +def load_file_download_map(filepath=_FILE_LIST_PATH): + if not os.path.exists(filepath): + raise FileNotFoundError(f"The file list (for downloads) was not found at: {filepath}") + + with open(filepath, 'r', encoding='utf-8') as f: + file_list_data = yaml.safe_load(f) + + download_info_map = {} + for category, files in file_list_data.get('file', {}).items(): + if isinstance(files, list): + for file_info in files: + if 'filename' in file_info: + file_info['category'] = category + download_info_map[file_info['filename']] = file_info + return download_info_map + + +def load_models_from_yaml(model_list_filepath=_MODEL_LIST_PATH, download_map=None): + if not os.path.exists(model_list_filepath): + raise FileNotFoundError(f"The model list file was not found at: {model_list_filepath}") + if download_map is None: + raise ValueError("download_map must be provided to load_models_from_yaml") + + with open(model_list_filepath, 'r', encoding='utf-8') as f: + model_data = yaml.safe_load(f) + + model_maps = { + "MODEL_MAP_CHECKPOINT": OrderedDict(), + "ALL_MODEL_MAP": OrderedDict(), + } + category_map_names = { + "Checkpoint": "MODEL_MAP_CHECKPOINT", + "Checkpoints": "MODEL_MAP_CHECKPOINT" + } + + for category, architectures in model_data.items(): + if category in category_map_names: + map_name = category_map_names[category] + if not isinstance(architectures, dict): continue + + for arch, arch_data in architectures.items(): + if not isinstance(arch_data, dict): continue + + latent_type = arch_data.get('latent_type', 'latent') + models = arch_data.get('models', []) + if not isinstance(models, list): continue + + for model in models: + display_name = model['display_name'] + path_or_components = model.get('path') or model.get('components') + mod_category = model.get('category', None) + + repo_id = '' + if isinstance(path_or_components, str): + download_info = download_map.get(path_or_components, {}) + repo_id = download_info.get('repo_id', '') + + model_tuple = ( + repo_id, + path_or_components, + arch, + latent_type, + mod_category + ) + model_maps[map_name][display_name] = model_tuple + model_maps["ALL_MODEL_MAP"][display_name] = model_tuple + + return model_maps + +try: + ALL_FILE_DOWNLOAD_MAP = load_file_download_map() + loaded_maps = load_models_from_yaml(download_map=ALL_FILE_DOWNLOAD_MAP) + MODEL_MAP_CHECKPOINT = loaded_maps["MODEL_MAP_CHECKPOINT"] + ALL_MODEL_MAP = loaded_maps["ALL_MODEL_MAP"] + + category_to_model_type = { + "diffusion_models": "UNET", + "text_encoders": "TEXT_ENCODER", + "vae": "VAE", + "checkpoints": "SDXL", + "loras": "LORA", + "controlnet": "CONTROLNET", + "model_patches": "MODEL_PATCH", + "style_models": "STYLE", + "clip_vision": "CLIP_VISION", + "ipadapter": "IPADAPTER", + "ipadapter-flux": "IPADAPTER_FLUX" + } + for filename, file_info in ALL_FILE_DOWNLOAD_MAP.items(): + if filename not in ALL_MODEL_MAP: + category = file_info.get('category') + model_type = category_to_model_type.get(category, 'UNKNOWN') + repo_id = file_info.get('repo_id', '') + ALL_MODEL_MAP[filename] = (repo_id, filename, model_type, None, None) + + MODEL_TYPE_MAP = {k: v[2] for k, v in ALL_MODEL_MAP.items()} + + ARCH_CATEGORIES_MAP = {} + for display_name, info in MODEL_MAP_CHECKPOINT.items(): + arch = info[2] + cat = info[4] if len(info) > 4 else None + if arch not in ARCH_CATEGORIES_MAP: + ARCH_CATEGORIES_MAP[arch] = [] + if cat and cat not in ARCH_CATEGORIES_MAP[arch]: + ARCH_CATEGORIES_MAP[arch].append(cat) + +except Exception as e: + print(f"FATAL: Could not load model configuration from YAML. Error: {e}") + ALL_FILE_DOWNLOAD_MAP = {} + MODEL_MAP_CHECKPOINT, ALL_MODEL_MAP = {}, {} + MODEL_TYPE_MAP = {} + ARCH_CATEGORIES_MAP = {} + + +try: + _constants = load_constants_from_yaml() + MAX_LORAS = _constants.get('MAX_LORAS', 5) + MAX_EMBEDDINGS = _constants.get('MAX_EMBEDDINGS', 5) + MAX_CONDITIONINGS = _constants.get('MAX_CONDITIONINGS', 10) + MAX_CONTROLNETS = _constants.get('MAX_CONTROLNETS', 5) + MAX_IPADAPTERS = _constants.get('MAX_IPADAPTERS', 5) + LORA_SOURCE_CHOICES = _constants.get('LORA_SOURCE_CHOICES', ["Civitai", "File"]) + RESOLUTION_MAP = _constants.get('RESOLUTION_MAP', {}) + MULTIPLIERS_MAP = _constants.get('MULTIPLIERS_MAP', {}) + ARCHITECTURES_CONFIG = load_architectures_config() + FEATURES_CONFIG = load_features_config() + MODEL_DEFAULTS_CONFIG = load_model_defaults() +except Exception as e: + print(f"FATAL: Could not load constants from YAML. Error: {e}") + MAX_LORAS, MAX_EMBEDDINGS, MAX_CONDITIONINGS, MAX_CONTROLNETS, MAX_IPADAPTERS = 5, 5, 10, 5, 5 + LORA_SOURCE_CHOICES = ["Civitai", "File"] + RESOLUTION_MAP = {} + MULTIPLIERS_MAP = {} + ARCHITECTURES_CONFIG = {} + FEATURES_CONFIG = {} + MODEL_DEFAULTS_CONFIG = {} diff --git a/core/shared_state.py b/core/shared_state.py new file mode 100644 index 0000000000000000000000000000000000000000..8db5f14d4f4155429daa4853ce4eccbb2294ab33 --- /dev/null +++ b/core/shared_state.py @@ -0,0 +1 @@ +INVALID_MODEL_URLS = {} diff --git a/core/task_scheduler.py b/core/task_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..4bcd31146becb69bfe201ad736d2168194097619 --- /dev/null +++ b/core/task_scheduler.py @@ -0,0 +1,122 @@ +"""One bounded scheduler for UI, API, and MCP generation requests.""" + +from __future__ import annotations + +import threading +from concurrent.futures import Future, ThreadPoolExecutor +from contextlib import contextmanager +from functools import wraps +from typing import Callable, Iterator, TypeVar + +from .runtime_config import CONFIG + +T = TypeVar("T") + + +class QueueFullError(RuntimeError): + pass + + +class TaskCancelledError(RuntimeError): + pass + + +_pending_slots = threading.BoundedSemaphore(CONFIG.mcp_max_pending) +_executor = ThreadPoolExecutor( + max_workers=CONFIG.gpu_concurrency, + thread_name_prefix="imagegen-worker", +) + + +class _FairGenerationGate: + """FIFO gate for the single process-global ComfyUI runtime.""" + + def __init__(self) -> None: + self._condition = threading.Condition() + self._next_ticket = 0 + self._serving_ticket = 0 + self._active = False + self._cancelled_tickets: set[int] = set() + + def _skip_cancelled_locked(self) -> None: + while not self._active and self._serving_ticket in self._cancelled_tickets: + self._cancelled_tickets.remove(self._serving_ticket) + self._serving_ticket += 1 + + def acquire(self, cancel_event: threading.Event | None = None) -> None: + with self._condition: + ticket = self._next_ticket + self._next_ticket += 1 + while True: + if cancel_event is not None and cancel_event.is_set(): + self._cancelled_tickets.add(ticket) + self._skip_cancelled_locked() + self._condition.notify_all() + raise TaskCancelledError("任务已在等待 GPU 时取消。") + + self._skip_cancelled_locked() + if ticket == self._serving_ticket and not self._active: + self._active = True + return + + # A cancellation event does not notify the gate, so poll it at + # a low frequency. Jobs without cancellation remain fully + # condition-driven. + self._condition.wait(timeout=0.2 if cancel_event is not None else None) + + def release(self) -> None: + with self._condition: + self._active = False + self._serving_ticket += 1 + self._skip_cancelled_locked() + self._condition.notify_all() + + +_generation_gate = _FairGenerationGate() + + +@contextmanager +def generation_slot(cancel_event: threading.Event | None = None) -> Iterator[None]: + """Serialize access to the shared in-process ComfyUI runtime by default.""" + + _generation_gate.acquire(cancel_event) + try: + yield + finally: + _generation_gate.release() + + +def generation_guard(function: Callable[..., T]) -> Callable[..., T]: + @wraps(function) + def wrapped(*args, **kwargs): + ui_inputs = kwargs.get("ui_inputs") + if ui_inputs is None: + ui_inputs = next( + (value for value in args if isinstance(value, dict)), None + ) + cancel_event = ( + ui_inputs.get("_cancel_event") if isinstance(ui_inputs, dict) else None + ) + with generation_slot(cancel_event): + if cancel_event is not None and cancel_event.is_set(): + raise TaskCancelledError("任务已在进入 GPU 前取消。") + return function(*args, **kwargs) + + return wrapped + + +def submit_background(function: Callable[..., T], *args, **kwargs) -> Future[T]: + """Submit an MCP job without creating an unbounded daemon thread.""" + + if not _pending_slots.acquire(blocking=False): + raise QueueFullError( + f"任务队列已满(最多 {CONFIG.mcp_max_pending} 个待处理任务),请稍后再试。" + ) + + def run_and_release() -> T: + try: + return function(*args, **kwargs) + finally: + _pending_slots.release() + + return _executor.submit(run_and_release) diff --git a/core/workflow_assembler.py b/core/workflow_assembler.py new file mode 100644 index 0000000000000000000000000000000000000000..15438cf1471c5092c4190d57c95d4aa8b103d1c7 --- /dev/null +++ b/core/workflow_assembler.py @@ -0,0 +1,165 @@ +import yaml +import os +import importlib +from copy import deepcopy +from comfy_integration.nodes import NODE_CLASS_MAPPINGS +from chain_injectors import discover_injectors, get_registered_features +from core.settings import FEATURES_CONFIG + +class WorkflowAssembler: + def __init__(self, recipe_path, dynamic_values=None): + self.base_path = os.path.dirname(recipe_path) + self.dynamic_values = dynamic_values or {} + self.node_counter = 0 + self.workflow = {} + self.node_map = {} + + model_type = self.dynamic_values.get('model_type') + self._load_injector_config(model_type=model_type) + + self.recipe = self._load_and_merge_recipe(os.path.basename(recipe_path), self.dynamic_values) + + def _load_injector_config(self, model_type=None): + self.global_injectors = discover_injectors() + registered_features = get_registered_features() + + order = [] + if model_type and model_type in FEATURES_CONFIG: + enabled_features = FEATURES_CONFIG[model_type].get('enabled_chains', []) + for feat in enabled_features: + if feat in registered_features: + chain_key = registered_features[feat]['chain_type'] + else: + chain_key = f"dynamic_{feat}_chains" + if chain_key in self.global_injectors and chain_key not in order: + order.append(chain_key) + + for chain_key in self.global_injectors.keys(): + if chain_key not in order: + order.append(chain_key) + + self.injector_order = order + + def _get_unique_id(self): + self.node_counter += 1 + return str(self.node_counter) + + def _get_node_template(self, class_type): + if class_type not in NODE_CLASS_MAPPINGS: + raise ValueError(f"Node class '{class_type}' not found. Ensure it's correctly imported in comfy_integration/nodes.py.") + + node_class = NODE_CLASS_MAPPINGS[class_type] + input_types = node_class.INPUT_TYPES() + + template = { + "inputs": {}, + "class_type": class_type, + "_meta": {"title": node_class.NODE_NAME if hasattr(node_class, 'NODE_NAME') else class_type} + } + + all_inputs = {**input_types.get('required', {}), **input_types.get('optional', {})} + for name, details in all_inputs.items(): + config = details[1] if len(details) > 1 and isinstance(details[1], dict) else {} + template["inputs"][name] = config.get("default") + + return template + + def _load_and_merge_recipe(self, recipe_filename, dynamic_values, search_context_dir=None): + search_path = search_context_dir or self.base_path + recipe_path_to_use = os.path.join(search_path, recipe_filename) + + if not os.path.exists(recipe_path_to_use): + raise FileNotFoundError(f"Recipe file not found: {recipe_path_to_use}") + + with open(recipe_path_to_use, 'r', encoding='utf-8') as f: + content = f.read() + + for key, value in dynamic_values.items(): + if value is not None: + content = content.replace(f"{{{{ {key} }}}}", str(value)) + + main_recipe = yaml.safe_load(content) + + merged_recipe = {'nodes': {}, 'connections': [], 'ui_map': {}} + for key in self.injector_order: + if key.startswith('dynamic_'): + merged_recipe[key] = {} + + parent_recipe_dir = os.path.dirname(recipe_path_to_use) + for import_path_template in main_recipe.get('imports', []): + import_path = import_path_template + for key, value in dynamic_values.items(): + if value is not None: + import_path = import_path.replace(f"{{{{ {key} }}}}", str(value)) + + try: + imported_recipe = self._load_and_merge_recipe(import_path, dynamic_values, search_context_dir=parent_recipe_dir) + merged_recipe['nodes'].update(imported_recipe.get('nodes', {})) + merged_recipe['connections'].extend(imported_recipe.get('connections', [])) + merged_recipe['ui_map'].update(imported_recipe.get('ui_map', {})) + for key in self.injector_order: + if key in imported_recipe and key.startswith('dynamic_'): + merged_recipe[key].update(imported_recipe.get(key, {})) + except FileNotFoundError: + print(f"Warning: Optional recipe partial '{import_path}' not found. Skipping.") + + merged_recipe['nodes'].update(main_recipe.get('nodes', {})) + merged_recipe['connections'].extend(main_recipe.get('connections', [])) + merged_recipe['ui_map'].update(main_recipe.get('ui_map', {})) + for key in self.injector_order: + if key in main_recipe and key.startswith('dynamic_'): + merged_recipe[key].update(main_recipe.get(key, {})) + + return merged_recipe + + def assemble(self, ui_values): + self.ui_values = ui_values + for name, details in self.recipe['nodes'].items(): + class_type = details['class_type'] + template = self._get_node_template(class_type) + node_data = deepcopy(template) + + unique_id = self._get_unique_id() + self.node_map[name] = unique_id + + if 'params' in details: + for param, value in details['params'].items(): + if param in node_data['inputs']: + node_data['inputs'][param] = value + + self.workflow[unique_id] = node_data + + for ui_key, target in self.recipe.get('ui_map', {}).items(): + if ui_key in ui_values and ui_values[ui_key] is not None: + target_list = target if isinstance(target, list) else [target] + for t in target_list: + target_name, target_param = t.split(':') + if target_name in self.node_map: + self.workflow[self.node_map[target_name]]['inputs'][target_param] = ui_values[ui_key] + + for conn in self.recipe.get('connections', []): + from_name, from_output_idx = conn['from'].split(':') + to_name, to_input_name = conn['to'].split(':') + + from_id = self.node_map.get(from_name) + to_id = self.node_map.get(to_name) + + if from_id and to_id: + self.workflow[to_id]['inputs'][to_input_name] = [from_id, int(from_output_idx)] + + print("--- [Assembler] Applying dynamic injectors ---") + recipe_chain_types = {key for key in self.recipe if key.startswith('dynamic_')} + processing_order = [key for key in self.injector_order if key in recipe_chain_types] + + for chain_type in processing_order: + injector_func = self.global_injectors.get(chain_type) + if injector_func: + for chain_key, chain_def in self.recipe.get(chain_type, {}).items(): + if chain_key in ui_values and ui_values[chain_key]: + print(f" -> Injecting '{chain_type}' for '{chain_key}'...") + chain_items = ui_values[chain_key] + injector_func(self, chain_def, chain_items) + + print("--- [Assembler] Finished applying injectors ---") + + return self.workflow diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000000000000000000000000000000000000..7515492ea13e197f4115b2ebd09f568fc7ce5e85 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,62 @@ +# 架构说明 + +## 为什么只有一个引擎 + +Fluxus 是 ImageGen 的直接 fork,并共享模型注册表、ComfyUI 执行器、YAML 工作流与 UI。因此“双后端切换”只会复制状态、模型下载和显存占用,不能增加能力。本项目把两者统一为一个本地 ImageGen 引擎,用配置开关和 API alias 处理部署差异。 + +## 请求路径 + +```text +统一 Gradio 工作台 / MCP 高层接口 + ↓ + 规范化输入字典 + ↓ + 模型能力过滤 + 参数校验 + ↓ + 有界队列 + GPU 信号量 + ↓ + YAML recipe + chain injector + ↓ + 进程内 ComfyUI 节点执行 + ↓ + PNG 参数 + workflow 元数据输出 +``` + +## 切换语义 + +- 任务切换只控制可见区域;共用模型、Prompt、种子和采样参数。 +- 源图片、重绘蒙版和各任务参数保留在各自组件中,切回时仍可继续。 +- 架构/分类筛选时,当前模型若仍有效则保持不变。 +- 切模型会更新推荐步数、CFG、Sampler、Scheduler 和兼容扩展,但不会改写正面或负面 Prompt。 +- Pipeline 在提交前再次过滤不兼容扩展,避免隐藏旧状态进入工作流。 + +## 并发边界 + +- Gradio 生成事件使用共同的 `concurrency_id="gpu_generation"`。 +- Pipeline 入口使用 FIFO ticket gate,覆盖 UI、同步 API 和异步 MCP 三条路径。 +- MCP 异步任务使用固定大小线程池和待处理信号量,不再创建无限线程。 +- 模型/LoRA/ControlNet/IP-Adapter 下载与链接由进程级可重入锁保护。 +- 临时文件使用 UUID;任务表读写使用锁,并只保留有限条记录。 +- “取消排队”会取消 Gradio 等待任务;内部 GPU 闸门会轮询取消标记并跳过对应票据;模型准备完成后和进入 GPU 前还会再次检查。已开始采样的任务目前不能强制中断。 + +Gradio 与 MCP 各自保留有界入口,最后在 Pipeline 的公平 GPU 闸门汇合。它们不是同一个可观测队列,因此网页排队位置只表示 Gradio 侧等待情况;FIFO 闸门负责避免已经到达 Pipeline 的任一来源长期饥饿,并保证共享 ComfyUI 运行时一次只执行一个任务。 + +## 批量与 PK 编排 + +- `core/execution_plan.py` 只把一次提交展开成若干现有 Pipeline 输入,不复制工作流执行器。 +- 独立多图按同模型分组,减少 checkpoint 切换;图片×模型总任务受硬上限约束。 +- 模型 PK 共享 Prompt、源图、尺寸和一次解析出的 Seed;默认采用各模型推荐采样参数。 +- PK V1 清空高级 injector,仅比较基础 checkpoint 的共同输入能力。 +- 多图融合固定为 `txt2img + 模型专属 reference chain`;它与普通 img2img 的 source latent 是两种不同语义。 +- 模型边界在 GPU 租约内调用 ComfyUI 的 unload/cleanup;普通同模型连续生成保留热缓存。 + +## 可复现依赖 + +`vendor.lock.yaml` 固定 ComfyUI 和 custom nodes 的完整 commit。默认克隆到 `_vendor/ComfyUI` 与 `custom_nodes/`,不再把 ComfyUI 内容覆盖到项目根。设置 `COMFYUI_PATH` 可使用已有 checkout。 + +升级依赖时应: + +1. 在独立分支更新一个 revision; +2. 运行全部测试和至少一个低分辨率 GPU 冒烟任务; +3. 检查节点类名、输入 schema 和 PNG metadata; +4. 再更新 `vendor.lock.yaml` 与 `NOTICE.md`。 diff --git a/docs/HF_SPACE_DEPLOYMENT.md b/docs/HF_SPACE_DEPLOYMENT.md new file mode 100644 index 0000000000000000000000000000000000000000..db4db406bbe5eb46726673cdca328be1d09fb983 --- /dev/null +++ b/docs/HF_SPACE_DEPLOYMENT.md @@ -0,0 +1,59 @@ +# Hugging Face Space 部署审查 + +审查日期:2026-08-08 + +## 结论 + +当前仓库达到“可构建、可启动、适合小范围 ZeroGPU 验证”的状态;尚不能承诺 92 个模型都能在默认公共 Space 的磁盘、配额与 120 秒 GPU 时间内稳定运行。92 是可选模型目录,不是显存常驻数量。 + +| 项目 | 状态 | 处理 | +|---|---|---| +| Gradio / MCP | 通过本地隔离环境烟测 | `gradio[mcp]==5.50.0`,仅 9 个高层公共端点 | +| Python | 已适配 | metadata 固定官方 ZeroGPU 支持的 `3.12.12` | +| ZeroGPU 串行 | 已适配 | 所有入口最终进入单 GPU FIFO 闸门;PK 每模型分别申请 GPU | +| 多模型显存 | 不支持,且不计划支持 | 磁盘按需缓存;GPU 一次只执行一个模型;模型边界释放 Comfy 状态 | +| 磁盘 | 有保护,仍需规划 | 下载前检查远端文件大小并预留 3 GB;不自动误删 Hub cache | +| 冷启动 | 有缓解 | ComfyUI/custom nodes 固定 commit;metadata 启动上限为 1 小时 | +| 持久缓存 | 可配置 | Storage Bucket 挂载到 `/home/user/app/models`,同时设置 `HF_HOME` | +| gated 模型 | 需部署者操作 | 设置 `HF_TOKEN`,且账号须先在各模型页接受条款 | +| PyTorch ABI | 待真实 Space 固化 | ZeroGPU 支持当前范围,但三件套暂沿用上游非固定版本 | +| 真实 GPU 全矩阵 | 未完成 | 需在目标 Space 对精选模型逐个做低分辨率冷/热启动测试 | + +## 推荐的公共 ZeroGPU 配置 + +```text +IMAGEGEN_MAX_BATCH_SIZE=2 +IMAGEGEN_MAX_PK_MODELS=2 +IMAGEGEN_MAX_MULTI_IMAGES=4 +IMAGEGEN_MAX_PLAN_JOBS=4 +IMAGEGEN_MAX_PLAN_OUTPUTS=8 +IMAGEGEN_MIN_FREE_DISK_GB=3 +``` + +默认不要做模型常驻池,也不要把四个大模型装进一次 GPU 租约。PK 会解析一次随机 Seed,按模型顺序运行;模型切换前释放上一模型,最后一个模型保留为热状态。 + +## 持久模型缓存 + +1. 创建 Hugging Face Storage Bucket。 +2. 挂载到 `/home/user/app/models`。 +3. 设置变量 `HF_HOME=/home/user/app/models/.hf-cache`。 +4. 重启 Space,并先用一个小模型做冷启动测试。 + +代码中的 `models/` 文件大多是指向 Hub cache 的符号链接,因此两者应放在同一持久卷。自动 LRU 暂不启用:删除 Hub revision 可能使仍在使用的符号链接失效,公共部署应先精选模型或人工清理。 + +## 上线前必须实测 + +- 默认模型:首次下载、首次 GPU 装载、第二次热运行。 +- 两模型 PK:相同 Prompt / Seed,确认模型边界后显存释放。 +- 两张独立图片 × 两模型:4 个顺序任务,确认取消能保留已完成结果。 +- 编辑模型:1 张参考图→1 张图、3 张参考图→1 张图、参考组→多张变体。 +- 磁盘余量不足:确认下载前给出中文错误且不留下破损链接。 +- gated 模型:无 Token、未接受条款、已授权三种状态。 +- Space 重建:确认持久卷挂载和 `HF_HOME` 生效。 + +## 官方依据 + +- [ZeroGPU 规格、Python/PyTorch 版本、配额和模型装载建议](https://huggingface.co/docs/hub/spaces-zerogpu) +- [Space 默认资源与临时磁盘](https://huggingface.co/docs/hub/spaces-overview) +- [README metadata、启动超时与预加载字段](https://huggingface.co/docs/hub/spaces-config-reference) +- [Space 存储与 Storage Buckets](https://huggingface.co/docs/hub/spaces-storage) diff --git a/imagegen_utils/__init__.py b/imagegen_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/imagegen_utils/app_utils.py b/imagegen_utils/app_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1a4cae89574bcb76d95a6185fdec0199ce255bb5 --- /dev/null +++ b/imagegen_utils/app_utils.py @@ -0,0 +1,755 @@ +import os +import requests +import hashlib +import re +import threading +from functools import wraps +from typing import Sequence, Mapping, Any, Union, Set +from pathlib import Path +import shutil + +import gradio as gr +from huggingface_hub import hf_hub_download, constants as hf_constants +import torch +import numpy as np +from PIL import Image, ImageChops +import yaml + +from core.settings import * +from core.runtime_config import CONFIG + +IPADAPTER_PRESETS = None +_DOWNLOAD_LOCK = threading.RLock() + + +def _download_serialized(function): + """Protect shared model directories and symlink creation in one process.""" + + @wraps(function) + def wrapped(*args, **kwargs): + with _DOWNLOAD_LOCK: + return function(*args, **kwargs) + + return wrapped + +class UniqueKeyLoader(yaml.SafeLoader): + """ + A custom YAML loader that handles duplicate keys by grouping their values into a list. + """ + def construct_mapping(self, node, deep=False): + mapping = [] + for key_node, value_node in node.value: + key = self.construct_object(key_node, deep=deep) + value = self.construct_object(value_node, deep=deep) + mapping.append((key, value)) + + result = {} + for k, v in mapping: + if k in result: + if isinstance(result[k], list): + result[k].append(v) + else: + result[k] = [result[k], v] + else: + result[k] = v + return result + +UniqueKeyLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, UniqueKeyLoader.construct_mapping) + +@_download_serialized +def save_uploaded_file_with_hash(file_obj: gr.File, target_dir: str) -> str: + if not file_obj: + return "" + + temp_path = file_obj.name + + sha256 = hashlib.sha256() + with open(temp_path, 'rb') as f: + for block in iter(lambda: f.read(65536), b''): + sha256.update(block) + + file_hash = sha256.hexdigest() + _, extension = os.path.splitext(temp_path) + hashed_filename = f"{file_hash}{extension.lower()}" + + dest_path = os.path.join(target_dir, hashed_filename) + + os.makedirs(target_dir, exist_ok=True) + if not os.path.exists(dest_path): + shutil.copy(temp_path, dest_path) + print(f"✅ Saved uploaded file as: {dest_path}") + else: + print(f"ℹ️ File already exists (deduplicated): {dest_path}") + + return hashed_filename + +def bytes_to_gb(byte_size: int) -> float: + if byte_size is None or byte_size == 0: + return 0.0 + return round(byte_size / (1024 ** 3), 2) + +def get_directory_size(path: str) -> int: + total_size = 0 + if not os.path.exists(path): + return 0 + try: + for dirpath, _, filenames in os.walk(path): + for f in filenames: + fp = os.path.join(dirpath, f) + if os.path.isfile(fp) and not os.path.islink(fp): + total_size += os.path.getsize(fp) + except OSError as e: + print(f"Warning: Could not access {path} to calculate size: {e}") + return total_size + + +def _existing_disk_path(path: str) -> str: + """Find an existing ancestor suitable for ``shutil.disk_usage``.""" + + candidate = os.path.abspath(os.path.expanduser(path)) + while not os.path.exists(candidate): + parent = os.path.dirname(candidate) + if parent == candidate: + return os.getcwd() + candidate = parent + return candidate + + +def _assert_download_space( + expected_bytes: int | None, filename: str, target_path: str +) -> None: + """Reject a download before HF Space exhausts its ephemeral filesystem.""" + + free_bytes = shutil.disk_usage(_existing_disk_path(target_path)).free + reserve_bytes = int(CONFIG.min_free_disk_gb * 1024**3) + needed_bytes = max(0, int(expected_bytes or 0)) + reserve_bytes + if free_bytes < needed_bytes: + expected_text = ( + f",该文件约 {bytes_to_gb(expected_bytes):g} GB" + if expected_bytes + else "" + ) + raise gr.Error( + f"磁盘空间不足,无法下载“{filename}”{expected_text}。" + f"当前剩余 {bytes_to_gb(free_bytes):g} GB,系统需保留 " + f"{CONFIG.min_free_disk_gb:g} GB。请删除缓存、挂载持久存储或换用较小模型。" + ) + + +def _hf_remote_file_size(repo_id: str, filename: str) -> int | None: + """Read the Hub file size without downloading its body.""" + + try: + from huggingface_hub import get_hf_file_metadata, hf_hub_url + + metadata = get_hf_file_metadata( + hf_hub_url(repo_id=repo_id, filename=filename), + token=os.environ.get("HF_TOKEN"), + ) + return int(metadata.size) if metadata.size is not None else None + except Exception as exc: + # The actual download will surface access/network errors with context. + print(f"Warning: Could not preflight Hub file size for {repo_id}/{filename}: {exc}") + return None + +def get_value_at_index(obj: Union[Sequence, Mapping], index: int) -> Any: + try: + return obj[index] + except (KeyError, IndexError): + try: + return obj["result"][index] + except (KeyError, IndexError): + return None + +def sanitize_prompt(prompt: str) -> str: + if not isinstance(prompt, str): + return "" + return "".join(char for char in prompt if char.isprintable() or char in ('\n', '\t')) + +def sanitize_id(input_id: str) -> str: + if not isinstance(input_id, str): + return "" + input_id = input_id.strip() + if "civitai" in input_id.lower(): + version_match = re.search(r'modelVersionId=(\d+)', input_id) + if version_match: + return version_match.group(1) + model_match = re.search(r'/models/(\d+)', input_id) + if model_match: + return model_match.group(1) + return re.sub(r'[^0-9]', '', input_id) + +def sanitize_url(url: str) -> str: + if not isinstance(url, str): + raise ValueError("URL must be a string.") + url = url.strip() + if not re.match(r'^https?://[^\s/$.?#].[^\s]*$', url): + raise ValueError("Invalid URL format or scheme. Only HTTP and HTTPS are allowed.") + return url + +def sanitize_filename(filename: str) -> str: + if not isinstance(filename, str): + return "" + sanitized = filename.replace('..', '') + sanitized = re.sub(r'[^\w\.\-]', '_', sanitized) + return sanitized.lstrip('/\\') + +def get_civitai_file_info(version_id: str) -> dict | None: + api_url = f"https://civitai.com/api/v1/model-versions/{version_id}" + try: + response = requests.get(api_url, timeout=10) + response.raise_for_status() + data = response.json() + + model_type = data.get('model', {}).get('type') + + result_file = None + for file_data in data.get('files', []): + if file_data.get('type') == 'Model' and file_data['name'].endswith(('.safetensors', '.pt', '.bin')): + result_file = file_data.copy() + break + + if not result_file and data.get('files'): + result_file = data['files'][0].copy() + + if result_file: + result_file['model_type'] = model_type + return result_file + except Exception: + return None + +def download_file(url: str, save_path: str, api_key: str = None, progress=None, desc: str = "") -> str: + if os.path.exists(save_path): + return f"File already exists: {os.path.basename(save_path)}" + + headers = {'Authorization': f'Bearer {api_key}'} if api_key and api_key.strip() else {} + try: + if progress: + progress(0, desc=desc) + + response = requests.get(url, stream=True, headers=headers, timeout=15) + response.raise_for_status() + total_size = int(response.headers.get('content-length', 0)) + + with open(save_path, "wb") as f: + downloaded = 0 + for chunk in response.iter_content(chunk_size=8192): + f.write(chunk) + if progress and total_size > 0: + downloaded += len(chunk) + progress(downloaded / total_size, desc=desc) + return f"Successfully downloaded: {os.path.basename(save_path)}" + except Exception as e: + if os.path.exists(save_path): + os.remove(save_path) + return f"Download failed for {os.path.basename(save_path)}: {e}" + +@_download_serialized +def get_lora_path(source: str, id_or_url: str, civitai_key: str, progress) -> tuple[str | None, str]: + if not id_or_url or not id_or_url.strip(): + return None, "No ID/URL provided." + + try: + if source == "Civitai": + version_id = sanitize_id(id_or_url) + if not version_id: + return None, "Invalid Civitai ID provided. Must be numeric." + + file_info = get_civitai_file_info(version_id) + if file_info: + model_type = file_info.get('model_type') + if model_type and model_type.lower() == 'checkpoint': + return None, f"Invalid Civitai model type '{model_type}' for LoRA. Checkpoint models are not allowed." + + filename = sanitize_filename(f"civitai_{version_id}.safetensors") + local_path = os.path.join(LORA_DIR, filename) + api_key_to_use = civitai_key + source_name = f"Civitai ID {version_id}" + elif source == "Hugging Face": + parts = id_or_url.strip().split('/') + if len(parts) < 3: + return None, "Invalid Hugging Face path. Format: repo_owner/repo_name/filename" + repo_id = f"{parts[0]}/{parts[1]}" + repo_file_path = "/".join(parts[2:]) + unique_name = id_or_url.strip().replace('/', '_') + filename = sanitize_filename(unique_name) + local_path = os.path.join(LORA_DIR, filename) + source_name = f"HF {repo_file_path}" + else: + return None, "Invalid source." + + except ValueError as e: + return None, f"Input validation failed: {e}" + + if os.path.lexists(local_path): + if not os.path.exists(local_path): + os.remove(local_path) + else: + return local_path, "File already exists." + + if source == "Civitai": + if not file_info or not file_info.get('downloadUrl'): + return None, f"Could not get download link for {source_name}." + + status = download_file(file_info['downloadUrl'], local_path, api_key_to_use, progress=progress, desc=f"Downloading {source_name}") + return (local_path, status) if "Successfully" in status else (None, status) + elif source == "Hugging Face": + try: + if progress: progress(0, desc=f"Downloading {source_name}") + cached_path = hf_hub_download(repo_id=repo_id, filename=repo_file_path, token=os.environ.get("HF_TOKEN")) + os.makedirs(LORA_DIR, exist_ok=True) + os.symlink(cached_path, local_path) + if progress: progress(1.0, desc=f"Downloaded {source_name}") + return local_path, f"Successfully downloaded: {filename}" + except Exception as e: + return None, f"Hugging Face download failed: {e}" + +@_download_serialized +def get_embedding_path(source: str, id_or_url: str, civitai_key: str, progress) -> tuple[str | None, str]: + if not id_or_url or not id_or_url.strip(): + return None, "No ID/URL provided." + + try: + if source == "Civitai": + version_id = sanitize_id(id_or_url) + if not version_id: + return None, "Invalid Civitai ID. Must be numeric." + + file_info = get_civitai_file_info(version_id) + if file_info: + model_type = file_info.get('model_type') + if model_type and model_type.lower() == 'checkpoint': + return None, f"Invalid Civitai model type '{model_type}' for Embedding. Checkpoint models are not allowed." + + file_ext = ".safetensors" + if file_info and file_info.get('name') and file_info['name'].lower().endswith(('.pt', '.bin')): + file_ext = os.path.splitext(file_info['name'])[1] + + filename = sanitize_filename(f"civitai_{version_id}{file_ext}") + local_path = os.path.join(EMBEDDING_DIR, filename) + api_key_to_use = civitai_key + source_name = f"Embedding Civitai ID {version_id}" + elif source == "Hugging Face": + parts = id_or_url.strip().split('/') + if len(parts) < 3: + return None, "Invalid Hugging Face path. Format: repo_owner/repo_name/filename" + repo_id = f"{parts[0]}/{parts[1]}" + repo_file_path = "/".join(parts[2:]) + filename = sanitize_filename(parts[-1]) + local_path = os.path.join(EMBEDDING_DIR, filename) + source_name = f"Embedding HF {repo_file_path}" + else: + return None, "Invalid source." + + except ValueError as e: + return None, f"Input validation failed: {e}" + + if os.path.lexists(local_path): + if not os.path.exists(local_path): + os.remove(local_path) + else: + return local_path, "File already exists." + + if source == "Civitai": + if not file_info or not file_info.get('downloadUrl'): + return None, f"Could not get download link for {source_name}." + + status = download_file(file_info['downloadUrl'], local_path, api_key_to_use, progress=progress, desc=f"Downloading {source_name}") + return (local_path, status) if "Successfully" in status else (None, status) + elif source == "Hugging Face": + try: + if progress: progress(0, desc=f"Downloading {source_name}") + cached_path = hf_hub_download(repo_id=repo_id, filename=repo_file_path, token=os.environ.get("HF_TOKEN")) + os.makedirs(EMBEDDING_DIR, exist_ok=True) + os.symlink(cached_path, local_path) + if progress: progress(1.0, desc=f"Downloaded {source_name}") + return local_path, f"Successfully downloaded: {filename}" + except Exception as e: + return None, f"Hugging Face download failed: {e}" + +@_download_serialized +def get_vae_path(source: str, id_or_url: str, civitai_key: str, progress) -> tuple[str | None, str]: + if not id_or_url or not id_or_url.strip(): + return None, "No ID/URL provided." + + try: + if source == "Civitai": + version_id = sanitize_id(id_or_url) + if not version_id: + return None, "Invalid Civitai ID. Must be numeric." + + file_info = get_civitai_file_info(version_id) + if file_info: + model_type = file_info.get('model_type') + if model_type and model_type.lower() == 'checkpoint': + return None, f"Invalid Civitai model type '{model_type}' for VAE. Checkpoint models are not allowed." + + file_ext = ".safetensors" + if file_info and file_info.get('name') and file_info['name'].lower().endswith(('.pt', '.bin')): + file_ext = os.path.splitext(file_info['name'])[1] + + filename = sanitize_filename(f"civitai_{version_id}{file_ext}") + local_path = os.path.join(VAE_DIR, filename) + api_key_to_use = civitai_key + source_name = f"VAE Civitai ID {version_id}" + elif source == "Hugging Face": + parts = id_or_url.strip().split('/') + if len(parts) < 3: + return None, "Invalid Hugging Face path. Format: repo_owner/repo_name/filename" + repo_id = f"{parts[0]}/{parts[1]}" + repo_file_path = "/".join(parts[2:]) + unique_name = id_or_url.strip().replace('/', '_') + filename = sanitize_filename(unique_name) + local_path = os.path.join(VAE_DIR, filename) + source_name = f"VAE HF {repo_file_path}" + else: + return None, "Invalid source." + + except ValueError as e: + return None, f"Input validation failed: {e}" + + if os.path.lexists(local_path): + if not os.path.exists(local_path): + os.remove(local_path) + else: + return local_path, "File already exists." + + if source == "Civitai": + if not file_info or not file_info.get('downloadUrl'): + return None, f"Could not get download link for {source_name}." + + status = download_file(file_info['downloadUrl'], local_path, api_key_to_use, progress=progress, desc=f"Downloading {source_name}") + return (local_path, status) if "Successfully" in status else (None, status) + elif source == "Hugging Face": + try: + if progress: progress(0, desc=f"Downloading {source_name}") + cached_path = hf_hub_download(repo_id=repo_id, filename=repo_file_path, token=os.environ.get("HF_TOKEN")) + os.makedirs(VAE_DIR, exist_ok=True) + os.symlink(cached_path, local_path) + if progress: progress(1.0, desc=f"Downloaded {source_name}") + return local_path, f"Successfully downloaded: {filename}" + except Exception as e: + return None, f"Hugging Face download failed: {e}" + +@_download_serialized +def _ensure_model_downloaded(display_name: str, progress=gr.Progress()): + if display_name not in ALL_MODEL_MAP: + raise ValueError(f"Model '{display_name}' not found in configuration.") + + model_info = ALL_MODEL_MAP[display_name] + repo_filename = model_info[1] + base_filename = os.path.basename(repo_filename) + + download_info = ALL_FILE_DOWNLOAD_MAP.get(base_filename) + if not download_info: + raise gr.Error(f"配置中找不到模型文件“{base_filename}”,无法下载。") + + category = download_info.get("category") + dest_dir = CATEGORY_TO_DIR_MAP.get(category) + + if not dest_dir: + raise ValueError(f"Unknown YAML category '{category}' for '{base_filename}'.") + + dest_path = os.path.join(dest_dir, base_filename) + + if os.path.lexists(dest_path): + if not os.path.exists(dest_path): + print(f"⚠️ Found and removed broken symlink: {dest_path}") + os.remove(dest_path) + else: + return base_filename + + source = download_info.get("source") + try: + progress(0, desc=f"Downloading: {base_filename}") + + if source == "hf": + repo_id = download_info.get("repo_id") + hf_filename = download_info.get("repository_file_path", base_filename) + if not repo_id: + raise ValueError(f"repo_id is missing for HF model '{base_filename}'") + + # Re-link an existing Hub cache entry without requiring extra free + # space. Only preflight when bytes really need to be downloaded. + try: + cached_path = hf_hub_download( + repo_id=repo_id, + filename=hf_filename, + token=os.environ.get("HF_TOKEN"), + local_files_only=True, + ) + except Exception: + cached_path = None + if cached_path is None: + expected_bytes = _hf_remote_file_size(repo_id, hf_filename) + _assert_download_space( + expected_bytes, + base_filename, + hf_constants.HF_HUB_CACHE, + ) + cached_path = hf_hub_download( + repo_id=repo_id, + filename=hf_filename, + token=os.environ.get("HF_TOKEN"), + ) + os.makedirs(dest_dir, exist_ok=True) + os.symlink(cached_path, dest_path) + print(f"✅ Symlinked '{cached_path}' to '{dest_path}'") + + elif source == "civitai": + model_version_id = download_info.get("model_version_id") + if not model_version_id: + raise ValueError(f"model_version_id is missing for Civitai model '{base_filename}'") + + file_info = get_civitai_file_info(model_version_id) + if not file_info or not file_info.get('downloadUrl'): + raise ConnectionError(f"Could not get download URL for Civitai model version ID {model_version_id}") + + expected_bytes = None + if file_info.get("sizeKB") is not None: + expected_bytes = int(float(file_info["sizeKB"]) * 1024) + _assert_download_space(expected_bytes, base_filename, dest_dir) + status = download_file( + file_info['downloadUrl'], dest_path, api_key=os.environ.get("CIVITAI_API_KEY", ""), progress=progress, desc=f"Downloading: {base_filename}" + ) + if "Failed" in status: + raise ConnectionError(status) + else: + raise NotImplementedError(f"Download source '{source}' is not implemented for '{base_filename}'") + + progress(1.0, desc=f"Downloaded: {base_filename}") + + except Exception as e: + if os.path.lexists(dest_path): + try: + os.remove(dest_path) + except OSError: pass + raise gr.Error(f"模型“{display_name}”下载或链接失败:{e}") + + return base_filename + +@_download_serialized +def ensure_controlnet_model_downloaded(filename: str, progress): + if not filename or filename == "None": + return + + download_info = ALL_FILE_DOWNLOAD_MAP.get(filename) + if not download_info: + raise gr.Error(f"配置中找不到 ControlNet 模型“{filename}”,无法下载。") + + category = download_info.get("category", "controlnet") + dest_dir = CATEGORY_TO_DIR_MAP.get(category, CONTROLNET_DIR) + dest_path = os.path.join(dest_dir, filename) + + if os.path.lexists(dest_path): + if not os.path.exists(dest_path): + print(f"⚠️ Found and removed broken symlink: {dest_path}") + os.remove(dest_path) + else: + return + + source = download_info.get("source") + + try: + if source == "hf": + repo_id = download_info.get("repo_id") + repo_filename = download_info.get("repository_file_path", filename) + if not repo_id: + raise ValueError("repo_id is missing for Hugging Face download.") + + progress(0, desc=f"Downloading CN: {filename}") + cached_path = hf_hub_download(repo_id=repo_id, filename=repo_filename, token=os.environ.get("HF_TOKEN")) + os.makedirs(dest_dir, exist_ok=True) + os.symlink(cached_path, dest_path) + print(f"✅ Symlinked ControlNet '{cached_path}' to '{dest_path}'") + progress(1.0, desc=f"Downloaded CN: {filename}") + + elif source == "civitai": + model_version_id = download_info.get("model_version_id") + if not model_version_id: + raise ValueError("model_version_id is missing for Civitai download.") + + file_info = get_civitai_file_info(model_version_id) + if not file_info or not file_info.get('downloadUrl'): + raise ConnectionError(f"Could not get download URL for Civitai model version ID {model_version_id}") + + status = download_file( + file_info['downloadUrl'], + dest_path, + api_key=os.environ.get("CIVITAI_API_KEY", ""), + progress=progress, + desc=f"Downloading CN: {filename}" + ) + if "Failed" in status: + raise ConnectionError(status) + else: + raise NotImplementedError(f"Download source '{source}' is not implemented for ControlNets.") + + except Exception as e: + if os.path.lexists(dest_path): + try: + os.remove(dest_path) + except OSError: + pass + raise gr.Error(f"ControlNet 模型“{filename}”下载失败:{e}") + +@_download_serialized +def ensure_file_downloaded(filename: str, progress=None): + if not filename or filename == "None": + return + + download_info = ALL_FILE_DOWNLOAD_MAP.get(filename) + if not download_info: + print(f"⚠️ Warning: File '{filename}' not found in configuration (file_list.yaml). Cannot download.") + return + + category = download_info.get("category", "loras") + dest_dir = CATEGORY_TO_DIR_MAP.get(category, LORA_DIR) + dest_path = os.path.join(dest_dir, filename) + + if os.path.lexists(dest_path): + if not os.path.exists(dest_path): + print(f"⚠️ Found and removed broken symlink: {dest_path}") + os.remove(dest_path) + else: + return + + source = download_info.get("source") + try: + if source == "hf": + repo_id = download_info.get("repo_id") + repo_filename = download_info.get("repository_file_path", filename) + if not repo_id: + raise ValueError("repo_id is missing for Hugging Face download.") + + if progress and callable(progress): + progress(0, desc=f"Downloading: {filename}") + cached_path = hf_hub_download(repo_id=repo_id, filename=repo_filename, token=os.environ.get("HF_TOKEN")) + os.makedirs(dest_dir, exist_ok=True) + os.symlink(cached_path, dest_path) + print(f"✅ Symlinked '{cached_path}' to '{dest_path}'") + if progress and callable(progress): + progress(1.0, desc=f"Downloaded: {filename}") + + elif source == "civitai": + model_version_id = download_info.get("model_version_id") + if not model_version_id: + raise ValueError("model_version_id is missing for Civitai download.") + + file_info = get_civitai_file_info(model_version_id) + if not file_info or not file_info.get('downloadUrl'): + raise ConnectionError(f"Could not get download URL for Civitai model version ID {model_version_id}") + + status = download_file( + file_info['downloadUrl'], + dest_path, + api_key=os.environ.get("CIVITAI_API_KEY", ""), + progress=progress, + desc=f"Downloading: {filename}" + ) + if "Failed" in status: + raise ConnectionError(status) + else: + raise NotImplementedError(f"Download source '{source}' is not implemented for '{filename}'.") + + except Exception as e: + if os.path.lexists(dest_path): + try: + os.remove(dest_path) + except OSError: + pass + raise gr.Error(f"文件“{filename}”下载失败:{e}") + +def load_ipadapter_presets(): + global IPADAPTER_PRESETS + if IPADAPTER_PRESETS is not None: + return + + _PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + _IPADAPTER_MODELS_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'ipadapter_models.yaml') + + try: + with open(_IPADAPTER_MODELS_PATH, 'r', encoding='utf-8') as f: + presets_list = yaml.load(f, Loader=UniqueKeyLoader) + + IPADAPTER_PRESETS = {item['preset_name']: item for item in presets_list} + print("✅ IPAdapter presets loaded successfully.") + except Exception as e: + print(f"❌ FATAL: Could not load or parse ipadapter_models.yaml. IPAdapter will not work. Error: {e}") + IPADAPTER_PRESETS = {} + +@_download_serialized +def ensure_ipadapter_models_downloaded(preset_name: str, progress): + if not preset_name: + return + + if IPADAPTER_PRESETS is None: + raise RuntimeError("IPAdapter presets have not been loaded. `load_ipadapter_presets` must be called on startup.") + + preset_info = IPADAPTER_PRESETS.get(preset_name) + if not preset_info: + print(f"⚠️ Warning: IPAdapter preset '{preset_name}' not found in configuration. Skipping download.") + return + + model_files_to_check = [] + + def add_files(value, type_name): + if not value: return + if isinstance(value, list): + for v in value: + model_files_to_check.append((v, type_name)) + else: + model_files_to_check.append((value, type_name)) + + add_files(preset_info.get('clip_vision'), 'CLIP_VISION') + add_files(preset_info.get('ipadapter'), 'IPADAPTER') + add_files(preset_info.get('loras'), 'LORA') + + for filename, model_type in model_files_to_check: + if not filename: + continue + + temp_display_name = f"ipadapter_asset_{filename}" + + if temp_display_name not in ALL_MODEL_MAP: + ALL_MODEL_MAP[temp_display_name] = (None, filename, model_type, None, None) + + try: + _ensure_model_downloaded(temp_display_name, progress) + except Exception as e: + print(f"❌ Error ensuring download for IPAdapter asset '{filename}': {e}") + +@_download_serialized +def ensure_sd3_ipadapter_models_downloaded(progress): + _PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + yaml_path = os.path.join(_PROJECT_ROOT, 'yaml', 'ipadapter_sd3_models.yaml') + try: + with open(yaml_path, 'r', encoding='utf-8') as f: + sd3_models = yaml.safe_load(f) + if sd3_models: + if 'ipadapter' in sd3_models: + _ensure_model_downloaded(sd3_models['ipadapter'], progress) + if 'clip_vision' in sd3_models: + _ensure_model_downloaded(sd3_models['clip_vision'], progress) + except Exception as e: + print(f"Warning: Failed to load or download sd3 ipadapter models: {e}") + +def get_model_generation_defaults(model_display_name: str, model_type: str, defaults_config: dict): + final_defaults = { + 'steps': 25, 'cfg': 7.0, 'sampler_name': 'euler', 'scheduler': 'simple', + 'positive_prompt': '', 'negative_prompt': '' + } + + if 'Default' in defaults_config: + final_defaults.update(defaults_config['Default']) + + model_type_key = next((key for key in defaults_config if key.lower().replace(" ", "-").replace(".", "") == model_type.lower()), None) + if model_type_key: + model_type_config = defaults_config[model_type_key] + if '_defaults' in model_type_config: + final_defaults.update(model_type_config['_defaults']) + + if model_display_name in model_type_config: + final_defaults.update(model_type_config[model_display_name]) + + return final_defaults diff --git a/mcp_tools/__init__.py b/mcp_tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..44af4b7976e0b589c95719de939dbf6b98b64948 --- /dev/null +++ b/mcp_tools/__init__.py @@ -0,0 +1,50 @@ +def __getattr__(name): + if name in ("types", "server", "client", "shared"): + raise ImportError(f"No module named 'mcp.{name}' in local mcp package") + raise AttributeError(f"module '{__name__}' has no attribute '{name}'") + +from .get_task_list import handle_get_task_list +from .get_model_architecture_list import handle_get_model_architecture_list +from .get_model_list import handle_get_model_list +from .get_feature_list import handle_get_feature_list +from .get_model_features import handle_get_model_features +from .run import handle_run +from .get_task_status import handle_get_task_status +from .get_chain_schema import handle_get_chain_schema +from .error_schema import make_error, make_validation_error, make_not_found_error +from .mcp_gradio_integration import ( + register_high_level_mcp_apis, + cleanup_dependencies_api_names, + patch_gradio_api_suppression, + HIGH_LEVEL_MCP_API_NAMES, +) + +MCP_FUNCTIONS = [ + handle_get_task_list, + handle_get_model_architecture_list, + handle_get_model_list, + handle_get_feature_list, + handle_get_model_features, + handle_run, + handle_get_task_status, + handle_get_chain_schema, +] + +__all__ = [ + "handle_get_task_list", + "handle_get_model_architecture_list", + "handle_get_model_list", + "handle_get_feature_list", + "handle_get_model_features", + "handle_run", + "handle_get_task_status", + "handle_get_chain_schema", + "make_error", + "make_validation_error", + "make_not_found_error", + "register_high_level_mcp_apis", + "cleanup_dependencies_api_names", + "patch_gradio_api_suppression", + "HIGH_LEVEL_MCP_API_NAMES", + "MCP_FUNCTIONS", +] diff --git a/mcp_tools/common.py b/mcp_tools/common.py new file mode 100644 index 0000000000000000000000000000000000000000..bfaa6701f51a39af75ddbdfba79f08c11d9fa732 --- /dev/null +++ b/mcp_tools/common.py @@ -0,0 +1,802 @@ +""" +MCP Common Utilities & Data Structures +Contains YAML loading utilities, config file paths, task definitions, and async task database. +""" + +import os +import time +import urllib.parse +import urllib.request +import urllib.error +import ipaddress +import socket +import base64 +import io +import copy +import threading +import yaml +from typing import Dict, Any +from PIL import Image +from core.runtime_config import CONFIG + +_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +_YAML_DIR = os.path.join(_PROJECT_ROOT, "yaml") + +_MODEL_ARCHITECTURES_PATH = os.path.join(_YAML_DIR, "model_architectures.yaml") +_MODEL_LIST_PATH = os.path.join(_YAML_DIR, "model_list.yaml") +_MODEL_DEFAULTS_PATH = os.path.join(_YAML_DIR, "model_defaults.yaml") +_IMAGE_GEN_FEATURES_PATH = os.path.join(_YAML_DIR, "image_gen_features.yaml") +_CHAIN_FEATURES_PATH = os.path.join(_YAML_DIR, "chain_features.yaml") +_CONSTANTS_PATH = os.path.join(_YAML_DIR, "constants.yaml") + + +_MAX_IMAGE_DOWNLOAD_BYTES = 50 * 1024 * 1024 # 50 MB +_IMAGE_DOWNLOAD_TIMEOUT = 30 # seconds +_ALLOWED_IMAGE_CONTENT_TYPES = frozenset([ + "image/png", "image/jpeg", "image/jpg", "image/gif", + "image/webp", "image/bmp", "image/tiff", +]) + + +def _validate_public_image_url(url: str) -> None: + parsed = urllib.parse.urlsplit(url) + if parsed.scheme not in {"http", "https"} or not parsed.hostname: + raise ValueError("Image URL must use HTTP or HTTPS and include a host.") + if parsed.username or parsed.password: + raise ValueError("Image URLs containing credentials are not accepted.") + try: + addresses = { + item[4][0] + for item in socket.getaddrinfo( + parsed.hostname, + parsed.port or (443 if parsed.scheme == "https" else 80), + ) + } + except socket.gaierror as exc: + raise ValueError(f"Could not resolve image URL host: {exc}") from exc + for address in addresses: + ip = ipaddress.ip_address(address.split("%", 1)[0]) + if not ip.is_global: + raise ValueError("Image URL must resolve to a public network address.") + + +class _PublicOnlyRedirectHandler(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + _validate_public_image_url(newurl) + return super().redirect_request(req, fp, code, msg, headers, newurl) + + +def _get_ipadapter_presets_by_arch() -> Dict[str, list]: + """Load IPAdapter presets from yaml/ipadapter.yaml for SD1.5 and SDXL.""" + ipadapter_yaml_path = os.path.join(_YAML_DIR, "ipadapter.yaml") + data = _load_yaml(ipadapter_yaml_path) + res = {} + for arch in ("SD1.5", "SDXL"): + std = data.get("IPAdapter_presets", {}).get(arch, []) + face = data.get("IPAdapter_FaceID_presets", {}).get(arch, []) + res[arch] = list(std) + list(face) + return res + + +def _parse_image_param(image_param: Any) -> Any: + """Parse a Base64 Data URI, HTTP/HTTPS URL, or PIL.Image into a PIL Image object.""" + if isinstance(image_param, Image.Image): + return _validate_decoded_image(image_param) + + if not isinstance(image_param, str) or not image_param.strip(): + return None + + image_param = image_param.strip() + + # HTTP / HTTPS URL — download the image + if image_param.startswith("http://") or image_param.startswith("https://"): + return _validate_decoded_image(_download_image_from_url(image_param)) + + # Base64 Data URI (e.g. data:image/png;base64,...) + if image_param.startswith("data:image/"): + _, encoded = image_param.split(",", 1) if "," in image_param else ("", image_param) + if len(encoded) > (_MAX_IMAGE_DOWNLOAD_BYTES * 4 // 3) + 8: + raise ValueError("Base64 image exceeds the 50 MB decoded-size limit.") + data = base64.b64decode(encoded) + if len(data) > _MAX_IMAGE_DOWNLOAD_BYTES: + raise ValueError("Decoded image exceeds the 50 MB size limit.") + return _validate_decoded_image(Image.open(io.BytesIO(data))) + + # Base64 string without header + if len(image_param) > 100: + try: + if len(image_param) > (_MAX_IMAGE_DOWNLOAD_BYTES * 4 // 3) + 8: + raise ValueError("Base64 image exceeds the 50 MB decoded-size limit.") + data = base64.b64decode(image_param) + if len(data) > _MAX_IMAGE_DOWNLOAD_BYTES: + raise ValueError("Decoded image exceeds the 50 MB size limit.") + return _validate_decoded_image(Image.open(io.BytesIO(data))) + except ValueError: + raise + except Exception: + pass + + raise ValueError( + "Invalid image parameter format. Expected a Base64 Data URI (e.g., 'data:image/png;base64,...') " + "or an HTTP/HTTPS URL." + ) + + +def _validate_decoded_image(image: Image.Image) -> Image.Image: + image.load() + megapixels = (image.width * image.height) / 1_000_000 + if megapixels > CONFIG.max_input_megapixels: + raise ValueError( + f"Decoded image is {megapixels:.1f} MP; maximum is " + f"{CONFIG.max_input_megapixels:g} MP." + ) + return image.copy() + + +def _download_image_from_url(url: str) -> Image.Image: + """Download an image from an HTTP/HTTPS URL and return it as a PIL Image. + + Security measures: + - Timeout to prevent hanging on slow/malicious servers. + - Response size cap to prevent memory exhaustion. + - Content-Type validation to reject non-image responses. + """ + _validate_public_image_url(url) + req = urllib.request.Request(url, headers={"User-Agent": "ImageGen-MCP/1.0"}) + opener = urllib.request.build_opener(_PublicOnlyRedirectHandler()) + try: + with opener.open(req, timeout=_IMAGE_DOWNLOAD_TIMEOUT) as resp: + # Validate content type + content_type = resp.headers.get("Content-Type", "").split(";")[0].strip().lower() + if content_type and content_type not in _ALLOWED_IMAGE_CONTENT_TYPES: + raise ValueError( + f"URL returned non-image Content-Type '{content_type}'. " + f"Expected one of: {', '.join(sorted(_ALLOWED_IMAGE_CONTENT_TYPES))}." + ) + + # Enforce size limit + content_length = resp.headers.get("Content-Length") + if content_length and int(content_length) > _MAX_IMAGE_DOWNLOAD_BYTES: + raise ValueError( + f"Image at URL is too large ({int(content_length)} bytes). " + f"Maximum allowed size is {_MAX_IMAGE_DOWNLOAD_BYTES} bytes." + ) + + # Stream-read with size cap + chunks = [] + total = 0 + while True: + chunk = resp.read(8192) + if not chunk: + break + total += len(chunk) + if total > _MAX_IMAGE_DOWNLOAD_BYTES: + raise ValueError( + f"Image download exceeded maximum allowed size of " + f"{_MAX_IMAGE_DOWNLOAD_BYTES} bytes." + ) + chunks.append(chunk) + + data = b"".join(chunks) + + except urllib.error.HTTPError as e: + raise ValueError(f"HTTP error {e.code} when downloading image from URL: {e.reason}") from e + except urllib.error.URLError as e: + raise ValueError(f"Failed to download image from URL: {e}") from e + + if not data: + raise ValueError("Downloaded image data is empty.") + + return Image.open(io.BytesIO(data)) + + +def _load_yaml(filepath: str) -> dict: + """Safely load a YAML file, returning an empty dict if the file does not exist.""" + if not os.path.exists(filepath): + print(f"Warning: YAML file not found: {filepath}") + return {} + with open(filepath, "r", encoding="utf-8") as f: + return yaml.safe_load(f) or {} + + +_COMMON_OPTIONAL_INPUTS = [ + "steps", "cfg", "sampler", "scheduler", "seed", + "negative_prompt", "batch_size", "chain", "async_execution", +] + +_TASK_DEFINITIONS = [ + { + "task_type": "txt2img", + "display_name": "Text-to-Image", + "description": "Generate images from text prompts. Canvas width and height must be specified.", + "required_inputs": ["prompt", "width", "height"], + "optional_inputs": _COMMON_OPTIONAL_INPUTS, + }, + { + "task_type": "img2img", + "display_name": "Image-to-Image", + "description": "Perform global repaint and style transfer based on a source image. Denoise strength must be specified.", + "required_inputs": ["prompt", "image", "denoise"], + "optional_inputs": _COMMON_OPTIONAL_INPUTS, + }, + { + "task_type": "inpaint", + "display_name": "Inpaint", + "description": "Repaint specified masked regions of the input image (with alpha mask/channel).", + "required_inputs": ["prompt", "image"], + "optional_inputs": ["denoise"] + _COMMON_OPTIONAL_INPUTS, + }, + { + "task_type": "outpaint", + "display_name": "Outpaint", + "description": "Extend the canvas outward from the source image. Padding pixel values for top, bottom, left, and right must be specified.", + "required_inputs": ["prompt", "image", "pad_left", "pad_right", "pad_top", "pad_bottom"], + "optional_inputs": _COMMON_OPTIONAL_INPUTS, + }, + { + "task_type": "hires_fix", + "display_name": "Hi-Res Fix / Upscale", + "description": "Enhance details and upscale an existing low-resolution image.", + "required_inputs": ["prompt", "image", "upscale_by"], + "optional_inputs": ["upscaler", "denoise"] + _COMMON_OPTIONAL_INPUTS, + }, +] + +_TASKS_DB: Dict[str, Dict[str, Any]] = {} +_TASKS_LOCK = threading.RLock() + + +def _update_task(task_id: str, **changes) -> None: + with _TASKS_LOCK: + if task_id in _TASKS_DB: + _TASKS_DB[task_id].update(changes) + + +def _get_task_snapshot(task_id: str) -> Dict[str, Any] | None: + with _TASKS_LOCK: + task = _TASKS_DB.get(task_id) + return copy.deepcopy(task) if task is not None else None + + +class DummyProgress: + def __call__(self, progress=0.0, desc=None): + pass + + +def _get_public_base_url() -> str: + """Auto-resolve the publicly accessible base URL (including protocol and port).""" + # 1. Explicit environment variable override + public_url = os.getenv("PUBLIC_URL") or os.getenv("BASE_URL") + if public_url: + return public_url.rstrip("/") + + # 2. Hugging Face Space environment variable + space_host = os.getenv("SPACE_HOST") + if space_host: + if not space_host.startswith("http://") and not space_host.startswith("https://"): + return f"https://{space_host}" + return space_host.rstrip("/") + + # 3. Local Gradio config fallback + try: + from core.settings import GRADIO_SERVER_NAME, SERVER_PORT + except ImportError: + GRADIO_SERVER_NAME = "127.0.0.1" + SERVER_PORT = 7860 + + server_name = os.getenv("GRADIO_SERVER_NAME", GRADIO_SERVER_NAME) + if server_name == "0.0.0.0": + server_name = "127.0.0.1" + port = os.getenv("GRADIO_SERVER_PORT", str(SERVER_PORT)) + + return f"http://{server_name}:{port}" + + +def _execute_imagegen_pipeline(task_id: str, params: dict): + """Execute the image generation pipeline in the background and update _TASKS_DB.""" + start_time = time.time() + try: + _update_task( + task_id, + status="processing", + progress=10, + updated_at=int(start_time), + ) + + from core.generation_logic import sd_image_pipeline + + task_type = params["task_type"] + model = params["model"] + prompt = params["prompt"] + + model_defaults = _load_yaml(_MODEL_DEFAULTS_PATH) + model_list = _load_yaml(_MODEL_LIST_PATH) + checkpoints = model_list.get("Checkpoint", {}) + found_arch = None + for arch_name, arch_data in checkpoints.items(): + if isinstance(arch_data, dict): + for m in arch_data.get("models", []): + if m.get("display_name") == model: + found_arch = arch_name + break + if found_arch: + break + + arch_defaults_section = model_defaults.get(found_arch, {}) if found_arch else {} + arch_level_defaults = arch_defaults_section.get("_defaults", {}) + model_specific_defaults = arch_defaults_section.get(model, {}) + global_defaults = model_defaults.get("Default", {}) + merged_defaults = {**global_defaults, **arch_level_defaults, **model_specific_defaults} + + steps = params.get("steps") if params.get("steps") is not None else merged_defaults.get("steps", 20) + cfg = params.get("cfg") if params.get("cfg") is not None else merged_defaults.get("cfg", 1.0) + sampler = params.get("sampler") or merged_defaults.get("sampler_name", "euler") + scheduler = params.get("scheduler") or merged_defaults.get("scheduler", "simple") + + ui_inputs = { + "task_type": task_type, + "model_display_name": model, + "base_model_" + task_type: model, + "positive_prompt": prompt, + "negative_prompt": params.get("negative_prompt", merged_defaults.get("negative_prompt", "")), + "width": params.get("width", 1024), + "height": params.get("height", 1024), + "num_inference_steps": steps, + "guidance_scale": cfg, + "sampler": sampler, + "scheduler": scheduler, + "seed": params.get("seed", -1), + "batch_size": params.get("batch_size", 1), + "zero_gpu_duration": params.get("zero_gpu_duration"), + "denoise": params.get("denoise", 1.0), + } + + if "image" in params and params["image"]: + pil_img = _parse_image_param(params["image"]) + if pil_img: + if task_type == "img2img": + ui_inputs["img2img_image"] = pil_img + ui_inputs["img2img_denoise"] = params.get("denoise", 0.7) + elif task_type == "inpaint": + ui_inputs["inpaint_image"] = pil_img + ui_inputs["inpaint_denoise"] = params.get("denoise", 1.0) + elif task_type == "outpaint": + ui_inputs["outpaint_image"] = pil_img + ui_inputs["left"] = params.get("pad_left", 0) + ui_inputs["right"] = params.get("pad_right", 0) + ui_inputs["top"] = params.get("pad_top", 0) + ui_inputs["bottom"] = params.get("pad_bottom", 0) + ui_inputs["feathering"] = params.get("feathering", 10) + elif task_type == "hires_fix": + ui_inputs["hires_image"] = pil_img + upscaler = params.get("upscaler", "nearest-exact") + if upscaler == "latent" or upscaler not in ["nearest-exact", "bilinear", "area", "bicubic", "bislerp"]: + upscaler = "nearest-exact" + ui_inputs["hires_upscaler"] = upscaler + ui_inputs["hires_scale_by"] = params.get("upscale_by", 2.0) + ui_inputs["hires_denoise"] = params.get("denoise", 0.55) + + chain = params.get("chain", []) + if chain: + lora_data = [] + embedding_data = [] + controlnet_data = [] + diffsynth_controlnet_data = [] + ipadapter_data = [] + ipadapter_images = [] + ipadapter_weights = [] + ipadapter_lora_strengths = [] + ipadapter_global_preset = params.get("ipadapter_preset") or params.get("preset") + ipadapter_global_embeds_scaling = params.get("ipadapter_embeds_scaling") or params.get("embeds_scaling") + ipadapter_global_combine_method = params.get("ipadapter_combine_method") or params.get("combine_method") + ipadapter_global_final_weight = params.get("ipadapter_final_weight") or params.get("final_weight") + flux1_ipadapter_images = [] + flux1_ipadapter_weights = [] + flux1_ipadapter_starts = [] + flux1_ipadapter_ends = [] + sd3_ipadapter_images = [] + sd3_ipadapter_weights = [] + sd3_ipadapter_starts = [] + sd3_ipadapter_ends = [] + style_images = [] + style_strengths = [] + krea2_identity_edit_data = [] + krea2_reference_edit_data = [] + krea2_controlnet_data = [] + anima_controlnet_lllite_data = [] + reference_latent_data = [] + reference_image_data = [] + joyai_reference_data = [] + boogu_edit_data = [] + qwen_image_edit_data = [] + hidream_o1_reference_data = [] + cond_prompts = [] + cond_widths = [] + cond_heights = [] + cond_xs = [] + cond_ys = [] + cond_strengths = [] + + for item in chain: + itype = item.get("injector_type") + if itype == "lora": + lora_data.extend([ + item.get("source", item.get("lora_source", "Civitai")), + item.get("lora_value", ""), + item.get("scale", 1.0), + None + ]) + elif itype == "embedding": + e_source = item.get("source", item.get("embedding_source", "Civitai")) + e_val = item.get("embedding_value", item.get("value", item.get("embedding_id", ""))) + if e_source and e_val: + embedding_data.extend([ + e_source, + str(e_val), + None + ]) + elif itype == "conditioning": + p = item.get("prompt", "") + if p: + cond_prompts.append(p) + cond_widths.append(int(item.get("width", 512))) + cond_heights.append(int(item.get("height", 512))) + cond_xs.append(int(item.get("x", 0))) + cond_ys.append(int(item.get("y", 0))) + cond_strengths.append(float(item.get("strength", 1.0))) + elif itype == "controlnet": + cn_type = item.get("type", item.get("Type", "")) + cn_series = item.get("series", item.get("Series", "")) + cn_strength = float(item.get("strength", 1.0)) + cn_img = _parse_image_param(item.get("image")) + + cn_filepath = item.get("control_net_name", "None") + cn_raw = _load_yaml(os.path.join(_YAML_DIR, "controlnet_models.yaml")).get("ControlNet", {}) + + cn_arch_key = None + if found_arch: + arch_cfg = _load_yaml(os.path.join(_YAML_DIR, "model_architectures.yaml")).get("architectures", {}) + cn_arch_key = arch_cfg.get(found_arch, {}).get("controlnet_key", found_arch) + + arch_entries = [] + if cn_arch_key and cn_arch_key in cn_raw: + arch_entries = cn_raw[cn_arch_key] + elif found_arch and found_arch in cn_raw: + arch_entries = cn_raw[found_arch] + else: + for val in cn_raw.values(): + if isinstance(val, list): + arch_entries.extend(val) + elif isinstance(val, dict): + arch_entries.append(val) + + if arch_entries: + for entry in arch_entries: + entry_types = entry.get("Type", []) + if isinstance(entry_types, str): + entry_types = [entry_types] + if not cn_type or cn_type in entry_types: + if not cn_series or entry.get("Series") == cn_series: + cn_filepath = entry.get("Filepath", cn_filepath) + if not cn_series: + cn_series = entry.get("Series", "") + if not cn_type and entry_types: + cn_type = entry_types[0] + break + + controlnet_data.extend([ + cn_img, + cn_type, + cn_series, + cn_strength, + cn_filepath + ]) + elif itype == "anima_controlnet_lllite": + cn_type = item.get("type", item.get("Type", "")) + cn_series = item.get("series", item.get("Series", "")) + cn_strength = float(item.get("strength", 1.0)) + cn_start = float(item.get("start_percent", 0.0)) + cn_end = float(item.get("end_percent", 1.0)) + cn_img = _parse_image_param(item.get("image")) + + cn_filepath = item.get("control_net_name", "None") + anima_cfg = _load_yaml(os.path.join(_YAML_DIR, "anima_controlnet_lllite_models.yaml")).get("Anima_ControlNet_Lllite", []) + if anima_cfg: + for entry in anima_cfg: + entry_types = entry.get("Type", []) + if isinstance(entry_types, str): + entry_types = [entry_types] + if not cn_type or cn_type in entry_types: + if not cn_series or entry.get("Series") == cn_series: + cn_filepath = entry.get("Filepath", cn_filepath) + if not cn_series: + cn_series = entry.get("Series", "") + if not cn_type and entry_types: + cn_type = entry_types[0] + break + + anima_controlnet_lllite_data.extend([ + cn_img, + cn_type, + cn_series, + cn_strength, + cn_filepath, + cn_start, + cn_end + ]) + elif itype == "diffsynth_controlnet": + cn_type = item.get("type", "") + cn_series = item.get("series", "") + cn_strength = float(item.get("strength", 1.0)) + cn_img = _parse_image_param(item.get("image")) + + cn_filepath = "None" + diffsynth_raw = _load_yaml(os.path.join(_YAML_DIR, "diffsynth_controlnet_models.yaml")).get("DiffSynth_ControlNet", {}) + diffsynth_entries = [] + if isinstance(diffsynth_raw, dict): + for val in diffsynth_raw.values(): + if isinstance(val, list): + diffsynth_entries.extend(val) + elif isinstance(val, dict): + diffsynth_entries.append(val) + elif isinstance(diffsynth_raw, list): + diffsynth_entries = diffsynth_raw + + if diffsynth_entries: + for entry in diffsynth_entries: + if not cn_type or cn_type in entry.get("Type", []): + if not cn_series or entry.get("Series") == cn_series: + cn_filepath = entry.get("Filepath", cn_filepath) + if not cn_series: + cn_series = entry.get("Series", cn_series) + if not cn_type and entry.get("Type"): + cn_type = entry.get("Type")[0] + break + + diffsynth_controlnet_data.extend([ + cn_img, + cn_type, + cn_series, + cn_strength, + cn_filepath + ]) + elif itype == "krea2_controlnet": + cn_type = item.get("type", "Depth") + cn_series = item.get("series", "Patil") + cn_strength = float(item.get("strength", 1.0)) + cn_img = _parse_image_param(item.get("image")) + + cn_filepath = "depth-control-lora.safetensors" + krea2_cfg = _load_yaml(os.path.join(_YAML_DIR, "krea2_controlnet_models.yaml")).get("Krea2_ControlNet", []) + if krea2_cfg: + for entry in krea2_cfg: + if cn_type in entry.get("Type", []): + if not cn_series or entry.get("Series") == cn_series: + cn_filepath = entry.get("Filepath", cn_filepath) + cn_series = entry.get("Series", cn_series) + break + + krea2_controlnet_data.extend([ + cn_img, + cn_type, + cn_series, + cn_strength, + cn_filepath + ]) + elif itype == "flux1_ipadapter": + if len(flux1_ipadapter_images) < 5: + img = _parse_image_param(item.get("image")) + weight = float(item.get("weight", 1.0)) + start_at = float(item.get("start_at", item.get("start_percent", item.get("start", 0.0)))) + end_at = float(item.get("end_at", item.get("end_percent", item.get("end", 1.0)))) + flux1_ipadapter_images.append(img) + flux1_ipadapter_weights.append(weight) + flux1_ipadapter_starts.append(start_at) + flux1_ipadapter_ends.append(end_at) + elif itype == "sd3_ipadapter": + if len(sd3_ipadapter_images) < 5: + img = _parse_image_param(item.get("image")) + weight = float(item.get("weight", 1.0)) + start_at = float(item.get("start_at", item.get("start_percent", item.get("start", 0.0)))) + end_at = float(item.get("end_at", item.get("end_percent", item.get("end", 1.0)))) + sd3_ipadapter_images.append(img) + sd3_ipadapter_weights.append(weight) + sd3_ipadapter_starts.append(start_at) + sd3_ipadapter_ends.append(end_at) + elif itype == "ipadapter": + if len(ipadapter_images) < 5: + img = _parse_image_param(item.get("image")) + weight = float(item.get("weight", 1.0)) + lora_str = float(item.get("lora_strength", 0.6)) + ipadapter_images.append(img) + ipadapter_weights.append(weight) + ipadapter_lora_strengths.append(lora_str) + + if "preset" in item and not ipadapter_global_preset: + ipadapter_global_preset = item["preset"] + if "embeds_scaling" in item and not ipadapter_global_embeds_scaling: + ipadapter_global_embeds_scaling = item["embeds_scaling"] + if "combine_method" in item and not ipadapter_global_combine_method: + ipadapter_global_combine_method = item["combine_method"] + if "final_weight" in item and ipadapter_global_final_weight is None: + ipadapter_global_final_weight = float(item["final_weight"]) + elif itype in ("style", "flux1_style"): + img = _parse_image_param(item.get("image")) + if img: + style_images.append(img) + style_strengths.append(float(item.get("strength", item.get("weight", 1.0)))) + elif itype == "pid": + is_enabled = item.get("enabled", True) + if isinstance(is_enabled, str): + is_enabled = is_enabled.upper() in ("ON", "TRUE", "1") + ui_inputs["pid_settings"] = "ON" if is_enabled else "OFF" + elif itype == "krea2_identity_edit": + img = _parse_image_param(item.get("image")) + if img: + krea2_identity_edit_data.append(img) + elif itype == "krea2_style_reference": + img = _parse_image_param(item.get("image")) + if img: + krea2_reference_edit_data.append(img) + elif itype in ("reference_latent", "reference_edit"): + img = _parse_image_param(item.get("image")) + if img: + reference_latent_data.append(img) + elif itype in ("reference_image", "mage_flow_reference_edit"): + img = _parse_image_param(item.get("image")) + if img: + reference_image_data.append(img) + elif itype in ("joyai_image", "joyai_reference_edit"): + img = _parse_image_param(item.get("image")) + if img: + joyai_reference_data.append(img) + elif itype in ("boogu_image_edit", "boogu_edit"): + img = _parse_image_param(item.get("image")) + if img: + boogu_edit_data.append(img) + elif itype == "qwen_image_edit": + img = _parse_image_param(item.get("image")) + if img: + qwen_image_edit_data.append(img) + elif itype == "hidream_o1_reference": + img = _parse_image_param(item.get("image")) + if img: + hidream_o1_reference_data.append(img) + elif itype == "vae": + v_source = item.get("source", item.get("vae_source", "Civitai")) + v_val = item.get("vae_value", item.get("value", item.get("vae_id", item.get("vae_name", "")))) + if v_source and v_val: + ui_inputs["vae_source"] = v_source + ui_inputs["vae_id"] = str(v_val) + + if lora_data: ui_inputs["lora_data"] = lora_data + if embedding_data: ui_inputs["embedding_data"] = embedding_data + if controlnet_data: ui_inputs["controlnet_data"] = controlnet_data + if anima_controlnet_lllite_data: ui_inputs["anima_controlnet_lllite_data"] = anima_controlnet_lllite_data + if diffsynth_controlnet_data: ui_inputs["diffsynth_controlnet_data"] = diffsynth_controlnet_data + if krea2_controlnet_data: ui_inputs["krea2_controlnet_data"] = krea2_controlnet_data + if ipadapter_images: + preset = ipadapter_global_preset or "STANDARD (medium strength)" + embeds_scaling = ipadapter_global_embeds_scaling or "V only" + combine_method = ipadapter_global_combine_method or "concat" + final_weight = float(ipadapter_global_final_weight) if ipadapter_global_final_weight is not None else 1.0 + final_lora_strength = 0.6 + + presets_by_arch = _get_ipadapter_presets_by_arch() + target_arch = "SD1.5" if found_arch in ("sd15", "SD1.5") else "SDXL" + allowed_presets = presets_by_arch.get(target_arch, []) + + if preset not in allowed_presets: + raise ValueError( + f"Invalid IPAdapter preset '{preset}' for model architecture '{target_arch}'. " + f"Preset must match the target model architecture. Allowed presets for {target_arch}: {allowed_presets}" + ) + + ui_inputs["ipadapter_data"] = ( + ipadapter_images + ipadapter_weights + ipadapter_lora_strengths + + [preset, final_weight, final_lora_strength, embeds_scaling, combine_method] + ) + elif ipadapter_data: + ui_inputs["ipadapter_data"] = ipadapter_data + if flux1_ipadapter_images: + ui_inputs["flux1_ipadapter_data"] = ( + flux1_ipadapter_images + flux1_ipadapter_weights + flux1_ipadapter_starts + flux1_ipadapter_ends + ) + if sd3_ipadapter_images: + ui_inputs["sd3_ipadapter_chain"] = ( + sd3_ipadapter_images + sd3_ipadapter_weights + sd3_ipadapter_starts + sd3_ipadapter_ends + ) + if style_images: ui_inputs["style_data"] = style_images + style_strengths + if krea2_identity_edit_data: ui_inputs["krea2_identity_edit_data"] = krea2_identity_edit_data + if krea2_reference_edit_data: ui_inputs["krea2_reference_edit_data"] = krea2_reference_edit_data + if reference_latent_data: ui_inputs["reference_latent_data"] = reference_latent_data + if reference_image_data: ui_inputs["reference_image_data"] = reference_image_data + if joyai_reference_data: ui_inputs["joyai_reference_data"] = joyai_reference_data + if boogu_edit_data: ui_inputs["boogu_edit_data"] = boogu_edit_data + if qwen_image_edit_data: ui_inputs["qwen_image_edit_data"] = qwen_image_edit_data + if hidream_o1_reference_data: ui_inputs["hidream_o1_reference_data"] = hidream_o1_reference_data + if cond_prompts: + ui_inputs["conditioning_data"] = ( + cond_prompts + cond_widths + cond_heights + cond_xs + cond_ys + cond_strengths + ) + + if "vae_source" in params and "vae_id" in params: + ui_inputs["vae_source"] = params["vae_source"] + ui_inputs["vae_id"] = str(params["vae_id"]) + + pid_val = params.get("pid") if params.get("pid") is not None else params.get("pid_settings") + if pid_val is not None: + if isinstance(pid_val, bool): + ui_inputs["pid_settings"] = "ON" if pid_val else "OFF" + elif str(pid_val).upper() in ("ON", "TRUE", "1"): + ui_inputs["pid_settings"] = "ON" + else: + ui_inputs["pid_settings"] = "OFF" + + _update_task(task_id, progress=50) + + # Execute Pipeline + output = sd_image_pipeline.run(ui_inputs=ui_inputs, progress=DummyProgress()) + + try: + from core.settings import OUTPUT_DIR + except ImportError: + OUTPUT_DIR = os.path.join(_PROJECT_ROOT, "output") + + os.makedirs(OUTPUT_DIR, exist_ok=True) + + import tempfile + import gradio.processing_utils as pu + + gradio_cache_dir = os.path.join(tempfile.gettempdir(), "gradio") + os.makedirs(gradio_cache_dir, exist_ok=True) + + base_url = _get_public_base_url() + images = [] + raw_list = output if isinstance(output, list) else ([output] if output else []) + for idx, item in enumerate(raw_list): + target_path = None + if hasattr(item, "save"): # PIL Image + filename = f"mcp_{task_id}_{idx}.png" + filepath = os.path.join(OUTPUT_DIR, filename) + item.save(filepath) + target_path = filepath + elif isinstance(item, str) and os.path.exists(item): + target_path = item + + if target_path: + try: + cached_path = pu.save_file_to_cache(target_path, cache_dir=gradio_cache_dir) + abs_path = os.path.abspath(cached_path).replace("\\", "/") + except Exception as e: + print(f"Warning: Failed to cache image file to Gradio temp dir: {e}") + abs_path = os.path.abspath(target_path).replace("\\", "/") + + url = f"{base_url}/gradio_api/file={urllib.parse.quote(abs_path)}" + images.append(url) + elif item: + images.append(str(item)) + + execution_time = round(time.time() - start_time, 2) + _update_task( + task_id, + status="completed", + progress=100, + completed_at=int(time.time()), + result={ + "images": images, + "seed": ui_inputs.get("seed", params.get("seed", -1)), + "width": ui_inputs.get("width", params.get("width", 1024)), + "height": ui_inputs.get("height", params.get("height", 1024)), + "execution_time_seconds": execution_time, + }, + ) + + except Exception as e: + _update_task( + task_id, + status="failed", + progress=0, + failed_at=int(time.time()), + error={"code": "EXECUTION_ERROR", "message": str(e)}, + ) diff --git a/mcp_tools/error_schema.py b/mcp_tools/error_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..5e4fe9d79f5b2f53faffad72e67be8a9a441ebd6 --- /dev/null +++ b/mcp_tools/error_schema.py @@ -0,0 +1,85 @@ +""" +Unified MCP tool error response format. + +Error code enumeration: + - INVALID_PARAMS: Parameter validation failed (missing required fields, type errors, value out of range) + - MODEL_NOT_FOUND: The specified model name does not exist + - ARCHITECTURE_NOT_FOUND: The specified architecture name does not exist + - CHAIN_TYPE_NOT_FOUND: The specified chain/injector type is invalid + - FEATURE_NOT_SUPPORTED: The current model does not support the requested feature + - TASK_NOT_FOUND: The async task ID does not exist + - MODEL_OOM: GPU out of memory + - INTERNAL_ERROR: Internal server error +""" + + +def make_error(code: str, message: str, details: dict = None) -> dict: + """ + Construct a unified MCP tool error response. + + Args: + code: Error code (UPPER_SNAKE_CASE format) + message: Human-readable error description + details: Optional details dictionary + + Returns: + Standardized error response dictionary + """ + error = { + "error": { + "code": code, + "message": message, + } + } + if details: + error["error"]["details"] = details + return error + + +def make_validation_error( + message: str = "Request validation failed.", + missing_fields: list = None, + invalid_fields: dict = None, +) -> dict: + """ + Construct a parameter validation failure error response. + + Args: + message: Error description + missing_fields: List of missing required field names + invalid_fields: Key-value pairs of invalid fields, key=field name, value=reason description + + Returns: + Standardized INVALID_PARAMS error response + """ + details = {} + if missing_fields: + details["missing_fields"] = missing_fields + if invalid_fields: + details["invalid_fields"] = invalid_fields + return make_error("INVALID_PARAMS", message, details if details else None) + + +def make_not_found_error(resource_type: str, resource_id: str) -> dict: + """ + Construct a resource-not-found error response. + + Args: + resource_type: Resource type (e.g., "model", "architecture", "chain_type", "task") + resource_id: Resource identifier + + Returns: + Standardized *_NOT_FOUND error response + """ + code_map = { + "model": "MODEL_NOT_FOUND", + "architecture": "ARCHITECTURE_NOT_FOUND", + "chain_type": "CHAIN_TYPE_NOT_FOUND", + "task": "TASK_NOT_FOUND", + } + code = code_map.get(resource_type, f"{resource_type.upper()}_NOT_FOUND") + return make_error( + code, + f"The specified {resource_type} '{resource_id}' was not found.", + {"resource_type": resource_type, "resource_id": resource_id}, + ) diff --git a/mcp_tools/get_chain_schema.py b/mcp_tools/get_chain_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..54b51da4fa5db0d2b854028ed004b7af465cbaff --- /dev/null +++ b/mcp_tools/get_chain_schema.py @@ -0,0 +1,39 @@ +"""Fluxus-compatible feature schema endpoint.""" + +from .common import _CHAIN_FEATURES_PATH, _load_yaml +from .error_schema import make_not_found_error, make_validation_error + + +def handle_get_chain_schema(chain_type: str) -> dict: + if not chain_type: + return make_validation_error( + "Parameter 'chain_type' is required.", + missing_fields=["chain_type"], + ) + + chain_features = _load_yaml(_CHAIN_FEATURES_PATH) + resolved = chain_type if chain_type in chain_features else None + if resolved is None: + for feature_name, feature_data in chain_features.items(): + aliases = feature_data.get("chains") + if aliases == chain_type or ( + isinstance(aliases, list) and chain_type in aliases + ): + resolved = feature_name + break + + if resolved is None: + return make_not_found_error("chain_type", chain_type) + + chain_data = chain_features[resolved] + return { + "feature_name": chain_type, + "canonical_feature_name": resolved, + "chains": chain_data.get("chains", resolved), + "display_name": chain_data.get("display_name", resolved), + "description": chain_data.get("description", ""), + "supported_tasks": chain_data.get("supported_tasks", []), + "max_count": chain_data.get("max_count", 1), + "usage_guideline": chain_data.get("usage_guideline", ""), + "parameters_schema": chain_data.get("parameters_schema", {}), + } diff --git a/mcp_tools/get_feature_list.py b/mcp_tools/get_feature_list.py new file mode 100644 index 0000000000000000000000000000000000000000..6475dbf7fe247d2f42714f2ad946c3eb3f755055 --- /dev/null +++ b/mcp_tools/get_feature_list.py @@ -0,0 +1,131 @@ +import os +from copy import deepcopy +from .common import _load_yaml, _CHAIN_FEATURES_PATH, _YAML_DIR +from .error_schema import make_not_found_error + + +def _build_feature_entry(chain_name: str, chain_data: dict, include_schema: bool = False) -> dict: + entry = { + "feature_name": chain_name, + "chains": chain_data.get("chains", chain_name), + "display_name": chain_data.get("display_name", chain_name), + "description": chain_data.get("description", ""), + "supported_tasks": chain_data.get("supported_tasks", []), + "max_count": chain_data.get("max_count", 1), + "usage_guideline": chain_data.get("usage_guideline", ""), + } + if include_schema: + schema = deepcopy(chain_data.get("parameters_schema", {})) + if chain_name in ("krea2_controlnet", "diffsynth_controlnet", "controlnet", "anima_controlnet_lllite"): + config_key = ( + "Krea2_ControlNet" if chain_name == "krea2_controlnet" + else "DiffSynth_ControlNet" if chain_name == "diffsynth_controlnet" + else "Anima_ControlNet_Lllite" if chain_name == "anima_controlnet_lllite" + else "ControlNet" + ) + yaml_filename = f"{chain_name}_models.yaml" + model_path = os.path.join(_YAML_DIR, yaml_filename) + raw_models = _load_yaml(model_path).get(config_key, []) + models_list = [] + if isinstance(raw_models, dict): + for val in raw_models.values(): + if isinstance(val, list): + models_list.extend(val) + elif isinstance(val, dict): + models_list.append(val) + elif isinstance(raw_models, list): + models_list = raw_models + + types_set = set() + for m in models_list: + t_val = m.get("Type", []) + if isinstance(t_val, list): + types_set.update(t_val) + elif isinstance(t_val, str): + types_set.add(t_val) + types = sorted(list(types_set)) + series = sorted(list(set(m.get("Series") for m in models_list if m.get("Series")))) + if "properties" in schema: + if "type" in schema["properties"] and types: + schema["properties"]["type"]["enum"] = types + if "series" in schema["properties"] and series: + schema["properties"]["series"]["enum"] = series + if chain_name == "controlnet" and isinstance(raw_models, dict): + schema["architectures"] = raw_models + elif chain_name == "ipadapter": + from .common import _get_ipadapter_presets_by_arch + presets_by_arch = _get_ipadapter_presets_by_arch() + schema["presets_by_architecture"] = presets_by_arch + all_presets = sorted(list(set(presets_by_arch.get("SD1.5", []) + presets_by_arch.get("SDXL", [])))) + if "properties" in schema and "preset" in schema["properties"]: + schema["properties"]["preset"]["enum"] = all_presets + entry["parameters_schema"] = schema + return entry + + +def handle_get_feature_list( + feature_name: str | list[str] = "", + include_schema_on_empty: bool = False, +) -> list | dict: + """ + Dynamically load supported advanced features from chain_features.yaml. + + - If feature_name is empty: returns summaries by default; callers can set + include_schema_on_empty for the legacy Fluxus full-schema contract. + - If feature_name is specified (single feature name, comma-separated string, or list of strings): + returns complete feature details INCLUDING parameters_schema for the requested feature(s). + """ + chain_features = _load_yaml(_CHAIN_FEATURES_PATH) + + targets = [] + is_single_string_query = False + + if isinstance(feature_name, list): + targets = [str(x).strip() for x in feature_name if str(x).strip()] + elif isinstance(feature_name, str) and feature_name.strip(): + raw_str = feature_name.strip() + parts = [x.strip() for x in raw_str.split(",") if x.strip()] + targets = parts + if len(parts) == 1 and "," not in raw_str: + is_single_string_query = True + + # Empty discovery can serve both contracts: compact ImageGen summaries or + # Fluxus-compatible full schemas. + if not targets: + return [ + _build_feature_entry( + name, data, include_schema=include_schema_on_empty + ) + for name, data in chain_features.items() + ] + + # Helper function to resolve feature target by key or chains alias + def _resolve_target(target_name: str) -> str | None: + if target_name in chain_features: + return target_name + for feat_key, feat_data in chain_features.items(): + feat_chains = feat_data.get("chains") + if isinstance(feat_chains, str) and feat_chains == target_name: + return feat_key + elif isinstance(feat_chains, list) and target_name in feat_chains: + return feat_key + return None + + resolved_targets = [] + # Case 2: Specific feature(s) requested -> validate existence + for target in targets: + resolved = _resolve_target(target) + if not resolved: + return make_not_found_error("feature_name", target) + resolved_targets.append(resolved) + + # Case 3: Return full info including parameters_schema + results = [ + _build_feature_entry(target, chain_features[target], include_schema=True) + for target in resolved_targets + ] + + if is_single_string_query and len(results) == 1: + return results[0] + + return results diff --git a/mcp_tools/get_model_architecture_list.py b/mcp_tools/get_model_architecture_list.py new file mode 100644 index 0000000000000000000000000000000000000000..fd03154addc21853c20f74f2669e19a19b0d3a35 --- /dev/null +++ b/mcp_tools/get_model_architecture_list.py @@ -0,0 +1,36 @@ +""" +MCP Tool: get_model_architecture_list +Get all supported model architectures and their corresponding default resolutions. +""" + +from .common import _load_yaml, _MODEL_ARCHITECTURES_PATH, _CONSTANTS_PATH + + +def handle_get_model_architecture_list() -> list: + """Dynamically load all supported model architectures from model_architectures.yaml.""" + arch_config = _load_yaml(_MODEL_ARCHITECTURES_PATH) + constants = _load_yaml(_CONSTANTS_PATH) + resolution_map = constants.get("RESOLUTION_MAP", {}) + architectures = arch_config.get("architectures", {}) + architecture_order = arch_config.get("architecture_order", list(architectures.keys())) + + result = [] + for arch_name in architecture_order: + if arch_name not in architectures: + continue + arch_data = architectures[arch_name] + model_type = arch_data.get("model_type", arch_name.lower()) + + default_res = [1024, 1024] + if model_type in resolution_map: + resolutions = resolution_map[model_type] + if resolutions: + first_key = next(iter(resolutions)) + default_res = resolutions[first_key] + + result.append({ + "model_architecture": arch_name, + "default_resolution": default_res, + }) + + return result diff --git a/mcp_tools/get_model_features.py b/mcp_tools/get_model_features.py new file mode 100644 index 0000000000000000000000000000000000000000..69115fee9db55d4f21b1114b7401fd5c6d03e05f --- /dev/null +++ b/mcp_tools/get_model_features.py @@ -0,0 +1,106 @@ +""" +MCP Tool: get_model_features +Query metadata for a specified model, including supported task types, extended features, and default inference parameters. +""" + +from .common import ( + _load_yaml, + _MODEL_LIST_PATH, + _MODEL_DEFAULTS_PATH, + _IMAGE_GEN_FEATURES_PATH, + _MODEL_ARCHITECTURES_PATH, + _CHAIN_FEATURES_PATH, + _TASK_DEFINITIONS, +) +from .error_schema import make_validation_error, make_not_found_error +from core.model_capabilities import supports_chain_for_model + + +def handle_get_model_features(model: str) -> dict: + """Query metadata for a specified model: supported task types, extended features, and default inference parameters.""" + if not model: + return make_validation_error( + "Parameter 'model' is required.", + missing_fields=["model"], + ) + + model_list = _load_yaml(_MODEL_LIST_PATH) + model_defaults = _load_yaml(_MODEL_DEFAULTS_PATH) + features_config = _load_yaml(_IMAGE_GEN_FEATURES_PATH) + arch_config = _load_yaml(_MODEL_ARCHITECTURES_PATH) + chain_features = _load_yaml(_CHAIN_FEATURES_PATH) + + found_arch = None + checkpoints = model_list.get("Checkpoint", {}) + for arch_name, arch_data in checkpoints.items(): + if not isinstance(arch_data, dict): + continue + for m in arch_data.get("models", []): + if m.get("display_name") == model: + found_arch = arch_name + break + if found_arch: + break + + if not found_arch: + return make_not_found_error("model", model) + + architectures = arch_config.get("architectures", {}) + arch_info = architectures.get(found_arch, {}) + model_type = arch_info.get("model_type", found_arch.lower()) + + arch_features = features_config.get(model_type, features_config.get("default", {})) + enabled_chains = arch_features.get("enabled_chains", []) + + supported_features = [] + for feat_name, feat_data in chain_features.items(): + feat_chains = feat_data.get("chains") + if feat_chains is None: + feat_chains = [feat_name] + elif isinstance(feat_chains, str): + feat_chains = [feat_chains] + + if any( + c in enabled_chains and supports_chain_for_model(model, c) + for c in feat_chains + ): + supported_features.append(feat_name) + + arch_defaults_section = model_defaults.get(found_arch, {}) + arch_level_defaults = arch_defaults_section.get("_defaults", {}) + model_specific_defaults = arch_defaults_section.get(model, {}) + global_defaults = model_defaults.get("Default", {}) + + merged_defaults = {**global_defaults, **arch_level_defaults, **model_specific_defaults} + + default_parameter = { + "sampler": merged_defaults.get("sampler_name", "euler"), + "scheduler": merged_defaults.get("scheduler", "simple"), + "steps": merged_defaults.get("steps", 20), + "cfg": merged_defaults.get("cfg", 1.0), + } + + supported_tasks = [t["task_type"] for t in _TASK_DEFINITIONS] + + result = { + "name": model, + "model_architecture": found_arch, + "supported_tasks": supported_tasks, + "supported_features": supported_features, + "default_parameter": default_parameter, + } + + default_pos = model_specific_defaults.get( + "positive_prompt", + arch_level_defaults.get("positive_prompt", ""), + ) + default_neg = model_specific_defaults.get( + "negative_prompt", + arch_level_defaults.get("negative_prompt", ""), + ) + if default_pos: + result["default_positive_prompt"] = default_pos + if default_neg: + result["default_negative_prompt"] = default_neg + + return result diff --git a/mcp_tools/get_model_list.py b/mcp_tools/get_model_list.py new file mode 100644 index 0000000000000000000000000000000000000000..fc60fc112538f1226179284de8cedd7d5c814a9e --- /dev/null +++ b/mcp_tools/get_model_list.py @@ -0,0 +1,64 @@ +""" +MCP Tool: get_model_list +Query the list of available image generation models, with optional filtering by model architecture. +""" + +from .common import _load_yaml, _MODEL_LIST_PATH, _MODEL_DEFAULTS_PATH, _MODEL_ARCHITECTURES_PATH +from .error_schema import make_not_found_error + + +def handle_get_model_list(model_architecture: str = None) -> list | dict: + """Dynamically load the list of available image generation models from model_list.yaml.""" + model_list = _load_yaml(_MODEL_LIST_PATH) + model_defaults = _load_yaml(_MODEL_DEFAULTS_PATH) + arch_config = _load_yaml(_MODEL_ARCHITECTURES_PATH) + valid_architectures = set(arch_config.get("architectures", {}).keys()) + + if model_architecture and model_architecture not in valid_architectures: + return make_not_found_error("architecture", model_architecture) + + result = [] + checkpoints = model_list.get("Checkpoint", {}) + + for arch_name, arch_data in checkpoints.items(): + if model_architecture and arch_name != model_architecture: + continue + if not isinstance(arch_data, dict): + continue + + models = arch_data.get("models", []) + if not isinstance(models, list): + continue + + arch_defaults = model_defaults.get(arch_name, {}) + arch_level_defaults = arch_defaults.get("_defaults", {}) + + for model in models: + display_name = model.get("display_name", "") + category = model.get("category", None) + + model_specific_defaults = arch_defaults.get(display_name, {}) + + default_pos = model_specific_defaults.get( + "positive_prompt", + arch_level_defaults.get("positive_prompt", ""), + ) + default_neg = model_specific_defaults.get( + "negative_prompt", + arch_level_defaults.get("negative_prompt", ""), + ) + + entry = { + "name": display_name, + "model_architecture": arch_name, + } + if category: + entry["category"] = category + if default_pos: + entry["default_positive_prompt"] = default_pos + if default_neg: + entry["default_negative_prompt"] = default_neg + + result.append(entry) + + return result diff --git a/mcp_tools/get_task_list.py b/mcp_tools/get_task_list.py new file mode 100644 index 0000000000000000000000000000000000000000..df6b8f1591ba73ed835b1b1457018f6afdf5176d --- /dev/null +++ b/mcp_tools/get_task_list.py @@ -0,0 +1,11 @@ +""" +MCP Tool: get_task_list +Get a list of all supported image generation task types along with their required/optional parameter lists. +""" + +from .common import _TASK_DEFINITIONS + + +def handle_get_task_list() -> list: + """Get a list of all supported image generation task types along with their required/optional parameter lists.""" + return _TASK_DEFINITIONS diff --git a/mcp_tools/get_task_status.py b/mcp_tools/get_task_status.py new file mode 100644 index 0000000000000000000000000000000000000000..4e8898eadbb87fc008d63f842f093933397ce0c9 --- /dev/null +++ b/mcp_tools/get_task_status.py @@ -0,0 +1,22 @@ +""" +MCP Tool: get_task_status +Query the processing progress and final results of an async image generation task. +""" + +from .common import _get_task_snapshot +from .error_schema import make_validation_error, make_not_found_error + + +def handle_get_task_status(task_id: str) -> dict: + """Query the processing progress and final results of an async image generation task.""" + if not task_id: + return make_validation_error( + "Parameter 'task_id' is required.", + missing_fields=["task_id"], + ) + + task = _get_task_snapshot(task_id) + if task is None: + return make_not_found_error("task", task_id) + + return task diff --git a/mcp_tools/mcp_gradio_integration.py b/mcp_tools/mcp_gradio_integration.py new file mode 100644 index 0000000000000000000000000000000000000000..64ec620cbc726f85191482d38a539506828e04cf --- /dev/null +++ b/mcp_tools/mcp_gradio_integration.py @@ -0,0 +1,148 @@ +""" +MCP & Gradio Integration Module + +Provides: +1. register_high_level_mcp_apis: Expose the canonical API plus Fluxus-compatible aliases +2. cleanup_dependencies_api_names: Force cleanup of show_api attribute for non-high-level APIs in dependencies +3. patch_gradio_api_suppression: No-op implementation retained for backward compatibility +""" + +import json +import gradio as gr + +from .get_task_list import handle_get_task_list +from .get_model_architecture_list import handle_get_model_architecture_list +from .get_model_list import handle_get_model_list +from .get_feature_list import handle_get_feature_list +from .get_model_features import handle_get_model_features +from .run import handle_run +from .get_task_status import handle_get_task_status +from .get_chain_schema import handle_get_chain_schema + +HIGH_LEVEL_MCP_API_NAMES = { + "get_task_list", + "get_model_architecture_list", + "get_model_list", + "get_feature_list", + "get_model_features", + "run", + "get_task_status", + "run_imagegen", + "get_chain_schema", +} + + +def sanitize_keys(obj): + """Recursively ensure all dictionary keys are converted to str type to avoid Gradio 5 orjson TypeError: Dict key must be str.""" + if isinstance(obj, dict): + return {str(k): sanitize_keys(v) for k, v in obj.items()} + elif isinstance(obj, list): + return [sanitize_keys(x) for x in obj] + elif isinstance(obj, tuple): + return tuple(sanitize_keys(x) for x in obj) + return obj + + +def patch_gradio_api_suppression(): + """Retained for backward compatibility (no-op).""" + pass + + +def cleanup_dependencies_api_names(demo): + """ + Clean up residual auto-generated API names in demo.fns and demo.dependencies. + Force only the 7 high-level abstract MCP APIs to be exposed as public endpoints. + """ + for fn in demo.fns.values(): + api_name = getattr(fn, "api_name", None) + if api_name not in HIGH_LEVEL_MCP_API_NAMES: + fn.show_api = False + + deps = getattr(demo, "dependencies", None) + if deps is None and hasattr(demo, "config") and isinstance(demo.config, dict): + deps = demo.config.get("dependencies", []) + + if deps: + for dep in deps: + if isinstance(dep, dict): + api_name = dep.get("api_name") + if api_name not in HIGH_LEVEL_MCP_API_NAMES: + dep["show_api"] = False + + print("[MCP Protection] Cleaned up demo dependencies. Suppressed atomic API endpoints.") + + +def register_high_level_mcp_apis(demo): + """ + Explicitly register 7 high-level abstract MCP API endpoints on the Gradio demo using gr.api. + Using gr.api() never adds any visual UI components (such as Row, Textbox, Button, etc.), avoiding duplicate interface rendering. + """ + def get_task_list() -> list: + """[Recommended Discovery Flow Step 1] Get a list of all supported image generation task types (txt2img, img2img, inpaint, outpaint, hires_fix) along with their required and optional parameter lists. Recommended flow: get_task_list -> get_model_architecture_list -> get_model_list -> [Path 1: Call run directly (pass only required params) | Path 2: Call get_model_features to get official default hyperparams -> run].""" + return sanitize_keys(handle_get_task_list()) + + def get_model_architecture_list() -> list: + """[Recommended Discovery Flow Step 2] Get a list of all supported model architectures (e.g., SD1.5, SDXL, FLUX, etc.) along with their default resolutions. It is recommended to call this tool before get_model_list to obtain valid model_architecture parameters for precise model filtering.""" + return sanitize_keys(handle_get_model_architecture_list()) + + def get_model_list(model_architecture: str = "") -> list | dict: + """[Recommended Discovery Flow Step 3] Query the list of available image generation models. After obtaining models, choose one of two paths: 1. [Path 1 (Recommended - Minimal Mode)] Call run directly with only required parameters. Do NOT guess steps/cfg/sampler/scheduler from experience; the server will automatically apply the model's optimal default hyperparameters. 2. [Path 2 (Explicit Alignment Mode)] First call get_model_features to query the model's officially recommended hyperparameters, then pass them to run.""" + arch = model_architecture.strip() if model_architecture else None + return sanitize_keys(handle_get_model_list(arch)) + + def get_feature_list(feature_name: str = "", compact: bool = False) -> list | dict: + """Get supported advanced features. Empty input returns Fluxus-compatible full schemas; set compact=true for a token-saving summary. Pass feature_name for one or more complete schemas.""" + return sanitize_keys( + handle_get_feature_list( + feature_name.strip() if isinstance(feature_name, str) else feature_name, + include_schema_on_empty=not compact, + ) + ) + + def get_model_features(model: str = "") -> dict: + """Query metadata for the specified model, including supported task types, extended features, and official default inference parameters (steps, cfg, sampler, scheduler). This tool MUST be called when explicitly obtaining a model's optimal default hyperparameters (Path 2). Guessing or fabricating hyperparameters without querying is strictly prohibited.""" + return sanitize_keys(handle_get_model_features(model.strip())) + + def run(json_params: str = "{}") -> dict: + """[Recommended Discovery Flow Step 4] Unified image generation task execution interface. Supports txt2img, img2img, and other tasks with chainable extended features. [IMPORTANT PARAMETER RULES] Do NOT guess or fabricate inference hyperparameters such as steps, cfg, sampler, scheduler! Path 1 (Recommended): Pass only required parameters (task_type, model, prompt, width, height), leave optional hyperparams empty (server uses optimal defaults). Path 2: If explicit hyperparams are needed, you MUST first call get_model_features to obtain official defaults before passing them.""" + try: + if isinstance(json_params, dict): + params = json_params + else: + params = json.loads(json_params or "{}") + except Exception as e: + return {"error": {"code": "INVALID_JSON", "message": f"Failed to parse JSON params: {e}"}} + return sanitize_keys(handle_run(params)) + + def get_task_status(task_id: str = "") -> dict: + """Query the progress, status, and final generated results of an async image generation task.""" + return sanitize_keys(handle_get_task_status(task_id.strip())) + + def run_imagegen(json_params: str = "{}") -> dict: + """Backward-compatible alias for run, retained for Fluxus clients.""" + return run(json_params) + + def get_chain_schema(chain_type: str = "") -> dict: + """Backward-compatible Fluxus endpoint for one chain/injector schema.""" + return sanitize_keys(handle_get_chain_schema(chain_type.strip())) + + funcs = [ + get_task_list, + get_model_architecture_list, + get_model_list, + get_feature_list, + get_model_features, + run, + get_task_status, + run_imagegen, + get_chain_schema, + ] + + for func in funcs: + gr.api(func) + + for fn in demo.fns.values(): + if getattr(fn, "api_name", None) in HIGH_LEVEL_MCP_API_NAMES: + fn.show_api = True + + print("[MCP Integration] Registered 7 canonical MCP APIs and 2 Fluxus aliases.") diff --git a/mcp_tools/run.py b/mcp_tools/run.py new file mode 100644 index 0000000000000000000000000000000000000000..755f61633ded2c07f783091e1090398f3d1f4b61 --- /dev/null +++ b/mcp_tools/run.py @@ -0,0 +1,129 @@ +""" +MCP Tool: run +Unified image generation task submission and execution interface. +""" + +import time +import uuid +from core.task_scheduler import QueueFullError, submit_background +from core.runtime_config import CONFIG +from .common import ( + _load_yaml, + _MODEL_LIST_PATH, + _TASK_DEFINITIONS, + _TASKS_DB, + _TASKS_LOCK, + _get_task_snapshot, + _execute_imagegen_pipeline, +) +from .error_schema import make_error, make_validation_error, make_not_found_error + + +def handle_run(params: dict) -> dict: + """Unified image generation task execution interface.""" + if not isinstance(params, dict): + return make_validation_error("Request params must be an object.") + + missing = [] + for req_field in ["task_type", "model", "prompt"]: + if req_field not in params or not params[req_field]: + missing.append(req_field) + if missing: + return make_validation_error( + f"Missing required parameter(s): {', '.join(missing)}", + missing_fields=missing, + ) + + task_type = params["task_type"] + valid_tasks = [t["task_type"] for t in _TASK_DEFINITIONS] + if task_type not in valid_tasks: + return make_validation_error( + f"Invalid task_type '{task_type}'. Must be one of {valid_tasks}.", + invalid_fields={"task_type": f"Must be in {valid_tasks}"}, + ) + + model_list = _load_yaml(_MODEL_LIST_PATH) + checkpoints = model_list.get("Checkpoint", {}) + all_models = set() + for arch_name, arch_data in checkpoints.items(): + if isinstance(arch_data, dict): + for m in arch_data.get("models", []): + all_models.add(m.get("display_name")) + + if params["model"] not in all_models: + return make_not_found_error("model", params["model"]) + + task_requirements = { + "txt2img": ("width", "height"), + "img2img": ("image",), + "inpaint": ("image",), + "outpaint": ("image", "pad_left", "pad_right", "pad_top", "pad_bottom"), + "hires_fix": ("image", "upscale_by"), + } + missing_task_fields = [ + field + for field in task_requirements.get(task_type, ()) + if field not in params or params[field] is None or params[field] == "" + ] + if missing_task_fields: + return make_validation_error( + f"Missing required parameter(s) for {task_type}: {', '.join(missing_task_fields)}", + missing_fields=missing_task_fields, + ) + + try: + batch_size = int(params.get("batch_size", 1)) + except (TypeError, ValueError): + batch_size = 0 + if not 1 <= batch_size <= CONFIG.max_batch_size: + return make_validation_error( + f"batch_size must be between 1 and {CONFIG.max_batch_size}.", + invalid_fields={"batch_size": f"Expected 1..{CONFIG.max_batch_size}"}, + ) + + with _TASKS_LOCK: + if len(_TASKS_DB) >= CONFIG.mcp_task_retention: + finished = sorted( + ( + (old_task_id, task) + for old_task_id, task in _TASKS_DB.items() + if task.get("status") in {"completed", "failed"} + ), + key=lambda pair: pair[1].get("completed_at", pair[1].get("failed_at", 0)), + ) + remove_count = max(1, len(_TASKS_DB) - CONFIG.mcp_task_retention + 1) + for old_task_id, _ in finished[:remove_count]: + _TASKS_DB.pop(old_task_id, None) + if len(_TASKS_DB) >= CONFIG.mcp_task_retention: + return make_error( + "QUEUE_FULL", + "任务记录已满且当前任务均未结束,请稍后再试。", + ) + + task_id = f"img_task_{uuid.uuid4().hex[:10]}" + created_at = int(time.time()) + _TASKS_DB[task_id] = { + "task_id": task_id, + "status": "queued", + "progress": 0, + "created_at": created_at, + } + + async_exec = params.get("async_execution", False) + + if async_exec: + try: + submit_background(_execute_imagegen_pipeline, task_id, params) + except QueueFullError as exc: + with _TASKS_LOCK: + _TASKS_DB.pop(task_id, None) + return make_error("QUEUE_FULL", str(exc)) + return { + "status": "queued", + "task_id": task_id, + "poll_interval_ms": 2000, + "message": "Task queued successfully. Poll get_task_status for results.", + } + else: + _execute_imagegen_pipeline(task_id, params) + return _get_task_snapshot(task_id) diff --git a/mcp_tools/tool_handlers.py b/mcp_tools/tool_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..04ed9d71793fdfd80c79bb5d22e84d905e48f2a4 --- /dev/null +++ b/mcp_tools/tool_handlers.py @@ -0,0 +1,30 @@ +""" +MCP Tool Handlers — Backward-compatible aggregation entry point. +Core logic has been split into individual files (get_*.py and run.py). +""" + +from .get_task_list import handle_get_task_list +from .get_model_architecture_list import handle_get_model_architecture_list +from .get_model_list import handle_get_model_list +from .get_feature_list import handle_get_feature_list +from .get_model_features import handle_get_model_features +from .run import handle_run +from .get_task_status import handle_get_task_status +from .get_chain_schema import handle_get_chain_schema +from .common import ( + _TASK_DEFINITIONS, + _TASKS_DB, + _load_yaml, + _execute_imagegen_pipeline, +) + +__all__ = [ + "handle_get_task_list", + "handle_get_model_architecture_list", + "handle_get_model_list", + "handle_get_feature_list", + "handle_get_model_features", + "handle_run", + "handle_get_task_status", + "handle_get_chain_schema", +] diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..f6161fd718f1986365b02eb8274ecb3fba859855 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,48 @@ +comfyui-frontend-package==1.48.7 +comfyui-workflow-templates==0.11.37 +comfyui-embedded-docs==0.5.9 +gradio[mcp]==5.50.0 +torch +torchsde +torchvision +torchaudio +numpy>=1.25.0 +einops +transformers>=4.50.3 +tokenizers>=0.13.3 +sentencepiece +safetensors>=0.4.2 +aiohttp>=3.11.8 +yarl>=1.18.0 +pyyaml +Pillow +scipy +tqdm +psutil +alembic +SQLAlchemy>=2.0.0 +filelock +av>=16.0.0 +comfy-kitchen==0.2.28 +comfy-aimdo==0.4.13 +requests +simpleeval>=1.0.0 +blake3 + +#non essential dependencies: +kornia>=0.7.1 +spandrel +pydantic~=2.0 +pydantic-settings~=2.0 +PyOpenGL>=3.1.8 +comfy-angle + + +diffusers +protobuf +insightface +onnxruntime-gpu==1.28.0 +huggingface-hub +imageio +spaces +sageattention @ https://huggingface.co/RioShiina/Sage-Attention-ZeroGPU-Space-Build/resolve/65ab933ca7fdcf996065697e69cbba2ce7353557/sageattention-2.2.0-cp312-cp312-linux_x86_64.whl ; platform_system == "Linux" and platform_machine == "x86_64" and python_version >= "3.12" and python_version < "3.13" diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..49f39b5946d1949bec4a182fc44c44df55865b85 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +"""ImageGen Studio regression tests.""" diff --git a/tests/test_execution_plan.py b/tests/test_execution_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..650f8129b03fcbb8b9f3010e5f6a692d42d6a376 --- /dev/null +++ b/tests/test_execution_plan.py @@ -0,0 +1,159 @@ +from __future__ import annotations + +import threading +import unittest + +from PIL import Image + +from core.execution_plan import ( + MODE_MODEL_PK, + MODE_MULTI_INDEPENDENT, + MODE_MULTI_MODEL_GRID, + MODE_MULTI_REFERENCE, + ExecutionPlanError, + PlannedGeneration, + build_execution_plan, + execute_generation_plan, +) + + +def base_inputs(**overrides): + values = { + "task_type": "txt2img", + "model_display_name": "Krea-2-Turbo", + "positive_prompt": "一只猫", + "negative_prompt": "", + "seed": -1, + "batch_size": 1, + "num_inference_steps": 13, + "guidance_scale": 2.5, + "sampler": "euler", + "scheduler": "simple", + "width": 1024, + "height": 1024, + } + values.update(overrides) + return values + + +class ExecutionPlanTests(unittest.TestCase): + def test_pk_resolves_one_seed_and_marks_only_the_model_boundary(self): + plan = build_execution_plan( + base_inputs(lora_data=["Civitai", "123", 1.0, None]), + mode=MODE_MODEL_PK, + extra_models=["Krea-2-Raw"], + use_model_defaults=True, + ) + self.assertEqual(len(plan), 2) + self.assertEqual(plan[0].inputs["seed"], plan[1].inputs["seed"]) + self.assertGreaterEqual(plan[0].inputs["seed"], 0) + self.assertEqual(plan[0].inputs["num_inference_steps"], 8) + self.assertEqual(plan[1].inputs["num_inference_steps"], 52) + self.assertTrue(plan[0].inputs["_release_models_after_run"]) + self.assertNotIn("_release_models_after_run", plan[1].inputs) + self.assertEqual(plan[0].inputs["lora_data"], []) + self.assertEqual(plan[1].inputs["lora_data"], []) + + def test_independent_images_keep_user_sampling_values(self): + images = [Image.new("RGB", (32, 32)), Image.new("RGB", (48, 32))] + plan = build_execution_plan( + base_inputs(task_type="img2img"), + mode=MODE_MULTI_INDEPENDENT, + images=images, + use_model_defaults=True, + ) + self.assertEqual(len(plan), 2) + self.assertEqual([item.inputs["img2img_image"] for item in plan], images) + self.assertTrue(all(item.inputs["num_inference_steps"] == 13 for item in plan)) + + def test_image_model_grid_groups_inputs_by_model(self): + images = [Image.new("RGB", (32, 32)), Image.new("RGB", (48, 32))] + plan = build_execution_plan( + base_inputs(task_type="img2img"), + mode=MODE_MULTI_MODEL_GRID, + extra_models=["Krea-2-Raw"], + images=images, + ) + self.assertEqual( + [item.inputs["model_display_name"] for item in plan], + ["Krea-2-Turbo", "Krea-2-Turbo", "Krea-2-Raw", "Krea-2-Raw"], + ) + self.assertNotIn("_release_models_after_run", plan[0].inputs) + self.assertTrue(plan[1].inputs["_release_models_after_run"]) + + def test_reference_fusion_uses_edit_checkpoint_chain(self): + images = [Image.new("RGB", (32, 32)), Image.new("RGB", (32, 32))] + edit_model = "lightx2v/Qwen-Image-Edit-2511-Lightning" + plan = build_execution_plan( + base_inputs(model_display_name=edit_model), + mode=MODE_MULTI_REFERENCE, + images=images, + ) + self.assertEqual(plan[0].inputs["qwen_image_edit_data"], images) + + with self.assertRaisesRegex(ExecutionPlanError, "编辑/多模态模型"): + build_execution_plan( + base_inputs( + model_display_name="lightx2v/Qwen-Image-2512-Lightning" + ), + mode=MODE_MULTI_REFERENCE, + images=images, + ) + + def test_reference_fusion_is_not_img2img(self): + with self.assertRaisesRegex(ExecutionPlanError, "文生图"): + build_execution_plan( + base_inputs(task_type="img2img"), + mode=MODE_MULTI_REFERENCE, + images=[Image.new("RGB", (32, 32))], + ) + + def test_executor_keeps_partial_results_and_failure_context(self): + plan = [ + PlannedGeneration({"id": 1}, "模型一"), + PlannedGeneration({"id": 2}, "模型二"), + ] + + def generate(inputs, _progress): + if inputs["id"] == 2: + raise RuntimeError("显存不足") + return ["one.png"] + + gallery, summary = execute_generation_plan(plan, generate) + self.assertEqual(gallery, [("one.png", "模型一")]) + self.assertIn("模型二:显存不足", summary) + + def test_executor_stops_before_next_case_after_cancel(self): + cancellation = threading.Event() + cancellation.set() + with self.assertRaisesRegex(ExecutionPlanError, "已取消"): + execute_generation_plan( + [PlannedGeneration({}, "任务")], + lambda *_: ["unexpected.png"], + cancel_event=cancellation, + ) + + def test_cancel_after_success_keeps_partial_gallery(self): + cancellation = threading.Event() + called = [] + + def generate(inputs, _progress): + called.append(inputs["id"]) + cancellation.set() + return ["kept.png"] + + gallery, summary = execute_generation_plan( + [ + PlannedGeneration({"id": 1}, "任务一"), + PlannedGeneration({"id": 2}, "任务二"), + ], + generate, + cancel_event=cancellation, + ) + self.assertEqual(called, [1]) + self.assertEqual(gallery, [("kept.png", "任务一")]) + self.assertIn("已保留成功结果", summary) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_mcp_validation.py b/tests/test_mcp_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..e8f32cc2bc53ff6f474d0869ad438189d6a5c64c --- /dev/null +++ b/tests/test_mcp_validation.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +import unittest + +from PIL import Image + +from mcp_tools.common import _parse_image_param, _validate_public_image_url +from mcp_tools.get_chain_schema import handle_get_chain_schema +from mcp_tools.get_feature_list import handle_get_feature_list +from mcp_tools.get_model_features import handle_get_model_features +from mcp_tools.run import handle_run + + +class McpValidationTests(unittest.TestCase): + def test_requires_common_fields(self): + result = handle_run({}) + self.assertEqual(result["error"]["code"], "INVALID_PARAMS") + + def test_requires_task_specific_fields_before_execution(self): + result = handle_run( + { + "task_type": "txt2img", + "model": "Krea-2-Turbo", + "prompt": "测试", + } + ) + self.assertEqual(result["error"]["code"], "INVALID_PARAMS") + self.assertEqual(set(result["error"]["details"]["missing_fields"]), {"width", "height"}) + + def test_batch_limit_is_enforced(self): + result = handle_run( + { + "task_type": "txt2img", + "model": "Krea-2-Turbo", + "prompt": "测试", + "width": 1024, + "height": 1024, + "batch_size": 999, + } + ) + self.assertEqual(result["error"]["code"], "INVALID_PARAMS") + + def test_private_image_urls_are_rejected(self): + with self.assertRaises(ValueError): + _validate_public_image_url("http://127.0.0.1/private.png") + + def test_decoded_image_pixel_budget_is_enforced(self): + with self.assertRaisesRegex(ValueError, "maximum"): + _parse_image_param(Image.new("RGB", (3000, 2000))) + + def test_fluxus_chain_schema_contract(self): + missing = handle_get_chain_schema("") + self.assertEqual(missing["error"]["code"], "INVALID_PARAMS") + self.assertEqual( + missing["error"]["details"]["missing_fields"], ["chain_type"] + ) + self.assertEqual(handle_get_chain_schema("lora")["feature_name"], "lora") + self.assertEqual( + handle_get_chain_schema("style")["canonical_feature_name"], "flux1_style" + ) + + def test_fluxus_feature_discovery_can_return_full_schemas(self): + full = handle_get_feature_list("", include_schema_on_empty=True) + compact = handle_get_feature_list("") + self.assertTrue(full) + self.assertTrue(all("parameters_schema" in item for item in full)) + self.assertTrue(all("parameters_schema" not in item for item in compact)) + + def test_checkpoint_level_edit_capability_is_not_overreported(self): + regular = handle_get_model_features( + "lightx2v/Qwen-Image-2512-Lightning" + ) + editing = handle_get_model_features( + "lightx2v/Qwen-Image-Edit-2511-Lightning" + ) + self.assertNotIn("qwen_image_edit", regular["supported_features"]) + self.assertIn("qwen_image_edit", editing["supported_features"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_runtime_and_registry.py b/tests/test_runtime_and_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..29bb5aff3ad833e9dd178dfaf823353f64c4dda9 --- /dev/null +++ b/tests/test_runtime_and_registry.py @@ -0,0 +1,186 @@ +from __future__ import annotations + +import threading +import time +import unittest +from pathlib import Path + +import yaml + +from core.runtime_config import CONFIG, estimate_gpu_duration +from core.settings import CHECKPOINT_DIR, INPUT_DIR, OUTPUT_DIR +from core.task_scheduler import ( + QueueFullError, + TaskCancelledError, + generation_guard, + generation_slot, + submit_background, +) + + +ROOT = Path(__file__).resolve().parents[1] + + +class RuntimeConfigTests(unittest.TestCase): + def test_duration_estimation_is_bounded(self): + self.assertEqual(estimate_gpu_duration({"zero_gpu_duration": 999}), 120) + self.assertEqual(estimate_gpu_duration({"zero_gpu_duration": 1}), 30) + self.assertEqual( + estimate_gpu_duration( + { + "model_display_name": "example-lightning", + "num_inference_steps": 4, + "batch_size": 1, + "width": 1024, + "height": 1024, + } + ), + 45, + ) + self.assertEqual( + estimate_gpu_duration( + { + "model_display_name": "large-model", + "num_inference_steps": 40, + "batch_size": 3, + "width": 2048, + "height": 2048, + } + ), + 120, + ) + + def test_generation_slots_respect_configured_limit(self): + active = 0 + maximum = 0 + state_lock = threading.Lock() + + def worker(): + nonlocal active, maximum + with generation_slot(): + with state_lock: + active += 1 + maximum = max(maximum, active) + time.sleep(0.02) + with state_lock: + active -= 1 + + threads = [threading.Thread(target=worker) for _ in range(CONFIG.gpu_concurrency + 2)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + self.assertLessEqual(maximum, CONFIG.gpu_concurrency) + + def test_cancelled_job_stops_before_guarded_execution(self): + reached_function = False + + @generation_guard + def guarded(ui_inputs): + nonlocal reached_function + reached_function = True + + cancel_event = threading.Event() + cancel_event.set() + with self.assertRaises(TaskCancelledError): + guarded({"_cancel_event": cancel_event}) + self.assertFalse(reached_function) + + def test_waiting_cancelled_job_leaves_gate_before_gpu_is_free(self): + holder_started = threading.Event() + release_holder = threading.Event() + cancellation = threading.Event() + errors = [] + + def holder(): + with generation_slot(): + holder_started.set() + release_holder.wait(2) + + @generation_guard + def waiting_job(ui_inputs): + raise AssertionError("cancelled job must not execute") + + def wait_then_cancel(): + try: + waiting_job({"_cancel_event": cancellation}) + except BaseException as exc: + errors.append(exc) + + holder_thread = threading.Thread(target=holder) + holder_thread.start() + self.assertTrue(holder_started.wait(1)) + + waiting_thread = threading.Thread(target=wait_then_cancel) + waiting_thread.start() + cancellation.set() + waiting_thread.join(1) + + self.assertFalse(waiting_thread.is_alive()) + self.assertEqual(len(errors), 1) + self.assertIsInstance(errors[0], TaskCancelledError) + + release_holder.set() + holder_thread.join(1) + self.assertFalse(holder_thread.is_alive()) + + def test_mcp_pending_queue_is_bounded(self): + release = threading.Event() + futures = [ + submit_background(lambda: release.wait(2)) + for _ in range(CONFIG.mcp_max_pending) + ] + with self.assertRaises(QueueFullError): + submit_background(lambda: None) + release.set() + for future in futures: + self.assertTrue(future.result(timeout=3)) + + +class RegistryTests(unittest.TestCase): + def test_runtime_directories_are_project_absolute(self): + for configured in (CHECKPOINT_DIR, INPUT_DIR, OUTPUT_DIR): + path = Path(configured) + self.assertTrue(path.is_absolute()) + self.assertTrue(path.is_relative_to(ROOT)) + + def test_quick_presets_exist(self): + registry = yaml.safe_load((ROOT / "yaml" / "model_list.yaml").read_text("utf-8")) + names = { + model["display_name"] + for architecture in registry["Checkpoint"].values() + for model in architecture.get("models", []) + } + expected = { + "Krea-2-Turbo", + "lightx2v/Qwen-Image-2512-Lightning", + "circlestone-labs/Anima-Turbo-v1.0", + "lightx2v/Qwen-Image-Edit-2511-Lightning", + "CagliostroLab/Animagine XL 4.0", + } + self.assertTrue(expected.issubset(names)) + + def test_vendor_revisions_are_full_commits(self): + lock = yaml.safe_load((ROOT / "vendor.lock.yaml").read_text("utf-8")) + entries = [lock["comfyui"], *lock["custom_nodes"].values()] + for entry in entries: + revision = entry["revision"] + self.assertEqual(len(revision), 40) + int(revision, 16) + + def test_concurrency_regressions_are_absent(self): + mcp_run = (ROOT / "mcp_tools" / "run.py").read_text("utf-8") + input_processor = ( + ROOT / "core" / "pipelines" / "pipeline_input_processor.py" + ).read_text("utf-8") + studio = (ROOT / "ui" / "shared" / "studio_ui.py").read_text("utf-8") + requirements = (ROOT / "requirements.txt").read_text("utf-8") + self.assertNotIn("threading.Thread", mcp_run) + self.assertIn("uuid.uuid4().hex", input_processor) + self.assertIn('"_task_prefixes": [(prefix, None)]', studio) + self.assertIn("onnxruntime-gpu==", requirements) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_ui_smoke.py b/tests/test_ui_smoke.py new file mode 100644 index 0000000000000000000000000000000000000000..8d9d504f072600b2d4deb2001575bcd5fc1d63cd --- /dev/null +++ b/tests/test_ui_smoke.py @@ -0,0 +1,90 @@ +from __future__ import annotations + +import os +import sys +import types +import unittest +from unittest import mock + +os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "False") +os.environ.setdefault("HF_HUB_OFFLINE", "1") + +try: + import gradio +except ImportError: + gradio = None + + +@unittest.skipIf(gradio is None, "Gradio is not installed") +class UnifiedUiSmokeTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + torch_stub = types.ModuleType("torch") + torch_stub.Tensor = object + torch_stub.cuda = types.SimpleNamespace( + empty_cache=lambda: None, is_available=lambda: False + ) + sys.modules.setdefault("torch", torch_stub) + + nodes_stub = types.ModuleType("comfy_integration.nodes") + nodes_stub.SAMPLER_CHOICES = ["euler", "dpmpp_2m_sde_gpu"] + nodes_stub.SCHEDULER_CHOICES = ["simple", "normal", "karras"] + sys.modules["comfy_integration.nodes"] = nodes_stub + + generation_stub = types.ModuleType("core.generation_logic") + generation_stub.generate_image_wrapper = lambda inputs, progress=None: [] + sys.modules["core.generation_logic"] = generation_stub + + def test_builds_one_workspace_and_only_high_level_public_apis(self): + from ui.events import attach_event_handlers + from ui.layout import build_ui + + app = build_ui(attach_event_handlers) + config = app.get_config_file() + self.assertLess(len(config.get("components", [])), 1000) + self.assertLess(len(config.get("dependencies", [])), 150) + public_names = { + dependency.get("api_name") + for dependency in config.get("dependencies", []) + if dependency.get("show_api") and dependency.get("api_name") + } + self.assertEqual( + public_names, + { + "get_task_list", + "get_model_architecture_list", + "get_model_list", + "get_feature_list", + "get_model_features", + "run", + "get_task_status", + "run_imagegen", + "get_chain_schema", + }, + ) + + def test_reference_budget_rejects_oversized_advanced_image(self): + from PIL import Image + + from core.pipelines.pipeline_input_processor import ( + _validate_reference_image_budget, + ) + + with self.assertRaises(gradio.Error): + _validate_reference_image_budget( + {"reference_latent_data": [Image.new("1", (3000, 2000))]} + ) + + def test_model_download_preflight_preserves_disk_reserve(self): + from imagegen_utils.app_utils import _assert_download_space + + usage = types.SimpleNamespace(total=10, used=9, free=1) + with ( + mock.patch("shutil.disk_usage", return_value=usage), + self.assertRaises(gradio.Error), + ): + _assert_download_space(100, "model.safetensors", "/tmp") + + +if __name__ == "__main__": + unittest.main() diff --git a/ui/__init__.py b/ui/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/ui/events/__init__.py b/ui/events/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..844d96b263501e82c0e4f35f5661577836d456ed --- /dev/null +++ b/ui/events/__init__.py @@ -0,0 +1,12 @@ +from .main import attach_event_handlers +from .config_loaders import ( + load_controlnet_config, + get_cn_defaults, + load_anima_controlnet_lllite_config, + get_anima_cn_defaults, + load_diffsynth_controlnet_config, + get_diffsynth_cn_defaults, + load_krea2_controlnet_config, + get_krea2_cn_defaults, + load_ipadapter_config +) diff --git a/ui/events/chain_handlers.py b/ui/events/chain_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..7ed3a5b9b25f19846fe11288455107b6f7665e9a --- /dev/null +++ b/ui/events/chain_handlers.py @@ -0,0 +1,1008 @@ +import gradio as gr +from core.settings import VAE_DIR, LORA_DIR, EMBEDDING_DIR, ARCHITECTURES_CONFIG +from imagegen_utils.app_utils import save_uploaded_file_with_hash +from ui.shared.ui_components import ( + MAX_CONTROLNETS, + MAX_IPADAPTERS, + MAX_EMBEDDINGS, + MAX_CONDITIONINGS, + MAX_LORAS +) +from .config_loaders import ( + load_controlnet_config, + load_anima_controlnet_lllite_config, + load_diffsynth_controlnet_config, + load_krea2_controlnet_config, + load_ipadapter_config +) + +def on_vae_upload(file_obj): + if not file_obj: + return gr.update(), gr.update(), None + + hashed_filename = save_uploaded_file_with_hash(file_obj, VAE_DIR) + return hashed_filename, "File", file_obj + + +def on_lora_upload(file_obj): + if not file_obj: + return gr.update(), gr.update() + + hashed_filename = save_uploaded_file_with_hash(file_obj, LORA_DIR) + return hashed_filename, "File" + + +def on_embedding_upload(file_obj): + if not file_obj: + return gr.update(), gr.update(), None + + hashed_filename = save_uploaded_file_with_hash(file_obj, EMBEDDING_DIR) + return hashed_filename, "File", file_obj + + +def create_lora_event_handlers(prefix, ui_components): + lora_rows = ui_components.get(f'lora_rows_{prefix}') + if not lora_rows: return + lora_ids = ui_components[f'lora_ids_{prefix}'] + lora_scales = ui_components[f'lora_scales_{prefix}'] + lora_uploads = ui_components[f'lora_uploads_{prefix}'] + lora_sources = ui_components[f'lora_sources_{prefix}'] + count_state = ui_components[f'lora_count_state_{prefix}'] + add_button = ui_components[f'add_lora_button_{prefix}'] + del_button = ui_components[f'delete_lora_button_{prefix}'] + + for i in range(MAX_LORAS): + lora_uploads[i].upload( + fn=on_lora_upload, + inputs=[lora_uploads[i]], + outputs=[lora_ids[i], lora_sources[i]], + show_progress=True + ) + + def add_lora_row(c): + updates = {} + if c < MAX_LORAS: + c += 1 + updates[lora_rows[c - 1]] = gr.update(visible=True) + + updates[count_state] = c + updates[add_button] = gr.update(visible=c < MAX_LORAS) + updates[del_button] = gr.update(visible=c > 1) + return updates + + def del_lora_row(c): + updates = {} + if c > 1: + updates[lora_rows[c - 1]] = gr.update(visible=False) + updates[lora_ids[c - 1]] = "" + updates[lora_scales[c - 1]] = 0.0 + updates[lora_uploads[c - 1]] = None + c -= 1 + + updates[count_state] = c + updates[add_button] = gr.update(visible=True) + updates[del_button] = gr.update(visible=c > 1) + return updates + + add_outputs = [count_state, add_button, del_button] + lora_rows + del_outputs = [count_state, add_button, del_button] + lora_rows + lora_ids + lora_scales + lora_uploads + + add_button.click(add_lora_row, [count_state], add_outputs, show_progress=False) + del_button.click(del_lora_row, [count_state], del_outputs, show_progress=False) + + +def create_controlnet_event_handlers(prefix, ui_components): + cn_rows = ui_components.get(f'controlnet_rows_{prefix}') + if not cn_rows: return + cn_types = ui_components[f'controlnet_types_{prefix}'] + cn_series = ui_components[f'controlnet_series_{prefix}'] + cn_filepaths = ui_components[f'controlnet_filepaths_{prefix}'] + cn_images = ui_components[f'controlnet_images_{prefix}'] + cn_strengths = ui_components[f'controlnet_strengths_{prefix}'] + + count_state = ui_components[f'controlnet_count_state_{prefix}'] + add_button = ui_components[f'add_controlnet_button_{prefix}'] + del_button = ui_components[f'delete_controlnet_button_{prefix}'] + accordion = ui_components[f'controlnet_accordion_{prefix}'] + + base_model_comp = ui_components.get(f'base_model_{prefix}') + actual_arch_comp = base_model_comp if base_model_comp else gr.State("SDXL") + + def add_cn_row(c): + c += 1 + updates = { + count_state: c, + cn_rows[c-1]: gr.update(visible=True), + add_button: gr.update(visible=c < MAX_CONTROLNETS), + del_button: gr.update(visible=True) + } + return updates + + def del_cn_row(c): + c -= 1 + updates = { + count_state: c, + cn_rows[c]: gr.update(visible=False), + cn_images[c]: None, + cn_strengths[c]: 1.0, + add_button: gr.update(visible=True), + del_button: gr.update(visible=c > 0) + } + return updates + + add_outputs = [count_state, add_button, del_button] + cn_rows + del_outputs = [count_state, add_button, del_button] + cn_rows + cn_images + cn_strengths + add_button.click(fn=add_cn_row, inputs=[count_state], outputs=add_outputs, show_progress=False) + del_button.click(fn=del_cn_row, inputs=[count_state], outputs=del_outputs, show_progress=False) + + def on_cn_type_change(selected_type, model_name): + from core.settings import MODEL_TYPE_MAP + m_type = MODEL_TYPE_MAP.get(model_name, "SDXL") if model_name else "SDXL" + cn_full_config = load_controlnet_config() + + architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {}) + controlnet_key = architectures_dict.get(m_type, {}).get("controlnet_key", m_type) + + cn_config = cn_full_config.get(controlnet_key, []) + series_choices = [] + if selected_type: + series_choices = sorted(list(set( + model.get("Series", "Default") for model in cn_config + if selected_type in model.get("Type", []) + ))) + default_series = series_choices[0] if series_choices else None + filepath = "None" + if default_series: + for model in cn_config: + if model.get("Series") == default_series and selected_type in model.get("Type", []): + filepath = model.get("Filepath") + break + return gr.update(choices=series_choices, value=default_series), filepath + + def on_cn_series_change(selected_series, selected_type, model_name): + from core.settings import MODEL_TYPE_MAP + m_type = MODEL_TYPE_MAP.get(model_name, "SDXL") if model_name else "SDXL" + cn_full_config = load_controlnet_config() + + architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {}) + controlnet_key = architectures_dict.get(m_type, {}).get("controlnet_key", m_type) + + cn_config = cn_full_config.get(controlnet_key, []) + filepath = "None" + if selected_series and selected_type: + for model in cn_config: + if model.get("Series") == selected_series and selected_type in model.get("Type", []): + filepath = model.get("Filepath") + break + return filepath + + for i in range(MAX_CONTROLNETS): + cn_types[i].change( + fn=on_cn_type_change, + inputs=[cn_types[i], actual_arch_comp], + outputs=[cn_series[i], cn_filepaths[i]], + show_progress=False + ) + cn_series[i].change( + fn=on_cn_series_change, + inputs=[cn_series[i], cn_types[i], actual_arch_comp], + outputs=[cn_filepaths[i]], + show_progress=False + ) + + def on_accordion_expand(*images): + return [gr.update() for _ in images] + + accordion.expand( + fn=on_accordion_expand, + inputs=cn_images, + outputs=cn_images, + show_progress=False + ) + + +def create_krea2_controlnet_event_handlers(prefix, ui_components): + cn_rows = ui_components.get(f'krea2_controlnet_rows_{prefix}') + if not cn_rows: return + cn_types = ui_components[f'krea2_controlnet_types_{prefix}'] + cn_series = ui_components[f'krea2_controlnet_series_{prefix}'] + cn_filepaths = ui_components[f'krea2_controlnet_filepaths_{prefix}'] + cn_images = ui_components[f'krea2_controlnet_images_{prefix}'] + cn_strengths = ui_components[f'krea2_controlnet_strengths_{prefix}'] + + count_state = ui_components[f'krea2_controlnet_count_state_{prefix}'] + add_button = ui_components[f'add_krea2_controlnet_button_{prefix}'] + del_button = ui_components[f'delete_krea2_controlnet_button_{prefix}'] + accordion = ui_components[f'krea2_controlnet_accordion_{prefix}'] + + def add_cn_row(c): + c += 1 + updates = { + count_state: c, + cn_rows[c-1]: gr.update(visible=True), + add_button: gr.update(visible=c < MAX_CONTROLNETS), + del_button: gr.update(visible=True) + } + return updates + + def del_cn_row(c): + c -= 1 + updates = { + count_state: c, + cn_rows[c]: gr.update(visible=False), + cn_images[c]: None, + cn_strengths[c]: 1.0, + add_button: gr.update(visible=True), + del_button: gr.update(visible=c > 0) + } + return updates + + add_outputs = [count_state, add_button, del_button] + cn_rows + del_outputs = [count_state, add_button, del_button] + cn_rows + cn_images + cn_strengths + add_button.click(fn=add_cn_row, inputs=[count_state], outputs=add_outputs, show_progress=False) + del_button.click(fn=del_cn_row, inputs=[count_state], outputs=del_outputs, show_progress=False) + + def on_cn_type_change(selected_type): + cn_config = load_krea2_controlnet_config() + series_choices = [] + if selected_type: + series_choices = sorted(list(set( + model.get("Series", "Default") for model in cn_config + if selected_type in model.get("Type", []) + ))) + default_series = series_choices[0] if series_choices else None + filepath = "None" + if default_series: + for model in cn_config: + if model.get("Series") == default_series and selected_type in model.get("Type", []): + filepath = model.get("Filepath") + break + return gr.update(choices=series_choices, value=default_series), filepath + + def on_cn_series_change(selected_series, selected_type): + cn_config = load_krea2_controlnet_config() + filepath = "None" + if selected_series and selected_type: + for model in cn_config: + if model.get("Series") == selected_series and selected_type in model.get("Type", []): + filepath = model.get("Filepath") + break + return filepath + + for i in range(MAX_CONTROLNETS): + cn_types[i].change( + fn=on_cn_type_change, + inputs=[cn_types[i]], + outputs=[cn_series[i], cn_filepaths[i]], + show_progress=False + ) + cn_series[i].change( + fn=on_cn_series_change, + inputs=[cn_series[i], cn_types[i]], + outputs=[cn_filepaths[i]], + show_progress=False + ) + + def on_accordion_expand(*images): + return [gr.update() for _ in images] + + accordion.expand( + fn=on_accordion_expand, + inputs=cn_images, + outputs=cn_images, + show_progress=False + ) + + +def create_anima_controlnet_lllite_event_handlers(prefix, ui_components): + cn_rows = ui_components.get(f'anima_controlnet_lllite_rows_{prefix}') + if not cn_rows: return + cn_types = ui_components[f'anima_controlnet_lllite_types_{prefix}'] + cn_series = ui_components[f'anima_controlnet_lllite_series_{prefix}'] + cn_filepaths = ui_components[f'anima_controlnet_lllite_filepaths_{prefix}'] + cn_images = ui_components[f'anima_controlnet_lllite_images_{prefix}'] + cn_strengths = ui_components[f'anima_controlnet_lllite_strengths_{prefix}'] + + count_state = ui_components[f'anima_controlnet_lllite_count_state_{prefix}'] + add_button = ui_components[f'add_anima_controlnet_lllite_button_{prefix}'] + del_button = ui_components[f'delete_anima_controlnet_lllite_button_{prefix}'] + accordion = ui_components[f'anima_controlnet_lllite_accordion_{prefix}'] + + def add_cn_row(c): + c += 1 + updates = { + count_state: c, + cn_rows[c-1]: gr.update(visible=True), + add_button: gr.update(visible=c < MAX_CONTROLNETS), + del_button: gr.update(visible=True) + } + return updates + + def del_cn_row(c): + c -= 1 + updates = { + count_state: c, + cn_rows[c]: gr.update(visible=False), + cn_images[c]: None, + cn_strengths[c]: 1.0, + add_button: gr.update(visible=True), + del_button: gr.update(visible=c > 0) + } + return updates + + add_outputs = [count_state, add_button, del_button] + cn_rows + del_outputs = [count_state, add_button, del_button] + cn_rows + cn_images + cn_strengths + add_button.click(fn=add_cn_row, inputs=[count_state], outputs=add_outputs, show_progress=False) + del_button.click(fn=del_cn_row, inputs=[count_state], outputs=del_outputs, show_progress=False) + + def on_cn_type_change(selected_type): + cn_config = load_anima_controlnet_lllite_config() + series_choices = [] + if selected_type: + series_choices = sorted(list(set( + model.get("Series", "Default") for model in cn_config + if selected_type in model.get("Type", []) + ))) + default_series = series_choices[0] if series_choices else None + filepath = "None" + if default_series: + for model in cn_config: + if model.get("Series") == default_series and selected_type in model.get("Type", []): + filepath = model.get("Filepath") + break + return gr.update(choices=series_choices, value=default_series), filepath + + def on_cn_series_change(selected_series, selected_type): + cn_config = load_anima_controlnet_lllite_config() + filepath = "None" + if selected_series and selected_type: + for model in cn_config: + if model.get("Series") == selected_series and selected_type in model.get("Type", []): + filepath = model.get("Filepath") + break + return filepath + + for i in range(MAX_CONTROLNETS): + cn_types[i].change( + fn=on_cn_type_change, + inputs=[cn_types[i]], + outputs=[cn_series[i], cn_filepaths[i]], + show_progress=False + ) + cn_series[i].change( + fn=on_cn_series_change, + inputs=[cn_series[i], cn_types[i]], + outputs=[cn_filepaths[i]], + show_progress=False + ) + + def on_accordion_expand(*images): + return [gr.update() for _ in images] + + accordion.expand( + fn=on_accordion_expand, + inputs=cn_images, + outputs=cn_images, + show_progress=False + ) + + +def create_diffsynth_controlnet_event_handlers(prefix, ui_components): + cn_rows = ui_components.get(f'diffsynth_controlnet_rows_{prefix}') + if not cn_rows: return + cn_types = ui_components[f'diffsynth_controlnet_types_{prefix}'] + cn_series = ui_components[f'diffsynth_controlnet_series_{prefix}'] + cn_filepaths = ui_components[f'diffsynth_controlnet_filepaths_{prefix}'] + cn_images = ui_components[f'diffsynth_controlnet_images_{prefix}'] + cn_strengths = ui_components[f'diffsynth_controlnet_strengths_{prefix}'] + + count_state = ui_components[f'diffsynth_controlnet_count_state_{prefix}'] + add_button = ui_components[f'add_diffsynth_controlnet_button_{prefix}'] + del_button = ui_components[f'delete_diffsynth_controlnet_button_{prefix}'] + accordion = ui_components[f'diffsynth_controlnet_accordion_{prefix}'] + + base_model_comp = ui_components.get(f'base_model_{prefix}') + actual_arch_comp = base_model_comp if base_model_comp else gr.State("SDXL") + + def add_cn_row(c): + c += 1 + updates = { + count_state: c, + cn_rows[c-1]: gr.update(visible=True), + add_button: gr.update(visible=c < MAX_CONTROLNETS), + del_button: gr.update(visible=True) + } + return updates + + def del_cn_row(c): + c -= 1 + updates = { + count_state: c, + cn_rows[c]: gr.update(visible=False), + cn_images[c]: None, + cn_strengths[c]: 1.0, + add_button: gr.update(visible=True), + del_button: gr.update(visible=c > 0) + } + return updates + + add_outputs = [count_state, add_button, del_button] + cn_rows + del_outputs = [count_state, add_button, del_button] + cn_rows + cn_images + cn_strengths + add_button.click(fn=add_cn_row, inputs=[count_state], outputs=add_outputs, show_progress=False) + del_button.click(fn=del_cn_row, inputs=[count_state], outputs=del_outputs, show_progress=False) + + def on_cn_type_change(selected_type, model_name): + from core.settings import MODEL_TYPE_MAP + m_type = MODEL_TYPE_MAP.get(model_name, "SDXL") if model_name else "SDXL" + cn_full_config = load_diffsynth_controlnet_config() + + architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {}) + controlnet_key = architectures_dict.get(m_type, {}).get("controlnet_key", m_type) + + cn_config = cn_full_config.get(controlnet_key, []) + series_choices = [] + if selected_type: + series_choices = sorted(list(set( + model.get("Series", "Default") for model in cn_config + if selected_type in model.get("Type", []) + ))) + default_series = series_choices[0] if series_choices else None + filepath = "None" + if default_series: + for model in cn_config: + if model.get("Series") == default_series and selected_type in model.get("Type", []): + filepath = model.get("Filepath") + break + return gr.update(choices=series_choices, value=default_series), filepath + + def on_cn_series_change(selected_series, selected_type, model_name): + from core.settings import MODEL_TYPE_MAP + m_type = MODEL_TYPE_MAP.get(model_name, "SDXL") if model_name else "SDXL" + cn_full_config = load_diffsynth_controlnet_config() + + architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {}) + controlnet_key = architectures_dict.get(m_type, {}).get("controlnet_key", m_type) + + cn_config = cn_full_config.get(controlnet_key, []) + filepath = "None" + if selected_series and selected_type: + for model in cn_config: + if model.get("Series") == selected_series and selected_type in model.get("Type", []): + filepath = model.get("Filepath") + break + return filepath + + for i in range(MAX_CONTROLNETS): + cn_types[i].change( + fn=on_cn_type_change, + inputs=[cn_types[i], actual_arch_comp], + outputs=[cn_series[i], cn_filepaths[i]], + show_progress=False + ) + cn_series[i].change( + fn=on_cn_series_change, + inputs=[cn_series[i], cn_types[i], actual_arch_comp], + outputs=[cn_filepaths[i]], + show_progress=False + ) + + def on_accordion_expand(*images): + return [gr.update() for _ in images] + + accordion.expand( + fn=on_accordion_expand, + inputs=cn_images, + outputs=cn_images, + show_progress=False + ) + + +def create_flux1_ipadapter_event_handlers(prefix, ui_components): + fipa_rows = ui_components.get(f'flux1_ipadapter_rows_{prefix}') + if not fipa_rows: return + count_state = ui_components[f'flux1_ipadapter_count_state_{prefix}'] + add_button = ui_components[f'add_flux1_ipadapter_button_{prefix}'] + del_button = ui_components[f'delete_flux1_ipadapter_button_{prefix}'] + images = ui_components[f'flux1_ipadapter_images_{prefix}'] + weights = ui_components[f'flux1_ipadapter_weights_{prefix}'] + start_percents = ui_components[f'flux1_ipadapter_start_percents_{prefix}'] + end_percents = ui_components[f'flux1_ipadapter_end_percents_{prefix}'] + + def add_fipa_row(c): + c += 1 + return { + count_state: c, + fipa_rows[c - 1]: gr.update(visible=True), + add_button: gr.update(visible=c < MAX_IPADAPTERS), + del_button: gr.update(visible=True), + } + + def del_fipa_row(c): + c -= 1 + return { + count_state: c, + fipa_rows[c]: gr.update(visible=False), + images[c]: None, + weights[c]: 0.6, + start_percents[c]: 0.0, + end_percents[c]: 0.6, + add_button: gr.update(visible=True), + del_button: gr.update(visible=c > 0), + } + + add_outputs = [count_state, add_button, del_button] + fipa_rows + del_outputs = [count_state, add_button, del_button] + fipa_rows + images + weights + start_percents + end_percents + add_button.click(fn=add_fipa_row, inputs=[count_state], outputs=add_outputs, show_progress=False) + del_button.click(fn=del_fipa_row, inputs=[count_state], outputs=del_outputs, show_progress=False) + + +def create_sd3_ipadapter_event_handlers(prefix, ui_components): + ipa_rows = ui_components.get(f'sd3_ipadapter_rows_{prefix}') + if not ipa_rows: return + count_state = ui_components[f'sd3_ipadapter_count_state_{prefix}'] + add_button = ui_components[f'add_sd3_ipadapter_button_{prefix}'] + del_button = ui_components[f'delete_sd3_ipadapter_button_{prefix}'] + images = ui_components[f'sd3_ipadapter_images_{prefix}'] + weights = ui_components[f'sd3_ipadapter_weights_{prefix}'] + start_percents = ui_components[f'sd3_ipadapter_start_percents_{prefix}'] + end_percents = ui_components[f'sd3_ipadapter_end_percents_{prefix}'] + + def add_ipa_row(c): + c += 1 + return { + count_state: c, + ipa_rows[c - 1]: gr.update(visible=True), + add_button: gr.update(visible=c < MAX_IPADAPTERS), + del_button: gr.update(visible=True), + } + + def del_ipa_row(c): + c -= 1 + return { + count_state: c, + ipa_rows[c]: gr.update(visible=False), + images[c]: None, + weights[c]: 0.5, + start_percents[c]: 0.0, + end_percents[c]: 1.0, + add_button: gr.update(visible=True), + del_button: gr.update(visible=c > 0), + } + + add_outputs = [count_state, add_button, del_button] + ipa_rows + del_outputs = [count_state, add_button, del_button] + ipa_rows + images + weights + start_percents + end_percents + add_button.click(fn=add_ipa_row, inputs=[count_state], outputs=add_outputs, show_progress=False) + del_button.click(fn=del_ipa_row, inputs=[count_state], outputs=del_outputs, show_progress=False) + + +def create_style_event_handlers(prefix, ui_components): + style_rows = ui_components.get(f'style_rows_{prefix}') + if not style_rows: return + count_state = ui_components[f'style_count_state_{prefix}'] + add_button = ui_components[f'add_style_button_{prefix}'] + del_button = ui_components[f'delete_style_button_{prefix}'] + images = ui_components[f'style_images_{prefix}'] + strengths = ui_components[f'style_strengths_{prefix}'] + + def add_style_row(c): + c += 1 + return { + count_state: c, + style_rows[c - 1]: gr.update(visible=True), + add_button: gr.update(visible=c < 5), + del_button: gr.update(visible=True), + } + + def del_style_row(c): + c -= 1 + return { + count_state: c, + style_rows[c]: gr.update(visible=False), + images[c]: None, + strengths[c]: 1.0, + add_button: gr.update(visible=True), + del_button: gr.update(visible=c > 0), + } + + add_outputs = [count_state, add_button, del_button] + style_rows + del_outputs = [count_state, add_button, del_button] + style_rows + images + strengths + add_button.click(fn=add_style_row, inputs=[count_state], outputs=add_outputs, show_progress=False) + del_button.click(fn=del_style_row, inputs=[count_state], outputs=del_outputs, show_progress=False) + + +def create_ipadapter_event_handlers(prefix, ui_components): + ipa_rows = ui_components.get(f'ipadapter_rows_{prefix}') + if not ipa_rows: return + ipa_lora_strengths = ui_components[f'ipadapter_lora_strengths_{prefix}'] + ipa_final_preset = ui_components[f'ipadapter_final_preset_{prefix}'] + ipa_final_lora_strength = ui_components[f'ipadapter_final_lora_strength_{prefix}'] + count_state = ui_components[f'ipadapter_count_state_{prefix}'] + add_button = ui_components[f'add_ipadapter_button_{prefix}'] + del_button = ui_components[f'delete_ipadapter_button_{prefix}'] + accordion = ui_components[f'ipadapter_accordion_{prefix}'] + images = ui_components[f'ipadapter_images_{prefix}'] + weights = ui_components[f'ipadapter_weights_{prefix}'] + + def add_ipa_row(c): + c += 1 + return { + count_state: c, + ipa_rows[c - 1]: gr.update(visible=True), + add_button: gr.update(visible=c < MAX_IPADAPTERS), + del_button: gr.update(visible=True), + } + + def del_ipa_row(c): + c -= 1 + return { + count_state: c, + ipa_rows[c]: gr.update(visible=False), + images[c]: None, + weights[c]: 1.0, + ipa_lora_strengths[c]: 0.6, + add_button: gr.update(visible=True), + del_button: gr.update(visible=c > 0), + } + + add_outputs = [count_state, add_button, del_button] + ipa_rows + del_outputs = [count_state, add_button, del_button] + ipa_rows + images + weights + ipa_lora_strengths + add_button.click(fn=add_ipa_row, inputs=[count_state], outputs=add_outputs, show_progress=False) + del_button.click(fn=del_ipa_row, inputs=[count_state], outputs=del_outputs, show_progress=False) + + def on_preset_change(preset_value): + config = load_ipadapter_config() + faceid_presets = [] + if config: + faceid_presets.extend(config.get("IPAdapter_FaceID_presets", {}).get("SDXL", [])) + faceid_presets.extend(config.get("IPAdapter_FaceID_presets", {}).get("SD1.5", [])) + + is_visible = preset_value in faceid_presets + updates = [gr.update(visible=is_visible)] * (MAX_IPADAPTERS + 1) + return updates + + all_lora_strength_sliders = [ipa_final_lora_strength] + ipa_lora_strengths + ipa_final_preset.change(fn=on_preset_change, inputs=[ipa_final_preset], outputs=all_lora_strength_sliders, show_progress=False) + + accordion.expand(fn=lambda *imgs: [gr.update() for _ in imgs], inputs=ui_components[f'ipadapter_images_{prefix}'], outputs=ui_components[f'ipadapter_images_{prefix}'], show_progress=False) + + +def create_reference_latent_event_handlers(prefix, ui_components): + ref_rows = ui_components.get(f'reference_latent_rows_{prefix}') + if not ref_rows: return + count_state = ui_components[f'reference_latent_count_state_{prefix}'] + add_button = ui_components[f'add_reference_latent_button_{prefix}'] + del_button = ui_components[f'delete_reference_latent_button_{prefix}'] + images = ui_components[f'reference_latent_images_{prefix}'] + + def add_ref_row(c): + c += 1 + return { + count_state: c, + ref_rows[c - 1]: gr.update(visible=True), + add_button: gr.update(visible=c < 10), + del_button: gr.update(visible=True), + } + + def del_ref_row(c): + c -= 1 + return { + count_state: c, + ref_rows[c]: gr.update(visible=False), + images[c]: None, + add_button: gr.update(visible=True), + del_button: gr.update(visible=c > 0), + } + + add_outputs = [count_state, add_button, del_button] + ref_rows + del_outputs = [count_state, add_button, del_button] + ref_rows + images + add_button.click(fn=add_ref_row, inputs=[count_state], outputs=add_outputs, show_progress=False) + del_button.click(fn=del_ref_row, inputs=[count_state], outputs=del_outputs, show_progress=False) + + +def create_hidream_o1_reference_event_handlers(prefix, ui_components): + ref_rows = ui_components.get(f'hidream_o1_reference_rows_{prefix}') + if not ref_rows: return + count_state = ui_components[f'hidream_o1_reference_count_state_{prefix}'] + add_button = ui_components[f'add_hidream_o1_reference_button_{prefix}'] + del_button = ui_components[f'delete_hidream_o1_reference_button_{prefix}'] + images = ui_components[f'hidream_o1_reference_images_{prefix}'] + + def add_ref_row(c): + c += 1 + return { + count_state: c, + ref_rows[c - 1]: gr.update(visible=True), + add_button: gr.update(visible=c < 10), + del_button: gr.update(visible=True), + } + + def del_ref_row(c): + c -= 1 + return { + count_state: c, + ref_rows[c]: gr.update(visible=False), + images[c]: None, + add_button: gr.update(visible=True), + del_button: gr.update(visible=c > 0), + } + + add_outputs = [count_state, add_button, del_button] + ref_rows + del_outputs = [count_state, add_button, del_button] + ref_rows + images + add_button.click(fn=add_ref_row, inputs=[count_state], outputs=add_outputs, show_progress=False) + del_button.click(fn=del_ref_row, inputs=[count_state], outputs=del_outputs, show_progress=False) + + +def create_joyai_reference_event_handlers(prefix, ui_components): + ref_rows = ui_components.get(f'joyai_reference_rows_{prefix}') + if not ref_rows: return + count_state = ui_components[f'joyai_reference_count_state_{prefix}'] + add_button = ui_components[f'add_joyai_reference_button_{prefix}'] + del_button = ui_components[f'delete_joyai_reference_button_{prefix}'] + images = ui_components[f'joyai_reference_images_{prefix}'] + + def add_ref_row(c): + c += 1 + return { + count_state: c, + ref_rows[c - 1]: gr.update(visible=True), + add_button: gr.update(visible=c < 2), + del_button: gr.update(visible=True), + } + + def del_ref_row(c): + c -= 1 + return { + count_state: c, + ref_rows[c]: gr.update(visible=False), + images[c]: None, + add_button: gr.update(visible=True), + del_button: gr.update(visible=c > 0), + } + + add_outputs = [count_state, add_button, del_button] + ref_rows + del_outputs = [count_state, add_button, del_button] + ref_rows + images + add_button.click(fn=add_ref_row, inputs=[count_state], outputs=add_outputs, show_progress=False) + del_button.click(fn=del_ref_row, inputs=[count_state], outputs=del_outputs, show_progress=False) + + +def create_reference_image_event_handlers(prefix, ui_components): + ref_rows = ui_components.get(f'reference_image_rows_{prefix}') + if not ref_rows: return + count_state = ui_components[f'reference_image_count_state_{prefix}'] + add_button = ui_components[f'add_reference_image_button_{prefix}'] + del_button = ui_components[f'delete_reference_image_button_{prefix}'] + images = ui_components[f'reference_image_images_{prefix}'] + + def add_ref_row(c): + c += 1 + return { + count_state: c, + ref_rows[c - 1]: gr.update(visible=True), + add_button: gr.update(visible=c < 10), + del_button: gr.update(visible=True), + } + + def del_ref_row(c): + c -= 1 + return { + count_state: c, + ref_rows[c]: gr.update(visible=False), + images[c]: None, + add_button: gr.update(visible=True), + del_button: gr.update(visible=c > 0), + } + + add_outputs = [count_state, add_button, del_button] + ref_rows + del_outputs = [count_state, add_button, del_button] + ref_rows + images + add_button.click(fn=add_ref_row, inputs=[count_state], outputs=add_outputs, show_progress=False) + del_button.click(fn=del_ref_row, inputs=[count_state], outputs=del_outputs, show_progress=False) + + +def create_embedding_event_handlers(prefix, ui_components): + rows = ui_components.get(f'embedding_rows_{prefix}') + if not rows: return + ids = ui_components[f'embeddings_ids_{prefix}'] + files = ui_components[f'embeddings_files_{prefix}'] + sources = ui_components[f'embeddings_sources_{prefix}'] + upload_buttons = ui_components[f'embeddings_uploads_{prefix}'] + count_state = ui_components[f'embedding_count_state_{prefix}'] + add_button = ui_components[f'add_embedding_button_{prefix}'] + del_button = ui_components[f'delete_embedding_button_{prefix}'] + + for i in range(MAX_EMBEDDINGS): + upload_buttons[i].upload( + fn=on_embedding_upload, + inputs=[upload_buttons[i]], + outputs=[ids[i], sources[i], files[i]], + show_progress=True + ) + + def add_row(c): + c += 1 + return { + count_state: c, + rows[c - 1]: gr.update(visible=True), + add_button: gr.update(visible=c < MAX_EMBEDDINGS), + del_button: gr.update(visible=True) + } + + def del_row(c): + c -= 1 + return { + count_state: c, + rows[c]: gr.update(visible=False), + ids[c]: "", + files[c]: None, + add_button: gr.update(visible=True), + del_button: gr.update(visible=c > 0) + } + + add_outputs = [count_state, add_button, del_button] + rows + del_outputs = [count_state, add_button, del_button] + rows + ids + files + add_button.click(fn=add_row, inputs=[count_state], outputs=add_outputs, show_progress=False) + del_button.click(fn=del_row, inputs=[count_state], outputs=del_outputs, show_progress=False) + + +def create_conditioning_event_handlers(prefix, ui_components): + rows = ui_components.get(f'conditioning_rows_{prefix}') + if not rows: return + prompts = ui_components[f'conditioning_prompts_{prefix}'] + count_state = ui_components[f'conditioning_count_state_{prefix}'] + add_button = ui_components[f'add_conditioning_button_{prefix}'] + del_button = ui_components[f'delete_conditioning_button_{prefix}'] + + def add_row(c): + c += 1 + return { + count_state: c, + rows[c - 1]: gr.update(visible=True), + add_button: gr.update(visible=c < MAX_CONDITIONINGS), + del_button: gr.update(visible=True), + } + + def del_row(c): + c -= 1 + return { + count_state: c, + rows[c]: gr.update(visible=False), + prompts[c]: "", + add_button: gr.update(visible=True), + del_button: gr.update(visible=c > 0), + } + + add_outputs = [count_state, add_button, del_button] + rows + del_outputs = [count_state, add_button, del_button] + rows + prompts + add_button.click(fn=add_row, inputs=[count_state], outputs=add_outputs, show_progress=False) + del_button.click(fn=del_row, inputs=[count_state], outputs=del_outputs, show_progress=False) + + +def create_krea2_identity_edit_event_handlers(prefix, ui_components): + ref_rows = ui_components.get(f'krea2_identity_edit_rows_{prefix}') + if not ref_rows: return + count_state = ui_components[f'krea2_identity_edit_count_state_{prefix}'] + add_button = ui_components[f'add_krea2_identity_edit_button_{prefix}'] + del_button = ui_components[f'delete_krea2_identity_edit_button_{prefix}'] + images = ui_components[f'krea2_identity_edit_images_{prefix}'] + + def add_ref_row(c): + c += 1 + return { + count_state: c, + ref_rows[c - 1]: gr.update(visible=True), + add_button: gr.update(visible=c < 2), + del_button: gr.update(visible=True), + } + + def del_ref_row(c): + c -= 1 + return { + count_state: c, + ref_rows[c]: gr.update(visible=False), + images[c]: None, + add_button: gr.update(visible=True), + del_button: gr.update(visible=c > 0), + } + + add_outputs = [count_state, add_button, del_button] + ref_rows + del_outputs = [count_state, add_button, del_button] + ref_rows + images + add_button.click(fn=add_ref_row, inputs=[count_state], outputs=add_outputs, show_progress=False) + del_button.click(fn=del_ref_row, inputs=[count_state], outputs=del_outputs, show_progress=False) + + +def create_qwen_image_edit_event_handlers(prefix, ui_components): + ref_rows = ui_components.get(f'qwen_image_edit_rows_{prefix}') + if not ref_rows: return + count_state = ui_components[f'qwen_image_edit_count_state_{prefix}'] + add_button = ui_components[f'add_qwen_image_edit_button_{prefix}'] + del_button = ui_components[f'delete_qwen_image_edit_button_{prefix}'] + images = ui_components[f'qwen_image_edit_images_{prefix}'] + + def add_ref_row(c): + c += 1 + return { + count_state: c, + ref_rows[c - 1]: gr.update(visible=True), + add_button: gr.update(visible=c < 3), + del_button: gr.update(visible=True), + } + + def del_ref_row(c): + c -= 1 + return { + count_state: c, + ref_rows[c]: gr.update(visible=False), + images[c]: None, + add_button: gr.update(visible=True), + del_button: gr.update(visible=c > 0), + } + + add_outputs = [count_state, add_button, del_button] + ref_rows + del_outputs = [count_state, add_button, del_button] + ref_rows + images + add_button.click(fn=add_ref_row, inputs=[count_state], outputs=add_outputs, show_progress=False) + del_button.click(fn=del_ref_row, inputs=[count_state], outputs=del_outputs, show_progress=False) + + +def create_krea2_reference_edit_event_handlers(prefix, ui_components): + ref_rows = ui_components.get(f'krea2_reference_edit_rows_{prefix}') + if not ref_rows: return + count_state = ui_components[f'krea2_reference_edit_count_state_{prefix}'] + add_button = ui_components[f'add_krea2_reference_edit_button_{prefix}'] + del_button = ui_components[f'delete_krea2_reference_edit_button_{prefix}'] + images = ui_components[f'krea2_reference_edit_images_{prefix}'] + + def add_ref_row(c): + c += 1 + return { + count_state: c, + ref_rows[c - 1]: gr.update(visible=True), + add_button: gr.update(visible=c < 3), + del_button: gr.update(visible=True), + } + + def del_ref_row(c): + c -= 1 + return { + count_state: c, + ref_rows[c]: gr.update(visible=False), + images[c]: None, + add_button: gr.update(visible=True), + del_button: gr.update(visible=c > 0), + } + + add_outputs = [count_state, add_button, del_button] + ref_rows + del_outputs = [count_state, add_button, del_button] + ref_rows + images + add_button.click(fn=add_ref_row, inputs=[count_state], outputs=add_outputs, show_progress=False) + del_button.click(fn=del_ref_row, inputs=[count_state], outputs=del_outputs, show_progress=False) + + +def create_boogu_edit_event_handlers(prefix, ui_components, max_units=10): + ref_rows = ui_components.get(f'boogu_edit_rows_{prefix}') + if not ref_rows: return + count_state = ui_components[f'boogu_edit_count_state_{prefix}'] + add_button = ui_components[f'add_boogu_edit_button_{prefix}'] + del_button = ui_components[f'delete_boogu_edit_button_{prefix}'] + images = ui_components[f'boogu_edit_images_{prefix}'] + + def add_ref_row(c): + c += 1 + return { + count_state: c, + ref_rows[c - 1]: gr.update(visible=True), + add_button: gr.update(visible=c < max_units), + del_button: gr.update(visible=True), + } + + def del_ref_row(c): + c -= 1 + return { + count_state: c, + ref_rows[c]: gr.update(visible=False), + images[c]: None, + add_button: gr.update(visible=True), + del_button: gr.update(visible=c > 1), + } + + add_outputs = [count_state, add_button, del_button] + ref_rows + del_outputs = [count_state, add_button, del_button] + ref_rows + images + add_button.click(fn=add_ref_row, inputs=[count_state], outputs=add_outputs, show_progress=False) + del_button.click(fn=del_ref_row, inputs=[count_state], outputs=del_outputs, show_progress=False) diff --git a/ui/events/change_handlers.py b/ui/events/change_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..44f8c85bc9150ed1b02b073f9a691c845f7d5faa --- /dev/null +++ b/ui/events/change_handlers.py @@ -0,0 +1,395 @@ +import gradio as gr +from core.settings import ( + MODEL_TYPE_MAP, + MODEL_MAP_CHECKPOINT, + FEATURES_CONFIG, + ARCHITECTURES_CONFIG, + MODEL_DEFAULTS_CONFIG, + ARCH_CATEGORIES_MAP +) +from imagegen_utils.app_utils import get_model_generation_defaults +from core.model_capabilities import supports_chain_for_model +from ui.shared.ui_components import RESOLUTION_MAP +from .config_loaders import ( + get_cn_defaults, + get_anima_cn_defaults, + get_diffsynth_cn_defaults, + get_krea2_cn_defaults, + load_ipadapter_config +) + +def make_update_fn(m_comp, cat_comp, cs_comp, ar_comp, width_comp, height_comp, cn_types, cn_series, cn_filepaths, anima_cn_types, anima_cn_series, anima_cn_filepaths, diffsynth_cn_types, diffsynth_cn_series, diffsynth_cn_filepaths, krea2_cn_types, krea2_cn_series, krea2_cn_filepaths, ipa_preset, lora_acc, cn_acc, anima_cn_acc, diffsynth_cn_acc, krea2_cn_acc, ipa_acc, sd3_ipa_acc, flux1_ipa_acc, style_acc, embed_acc, cond_acc, ref_latent_acc, hidream_o1_ref_acc, guidance_comp, prompt_comp, neg_prompt_comp, steps_comp, cfg_comp, sampler_comp, scheduler_comp, pid_acc=None, vae_acc=None, joyai_ref_acc=None, krea2_identity_edit_acc=None, krea2_reference_edit_acc=None, qwen_image_edit_acc=None, boogu_edit_acc=None, ref_img_acc=None, auto_params_comp=None): + def update_fn(*args): + arch = args[0] + category = args[1] + current_model = args[2] if len(args) > 2 else None + idx = 3 + current_ar = args[idx] if ar_comp and len(args) > idx else None + if ar_comp: + idx += 1 + auto_params = args[idx] if auto_params_comp and len(args) > idx else True + + if arch == "ALL": + valid_cats = list(set(cat for cats in ARCH_CATEGORIES_MAP.values() for cat in cats)) + else: + valid_cats = ARCH_CATEGORIES_MAP.get(arch, []) + + cat_choices = ["ALL"] + sorted(valid_cats) + new_category = category if category in cat_choices else "ALL" + + choices = [] + for name, info in MODEL_MAP_CHECKPOINT.items(): + m_arch = info[2] + m_cat = info[4] if len(info) > 4 else None + arch_match = (arch == "ALL" or m_arch == arch) + cat_match = (new_category == "ALL" or m_cat == new_category) + if arch_match and cat_match: + choices.append(name) + + # Filtering must not silently switch a model that is still valid. + val = current_model if current_model in choices else (choices[0] if choices else None) + + updates = { + m_comp: gr.update(choices=choices, value=val), + cat_comp: gr.update(choices=cat_choices, value=new_category) + } + + m_type = MODEL_TYPE_MAP.get(val, "SDXL") if val else "SDXL" + + architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {}) + arch_model_type = architectures_dict.get(m_type, {}).get("model_type", m_type.lower().replace(" ", "").replace(".", "")) + + arch_features = FEATURES_CONFIG.get(arch_model_type, {}) + enabled_chains = arch_features.get('enabled_chains', []) + + if lora_acc: updates[lora_acc] = gr.update(visible=('lora' in enabled_chains)) + if cn_acc: updates[cn_acc] = gr.update(visible=('controlnet' in enabled_chains)) + if anima_cn_acc: updates[anima_cn_acc] = gr.update(visible=('anima_controlnet_lllite' in enabled_chains)) + if diffsynth_cn_acc: updates[diffsynth_cn_acc] = gr.update(visible=('diffsynth_controlnet' in enabled_chains)) + if krea2_cn_acc: updates[krea2_cn_acc] = gr.update(visible=('krea2_controlnet' in enabled_chains)) + if ipa_acc: updates[ipa_acc] = gr.update(visible=('ipadapter' in enabled_chains)) + if flux1_ipa_acc: updates[flux1_ipa_acc] = gr.update(visible=('flux1_ipadapter' in enabled_chains)) + if sd3_ipa_acc: updates[sd3_ipa_acc] = gr.update(visible=('sd3_ipadapter' in enabled_chains)) + if style_acc: updates[style_acc] = gr.update(visible=('style' in enabled_chains)) + if embed_acc: updates[embed_acc] = gr.update(visible=('embedding' in enabled_chains)) + if cond_acc: updates[cond_acc] = gr.update(visible=('conditioning' in enabled_chains)) + if ref_latent_acc: updates[ref_latent_acc] = gr.update(visible=('reference_latent' in enabled_chains)) + if hidream_o1_ref_acc: updates[hidream_o1_ref_acc] = gr.update(visible=('hidream_o1_reference' in enabled_chains)) + if joyai_ref_acc: updates[joyai_ref_acc] = gr.update(visible=('joyai_image' in enabled_chains)) + if krea2_identity_edit_acc: updates[krea2_identity_edit_acc] = gr.update(visible=('krea2_identity_edit' in enabled_chains)) + if krea2_reference_edit_acc: updates[krea2_reference_edit_acc] = gr.update(visible=('krea2_style_reference' in enabled_chains)) + if qwen_image_edit_acc: updates[qwen_image_edit_acc] = gr.update(visible=('qwen_image_edit' in enabled_chains and supports_chain_for_model(val, 'qwen_image_edit'))) + if boogu_edit_acc: updates[boogu_edit_acc] = gr.update(visible=('boogu_image_edit' in enabled_chains and supports_chain_for_model(val, 'boogu_image_edit'))) + if ref_img_acc: updates[ref_img_acc] = gr.update(visible=('reference_image' in enabled_chains and supports_chain_for_model(val, 'reference_image'))) + if pid_acc: updates[pid_acc] = gr.update(visible=('pid' in enabled_chains)) + if vae_acc: updates[vae_acc] = gr.update(visible=('vae' in enabled_chains)) + + if cs_comp: + updates[cs_comp] = gr.update(visible=(arch_model_type == "sd15")) + if guidance_comp: + updates[guidance_comp] = gr.update(visible=(arch_model_type == "flux1")) + + if ar_comp: + res_key = arch_model_type + if res_key not in RESOLUTION_MAP: + res_key = 'sdxl' + res_map = RESOLUTION_MAP.get(res_key, {}) + target_ar = current_ar if current_ar in res_map else (list(res_map.keys())[0] if res_map else "1:1 (Square)") + updates[ar_comp] = gr.update(choices=list(res_map.keys()), value=target_ar) + if width_comp and height_comp and target_ar in res_map: + updates[width_comp] = gr.update(value=res_map[target_ar][0]) + updates[height_comp] = gr.update(value=res_map[target_ar][1]) + + controlnet_key = architectures_dict.get(m_type, {}).get("controlnet_key", m_type) + + all_types, default_type, series_choices, default_series, filepath = get_cn_defaults(controlnet_key) + for t_comp in cn_types: + updates[t_comp] = gr.update(choices=all_types, value=default_type) + for s_comp in cn_series: + updates[s_comp] = gr.update(choices=series_choices, value=default_series) + for f_comp in cn_filepaths: + updates[f_comp] = filepath + + anima_all_types, anima_default_type, anima_series_choices, anima_default_series, anima_filepath = get_anima_cn_defaults() + for t_comp in anima_cn_types: + updates[t_comp] = gr.update(choices=anima_all_types, value=anima_default_type) + for s_comp in anima_cn_series: + updates[s_comp] = gr.update(choices=anima_series_choices, value=anima_default_series) + for f_comp in anima_cn_filepaths: + updates[f_comp] = anima_filepath + + diffsynth_all_types, diffsynth_default_type, diffsynth_series_choices, diffsynth_default_series, diffsynth_filepath = get_diffsynth_cn_defaults(controlnet_key) + for t_comp in diffsynth_cn_types: + updates[t_comp] = gr.update(choices=diffsynth_all_types, value=diffsynth_default_type) + for s_comp in diffsynth_cn_series: + updates[s_comp] = gr.update(choices=diffsynth_series_choices, value=diffsynth_default_series) + for f_comp in diffsynth_cn_filepaths: + updates[f_comp] = diffsynth_filepath + + krea2_all_types, krea2_default_type, krea2_series_choices, krea2_default_series, krea2_filepath = get_krea2_cn_defaults() + for t_comp in krea2_cn_types: + updates[t_comp] = gr.update(choices=krea2_all_types, value=krea2_default_type) + for s_comp in krea2_cn_series: + updates[s_comp] = gr.update(choices=krea2_series_choices, value=krea2_default_series) + for f_comp in krea2_cn_filepaths: + updates[f_comp] = krea2_filepath + + if ipa_preset and (arch_model_type in ["sdxl", "sd15", "sd35"]): + config = load_ipadapter_config() + ipa_arch_key = "SDXL" if arch_model_type in ["sdxl", "sd35"] else "SD1.5" + std_presets = config.get("IPAdapter_presets", {}).get(ipa_arch_key, []) + face_presets = config.get("IPAdapter_FaceID_presets", {}).get(ipa_arch_key, []) + all_ipa_presets = std_presets + face_presets + default_ipa = all_ipa_presets[0] if all_ipa_presets else None + updates[ipa_preset] = gr.update(choices=all_ipa_presets, value=default_ipa) + + defaults = get_model_generation_defaults(val, arch_model_type, MODEL_DEFAULTS_CONFIG) + if steps_comp: updates[steps_comp] = gr.update(value=defaults.get('steps')) if auto_params else gr.update() + if cfg_comp: updates[cfg_comp] = gr.update(value=defaults.get('cfg')) if auto_params else gr.update() + if sampler_comp: updates[sampler_comp] = gr.update(value=defaults.get('sampler_name')) if auto_params else gr.update() + if scheduler_comp: updates[scheduler_comp] = gr.update(value=defaults.get('scheduler')) if auto_params else gr.update() + # Model/filter changes may tune sampling defaults, but user-authored text is + # never overwritten. This is especially important when comparing models. + if prompt_comp: updates[prompt_comp] = gr.update() + if neg_prompt_comp: updates[neg_prompt_comp] = gr.update() + + return updates + return update_fn + + +def make_model_change_fn(cat_comp_ref, cs_comp, ar_comp, width_comp, height_comp, cn_types, cn_series, cn_filepaths, anima_cn_types, anima_cn_series, anima_cn_filepaths, diffsynth_cn_types, diffsynth_cn_series, diffsynth_cn_filepaths, krea2_cn_types, krea2_cn_series, krea2_cn_filepaths, arch_comp_ref, ipa_preset, lora_acc, cn_acc, anima_cn_acc, diffsynth_cn_acc, krea2_cn_acc, ipa_acc, sd3_ipa_acc, flux1_ipa_acc, style_acc, embed_acc, cond_acc, ref_latent_acc, hidream_o1_ref_acc, guidance_comp, prompt_comp, neg_prompt_comp, steps_comp, cfg_comp, sampler_comp, scheduler_comp, pid_acc=None, vae_acc=None, joyai_ref_acc=None, krea2_identity_edit_acc=None, krea2_reference_edit_acc=None, qwen_image_edit_acc=None, boogu_edit_acc=None, ref_img_acc=None, auto_params_comp=None): + def change_fn(*args): + model_name = args[0] + idx = 1 + current_arch = args[idx] if arch_comp_ref and idx < len(args) else None + if arch_comp_ref: idx += 1 + current_cat = args[idx] if cat_comp_ref and idx < len(args) else None + if cat_comp_ref: idx += 1 + current_ar = args[idx] if ar_comp and idx < len(args) else None + if ar_comp: + idx += 1 + auto_params = args[idx] if auto_params_comp and idx < len(args) else True + + m_type = MODEL_TYPE_MAP.get(model_name, "SDXL") + + m_info = MODEL_MAP_CHECKPOINT.get(model_name) + m_cat = m_info[4] if m_info and len(m_info) > 4 else None + if not m_cat: m_cat = "ALL" + + updates = {} + target_arch = m_type + if arch_comp_ref: + if current_arch == "ALL": + updates[arch_comp_ref] = gr.update() + target_arch = "ALL" + else: + updates[arch_comp_ref] = m_type + + if cat_comp_ref: + if target_arch == "ALL": + valid_cats = list(set(cat for cats in ARCH_CATEGORIES_MAP.values() for cat in cats)) + else: + valid_cats = ARCH_CATEGORIES_MAP.get(target_arch, []) + cat_choices = ["ALL"] + sorted(valid_cats) + + if current_cat == "ALL": + updates[cat_comp_ref] = gr.update(choices=cat_choices) + else: + updates[cat_comp_ref] = gr.update(choices=cat_choices, value=m_cat) + + architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {}) + arch_model_type = architectures_dict.get(m_type, {}).get("model_type", m_type.lower().replace(" ", "").replace(".", "")) + + arch_features = FEATURES_CONFIG.get(arch_model_type, {}) + enabled_chains = arch_features.get('enabled_chains', []) + + if lora_acc: updates[lora_acc] = gr.update(visible=('lora' in enabled_chains)) + if cn_acc: updates[cn_acc] = gr.update(visible=('controlnet' in enabled_chains)) + if anima_cn_acc: updates[anima_cn_acc] = gr.update(visible=('anima_controlnet_lllite' in enabled_chains)) + if diffsynth_cn_acc: updates[diffsynth_cn_acc] = gr.update(visible=('diffsynth_controlnet' in enabled_chains)) + if krea2_cn_acc: updates[krea2_cn_acc] = gr.update(visible=('krea2_controlnet' in enabled_chains)) + if ipa_acc: updates[ipa_acc] = gr.update(visible=('ipadapter' in enabled_chains)) + if flux1_ipa_acc: updates[flux1_ipa_acc] = gr.update(visible=('flux1_ipadapter' in enabled_chains)) + if sd3_ipa_acc: updates[sd3_ipa_acc] = gr.update(visible=('sd3_ipadapter' in enabled_chains)) + if style_acc: updates[style_acc] = gr.update(visible=('style' in enabled_chains)) + if embed_acc: updates[embed_acc] = gr.update(visible=('embedding' in enabled_chains)) + if cond_acc: updates[cond_acc] = gr.update(visible=('conditioning' in enabled_chains)) + if ref_latent_acc: updates[ref_latent_acc] = gr.update(visible=('reference_latent' in enabled_chains)) + if hidream_o1_ref_acc: updates[hidream_o1_ref_acc] = gr.update(visible=('hidream_o1_reference' in enabled_chains)) + if joyai_ref_acc: updates[joyai_ref_acc] = gr.update(visible=('joyai_image' in enabled_chains)) + if krea2_identity_edit_acc: updates[krea2_identity_edit_acc] = gr.update(visible=('krea2_identity_edit' in enabled_chains)) + if krea2_reference_edit_acc: updates[krea2_reference_edit_acc] = gr.update(visible=('krea2_style_reference' in enabled_chains)) + if qwen_image_edit_acc: updates[qwen_image_edit_acc] = gr.update(visible=('qwen_image_edit' in enabled_chains and supports_chain_for_model(model_name, 'qwen_image_edit'))) + if boogu_edit_acc: updates[boogu_edit_acc] = gr.update(visible=('boogu_image_edit' in enabled_chains and supports_chain_for_model(model_name, 'boogu_image_edit'))) + if ref_img_acc: updates[ref_img_acc] = gr.update(visible=('reference_image' in enabled_chains and supports_chain_for_model(model_name, 'reference_image'))) + if pid_acc: updates[pid_acc] = gr.update(visible=('pid' in enabled_chains)) + if vae_acc: updates[vae_acc] = gr.update(visible=('vae' in enabled_chains)) + + if cs_comp: + updates[cs_comp] = gr.update(visible=(arch_model_type == "sd15")) + if guidance_comp: + updates[guidance_comp] = gr.update(visible=(arch_model_type == "flux1")) + + if ar_comp: + res_key = arch_model_type + if res_key not in RESOLUTION_MAP: + res_key = 'sdxl' + res_map = RESOLUTION_MAP.get(res_key, {}) + target_ar = current_ar if current_ar in res_map else (list(res_map.keys())[0] if res_map else "1:1 (Square)") + updates[ar_comp] = gr.update(choices=list(res_map.keys()), value=target_ar) + if width_comp and height_comp and target_ar in res_map: + updates[width_comp] = gr.update(value=res_map[target_ar][0]) + updates[height_comp] = gr.update(value=res_map[target_ar][1]) + + controlnet_key = architectures_dict.get(m_type, {}).get("controlnet_key", m_type) + + all_types, default_type, series_choices, default_series, filepath = get_cn_defaults(controlnet_key) + for t_comp in cn_types: + updates[t_comp] = gr.update(choices=all_types, value=default_type) + for s_comp in cn_series: + updates[s_comp] = gr.update(choices=series_choices, value=default_series) + for f_comp in cn_filepaths: + updates[f_comp] = filepath + + anima_all_types, anima_default_type, anima_series_choices, anima_default_series, anima_filepath = get_anima_cn_defaults() + for t_comp in anima_cn_types: + updates[t_comp] = gr.update(choices=anima_all_types, value=anima_default_type) + for s_comp in anima_cn_series: + updates[s_comp] = gr.update(choices=anima_series_choices, value=anima_default_series) + for f_comp in anima_cn_filepaths: + updates[f_comp] = anima_filepath + + diffsynth_all_types, diffsynth_default_type, diffsynth_series_choices, diffsynth_default_series, diffsynth_filepath = get_diffsynth_cn_defaults(controlnet_key) + for t_comp in diffsynth_cn_types: + updates[t_comp] = gr.update(choices=diffsynth_all_types, value=diffsynth_default_type) + for s_comp in diffsynth_cn_series: + updates[s_comp] = gr.update(choices=diffsynth_series_choices, value=diffsynth_default_series) + for f_comp in diffsynth_cn_filepaths: + updates[f_comp] = diffsynth_filepath + + krea2_all_types, krea2_default_type, krea2_series_choices, krea2_default_series, krea2_filepath = get_krea2_cn_defaults() + for t_comp in krea2_cn_types: + updates[t_comp] = gr.update(choices=krea2_all_types, value=krea2_default_type) + for s_comp in krea2_cn_series: + updates[s_comp] = gr.update(choices=krea2_series_choices, value=krea2_default_series) + for f_comp in krea2_cn_filepaths: + updates[f_comp] = krea2_filepath + + if ipa_preset and (arch_model_type in ["sdxl", "sd15", "sd35"]): + config = load_ipadapter_config() + ipa_arch_key = "SDXL" if arch_model_type in ["sdxl", "sd35"] else "SD1.5" + std_presets = config.get("IPAdapter_presets", {}).get(ipa_arch_key, []) + face_presets = config.get("IPAdapter_FaceID_presets", {}).get(ipa_arch_key, []) + all_ipa_presets = std_presets + face_presets + default_ipa = all_ipa_presets[0] if all_ipa_presets else None + updates[ipa_preset] = gr.update(choices=all_ipa_presets, value=default_ipa) + + defaults = get_model_generation_defaults(model_name, arch_model_type, MODEL_DEFAULTS_CONFIG) + if steps_comp: updates[steps_comp] = gr.update(value=defaults.get('steps')) if auto_params else gr.update() + if cfg_comp: updates[cfg_comp] = gr.update(value=defaults.get('cfg')) if auto_params else gr.update() + if sampler_comp: updates[sampler_comp] = gr.update(value=defaults.get('sampler_name')) if auto_params else gr.update() + if scheduler_comp: updates[scheduler_comp] = gr.update(value=defaults.get('scheduler')) if auto_params else gr.update() + if prompt_comp: updates[prompt_comp] = gr.update() + if neg_prompt_comp: updates[neg_prompt_comp] = gr.update() + + return updates + return change_fn + + +def initialize_all_cn_dropdowns(ui_components): + default_model_name = list(MODEL_MAP_CHECKPOINT.keys())[0] if MODEL_MAP_CHECKPOINT else None + default_m_type = MODEL_TYPE_MAP.get(default_model_name, "SDXL") if default_model_name else "SDXL" + architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {}) + controlnet_key = architectures_dict.get(default_m_type, {}).get("controlnet_key", default_m_type) + + all_types, default_type, series_choices, default_series, filepath = get_cn_defaults(controlnet_key) + anima_all_types, anima_default_type, anima_series_choices, anima_default_series, anima_filepath = get_anima_cn_defaults() + diffsynth_all_types, diffsynth_default_type, diffsynth_series_choices, diffsynth_default_series, diffsynth_filepath = get_diffsynth_cn_defaults(controlnet_key) + krea2_all_types, krea2_default_type, krea2_series_choices, krea2_default_series, krea2_filepath = get_krea2_cn_defaults() + + updates = {} + prefixes = [item[0] for item in ui_components.get("_task_prefixes", [])] + if not prefixes: + prefixes = ["txt2img", "img2img", "inpaint", "outpaint", "hires_fix"] + for prefix in prefixes: + if f'controlnet_types_{prefix}' in ui_components: + for type_dd in ui_components[f'controlnet_types_{prefix}']: + updates[type_dd] = gr.update(choices=all_types, value=default_type) + for series_dd in ui_components[f'controlnet_series_{prefix}']: + updates[series_dd] = gr.update(choices=series_choices, value=default_series) + for filepath_state in ui_components[f'controlnet_filepaths_{prefix}']: + updates[filepath_state] = filepath + + if f'anima_controlnet_lllite_types_{prefix}' in ui_components: + for type_dd in ui_components[f'anima_controlnet_lllite_types_{prefix}']: + updates[type_dd] = gr.update(choices=anima_all_types, value=anima_default_type) + for series_dd in ui_components[f'anima_controlnet_lllite_series_{prefix}']: + updates[series_dd] = gr.update(choices=anima_series_choices, value=anima_default_series) + for filepath_state in ui_components[f'anima_controlnet_lllite_filepaths_{prefix}']: + updates[filepath_state] = anima_filepath + + if f'diffsynth_controlnet_types_{prefix}' in ui_components: + for type_dd in ui_components[f'diffsynth_controlnet_types_{prefix}']: + updates[type_dd] = gr.update(choices=diffsynth_all_types, value=diffsynth_default_type) + for series_dd in ui_components[f'diffsynth_controlnet_series_{prefix}']: + updates[series_dd] = gr.update(choices=diffsynth_series_choices, value=default_series) + for filepath_state in ui_components[f'diffsynth_controlnet_filepaths_{prefix}']: + updates[filepath_state] = diffsynth_filepath + + if f'krea2_controlnet_types_{prefix}' in ui_components: + for type_dd in ui_components[f'krea2_controlnet_types_{prefix}']: + updates[type_dd] = gr.update(choices=krea2_all_types, value=krea2_default_type) + for series_dd in ui_components[f'krea2_controlnet_series_{prefix}']: + updates[series_dd] = gr.update(choices=krea2_series_choices, value=krea2_default_series) + for filepath_state in ui_components[f'krea2_controlnet_filepaths_{prefix}']: + updates[filepath_state] = krea2_filepath + + return updates + + +def initialize_all_ipa_dropdowns(ui_components): + config = load_ipadapter_config() + if not config: return {} + + default_model_name = list(MODEL_MAP_CHECKPOINT.keys())[0] if MODEL_MAP_CHECKPOINT else None + default_m_type = MODEL_TYPE_MAP.get(default_model_name, "SDXL") if default_model_name else "SDXL" + architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {}) + arch_model_type = architectures_dict.get(default_m_type, {}).get("model_type", default_m_type.lower().replace(" ", "").replace(".", "")) + ipa_arch_key = "SDXL" if arch_model_type in ["sdxl", "sd35"] else "SD1.5" + + unified_presets = config.get("IPAdapter_presets", {}).get(ipa_arch_key, []) + faceid_presets = config.get("IPAdapter_FaceID_presets", {}).get(ipa_arch_key, []) + + all_presets = unified_presets + faceid_presets + default_preset = all_presets[0] if all_presets else None + is_faceid_default = default_preset in faceid_presets + + lora_strength_update = gr.update(visible=is_faceid_default) + + updates = {} + prefixes = [item[0] for item in ui_components.get("_task_prefixes", [])] + if not prefixes: + prefixes = ["txt2img", "img2img", "inpaint", "outpaint", "hires_fix"] + for prefix in prefixes: + if f'ipadapter_final_preset_{prefix}' in ui_components: + for lora_strength_slider in ui_components[f'ipadapter_lora_strengths_{prefix}']: + updates[lora_strength_slider] = lora_strength_update + updates[ui_components[f'ipadapter_final_preset_{prefix}']] = gr.update(choices=all_presets, value=default_preset) + updates[ui_components[f'ipadapter_final_lora_strength_{prefix}']] = lora_strength_update + return updates + + +def run_on_load(ui_components): + cn_updates = initialize_all_cn_dropdowns(ui_components) + ipa_updates = initialize_all_ipa_dropdowns(ui_components) + return {**cn_updates, **ipa_updates} + + +def on_aspect_ratio_change(ratio_key, model_display_name): + m_type = MODEL_TYPE_MAP.get(model_display_name, 'SDXL') + architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {}) + arch_model_type = architectures_dict.get(m_type, {}).get("model_type", m_type.lower().replace(" ", "").replace(".", "")) + + res_map = RESOLUTION_MAP.get(arch_model_type, RESOLUTION_MAP.get("sdxl", {})) + w, h = res_map.get(ratio_key, (1024, 1024)) + return w, h diff --git a/ui/events/config_loaders.py b/ui/events/config_loaders.py new file mode 100644 index 0000000000000000000000000000000000000000..cc60885afc443fd014937528c693c615ff4b984e --- /dev/null +++ b/ui/events/config_loaders.py @@ -0,0 +1,168 @@ +import os +import yaml +from functools import lru_cache + +@lru_cache(maxsize=1) +def load_controlnet_config(): + _PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + _CN_MODEL_LIST_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'controlnet_models.yaml') + try: + print("--- Loading controlnet_models.yaml ---") + with open(_CN_MODEL_LIST_PATH, 'r', encoding='utf-8') as f: + config = yaml.safe_load(f) + print("--- ✅ controlnet_models.yaml loaded successfully ---") + return config.get("ControlNet", {}) + except Exception as e: + print(f"Error loading controlnet_models.yaml: {e}") + return {} + + +def get_cn_defaults(arch_val): + cn_full_config = load_controlnet_config() + cn_config = cn_full_config.get(arch_val, []) + + if not cn_config: + return [], None, [], None, "None" + + all_types = sorted(list(set(t for model in cn_config for t in model.get("Type", [])))) + default_type = all_types[0] if all_types else None + + series_choices = [] + if default_type: + series_choices = sorted(list(set(model.get("Series", "Default") for model in cn_config if default_type in model.get("Type", [])))) + default_series = series_choices[0] if series_choices else None + + filepath = "None" + if default_series and default_type: + for model in cn_config: + if model.get("Series") == default_series and default_type in model.get("Type", []): + filepath = model.get("Filepath") + break + + return all_types, default_type, series_choices, default_series, filepath + + +@lru_cache(maxsize=1) +def load_anima_controlnet_lllite_config(): + _PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + _CN_MODEL_LIST_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'anima_controlnet_lllite_models.yaml') + try: + print("--- Loading anima_controlnet_lllite_models.yaml ---") + with open(_CN_MODEL_LIST_PATH, 'r', encoding='utf-8') as f: + config = yaml.safe_load(f) + print("--- ✅ anima_controlnet_lllite_models.yaml loaded successfully ---") + return config.get("Anima_ControlNet_Lllite", []) + except Exception as e: + print(f"Error loading anima_controlnet_lllite_models.yaml: {e}") + return [] + + +def get_anima_cn_defaults(): + cn_config = load_anima_controlnet_lllite_config() + if not cn_config: + return [], None, [], None, "None" + all_types = sorted(list(set(t for model in cn_config for t in model.get("Type", [])))) + default_type = all_types[0] if all_types else None + series_choices = [] + if default_type: + series_choices = sorted(list(set(model.get("Series", "Default") for model in cn_config if default_type in model.get("Type", [])))) + default_series = series_choices[0] if series_choices else None + filepath = "None" + if default_series and default_type: + for model in cn_config: + if model.get("Series") == default_series and default_type in model.get("Type", []): + filepath = model.get("Filepath") + break + return all_types, default_type, series_choices, default_series, filepath + + +@lru_cache(maxsize=1) +def load_diffsynth_controlnet_config(): + _PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + _CN_MODEL_LIST_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'diffsynth_controlnet_models.yaml') + try: + print("--- Loading diffsynth_controlnet_models.yaml ---") + with open(_CN_MODEL_LIST_PATH, 'r', encoding='utf-8') as f: + config = yaml.safe_load(f) + print("--- ✅ diffsynth_controlnet_models.yaml loaded successfully ---") + return config.get("DiffSynth_ControlNet", {}) + except Exception as e: + print(f"Error loading diffsynth_controlnet_models.yaml: {e}") + return {} + + +def get_diffsynth_cn_defaults(arch_val): + cn_full_config = load_diffsynth_controlnet_config() + cn_config = cn_full_config.get(arch_val, []) + + if not cn_config: + return [], None, [], None, "None" + + all_types = sorted(list(set(t for model in cn_config for t in model.get("Type", [])))) + default_type = all_types[0] if all_types else None + + series_choices = [] + if default_type: + series_choices = sorted(list(set(model.get("Series", "Default") for model in cn_config if default_type in model.get("Type", [])))) + default_series = series_choices[0] if series_choices else None + + filepath = "None" + if default_series and default_type: + for model in cn_config: + if model.get("Series") == default_series and default_type in model.get("Type", []): + filepath = model.get("Filepath") + break + + return all_types, default_type, series_choices, default_series, filepath + + +@lru_cache(maxsize=1) +def load_krea2_controlnet_config(): + _PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + _CN_MODEL_LIST_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'krea2_controlnet_models.yaml') + try: + print("--- Loading krea2_controlnet_models.yaml ---") + with open(_CN_MODEL_LIST_PATH, 'r', encoding='utf-8') as f: + config = yaml.safe_load(f) + print("--- ✅ krea2_controlnet_models.yaml loaded successfully ---") + return config.get("Krea2_ControlNet", []) + except Exception as e: + print(f"Error loading krea2_controlnet_models.yaml: {e}") + return [] + +def get_krea2_cn_defaults(): + cn_config = load_krea2_controlnet_config() + if not cn_config: + return [], None, [], None, "None" + + all_types = sorted(list(set(t for model in cn_config for t in model.get("Type", [])))) + default_type = all_types[0] if all_types else None + + series_choices = [] + if default_type: + series_choices = sorted(list(set(model.get("Series", "Default") for model in cn_config if default_type in model.get("Type", [])))) + default_series = series_choices[0] if series_choices else None + + filepath = "None" + if default_series and default_type: + for model in cn_config: + if model.get("Series") == default_series and default_type in model.get("Type", []): + filepath = model.get("Filepath") + break + + return all_types, default_type, series_choices, default_series, filepath + + +@lru_cache(maxsize=1) +def load_ipadapter_config(): + _PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + _IPA_MODEL_LIST_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'ipadapter.yaml') + try: + print("--- Loading ipadapter.yaml ---") + with open(_IPA_MODEL_LIST_PATH, 'r', encoding='utf-8') as f: + config = yaml.safe_load(f) + print("--- ✅ ipadapter.yaml loaded successfully ---") + return config + except Exception as e: + print(f"Error loading ipadapter.yaml: {e}") + return {} diff --git a/ui/events/main.py b/ui/events/main.py new file mode 100644 index 0000000000000000000000000000000000000000..2674ee9739b05228b84f6b9066fcd2f20ee93c21 --- /dev/null +++ b/ui/events/main.py @@ -0,0 +1,360 @@ +"""Event wiring for the unified ImageGen Studio workspace.""" + +from __future__ import annotations + +import gradio as gr + +from ui.guidance import model_hint, recommended_params, task_help +from .chain_handlers import ( + create_anima_controlnet_lllite_event_handlers, + create_boogu_edit_event_handlers, + create_conditioning_event_handlers, + create_controlnet_event_handlers, + create_diffsynth_controlnet_event_handlers, + create_embedding_event_handlers, + create_flux1_ipadapter_event_handlers, + create_hidream_o1_reference_event_handlers, + create_ipadapter_event_handlers, + create_joyai_reference_event_handlers, + create_krea2_controlnet_event_handlers, + create_krea2_identity_edit_event_handlers, + create_krea2_reference_edit_event_handlers, + create_lora_event_handlers, + create_qwen_image_edit_event_handlers, + create_reference_image_event_handlers, + create_reference_latent_event_handlers, + create_sd3_ipadapter_event_handlers, + create_style_event_handlers, +) +from .change_handlers import ( + make_model_change_fn, + make_update_fn, + on_aspect_ratio_change, + run_on_load, +) +from .run_handlers import create_run_event, create_unified_run_event + + +CHAIN_EVENT_FACTORIES = ( + create_lora_event_handlers, + create_controlnet_event_handlers, + create_anima_controlnet_lllite_event_handlers, + create_diffsynth_controlnet_event_handlers, + create_krea2_controlnet_event_handlers, + create_ipadapter_event_handlers, + create_embedding_event_handlers, + create_conditioning_event_handlers, + create_flux1_ipadapter_event_handlers, + create_sd3_ipadapter_event_handlers, + create_style_event_handlers, + create_reference_latent_event_handlers, + create_hidream_o1_reference_event_handlers, + create_joyai_reference_event_handlers, + create_krea2_identity_edit_event_handlers, + create_krea2_reference_edit_event_handlers, + create_qwen_image_edit_event_handlers, + create_boogu_edit_event_handlers, + create_reference_image_event_handlers, +) + + +def _append_if(target, component): + if component is not None: + target.append(component) + + +def _task_switch_values(task_type): + uses_source = task_type in {"img2img", "outpaint", "hires_fix"} + labels = { + "img2img": "源图片(图生图)", + "outpaint": "源图片(扩图)", + "hires_fix": "源图片(高清修复)", + } + run_labels = { + "txt2img": "开始生成", + "img2img": "开始重绘", + "inpaint": "开始局部重绘", + "outpaint": "开始扩图", + "hires_fix": "开始高清修复", + } + return ( + task_help(task_type), + gr.update(visible=uses_source), + gr.update(label=labels.get(task_type, "源图片")), + gr.update(visible=task_type == "inpaint"), + gr.update(visible=task_type == "img2img"), + gr.update(visible=task_type == "outpaint"), + gr.update(visible=task_type == "hires_fix"), + gr.update(visible=task_type == "txt2img"), + gr.update(value=run_labels.get(task_type, "开始生成")), + ) + + +def _select_quick_preset(preset): + if preset == "__manual__": + return gr.update() + return gr.update(value=preset) + + +def _prefixes(ui_components): + return ui_components.get( + "_task_prefixes", + [ + ("txt2img", "txt2img"), + ("img2img", "img2img"), + ("inpaint", "inpaint"), + ("outpaint", "outpaint"), + ("hires_fix", "hires_fix"), + ], + ) + + +def attach_event_handlers(ui_components, demo): + task_prefixes = _prefixes(ui_components) + + for prefix, task_type in task_prefixes: + arch_comp = ui_components.get(f"model_arch_{prefix}") + cat_comp = ui_components.get(f"model_cat_{prefix}") + model_comp = ui_components.get(f"base_model_{prefix}") + clip_skip_comp = ui_components.get(f"clip_skip_{prefix}") or ui_components.get(f"{prefix}_clip_skip") + guidance_comp = ui_components.get(f"guidance_{prefix}") or ui_components.get(f"{prefix}_guidance") + aspect_ratio_comp = ui_components.get(f"aspect_ratio_{prefix}") or ui_components.get(f"{prefix}_aspect_ratio_dropdown") + width_comp = ui_components.get(f"width_{prefix}") or ui_components.get(f"{prefix}_width") + height_comp = ui_components.get(f"height_{prefix}") or ui_components.get(f"{prefix}_height") + + cn_types = ui_components.get(f"controlnet_types_{prefix}", []) + cn_series = ui_components.get(f"controlnet_series_{prefix}", []) + cn_filepaths = ui_components.get(f"controlnet_filepaths_{prefix}", []) + anima_types = ui_components.get(f"anima_controlnet_lllite_types_{prefix}", []) + anima_series = ui_components.get(f"anima_controlnet_lllite_series_{prefix}", []) + anima_filepaths = ui_components.get(f"anima_controlnet_lllite_filepaths_{prefix}", []) + diffsynth_types = ui_components.get(f"diffsynth_controlnet_types_{prefix}", []) + diffsynth_series = ui_components.get(f"diffsynth_controlnet_series_{prefix}", []) + diffsynth_filepaths = ui_components.get(f"diffsynth_controlnet_filepaths_{prefix}", []) + krea2_types = ui_components.get(f"krea2_controlnet_types_{prefix}", []) + krea2_series = ui_components.get(f"krea2_controlnet_series_{prefix}", []) + krea2_filepaths = ui_components.get(f"krea2_controlnet_filepaths_{prefix}", []) + + accordion_names = { + "lora": "lora_accordion", + "cn": "controlnet_accordion", + "anima": "anima_controlnet_lllite_accordion", + "diffsynth": "diffsynth_controlnet_accordion", + "krea2": "krea2_controlnet_accordion", + "ipa": "ipadapter_accordion", + "sd3_ipa": "sd3_ipadapter_accordion", + "flux1_ipa": "flux1_ipadapter_accordion", + "style": "style_accordion", + "embed": "embedding_accordion", + "cond": "conditioning_accordion", + "ref_latent": "reference_latent_accordion", + "hidream": "hidream_o1_reference_accordion", + "joyai": "joyai_reference_accordion", + "krea2_identity": "krea2_identity_edit_accordion", + "krea2_reference": "krea2_reference_edit_accordion", + "qwen_edit": "qwen_image_edit_accordion", + "boogu": "boogu_edit_accordion", + "ref_img": "reference_image_accordion", + "pid": "pid_accordion", + "vae": "vae_accordion", + } + acc = { + key: ui_components.get(f"{component_name}_{prefix}") + for key, component_name in accordion_names.items() + } + ipa_preset = ui_components.get(f"ipadapter_final_preset_{prefix}") + + prompt_comp = ui_components.get(f"prompt_{prefix}") or ui_components.get(f"{prefix}_positive_prompt") + neg_prompt_comp = ui_components.get(f"neg_prompt_{prefix}") or ui_components.get(f"{prefix}_negative_prompt") + steps_comp = ui_components.get(f"steps_{prefix}") or ui_components.get(f"{prefix}_steps") + cfg_comp = ui_components.get(f"cfg_{prefix}") or ui_components.get(f"{prefix}_cfg") + sampler_comp = ui_components.get(f"sampler_{prefix}") or ui_components.get(f"{prefix}_sampler_name") + scheduler_comp = ui_components.get(f"scheduler_{prefix}") or ui_components.get(f"{prefix}_scheduler") + auto_params_comp = ui_components.get(f"auto_model_params_{prefix}") + parameter_outputs = [ + item + for item in ( + prompt_comp, + neg_prompt_comp, + steps_comp, + cfg_comp, + sampler_comp, + scheduler_comp, + width_comp, + height_comp, + ) + if item is not None + ] + + if arch_comp is not None and cat_comp is not None and model_comp is not None: + filter_outputs = [model_comp, cat_comp] + for component in (clip_skip_comp, guidance_comp, aspect_ratio_comp): + _append_if(filter_outputs, component) + filter_outputs.extend( + cn_types + cn_series + cn_filepaths + + anima_types + anima_series + anima_filepaths + + diffsynth_types + diffsynth_series + diffsynth_filepaths + + krea2_types + krea2_series + krea2_filepaths + ) + for component in acc.values(): + _append_if(filter_outputs, component) + _append_if(filter_outputs, ipa_preset) + filter_outputs.extend(parameter_outputs) + + filter_fn = make_update_fn( + model_comp, cat_comp, clip_skip_comp, aspect_ratio_comp, width_comp, height_comp, + cn_types, cn_series, cn_filepaths, + anima_types, anima_series, anima_filepaths, + diffsynth_types, diffsynth_series, diffsynth_filepaths, + krea2_types, krea2_series, krea2_filepaths, + ipa_preset, acc["lora"], acc["cn"], acc["anima"], acc["diffsynth"], + acc["krea2"], acc["ipa"], acc["sd3_ipa"], acc["flux1_ipa"], + acc["style"], acc["embed"], acc["cond"], acc["ref_latent"], + acc["hidream"], guidance_comp, prompt_comp, neg_prompt_comp, steps_comp, + cfg_comp, sampler_comp, scheduler_comp, pid_acc=acc["pid"], + vae_acc=acc["vae"], joyai_ref_acc=acc["joyai"], + krea2_identity_edit_acc=acc["krea2_identity"], + krea2_reference_edit_acc=acc["krea2_reference"], + qwen_image_edit_acc=acc["qwen_edit"], boogu_edit_acc=acc["boogu"], + ref_img_acc=acc["ref_img"], auto_params_comp=auto_params_comp, + ) + filter_inputs = [arch_comp, cat_comp, model_comp] + if aspect_ratio_comp is not None: + filter_inputs.append(aspect_ratio_comp) + if auto_params_comp is not None: + filter_inputs.append(auto_params_comp) + arch_comp.change(filter_fn, filter_inputs, filter_outputs, show_progress="hidden") + cat_comp.change(filter_fn, filter_inputs, filter_outputs, show_progress="hidden") + + if model_comp is not None: + model_outputs = [] + for component in (arch_comp, cat_comp, clip_skip_comp, guidance_comp, aspect_ratio_comp): + _append_if(model_outputs, component) + model_outputs.extend( + cn_types + cn_series + cn_filepaths + + anima_types + anima_series + anima_filepaths + + diffsynth_types + diffsynth_series + diffsynth_filepaths + + krea2_types + krea2_series + krea2_filepaths + ) + for component in acc.values(): + _append_if(model_outputs, component) + _append_if(model_outputs, ipa_preset) + model_outputs.extend(parameter_outputs) + + model_inputs = [model_comp] + for component in (arch_comp, cat_comp, aspect_ratio_comp): + _append_if(model_inputs, component) + _append_if(model_inputs, auto_params_comp) + model_fn = make_model_change_fn( + cat_comp, clip_skip_comp, aspect_ratio_comp, width_comp, height_comp, + cn_types, cn_series, cn_filepaths, + anima_types, anima_series, anima_filepaths, + diffsynth_types, diffsynth_series, diffsynth_filepaths, + krea2_types, krea2_series, krea2_filepaths, + arch_comp, ipa_preset, acc["lora"], acc["cn"], acc["anima"], + acc["diffsynth"], acc["krea2"], acc["ipa"], acc["sd3_ipa"], + acc["flux1_ipa"], acc["style"], acc["embed"], acc["cond"], + acc["ref_latent"], acc["hidream"], guidance_comp, prompt_comp, + neg_prompt_comp, steps_comp, cfg_comp, sampler_comp, scheduler_comp, + pid_acc=acc["pid"], vae_acc=acc["vae"], joyai_ref_acc=acc["joyai"], + krea2_identity_edit_acc=acc["krea2_identity"], + krea2_reference_edit_acc=acc["krea2_reference"], + qwen_image_edit_acc=acc["qwen_edit"], boogu_edit_acc=acc["boogu"], + ref_img_acc=acc["ref_img"], auto_params_comp=auto_params_comp, + ) + model_comp.change(model_fn, model_inputs, model_outputs, show_progress="hidden") + + for factory in CHAIN_EVENT_FACTORIES: + factory(prefix, ui_components) + + if task_type is None: + create_unified_run_event(prefix, ui_components) + else: + create_run_event(prefix, task_type, ui_components) + + if all(component is not None for component in (aspect_ratio_comp, width_comp, height_comp, model_comp)): + aspect_ratio_comp.change( + on_aspect_ratio_change, + [aspect_ratio_comp, model_comp], + [width_comp, height_comp], + show_progress="hidden", + api_name=False, + show_api=False, + ) + + if task_type is None: + task_component = ui_components[f"task_type_{prefix}"] + task_component.change( + _task_switch_values, + [task_component], + [ + ui_components[f"task_help_{prefix}"], + ui_components[f"source_panel_{prefix}"], + ui_components[f"source_image_{prefix}"], + ui_components[f"inpaint_panel_{prefix}"], + ui_components[f"img2img_panel_{prefix}"], + ui_components[f"outpaint_panel_{prefix}"], + ui_components[f"hires_panel_{prefix}"], + ui_components[f"size_panel_{prefix}"], + ui_components[f"run_{prefix}"], + ], + show_progress="hidden", + api_name=False, + show_api=False, + ) + preset = ui_components[f"quick_preset_{prefix}"] + preset.change( + _select_quick_preset, + [preset], + [model_comp], + show_progress="hidden", + api_name=False, + show_api=False, + ) + model_comp.input( + lambda: "__manual__", + outputs=[preset], + show_progress="hidden", + api_name=False, + show_api=False, + ) + model_comp.change( + model_hint, + [model_comp], + [ui_components[f"model_hint_{prefix}"]], + show_progress="hidden", + api_name=False, + show_api=False, + ) + ui_components[f"reset_model_params_{prefix}"].click( + recommended_params, + [model_comp], + [steps_comp, cfg_comp, sampler_comp, scheduler_comp], + show_progress="hidden", + api_name=False, + show_api=False, + ) + + load_outputs = [] + for prefix, _ in task_prefixes: + for base_name in ( + "controlnet_types", "controlnet_series", "controlnet_filepaths", + "anima_controlnet_lllite_types", "anima_controlnet_lllite_series", + "anima_controlnet_lllite_filepaths", "diffsynth_controlnet_types", + "diffsynth_controlnet_series", "diffsynth_controlnet_filepaths", + "krea2_controlnet_types", "krea2_controlnet_series", "krea2_controlnet_filepaths", + ): + load_outputs.extend(ui_components.get(f"{base_name}_{prefix}", [])) + if f"ipadapter_final_preset_{prefix}" in ui_components: + load_outputs.extend(ui_components.get(f"ipadapter_lora_strengths_{prefix}", [])) + load_outputs.append(ui_components[f"ipadapter_final_preset_{prefix}"]) + load_outputs.append(ui_components[f"ipadapter_final_lora_strength_{prefix}"]) + + if load_outputs: + demo.load( + lambda: run_on_load(ui_components), + outputs=load_outputs, + show_progress="hidden", + api_name=False, + show_api=False, + ) diff --git a/ui/events/run_handlers.py b/ui/events/run_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..4ed23687e66b5b8d3645baffd3e4ad821f94b93f --- /dev/null +++ b/ui/events/run_handlers.py @@ -0,0 +1,360 @@ +import threading + +import gradio as gr +from core.execution_plan import ( + ExecutionPlanError, + MODE_MODEL_PK, + MODE_MULTI_INDEPENDENT, + MODE_MULTI_MODEL_GRID, + MODE_MULTI_REFERENCE, + build_execution_plan, + execute_generation_plan, + load_uploaded_images, +) +from core.generation_logic import generate_image_wrapper +from core.runtime_config import CONFIG +from core.task_scheduler import TaskCancelledError + + +_CANCEL_LOCK = threading.Lock() +_CANCEL_EVENTS = {} + + +def _session_key(request: gr.Request) -> str: + return getattr(request, "session_hash", None) or "anonymous" + +def create_run_event(prefix: str, task_type: str, ui_components: dict): + run_inputs_map = { + 'model_display_name': ui_components[f'base_model_{prefix}'], + 'positive_prompt': ui_components.get(f'prompt_{prefix}') or ui_components.get(f'{prefix}_positive_prompt'), + 'negative_prompt': ui_components.get(f'neg_prompt_{prefix}') or ui_components.get(f'{prefix}_negative_prompt'), + 'seed': ui_components.get(f'seed_{prefix}') or ui_components.get(f'{prefix}_seed'), + 'batch_size': ui_components.get(f'batch_size_{prefix}') or ui_components.get(f'{prefix}_batch_size'), + 'guidance_scale': ui_components.get(f'cfg_{prefix}') or ui_components.get(f'{prefix}_cfg'), + 'num_inference_steps': ui_components.get(f'steps_{prefix}') or ui_components.get(f'{prefix}_steps'), + 'sampler': ui_components.get(f'sampler_{prefix}') or ui_components.get(f'{prefix}_sampler_name'), + 'scheduler': ui_components.get(f'scheduler_{prefix}') or ui_components.get(f'{prefix}_scheduler'), + 'zero_gpu_duration': ui_components.get(f'zero_gpu_{prefix}'), + + 'clip_skip': ui_components.get(f'clip_skip_{prefix}'), + 'guidance': ui_components.get(f'guidance_{prefix}'), + 'task_type': gr.State(task_type) + } + + if ui_components.get(f'pid_settings_{prefix}'): + run_inputs_map['pid_settings'] = ui_components[f'pid_settings_{prefix}'] + + if task_type not in ['img2img', 'inpaint']: + run_inputs_map.update({ + 'width': ui_components.get(f'width_{prefix}') or ui_components.get(f'{prefix}_width'), + 'height': ui_components.get(f'height_{prefix}') or ui_components.get(f'{prefix}_height') + }) + + task_specific_map = { + 'img2img': {'img2img_image': f'input_image_{prefix}', 'img2img_denoise': f'denoise_{prefix}'}, + 'inpaint': {'inpaint_image_dict': f'input_image_dict_{prefix}', 'grow_mask_by': f'grow_mask_by_{prefix}', 'inpaint_denoise': f'denoise_{prefix}'}, + 'outpaint': {'outpaint_image': f'input_image_{prefix}', 'left': f'left_{prefix}', 'top': f'top_{prefix}', 'right': f'right_{prefix}', 'bottom': f'bottom_{prefix}', 'feathering': f'feathering_{prefix}'}, + 'hires_fix': {'hires_image': f'input_image_{prefix}', 'hires_upscaler': f'hires_upscaler_{prefix}', 'hires_scale_by': f'hires_scale_by_{prefix}', 'hires_denoise': f'denoise_{prefix}'} + } + if task_type in task_specific_map: + for key, comp_name in task_specific_map[task_type].items(): + if comp_name in ui_components: + run_inputs_map[key] = ui_components[comp_name] + + lora_data_components = ui_components.get(f'all_lora_components_flat_{prefix}', []) + controlnet_data_components = ui_components.get(f'all_controlnet_components_flat_{prefix}', []) + anima_controlnet_lllite_data_components = ui_components.get(f'all_anima_controlnet_lllite_components_flat_{prefix}', []) + diffsynth_controlnet_data_components = ui_components.get(f'all_diffsynth_controlnet_components_flat_{prefix}', []) + krea2_controlnet_data_components = ui_components.get(f'all_krea2_controlnet_components_flat_{prefix}', []) + ipadapter_data_components = ui_components.get(f'all_ipadapter_components_flat_{prefix}', []) + sd3_ipadapter_data_components = ui_components.get(f'all_sd3_ipadapter_components_flat_{prefix}', []) + flux1_ipadapter_data_components = ui_components.get(f'all_flux1_ipadapter_components_flat_{prefix}', []) + style_data_components = ui_components.get(f'all_style_components_flat_{prefix}', []) + embedding_data_components = ui_components.get(f'all_embedding_components_flat_{prefix}', []) + conditioning_data_components = ui_components.get(f'all_conditioning_components_flat_{prefix}', []) + reference_latent_data_components = ui_components.get(f'all_reference_latent_components_flat_{prefix}', []) + hidream_o1_reference_data_components = ui_components.get(f'all_hidream_o1_reference_components_flat_{prefix}', []) + joyai_reference_data_components = ui_components.get(f'all_joyai_reference_components_flat_{prefix}', []) + krea2_identity_edit_data_components = ui_components.get(f'all_krea2_identity_edit_components_flat_{prefix}', []) + krea2_reference_edit_data_components = ui_components.get(f'all_krea2_reference_edit_components_flat_{prefix}', []) + qwen_image_edit_data_components = ui_components.get(f'all_qwen_image_edit_components_flat_{prefix}', []) + boogu_edit_data_components = ui_components.get(f'all_boogu_edit_components_flat_{prefix}', []) + reference_image_data_components = ui_components.get(f'all_reference_image_components_flat_{prefix}', []) + + run_inputs_map['vae_source'] = ui_components.get(f'vae_source_{prefix}') + run_inputs_map['vae_id'] = ui_components.get(f'vae_id_{prefix}') + run_inputs_map['vae_file'] = ui_components.get(f'vae_file_{prefix}') + + input_keys = list(run_inputs_map.keys()) + input_list_flat = [v for v in run_inputs_map.values() if v is not None] + all_chains = [ + lora_data_components, controlnet_data_components, anima_controlnet_lllite_data_components, diffsynth_controlnet_data_components, krea2_controlnet_data_components, ipadapter_data_components, + sd3_ipadapter_data_components, flux1_ipadapter_data_components, style_data_components, + embedding_data_components, conditioning_data_components, reference_latent_data_components, hidream_o1_reference_data_components, joyai_reference_data_components, krea2_identity_edit_data_components, krea2_reference_edit_data_components, qwen_image_edit_data_components, boogu_edit_data_components, reference_image_data_components + ] + for chain in all_chains: + if chain: + input_list_flat.extend(chain) + + def create_ui_inputs_dict(*args): + valid_keys = [k for k in input_keys if run_inputs_map[k] is not None] + ui_dict = dict(zip(valid_keys, args[:len(valid_keys)])) + arg_idx = len(valid_keys) + + def assign_chain_data(chain_key, components_list): + nonlocal arg_idx + if components_list: + ui_dict[chain_key] = list(args[arg_idx : arg_idx + len(components_list)]) + arg_idx += len(components_list) + + assign_chain_data('lora_data', lora_data_components) + assign_chain_data('controlnet_data', controlnet_data_components) + assign_chain_data('anima_controlnet_lllite_data', anima_controlnet_lllite_data_components) + assign_chain_data('diffsynth_controlnet_data', diffsynth_controlnet_data_components) + assign_chain_data('krea2_controlnet_data', krea2_controlnet_data_components) + assign_chain_data('ipadapter_data', ipadapter_data_components) + assign_chain_data('sd3_ipadapter_chain', sd3_ipadapter_data_components) + assign_chain_data('flux1_ipadapter_data', flux1_ipadapter_data_components) + assign_chain_data('style_data', style_data_components) + assign_chain_data('embedding_data', embedding_data_components) + assign_chain_data('conditioning_data', conditioning_data_components) + assign_chain_data('reference_latent_data', reference_latent_data_components) + assign_chain_data('hidream_o1_reference_data', hidream_o1_reference_data_components) + assign_chain_data('joyai_reference_data', joyai_reference_data_components) + assign_chain_data('krea2_identity_edit_data', krea2_identity_edit_data_components) + assign_chain_data('krea2_reference_edit_data', krea2_reference_edit_data_components) + assign_chain_data('qwen_image_edit_data', qwen_image_edit_data_components) + assign_chain_data('boogu_edit_data', boogu_edit_data_components) + assign_chain_data('reference_image_data', reference_image_data_components) + + return ui_dict + + run_btn = ui_components.get(f'run_{prefix}') or ui_components.get(f'{prefix}_run_button') + res_gal = ui_components.get(f'result_{prefix}') or ui_components.get(f'{prefix}_output_gallery') + if run_btn and res_gal: + run_btn.click( + fn=lambda *args, progress=gr.Progress(track_tqdm=True): generate_image_wrapper(create_ui_inputs_dict(*args), progress), + inputs=input_list_flat, + outputs=[res_gal] + ) + + +def create_unified_run_event(prefix: str, ui_components: dict): + """Attach one generation event shared by all five task modes.""" + + run_inputs_map = { + "task_type": ui_components[f"task_type_{prefix}"], + "model_display_name": ui_components[f"base_model_{prefix}"], + "positive_prompt": ui_components[f"prompt_{prefix}"], + "negative_prompt": ui_components[f"neg_prompt_{prefix}"], + "seed": ui_components[f"seed_{prefix}"], + "batch_size": ui_components[f"batch_size_{prefix}"], + "guidance_scale": ui_components[f"cfg_{prefix}"], + "num_inference_steps": ui_components[f"steps_{prefix}"], + "sampler": ui_components[f"sampler_{prefix}"], + "scheduler": ui_components[f"scheduler_{prefix}"], + "zero_gpu_duration": ui_components[f"zero_gpu_{prefix}"], + "clip_skip": ui_components.get(f"clip_skip_{prefix}"), + "guidance": ui_components.get(f"guidance_{prefix}"), + "width": ui_components[f"width_{prefix}"], + "height": ui_components[f"height_{prefix}"], + "source_image": ui_components[f"source_image_{prefix}"], + "inpaint_image_dict": ui_components[f"inpaint_image_dict_{prefix}"], + "img2img_denoise": ui_components[f"img2img_denoise_{prefix}"], + "inpaint_denoise": ui_components[f"inpaint_denoise_{prefix}"], + "grow_mask_by": ui_components[f"grow_mask_by_{prefix}"], + "left": ui_components[f"left_{prefix}"], + "top": ui_components[f"top_{prefix}"], + "right": ui_components[f"right_{prefix}"], + "bottom": ui_components[f"bottom_{prefix}"], + "feathering": ui_components[f"feathering_{prefix}"], + "hires_upscaler": ui_components[f"hires_upscaler_{prefix}"], + "hires_scale_by": ui_components[f"hires_scale_by_{prefix}"], + "hires_denoise": ui_components[f"hires_denoise_{prefix}"], + "pid_settings": ui_components.get(f"pid_settings_{prefix}"), + "vae_source": ui_components.get(f"vae_source_{prefix}"), + "vae_id": ui_components.get(f"vae_id_{prefix}"), + "vae_file": ui_components.get(f"vae_file_{prefix}"), + "_run_mode": ui_components[f"run_mode_{prefix}"], + "_pk_models": ui_components[f"pk_models_{prefix}"], + "_batch_images": ui_components[f"batch_images_{prefix}"], + "_reference_role": ui_components[f"reference_role_{prefix}"], + "_pk_model_defaults": ui_components[f"pk_model_defaults_{prefix}"], + } + run_inputs_map = {key: value for key, value in run_inputs_map.items() if value is not None} + input_keys = list(run_inputs_map) + input_components = list(run_inputs_map.values()) + + chain_specs = [ + ("lora_data", "all_lora_components_flat"), + ("controlnet_data", "all_controlnet_components_flat"), + ("anima_controlnet_lllite_data", "all_anima_controlnet_lllite_components_flat"), + ("diffsynth_controlnet_data", "all_diffsynth_controlnet_components_flat"), + ("krea2_controlnet_data", "all_krea2_controlnet_components_flat"), + ("ipadapter_data", "all_ipadapter_components_flat"), + ("sd3_ipadapter_chain", "all_sd3_ipadapter_components_flat"), + ("flux1_ipadapter_data", "all_flux1_ipadapter_components_flat"), + ("style_data", "all_style_components_flat"), + ("embedding_data", "all_embedding_components_flat"), + ("conditioning_data", "all_conditioning_components_flat"), + ("reference_latent_data", "all_reference_latent_components_flat"), + ("hidream_o1_reference_data", "all_hidream_o1_reference_components_flat"), + ("joyai_reference_data", "all_joyai_reference_components_flat"), + ("krea2_identity_edit_data", "all_krea2_identity_edit_components_flat"), + ("krea2_reference_edit_data", "all_krea2_reference_edit_components_flat"), + ("qwen_image_edit_data", "all_qwen_image_edit_components_flat"), + ("boogu_edit_data", "all_boogu_edit_components_flat"), + ("reference_image_data", "all_reference_image_components_flat"), + ] + chain_components = [] + for chain_key, component_key in chain_specs: + values = ui_components.get(f"{component_key}_{prefix}", []) + chain_components.append((chain_key, values)) + input_components.extend(values) + + def create_inputs(*args): + values = dict(zip(input_keys, args[: len(input_keys)])) + index = len(input_keys) + for chain_key, components in chain_components: + if components: + values[chain_key] = list(args[index : index + len(components)]) + index += len(components) + + task_type = values["task_type"] + run_mode = values.get("_run_mode", "single") + source_image = values.pop("source_image", None) + batch_driven = run_mode in {MODE_MULTI_INDEPENDENT, MODE_MULTI_MODEL_GRID} + if task_type == "img2img" and not batch_driven: + if source_image is None: + raise gr.Error("图生图需要先上传源图片。") + values["img2img_image"] = source_image + elif task_type == "inpaint" and not batch_driven: + image_dict = values.get("inpaint_image_dict") + if not image_dict or not image_dict.get("background"): + raise gr.Error("局部重绘需要先上传图片并涂抹蒙版。") + elif task_type == "outpaint" and not batch_driven: + if source_image is None: + raise gr.Error("扩图需要先上传源图片。") + values["outpaint_image"] = source_image + elif task_type == "hires_fix" and not batch_driven: + if source_image is None: + raise gr.Error("高清修复需要先上传源图片。") + values["hires_image"] = source_image + return values + + run_button = ui_components[f"run_{prefix}"] + result_gallery = ui_components[f"result_{prefix}"] + run_summary = ui_components[f"run_summary_{prefix}"] + + def change_run_mode(mode): + is_pk = mode in {MODE_MODEL_PK, MODE_MULTI_MODEL_GRID} + uses_files = mode in { + MODE_MULTI_INDEPENDENT, + MODE_MULTI_MODEL_GRID, + MODE_MULTI_REFERENCE, + } + return ( + gr.update(visible=is_pk), + gr.update(visible=uses_files), + gr.update(visible=mode == MODE_MULTI_REFERENCE), + gr.update(visible=is_pk), + ) + + ui_components[f"run_mode_{prefix}"].change( + fn=change_run_mode, + inputs=[ui_components[f"run_mode_{prefix}"]], + outputs=[ + ui_components[f"pk_models_{prefix}"], + ui_components[f"batch_images_{prefix}"], + ui_components[f"reference_role_{prefix}"], + ui_components[f"pk_model_defaults_{prefix}"], + ], + queue=False, + show_progress="hidden", + api_name=False, + show_api=False, + ) + + def execute( + request: gr.Request, + progress=gr.Progress(track_tqdm=True), + *args, + ): + key = _session_key(request) + cancel_event = threading.Event() + with _CANCEL_LOCK: + _CANCEL_EVENTS[key] = cancel_event + try: + values = create_inputs(*args) + values["_cancel_event"] = cancel_event + run_mode = values.pop("_run_mode", "single") + pk_models = values.pop("_pk_models", []) or [] + uploaded_files = values.pop("_batch_images", []) or [] + reference_role = values.pop("_reference_role", "auto") or "auto" + use_model_defaults = bool(values.pop("_pk_model_defaults", True)) + images = ( + load_uploaded_images(uploaded_files) + if run_mode + in { + MODE_MULTI_INDEPENDENT, + MODE_MULTI_MODEL_GRID, + MODE_MULTI_REFERENCE, + } + else [] + ) + plan = build_execution_plan( + values, + mode=run_mode, + extra_models=pk_models, + images=images, + reference_role=reference_role, + use_model_defaults=use_model_defaults, + ) + return execute_generation_plan( + plan, + generate_image_wrapper, + progress=progress, + cancel_event=cancel_event, + ) + except (TaskCancelledError, ExecutionPlanError) as exc: + raise gr.Error(str(exc)) from exc + finally: + with _CANCEL_LOCK: + if _CANCEL_EVENTS.get(key) is cancel_event: + _CANCEL_EVENTS.pop(key, None) + + def cancel_waiting(request: gr.Request): + with _CANCEL_LOCK: + cancel_event = _CANCEL_EVENTS.get(_session_key(request)) + if cancel_event is not None: + cancel_event.set() + + run_event = run_button.click( + fn=execute, + inputs=input_components, + outputs=[result_gallery, run_summary], + concurrency_id="gpu_generation", + concurrency_limit=CONFIG.gpu_concurrency, + trigger_mode="once", + show_progress="full", + show_progress_on=[result_gallery], + scroll_to_output=True, + api_name=False, + show_api=False, + ) + + ui_components[f"cancel_{prefix}"].click( + fn=cancel_waiting, + cancels=[run_event], + queue=False, + api_name=False, + show_api=False, + ) + ui_components[f"clear_result_{prefix}"].click( + fn=lambda: ([], "已清空本次结果。"), + outputs=[result_gallery, run_summary], + queue=False, + show_progress="hidden", + api_name=False, + show_api=False, + ) diff --git a/ui/guidance.py b/ui/guidance.py new file mode 100644 index 0000000000000000000000000000000000000000..0526d12974dc6de48b469539ce1b12e5452f6136 --- /dev/null +++ b/ui/guidance.py @@ -0,0 +1,122 @@ +"""Chinese-first task and model guidance generated from the existing registry.""" + +from __future__ import annotations + +from core.settings import ( + ARCHITECTURES_CONFIG, + FEATURES_CONFIG, + MODEL_DEFAULTS_CONFIG, + MODEL_MAP_CHECKPOINT, + MODEL_TYPE_MAP, +) +from imagegen_utils.app_utils import get_model_generation_defaults + + +TASK_HELP = { + "txt2img": "**文生图**:选择模型,写清主体、动作、构图、风格和光线,再点击生成。", + "img2img": "**图生图**:上传原图;重绘幅度越低越接近原图,越高改动越大。", + "inpaint": "**局部重绘**:上传图片并涂抹需要修改的区域;提示词只描述希望出现的新内容。", + "outpaint": "**扩图**:上传原图,设置向四周扩展的像素;提示词描述画面外应延续的内容。", + "hires_fix": "**高清修复**:上传图片,先用 1.5× 和 0.35–0.55 重绘幅度试跑,避免细节漂移。", +} + + +FEATURE_NAMES = { + "lora": "LoRA", + "controlnet": "ControlNet", + "anima_controlnet_lllite": "Anima ControlNet", + "diffsynth_controlnet": "DiffSynth ControlNet", + "krea2_controlnet": "Krea2 ControlNet", + "ipadapter": "IP-Adapter", + "flux1_ipadapter": "FLUX IP-Adapter", + "sd3_ipadapter": "SD3 IP-Adapter", + "style": "风格参考", + "embedding": "Embedding", + "conditioning": "区域提示", + "reference_latent": "多图编辑", + "hidream_o1_reference": "HiDream 参考图", + "joyai_image": "JoyAI 参考图", + "krea2_identity_edit": "Krea2 身份参考", + "krea2_style_reference": "Krea2 风格参考", + "qwen_image_edit": "Qwen 图片编辑", + "boogu_image_edit": "Boogu 图片编辑", + "reference_image": "Mage-Flow 参考图", + "vae": "VAE 替换", + "pid": "PiD 解码", +} + + +QUICK_PRESETS = [ + ("手动选择", "__manual__"), + ("快速通用 · Krea-2-Turbo", "Krea-2-Turbo"), + ("中文与文字 · Qwen-Image Lightning", "lightx2v/Qwen-Image-2512-Lightning"), + ("动漫角色 · Anima Turbo", "circlestone-labs/Anima-Turbo-v1.0"), + ("快速编辑 · Qwen-Image-Edit Lightning", "lightx2v/Qwen-Image-Edit-2511-Lightning"), + ("SDXL 动漫 · Animagine XL 4.0", "CagliostroLab/Animagine XL 4.0"), +] + + +def task_help(task_type: str) -> str: + return TASK_HELP.get(task_type, TASK_HELP["txt2img"]) + + +def model_hint(model_name: str) -> str: + info = MODEL_MAP_CHECKPOINT.get(model_name) + if not info: + return "请选择配置中已有的模型。" + + architecture = MODEL_TYPE_MAP.get(model_name, info[2]) + architecture_config = ARCHITECTURES_CONFIG.get("architectures", {}).get(architecture, {}) + workflow_type = architecture_config.get( + "model_type", architecture.lower().replace(" ", "").replace(".", "") + ) + defaults = get_model_generation_defaults( + model_name, workflow_type, MODEL_DEFAULTS_CONFIG + ) + features = FEATURES_CONFIG.get(workflow_type, {}).get("enabled_chains", []) + feature_text = "、".join(FEATURE_NAMES.get(item, item) for item in features[:6]) or "基础生成" + if len(features) > 6: + feature_text += f" 等 {len(features)} 项" + + tag_first_architectures = {"SDXL", "SD1.5", "Anima", "NewBie-Image"} + if architecture in tag_first_architectures: + language_tip = "更适合英文标签式 Prompt;中文意图可保留,但建议补充英文关键词。" + elif architecture in {"Qwen-Image", "Z-Image", "HunyuanImage", "ERNIE-Image"}: + language_tip = "可优先直接使用中文自然语言;涉及文字时把具体文字用引号写出。" + else: + language_tip = "可先用中文自然语言;若构图不稳定,再补充简短英文关键词。" + + edit_tip = "" + if "edit" in model_name.lower(): + edit_tip = " 这是编辑向模型,配合下方自动出现的参考图能力使用。" + + return ( + f"**{architecture} · 推荐参数**:{defaults.get('steps', 20)} 步," + f"CFG {defaults.get('cfg', 1.0)},{defaults.get('sampler_name', 'euler')} / " + f"{defaults.get('scheduler', 'simple')} \n" + f"**Prompt 建议**:{language_tip}{edit_tip} \n" + f"**当前可用扩展**:{feature_text}" + ) + + +def recommended_params(model_name: str) -> tuple: + """Return the registry defaults shown by the one-click reset control.""" + info = MODEL_MAP_CHECKPOINT.get(model_name) + if not info: + return 20, 1.0, "euler", "simple" + architecture = MODEL_TYPE_MAP.get(model_name, info[2]) + architecture_config = ARCHITECTURES_CONFIG.get("architectures", {}).get( + architecture, {} + ) + workflow_type = architecture_config.get( + "model_type", architecture.lower().replace(" ", "").replace(".", "") + ) + defaults = get_model_generation_defaults( + model_name, workflow_type, MODEL_DEFAULTS_CONFIG + ) + return ( + defaults.get("steps", 20), + defaults.get("cfg", 1.0), + defaults.get("sampler_name", "euler"), + defaults.get("scheduler", "simple"), + ) diff --git a/ui/layout.py b/ui/layout.py new file mode 100644 index 0000000000000000000000000000000000000000..b331594c988b9611f76e932df836675cca017060 --- /dev/null +++ b/ui/layout.py @@ -0,0 +1,86 @@ +"""Application layout: one shared workspace for all image tasks.""" + +from __future__ import annotations + +import gradio as gr + +from core.runtime_config import CONFIG +from .shared import studio_ui +from .theme import APP_CSS + + +def build_ui(event_handler_function): + ui_components = {} + theme = gr.themes.Soft( + primary_hue="indigo", + secondary_hue="violet", + neutral_hue="slate", + radius_size="lg", + ) + + with gr.Blocks( + theme=theme, + css=APP_CSS, + title="ImageGen Studio 中文版", + fill_width=True, + ) as demo: + gr.HTML( + """ + + ImageGen Studio + 一套界面完成文生图、图生图、局部重绘、扩图和高清修复。模型与任务切换会保留你的提示词和已上传素材。 + + + ① 选任务先决定生成、编辑,还是修复图片 + ② 选模型并描述不确定时使用快速方案和模型提示 + ③ 生成并迭代先用默认参数出图,再逐项微调 + + """ + ) + + ui_components.update(studio_ui.create_ui()) + + with gr.Accordion("使用说明与常见问题", open=False): + gr.Markdown( + """ +- **切换任务会丢内容吗?** 不会。提示词、模型、参数和上传素材都保留,只切换当前需要的控件。 +- **中文提示词是否可用?** Qwen-Image、Z-Image、HunyuanImage 等优先支持中文;SDXL 动漫模型更适合英文标签,模型说明会给出建议。 +- **为什么显示排队?** GPU 任务通过同一队列调度,避免 UI 和 MCP 同时抢占显存。等待期间可以修改表单,但同一按钮不会重复提交。 +- **第一次为什么较慢?** 首次使用某模型会下载权重;下载过程有互斥保护,避免并发请求重复下载或写坏文件。 +- **扩展能力为什么会变化?** LoRA、ControlNet、IP-Adapter 等只在当前模型兼容时显示;不兼容的隐藏状态不会送入生成管线。 + """ + ) + + gr.HTML( + """ + + """ + ) + + event_handler_function(ui_components, demo) + + high_level_names = set() + if CONFIG.enable_mcp: + try: + import mcp_tools as mcp + + high_level_names = getattr(mcp, "HIGH_LEVEL_MCP_API_NAMES", set()) + if hasattr(mcp, "register_high_level_mcp_apis"): + mcp.register_high_level_mcp_apis(demo) + mcp.cleanup_dependencies_api_names(demo) + elif hasattr(mcp, "MCP_FUNCTIONS") and isinstance(mcp.MCP_FUNCTIONS, list): + for func in mcp.MCP_FUNCTIONS: + gr.api(func) + except Exception as exc: + print(f"⚠️ MCP 接口注册失败:{exc}") + + # Only the intentional high-level MCP surface is public. + for fn in demo.fns.values(): + if getattr(fn, "api_name", None) not in high_level_names: + fn.show_api = False + + return demo diff --git a/ui/shared/studio_ui.py b/ui/shared/studio_ui.py new file mode 100644 index 0000000000000000000000000000000000000000..37b641b1b18f2c5a2114b54eb1ff69d7d9866a6d --- /dev/null +++ b/ui/shared/studio_ui.py @@ -0,0 +1,365 @@ +"""One shared, task-switchable UI instead of five duplicated forms.""" + +from __future__ import annotations + +import gradio as gr + +from comfy_integration.nodes import SAMPLER_CHOICES, SCHEDULER_CHOICES +from core.execution_plan import RUN_MODE_CHOICES +from core.runtime_config import CONFIG +from core.settings import ( + ARCHITECTURES_CONFIG, + MODEL_DEFAULTS_CONFIG, + MODEL_MAP_CHECKPOINT, + MODEL_TYPE_MAP, + RESOLUTION_MAP, +) +from ui.guidance import QUICK_PRESETS, model_hint, task_help +from .ui_components import ( + create_anima_controlnet_lllite_ui, + create_boogu_edit_ui, + create_category_filter_ui, + create_conditioning_ui, + create_controlnet_ui, + create_diffsynth_controlnet_ui, + create_embedding_ui, + create_flux1_ipadapter_ui, + create_hidream_o1_reference_ui, + create_ipadapter_ui, + create_joyai_reference_ui, + create_krea2_controlnet_ui, + create_krea2_identity_edit_ui, + create_krea2_reference_edit_ui, + create_lora_settings_ui, + create_model_architecture_filter_ui, + create_pid_ui, + create_qwen_image_edit_ui, + create_reference_image_ui, + create_reference_latent_ui, + create_sd3_ipadapter_ui, + create_style_ui, + create_vae_override_ui, +) + + +TASK_CHOICES = [ + ("✨ 文生图", "txt2img"), + ("🖼️ 图生图", "img2img"), + ("🖌️ 局部重绘", "inpaint"), + ("↔️ 扩图", "outpaint"), + ("🔎 高清修复", "hires_fix"), +] + +PROMPT_EXAMPLES = [ + ["一位银发少女站在雨夜车站,半身构图,电影感侧光,细腻插画,高质量"], + ["现代东方客厅,浅木色与米白配色,午后自然光,广角室内摄影"], + ["未来城市夜景,湿润街道倒影,霓虹灯,低机位,强烈纵深,电影概念设计"], +] + + +def create_ui() -> dict: + prefix = "studio" + components: dict = {"_task_prefixes": [(prefix, None)]} + default_values = MODEL_DEFAULTS_CONFIG.get("Default", {}) + default_model = next(iter(MODEL_MAP_CHECKPOINT), None) + default_architecture = MODEL_TYPE_MAP.get(default_model, "SDXL") + default_architecture_info = ARCHITECTURES_CONFIG.get("architectures", {}).get( + default_architecture, {} + ) + default_resolution_key = default_architecture_info.get("model_type", "sdxl") + default_resolution_map = RESOLUTION_MAP.get( + default_resolution_key, RESOLUTION_MAP.get("sdxl", {}) + ) + default_aspect = next(iter(default_resolution_map), "1:1 (Square)") + default_width, default_height = default_resolution_map.get(default_aspect, (1024, 1024)) + + components[f"task_type_{prefix}"] = gr.Radio( + choices=TASK_CHOICES, + value="txt2img", + label="1. 选择任务", + elem_id="task-switcher", + ) + components[f"task_help_{prefix}"] = gr.Markdown( + task_help("txt2img"), elem_classes="task-help" + ) + + with gr.Row(equal_height=False, elem_id="workspace-row"): + with gr.Column(scale=7, min_width=360): + with gr.Accordion("2. 选择模型", open=True): + components[f"quick_preset_{prefix}"] = gr.Dropdown( + choices=QUICK_PRESETS, + value="__manual__", + label="快速方案", + info="只是帮你定位模型;仍可继续调整所有参数。", + interactive=True, + ) + components.update(create_model_architecture_filter_ui(prefix)) + with gr.Row(): + components.update(create_category_filter_ui(prefix)) + components[f"base_model_{prefix}"] = gr.Dropdown( + label="具体模型", + choices=list(MODEL_MAP_CHECKPOINT.keys()), + value=default_model, + filterable=True, + allow_custom_value=False, + scale=3, + interactive=True, + ) + components[f"model_hint_{prefix}"] = gr.Markdown( + model_hint(default_model) if default_model else "暂无可用模型。", + elem_classes="model-hint", + ) + + with gr.Accordion("批量、多图与模型 PK(可选)", open=False): + components[f"run_mode_{prefix}"] = gr.Dropdown( + choices=RUN_MODE_CHOICES, + value="single", + label="运行方式", + info="所有模式都顺序执行,不会同时把多个大模型塞进显存。", + ) + components[f"pk_models_{prefix}"] = gr.Dropdown( + choices=list(MODEL_MAP_CHECKPOINT.keys()), + value=[], + multiselect=True, + max_choices=max(1, CONFIG.max_pk_models - 1), + label="额外对比模型", + info=f"当前模型会自动加入;最多合计 {CONFIG.max_pk_models} 个。", + filterable=True, + visible=False, + ) + components[f"batch_images_{prefix}"] = gr.File( + file_count="multiple", + file_types=["image"], + type="filepath", + allow_reordering=True, + label="批量输入 / 多图参考", + visible=False, + ) + with gr.Row(): + components[f"reference_role_{prefix}"] = gr.Dropdown( + choices=[ + ("自动匹配模型能力", "auto"), + ("人物 / 身份参考", "identity"), + ("风格参考", "style"), + ], + value="auto", + label="多图融合用途", + visible=False, + ) + components[f"pk_model_defaults_{prefix}"] = gr.Checkbox( + value=True, + label="PK 使用各模型推荐采样参数", + info="Prompt、尺寸与种子保持一致;步数和 CFG 按模型推荐值。", + visible=False, + ) + gr.Markdown( + "**怎么选:** 多图独立是 A→A′、B→B′;多图×多模型会执行图片和模型的组合;" + "多图融合是把整组图片同时交给 Qwen/Mage-Flow/JoyAI/Boogu/Krea/Flux 等兼容模型。" + ) + + with gr.Group(elem_classes="prompt-card"): + components[f"prompt_{prefix}"] = gr.Textbox( + label="3. 描述你想要的画面", + placeholder="主体 + 动作 + 场景 + 构图 + 风格 + 光线", + lines=4, + max_lines=8, + value=default_values.get("positive_prompt", ""), + ) + with gr.Accordion("负面提示词(可选)", open=False): + components[f"neg_prompt_{prefix}"] = gr.Textbox( + label="不希望出现的内容", + placeholder="例如:低质量、模糊、多余手指、水印", + lines=2, + value=default_values.get("negative_prompt", ""), + ) + gr.Examples( + examples=PROMPT_EXAMPLES, + inputs=[components[f"prompt_{prefix}"]], + label="点一下填入示例", + ) + + with gr.Group(visible=False) as source_panel: + components[f"source_image_{prefix}"] = gr.Image( + type="pil", + label="源图片", + sources=["upload", "clipboard"], + height=300, + ) + components[f"source_panel_{prefix}"] = source_panel + + with gr.Group(visible=False) as inpaint_panel: + gr.Markdown("涂抹需要替换的区域;未涂抹部分会尽量保留。") + components[f"inpaint_image_dict_{prefix}"] = gr.ImageEditor( + type="pil", + label="图片与蒙版", + sources=["upload", "clipboard"], + height=420, + ) + with gr.Row(): + components[f"inpaint_denoise_{prefix}"] = gr.Slider( + 0.0, 1.0, value=1.0, step=0.05, label="局部重绘幅度" + ) + components[f"grow_mask_by_{prefix}"] = gr.Slider( + 0, 64, value=6, step=1, label="蒙版外扩像素" + ) + components[f"inpaint_panel_{prefix}"] = inpaint_panel + + with gr.Group(visible=False) as img2img_panel: + components[f"img2img_denoise_{prefix}"] = gr.Slider( + 0.0, + 1.0, + value=0.7, + step=0.01, + label="重绘幅度", + info="0 更接近原图,1 改动最大。", + ) + components[f"img2img_panel_{prefix}"] = img2img_panel + + with gr.Group(visible=False) as outpaint_panel: + with gr.Row(): + components[f"left_{prefix}"] = gr.Slider(0, 512, 64, step=64, label="向左扩展") + components[f"right_{prefix}"] = gr.Slider(0, 512, 64, step=64, label="向右扩展") + with gr.Row(): + components[f"top_{prefix}"] = gr.Slider(0, 512, 64, step=64, label="向上扩展") + components[f"bottom_{prefix}"] = gr.Slider(0, 512, 64, step=64, label="向下扩展") + components[f"feathering_{prefix}"] = gr.Slider( + 0, 100, 10, step=1, label="接缝羽化 / 蒙版外扩" + ) + components[f"outpaint_panel_{prefix}"] = outpaint_panel + + with gr.Group(visible=False) as hires_panel: + with gr.Row(): + components[f"hires_upscaler_{prefix}"] = gr.Dropdown( + choices=["nearest-exact", "bilinear", "area", "bicubic", "bislerp"], + value="nearest-exact", + label="放大算法", + ) + components[f"hires_scale_by_{prefix}"] = gr.Slider( + 1.0, 4.0, 1.5, step=0.1, label="放大倍数" + ) + components[f"hires_denoise_{prefix}"] = gr.Slider( + 0.0, 1.0, 0.55, step=0.01, label="细节重绘幅度" + ) + components[f"hires_panel_{prefix}"] = hires_panel + + with gr.Group() as size_panel: + with gr.Row(): + components[f"aspect_ratio_{prefix}"] = gr.Dropdown( + label="画幅", + choices=list(default_resolution_map) or [default_aspect], + value=default_aspect, + interactive=True, + scale=2, + ) + components[f"width_{prefix}"] = gr.Number( + label="宽度", value=default_width, precision=0, interactive=True + ) + components[f"height_{prefix}"] = gr.Number( + label="高度", value=default_height, precision=0, interactive=True + ) + components[f"size_panel_{prefix}"] = size_panel + + with gr.Accordion("高级采样与运行参数", open=False): + with gr.Row(): + components[f"sampler_{prefix}"] = gr.Dropdown( + choices=SAMPLER_CHOICES, + value=default_values.get("sampler_name", "euler"), + label="采样器", + ) + components[f"scheduler_{prefix}"] = gr.Dropdown( + choices=SCHEDULER_CHOICES, + value=default_values.get("scheduler", "simple"), + label="调度器", + ) + with gr.Row(): + components[f"steps_{prefix}"] = gr.Slider( + 1, 100, default_values.get("steps", 8), step=1, label="采样步数" + ) + components[f"cfg_{prefix}"] = gr.Slider( + 1.0, 20.0, default_values.get("cfg", 1.0), step=0.1, label="CFG" + ) + with gr.Row(): + components[f"seed_{prefix}"] = gr.Number( + label="随机种子(-1 为随机)", value=-1, precision=0 + ) + components[f"batch_size_{prefix}"] = gr.Slider( + 1, + CONFIG.max_batch_size, + 1, + step=1, + label="单次生成数量", + info="数量越大,显存与 ZeroGPU 配额消耗越高。", + ) + with gr.Row(): + components[f"clip_skip_{prefix}"] = gr.Slider( + 1, 2, 1, step=1, label="Clip Skip", visible=False + ) + components[f"guidance_{prefix}"] = gr.Slider( + 1.0, 10.0, 3.5, step=0.1, label="FLUX Guidance", visible=False + ) + components[f"zero_gpu_{prefix}"] = gr.Dropdown( + choices=[("自动估算", 0), ("60 秒", 60), ("90 秒", 90), ("120 秒", 120)], + value=0, + label="ZeroGPU 运行时长", + info="通常保持自动;复杂高分辨率任务可手动提高。", + ) + with gr.Row(): + components[f"auto_model_params_{prefix}"] = gr.Checkbox( + value=True, + label="切模型时自动应用推荐采样参数", + info="关闭后会保留你手调的步数、CFG、采样器和调度器。", + scale=3, + ) + components[f"reset_model_params_{prefix}"] = gr.Button( + "恢复当前模型推荐值", size="sm", scale=1 + ) + + with gr.Column(scale=5, min_width=340, elem_id="result-column"): + with gr.Row(): + components[f"run_{prefix}"] = gr.Button( + "开始生成", variant="primary", size="lg", scale=3 + ) + components[f"cancel_{prefix}"] = gr.Button( + "取消排队", variant="stop", size="lg", scale=1 + ) + components[f"result_{prefix}"] = gr.Gallery( + label="生成结果", + show_label=True, + columns=2, + object_fit="contain", + height=720, + ) + components[f"run_summary_{prefix}"] = gr.Markdown( + "普通模式会在这里显示执行结果;PK/批量模式会逐项列出成功与失败。" + ) + components[f"clear_result_{prefix}"] = gr.Button("清空结果", size="sm") + gr.Markdown( + "生成结果包含 Prompt、参数和完整 ComfyUI 工作流元数据,下载 PNG 后可继续复现。", + elem_classes="result-note", + ) + + gr.Markdown("## 当前模型可用的扩展能力", elem_classes="advanced-title") + gr.Markdown("下方只显示当前模型兼容的能力;切换模型后会自动更新。") + components.update(create_lora_settings_ui(prefix)) + components.update(create_controlnet_ui(prefix)) + components.update(create_anima_controlnet_lllite_ui(prefix)) + components.update(create_diffsynth_controlnet_ui(prefix)) + components.update(create_krea2_controlnet_ui(prefix)) + components.update(create_ipadapter_ui(prefix)) + components.update(create_flux1_ipadapter_ui(prefix)) + components.update(create_sd3_ipadapter_ui(prefix)) + components.update(create_embedding_ui(prefix)) + components.update(create_style_ui(prefix)) + components.update(create_conditioning_ui(prefix)) + components.update(create_reference_latent_ui(prefix)) + components.update(create_hidream_o1_reference_ui(prefix)) + components.update(create_joyai_reference_ui(prefix)) + components.update(create_krea2_identity_edit_ui(prefix)) + components.update(create_krea2_reference_edit_ui(prefix)) + components.update(create_qwen_image_edit_ui(prefix)) + components.update(create_boogu_edit_ui(prefix)) + components.update(create_reference_image_ui(prefix)) + components.update(create_vae_override_ui(prefix)) + components.update(create_pid_ui(prefix)) + + return components diff --git a/ui/shared/ui_components.py b/ui/shared/ui_components.py new file mode 100644 index 0000000000000000000000000000000000000000..e76c6b39aaf9e0cbe756e0e0b9a82257ae215c34 --- /dev/null +++ b/ui/shared/ui_components.py @@ -0,0 +1,891 @@ +import gradio as gr +from comfy_integration.nodes import SAMPLER_CHOICES, SCHEDULER_CHOICES +from core.settings import ( + MAX_LORAS, LORA_SOURCE_CHOICES, MAX_EMBEDDINGS, MAX_CONDITIONINGS, + MAX_CONTROLNETS, MAX_IPADAPTERS, RESOLUTION_MAP, ARCHITECTURES_CONFIG, + MODEL_MAP_CHECKPOINT, MODEL_TYPE_MAP, FEATURES_CONFIG, ARCH_CATEGORIES_MAP, + VAE_DIR, MODEL_DEFAULTS_CONFIG +) +import yaml +import os +from functools import lru_cache +from imagegen_utils.app_utils import save_uploaded_file_with_hash + +default_model_name = list(MODEL_MAP_CHECKPOINT.keys())[0] if MODEL_MAP_CHECKPOINT else None +default_m_type = MODEL_TYPE_MAP.get(default_model_name, "SDXL") if default_model_name else "SDXL" +default_architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {}) +default_arch_model_type = default_architectures_dict.get(default_m_type, {}).get("model_type", default_m_type.lower().replace(" ", "").replace(".", "")) +default_arch_features = FEATURES_CONFIG.get(default_arch_model_type, {}) +default_enabled_chains = default_arch_features.get('enabled_chains', []) + +default_vals = MODEL_DEFAULTS_CONFIG.get('Default', {}) +DEFAULT_STEPS = default_vals.get('steps', 20) +DEFAULT_CFG = default_vals.get('cfg', 5.0) +DEFAULT_SAMPLER = default_vals.get('sampler_name', 'euler') +DEFAULT_SCHEDULER = default_vals.get('scheduler', 'simple') +DEFAULT_POS_PROMPT = default_vals.get('positive_prompt', '') +DEFAULT_NEG_PROMPT = default_vals.get('negative_prompt', '') + +@lru_cache(maxsize=1) +def get_ipadapter_config_from_yaml(): + try: + _PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + _IPADAPTER_LIST_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'ipadapter.yaml') + with open(_IPADAPTER_LIST_PATH, 'r', encoding='utf-8') as f: + config = yaml.safe_load(f) + return config + except Exception as e: + print(f"Warning: Could not load ipadapter.yaml for UI components: {e}") + return {} + +def get_ipadapter_presets(arch="SDXL"): + config = get_ipadapter_config_from_yaml() + presets = [] + if config: + std_presets = config.get("IPAdapter_presets", {}).get(arch, []) + face_presets = config.get("IPAdapter_FaceID_presets", {}).get(arch, []) + if std_presets: + presets.extend(std_presets) + if face_presets: + presets.extend(face_presets) + return presets if presets else ["STANDARD (medium strength)"] + +def create_model_architecture_filter_ui(prefix): + components = {} + ordered_architectures = ARCHITECTURES_CONFIG.get("architecture_order", []) + choices = ["ALL"] + ordered_architectures + + components[f'model_arch_{prefix}'] = gr.Dropdown( + label="模型架构", + choices=choices, + value="ALL", + interactive=True, + visible=True, + filterable=True, + info="用于缩小模型范围;保持 ALL 可直接搜索全部模型。", + ) + return components + +def create_category_filter_ui(prefix): + valid_cats = list(set(cat for cats in ARCH_CATEGORIES_MAP.values() for cat in cats)) + cat_choices = ["ALL"] + sorted(valid_cats) + + components = {} + components[f'model_cat_{prefix}'] = gr.Dropdown( + label="模型分类", + choices=cat_choices, + value="ALL", + interactive=True, + scale=1, + allow_custom_value=False, + info="主要用于 SDXL 的 NoobAI、Illustrious、Pony 等分类。", + ) + return components + +def create_base_parameter_ui(prefix, defaults=None): + if defaults is None: + defaults = {} + + components = {} + + with gr.Row(): + components[f'aspect_ratio_{prefix}'] = gr.Dropdown( + label="Aspect Ratio", + choices=list(RESOLUTION_MAP.get('sdxl', {}).keys()), + value="1:1 (Square)", + interactive=True, + allow_custom_value=True + ) + with gr.Row(): + components[f'width_{prefix}'] = gr.Number(label="Width", value=defaults.get('w', 1024), interactive=True) + components[f'height_{prefix}'] = gr.Number(label="Height", value=defaults.get('h', 1024), interactive=True) + with gr.Row(): + components[f'sampler_{prefix}'] = gr.Dropdown( + label="Sampler", + choices=SAMPLER_CHOICES, + value=DEFAULT_SAMPLER if DEFAULT_SAMPLER in SAMPLER_CHOICES else (SAMPLER_CHOICES[0] if SAMPLER_CHOICES else 'euler') + ) + components[f'scheduler_{prefix}'] = gr.Dropdown( + label="Scheduler", + choices=SCHEDULER_CHOICES, + value=DEFAULT_SCHEDULER if DEFAULT_SCHEDULER in SCHEDULER_CHOICES else (SCHEDULER_CHOICES[0] if SCHEDULER_CHOICES else 'simple') + ) + with gr.Row(): + components[f'steps_{prefix}'] = gr.Slider(label="Steps", minimum=1, maximum=100, step=1, value=DEFAULT_STEPS) + components[f'cfg_{prefix}'] = gr.Slider(label="CFG Scale", minimum=1.0, maximum=20.0, step=0.1, value=DEFAULT_CFG) + with gr.Row(): + components[f'seed_{prefix}'] = gr.Number(label="Seed (-1 for random)", value=-1, precision=0) + components[f'batch_size_{prefix}'] = gr.Slider(label="Batch Size", minimum=1, maximum=16, step=1, value=1) + with gr.Row(): + components[f'clip_skip_{prefix}'] = gr.Slider(label="Clip Skip", minimum=1, maximum=2, step=1, value=1, visible=False, interactive=True) + components[f'guidance_{prefix}'] = gr.Slider(label="Guidance (FLUX)", minimum=1.0, maximum=10.0, step=0.1, value=3.5, visible=False, interactive=True) + components[f'zero_gpu_{prefix}'] = gr.Number(label="ZeroGPU Duration (s)", value=None, placeholder="Default: 60s, Max: 120s", info="Optional: Set how long to reserve the GPU.") + + return components + + +def create_lora_settings_ui(prefix: str): + components = {} + + lora_rows, lora_sources, lora_ids, lora_scales, lora_uploads = [], [], [], [], [] + + with gr.Accordion("LoRA 设置", open=False, visible=('lora' in default_enabled_chains)) as lora_accordion: + components[f'lora_accordion_{prefix}'] = lora_accordion + gr.Markdown("💡 Civitai 请填写 **Version ID**,不要填 Model ID;Hugging Face 请填写 `repo_id/文件路径`。") + components[f'lora_count_state_{prefix}'] = gr.State(1) + + for i in range(MAX_LORAS): + with gr.Row(visible=i==0) as row: + source = gr.Dropdown(label=f"LoRA 来源 {i+1}", choices=LORA_SOURCE_CHOICES, value=LORA_SOURCE_CHOICES[0], scale=1) + lora_id = gr.Textbox(label="Civitai Version ID / HF 文件 / 已上传文件", scale=2, type="text") + scale = gr.Slider(label="权重", minimum=0.0, maximum=2.0, step=0.05, value=1.0, scale=1) + upload = gr.UploadButton(label="上传", file_types=[".safetensors"], scale=1) + + lora_rows.append(row) + lora_sources.append(source) + lora_ids.append(lora_id) + lora_scales.append(scale) + lora_uploads.append(upload) + + with gr.Row(): + components[f'add_lora_button_{prefix}'] = gr.Button("添加 LoRA", variant="secondary") + components[f'delete_lora_button_{prefix}'] = gr.Button("移除 LoRA", variant="secondary", visible=False) + + components[f'lora_rows_{prefix}'] = lora_rows + components[f'lora_sources_{prefix}'] = lora_sources + components[f'lora_ids_{prefix}'] = lora_ids + components[f'lora_scales_{prefix}'] = lora_scales + components[f'lora_uploads_{prefix}'] = lora_uploads + + all_lora_components_flat = [] + for i in range(MAX_LORAS): + all_lora_components_flat.extend([lora_sources[i], lora_ids[i], lora_scales[i], lora_uploads[i]]) + components[f'all_lora_components_flat_{prefix}'] = all_lora_components_flat + + return components + +def create_controlnet_ui(prefix: str, max_units=MAX_CONTROLNETS): + components = {} + key = lambda name: f"{name}_{prefix}" + + with gr.Accordion("ControlNet 设置", open=False, visible=('controlnet' in default_enabled_chains)) as accordion: + components[key('controlnet_accordion')] = accordion + + cn_rows, images, series, types, strengths, filepaths = [], [], [], [], [], [] + components.update({ + key('controlnet_rows'): cn_rows, + key('controlnet_images'): images, + key('controlnet_series'): series, + key('controlnet_types'): types, + key('controlnet_strengths'): strengths, + key('controlnet_filepaths'): filepaths + }) + + for i in range(max_units): + with gr.Row(visible=(i < 1)) as row: + with gr.Column(scale=1): + images.append(gr.Image(label=f"控制图 {i+1}", type="pil", sources=["upload"], height=256)) + with gr.Column(scale=2): + types.append(gr.Dropdown(label="类型", choices=[], interactive=True, allow_custom_value=True)) + series.append(gr.Dropdown(label="系列", choices=[], interactive=True, allow_custom_value=True)) + strengths.append(gr.Slider(label="强度", minimum=0.0, maximum=2.0, step=0.05, value=1.0, interactive=True)) + filepaths.append(gr.State(None)) + cn_rows.append(row) + + with gr.Row(): + components[key('add_controlnet_button')] = gr.Button("✚ 添加 ControlNet") + components[key('delete_controlnet_button')] = gr.Button("➖ 移除 ControlNet", visible=False) + components[key('controlnet_count_state')] = gr.State(1) + + all_cn_components_flat = [] + for i in range(max_units): + all_cn_components_flat.extend([ + images[i], types[i], series[i], strengths[i], filepaths[i] + ]) + components[key('all_controlnet_components_flat')] = all_cn_components_flat + + return components + +def create_krea2_controlnet_ui(prefix: str, max_units=MAX_CONTROLNETS): + components = {} + key = lambda name: f"{name}_{prefix}" + + with gr.Accordion("Krea2 ControlNet 设置", open=False, visible=('krea2_controlnet' in default_enabled_chains)) as accordion: + components[key('krea2_controlnet_accordion')] = accordion + gr.Markdown("💡 由 [facok/comfyui-krea2-controlnet](https://github.com/facok/comfyui-krea2-controlnet) 节点处理。") + + cn_rows, images, series, types, strengths, filepaths = [], [], [], [], [], [] + components.update({ + key('krea2_controlnet_rows'): cn_rows, + key('krea2_controlnet_images'): images, + key('krea2_controlnet_series'): series, + key('krea2_controlnet_types'): types, + key('krea2_controlnet_strengths'): strengths, + key('krea2_controlnet_filepaths'): filepaths + }) + + for i in range(max_units): + with gr.Row(visible=(i < 1)) as row: + with gr.Column(scale=1): + images.append(gr.Image(label=f"控制图 {i+1}", type="pil", sources=["upload"], height=256)) + with gr.Column(scale=2): + types.append(gr.Dropdown(label="类型", choices=[], interactive=True, allow_custom_value=True)) + series.append(gr.Dropdown(label="系列", choices=[], interactive=True, allow_custom_value=True)) + strengths.append(gr.Slider(label="强度", minimum=0.0, maximum=2.0, step=0.05, value=1.0, interactive=True)) + filepaths.append(gr.State(None)) + cn_rows.append(row) + + with gr.Row(): + components[key('add_krea2_controlnet_button')] = gr.Button("✚ 添加 Krea2 ControlNet") + components[key('delete_krea2_controlnet_button')] = gr.Button("➖ 移除 Krea2 ControlNet", visible=False) + components[key('krea2_controlnet_count_state')] = gr.State(1) + + all_cn_components_flat = [] + for i in range(max_units): + all_cn_components_flat.extend([ + images[i], types[i], series[i], strengths[i], filepaths[i] + ]) + components[key('all_krea2_controlnet_components_flat')] = all_cn_components_flat + + return components + +def create_anima_controlnet_lllite_ui(prefix: str, max_units=MAX_CONTROLNETS): + components = {} + key = lambda name: f"{name}_{prefix}" + + with gr.Accordion("Anima ControlNet LLLite 设置", open=False, visible=('anima_controlnet_lllite' in default_enabled_chains)) as accordion: + components[key('anima_controlnet_lllite_accordion')] = accordion + + cn_rows, images, series, types, strengths, filepaths, start_percents, end_percents = [], [], [], [], [], [], [], [] + components.update({ + key('anima_controlnet_lllite_rows'): cn_rows, + key('anima_controlnet_lllite_images'): images, + key('anima_controlnet_lllite_series'): series, + key('anima_controlnet_lllite_types'): types, + key('anima_controlnet_lllite_strengths'): strengths, + key('anima_controlnet_lllite_filepaths'): filepaths, + key('anima_controlnet_lllite_start_percents'): start_percents, + key('anima_controlnet_lllite_end_percents'): end_percents + }) + + for i in range(max_units): + with gr.Row(visible=(i < 1)) as row: + with gr.Column(scale=1): + images.append(gr.Image(label=f"控制图 {i+1}", type="pil", sources=["upload"], height=256)) + with gr.Column(scale=2): + types.append(gr.Dropdown(label="类型", choices=[], interactive=True, allow_custom_value=True)) + series.append(gr.Dropdown(label="系列", choices=[], interactive=True, allow_custom_value=True)) + strengths.append(gr.Slider(label="强度", minimum=0.0, maximum=2.0, step=0.05, value=1.0, interactive=True)) + with gr.Row(visible=False): + start_percents.append(gr.State(0.0)) + end_percents.append(gr.State(1.0)) + filepaths.append(gr.State(None)) + cn_rows.append(row) + + with gr.Row(): + components[key('add_anima_controlnet_lllite_button')] = gr.Button("✚ 添加 LLLite") + components[key('delete_anima_controlnet_lllite_button')] = gr.Button("➖ 移除 LLLite", visible=False) + components[key('anima_controlnet_lllite_count_state')] = gr.State(1) + + all_cn_components_flat = [] + for i in range(max_units): + all_cn_components_flat.extend([ + images[i], types[i], series[i], strengths[i], filepaths[i], start_percents[i], end_percents[i] + ]) + components[key('all_anima_controlnet_lllite_components_flat')] = all_cn_components_flat + + return components + +def create_diffsynth_controlnet_ui(prefix: str, max_units=MAX_CONTROLNETS): + components = {} + key = lambda name: f"{name}_{prefix}" + + with gr.Accordion("DiffSynth ControlNet 设置", open=False, visible=('diffsynth_controlnet' in default_enabled_chains)) as accordion: + components[key('diffsynth_controlnet_accordion')] = accordion + + cn_rows, images, series, types, strengths, filepaths = [], [], [], [], [], [] + components.update({ + key('diffsynth_controlnet_rows'): cn_rows, + key('diffsynth_controlnet_images'): images, + key('diffsynth_controlnet_series'): series, + key('diffsynth_controlnet_types'): types, + key('diffsynth_controlnet_strengths'): strengths, + key('diffsynth_controlnet_filepaths'): filepaths + }) + + for i in range(max_units): + with gr.Row(visible=(i < 1)) as row: + with gr.Column(scale=1): + images.append(gr.Image(label=f"控制图 {i+1}", type="pil", sources=["upload"], height=256)) + with gr.Column(scale=2): + types.append(gr.Dropdown(label="类型", choices=[], interactive=True, allow_custom_value=True)) + series.append(gr.Dropdown(label="系列", choices=[], interactive=True, allow_custom_value=True)) + strengths.append(gr.Slider(label="强度", minimum=0.0, maximum=2.0, step=0.05, value=1.0, interactive=True)) + filepaths.append(gr.State(None)) + cn_rows.append(row) + + with gr.Row(): + components[key('add_diffsynth_controlnet_button')] = gr.Button("✚ 添加 DiffSynth ControlNet") + components[key('delete_diffsynth_controlnet_button')] = gr.Button("➖ 移除 DiffSynth ControlNet", visible=False) + components[key('diffsynth_controlnet_count_state')] = gr.State(1) + + all_cn_components_flat = [] + for i in range(max_units): + all_cn_components_flat.extend([ + images[i], types[i], series[i], strengths[i], filepaths[i] + ]) + components[key('all_diffsynth_controlnet_components_flat')] = all_cn_components_flat + + return components + +def create_ipadapter_ui(prefix: str, max_units=MAX_IPADAPTERS): + components = {} + key = lambda name: f"{name}_{prefix}" + + sdxl_presets = get_ipadapter_presets("SDXL") + default_preset = sdxl_presets[0] if sdxl_presets else None + + with gr.Accordion("IP-Adapter 设置", open=False, visible=('ipadapter' in default_enabled_chains)) as accordion: + components[key('ipadapter_accordion')] = accordion + gr.Markdown("💡 由 [cubiq/ComfyUI_IPAdapter_plus](https://github.com/cubiq/ComfyUI_IPAdapter_plus) 节点处理。") + + with gr.Row(): + components[key('ipadapter_final_preset')] = gr.Dropdown( + label="预设(应用于全部参考图)", + choices=sdxl_presets, + value=default_preset, + interactive=True, + allow_custom_value=True + ) + components[key('ipadapter_embeds_scaling')] = gr.Dropdown( + label="特征缩放方式", + choices=['V only', 'K+V', 'K+V w/ C penalty', 'K+mean(V) w/ C penalty'], + value='V only', + interactive=True + ) + + with gr.Row(): + components[key('ipadapter_combine_method')] = gr.Dropdown( + label="合并方式", + choices=["concat", "add", "subtract", "average", "norm average", "max", "min"], + value="concat", + interactive=True + ) + components[key('ipadapter_final_weight')] = gr.Slider(label="最终权重", minimum=0.0, maximum=2.0, step=0.05, value=1.0, interactive=True) + components[key('ipadapter_final_lora_strength')] = gr.Slider(label="最终 LoRA 强度", minimum=0.0, maximum=2.0, step=0.05, value=0.6, interactive=True, visible=False) + + gr.Markdown("---") + + ipa_rows, images, weights, lora_strengths = [], [], [], [] + components.update({ + key('ipadapter_rows'): ipa_rows, + key('ipadapter_images'): images, + key('ipadapter_weights'): weights, + key('ipadapter_lora_strengths'): lora_strengths + }) + + for i in range(max_units): + with gr.Row(visible=(i < 1)) as row: + with gr.Column(scale=1): + images.append(gr.Image(label=f"IP-Adapter 参考图 {i+1}", type="pil", sources=["upload"], height=256)) + with gr.Column(scale=2): + weights.append(gr.Slider(label="权重", minimum=0.0, maximum=2.0, step=0.05, value=1.0, interactive=True)) + lora_strengths.append(gr.Slider(label="LoRA 强度", minimum=0.0, maximum=2.0, step=0.05, value=0.6, interactive=True, visible=False)) + ipa_rows.append(row) + + with gr.Row(): + components[key('add_ipadapter_button')] = gr.Button("✚ 添加 IP-Adapter") + components[key('delete_ipadapter_button')] = gr.Button("➖ 移除 IP-Adapter", visible=False) + components[key('ipadapter_count_state')] = gr.State(1) + + all_ipa_components_flat = images + weights + lora_strengths + all_ipa_components_flat += [ + components[key('ipadapter_final_preset')], + components[key('ipadapter_final_weight')], + components[key('ipadapter_final_lora_strength')], + components[key('ipadapter_embeds_scaling')], + components[key('ipadapter_combine_method')], + ] + components[key('all_ipadapter_components_flat')] = all_ipa_components_flat + + return components + +def create_flux1_ipadapter_ui(prefix: str, max_units=MAX_IPADAPTERS): + components = {} + key = lambda name: f"{name}_{prefix}" + + with gr.Accordion("FLUX.1 IP-Adapter 设置", open=False, visible=('flux1_ipadapter' in default_enabled_chains)) as accordion: + components[key('flux1_ipadapter_accordion')] = accordion + gr.Markdown("💡 由 [Shakker-Labs/ComfyUI-IPAdapter-Flux](https://github.com/Shakker-Labs/ComfyUI-IPAdapter-Flux) 节点处理。") + + ipa_rows, images, weights, start_percents, end_percents = [], [], [], [], [] + components.update({ + key('flux1_ipadapter_rows'): ipa_rows, + key('flux1_ipadapter_images'): images, + key('flux1_ipadapter_weights'): weights, + key('flux1_ipadapter_start_percents'): start_percents, + key('flux1_ipadapter_end_percents'): end_percents, + }) + + for i in range(max_units): + with gr.Row(visible=(i < 1)) as row: + with gr.Column(scale=1): + images.append(gr.Image(label=f"IP-Adapter 参考图 {i+1}", type="pil", sources=["upload"], height=256)) + with gr.Column(scale=2): + weights.append(gr.Slider(label="权重", minimum=0.0, maximum=2.0, step=0.05, value=0.6, interactive=True)) + with gr.Row(): + start_percents.append(gr.Slider(label="开始位置", minimum=0.0, maximum=1.0, step=0.01, value=0.0, interactive=True)) + end_percents.append(gr.Slider(label="结束位置", minimum=0.0, maximum=1.0, step=0.01, value=0.6, interactive=True)) + ipa_rows.append(row) + + with gr.Row(): + components[key('add_flux1_ipadapter_button')] = gr.Button("✚ 添加 FLUX IP-Adapter") + components[key('delete_flux1_ipadapter_button')] = gr.Button("➖ 移除 FLUX IP-Adapter", visible=False) + components[key('flux1_ipadapter_count_state')] = gr.State(1) + + all_flux1_ipa_components_flat = images + weights + start_percents + end_percents + components[key('all_flux1_ipadapter_components_flat')] = all_flux1_ipa_components_flat + + return components + +def create_sd3_ipadapter_ui(prefix: str, max_units=MAX_IPADAPTERS): + components = {} + key = lambda name: f"{name}_{prefix}" + + with gr.Accordion("SD3 IP-Adapter 设置", open=False, visible=('sd3_ipadapter' in default_enabled_chains)) as accordion: + components[key('sd3_ipadapter_accordion')] = accordion + gr.Markdown("💡 由 [Slickytail/ComfyUI-InstantX-IPAdapter-SD3](https://github.com/Slickytail/ComfyUI-InstantX-IPAdapter-SD3) 节点处理。") + + ipa_rows, images, weights, start_percents, end_percents = [], [], [], [], [] + components.update({ + key('sd3_ipadapter_rows'): ipa_rows, + key('sd3_ipadapter_images'): images, + key('sd3_ipadapter_weights'): weights, + key('sd3_ipadapter_start_percents'): start_percents, + key('sd3_ipadapter_end_percents'): end_percents, + }) + + for i in range(max_units): + with gr.Row(visible=(i < 1)) as row: + with gr.Column(scale=1): + images.append(gr.Image(label=f"IP-Adapter 参考图 {i+1}", type="pil", sources=["upload"], height=256)) + with gr.Column(scale=2): + weights.append(gr.Slider(label="权重", minimum=0.0, maximum=2.0, step=0.05, value=0.5, interactive=True)) + with gr.Row(): + start_percents.append(gr.Slider(label="开始位置", minimum=0.0, maximum=1.0, step=0.01, value=0.0, interactive=True)) + end_percents.append(gr.Slider(label="结束位置", minimum=0.0, maximum=1.0, step=0.01, value=1.0, interactive=True)) + ipa_rows.append(row) + + with gr.Row(): + components[key('add_sd3_ipadapter_button')] = gr.Button("✚ 添加 SD3 IP-Adapter") + components[key('delete_sd3_ipadapter_button')] = gr.Button("➖ 移除 SD3 IP-Adapter", visible=False) + components[key('sd3_ipadapter_count_state')] = gr.State(1) + + all_sd3_ipa_components_flat = images + weights + start_percents + end_percents + components[key('all_sd3_ipadapter_components_flat')] = all_sd3_ipa_components_flat + + return components + +def create_style_ui(prefix: str): + components = {} + key = lambda name: f"{name}_{prefix}" + + with gr.Accordion("FLUX.1 风格参考", open=False, visible=('style' in default_enabled_chains)) as accordion: + components[key('style_accordion')] = accordion + + style_rows, images, strengths = [], [], [] + components.update({ + key('style_rows'): style_rows, + key('style_images'): images, + key('style_strengths'): strengths + }) + + for i in range(5): + with gr.Row(visible=(i < 1)) as row: + with gr.Column(scale=1): + images.append(gr.Image(label=f"Style Image {i+1}", type="pil", sources=["upload"], height=256)) + with gr.Column(scale=2): + strengths.append(gr.Slider(label="强度", minimum=0.0, maximum=2.0, step=0.05, value=1.0, interactive=True)) + style_rows.append(row) + + with gr.Row(): + components[key('add_style_button')] = gr.Button("✚ 添加风格参考图") + components[key('delete_style_button')] = gr.Button("➖ 移除风格参考图", visible=False) + components[key('style_count_state')] = gr.State(1) + + all_style_components_flat = images + strengths + components[key('all_style_components_flat')] = all_style_components_flat + + return components + +def create_embedding_ui(prefix: str): + components = {} + key = lambda name: f"{name}_{prefix}" + + with gr.Accordion("Embedding 设置", open=False, visible=('embedding' in default_enabled_chains)) as accordion: + components[key('embedding_accordion')] = accordion + gr.Markdown("💡 Civitai 请填写 Version ID;Hugging Face 请填写 `repo_id/文件路径`。下载后在正面或负面提示词中写入 `embedding:文件名` 才会生效。") + + embedding_rows, sources, ids, files, upload_buttons = [], [], [], [], [] + components.update({ + key('embedding_rows'): embedding_rows, + key('embeddings_sources'): sources, + key('embeddings_ids'): ids, + key('embeddings_files'): files, + key('embeddings_uploads'): upload_buttons + }) + + for i in range(MAX_EMBEDDINGS): + with gr.Row(visible=(i < 1)) as row: + sources.append(gr.Dropdown(label=f"Embedding 来源 {i+1}", choices=LORA_SOURCE_CHOICES, value="Civitai", scale=1, interactive=True)) + ids.append(gr.Textbox(label="Civitai Version ID / HF 文件 / 已上传文件", scale=3, interactive=True, type="text")) + upload_btn = gr.UploadButton("上传", file_types=[".safetensors"], scale=1) + files.append(gr.State(None)) + upload_buttons.append(upload_btn) + embedding_rows.append(row) + + with gr.Row(): + components[key('add_embedding_button')] = gr.Button("✚ 添加 Embedding") + components[key('delete_embedding_button')] = gr.Button("➖ 移除 Embedding", visible=False) + components[key('embedding_count_state')] = gr.State(1) + + all_embedding_components_flat = [] + for i in range(MAX_EMBEDDINGS): + all_embedding_components_flat.extend([sources[i], ids[i], files[i]]) + components[key('all_embedding_components_flat')] = all_embedding_components_flat + + return components + +def create_conditioning_ui(prefix: str): + components = {} + key = lambda name: f"{name}_{prefix}" + + with gr.Accordion("区域提示设置", open=False, visible=('conditioning' in default_enabled_chains)) as accordion: + components[key('conditioning_accordion')] = accordion + gr.Markdown("💡 为矩形区域设置单独提示词;坐标 X、Y 从画面左上角开始计算。") + + cond_rows, prompts, widths, heights, xs, ys, strengths = [], [], [], [], [], [], [] + components.update({ + key('conditioning_rows'): cond_rows, + key('conditioning_prompts'): prompts, + key('conditioning_widths'): widths, + key('conditioning_heights'): heights, + key('conditioning_xs'): xs, + key('conditioning_ys'): ys, + key('conditioning_strengths'): strengths + }) + + for i in range(MAX_CONDITIONINGS): + with gr.Column(visible=(i < 1)) as row_wrapper: + prompts.append(gr.Textbox(label=f"区域提示词 {i+1}", lines=2, interactive=True)) + with gr.Row(): + xs.append(gr.Number(label="X", value=0, interactive=True, step=8, scale=1)) + ys.append(gr.Number(label="Y", value=0, interactive=True, step=8, scale=1)) + widths.append(gr.Number(label="宽度", value=512, interactive=True, step=8, scale=1)) + heights.append(gr.Number(label="高度", value=512, interactive=True, step=8, scale=1)) + strengths.append(gr.Slider(label="强度", minimum=0.1, maximum=2.0, step=0.05, value=1.0, interactive=True, scale=2)) + cond_rows.append(row_wrapper) + + with gr.Row(): + components[key('add_conditioning_button')] = gr.Button("✚ 添加区域") + components[key('delete_conditioning_button')] = gr.Button("➖ 移除区域", visible=False) + components[key('conditioning_count_state')] = gr.State(1) + + all_cond_components_flat = prompts + widths + heights + xs + ys + strengths + components[key('all_conditioning_components_flat')] = all_cond_components_flat + + return components + +def on_vae_upload(file_obj): + if not file_obj: + return gr.update(), gr.update(), None + + hashed_filename = save_uploaded_file_with_hash(file_obj, VAE_DIR) + return hashed_filename, "File", file_obj + +def create_vae_override_ui(prefix: str): + components = {} + key = lambda name: f"{name}_{prefix}" + source_choices = ["None"] + LORA_SOURCE_CHOICES + + with gr.Accordion("替换 VAE", open=False, visible=('vae' in default_enabled_chains)) as vae_accordion: + components[key('vae_accordion')] = vae_accordion + gr.Markdown("💡 Civitai 请填写 Version ID;Hugging Face 请填写 `repo_id/文件路径`。") + with gr.Row(): + components[key('vae_source')] = gr.Dropdown( + label="VAE 来源", + choices=source_choices, + value="None", + scale=1, + interactive=True + ) + components[key('vae_id')] = gr.Textbox( + label="Civitai Version ID / HF 文件 / 已上传文件", + scale=3, + interactive=True, + type="text" + ) + upload_btn = gr.UploadButton( + "上传", + file_types=[".safetensors"], + scale=1 + ) + components[key('vae_upload_button')] = upload_btn + components[key('vae_file')] = gr.State(None) + + upload_btn.upload( + fn=on_vae_upload, + inputs=[upload_btn], + outputs=[components[key('vae_id')], components[key('vae_source')], components[key('vae_file')]] + ) + + return components + +def create_reference_latent_ui(prefix: str, max_units=10): + components = {} + key = lambda name: f"{name}_{prefix}" + + with gr.Accordion("多图参考编辑", open=False, visible=('reference_latent' in default_enabled_chains)) as ref_accordion: + components[key('reference_latent_accordion')] = ref_accordion + gr.Markdown("💡 一张参考图用于图片编辑,多张参考图用于图片组合;仅兼容支持多模态输入的模型。") + + ref_image_groups = [] + ref_image_inputs = [] + with gr.Row(): + for i in range(max_units): + with gr.Column(visible=(i < 1), min_width=160) as img_col: + img_comp = gr.Image(type="pil", label=f"参考图 {i+1}", sources=["upload"], height=150) + ref_image_groups.append(img_col) + ref_image_inputs.append(img_comp) + + components[key('reference_latent_rows')] = ref_image_groups + components[key('reference_latent_images')] = ref_image_inputs + + with gr.Row(): + components[key('add_reference_latent_button')] = gr.Button("✚ 添加参考图") + components[key('delete_reference_latent_button')] = gr.Button("➖ 移除参考图", visible=False) + components[key('reference_latent_count_state')] = gr.State(1) + + components[key('all_reference_latent_components_flat')] = ref_image_inputs + + return components + +def create_hidream_o1_reference_ui(prefix: str, max_units=10): + components = {} + key = lambda name: f"{name}_{prefix}" + + with gr.Accordion("HiDream-O1 参考图编辑", open=False, visible=('hidream_o1_reference' in default_enabled_chains)) as ref_accordion: + components[key('hidream_o1_reference_accordion')] = ref_accordion + gr.Markdown("💡 建议使用 **HiDream-O1-Image-Dev** 并设置约 **4MP** 分辨率;一张图用于编辑,多张图用于组合。") + + ref_image_groups = [] + ref_image_inputs = [] + with gr.Row(): + for i in range(max_units): + with gr.Column(visible=(i < 1), min_width=160) as img_col: + img_comp = gr.Image(type="pil", label=f"参考图 {i+1}", sources=["upload"], height=150) + ref_image_groups.append(img_col) + ref_image_inputs.append(img_comp) + + components[key('hidream_o1_reference_rows')] = ref_image_groups + components[key('hidream_o1_reference_images')] = ref_image_inputs + + with gr.Row(): + components[key('add_hidream_o1_reference_button')] = gr.Button("✚ 添加参考图") + components[key('delete_hidream_o1_reference_button')] = gr.Button("➖ 移除参考图", visible=False) + components[key('hidream_o1_reference_count_state')] = gr.State(1) + + components[key('all_hidream_o1_reference_components_flat')] = ref_image_inputs + + return components + +def create_joyai_reference_ui(prefix: str, max_units=2): + components = {} + key = lambda name: f"{name}_{prefix}" + + with gr.Accordion("JoyAI 参考图编辑", open=False, visible=('joyai_image' in default_enabled_chains)) as ref_accordion: + components[key('joyai_reference_accordion')] = ref_accordion + gr.Markdown("💡 一张图建议使用 JoyAI-Image-Edit;多图组合建议使用 JoyAI-Image-Edit-Plus,复杂任务会自动申请更长 GPU 时长。") + + ref_image_groups = [] + ref_image_inputs = [] + with gr.Row(): + for i in range(max_units): + with gr.Column(visible=(i < 1), min_width=160) as img_col: + img_comp = gr.Image(type="pil", label=f"参考图 {i+1}", sources=["upload"], height=150) + ref_image_groups.append(img_col) + ref_image_inputs.append(img_comp) + + components[key('joyai_reference_rows')] = ref_image_groups + components[key('joyai_reference_images')] = ref_image_inputs + + with gr.Row(): + components[key('add_joyai_reference_button')] = gr.Button("✚ 添加参考图") + components[key('delete_joyai_reference_button')] = gr.Button("➖ 移除参考图", visible=False) + components[key('joyai_reference_count_state')] = gr.State(1) + + components[key('all_joyai_reference_components_flat')] = ref_image_inputs + + return components + +def create_reference_image_ui(prefix: str, max_units=10): + components = {} + key = lambda name: f"{name}_{prefix}" + + with gr.Accordion("Mage-Flow 参考图编辑", open=False, visible=('reference_image' in default_enabled_chains)) as ref_accordion: + components[key('reference_image_accordion')] = ref_accordion + gr.Markdown("💡 建议使用 Mage-Flow-Edit-Turbo 或 Mage-Flow-Edit;一张图用于编辑,多张图用于组合。") + + ref_image_groups = [] + ref_image_inputs = [] + with gr.Row(): + for i in range(max_units): + with gr.Column(visible=(i < 1), min_width=160) as img_col: + img_comp = gr.Image(type="pil", label=f"参考图 {i+1}", sources=["upload"], height=150) + ref_image_groups.append(img_col) + ref_image_inputs.append(img_comp) + + components[key('reference_image_rows')] = ref_image_groups + components[key('reference_image_images')] = ref_image_inputs + + with gr.Row(): + components[key('add_reference_image_button')] = gr.Button("✚ 添加参考图") + components[key('delete_reference_image_button')] = gr.Button("➖ 移除参考图", visible=False) + components[key('reference_image_count_state')] = gr.State(1) + + components[key('all_reference_image_components_flat')] = ref_image_inputs + + return components + +def create_pid_ui(prefix: str): + components = {} + key = lambda name: f"{name}_{prefix}" + + with gr.Accordion("PiD 4× 解码", open=False, visible=('pid' in default_enabled_chains)) as pid_accordion: + components[key('pid_accordion')] = pid_accordion + gr.Markdown("💡 使用 PiD(Pixel Diffusion Decoder)替代 VAE 解码器进行 4× 解码。") + with gr.Row(): + components[key('pid_settings')] = gr.Dropdown( + label="PiD 模式", + choices=["OFF", "ON"], + value="OFF", + interactive=True + ) + + return components + +def create_krea2_identity_edit_ui(prefix: str, max_units=2): + components = {} + key = lambda name: f"{name}_{prefix}" + + with gr.Accordion("Krea2 身份参考编辑", open=False, visible=('krea2_identity_edit' in default_enabled_chains)) as ref_accordion: + components[key('krea2_identity_edit_accordion')] = ref_accordion + gr.Markdown("💡 建议使用 Krea-2-Turbo;一张参考图用于身份编辑,多张图用于组合。Krea-2-Raw 的复杂任务会自动申请更长 GPU 时长。") + + ref_image_groups = [] + ref_image_inputs = [] + with gr.Row(): + for i in range(max_units): + with gr.Column(visible=(i < 1), min_width=160) as img_col: + img_comp = gr.Image(type="pil", label=f"参考图 {i+1}", sources=["upload"], height=150) + ref_image_groups.append(img_col) + ref_image_inputs.append(img_comp) + + components[key('krea2_identity_edit_rows')] = ref_image_groups + components[key('krea2_identity_edit_images')] = ref_image_inputs + + with gr.Row(): + components[key('add_krea2_identity_edit_button')] = gr.Button("✚ 添加参考图") + components[key('delete_krea2_identity_edit_button')] = gr.Button("➖ 移除参考图", visible=False) + components[key('krea2_identity_edit_count_state')] = gr.State(1) + + components[key('all_krea2_identity_edit_components_flat')] = ref_image_inputs + + return components + +def create_qwen_image_edit_ui(prefix: str, max_units=3): + components = {} + key = lambda name: f"{name}_{prefix}" + + with gr.Accordion("Qwen-Image 图片编辑", open=False, visible=('qwen_image_edit' in default_enabled_chains)) as ref_accordion: + components[key('qwen_image_edit_accordion')] = ref_accordion + gr.Markdown("💡 建议使用 Qwen-Image-Edit-2511-Lightning;一张参考图用于编辑,多张图用于组合。") + + ref_image_groups = [] + ref_image_inputs = [] + with gr.Row(): + for i in range(max_units): + with gr.Column(visible=(i < 1), min_width=160) as img_col: + img_comp = gr.Image(type="pil", label=f"参考图 {i+1}", sources=["upload"], height=150) + ref_image_groups.append(img_col) + ref_image_inputs.append(img_comp) + + components[key('qwen_image_edit_rows')] = ref_image_groups + components[key('qwen_image_edit_images')] = ref_image_inputs + + with gr.Row(): + components[key('add_qwen_image_edit_button')] = gr.Button("✚ 添加参考图") + components[key('delete_qwen_image_edit_button')] = gr.Button("➖ 移除参考图", visible=False) + components[key('qwen_image_edit_count_state')] = gr.State(1) + + components[key('all_qwen_image_edit_components_flat')] = ref_image_inputs + + return components + +def create_krea2_reference_edit_ui(prefix: str, max_units=3): + components = {} + key = lambda name: f"{name}_{prefix}" + + with gr.Accordion("Krea2 风格参考编辑", open=False, visible=('krea2_style_reference' in default_enabled_chains)) as ref_accordion: + components[key('krea2_reference_edit_accordion')] = ref_accordion + gr.Markdown("💡 建议使用 Krea-2-Turbo;添加参考图后可按其风格编辑画面。") + + ref_image_groups = [] + ref_image_inputs = [] + with gr.Row(): + for i in range(max_units): + with gr.Column(visible=(i < 1), min_width=160) as img_col: + img_comp = gr.Image(type="pil", label=f"参考图 {i+1}", sources=["upload"], height=150) + ref_image_groups.append(img_col) + ref_image_inputs.append(img_comp) + + components[key('krea2_reference_edit_rows')] = ref_image_groups + components[key('krea2_reference_edit_images')] = ref_image_inputs + + with gr.Row(): + components[key('add_krea2_reference_edit_button')] = gr.Button("✚ 添加参考图") + components[key('delete_krea2_reference_edit_button')] = gr.Button("➖ 移除参考图", visible=False) + components[key('krea2_reference_edit_count_state')] = gr.State(1) + + components[key('all_krea2_reference_edit_components_flat')] = ref_image_inputs + + return components + +def create_boogu_edit_ui(prefix: str, max_units=10): + components = {} + key = lambda name: f"{name}_{prefix}" + + with gr.Accordion("Boogu-Image 图片编辑", open=False, visible=('boogu_image_edit' in default_enabled_chains)) as ref_accordion: + components[key('boogu_edit_accordion')] = ref_accordion + gr.Markdown("💡 建议使用 Boogu-Image-Edit-Turbo 或 Boogu-Image-Edit;一张图用于编辑,多张图用于组合,复杂任务会自动申请更长 GPU 时长。") + + ref_image_groups = [] + ref_image_inputs = [] + with gr.Row(): + for i in range(max_units): + with gr.Column(visible=(i < 1), min_width=160) as img_col: + img_comp = gr.Image(type="pil", label=f"参考图 {i+1}", sources=["upload"], height=150) + ref_image_groups.append(img_col) + ref_image_inputs.append(img_comp) + + components[key('boogu_edit_rows')] = ref_image_groups + components[key('boogu_edit_images')] = ref_image_inputs + + with gr.Row(): + components[key('add_boogu_edit_button')] = gr.Button("✚ 添加参考图") + components[key('delete_boogu_edit_button')] = gr.Button("➖ 移除参考图", visible=False) + components[key('boogu_edit_count_state')] = gr.State(1) + + components[key('all_boogu_edit_components_flat')] = ref_image_inputs + + return components diff --git a/ui/theme.py b/ui/theme.py new file mode 100644 index 0000000000000000000000000000000000000000..b83c81680ff00e6e07780a647d33b6efe62ff48f --- /dev/null +++ b/ui/theme.py @@ -0,0 +1,48 @@ +"""Visual system for the Chinese-first Studio interface.""" + +APP_CSS = r""" +:root { + --studio-ink: #172033; + --studio-muted: #667085; + --studio-line: rgba(84, 96, 128, .16); +} + +.gradio-container { + max-width: 1480px !important; + margin: 0 auto !important; +} + +#studio-hero { + padding: 28px 30px; + margin: 14px 0 18px; + border: 1px solid var(--studio-line); + border-radius: 22px; + background: + radial-gradient(circle at 88% 12%, rgba(129, 92, 246, .18), transparent 32%), + linear-gradient(135deg, rgba(79, 70, 229, .10), rgba(255, 255, 255, .72)); +} + +#studio-hero h1 { margin: 0 0 8px; color: var(--studio-ink); font-size: clamp(28px, 4vw, 46px); } +#studio-hero p { margin: 0; max-width: 820px; color: var(--studio-muted); font-size: 16px; line-height: 1.7; } + +.studio-steps { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-bottom: 18px; } +.studio-step { padding: 14px 16px; border: 1px solid var(--studio-line); border-radius: 14px; background: rgba(255,255,255,.62); } +.studio-step b { display: block; margin-bottom: 3px; color: var(--studio-ink); } +.studio-step span { color: var(--studio-muted); font-size: 13px; } + +#task-switcher { margin-bottom: 8px; } +#task-switcher label { min-height: 42px; } +.task-help, .model-hint, .result-note { color: var(--studio-muted); } +.model-hint { padding: 10px 12px; border-left: 3px solid #6366f1; background: rgba(99,102,241,.06); border-radius: 8px; } +.prompt-card { padding: 6px; border: 1px solid rgba(99,102,241,.14) !important; } +#result-column { position: sticky; top: 10px; align-self: flex-start; } +.advanced-title { margin-top: 22px; } +.studio-footer { text-align: center; margin: 32px 0 12px; color: var(--studio-muted); font-size: 13px; } + +@media (max-width: 900px) { + .studio-steps { grid-template-columns: 1fr; } + #workspace-row { flex-direction: column; } + #result-column { position: static; } + #studio-hero { padding: 22px 20px; } +} +""" diff --git a/vendor.lock.yaml b/vendor.lock.yaml new file mode 100644 index 0000000000000000000000000000000000000000..11908d3e9d5a37d7ec06a38d45abbc916eed7775 --- /dev/null +++ b/vendor.lock.yaml @@ -0,0 +1,20 @@ +comfyui: + url: https://github.com/comfyanonymous/ComfyUI.git + revision: dd79c643a95402136a75a28f6187d843bcf457ed + +custom_nodes: + ComfyUI_IPAdapter_plus: + url: https://github.com/cubiq/ComfyUI_IPAdapter_plus.git + revision: a0f451a5113cf9becb0847b92884cb10cbdec0ef + ComfyUI-InstantX-IPAdapter-SD3: + url: https://github.com/Slickytail/ComfyUI-InstantX-IPAdapter-SD3.git + revision: 9f9a9a8a428857a98d3e02f18d1ecc6ee9f671d0 + ComfyUI-IPAdapter-Flux: + url: https://github.com/Shakker-Labs/ComfyUI-IPAdapter-Flux.git + revision: 720d5e763747f498a87265263e71f12506735c31 + comfyui-krea2-controlnet: + url: https://github.com/facok/comfyui-krea2-controlnet.git + revision: 79ebfd3bd80d2180b334dd7ce57f3c9ddaa0848f + comfyui-krea2edit: + url: https://github.com/lbouaraba/comfyui-krea2edit.git + revision: 86f886dac23013d88996e3a2e99093ba44d322fb diff --git a/yaml/anima_controlnet_lllite_models.yaml b/yaml/anima_controlnet_lllite_models.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4c88b54aa4d41a0e98836ce1618096da08958f38 --- /dev/null +++ b/yaml/anima_controlnet_lllite_models.yaml @@ -0,0 +1,16 @@ +Anima_ControlNet_Lllite: + - Filepath: "anima-lllite-any-test-like-v2.safetensors" + Series: "kohya-ss" + Type: ["Any-Test"] + - Filepath: "anima-lllite-depth-1.safetensors" + Series: "kohya-ss" + Type: ["Depth"] + - Filepath: "anima-lllite-lineart-1.safetensors" + Series: "kohya-ss" + Type: ["Lineart"] + - Filepath: "anima-lllite-pose-1.safetensors" + Series: "kohya-ss" + Type: ["Pose"] + - Filepath: "anima-lllite-scribble-1.safetensors" + Series: "kohya-ss" + Type: ["Scribble"] diff --git a/yaml/chain_features.yaml b/yaml/chain_features.yaml new file mode 100644 index 0000000000000000000000000000000000000000..22e89e24cbd6ee227e1030ae6c99ec19a7e0fa40 --- /dev/null +++ b/yaml/chain_features.yaml @@ -0,0 +1,620 @@ +# Complete Feature & Chain Definitions Configuration for MCP Tools +# Every chain injector in chain_injectors/ corresponds 1-to-1 with an entry here (21 injectors total). + +lora: + chains: lora + display_name: "LoRA Fine-tuning Injector" + description: "Injects LoRA weights into UNet/DiT model and CLIP text encoder for custom style, character, or domain adaptation." + supported_tasks: + - txt2img + - img2img + - inpaint + - outpaint + - hires_fix + max_count: 5 + usage_guideline: "Specify source ('Civitai' or 'Hugging Face'), then provide the lora_value (Civitai Version ID or HF repo path), and a single scale value (0.0~2.0) that controls both model and clip strength simultaneously." + parameters_schema: + type: object + properties: + source: + type: string + enum: ["Civitai", "Hugging Face"] + description: "Download source for the LoRA model. Use 'Civitai' to download by Version ID, or 'Hugging Face' to download by repo path." + lora_value: + type: string + description: "For Civitai: the Version ID (e.g., '456' from civitai.com/models/123?modelVersionId=456). For Hugging Face: repo_id/filename.extension or repo_id/folder_path/filename.extension (e.g., 'lightx2v/Qwen-Image-Lightning/Qwen-Image-Lightning-4steps-V2.0-bf16.safetensors')." + scale: + type: number + default: 1.0 + minimum: 0.0 + maximum: 2.0 + description: "Unified strength applied to both the UNet/DiT model and CLIP text encoder (0.0 to 2.0)." + required: + - source + - lora_value + +ipadapter: + chains: ipadapter + display_name: "IP-Adapter Image Prompt" + description: "Uses reference images to guide generation style, composition, structure, or face appearance without prompt text restrictions (SD1.5 & SDXL)." + supported_tasks: + - txt2img + - img2img + - inpaint + - outpaint + - hires_fix + max_count: 5 + usage_guideline: "Supply global settings (preset, embeds_scaling, combine_method, final_weight) and up to 5 reference images with individual weights. Preset must match the target model architecture (SD1.5 or SDXL)." + parameters_schema: + type: object + properties: + image: + type: string + description: "Reference image encoded as Base64 Data URI (e.g., data:image/png;base64,...) or HTTP/HTTPS URL." + weight: + type: number + default: 1.0 + minimum: 0.0 + maximum: 2.0 + description: "Influence weight of the individual image prompt (0.0 to 2.0)." + preset: + type: string + default: "STANDARD (medium strength)" + description: "IPAdapter preset model variant loaded from ipadapter.yaml. Must match model architecture (SD1.5 vs SDXL)." + embeds_scaling: + type: string + default: "V only" + enum: + - "V only" + - "K+V" + - "K+V w/ C penalty" + - "K+mean(V) w/ C penalty" + description: "Embedding scaling method for IPAdapter." + combine_method: + type: string + default: "concat" + enum: + - "concat" + - "add" + - "subtract" + - "average" + - "norm average" + - "max" + - "min" + description: "Combination method for multiple reference images." + final_weight: + type: number + default: 1.0 + minimum: 0.0 + maximum: 2.0 + description: "Global weight multiplier for IPAdapter conditioning (0.0 to 2.0)." + lora_strength: + type: number + default: 0.6 + description: "LoRA weight strength for FaceID adapter variants." + required: + - image + +controlnet: + chains: controlnet + display_name: "ControlNet Spatial Guidance" + description: "Applies structural and spatial conditioning (depth, pose, lineart, tile, scribble, canny) to guide output composition." + supported_tasks: + - txt2img + - img2img + - inpaint + - outpaint + - hires_fix + max_count: 5 + usage_guideline: "Specify ControlNet type and series (must match requested model architecture e.g., SD1.5, SDXL, SD3.5, FLUX.1, Qwen-Image), pre-processed control image (Base64 Data URI or HTTP/HTTPS URL; system does NOT pre-process raw RGB images), and guidance strength." + parameters_schema: + type: object + properties: + type: + type: string + description: "ControlNet conditioning type (must match model architecture)." + series: + type: string + description: "ControlNet model series (must match model architecture)." + image: + type: string + description: "Pre-processed control image (e.g., Depth, Canny, Pose, Lineart map) encoded as Base64 Data URI or HTTP/HTTPS URL. Note: System does NOT automatically pre-process raw RGB images." + strength: + type: number + default: 1.0 + minimum: 0.0 + maximum: 2.0 + description: "Control influence strength (0.0 to 2.0)." + required: + - type + - series + - image + +conditioning: + chains: conditioning + display_name: "Regional Conditioning / Area Prompt" + description: "Defines rectangular areas (X, Y, Width, Height) and assigns specific text prompts and conditioning strengths to them." + supported_tasks: + - txt2img + - img2img + - inpaint + - outpaint + - hires_fix + max_count: 10 + usage_guideline: "Define rectangular spatial areas (X, Y, width, height) and assign specific prompts and strengths to them. Supports up to 10 area prompts." + parameters_schema: + type: object + properties: + prompt: + type: string + description: "Text prompt for this specific rectangular area." + x: + type: integer + default: 0 + description: "Top-left X coordinate of the rectangular area." + y: + type: integer + default: 0 + description: "Top-left Y coordinate of the rectangular area." + width: + type: integer + default: 512 + description: "Width of the rectangular area." + height: + type: integer + default: 512 + description: "Height of the rectangular area." + strength: + type: number + default: 1.0 + minimum: 0.1 + maximum: 2.0 + description: "Conditioning strength for this area (0.1 to 2.0)." + required: + - prompt + +vae: + chains: vae + display_name: "Custom VAE Loader" + description: "Overrides default VAE model used for latent space encoding and final image decoding." + supported_tasks: + - txt2img + - img2img + - inpaint + - outpaint + - hires_fix + max_count: 1 + usage_guideline: "Specify source ('Civitai' or 'Hugging Face'), then provide the vae_value (Civitai Version ID or HF file path)." + parameters_schema: + type: object + properties: + source: + type: string + enum: ["Civitai", "Hugging Face"] + description: "Download source for the VAE model. Use 'Civitai' to download by Version ID, or 'Hugging Face' to download by repo path." + vae_value: + type: string + description: "For Civitai: the Version ID (e.g., '456' from civitai.com/models/123?modelVersionId=456). For Hugging Face: repo_id/filename.extension or repo_id/folder_path/filename.extension (e.g., 'madebyollin/sdxl-vae-fp16-fix/sdxl_vae.safetensors')." + required: + - source + - vae_value + +pid: + chains: pid + display_name: "PiD High-Resolution Refinement" + description: "Progressive Detail (PiD) upscale injector for fine detail enhancement and resolution upscaling." + supported_tasks: + - txt2img + max_count: 1 + usage_guideline: "Enables PiD detail refinement pipeline using a boolean switch ('enabled': true/false)." + parameters_schema: + type: object + properties: + enabled: + type: boolean + default: true + description: "Enable or disable PiD High-Resolution Refinement." + required: + - enabled + +flux1_style: + chains: style + display_name: "FLUX.1 Style Reference" + description: "Applies artistic style conditioning from reference images onto FLUX.1 model generated outputs." + supported_tasks: + - txt2img + - img2img + - inpaint + - outpaint + - hires_fix + max_count: 5 + usage_guideline: "Supply style reference image(s) (up to 5) encoded as Base64 Data URI or HTTP/HTTPS URL and optional strength." + parameters_schema: + type: object + properties: + image: + type: string + description: "Style reference image encoded as Base64 Data URI or HTTP/HTTPS URL." + strength: + type: number + default: 1.0 + minimum: 0.0 + maximum: 2.0 + description: "Style influence strength (0.0 to 2.0)." + required: + - image + +reference_edit: + chains: reference_latent + display_name: "Reference Edit" + description: "For multimodal models, this feature enables powerful editing and combining capabilities. In txt2img mode, adding a single reference image performs an Image Edit, while adding multiple images performs an Image Combine." + supported_tasks: + - txt2img + max_count: 10 + usage_guideline: "Supply reference image(s) encoded as Base64 Data URI or HTTP/HTTPS URL. Passing a single reference image performs an Image Edit, while passing multiple images (up to 10) performs an Image Combine." + parameters_schema: + type: object + properties: + image: + type: string + description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL." + required: + - image + +mage_flow_reference_edit: + chains: reference_image + display_name: "Mage-Flow Reference Edit" + description: " (Mage-Flow-Edit-Turbo/Mage-Flow-Edit recommended) For multimodal models, this feature enables powerful editing and combining capabilities. In txt2img mode, adding a single reference image performs an Image Edit, while adding multiple images performs an Image Combine." + supported_tasks: + - txt2img + max_count: 10 + usage_guideline: "Supply reference image as Base64 Data URI or HTTP/HTTPS URL." + parameters_schema: + type: object + properties: + image: + type: string + description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL." + required: + - image + +krea2_identity_edit: + chains: krea2_identity_edit + display_name: "KREA2 Identity Edit" + description: "Processed using the lbouaraba/comfyui-krea2edit node. (Krea-2-Turbo recommended, Krea-2-Raw need set ZeroGPU Duration (s) to 120 ) In txt2img mode, adding a single reference image performs an Image Edit, while adding multiple images performs an Image Combine." + supported_tasks: + - txt2img + max_count: 2 + usage_guideline: "Supply reference image as Base64 Data URI or HTTP/HTTPS URL." + parameters_schema: + type: object + properties: + image: + type: string + description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL." + required: + - image + +krea2_style_reference: + chains: krea2_style_reference + display_name: "KREA2 Style Reference" + description: "(Krea-2-Turbo recommended) Add style reference images to perform style reference editing." + supported_tasks: + - txt2img + max_count: 3 + usage_guideline: "Supply style reference image as Base64 Data URI or HTTP/HTTPS URL." + parameters_schema: + type: object + properties: + image: + type: string + description: "Style reference image encoded as Base64 Data URI or HTTP/HTTPS URL." + required: + - image + +diffsynth_controlnet: + chains: diffsynth_controlnet + display_name: "DiffSynth ControlNet" + description: "DiffSynth optimized ControlNet injector for Z-Image models." + supported_tasks: + - txt2img + - img2img + - inpaint + - outpaint + - hires_fix + max_count: 5 + usage_guideline: "Supply ControlNet type (e.g., 'Canny'), series (e.g., 'alibaba-pai Controlnet Union 2.1 8steps'), pre-processed control image (Base64 Data URI or HTTP/HTTPS URL; system does NOT pre-process raw RGB images), and optional strength." + parameters_schema: + type: object + properties: + type: + type: string + description: "ControlNet conditioning type." + series: + type: string + description: "ControlNet model series name." + image: + type: string + description: "Pre-processed control image (e.g., Depth map) encoded as Base64 Data URI or HTTP/HTTPS URL. Note: System does NOT automatically pre-process raw RGB images." + strength: + type: number + default: 1.0 + description: "Control influence strength." + required: + - type + - series + - image + +boogu_image_edit: + chains: boogu_image_edit + display_name: "Boogu-Image Edit" + description: " (Boogu-Image-Edit-Turbo/Boogu-Image-Edit recommended, Boogu-Image-Edit need set ZeroGPU Duration (s) to 120 ) In txt2img mode, adding a single reference image performs an Image Edit, while adding multiple images performs an Image Combine." + supported_tasks: + - txt2img + max_count: 10 + usage_guideline: "Supply reference image as Base64 Data URI or HTTP/HTTPS URL." + parameters_schema: + type: object + properties: + image: + type: string + description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL." + required: + - image + +joyai_reference_edit: + chains: joyai_image + display_name: "JoyAI Reference Edit" + description: " (JoyAI-Image-Edit recommended) For multimodal models, this feature enables powerful editing and combining capabilities. In txt2img mode, adding a single reference image performs an Image Edit (JoyAI-Image-Edit recommended), while adding multiple images performs an Image Combine (JoyAI-Image-Edit-Plus recommended with ZeroGPU Duration (s) set to 120)." + supported_tasks: + - txt2img + max_count: 2 + usage_guideline: "Supply JoyAI reference image as Base64 Data URI or HTTP/HTTPS URL." + parameters_schema: + type: object + properties: + image: + type: string + description: "Input reference image encoded as Base64 Data URI or HTTP/HTTPS URL." + required: + - image + +qwen_image_edit: + chains: qwen_image_edit + display_name: "Qwen-Image Edit" + description: " (lightx2v/Qwen-Image-Edit-2511-Lightning recommended) In txt2img mode, adding a single reference image performs an Image Edit, while adding multiple images performs an Image Combine." + supported_tasks: + - txt2img + max_count: 3 + usage_guideline: "Supply reference image(s) (up to 3) encoded as Base64 Data URI or HTTP/HTTPS URL. Passing a single reference image performs an Image Edit, while passing multiple images performs an Image Combine." + parameters_schema: + type: object + properties: + image: + type: string + description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL." + required: + - image + +hidream_o1_smoothing: + chains: hidream_o1_smoothing + display_name: "HiDream O1 Smoothing Injector" + description: "HiDream O1 detail smoothing and artifact reduction injector." + supported_tasks: + - txt2img + - img2img + - inpaint + - outpaint + - hires_fix + max_count: 1 + usage_guideline: "Configures smoothing factor for HiDream models." + parameters_schema: + type: object + properties: + factor: + type: number + default: 0.5 + description: "Smoothing intensity (0.0 to 1.0)." + required: [] + +krea2_controlnet: + chains: krea2_controlnet + display_name: "KREA2 ControlNet" + description: "Processed using the facok/comfyui-krea2-controlnet node." + supported_tasks: + - txt2img + - img2img + - inpaint + - outpaint + - hires_fix + max_count: 5 + usage_guideline: "Supply ControlNet type (e.g., 'Depth'), series (e.g., 'Patil'), pre-processed control image (Base64 Data URI or HTTP/HTTPS URL; system does NOT pre-process raw RGB images), and optional strength." + parameters_schema: + type: object + properties: + type: + type: string + enum: + - "Depth" + description: "ControlNet conditioning type." + series: + type: string + enum: + - "Patil" + default: "Patil" + description: "ControlNet model series." + image: + type: string + description: "Pre-processed control image (e.g., Depth map) encoded as Base64 Data URI or HTTP/HTTPS URL. Note: System does NOT automatically pre-process raw RGB images." + strength: + type: number + default: 1.0 + minimum: 0.0 + maximum: 2.0 + description: "Control influence strength (0.0 to 2.0)." + required: + - type + - series + - image + +anima_controlnet_lllite: + chains: anima_controlnet_lllite + display_name: "Anima ControlNet LLLite" + description: "Anima model-specific lightweight ControlNet." + supported_tasks: + - txt2img + - img2img + - inpaint + - outpaint + - hires_fix + max_count: 5 + usage_guideline: "Supply Anima ControlNet LLLite type (e.g., 'Depth'), series (e.g., 'kohya-ss'), pre-processed control image (Base64 Data URI or HTTP/HTTPS URL; system does NOT pre-process raw RGB images), and optional strength." + parameters_schema: + type: object + properties: + type: + type: string + description: "Anima ControlNet LLLite conditioning type." + series: + type: string + description: "Anima ControlNet LLLite model series." + image: + type: string + description: "Pre-processed control image (e.g., Depth, Lineart map) encoded as Base64 Data URI or HTTP/HTTPS URL. Note: System does NOT automatically pre-process raw RGB images." + strength: + type: number + default: 1.0 + minimum: 0.0 + maximum: 2.0 + description: "Control influence strength (0.0 to 2.0)." + required: + - type + - series + - image + +hidream_o1_reference: + chains: hidream_o1_reference + display_name: "HiDream-O1 Reference Edit" + description: " (HiDream-O1-Image-Dev recommended with resolution set to 4.0MP, e.g., 2048x2048) For HiDream-O1 models, this feature enables reference image editing and combining capabilities. In txt2img mode, adding a single reference image performs an Image Edit, while adding multiple images performs an Image Combine." + supported_tasks: + - txt2img + max_count: 10 + usage_guideline: "Supply reference image(s) (up to 10) encoded as Base64 Data URI or HTTP/HTTPS URL. Passing a single reference image performs an Image Edit, while passing multiple images performs an Image Combine." + parameters_schema: + type: object + properties: + image: + type: string + description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL." + required: + - image + +flux1_ipadapter: + chains: flux1_ipadapter + display_name: "Flux1 IP-Adapter" + description: "FLUX.1 model-specific IP-Adapter implementation." + supported_tasks: + - txt2img + - img2img + - inpaint + - outpaint + - hires_fix + max_count: 5 + usage_guideline: "Supply reference image (Base64 Data URI or HTTP/HTTPS URL), optional weight (default 1.0), start_at (default 0.0), and end_at (default 1.0). Up to 5 images supported." + parameters_schema: + type: object + properties: + image: + type: string + description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL." + weight: + type: number + default: 1.0 + description: "Influence weight of the image prompt (0.0 to 2.0)." + start_at: + type: number + default: 0.0 + description: "Start step percentage for IP-Adapter application (0.0 to 1.0)." + end_at: + type: number + default: 1.0 + description: "End step percentage for IP-Adapter application (0.0 to 1.0)." + start_percent: + type: number + default: 0.0 + description: "Alias for start_at." + end_percent: + type: number + default: 1.0 + description: "Alias for end_at." + required: + - image + +sd3_ipadapter: + chains: sd3_ipadapter + display_name: "SD3 IP-Adapter" + description: "SD3/SD3.5 model-specific IP-Adapter implementation." + supported_tasks: + - txt2img + - img2img + - inpaint + - outpaint + - hires_fix + max_count: 5 + usage_guideline: "Supply reference image (Base64 Data URI or HTTP/HTTPS URL), optional weight (default 1.0), start_at (default 0.0), and end_at (default 1.0). Up to 5 images supported." + parameters_schema: + type: object + properties: + image: + type: string + description: "Reference image encoded as Base64 Data URI or HTTP/HTTPS URL." + weight: + type: number + default: 1.0 + description: "Influence weight of the image prompt (0.0 to 2.0)." + start_at: + type: number + default: 0.0 + description: "Start step percentage for IP-Adapter application (0.0 to 1.0)." + end_at: + type: number + default: 1.0 + description: "End step percentage for IP-Adapter application (0.0 to 1.0)." + start_percent: + type: number + default: 0.0 + description: "Alias for start_at." + end_percent: + type: number + default: 1.0 + description: "Alias for end_at." + required: + - image + +embedding: + chains: embedding + display_name: "Textual Inversion Embedding Injector" + description: "Downloads Textual Inversion embedding files from Civitai or Hugging Face to the server. Note: This feature ONLY handles file downloading/preparation. To activate the embedding, manually add 'embedding:' (e.g. 'embedding:civitai_456' for Civitai ID 456, or 'embedding:filename' for Hugging Face) into your prompt or negative_prompt." + supported_tasks: + - txt2img + - img2img + - inpaint + - outpaint + - hires_fix + max_count: 5 + usage_guideline: "Specify source ('Civitai' or 'Hugging Face'), and embedding_value (Civitai Version ID or HF repo file path). The file is downloaded to server; manually enter 'embedding:' in prompt or negative_prompt to activate." + parameters_schema: + type: object + properties: + source: + type: string + enum: + - "Civitai" + - "Hugging Face" + description: "Download source for the Textual Inversion embedding file. Use 'Civitai' to download by Version ID, or 'Hugging Face' to download by repo file path." + embedding_value: + type: string + description: "For Civitai: the Version ID (e.g., '456' from civitai.com/models/123?modelVersionId=456, saved as 'civitai_456.safetensors'). For Hugging Face: repo_id/filename.extension (e.g., 'ilikebigturtles/lazypos/lazypos.safetensors', saved as 'lazypos.safetensors'). Manually reference embedding: in prompt or negative_prompt." + required: + - source + - embedding_value diff --git a/yaml/constants.yaml b/yaml/constants.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2e5724d514def55edcdfec35532ebcf45609a69c --- /dev/null +++ b/yaml/constants.yaml @@ -0,0 +1,281 @@ +MAX_LORAS: 5 +MAX_CONTROLNETS: 5 +MAX_IPADAPTERS: 5 +MAX_EMBEDDINGS: 5 +MAX_CONDITIONINGS: 10 +MAX_REFERENCE_LATENTS: 10 +LORA_SOURCE_CHOICES: ["Civitai", "Hugging Face", "File"] + +RESOLUTION_MAP: + krea-2: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + mage-flow: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + joyai-image: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + boogu-image: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + pixeldit: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + ideogram-4: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + lens: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + flux2-kv: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + flux2: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + ernie-image: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + z-image: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + qwen-image: + "1:1 (Square)": [1328, 1328] + "16:9 (Landscape)": [1664, 928] + "9:16 (Portrait)": [928, 1664] + "4:3 (Classic)": [1472, 1104] + "3:4 (Classic Portrait)": [1104, 1472] + "3:2 (Photography)": [1536, 1024] + "2:3 (Photography Portrait)": [1024, 1536] + longcat-image: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + cosmos-predict2: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + anima: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + newbie-image: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + kandinsky-5: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + ovis-image: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + hunyuanimage: + "1:1 (Square)": [2048, 2048] + "16:9 (Landscape)": [2728, 1536] + "9:16 (Portrait)": [1536, 2728] + "4:3 (Classic)": [2368, 1776] + "3:4 (Classic Portrait)": [1776, 2368] + "3:2 (Photography)": [2504, 1672] + "2:3 (Photography Portrait)": [1672, 2504] + chroma1-radiance: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + chroma1: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + omnigen2: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + lumina: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + hidream-o1: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + hidream-i1: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + flux1: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + auraflow: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + sd35: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + sdxl: + "1:1 (Square)": [1024, 1024] + "16:9 (Landscape)": [1344, 768] + "9:16 (Portrait)": [768, 1344] + "4:3 (Classic)": [1152, 896] + "3:4 (Classic Portrait)": [896, 1152] + "3:2 (Photography)": [1216, 832] + "2:3 (Photography Portrait)": [832, 1216] + sd15: + "1:1 (Square)": [512, 512] + "16:9 (Landscape)": [896, 512] + "9:16 (Portrait)": [512, 896] + "4:3 (Classic Landscape)": [683, 512] + "3:4 (Classic Portrait)": [512, 683] + "3:2 (Landscape)": [768, 512] + "2:3 (Portrait)": [512, 768] + +MULTIPLIERS_MAP: + krea-2: 1 + mage-flow: 1 + joyai-image: 1 + boogu-image: 1 + pixeldit: 1 + ideogram-4: 1 + lens: 1 + flux2-kv: 1 + flux2: 1 + ernie-image: 1 + z-image: 1 + qwen-image: 1 + longcat-image: 1 + cosmos-predict2: 1 + anima: 1 + newbie-image: 1 + kandinsky-5: 32 + ovis-image: 1 + hunyuanimage: 1 + chroma1-radiance: 64 + chroma1: 1 + omnigen2: 1 + lumina: 1 + hidream-o1: 32 + hidream-i1: 1 + flux1: 1 + auraflow: 1 + sd35: 1 + sdxl: 1 + sd15: 1 diff --git a/yaml/controlnet_models.yaml b/yaml/controlnet_models.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9b695ca03f3cd0a220e3a84d3bef16c6e73e77fd --- /dev/null +++ b/yaml/controlnet_models.yaml @@ -0,0 +1,177 @@ +ControlNet: + Qwen-Image: + - Filepath: "Qwen-Image-InstantX-ControlNet-Union.safetensors" + Series: "InstantX Union" + Type: ["Canny", "Soft Edge", "Depth", "Pose"] + FLUX.1: + - Filepath: "FLUX.1-dev-ControlNet-Union-Pro-2.0.safetensors" + Series: "Shakker Labs Union Pro" + Type: ["Canny", "Tile", "Depth", "Blur", "Pose", "Gray", "Low Quality"] + - Filepath: "flux-canny-controlnet-v3.safetensors" + Series: "XLabs-AI" + Type: ["Canny"] + - Filepath: "flux-depth-controlnet-v3.safetensors" + Series: "XLabs-AI" + Type: ["Depth (Midas)"] + - Filepath: "flux-hed-controlnet-v3.safetensors" + Series: "XLabs-AI" + Type: ["HED"] + SD3.5: + - Filepath: "sd3.5_large_controlnet_blur.safetensors" + Series: "[Large] StabilityAI" + Type: ["Blur"] + - Filepath: "sd3.5_large_controlnet_canny.safetensors" + Series: "[Large] StabilityAI" + Type: ["Canny"] + - Filepath: "sd3.5_large_controlnet_depth.safetensors" + Series: "[Large] StabilityAI" + Type: ["Depth"] + SDXL: + - Filepath: "controlnet-union-sdxl-1.0_promax.safetensors" + Series: "xinsir Union" + Type: ["Tile Deblur", "Tile variation", "Tile Super Resolution", "Image Inpainting", "Image Outpainting", "OpenPose", "Depth", "Canny", "Lineart", "Anime Lineart", "Mlsd", "Scribble", "Hed", "Pidi(Softedge)", "Teed", "Segment", "Normal"] + - Filepath: "controlnet-tile-sdxl-1.0.safetensors" + Series: "xinsir" + Type: ["Tile"] + - Filepath: "controlnet-canny-sdxl-1.0_V2.safetensors" + Series: "xinsir" + Type: ["Canny"] + - Filepath: "controlnet-openpose-sdxl-1.0.safetensors" + Series: "xinsir" + Type: ["OpenPose"] + - Filepath: "controlnet-openpose-sdxl-1.0.safetensors" + Series: "xinsir" + Type: ["OpenPose(Twins)"] + - Filepath: "controlnet-depth-sdxl-1.0" + Series: "xinsir" + Type: ["Depth"] + - Filepath: "controlnet-scribble-sdxl-1.0.safetensors" + Series: "xinsir" + Type: ["Scribble"] + - Filepath: "anime-painter.safetensors" + Series: "xinsir" + Type: ["Anime Painter"] + # SDXL-NoobAI + - Filepath: "noob_sdxl_controlnet_canny.fp16.safetensors" + Series: "NoobAI" + Type: ["Canny"] + - Filepath: "noob_sdxl_controlnet_depth.fp16.safetensors" + Series: "NoobAI" + Type: ["Depth"] + - Filepath: "noob-sdxl-controlnet-lineart_anime.fp16.safetensors" + Series: "NoobAI" + Type: ["Anime Lineart"] + - Filepath: "noob-sdxl-controlnet-lineart_realistic.fp16.safetensors" + Series: "NoobAI" + Type: ["Realistic Lineart"] + - Filepath: "noob-sdxl-controlnet-manga_line.fp16.safetensors" + Series: "NoobAI" + Type: ["Manga Lineart"] + - Filepath: "noob-sdxl-controlnet-normal.fp16.safetensors" + Series: "NoobAI" + Type: ["Normal"] + - Filepath: "noob-sdxl-controlnet-softedge_hed.fp16.safetensors" + Series: "NoobAI" + Type: ["SoftEdge (HED)"] + - Filepath: "noob-sdxl-controlnet-tile.fp16.safetensors" + Series: "NoobAI" + Type: ["Tile"] + - Filepath: "NoobAI_Inpainting_ControlNet.safetensors" + Series: "NoobAI" + Type: ["Inpainting"] + - Filepath: "noob_openpose_pre.safetensors" + Series: "NoobAI" + Type: ["OpenPose"] + - Filepath: "noobaiXLControlnet_epsDepthMidasV11.safetensors" + Series: "NoobAI" + Type: ["Depth (Midas)"] + - Filepath: "noobaiXLControlnet_epsNormalMidas.safetensors" + Series: "NoobAI" + Type: ["Normal (Midas)"] + - Filepath: "noobaiXLControlnet_epsScribbleHed.safetensors" + Series: "NoobAI" + Type: ["Scribble (HED)"] + - Filepath: "noobaiXLControlnet_epsScribblePidinet.safetensors" + Series: "NoobAI" + Type: ["Scribble (PiDiNet)"] + - Filepath: "noobaiXLControlnet_epsDepthMidas.safetensors" + Series: "NoobAI" + Type: ["Depth (Midas)"] + - Filepath: "noobaiXLControlnet_openposeModel.safetensors" + Series: "NoobAI" + Type: ["OpenPose"] + # SDXL - Illustrious-XL-v0.1 + - Filepath: "illustriousXLv0.1_Canny_fp16.safetensors" + Series: "MIC-Lab/illustriousXLv0.1_controlnet" + Type: ["Canny"] + - Filepath: "illustriousXLv0.1_Lineart_fp16.safetensors" + Series: "MIC-Lab/illustriousXLv0.1_controlnet" + Type: ["Lineart"] + - Filepath: "illustriousXLv0.1_Softedge_fp16.safetensors" + Series: "MIC-Lab/illustriousXLv0.1_controlnet" + Type: ["SoftEdge"] + - Filepath: "illustriousXLv0.1_Tile_fp16.safetensors" + Series: "MIC-Lab/illustriousXLv0.1_controlnet" + Type: ["Tile"] + - Filepath: "illustriousXLv0.1_depth_midas_fp16.safetensors" + Series: "MIC-Lab/illustriousXLv0.1_controlnet" + Type: ["Depth (Midas)"] + - Filepath: "illustriousXLv0.1_inpainting_fp16.safetensors" + Series: "MIC-Lab/illustriousXLv0.1_controlnet" + Type: ["Inpainting"] + # SDXL - Illustrious-XL-v1.1 + - Filepath: "illustriousXLv1.1_canny_fp16.safetensors" + Series: "MIC-Lab/illustriousXLv1.1_controlnet" + Type: ["Canny"] + - Filepath: "illustriousXLv1.1_depth_midas_fp16.safetensors" + Series: "MIC-Lab/illustriousXLv1.1_controlnet" + Type: ["Depth (Midas)"] + - Filepath: "illustriousXLv1.1_inpainting_fp16.safetensors" + Series: "MIC-Lab/illustriousXLv1.1_controlnet" + Type: ["Inpainting"] + - Filepath: "illustriousXLv1.1_tile_fp16.safetensors" + Series: "MIC-Lab/illustriousXLv1.1_controlnet" + Type: ["Tile"] + SD1.5: + - Filepath: "control_v11p_sd15_canny_fp16.safetensors" + Series: "Standard" + Type: ["Canny"] + - Filepath: "control_v11f1p_sd15_depth_fp16.safetensors" + Series: "Standard" + Type: ["Depth"] + - Filepath: "control_v11p_sd15_openpose_fp16.safetensors" + Series: "Standard" + Type: ["OpenPose"] + - Filepath: "control_v11p_sd15_lineart_fp16.safetensors" + Series: "Standard" + Type: ["Lineart"] + - Filepath: "control_v11p_sd15_softedge_fp16.safetensors" + Series: "Standard" + Type: ["SoftEdge"] + - Filepath: "control_v11p_sd15_scribble_fp16.safetensors" + Series: "Standard" + Type: ["Scribble"] + - Filepath: "control_v11p_sd15_seg_fp16.safetensors" + Series: "Standard" + Type: ["Segmentation"] + - Filepath: "control_v11p_sd15_normalbae_fp16.safetensors" + Series: "Standard" + Type: ["Normal BAE"] + - Filepath: "control_v11p_sd15_mlsd_fp16.safetensors" + Series: "Standard" + Type: ["MLSD"] + - Filepath: "control_v11p_sd15_inpaint_fp16.safetensors" + Series: "Standard" + Type: ["Inpaint"] + - Filepath: "control_v11f1e_sd15_tile_fp16.safetensors" + Series: "Standard" + Type: ["Tile"] + - Filepath: "control_v11e_sd15_shuffle_fp16.safetensors" + Series: "Standard" + Type: ["Shuffle"] + - Filepath: "control_v11e_sd15_ip2p_fp16.safetensors" + Series: "Standard" + Type: ["Instruct P2P"] + - Filepath: "control_v11p_sd15s2_lineart_anime_fp16.safetensors" + Series: "Standard" + Type: ["Anime Lineart"] diff --git a/yaml/diffsynth_controlnet_models.yaml b/yaml/diffsynth_controlnet_models.yaml new file mode 100644 index 0000000000000000000000000000000000000000..afdc7738dfbe81ad4127923baefd64301902782f --- /dev/null +++ b/yaml/diffsynth_controlnet_models.yaml @@ -0,0 +1,8 @@ +DiffSynth_ControlNet: + Z-Image: + - Filepath: "Z-Image-Turbo-Fun-Controlnet-Union-2.1-8steps.safetensors" + Series: "alibaba-pai Controlnet Union 2.1 8steps" + Type: ["Pose", "Canny", "HED", "Depth", "MLSD"] + - Filepath: "Z-Image-Turbo-Fun-Controlnet-Tile-2.1-8steps.safetensors" + Series: "alibaba-pai Controlnet Union 2.1 8steps" + Type: ["Tile"] diff --git a/yaml/file_list.yaml b/yaml/file_list.yaml new file mode 100644 index 0000000000000000000000000000000000000000..36141a4a860688ae5fc1a6d4d355c3b38d83abbe --- /dev/null +++ b/yaml/file_list.yaml @@ -0,0 +1,987 @@ +file: + checkpoints: + # HiDream-O1 + - filename: "hidream_o1_image_dev_fp8_scaled.safetensors" + source: "hf" + repo_id: "Comfy-Org/HiDream-O1-Image" + repository_file_path: "checkpoints/hidream_o1_image_dev_fp8_scaled.safetensors" + - filename: "hidream_o1_image_fp8_scaled.safetensors" + source: "hf" + repo_id: "Comfy-Org/HiDream-O1-Image" + repository_file_path: "checkpoints/hidream_o1_image_fp8_scaled.safetensors" + # Lumina + - filename: "lumina_2.safetensors" + source: "hf" + repo_id: "Comfy-Org/Lumina_Image_2.0_Repackaged" + repository_file_path: "all_in_one/lumina_2.safetensors" + # AuraFlow + - filename: "aura_flow_0.3.safetensors" + source: "hf" + repo_id: "fal/AuraFlow-v0.3" + repository_file_path: "aura_flow_0.3.safetensors" + # SD3.5 + - filename: "sd3.5_large_fp8_scaled.safetensors" + source: "hf" + repo_id: "Comfy-Org/stable-diffusion-3.5-fp8" + repository_file_path: "sd3.5_large_fp8_scaled.safetensors" + - filename: "sd3.5_medium_incl_clips_t5xxlfp8scaled.safetensors" + source: "hf" + repo_id: "Comfy-Org/stable-diffusion-3.5-fp8" + repository_file_path: "sd3.5_medium_incl_clips_t5xxlfp8scaled.safetensors" + # SDXL-NoobAI + - filename: "NoobAI-XL-Vpred-v1.0.safetensors" + source: hf + repo_id: "Laxhar/noobai-XL-Vpred-1.0" + repository_file_path: "NoobAI-XL-Vpred-v1.0.safetensors" + - filename: "NoobAI-XL-v1.1.safetensors" + source: hf + repo_id: "Laxhar/noobai-XL-1.1" + repository_file_path: "NoobAI-XL-v1.1.safetensors" + - filename: "noob_v_pencil-XL-v3.0.0.safetensors" + source: hf + repo_id: "bluepen5805/noob_v_pencil-XL" + repository_file_path: "noob_v_pencil-XL-v3.0.0.safetensors" + - filename: "Hikari_Noob_v-pred_1.2.4.safetensors" + source: hf + repo_id: "RedRayz/hikari_noob_v-pred_1.2.4" + repository_file_path: "Hikari_Noob_v-pred_1.2.4.safetensors" + - filename: "ChenkinNoob-XL-V0.5.safetensors" + source: hf + repo_id: "ChenkinNoob/ChenkinNoob-XL-V0.5" + repository_file_path: "ChenkinNoob-XL-V0.5.safetensors" + # SDXL-Illustrious + - filename: "waiIllustriousSDXL_v170.safetensors" + source: hf + repo_id: "zhenshipo/waiIllustriousSDXL_v170" + repository_file_path: "waiIllustriousSDXL_v170.safetensors" + - filename: "mellow_pencil-XL-v1.0.0.safetensors" + source: hf + repo_id: "bluepen5805/mellow_pencil-XL" + repository_file_path: "mellow_pencil-XL-v1.0.0.safetensors" + - filename: "illustrious_pencil-XL-v5.0.0.safetensors" + source: hf + repo_id: "bluepen5805/illustrious_pencil-XL" + repository_file_path: "illustrious_pencil-XL-v5.0.0.safetensors" + - filename: "hassakuXLIllustrious_v30.safetensors" + source: hf + repo_id: "misri/hassakuXLIllustrious_v30" + repository_file_path: "hassakuXLIllustrious_v30.safetensors" + - filename: "novaAnimeXL_ilV180.safetensors" + source: hf + repo_id: "frankjoshua/novaAnimeXL_ilV180" + repository_file_path: "novaAnimeXL_ilV180.safetensors" + - filename: "Illustrious-XL-v2.0.safetensors" + source: hf + repo_id: "OnomaAIResearch/Illustrious-XL-v2.0" + repository_file_path: "Illustrious-XL-v2.0.safetensors" + - filename: "Illustrious-XL-v1.1.safetensors" + source: hf + repo_id: "OnomaAIResearch/Illustrious-XL-v1.1" + repository_file_path: "Illustrious-XL-v1.1.safetensors" + - filename: "Illustrious-XL-v1.0.safetensors" + source: hf + repo_id: "OnomaAIResearch/Illustrious-XL-v1.0" + repository_file_path: "Illustrious-XL-v1.0.safetensors" + - filename: "illustriousXL_v01.safetensors" + source: hf + repo_id: "AiAF/Illustrious-XL-v0.1.safetensors" + repository_file_path: "illustriousXL_v01.safetensors" + # SDXL-Animate + - filename: "animagine-xl-4.0.safetensors" + source: hf + repo_id: "cagliostrolab/animagine-xl-4.0" + repository_file_path: "animagine-xl-4.0.safetensors" + - filename: "animagine-xl-3.1.safetensors" + source: hf + repo_id: "cagliostrolab/animagine-xl-3.1" + repository_file_path: "animagine-xl-3.1.safetensors" + - filename: "4nima_pencil-XL-v1.0.1.safetensors" + source: hf + repo_id: "bluepen5805/4nima_pencil-XL" + repository_file_path: "4nima_pencil-XL-v1.0.1.safetensors" + - filename: "anima_pencil-XL-v5.0.0.safetensors" + source: hf + repo_id: "bluepen5805/anima_pencil-XL" + repository_file_path: "anima_pencil-XL-v5.0.0.safetensors" + - filename: "blue_pencil-XL-v7.0.0.safetensors" + source: hf + repo_id: "bluepen5805/blue_pencil-XL" + repository_file_path: "blue_pencil-XL-v7.0.0.safetensors" + # SDXL-Pony + - filename: "ponyDiffusionV6XL_v6StartWithThisOne.safetensors" + source: hf + repo_id: "LyliaEngine/Pony_Diffusion_V6_XL" + repository_file_path: "ponyDiffusionV6XL_v6StartWithThisOne.safetensors" + - filename: "pony_pencil-XL-v2.0.0.safetensors" + source: hf + repo_id: "bluepen5805/pony_pencil-XL" + repository_file_path: "pony_pencil-XL-v2.0.0.safetensors" + - filename: "CyberRealisticPony_V17.0_FP16.safetensors" + source: hf + repo_id: "cyberdelia/CyberRealisticPony" + repository_file_path: "CyberRealisticPony_V17.0_FP16.safetensors" + # SDXL-Base + - filename: "sd_xl_base_1.0.safetensors" + source: "hf" + repo_id: "stabilityai/stable-diffusion-xl-base-1.0" + repository_file_path: "sd_xl_base_1.0.safetensors" + # SDXL-Turbo + - filename: "sd_xl_turbo_1.0_fp16.safetensors" + source: "hf" + repo_id: "stabilityai/sdxl-turbo" + repository_file_path: "sd_xl_turbo_1.0_fp16.safetensors" + # SD1.5 + - filename: "v1-5-pruned-emaonly.safetensors" + source: "hf" + repo_id: "stable-diffusion-v1-5/stable-diffusion-v1-5" + repository_file_path: "v1-5-pruned-emaonly.safetensors" + clip_vision: + # style_injector + - filename: "sigclip_vision_patch14_384.safetensors" + source: "hf" + repo_id: "Comfy-Org/sigclip_vision_384" + repository_file_path: "sigclip_vision_patch14_384.safetensors" + # IPAdapter + - filename: "CLIP-ViT-H-14-laion2B-s32B-b79K.safetensors" + source: "hf" + repo_id: "h94/IP-Adapter" + repository_file_path: "models/image_encoder/model.safetensors" + - filename: "CLIP-ViT-bigG-14-laion2B-39B-b160k.safetensors" + source: "hf" + repo_id: "h94/IP-Adapter" + repository_file_path: "sdxl_models/image_encoder/model.safetensors" + # IPAdapter-SD3 + - filename: "sigclip_vision_patch14_384.safetensors" + source: "hf" + repo_id: "Comfy-Org/sigclip_vision_384" + repository_file_path: "sigclip_vision_patch14_384.safetensors" + controlnet: + # SD3.5 + - filename: "sd3.5_large_controlnet_blur.safetensors" + source: "hf" + repo_id: "stabilityai/stable-diffusion-3.5-controlnets" + repository_file_path: "sd3.5_large_controlnet_blur.safetensors" + - filename: "sd3.5_large_controlnet_canny.safetensors" + source: "hf" + repo_id: "stabilityai/stable-diffusion-3.5-controlnets" + repository_file_path: "sd3.5_large_controlnet_canny.safetensors" + - filename: "sd3.5_large_controlnet_depth.safetensors" + source: "hf" + repo_id: "stabilityai/stable-diffusion-3.5-controlnets" + repository_file_path: "sd3.5_large_controlnet_depth.safetensors" + # Qwen-Image + - filename: "Qwen-Image-InstantX-ControlNet-Union.safetensors" + source: "hf" + repo_id: "InstantX/Qwen-Image-ControlNet-Union" + repository_file_path: "diffusion_pytorch_model.safetensors" + - filename: "Qwen-Image-InstantX-ControlNet-Inpainting.safetensors" + source: "hf" + repo_id: "InstantX/Qwen-Image-ControlNet-Inpainting" + repository_file_path: "diffusion_pytorch_model.safetensors" + # FLUX.1 + - filename: "FLUX.1-dev-ControlNet-Union-Pro-2.0.safetensors" + source: "hf" + repo_id: "Shakker-Labs/FLUX.1-dev-ControlNet-Union-Pro-2.0" + repository_file_path: "diffusion_pytorch_model.safetensors" + - filename: "flux-canny-controlnet-v3.safetensors" + source: "hf" + repo_id: "XLabs-AI/flux-controlnet-collections" + repository_file_path: "flux-canny-controlnet-v3.safetensors" + - filename: "flux-depth-controlnet-v3.safetensors" + source: "hf" + repo_id: "XLabs-AI/flux-controlnet-collections" + repository_file_path: "flux-depth-controlnet-v3.safetensors" + - filename: "flux-hed-controlnet-v3.safetensors" + source: "hf" + repo_id: "XLabs-AI/flux-controlnet-collections" + repository_file_path: "flux-hed-controlnet-v3.safetensors" + # SDXL + - filename: "controlnet-union-sdxl-1.0_promax.safetensors" + source: "hf" + repo_id: "xinsir/controlnet-union-sdxl-1.0" + repository_file_path: "diffusion_pytorch_model_promax.safetensors" + - filename: "controlnet-tile-sdxl-1.0.safetensors" + source: "hf" + repo_id: "xinsir/controlnet-tile-sdxl-1.0" + repository_file_path: "diffusion_pytorch_model.safetensors" + - filename: "controlnet-canny-sdxl-1.0_V2.safetensors" + source: "hf" + repo_id: "xinsir/controlnet-canny-sdxl-1.0" + repository_file_path: "diffusion_pytorch_model_V2.safetensors" + - filename: "controlnet-openpose-sdxl-1.0.safetensors" + source: "hf" + repo_id: "xinsir/controlnet-openpose-sdxl-1.0" + repository_file_path: "diffusion_pytorch_model.safetensors" + - filename: "controlnet-depth-sdxl-1.0.safetensors" + source: "hf" + repo_id: "xinsir/controlnet-depth-sdxl-1.0" + repository_file_path: "diffusion_pytorch_model.safetensors" + - filename: "controlnet-scribble-sdxl-1.0.safetensors" + source: "hf" + repo_id: "xinsir/controlnet-scribble-sdxl-1.0" + repository_file_path: "diffusion_pytorch_model.safetensors" + - filename: "anime-painter.safetensors" + source: "hf" + repo_id: "xinsir/anime-painter" + repository_file_path: "diffusion_pytorch_model.safetensors" + # SDXL - NoobAI + - filename: "noob_sdxl_controlnet_canny.fp16.safetensors" + source: "hf" + repo_id: "Eugeoter/noob-sdxl-controlnet-canny" + repository_file_path: "noob_sdxl_controlnet_canny.fp16.safetensors" + - filename: "noob_sdxl_controlnet_depth.fp16.safetensors" + source: "hf" + repo_id: "Eugeoter/noob-sdxl-controlnet-depth" + repository_file_path: "diffusion_pytorch_model.fp16.safetensors" + - filename: "noob-sdxl-controlnet-lineart_anime.fp16.safetensors" + source: "hf" + repo_id: "Eugeoter/noob-sdxl-controlnet-lineart_anime" + repository_file_path: "diffusion_pytorch_model.fp16.safetensors" + - filename: "noob-sdxl-controlnet-lineart_realistic.fp16.safetensors" + source: "hf" + repo_id: "Eugeoter/noob-sdxl-controlnet-lineart_realistic" + repository_file_path: "diffusion_pytorch_model.fp16.safetensors" + - filename: "noob-sdxl-controlnet-manga_line.fp16.safetensors" + source: "hf" + repo_id: "Eugeoter/noob-sdxl-controlnet-manga_line" + repository_file_path: "diffusion_pytorch_model.fp16.safetensors" + - filename: "noob-sdxl-controlnet-normal.fp16.safetensors" + source: "hf" + repo_id: "Eugeoter/noob-sdxl-controlnet-normal" + repository_file_path: "diffusion_pytorch_model.fp16.safetensors" + - filename: "noob-sdxl-controlnet-softedge_hed.fp16.safetensors" + source: "hf" + repo_id: "Eugeoter/noob-sdxl-controlnet-softedge_hed" + repository_file_path: "diffusion_pytorch_model.fp16.safetensors" + - filename: "noob-sdxl-controlnet-tile.fp16.safetensors" + source: "hf" + repo_id: "Eugeoter/noob-sdxl-controlnet-tile" + repository_file_path: "diffusion_pytorch_model.fp16.safetensors" + - filename: "NoobAI_Inpainting_ControlNet.safetensors" + source: "hf" + repo_id: "Wenaka/NoobAI_XL_Inpainting_ControlNet_Full" + repository_file_path: "NoobAI_Inpainting_ControlNet.safetensors" + - filename: "noob_openpose_pre.safetensors" + source: "hf" + repo_id: "Laxhar/noob_openpose" + repository_file_path: "openpose_pre.safetensors" + - filename: "noobaiXLControlnet_epsBlur.safetensors" + source: "civitai" + model_version_id: "1731092" + - filename: "noobaiXLControlnet_epsDepthMidasV11.safetensors" + source: "hf" + repo_id: "licyk/sd_control_collection" + repository_file_path: "noobaiXLControlnet_epsDepthMidasV11.safetensors" + - filename: "noobaiXLControlnet_epsNormalMidas.safetensors" + source: "hf" + repo_id: "licyk/sd_control_collection" + repository_file_path: "noobaiXLControlnet_epsNormalMidas.safetensors" + - filename: "noobaiXLControlnet_epsScribbleHed.safetensors" + source: "hf" + repo_id: "licyk/sd_control_collection" + repository_file_path: "noobaiXLControlnet_epsScribbleHed.safetensors" + - filename: "noobaiXLControlnet_epsScribblePidinet.safetensors" + source: "hf" + repo_id: "licyk/sd_control_collection" + repository_file_path: "noobaiXLControlnet_epsScribblePidinet.safetensors" + - filename: "noobaiXLControlnet_epsDepthMidas.safetensors" + source: "hf" + repo_id: "licyk/sd_control_collection" + repository_file_path: "noobaiXLControlnet_epsDepthMidas.safetensors" + - filename: "noobaiXLControlnet_openposeModel.safetensors" + source: "hf" + repo_id: "licyk/sd_control_collection" + repository_file_path: "noobaiXLControlnet_openposeModel.safetensors" + # SDXL - Illustrious-XL-v0.1 + - filename: "illustriousXLv0.1_Canny_fp16.safetensors" + source: "hf" + repo_id: "MIC-Lab/illustriousXLv0.1_controlnet" + repository_file_path: "illustriousXLv0.1_Canny_fp16.safetensors" + - filename: "illustriousXLv0.1_Lineart_fp16.safetensors" + source: "hf" + repo_id: "MIC-Lab/illustriousXLv0.1_controlnet" + repository_file_path: "illustriousXLv0.1_Lineart_fp16.safetensors" + - filename: "illustriousXLv0.1_Softedge_fp16.safetensors" + source: "hf" + repo_id: "MIC-Lab/illustriousXLv0.1_controlnet" + repository_file_path: "illustriousXLv0.1_Softedge_fp16.safetensors" + - filename: "illustriousXLv0.1_Tile_fp16.safetensors" + source: "hf" + repo_id: "MIC-Lab/illustriousXLv0.1_controlnet" + repository_file_path: "illustriousXLv0.1_Tile_fp16.safetensors" + - filename: "illustriousXLv0.1_depth_midas_fp16.safetensors" + source: "hf" + repo_id: "MIC-Lab/illustriousXLv0.1_controlnet" + repository_file_path: "illustriousXLv0.1_depth_midas_fp16.safetensors" + - filename: "illustriousXLv0.1_inpainting_fp16.safetensors" + source: "hf" + repo_id: "MIC-Lab/illustriousXLv0.1_controlnet" + repository_file_path: "illustriousXLv0.1_inpainting_fp16.safetensors" + # SDXL - Illustrious-XL-v1.1 + - filename: "illustriousXLv1.1_canny_fp16.safetensors" + source: "hf" + repo_id: "MIC-Lab/illustriousXLv1.1_controlnet" + repository_file_path: "illustriousXLv1.1_canny_fp16.safetensors" + - filename: "illustriousXLv1.1_depth_midas_fp16.safetensors" + source: "hf" + repo_id: "MIC-Lab/illustriousXLv1.1_controlnet" + repository_file_path: "illustriousXLv1.1_depth_midas_fp16.safetensors" + - filename: "illustriousXLv1.1_inpainting_fp16.safetensors" + source: "hf" + repo_id: "MIC-Lab/illustriousXLv1.1_controlnet" + repository_file_path: "illustriousXLv1.1_inpainting_fp16.safetensors" + - filename: "illustriousXLv1.1_tile_fp16.safetensors" + source: "hf" + repo_id: "MIC-Lab/illustriousXLv1.1_controlnet" + repository_file_path: "illustriousXLv1.1_tile_fp16.safetensors" + # SD1.5 + - filename: "control_v11e_sd15_ip2p_fp16.safetensors" + source: "hf" + repo_id: "comfyanonymous/ControlNet-v1-1_fp16_safetensors" + repository_file_path: "control_v11e_sd15_ip2p_fp16.safetensors" + - filename: "control_v11e_sd15_shuffle_fp16.safetensors" + source: "hf" + repo_id: "comfyanonymous/ControlNet-v1-1_fp16_safetensors" + repository_file_path: "control_v11e_sd15_shuffle_fp16.safetensors" + - filename: "control_v11f1e_sd15_tile_fp16.safetensors" + source: "hf" + repo_id: "comfyanonymous/ControlNet-v1-1_fp16_safetensors" + repository_file_path: "control_v11f1e_sd15_tile_fp16.safetensors" + - filename: "control_v11f1p_sd15_depth_fp16.safetensors" + source: "hf" + repo_id: "comfyanonymous/ControlNet-v1-1_fp16_safetensors" + repository_file_path: "control_v11f1p_sd15_depth_fp16.safetensors" + - filename: "control_v11p_sd15_canny_fp16.safetensors" + source: "hf" + repo_id: "comfyanonymous/ControlNet-v1-1_fp16_safetensors" + repository_file_path: "control_v11p_sd15_canny_fp16.safetensors" + - filename: "control_v11p_sd15_inpaint_fp16.safetensors" + source: "hf" + repo_id: "comfyanonymous/ControlNet-v1-1_fp16_safetensors" + repository_file_path: "control_v11p_sd15_inpaint_fp16.safetensors" + - filename: "control_v11p_sd15_lineart_fp16.safetensors" + source: "hf" + repo_id: "comfyanonymous/ControlNet-v1-1_fp16_safetensors" + repository_file_path: "control_v11p_sd15_lineart_fp16.safetensors" + - filename: "control_v11p_sd15_mlsd_fp16.safetensors" + source: "hf" + repo_id: "comfyanonymous/ControlNet-v1-1_fp16_safetensors" + repository_file_path: "control_v11p_sd15_mlsd_fp16.safetensors" + - filename: "control_v11p_sd15_normalbae_fp16.safetensors" + source: "hf" + repo_id: "comfyanonymous/ControlNet-v1-1_fp16_safetensors" + repository_file_path: "control_v11p_sd15_normalbae_fp16.safetensors" + - filename: "control_v11p_sd15_openpose_fp16.safetensors" + source: "hf" + repo_id: "comfyanonymous/ControlNet-v1-1_fp16_safetensors" + repository_file_path: "control_v11p_sd15_openpose_fp16.safetensors" + - filename: "control_v11p_sd15_scribble_fp16.safetensors" + source: "hf" + repo_id: "comfyanonymous/ControlNet-v1-1_fp16_safetensors" + repository_file_path: "control_v11p_sd15_scribble_fp16.safetensors" + - filename: "control_v11p_sd15_seg_fp16.safetensors" + source: "hf" + repo_id: "comfyanonymous/ControlNet-v1-1_fp16_safetensors" + repository_file_path: "control_v11p_sd15_seg_fp16.safetensors" + - filename: "control_v11p_sd15_softedge_fp16.safetensors" + source: "hf" + repo_id: "comfyanonymous/ControlNet-v1-1_fp16_safetensors" + repository_file_path: "control_v11p_sd15_softedge_fp16.safetensors" + - filename: "control_v11p_sd15s2_lineart_anime_fp16.safetensors" + source: "hf" + repo_id: "comfyanonymous/ControlNet-v1-1_fp16_safetensors" + repository_file_path: "control_v11p_sd15s2_lineart_anime_fp16.safetensors" + - filename: "control_v11u_sd15_tile_fp16.safetensors" + source: "hf" + repo_id: "comfyanonymous/ControlNet-v1-1_fp16_safetensors" + repository_file_path: "control_v11u_sd15_tile_fp16.safetensors" + diffusion_models: + # Krea-2 + - filename: "krea2_turbo_nvfp4.safetensors" + source: "hf" + repo_id: "Comfy-Org/Krea-2" + repository_file_path: "diffusion_models/krea2_turbo_nvfp4.safetensors" + - filename: "krea2_raw-nvfp4.safetensors" + source: "hf" + repo_id: "tsukiyomi/krea2_raw-nvfp4" + repository_file_path: "krea2_raw-nvfp4.safetensors" + # Mage-Flow + - filename: "mage_flow_turbo_int8_convrot.safetensors" + source: "hf" + repo_id: "Comfy-Org/Mage-Flow" + repository_file_path: "diffusion_models/mage_flow_turbo_int8_convrot.safetensors" + - filename: "mage_flow_int8_convrot.safetensors" + source: "hf" + repo_id: "Comfy-Org/Mage-Flow" + repository_file_path: "diffusion_models/mage_flow_int8_convrot.safetensors" + - filename: "mage_flow_base_bf16.safetensors" + source: "hf" + repo_id: "Comfy-Org/Mage-Flow" + repository_file_path: "diffusion_models/mage_flow_base_bf16.safetensors" + - filename: "mage_flow_edit_turbo_int8_convrot.safetensors" + source: "hf" + repo_id: "Comfy-Org/Mage-Flow" + repository_file_path: "diffusion_models/mage_flow_edit_turbo_int8_convrot.safetensors" + - filename: "mage_flow_edit_int8_convrot.safetensors" + source: "hf" + repo_id: "Comfy-Org/Mage-Flow" + repository_file_path: "diffusion_models/mage_flow_edit_int8_convrot.safetensors" + - filename: "mage_flow_edit_base_bf16.safetensors" + source: "hf" + repo_id: "Comfy-Org/Mage-Flow" + repository_file_path: "diffusion_models/mage_flow_edit_base_bf16.safetensors" + # JoyAI-Image + - filename: "joyai_image_edit_int8_convrot.safetensors" + source: "hf" + repo_id: "jdopensource/JoyAI-Image-Edit-ComfyUI" + repository_file_path: "diffusion_models/joyai_image_edit_int8_convrot.safetensors" + - filename: "joyai_image_edit_plus_int8_convrot.safetensors" + source: "hf" + repo_id: "jdopensource/JoyAI-Image-Edit-Plus-ComfyUI" + repository_file_path: "diffusion_models/joyai_image_edit_plus_int8_convrot.safetensors" + # Boogu-Image + - filename: "boogu_image_base_nvfp4.safetensors" + source: "hf" + repo_id: "Comfy-Org/Boogu-Image" + repository_file_path: "diffusion_models/boogu_image_base_nvfp4.safetensors" + - filename: "boogu_image_turbo_hotfix_nvfp4.safetensors" + source: "hf" + repo_id: "Comfy-Org/Boogu-Image" + repository_file_path: "diffusion_models/boogu_image_turbo_hotfix_nvfp4.safetensors" + - filename: "boogu_image_edit_turbo_hotfix_1k_20260708_int8_convrot.safetensors" + source: "hf" + repo_id: "Comfy-Org/Boogu-Image" + repository_file_path: "diffusion_models/boogu_image_edit_turbo_hotfix_1k_20260708_int8_convrot.safetensors" + - filename: "boogu_image_edit_nvfp4.safetensors" + source: "hf" + repo_id: "Comfy-Org/Boogu-Image" + repository_file_path: "diffusion_models/boogu_image_edit_nvfp4.safetensors" + # Ideogram-4 + - filename: "ideogram4_nvfp4_mixed.safetensors" + source: "hf" + repo_id: "Comfy-Org/Ideogram-4" + repository_file_path: "diffusion_models/ideogram4_nvfp4_mixed.safetensors" + - filename: "ideogram4_unconditional_nvfp4_mixed.safetensors" + source: "hf" + repo_id: "Comfy-Org/Ideogram-4" + repository_file_path: "diffusion_models/ideogram4_unconditional_nvfp4_mixed.safetensors" + # PixelDiT + - filename: "pixeldit_1300m_1024px_mxfp8.safetensors" + source: "hf" + repo_id: "Comfy-Org/PixelDiT" + repository_file_path: "diffusion_models/pixeldit_1300m_1024px_mxfp8.safetensors" + # PiD + - filename: "pid_sdxl_1024_to_4096_4step_bf16.safetensors" + source: "hf" + repo_id: "Comfy-Org/PixelDiT" + repository_file_path: "diffusion_models/pid_sdxl_1024_to_4096_4step_bf16.safetensors" + - filename: "pid_sd3_1024_to_4096_4step_bf16.safetensors" + source: "hf" + repo_id: "Comfy-Org/PixelDiT" + repository_file_path: "diffusion_models/pid_sd3_1024_to_4096_4step_bf16.safetensors" + - filename: "pid_1.5_flux1_1024_to_4096_4step_int8_convrot.safetensors" + source: "hf" + repo_id: "Comfy-Org/PixelDiT" + repository_file_path: "diffusion_models/pid_1.5_flux1_1024_to_4096_4step_int8_convrot.safetensors" + - filename: "pid_1.5_qwenimage_1024_to_4096_4step_int8_convrot.safetensors" + source: "hf" + repo_id: "Comfy-Org/PixelDiT" + repository_file_path: "diffusion_models/pid_1.5_qwenimage_1024_to_4096_4step_int8_convrot.safetensors" + - filename: "pid_1.5_flux2_1024_to_4096_4step_int8_convrot.safetensors" + source: "hf" + repo_id: "Comfy-Org/PixelDiT" + repository_file_path: "diffusion_models/pid_1.5_flux2_1024_to_4096_4step_int8_convrot.safetensors" + # Lens + - filename: "lens_mxfp8.safetensors" + source: "hf" + repo_id: "Comfy-Org/Lens" + repository_file_path: "diffusion_models/lens_mxfp8.safetensors" + - filename: "lens_turbo_mxfp8.safetensors" + source: "hf" + repo_id: "Comfy-Org/Lens" + repository_file_path: "diffusion_models/lens_turbo_mxfp8.safetensors" + # Cosmos-Predict2 + - filename: "cosmos_predict2_2B_t2i.pt" + source: "hf" + repo_id: "nvidia/Cosmos-Predict2-2B-Text2Image" + repository_file_path: "model.pt" + - filename: "cosmos_predict2_14B_t2i.pt" + source: "hf" + repo_id: "nvidia/Cosmos-Predict2-14B-Text2Image" + repository_file_path: "model.pt" + # Anima + - filename: "anima-turbo-v1.0.safetensors" + source: "hf" + repo_id: "circlestone-labs/Anima" + repository_file_path: "split_files/diffusion_models/anima-turbo-v1.0.safetensors" + - filename: "anima-aesthetic-v1.1.safetensors" + source: "hf" + repo_id: "circlestone-labs/Anima" + repository_file_path: "split_files/diffusion_models/anima-aesthetic-v1.1.safetensors" + - filename: "anima-base-v1.0.safetensors" + source: "hf" + repo_id: "circlestone-labs/Anima" + repository_file_path: "split_files/diffusion_models/anima-base-v1.0.safetensors" + - filename: "waiANIMA_v10Base10.safetensors" + source: "hf" + repo_id: "diffusionmodels1254ani/waiANIMA" + repository_file_path: "waiANIMA_v10Base10.safetensors" + - filename: "AnimaYume_v10_final_base.safetensors" + source: "hf" + repo_id: "duongve/AnimaYume" + repository_file_path: "split_files/diffusion_models/AnimaYume_v10_final_base.safetensors" + - filename: "hassakuAnima_v1Style.safetensors" + source: "hf" + repo_id: "diffusionmodels1254ani/hassakuAnima" + repository_file_path: "hassakuAnima_v1Style.safetensors" + - filename: "kirazuriAnima_v30AnimaBase1.safetensors" + source: "hf" + repo_id: "diffusionmodels1254ani/kirazuriAnima_v30AnimaBase1" + repository_file_path: "kirazuriAnima_v30AnimaBase1.safetensors" + - filename: "anima_pencil-v2.1.0.safetensors" + source: "hf" + repo_id: "bluepen5805/anima-models" + repository_file_path: "anima_pencil-v2.1.0.safetensors" + # NewBie-Image + - filename: "NewBie-Image-Exp0.1-bf16.safetensors" + source: "hf" + repo_id: "Comfy-Org/NewBie-image-Exp0.1_repackaged" + repository_file_path: "split_files/diffusion_models/NewBie-Image-Exp0.1-bf16.safetensors" + # ERNIE-Image + - filename: "ernie-image.safetensors" + source: "hf" + repo_id: "Comfy-Org/ERNIE-Image" + repository_file_path: "diffusion_models/ernie-image.safetensors" + - filename: "ernie-image-turbo.safetensors" + source: "hf" + repo_id: "Comfy-Org/ERNIE-Image" + repository_file_path: "diffusion_models/ernie-image-turbo.safetensors" + # FLUX.2-klein-9B-KV + - filename: "flux-2-klein-9b-kv-fp8.safetensors" + source: "hf" + repo_id: "black-forest-labs/FLUX.2-klein-9b-kv-fp8" + repository_file_path: "flux-2-klein-9b-kv-fp8.safetensors" + # FLUX.2-klein-4B + - filename: "flux-2-klein-4b-nvfp4.safetensors" + source: "hf" + repo_id: "black-forest-labs/FLUX.2-klein-4b-nvfp4" + repository_file_path: "flux-2-klein-4b-nvfp4.safetensors" + # FLUX.2-klein-base-4B + - filename: "flux-2-klein-base-4b-nvfp4.safetensors" + source: "hf" + repo_id: "black-forest-labs/FLUX.2-klein-base-4b-nvfp4" + repository_file_path: "flux-2-klein-base-4b-nvfp4.safetensors" + # FLUX.2-klein-9B + - filename: "flux-2-klein-9b-nvfp4.safetensors" + source: "hf" + repo_id: "black-forest-labs/FLUX.2-klein-9b-nvfp4" + repository_file_path: "flux-2-klein-9b-nvfp4.safetensors" + # FLUX.2-klein-base-9B + - filename: "flux-2-klein-base-9b-nvfp4.safetensors" + source: "hf" + repo_id: "black-forest-labs/FLUX.2-klein-base-9b-nvfp4" + repository_file_path: "flux-2-klein-base-9b-nvfp4.safetensors" + # FLUX.2-dev + - filename: "flux2-dev-nvfp4.safetensors" + source: "hf" + repo_id: "black-forest-labs/FLUX.2-dev-NVFP4" + repository_file_path: "flux2-dev-nvfp4.safetensors" + # LongCat-Image + - filename: "longcat_image_bf16.safetensors" + source: "hf" + repo_id: "Comfy-Org/LongCat-Image" + repository_file_path: "split_files/diffusion_models/longcat_image_bf16.safetensors" + # Ovis-Image + - filename: "ovis_image_bf16.safetensors" + source: "hf" + repo_id: "Comfy-Org/Ovis-Image" + repository_file_path: "split_files/diffusion_models/ovis_image_bf16.safetensors" + # Z-Image + - filename: "z_image_turbo_nvfp4.safetensors" + source: "hf" + repo_id: "Comfy-Org/z_image_turbo" + repository_file_path: "split_files/diffusion_models/z_image_turbo_nvfp4.safetensors" + - filename: "z_image_bf16.safetensors" + source: "hf" + repo_id: "Comfy-Org/z_image" + repository_file_path: "split_files/diffusion_models/z_image_bf16.safetensors" + # Qwen-Image + - filename: "qwen_image_2512_fp8_e4m3fn_scaled_comfyui_4steps_v1.0.safetensors" + source: "hf" + repo_id: "lightx2v/Qwen-Image-2512-Lightning" + repository_file_path: "qwen_image_2512_fp8_e4m3fn_scaled_comfyui_4steps_v1.0.safetensors" + - filename: "qwen_image_2512_fp8_e4m3fn.safetensors" + source: "hf" + repo_id: "Comfy-Org/Qwen-Image_ComfyUI" + repository_file_path: "split_files/diffusion_models/qwen_image_2512_fp8_e4m3fn.safetensors" + - filename: "qwen_image_nvfp4.safetensors" + source: "hf" + repo_id: "Comfy-Org/Qwen-Image_ComfyUI" + repository_file_path: "split_files/diffusion_models/qwen_image_nvfp4.safetensors" + # Qwen-Image-Edit + - filename: "qwen_image_edit_2511_fp8_e4m3fn_scaled_lightning_comfyui_4steps_v1.0.safetensors" + source: "hf" + repo_id: "lightx2v/Qwen-Image-Edit-2511-Lightning" + repository_file_path: "qwen_image_edit_2511_fp8_e4m3fn_scaled_lightning_comfyui_4steps_v1.0.safetensors" + - filename: "qwen_image_edit_2511_int8_convrot.safetensors" + source: "hf" + repo_id: "Comfy-Org/Qwen-Image-Edit_ComfyUI" + repository_file_path: "split_files/diffusion_models/qwen_image_edit_2511_int8_convrot.safetensors" + - filename: "qwen_image_edit_2509_fp8mixed.safetensors" + source: "hf" + repo_id: "Comfy-Org/Qwen-Image-Edit_ComfyUI" + repository_file_path: "split_files/diffusion_models/qwen_image_edit_2509_fp8mixed.safetensors" + - filename: "qwen_image_edit_fp8_e4m3fn.safetensors" + source: "hf" + repo_id: "Comfy-Org/Qwen-Image-Edit_ComfyUI" + repository_file_path: "split_files/diffusion_models/qwen_image_edit_fp8_e4m3fn.safetensors" + # Kandinsky-5 + - filename: "kandinsky5lite_t2i.safetensors" + source: "hf" + repo_id: "kandinskylab/Kandinsky-5.0-T2I-Lite" + repository_file_path: "model/kandinsky5lite_t2i.safetensors" + # Flux.1 + - filename: "flux1-dev-nvfp4.safetensors" + source: "hf" + repo_id: "black-forest-labs/FLUX.1-dev-NVFP4" + repository_file_path: "flux1-dev-nvfp4.safetensors" + - filename: "flux1-schnell-fp8-e4m3fn.safetensors" + source: "hf" + repo_id: "Kijai/flux-fp8" + repository_file_path: "flux1-schnell-fp8-e4m3fn.safetensors" + - filename: "flux1-krea-dev_fp8_scaled.safetensors" + source: "hf" + repo_id: "Comfy-Org/FLUX.1-Krea-dev_ComfyUI" + repository_file_path: "split_files/diffusion_models/flux1-krea-dev_fp8_scaled.safetensors" + # HiDream-I1 + - filename: "hidream_i1_dev_fp8.safetensors" + source: "hf" + repo_id: "Comfy-Org/HiDream-I1_ComfyUI" + repository_file_path: "split_files/diffusion_models/hidream_i1_dev_fp8.safetensors" + - filename: "hidream_i1_fast_fp8.safetensors" + source: "hf" + repo_id: "Comfy-Org/HiDream-I1_ComfyUI" + repository_file_path: "split_files/diffusion_models/hidream_i1_fast_fp8.safetensors" + - filename: "hidream_i1_full_fp8.safetensors" + source: "hf" + repo_id: "Comfy-Org/HiDream-I1_ComfyUI" + repository_file_path: "split_files/diffusion_models/hidream_i1_full_fp8.safetensors" + # HunyuanImage-2.1 + - filename: "hunyuanimage2.1_fp8_e4m3fn.safetensors" + source: "hf" + repo_id: "Comfy-Org/HunyuanImage_2.1_ComfyUI" + repository_file_path: "split_files/diffusion_models/hunyuanimage2.1_fp8_e4m3fn.safetensors" + - filename: "hunyuanimage2.1_distilled_fp8_e4m3fn.safetensors" + source: "hf" + repo_id: "Comfy-Org/HunyuanImage_2.1_ComfyUI" + repository_file_path: "split_files/diffusion_models/hunyuanimage2.1_distilled_fp8_e4m3fn.safetensors" + # Chroma1-Radiance + - filename: "Chroma1-Radiance-x0-fp8mixed_fullmm-20260104.safetensors" + source: "hf" + repo_id: "silveroxides/Chroma1-Radiance-fp8-scaled" + repository_file_path: "Chroma1-Radiance-x0-fp8mixed_fullmm-20260104.safetensors" + # Chroma1 + - filename: "Chroma1-HD-Flash_float8_e4m3fn_scaled_learned_topk8_svd.safetensors" + source: "hf" + repo_id: "Clybius/Chroma-fp8-scaled" + repository_file_path: "Chroma1-HD/Chroma1-HD-Flash_float8_e4m3fn_scaled_learned_topk8_svd.safetensors" + - filename: "Chroma1-HD_float8_e4m3fn_scaled_learned_topk8_svd.safetensors" + source: "hf" + repo_id: "Clybius/Chroma-fp8-scaled" + repository_file_path: "Chroma1-HD/Chroma1-HD_float8_e4m3fn_scaled_learned_topk8_svd.safetensors" + # Omnigen2 + - filename: "omnigen2_fp16.safetensors" + source: "hf" + repo_id: "Comfy-Org/Omnigen2_ComfyUI_repackaged" + repository_file_path: "split_files/diffusion_models/omnigen2_fp16.safetensors" + ipadapter: + # SD3.5 + - filename: "ip-adapter_sd35l_instantx.bin" + source: "hf" + repo_id: "InstantX/SD3.5-Large-IP-Adapter" + repository_file_path: "ip-adapter.bin" + # SD1.5 + - filename: "ip-adapter_sd15.safetensors" + source: "hf" + repo_id: "h94/IP-Adapter" + repository_file_path: "models/ip-adapter_sd15.safetensors" + - filename: "ip-adapter_sd15_light_v11.bin" + source: "hf" + repo_id: "h94/IP-Adapter" + repository_file_path: "models/ip-adapter_sd15_light_v11.bin" + - filename: "ip-adapter-plus_sd15.safetensors" + source: "hf" + repo_id: "h94/IP-Adapter" + repository_file_path: "models/ip-adapter-plus_sd15.safetensors" + - filename: "ip-adapter-plus-face_sd15.safetensors" + source: "hf" + repo_id: "h94/IP-Adapter" + repository_file_path: "models/ip-adapter-plus-face_sd15.safetensors" + - filename: "ip-adapter-full-face_sd15.safetensors" + source: "hf" + repo_id: "h94/IP-Adapter" + repository_file_path: "models/ip-adapter-full-face_sd15.safetensors" + - filename: "ip-adapter_sd15_vit-G.safetensors" + source: "hf" + repo_id: "h94/IP-Adapter" + repository_file_path: "models/ip-adapter_sd15_vit-G.safetensors" + # SDXL + - filename: "ip-adapter_sdxl_vit-h.safetensors" + source: "hf" + repo_id: "h94/IP-Adapter" + repository_file_path: "sdxl_models/ip-adapter_sdxl_vit-h.safetensors" + - filename: "ip-adapter-plus_sdxl_vit-h.safetensors" + source: "hf" + repo_id: "h94/IP-Adapter" + repository_file_path: "sdxl_models/ip-adapter-plus_sdxl_vit-h.safetensors" + - filename: "ip-adapter-plus-face_sdxl_vit-h.safetensors" + source: "hf" + repo_id: "h94/IP-Adapter" + repository_file_path: "sdxl_models/ip-adapter-plus-face_sdxl_vit-h.safetensors" + - filename: "ip-adapter_sdxl.safetensors" + source: "hf" + repo_id: "h94/IP-Adapter" + repository_file_path: "sdxl_models/ip-adapter_sdxl.safetensors" + - filename: "ip-adapter-faceid_sd15.bin" + source: "hf" + repo_id: "h94/IP-Adapter-FaceID" + repository_file_path: "ip-adapter-faceid_sd15.bin" + - filename: "ip-adapter-faceid-plusv2_sd15.bin" + source: "hf" + repo_id: "h94/IP-Adapter-FaceID" + repository_file_path: "ip-adapter-faceid-plusv2_sd15.bin" + - filename: "ip-adapter-faceid-portrait-v11_sd15.bin" + source: "hf" + repo_id: "h94/IP-Adapter-FaceID" + repository_file_path: "ip-adapter-faceid-portrait-v11_sd15.bin" + - filename: "ip-adapter-faceid_sdxl.bin" + source: "hf" + repo_id: "h94/IP-Adapter-FaceID" + repository_file_path: "ip-adapter-faceid_sdxl.bin" + - filename: "ip-adapter-faceid-plusv2_sdxl.bin" + source: "hf" + repo_id: "h94/IP-Adapter-FaceID" + repository_file_path: "ip-adapter-faceid-plusv2_sdxl.bin" + - filename: "ip-adapter-faceid-portrait_sdxl.bin" + source: "hf" + repo_id: "h94/IP-Adapter-FaceID" + repository_file_path: "ip-adapter-faceid-portrait_sdxl.bin" + - filename: "ip-adapter-faceid-portrait_sdxl_unnorm.bin" + source: "hf" + repo_id: "h94/IP-Adapter-FaceID" + repository_file_path: "ip-adapter-faceid-portrait_sdxl_unnorm.bin" + ipadapter-flux: + - filename: "ip-adapter.bin" + source: "hf" + repo_id: "InstantX/FLUX.1-dev-IP-Adapter" + repository_file_path: "ip-adapter.bin" + style_models: + # FLUX.1-Redux-dev + - filename: "flux1-redux-dev.safetensors" + source: "hf" + repo_id: "black-forest-labs/FLUX.1-Redux-dev" + repository_file_path: "flux1-redux-dev.safetensors" + loras: + # Krea2 Identity Edit + - filename: "krea2_identity_edit_v1_2.safetensors" + source: "hf" + repo_id: "conradlocke/krea2-identity-edit" + repository_file_path: "krea2_identity_edit_v1_2.safetensors" + # Krea2 Style Reference Edit + - filename: "krea2_style_reference.safetensors" + source: "hf" + repo_id: "ostris/krea2_turbo_style_reference" + repository_file_path: "krea2_style_reference.safetensors" + # Krea2 ControlNet + - filename: "depth-control-lora.safetensors" + source: "hf" + repo_id: "Patil/Krea-2-depth-controlnet" + repository_file_path: "depth-control-lora.safetensors" + # SD1.5 FaceID + - filename: "ip-adapter-faceid_sd15_lora.safetensors" + source: "hf" + repo_id: "h94/IP-Adapter-FaceID" + repository_file_path: "ip-adapter-faceid_sd15_lora.safetensors" + - filename: "ip-adapter-faceid-plusv2_sd15_lora.safetensors" + source: "hf" + repo_id: "h94/IP-Adapter-FaceID" + repository_file_path: "ip-adapter-faceid-plusv2_sd15_lora.safetensors" + - filename: "ip-adapter-faceid_sdxl_lora.safetensors" + source: "hf" + repo_id: "h94/IP-Adapter-FaceID" + repository_file_path: "ip-adapter-faceid_sdxl_lora.safetensors" + - filename: "ip-adapter-faceid-plusv2_sdxl_lora.safetensors" + source: "hf" + repo_id: "h94/IP-Adapter-FaceID" + repository_file_path: "ip-adapter-faceid-plusv2_sdxl_lora.safetensors" + model_patches: + # Anima + - filename: "anima-lllite-any-test-like-v2.safetensors" + source: "hf" + repo_id: "Comfy-Org/Anima-LLLite" + repository_file_path: "model_patches/anima-lllite-any-test-like-v2.safetensors" + - filename: "anima-lllite-lineart-1.safetensors" + source: "hf" + repo_id: "Comfy-Org/Anima-LLLite" + repository_file_path: "model_patches/anima-lllite-lineart-1.safetensors" + - filename: "anima-lllite-depth-1.safetensors" + source: "hf" + repo_id: "Comfy-Org/Anima-LLLite" + repository_file_path: "model_patches/anima-lllite-depth-1.safetensors" + - filename: "anima-lllite-pose-1.safetensors" + source: "hf" + repo_id: "Comfy-Org/Anima-LLLite" + repository_file_path: "model_patches/anima-lllite-pose-1.safetensors" + - filename: "anima-lllite-scribble-1.safetensors" + source: "hf" + repo_id: "Comfy-Org/Anima-LLLite" + repository_file_path: "model_patches/anima-lllite-scribble-1.safetensors" + # Z-Image + - filename: "Z-Image-Turbo-Fun-Controlnet-Union-2.1-8steps.safetensors" + source: "hf" + repo_id: "alibaba-pai/Z-Image-Turbo-Fun-Controlnet-Union-2.1" + repository_file_path: "Z-Image-Turbo-Fun-Controlnet-Union-2.1-8steps.safetensors" + - filename: "Z-Image-Turbo-Fun-Controlnet-Tile-2.1-8steps.safetensors" + source: "hf" + repo_id: "alibaba-pai/Z-Image-Turbo-Fun-Controlnet-Union-2.1" + repository_file_path: "Z-Image-Turbo-Fun-Controlnet-Tile-2.1-8steps.safetensors" + text_encoders: + # Krea-2 + - filename: "qwen3vl_4b_fp8_scaled.safetensors" + source: "hf" + repo_id: "Comfy-Org/Krea-2" + repository_file_path: "text_encoders/qwen3vl_4b_fp8_scaled.safetensors" + # JoyAI-Image + - filename: "qwen3vl_8b_joyimage_edit_int8_convrot.safetensors" + source: "hf" + repo_id: "jdopensource/JoyAI-Image-Edit-ComfyUI" + repository_file_path: "text_encoders/qwen3vl_8b_joyimage_edit_int8_convrot.safetensors" + - filename: "qwen3vl_8b_joyimage_edit_plus_int8_convrot.safetensors" + source: "hf" + repo_id: "jdopensource/JoyAI-Image-Edit-Plus-ComfyUI" + repository_file_path: "text_encoders/qwen3vl_8b_joyimage_edit_plus_int8_convrot.safetensors" + # Cosmos-Predict2 + - filename: "oldt5_xxl_fp8_e4m3fn_scaled.safetensors" + source: "hf" + repo_id: "comfyanonymous/cosmos_1.0_text_encoder_and_VAE_ComfyUI" + repository_file_path: "text_encoders/oldt5_xxl_fp8_e4m3fn_scaled.safetensors" + # Ideogram-4 & Boogu-Image + - filename: "qwen3vl_8b_nvfp4.safetensors" + source: "hf" + repo_id: "Comfy-Org/Ideogram-4" + repository_file_path: "text_encoders/qwen3vl_8b_nvfp4.safetensors" + # PixelDiT + - filename: "gemma_2_2b_it_elm_fp8_scaled.safetensors" + source: "hf" + repo_id: "Comfy-Org/PixelDiT" + repository_file_path: "text_encoders/gemma_2_2b_it_elm_fp8_scaled.safetensors" + # Lens + - filename: "gpt_oss_20b_nvfp4.safetensors" + source: "hf" + repo_id: "Comfy-Org/Lens" + repository_file_path: "text_encoders/gpt_oss_20b_nvfp4.safetensors" + # Anima + - filename: "qwen_3_06b_base.safetensors" + source: "hf" + repo_id: "circlestone-labs/Anima" + repository_file_path: "split_files/text_encoders/qwen_3_06b_base.safetensors" + # NewBie-Image + - filename: "gemma_3_4b_it_bf16.safetensors" + source: "hf" + repo_id: "Comfy-Org/NewBie-image-Exp0.1_repackaged" + repository_file_path: "split_files/text_encoders/gemma_3_4b_it_bf16.safetensors" + - filename: "jina_clip_v2_bf16.safetensors" + source: "hf" + repo_id: "Comfy-Org/NewBie-image-Exp0.1_repackaged" + repository_file_path: "split_files/text_encoders/jina_clip_v2_bf16.safetensors" + # ERNIE-Image + - filename: "ministral-3-3b.safetensors" + source: "hf" + repo_id: "Comfy-Org/ERNIE-Image" + repository_file_path: "text_encoders/ministral-3-3b.safetensors" + # FLUX.2-klein-4B & base + - filename: "qwen_3_4b_fp4_flux2.safetensors" + source: "hf" + repo_id: "Comfy-Org/vae-text-encorder-for-flux-klein-4b" + repository_file_path: "split_files/text_encoders/qwen_3_4b_fp4_flux2.safetensors" + # FLUX.2-klein-9B & base + - filename: "qwen_3_8b_fp4mixed.safetensors" + source: "hf" + repo_id: "Comfy-Org/vae-text-encorder-for-flux-klein-9b" + repository_file_path: "split_files/text_encoders/qwen_3_8b_fp4mixed.safetensors" + # FLUX.2-dev + - filename: "mistral_3_small_flux2_fp4_mixed.safetensors" + source: "hf" + repo_id: "Comfy-Org/flux2-dev" + repository_file_path: "split_files/text_encoders/mistral_3_small_flux2_fp4_mixed.safetensors" + # Ovis-Image + - filename: "ovis_2.5.safetensors" + source: "hf" + repo_id: "Comfy-Org/Ovis-Image" + repository_file_path: "split_files/text_encoders/ovis_2.5.safetensors" + # Z-Image + - filename: "qwen_3_4b_fp4_mixed.safetensors" + source: "hf" + repo_id: "Comfy-Org/z_image_turbo" + repository_file_path: "split_files/text_encoders/qwen_3_4b_fp4_mixed.safetensors" + - filename: "clip_l.safetensors" + source: "hf" + repo_id: "comfyanonymous/flux_text_encoders" + repository_file_path: "clip_l.safetensors" + - filename: "t5xxl_fp8_e4m3fn_scaled.safetensors" + source: "hf" + repo_id: "comfyanonymous/flux_text_encoders" + repository_file_path: "t5xxl_fp8_e4m3fn_scaled.safetensors" + - filename: "clip_l_hidream.safetensors" + source: "hf" + repo_id: "Comfy-Org/HiDream-I1_ComfyUI" + repository_file_path: "split_files/text_encoders/clip_l_hidream.safetensors" + - filename: "clip_g_hidream.safetensors" + source: "hf" + repo_id: "Comfy-Org/HiDream-I1_ComfyUI" + repository_file_path: "split_files/text_encoders/clip_g_hidream.safetensors" + - filename: "llama_3.1_8b_instruct_fp8_scaled.safetensors" + source: "hf" + repo_id: "Comfy-Org/HiDream-I1_ComfyUI" + repository_file_path: "split_files/text_encoders/llama_3.1_8b_instruct_fp8_scaled.safetensors" + - filename: "qwen_2.5_vl_7b_nvfp4.safetensors" + source: "hf" + repo_id: "Comfy-Org/Qwen-Image_ComfyUI" + repository_file_path: "split_files/text_encoders/qwen_2.5_vl_7b_nvfp4.safetensors" + - filename: "byt5_small_glyphxl_fp16.safetensors" + source: "hf" + repo_id: "Comfy-Org/HunyuanImage_2.1_ComfyUI" + repository_file_path: "split_files/text_encoders/byt5_small_glyphxl_fp16.safetensors" + - filename: "qwen_2.5_vl_fp16.safetensors" + source: "hf" + repo_id: "Comfy-Org/Omnigen2_ComfyUI_repackaged" + repository_file_path: "split_files/text_encoders/qwen_2.5_vl_fp16.safetensors" + vae: + - filename: "wan_2.1_vae.safetensors" + source: "hf" + repo_id: "Comfy-Org/Wan_2.1_ComfyUI_repackaged" + repository_file_path: "split_files/vae/wan_2.1_vae.safetensors" + - filename: "qwen_image_vae.safetensors" + source: "hf" + repo_id: "Comfy-Org/Qwen-Image_ComfyUI" + repository_file_path: "split_files/vae/qwen_image_vae.safetensors" + - filename: "hunyuan_image_2.1_vae_fp16.safetensors" + source: "hf" + repo_id: "Comfy-Org/HunyuanImage_2.1_ComfyUI" + repository_file_path: "split_files/vae/hunyuan_image_2.1_vae_fp16.safetensors" + - filename: "hunyuan_image_refiner_vae_fp16.safetensors" + source: "hf" + repo_id: "Comfy-Org/HunyuanImage_2.1_ComfyUI" + repository_file_path: "split_files/vae/hunyuan_image_refiner_vae_fp16.safetensors" + - filename: "ae.safetensors" + source: "hf" + repo_id: "Comfy-Org/Lumina_Image_2.0_Repackaged" + repository_file_path: "split_files/vae/ae.safetensors" + - filename: "flux2-vae.safetensors" + source: "hf" + repo_id: "Comfy-Org/flux2-dev" + repository_file_path: "split_files/vae/flux2-vae.safetensors" + - filename: "mage_flow_vae_bf16.safetensors" + source: "hf" + repo_id: "Comfy-Org/Mage-Flow" + repository_file_path: "vae/mage_flow_vae_bf16.safetensors" diff --git a/yaml/image_gen_features.yaml b/yaml/image_gen_features.yaml new file mode 100644 index 0000000000000000000000000000000000000000..51a1f44ef53f185e55060ea11e63a50f68050396 --- /dev/null +++ b/yaml/image_gen_features.yaml @@ -0,0 +1,200 @@ +# Feature names in enabled_chains correspond 1-to-1 with chain_injectors/_injector.py +krea-2: + enabled_chains: + - lora + - krea2_controlnet + - krea2_identity_edit + - krea2_style_reference + - pid + +mage-flow: + enabled_chains: + - reference_image + +joyai-image: + enabled_chains: + - joyai_image + +boogu-image: + enabled_chains: + - lora + - boogu_image_edit + - pid + +pixeldit: + enabled_chains: + - conditioning + +ideogram-4: + enabled_chains: + - vae + - pid + +lens: + enabled_chains: + - conditioning + - pid + +flux2-kv: + enabled_chains: + - lora + - reference_latent + - conditioning + - vae + - pid + +flux2: + enabled_chains: + - lora + - reference_latent + - conditioning + - vae + - pid + +ernie-image: + enabled_chains: + - conditioning + - pid + +z-image: + enabled_chains: + - lora + - diffsynth_controlnet + - conditioning + - vae + - pid + +qwen-image: + enabled_chains: + - lora + - conditioning + - controlnet + - qwen_image_edit + - vae + - pid + +longcat-image: + enabled_chains: + - lora + - conditioning + - pid + +cosmos-predict2: + enabled_chains: + - conditioning + - vae + +anima: + enabled_chains: + - lora + - conditioning + - anima_controlnet_lllite + - vae + - pid + +newbie-image: + enabled_chains: + - lora + - embedding + - conditioning + - vae + - pid + +kandinsky-5: + enabled_chains: + - conditioning + - vae + - pid + +ovis-image: + enabled_chains: + - conditioning + - vae + - pid + +hunyuanimage: + enabled_chains: + - conditioning + - vae + +chroma1-radiance: + enabled_chains: + - conditioning + +chroma1: + enabled_chains: + - conditioning + - vae + - pid + +omnigen2: + enabled_chains: + - reference_latent + - conditioning + - pid + +lumina: + enabled_chains: + - lora + - embedding + - conditioning + - vae + - pid + +hidream-o1: + enabled_chains: + - lora + - conditioning + - hidream_o1_smoothing + - hidream_o1_reference + +hidream-i1: + enabled_chains: + - lora + - conditioning + - pid + +flux1: + enabled_chains: + - lora + - flux1_ipadapter + - conditioning + - style + - controlnet + - vae + - pid + +auraflow: + enabled_chains: + - lora + - conditioning + - vae + +sd35: + enabled_chains: + - lora + - sd3_ipadapter + - embedding + - conditioning + - controlnet + - vae + - pid + +sdxl: + enabled_chains: + - lora + - ipadapter + - embedding + - conditioning + - controlnet + - vae + - pid + +sd15: + enabled_chains: + - lora + - ipadapter + - embedding + - conditioning + - controlnet + - vae diff --git a/yaml/ipadapter.yaml b/yaml/ipadapter.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b3663cb8d39e261502622317f50c452b89f1f03c --- /dev/null +++ b/yaml/ipadapter.yaml @@ -0,0 +1,25 @@ +IPAdapter_presets: + SD1.5: + - "LIGHT - SD1.5 only (low strength)" + - "STANDARD (medium strength)" + - "VIT-G (medium strength)" + - "PLUS (high strength)" + - "PLUS FACE (portraits)" + - "FULL FACE - SD1.5 only (portraits stronger)" + SDXL: + - "STANDARD (medium strength)" + - "VIT-G (medium strength)" + - "PLUS (high strength)" + - "PLUS FACE (portraits)" + +IPAdapter_FaceID_presets: + SD1.5: + - "FACEID" + - "FACEID PLUS - SD1.5 only" + - "FACEID PLUS V2" + - "FACEID PORTRAIT (style transfer)" + SDXL: + - "FACEID" + - "FACEID PLUS V2" + - "FACEID PORTRAIT (style transfer)" + - "FACEID PORTRAIT UNNORM - SDXL only (strong)" diff --git a/yaml/ipadapter_models.yaml b/yaml/ipadapter_models.yaml new file mode 100644 index 0000000000000000000000000000000000000000..76bb54d3080e29f5e61d14015632c16241661ab6 --- /dev/null +++ b/yaml/ipadapter_models.yaml @@ -0,0 +1,55 @@ +- preset_name: "LIGHT - SD1.5 only (low strength)" + clip_vision: "CLIP-ViT-H-14-laion2B-s32B-b79K.safetensors" + ipadapter: "ip-adapter_sd15_light_v11.bin" + +- preset_name: "STANDARD (medium strength)" + clip_vision: "CLIP-ViT-H-14-laion2B-s32B-b79K.safetensors" + ipadapter: "ip-adapter_sdxl_vit-h.safetensors" + ipadapter: "ip-adapter_sd15.safetensors" + +- preset_name: "VIT-G (medium strength)" + clip_vision: "CLIP-ViT-bigG-14-laion2B-39B-b160k.safetensors" + ipadapter: "ip-adapter_sdxl.safetensors" + ipadapter: "ip-adapter_sd15_vit-G.safetensors" + +- preset_name: "PLUS (high strength)" + clip_vision: "CLIP-ViT-H-14-laion2B-s32B-b79K.safetensors" + ipadapter: "ip-adapter-plus_sdxl_vit-h.safetensors" + ipadapter: "ip-adapter-plus_sd15.safetensors" + +- preset_name: "PLUS FACE (portraits)" + clip_vision: "CLIP-ViT-H-14-laion2B-s32B-b79K.safetensors" + ipadapter: "ip-adapter-plus-face_sdxl_vit-h.safetensors" + ipadapter: "ip-adapter-plus-face_sd15.safetensors" + +- preset_name: "FULL FACE - SD1.5 only (portraits stronger)" + clip_vision: "CLIP-ViT-H-14-laion2B-s32B-b79K.safetensors" + ipadapter: "ip-adapter-full-face_sd15.safetensors" + +- preset_name: "FACEID" + clip_vision: "CLIP-ViT-H-14-laion2B-s32B-b79K.safetensors" + ipadapter: "ip-adapter-faceid_sdxl.bin" + loras: "ip-adapter-faceid_sdxl_lora.safetensors" + ipadapter: "ip-adapter-faceid_sd15.bin" + loras: "ip-adapter-faceid_sd15_lora.safetensors" + +- preset_name: "FACEID PLUS - SD1.5 only" + clip_vision: "CLIP-ViT-H-14-laion2B-s32B-b79K.safetensors" + ipadapter: "ip-adapter-faceid-plus_sd15.bin" + loras: "ip-adapter-faceid-plus_sd15_lora.safetensors" + +- preset_name: "FACEID PLUS V2" + clip_vision: "CLIP-ViT-H-14-laion2B-s32B-b79K.safetensors" + ipadapter: "ip-adapter-faceid-plusv2_sdxl.bin" + loras: "ip-adapter-faceid-plusv2_sdxl_lora.safetensors" + ipadapter: "ip-adapter-faceid-plusv2_sd15.bin" + loras: "ip-adapter-faceid-plusv2_sd15_lora.safetensors" + +- preset_name: "FACEID PORTRAIT (style transfer)" + clip_vision: "CLIP-ViT-H-14-laion2B-s32B-b79K.safetensors" + ipadapter: "ip-adapter-faceid-portrait_sdxl.bin" + ipadapter: "ip-adapter-faceid-portrait-v11_sd15.bin" + +- preset_name: "FACEID PORTRAIT UNNORM - SDXL only (strong)" + clip_vision: "CLIP-ViT-H-14-laion2B-s32B-b79K.safetensors" + ipadapter: "ip-adapter-faceid-portrait_sdxl_unnorm.bin" diff --git a/yaml/ipadapter_sd3_models.yaml b/yaml/ipadapter_sd3_models.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b73601b0413777040d7094e075d91388e820b316 --- /dev/null +++ b/yaml/ipadapter_sd3_models.yaml @@ -0,0 +1,2 @@ +ipadapter: "ip-adapter_sd35l_instantx.bin" +clip_vision: "sigclip_vision_patch14_384.safetensors" diff --git a/yaml/krea2_controlnet_models.yaml b/yaml/krea2_controlnet_models.yaml new file mode 100644 index 0000000000000000000000000000000000000000..59ce75e5879b5099e67f491ceca8a6b1b0e63d70 --- /dev/null +++ b/yaml/krea2_controlnet_models.yaml @@ -0,0 +1,4 @@ +Krea2_ControlNet: + - Filepath: "depth-control-lora.safetensors" + Series: "Patil" + Type: ["Depth"] diff --git a/yaml/model_architectures.yaml b/yaml/model_architectures.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7cefc6770673d5967f5a1fd867b350b376ab3ead --- /dev/null +++ b/yaml/model_architectures.yaml @@ -0,0 +1,115 @@ +architecture_order: + - "Krea-2" + - "Mage-Flow" + - "JoyAI-Image" + - "Boogu-Image" + - "PixelDiT" + - "Ideogram-4" + - "Lens" + - "FLUX.2-KV" + - "FLUX.2" + - "ERNIE-Image" + - "Z-Image" + - "Qwen-Image" + - "LongCat-Image" + - "Cosmos-Predict2" + - "Anima" + - "NewBie-Image" + - "Kandinsky-5" + - "Ovis-Image" + - "HunyuanImage" + - "Chroma1-Radiance" + - "Chroma1" + - "OmniGen2" + - "Lumina" + - "HiDream-O1" + - "HiDream-I1" + - "FLUX.1" + - "AuraFlow" + - "SD3.5" + - "SDXL" + - "SD1.5" + +architectures: + Krea-2: + model_type: "krea-2" + "Mage-Flow": + model_type: "mage-flow" + "JoyAI-Image": + model_type: "joyai-image" + "Boogu-Image": + model_type: "boogu-image" + "PixelDiT": + model_type: "pixeldit" + "Ideogram-4": + model_type: "ideogram-4" + "Lens": + model_type: "lens" + "ERNIE-Image": + model_type: "ernie-image" + "FLUX.2-KV": + model_type: "flux2-kv" + controlnet_key: "FLUX.2" + "FLUX.2": + model_type: "flux2" + controlnet_key: "FLUX.2" + "Z-Image": + model_type: "z-image" + controlnet_key: "Z-Image" + "Qwen-Image": + model_type: "qwen-image" + controlnet_key: "Qwen-Image" + "LongCat-Image": + model_type: "longcat-image" + controlnet_key: "LongCat-Image" + "Cosmos-Predict2": + model_type: "cosmos-predict2" + controlnet_key: "Cosmos-Predict2" + "Anima": + model_type: "anima" + controlnet_key: "Anima" + "Chroma1-Radiance": + model_type: "chroma1-radiance" + controlnet_key: "Chroma1-Radiance" + "Chroma1": + model_type: "chroma1" + controlnet_key: "Chroma1" + "OmniGen2": + model_type: "omnigen2" + controlnet_key: "OmniGen2" + "Lumina": + model_type: "lumina" + controlnet_key: "Lumina" + "Kandinsky-5": + model_type: "kandinsky-5" + controlnet_key: "Kandinsky-5" + "Ovis-Image": + model_type: "ovis-image" + controlnet_key: "Ovis-Image" + "HunyuanImage": + model_type: "hunyuanimage" + controlnet_key: "HunyuanImage" + "NewBie-Image": + model_type: "newbie-image" + controlnet_key: "NewBie-Image" + "FLUX.1": + model_type: "flux1" + controlnet_key: "FLUX.1" + "AuraFlow": + model_type: "auraflow" + controlnet_key: "AuraFlow" + "SDXL": + model_type: "sdxl" + controlnet_key: "SDXL" + "SD3.5": + model_type: "sd35" + controlnet_key: "SD3.5" + "HiDream-O1": + model_type: "hidream-o1" + controlnet_key: "HiDream-O1" + "HiDream-I1": + model_type: "hidream-i1" + controlnet_key: "HiDream-I1" + "SD1.5": + model_type: "sd15" + controlnet_key: "SD1.5" diff --git a/yaml/model_defaults.yaml b/yaml/model_defaults.yaml new file mode 100644 index 0000000000000000000000000000000000000000..209bd5b5efdb54136ba0ab438c26393ffac56fec --- /dev/null +++ b/yaml/model_defaults.yaml @@ -0,0 +1,310 @@ +Default: + steps: 8 + cfg: 1.0 + sampler_name: "euler" + scheduler: "simple" + positive_prompt: "" + negative_prompt: "" + +Krea-2: + _defaults: + steps: 52 + cfg: 3.5 + sampler_name: "euler" + scheduler: "simple" + "Krea-2-Turbo": + steps: 8 + cfg: 1.0 + sampler_name: "euler" + scheduler: "simple" + +Mage-Flow: + _defaults: + steps: 30 + cfg: 5.0 + sampler_name: "euler" + scheduler: "simple" + "Mage-Flow-Turbo": + steps: 4 + cfg: 1.0 + "Mage-Flow-Edit-Turbo": + steps: 4 + cfg: 1.0 + +JoyAI-Image: + _defaults: + steps: 40 + cfg: 4.0 + sampler_name: "euler" + scheduler: "normal" + "JoyAI-Image-Edit-Plus": + steps: 30 + cfg: 4.0 + +Boogu-Image: + _defaults: + steps: 25 + cfg: 3.5 + sampler_name: "dpmpp_2m" + scheduler: "simple" + "Boogu-Image-Turbo": + steps: 4 + cfg: 1.0 + sampler_name: "lcm" + scheduler: "sgm_uniform" + "Boogu-Image-Edit-Turbo": + steps: 4 + cfg: 1.0 + sampler_name: "lcm" + scheduler: "sgm_uniform" + +PixelDiT: + _defaults: + steps: 30 + cfg: 4.0 + sampler_name: "er_sde" + scheduler: "simple" + negative_prompt: "low quality, worst quality, over-saturated, blurry, deformed, watermark" + +Ideogram-4: + _defaults: + steps: 20 + cfg: 7.0 + sampler_name: "res_multistep" + scheduler: "simple" + positive_prompt: "NOTE: If you see \"Image blocked by safety filter\" it is because of safety training in the model itself, ImageGen does not have any safety filter." + +Lens: + _defaults: + steps: 20 + cfg: 5.0 + sampler_name: "euler" + scheduler: "simple" + "Microsoft/Lens-Turbo": + steps: 4 + cfg: 1.0 + +FLUX.2-KV: + _defaults: + steps: 4 + cfg: 1.0 + sampler_name: "euler" + scheduler: "simple" + +FLUX.2: + _defaults: + steps: 20 + cfg: 4.0 + sampler_name: "euler" + scheduler: "simple" + "black-forest-labs/FLUX.2-klein-4B": + steps: 4 + cfg: 1.0 + "black-forest-labs/FLUX.2-klein-9B": + steps: 4 + cfg: 1.0 + +ERNIE-Image: + _defaults: + steps: 20 + cfg: 4.0 + sampler_name: "euler" + scheduler: "simple" + "baidu/ERNIE-Image-Turbo": + steps: 8 + cfg: 1.0 + +Z-Image: + _defaults: + steps: 25 + cfg: 4.0 + sampler_name: "euler" + scheduler: "simple" + "Tongyi-MAI/Z Image Turbo": + steps: 9 + cfg: 1.0 + +Qwen-Image: + _defaults: + steps: 20 + cfg: 4.0 + sampler_name: "euler" + scheduler: "simple" + "lightx2v/Qwen-Image-2512-Lightning": + steps: 4 + cfg: 1.0 + "lightx2v/Qwen-Image-Edit-2511-Lightning": + steps: 4 + cfg: 1.0 + +LongCat-Image: + _defaults: + steps: 20 + cfg: 4.0 + guidance: 4.0 + sampler_name: "euler" + scheduler: "simple" + +Cosmos-Predict2: + _defaults: + steps: 35 + cfg: 4.0 + sampler_name: "euler" + scheduler: "karras" + +Anima: + _defaults: + steps: 30 + cfg: 4.0 + sampler_name: "er_sde" + scheduler: "simple" + positive_prompt: "masterpiece, best quality, score_7, safe. " + negative_prompt: "worst quality, low quality, score_1, score_2, score_3, blurry, jpeg artifacts, sepia" + "circlestone-labs/Anima-Turbo-v1.0": + steps: 10 + cfg: 1.0 + +NewBie-Image: + _defaults: + steps: 20 + cfg: 5.5 + sampler_name: "res_multistep" + scheduler: "simple" + positive_prompt: "You are an assistant designed to generate high-quality anime images with the highest degree of image-text alignment based on xml format textual prompts. " + negative_prompt: "You are an assistant designed to generate low-quality images based on textual prompts. " + +Kandinsky-5: + _defaults: + steps: 50 + cfg: 3.5 + sampler_name: "euler" + scheduler: "simple" + +Ovis-Image: + _defaults: + steps: 20 + cfg: 5.0 + sampler_name: "euler" + scheduler: "simple" + +HunyuanImage: + _defaults: + steps: 20 + cfg: 3.5 + sampler_name: "euler" + scheduler: "simple" + "HunyuanImage-2.1-Distilled": + steps: 8 + cfg: 1.0 + +Chroma1-Radiance: + _defaults: + steps: 30 + cfg: 4.0 + sampler_name: "euler" + scheduler: "simple" + negative_prompt: "low quality, bad anatomy, extra digits, missing digits, extra limbs, missing limbs, hands, fingers" + +Chroma1: + _defaults: + steps: 30 + cfg: 4.0 + sampler_name: "euler" + scheduler: "simple" + negative_prompt: "low quality, bad anatomy, extra digits, missing digits, extra limbs, missing limbs" + "lodestones/Chroma1-HD-Flash": + steps: 8 + cfg: 1.0 + scheduler: "beta" + +OmniGen2: + _defaults: + steps: 20 + cfg: 5.0 + sampler_name: "euler" + scheduler: "simple" + positive_prompt: "" + negative_prompt: "" + +Lumina: + _defaults: + steps: 20 + cfg: 4.0 + sampler_name: "res_multistep" + scheduler: "simple" + positive_prompt: "" + negative_prompt: "" + +HiDream-O1: + _defaults: + steps: 40 + cfg: 5.0 + sampler_name: "dpmpp_2m_sde_gpu" + scheduler: "normal" + "HiDream-O1-Image-Dev": + steps: 28 + cfg: 1.0 + sampler_name: "lcm" + scheduler: "normal" + +HiDream-I1: + _defaults: + steps: 50 + cfg: 3.0 + sampler_name: "uni_pc" + scheduler: "simple" + negative_prompt: "bad ugly jpeg artifacts" + "HiDream_i1_Dev": + steps: 28 + cfg: 1.0 + sampler_name: "lcm" + scheduler: "normal" + "HiDream_i1_Fast": + steps: 16 + cfg: 1.0 + sampler_name: "lcm" + scheduler: "normal" + +FLUX.1: + _defaults: + steps: 20 + cfg: 1.0 + sampler_name: "euler" + scheduler: "simple" + "flux1-schnell": + steps: 4 + cfg: 1.0 + sampler_name: "euler" + scheduler: "simple" + +AuraFlow: + _defaults: + steps: 20 + cfg: 3.5 + sampler_name: "euler" + scheduler: "sgm_uniform" + +SD3.5: + _defaults: + steps: 20 + cfg: 4.0 + sampler_name: "euler" + scheduler: "sgm_uniform" + +SDXL: + _defaults: + steps: 25 + cfg: 7.0 + sampler_name: "euler_ancestral" + scheduler: "simple" + "stabilityai/SDXL-Turbo-1.0": + steps: 1 + cfg: 1.0 + positive_prompt: "NOTE: The model generates images of size 512x512 but higher image sizes work as well." + +SD1.5: + _defaults: + steps: 47 + cfg: 7.0 + sampler_name: "euler_ancestral" + scheduler: "simple" diff --git a/yaml/model_list.yaml b/yaml/model_list.yaml new file mode 100644 index 0000000000000000000000000000000000000000..153c5e82ccf551c228b890bfafa95cab32d5a9b5 --- /dev/null +++ b/yaml/model_list.yaml @@ -0,0 +1,505 @@ +Checkpoint: + Krea-2: + latent_type: latent + models: + - display_name: "Krea-2-Turbo" + components: + unet: "krea2_turbo_nvfp4.safetensors" + clip: "qwen3vl_4b_fp8_scaled.safetensors" + vae: "qwen_image_vae.safetensors" + - display_name: "Krea-2-Raw" + components: + unet: "krea2_raw-nvfp4.safetensors" + clip: "qwen3vl_4b_fp8_scaled.safetensors" + vae: "qwen_image_vae.safetensors" + Mage-Flow: + latent_type: none + models: + - display_name: "Mage-Flow-Turbo" + components: + unet: "mage_flow_turbo_int8_convrot.safetensors" + clip: "qwen3vl_4b_fp8_scaled.safetensors" + vae: "mage_flow_vae_bf16.safetensors" + - display_name: "Mage-Flow" + components: + unet: "mage_flow_int8_convrot.safetensors" + clip: "qwen3vl_4b_fp8_scaled.safetensors" + vae: "mage_flow_vae_bf16.safetensors" + - display_name: "Mage-Flow-Base" + components: + unet: "mage_flow_base_bf16.safetensors" + clip: "qwen3vl_4b_fp8_scaled.safetensors" + vae: "mage_flow_vae_bf16.safetensors" + - display_name: "Mage-Flow-Edit-Turbo" + components: + unet: "mage_flow_edit_turbo_int8_convrot.safetensors" + clip: "qwen3vl_4b_fp8_scaled.safetensors" + vae: "mage_flow_vae_bf16.safetensors" + - display_name: "Mage-Flow-Edit" + components: + unet: "mage_flow_edit_int8_convrot.safetensors" + clip: "qwen3vl_4b_fp8_scaled.safetensors" + vae: "mage_flow_vae_bf16.safetensors" + - display_name: "Mage-Flow-Edit-Base" + components: + unet: "mage_flow_edit_base_bf16.safetensors" + clip: "qwen3vl_4b_fp8_scaled.safetensors" + vae: "mage_flow_vae_bf16.safetensors" + JoyAI-Image: + latent_type: sd3_latent + models: + - display_name: "JoyAI-Image-Edit" + components: + unet: "joyai_image_edit_int8_convrot.safetensors" + clip: "qwen3vl_8b_joyimage_edit_int8_convrot.safetensors" + vae: "wan_2.1_vae.safetensors" + - display_name: "JoyAI-Image-Edit-Plus" + components: + unet: "joyai_image_edit_plus_int8_convrot.safetensors" + clip: "qwen3vl_8b_joyimage_edit_plus_int8_convrot.safetensors" + vae: "wan_2.1_vae.safetensors" + Boogu-Image: + latent_type: latent + models: + - display_name: "Boogu-Image-Turbo" + components: + unet: "boogu_image_turbo_hotfix_nvfp4.safetensors" + clip: "qwen3vl_8b_nvfp4.safetensors" + vae: "ae.safetensors" + - display_name: "Boogu-Image-Base" + components: + unet: "boogu_image_base_nvfp4.safetensors" + clip: "qwen3vl_8b_nvfp4.safetensors" + vae: "ae.safetensors" + - display_name: "Boogu-Image-Edit-Turbo" + components: + unet: "boogu_image_edit_turbo_hotfix_1k_20260708_int8_convrot.safetensors" + clip: "qwen3vl_8b_nvfp4.safetensors" + vae: "ae.safetensors" + - display_name: "Boogu-Image-Edit" + components: + unet: "boogu_image_edit_nvfp4.safetensors" + clip: "qwen3vl_8b_nvfp4.safetensors" + vae: "ae.safetensors" + PixelDiT: + latent_type: chroma_radiance_latent + models: + - display_name: "nvidia/PixelDiT-1300M-1024px" + components: + unet: "pixeldit_1300m_1024px_mxfp8.safetensors" + clip: "gemma_2_2b_it_elm_fp8_scaled.safetensors" + vae: "pixel_space" + Ideogram-4: + latent_type: flux2_latent + models: + - display_name: "ideogram-ai/ideogram-4" + components: + unet: "ideogram4_nvfp4_mixed.safetensors" + unet_uncond: "ideogram4_unconditional_nvfp4_mixed.safetensors" + clip: "qwen3vl_8b_nvfp4.safetensors" + vae: "flux2-vae.safetensors" + Lens: + latent_type: flux2_latent + models: + - display_name: "Microsoft/Lens" + components: + unet: "lens_mxfp8.safetensors" + clip: "gpt_oss_20b_nvfp4.safetensors" + vae: "flux2-vae.safetensors" + - display_name: "Microsoft/Lens-Turbo" + components: + unet: "lens_turbo_mxfp8.safetensors" + clip: "gpt_oss_20b_nvfp4.safetensors" + vae: "flux2-vae.safetensors" + FLUX.2-KV: + latent_type: flux2_latent + models: + - display_name: "black-forest-labs/FLUX.2-klein-9B-KV" + components: + unet: "flux-2-klein-9b-kv-fp8.safetensors" + clip: "qwen_3_8b_fp4mixed.safetensors" + vae: "flux2-vae.safetensors" + FLUX.2: + latent_type: flux2_latent + models: + - display_name: "black-forest-labs/FLUX.2-klein-4B" + components: + unet: "flux-2-klein-4b-nvfp4.safetensors" + clip: "qwen_3_4b_fp4_flux2.safetensors" + vae: "flux2-vae.safetensors" + - display_name: "black-forest-labs/FLUX.2-klein-9B" + components: + unet: "flux-2-klein-9b-nvfp4.safetensors" + clip: "qwen_3_8b_fp4mixed.safetensors" + vae: "flux2-vae.safetensors" + - display_name: "black-forest-labs/FLUX.2-klein-base-4B" + components: + unet: "flux-2-klein-base-4b-nvfp4.safetensors" + clip: "qwen_3_4b_fp4_flux2.safetensors" + vae: "flux2-vae.safetensors" + - display_name: "black-forest-labs/FLUX.2-klein-base-9B" + components: + unet: "flux-2-klein-base-9b-nvfp4.safetensors" + clip: "qwen_3_8b_fp4mixed.safetensors" + vae: "flux2-vae.safetensors" + - display_name: "black-forest-labs/FLUX.2-dev" + components: + unet: "flux2-dev-nvfp4.safetensors" + clip: "mistral_3_small_flux2_fp4_mixed.safetensors" + vae: "flux2-vae.safetensors" + ERNIE-Image: + latent_type: flux2_latent + models: + - display_name: "baidu/ERNIE-Image" + components: + unet: "ernie-image.safetensors" + vae: "flux2-vae.safetensors" + clip: "ministral-3-3b.safetensors" + - display_name: "baidu/ERNIE-Image-Turbo" + components: + unet: "ernie-image-turbo.safetensors" + vae: "flux2-vae.safetensors" + clip: "ministral-3-3b.safetensors" + Z-Image: + latent_type: sd3_latent + models: + - display_name: "Tongyi-MAI/Z Image Turbo" + components: + unet: "z_image_turbo_nvfp4.safetensors" + vae: "ae.safetensors" + clip: "qwen_3_4b_fp4_mixed.safetensors" + - display_name: "Tongyi-MAI/Z Image" + components: + unet: "z_image_bf16.safetensors" + vae: "ae.safetensors" + clip: "qwen_3_4b_fp4_mixed.safetensors" + Qwen-Image: + latent_type: sd3_latent + models: + - display_name: "lightx2v/Qwen-Image-2512-Lightning" + components: + unet: "qwen_image_2512_fp8_e4m3fn_scaled_comfyui_4steps_v1.0.safetensors" + vae: "qwen_image_vae.safetensors" + clip: "qwen_2.5_vl_7b_nvfp4.safetensors" + - display_name: "Qwen-Image-2512" + components: + unet: "qwen_image_2512_fp8_e4m3fn.safetensors" + vae: "qwen_image_vae.safetensors" + clip: "qwen_2.5_vl_7b_nvfp4.safetensors" + - display_name: "Qwen-Image" + components: + unet: "qwen_image_nvfp4.safetensors" + vae: "qwen_image_vae.safetensors" + clip: "qwen_2.5_vl_7b_nvfp4.safetensors" + - display_name: "lightx2v/Qwen-Image-Edit-2511-Lightning" + components: + unet: "qwen_image_edit_2511_fp8_e4m3fn_scaled_lightning_comfyui_4steps_v1.0.safetensors" + vae: "qwen_image_vae.safetensors" + clip: "qwen_2.5_vl_7b_nvfp4.safetensors" + - display_name: "Qwen-Image-Edit-2511" + components: + unet: "qwen_image_edit_2511_int8_convrot.safetensors" + vae: "qwen_image_vae.safetensors" + clip: "qwen_2.5_vl_7b_nvfp4.safetensors" + - display_name: "Qwen-Image-Edit-2509" + components: + unet: "qwen_image_edit_2509_fp8mixed.safetensors" + vae: "qwen_image_vae.safetensors" + clip: "qwen_2.5_vl_7b_nvfp4.safetensors" + - display_name: "Qwen-Image-Edit" + components: + unet: "qwen_image_edit_fp8_e4m3fn.safetensors" + vae: "qwen_image_vae.safetensors" + clip: "qwen_2.5_vl_7b_nvfp4.safetensors" + LongCat-Image: + latent_type: sd3_latent + models: + - display_name: "meituan-longcat/LongCat-Image" + components: + unet: "longcat_image_bf16.safetensors" + vae: "ae.safetensors" + clip: "qwen_2.5_vl_7b_nvfp4.safetensors" + Cosmos-Predict2: + latent_type: sd3_latent + models: + - display_name: "Cosmos-Predict2-2B-T2I" + components: + unet: "cosmos_predict2_2B_t2i.pt" + clip: "oldt5_xxl_fp8_e4m3fn_scaled.safetensors" + vae: "wan_2.1_vae.safetensors" + - display_name: "Cosmos-Predict2-14B-T2I" + components: + unet: "cosmos_predict2_14B_t2i.pt" + clip: "oldt5_xxl_fp8_e4m3fn_scaled.safetensors" + vae: "wan_2.1_vae.safetensors" + Anima: + latent_type: latent + models: + - display_name: "circlestone-labs/Anima-Turbo-v1.0" + components: + unet: "anima-turbo-v1.0.safetensors" + vae: "qwen_image_vae.safetensors" + clip: "qwen_3_06b_base.safetensors" + - display_name: "circlestone-labs/Anima-Aesthetic-v1.1" + components: + unet: "anima-aesthetic-v1.1.safetensors" + vae: "qwen_image_vae.safetensors" + clip: "qwen_3_06b_base.safetensors" + - display_name: "circlestone-labs/Anima-Base-v1.0" + components: + unet: "anima-base-v1.0.safetensors" + vae: "qwen_image_vae.safetensors" + clip: "qwen_3_06b_base.safetensors" + - display_name: "WAI0731/waiANIMA-v1.0" + components: + unet: "waiANIMA_v10Base10.safetensors" + vae: "qwen_image_vae.safetensors" + clip: "qwen_3_06b_base.safetensors" + - display_name: "duongve/AnimaYume-v1.0" + components: + unet: "AnimaYume_v10_final_base.safetensors" + vae: "qwen_image_vae.safetensors" + clip: "qwen_3_06b_base.safetensors" + - display_name: "bluepen5805/Anima-pencil-v2.1" + components: + unet: "anima_pencil-v2.1.0.safetensors" + vae: "qwen_image_vae.safetensors" + clip: "qwen_3_06b_base.safetensors" + - display_name: "Ikena/Hassaku-Anima-v1-Style" + components: + unet: "hassakuAnima_v1Style.safetensors" + vae: "qwen_image_vae.safetensors" + clip: "qwen_3_06b_base.safetensors" + - display_name: "motimalu/Kirazuri (Anima)-v3.0" + components: + unet: "hassakuAnima_v1Style.safetensors" + vae: "qwen_image_vae.safetensors" + clip: "qwen_3_06b_base.safetensors" + NewBie-Image: + latent_type: sd3_latent + models: + - display_name: "NewBie-AI/NewBie-image-Exp0.1" + components: + unet: "NewBie-Image-Exp0.1-bf16.safetensors" + vae: "ae.safetensors" + clip1: "gemma_3_4b_it_bf16.safetensors" + clip2: "jina_clip_v2_bf16.safetensors" + Kandinsky-5: + latent_type: latent + models: + - display_name: "Kandinsky-5.0-T2I-Lite" + components: + unet: "kandinsky5lite_t2i.safetensors" + vae: "ae.safetensors" + clip1: "qwen_2.5_vl_7b_nvfp4.safetensors" + clip2: "clip_l.safetensors" + Ovis-Image: + latent_type: sd3_latent + models: + - display_name: "AIDC-AI/Ovis-Image" + components: + unet: "ovis_image_bf16.safetensors" + vae: "ae.safetensors" + clip: "ovis_2.5.safetensors" + HunyuanImage: + latent_type: hunyuan_latent + models: + - display_name: "HunyuanImage-2.1" + components: + unet: "hunyuanimage2.1_fp8_e4m3fn.safetensors" + vae: "hunyuan_image_2.1_vae_fp16.safetensors" + clip1: "qwen_2.5_vl_7b_nvfp4.safetensors" + clip2: "byt5_small_glyphxl_fp16.safetensors" + - display_name: "HunyuanImage-2.1-Distilled" + components: + unet: "hunyuanimage2.1_distilled_fp8_e4m3fn.safetensors" + vae: "hunyuan_image_2.1_vae_fp16.safetensors" + clip1: "qwen_2.5_vl_7b_nvfp4.safetensors" + clip2: "byt5_small_glyphxl_fp16.safetensors" + Chroma1-Radiance: + latent_type: chroma_radiance_latent + models: + - display_name: "lodestones/Chroma1-Radiance-x0" + components: + unet: "Chroma1-Radiance-x0-fp8mixed_fullmm-20260104.safetensors" + vae: "pixel_space" + clip: "t5xxl_fp8_e4m3fn_scaled.safetensors" + Chroma1: + latent_type: sd3_latent + models: + - display_name: "lodestones/Chroma1-HD" + components: + unet: "Chroma1-HD_float8_e4m3fn_scaled_learned_topk8_svd.safetensors" + vae: "ae.safetensors" + clip: "t5xxl_fp8_e4m3fn_scaled.safetensors" + - display_name: "lodestones/Chroma1-HD-Flash" + components: + unet: "Chroma1-HD-Flash_float8_e4m3fn_scaled_learned_topk8_svd.safetensors" + vae: "ae.safetensors" + clip: "t5xxl_fp8_e4m3fn_scaled.safetensors" + OmniGen2: + latent_type: sd3_latent + models: + - display_name: "OmniGen2" + components: + unet: "omnigen2_fp16.safetensors" + vae: "ae.safetensors" + clip: "qwen_2.5_vl_fp16.safetensors" + Lumina: + latent_type: sd3_latent + models: + - display_name: "Alpha-VLLM/Lumina-Image-2.0" + path: "lumina_2.safetensors" + HiDream-O1: + latent_type: hidream_o1_latent + models: + - display_name: "HiDream-O1-Image-Dev" + path: "hidream_o1_image_dev_fp8_scaled.safetensors" + - display_name: "HiDream-O1-Image" + path: "hidream_o1_image_fp8_scaled.safetensors" + HiDream-I1: + latent_type: sd3_latent + models: + - display_name: "HiDream_i1_Dev" + components: + unet: "hidream_i1_dev_fp8.safetensors" + vae: "ae.safetensors" + clip1: "clip_l_hidream.safetensors" + clip2: "clip_g_hidream.safetensors" + clip3: "t5xxl_fp8_e4m3fn_scaled.safetensors" + clip4: "llama_3.1_8b_instruct_fp8_scaled.safetensors" + - display_name: "HiDream_i1_Full" + components: + unet: "hidream_i1_full_fp8.safetensors" + vae: "ae.safetensors" + clip1: "clip_l_hidream.safetensors" + clip2: "clip_g_hidream.safetensors" + clip3: "t5xxl_fp8_e4m3fn_scaled.safetensors" + clip4: "llama_3.1_8b_instruct_fp8_scaled.safetensors" + - display_name: "HiDream_i1_Fast" + components: + unet: "hidream_i1_fast_fp8.safetensors" + vae: "ae.safetensors" + clip1: "clip_l_hidream.safetensors" + clip2: "clip_g_hidream.safetensors" + clip3: "t5xxl_fp8_e4m3fn_scaled.safetensors" + clip4: "llama_3.1_8b_instruct_fp8_scaled.safetensors" + FLUX.1: + latent_type: sd3_latent + models: + - display_name: "flux1-dev" + components: + unet: "flux1-dev-nvfp4.safetensors" + vae: "ae.safetensors" + clip1: "clip_l.safetensors" + clip2: "t5xxl_fp8_e4m3fn_scaled.safetensors" + - display_name: "flux1-schnell" + components: + unet: "flux1-schnell-fp8-e4m3fn.safetensors" + vae: "ae.safetensors" + clip1: "clip_l.safetensors" + clip2: "t5xxl_fp8_e4m3fn_scaled.safetensors" + - display_name: "flux1-krea-dev" + components: + unet: "flux1-krea-dev_fp8_scaled.safetensors" + vae: "ae.safetensors" + clip1: "clip_l.safetensors" + clip2: "t5xxl_fp8_e4m3fn_scaled.safetensors" + AuraFlow: + latent_type: latent + models: + - display_name: "fal/AuraFlow-v0.3" + path: "aura_flow_0.3.safetensors" + SD3.5: + latent_type: sd3_latent + models: + - display_name: "StabilityAI/SD3.5-Large" + path: "sd3.5_large_fp8_scaled.safetensors" + - display_name: "StabilityAI/SD3.5-Medium" + path: "sd3.5_medium_incl_clips_t5xxlfp8scaled.safetensors" + SDXL: + latent_type: latent + models: + # NoobAI + - display_name: "Laxhar/noobai-XL-Vpred-1.0" + path: "NoobAI-XL-Vpred-v1.0.safetensors" + category: "NoobAI" + - display_name: "Laxhar/noobai-XL-1.1" + path: "NoobAI-XL-v1.1.safetensors" + category: "NoobAI" + - display_name: "bluepen5805/noob_v_pencil-XL-3.0.0" + path: "noob_v_pencil-XL-v3.0.0.safetensors" + category: "NoobAI" + - display_name: "RedRayz/hikari_noob_v-pred_1.2.4" + path: "Hikari_Noob_v-pred_1.2.4.safetensors" + category: "NoobAI" + - display_name: "ChenkinNoob/ChenkinNoob-XL-V0.5" + path: "ChenkinNoob-XL-V0.5.safetensors" + category: "NoobAI" + # Illustrious + - display_name: "WAI0731/wai-illustrious-sdxl-v170" + path: "waiIllustriousSDXL_v170.safetensors" + category: "Illustrious" + - display_name: "blue_pen5805/mellow_pencil-XL-v1.0.0" + path: "mellow_pencil-XL-v1.0.0.safetensors" + category: "Illustrious" + - display_name: "blue_pen5805/illustrious_pencil-XL-v5.0.0" + path: "illustrious_pencil-XL-v5.0.0.safetensors" + category: "Illustrious" + - display_name: "Ikena/hassaku-xl-illustrious-v3.0" + path: "hassakuXLIllustrious_v30.safetensors" + category: "Illustrious" + - display_name: "Crody/Nova-Anime-XL-v18.0" + path: "novaAnimeXL_ilV180.safetensors" + category: "Illustrious" + - display_name: "OnomaAIResearch/Illustrious-XL-v2.0" + path: "Illustrious-XL-v2.0.safetensors" + category: "Illustrious" + - display_name: "OnomaAIResearch/Illustrious-XL-v1.1" + path: "Illustrious-XL-v1.1.safetensors" + category: "Illustrious" + - display_name: "OnomaAIResearch/Illustrious-XL-v1.0" + path: "Illustrious-XL-v1.0.safetensors" + category: "Illustrious" + - display_name: "aria1th261/Illustrious-XL-v0.1" + path: "illustriousXL_v01.safetensors" + category: "Illustrious" + # SDXL-Animate + - display_name: "CagliostroLab/Animagine XL 4.0" + path: "animagine-xl-4.0.safetensors" + category: "Animate" + - display_name: "CagliostroLab/Animagine XL 3.1" + path: "animagine-xl-3.1.safetensors" + category: "Animate" + - display_name: "blue_pen5805/4nima_pencil-XL v1.0.1" + path: "4nima_pencil-XL-v1.0.1.safetensors" + category: "Animate" + - display_name: "blue_pen5805/anima_pencil-XL v5.0.0" + path: "anima_pencil-XL-v5.0.0.safetensors" + category: "Animate" + - display_name: "blue_pen5805/blue_pencil-XL v7.0.0" + path: "blue_pencil-XL-v7.0.0.safetensors" + category: "Animate" + # SDXL-Pony + - display_name: "PurpleSmartAI/Pony Diffusion V6 XL" + path: "ponyDiffusionV6XL_v6StartWithThisOne.safetensors" + category: "Pony" + - display_name: "blue_pen5805/pony_pencil-XL v2.0.0" + path: "pony_pencil-XL-v2.0.0.safetensors" + category: "Pony" + - display_name: "Cyberdelia/CyberRealistic Pony v17.0" + path: "CyberRealisticPony_V17.0_FP16.safetensors" + category: "Pony" + # SDXL-Base + - display_name: "stabilityai/SDXL-Base-1.0" + path: "sd_xl_base_1.0.safetensors" + category: "Base" + # SDXL-Turbo + - display_name: "stabilityai/SDXL-Turbo-1.0" + path: "sd_xl_turbo_1.0_fp16.safetensors" + category: "Turbo" + SD1.5: + latent_type: latent + models: + - display_name: "stable-diffusion-v1-5/stable-diffusion-v1-5" + path: "v1-5-pruned-emaonly.safetensors" diff --git a/yaml/pid.yaml b/yaml/pid.yaml new file mode 100644 index 0000000000000000000000000000000000000000..beb96d55312ab8234012503cae641098ba9204ad --- /dev/null +++ b/yaml/pid.yaml @@ -0,0 +1,16 @@ +PiD: + - filepath: "pid_1.5_flux2_1024_to_4096_4step_int8_convrot.safetensors" + latent_format: "flux" + architectures: ["flux2", "flux2-kv", "ideogram-4", "lens", "ernie-image"] + - filepath: "pid_1.5_qwenimage_1024_to_4096_4step_int8_convrot.safetensors" + latent_format: "qwenimage" + architectures: ["anima", "qwen-image", "krea-2"] + - filepath: "pid_1.5_flux1_1024_to_4096_4step_int8_convrot.safetensors" + latent_format: "flux" + architectures: ["longcat-image", "newbie-image", "z-image", "kandinsky-5", "ovis-image", "omnigen2", "chroma1", "hidream-i1", "flux1", "boogu-image"] + - filepath: "pid_sd3_1024_to_4096_4step_bf16.safetensors" + latent_format: "sd3" + architectures: ["sd35"] + - filepath: "pid_sdxl_1024_to_4096_4step_bf16.safetensors" + latent_format: "sdxl" + architectures: ["sdxl"]
一套界面完成文生图、图生图、局部重绘、扩图和高清修复。模型与任务切换会保留你的提示词和已上传素材。