DegMaTsu commited on
Commit
2610ebb
·
verified ·
1 Parent(s): 33eb54c

Upload 302 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. custom_nodes/comfyui-reactor-node/.gitignore +5 -0
  2. custom_nodes/comfyui-reactor-node/LICENSE +235 -0
  3. custom_nodes/comfyui-reactor-node/README.md +499 -0
  4. custom_nodes/comfyui-reactor-node/README_RU.md +508 -0
  5. custom_nodes/comfyui-reactor-node/__init__.py +39 -0
  6. custom_nodes/comfyui-reactor-node/install.bat +37 -0
  7. custom_nodes/comfyui-reactor-node/install.py +104 -0
  8. custom_nodes/comfyui-reactor-node/modules/__init__.py +0 -0
  9. custom_nodes/comfyui-reactor-node/modules/__pycache__/__init__.cpython-312.pyc +0 -0
  10. custom_nodes/comfyui-reactor-node/modules/__pycache__/processing.cpython-312.pyc +0 -0
  11. custom_nodes/comfyui-reactor-node/modules/__pycache__/scripts.cpython-312.pyc +0 -0
  12. custom_nodes/comfyui-reactor-node/modules/__pycache__/scripts_postprocessing.cpython-312.pyc +0 -0
  13. custom_nodes/comfyui-reactor-node/modules/__pycache__/shared.cpython-312.pyc +0 -0
  14. custom_nodes/comfyui-reactor-node/modules/images.py +0 -0
  15. custom_nodes/comfyui-reactor-node/modules/processing.py +13 -0
  16. custom_nodes/comfyui-reactor-node/modules/scripts.py +13 -0
  17. custom_nodes/comfyui-reactor-node/modules/scripts_postprocessing.py +0 -0
  18. custom_nodes/comfyui-reactor-node/modules/shared.py +19 -0
  19. custom_nodes/comfyui-reactor-node/nodes.py +1581 -0
  20. custom_nodes/comfyui-reactor-node/r_basicsr/__init__.py +12 -0
  21. custom_nodes/comfyui-reactor-node/r_basicsr/__pycache__/__init__.cpython-312.pyc +0 -0
  22. custom_nodes/comfyui-reactor-node/r_basicsr/__pycache__/test.cpython-312.pyc +0 -0
  23. custom_nodes/comfyui-reactor-node/r_basicsr/__pycache__/train.cpython-312.pyc +0 -0
  24. custom_nodes/comfyui-reactor-node/r_basicsr/__pycache__/version.cpython-312.pyc +0 -0
  25. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__init__.py +25 -0
  26. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/__init__.cpython-312.pyc +0 -0
  27. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/arch_util.cpython-312.pyc +0 -0
  28. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/basicvsr_arch.cpython-312.pyc +0 -0
  29. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/basicvsrpp_arch.cpython-312.pyc +0 -0
  30. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/dfdnet_arch.cpython-312.pyc +0 -0
  31. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/dfdnet_util.cpython-312.pyc +0 -0
  32. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/discriminator_arch.cpython-312.pyc +0 -0
  33. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/duf_arch.cpython-312.pyc +0 -0
  34. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/ecbsr_arch.cpython-312.pyc +0 -0
  35. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/edsr_arch.cpython-312.pyc +0 -0
  36. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/edvr_arch.cpython-312.pyc +0 -0
  37. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/hifacegan_arch.cpython-312.pyc +0 -0
  38. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/hifacegan_util.cpython-312.pyc +0 -0
  39. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/rcan_arch.cpython-312.pyc +0 -0
  40. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/ridnet_arch.cpython-312.pyc +0 -0
  41. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/rrdbnet_arch.cpython-312.pyc +0 -0
  42. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/spynet_arch.cpython-312.pyc +0 -0
  43. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/srresnet_arch.cpython-312.pyc +0 -0
  44. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/srvgg_arch.cpython-312.pyc +0 -0
  45. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/stylegan2_arch.cpython-312.pyc +0 -0
  46. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/swinir_arch.cpython-312.pyc +0 -0
  47. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/tof_arch.cpython-312.pyc +0 -0
  48. custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/vgg_arch.cpython-312.pyc +0 -0
  49. custom_nodes/comfyui-reactor-node/r_basicsr/archs/arch_util.py +322 -0
  50. custom_nodes/comfyui-reactor-node/r_basicsr/archs/basicvsr_arch.py +336 -0
custom_nodes/comfyui-reactor-node/.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ __pycache__/
2
+ *$py.class
3
+ .vscode/
4
+ example
5
+ input
custom_nodes/comfyui-reactor-node/LICENSE ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5
+
6
+ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
11
+
12
+ The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
13
+
14
+ When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
15
+
16
+ Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
17
+
18
+ A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
19
+
20
+ The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
21
+
22
+ An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
23
+
24
+ The precise terms and conditions for copying, distribution and modification follow.
25
+
26
+ TERMS AND CONDITIONS
27
+
28
+ 0. Definitions.
29
+
30
+ "This License" refers to version 3 of the GNU Affero General Public License.
31
+
32
+ "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
33
+
34
+ "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
35
+
36
+ To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
37
+
38
+ A "covered work" means either the unmodified Program or a work based on the Program.
39
+
40
+ To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
41
+
42
+ To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
43
+
44
+ An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
45
+
46
+ 1. Source Code.
47
+ The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
48
+
49
+ A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
50
+
51
+ The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
52
+
53
+ The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
54
+ subprograms and other parts of the work.
55
+
56
+ The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
57
+
58
+ The Corresponding Source for a work in source code form is that same work.
59
+
60
+ 2. Basic Permissions.
61
+ All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
62
+
63
+ You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
64
+
65
+ Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
66
+
67
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
68
+ No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
69
+
70
+ When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
71
+
72
+ 4. Conveying Verbatim Copies.
73
+ You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
74
+
75
+ You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
76
+
77
+ 5. Conveying Modified Source Versions.
78
+ You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
79
+
80
+ a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
81
+
82
+ b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
83
+
84
+ c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
85
+
86
+ d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
87
+
88
+ A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
89
+
90
+ 6. Conveying Non-Source Forms.
91
+ You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
92
+
93
+ a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
94
+
95
+ b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
96
+
97
+ c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
98
+
99
+ d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
100
+
101
+ e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
102
+
103
+ A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
104
+
105
+ A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
106
+
107
+ "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
108
+
109
+ If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
110
+
111
+ The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
112
+
113
+ Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
114
+
115
+ 7. Additional Terms.
116
+ "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
117
+
118
+ When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
119
+
120
+ Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
121
+
122
+ a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
123
+
124
+ b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
125
+
126
+ c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
127
+
128
+ d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
129
+
130
+ e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
131
+
132
+ f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
133
+
134
+ All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
135
+
136
+ If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
137
+
138
+ Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
139
+
140
+ 8. Termination.
141
+
142
+ You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
143
+
144
+ However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
145
+
146
+ Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
147
+
148
+ Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
149
+
150
+ 9. Acceptance Not Required for Having Copies.
151
+
152
+ You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
153
+
154
+ 10. Automatic Licensing of Downstream Recipients.
155
+
156
+ Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
157
+
158
+ An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
159
+
160
+ You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
161
+
162
+ 11. Patents.
163
+
164
+ A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
165
+
166
+ A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
167
+
168
+ Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
169
+
170
+ In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
171
+
172
+ If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
173
+ license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
174
+
175
+ If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
176
+
177
+ A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
178
+
179
+ Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
180
+
181
+ 12. No Surrender of Others' Freedom.
182
+
183
+ If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
184
+ not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
185
+
186
+ 13. Remote Network Interaction; Use with the GNU General Public License.
187
+
188
+ Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
189
+
190
+ Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
191
+
192
+ 14. Revised Versions of this License.
193
+
194
+ The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
195
+
196
+ Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
197
+
198
+ If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
199
+
200
+ Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
201
+
202
+ 15. Disclaimer of Warranty.
203
+
204
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
205
+
206
+ 16. Limitation of Liability.
207
+
208
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
209
+
210
+ 17. Interpretation of Sections 15 and 16.
211
+
212
+ If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
213
+
214
+ END OF TERMS AND CONDITIONS
215
+
216
+ How to Apply These Terms to Your New Programs
217
+
218
+ If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
219
+
220
+ To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
221
+
222
+ comfyui-reactor-node
223
+ Copyright (C) 2025 Gourieff
224
+
225
+ This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
226
+
227
+ This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
228
+
229
+ You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
230
+
231
+ Also add information on how to contact you by electronic and paper mail.
232
+
233
+ If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
234
+
235
+ You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
custom_nodes/comfyui-reactor-node/README.md ADDED
@@ -0,0 +1,499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/ReActor_logo_NEW_EN.png?raw=true" alt="logo" width="180px"/>
4
+
5
+ ![Version](https://img.shields.io/badge/node_version-0.6.1_beta2-green?style=for-the-badge&labelColor=darkgreen)
6
+
7
+ <!--<sup>
8
+ <font color=brightred>
9
+
10
+ ## !!! [Important Update](#latestupdate) !!!<br>Don't forget to add the Node again in existing workflows
11
+
12
+ </font>
13
+ </sup>-->
14
+
15
+ <a href="https://boosty.to/artgourieff" target="_blank">
16
+ <img src="https://lovemet.ru/img/boosty.jpg" width="108" alt="Support Me on Boosty"/>
17
+ <br>
18
+ <sup>
19
+ Support This Project
20
+ </sup>
21
+ </a>
22
+
23
+ <a href="https://t.me/reactor_faceswap" target="_blank"><img src="https://img.shields.io/badge/Official_Channel-2CA5E0?style=for-the-badge&logo=Telegram&logoColor=white&labelColor=blue"></img></a>
24
+
25
+ <hr>
26
+
27
+ ![Last commit](https://img.shields.io/gitea/last-commit/Gourieff/comfyui-reactor-node/main?gitea_url=https%3A%2F%2Fcodeberg.org&cacheSeconds=0)
28
+ [![Opened issues](https://img.shields.io/gitea/issues/open/Gourieff/comfyui-reactor-node?gitea_url=https%3A%2F%2Fcodeberg.org&color=red&cacheSeconds=0)](https://codeberg.org/Gourieff/comfyui-reactor-node/issues)
29
+ [![Closed issues](https://img.shields.io/gitea/issues/closed/Gourieff/comfyui-reactor-node?gitea_url=https%3A%2F%2Fcodeberg.org&color=green&cacheSeconds=0)](https://codeberg.org/Gourieff/comfyui-reactor-node/issues?q=&state=closed)
30
+
31
+ English | [Русский](README_RU.md)
32
+
33
+ # ReActor Node for ComfyUI
34
+
35
+ </div>
36
+
37
+ ### The Fast and Simple Face Swap Extension Node for ComfyUI, based on [blocked ReActor](https://github.com/Gourieff/comfyui-reactor-node) (RIP Bro)
38
+
39
+ > This Node goes without NSFW filter (uncensored, use it on your own [responsibility](#disclaimer))
40
+
41
+ <div align="center">
42
+
43
+ ---
44
+ [**What's new**](#latestupdate) | [**Installation**](#installation) | [**Usage**](#usage) | [**Troubleshooting**](#troubleshooting) | [**Updating**](#updating) | [**Disclaimer**](#disclaimer) | [**Credits**](#credits) | [**Note!**](#note)
45
+
46
+ ---
47
+
48
+ </div>
49
+
50
+ <div align="center">
51
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/uploads/demo.gif?raw=true" alt="demo" width="75%"/>
52
+ </div>
53
+
54
+ <a name="latestupdate">
55
+
56
+ ## What's new in the latest update
57
+
58
+ ### 0.6.1 <sub><sup>BETA1, BETA2</sup></sub>
59
+
60
+ - MaskHelper node 2x speed up - not perfect yet but 1.5x-2x faster then before
61
+ - ComfyUI native ProgressBar for different steps
62
+ - ORIGINAL_IMAGE output for main nodes
63
+ - Different fixes and improvements
64
+
65
+ ### 0.6.0
66
+
67
+ - New Node `ReActorSetWeight` - you can now set the strength of face swap for `source_image` or `face_model` from 0% to 100% (in 12.5% step)
68
+
69
+ <center>
70
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.6.0-whatsnew-01.jpg?raw=true" alt="0.6.0-whatsnew-01" width="100%"/>
71
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.6.0-whatsnew-02.jpg?raw=true" alt="0.6.0-whatsnew-02" width="100%"/>
72
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.6.0-alpha1-01.gif?raw=true" alt="0.6.0-whatsnew-03" width="540px"/>
73
+ </center>
74
+
75
+ <details>
76
+ <summary><a>Previous versions</a></summary>
77
+
78
+ ### 0.5.2
79
+
80
+ - ReSwapper models support. Although Inswapper still has the best similarity, but ReSwapper is evolving - thanks @somanchiu https://github.com/somanchiu/ReSwapper for the ReSwapper models and the ReSwapper project! This is a good step for the Community in the Inswapper's alternative creation!
81
+
82
+ <div align="center">
83
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.2-whatsnew-03.jpg?raw=true" alt="0.5.2-whatsnew-03" width="75%"/>
84
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.2-whatsnew-04.jpg?raw=true" alt="0.5.2-whatsnew-04" width="75%"/>
85
+ </div>
86
+
87
+ You can download ReSwapper models here:
88
+ https://huggingface.co/datasets/Gourieff/ReActor/tree/main/models<br>
89
+ Just put them into the "models/reswapper" directory.
90
+
91
+ - New node "Unload ReActor Models" - is useful for complex WFs when you need to free some VRAM utilized by ReActor
92
+
93
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.2-whatsnew-01.jpg?raw=true" alt="0.5.2-whatsnew-01" width="100%"/>
94
+
95
+ - Support of ORT CoreML and ROCM EPs, just install onnxruntime version you need
96
+ - Install script improvements to install latest versions of ORT-GPU
97
+
98
+ <center>
99
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.2-whatsnew-02.jpg?raw=true" alt="0.5.2-whatsnew-02" width="50%"/>
100
+ </center>
101
+
102
+ - Fixes and improvements
103
+
104
+ ### 0.5.1
105
+
106
+ - Support of GPEN 1024/2048 restoration models (available in the HF dataset https://huggingface.co/datasets/Gourieff/ReActor/tree/main/models/facerestore_models)
107
+ - ReActorFaceBoost Node - an attempt to improve the quality of swapped faces. The idea is to restore and scale the swapped face (according to the `face_size` parameter of the restoration model) BEFORE pasting it to the target image (via inswapper algorithms)
108
+
109
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.1-whatsnew-01.jpg?raw=true" alt="0.5.1-whatsnew-01" width="100%"/>
110
+
111
+ [Full size demo preview](https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.1-whatsnew-02.png)
112
+
113
+ - Sorting facemodels alphabetically
114
+ - A lot of fixes and improvements
115
+
116
+ ### 0.5.0 <sub><sup>BETA4</sup></sub>
117
+
118
+ - Spandrel lib support for GFPGAN
119
+
120
+ ### 0.5.0 <sub><sup>BETA3</sup></sub>
121
+
122
+ - Fixes: "RAM issue", "No detection" for MaskingHelper
123
+
124
+ ### 0.5.0 <sub><sup>BETA2</sup></sub>
125
+
126
+ - You can now build a blended face model from a batch of face models you already have, just add the "Make Face Model Batch" node to your workflow and connect several models via "Load Face Model"
127
+ - Huge performance boost of the image analyzer's module! 10x speed up! Working with videos is now a pleasure!
128
+
129
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.0-whatsnew-05.png?raw=true" alt="0.5.0-whatsnew-05" width="100%"/>
130
+
131
+ ### 0.5.0 <sub><sup>BETA1</sup></sub>
132
+
133
+ - SWAPPED_FACE output for the Masking Helper Node
134
+ - FIX: Empty A-channel for Masking Helper IMAGE output (causing errors with some nodes) was removed
135
+
136
+ ### 0.5.0 <sub><sup>ALPHA1</sup></sub>
137
+
138
+ - ReActorBuildFaceModel Node got "face_model" output to provide a blended face model directly to the main Node:
139
+
140
+ Basic workflow [💾](https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/workflows/ReActor--Build-Blended-Face-Model--v2.json)
141
+
142
+ - Face Masking feature is available now, just add the "ReActorMaskHelper" Node to the workflow and connect it as shown below:
143
+
144
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.0-whatsnew-01.jpg?raw=true" alt="0.5.0-whatsnew-01" width="100%"/>
145
+
146
+ If you don't have the "face_yolov8m.pt" Ultralytics model - you can download it from the [Assets](https://huggingface.co/datasets/Gourieff/ReActor/blob/main/models/detection/bbox/face_yolov8m.pt) and put it into the "ComfyUI\models\ultralytics\bbox" directory
147
+ <br>
148
+ As well as ["sam_vit_b_01ec64.pth"](https://huggingface.co/datasets/Gourieff/ReActor/blob/main/models/sams/sam_vit_b_01ec64.pth) model - download (if you don't have it) and put it into the "ComfyUI\models\sams" directory;
149
+
150
+ Use this Node to gain the best results of the face swapping process:
151
+
152
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.0-whatsnew-02.jpg?raw=true" alt="0.5.0-whatsnew-02" width="100%"/>
153
+
154
+ - ReActorImageDublicator Node - rather useful for those who create videos, it helps to duplicate one image to several frames to use them with VAE Encoder (e.g. live avatars):
155
+
156
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.0-whatsnew-03.jpg?raw=true" alt="0.5.0-whatsnew-03" width="100%"/>
157
+
158
+ - ReActorFaceSwapOpt (a simplified version of the Main Node) + ReActorOptions Nodes to set some additional options such as (new) "input/source faces separate order". Yes! You can now set the order of faces in the index in the way you want ("large to small" goes by default)!
159
+
160
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.0-whatsnew-04.jpg?raw=true" alt="0.5.0-whatsnew-04" width="100%"/>
161
+
162
+ - Little speed boost when analyzing target images (unfortunately it is still quite slow in compare to swapping and restoring...)
163
+
164
+ ### 0.4.2
165
+
166
+ - GPEN-BFR-512 and RestoreFormer_Plus_Plus face restoration models support
167
+
168
+ You can download models here: https://huggingface.co/datasets/Gourieff/ReActor/tree/main/models/facerestore_models
169
+ <br>Put them into the `ComfyUI\models\facerestore_models` folder
170
+
171
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.4.2-whatsnew-04.jpg?raw=true" alt="0.4.2-whatsnew-04" width="100%"/>
172
+
173
+ - Due to popular demand - you can now blend several images with persons into one face model file and use it with "Load Face Model" Node or in SD WebUI as well;
174
+
175
+ Experiment and create new faces or blend faces of one person to gain better accuracy and likeness!
176
+
177
+ Just add the ImpactPack's "Make Image Batch" Node as the input to the ReActor's one and load images you want to blend into one model:
178
+
179
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.4.2-whatsnew-01.jpg?raw=true" alt="0.4.2-whatsnew-01" width="100%"/>
180
+
181
+ Result example (the new face was created from 4 faces of different actresses):
182
+
183
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.4.2-whatsnew-02.jpg?raw=true" alt="0.4.2-whatsnew-02" width="75%"/>
184
+
185
+ Basic workflow [💾](https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/workflows/ReActor--Build-Blended-Face-Model--v1.json)
186
+
187
+ ### 0.4.1
188
+
189
+ - CUDA 12 Support - don't forget to run (Windows) `install.bat` or (Linux/MacOS) `install.py` for ComfyUI's Python enclosure or try to install ORT-GPU for CU12 manually (https://onnxruntime.ai/docs/install/#install-onnx-runtime-gpu-cuda-12x)
190
+ - Issue https://github.com/Gourieff/comfyui-reactor-node/issues/173 fix
191
+
192
+ - Separate Node for the Face Restoration postprocessing, can be found inside ReActor's menu (RestoreFace Node)
193
+ - (Windows) Installation can be done for Python from the System's PATH
194
+ - Different fixes and improvements
195
+
196
+ - Face Restore Visibility and CodeFormer Weight (Fidelity) options are now available! Don't forget to reload the Node in your existing workflow
197
+
198
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.4.1-whatsnew-01.jpg?raw=true" alt="0.4.1-whatsnew-01" width="100%"/>
199
+
200
+ ### 0.4.0
201
+
202
+ - Input "input_image" goes first now, it gives a correct bypass and also it is right to have the main input first;
203
+ - You can now save face models as "safetensors" files (`ComfyUI\models\reactor\faces`) and load them into ReActor implementing different scenarios and keeping super lightweight face models of the faces you use:
204
+
205
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.4.0-whatsnew-01.jpg?raw=true" alt="0.4.0-whatsnew-01" width="100%"/>
206
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.4.0-whatsnew-02.jpg?raw=true" alt="0.4.0-whatsnew-02" width="100%"/>
207
+
208
+ - Ability to build and save face models directly from an image:
209
+
210
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.4.0-whatsnew-03.jpg?raw=true" alt="0.4.0-whatsnew-03" width="50%"/>
211
+
212
+ - Both the inputs are optional, just connect one of them according to your workflow; if both is connected - `image` has a priority.
213
+ - Different fixes making this extension better.
214
+
215
+ Thanks to everyone who finds bugs, suggests new features and supports this project!
216
+
217
+ </details>
218
+
219
+ ## Installation
220
+
221
+ <details>
222
+ <summary>SD WebUI: <a href="https://github.com/AUTOMATIC1111/stable-diffusion-webui/">AUTOMATIC1111</a> or <a href="https://github.com/vladmandic/automatic">SD.Next</a></summary>
223
+
224
+ 1. Close (stop) your SD-WebUI/Comfy Server if it's running
225
+ 2. (For Windows Users):
226
+ - Install [Visual Studio 2022](https://visualstudio.microsoft.com/downloads/) (Community version - you need this step to build Insightface)
227
+ - OR only [VS C++ Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) and select "Desktop Development with C++" under "Workloads -> Desktop & Mobile"
228
+ - OR if you don't want to install VS or VS C++ BT - follow [this steps (sec. I)](#insightfacebuild)
229
+ 3. Go to the `extensions\sd-webui-comfyui\ComfyUI\custom_nodes`
230
+ 4. Open Console or Terminal and run `git clone https://codeberg.org/Gourieff/comfyui-reactor-node`
231
+ 5. Go to the SD WebUI root folder, open Console or Terminal and run (Windows users)`.\venv\Scripts\activate` or (Linux/MacOS)`venv/bin/activate`
232
+ 6. `python -m pip install -U pip`
233
+ 7. `cd extensions\sd-webui-comfyui\ComfyUI\custom_nodes\comfyui-reactor-node`
234
+ 8. `python install.py`
235
+ 9. Please, wait until the installation process will be finished
236
+ 10. (From the version 0.3.0) Download additional facerestorers models from the link below and put them into the `extensions\sd-webui-comfyui\ComfyUI\models\facerestore_models` directory:<br>
237
+ https://huggingface.co/datasets/Gourieff/ReActor/tree/main/models/facerestore_models
238
+ 11. Run SD WebUI and check console for the message that ReActor Node is running:
239
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/uploads/console_status_running.jpg?raw=true" alt="console_status_running" width="759"/>
240
+
241
+ 12. Go to the ComfyUI tab and find there ReActor Node inside the menu `ReActor` or by using a search:
242
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/uploads/webui-demo.png?raw=true" alt="webui-demo" width="100%"/>
243
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/uploads/search-demo.png?raw=true" alt="webui-demo" width="1043"/>
244
+
245
+ </details>
246
+
247
+ <details>
248
+ <summary>Standalone (Portable) <a href="https://github.com/comfyanonymous/ComfyUI">ComfyUI</a> for Windows</summary>
249
+
250
+ 1. Do the following:
251
+ - Install [Visual Studio 2022](https://visualstudio.microsoft.com/downloads/) (Community version - you need this step to build Insightface)
252
+ - OR only [VS C++ Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) and select "Desktop Development with C++" under "Workloads -> Desktop & Mobile"
253
+ - OR if you don't want to install VS or VS C++ BT - follow [this steps (sec. I)](#insightfacebuild)
254
+ 2. Choose between two options:
255
+ - (ComfyUI Manager) Open ComfyUI Manager, click "Install Custom Nodes", type "ReActor" in the "Search" field and then click "Install". After ComfyUI will complete the process - please restart the Server.
256
+ - (Manually) Go to `ComfyUI\custom_nodes`, open Console and run `git clone https://codeberg.org/Gourieff/comfyui-reactor-node`
257
+ 3. Go to `ComfyUI\custom_nodes\comfyui-reactor-node` and run `install.bat`
258
+ 4. If you don't have the "face_yolov8m.pt" Ultralytics model - you can download it from the [Assets](https://huggingface.co/datasets/Gourieff/ReActor/blob/main/models/detection/bbox/face_yolov8m.pt) and put it into the "ComfyUI\models\ultralytics\bbox" directory
259
+ <br>
260
+ As well as one or both of "Sams" models from [here](https://huggingface.co/datasets/Gourieff/ReActor/tree/main/models/sams) - download (if you don't have them) and put into the "ComfyUI\models\sams" directory
261
+ 5. Run ComfyUI and find there ReActor Nodes inside the menu `ReActor` or by using a search
262
+
263
+ </details>
264
+
265
+ ## Usage
266
+
267
+ You can find ReActor Nodes inside the menu `ReActor` or by using a search (just type "ReActor" in the search field)
268
+
269
+ List of Nodes:
270
+ - ••• Main Nodes •••
271
+ - ReActorFaceSwap (Main Node)
272
+ - ReActorFaceSwapOpt (Main Node with the additional Options input)
273
+ - ReActorOptions (Options for ReActorFaceSwapOpt)
274
+ - ReActorFaceBoost (Face Booster Node)
275
+ - ReActorMaskHelper (Masking Helper)
276
+ - ••• Operations with Face Models •••
277
+ - ReActorSaveFaceModel (Save Face Model)
278
+ - ReActorLoadFaceModel (Load Face Model)
279
+ - ReActorBuildFaceModel (Build Blended Face Model)
280
+ - ReActorMakeFaceModelBatch (Make Face Model Batch)
281
+ - ••• Additional Nodes •••
282
+ - ReActorRestoreFace (Face Restoration)
283
+ - ReActorImageDublicator (Dublicate one Image to Images List)
284
+ - ImageRGBA2RGB (Convert RGBA to RGB)
285
+
286
+ Connect all required slots and run the query.
287
+
288
+ ### Main Node Inputs
289
+
290
+ - `input_image` - is an image to be processed (target image, analog of "target image" in the SD WebUI extension);
291
+ - Supported Nodes: "Load Image", "Load Video" or any other nodes providing images as an output;
292
+ - `source_image` - is an image with a face or faces to swap in the `input_image` (source image, analog of "source image" in the SD WebUI extension);
293
+ - Supported Nodes: "Load Image" or any other nodes providing images as an output;
294
+ - `face_model` - is the input for the "Load Face Model" Node or another ReActor node to provide a face model file (face embedding) you created earlier via the "Save Face Model" Node;
295
+ - Supported Nodes: "Load Face Model", "Build Blended Face Model";
296
+
297
+ ### Main Node Outputs
298
+
299
+ - `IMAGE` - is an output with the resulted image;
300
+ - Supported Nodes: any nodes which have images as an input;
301
+ - `FACE_MODEL` - is an output providing a source face's model being built during the swapping process;
302
+ - Supported Nodes: "Save Face Model", "ReActor", "Make Face Model Batch";
303
+
304
+ ### Face Restoration
305
+
306
+ Since version 0.3.0 ReActor Node has a buil-in face restoration.<br>Just download the models you want (see [Installation](#installation) instruction) and select one of them to restore the resulting face(s) during the faceswap. It will enhance face details and make your result more accurate.
307
+
308
+ ### Face Indexes
309
+
310
+ By default ReActor detects faces in images from "large" to "small".<br>You can change this option by adding ReActorFaceSwapOpt node with ReActorOptions.
311
+
312
+ And if you need to specify faces, you can set indexes for source and input images.
313
+
314
+ Index of the first detected face is 0.
315
+
316
+ You can set indexes in the order you need.<br>
317
+ E.g.: 0,1,2 (for Source); 1,0,2 (for Input).<br>This means: the second Input face (index = 1) will be swapped by the first Source face (index = 0) and so on.
318
+
319
+ ### Genders
320
+
321
+ You can specify the gender to detect in images.<br>
322
+ ReActor will swap a face only if it meets the given condition.
323
+
324
+ ### Face Models
325
+
326
+ Since version 0.4.0 you can save face models as "safetensors" files (stored in `ComfyUI\models\reactor\faces`) and load them into ReActor implementing different scenarios and keeping super lightweight face models of the faces you use.
327
+
328
+ To make new models appear in the list of the "Load Face Model" Node - just refresh the page of your ComfyUI web application.<br>
329
+ (I recommend you to use ComfyUI Manager - otherwise you workflow can be lost after you refresh the page if you didn't save it before that).
330
+
331
+ ## Troubleshooting
332
+
333
+ <a name="insightfacebuild">
334
+
335
+ ### **I. (For Windows users) If you still cannot build Insightface for some reasons or just don't want to install Visual Studio or VS C++ Build Tools - do the following:**
336
+
337
+ 1. (ComfyUI Portable) From the root folder check the version of Python:<br>run CMD and type `python_embeded\python.exe -V`
338
+ 2. Download prebuilt Insightface package [for Python 3.10](https://github.com/Gourieff/Assets/raw/main/Insightface/insightface-0.7.3-cp310-cp310-win_amd64.whl) or [for Python 3.11](https://github.com/Gourieff/Assets/raw/main/Insightface/insightface-0.7.3-cp311-cp311-win_amd64.whl) (if in the previous step you see 3.11) or [for Python 3.12](https://github.com/Gourieff/Assets/raw/main/Insightface/insightface-0.7.3-cp312-cp312-win_amd64.whl) (if in the previous step you see 3.12) and put into the stable-diffusion-webui (A1111 or SD.Next) root folder (where you have "webui-user.bat" file) or into ComfyUI root folder if you use ComfyUI Portable
339
+ 3. From the root folder run:
340
+ - (SD WebUI) CMD and `.\venv\Scripts\activate`
341
+ - (ComfyUI Portable) run CMD
342
+ 4. Then update your PIP:
343
+ - (SD WebUI) `python -m pip install -U pip`
344
+ - (ComfyUI Portable) `python_embeded\python.exe -m pip install -U pip`
345
+ 5. Then install Insightface:
346
+ - (SD WebUI) `pip install insightface-0.7.3-cp310-cp310-win_amd64.whl` (for 3.10) or `pip install insightface-0.7.3-cp311-cp311-win_amd64.whl` (for 3.11) or `pip install insightface-0.7.3-cp312-cp312-win_amd64.whl` (for 3.12)
347
+ - (ComfyUI Portable) `python_embeded\python.exe -m pip install insightface-0.7.3-cp310-cp310-win_amd64.whl` (for 3.10) or `python_embeded\python.exe -m pip install insightface-0.7.3-cp311-cp311-win_amd64.whl` (for 3.11) or `python_embeded\python.exe -m pip install insightface-0.7.3-cp312-cp312-win_amd64.whl` (for 3.12)
348
+ 6. Enjoy!
349
+
350
+ ### **II. "AttributeError: 'NoneType' object has no attribute 'get'"**
351
+
352
+ This error may occur if there's smth wrong with the model file `inswapper_128.onnx`
353
+
354
+ Try to download it manually from [here](https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128.onnx)
355
+ and put it to the `ComfyUI\models\insightface` replacing existing one
356
+
357
+ ### **III. "reactor.execute() got an unexpected keyword argument 'reference_image'"**
358
+
359
+ This means that input points have been changed with the latest update<br>
360
+ Remove the current ReActor Node from your workflow and add it again
361
+
362
+ ### **IV. ControlNet Aux Node IMPORT failed error when using with ReActor Node**
363
+
364
+ 1. Close ComfyUI if it runs
365
+ 2. Go to the ComfyUI root folder, open CMD there and run:
366
+ - `python_embeded\python.exe -m pip uninstall -y opencv-python opencv-contrib-python opencv-python-headless`
367
+ - `python_embeded\python.exe -m pip install opencv-python==4.7.0.72`
368
+ 3. That's it!
369
+
370
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/uploads/reactor-w-controlnet.png?raw=true" alt="reactor+controlnet" />
371
+
372
+ ### **V. "ModuleNotFoundError: No module named 'basicsr'" or "subprocess-exited-with-error" during future-0.18.3 installation**
373
+
374
+ - Download https://github.com/Gourieff/Assets/raw/main/comfyui-reactor-node/future-0.18.3-py3-none-any.whl<br>
375
+ - Put it to ComfyUI root And run:
376
+
377
+ python_embeded\python.exe -m pip install future-0.18.3-py3-none-any.whl
378
+
379
+ - Then:
380
+
381
+ python_embeded\python.exe -m pip install basicsr
382
+
383
+ ### **VI. "fatal: fetch-pack: invalid index-pack output" when you try to `git clone` the repository"**
384
+
385
+ Try to clone with `--depth=1` (last commit only):
386
+
387
+ git clone --depth=1 https://codeberg.org/Gourieff/comfyui-reactor-node
388
+
389
+ Then retrieve the rest (if you need):
390
+
391
+ git fetch --unshallow
392
+
393
+ ## Updating
394
+
395
+ Just put .bat or .sh script from this [Repo](https://github.com/Gourieff/sd-webui-extensions-updater) to the `ComfyUI\custom_nodes` directory and run it when you need to check for updates
396
+
397
+ ### Disclaimer
398
+
399
+ This software is meant to be a productive contribution to the rapidly growing AI-generated media industry. It will help artists with tasks such as animating a custom character or using the character as a model for clothing etc.
400
+
401
+ The developers of this software are aware of its possible unethical applications and are committed to take preventative measures against them. We will continue to develop this project in the positive direction while adhering to law and ethics.
402
+
403
+ Users of this software are expected to use this software responsibly while abiding the local law. If face of a real person is being used, users are suggested to get consent from the concerned person and clearly mention that it is a deepfake when posting content online. **Developers and Contributors of this software are not responsible for actions of end-users.**
404
+
405
+ By using this extension you are agree not to create any content that:
406
+ - violates any laws;
407
+ - causes any harm to a person or persons;
408
+ - propagates (spreads) any information (both public or personal) or images (both public or personal) which could be meant for harm;
409
+ - spreads misinformation;
410
+ - targets vulnerable groups of people.
411
+
412
+ This software utilizes the pre-trained models `buffalo_l` and `inswapper_128.onnx`, which are provided by [InsightFace](https://github.com/deepinsight/insightface/). These models are included under the following conditions:
413
+
414
+ [From insighface license](https://github.com/deepinsight/insightface/tree/master/python-package): The InsightFace’s pre-trained models are available for non-commercial research purposes only. This includes both auto-downloading models and manually downloaded models.
415
+
416
+ Users of this software must strictly adhere to these conditions of use. The developers and maintainers of this software are not responsible for any misuse of InsightFace’s pre-trained models.
417
+
418
+ Please note that if you intend to use this software for any commercial purposes, you will need to train your own models or find models that can be used commercially.
419
+
420
+ ### Models Hashsum
421
+
422
+ #### Safe-to-use models have the following hash:
423
+
424
+ inswapper_128.onnx
425
+ ```
426
+ MD5:a3a155b90354160350efd66fed6b3d80
427
+ SHA256:e4a3f08c753cb72d04e10aa0f7dbe3deebbf39567d4ead6dce08e98aa49e16af
428
+ ```
429
+
430
+ 1k3d68.onnx
431
+
432
+ ```
433
+ MD5:6fb94fcdb0055e3638bf9158e6a108f4
434
+ SHA256:df5c06b8a0c12e422b2ed8947b8869faa4105387f199c477af038aa01f9a45cc
435
+ ```
436
+
437
+ 2d106det.onnx
438
+
439
+ ```
440
+ MD5:a3613ef9eb3662b4ef88eb90db1fcf26
441
+ SHA256:f001b856447c413801ef5c42091ed0cd516fcd21f2d6b79635b1e733a7109dbf
442
+ ```
443
+
444
+ det_10g.onnx
445
+
446
+ ```
447
+ MD5:4c10eef5c9e168357a16fdd580fa8371
448
+ SHA256:5838f7fe053675b1c7a08b633df49e7af5495cee0493c7dcf6697200b85b5b91
449
+ ```
450
+
451
+ genderage.onnx
452
+
453
+ ```
454
+ MD5:81c77ba87ab38163b0dec6b26f8e2af2
455
+ SHA256:4fde69b1c810857b88c64a335084f1c3fe8f01246c9a191b48c7bb756d6652fb
456
+ ```
457
+
458
+ w600k_r50.onnx
459
+
460
+ ```
461
+ MD5:80248d427976241cbd1343889ed132b3
462
+ SHA256:4c06341c33c2ca1f86781dab0e829f88ad5b64be9fba56e56bc9ebdefc619e43
463
+ ```
464
+
465
+ **Please check hashsums if you download these models from unverified (or untrusted) sources**
466
+
467
+ <a name="credits">
468
+
469
+ ## Thanks and Credits
470
+
471
+ <details>
472
+ <summary><a>Click to expand</a></summary>
473
+
474
+ <br>
475
+
476
+ |file|source|license|
477
+ |----|------|-------|
478
+ |[buffalo_l.zip](https://huggingface.co/datasets/Gourieff/ReActor/blob/main/models/buffalo_l.zip) | [DeepInsight](https://github.com/deepinsight/insightface) | ![license](https://img.shields.io/badge/license-non_commercial-red) |
479
+ | [codeformer-v0.1.0.pth](https://huggingface.co/datasets/Gourieff/ReActor/blob/main/models/facerestore_models/codeformer-v0.1.0.pth) | [sczhou](https://github.com/sczhou/CodeFormer) | ![license](https://img.shields.io/badge/license-non_commercial-red) |
480
+ | [GFPGANv1.3.pth](https://huggingface.co/datasets/Gourieff/ReActor/blob/main/models/facerestore_models/GFPGANv1.3.pth) | [TencentARC](https://github.com/TencentARC/GFPGAN) | ![license](https://img.shields.io/badge/license-Apache_2.0-green.svg) |
481
+ | [GFPGANv1.4.pth](https://huggingface.co/datasets/Gourieff/ReActor/blob/main/models/facerestore_models/GFPGANv1.4.pth) | [TencentARC](https://github.com/TencentARC/GFPGAN) | ![license](https://img.shields.io/badge/license-Apache_2.0-green.svg) |
482
+ | [inswapper_128.onnx](https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128.onnx) | [DeepInsight](https://github.com/deepinsight/insightface) | ![license](https://img.shields.io/badge/license-non_commercial-red) |
483
+ | [inswapper_128_fp16.onnx](https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128_fp16.onnx) | [Hillobar](https://github.com/Hillobar/Rope) | ![license](https://img.shields.io/badge/license-non_commercial-red) |
484
+
485
+ [BasicSR](https://github.com/XPixelGroup/BasicSR) - [@XPixelGroup](https://github.com/XPixelGroup) <br>
486
+ [facexlib](https://github.com/xinntao/facexlib) - [@xinntao](https://github.com/xinntao) <br>
487
+
488
+ [@s0md3v](https://github.com/s0md3v), [@henryruhs](https://github.com/henryruhs) - the original Roop App <br>
489
+ [@ssitu](https://github.com/ssitu) - the first version of [ComfyUI_roop](https://github.com/ssitu/ComfyUI_roop) extension
490
+
491
+ </details>
492
+
493
+ <a name="note">
494
+
495
+ ### Note!
496
+
497
+ **If you encounter any errors when you use ReActor Node - don't rush to open an issue, first try to remove current ReActor node in your workflow and add it again**
498
+
499
+ **ReActor Node gets updates from time to time, new functions appear and old node can work with errors or not work at all**
custom_nodes/comfyui-reactor-node/README_RU.md ADDED
@@ -0,0 +1,508 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/ReActor_logo_NEW_RU.png?raw=true" alt="logo" width="180px"/>
4
+
5
+ ![Version](https://img.shields.io/badge/версия_нода-0.6.1_beta2-green?style=for-the-badge&labelColor=darkgreen)
6
+
7
+ <!--<sup>
8
+ <font color=brightred>
9
+
10
+ ## !!! [Важные изменения](#latestupdate) !!!<br>Не забудьте добавить Нод заново в существующие воркфлоу
11
+
12
+ </font>
13
+ </sup>-->
14
+
15
+ <a href="https://boosty.to/artgourieff" target="_blank">
16
+ <img src="https://lovemet.ru/img/boosty.jpg" width="108" alt="Поддержать проект на Boosty"/>
17
+ <br>
18
+ <sup>
19
+ Поддержать проект
20
+ </sup>
21
+ </a>
22
+
23
+ <a href="https://t.me/reactor_faceswap" target="_blank"><img src="https://img.shields.io/badge/Official_Channel-2CA5E0?style=for-the-badge&logo=Telegram&logoColor=white&labelColor=blue"></img></a>
24
+
25
+ <hr>
26
+
27
+ ![Last commit](https://img.shields.io/gitea/last-commit/Gourieff/comfyui-reactor-node/main?gitea_url=https%3A%2F%2Fcodeberg.org&cacheSeconds=0)
28
+ [![Opened issues](https://img.shields.io/gitea/issues/open/Gourieff/comfyui-reactor-node?gitea_url=https%3A%2F%2Fcodeberg.org&color=red&cacheSeconds=0)](https://codeberg.org/Gourieff/comfyui-reactor-node/issues)
29
+ [![Closed issues](https://img.shields.io/gitea/issues/closed/Gourieff/comfyui-reactor-node?gitea_url=https%3A%2F%2Fcodeberg.org&color=green&cacheSeconds=0)](https://codeberg.org/Gourieff/comfyui-reactor-node/issues?q=&state=closed)
30
+
31
+ [English](README.md) | Русский
32
+
33
+ # ReActor Node для ComfyUI
34
+
35
+ </div>
36
+
37
+ ### Нод (node) для быстрой и простой замены лиц на любых изображениях для работы с ComfyUI, основан на [заблокированном РеАкторе](https://github.com/Gourieff/comfyui-reactor-node) (помянем)
38
+
39
+ > Данный Нод идёт без фильтра цензуры (18+, используйте под вашу собственную [ответственность](#disclaimer))
40
+
41
+ <div align="center">
42
+
43
+ ---
44
+ [**Что нового**](#latestupdate) | [**Установка**](#installation) | [**Использование**](#usage) | [**Устранение проблем**](#troubleshooting) | [**Обновление**](#updating) | [**Ответственность**](#disclaimer) | [**Благодарности**](#credits) | [**Заметка**](#note)
45
+
46
+ ---
47
+
48
+ </div>
49
+
50
+ <div align="center">
51
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/uploads/demo.gif?raw=true" alt="logo" width="100%"/>
52
+ </div>
53
+
54
+ <a name="latestupdate">
55
+
56
+ ## Что нового в последнем обновлении
57
+
58
+ ### 0.6.1 <sub><sup>BETA1, BETA2</sup></sub>
59
+
60
+ - MaskHelper нод теперь почти вдвое быстрее - пока не идеально, но лучше, чем было ранее
61
+ - Нативный ProgressBar ComfyUI для разных шагов
62
+ - Добавлен выход ORIGINAL_IMAGE для основных нодов
63
+ - Разные исправления и улучшения
64
+
65
+ ### 0.6.0
66
+
67
+ - Новый нод `ReActorSetWeight` - теперь можно установить силу замены лица для `source_image` или `face_model` от 0% до 100% (с шагом 12.5%)
68
+
69
+ <center>
70
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.6.0-whatsnew-01.jpg?raw=true" alt="0.6.0-whatsnew-01" width="100%"/>
71
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.6.0-whatsnew-02.jpg?raw=true" alt="0.6.0-whatsnew-02" width="100%"/>
72
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.6.0-alpha1-01.gif?raw=true" alt="0.6.0-whatsnew-03" width="540px"/>
73
+ </center>
74
+
75
+ <details>
76
+ <summary><a>Предыдущие версии</a></summary>
77
+
78
+ ### 0.5.2
79
+
80
+ - Поддержка моделей ReSwapper. Несмотря на то, что Inswapper по-прежнему даёт лучшее сходство, но ReSwapper развивается - спасибо @somanchiu https://github.com/somanchiu/ReSwapper за эти модели и проект ReSwapper! Это хороший шаг для Сообщества в создании альтернативы Инсваппера!
81
+
82
+ <div align="center">
83
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.2-whatsnew-03.jpg?raw=true" alt="0.5.2-whatsnew-03" width="75%"/>
84
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.2-whatsnew-04.jpg?raw=true" alt="0.5.2-whatsnew-04" width="75%"/>
85
+ </div>
86
+
87
+ Скачать модели ReSwapper можно отсюда:
88
+ https://huggingface.co/datasets/Gourieff/ReActor/tree/main/models<br>
89
+ Сохраните их в директорию "models/reswapper".
90
+
91
+ - Новый нод "Unload ReActor Models" - полезен для сложных воркфлоу, когда вам нужно освободить ОЗУ, занятую РеАктором
92
+
93
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.2-whatsnew-01.jpg?raw=true" alt="0.5.2-whatsnew-01" width="100%"/>
94
+
95
+ - Поддержка ORT CoreML and ROCM EPs, достаточно установить ту версию onnxruntime, которая соответствует вашему GPU
96
+ - Некоторые улучшения скрипта установки для поддержки последней версии ORT-GPU
97
+
98
+ <center>
99
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.2-whatsnew-02.jpg?raw=true" alt="0.5.2-whatsnew-02" width="50%"/>
100
+ </center>
101
+
102
+ - Исправления и улучшения
103
+
104
+ ### 0.5.1
105
+
106
+ - Поддержка моделей восстановления лиц GPEN 1024/2048 (доступны в датасете на HF https://huggingface.co/datasets/Gourieff/ReActor/tree/main/models/facerestore_models)
107
+ - Нод ReActorFaceBoost - попытка улучшить качество заменённых лиц. Идея состоит в том, чтобы восстановить и увеличить заменённое лицо (в соответствии с параметром `face_size` модели реставрации) ДО того, как лицо будет вставлено в целевое изображения (через алгоритмы инсваппера)
108
+
109
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.1-whatsnew-01.jpg?raw=true" alt="0.5.1-whatsnew-01" width="100%"/>
110
+
111
+ [Полноразмерное демо-превью](https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.1-whatsnew-02.png)
112
+
113
+ - Сортировка моделей лиц по алфавиту
114
+ - Множество исправлений и улучшений
115
+
116
+ ### 0.5.0 <sub><sup>BETA4</sup></sub>
117
+
118
+ - Поддержка библиотеки Spandrel при работе с GFPGAN
119
+
120
+ ### 0.5.0 <sub><sup>BETA3</sup></sub>
121
+
122
+ - Исправления: "RAM issue", "No detection" для MaskingHelper
123
+
124
+ ### 0.5.0 <sub><sup>BETA2</sup></sub>
125
+
126
+ - Появилась возможность строить смешанные модели лиц из пачки уже имеющихся моделей - добавьте для этого нод "Make Face Model Batch" в свой воркфлоу и загрузите несколько моделей через ноды "Load Face Model"
127
+ - Огромный буст производительности модуля анализа изображений! 10-кратный прирост скорости! Работа с видео теперь в удовольствие!
128
+
129
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.0-whatsnew-05.png?raw=true" alt="0.5.0-whatsnew-05" width="100%"/>
130
+
131
+ ### 0.5.0 <sub><sup>BETA1</sup></sub>
132
+
133
+ - Добавлен выход SWAPPED_FACE для нода Masking Helper
134
+ - FIX: Удалён пустой A-канал на выходе IMAGE нода Masking Helper (вызывавший ошибки с некоторым нодами)
135
+
136
+ ### 0.5.0 <sub><sup>ALPHA1</sup></sub>
137
+
138
+ - Нод ReActorBuildFaceModel получил выход "face_model" для отправки совмещенной модели лиц непосредственно в основной Нод:
139
+
140
+ Basic workflow [💾](https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/workflows/ReActor--Build-Blended-Face-Model--v2.json)
141
+
142
+ - Функции маски лица теперь доступна и в версии для Комфи, просто добавьте нод "ReActorMaskHelper" в воркфлоу и соедините узлы, как показано ниже:
143
+
144
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.0-whatsnew-01.jpg?raw=true" alt="0.5.0-whatsnew-01" width="100%"/>
145
+
146
+ Если модель "face_yolov8m.pt" у вас отсутствует - можете скачать её [отсюда](https://huggingface.co/datasets/Gourieff/ReActor/blob/main/models/detection/bbox/face_yolov8m.pt) и положить в папку "ComfyUI\models\ultralytics\bbox"
147
+ <br>
148
+ То же самое и с ["sam_vit_b_01ec64.pth"](https://huggingface.co/datasets/Gourieff/ReActor/blob/main/models/sams/sam_vit_b_01ec64.pth) - скачайте (если отсутствует) и положите в папку "ComfyUI\models\sams";
149
+
150
+ Данный нод поможет вам получить куда более аккуратный результат при замене лиц:
151
+
152
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.0-whatsnew-02.jpg?raw=true" alt="0.5.0-whatsnew-02" width="100%"/>
153
+
154
+ - Нод ReActorImageDublicator - полезен тем, кто создает видео, ��омогает продублировать одиночное изображение в несколько копий, чтобы использовать их, к примеру, с VAE энкодером:
155
+
156
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.0-whatsnew-03.jpg?raw=true" alt="0.5.0-whatsnew-03" width="100%"/>
157
+
158
+ - ReActorFaceSwapOpt (упрощенная версия основного нода) + нод ReActorOptions для установки дополнительных опций, как (новые) "отдельный порядок лиц для input/source". Да! Теперь можно установить любой порядок "чтения" индекса лиц на изображении, в т.ч. от большего к меньшему (по умолчанию)!
159
+
160
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.5.0-whatsnew-04.jpg?raw=true" alt="0.5.0-whatsnew-04" width="100%"/>
161
+
162
+ - Небольшое улучшение скорости анализа целевых изображений (input)
163
+
164
+ ### 0.4.2
165
+
166
+ - Добавлена поддержка GPEN-BFR-512 и RestoreFormer_Plus_Plus моделей восстановления лиц
167
+
168
+ Скачать можно здесь: https://huggingface.co/datasets/Gourieff/ReActor/tree/main/models/facerestore_models
169
+ <br>Добавьте модели в папку `ComfyUI\models\facerestore_models`
170
+
171
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.4.2-whatsnew-04.jpg?raw=true" alt="0.4.2-whatsnew-04" width="100%"/>
172
+
173
+ - По многочисленным просьбам появилась возможность строить смешанные модели лиц и в ComfyUI тоже и использовать их с нодом "Load Face Model" Node или в SD WebUI;
174
+
175
+ Экспериментируйте и создавайте новые лица или совмещайте разные лица нужного вам персонажа, чтобы добиться лучшей точности и схожести с оригиналом!
176
+
177
+ Достаточно добавить нод "Make Image Batch" (ImpactPack) на вход нового нода РеАктора и загрузить в пачку необходимые вам изображения для построения смешанной модели:
178
+
179
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.4.2-whatsnew-01.jpg?raw=true" alt="0.4.2-whatsnew-01" width="100%"/>
180
+
181
+ Пример результата (на основе лиц 4-х актрис создано новое лицо):
182
+
183
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.4.2-whatsnew-02.jpg?raw=true" alt="0.4.2-whatsnew-02" width="75%"/>
184
+
185
+ Базовый воркфлоу [💾](https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/workflows/ReActor--Build-Blended-Face-Model--v1.json)
186
+
187
+ ### 0.4.1
188
+
189
+ - Поддержка CUDA 12 - не забудьте запустить (Windows) `install.bat` или (Linux/MacOS) `install.py` для используемого Python окружения или попробуйте установить ORT-GPU для CU12 вручную (https://onnxruntime.ai/docs/install/#install-onnx-runtime-gpu-cuda-12x)
190
+ - Исправление Issue https://github.com/Gourieff/comfyui-reactor-node/issues/173
191
+
192
+ - Отдельный Нод для восстаноления лиц, располагается внутри меню ReActor (нод RestoreFace)
193
+ - (Windows) Установка зависимостей теперь может быть выполнена в Python из PATH ОС
194
+ - Разные исправления и улучшения
195
+
196
+ - Face Restore Visibility и CodeFormer Weight (Fidelity) теперь доступны; не забудьте заново добавить Нод в ваших существующих воркфлоу
197
+
198
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.4.1-whatsnew-01.jpg?raw=true" alt="0.4.1-whatsnew-01" width="100%"/>
199
+
200
+ ### 0.4.0
201
+
202
+ - Вход "input_image" теперь идёт первым, это даёт возможность корректного байпаса, а также это правильно с точки зрения расположения входов (главный вход - первый);
203
+ - Теперь можно сохранять модели лиц в качестве файлов "safetensors" (`ComfyUI\models\reactor\faces`) и загружать их в ReActor, реализуя разные сценарии использования, а также храня супер легкие модели лиц, которые вы чаще всего используете:
204
+
205
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.4.0-whatsnew-01.jpg?raw=true" alt="0.4.0-whatsnew-01" width="100%"/>
206
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.4.0-whatsnew-02.jpg?raw=true" alt="0.4.0-whatsnew-02" width="100%"/>
207
+
208
+ - Возможность сохранять модели лиц напрямую из изображения:
209
+
210
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/0.4.0-whatsnew-03.jpg?raw=true" alt="0.4.0-whatsnew-03" width="50%"/>
211
+
212
+ - Оба входа опциональны, присоедините один из них в соответствии с вашим воркфлоу; если присоеденены оба - вход `image` имеет приоритет.
213
+ - Различные исправления, делающие это расширение лучше.
214
+
215
+ Спасибо всем, кто находит ошибки, предлагает новые функции и поддерживает данный проект!
216
+
217
+ </details>
218
+
219
+ <a name="installation">
220
+
221
+ ## Установка
222
+
223
+ <details>
224
+ <summary>SD WebUI: <a href="https://github.com/AUTOMATIC1111/stable-diffusion-webui/">AUTOMATIC1111</a> или <a href="https://github.com/vladmandic/automatic">SD.Next</a></summary>
225
+
226
+ 1. Закройте (остановите) SD-WebUI Сервер, если запущен
227
+ 2. (Для пользователей Windows):
228
+ - Установите [Visual Studio 2022](https://visualstudio.microsoft.com/downloads/) (Например, версию Community - этот шаг нужен для правильной компиляции библиотеки Insightface)
229
+ - ИЛИ только [VS C++ Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/), выберите "Desktop Development with C++" в разделе "Workloads -> Desktop & Mobile"
230
+ - ИЛИ если же вы не хотите устанавливать что-либо из вышеуказанного - выполните [данные шаги (раздел. I)](#insightfacebuild)
231
+ 3. Перейдите в `extensions\sd-webui-comfyui\ComfyUI\custom_nodes`
232
+ 4. Откройте Консоль или Терминал и выполните `git clone https://codeberg.org/Gourieff/comfyui-reactor-node`
233
+ 5. Перейдите в корневую директорию SD WebUI, откройте Консоль или Терминал и выполните (для пользователей Windows)`.\venv\Scripts\activate` или (для пользователей Linux/MacOS)`venv/bin/activate`
234
+ 6. `python -m pip install -U pip`
235
+ 7. `cd extensions\sd-webui-comfyui\ComfyUI\custom_nodes\comfyui-reactor-node`
236
+ 8. `python install.py`
237
+ 9. Пожалуйста, дождитесь полного завершения установки
238
+ 10. (Начиная с версии 0.3.0) Скачайте дополнительные модели восстановления лиц (по ссылке ниже) и сохраните их в папку `extensions\sd-webui-comfyui\ComfyUI\models\facerestore_models`:<br>
239
+ https://huggingface.co/datasets/Gourieff/ReActor/tree/main/models/facerestore_models
240
+ 11. Запустите SD WebUI и проверьте консоль на сообщение, что ReActor Node работает:
241
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/uploads/console_status_running.jpg?raw=true" alt="console_status_running" width="759"/>
242
+
243
+ 12. Перейдите во вкладку ComfyUI и найдите там ReActor Node внутри меню `ReActor` или через поиск:
244
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/uploads/webui-demo.png?raw=true" alt="webui-demo" width="100%"/>
245
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/uploads/search-demo.png?raw=true" alt="webui-demo" width="1043"/>
246
+
247
+ </details>
248
+
249
+ <details>
250
+ <summary>Портативная версия <a href="https://github.com/comfyanonymous/ComfyUI">ComfyUI</a> для Windows</summary>
251
+
252
+ 1. Сделайте следующее:
253
+ - Установите [Visual Studio 2022](https://visualstudio.microsoft.com/downloads/) (Например, версию Community - этот шаг нужен для правильной компиляции библиотеки Insightface)
254
+ - ИЛИ только [VS C++ Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/), выберите "Desktop Development with C++" в разделе "Workloads -> Desktop & Mobile"
255
+ - ИЛИ если же вы не хотите устанавливать что-либо из вышеуказанного - выполните [данные шаги (раздел. I)](#insightfacebuild)
256
+ 2. Выберите из двух вариантов:
257
+ - (ComfyUI Manager) Откройте ComfyUI Manager, нажвите "Install Custom Nodes", введите "ReActor" в поле "Search" и далее нажмите "Install". После того, как ComfyUI завершит установку, перезагрузите сервер.
258
+ - (Вручную) Пер��йдите в `ComfyUI\custom_nodes`, откройте Консоль и выполните `git clone https://codeberg.org/Gourieff/comfyui-reactor-node`
259
+ 3. Перейдите `ComfyUI\custom_nodes\comfyui-reactor-node` и запустите `install.bat`, дождитесь окончания установки
260
+ 4. Если модель "face_yolov8m.pt" у вас отсутствует - можете скачать её [отсюда](https://huggingface.co/datasets/Gourieff/ReActor/blob/main/models/detection/bbox/face_yolov8m.pt) и положить в папку "ComfyUI\models\ultralytics\bbox"
261
+ <br>
262
+ То же самое и с "Sams" моделями, скачайте одну или обе [отсюда](https://huggingface.co/datasets/Gourieff/ReActor/tree/main/models/sams) - и положите в папку "ComfyUI\models\sams"
263
+ 5. Запустите ComfyUI и найдите ReActor Node внутри меню `ReActor` или через поиск
264
+
265
+ </details>
266
+
267
+ <a name="usage">
268
+
269
+ ## Использование
270
+
271
+ Вы можете найти ноды ReActor внутри меню `ReActor` или через поиск (достаточно ввести "ReActor" в поисковой строке)
272
+
273
+ Список нодов:
274
+ - ••• Main Nodes •••
275
+ - ReActorFaceSwap (Основной нод)
276
+ - ReActorFaceSwapOpt (Основной нод с доп. входом Options)
277
+ - ReActorOptions (Опции для ReActorFaceSwapOpt)
278
+ - ReActorFaceBoost (Нод Face Booster)
279
+ - ReActorMaskHelper (Masking Helper)
280
+ - ••• Operations with Face Models •••
281
+ - ReActorSaveFaceModel (Save Face Model)
282
+ - ReActorLoadFaceModel (Load Face Model)
283
+ - ReActorBuildFaceModel (Build Blended Face Model)
284
+ - ReActorMakeFaceModelBatch (Make Face Model Batch)
285
+ - ••• Additional Nodes •••
286
+ - ReActorRestoreFace (Face Restoration)
287
+ - ReActorImageDublicator (Dublicate one Image to Images List)
288
+ - ImageRGBA2RGB (Convert RGBA to RGB)
289
+
290
+ Соедините все необходимые слоты (slots) и запустите очередь (query).
291
+
292
+ ### Входы основного Нода
293
+
294
+ - `input_image` - это изображение, на котором надо поменять лицо или лица (целевое изображение, аналог "target image" в версии для SD WebUI);
295
+ - Поддерживаемые ноды: "Load Image", "Load Video" или любые другие ноды предоставляющие изображение в качестве выхода;
296
+ - `source_image` - это изображение с лицом или лицами для замены (изображение-источник, аналог "source image" в версии для SD WebUI);
297
+ - Поддерживаемые ноды: "Load Image" или любые другие ноды с выходом Image(s);
298
+ - `face_model` - это вход для выхода с нода "Load Face Model" или другого нода ReActor для загрузки модели лица (face model или face embedding), которое вы создали ранее через нод "Save Face Model";
299
+ - Поддерживаемые ноды: "Load Face Model", "Build Blended Face Model";
300
+
301
+ ### Выходы основного Нода
302
+
303
+ - `IMAGE` - выход с готовым изображением (результатом);
304
+ - Поддерживаемые ноды: любые ноды с изображением на входе;
305
+ - `FACE_MODEL` - выход, предоставляющий модель лица, построенную в ходе замены;
306
+ - Поддерживаемые ноды: "Save Face Model", "ReActor", "Make Face Model Batch";
307
+
308
+ ### Восстановление лиц
309
+
310
+ Начиная с версии 0.3.0 ReActor Node имеет встроенное восстановление лиц.<br>Скачайте нужные вам модели (см. инструкцию по [Установке](#installation)) и выберите одну из них, чтобы улучшить качество финального лица.
311
+
312
+ ### Индексы Лиц (Face Indexes)
313
+
314
+ По умолчанию ReActor определяет лица на изображении в порядке от "большого" к "малому".<br>Вы можете поменять эту опцию, используя нод ReActorFaceSwapOpt вместе с ReActorOptions.
315
+
316
+ Если вам нужно заменить определенное лицо, вы можете указать индекс для исходного (source, с лицом) и входного (input, где будет замена лица) изображений.
317
+
318
+ Индекс первого обнаруженного лица - 0.
319
+
320
+ Вы можете задать индексы в том порядке, который вам нужен.<br>
321
+ Например: 0,1,2 (для Source); 1,0,2 (для Input).<br>Это означает, что: второе лицо из Input (индекс = 1) будет заменено первым лицом из Source (индекс = 0) и так далее.
322
+
323
+ ### Определение Пола
324
+
325
+ Вы можете обозначить, какой пол нужно определять на изображении.<br>
326
+ ReActor заменит только то лицо, которое удовлетворяет заданному условию.
327
+
328
+ ### Модели Лиц
329
+ Начиная с версии 0.4.0, вы можете сохранять модели лиц как файлы "safetensors" (хранятся в папке `ComfyUI\models\reactor\faces`) и загружать их в ReActor, реализуя разные сценарии использования, а также храня супер легкие модели лиц, которые вы чаще всего используете.
330
+
331
+ Чтобы новые модели появились в списке моделей нода "Load Face Model" - обновите страницу of с ComfyUI.<br>
332
+ (Рекомендую использовать ComfyUI Manager - иначе ваше воркфлоу может быть потеряно после перезагрузки страницы, если вы не сохранили его).
333
+
334
+ <a name="troubleshooting">
335
+
336
+ ## Устранение проблем
337
+
338
+ <a name="insightfacebuild">
339
+
340
+ ### **I. (Для пользователей Windows) Если вы до сих пор не можете установить пакет Insightface по каким-то причинам или же просто не желаете устанавливать Visual Studio или VS C++ Build Tools - сделайте следующее:**
341
+
342
+ 1. (ComfyUI Portable) Находясь в корневой директории, проверьте версию Python:<br>запустите CMD и выполните `python_embeded\python.exe -V`<br>Вы должны увидеть версию или 3.10, или 3.11, или 3.12
343
+ 2. Скачайте готовый пакет Insightface [для версии 3.10](https://github.com/Gourieff/sd-webui-reactor/raw/main/example/insightface-0.7.3-cp310-cp310-win_amd64.whl) или [для 3.11](https://github.com/Gourieff/Assets/raw/main/Insightface/insightface-0.7.3-cp311-cp311-win_amd64.whl) (если на предыдущем шаге вы увидели 3.11) или [для 3.12](https://github.com/Gourieff/Assets/raw/main/Insightface/insightface-0.7.3-cp312-cp312-win_amd64.whl) (если на предыдущем шаге вы увидели 3.12) и сохраните его в корневую директорию stable-diffusion-webui (A1111 или SD.Next) - туда, где лежит файл "webui-user.bat" -ИЛИ- в корневую директорию ComfyUI, если вы используете ComfyUI Portable
344
+ 3. Из корневой директории запустите:
345
+ - (SD WebUI) CMD и `.\venv\Scripts\activate`
346
+ - (ComfyUI Portable) CMD
347
+ 4. Обновите PIP:
348
+ - (SD WebUI) `python -m pip install -U pip`
349
+ - (ComfyUI Portable) `python_embeded\python.exe -m pip install -U pip`
350
+ 5. Затем установите Insightface:
351
+ - (SD WebUI) `pip install insightface-0.7.3-cp310-cp310-win_amd64.whl` (для 3.10) или `pip install insightface-0.7.3-cp311-cp311-win_amd64.whl` (для 3.11) или `pip install insightface-0.7.3-cp312-cp312-win_amd64.whl` (for 3.12)
352
+ - (ComfyUI Portable) `python_embeded\python.exe -m pip install insightface-0.7.3-cp310-cp310-win_amd64.whl` (для 3.10) или `python_embeded\python.exe -m pip install insightface-0.7.3-cp311-cp311-win_amd64.whl` (для 3.11) или `python_embeded\python.exe -m pip install insightface-0.7.3-cp312-cp312-win_amd64.whl` (for 3.12)
353
+ 6. Готово!
354
+
355
+ ### **II. "AttributeError: 'NoneType' object has no attribute 'get'"**
356
+
357
+ Эта ошибка появляется, если что-то не так с файлом модели `inswapper_128.onnx`
358
+
359
+ Скачайте вручную по ссылке [отсюда](https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128.onnx)
360
+ и сохраните в директорию `ComfyUI\models\insightface`, заменив имеющийся файл
361
+
362
+ ### **III. "reactor.execute() got an unexpected keyword argument 'reference_image'"**
363
+
364
+ Это означает, что поменялось обозначение входных точек (input points) всвязи с последним обновлением<br>
365
+ Удалите из вашего рабочего пространства имеющийся ReActor Node и добавьте его снова
366
+
367
+ ### **IV. ControlNet Aux Node IMPORT failed - при использовании совместно с нодом ReActor**
368
+
369
+ 1. Закройте или остановите ComfyUI сервер, если он запущен
370
+ 2. Перейдите в корневую папку ComfyUI, откройте консоль CMD и выполните следующее:
371
+ - `python_embeded\python.exe -m pip uninstall -y opencv-python opencv-contrib-python opencv-python-headless`
372
+ - `python_embeded\python.exe -m pip install opencv-python==4.7.0.72`
373
+ 3. Готово!
374
+
375
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/uploads/reactor-w-controlnet.png?raw=true" alt="reactor+controlnet" />
376
+
377
+ ### **V. "ModuleNotFoundError: No module named 'basicsr'" или "subprocess-exited-with-error" при установке пакета future-0.18.3**
378
+
379
+ - Скачайте https://github.com/Gourieff/Assets/raw/main/comfyui-reactor-node/future-0.18.3-py3-none-any.whl<br>
380
+ - Скопируйте файл в корневую папку ComfyUI и выполните в консоли:
381
+
382
+ python_embeded\python.exe -m pip install future-0.18.3-py3-none-any.whl
383
+
384
+ - Затем:
385
+
386
+ python_embeded\python.exe -m pip install basicsr
387
+
388
+ ### **VI. "fatal: fetch-pack: invalid index-pack output" при исполнении команды `git clone`"**
389
+
390
+ Попробуйте клонировать репозиторий с параметром `--depth=1` (только последний коммит):
391
+
392
+ git clone --depth=1 https://codeberg.org/Gourieff/comfyui-reactor-node
393
+
394
+ Затем вытяните оставшееся (если требуется):
395
+
396
+ git fetch --unshallow
397
+
398
+ <a name="updating">
399
+
400
+ ## Обновление
401
+
402
+ Положите .bat или .sh скрипт из [данного репозитория](https://github.com/Gourieff/sd-webui-extensions-updater) в папку `ComfyUI\custom_nodes` и запустите, когда желаете обновить ComfyUI и Ноды
403
+
404
+ <a name="disclaimer">
405
+
406
+ ## Ответственность
407
+
408
+ Это программное обеспечение призвано стать продуктивным вкладом в быстрорастущую медиаиндустрию на основе генеративных сетей и искусственного интеллекта. Данное ПО поможет художникам в решении таких задач, как анимация собственного персонажа или использование персонажа в качестве модели для одежды и т.д.
409
+
410
+ Разработчики этого программного обеспечения осведомлены о возможных неэтичных применениях и обязуются принять против этого превентивные меры. Мы продолжим развивать этот проект в позитивном направлении, придерживаясь закона и этики.
411
+
412
+ Подразумевается, что пользователи этого программного обеспечения будут использовать его ответственно, соблюдая локальное законодательство. Если используется лицо реального человека, пользователь обязан получить согласие заинтересованного лица и четко указать, что это дипфейк при размещении контента в Интернете. **Разработчики и Со-авторы данного программного обеспечения не несут ответственности за действия конечных пользователей.**
413
+
414
+ Используя данное расширение, вы соглашаетесь не создавать материалы, которые:
415
+ - нарушают какие-либо действующие законы тех или иных государств или международных организаций;
416
+ - причиняют какой-либо вред человеку или лицам;
417
+ - пропагандируют любую информацию (как общедоступную, так и личную) или изображения (как общедоступные, так и личные), которые могут быть направлены на причинение вреда;
418
+ - используются для распространения дезинформации;
419
+ - нацелены на уязвимые группы людей.
420
+
421
+ Данное программное обеспечение использует предварительно обученные модели `buffalo_l` и `inswapper_128.onnx`, представленные разработчиками [InsightFace](https://github.com/deepinsight/insightface/). Эти модели распространяются при следующих условиях:
422
+
423
+ [Перевод из текста лицензии insighface](https://github.com/deepinsight/insightface/tree/master/python-package): Предварительно обученные модели InsightFace доступны только для некоммерческих исследовательских целей. Сюда входят как модели с автоматической загрузкой, так и модели, загруженные вручную.
424
+
425
+ Пользователи данного программного обеспечения должны строго соблюдать данные условия использования. Разработчики и Со-авторы данного программного продукта не несут ответственности за неправильное использование предварительно обученных моделей InsightFace.
426
+
427
+ Обратите внимание: если вы собираетесь использовать это программное обеспечение в каких-либо коммерческих целях, вам необходимо будет обучить свои собственные модели или найти модели, которые можно использовать в коммерческих целях.
428
+
429
+ ### Хэш файлов моделей
430
+
431
+ #### Безопасные для использования модели имеют следующий хэш:
432
+
433
+ inswapper_128.onnx
434
+ ```
435
+ MD5:a3a155b90354160350efd66fed6b3d80
436
+ SHA256:e4a3f08c753cb72d04e10aa0f7dbe3deebbf39567d4ead6dce08e98aa49e16af
437
+ ```
438
+
439
+ 1k3d68.onnx
440
+
441
+ ```
442
+ MD5:6fb94fcdb0055e3638bf9158e6a108f4
443
+ SHA256:df5c06b8a0c12e422b2ed8947b8869faa4105387f199c477af038aa01f9a45cc
444
+ ```
445
+
446
+ 2d106det.onnx
447
+
448
+ ```
449
+ MD5:a3613ef9eb3662b4ef88eb90db1fcf26
450
+ SHA256:f001b856447c413801ef5c42091ed0cd516fcd21f2d6b79635b1e733a7109dbf
451
+ ```
452
+
453
+ det_10g.onnx
454
+
455
+ ```
456
+ MD5:4c10eef5c9e168357a16fdd580fa8371
457
+ SHA256:5838f7fe053675b1c7a08b633df49e7af5495cee0493c7dcf6697200b85b5b91
458
+ ```
459
+
460
+ genderage.onnx
461
+
462
+ ```
463
+ MD5:81c77ba87ab38163b0dec6b26f8e2af2
464
+ SHA256:4fde69b1c810857b88c64a335084f1c3fe8f01246c9a191b48c7bb756d6652fb
465
+ ```
466
+
467
+ w600k_r50.onnx
468
+
469
+ ```
470
+ MD5:80248d427976241cbd1343889ed132b3
471
+ SHA256:4c06341c33c2ca1f86781dab0e829f88ad5b64be9fba56e56bc9ebdefc619e43
472
+ ```
473
+
474
+ **Пожалуйста, сравните хэш, если вы скачиваете данные модели из непроверенных источников**
475
+
476
+ <a name="credits">
477
+
478
+ ## Благодарности и авторы компонентов
479
+
480
+ <details>
481
+ <summary><a>Нажмите, чтобы посмотреть</a></summary>
482
+
483
+ <br>
484
+
485
+ |файл|источник|лицензия|
486
+ |----|--------|--------|
487
+ |[buffalo_l.zip](https://huggingface.co/datasets/Gourieff/ReActor/blob/main/models/buffalo_l.zip) | [DeepInsight](https://github.com/deepinsight/insightface) | ![license](https://img.shields.io/badge/license-non_commercial-red) |
488
+ | [codeformer-v0.1.0.pth](https://huggingface.co/datasets/Gourieff/ReActor/blob/main/models/facerestore_models/codeformer-v0.1.0.pth) | [sczhou](https://github.com/sczhou/CodeFormer) | ![license](https://img.shields.io/badge/license-non_commercial-red) |
489
+ | [GFPGANv1.3.pth](https://huggingface.co/datasets/Gourieff/ReActor/blob/main/models/facerestore_models/GFPGANv1.3.pth) | [TencentARC](https://github.com/TencentARC/GFPGAN) | ![license](https://img.shields.io/badge/license-Apache_2.0-green.svg) |
490
+ | [GFPGANv1.4.pth](https://huggingface.co/datasets/Gourieff/ReActor/blob/main/models/facerestore_models/GFPGANv1.4.pth) | [TencentARC](https://github.com/TencentARC/GFPGAN) | ![license](https://img.shields.io/badge/license-Apache_2.0-green.svg) |
491
+ | [inswapper_128.onnx](https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128.onnx) | [DeepInsight](https://github.com/deepinsight/insightface) | ![license](https://img.shields.io/badge/license-non_commercial-red) |
492
+ | [inswapper_128_fp16.onnx](https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128_fp16.onnx) | [Hillobar](https://github.com/Hillobar/Rope) | ![license](https://img.shields.io/badge/license-non_commercial-red) |
493
+
494
+ [BasicSR](https://github.com/XPixelGroup/BasicSR) - [@XPixelGroup](https://github.com/XPixelGroup) <br>
495
+ [facexlib](https://github.com/xinntao/facexlib) - [@xinntao](https://github.com/xinntao) <br>
496
+
497
+ [@s0md3v](https://github.com/s0md3v), [@henryruhs](https://github.com/henryruhs) - оригинальное приложение Roop <br>
498
+ [@ssitu](https://github.com/ssitu) - первая версия расширения с поддержкой ComfyUI [ComfyUI_roop](https://github.com/ssitu/ComfyUI_roop)
499
+
500
+ </details>
501
+
502
+ <a name="note">
503
+
504
+ ### Обратите внимание!
505
+
506
+ **Если у вас возникли какие-либо ошибки при очередном использовании Нода ReActor - не торопитесь открывать Issue, для начала попробуйте удалить те��ущий Нод из вашего рабочего пространства и добавить его снова**
507
+
508
+ **ReActor Node периодически получает обновления, появляются новые функции, из-за чего имеющийся Нод может работать с ошибками или не работать вовсе**
custom_nodes/comfyui-reactor-node/__init__.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+
4
+ repo_dir = os.path.dirname(os.path.realpath(__file__))
5
+ sys.path.insert(0, repo_dir)
6
+ original_modules = sys.modules.copy()
7
+
8
+ # Place aside existing modules if using a1111 web ui
9
+ modules_used = [
10
+ "modules",
11
+ "modules.images",
12
+ "modules.processing",
13
+ "modules.scripts_postprocessing",
14
+ "modules.scripts",
15
+ "modules.shared",
16
+ ]
17
+ original_webui_modules = {}
18
+ for module in modules_used:
19
+ if module in sys.modules:
20
+ original_webui_modules[module] = sys.modules.pop(module)
21
+
22
+ # Proceed with node setup
23
+ from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
24
+
25
+ __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
26
+
27
+ # Clean up imports
28
+ # Remove repo directory from path
29
+ sys.path.remove(repo_dir)
30
+ # Remove any new modules
31
+ modules_to_remove = []
32
+ for module in sys.modules:
33
+ if module not in original_modules and not module.startswith("google.protobuf") and not module.startswith("onnx") and not module.startswith("cv2"):
34
+ modules_to_remove.append(module)
35
+ for module in modules_to_remove:
36
+ del sys.modules[module]
37
+
38
+ # Restore original modules
39
+ sys.modules.update(original_webui_modules)
custom_nodes/comfyui-reactor-node/install.bat ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ setlocal enabledelayedexpansion
3
+
4
+ :: Try to use embedded python first
5
+ if exist ..\..\..\python_embeded\python.exe (
6
+ :: Use the embedded python
7
+ set PYTHON=..\..\..\python_embeded\python.exe
8
+ ) else (
9
+ :: Embedded python not found, check for python in the PATH
10
+ for /f "tokens=* USEBACKQ" %%F in (`python --version 2^>^&1`) do (
11
+ set PYTHON_VERSION=%%F
12
+ )
13
+ if errorlevel 1 (
14
+ echo I couldn't find an embedded version of Python, nor one in the Windows PATH. Please install manually.
15
+ pause
16
+ exit /b 1
17
+ ) else (
18
+ :: Use python from the PATH (if it's the right version and the user agrees)
19
+ echo I couldn't find an embedded version of Python, but I did find !PYTHON_VERSION! in your Windows PATH.
20
+ echo Would you like to proceed with the install using that version? (Y/N^)
21
+ set /p USE_PYTHON=
22
+ if /i "!USE_PYTHON!"=="Y" (
23
+ set PYTHON=python
24
+ ) else (
25
+ echo Okay. Please install manually.
26
+ pause
27
+ exit /b 1
28
+ )
29
+ )
30
+ )
31
+
32
+ :: Install the package
33
+ echo Installing...
34
+ %PYTHON% install.py
35
+ echo Done^!
36
+
37
+ @pause
custom_nodes/comfyui-reactor-node/install.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ warnings.filterwarnings("ignore", category=DeprecationWarning)
3
+
4
+ import subprocess
5
+ import os, sys
6
+ try:
7
+ from pkg_resources import get_distribution as distributions
8
+ except:
9
+ from importlib_metadata import distributions
10
+ from tqdm import tqdm
11
+ import urllib.request
12
+ from packaging import version as pv
13
+ try:
14
+ from folder_paths import models_dir
15
+ except:
16
+ from pathlib import Path
17
+ models_dir = os.path.join(Path(__file__).parents[2], "models")
18
+
19
+ sys.path.append(os.path.dirname(os.path.realpath(__file__)))
20
+
21
+ req_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "requirements.txt")
22
+
23
+ model_url = "https://huggingface.co/datasets/Gourieff/ReActor/resolve/main/models/inswapper_128.onnx"
24
+ model_name = os.path.basename(model_url)
25
+ models_dir_path = os.path.join(models_dir, "insightface")
26
+ model_path = os.path.join(models_dir_path, model_name)
27
+
28
+ def run_pip(*args):
29
+ subprocess.run([sys.executable, "-m", "pip", "install", "--no-warn-script-location", *args])
30
+
31
+ def is_installed (
32
+ package: str, version: str = None, strict: bool = True
33
+ ):
34
+ has_package = None
35
+ try:
36
+ has_package = distributions(package)
37
+ if has_package is not None:
38
+ if version is not None:
39
+ installed_version = has_package.version
40
+ if (installed_version != version and strict == True) or (pv.parse(installed_version) < pv.parse(version) and strict == False):
41
+ return False
42
+ else:
43
+ return True
44
+ else:
45
+ return True
46
+ else:
47
+ return False
48
+ except Exception as e:
49
+ print(f"Status: {e}")
50
+ return False
51
+
52
+ def download(url, path, name):
53
+ request = urllib.request.urlopen(url)
54
+ total = int(request.headers.get('Content-Length', 0))
55
+ with tqdm(total=total, desc=f'[ReActor] Downloading {name} to {path}', unit='B', unit_scale=True, unit_divisor=1024) as progress:
56
+ urllib.request.urlretrieve(url, path, reporthook=lambda count, block_size, total_size: progress.update(block_size))
57
+
58
+ if not os.path.exists(models_dir_path):
59
+ os.makedirs(models_dir_path)
60
+
61
+ if not os.path.exists(model_path):
62
+ download(model_url, model_path, model_name)
63
+
64
+ with open(req_file) as file:
65
+ try:
66
+ ort = "onnxruntime-gpu"
67
+ import torch
68
+ cuda_version = None
69
+ if torch.cuda.is_available():
70
+ cuda_version = torch.version.cuda
71
+ print(f"CUDA {cuda_version}")
72
+ elif torch.backends.mps.is_available() or hasattr(torch,'dml') or hasattr(torch,'privateuseone'):
73
+ ort = "onnxruntime"
74
+ if cuda_version is not None and float(cuda_version)>=12 and torch.torch_version.__version__ <= "2.2.0": # CU12.x and torch<=2.2.0
75
+ print(f"Torch: {torch.torch_version.__version__}")
76
+ if not is_installed(ort,"1.17.0",False):
77
+ run_pip(ort,"--extra-index-url", "https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/")
78
+ elif cuda_version is not None and float(cuda_version)>=12 and torch.torch_version.__version__ >= "2.4.0" : # CU12.x and latest torch
79
+ print(f"Torch: {torch.torch_version.__version__}")
80
+ if not is_installed(ort,"1.20.1",False): # latest ort-gpu
81
+ run_pip(ort,"-U")
82
+ elif not is_installed(ort,"1.16.1",False):
83
+ run_pip(ort, "-U")
84
+ except Exception as e:
85
+ print(e)
86
+ print(f"Warning: Failed to install {ort}, ReActor will not work.")
87
+ raise e
88
+ strict = True
89
+ for package in file:
90
+ package_version = None
91
+ try:
92
+ package = package.strip()
93
+ if "==" in package:
94
+ package_version = package.split('==')[1]
95
+ elif ">=" in package:
96
+ package_version = package.split('>=')[1]
97
+ strict = False
98
+ if not is_installed(package,package_version,strict):
99
+ run_pip(package)
100
+ except Exception as e:
101
+ print(e)
102
+ print(f"Warning: Failed to install {package}, ReActor will not work.")
103
+ raise e
104
+ print("Ok")
custom_nodes/comfyui-reactor-node/modules/__init__.py ADDED
File without changes
custom_nodes/comfyui-reactor-node/modules/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (161 Bytes). View file
 
custom_nodes/comfyui-reactor-node/modules/__pycache__/processing.cpython-312.pyc ADDED
Binary file (1.13 kB). View file
 
custom_nodes/comfyui-reactor-node/modules/__pycache__/scripts.cpython-312.pyc ADDED
Binary file (860 Bytes). View file
 
custom_nodes/comfyui-reactor-node/modules/__pycache__/scripts_postprocessing.cpython-312.pyc ADDED
Binary file (175 Bytes). View file
 
custom_nodes/comfyui-reactor-node/modules/__pycache__/shared.cpython-312.pyc ADDED
Binary file (877 Bytes). View file
 
custom_nodes/comfyui-reactor-node/modules/images.py ADDED
File without changes
custom_nodes/comfyui-reactor-node/modules/processing.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class StableDiffusionProcessing:
2
+
3
+ def __init__(self, init_imgs):
4
+ self.init_images = init_imgs
5
+ self.width = init_imgs[0].width
6
+ self.height = init_imgs[0].height
7
+ self.extra_generation_params = {}
8
+
9
+
10
+ class StableDiffusionProcessingImg2Img(StableDiffusionProcessing):
11
+
12
+ def __init__(self, init_img):
13
+ super().__init__(init_img)
custom_nodes/comfyui-reactor-node/modules/scripts.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+
4
+ class Script:
5
+ pass
6
+
7
+
8
+ def basedir():
9
+ return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
10
+
11
+
12
+ class PostprocessImageArgs:
13
+ pass
custom_nodes/comfyui-reactor-node/modules/scripts_postprocessing.py ADDED
File without changes
custom_nodes/comfyui-reactor-node/modules/shared.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class Options:
2
+ img2img_background_color = "#ffffff" # Set to white for now
3
+
4
+
5
+ class State:
6
+ interrupted = False
7
+
8
+ def begin(self):
9
+ pass
10
+
11
+ def end(self):
12
+ pass
13
+
14
+
15
+ opts = Options()
16
+ state = State()
17
+ cmd_opts = None
18
+ sd_upscalers = []
19
+ face_restorers = []
custom_nodes/comfyui-reactor-node/nodes.py ADDED
@@ -0,0 +1,1581 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, glob, sys
2
+ import logging
3
+
4
+ import torch
5
+ import torch.nn.functional as F
6
+ import torchvision.transforms as T
7
+ from torchvision.transforms.functional import normalize
8
+ from torchvision.ops import masks_to_boxes
9
+
10
+ import numpy as np
11
+ import cv2
12
+ import math
13
+ from typing import List
14
+ from PIL import Image
15
+ import io
16
+ from scipy import stats
17
+ from insightface.app.common import Face
18
+ from segment_anything import sam_model_registry
19
+
20
+ from modules.processing import StableDiffusionProcessingImg2Img
21
+ from modules.shared import state
22
+ # from comfy_extras.chainner_models import model_loading
23
+ import comfy.model_management as model_management
24
+ import comfy.utils
25
+ import folder_paths
26
+
27
+ import scripts.reactor_version
28
+ from r_chainner import model_loading
29
+ from scripts.reactor_faceswap import (
30
+ FaceSwapScript,
31
+ get_models,
32
+ get_current_faces_model,
33
+ analyze_faces,
34
+ half_det_size,
35
+ providers
36
+ )
37
+ from scripts.reactor_swapper import (
38
+ unload_all_models,
39
+ )
40
+ from scripts.reactor_logger import logger
41
+ from reactor_utils import (
42
+ batch_tensor_to_pil,
43
+ batched_pil_to_tensor,
44
+ tensor_to_pil,
45
+ img2tensor,
46
+ tensor2img,
47
+ save_face_model,
48
+ load_face_model,
49
+ download,
50
+ set_ort_session,
51
+ prepare_cropped_face,
52
+ normalize_cropped_face,
53
+ add_folder_path_and_extensions,
54
+ rgba2rgb_tensor,
55
+ progress_bar,
56
+ progress_bar_reset
57
+ )
58
+ from reactor_patcher import apply_patch
59
+ from r_facelib.utils.face_restoration_helper import FaceRestoreHelper
60
+ from r_basicsr.utils.registry import ARCH_REGISTRY
61
+ import scripts.r_archs.codeformer_arch
62
+ import scripts.r_masking.subcore as subcore
63
+ import scripts.r_masking.core as core
64
+ import scripts.r_masking.segs as masking_segs
65
+
66
+
67
+ models_dir = folder_paths.models_dir
68
+ REACTOR_MODELS_PATH = os.path.join(models_dir, "reactor")
69
+ FACE_MODELS_PATH = os.path.join(REACTOR_MODELS_PATH, "faces")
70
+
71
+ if not os.path.exists(REACTOR_MODELS_PATH):
72
+ os.makedirs(REACTOR_MODELS_PATH)
73
+ if not os.path.exists(FACE_MODELS_PATH):
74
+ os.makedirs(FACE_MODELS_PATH)
75
+
76
+ dir_facerestore_models = os.path.join(models_dir, "facerestore_models")
77
+ os.makedirs(dir_facerestore_models, exist_ok=True)
78
+ folder_paths.folder_names_and_paths["facerestore_models"] = ([dir_facerestore_models], folder_paths.supported_pt_extensions)
79
+
80
+ BLENDED_FACE_MODEL = None
81
+ FACE_SIZE: int = 512
82
+ FACE_HELPER = None
83
+
84
+ if "ultralytics" not in folder_paths.folder_names_and_paths:
85
+ add_folder_path_and_extensions("ultralytics_bbox", [os.path.join(models_dir, "ultralytics", "bbox")], folder_paths.supported_pt_extensions)
86
+ add_folder_path_and_extensions("ultralytics_segm", [os.path.join(models_dir, "ultralytics", "segm")], folder_paths.supported_pt_extensions)
87
+ add_folder_path_and_extensions("ultralytics", [os.path.join(models_dir, "ultralytics")], folder_paths.supported_pt_extensions)
88
+ if "sams" not in folder_paths.folder_names_and_paths:
89
+ add_folder_path_and_extensions("sams", [os.path.join(models_dir, "sams")], folder_paths.supported_pt_extensions)
90
+
91
+ def get_facemodels():
92
+ models_path = os.path.join(FACE_MODELS_PATH, "*")
93
+ models = glob.glob(models_path)
94
+ models = [x for x in models if x.endswith(".safetensors")]
95
+ return models
96
+
97
+ def get_restorers():
98
+ models_path = os.path.join(models_dir, "facerestore_models/*")
99
+ models = glob.glob(models_path)
100
+ models = [x for x in models if (x.endswith(".pth") or x.endswith(".onnx"))]
101
+ if len(models) == 0:
102
+ fr_urls = [
103
+ "https://huggingface.co/datasets/Gourieff/ReActor/resolve/main/models/facerestore_models/GFPGANv1.3.pth",
104
+ "https://huggingface.co/datasets/Gourieff/ReActor/resolve/main/models/facerestore_models/GFPGANv1.4.pth",
105
+ "https://huggingface.co/datasets/Gourieff/ReActor/resolve/main/models/facerestore_models/codeformer-v0.1.0.pth",
106
+ "https://huggingface.co/datasets/Gourieff/ReActor/resolve/main/models/facerestore_models/GPEN-BFR-512.onnx",
107
+ "https://huggingface.co/datasets/Gourieff/ReActor/resolve/main/models/facerestore_models/GPEN-BFR-1024.onnx",
108
+ "https://huggingface.co/datasets/Gourieff/ReActor/resolve/main/models/facerestore_models/GPEN-BFR-2048.onnx",
109
+ ]
110
+ for model_url in fr_urls:
111
+ model_name = os.path.basename(model_url)
112
+ model_path = os.path.join(dir_facerestore_models, model_name)
113
+ download(model_url, model_path, model_name)
114
+ models = glob.glob(models_path)
115
+ models = [x for x in models if (x.endswith(".pth") or x.endswith(".onnx"))]
116
+ return models
117
+
118
+ def get_model_names(get_models):
119
+ models = get_models()
120
+ names = []
121
+ for x in models:
122
+ names.append(os.path.basename(x))
123
+ names.sort(key=str.lower)
124
+ names.insert(0, "none")
125
+ return names
126
+
127
+ def model_names():
128
+ models = get_models()
129
+ return {os.path.basename(x): x for x in models}
130
+
131
+
132
+ class reactor:
133
+ @classmethod
134
+ def INPUT_TYPES(s):
135
+ return {
136
+ "required": {
137
+ "enabled": ("BOOLEAN", {"default": True, "label_off": "OFF", "label_on": "ON"}),
138
+ "input_image": ("IMAGE",),
139
+ "swap_model": (list(model_names().keys()),),
140
+ "facedetection": (["retinaface_resnet50", "retinaface_mobile0.25", "YOLOv5l", "YOLOv5n"],),
141
+ "face_restore_model": (get_model_names(get_restorers),),
142
+ "face_restore_visibility": ("FLOAT", {"default": 1, "min": 0.1, "max": 1, "step": 0.05}),
143
+ "codeformer_weight": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1, "step": 0.05}),
144
+ "detect_gender_input": (["no","female","male"], {"default": "no"}),
145
+ "detect_gender_source": (["no","female","male"], {"default": "no"}),
146
+ "input_faces_index": ("STRING", {"default": "0"}),
147
+ "source_faces_index": ("STRING", {"default": "0"}),
148
+ "console_log_level": ([0, 1, 2], {"default": 1}),
149
+ },
150
+ "optional": {
151
+ "source_image": ("IMAGE",),
152
+ "face_model": ("FACE_MODEL",),
153
+ "face_boost": ("FACE_BOOST",),
154
+ },
155
+ "hidden": {"faces_order": "FACES_ORDER"},
156
+ }
157
+
158
+ RETURN_TYPES = ("IMAGE","FACE_MODEL","IMAGE")
159
+ RETURN_NAMES = ("SWAPPED_IMAGE","FACE_MODEL","ORIGINAL_IMAGE")
160
+ FUNCTION = "execute"
161
+ CATEGORY = "🌌 ReActor"
162
+
163
+ def __init__(self):
164
+ # self.face_helper = None
165
+ self.faces_order = ["large-small", "large-small"]
166
+ # self.face_size = FACE_SIZE
167
+ self.face_boost_enabled = False
168
+ self.restore = True
169
+ self.boost_model = None
170
+ self.interpolation = "Bicubic"
171
+ self.boost_model_visibility = 1
172
+ self.boost_cf_weight = 0.5
173
+
174
+ def restore_face(
175
+ self,
176
+ input_image,
177
+ face_restore_model,
178
+ face_restore_visibility,
179
+ codeformer_weight,
180
+ facedetection,
181
+ face_selection="all",
182
+ sort_by="area",
183
+ descending=True,
184
+ min_x_position=0.0,
185
+ max_x_position=1.0,
186
+ min_y_position=0.0,
187
+ max_y_position=1.0,
188
+ take_start=0,
189
+ take_count=1,
190
+ face_index=0,
191
+ ):
192
+
193
+ # >>>>> ПРИНУДИТЕЛЬНЫЙ ВЫВОД ОТЛАДКИ <<<<<
194
+ # print(f"\n--- [ReActor Debug] Face selection: {face_selection}, Sort by: {sort_by}, Descending: {descending}")
195
+
196
+ result = input_image
197
+
198
+ if face_restore_model != "none" and not model_management.processing_interrupted():
199
+
200
+ global FACE_SIZE, FACE_HELPER
201
+
202
+ self.face_helper = FACE_HELPER
203
+
204
+ faceSize = 512
205
+ if "1024" in face_restore_model.lower():
206
+ faceSize = 1024
207
+ elif "2048" in face_restore_model.lower():
208
+ faceSize = 2048
209
+
210
+ logger.status(f"Restoring with {face_restore_model} | Face Size is set to {faceSize}")
211
+
212
+ model_path = folder_paths.get_full_path("facerestore_models", face_restore_model)
213
+
214
+ device = model_management.get_torch_device()
215
+
216
+ if "codeformer" in face_restore_model.lower():
217
+
218
+ codeformer_net = ARCH_REGISTRY.get("CodeFormer")(
219
+ dim_embd=512,
220
+ codebook_size=1024,
221
+ n_head=8,
222
+ n_layers=9,
223
+ connect_list=["32", "64", "128", "256"],
224
+ ).to(device)
225
+ checkpoint = torch.load(model_path)["params_ema"]
226
+ codeformer_net.load_state_dict(checkpoint)
227
+ facerestore_model = codeformer_net.eval()
228
+
229
+ elif ".onnx" in face_restore_model:
230
+
231
+ ort_session = set_ort_session(model_path, providers=providers)
232
+ ort_session_inputs = {}
233
+ facerestore_model = ort_session
234
+
235
+ else:
236
+
237
+ sd = comfy.utils.load_torch_file(model_path, safe_load=True)
238
+ facerestore_model = model_loading.load_state_dict(sd).eval()
239
+ facerestore_model.to(device)
240
+
241
+ if faceSize != FACE_SIZE or self.face_helper is None:
242
+ self.face_helper = FaceRestoreHelper(1, face_size=faceSize, crop_ratio=(1, 1), det_model=facedetection, save_ext='png', use_parse=True, device=device)
243
+ FACE_SIZE = faceSize
244
+ FACE_HELPER = self.face_helper
245
+
246
+ # Copying Tensor to CPU (if it isn't) to convert torch.Tensor to np.ndarray
247
+ image_np = 255. * result.cpu().numpy()
248
+
249
+ total_images = image_np.shape[0]
250
+
251
+ out_images = []
252
+
253
+ pbar = progress_bar(total_images)
254
+
255
+ for i in range(total_images):
256
+
257
+ # if total_images > 1:
258
+ # logger.status(f"Restoring {i}")
259
+
260
+ cur_image_np = image_np[i,:, :, ::-1]
261
+
262
+ original_resolution = cur_image_np.shape[0:2]
263
+
264
+ if facerestore_model is None or self.face_helper is None:
265
+ return result
266
+
267
+ self.face_helper.clean_all()
268
+ self.face_helper.read_image(cur_image_np)
269
+ self.face_helper.get_face_landmarks_5(only_center_face=False, resize=640, eye_dist_threshold=5)
270
+ self.face_helper.align_warp_face()
271
+
272
+ # Фильтрация лиц
273
+ if face_selection != "all" and self.face_helper.cropped_faces:
274
+ # Собираем информацию о лицах для фильтрации
275
+ face_info = []
276
+ img_height, img_width = cur_image_np.shape[0:2]
277
+
278
+ for j, face in enumerate(self.face_helper.cropped_faces):
279
+ # Используем центр лица вместо левого верхнего угла
280
+ if hasattr(self.face_helper, 'det_faces') and len(self.face_helper.det_faces) > j:
281
+ bbox = self.face_helper.det_faces[j]
282
+ # Вычисляем центр лица для более точного позиционирования
283
+ x1 = ((bbox[0] + bbox[2]) / 2) / img_width # центр x
284
+ y1 = ((bbox[1] + bbox[3]) / 2) / img_height # центр y
285
+ area = face.shape[0] * face.shape[1]
286
+ confidence = bbox[4] if len(bbox) > 4 else 1.0
287
+ else:
288
+ # Если информация о bbox недоступна, используем приблизительные данные
289
+ area = face.shape[0] * face.shape[1]
290
+ x1, y1 = 0.5, 0.5 # центр изображения
291
+ confidence = 1.0
292
+
293
+ face_info.append({
294
+ 'index': j,
295
+ 'area': area,
296
+ 'x_position': x1,
297
+ 'y_position': y1,
298
+ 'detection_confidence': confidence
299
+ })
300
+
301
+ # Сначала сортируем все лица по выбранному критерию
302
+ all_indices = list(range(len(self.face_helper.cropped_faces)))
303
+
304
+ # Отладочный вывод перед сортировкой
305
+ # print(f"--- [ReActor Debug] Sorting all faces by {sort_by}, descending={descending}")
306
+
307
+ # Вывод для x_position и y_position
308
+ if sort_by == "y_position":
309
+ all_positions = [(idx, face_info[idx]['y_position']) for idx in all_indices]
310
+ # print(f"--- [ReActor Debug] All positions before sort: {all_positions}")
311
+ elif sort_by == "x_position":
312
+ all_positions = [(idx, face_info[idx]['x_position']) for idx in all_indices]
313
+ # print(f"--- [ReActor Debug] All X positions before sort: {all_positions}")
314
+
315
+ # Сортировка по выбранному критерию
316
+ sorted_indices = sorted(
317
+ all_indices,
318
+ key=lambda idx: face_info[idx][sort_by],
319
+ reverse=descending
320
+ )
321
+
322
+ # Отладочный вывод после сортировки
323
+ if sort_by == "y_position":
324
+ sorted_positions = [(idx, face_info[idx]['y_position']) for idx in sorted_indices]
325
+ # print(f"--- [ReActor Debug] All positions after sort: {sorted_positions}")
326
+ elif sort_by == "x_position":
327
+ sorted_positions = [(idx, face_info[idx]['x_position']) for idx in sorted_indices]
328
+ # print(f"--- [ReActor Debug] All X positions after sort: {sorted_positions}")
329
+
330
+ # Применяем фильтрацию в зависимости от режима
331
+ if face_selection == "filter":
332
+ # Фильтрация по координатам
333
+ filtered_indices = [
334
+ idx for idx in sorted_indices
335
+ if min_x_position <= face_info[idx]['x_position'] <= max_x_position and
336
+ min_y_position <= face_info[idx]['y_position'] <= max_y_position
337
+ ]
338
+
339
+ # print(f"--- [ReActor Debug] Filtered faces: {len(filtered_indices)}")
340
+
341
+ # Выборка по take_start и take_count
342
+ selected_indices = filtered_indices[take_start:take_start + take_count]
343
+
344
+ elif face_selection == "largest":
345
+ # При выборе "largest" просто берем take_count лиц с наибольшей площадью, начиная с take_start
346
+ selected_indices = sorted_indices[take_start:take_start + take_count]
347
+ # print(f"--- [ReActor Debug] Selected {take_count} face(s) starting from {take_start}: {selected_indices}")
348
+
349
+ elif face_selection == "index":
350
+ # В режиме "index" просто берем лица, начиная с take_start
351
+ selected_indices = sorted_indices[take_start:take_start + take_count]
352
+ # print(f"--- [ReActor Debug] Selected {take_count} face(s) starting from {take_start}: {selected_indices}")
353
+
354
+ # Дополнительная отладочная информация
355
+ # for i, idx in enumerate(selected_indices):
356
+ # if sort_by == "x_position":
357
+ # print(f"--- [ReActor Debug] Selected face {i}: X position = {face_info[idx]['x_position']}")
358
+ # elif sort_by == "y_position":
359
+ # print(f"--- [ReActor Debug] Selected face {i}: Y position = {face_info[idx]['y_position']}")
360
+
361
+ # Применяем фильтрацию ко всем спискам
362
+ # print(f"--- [ReActor Debug] Final selected indices: {selected_indices}")
363
+ if selected_indices:
364
+ self.face_helper.cropped_faces = [self.face_helper.cropped_faces[j] for j in selected_indices]
365
+ if hasattr(self.face_helper, 'restored_faces'):
366
+ self.face_helper.restored_faces = []
367
+ if hasattr(self.face_helper, 'affine_matrices'):
368
+ self.face_helper.affine_matrices = [self.face_helper.affine_matrices[j] for j in selected_indices]
369
+ if hasattr(self.face_helper, 'det_faces'):
370
+ self.face_helper.det_faces = [self.face_helper.det_faces[j] for j in selected_indices]
371
+
372
+ restored_face = None
373
+
374
+ for idx, cropped_face in enumerate(self.face_helper.cropped_faces):
375
+
376
+ # if ".pth" in face_restore_model:
377
+ cropped_face_t = img2tensor(cropped_face / 255., bgr2rgb=True, float32=True)
378
+ normalize(cropped_face_t, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
379
+ cropped_face_t = cropped_face_t.unsqueeze(0).to(device)
380
+
381
+ try:
382
+
383
+ with torch.no_grad():
384
+
385
+ if ".onnx" in face_restore_model: # ONNX models
386
+
387
+ for ort_session_input in ort_session.get_inputs():
388
+ if ort_session_input.name == "input":
389
+ cropped_face_prep = prepare_cropped_face(cropped_face)
390
+ ort_session_inputs[ort_session_input.name] = cropped_face_prep
391
+ if ort_session_input.name == "weight":
392
+ weight = np.array([ 1 ], dtype = np.double)
393
+ ort_session_inputs[ort_session_input.name] = weight
394
+
395
+ output = ort_session.run(None, ort_session_inputs)[0][0]
396
+ restored_face = normalize_cropped_face(output)
397
+
398
+ else: # PTH models
399
+
400
+ output = facerestore_model(cropped_face_t, w=codeformer_weight)[0] if "codeformer" in face_restore_model.lower() else facerestore_model(cropped_face_t)[0]
401
+ restored_face = tensor2img(output, rgb2bgr=True, min_max=(-1, 1))
402
+
403
+ del output
404
+ torch.cuda.empty_cache()
405
+
406
+ except Exception as error:
407
+
408
+ print(f"\tFailed inference: {error}", file=sys.stderr)
409
+ restored_face = tensor2img(cropped_face_t, rgb2bgr=True, min_max=(-1, 1))
410
+
411
+ if face_restore_visibility < 1:
412
+ restored_face = cropped_face * (1 - face_restore_visibility) + restored_face * face_restore_visibility
413
+
414
+ restored_face = restored_face.astype("uint8")
415
+ self.face_helper.add_restored_face(restored_face)
416
+
417
+ self.face_helper.get_inverse_affine(None)
418
+
419
+ restored_img = self.face_helper.paste_faces_to_input_image()
420
+ restored_img = restored_img[:, :, ::-1]
421
+
422
+ if original_resolution != restored_img.shape[0:2]:
423
+ restored_img = cv2.resize(restored_img, (0, 0), fx=original_resolution[1]/restored_img.shape[1], fy=original_resolution[0]/restored_img.shape[0], interpolation=cv2.INTER_AREA)
424
+
425
+ self.face_helper.clean_all()
426
+
427
+ # out_images[i] = restored_img
428
+ out_images.append(restored_img)
429
+
430
+ if state.interrupted or model_management.processing_interrupted():
431
+ logger.status("Interrupted by User")
432
+ return input_image
433
+
434
+ pbar.update(1)
435
+
436
+ restored_img_np = np.array(out_images).astype(np.float32) / 255.0
437
+ restored_img_tensor = torch.from_numpy(restored_img_np)
438
+
439
+ result = restored_img_tensor
440
+
441
+ progress_bar_reset(pbar)
442
+
443
+ return result
444
+
445
+ def execute(self, enabled, input_image, swap_model, detect_gender_source, detect_gender_input, source_faces_index, input_faces_index, console_log_level, face_restore_model, face_restore_visibility, codeformer_weight, facedetection, source_image=None, face_model=None, faces_order=None, face_boost=None):
446
+
447
+ device = model_management.get_torch_device()
448
+
449
+ if isinstance(input_image, torch.Tensor) and input_image.device != device:
450
+ input_image = input_image.to(device)
451
+
452
+ if face_boost is not None:
453
+ self.face_boost_enabled = face_boost["enabled"]
454
+ self.boost_model = face_boost["boost_model"]
455
+ self.interpolation = face_boost["interpolation"]
456
+ self.boost_model_visibility = face_boost["visibility"]
457
+ self.boost_cf_weight = face_boost["codeformer_weight"]
458
+ self.restore = face_boost["restore_with_main_after"]
459
+ else:
460
+ self.face_boost_enabled = False
461
+
462
+ if faces_order is None:
463
+ faces_order = self.faces_order
464
+
465
+ apply_patch(console_log_level)
466
+
467
+ if not enabled:
468
+ return (input_image,face_model)
469
+ elif source_image is None and face_model is None:
470
+ logger.error("Please provide 'source_image' or `face_model`")
471
+ return (input_image,face_model)
472
+
473
+ if face_model == "none":
474
+ face_model = None
475
+
476
+ # Сохраняем параметры для последующего использования при restore
477
+ target_indices = []
478
+ if input_faces_index == "0" or input_faces_index == "":
479
+ target_indices = [0]
480
+ else:
481
+ try:
482
+ target_indices = [int(x.strip()) for x in input_faces_index.split(",") if x.strip()]
483
+ except:
484
+ target_indices = [0]
485
+
486
+ # Определяем параметры сортировки
487
+ sort_by = "area"
488
+ descending = True
489
+ if faces_order is not None:
490
+ input_order = faces_order[0]
491
+ if input_order in ["left-right", "right-left"]:
492
+ sort_by = "x_position"
493
+ descending = (input_order == "right-left")
494
+ elif input_order in ["top-bottom", "bottom-top"]:
495
+ sort_by = "y_position"
496
+ descending = (input_order == "bottom-top")
497
+ elif input_order in ["small-large", "large-small"]:
498
+ sort_by = "area"
499
+ descending = (input_order == "large-small")
500
+
501
+ # Выполняем face swap
502
+ script = FaceSwapScript()
503
+ pil_images = batch_tensor_to_pil(input_image)
504
+
505
+ if source_image is not None:
506
+ source = tensor_to_pil(source_image)
507
+ else:
508
+ source = None
509
+ p = StableDiffusionProcessingImg2Img(pil_images)
510
+ script.process(
511
+ p=p,
512
+ img=source,
513
+ enable=True,
514
+ source_faces_index=source_faces_index,
515
+ faces_index=input_faces_index,
516
+ model=swap_model,
517
+ swap_in_source=True,
518
+ swap_in_generated=True,
519
+ gender_source=detect_gender_source,
520
+ gender_target=detect_gender_input,
521
+ face_model=face_model,
522
+ faces_order=faces_order,
523
+ # face boost:
524
+ face_boost_enabled=self.face_boost_enabled,
525
+ face_restore_model=self.boost_model,
526
+ face_restore_visibility=self.boost_model_visibility,
527
+ codeformer_weight=self.boost_cf_weight,
528
+ interpolation=self.interpolation,
529
+ )
530
+ swapped_result = batched_pil_to_tensor(p.init_images)
531
+ original_image = batched_pil_to_tensor(pil_images)
532
+
533
+ if face_model is None:
534
+ current_face_model = get_current_faces_model()
535
+ face_model_to_provide = current_face_model[0] if (current_face_model is not None and len(current_face_model) > 0) else face_model
536
+ else:
537
+ face_model_to_provide = face_model
538
+
539
+ # Применяем restore face к результату face swap
540
+ if self.restore or not self.face_boost_enabled:
541
+ # НОВЫЙ ПОДХОД: Анализируем лица ПОСЛЕ face swap
542
+ target_faces_coords = []
543
+ try:
544
+ # Преобразуем результат face swap в изображение для анализа
545
+ swapped_img_tensor = swapped_result[0].cpu()
546
+ swapped_img_np = (255 * swapped_img_tensor.numpy()).astype(np.uint8)
547
+ swapped_img_pil = Image.fromarray(swapped_img_np)
548
+ swapped_img_cv = cv2.cvtColor(np.array(swapped_img_pil), cv2.COLOR_RGB2BGR)
549
+
550
+ # Определяем лица после face swap
551
+ face_analyser = get_current_faces_model()
552
+ detected_faces = analyze_faces(swapped_img_cv, (640, 640))
553
+
554
+ if not detected_faces:
555
+ # Пробуем с меньшим размером детекции
556
+ detected_faces = analyze_faces(swapped_img_cv, (320, 320))
557
+
558
+ if detected_faces:
559
+ # Сортируем лица тем же способом, что и в face swap
560
+ if sort_by == "x_position":
561
+ detected_faces.sort(key=lambda x: (x.bbox[0] + x.bbox[2])/2, reverse=descending)
562
+ elif sort_by == "y_position":
563
+ detected_faces.sort(key=lambda x: (x.bbox[1] + x.bbox[3])/2, reverse=descending)
564
+ elif sort_by == "area":
565
+ detected_faces.sort(key=lambda x: (x.bbox[2]-x.bbox[0])*(x.bbox[3]-x.bbox[1]), reverse=descending)
566
+
567
+ # Выбираем лица по тем же индексам, что и для face swap
568
+ for idx in target_indices:
569
+ if idx < len(detected_faces):
570
+ face = detected_faces[idx]
571
+ # Сохраняем координаты центра лица
572
+ center_x = (face.bbox[0] + face.bbox[2]) / 2 / swapped_img_cv.shape[1] # нормализуем
573
+ center_y = (face.bbox[1] + face.bbox[3]) / 2 / swapped_img_cv.shape[0] # нормализуем
574
+ target_faces_coords.append((center_x, center_y))
575
+
576
+ # print(f"--- [ReActor Debug] Detected face coordinates after swap: {target_faces_coords}")
577
+ # else:
578
+ # print("--- [ReActor Debug] No faces detected after face swap")
579
+
580
+ except Exception as e:
581
+ # print(f"--- [ReActor Debug] Error analyzing faces after swap: {str(e)}")
582
+ target_faces_coords = []
583
+
584
+ # Если определены координаты лиц, применяем restore только к ним
585
+ if target_faces_coords:
586
+ # Используем небольшой отступ вокруг каждого лица
587
+ margin = 0.15 # 15% от размера изображения
588
+
589
+ restored_result = swapped_result
590
+ for center_x, center_y in target_faces_coords:
591
+ min_x = max(0.0, center_x - margin)
592
+ max_x = min(1.0, center_x + margin)
593
+ min_y = max(0.0, center_y - margin)
594
+ max_y = min(1.0, center_y + margin)
595
+
596
+ # print(f"--- [ReActor Debug] Restoring faces in region: x={min_x:.2f}-{max_x:.2f}, y={min_y:.2f}-{max_y:.2f}")
597
+
598
+ # Применяем restore_face к указанной области
599
+ restored_result = reactor.restore_face(
600
+ self,
601
+ restored_result,
602
+ face_restore_model,
603
+ face_restore_visibility,
604
+ codeformer_weight,
605
+ facedetection,
606
+ "filter", # Используем filter для выбора по координатам
607
+ sort_by,
608
+ descending,
609
+ min_x,
610
+ max_x,
611
+ min_y,
612
+ max_y,
613
+ 0, # take_start
614
+ 10 # take_count - берем больше лиц для надежности
615
+ )
616
+
617
+ return (restored_result, face_model_to_provide, original_image)
618
+ else:
619
+ # Если координаты не определены, восстанавливаем все лица
620
+ # print("--- [ReActor Debug] Falling back to restoring all faces")
621
+ restored_result = reactor.restore_face(
622
+ self,
623
+ swapped_result,
624
+ face_restore_model,
625
+ face_restore_visibility,
626
+ codeformer_weight,
627
+ facedetection
628
+ )
629
+ return (restored_result, face_model_to_provide, original_image)
630
+ else:
631
+ # Если restore не требуется
632
+ return (swapped_result, face_model_to_provide, original_image)
633
+
634
+ class ReActorPlusOpt:
635
+ @classmethod
636
+ def INPUT_TYPES(s):
637
+ return {
638
+ "required": {
639
+ "enabled": ("BOOLEAN", {"default": True, "label_off": "OFF", "label_on": "ON"}),
640
+ "input_image": ("IMAGE",),
641
+ "swap_model": (list(model_names().keys()),),
642
+ "facedetection": (["retinaface_resnet50", "retinaface_mobile0.25", "YOLOv5l", "YOLOv5n"],),
643
+ "face_restore_model": (get_model_names(get_restorers),),
644
+ "face_restore_visibility": ("FLOAT", {"default": 1, "min": 0.1, "max": 1, "step": 0.05}),
645
+ "codeformer_weight": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1, "step": 0.05}),
646
+ },
647
+ "optional": {
648
+ "source_image": ("IMAGE",),
649
+ "face_model": ("FACE_MODEL",),
650
+ "options": ("OPTIONS",),
651
+ "face_boost": ("FACE_BOOST",),
652
+ }
653
+ }
654
+
655
+ RETURN_TYPES = ("IMAGE","FACE_MODEL","IMAGE")
656
+ RETURN_NAMES = ("SWAPPED_IMAGE","FACE_MODEL","ORIGINAL_IMAGE")
657
+ FUNCTION = "execute"
658
+ CATEGORY = "🌌 ReActor"
659
+
660
+ def __init__(self):
661
+ # self.face_helper = None
662
+ self.faces_order = ["large-small", "large-small"]
663
+ self.detect_gender_input = "no"
664
+ self.detect_gender_source = "no"
665
+ self.input_faces_index = "0"
666
+ self.source_faces_index = "0"
667
+ self.console_log_level = 1
668
+ # self.face_size = 512
669
+ self.face_boost_enabled = False
670
+ self.restore = True
671
+ self.boost_model = None
672
+ self.interpolation = "Bicubic"
673
+ self.boost_model_visibility = 1
674
+ self.boost_cf_weight = 0.5
675
+
676
+ def execute(self, enabled, input_image, swap_model, facedetection, face_restore_model, face_restore_visibility, codeformer_weight, source_image=None, face_model=None, options=None, face_boost=None):
677
+
678
+ if options is not None:
679
+ self.faces_order = [options["input_faces_order"], options["source_faces_order"]]
680
+ self.console_log_level = options["console_log_level"]
681
+ self.detect_gender_input = options["detect_gender_input"]
682
+ self.detect_gender_source = options["detect_gender_source"]
683
+ self.input_faces_index = options["input_faces_index"]
684
+ self.source_faces_index = options["source_faces_index"]
685
+
686
+ if face_boost is not None:
687
+ self.face_boost_enabled = face_boost["enabled"]
688
+ self.restore = face_boost["restore_with_main_after"]
689
+ else:
690
+ self.face_boost_enabled = False
691
+
692
+ result = reactor.execute(
693
+ self,enabled,input_image,swap_model,self.detect_gender_source,self.detect_gender_input,self.source_faces_index,self.input_faces_index,self.console_log_level,face_restore_model,face_restore_visibility,codeformer_weight,facedetection,source_image,face_model,self.faces_order, face_boost=face_boost
694
+ )
695
+
696
+ return result
697
+
698
+
699
+ class LoadFaceModel:
700
+ @classmethod
701
+ def INPUT_TYPES(s):
702
+ return {
703
+ "required": {
704
+ "face_model": (get_model_names(get_facemodels),),
705
+ }
706
+ }
707
+
708
+ RETURN_TYPES = ("FACE_MODEL",)
709
+ FUNCTION = "load_model"
710
+ CATEGORY = "🌌 ReActor"
711
+
712
+ def load_model(self, face_model):
713
+ self.face_model = face_model
714
+ self.face_models_path = FACE_MODELS_PATH
715
+ if self.face_model != "none":
716
+ face_model_path = os.path.join(self.face_models_path, self.face_model)
717
+ out = load_face_model(face_model_path)
718
+ else:
719
+ out = None
720
+ return (out, )
721
+
722
+
723
+ class ReActorWeight:
724
+ @classmethod
725
+ def INPUT_TYPES(s):
726
+ return {
727
+ "required": {
728
+ "input_image": ("IMAGE",),
729
+ "faceswap_weight": (["0%", "12.5%", "25%", "37.5%", "50%", "62.5%", "75%", "87.5%", "100%"], {"default": "50%"}),
730
+ },
731
+ "optional": {
732
+ "source_image": ("IMAGE",),
733
+ "face_model": ("FACE_MODEL",),
734
+ }
735
+ }
736
+
737
+ RETURN_TYPES = ("IMAGE","FACE_MODEL")
738
+ RETURN_NAMES = ("INPUT_IMAGE","FACE_MODEL")
739
+ FUNCTION = "set_weight"
740
+
741
+ OUTPUT_NODE = True
742
+
743
+ CATEGORY = "🌌 ReActor"
744
+
745
+ def set_weight(self, input_image, faceswap_weight, face_model=None, source_image=None):
746
+
747
+ if input_image is None:
748
+ logger.error("Please provide `input_image`")
749
+ return (input_image,None)
750
+
751
+ if source_image is None and face_model is None:
752
+ logger.error("Please provide `source_image` or `face_model`")
753
+ return (input_image,None)
754
+
755
+ weight = float(faceswap_weight.split("%")[0])
756
+
757
+ images = []
758
+ faces = [] if face_model is None else [face_model]
759
+ embeddings = [] if face_model is None else [face_model.embedding]
760
+
761
+ if weight == 0:
762
+ images = [input_image]
763
+ faces = []
764
+ embeddings = []
765
+ elif weight == 100:
766
+ if face_model is None:
767
+ images = [source_image]
768
+ else:
769
+ if weight > 50:
770
+ images = [input_image]
771
+ count = round(100/(100-weight))
772
+ else:
773
+ if face_model is None:
774
+ images = [source_image]
775
+ count = round(100/(weight))
776
+ for i in range(count-1):
777
+ if weight > 50:
778
+ if face_model is None:
779
+ images.append(source_image)
780
+ else:
781
+ faces.append(face_model)
782
+ embeddings.append(face_model.embedding)
783
+ else:
784
+ images.append(input_image)
785
+
786
+ images_list: List[Image.Image] = []
787
+
788
+ apply_patch(1)
789
+
790
+ if len(images) > 0:
791
+
792
+ for image in images:
793
+ img = tensor_to_pil(image)
794
+ images_list.append(img)
795
+
796
+ for image in images_list:
797
+ face = BuildFaceModel.build_face_model(self,image)
798
+ if isinstance(face, str):
799
+ continue
800
+ faces.append(face)
801
+ embeddings.append(face.embedding)
802
+
803
+ if len(faces) > 0:
804
+ blended_embedding = np.mean(embeddings, axis=0)
805
+ blended_face = Face(
806
+ bbox=faces[0].bbox,
807
+ kps=faces[0].kps,
808
+ det_score=faces[0].det_score,
809
+ landmark_3d_68=faces[0].landmark_3d_68,
810
+ pose=faces[0].pose,
811
+ landmark_2d_106=faces[0].landmark_2d_106,
812
+ embedding=blended_embedding,
813
+ gender=faces[0].gender,
814
+ age=faces[0].age
815
+ )
816
+ if blended_face is None:
817
+ no_face_msg = "Something went wrong, please try another set of images"
818
+ logger.error(no_face_msg)
819
+
820
+ return (input_image,blended_face)
821
+
822
+
823
+ class BuildFaceModel:
824
+ def __init__(self):
825
+ self.output_dir = FACE_MODELS_PATH
826
+
827
+ @classmethod
828
+ def INPUT_TYPES(s):
829
+ return {
830
+ "required": {
831
+ "save_mode": ("BOOLEAN", {"default": True, "label_off": "OFF", "label_on": "ON"}),
832
+ "send_only": ("BOOLEAN", {"default": False, "label_off": "NO", "label_on": "YES"}),
833
+ "face_model_name": ("STRING", {"default": "default"}),
834
+ "compute_method": (["Mean", "Median", "Mode"], {"default": "Mean"}),
835
+ },
836
+ "optional": {
837
+ "images": ("IMAGE",),
838
+ "face_models": ("FACE_MODEL",),
839
+ }
840
+ }
841
+
842
+ RETURN_TYPES = ("FACE_MODEL",)
843
+ FUNCTION = "blend_faces"
844
+
845
+ OUTPUT_NODE = True
846
+
847
+ CATEGORY = "🌌 ReActor"
848
+
849
+ def build_face_model(self, image: Image.Image, det_size=(640, 640)):
850
+ logging.StreamHandler.terminator = "\n"
851
+ if image is None:
852
+ error_msg = "Please load an Image"
853
+ logger.error(error_msg)
854
+ return error_msg
855
+ image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
856
+ face_model = analyze_faces(image, det_size)
857
+
858
+ if len(face_model) == 0:
859
+ print("")
860
+ det_size_half = half_det_size(det_size)
861
+ face_model = analyze_faces(image, det_size_half)
862
+ if face_model is not None and len(face_model) > 0:
863
+ print("...........................................................", end=" ")
864
+
865
+ if face_model is not None and len(face_model) > 0:
866
+ return face_model[0]
867
+ else:
868
+ no_face_msg = "No face found, please try another image"
869
+ # logger.error(no_face_msg)
870
+ return no_face_msg
871
+
872
+ def blend_faces(self, save_mode, send_only, face_model_name, compute_method, images=None, face_models=None):
873
+ global BLENDED_FACE_MODEL
874
+ blended_face: Face = BLENDED_FACE_MODEL
875
+
876
+ if send_only and blended_face is None:
877
+ send_only = False
878
+
879
+ if (images is not None or face_models is not None) and not send_only:
880
+
881
+ faces = []
882
+ embeddings = []
883
+
884
+ apply_patch(1)
885
+
886
+ if images is not None:
887
+ images_list: List[Image.Image] = batch_tensor_to_pil(images)
888
+
889
+ n = len(images_list)
890
+
891
+ for i,image in enumerate(images_list):
892
+ logging.StreamHandler.terminator = " "
893
+ logger.status(f"Building Face Model {i+1} of {n}...")
894
+ face = self.build_face_model(image)
895
+ if isinstance(face, str):
896
+ logger.error(f"No faces found in image {i+1}, skipping")
897
+ continue
898
+ else:
899
+ print(f"{int(((i+1)/n)*100)}%")
900
+ faces.append(face)
901
+ embeddings.append(face.embedding)
902
+
903
+ elif face_models is not None:
904
+
905
+ n = len(face_models)
906
+
907
+ for i,face_model in enumerate(face_models):
908
+ logging.StreamHandler.terminator = " "
909
+ logger.status(f"Extracting Face Model {i+1} of {n}...")
910
+ face = face_model
911
+ if isinstance(face, str):
912
+ logger.error(f"No faces found for face_model {i+1}, skipping")
913
+ continue
914
+ else:
915
+ print(f"{int(((i+1)/n)*100)}%")
916
+ faces.append(face)
917
+ embeddings.append(face.embedding)
918
+
919
+ logging.StreamHandler.terminator = "\n"
920
+ if len(faces) > 0:
921
+ # compute_method_name = "Mean" if compute_method == 0 else "Median" if compute_method == 1 else "Mode"
922
+ logger.status(f"Blending with Compute Method '{compute_method}'...")
923
+ blended_embedding = np.mean(embeddings, axis=0) if compute_method == "Mean" else np.median(embeddings, axis=0) if compute_method == "Median" else stats.mode(embeddings, axis=0)[0].astype(np.float32)
924
+ blended_face = Face(
925
+ bbox=faces[0].bbox,
926
+ kps=faces[0].kps,
927
+ det_score=faces[0].det_score,
928
+ landmark_3d_68=faces[0].landmark_3d_68,
929
+ pose=faces[0].pose,
930
+ landmark_2d_106=faces[0].landmark_2d_106,
931
+ embedding=blended_embedding,
932
+ gender=faces[0].gender,
933
+ age=faces[0].age
934
+ )
935
+ if blended_face is not None:
936
+ BLENDED_FACE_MODEL = blended_face
937
+ if save_mode:
938
+ face_model_path = os.path.join(FACE_MODELS_PATH, face_model_name + ".safetensors")
939
+ save_face_model(blended_face,face_model_path)
940
+ # done_msg = f"Face model has been saved to '{face_model_path}'"
941
+ # logger.status(done_msg)
942
+ logger.status("--Done!--")
943
+ # return (blended_face,)
944
+ else:
945
+ no_face_msg = "Something went wrong, please try another set of images"
946
+ logger.error(no_face_msg)
947
+ # return (blended_face,)
948
+ # logger.status("--Done!--")
949
+ if images is None and face_models is None:
950
+ logger.error("Please provide `images` or `face_models`")
951
+ return (blended_face,)
952
+
953
+
954
+ class SaveFaceModel:
955
+ def __init__(self):
956
+ self.output_dir = FACE_MODELS_PATH
957
+
958
+ @classmethod
959
+ def INPUT_TYPES(s):
960
+ return {
961
+ "required": {
962
+ "save_mode": ("BOOLEAN", {"default": True, "label_off": "OFF", "label_on": "ON"}),
963
+ "face_model_name": ("STRING", {"default": "default"}),
964
+ "select_face_index": ("INT", {"default": 0, "min": 0}),
965
+ },
966
+ "optional": {
967
+ "image": ("IMAGE",),
968
+ "face_model": ("FACE_MODEL",),
969
+ }
970
+ }
971
+
972
+ RETURN_TYPES = ()
973
+ FUNCTION = "save_model"
974
+
975
+ OUTPUT_NODE = True
976
+
977
+ CATEGORY = "🌌 ReActor"
978
+
979
+ def save_model(self, save_mode, face_model_name, select_face_index, image=None, face_model=None, det_size=(640, 640)):
980
+ if save_mode and image is not None:
981
+ source = tensor_to_pil(image)
982
+ source = cv2.cvtColor(np.array(source), cv2.COLOR_RGB2BGR)
983
+ apply_patch(1)
984
+ logger.status("Building Face Model...")
985
+ face_model_raw = analyze_faces(source, det_size)
986
+ if len(face_model_raw) == 0:
987
+ det_size_half = half_det_size(det_size)
988
+ face_model_raw = analyze_faces(source, det_size_half)
989
+ try:
990
+ face_model = face_model_raw[select_face_index]
991
+ except:
992
+ logger.error("No face(s) found")
993
+ return face_model_name
994
+ logger.status("--Done!--")
995
+ if save_mode and (face_model != "none" or face_model is not None):
996
+ face_model_path = os.path.join(self.output_dir, face_model_name + ".safetensors")
997
+ save_face_model(face_model,face_model_path)
998
+ if image is None and face_model is None:
999
+ logger.error("Please provide `face_model` or `image`")
1000
+ return face_model_name
1001
+
1002
+
1003
+ class RestoreFace:
1004
+ @classmethod
1005
+ def INPUT_TYPES(s):
1006
+ return {
1007
+ "required": {
1008
+ "image": ("IMAGE",),
1009
+ "facedetection": (["retinaface_resnet50", "retinaface_mobile0.25", "YOLOv5l", "YOLOv5n"],),
1010
+ "model": (get_model_names(get_restorers),),
1011
+ "visibility": ("FLOAT", {"default": 1, "min": 0.0, "max": 1, "step": 0.05}),
1012
+ "codeformer_weight": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1, "step": 0.05}),
1013
+ "face_selection": (["all", "filter", "largest"],{"default": "all"}), # ["all", "filter", "largest", "index"]
1014
+ },
1015
+ "optional": {
1016
+ "sort_by": (["area", "x_position", "y_position", "detection_confidence"],{"default": "area"}),
1017
+ "descending": ("BOOLEAN", {"default": True}),
1018
+ # "min_x_position": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
1019
+ # "max_x_position": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
1020
+ # "min_y_position": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
1021
+ # "max_y_position": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
1022
+ "take_start": ("INT", {"default": 0, "min": 0, "max": 100, "step": 1}),
1023
+ "take_count": ("INT", {"default": 1, "min": 1, "max": 100, "step": 1}),
1024
+ # "face_index": ("INT", {"default": 0, "min": 0, "max": 100, "step": 1}),
1025
+ }
1026
+ }
1027
+
1028
+ RETURN_TYPES = ("IMAGE",)
1029
+ FUNCTION = "execute"
1030
+ CATEGORY = "🌌 ReActor"
1031
+
1032
+ def execute(self, image, model, visibility, codeformer_weight, facedetection, face_selection="all",
1033
+ sort_by="area", descending=True, min_x_position=0.0, max_x_position=1.0,
1034
+ min_y_position=0.0, max_y_position=1.0, take_start=0, take_count=1, face_index=0):
1035
+ result = reactor.restore_face(
1036
+ self, image, model, visibility, codeformer_weight, facedetection,
1037
+ face_selection, sort_by, descending, min_x_position, max_x_position,
1038
+ min_y_position, max_y_position, take_start, take_count, face_index
1039
+ )
1040
+ return (result,)
1041
+
1042
+
1043
+ class MaskHelper:
1044
+ def __init__(self):
1045
+ self.labels = "all"
1046
+ self.detailer_hook = None
1047
+ self.device_mode = "AUTO"
1048
+ self.detection_hint = "center-1"
1049
+ self._sam_cache = {}
1050
+ self._bbox_cache = {}
1051
+
1052
+ @classmethod
1053
+ def INPUT_TYPES(s):
1054
+ bboxs = ["bbox/"+x for x in folder_paths.get_filename_list("ultralytics_bbox")]
1055
+ segms = ["segm/"+x for x in folder_paths.get_filename_list("ultralytics_segm")]
1056
+ sam_models = [x for x in folder_paths.get_filename_list("sams") if 'hq' not in x]
1057
+ return {
1058
+ "required": {
1059
+ "image": ("IMAGE",),
1060
+ "swapped_image": ("IMAGE",),
1061
+ "bbox_model_name": (bboxs + segms, ),
1062
+ "bbox_threshold": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
1063
+ "bbox_dilation": ("INT", {"default": 10, "min": -512, "max": 512, "step": 1}),
1064
+ "bbox_crop_factor": ("FLOAT", {"default": 3.0, "min": 1.0, "max": 100, "step": 0.1}),
1065
+ "bbox_drop_size": ("INT", {"min": 1, "max": 8192, "step": 1, "default": 10}),
1066
+ "sam_model_name": (sam_models, ),
1067
+ "sam_dilation": ("INT", {"default": 0, "min": -512, "max": 512, "step": 1}),
1068
+ "sam_threshold": ("FLOAT", {"default": 0.93, "min": 0.0, "max": 1.0, "step": 0.01}),
1069
+ "bbox_expansion": ("INT", {"default": 0, "min": 0, "max": 1000, "step": 1}),
1070
+ "mask_hint_threshold": ("FLOAT", {"default": 0.7, "min": 0.0, "max": 1.0, "step": 0.01}),
1071
+ "mask_hint_use_negative": (["False", "Small", "Outter"], ),
1072
+ "morphology_operation": (["dilate", "erode", "open", "close"],),
1073
+ "morphology_distance": ("INT", {"default": 0, "min": 0, "max": 128, "step": 1}),
1074
+ "blur_radius": ("INT", {"default": 9, "min": 0, "max": 48, "step": 1}),
1075
+ "sigma_factor": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 3., "step": 0.01}),
1076
+ },
1077
+ "optional": {
1078
+ "mask_optional": ("MASK",),
1079
+ }
1080
+ }
1081
+
1082
+ RETURN_TYPES = ("IMAGE","MASK","IMAGE","IMAGE")
1083
+ RETURN_NAMES = ("IMAGE","MASK","MASK_PREVIEW","SWAPPED_FACE")
1084
+ FUNCTION = "execute"
1085
+ CATEGORY = "🌌 ReActor"
1086
+
1087
+ def execute(self, image, swapped_image, bbox_model_name, bbox_threshold, bbox_dilation, bbox_crop_factor, bbox_drop_size, sam_model_name, sam_dilation, sam_threshold, bbox_expansion, mask_hint_threshold, mask_hint_use_negative, morphology_operation, morphology_distance, blur_radius, sigma_factor, mask_optional=None):
1088
+ device = model_management.get_torch_device()
1089
+
1090
+ # images = [image[i:i + 1, ...] for i in range(image.shape[0])]
1091
+ # Оптимально перемещаем тензоры
1092
+ if isinstance(image, torch.Tensor) and image.device != device:
1093
+ image = image.to(device)
1094
+
1095
+ images = image
1096
+
1097
+ if mask_optional is not None:
1098
+ combined_mask = mask_optional
1099
+ else:
1100
+ # Load and cache BBox model
1101
+ if bbox_model_name not in self._bbox_cache:
1102
+ bbox_model_path = folder_paths.get_full_path("ultralytics", bbox_model_name)
1103
+ model = subcore.load_yolo(bbox_model_path)
1104
+ self._bbox_cache[bbox_model_name] = subcore.UltraBBoxDetector(model)
1105
+ bbox_detector = self._bbox_cache[bbox_model_name]
1106
+
1107
+ segs_all, seg_labels = bbox_detector.detect(image, bbox_threshold, bbox_dilation, bbox_crop_factor, bbox_drop_size, self.detailer_hook)
1108
+
1109
+ if self.labels != 'all':
1110
+ labels = self.labels.split(',') if isinstance(self.labels, str) else self.labels
1111
+ segs_all, _ = masking_segs.filter(segs_all, labels)
1112
+
1113
+ # Load and cache SAM model
1114
+ if sam_model_name not in self._sam_cache:
1115
+ sam_model_path = folder_paths.get_full_path("sams", sam_model_name)
1116
+ if 'vit_h' in sam_model_name:
1117
+ model_kind = 'vit_h'
1118
+ elif 'vit_l' in sam_model_name:
1119
+ model_kind = 'vit_l'
1120
+ else:
1121
+ model_kind = 'vit_b'
1122
+ sam = sam_model_registry[model_kind](checkpoint=sam_model_path)
1123
+ size = os.path.getsize(sam_model_path)
1124
+ sam.safe_to = core.SafeToGPU(size)
1125
+ sam.safe_to.to_device(sam, device)
1126
+ sam.is_auto_mode = self.device_mode == "AUTO"
1127
+ self._sam_cache[sam_model_name] = sam
1128
+ else:
1129
+ sam = self._sam_cache[sam_model_name]
1130
+
1131
+ # Handle batched input
1132
+ if image.ndim == 4:
1133
+ combined_masks = []
1134
+ for i in range(image.shape[0]):
1135
+ segs_i = segs_all[i] if i < len(segs_all) else []
1136
+ segs_tuple = ([segs_i], seg_labels) if isinstance(segs_i, dict) else (segs_i, seg_labels)
1137
+ image_device = image.to(device) if image.device != device else image
1138
+ image_i = image_device[i]
1139
+ mask_i, _ = core.make_sam_mask_segmented(
1140
+ sam, segs_tuple, image_i, self.detection_hint,
1141
+ sam_dilation, sam_threshold, bbox_expansion,
1142
+ mask_hint_threshold, mask_hint_use_negative
1143
+ )
1144
+ combined_masks.append(mask_i)
1145
+ combined_mask = torch.stack(combined_masks)
1146
+ else:
1147
+ image_device = image.to(device) if image.device != device else image
1148
+ combined_mask, _ = core.make_sam_mask_segmented(
1149
+ sam, (segs_all, seg_labels), image_device, self.detection_hint,
1150
+ sam_dilation, sam_threshold, bbox_expansion,
1151
+ mask_hint_threshold, mask_hint_use_negative
1152
+ )
1153
+
1154
+ # # *** MASK TO IMAGE ***:
1155
+
1156
+ # mask_image = combined_mask.reshape((-1, 1, combined_mask.shape[-2], combined_mask.shape[-1])).movedim(1, -1).expand(-1, -1, -1, 3)
1157
+
1158
+ # # *** MASK MORPH ***:
1159
+
1160
+ # mask_image = core.tensor2mask(mask_image)
1161
+
1162
+ # Morph operations
1163
+ if morphology_operation == "dilate":
1164
+ combined_mask = self.iterative_morphology(combined_mask, morphology_distance, op="dilate")
1165
+ elif morphology_operation == "erode":
1166
+ combined_mask = self.iterative_morphology(combined_mask, morphology_distance, op="erode")
1167
+ elif morphology_operation == "open":
1168
+ combined_mask = self.iterative_morphology(self.iterative_morphology(combined_mask, morphology_distance, op="erode"), morphology_distance, op="dilate")
1169
+ elif morphology_operation == "close":
1170
+ combined_mask = self.iterative_morphology(self.iterative_morphology(combined_mask, morphology_distance, op="dilate"), morphology_distance, op="erode")
1171
+
1172
+ # # *** MASK BLUR ***:
1173
+
1174
+ # if len(mask_image.size()) == 3:
1175
+ # mask_image = mask_image.unsqueeze(3)
1176
+ # Gaussian blur
1177
+
1178
+ if blur_radius > 0:
1179
+ blur = T.GaussianBlur(kernel_size=blur_radius * 2 + 1, sigma=sigma_factor)
1180
+ mask_blurred = blur(combined_mask.unsqueeze(1)).squeeze(1)
1181
+ else:
1182
+ mask_blurred = combined_mask
1183
+
1184
+ # mask_image = mask_image.permute(0, 3, 1, 2)
1185
+ # kernel_size = blur_radius * 2 + 1
1186
+ # sigma = sigma_factor * (0.6 * blur_radius - 0.3)
1187
+ # mask_image_final = self.gaussian_blur(mask_image, kernel_size, sigma).permute(0, 2, 3, 1)
1188
+ # if mask_image_final.size()[3] == 1:
1189
+ # mask_image_final = mask_image_final[:, :, :, 0]
1190
+
1191
+ # Apply mask to swapped image (basic RGBA composite)
1192
+ swapped_image = swapped_image.to(device) if swapped_image.device != device else swapped_image
1193
+ swapped_rgba = core.tensor2rgba(swapped_image)
1194
+
1195
+ mask_image_final = mask_blurred
1196
+
1197
+ # *** CUT BY MASK ***:
1198
+
1199
+ if len(swapped_image.shape) < 4:
1200
+ C = 1
1201
+ else:
1202
+ C = swapped_image.shape[3]
1203
+
1204
+ # We operate on RGBA to keep the code clean and then convert back after
1205
+ swapped_image = core.tensor2rgba(swapped_image)
1206
+ mask = core.tensor2mask(mask_image_final)
1207
+
1208
+ # Scale the mask to be a matching size if it isn't
1209
+ B, H, W, _ = swapped_image.shape
1210
+ mask = torch.nn.functional.interpolate(mask.unsqueeze(1), size=(H, W), mode='nearest')[:,0,:,:]
1211
+ MB, _, _ = mask.shape
1212
+
1213
+ if MB < B:
1214
+ assert(B % MB == 0)
1215
+ mask = mask.repeat(B // MB, 1, 1)
1216
+
1217
+ # masks_to_boxes errors if the tensor is all zeros, so we'll add a single pixel and zero it out at the end
1218
+ is_empty = ~torch.gt(torch.max(torch.reshape(mask,[MB, H * W]), dim=1).values, 0.)
1219
+ mask[is_empty,0,0] = 1.
1220
+ boxes = masks_to_boxes(mask)
1221
+ mask[is_empty,0,0] = 0.
1222
+
1223
+ min_x = boxes[:,0]
1224
+ min_y = boxes[:,1]
1225
+ max_x = boxes[:,2]
1226
+ max_y = boxes[:,3]
1227
+
1228
+ width = max_x - min_x + 1
1229
+ height = max_y - min_y + 1
1230
+
1231
+ use_width = int(torch.max(width).item())
1232
+ use_height = int(torch.max(height).item())
1233
+
1234
+ alpha_mask = torch.ones((B, H, W, 4))
1235
+ alpha_mask[:,:,:,3] = mask
1236
+
1237
+ alpha_mask = alpha_mask.to(device) if alpha_mask.device != device else alpha_mask
1238
+
1239
+ swapped_image = swapped_image * alpha_mask
1240
+
1241
+ cutted_image = torch.zeros((B, use_height, use_width, 4))
1242
+ for i in range(0, B):
1243
+ if not is_empty[i]:
1244
+ ymin = int(min_y[i].item())
1245
+ ymax = int(max_y[i].item())
1246
+ xmin = int(min_x[i].item())
1247
+ xmax = int(max_x[i].item())
1248
+ single = (swapped_image[i, ymin:ymax+1, xmin:xmax+1,:]).unsqueeze(0)
1249
+ resized = torch.nn.functional.interpolate(single.permute(0, 3, 1, 2), size=(use_height, use_width), mode='bicubic').permute(0, 2, 3, 1)
1250
+ cutted_image[i] = resized[0]
1251
+
1252
+ # Preserve our type unless we were previously RGB and added non-opaque alpha due to the mask size
1253
+ if C == 1:
1254
+ cutted_image = core.tensor2mask(cutted_image)
1255
+ elif C == 3 and torch.min(cutted_image[:,:,:,3]) == 1:
1256
+ cutted_image = core.tensor2rgb(cutted_image)
1257
+
1258
+ # *** PASTE BY MASK ***:
1259
+
1260
+ image_base = core.tensor2rgba(image)
1261
+ image_to_paste = core.tensor2rgba(cutted_image)
1262
+ mask = core.tensor2mask(mask_image_final)
1263
+
1264
+ # Scale the mask to be a matching size if it isn't
1265
+ B, H, W, C = image_base.shape
1266
+ MB = mask.shape[0]
1267
+ PB = image_to_paste.shape[0]
1268
+
1269
+ if B < PB:
1270
+ assert(PB % B == 0)
1271
+ image_base = image_base.repeat(PB // B, 1, 1, 1)
1272
+ B, H, W, C = image_base.shape
1273
+ if MB < B:
1274
+ assert(B % MB == 0)
1275
+ mask = mask.repeat(B // MB, 1, 1)
1276
+ elif B < MB:
1277
+ assert(MB % B == 0)
1278
+ image_base = image_base.repeat(MB // B, 1, 1, 1)
1279
+ if PB < B:
1280
+ assert(B % PB == 0)
1281
+ image_to_paste = image_to_paste.repeat(B // PB, 1, 1, 1)
1282
+
1283
+ mask = torch.nn.functional.interpolate(mask.unsqueeze(1), size=(H, W), mode='nearest')[:,0,:,:]
1284
+ MB, MH, MW = mask.shape
1285
+
1286
+ # masks_to_boxes errors if the tensor is all zeros, so we'll add a single pixel and zero it out at the end
1287
+ is_empty = ~torch.gt(torch.max(torch.reshape(mask,[MB, MH * MW]), dim=1).values, 0.)
1288
+ mask[is_empty,0,0] = 1.
1289
+ boxes = masks_to_boxes(mask)
1290
+ mask[is_empty,0,0] = 0.
1291
+
1292
+ min_x = boxes[:,0]
1293
+ min_y = boxes[:,1]
1294
+ max_x = boxes[:,2]
1295
+ max_y = boxes[:,3]
1296
+ mid_x = (min_x + max_x) / 2
1297
+ mid_y = (min_y + max_y) / 2
1298
+
1299
+ target_width = max_x - min_x + 1
1300
+ target_height = max_y - min_y + 1
1301
+
1302
+ result = image_base.detach().clone()
1303
+ face_segment = mask_image_final
1304
+
1305
+ for i in range(0, MB):
1306
+ if is_empty[i]:
1307
+ continue
1308
+ else:
1309
+ image_index = i
1310
+ # source_size = image_to_paste.size()
1311
+ SB, SH, SW, _ = image_to_paste.shape
1312
+
1313
+ # Figure out the desired size
1314
+ width = int(target_width[i].item())
1315
+ height = int(target_height[i].item())
1316
+
1317
+ width = SW
1318
+ height = SH
1319
+
1320
+ # Resize the image we're pasting if needed
1321
+ resized_image = image_to_paste[i].unsqueeze(0)
1322
+
1323
+ pasting = torch.ones([H, W, C])
1324
+ ymid = float(mid_y[i].item())
1325
+ ymin = int(math.floor(ymid - height / 2)) + 1
1326
+ ymax = int(math.floor(ymid + height / 2)) + 1
1327
+ xmid = float(mid_x[i].item())
1328
+ xmin = int(math.floor(xmid - width / 2)) + 1
1329
+ xmax = int(math.floor(xmid + width / 2)) + 1
1330
+
1331
+ _, source_ymax, source_xmax, _ = resized_image.shape
1332
+ source_ymin, source_xmin = 0, 0
1333
+
1334
+ if xmin < 0:
1335
+ source_xmin = abs(xmin)
1336
+ xmin = 0
1337
+ if ymin < 0:
1338
+ source_ymin = abs(ymin)
1339
+ ymin = 0
1340
+ if xmax > W:
1341
+ source_xmax -= (xmax - W)
1342
+ xmax = W
1343
+ if ymax > H:
1344
+ source_ymax -= (ymax - H)
1345
+ ymax = H
1346
+
1347
+ pasting[ymin:ymax, xmin:xmax, :] = resized_image[0, source_ymin:source_ymax, source_xmin:source_xmax, :]
1348
+ pasting[:, :, 3] = 1.
1349
+
1350
+ pasting_alpha = torch.zeros([H, W])
1351
+ pasting_alpha[ymin:ymax, xmin:xmax] = resized_image[0, source_ymin:source_ymax, source_xmin:source_xmax, 3]
1352
+
1353
+ paste_mask = torch.min(pasting_alpha, mask[i]).unsqueeze(2).repeat(1, 1, 4)
1354
+
1355
+ pasting = pasting.to(device) if pasting.device != device else pasting
1356
+ paste_mask = paste_mask.to(device) if paste_mask.device != device else paste_mask
1357
+
1358
+ result[image_index] = pasting * paste_mask + result[image_index] * (1. - paste_mask)
1359
+
1360
+ face_segment = result
1361
+
1362
+ face_segment[...,3] = mask[i]
1363
+
1364
+ result = rgba2rgb_tensor(result)
1365
+
1366
+ # return (result,combined_mask,mask_image_final,face_segment,)
1367
+ try:
1368
+ torch.cuda.empty_cache()
1369
+ except:
1370
+ pass
1371
+
1372
+ return (result, combined_mask, mask_blurred, face_segment)
1373
+
1374
+ def iterative_morphology(self, image, distance, op="dilate"):
1375
+ if distance <= 0:
1376
+ return image
1377
+ image = image.unsqueeze(1) # shape [B, 1, H, W] or [1, 1, H, W]
1378
+ for _ in range(distance):
1379
+ if op == "dilate":
1380
+ image = F.max_pool2d(image, kernel_size=3, stride=1, padding=1)
1381
+ elif op == "erode":
1382
+ image = -F.max_pool2d(-image, kernel_size=3, stride=1, padding=1)
1383
+ return image.squeeze(1)
1384
+
1385
+
1386
+ class ImageDublicator:
1387
+ @classmethod
1388
+ def INPUT_TYPES(s):
1389
+ return {
1390
+ "required": {
1391
+ "image": ("IMAGE",),
1392
+ "count": ("INT", {"default": 1, "min": 0}),
1393
+ },
1394
+ }
1395
+
1396
+ RETURN_TYPES = ("IMAGE",)
1397
+ RETURN_NAMES = ("IMAGES",)
1398
+ OUTPUT_IS_LIST = (True,)
1399
+ FUNCTION = "execute"
1400
+ CATEGORY = "🌌 ReActor"
1401
+
1402
+ def execute(self, image, count):
1403
+ images = [image for i in range(count)]
1404
+ return (images,)
1405
+
1406
+
1407
+ class ImageRGBA2RGB:
1408
+ @classmethod
1409
+ def INPUT_TYPES(s):
1410
+ return {
1411
+ "required": {
1412
+ "image": ("IMAGE",),
1413
+ },
1414
+ }
1415
+
1416
+ RETURN_TYPES = ("IMAGE",)
1417
+ FUNCTION = "execute"
1418
+ CATEGORY = "🌌 ReActor"
1419
+
1420
+ def execute(self, image):
1421
+ out = rgba2rgb_tensor(image)
1422
+ return (out,)
1423
+
1424
+
1425
+ class MakeFaceModelBatch:
1426
+ @classmethod
1427
+ def INPUT_TYPES(s):
1428
+ return {
1429
+ "required": {
1430
+ "face_model1": ("FACE_MODEL",),
1431
+ },
1432
+ "optional": {
1433
+ "face_model2": ("FACE_MODEL",),
1434
+ "face_model3": ("FACE_MODEL",),
1435
+ "face_model4": ("FACE_MODEL",),
1436
+ "face_model5": ("FACE_MODEL",),
1437
+ "face_model6": ("FACE_MODEL",),
1438
+ "face_model7": ("FACE_MODEL",),
1439
+ "face_model8": ("FACE_MODEL",),
1440
+ "face_model9": ("FACE_MODEL",),
1441
+ "face_model10": ("FACE_MODEL",),
1442
+ },
1443
+ }
1444
+
1445
+ RETURN_TYPES = ("FACE_MODEL",)
1446
+ RETURN_NAMES = ("FACE_MODELS",)
1447
+ FUNCTION = "execute"
1448
+
1449
+ CATEGORY = "🌌 ReActor"
1450
+
1451
+ def execute(self, **kwargs):
1452
+ if len(kwargs) > 0:
1453
+ face_models = [value for value in kwargs.values()]
1454
+ return (face_models,)
1455
+ else:
1456
+ logger.error("Please provide at least 1 `face_model`")
1457
+ return (None,)
1458
+
1459
+
1460
+ class ReActorOptions:
1461
+ @classmethod
1462
+ def INPUT_TYPES(s):
1463
+ return {
1464
+ "required": {
1465
+ "input_faces_order": (
1466
+ ["left-right","right-left","top-bottom","bottom-top","small-large","large-small"], {"default": "large-small"}
1467
+ ),
1468
+ "input_faces_index": ("STRING", {"default": "0"}),
1469
+ "detect_gender_input": (["no","female","male"], {"default": "no"}),
1470
+ "source_faces_order": (
1471
+ ["left-right","right-left","top-bottom","bottom-top","small-large","large-small"], {"default": "large-small"}
1472
+ ),
1473
+ "source_faces_index": ("STRING", {"default": "0"}),
1474
+ "detect_gender_source": (["no","female","male"], {"default": "no"}),
1475
+ "console_log_level": ([0, 1, 2], {"default": 1}),
1476
+ }
1477
+ }
1478
+
1479
+ RETURN_TYPES = ("OPTIONS",)
1480
+ FUNCTION = "execute"
1481
+ CATEGORY = "🌌 ReActor"
1482
+
1483
+ def execute(self,input_faces_order, input_faces_index, detect_gender_input, source_faces_order, source_faces_index, detect_gender_source, console_log_level):
1484
+ options: dict = {
1485
+ "input_faces_order": input_faces_order,
1486
+ "input_faces_index": input_faces_index,
1487
+ "detect_gender_input": detect_gender_input,
1488
+ "source_faces_order": source_faces_order,
1489
+ "source_faces_index": source_faces_index,
1490
+ "detect_gender_source": detect_gender_source,
1491
+ "console_log_level": console_log_level,
1492
+ }
1493
+ return (options, )
1494
+
1495
+
1496
+ class ReActorFaceBoost:
1497
+ @classmethod
1498
+ def INPUT_TYPES(s):
1499
+ return {
1500
+ "required": {
1501
+ "enabled": ("BOOLEAN", {"default": True, "label_off": "OFF", "label_on": "ON"}),
1502
+ "boost_model": (get_model_names(get_restorers),),
1503
+ "interpolation": (["Nearest","Bilinear","Bicubic","Lanczos"], {"default": "Bicubic"}),
1504
+ "visibility": ("FLOAT", {"default": 1, "min": 0.1, "max": 1, "step": 0.05}),
1505
+ "codeformer_weight": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1, "step": 0.05}),
1506
+ "restore_with_main_after": ("BOOLEAN", {"default": False}),
1507
+ }
1508
+ }
1509
+
1510
+ RETURN_TYPES = ("FACE_BOOST",)
1511
+ FUNCTION = "execute"
1512
+ CATEGORY = "🌌 ReActor"
1513
+
1514
+ def execute(self,enabled,boost_model,interpolation,visibility,codeformer_weight,restore_with_main_after):
1515
+ face_boost: dict = {
1516
+ "enabled": enabled,
1517
+ "boost_model": boost_model,
1518
+ "interpolation": interpolation,
1519
+ "visibility": visibility,
1520
+ "codeformer_weight": codeformer_weight,
1521
+ "restore_with_main_after": restore_with_main_after,
1522
+ }
1523
+ return (face_boost, )
1524
+
1525
+ class ReActorUnload:
1526
+ @classmethod
1527
+ def INPUT_TYPES(s):
1528
+ return {
1529
+ "required": {
1530
+ "trigger": ("IMAGE", ),
1531
+ },
1532
+ }
1533
+
1534
+ RETURN_TYPES = ("IMAGE",)
1535
+ FUNCTION = "execute"
1536
+ CATEGORY = "🌌 ReActor"
1537
+
1538
+ def execute(self, trigger):
1539
+ unload_all_models()
1540
+ return (trigger,)
1541
+
1542
+
1543
+ NODE_CLASS_MAPPINGS = {
1544
+ # --- MAIN NODES ---
1545
+ "ReActorFaceSwap": reactor,
1546
+ "ReActorFaceSwapOpt": ReActorPlusOpt,
1547
+ "ReActorOptions": ReActorOptions,
1548
+ "ReActorFaceBoost": ReActorFaceBoost,
1549
+ "ReActorMaskHelper": MaskHelper,
1550
+ "ReActorSetWeight": ReActorWeight,
1551
+ # --- Operations with Face Models ---
1552
+ "ReActorSaveFaceModel": SaveFaceModel,
1553
+ "ReActorLoadFaceModel": LoadFaceModel,
1554
+ "ReActorBuildFaceModel": BuildFaceModel,
1555
+ "ReActorMakeFaceModelBatch": MakeFaceModelBatch,
1556
+ # --- Additional Nodes ---
1557
+ "ReActorRestoreFace": RestoreFace,
1558
+ "ReActorImageDublicator": ImageDublicator,
1559
+ "ImageRGBA2RGB": ImageRGBA2RGB,
1560
+ "ReActorUnload": ReActorUnload,
1561
+ }
1562
+
1563
+ NODE_DISPLAY_NAME_MAPPINGS = {
1564
+ # --- MAIN NODES ---
1565
+ "ReActorFaceSwap": "ReActor 🌌 Fast Face Swap",
1566
+ "ReActorFaceSwapOpt": "ReActor 🌌 Fast Face Swap [OPTIONS]",
1567
+ "ReActorOptions": "ReActor 🌌 Options",
1568
+ "ReActorFaceBoost": "ReActor 🌌 Face Booster",
1569
+ "ReActorMaskHelper": "ReActor 🌌 Masking Helper",
1570
+ "ReActorSetWeight": "ReActor 🌌 Set Face Swap Weight",
1571
+ # --- Operations with Face Models ---
1572
+ "ReActorSaveFaceModel": "Save Face Model 🌌 ReActor",
1573
+ "ReActorLoadFaceModel": "Load Face Model 🌌 ReActor",
1574
+ "ReActorBuildFaceModel": "Build Blended Face Model 🌌 ReActor",
1575
+ "ReActorMakeFaceModelBatch": "Make Face Model Batch 🌌 ReActor",
1576
+ # --- Additional Nodes ---
1577
+ "ReActorRestoreFace": "Restore Face 🌌 ReActor",
1578
+ "ReActorImageDublicator": "Image Dublicator (List) 🌌 ReActor",
1579
+ "ImageRGBA2RGB": "Convert RGBA to RGB 🌌 ReActor",
1580
+ "ReActorUnload": "Unload ReActor Models 🌌 ReActor",
1581
+ }
custom_nodes/comfyui-reactor-node/r_basicsr/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # https://github.com/xinntao/BasicSR
2
+ # flake8: noqa
3
+ from .archs import *
4
+ from .data import *
5
+ from .losses import *
6
+ from .metrics import *
7
+ from .models import *
8
+ from .ops import *
9
+ from .test import *
10
+ from .train import *
11
+ from .utils import *
12
+ from .version import __gitsha__, __version__
custom_nodes/comfyui-reactor-node/r_basicsr/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (420 Bytes). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/__pycache__/test.cpython-312.pyc ADDED
Binary file (2.66 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/__pycache__/train.cpython-312.pyc ADDED
Binary file (11.1 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/__pycache__/version.cpython-312.pyc ADDED
Binary file (260 Bytes). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__init__.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ from copy import deepcopy
3
+ from os import path as osp
4
+
5
+ from r_basicsr.utils import get_root_logger, scandir
6
+ from r_basicsr.utils.registry import ARCH_REGISTRY
7
+
8
+ __all__ = ['build_network']
9
+
10
+ # automatically scan and import arch modules for registry
11
+ # scan all the files under the 'archs' folder and collect files ending with
12
+ # '_arch.py'
13
+ arch_folder = osp.dirname(osp.abspath(__file__))
14
+ arch_filenames = [osp.splitext(osp.basename(v))[0] for v in scandir(arch_folder) if v.endswith('_arch.py')]
15
+ # import all the arch modules
16
+ _arch_modules = [importlib.import_module(f'r_basicsr.archs.{file_name}') for file_name in arch_filenames]
17
+
18
+
19
+ def build_network(opt):
20
+ opt = deepcopy(opt)
21
+ network_type = opt.pop('type')
22
+ net = ARCH_REGISTRY.get(network_type)(**opt)
23
+ logger = get_root_logger()
24
+ logger.info(f'Network [{net.__class__.__name__}] is created.')
25
+ return net
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (1.59 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/arch_util.cpython-312.pyc ADDED
Binary file (16.1 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/basicvsr_arch.cpython-312.pyc ADDED
Binary file (18.4 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/basicvsrpp_arch.cpython-312.pyc ADDED
Binary file (21 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/dfdnet_arch.cpython-312.pyc ADDED
Binary file (9.41 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/dfdnet_util.cpython-312.pyc ADDED
Binary file (8.85 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/discriminator_arch.cpython-312.pyc ADDED
Binary file (10.5 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/duf_arch.cpython-312.pyc ADDED
Binary file (14.5 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/ecbsr_arch.cpython-312.pyc ADDED
Binary file (17.3 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/edsr_arch.cpython-312.pyc ADDED
Binary file (3.24 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/edvr_arch.cpython-312.pyc ADDED
Binary file (21.6 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/hifacegan_arch.cpython-312.pyc ADDED
Binary file (12.4 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/hifacegan_util.cpython-312.pyc ADDED
Binary file (14.2 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/rcan_arch.cpython-312.pyc ADDED
Binary file (7.04 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/ridnet_arch.cpython-312.pyc ADDED
Binary file (10.2 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/rrdbnet_arch.cpython-312.pyc ADDED
Binary file (7.17 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/spynet_arch.cpython-312.pyc ADDED
Binary file (6.99 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/srresnet_arch.cpython-312.pyc ADDED
Binary file (4.29 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/srvgg_arch.cpython-312.pyc ADDED
Binary file (3.8 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/stylegan2_arch.cpython-312.pyc ADDED
Binary file (39 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/swinir_arch.cpython-312.pyc ADDED
Binary file (47.7 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/tof_arch.cpython-312.pyc ADDED
Binary file (9.76 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/__pycache__/vgg_arch.cpython-312.pyc ADDED
Binary file (6.78 kB). View file
 
custom_nodes/comfyui-reactor-node/r_basicsr/archs/arch_util.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections.abc
2
+ import math
3
+ import torch
4
+ import torchvision
5
+ import warnings
6
+ try:
7
+ from distutils.version import LooseVersion
8
+ except:
9
+ from packaging.version import Version
10
+ LooseVersion = Version
11
+ from itertools import repeat
12
+ from torch import nn as nn
13
+ from torch.nn import functional as F
14
+ from torch.nn import init as init
15
+ from torch.nn.modules.batchnorm import _BatchNorm
16
+
17
+ from r_basicsr.ops.dcn import ModulatedDeformConvPack, modulated_deform_conv
18
+ from r_basicsr.utils import get_root_logger
19
+
20
+
21
+ @torch.no_grad()
22
+ def default_init_weights(module_list, scale=1, bias_fill=0, **kwargs):
23
+ """Initialize network weights.
24
+
25
+ Args:
26
+ module_list (list[nn.Module] | nn.Module): Modules to be initialized.
27
+ scale (float): Scale initialized weights, especially for residual
28
+ blocks. Default: 1.
29
+ bias_fill (float): The value to fill bias. Default: 0
30
+ kwargs (dict): Other arguments for initialization function.
31
+ """
32
+ if not isinstance(module_list, list):
33
+ module_list = [module_list]
34
+ for module in module_list:
35
+ for m in module.modules():
36
+ if isinstance(m, nn.Conv2d):
37
+ init.kaiming_normal_(m.weight, **kwargs)
38
+ m.weight.data *= scale
39
+ if m.bias is not None:
40
+ m.bias.data.fill_(bias_fill)
41
+ elif isinstance(m, nn.Linear):
42
+ init.kaiming_normal_(m.weight, **kwargs)
43
+ m.weight.data *= scale
44
+ if m.bias is not None:
45
+ m.bias.data.fill_(bias_fill)
46
+ elif isinstance(m, _BatchNorm):
47
+ init.constant_(m.weight, 1)
48
+ if m.bias is not None:
49
+ m.bias.data.fill_(bias_fill)
50
+
51
+
52
+ def make_layer(basic_block, num_basic_block, **kwarg):
53
+ """Make layers by stacking the same blocks.
54
+
55
+ Args:
56
+ basic_block (nn.module): nn.module class for basic block.
57
+ num_basic_block (int): number of blocks.
58
+
59
+ Returns:
60
+ nn.Sequential: Stacked blocks in nn.Sequential.
61
+ """
62
+ layers = []
63
+ for _ in range(num_basic_block):
64
+ layers.append(basic_block(**kwarg))
65
+ return nn.Sequential(*layers)
66
+
67
+
68
+ class ResidualBlockNoBN(nn.Module):
69
+ """Residual block without BN.
70
+
71
+ It has a style of:
72
+ ---Conv-ReLU-Conv-+-
73
+ |________________|
74
+
75
+ Args:
76
+ num_feat (int): Channel number of intermediate features.
77
+ Default: 64.
78
+ res_scale (float): Residual scale. Default: 1.
79
+ pytorch_init (bool): If set to True, use pytorch default init,
80
+ otherwise, use default_init_weights. Default: False.
81
+ """
82
+
83
+ def __init__(self, num_feat=64, res_scale=1, pytorch_init=False):
84
+ super(ResidualBlockNoBN, self).__init__()
85
+ self.res_scale = res_scale
86
+ self.conv1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=True)
87
+ self.conv2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=True)
88
+ self.relu = nn.ReLU(inplace=True)
89
+
90
+ if not pytorch_init:
91
+ default_init_weights([self.conv1, self.conv2], 0.1)
92
+
93
+ def forward(self, x):
94
+ identity = x
95
+ out = self.conv2(self.relu(self.conv1(x)))
96
+ return identity + out * self.res_scale
97
+
98
+
99
+ class Upsample(nn.Sequential):
100
+ """Upsample module.
101
+
102
+ Args:
103
+ scale (int): Scale factor. Supported scales: 2^n and 3.
104
+ num_feat (int): Channel number of intermediate features.
105
+ """
106
+
107
+ def __init__(self, scale, num_feat):
108
+ m = []
109
+ if (scale & (scale - 1)) == 0: # scale = 2^n
110
+ for _ in range(int(math.log(scale, 2))):
111
+ m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1))
112
+ m.append(nn.PixelShuffle(2))
113
+ elif scale == 3:
114
+ m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1))
115
+ m.append(nn.PixelShuffle(3))
116
+ else:
117
+ raise ValueError(f'scale {scale} is not supported. Supported scales: 2^n and 3.')
118
+ super(Upsample, self).__init__(*m)
119
+
120
+
121
+ def flow_warp(x, flow, interp_mode='bilinear', padding_mode='zeros', align_corners=True):
122
+ """Warp an image or feature map with optical flow.
123
+
124
+ Args:
125
+ x (Tensor): Tensor with size (n, c, h, w).
126
+ flow (Tensor): Tensor with size (n, h, w, 2), normal value.
127
+ interp_mode (str): 'nearest' or 'bilinear'. Default: 'bilinear'.
128
+ padding_mode (str): 'zeros' or 'border' or 'reflection'.
129
+ Default: 'zeros'.
130
+ align_corners (bool): Before pytorch 1.3, the default value is
131
+ align_corners=True. After pytorch 1.3, the default value is
132
+ align_corners=False. Here, we use the True as default.
133
+
134
+ Returns:
135
+ Tensor: Warped image or feature map.
136
+ """
137
+ assert x.size()[-2:] == flow.size()[1:3]
138
+ _, _, h, w = x.size()
139
+ # create mesh grid
140
+ grid_y, grid_x = torch.meshgrid(torch.arange(0, h).type_as(x), torch.arange(0, w).type_as(x))
141
+ grid = torch.stack((grid_x, grid_y), 2).float() # W(x), H(y), 2
142
+ grid.requires_grad = False
143
+
144
+ vgrid = grid + flow
145
+ # scale grid to [-1,1]
146
+ vgrid_x = 2.0 * vgrid[:, :, :, 0] / max(w - 1, 1) - 1.0
147
+ vgrid_y = 2.0 * vgrid[:, :, :, 1] / max(h - 1, 1) - 1.0
148
+ vgrid_scaled = torch.stack((vgrid_x, vgrid_y), dim=3)
149
+ output = F.grid_sample(x, vgrid_scaled, mode=interp_mode, padding_mode=padding_mode, align_corners=align_corners)
150
+
151
+ # TODO, what if align_corners=False
152
+ return output
153
+
154
+
155
+ def resize_flow(flow, size_type, sizes, interp_mode='bilinear', align_corners=False):
156
+ """Resize a flow according to ratio or shape.
157
+
158
+ Args:
159
+ flow (Tensor): Precomputed flow. shape [N, 2, H, W].
160
+ size_type (str): 'ratio' or 'shape'.
161
+ sizes (list[int | float]): the ratio for resizing or the final output
162
+ shape.
163
+ 1) The order of ratio should be [ratio_h, ratio_w]. For
164
+ downsampling, the ratio should be smaller than 1.0 (i.e., ratio
165
+ < 1.0). For upsampling, the ratio should be larger than 1.0 (i.e.,
166
+ ratio > 1.0).
167
+ 2) The order of output_size should be [out_h, out_w].
168
+ interp_mode (str): The mode of interpolation for resizing.
169
+ Default: 'bilinear'.
170
+ align_corners (bool): Whether align corners. Default: False.
171
+
172
+ Returns:
173
+ Tensor: Resized flow.
174
+ """
175
+ _, _, flow_h, flow_w = flow.size()
176
+ if size_type == 'ratio':
177
+ output_h, output_w = int(flow_h * sizes[0]), int(flow_w * sizes[1])
178
+ elif size_type == 'shape':
179
+ output_h, output_w = sizes[0], sizes[1]
180
+ else:
181
+ raise ValueError(f'Size type should be ratio or shape, but got type {size_type}.')
182
+
183
+ input_flow = flow.clone()
184
+ ratio_h = output_h / flow_h
185
+ ratio_w = output_w / flow_w
186
+ input_flow[:, 0, :, :] *= ratio_w
187
+ input_flow[:, 1, :, :] *= ratio_h
188
+ resized_flow = F.interpolate(
189
+ input=input_flow, size=(output_h, output_w), mode=interp_mode, align_corners=align_corners)
190
+ return resized_flow
191
+
192
+
193
+ # TODO: may write a cpp file
194
+ def pixel_unshuffle(x, scale):
195
+ """ Pixel unshuffle.
196
+
197
+ Args:
198
+ x (Tensor): Input feature with shape (b, c, hh, hw).
199
+ scale (int): Downsample ratio.
200
+
201
+ Returns:
202
+ Tensor: the pixel unshuffled feature.
203
+ """
204
+ b, c, hh, hw = x.size()
205
+ out_channel = c * (scale**2)
206
+ assert hh % scale == 0 and hw % scale == 0
207
+ h = hh // scale
208
+ w = hw // scale
209
+ x_view = x.view(b, c, h, scale, w, scale)
210
+ return x_view.permute(0, 1, 3, 5, 2, 4).reshape(b, out_channel, h, w)
211
+
212
+
213
+ class DCNv2Pack(ModulatedDeformConvPack):
214
+ """Modulated deformable conv for deformable alignment.
215
+
216
+ Different from the official DCNv2Pack, which generates offsets and masks
217
+ from the preceding features, this DCNv2Pack takes another different
218
+ features to generate offsets and masks.
219
+
220
+ Ref:
221
+ Delving Deep into Deformable Alignment in Video Super-Resolution.
222
+ """
223
+
224
+ def forward(self, x, feat):
225
+ out = self.conv_offset(feat)
226
+ o1, o2, mask = torch.chunk(out, 3, dim=1)
227
+ offset = torch.cat((o1, o2), dim=1)
228
+ mask = torch.sigmoid(mask)
229
+
230
+ offset_absmean = torch.mean(torch.abs(offset))
231
+ if offset_absmean > 50:
232
+ logger = get_root_logger()
233
+ logger.warning(f'Offset abs mean is {offset_absmean}, larger than 50.')
234
+
235
+ if LooseVersion(torchvision.__version__) >= LooseVersion('0.9.0'):
236
+ return torchvision.ops.deform_conv2d(x, offset, self.weight, self.bias, self.stride, self.padding,
237
+ self.dilation, mask)
238
+ else:
239
+ return modulated_deform_conv(x, offset, mask, self.weight, self.bias, self.stride, self.padding,
240
+ self.dilation, self.groups, self.deformable_groups)
241
+
242
+
243
+ def _no_grad_trunc_normal_(tensor, mean, std, a, b):
244
+ # From: https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/weight_init.py
245
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
246
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
247
+ def norm_cdf(x):
248
+ # Computes standard normal cumulative distribution function
249
+ return (1. + math.erf(x / math.sqrt(2.))) / 2.
250
+
251
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
252
+ warnings.warn(
253
+ 'mean is more than 2 std from [a, b] in nn.init.trunc_normal_. '
254
+ 'The distribution of values may be incorrect.',
255
+ stacklevel=2)
256
+
257
+ with torch.no_grad():
258
+ # Values are generated by using a truncated uniform distribution and
259
+ # then using the inverse CDF for the normal distribution.
260
+ # Get upper and lower cdf values
261
+ low = norm_cdf((a - mean) / std)
262
+ up = norm_cdf((b - mean) / std)
263
+
264
+ # Uniformly fill tensor with values from [low, up], then translate to
265
+ # [2l-1, 2u-1].
266
+ tensor.uniform_(2 * low - 1, 2 * up - 1)
267
+
268
+ # Use inverse cdf transform for normal distribution to get truncated
269
+ # standard normal
270
+ tensor.erfinv_()
271
+
272
+ # Transform to proper mean, std
273
+ tensor.mul_(std * math.sqrt(2.))
274
+ tensor.add_(mean)
275
+
276
+ # Clamp to ensure it's in the proper range
277
+ tensor.clamp_(min=a, max=b)
278
+ return tensor
279
+
280
+
281
+ def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
282
+ r"""Fills the input Tensor with values drawn from a truncated
283
+ normal distribution.
284
+
285
+ From: https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/weight_init.py
286
+
287
+ The values are effectively drawn from the
288
+ normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`
289
+ with values outside :math:`[a, b]` redrawn until they are within
290
+ the bounds. The method used for generating the random values works
291
+ best when :math:`a \leq \text{mean} \leq b`.
292
+
293
+ Args:
294
+ tensor: an n-dimensional `torch.Tensor`
295
+ mean: the mean of the normal distribution
296
+ std: the standard deviation of the normal distribution
297
+ a: the minimum cutoff value
298
+ b: the maximum cutoff value
299
+
300
+ Examples:
301
+ >>> w = torch.empty(3, 5)
302
+ >>> nn.init.trunc_normal_(w)
303
+ """
304
+ return _no_grad_trunc_normal_(tensor, mean, std, a, b)
305
+
306
+
307
+ # From PyTorch
308
+ def _ntuple(n):
309
+
310
+ def parse(x):
311
+ if isinstance(x, collections.abc.Iterable):
312
+ return x
313
+ return tuple(repeat(x, n))
314
+
315
+ return parse
316
+
317
+
318
+ to_1tuple = _ntuple(1)
319
+ to_2tuple = _ntuple(2)
320
+ to_3tuple = _ntuple(3)
321
+ to_4tuple = _ntuple(4)
322
+ to_ntuple = _ntuple
custom_nodes/comfyui-reactor-node/r_basicsr/archs/basicvsr_arch.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn as nn
3
+ from torch.nn import functional as F
4
+
5
+ from r_basicsr.utils.registry import ARCH_REGISTRY
6
+ from .arch_util import ResidualBlockNoBN, flow_warp, make_layer
7
+ from .edvr_arch import PCDAlignment, TSAFusion
8
+ from .spynet_arch import SpyNet
9
+
10
+
11
+ @ARCH_REGISTRY.register()
12
+ class BasicVSR(nn.Module):
13
+ """A recurrent network for video SR. Now only x4 is supported.
14
+
15
+ Args:
16
+ num_feat (int): Number of channels. Default: 64.
17
+ num_block (int): Number of residual blocks for each branch. Default: 15
18
+ spynet_path (str): Path to the pretrained weights of SPyNet. Default: None.
19
+ """
20
+
21
+ def __init__(self, num_feat=64, num_block=15, spynet_path=None):
22
+ super().__init__()
23
+ self.num_feat = num_feat
24
+
25
+ # alignment
26
+ self.spynet = SpyNet(spynet_path)
27
+
28
+ # propagation
29
+ self.backward_trunk = ConvResidualBlocks(num_feat + 3, num_feat, num_block)
30
+ self.forward_trunk = ConvResidualBlocks(num_feat + 3, num_feat, num_block)
31
+
32
+ # reconstruction
33
+ self.fusion = nn.Conv2d(num_feat * 2, num_feat, 1, 1, 0, bias=True)
34
+ self.upconv1 = nn.Conv2d(num_feat, num_feat * 4, 3, 1, 1, bias=True)
35
+ self.upconv2 = nn.Conv2d(num_feat, 64 * 4, 3, 1, 1, bias=True)
36
+ self.conv_hr = nn.Conv2d(64, 64, 3, 1, 1)
37
+ self.conv_last = nn.Conv2d(64, 3, 3, 1, 1)
38
+
39
+ self.pixel_shuffle = nn.PixelShuffle(2)
40
+
41
+ # activation functions
42
+ self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True)
43
+
44
+ def get_flow(self, x):
45
+ b, n, c, h, w = x.size()
46
+
47
+ x_1 = x[:, :-1, :, :, :].reshape(-1, c, h, w)
48
+ x_2 = x[:, 1:, :, :, :].reshape(-1, c, h, w)
49
+
50
+ flows_backward = self.spynet(x_1, x_2).view(b, n - 1, 2, h, w)
51
+ flows_forward = self.spynet(x_2, x_1).view(b, n - 1, 2, h, w)
52
+
53
+ return flows_forward, flows_backward
54
+
55
+ def forward(self, x):
56
+ """Forward function of BasicVSR.
57
+
58
+ Args:
59
+ x: Input frames with shape (b, n, c, h, w). n is the temporal dimension / number of frames.
60
+ """
61
+ flows_forward, flows_backward = self.get_flow(x)
62
+ b, n, _, h, w = x.size()
63
+
64
+ # backward branch
65
+ out_l = []
66
+ feat_prop = x.new_zeros(b, self.num_feat, h, w)
67
+ for i in range(n - 1, -1, -1):
68
+ x_i = x[:, i, :, :, :]
69
+ if i < n - 1:
70
+ flow = flows_backward[:, i, :, :, :]
71
+ feat_prop = flow_warp(feat_prop, flow.permute(0, 2, 3, 1))
72
+ feat_prop = torch.cat([x_i, feat_prop], dim=1)
73
+ feat_prop = self.backward_trunk(feat_prop)
74
+ out_l.insert(0, feat_prop)
75
+
76
+ # forward branch
77
+ feat_prop = torch.zeros_like(feat_prop)
78
+ for i in range(0, n):
79
+ x_i = x[:, i, :, :, :]
80
+ if i > 0:
81
+ flow = flows_forward[:, i - 1, :, :, :]
82
+ feat_prop = flow_warp(feat_prop, flow.permute(0, 2, 3, 1))
83
+
84
+ feat_prop = torch.cat([x_i, feat_prop], dim=1)
85
+ feat_prop = self.forward_trunk(feat_prop)
86
+
87
+ # upsample
88
+ out = torch.cat([out_l[i], feat_prop], dim=1)
89
+ out = self.lrelu(self.fusion(out))
90
+ out = self.lrelu(self.pixel_shuffle(self.upconv1(out)))
91
+ out = self.lrelu(self.pixel_shuffle(self.upconv2(out)))
92
+ out = self.lrelu(self.conv_hr(out))
93
+ out = self.conv_last(out)
94
+ base = F.interpolate(x_i, scale_factor=4, mode='bilinear', align_corners=False)
95
+ out += base
96
+ out_l[i] = out
97
+
98
+ return torch.stack(out_l, dim=1)
99
+
100
+
101
+ class ConvResidualBlocks(nn.Module):
102
+ """Conv and residual block used in BasicVSR.
103
+
104
+ Args:
105
+ num_in_ch (int): Number of input channels. Default: 3.
106
+ num_out_ch (int): Number of output channels. Default: 64.
107
+ num_block (int): Number of residual blocks. Default: 15.
108
+ """
109
+
110
+ def __init__(self, num_in_ch=3, num_out_ch=64, num_block=15):
111
+ super().__init__()
112
+ self.main = nn.Sequential(
113
+ nn.Conv2d(num_in_ch, num_out_ch, 3, 1, 1, bias=True), nn.LeakyReLU(negative_slope=0.1, inplace=True),
114
+ make_layer(ResidualBlockNoBN, num_block, num_feat=num_out_ch))
115
+
116
+ def forward(self, fea):
117
+ return self.main(fea)
118
+
119
+
120
+ @ARCH_REGISTRY.register()
121
+ class IconVSR(nn.Module):
122
+ """IconVSR, proposed also in the BasicVSR paper.
123
+
124
+ Args:
125
+ num_feat (int): Number of channels. Default: 64.
126
+ num_block (int): Number of residual blocks for each branch. Default: 15.
127
+ keyframe_stride (int): Keyframe stride. Default: 5.
128
+ temporal_padding (int): Temporal padding. Default: 2.
129
+ spynet_path (str): Path to the pretrained weights of SPyNet. Default: None.
130
+ edvr_path (str): Path to the pretrained EDVR model. Default: None.
131
+ """
132
+
133
+ def __init__(self,
134
+ num_feat=64,
135
+ num_block=15,
136
+ keyframe_stride=5,
137
+ temporal_padding=2,
138
+ spynet_path=None,
139
+ edvr_path=None):
140
+ super().__init__()
141
+
142
+ self.num_feat = num_feat
143
+ self.temporal_padding = temporal_padding
144
+ self.keyframe_stride = keyframe_stride
145
+
146
+ # keyframe_branch
147
+ self.edvr = EDVRFeatureExtractor(temporal_padding * 2 + 1, num_feat, edvr_path)
148
+ # alignment
149
+ self.spynet = SpyNet(spynet_path)
150
+
151
+ # propagation
152
+ self.backward_fusion = nn.Conv2d(2 * num_feat, num_feat, 3, 1, 1, bias=True)
153
+ self.backward_trunk = ConvResidualBlocks(num_feat + 3, num_feat, num_block)
154
+
155
+ self.forward_fusion = nn.Conv2d(2 * num_feat, num_feat, 3, 1, 1, bias=True)
156
+ self.forward_trunk = ConvResidualBlocks(2 * num_feat + 3, num_feat, num_block)
157
+
158
+ # reconstruction
159
+ self.upconv1 = nn.Conv2d(num_feat, num_feat * 4, 3, 1, 1, bias=True)
160
+ self.upconv2 = nn.Conv2d(num_feat, 64 * 4, 3, 1, 1, bias=True)
161
+ self.conv_hr = nn.Conv2d(64, 64, 3, 1, 1)
162
+ self.conv_last = nn.Conv2d(64, 3, 3, 1, 1)
163
+
164
+ self.pixel_shuffle = nn.PixelShuffle(2)
165
+
166
+ # activation functions
167
+ self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True)
168
+
169
+ def pad_spatial(self, x):
170
+ """Apply padding spatially.
171
+
172
+ Since the PCD module in EDVR requires that the resolution is a multiple
173
+ of 4, we apply padding to the input LR images if their resolution is
174
+ not divisible by 4.
175
+
176
+ Args:
177
+ x (Tensor): Input LR sequence with shape (n, t, c, h, w).
178
+ Returns:
179
+ Tensor: Padded LR sequence with shape (n, t, c, h_pad, w_pad).
180
+ """
181
+ n, t, c, h, w = x.size()
182
+
183
+ pad_h = (4 - h % 4) % 4
184
+ pad_w = (4 - w % 4) % 4
185
+
186
+ # padding
187
+ x = x.view(-1, c, h, w)
188
+ x = F.pad(x, [0, pad_w, 0, pad_h], mode='reflect')
189
+
190
+ return x.view(n, t, c, h + pad_h, w + pad_w)
191
+
192
+ def get_flow(self, x):
193
+ b, n, c, h, w = x.size()
194
+
195
+ x_1 = x[:, :-1, :, :, :].reshape(-1, c, h, w)
196
+ x_2 = x[:, 1:, :, :, :].reshape(-1, c, h, w)
197
+
198
+ flows_backward = self.spynet(x_1, x_2).view(b, n - 1, 2, h, w)
199
+ flows_forward = self.spynet(x_2, x_1).view(b, n - 1, 2, h, w)
200
+
201
+ return flows_forward, flows_backward
202
+
203
+ def get_keyframe_feature(self, x, keyframe_idx):
204
+ if self.temporal_padding == 2:
205
+ x = [x[:, [4, 3]], x, x[:, [-4, -5]]]
206
+ elif self.temporal_padding == 3:
207
+ x = [x[:, [6, 5, 4]], x, x[:, [-5, -6, -7]]]
208
+ x = torch.cat(x, dim=1)
209
+
210
+ num_frames = 2 * self.temporal_padding + 1
211
+ feats_keyframe = {}
212
+ for i in keyframe_idx:
213
+ feats_keyframe[i] = self.edvr(x[:, i:i + num_frames].contiguous())
214
+ return feats_keyframe
215
+
216
+ def forward(self, x):
217
+ b, n, _, h_input, w_input = x.size()
218
+
219
+ x = self.pad_spatial(x)
220
+ h, w = x.shape[3:]
221
+
222
+ keyframe_idx = list(range(0, n, self.keyframe_stride))
223
+ if keyframe_idx[-1] != n - 1:
224
+ keyframe_idx.append(n - 1) # last frame is a keyframe
225
+
226
+ # compute flow and keyframe features
227
+ flows_forward, flows_backward = self.get_flow(x)
228
+ feats_keyframe = self.get_keyframe_feature(x, keyframe_idx)
229
+
230
+ # backward branch
231
+ out_l = []
232
+ feat_prop = x.new_zeros(b, self.num_feat, h, w)
233
+ for i in range(n - 1, -1, -1):
234
+ x_i = x[:, i, :, :, :]
235
+ if i < n - 1:
236
+ flow = flows_backward[:, i, :, :, :]
237
+ feat_prop = flow_warp(feat_prop, flow.permute(0, 2, 3, 1))
238
+ if i in keyframe_idx:
239
+ feat_prop = torch.cat([feat_prop, feats_keyframe[i]], dim=1)
240
+ feat_prop = self.backward_fusion(feat_prop)
241
+ feat_prop = torch.cat([x_i, feat_prop], dim=1)
242
+ feat_prop = self.backward_trunk(feat_prop)
243
+ out_l.insert(0, feat_prop)
244
+
245
+ # forward branch
246
+ feat_prop = torch.zeros_like(feat_prop)
247
+ for i in range(0, n):
248
+ x_i = x[:, i, :, :, :]
249
+ if i > 0:
250
+ flow = flows_forward[:, i - 1, :, :, :]
251
+ feat_prop = flow_warp(feat_prop, flow.permute(0, 2, 3, 1))
252
+ if i in keyframe_idx:
253
+ feat_prop = torch.cat([feat_prop, feats_keyframe[i]], dim=1)
254
+ feat_prop = self.forward_fusion(feat_prop)
255
+
256
+ feat_prop = torch.cat([x_i, out_l[i], feat_prop], dim=1)
257
+ feat_prop = self.forward_trunk(feat_prop)
258
+
259
+ # upsample
260
+ out = self.lrelu(self.pixel_shuffle(self.upconv1(feat_prop)))
261
+ out = self.lrelu(self.pixel_shuffle(self.upconv2(out)))
262
+ out = self.lrelu(self.conv_hr(out))
263
+ out = self.conv_last(out)
264
+ base = F.interpolate(x_i, scale_factor=4, mode='bilinear', align_corners=False)
265
+ out += base
266
+ out_l[i] = out
267
+
268
+ return torch.stack(out_l, dim=1)[..., :4 * h_input, :4 * w_input]
269
+
270
+
271
+ class EDVRFeatureExtractor(nn.Module):
272
+ """EDVR feature extractor used in IconVSR.
273
+
274
+ Args:
275
+ num_input_frame (int): Number of input frames.
276
+ num_feat (int): Number of feature channels
277
+ load_path (str): Path to the pretrained weights of EDVR. Default: None.
278
+ """
279
+
280
+ def __init__(self, num_input_frame, num_feat, load_path):
281
+
282
+ super(EDVRFeatureExtractor, self).__init__()
283
+
284
+ self.center_frame_idx = num_input_frame // 2
285
+
286
+ # extract pyramid features
287
+ self.conv_first = nn.Conv2d(3, num_feat, 3, 1, 1)
288
+ self.feature_extraction = make_layer(ResidualBlockNoBN, 5, num_feat=num_feat)
289
+ self.conv_l2_1 = nn.Conv2d(num_feat, num_feat, 3, 2, 1)
290
+ self.conv_l2_2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
291
+ self.conv_l3_1 = nn.Conv2d(num_feat, num_feat, 3, 2, 1)
292
+ self.conv_l3_2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
293
+
294
+ # pcd and tsa module
295
+ self.pcd_align = PCDAlignment(num_feat=num_feat, deformable_groups=8)
296
+ self.fusion = TSAFusion(num_feat=num_feat, num_frame=num_input_frame, center_frame_idx=self.center_frame_idx)
297
+
298
+ # activation function
299
+ self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True)
300
+
301
+ if load_path:
302
+ self.load_state_dict(torch.load(load_path, map_location=lambda storage, loc: storage)['params'])
303
+
304
+ def forward(self, x):
305
+ b, n, c, h, w = x.size()
306
+
307
+ # extract features for each frame
308
+ # L1
309
+ feat_l1 = self.lrelu(self.conv_first(x.view(-1, c, h, w)))
310
+ feat_l1 = self.feature_extraction(feat_l1)
311
+ # L2
312
+ feat_l2 = self.lrelu(self.conv_l2_1(feat_l1))
313
+ feat_l2 = self.lrelu(self.conv_l2_2(feat_l2))
314
+ # L3
315
+ feat_l3 = self.lrelu(self.conv_l3_1(feat_l2))
316
+ feat_l3 = self.lrelu(self.conv_l3_2(feat_l3))
317
+
318
+ feat_l1 = feat_l1.view(b, n, -1, h, w)
319
+ feat_l2 = feat_l2.view(b, n, -1, h // 2, w // 2)
320
+ feat_l3 = feat_l3.view(b, n, -1, h // 4, w // 4)
321
+
322
+ # PCD alignment
323
+ ref_feat_l = [ # reference feature list
324
+ feat_l1[:, self.center_frame_idx, :, :, :].clone(), feat_l2[:, self.center_frame_idx, :, :, :].clone(),
325
+ feat_l3[:, self.center_frame_idx, :, :, :].clone()
326
+ ]
327
+ aligned_feat = []
328
+ for i in range(n):
329
+ nbr_feat_l = [ # neighboring feature list
330
+ feat_l1[:, i, :, :, :].clone(), feat_l2[:, i, :, :, :].clone(), feat_l3[:, i, :, :, :].clone()
331
+ ]
332
+ aligned_feat.append(self.pcd_align(nbr_feat_l, ref_feat_l))
333
+ aligned_feat = torch.stack(aligned_feat, dim=1) # (b, t, c, h, w)
334
+
335
+ # TSA fusion
336
+ return self.fusion(aligned_feat)