├── .github └── workflows │ └── publish.yml ├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── core ├── __init__.py ├── pipeline.py ├── recaption.py └── transformer.py ├── dsd_imports.py ├── dsd_nodes.py ├── examples ├── example_workflow.json └── workflow.png ├── pyproject.toml ├── requirements.txt ├── utils.py └── web └── js └── showEnhancedPrompt.js /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish to Comfy registry 2 | on: 3 | workflow_dispatch: 4 | push: 5 | branches: 6 | - main 7 | - master 8 | paths: 9 | - "pyproject.toml" 10 | 11 | permissions: 12 | issues: write 13 | 14 | jobs: 15 | publish-node: 16 | name: Publish Custom Node to registry 17 | runs-on: ubuntu-latest 18 | if: ${{ github.repository_owner == 'irreveloper' }} 19 | steps: 20 | - name: Check out code 21 | uses: actions/checkout@v4 22 | with: 23 | submodules: true 24 | - name: Publish Custom Node 25 | uses: Comfy-Org/publish-node-action@v1 26 | with: 27 | ## Add your own personal access token to your Github Repository secrets and reference it here. 28 | personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }} 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Python 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | *.so 6 | .Python 7 | build/ 8 | develop-eggs/ 9 | dist/ 10 | downloads/ 11 | eggs/ 12 | .eggs/ 13 | lib/ 14 | lib64/ 15 | parts/ 16 | sdist/ 17 | var/ 18 | wheels/ 19 | *.egg-info/ 20 | .installed.cfg 21 | *.egg 22 | 23 | # Virtual Environment 24 | venv/ 25 | env/ 26 | ENV/ 27 | 28 | # IDE specific files 29 | .idea/ 30 | .vscode/ 31 | *.swp 32 | *.swo 33 | 34 | # OS specific files 35 | .DS_Store 36 | .DS_Store? 37 | ._* 38 | .Spotlight-V100 39 | .Trashes 40 | ehthumbs.db 41 | Thumbs.db 42 | 43 | # Jupyter Notebook 44 | .ipynb_checkpoints 45 | 46 | # Logs 47 | logs/ 48 | *.log 49 | 50 | # Local configuration 51 | .env 52 | .env.local 53 | .env.development.local 54 | .env.test.local 55 | .env.production.local 56 | 57 | # Distribution / packaging 58 | *.manifest 59 | *.spec 60 | 61 | # Unit test / coverage reports 62 | htmlcov/ 63 | .tox/ 64 | .coverage 65 | .coverage.* 66 | .cache 67 | nosetests.xml 68 | coverage.xml 69 | *.cover 70 | .hypothesis/ 71 | 72 | .DS_Store 73 | .__MACOSX -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ComfyUI-DSD 2 | 3 | An Unofficial ComfyUI custom node package that integrates [Diffusion Self-Distillation (DSD)](https://github.com/primecai/diffusion-self-distillation) for zero-shot customized image generation. 4 | 5 | DSD is a model for subject-preserving image generation that allows you to create images of a specific subject in novel contexts without per-instance tuning. 6 | 7 | ## Features 8 | 9 | - Subject-preserving image generation using DSD model 10 | - Gemini API prompt enhancement 11 | - Direct model download from Hugging Face 12 | - Fine-grained control over generation parameters 13 | - Multiple image resizing options 14 | 15 | ## Installation 16 | 17 | 1. Clone this repository into your ComfyUI custom_nodes folder: 18 | 19 | ```bash 20 | cd ComfyUI/custom_nodes 21 | git clone https://github.com/irreveloper/ComfyUI-DSD.git 22 | ``` 23 | 24 | 2. Install the required dependencies: 25 | 26 | ```bash 27 | pip install -r requirements.txt 28 | ``` 29 | 30 | 3. Get the model files (two options): 31 | - **Option 1**: Use the `DSD Model Downloader` node in ComfyUI to automatically download the model 32 | - **Option 2**: Download manually from [Hugging Face](https://huggingface.co/primecai/dsd_model) or [Google Drive](https://drive.google.com/drive/folders/1VStt7J2whm5RRloa4NK1hGTHuS9WiTfO?usp=sharing) 33 | 34 | The model files will be stored in: 35 | - `ComfyUI/models/dsd_model/transformer/` (for transformer files) 36 | - `ComfyUI/models/dsd_model/pytorch_lora_weights.safetensors` (for LoRA file) 37 | 38 | 4. Restart ComfyUI 39 | 40 | ## Available Nodes 41 | 42 | 1. **DSD Model Downloader**: Automatically downloads the model from Hugging Face 43 | - Supports downloading from custom repositories with the `repo_id` parameter 44 | - Includes options for model precision (bfloat16, float16, float32) 45 | - Provides memory optimization options (low_cpu_mem_usage, model_cpu_offload, sequential_cpu_offload) 46 | - Optional Hugging Face token support via parameter or HF_TOKEN environment variable 47 | 48 | 2. **DSD Model Loader**: Loads a pre-downloaded model 49 | - Supports custom model and LoRA paths 50 | - Multiple precision options (bfloat16, float16, float32) 51 | - Memory optimization options for different hardware configurations 52 | 53 | 3. **DSD Model Selector**: Helps select models from local directories 54 | - Automatically finds models in the default ComfyUI model paths 55 | - Verifies model existence and provides appropriate warnings 56 | 57 | 4. **DSD Gemini Prompt Enhancer**: Uses Google's Gemini API to enhance prompts for better image generation results 58 | - The API key can be provided in two ways: 59 | - As an input parameter to the node (not recommended for sharing workflows) 60 | - Through the `GEMINI_API_KEY` environment variable (strongly recommended) 61 | - Analyzes both the input image and text prompt to generate improved prompts 62 | 63 | Note: To use the enhanced prompts, connect this node's output to the DSD Image Generator's prompt input and enable the `use_gemini_prompt` option. If no API key is provided, the original prompt will be used. 64 | 65 | 5. **DSD Image Generator**: Generates images with the DSD model 66 | - Supports detailed parameter control: 67 | - Guidance scale (overall, image-specific, and text-specific) 68 | - Inference steps 69 | - Resolution control 70 | - Seed control (0 for random seed) 71 | - Returns both the generated image and the reference image 72 | - Displays progress during generation 73 | 74 | 6. **DSD Resize Selector**: Provides flexible image resizing options for the DSD Image Generator: 75 | - **resize_and_center_crop**: Resizes and center crops the image (default behavior) 76 | - **center_crop**: Simple center crop and resize 77 | - **pad**: Preserves aspect ratio and adds padding to reach target size 78 | - **fit**: Resizes to target dimensions without preserving aspect ratio 79 | - Additional customization: 80 | - Interpolation method (LANCZOS, BICUBIC, BILINEAR, NEAREST) 81 | - Padding color (RGB values for pad mode) 82 | 83 | ## Basic Workflow 84 | 85 | ![Sample](examples/workflow.png) 86 | 87 | ## Advanced Usage 88 | 89 | ### Memory Optimization 90 | 91 | The DSD model can be memory-intensive. Several options are available to optimize memory usage: 92 | 93 | - **Precision**: Use `bfloat16` (default) for the best balance of speed and memory usage 94 | - **CPU Offloading**: Enable `model_cpu_offload` or `sequential_cpu_offload` for systems with limited VRAM 95 | - **Resolution**: Lower resolution and fewer inference steps can significantly reduce memory requirements 96 | 97 | ### Gemini API Integration 98 | 99 | For optimal results with the Gemini API: 100 | 1. Obtain a Gemini API key from Google AI Studio 101 | 2. Set it as an environment variable: `GEMINI_API_KEY=your_key_here` 102 | 3. Connect the DSD Gemini Prompt Enhancer to your workflow 103 | 4. Enable `use_gemini_prompt` on the DSD Image Generator 104 | 105 | ### Custom Model Loading 106 | 107 | If you have custom DSD models or want to use a different repository: 108 | 1. Use the DSD Model Downloader with a custom `repo_id` 109 | 2. Or manually download the model files and use DSD Model Loader with custom paths 110 | 111 | ## Troubleshooting 112 | 113 | - **Memory Issues**: Try reducing precision (use bfloat16), lower resolution, or fewer steps 114 | - **Gemini API**: Ensure you have a valid API key (can be set via GEMINI_API_KEY environment variable) 115 | - **Model Loading**: If you see errors, try using the Model Downloader node to re-download files 116 | - **Import Errors**: Make sure all dependencies are installed correctly 117 | - **CUDA Errors**: If you encounter CUDA out-of-memory errors, try enabling CPU offloading options 118 | 119 | ## Examples 120 | 121 | Check the `examples` directory for sample workflows. -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Diffusion Self-Distillation ComfyUI nodes 3 | """ 4 | 5 | from .dsd_nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS 6 | 7 | WEB_DIRECTORY = "./web" 8 | 9 | __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"] -------------------------------------------------------------------------------- /core/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Core components of the Diffusion Self-Distillation (DSD) model. 3 | """ 4 | 5 | from .pipeline import FluxConditionalPipeline 6 | from .transformer import FluxTransformer2DConditionalModel 7 | from .recaption import enhance_prompt 8 | 9 | __all__ = ["FluxConditionalPipeline", "FluxTransformer2DConditionalModel", "enhance_prompt"] -------------------------------------------------------------------------------- /core/pipeline.py: -------------------------------------------------------------------------------- 1 | # Copyright 2024 Black Forest Labs and The HuggingFace Team. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import inspect 16 | from typing import Any, Callable, Dict, List, Optional, Union 17 | 18 | import numpy as np 19 | import torch 20 | from transformers import ( 21 | CLIPTextModel, 22 | CLIPTokenizer, 23 | T5EncoderModel, 24 | T5TokenizerFast, 25 | ) 26 | 27 | from diffusers.image_processor import VaeImageProcessor 28 | from diffusers.loaders import SD3LoraLoaderMixin 29 | from diffusers.models.autoencoders import AutoencoderKL 30 | # from diffusers.models.transformers import FluxTransformer2DModel 31 | from diffusers.schedulers import FlowMatchEulerDiscreteScheduler 32 | from diffusers.utils import ( 33 | USE_PEFT_BACKEND, 34 | is_torch_xla_available, 35 | logging, 36 | replace_example_docstring, 37 | scale_lora_layers, 38 | unscale_lora_layers, 39 | ) 40 | from diffusers.utils.torch_utils import randn_tensor 41 | from diffusers.pipelines.pipeline_utils import DiffusionPipeline 42 | from .recaption import enhance_prompt 43 | from .transformer import FluxTransformer2DConditionalModel 44 | 45 | 46 | if is_torch_xla_available(): 47 | import torch_xla.core.xla_model as xm 48 | 49 | XLA_AVAILABLE = True 50 | else: 51 | XLA_AVAILABLE = False 52 | 53 | 54 | logger = logging.get_logger(__name__) # pylint: disable=invalid-name 55 | 56 | EXAMPLE_DOC_STRING = """ 57 | Examples: 58 | ```py 59 | >>> import torch 60 | >>> from diffusers import FluxPipeline 61 | 62 | >>> pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16) 63 | >>> pipe.to("cuda") 64 | >>> prompt = "A cat holding a sign that says hello world" 65 | >>> # Depending on the variant being used, the pipeline call will slightly vary. 66 | >>> # Refer to the pipeline documentation for more details. 67 | >>> image = pipe(prompt, num_inference_steps=4, guidance_scale=0.0).images[0] 68 | >>> image.save("flux.png") 69 | ``` 70 | """ 71 | 72 | 73 | def calculate_shift( 74 | image_seq_len, 75 | base_seq_len: int = 256, 76 | max_seq_len: int = 4096, 77 | base_shift: float = 0.5, 78 | max_shift: float = 1.16, 79 | ): 80 | m = (max_shift - base_shift) / (max_seq_len - base_seq_len) 81 | b = base_shift - m * base_seq_len 82 | mu = image_seq_len * m + b 83 | return mu 84 | 85 | 86 | # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps 87 | def retrieve_timesteps( 88 | scheduler, 89 | num_inference_steps: Optional[int] = None, 90 | device: Optional[Union[str, torch.device]] = None, 91 | timesteps: Optional[List[int]] = None, 92 | sigmas: Optional[List[float]] = None, 93 | **kwargs, 94 | ): 95 | """ 96 | Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles 97 | custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`. 98 | 99 | Args: 100 | scheduler (`SchedulerMixin`): 101 | The scheduler to get timesteps from. 102 | num_inference_steps (`int`): 103 | The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps` 104 | must be `None`. 105 | device (`str` or `torch.device`, *optional*): 106 | The device to which the timesteps should be moved to. If `None`, the timesteps are not moved. 107 | timesteps (`List[int]`, *optional*): 108 | Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed, 109 | `num_inference_steps` and `sigmas` must be `None`. 110 | sigmas (`List[float]`, *optional*): 111 | Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed, 112 | `num_inference_steps` and `timesteps` must be `None`. 113 | 114 | Returns: 115 | `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the 116 | second element is the number of inference steps. 117 | """ 118 | if timesteps is not None and sigmas is not None: 119 | raise ValueError( 120 | "Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values" 121 | ) 122 | if timesteps is not None: 123 | accepts_timesteps = "timesteps" in set( 124 | inspect.signature(scheduler.set_timesteps).parameters.keys() 125 | ) 126 | if not accepts_timesteps: 127 | raise ValueError( 128 | f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom" 129 | f" timestep schedules. Please check whether you are using the correct scheduler." 130 | ) 131 | scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs) 132 | timesteps = scheduler.timesteps 133 | num_inference_steps = len(timesteps) 134 | elif sigmas is not None: 135 | accept_sigmas = "sigmas" in set( 136 | inspect.signature(scheduler.set_timesteps).parameters.keys() 137 | ) 138 | if not accept_sigmas: 139 | raise ValueError( 140 | f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom" 141 | f" sigmas schedules. Please check whether you are using the correct scheduler." 142 | ) 143 | scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs) 144 | timesteps = scheduler.timesteps 145 | num_inference_steps = len(timesteps) 146 | else: 147 | scheduler.set_timesteps(num_inference_steps, device=device, **kwargs) 148 | timesteps = scheduler.timesteps 149 | return timesteps, num_inference_steps 150 | 151 | 152 | class FluxConditionalPipeline(DiffusionPipeline, SD3LoraLoaderMixin): 153 | r""" 154 | The Flux pipeline for text-to-image generation. 155 | 156 | Reference: https://blackforestlabs.ai/announcing-black-forest-labs/ 157 | 158 | Args: 159 | transformer ([`FluxTransformer2DModel`]): 160 | Conditional Transformer (MMDiT) architecture to denoise the encoded image latents. 161 | scheduler ([`FlowMatchEulerDiscreteScheduler`]): 162 | A scheduler to be used in combination with `transformer` to denoise the encoded image latents. 163 | vae ([`AutoencoderKL`]): 164 | Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. 165 | text_encoder ([`CLIPTextModelWithProjection`]): 166 | [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection), 167 | specifically the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant, 168 | with an additional added projection layer that is initialized with a diagonal matrix with the `hidden_size` 169 | as its dimension. 170 | text_encoder_2 ([`CLIPTextModelWithProjection`]): 171 | [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection), 172 | specifically the 173 | [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k) 174 | variant. 175 | tokenizer (`CLIPTokenizer`): 176 | Tokenizer of class 177 | [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer). 178 | tokenizer_2 (`CLIPTokenizer`): 179 | Second Tokenizer of class 180 | [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer). 181 | """ 182 | 183 | model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae" 184 | _optional_components = [] 185 | _callback_tensor_inputs = ["latents", "prompt_embeds"] 186 | 187 | def __init__( 188 | self, 189 | scheduler: FlowMatchEulerDiscreteScheduler, 190 | vae: AutoencoderKL, 191 | text_encoder: CLIPTextModel, 192 | tokenizer: CLIPTokenizer, 193 | text_encoder_2: T5EncoderModel, 194 | tokenizer_2: T5TokenizerFast, 195 | transformer: FluxTransformer2DConditionalModel, 196 | ): 197 | super().__init__() 198 | 199 | self.register_modules( 200 | vae=vae, 201 | text_encoder=text_encoder, 202 | text_encoder_2=text_encoder_2, 203 | tokenizer=tokenizer, 204 | tokenizer_2=tokenizer_2, 205 | transformer=transformer, 206 | scheduler=scheduler, 207 | ) 208 | self.vae_scale_factor = ( 209 | 2 ** (len(self.vae.config.block_out_channels)) 210 | if hasattr(self, "vae") and self.vae is not None 211 | else 16 212 | ) 213 | self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor) 214 | self.tokenizer_max_length = ( 215 | self.tokenizer.model_max_length 216 | if hasattr(self, "tokenizer") and self.tokenizer is not None 217 | else 77 218 | ) 219 | self.default_sample_size = 64 220 | 221 | def _get_t5_prompt_embeds( 222 | self, 223 | prompt: Union[str, List[str]] = None, 224 | num_images_per_prompt: int = 1, 225 | max_sequence_length: int = 512, 226 | device: Optional[torch.device] = None, 227 | dtype: Optional[torch.dtype] = None, 228 | ): 229 | device = device or self._execution_device 230 | dtype = dtype or self.text_encoder.dtype 231 | 232 | prompt = [prompt] if isinstance(prompt, str) else prompt 233 | batch_size = len(prompt) 234 | 235 | text_inputs = self.tokenizer_2( 236 | prompt, 237 | padding="max_length", 238 | max_length=max_sequence_length, 239 | truncation=True, 240 | return_length=False, 241 | return_overflowing_tokens=False, 242 | return_tensors="pt", 243 | ) 244 | prompt_attention_mask = text_inputs.attention_mask 245 | text_input_ids = text_inputs.input_ids 246 | untruncated_ids = self.tokenizer_2( 247 | prompt, padding="longest", return_tensors="pt" 248 | ).input_ids 249 | 250 | if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal( 251 | text_input_ids, untruncated_ids 252 | ): 253 | removed_text = self.tokenizer_2.batch_decode( 254 | untruncated_ids[:, self.tokenizer_max_length - 1 : -1] 255 | ) 256 | # logger.warning( 257 | # "The following part of your input was truncated because `max_sequence_length` is set to " 258 | # f" {max_sequence_length} tokens: {removed_text}" 259 | # ) 260 | 261 | prompt_embeds = self.text_encoder_2( 262 | text_input_ids.to(device), output_hidden_states=False 263 | )[0] 264 | 265 | dtype = self.text_encoder_2.dtype 266 | prompt_embeds = prompt_embeds.to(dtype=dtype, device=device) 267 | 268 | _, seq_len, _ = prompt_embeds.shape 269 | 270 | # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method 271 | prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1) 272 | prompt_embeds = prompt_embeds.view( 273 | batch_size * num_images_per_prompt, seq_len, -1 274 | ) 275 | 276 | return prompt_embeds, prompt_attention_mask 277 | 278 | def _get_clip_prompt_embeds( 279 | self, 280 | prompt: Union[str, List[str]], 281 | num_images_per_prompt: int = 1, 282 | device: Optional[torch.device] = None, 283 | ): 284 | device = device or self._execution_device 285 | 286 | prompt = [prompt] if isinstance(prompt, str) else prompt 287 | batch_size = len(prompt) 288 | 289 | text_inputs = self.tokenizer( 290 | prompt, 291 | padding="max_length", 292 | max_length=self.tokenizer_max_length, 293 | truncation=True, 294 | return_overflowing_tokens=False, 295 | return_length=False, 296 | return_tensors="pt", 297 | ) 298 | 299 | text_input_ids = text_inputs.input_ids 300 | untruncated_ids = self.tokenizer( 301 | prompt, padding="longest", return_tensors="pt" 302 | ).input_ids 303 | if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal( 304 | text_input_ids, untruncated_ids 305 | ): 306 | removed_text = self.tokenizer.batch_decode( 307 | untruncated_ids[:, self.tokenizer_max_length - 1 : -1] 308 | ) 309 | logger.warning( 310 | "The following part of your input was truncated because CLIP can only handle sequences up to" 311 | f" {self.tokenizer_max_length} tokens: {removed_text}" 312 | ) 313 | prompt_embeds = self.text_encoder( 314 | text_input_ids.to(device), output_hidden_states=False 315 | ) 316 | 317 | # Use pooled output of CLIPTextModel 318 | prompt_embeds = prompt_embeds.pooler_output 319 | prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device) 320 | 321 | # duplicate text embeddings for each generation per prompt, using mps friendly method 322 | prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1) 323 | prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1) 324 | 325 | return prompt_embeds 326 | 327 | def encode_prompt( 328 | self, 329 | prompt: Union[str, List[str]], 330 | prompt_2: Union[str, List[str]], 331 | device: Optional[torch.device] = None, 332 | num_images_per_prompt: int = 1, 333 | prompt_embeds: Optional[torch.FloatTensor] = None, 334 | pooled_prompt_embeds: Optional[torch.FloatTensor] = None, 335 | max_sequence_length: int = 512, 336 | lora_scale: Optional[float] = None, 337 | ): 338 | r""" 339 | 340 | Args: 341 | prompt (`str` or `List[str]`, *optional*): 342 | prompt to be encoded 343 | prompt_2 (`str` or `List[str]`, *optional*): 344 | The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is 345 | used in all text-encoders 346 | device: (`torch.device`): 347 | torch device 348 | num_images_per_prompt (`int`): 349 | number of images that should be generated per prompt 350 | prompt_embeds (`torch.FloatTensor`, *optional*): 351 | Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not 352 | provided, text embeddings will be generated from `prompt` input argument. 353 | pooled_prompt_embeds (`torch.FloatTensor`, *optional*): 354 | Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. 355 | If not provided, pooled text embeddings will be generated from `prompt` input argument. 356 | clip_skip (`int`, *optional*): 357 | Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that 358 | the output of the pre-final layer will be used for computing the prompt embeddings. 359 | lora_scale (`float`, *optional*): 360 | A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded. 361 | """ 362 | device = device or self._execution_device 363 | 364 | # set lora scale so that monkey patched LoRA 365 | # function of text encoder can correctly access it 366 | if lora_scale is not None and isinstance(self, SD3LoraLoaderMixin): 367 | self._lora_scale = lora_scale 368 | 369 | # dynamically adjust the LoRA scale 370 | if self.text_encoder is not None and USE_PEFT_BACKEND: 371 | scale_lora_layers(self.text_encoder, lora_scale) 372 | if self.text_encoder_2 is not None and USE_PEFT_BACKEND: 373 | scale_lora_layers(self.text_encoder_2, lora_scale) 374 | 375 | prompt = [prompt] if isinstance(prompt, str) else prompt 376 | if prompt is not None: 377 | batch_size = len(prompt) 378 | else: 379 | batch_size = prompt_embeds.shape[0] 380 | 381 | prompt_attention_mask = None 382 | if prompt_embeds is None: 383 | prompt_2 = prompt_2 or prompt 384 | prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2 385 | 386 | # We only use the pooled prompt output from the CLIPTextModel 387 | pooled_prompt_embeds = self._get_clip_prompt_embeds( 388 | prompt=prompt, 389 | device=device, 390 | num_images_per_prompt=num_images_per_prompt, 391 | ) 392 | prompt_embeds, prompt_attention_mask = self._get_t5_prompt_embeds( 393 | prompt=prompt_2, 394 | num_images_per_prompt=num_images_per_prompt, 395 | max_sequence_length=max_sequence_length, 396 | device=device 397 | ) 398 | 399 | if self.text_encoder is not None: 400 | if isinstance(self, SD3LoraLoaderMixin) and USE_PEFT_BACKEND: 401 | # Retrieve the original scale by scaling back the LoRA layers 402 | unscale_lora_layers(self.text_encoder, lora_scale) 403 | 404 | if self.text_encoder_2 is not None: 405 | if isinstance(self, SD3LoraLoaderMixin) and USE_PEFT_BACKEND: 406 | # Retrieve the original scale by scaling back the LoRA layers 407 | unscale_lora_layers(self.text_encoder_2, lora_scale) 408 | 409 | text_ids = torch.zeros(batch_size, prompt_embeds.shape[1], 3).to( 410 | device=device, dtype=prompt_embeds.dtype 411 | ) 412 | 413 | return prompt_embeds, pooled_prompt_embeds, text_ids, prompt_attention_mask 414 | 415 | def check_inputs( 416 | self, 417 | prompt, 418 | prompt_2, 419 | height, 420 | width, 421 | prompt_embeds=None, 422 | pooled_prompt_embeds=None, 423 | callback_on_step_end_tensor_inputs=None, 424 | max_sequence_length=None, 425 | image=None 426 | ): 427 | if height % 8 != 0 or width % 8 != 0: 428 | raise ValueError( 429 | f"`height` and `width` have to be divisible by 8 but are {height} and {width}." 430 | ) 431 | 432 | if callback_on_step_end_tensor_inputs is not None and not all( 433 | k in self._callback_tensor_inputs 434 | for k in callback_on_step_end_tensor_inputs 435 | ): 436 | raise ValueError( 437 | f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}" 438 | ) 439 | 440 | if prompt is not None and prompt_embeds is not None: 441 | raise ValueError( 442 | f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to" 443 | " only forward one of the two." 444 | ) 445 | elif prompt_2 is not None and prompt_embeds is not None: 446 | raise ValueError( 447 | f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to" 448 | " only forward one of the two." 449 | ) 450 | elif prompt is None and prompt_embeds is None: 451 | raise ValueError( 452 | "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined." 453 | ) 454 | elif prompt is not None and ( 455 | not isinstance(prompt, str) and not isinstance(prompt, list) 456 | ): 457 | raise ValueError( 458 | f"`prompt` has to be of type `str` or `list` but is {type(prompt)}" 459 | ) 460 | elif prompt_2 is not None and ( 461 | not isinstance(prompt_2, str) and not isinstance(prompt_2, list) 462 | ): 463 | raise ValueError( 464 | f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}" 465 | ) 466 | 467 | if prompt_embeds is not None and pooled_prompt_embeds is None: 468 | raise ValueError( 469 | "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`." 470 | ) 471 | 472 | if max_sequence_length is not None and max_sequence_length > 512: 473 | raise ValueError( 474 | f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}" 475 | ) 476 | 477 | @staticmethod 478 | def _prepare_latent_image_ids(batch_size, height, width, device, dtype): 479 | latent_image_ids = torch.zeros(height // 2, width // 2, 3) 480 | latent_image_ids[..., 1] = ( 481 | latent_image_ids[..., 1] + torch.arange(height // 2)[:, None] 482 | ) 483 | latent_image_ids[..., 2] = ( 484 | latent_image_ids[..., 2] + torch.arange(width // 2)[None, :] 485 | ) 486 | 487 | latent_image_id_height, latent_image_id_width, latent_image_id_channels = ( 488 | latent_image_ids.shape 489 | ) 490 | 491 | latent_image_ids = latent_image_ids[None, :].repeat(batch_size, 1, 1, 1) 492 | latent_image_ids = latent_image_ids.reshape( 493 | batch_size, 494 | latent_image_id_height * latent_image_id_width, 495 | latent_image_id_channels, 496 | ) 497 | 498 | return latent_image_ids.to(device=device, dtype=dtype) 499 | 500 | @staticmethod 501 | def _pack_latents(latents, batch_size, num_channels_latents, height, width): 502 | latents = latents.view( 503 | batch_size, num_channels_latents, height // 2, 2, width // 2, 2 504 | ) 505 | latents = latents.permute(0, 2, 4, 1, 3, 5) 506 | latents = latents.reshape( 507 | batch_size, (height // 2) * (width // 2), num_channels_latents * 4 508 | ) 509 | 510 | return latents 511 | 512 | @staticmethod 513 | def _unpack_latents(latents, height, width, vae_scale_factor): 514 | batch_size, num_patches, channels = latents.shape 515 | 516 | height = height // vae_scale_factor 517 | width = width // vae_scale_factor 518 | 519 | latents = latents.view(batch_size, height, width, channels // 4, 2, 2) 520 | latents = latents.permute(0, 3, 1, 4, 2, 5) 521 | 522 | latents = latents.reshape( 523 | batch_size, channels // (2 * 2), height * 2, width * 2 524 | ) 525 | 526 | return latents 527 | 528 | def prepare_latents( 529 | self, 530 | batch_size, 531 | num_channels_latents, 532 | height, 533 | width, 534 | dtype, 535 | device, 536 | generator, 537 | latents=None, 538 | ): 539 | height = 2 * (int(height) // self.vae_scale_factor) 540 | width = 2 * (int(width) // self.vae_scale_factor) 541 | 542 | shape = (batch_size, num_channels_latents, height, width) 543 | 544 | if latents is not None: 545 | latent_image_ids = self._prepare_latent_image_ids( 546 | batch_size, height, width, device, dtype 547 | ) 548 | return latents.to(device=device, dtype=dtype), latent_image_ids 549 | 550 | if isinstance(generator, list) and len(generator) != batch_size: 551 | raise ValueError( 552 | f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" 553 | f" size of {batch_size}. Make sure the batch size matches the length of the generators." 554 | ) 555 | 556 | latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype) 557 | # _pack_latents(latents, batch_size, num_channels_latents, height, width) 558 | latents = self._pack_latents( 559 | latents, batch_size, num_channels_latents, height, width 560 | ) 561 | 562 | latent_image_ids = self._prepare_latent_image_ids( 563 | batch_size, height, width, device, dtype 564 | ) 565 | 566 | return latents, latent_image_ids 567 | 568 | @property 569 | def guidance_scale(self): 570 | return self._guidance_scale 571 | 572 | @property 573 | def joint_attention_kwargs(self): 574 | return self._joint_attention_kwargs 575 | 576 | @property 577 | def num_timesteps(self): 578 | return self._num_timesteps 579 | 580 | @property 581 | def interrupt(self): 582 | return self._interrupt 583 | 584 | @torch.no_grad() 585 | @replace_example_docstring(EXAMPLE_DOC_STRING) 586 | def __call__( 587 | self, 588 | prompt: Union[str, List[str]] = None, 589 | prompt_mask: Optional[Union[torch.FloatTensor, List[torch.FloatTensor]]] = None, 590 | negative_mask: Optional[ 591 | Union[torch.FloatTensor, List[torch.FloatTensor]] 592 | ] = None, 593 | prompt_2: Optional[Union[str, List[str]]] = None, 594 | height: Optional[int] = None, 595 | width: Optional[int] = None, 596 | num_inference_steps: int = 28, 597 | timesteps: List[int] = None, 598 | guidance_scale: float = 3.5, 599 | num_images_per_prompt: Optional[int] = 1, 600 | generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, 601 | latents: Optional[torch.FloatTensor] = None, 602 | prompt_embeds: Optional[torch.FloatTensor] = None, 603 | pooled_prompt_embeds: Optional[torch.FloatTensor] = None, 604 | output_type: Optional[str] = "pil", 605 | return_dict: bool = True, 606 | joint_attention_kwargs: Optional[Dict[str, Any]] = None, 607 | callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None, 608 | callback_on_step_end_tensor_inputs: List[str] = ["latents"], 609 | max_sequence_length: int = 512, 610 | guidance_scale_real_i: float = 1.0, 611 | guidance_scale_real_t: float = 1.0, 612 | negative_prompt: Union[str, List[str]] = "", 613 | negative_prompt_2: Union[str, List[str]] = "", 614 | negative_prompt_embeds: Optional[torch.FloatTensor] = None, 615 | negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None, 616 | no_cfg_until_timestep: int = 2, 617 | image: Optional[torch.FloatTensor] = None, 618 | cut_output = True 619 | ): 620 | r""" 621 | Function invoked when calling the pipeline for generation. 622 | 623 | Args: 624 | prompt (`str` or `List[str]`, *optional*): 625 | The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`. 626 | instead. 627 | prompt_mask (`str` or `List[str]`, *optional*): 628 | The prompt or prompts to be used as a mask for the image generation. If not defined, `prompt` is used 629 | instead. 630 | prompt_2 (`str` or `List[str]`, *optional*): 631 | The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is 632 | will be used instead 633 | height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): 634 | The height in pixels of the generated image. This is set to 1024 by default for the best results. 635 | width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): 636 | The width in pixels of the generated image. This is set to 1024 by default for the best results. 637 | num_inference_steps (`int`, *optional*, defaults to 50): 638 | The number of denoising steps. More denoising steps usually lead to a higher quality image at the 639 | expense of slower inference. 640 | timesteps (`List[int]`, *optional*): 641 | Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument 642 | in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is 643 | passed will be used. Must be in descending order. 644 | guidance_scale (`float`, *optional*, defaults to 7.0): 645 | Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). 646 | `guidance_scale` is defined as `w` of equation 2. of [Imagen 647 | Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > 648 | 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, 649 | usually at the expense of lower image quality. 650 | num_images_per_prompt (`int`, *optional*, defaults to 1): 651 | The number of images to generate per prompt. 652 | generator (`torch.Generator` or `List[torch.Generator]`, *optional*): 653 | One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html) 654 | to make generation deterministic. 655 | latents (`torch.FloatTensor`, *optional*): 656 | Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image 657 | generation. Can be used to tweak the same generation with different prompts. If not provided, a latents 658 | tensor will ge generated by sampling using the supplied random `generator`. 659 | prompt_embeds (`torch.FloatTensor`, *optional*): 660 | Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not 661 | provided, text embeddings will be generated from `prompt` input argument. 662 | pooled_prompt_embeds (`torch.FloatTensor`, *optional*): 663 | Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. 664 | If not provided, pooled text embeddings will be generated from `prompt` input argument. 665 | output_type (`str`, *optional*, defaults to `"pil"`): 666 | The output format of the generate image. Choose between 667 | [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. 668 | return_dict (`bool`, *optional*, defaults to `True`): 669 | Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple. 670 | joint_attention_kwargs (`dict`, *optional*): 671 | A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under 672 | `self.processor` in 673 | [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). 674 | callback_on_step_end (`Callable`, *optional*): 675 | A function that calls at the end of each denoising steps during the inference. The function is called 676 | with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, 677 | callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by 678 | `callback_on_step_end_tensor_inputs`. 679 | callback_on_step_end_tensor_inputs (`List`, *optional*): 680 | The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list 681 | will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the 682 | `._callback_tensor_inputs` attribute of your pipeline class. 683 | max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`. 684 | 685 | Examples: 686 | 687 | Returns: 688 | [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict` 689 | is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated 690 | images. 691 | """ 692 | 693 | height = height or self.default_sample_size * self.vae_scale_factor 694 | width = width or self.default_sample_size * self.vae_scale_factor 695 | 696 | # 1. Check inputs. Raise error if not correct 697 | self.check_inputs( 698 | prompt, 699 | prompt_2, 700 | height, 701 | width, 702 | prompt_embeds=prompt_embeds, 703 | pooled_prompt_embeds=pooled_prompt_embeds, 704 | callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs, 705 | max_sequence_length=max_sequence_length, 706 | ) 707 | 708 | self._guidance_scale = guidance_scale 709 | self._guidance_scale_real_i = guidance_scale_real_i 710 | self._guidance_scale_real_t = guidance_scale_real_t 711 | self._joint_attention_kwargs = joint_attention_kwargs 712 | self._interrupt = False 713 | 714 | # 2. Define call parameters 715 | if prompt is not None and isinstance(prompt, str): 716 | batch_size = 1 717 | elif prompt is not None and isinstance(prompt, list): 718 | batch_size = len(prompt) 719 | else: 720 | batch_size = prompt_embeds.shape[0] 721 | 722 | device = self._execution_device 723 | 724 | # prompt = enhance_prompt(image, prompt) 725 | # if gemini_prompt: 726 | # while True: 727 | # try: 728 | # prompt = enhance_prompt(image, prompt) 729 | # break # Exit the loop if the function succeeds 730 | # except Exception as e: 731 | # print(f"An error occurred: {e}") 732 | 733 | lora_scale = ( 734 | self.joint_attention_kwargs.get("scale", None) 735 | if self.joint_attention_kwargs is not None 736 | else None 737 | ) 738 | ( 739 | prompt_embeds, 740 | pooled_prompt_embeds, 741 | text_ids, 742 | _, 743 | ) = self.encode_prompt( 744 | prompt=prompt, 745 | prompt_2=prompt_2, 746 | prompt_embeds=prompt_embeds, 747 | pooled_prompt_embeds=pooled_prompt_embeds, 748 | device=device, 749 | num_images_per_prompt=num_images_per_prompt, 750 | max_sequence_length=max_sequence_length, 751 | lora_scale=lora_scale, 752 | ) 753 | 754 | if negative_prompt_2 == "" and negative_prompt != "": 755 | negative_prompt_2 = negative_prompt 756 | 757 | negative_text_ids = text_ids 758 | if guidance_scale_real_i > 1.0 and ( 759 | negative_prompt_embeds is None or negative_pooled_prompt_embeds is None 760 | ): 761 | ( 762 | negative_prompt_embeds, 763 | negative_pooled_prompt_embeds, 764 | negative_text_ids, 765 | _, 766 | ) = self.encode_prompt( 767 | prompt=negative_prompt, 768 | prompt_2=negative_prompt_2, 769 | prompt_embeds=None, 770 | pooled_prompt_embeds=None, 771 | device=device, 772 | num_images_per_prompt=num_images_per_prompt, 773 | max_sequence_length=max_sequence_length, 774 | lora_scale=lora_scale, 775 | ) 776 | 777 | # 3. Preprocess image 778 | image = self.image_processor.preprocess(image) 779 | # image = image[..., :512] 780 | image = torch.nn.functional.interpolate(image, size=(height, width // 2)) 781 | black_image = torch.full((1, 3, height, width // 2), -1.0) 782 | image = torch.cat([image, black_image], dim=3) 783 | latents_cond = self.vae.encode(image.to(dtype=self.vae.dtype).to(device)).latent_dist.sample() 784 | latents_cond = ( 785 | latents_cond - self.vae.config.shift_factor 786 | ) * self.vae.config.scaling_factor 787 | # from customization.utils import mask_random_quadrants 788 | # latent_cond = mask_random_quadrants(latent_cond) 789 | 790 | # 4. Prepare latent variables 791 | num_channels_latents = self.transformer.config.in_channels // 4 792 | latents, latent_image_ids = self.prepare_latents( 793 | batch_size * num_images_per_prompt, 794 | num_channels_latents, 795 | height, 796 | width, 797 | prompt_embeds.dtype, 798 | device, 799 | generator, 800 | latents, 801 | ) 802 | # _pack_latents(latents, batch_size, num_channels_latents, height, width) 803 | latents_cond = self._pack_latents( 804 | latents_cond, batch_size, num_channels_latents, 2 * (int(height) // self.vae_scale_factor), 2 * (int(width) // self.vae_scale_factor) 805 | ) 806 | 807 | # 5. Prepare timesteps 808 | sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) 809 | image_seq_len = latents.shape[1] 810 | mu = calculate_shift( 811 | image_seq_len, 812 | self.scheduler.config.base_image_seq_len, 813 | self.scheduler.config.max_image_seq_len, 814 | self.scheduler.config.base_shift, 815 | self.scheduler.config.max_shift, 816 | ) 817 | timesteps, num_inference_steps = retrieve_timesteps( 818 | self.scheduler, 819 | num_inference_steps, 820 | device, 821 | timesteps, 822 | sigmas, 823 | mu=mu, 824 | ) 825 | num_warmup_steps = max( 826 | len(timesteps) - num_inference_steps * self.scheduler.order, 0 827 | ) 828 | self._num_timesteps = len(timesteps) 829 | 830 | # 6. Denoising loop 831 | with self.progress_bar(total=num_inference_steps) as progress_bar: 832 | for i, t in enumerate(timesteps): 833 | if self.interrupt: 834 | continue 835 | 836 | # broadcast to batch dimension in a way that's compatible with ONNX/Core ML 837 | timestep = t.expand(latents.shape[0]).to(latents.dtype) 838 | 839 | # handle guidance 840 | if self.transformer.config.guidance_embeds: 841 | guidance = torch.tensor( 842 | [guidance_scale], device=device 843 | ) 844 | guidance = guidance.expand(latents.shape[0]) 845 | else: 846 | guidance = None 847 | 848 | extra_transformer_args = {} 849 | if prompt_mask is not None: 850 | extra_transformer_args["attention_mask"] = prompt_mask.to( 851 | device=self.transformer.device 852 | ) 853 | 854 | noise_pred = self.transformer( 855 | hidden_states=latents, 856 | # YiYi notes: divide it by 1000 for now because we scale it by 1000 in the transforme rmodel (we should not keep it but I want to keep the inputs same for the model for testing) 857 | timestep=timestep / 1000, 858 | guidance=guidance, 859 | pooled_projections=pooled_prompt_embeds, 860 | encoder_hidden_states=prompt_embeds, 861 | txt_ids=text_ids, 862 | img_ids=latent_image_ids, 863 | joint_attention_kwargs=self.joint_attention_kwargs, 864 | return_dict=False, 865 | condition_hidden_states=latents_cond, 866 | **extra_transformer_args, 867 | )[0] 868 | 869 | # TODO optionally use batch prediction to speed this up. 870 | if guidance_scale_real_i > 1.0 and i >= no_cfg_until_timestep: 871 | noise_pred_uncond = self.transformer( 872 | hidden_states=latents, 873 | # YiYi notes: divide it by 1000 for now because we scale it by 1000 in the transforme rmodel (we should not keep it but I want to keep the inputs same for the model for testing) 874 | timestep=timestep / 1000, 875 | guidance=guidance, 876 | pooled_projections=negative_pooled_prompt_embeds, 877 | encoder_hidden_states=negative_prompt_embeds, 878 | txt_ids=negative_text_ids, 879 | img_ids=latent_image_ids, 880 | joint_attention_kwargs=self.joint_attention_kwargs, 881 | return_dict=False, 882 | condition_hidden_states=torch.zeros_like(latents_cond), 883 | )[0] 884 | noise_pred_uncond_t = self.transformer( 885 | hidden_states=latents, 886 | # YiYi notes: divide it by 1000 for now because we scale it by 1000 in the transforme rmodel (we should not keep it but I want to keep the inputs same for the model for testing) 887 | timestep=timestep / 1000, 888 | guidance=guidance, 889 | pooled_projections=negative_pooled_prompt_embeds, 890 | encoder_hidden_states=negative_prompt_embeds, 891 | txt_ids=negative_text_ids, 892 | img_ids=latent_image_ids, 893 | joint_attention_kwargs=self.joint_attention_kwargs, 894 | return_dict=False, 895 | condition_hidden_states=latents_cond, 896 | )[0] 897 | 898 | # noise_pred = noise_pred_uncond + guidance_scale_real * ( 899 | # noise_pred - noise_pred_uncond 900 | # ) 901 | noise_pred = ( 902 | noise_pred_uncond 903 | + guidance_scale_real_i 904 | * (noise_pred_uncond_t - noise_pred_uncond) 905 | + guidance_scale_real_t * (noise_pred - noise_pred_uncond_t) 906 | ) 907 | 908 | # compute the previous noisy sample x_t -> x_t-1 909 | latents_dtype = latents.dtype 910 | latents = self.scheduler.step( 911 | noise_pred, t, latents, return_dict=False 912 | )[0] 913 | 914 | if latents.dtype != latents_dtype: 915 | if torch.backends.mps.is_available(): 916 | # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272 917 | latents = latents.to(latents_dtype) 918 | 919 | if callback_on_step_end is not None: 920 | callback_kwargs = {} 921 | for k in callback_on_step_end_tensor_inputs: 922 | callback_kwargs[k] = locals()[k] 923 | callback_outputs = callback_on_step_end(self, i, t, callback_kwargs) 924 | 925 | latents = callback_outputs.pop("latents", latents) 926 | prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds) 927 | 928 | # call the callback, if provided 929 | if i == len(timesteps) - 1 or ( 930 | (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0 931 | ): 932 | progress_bar.update() 933 | 934 | if XLA_AVAILABLE: 935 | xm.mark_step() 936 | 937 | reference_image = None 938 | 939 | if output_type == "latent": 940 | image = latents 941 | 942 | else: 943 | latents = self._unpack_latents( 944 | latents, height, width, self.vae_scale_factor 945 | ) 946 | latents = ( 947 | latents / self.vae.config.scaling_factor 948 | ) + self.vae.config.shift_factor 949 | 950 | image = self.vae.decode( 951 | latents, 952 | return_dict=False, 953 | )[0] 954 | 955 | # Debug the image shape before splitting 956 | print(f"Image shape before splitting: {image.shape}") 957 | 958 | if cut_output: 959 | # Store the reference image (left side) 960 | reference_image = image[...,:width//2].clone() # Use clone to ensure we have a separate copy 961 | # Store the output image (right side) 962 | image = image[..., width//2:] 963 | 964 | # Debug the shapes after splitting 965 | print(f"Reference image shape after splitting: {reference_image.shape}") 966 | print(f"Output image shape after splitting: {image.shape}") 967 | 968 | # Post-process the images 969 | image = self.image_processor.postprocess(image, output_type=output_type) 970 | if reference_image is not None: 971 | reference_image = self.image_processor.postprocess(reference_image, output_type=output_type) 972 | print(f"Reference image type after postprocessing: {type(reference_image)}") 973 | if isinstance(reference_image, list): 974 | print(f"Reference image list length: {len(reference_image)}") 975 | if len(reference_image) > 0: 976 | print(f"First reference image type: {type(reference_image[0])}") 977 | print(f"First reference image size: {reference_image[0].size if hasattr(reference_image[0], 'size') else 'unknown'}") 978 | 979 | # Offload all models 980 | self.maybe_free_model_hooks() 981 | 982 | if not return_dict: 983 | return (image, reference_image) 984 | 985 | return FluxPipelineOutput(images=(image, reference_image)) 986 | 987 | 988 | from dataclasses import dataclass 989 | from typing import List, Union 990 | import PIL.Image 991 | from diffusers.utils import BaseOutput 992 | 993 | 994 | @dataclass 995 | class FluxPipelineOutput(BaseOutput): 996 | """ 997 | Output class for Stable Diffusion pipelines. 998 | 999 | Args: 1000 | images (`List[PIL.Image.Image]` or `np.ndarray` or tuple) 1001 | List of denoised PIL images of length `batch_size` or numpy array of shape `(batch_size, height, width, 1002 | num_channels)` or tuple of (output_image, reference_image). PIL images or numpy array present the denoised 1003 | images of the diffusion pipeline. 1004 | """ 1005 | 1006 | images: Union[List[PIL.Image.Image], np.ndarray, tuple] 1007 | 1008 | def __post_init__(self): 1009 | # Ensure images is always a tuple of (output_image, reference_image) 1010 | if not isinstance(self.images, tuple): 1011 | self.images = (self.images, None) 1012 | -------------------------------------------------------------------------------- /core/recaption.py: -------------------------------------------------------------------------------- 1 | from google import genai 2 | 3 | 4 | def enhance_prompt(image, prompt,api_key): 5 | # input_caption_prompt = "Please provide a prompt for the image for Diffusion Model text-to-image generative model training, i.e. for FLUX or StableDiffusion 3. The prompt should be a detailed description of the image, including the character/asset/item, the environment, the pose, the lighting, the camera view, etc. The prompt should be detailed enough to generate the image. The prompt should be as short and precise as possible, in one-line format, and does not exceed 77 tokens." 6 | input_caption_prompt = ( 7 | "Please provide a prompt for a Diffusion Model text-to-image generative model for the image I will give you. " 8 | "The prompt should be a detailed description of the image, especially the main subject (i.e. the main character/asset/item), the environment, the pose, the lighting, the camera view, the style etc." 9 | "The prompt should be detailed enough to generate the target image. " 10 | # "Identify key elements and that remain consistent from the source image, and highlight differences in the target image. " 11 | # "The prompt should be short, precise, one-line, similar to LAION dataset style, and not exceed 77 tokens. " 12 | # "The prompt should be detailed enough to generate the target image." 13 | "The prompt should be short and precise, in one-line format, and does not exceed 77 tokens." 14 | "The prompt should be individually coherent as a description of the image." 15 | ) 16 | 17 | # Choose a Gemini model. 18 | caption_model = genai.Client(api_key=api_key) 19 | input_image_prompt = caption_model.models.generate_content( 20 | model='gemini-2.0-flash-001', contents=[input_caption_prompt, image]).text 21 | input_image_prompt = input_image_prompt.replace('\r', '').replace('\n', '') 22 | 23 | enhance_instruction = "Enhance this input text prompt: '" 24 | enhance_instruction += prompt 25 | enhance_instruction += "'. Please extract other details, especially description of the main subject from the following reference prompt: '" 26 | enhance_instruction += input_image_prompt 27 | enhance_instruction += "'. Please keep the details that are mentioned in the input prompt, and enhance the rest. " 28 | enhance_instruction += "Response with only the enhanced prompt. " 29 | enhance_instruction += "The enhanced prompt should be short and precise, in one-line format, and does not exceed 77 tokens." 30 | enhanced_prompt = caption_model.models.generate_content( 31 | model='gemini-2.0-flash-001', contents=[enhance_instruction]).text.replace('\r', '').replace('\n', '') 32 | print("input_image_prompt: ", input_image_prompt) 33 | print("prompt: ", prompt) 34 | print("enhanced_prompt: ", enhanced_prompt) 35 | return enhanced_prompt 36 | 37 | 38 | -------------------------------------------------------------------------------- /core/transformer.py: -------------------------------------------------------------------------------- 1 | # Copyright 2024 Black Forest Labs, The HuggingFace Team and The InstantX Team. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | from typing import Any, Dict, Optional, Tuple, Union 17 | 18 | import numpy as np 19 | import torch 20 | import torch.nn as nn 21 | import torch.nn.functional as F 22 | 23 | from diffusers.configuration_utils import ConfigMixin, register_to_config 24 | from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin 25 | from diffusers.models.attention import FeedForward 26 | from diffusers.models.attention_processor import ( 27 | Attention, 28 | AttentionProcessor, 29 | FluxAttnProcessor2_0, 30 | FusedFluxAttnProcessor2_0, 31 | ) 32 | from diffusers.models.modeling_utils import ModelMixin 33 | from diffusers.models.normalization import AdaLayerNormContinuous, AdaLayerNormZero, AdaLayerNormZeroSingle 34 | from diffusers.utils import USE_PEFT_BACKEND, is_torch_version, logging, scale_lora_layers, unscale_lora_layers 35 | from diffusers.utils.torch_utils import maybe_allow_in_graph 36 | from diffusers.models.embeddings import CombinedTimestepGuidanceTextProjEmbeddings, CombinedTimestepTextProjEmbeddings, FluxPosEmbed 37 | from diffusers.models.modeling_outputs import Transformer2DModelOutput 38 | 39 | 40 | logger = logging.get_logger(__name__) # pylint: disable=invalid-name 41 | 42 | 43 | @maybe_allow_in_graph 44 | class FluxSingleTransformerBlock(nn.Module): 45 | r""" 46 | A Transformer block following the MMDiT architecture, introduced in Stable Diffusion 3. 47 | 48 | Reference: https://arxiv.org/abs/2403.03206 49 | 50 | Parameters: 51 | dim (`int`): The number of channels in the input and output. 52 | num_attention_heads (`int`): The number of heads to use for multi-head attention. 53 | attention_head_dim (`int`): The number of channels in each head. 54 | context_pre_only (`bool`): Boolean to determine if we should add some blocks associated with the 55 | processing of `context` conditions. 56 | """ 57 | 58 | def __init__(self, dim, num_attention_heads, attention_head_dim, mlp_ratio=4.0): 59 | super().__init__() 60 | self.mlp_hidden_dim = int(dim * mlp_ratio) 61 | 62 | self.norm = AdaLayerNormZeroSingle(dim) 63 | self.proj_mlp = nn.Linear(dim, self.mlp_hidden_dim) 64 | self.act_mlp = nn.GELU(approximate="tanh") 65 | self.proj_out = nn.Linear(dim + self.mlp_hidden_dim, dim) 66 | 67 | processor = FluxAttnProcessor2_0() 68 | self.attn = Attention( 69 | query_dim=dim, 70 | cross_attention_dim=None, 71 | dim_head=attention_head_dim, 72 | heads=num_attention_heads, 73 | out_dim=dim, 74 | bias=True, 75 | processor=processor, 76 | qk_norm="rms_norm", 77 | eps=1e-6, 78 | pre_only=True, 79 | ) 80 | 81 | def forward( 82 | self, 83 | hidden_states: torch.FloatTensor, 84 | temb: torch.FloatTensor, 85 | image_rotary_emb=None, 86 | ): 87 | residual = hidden_states 88 | norm_hidden_states, gate = self.norm(hidden_states, emb=temb) 89 | mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states)) 90 | 91 | attn_output = self.attn( 92 | hidden_states=norm_hidden_states, 93 | image_rotary_emb=image_rotary_emb, 94 | ) 95 | 96 | hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2) 97 | gate = gate.unsqueeze(1) 98 | hidden_states = gate * self.proj_out(hidden_states) 99 | hidden_states = residual + hidden_states 100 | if hidden_states.dtype == torch.float16: 101 | hidden_states = hidden_states.clip(-65504, 65504) 102 | 103 | return hidden_states 104 | 105 | 106 | @maybe_allow_in_graph 107 | class FluxTransformerBlock(nn.Module): 108 | r""" 109 | A Transformer block following the MMDiT architecture, introduced in Stable Diffusion 3. 110 | 111 | Reference: https://arxiv.org/abs/2403.03206 112 | 113 | Parameters: 114 | dim (`int`): The number of channels in the input and output. 115 | num_attention_heads (`int`): The number of heads to use for multi-head attention. 116 | attention_head_dim (`int`): The number of channels in each head. 117 | context_pre_only (`bool`): Boolean to determine if we should add some blocks associated with the 118 | processing of `context` conditions. 119 | """ 120 | 121 | def __init__(self, dim, num_attention_heads, attention_head_dim, qk_norm="rms_norm", eps=1e-6): 122 | super().__init__() 123 | 124 | self.norm1 = AdaLayerNormZero(dim) 125 | 126 | self.norm1_context = AdaLayerNormZero(dim) 127 | 128 | if hasattr(F, "scaled_dot_product_attention"): 129 | processor = FluxAttnProcessor2_0() 130 | else: 131 | raise ValueError( 132 | "The current PyTorch version does not support the `scaled_dot_product_attention` function." 133 | ) 134 | self.attn = Attention( 135 | query_dim=dim, 136 | cross_attention_dim=None, 137 | added_kv_proj_dim=dim, 138 | dim_head=attention_head_dim, 139 | heads=num_attention_heads, 140 | out_dim=dim, 141 | context_pre_only=False, 142 | bias=True, 143 | processor=processor, 144 | qk_norm=qk_norm, 145 | eps=eps, 146 | ) 147 | 148 | self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6) 149 | self.ff = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate") 150 | 151 | self.norm2_context = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6) 152 | self.ff_context = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate") 153 | 154 | # let chunk size default to None 155 | self._chunk_size = None 156 | self._chunk_dim = 0 157 | 158 | def forward( 159 | self, 160 | hidden_states: torch.FloatTensor, 161 | encoder_hidden_states: torch.FloatTensor, 162 | temb: torch.FloatTensor, 163 | image_rotary_emb=None, 164 | ): 165 | norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb) 166 | 167 | norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context( 168 | encoder_hidden_states, emb=temb 169 | ) 170 | 171 | # Attention. 172 | attn_output, context_attn_output = self.attn( 173 | hidden_states=norm_hidden_states, 174 | encoder_hidden_states=norm_encoder_hidden_states, 175 | image_rotary_emb=image_rotary_emb, 176 | ) 177 | 178 | # Process attention outputs for the `hidden_states`. 179 | attn_output = gate_msa.unsqueeze(1) * attn_output 180 | hidden_states = hidden_states + attn_output 181 | 182 | norm_hidden_states = self.norm2(hidden_states) 183 | norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] 184 | 185 | ff_output = self.ff(norm_hidden_states) 186 | ff_output = gate_mlp.unsqueeze(1) * ff_output 187 | 188 | hidden_states = hidden_states + ff_output 189 | 190 | # Process attention outputs for the `encoder_hidden_states`. 191 | 192 | context_attn_output = c_gate_msa.unsqueeze(1) * context_attn_output 193 | encoder_hidden_states = encoder_hidden_states + context_attn_output 194 | 195 | norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states) 196 | norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None] 197 | 198 | context_ff_output = self.ff_context(norm_encoder_hidden_states) 199 | encoder_hidden_states = encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output 200 | if encoder_hidden_states.dtype == torch.float16: 201 | encoder_hidden_states = encoder_hidden_states.clip(-65504, 65504) 202 | 203 | return encoder_hidden_states, hidden_states 204 | 205 | 206 | class FluxTransformer2DConditionalModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin): 207 | """ 208 | The Transformer model introduced in Flux. 209 | 210 | Reference: https://blackforestlabs.ai/announcing-black-forest-labs/ 211 | 212 | Parameters: 213 | patch_size (`int`): Patch size to turn the input data into small patches. 214 | in_channels (`int`, *optional*, defaults to 16): The number of channels in the input. 215 | num_layers (`int`, *optional*, defaults to 18): The number of layers of MMDiT blocks to use. 216 | num_single_layers (`int`, *optional*, defaults to 18): The number of layers of single DiT blocks to use. 217 | attention_head_dim (`int`, *optional*, defaults to 64): The number of channels in each head. 218 | num_attention_heads (`int`, *optional*, defaults to 18): The number of heads to use for multi-head attention. 219 | joint_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use. 220 | pooled_projection_dim (`int`): Number of dimensions to use when projecting the `pooled_projections`. 221 | guidance_embeds (`bool`, defaults to False): Whether to use guidance embeddings. 222 | """ 223 | 224 | _supports_gradient_checkpointing = True 225 | _no_split_modules = ["FluxTransformerBlock", "FluxSingleTransformerBlock"] 226 | 227 | @register_to_config 228 | def __init__( 229 | self, 230 | patch_size: int = 1, 231 | in_channels: int = 64, 232 | num_layers: int = 19, 233 | num_single_layers: int = 38, 234 | attention_head_dim: int = 128, 235 | num_attention_heads: int = 24, 236 | joint_attention_dim: int = 4096, 237 | pooled_projection_dim: int = 768, 238 | guidance_embeds: bool = False, 239 | axes_dims_rope: Tuple[int] = (16, 56, 56), 240 | ): 241 | super().__init__() 242 | self.out_channels = in_channels 243 | self.inner_dim = self.config.num_attention_heads * self.config.attention_head_dim 244 | 245 | self.pos_embed = FluxPosEmbed(theta=10000, axes_dim=axes_dims_rope) 246 | 247 | text_time_guidance_cls = ( 248 | CombinedTimestepGuidanceTextProjEmbeddings if guidance_embeds else CombinedTimestepTextProjEmbeddings 249 | ) 250 | self.time_text_embed = text_time_guidance_cls( 251 | embedding_dim=self.inner_dim, pooled_projection_dim=self.config.pooled_projection_dim 252 | ) 253 | 254 | self.context_embedder = nn.Linear(self.config.joint_attention_dim, self.inner_dim) 255 | self.x_embedder = torch.nn.Linear(self.config.in_channels, self.inner_dim) 256 | self.c_embedder = zero_module(torch.nn.Linear(self.config.in_channels, self.inner_dim)) 257 | 258 | self.transformer_blocks = nn.ModuleList( 259 | [ 260 | FluxTransformerBlock( 261 | dim=self.inner_dim, 262 | num_attention_heads=self.config.num_attention_heads, 263 | attention_head_dim=self.config.attention_head_dim, 264 | ) 265 | for i in range(self.config.num_layers) 266 | ] 267 | ) 268 | 269 | self.single_transformer_blocks = nn.ModuleList( 270 | [ 271 | FluxSingleTransformerBlock( 272 | dim=self.inner_dim, 273 | num_attention_heads=self.config.num_attention_heads, 274 | attention_head_dim=self.config.attention_head_dim, 275 | ) 276 | for i in range(self.config.num_single_layers) 277 | ] 278 | ) 279 | 280 | self.norm_out = AdaLayerNormContinuous(self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6) 281 | self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=True) 282 | 283 | self.gradient_checkpointing = False 284 | 285 | @property 286 | # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors 287 | def attn_processors(self) -> Dict[str, AttentionProcessor]: 288 | r""" 289 | Returns: 290 | `dict` of attention processors: A dictionary containing all attention processors used in the model with 291 | indexed by its weight name. 292 | """ 293 | # set recursively 294 | processors = {} 295 | 296 | def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]): 297 | if hasattr(module, "get_processor"): 298 | processors[f"{name}.processor"] = module.get_processor() 299 | 300 | for sub_name, child in module.named_children(): 301 | fn_recursive_add_processors(f"{name}.{sub_name}", child, processors) 302 | 303 | return processors 304 | 305 | for name, module in self.named_children(): 306 | fn_recursive_add_processors(name, module, processors) 307 | 308 | return processors 309 | 310 | # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor 311 | def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]): 312 | r""" 313 | Sets the attention processor to use to compute attention. 314 | 315 | Parameters: 316 | processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`): 317 | The instantiated processor class or a dictionary of processor classes that will be set as the processor 318 | for **all** `Attention` layers. 319 | 320 | If `processor` is a dict, the key needs to define the path to the corresponding cross attention 321 | processor. This is strongly recommended when setting trainable attention processors. 322 | 323 | """ 324 | count = len(self.attn_processors.keys()) 325 | 326 | if isinstance(processor, dict) and len(processor) != count: 327 | raise ValueError( 328 | f"A dict of processors was passed, but the number of processors {len(processor)} does not match the" 329 | f" number of attention layers: {count}. Please make sure to pass {count} processor classes." 330 | ) 331 | 332 | def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor): 333 | if hasattr(module, "set_processor"): 334 | if not isinstance(processor, dict): 335 | module.set_processor(processor) 336 | else: 337 | module.set_processor(processor.pop(f"{name}.processor")) 338 | 339 | for sub_name, child in module.named_children(): 340 | fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor) 341 | 342 | for name, module in self.named_children(): 343 | fn_recursive_attn_processor(name, module, processor) 344 | 345 | # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections with FusedAttnProcessor2_0->FusedFluxAttnProcessor2_0 346 | def fuse_qkv_projections(self): 347 | """ 348 | Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value) 349 | are fused. For cross-attention modules, key and value projection matrices are fused. 350 | 351 | 352 | 353 | This API is 🧪 experimental. 354 | 355 | 356 | """ 357 | self.original_attn_processors = None 358 | 359 | for _, attn_processor in self.attn_processors.items(): 360 | if "Added" in str(attn_processor.__class__.__name__): 361 | raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.") 362 | 363 | self.original_attn_processors = self.attn_processors 364 | 365 | for module in self.modules(): 366 | if isinstance(module, Attention): 367 | module.fuse_projections(fuse=True) 368 | 369 | self.set_attn_processor(FusedFluxAttnProcessor2_0()) 370 | 371 | # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections 372 | def unfuse_qkv_projections(self): 373 | """Disables the fused QKV projection if enabled. 374 | 375 | 376 | 377 | This API is 🧪 experimental. 378 | 379 | 380 | 381 | """ 382 | if self.original_attn_processors is not None: 383 | self.set_attn_processor(self.original_attn_processors) 384 | 385 | def _set_gradient_checkpointing(self, module, value=False): 386 | if hasattr(module, "gradient_checkpointing"): 387 | module.gradient_checkpointing = value 388 | 389 | def forward( 390 | self, 391 | hidden_states: torch.Tensor, 392 | encoder_hidden_states: torch.Tensor = None, 393 | pooled_projections: torch.Tensor = None, 394 | timestep: torch.LongTensor = None, 395 | img_ids: torch.Tensor = None, 396 | txt_ids: torch.Tensor = None, 397 | guidance: torch.Tensor = None, 398 | joint_attention_kwargs: Optional[Dict[str, Any]] = None, 399 | controlnet_block_samples=None, 400 | controlnet_single_block_samples=None, 401 | condition_hidden_states: torch.Tensor = None, 402 | return_dict: bool = True, 403 | ) -> Union[torch.FloatTensor, Transformer2DModelOutput]: 404 | """ 405 | The [`FluxTransformer2DModel`] forward method. 406 | 407 | Args: 408 | hidden_states (`torch.FloatTensor` of shape `(batch size, channel, height, width)`): 409 | Input `hidden_states`. 410 | encoder_hidden_states (`torch.FloatTensor` of shape `(batch size, sequence_len, embed_dims)`): 411 | Conditional embeddings (embeddings computed from the input conditions such as prompts) to use. 412 | pooled_projections (`torch.FloatTensor` of shape `(batch_size, projection_dim)`): Embeddings projected 413 | from the embeddings of input conditions. 414 | timestep ( `torch.LongTensor`): 415 | Used to indicate denoising step. 416 | block_controlnet_hidden_states: (`list` of `torch.Tensor`): 417 | A list of tensors that if specified are added to the residuals of transformer blocks. 418 | joint_attention_kwargs (`dict`, *optional*): 419 | A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under 420 | `self.processor` in 421 | [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). 422 | return_dict (`bool`, *optional*, defaults to `True`): 423 | Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain 424 | tuple. 425 | 426 | Returns: 427 | If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a 428 | `tuple` where the first element is the sample tensor. 429 | """ 430 | if joint_attention_kwargs is not None: 431 | joint_attention_kwargs = joint_attention_kwargs.copy() 432 | lora_scale = joint_attention_kwargs.pop("scale", 1.0) 433 | else: 434 | lora_scale = 1.0 435 | 436 | if USE_PEFT_BACKEND: 437 | # weight the lora layers by setting `lora_scale` for each PEFT layer 438 | scale_lora_layers(self, lora_scale) 439 | else: 440 | if joint_attention_kwargs is not None and joint_attention_kwargs.get("scale", None) is not None: 441 | logger.warning( 442 | "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective." 443 | ) 444 | hidden_states = self.x_embedder(hidden_states) + self.c_embedder(condition_hidden_states) 445 | 446 | timestep = timestep.to(hidden_states.dtype) * 1000 447 | if guidance is not None: 448 | guidance = guidance.to(hidden_states.dtype) * 1000 449 | else: 450 | guidance = None 451 | temb = ( 452 | self.time_text_embed(timestep, pooled_projections) 453 | if guidance is None 454 | else self.time_text_embed(timestep, guidance, pooled_projections) 455 | ) 456 | encoder_hidden_states = self.context_embedder(encoder_hidden_states) 457 | 458 | if txt_ids.ndim == 3: 459 | # logger.warning( 460 | # "Passing `txt_ids` 3d torch.Tensor is deprecated." 461 | # "Please remove the batch dimension and pass it as a 2d torch Tensor" 462 | # ) 463 | txt_ids = txt_ids[0] 464 | if img_ids.ndim == 3: 465 | # logger.warning( 466 | # "Passing `img_ids` 3d torch.Tensor is deprecated." 467 | # "Please remove the batch dimension and pass it as a 2d torch Tensor" 468 | # ) 469 | img_ids = img_ids[0] 470 | ids = torch.cat((txt_ids, img_ids), dim=0) 471 | image_rotary_emb = self.pos_embed(ids) 472 | 473 | for index_block, block in enumerate(self.transformer_blocks): 474 | if self.training and self.gradient_checkpointing: 475 | 476 | def create_custom_forward(module, return_dict=None): 477 | def custom_forward(*inputs): 478 | if return_dict is not None: 479 | return module(*inputs, return_dict=return_dict) 480 | else: 481 | return module(*inputs) 482 | 483 | return custom_forward 484 | 485 | ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {} 486 | encoder_hidden_states, hidden_states = torch.utils.checkpoint.checkpoint( 487 | create_custom_forward(block), 488 | hidden_states, 489 | encoder_hidden_states, 490 | temb, 491 | image_rotary_emb, 492 | **ckpt_kwargs, 493 | ) 494 | 495 | else: 496 | encoder_hidden_states, hidden_states = block( 497 | hidden_states=hidden_states, 498 | encoder_hidden_states=encoder_hidden_states, 499 | temb=temb, 500 | image_rotary_emb=image_rotary_emb, 501 | ) 502 | 503 | # controlnet residual 504 | if controlnet_block_samples is not None: 505 | interval_control = len(self.transformer_blocks) / len(controlnet_block_samples) 506 | interval_control = int(np.ceil(interval_control)) 507 | hidden_states = hidden_states + controlnet_block_samples[index_block // interval_control] 508 | 509 | hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1) 510 | 511 | for index_block, block in enumerate(self.single_transformer_blocks): 512 | if self.training and self.gradient_checkpointing: 513 | 514 | def create_custom_forward(module, return_dict=None): 515 | def custom_forward(*inputs): 516 | if return_dict is not None: 517 | return module(*inputs, return_dict=return_dict) 518 | else: 519 | return module(*inputs) 520 | 521 | return custom_forward 522 | 523 | ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {} 524 | hidden_states = torch.utils.checkpoint.checkpoint( 525 | create_custom_forward(block), 526 | hidden_states, 527 | temb, 528 | image_rotary_emb, 529 | **ckpt_kwargs, 530 | ) 531 | 532 | else: 533 | hidden_states = block( 534 | hidden_states=hidden_states, 535 | temb=temb, 536 | image_rotary_emb=image_rotary_emb, 537 | ) 538 | 539 | # controlnet residual 540 | if controlnet_single_block_samples is not None: 541 | interval_control = len(self.single_transformer_blocks) / len(controlnet_single_block_samples) 542 | interval_control = int(np.ceil(interval_control)) 543 | hidden_states[:, encoder_hidden_states.shape[1] :, ...] = ( 544 | hidden_states[:, encoder_hidden_states.shape[1] :, ...] 545 | + controlnet_single_block_samples[index_block // interval_control] 546 | ) 547 | 548 | hidden_states = hidden_states[:, encoder_hidden_states.shape[1] :, ...] 549 | 550 | hidden_states = self.norm_out(hidden_states, temb) 551 | output = self.proj_out(hidden_states) 552 | 553 | if USE_PEFT_BACKEND: 554 | # remove `lora_scale` from each PEFT layer 555 | unscale_lora_layers(self, lora_scale) 556 | 557 | if not return_dict: 558 | return (output,) 559 | 560 | return Transformer2DModelOutput(sample=output) 561 | 562 | def zero_module(module): 563 | for p in module.parameters(): 564 | torch.nn.init.zeros_(p) 565 | return module -------------------------------------------------------------------------------- /dsd_imports.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import importlib 4 | 5 | 6 | 7 | from .core.pipeline import FluxConditionalPipeline 8 | from .core.transformer import FluxTransformer2DConditionalModel 9 | from .core.recaption import enhance_prompt 10 | IMPORTS_AVAILABLE = True 11 | print("Successfully imported DSD components from the node's core module.") 12 | -------------------------------------------------------------------------------- /dsd_nodes.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | import folder_paths 4 | from PIL import Image 5 | import numpy as np 6 | import shutil 7 | import requests 8 | import json 9 | from pathlib import Path 10 | from tqdm import tqdm 11 | from huggingface_hub import hf_hub_download, snapshot_download 12 | 13 | from .utils import get_model_path, get_lora_path, comfy_to_pil, pil_to_comfy, resize_and_center_crop, center_crop, pad_resize, fit_resize 14 | from .dsd_imports import FluxConditionalPipeline, FluxTransformer2DConditionalModel, enhance_prompt, IMPORTS_AVAILABLE 15 | from comfy.utils import ProgressBar 16 | try: 17 | from google import genai 18 | GEMINI_AVAILABLE = True 19 | except ImportError: 20 | GEMINI_AVAILABLE = False 21 | print("Google Gemini API not available. Install with: pip install google-genai") 22 | 23 | # Add support paths 24 | custom_nodes_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) 25 | 26 | # Add ComfyUI models path 27 | comfyui_models_path = os.path.join(os.path.dirname(custom_nodes_dir), "models") 28 | os.makedirs(comfyui_models_path, exist_ok=True) 29 | dsd_model_path = os.path.join(comfyui_models_path, "dsd_model") 30 | os.makedirs(dsd_model_path, exist_ok=True) 31 | 32 | # Register the dsd_model path with ComfyUI 33 | folder_paths.add_model_folder_path("dsd_models", dsd_model_path) 34 | 35 | class DSDModelLoader: 36 | """Loads the DSD (Diffusion Self-Distillation) model""" 37 | 38 | @classmethod 39 | def INPUT_TYPES(cls): 40 | return { 41 | "required": { 42 | "model_path": ("STRING", {"default": ""}), 43 | "lora_path": ("STRING", {"default": ""}), 44 | "device": (["cuda", "cpu"], {"default": "cuda"}), 45 | "dtype": (["bfloat16", "float16", "float32"], {"default": "bfloat16"}), 46 | "low_cpu_mem_usage": ("BOOLEAN", {"default": True, "tooltip": "Reduces CPU memory usage during model loading. Recommended for faster loading."}), 47 | "model_cpu_offload": ("BOOLEAN", {"default": False, "tooltip": "Offloads state dict to reduce memory usage during loading. May slow down inference speed."}), 48 | "sequential_cpu_offload": ("BOOLEAN", {"default": False, "tooltip": "Enables sequential CPU offloading. Only use if low on VRAM. Significantly impacts inference speed."}) 49 | } 50 | } 51 | 52 | RETURN_TYPES = ("DSD_MODEL",) 53 | RETURN_NAMES = ("dsd_model",) 54 | FUNCTION = "load_model" 55 | CATEGORY = "DSD" 56 | 57 | def load_model(self, model_path, lora_path, device, dtype, low_cpu_mem_usage, model_cpu_offload, sequential_cpu_offload): 58 | if not IMPORTS_AVAILABLE: 59 | raise ImportError("Could not import DSD modules. Make sure DSD project files (pipeline.py, transformer.py) are properly installed in the parent directory.") 60 | 61 | # Check if model_path is empty, use default path 62 | if not model_path: 63 | model_path = os.path.join(dsd_model_path, "transformer", "diffusion_pytorch_model.safetensors") 64 | print(f"Using default model path: {model_path}") 65 | 66 | # Check if lora_path is empty, use default path 67 | if not lora_path: 68 | lora_path = os.path.join(dsd_model_path, "pytorch_lora_weights.safetensors") 69 | print(f"Using default lora path: {lora_path}") 70 | 71 | # Check if files exist 72 | if not os.path.exists(model_path): 73 | raise FileNotFoundError(f"Model file not found at {model_path}. Please use DSDModelDownloader to download the model first.") 74 | 75 | if not os.path.exists(lora_path): 76 | raise FileNotFoundError(f"LoRA file not found at {lora_path}. Please use DSDModelDownloader to download the model first.") 77 | 78 | print("Loading model...") 79 | # Convert dtype string to torch dtype 80 | torch_dtype = { 81 | "bfloat16": torch.bfloat16, 82 | "float16": torch.float16, 83 | "float32": torch.float32 84 | }.get(dtype, torch.bfloat16) 85 | 86 | print("Loading transformer...") 87 | 88 | model_folder = os.path.dirname(model_path) 89 | # Load model with user-specified parameters 90 | transformer = FluxTransformer2DConditionalModel.from_pretrained( 91 | model_folder, 92 | torch_dtype=torch_dtype, 93 | low_cpu_mem_usage=low_cpu_mem_usage, 94 | ignore_mismatched_sizes=True, 95 | use_safetensors=True, 96 | ) 97 | 98 | 99 | 100 | print("Loading pipeline...") 101 | 102 | # Use the optimized from_pretrained method (which was monkey-patched in pipeline.py) 103 | # Use the optimized from_pretrained method 104 | pipe = FluxConditionalPipeline.from_pretrained( 105 | "black-forest-labs/FLUX.1-schnell", 106 | transformer=transformer, 107 | torch_dtype=torch_dtype 108 | ) 109 | 110 | # Access and modify scheduler configs 111 | pipe.scheduler.config.shift = 3 112 | pipe.scheduler.config.use_dynamic_shifting = True 113 | 114 | print("Loading LoRA weights...") 115 | 116 | # Load LoRA weights if provided 117 | if lora_path and os.path.exists(lora_path): 118 | pipe.load_lora_weights(lora_path) 119 | 120 | print("Moving to device...") 121 | 122 | # Apply sequential CPU offloading if requested and device is CPU 123 | if model_cpu_offload: 124 | pipe.enable_model_cpu_offload() 125 | if sequential_cpu_offload: 126 | pipe.enable_sequential_cpu_offload() 127 | if not model_cpu_offload and not sequential_cpu_offload: 128 | pipe.to(device) 129 | 130 | 131 | 132 | 133 | print("Model loaded successfully") 134 | 135 | return (pipe,) 136 | 137 | 138 | class DSDGeminiPromptEnhancer: 139 | """Enhances prompts using Google's Gemini API""" 140 | 141 | @classmethod 142 | def INPUT_TYPES(cls): 143 | return { 144 | "required": { 145 | "image": ("IMAGE",), 146 | "prompt": ("STRING", {"multiline": True}), 147 | "api_key": ("STRING", {"default": "", "multiline": False,"tooltip":"Enter your Gemini API key here or use the environment variable GEMINI_API_KEY."}) 148 | } 149 | } 150 | 151 | RETURN_TYPES = ("STRING",) 152 | RETURN_NAMES = ("enhanced_prompt",) 153 | FUNCTION = "enhance_prompt" 154 | CATEGORY = "DSD" 155 | OUTPUT_NODE = True # This ensures that UI data is sent to the node 156 | 157 | def __init__(self): 158 | self.enhanced_prompt = None 159 | 160 | def get_state(self): 161 | return { 162 | "enhanced_prompt": self.enhanced_prompt 163 | } 164 | 165 | def enhance_prompt(self, image, prompt, api_key): 166 | if not IMPORTS_AVAILABLE: 167 | print("Warning: DSD modules not available. Using original prompt.") 168 | self.enhanced_prompt = None 169 | return (prompt,) 170 | 171 | if not GEMINI_AVAILABLE: 172 | print("Warning: Google Gemini API not available. Returning original prompt.") 173 | self.enhanced_prompt = None 174 | return (prompt,) 175 | 176 | if not api_key: 177 | #try to get api key from environment variable 178 | api_key = os.getenv("GEMINI_API_KEY") 179 | if not api_key: 180 | print("Warning: No API key provided for Gemini. Returning original prompt.") 181 | self.enhanced_prompt = None 182 | return (prompt,) 183 | 184 | # Convert from ComfyUI image to PIL 185 | pil_image = comfy_to_pil(image) 186 | 187 | # Use the imported enhance_prompt function 188 | try: 189 | 190 | # Call the imported enhance_prompt function 191 | enhanced_prompt = enhance_prompt(pil_image, prompt, api_key) 192 | 193 | print("Original prompt:", prompt) 194 | print("Enhanced prompt:", enhanced_prompt) 195 | 196 | # Store the enhanced prompt for UI display 197 | self.enhanced_prompt = enhanced_prompt 198 | 199 | # Return the enhanced prompt and explicitly include it in the UI data 200 | # Make sure enhanced_prompt is a proper string, not an array/list of characters 201 | return {"ui": {"enhanced_prompt": str(enhanced_prompt)}, "result": (enhanced_prompt,)} 202 | except Exception as e: 203 | print(f"Error enhancing prompt: {e}") 204 | self.enhanced_prompt = None 205 | return (prompt,) 206 | 207 | 208 | class DSDImageGenerator: 209 | """Generates images using the DSD model""" 210 | 211 | @classmethod 212 | def INPUT_TYPES(cls): 213 | return { 214 | "required": { 215 | "dsd_model": ("DSD_MODEL",), 216 | "image": ("IMAGE",), 217 | "prompt": ("STRING", {"multiline": True}), 218 | "negative_prompt": ("STRING", {"multiline": True, "default": ""}), 219 | "seed": ("INT", {"default": 0, "min": 0, "max": 2147483647}), 220 | "guidance_scale": ("FLOAT", {"default": 3.5, "min": 0.0, "max": 20.0, "step": 0.1}), 221 | "image_guidance_scale": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 20.0, "step": 0.1}), 222 | "text_guidance_scale": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 20.0, "step": 0.1}), 223 | "num_inference_steps": ("INT", {"default": 28, "min": 1, "max": 100}), 224 | "width": ("INT", {"default": 1024, "min": 512, "max": 2048, "step": 64}), 225 | "height": ("INT", {"default": 512, "min": 512, "max": 2048, "step": 64}), 226 | "use_gemini_prompt": ("BOOLEAN", {"default": False}) 227 | }, 228 | "optional": { 229 | "resize_params": ("RESIZE_PARAMS",), 230 | } 231 | } 232 | 233 | RETURN_TYPES = ("IMAGE", "IMAGE", "INT") 234 | RETURN_NAMES = ("image", "reference_image", "seed") 235 | FUNCTION = "generate" 236 | CATEGORY = "DSD" 237 | 238 | def __init__(self): 239 | self.enhanced_prompt = None 240 | # For state tracking 241 | self.progress_value = 0.0 242 | 243 | def get_state(self): 244 | return { 245 | "progress": self.progress_value, 246 | "status_text": self.status_text 247 | } 248 | 249 | @property 250 | def status_text(self): 251 | if self.enhanced_prompt: 252 | return f"Enhanced prompt: {self.enhanced_prompt}" 253 | return "" 254 | 255 | def generate(self, dsd_model, image, prompt, negative_prompt, seed, 256 | guidance_scale, image_guidance_scale, text_guidance_scale, num_inference_steps, 257 | width, height, use_gemini_prompt, resize_params=None): 258 | # Initialize progress bar 259 | pbar = ProgressBar(num_inference_steps) 260 | # Reset progress value 261 | self.progress_value = 0.0 262 | 263 | # Convert from ComfyUI image format to PIL 264 | pil_image = comfy_to_pil(image) 265 | 266 | # Process the image based on resize_params 267 | if resize_params is not None: 268 | method = resize_params.get("method", "center_crop") 269 | interpolation = resize_params.get("interpolation", "LANCZOS") 270 | pad_color = resize_params.get("pad_color", (0, 0, 0)) 271 | 272 | # Apply the selected resize method 273 | if method == "resize_and_center_crop": 274 | pil_image = resize_and_center_crop(pil_image, height, width//2) 275 | elif method == "center_crop": 276 | pil_image = center_crop(pil_image, height, width//2, interpolation) 277 | elif method == "pad": 278 | pil_image = pad_resize(pil_image, height, width//2, pad_color, interpolation) 279 | elif method == "fit": 280 | pil_image = fit_resize(pil_image, height, width//2, interpolation) 281 | else: 282 | # Use the default center_crop_and_resize if no resize_params provided 283 | pil_image = resize_and_center_crop(pil_image, height, width//2) 284 | 285 | # Clean prompt 286 | prompt = prompt.strip().replace("\n", "").replace("\r", "") 287 | negative_prompt = negative_prompt.strip().replace("\n", "").replace("\r", "") 288 | 289 | # If use_gemini_prompt enabled, we've already enhanced the prompt, so just store it to show in the UI 290 | if use_gemini_prompt: 291 | try: 292 | self.enhanced_prompt = prompt 293 | except Exception as e: 294 | print(f"Error enhancing prompt: {e}") 295 | self.enhanced_prompt = None 296 | else: 297 | self.enhanced_prompt = None 298 | 299 | # Set up progress callback 300 | def progress_callback(pipe, step, t, callback_kwargs): 301 | # Update the progress bar 302 | pbar.update_absolute(step + 1) 303 | # Update progress value for state tracking 304 | self.progress_value = (step + 1) / num_inference_steps 305 | return callback_kwargs 306 | 307 | # Set up generator with seed 308 | if seed == 0: 309 | # Use a random seed if 0 is provided 310 | seed = torch.randint(0, 2147483647, (1,)).item() 311 | print(f"Using random seed: {seed}") 312 | 313 | # Create generator with the seed 314 | generator = torch.Generator(device="cuda" if torch.cuda.is_available() else "cpu") 315 | generator.manual_seed(seed) 316 | 317 | 318 | 319 | # Run generation 320 | result = dsd_model( 321 | prompt=prompt, 322 | negative_prompt=negative_prompt, 323 | num_inference_steps=num_inference_steps, 324 | height=height, 325 | width=width, 326 | guidance_scale=guidance_scale, 327 | image=pil_image, 328 | guidance_scale_real_i=image_guidance_scale, 329 | guidance_scale_real_t=text_guidance_scale, 330 | callback_on_step_end=progress_callback, 331 | generator=generator 332 | ).images 333 | 334 | # Debug information 335 | print(f"Result type: {type(result)}") 336 | print(f"Result length: {len(result)}") 337 | 338 | # Get the output image (right side) 339 | output_image = None 340 | if result[0] is not None: 341 | print(f"Output image type: {type(result[0])}") 342 | if isinstance(result[0], list): 343 | print(f"Output image list length: {len(result[0])}") 344 | if len(result[0]) > 0: 345 | print(f"First output image type: {type(result[0][0])}, size: {result[0][0].size if hasattr(result[0][0], 'size') else 'unknown'}") 346 | else: 347 | print(f"Output image size: {result[0].size if hasattr(result[0], 'size') else 'unknown'}") 348 | 349 | # Convert to ComfyUI format 350 | output_image = pil_to_comfy(result[0]) 351 | if output_image is not None: 352 | print(f"Converted output image shape: {output_image.shape}") 353 | 354 | # Get the reference image (left side) 355 | reference_image = None 356 | if len(result) > 1 and result[1] is not None: 357 | print(f"Reference image type: {type(result[1])}") 358 | if isinstance(result[1], list): 359 | print(f"Reference image list length: {len(result[1])}") 360 | if len(result[1]) > 0: 361 | print(f"First reference image type: {type(result[1][0])}, size: {result[1][0].size if hasattr(result[1][0], 'size') else 'unknown'}") 362 | else: 363 | print(f"Reference image size: {result[1].size if hasattr(result[1], 'size') else 'unknown'}") 364 | 365 | # Convert to ComfyUI format 366 | reference_image = pil_to_comfy(result[1]) 367 | if reference_image is not None: 368 | print(f"Converted reference image shape: {reference_image.shape}") 369 | 370 | # Ensure progress is complete 371 | pbar.update_absolute(num_inference_steps) 372 | self.progress_value = 1.0 373 | 374 | 375 | 376 | return (output_image, reference_image, seed) 377 | 378 | 379 | # Add a separate model selector that helps find models in the model directory 380 | class DSDModelSelector: 381 | """Selects a DSD model from the models directory""" 382 | 383 | @classmethod 384 | def INPUT_TYPES(cls): 385 | return { 386 | "required": { 387 | "check_model_exists": ("BOOLEAN", {"default": True}), 388 | } 389 | } 390 | 391 | RETURN_TYPES = ("STRING", "STRING") 392 | RETURN_NAMES = ("model_path", "lora_path") 393 | FUNCTION = "select_model" 394 | CATEGORY = "DSD" 395 | 396 | def select_model(self, check_model_exists): 397 | # Get the transformer path 398 | model_path = os.path.join(dsd_model_path, "transformer", "diffusion_pytorch_model.safetensors") 399 | # Get the lora path 400 | lora_path = os.path.join(dsd_model_path, "pytorch_lora_weights.safetensors") 401 | 402 | # Check if files exist 403 | if check_model_exists: 404 | if not os.path.exists(model_path): 405 | print(f"Warning: Model file not found at {model_path}") 406 | print("You can use DSDModelDownloader to download and load the model.") 407 | 408 | if not os.path.exists(lora_path): 409 | print(f"Warning: LoRA file not found at {lora_path}") 410 | print("You can use DSDModelDownloader to download and load the model.") 411 | 412 | return (model_path, lora_path) 413 | 414 | 415 | class DSDModelDownloader: 416 | """Downloads and loads the DSD model from Hugging Face""" 417 | 418 | @classmethod 419 | def INPUT_TYPES(cls): 420 | return { 421 | "required": { 422 | "repo_id": ("STRING", {"default": "primecai/dsd_model"}), 423 | "force_download": ("BOOLEAN", {"default": False}), 424 | "device": (["cuda", "cpu"], {"default": "cuda"}), 425 | "dtype": (["bfloat16", "float16", "float32"], {"default": "bfloat16", "tooltip": "bfloat16 provides best speed/memory tradeoff"}), 426 | "low_cpu_mem_usage": ("BOOLEAN", {"default": True, "tooltip": "Reduces CPU memory usage during model loading. Recommended for faster loading."}), 427 | "model_cpu_offload": ("BOOLEAN", {"default": False, "tooltip": "Offloads state dict to reduce memory usage during loading. May slow down loading speed."}), 428 | "sequential_cpu_offload": ("BOOLEAN", {"default": False, "tooltip": "Enables sequential CPU offloading. Only use if low on VRAM. Significantly impacts loading speed."}) 429 | } 430 | } 431 | 432 | RETURN_TYPES = ("DSD_MODEL", "STRING", "STRING") 433 | RETURN_NAMES = ("dsd_model", "model_path", "lora_path") 434 | FUNCTION = "download_and_load_model" 435 | CATEGORY = "DSD" 436 | 437 | def __init__(self): 438 | self.progress_value = 0.0 439 | self.status_text = "" 440 | 441 | def get_state(self): 442 | return { 443 | "progress": self.progress_value, 444 | "status_text": self.status_text 445 | } 446 | 447 | def download_and_load_model(self, repo_id, force_download, device, dtype, low_cpu_mem_usage, model_cpu_offload, sequential_cpu_offload): 448 | if not IMPORTS_AVAILABLE: 449 | raise ImportError("Could not import DSD modules. Make sure DSD project files (pipeline.py, transformer.py) are properly installed in the parent directory.") 450 | 451 | # Create the dsd_model directory in ComfyUI models folder if it doesn't exist 452 | os.makedirs(dsd_model_path, exist_ok=True) 453 | transformer_path = os.path.join(dsd_model_path, "transformer") 454 | os.makedirs(transformer_path, exist_ok=True) 455 | 456 | # Check if model already exists 457 | model_file = os.path.join(transformer_path, "diffusion_pytorch_model.safetensors") 458 | config_file = os.path.join(transformer_path, "config.json") 459 | lora_file = os.path.join(dsd_model_path, "pytorch_lora_weights.safetensors") 460 | 461 | files_exist = os.path.exists(model_file) and os.path.exists(config_file) and os.path.exists(lora_file) 462 | 463 | if not files_exist or force_download: 464 | self.status_text = f"Downloading DSD model from {repo_id}..." 465 | print(self.status_text) 466 | self.progress_value = 0.1 467 | 468 | try: 469 | # Download the model files 470 | self.status_text = "Downloading transformer model and LoRA weights..." 471 | print(self.status_text) 472 | 473 | # Use snapshot_download to download all files 474 | snapshot_download( 475 | repo_id=repo_id, 476 | local_dir=dsd_model_path, 477 | local_dir_use_symlinks=False, 478 | resume_download=True 479 | ) 480 | 481 | self.progress_value = 0.5 482 | self.status_text = "Model downloaded successfully" 483 | print(self.status_text) 484 | 485 | # Verify files were downloaded correctly 486 | if not os.path.exists(model_file): 487 | raise FileNotFoundError(f"Model file not found at {model_file} after download. The repository structure may be different than expected.") 488 | 489 | if not os.path.exists(config_file): 490 | raise FileNotFoundError(f"Config file not found at {config_file} after download. The repository structure may be different than expected.") 491 | 492 | if not os.path.exists(lora_file): 493 | raise FileNotFoundError(f"LoRA file not found at {lora_file} after download. The repository structure may be different than expected.") 494 | 495 | except Exception as e: 496 | self.status_text = f"Error downloading model: {str(e)}" 497 | print(self.status_text) 498 | raise 499 | else: 500 | self.status_text = "Model files already exist. Skipping download." 501 | print(self.status_text) 502 | self.progress_value = 0.5 503 | 504 | # Convert dtype string to torch dtype 505 | torch_dtype = { 506 | "bfloat16": torch.bfloat16, 507 | "float16": torch.float16, 508 | "float32": torch.float32 509 | }.get(dtype, torch.bfloat16) 510 | 511 | self.status_text = "Loading transformer..." 512 | print(self.status_text) 513 | self.progress_value = 0.6 514 | 515 | try: 516 | # Load model with user-specified parameters 517 | transformer = FluxTransformer2DConditionalModel.from_pretrained( 518 | transformer_path, 519 | torch_dtype=torch_dtype, 520 | low_cpu_mem_usage=low_cpu_mem_usage, 521 | ignore_mismatched_sizes=True, 522 | use_safetensors=True 523 | ) 524 | 525 | self.status_text = "Loading pipeline..." 526 | print(self.status_text) 527 | self.progress_value = 0.7 528 | 529 | 530 | 531 | 532 | # Using black-forest-labs/FLUX.1-schnell,so we don't need to login to Hugging Face 533 | pipe = FluxConditionalPipeline.from_pretrained( 534 | "black-forest-labs/FLUX.1-schnell", 535 | transformer=transformer, 536 | torch_dtype=torch_dtype 537 | ) 538 | 539 | # Access and modify scheduler configs 540 | pipe.scheduler.config.shift = 3 541 | pipe.scheduler.config.use_dynamic_shifting = True 542 | 543 | 544 | 545 | self.status_text = "Loading LoRA weights..." 546 | print(self.status_text) 547 | self.progress_value = 0.8 548 | 549 | # Load LoRA weights 550 | pipe.load_lora_weights(lora_file) 551 | 552 | # Apply sequential CPU offloading if requested and device is CPU 553 | if model_cpu_offload: 554 | pipe.enable_model_cpu_offload() 555 | if sequential_cpu_offload: 556 | pipe.enable_sequential_cpu_offload() 557 | if not model_cpu_offload and not sequential_cpu_offload: 558 | pipe.to(device) 559 | 560 | self.progress_value = 0.9 561 | 562 | self.status_text = "Model loaded successfully" 563 | print(self.status_text) 564 | self.progress_value = 1.0 565 | 566 | return (pipe, model_file, lora_file) 567 | 568 | except Exception as e: 569 | self.status_text = f"Error loading model: {str(e)}" 570 | print(self.status_text) 571 | raise 572 | 573 | 574 | class DSDResizeSelector: 575 | """Selects image resize options for DSD Image Generator""" 576 | 577 | @classmethod 578 | def INPUT_TYPES(cls): 579 | return { 580 | "required": { 581 | "resize_method": (["resize_and_center_crop", "center_crop", "pad", "fit"], {"default": "resize_and_center_crop"}), 582 | "interpolation": (["LANCZOS", "BICUBIC", "BILINEAR", "NEAREST"], {"default": "LANCZOS"}), 583 | "pad_r": ("INT", {"default": 0, "min": 0, "max": 255}), 584 | "pad_g": ("INT", {"default": 0, "min": 0, "max": 255}), 585 | "pad_b": ("INT", {"default": 0, "min": 0, "max": 255}), 586 | } 587 | } 588 | 589 | RETURN_TYPES = ("RESIZE_PARAMS",) 590 | RETURN_NAMES = ("resize_params",) 591 | FUNCTION = "select_resize_options" 592 | CATEGORY = "DSD" 593 | 594 | def select_resize_options(self, resize_method, interpolation, pad_r, pad_g, pad_b): 595 | # Create a JSON object with the resize parameters 596 | resize_params = { 597 | "method": resize_method, 598 | "interpolation": interpolation, 599 | "pad_color": (pad_r, pad_g, pad_b) 600 | } 601 | 602 | return (resize_params,) 603 | 604 | 605 | # Register nodes 606 | NODE_CLASS_MAPPINGS = { 607 | "DSDModelLoader": DSDModelLoader, 608 | "DSDGeminiPromptEnhancer": DSDGeminiPromptEnhancer, 609 | "DSDImageGenerator": DSDImageGenerator, 610 | "DSDModelSelector": DSDModelSelector, 611 | "DSDModelDownloader": DSDModelDownloader, 612 | "DSDResizeSelector": DSDResizeSelector 613 | } 614 | 615 | # Node display names 616 | NODE_DISPLAY_NAME_MAPPINGS = { 617 | "DSDModelLoader": "DSD Model Loader", 618 | "DSDGeminiPromptEnhancer": "DSD Gemini Prompt Enhancer", 619 | "DSDImageGenerator": "DSD Image Generator", 620 | "DSDModelSelector": "DSD Model Selector", 621 | "DSDModelDownloader": "DSD Model Downloader", 622 | "DSDResizeSelector": "DSD Resize Selector" 623 | } -------------------------------------------------------------------------------- /examples/example_workflow.json: -------------------------------------------------------------------------------- 1 | { 2 | "last_node_id": 39, 3 | "last_link_id": 117, 4 | "nodes": [ 5 | { 6 | "id": 18, 7 | "type": "PreviewImage", 8 | "pos": [ 9 | 1214.10986328125, 10 | -74.78528594970703 11 | ], 12 | "size": [ 13 | 406.026123046875, 14 | 409.0712585449219 15 | ], 16 | "flags": {}, 17 | "order": 7, 18 | "mode": 0, 19 | "inputs": [ 20 | { 21 | "name": "images", 22 | "type": "IMAGE", 23 | "link": 115 24 | } 25 | ], 26 | "outputs": [], 27 | "properties": { 28 | "cnr_id": "comfy-core", 29 | "ver": "0.3.26", 30 | "Node name for S&R": "PreviewImage" 31 | }, 32 | "widgets_values": [] 33 | }, 34 | { 35 | "id": 3, 36 | "type": "LoadImage", 37 | "pos": [ 38 | -119.63543701171875, 39 | -71.78013610839844 40 | ], 41 | "size": [ 42 | 366.44219970703125, 43 | 419.337890625 44 | ], 45 | "flags": {}, 46 | "order": 0, 47 | "mode": 0, 48 | "inputs": [], 49 | "outputs": [ 50 | { 51 | "name": "IMAGE", 52 | "type": "IMAGE", 53 | "shape": 3, 54 | "links": [ 55 | 4, 56 | 109 57 | ], 58 | "slot_index": 0 59 | }, 60 | { 61 | "name": "MASK", 62 | "type": "MASK", 63 | "shape": 3, 64 | "links": [] 65 | } 66 | ], 67 | "properties": { 68 | "cnr_id": "comfy-core", 69 | "ver": "0.3.26", 70 | "Node name for S&R": "LoadImage" 71 | }, 72 | "widgets_values": [ 73 | "DALL·E 2024-08-18 18.34.08 - A 2D anime-style character concept art in the style of Porco Rosso. The character is a young, male airplane mechanic in his early 20s, with messy brow.webp", 74 | "image" 75 | ] 76 | }, 77 | { 78 | "id": 19, 79 | "type": "PreviewImage", 80 | "pos": [ 81 | 1271.379638671875, 82 | 431.7550964355469 83 | ], 84 | "size": [ 85 | 210, 86 | 246 87 | ], 88 | "flags": {}, 89 | "order": 8, 90 | "mode": 0, 91 | "inputs": [ 92 | { 93 | "name": "images", 94 | "type": "IMAGE", 95 | "link": 113 96 | } 97 | ], 98 | "outputs": [], 99 | "properties": { 100 | "cnr_id": "comfy-core", 101 | "ver": "0.3.26", 102 | "Node name for S&R": "PreviewImage" 103 | }, 104 | "widgets_values": [] 105 | }, 106 | { 107 | "id": 5, 108 | "type": "DSDGeminiPromptEnhancer", 109 | "pos": [ 110 | 299.41937255859375, 111 | 386.8332824707031 112 | ], 113 | "size": [ 114 | 334.03948974609375, 115 | 137.88925170898438 116 | ], 117 | "flags": {}, 118 | "order": 5, 119 | "mode": 0, 120 | "inputs": [ 121 | { 122 | "name": "image", 123 | "type": "IMAGE", 124 | "link": 4 125 | }, 126 | { 127 | "name": "prompt", 128 | "type": "STRING", 129 | "widget": { 130 | "name": "prompt" 131 | }, 132 | "link": 5 133 | } 134 | ], 135 | "outputs": [ 136 | { 137 | "name": "enhanced_prompt", 138 | "type": "STRING", 139 | "shape": 3, 140 | "links": [ 141 | 110 142 | ], 143 | "slot_index": 0 144 | } 145 | ], 146 | "properties": { 147 | "cnr_id": "dsd", 148 | "ver": "4642def54ab46095a128cc2f8d37abde99a0f099", 149 | "Node name for S&R": "DSDGeminiPromptEnhancer", 150 | "aux_id": "irreveloper/ComfyUI-DSD-Node" 151 | }, 152 | "widgets_values": [ 153 | "Side view of anime character.", 154 | "" 155 | ] 156 | }, 157 | { 158 | "id": 39, 159 | "type": "DSDResizeSelector", 160 | "pos": [ 161 | 314.8365478515625, 162 | 171.76687622070312 163 | ], 164 | "size": [ 165 | 315, 166 | 154 167 | ], 168 | "flags": {}, 169 | "order": 1, 170 | "mode": 0, 171 | "inputs": [], 172 | "outputs": [ 173 | { 174 | "name": "resize_params", 175 | "type": "RESIZE_PARAMS", 176 | "links": [ 177 | 117 178 | ], 179 | "slot_index": 0 180 | } 181 | ], 182 | "properties": { 183 | "cnr_id": "dsd", 184 | "ver": "48d020ac58d05c8a14223dac597a645ee908684a", 185 | "Node name for S&R": "DSDResizeSelector" 186 | }, 187 | "widgets_values": [ 188 | "resize_and_center_crop", 189 | "LANCZOS", 190 | 0, 191 | 0, 192 | 0 193 | ] 194 | }, 195 | { 196 | "id": 38, 197 | "type": "DSDModelDownloader", 198 | "pos": [ 199 | 328.3520812988281, 200 | -165.09207153320312 201 | ], 202 | "size": [ 203 | 315, 204 | 266 205 | ], 206 | "flags": {}, 207 | "order": 2, 208 | "mode": 0, 209 | "inputs": [], 210 | "outputs": [ 211 | { 212 | "name": "dsd_model", 213 | "type": "DSD_MODEL", 214 | "links": [ 215 | 116 216 | ] 217 | }, 218 | { 219 | "name": "model_path", 220 | "type": "STRING", 221 | "links": null 222 | }, 223 | { 224 | "name": "lora_path", 225 | "type": "STRING", 226 | "links": null 227 | } 228 | ], 229 | "properties": { 230 | "cnr_id": "dsd", 231 | "ver": "4642def54ab46095a128cc2f8d37abde99a0f099", 232 | "Node name for S&R": "DSDModelDownloader", 233 | "aux_id": "irreveloper/ComfyUI-DSD-Node" 234 | }, 235 | "widgets_values": [ 236 | "primecai/dsd_model", 237 | false, 238 | "cuda", 239 | "bfloat16", 240 | true, 241 | false, 242 | false, 243 | "" 244 | ] 245 | }, 246 | { 247 | "id": 4, 248 | "type": "PrimitiveNode", 249 | "pos": [ 250 | -117.78815460205078, 251 | 407.2402648925781 252 | ], 253 | "size": [ 254 | 315, 255 | 130 256 | ], 257 | "flags": {}, 258 | "order": 3, 259 | "mode": 0, 260 | "inputs": [], 261 | "outputs": [ 262 | { 263 | "name": "STRING", 264 | "type": "STRING", 265 | "shape": 3, 266 | "links": [ 267 | 5 268 | ], 269 | "slot_index": 0 270 | } 271 | ], 272 | "properties": { 273 | "Run widget replace on values": false 274 | }, 275 | "widgets_values": [ 276 | "Side view of anime character." 277 | ] 278 | }, 279 | { 280 | "id": 11, 281 | "type": "PrimitiveNode", 282 | "pos": [ 283 | -106.84088897705078, 284 | 607.5902099609375 285 | ], 286 | "size": [ 287 | 301.3577880859375, 288 | 88 289 | ], 290 | "flags": {}, 291 | "order": 4, 292 | "mode": 0, 293 | "inputs": [], 294 | "outputs": [ 295 | { 296 | "name": "STRING", 297 | "type": "STRING", 298 | "links": [ 299 | 111 300 | ] 301 | } 302 | ], 303 | "title": "negative_prompt", 304 | "properties": { 305 | "Run widget replace on values": false 306 | }, 307 | "widgets_values": [ 308 | "text, watermark, blurry" 309 | ] 310 | }, 311 | { 312 | "id": 37, 313 | "type": "DSDImageGenerator", 314 | "pos": [ 315 | 721.5396728515625, 316 | 86.6509017944336 317 | ], 318 | "size": [ 319 | 400, 320 | 398 321 | ], 322 | "flags": {}, 323 | "order": 6, 324 | "mode": 0, 325 | "inputs": [ 326 | { 327 | "name": "dsd_model", 328 | "type": "DSD_MODEL", 329 | "link": 116 330 | }, 331 | { 332 | "name": "image", 333 | "type": "IMAGE", 334 | "link": 109 335 | }, 336 | { 337 | "name": "prompt", 338 | "type": "STRING", 339 | "widget": { 340 | "name": "prompt" 341 | }, 342 | "link": 110 343 | }, 344 | { 345 | "name": "negative_prompt", 346 | "type": "STRING", 347 | "widget": { 348 | "name": "negative_prompt" 349 | }, 350 | "link": 111 351 | }, 352 | { 353 | "name": "resize_params", 354 | "type": "RESIZE_PARAMS", 355 | "shape": 7, 356 | "link": 117 357 | } 358 | ], 359 | "outputs": [ 360 | { 361 | "name": "image", 362 | "type": "IMAGE", 363 | "links": [ 364 | 115 365 | ] 366 | }, 367 | { 368 | "name": "reference_image", 369 | "type": "IMAGE", 370 | "links": [ 371 | 113 372 | ] 373 | }, 374 | { 375 | "name": "seed", 376 | "type": "INT", 377 | "links": [] 378 | } 379 | ], 380 | "properties": { 381 | "cnr_id": "dsd", 382 | "ver": "4642def54ab46095a128cc2f8d37abde99a0f099", 383 | "Node name for S&R": "DSDImageGenerator", 384 | "aux_id": "irreveloper/ComfyUI-DSD-Node" 385 | }, 386 | "widgets_values": [ 387 | "", 388 | "text, watermark, blurry", 389 | 3, 390 | "fixed", 391 | 3.5, 392 | 1, 393 | 1, 394 | 28, 395 | 1024, 396 | 512, 397 | true 398 | ] 399 | } 400 | ], 401 | "links": [ 402 | [ 403 | 4, 404 | 3, 405 | 0, 406 | 5, 407 | 0, 408 | "IMAGE" 409 | ], 410 | [ 411 | 5, 412 | 4, 413 | 0, 414 | 5, 415 | 1, 416 | "STRING" 417 | ], 418 | [ 419 | 109, 420 | 3, 421 | 0, 422 | 37, 423 | 1, 424 | "IMAGE" 425 | ], 426 | [ 427 | 110, 428 | 5, 429 | 0, 430 | 37, 431 | 2, 432 | "STRING" 433 | ], 434 | [ 435 | 111, 436 | 11, 437 | 0, 438 | 37, 439 | 3, 440 | "STRING" 441 | ], 442 | [ 443 | 113, 444 | 37, 445 | 1, 446 | 19, 447 | 0, 448 | "IMAGE" 449 | ], 450 | [ 451 | 115, 452 | 37, 453 | 0, 454 | 18, 455 | 0, 456 | "IMAGE" 457 | ], 458 | [ 459 | 116, 460 | 38, 461 | 0, 462 | 37, 463 | 0, 464 | "DSD_MODEL" 465 | ], 466 | [ 467 | 117, 468 | 39, 469 | 0, 470 | 37, 471 | 4, 472 | "RESIZE_PARAMS" 473 | ] 474 | ], 475 | "groups": [], 476 | "config": {}, 477 | "extra": { 478 | "ds": { 479 | "scale": 0.8768324088719838, 480 | "offset": [ 481 | 773.2185529985686, 482 | 450.555653889974 483 | ] 484 | } 485 | }, 486 | "version": 0.4 487 | } -------------------------------------------------------------------------------- /examples/workflow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/irreveloper/ComfyUI-DSD/6af416966bdc6373c402079289661f37e8070061/examples/workflow.png -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "dsd" 3 | description = "An Unofficial ComfyUI custom node package that integrates [a/Diffusion Self-Distillation (DSD)](https://github.com/primecai/diffusion-self-distillation) for zero-shot customized image generation.\nDSD is a model for subject-preserving image generation that allows you to create images of a specific subject in novel contexts without per-instance tuning." 4 | version = "1.0.2" 5 | license = {file = "LICENSE"} 6 | dependencies = ["torch>=2.0.0", "diffusers>=0.24.0", "transformers>=4.36.0", "sentencepiece>=0.1.99", "accelerate>=0.27.0", "google-genai>=0.1.0", "Pillow>=9.5.0", "protobuf>=4.25.0", "peft>=0.7.0", "hf_transfer"] 7 | 8 | [project.urls] 9 | Repository = "https://github.com/irreveloper/ComfyUI-DSD" 10 | # Used by Comfy Registry https://comfyregistry.org 11 | 12 | [tool.comfy] 13 | PublisherId = "irreveloper" 14 | DisplayName = "ComfyUI-DSD" 15 | Icon = "" 16 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | torch>=2.0.0 2 | diffusers>=0.24.0 3 | transformers>=4.36.0 4 | sentencepiece>=0.1.99 5 | accelerate>=0.27.0 6 | google-genai>=0.1.0 7 | Pillow>=9.5.0 8 | protobuf>=4.25.0 9 | peft>=0.7.0 10 | hf_transfer -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | import numpy as np 4 | from PIL import Image 5 | from typing import Union, List, Optional 6 | 7 | def get_model_path(model_name: str) -> str: 8 | """ 9 | Get the path to a model file in the models directory. 10 | 11 | Args: 12 | model_name: Name of the model file or directory 13 | 14 | Returns: 15 | Full path to the model 16 | """ 17 | # Determine the path to the models directory 18 | current_dir = os.path.dirname(os.path.abspath(__file__)) 19 | models_dir = os.path.join(current_dir, "models") 20 | 21 | # Check if the model exists 22 | model_path = os.path.join(models_dir, model_name) 23 | if not os.path.exists(model_path): 24 | raise FileNotFoundError(f"Model {model_name} not found in {models_dir}") 25 | 26 | return model_path 27 | 28 | def get_lora_path(lora_name: str) -> str: 29 | """ 30 | Get the path to a LoRA file in the loras directory. 31 | 32 | Args: 33 | lora_name: Name of the LoRA file 34 | 35 | Returns: 36 | Full path to the LoRA file 37 | """ 38 | # Determine the path to the loras directory 39 | current_dir = os.path.dirname(os.path.abspath(__file__)) 40 | loras_dir = os.path.join(current_dir, "loras") 41 | 42 | # Check if the LoRA file exists 43 | lora_path = os.path.join(loras_dir, lora_name) 44 | if not os.path.exists(lora_path): 45 | raise FileNotFoundError(f"LoRA file {lora_name} not found in {loras_dir}") 46 | 47 | return lora_path 48 | 49 | def comfy_to_pil(image: torch.Tensor) -> Image.Image: 50 | """ 51 | Convert a ComfyUI image tensor to a PIL Image. 52 | 53 | Args: 54 | image: ComfyUI image tensor (1, H, W, 3) in range [0, 1] 55 | 56 | Returns: 57 | PIL Image 58 | """ 59 | # Convert to numpy array and scale to [0, 255] 60 | image_np = np.clip(255. * image[0].cpu().numpy(), 0, 255).astype(np.uint8) 61 | # Convert to PIL Image 62 | return Image.fromarray(image_np) 63 | 64 | def pil_to_comfy(image: Union[Image.Image, List[Image.Image], None]) -> Optional[torch.Tensor]: 65 | """ 66 | Convert a PIL Image or list of PIL Images to a ComfyUI image tensor. 67 | 68 | Args: 69 | image: PIL Image, list of PIL Images, or None 70 | 71 | Returns: 72 | ComfyUI image tensor (1, H, W, 3) in range [0, 1] or None if input is None 73 | """ 74 | if image is None: 75 | return None 76 | 77 | # Handle list of PIL images - take the first one 78 | if isinstance(image, list): 79 | if len(image) == 0: 80 | return None 81 | image = image[0] # Take the first image from the list 82 | 83 | # Convert to numpy array and scale to [0, 1] 84 | image_np = np.array(image).astype(np.float32) / 255.0 85 | 86 | # Ensure the image has the right shape (H, W, 3) 87 | if len(image_np.shape) == 2: # Grayscale image 88 | image_np = np.stack([image_np, image_np, image_np], axis=-1) 89 | elif image_np.shape[-1] == 4: # RGBA image 90 | image_np = image_np[..., :3] # Remove alpha channel 91 | 92 | # Convert to torch tensor and add batch dimension 93 | return torch.from_numpy(image_np)[None,] 94 | 95 | def resize_and_center_crop(image: Union[torch.Tensor, Image.Image], target_height: int = 512,target_width: int = 512) -> Union[torch.Tensor, Image.Image]: 96 | """ 97 | Center crop and resize an image. 98 | 99 | Args: 100 | image: Image to process (ComfyUI tensor or PIL Image) 101 | target_height: Target height 102 | target_width: Target width 103 | 104 | Returns: 105 | Processed image in the same format as input 106 | """ 107 | # Handle ComfyUI tensor 108 | if isinstance(image, torch.Tensor): 109 | pil_image = comfy_to_pil(image) 110 | result = resize_and_center_crop(pil_image, target_height, target_width) 111 | return pil_to_comfy(result) 112 | 113 | # Handle PIL Image 114 | w, h = image.size 115 | min_size = min(w, h) 116 | 117 | # Calculate target aspect ratio 118 | target_ratio = target_width / target_height 119 | # Calculate current aspect ratio 120 | current_ratio = w / h 121 | 122 | # Resize to match target width or height while preserving aspect ratio 123 | if current_ratio > target_ratio: 124 | # Image is wider than target - resize by height 125 | new_height = target_height 126 | new_width = int(w * (target_height / h)) 127 | else: 128 | # Image is taller than target - resize by width 129 | new_width = target_width 130 | new_height = int(h * (target_width / w)) 131 | 132 | image = image.resize((new_width, new_height), Image.BILINEAR) 133 | 134 | # Center crop the image to the target size 135 | cropped = image.crop(((new_width - target_width) // 2, 136 | (new_height - target_height) // 2, 137 | (new_width + target_width) // 2, 138 | (new_height + target_height) // 2)) 139 | 140 | return cropped 141 | 142 | def center_crop(image: Union[torch.Tensor, Image.Image], target_height: int = 512, target_width: int = 512, 143 | interpolation: str = "LANCZOS") -> Union[torch.Tensor, Image.Image]: 144 | """ 145 | Center crop an image to target size. If image is smaller than target size, 146 | resize first before cropping. 147 | 148 | Args: 149 | image: Image to process (ComfyUI tensor or PIL Image) 150 | target_height: Target height 151 | target_width: Target width 152 | interpolation: Interpolation method (NEAREST, BILINEAR, BICUBIC, LANCZOS) 153 | 154 | Returns: 155 | Processed image in the same format as input 156 | """ 157 | # Handle ComfyUI tensor 158 | if isinstance(image, torch.Tensor): 159 | pil_image = comfy_to_pil(image) 160 | result = center_crop(pil_image, target_height, target_width, interpolation) 161 | return pil_to_comfy(result) 162 | 163 | # Handle PIL Image 164 | w, h = image.size 165 | 166 | # Get interpolation method 167 | interp_method = { 168 | "NEAREST": Image.NEAREST, 169 | "BILINEAR": Image.BILINEAR, 170 | "BICUBIC": Image.BICUBIC, 171 | "LANCZOS": Image.LANCZOS 172 | }.get(interpolation, Image.LANCZOS) 173 | 174 | # If image is smaller than target in either dimension, resize first 175 | if w < target_width or h < target_height: 176 | # Calculate scale factor needed 177 | scale = max(target_width / w, target_height / h) 178 | new_w = int(w * scale) 179 | new_h = int(h * scale) 180 | image = image.resize((new_w, new_h), interp_method) 181 | w, h = new_w, new_h 182 | 183 | # Calculate crop coordinates 184 | left = (w - target_width) // 2 185 | top = (h - target_height) // 2 186 | right = left + target_width 187 | bottom = top + target_height 188 | 189 | # Perform center crop 190 | cropped = image.crop((left, top, right, bottom)) 191 | return cropped 192 | 193 | def pad_resize(image: Union[torch.Tensor, Image.Image], target_height: int = 512, target_width: int = 512, 194 | pad_color: tuple = (0, 0, 0), interpolation: str = "LANCZOS") -> Union[torch.Tensor, Image.Image]: 195 | """ 196 | Resize image preserving aspect ratio and pad to target size. 197 | 198 | Args: 199 | image: Image to process (ComfyUI tensor or PIL Image) 200 | target_height: Target height 201 | target_width: Target width 202 | pad_color: RGB color tuple for padding (default: black) 203 | interpolation: Interpolation method (NEAREST, BILINEAR, BICUBIC, LANCZOS) 204 | 205 | Returns: 206 | Processed image in the same format as input 207 | """ 208 | # Handle ComfyUI tensor 209 | if isinstance(image, torch.Tensor): 210 | pil_image = comfy_to_pil(image) 211 | result = pad_resize(pil_image, target_height, target_width, pad_color, interpolation) 212 | return pil_to_comfy(result) 213 | 214 | # Handle PIL Image 215 | w, h = image.size 216 | 217 | # Get interpolation method 218 | interp_method = { 219 | "NEAREST": Image.NEAREST, 220 | "BILINEAR": Image.BILINEAR, 221 | "BICUBIC": Image.BICUBIC, 222 | "LANCZOS": Image.LANCZOS 223 | }.get(interpolation, Image.LANCZOS) 224 | 225 | # Calculate target aspect ratio 226 | target_ratio = target_width / target_height 227 | # Calculate current aspect ratio 228 | current_ratio = w / h 229 | 230 | # Create a new image with the target size and fill with the pad color 231 | new_image = Image.new("RGB", (target_width, target_height), pad_color) 232 | 233 | # Resize the original image preserving aspect ratio 234 | if current_ratio > target_ratio: 235 | # Image is wider than target - resize by width 236 | new_w = target_width 237 | new_h = int(h * (target_width / w)) 238 | resized = image.resize((new_w, new_h), interp_method) 239 | # Paste in the center (horizontally) 240 | new_image.paste(resized, (0, (target_height - new_h) // 2)) 241 | else: 242 | # Image is taller than target - resize by height 243 | new_h = target_height 244 | new_w = int(w * (target_height / h)) 245 | resized = image.resize((new_w, new_h), interp_method) 246 | # Paste in the center (vertically) 247 | new_image.paste(resized, ((target_width - new_w) // 2, 0)) 248 | 249 | return new_image 250 | 251 | def fit_resize(image: Union[torch.Tensor, Image.Image], target_height: int = 512, target_width: int = 512, 252 | interpolation: str = "LANCZOS") -> Union[torch.Tensor, Image.Image]: 253 | """ 254 | Resize image to target size without preserving aspect ratio. 255 | 256 | Args: 257 | image: Image to process (ComfyUI tensor or PIL Image) 258 | target_height: Target height 259 | target_width: Target width 260 | interpolation: Interpolation method (NEAREST, BILINEAR, BICUBIC, LANCZOS) 261 | 262 | Returns: 263 | Processed image in the same format as input 264 | """ 265 | # Handle ComfyUI tensor 266 | if isinstance(image, torch.Tensor): 267 | pil_image = comfy_to_pil(image) 268 | result = fit_resize(pil_image, target_height, target_width, interpolation) 269 | return pil_to_comfy(result) 270 | 271 | # Handle PIL Image 272 | # Get interpolation method 273 | interp_method = { 274 | "NEAREST": Image.NEAREST, 275 | "BILINEAR": Image.BILINEAR, 276 | "BICUBIC": Image.BICUBIC, 277 | "LANCZOS": Image.LANCZOS 278 | }.get(interpolation, Image.LANCZOS) 279 | 280 | # Resize directly to target size (no aspect ratio preservation) 281 | resized = image.resize((target_width, target_height), interp_method) 282 | return resized -------------------------------------------------------------------------------- /web/js/showEnhancedPrompt.js: -------------------------------------------------------------------------------- 1 | import { app } from "../../../scripts/app.js"; 2 | import { ComfyWidgets } from "../../../scripts/widgets.js"; 3 | 4 | // Displays enhanced prompt on DSDGeminiPromptEnhancer node 5 | app.registerExtension({ 6 | name: "comfyui.dsd.showEnhancedPrompt", 7 | async beforeRegisterNodeDef(nodeType, nodeData, app) { 8 | if (nodeData.name === "DSDGeminiPromptEnhancer") { 9 | function normalizePrompt(prompt) { 10 | if (!prompt) return ""; 11 | if (Array.isArray(prompt)) { 12 | return prompt.join(""); 13 | } 14 | return prompt; 15 | } 16 | 17 | function populateEnhancedPrompt(enhancedPrompt) { 18 | enhancedPrompt = normalizePrompt(enhancedPrompt); 19 | if (!enhancedPrompt) { 20 | return; 21 | } 22 | 23 | try { 24 | if (this.widgets) { 25 | for (let i = 0; i < this.widgets.length; i++) { 26 | if (this.widgets[i].name === "enhanced_prompt_display") { 27 | this.widgets[i].onRemove?.(); 28 | this.widgets.splice(i, 1); 29 | i--; 30 | } 31 | } 32 | } 33 | 34 | const textWidgetResult = ComfyWidgets["STRING"](this, "enhanced_prompt_text", ["STRING", { multiline: true }], app); 35 | if (!textWidgetResult || !textWidgetResult.widget || !textWidgetResult.widget.inputEl) { 36 | return; 37 | } 38 | const w = textWidgetResult.widget; 39 | w.inputEl.readOnly = true; 40 | w.inputEl.style.opacity = 0.8; 41 | w.inputEl.style.backgroundColor = "#1e2124"; 42 | w.inputEl.style.color = "#9eec51"; 43 | w.name = "enhanced_prompt_display"; 44 | w.value = enhancedPrompt; 45 | 46 | requestAnimationFrame(() => { 47 | const sz = this.computeSize(); 48 | if (sz[0] < this.size[0]) sz[0] = this.size[0]; 49 | if (sz[1] < this.size[1]) sz[1] = this.size[1]; 50 | this.onResize?.(sz); 51 | app.graph.setDirtyCanvas(true, false); 52 | }); 53 | } catch (error) { 54 | // Silent error handling 55 | } 56 | } 57 | 58 | const onExecuted = nodeType.prototype.onExecuted; 59 | nodeType.prototype.onExecuted = function (message) { 60 | try { 61 | onExecuted?.apply(this, arguments); 62 | if (message.enhanced_prompt) { 63 | populateEnhancedPrompt.call(this, message.enhanced_prompt); 64 | } else if (message.ui && message.ui.enhanced_prompt) { 65 | populateEnhancedPrompt.call(this, message.ui.enhanced_prompt); 66 | } else if (message.text) { 67 | populateEnhancedPrompt.call(this, message.text); 68 | } 69 | } catch (error) { 70 | // Silent error handling 71 | } 72 | }; 73 | } 74 | }, 75 | }); 76 | 77 | window.DSD_ENHANCED_PROMPT_LOADED = true; --------------------------------------------------------------------------------