├── .github
└── workflows
│ └── publish.yml
├── .gitignore
├── LICENSE
├── README.md
├── __init__.py
├── assets
├── deepfaceAnalyzeFaceAttributes.png
├── detectorForNSFW.png
└── maskFromFacemodel.png
├── py
├── color_correct.py
├── node_crop_by_mask.py
├── node_face_attributes.py
├── node_gemini_enhance_prompt.py
├── node_image.py
├── node_image_composite.py
├── node_mask.py
├── node_nsfw.py
├── node_others.py
├── node_volcano.py
├── nodes.py
├── nodes_torch_compile.py
├── nodes_video.py
└── utils.py
├── pyproject.toml
├── r_deepface
└── demography.py
├── r_nudenet
├── 320n.onnx
└── nudenet.py
├── requirements.txt
└── web
└── js
└── previewText.js
/.github/workflows/publish.yml:
--------------------------------------------------------------------------------
1 | name: Publish to Comfy registry
2 | on:
3 | workflow_dispatch:
4 | push:
5 | branches:
6 | - master
7 | paths:
8 | - "pyproject.toml"
9 |
10 | permissions:
11 | issues: write
12 |
13 | jobs:
14 | publish-node:
15 | name: Publish Custom Node to registry
16 | runs-on: ubuntu-latest
17 | if: ${{ github.repository_owner == 'zhangp365' }}
18 | steps:
19 | - name: Check out code
20 | uses: actions/checkout@v4
21 | - name: Publish Custom Node
22 | uses: Comfy-Org/publish-node-action@v1
23 | with:
24 | ## Add your own personal access token to your Github Repository secrets and reference it here.
25 | personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
26 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | __pycache__/
2 |
--------------------------------------------------------------------------------
/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 | # Some Utils for ComfyUI
2 |
3 | ## LoadImageWithSwitch
4 | Modified the official LoadImage node by adding a switch. When turned off, it will not load the image.
5 |
6 | ## LoadImageMaskWithSwitch
7 | Modified the official LoadImageMask node by adding a switch. When turned off, it will not load the image to mask.
8 |
9 | ## LoadImageWithoutListDir
10 | When there are a lot of images in the input directory, loading image with `os.listdir` can be slow. This node avoids using `os.listdir` to improve performance.
11 |
12 | ## LoadImageMaskWithoutListDir
13 | When there are a lot of images in the input directory, loading image as Mask with `os.listdir` can be slow. This node avoids using `os.listdir` to improve performance.
14 |
15 | ## ImageCompositeMaskedWithSwitch
16 | Modified the official ImageCompositeMasked node by adding a switch. When turned off, it will return the destination image directly.
17 |
18 | ## ImageCompositeMaskedOneByOne
19 | Modified the official ImageCompositeMasked node to process images one by one, instead of processing an entire batch at once. In video scenarios, processing in a batch may requires a significant amount of memory, but this method helps reduce memory usage.
20 |
21 | ## ImageBatchOneOrMore
22 | This node can input one or more images, the limit is six. It expands the functionality of the official ImageBatch node from two to multiple images.
23 |
24 | ## ImageConcatenateOfUtils
25 |
26 | This node, ImageConcatenateOfUtils, is an extension of the original [ImageConcatenate](https://github.com/kijai/ComfyUI-KJNodes) node developed by @kijai.
27 |
28 | ### Features
29 | - **Upscale**: This extension adds the capability to upscale images.
30 | - **Check**: Additional functionality for cheching the second image empty or not.
31 |
32 | ### Original node
33 | The original ImageConcatenate node can be found [here](https://github.com/kijai/ComfyUI-KJNodes).
34 | Special thanks to @kijai for their contribution to the initial version.
35 |
36 | ## ColorCorrectOfUtils
37 | This node, ColorCorrectOfUtils, is an extension of the original [ColorCorrect](https://github.com/EllangoK/ComfyUI-post-processing-nodes/blob/master/post_processing/color_correct.py) node developed by @EllangoK. Added the chanels of red, green, and blue adjustment functionalities.
38 |
39 | ## ImagesConcanateToGrid
40 | This node is designed to concatenate the input one batch images to a grid. It can concatenate images in the horizontal or vertical direction.
41 |
42 | ## VolcanoOutpainting
43 | This node is designed to outpaint the input image using the Volcano engine.
44 |
45 | use this node, must get your free API key from Volcano engine:
46 | - Visit [Volcano engine](https://console.volcengine.com/)
47 | - Log in with your Volcano engine account
48 | - Click on "访问控制" or go to [settings](https://console.volcengine.com/iam/keymanage)
49 | - Create a new API key
50 | - Copy the API key for use in the node's input
51 |
52 | ## ModifyTextGender
53 | This node adjusts the text to describe the gender based on the input. If the gender input is 'M', the text will be adjusted to describe as male; if the gender input is 'F', it will be adjusted to describe as female.
54 |
55 | ## GeminiPromptEnhance
56 | This node is designed to enhance the text description of the image, using the latest Gemini 2.0 flash model. It can add quality descriptors, lighting descriptions, scene descriptions, and skin descriptions to the text. and according to the gender input, can modifiy the content about gender.
57 |
58 | use this node, must get your free API key from Google AI Studio:
59 | - Visit [Google AI Studio](https://aistudio.google.com/prompts/new_chat)
60 | - Log in with your Google account
61 | - Click on "Get API key" or go to settings
62 | - Create a new API key
63 | - Copy the API key for use in the node's input or gemini_config.json
64 |
65 | this code is original from https://github.com/ShmuelRonen/ComfyUI-Gemini_Flash_2.0_Exp, added new features. thanks to @ShmuelRonen.
66 |
67 | ## GenderControlOutput
68 | This node determines the output based on the input gender. If the gender input is 'M', it will output male-specific text, float, and integer values. If the gender input is 'F', it will output female-specific text, float, and integer values.
69 |
70 | ## BooleanControlOutput
71 | This node outputs different values based on a boolean input. If the boolean input is True, it will output the values of true_text, true_float, true_int, True, and False. If the boolean input is False, it will output the values of false_text, false_float, false_int, False, and True.
72 |
73 | ## SplitMask
74 | This node splits one mask into two masks of the same size according to the area of the submasks. If there are more than two areas, it will select the two largest submasks.
75 |
76 | ## MaskFastGrow
77 | This node is designed for growing masks quickly. When using the official or other mask growth nodes, the speed slows down significantly with large grow values, such as above 20. In contrast, this node maintains consistent speed regardless of the grow value.
78 |
79 | ## MaskFromFaceModel
80 | Generates a mask from the face model of the Reactor face swap node. The mask covers the facial area below the eyes, excluding the forehead. Enabling add_bbox_upper_points provides a rough approximation but lacks precision. If the forehead is essential for your application, consider using a different mask or adjusting the generated mask as needed.
81 |
82 |
83 |
84 | ## MaskAutoSelector
85 | Check the three input masks. If any are available, return the first. If none are available, raise an exception.
86 |
87 | ## MaskCoverFourCorners
88 | Generates a mask by covering the selected corners with circular edges. This mask can be used as an attention mask to remove watermarks from the corners.
89 |
90 | ## MaskofCenter
91 | Generates a mask by covering the center of the image with a circular edge. This mask can be used as an attention mask, then model can focus on the center of the image.
92 |
93 | ## MaskAreaComparison
94 | This node compares the area of the mask with the threshold. If the area is greater than the threshold, it will return True; otherwise, it will return False.
95 |
96 |
97 | ## CheckpointLoaderSimpleWithSwitch
98 | Enhanced the official LoadCheckpoint node by integrating three switches. Each switch controls whether a specific component is loaded. When a switch is turned off, the corresponding component will not be loaded. if you use the extra vae and close the model's vae loading, that will save memory.
99 |
100 | ## ImageResizeTo8x
101 | Modified the [image-resize-comfyui](https://github.com/palant/image-resize-comfyui) image resize node by adding logic to crop the resulting image size to 8 times size, similar to the VAE encode node. This avoids pixel differences when pasting back by the ImageCompositeMasked node.
102 |
103 | ## ImageAutoSelector
104 | This node is designed to automatically select the image from the input. If the prior image is not empty, return the prior image; otherwise, return the alternative image or the third image.
105 |
106 | ## TextPreview
107 | Added the node for convenience. The code is originally from ComfyUI-Custom-Scripts, thanks.
108 |
109 | ## TextInputAutoSelector
110 | Check the component and alternative input. If the component input is not empty, return this text; otherwise, return the alternative text.
111 |
112 | ## MatchImageRatioToPreset
113 | According to the input image ratio, decide which standard SDXL training size is the closest match. This is useful for subsequent image resizing and other processes.
114 |
115 | ## UpscaleImageWithModelIfNeed
116 | Enhanced the official UpscaleImageWithModel node by adding a judge. If the input image area exceeds a predefined threshold, upscaling is bypassed. The threshold is a percentage of the SDXL standard size (1024x1024) area.
117 |
118 | ## ImageCompositeWatermark
119 | This node is designed to composite a watermark into the destination image. It can select the position of the watermark, resize the watermark according to the input ratio, and add a margin to the watermark.
120 |
121 | ## ImageTransition
122 | This node is designed to generate a transition image between two images. The first image gradually fades out while the second image simultaneously appears, creating a smooth transition effect.
123 |
124 | ## ImageTransitionLeftToRight
125 | This node is designed to generate a transition image between two images. The first image gradually slides to the right while the second image simultaneously appears from the left, creating a smooth transition effect.
126 |
127 | ## ImageMaskColorAverage
128 | This node is designed to calculate the average color of the image within the mask. It returns the decimal and hexadecimal values of the average color.
129 |
130 | ## TorchCompileModelAdvanced
131 | This node enables model compilation using torch.compile. It extends ComfyUI's original torch compile node by adding compile mode options and a toggle switch.
132 |
133 | ## DetectorForNSFW
134 | This node adapts the original model and inference code from [nudenet](https://github.com/notAI-tech/NudeNet.git) for use with Comfy. A small 10MB default model, [320n.onnx](https://github.com/notAI-tech/NudeNet?tab=readme-ov-file#available-models), is provided. If you wish to use other models from that repository, download the [ONNX model](https://huggingface.co/zhangsongbo365/nudenet_onnx/tree/main) and place it in the models/nsfw directory, then set the appropriate detect_size.
135 |
136 | From initial testing, the filtering effect is better than classifier models such as [Falconsai/nsfw_image_detection](https://huggingface.co/Falconsai/nsfw_image_detection).
137 |
138 |
139 | You can also adjust the confidence levels for various rules such as buttocks_exposed to be more lenient or strict. Lower confidence levels will filter out more potential NSFW images. Setting the value to 1 will stop filtering for that specific feature.
140 |
141 | ### output
142 | The output_image includes the original image and the alternative image or the blank image. detect_result is the result of the detection with json format. filtered_image only includes the image after filtering, if it is just one image and nsfw, it raises an exception in the save_image node.
143 |
144 | ## DeepfaceAnalyzeFaceAttributes
145 | This node integrates the [deepface](https://github.com/serengil/deepface) library to analyze face attributes (gender, race, emotion, age). It analyzes only the largest face in the image and supports processing one image at a time.
146 |
147 |
148 | If the input image is a standard square face image, you can enable the standard_single_face_image switch. In this case, the node will skip face detection and analyze the attributes directly.
149 |
150 | Upon the first run, the node will download the [deepface](https://github.com/serengil/deepface) models, which may take some time.
151 |
152 | > **Note:** If you encounter the following exception while running the node:
153 |
154 | > ```
155 | > ValueError: The layer sequential has never been called and thus has no defined input.
156 | > ```
157 |
158 | > Please set the environment variable `TF_USE_LEGACY_KERAS` to `1`, then restart ComfyUI.
159 |
160 | ## EmptyConditioning
161 | This node is designed to return an empty conditioning, the size is zero. It can be used to replace the conditioning when the conditioning is not actually needed.
162 |
163 | ## CropByMaskToSpecificSize
164 | This node is designed to crop the image by the mask to a specific size.
165 |
--------------------------------------------------------------------------------
/__init__.py:
--------------------------------------------------------------------------------
1 | import server
2 | from aiohttp import web
3 | import logging
4 | logger = logging.getLogger(__file__)
5 | import os
6 | import importlib.util
7 | import shutil,filecmp
8 | import __main__
9 |
10 | from .py.nodes import GenderWordsConfig
11 |
12 |
13 | @server.PromptServer.instance.routes.get("/utils_node/reload_gender_words_config")
14 | async def reload_gender_words_config(request):
15 | try:
16 | GenderWordsConfig.load_config()
17 | return web.json_response({"result": "reload successful."})
18 | except Exception as e:
19 | logger.exception(e)
20 | return web.json_response({"error": str(e)})
21 |
22 |
23 | NODE_CLASS_MAPPINGS = {}
24 | NODE_DISPLAY_NAME_MAPPINGS = {}
25 |
26 | def get_ext_dir(subpath=None, mkdir=False):
27 | dir = os.path.dirname(__file__)
28 | if subpath is not None:
29 | dir = os.path.join(dir, subpath)
30 |
31 | dir = os.path.abspath(dir)
32 |
33 | if mkdir and not os.path.exists(dir):
34 | os.makedirs(dir)
35 | return dir
36 |
37 | py = get_ext_dir("py")
38 | files = os.listdir(py)
39 | for file in files:
40 | if not file.endswith(".py"):
41 | continue
42 | name = os.path.splitext(file)[0]
43 | if not name.startswith("node"):
44 | continue
45 | try:
46 | imported_module = importlib.import_module(".py.{}".format(name), __name__)
47 | NODE_CLASS_MAPPINGS = {**NODE_CLASS_MAPPINGS, **imported_module.NODE_CLASS_MAPPINGS}
48 | NODE_DISPLAY_NAME_MAPPINGS = {**NODE_DISPLAY_NAME_MAPPINGS, **imported_module.NODE_DISPLAY_NAME_MAPPINGS}
49 | except Exception as e:
50 | logger.exception(e)
51 |
52 | WEB_DIRECTORY = "./web"
53 | __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
54 |
--------------------------------------------------------------------------------
/assets/deepfaceAnalyzeFaceAttributes.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zhangp365/ComfyUI-utils-nodes/62a5ce76735e1a380e140932dc974e0220a65c43/assets/deepfaceAnalyzeFaceAttributes.png
--------------------------------------------------------------------------------
/assets/detectorForNSFW.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zhangp365/ComfyUI-utils-nodes/62a5ce76735e1a380e140932dc974e0220a65c43/assets/detectorForNSFW.png
--------------------------------------------------------------------------------
/assets/maskFromFacemodel.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zhangp365/ComfyUI-utils-nodes/62a5ce76735e1a380e140932dc974e0220a65c43/assets/maskFromFacemodel.png
--------------------------------------------------------------------------------
/py/color_correct.py:
--------------------------------------------------------------------------------
1 | # Adapt from https://github.com/EllangoK/ComfyUI-post-processing-nodes/blob/master/post_processing/color_correct.py
2 |
3 | import cv2
4 | import numpy as np
5 | import torch
6 | from PIL import Image, ImageEnhance
7 |
8 |
9 | class ColorCorrectOfUtils:
10 | @classmethod
11 | def INPUT_TYPES(s):
12 | return {
13 | "required": {
14 | "image": ("IMAGE",),
15 | "temperature": (
16 | "FLOAT",
17 | {"default": 0, "min": -100, "max": 100, "step": 5},
18 | ),
19 | "red": (
20 | "FLOAT",
21 | {"default": 0, "min": -100, "max": 100, "step": 5},
22 | ),
23 | "green": (
24 | "FLOAT",
25 | {"default": 0, "min": -100, "max": 100, "step": 5},
26 | ),
27 | "blue": (
28 | "FLOAT",
29 | {"default": 0, "min": -100, "max": 100, "step": 5},
30 | ),
31 | "hue": ("FLOAT", {"default": 0, "min": -90, "max": 90, "step": 5}),
32 | "brightness": (
33 | "FLOAT",
34 | {"default": 0, "min": -100, "max": 100, "step": 5},
35 | ),
36 | "contrast": (
37 | "FLOAT",
38 | {"default": 0, "min": -100, "max": 100, "step": 5},
39 | ),
40 | "saturation": (
41 | "FLOAT",
42 | {"default": 0, "min": -100, "max": 100, "step": 5},
43 | ),
44 | "gamma": ("FLOAT", {"default": 1, "min": 0.2, "max": 2.2, "step": 0.1}),
45 | "grain": ("FLOAT", {"default": 0, "min": 0.0, "max": 1, "step": 0.01}),
46 | },
47 | }
48 |
49 | RETURN_TYPES = ("IMAGE",)
50 | FUNCTION = "color_correct"
51 |
52 | CATEGORY = "Art Venture/Post Processing"
53 |
54 | def color_correct(
55 | self,
56 | image: torch.Tensor,
57 | temperature: float,
58 | red:float,
59 | green:float,
60 | blue:float,
61 | hue: float,
62 | brightness: float,
63 | contrast: float,
64 | saturation: float,
65 | gamma: float,
66 | grain: float,
67 | ):
68 | batch_size, height, width, _ = image.shape
69 | result = torch.zeros_like(image)
70 |
71 | brightness /= 100
72 | contrast /= 100
73 | saturation /= 100
74 | temperature /= 100
75 | red /= 100
76 | green /= 100
77 | blue /= 100
78 |
79 | brightness = 1 + brightness
80 | contrast = 1 + contrast
81 | saturation = 1 + saturation
82 |
83 | for b in range(batch_size):
84 | tensor_image = image[b].numpy()
85 |
86 | modified_image = Image.fromarray((tensor_image * 255).astype(np.uint8))
87 |
88 | # brightness
89 | modified_image = ImageEnhance.Brightness(modified_image).enhance(brightness)
90 |
91 | # contrast
92 | modified_image = ImageEnhance.Contrast(modified_image).enhance(contrast)
93 | modified_image = np.array(modified_image).astype(np.float32)
94 |
95 | # temperature
96 | if temperature > 0:
97 | modified_image[:, :, 0] *= 1 + temperature
98 | modified_image[:, :, 1] *= 1 + temperature * 0.4
99 | elif temperature < 0:
100 | modified_image[:, :, 2] *= 1 - temperature
101 |
102 | # red
103 | modified_image[:, :, 0] *= 1 + red
104 | # green
105 | modified_image[:, :, 1] *= 1 + green
106 | # blue
107 | modified_image[:, :, 2] *= 1 + blue
108 | modified_image = np.clip(modified_image, 0, 255) / 255
109 |
110 | # gamma
111 | modified_image = np.clip(np.power(modified_image, gamma), 0, 1)
112 |
113 | # saturation
114 | hls_img = cv2.cvtColor(modified_image, cv2.COLOR_RGB2HLS)
115 | hls_img[:, :, 2] = np.clip(saturation * hls_img[:, :, 2], 0, 1)
116 | modified_image = cv2.cvtColor(hls_img, cv2.COLOR_HLS2RGB) * 255
117 |
118 | # hue
119 | hsv_img = cv2.cvtColor(modified_image, cv2.COLOR_RGB2HSV)
120 | hsv_img[:, :, 0] = (hsv_img[:, :, 0] + hue) % 360
121 | modified_image = cv2.cvtColor(hsv_img, cv2.COLOR_HSV2RGB)
122 |
123 | # grain
124 | if grain > 0:
125 | grain_image = np.random.normal(0, 15, (modified_image.shape[0], modified_image.shape[1], 3)).astype(np.uint8)
126 | size = modified_image.shape[:2]
127 | modified_image = cv2.blendLinear(modified_image.astype(np.uint8), grain_image, np.ones(size,dtype=np.float32)*(1-grain),np.ones(size, dtype=np.float32)*grain)
128 |
129 | modified_image = modified_image.astype(np.uint8)
130 | modified_image = modified_image / 255
131 | modified_image = torch.from_numpy(modified_image).unsqueeze(0)
132 | result[b] = modified_image
133 |
134 | return (result,)
135 |
--------------------------------------------------------------------------------
/py/node_crop_by_mask.py:
--------------------------------------------------------------------------------
1 | from .utils import *
2 | # this node is original from ComfyUI-LayerStyle, modified the logic of crop to specific size and others
3 | import torch
4 | import logging
5 | from PIL import Image
6 |
7 | logger = logging.getLogger(__name__)
8 |
9 |
10 |
11 | class CropByMaskToSpecificSize:
12 |
13 | def __init__(self):
14 | pass
15 |
16 | @classmethod
17 | def INPUT_TYPES(self):
18 | return {
19 | "required": {
20 | "image": ("IMAGE", ), #
21 | "mask": ("MASK",),
22 | "invert_mask": ("BOOLEAN", {"default": False}), # 反转mask#
23 | "top_reserve": ("FLOAT", {"default": 0.1, "min": 0, "max": 1, "step": 0.01}),
24 | "bottom_reserve": ("FLOAT", {"default": 0.1, "min": 0, "max": 1, "step": 0.01}),
25 | "left_reserve": ("FLOAT", {"default": 0.1, "min": 0, "max": 1, "step": 0.01}),
26 | "right_reserve": ("FLOAT", {"default": 0.1, "min": 0, "max": 1, "step": 0.01}),
27 | "width": ("INT", {"default": 1024, "min": 200, "max": 4096, "step": 2}),
28 | "height": ("INT", {"default": 1024, "min": 200, "max": 4096, "step": 2}),
29 | "width_padding_position":(["left","center","right"],{"default":"center",}),
30 | "height_padding_position":(["top","center","bottom"],{"default":"center"}),
31 | },
32 | "optional": {
33 | "crop_box": ("BOX",),
34 | }
35 | }
36 |
37 | RETURN_TYPES = ("IMAGE", "MASK", "BOX", "IMAGE",)
38 | RETURN_NAMES = ("croped_image", "croped_mask", "crop_box", "box_preview")
39 | FUNCTION = 'crop_by_mask'
40 | CATEGORY = 'utils/mask'
41 |
42 | def crop_by_mask(self, image, mask, invert_mask,
43 | top_reserve, bottom_reserve,
44 | left_reserve, right_reserve,
45 | width, height,
46 | width_padding_position, height_padding_position,
47 | crop_box=None
48 | ):
49 |
50 | ret_images = []
51 | ret_masks = []
52 | l_images = []
53 | l_masks = []
54 |
55 | for l in image:
56 | l_images.append(torch.unsqueeze(l, 0))
57 | if mask.dim() == 2:
58 | mask = torch.unsqueeze(mask, 0)
59 | # 如果有多张mask输入,使用第一张
60 | if mask.shape[0] > 1:
61 | logger.warn(f"Warning: Multiple mask inputs, using the first.")
62 | mask = torch.unsqueeze(mask[0], 0)
63 | if invert_mask:
64 | mask = 1 - mask
65 | l_masks.append(tensor2pil(torch.unsqueeze(mask, 0)).convert('L'))
66 |
67 | _mask = mask2image(mask)
68 | preview_image = tensor2pil(mask).convert('RGBA')
69 | if crop_box is None:
70 | x = 0
71 | y = 0
72 | (x, y, w, h) = mask_area(_mask)
73 | left_reserve = left_reserve * w
74 | top_reserve = top_reserve * h
75 | right_reserve = right_reserve * w
76 | bottom_reserve = bottom_reserve * h
77 |
78 | canvas_width, canvas_height = tensor2pil(torch.unsqueeze(image[0], 0)).convert('RGBA').size
79 | x1 = x - left_reserve if x - left_reserve > 0 else 0
80 | y1 = y - top_reserve if y - top_reserve > 0 else 0
81 | x2 = x + w + right_reserve if x + w + right_reserve < canvas_width else canvas_width
82 | y2 = y + h + bottom_reserve if y + h + bottom_reserve < canvas_height else canvas_height
83 |
84 | # 计算当前裁剪框的宽高
85 | current_width = x2 - x1
86 | current_height = y2 - y1
87 |
88 | # 计算目标宽高比和当前宽高比
89 | target_ratio = width / height
90 | current_ratio = current_width / current_height
91 |
92 | # 根据比例调整裁剪框
93 | if current_ratio < target_ratio:
94 | # 需要增加宽度
95 | needed_width = current_height * target_ratio
96 | width_increase = needed_width - current_width
97 | x1 = max(0, x1 - width_increase / 2)
98 | x2 = min(canvas_width, x2 + width_increase / 2)
99 | else:
100 | # 需要增加高度
101 | needed_height = current_width / target_ratio
102 | height_increase = needed_height - current_height
103 | y1 = max(0, y1 - height_increase / 2)
104 | y2 = min(canvas_height, y2 + height_increase / 2)
105 |
106 | logger.info(f"Box detected. x={x1},y={y1},width={width},height={height}")
107 | crop_box = (int(x1), int(y1), int(x2), int(y2))
108 | preview_image = draw_rect(preview_image, x, y, w, h, line_color="#F00000",
109 | line_width=(w + h) // 100)
110 | preview_image = draw_rect(preview_image, crop_box[0], crop_box[1],
111 | crop_box[2] - crop_box[0], crop_box[3] - crop_box[1],
112 | line_color="#00F000",
113 | line_width=(crop_box[2] - crop_box[0] + crop_box[3] - crop_box[1]) // 200)
114 | for i in range(len(l_images)):
115 | _canvas = tensor2pil(l_images[i]).convert('RGBA')
116 | _mask = l_masks[0]
117 |
118 | # 裁剪图像和遮罩
119 | cropped_image = _canvas.crop(crop_box)
120 | cropped_mask = _mask.crop(crop_box)
121 |
122 | # 计算缩放比例
123 | crop_width = crop_box[2] - crop_box[0]
124 | crop_height = crop_box[3] - crop_box[1]
125 | scale_w = width / crop_width
126 | scale_h = height / crop_height
127 | scale = min(scale_w, scale_h)
128 |
129 | # 按比例缩放
130 | new_w = int(crop_width * scale)
131 | new_h = int(crop_height * scale)
132 | resized_image = cropped_image.resize((new_w, new_h), Image.LANCZOS)
133 | resized_mask = cropped_mask.resize((new_w, new_h), Image.LANCZOS)
134 |
135 | # 创建目标尺寸的灰色背景
136 | final_image = Image.new('RGBA', (width, height), (128, 128, 128, 255))
137 | final_mask = Image.new('L', (width, height), 0)
138 |
139 | # 计算粘贴位置(居中)
140 | if width_padding_position == "center":
141 | paste_x = (width - new_w) // 2
142 | elif width_padding_position == "left":
143 | paste_x = width - new_w
144 | elif width_padding_position == "right":
145 | paste_x = 0
146 |
147 |
148 | if height_padding_position == "center":
149 | paste_y = (height - new_h) // 2
150 | elif height_padding_position == "top":
151 | paste_y = height - new_h
152 | elif height_padding_position == "bottom":
153 | paste_y = 0
154 |
155 |
156 | # 粘贴调整后的图像和遮罩
157 | final_image.paste(resized_image, (paste_x, paste_y))
158 | final_mask.paste(resized_mask, (paste_x, paste_y))
159 |
160 | ret_images.append(pil2tensor(final_image))
161 | ret_masks.append(image2mask(final_mask))
162 |
163 | logger.info(f"Processed {len(ret_images)} image(s).")
164 | return (torch.cat(ret_images, dim=0), torch.cat(ret_masks, dim=0), list(crop_box), pil2tensor(preview_image),)
165 |
166 |
167 | NODE_CLASS_MAPPINGS = {
168 | "CropByMaskToSpecificSize": CropByMaskToSpecificSize
169 | }
170 |
171 | NODE_DISPLAY_NAME_MAPPINGS = {
172 | "LayerUtility: CropByMask To Specific Size": "LayerUtility: CropByMask To Specific Size"
173 | }
--------------------------------------------------------------------------------
/py/node_face_attributes.py:
--------------------------------------------------------------------------------
1 | import os
2 | os.environ["TF_USE_LEGACY_KERAS"] = "1"
3 |
4 | import numpy as np
5 | from typing import Union, List, Dict, Any
6 | from .utils import tensor2np,np2tensor
7 | from ..r_deepface import demography
8 |
9 | import folder_paths
10 | import json
11 | import logging
12 | logger = logging.getLogger(__file__)
13 |
14 |
15 | def prepare_deepface_home():
16 | deepface_path = os.path.join(folder_paths.models_dir, "deepface")
17 |
18 | # Deepface requires a specific structure within the DEEPFACE_HOME directory
19 | deepface_dot_path = os.path.join(deepface_path, ".deepface")
20 | deepface_weights_path = os.path.join(deepface_dot_path, "weights")
21 | if not os.path.exists(deepface_weights_path):
22 | os.makedirs(deepface_weights_path)
23 |
24 | os.environ["DEEPFACE_HOME"] = deepface_path
25 |
26 |
27 | def get_largest_face(faces):
28 | largest_face = {}
29 | largest_area = 0
30 | if len(faces) == 1:
31 | return faces[0]
32 |
33 | for face in faces:
34 | if 'region' in face:
35 | w = face['region']['w']
36 | h = face['region']['h']
37 | area = w * h
38 | if area > largest_area:
39 | largest_area = area
40 | largest_face = face
41 | return largest_face
42 |
43 |
44 | class DeepfaceAnalyzeFaceAttributes:
45 | '''
46 | - 'gender' (str): The gender in the detected face. "M" or "F"
47 |
48 | - 'emotion' (str): The emotion in the detected face.
49 | Possible values include "sad," "angry," "surprise," "fear," "happy,"
50 | "disgust," and "neutral."
51 |
52 | - 'race' (str): The race in the detected face.
53 | Possible values include "indian," "asian," "latino hispanic,"
54 | "black," "middle eastern," and "white."
55 | '''
56 |
57 | def __init__(self) -> None:
58 | prepare_deepface_home()
59 |
60 | @classmethod
61 | def INPUT_TYPES(cls):
62 | return {
63 | "required": {
64 | "image": ("IMAGE",),
65 | "detector_backend": ([
66 | "opencv",
67 | "ssd",
68 | "dlib",
69 | "mtcnn",
70 | "retinaface",
71 | "mediapipe",
72 | "yolov8",
73 | "yunet",
74 | "fastmtcnn",
75 | ], {
76 | "default": "yolov8",
77 | }),
78 | },
79 | "optional": {
80 | "analyze_gender": ("BOOLEAN", {"default": True}),
81 | "analyze_race": ("BOOLEAN", {"default": True}),
82 | "analyze_emotion": ("BOOLEAN", {"default": True}),
83 | "analyze_age": ("BOOLEAN", {"default": True}),
84 | "standard_single_face_image": ("BOOLEAN", {"default": False}),
85 | },
86 | }
87 |
88 | RETURN_TYPES = ("STRING","STRING","STRING","STRING", "STRING")
89 | RETURN_NAMES = ("gender","race","emotion","age", "json_info")
90 | FUNCTION = "analyze_face"
91 | CATEGORY = "utils/face"
92 |
93 | def analyze_face(self, image, detector_backend, analyze_gender=True, analyze_race=True, analyze_emotion=True, analyze_age=True, standard_single_face_image=False):
94 | # 将图像转换为numpy数组
95 | img_np = tensor2np(image)
96 | if isinstance(img_np, List):
97 | if len(img_np) > 1:
98 | logger.warn(f"DeepfaceAnalyzeFaceAttributes only support for one image and only analyze the largest face.")
99 | img_np = img_np[0]
100 |
101 | # 准备actions列表
102 | actions = []
103 | if analyze_gender:
104 | actions.append("gender")
105 | if analyze_race:
106 | actions.append("race")
107 | if analyze_emotion:
108 | actions.append("emotion")
109 | if analyze_age:
110 | actions.append("age")
111 |
112 | # 调用analyze函数
113 | results = demography.analyze(img_np, actions=actions, detector_backend=detector_backend, enforce_detection=False, is_single_face_image=standard_single_face_image)
114 |
115 | # 获取面积最大的脸
116 | largest_face = get_largest_face(results)
117 |
118 | if not standard_single_face_image and largest_face.get("face_confidence")==0:
119 | largest_face ={}
120 |
121 | gender_map = {"Woman":"F","Man":"M",'':''}
122 | # 提取结果
123 | gender = gender_map.get(largest_face.get('dominant_gender', ''),'')if analyze_gender else ''
124 | race = largest_face.get('dominant_race', '') if analyze_race else ''
125 | emotion = largest_face.get('dominant_emotion', '') if analyze_emotion else ''
126 | age = str(largest_face.get('age', '0')) if analyze_age else '0'
127 |
128 | json_info= json.dumps(largest_face)
129 | return (gender, race, emotion, age, json_info)
130 |
131 | NODE_CLASS_MAPPINGS = {
132 | #image
133 | "DeepfaceAnalyzeFaceAttributes": DeepfaceAnalyzeFaceAttributes,
134 |
135 | }
136 |
137 | NODE_DISPLAY_NAME_MAPPINGS = {
138 | # Image
139 | "DeepfaceAnalyzeFaceAttributes": "Deepface Analyze Face Attributes",
140 |
141 | }
--------------------------------------------------------------------------------
/py/node_gemini_enhance_prompt.py:
--------------------------------------------------------------------------------
1 | # this code is original from https://github.com/ShmuelRonen/ComfyUI-Gemini_Flash_2.0_Exp, added cache and gender support
2 | import os
3 | import sys
4 | sys.path.append(".")
5 | import google.generativeai as genai
6 | from contextlib import contextmanager
7 | from collections import OrderedDict
8 | import folder_paths
9 | import logging
10 | import yaml
11 | from google.api_core import retry
12 | from google.generativeai.types import RequestOptions
13 | logger = logging.getLogger(__name__)
14 |
15 | config_dir = os.path.join(folder_paths.base_path, "config")
16 | if not os.path.exists(config_dir):
17 | os.makedirs(config_dir)
18 |
19 |
20 | def get_config():
21 | try:
22 | config_path = os.path.join(config_dir, 'gemini_config.yml')
23 | with open(config_path, 'r') as f:
24 | config = yaml.load(f, Loader=yaml.FullLoader)
25 | return config
26 | except:
27 | return {}
28 |
29 | def save_config(config):
30 | config_path = os.path.join(config_dir, 'gemini_config.yml')
31 | with open(config_path, 'w') as f:
32 | yaml.dump(config, f, indent=4)
33 |
34 | @contextmanager
35 | def temporary_env_var(key: str, new_value):
36 | old_value = os.environ.get(key)
37 | if new_value is not None:
38 | os.environ[key] = new_value
39 | elif key in os.environ:
40 | del os.environ[key]
41 | try:
42 | yield
43 | finally:
44 | if old_value is not None:
45 | os.environ[key] = old_value
46 | elif key in os.environ:
47 | del os.environ[key]
48 |
49 | class LRUCache(OrderedDict):
50 | def __init__(self, capacity):
51 | super().__init__()
52 | self.capacity = capacity
53 |
54 | def get(self, key):
55 | if key not in self:
56 | return None
57 | self.move_to_end(key)
58 | return self[key]
59 |
60 | def put(self, key, value):
61 | if key in self:
62 | self.move_to_end(key)
63 | self[key] = value
64 | if len(self) > self.capacity:
65 | self.popitem(last=False)
66 |
67 | class GeminiPromptEnhance:
68 | default_prompt = "### Instruction: 1.Edit and enhance the text description of the image. \nAdd quality descriptors, like 'A high-quality photo, an 8K photo.' \n2.Add lighting descriptions based on the scene, like 'The lighting is natural and bright, casting soft shadows.' \n3.Add scene descriptions according to the context, like 'The overall mood is serene and peaceful.' \n4.If a person is in the scene, include a description of the skin, such as 'natural skin tones and ensure the skin appears realistic with clear, fine details.' \n\n5.Only output the result of the text, no others.\n### Text:"
69 |
70 | def __init__(self, api_key=None, proxy=None):
71 | config = get_config()
72 | self.api_key = api_key or config.get("GEMINI_API_KEY")
73 | self.proxy = proxy or config.get("PROXY")
74 | self.cache_size = 500 # 缓存最大条数
75 | self.cache_file = os.path.join(config_dir, 'prompt_cache_gemini.yml')
76 | self.cache = LRUCache(self.cache_size)
77 | self.last_prompt = ""
78 | if self.api_key is not None:
79 | self.configure_genai()
80 |
81 | def load_cache(self):
82 | try:
83 | if os.path.exists(self.cache_file):
84 | with open(self.cache_file, 'r', encoding='utf-8') as f:
85 | cache_data = yaml.load(f, Loader=yaml.FullLoader)
86 | # 重新创建LRU缓存
87 | for k, v in cache_data.items():
88 | self.cache.put(k, v)
89 | except Exception as e:
90 | logger.error(f"加载缓存出错: {str(e)}")
91 | self.cache = LRUCache(self.cache_size)
92 |
93 | def save_cache(self):
94 | try:
95 | with open(self.cache_file, 'w', encoding='utf-8') as f:
96 | yaml.dump(dict(self.cache), f, indent=4)
97 | except Exception as e:
98 | logger.error(f"保存缓存出错: {str(e)}")
99 |
100 | def configure_genai(self):
101 | genai.configure(api_key=self.api_key, transport='rest')
102 |
103 | @classmethod
104 | def INPUT_TYPES(cls):
105 | return {
106 | "required": {
107 | "prompt": ("STRING", {"default": cls.default_prompt, "multiline": True}),
108 | },
109 | "optional": {
110 | "text_input": ("STRING", {"default": "", "multiline": True}),
111 | "api_key": ("STRING", {"default": ""}),
112 | "proxy": ("STRING", {"default": ""}),
113 | "max_output_tokens": ("INT", {"default": 8192, "min": 1, "max": 8192}),
114 | "temperature": ("FLOAT", {"default": 0.4, "min": 0.0, "max": 1.0, "step": 0.1}),
115 | "gender_prior": (["","M", "F"], {"default": ""}),
116 | "gender_alternative": ("STRING", {"forceInput": True}),
117 | "enabled": ("BOOLEAN", {"default": True}),
118 | "request_exception_handle": (["bypass","raise_exception","output_exception"], {"default":"bypass"}),
119 | "model": (["gemini-2.0-flash-exp", "gemini-2.0-flash"], {"default": "gemini-2.0-flash"})
120 | }
121 | }
122 |
123 | RETURN_TYPES = ("STRING",)
124 | RETURN_NAMES = ("generated_content",)
125 | FUNCTION = "generate_content"
126 | CATEGORY = "utils/text"
127 |
128 | def prepare_content(self, prompt, text_input, gender=""):
129 | gender_word = "male" if gender == "M" else "female" if gender == "F" else gender
130 | if "### Instruction" not in prompt:
131 | prompt = f"### Instruction:" + "\n".join([f"{i+1}.{line}" for i, line in enumerate(prompt.split("\n")) if line.strip()])
132 | if gender_word:
133 | gender_instruction = f"### Instruction:\n0. Edit and enhance the text below,must replacing the main object's traits with those provided in ({gender_word}), and ensure they are well-integrated into the narrative. "
134 | prompt = prompt.replace("### Instruction:", gender_instruction)
135 | if "### Text:" not in prompt:
136 | prompt = prompt + "\n### Text:"
137 | text_content = prompt if not text_input else f"{prompt} \n{text_input}"
138 | logger.debug(f"text_content: {text_content}")
139 | return [{"text": text_content}]
140 |
141 | def generate_content(self, prompt, text_input=None, api_key="", proxy="",
142 | max_output_tokens=8192, temperature=0.4, gender_prior="",gender_alternative="", enabled=True, request_exception_handle="bypass", model="gemini-2.0-flash"):
143 | if not enabled:
144 | return (text_input,)
145 | if prompt is None or prompt.strip() == "":
146 | prompt = self.default_prompt
147 |
148 | if prompt != self.last_prompt:
149 | self.last_prompt = prompt
150 | self.cache.clear()
151 | logger.info(f"clear cache for new prompt: {prompt}")
152 |
153 | gender = gender_prior if gender_prior else gender_alternative
154 | # 生成缓存键
155 | cache_key = f"{text_input or ''}_{gender}"
156 |
157 | # 检查缓存
158 | cached_result = self.cache.get(cache_key)
159 | if cached_result is not None:
160 | return (cached_result,)
161 |
162 | # Set all safety settings to block_none by default
163 | safety_settings = [
164 | {"category": "harassment", "threshold": "NONE"},
165 | {"category": "hate_speech", "threshold": "NONE"},
166 | {"category": "sexually_explicit", "threshold": "NONE"},
167 | {"category": "dangerous_content", "threshold": "NONE"},
168 | {"category": "civic", "threshold": "NONE"}
169 | ]
170 |
171 | # Only update API key if explicitly provided in the node
172 | if api_key.strip():
173 | self.api_key = api_key
174 | save_config({"GEMINI_API_KEY": self.api_key, "PROXY": self.proxy})
175 | self.configure_genai()
176 |
177 | # Only update proxy if explicitly provided in the node
178 | if proxy.strip():
179 | self.proxy = proxy
180 | save_config({"GEMINI_API_KEY": self.api_key, "PROXY": self.proxy})
181 |
182 | if not self.api_key:
183 | raise ValueError("API key not found in gemini_config.yml or node input")
184 |
185 | model_name = f'models/{model}'
186 | model = genai.GenerativeModel(model_name)
187 |
188 | # Apply fixed safety settings to the model
189 | model.safety_settings = safety_settings
190 |
191 | generation_config = genai.types.GenerationConfig(
192 | max_output_tokens=max_output_tokens,
193 | temperature=temperature
194 | )
195 | logger.debug(f"self.proxy: {self.proxy}")
196 | if self.proxy:
197 | with temporary_env_var('HTTP_PROXY', self.proxy), temporary_env_var('HTTPS_PROXY', self.proxy):
198 | generated_content = self.do_request(model, generation_config, prompt, text_input, gender,cache_key, request_exception_handle)
199 | else:
200 | generated_content = self.do_request(model, generation_config, prompt, text_input, gender,cache_key, request_exception_handle)
201 | logger.debug(f"gender_alternative: {gender_alternative}, text_input: {text_input}, gender: {gender}, \ngenerated_content: {generated_content}")
202 | return (generated_content,)
203 |
204 | def do_request(self, model, generation_config, prompt, text_input, gender, cache_key, request_exception_handle="bypass"):
205 | try:
206 | content_parts = self.prepare_content(prompt, text_input, gender)
207 | response = model.generate_content(content_parts, generation_config=generation_config, request_options= RequestOptions(
208 | timeout=8))
209 | generated_content = response.text
210 |
211 | if generated_content.startswith("I'm sorry"):
212 | raise Exception(f"Gemini returned an rejection: {generated_content}")
213 | # 更新缓存
214 | self.cache.put(cache_key, generated_content)
215 | self.save_cache()
216 |
217 | except Exception as e:
218 | logger.exception(e)
219 | if request_exception_handle == "raise_exception":
220 | raise e
221 | elif request_exception_handle == "output_exception":
222 | generated_content = f"Error: {str(e)}"
223 | else:
224 | generated_content = text_input
225 | return generated_content
226 |
227 | NODE_CLASS_MAPPINGS = {
228 | "GeminiPromptEnhance": GeminiPromptEnhance,
229 | }
230 |
231 | NODE_DISPLAY_NAME_MAPPINGS = {
232 | "GeminiPromptEnhance": "Gemini prompt enhance",
233 | }
234 |
235 | # add a test code here
236 | if __name__ == "__main__":
237 | logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
238 | logger.info("start test")
239 | enhance = GeminiPromptEnhance()
240 | result = enhance.generate_content(enhance.default_prompt, "a photo of a beautiful girl ",gender_alternative= "M")
241 | logger.info(result)
242 |
243 |
--------------------------------------------------------------------------------
/py/node_image.py:
--------------------------------------------------------------------------------
1 | from comfy_extras.nodes_mask import ImageCompositeMasked
2 | import torch
3 | import torch.nn.functional as F
4 | class ImageCompositeWatermark(ImageCompositeMasked):
5 | @classmethod
6 | def INPUT_TYPES(s):
7 | return {
8 | "required": {
9 | "destination": ("IMAGE",),
10 | "watermark": ("IMAGE",),
11 | "position": (["bottom_right", "bottom_center", "bottom_left"], {"default": "bottom_right"}),
12 | "resize_ratio": ("FLOAT", {"default": 1, "min": 0, "max": 10, "step": 0.05}),
13 | "margin": ("INT", {"default": 0, "min": 0, "max": 1000, "step": 1}),
14 | },
15 | "optional": {
16 | "mask": ("MASK",),
17 | "enabled": ("BOOLEAN", {"default": True, "label_on": "enabled", "label_off": "disabled"}),
18 | "invert_mask": ("BOOLEAN", {"default": False, "label_on": "enabled", "label_off": "disabled"}),
19 | }
20 | }
21 | RETURN_TYPES = ("IMAGE",)
22 | FUNCTION = "composite_watermark"
23 | CATEGORY = "utils/image"
24 |
25 | def composite_watermark(self, destination, watermark, position, resize_ratio, margin, mask=None, enabled=True, invert_mask=False):
26 | if not enabled:
27 | return (destination,)
28 |
29 | dest_h, dest_w = destination.shape[1:3]
30 | water_h, water_w = watermark.shape[1:3]
31 |
32 | scale = 1
33 | if water_h > dest_h or water_w > dest_w:
34 | # 计算需要的缩放比例
35 | scale_h = dest_h / water_h
36 | scale_w = dest_w / water_w
37 | scale = min(scale_h, scale_w)
38 |
39 |
40 | if resize_ratio != 1 or scale != 1:
41 | watermark = torch.nn.functional.interpolate(
42 | watermark.movedim(-1, 1), scale_factor=resize_ratio * scale, mode="bicubic", antialias=True).movedim(1, -1).clamp(0.0, 1.0)
43 | if mask is not None:
44 | mask = torch.nn.functional.interpolate(mask.unsqueeze(
45 | 0), scale_factor=resize_ratio * scale, mode="bicubic", antialias=True).squeeze(0).clamp(0.0, 1.0)
46 |
47 | water_h, water_w = watermark.shape[1:3]
48 | # 计算y坐标 - 总是在底部
49 | y = dest_h - water_h - margin
50 |
51 | x = 0
52 | # 根据position计算x坐标
53 | if position == "bottom_left":
54 | x = margin
55 | elif position == "bottom_center":
56 | x = (dest_w - water_w) // 2
57 | elif position == "bottom_right":
58 | x = dest_w - water_w - margin
59 |
60 | if invert_mask and mask is not None:
61 | mask = 1.0 - mask
62 |
63 |
64 | return self.composite(destination, watermark, x, y, False, mask)
65 |
66 | class ImageTransition:
67 | @classmethod
68 | def INPUT_TYPES(s):
69 | return {
70 | "required": {
71 | "first_image": ("IMAGE",),
72 | "last_image": ("IMAGE",),
73 | "frames": ("INT", {"default": 24, "min": 2, "max": 120, "step": 1}),
74 | "transition_type": (["uniform", "smooth"], {"default": "uniform"}),
75 | "smooth_effect": ("FLOAT", {"default": 1.0, "min": 0.1, "max": 10.0, "step": 0.1}),
76 | }
77 | }
78 |
79 | RETURN_TYPES = ("IMAGE",)
80 | FUNCTION = "generate_transition"
81 | CATEGORY = "utils/image"
82 |
83 | def generate_transition(self, first_image, last_image, frames, transition_type="uniform", smooth_effect=1.0):
84 | # 生成插值权重
85 | if transition_type == "uniform":
86 | weights = torch.linspace(0, 1, frames)
87 | else: # sigmoid
88 | x = torch.linspace(-20, 20, frames)
89 | weights = torch.sigmoid(x / smooth_effect)
90 |
91 | # 创建输出张量列表
92 | output_frames = []
93 |
94 | # 生成过渡帧
95 | for w in weights:
96 | # 使用权重进行插值
97 | transition_frame = first_image * (1 - w) + last_image * w
98 | output_frames.append(transition_frame)
99 |
100 | # 将所有帧拼接在一起
101 | result = torch.cat(output_frames, dim=0)
102 |
103 | return (result,)
104 |
105 | class ImageMaskColorAverage:
106 | @classmethod
107 | def INPUT_TYPES(s):
108 | return {
109 | "required": {
110 | "image": ("IMAGE",),
111 | "mask": ("MASK",),
112 | }
113 | }
114 |
115 | RETURN_TYPES = ("INT", "STRING")
116 | RETURN_NAMES = ("COLOR_DEC", "COLOR_HEX")
117 | FUNCTION = "calculate_average_color"
118 | CATEGORY = "utils/image"
119 |
120 | def calculate_average_color(self, image, mask):
121 | # 确保mask是二维的
122 | if len(mask.shape) > 2:
123 | mask = mask.squeeze()
124 |
125 | # 将mask扩展为与图像相同的通道数
126 | expanded_mask = mask.unsqueeze(-1).expand(-1, -1, 3)
127 |
128 | # 计算mask区域的像素总数
129 | pixel_count = torch.sum(mask)
130 |
131 | if pixel_count == 0:
132 | # 如果mask中没有选中区域,返回黑色
133 | return (0, "#000000")
134 |
135 | # 计算mask区域的颜色总和
136 | masked_image = image * expanded_mask.unsqueeze(0)
137 | color_sum = torch.sum(masked_image, dim=[0, 1, 2])
138 |
139 | # 计算平均颜色
140 | avg_color = color_sum / pixel_count
141 |
142 | # 转换为0-255范围的整数
143 | r = int(avg_color[0].item() * 255)
144 | g = int(avg_color[1].item() * 255)
145 | b = int(avg_color[2].item() * 255)
146 |
147 | # 生成十六进制颜色代码
148 | hex_color = f"#{r:02x}{g:02x}{b:02x}"
149 |
150 | # 计算十进制颜色值 (R*65536 + G*256 + B)
151 | dec_color = r * 65536 + g * 256 + b
152 |
153 | return (dec_color, hex_color)
154 |
155 |
156 | class ImagesConcanateToGrid:
157 | @classmethod
158 | def INPUT_TYPES(s):
159 | return {"required": {
160 | "image1": ("IMAGE",),
161 | "direction": (
162 | ['right',
163 | 'down',
164 | ],
165 | {
166 | "default": 'right'
167 | }),
168 | "dimension_number": ("INT", {"default": 2, "min": 1, "max": 20, "step": 1}),
169 | }
170 | }
171 |
172 | RETURN_TYPES = ("IMAGE",)
173 | FUNCTION = "concanate"
174 | CATEGORY = "utils/image"
175 |
176 | def concanate(self, image1, direction='right', dimension_number=2):
177 | # 检查图像维度,如果不是4维直接返回
178 | if len(image1.shape) != 4:
179 | return (image1,)
180 |
181 | batch_size = image1.shape[0]
182 |
183 | # 如果批次大小为1,直接返回
184 | if batch_size == 1:
185 | return (image1,)
186 |
187 | # 将批次图像分离为单独的图像列表
188 | images = [image1[i:i+1] for i in range(batch_size)]
189 |
190 | # 根据方向计算行数和列数
191 | if direction == 'right':
192 | cols = dimension_number
193 | rows = (batch_size + cols - 1) // cols # 向上取整
194 | else: # direction == 'down'
195 | rows = dimension_number
196 | cols = (batch_size + rows - 1) // rows # 向上取整
197 |
198 | # 创建网格来存放图像
199 | grid_rows = []
200 |
201 | for row in range(rows):
202 | row_images = []
203 | for col in range(cols):
204 | idx = row * cols + col if direction == 'right' else col * rows + row
205 | if idx < len(images):
206 | row_images.append(images[idx])
207 | else:
208 | # 如果没有足够的图像,用黑色图像填充
209 | black_image = torch.zeros_like(images[0])
210 | row_images.append(black_image)
211 |
212 | # 水平拼接当前行的图像
213 | if row_images:
214 | row_concat = torch.cat(row_images, dim=2) # 在宽度维度拼接
215 | grid_rows.append(row_concat)
216 |
217 | # 垂直拼接所有行
218 | if grid_rows:
219 | result = torch.cat(grid_rows, dim=1) # 在高度维度拼接
220 | else:
221 | result = image1
222 |
223 | return (result,)
224 |
225 | class NeedImageSizeAndCount:
226 | @classmethod
227 | def INPUT_TYPES(s):
228 | return {"required": {"image": ("IMAGE",)}}
229 |
230 | RETURN_TYPES = ("INT", "INT", "INT")
231 | RETURN_NAMES = ("width", "height", "count")
232 | FUNCTION = "get_image_size_and_count"
233 | CATEGORY = "utils/image"
234 |
235 | def get_image_size_and_count(self, image):
236 | return (image.shape[2], image.shape[1], image.shape[0])
237 |
238 | NODE_CLASS_MAPPINGS = {
239 | #image
240 | "ImageCompositeWatermark": ImageCompositeWatermark,
241 | "ImageTransition": ImageTransition,
242 | "ImageMaskColorAverage": ImageMaskColorAverage,
243 | "ImagesConcanateToGrid": ImagesConcanateToGrid,
244 | "NeedImageSizeAndCount": NeedImageSizeAndCount,
245 | }
246 |
247 | NODE_DISPLAY_NAME_MAPPINGS = {
248 | # Image
249 | "ImageCompositeWatermark": "Image Composite Watermark",
250 | "ImageTransition": "Image Transition",
251 | "ImageMaskColorAverage": "Image Mask Color Average",
252 | "ImagesConcanateToGrid": "Images Concanate To Grid",
253 | "NeedImageSizeAndCount": "get Image Size And Count by utils",
254 | }
255 |
--------------------------------------------------------------------------------
/py/node_image_composite.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import logging
3 | logger = logging.getLogger(__file__)
4 | MAX_RESOLUTION=16384
5 |
6 | def composite(destination, source, x, y, mask=None, resize_source=False, resize_mode='bilinear'):
7 | device = destination.device
8 | batch_size, _, dest_height, dest_width = destination.shape
9 | if not resize_source:
10 | _, _, source_height, source_width = source.shape
11 | else:
12 | source_height, source_width = dest_height, dest_width
13 |
14 | if x > dest_width or y > dest_height:
15 | return destination
16 |
17 | left = x
18 | top = y
19 |
20 | visible_width = min(dest_width - left, source_width)
21 | visible_height = min(dest_height - top, source_height)
22 |
23 | if resize_source:
24 | resize_height, resize_width = dest_height, dest_width
25 | else:
26 | resize_height, resize_width = source_height, source_width
27 |
28 | for i in range(batch_size):
29 | source_slice = source[i:i+1].to(device)
30 |
31 | if resize_source:
32 | source_slice = torch.nn.functional.interpolate(source_slice, size=(resize_height, resize_width), mode=resize_mode)
33 |
34 | if mask is None:
35 | mask_slice = torch.ones_like(source_slice)
36 | else:
37 | mask_slice = mask[i:i+1].to(device)
38 | mask_slice = torch.nn.functional.interpolate(mask_slice.reshape((-1, 1, mask_slice.shape[-2], mask_slice.shape[-1])),
39 | size=(resize_height, resize_width), mode=resize_mode)
40 |
41 | mask_slice = mask_slice[:, :, :visible_height, :visible_width]
42 |
43 | dest_portion = destination[i:i+1, :, top:top+visible_height, left:left+visible_width]
44 | source_portion = source_slice[:, :, :visible_height, :visible_width]
45 |
46 | dest_portion.mul_(1 - mask_slice)
47 | dest_portion.add_(source_portion * mask_slice)
48 |
49 | # Free up memory
50 | del source_slice, mask_slice, dest_portion, source_portion
51 | torch.cuda.empty_cache()
52 |
53 | return destination
54 |
55 |
56 | class ImageCompositeMaskedOneByOne:
57 | @classmethod
58 | def INPUT_TYPES(s):
59 | return {
60 | "required": {
61 | "destination": ("IMAGE",),
62 | "source": ("IMAGE",),
63 | "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
64 | "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
65 | "resize_source": ("BOOLEAN", {"default": False}),
66 | "resize_source_mode":(["nearest", "bilinear", "bicubic", "area", "nearest-exact"],)
67 | },
68 | "optional": {
69 | "mask": ("MASK",),
70 | }
71 | }
72 | RETURN_TYPES = ("IMAGE",)
73 | FUNCTION = "composite"
74 |
75 | CATEGORY = "utils/image"
76 |
77 | def composite(self, destination, source, x, y, resize_source, resize_source_mode= "bilinear", mask = None):
78 | destination = destination.clone().movedim(-1, 1)
79 | output = composite(destination, source.movedim(-1, 1), x, y, mask, resize_source, resize_source_mode).movedim(1, -1)
80 | return (output,)
81 |
82 |
83 | NODE_CLASS_MAPPINGS = {
84 | #image
85 | "ImageCompositeMaskedOneByOne": ImageCompositeMaskedOneByOne,
86 |
87 | }
88 |
89 | NODE_DISPLAY_NAME_MAPPINGS = {
90 | # Image
91 | "ImageCompositeMaskedOneByOne": "image composite masked one bye one",
92 |
93 | }
94 |
--------------------------------------------------------------------------------
/py/node_mask.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import numpy as np
3 |
4 | class MaskAreaComparison:
5 | @classmethod
6 | def INPUT_TYPES(cls):
7 | return {
8 | "required": {
9 | "mask": ("MASK",),
10 | "area_threshold": ("INT", {
11 | "default": 40000,
12 | "min": 0,
13 | "step": 50,
14 | "max": 1000000000,
15 | "display": "number"
16 | }),
17 | }
18 | }
19 |
20 | RETURN_TYPES = ("BOOLEAN", "BOOLEAN")
21 | RETURN_NAMES = ("is_greater", "is_smaller")
22 | FUNCTION = "compare_mask_area"
23 | CATEGORY = "mask/utils"
24 |
25 | def compare_mask_area(self, mask, area_threshold):
26 | # 确保mask是tensor格式
27 | if isinstance(mask, np.ndarray):
28 | mask = torch.from_numpy(mask)
29 |
30 | # 计算mask的实际面积(非零像素数量)
31 | mask_area = torch.sum(mask > 0.5).item()
32 |
33 | # 比较面积
34 | is_greater = mask_area > area_threshold
35 | is_smaller = mask_area < area_threshold
36 |
37 | return (is_greater, is_smaller)
38 |
39 | # 节点映射
40 | NODE_CLASS_MAPPINGS = {
41 | "MaskAreaComparison": MaskAreaComparison
42 | }
43 |
44 | NODE_DISPLAY_NAME_MAPPINGS = {
45 | "MaskAreaComparison": "Mask Area Comparison"
46 | }
47 |
--------------------------------------------------------------------------------
/py/node_nsfw.py:
--------------------------------------------------------------------------------
1 | import cv2
2 | import numpy as np
3 | from ..r_nudenet.nudenet import NudeDetector
4 | import os
5 | import torch
6 | import folder_paths as comfy_paths
7 | from folder_paths import models_dir
8 | from typing import Union, List
9 | import json
10 | import logging
11 | from .utils import tensor2np,np2tensor
12 |
13 | logger = logging.getLogger(__file__)
14 |
15 | comfy_paths.folder_names_and_paths["nsfw"] = ([os.path.join(models_dir, "nsfw")], {".pt",".onnx"})
16 |
17 |
18 | class DetectorForNSFW:
19 |
20 | def __init__(self) -> None:
21 | self.model = None
22 |
23 | @classmethod
24 | def INPUT_TYPES(cls):
25 | return {
26 | "required": {
27 | "image": ("IMAGE",),
28 | "detect_size":([640, 320], {"default": 320}),
29 | "provider": (["CPU", "CUDA", "ROCM"], ),
30 | },
31 | "optional": {
32 | "model_name": (comfy_paths.get_filename_list("nsfw") + [""], {"default": ""}),
33 | "alternative_image": ("IMAGE",),
34 | "buttocks_exposed": ("FLOAT", {"default": 0.7, "min": 0.0, "max": 1.0, "step": 0.05}),
35 | "female_breast_exposed": ("FLOAT", {"default": 0.7, "min": 0.0, "max": 1.0, "step": 0.05}),
36 | "female_genitalia_exposed": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.05}),
37 | "anus_exposed": ("FLOAT", {"default": 0.7, "min": 0.0, "max": 1.0, "step": 0.05}),
38 | "male_genitalia_exposed": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.05}),
39 | },
40 | }
41 |
42 | RETURN_TYPES = ("IMAGE", "STRING", "IMAGE")
43 | RETURN_NAMES = ("output_image", "detect_result", "filtered_image")
44 | FUNCTION = "filter_exposure"
45 |
46 | CATEGORY = "utils/filter"
47 |
48 | all_labels = [
49 | "FEMALE_GENITALIA_COVERED",
50 | "FACE_FEMALE",
51 | "BUTTOCKS_EXPOSED",
52 | "FEMALE_BREAST_EXPOSED",
53 | "FEMALE_GENITALIA_EXPOSED",
54 | "MALE_BREAST_EXPOSED",
55 | "ANUS_EXPOSED",
56 | "FEET_EXPOSED",
57 | "BELLY_COVERED",
58 | "FEET_COVERED",
59 | "ARMPITS_COVERED",
60 | "ARMPITS_EXPOSED",
61 | "FACE_MALE",
62 | "BELLY_EXPOSED",
63 | "MALE_GENITALIA_EXPOSED",
64 | "ANUS_COVERED",
65 | "FEMALE_BREAST_COVERED",
66 | "BUTTOCKS_COVERED",
67 | ]
68 |
69 | def filter_exposure(self, image, model_name=None, detect_size=320, provider="CPU", alternative_image=None, **kwargs):
70 | if self.model is None:
71 | self.init_model(model_name, detect_size, provider)
72 |
73 | if alternative_image is not None:
74 | alternative_image = tensor2np(alternative_image)
75 |
76 | images = tensor2np(image)
77 | if not isinstance(images, List):
78 | images = [images]
79 |
80 | results, result_info, filtered_results = [],[],[]
81 | for img in images:
82 | detect_result = self.model.detect(img)
83 |
84 | logger.debug(f"nudenet detect result:{detect_result}")
85 | detected_results = []
86 | for item in detect_result:
87 | label = item['class']
88 | score = item['score']
89 | confidence_level = kwargs.get(label.lower())
90 | if label.lower() in kwargs and score > confidence_level:
91 | detected_results.append(item)
92 | info = {"detect_result":detect_result}
93 | if len(detected_results) == 0:
94 | results.append(img)
95 | info["nsfw"] = False
96 | filtered_results.append(img)
97 | else:
98 | placeholder_image = alternative_image if alternative_image is not None else np.ones_like(img) * 255
99 | results.append(placeholder_image)
100 | info["nsfw"] = True
101 |
102 | result_info.append(info)
103 |
104 | result_tensor = np2tensor(results)
105 | filtered_tensor = np2tensor(filtered_results)
106 | result_info = json.dumps(result_info)
107 | return (result_tensor, result_info, filtered_tensor)
108 |
109 | def init_model(self, model_name, detect_size, provider):
110 | model_path = comfy_paths.get_full_path("nsfw", model_name) if model_name else None
111 | self.model = NudeDetector(model_path=model_path, providers=[provider + 'ExecutionProvider',], inference_resolution=detect_size)
112 |
113 |
114 | NODE_CLASS_MAPPINGS = {
115 | #image
116 | "DetectorForNSFW": DetectorForNSFW,
117 |
118 | }
119 |
120 | NODE_DISPLAY_NAME_MAPPINGS = {
121 | # Image
122 | "DetectorForNSFW": "detector for the NSFW",
123 |
124 | }
125 |
--------------------------------------------------------------------------------
/py/node_others.py:
--------------------------------------------------------------------------------
1 | import torch
2 |
3 |
4 | class EmptyConditioning:
5 | @classmethod
6 | def INPUT_TYPES(s):
7 | return {"required": {}}
8 |
9 | RETURN_TYPES = ("CONDITIONING",)
10 | FUNCTION = "get_empty_conditioning"
11 | CATEGORY = "utils/conditioning"
12 |
13 | def get_empty_conditioning(self):
14 | return ([(None,{"pooled_output":None}),], )
15 |
16 | NODE_CLASS_MAPPINGS = {
17 | "EmptyConditioning": EmptyConditioning,
18 | }
19 |
20 | NODE_DISPLAY_NAME_MAPPINGS = {
21 | "EmptyConditioning": "Empty Conditioning",
22 | }
23 |
--------------------------------------------------------------------------------
/py/node_volcano.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import numpy as np
3 | import base64
4 | import io
5 | from PIL import Image
6 | import tempfile
7 | import os
8 | from volcengine.visual.VisualService import VisualService
9 | import folder_paths
10 | import logging
11 | import yaml
12 | from .utils import tensor2pil, pil2tensor
13 |
14 | config_dir = os.path.join(folder_paths.base_path, "config")
15 | if not os.path.exists(config_dir):
16 | os.makedirs(config_dir)
17 |
18 | logger = logging.getLogger(__name__)
19 |
20 | class VolcanoOutpaintingNode:
21 | @classmethod
22 | def INPUT_TYPES(s):
23 | return {
24 | "required": {
25 | "image": ("IMAGE",),
26 | "mask": ("MASK",),
27 | "ak": ("STRING", {"default": ""}),
28 | "sk": ("STRING", {"default": ""}),
29 | "seed": ("INT", {"default": 42, "min": 0, "max": 999999})
30 | }
31 | }
32 |
33 | RETURN_TYPES = ("IMAGE",)
34 | RETURN_NAMES = ("result_image",)
35 | FUNCTION = "process_outpainting"
36 | CATEGORY = "image/volcano"
37 |
38 | def save_config(self, config):
39 | config_path = os.path.join(config_dir, 'volcano_config.yml')
40 | with open(config_path, 'w', encoding='utf-8') as f:
41 | yaml.dump(config, f, indent=4)
42 |
43 | def load_config(self):
44 | config_path = os.path.join(config_dir, 'volcano_config.yml')
45 | with open(config_path, 'r', encoding='utf-8') as f:
46 | config = yaml.load(f, Loader=yaml.FullLoader)
47 | return config
48 |
49 | def pil_to_base64(self, pil_image):
50 | """将PIL图像转换为base64字符串"""
51 | buffer = io.BytesIO()
52 | pil_image.save(buffer, format='PNG')
53 | img_data = buffer.getvalue()
54 | return base64.b64encode(img_data).decode('utf-8')
55 |
56 | def request_valcanic_outpainting(self, req_key, ak, sk, image_base64s, seed=42, top=0, left=0, bottom=0, right=0):
57 | """调用火山引擎图像扩展API"""
58 | visual_service = VisualService()
59 |
60 | if ak and sk:
61 | self.save_config({"ak": ak, "sk": sk})
62 | else:
63 | config = self.load_config()
64 | ak = config.get("ak")
65 | sk = config.get("sk")
66 | if not ak or not sk:
67 | raise Exception("volcano engine ak or sk not found")
68 |
69 | visual_service.set_ak(ak)
70 | visual_service.set_sk(sk)
71 |
72 | # 请求参数
73 | form = {
74 | "req_key": req_key,
75 | "binary_data_base64": image_base64s,
76 | "top": top,
77 | "left": left,
78 | "bottom": bottom,
79 | "right": right,
80 | "seed": seed
81 | }
82 |
83 | resp = visual_service.cv_process(form)
84 |
85 | # 解码返回的图像
86 | img_base64 = resp['data']['binary_data_base64'][0]
87 | img_data = base64.b64decode(img_base64)
88 | # 转换为PIL图像
89 | result_image = Image.open(io.BytesIO(img_data))
90 |
91 | # 删除图片base64, 方便print
92 | resp['data']['binary_data_base64'][0] =""
93 |
94 | logger.debug(f"volcano outpainting response: {resp}")
95 | return result_image, resp
96 |
97 | def process_outpainting(self, image, mask, ak, sk, seed):
98 | try:
99 | # 使用节点库的转换函数
100 | pil_image = tensor2pil(image)
101 | pil_mask = tensor2pil(mask)
102 |
103 | # 确保mask是灰度图像
104 | if pil_mask.mode != 'L':
105 | pil_mask = pil_mask.convert('L')
106 |
107 | # 直接转换为base64
108 | image_base64 = self.pil_to_base64(pil_image)
109 | mask_base64 = self.pil_to_base64(pil_mask)
110 |
111 | # 调用API
112 | result_image, _ = self.request_valcanic_outpainting(
113 | req_key="i2i_outpainting",
114 | ak=ak,
115 | sk=sk,
116 | image_base64s=[image_base64, mask_base64],
117 | seed=seed
118 | )
119 |
120 | # 使用节点库的转换函数转换结果为tensor
121 | result_tensor = pil2tensor(result_image)
122 |
123 | return (result_tensor,)
124 |
125 | except Exception as e:
126 | logger.exception(e)
127 | # 返回原图作为fallback
128 | return (image,)
129 |
130 | # 节点映射
131 | NODE_CLASS_MAPPINGS = {
132 | "VolcanoOutpaintingNode": VolcanoOutpaintingNode
133 | }
134 |
135 | NODE_DISPLAY_NAME_MAPPINGS = {
136 | "VolcanoOutpaintingNode": "volcano outpainting"
137 | }
138 |
--------------------------------------------------------------------------------
/py/nodes.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import folder_paths
3 | from nodes import LoadImage, LoadImageMask
4 | from comfy_extras.nodes_mask import ImageCompositeMasked
5 | from comfy.cli_args import args
6 | import comfy.model_management
7 | import comfy.clip_vision
8 | import comfy.controlnet
9 | import comfy.utils
10 | import comfy.sd
11 | import comfy.sample
12 | import comfy.samplers
13 | import comfy.diffusers_load
14 | import torch
15 | import yaml
16 | import os
17 | import sys
18 | import numpy as np
19 | from PIL import Image, ImageEnhance
20 | from .color_correct import ColorCorrectOfUtils
21 | import cv2
22 | from comfy_extras.nodes_upscale_model import ImageUpscaleWithModel
23 | from math import dist
24 | import folder_paths
25 | from .utils import tensor2cv
26 | import hashlib
27 |
28 | config_dir = os.path.join(folder_paths.base_path, "config")
29 | if not os.path.exists(config_dir):
30 | os.makedirs(config_dir)
31 |
32 | sys.path.insert(0, os.path.join(
33 | os.path.dirname(os.path.realpath(__file__)), "comfy"))
34 |
35 |
36 | logger = logging.getLogger(__file__)
37 |
38 |
39 | class LoadImageWithSwitch(LoadImage):
40 | @classmethod
41 | def INPUT_TYPES(s):
42 | input_dir = folder_paths.get_input_directory()
43 | files = [f for f in os.listdir(input_dir) if os.path.isfile(
44 | os.path.join(input_dir, f))]
45 | return {"required":
46 | {"image": (sorted(files), {"image_upload": True})},
47 | "optional": {
48 | "enabled": ("BOOLEAN", {"default": True, "label_on": "enabled", "label_off": "disabled"}),
49 | }
50 | }
51 |
52 | CATEGORY = "utils/image"
53 |
54 | RETURN_TYPES = ("IMAGE", "MASK", "BOOLEAN")
55 | RETURN_NAMES = ("image", "mask", "enabled")
56 | FUNCTION = "load_image_with_switch"
57 |
58 | def load_image_with_switch(self, image, enabled=True):
59 | logger.debug("start load image")
60 | if not enabled:
61 | return None, None, enabled
62 | return self.load_image(image) + (enabled, )
63 |
64 |
65 | class LoadImageWithoutListDir(LoadImage):
66 | @classmethod
67 | def INPUT_TYPES(s):
68 | return {"required":
69 | {"image": ([], {"image_upload": True})},
70 | "optional": {
71 | "enabled": ("BOOLEAN", {"default": True, "label_on": "enabled", "label_off": "disabled"}),
72 | }
73 | }
74 |
75 | CATEGORY = "utils/image"
76 |
77 | RETURN_TYPES = ("IMAGE", "MASK", "BOOLEAN", "STRING", "INT", "INT")
78 | RETURN_NAMES = ("image", "mask", "enabled", "filename", "width", "height")
79 | FUNCTION = "load_image_with_switch"
80 |
81 | def load_image_with_switch(self, image, enabled=True):
82 | logger.debug("start load image")
83 | if not enabled:
84 | return None, None, enabled, "", 0, 0
85 | output_image, output_mask = self.load_image(image)
86 | return (output_image, output_mask, enabled, image, output_image.shape[2], output_image.shape[1])
87 |
88 |
89 | @classmethod
90 | def IS_CHANGED(s, image, enabled):
91 | if not enabled:
92 | return ""
93 | image_path = folder_paths.get_annotated_filepath(image)
94 | m = hashlib.sha256()
95 | with open(image_path, 'rb') as f:
96 | m.update(f.read())
97 | return m.digest().hex()
98 |
99 | class LoadImageMaskWithSwitch(LoadImageMask):
100 | @classmethod
101 | def INPUT_TYPES(s):
102 | input_dir = folder_paths.get_input_directory()
103 | files = [f for f in os.listdir(input_dir) if os.path.isfile(
104 | os.path.join(input_dir, f))]
105 | return {"required":
106 | {"image": (sorted(files), {"image_upload": True}),
107 | "channel": (["red", "green", "blue", "alpha"], ), },
108 | "optional": {
109 | "enabled": ("BOOLEAN", {"default": True, "label_on": "enabled", "label_off": "disabled"}),
110 | },
111 | }
112 |
113 | CATEGORY = "utils/mask"
114 |
115 | RETURN_TYPES = ("MASK", "BOOLEAN")
116 | RETURN_NAMES = ("mask", "enabled")
117 | FUNCTION = "load_image_with_switch"
118 |
119 | def load_image_with_switch(self, image, channel, enabled=True):
120 | if not enabled:
121 | return (None, enabled)
122 | return self.load_image(image, channel) + (enabled, )
123 |
124 | @classmethod
125 | def VALIDATE_INPUTS(s, image, enabled):
126 | if not enabled:
127 | return True
128 | if not folder_paths.exists_annotated_filepath(image):
129 | return "Invalid image file: {}".format(image)
130 | return True
131 |
132 |
133 | class LoadImageMaskWithoutListDir(LoadImageMask):
134 | @classmethod
135 | def INPUT_TYPES(s):
136 | return {"required":
137 | {"image": ([], {"image_upload": True}),
138 | "channel": (["red", "green", "blue", "alpha"], ), },
139 | "optional": {
140 | "enabled": ("BOOLEAN", {"default": True, "label_on": "enabled", "label_off": "disabled"}),
141 | "mask_repeat_number":("INT", {"default": 1, "min": 1, "step": 1}),
142 | },
143 | }
144 |
145 | CATEGORY = "utils/mask"
146 |
147 | RETURN_TYPES = ("MASK", "BOOLEAN")
148 | RETURN_NAMES = ("mask", "enabled")
149 | FUNCTION = "load_image_with_switch"
150 |
151 | def load_image_with_switch(self, image, channel, enabled=True, mask_repeat_number=1):
152 | if not enabled:
153 | return (None, enabled)
154 | mask = self.load_image(image, channel)[0]
155 | mask = mask.unsqueeze(0) if mask.dim() == 2 else mask
156 | new_mask = mask.expand(mask_repeat_number, -1, -1)
157 | return (new_mask, enabled)
158 |
159 | @classmethod
160 | def VALIDATE_INPUTS(s, image, enabled):
161 | if not enabled:
162 | return True
163 | if not folder_paths.exists_annotated_filepath(image):
164 | return "Invalid image file: {}".format(image)
165 | return True
166 |
167 | @classmethod
168 | def IS_CHANGED(s, image, channel, enabled=True, mask_repeat_number=1):
169 | if not enabled:
170 | return ""
171 | image_path = folder_paths.get_annotated_filepath(image)
172 | m = hashlib.sha256()
173 | with open(image_path, 'rb') as f:
174 | m.update(f.read())
175 | return m.digest().hex()
176 |
177 | class ImageBatchOneOrMore:
178 |
179 | @classmethod
180 | def INPUT_TYPES(s):
181 | return {"required": {"image1": ("IMAGE",)},
182 | "optional": {"image2": ("IMAGE",), "image3": ("IMAGE",), "image4": ("IMAGE",), "image5": ("IMAGE",), "image6": ("IMAGE",)}}
183 |
184 | RETURN_TYPES = ("IMAGE",)
185 | FUNCTION = "batch"
186 |
187 | CATEGORY = "utils/image"
188 |
189 | def batch(self, image1, image2=None, image3=None, image4=None, image5=None, image6=None):
190 | images = [image1]
191 | for other_image in [image2, image3, image4, image5, image6]:
192 | if other_image is not None:
193 | try:
194 | if image1.shape[1:] != other_image.shape[1:]:
195 | other_image = comfy.utils.common_upscale(
196 | other_image.movedim(-1, 1), image1.shape[2], image1.shape[1], "bilinear", "center").movedim(1, -1)
197 | images.append(other_image)
198 | except Exception as e:
199 | logger.exception(e)
200 | s = torch.cat(images, dim=0)
201 | return (s,)
202 |
203 |
204 | class ConcatTextOfUtils:
205 | """
206 | This node will concatenate two strings together
207 | """
208 | @ classmethod
209 | def INPUT_TYPES(cls):
210 | return {"required": {
211 | "text1": ("STRING", {"multiline": True, "defaultBehavior": "input"}),
212 | "text2": ("STRING", {"multiline": True, "defaultBehavior": "input"}),
213 | "separator": ("STRING", {"multiline": False, "default": ","}),
214 | },
215 | "optional": {
216 | "text3": ("STRING", {"multiline": True, "defaultBehavior": "input"}),
217 | }
218 | }
219 |
220 | RETURN_TYPES = ("STRING",)
221 | FUNCTION = "fun"
222 | CATEGORY = "utils/text"
223 |
224 | @ staticmethod
225 | def fun(text1, separator, text2, text3=""):
226 | texts = [text1, text2, text3]
227 | texts = [text.strip() for text in texts if text.strip()]
228 | return (separator.join(texts),)
229 |
230 | class GenderWordsConfig:
231 | file_path = os.path.join(config_dir, "gender_words_config.yaml")
232 | if not os.path.exists(file_path):
233 | gender_map = {
234 | 'F': {
235 | 'man': 'woman', 'men': 'women', 'sir': 'madam', 'father': 'mother',
236 | 'husband': 'wife', 'son': 'daughter', 'boy': 'girl', 'brother': 'sister',
237 | 'uncle': 'aunt', 'grandfather': 'grandmother', 'nephew': 'niece',
238 | 'groom': 'bride', 'waiter': 'waitress', 'king': 'queen', 'gentleman': 'lady',
239 | 'prince': 'princess', 'male': 'female', 'fiance': 'fiancee',
240 | 'actor': 'actress', 'hero': 'heroine', 'he': 'she', 'his': 'her',
241 | 'him': 'her', 'himself': 'herself', "he's": "she's",
242 | }
243 | }
244 | gender_map['M'] = {value: key for key,
245 | value in gender_map['F'].items()}
246 | config = {"gender_map": gender_map, "gender_add_words": {
247 | "M": ["male",], "F": ["female"], },"error_words": {"person",}}
248 | with open(file_path, 'w') as file:
249 | yaml.dump(config, file)
250 |
251 | config = {}
252 |
253 | @staticmethod
254 | def load_config():
255 | with open(GenderWordsConfig.file_path, 'r') as file:
256 | GenderWordsConfig.config = yaml.safe_load(file)
257 |
258 | @staticmethod
259 | def get_config():
260 | return GenderWordsConfig.config
261 |
262 | @staticmethod
263 | def update_config(new_config):
264 | GenderWordsConfig.config.update(new_config)
265 | GenderWordsConfig.save_config()
266 |
267 | @staticmethod
268 | def save_config():
269 | with open(GenderWordsConfig.file_path, 'w') as file:
270 | yaml.dump(GenderWordsConfig.config, file)
271 |
272 |
273 | class ModifyTextGender:
274 | """
275 | This node will modify the prompt string according gender. gender words include M, F
276 | """
277 | @ classmethod
278 | def INPUT_TYPES(cls):
279 | return {"required": {
280 | "gender_prior": (["", "M", "F"],),
281 | "text": ("STRING", {"forceInput": True}),
282 | },
283 | "optional": {
284 | "gender_prior_weight": ("FLOAT", {"default": 1, "min": 0, "max": 3, "step": 0.1}),
285 | "gender_alternative": ("STRING", {"forceInput": True}),
286 | "enabled": ("BOOLEAN", {"default": True, "label_on": "enabled", "label_off": "disabled"}),
287 | },
288 | "hidden": {
289 | "age": ("INT", {"default": -1, "min": -1, "max": 120, "step": 1}),
290 | }
291 | }
292 |
293 | RETURN_TYPES = ("STRING",)
294 | FUNCTION = "fun"
295 | CATEGORY = "utils/text"
296 | GenderWordsConfig.load_config()
297 |
298 | @ staticmethod
299 | def fun(text, gender_prior="", gender_alternative=None, age=-1, enabled=True,gender_prior_weight=1.0):
300 | gender= gender_prior if gender_prior else gender_alternative
301 | weight = gender_prior_weight if gender_prior else 1.0
302 | gender_map = GenderWordsConfig.get_config().get("gender_map", {})
303 | if not enabled or text is None or gender is None or gender.upper() not in gender_map:
304 | return (text,)
305 | result = ModifyTextGender.gender_swap(text, gender, gender_map)
306 |
307 | result = ModifyTextGender.gender_add_words(result, gender, weight = weight)
308 | logger.info(f"ModifyTextGender result:{result}")
309 | return (result,)
310 |
311 | @ staticmethod
312 | def gender_add_words(text, gender, weight = 1.0):
313 | gender_add_map = GenderWordsConfig.get_config().get("gender_add_words", {})
314 | prefixes = gender_add_map[gender.upper()]
315 | if weight != 1.0:
316 | prefixes = [f"({prefix}:{weight:.1f})" for prefix in prefixes]
317 | result = ", ".join(prefixes + [text])
318 | return result
319 |
320 | @ staticmethod
321 | def gender_swap(text, gender, gender_map):
322 | words = text.split()
323 | mappings = gender_map[gender.upper()]
324 | for i, word in enumerate(words):
325 | masks = ""
326 | case = 'lower'
327 | original_word = word.lower()
328 | if original_word in GenderWordsConfig.get_config().get("error_words", {}):
329 | continue
330 | if word.endswith(".") or word.endswith(",") or word.endswith("'") or word.endswith('"') or word.endswith(":"):
331 | case = "masks"
332 | original_word, masks = original_word[:-1], original_word[-1]
333 |
334 | replacement = None
335 | for key, value in mappings.items():
336 | if len(key) == 2:
337 | if original_word == key:
338 | replacement = value
339 | break
340 | elif original_word.startswith(key) or original_word.endswith(key):
341 | replacement = original_word.replace(key, value)
342 | break
343 | if replacement is not None:
344 | if case == "masks":
345 | replacement = replacement + masks
346 | words[i] = replacement
347 | return ' '.join(words)
348 |
349 |
350 | class GenderControlOutput:
351 | """
352 | This node will modify the prompt string according gender. gender words include M, F
353 | """
354 | @ classmethod
355 | def INPUT_TYPES(cls):
356 | return {"required": {
357 | "gender_prior": (["", "M", "F"],),
358 | "male_text": ("STRING", {"multiline": True, "defaultBehavior": "input"}),
359 | "male_float": ("FLOAT", {"default": 1, "step": 0.1}),
360 | "male_int": ("INT", {"default": 1, "step": 1}),
361 | "female_text": ("STRING", {"multiline": True, "defaultBehavior": "input"}),
362 | "female_float": ("FLOAT", {"default": 1, "step": 0.1}),
363 | "female_int": ("INT", {"default": 1, "step": 1}),
364 | },
365 | "optional": {
366 | "gender_alternative": ("STRING", {"forceInput": True}),
367 | }
368 | }
369 |
370 | RETURN_TYPES = ("STRING","FLOAT","INT","BOOLEAN","BOOLEAN")
371 | RETURN_NAMES = ("gender_text","float","int","is_male","is_female")
372 | FUNCTION = "fun"
373 | CATEGORY = "utils/text"
374 |
375 | @ staticmethod
376 | def fun(gender_prior,male_text,male_float,male_int,female_text,female_float,female_int, gender_alternative=None):
377 | gender= gender_prior if gender_prior else gender_alternative
378 | if gender is None or gender.upper() not in ["M", "F"]:
379 | raise Exception("can't get any gender input.")
380 | if gender.upper()== "M":
381 | return (male_text, male_float, male_int, True, False)
382 | else:
383 | return (female_text, female_float, female_int, False, True)
384 |
385 |
386 | class ImageConcanateOfUtils:
387 | @classmethod
388 | def INPUT_TYPES(s):
389 | return {"required": {
390 | "image1": ("IMAGE",),
391 | "image2": ("IMAGE",),
392 | "direction": (
393 | ['right',
394 | 'down',
395 | 'left',
396 | 'up',
397 | ],
398 | {
399 | "default": 'right'
400 | }),
401 | },
402 | "optional":{
403 | "image3": ("IMAGE",),
404 | "image4": ("IMAGE",),
405 | "image5": ("IMAGE",),
406 | "image6": ("IMAGE",),
407 | }
408 | }
409 |
410 | RETURN_TYPES = ("IMAGE",)
411 | FUNCTION = "concanate"
412 | CATEGORY = "utils/image"
413 |
414 | def concanate(self, image1, image2=None, image3=None, image4=None, image5=None, image6=None, direction='right'):
415 | images = [image1]
416 |
417 | # 添加非空的image3-6到列表中
418 | for img in [image2,image3, image4, image5, image6]:
419 | if img is not None:
420 | images.append(img)
421 |
422 | # 如果只有一张图片,直接返回
423 | if len(images) == 1:
424 | return (images[0],)
425 |
426 | # 调整所有图片的大小为第一张图片的大小
427 | for i in range(1, len(images)):
428 | if images[i].shape[1:] != images[0].shape[1:]:
429 | images[i] = comfy.utils.common_upscale(
430 | images[i].movedim(-1, 1), images[0].shape[2], images[0].shape[1], "bilinear", "center").movedim(1, -1)
431 |
432 | # 根据方向拼接图片
433 | if direction in ['right', 'left']:
434 | row = torch.cat(images if direction == 'right' else [i for i in reversed(images)], dim=2)
435 | elif direction in ['down', 'up']:
436 | row = torch.cat(images if direction == 'down' else [i for i in reversed(images)], dim=1)
437 |
438 | return (row,)
439 |
440 | class SplitMask:
441 |
442 | @classmethod
443 | def INPUT_TYPES(self):
444 |
445 | return {
446 | "required": {
447 | "mask_prior": ("MASK", ),
448 | },
449 | "optional": {
450 | "mask_alternative": ("MASK", )
451 | }
452 | }
453 |
454 | RETURN_TYPES = ("MASK", "MASK",)
455 | RETURN_NAMES = ("mask", "mask",)
456 | FUNCTION = 'split_mask'
457 | CATEGORY = 'utils/mask'
458 |
459 | def split_mask(self, mask_prior, mask_alternative=None):
460 | mask = mask_prior if mask_prior is not None else mask_alternative
461 | if mask is None:
462 | return [torch.zeros((64, 64)).unsqueeze(0)] * 2
463 | ret_masks = []
464 | gray_image = mask[0].detach().cpu().numpy()
465 |
466 | # 对灰度图像进行阈值化处理,将白色区域转换为二进制掩码
467 | _, binary_mask = cv2.threshold(gray_image.astype(
468 | np.uint8), 0.5, 255, cv2.THRESH_BINARY)
469 |
470 | # 寻找白色区域的轮廓
471 | contours, _ = cv2.findContours(
472 | binary_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
473 | logger.info(f"find mask areas:{len(contours)}")
474 | if contours is not None and len(contours) > 0:
475 | # 根据轮廓的面积对其进行排序
476 | contours = sorted(contours, key=cv2.contourArea, reverse=True)[:2]
477 | contours = sorted(contours, key=lambda c: cv2.boundingRect(c)[0])
478 |
479 | for i, contour in enumerate(contours):
480 | # 创建一个新的同样尺寸的空图像
481 | new_mask = np.zeros_like(gray_image)
482 | # 在空图像中绘制当前轮廓
483 | cv2.drawContours(
484 | new_mask, [contour], -1, (255), thickness=cv2.FILLED)
485 | ret_masks.append(torch.tensor(new_mask/255))
486 | else:
487 | # 如果未找到轮廓,则返回空 tensor
488 | ret_masks = [torch.tensor(np.zeros_like(gray_image))] * 2
489 | if len(ret_masks) < 2:
490 | ret_masks.extend(
491 | [torch.tensor(np.zeros_like(gray_image))]*(2-len(ret_masks)))
492 |
493 | ret_masks = [torch.unsqueeze(m, 0) for m in ret_masks]
494 | return ret_masks
495 |
496 |
497 | class MaskFastGrow:
498 |
499 | @classmethod
500 | def INPUT_TYPES(self):
501 |
502 | return {
503 | "required": {
504 | "mask": ("MASK", ),
505 | "invert_mask": ("BOOLEAN", {"default": True}), # 反转mask
506 | "grow": ("INT", {"default": 4, "min": -999, "max": 999, "step": 1}),
507 | "blur": ("INT", {"default": 4, "min": 0, "max": 999, "step": 1}),
508 | },
509 | "optional": {
510 | "low_limit": ("FLOAT", {"default": 0, "min": 0, "max": 1, "step": 0.01}),
511 | "high_limit": ("FLOAT", {"default": 1, "min": 0, "max": 1, "step": 0.01}),
512 | "enabled": ("BOOLEAN", {"default": True, "label_on": "enabled", "label_off": "disabled"}),
513 | }
514 | }
515 |
516 | RETURN_TYPES = ("MASK",)
517 | FUNCTION = 'mask_grow'
518 | CATEGORY = 'utils/mask'
519 |
520 | def mask_grow(self, mask, invert_mask, grow, blur, low_limit=0, high_limit=1, enabled=True):
521 | if not enabled:
522 | return (mask,)
523 |
524 | if mask.dim() == 2:
525 | mask = torch.unsqueeze(mask, 0)
526 |
527 | c = 0
528 | kernel = np.array([[c, 1, c],
529 | [1, 1, 1],
530 | [c, 1, c]], dtype=np.uint8)
531 |
532 | mask = mask.reshape((-1, mask.shape[-2], mask.shape[-1]))
533 | out = []
534 |
535 | for m in mask:
536 | if invert_mask:
537 | m = 1 - m
538 | output = m.numpy().astype(np.float32)
539 |
540 | # Scale the float mask to [0, 255] for OpenCV processing
541 | output_scaled = (output * 255).astype(np.uint8)
542 |
543 | if grow > 0:
544 | output_scaled = cv2.dilate(
545 | output_scaled, kernel, iterations=grow)
546 | else:
547 | output_scaled = cv2.erode(
548 | output_scaled, kernel, iterations=-grow)
549 |
550 | # Apply Gaussian blur using OpenCV
551 | if blur > 0:
552 | output_blurred = cv2.GaussianBlur(
553 | output_scaled, (blur*2+1, blur*2+1), 0)
554 | else:
555 | output_blurred = output_scaled
556 |
557 | # Scale back to [0, 1]
558 | output = output_blurred.astype(np.float32) / 255.0
559 |
560 | if low_limit > 0:
561 | output = np.clip(output, low_limit, 1)
562 | if high_limit < 1:
563 | output = np.clip(output, 0, high_limit)
564 |
565 | out.append(torch.from_numpy(output))
566 |
567 | result = torch.stack(out, dim=0)
568 | if result.dim() == 2:
569 | result = torch.unsqueeze(result, 0)
570 | return (result,)
571 |
572 | class MaskFromFaceModel:
573 |
574 | @classmethod
575 | def INPUT_TYPES(self):
576 | return {
577 | "required": {
578 | "image": ("IMAGE",),
579 | "max_face_number": ("INT", {"default": -1, "min": -1, "max": 99, "step": 1}),
580 | "add_bbox_upper_points": ("BOOLEAN", {"default": False}), # 新增参数
581 | },
582 | "optional": {
583 | "faceanalysis": ("FACEANALYSIS", ),
584 | "face_model": ("FACE_MODEL", ),
585 | "cant_detect_mask_mode": (["black", "white", "none"], {"default": "black"}),
586 | "enabled": ("BOOLEAN", {"default": True, "label_on": "enabled", "label_off": "disabled"}),
587 | }
588 | }
589 |
590 | RETURN_TYPES = ("MASK","STRING")
591 | RETURN_NAMES = ("mask","genders")
592 | FUNCTION = 'mask_get'
593 | CATEGORY = 'utils/mask'
594 |
595 | def mask_get(self, image, max_face_number, add_bbox_upper_points, faceanalysis=None, face_model=None, cant_detect_mask_mode="black", enabled=True):
596 | if not enabled:
597 | return (None,)
598 |
599 | h, w = image.shape[-3:-1]
600 |
601 | cant_detect_result = None
602 | if cant_detect_mask_mode == "black":
603 | cant_detect_result = torch.zeros((1, h, w), dtype=torch.uint8)
604 | elif cant_detect_mask_mode == "white":
605 | cant_detect_result = torch.ones((1, h, w), dtype=torch.uint8)
606 |
607 | if faceanalysis is None and face_model is None:
608 | raise Exception("both faceanalysis and face_model are none!")
609 |
610 | if face_model is None:
611 | image_np = tensor2cv(image)
612 | image_np = image_np[0] if isinstance(image_np, list) else image_np
613 | face_model = self.analyze_faces(faceanalysis, image_np)
614 |
615 | if not isinstance(face_model,list):
616 | if face_model is None:
617 | face_models = []
618 | else:
619 | face_models = [face_model]
620 | else:
621 | face_models = face_model
622 |
623 | if len(face_models) == 0:
624 | return (cant_detect_result,)
625 |
626 | # 过滤低置信度的face
627 | det_scores = [f.det_score for f in face_models]
628 | if len(face_models) > 1 and max(det_scores) > 0.7:
629 | face_models = [f for f in face_models if f.det_score > 0.7]
630 |
631 | if max_face_number !=-1 and len(face_model) > max_face_number:
632 | face_models = self.remove_unavaible_face_models(face_models=face_models,max_people_number=max_face_number)
633 |
634 | face_models = sorted(face_models, key=lambda x:x.bbox[0])
635 | result = np.zeros((h, w), dtype=np.uint8)
636 | genders = []
637 | for face in face_models:
638 | genders.append(face.sex)
639 | points = face.landmark_2d_106.astype(np.int32) # Convert landmarks to integer format
640 | if add_bbox_upper_points:
641 | # 获取bbox的坐标
642 | x1, y1 = face.bbox[0:2]
643 | x2, y2 = face.bbox[2:4]
644 |
645 | # 计算上边的1/4和3/4位置的点
646 | width = x2 - x1
647 | left_quarter_x = x1 + width // 4
648 | right_quarter_x = x2 - width // 4
649 |
650 | # 创建两个新点
651 | left_quarter_point = np.array([left_quarter_x, y1], dtype=np.int32)
652 | right_quarter_point = np.array([right_quarter_x, y1], dtype=np.int32)
653 |
654 | # 将两个点添加到landmarks中
655 | points = np.vstack((points, left_quarter_point, right_quarter_point))
656 |
657 | points = points.reshape((-1, 1, 2)) # Reshape for cv2.drawContours
658 |
659 | # Compute the convex hull for the landmarks
660 | hull = cv2.convexHull(points)
661 |
662 | # Draw the convex hull on the mask as well
663 | cv2.drawContours(result, [hull], contourIdx=-1, color=255, thickness=cv2.FILLED)
664 |
665 | result = torch.unsqueeze(torch.tensor(np.clip(result/255, 0, 1)), 0)
666 |
667 | return (result, ",".join(genders))
668 |
669 | def remove_unavaible_face_models(self, face_models, max_people_number):
670 | max_lengths = []
671 |
672 | # Calculate the maximum length for each group of keypoints
673 | kpss = [f.kps for f in face_models]
674 | for keypoints in kpss:
675 | max_length = self.get_max_distance(keypoints)
676 | max_lengths.append(max_length)
677 |
678 | sorted_touple = sorted(zip(face_models, max_lengths), key=lambda x:x[1], reverse=True)
679 |
680 | # Filter out keypoints groups that have a maximum length less than one-fourth of the largest maximum length
681 | filtered_face_models = [
682 | face_model for face_model, _ in sorted_touple[:max_people_number]
683 | ]
684 |
685 | return filtered_face_models
686 |
687 | def get_max_distance(self, keypoints):
688 | max_distance = 0
689 |
690 | # Calculate the distance between every pair of keypoints
691 | for i in range(len(keypoints)):
692 | for j in range(i + 1, len(keypoints)):
693 | if keypoints[i] is not None and keypoints[j] is not None:
694 | distance = dist(keypoints[i], keypoints[j])
695 | max_distance = max(max_distance, distance)
696 |
697 | return max_distance
698 |
699 | def analyze_faces(self, insightface, img_data: np.ndarray):
700 | for size in [(size, size) for size in range(640, 310, -320)]:
701 | insightface.det_model.input_size = size
702 | face = insightface.get(img_data)
703 | if face:
704 | if 640 not in size:
705 | print(f"\033[33mINFO: InsightFace detection resolution lowered to {size}.\033[0m")
706 | break
707 | return face
708 |
709 | class MaskofCenter:
710 | @classmethod
711 | def INPUT_TYPES(s):
712 | return {
713 | "required": {
714 | "width": ("INT", {"default": 1024, "min": 0, "max": 8096, "step": 8}),
715 | "height": ("INT", {"default": 1024, "min": 0, "max": 8096, "step": 8}),
716 | "top": ("FLOAT", {"default": 0.25, "min": 0.0, "max": 1.0, "step": 0.01}),
717 | "bottom": ("FLOAT", {"default": 0.25, "min": 0.0, "max": 1.0, "step": 0.01}),
718 | "left": ("FLOAT", {"default": 0.25, "min": 0.0, "max": 1.0, "step": 0.01}),
719 | "right": ("FLOAT", {"default": 0.25, "min": 0.0, "max": 1.0, "step": 0.01}),
720 | "redius": ("FLOAT", {"default": 0.05, "min": 0.0, "max": 0.5, "step": 0.01}),
721 | },
722 | "optional": {
723 | "size_as": ("IMAGE",),
724 | }
725 | }
726 |
727 | RETURN_TYPES = ("MASK","INT","INT")
728 | RETURN_NAMES = ("mask","width","height")
729 | FUNCTION = 'mask_get'
730 | CATEGORY = 'utils/mask'
731 |
732 | def mask_get(self, size_as=None, width=1024, height=1024, top=0.25, bottom=0.25, left=0.25, right=0.25, redius=0.05):
733 | if size_as is not None:
734 | height, width = size_as.shape[-3:-1]
735 |
736 | # 创建全白色mask
737 | mask = torch.ones((1, height, width), dtype=torch.float32)
738 |
739 | # 计算各边界的像素值
740 | top_pixels = int(height * top)
741 | bottom_pixels = int(height * bottom)
742 | left_pixels = int(width * left)
743 | right_pixels = int(width * right)
744 | # 将边界区域设为黑色(0)
745 | if top > 0:
746 | mask[:, :top_pixels, :] = 0
747 | if bottom > 0:
748 | mask[:, -bottom_pixels:, :] = 0
749 | if left > 0:
750 | mask[:, :, :left_pixels] = 0
751 | if right > 0:
752 | mask[:, :, -right_pixels:] = 0
753 |
754 | # 添加圆弧效果
755 | if redius > 0:
756 | mask = self.add_corner_radius(mask[0], top_pixels, bottom_pixels, left_pixels, right_pixels, redius)
757 | mask = torch.unsqueeze(mask, 0)
758 |
759 | return (mask, width, height)
760 |
761 | def add_corner_radius(self, mask, top_pixels, bottom_pixels, left_pixels, right_pixels, radius_percent):
762 | """在mask的白色区域四个角添加圆弧效果
763 | Args:
764 | mask: 2D tensor mask
765 | top_pixels: 顶部黑色区域高度
766 | bottom_pixels: 底部黑色区域高度
767 | left_pixels: 左侧黑色区域宽度
768 | right_pixels: 右侧黑色区域宽度
769 | radius_percent: 圆弧半径(相对于较短边的百分比)
770 | """
771 | height, width = mask.shape
772 | min_side = min(height, width)
773 | radius = int(min_side * radius_percent)
774 |
775 | if radius <= 0:
776 | return mask
777 |
778 | # 创建圆形kernel
779 | y, x = torch.meshgrid(torch.arange(radius), torch.arange(radius))
780 | # 计算到圆心的距离
781 | dist_from_center = torch.sqrt((x - (radius-1))**2 + (y - (radius-1))**2).float()
782 | # 圆内为1,圆外为0
783 | circle = (dist_from_center <= radius).float()
784 |
785 | # 左上角
786 | mask[top_pixels:top_pixels+radius, left_pixels:left_pixels+radius] = circle
787 |
788 | # 右上角
789 | mask[top_pixels:top_pixels+radius, width-right_pixels-radius:width-right_pixels] = torch.flip(circle, [1])
790 |
791 | # 左下角
792 | mask[height-bottom_pixels-radius:height-bottom_pixels, left_pixels:left_pixels+radius] = torch.flip(circle, [0])
793 |
794 | # 右下角
795 | mask[height-bottom_pixels-radius:height-bottom_pixels, width-right_pixels-radius:width-right_pixels] = torch.flip(circle, [0, 1])
796 |
797 | return mask
798 |
799 | class MaskCoverFourCorners:
800 |
801 | @classmethod
802 | def INPUT_TYPES(self):
803 |
804 | return {
805 | "required": {
806 | "width": ("INT", {"default": 1024, "min": 0, "max": 8096, "step": 8}),
807 | "height": ("INT", {"default": 1024, "min": 0, "max": 8096, "step": 8}),
808 | "radius": ("INT", {"default": 100, "min": 0, "max": 8096, "step": 5}),
809 | "draw_top_left": ("BOOLEAN", {"default": False}),
810 | "draw_top_right": ("BOOLEAN", {"default": False}),
811 | "draw_bottom_right": ("BOOLEAN", {"default": True}),
812 | "draw_bottom_left": ("BOOLEAN", {"default": False}),
813 | },
814 | "optional": {
815 | "size_as": ("IMAGE",),
816 | }
817 | }
818 |
819 | RETURN_TYPES = ("MASK",)
820 | FUNCTION = 'mask_get'
821 | CATEGORY = 'utils/mask'
822 |
823 | def mask_get(self, size_as=None, width=1024, height=1024, radius=100,
824 | draw_top_left=False, draw_top_right=False, draw_bottom_right=True, draw_bottom_left=False):
825 | if size_as is not None:
826 | height, width = size_as.shape[-3:-1]
827 | result = self.create_mask_with_arcs(width, height, radius,draw_top_left, draw_top_right,draw_bottom_right,draw_bottom_left)
828 |
829 | result = torch.unsqueeze(torch.tensor(np.clip(result/255, 0, 1)), 0)
830 | return (result,)
831 |
832 | def create_mask_with_arcs(self, width=None, height=None, radius=50,
833 | draw_top_left=True, draw_top_right=True, draw_bottom_right=True, draw_bottom_left=True):
834 | """
835 | Creates a mask with circular arcs at the corners.
836 |
837 | :param width: Width of the mask.
838 | :param height: Height of the mask.
839 | :param radius: Radius of the circular arcs.
840 | :param draw_top_left: Boolean indicating whether to draw an arc at the top-left corner.
841 | :param draw_top_right: Boolean indicating whether to draw an arc at the top-right corner.
842 | :param draw_bottom_right: Boolean indicating whether to draw an arc at the bottom-right corner.
843 | :param draw_bottom_left: Boolean indicating whether to draw an arc at the bottom-left corner.
844 | :return: Mask image with arcs drawn.
845 | """
846 |
847 | # Create a white mask
848 | mask = np.ones((height, width), dtype=np.uint8) * 255
849 |
850 | # Draw arcs on the mask, filling them with black color
851 | if draw_top_left: # Top-left corner
852 | cv2.ellipse(mask, (0, 0), (radius, radius), 0, 0, 90, 0, -1) # Fill with black
853 | if draw_top_right: # Top-right corner
854 | cv2.ellipse(mask, (width, 0), (radius, radius), 0, 90, 180, 0, -1) # Fill with black
855 | if draw_bottom_right: # Bottom-right corner
856 | cv2.ellipse(mask, (width, height), (radius, radius), 0, 180, 270, 0, -1) # Fill with black
857 | if draw_bottom_left: # Bottom-left corner
858 | cv2.ellipse(mask, (0, height), (radius, radius), 0, 0, -90, 0, -1) # Fill with black
859 |
860 | return mask
861 |
862 |
863 | class MaskAutoSelector:
864 | @classmethod
865 | def INPUT_TYPES(self):
866 |
867 | return {
868 | "required": {
869 | "mask_prior": ("MASK", ),
870 | },
871 | "optional": {
872 | "mask_alternative": ("MASK", ),
873 | "mask_third": ("MASK", )
874 | }
875 | }
876 |
877 | RETURN_TYPES = ("MASK",)
878 | RETURN_NAMES = ("mask",)
879 | FUNCTION = 'select_mask'
880 | CATEGORY = 'utils/mask'
881 |
882 | def select_mask(self, mask_prior=None, mask_alternative=None, mask_third=None):
883 | if mask_prior is not None:
884 | mask = mask_prior
885 | elif mask_alternative is not None:
886 | mask = mask_alternative
887 | else:
888 | mask = mask_third
889 |
890 | if mask is None:
891 | raise RuntimeError("all mask inputs is None")
892 |
893 | if mask.dim() == 2:
894 | mask = torch.unsqueeze(mask, 0)
895 | return (mask,)
896 |
897 |
898 | class FloatMultipleAddLiteral:
899 | RETURN_TYPES = ("FLOAT", "FLOAT", "INT")
900 | RETURN_NAMES = ("x", "ax + b", "ax + b(int)")
901 | FUNCTION = "get_float"
902 | CATEGORY = "utils/numbers"
903 |
904 | @classmethod
905 | def INPUT_TYPES(cls):
906 | return {"required": {"number": ("FLOAT", {"default": 0, "min": 0, "max": 1000000})},
907 | "optional": {"a_aign": (["positive", "negative"], {"default": "positive"}),
908 | "a": ("FLOAT", {"default": 1.0, "step": 0.001}), "b": ("FLOAT", {"default": 1, "step": 0.001}),
909 | }
910 | }
911 |
912 | def get_float(self, number, a, b, a_aign):
913 | if a_aign == "negative":
914 | a = - a
915 | return (number, a*number + b, int(a*number + b))
916 |
917 | class IntMultipleAddLiteral:
918 | RETURN_TYPES = ("INT", "INT", "FLOAT")
919 | RETURN_NAMES = ("x", "ax + b", "ax + b(float)")
920 | FUNCTION = "get_int"
921 | CATEGORY = "utils/numbers"
922 |
923 | @classmethod
924 | def INPUT_TYPES(cls):
925 | return {"required": {"number": ("INT", {"default": 0, "min": 0, "max": 1000000})},
926 | "optional": {"a_aign": (["positive", "negative"], {"default": "positive"}),
927 | "a": ("FLOAT", {"default": 1.0, "step": 0.001}), "b": ("INT", {"default": 1, "step": 1}),
928 | }
929 | }
930 |
931 | def get_int(self, number, a, b, a_aign):
932 | if a_aign == "negative":
933 | a = - a
934 | return (number, int(a*number + b), a*number + b)
935 |
936 | MAX_RESOLUTION = 16384
937 |
938 |
939 | class ImageCompositeMaskedWithSwitch(ImageCompositeMasked):
940 | @classmethod
941 | def INPUT_TYPES(s):
942 | return {
943 | "required": {
944 | "destination": ("IMAGE",),
945 | "source": ("IMAGE",),
946 | "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
947 | "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
948 | "resize_source": ("BOOLEAN", {"default": False}),
949 | },
950 | "optional": {
951 | "mask": ("MASK",),
952 | "enabled": ("BOOLEAN", {"default": True, "label_on": "enabled", "label_off": "disabled"}),
953 | "invert_mask": ("BOOLEAN", {"default": False, "label_on": "enabled", "label_off": "disabled"}),
954 | }
955 | }
956 | RETURN_TYPES = ("IMAGE",)
957 | FUNCTION = "composite_with_switch"
958 |
959 | CATEGORY = "utils/image"
960 |
961 | def composite_with_switch(self, destination, source, x, y, resize_source, mask=None, enabled=True, invert_mask=False):
962 | if not enabled:
963 | return (destination, )
964 | if invert_mask:
965 | mask = 1.0 - mask
966 | return self.composite(destination, source, x, y, resize_source, mask)
967 |
968 |
969 | class CheckpointLoaderSimpleWithSwitch:
970 | @classmethod
971 | def INPUT_TYPES(s):
972 | return {"required": {"ckpt_name": (folder_paths.get_filename_list("checkpoints"), ),
973 | },
974 | "optional": {
975 | "load_model": ("BOOLEAN", {"default": True, "label_on": "enabled", "label_off": "disabled"}),
976 | "load_clip": ("BOOLEAN", {"default": True, "label_on": "enabled", "label_off": "disabled"}),
977 | "load_vae": ("BOOLEAN", {"default": True, "label_on": "enabled", "label_off": "disabled"}),
978 | }}
979 | RETURN_TYPES = ("MODEL", "CLIP", "VAE")
980 | FUNCTION = "load_checkpoint"
981 |
982 | CATEGORY = "utils/loaders"
983 |
984 | def load_checkpoint(self, ckpt_name, load_model, load_clip, load_vae):
985 | ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
986 | out = comfy.sd.load_checkpoint_guess_config(ckpt_path, output_model=load_model, output_vae=load_vae,
987 | output_clip=load_clip, embedding_directory=folder_paths.get_folder_paths("embeddings"))
988 | return out[:3]
989 |
990 |
991 | class ImageResizeTo8x:
992 | def __init__(self):
993 | pass
994 |
995 | ACTION_TYPE_RESIZE = "resize only"
996 | ACTION_TYPE_CROP = "crop to ratio"
997 | ACTION_TYPE_PAD = "pad to ratio"
998 | RESIZE_MODE_DOWNSCALE = "reduce size only"
999 | RESIZE_MODE_UPSCALE = "increase size only"
1000 | RESIZE_MODE_ANY = "any"
1001 | RETURN_TYPES = ("IMAGE", "MASK", "INT", "INT")
1002 | RETURN_NAMES = ("image", "mask", "width", "height")
1003 | FUNCTION = "resize"
1004 | CATEGORY = "utils/image"
1005 |
1006 | @classmethod
1007 | def INPUT_TYPES(s):
1008 | return {
1009 | "required": {
1010 | "pixels": ("IMAGE",),
1011 | "action": ([s.ACTION_TYPE_RESIZE, s.ACTION_TYPE_CROP, s.ACTION_TYPE_PAD],),
1012 | "smaller_side": ("INT", {"default": 0, "min": 0, "max": 8192, "step": 8}),
1013 | "larger_side": ("INT", {"default": 0, "min": 0, "max": 8192, "step": 8}),
1014 | "target_width": ("INT", {"default": 0, "min": 0, "max": 8192, "step": 1}),
1015 | "target_height": ("INT", {"default": 0, "min": 0, "max": 8192, "step": 1}),
1016 | "scale_factor": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 10.0, "step": 0.1}),
1017 | "resize_mode": ([s.RESIZE_MODE_DOWNSCALE, s.RESIZE_MODE_UPSCALE, s.RESIZE_MODE_ANY],),
1018 | "side_ratio": ("STRING", {"default": "4:3"}),
1019 | "crop_pad_position": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
1020 | "pad_feathering": ("INT", {"default": 20, "min": 0, "max": 8192, "step": 1}),
1021 | "all_szie_8x": (["disable", "crop", "resize"],),
1022 | },
1023 | "optional": {
1024 | "mask_optional": ("MASK",),
1025 | "all_size_16x": (["disable", "crop", "resize"],),
1026 | },
1027 | }
1028 |
1029 | @classmethod
1030 | def VALIDATE_INPUTS(s, action, smaller_side, larger_side, scale_factor, resize_mode, side_ratio,target_width,target_height, **_):
1031 | if side_ratio is not None:
1032 | if action != s.ACTION_TYPE_RESIZE and s.parse_side_ratio(side_ratio) is None:
1033 | return f"Invalid side ratio: {side_ratio}"
1034 |
1035 | if smaller_side is not None and larger_side is not None and scale_factor is not None:
1036 | if int(smaller_side > 0) + int(larger_side > 0) + int(scale_factor > 0) > 1:
1037 | return f"At most one scaling rule (smaller_side, larger_side, scale_factor) should be enabled by setting a non-zero value"
1038 |
1039 | if scale_factor is not None:
1040 | if resize_mode == s.RESIZE_MODE_DOWNSCALE and scale_factor > 1.0:
1041 | return f"For resize_mode {s.RESIZE_MODE_DOWNSCALE}, scale_factor should be less than one but got {scale_factor}"
1042 | if resize_mode == s.RESIZE_MODE_UPSCALE and scale_factor > 0.0 and scale_factor < 1.0:
1043 | return f"For resize_mode {s.RESIZE_MODE_UPSCALE}, scale_factor should be larger than one but got {scale_factor}"
1044 |
1045 | if (target_width == 0 and target_height != 0) or (target_width != 0 and target_height == 0):
1046 | return f"targe_width and target_height should be set or unset simultaneously"
1047 | return True
1048 |
1049 | @classmethod
1050 | def parse_side_ratio(s, side_ratio):
1051 | try:
1052 | x, y = map(int, side_ratio.split(":", 1))
1053 | if x < 1 or y < 1:
1054 | raise Exception("Ratio factors have to be positive numbers")
1055 | return float(x) / float(y)
1056 | except:
1057 | return None
1058 |
1059 | def vae_encode_crop_pixels(self, pixels, ratio=8):
1060 | dims = pixels.shape[1:3]
1061 | for d in range(len(dims)):
1062 | x = (dims[d] // ratio) * ratio
1063 | x_offset = (dims[d] % ratio) // 2
1064 | if x != dims[d]:
1065 | pixels = pixels.narrow(d + 1, x_offset, x)
1066 | return pixels
1067 |
1068 | def resize_a_little_to_ratio(self, image, mask,ratio=8):
1069 | in_h, in_w = image.shape[1:3]
1070 | out_h = (in_h // ratio) * ratio
1071 | out_w = (in_w // ratio) * ratio
1072 | if in_h != out_h or in_w != out_w:
1073 | image, mask = self.interpolate_to_target_size(image, mask, out_h, out_w)
1074 | return image, mask
1075 |
1076 | def interpolate_to_target_size(self, image, mask, height, width):
1077 | image = torch.nn.functional.interpolate(
1078 | image.movedim(-1, 1), size=(height, width), mode="bicubic", antialias=True).movedim(1, -1).clamp(0.0, 1.0)
1079 | mask = torch.nn.functional.interpolate(mask.unsqueeze(
1080 | 0), size=(height, width), mode="bicubic", antialias=True).squeeze(0).clamp(0.0, 1.0)
1081 |
1082 | return image, mask
1083 |
1084 | def resize(self, pixels, action, smaller_side, larger_side, scale_factor, resize_mode, side_ratio, crop_pad_position, pad_feathering, mask_optional=None, all_szie_8x="disable",target_width=0,target_height=0,all_size_16x="disable"):
1085 | validity = self.VALIDATE_INPUTS(
1086 | action, smaller_side, larger_side, scale_factor, resize_mode, side_ratio,target_width,target_height)
1087 | if validity is not True:
1088 | raise Exception(validity)
1089 |
1090 | height, width = pixels.shape[1:3]
1091 | if mask_optional is None:
1092 | mask = torch.zeros(1, height, width, dtype=torch.float32)
1093 | else:
1094 | mask = mask_optional
1095 | if len(mask.shape) == 2:
1096 | mask = mask.unsqueeze(0)
1097 | if mask.shape[1] != height or mask.shape[2] != width:
1098 | mask = torch.nn.functional.interpolate(mask.unsqueeze(0), size=(
1099 | height, width), mode="bicubic").squeeze(0).clamp(0.0, 1.0)
1100 |
1101 | crop_x, crop_y, pad_x, pad_y = (0.0, 0.0, 0.0, 0.0)
1102 | if action == self.ACTION_TYPE_CROP:
1103 | target_ratio = target_width / target_height if target_width != 0 and target_height!=0 else self.parse_side_ratio(side_ratio)
1104 | if height * target_ratio < width:
1105 | crop_x = width - height * target_ratio
1106 | else:
1107 | crop_y = height - width / target_ratio
1108 | elif action == self.ACTION_TYPE_PAD:
1109 | target_ratio = target_width / target_height if target_width != 0 and target_height!=0 else self.parse_side_ratio(side_ratio)
1110 | if height * target_ratio > width:
1111 | pad_x = height * target_ratio - width
1112 | else:
1113 | pad_y = width / target_ratio - height
1114 |
1115 | if smaller_side > 0:
1116 | if width + pad_x - crop_x > height + pad_y - crop_y:
1117 | scale_factor = float(smaller_side) / (height + pad_y - crop_y)
1118 | else:
1119 | scale_factor = float(smaller_side) / (width + pad_x - crop_x)
1120 | if larger_side > 0:
1121 | if width + pad_x - crop_x > height + pad_y - crop_y:
1122 | scale_factor = float(larger_side) / (width + pad_x - crop_x)
1123 | else:
1124 | scale_factor = float(larger_side) / (height + pad_y - crop_y)
1125 |
1126 | if (resize_mode == self.RESIZE_MODE_DOWNSCALE and scale_factor >= 1.0) or (resize_mode == self.RESIZE_MODE_UPSCALE and scale_factor <= 1.0):
1127 | scale_factor = 0.0
1128 |
1129 | if scale_factor > 0.0:
1130 | pixels = torch.nn.functional.interpolate(
1131 | pixels.movedim(-1, 1), scale_factor=scale_factor, mode="bicubic", antialias=True).movedim(1, -1).clamp(0.0, 1.0)
1132 | mask = torch.nn.functional.interpolate(mask.unsqueeze(
1133 | 0), scale_factor=scale_factor, mode="bicubic", antialias=True).squeeze(0).clamp(0.0, 1.0)
1134 | height, width = pixels.shape[1:3]
1135 |
1136 | crop_x *= scale_factor
1137 | crop_y *= scale_factor
1138 | pad_x *= scale_factor
1139 | pad_y *= scale_factor
1140 |
1141 | if crop_x > 0.0 or crop_y > 0.0:
1142 | remove_x = (round(crop_x * crop_pad_position), round(crop_x *
1143 | (1 - crop_pad_position))) if crop_x > 0.0 else (0, 0)
1144 | remove_y = (round(crop_y * crop_pad_position), round(crop_y *
1145 | (1 - crop_pad_position))) if crop_y > 0.0 else (0, 0)
1146 | pixels = pixels[:, remove_y[0]:height -
1147 | remove_y[1], remove_x[0]:width - remove_x[1], :]
1148 | mask = mask[:, remove_y[0]:height - remove_y[1],
1149 | remove_x[0]:width - remove_x[1]]
1150 | elif pad_x > 0.0 or pad_y > 0.0:
1151 | add_x = (round(pad_x * crop_pad_position), round(pad_x *
1152 | (1 - crop_pad_position))) if pad_x > 0.0 else (0, 0)
1153 | add_y = (round(pad_y * crop_pad_position), round(pad_y *
1154 | (1 - crop_pad_position))) if pad_y > 0.0 else (0, 0)
1155 |
1156 | new_pixels = torch.zeros(pixels.shape[0], height + add_y[0] + add_y[1],
1157 | width + add_x[0] + add_x[1], pixels.shape[3], dtype=torch.float32)
1158 | new_pixels[:, add_y[0]:height + add_y[0],
1159 | add_x[0]:width + add_x[0], :] = pixels
1160 | pixels = new_pixels
1161 |
1162 | new_mask = torch.ones(
1163 | mask.shape[0], height + add_y[0] + add_y[1], width + add_x[0] + add_x[1], dtype=torch.float32)
1164 | new_mask[:, add_y[0]:height + add_y[0],
1165 | add_x[0]:width + add_x[0]] = mask
1166 | mask = new_mask
1167 |
1168 | if pad_feathering > 0:
1169 | for i in range(mask.shape[0]):
1170 | for j in range(pad_feathering):
1171 | feather_strength = (
1172 | 1 - j / pad_feathering) * (1 - j / pad_feathering)
1173 | if add_x[0] > 0 and j < width:
1174 | for k in range(height):
1175 | mask[i, k, add_x[0] +
1176 | j] = max(mask[i, k, add_x[0] + j], feather_strength)
1177 | if add_x[1] > 0 and j < width:
1178 | for k in range(height):
1179 | mask[i, k, width + add_x[0] - j - 1] = max(
1180 | mask[i, k, width + add_x[0] - j - 1], feather_strength)
1181 | if add_y[0] > 0 and j < height:
1182 | for k in range(width):
1183 | mask[i, add_y[0] + j,
1184 | k] = max(mask[i, add_y[0] + j, k], feather_strength)
1185 | if add_y[1] > 0 and j < height:
1186 | for k in range(width):
1187 | mask[i, height + add_y[0] - j - 1, k] = max(
1188 | mask[i, height + add_y[0] - j - 1, k], feather_strength)
1189 |
1190 | if target_width != 0 and target_height!=0:
1191 | pixels, mask = self.interpolate_to_target_size(pixels, mask, target_height, target_width)
1192 |
1193 | if all_size_16x == "crop":
1194 | pixels = self.vae_encode_crop_pixels(pixels,16)
1195 | mask = self.vae_encode_crop_pixels(mask,16)
1196 | elif all_size_16x == "resize":
1197 | pixels, mask = self.resize_a_little_to_ratio(pixels, mask, ratio=16)
1198 |
1199 | elif all_szie_8x == "crop":
1200 | pixels = self.vae_encode_crop_pixels(pixels)
1201 | mask = self.vae_encode_crop_pixels(mask)
1202 | elif all_szie_8x == "resize":
1203 | pixels, mask = self.resize_a_little_to_ratio(pixels, mask, ratio=8)
1204 |
1205 | height, width = pixels.shape[1:3]
1206 | return (pixels, mask, width, height)
1207 |
1208 |
1209 | class TextPreview:
1210 | """this node code comes from ComfyUI-Custom-Scripts\py\show_text.py. thanks the orininal writer."""
1211 |
1212 | @classmethod
1213 | def INPUT_TYPES(s):
1214 | return {
1215 | "required": {
1216 | "text": ("STRING", {"forceInput": True}),
1217 | },
1218 | "hidden": {
1219 | "unique_id": "UNIQUE_ID",
1220 | "extra_pnginfo": "EXTRA_PNGINFO",
1221 | },
1222 | }
1223 |
1224 | INPUT_IS_LIST = True
1225 | RETURN_TYPES = ("STRING",)
1226 | FUNCTION = "notify"
1227 | OUTPUT_NODE = True
1228 | OUTPUT_IS_LIST = (True,)
1229 |
1230 | CATEGORY = "utils/text"
1231 |
1232 | def notify(self, text, unique_id=None, extra_pnginfo=None):
1233 | if unique_id is not None and extra_pnginfo is not None:
1234 | if not isinstance(extra_pnginfo, list):
1235 | logger.warn("Error: extra_pnginfo is not a list")
1236 | elif (
1237 | not isinstance(extra_pnginfo[0], dict)
1238 | or "workflow" not in extra_pnginfo[0]
1239 | ):
1240 | logger.warn(
1241 | "Error: extra_pnginfo[0] is not a dict or missing 'workflow' key")
1242 | else:
1243 | workflow = extra_pnginfo[0]["workflow"]
1244 | node = next(
1245 | (x for x in workflow["nodes"] if str(
1246 | x["id"]) == str(unique_id[0])),
1247 | None,
1248 | )
1249 | if node:
1250 | node["widgets_values"] = [text]
1251 |
1252 | return {"ui": {"text": text}, "result": (text,)}
1253 |
1254 | class TextInputAutoSelector:
1255 | @classmethod
1256 | def INPUT_TYPES(s):
1257 | return {
1258 | "required": {
1259 | "component_input": ("STRING", {"multiline": True}),
1260 | },
1261 | "optional":{
1262 | "alternative_input": ("STRING",{"forceInput": True}),
1263 | }
1264 | }
1265 |
1266 | RETURN_TYPES = ("STRING",)
1267 | FUNCTION = "select_input"
1268 | CATEGORY = "utils/text"
1269 |
1270 | def select_input(self, component_input, alternative_input=""):
1271 | # 去除组件输入两端的空白字符
1272 | component_input = component_input.strip()
1273 |
1274 | # 如果组件输入为空或只包含空白字符,选择外部输入
1275 | if not component_input:
1276 | selected_input = alternative_input
1277 | else:
1278 | selected_input = component_input
1279 |
1280 | return (selected_input,)
1281 |
1282 |
1283 | class MatchImageRatioToPreset:
1284 | def __init__(self):
1285 | self.presets = [
1286 | (704, 1408), (704, 1344), (768, 1344), (768,
1287 | 1280), (832, 1216), (832, 1152),
1288 | (896, 1152), (896, 1088), (960, 1088), (960,
1289 | 1024), (1024, 1024), (1024, 960),
1290 | (1088, 960), (1088, 896), (1152,
1291 | 896), (1152, 832), (1216, 832), (1280, 768),
1292 | (1344, 768), (1344, 704), (1408,
1293 | 704), (1472, 704), (1536, 640), (1600, 640),
1294 | (1664, 576), (1728, 576)
1295 | ]
1296 |
1297 | @classmethod
1298 | def INPUT_TYPES(s):
1299 | return {
1300 | "required": {
1301 | "image": ("IMAGE",),
1302 | "width_offset": ("INT", {"default": 0, "min": -128, "max": 128, "step": 8}),
1303 | "height_offset": ("INT", {"default": 0, "min": -128, "max": 128, "step": 8}),
1304 | }
1305 | }
1306 |
1307 | RETURN_TYPES = ("INT", "INT", "INT", "INT")
1308 | RETURN_NAMES = ("standard_width", "standard_height", "min", "max")
1309 | FUNCTION = "forward"
1310 |
1311 | CATEGORY = "utils/image"
1312 |
1313 | def forward(self, image, width_offset=0, height_offset=0):
1314 | h, w = image.shape[1:-1]
1315 | aspect_ratio = w / h
1316 |
1317 | # 计算每个预设的宽高比,并与输入图像的宽高比进行比较
1318 | distances = [abs(aspect_ratio - w/h) for w,h in self.presets]
1319 | closest_index = np.argmin(distances)
1320 |
1321 | # 选择最接近的预设尺寸
1322 | target_w, target_h = self.presets[closest_index]
1323 | if width_offset != 0:
1324 | target_w += width_offset
1325 | if height_offset != 0:
1326 | target_h += height_offset
1327 |
1328 | max_v, min_v = max(target_h, target_w), min(target_h, target_w)
1329 | logger.debug((target_w, target_h, min_v, max_v))
1330 | return (target_w, target_h, min_v, max_v)
1331 |
1332 |
1333 | class UpscaleImageWithModelIfNeed(ImageUpscaleWithModel):
1334 |
1335 | def __init__(self) -> None:
1336 | super().__init__()
1337 |
1338 | @classmethod
1339 | def INPUT_TYPES(s):
1340 | return {"required": {"upscale_model": ("UPSCALE_MODEL",),
1341 | "image": ("IMAGE",),
1342 | "threshold_of_xl_area": ("FLOAT", {"default": 0.9, "min": 0.0, "max": 64.0, "step": 0.01}),
1343 | },
1344 | "hidden":{
1345 | "tile_size": ("INT", {"default": 512, "min": 128, "max": 10000}),
1346 | }}
1347 | RETURN_TYPES = ("IMAGE",)
1348 | FUNCTION = "forward"
1349 |
1350 | CATEGORY = "utils/image"
1351 |
1352 | def forward(self, image, upscale_model, threshold_of_xl_area=0.9):
1353 | h, w = image.shape[1:-1]
1354 | percent = h * w / (1024 * 1024)
1355 | if percent > threshold_of_xl_area:
1356 | return (image,)
1357 |
1358 | return self.upscale(upscale_model, image)
1359 |
1360 |
1361 | class ImageAutoSelector:
1362 | @classmethod
1363 | def INPUT_TYPES(s):
1364 | return {
1365 | "required": {
1366 | },
1367 | "optional": {
1368 | "image_prior": ("IMAGE",),
1369 | "image_alternative": ("IMAGE",),
1370 | "image_third": ("IMAGE",)
1371 | }
1372 | }
1373 |
1374 | RETURN_TYPES = ("IMAGE",)
1375 | RETURN_NAMES = ("image",)
1376 | FUNCTION = "select_image"
1377 | CATEGORY = "utils/image"
1378 |
1379 | def select_image(self, image_prior=None, image_alternative=None, image_third=None):
1380 | if image_prior is not None:
1381 | image = image_prior
1382 | elif image_alternative is not None:
1383 | image = image_alternative
1384 | else:
1385 | image = image_third
1386 |
1387 | if image is None:
1388 | raise RuntimeError("all image inputs are None")
1389 |
1390 | return (image,)
1391 |
1392 | class BooleanControlOutput:
1393 | """
1394 | This node will output different values based on a boolean input
1395 | """
1396 | @classmethod
1397 | def INPUT_TYPES(cls):
1398 | return {"required": {
1399 | "boolean_input": ("BOOLEAN", {"default": True, "label_on": "True", "label_off": "False"}),
1400 | "true_text": ("STRING", {"multiline": True, "defaultBehavior": "input"}),
1401 | "true_float": ("FLOAT", {"default": 1, "step": 0.05}),
1402 | "true_int": ("INT", {"default": 1, "step": 1}),
1403 | "false_text": ("STRING", {"multiline": True, "defaultBehavior": "input"}),
1404 | "false_float": ("FLOAT", {"default": 0, "step": 0.1}),
1405 | "false_int": ("INT", {"default": 0, "step": 1}),
1406 | }}
1407 |
1408 | RETURN_TYPES = ("STRING", "FLOAT", "INT", "BOOLEAN", "BOOLEAN")
1409 | RETURN_NAMES = ("text", "float", "int", "is_true", "is_false")
1410 | FUNCTION = "fun"
1411 | CATEGORY = "utils/text"
1412 |
1413 | @staticmethod
1414 | def fun(boolean_input, true_text, true_float, true_int, false_text, false_float, false_int):
1415 | if boolean_input:
1416 | return (true_text, true_float, true_int, True, False)
1417 | else:
1418 | return (false_text, false_float, false_int, False, True)
1419 |
1420 |
1421 | NODE_CLASS_MAPPINGS = {
1422 |
1423 | #image
1424 | "LoadImageWithSwitch": LoadImageWithSwitch,
1425 | "LoadImageMaskWithSwitch": LoadImageMaskWithSwitch,
1426 | "LoadImageWithoutListDir": LoadImageWithoutListDir,
1427 | "LoadImageMaskWithoutListDir": LoadImageMaskWithoutListDir,
1428 | "ImageCompositeMaskedWithSwitch": ImageCompositeMaskedWithSwitch,
1429 | "ImageBatchOneOrMore": ImageBatchOneOrMore,
1430 | "ImageConcanateOfUtils": ImageConcanateOfUtils,
1431 | "ColorCorrectOfUtils": ColorCorrectOfUtils,
1432 | "UpscaleImageWithModelIfNeed": UpscaleImageWithModelIfNeed,
1433 | "ImageResizeTo8x": ImageResizeTo8x,
1434 | "ImageAutoSelector": ImageAutoSelector,
1435 |
1436 | # text
1437 | "ConcatTextOfUtils": ConcatTextOfUtils,
1438 | "ModifyTextGender": ModifyTextGender,
1439 | "GenderControlOutput": GenderControlOutput,
1440 | "TextPreview": TextPreview,
1441 | "TextInputAutoSelector": TextInputAutoSelector,
1442 | "BooleanControlOutput": BooleanControlOutput,
1443 |
1444 | # numbers
1445 | "MatchImageRatioToPreset": MatchImageRatioToPreset,
1446 | "FloatMultipleAddLiteral": FloatMultipleAddLiteral,
1447 | "IntMultipleAddLiteral": IntMultipleAddLiteral,
1448 |
1449 | # mask
1450 | "SplitMask": SplitMask,
1451 | "MaskFastGrow": MaskFastGrow,
1452 | "MaskAutoSelector": MaskAutoSelector,
1453 | "MaskFromFaceModel": MaskFromFaceModel,
1454 | "MaskCoverFourCorners": MaskCoverFourCorners,
1455 | "MaskofCenter": MaskofCenter,
1456 |
1457 | #loader
1458 | "CheckpointLoaderSimpleWithSwitch": CheckpointLoaderSimpleWithSwitch,
1459 | "ImageAutoSelector": ImageAutoSelector,
1460 | }
1461 |
1462 | NODE_DISPLAY_NAME_MAPPINGS = {
1463 | # Image
1464 | "LoadImageWithSwitch": "Load Image with Switch",
1465 | "LoadImageMaskWithSwitch": "Load Image as Mask with Switch",
1466 | "LoadImageWithoutListDir": "Load Image without Listing Input Dir",
1467 | "LoadImageMaskWithoutListDir": "Load Image as Mask without Listing Input Dir",
1468 | "ImageCompositeMaskedWithSwitch": "Image Composite Masked with Switch",
1469 | "ImageBatchOneOrMore": "Batch Images One or More",
1470 | "ImageConcanateOfUtils": "Image Concatenate of Utils",
1471 | "ColorCorrectOfUtils": "Color Correct of Utils",
1472 | "UpscaleImageWithModelIfNeed": "Upscale Image Using Model if Need",
1473 | "ImageResizeTo8x": "Image Resize to 8x",
1474 | "ImageAutoSelector": "Image Auto Selector",
1475 |
1476 | # Text
1477 | "ConcatTextOfUtils": "Concat Text",
1478 | "ModifyTextGender": "Modify Text Gender",
1479 | "GenderControlOutput": "Gender Control Output",
1480 | "TextPreview": "Preview Text",
1481 | "TextInputAutoSelector": "Text Input Auto Selector",
1482 | "BooleanControlOutput": "Boolean Control Output",
1483 |
1484 | # Number
1485 | "MatchImageRatioToPreset": "Match Image Ratio to Standard Size",
1486 | "FloatMultipleAddLiteral": "Float Multiple and Add Literal",
1487 | "IntMultipleAddLiteral": "Int Multiple and Add Literal",
1488 |
1489 | # Mask
1490 | "SplitMask": "Split Mask by Contours",
1491 | "MaskFastGrow": "Mask Grow Fast",
1492 | "MaskAutoSelector": "Mask Auto Selector",
1493 | "MaskFromFaceModel": "Mask from FaceModel",
1494 | "MaskCoverFourCorners": "Mask Cover Four Corners",
1495 | "MaskofCenter": "Mask of Center",
1496 |
1497 | # Loader
1498 | "CheckpointLoaderSimpleWithSwitch": "Load Checkpoint with Switch",
1499 | }
1500 |
--------------------------------------------------------------------------------
/py/nodes_torch_compile.py:
--------------------------------------------------------------------------------
1 | import torch
2 |
3 | class TorchCompileModelAdvanced:
4 | @classmethod
5 | def INPUT_TYPES(s):
6 | return {"required": { "model": ("MODEL",),
7 | "backend": (["inductor", "cudagraphs"],),
8 | "compile_mode": (["reduce-overhead", "default", "max-autotune"],),
9 | "enabled": ("BOOLEAN", {"default": False}),
10 | }}
11 | RETURN_TYPES = ("MODEL",)
12 | FUNCTION = "patch"
13 |
14 | CATEGORY = "utils"
15 | EXPERIMENTAL = True
16 |
17 | def patch(self, model, backend, compile_mode, enabled):
18 | if not enabled:
19 | return (model, )
20 | m = model.clone()
21 | m.add_object_patch("diffusion_model", torch.compile(model=m.get_model_object("diffusion_model"), mode=compile_mode, backend=backend))
22 | return (m, )
23 |
24 | NODE_CLASS_MAPPINGS = {
25 | "TorchCompileModelAdvanced": TorchCompileModelAdvanced,
26 | }
27 | NODE_DISPLAY_NAME_MAPPINGS = {
28 | "TorchCompileModelAdvanced": "Torch Compile Model Advanced"
29 | }
30 |
--------------------------------------------------------------------------------
/py/nodes_video.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import numpy as np
3 | import logging
4 | logger = logging.getLogger(__name__)
5 |
6 | class FrameAdjuster:
7 | def __init__(self):
8 | pass
9 |
10 | @classmethod
11 | def INPUT_TYPES(cls):
12 | return {"required":{
13 | "images": ("IMAGE",),
14 | "duration": ("FLOAT", {"default": 5.0, "min": 0.1, "max": 60.0, "step": 0.1}),
15 | "fps": ("FLOAT", {"default": 24.0, "min": 1.0, "max": 120.0, "step": 1.0}),
16 | "remove_frames": ("INT", {"default": 0, "min": 0, "max": 20, "step": 1}),
17 | },
18 | "optional": {
19 | "extend_tail_frame_if_adjust":("BOOLEAN", {"default": False})
20 | }
21 | }
22 |
23 | RETURN_TYPES = ("IMAGE", "INT", "FLOAT")
24 | RETURN_NAMES = ("images", "frame_count", "fps")
25 | FUNCTION = "adjust_frames"
26 | CATEGORY = "utils"
27 |
28 | def adjust_frames(self, images: torch.Tensor, duration: float, fps: float, remove_frames: int, extend_tail_frame_if_adjust: bool = False):
29 | if remove_frames > 0:
30 | images = images[:-remove_frames]
31 | batch_size = images.shape[0]
32 | min_frames = int(fps * duration)
33 | max_frames = int(fps * (duration + 1)) - 1
34 |
35 | # 如果在目标范围内,直接返回
36 | if min_frames <= batch_size <= max_frames:
37 | return (images, len(images), fps)
38 |
39 | # 如果帧数过少,需要插值
40 | if batch_size < min_frames:
41 | target_frames = min_frames + 5 if not extend_tail_frame_if_adjust else min_frames
42 |
43 | # 如果帧数过多,需要减帧
44 | if batch_size > max_frames:
45 | target_frames = max_frames - 5
46 | indices = np.linspace(0, batch_size - 1, target_frames)
47 | indices = np.floor(indices).astype(int)
48 | new_images = images[indices]
49 |
50 |
51 | if extend_tail_frame_if_adjust:
52 | unique, counts = np.unique(indices, return_counts=True)
53 | repeat_count = np.min(counts[:-1]) if len(counts) > 1 else int(fps // 2)
54 | logger.info(f"repeat_count: {repeat_count}, unique: {unique}, counts: {counts}")
55 | new_images = torch.cat([new_images, images[-1].unsqueeze(0).repeat(repeat_count, 1, 1, 1)], dim=0)
56 | return (new_images, len(new_images), fps)
57 |
58 | class ImageTransitionLeftToRight:
59 | def __init__(self):
60 | pass
61 |
62 | @classmethod
63 | def INPUT_TYPES(cls):
64 | return {"required":{
65 | "before_image": ("IMAGE",),
66 | "after_image": ("IMAGE",),
67 | "duration": ("FLOAT", {"default": 5.0, "min": 0.1, "max": 60.0, "step": 0.1}),
68 | "fps": ("FLOAT", {"default": 24.0, "min": 1.0, "max": 120.0, "step": 1.0}),
69 | },
70 | }
71 |
72 | RETURN_TYPES = ("IMAGE", "FLOAT", "FLOAT")
73 | RETURN_NAMES = ("images", "duration", "fps")
74 | FUNCTION = "create_transition"
75 | CATEGORY = "utils"
76 |
77 | def create_transition(self, before_image: torch.Tensor, after_image: torch.Tensor, duration: float, fps: float):
78 |
79 | # 确保输入是单张图片,如果是批次则取第一张
80 | if len(before_image.shape) == 4 and before_image.shape[0] > 1:
81 | before_image = before_image[0:1]
82 | if len(after_image.shape) == 4 and after_image.shape[0] > 1:
83 | after_image = after_image[0:1]
84 |
85 | # 获取目标尺寸(前图的尺寸)
86 | _, target_width = before_image.shape[1:3]
87 |
88 |
89 | adjusted_after = self.check_and_resizee_size(before_image, after_image)
90 |
91 | # 计算总帧数
92 | total_frames = int(duration * fps)
93 |
94 | # 创建过渡帧
95 | frames = []
96 |
97 | for i in range(total_frames):
98 | # 计算当前过渡位置 (0.0 到 1.0)
99 | progress = i / (total_frames - 1) if total_frames > 1 else 1.0
100 |
101 | # 计算过渡线的x坐标
102 | transition_x = int(target_width * progress)
103 |
104 | # 创建新帧
105 | new_frame = torch.zeros_like(before_image)
106 |
107 | # 从左到右过渡:左侧显示后图,右侧显示前图
108 | # 先填充整个前图
109 | new_frame[0] = before_image[0]
110 |
111 | # 然后在左侧填充后图(覆盖前图)
112 | if transition_x > 0:
113 | new_frame[0, :, :transition_x,:] = adjusted_after[0, :, :transition_x, :]
114 |
115 | frames.append(new_frame)
116 |
117 | # 合并所有帧
118 | result = torch.cat(frames, dim=0)
119 |
120 | return (result, duration, fps)
121 |
122 | def check_and_resizee_size(self, before_image, after_image):
123 | # 获取目标尺寸(前图的尺寸)
124 | before_height, before_width = before_image.shape[1:3]
125 |
126 | # 获取后图的原始尺寸
127 | after_height, after_width = after_image.shape[1:3]
128 |
129 | # 如果尺寸相同,直接返回
130 | if before_height == after_height and before_width == after_width:
131 | return after_image
132 |
133 |
134 | # 计算宽高比
135 | before_ratio = before_width / before_height
136 | after_ratio = after_width / after_height
137 |
138 |
139 | logger.debug(f"before_image: {before_image.shape}, after_image: {after_image.shape}")
140 |
141 | # 调整后图尺寸,填充满目标尺寸(可能需要裁剪)
142 | if after_ratio > before_ratio:
143 | # 后图更宽,需要裁剪宽度
144 | new_width = int(after_height * before_ratio)
145 |
146 | # 计算裁剪的起始位置(居中裁剪)
147 | start_x = (after_width - new_width) // 2
148 | logger.debug(f"start_x: {start_x}, new_width: {new_width}")
149 | # 裁剪后图
150 | cropped_after = after_image[:, :, start_x:start_x+new_width, :]
151 | else:
152 | # 后图更高,需要裁剪高度
153 | new_height = int(after_width / before_ratio)
154 |
155 | # 计算裁剪的起始位置(居中裁剪)
156 | start_y = (after_height - new_height) // 2
157 | logger.debug(f"start_y: {start_y}, new_height: {new_height}")
158 | # 裁剪后图
159 | cropped_after = after_image[:, start_y:start_y+new_height, :, :]
160 | logger.debug(f"cropped_after: {cropped_after.shape}")
161 | # 缩放到目标尺寸
162 | adjusted_after = torch.nn.functional.interpolate(
163 | cropped_after.movedim(-1, 1),
164 | size=(before_height, before_width),
165 | mode='bicubic',
166 | align_corners=False
167 | ).movedim(1, -1).clamp(0.0, 1.0)
168 |
169 | return adjusted_after
170 |
171 | NODE_CLASS_MAPPINGS = {
172 | "FrameAdjuster": FrameAdjuster,
173 | "ImageTransitionLeftToRight": ImageTransitionLeftToRight
174 | }
175 |
176 | NODE_DISPLAY_NAME_MAPPINGS = {
177 | "FrameAdjuster": "Frame Adjuster",
178 | "ImageTransitionLeftToRight": "Image Transition Left to Right"
179 | }
180 |
--------------------------------------------------------------------------------
/py/utils.py:
--------------------------------------------------------------------------------
1 | import cv2
2 | import numpy as np
3 | from typing import Union, List
4 | import torch
5 | from PIL import Image, ImageDraw
6 |
7 | def tensor2np(tensor: torch.Tensor):
8 | if len(tensor.shape) == 3: # Single image
9 | return np.clip(255.0 * tensor.cpu().numpy(), 0, 255).astype(np.uint8)
10 | else: # Batch of images
11 | return [np.clip(255.0 * t.cpu().numpy(), 0, 255).astype(np.uint8) for t in tensor]
12 |
13 | def np2tensor(img_np: Union[np.ndarray, List[np.ndarray]]) -> torch.Tensor:
14 | if isinstance(img_np, list):
15 | if len(img_np) == 0:
16 | return torch.tensor([])
17 | return torch.cat([np2tensor(img) for img in img_np], dim=0)
18 | return torch.from_numpy(img_np.astype(np.float32) / 255.0).unsqueeze(0)
19 |
20 | def tensor2pil(t_image: torch.Tensor) -> Image:
21 | return Image.fromarray(np.clip(255.0 * t_image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8))
22 |
23 | def pil2tensor(image:Image) -> torch.Tensor:
24 | return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
25 |
26 | def image2mask(image:Image) -> torch.Tensor:
27 | if image.mode == 'L':
28 | return torch.tensor([pil2tensor(image)[0, :, :].tolist()])
29 | else:
30 | image = image.convert('RGB').split()[0]
31 | return torch.tensor([pil2tensor(image)[0, :, :].tolist()])
32 |
33 | def mask2image(mask:torch.Tensor) -> Image:
34 | masks = tensor2np(mask)
35 | for m in masks:
36 | _mask = Image.fromarray(m).convert("L")
37 | _image = Image.new("RGBA", _mask.size, color='white')
38 | _image = Image.composite(
39 | _image, Image.new("RGBA", _mask.size, color='black'), _mask)
40 | return _image
41 |
42 | def pil2cv2(pil_img:Image) -> np.array:
43 | np_img_array = np.asarray(pil_img)
44 | return cv2.cvtColor(np_img_array, cv2.COLOR_RGB2BGR)
45 |
46 | def min_bounding_rect(image:Image) -> tuple:
47 | cv2_image = pil2cv2(image)
48 | gray = cv2.cvtColor(cv2_image, cv2.COLOR_BGR2GRAY)
49 | ret, thresh = cv2.threshold(gray, 127, 255, 0)
50 | contours, _ = cv2.findContours(thresh, 1, 2)
51 | x, y, width, height = 0, 0, 0, 0
52 | area = 0
53 | for contour in contours:
54 | _x, _y, _w, _h = cv2.boundingRect(contour)
55 | _area = _w * _h
56 | if _area > area:
57 | area = _area
58 | x, y, width, height = _x, _y, _w, _h
59 | return (x, y, width, height)
60 |
61 | def mask_area(image:Image) -> tuple:
62 | cv2_image = pil2cv2(image.convert('RGBA'))
63 | gray = cv2.cvtColor(cv2_image, cv2.COLOR_BGR2GRAY)
64 | _, thresh = cv2.threshold(gray, 127, 255, 0)
65 | locs = np.where(thresh == 255)
66 | x1 = np.min(locs[1]) if len(locs[1]) > 0 else 0
67 | x2 = np.max(locs[1]) if len(locs[1]) > 0 else image.width
68 | y1 = np.min(locs[0]) if len(locs[0]) > 0 else 0
69 | y2 = np.max(locs[0]) if len(locs[0]) > 0 else image.height
70 | x1, y1, x2, y2 = min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2)
71 | return (x1, y1, x2 - x1, y2 - y1)
72 |
73 | def draw_rect(image:Image, x:int, y:int, width:int, height:int, line_color:str, line_width:int,
74 | box_color:str=None) -> Image:
75 | draw = ImageDraw.Draw(image)
76 | draw.rectangle((x, y, x + width, y + height), fill=box_color, outline=line_color, width=line_width, )
77 | return image
78 |
79 | # Tensor to cv2
80 | def tensor2cv(image):
81 | image_np = np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)
82 | return cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [project]
2 | name = "comfyui-utils-nodes"
3 | description = "Nodes:LoadImageWithSwitch, ImageBatchOneOrMore, ModifyTextGender, GenderControlOutput, ImageCompositeMaskedWithSwitch, ImageCompositeMaskedOneByOne, ColorCorrectOfUtils, SplitMask, MaskFastGrow, CheckpointLoaderSimpleWithSwitch, ImageResizeTo8x, MatchImageRatioToPreset, UpscaleImageWithModelIfNeed, MaskFromFaceModel, MaskCoverFourCorners, DetectorForNSFW, DeepfaceAnalyzeFaceAttributes etc."
4 | version = "1.3.1"
5 | license = { file = "LICENSE" }
6 | dependencies = []
7 |
8 | [project.urls]
9 | Repository = "https://github.com/zhangp365/ComfyUI-utils-nodes"
10 | # Used by Comfy Registry https://comfyregistry.org
11 |
12 | [tool.comfy]
13 | PublisherId = "zhangp365"
14 | DisplayName = "ComfyUI-utils-nodes"
15 | Icon = ""
16 |
--------------------------------------------------------------------------------
/r_deepface/demography.py:
--------------------------------------------------------------------------------
1 | # built-in dependencies
2 | from typing import Any, Dict, List, Union
3 |
4 | # 3rd party dependencies
5 | import numpy as np
6 | from tqdm import tqdm
7 |
8 |
9 | def analyze(
10 | img_path: Union[str, np.ndarray],
11 | actions: Union[tuple, list] = ("emotion", "age", "gender", "race"),
12 | enforce_detection: bool = True,
13 | detector_backend: str = "opencv",
14 | align: bool = True,
15 | expand_percentage: int = 0,
16 | silent: bool = False,
17 | anti_spoofing: bool = False,
18 | is_single_face_image: bool = False,
19 | ) -> List[Dict[str, Any]]:
20 | # project dependencies
21 | from deepface.modules import modeling, detection, preprocessing
22 | from deepface.models.demography import Gender, Race, Emotion
23 | """
24 | Analyze facial attributes such as age, gender, emotion, and race in the provided image.
25 |
26 | Args:
27 | img_path (str or np.ndarray): The exact path to the image, a numpy array in BGR format,
28 | or a base64 encoded image. If the source image contains multiple faces, the result will
29 | include information for each detected face.
30 |
31 | actions (tuple): Attributes to analyze. The default is ('age', 'gender', 'emotion', 'race').
32 | You can exclude some of these attributes from the analysis if needed.
33 |
34 | enforce_detection (boolean): If no face is detected in an image, raise an exception.
35 | Set to False to avoid the exception for low-resolution images (default is True).
36 |
37 | detector_backend (string): face detector backend. Options: 'opencv', 'retinaface',
38 | 'mtcnn', 'ssd', 'dlib', 'mediapipe', 'yolov8', 'centerface' or 'skip'
39 | (default is opencv).
40 |
41 | distance_metric (string): Metric for measuring similarity. Options: 'cosine',
42 | 'euclidean', 'euclidean_l2' (default is cosine).
43 |
44 | align (boolean): Perform alignment based on the eye positions (default is True).
45 |
46 | expand_percentage (int): expand detected facial area with a percentage (default is 0).
47 |
48 | silent (boolean): Suppress or allow some log messages for a quieter analysis process
49 | (default is False).
50 |
51 | anti_spoofing (boolean): Flag to enable anti spoofing (default is False).
52 |
53 | Returns:
54 | results (List[Dict[str, Any]]): A list of dictionaries, where each dictionary represents
55 | the analysis results for a detected face.
56 |
57 | Each dictionary in the list contains the following keys:
58 |
59 | - 'region' (dict): Represents the rectangular region of the detected face in the image.
60 | - 'x': x-coordinate of the top-left corner of the face.
61 | - 'y': y-coordinate of the top-left corner of the face.
62 | - 'w': Width of the detected face region.
63 | - 'h': Height of the detected face region.
64 |
65 | - 'age' (float): Estimated age of the detected face.
66 |
67 | - 'face_confidence' (float): Confidence score for the detected face.
68 | Indicates the reliability of the face detection.
69 |
70 | - 'dominant_gender' (str): The dominant gender in the detected face.
71 | Either "Man" or "Woman."
72 |
73 | - 'gender' (dict): Confidence scores for each gender category.
74 | - 'Man': Confidence score for the male gender.
75 | - 'Woman': Confidence score for the female gender.
76 |
77 | - 'dominant_emotion' (str): The dominant emotion in the detected face.
78 | Possible values include "sad," "angry," "surprise," "fear," "happy,"
79 | "disgust," and "neutral."
80 |
81 | - 'emotion' (dict): Confidence scores for each emotion category.
82 | - 'sad': Confidence score for sadness.
83 | - 'angry': Confidence score for anger.
84 | - 'surprise': Confidence score for surprise.
85 | - 'fear': Confidence score for fear.
86 | - 'happy': Confidence score for happiness.
87 | - 'disgust': Confidence score for disgust.
88 | - 'neutral': Confidence score for neutrality.
89 |
90 | - 'dominant_race' (str): The dominant race in the detected face.
91 | Possible values include "indian," "asian," "latino hispanic,"
92 | "black," "middle eastern," and "white."
93 |
94 | - 'race' (dict): Confidence scores for each race category.
95 | - 'indian': Confidence score for Indian ethnicity.
96 | - 'asian': Confidence score for Asian ethnicity.
97 | - 'latino hispanic': Confidence score for Latino/Hispanic ethnicity.
98 | - 'black': Confidence score for Black ethnicity.
99 | - 'middle eastern': Confidence score for Middle Eastern ethnicity.
100 | - 'white': Confidence score for White ethnicity.
101 | """
102 |
103 | # if actions is passed as tuple with single item, interestingly it becomes str here
104 | if isinstance(actions, str):
105 | actions = (actions,)
106 |
107 | # check if actions is not an iterable or empty.
108 | if not hasattr(actions, "__getitem__") or not actions:
109 | raise ValueError("`actions` must be a list of strings.")
110 |
111 | actions = list(actions)
112 |
113 | # For each action, check if it is valid
114 | for action in actions:
115 | if action not in ("emotion", "age", "gender", "race"):
116 | raise ValueError(
117 | f"Invalid action passed ({repr(action)})). "
118 | "Valid actions are `emotion`, `age`, `gender`, `race`."
119 | )
120 | # ---------------------------------
121 | resp_objects = []
122 | if is_single_face_image:
123 | img_obj = {"face": img_path,"facial_area":{},"confidence":1}
124 | img_objs = [img_obj]
125 | else:
126 | img_objs = detection.extract_faces(
127 | img_path=img_path,
128 | detector_backend=detector_backend,
129 | enforce_detection=enforce_detection,
130 | grayscale=False,
131 | align=align,
132 | expand_percentage=expand_percentage,
133 | anti_spoofing=anti_spoofing,
134 | )
135 |
136 | for img_obj in img_objs:
137 | if anti_spoofing is True and img_obj.get("is_real", True) is False:
138 | raise ValueError("Spoof detected in the given image.")
139 |
140 | img_content = img_obj["face"]
141 | img_region = img_obj["facial_area"]
142 | img_confidence = img_obj["confidence"]
143 | if img_content.shape[0] == 0 or img_content.shape[1] == 0:
144 | continue
145 |
146 | # rgb to bgr
147 | img_content = img_content[:, :, ::-1]
148 |
149 | # resize input image
150 | img_content = preprocessing.resize_image(img=img_content, target_size=(224, 224))
151 |
152 | obj = {}
153 | # facial attribute analysis
154 | pbar = tqdm(
155 | range(0, len(actions)),
156 | desc="Finding actions",
157 | disable=silent if len(actions) > 1 else True,
158 | )
159 | for index in pbar:
160 | action = actions[index]
161 | pbar.set_description(f"Action: {action}")
162 |
163 | if action == "emotion":
164 | emotion_predictions = modeling.build_model(
165 | task="facial_attribute", model_name="Emotion"
166 | ).predict(img_content)
167 | sum_of_predictions = emotion_predictions.sum()
168 |
169 | obj["emotion"] = {}
170 | for i, emotion_label in enumerate(Emotion.labels):
171 | emotion_prediction = 100 * emotion_predictions[i] / sum_of_predictions
172 | obj["emotion"][emotion_label] = emotion_prediction
173 |
174 | obj["dominant_emotion"] = Emotion.labels[np.argmax(emotion_predictions)]
175 |
176 | elif action == "age":
177 | apparent_age = modeling.build_model(
178 | task="facial_attribute", model_name="Age"
179 | ).predict(img_content)
180 | # int cast is for exception - object of type 'float32' is not JSON serializable
181 | obj["age"] = int(apparent_age)
182 |
183 | elif action == "gender":
184 | gender_predictions = modeling.build_model(
185 | task="facial_attribute", model_name="Gender"
186 | ).predict(img_content)
187 | obj["gender"] = {}
188 | for i, gender_label in enumerate(Gender.labels):
189 | gender_prediction = 100 * gender_predictions[i]
190 | obj["gender"][gender_label] = gender_prediction
191 |
192 | obj["dominant_gender"] = Gender.labels[np.argmax(gender_predictions)]
193 |
194 | elif action == "race":
195 | race_predictions = modeling.build_model(
196 | task="facial_attribute", model_name="Race"
197 | ).predict(img_content)
198 | sum_of_predictions = race_predictions.sum()
199 |
200 | obj["race"] = {}
201 | for i, race_label in enumerate(Race.labels):
202 | race_prediction = 100 * race_predictions[i] / sum_of_predictions
203 | obj["race"][race_label] = race_prediction
204 |
205 | obj["dominant_race"] = Race.labels[np.argmax(race_predictions)]
206 |
207 | # -----------------------------
208 | # mention facial areas
209 | obj["region"] = img_region
210 | # include image confidence
211 | obj["face_confidence"] = img_confidence
212 |
213 | resp_objects.append(obj)
214 |
215 | return resp_objects
216 |
--------------------------------------------------------------------------------
/r_nudenet/320n.onnx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zhangp365/ComfyUI-utils-nodes/62a5ce76735e1a380e140932dc974e0220a65c43/r_nudenet/320n.onnx
--------------------------------------------------------------------------------
/r_nudenet/nudenet.py:
--------------------------------------------------------------------------------
1 | import os
2 | import _io
3 | import math
4 | import cv2
5 | import numpy as np
6 | import onnxruntime
7 | from onnxruntime.capi import _pybind_state as C
8 |
9 | '''
10 | This original file comes from https://github.com/notAI-tech/NudeNet
11 | '''
12 |
13 | __labels = [
14 | "FEMALE_GENITALIA_COVERED",
15 | "FACE_FEMALE",
16 | "BUTTOCKS_EXPOSED",
17 | "FEMALE_BREAST_EXPOSED",
18 | "FEMALE_GENITALIA_EXPOSED",
19 | "MALE_BREAST_EXPOSED",
20 | "ANUS_EXPOSED",
21 | "FEET_EXPOSED",
22 | "BELLY_COVERED",
23 | "FEET_COVERED",
24 | "ARMPITS_COVERED",
25 | "ARMPITS_EXPOSED",
26 | "FACE_MALE",
27 | "BELLY_EXPOSED",
28 | "MALE_GENITALIA_EXPOSED",
29 | "ANUS_COVERED",
30 | "FEMALE_BREAST_COVERED",
31 | "BUTTOCKS_COVERED",
32 | ]
33 |
34 |
35 | def _read_image(image_path, target_size=320):
36 | if isinstance(image_path, str):
37 | mat = cv2.imread(image_path)
38 | elif isinstance(image_path, np.ndarray):
39 | mat = image_path
40 | elif isinstance(image_path, bytes):
41 | mat = cv2.imdecode(np.frombuffer(image_path, np.uint8), -1)
42 | elif isinstance(image_path, _io.BufferedReader):
43 | mat = cv2.imdecode(np.frombuffer(image_path.read(), np.uint8), -1)
44 | else:
45 | raise ValueError(
46 | "please make sure the image_path is str or np.ndarray or bytes"
47 | )
48 |
49 | image_original_width, image_original_height = mat.shape[1], mat.shape[0]
50 |
51 | mat_c3 = cv2.cvtColor(mat, cv2.COLOR_RGBA2BGR)
52 |
53 | max_size = max(mat_c3.shape[:2]) # get max size from width and height
54 | x_pad = max_size - mat_c3.shape[1] # set xPadding
55 | x_ratio = max_size / mat_c3.shape[1] # set xRatio
56 | y_pad = max_size - mat_c3.shape[0] # set yPadding
57 | y_ratio = max_size / mat_c3.shape[0] # set yRatio
58 |
59 | mat_pad = cv2.copyMakeBorder(mat_c3, 0, y_pad, 0, x_pad, cv2.BORDER_CONSTANT)
60 |
61 | input_blob = cv2.dnn.blobFromImage(
62 | mat_pad,
63 | 1 / 255.0, # normalize
64 | (target_size, target_size), # resize to model input size
65 | (0, 0, 0), # mean subtraction
66 | swapRB=True, # swap red and blue channels
67 | crop=False, # don't crop
68 | )
69 |
70 | return (
71 | input_blob,
72 | x_ratio,
73 | y_ratio,
74 | x_pad,
75 | y_pad,
76 | image_original_width,
77 | image_original_height,
78 | )
79 |
80 |
81 | def _postprocess(
82 | output,
83 | x_pad,
84 | y_pad,
85 | x_ratio,
86 | y_ratio,
87 | image_original_width,
88 | image_original_height,
89 | model_width,
90 | model_height,
91 | ):
92 | outputs = np.transpose(np.squeeze(output[0]))
93 | rows = outputs.shape[0]
94 | boxes = []
95 | scores = []
96 | class_ids = []
97 |
98 | for i in range(rows):
99 | classes_scores = outputs[i][4:]
100 | max_score = np.amax(classes_scores)
101 |
102 | if max_score >= 0.2:
103 | class_id = np.argmax(classes_scores)
104 | x, y, w, h = outputs[i][0:4]
105 |
106 | # Convert from center coordinates to top-left corner coordinates
107 | x = x - w / 2
108 | y = y - h / 2
109 |
110 | # Scale coordinates to original image size
111 | x = x * (image_original_width + x_pad) / model_width
112 | y = y * (image_original_height + y_pad) / model_height
113 | w = w * (image_original_width + x_pad) / model_width
114 | h = h * (image_original_height + y_pad) / model_height
115 |
116 | # Remove padding
117 | x = x
118 | y = y
119 |
120 | # Clip coordinates to image boundaries
121 | x = max(0, min(x, image_original_width))
122 | y = max(0, min(y, image_original_height))
123 | w = min(w, image_original_width - x)
124 | h = min(h, image_original_height - y)
125 |
126 | class_ids.append(class_id)
127 | scores.append(max_score)
128 | boxes.append([x, y, w, h])
129 |
130 | indices = cv2.dnn.NMSBoxes(boxes, scores, 0.25, 0.45)
131 |
132 | detections = []
133 | for i in indices:
134 | box = boxes[i]
135 | score = scores[i]
136 | class_id = class_ids[i]
137 |
138 | x, y, w, h = box
139 | detections.append(
140 | {
141 | "class": __labels[class_id],
142 | "score": float(score),
143 | "box": [int(x), int(y), int(w), int(h)],
144 | }
145 | )
146 |
147 | return detections
148 |
149 |
150 | class NudeDetector:
151 | def __init__(self, model_path=None, providers=None, inference_resolution=320):
152 | self.onnx_session = onnxruntime.InferenceSession(
153 | os.path.join(os.path.dirname(__file__), "320n.onnx")
154 | if not model_path
155 | else model_path,
156 | providers=providers,
157 | )
158 | model_inputs = self.onnx_session.get_inputs()
159 |
160 | self.input_width = inference_resolution
161 | self.input_height = inference_resolution
162 | self.input_name = model_inputs[0].name
163 |
164 | def detect(self, image_path):
165 | (
166 | preprocessed_image,
167 | x_ratio,
168 | y_ratio,
169 | x_pad,
170 | y_pad,
171 | image_original_width,
172 | image_original_height,
173 | ) = _read_image(image_path, self.input_width)
174 | outputs = self.onnx_session.run(None, {self.input_name: preprocessed_image})
175 | detections = _postprocess(
176 | outputs,
177 | x_pad,
178 | y_pad,
179 | x_ratio,
180 | y_ratio,
181 | image_original_width,
182 | image_original_height,
183 | self.input_width,
184 | self.input_height,
185 | )
186 |
187 | return detections
188 |
189 | def detect_batch(self, image_paths, batch_size=4):
190 | """
191 | Perform batch detection on a list of images.
192 |
193 | Args:
194 | image_paths (List[Union[str, np.ndarray]]): List of image paths or numpy arrays.
195 | batch_size (int): Number of images to process in each batch.
196 |
197 | Returns:
198 | List of detection results for each image.
199 | """
200 | all_detections = []
201 |
202 | for i in range(0, len(image_paths), batch_size):
203 | batch = image_paths[i : i + batch_size]
204 | batch_inputs = []
205 | batch_metadata = []
206 |
207 | for image_path in batch:
208 | (
209 | preprocessed_image,
210 | x_ratio,
211 | y_ratio,
212 | x_pad,
213 | y_pad,
214 | image_original_width,
215 | image_original_height,
216 | ) = _read_image(image_path, self.input_width)
217 | batch_inputs.append(preprocessed_image)
218 | batch_metadata.append(
219 | (
220 | x_ratio,
221 | y_ratio,
222 | x_pad,
223 | y_pad,
224 | image_original_width,
225 | image_original_height,
226 | )
227 | )
228 |
229 | # Stack the preprocessed images into a single numpy array
230 | batch_input = np.vstack(batch_inputs)
231 |
232 | # Run inference on the batch
233 | outputs = self.onnx_session.run(None, {self.input_name: batch_input})
234 |
235 | # Process the outputs for each image in the batch
236 | for j, metadata in enumerate(batch_metadata):
237 | (
238 | x_ratio,
239 | y_ratio,
240 | x_pad,
241 | y_pad,
242 | image_original_width,
243 | image_original_height,
244 | ) = metadata
245 | detections = _postprocess(
246 | [outputs[0][j : j + 1]], # Select the output for this image
247 | x_pad,
248 | y_pad,
249 | x_ratio,
250 | y_ratio,
251 | image_original_width,
252 | image_original_height,
253 | self.input_width,
254 | self.input_height,
255 | )
256 | all_detections.append(detections)
257 |
258 | return all_detections
259 |
260 | def censor(self, image_path, classes=[], output_path=None):
261 | detections = self.detect(image_path)
262 | if classes:
263 | detections = [
264 | detection for detection in detections if detection["class"] in classes
265 | ]
266 |
267 | img = cv2.imread(image_path)
268 |
269 | for detection in detections:
270 | box = detection["box"]
271 | x, y, w, h = box[0], box[1], box[2], box[3]
272 | # change these pixels to pure black
273 | img[y : y + h, x : x + w] = (0, 0, 0)
274 |
275 | if not output_path:
276 | image_path, ext = os.path.splitext(image_path)
277 | output_path = f"{image_path}_censored{ext}"
278 |
279 | cv2.imwrite(output_path, img)
280 |
281 | return output_path
282 |
283 |
284 | if __name__ == "__main__":
285 | detector = NudeDetector()
286 | # detections = detector.detect("/Users/praneeth.bedapudi/Desktop/cory.jpeg")
287 | print(
288 | detector.detect_batch(
289 | [
290 | "/Users/praneeth.bedapudi/Desktop/d.jpg",
291 | "/Users/praneeth.bedapudi/Desktop/a.jpeg",
292 | ]
293 | )[0]
294 | )
295 | print(detector.detect_batch(["/Users/praneeth.bedapudi/Desktop/d.jpg"])[0])
296 |
297 | print(
298 | detector.detect_batch(
299 | [
300 | "/Users/praneeth.bedapudi/Desktop/d.jpg",
301 | "/Users/praneeth.bedapudi/Desktop/a.jpeg",
302 | ]
303 | )[1]
304 | )
305 | print(detector.detect_batch(["/Users/praneeth.bedapudi/Desktop/a.jpeg"])[0])
306 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 |
2 |
3 | #non essential dependencies:
4 | # DetectorForNSFW
5 | onnxruntime>=1.19.2
6 |
7 | # DeepfaceAnalyzeFaceAttributes
8 | deepface==0.0.93
9 | ultralytics
10 | tf-keras==2.17.0
11 |
12 | # Gemini_prompt_enhance nod
13 | google-generativeai>0.4.1
14 |
15 | # volcano outpainting node
16 | volcengine
--------------------------------------------------------------------------------
/web/js/previewText.js:
--------------------------------------------------------------------------------
1 | import { app } from "../../../scripts/app.js";
2 | import { ComfyWidgets } from "../../../scripts/widgets.js";
3 |
4 | // this frontend code is from https://github.com/pythongosssss/ComfyUI-Custom-Scripts/blob/main/web/js/showText.js thanks to pysssss
5 | // Displays input text on a node
6 |
7 | // TODO: This should need to be so complicated. Refactor at some point.
8 |
9 | app.registerExtension({
10 | name: "TextPreview",
11 | async beforeRegisterNodeDef(nodeType, nodeData, app) {
12 | if (nodeData.name === "TextPreview") {
13 | function populate(text) {
14 | if (this.widgets) {
15 | // On older frontend versions there is a hidden converted-widget
16 | const isConvertedWidget = +!!this.inputs?.[0].widget;
17 | for (let i = isConvertedWidget; i < this.widgets.length; i++) {
18 | this.widgets[i].onRemove?.();
19 | }
20 | this.widgets.length = isConvertedWidget;
21 | }
22 |
23 | const v = [...text];
24 | if (!v[0]) {
25 | v.shift();
26 | }
27 | for (let list of v) {
28 | // Force list to be an array, not sure why sometimes it is/isn't
29 | if (!(list instanceof Array)) list = [list];
30 | for (const l of list) {
31 | const w = ComfyWidgets["STRING"](this, "text_" + this.widgets?.length ?? 0, ["STRING", { multiline: true }], app).widget;
32 | w.inputEl.readOnly = true;
33 | w.inputEl.style.opacity = 0.6;
34 | w.value = l;
35 | }
36 | }
37 |
38 | requestAnimationFrame(() => {
39 | const sz = this.computeSize();
40 | if (sz[0] < this.size[0]) {
41 | sz[0] = this.size[0];
42 | }
43 | if (sz[1] < this.size[1]) {
44 | sz[1] = this.size[1];
45 | }
46 | this.onResize?.(sz);
47 | app.graph.setDirtyCanvas(true, false);
48 | });
49 | }
50 |
51 | // When the node is executed we will be sent the input text, display this in the widget
52 | const onExecuted = nodeType.prototype.onExecuted;
53 | nodeType.prototype.onExecuted = function (message) {
54 | onExecuted?.apply(this, arguments);
55 | populate.call(this, message.text);
56 | };
57 |
58 | const VALUES = Symbol();
59 | const configure = nodeType.prototype.configure;
60 | nodeType.prototype.configure = function () {
61 | // Store unmodified widget values as they get removed on configure by new frontend
62 | this[VALUES] = arguments[0]?.widgets_values;
63 | return configure?.apply(this, arguments);
64 | };
65 |
66 | const onConfigure = nodeType.prototype.onConfigure;
67 | nodeType.prototype.onConfigure = function () {
68 | onConfigure?.apply(this, arguments);
69 | const widgets_values = this[VALUES];
70 | if (widgets_values?.length) {
71 | // In newer frontend there seems to be a delay in creating the initial widget
72 | requestAnimationFrame(() => {
73 | populate.call(this, widgets_values.slice(+(widgets_values.length > 1 && this.inputs?.[0].widget)));
74 | });
75 | }
76 | };
77 | }
78 | },
79 | });
--------------------------------------------------------------------------------