ZiqianLiu commited on
Commit
e6043d4
1 Parent(s): 5094aa2

Upload 10 files

Browse files
Files changed (10) hide show
  1. .gitignore +5 -0
  2. LICENSE +674 -0
  3. README.md +363 -0
  4. __init__.py +39 -0
  5. install.bat +37 -0
  6. install.py +99 -0
  7. nodes.py +440 -0
  8. reactor_log_patch.py +120 -0
  9. reactor_utils.py +160 -0
  10. requirements.txt +4 -0
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ __pycache__/
2
+ *$py.class
3
+ .vscode/
4
+ example
5
+ input
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
README.md ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # reactor_node
2
+ 新增人脸检测功能(图片中有人脸就换脸,没人脸就直接返回)
3
+
4
+ <div align="center">
5
+
6
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/ReActor_logo_NEW_EN.png?raw=true" alt="logo" width="180px"/>
7
+
8
+ ![Version](https://img.shields.io/badge/node_version-0.4.1_beta12-green?style=for-the-badge&labelColor=darkgreen)
9
+
10
+ <sup>
11
+ <font color=brightred>
12
+
13
+ ## !!! [Important Update](#latestupdate) !!!<br>Don't forget to add the Node again in existing workflows
14
+
15
+ </font>
16
+ </sup>
17
+
18
+ <a href="https://boosty.to/artgourieff" target="_blank">
19
+ <img src="https://lovemet.ru/www/boosty.jpg" width="108" alt="Support Me on Boosty"/>
20
+ <br>
21
+ <sup>
22
+ Support This Project
23
+ </sup>
24
+ </a>
25
+
26
+ <hr>
27
+
28
+ [![Commit activity](https://img.shields.io/github/commit-activity/t/Gourieff/comfyui-reactor-node/main?cacheSeconds=0)](https://github.com/Gourieff/comfyui-reactor-node/commits/main)
29
+ ![Last commit](https://img.shields.io/github/last-commit/Gourieff/comfyui-reactor-node/main?cacheSeconds=0)
30
+ [![Opened issues](https://img.shields.io/github/issues/Gourieff/comfyui-reactor-node?color=red)](https://github.com/Gourieff/comfyui-reactor-node/issues?cacheSeconds=0)
31
+ [![Closed issues](https://img.shields.io/github/issues-closed/Gourieff/comfyui-reactor-node?color=green&cacheSeconds=0)](https://github.com/Gourieff/comfyui-reactor-node/issues?q=is%3Aissue+is%3Aclosed)
32
+ ![License](https://img.shields.io/github/license/Gourieff/comfyui-reactor-node)
33
+
34
+ English | [Русский](/README_RU.md)
35
+
36
+ # ReActor Node for ComfyUI
37
+
38
+ </div>
39
+
40
+ ### The Fast and Simple Face Swap Extension Node for ComfyUI, based on [ReActor](https://github.com/Gourieff/sd-webui-reactor) SD-WebUI Face Swap Extension
41
+
42
+ > This Node goes without NSFW filter (uncensored, use it on your own [responsibility](#disclaimer))
43
+
44
+ <div align="center">
45
+
46
+ ---
47
+ [**What's new**](#latestupdate) | [**Installation**](#installation) | [**Usage**](#usage) | [**Troubleshooting**](#troubleshooting) | [**Updating**](#updating) | [**Disclaimer**](#disclaimer) | [**Credits**](#credits) | [**Note!**](#note)
48
+
49
+ ---
50
+
51
+ </div>
52
+
53
+ <div align="center">
54
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/uploads/demo.gif?raw=true" alt="demo" width="100%"/>
55
+ </div>
56
+
57
+ <a name="latestupdate">
58
+
59
+ ## What's new in the latest update
60
+
61
+ ### 0.4.1 <sub><sup>BETA9</sup></sub>
62
+
63
+ - 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)
64
+ - Issue https://github.com/Gourieff/comfyui-reactor-node/issues/173 fix
65
+
66
+ ### 0.4.1 <sub><sup>BETA8</sup></sub>
67
+
68
+ - Seperate Node for the Face Restoration postprocessing (FR https://github.com/Gourieff/comfyui-reactor-node/issues/191), can be found inside ReActor's menu (RestoreFace Node)
69
+ - (Windows) Installation can be done for Python from the System's PATH
70
+ - Different fixes and improvements
71
+
72
+ ### 0.4.1 <sub><sup>BETA1</sup></sub>
73
+
74
+ - Face Restore Visibility and CodeFormer Weight (Fidelity) options are now available! Don't forget to reload the Node in your existing workflow
75
+
76
+ <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%"/>
77
+
78
+ ### 0.4.0
79
+
80
+ - Input "input_image" goes first now, it gives a correct bypass and also it is right to have the main input first;
81
+ - 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:
82
+
83
+ <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%"/>
84
+ <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%"/>
85
+
86
+ - Ability to build and save face models directly from an image:
87
+
88
+ <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%"/>
89
+
90
+ - Both the inputs are optional, just connect one of them according to your workflow; if both is connected - `image` has a priority.
91
+ - Different fixes making this extension better.
92
+
93
+ Thanks to everyone who finds bugs, suggests new features and supports this project!
94
+
95
+ ## Installation
96
+
97
+ <details>
98
+ <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>
99
+
100
+ 1. Close (stop) your SD-WebUI/Comfy Server if it's running
101
+ 2. (For Windows Users):
102
+ - Install [Visual Studio 2022](https://visualstudio.microsoft.com/downloads/) (Community version - you need this step to build Insightface)
103
+ - OR only [VS C++ Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) and select "Desktop Development with C++" under "Workloads -> Desktop & Mobile"
104
+ - OR if you don't want to install VS or VS C++ BT - follow [this steps (sec. I)](#insightfacebuild)
105
+ 3. Go to the `extensions\sd-webui-comfyui\ComfyUI\custom_nodes`
106
+ 4. Open Console or Terminal and run `git clone https://github.com/Gourieff/comfyui-reactor-node`
107
+ 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`
108
+ 6. `python -m pip install -U pip`
109
+ 7. `cd extensions\sd-webui-comfyui\ComfyUI\custom_nodes\comfyui-reactor-node`
110
+ 8. `python install.py`
111
+ 9. Please, wait until the installation process will be finished
112
+ 10. (From the version 0.3.0) Download facerestorers models from the links below and put them into the `extensions\sd-webui-comfyui\ComfyUI\custom_nodes\comfyui-reactor-node\models\facerestore_models` directory:
113
+ - CodeFormer: https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth
114
+ - GFPGAN: https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/GFPGANv1.4.pth
115
+ 11. Run SD WebUI and check console for the message that ReActor Node is running:
116
+ <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"/>
117
+
118
+ 1. Go to the ComfyUI tab and find there ReActor Node inside the menu `ReActor` or by using a search:
119
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/uploads/webui-demo.png?raw=true" alt="webui-demo" width="100%"/>
120
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/uploads/search-demo.png?raw=true" alt="webui-demo" width="1043"/>
121
+
122
+ </details>
123
+
124
+ <details>
125
+ <summary>Standalone (Portable) <a href="https://github.com/comfyanonymous/ComfyUI">ComfyUI</a> for Windows</summary>
126
+
127
+ 1. Do the following:
128
+ - Install [Visual Studio 2022](https://visualstudio.microsoft.com/downloads/) (Community version - you need this step to build Insightface)
129
+ - OR only [VS C++ Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) and select "Desktop Development with C++" under "Workloads -> Desktop & Mobile"
130
+ - OR if you don't want to install VS or VS C++ BT - follow [this steps (sec. I)](#insightfacebuild)
131
+ 2. Go to the `ComfyUI\custom_nodes` directory
132
+ 3. Open Console and run `git clone https://github.com/Gourieff/comfyui-reactor-node`
133
+ 4. Run `install.bat`
134
+ 5. (From the version 0.3.0) Download facerestorers models from the links below and put them into the `ComfyUI\models\facerestore_models` directory:
135
+ - CodeFormer: https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth
136
+ - GFPGAN: https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/GFPGANv1.4.pth
137
+ 6. Run ComfyUI and find there ReActor Node inside the menu `ReActor` or by using a search
138
+
139
+ </details>
140
+
141
+ ## Usage
142
+
143
+ You can find ReActor Nodes inside the menu `ReActor` or by using a search (just type "ReActor" in the search field)
144
+
145
+ List of Nodes:
146
+ - ReActorFaceSwap (Main Node)
147
+ - ReActorLoadFaceModel (Load Face Model)
148
+ - ReActorSaveFaceModel (Save Face Model)
149
+
150
+ Connect all required slots and run the query.
151
+
152
+ ### Main Node Inputs
153
+
154
+ - `input_image` - is an image to be processed (target image, analog of "target image" in the SD WebUI extension);
155
+ - Supported Nodes: "Load Image", "Load Video" or any other nodes providng images as an output;
156
+ - `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);
157
+ - Supported Nodes: "Load Image";
158
+ - `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;
159
+ - Supported Nodes: "Load Face Model";
160
+
161
+ ### Main Node Outputs
162
+
163
+ - `IMAGE` - is an output with the resulted image;
164
+ - Supported Nodes: any nodes which have images as an input;
165
+ - `FACE_MODEL` - is an output providng a source face's model being built during the swapping process;
166
+ - Supported Nodes: "Save Face Model", "ReActor";
167
+
168
+ ### Face Restoration
169
+
170
+ 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.
171
+
172
+ ### Face Indexes
173
+
174
+ ReActor detects faces in images in the following order:<br>left->right, top->bottom
175
+
176
+ And if you need to specify faces, you can set indexes for source and input images.
177
+
178
+ Index of the first detected face is 0.
179
+
180
+ You can set indexes in the order you need.<br>
181
+ 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.
182
+
183
+ ### Genders
184
+
185
+ You can specify the gender to detect in images.<br>
186
+ ReActor will swap a face only if it meets the given condition.
187
+
188
+ ### Face Models
189
+
190
+ 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.
191
+
192
+ To make new models appear in the list of the "Load Face Model" Node - just refresh the page of your ComfyUI web application.<br>
193
+ (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).
194
+
195
+ ## Troubleshooting
196
+
197
+ <a name="insightfacebuild">
198
+
199
+ ### **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:**
200
+
201
+ 1. (ComfyUI Portable) From the root folder check the version of Python:<br>run CMD and type `python_embeded\python.exe -V`
202
+ 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
203
+ 3. From the root folder run:
204
+ - (SD WebUI) CMD and `.\venv\Scripts\activate`
205
+ - (ComfyUI Portable) run CMD
206
+ 4. Then update your PIP:
207
+ - (SD WebUI) `python -m pip install -U pip`
208
+ - (ComfyUI Portable) `python_embeded\python.exe -m pip install -U pip`
209
+ 5. Then install Insightface:
210
+ - (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)
211
+ - (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)
212
+ 6. Enjoy!
213
+
214
+ ### **II. "AttributeError: 'NoneType' object has no attribute 'get'"**
215
+
216
+ This error may occur if there's smth wrong with the model file `inswapper_128.onnx`
217
+
218
+ Try to download it manually from [here](https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128.onnx)
219
+ and put it to the `ComfyUI\models\insightface` replacing existing one
220
+
221
+ ### **III. "reactor.execute() got an unexpected keyword argument 'reference_image'"**
222
+
223
+ This means that input points have been changed with the latest update<br>
224
+ Remove the current ReActor Node from your workflow and add it again
225
+
226
+ ### **IV. ControlNet Aux Node IMPORT failed error when using with ReActor Node**
227
+
228
+ 1. Close ComfyUI if it runs
229
+ 2. Go to the ComfyUI root folder, open CMD there and run:
230
+ - `python_embeded\python.exe -m pip uninstall -y opencv-python opencv-contrib-python opencv-python-headless`
231
+ - `python_embeded\python.exe -m pip install opencv-python==4.7.0.72`
232
+ 3. That's it!
233
+
234
+ <img src="https://github.com/Gourieff/Assets/blob/main/comfyui-reactor-node/uploads/reactor-w-controlnet.png?raw=true" alt="reactor+controlnet" />
235
+
236
+ ### **V. "ModuleNotFoundError: No module named 'basicsr'" or "subprocess-exited-with-error" during future-0.18.3 installation**
237
+
238
+ - Download https://github.com/Gourieff/Assets/raw/main/comfyui-reactor-node/future-0.18.3-py3-none-any.whl<br>
239
+ - Put it to ComfyUI root And run:
240
+
241
+ python_embeded\python.exe -m pip install future-0.18.3-py3-none-any.whl
242
+
243
+ - Then:
244
+
245
+ python_embeded\python.exe -m pip install basicsr
246
+
247
+ ### **VI. "fatal: fetch-pack: invalid index-pack output" when you try to `git clone` the repository"**
248
+
249
+ Try to clone with `--depth=1` (last commit only):
250
+
251
+ git clone --depth=1 https://github.com/Gourieff/comfyui-reactor-node
252
+
253
+ Then retrieve the rest (if you need):
254
+
255
+ git fetch --unshallow
256
+
257
+ ## Updating
258
+
259
+ 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
260
+
261
+ ### Disclaimer
262
+
263
+ 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.
264
+
265
+ The developers of this software are aware of its possible unethical applicaitons 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.
266
+
267
+ 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.**
268
+
269
+ By using this extension you are agree not to create any content that:
270
+ - violates any laws;
271
+ - causes any harm to a person or persons;
272
+ - propogates (spreads) any information (both public or personal) or images (both public or personal) which could be meant for harm;
273
+ - spreads misinformation;
274
+ - targets vulnerable groups of people.
275
+
276
+ 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:
277
+
278
+ [From insighface licence](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.
279
+
280
+ 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.
281
+
282
+ 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.
283
+
284
+ ### Models Hashsum
285
+
286
+ #### Safe-to-use models have the folowing hash:
287
+
288
+ inswapper_128.onnx
289
+ ```
290
+ MD5:a3a155b90354160350efd66fed6b3d80
291
+ SHA256:e4a3f08c753cb72d04e10aa0f7dbe3deebbf39567d4ead6dce08e98aa49e16af
292
+ ```
293
+
294
+ 1k3d68.onnx
295
+
296
+ ```
297
+ MD5:6fb94fcdb0055e3638bf9158e6a108f4
298
+ SHA256:df5c06b8a0c12e422b2ed8947b8869faa4105387f199c477af038aa01f9a45cc
299
+ ```
300
+
301
+ 2d106det.onnx
302
+
303
+ ```
304
+ MD5:a3613ef9eb3662b4ef88eb90db1fcf26
305
+ SHA256:f001b856447c413801ef5c42091ed0cd516fcd21f2d6b79635b1e733a7109dbf
306
+ ```
307
+
308
+ det_10g.onnx
309
+
310
+ ```
311
+ MD5:4c10eef5c9e168357a16fdd580fa8371
312
+ SHA256:5838f7fe053675b1c7a08b633df49e7af5495cee0493c7dcf6697200b85b5b91
313
+ ```
314
+
315
+ genderage.onnx
316
+
317
+ ```
318
+ MD5:81c77ba87ab38163b0dec6b26f8e2af2
319
+ SHA256:4fde69b1c810857b88c64a335084f1c3fe8f01246c9a191b48c7bb756d6652fb
320
+ ```
321
+
322
+ w600k_r50.onnx
323
+
324
+ ```
325
+ MD5:80248d427976241cbd1343889ed132b3
326
+ SHA256:4c06341c33c2ca1f86781dab0e829f88ad5b64be9fba56e56bc9ebdefc619e43
327
+ ```
328
+
329
+ **Please check hashsums if you download these models from unverified (or untrusted) sources**
330
+
331
+ <a name="credits">
332
+
333
+ ## Thanks and Credits
334
+
335
+ <details>
336
+ <summary><a>Click to expand</a></summary>
337
+
338
+ <br>
339
+
340
+ |file|source|license|
341
+ |----|------|-------|
342
+ |[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) |
343
+ | [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) |
344
+ | [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) |
345
+ | [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) |
346
+ | [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) |
347
+ | [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) |
348
+
349
+ [BasicSR](https://github.com/XPixelGroup/BasicSR) - [@XPixelGroup](https://github.com/XPixelGroup) <br>
350
+ [facexlib](https://github.com/xinntao/facexlib) - [@xinntao](https://github.com/xinntao) <br>
351
+
352
+ [@s0md3v](https://github.com/s0md3v), [@henryruhs](https://github.com/henryruhs) - the original Roop App <br>
353
+ [@ssitu](https://github.com/ssitu) - the first version of [ComfyUI_roop](https://github.com/ssitu/ComfyUI_roop) extension
354
+
355
+ </details>
356
+
357
+ <a name="note">
358
+
359
+ ### Note!
360
+
361
+ **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**
362
+
363
+ **ReActor Node gets updates from time to time, new functions appears and old node can work with errors or not work at all**
__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)
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
install.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: # CU12
75
+ if not is_installed(ort,"1.17.0",False):
76
+ run_pip(ort,"--extra-index-url", "https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/")
77
+ elif not is_installed(ort,"1.16.1",False):
78
+ run_pip(ort, "-U")
79
+ except Exception as e:
80
+ print(e)
81
+ print(f"Warning: Failed to install {ort}, ReActor will not work.")
82
+ raise e
83
+ strict = True
84
+ for package in file:
85
+ package_version = None
86
+ try:
87
+ package = package.strip()
88
+ if "==" in package:
89
+ package_version = package.split('==')[1]
90
+ elif ">=" in package:
91
+ package_version = package.split('>=')[1]
92
+ strict = False
93
+ if not is_installed(package,package_version,strict):
94
+ run_pip(package)
95
+ except Exception as e:
96
+ print(e)
97
+ print(f"Warning: Failed to install {package}, ReActor will not work.")
98
+ raise e
99
+ print("Ok")
nodes.py ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, glob, sys
2
+
3
+ import torch
4
+ from torchvision.transforms.functional import normalize
5
+ import numpy as np
6
+ import cv2
7
+
8
+ from modules.processing import StableDiffusionProcessingImg2Img
9
+ from comfy_extras.chainner_models import model_loading
10
+ import comfy.model_management as model_management
11
+ import comfy.utils
12
+ import folder_paths
13
+
14
+ import scripts.reactor_version
15
+ from scripts.reactor_faceswap import (
16
+ FaceSwapScript,
17
+ get_models,
18
+ get_current_faces_model,
19
+ analyze_faces,
20
+ half_det_size
21
+ )
22
+ from scripts.reactor_logger import logger
23
+ from reactor_utils import (
24
+ batch_tensor_to_pil,
25
+ batched_pil_to_tensor,
26
+ tensor_to_pil,
27
+ img2tensor,
28
+ tensor2img,
29
+ save_face_model,
30
+ load_face_model,
31
+ download
32
+ )
33
+ from reactor_log_patch import apply_logging_patch
34
+ from r_facelib.utils.face_restoration_helper import FaceRestoreHelper
35
+ from r_basicsr.utils.registry import ARCH_REGISTRY
36
+ import scripts.r_archs.codeformer_arch
37
+
38
+
39
+ models_dir = folder_paths.models_dir
40
+ REACTOR_MODELS_PATH = os.path.join(models_dir, "reactor")
41
+ FACE_MODELS_PATH = os.path.join(REACTOR_MODELS_PATH, "faces")
42
+
43
+ if not os.path.exists(REACTOR_MODELS_PATH):
44
+ os.makedirs(REACTOR_MODELS_PATH)
45
+ if not os.path.exists(FACE_MODELS_PATH):
46
+ os.makedirs(FACE_MODELS_PATH)
47
+
48
+ dir_facerestore_models = os.path.join(models_dir, "facerestore_models")
49
+ os.makedirs(dir_facerestore_models, exist_ok=True)
50
+ folder_paths.folder_names_and_paths["facerestore_models"] = ([dir_facerestore_models], folder_paths.supported_pt_extensions)
51
+
52
+
53
+ def get_facemodels():
54
+ models_path = os.path.join(FACE_MODELS_PATH, "*")
55
+ models = glob.glob(models_path)
56
+ models = [x for x in models if x.endswith(".safetensors")]
57
+ return models
58
+
59
+ def get_restorers():
60
+ models_path = os.path.join(models_dir, "facerestore_models/*")
61
+ models = glob.glob(models_path)
62
+ models = [x for x in models if x.endswith(".pth")]
63
+ if len(models) == 0:
64
+ fr_urls = [
65
+ "https://huggingface.co/datasets/Gourieff/ReActor/resolve/main/models/facerestore_models/GFPGANv1.3.pth",
66
+ "https://huggingface.co/datasets/Gourieff/ReActor/resolve/main/models/facerestore_models/GFPGANv1.4.pth",
67
+ "https://huggingface.co/datasets/Gourieff/ReActor/resolve/main/models/facerestore_models/codeformer-v0.1.0.pth"
68
+ ]
69
+ for model_url in fr_urls:
70
+ model_name = os.path.basename(model_url)
71
+ model_path = os.path.join(dir_facerestore_models, model_name)
72
+ download(model_url, model_path, model_name)
73
+ models = glob.glob(models_path)
74
+ models = [x for x in models if x.endswith(".pth")]
75
+ return models
76
+
77
+ def get_model_names(get_models):
78
+ models = get_models()
79
+ names = ["none"]
80
+ for x in models:
81
+ names.append(os.path.basename(x))
82
+ return names
83
+
84
+ def model_names():
85
+ models = get_models()
86
+ return {os.path.basename(x): x for x in models}
87
+
88
+
89
+ class reactor:
90
+ @classmethod
91
+ def INPUT_TYPES(s):
92
+ return {
93
+ "required": {
94
+ "enabled": ("BOOLEAN", {"default": True, "label_off": "OFF", "label_on": "ON"}),
95
+ "input_image": ("IMAGE",),
96
+ "swap_model": (list(model_names().keys()),),
97
+ "facedetection": (["retinaface_resnet50", "retinaface_mobile0.25", "YOLOv5l", "YOLOv5n"],),
98
+ "face_restore_model": (get_model_names(get_restorers),),
99
+ "face_restore_visibility": ("FLOAT", {"default": 1, "min": 0.1, "max": 1, "step": 0.05}),
100
+ "codeformer_weight": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1, "step": 0.05}),
101
+ "detect_gender_input": (["no","female","male"], {"default": "no"}),
102
+ "detect_gender_source": (["no","female","male"], {"default": "no"}),
103
+ "input_faces_index": ("STRING", {"default": "0"}),
104
+ "source_faces_index": ("STRING", {"default": "0"}),
105
+ "console_log_level": ([0, 1, 2], {"default": 1}),
106
+ },
107
+ "optional": {
108
+ "source_image": ("IMAGE",),
109
+ "face_model": ("FACE_MODEL",),
110
+ }
111
+ }
112
+
113
+ RETURN_TYPES = ("IMAGE","FACE_MODEL")
114
+ FUNCTION = "execute"
115
+ CATEGORY = "ReActor"
116
+
117
+ def __init__(self):
118
+ self.face_helper = None
119
+
120
+ def restore_face(
121
+ self,
122
+ input_image,
123
+ face_restore_model,
124
+ face_restore_visibility,
125
+ codeformer_weight,
126
+ facedetection
127
+ ):
128
+
129
+ result = input_image
130
+
131
+ if face_restore_model != "none" and not model_management.processing_interrupted():
132
+
133
+ logger.status(f"Restoring with {face_restore_model}")
134
+
135
+ model_path = folder_paths.get_full_path("facerestore_models", face_restore_model)
136
+
137
+ device = model_management.get_torch_device()
138
+
139
+ if "codeformer" in face_restore_model.lower():
140
+
141
+ codeformer_net = ARCH_REGISTRY.get("CodeFormer")(
142
+ dim_embd=512,
143
+ codebook_size=1024,
144
+ n_head=8,
145
+ n_layers=9,
146
+ connect_list=["32", "64", "128", "256"],
147
+ ).to(device)
148
+ checkpoint = torch.load(model_path)["params_ema"]
149
+ codeformer_net.load_state_dict(checkpoint)
150
+ facerestore_model = codeformer_net.eval()
151
+
152
+ else:
153
+
154
+ sd = comfy.utils.load_torch_file(model_path, safe_load=True)
155
+ facerestore_model = model_loading.load_state_dict(sd).eval()
156
+
157
+ facerestore_model.to(device)
158
+
159
+ if self.face_helper is None:
160
+ self.face_helper = FaceRestoreHelper(1, face_size=512, crop_ratio=(1, 1), det_model=facedetection, save_ext='png', use_parse=True, device=device)
161
+
162
+ image_np = 255. * result.cpu().numpy()
163
+
164
+ total_images = image_np.shape[0]
165
+ out_images = np.ndarray(shape=image_np.shape)
166
+
167
+ for i in range(total_images):
168
+ cur_image_np = image_np[i,:, :, ::-1]
169
+
170
+ original_resolution = cur_image_np.shape[0:2]
171
+
172
+ if facerestore_model is None or self.face_helper is None:
173
+ return result
174
+
175
+ self.face_helper.clean_all()
176
+ self.face_helper.read_image(cur_image_np)
177
+ self.face_helper.get_face_landmarks_5(only_center_face=False, resize=640, eye_dist_threshold=5)
178
+ self.face_helper.align_warp_face()
179
+
180
+ restored_face = None
181
+ for idx, cropped_face in enumerate(self.face_helper.cropped_faces):
182
+ cropped_face_t = img2tensor(cropped_face / 255., bgr2rgb=True, float32=True)
183
+ normalize(cropped_face_t, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
184
+ cropped_face_t = cropped_face_t.unsqueeze(0).to(device)
185
+
186
+ try:
187
+ with torch.no_grad():
188
+ output = facerestore_model(cropped_face_t, w=codeformer_weight)[0] if "codeformer" in face_restore_model.lower() else facerestore_model(cropped_face_t)[0]
189
+ restored_face = tensor2img(output, rgb2bgr=True, min_max=(-1, 1))
190
+ del output
191
+ torch.cuda.empty_cache()
192
+ except Exception as error:
193
+ print(f'\tFailed inference for CodeFormer: {error}', file=sys.stderr)
194
+ restored_face = tensor2img(cropped_face_t, rgb2bgr=True, min_max=(-1, 1))
195
+
196
+ if face_restore_visibility < 1:
197
+ restored_face = cropped_face * (1 - face_restore_visibility) + restored_face * face_restore_visibility
198
+
199
+ restored_face = restored_face.astype('uint8')
200
+ self.face_helper.add_restored_face(restored_face)
201
+
202
+ self.face_helper.get_inverse_affine(None)
203
+
204
+ restored_img = self.face_helper.paste_faces_to_input_image()
205
+ restored_img = restored_img[:, :, ::-1]
206
+
207
+ if original_resolution != restored_img.shape[0:2]:
208
+ 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_LINEAR)
209
+
210
+ self.face_helper.clean_all()
211
+
212
+ out_images[i] = restored_img
213
+
214
+ restored_img_np = np.array(out_images).astype(np.float32) / 255.0
215
+ restored_img_tensor = torch.from_numpy(restored_img_np)
216
+
217
+ result = restored_img_tensor
218
+
219
+ return result
220
+
221
+ 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):
222
+ apply_logging_patch(console_log_level)
223
+
224
+ if not enabled:
225
+ return (input_image,face_model)
226
+ elif source_image is None and face_model is None:
227
+ logger.error("Please provide 'source_image' or `face_model`")
228
+ return (input_image,face_model)
229
+
230
+ if face_model == "none":
231
+ face_model = None
232
+
233
+ script = FaceSwapScript()
234
+ pil_images = batch_tensor_to_pil(input_image)
235
+ if source_image is not None:
236
+ source = tensor_to_pil(source_image)
237
+ else:
238
+ source = None
239
+ p = StableDiffusionProcessingImg2Img(pil_images)
240
+ script.process(
241
+ p=p,
242
+ img=source,
243
+ enable=True,
244
+ source_faces_index=source_faces_index,
245
+ faces_index=input_faces_index,
246
+ model=swap_model,
247
+ swap_in_source=True,
248
+ swap_in_generated=True,
249
+ gender_source=detect_gender_source,
250
+ gender_target=detect_gender_input,
251
+ face_model=face_model,
252
+ )
253
+ result = batched_pil_to_tensor(p.init_images)
254
+
255
+ if face_model is None:
256
+ current_face_model = get_current_faces_model()
257
+ face_model_to_provide = current_face_model[0] if (current_face_model is not None and len(current_face_model) > 0) else face_model
258
+ else:
259
+ face_model_to_provide = face_model
260
+
261
+ result = reactor.restore_face(self,result,face_restore_model,face_restore_visibility,codeformer_weight,facedetection)
262
+
263
+ return (result,face_model_to_provide)
264
+
265
+
266
+ class LoadFaceModel:
267
+ @classmethod
268
+ def INPUT_TYPES(s):
269
+ return {
270
+ "required": {
271
+ "face_model": (get_model_names(get_facemodels),),
272
+ }
273
+ }
274
+
275
+ RETURN_TYPES = ("FACE_MODEL",)
276
+ FUNCTION = "load_model"
277
+ CATEGORY = "ReActor"
278
+
279
+ def load_model(self, face_model):
280
+ self.face_model = face_model
281
+ self.face_models_path = FACE_MODELS_PATH
282
+ if self.face_model != "none":
283
+ face_model_path = os.path.join(self.face_models_path, self.face_model)
284
+ out = load_face_model(face_model_path)
285
+ else:
286
+ out = None
287
+ return (out, )
288
+
289
+
290
+ class SaveFaceModel:
291
+ def __init__(self):
292
+ self.output_dir = FACE_MODELS_PATH
293
+
294
+ @classmethod
295
+ def INPUT_TYPES(s):
296
+ return {
297
+ "required": {
298
+ "save_mode": ("BOOLEAN", {"default": True, "label_off": "OFF", "label_on": "ON"}),
299
+ "face_model_name": ("STRING", {"default": "default"}),
300
+ "select_face_index": ("INT", {"default": 0, "min": 0}),
301
+ },
302
+ "optional": {
303
+ "image": ("IMAGE",),
304
+ "face_model": ("FACE_MODEL",),
305
+ }
306
+ }
307
+
308
+ RETURN_TYPES = ()
309
+ FUNCTION = "save_model"
310
+
311
+ OUTPUT_NODE = True
312
+
313
+ CATEGORY = "ReActor"
314
+
315
+ def save_model(self, save_mode, face_model_name, select_face_index, image=None, face_model=None, det_size=(640, 640)):
316
+ if save_mode and image is not None:
317
+ source = tensor_to_pil(image)
318
+ source = cv2.cvtColor(np.array(source), cv2.COLOR_RGB2BGR)
319
+ apply_logging_patch(1)
320
+ logger.status("Building Face Model...")
321
+ face_model_raw = analyze_faces(source, det_size)
322
+ if len(face_model_raw) == 0:
323
+ det_size_half = half_det_size(det_size)
324
+ face_model_raw = analyze_faces(source, det_size_half)
325
+ try:
326
+ face_model = face_model_raw[select_face_index]
327
+ except:
328
+ logger.error("No face(s) found")
329
+ return face_model_name
330
+ logger.status("--Done!--")
331
+ if save_mode and (face_model != "none" or face_model is not None):
332
+ face_model_path = os.path.join(self.output_dir, face_model_name + ".safetensors")
333
+ save_face_model(face_model,face_model_path)
334
+ if image is None and face_model is None:
335
+ logger.error("Please provide `face_model` or `image`")
336
+ return face_model_name
337
+
338
+
339
+ class RestoreFace:
340
+ @classmethod
341
+ def INPUT_TYPES(s):
342
+ return {
343
+ "required": {
344
+ "image": ("IMAGE",),
345
+ "facedetection": (["retinaface_resnet50", "retinaface_mobile0.25", "YOLOv5l", "YOLOv5n"],),
346
+ "model": (get_model_names(get_restorers),),
347
+ "visibility": ("FLOAT", {"default": 1, "min": 0.0, "max": 1, "step": 0.05}),
348
+ "codeformer_weight": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1, "step": 0.05}),
349
+ },
350
+ }
351
+
352
+ RETURN_TYPES = ("IMAGE",)
353
+ FUNCTION = "execute"
354
+ CATEGORY = "ReActor"
355
+
356
+ def __init__(self):
357
+ self.face_helper = None
358
+
359
+ def execute(self, image, model, visibility, codeformer_weight, facedetection):
360
+ result = reactor.restore_face(self,image,model,visibility,codeformer_weight,facedetection)
361
+ return (result,)
362
+
363
+ import numpy as np
364
+ from ultralytics import YOLO
365
+ from PIL import Image
366
+
367
+ # Load a pretrained YOLOv8n model
368
+ model = YOLO(task='detect', model='/root/autodl-tmp/ComfyUI/custom_nodes/comfyui-reactor-node/yolov8m_200e.pt')
369
+
370
+ class Mynode_2:
371
+ @classmethod
372
+ def INPUT_TYPES(s):
373
+ return {
374
+ "required": {
375
+ "input_image": ("IMAGE",),
376
+ "source_image": ("IMAGE",),
377
+ },
378
+ "optional": {
379
+
380
+ }
381
+ }
382
+
383
+ CATEGORY = "ReActor"
384
+ RETURN_TYPES = ("IMAGE",)
385
+ FUNCTION = "method"
386
+
387
+ def method(self, input_image, source_image):
388
+ input_image_tmp = input_image.squeeze()
389
+ # Pytorch张量转PIL对象
390
+ input_image_pil = Image.fromarray(
391
+ np.clip(255. * input_image_tmp.cpu().numpy(), 0, 255).astype(np.uint8)).convert('RGBA')
392
+
393
+ # Run inference on an image
394
+ results = model.predict(source=input_image_pil, conf=0.5)
395
+ # View results
396
+ tmp = results[0].boxes.shape
397
+ judge_face = tmp[0]
398
+ print(judge_face)
399
+
400
+ if judge_face == 0: # 等于0就是没检测出脸
401
+
402
+ return (input_image,)
403
+
404
+ else:
405
+ enabled = True
406
+
407
+ swap_model = "inswapper_128.onnx"
408
+ facedetection = "retinaface_resnet50"
409
+ face_restore_model = "GFPGANv1.4.pth"
410
+ face_restore_visibility = 1
411
+ codeformer_weight = 0.5
412
+ detect_gender_input = "no"
413
+ detect_gender_source = "no"
414
+ input_faces_index = "0"
415
+ source_faces_index = "0"
416
+ console_log_level = 1
417
+
418
+ class_reactor = reactor()
419
+ change_face_img, face_model = class_reactor.execute(enabled, input_image, swap_model, detect_gender_source, detect_gender_input,
420
+ source_faces_index, input_faces_index, console_log_level, face_restore_model,
421
+ face_restore_visibility, codeformer_weight, facedetection, source_image=source_image,
422
+ face_model=None)
423
+
424
+ return (change_face_img,)
425
+
426
+ NODE_CLASS_MAPPINGS = {
427
+ "ReActorFaceSwap": reactor,
428
+ "ReActorLoadFaceModel": LoadFaceModel,
429
+ "ReActorSaveFaceModel": SaveFaceModel,
430
+ "ReActorRestoreFace": RestoreFace,
431
+ "face_detect": Mynode_2,
432
+ }
433
+
434
+ NODE_DISPLAY_NAME_MAPPINGS = {
435
+ "ReActorFaceSwap": "ReActor - Fast Face Swap",
436
+ "ReActorLoadFaceModel": "Load Face Model",
437
+ "ReActorSaveFaceModel": "Save Face Model",
438
+ "ReActorRestoreFace": "Restore Face",
439
+ "face_detect": "face_detect - Reactor",
440
+ }
reactor_log_patch.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os.path as osp
2
+ import glob
3
+ import logging
4
+ import insightface
5
+ from insightface.model_zoo.model_zoo import ModelRouter, PickableInferenceSession
6
+ from insightface.model_zoo.retinaface import RetinaFace
7
+ from insightface.model_zoo.landmark import Landmark
8
+ from insightface.model_zoo.attribute import Attribute
9
+ from insightface.model_zoo.inswapper import INSwapper
10
+ from insightface.model_zoo.arcface_onnx import ArcFaceONNX
11
+ from insightface.app import FaceAnalysis
12
+ from insightface.utils import DEFAULT_MP_NAME, ensure_available
13
+ from insightface.model_zoo import model_zoo
14
+ import onnxruntime
15
+ import onnx
16
+ from onnx import numpy_helper
17
+ from scripts.reactor_logger import logger
18
+
19
+
20
+ def patched_get_model(self, **kwargs):
21
+ session = PickableInferenceSession(self.onnx_file, **kwargs)
22
+ inputs = session.get_inputs()
23
+ input_cfg = inputs[0]
24
+ input_shape = input_cfg.shape
25
+ outputs = session.get_outputs()
26
+
27
+ if len(outputs) >= 5:
28
+ return RetinaFace(model_file=self.onnx_file, session=session)
29
+ elif input_shape[2] == 192 and input_shape[3] == 192:
30
+ return Landmark(model_file=self.onnx_file, session=session)
31
+ elif input_shape[2] == 96 and input_shape[3] == 96:
32
+ return Attribute(model_file=self.onnx_file, session=session)
33
+ elif len(inputs) == 2 and input_shape[2] == 128 and input_shape[3] == 128:
34
+ return INSwapper(model_file=self.onnx_file, session=session)
35
+ elif input_shape[2] == input_shape[3] and input_shape[2] >= 112 and input_shape[2] % 16 == 0:
36
+ return ArcFaceONNX(model_file=self.onnx_file, session=session)
37
+ else:
38
+ return None
39
+
40
+
41
+ def patched_faceanalysis_init(self, name=DEFAULT_MP_NAME, root='~/.insightface', allowed_modules=None, **kwargs):
42
+ onnxruntime.set_default_logger_severity(3)
43
+ self.models = {}
44
+ self.model_dir = ensure_available('models', name, root=root)
45
+ onnx_files = glob.glob(osp.join(self.model_dir, '*.onnx'))
46
+ onnx_files = sorted(onnx_files)
47
+ for onnx_file in onnx_files:
48
+ model = model_zoo.get_model(onnx_file, **kwargs)
49
+ if model is None:
50
+ print('model not recognized:', onnx_file)
51
+ elif allowed_modules is not None and model.taskname not in allowed_modules:
52
+ print('model ignore:', onnx_file, model.taskname)
53
+ del model
54
+ elif model.taskname not in self.models and (allowed_modules is None or model.taskname in allowed_modules):
55
+ self.models[model.taskname] = model
56
+ else:
57
+ print('duplicated model task type, ignore:', onnx_file, model.taskname)
58
+ del model
59
+ assert 'detection' in self.models
60
+ self.det_model = self.models['detection']
61
+
62
+
63
+ def patched_faceanalysis_prepare(self, ctx_id, det_thresh=0.5, det_size=(640, 640)):
64
+ self.det_thresh = det_thresh
65
+ assert det_size is not None
66
+ self.det_size = det_size
67
+ for taskname, model in self.models.items():
68
+ if taskname == 'detection':
69
+ model.prepare(ctx_id, input_size=det_size, det_thresh=det_thresh)
70
+ else:
71
+ model.prepare(ctx_id)
72
+
73
+
74
+ def patched_inswapper_init(self, model_file=None, session=None):
75
+ self.model_file = model_file
76
+ self.session = session
77
+ model = onnx.load(self.model_file)
78
+ graph = model.graph
79
+ self.emap = numpy_helper.to_array(graph.initializer[-1])
80
+ self.input_mean = 0.0
81
+ self.input_std = 255.0
82
+ if self.session is None:
83
+ self.session = onnxruntime.InferenceSession(self.model_file, None)
84
+ inputs = self.session.get_inputs()
85
+ self.input_names = []
86
+ for inp in inputs:
87
+ self.input_names.append(inp.name)
88
+ outputs = self.session.get_outputs()
89
+ output_names = []
90
+ for out in outputs:
91
+ output_names.append(out.name)
92
+ self.output_names = output_names
93
+ assert len(self.output_names) == 1
94
+ input_cfg = inputs[0]
95
+ input_shape = input_cfg.shape
96
+ self.input_shape = input_shape
97
+ self.input_size = tuple(input_shape[2:4][::-1])
98
+
99
+
100
+ def patch_insightface(get_model, faceanalysis_init, faceanalysis_prepare, inswapper_init):
101
+ insightface.model_zoo.model_zoo.ModelRouter.get_model = get_model
102
+ insightface.app.FaceAnalysis.__init__ = faceanalysis_init
103
+ insightface.app.FaceAnalysis.prepare = faceanalysis_prepare
104
+ insightface.model_zoo.inswapper.INSwapper.__init__ = inswapper_init
105
+
106
+
107
+ original_functions = [ModelRouter.get_model, FaceAnalysis.__init__, FaceAnalysis.prepare, INSwapper.__init__]
108
+ patched_functions = [patched_get_model, patched_faceanalysis_init, patched_faceanalysis_prepare, patched_inswapper_init]
109
+
110
+
111
+ def apply_logging_patch(console_log_level):
112
+ if console_log_level == 0:
113
+ patch_insightface(*patched_functions)
114
+ logger.setLevel(logging.WARNING)
115
+ elif console_log_level == 1:
116
+ patch_insightface(*patched_functions)
117
+ logger.setLevel(logging.STATUS)
118
+ elif console_log_level == 2:
119
+ patch_insightface(*original_functions)
120
+ logger.setLevel(logging.INFO)
reactor_utils.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from PIL import Image
3
+ import numpy as np
4
+ import torch
5
+ import cv2
6
+ import logging
7
+ import hashlib
8
+ from insightface.app.common import Face
9
+ from safetensors.torch import save_file, safe_open
10
+ from tqdm import tqdm
11
+ import urllib.request
12
+
13
+
14
+ def tensor_to_pil(img_tensor, batch_index=0):
15
+ # Convert tensor of shape [batch_size, channels, height, width] at the batch_index to PIL Image
16
+ img_tensor = img_tensor[batch_index].unsqueeze(0)
17
+ i = 255. * img_tensor.cpu().numpy()
18
+ img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8).squeeze())
19
+ return img
20
+
21
+
22
+ def batch_tensor_to_pil(img_tensor):
23
+ # Convert tensor of shape [batch_size, channels, height, width] to a list of PIL Images
24
+ return [tensor_to_pil(img_tensor, i) for i in range(img_tensor.shape[0])]
25
+
26
+
27
+ def pil_to_tensor(image):
28
+ # Takes a PIL image and returns a tensor of shape [1, height, width, channels]
29
+ image = np.array(image).astype(np.float32) / 255.0
30
+ image = torch.from_numpy(image).unsqueeze(0)
31
+ if len(image.shape) == 3: # If the image is grayscale, add a channel dimension
32
+ image = image.unsqueeze(-1)
33
+ return image
34
+
35
+
36
+ def batched_pil_to_tensor(images):
37
+ # Takes a list of PIL images and returns a tensor of shape [batch_size, height, width, channels]
38
+ return torch.cat([pil_to_tensor(image) for image in images], dim=0)
39
+
40
+
41
+ def img2tensor(imgs, bgr2rgb=True, float32=True):
42
+
43
+ def _totensor(img, bgr2rgb, float32):
44
+ if img.shape[2] == 3 and bgr2rgb:
45
+ if img.dtype == 'float64':
46
+ img = img.astype('float32')
47
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
48
+ img = torch.from_numpy(img.transpose(2, 0, 1))
49
+ if float32:
50
+ img = img.float()
51
+ return img
52
+
53
+ if isinstance(imgs, list):
54
+ return [_totensor(img, bgr2rgb, float32) for img in imgs]
55
+ else:
56
+ return _totensor(imgs, bgr2rgb, float32)
57
+
58
+
59
+ def tensor2img(tensor, rgb2bgr=True, out_type=np.uint8, min_max=(0, 1)):
60
+
61
+ if not (torch.is_tensor(tensor) or (isinstance(tensor, list) and all(torch.is_tensor(t) for t in tensor))):
62
+ raise TypeError(f'tensor or list of tensors expected, got {type(tensor)}')
63
+
64
+ if torch.is_tensor(tensor):
65
+ tensor = [tensor]
66
+ result = []
67
+ for _tensor in tensor:
68
+ _tensor = _tensor.squeeze(0).float().detach().cpu().clamp_(*min_max)
69
+ _tensor = (_tensor - min_max[0]) / (min_max[1] - min_max[0])
70
+
71
+ n_dim = _tensor.dim()
72
+ if n_dim == 4:
73
+ img_np = make_grid(_tensor, nrow=int(math.sqrt(_tensor.size(0))), normalize=False).numpy()
74
+ img_np = img_np.transpose(1, 2, 0)
75
+ if rgb2bgr:
76
+ img_np = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)
77
+ elif n_dim == 3:
78
+ img_np = _tensor.numpy()
79
+ img_np = img_np.transpose(1, 2, 0)
80
+ if img_np.shape[2] == 1: # gray image
81
+ img_np = np.squeeze(img_np, axis=2)
82
+ else:
83
+ if rgb2bgr:
84
+ img_np = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)
85
+ elif n_dim == 2:
86
+ img_np = _tensor.numpy()
87
+ else:
88
+ raise TypeError('Only support 4D, 3D or 2D tensor. ' f'But received with dimension: {n_dim}')
89
+ if out_type == np.uint8:
90
+ # Unlike MATLAB, numpy.unit8() WILL NOT round by default.
91
+ img_np = (img_np * 255.0).round()
92
+ img_np = img_np.astype(out_type)
93
+ result.append(img_np)
94
+ if len(result) == 1:
95
+ result = result[0]
96
+ return result
97
+
98
+ def download(url, path, name):
99
+ request = urllib.request.urlopen(url)
100
+ total = int(request.headers.get('Content-Length', 0))
101
+ with tqdm(total=total, desc=f'[ReActor] Downloading {name} to {path}', unit='B', unit_scale=True, unit_divisor=1024) as progress:
102
+ urllib.request.urlretrieve(url, path, reporthook=lambda count, block_size, total_size: progress.update(block_size))
103
+
104
+ def move_path(old_path, new_path):
105
+ if os.path.exists(old_path):
106
+ try:
107
+ models = os.listdir(old_path)
108
+ for model in models:
109
+ move_old_path = os.path.join(old_path, model)
110
+ move_new_path = os.path.join(new_path, model)
111
+ os.rename(move_old_path, move_new_path)
112
+ os.rmdir(old_path)
113
+ except Exception as e:
114
+ print(f"Error: {e}")
115
+ new_path = old_path
116
+
117
+ def addLoggingLevel(levelName, levelNum, methodName=None):
118
+ if not methodName:
119
+ methodName = levelName.lower()
120
+
121
+ def logForLevel(self, message, *args, **kwargs):
122
+ if self.isEnabledFor(levelNum):
123
+ self._log(levelNum, message, args, **kwargs)
124
+
125
+ def logToRoot(message, *args, **kwargs):
126
+ logging.log(levelNum, message, *args, **kwargs)
127
+
128
+ logging.addLevelName(levelNum, levelName)
129
+ setattr(logging, levelName, levelNum)
130
+ setattr(logging.getLoggerClass(), methodName, logForLevel)
131
+ setattr(logging, methodName, logToRoot)
132
+
133
+ def get_image_md5hash(image: Image.Image):
134
+ md5hash = hashlib.md5(image.tobytes())
135
+ return md5hash.hexdigest()
136
+
137
+ def save_face_model(face: Face, filename: str) -> None:
138
+ try:
139
+ tensors = {
140
+ "bbox": torch.tensor(face["bbox"]),
141
+ "kps": torch.tensor(face["kps"]),
142
+ "det_score": torch.tensor(face["det_score"]),
143
+ "landmark_3d_68": torch.tensor(face["landmark_3d_68"]),
144
+ "pose": torch.tensor(face["pose"]),
145
+ "landmark_2d_106": torch.tensor(face["landmark_2d_106"]),
146
+ "embedding": torch.tensor(face["embedding"]),
147
+ "gender": torch.tensor(face["gender"]),
148
+ "age": torch.tensor(face["age"]),
149
+ }
150
+ save_file(tensors, filename)
151
+ print(f"Face model has been saved to '{filename}'")
152
+ except Exception as e:
153
+ print(f"Error: {e}")
154
+
155
+ def load_face_model(filename: str):
156
+ face = {}
157
+ with safe_open(filename, framework="pt") as f:
158
+ for k in f.keys():
159
+ face[k] = f.get_tensor(k).numpy()
160
+ return Face(face)
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ insightface==0.7.3
2
+ onnx>=1.14.0
3
+ opencv-python>=4.7.0.72
4
+ numpy