supArs commited on
Commit
43adbb1
·
1 Parent(s): 252f465

Upload 48 files

Browse files
.flake8 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [flake8]
2
+ select = E3, E4, F
3
+ per-file-ignores = roop/core.py:E402
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ docs/screenshot.png filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
11
+ software and other kinds of works, specifically designed to ensure
12
+ cooperation with the community in the case of network server software.
13
+
14
+ The licenses for most software and other practical works are designed
15
+ to take away your freedom to share and change the works. By contrast,
16
+ our General Public Licenses are intended to guarantee your freedom to
17
+ share and change all versions of a program--to make sure it remains free
18
+ software for all its users.
19
+
20
+ When we speak of free software, we are referring to freedom, not
21
+ price. Our General Public Licenses are designed to make sure that you
22
+ have the freedom to distribute copies of free software (and charge for
23
+ them if you wish), that you receive source code or can get it if you
24
+ want it, that you can change the software or use pieces of it in new
25
+ free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights
28
+ with two steps: (1) assert copyright on the software, and (2) offer
29
+ you this License which gives you legal permission to copy, distribute
30
+ and/or modify the software.
31
+
32
+ A secondary benefit of defending all users' freedom is that
33
+ improvements made in alternate versions of the program, if they
34
+ receive widespread use, become available for other developers to
35
+ incorporate. Many developers of free software are heartened and
36
+ encouraged by the resulting cooperation. However, in the case of
37
+ software used on network servers, this result may fail to come about.
38
+ The GNU General Public License permits making a modified version and
39
+ letting the public access it on a server without ever releasing its
40
+ source code to the public.
41
+
42
+ The GNU Affero General Public License is designed specifically to
43
+ ensure that, in such cases, the modified source code becomes available
44
+ to the community. It requires the operator of a network server to
45
+ provide the source code of the modified version running there to the
46
+ users of that server. Therefore, public use of a modified version, on
47
+ a publicly accessible server, gives the public access to the source
48
+ code of the modified version.
49
+
50
+ An older license, called the Affero General Public License and
51
+ published by Affero, was designed to accomplish similar goals. This is
52
+ a different license, not a version of the Affero GPL, but Affero has
53
+ released a new version of the Affero GPL which permits relicensing under
54
+ this license.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ TERMS AND CONDITIONS
60
+
61
+ 0. Definitions.
62
+
63
+ "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+ "Copyright" also means copyright-like laws that apply to other kinds of
66
+ works, such as semiconductor masks.
67
+
68
+ "The Program" refers to any copyrightable work licensed under this
69
+ License. Each licensee is addressed as "you". "Licensees" and
70
+ "recipients" may be individuals or organizations.
71
+
72
+ To "modify" a work means to copy from or adapt all or part of the work
73
+ in a fashion requiring copyright permission, other than the making of an
74
+ exact copy. The resulting work is called a "modified version" of the
75
+ earlier work or a work "based on" the earlier work.
76
+
77
+ A "covered work" means either the unmodified Program or a work based
78
+ on the Program.
79
+
80
+ To "propagate" a work means to do anything with it that, without
81
+ permission, would make you directly or secondarily liable for
82
+ infringement under applicable copyright law, except executing it on a
83
+ computer or modifying a private copy. Propagation includes copying,
84
+ distribution (with or without modification), making available to the
85
+ public, and in some countries other activities as well.
86
+
87
+ To "convey" a work means any kind of propagation that enables other
88
+ parties to make or receive copies. Mere interaction with a user through
89
+ a computer network, with no transfer of a copy, is not conveying.
90
+
91
+ An interactive user interface displays "Appropriate Legal Notices"
92
+ to the extent that it includes a convenient and prominently visible
93
+ feature that (1) displays an appropriate copyright notice, and (2)
94
+ tells the user that there is no warranty for the work (except to the
95
+ extent that warranties are provided), that licensees may convey the
96
+ work under this License, and how to view a copy of this License. If
97
+ the interface presents a list of user commands or options, such as a
98
+ menu, a prominent item in the list meets this criterion.
99
+
100
+ 1. Source Code.
101
+
102
+ The "source code" for a work means the preferred form of the work
103
+ for making modifications to it. "Object code" means any non-source
104
+ form of a work.
105
+
106
+ A "Standard Interface" means an interface that either is an official
107
+ standard defined by a recognized standards body, or, in the case of
108
+ interfaces specified for a particular programming language, one that
109
+ is widely used among developers working in that language.
110
+
111
+ The "System Libraries" of an executable work include anything, other
112
+ than the work as a whole, that (a) is included in the normal form of
113
+ packaging a Major Component, but which is not part of that Major
114
+ Component, and (b) serves only to enable use of the work with that
115
+ Major Component, or to implement a Standard Interface for which an
116
+ implementation is available to the public in source code form. A
117
+ "Major Component", in this context, means a major essential component
118
+ (kernel, window system, and so on) of the specific operating system
119
+ (if any) on which the executable work runs, or a compiler used to
120
+ produce the work, or an object code interpreter used to run it.
121
+
122
+ The "Corresponding Source" for a work in object code form means all
123
+ the source code needed to generate, install, and (for an executable
124
+ work) run the object code and to modify the work, including scripts to
125
+ control those activities. However, it does not include the work's
126
+ System Libraries, or general-purpose tools or generally available free
127
+ programs which are used unmodified in performing those activities but
128
+ which are not part of the work. For example, Corresponding Source
129
+ includes interface definition files associated with source files for
130
+ the work, and the source code for shared libraries and dynamically
131
+ linked subprograms that the work is specifically designed to require,
132
+ such as by intimate data communication or control flow between those
133
+ subprograms and other parts of the work.
134
+
135
+ The Corresponding Source need not include anything that users
136
+ can regenerate automatically from other parts of the Corresponding
137
+ Source.
138
+
139
+ The Corresponding Source for a work in source code form is that
140
+ same work.
141
+
142
+ 2. Basic Permissions.
143
+
144
+ All rights granted under this License are granted for the term of
145
+ copyright on the Program, and are irrevocable provided the stated
146
+ conditions are met. This License explicitly affirms your unlimited
147
+ permission to run the unmodified Program. The output from running a
148
+ covered work is covered by this License only if the output, given its
149
+ content, constitutes a covered work. This License acknowledges your
150
+ rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+ You may make, run and propagate covered works that you do not
153
+ convey, without conditions so long as your license otherwise remains
154
+ in force. You may convey covered works to others for the sole purpose
155
+ of having them make modifications exclusively for you, or provide you
156
+ with facilities for running those works, provided that you comply with
157
+ the terms of this License in conveying all material for which you do
158
+ not control copyright. Those thus making or running the covered works
159
+ for you must do so exclusively on your behalf, under your direction
160
+ and control, on terms that prohibit them from making any copies of
161
+ your copyrighted material outside their relationship with you.
162
+
163
+ Conveying under any other circumstances is permitted solely under
164
+ the conditions stated below. Sublicensing is not allowed; section 10
165
+ makes it unnecessary.
166
+
167
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+ No covered work shall be deemed part of an effective technological
170
+ measure under any applicable law fulfilling obligations under article
171
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+ similar laws prohibiting or restricting circumvention of such
173
+ measures.
174
+
175
+ When you convey a covered work, you waive any legal power to forbid
176
+ circumvention of technological measures to the extent such circumvention
177
+ is effected by exercising rights under this License with respect to
178
+ the covered work, and you disclaim any intention to limit operation or
179
+ modification of the work as a means of enforcing, against the work's
180
+ users, your or third parties' legal rights to forbid circumvention of
181
+ technological measures.
182
+
183
+ 4. Conveying Verbatim Copies.
184
+
185
+ You may convey verbatim copies of the Program's source code as you
186
+ receive it, in any medium, provided that you conspicuously and
187
+ appropriately publish on each copy an appropriate copyright notice;
188
+ keep intact all notices stating that this License and any
189
+ non-permissive terms added in accord with section 7 apply to the code;
190
+ keep intact all notices of the absence of any warranty; and give all
191
+ recipients a copy of this License along with the Program.
192
+
193
+ You may charge any price or no price for each copy that you convey,
194
+ and you may offer support or warranty protection for a fee.
195
+
196
+ 5. Conveying Modified Source Versions.
197
+
198
+ You may convey a work based on the Program, or the modifications to
199
+ produce it from the Program, in the form of source code under the
200
+ terms of section 4, provided that you also meet all of these conditions:
201
+
202
+ a) The work must carry prominent notices stating that you modified
203
+ it, and giving a relevant date.
204
+
205
+ b) The work must carry prominent notices stating that it is
206
+ released under this License and any conditions added under section
207
+ 7. This requirement modifies the requirement in section 4 to
208
+ "keep intact all notices".
209
+
210
+ c) You must license the entire work, as a whole, under this
211
+ License to anyone who comes into possession of a copy. This
212
+ License will therefore apply, along with any applicable section 7
213
+ additional terms, to the whole of the work, and all its parts,
214
+ regardless of how they are packaged. This License gives no
215
+ permission to license the work in any other way, but it does not
216
+ invalidate such permission if you have separately received it.
217
+
218
+ d) If the work has interactive user interfaces, each must display
219
+ Appropriate Legal Notices; however, if the Program has interactive
220
+ interfaces that do not display Appropriate Legal Notices, your
221
+ work need not make them do so.
222
+
223
+ A compilation of a covered work with other separate and independent
224
+ works, which are not by their nature extensions of the covered work,
225
+ and which are not combined with it such as to form a larger program,
226
+ in or on a volume of a storage or distribution medium, is called an
227
+ "aggregate" if the compilation and its resulting copyright are not
228
+ used to limit the access or legal rights of the compilation's users
229
+ beyond what the individual works permit. Inclusion of a covered work
230
+ in an aggregate does not cause this License to apply to the other
231
+ parts of the aggregate.
232
+
233
+ 6. Conveying Non-Source Forms.
234
+
235
+ You may convey a covered work in object code form under the terms
236
+ of sections 4 and 5, provided that you also convey the
237
+ machine-readable Corresponding Source under the terms of this License,
238
+ in one of these ways:
239
+
240
+ a) Convey the object code in, or embodied in, a physical product
241
+ (including a physical distribution medium), accompanied by the
242
+ Corresponding Source fixed on a durable physical medium
243
+ customarily used for software interchange.
244
+
245
+ b) Convey the object code in, or embodied in, a physical product
246
+ (including a physical distribution medium), accompanied by a
247
+ written offer, valid for at least three years and valid for as
248
+ long as you offer spare parts or customer support for that product
249
+ model, to give anyone who possesses the object code either (1) a
250
+ copy of the Corresponding Source for all the software in the
251
+ product that is covered by this License, on a durable physical
252
+ medium customarily used for software interchange, for a price no
253
+ more than your reasonable cost of physically performing this
254
+ conveying of source, or (2) access to copy the
255
+ Corresponding Source from a network server at no charge.
256
+
257
+ c) Convey individual copies of the object code with a copy of the
258
+ written offer to provide the Corresponding Source. This
259
+ alternative is allowed only occasionally and noncommercially, and
260
+ only if you received the object code with such an offer, in accord
261
+ with subsection 6b.
262
+
263
+ d) Convey the object code by offering access from a designated
264
+ place (gratis or for a charge), and offer equivalent access to the
265
+ Corresponding Source in the same way through the same place at no
266
+ further charge. You need not require recipients to copy the
267
+ Corresponding Source along with the object code. If the place to
268
+ copy the object code is a network server, the Corresponding Source
269
+ may be on a different server (operated by you or a third party)
270
+ that supports equivalent copying facilities, provided you maintain
271
+ clear directions next to the object code saying where to find the
272
+ Corresponding Source. Regardless of what server hosts the
273
+ Corresponding Source, you remain obligated to ensure that it is
274
+ available for as long as needed to satisfy these requirements.
275
+
276
+ e) Convey the object code using peer-to-peer transmission, provided
277
+ you inform other peers where the object code and Corresponding
278
+ Source of the work are being offered to the general public at no
279
+ charge under subsection 6d.
280
+
281
+ A separable portion of the object code, whose source code is excluded
282
+ from the Corresponding Source as a System Library, need not be
283
+ included in conveying the object code work.
284
+
285
+ A "User Product" is either (1) a "consumer product", which means any
286
+ tangible personal property which is normally used for personal, family,
287
+ or household purposes, or (2) anything designed or sold for incorporation
288
+ into a dwelling. In determining whether a product is a consumer product,
289
+ doubtful cases shall be resolved in favor of coverage. For a particular
290
+ product received by a particular user, "normally used" refers to a
291
+ typical or common use of that class of product, regardless of the status
292
+ of the particular user or of the way in which the particular user
293
+ actually uses, or expects or is expected to use, the product. A product
294
+ is a consumer product regardless of whether the product has substantial
295
+ commercial, industrial or non-consumer uses, unless such uses represent
296
+ the only significant mode of use of the product.
297
+
298
+ "Installation Information" for a User Product means any methods,
299
+ procedures, authorization keys, or other information required to install
300
+ and execute modified versions of a covered work in that User Product from
301
+ a modified version of its Corresponding Source. The information must
302
+ suffice to ensure that the continued functioning of the modified object
303
+ code is in no case prevented or interfered with solely because
304
+ modification has been made.
305
+
306
+ If you convey an object code work under this section in, or with, or
307
+ specifically for use in, a User Product, and the conveying occurs as
308
+ part of a transaction in which the right of possession and use of the
309
+ User Product is transferred to the recipient in perpetuity or for a
310
+ fixed term (regardless of how the transaction is characterized), the
311
+ Corresponding Source conveyed under this section must be accompanied
312
+ by the Installation Information. But this requirement does not apply
313
+ if neither you nor any third party retains the ability to install
314
+ modified object code on the User Product (for example, the work has
315
+ been installed in ROM).
316
+
317
+ The requirement to provide Installation Information does not include a
318
+ requirement to continue to provide support service, warranty, or updates
319
+ for a work that has been modified or installed by the recipient, or for
320
+ the User Product in which it has been modified or installed. Access to a
321
+ network may be denied when the modification itself materially and
322
+ adversely affects the operation of the network or violates the rules and
323
+ protocols for communication across the network.
324
+
325
+ Corresponding Source conveyed, and Installation Information provided,
326
+ in accord with this section must be in a format that is publicly
327
+ documented (and with an implementation available to the public in
328
+ source code form), and must require no special password or key for
329
+ unpacking, reading or copying.
330
+
331
+ 7. Additional Terms.
332
+
333
+ "Additional permissions" are terms that supplement the terms of this
334
+ License by making exceptions from one or more of its conditions.
335
+ Additional permissions that are applicable to the entire Program shall
336
+ be treated as though they were included in this License, to the extent
337
+ that they are valid under applicable law. If additional permissions
338
+ apply only to part of the Program, that part may be used separately
339
+ under those permissions, but the entire Program remains governed by
340
+ this License without regard to the additional permissions.
341
+
342
+ When you convey a copy of a covered work, you may at your option
343
+ remove any additional permissions from that copy, or from any part of
344
+ it. (Additional permissions may be written to require their own
345
+ removal in certain cases when you modify the work.) You may place
346
+ additional permissions on material, added by you to a covered work,
347
+ for which you have or can give appropriate copyright permission.
348
+
349
+ Notwithstanding any other provision of this License, for material you
350
+ add to a covered work, you may (if authorized by the copyright holders of
351
+ that material) supplement the terms of this License with terms:
352
+
353
+ a) Disclaiming warranty or limiting liability differently from the
354
+ terms of sections 15 and 16 of this License; or
355
+
356
+ b) Requiring preservation of specified reasonable legal notices or
357
+ author attributions in that material or in the Appropriate Legal
358
+ Notices displayed by works containing it; or
359
+
360
+ c) Prohibiting misrepresentation of the origin of that material, or
361
+ requiring that modified versions of such material be marked in
362
+ reasonable ways as different from the original version; or
363
+
364
+ d) Limiting the use for publicity purposes of names of licensors or
365
+ authors of the material; or
366
+
367
+ e) Declining to grant rights under trademark law for use of some
368
+ trade names, trademarks, or service marks; or
369
+
370
+ f) Requiring indemnification of licensors and authors of that
371
+ material by anyone who conveys the material (or modified versions of
372
+ it) with contractual assumptions of liability to the recipient, for
373
+ any liability that these contractual assumptions directly impose on
374
+ those licensors and authors.
375
+
376
+ All other non-permissive additional terms are considered "further
377
+ restrictions" within the meaning of section 10. If the Program as you
378
+ received it, or any part of it, contains a notice stating that it is
379
+ governed by this License along with a term that is a further
380
+ restriction, you may remove that term. If a license document contains
381
+ a further restriction but permits relicensing or conveying under this
382
+ License, you may add to a covered work material governed by the terms
383
+ of that license document, provided that the further restriction does
384
+ not survive such relicensing or conveying.
385
+
386
+ If you add terms to a covered work in accord with this section, you
387
+ must place, in the relevant source files, a statement of the
388
+ additional terms that apply to those files, or a notice indicating
389
+ where to find the applicable terms.
390
+
391
+ Additional terms, permissive or non-permissive, may be stated in the
392
+ form of a separately written license, or stated as exceptions;
393
+ the above requirements apply either way.
394
+
395
+ 8. Termination.
396
+
397
+ You may not propagate or modify a covered work except as expressly
398
+ provided under this License. Any attempt otherwise to propagate or
399
+ modify it is void, and will automatically terminate your rights under
400
+ this License (including any patent licenses granted under the third
401
+ paragraph of section 11).
402
+
403
+ However, if you cease all violation of this License, then your
404
+ license from a particular copyright holder is reinstated (a)
405
+ provisionally, unless and until the copyright holder explicitly and
406
+ finally terminates your license, and (b) permanently, if the copyright
407
+ holder fails to notify you of the violation by some reasonable means
408
+ prior to 60 days after the cessation.
409
+
410
+ Moreover, your license from a particular copyright holder is
411
+ reinstated permanently if the copyright holder notifies you of the
412
+ violation by some reasonable means, this is the first time you have
413
+ received notice of violation of this License (for any work) from that
414
+ copyright holder, and you cure the violation prior to 30 days after
415
+ your receipt of the notice.
416
+
417
+ Termination of your rights under this section does not terminate the
418
+ licenses of parties who have received copies or rights from you under
419
+ this License. If your rights have been terminated and not permanently
420
+ reinstated, you do not qualify to receive new licenses for the same
421
+ material under section 10.
422
+
423
+ 9. Acceptance Not Required for Having Copies.
424
+
425
+ You are not required to accept this License in order to receive or
426
+ run a copy of the Program. Ancillary propagation of a covered work
427
+ occurring solely as a consequence of using peer-to-peer transmission
428
+ to receive a copy likewise does not require acceptance. However,
429
+ nothing other than this License grants you permission to propagate or
430
+ modify any covered work. These actions infringe copyright if you do
431
+ not accept this License. Therefore, by modifying or propagating a
432
+ covered work, you indicate your acceptance of this License to do so.
433
+
434
+ 10. Automatic Licensing of Downstream Recipients.
435
+
436
+ Each time you convey a covered work, the recipient automatically
437
+ receives a license from the original licensors, to run, modify and
438
+ propagate that work, subject to this License. You are not responsible
439
+ for enforcing compliance by third parties with this License.
440
+
441
+ An "entity transaction" is a transaction transferring control of an
442
+ organization, or substantially all assets of one, or subdividing an
443
+ organization, or merging organizations. If propagation of a covered
444
+ work results from an entity transaction, each party to that
445
+ transaction who receives a copy of the work also receives whatever
446
+ licenses to the work the party's predecessor in interest had or could
447
+ give under the previous paragraph, plus a right to possession of the
448
+ Corresponding Source of the work from the predecessor in interest, if
449
+ the predecessor has it or can get it with reasonable efforts.
450
+
451
+ You may not impose any further restrictions on the exercise of the
452
+ rights granted or affirmed under this License. For example, you may
453
+ not impose a license fee, royalty, or other charge for exercise of
454
+ rights granted under this License, and you may not initiate litigation
455
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
456
+ any patent claim is infringed by making, using, selling, offering for
457
+ sale, or importing the Program or any portion of it.
458
+
459
+ 11. Patents.
460
+
461
+ A "contributor" is a copyright holder who authorizes use under this
462
+ License of the Program or a work on which the Program is based. The
463
+ work thus licensed is called the contributor's "contributor version".
464
+
465
+ A contributor's "essential patent claims" are all patent claims
466
+ owned or controlled by the contributor, whether already acquired or
467
+ hereafter acquired, that would be infringed by some manner, permitted
468
+ by this License, of making, using, or selling its contributor version,
469
+ but do not include claims that would be infringed only as a
470
+ consequence of further modification of the contributor version. For
471
+ purposes of this definition, "control" includes the right to grant
472
+ patent sublicenses in a manner consistent with the requirements of
473
+ this License.
474
+
475
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+ patent license under the contributor's essential patent claims, to
477
+ make, use, sell, offer for sale, import and otherwise run, modify and
478
+ propagate the contents of its contributor version.
479
+
480
+ In the following three paragraphs, a "patent license" is any express
481
+ agreement or commitment, however denominated, not to enforce a patent
482
+ (such as an express permission to practice a patent or covenant not to
483
+ sue for patent infringement). To "grant" such a patent license to a
484
+ party means to make such an agreement or commitment not to enforce a
485
+ patent against the party.
486
+
487
+ If you convey a covered work, knowingly relying on a patent license,
488
+ and the Corresponding Source of the work is not available for anyone
489
+ to copy, free of charge and under the terms of this License, through a
490
+ publicly available network server or other readily accessible means,
491
+ then you must either (1) cause the Corresponding Source to be so
492
+ available, or (2) arrange to deprive yourself of the benefit of the
493
+ patent license for this particular work, or (3) arrange, in a manner
494
+ consistent with the requirements of this License, to extend the patent
495
+ license to downstream recipients. "Knowingly relying" means you have
496
+ actual knowledge that, but for the patent license, your conveying the
497
+ covered work in a country, or your recipient's use of the covered work
498
+ in a country, would infringe one or more identifiable patents in that
499
+ country that you have reason to believe are valid.
500
+
501
+ If, pursuant to or in connection with a single transaction or
502
+ arrangement, you convey, or propagate by procuring conveyance of, a
503
+ covered work, and grant a patent license to some of the parties
504
+ receiving the covered work authorizing them to use, propagate, modify
505
+ or convey a specific copy of the covered work, then the patent license
506
+ you grant is automatically extended to all recipients of the covered
507
+ work and works based on it.
508
+
509
+ A patent license is "discriminatory" if it does not include within
510
+ the scope of its coverage, prohibits the exercise of, or is
511
+ conditioned on the non-exercise of one or more of the rights that are
512
+ specifically granted under this License. You may not convey a covered
513
+ work if you are a party to an arrangement with a third party that is
514
+ in the business of distributing software, under which you make payment
515
+ to the third party based on the extent of your activity of conveying
516
+ the work, and under which the third party grants, to any of the
517
+ parties who would receive the covered work from you, a discriminatory
518
+ patent license (a) in connection with copies of the covered work
519
+ conveyed by you (or copies made from those copies), or (b) primarily
520
+ for and in connection with specific products or compilations that
521
+ contain the covered work, unless you entered into that arrangement,
522
+ or that patent license was granted, prior to 28 March 2007.
523
+
524
+ Nothing in this License shall be construed as excluding or limiting
525
+ any implied license or other defenses to infringement that may
526
+ otherwise be available to you under applicable patent law.
527
+
528
+ 12. No Surrender of Others' Freedom.
529
+
530
+ If conditions are imposed on you (whether by court order, agreement or
531
+ otherwise) that contradict the conditions of this License, they do not
532
+ excuse you from the conditions of this License. If you cannot convey a
533
+ covered work so as to satisfy simultaneously your obligations under this
534
+ License and any other pertinent obligations, then as a consequence you may
535
+ not convey it at all. For example, if you agree to terms that obligate you
536
+ to collect a royalty for further conveying from those to whom you convey
537
+ the Program, the only way you could satisfy both those terms and this
538
+ License would be to refrain entirely from conveying the Program.
539
+
540
+ 13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+ Notwithstanding any other provision of this License, if you modify the
543
+ Program, your modified version must prominently offer all users
544
+ interacting with it remotely through a computer network (if your version
545
+ supports such interaction) an opportunity to receive the Corresponding
546
+ Source of your version by providing access to the Corresponding Source
547
+ from a network server at no charge, through some standard or customary
548
+ means of facilitating copying of software. This Corresponding Source
549
+ shall include the Corresponding Source for any work covered by version 3
550
+ of the GNU General Public License that is incorporated pursuant to the
551
+ following paragraph.
552
+
553
+ Notwithstanding any other provision of this License, you have
554
+ permission to link or combine any covered work with a work licensed
555
+ under version 3 of the GNU General Public License into a single
556
+ combined work, and to convey the resulting work. The terms of this
557
+ License will continue to apply to the part which is the covered work,
558
+ but the work with which it is combined will remain governed by version
559
+ 3 of the GNU General Public License.
560
+
561
+ 14. Revised Versions of this License.
562
+
563
+ The Free Software Foundation may publish revised and/or new versions of
564
+ the GNU Affero General Public License from time to time. Such new versions
565
+ will be similar in spirit to the present version, but may differ in detail to
566
+ address new problems or concerns.
567
+
568
+ Each version is given a distinguishing version number. If the
569
+ Program specifies that a certain numbered version of the GNU Affero General
570
+ Public License "or any later version" applies to it, you have the
571
+ option of following the terms and conditions either of that numbered
572
+ version or of any later version published by the Free Software
573
+ Foundation. If the Program does not specify a version number of the
574
+ GNU Affero General Public License, you may choose any version ever published
575
+ by the Free Software Foundation.
576
+
577
+ If the Program specifies that a proxy can decide which future
578
+ versions of the GNU Affero General Public License can be used, that proxy's
579
+ public statement of acceptance of a version permanently authorizes you
580
+ to choose that version for the Program.
581
+
582
+ Later license versions may give you additional or different
583
+ permissions. However, no additional obligations are imposed on any
584
+ author or copyright holder as a result of your choosing to follow a
585
+ later version.
586
+
587
+ 15. Disclaimer of Warranty.
588
+
589
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+ 16. Limitation of Liability.
599
+
600
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+ SUCH DAMAGES.
609
+
610
+ 17. Interpretation of Sections 15 and 16.
611
+
612
+ If the disclaimer of warranty and limitation of liability provided
613
+ above cannot be given local legal effect according to their terms,
614
+ reviewing courts shall apply local law that most closely approximates
615
+ an absolute waiver of all civil liability in connection with the
616
+ Program, unless a warranty or assumption of liability accompanies a
617
+ copy of the Program in return for a fee.
618
+
619
+ END OF TERMS AND CONDITIONS
620
+
621
+ How to Apply These Terms to Your New Programs
622
+
623
+ If you develop a new program, and you want it to be of the greatest
624
+ possible use to the public, the best way to achieve this is to make it
625
+ free software which everyone can redistribute and change under these terms.
626
+
627
+ To do so, attach the following notices to the program. It is safest
628
+ to attach them to the start of each source file to most effectively
629
+ state the exclusion of warranty; and each file should have at least
630
+ the "copyright" line and a pointer to where the full notice is found.
631
+
632
+ <one line to give the program's name and a brief idea of what it does.>
633
+ Copyright (C) <year> <name of author>
634
+
635
+ This program is free software: you can redistribute it and/or modify
636
+ it under the terms of the GNU Affero General Public License as published
637
+ by the Free Software Foundation, either version 3 of the License, or
638
+ (at your option) any later version.
639
+
640
+ This program is distributed in the hope that it will be useful,
641
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643
+ GNU Affero General Public License for more details.
644
+
645
+ You should have received a copy of the GNU Affero General Public License
646
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647
+
648
+ Also add information on how to contact you by electronic and paper mail.
649
+
650
+ If your software can interact with users remotely through a computer
651
+ network, you should also make sure that it provides a way for users to
652
+ get its source. For example, if your program is a web application, its
653
+ interface could display a "Source" link that leads users to an archive
654
+ of the code. There are many ways you could offer source, and different
655
+ solutions will be better for different programs; see section 13 for the
656
+ specific requirements.
657
+
658
+ You should also get your employer (if you work as a programmer) or school,
659
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+ For more information on this, and how to apply and follow the GNU AGPL, see
661
+ <https://www.gnu.org/licenses/>.
README.md CHANGED
@@ -1,13 +1,114 @@
1
- ---
2
- title: FaceSwap
3
- emoji: 🏃
4
- colorFrom: blue
5
- colorTo: blue
6
- sdk: gradio
7
- sdk_version: 3.44.3
8
- app_file: app.py
9
- pinned: false
10
- license: openrail
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # roop-unleashed
2
+
3
+ [Changelog](#changelog) • [Installation](#installation) • [Usage](#usage) • [Example](#example) • [FAQ](#faq)
4
+
5
+
6
+ Uncensored Deepfakes for images and videos without training and an easy-to-use GUI.
7
+
8
+
9
+ ![Screen](docs/screenshot.png)
10
+
11
+
12
+ ### Features
13
+
14
+ - Platform-independant Browser GUI
15
+ - Selection of multiple input/output faces in one go
16
+ - Many different swapping modes, first detected, face selections, by gender
17
+ - Batch processing of images/videos
18
+ - Masking of face occluders using text prompts
19
+ - Optional Face Restoration using different enhancers
20
+ - Preview swapping from different video frames
21
+ - Live Fake Cam using your webcam
22
+ - Extras Tab for cutting videos etc.
23
+ - Settings - storing configuration for next session
24
+ - Theme Support
25
+
26
+ and lots more...
27
+
28
+
29
+ ## Disclaimer
30
+
31
+ This project is for technical and academic use only.
32
+ Users of this software are expected to use this software responsibly while abiding the local law. If a 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 of this software will not be responsible for actions of end-users.
33
+ **Please do not apply it to illegal and unethical scenarios.**
34
+
35
+ In the event of violation of the legal and ethical requirements of the user's country or region, this code repository is exempt from liability
36
+
37
+ ### Installation
38
+
39
+ > For Windows, you need to download and install [Visual Studio](https://visualstudio.microsoft.com/de/downloads/) (in theory build-tools might work too but in my experience so far they don't). During the install, make sure to include the C++ package.
40
+
41
+ Besides that, just use the 1-click installer in releases. This will download and install everything
42
+ in a handy conda environment. This not only installs the application but also runs it, once installed.
43
+
44
+ For other OS or if you know what you're doing:
45
+
46
+ - `git clone https://github.com/C0untFloyd/roop-unleashed`
47
+ - preferably create a venv or conda environment
48
+ - `cd roop-unleashed`
49
+ - `pip install -r requirements.txt`
50
+
51
+ Depending on your available GPU there are additional packages you need to install. Here are the instructions from the original roop page:
52
+
53
+ [Using GPU Acceleration](https://github.com/s0md3v/roop/wiki/2.-Acceleration)
54
+
55
+ The used GPU Provider is configured in the settings tab, no need to use cmdline arguments any more. Default is CUDA (for NVIDIA). If you change it, please restart roop-unleashed completely to allow for model reloading.
56
+
57
+ For Video face-swapping you also need to have ffmpeg properly installed (having it in your PATH Env). The windows installer tries to do this automatically.
58
+
59
+
60
+
61
+ ### Usage
62
+
63
+ - Windows: run the `windows_run.bat` from the Installer.
64
+ - Linux: `python run.py`
65
+
66
+ <a target="_blank" href="https://colab.research.google.com/github/C0untFloyd/roop-unleashed/blob/main/roop-unleashed.ipynb">
67
+ <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
68
+ </a>
69
+
70
+
71
+ Additional commandline arguments are currently unsupported and settings should be done via the UI.
72
+
73
+ > Note: When you run this program for the first time, it will download some models roughly ~2Gb in size.
74
+
75
+
76
+ ### Example
77
+
78
+ *Coming soon*
79
+
80
+
81
+
82
+ ### Changelog
83
+
84
+ **11.8.2023** v2.7.0
85
+
86
+ Initial Gradio Version - old TkInter Version now deprecated
87
+
88
+ - Re-added unified padding to face enhancers
89
+ - Fixed DMDNet for all resolutions
90
+ - Selecting target face now automatically switches swapping mode to selected
91
+ - GPU providers are correctly set using the GUI (needs restart currently)
92
+ - Local output folder can be opened from page
93
+ - Unfinished extras functions disabled for now
94
+ - Installer checks out specific commit, allowing to go back to first install
95
+ - Updated readme for new gradio version
96
+ - Updated Colab
97
+
98
+
99
+ # Acknowledgements
100
+
101
+ Lots of ideas, code or pre-trained models used from the following projects:
102
+
103
+ https://github.com/deepinsight/insightface
104
+ https://github.com/s0md3v/roop
105
+ https://github.com/AUTOMATIC1111/stable-diffusion-webui
106
+ https://github.com/Hillobar/Rope
107
+ https://github.com/janvarev/chain-img-processor
108
+ https://github.com/TencentARC/GFPGAN
109
+ https://github.com/kadirnar/codeformer-pip
110
+ https://github.com/csxmli2016/DMDNet
111
+
112
+
113
+ Thanks to all developers!
114
+
chain_img_processor/image.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import cv2
3
+ from jaa import JaaCore
4
+ from roop.utilities import get_device
5
+
6
+
7
+ from typing import Any
8
+
9
+ version = "4.0.0"
10
+
11
+ class ChainImgProcessor(JaaCore):
12
+
13
+ def __init__(self):
14
+ JaaCore.__init__(self)
15
+
16
+ self.processors:dict = {
17
+ }
18
+
19
+ self.processors_objects:dict[str,list[ChainImgPlugin]] = {}
20
+
21
+ self.default_chain = ""
22
+ self.init_on_start = ""
23
+
24
+ self.inited_processors = []
25
+
26
+ self.is_demo_row_render = False
27
+
28
+ def process_plugin_manifest(self, modname, manifest):
29
+ # adding processors from plugin manifest
30
+ if "img_processor" in manifest: # process commands
31
+ for cmd in manifest["img_processor"].keys():
32
+ self.processors[cmd] = manifest["img_processor"][cmd]
33
+
34
+ return manifest
35
+
36
+ def init_with_plugins(self):
37
+ self.init_plugins(["core"])
38
+ self.display_init_info()
39
+
40
+ #self.init_translator_engine(self.default_translator)
41
+ init_on_start_arr = self.init_on_start.split(",")
42
+ for proc_id in init_on_start_arr:
43
+ self.init_processor(proc_id)
44
+
45
+ def run_chain(self, img, params:dict[str,Any] = None, chain:str = None, thread_index:int = 0):
46
+ if chain is None:
47
+ chain = self.default_chain
48
+ if params is None:
49
+ params = {}
50
+ params["_thread_index"] = thread_index
51
+ chain_ar = chain.split(",")
52
+ # init all not inited processors first
53
+ for proc_id in chain_ar:
54
+ if proc_id != "":
55
+ if not proc_id in self.inited_processors:
56
+ self.init_processor(proc_id)
57
+
58
+
59
+
60
+ # run processing
61
+ if self.is_demo_row_render:
62
+ import cv2
63
+ import numpy as np
64
+ height, width, channels = img.shape
65
+ img_blank = np.zeros((height+30, width*(1+len(chain_ar)), 3), dtype=np.uint8)
66
+ img_blank.fill(255)
67
+
68
+ y = 30
69
+ x = 0
70
+ img_blank[y:y + height, x:x + width] = img
71
+
72
+ # Set the font scale and thickness
73
+ font_scale = 1
74
+ thickness = 2
75
+
76
+ # Set the font face to a monospace font
77
+ font_face = cv2.FONT_HERSHEY_SIMPLEX
78
+
79
+ cv2.putText(img_blank, "original", (x+4, y-7), font_face, font_scale, (0, 0, 0), thickness)
80
+
81
+
82
+ i = 0
83
+ for proc_id in chain_ar:
84
+ i += 1
85
+ if proc_id != "":
86
+ #img = self.processors[proc_id][1](self, img, params) # params can be modified inside
87
+ y = 30
88
+ img = self.processors_objects[proc_id][thread_index].process(img,params)
89
+ if self.is_demo_row_render:
90
+ x = width*i
91
+ img_blank[y:y + height, x:x + width] = img
92
+ cv2.putText(img_blank, proc_id, (x + 4, y - 7), font_face, font_scale, (0, 0, 0), thickness)
93
+
94
+ if self.is_demo_row_render:
95
+ return img_blank, params
96
+
97
+ return img, params
98
+
99
+ # ---------------- init translation stuff ----------------
100
+ def fill_processors_for_thread_chains(self, threads:int = 1, chain:str = None):
101
+ if chain is None:
102
+ chain = self.default_chain
103
+
104
+ chain_ar = chain.split(",")
105
+ # init all not initialized processors first
106
+ for processor_id in chain_ar:
107
+ if processor_id != "":
108
+ if self.processors_objects.get(processor_id) is None:
109
+ self.processors_objects[processor_id] = []
110
+ while len(self.processors_objects[processor_id]) < threads:
111
+ self.add_processor_to_list(processor_id)
112
+
113
+ def add_processor_to_list(self, processor_id: str):
114
+ obj = self.processors[processor_id](self)
115
+ obj.init_plugin()
116
+ if self.processors_objects.get(processor_id) is None:
117
+ self.processors_objects[processor_id] = []
118
+ self.processors_objects[processor_id].append(obj)
119
+ def init_processor(self, processor_id: str):
120
+ if processor_id == "": # blank line case
121
+ return
122
+
123
+ if processor_id in self.inited_processors:
124
+ return
125
+
126
+ try:
127
+ if self.verbose:
128
+ self.print_blue("TRY: init processor plugin '{0}'...".format(processor_id))
129
+ self.add_processor_to_list(processor_id)
130
+ self.inited_processors.append(processor_id)
131
+ if self.verbose:
132
+ self.print_blue("SUCCESS: '{0}' initialized!".format(processor_id))
133
+
134
+ except Exception as e:
135
+ self.print_error("Error init processor plugin {0}...".format(processor_id), e)
136
+
137
+ # ------------ formatting stuff -------------------
138
+ def display_init_info(self):
139
+ if self.verbose:
140
+ print("ChainImgProcessor v{0}:".format(version))
141
+ self.format_print_key_list("processors:", self.processors.keys())
142
+
143
+ def format_print_key_list(self, key:str, value:list):
144
+ print(key+": ".join(value))
145
+
146
+ def print_error(self,err_txt,e:Exception = None):
147
+ print(err_txt,"red")
148
+ # if e != None:
149
+ # cprint(e,"red")
150
+ import traceback
151
+ traceback.print_exc()
152
+
153
+ def print_red(self,txt):
154
+ print(txt)
155
+
156
+ def print_blue(self, txt):
157
+ print(txt)
158
+
159
+ class ChainImgPlugin:
160
+
161
+ device = 'cpu'
162
+
163
+ def __init__(self, core: ChainImgProcessor):
164
+ self.core = core
165
+ self.device = get_device()
166
+
167
+ def init_plugin(self): # here you can init something. Called once
168
+ pass
169
+ def process(self, img, params:dict): # process img. Called multiple
170
+ return img
171
+
172
+ def unload(self):
173
+ pass
174
+
175
+
176
+ def cutout(self, frame, start_x, start_y, end_x, end_y, padding_factor):
177
+ padding_x = int((end_x - start_x) * padding_factor)
178
+ padding_y = int((end_y - start_y) * padding_factor)
179
+
180
+ start_x = max(0, start_x - padding_x)
181
+ start_y = max(0, start_y - padding_y)
182
+ end_x = min(frame.shape[1], end_x + padding_x)
183
+ end_y = min(frame.shape[0], end_y + padding_y)
184
+ return frame[start_y:end_y, start_x:end_x], start_x, start_y, end_x, end_y
185
+
186
+ def paste_into(self, clip, frame, start_x, start_y, end_x, end_y, smooth):
187
+ if smooth:
188
+ smallest = min(clip.shape[0], clip.shape[1])
189
+ mask_border = smallest // 12
190
+ if mask_border > 4:
191
+ img_white = np.full((clip.shape[0], clip.shape[1]), 0, dtype=float)
192
+ # img_white = cv2.warpAffine(img_white, mat_rev, img_shape)
193
+ # img_white[img_white > 20] = 255
194
+ img_white = cv2.rectangle(img_white, (mask_border, mask_border),
195
+ (img_white.shape[1] - mask_border, img_white.shape[0]-mask_border), (255, 255, 255), -1)
196
+ img_mask = img_white
197
+ t1 = mask_border * 2
198
+ kernel = np.ones((t1, t1), np.uint8)
199
+ img_mask = cv2.erode(img_mask, kernel, iterations=2)
200
+ t1 = mask_border
201
+ kernel_size = (t1, t1)
202
+ blur_size = tuple(2 * j + 1 for j in kernel_size)
203
+ img_mask = cv2.GaussianBlur(img_mask, blur_size, 0)
204
+ img_mask /= 255
205
+ img_mask = np.reshape(img_mask, [img_mask.shape[0], img_mask.shape[1], 1])
206
+ frame_clip = frame[start_y:end_y, start_x:end_x]
207
+ clip = img_mask * clip + (1 - img_mask) * frame_clip
208
+
209
+ frame[start_y:end_y, start_x:end_x] = clip
210
+ return frame
211
+
212
+
213
+
214
+
215
+ _img_processor:ChainImgProcessor = None
216
+ def get_single_image_processor() -> ChainImgProcessor:
217
+ global _img_processor
218
+ if _img_processor is None:
219
+ _img_processor = ChainImgProcessor()
220
+ _img_processor.init_with_plugins()
221
+ return _img_processor
222
+
clip/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .clip import *
clip/bpe_simple_vocab_16e6.txt.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a
3
+ size 1356917
clip/clip.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import os
3
+ import urllib
4
+ import warnings
5
+ from typing import Any, Union, List
6
+ from pkg_resources import packaging
7
+
8
+ import torch
9
+ from PIL import Image
10
+ from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
11
+ from tqdm import tqdm
12
+
13
+ from .model import build_model
14
+ from .simple_tokenizer import SimpleTokenizer as _Tokenizer
15
+
16
+ try:
17
+ from torchvision.transforms import InterpolationMode
18
+ BICUBIC = InterpolationMode.BICUBIC
19
+ except ImportError:
20
+ BICUBIC = Image.BICUBIC
21
+
22
+
23
+ if packaging.version.parse(torch.__version__) < packaging.version.parse("1.7.1"):
24
+ warnings.warn("PyTorch version 1.7.1 or higher is recommended")
25
+
26
+
27
+ __all__ = ["available_models", "load", "tokenize"]
28
+ _tokenizer = _Tokenizer()
29
+
30
+ _MODELS = {
31
+ "RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt",
32
+ "RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt",
33
+ "RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt",
34
+ "RN50x16": "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt",
35
+ "RN50x64": "https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt",
36
+ "ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt",
37
+ "ViT-B/16": "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt",
38
+ "ViT-L/14": "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt",
39
+ "ViT-L/14@336px": "https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt",
40
+ }
41
+
42
+
43
+ def _download(url: str, root: str):
44
+ os.makedirs(root, exist_ok=True)
45
+ filename = os.path.basename(url)
46
+
47
+ expected_sha256 = url.split("/")[-2]
48
+ download_target = os.path.join(root, filename)
49
+
50
+ if os.path.exists(download_target) and not os.path.isfile(download_target):
51
+ raise RuntimeError(f"{download_target} exists and is not a regular file")
52
+
53
+ if os.path.isfile(download_target):
54
+ if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256:
55
+ return download_target
56
+ else:
57
+ warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
58
+
59
+ with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
60
+ with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True, unit_divisor=1024) as loop:
61
+ while True:
62
+ buffer = source.read(8192)
63
+ if not buffer:
64
+ break
65
+
66
+ output.write(buffer)
67
+ loop.update(len(buffer))
68
+
69
+ if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256:
70
+ raise RuntimeError("Model has been downloaded but the SHA256 checksum does not not match")
71
+
72
+ return download_target
73
+
74
+
75
+ def _convert_image_to_rgb(image):
76
+ return image.convert("RGB")
77
+
78
+
79
+ def _transform(n_px):
80
+ return Compose([
81
+ Resize(n_px, interpolation=BICUBIC),
82
+ CenterCrop(n_px),
83
+ _convert_image_to_rgb,
84
+ ToTensor(),
85
+ Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
86
+ ])
87
+
88
+
89
+ def available_models() -> List[str]:
90
+ """Returns the names of available CLIP models"""
91
+ return list(_MODELS.keys())
92
+
93
+
94
+ def load(name: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", jit: bool = False, download_root: str = None):
95
+ """Load a CLIP model
96
+
97
+ Parameters
98
+ ----------
99
+ name : str
100
+ A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
101
+
102
+ device : Union[str, torch.device]
103
+ The device to put the loaded model
104
+
105
+ jit : bool
106
+ Whether to load the optimized JIT model or more hackable non-JIT model (default).
107
+
108
+ download_root: str
109
+ path to download the model files; by default, it uses "~/.cache/clip"
110
+
111
+ Returns
112
+ -------
113
+ model : torch.nn.Module
114
+ The CLIP model
115
+
116
+ preprocess : Callable[[PIL.Image], torch.Tensor]
117
+ A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
118
+ """
119
+ if name in _MODELS:
120
+ model_path = _download(_MODELS[name], download_root or os.path.expanduser("~/.cache/clip"))
121
+ elif os.path.isfile(name):
122
+ model_path = name
123
+ else:
124
+ raise RuntimeError(f"Model {name} not found; available models = {available_models()}")
125
+
126
+ with open(model_path, 'rb') as opened_file:
127
+ try:
128
+ # loading JIT archive
129
+ model = torch.jit.load(opened_file, map_location=device if jit else "cpu").eval()
130
+ state_dict = None
131
+ except RuntimeError:
132
+ # loading saved state dict
133
+ if jit:
134
+ warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead")
135
+ jit = False
136
+ state_dict = torch.load(opened_file, map_location="cpu")
137
+
138
+ if not jit:
139
+ model = build_model(state_dict or model.state_dict()).to(device)
140
+ if str(device) == "cpu":
141
+ model.float()
142
+ return model, _transform(model.visual.input_resolution)
143
+
144
+ # patch the device names
145
+ device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[])
146
+ device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1]
147
+
148
+ def _node_get(node: torch._C.Node, key: str):
149
+ """Gets attributes of a node which is polymorphic over return type.
150
+
151
+ From https://github.com/pytorch/pytorch/pull/82628
152
+ """
153
+ sel = node.kindOf(key)
154
+ return getattr(node, sel)(key)
155
+
156
+ def patch_device(module):
157
+ try:
158
+ graphs = [module.graph] if hasattr(module, "graph") else []
159
+ except RuntimeError:
160
+ graphs = []
161
+
162
+ if hasattr(module, "forward1"):
163
+ graphs.append(module.forward1.graph)
164
+
165
+ for graph in graphs:
166
+ for node in graph.findAllNodes("prim::Constant"):
167
+ if "value" in node.attributeNames() and str(_node_get(node, "value")).startswith("cuda"):
168
+ node.copyAttributes(device_node)
169
+
170
+ model.apply(patch_device)
171
+ patch_device(model.encode_image)
172
+ patch_device(model.encode_text)
173
+
174
+ # patch dtype to float32 on CPU
175
+ if str(device) == "cpu":
176
+ float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[])
177
+ float_input = list(float_holder.graph.findNode("aten::to").inputs())[1]
178
+ float_node = float_input.node()
179
+
180
+ def patch_float(module):
181
+ try:
182
+ graphs = [module.graph] if hasattr(module, "graph") else []
183
+ except RuntimeError:
184
+ graphs = []
185
+
186
+ if hasattr(module, "forward1"):
187
+ graphs.append(module.forward1.graph)
188
+
189
+ for graph in graphs:
190
+ for node in graph.findAllNodes("aten::to"):
191
+ inputs = list(node.inputs())
192
+ for i in [1, 2]: # dtype can be the second or third argument to aten::to()
193
+ if _node_get(inputs[i].node(), "value") == 5:
194
+ inputs[i].node().copyAttributes(float_node)
195
+
196
+ model.apply(patch_float)
197
+ patch_float(model.encode_image)
198
+ patch_float(model.encode_text)
199
+
200
+ model.float()
201
+
202
+ return model, _transform(model.input_resolution.item())
203
+
204
+
205
+ def tokenize(texts: Union[str, List[str]], context_length: int = 77, truncate: bool = False) -> Union[torch.IntTensor, torch.LongTensor]:
206
+ """
207
+ Returns the tokenized representation of given input string(s)
208
+
209
+ Parameters
210
+ ----------
211
+ texts : Union[str, List[str]]
212
+ An input string or a list of input strings to tokenize
213
+
214
+ context_length : int
215
+ The context length to use; all CLIP models use 77 as the context length
216
+
217
+ truncate: bool
218
+ Whether to truncate the text in case its encoding is longer than the context length
219
+
220
+ Returns
221
+ -------
222
+ A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length].
223
+ We return LongTensor when torch version is <1.8.0, since older index_select requires indices to be long.
224
+ """
225
+ if isinstance(texts, str):
226
+ texts = [texts]
227
+
228
+ sot_token = _tokenizer.encoder["<|startoftext|>"]
229
+ eot_token = _tokenizer.encoder["<|endoftext|>"]
230
+ all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts]
231
+ if packaging.version.parse(torch.__version__) < packaging.version.parse("1.8.0"):
232
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
233
+ else:
234
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.int)
235
+
236
+ for i, tokens in enumerate(all_tokens):
237
+ if len(tokens) > context_length:
238
+ if truncate:
239
+ tokens = tokens[:context_length]
240
+ tokens[-1] = eot_token
241
+ else:
242
+ raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}")
243
+ result[i, :len(tokens)] = torch.tensor(tokens)
244
+
245
+ return result
clip/clipseg.py ADDED
@@ -0,0 +1,538 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from os.path import basename, dirname, join, isfile
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as nnf
6
+ from torch.nn.modules.activation import ReLU
7
+
8
+
9
+ def get_prompt_list(prompt):
10
+ if prompt == 'plain':
11
+ return ['{}']
12
+ elif prompt == 'fixed':
13
+ return ['a photo of a {}.']
14
+ elif prompt == 'shuffle':
15
+ return ['a photo of a {}.', 'a photograph of a {}.', 'an image of a {}.', '{}.']
16
+ elif prompt == 'shuffle+':
17
+ return ['a photo of a {}.', 'a photograph of a {}.', 'an image of a {}.', '{}.',
18
+ 'a cropped photo of a {}.', 'a good photo of a {}.', 'a photo of one {}.',
19
+ 'a bad photo of a {}.', 'a photo of the {}.']
20
+ else:
21
+ raise ValueError('Invalid value for prompt')
22
+
23
+
24
+ def forward_multihead_attention(x, b, with_aff=False, attn_mask=None):
25
+ """
26
+ Simplified version of multihead attention (taken from torch source code but without tons of if clauses).
27
+ The mlp and layer norm come from CLIP.
28
+ x: input.
29
+ b: multihead attention module.
30
+ """
31
+
32
+ x_ = b.ln_1(x)
33
+ q, k, v = nnf.linear(x_, b.attn.in_proj_weight, b.attn.in_proj_bias).chunk(3, dim=-1)
34
+ tgt_len, bsz, embed_dim = q.size()
35
+
36
+ head_dim = embed_dim // b.attn.num_heads
37
+ scaling = float(head_dim) ** -0.5
38
+
39
+ q = q.contiguous().view(tgt_len, bsz * b.attn.num_heads, b.attn.head_dim).transpose(0, 1)
40
+ k = k.contiguous().view(-1, bsz * b.attn.num_heads, b.attn.head_dim).transpose(0, 1)
41
+ v = v.contiguous().view(-1, bsz * b.attn.num_heads, b.attn.head_dim).transpose(0, 1)
42
+
43
+ q = q * scaling
44
+
45
+ attn_output_weights = torch.bmm(q, k.transpose(1, 2)) # n_heads * batch_size, tokens^2, tokens^2
46
+ if attn_mask is not None:
47
+
48
+
49
+ attn_mask_type, attn_mask = attn_mask
50
+ n_heads = attn_output_weights.size(0) // attn_mask.size(0)
51
+ attn_mask = attn_mask.repeat(n_heads, 1)
52
+
53
+ if attn_mask_type == 'cls_token':
54
+ # the mask only affects similarities compared to the readout-token.
55
+ attn_output_weights[:, 0, 1:] = attn_output_weights[:, 0, 1:] * attn_mask[None,...]
56
+ # attn_output_weights[:, 0, 0] = 0*attn_output_weights[:, 0, 0]
57
+
58
+ if attn_mask_type == 'all':
59
+ # print(attn_output_weights.shape, attn_mask[:, None].shape)
60
+ attn_output_weights[:, 1:, 1:] = attn_output_weights[:, 1:, 1:] * attn_mask[:, None]
61
+
62
+
63
+ attn_output_weights = torch.softmax(attn_output_weights, dim=-1)
64
+
65
+ attn_output = torch.bmm(attn_output_weights, v)
66
+ attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
67
+ attn_output = b.attn.out_proj(attn_output)
68
+
69
+ x = x + attn_output
70
+ x = x + b.mlp(b.ln_2(x))
71
+
72
+ if with_aff:
73
+ return x, attn_output_weights
74
+ else:
75
+ return x
76
+
77
+
78
+ class CLIPDenseBase(nn.Module):
79
+
80
+ def __init__(self, version, reduce_cond, reduce_dim, prompt, n_tokens):
81
+ super().__init__()
82
+
83
+ import clip
84
+
85
+ # prec = torch.FloatTensor
86
+ self.clip_model, _ = clip.load(version, device='cpu', jit=False)
87
+ self.model = self.clip_model.visual
88
+
89
+ # if not None, scale conv weights such that we obtain n_tokens.
90
+ self.n_tokens = n_tokens
91
+
92
+ for p in self.clip_model.parameters():
93
+ p.requires_grad_(False)
94
+
95
+ # conditional
96
+ if reduce_cond is not None:
97
+ self.reduce_cond = nn.Linear(512, reduce_cond)
98
+ for p in self.reduce_cond.parameters():
99
+ p.requires_grad_(False)
100
+ else:
101
+ self.reduce_cond = None
102
+
103
+ self.film_mul = nn.Linear(512 if reduce_cond is None else reduce_cond, reduce_dim)
104
+ self.film_add = nn.Linear(512 if reduce_cond is None else reduce_cond, reduce_dim)
105
+
106
+ self.reduce = nn.Linear(768, reduce_dim)
107
+
108
+ self.prompt_list = get_prompt_list(prompt)
109
+
110
+ # precomputed prompts
111
+ import pickle
112
+ if isfile('precomputed_prompt_vectors.pickle'):
113
+ precomp = pickle.load(open('precomputed_prompt_vectors.pickle', 'rb'))
114
+ self.precomputed_prompts = {k: torch.from_numpy(v) for k, v in precomp.items()}
115
+ else:
116
+ self.precomputed_prompts = dict()
117
+
118
+ def rescaled_pos_emb(self, new_size):
119
+ assert len(new_size) == 2
120
+
121
+ a = self.model.positional_embedding[1:].T.view(1, 768, *self.token_shape)
122
+ b = nnf.interpolate(a, new_size, mode='bicubic', align_corners=False).squeeze(0).view(768, new_size[0]*new_size[1]).T
123
+ return torch.cat([self.model.positional_embedding[:1], b])
124
+
125
+ def visual_forward(self, x_inp, extract_layers=(), skip=False, mask=None):
126
+
127
+
128
+ with torch.no_grad():
129
+
130
+ inp_size = x_inp.shape[2:]
131
+
132
+ if self.n_tokens is not None:
133
+ stride2 = x_inp.shape[2] // self.n_tokens
134
+ conv_weight2 = nnf.interpolate(self.model.conv1.weight, (stride2, stride2), mode='bilinear', align_corners=True)
135
+ x = nnf.conv2d(x_inp, conv_weight2, bias=self.model.conv1.bias, stride=stride2, dilation=self.model.conv1.dilation)
136
+ else:
137
+ x = self.model.conv1(x_inp) # shape = [*, width, grid, grid]
138
+
139
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
140
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
141
+
142
+ x = torch.cat([self.model.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width]
143
+
144
+ standard_n_tokens = 50 if self.model.conv1.kernel_size[0] == 32 else 197
145
+
146
+ if x.shape[1] != standard_n_tokens:
147
+ new_shape = int(math.sqrt(x.shape[1]-1))
148
+ x = x + self.rescaled_pos_emb((new_shape, new_shape)).to(x.dtype)[None,:,:]
149
+ else:
150
+ x = x + self.model.positional_embedding.to(x.dtype)
151
+
152
+ x = self.model.ln_pre(x)
153
+
154
+ x = x.permute(1, 0, 2) # NLD -> LND
155
+
156
+ activations, affinities = [], []
157
+ for i, res_block in enumerate(self.model.transformer.resblocks):
158
+
159
+ if mask is not None:
160
+ mask_layer, mask_type, mask_tensor = mask
161
+ if mask_layer == i or mask_layer == 'all':
162
+ # import ipdb; ipdb.set_trace()
163
+ size = int(math.sqrt(x.shape[0] - 1))
164
+
165
+ attn_mask = (mask_type, nnf.interpolate(mask_tensor.unsqueeze(1).float(), (size, size)).view(mask_tensor.shape[0], size * size))
166
+
167
+ else:
168
+ attn_mask = None
169
+ else:
170
+ attn_mask = None
171
+
172
+ x, aff_per_head = forward_multihead_attention(x, res_block, with_aff=True, attn_mask=attn_mask)
173
+
174
+ if i in extract_layers:
175
+ affinities += [aff_per_head]
176
+
177
+ #if self.n_tokens is not None:
178
+ # activations += [nnf.interpolate(x, inp_size, mode='bilinear', align_corners=True)]
179
+ #else:
180
+ activations += [x]
181
+
182
+ if len(extract_layers) > 0 and i == max(extract_layers) and skip:
183
+ print('early skip')
184
+ break
185
+
186
+ x = x.permute(1, 0, 2) # LND -> NLD
187
+ x = self.model.ln_post(x[:, 0, :])
188
+
189
+ if self.model.proj is not None:
190
+ x = x @ self.model.proj
191
+
192
+ return x, activations, affinities
193
+
194
+ def sample_prompts(self, words, prompt_list=None):
195
+
196
+ prompt_list = prompt_list if prompt_list is not None else self.prompt_list
197
+
198
+ prompt_indices = torch.multinomial(torch.ones(len(prompt_list)), len(words), replacement=True)
199
+ prompts = [prompt_list[i] for i in prompt_indices]
200
+ return [promt.format(w) for promt, w in zip(prompts, words)]
201
+
202
+ def get_cond_vec(self, conditional, batch_size):
203
+ # compute conditional from a single string
204
+ if conditional is not None and type(conditional) == str:
205
+ cond = self.compute_conditional(conditional)
206
+ cond = cond.repeat(batch_size, 1)
207
+
208
+ # compute conditional from string list/tuple
209
+ elif conditional is not None and type(conditional) in {list, tuple} and type(conditional[0]) == str:
210
+ assert len(conditional) == batch_size
211
+ cond = self.compute_conditional(conditional)
212
+
213
+ # use conditional directly
214
+ elif conditional is not None and type(conditional) == torch.Tensor and conditional.ndim == 2:
215
+ cond = conditional
216
+
217
+ # compute conditional from image
218
+ elif conditional is not None and type(conditional) == torch.Tensor:
219
+ with torch.no_grad():
220
+ cond, _, _ = self.visual_forward(conditional)
221
+ else:
222
+ raise ValueError('invalid conditional')
223
+ return cond
224
+
225
+ def compute_conditional(self, conditional):
226
+ import clip
227
+
228
+ dev = next(self.parameters()).device
229
+
230
+ if type(conditional) in {list, tuple}:
231
+ text_tokens = clip.tokenize(conditional).to(dev)
232
+ cond = self.clip_model.encode_text(text_tokens)
233
+ else:
234
+ if conditional in self.precomputed_prompts:
235
+ cond = self.precomputed_prompts[conditional].float().to(dev)
236
+ else:
237
+ text_tokens = clip.tokenize([conditional]).to(dev)
238
+ cond = self.clip_model.encode_text(text_tokens)[0]
239
+
240
+ if self.shift_vector is not None:
241
+ return cond + self.shift_vector
242
+ else:
243
+ return cond
244
+
245
+
246
+ def clip_load_untrained(version):
247
+ assert version == 'ViT-B/16'
248
+ from clip.model import CLIP
249
+ from clip.clip import _MODELS, _download
250
+ model = torch.jit.load(_download(_MODELS['ViT-B/16'])).eval()
251
+ state_dict = model.state_dict()
252
+
253
+ vision_width = state_dict["visual.conv1.weight"].shape[0]
254
+ vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
255
+ vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
256
+ grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
257
+ image_resolution = vision_patch_size * grid_size
258
+ embed_dim = state_dict["text_projection"].shape[1]
259
+ context_length = state_dict["positional_embedding"].shape[0]
260
+ vocab_size = state_dict["token_embedding.weight"].shape[0]
261
+ transformer_width = state_dict["ln_final.weight"].shape[0]
262
+ transformer_heads = transformer_width // 64
263
+ transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks")))
264
+
265
+ return CLIP(embed_dim, image_resolution, vision_layers, vision_width, vision_patch_size,
266
+ context_length, vocab_size, transformer_width, transformer_heads, transformer_layers)
267
+
268
+
269
+ class CLIPDensePredT(CLIPDenseBase):
270
+
271
+ def __init__(self, version='ViT-B/32', extract_layers=(3, 6, 9), cond_layer=0, reduce_dim=128, n_heads=4, prompt='fixed',
272
+ extra_blocks=0, reduce_cond=None, fix_shift=False,
273
+ learn_trans_conv_only=False, limit_to_clip_only=False, upsample=False,
274
+ add_calibration=False, rev_activations=False, trans_conv=None, n_tokens=None, complex_trans_conv=False):
275
+
276
+ super().__init__(version, reduce_cond, reduce_dim, prompt, n_tokens)
277
+ # device = 'cpu'
278
+
279
+ self.extract_layers = extract_layers
280
+ self.cond_layer = cond_layer
281
+ self.limit_to_clip_only = limit_to_clip_only
282
+ self.process_cond = None
283
+ self.rev_activations = rev_activations
284
+
285
+ depth = len(extract_layers)
286
+
287
+ if add_calibration:
288
+ self.calibration_conds = 1
289
+
290
+ self.upsample_proj = nn.Conv2d(reduce_dim, 1, kernel_size=1) if upsample else None
291
+
292
+ self.add_activation1 = True
293
+
294
+ self.version = version
295
+
296
+ self.token_shape = {'ViT-B/32': (7, 7), 'ViT-B/16': (14, 14)}[version]
297
+
298
+ if fix_shift:
299
+ # self.shift_vector = nn.Parameter(torch.load(join(dirname(basename(__file__)), 'clip_text_shift_vector.pth')), requires_grad=False)
300
+ self.shift_vector = nn.Parameter(torch.load(join(dirname(basename(__file__)), 'shift_text_to_vis.pth')), requires_grad=False)
301
+ # self.shift_vector = nn.Parameter(-1*torch.load(join(dirname(basename(__file__)), 'shift2.pth')), requires_grad=False)
302
+ else:
303
+ self.shift_vector = None
304
+
305
+ if trans_conv is None:
306
+ trans_conv_ks = {'ViT-B/32': (32, 32), 'ViT-B/16': (16, 16)}[version]
307
+ else:
308
+ # explicitly define transposed conv kernel size
309
+ trans_conv_ks = (trans_conv, trans_conv)
310
+
311
+ if not complex_trans_conv:
312
+ self.trans_conv = nn.ConvTranspose2d(reduce_dim, 1, trans_conv_ks, stride=trans_conv_ks)
313
+ else:
314
+ assert trans_conv_ks[0] == trans_conv_ks[1]
315
+
316
+ tp_kernels = (trans_conv_ks[0] // 4, trans_conv_ks[0] // 4)
317
+
318
+ self.trans_conv = nn.Sequential(
319
+ nn.Conv2d(reduce_dim, reduce_dim, kernel_size=3, padding=1),
320
+ nn.ReLU(),
321
+ nn.ConvTranspose2d(reduce_dim, reduce_dim // 2, kernel_size=tp_kernels[0], stride=tp_kernels[0]),
322
+ nn.ReLU(),
323
+ nn.ConvTranspose2d(reduce_dim // 2, 1, kernel_size=tp_kernels[1], stride=tp_kernels[1]),
324
+ )
325
+
326
+ # self.trans_conv = nn.ConvTranspose2d(reduce_dim, 1, trans_conv_ks, stride=trans_conv_ks)
327
+
328
+ assert len(self.extract_layers) == depth
329
+
330
+ self.reduces = nn.ModuleList([nn.Linear(768, reduce_dim) for _ in range(depth)])
331
+ self.blocks = nn.ModuleList([nn.TransformerEncoderLayer(d_model=reduce_dim, nhead=n_heads) for _ in range(len(self.extract_layers))])
332
+ self.extra_blocks = nn.ModuleList([nn.TransformerEncoderLayer(d_model=reduce_dim, nhead=n_heads) for _ in range(extra_blocks)])
333
+
334
+ # refinement and trans conv
335
+
336
+ if learn_trans_conv_only:
337
+ for p in self.parameters():
338
+ p.requires_grad_(False)
339
+
340
+ for p in self.trans_conv.parameters():
341
+ p.requires_grad_(True)
342
+
343
+ self.prompt_list = get_prompt_list(prompt)
344
+
345
+
346
+ def forward(self, inp_image, conditional=None, return_features=False, mask=None):
347
+
348
+ assert type(return_features) == bool
349
+
350
+ inp_image = inp_image.to(self.model.positional_embedding.device)
351
+
352
+ if mask is not None:
353
+ raise ValueError('mask not supported')
354
+
355
+ # x_inp = normalize(inp_image)
356
+ x_inp = inp_image
357
+
358
+ bs, dev = inp_image.shape[0], x_inp.device
359
+
360
+ cond = self.get_cond_vec(conditional, bs)
361
+
362
+ visual_q, activations, _ = self.visual_forward(x_inp, extract_layers=[0] + list(self.extract_layers))
363
+
364
+ activation1 = activations[0]
365
+ activations = activations[1:]
366
+
367
+ _activations = activations[::-1] if not self.rev_activations else activations
368
+
369
+ a = None
370
+ for i, (activation, block, reduce) in enumerate(zip(_activations, self.blocks, self.reduces)):
371
+
372
+ if a is not None:
373
+ a = reduce(activation) + a
374
+ else:
375
+ a = reduce(activation)
376
+
377
+ if i == self.cond_layer:
378
+ if self.reduce_cond is not None:
379
+ cond = self.reduce_cond(cond)
380
+
381
+ a = self.film_mul(cond) * a + self.film_add(cond)
382
+
383
+ a = block(a)
384
+
385
+ for block in self.extra_blocks:
386
+ a = a + block(a)
387
+
388
+ a = a[1:].permute(1, 2, 0) # rm cls token and -> BS, Feats, Tokens
389
+
390
+ size = int(math.sqrt(a.shape[2]))
391
+
392
+ a = a.view(bs, a.shape[1], size, size)
393
+
394
+ a = self.trans_conv(a)
395
+
396
+ if self.n_tokens is not None:
397
+ a = nnf.interpolate(a, x_inp.shape[2:], mode='bilinear', align_corners=True)
398
+
399
+ if self.upsample_proj is not None:
400
+ a = self.upsample_proj(a)
401
+ a = nnf.interpolate(a, x_inp.shape[2:], mode='bilinear')
402
+
403
+ if return_features:
404
+ return a, visual_q, cond, [activation1] + activations
405
+ else:
406
+ return a,
407
+
408
+
409
+
410
+ class CLIPDensePredTMasked(CLIPDensePredT):
411
+
412
+ def __init__(self, version='ViT-B/32', extract_layers=(3, 6, 9), cond_layer=0, reduce_dim=128, n_heads=4,
413
+ prompt='fixed', extra_blocks=0, reduce_cond=None, fix_shift=False, learn_trans_conv_only=False,
414
+ refine=None, limit_to_clip_only=False, upsample=False, add_calibration=False, n_tokens=None):
415
+
416
+ super().__init__(version=version, extract_layers=extract_layers, cond_layer=cond_layer, reduce_dim=reduce_dim,
417
+ n_heads=n_heads, prompt=prompt, extra_blocks=extra_blocks, reduce_cond=reduce_cond,
418
+ fix_shift=fix_shift, learn_trans_conv_only=learn_trans_conv_only,
419
+ limit_to_clip_only=limit_to_clip_only, upsample=upsample, add_calibration=add_calibration,
420
+ n_tokens=n_tokens)
421
+
422
+ def visual_forward_masked(self, img_s, seg_s):
423
+ return super().visual_forward(img_s, mask=('all', 'cls_token', seg_s))
424
+
425
+ def forward(self, img_q, cond_or_img_s, seg_s=None, return_features=False):
426
+
427
+ if seg_s is None:
428
+ cond = cond_or_img_s
429
+ else:
430
+ img_s = cond_or_img_s
431
+
432
+ with torch.no_grad():
433
+ cond, _, _ = self.visual_forward_masked(img_s, seg_s)
434
+
435
+ return super().forward(img_q, cond, return_features=return_features)
436
+
437
+
438
+
439
+ class CLIPDenseBaseline(CLIPDenseBase):
440
+
441
+ def __init__(self, version='ViT-B/32', cond_layer=0,
442
+ extract_layer=9, reduce_dim=128, reduce2_dim=None, prompt='fixed',
443
+ reduce_cond=None, limit_to_clip_only=False, n_tokens=None):
444
+
445
+ super().__init__(version, reduce_cond, reduce_dim, prompt, n_tokens)
446
+ device = 'cpu'
447
+
448
+ # self.cond_layer = cond_layer
449
+ self.extract_layer = extract_layer
450
+ self.limit_to_clip_only = limit_to_clip_only
451
+ self.shift_vector = None
452
+
453
+ self.token_shape = {'ViT-B/32': (7, 7), 'ViT-B/16': (14, 14)}[version]
454
+
455
+ assert reduce2_dim is not None
456
+
457
+ self.reduce2 = nn.Sequential(
458
+ nn.Linear(reduce_dim, reduce2_dim),
459
+ nn.ReLU(),
460
+ nn.Linear(reduce2_dim, reduce_dim)
461
+ )
462
+
463
+ trans_conv_ks = {'ViT-B/32': (32, 32), 'ViT-B/16': (16, 16)}[version]
464
+ self.trans_conv = nn.ConvTranspose2d(reduce_dim, 1, trans_conv_ks, stride=trans_conv_ks)
465
+
466
+
467
+ def forward(self, inp_image, conditional=None, return_features=False):
468
+
469
+ inp_image = inp_image.to(self.model.positional_embedding.device)
470
+
471
+ # x_inp = normalize(inp_image)
472
+ x_inp = inp_image
473
+
474
+ bs, dev = inp_image.shape[0], x_inp.device
475
+
476
+ cond = self.get_cond_vec(conditional, bs)
477
+
478
+ visual_q, activations, affinities = self.visual_forward(x_inp, extract_layers=[self.extract_layer])
479
+
480
+ a = activations[0]
481
+ a = self.reduce(a)
482
+ a = self.film_mul(cond) * a + self.film_add(cond)
483
+
484
+ if self.reduce2 is not None:
485
+ a = self.reduce2(a)
486
+
487
+ # the original model would execute a transformer block here
488
+
489
+ a = a[1:].permute(1, 2, 0) # rm cls token and -> BS, Feats, Tokens
490
+
491
+ size = int(math.sqrt(a.shape[2]))
492
+
493
+ a = a.view(bs, a.shape[1], size, size)
494
+ a = self.trans_conv(a)
495
+
496
+ if return_features:
497
+ return a, visual_q, cond, activations
498
+ else:
499
+ return a,
500
+
501
+
502
+ class CLIPSegMultiLabel(nn.Module):
503
+
504
+ def __init__(self, model) -> None:
505
+ super().__init__()
506
+
507
+ from third_party.JoEm.data_loader import get_seen_idx, get_unseen_idx, VOC
508
+
509
+ self.pascal_classes = VOC
510
+
511
+ from clip.clipseg import CLIPDensePredT
512
+ from general_utils import load_model
513
+ # self.clipseg = load_model('rd64-vit16-neg0.2-phrasecut', strict=False)
514
+ self.clipseg = load_model(model, strict=False)
515
+
516
+ self.clipseg.eval()
517
+
518
+ def forward(self, x):
519
+
520
+ bs = x.shape[0]
521
+ out = torch.ones(21, bs, 352, 352).to(x.device) * -10
522
+
523
+ for class_id, class_name in enumerate(self.pascal_classes):
524
+
525
+ fac = 3 if class_name == 'background' else 1
526
+
527
+ with torch.no_grad():
528
+ pred = torch.sigmoid(self.clipseg(x, class_name)[0][:,0]) * fac
529
+
530
+ out[class_id] += pred
531
+
532
+
533
+ out = out.permute(1, 0, 2, 3)
534
+
535
+ return out
536
+
537
+ # construct output tensor
538
+
clip/model.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from typing import Tuple, Union
3
+
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from torch import nn
8
+
9
+
10
+ class Bottleneck(nn.Module):
11
+ expansion = 4
12
+
13
+ def __init__(self, inplanes, planes, stride=1):
14
+ super().__init__()
15
+
16
+ # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
17
+ self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
18
+ self.bn1 = nn.BatchNorm2d(planes)
19
+ self.relu1 = nn.ReLU(inplace=True)
20
+
21
+ self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
22
+ self.bn2 = nn.BatchNorm2d(planes)
23
+ self.relu2 = nn.ReLU(inplace=True)
24
+
25
+ self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
26
+
27
+ self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
28
+ self.bn3 = nn.BatchNorm2d(planes * self.expansion)
29
+ self.relu3 = nn.ReLU(inplace=True)
30
+
31
+ self.downsample = None
32
+ self.stride = stride
33
+
34
+ if stride > 1 or inplanes != planes * Bottleneck.expansion:
35
+ # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
36
+ self.downsample = nn.Sequential(OrderedDict([
37
+ ("-1", nn.AvgPool2d(stride)),
38
+ ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
39
+ ("1", nn.BatchNorm2d(planes * self.expansion))
40
+ ]))
41
+
42
+ def forward(self, x: torch.Tensor):
43
+ identity = x
44
+
45
+ out = self.relu1(self.bn1(self.conv1(x)))
46
+ out = self.relu2(self.bn2(self.conv2(out)))
47
+ out = self.avgpool(out)
48
+ out = self.bn3(self.conv3(out))
49
+
50
+ if self.downsample is not None:
51
+ identity = self.downsample(x)
52
+
53
+ out += identity
54
+ out = self.relu3(out)
55
+ return out
56
+
57
+
58
+ class AttentionPool2d(nn.Module):
59
+ def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
60
+ super().__init__()
61
+ self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
62
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
63
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
64
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
65
+ self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
66
+ self.num_heads = num_heads
67
+
68
+ def forward(self, x):
69
+ x = x.flatten(start_dim=2).permute(2, 0, 1) # NCHW -> (HW)NC
70
+ x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
71
+ x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
72
+ x, _ = F.multi_head_attention_forward(
73
+ query=x[:1], key=x, value=x,
74
+ embed_dim_to_check=x.shape[-1],
75
+ num_heads=self.num_heads,
76
+ q_proj_weight=self.q_proj.weight,
77
+ k_proj_weight=self.k_proj.weight,
78
+ v_proj_weight=self.v_proj.weight,
79
+ in_proj_weight=None,
80
+ in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
81
+ bias_k=None,
82
+ bias_v=None,
83
+ add_zero_attn=False,
84
+ dropout_p=0,
85
+ out_proj_weight=self.c_proj.weight,
86
+ out_proj_bias=self.c_proj.bias,
87
+ use_separate_proj_weight=True,
88
+ training=self.training,
89
+ need_weights=False
90
+ )
91
+ return x.squeeze(0)
92
+
93
+
94
+ class ModifiedResNet(nn.Module):
95
+ """
96
+ A ResNet class that is similar to torchvision's but contains the following changes:
97
+ - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
98
+ - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
99
+ - The final pooling layer is a QKV attention instead of an average pool
100
+ """
101
+
102
+ def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
103
+ super().__init__()
104
+ self.output_dim = output_dim
105
+ self.input_resolution = input_resolution
106
+
107
+ # the 3-layer stem
108
+ self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
109
+ self.bn1 = nn.BatchNorm2d(width // 2)
110
+ self.relu1 = nn.ReLU(inplace=True)
111
+ self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
112
+ self.bn2 = nn.BatchNorm2d(width // 2)
113
+ self.relu2 = nn.ReLU(inplace=True)
114
+ self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
115
+ self.bn3 = nn.BatchNorm2d(width)
116
+ self.relu3 = nn.ReLU(inplace=True)
117
+ self.avgpool = nn.AvgPool2d(2)
118
+
119
+ # residual layers
120
+ self._inplanes = width # this is a *mutable* variable used during construction
121
+ self.layer1 = self._make_layer(width, layers[0])
122
+ self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
123
+ self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
124
+ self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
125
+
126
+ embed_dim = width * 32 # the ResNet feature dimension
127
+ self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
128
+
129
+ def _make_layer(self, planes, blocks, stride=1):
130
+ layers = [Bottleneck(self._inplanes, planes, stride)]
131
+
132
+ self._inplanes = planes * Bottleneck.expansion
133
+ for _ in range(1, blocks):
134
+ layers.append(Bottleneck(self._inplanes, planes))
135
+
136
+ return nn.Sequential(*layers)
137
+
138
+ def forward(self, x):
139
+ def stem(x):
140
+ x = self.relu1(self.bn1(self.conv1(x)))
141
+ x = self.relu2(self.bn2(self.conv2(x)))
142
+ x = self.relu3(self.bn3(self.conv3(x)))
143
+ x = self.avgpool(x)
144
+ return x
145
+
146
+ x = x.type(self.conv1.weight.dtype)
147
+ x = stem(x)
148
+ x = self.layer1(x)
149
+ x = self.layer2(x)
150
+ x = self.layer3(x)
151
+ x = self.layer4(x)
152
+ x = self.attnpool(x)
153
+
154
+ return x
155
+
156
+
157
+ class LayerNorm(nn.LayerNorm):
158
+ """Subclass torch's LayerNorm to handle fp16."""
159
+
160
+ def forward(self, x: torch.Tensor):
161
+ orig_type = x.dtype
162
+ ret = super().forward(x.type(torch.float32))
163
+ return ret.type(orig_type)
164
+
165
+
166
+ class QuickGELU(nn.Module):
167
+ def forward(self, x: torch.Tensor):
168
+ return x * torch.sigmoid(1.702 * x)
169
+
170
+
171
+ class ResidualAttentionBlock(nn.Module):
172
+ def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
173
+ super().__init__()
174
+
175
+ self.attn = nn.MultiheadAttention(d_model, n_head)
176
+ self.ln_1 = LayerNorm(d_model)
177
+ self.mlp = nn.Sequential(OrderedDict([
178
+ ("c_fc", nn.Linear(d_model, d_model * 4)),
179
+ ("gelu", QuickGELU()),
180
+ ("c_proj", nn.Linear(d_model * 4, d_model))
181
+ ]))
182
+ self.ln_2 = LayerNorm(d_model)
183
+ self.attn_mask = attn_mask
184
+
185
+ def attention(self, x: torch.Tensor):
186
+ self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
187
+ return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
188
+
189
+ def forward(self, x: torch.Tensor):
190
+ x = x + self.attention(self.ln_1(x))
191
+ x = x + self.mlp(self.ln_2(x))
192
+ return x
193
+
194
+
195
+ class Transformer(nn.Module):
196
+ def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):
197
+ super().__init__()
198
+ self.width = width
199
+ self.layers = layers
200
+ self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])
201
+
202
+ def forward(self, x: torch.Tensor):
203
+ return self.resblocks(x)
204
+
205
+
206
+ class VisionTransformer(nn.Module):
207
+ def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int):
208
+ super().__init__()
209
+ self.input_resolution = input_resolution
210
+ self.output_dim = output_dim
211
+ self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
212
+
213
+ scale = width ** -0.5
214
+ self.class_embedding = nn.Parameter(scale * torch.randn(width))
215
+ self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
216
+ self.ln_pre = LayerNorm(width)
217
+
218
+ self.transformer = Transformer(width, layers, heads)
219
+
220
+ self.ln_post = LayerNorm(width)
221
+ self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
222
+
223
+ def forward(self, x: torch.Tensor):
224
+ x = self.conv1(x) # shape = [*, width, grid, grid]
225
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
226
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
227
+ x = torch.cat([self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width]
228
+ x = x + self.positional_embedding.to(x.dtype)
229
+ x = self.ln_pre(x)
230
+
231
+ x = x.permute(1, 0, 2) # NLD -> LND
232
+ x = self.transformer(x)
233
+ x = x.permute(1, 0, 2) # LND -> NLD
234
+
235
+ x = self.ln_post(x[:, 0, :])
236
+
237
+ if self.proj is not None:
238
+ x = x @ self.proj
239
+
240
+ return x
241
+
242
+
243
+ class CLIP(nn.Module):
244
+ def __init__(self,
245
+ embed_dim: int,
246
+ # vision
247
+ image_resolution: int,
248
+ vision_layers: Union[Tuple[int, int, int, int], int],
249
+ vision_width: int,
250
+ vision_patch_size: int,
251
+ # text
252
+ context_length: int,
253
+ vocab_size: int,
254
+ transformer_width: int,
255
+ transformer_heads: int,
256
+ transformer_layers: int
257
+ ):
258
+ super().__init__()
259
+
260
+ self.context_length = context_length
261
+
262
+ if isinstance(vision_layers, (tuple, list)):
263
+ vision_heads = vision_width * 32 // 64
264
+ self.visual = ModifiedResNet(
265
+ layers=vision_layers,
266
+ output_dim=embed_dim,
267
+ heads=vision_heads,
268
+ input_resolution=image_resolution,
269
+ width=vision_width
270
+ )
271
+ else:
272
+ vision_heads = vision_width // 64
273
+ self.visual = VisionTransformer(
274
+ input_resolution=image_resolution,
275
+ patch_size=vision_patch_size,
276
+ width=vision_width,
277
+ layers=vision_layers,
278
+ heads=vision_heads,
279
+ output_dim=embed_dim
280
+ )
281
+
282
+ self.transformer = Transformer(
283
+ width=transformer_width,
284
+ layers=transformer_layers,
285
+ heads=transformer_heads,
286
+ attn_mask=self.build_attention_mask()
287
+ )
288
+
289
+ self.vocab_size = vocab_size
290
+ self.token_embedding = nn.Embedding(vocab_size, transformer_width)
291
+ self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))
292
+ self.ln_final = LayerNorm(transformer_width)
293
+
294
+ self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
295
+ self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
296
+
297
+ self.initialize_parameters()
298
+
299
+ def initialize_parameters(self):
300
+ nn.init.normal_(self.token_embedding.weight, std=0.02)
301
+ nn.init.normal_(self.positional_embedding, std=0.01)
302
+
303
+ if isinstance(self.visual, ModifiedResNet):
304
+ if self.visual.attnpool is not None:
305
+ std = self.visual.attnpool.c_proj.in_features ** -0.5
306
+ nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std)
307
+ nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std)
308
+ nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std)
309
+ nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)
310
+
311
+ for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]:
312
+ for name, param in resnet_block.named_parameters():
313
+ if name.endswith("bn3.weight"):
314
+ nn.init.zeros_(param)
315
+
316
+ proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
317
+ attn_std = self.transformer.width ** -0.5
318
+ fc_std = (2 * self.transformer.width) ** -0.5
319
+ for block in self.transformer.resblocks:
320
+ nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
321
+ nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
322
+ nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
323
+ nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
324
+
325
+ if self.text_projection is not None:
326
+ nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
327
+
328
+ def build_attention_mask(self):
329
+ # lazily create causal attention mask, with full attention between the vision tokens
330
+ # pytorch uses additive attention mask; fill with -inf
331
+ mask = torch.empty(self.context_length, self.context_length)
332
+ mask.fill_(float("-inf"))
333
+ mask.triu_(1) # zero out the lower diagonal
334
+ return mask
335
+
336
+ @property
337
+ def dtype(self):
338
+ return self.visual.conv1.weight.dtype
339
+
340
+ def encode_image(self, image):
341
+ return self.visual(image.type(self.dtype))
342
+
343
+ def encode_text(self, text):
344
+ x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
345
+
346
+ x = x + self.positional_embedding.type(self.dtype)
347
+ x = x.permute(1, 0, 2) # NLD -> LND
348
+ x = self.transformer(x)
349
+ x = x.permute(1, 0, 2) # LND -> NLD
350
+ x = self.ln_final(x).type(self.dtype)
351
+
352
+ # x.shape = [batch_size, n_ctx, transformer.width]
353
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
354
+ x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
355
+
356
+ return x
357
+
358
+ def forward(self, image, text):
359
+ image_features = self.encode_image(image)
360
+ text_features = self.encode_text(text)
361
+
362
+ # normalized features
363
+ image_features = image_features / image_features.norm(dim=1, keepdim=True)
364
+ text_features = text_features / text_features.norm(dim=1, keepdim=True)
365
+
366
+ # cosine similarity as logits
367
+ logit_scale = self.logit_scale.exp()
368
+ logits_per_image = logit_scale * image_features @ text_features.t()
369
+ logits_per_text = logits_per_image.t()
370
+
371
+ # shape = [global_batch_size, global_batch_size]
372
+ return logits_per_image, logits_per_text
373
+
374
+
375
+ def convert_weights(model: nn.Module):
376
+ """Convert applicable model parameters to fp16"""
377
+
378
+ def _convert_weights_to_fp16(l):
379
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
380
+ l.weight.data = l.weight.data.half()
381
+ if l.bias is not None:
382
+ l.bias.data = l.bias.data.half()
383
+
384
+ if isinstance(l, nn.MultiheadAttention):
385
+ for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
386
+ tensor = getattr(l, attr)
387
+ if tensor is not None:
388
+ tensor.data = tensor.data.half()
389
+
390
+ for name in ["text_projection", "proj"]:
391
+ if hasattr(l, name):
392
+ attr = getattr(l, name)
393
+ if attr is not None:
394
+ attr.data = attr.data.half()
395
+
396
+ model.apply(_convert_weights_to_fp16)
397
+
398
+
399
+ def build_model(state_dict: dict):
400
+ vit = "visual.proj" in state_dict
401
+
402
+ if vit:
403
+ vision_width = state_dict["visual.conv1.weight"].shape[0]
404
+ vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
405
+ vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
406
+ grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
407
+ image_resolution = vision_patch_size * grid_size
408
+ else:
409
+ counts: list = [len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]]
410
+ vision_layers = tuple(counts)
411
+ vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
412
+ output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
413
+ vision_patch_size = None
414
+ assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
415
+ image_resolution = output_width * 32
416
+
417
+ embed_dim = state_dict["text_projection"].shape[1]
418
+ context_length = state_dict["positional_embedding"].shape[0]
419
+ vocab_size = state_dict["token_embedding.weight"].shape[0]
420
+ transformer_width = state_dict["ln_final.weight"].shape[0]
421
+ transformer_heads = transformer_width // 64
422
+ transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith("transformer.resblocks")))
423
+
424
+ model = CLIP(
425
+ embed_dim,
426
+ image_resolution, vision_layers, vision_width, vision_patch_size,
427
+ context_length, vocab_size, transformer_width, transformer_heads, transformer_layers
428
+ )
429
+
430
+ for key in ["input_resolution", "context_length", "vocab_size"]:
431
+ if key in state_dict:
432
+ del state_dict[key]
433
+
434
+ convert_weights(model)
435
+ model.load_state_dict(state_dict)
436
+ return model.eval()
clip/simple_tokenizer.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gzip
2
+ import html
3
+ import os
4
+ from functools import lru_cache
5
+
6
+ import ftfy
7
+ import regex as re
8
+
9
+
10
+ @lru_cache()
11
+ def default_bpe():
12
+ return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
13
+
14
+
15
+ @lru_cache()
16
+ def bytes_to_unicode():
17
+ """
18
+ Returns list of utf-8 byte and a corresponding list of unicode strings.
19
+ The reversible bpe codes work on unicode strings.
20
+ This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
21
+ When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
22
+ This is a signficant percentage of your normal, say, 32K bpe vocab.
23
+ To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
24
+ And avoids mapping to whitespace/control characters the bpe code barfs on.
25
+ """
26
+ bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1))
27
+ cs = bs[:]
28
+ n = 0
29
+ for b in range(2**8):
30
+ if b not in bs:
31
+ bs.append(b)
32
+ cs.append(2**8+n)
33
+ n += 1
34
+ cs = [chr(n) for n in cs]
35
+ return dict(zip(bs, cs))
36
+
37
+
38
+ def get_pairs(word):
39
+ """Return set of symbol pairs in a word.
40
+ Word is represented as tuple of symbols (symbols being variable-length strings).
41
+ """
42
+ pairs = set()
43
+ prev_char = word[0]
44
+ for char in word[1:]:
45
+ pairs.add((prev_char, char))
46
+ prev_char = char
47
+ return pairs
48
+
49
+
50
+ def basic_clean(text):
51
+ text = ftfy.fix_text(text)
52
+ text = html.unescape(html.unescape(text))
53
+ return text.strip()
54
+
55
+
56
+ def whitespace_clean(text):
57
+ text = re.sub(r'\s+', ' ', text)
58
+ text = text.strip()
59
+ return text
60
+
61
+
62
+ class SimpleTokenizer(object):
63
+ def __init__(self, bpe_path: str = default_bpe()):
64
+ self.byte_encoder = bytes_to_unicode()
65
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
66
+ merges = gzip.open(bpe_path).read().decode("utf-8").split('\n')
67
+ merges = merges[1:49152-256-2+1]
68
+ merges = [tuple(merge.split()) for merge in merges]
69
+ vocab = list(bytes_to_unicode().values())
70
+ vocab = vocab + [v+'</w>' for v in vocab]
71
+ for merge in merges:
72
+ vocab.append(''.join(merge))
73
+ vocab.extend(['<|startoftext|>', '<|endoftext|>'])
74
+ self.encoder = dict(zip(vocab, range(len(vocab))))
75
+ self.decoder = {v: k for k, v in self.encoder.items()}
76
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
77
+ self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'}
78
+ self.pat = re.compile(r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE)
79
+
80
+ def bpe(self, token):
81
+ if token in self.cache:
82
+ return self.cache[token]
83
+ word = tuple(token[:-1]) + ( token[-1] + '</w>',)
84
+ pairs = get_pairs(word)
85
+
86
+ if not pairs:
87
+ return token+'</w>'
88
+
89
+ while True:
90
+ bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf')))
91
+ if bigram not in self.bpe_ranks:
92
+ break
93
+ first, second = bigram
94
+ new_word = []
95
+ i = 0
96
+ while i < len(word):
97
+ try:
98
+ j = word.index(first, i)
99
+ new_word.extend(word[i:j])
100
+ i = j
101
+ except:
102
+ new_word.extend(word[i:])
103
+ break
104
+
105
+ if word[i] == first and i < len(word)-1 and word[i+1] == second:
106
+ new_word.append(first+second)
107
+ i += 2
108
+ else:
109
+ new_word.append(word[i])
110
+ i += 1
111
+ new_word = tuple(new_word)
112
+ word = new_word
113
+ if len(word) == 1:
114
+ break
115
+ else:
116
+ pairs = get_pairs(word)
117
+ word = ' '.join(word)
118
+ self.cache[token] = word
119
+ return word
120
+
121
+ def encode(self, text):
122
+ bpe_tokens = []
123
+ text = whitespace_clean(basic_clean(text)).lower()
124
+ for token in re.findall(self.pat, text):
125
+ token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))
126
+ bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))
127
+ return bpe_tokens
128
+
129
+ def decode(self, tokens):
130
+ text = ''.join([self.decoder[token] for token in tokens])
131
+ text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('</w>', ' ')
132
+ return text
clip/vitseg.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from posixpath import basename, dirname, join
3
+ # import clip
4
+ from clip.model import convert_weights
5
+ import torch
6
+ import json
7
+ from torch import nn
8
+ from torch.nn import functional as nnf
9
+ from torch.nn.modules import activation
10
+ from torch.nn.modules.activation import ReLU
11
+ from torchvision import transforms
12
+
13
+ normalize = transforms.Normalize(mean=(0.48145466, 0.4578275, 0.40821073), std=(0.26862954, 0.26130258, 0.27577711))
14
+
15
+ from torchvision.models import ResNet
16
+
17
+
18
+ def process_prompts(conditional, prompt_list, conditional_map):
19
+ # DEPRECATED
20
+
21
+ # randomly sample a synonym
22
+ words = [conditional_map[int(i)] for i in conditional]
23
+ words = [syns[torch.multinomial(torch.ones(len(syns)), 1, replacement=True).item()] for syns in words]
24
+ words = [w.replace('_', ' ') for w in words]
25
+
26
+ if prompt_list is not None:
27
+ prompt_indices = torch.multinomial(torch.ones(len(prompt_list)), len(words), replacement=True)
28
+ prompts = [prompt_list[i] for i in prompt_indices]
29
+ else:
30
+ prompts = ['a photo of {}'] * (len(words))
31
+
32
+ return [promt.format(w) for promt, w in zip(prompts, words)]
33
+
34
+
35
+ class VITDenseBase(nn.Module):
36
+
37
+ def rescaled_pos_emb(self, new_size):
38
+ assert len(new_size) == 2
39
+
40
+ a = self.model.positional_embedding[1:].T.view(1, 768, *self.token_shape)
41
+ b = nnf.interpolate(a, new_size, mode='bicubic', align_corners=False).squeeze(0).view(768, new_size[0]*new_size[1]).T
42
+ return torch.cat([self.model.positional_embedding[:1], b])
43
+
44
+ def visual_forward(self, x_inp, extract_layers=(), skip=False, mask=None):
45
+
46
+ with torch.no_grad():
47
+
48
+ x_inp = nnf.interpolate(x_inp, (384, 384))
49
+
50
+ x = self.model.patch_embed(x_inp)
51
+ cls_token = self.model.cls_token.expand(x.shape[0], -1, -1) # stole cls_tokens impl from Phil Wang, thanks
52
+ if self.model.dist_token is None:
53
+ x = torch.cat((cls_token, x), dim=1)
54
+ else:
55
+ x = torch.cat((cls_token, self.model.dist_token.expand(x.shape[0], -1, -1), x), dim=1)
56
+ x = self.model.pos_drop(x + self.model.pos_embed)
57
+
58
+ activations = []
59
+ for i, block in enumerate(self.model.blocks):
60
+ x = block(x)
61
+
62
+ if i in extract_layers:
63
+ # permute to be compatible with CLIP
64
+ activations += [x.permute(1,0,2)]
65
+
66
+ x = self.model.norm(x)
67
+ x = self.model.head(self.model.pre_logits(x[:, 0]))
68
+
69
+ # again for CLIP compatibility
70
+ # x = x.permute(1, 0, 2)
71
+
72
+ return x, activations, None
73
+
74
+ def sample_prompts(self, words, prompt_list=None):
75
+
76
+ prompt_list = prompt_list if prompt_list is not None else self.prompt_list
77
+
78
+ prompt_indices = torch.multinomial(torch.ones(len(prompt_list)), len(words), replacement=True)
79
+ prompts = [prompt_list[i] for i in prompt_indices]
80
+ return [promt.format(w) for promt, w in zip(prompts, words)]
81
+
82
+ def get_cond_vec(self, conditional, batch_size):
83
+ # compute conditional from a single string
84
+ if conditional is not None and type(conditional) == str:
85
+ cond = self.compute_conditional(conditional)
86
+ cond = cond.repeat(batch_size, 1)
87
+
88
+ # compute conditional from string list/tuple
89
+ elif conditional is not None and type(conditional) in {list, tuple} and type(conditional[0]) == str:
90
+ assert len(conditional) == batch_size
91
+ cond = self.compute_conditional(conditional)
92
+
93
+ # use conditional directly
94
+ elif conditional is not None and type(conditional) == torch.Tensor and conditional.ndim == 2:
95
+ cond = conditional
96
+
97
+ # compute conditional from image
98
+ elif conditional is not None and type(conditional) == torch.Tensor:
99
+ with torch.no_grad():
100
+ cond, _, _ = self.visual_forward(conditional)
101
+ else:
102
+ raise ValueError('invalid conditional')
103
+ return cond
104
+
105
+ def compute_conditional(self, conditional):
106
+ import clip
107
+
108
+ dev = next(self.parameters()).device
109
+
110
+ if type(conditional) in {list, tuple}:
111
+ text_tokens = clip.tokenize(conditional).to(dev)
112
+ cond = self.clip_model.encode_text(text_tokens)
113
+ else:
114
+ if conditional in self.precomputed_prompts:
115
+ cond = self.precomputed_prompts[conditional].float().to(dev)
116
+ else:
117
+ text_tokens = clip.tokenize([conditional]).to(dev)
118
+ cond = self.clip_model.encode_text(text_tokens)[0]
119
+
120
+ return cond
121
+
122
+
123
+ class VITDensePredT(VITDenseBase):
124
+
125
+ def __init__(self, extract_layers=(3, 6, 9), cond_layer=0, reduce_dim=128, n_heads=4, prompt='fixed',
126
+ depth=3, extra_blocks=0, reduce_cond=None, fix_shift=False,
127
+ learn_trans_conv_only=False, refine=None, limit_to_clip_only=False, upsample=False,
128
+ add_calibration=False, process_cond=None, not_pretrained=False):
129
+ super().__init__()
130
+ # device = 'cpu'
131
+
132
+ self.extract_layers = extract_layers
133
+ self.cond_layer = cond_layer
134
+ self.limit_to_clip_only = limit_to_clip_only
135
+ self.process_cond = None
136
+
137
+ if add_calibration:
138
+ self.calibration_conds = 1
139
+
140
+ self.upsample_proj = nn.Conv2d(reduce_dim, 1, kernel_size=1) if upsample else None
141
+
142
+ self.add_activation1 = True
143
+
144
+ import timm
145
+ self.model = timm.create_model('vit_base_patch16_384', pretrained=True)
146
+ self.model.head = nn.Linear(768, 512 if reduce_cond is None else reduce_cond)
147
+
148
+ for p in self.model.parameters():
149
+ p.requires_grad_(False)
150
+
151
+ import clip
152
+ self.clip_model, _ = clip.load('ViT-B/16', device='cpu', jit=False)
153
+ # del self.clip_model.visual
154
+
155
+
156
+ self.token_shape = (14, 14)
157
+
158
+ # conditional
159
+ if reduce_cond is not None:
160
+ self.reduce_cond = nn.Linear(512, reduce_cond)
161
+ for p in self.reduce_cond.parameters():
162
+ p.requires_grad_(False)
163
+ else:
164
+ self.reduce_cond = None
165
+
166
+ # self.film = AVAILABLE_BLOCKS['film'](512, 128)
167
+ self.film_mul = nn.Linear(512 if reduce_cond is None else reduce_cond, reduce_dim)
168
+ self.film_add = nn.Linear(512 if reduce_cond is None else reduce_cond, reduce_dim)
169
+
170
+ # DEPRECATED
171
+ # self.conditional_map = {c['id']: c['synonyms'] for c in json.load(open(cond_map))}
172
+
173
+ assert len(self.extract_layers) == depth
174
+
175
+ self.reduces = nn.ModuleList([nn.Linear(768, reduce_dim) for _ in range(depth)])
176
+ self.blocks = nn.ModuleList([nn.TransformerEncoderLayer(d_model=reduce_dim, nhead=n_heads) for _ in range(len(self.extract_layers))])
177
+ self.extra_blocks = nn.ModuleList([nn.TransformerEncoderLayer(d_model=reduce_dim, nhead=n_heads) for _ in range(extra_blocks)])
178
+
179
+ trans_conv_ks = (16, 16)
180
+ self.trans_conv = nn.ConvTranspose2d(reduce_dim, 1, trans_conv_ks, stride=trans_conv_ks)
181
+
182
+ # refinement and trans conv
183
+
184
+ if learn_trans_conv_only:
185
+ for p in self.parameters():
186
+ p.requires_grad_(False)
187
+
188
+ for p in self.trans_conv.parameters():
189
+ p.requires_grad_(True)
190
+
191
+ if prompt == 'fixed':
192
+ self.prompt_list = ['a photo of a {}.']
193
+ elif prompt == 'shuffle':
194
+ self.prompt_list = ['a photo of a {}.', 'a photograph of a {}.', 'an image of a {}.', '{}.']
195
+ elif prompt == 'shuffle+':
196
+ self.prompt_list = ['a photo of a {}.', 'a photograph of a {}.', 'an image of a {}.', '{}.',
197
+ 'a cropped photo of a {}.', 'a good photo of a {}.', 'a photo of one {}.',
198
+ 'a bad photo of a {}.', 'a photo of the {}.']
199
+ elif prompt == 'shuffle_clip':
200
+ from models.clip_prompts import imagenet_templates
201
+ self.prompt_list = imagenet_templates
202
+
203
+ if process_cond is not None:
204
+ if process_cond == 'clamp' or process_cond[0] == 'clamp':
205
+
206
+ val = process_cond[1] if type(process_cond) in {list, tuple} else 0.2
207
+
208
+ def clamp_vec(x):
209
+ return torch.clamp(x, -val, val)
210
+
211
+ self.process_cond = clamp_vec
212
+
213
+ elif process_cond.endswith('.pth'):
214
+
215
+ shift = torch.load(process_cond)
216
+ def add_shift(x):
217
+ return x + shift.to(x.device)
218
+
219
+ self.process_cond = add_shift
220
+
221
+ import pickle
222
+ precomp = pickle.load(open('precomputed_prompt_vectors.pickle', 'rb'))
223
+ self.precomputed_prompts = {k: torch.from_numpy(v) for k, v in precomp.items()}
224
+
225
+
226
+ def forward(self, inp_image, conditional=None, return_features=False, mask=None):
227
+
228
+ assert type(return_features) == bool
229
+
230
+ # inp_image = inp_image.to(self.model.positional_embedding.device)
231
+
232
+ if mask is not None:
233
+ raise ValueError('mask not supported')
234
+
235
+ # x_inp = normalize(inp_image)
236
+ x_inp = inp_image
237
+
238
+ bs, dev = inp_image.shape[0], x_inp.device
239
+
240
+ inp_image_size = inp_image.shape[2:]
241
+
242
+ cond = self.get_cond_vec(conditional, bs)
243
+
244
+ visual_q, activations, _ = self.visual_forward(x_inp, extract_layers=[0] + list(self.extract_layers))
245
+
246
+ activation1 = activations[0]
247
+ activations = activations[1:]
248
+
249
+ a = None
250
+ for i, (activation, block, reduce) in enumerate(zip(activations[::-1], self.blocks, self.reduces)):
251
+
252
+ if a is not None:
253
+ a = reduce(activation) + a
254
+ else:
255
+ a = reduce(activation)
256
+
257
+ if i == self.cond_layer:
258
+ if self.reduce_cond is not None:
259
+ cond = self.reduce_cond(cond)
260
+
261
+ a = self.film_mul(cond) * a + self.film_add(cond)
262
+
263
+ a = block(a)
264
+
265
+ for block in self.extra_blocks:
266
+ a = a + block(a)
267
+
268
+ a = a[1:].permute(1, 2, 0) # rm cls token and -> BS, Feats, Tokens
269
+
270
+ size = int(math.sqrt(a.shape[2]))
271
+
272
+ a = a.view(bs, a.shape[1], size, size)
273
+
274
+ if self.trans_conv is not None:
275
+ a = self.trans_conv(a)
276
+
277
+ if self.upsample_proj is not None:
278
+ a = self.upsample_proj(a)
279
+ a = nnf.interpolate(a, x_inp.shape[2:], mode='bilinear')
280
+
281
+ a = nnf.interpolate(a, inp_image_size)
282
+
283
+ if return_features:
284
+ return a, visual_q, cond, [activation1] + activations
285
+ else:
286
+ return a,
config_colab.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ clear_output: true
2
+ force_cpu: false
3
+ live_cam_start_active: false
4
+ max_threads: 3
5
+ memory_limit: 0
6
+ output_image_format: png
7
+ output_template: '{file}_{time}'
8
+ output_video_codec: libx264
9
+ output_video_format: mp4
10
+ provider: cuda
11
+ selected_theme: Default
12
+ server_name: ''
13
+ server_port: 0
14
+ server_share: true
15
+ video_quality: 14
docs/screenshot.png ADDED

Git LFS Details

  • SHA256: 51852858923e217894effd4fb94f3ab216a7a84e3e5aa09a6c5d482ab1a4e563
  • Pointer size: 132 Bytes
  • Size of remote file: 1.9 MB
installer/installer.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import glob
3
+ import os
4
+ import shutil
5
+ import site
6
+ import subprocess
7
+ import sys
8
+
9
+
10
+ script_dir = os.getcwd()
11
+
12
+
13
+ def run_cmd(cmd, capture_output=False, env=None):
14
+ # Run shell commands
15
+ return subprocess.run(cmd, shell=True, capture_output=capture_output, env=env)
16
+
17
+
18
+ def check_env():
19
+ # If we have access to conda, we are probably in an environment
20
+ conda_not_exist = run_cmd("conda", capture_output=True).returncode
21
+ if conda_not_exist:
22
+ print("Conda is not installed. Exiting...")
23
+ sys.exit()
24
+
25
+ # Ensure this is a new environment and not the base environment
26
+ if os.environ["CONDA_DEFAULT_ENV"] == "base":
27
+ print("Create an environment for this project and activate it. Exiting...")
28
+ sys.exit()
29
+
30
+
31
+ def install_dependencies():
32
+ # Install Git and clone repo
33
+ run_cmd("conda install -y -k git")
34
+ run_cmd("git clone https://github.com/C0untFloyd/roop-unleashed.git")
35
+ run_cmd("git checkout 8ee085322158c4eeb0cd0126a49949f1acf0f7df")
36
+ # Install the webui dependencies
37
+ update_dependencies()
38
+
39
+
40
+ def update_dependencies():
41
+ global MY_PATH
42
+
43
+ os.chdir(MY_PATH)
44
+ # do a hard reset for to update even if there are local changes
45
+ run_cmd("git fetch --all")
46
+ run_cmd("git reset --hard origin/main")
47
+ run_cmd("git pull")
48
+ # Installs/Updates dependencies from all requirements.txt
49
+ run_cmd("python -m pip install -r requirements.txt")
50
+
51
+
52
+ def start_app():
53
+ global MY_PATH
54
+
55
+ os.chdir(MY_PATH)
56
+ # forward commandline arguments
57
+ sys.argv.pop(0)
58
+ args = ' '.join(sys.argv)
59
+ print("Launching App")
60
+ run_cmd(f'python run.py {args}')
61
+
62
+
63
+ if __name__ == "__main__":
64
+ global MY_PATH
65
+
66
+ MY_PATH = "roop-unleashed"
67
+
68
+
69
+ # Verifies we are in a conda environment
70
+ check_env()
71
+
72
+ # If webui has already been installed, skip and run
73
+ if not os.path.exists(MY_PATH):
74
+ install_dependencies()
75
+ else:
76
+ # moved update from batch to here, because of batch limitations
77
+ updatechoice = input("Check for Updates? [y/n]").lower()
78
+ if updatechoice == "y":
79
+ update_dependencies()
80
+
81
+ # Run the model with webui
82
+ os.chdir(script_dir)
83
+ start_app()
installer/windows_run.bat ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ REM Please set the following commandline arguments to your prefered settings
3
+ set COMMANDLINE_ARGS=
4
+
5
+ cd /D "%~dp0"
6
+
7
+ echo "%CD%"| findstr /C:" " >nul && echo This script relies on Miniconda which can not be silently installed under a path with spaces. && goto end
8
+
9
+ set PATH=%PATH%;%SystemRoot%\system32
10
+
11
+ @rem config
12
+ set INSTALL_DIR=%cd%\installer_files
13
+ set CONDA_ROOT_PREFIX=%cd%\installer_files\conda
14
+ set INSTALL_ENV_DIR=%cd%\installer_files\env
15
+ set MINICONDA_DOWNLOAD_URL=https://repo.anaconda.com/miniconda/Miniconda3-latest-Windows-x86_64.exe
16
+ set FFMPEG_DOWNLOAD_URL=https://github.com/GyanD/codexffmpeg/releases/download/2023-06-21-git-1bcb8a7338/ffmpeg-2023-06-21-git-1bcb8a7338-essentials_build.zip
17
+ set INSTALL_FFMPEG_DIR=%cd%\installer_files\ffmpeg
18
+ set conda_exists=F
19
+
20
+ @rem figure out whether git and conda needs to be installed
21
+ call "%CONDA_ROOT_PREFIX%\_conda.exe" --version >nul 2>&1
22
+ if "%ERRORLEVEL%" EQU "0" set conda_exists=T
23
+
24
+ @rem (if necessary) install git and conda into a contained environment
25
+ @rem download conda
26
+ if "%conda_exists%" == "F" (
27
+ echo Downloading Miniconda from %MINICONDA_DOWNLOAD_URL% to %INSTALL_DIR%\miniconda_installer.exe
28
+
29
+ mkdir "%INSTALL_DIR%"
30
+ call curl -Lk "%MINICONDA_DOWNLOAD_URL%" > "%INSTALL_DIR%\miniconda_installer.exe" || ( echo. && echo Miniconda failed to download. && goto end )
31
+
32
+ echo Installing Miniconda to %CONDA_ROOT_PREFIX%
33
+ start /wait "" "%INSTALL_DIR%\miniconda_installer.exe" /InstallationType=JustMe /NoShortcuts=1 /AddToPath=0 /RegisterPython=0 /NoRegistry=1 /S /D=%CONDA_ROOT_PREFIX%
34
+
35
+ @rem test the conda binary
36
+ echo Miniconda version:
37
+ call "%CONDA_ROOT_PREFIX%\_conda.exe" --version || ( echo. && echo Miniconda not found. && goto end )
38
+ )
39
+
40
+ @rem create the installer env
41
+ if not exist "%INSTALL_ENV_DIR%" (
42
+ echo Packages to install: %PACKAGES_TO_INSTALL%
43
+ call "%CONDA_ROOT_PREFIX%\_conda.exe" create --no-shortcuts -y -k --prefix "%INSTALL_ENV_DIR%" python=3.10 || ( echo. && echo Conda environment creation failed. && goto end )
44
+ )
45
+
46
+ if not exist "%INSTALL_FFMPEG_DIR%" (
47
+ echo Downloading ffmpeg from %FFMPEG_DOWNLOAD_URL% to %INSTALL_DIR%
48
+ call curl -Lk "%FFMPEG_DOWNLOAD_URL%" > "%INSTALL_DIR%\ffmpeg.zip" || ( echo. && echo ffmpeg failed to download. && goto end )
49
+ call powershell -command "Expand-Archive -Force '%INSTALL_DIR%\ffmpeg.zip' '%INSTALL_DIR%\'"
50
+
51
+ cd "installer_files"
52
+ setlocal EnableExtensions EnableDelayedExpansion
53
+
54
+ for /f "tokens=*" %%f in ('dir /s /b /ad "ffmpeg*"') do (
55
+ ren "%%f" "ffmpeg"
56
+ )
57
+ endlocal
58
+ setx PATH "%INSTALL_FFMPEG_DIR%\bin\;%PATH%"
59
+ echo To use videos, you need to restart roop after this installation.
60
+ cd ..
61
+ )
62
+
63
+ @rem check if conda environment was actually created
64
+ if not exist "%INSTALL_ENV_DIR%\python.exe" ( echo. && echo ERROR: Conda environment is empty. && goto end )
65
+
66
+ @rem activate installer env
67
+ call "%CONDA_ROOT_PREFIX%\condabin\conda.bat" activate "%INSTALL_ENV_DIR%" || ( echo. && echo Miniconda hook not found. && goto end )
68
+
69
+ @rem setup installer env
70
+ echo Launching roop unleashed - please edit windows_run.bat to customize commandline arguments
71
+ call python installer.py %COMMANDLINE_ARGS%
72
+
73
+ echo.
74
+ echo Done!
75
+
76
+ :end
77
+ pause
78
+
79
+
80
+
mypy.ini ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ [mypy]
2
+ check_untyped_defs = True
3
+ disallow_any_generics = True
4
+ disallow_untyped_calls = True
5
+ disallow_untyped_defs = True
6
+ ignore_missing_imports = True
7
+ strict_optional = False
requirements.txt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cu118
2
+
3
+ numpy==1.24.2
4
+ gradio>=3.41.2
5
+ opencv-python==4.7.0.72
6
+ onnx==1.14.0
7
+ insightface==0.7.3
8
+ psutil==5.9.5
9
+ pillow==9.5.0
10
+ torch==2.0.1+cu118; sys_platform != 'darwin'
11
+ torch==2.0.1; sys_platform == 'darwin'
12
+ torchvision==0.15.2+cu118; sys_platform != 'darwin'
13
+ torchvision==0.15.2; sys_platform == 'darwin'
14
+ onnxruntime==1.15.0; sys_platform == 'darwin' and platform_machine != 'arm64'
15
+ onnxruntime-silicon==1.13.1; sys_platform == 'darwin' and platform_machine == 'arm64'
16
+ onnxruntime-gpu==1.15.0; sys_platform != 'darwin'
17
+ tensorflow==2.13.0
18
+ protobuf==4.23.2
19
+ tqdm==4.65.0
20
+ codeformer-pip==0.0.4
21
+ gfpgan==1.3.8
22
+ ftfy
23
+ regex
24
+ pyvirtualcam
roop-unleashed.ipynb ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "gpuType": "T4",
8
+ "collapsed_sections": [
9
+ "UdQ1VHdI8lCf"
10
+ ]
11
+ },
12
+ "kernelspec": {
13
+ "name": "python3",
14
+ "display_name": "Python 3"
15
+ },
16
+ "language_info": {
17
+ "name": "python"
18
+ },
19
+ "accelerator": "GPU"
20
+ },
21
+ "cells": [
22
+ {
23
+ "cell_type": "markdown",
24
+ "source": [
25
+ "# Colab for roop-unleashed - Gradio version\n",
26
+ "https://github.com/C0untFloyd/roop-unleashed\n"
27
+ ],
28
+ "metadata": {
29
+ "id": "G9BdiCppV6AS"
30
+ }
31
+ },
32
+ {
33
+ "cell_type": "markdown",
34
+ "source": [
35
+ "Installing & preparing requirements"
36
+ ],
37
+ "metadata": {
38
+ "id": "0ZYRNb0AWLLW"
39
+ }
40
+ },
41
+ {
42
+ "cell_type": "code",
43
+ "execution_count": null,
44
+ "metadata": {
45
+ "id": "t1yPuhdySqCq"
46
+ },
47
+ "outputs": [],
48
+ "source": [
49
+ "!git clone https://github.com/C0untFloyd/roop-unleashed.git\n",
50
+ "%cd roop-unleashed\n",
51
+ "!mv config_colab.yaml config.yaml\n",
52
+ "!pip install pip install -r requirements.txt"
53
+ ]
54
+ },
55
+ {
56
+ "cell_type": "markdown",
57
+ "source": [
58
+ "Running roop-unleashed with default config"
59
+ ],
60
+ "metadata": {
61
+ "id": "u_4JQiSlV9Fi"
62
+ }
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "source": [
67
+ "!python run.py"
68
+ ],
69
+ "metadata": {
70
+ "id": "Is6U2huqSzLE"
71
+ },
72
+ "execution_count": null,
73
+ "outputs": []
74
+ },
75
+ {
76
+ "cell_type": "markdown",
77
+ "source": [
78
+ "### Download generated images folder\n",
79
+ "(only needed if you want to zip the generated output)"
80
+ ],
81
+ "metadata": {
82
+ "id": "UdQ1VHdI8lCf"
83
+ }
84
+ },
85
+ {
86
+ "cell_type": "code",
87
+ "source": [
88
+ "import shutil\n",
89
+ "import os\n",
90
+ "from google.colab import files\n",
91
+ "\n",
92
+ "def zip_directory(directory_path, zip_path):\n",
93
+ " shutil.make_archive(zip_path, 'zip', directory_path)\n",
94
+ "\n",
95
+ "# Set the directory path you want to download\n",
96
+ "directory_path = '/content/roop-unleashed/output'\n",
97
+ "\n",
98
+ "# Set the zip file name\n",
99
+ "zip_filename = 'fake_output.zip'\n",
100
+ "\n",
101
+ "# Zip the directory\n",
102
+ "zip_directory(directory_path, zip_filename)\n",
103
+ "\n",
104
+ "# Download the zip file\n",
105
+ "files.download(zip_filename+'.zip')\n"
106
+ ],
107
+ "metadata": {
108
+ "colab": {
109
+ "base_uri": "https://localhost:8080/",
110
+ "height": 17
111
+ },
112
+ "id": "oYjWveAmw10X",
113
+ "outputId": "5b4c3650-f951-434a-c650-5525a8a70c1e"
114
+ },
115
+ "execution_count": null,
116
+ "outputs": [
117
+ {
118
+ "output_type": "display_data",
119
+ "data": {
120
+ "text/plain": [
121
+ "<IPython.core.display.Javascript object>"
122
+ ],
123
+ "application/javascript": [
124
+ "\n",
125
+ " async function download(id, filename, size) {\n",
126
+ " if (!google.colab.kernel.accessAllowed) {\n",
127
+ " return;\n",
128
+ " }\n",
129
+ " const div = document.createElement('div');\n",
130
+ " const label = document.createElement('label');\n",
131
+ " label.textContent = `Downloading \"${filename}\": `;\n",
132
+ " div.appendChild(label);\n",
133
+ " const progress = document.createElement('progress');\n",
134
+ " progress.max = size;\n",
135
+ " div.appendChild(progress);\n",
136
+ " document.body.appendChild(div);\n",
137
+ "\n",
138
+ " const buffers = [];\n",
139
+ " let downloaded = 0;\n",
140
+ "\n",
141
+ " const channel = await google.colab.kernel.comms.open(id);\n",
142
+ " // Send a message to notify the kernel that we're ready.\n",
143
+ " channel.send({})\n",
144
+ "\n",
145
+ " for await (const message of channel.messages) {\n",
146
+ " // Send a message to notify the kernel that we're ready.\n",
147
+ " channel.send({})\n",
148
+ " if (message.buffers) {\n",
149
+ " for (const buffer of message.buffers) {\n",
150
+ " buffers.push(buffer);\n",
151
+ " downloaded += buffer.byteLength;\n",
152
+ " progress.value = downloaded;\n",
153
+ " }\n",
154
+ " }\n",
155
+ " }\n",
156
+ " const blob = new Blob(buffers, {type: 'application/binary'});\n",
157
+ " const a = document.createElement('a');\n",
158
+ " a.href = window.URL.createObjectURL(blob);\n",
159
+ " a.download = filename;\n",
160
+ " div.appendChild(a);\n",
161
+ " a.click();\n",
162
+ " div.remove();\n",
163
+ " }\n",
164
+ " "
165
+ ]
166
+ },
167
+ "metadata": {}
168
+ },
169
+ {
170
+ "output_type": "display_data",
171
+ "data": {
172
+ "text/plain": [
173
+ "<IPython.core.display.Javascript object>"
174
+ ],
175
+ "application/javascript": [
176
+ "download(\"download_789eab11-93d2-4880-adf3-6aceee0cc5f9\", \"fake_output.zip.zip\", 80125)"
177
+ ]
178
+ },
179
+ "metadata": {}
180
+ }
181
+ ]
182
+ }
183
+ ]
184
+ }
roop/ProcessEntry.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ class ProcessEntry:
2
+ def __init__(self, filename: str, start: int, end: int, fps: float):
3
+ self.filename = filename
4
+ self.finalname = None
5
+ self.startframe = start
6
+ self.endframe = end
7
+ self.fps = fps
roop/ProcessMgr.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import numpy as np
4
+ import psutil
5
+
6
+ from roop.ProcessOptions import ProcessOptions
7
+
8
+ from roop.face_util import get_first_face, get_all_faces
9
+ from roop.utilities import compute_cosine_distance, get_device, str_to_class
10
+
11
+ from typing import Any, List, Callable
12
+ from roop.typing import Frame
13
+ from concurrent.futures import ThreadPoolExecutor, as_completed
14
+ from threading import Thread, Lock
15
+ from queue import Queue
16
+ from tqdm import tqdm
17
+ from roop.ffmpeg_writer import FFMPEG_VideoWriter
18
+ import roop.globals
19
+
20
+
21
+ def create_queue(temp_frame_paths: List[str]) -> Queue[str]:
22
+ queue: Queue[str] = Queue()
23
+ for frame_path in temp_frame_paths:
24
+ queue.put(frame_path)
25
+ return queue
26
+
27
+
28
+ def pick_queue(queue: Queue[str], queue_per_future: int) -> List[str]:
29
+ queues = []
30
+ for _ in range(queue_per_future):
31
+ if not queue.empty():
32
+ queues.append(queue.get())
33
+ return queues
34
+
35
+
36
+ class ProcessMgr():
37
+ input_face_datas = []
38
+ target_face_datas = []
39
+
40
+ processors = []
41
+ options : ProcessOptions = None
42
+
43
+ num_threads = 1
44
+ current_index = 0
45
+ processing_threads = 1
46
+ buffer_wait_time = 0.1
47
+
48
+ lock = Lock()
49
+
50
+ frames_queue = None
51
+ processed_queue = None
52
+
53
+ videowriter= None
54
+
55
+ progress_gradio = None
56
+ total_frames = 0
57
+
58
+
59
+
60
+ # 5-point template constant for face alignment - don't ask
61
+ insight_arcface_dst = np.array(
62
+ [[38.2946, 51.6963], [73.5318, 51.5014], [56.0252, 71.7366],
63
+ [41.5493, 92.3655], [70.7299, 92.2041]],
64
+ dtype=np.float32)
65
+
66
+ plugins = {
67
+ 'faceswap' : 'FaceSwapInsightFace',
68
+ 'mask_clip2seg' : 'Mask_Clip2Seg',
69
+ 'codeformer' : 'Enhance_CodeFormer',
70
+ 'gfpgan' : 'Enhance_GFPGAN',
71
+ 'dmdnet' : 'Enhance_DMDNet',
72
+ }
73
+
74
+ def __init__(self, progress):
75
+ if progress is not None:
76
+ self.progress_gradio = progress
77
+
78
+
79
+ def initialize(self, input_faces, target_faces, options):
80
+ self.input_face_datas = input_faces
81
+ self.target_face_datas = target_faces
82
+ self.options = options
83
+
84
+ processornames = options.processors.split(",")
85
+ devicename = get_device()
86
+ if len(self.processors) < 1:
87
+ for pn in processornames:
88
+ classname = self.plugins[pn]
89
+ module = 'roop.processors.' + classname
90
+ p = str_to_class(module, classname)
91
+ p.Initialize(devicename)
92
+ self.processors.append(p)
93
+ else:
94
+ for i in range(len(self.processors) -1, -1, -1):
95
+ if not self.processors[i].processorname in processornames:
96
+ self.processors[i].Release()
97
+ del self.processors[i]
98
+
99
+ for i,pn in enumerate(processornames):
100
+ if i >= len(self.processors) or self.processors[i].processorname != pn:
101
+ p = None
102
+ classname = self.plugins[pn]
103
+ module = 'roop.processors.' + classname
104
+ p = str_to_class(module, classname)
105
+ p.Initialize(devicename)
106
+ if p is not None:
107
+ self.processors.insert(i, p)
108
+
109
+
110
+
111
+ def run_batch(self, source_files, target_files, threads:int = 1):
112
+ progress_bar_format = '{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]'
113
+ self.total_frames = len(source_files)
114
+ self.num_threads = threads
115
+ with tqdm(total=self.total_frames, desc='Processing', unit='frame', dynamic_ncols=True, bar_format=progress_bar_format) as progress:
116
+ with ThreadPoolExecutor(max_workers=threads) as executor:
117
+ futures = []
118
+ queue = create_queue(source_files)
119
+ queue_per_future = max(len(source_files) // threads, 1)
120
+ while not queue.empty():
121
+ future = executor.submit(self.process_frames, source_files, target_files, pick_queue(queue, queue_per_future), lambda: self.update_progress(progress))
122
+ futures.append(future)
123
+ for future in as_completed(futures):
124
+ future.result()
125
+
126
+
127
+ def process_frames(self, source_files: List[str], target_files: List[str], current_files, update: Callable[[], None]) -> None:
128
+ for f in current_files:
129
+ if not roop.globals.processing:
130
+ return
131
+
132
+ temp_frame = cv2.imread(f)
133
+ if temp_frame is not None:
134
+ resimg = self.process_frame(temp_frame)
135
+ if resimg is not None:
136
+ i = source_files.index(f)
137
+ cv2.imwrite(target_files[i], resimg)
138
+ if update:
139
+ update()
140
+
141
+
142
+
143
+ def read_frames_thread(self, cap, frame_start, frame_end, num_threads):
144
+ num_frame = 0
145
+ total_num = frame_end - frame_start
146
+ if frame_start > 0:
147
+ cap.set(cv2.CAP_PROP_POS_FRAMES,frame_start)
148
+
149
+ while True and roop.globals.processing:
150
+ ret, frame = cap.read()
151
+ if not ret:
152
+ break
153
+
154
+ self.frames_queue[num_frame % num_threads].put(frame, block=True)
155
+ num_frame += 1
156
+ if num_frame == total_num:
157
+ break
158
+
159
+ for i in range(num_threads):
160
+ self.frames_queue[i].put(None)
161
+
162
+
163
+
164
+ def process_videoframes(self, threadindex, progress) -> None:
165
+ while True:
166
+ frame = self.frames_queue[threadindex].get()
167
+ if frame is None:
168
+ self.processing_threads -= 1
169
+ self.processed_queue[threadindex].put(None)
170
+ return
171
+ else:
172
+ resimg = self.process_frame(frame)
173
+ self.processed_queue[threadindex].put(resimg)
174
+ del frame
175
+ progress()
176
+
177
+
178
+ def write_frames_thread(self):
179
+ nextindex = 0
180
+ num_producers = self.num_threads
181
+
182
+ while True:
183
+ frame = self.processed_queue[nextindex % self.num_threads].get()
184
+ nextindex += 1
185
+ if frame is not None:
186
+ self.videowriter.write_frame(frame)
187
+ del frame
188
+ else:
189
+ num_producers -= 1
190
+ if num_producers < 1:
191
+ return
192
+
193
+
194
+
195
+ def run_batch_inmem(self, source_video, target_video, frame_start, frame_end, fps, threads:int = 1, skip_audio=False):
196
+ cap = cv2.VideoCapture(source_video)
197
+ # frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
198
+ frame_count = (frame_end - frame_start) + 1
199
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
200
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
201
+
202
+ self.total_frames = frame_count
203
+ self.num_threads = threads
204
+
205
+ self.processing_threads = self.num_threads
206
+ self.frames_queue = []
207
+ self.processed_queue = []
208
+ for _ in range(threads):
209
+ self.frames_queue.append(Queue(1))
210
+ self.processed_queue.append(Queue(1))
211
+
212
+ self.videowriter = FFMPEG_VideoWriter(target_video, (width, height), fps, codec=roop.globals.video_encoder, crf=roop.globals.video_quality, audiofile=None)
213
+ if not skip_audio and frame_start > 0:
214
+ print('Writing offset frames')
215
+ num_write = frame_start
216
+ cap.set(cv2.CAP_PROP_POS_FRAMES,frame_start)
217
+ ret, frame = cap.read()
218
+ fake_frame = self.process_frame(frame)
219
+ while num_write > 0:
220
+ self.videowriter.write_frame(fake_frame)
221
+ num_write -= 1
222
+
223
+ readthread = Thread(target=self.read_frames_thread, args=(cap, frame_start, frame_end, threads))
224
+ readthread.start()
225
+
226
+ writethread = Thread(target=self.write_frames_thread)
227
+ writethread.start()
228
+
229
+ progress_bar_format = '{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]'
230
+ with tqdm(total=self.total_frames, desc='Processing', unit='frames', dynamic_ncols=True, bar_format=progress_bar_format) as progress:
231
+ with ThreadPoolExecutor(thread_name_prefix='swap_proc', max_workers=self.num_threads) as executor:
232
+ futures = []
233
+
234
+ for threadindex in range(threads):
235
+ future = executor.submit(self.process_videoframes, threadindex, lambda: self.update_progress(progress))
236
+ futures.append(future)
237
+
238
+ for future in as_completed(futures):
239
+ future.result()
240
+ # wait for the task to complete
241
+ readthread.join()
242
+ writethread.join()
243
+ cap.release()
244
+ self.videowriter.close()
245
+ self.frames_queue.clear()
246
+ self.processed_queue.clear()
247
+
248
+
249
+
250
+
251
+ def update_progress(self, progress: Any = None) -> None:
252
+ process = psutil.Process(os.getpid())
253
+ memory_usage = process.memory_info().rss / 1024 / 1024 / 1024
254
+ msg = 'memory_usage: ' + '{:.2f}'.format(memory_usage).zfill(5) + f' GB execution_threads {self.num_threads}'
255
+ progress.set_postfix({
256
+ 'memory_usage': '{:.2f}'.format(memory_usage).zfill(5) + 'GB',
257
+ 'execution_threads': self.num_threads
258
+ })
259
+ progress.update(1)
260
+ self.progress_gradio((progress.n, self.total_frames), desc='Processing', total=self.total_frames, unit='frames')
261
+
262
+
263
+
264
+
265
+
266
+ def process_frame(self, frame:Frame):
267
+ if len(self.input_face_datas) < 1:
268
+ return frame
269
+
270
+ temp_frame = frame.copy()
271
+
272
+ if self.options.swap_mode == "first":
273
+ face = get_first_face(frame)
274
+ if face is None:
275
+ return frame
276
+ return self.process_face(self.options.selected_index, face, temp_frame)
277
+
278
+ else:
279
+ faces = get_all_faces(frame)
280
+ if faces is None:
281
+ return frame
282
+
283
+ if self.options.swap_mode == "all":
284
+ for face in faces:
285
+ temp_frame = self.process_face(self.options.selected_index, face, temp_frame)
286
+ del face
287
+ return temp_frame
288
+
289
+ elif self.options.swap_mode == "selected":
290
+ for i,tf in enumerate(self.target_face_datas):
291
+ for face in faces:
292
+ if compute_cosine_distance(tf.embedding, face.embedding) <= self.options.face_distance_threshold:
293
+ if i < len(self.input_face_datas):
294
+ temp_frame = self.process_face(i, face, temp_frame)
295
+ break
296
+ del face
297
+
298
+ elif self.options.swap_mode == "all_female" or self.options.swap_mode == "all_male":
299
+ gender = 'F' if self.swap_mode == "all_female" else 'M'
300
+ for face in faces:
301
+ if face.sex == gender:
302
+ temp_frame = self.process_face(self.options.selected_index, face, temp_frame)
303
+ del face
304
+
305
+ return temp_frame
306
+
307
+
308
+ def process_face(self,face_index, target_face, frame:Frame):
309
+ enhanced_frame = None
310
+ img_mask = None
311
+ for p in self.processors:
312
+ if p.type == 'swap':
313
+ fake_frame = p.Run(self.input_face_datas[face_index], target_face, frame)
314
+ scale_factor = 0.0
315
+ elif p.type == 'mask':
316
+ start_x, start_y, end_x, end_y = map(int, target_face['bbox'])
317
+ orig_frame = frame[start_y:end_y, start_x:end_x]
318
+ img_mask = p.Run(orig_frame, self.options.masking_text)
319
+ else:
320
+ enhanced_frame, scale_factor = p.Run(self.input_face_datas[face_index], target_face, fake_frame)
321
+
322
+ upscale = 512
323
+ orig_width = fake_frame.shape[1]
324
+ fake_frame = cv2.resize(fake_frame, (upscale, upscale), cv2.INTER_CUBIC)
325
+ mask_top = self.input_face_datas[face_index].mask_top
326
+ if enhanced_frame is None:
327
+ scale_factor = int(upscale / orig_width)
328
+ result = self.paste_upscale(fake_frame, fake_frame, target_face.matrix, frame, scale_factor, mask_top)
329
+ else:
330
+ result = self.paste_upscale(fake_frame, enhanced_frame, target_face.matrix, frame, scale_factor, mask_top)
331
+ if img_mask is not None:
332
+ target = result[start_y:end_y, start_x:end_x]
333
+ img_mask = cv2.resize(img_mask, (target.shape[1], target.shape[0]))
334
+ img_mask = np.reshape(img_mask, [img_mask.shape[0],img_mask.shape[1],1])
335
+
336
+ target = target.astype(np.float32)
337
+ clip = (1-img_mask) * target
338
+ clip += img_mask * orig_frame.astype(np.float32)
339
+ result[start_y:end_y, start_x:end_x] = clip
340
+ return result
341
+
342
+ return result
343
+
344
+
345
+
346
+
347
+
348
+
349
+ # Paste back adapted from here
350
+ # https://github.com/fAIseh00d/refacer/blob/main/refacer.py
351
+ # which is revised insightface paste back code
352
+
353
+ def paste_upscale(self, fake_face, upsk_face, M, target_img, scale_factor, mask_top):
354
+ M_scale = M * scale_factor
355
+ IM = cv2.invertAffineTransform(M_scale)
356
+
357
+ face_matte = np.full((target_img.shape[0],target_img.shape[1]), 255, dtype=np.uint8)
358
+ ##Generate white square sized as a upsk_face
359
+ img_matte = np.full((upsk_face.shape[0],upsk_face.shape[1]), 255, dtype=np.uint8)
360
+ if mask_top > 0:
361
+ img_matte[:mask_top,:] = 0
362
+
363
+ ##Transform white square back to target_img
364
+ img_matte = cv2.warpAffine(img_matte, IM, (target_img.shape[1], target_img.shape[0]), flags=cv2.INTER_NEAREST, borderValue=0.0)
365
+ ##Blacken the edges of face_matte by 1 pixels (so the mask in not expanded on the image edges)
366
+ img_matte[:1,:] = img_matte[-1:,:] = img_matte[:,:1] = img_matte[:,-1:] = 0
367
+
368
+ #Detect the affine transformed white area
369
+ mask_h_inds, mask_w_inds = np.where(img_matte==255)
370
+ #Calculate the size (and diagonal size) of transformed white area width and height boundaries
371
+ mask_h = np.max(mask_h_inds) - np.min(mask_h_inds)
372
+ mask_w = np.max(mask_w_inds) - np.min(mask_w_inds)
373
+ mask_size = int(np.sqrt(mask_h*mask_w))
374
+ #Calculate the kernel size for eroding img_matte by kernel (insightface empirical guess for best size was max(mask_size//10,10))
375
+ # k = max(mask_size//12, 8)
376
+ k = max(mask_size//10, 10)
377
+ kernel = np.ones((k,k),np.uint8)
378
+ img_matte = cv2.erode(img_matte,kernel,iterations = 1)
379
+ #Calculate the kernel size for blurring img_matte by blur_size (insightface empirical guess for best size was max(mask_size//20, 5))
380
+ # k = max(mask_size//24, 4)
381
+ k = max(mask_size//20, 5)
382
+ kernel_size = (k, k)
383
+ blur_size = tuple(2*i+1 for i in kernel_size)
384
+ img_matte = cv2.GaussianBlur(img_matte, blur_size, 0)
385
+
386
+ #Normalize images to float values and reshape
387
+ img_matte = img_matte.astype(np.float32)/255
388
+ face_matte = face_matte.astype(np.float32)/255
389
+ img_matte = np.minimum(face_matte, img_matte)
390
+ img_matte = np.reshape(img_matte, [img_matte.shape[0],img_matte.shape[1],1])
391
+ ##Transform upcaled face back to target_img
392
+ paste_face = cv2.warpAffine(upsk_face, IM, (target_img.shape[1], target_img.shape[0]), borderMode=cv2.BORDER_REPLICATE)
393
+ if upsk_face is not fake_face:
394
+ fake_face = cv2.warpAffine(fake_face, IM, (target_img.shape[1], target_img.shape[0]), borderMode=cv2.BORDER_REPLICATE)
395
+ paste_face = cv2.addWeighted(paste_face, self.options.blend_ratio, fake_face, 1.0 - self.options.blend_ratio, 0)
396
+
397
+ ##Re-assemble image
398
+ paste_face = img_matte * paste_face
399
+ paste_face = paste_face + (1-img_matte) * target_img.astype(np.float32)
400
+ del img_matte
401
+ del face_matte
402
+ del upsk_face
403
+ del fake_face
404
+ return paste_face.astype(np.uint8)
405
+
406
+
407
+ def process_mask(self, frame:Frame, target:Frame):
408
+ for p in self.processors:
409
+ if p.type == 'mask':
410
+ img_mask = p.Run(frame, self.options.masking_text)
411
+ img_mask = cv2.resize(img_mask, (target.shape[1], target.shape[0]))
412
+ img_mask = np.reshape(img_mask, [img_mask.shape[0],img_mask.shape[1],1])
413
+
414
+ target = target.astype(np.float32)
415
+ result = (1-img_mask) * target
416
+ result += img_mask * frame.astype(np.float32)
417
+ return np.uint8(result)
418
+
419
+
420
+
421
+
422
+ def unload_models():
423
+ pass
424
+
425
+
426
+ def release_resources(self):
427
+ for p in self.processors:
428
+ p.Release()
429
+ self.processors.clear()
430
+
431
+
432
+
roop/ProcessOptions.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ class ProcessOptions:
2
+
3
+ def __init__(self,processors, face_distance, blend_ratio, swap_mode, selected_index, masking_text):
4
+ self.processors = processors
5
+ self.face_distance_threshold = face_distance
6
+ self.blend_ratio = blend_ratio
7
+ self.swap_mode = swap_mode
8
+ self.selected_index = selected_index
9
+ self.masking_text = masking_text
roop/__init__.py ADDED
File without changes
roop/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (171 Bytes). View file
 
roop/__pycache__/core.cpython-311.pyc ADDED
Binary file (26.2 kB). View file
 
roop/__pycache__/globals.cpython-311.pyc ADDED
Binary file (1.26 kB). View file
 
roop/__pycache__/metadata.cpython-311.pyc ADDED
Binary file (218 Bytes). View file
 
roop/__pycache__/utilities.cpython-311.pyc ADDED
Binary file (22.6 kB). View file
 
roop/capturer.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+ import cv2
3
+
4
+ from roop.typing import Frame
5
+
6
+ def get_image_frame(filename: str):
7
+ try:
8
+ frame = cv2.imread(filename)
9
+ return frame
10
+ except:
11
+ print(f"Exception reading {filename}")
12
+ return None
13
+
14
+
15
+ def get_video_frame(video_path: str, frame_number: int = 0) -> Optional[Frame]:
16
+ capture = cv2.VideoCapture(video_path)
17
+ frame_total = capture.get(cv2.CAP_PROP_FRAME_COUNT)
18
+ capture.set(cv2.CAP_PROP_POS_FRAMES, min(frame_total, frame_number - 1))
19
+ has_frame, frame = capture.read()
20
+ capture.release()
21
+ if has_frame:
22
+ return frame
23
+ return None
24
+
25
+
26
+ def get_video_frame_total(video_path: str) -> int:
27
+ capture = cv2.VideoCapture(video_path)
28
+ video_frame_total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
29
+ capture.release()
30
+ return video_frame_total
roop/core.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ import os
4
+ import sys
5
+ import shutil
6
+ # single thread doubles cuda performance - needs to be set before torch import
7
+ if any(arg.startswith('--execution-provider') for arg in sys.argv):
8
+ os.environ['OMP_NUM_THREADS'] = '1'
9
+
10
+ import warnings
11
+ from typing import List
12
+ import platform
13
+ import signal
14
+ import argparse
15
+ import torch
16
+ import onnxruntime
17
+ import tensorflow
18
+ import pathlib
19
+
20
+ from time import time
21
+
22
+ import roop.globals
23
+ import roop.metadata
24
+ import roop.utilities as util
25
+ import roop.ui as ui
26
+ from settings import Settings
27
+ from roop.face_util import extract_face_images
28
+ from roop.ProcessEntry import ProcessEntry
29
+ from roop.ProcessMgr import ProcessMgr
30
+ from roop.ProcessOptions import ProcessOptions
31
+
32
+
33
+ clip_text = None
34
+
35
+ call_display_ui = None
36
+
37
+ process_mgr = None
38
+
39
+
40
+ if 'ROCMExecutionProvider' in roop.globals.execution_providers:
41
+ del torch
42
+
43
+ warnings.filterwarnings('ignore', category=FutureWarning, module='insightface')
44
+ warnings.filterwarnings('ignore', category=UserWarning, module='torchvision')
45
+
46
+
47
+ def parse_args() -> None:
48
+ signal.signal(signal.SIGINT, lambda signal_number, frame: destroy())
49
+ program = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=100))
50
+ program.add_argument('-s', '--source', help='select a source image', dest='source_path')
51
+ program.add_argument('-t', '--target', help='select a target image or video', dest='target_path')
52
+ program.add_argument('-o', '--output', help='select output file or directory', dest='output_path')
53
+ program.add_argument('-f', '--folder', help='select a target folder with images or videos to batch process', dest='target_folder_path')
54
+ program.add_argument('--frame-processor', help='frame processors (choices: face_swapper, face_enhancer, ...)', dest='frame_processor', default=['face_swapper'], nargs='+')
55
+ program.add_argument('--keep-fps', help='keep target fps', dest='keep_fps', action='store_true')
56
+ program.add_argument('--keep-frames', help='keep temporary frames', dest='keep_frames', action='store_true')
57
+ program.add_argument('--skip-audio', help='skip target audio', dest='skip_audio', action='store_true')
58
+ program.add_argument('--many-faces', help='process every face', dest='many_faces', action='store_true')
59
+ program.add_argument('--source-face_index', help='index position of source face in image', dest='source_face_index', type=int, default=0)
60
+ program.add_argument('--target-face_index', help='index position of target face in image', dest='target_face_index', type=int, default=0)
61
+ program.add_argument('--video-encoder', help='adjust output video encoder', dest='video_encoder', default='libx264', choices=['libx264', 'libx265', 'libvpx-vp9'])
62
+ program.add_argument('--video-quality', help='adjust output video quality', dest='video_quality', type=int, default=18, choices=range(52), metavar='[0-51]')
63
+ program.add_argument('--max-memory', help='maximum amount of RAM in GB', dest='max_memory', type=int, default=suggest_max_memory())
64
+ program.add_argument('--execution-provider', help='available execution provider (choices: cpu, ...)', dest='execution_provider', default=['cpu'], choices=suggest_execution_providers(), nargs='+')
65
+ program.add_argument('--execution-threads', help='number of execution threads', dest='execution_threads', type=int, default=suggest_execution_threads())
66
+ program.add_argument('-v', '--version', action='version', version=f'{roop.metadata.name} {roop.metadata.version}')
67
+
68
+ args = program.parse_args()
69
+
70
+ roop.globals.source_path = args.source_path
71
+ roop.globals.target_path = args.target_path
72
+ roop.globals.output_path = util.normalize_output_path(roop.globals.source_path, roop.globals.target_path, args.output_path)
73
+ roop.globals.target_folder_path = args.target_folder_path
74
+ roop.globals.headless = args.source_path or args.target_path or args.output_path
75
+ # Always enable all processors when using GUI
76
+ if not roop.globals.headless:
77
+ roop.globals.frame_processors = ['face_swapper', 'face_enhancer']
78
+ else:
79
+ roop.globals.frame_processors = args.frame_processor
80
+
81
+ roop.globals.keep_fps = args.keep_fps
82
+ roop.globals.keep_frames = args.keep_frames
83
+ roop.globals.skip_audio = args.skip_audio
84
+ roop.globals.many_faces = args.many_faces
85
+ roop.globals.source_face_index = args.source_face_index
86
+ roop.globals.target_face_index = args.target_face_index
87
+ roop.globals.video_encoder = args.video_encoder
88
+ roop.globals.video_quality = args.video_quality
89
+ roop.globals.max_memory = args.max_memory
90
+ roop.globals.execution_providers = decode_execution_providers(args.execution_provider)
91
+ roop.globals.execution_threads = args.execution_threads
92
+
93
+
94
+ def encode_execution_providers(execution_providers: List[str]) -> List[str]:
95
+ return [execution_provider.replace('ExecutionProvider', '').lower() for execution_provider in execution_providers]
96
+
97
+
98
+ def decode_execution_providers(execution_providers: List[str]) -> List[str]:
99
+ return [provider for provider, encoded_execution_provider in zip(onnxruntime.get_available_providers(), encode_execution_providers(onnxruntime.get_available_providers()))
100
+ if any(execution_provider in encoded_execution_provider for execution_provider in execution_providers)]
101
+
102
+
103
+ def suggest_max_memory() -> int:
104
+ if platform.system().lower() == 'darwin':
105
+ return 4
106
+ return 16
107
+
108
+
109
+ def suggest_execution_providers() -> List[str]:
110
+ return encode_execution_providers(onnxruntime.get_available_providers())
111
+
112
+
113
+ def suggest_execution_threads() -> int:
114
+ if 'DmlExecutionProvider' in roop.globals.execution_providers:
115
+ return 1
116
+ if 'ROCMExecutionProvider' in roop.globals.execution_providers:
117
+ return 1
118
+ return 8
119
+
120
+
121
+ def limit_resources() -> None:
122
+ # prevent tensorflow memory leak
123
+ gpus = tensorflow.config.experimental.list_physical_devices('GPU')
124
+ for gpu in gpus:
125
+ tensorflow.config.experimental.set_virtual_device_configuration(gpu, [
126
+ tensorflow.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)
127
+ ])
128
+ # limit memory usage
129
+ if roop.globals.max_memory:
130
+ memory = roop.globals.max_memory * 1024 ** 3
131
+ if platform.system().lower() == 'darwin':
132
+ memory = roop.globals.max_memory * 1024 ** 6
133
+ if platform.system().lower() == 'windows':
134
+ import ctypes
135
+ kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
136
+ kernel32.SetProcessWorkingSetSize(-1, ctypes.c_size_t(memory), ctypes.c_size_t(memory))
137
+ else:
138
+ import resource
139
+ resource.setrlimit(resource.RLIMIT_DATA, (memory, memory))
140
+
141
+
142
+
143
+ def release_resources() -> None:
144
+ import gc
145
+ global process_mgr
146
+
147
+ if process_mgr is not None:
148
+ process_mgr.release_resources()
149
+ process_mgr = None
150
+
151
+ gc.collect()
152
+ if 'CUDAExecutionProvider' in roop.globals.execution_providers and torch.cuda.is_available():
153
+ with torch.cuda.device('cuda'):
154
+ torch.cuda.empty_cache()
155
+ torch.cuda.ipc_collect()
156
+
157
+
158
+ def pre_check() -> bool:
159
+ if sys.version_info < (3, 9):
160
+ update_status('Python version is not supported - please upgrade to 3.9 or higher.')
161
+ return False
162
+
163
+ download_directory_path = util.resolve_relative_path('../models')
164
+ util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/inswapper_128.onnx'])
165
+ util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/GFPGANv1.4.onnx'])
166
+ util.conditional_download(download_directory_path, ['https://github.com/csxmli2016/DMDNet/releases/download/v1/DMDNet.pth'])
167
+ download_directory_path = util.resolve_relative_path('../models/CLIP')
168
+ util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/rd64-uni-refined.pth'])
169
+ download_directory_path = util.resolve_relative_path('../models/CodeFormer')
170
+ util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/CodeFormerv0.1.onnx'])
171
+
172
+ if not shutil.which('ffmpeg'):
173
+ update_status('ffmpeg is not installed.')
174
+ return True
175
+
176
+ def set_display_ui(function):
177
+ global call_display_ui
178
+
179
+ call_display_ui = function
180
+
181
+
182
+ def update_status(message: str) -> None:
183
+ global call_display_ui
184
+
185
+ print(message)
186
+ if call_display_ui is not None:
187
+ call_display_ui(message)
188
+
189
+
190
+
191
+
192
+ def start() -> None:
193
+ if roop.globals.headless:
194
+ faces = extract_face_images(roop.globals.source_path, (False, 0))
195
+ roop.globals.INPUT_FACES.append(faces[roop.globals.source_face_index])
196
+ faces = extract_face_images(roop.globals.target_path, (False, util.has_image_extension(roop.globals.target_path)))
197
+ roop.globals.TARGET_FACES.append(faces[roop.globals.target_face_index])
198
+ if 'face_enhancer' in roop.globals.frame_processors:
199
+ roop.globals.selected_enhancer = 'GFPGAN'
200
+
201
+ batch_process(None, False, None)
202
+
203
+
204
+ def get_processing_plugins(use_clip):
205
+ processors = "faceswap"
206
+ if use_clip:
207
+ processors += ",mask_clip2seg"
208
+
209
+ if roop.globals.selected_enhancer == 'GFPGAN':
210
+ processors += ",gfpgan"
211
+ elif roop.globals.selected_enhancer == 'Codeformer':
212
+ processors += ",codeformer"
213
+ elif roop.globals.selected_enhancer == 'DMDNet':
214
+ processors += ",dmdnet"
215
+ return processors
216
+
217
+
218
+ def live_swap(frame, swap_mode, use_clip, clip_text, selected_index = 0):
219
+ global process_mgr
220
+
221
+ if frame is None:
222
+ return frame
223
+
224
+ if process_mgr is None:
225
+ process_mgr = ProcessMgr(None)
226
+
227
+ options = ProcessOptions(get_processing_plugins(use_clip), roop.globals.distance_threshold, roop.globals.blend_ratio, swap_mode, selected_index, clip_text)
228
+ process_mgr.initialize(roop.globals.INPUT_FACES, roop.globals.TARGET_FACES, options)
229
+ return process_mgr.process_frame(frame)
230
+
231
+
232
+ def preview_mask(frame, clip_text):
233
+ import numpy as np
234
+ global process_mgr
235
+
236
+ maskimage = np.zeros((frame.shape), np.uint8)
237
+ if process_mgr is None:
238
+ process_mgr = ProcessMgr()
239
+ options = ProcessOptions("mask_clip2seg", roop.globals.distance_threshold, roop.globals.blend_ratio, "None", 0, clip_text)
240
+ process_mgr.initialize(roop.globals.INPUT_FACES, roop.globals.TARGET_FACES, options)
241
+ return process_mgr.process_mask(frame, maskimage)
242
+
243
+
244
+
245
+
246
+
247
+ def batch_process(files:list[ProcessEntry], use_clip, new_clip_text, use_new_method, progress) -> None:
248
+ global clip_text, process_mgr
249
+
250
+ roop.globals.processing = True
251
+ release_resources()
252
+ limit_resources()
253
+
254
+ # limit threads for some providers
255
+ max_threads = suggest_execution_threads()
256
+ if max_threads == 1:
257
+ roop.globals.execution_threads = 1
258
+
259
+ imagefiles:list[ProcessEntry] = []
260
+ videofiles:list[ProcessEntry] = []
261
+
262
+ update_status('Sorting videos/images')
263
+
264
+
265
+ for index, f in enumerate(files):
266
+ fullname = f.filename
267
+ if util.has_image_extension(fullname):
268
+ destination = util.get_destfilename_from_path(fullname, roop.globals.output_path, f'.{roop.globals.CFG.output_image_format}')
269
+ destination = util.replace_template(destination, index=index)
270
+ pathlib.Path(os.path.dirname(destination)).mkdir(parents=True, exist_ok=True)
271
+ f.finalname = destination
272
+ imagefiles.append(f)
273
+
274
+ elif util.is_video(fullname) or util.has_extension(fullname, ['gif']):
275
+ destination = util.get_destfilename_from_path(fullname, roop.globals.output_path, f'__temp.{roop.globals.CFG.output_video_format}')
276
+ f.finalname = destination
277
+ videofiles.append(f)
278
+
279
+
280
+ if process_mgr is None:
281
+ process_mgr = ProcessMgr(progress)
282
+
283
+ options = ProcessOptions(get_processing_plugins(use_clip), roop.globals.distance_threshold, roop.globals.blend_ratio, roop.globals.face_swap_mode, 0, new_clip_text)
284
+ process_mgr.initialize(roop.globals.INPUT_FACES, roop.globals.TARGET_FACES, options)
285
+
286
+ if(len(imagefiles) > 0):
287
+ update_status('Processing image(s)')
288
+ origimages = []
289
+ fakeimages = []
290
+ for f in imagefiles:
291
+ origimages.append(f.filename)
292
+ fakeimages.append(f.finalname)
293
+
294
+ process_mgr.run_batch(origimages, fakeimages, roop.globals.execution_threads)
295
+ origimages.clear()
296
+ fakeimages.clear()
297
+
298
+ if(len(videofiles) > 0):
299
+ for index,v in enumerate(videofiles):
300
+ if not roop.globals.processing:
301
+ end_processing('Processing stopped!')
302
+ return
303
+ fps = v.fps if v.fps > 0 else util.detect_fps(v.filename)
304
+ update_status(f'Creating {os.path.basename(v.finalname)} with {fps} FPS...')
305
+ start_processing = time()
306
+ if roop.globals.keep_frames or not use_new_method:
307
+ util.create_temp(v.filename)
308
+ update_status('Extracting frames...')
309
+ util.extract_frames(v.filename,v.startframe,v.endframe, fps)
310
+ if not roop.globals.processing:
311
+ end_processing('Processing stopped!')
312
+ return
313
+
314
+ temp_frame_paths = util.get_temp_frame_paths(v.filename)
315
+ process_mgr.run_batch(temp_frame_paths, temp_frame_paths, roop.globals.execution_threads)
316
+ if not roop.globals.processing:
317
+ end_processing('Processing stopped!')
318
+ return
319
+
320
+ util.create_video(v.filename, f.finalname, fps)
321
+ if not roop.globals.keep_frames:
322
+ util.delete_temp_frames(temp_frame_paths[0])
323
+ else:
324
+ if util.has_extension(v.filename, ['gif']):
325
+ skip_audio = True
326
+ else:
327
+ skip_audio = roop.globals.skip_audio
328
+ process_mgr.run_batch_inmem(v.filename, v.finalname, v.startframe, v.endframe, fps,roop.globals.execution_threads, skip_audio)
329
+
330
+ if not roop.globals.processing:
331
+ end_processing('Processing stopped!')
332
+ return
333
+
334
+ video_file_name = v.finalname
335
+ if os.path.isfile(video_file_name):
336
+ destination = ''
337
+ if util.has_extension(v.filename, ['gif']):
338
+ gifname = util.get_destfilename_from_path(v.filename, roop.globals.output_path, '.gif')
339
+ destination = util.replace_template(gifname, index=index)
340
+ pathlib.Path(os.path.dirname(destination)).mkdir(parents=True, exist_ok=True)
341
+
342
+ update_status('Creating final GIF')
343
+ util.create_gif_from_video(video_file_name, destination)
344
+ if os.path.isfile(destination):
345
+ os.remove(video_file_name)
346
+ else:
347
+ skip_audio = roop.globals.skip_audio
348
+ destination = util.replace_template(video_file_name, index=index)
349
+ pathlib.Path(os.path.dirname(destination)).mkdir(parents=True, exist_ok=True)
350
+
351
+ if not skip_audio:
352
+ util.restore_audio(video_file_name, v.filename, v.startframe, v.endframe, destination)
353
+ if os.path.isfile(destination):
354
+ os.remove(video_file_name)
355
+ else:
356
+ shutil.move(video_file_name, destination)
357
+ update_status(f'\nProcessing {os.path.basename(destination)} took {time() - start_processing} secs')
358
+
359
+ else:
360
+ update_status(f'Failed processing {os.path.basename(v.finalname)}!')
361
+ end_processing('Finished')
362
+
363
+
364
+ def end_processing(msg:str):
365
+ update_status(msg)
366
+ roop.globals.target_folder_path = None
367
+ release_resources()
368
+
369
+
370
+ def destroy() -> None:
371
+ if roop.globals.target_path:
372
+ util.clean_temp(roop.globals.target_path)
373
+ release_resources()
374
+ sys.exit()
375
+
376
+
377
+ def run() -> None:
378
+ parse_args()
379
+ if not pre_check():
380
+ return
381
+ roop.globals.CFG = Settings('config.yaml')
382
+ if roop.globals.headless:
383
+ start()
384
+ else:
385
+ ui.run()
roop/face_util.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import threading
2
+ from typing import Any
3
+ import insightface
4
+
5
+ import roop.globals
6
+ from roop.typing import Frame, Face
7
+
8
+ import cv2
9
+ import numpy as np
10
+ from roop.capturer import get_video_frame
11
+ from roop.utilities import resolve_relative_path, conditional_download
12
+
13
+ FACE_ANALYSER = None
14
+ THREAD_LOCK_ANALYSER = threading.Lock()
15
+ THREAD_LOCK_SWAPPER = threading.Lock()
16
+ FACE_SWAPPER = None
17
+
18
+
19
+ def get_face_analyser() -> Any:
20
+ global FACE_ANALYSER
21
+
22
+ with THREAD_LOCK_ANALYSER:
23
+ if FACE_ANALYSER is None:
24
+ if roop.globals.CFG.force_cpu:
25
+ print('Forcing CPU for Face Analysis')
26
+ FACE_ANALYSER = insightface.app.FaceAnalysis(name='buffalo_l', providers=['CPUExecutionProvider'])
27
+ else:
28
+ FACE_ANALYSER = insightface.app.FaceAnalysis(name='buffalo_l', providers=roop.globals.execution_providers)
29
+ FACE_ANALYSER.prepare(ctx_id=0, det_size=(640, 640) if roop.globals.default_det_size else (320,320))
30
+ return FACE_ANALYSER
31
+
32
+
33
+ def get_first_face(frame: Frame) -> Any:
34
+ try:
35
+ faces = get_face_analyser().get(frame)
36
+ return min(faces, key=lambda x: x.bbox[0])
37
+ # return sorted(faces, reverse=True, key=lambda x: (x.bbox[2] - x.bbox[0]) * (x.bbox[3] - x.bbox[1]))[0]
38
+ except:
39
+ return None
40
+
41
+
42
+ def get_all_faces(frame: Frame) -> Any:
43
+ try:
44
+ faces = get_face_analyser().get(frame)
45
+ return sorted(faces, key = lambda x : x.bbox[0])
46
+ except:
47
+ return None
48
+
49
+
50
+ def extract_face_images(source_filename, video_info):
51
+ face_data = []
52
+ source_image = None
53
+
54
+ if video_info[0]:
55
+ frame = get_video_frame(source_filename, video_info[1])
56
+ if frame is not None:
57
+ source_image = frame
58
+ else:
59
+ return face_data
60
+ else:
61
+ source_image = cv2.imread(source_filename)
62
+
63
+
64
+ faces = get_all_faces(source_image)
65
+ if faces is None:
66
+ return face_data
67
+
68
+ i = 0
69
+ for face in faces:
70
+ (startX, startY, endX, endY) = face['bbox'].astype("int")
71
+ face_temp = source_image[startY:endY, startX:endX]
72
+ if face_temp.size < 1:
73
+ continue
74
+ i += 1
75
+ face_data.append([face, face_temp])
76
+ return face_data
77
+
78
+
79
+
80
+
81
+ def get_face_swapper() -> Any:
82
+ global FACE_SWAPPER
83
+
84
+ with THREAD_LOCK_SWAPPER:
85
+ if FACE_SWAPPER is None:
86
+ model_path = resolve_relative_path('../models/inswapper_128.onnx')
87
+ FACE_SWAPPER = insightface.model_zoo.get_model(model_path, providers=roop.globals.execution_providers)
88
+ return FACE_SWAPPER
89
+
90
+
91
+ def pre_check() -> bool:
92
+ download_directory_path = resolve_relative_path('../models')
93
+ conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/inswapper_128.onnx'])
94
+ return True
95
+
96
+
97
+ def swap_face(source_face: Face, target_face: Face, temp_frame: Frame) -> Frame:
98
+ return get_face_swapper().get(temp_frame, target_face, source_face, paste_back=True)
99
+
100
+ def face_offset_top(face: Face, offset):
101
+ smallestmin = np.min(face.landmark_2d_106, 1)
102
+ smallest = smallestmin[1]
103
+ face['bbox'][1] += offset
104
+ face['bbox'][3] += offset
105
+ lm106 = face.landmark_2d_106
106
+ add = np.full_like(lm106, [0, offset])
107
+ face['landmark_2d_106'] = lm106 + add
108
+ return face
roop/ffmpeg_writer.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FFMPEG_Writer - write set of frames to video file
3
+
4
+ original from
5
+ https://github.com/Zulko/moviepy/blob/master/moviepy/video/io/ffmpeg_writer.py
6
+
7
+ removed unnecessary dependencies
8
+
9
+ The MIT License (MIT)
10
+
11
+ Copyright (c) 2015 Zulko
12
+ Copyright (c) 2023 Janvarev Vladislav
13
+ """
14
+
15
+ import os
16
+ import subprocess as sp
17
+
18
+ PIPE = -1
19
+ STDOUT = -2
20
+ DEVNULL = -3
21
+
22
+ FFMPEG_BINARY = "ffmpeg"
23
+
24
+ class FFMPEG_VideoWriter:
25
+ """ A class for FFMPEG-based video writing.
26
+
27
+ A class to write videos using ffmpeg. ffmpeg will write in a large
28
+ choice of formats.
29
+
30
+ Parameters
31
+ -----------
32
+
33
+ filename
34
+ Any filename like 'video.mp4' etc. but if you want to avoid
35
+ complications it is recommended to use the generic extension
36
+ '.avi' for all your videos.
37
+
38
+ size
39
+ Size (width,height) of the output video in pixels.
40
+
41
+ fps
42
+ Frames per second in the output video file.
43
+
44
+ codec
45
+ FFMPEG codec. It seems that in terms of quality the hierarchy is
46
+ 'rawvideo' = 'png' > 'mpeg4' > 'libx264'
47
+ 'png' manages the same lossless quality as 'rawvideo' but yields
48
+ smaller files. Type ``ffmpeg -codecs`` in a terminal to get a list
49
+ of accepted codecs.
50
+
51
+ Note for default 'libx264': by default the pixel format yuv420p
52
+ is used. If the video dimensions are not both even (e.g. 720x405)
53
+ another pixel format is used, and this can cause problem in some
54
+ video readers.
55
+
56
+ audiofile
57
+ Optional: The name of an audio file that will be incorporated
58
+ to the video.
59
+
60
+ preset
61
+ Sets the time that FFMPEG will take to compress the video. The slower,
62
+ the better the compression rate. Possibilities are: ultrafast,superfast,
63
+ veryfast, faster, fast, medium (default), slow, slower, veryslow,
64
+ placebo.
65
+
66
+ bitrate
67
+ Only relevant for codecs which accept a bitrate. "5000k" offers
68
+ nice results in general.
69
+
70
+ """
71
+
72
+ def __init__(self, filename, size, fps, codec="libx265", crf=14, audiofile=None,
73
+ preset="medium", bitrate=None,
74
+ logfile=None, threads=None, ffmpeg_params=None):
75
+
76
+ if logfile is None:
77
+ logfile = sp.PIPE
78
+
79
+ self.filename = filename
80
+ self.codec = codec
81
+ self.ext = self.filename.split(".")[-1]
82
+ w = size[0] - 1 if size[0] % 2 != 0 else size[0]
83
+ h = size[1] - 1 if size[1] % 2 != 0 else size[1]
84
+
85
+
86
+ # order is important
87
+ cmd = [
88
+ FFMPEG_BINARY,
89
+ '-hide_banner',
90
+ '-hwaccel', 'auto',
91
+ '-y',
92
+ '-loglevel', 'error' if logfile == sp.PIPE else 'info',
93
+ '-f', 'rawvideo',
94
+ '-vcodec', 'rawvideo',
95
+ '-s', '%dx%d' % (size[0], size[1]),
96
+ #'-pix_fmt', 'rgba' if withmask else 'rgb24',
97
+ '-pix_fmt', 'bgr24',
98
+ '-r', str(fps),
99
+ '-an', '-i', '-'
100
+ ]
101
+
102
+ if audiofile is not None:
103
+ cmd.extend([
104
+ '-i', audiofile,
105
+ '-acodec', 'copy'
106
+ ])
107
+
108
+ cmd.extend([
109
+ '-vcodec', codec,
110
+ '-crf', str(crf)
111
+ #'-preset', preset,
112
+ ])
113
+ if ffmpeg_params is not None:
114
+ cmd.extend(ffmpeg_params)
115
+ if bitrate is not None:
116
+ cmd.extend([
117
+ '-b', bitrate
118
+ ])
119
+
120
+ # scale to a resolution divisible by 2 if not even
121
+ cmd.extend(['-vf', f'scale={w}:{h}' if w != size[0] or h != size[1] else 'colorspace=bt709:iall=bt601-6-625:fast=1'])
122
+
123
+ if threads is not None:
124
+ cmd.extend(["-threads", str(threads)])
125
+
126
+ cmd.extend([
127
+ '-pix_fmt', 'yuv420p',
128
+
129
+ ])
130
+ cmd.extend([
131
+ filename
132
+ ])
133
+
134
+ test = str(cmd)
135
+ print(test)
136
+
137
+ popen_params = {"stdout": DEVNULL,
138
+ "stderr": logfile,
139
+ "stdin": sp.PIPE}
140
+
141
+ # This was added so that no extra unwanted window opens on windows
142
+ # when the child process is created
143
+ if os.name == "nt":
144
+ popen_params["creationflags"] = 0x08000000 # CREATE_NO_WINDOW
145
+
146
+ self.proc = sp.Popen(cmd, **popen_params)
147
+
148
+
149
+ def write_frame(self, img_array):
150
+ """ Writes one frame in the file."""
151
+ try:
152
+ #if PY3:
153
+ self.proc.stdin.write(img_array.tobytes())
154
+ # else:
155
+ # self.proc.stdin.write(img_array.tostring())
156
+ except IOError as err:
157
+ _, ffmpeg_error = self.proc.communicate()
158
+ error = (str(err) + ("\n\nroop unleashed error: FFMPEG encountered "
159
+ "the following error while writing file %s:"
160
+ "\n\n %s" % (self.filename, str(ffmpeg_error))))
161
+
162
+ if b"Unknown encoder" in ffmpeg_error:
163
+
164
+ error = error+("\n\nThe video export "
165
+ "failed because FFMPEG didn't find the specified "
166
+ "codec for video encoding (%s). Please install "
167
+ "this codec or change the codec when calling "
168
+ "write_videofile. For instance:\n"
169
+ " >>> clip.write_videofile('myvid.webm', codec='libvpx')")%(self.codec)
170
+
171
+ elif b"incorrect codec parameters ?" in ffmpeg_error:
172
+
173
+ error = error+("\n\nThe video export "
174
+ "failed, possibly because the codec specified for "
175
+ "the video (%s) is not compatible with the given "
176
+ "extension (%s). Please specify a valid 'codec' "
177
+ "argument in write_videofile. This would be 'libx264' "
178
+ "or 'mpeg4' for mp4, 'libtheora' for ogv, 'libvpx for webm. "
179
+ "Another possible reason is that the audio codec was not "
180
+ "compatible with the video codec. For instance the video "
181
+ "extensions 'ogv' and 'webm' only allow 'libvorbis' (default) as a"
182
+ "video codec."
183
+ )%(self.codec, self.ext)
184
+
185
+ elif b"encoder setup failed" in ffmpeg_error:
186
+
187
+ error = error+("\n\nThe video export "
188
+ "failed, possibly because the bitrate you specified "
189
+ "was too high or too low for the video codec.")
190
+
191
+ elif b"Invalid encoder type" in ffmpeg_error:
192
+
193
+ error = error + ("\n\nThe video export failed because the codec "
194
+ "or file extension you provided is not a video")
195
+
196
+
197
+ raise IOError(error)
198
+
199
+ def close(self):
200
+ if self.proc:
201
+ self.proc.stdin.close()
202
+ if self.proc.stderr is not None:
203
+ self.proc.stderr.close()
204
+ self.proc.wait()
205
+
206
+ self.proc = None
207
+
208
+ # Support the Context Manager protocol, to ensure that resources are cleaned up.
209
+
210
+ def __enter__(self):
211
+ return self
212
+
213
+ def __exit__(self, exc_type, exc_value, traceback):
214
+ self.close()
215
+
216
+
217
+
218
+
roop/globals.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from settings import Settings
2
+ from typing import List
3
+
4
+ source_path = None
5
+ target_path = None
6
+ output_path = None
7
+ target_folder_path = None
8
+
9
+ frame_processors: List[str] = []
10
+ keep_fps = None
11
+ keep_frames = None
12
+ skip_audio = None
13
+ many_faces = None
14
+ use_batch = None
15
+ source_face_index = 0
16
+ target_face_index = 0
17
+ face_position = None
18
+ video_encoder = None
19
+ video_quality = None
20
+ max_memory = None
21
+ execution_providers: List[str] = []
22
+ execution_threads = None
23
+ headless = None
24
+ log_level = 'error'
25
+ selected_enhancer = None
26
+ face_swap_mode = None
27
+ blend_ratio = 0.5
28
+ distance_threshold = 0.65
29
+ default_det_size = True
30
+
31
+ processing = False
32
+
33
+ FACE_ENHANCER = None
34
+
35
+ INPUT_FACES = []
36
+ TARGET_FACES = []
37
+
38
+ IMAGE_CHAIN_PROCESSOR = None
39
+ VIDEO_CHAIN_PROCESSOR = None
40
+ BATCH_IMAGE_CHAIN_PROCESSOR = None
41
+
42
+ CFG: Settings = None
43
+
44
+
roop/metadata.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ name = 'roop unleashed'
2
+ version = '3.0.2'
roop/processors/Enhance_Codeformer.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Callable
2
+ import cv2
3
+ import threading
4
+ import numpy as np
5
+ import onnxruntime
6
+ import onnx
7
+ import roop.globals
8
+
9
+ from roop.typing import Face, Frame
10
+ from roop.utilities import resolve_relative_path
11
+
12
+
13
+ # THREAD_LOCK = threading.Lock()
14
+
15
+
16
+ class Enhance_CodeFormer():
17
+ model_codeformer = None
18
+ devicename = None
19
+
20
+ processorname = 'codeformer'
21
+ type = 'enhance'
22
+
23
+
24
+ def Initialize(self, devicename):
25
+ if self.model_codeformer is None:
26
+ self.devicename = devicename
27
+ model_path = resolve_relative_path('../models/CodeFormer/CodeFormerv0.1.onnx')
28
+ self.model_codeformer = onnxruntime.InferenceSession(model_path, None, providers=roop.globals.execution_providers)
29
+ self.model_inputs = self.model_codeformer.get_inputs()
30
+ model_outputs = self.model_codeformer.get_outputs()
31
+ self.io_binding = self.model_codeformer.io_binding()
32
+ self.io_binding.bind_cpu_input(self.model_inputs[1].name, np.array([0.5]))
33
+ self.io_binding.bind_output(model_outputs[0].name, self.devicename)
34
+
35
+
36
+ def Run(self, source_face: Face, target_face: Face, temp_frame: Frame) -> Frame:
37
+ input_size = temp_frame.shape[1]
38
+ # preprocess
39
+ temp_frame = cv2.resize(temp_frame, (512, 512), cv2.INTER_CUBIC)
40
+ temp_frame = cv2.cvtColor(temp_frame, cv2.COLOR_BGR2RGB)
41
+ temp_frame = temp_frame.astype('float32') / 255.0
42
+ temp_frame = (temp_frame - 0.5) / 0.5
43
+ temp_frame = np.expand_dims(temp_frame, axis=0).transpose(0, 3, 1, 2)
44
+
45
+ self.io_binding.bind_cpu_input(self.model_inputs[0].name, temp_frame.astype(np.float32))
46
+ self.model_codeformer.run_with_iobinding(self.io_binding)
47
+ ort_outs = self.io_binding.copy_outputs_to_cpu()
48
+ result = ort_outs[0][0]
49
+ del ort_outs
50
+
51
+ # post-process
52
+ result = result.transpose((1, 2, 0))
53
+
54
+ un_min = -1.0
55
+ un_max = 1.0
56
+ result = np.clip(result, un_min, un_max)
57
+ result = (result - un_min) / (un_max - un_min)
58
+
59
+ result = cv2.cvtColor(result, cv2.COLOR_RGB2BGR)
60
+ result = (result * 255.0).round()
61
+ scale_factor = int(result.shape[1] / input_size)
62
+ return result.astype(np.uint8), scale_factor
63
+
64
+
65
+ def Release(self):
66
+ del self.model_codeformer
67
+ self.model_codeformer = None
68
+ del self.io_binding
69
+ self.io_binding = None
70
+
roop/processors/Enhance_DMDNet.py ADDED
@@ -0,0 +1,861 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Callable
2
+ import cv2
3
+ import numpy as np
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ import torch.nn.utils.spectral_norm as SpectralNorm
8
+ import threading
9
+ from torchvision.ops import roi_align
10
+
11
+ from math import sqrt
12
+
13
+ from torchvision.transforms.functional import normalize
14
+ import roop.globals
15
+
16
+ from roop.typing import Face, Frame
17
+ from roop.utilities import resolve_relative_path
18
+
19
+
20
+ THREAD_LOCK_DMDNET = threading.Lock()
21
+
22
+
23
+ class Enhance_DMDNet():
24
+
25
+ model_dmdnet = None
26
+ torchdevice = None
27
+
28
+ processorname = 'dmdnet'
29
+ type = 'enhance'
30
+
31
+
32
+ def Initialize(self, devicename):
33
+ if self.model_dmdnet is None:
34
+ self.model_dmdnet = self.create(devicename)
35
+
36
+
37
+ # temp_frame already cropped+aligned, bbox not
38
+ def Run(self, source_face: Face, target_face: Face, temp_frame: Frame) -> Frame:
39
+ input_size = temp_frame.shape[1]
40
+
41
+ result = self.enhance_face(source_face, temp_frame, target_face)
42
+ scale_factor = int(result.shape[1] / input_size)
43
+ return result.astype(np.uint8), scale_factor
44
+
45
+
46
+ def Release(self):
47
+ self.model_gfpgan = None
48
+
49
+
50
+ # https://stackoverflow.com/a/67174339
51
+ def landmarks106_to_68(self, pt106):
52
+ map106to68=[1,10,12,14,16,3,5,7,0,23,21,19,32,30,28,26,17,
53
+ 43,48,49,51,50,
54
+ 102,103,104,105,101,
55
+ 72,73,74,86,78,79,80,85,84,
56
+ 35,41,42,39,37,36,
57
+ 89,95,96,93,91,90,
58
+ 52,64,63,71,67,68,61,58,59,53,56,55,65,66,62,70,69,57,60,54
59
+ ]
60
+
61
+ pt68 = []
62
+ for i in range(68):
63
+ index = map106to68[i]
64
+ pt68.append(pt106[index])
65
+ return pt68
66
+
67
+
68
+
69
+
70
+ def check_bbox(self, imgs, boxes):
71
+ boxes = boxes.view(-1, 4, 4)
72
+ colors = [(0, 255, 0), (0, 255, 0), (255, 255, 0), (255, 0, 0)]
73
+ i = 0
74
+ for img, box in zip(imgs, boxes):
75
+ img = (img + 1)/2 * 255
76
+ img2 = img.permute(1, 2, 0).float().cpu().flip(2).numpy().copy()
77
+ for idx, point in enumerate(box):
78
+ cv2.rectangle(img2, (int(point[0]), int(point[1])), (int(point[2]), int(point[3])), color=colors[idx], thickness=2)
79
+ cv2.imwrite('dmdnet_{:02d}.png'.format(i), img2)
80
+ i += 1
81
+
82
+
83
+ def trans_points2d(self, pts, M):
84
+ new_pts = np.zeros(shape=pts.shape, dtype=np.float32)
85
+ for i in range(pts.shape[0]):
86
+ pt = pts[i]
87
+ new_pt = np.array([pt[0], pt[1], 1.0], dtype=np.float32)
88
+ new_pt = np.dot(M, new_pt)
89
+ new_pts[i] = new_pt[0:2]
90
+
91
+ return new_pts
92
+
93
+
94
+ def enhance_face(self, ref_face, temp_frame, face):
95
+ # preprocess
96
+ start_x, start_y, end_x, end_y = map(int, face['bbox'])
97
+ width = end_x - start_x
98
+ height = end_y - start_y
99
+
100
+
101
+ lm106 = face.landmark_2d_106
102
+ lq_landmarks = np.asarray(self.landmarks106_to_68(lm106))
103
+
104
+ if temp_frame.shape[0] != 512 or temp_frame.shape[1] != 512:
105
+ # scale to 512x512
106
+ scale_factor = 512 / temp_frame.shape[1]
107
+
108
+ M = face.matrix * scale_factor
109
+
110
+ lq_landmarks = self.trans_points2d(lq_landmarks, M)
111
+ temp_frame = cv2.resize(temp_frame, (512,512), interpolation = cv2.INTER_AREA)
112
+
113
+ if temp_frame.ndim == 2:
114
+ temp_frame = cv2.cvtColor(temp_frame, cv2.COLOR_GRAY2RGB) # GGG
115
+ # else:
116
+ # temp_frame = cv2.cvtColor(temp_frame, cv2.COLOR_BGR2RGB) # RGB
117
+
118
+ lq = read_img_tensor(temp_frame)
119
+
120
+ LQLocs = get_component_location(lq_landmarks)
121
+ # self.check_bbox(lq, LQLocs.unsqueeze(0))
122
+
123
+ # specific
124
+ # start_x, start_y, end_x, end_y = map(int, ref_face['bbox'])
125
+ # temp_face = temp_frame[start_y:end_y, start_x:end_x]
126
+ # if temp_face.size:
127
+ # SpecificImgs = []
128
+ # SpecificLocs = []
129
+ # lm106 = ref_face.landmark_2d_106
130
+ # ref_landmarks = asarray(self.landmarks106_to_68(lm106))
131
+ # ref_tensor, ref_landmarks, _ = read_img_tensor(clip, ref_landmarks)
132
+ # SpecificImgs.append(ref_tensor)
133
+ # ref_locs = get_component_location(ref_landmarks)
134
+ # SpecificLocs.append(ref_locs.unsqueeze(0))
135
+
136
+ # SpecificImgs = torch.cat(SpecificImgs, dim=0)
137
+ # SpecificLocs = torch.cat(SpecificLocs, dim=0)
138
+ # # check_bbox(SpecificImgs, SpecificLocs)
139
+ # SpMem256, SpMem128, SpMem64 = DMDNet.generate_specific_dictionary(sp_imgs = SpecificImgs.to(device), sp_locs = SpecificLocs)
140
+ # SpMem256Para = {}
141
+ # SpMem128Para = {}
142
+ # SpMem64Para = {}
143
+ # for k, v in SpMem256.items():
144
+ # SpMem256Para[k] = v
145
+ # for k, v in SpMem128.items():
146
+ # SpMem128Para[k] = v
147
+ # for k, v in SpMem64.items():
148
+ # SpMem64Para[k] = v
149
+
150
+ # generic
151
+ SpMem256Para, SpMem128Para, SpMem64Para = None, None, None
152
+
153
+ with torch.no_grad():
154
+ with THREAD_LOCK_DMDNET:
155
+ try:
156
+ GenericResult, SpecificResult = self.model_dmdnet(lq = lq.to(self.torchdevice), loc = LQLocs.unsqueeze(0), sp_256 = SpMem256Para, sp_128 = SpMem128Para, sp_64 = SpMem64Para)
157
+ except Exception as e:
158
+ print(f'Error {e} there may be something wrong with the detected component locations.')
159
+ return temp_frame
160
+ save_generic = GenericResult * 0.5 + 0.5
161
+ save_generic = save_generic.squeeze(0).permute(1, 2, 0).flip(2) # RGB->BGR
162
+ save_generic = np.clip(save_generic.float().cpu().numpy(), 0, 1) * 255.0
163
+
164
+ check_lq = lq * 0.5 + 0.5
165
+ check_lq = check_lq.squeeze(0).permute(1, 2, 0).flip(2) # RGB->BGR
166
+ check_lq = np.clip(check_lq.float().cpu().numpy(), 0, 1) * 255.0
167
+ enhanced_img = np.hstack((check_lq, save_generic))
168
+ temp_frame = save_generic.astype("uint8")
169
+ temp_frame = cv2.cvtColor(temp_frame, cv2.COLOR_RGB2BGR) # RGB
170
+ return temp_frame
171
+
172
+
173
+ def create(self, devicename):
174
+ self.torchdevice = torch.device(devicename)
175
+ model_dmdnet = DMDNet().to(self.torchdevice)
176
+ weights = torch.load('./models/DMDNet.pth')
177
+ model_dmdnet.load_state_dict(weights, strict=True)
178
+
179
+ model_dmdnet.eval()
180
+ num_params = 0
181
+ for param in model_dmdnet.parameters():
182
+ num_params += param.numel()
183
+ return model_dmdnet
184
+
185
+ # print('{:>8s} : {}'.format('Using device', device))
186
+ # print('{:>8s} : {:.2f}M'.format('Model params', num_params/1e6))
187
+
188
+
189
+
190
+ def read_img_tensor(Img=None): #rgb -1~1
191
+ Img = Img.transpose((2, 0, 1))/255.0
192
+ Img = torch.from_numpy(Img).float()
193
+ normalize(Img, [0.5,0.5,0.5], [0.5,0.5,0.5], inplace=True)
194
+ ImgTensor = Img.unsqueeze(0)
195
+ return ImgTensor
196
+
197
+
198
+ def get_component_location(Landmarks, re_read=False):
199
+ if re_read:
200
+ ReadLandmark = []
201
+ with open(Landmarks,'r') as f:
202
+ for line in f:
203
+ tmp = [float(i) for i in line.split(' ') if i != '\n']
204
+ ReadLandmark.append(tmp)
205
+ ReadLandmark = np.array(ReadLandmark) #
206
+ Landmarks = np.reshape(ReadLandmark, [-1, 2]) # 68*2
207
+ Map_LE_B = list(np.hstack((range(17,22), range(36,42))))
208
+ Map_RE_B = list(np.hstack((range(22,27), range(42,48))))
209
+ Map_LE = list(range(36,42))
210
+ Map_RE = list(range(42,48))
211
+ Map_NO = list(range(29,36))
212
+ Map_MO = list(range(48,68))
213
+
214
+ Landmarks[Landmarks>504]=504
215
+ Landmarks[Landmarks<8]=8
216
+
217
+ #left eye
218
+ Mean_LE = np.mean(Landmarks[Map_LE],0)
219
+ L_LE1 = Mean_LE[1] - np.min(Landmarks[Map_LE_B,1])
220
+ L_LE1 = L_LE1 * 1.3
221
+ L_LE2 = L_LE1 / 1.9
222
+ L_LE_xy = L_LE1 + L_LE2
223
+ L_LE_lt = [L_LE_xy/2, L_LE1]
224
+ L_LE_rb = [L_LE_xy/2, L_LE2]
225
+ Location_LE = np.hstack((Mean_LE - L_LE_lt + 1, Mean_LE + L_LE_rb)).astype(int)
226
+
227
+ #right eye
228
+ Mean_RE = np.mean(Landmarks[Map_RE],0)
229
+ L_RE1 = Mean_RE[1] - np.min(Landmarks[Map_RE_B,1])
230
+ L_RE1 = L_RE1 * 1.3
231
+ L_RE2 = L_RE1 / 1.9
232
+ L_RE_xy = L_RE1 + L_RE2
233
+ L_RE_lt = [L_RE_xy/2, L_RE1]
234
+ L_RE_rb = [L_RE_xy/2, L_RE2]
235
+ Location_RE = np.hstack((Mean_RE - L_RE_lt + 1, Mean_RE + L_RE_rb)).astype(int)
236
+
237
+ #nose
238
+ Mean_NO = np.mean(Landmarks[Map_NO],0)
239
+ L_NO1 =( np.max([Mean_NO[0] - Landmarks[31][0], Landmarks[35][0] - Mean_NO[0]])) * 1.25
240
+ L_NO2 = (Landmarks[33][1] - Mean_NO[1]) * 1.1
241
+ L_NO_xy = L_NO1 * 2
242
+ L_NO_lt = [L_NO_xy/2, L_NO_xy - L_NO2]
243
+ L_NO_rb = [L_NO_xy/2, L_NO2]
244
+ Location_NO = np.hstack((Mean_NO - L_NO_lt + 1, Mean_NO + L_NO_rb)).astype(int)
245
+
246
+ #mouth
247
+ Mean_MO = np.mean(Landmarks[Map_MO],0)
248
+ L_MO = np.max((np.max(np.max(Landmarks[Map_MO],0) - np.min(Landmarks[Map_MO],0))/2,16)) * 1.1
249
+ MO_O = Mean_MO - L_MO + 1
250
+ MO_T = Mean_MO + L_MO
251
+ MO_T[MO_T>510]=510
252
+ Location_MO = np.hstack((MO_O, MO_T)).astype(int)
253
+ return torch.cat([torch.FloatTensor(Location_LE).unsqueeze(0), torch.FloatTensor(Location_RE).unsqueeze(0), torch.FloatTensor(Location_NO).unsqueeze(0), torch.FloatTensor(Location_MO).unsqueeze(0)], dim=0)
254
+
255
+
256
+
257
+
258
+ def calc_mean_std_4D(feat, eps=1e-5):
259
+ # eps is a small value added to the variance to avoid divide-by-zero.
260
+ size = feat.size()
261
+ assert (len(size) == 4)
262
+ N, C = size[:2]
263
+ feat_var = feat.view(N, C, -1).var(dim=2) + eps
264
+ feat_std = feat_var.sqrt().view(N, C, 1, 1)
265
+ feat_mean = feat.view(N, C, -1).mean(dim=2).view(N, C, 1, 1)
266
+ return feat_mean, feat_std
267
+
268
+ def adaptive_instance_normalization_4D(content_feat, style_feat): # content_feat is ref feature, style is degradate feature
269
+ size = content_feat.size()
270
+ style_mean, style_std = calc_mean_std_4D(style_feat)
271
+ content_mean, content_std = calc_mean_std_4D(content_feat)
272
+ normalized_feat = (content_feat - content_mean.expand(size)) / content_std.expand(size)
273
+ return normalized_feat * style_std.expand(size) + style_mean.expand(size)
274
+
275
+
276
+ def convU(in_channels, out_channels,conv_layer, norm_layer, kernel_size=3, stride=1,dilation=1, bias=True):
277
+ return nn.Sequential(
278
+ SpectralNorm(conv_layer(in_channels, out_channels, kernel_size=kernel_size, stride=stride, dilation=dilation, padding=((kernel_size-1)//2)*dilation, bias=bias)),
279
+ nn.LeakyReLU(0.2),
280
+ SpectralNorm(conv_layer(out_channels, out_channels, kernel_size=kernel_size, stride=stride, dilation=dilation, padding=((kernel_size-1)//2)*dilation, bias=bias)),
281
+ )
282
+
283
+
284
+ class MSDilateBlock(nn.Module):
285
+ def __init__(self, in_channels,conv_layer=nn.Conv2d, norm_layer=nn.BatchNorm2d, kernel_size=3, dilation=[1,1,1,1], bias=True):
286
+ super(MSDilateBlock, self).__init__()
287
+ self.conv1 = convU(in_channels, in_channels,conv_layer, norm_layer, kernel_size,dilation=dilation[0], bias=bias)
288
+ self.conv2 = convU(in_channels, in_channels,conv_layer, norm_layer, kernel_size,dilation=dilation[1], bias=bias)
289
+ self.conv3 = convU(in_channels, in_channels,conv_layer, norm_layer, kernel_size,dilation=dilation[2], bias=bias)
290
+ self.conv4 = convU(in_channels, in_channels,conv_layer, norm_layer, kernel_size,dilation=dilation[3], bias=bias)
291
+ self.convi = SpectralNorm(conv_layer(in_channels*4, in_channels, kernel_size=kernel_size, stride=1, padding=(kernel_size-1)//2, bias=bias))
292
+ def forward(self, x):
293
+ conv1 = self.conv1(x)
294
+ conv2 = self.conv2(x)
295
+ conv3 = self.conv3(x)
296
+ conv4 = self.conv4(x)
297
+ cat = torch.cat([conv1, conv2, conv3, conv4], 1)
298
+ out = self.convi(cat) + x
299
+ return out
300
+
301
+
302
+ class AdaptiveInstanceNorm(nn.Module):
303
+ def __init__(self, in_channel):
304
+ super().__init__()
305
+ self.norm = nn.InstanceNorm2d(in_channel)
306
+
307
+ def forward(self, input, style):
308
+ style_mean, style_std = calc_mean_std_4D(style)
309
+ out = self.norm(input)
310
+ size = input.size()
311
+ out = style_std.expand(size) * out + style_mean.expand(size)
312
+ return out
313
+
314
+ class NoiseInjection(nn.Module):
315
+ def __init__(self, channel):
316
+ super().__init__()
317
+ self.weight = nn.Parameter(torch.zeros(1, channel, 1, 1))
318
+ def forward(self, image, noise):
319
+ if noise is None:
320
+ b, c, h, w = image.shape
321
+ noise = image.new_empty(b, 1, h, w).normal_()
322
+ return image + self.weight * noise
323
+
324
+ class StyledUpBlock(nn.Module):
325
+ def __init__(self, in_channel, out_channel, kernel_size=3, padding=1,upsample=False, noise_inject=False):
326
+ super().__init__()
327
+
328
+ self.noise_inject = noise_inject
329
+ if upsample:
330
+ self.conv1 = nn.Sequential(
331
+ nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),
332
+ SpectralNorm(nn.Conv2d(in_channel, out_channel, kernel_size, padding=padding)),
333
+ nn.LeakyReLU(0.2),
334
+ )
335
+ else:
336
+ self.conv1 = nn.Sequential(
337
+ SpectralNorm(nn.Conv2d(in_channel, out_channel, kernel_size, padding=padding)),
338
+ nn.LeakyReLU(0.2),
339
+ SpectralNorm(nn.Conv2d(out_channel, out_channel, kernel_size, padding=padding)),
340
+ )
341
+ self.convup = nn.Sequential(
342
+ nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),
343
+ SpectralNorm(nn.Conv2d(out_channel, out_channel, kernel_size, padding=padding)),
344
+ nn.LeakyReLU(0.2),
345
+ SpectralNorm(nn.Conv2d(out_channel, out_channel, kernel_size, padding=padding)),
346
+ )
347
+ if self.noise_inject:
348
+ self.noise1 = NoiseInjection(out_channel)
349
+
350
+ self.lrelu1 = nn.LeakyReLU(0.2)
351
+
352
+ self.ScaleModel1 = nn.Sequential(
353
+ SpectralNorm(nn.Conv2d(in_channel,out_channel,3, 1, 1)),
354
+ nn.LeakyReLU(0.2),
355
+ SpectralNorm(nn.Conv2d(out_channel, out_channel, 3, 1, 1))
356
+ )
357
+ self.ShiftModel1 = nn.Sequential(
358
+ SpectralNorm(nn.Conv2d(in_channel,out_channel,3, 1, 1)),
359
+ nn.LeakyReLU(0.2),
360
+ SpectralNorm(nn.Conv2d(out_channel, out_channel, 3, 1, 1)),
361
+ )
362
+
363
+ def forward(self, input, style):
364
+ out = self.conv1(input)
365
+ out = self.lrelu1(out)
366
+ Shift1 = self.ShiftModel1(style)
367
+ Scale1 = self.ScaleModel1(style)
368
+ out = out * Scale1 + Shift1
369
+ if self.noise_inject:
370
+ out = self.noise1(out, noise=None)
371
+ outup = self.convup(out)
372
+ return outup
373
+
374
+
375
+ ####################################################################
376
+ ###############Face Dictionary Generator
377
+ ####################################################################
378
+ def AttentionBlock(in_channel):
379
+ return nn.Sequential(
380
+ SpectralNorm(nn.Conv2d(in_channel, in_channel, 3, 1, 1)),
381
+ nn.LeakyReLU(0.2),
382
+ SpectralNorm(nn.Conv2d(in_channel, in_channel, 3, 1, 1)),
383
+ )
384
+
385
+ class DilateResBlock(nn.Module):
386
+ def __init__(self, dim, dilation=[5,3] ):
387
+ super(DilateResBlock, self).__init__()
388
+ self.Res = nn.Sequential(
389
+ SpectralNorm(nn.Conv2d(dim, dim, 3, 1, ((3-1)//2)*dilation[0], dilation[0])),
390
+ nn.LeakyReLU(0.2),
391
+ SpectralNorm(nn.Conv2d(dim, dim, 3, 1, ((3-1)//2)*dilation[1], dilation[1])),
392
+ )
393
+ def forward(self, x):
394
+ out = x + self.Res(x)
395
+ return out
396
+
397
+
398
+ class KeyValue(nn.Module):
399
+ def __init__(self, indim, keydim, valdim):
400
+ super(KeyValue, self).__init__()
401
+ self.Key = nn.Sequential(
402
+ SpectralNorm(nn.Conv2d(indim, keydim, kernel_size=(3,3), padding=(1,1), stride=1)),
403
+ nn.LeakyReLU(0.2),
404
+ SpectralNorm(nn.Conv2d(keydim, keydim, kernel_size=(3,3), padding=(1,1), stride=1)),
405
+ )
406
+ self.Value = nn.Sequential(
407
+ SpectralNorm(nn.Conv2d(indim, valdim, kernel_size=(3,3), padding=(1,1), stride=1)),
408
+ nn.LeakyReLU(0.2),
409
+ SpectralNorm(nn.Conv2d(valdim, valdim, kernel_size=(3,3), padding=(1,1), stride=1)),
410
+ )
411
+ def forward(self, x):
412
+ return self.Key(x), self.Value(x)
413
+
414
+ class MaskAttention(nn.Module):
415
+ def __init__(self, indim):
416
+ super(MaskAttention, self).__init__()
417
+ self.conv1 = nn.Sequential(
418
+ SpectralNorm(nn.Conv2d(indim, indim//3, kernel_size=(3,3), padding=(1,1), stride=1)),
419
+ nn.LeakyReLU(0.2),
420
+ SpectralNorm(nn.Conv2d(indim//3, indim//3, kernel_size=(3,3), padding=(1,1), stride=1)),
421
+ )
422
+ self.conv2 = nn.Sequential(
423
+ SpectralNorm(nn.Conv2d(indim, indim//3, kernel_size=(3,3), padding=(1,1), stride=1)),
424
+ nn.LeakyReLU(0.2),
425
+ SpectralNorm(nn.Conv2d(indim//3, indim//3, kernel_size=(3,3), padding=(1,1), stride=1)),
426
+ )
427
+ self.conv3 = nn.Sequential(
428
+ SpectralNorm(nn.Conv2d(indim, indim//3, kernel_size=(3,3), padding=(1,1), stride=1)),
429
+ nn.LeakyReLU(0.2),
430
+ SpectralNorm(nn.Conv2d(indim//3, indim//3, kernel_size=(3,3), padding=(1,1), stride=1)),
431
+ )
432
+ self.convCat = nn.Sequential(
433
+ SpectralNorm(nn.Conv2d(indim//3 * 3, indim, kernel_size=(3,3), padding=(1,1), stride=1)),
434
+ nn.LeakyReLU(0.2),
435
+ SpectralNorm(nn.Conv2d(indim, indim, kernel_size=(3,3), padding=(1,1), stride=1)),
436
+ )
437
+ def forward(self, x, y, z):
438
+ c1 = self.conv1(x)
439
+ c2 = self.conv2(y)
440
+ c3 = self.conv3(z)
441
+ return self.convCat(torch.cat([c1,c2,c3], dim=1))
442
+
443
+ class Query(nn.Module):
444
+ def __init__(self, indim, quedim):
445
+ super(Query, self).__init__()
446
+ self.Query = nn.Sequential(
447
+ SpectralNorm(nn.Conv2d(indim, quedim, kernel_size=(3,3), padding=(1,1), stride=1)),
448
+ nn.LeakyReLU(0.2),
449
+ SpectralNorm(nn.Conv2d(quedim, quedim, kernel_size=(3,3), padding=(1,1), stride=1)),
450
+ )
451
+ def forward(self, x):
452
+ return self.Query(x)
453
+
454
+ def roi_align_self(input, location, target_size):
455
+ return torch.cat([F.interpolate(input[i:i+1,:,location[i,1]:location[i,3],location[i,0]:location[i,2]],(target_size,target_size),mode='bilinear',align_corners=False) for i in range(input.size(0))],0)
456
+
457
+ class FeatureExtractor(nn.Module):
458
+ def __init__(self, ngf = 64, key_scale = 4):#
459
+ super().__init__()
460
+
461
+ self.key_scale = 4
462
+ self.part_sizes = np.array([80,80,50,110]) #
463
+ self.feature_sizes = np.array([256,128,64]) #
464
+
465
+ self.conv1 = nn.Sequential(
466
+ SpectralNorm(nn.Conv2d(3, ngf, 3, 2, 1)),
467
+ nn.LeakyReLU(0.2),
468
+ SpectralNorm(nn.Conv2d(ngf, ngf, 3, 1, 1)),
469
+ )
470
+ self.conv2 = nn.Sequential(
471
+ SpectralNorm(nn.Conv2d(ngf, ngf, 3, 1, 1)),
472
+ nn.LeakyReLU(0.2),
473
+ SpectralNorm(nn.Conv2d(ngf, ngf, 3, 1, 1))
474
+ )
475
+ self.res1 = DilateResBlock(ngf, [5,3])
476
+ self.res2 = DilateResBlock(ngf, [5,3])
477
+
478
+
479
+ self.conv3 = nn.Sequential(
480
+ SpectralNorm(nn.Conv2d(ngf, ngf*2, 3, 2, 1)),
481
+ nn.LeakyReLU(0.2),
482
+ SpectralNorm(nn.Conv2d(ngf*2, ngf*2, 3, 1, 1)),
483
+ )
484
+ self.conv4 = nn.Sequential(
485
+ SpectralNorm(nn.Conv2d(ngf*2, ngf*2, 3, 1, 1)),
486
+ nn.LeakyReLU(0.2),
487
+ SpectralNorm(nn.Conv2d(ngf*2, ngf*2, 3, 1, 1))
488
+ )
489
+ self.res3 = DilateResBlock(ngf*2, [3,1])
490
+ self.res4 = DilateResBlock(ngf*2, [3,1])
491
+
492
+ self.conv5 = nn.Sequential(
493
+ SpectralNorm(nn.Conv2d(ngf*2, ngf*4, 3, 2, 1)),
494
+ nn.LeakyReLU(0.2),
495
+ SpectralNorm(nn.Conv2d(ngf*4, ngf*4, 3, 1, 1)),
496
+ )
497
+ self.conv6 = nn.Sequential(
498
+ SpectralNorm(nn.Conv2d(ngf*4, ngf*4, 3, 1, 1)),
499
+ nn.LeakyReLU(0.2),
500
+ SpectralNorm(nn.Conv2d(ngf*4, ngf*4, 3, 1, 1))
501
+ )
502
+ self.res5 = DilateResBlock(ngf*4, [1,1])
503
+ self.res6 = DilateResBlock(ngf*4, [1,1])
504
+
505
+ self.LE_256_Q = Query(ngf, ngf // self.key_scale)
506
+ self.RE_256_Q = Query(ngf, ngf // self.key_scale)
507
+ self.MO_256_Q = Query(ngf, ngf // self.key_scale)
508
+ self.LE_128_Q = Query(ngf * 2, ngf * 2 // self.key_scale)
509
+ self.RE_128_Q = Query(ngf * 2, ngf * 2 // self.key_scale)
510
+ self.MO_128_Q = Query(ngf * 2, ngf * 2 // self.key_scale)
511
+ self.LE_64_Q = Query(ngf * 4, ngf * 4 // self.key_scale)
512
+ self.RE_64_Q = Query(ngf * 4, ngf * 4 // self.key_scale)
513
+ self.MO_64_Q = Query(ngf * 4, ngf * 4 // self.key_scale)
514
+
515
+
516
+ def forward(self, img, locs):
517
+ le_location = locs[:,0,:].int().cpu().numpy()
518
+ re_location = locs[:,1,:].int().cpu().numpy()
519
+ no_location = locs[:,2,:].int().cpu().numpy()
520
+ mo_location = locs[:,3,:].int().cpu().numpy()
521
+
522
+
523
+ f1_0 = self.conv1(img)
524
+ f1_1 = self.res1(f1_0)
525
+ f2_0 = self.conv2(f1_1)
526
+ f2_1 = self.res2(f2_0)
527
+
528
+ f3_0 = self.conv3(f2_1)
529
+ f3_1 = self.res3(f3_0)
530
+ f4_0 = self.conv4(f3_1)
531
+ f4_1 = self.res4(f4_0)
532
+
533
+ f5_0 = self.conv5(f4_1)
534
+ f5_1 = self.res5(f5_0)
535
+ f6_0 = self.conv6(f5_1)
536
+ f6_1 = self.res6(f6_0)
537
+
538
+
539
+ ####ROI Align
540
+ le_part_256 = roi_align_self(f2_1.clone(), le_location//2, self.part_sizes[0]//2)
541
+ re_part_256 = roi_align_self(f2_1.clone(), re_location//2, self.part_sizes[1]//2)
542
+ mo_part_256 = roi_align_self(f2_1.clone(), mo_location//2, self.part_sizes[3]//2)
543
+
544
+ le_part_128 = roi_align_self(f4_1.clone(), le_location//4, self.part_sizes[0]//4)
545
+ re_part_128 = roi_align_self(f4_1.clone(), re_location//4, self.part_sizes[1]//4)
546
+ mo_part_128 = roi_align_self(f4_1.clone(), mo_location//4, self.part_sizes[3]//4)
547
+
548
+ le_part_64 = roi_align_self(f6_1.clone(), le_location//8, self.part_sizes[0]//8)
549
+ re_part_64 = roi_align_self(f6_1.clone(), re_location//8, self.part_sizes[1]//8)
550
+ mo_part_64 = roi_align_self(f6_1.clone(), mo_location//8, self.part_sizes[3]//8)
551
+
552
+
553
+ le_256_q = self.LE_256_Q(le_part_256)
554
+ re_256_q = self.RE_256_Q(re_part_256)
555
+ mo_256_q = self.MO_256_Q(mo_part_256)
556
+
557
+ le_128_q = self.LE_128_Q(le_part_128)
558
+ re_128_q = self.RE_128_Q(re_part_128)
559
+ mo_128_q = self.MO_128_Q(mo_part_128)
560
+
561
+ le_64_q = self.LE_64_Q(le_part_64)
562
+ re_64_q = self.RE_64_Q(re_part_64)
563
+ mo_64_q = self.MO_64_Q(mo_part_64)
564
+
565
+ return {'f256': f2_1, 'f128': f4_1, 'f64': f6_1,\
566
+ 'le256': le_part_256, 're256': re_part_256, 'mo256': mo_part_256, \
567
+ 'le128': le_part_128, 're128': re_part_128, 'mo128': mo_part_128, \
568
+ 'le64': le_part_64, 're64': re_part_64, 'mo64': mo_part_64, \
569
+ 'le_256_q': le_256_q, 're_256_q': re_256_q, 'mo_256_q': mo_256_q,\
570
+ 'le_128_q': le_128_q, 're_128_q': re_128_q, 'mo_128_q': mo_128_q,\
571
+ 'le_64_q': le_64_q, 're_64_q': re_64_q, 'mo_64_q': mo_64_q}
572
+
573
+
574
+ class DMDNet(nn.Module):
575
+ def __init__(self, ngf = 64, banks_num = 128):
576
+ super().__init__()
577
+ self.part_sizes = np.array([80,80,50,110]) # size for 512
578
+ self.feature_sizes = np.array([256,128,64]) # size for 512
579
+
580
+ self.banks_num = banks_num
581
+ self.key_scale = 4
582
+
583
+ self.E_lq = FeatureExtractor(key_scale = self.key_scale)
584
+ self.E_hq = FeatureExtractor(key_scale = self.key_scale)
585
+
586
+ self.LE_256_KV = KeyValue(ngf, ngf // self.key_scale, ngf)
587
+ self.RE_256_KV = KeyValue(ngf, ngf // self.key_scale, ngf)
588
+ self.MO_256_KV = KeyValue(ngf, ngf // self.key_scale, ngf)
589
+
590
+ self.LE_128_KV = KeyValue(ngf * 2 , ngf * 2 // self.key_scale, ngf * 2)
591
+ self.RE_128_KV = KeyValue(ngf * 2 , ngf * 2 // self.key_scale, ngf * 2)
592
+ self.MO_128_KV = KeyValue(ngf * 2 , ngf * 2 // self.key_scale, ngf * 2)
593
+
594
+ self.LE_64_KV = KeyValue(ngf * 4 , ngf * 4 // self.key_scale, ngf * 4)
595
+ self.RE_64_KV = KeyValue(ngf * 4 , ngf * 4 // self.key_scale, ngf * 4)
596
+ self.MO_64_KV = KeyValue(ngf * 4 , ngf * 4 // self.key_scale, ngf * 4)
597
+
598
+
599
+ self.LE_256_Attention = AttentionBlock(64)
600
+ self.RE_256_Attention = AttentionBlock(64)
601
+ self.MO_256_Attention = AttentionBlock(64)
602
+
603
+ self.LE_128_Attention = AttentionBlock(128)
604
+ self.RE_128_Attention = AttentionBlock(128)
605
+ self.MO_128_Attention = AttentionBlock(128)
606
+
607
+ self.LE_64_Attention = AttentionBlock(256)
608
+ self.RE_64_Attention = AttentionBlock(256)
609
+ self.MO_64_Attention = AttentionBlock(256)
610
+
611
+ self.LE_256_Mask = MaskAttention(64)
612
+ self.RE_256_Mask = MaskAttention(64)
613
+ self.MO_256_Mask = MaskAttention(64)
614
+
615
+ self.LE_128_Mask = MaskAttention(128)
616
+ self.RE_128_Mask = MaskAttention(128)
617
+ self.MO_128_Mask = MaskAttention(128)
618
+
619
+ self.LE_64_Mask = MaskAttention(256)
620
+ self.RE_64_Mask = MaskAttention(256)
621
+ self.MO_64_Mask = MaskAttention(256)
622
+
623
+ self.MSDilate = MSDilateBlock(ngf*4, dilation = [4,3,2,1])
624
+
625
+ self.up1 = StyledUpBlock(ngf*4, ngf*2, noise_inject=False) #
626
+ self.up2 = StyledUpBlock(ngf*2, ngf, noise_inject=False) #
627
+ self.up3 = StyledUpBlock(ngf, ngf, noise_inject=False) #
628
+ self.up4 = nn.Sequential(
629
+ SpectralNorm(nn.Conv2d(ngf, ngf, 3, 1, 1)),
630
+ nn.LeakyReLU(0.2),
631
+ UpResBlock(ngf),
632
+ UpResBlock(ngf),
633
+ SpectralNorm(nn.Conv2d(ngf, 3, kernel_size=3, stride=1, padding=1)),
634
+ nn.Tanh()
635
+ )
636
+
637
+ # define generic memory, revise register_buffer to register_parameter for backward update
638
+ self.register_buffer('le_256_mem_key', torch.randn(128,16,40,40))
639
+ self.register_buffer('re_256_mem_key', torch.randn(128,16,40,40))
640
+ self.register_buffer('mo_256_mem_key', torch.randn(128,16,55,55))
641
+ self.register_buffer('le_256_mem_value', torch.randn(128,64,40,40))
642
+ self.register_buffer('re_256_mem_value', torch.randn(128,64,40,40))
643
+ self.register_buffer('mo_256_mem_value', torch.randn(128,64,55,55))
644
+
645
+
646
+ self.register_buffer('le_128_mem_key', torch.randn(128,32,20,20))
647
+ self.register_buffer('re_128_mem_key', torch.randn(128,32,20,20))
648
+ self.register_buffer('mo_128_mem_key', torch.randn(128,32,27,27))
649
+ self.register_buffer('le_128_mem_value', torch.randn(128,128,20,20))
650
+ self.register_buffer('re_128_mem_value', torch.randn(128,128,20,20))
651
+ self.register_buffer('mo_128_mem_value', torch.randn(128,128,27,27))
652
+
653
+ self.register_buffer('le_64_mem_key', torch.randn(128,64,10,10))
654
+ self.register_buffer('re_64_mem_key', torch.randn(128,64,10,10))
655
+ self.register_buffer('mo_64_mem_key', torch.randn(128,64,13,13))
656
+ self.register_buffer('le_64_mem_value', torch.randn(128,256,10,10))
657
+ self.register_buffer('re_64_mem_value', torch.randn(128,256,10,10))
658
+ self.register_buffer('mo_64_mem_value', torch.randn(128,256,13,13))
659
+
660
+
661
+ def readMem(self, k, v, q):
662
+ sim = F.conv2d(q, k)
663
+ score = F.softmax(sim/sqrt(sim.size(1)), dim=1) #B * S * 1 * 1 6*128
664
+ sb,sn,sw,sh = score.size()
665
+ s_m = score.view(sb, -1).unsqueeze(1)#2*1*M
666
+ vb,vn,vw,vh = v.size()
667
+ v_in = v.view(vb, -1).repeat(sb,1,1)#2*M*(c*w*h)
668
+ mem_out = torch.bmm(s_m, v_in).squeeze(1).view(sb, vn, vw,vh)
669
+ max_inds = torch.argmax(score, dim=1).squeeze()
670
+ return mem_out, max_inds
671
+
672
+
673
+ def memorize(self, img, locs):
674
+ fs = self.E_hq(img, locs)
675
+ LE256_key, LE256_value = self.LE_256_KV(fs['le256'])
676
+ RE256_key, RE256_value = self.RE_256_KV(fs['re256'])
677
+ MO256_key, MO256_value = self.MO_256_KV(fs['mo256'])
678
+
679
+ LE128_key, LE128_value = self.LE_128_KV(fs['le128'])
680
+ RE128_key, RE128_value = self.RE_128_KV(fs['re128'])
681
+ MO128_key, MO128_value = self.MO_128_KV(fs['mo128'])
682
+
683
+ LE64_key, LE64_value = self.LE_64_KV(fs['le64'])
684
+ RE64_key, RE64_value = self.RE_64_KV(fs['re64'])
685
+ MO64_key, MO64_value = self.MO_64_KV(fs['mo64'])
686
+
687
+ Mem256 = {'LE256Key': LE256_key, 'LE256Value': LE256_value, 'RE256Key': RE256_key, 'RE256Value': RE256_value,'MO256Key': MO256_key, 'MO256Value': MO256_value}
688
+ Mem128 = {'LE128Key': LE128_key, 'LE128Value': LE128_value, 'RE128Key': RE128_key, 'RE128Value': RE128_value,'MO128Key': MO128_key, 'MO128Value': MO128_value}
689
+ Mem64 = {'LE64Key': LE64_key, 'LE64Value': LE64_value, 'RE64Key': RE64_key, 'RE64Value': RE64_value,'MO64Key': MO64_key, 'MO64Value': MO64_value}
690
+
691
+ FS256 = {'LE256F':fs['le256'], 'RE256F':fs['re256'], 'MO256F':fs['mo256']}
692
+ FS128 = {'LE128F':fs['le128'], 'RE128F':fs['re128'], 'MO128F':fs['mo128']}
693
+ FS64 = {'LE64F':fs['le64'], 'RE64F':fs['re64'], 'MO64F':fs['mo64']}
694
+
695
+ return Mem256, Mem128, Mem64
696
+
697
+ def enhancer(self, fs_in, sp_256=None, sp_128=None, sp_64=None):
698
+ le_256_q = fs_in['le_256_q']
699
+ re_256_q = fs_in['re_256_q']
700
+ mo_256_q = fs_in['mo_256_q']
701
+
702
+ le_128_q = fs_in['le_128_q']
703
+ re_128_q = fs_in['re_128_q']
704
+ mo_128_q = fs_in['mo_128_q']
705
+
706
+ le_64_q = fs_in['le_64_q']
707
+ re_64_q = fs_in['re_64_q']
708
+ mo_64_q = fs_in['mo_64_q']
709
+
710
+
711
+ ####for 256
712
+ le_256_mem_g, le_256_inds = self.readMem(self.le_256_mem_key, self.le_256_mem_value, le_256_q)
713
+ re_256_mem_g, re_256_inds = self.readMem(self.re_256_mem_key, self.re_256_mem_value, re_256_q)
714
+ mo_256_mem_g, mo_256_inds = self.readMem(self.mo_256_mem_key, self.mo_256_mem_value, mo_256_q)
715
+
716
+ le_128_mem_g, le_128_inds = self.readMem(self.le_128_mem_key, self.le_128_mem_value, le_128_q)
717
+ re_128_mem_g, re_128_inds = self.readMem(self.re_128_mem_key, self.re_128_mem_value, re_128_q)
718
+ mo_128_mem_g, mo_128_inds = self.readMem(self.mo_128_mem_key, self.mo_128_mem_value, mo_128_q)
719
+
720
+ le_64_mem_g, le_64_inds = self.readMem(self.le_64_mem_key, self.le_64_mem_value, le_64_q)
721
+ re_64_mem_g, re_64_inds = self.readMem(self.re_64_mem_key, self.re_64_mem_value, re_64_q)
722
+ mo_64_mem_g, mo_64_inds = self.readMem(self.mo_64_mem_key, self.mo_64_mem_value, mo_64_q)
723
+
724
+ if sp_256 is not None and sp_128 is not None and sp_64 is not None:
725
+ le_256_mem_s, _ = self.readMem(sp_256['LE256Key'], sp_256['LE256Value'], le_256_q)
726
+ re_256_mem_s, _ = self.readMem(sp_256['RE256Key'], sp_256['RE256Value'], re_256_q)
727
+ mo_256_mem_s, _ = self.readMem(sp_256['MO256Key'], sp_256['MO256Value'], mo_256_q)
728
+ le_256_mask = self.LE_256_Mask(fs_in['le256'],le_256_mem_s,le_256_mem_g)
729
+ le_256_mem = le_256_mask*le_256_mem_s + (1-le_256_mask)*le_256_mem_g
730
+ re_256_mask = self.RE_256_Mask(fs_in['re256'],re_256_mem_s,re_256_mem_g)
731
+ re_256_mem = re_256_mask*re_256_mem_s + (1-re_256_mask)*re_256_mem_g
732
+ mo_256_mask = self.MO_256_Mask(fs_in['mo256'],mo_256_mem_s,mo_256_mem_g)
733
+ mo_256_mem = mo_256_mask*mo_256_mem_s + (1-mo_256_mask)*mo_256_mem_g
734
+
735
+ le_128_mem_s, _ = self.readMem(sp_128['LE128Key'], sp_128['LE128Value'], le_128_q)
736
+ re_128_mem_s, _ = self.readMem(sp_128['RE128Key'], sp_128['RE128Value'], re_128_q)
737
+ mo_128_mem_s, _ = self.readMem(sp_128['MO128Key'], sp_128['MO128Value'], mo_128_q)
738
+ le_128_mask = self.LE_128_Mask(fs_in['le128'],le_128_mem_s,le_128_mem_g)
739
+ le_128_mem = le_128_mask*le_128_mem_s + (1-le_128_mask)*le_128_mem_g
740
+ re_128_mask = self.RE_128_Mask(fs_in['re128'],re_128_mem_s,re_128_mem_g)
741
+ re_128_mem = re_128_mask*re_128_mem_s + (1-re_128_mask)*re_128_mem_g
742
+ mo_128_mask = self.MO_128_Mask(fs_in['mo128'],mo_128_mem_s,mo_128_mem_g)
743
+ mo_128_mem = mo_128_mask*mo_128_mem_s + (1-mo_128_mask)*mo_128_mem_g
744
+
745
+ le_64_mem_s, _ = self.readMem(sp_64['LE64Key'], sp_64['LE64Value'], le_64_q)
746
+ re_64_mem_s, _ = self.readMem(sp_64['RE64Key'], sp_64['RE64Value'], re_64_q)
747
+ mo_64_mem_s, _ = self.readMem(sp_64['MO64Key'], sp_64['MO64Value'], mo_64_q)
748
+ le_64_mask = self.LE_64_Mask(fs_in['le64'],le_64_mem_s,le_64_mem_g)
749
+ le_64_mem = le_64_mask*le_64_mem_s + (1-le_64_mask)*le_64_mem_g
750
+ re_64_mask = self.RE_64_Mask(fs_in['re64'],re_64_mem_s,re_64_mem_g)
751
+ re_64_mem = re_64_mask*re_64_mem_s + (1-re_64_mask)*re_64_mem_g
752
+ mo_64_mask = self.MO_64_Mask(fs_in['mo64'],mo_64_mem_s,mo_64_mem_g)
753
+ mo_64_mem = mo_64_mask*mo_64_mem_s + (1-mo_64_mask)*mo_64_mem_g
754
+ else:
755
+ le_256_mem = le_256_mem_g
756
+ re_256_mem = re_256_mem_g
757
+ mo_256_mem = mo_256_mem_g
758
+ le_128_mem = le_128_mem_g
759
+ re_128_mem = re_128_mem_g
760
+ mo_128_mem = mo_128_mem_g
761
+ le_64_mem = le_64_mem_g
762
+ re_64_mem = re_64_mem_g
763
+ mo_64_mem = mo_64_mem_g
764
+
765
+ le_256_mem_norm = adaptive_instance_normalization_4D(le_256_mem, fs_in['le256'])
766
+ re_256_mem_norm = adaptive_instance_normalization_4D(re_256_mem, fs_in['re256'])
767
+ mo_256_mem_norm = adaptive_instance_normalization_4D(mo_256_mem, fs_in['mo256'])
768
+
769
+ ####for 128
770
+ le_128_mem_norm = adaptive_instance_normalization_4D(le_128_mem, fs_in['le128'])
771
+ re_128_mem_norm = adaptive_instance_normalization_4D(re_128_mem, fs_in['re128'])
772
+ mo_128_mem_norm = adaptive_instance_normalization_4D(mo_128_mem, fs_in['mo128'])
773
+
774
+ ####for 64
775
+ le_64_mem_norm = adaptive_instance_normalization_4D(le_64_mem, fs_in['le64'])
776
+ re_64_mem_norm = adaptive_instance_normalization_4D(re_64_mem, fs_in['re64'])
777
+ mo_64_mem_norm = adaptive_instance_normalization_4D(mo_64_mem, fs_in['mo64'])
778
+
779
+
780
+ EnMem256 = {'LE256Norm': le_256_mem_norm, 'RE256Norm': re_256_mem_norm, 'MO256Norm': mo_256_mem_norm}
781
+ EnMem128 = {'LE128Norm': le_128_mem_norm, 'RE128Norm': re_128_mem_norm, 'MO128Norm': mo_128_mem_norm}
782
+ EnMem64 = {'LE64Norm': le_64_mem_norm, 'RE64Norm': re_64_mem_norm, 'MO64Norm': mo_64_mem_norm}
783
+ Ind256 = {'LE': le_256_inds, 'RE': re_256_inds, 'MO': mo_256_inds}
784
+ Ind128 = {'LE': le_128_inds, 'RE': re_128_inds, 'MO': mo_128_inds}
785
+ Ind64 = {'LE': le_64_inds, 'RE': re_64_inds, 'MO': mo_64_inds}
786
+ return EnMem256, EnMem128, EnMem64, Ind256, Ind128, Ind64
787
+
788
+ def reconstruct(self, fs_in, locs, memstar):
789
+ le_256_mem_norm, re_256_mem_norm, mo_256_mem_norm = memstar[0]['LE256Norm'], memstar[0]['RE256Norm'], memstar[0]['MO256Norm']
790
+ le_128_mem_norm, re_128_mem_norm, mo_128_mem_norm = memstar[1]['LE128Norm'], memstar[1]['RE128Norm'], memstar[1]['MO128Norm']
791
+ le_64_mem_norm, re_64_mem_norm, mo_64_mem_norm = memstar[2]['LE64Norm'], memstar[2]['RE64Norm'], memstar[2]['MO64Norm']
792
+
793
+ le_256_final = self.LE_256_Attention(le_256_mem_norm - fs_in['le256']) * le_256_mem_norm + fs_in['le256']
794
+ re_256_final = self.RE_256_Attention(re_256_mem_norm - fs_in['re256']) * re_256_mem_norm + fs_in['re256']
795
+ mo_256_final = self.MO_256_Attention(mo_256_mem_norm - fs_in['mo256']) * mo_256_mem_norm + fs_in['mo256']
796
+
797
+ le_128_final = self.LE_128_Attention(le_128_mem_norm - fs_in['le128']) * le_128_mem_norm + fs_in['le128']
798
+ re_128_final = self.RE_128_Attention(re_128_mem_norm - fs_in['re128']) * re_128_mem_norm + fs_in['re128']
799
+ mo_128_final = self.MO_128_Attention(mo_128_mem_norm - fs_in['mo128']) * mo_128_mem_norm + fs_in['mo128']
800
+
801
+ le_64_final = self.LE_64_Attention(le_64_mem_norm - fs_in['le64']) * le_64_mem_norm + fs_in['le64']
802
+ re_64_final = self.RE_64_Attention(re_64_mem_norm - fs_in['re64']) * re_64_mem_norm + fs_in['re64']
803
+ mo_64_final = self.MO_64_Attention(mo_64_mem_norm - fs_in['mo64']) * mo_64_mem_norm + fs_in['mo64']
804
+
805
+
806
+ le_location = locs[:,0,:]
807
+ re_location = locs[:,1,:]
808
+ mo_location = locs[:,3,:]
809
+ le_location = le_location.cpu().int().numpy()
810
+ re_location = re_location.cpu().int().numpy()
811
+ mo_location = mo_location.cpu().int().numpy()
812
+
813
+ up_in_256 = fs_in['f256'].clone()# * 0
814
+ up_in_128 = fs_in['f128'].clone()# * 0
815
+ up_in_64 = fs_in['f64'].clone()# * 0
816
+
817
+ for i in range(fs_in['f256'].size(0)):
818
+ up_in_256[i:i+1,:,le_location[i,1]//2:le_location[i,3]//2,le_location[i,0]//2:le_location[i,2]//2] = F.interpolate(le_256_final[i:i+1,:,:,:].clone(), (le_location[i,3]//2-le_location[i,1]//2,le_location[i,2]//2-le_location[i,0]//2),mode='bilinear',align_corners=False)
819
+ up_in_256[i:i+1,:,re_location[i,1]//2:re_location[i,3]//2,re_location[i,0]//2:re_location[i,2]//2] = F.interpolate(re_256_final[i:i+1,:,:,:].clone(), (re_location[i,3]//2-re_location[i,1]//2,re_location[i,2]//2-re_location[i,0]//2),mode='bilinear',align_corners=False)
820
+ up_in_256[i:i+1,:,mo_location[i,1]//2:mo_location[i,3]//2,mo_location[i,0]//2:mo_location[i,2]//2] = F.interpolate(mo_256_final[i:i+1,:,:,:].clone(), (mo_location[i,3]//2-mo_location[i,1]//2,mo_location[i,2]//2-mo_location[i,0]//2),mode='bilinear',align_corners=False)
821
+
822
+ up_in_128[i:i+1,:,le_location[i,1]//4:le_location[i,3]//4,le_location[i,0]//4:le_location[i,2]//4] = F.interpolate(le_128_final[i:i+1,:,:,:].clone(), (le_location[i,3]//4-le_location[i,1]//4,le_location[i,2]//4-le_location[i,0]//4),mode='bilinear',align_corners=False)
823
+ up_in_128[i:i+1,:,re_location[i,1]//4:re_location[i,3]//4,re_location[i,0]//4:re_location[i,2]//4] = F.interpolate(re_128_final[i:i+1,:,:,:].clone(), (re_location[i,3]//4-re_location[i,1]//4,re_location[i,2]//4-re_location[i,0]//4),mode='bilinear',align_corners=False)
824
+ up_in_128[i:i+1,:,mo_location[i,1]//4:mo_location[i,3]//4,mo_location[i,0]//4:mo_location[i,2]//4] = F.interpolate(mo_128_final[i:i+1,:,:,:].clone(), (mo_location[i,3]//4-mo_location[i,1]//4,mo_location[i,2]//4-mo_location[i,0]//4),mode='bilinear',align_corners=False)
825
+
826
+ up_in_64[i:i+1,:,le_location[i,1]//8:le_location[i,3]//8,le_location[i,0]//8:le_location[i,2]//8] = F.interpolate(le_64_final[i:i+1,:,:,:].clone(), (le_location[i,3]//8-le_location[i,1]//8,le_location[i,2]//8-le_location[i,0]//8),mode='bilinear',align_corners=False)
827
+ up_in_64[i:i+1,:,re_location[i,1]//8:re_location[i,3]//8,re_location[i,0]//8:re_location[i,2]//8] = F.interpolate(re_64_final[i:i+1,:,:,:].clone(), (re_location[i,3]//8-re_location[i,1]//8,re_location[i,2]//8-re_location[i,0]//8),mode='bilinear',align_corners=False)
828
+ up_in_64[i:i+1,:,mo_location[i,1]//8:mo_location[i,3]//8,mo_location[i,0]//8:mo_location[i,2]//8] = F.interpolate(mo_64_final[i:i+1,:,:,:].clone(), (mo_location[i,3]//8-mo_location[i,1]//8,mo_location[i,2]//8-mo_location[i,0]//8),mode='bilinear',align_corners=False)
829
+
830
+ ms_in_64 = self.MSDilate(fs_in['f64'].clone())
831
+ fea_up1 = self.up1(ms_in_64, up_in_64)
832
+ fea_up2 = self.up2(fea_up1, up_in_128) #
833
+ fea_up3 = self.up3(fea_up2, up_in_256) #
834
+ output = self.up4(fea_up3) #
835
+ return output
836
+
837
+ def generate_specific_dictionary(self, sp_imgs=None, sp_locs=None):
838
+ return self.memorize(sp_imgs, sp_locs)
839
+
840
+ def forward(self, lq=None, loc=None, sp_256 = None, sp_128 = None, sp_64 = None):
841
+ fs_in = self.E_lq(lq, loc) # low quality images
842
+ GeMemNorm256, GeMemNorm128, GeMemNorm64, Ind256, Ind128, Ind64 = self.enhancer(fs_in)
843
+ GeOut = self.reconstruct(fs_in, loc, memstar = [GeMemNorm256, GeMemNorm128, GeMemNorm64])
844
+ if sp_256 is not None and sp_128 is not None and sp_64 is not None:
845
+ GSMemNorm256, GSMemNorm128, GSMemNorm64, _, _, _ = self.enhancer(fs_in, sp_256, sp_128, sp_64)
846
+ GSOut = self.reconstruct(fs_in, loc, memstar = [GSMemNorm256, GSMemNorm128, GSMemNorm64])
847
+ else:
848
+ GSOut = None
849
+ return GeOut, GSOut
850
+
851
+ class UpResBlock(nn.Module):
852
+ def __init__(self, dim, conv_layer = nn.Conv2d, norm_layer = nn.BatchNorm2d):
853
+ super(UpResBlock, self).__init__()
854
+ self.Model = nn.Sequential(
855
+ SpectralNorm(conv_layer(dim, dim, 3, 1, 1)),
856
+ nn.LeakyReLU(0.2),
857
+ SpectralNorm(conv_layer(dim, dim, 3, 1, 1)),
858
+ )
859
+ def forward(self, x):
860
+ out = x + self.Model(x)
861
+ return out
roop/processors/Enhance_GFPGAN.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Callable
2
+ import cv2
3
+ import numpy as np
4
+ import onnxruntime
5
+ import roop.globals
6
+
7
+ from roop.typing import Face, Frame
8
+ from roop.utilities import resolve_relative_path
9
+
10
+
11
+ # THREAD_LOCK = threading.Lock()
12
+
13
+
14
+ class Enhance_GFPGAN():
15
+
16
+ model_gfpgan = None
17
+ name = None
18
+ devicename = None
19
+
20
+ processorname = 'gfpgan'
21
+ type = 'enhance'
22
+
23
+
24
+ def Initialize(self, devicename):
25
+ if self.model_gfpgan is None:
26
+ model_path = resolve_relative_path('../models/GFPGANv1.4.onnx')
27
+ self.model_gfpgan = onnxruntime.InferenceSession(model_path, None, providers=roop.globals.execution_providers)
28
+ self.devicename = devicename
29
+
30
+ self.name = self.model_gfpgan.get_inputs()[0].name
31
+
32
+ def Run(self, source_face: Face, target_face: Face, temp_frame: Frame) -> Frame:
33
+ # preprocess
34
+ input_size = temp_frame.shape[1]
35
+ temp_frame = cv2.resize(temp_frame, (512, 512), cv2.INTER_CUBIC)
36
+
37
+ temp_frame = cv2.cvtColor(temp_frame, cv2.COLOR_BGR2RGB)
38
+ temp_frame = temp_frame.astype('float32') / 255.0
39
+ temp_frame = (temp_frame - 0.5) / 0.5
40
+ temp_frame = np.expand_dims(temp_frame, axis=0).transpose(0, 3, 1, 2)
41
+
42
+ io_binding = self.model_gfpgan.io_binding()
43
+ io_binding.bind_cpu_input("input", temp_frame)
44
+ io_binding.bind_output("1288", self.devicename)
45
+ self.model_gfpgan.run_with_iobinding(io_binding)
46
+ ort_outs = io_binding.copy_outputs_to_cpu()
47
+ result = ort_outs[0][0]
48
+
49
+ # post-process
50
+ result = np.clip(result, -1, 1)
51
+ result = (result + 1) / 2
52
+ result = result.transpose(1, 2, 0) * 255.0
53
+ result = cv2.cvtColor(result, cv2.COLOR_RGB2BGR)
54
+ scale_factor = int(result.shape[1] / input_size)
55
+ return result.astype(np.uint8), scale_factor
56
+
57
+
58
+ def Release(self):
59
+ self.model_gfpgan = None
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
roop/processors/FaceSwapInsightFace.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Callable
2
+ import roop.globals
3
+ import insightface
4
+ import cv2
5
+ import numpy as np
6
+
7
+ from roop.typing import Face, Frame
8
+ from roop.utilities import resolve_relative_path
9
+
10
+
11
+
12
+ class FaceSwapInsightFace():
13
+ model_swap_insightface = None
14
+
15
+
16
+ processorname = 'faceswap'
17
+ type = 'swap'
18
+
19
+
20
+ def Initialize(self, devicename):
21
+ if self.model_swap_insightface is None:
22
+ model_path = resolve_relative_path('../models/inswapper_128.onnx')
23
+ self.model_swap_insightface = insightface.model_zoo.get_model(model_path, providers=roop.globals.execution_providers)
24
+
25
+
26
+ def Run(self, source_face: Face, target_face: Face, temp_frame: Frame) -> Frame:
27
+ img_fake, M = self.model_swap_insightface.get(temp_frame, target_face, source_face, paste_back=False)
28
+ target_face.matrix = M
29
+ return img_fake
30
+
31
+
32
+ def Release(self):
33
+ del self.model_swap_insightface
34
+ self.model_swap_insightface = None
35
+
36
+
37
+
38
+
39
+
40
+
roop/processors/Mask_Clip2Seg.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import numpy as np
4
+ import torch
5
+ import threading
6
+ from torchvision import transforms
7
+ from clip.clipseg import CLIPDensePredT
8
+ from numpy import asarray
9
+ from typing import Any, List, Callable
10
+ import numpy as np
11
+
12
+ from roop.typing import Face, Frame
13
+ from roop.utilities import resolve_relative_path
14
+
15
+ THREAD_LOCK_CLIP = threading.Lock()
16
+
17
+
18
+ class Mask_Clip2Seg():
19
+
20
+ model_clip = None
21
+
22
+ processorname = 'clip2seg'
23
+ type = 'mask'
24
+
25
+
26
+ def Initialize(self, devicename):
27
+ if self.model_clip is None:
28
+ self.model_clip = CLIPDensePredT(version='ViT-B/16', reduce_dim=64, complex_trans_conv=True)
29
+ self.model_clip.eval();
30
+ self.model_clip.load_state_dict(torch.load('models/CLIP/rd64-uni-refined.pth', map_location=torch.device('cpu')), strict=False)
31
+
32
+ device = torch.device(devicename)
33
+ self.model_clip.to(device)
34
+
35
+
36
+ def Run(self, img1, keywords:str) -> Frame:
37
+ if keywords is None or len(keywords) < 1:
38
+ return img1
39
+
40
+ source_image_small = cv2.resize(img1, (256,256))
41
+
42
+ img_mask = np.full((source_image_small.shape[0],source_image_small.shape[1]), 0, dtype=np.float32)
43
+ mask_border = 1
44
+ l = 0
45
+ t = 0
46
+ r = 1
47
+ b = 1
48
+
49
+ mask_blur = 5
50
+ clip_blur = 5
51
+
52
+ img_mask = cv2.rectangle(img_mask, (mask_border+int(l), mask_border+int(t)),
53
+ (256 - mask_border-int(r), 256-mask_border-int(b)), (255, 255, 255), -1)
54
+ img_mask = cv2.GaussianBlur(img_mask, (mask_blur*2+1,mask_blur*2+1), 0)
55
+ img_mask /= 255
56
+
57
+
58
+ input_image = source_image_small
59
+
60
+ transform = transforms.Compose([
61
+ transforms.ToTensor(),
62
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
63
+ transforms.Resize((256, 256)),
64
+ ])
65
+ img = transform(input_image).unsqueeze(0)
66
+
67
+ thresh = 0.5
68
+ prompts = keywords.split(',')
69
+ with THREAD_LOCK_CLIP:
70
+ with torch.no_grad():
71
+ preds = self.model_clip(img.repeat(len(prompts),1,1,1), prompts)[0]
72
+ clip_mask = torch.sigmoid(preds[0][0])
73
+ for i in range(len(prompts)-1):
74
+ clip_mask += torch.sigmoid(preds[i+1][0])
75
+
76
+ clip_mask = clip_mask.data.cpu().numpy()
77
+ np.clip(clip_mask, 0, 1)
78
+
79
+ clip_mask[clip_mask>thresh] = 1.0
80
+ clip_mask[clip_mask<=thresh] = 0.0
81
+ kernel = np.ones((5, 5), np.float32)
82
+ clip_mask = cv2.dilate(clip_mask, kernel, iterations=1)
83
+ clip_mask = cv2.GaussianBlur(clip_mask, (clip_blur*2+1,clip_blur*2+1), 0)
84
+
85
+ img_mask *= clip_mask
86
+ img_mask[img_mask<0.0] = 0.0
87
+ return img_mask
88
+
89
+
90
+
91
+ def Release(self):
92
+ self.model_clip = None
93
+
roop/processors/__init__.py ADDED
File without changes
roop/processors/frame/__init__.py ADDED
File without changes
roop/processors/frame/face_swapper.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Callable
2
+ import cv2
3
+ import insightface
4
+ import threading
5
+
6
+ import roop.globals
7
+ import roop.processors.frame.core
8
+ from roop.face_util import get_first_face, get_all_faces
9
+ from roop.typing import Face, Frame
10
+ from roop.utilities import conditional_download, resolve_relative_path, is_image, is_video, compute_cosine_distance, get_destfilename_from_path
11
+
12
+ FACE_SWAPPER = None
13
+ THREAD_LOCK = threading.Lock()
14
+ NAME = 'ROOP.FACE-SWAPPER'
15
+
16
+ DIST_THRESHOLD = 0.65
17
+
18
+
19
+ def get_face_swapper() -> Any:
20
+ global FACE_SWAPPER
21
+
22
+ with THREAD_LOCK:
23
+ if FACE_SWAPPER is None:
24
+ model_path = resolve_relative_path('../models/inswapper_128.onnx')
25
+ FACE_SWAPPER = insightface.model_zoo.get_model(model_path, providers=roop.globals.execution_providers)
26
+ return FACE_SWAPPER
27
+
28
+
29
+ def pre_check() -> bool:
30
+ download_directory_path = resolve_relative_path('../models')
31
+ conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/inswapper_128.onnx'])
32
+ return True
33
+
34
+
35
+ def pre_start() -> bool:
36
+ return True
37
+
38
+
39
+ def post_process() -> None:
40
+ global FACE_SWAPPER
41
+
42
+ FACE_SWAPPER = None
43
+
44
+
45
+ def swap_face(source_face: Face, target_face: Face, temp_frame: Frame) -> Frame:
46
+ return get_face_swapper().get(temp_frame, target_face, source_face, paste_back=True)
47
+
48
+
49
+ def process_frame(source_face: Face, target_face: Face, temp_frame: Frame) -> Frame:
50
+ global DIST_THRESHOLD
51
+
52
+ if roop.globals.many_faces:
53
+ many_faces = get_all_faces(temp_frame)
54
+ if many_faces is not None:
55
+ for target_face in many_faces:
56
+ if target_face['det_score'] > 0.65:
57
+ temp_frame = swap_face(source_face, target_face, temp_frame)
58
+ else:
59
+ if target_face:
60
+ target_embedding = target_face.embedding
61
+ many_faces = get_all_faces(temp_frame)
62
+ target_face = None
63
+ for dest_face in many_faces:
64
+ dest_embedding = dest_face.embedding
65
+ if compute_cosine_distance(target_embedding, dest_embedding) <= DIST_THRESHOLD:
66
+ target_face = dest_face
67
+ break
68
+ if target_face:
69
+ temp_frame = swap_face(source_face, target_face, temp_frame)
70
+ return temp_frame
71
+
72
+ target_face = get_first_face(temp_frame)
73
+ if target_face is not None:
74
+ temp_frame = swap_face(source_face, target_face, temp_frame)
75
+ return temp_frame
76
+
77
+
78
+
79
+ def process_frames(is_batch: bool, source_face: Face, target_face: Face, temp_frame_paths: List[str], update: Callable[[], None]) -> None:
80
+ for temp_frame_path in temp_frame_paths:
81
+ temp_frame = cv2.imread(temp_frame_path)
82
+ if temp_frame is not None:
83
+ result = process_frame(source_face, target_face, temp_frame)
84
+ if result is not None:
85
+ if is_batch:
86
+ tf = get_destfilename_from_path(temp_frame_path, roop.globals.output_path, '_fake.png')
87
+ cv2.imwrite(tf, result)
88
+ else:
89
+ cv2.imwrite(temp_frame_path, result)
90
+ if update:
91
+ update()
92
+
93
+
94
+ def process_image(source_face: Any, target_face: Any, target_path: str, output_path: str) -> None:
95
+ global DIST_THRESHOLD
96
+
97
+ target_frame = cv2.imread(target_path)
98
+ if target_frame is not None:
99
+ result = process_frame(source_face, target_face, target_frame)
100
+ if result is not None:
101
+ cv2.imwrite(output_path, result)
102
+
103
+
104
+ def process_video(source_face: Any, target_face: Any, temp_frame_paths: List[str]) -> None:
105
+ global DIST_THRESHOLD
106
+
107
+ roop.processors.frame.core.process_video(source_face, target_face, temp_frame_paths, process_frames)
108
+
109
+
110
+ def process_batch_images(source_face: Any, target_face: Any, temp_frame_paths: List[str]) -> None:
111
+ global DIST_THRESHOLD
112
+
113
+ roop.processors.frame.core.process_batch(source_face, target_face, temp_frame_paths, process_frames)
roop/template_parser.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from datetime import datetime
3
+
4
+ template_functions = {
5
+ "timestamp": lambda data: str(int(datetime.now().timestamp())),
6
+ "i": lambda data: data.get("index", False),
7
+ "file": lambda data: data.get("file", False),
8
+ "date": lambda data: datetime.now().strftime("%Y-%m-%d"),
9
+ "time": lambda data: datetime.now().strftime("%H-%M-%S"),
10
+ }
11
+
12
+
13
+ def parse(text: str, data: dict):
14
+ pattern = r"\{([^}]+)\}"
15
+
16
+ matches = re.findall(pattern, text)
17
+
18
+ for match in matches:
19
+ replacement = template_functions[match](data)
20
+ if replacement is not False:
21
+ text = text.replace(f"{{{match}}}", replacement)
22
+
23
+ return text
roop/typing.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ from insightface.app.common import Face
4
+ import numpy
5
+
6
+ Face = Face
7
+ Frame = numpy.ndarray[Any, Any]
roop/ui.py ADDED
@@ -0,0 +1,926 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import gradio as gr
4
+ import cv2
5
+ import pathlib
6
+ import shutil
7
+ import roop.globals
8
+ import roop.metadata
9
+ import roop.utilities as util
10
+
11
+ from roop.face_util import extract_face_images
12
+ from roop.capturer import get_video_frame, get_video_frame_total, get_image_frame
13
+ from roop.ProcessEntry import ProcessEntry
14
+
15
+ restart_server = False
16
+ live_cam_active = False
17
+
18
+ RECENT_DIRECTORY_SOURCE = None
19
+ RECENT_DIRECTORY_TARGET = None
20
+ RECENT_DIRECTORY_OUTPUT = None
21
+
22
+ SELECTION_FACES_DATA = None
23
+
24
+ last_image = None
25
+
26
+ input_thumbs = []
27
+ target_thumbs = []
28
+
29
+
30
+ IS_INPUT = True
31
+ SELECTED_FACE_INDEX = 0
32
+
33
+ SELECTED_INPUT_FACE_INDEX = 0
34
+ SELECTED_TARGET_FACE_INDEX = 0
35
+
36
+ roop.globals.keep_fps = None
37
+ roop.globals.keep_frames = None
38
+ roop.globals.skip_audio = None
39
+ roop.globals.use_batch = None
40
+
41
+ input_faces = None
42
+ target_faces = None
43
+ face_selection = None
44
+ fake_cam_image = None
45
+
46
+ current_cam_image = None
47
+ cam_swapping = False
48
+ camthread = None
49
+
50
+ selected_preview_index = 0
51
+
52
+ is_processing = False
53
+
54
+ list_files_process : list[ProcessEntry] = []
55
+
56
+
57
+ def prepare_environment():
58
+ roop.globals.output_path = os.path.abspath(os.path.join(os.getcwd(), "output"))
59
+ os.makedirs(roop.globals.output_path, exist_ok=True)
60
+ os.environ["TEMP"] = os.environ["TMP"] = os.path.abspath(os.path.join(os.getcwd(), "temp"))
61
+ os.makedirs(os.environ["TEMP"], exist_ok=True)
62
+ os.environ["GRADIO_TEMP_DIR"] = os.environ["TEMP"]
63
+
64
+
65
+ def run():
66
+ from roop.core import suggest_execution_providers, decode_execution_providers, set_display_ui
67
+ global input_faces, target_faces, face_selection, fake_cam_image, restart_server, live_cam_active, on_settings_changed
68
+
69
+ prepare_environment()
70
+
71
+ available_themes = ["Default", "gradio/glass", "gradio/monochrome", "gradio/seafoam", "gradio/soft", "gstaff/xkcd", "freddyaboulton/dracula_revamped", "ysharma/steampunk"]
72
+ image_formats = ['jpg','png', 'webp']
73
+ video_formats = ['avi','mkv', 'mp4', 'webm']
74
+ video_codecs = ['libx264', 'libx265', 'libvpx-vp9', 'h264_nvenc', 'hevc_nvenc']
75
+ providerlist = suggest_execution_providers()
76
+
77
+ settings_controls = []
78
+
79
+ live_cam_active = roop.globals.CFG.live_cam_start_active
80
+ set_display_ui(show_msg)
81
+ roop.globals.execution_providers = decode_execution_providers([roop.globals.CFG.provider])
82
+ print(f'Using provider {roop.globals.execution_providers} - Device:{util.get_device()}')
83
+
84
+ run_server = True
85
+ mycss = """
86
+ span {color: var(--block-info-text-color)}
87
+ #fixedheight {
88
+ max-height: 238.4px;
89
+ overflow-y: auto !important;
90
+ }
91
+ """
92
+
93
+ while run_server:
94
+ server_name = roop.globals.CFG.server_name
95
+ if server_name is None or len(server_name) < 1:
96
+ server_name = None
97
+ server_port = roop.globals.CFG.server_port
98
+ if server_port <= 0:
99
+ server_port = None
100
+ ssl_verify = False if server_name == '0.0.0.0' else True
101
+ with gr.Blocks(title=f'{roop.metadata.name} {roop.metadata.version}', theme=roop.globals.CFG.selected_theme, css=mycss) as ui:
102
+ with gr.Row(variant='compact'):
103
+ gr.Markdown(f"### [{roop.metadata.name} {roop.metadata.version}](https://github.com/C0untFloyd/roop-unleashed)")
104
+ gr.HTML(util.create_version_html(), elem_id="versions")
105
+ with gr.Tab("🎭 Face Swap"):
106
+ with gr.Row(variant='panel'):
107
+ with gr.Column(scale=2):
108
+ with gr.Row():
109
+ with gr.Column(min_width=160):
110
+ input_faces = gr.Gallery(label="Input faces", allow_preview=True, preview=True, height=128, object_fit="scale-down")
111
+ mask_top = gr.Slider(0, 256, value=0, label="Offset Face Top", step=1.0, interactive=True)
112
+ bt_remove_selected_input_face = gr.Button("❌ Remove selected", size='sm')
113
+ bt_clear_input_faces = gr.Button("💥 Clear all", variant='stop', size='sm')
114
+ with gr.Column(min_width=160):
115
+ target_faces = gr.Gallery(label="Target faces", allow_preview=True, preview=True, height=128, object_fit="scale-down")
116
+ bt_remove_selected_target_face = gr.Button("❌ Remove selected", size='sm')
117
+ bt_add_local = gr.Button('Add local files from', size='sm')
118
+ local_folder = gr.Textbox(show_label=False, placeholder="/content/", interactive=True)
119
+ with gr.Row(variant='panel'):
120
+ bt_srcimg = gr.Image(label='Source Face Image', type='filepath', tool=None, height=233)
121
+ bt_destfiles = gr.Files(label='Target File(s)', file_count="multiple", elem_id='filelist', height=233)
122
+ with gr.Row(variant='panel'):
123
+ gr.Markdown('')
124
+ forced_fps = gr.Slider(minimum=0, maximum=120, value=0, label="Video FPS", info='Overrides detected fps if not 0', step=1.0, interactive=True, container=True)
125
+
126
+ with gr.Column(scale=2):
127
+ previewimage = gr.Image(label="Preview Image", height=576, interactive=False)
128
+ with gr.Row(variant='panel'):
129
+ fake_preview = gr.Checkbox(label="Face swap frames", value=False)
130
+ bt_refresh_preview = gr.Button("🔄 Refresh", variant='secondary', size='sm')
131
+ bt_use_face_from_preview = gr.Button("Use Face from this Frame", variant='primary', size='sm')
132
+ with gr.Row():
133
+ preview_frame_num = gr.Slider(0, 0, value=0, label="Frame Number", step=1.0, interactive=True)
134
+ with gr.Row():
135
+ text_frame_clip = gr.Markdown('Processing frame range [0 - 0]')
136
+ set_frame_start = gr.Button("⬅ Set as Start", size='sm')
137
+ set_frame_end = gr.Button("➡ Set as End", size='sm')
138
+ with gr.Row(visible=False) as dynamic_face_selection:
139
+ with gr.Column(scale=2):
140
+ face_selection = gr.Gallery(label="Detected faces", allow_preview=True, preview=True, height=256, object_fit="scale-down")
141
+ with gr.Column():
142
+ bt_faceselect = gr.Button("☑ Use selected face", size='sm')
143
+ bt_cancelfaceselect = gr.Button("Done", size='sm')
144
+ with gr.Column():
145
+ gr.Markdown(' ')
146
+
147
+ with gr.Row(variant='panel'):
148
+ with gr.Column(scale=1):
149
+ selected_face_detection = gr.Dropdown(["First found", "All faces", "Selected face", "All female", "All male"], value="First found", label="Select face selection for swapping")
150
+ max_face_distance = gr.Slider(0.01, 1.0, value=0.65, label="Max Face Similarity Threshold")
151
+ video_swapping_method = gr.Dropdown(["Extract Frames to media","In-Memory processing"], value="In-Memory", label="Select video processing method", interactive=True)
152
+ roop.globals.keep_frames = gr.Checkbox(label="Keep Frames (relevant only when extracting frames)", value=False)
153
+ roop.globals.skip_audio = gr.Checkbox(label="Skip audio", value=False)
154
+ with gr.Column(scale=1):
155
+ selected_enhancer = gr.Dropdown(["None", "Codeformer", "DMDNet", "GFPGAN"], value="None", label="Select post-processing")
156
+ blend_ratio = gr.Slider(0.0, 1.0, value=0.65, label="Original/Enhanced image blend ratio")
157
+ with gr.Column(scale=1):
158
+ chk_useclip = gr.Checkbox(label="Use Text Masking", value=False)
159
+ clip_text = gr.Textbox(label="List of objects to mask and restore back on fake image", placeholder="cup,hands,hair,banana" ,elem_id='tooltip')
160
+ gr.Dropdown(["Clip2Seg"], value="Clip2Seg", label="Engine")
161
+ bt_preview_mask = gr.Button("👥 Show Mask Preview", variant='secondary')
162
+
163
+ with gr.Row(variant='panel'):
164
+ with gr.Column():
165
+ bt_start = gr.Button("▶ Start", variant='primary')
166
+ gr.Button("👀 Open Output Folder", size='sm').click(fn=lambda: util.open_folder(roop.globals.output_path))
167
+ with gr.Column():
168
+ bt_stop = gr.Button("⏹ Stop", variant='secondary')
169
+ with gr.Column(scale=2):
170
+ gr.Markdown(' ')
171
+ with gr.Row(variant='panel'):
172
+ with gr.Column():
173
+ resultfiles = gr.Files(label='Processed File(s)', interactive=False)
174
+ with gr.Column():
175
+ resultimage = gr.Image(type='filepath', label='Final Image', interactive=False, )
176
+
177
+
178
+ with gr.Tab("🎥 Live Cam"):
179
+ with gr.Row():
180
+ with gr.Column(scale=2):
181
+ cam_toggle = gr.Checkbox(label='Activate', value=live_cam_active)
182
+ with gr.Column(scale=1):
183
+ vcam_toggle = gr.Checkbox(label='Stream to virtual camera', value=False)
184
+ with gr.Column(scale=1):
185
+ camera_num = gr.Slider(0, 2, value=0, label="Camera Number", step=1.0, interactive=True)
186
+
187
+ if live_cam_active:
188
+ with gr.Row():
189
+ with gr.Column():
190
+ cam = gr.Webcam(label='Camera', source='webcam', mirror_webcam=True, interactive=True, streaming=False)
191
+ with gr.Column():
192
+ fake_cam_image = gr.Image(label='Fake Camera Output', interactive=False)
193
+
194
+
195
+ with gr.Tab("🎉 Extras"):
196
+ with gr.Row():
197
+ files_to_process = gr.Files(label='File(s) to process', file_count="multiple")
198
+ # with gr.Row(variant='panel'):
199
+ # with gr.Accordion(label="Post process", open=False):
200
+ # with gr.Column():
201
+ # selected_post_enhancer = gr.Dropdown(["None", "Codeformer", "GFPGAN"], value="None", label="Select post-processing")
202
+ # with gr.Column():
203
+ # gr.Button("Start").click(fn=lambda: gr.Info('Not yet implemented...'))
204
+ with gr.Row(variant='panel'):
205
+ with gr.Accordion(label="Video/GIF", open=False):
206
+ with gr.Row(variant='panel'):
207
+ with gr.Column():
208
+ gr.Markdown("""
209
+ # Cut video
210
+ Be aware that this means re-encoding the video which might take a longer time.
211
+ Encoding uses your configuration from the Settings Tab.
212
+ """)
213
+ with gr.Column():
214
+ cut_start_time = gr.Slider(0, 1000000, value=0, label="Start Frame", step=1.0, interactive=True)
215
+ with gr.Column():
216
+ cut_end_time = gr.Slider(1, 1000000, value=1, label="End Frame", step=1.0, interactive=True)
217
+ with gr.Column():
218
+ start_cut_video = gr.Button("Start")
219
+
220
+ # with gr.Row(variant='panel'):
221
+ # with gr.Column():
222
+ # gr.Markdown("""
223
+ # # Join videos
224
+ # This also re-encodes the videos like cutting above.
225
+ # """)
226
+ # with gr.Column():
227
+ # start_join_videos = gr.Button("Start")
228
+ with gr.Row(variant='panel'):
229
+ gr.Markdown("Extract frames from video")
230
+ start_extract_frames = gr.Button("Start")
231
+ with gr.Row(variant='panel'):
232
+ gr.Markdown("Create video from image files")
233
+ gr.Button("Start").click(fn=lambda: gr.Info('Not yet implemented...'))
234
+ with gr.Row(variant='panel'):
235
+ gr.Markdown("Create GIF from video")
236
+ start_create_gif = gr.Button("Create GIF")
237
+ with gr.Row():
238
+ extra_files_output = gr.Files(label='Resulting output files', file_count="multiple")
239
+
240
+
241
+ with gr.Tab("⚙ Settings"):
242
+ with gr.Row():
243
+ with gr.Column():
244
+ themes = gr.Dropdown(available_themes, label="Theme", info="Change needs complete restart", value=roop.globals.CFG.selected_theme)
245
+ with gr.Column():
246
+ settings_controls.append(gr.Checkbox(label="Public Server", value=roop.globals.CFG.server_share, elem_id='server_share', interactive=True))
247
+ settings_controls.append(gr.Checkbox(label='Clear output folder before each run', value=roop.globals.CFG.clear_output, elem_id='clear_output', interactive=True))
248
+ output_template = gr.Textbox(label="Filename Output Template", info="(file extension is added automatically)", lines=1, placeholder='{file}_{time}', value=roop.globals.CFG.output_template)
249
+ with gr.Column():
250
+ input_server_name = gr.Textbox(label="Server Name", lines=1, info="Leave blank to run locally", value=roop.globals.CFG.server_name)
251
+ with gr.Column():
252
+ input_server_port = gr.Number(label="Server Port", precision=0, info="Leave at 0 to use default", value=roop.globals.CFG.server_port)
253
+ with gr.Row():
254
+ with gr.Column():
255
+ settings_controls.append(gr.Dropdown(providerlist, label="Provider", value=roop.globals.CFG.provider, elem_id='provider', interactive=True))
256
+ chk_det_size = gr.Checkbox(label="Use default Det-Size", value=True, elem_id='default_det_size', interactive=True)
257
+ settings_controls.append(gr.Checkbox(label="Force CPU for Face Analyser", value=roop.globals.CFG.force_cpu, elem_id='force_cpu', interactive=True))
258
+ max_threads = gr.Slider(1, 32, value=roop.globals.CFG.max_threads, label="Max. Number of Threads", info='default: 3', step=1.0, interactive=True)
259
+ with gr.Column():
260
+ memory_limit = gr.Slider(0, 128, value=roop.globals.CFG.memory_limit, label="Max. Memory to use (Gb)", info='0 meaning no limit', step=1.0, interactive=True)
261
+ settings_controls.append(gr.Dropdown(image_formats, label="Image Output Format", info='default: png', value=roop.globals.CFG.output_image_format, elem_id='output_image_format', interactive=True))
262
+ with gr.Column():
263
+ settings_controls.append(gr.Dropdown(video_codecs, label="Video Codec", info='default: libx264', value=roop.globals.CFG.output_video_codec, elem_id='output_video_codec', interactive=True))
264
+ settings_controls.append(gr.Dropdown(video_formats, label="Video Output Format", info='default: mp4', value=roop.globals.CFG.output_video_format, elem_id='output_video_format', interactive=True))
265
+ video_quality = gr.Slider(0, 100, value=roop.globals.CFG.video_quality, label="Video Quality (crf)", info='default: 14', step=1.0, interactive=True)
266
+ with gr.Column():
267
+ button_apply_restart = gr.Button("Restart Server", variant='primary')
268
+ settings_controls.append(gr.Checkbox(label='Start with active live cam', value=roop.globals.CFG.live_cam_start_active, elem_id='live_cam_start_active', interactive=True))
269
+ button_clean_temp = gr.Button("Clean temp folder")
270
+ button_apply_settings = gr.Button("Apply Settings")
271
+
272
+ previewinputs = [preview_frame_num, bt_destfiles, fake_preview, selected_enhancer, selected_face_detection,
273
+ max_face_distance, blend_ratio, chk_useclip, clip_text]
274
+ input_faces.select(on_select_input_face, None, None).then(fn=on_preview_frame_changed, inputs=previewinputs, outputs=[previewimage, mask_top])
275
+ bt_remove_selected_input_face.click(fn=remove_selected_input_face, outputs=[input_faces])
276
+ bt_srcimg.change(fn=on_srcimg_changed, show_progress='full', inputs=bt_srcimg, outputs=[dynamic_face_selection, face_selection, input_faces])
277
+
278
+ mask_top.input(fn=on_mask_top_changed, inputs=[mask_top], show_progress='hidden')
279
+
280
+
281
+ target_faces.select(on_select_target_face, None, None)
282
+ bt_remove_selected_target_face.click(fn=remove_selected_target_face, outputs=[target_faces])
283
+
284
+ forced_fps.change(fn=on_fps_changed, inputs=[forced_fps], show_progress='hidden')
285
+ bt_destfiles.change(fn=on_destfiles_changed, inputs=[bt_destfiles], outputs=[preview_frame_num, text_frame_clip], show_progress='hidden').then(fn=on_preview_frame_changed, inputs=previewinputs, outputs=[previewimage, mask_top], show_progress='full')
286
+ bt_destfiles.select(fn=on_destfiles_selected, outputs=[preview_frame_num, text_frame_clip, forced_fps], show_progress='hidden').then(fn=on_preview_frame_changed, inputs=previewinputs, outputs=[previewimage, mask_top], show_progress='hidden')
287
+ bt_destfiles.clear(fn=on_clear_destfiles, outputs=[target_faces])
288
+ resultfiles.select(fn=on_resultfiles_selected, inputs=[resultfiles], outputs=[resultimage])
289
+
290
+ face_selection.select(on_select_face, None, None)
291
+ bt_faceselect.click(fn=on_selected_face, outputs=[input_faces, target_faces, selected_face_detection])
292
+ bt_cancelfaceselect.click(fn=on_end_face_selection, outputs=[dynamic_face_selection, face_selection])
293
+
294
+ bt_clear_input_faces.click(fn=on_clear_input_faces, outputs=[input_faces])
295
+
296
+ chk_det_size.select(fn=on_option_changed)
297
+
298
+ bt_add_local.click(fn=on_add_local_folder, inputs=[local_folder], outputs=[bt_destfiles])
299
+ bt_preview_mask.click(fn=on_preview_mask, inputs=[preview_frame_num, bt_destfiles, clip_text], outputs=[previewimage])
300
+
301
+ start_event = bt_start.click(fn=start_swap,
302
+ inputs=[selected_enhancer, selected_face_detection, roop.globals.keep_frames,
303
+ roop.globals.skip_audio, max_face_distance, blend_ratio, chk_useclip, clip_text,video_swapping_method],
304
+ outputs=[bt_start, resultfiles]).then(fn=on_resultfiles_finished, inputs=[resultfiles], outputs=[resultimage])
305
+
306
+ bt_stop.click(fn=stop_swap, cancels=[start_event])
307
+
308
+ bt_refresh_preview.click(fn=on_preview_frame_changed, inputs=previewinputs, outputs=[previewimage, mask_top])
309
+ fake_preview.change(fn=on_preview_frame_changed, inputs=previewinputs, outputs=[previewimage, mask_top])
310
+ preview_frame_num.change(fn=on_preview_frame_changed, inputs=previewinputs, outputs=[previewimage, mask_top], show_progress='hidden')
311
+ bt_use_face_from_preview.click(fn=on_use_face_from_selected, show_progress='full', inputs=[bt_destfiles, preview_frame_num], outputs=[dynamic_face_selection, face_selection, target_faces, selected_face_detection])
312
+ set_frame_start.click(fn=on_set_frame, inputs=[set_frame_start, preview_frame_num], outputs=[text_frame_clip])
313
+ set_frame_end.click(fn=on_set_frame, inputs=[set_frame_end, preview_frame_num], outputs=[text_frame_clip])
314
+
315
+
316
+ # Live Cam
317
+ cam_toggle.change(fn=on_cam_toggle, inputs=[cam_toggle])
318
+
319
+ if live_cam_active:
320
+ vcam_toggle.change(fn=on_vcam_toggle, inputs=[vcam_toggle, camera_num], outputs=[cam, fake_cam_image])
321
+ cam.stream(on_stream_swap_cam, inputs=[cam, selected_enhancer, blend_ratio], outputs=[fake_cam_image], preprocess=True, postprocess=True, show_progress="hidden")
322
+
323
+ # Extras
324
+ start_cut_video.click(fn=on_cut_video, inputs=[files_to_process, cut_start_time, cut_end_time], outputs=[extra_files_output])
325
+ # start_join_videos.click(fn=on_join_videos, inputs=[files_to_process], outputs=[extra_files_output])
326
+ start_extract_frames.click(fn=on_extract_frames, inputs=[files_to_process], outputs=[extra_files_output])
327
+ start_create_gif.click(fn=on_create_gif, inputs=[files_to_process], outputs=[extra_files_output])
328
+
329
+ # Settings
330
+ for s in settings_controls:
331
+ s.select(fn=on_settings_changed)
332
+ max_threads.input(fn=lambda a,b='max_threads':on_settings_changed_misc(a,b), inputs=[max_threads])
333
+ memory_limit.input(fn=lambda a,b='memory_limit':on_settings_changed_misc(a,b), inputs=[memory_limit])
334
+ video_quality.input(fn=lambda a,b='video_quality':on_settings_changed_misc(a,b), inputs=[video_quality])
335
+
336
+ button_clean_temp.click(fn=clean_temp, outputs=[bt_srcimg, input_faces, target_faces, bt_destfiles])
337
+ button_apply_settings.click(apply_settings, inputs=[themes, input_server_name, input_server_port, output_template])
338
+ button_apply_restart.click(restart)
339
+
340
+
341
+
342
+ restart_server = False
343
+ try:
344
+ ui.queue().launch(inbrowser=True, server_name=server_name, server_port=server_port, share=roop.globals.CFG.server_share, ssl_verify=ssl_verify, prevent_thread_lock=True, show_error=True)
345
+ except:
346
+ restart_server = True
347
+ run_server = False
348
+ try:
349
+ while restart_server == False:
350
+ time.sleep(1.0)
351
+ except (KeyboardInterrupt, OSError):
352
+ print("Keyboard interruption in main thread... closing server.")
353
+ run_server = False
354
+ ui.close()
355
+
356
+
357
+ def on_mask_top_changed(mask_top):
358
+ global SELECTED_INPUT_FACE_INDEX
359
+
360
+ if len(roop.globals.INPUT_FACES) > SELECTED_INPUT_FACE_INDEX:
361
+ roop.globals.INPUT_FACES[SELECTED_INPUT_FACE_INDEX].mask_top = mask_top
362
+
363
+
364
+ def on_option_changed(evt: gr.SelectData):
365
+ attribname = evt.target.elem_id
366
+ if isinstance(evt.target, gr.Checkbox):
367
+ if hasattr(roop.globals, attribname):
368
+ setattr(roop.globals, attribname, evt.selected)
369
+ return
370
+ elif isinstance(evt.target, gr.Dropdown):
371
+ if hasattr(roop.globals, attribname):
372
+ setattr(roop.globals, attribname, evt.value)
373
+ return
374
+ raise gr.Error(f'Unhandled Setting for {evt.target}')
375
+
376
+
377
+ def on_settings_changed_misc(new_val, attribname):
378
+ if hasattr(roop.globals.CFG, attribname):
379
+ setattr(roop.globals.CFG, attribname, new_val)
380
+ else:
381
+ print("Didn't find attrib!")
382
+
383
+
384
+
385
+ def on_settings_changed(evt: gr.SelectData):
386
+ attribname = evt.target.elem_id
387
+ if isinstance(evt.target, gr.Checkbox):
388
+ if hasattr(roop.globals.CFG, attribname):
389
+ setattr(roop.globals.CFG, attribname, evt.selected)
390
+ return
391
+ elif isinstance(evt.target, gr.Dropdown):
392
+ if hasattr(roop.globals.CFG, attribname):
393
+ setattr(roop.globals.CFG, attribname, evt.value)
394
+ return
395
+
396
+ raise gr.Error(f'Unhandled Setting for {evt.target}')
397
+
398
+
399
+ def on_add_local_folder(folder):
400
+ files = util.get_local_files_from_folder(folder)
401
+ if files is None:
402
+ gr.Warning("Empty folder or folder not found!")
403
+ return files
404
+
405
+
406
+ def on_srcimg_changed(imgsrc, progress=gr.Progress()):
407
+ global RECENT_DIRECTORY_SOURCE, SELECTION_FACES_DATA, IS_INPUT, input_faces, face_selection, input_thumbs, last_image
408
+
409
+ IS_INPUT = True
410
+
411
+ if imgsrc == None or last_image == imgsrc:
412
+ return gr.Column.update(visible=False), None, input_thumbs
413
+
414
+ last_image = imgsrc
415
+
416
+ progress(0, desc="Retrieving faces from image", )
417
+ source_path = imgsrc
418
+ thumbs = []
419
+ if util.is_image(source_path):
420
+ roop.globals.source_path = source_path
421
+ RECENT_DIRECTORY_SOURCE = os.path.dirname(roop.globals.source_path)
422
+ SELECTION_FACES_DATA = extract_face_images(roop.globals.source_path, (False, 0))
423
+ progress(0.5, desc="Retrieving faces from image")
424
+ for f in SELECTION_FACES_DATA:
425
+ image = convert_to_gradio(f[1])
426
+ thumbs.append(image)
427
+
428
+ progress(1.0, desc="Retrieving faces from image")
429
+ if len(thumbs) < 1:
430
+ raise gr.Error('No faces detected!')
431
+
432
+ if len(thumbs) == 1:
433
+ face = SELECTION_FACES_DATA[0][0]
434
+ face.mask_top = 0
435
+ roop.globals.INPUT_FACES.append(face)
436
+ input_thumbs.append(thumbs[0])
437
+ return gr.Column.update(visible=False), None, input_thumbs
438
+
439
+ return gr.Column.update(visible=True), thumbs, gr.Gallery.update(visible=True)
440
+
441
+ def on_select_input_face(evt: gr.SelectData):
442
+ global SELECTED_INPUT_FACE_INDEX
443
+
444
+ SELECTED_INPUT_FACE_INDEX = evt.index
445
+
446
+
447
+ def remove_selected_input_face():
448
+ global input_thumbs, SELECTED_INPUT_FACE_INDEX
449
+
450
+ if len(roop.globals.INPUT_FACES) > SELECTED_INPUT_FACE_INDEX:
451
+ f = roop.globals.INPUT_FACES.pop(SELECTED_INPUT_FACE_INDEX)
452
+ del f
453
+ if len(input_thumbs) > SELECTED_INPUT_FACE_INDEX:
454
+ f = input_thumbs.pop(SELECTED_INPUT_FACE_INDEX)
455
+ del f
456
+
457
+ return input_thumbs
458
+
459
+ def on_select_target_face(evt: gr.SelectData):
460
+ global SELECTED_TARGET_FACE_INDEX
461
+
462
+ SELECTED_TARGET_FACE_INDEX = evt.index
463
+
464
+ def remove_selected_target_face():
465
+ global target_thumbs, SELECTED_TARGET_FACE_INDEX
466
+
467
+ if len(roop.globals.TARGET_FACES) > SELECTED_TARGET_FACE_INDEX:
468
+ f = roop.globals.TARGET_FACES.pop(SELECTED_TARGET_FACE_INDEX)
469
+ del f
470
+ if len(target_thumbs) > SELECTED_TARGET_FACE_INDEX:
471
+ f = target_thumbs.pop(SELECTED_TARGET_FACE_INDEX)
472
+ del f
473
+ return target_thumbs
474
+
475
+
476
+
477
+
478
+
479
+ def on_use_face_from_selected(files, frame_num):
480
+ global IS_INPUT, SELECTION_FACES_DATA
481
+
482
+ IS_INPUT = False
483
+ thumbs = []
484
+
485
+ roop.globals.target_path = files[selected_preview_index].name
486
+ if util.is_image(roop.globals.target_path) and not roop.globals.target_path.lower().endswith(('gif')):
487
+ SELECTION_FACES_DATA = extract_face_images(roop.globals.target_path, (False, 0))
488
+ if len(SELECTION_FACES_DATA) > 0:
489
+ for f in SELECTION_FACES_DATA:
490
+ image = convert_to_gradio(f[1])
491
+ thumbs.append(image)
492
+ else:
493
+ gr.Info('No faces detected!')
494
+ roop.globals.target_path = None
495
+
496
+ elif util.is_video(roop.globals.target_path) or roop.globals.target_path.lower().endswith(('gif')):
497
+ selected_frame = frame_num
498
+ SELECTION_FACES_DATA = extract_face_images(roop.globals.target_path, (True, selected_frame))
499
+ if len(SELECTION_FACES_DATA) > 0:
500
+ for f in SELECTION_FACES_DATA:
501
+ image = convert_to_gradio(f[1])
502
+ thumbs.append(image)
503
+ else:
504
+ gr.Info('No faces detected!')
505
+ roop.globals.target_path = None
506
+
507
+ if len(thumbs) == 1:
508
+ roop.globals.TARGET_FACES.append(SELECTION_FACES_DATA[0][0])
509
+ target_thumbs.append(thumbs[0])
510
+ return gr.Row.update(visible=False), None, target_thumbs, gr.Dropdown.update(value='Selected face')
511
+
512
+ return gr.Row.update(visible=True), thumbs, gr.Gallery.update(visible=True), gr.Dropdown.update(visible=True)
513
+
514
+
515
+
516
+ def on_select_face(evt: gr.SelectData): # SelectData is a subclass of EventData
517
+ global SELECTED_FACE_INDEX
518
+ SELECTED_FACE_INDEX = evt.index
519
+
520
+
521
+ def on_selected_face():
522
+ global IS_INPUT, SELECTED_FACE_INDEX, SELECTION_FACES_DATA, input_thumbs, target_thumbs
523
+
524
+ fd = SELECTION_FACES_DATA[SELECTED_FACE_INDEX]
525
+ image = convert_to_gradio(fd[1])
526
+ if IS_INPUT:
527
+ fd[0].mask_top = 0
528
+ roop.globals.INPUT_FACES.append(fd[0])
529
+ input_thumbs.append(image)
530
+ return input_thumbs, gr.Gallery.update(visible=True), gr.Dropdown.update(visible=True)
531
+ else:
532
+ roop.globals.TARGET_FACES.append(fd[0])
533
+ target_thumbs.append(image)
534
+ return gr.Gallery.update(visible=True), target_thumbs, gr.Dropdown.update(value='Selected face')
535
+
536
+ # bt_faceselect.click(fn=on_selected_face, outputs=[dynamic_face_selection, face_selection, input_faces, target_faces])
537
+
538
+ def on_end_face_selection():
539
+ return gr.Column.update(visible=False), None
540
+
541
+
542
+ def on_preview_frame_changed(frame_num, files, fake_preview, enhancer, detection, face_distance, blend_ratio, use_clip, clip_text):
543
+ global SELECTED_INPUT_FACE_INDEX, is_processing
544
+
545
+ from roop.core import live_swap
546
+
547
+ mask_top = 0
548
+ if len(roop.globals.INPUT_FACES) > SELECTED_INPUT_FACE_INDEX:
549
+ if hasattr(roop.globals.INPUT_FACES[SELECTED_INPUT_FACE_INDEX], 'mask_top'):
550
+ mask_top = roop.globals.INPUT_FACES[SELECTED_INPUT_FACE_INDEX].mask_top
551
+ else:
552
+ roop.globals.INPUT_FACES[SELECTED_INPUT_FACE_INDEX].mask_top = mask_top
553
+
554
+ if is_processing or files is None or selected_preview_index >= len(files) or frame_num is None:
555
+ return None, mask_top
556
+
557
+ filename = files[selected_preview_index].name
558
+ if util.is_video(filename) or filename.lower().endswith('gif'):
559
+ current_frame = get_video_frame(filename, frame_num)
560
+ else:
561
+ current_frame = get_image_frame(filename)
562
+ if current_frame is None:
563
+ return None, mask_top
564
+
565
+ time.sleep(0.2)
566
+
567
+ if not fake_preview or len(roop.globals.INPUT_FACES) < 1:
568
+ return convert_to_gradio(current_frame), mask_top
569
+
570
+ roop.globals.face_swap_mode = translate_swap_mode(detection)
571
+ roop.globals.selected_enhancer = enhancer
572
+ roop.globals.distance_threshold = face_distance
573
+ roop.globals.blend_ratio = blend_ratio
574
+
575
+ if use_clip and clip_text is None or len(clip_text) < 1:
576
+ use_clip = False
577
+
578
+ roop.globals.execution_threads = roop.globals.CFG.max_threads
579
+ current_frame = live_swap(current_frame, roop.globals.face_swap_mode, use_clip, clip_text, SELECTED_INPUT_FACE_INDEX)
580
+ if current_frame is None:
581
+ return None, mask_top
582
+ return convert_to_gradio(current_frame), mask_top
583
+
584
+
585
+ def gen_processing_text(start, end):
586
+ return f'Processing frame range [{start} - {end}]'
587
+
588
+ def on_set_frame(sender:str, frame_num):
589
+ global selected_preview_index, list_files_process
590
+
591
+ idx = selected_preview_index
592
+ if list_files_process[idx].endframe == 0:
593
+ return gen_processing_text(0,0)
594
+
595
+ start = list_files_process[idx].startframe
596
+ end = list_files_process[idx].endframe
597
+ if sender.lower().endswith('start'):
598
+ list_files_process[idx].startframe = min(frame_num, end)
599
+ else:
600
+ list_files_process[idx].endframe = max(frame_num, start)
601
+
602
+ return gen_processing_text(list_files_process[idx].startframe,list_files_process[idx].endframe)
603
+
604
+
605
+
606
+ def on_preview_mask(frame_num, files, clip_text):
607
+ from roop.core import preview_mask
608
+ global is_processing
609
+
610
+ if is_processing:
611
+ return None
612
+
613
+ filename = files[selected_preview_index].name
614
+ if util.is_video(filename) or filename.lower().endswith('gif'):
615
+ current_frame = get_video_frame(filename, frame_num)
616
+ else:
617
+ current_frame = get_image_frame(filename)
618
+ if current_frame is None:
619
+ return None
620
+
621
+ current_frame = preview_mask(current_frame, clip_text)
622
+ return convert_to_gradio(current_frame)
623
+
624
+
625
+ def on_clear_input_faces():
626
+ global input_thumbs
627
+
628
+ input_thumbs.clear()
629
+ roop.globals.INPUT_FACES.clear()
630
+ return input_thumbs
631
+
632
+ def on_clear_destfiles():
633
+ global target_thumbs
634
+
635
+ roop.globals.TARGET_FACES.clear()
636
+ target_thumbs.clear()
637
+ return target_thumbs
638
+
639
+
640
+
641
+ def translate_swap_mode(dropdown_text):
642
+ if dropdown_text == "Selected face":
643
+ return "selected"
644
+ elif dropdown_text == "First found":
645
+ return "first"
646
+ elif dropdown_text == "All female":
647
+ return "all_female"
648
+ elif dropdown_text == "All male":
649
+ return "all_male"
650
+
651
+ return "all"
652
+
653
+
654
+
655
+ def start_swap( enhancer, detection, keep_frames, skip_audio, face_distance, blend_ratio,
656
+ use_clip, clip_text, processing_method, progress=gr.Progress(track_tqdm=False)):
657
+ from roop.core import batch_process
658
+ global is_processing, list_files_process
659
+
660
+ if list_files_process is None or len(list_files_process) <= 0:
661
+ return gr.Button.update(variant="primary"), None
662
+
663
+ if roop.globals.CFG.clear_output:
664
+ shutil.rmtree(roop.globals.output_path)
665
+
666
+
667
+ prepare_environment()
668
+
669
+ roop.globals.selected_enhancer = enhancer
670
+ roop.globals.target_path = None
671
+ roop.globals.distance_threshold = face_distance
672
+ roop.globals.blend_ratio = blend_ratio
673
+ roop.globals.keep_frames = keep_frames
674
+ roop.globals.skip_audio = skip_audio
675
+ roop.globals.face_swap_mode = translate_swap_mode(detection)
676
+ if use_clip and clip_text is None or len(clip_text) < 1:
677
+ use_clip = False
678
+
679
+ if roop.globals.face_swap_mode == 'selected':
680
+ if len(roop.globals.TARGET_FACES) < 1:
681
+ gr.Error('No Target Face selected!')
682
+ return gr.Button.update(variant="primary"), None
683
+
684
+ is_processing = True
685
+ yield gr.Button.update(variant="secondary"), None
686
+ roop.globals.execution_threads = roop.globals.CFG.max_threads
687
+ roop.globals.video_encoder = roop.globals.CFG.output_video_codec
688
+ roop.globals.video_quality = roop.globals.CFG.video_quality
689
+ roop.globals.max_memory = roop.globals.CFG.memory_limit if roop.globals.CFG.memory_limit > 0 else None
690
+
691
+ batch_process(list_files_process, use_clip, clip_text, processing_method == "In-Memory", progress)
692
+ is_processing = False
693
+ outdir = pathlib.Path(roop.globals.output_path)
694
+ outfiles = [item for item in outdir.rglob("*") if item.is_file()]
695
+ if len(outfiles) > 0:
696
+ yield gr.Button.update(variant="primary"),gr.Files.update(value=outfiles)
697
+ else:
698
+ yield gr.Button.update(variant="primary"),None
699
+
700
+
701
+ def stop_swap():
702
+ roop.globals.processing = False
703
+ gr.Info('Aborting processing - please wait for the remaining threads to be stopped')
704
+
705
+
706
+ def on_fps_changed(fps):
707
+ global selected_preview_index, list_files_process
708
+
709
+ if len(list_files_process) < 1 or list_files_process[selected_preview_index].endframe < 1:
710
+ return
711
+ list_files_process[selected_preview_index].fps = fps
712
+
713
+
714
+ def on_destfiles_changed(destfiles):
715
+ global selected_preview_index, list_files_process
716
+
717
+ if destfiles is None or len(destfiles) < 1:
718
+ list_files_process.clear()
719
+ return gr.Slider.update(value=0, maximum=0), ''
720
+
721
+ for f in destfiles:
722
+ list_files_process.append(ProcessEntry(f.name, 0,0, 0))
723
+
724
+ selected_preview_index = 0
725
+ idx = selected_preview_index
726
+
727
+ filename = list_files_process[idx].filename
728
+
729
+ if util.is_video(filename) or filename.lower().endswith('gif'):
730
+ total_frames = get_video_frame_total(filename)
731
+ else:
732
+ total_frames = 0
733
+ list_files_process[idx].endframe = total_frames
734
+ if total_frames > 0:
735
+ return gr.Slider.update(value=0, maximum=total_frames), gen_processing_text(list_files_process[idx].startframe,list_files_process[idx].endframe)
736
+ return gr.Slider.update(value=0, maximum=total_frames), ''
737
+
738
+
739
+
740
+
741
+ def on_destfiles_selected(evt: gr.SelectData):
742
+ global selected_preview_index, list_files_process
743
+
744
+ if evt is not None:
745
+ selected_preview_index = evt.index
746
+ idx = selected_preview_index
747
+ filename = list_files_process[idx].filename
748
+ fps = list_files_process[idx].fps
749
+ if util.is_video(filename) or filename.lower().endswith('gif'):
750
+ total_frames = get_video_frame_total(filename)
751
+ if list_files_process[idx].endframe == 0:
752
+ list_files_process[idx].endframe = total_frames
753
+ else:
754
+ total_frames = 0
755
+
756
+ if total_frames > 0:
757
+ return gr.Slider.update(value=list_files_process[idx].startframe, maximum=total_frames), gen_processing_text(list_files_process[idx].startframe,list_files_process[idx].endframe), fps
758
+ return gr.Slider.update(value=0, maximum=total_frames), gen_processing_text(0,0), fps
759
+
760
+
761
+
762
+
763
+ def on_resultfiles_selected(evt: gr.SelectData, files):
764
+ selected_index = evt.index
765
+ filename = files[selected_index].name
766
+ if util.is_video(filename) or filename.lower().endswith('gif'):
767
+ current_frame = get_video_frame(filename, 0)
768
+ else:
769
+ current_frame = get_image_frame(filename)
770
+ return convert_to_gradio(current_frame)
771
+
772
+
773
+ def on_resultfiles_finished(files):
774
+ selected_index = 0
775
+ if files is None or len(files) < 1:
776
+ return None
777
+
778
+ filename = files[selected_index].name
779
+ if util.is_video(filename) or filename.lower().endswith('gif'):
780
+ current_frame = get_video_frame(filename, 0)
781
+ else:
782
+ current_frame = get_image_frame(filename)
783
+ return convert_to_gradio(current_frame)
784
+
785
+
786
+
787
+
788
+ def on_cam_toggle(state):
789
+ from threading import Thread
790
+ from roop.virtualcam import virtualcamera, cam_active
791
+ global live_cam_active, restart_server, camthread
792
+
793
+ live_cam_active = state
794
+ gr.Warning('Server will be restarted for this change!')
795
+ restart_server = True
796
+
797
+ def on_vcam_toggle(state, num):
798
+ from roop.virtualcam import stop_virtual_cam, start_virtual_cam
799
+
800
+ if state:
801
+ start_virtual_cam(num)
802
+ return gr.Webcam.update(interactive=False), None
803
+ else:
804
+ stop_virtual_cam()
805
+ return gr.Webcam.update(interactive=True, mirror_webcam=True), None
806
+
807
+
808
+
809
+ def on_stream_swap_cam(camimage, enhancer, blend_ratio):
810
+ from roop.core import live_swap
811
+ global current_cam_image, cam_counter, cam_swapping, fake_cam_image, SELECTED_INPUT_FACE_INDEX
812
+
813
+ roop.globals.selected_enhancer = enhancer
814
+ roop.globals.blend_ratio = blend_ratio
815
+
816
+ if not cam_swapping:
817
+ cam_swapping = True
818
+ if len(roop.globals.INPUT_FACES) > 0:
819
+ current_cam_image = live_swap(camimage, "all", False, None, SELECTED_INPUT_FACE_INDEX)
820
+ else:
821
+ current_cam_image = camimage
822
+ cam_swapping = False
823
+ return current_cam_image
824
+
825
+
826
+ def on_cut_video(files, cut_start_frame, cut_end_frame):
827
+ if files is None:
828
+ return None
829
+
830
+ resultfiles = []
831
+ for tf in files:
832
+ f = tf.name
833
+ destfile = util.get_destfilename_from_path(f, roop.globals.output_path, '_cut')
834
+ util.cut_video(f, destfile, cut_start_frame, cut_end_frame)
835
+ if os.path.isfile(destfile):
836
+ resultfiles.append(destfile)
837
+ else:
838
+ gr.Error('Cutting video failed!')
839
+ return resultfiles
840
+
841
+ def on_join_videos(files):
842
+ if files is None:
843
+ return None
844
+
845
+ filenames = []
846
+ for f in files:
847
+ filenames.append(f.name)
848
+ destfile = util.get_destfilename_from_path(filenames[0], roop.globals.output_path, '_join')
849
+ util.join_videos(filenames, destfile)
850
+ resultfiles = []
851
+ if os.path.isfile(destfile):
852
+ resultfiles.append(destfile)
853
+ else:
854
+ gr.Error('Joining videos failed!')
855
+ return resultfiles
856
+
857
+
858
+
859
+
860
+ def on_extract_frames(files):
861
+ if files is None:
862
+ return None
863
+
864
+ resultfiles = []
865
+ for tf in files:
866
+ f = tf.name
867
+ resfolder = util.extract_frames(f)
868
+ for file in os.listdir(resfolder):
869
+ outfile = os.path.join(resfolder, file)
870
+ if os.path.isfile(outfile):
871
+ resultfiles.append(outfile)
872
+ return resultfiles
873
+
874
+
875
+ def on_create_gif(files):
876
+ if files is None:
877
+ return None
878
+
879
+ for tf in files:
880
+ f = tf.name
881
+ gifname = util.get_destfilename_from_path(f, './output', '.gif')
882
+ util.create_gif_from_video(f, gifname)
883
+ return gifname
884
+
885
+
886
+
887
+
888
+
889
+ def clean_temp():
890
+ global input_thumbs, target_thumbs
891
+
892
+ shutil.rmtree(os.environ["TEMP"])
893
+ prepare_environment()
894
+
895
+ input_thumbs.clear()
896
+ roop.globals.INPUT_FACES.clear()
897
+ roop.globals.TARGET_FACES.clear()
898
+ target_thumbs = []
899
+ gr.Info('Temp Files removed')
900
+ return None,None,None,None
901
+
902
+
903
+ def apply_settings(themes, input_server_name, input_server_port, output_template):
904
+ roop.globals.CFG.selected_theme = themes
905
+ roop.globals.CFG.server_name = input_server_name
906
+ roop.globals.CFG.server_port = input_server_port
907
+ roop.globals.CFG.output_template = output_template
908
+ roop.globals.CFG.save()
909
+ show_msg('Settings saved')
910
+
911
+
912
+ def restart():
913
+ global restart_server
914
+ restart_server = True
915
+
916
+
917
+ def show_msg(msg: str):
918
+ gr.Info(msg)
919
+
920
+
921
+
922
+ # Gradio wants Images in RGB
923
+ def convert_to_gradio(image):
924
+ if image is None:
925
+ return None
926
+ return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
roop/utilities.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import mimetypes
3
+ import os
4
+ import platform
5
+ import shutil
6
+ import ssl
7
+ import subprocess
8
+ import sys
9
+ import urllib
10
+ import torch
11
+ import gradio
12
+ import tempfile
13
+ import cv2
14
+
15
+ from pathlib import Path
16
+ from typing import List, Any
17
+ from tqdm import tqdm
18
+ from scipy.spatial import distance
19
+
20
+ import roop.template_parser as template_parser
21
+
22
+ import roop.globals
23
+
24
+ TEMP_FILE = 'temp.mp4'
25
+ TEMP_DIRECTORY = 'temp'
26
+
27
+ # monkey patch ssl for mac
28
+ if platform.system().lower() == 'darwin':
29
+ ssl._create_default_https_context = ssl._create_unverified_context
30
+
31
+
32
+ def run_ffmpeg(args: List[str]) -> bool:
33
+ commands = ['ffmpeg', '-hide_banner', '-hwaccel', 'auto', '-y', '-loglevel', roop.globals.log_level]
34
+ commands.extend(args)
35
+ print (" ".join(commands))
36
+ try:
37
+ subprocess.check_output(commands, stderr=subprocess.STDOUT)
38
+ return True
39
+ except Exception:
40
+ pass
41
+ return False
42
+
43
+
44
+ # https://github.com/facefusion/facefusion/blob/master/facefusion
45
+ def detect_fps(target_path : str) -> float:
46
+ fps = 24.0
47
+ cap = cv2.VideoCapture(target_path)
48
+ if cap.isOpened():
49
+ fps = cap.get(cv2.CAP_PROP_FPS)
50
+ cap.release()
51
+ return fps
52
+
53
+
54
+ # commands = [ 'ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=r_frame_rate', '-of', 'json', target_path ]
55
+ # output = subprocess.check_output(commands).decode().strip()
56
+ # try:
57
+ # entries = json.loads(output)
58
+ # for stream in entries.get('streams'):
59
+ # numerator, denominator = map(int, stream.get('r_frame_rate').split('/'))
60
+ # return numerator / denominator
61
+ # return None
62
+ # except (ValueError, ZeroDivisionError):
63
+ # return 24
64
+
65
+
66
+ def cut_video(original_video: str, cut_video: str, start_frame: int, end_frame: int):
67
+ fps = detect_fps(original_video)
68
+ start_time = start_frame / fps
69
+ num_frames = end_frame - start_frame
70
+
71
+ run_ffmpeg(['-ss', str(start_time), '-i', original_video, '-c:v', roop.globals.video_encoder, '-c:a', 'aac', '-frames:v', str(num_frames), cut_video])
72
+
73
+ def join_videos(videos: List[str], dest_filename: str):
74
+ inputs = []
75
+ filter = ''
76
+ for i,v in enumerate(videos):
77
+ inputs.append('-i')
78
+ inputs.append(v)
79
+ filter += f'[{i}:v:0][{i}:a:0]'
80
+ run_ffmpeg([" ".join(inputs), '-filter_complex', f'"{filter}concat=n={len(videos)}:v=1:a=1[outv][outa]"', '-map', '"[outv]"', '-map', '"[outa]"', dest_filename])
81
+
82
+ # def extract_frames(target_path: str) -> None:
83
+ # create_temp(target_path)
84
+ # temp_directory_path = get_temp_directory_path(target_path)
85
+ # run_ffmpeg(['-i', target_path, '-q:v', '1', '-pix_fmt', 'rgb24', os.path.join(temp_directory_path, f'%04d.{roop.globals.CFG.output_image_format}')])
86
+ # return temp_directory_path
87
+
88
+
89
+ def extract_frames(target_path : str, trim_frame_start, trim_frame_end, fps : float) -> bool:
90
+ create_temp(target_path)
91
+ temp_directory_path = get_temp_directory_path(target_path)
92
+ commands = ['-i', target_path, '-q:v', '1', '-pix_fmt', 'rgb24', ]
93
+ if trim_frame_start is not None and trim_frame_end is not None:
94
+ commands.extend([ '-vf', 'trim=start_frame=' + str(trim_frame_start) + ':end_frame=' + str(trim_frame_end) + ',fps=' + str(fps) ])
95
+ # elif trim_frame_start is not None:
96
+ # commands.extend([ '-vf', 'trim=start_frame=' + str(trim_frame_start) + ',fps=' + str(fps) ])
97
+ # elif trim_frame_end is not None:
98
+ # # commands.extend([ '-vf', 'trim=end_frame=' + str(trim_frame_end) + ',fps=' + str(fps) ])
99
+ # else:
100
+ # commands.extend([ '-vf', 'fps=' + str(fps) ])
101
+ commands.extend([os.path.join(temp_directory_path, '%04d.' + roop.globals.CFG.output_image_format)])
102
+ return run_ffmpeg(commands)
103
+
104
+ def create_video(target_path: str, dest_filename: str, fps: float = 24.0) -> None:
105
+ temp_directory_path = get_temp_directory_path(target_path)
106
+ run_ffmpeg(['-r', str(fps), '-i', os.path.join(temp_directory_path, f'%04d.{roop.globals.CFG.output_image_format}'), '-c:v', roop.globals.video_encoder, '-crf', str(roop.globals.video_quality), '-pix_fmt', 'yuv420p', '-vf', 'colorspace=bt709:iall=bt601-6-625:fast=1', '-y', dest_filename])
107
+ return dest_filename
108
+
109
+
110
+ def create_gif_from_video(video_path: str, gif_path):
111
+ from roop.capturer import get_video_frame
112
+
113
+ fps = detect_fps(video_path)
114
+ frame = get_video_frame(video_path)
115
+
116
+ run_ffmpeg(['-i', video_path, '-vf', f'fps={fps},scale={frame.shape[0]}:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse', '-loop', '0', gif_path])
117
+
118
+
119
+ def restore_audio(intermediate_video: str, original_video: str, trim_frame_start, trim_frame_end, final_video : str) -> None:
120
+ fps = detect_fps(original_video)
121
+ commands = [ '-i', intermediate_video, '-i', original_video ]
122
+ if trim_frame_start is None and trim_frame_end is None:
123
+ commands.extend([ '-c:a', 'copy' ])
124
+ else:
125
+ if trim_frame_start is not None:
126
+ start_time = trim_frame_start / fps
127
+ commands.extend([ '-ss', format(start_time, ".2f")])
128
+ else:
129
+ commands.extend([ '-ss', '0' ])
130
+ if trim_frame_end is not None:
131
+ end_time = trim_frame_end / fps
132
+ commands.extend([ '-to', format(end_time, ".2f")])
133
+ commands.extend([ '-c:a', 'aac' ])
134
+ commands.extend([ '-map', '0:v:0', '-map', '1:a:0', '-y', final_video ])
135
+ run_ffmpeg(commands)
136
+
137
+
138
+
139
+ def get_temp_frame_paths(target_path: str) -> List[str]:
140
+ temp_directory_path = get_temp_directory_path(target_path)
141
+ return glob.glob((os.path.join(glob.escape(temp_directory_path), f'*.{roop.globals.CFG.output_image_format}')))
142
+
143
+
144
+ def get_temp_directory_path(target_path: str) -> str:
145
+ target_name, _ = os.path.splitext(os.path.basename(target_path))
146
+ target_directory_path = os.path.dirname(target_path)
147
+ return os.path.join(target_directory_path, TEMP_DIRECTORY, target_name)
148
+
149
+
150
+ def get_temp_output_path(target_path: str) -> str:
151
+ temp_directory_path = get_temp_directory_path(target_path)
152
+ return os.path.join(temp_directory_path, TEMP_FILE)
153
+
154
+
155
+ def normalize_output_path(source_path: str, target_path: str, output_path: str) -> Any:
156
+ if source_path and target_path:
157
+ source_name, _ = os.path.splitext(os.path.basename(source_path))
158
+ target_name, target_extension = os.path.splitext(os.path.basename(target_path))
159
+ if os.path.isdir(output_path):
160
+ return os.path.join(output_path, source_name + '-' + target_name + target_extension)
161
+ return output_path
162
+
163
+
164
+ def get_destfilename_from_path(srcfilepath: str, destfilepath: str, extension: str) -> str:
165
+ fn, ext = os.path.splitext(os.path.basename(srcfilepath))
166
+ if '.' in extension:
167
+ return os.path.join(destfilepath, f'{fn}{extension}')
168
+ return os.path.join(destfilepath, f'{fn}{extension}{ext}')
169
+
170
+ def replace_template(file_path: str, index: int = 0):
171
+ fn, ext = os.path.splitext(os.path.basename(file_path))
172
+
173
+ # Remove the "__temp" placeholder that was used as a temporary filename
174
+ fn = fn.replace('__temp', '')
175
+
176
+ template = roop.globals.CFG.output_template
177
+ replaced_filename = template_parser.parse(template, {
178
+ 'index': str(index),
179
+ 'file': fn
180
+ })
181
+
182
+ return os.path.join(roop.globals.output_path, f'{replaced_filename}{ext}')
183
+
184
+
185
+
186
+ def create_temp(target_path: str) -> None:
187
+ temp_directory_path = get_temp_directory_path(target_path)
188
+ Path(temp_directory_path).mkdir(parents=True, exist_ok=True)
189
+
190
+
191
+ def move_temp(target_path: str, output_path: str) -> None:
192
+ temp_output_path = get_temp_output_path(target_path)
193
+ if os.path.isfile(temp_output_path):
194
+ if os.path.isfile(output_path):
195
+ os.remove(output_path)
196
+ shutil.move(temp_output_path, output_path)
197
+
198
+
199
+ def clean_temp(target_path: str) -> None:
200
+ temp_directory_path = get_temp_directory_path(target_path)
201
+ parent_directory_path = os.path.dirname(temp_directory_path)
202
+ if not roop.globals.keep_frames and os.path.isdir(temp_directory_path):
203
+ shutil.rmtree(temp_directory_path)
204
+ if os.path.exists(parent_directory_path) and not os.listdir(parent_directory_path):
205
+ os.rmdir(parent_directory_path)
206
+
207
+ def delete_temp_frames(filename: str) -> None:
208
+ dir = os.path.dirname(os.path.dirname(filename))
209
+ shutil.rmtree(dir)
210
+
211
+
212
+
213
+
214
+ def has_image_extension(image_path: str) -> bool:
215
+ return image_path.lower().endswith(('png', 'jpg', 'jpeg', 'webp'))
216
+
217
+ def has_extension(filepath: str, extensions: List[str]) -> bool:
218
+ return filepath.lower().endswith(tuple(extensions))
219
+
220
+
221
+ def is_image(image_path: str) -> bool:
222
+ if image_path and os.path.isfile(image_path):
223
+ mimetype, _ = mimetypes.guess_type(image_path)
224
+ return bool(mimetype and mimetype.startswith('image/'))
225
+ return False
226
+
227
+
228
+ def is_video(video_path: str) -> bool:
229
+ if video_path and os.path.isfile(video_path):
230
+ mimetype, _ = mimetypes.guess_type(video_path)
231
+ return bool(mimetype and mimetype.startswith('video/'))
232
+ return False
233
+
234
+
235
+ def conditional_download(download_directory_path: str, urls: List[str]) -> None:
236
+ if not os.path.exists(download_directory_path):
237
+ os.makedirs(download_directory_path)
238
+ for url in urls:
239
+ download_file_path = os.path.join(download_directory_path, os.path.basename(url))
240
+ if not os.path.exists(download_file_path):
241
+ request = urllib.request.urlopen(url) # type: ignore[attr-defined]
242
+ total = int(request.headers.get('Content-Length', 0))
243
+ with tqdm(total=total, desc=f'Downloading {url}', unit='B', unit_scale=True, unit_divisor=1024) as progress:
244
+ urllib.request.urlretrieve(url, download_file_path, reporthook=lambda count, block_size, total_size: progress.update(block_size)) # type: ignore[attr-defined]
245
+
246
+
247
+ def resolve_relative_path(path: str) -> str:
248
+ return os.path.abspath(os.path.join(os.path.dirname(__file__), path))
249
+
250
+ def get_device() -> str:
251
+ if len(roop.globals.execution_providers) < 1:
252
+ roop.globals.execution_providers = ['CPUExecutionProvider']
253
+
254
+ prov = roop.globals.execution_providers[0]
255
+ if 'CUDAExecutionProvider' == prov:
256
+ return 'cuda'
257
+ if 'CoreMLExecutionProvider' == prov:
258
+ return 'mps'
259
+ return 'cpu'
260
+
261
+
262
+ def str_to_class(module_name, class_name):
263
+ from importlib import import_module
264
+ try:
265
+ module_ = import_module(module_name)
266
+ try:
267
+ class_ = getattr(module_, class_name)()
268
+ except AttributeError:
269
+ print('Class does not exist')
270
+ except ImportError:
271
+ print('Module does not exist')
272
+ return class_ or None
273
+
274
+
275
+ # Taken from https://stackoverflow.com/a/68842705
276
+ def get_platform():
277
+ if sys.platform == 'linux':
278
+ try:
279
+ proc_version = open('/proc/version').read()
280
+ if 'Microsoft' in proc_version:
281
+ return 'wsl'
282
+ except:
283
+ pass
284
+ return sys.platform
285
+
286
+ def open_with_default_app(filename):
287
+ if filename == None:
288
+ return
289
+ platform = get_platform()
290
+ if platform == 'darwin':
291
+ subprocess.call(('open', filename))
292
+ elif platform in ['win64', 'win32']:
293
+ os.startfile(filename.replace('/','\\'))
294
+ elif platform == 'wsl':
295
+ subprocess.call('cmd.exe /C start'.split() + [filename])
296
+ else: # linux variants
297
+ subprocess.call('xdg-open', filename)
298
+
299
+ def prepare_for_batch(target_files):
300
+ print("Preparing temp files")
301
+ tempfolder = os.path.join(tempfile.gettempdir(), "rooptmp")
302
+ if os.path.exists(tempfolder):
303
+ shutil.rmtree(tempfolder)
304
+ Path(tempfolder).mkdir(parents=True, exist_ok=True)
305
+ for f in target_files:
306
+ newname = os.path.basename(f.name)
307
+ shutil.move(f.name, os.path.join(tempfolder, newname))
308
+ return tempfolder
309
+
310
+
311
+ def open_folder(path:str):
312
+ platform = get_platform()
313
+ try:
314
+ if platform == 'darwin':
315
+ subprocess.call(('open', path))
316
+ elif platform in ['win64', 'win32']:
317
+ open_with_default_app(path)
318
+ elif platform == 'wsl':
319
+ subprocess.call('cmd.exe /C start'.split() + [path])
320
+ else: # linux variants
321
+ subprocess.call('xdg-open', path)
322
+ except Exception as e:
323
+ print(e)
324
+ pass
325
+ #import webbrowser
326
+ #webbrowser.open(url)
327
+
328
+
329
+
330
+ def create_version_html():
331
+ python_version = ".".join([str(x) for x in sys.version_info[0:3]])
332
+ versions_html = f"""
333
+ python: <span title="{sys.version}">{python_version}</span>
334
+
335
+ torch: {getattr(torch, '__long_version__',torch.__version__)}
336
+
337
+ gradio: {gradio.__version__}
338
+ """
339
+ return versions_html
340
+
341
+
342
+ def compute_cosine_distance(emb1, emb2):
343
+ return distance.cosine(emb1, emb2)
roop/virtualcam.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import roop.globals
3
+ import pyvirtualcam
4
+ import threading
5
+ import time
6
+
7
+
8
+ cam_active = False
9
+ cam_thread = None
10
+ vcam = None
11
+
12
+ def virtualcamera(cam_num):
13
+ from roop.core import live_swap
14
+
15
+ time.sleep(2)
16
+ print('Starting capture')
17
+ cap = cv2.VideoCapture(cam_num, cv2.CAP_DSHOW)
18
+ if not cap.isOpened():
19
+ print("Cannot open camera")
20
+ cap.release()
21
+ del cap
22
+ return
23
+
24
+ pref_width = 1280
25
+ pref_height = 720
26
+ pref_fps_in = 10
27
+ cap.set(cv2.CAP_PROP_FRAME_WIDTH, pref_width)
28
+ cap.set(cv2.CAP_PROP_FRAME_HEIGHT, pref_height)
29
+ cap.set(cv2.CAP_PROP_FPS, pref_fps_in)
30
+ print('Starting VCAM')
31
+ cam_active = True
32
+
33
+ # native format UYVY
34
+
35
+ with pyvirtualcam.Camera(width=pref_width, height=pref_height, fps=10, fmt=pyvirtualcam.PixelFormat.BGR, print_fps=True) as cam:
36
+
37
+ print(f'Using virtual camera: {cam.device}')
38
+ print(f'Using {cam.native_fmt}')
39
+
40
+ # RGB
41
+
42
+ while cam_active:
43
+ ret, frame = cap.read()
44
+ if not ret:
45
+ break
46
+
47
+ if len(roop.globals.INPUT_FACES) > 0:
48
+ frame = live_swap(frame, "all", False, None)
49
+ cam.send(frame)
50
+ else:
51
+ cam.send(frame)
52
+ cam.sleep_until_next_frame()
53
+
54
+ cap.release()
55
+ print('End cam')
56
+
57
+
58
+
59
+ def start_virtual_cam(cam_number):
60
+ global cam_thread, cam_active
61
+
62
+ if not cam_active:
63
+ cam_thread = threading.Thread(target=virtualcamera, args=[cam_number])
64
+ cam_thread.start()
65
+
66
+
67
+
68
+ def stop_virtual_cam():
69
+ global cam_active
70
+
71
+ cam_active = False
72
+
73
+
run.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ from roop import core
4
+
5
+ if __name__ == '__main__':
6
+ core.run()
settings.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import yaml
2
+
3
+ class Settings:
4
+ def __init__(self, config_file):
5
+ self.config_file = config_file
6
+ self.load()
7
+
8
+ def default_get(_, data, name, default):
9
+ value = default
10
+ try:
11
+ value = data.get(name, default)
12
+ except:
13
+ pass
14
+ return value
15
+
16
+
17
+ def load(self):
18
+ try:
19
+ with open(self.config_file, 'r') as f:
20
+ data = yaml.load(f, Loader=yaml.FullLoader)
21
+ except:
22
+ data = None
23
+
24
+ self.selected_theme = self.default_get(data, 'selected_theme', "Default")
25
+ self.server_name = self.default_get(data, 'server_name', "")
26
+ self.server_port = self.default_get(data, 'server_port', 0)
27
+ self.server_share = self.default_get(data, 'server_share', False)
28
+ self.output_image_format = self.default_get(data, 'output_image_format', 'png')
29
+ self.output_video_format = self.default_get(data, 'output_video_format', 'mp4')
30
+ self.output_video_codec = self.default_get(data, 'output_video_codec', 'libx264')
31
+ self.video_quality = self.default_get(data, 'video_quality', 14)
32
+ self.clear_output = self.default_get(data, 'clear_output', True)
33
+ self.live_cam_start_active = self.default_get(data, 'live_cam_start_active', False)
34
+ self.max_threads = self.default_get(data, 'max_threads', 2)
35
+ self.memory_limit = self.default_get(data, 'memory_limit', 0)
36
+ self.provider = self.default_get(data, 'provider', 'cuda')
37
+ self.force_cpu = self.default_get(data, 'force_cpu', False)
38
+ self.output_template = self.default_get(data, 'output_template', '{file}_{time}')
39
+
40
+
41
+
42
+
43
+ def save(self):
44
+ data = {
45
+ 'selected_theme': self.selected_theme,
46
+ 'server_name': self.server_name,
47
+ 'server_port': self.server_port,
48
+ 'server_share': self.server_share,
49
+ 'output_image_format' : self.output_image_format,
50
+ 'output_video_format' : self.output_video_format,
51
+ 'output_video_codec' : self.output_video_codec,
52
+ 'video_quality' : self.video_quality,
53
+ 'clear_output' : self.clear_output,
54
+ 'live_cam_start_active' : self.live_cam_start_active,
55
+ 'max_threads' : self.max_threads,
56
+ 'memory_limit' : self.memory_limit,
57
+ 'frame_buffer_size' : self.frame_buffer_size,
58
+ 'provider' : self.provider,
59
+ 'force_cpu' : self.force_cpu,
60
+ 'output_template' : self.output_template
61
+ }
62
+ with open(self.config_file, 'w') as f:
63
+ yaml.dump(data, f)
64
+
65
+
66
+