fangbin commited on
Commit
deb4e3b
·
1 Parent(s): f38da43

no message

Browse files
.gitattributes 2 ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
.gitignore ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ *.pyc
5
+ .idea
6
+ .todo
7
+ *.log
8
+ *.backup
9
+ tf_env/
10
+ *.png
11
+ *.mp4
12
+ *.mkv
13
+
14
+ .tmp/
15
+ temp/
16
+ .venv/
17
+ venv/
18
+ env/
19
+ workflow/
20
+ gfpgan/
21
+ models/inswapper_128.onnx
22
+ models/GFPGANv1.4.pth
23
+ *.onnx
24
+ models/DMDNet.pth
25
+ faceswap/
26
+ .vscode/
CONTRIBUTING.md ADDED
@@ -0,0 +1 @@
 
 
1
+ Please always push on the experimental to ensure we don't mess with the main branch. All the test will be done on the experimental and will be pushed to the main branch after few days of testing.
Dockerfile CHANGED
@@ -1,16 +1,28 @@
1
- # Read the doc: https://huggingface.co/docs/hub/spaces-sdks-docker
2
- # you will also find guides on how best to write your Dockerfile
3
 
4
- FROM python:3.9
 
5
 
6
- RUN useradd -m -u 1000 user
7
- USER user
8
- ENV PATH="/home/user/.local/bin:$PATH"
 
 
9
 
10
- WORKDIR /app
 
 
 
 
 
 
 
 
 
11
 
12
- COPY --chown=user ./requirements.txt requirements.txt
13
- RUN pip install --no-cache-dir --upgrade -r requirements.txt
14
 
15
- COPY --chown=user . /app
16
- CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
 
1
+ # 使用官方 Python 镜像作为基础镜像
2
+ FROM python:3.9-slim
3
 
4
+ # 设置工作目录
5
+ WORKDIR /app
6
 
7
+ # 安装系统依赖
8
+ RUN apt-get update && apt-get install -y \
9
+ libgl1-mesa-glx \
10
+ libglib2.0-0 \
11
+ && rm -rf /var/lib/apt/lists/*
12
 
13
+ # 复制项目文件到容器中
14
+ COPY . /app
15
+
16
+ # 安装 Python 依赖
17
+ RUN pip install --no-cache-dir -r requirements.txt
18
+
19
+ # 设置环境变量
20
+ ENV PYTHONUNBUFFERED=1
21
+ ENV LANG=C.UTF-8
22
+ ENV LC_ALL=C.UTF-8
23
 
24
+ # 暴露端口(如果您的应用需要的话)
25
+ # EXPOSE 8000
26
 
27
+ # 运行应用
28
+ CMD ["python", "main.py"]
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 2.md ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ ![demo-gif](demo.gif)
3
+ ![demo-gif](avgpcperformancedemo.gif)
4
+
5
+ ## Deep Live Cam
6
+
7
+ Real-time face swap and video deepfake with a single click and only a single image.
8
+
9
+ ## Disclaimer
10
+
11
+ This software is intended as a productive contribution to the AI-generated media industry. It aims to assist artists with tasks like animating custom characters or using them as models for clothing, etc.
12
+
13
+ We are aware of the potential for unethical applications and are committed to preventative measures. A built-in check prevents the program from processing inappropriate media (nudity, graphic content, sensitive material like war footage, etc.). We will continue to develop this project responsibly, adhering to law and ethics. We may shut down the project or add watermarks if legally required.
14
+
15
+ Users are expected to use this software responsibly and legally. If using a real person's face, obtain their consent and clearly label any output as a deepfake when sharing online. We are not responsible for end-user actions.
16
+
17
+
18
+ ## Features
19
+
20
+ ### Resizable Preview Window
21
+
22
+ Dynamically improve performance using the `--live-resizable` parameter.
23
+
24
+ ![resizable-gif](resizable.gif)
25
+
26
+ ### Face Mapping
27
+
28
+ Track and change faces on the fly.
29
+
30
+ ![face_mapping_source](face_mapping_source.gif)
31
+
32
+ **Source Video:**
33
+
34
+ ![face-mapping](face_mapping.png)
35
+
36
+ **Enable Face Mapping:**
37
+
38
+ ![face-mapping2](face_mapping2.png)
39
+
40
+ **Map the Faces:**
41
+
42
+ ![face_mapping_result](face_mapping_result.gif)
43
+
44
+ **See the Magic!**
45
+
46
+ ## Quick Start (Windows / Nvidia)
47
+
48
+ [Download latest pre-built version with CUDA support](https://hacksider.gumroad.com/l/vccdmm) - No Manual Installation/Downloading required.
49
+
50
+ ## Installation (Manual)
51
+
52
+ ### Basic Installation (CPU)
53
+
54
+ This is more likely to work on your computer but will be slower as it utilizes the CPU.
55
+
56
+ **1. Setup Your Platform**
57
+
58
+ - Python (3.10 recommended)
59
+ - pip
60
+ - git
61
+ - [ffmpeg](https://www.youtube.com/watch?v=OlNWCpFdVMA)
62
+ - [Visual Studio 2022 Runtimes (Windows)](https://visualstudio.microsoft.com/visual-cpp-build-tools/)
63
+
64
+ **2. Clone Repository**
65
+
66
+ ```bash
67
+ https://github.com/hacksider/Deep-Live-Cam.git
68
+ ```
69
+
70
+ **3. Download Models**
71
+
72
+ 1. [GFPGANv1.4](https://huggingface.co/hacksider/deep-live-cam/resolve/main/GFPGANv1.4.pth)
73
+ 2. [inswapper_128_fp16.onnx](https://huggingface.co/hacksider/deep-live-cam/resolve/main/inswapper_128.onnx) (Note: Use this [replacement version](https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128.onnx) if you encounter issues)
74
+
75
+ Place these files in the "**models**" folder.
76
+
77
+ **4. Install Dependencies**
78
+
79
+ We highly recommend using a `venv` to avoid issues.
80
+
81
+ ```bash
82
+ pip install -r requirements.txt
83
+ ```
84
+
85
+ **For macOS:** Install or upgrade the `python-tk` package:
86
+
87
+ ```bash
88
+ brew install [email protected]
89
+ ```
90
+
91
+ **Run:** If you don't have a GPU, you can run Deep-Live-Cam using `python run.py`. Note that initial execution will download models (~300MB).
92
+
93
+
94
+ ### GPU Acceleration (Optional)
95
+
96
+ <details>
97
+ <summary>Click to see the details</summary>
98
+
99
+ **CUDA Execution Provider (Nvidia)**
100
+
101
+ 1. Install [CUDA Toolkit 11.8](https://developer.nvidia.com/cuda-11-8-0-download-archive)
102
+ 2. Install dependencies:
103
+ ```bash
104
+ pip uninstall onnxruntime onnxruntime-gpu
105
+ pip install onnxruntime-gpu==1.16.3
106
+ ```
107
+ 3. Usage:
108
+ ```bash
109
+ python run.py --execution-provider cuda
110
+ ```
111
+
112
+ **CoreML Execution Provider (Apple Silicon)**
113
+
114
+ 1. Install dependencies:
115
+ ```bash
116
+ pip uninstall onnxruntime onnxruntime-silicon
117
+ pip install onnxruntime-silicon==1.13.1
118
+ ```
119
+ 2. Usage:
120
+ ```bash
121
+ python run.py --execution-provider coreml
122
+ ```
123
+
124
+ **CoreML Execution Provider (Apple Legacy)**
125
+
126
+ 1. Install dependencies:
127
+ ```bash
128
+ pip uninstall onnxruntime onnxruntime-coreml
129
+ pip install onnxruntime-coreml==1.13.1
130
+ ```
131
+ 2. Usage:
132
+ ```bash
133
+ python run.py --execution-provider coreml
134
+ ```
135
+
136
+ **DirectML Execution Provider (Windows)**
137
+
138
+ 1. Install dependencies:
139
+ ```bash
140
+ pip uninstall onnxruntime onnxruntime-directml
141
+ pip install onnxruntime-directml==1.15.1
142
+ ```
143
+ 2. Usage:
144
+ ```bash
145
+ python run.py --execution-provider directml
146
+ ```
147
+
148
+ **OpenVINO™ Execution Provider (Intel)**
149
+
150
+ 1. Install dependencies:
151
+ ```bash
152
+ pip uninstall onnxruntime onnxruntime-openvino
153
+ pip install onnxruntime-openvino==1.15.0
154
+ ```
155
+ 2. Usage:
156
+ ```bash
157
+ python run.py --execution-provider openvino
158
+ ```
159
+
160
+ </details>
161
+
162
+
163
+ ## Usage
164
+
165
+ **1. Image/Video Mode**
166
+
167
+ - Execute `python run.py`.
168
+ - Choose a source face image and a target image/video.
169
+ - Click "Start".
170
+ - The output will be saved in a directory named after the target video.
171
+
172
+ **2. Webcam Mode**
173
+
174
+ - Execute `python run.py`.
175
+ - Select a source face image.
176
+ - Click "Live".
177
+ - Wait for the preview to appear (10-30 seconds).
178
+ - Use a screen capture tool like OBS to stream.
179
+ - To change the face, select a new source image.
180
+
181
+ ![demo-gif](demo.gif)
182
+
183
+ ## Command Line Arguments
184
+
185
+ ```
186
+ options:
187
+ -h, --help show this help message and exit
188
+ -s SOURCE_PATH, --source SOURCE_PATH select a source image
189
+ -t TARGET_PATH, --target TARGET_PATH select a target image or video
190
+ -o OUTPUT_PATH, --output OUTPUT_PATH select output file or directory
191
+ --frame-processor FRAME_PROCESSOR [FRAME_PROCESSOR ...] frame processors (choices: face_swapper, face_enhancer, ...)
192
+ --keep-fps keep original fps
193
+ --keep-audio keep original audio
194
+ --keep-frames keep temporary frames
195
+ --many-faces process every face
196
+ --map-faces map source target faces
197
+ --nsfw-filter filter the NSFW image or video
198
+ --video-encoder {libx264,libx265,libvpx-vp9} adjust output video encoder
199
+ --video-quality [0-51] adjust output video quality
200
+ --live-mirror the live camera display as you see it in the front-facing camera frame
201
+ --live-resizable the live camera frame is resizable
202
+ --max-memory MAX_MEMORY maximum amount of RAM in GB
203
+ --execution-provider {cpu} [{cpu} ...] available execution provider (choices: cpu, ...)
204
+ --execution-threads EXECUTION_THREADS number of execution threads
205
+ -v, --version show program's version number and exit
206
+ ```
207
+
208
+ Looking for a CLI mode? Using the -s/--source argument will make the run program in cli mode.
209
+
210
+
211
+ ## Webcam Mode on WSL2 Ubuntu (Optional)
212
+
213
+ <details>
214
+ <summary>Click to see the details</summary>
215
+
216
+ If you want to use WSL2 on Windows 11 you will notice, that Ubuntu WSL2 doesn't come with USB-Webcam support in the Kernel. You need to do two things: Compile the Kernel with the right modules integrated and forward your USB Webcam from Windows to Ubuntu with the usbipd app. Here are detailed Steps:
217
+
218
+ This tutorial will guide you through the process of setting up WSL2 Ubuntu with USB webcam support, rebuilding the kernel, and preparing the environment for the Deep-Live-Cam project.
219
+
220
+ **1. Install WSL2 Ubuntu**
221
+
222
+ Install WSL2 Ubuntu from the Microsoft Store or using PowerShell:
223
+
224
+ **2. Enable USB Support in WSL2**
225
+
226
+ 1. Install the USB/IP tool for Windows:
227
+ [https://learn.microsoft.com/en-us/windows/wsl/connect-usb](https://learn.microsoft.com/en-us/windows/wsl/connect-usb)
228
+
229
+ 2. In Windows PowerShell (as Administrator), connect your webcam to WSL:
230
+
231
+ ```powershell
232
+ usbipd list
233
+ usbipd bind --busid x-x # Replace x-x with your webcam's bus ID
234
+ usbipd attach --wsl --busid x-x # Replace x-x with your webcam's bus ID
235
+ ```
236
+ You need to redo the above every time you reboot wsl or re-connect your webcam/usb device.
237
+
238
+ **3. Rebuild WSL2 Ubuntu Kernel with USB and Webcam Modules**
239
+
240
+ Follow these steps to rebuild the kernel:
241
+
242
+ 1. Start with this guide: [https://github.com/PINTO0309/wsl2_linux_kernel_usbcam_enable_conf](https://github.com/PINTO0309/wsl2_linux_kernel_usbcam_enable_conf)
243
+
244
+ 2. When you reach the `sudo wget [github.com](http://github.com/)...PINTO0309` step, which won't work for newer kernel versions, follow this video instead or alternatively follow the video tutorial from the beginning:
245
+ [https://www.youtube.com/watch?v=t_YnACEPmrM](https://www.youtube.com/watch?v=t_YnACEPmrM)
246
+
247
+ Additional info: [https://askubuntu.com/questions/1413377/camera-not-working-in-cheese-in-wsl2](https://askubuntu.com/questions/1413377/camera-not-working-in-cheese-in-wsl2)
248
+
249
+ 3. After rebuilding, restart WSL with the new kernel.
250
+
251
+ **4. Set Up Deep-Live-Cam Project**
252
+ Within Ubuntu:
253
+ 1. Clone the repository:
254
+
255
+ ```bash
256
+ git clone [https://github.com/hacksider/Deep-Live-Cam](https://github.com/hacksider/Deep-Live-Cam)
257
+ ```
258
+
259
+ 2. Follow the installation instructions in the repository, including cuda toolkit 11.8, make 100% sure it's not cuda toolkit 12.x.
260
+
261
+ **5. Verify and Load Kernel Modules**
262
+
263
+ 1. Check if USB and webcam modules are built into the kernel:
264
+
265
+ ```bash
266
+ zcat /proc/config.gz | grep -i "CONFIG_USB_VIDEO_CLASS"
267
+ ```
268
+
269
+ 2. If modules are loadable (m), not built-in (y), check if the file exists:
270
+
271
+ ```bash
272
+ ls /lib/modules/$(uname -r)/kernel/drivers/media/usb/uvc/
273
+ ```
274
+
275
+ 3. Load the module and check for errors (optional if built-in):
276
+
277
+ ```bash
278
+ sudo modprobe uvcvideo
279
+ dmesg | tail
280
+ ```
281
+
282
+ 4. Verify video devices:
283
+
284
+ ```bash
285
+ sudo ls -al /dev/video*
286
+ ```
287
+
288
+ **6. Set Up Permissions**
289
+
290
+ 1. Add user to video group and set permissions:
291
+
292
+ ```bash
293
+ sudo usermod -a -G video $USER
294
+ sudo chgrp video /dev/video0 /dev/video1
295
+ sudo chmod 660 /dev/video0 /dev/video1
296
+ ```
297
+
298
+ 2. Create a udev rule for permanent permissions:
299
+
300
+ ```bash
301
+ sudo nano /etc/udev/rules.d/81-webcam.rules
302
+ ```
303
+
304
+ Add this content:
305
+
306
+ ```
307
+ KERNEL=="video[0-9]*", GROUP="video", MODE="0660"
308
+ ```
309
+
310
+ 3. Reload udev rules:
311
+
312
+ ```bash
313
+ sudo udevadm control --reload-rules && sudo udevadm trigger
314
+ ```
315
+
316
+ 4. Log out and log back into your WSL session.
317
+
318
+ 5. Start Deep-Live-Cam with `python run.py --execution-provider cuda --max-memory 8` where 8 can be changed to the number of GB VRAM of your GPU has, minus 1-2GB. If you have a RTX3080 with 10GB I suggest adding 8GB. Leave some left for Windows.
319
+
320
+ **Final Notes**
321
+
322
+ - Steps 6 and 7 may be optional if the modules are built into the kernel and permissions are already set correctly.
323
+ - Always ensure you're using compatible versions of CUDA, ONNX, and other dependencies.
324
+ - If issues persist, consider checking the Deep-Live-Cam project's specific requirements and troubleshooting steps.
325
+
326
+ By following these steps, you should have a WSL2 Ubuntu environment with USB webcam support ready for the Deep-Live-Cam project. If you encounter any issues, refer back to the specific error messages and troubleshooting steps provided.
327
+
328
+ **Troubleshooting CUDA Issues**
329
+
330
+ If you encounter this error:
331
+
332
+ ```
333
+ [ONNXRuntimeError] : 1 : FAIL : Failed to load library [libonnxruntime_providers_cuda.so](http://libonnxruntime_providers_cuda.so/) with error: libcufft.so.10: cannot open shared object file: No such file or directory
334
+ ```
335
+
336
+ Follow these steps:
337
+
338
+ 1. Install CUDA Toolkit 11.8 (ONNX 1.16.3 requires CUDA 11.x, not 12.x):
339
+ [https://developer.nvidia.com/cuda-11-8-0-download-archive](https://developer.nvidia.com/cuda-11-8-0-download-archive)
340
+ select: Linux, x86_64, WSL-Ubuntu, 2.0, deb (local)
341
+ 2. Check CUDA version:
342
+
343
+ ```bash
344
+ /usr/local/cuda/bin/nvcc --version
345
+ ```
346
+
347
+ 3. If the wrong version is installed, remove it completely:
348
+ [https://askubuntu.com/questions/530043/removing-nvidia-cuda-toolkit-and-installing-new-one](https://askubuntu.com/questions/530043/removing-nvidia-cuda-toolkit-and-installing-new-one)
349
+
350
+ 4. Install CUDA Toolkit 11.8 again [https://developer.nvidia.com/cuda-11-8-0-download-archive](https://developer.nvidia.com/cuda-11-8-0-download-archive), select: Linux, x86_64, WSL-Ubuntu, 2.0, deb (local)
351
+
352
+ ```bash
353
+ sudo apt-get -y install cuda-toolkit-11-8
354
+ ```
355
+ </details>
356
+
357
+
358
+ ## Future Updates & Roadmap
359
+
360
+ For the latest experimental builds and features, see the [experimental branch](https://github.com/hacksider/Deep-Live-Cam/tree/experimental).
361
+
362
+ **TODO:**
363
+
364
+ - [x] Support multiple faces
365
+ - [ ] Develop a version for web app/service
366
+ - [ ] UI/UX enhancements for desktop app
367
+ - [ ] Speed up model loading
368
+ - [ ] Speed up real-time face swapping
369
+
370
+ This is an open-source project developed in our free time. Updates may be delayed.
371
+
372
+
373
+ ## Credits
374
+
375
+ - [ffmpeg](https://ffmpeg.org/): for making video related operations easy
376
+ - [deepinsight](https://github.com/deepinsight): for their [insightface](https://github.com/deepinsight/insightface) project which provided a well-made library and models. Please be reminded that the [use of the model is for non-commercial research purposes only](https://github.com/deepinsight/insightface?tab=readme-ov-file#license).
377
+ - [havok2-htwo](https://github.com/havok2-htwo) : for sharing the code for webcam
378
+ - [GosuDRM](https://github.com/GosuDRM) : for open version of roop
379
+ - [pereiraroland26](https://github.com/pereiraroland26) : Multiple faces support
380
+ - [vic4key](https://github.com/vic4key) : For supporting/contributing on this project
381
+ - [KRSHH](https://github.com/KRSHH) : For updating the UI
382
+ - and [all developers](https://github.com/hacksider/Deep-Live-Cam/graphs/contributors) behind libraries used in this project.
383
+ - Foot Note: [This is originally roop-cam, see the full history of the code here.](https://github.com/hacksider/roop-cam) Please be informed that the base author of the code is [s0md3v](https://github.com/s0md3v/roop)
384
+
385
+ ## Thanks to all the contributors
386
+ <a href="https://github.com/hacksider/Deep-Live-Cam/graphs/contributors" target="_blank">
387
+ <img src="https://contrib.rocks/image?repo=hacksider/Deep-Live-Cam" />
388
+ </a>
docs/gui-demo.jpg ADDED
models/instructions.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ just put the models in this folder
modules/__init__.py ADDED
File without changes
modules/capturer.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+ import cv2
3
+ import modules.globals # Import the globals to check the color correction toggle
4
+
5
+
6
+ def get_video_frame(video_path: str, frame_number: int = 0) -> Any:
7
+ capture = cv2.VideoCapture(video_path)
8
+
9
+ # Set MJPEG format to ensure correct color space handling
10
+ capture.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG'))
11
+
12
+ # Only force RGB conversion if color correction is enabled
13
+ if modules.globals.color_correction:
14
+ capture.set(cv2.CAP_PROP_CONVERT_RGB, 1)
15
+
16
+ frame_total = capture.get(cv2.CAP_PROP_FRAME_COUNT)
17
+ capture.set(cv2.CAP_PROP_POS_FRAMES, min(frame_total, frame_number - 1))
18
+ has_frame, frame = capture.read()
19
+
20
+ if has_frame and modules.globals.color_correction:
21
+ # Convert the frame color if necessary
22
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
23
+
24
+ capture.release()
25
+ return frame if has_frame else None
26
+
27
+
28
+ def get_video_frame_total(video_path: str) -> int:
29
+ capture = cv2.VideoCapture(video_path)
30
+ video_frame_total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
31
+ capture.release()
32
+ return video_frame_total
modules/cluster_analysis.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from sklearn.cluster import KMeans
3
+ from sklearn.metrics import silhouette_score
4
+ from typing import Any
5
+
6
+
7
+ def find_cluster_centroids(embeddings, max_k=10) -> Any:
8
+ inertia = []
9
+ cluster_centroids = []
10
+ K = range(1, max_k+1)
11
+
12
+ for k in K:
13
+ kmeans = KMeans(n_clusters=k, random_state=0)
14
+ kmeans.fit(embeddings)
15
+ inertia.append(kmeans.inertia_)
16
+ cluster_centroids.append({"k": k, "centroids": kmeans.cluster_centers_})
17
+
18
+ diffs = [inertia[i] - inertia[i+1] for i in range(len(inertia)-1)]
19
+ optimal_centroids = cluster_centroids[diffs.index(max(diffs)) + 1]['centroids']
20
+
21
+ return optimal_centroids
22
+
23
+ def find_closest_centroid(centroids: list, normed_face_embedding) -> list:
24
+ try:
25
+ centroids = np.array(centroids)
26
+ normed_face_embedding = np.array(normed_face_embedding)
27
+ similarities = np.dot(centroids, normed_face_embedding)
28
+ closest_centroid_index = np.argmax(similarities)
29
+
30
+ return closest_centroid_index, centroids[closest_centroid_index]
31
+ except ValueError:
32
+ return None
modules/core.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ # single thread doubles cuda performance - needs to be set before torch import
4
+ if any(arg.startswith('--execution-provider') for arg in sys.argv):
5
+ os.environ['OMP_NUM_THREADS'] = '1'
6
+ # reduce tensorflow log level
7
+ os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
8
+ import warnings
9
+ from typing import List
10
+ import platform
11
+ import signal
12
+ import shutil
13
+ import argparse
14
+ import torch
15
+ import onnxruntime
16
+ import tensorflow
17
+
18
+ import modules.globals
19
+ import modules.metadata
20
+ import modules.ui as ui
21
+ from modules.processors.frame.core import get_frame_processors_modules
22
+ from modules.utilities import has_image_extension, is_image, is_video, detect_fps, create_video, extract_frames, get_temp_frame_paths, restore_audio, create_temp, move_temp, clean_temp, normalize_output_path
23
+
24
+ if 'ROCMExecutionProvider' in modules.globals.execution_providers:
25
+ del torch
26
+
27
+ warnings.filterwarnings('ignore', category=FutureWarning, module='insightface')
28
+ warnings.filterwarnings('ignore', category=UserWarning, module='torchvision')
29
+
30
+
31
+ def parse_args() -> None:
32
+ signal.signal(signal.SIGINT, lambda signal_number, frame: destroy())
33
+ program = argparse.ArgumentParser()
34
+ program.add_argument('-s', '--source', help='select an source image', dest='source_path')
35
+ program.add_argument('-t', '--target', help='select an target image or video', dest='target_path')
36
+ program.add_argument('-o', '--output', help='select output file or directory', dest='output_path')
37
+ program.add_argument('--frame-processor', help='pipeline of frame processors', dest='frame_processor', default=['face_swapper'], choices=['face_swapper', 'face_enhancer'], nargs='+')
38
+ program.add_argument('--keep-fps', help='keep original fps', dest='keep_fps', action='store_true', default=False)
39
+ program.add_argument('--keep-audio', help='keep original audio', dest='keep_audio', action='store_true', default=True)
40
+ program.add_argument('--keep-frames', help='keep temporary frames', dest='keep_frames', action='store_true', default=False)
41
+ program.add_argument('--many-faces', help='process every face', dest='many_faces', action='store_true', default=False)
42
+ program.add_argument('--nsfw-filter', help='filter the NSFW image or video', dest='nsfw_filter', action='store_true', default=False)
43
+ program.add_argument('--map-faces', help='map source target faces', dest='map_faces', action='store_true', default=False)
44
+ program.add_argument('--video-encoder', help='adjust output video encoder', dest='video_encoder', default='libx264', choices=['libx264', 'libx265', 'libvpx-vp9'])
45
+ program.add_argument('--video-quality', help='adjust output video quality', dest='video_quality', type=int, default=18, choices=range(52), metavar='[0-51]')
46
+ program.add_argument('--live-mirror', help='The live camera display as you see it in the front-facing camera frame', dest='live_mirror', action='store_true', default=False)
47
+ program.add_argument('--live-resizable', help='The live camera frame is resizable', dest='live_resizable', action='store_true', default=False)
48
+ program.add_argument('--max-memory', help='maximum amount of RAM in GB', dest='max_memory', type=int, default=suggest_max_memory())
49
+ program.add_argument('--execution-provider', help='execution provider', dest='execution_provider', default=['cpu'], choices=suggest_execution_providers(), nargs='+')
50
+ program.add_argument('--execution-threads', help='number of execution threads', dest='execution_threads', type=int, default=suggest_execution_threads())
51
+ program.add_argument('-v', '--version', action='version', version=f'{modules.metadata.name} {modules.metadata.version}')
52
+
53
+ # register deprecated args
54
+ program.add_argument('-f', '--face', help=argparse.SUPPRESS, dest='source_path_deprecated')
55
+ program.add_argument('--cpu-cores', help=argparse.SUPPRESS, dest='cpu_cores_deprecated', type=int)
56
+ program.add_argument('--gpu-vendor', help=argparse.SUPPRESS, dest='gpu_vendor_deprecated')
57
+ program.add_argument('--gpu-threads', help=argparse.SUPPRESS, dest='gpu_threads_deprecated', type=int)
58
+
59
+ args = program.parse_args()
60
+
61
+ modules.globals.source_path = args.source_path
62
+ modules.globals.target_path = args.target_path
63
+ modules.globals.output_path = normalize_output_path(modules.globals.source_path, modules.globals.target_path, args.output_path)
64
+ modules.globals.frame_processors = args.frame_processor
65
+ modules.globals.headless = args.source_path or args.target_path or args.output_path
66
+ modules.globals.keep_fps = args.keep_fps
67
+ modules.globals.keep_audio = args.keep_audio
68
+ modules.globals.keep_frames = args.keep_frames
69
+ modules.globals.many_faces = args.many_faces
70
+ modules.globals.nsfw_filter = args.nsfw_filter
71
+ modules.globals.map_faces = args.map_faces
72
+ modules.globals.video_encoder = args.video_encoder
73
+ modules.globals.video_quality = args.video_quality
74
+ modules.globals.live_mirror = args.live_mirror
75
+ modules.globals.live_resizable = args.live_resizable
76
+ modules.globals.max_memory = args.max_memory
77
+ modules.globals.execution_providers = decode_execution_providers(args.execution_provider)
78
+ modules.globals.execution_threads = args.execution_threads
79
+
80
+ #for ENHANCER tumbler:
81
+ if 'face_enhancer' in args.frame_processor:
82
+ modules.globals.fp_ui['face_enhancer'] = True
83
+ else:
84
+ modules.globals.fp_ui['face_enhancer'] = False
85
+
86
+ # translate deprecated args
87
+ if args.source_path_deprecated:
88
+ print('\033[33mArgument -f and --face are deprecated. Use -s and --source instead.\033[0m')
89
+ modules.globals.source_path = args.source_path_deprecated
90
+ modules.globals.output_path = normalize_output_path(args.source_path_deprecated, modules.globals.target_path, args.output_path)
91
+ if args.cpu_cores_deprecated:
92
+ print('\033[33mArgument --cpu-cores is deprecated. Use --execution-threads instead.\033[0m')
93
+ modules.globals.execution_threads = args.cpu_cores_deprecated
94
+ if args.gpu_vendor_deprecated == 'apple':
95
+ print('\033[33mArgument --gpu-vendor apple is deprecated. Use --execution-provider coreml instead.\033[0m')
96
+ modules.globals.execution_providers = decode_execution_providers(['coreml'])
97
+ if args.gpu_vendor_deprecated == 'nvidia':
98
+ print('\033[33mArgument --gpu-vendor nvidia is deprecated. Use --execution-provider cuda instead.\033[0m')
99
+ modules.globals.execution_providers = decode_execution_providers(['cuda'])
100
+ if args.gpu_vendor_deprecated == 'amd':
101
+ print('\033[33mArgument --gpu-vendor amd is deprecated. Use --execution-provider cuda instead.\033[0m')
102
+ modules.globals.execution_providers = decode_execution_providers(['rocm'])
103
+ if args.gpu_threads_deprecated:
104
+ print('\033[33mArgument --gpu-threads is deprecated. Use --execution-threads instead.\033[0m')
105
+ modules.globals.execution_threads = args.gpu_threads_deprecated
106
+
107
+
108
+ def encode_execution_providers(execution_providers: List[str]) -> List[str]:
109
+ return [execution_provider.replace('ExecutionProvider', '').lower() for execution_provider in execution_providers]
110
+
111
+
112
+ def decode_execution_providers(execution_providers: List[str]) -> List[str]:
113
+ return [provider for provider, encoded_execution_provider in zip(onnxruntime.get_available_providers(), encode_execution_providers(onnxruntime.get_available_providers()))
114
+ if any(execution_provider in encoded_execution_provider for execution_provider in execution_providers)]
115
+
116
+
117
+ def suggest_max_memory() -> int:
118
+ if platform.system().lower() == 'darwin':
119
+ return 4
120
+ return 16
121
+
122
+
123
+ def suggest_execution_providers() -> List[str]:
124
+ return encode_execution_providers(onnxruntime.get_available_providers())
125
+
126
+
127
+ def suggest_execution_threads() -> int:
128
+ if 'DmlExecutionProvider' in modules.globals.execution_providers:
129
+ return 1
130
+ if 'ROCMExecutionProvider' in modules.globals.execution_providers:
131
+ return 1
132
+ return 8
133
+
134
+
135
+ def limit_resources() -> None:
136
+ # prevent tensorflow memory leak
137
+ gpus = tensorflow.config.experimental.list_physical_devices('GPU')
138
+ for gpu in gpus:
139
+ tensorflow.config.experimental.set_memory_growth(gpu, True)
140
+ # limit memory usage
141
+ if modules.globals.max_memory:
142
+ memory = modules.globals.max_memory * 1024 ** 3
143
+ if platform.system().lower() == 'darwin':
144
+ memory = modules.globals.max_memory * 1024 ** 6
145
+ if platform.system().lower() == 'windows':
146
+ import ctypes
147
+ kernel32 = ctypes.windll.kernel32
148
+ kernel32.SetProcessWorkingSetSize(-1, ctypes.c_size_t(memory), ctypes.c_size_t(memory))
149
+ else:
150
+ import resource
151
+ resource.setrlimit(resource.RLIMIT_DATA, (memory, memory))
152
+
153
+
154
+ def release_resources() -> None:
155
+ if 'CUDAExecutionProvider' in modules.globals.execution_providers:
156
+ torch.cuda.empty_cache()
157
+
158
+
159
+ def pre_check() -> bool:
160
+ if sys.version_info < (3, 9):
161
+ update_status('Python version is not supported - please upgrade to 3.9 or higher.')
162
+ return False
163
+ if not shutil.which('ffmpeg'):
164
+ update_status('ffmpeg is not installed.')
165
+ return False
166
+ return True
167
+
168
+
169
+ def update_status(message: str, scope: str = 'DLC.CORE') -> None:
170
+ print(f'[{scope}] {message}')
171
+ if not modules.globals.headless:
172
+ ui.update_status(message)
173
+
174
+ def start() -> None:
175
+ for frame_processor in get_frame_processors_modules(modules.globals.frame_processors):
176
+ if not frame_processor.pre_start():
177
+ return
178
+ update_status('Processing...')
179
+ # process image to image
180
+ if has_image_extension(modules.globals.target_path):
181
+ if modules.globals.nsfw_filter and ui.check_and_ignore_nsfw(modules.globals.target_path, destroy):
182
+ return
183
+ try:
184
+ shutil.copy2(modules.globals.target_path, modules.globals.output_path)
185
+ except Exception as e:
186
+ print("Error copying file:", str(e))
187
+ for frame_processor in get_frame_processors_modules(modules.globals.frame_processors):
188
+ update_status('Progressing...', frame_processor.NAME)
189
+ frame_processor.process_image(modules.globals.source_path, modules.globals.output_path, modules.globals.output_path)
190
+ release_resources()
191
+ if is_image(modules.globals.target_path):
192
+ update_status('Processing to image succeed!')
193
+ else:
194
+ update_status('Processing to image failed!')
195
+ return
196
+ # process image to videos
197
+ if modules.globals.nsfw_filter and ui.check_and_ignore_nsfw(modules.globals.target_path, destroy):
198
+ return
199
+
200
+ if not modules.globals.map_faces:
201
+ update_status('Creating temp resources...')
202
+ create_temp(modules.globals.target_path)
203
+ update_status('Extracting frames...')
204
+ extract_frames(modules.globals.target_path)
205
+
206
+ temp_frame_paths = get_temp_frame_paths(modules.globals.target_path)
207
+ for frame_processor in get_frame_processors_modules(modules.globals.frame_processors):
208
+ update_status('Progressing...', frame_processor.NAME)
209
+ frame_processor.process_video(modules.globals.source_path, temp_frame_paths)
210
+ release_resources()
211
+ # handles fps
212
+ if modules.globals.keep_fps:
213
+ update_status('Detecting fps...')
214
+ fps = detect_fps(modules.globals.target_path)
215
+ update_status(f'Creating video with {fps} fps...')
216
+ create_video(modules.globals.target_path, fps)
217
+ else:
218
+ update_status('Creating video with 30.0 fps...')
219
+ create_video(modules.globals.target_path)
220
+ # handle audio
221
+ if modules.globals.keep_audio:
222
+ if modules.globals.keep_fps:
223
+ update_status('Restoring audio...')
224
+ else:
225
+ update_status('Restoring audio might cause issues as fps are not kept...')
226
+ restore_audio(modules.globals.target_path, modules.globals.output_path)
227
+ else:
228
+ move_temp(modules.globals.target_path, modules.globals.output_path)
229
+ # clean and validate
230
+ clean_temp(modules.globals.target_path)
231
+ if is_video(modules.globals.target_path):
232
+ update_status('Processing to video succeed!')
233
+ else:
234
+ update_status('Processing to video failed!')
235
+
236
+
237
+ def destroy(to_quit=True) -> None:
238
+ if modules.globals.target_path:
239
+ clean_temp(modules.globals.target_path)
240
+ if to_quit: quit()
241
+
242
+
243
+ def run() -> None:
244
+ parse_args()
245
+ if not pre_check():
246
+ return
247
+ for frame_processor in get_frame_processors_modules(modules.globals.frame_processors):
248
+ if not frame_processor.pre_check():
249
+ return
250
+ limit_resources()
251
+ if modules.globals.headless:
252
+ start()
253
+ else:
254
+ window = ui.init(start, destroy)
255
+ window.mainloop()
modules/face_analyser.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ from typing import Any
4
+ import insightface
5
+
6
+ import cv2
7
+ import numpy as np
8
+ import modules.globals
9
+ from tqdm import tqdm
10
+ from modules.typing import Frame
11
+ from modules.cluster_analysis import find_cluster_centroids, find_closest_centroid
12
+ from modules.utilities import get_temp_directory_path, create_temp, extract_frames, clean_temp, get_temp_frame_paths
13
+ from pathlib import Path
14
+
15
+ FACE_ANALYSER = None
16
+
17
+
18
+ def get_face_analyser() -> Any:
19
+ global FACE_ANALYSER
20
+
21
+ if FACE_ANALYSER is None:
22
+ FACE_ANALYSER = insightface.app.FaceAnalysis(name='buffalo_l', providers=modules.globals.execution_providers)
23
+ FACE_ANALYSER.prepare(ctx_id=0, det_size=(640, 640))
24
+ return FACE_ANALYSER
25
+
26
+
27
+ def get_one_face(frame: Frame) -> Any:
28
+ face = get_face_analyser().get(frame)
29
+ try:
30
+ return min(face, key=lambda x: x.bbox[0])
31
+ except ValueError:
32
+ return None
33
+
34
+
35
+ def get_many_faces(frame: Frame) -> Any:
36
+ try:
37
+ return get_face_analyser().get(frame)
38
+ except IndexError:
39
+ return None
40
+
41
+ def has_valid_map() -> bool:
42
+ for map in modules.globals.souce_target_map:
43
+ if "source" in map and "target" in map:
44
+ return True
45
+ return False
46
+
47
+ def default_source_face() -> Any:
48
+ for map in modules.globals.souce_target_map:
49
+ if "source" in map:
50
+ return map['source']['face']
51
+ return None
52
+
53
+ def simplify_maps() -> Any:
54
+ centroids = []
55
+ faces = []
56
+ for map in modules.globals.souce_target_map:
57
+ if "source" in map and "target" in map:
58
+ centroids.append(map['target']['face'].normed_embedding)
59
+ faces.append(map['source']['face'])
60
+
61
+ modules.globals.simple_map = {'source_faces': faces, 'target_embeddings': centroids}
62
+ return None
63
+
64
+ def add_blank_map() -> Any:
65
+ try:
66
+ max_id = -1
67
+ if len(modules.globals.souce_target_map) > 0:
68
+ max_id = max(modules.globals.souce_target_map, key=lambda x: x['id'])['id']
69
+
70
+ modules.globals.souce_target_map.append({
71
+ 'id' : max_id + 1
72
+ })
73
+ except ValueError:
74
+ return None
75
+
76
+ def get_unique_faces_from_target_image() -> Any:
77
+ try:
78
+ modules.globals.souce_target_map = []
79
+ target_frame = cv2.imread(modules.globals.target_path)
80
+ many_faces = get_many_faces(target_frame)
81
+ i = 0
82
+
83
+ for face in many_faces:
84
+ x_min, y_min, x_max, y_max = face['bbox']
85
+ modules.globals.souce_target_map.append({
86
+ 'id' : i,
87
+ 'target' : {
88
+ 'cv2' : target_frame[int(y_min):int(y_max), int(x_min):int(x_max)],
89
+ 'face' : face
90
+ }
91
+ })
92
+ i = i + 1
93
+ except ValueError:
94
+ return None
95
+
96
+
97
+ def get_unique_faces_from_target_video() -> Any:
98
+ try:
99
+ modules.globals.souce_target_map = []
100
+ frame_face_embeddings = []
101
+ face_embeddings = []
102
+
103
+ print('Creating temp resources...')
104
+ clean_temp(modules.globals.target_path)
105
+ create_temp(modules.globals.target_path)
106
+ print('Extracting frames...')
107
+ extract_frames(modules.globals.target_path)
108
+
109
+ temp_frame_paths = get_temp_frame_paths(modules.globals.target_path)
110
+
111
+ i = 0
112
+ for temp_frame_path in tqdm(temp_frame_paths, desc="Extracting face embeddings from frames"):
113
+ temp_frame = cv2.imread(temp_frame_path)
114
+ many_faces = get_many_faces(temp_frame)
115
+
116
+ for face in many_faces:
117
+ face_embeddings.append(face.normed_embedding)
118
+
119
+ frame_face_embeddings.append({'frame': i, 'faces': many_faces, 'location': temp_frame_path})
120
+ i += 1
121
+
122
+ centroids = find_cluster_centroids(face_embeddings)
123
+
124
+ for frame in frame_face_embeddings:
125
+ for face in frame['faces']:
126
+ closest_centroid_index, _ = find_closest_centroid(centroids, face.normed_embedding)
127
+ face['target_centroid'] = closest_centroid_index
128
+
129
+ for i in range(len(centroids)):
130
+ modules.globals.souce_target_map.append({
131
+ 'id' : i
132
+ })
133
+
134
+ temp = []
135
+ for frame in tqdm(frame_face_embeddings, desc=f"Mapping frame embeddings to centroids-{i}"):
136
+ temp.append({'frame': frame['frame'], 'faces': [face for face in frame['faces'] if face['target_centroid'] == i], 'location': frame['location']})
137
+
138
+ modules.globals.souce_target_map[i]['target_faces_in_frame'] = temp
139
+
140
+ # dump_faces(centroids, frame_face_embeddings)
141
+ default_target_face()
142
+ except ValueError:
143
+ return None
144
+
145
+
146
+ def default_target_face():
147
+ for map in modules.globals.souce_target_map:
148
+ best_face = None
149
+ best_frame = None
150
+ for frame in map['target_faces_in_frame']:
151
+ if len(frame['faces']) > 0:
152
+ best_face = frame['faces'][0]
153
+ best_frame = frame
154
+ break
155
+
156
+ for frame in map['target_faces_in_frame']:
157
+ for face in frame['faces']:
158
+ if face['det_score'] > best_face['det_score']:
159
+ best_face = face
160
+ best_frame = frame
161
+
162
+ x_min, y_min, x_max, y_max = best_face['bbox']
163
+
164
+ target_frame = cv2.imread(best_frame['location'])
165
+ map['target'] = {
166
+ 'cv2' : target_frame[int(y_min):int(y_max), int(x_min):int(x_max)],
167
+ 'face' : best_face
168
+ }
169
+
170
+
171
+ def dump_faces(centroids: Any, frame_face_embeddings: list):
172
+ temp_directory_path = get_temp_directory_path(modules.globals.target_path)
173
+
174
+ for i in range(len(centroids)):
175
+ if os.path.exists(temp_directory_path + f"/{i}") and os.path.isdir(temp_directory_path + f"/{i}"):
176
+ shutil.rmtree(temp_directory_path + f"/{i}")
177
+ Path(temp_directory_path + f"/{i}").mkdir(parents=True, exist_ok=True)
178
+
179
+ for frame in tqdm(frame_face_embeddings, desc=f"Copying faces to temp/./{i}"):
180
+ temp_frame = cv2.imread(frame['location'])
181
+
182
+ j = 0
183
+ for face in frame['faces']:
184
+ if face['target_centroid'] == i:
185
+ x_min, y_min, x_max, y_max = face['bbox']
186
+
187
+ if temp_frame[int(y_min):int(y_max), int(x_min):int(x_max)].size > 0:
188
+ cv2.imwrite(temp_directory_path + f"/{i}/{frame['frame']}_{j}.png", temp_frame[int(y_min):int(y_max), int(x_min):int(x_max)])
189
+ j += 1
modules/globals.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import List, Dict, Any
3
+
4
+ ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
5
+ WORKFLOW_DIR = os.path.join(ROOT_DIR, 'workflow')
6
+
7
+ file_types = [
8
+ ('Image', ('*.png','*.jpg','*.jpeg','*.gif','*.bmp')),
9
+ ('Video', ('*.mp4','*.mkv'))
10
+ ]
11
+
12
+ souce_target_map = []
13
+ simple_map = {}
14
+
15
+ source_path = None
16
+ target_path = None
17
+ output_path = None
18
+ frame_processors: List[str] = []
19
+ keep_fps = None
20
+ keep_audio = None
21
+ keep_frames = None
22
+ many_faces = None
23
+ map_faces = None
24
+ color_correction = None # New global variable for color correction toggle
25
+ nsfw_filter = None
26
+ video_encoder = None
27
+ video_quality = None
28
+ live_mirror = None
29
+ live_resizable = None
30
+ max_memory = None
31
+ execution_providers: List[str] = []
32
+ execution_threads = None
33
+ headless = None
34
+ log_level = 'error'
35
+ fp_ui: Dict[str, bool] = {}
36
+ camera_input_combobox = None
37
+ webcam_preview_running = False
modules/metadata.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ name = 'Deep Live Cam'
2
+ version = '1.5.0'
3
+ edition = 'Portable'
modules/predicter.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy
2
+ import opennsfw2
3
+ from PIL import Image
4
+ import cv2 # Add OpenCV import
5
+ import modules.globals # Import globals to access the color correction toggle
6
+
7
+ from modules.typing import Frame
8
+
9
+ MAX_PROBABILITY = 0.85
10
+
11
+ # Preload the model once for efficiency
12
+ model = None
13
+
14
+ def predict_frame(target_frame: Frame) -> bool:
15
+ # Convert the frame to RGB before processing if color correction is enabled
16
+ if modules.globals.color_correction:
17
+ target_frame = cv2.cvtColor(target_frame, cv2.COLOR_BGR2RGB)
18
+
19
+ image = Image.fromarray(target_frame)
20
+ image = opennsfw2.preprocess_image(image, opennsfw2.Preprocessing.YAHOO)
21
+ global model
22
+ if model is None:
23
+ model = opennsfw2.make_open_nsfw_model()
24
+
25
+ views = numpy.expand_dims(image, axis=0)
26
+ _, probability = model.predict(views)[0]
27
+ return probability > MAX_PROBABILITY
28
+
29
+
30
+ def predict_image(target_path: str) -> bool:
31
+ return opennsfw2.predict_image(target_path) > MAX_PROBABILITY
32
+
33
+
34
+ def predict_video(target_path: str) -> bool:
35
+ _, probabilities = opennsfw2.predict_video_frames(video_path=target_path, frame_interval=100)
36
+ return any(probability > MAX_PROBABILITY for probability in probabilities)
modules/processors/__init__.py ADDED
File without changes
modules/processors/frame/__init__.py ADDED
File without changes
modules/processors/frame/core.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import importlib
3
+ from concurrent.futures import ThreadPoolExecutor
4
+ from types import ModuleType
5
+ from typing import Any, List, Callable
6
+ from tqdm import tqdm
7
+
8
+ import modules
9
+ import modules.globals
10
+
11
+ FRAME_PROCESSORS_MODULES: List[ModuleType] = []
12
+ FRAME_PROCESSORS_INTERFACE = [
13
+ 'pre_check',
14
+ 'pre_start',
15
+ 'process_frame',
16
+ 'process_image',
17
+ 'process_video'
18
+ ]
19
+
20
+
21
+ def load_frame_processor_module(frame_processor: str) -> Any:
22
+ try:
23
+ frame_processor_module = importlib.import_module(f'modules.processors.frame.{frame_processor}')
24
+ for method_name in FRAME_PROCESSORS_INTERFACE:
25
+ if not hasattr(frame_processor_module, method_name):
26
+ sys.exit()
27
+ except ImportError:
28
+ print(f"Frame processor {frame_processor} not found")
29
+ sys.exit()
30
+ return frame_processor_module
31
+
32
+
33
+ def get_frame_processors_modules(frame_processors: List[str]) -> List[ModuleType]:
34
+ global FRAME_PROCESSORS_MODULES
35
+
36
+ if not FRAME_PROCESSORS_MODULES:
37
+ for frame_processor in frame_processors:
38
+ frame_processor_module = load_frame_processor_module(frame_processor)
39
+ FRAME_PROCESSORS_MODULES.append(frame_processor_module)
40
+ set_frame_processors_modules_from_ui(frame_processors)
41
+ return FRAME_PROCESSORS_MODULES
42
+
43
+ def set_frame_processors_modules_from_ui(frame_processors: List[str]) -> None:
44
+ global FRAME_PROCESSORS_MODULES
45
+ for frame_processor, state in modules.globals.fp_ui.items():
46
+ if state == True and frame_processor not in frame_processors:
47
+ frame_processor_module = load_frame_processor_module(frame_processor)
48
+ FRAME_PROCESSORS_MODULES.append(frame_processor_module)
49
+ modules.globals.frame_processors.append(frame_processor)
50
+ if state == False:
51
+ try:
52
+ frame_processor_module = load_frame_processor_module(frame_processor)
53
+ FRAME_PROCESSORS_MODULES.remove(frame_processor_module)
54
+ modules.globals.frame_processors.remove(frame_processor)
55
+ except:
56
+ pass
57
+
58
+ def multi_process_frame(source_path: str, temp_frame_paths: List[str], process_frames: Callable[[str, List[str], Any], None], progress: Any = None) -> None:
59
+ with ThreadPoolExecutor(max_workers=modules.globals.execution_threads) as executor:
60
+ futures = []
61
+ for path in temp_frame_paths:
62
+ future = executor.submit(process_frames, source_path, [path], progress)
63
+ futures.append(future)
64
+ for future in futures:
65
+ future.result()
66
+
67
+
68
+ def process_video(source_path: str, frame_paths: list[str], process_frames: Callable[[str, List[str], Any], None]) -> None:
69
+ progress_bar_format = '{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]'
70
+ total = len(frame_paths)
71
+ with tqdm(total=total, desc='Processing', unit='frame', dynamic_ncols=True, bar_format=progress_bar_format) as progress:
72
+ progress.set_postfix({'execution_providers': modules.globals.execution_providers, 'execution_threads': modules.globals.execution_threads, 'max_memory': modules.globals.max_memory})
73
+ multi_process_frame(source_path, frame_paths, process_frames, progress)
modules/processors/frame/face_enhancer.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List
2
+ import cv2
3
+ import threading
4
+ import gfpgan
5
+ import os
6
+
7
+ import modules.globals
8
+ import modules.processors.frame.core
9
+ from modules.core import update_status
10
+ from modules.face_analyser import get_one_face
11
+ from modules.typing import Frame, Face
12
+ from modules.utilities import conditional_download, resolve_relative_path, is_image, is_video
13
+
14
+ FACE_ENHANCER = None
15
+ THREAD_SEMAPHORE = threading.Semaphore()
16
+ THREAD_LOCK = threading.Lock()
17
+ NAME = 'DLC.FACE-ENHANCER'
18
+
19
+
20
+ def pre_check() -> bool:
21
+ download_directory_path = resolve_relative_path('..\models')
22
+ conditional_download(download_directory_path, ['https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/GFPGANv1.4.pth'])
23
+ return True
24
+
25
+
26
+ def pre_start() -> bool:
27
+ if not is_image(modules.globals.target_path) and not is_video(modules.globals.target_path):
28
+ update_status('Select an image or video for target path.', NAME)
29
+ return False
30
+ return True
31
+
32
+
33
+ def get_face_enhancer() -> Any:
34
+ global FACE_ENHANCER
35
+
36
+ with THREAD_LOCK:
37
+ if FACE_ENHANCER is None:
38
+ if os.name == 'nt':
39
+ model_path = resolve_relative_path('..\models\GFPGANv1.4.pth')
40
+ # todo: set models path https://github.com/TencentARC/GFPGAN/issues/399
41
+ else:
42
+ model_path = resolve_relative_path('../models/GFPGANv1.4.pth')
43
+ FACE_ENHANCER = gfpgan.GFPGANer(model_path=model_path, upscale=1) # type: ignore[attr-defined]
44
+ return FACE_ENHANCER
45
+
46
+
47
+ def enhance_face(temp_frame: Frame) -> Frame:
48
+ with THREAD_SEMAPHORE:
49
+ _, _, temp_frame = get_face_enhancer().enhance(
50
+ temp_frame,
51
+ paste_back=True
52
+ )
53
+ return temp_frame
54
+
55
+
56
+ def process_frame(source_face: Face, temp_frame: Frame) -> Frame:
57
+ target_face = get_one_face(temp_frame)
58
+ if target_face:
59
+ temp_frame = enhance_face(temp_frame)
60
+ return temp_frame
61
+
62
+
63
+ def process_frames(source_path: str, temp_frame_paths: List[str], progress: Any = None) -> None:
64
+ for temp_frame_path in temp_frame_paths:
65
+ temp_frame = cv2.imread(temp_frame_path)
66
+ result = process_frame(None, temp_frame)
67
+ cv2.imwrite(temp_frame_path, result)
68
+ if progress:
69
+ progress.update(1)
70
+
71
+
72
+ def process_image(source_path: str, target_path: str, output_path: str) -> None:
73
+ target_frame = cv2.imread(target_path)
74
+ result = process_frame(None, target_frame)
75
+ cv2.imwrite(output_path, result)
76
+
77
+
78
+ def process_video(source_path: str, temp_frame_paths: List[str]) -> None:
79
+ modules.processors.frame.core.process_video(None, temp_frame_paths, process_frames)
modules/processors/frame/face_swapper.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List
2
+ import cv2
3
+ import insightface
4
+ import threading
5
+
6
+ import modules.globals
7
+ import modules.processors.frame.core
8
+ from modules.core import update_status
9
+ from modules.face_analyser import get_one_face, get_many_faces, default_source_face
10
+ from modules.typing import Face, Frame
11
+ from modules.utilities import conditional_download, resolve_relative_path, is_image, is_video
12
+ from modules.cluster_analysis import find_closest_centroid
13
+
14
+ FACE_SWAPPER = None
15
+ THREAD_LOCK = threading.Lock()
16
+ NAME = 'DLC.FACE-SWAPPER'
17
+
18
+
19
+ def pre_check() -> bool:
20
+ download_directory_path = resolve_relative_path('../models')
21
+ conditional_download(download_directory_path, ['https://huggingface.co/hacksider/deep-live-cam/blob/main/inswapper_128.onnx'])
22
+ return True
23
+
24
+
25
+ def pre_start() -> bool:
26
+ if not modules.globals.map_faces and not is_image(modules.globals.source_path):
27
+ update_status('Select an image for source path.', NAME)
28
+ return False
29
+ elif not modules.globals.map_faces and not get_one_face(cv2.imread(modules.globals.source_path)):
30
+ update_status('No face in source path detected.', NAME)
31
+ return False
32
+ if not is_image(modules.globals.target_path) and not is_video(modules.globals.target_path):
33
+ update_status('Select an image or video for target path.', NAME)
34
+ return False
35
+ return True
36
+
37
+
38
+ def get_face_swapper() -> Any:
39
+ global FACE_SWAPPER
40
+
41
+ with THREAD_LOCK:
42
+ if FACE_SWAPPER is None:
43
+ model_path = resolve_relative_path('../models/inswapper_128.onnx')
44
+ FACE_SWAPPER = insightface.model_zoo.get_model(model_path, providers=modules.globals.execution_providers)
45
+ return FACE_SWAPPER
46
+
47
+
48
+ def swap_face(source_face: Face, target_face: Face, temp_frame: Frame) -> Frame:
49
+ return get_face_swapper().get(temp_frame, target_face, source_face, paste_back=True)
50
+
51
+
52
+ def process_frame(source_face: Face, temp_frame: Frame) -> Frame:
53
+ # Ensure the frame is in RGB format if color correction is enabled
54
+ if modules.globals.color_correction:
55
+ temp_frame = cv2.cvtColor(temp_frame, cv2.COLOR_BGR2RGB)
56
+
57
+ if modules.globals.many_faces:
58
+ many_faces = get_many_faces(temp_frame)
59
+ if many_faces:
60
+ for target_face in many_faces:
61
+ temp_frame = swap_face(source_face, target_face, temp_frame)
62
+ else:
63
+ target_face = get_one_face(temp_frame)
64
+ if target_face:
65
+ temp_frame = swap_face(source_face, target_face, temp_frame)
66
+ return temp_frame
67
+
68
+
69
+ def process_frame_v2(temp_frame: Frame, temp_frame_path: str = "") -> Frame:
70
+ if is_image(modules.globals.target_path):
71
+ if modules.globals.many_faces:
72
+ source_face = default_source_face()
73
+ for map in modules.globals.souce_target_map:
74
+ target_face = map['target']['face']
75
+ temp_frame = swap_face(source_face, target_face, temp_frame)
76
+
77
+ elif not modules.globals.many_faces:
78
+ for map in modules.globals.souce_target_map:
79
+ if "source" in map:
80
+ source_face = map['source']['face']
81
+ target_face = map['target']['face']
82
+ temp_frame = swap_face(source_face, target_face, temp_frame)
83
+
84
+ elif is_video(modules.globals.target_path):
85
+ if modules.globals.many_faces:
86
+ source_face = default_source_face()
87
+ for map in modules.globals.souce_target_map:
88
+ target_frame = [f for f in map['target_faces_in_frame'] if f['location'] == temp_frame_path]
89
+
90
+ for frame in target_frame:
91
+ for target_face in frame['faces']:
92
+ temp_frame = swap_face(source_face, target_face, temp_frame)
93
+
94
+ elif not modules.globals.many_faces:
95
+ for map in modules.globals.souce_target_map:
96
+ if "source" in map:
97
+ target_frame = [f for f in map['target_faces_in_frame'] if f['location'] == temp_frame_path]
98
+ source_face = map['source']['face']
99
+
100
+ for frame in target_frame:
101
+ for target_face in frame['faces']:
102
+ temp_frame = swap_face(source_face, target_face, temp_frame)
103
+ else:
104
+ detected_faces = get_many_faces(temp_frame)
105
+ if modules.globals.many_faces:
106
+ if detected_faces:
107
+ source_face = default_source_face()
108
+ for target_face in detected_faces:
109
+ temp_frame = swap_face(source_face, target_face, temp_frame)
110
+
111
+ elif not modules.globals.many_faces:
112
+ if detected_faces:
113
+ if len(detected_faces) <= len(modules.globals.simple_map['target_embeddings']):
114
+ for detected_face in detected_faces:
115
+ closest_centroid_index, _ = find_closest_centroid(modules.globals.simple_map['target_embeddings'], detected_face.normed_embedding)
116
+
117
+ temp_frame = swap_face(modules.globals.simple_map['source_faces'][closest_centroid_index], detected_face, temp_frame)
118
+ else:
119
+ detected_faces_centroids = []
120
+ for face in detected_faces:
121
+ detected_faces_centroids.append(face.normed_embedding)
122
+ i = 0
123
+ for target_embedding in modules.globals.simple_map['target_embeddings']:
124
+ closest_centroid_index, _ = find_closest_centroid(detected_faces_centroids, target_embedding)
125
+
126
+ temp_frame = swap_face(modules.globals.simple_map['source_faces'][i], detected_faces[closest_centroid_index], temp_frame)
127
+ i += 1
128
+ return temp_frame
129
+
130
+
131
+ def process_frames(source_path: str, temp_frame_paths: List[str], progress: Any = None) -> None:
132
+ if not modules.globals.map_faces:
133
+ source_face = get_one_face(cv2.imread(source_path))
134
+ for temp_frame_path in temp_frame_paths:
135
+ temp_frame = cv2.imread(temp_frame_path)
136
+ try:
137
+ result = process_frame(source_face, temp_frame)
138
+ cv2.imwrite(temp_frame_path, result)
139
+ except Exception as exception:
140
+ print(exception)
141
+ pass
142
+ if progress:
143
+ progress.update(1)
144
+ else:
145
+ for temp_frame_path in temp_frame_paths:
146
+ temp_frame = cv2.imread(temp_frame_path)
147
+ try:
148
+ result = process_frame_v2(temp_frame, temp_frame_path)
149
+ cv2.imwrite(temp_frame_path, result)
150
+ except Exception as exception:
151
+ print(exception)
152
+ pass
153
+ if progress:
154
+ progress.update(1)
155
+
156
+
157
+ def process_image(source_path: str, target_path: str, output_path: str) -> None:
158
+ if not modules.globals.map_faces:
159
+ source_face = get_one_face(cv2.imread(source_path))
160
+ target_frame = cv2.imread(target_path)
161
+ result = process_frame(source_face, target_frame)
162
+ cv2.imwrite(output_path, result)
163
+ else:
164
+ if modules.globals.many_faces:
165
+ update_status('Many faces enabled. Using first source image. Progressing...', NAME)
166
+ target_frame = cv2.imread(output_path)
167
+ result = process_frame_v2(target_frame)
168
+ cv2.imwrite(output_path, result)
169
+
170
+
171
+ def process_video(source_path: str, temp_frame_paths: List[str]) -> None:
172
+ if modules.globals.map_faces and modules.globals.many_faces:
173
+ update_status('Many faces enabled. Using first source image. Progressing...', NAME)
174
+ modules.processors.frame.core.process_video(source_path, temp_frame_paths, process_frames)
modules/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]
modules/ui.json ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "CTk": {
3
+ "fg_color": ["gray95", "gray10"]
4
+ },
5
+ "CTkToplevel": {
6
+ "fg_color": ["gray95", "gray10"]
7
+ },
8
+ "CTkFrame": {
9
+ "corner_radius": 0,
10
+ "border_width": 0,
11
+ "fg_color": ["gray90", "gray13"],
12
+ "top_fg_color": ["gray85", "gray16"],
13
+ "border_color": ["gray65", "gray28"]
14
+ },
15
+ "CTkButton": {
16
+ "corner_radius": 0,
17
+ "border_width": 0,
18
+ "fg_color": ["#2aa666", "#1f538d"],
19
+ "hover_color": ["#3cb666", "#14375e"],
20
+ "border_color": ["#3e4a40", "#949A9F"],
21
+ "text_color": ["#f3faf6", "#f3faf6"],
22
+ "text_color_disabled": ["gray74", "gray60"]
23
+ },
24
+ "CTkLabel": {
25
+ "corner_radius": 0,
26
+ "fg_color": "transparent",
27
+ "text_color": ["gray14", "gray84"]
28
+ },
29
+ "CTkEntry": {
30
+ "corner_radius": 0,
31
+ "border_width": 2,
32
+ "fg_color": ["#F9F9FA", "#343638"],
33
+ "border_color": ["#979DA2", "#565B5E"],
34
+ "text_color": ["gray14", "gray84"],
35
+ "placeholder_text_color": ["gray52", "gray62"]
36
+ },
37
+ "CTkCheckbox": {
38
+ "corner_radius": 0,
39
+ "border_width": 3,
40
+ "fg_color": ["#2aa666", "#1f538d"],
41
+ "border_color": ["#3e4a40", "#949A9F"],
42
+ "hover_color": ["#3cb666", "#14375e"],
43
+ "checkmark_color": ["#f3faf6", "gray90"],
44
+ "text_color": ["gray14", "gray84"],
45
+ "text_color_disabled": ["gray60", "gray45"]
46
+ },
47
+ "CTkSwitch": {
48
+ "corner_radius": 1000,
49
+ "border_width": 3,
50
+ "button_length": 0,
51
+ "fg_color": ["#939BA2", "#4A4D50"],
52
+ "progress_color": ["#2aa666", "#1f538d"],
53
+ "button_color": ["gray36", "#D5D9DE"],
54
+ "button_hover_color": ["gray20", "gray100"],
55
+ "text_color": ["gray14", "gray84"],
56
+ "text_color_disabled": ["gray60", "gray45"]
57
+ },
58
+ "CTkRadiobutton": {
59
+ "corner_radius": 1000,
60
+ "border_width_checked": 6,
61
+ "border_width_unchecked": 3,
62
+ "fg_color": ["#2aa666", "#1f538d"],
63
+ "border_color": ["#3e4a40", "#949A9F"],
64
+ "hover_color": ["#3cb666", "#14375e"],
65
+ "text_color": ["gray14", "gray84"],
66
+ "text_color_disabled": ["gray60", "gray45"]
67
+ },
68
+ "CTkProgressBar": {
69
+ "corner_radius": 1000,
70
+ "border_width": 0,
71
+ "fg_color": ["#939BA2", "#4A4D50"],
72
+ "progress_color": ["#2aa666", "#1f538d"],
73
+ "border_color": ["gray", "gray"]
74
+ },
75
+ "CTkSlider": {
76
+ "corner_radius": 1000,
77
+ "button_corner_radius": 1000,
78
+ "border_width": 6,
79
+ "button_length": 0,
80
+ "fg_color": ["#939BA2", "#4A4D50"],
81
+ "progress_color": ["gray40", "#AAB0B5"],
82
+ "button_color": ["#2aa666", "#1f538d"],
83
+ "button_hover_color": ["#3cb666", "#14375e"]
84
+ },
85
+ "CTkOptionMenu": {
86
+ "corner_radius": 0,
87
+ "fg_color": ["#2aa666", "#1f538d"],
88
+ "button_color": ["#3cb666", "#14375e"],
89
+ "button_hover_color": ["#234567", "#1e2c40"],
90
+ "text_color": ["#f3faf6", "#f3faf6"],
91
+ "text_color_disabled": ["gray74", "gray60"]
92
+ },
93
+ "CTkComboBox": {
94
+ "corner_radius": 0,
95
+ "border_width": 2,
96
+ "fg_color": ["#F9F9FA", "#343638"],
97
+ "border_color": ["#979DA2", "#565B5E"],
98
+ "button_color": ["#979DA2", "#565B5E"],
99
+ "button_hover_color": ["#6E7174", "#7A848D"],
100
+ "text_color": ["gray14", "gray84"],
101
+ "text_color_disabled": ["gray50", "gray45"]
102
+ },
103
+ "CTkScrollbar": {
104
+ "corner_radius": 1000,
105
+ "border_spacing": 4,
106
+ "fg_color": "transparent",
107
+ "button_color": ["gray55", "gray41"],
108
+ "button_hover_color": ["gray40", "gray53"]
109
+ },
110
+ "CTkSegmentedButton": {
111
+ "corner_radius": 0,
112
+ "border_width": 2,
113
+ "fg_color": ["#979DA2", "gray29"],
114
+ "selected_color": ["#2aa666", "#1f538d"],
115
+ "selected_hover_color": ["#3cb666", "#14375e"],
116
+ "unselected_color": ["#979DA2", "gray29"],
117
+ "unselected_hover_color": ["gray70", "gray41"],
118
+ "text_color": ["#f3faf6", "#f3faf6"],
119
+ "text_color_disabled": ["gray74", "gray60"]
120
+ },
121
+ "CTkTextbox": {
122
+ "corner_radius": 0,
123
+ "border_width": 0,
124
+ "fg_color": ["gray100", "gray20"],
125
+ "border_color": ["#979DA2", "#565B5E"],
126
+ "text_color": ["gray14", "gray84"],
127
+ "scrollbar_button_color": ["gray55", "gray41"],
128
+ "scrollbar_button_hover_color": ["gray40", "gray53"]
129
+ },
130
+ "CTkScrollableFrame": {
131
+ "label_fg_color": ["gray80", "gray21"]
132
+ },
133
+ "DropdownMenu": {
134
+ "fg_color": ["gray90", "gray20"],
135
+ "hover_color": ["gray75", "gray28"],
136
+ "text_color": ["gray14", "gray84"]
137
+ },
138
+ "CTkFont": {
139
+ "macOS": {
140
+ "family": "Avenir",
141
+ "size": 18,
142
+ "weight": "normal"
143
+ },
144
+ "Windows": {
145
+ "family": "Corbel",
146
+ "size": 18,
147
+ "weight": "normal"
148
+ },
149
+ "Linux": {
150
+ "family": "Montserrat",
151
+ "size": 18,
152
+ "weight": "normal"
153
+ }
154
+ },
155
+ "URL": {
156
+ "text_color": ["gray74", "gray60"]
157
+ }
158
+ }
modules/ui.py ADDED
@@ -0,0 +1,1262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import webbrowser
3
+ import customtkinter as ctk
4
+ from typing import Callable, Tuple
5
+ import cv2
6
+ from PIL import Image, ImageOps
7
+ import tkinterdnd2 as tkdnd
8
+
9
+ import modules.globals
10
+ import modules.metadata
11
+ from modules.face_analyser import (
12
+ get_one_face,
13
+ get_unique_faces_from_target_image,
14
+ get_unique_faces_from_target_video,
15
+ add_blank_map,
16
+ has_valid_map,
17
+ simplify_maps,
18
+ )
19
+ from modules.capturer import get_video_frame, get_video_frame_total
20
+ from modules.processors.frame.core import get_frame_processors_modules
21
+ from modules.utilities import (
22
+ is_image,
23
+ is_video,
24
+ resolve_relative_path,
25
+ has_image_extension,
26
+ )
27
+
28
+ os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"
29
+ os.environ["QT_SCREEN_SCALE_FACTORS"] = "1"
30
+ os.environ["QT_SCALE_FACTOR"] = "1"
31
+
32
+ ROOT = None
33
+ POPUP = None
34
+ POPUP_LIVE = None
35
+ ROOT_HEIGHT = 800
36
+ ROOT_WIDTH = 1000
37
+
38
+ PREVIEW = None
39
+ PREVIEW_MAX_HEIGHT = 800
40
+ PREVIEW_MAX_WIDTH = 1400
41
+ PREVIEW_DEFAULT_WIDTH = 1280
42
+ PREVIEW_DEFAULT_HEIGHT = 720
43
+
44
+ POPUP_WIDTH = 700
45
+ POPUP_HEIGHT = 800
46
+ POPUP_SCROLL_WIDTH = 680
47
+ POPUP_SCROLL_HEIGHT = 600
48
+
49
+ POPUP_LIVE_WIDTH = 850
50
+ POPUP_LIVE_HEIGHT = 700
51
+ POPUP_LIVE_SCROLL_WIDTH = 830
52
+ POPUP_LIVE_SCROLL_HEIGHT = 600
53
+
54
+ MAPPER_PREVIEW_MAX_HEIGHT = 120
55
+ MAPPER_PREVIEW_MAX_WIDTH = 120
56
+
57
+ DEFAULT_BUTTON_WIDTH = 200
58
+ DEFAULT_BUTTON_HEIGHT = 40
59
+
60
+ RECENT_DIRECTORY_SOURCE = None
61
+ RECENT_DIRECTORY_TARGET = None
62
+ RECENT_DIRECTORY_OUTPUT = None
63
+
64
+ preview_label = None
65
+ preview_slider = None
66
+ source_label = None
67
+ target_label = None
68
+ status_label = None
69
+ popup_status_label = None
70
+ popup_status_label_live = None
71
+ source_label_dict = {}
72
+ source_label_dict_live = {}
73
+ target_label_dict_live = {}
74
+
75
+ img_ft, vid_ft = modules.globals.file_types
76
+
77
+
78
+ class ModernButton(ctk.CTkButton):
79
+ def __init__(self, master, **kwargs):
80
+ super().__init__(master, **kwargs)
81
+ self.configure(
82
+ font=("Roboto", 16, "bold"),
83
+ corner_radius=15,
84
+ border_width=2,
85
+ border_color="#3a7ebf",
86
+ hover_color="#2b5d8b",
87
+ fg_color="#3a7ebf",
88
+ text_color="white",
89
+ )
90
+
91
+
92
+ class DragDropButton(ModernButton):
93
+ def __init__(self, master, **kwargs):
94
+ super().__init__(master, **kwargs)
95
+ self.drop_target_register(tkdnd.DND_FILES)
96
+ self.dnd_bind("<<Drop>>", self.drop)
97
+
98
+ def drop(self, event):
99
+ file_path = event.data
100
+ if file_path.startswith("{"):
101
+ file_path = file_path[1:-1]
102
+ self.handle_drop(file_path)
103
+
104
+ def handle_drop(self, file_path):
105
+ pass
106
+
107
+
108
+ class SourceButton(DragDropButton):
109
+ def handle_drop(self, file_path):
110
+ if is_image(file_path):
111
+ modules.globals.source_path = file_path
112
+ global RECENT_DIRECTORY_SOURCE
113
+ RECENT_DIRECTORY_SOURCE = os.path.dirname(modules.globals.source_path)
114
+ image = render_image_preview(modules.globals.source_path, (250, 250))
115
+ source_label.configure(image=image)
116
+ source_label.configure(text="")
117
+
118
+
119
+ class SourceMapperButton(DragDropButton):
120
+ def __init__(self, master, map, button_num, **kwargs):
121
+ super().__init__(master, **kwargs)
122
+ self.map = map
123
+ self.button_num = button_num
124
+
125
+ def handle_drop(self, file_path):
126
+ if is_image(file_path):
127
+ update_popup_source(
128
+ self.master.master, self.map, self.button_num, file_path
129
+ )
130
+
131
+
132
+ class TargetButton(DragDropButton):
133
+ def handle_drop(self, file_path):
134
+ global RECENT_DIRECTORY_TARGET
135
+ if is_image(file_path) or is_video(file_path):
136
+ modules.globals.target_path = file_path
137
+ RECENT_DIRECTORY_TARGET = os.path.dirname(modules.globals.target_path)
138
+ if is_image(file_path):
139
+ image = render_image_preview(modules.globals.target_path, (250, 250))
140
+ target_label.configure(image=image)
141
+ target_label.configure(text="")
142
+ elif is_video(file_path):
143
+ video_frame = render_video_preview(file_path, (250, 250))
144
+ target_label.configure(image=video_frame)
145
+ target_label.configure(text="")
146
+
147
+
148
+ class ModernLabel(ctk.CTkLabel):
149
+ def __init__(self, master, **kwargs):
150
+ super().__init__(master, **kwargs)
151
+ self.configure(
152
+ font=("Roboto", 16),
153
+ corner_radius=10,
154
+ fg_color="#2a2d2e",
155
+ text_color="white",
156
+ )
157
+
158
+
159
+ class DragDropLabel(ModernLabel):
160
+ def __init__(self, master, **kwargs):
161
+ super().__init__(master, **kwargs)
162
+ self.drop_target_register(tkdnd.DND_FILES)
163
+ self.dnd_bind("<<Drop>>", self.drop)
164
+
165
+ def drop(self, event):
166
+ file_path = event.data
167
+ if file_path.startswith("{"):
168
+ file_path = file_path[1:-1]
169
+ self.handle_drop(file_path)
170
+
171
+ def handle_drop(self, file_path):
172
+ pass
173
+
174
+
175
+ class SourceLabel(DragDropLabel):
176
+ def handle_drop(self, file_path):
177
+ if is_image(file_path):
178
+ modules.globals.source_path = file_path
179
+ global RECENT_DIRECTORY_SOURCE
180
+ RECENT_DIRECTORY_SOURCE = os.path.dirname(modules.globals.source_path)
181
+ image = render_image_preview(modules.globals.source_path, (250, 250))
182
+ source_label.configure(image=image)
183
+ source_label.configure(text="")
184
+
185
+
186
+ class TargetLabel(DragDropLabel):
187
+ def handle_drop(self, file_path):
188
+ global RECENT_DIRECTORY_TARGET
189
+ if is_image(file_path) or is_video(file_path):
190
+ modules.globals.target_path = file_path
191
+ RECENT_DIRECTORY_TARGET = os.path.dirname(modules.globals.target_path)
192
+ if is_image(file_path):
193
+ image = render_image_preview(modules.globals.target_path, (250, 250))
194
+ target_label.configure(image=image)
195
+ target_label.configure(text="")
196
+ elif is_video(file_path):
197
+ video_frame = render_video_preview(file_path, (250, 250))
198
+ target_label.configure(image=video_frame)
199
+ target_label.configure(text="")
200
+
201
+
202
+ def init(start: Callable[[], None], destroy: Callable[[], None]) -> tkdnd.TkinterDnD.Tk:
203
+ global ROOT, PREVIEW
204
+
205
+ ROOT = create_root(start, destroy)
206
+ PREVIEW = create_preview(ROOT)
207
+
208
+ return ROOT
209
+
210
+
211
+ def create_root(
212
+ start: Callable[[], None], destroy: Callable[[], None]
213
+ ) -> tkdnd.TkinterDnD.Tk:
214
+ global source_label, target_label, status_label
215
+
216
+ ctk.set_appearance_mode("dark")
217
+ ctk.set_default_color_theme("blue")
218
+
219
+ root = tkdnd.TkinterDnD.Tk()
220
+ root.title(
221
+ f"{modules.metadata.name} {modules.metadata.version} {modules.metadata.edition}"
222
+ )
223
+ root.configure(bg="#1a1a1a")
224
+ root.protocol("WM_DELETE_WINDOW", lambda: destroy())
225
+ root.resizable(True, True)
226
+ root.attributes("-alpha", 1.0) # Set window opacity to fully opaque
227
+
228
+ main_frame = ctk.CTkFrame(root, fg_color="#1a1a1a")
229
+ main_frame.pack(fill="both", expand=True, padx=20, pady=20)
230
+
231
+ # Create two vertical frames for source and target
232
+ source_frame = ctk.CTkFrame(main_frame, fg_color="#2a2d2e", corner_radius=15)
233
+ source_frame.grid(row=0, column=0, padx=10, pady=10, sticky="nsew")
234
+
235
+ target_frame = ctk.CTkFrame(main_frame, fg_color="#2a2d2e", corner_radius=15)
236
+ target_frame.grid(row=0, column=2, padx=10, pady=10, sticky="nsew")
237
+
238
+ # Create a middle frame for swap button
239
+ middle_frame = ctk.CTkFrame(main_frame, fg_color="#1a1a1a")
240
+ middle_frame.grid(row=0, column=1, padx=5, pady=10, sticky="ns")
241
+
242
+ source_label = SourceLabel(
243
+ source_frame,
244
+ text="Drag & Drop\nSource Image Here",
245
+ justify="center",
246
+ width=250,
247
+ height=250,
248
+ )
249
+ source_label.pack(pady=(20, 10))
250
+
251
+ target_label = TargetLabel(
252
+ target_frame,
253
+ text="Drag & Drop\nTarget Image/Video Here",
254
+ justify="center",
255
+ width=250,
256
+ height=250,
257
+ )
258
+ target_label.pack(pady=(20, 10))
259
+
260
+ select_face_button = SourceButton(
261
+ source_frame,
262
+ text="Select a face",
263
+ cursor="hand2",
264
+ command=lambda: select_source_path(),
265
+ )
266
+ select_face_button.pack(pady=10)
267
+
268
+ select_target_button = TargetButton(
269
+ target_frame,
270
+ text="Select a target",
271
+ cursor="hand2",
272
+ command=lambda: select_target_path(),
273
+ )
274
+ select_target_button.pack(pady=10)
275
+
276
+ swap_faces_button = ModernButton(
277
+ middle_frame,
278
+ text="↔",
279
+ cursor="hand2",
280
+ command=lambda: swap_faces_paths(),
281
+ width=50,
282
+ height=50,
283
+ )
284
+ swap_faces_button.pack(expand=True)
285
+
286
+ options_frame = ctk.CTkFrame(main_frame, fg_color="#2a2d2e", corner_radius=15)
287
+ options_frame.grid(row=1, column=0, columnspan=3, padx=10, pady=10, sticky="nsew")
288
+
289
+ # Create a single column for options, centered
290
+ options_column = ctk.CTkFrame(options_frame, fg_color="#2a2d2e")
291
+ options_column.pack(expand=True)
292
+
293
+ # Switches
294
+ keep_fps_value = ctk.BooleanVar(value=modules.globals.keep_fps)
295
+ keep_fps_checkbox = ctk.CTkSwitch(
296
+ options_column,
297
+ text="Keep fps",
298
+ variable=keep_fps_value,
299
+ cursor="hand2",
300
+ command=lambda: setattr(
301
+ modules.globals, "keep_fps", not modules.globals.keep_fps
302
+ ),
303
+ progress_color="#3a7ebf",
304
+ font=("Roboto", 14, "bold"),
305
+ )
306
+ keep_fps_checkbox.pack(pady=5, anchor="w")
307
+
308
+ keep_frames_value = ctk.BooleanVar(value=modules.globals.keep_frames)
309
+ keep_frames_switch = ctk.CTkSwitch(
310
+ options_column,
311
+ text="Keep frames",
312
+ variable=keep_frames_value,
313
+ cursor="hand2",
314
+ command=lambda: setattr(
315
+ modules.globals, "keep_frames", keep_frames_value.get()
316
+ ),
317
+ progress_color="#3a7ebf",
318
+ font=("Roboto", 14, "bold"),
319
+ )
320
+ keep_frames_switch.pack(pady=5, anchor="w")
321
+
322
+ enhancer_value = ctk.BooleanVar(value=modules.globals.fp_ui["face_enhancer"])
323
+ enhancer_switch = ctk.CTkSwitch(
324
+ options_column,
325
+ text="Face Enhancer",
326
+ variable=enhancer_value,
327
+ cursor="hand2",
328
+ command=lambda: update_tumbler("face_enhancer", enhancer_value.get()),
329
+ progress_color="#3a7ebf",
330
+ font=("Roboto", 14, "bold"),
331
+ )
332
+ enhancer_switch.pack(pady=5, anchor="w")
333
+
334
+ keep_audio_value = ctk.BooleanVar(value=modules.globals.keep_audio)
335
+ keep_audio_switch = ctk.CTkSwitch(
336
+ options_column,
337
+ text="Keep audio",
338
+ variable=keep_audio_value,
339
+ cursor="hand2",
340
+ command=lambda: setattr(modules.globals, "keep_audio", keep_audio_value.get()),
341
+ progress_color="#3a7ebf",
342
+ font=("Roboto", 14, "bold"),
343
+ )
344
+ keep_audio_switch.pack(pady=5, anchor="w")
345
+
346
+ many_faces_value = ctk.BooleanVar(value=modules.globals.many_faces)
347
+ many_faces_switch = ctk.CTkSwitch(
348
+ options_column,
349
+ text="Many faces",
350
+ variable=many_faces_value,
351
+ cursor="hand2",
352
+ command=lambda: setattr(modules.globals, "many_faces", many_faces_value.get()),
353
+ progress_color="#3a7ebf",
354
+ font=("Roboto", 14, "bold"),
355
+ )
356
+ many_faces_switch.pack(pady=5, anchor="w")
357
+
358
+ color_correction_value = ctk.BooleanVar(value=modules.globals.color_correction)
359
+ color_correction_switch = ctk.CTkSwitch(
360
+ options_column,
361
+ text="Fix Blueish Cam",
362
+ variable=color_correction_value,
363
+ cursor="hand2",
364
+ command=lambda: setattr(
365
+ modules.globals, "color_correction", color_correction_value.get()
366
+ ),
367
+ progress_color="#3a7ebf",
368
+ font=("Roboto", 14, "bold"),
369
+ )
370
+ color_correction_switch.pack(pady=5, anchor="w")
371
+
372
+ map_faces = ctk.BooleanVar(value=modules.globals.map_faces)
373
+ map_faces_switch = ctk.CTkSwitch(
374
+ options_column,
375
+ text="Map faces",
376
+ variable=map_faces,
377
+ cursor="hand2",
378
+ command=lambda: setattr(modules.globals, "map_faces", map_faces.get()),
379
+ progress_color="#3a7ebf",
380
+ font=("Roboto", 14, "bold"),
381
+ )
382
+ map_faces_switch.pack(pady=5, anchor="w")
383
+
384
+ button_frame = ctk.CTkFrame(main_frame, fg_color="#1a1a1a")
385
+ button_frame.grid(row=2, column=0, columnspan=3, padx=10, pady=10, sticky="nsew")
386
+
387
+ start_button = ModernButton(
388
+ button_frame,
389
+ text="Start",
390
+ cursor="hand2",
391
+ command=lambda: analyze_target(start, root),
392
+ fg_color="#4CAF50",
393
+ hover_color="#45a049",
394
+ )
395
+ start_button.pack(side="left", padx=10, expand=True)
396
+
397
+ preview_button = ModernButton(
398
+ button_frame,
399
+ text="Preview",
400
+ cursor="hand2",
401
+ command=lambda: toggle_preview(),
402
+ )
403
+ preview_button.pack(side="left", padx=10, expand=True)
404
+
405
+ live_button = ModernButton(
406
+ button_frame,
407
+ text="Live",
408
+ cursor="hand2",
409
+ command=lambda: webcam_preview(root),
410
+ )
411
+ live_button.pack(side="left", padx=10, expand=True)
412
+
413
+ stop_button = ModernButton(
414
+ button_frame,
415
+ text="Destroy",
416
+ cursor="hand2",
417
+ command=lambda: destroy(),
418
+ fg_color="#f44336",
419
+ hover_color="#d32f2f",
420
+ )
421
+ stop_button.pack(side="left", padx=10, expand=True)
422
+
423
+ status_label = ModernLabel(
424
+ main_frame, text=None, justify="center", fg_color="#1a1a1a"
425
+ )
426
+ status_label.grid(row=3, column=0, columnspan=3, pady=10, sticky="ew")
427
+
428
+ donate_frame = ctk.CTkFrame(main_frame, fg_color="#1a1a1a")
429
+ donate_frame.grid(row=4, column=0, columnspan=3, pady=5, sticky="ew")
430
+
431
+ donate_label = ModernLabel(
432
+ donate_frame,
433
+ text="Donate",
434
+ justify="center",
435
+ cursor="hand2",
436
+ fg_color="#1870c4",
437
+ text_color="#1870c4",
438
+ )
439
+ donate_label.pack(side="left", expand=True)
440
+
441
+ donate_label.bind(
442
+ "<Button>", lambda event: webbrowser.open("https://paypal.me/hacksider")
443
+ )
444
+
445
+ remove_donate_button = ModernButton(
446
+ donate_frame,
447
+ text="X",
448
+ cursor="hand2",
449
+ command=lambda: donate_frame.destroy(),
450
+ width=30,
451
+ height=30,
452
+ fg_color="#f44336",
453
+ hover_color="#d32f2f",
454
+ )
455
+ remove_donate_button.pack(side="right", padx=(10, 0))
456
+
457
+ main_frame.grid_columnconfigure((0, 2), weight=1)
458
+ main_frame.grid_rowconfigure((0, 1, 2), weight=1)
459
+
460
+ root.grid_columnconfigure(0, weight=1)
461
+ root.grid_rowconfigure(0, weight=1)
462
+
463
+ return root
464
+
465
+
466
+ def analyze_target(start: Callable[[], None], root: ctk.CTk):
467
+ if POPUP is not None and POPUP.winfo_exists():
468
+ update_status("Please complete pop-up or close it.")
469
+ return
470
+
471
+ if modules.globals.map_faces:
472
+ modules.globals.souce_target_map = []
473
+
474
+ if is_image(modules.globals.target_path):
475
+ update_status("Getting unique faces")
476
+ get_unique_faces_from_target_image()
477
+ elif is_video(modules.globals.target_path):
478
+ update_status("Getting unique faces")
479
+ get_unique_faces_from_target_video()
480
+ else:
481
+ update_status("Invalid target file. Please select an image or video.")
482
+ return
483
+
484
+ if len(modules.globals.souce_target_map) > 0:
485
+ create_source_target_popup(start, root, modules.globals.souce_target_map)
486
+ else:
487
+ update_status("No faces found in target")
488
+ else:
489
+ select_output_path(start)
490
+
491
+
492
+ def create_source_target_popup(
493
+ start: Callable[[], None], root: ctk.CTk, map: list
494
+ ) -> None:
495
+ global POPUP, popup_status_label
496
+
497
+ POPUP = ctk.CTkToplevel(root)
498
+ POPUP.title("Source x Target Mapper")
499
+ POPUP.geometry(f"{POPUP_WIDTH}x{POPUP_HEIGHT}")
500
+ POPUP.focus()
501
+ POPUP.resizable(True, True)
502
+
503
+ def on_submit_click(start):
504
+ if has_valid_map():
505
+ POPUP.destroy()
506
+ select_output_path(start)
507
+ else:
508
+ update_pop_status("At least 1 source with target is required!")
509
+
510
+ scrollable_frame = ctk.CTkScrollableFrame(
511
+ POPUP, width=POPUP_SCROLL_WIDTH, height=POPUP_SCROLL_HEIGHT
512
+ )
513
+ scrollable_frame.pack(fill="both", expand=True, padx=10, pady=10)
514
+
515
+ def on_button_click(map, button_num):
516
+ update_popup_source(scrollable_frame, map, button_num)
517
+
518
+ # Create a frame to hold the table
519
+ table_frame = ctk.CTkFrame(scrollable_frame)
520
+ table_frame.pack(expand=True)
521
+
522
+ for item in map:
523
+ id = item["id"]
524
+
525
+ row_frame = ctk.CTkFrame(table_frame)
526
+ row_frame.pack(fill="x", pady=5)
527
+
528
+ source_button = SourceMapperButton(
529
+ row_frame,
530
+ map,
531
+ id,
532
+ text="Select source image",
533
+ command=lambda id=id: on_button_click(map, id),
534
+ width=DEFAULT_BUTTON_WIDTH,
535
+ height=DEFAULT_BUTTON_HEIGHT,
536
+ fg_color=("gray75", "gray25"),
537
+ hover_color=("gray85", "gray35"),
538
+ corner_radius=10,
539
+ )
540
+ source_button.pack(side="left", padx=(0, 10))
541
+
542
+ source_image = ctk.CTkLabel(
543
+ row_frame,
544
+ text=f"S-{id}",
545
+ width=MAPPER_PREVIEW_MAX_WIDTH,
546
+ height=MAPPER_PREVIEW_MAX_HEIGHT,
547
+ font=("Arial", 14, "bold"),
548
+ )
549
+ source_image.pack(side="left", padx=(0, 10))
550
+
551
+ x_label = ctk.CTkLabel(
552
+ row_frame,
553
+ text=f"X",
554
+ width=30,
555
+ font=("Arial", 14, "bold"),
556
+ )
557
+ x_label.pack(side="left", padx=(0, 10))
558
+
559
+ image = Image.fromarray(cv2.cvtColor(item["target"]["cv2"], cv2.COLOR_BGR2RGB))
560
+ image = image.resize(
561
+ (MAPPER_PREVIEW_MAX_WIDTH, MAPPER_PREVIEW_MAX_HEIGHT), Image.LANCZOS
562
+ )
563
+ tk_image = ctk.CTkImage(image, size=image.size)
564
+
565
+ target_image = ctk.CTkLabel(
566
+ row_frame,
567
+ text=f"T-{id}",
568
+ width=MAPPER_PREVIEW_MAX_WIDTH,
569
+ height=MAPPER_PREVIEW_MAX_HEIGHT,
570
+ font=("Arial", 14, "bold"),
571
+ )
572
+ target_image.pack(side="left")
573
+ target_image.configure(image=tk_image)
574
+
575
+ popup_status_label = ctk.CTkLabel(
576
+ POPUP, text=None, justify="center", font=("Arial", 14, "bold")
577
+ )
578
+ popup_status_label.pack(pady=10)
579
+
580
+ submit_button = ctk.CTkButton(
581
+ POPUP,
582
+ text="Submit",
583
+ command=lambda: on_submit_click(start),
584
+ fg_color=("DodgerBlue", "DodgerBlue"),
585
+ hover_color=("RoyalBlue", "RoyalBlue"),
586
+ corner_radius=10,
587
+ font=("Arial", 16, "bold"),
588
+ width=200,
589
+ height=50,
590
+ )
591
+ submit_button.pack(pady=10)
592
+
593
+ POPUP.update()
594
+ POPUP.minsize(POPUP.winfo_width(), POPUP.winfo_height())
595
+
596
+
597
+ def update_popup_source(
598
+ scrollable_frame: ctk.CTkScrollableFrame,
599
+ map: list,
600
+ button_num: int,
601
+ source_path: str = None,
602
+ ) -> list:
603
+ global source_label_dict, RECENT_DIRECTORY_SOURCE
604
+
605
+ if source_path is None:
606
+ source_path = ctk.filedialog.askopenfilename(
607
+ title="select an source image",
608
+ initialdir=RECENT_DIRECTORY_SOURCE,
609
+ filetypes=[img_ft],
610
+ )
611
+
612
+ if "source" in map[button_num]:
613
+ map[button_num].pop("source")
614
+ if button_num in source_label_dict:
615
+ source_label_dict[button_num].destroy()
616
+ del source_label_dict[button_num]
617
+
618
+ if source_path == "":
619
+ return map
620
+ else:
621
+ RECENT_DIRECTORY_SOURCE = os.path.dirname(source_path)
622
+ cv2_img = cv2.imread(source_path)
623
+ face = get_one_face(cv2_img)
624
+
625
+ if face:
626
+ x_min, y_min, x_max, y_max = face["bbox"]
627
+
628
+ map[button_num]["source"] = {
629
+ "cv2": cv2_img[int(y_min) : int(y_max), int(x_min) : int(x_max)],
630
+ "face": face,
631
+ }
632
+
633
+ image = Image.fromarray(
634
+ cv2.cvtColor(map[button_num]["source"]["cv2"], cv2.COLOR_BGR2RGB)
635
+ )
636
+ image = image.resize(
637
+ (MAPPER_PREVIEW_MAX_WIDTH, MAPPER_PREVIEW_MAX_HEIGHT), Image.LANCZOS
638
+ )
639
+ tk_image = ctk.CTkImage(image, size=image.size)
640
+
641
+ source_image = ctk.CTkLabel(
642
+ scrollable_frame.winfo_children()[button_num],
643
+ text=f"S-{button_num}",
644
+ width=MAPPER_PREVIEW_MAX_WIDTH,
645
+ height=MAPPER_PREVIEW_MAX_HEIGHT,
646
+ font=("Arial", 14, "bold"),
647
+ )
648
+ source_image.pack(
649
+ side="left",
650
+ padx=(0, 10),
651
+ after=scrollable_frame.winfo_children()[button_num].winfo_children()[0],
652
+ )
653
+ source_image.configure(image=tk_image)
654
+ source_label_dict[button_num] = source_image
655
+ else:
656
+ update_pop_status("Face could not be detected in last upload!")
657
+ return map
658
+
659
+
660
+ def create_preview(parent: ctk.CTkToplevel) -> ctk.CTkToplevel:
661
+ global preview_label, preview_slider
662
+
663
+ preview = ctk.CTkToplevel(parent)
664
+ preview.withdraw()
665
+ preview.title("Preview")
666
+ preview.configure()
667
+ preview.protocol("WM_DELETE_WINDOW", lambda: toggle_preview())
668
+ preview.resizable(width=True, height=True)
669
+
670
+ preview_label = ctk.CTkLabel(preview, text=None, font=("Arial", 14, "bold"))
671
+ preview_label.pack(fill="both", expand=True)
672
+
673
+ preview_slider = ctk.CTkSlider(
674
+ preview,
675
+ from_=0,
676
+ to=0,
677
+ command=lambda frame_value: update_preview(int(frame_value)),
678
+ fg_color=("gray75", "gray25"),
679
+ progress_color=("DodgerBlue", "DodgerBlue"),
680
+ button_color=("DodgerBlue", "DodgerBlue"),
681
+ button_hover_color=("RoyalBlue", "RoyalBlue"),
682
+ )
683
+ preview_slider.pack(fill="x", padx=20, pady=10)
684
+
685
+ return preview
686
+
687
+
688
+ def update_status(text: str) -> None:
689
+ status_label.configure(text=text)
690
+ ROOT.update()
691
+
692
+
693
+ def update_pop_status(text: str) -> None:
694
+ popup_status_label.configure(text=text)
695
+
696
+
697
+ def update_pop_live_status(text: str) -> None:
698
+ popup_status_label_live.configure(text=text)
699
+
700
+
701
+ def update_tumbler(var: str, value: bool) -> None:
702
+ modules.globals.fp_ui[var] = value
703
+
704
+
705
+ def select_source_path() -> None:
706
+ global RECENT_DIRECTORY_SOURCE, img_ft, vid_ft
707
+
708
+ PREVIEW.withdraw()
709
+ source_path = ctk.filedialog.askopenfilename(
710
+ title="select an source image",
711
+ initialdir=RECENT_DIRECTORY_SOURCE,
712
+ filetypes=[img_ft],
713
+ )
714
+ if is_image(source_path):
715
+ modules.globals.source_path = source_path
716
+ RECENT_DIRECTORY_SOURCE = os.path.dirname(modules.globals.source_path)
717
+ image = render_image_preview(modules.globals.source_path, (200, 200))
718
+ source_label.configure(image=image)
719
+ source_label.configure(text="")
720
+ else:
721
+ modules.globals.source_path = None
722
+ source_label.configure(image=None)
723
+ source_label.configure(text="Drag & Drop Source Image Here")
724
+
725
+
726
+ def swap_faces_paths() -> None:
727
+ global RECENT_DIRECTORY_SOURCE, RECENT_DIRECTORY_TARGET
728
+
729
+ source_path = modules.globals.source_path
730
+ target_path = modules.globals.target_path
731
+
732
+ if not is_image(source_path) or not is_image(target_path):
733
+ return
734
+
735
+ modules.globals.source_path = target_path
736
+ modules.globals.target_path = source_path
737
+
738
+ RECENT_DIRECTORY_SOURCE = os.path.dirname(modules.globals.source_path)
739
+ RECENT_DIRECTORY_TARGET = os.path.dirname(modules.globals.target_path)
740
+
741
+ PREVIEW.withdraw()
742
+
743
+ source_image = render_image_preview(modules.globals.source_path, (200, 200))
744
+ source_label.configure(image=source_image)
745
+ source_label.configure(text="")
746
+
747
+ target_image = render_image_preview(modules.globals.target_path, (200, 200))
748
+ target_label.configure(image=target_image)
749
+ target_label.configure(text="")
750
+
751
+
752
+ def select_target_path() -> None:
753
+ global RECENT_DIRECTORY_TARGET, img_ft, vid_ft
754
+
755
+ PREVIEW.withdraw()
756
+ target_path = ctk.filedialog.askopenfilename(
757
+ title="select an target image or video",
758
+ initialdir=RECENT_DIRECTORY_TARGET,
759
+ filetypes=[img_ft, vid_ft],
760
+ )
761
+ if is_image(target_path):
762
+ modules.globals.target_path = target_path
763
+ RECENT_DIRECTORY_TARGET = os.path.dirname(modules.globals.target_path)
764
+ image = render_image_preview(modules.globals.target_path, (200, 200))
765
+ target_label.configure(image=image)
766
+ target_label.configure(text="")
767
+ elif is_video(target_path):
768
+ modules.globals.target_path = target_path
769
+ RECENT_DIRECTORY_TARGET = os.path.dirname(modules.globals.target_path)
770
+ video_frame = render_video_preview(target_path, (200, 200))
771
+ target_label.configure(image=video_frame)
772
+ target_label.configure(text="")
773
+ else:
774
+ modules.globals.target_path = None
775
+ target_label.configure(image=None)
776
+ target_label.configure(text="Drag & Drop Target Image/Video Here")
777
+
778
+
779
+ def select_output_path(start: Callable[[], None]) -> None:
780
+ global RECENT_DIRECTORY_OUTPUT, img_ft, vid_ft
781
+
782
+ if is_image(modules.globals.target_path):
783
+ output_path = ctk.filedialog.asksaveasfilename(
784
+ title="save image output file",
785
+ filetypes=[img_ft],
786
+ defaultextension=".png",
787
+ initialfile="output.png",
788
+ initialdir=RECENT_DIRECTORY_OUTPUT,
789
+ )
790
+ elif is_video(modules.globals.target_path):
791
+ output_path = ctk.filedialog.asksaveasfilename(
792
+ title="save video output file",
793
+ filetypes=[vid_ft],
794
+ defaultextension=".mp4",
795
+ initialfile="output.mp4",
796
+ initialdir=RECENT_DIRECTORY_OUTPUT,
797
+ )
798
+ else:
799
+ output_path = None
800
+ if output_path:
801
+ modules.globals.output_path = output_path
802
+ RECENT_DIRECTORY_OUTPUT = os.path.dirname(modules.globals.output_path)
803
+ start()
804
+
805
+
806
+ def check_and_ignore_nsfw(target, destroy: Callable = None) -> bool:
807
+ """Check if the target is NSFW.
808
+ TODO: Consider to make blur the target.
809
+ """
810
+ from numpy import ndarray
811
+ from modules.predicter import predict_image, predict_video, predict_frame
812
+
813
+ if type(target) is str: # image/video file path
814
+ check_nsfw = predict_image if has_image_extension(target) else predict_video
815
+ elif type(target) is ndarray: # frame object
816
+ check_nsfw = predict_frame
817
+ if check_nsfw and check_nsfw(target):
818
+ if destroy:
819
+ destroy(
820
+ to_quit=False
821
+ ) # Do not need to destroy the window frame if the target is NSFW
822
+ update_status("Processing ignored!")
823
+ return True
824
+ else:
825
+ return False
826
+
827
+
828
+ def fit_image_to_size(image, width: int, height: int):
829
+ if width is None and height is None:
830
+ return image
831
+ h, w, _ = image.shape
832
+ ratio_h = 0.0
833
+ ratio_w = 0.0
834
+ if width > height:
835
+ ratio_h = height / h
836
+ else:
837
+ ratio_w = width / w
838
+ ratio = max(ratio_w, ratio_h)
839
+ new_size = (int(ratio * w), int(ratio * h))
840
+ return cv2.resize(image, dsize=new_size)
841
+
842
+
843
+ def render_image_preview(image_path: str, size: Tuple[int, int]) -> ctk.CTkImage:
844
+ image = Image.open(image_path)
845
+ if size:
846
+ image = ImageOps.fit(image, size, Image.LANCZOS)
847
+ return ctk.CTkImage(image, size=image.size)
848
+
849
+
850
+ def render_video_preview(
851
+ video_path: str, size: Tuple[int, int], frame_number: int = 0
852
+ ) -> ctk.CTkImage:
853
+ capture = cv2.VideoCapture(video_path)
854
+ if frame_number:
855
+ capture.set(cv2.CAP_PROP_POS_FRAMES, frame_number)
856
+ has_frame, frame = capture.read()
857
+ if has_frame:
858
+ image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
859
+ if size:
860
+ image = ImageOps.fit(image, size, Image.LANCZOS)
861
+ return ctk.CTkImage(image, size=image.size)
862
+ capture.release()
863
+ cv2.destroyAllWindows()
864
+
865
+
866
+ def toggle_preview() -> None:
867
+ if PREVIEW.state() == "normal":
868
+ PREVIEW.withdraw()
869
+ elif modules.globals.source_path and modules.globals.target_path:
870
+ init_preview()
871
+ update_preview()
872
+
873
+
874
+ def init_preview() -> None:
875
+ if is_image(modules.globals.target_path):
876
+ preview_slider.pack_forget()
877
+ if is_video(modules.globals.target_path):
878
+ video_frame_total = get_video_frame_total(modules.globals.target_path)
879
+ preview_slider.configure(to=video_frame_total)
880
+ preview_slider.pack(fill="x")
881
+ preview_slider.set(0)
882
+
883
+
884
+ def update_preview(frame_number: int = 0) -> None:
885
+ if modules.globals.source_path and modules.globals.target_path:
886
+ update_status("Processing...")
887
+
888
+ # Debug: Print the target path and frame number
889
+ print(
890
+ f"Target path: {modules.globals.target_path}, Frame number: {frame_number}"
891
+ )
892
+
893
+ temp_frame = None
894
+ if is_video(modules.globals.target_path):
895
+ temp_frame = get_video_frame(modules.globals.target_path, frame_number)
896
+ elif is_image(modules.globals.target_path):
897
+ temp_frame = cv2.imread(modules.globals.target_path)
898
+
899
+ # Debug: Check if temp_frame is None
900
+ if temp_frame is None:
901
+ print("Error: temp_frame is None")
902
+ update_status("Error: Could not read frame from video or image.")
903
+ return
904
+
905
+ if modules.globals.nsfw_filter and check_and_ignore_nsfw(temp_frame):
906
+ return
907
+
908
+ for frame_processor in get_frame_processors_modules(
909
+ modules.globals.frame_processors
910
+ ):
911
+ # Debug: Print the type of frame_processor
912
+ print(f"Processing frame with: {type(frame_processor).__name__}")
913
+
914
+ temp_frame = frame_processor.process_frame(
915
+ get_one_face(cv2.imread(modules.globals.source_path)), temp_frame
916
+ )
917
+
918
+ # Debug: Check if temp_frame is None after processing
919
+ if temp_frame is None:
920
+ print("Error: temp_frame is None after processing")
921
+ update_status("Error: Frame processing failed.")
922
+ return
923
+
924
+ image = Image.fromarray(cv2.cvtColor(temp_frame, cv2.COLOR_BGR2RGB))
925
+ image = ImageOps.contain(
926
+ image, (PREVIEW_MAX_WIDTH, PREVIEW_MAX_HEIGHT), Image.LANCZOS
927
+ )
928
+ image = ctk.CTkImage(image, size=image.size)
929
+ preview_label.configure(image=image)
930
+ update_status("Processing succeed!")
931
+ PREVIEW.deiconify()
932
+
933
+
934
+ def webcam_preview(root: ctk.CTk):
935
+ if not modules.globals.map_faces:
936
+ if modules.globals.source_path is None:
937
+ # No image selected
938
+ return
939
+ create_webcam_preview()
940
+ else:
941
+ modules.globals.souce_target_map = []
942
+ create_source_target_popup_for_webcam(root, modules.globals.souce_target_map)
943
+
944
+
945
+ def create_webcam_preview():
946
+ global preview_label, PREVIEW
947
+
948
+ camera = cv2.VideoCapture(
949
+ 0
950
+ ) # Use index for the webcam (adjust the index accordingly if necessary)
951
+ camera.set(
952
+ cv2.CAP_PROP_FRAME_WIDTH, PREVIEW_DEFAULT_WIDTH
953
+ ) # Set the width of the resolution
954
+ camera.set(
955
+ cv2.CAP_PROP_FRAME_HEIGHT, PREVIEW_DEFAULT_HEIGHT
956
+ ) # Set the height of the resolution
957
+ camera.set(cv2.CAP_PROP_FPS, 60) # Set the frame rate of the webcam
958
+
959
+ preview_label.configure(
960
+ width=PREVIEW_DEFAULT_WIDTH, height=PREVIEW_DEFAULT_HEIGHT
961
+ ) # Reset the preview image before startup
962
+
963
+ PREVIEW.deiconify() # Open preview window
964
+
965
+ frame_processors = get_frame_processors_modules(modules.globals.frame_processors)
966
+
967
+ source_image = None # Initialize variable for the selected face image
968
+
969
+ while camera:
970
+ ret, frame = camera.read()
971
+ if not ret:
972
+ break
973
+
974
+ temp_frame = frame.copy() # Create a copy of the frame
975
+
976
+ if modules.globals.live_mirror:
977
+ temp_frame = cv2.flip(temp_frame, 1) # horizontal flipping
978
+
979
+ if modules.globals.live_resizable:
980
+ temp_frame = fit_image_to_size(
981
+ temp_frame, PREVIEW.winfo_width(), PREVIEW.winfo_height()
982
+ )
983
+
984
+ if not modules.globals.map_faces:
985
+ # Select and save face image only once
986
+ if source_image is None and modules.globals.source_path:
987
+ source_image = get_one_face(cv2.imread(modules.globals.source_path))
988
+
989
+ for frame_processor in frame_processors:
990
+ temp_frame = frame_processor.process_frame(source_image, temp_frame)
991
+ else:
992
+ modules.globals.target_path = None
993
+
994
+ for frame_processor in frame_processors:
995
+ temp_frame = frame_processor.process_frame_v2(temp_frame)
996
+
997
+ image = cv2.cvtColor(
998
+ temp_frame, cv2.COLOR_BGR2RGB
999
+ ) # Convert the image to RGB format to display it with Tkinter
1000
+ image = Image.fromarray(image)
1001
+ image = ImageOps.contain(
1002
+ image, (temp_frame.shape[1], temp_frame.shape[0]), Image.LANCZOS
1003
+ )
1004
+ image = ctk.CTkImage(image, size=image.size)
1005
+ preview_label.configure(image=image)
1006
+ ROOT.update()
1007
+
1008
+ if PREVIEW.state() == "withdrawn":
1009
+ break
1010
+
1011
+ camera.release()
1012
+ PREVIEW.withdraw() # Close preview window when loop is finished
1013
+
1014
+
1015
+ def create_source_target_popup_for_webcam(root: ctk.CTk, map: list) -> None:
1016
+ global POPUP_LIVE, popup_status_label_live
1017
+
1018
+ POPUP_LIVE = ctk.CTkToplevel(root)
1019
+ POPUP_LIVE.title("Source x Target Mapper")
1020
+ POPUP_LIVE.geometry(f"{POPUP_LIVE_WIDTH}x{POPUP_LIVE_HEIGHT}")
1021
+ POPUP_LIVE.focus()
1022
+
1023
+ def on_submit_click():
1024
+ if has_valid_map():
1025
+ POPUP_LIVE.destroy()
1026
+ simplify_maps()
1027
+ create_webcam_preview()
1028
+ else:
1029
+ update_pop_live_status("At least 1 source with target is required!")
1030
+
1031
+ def on_add_click():
1032
+ add_blank_map()
1033
+ refresh_data(map)
1034
+ update_pop_live_status("Please provide mapping!")
1035
+
1036
+ popup_status_label_live = ctk.CTkLabel(POPUP_LIVE, text=None, justify="center")
1037
+ popup_status_label_live.grid(row=1, column=0, pady=15)
1038
+
1039
+ add_button = ctk.CTkButton(
1040
+ POPUP_LIVE,
1041
+ text="Add",
1042
+ command=lambda: on_add_click(),
1043
+ fg_color=("gray75", "gray25"),
1044
+ hover_color=("gray85", "gray35"),
1045
+ corner_radius=10,
1046
+ )
1047
+ add_button.place(relx=0.2, rely=0.92, relwidth=0.2, relheight=0.05)
1048
+
1049
+ close_button = ctk.CTkButton(
1050
+ POPUP_LIVE,
1051
+ text="Submit",
1052
+ command=lambda: on_submit_click(),
1053
+ fg_color=("DodgerBlue", "DodgerBlue"),
1054
+ hover_color=("RoyalBlue", "RoyalBlue"),
1055
+ corner_radius=10,
1056
+ )
1057
+ close_button.place(relx=0.6, rely=0.92, relwidth=0.2, relheight=0.05)
1058
+
1059
+ refresh_data(map) # Initial data refresh
1060
+
1061
+
1062
+ def refresh_data(map: list):
1063
+ global POPUP_LIVE
1064
+
1065
+ # Destroy existing widgets in the scrollable frame
1066
+ for widget in POPUP_LIVE.winfo_children():
1067
+ if isinstance(widget, ctk.CTkScrollableFrame):
1068
+ widget.destroy()
1069
+
1070
+ scrollable_frame = ctk.CTkScrollableFrame(
1071
+ POPUP_LIVE, width=POPUP_LIVE_SCROLL_WIDTH, height=POPUP_LIVE_SCROLL_HEIGHT
1072
+ )
1073
+ scrollable_frame.grid(row=0, column=0, padx=0, pady=0, sticky="nsew")
1074
+
1075
+ def on_sbutton_click(map, button_num):
1076
+ map = update_webcam_source(scrollable_frame, map, button_num)
1077
+
1078
+ def on_tbutton_click(map, button_num):
1079
+ map = update_webcam_target(scrollable_frame, map, button_num)
1080
+
1081
+ for item in map:
1082
+ id = item["id"]
1083
+
1084
+ row_frame = ctk.CTkFrame(scrollable_frame)
1085
+ row_frame.pack(fill="x", pady=5)
1086
+
1087
+ source_button = SourceMapperButton( # Use SourceMapperButton here
1088
+ row_frame,
1089
+ map,
1090
+ id,
1091
+ text="Select source image",
1092
+ command=lambda id=id: on_sbutton_click(map, id),
1093
+ width=DEFAULT_BUTTON_WIDTH,
1094
+ height=DEFAULT_BUTTON_HEIGHT,
1095
+ fg_color=("gray75", "gray25"),
1096
+ hover_color=("gray85", "gray35"),
1097
+ corner_radius=10,
1098
+ )
1099
+ source_button.pack(side="left", padx=(0, 10))
1100
+
1101
+ source_image_label = ctk.CTkLabel( # Create a label for source image
1102
+ row_frame,
1103
+ text=f"S-{id}",
1104
+ width=MAPPER_PREVIEW_MAX_WIDTH,
1105
+ height=MAPPER_PREVIEW_MAX_HEIGHT,
1106
+ )
1107
+ source_image_label.pack(side="left", padx=(0, 10))
1108
+
1109
+ if "source" in item:
1110
+ image = Image.fromarray(
1111
+ cv2.cvtColor(item["source"]["cv2"], cv2.COLOR_BGR2RGB)
1112
+ )
1113
+ image = image.resize(
1114
+ (MAPPER_PREVIEW_MAX_WIDTH, MAPPER_PREVIEW_MAX_HEIGHT), Image.LANCZOS
1115
+ )
1116
+ tk_image = ctk.CTkImage(image, size=image.size)
1117
+ source_image_label.configure(image=tk_image)
1118
+
1119
+ x_label = ctk.CTkLabel(
1120
+ row_frame,
1121
+ text=f"X",
1122
+ width=30,
1123
+ )
1124
+ x_label.pack(side="left", padx=(0, 10))
1125
+
1126
+ target_button = DragDropButton( # Use DragDropButton for target
1127
+ row_frame,
1128
+ text="Select target image",
1129
+ command=lambda id=id: on_tbutton_click(map, id),
1130
+ width=DEFAULT_BUTTON_WIDTH,
1131
+ height=DEFAULT_BUTTON_HEIGHT,
1132
+ fg_color=("gray75", "gray25"),
1133
+ hover_color=("gray85", "gray35"),
1134
+ corner_radius=10,
1135
+ )
1136
+
1137
+ target_button.handle_drop = lambda file_path, id=id: update_webcam_target(
1138
+ scrollable_frame, map, id, file_path
1139
+ ) # Add handle_drop for drag and drop
1140
+ target_button.pack(side="left", padx=(0, 10))
1141
+
1142
+ target_image_label = ctk.CTkLabel( # Create a label for target image
1143
+ row_frame,
1144
+ text=f"T-{id}",
1145
+ width=MAPPER_PREVIEW_MAX_WIDTH,
1146
+ height=MAPPER_PREVIEW_MAX_HEIGHT,
1147
+ )
1148
+ target_image_label.pack(side="left")
1149
+
1150
+ if "target" in item:
1151
+ image = Image.fromarray(
1152
+ cv2.cvtColor(item["target"]["cv2"], cv2.COLOR_BGR2RGB)
1153
+ )
1154
+ image = image.resize(
1155
+ (MAPPER_PREVIEW_MAX_WIDTH, MAPPER_PREVIEW_MAX_HEIGHT), Image.LANCZOS
1156
+ )
1157
+ tk_image = ctk.CTkImage(image, size=image.size)
1158
+ target_image_label.configure(image=tk_image)
1159
+
1160
+
1161
+ def update_webcam_source(
1162
+ scrollable_frame: ctk.CTkScrollableFrame, map: list, button_num: int
1163
+ ) -> list:
1164
+ global source_label_dict_live
1165
+
1166
+ source_path = ctk.filedialog.askopenfilename(
1167
+ title="select an source image",
1168
+ initialdir=RECENT_DIRECTORY_SOURCE,
1169
+ filetypes=[img_ft],
1170
+ )
1171
+
1172
+ if "source" in map[button_num]:
1173
+ map[button_num].pop("source")
1174
+ if button_num in source_label_dict_live:
1175
+ source_label_dict_live[button_num].destroy()
1176
+ del source_label_dict_live[button_num]
1177
+
1178
+ if source_path == "":
1179
+ return map
1180
+ else:
1181
+ cv2_img = cv2.imread(source_path)
1182
+ face = get_one_face(cv2_img)
1183
+
1184
+ if face:
1185
+ x_min, y_min, x_max, y_max = face["bbox"]
1186
+
1187
+ map[button_num]["source"] = {
1188
+ "cv2": cv2_img[int(y_min) : int(y_max), int(x_min) : int(x_max)],
1189
+ "face": face,
1190
+ }
1191
+
1192
+ image = Image.fromarray(
1193
+ cv2.cvtColor(map[button_num]["source"]["cv2"], cv2.COLOR_BGR2RGB)
1194
+ )
1195
+ image = image.resize(
1196
+ (MAPPER_PREVIEW_MAX_WIDTH, MAPPER_PREVIEW_MAX_HEIGHT), Image.LANCZOS
1197
+ )
1198
+ tk_image = ctk.CTkImage(image, size=image.size)
1199
+
1200
+ # Find the source image label in the row frame
1201
+ row_frame = scrollable_frame.winfo_children()[button_num]
1202
+ source_image_label = row_frame.winfo_children()[1]
1203
+
1204
+ source_image_label.configure(image=tk_image)
1205
+ source_label_dict_live[button_num] = source_image_label
1206
+ else:
1207
+ update_pop_live_status("Face could not be detected in last upload!")
1208
+ return map
1209
+
1210
+
1211
+ def update_webcam_target(
1212
+ scrollable_frame: ctk.CTkScrollableFrame,
1213
+ map: list,
1214
+ button_num: int,
1215
+ target_path: str = None,
1216
+ ) -> list:
1217
+ global target_label_dict_live
1218
+
1219
+ if target_path is None:
1220
+ target_path = ctk.filedialog.askopenfilename(
1221
+ title="select an target image",
1222
+ initialdir=RECENT_DIRECTORY_SOURCE,
1223
+ filetypes=[img_ft],
1224
+ )
1225
+
1226
+ if "target" in map[button_num]:
1227
+ map[button_num].pop("target")
1228
+ if button_num in target_label_dict_live:
1229
+ target_label_dict_live[button_num].destroy()
1230
+ del target_label_dict_live[button_num]
1231
+
1232
+ if target_path == "":
1233
+ return map
1234
+ else:
1235
+ cv2_img = cv2.imread(target_path)
1236
+ face = get_one_face(cv2_img)
1237
+
1238
+ if face:
1239
+ x_min, y_min, x_max, y_max = face["bbox"]
1240
+
1241
+ map[button_num]["target"] = {
1242
+ "cv2": cv2_img[int(y_min) : int(y_max), int(x_min) : int(x_max)],
1243
+ "face": face,
1244
+ }
1245
+
1246
+ image = Image.fromarray(
1247
+ cv2.cvtColor(map[button_num]["target"]["cv2"], cv2.COLOR_BGR2RGB)
1248
+ )
1249
+ image = image.resize(
1250
+ (MAPPER_PREVIEW_MAX_WIDTH, MAPPER_PREVIEW_MAX_HEIGHT), Image.LANCZOS
1251
+ )
1252
+ tk_image = ctk.CTkImage(image, size=image.size)
1253
+
1254
+ # Find the target image label in the row frame
1255
+ row_frame = scrollable_frame.winfo_children()[button_num]
1256
+ target_image_label = row_frame.winfo_children()[4]
1257
+
1258
+ target_image_label.configure(image=tk_image)
1259
+ target_label_dict_live[button_num] = target_image_label
1260
+ else:
1261
+ update_pop_live_status("Face could not be detected in last upload!")
1262
+ return map
modules/utilities.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import mimetypes
3
+ import os
4
+ import platform
5
+ import shutil
6
+ import ssl
7
+ import subprocess
8
+ import urllib
9
+ from pathlib import Path
10
+ from typing import List, Any
11
+ from tqdm import tqdm
12
+
13
+ import modules.globals
14
+
15
+ TEMP_FILE = 'temp.mp4'
16
+ TEMP_DIRECTORY = 'temp'
17
+
18
+ # monkey patch ssl for mac
19
+ if platform.system().lower() == 'darwin':
20
+ ssl._create_default_https_context = ssl._create_unverified_context
21
+
22
+
23
+ def run_ffmpeg(args: List[str]) -> bool:
24
+ commands = ['ffmpeg', '-hide_banner', '-hwaccel', 'auto', '-loglevel', modules.globals.log_level]
25
+ commands.extend(args)
26
+ try:
27
+ subprocess.check_output(commands, stderr=subprocess.STDOUT)
28
+ return True
29
+ except Exception:
30
+ pass
31
+ return False
32
+
33
+
34
+ def detect_fps(target_path: str) -> float:
35
+ command = ['ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=r_frame_rate', '-of', 'default=noprint_wrappers=1:nokey=1', target_path]
36
+ output = subprocess.check_output(command).decode().strip().split('/')
37
+ try:
38
+ numerator, denominator = map(int, output)
39
+ return numerator / denominator
40
+ except Exception:
41
+ pass
42
+ return 30.0
43
+
44
+
45
+ def extract_frames(target_path: str) -> None:
46
+ temp_directory_path = get_temp_directory_path(target_path)
47
+ run_ffmpeg(['-i', target_path, '-pix_fmt', 'rgb24', os.path.join(temp_directory_path, '%04d.png')])
48
+
49
+
50
+ def create_video(target_path: str, fps: float = 30.0) -> None:
51
+ temp_output_path = get_temp_output_path(target_path)
52
+ temp_directory_path = get_temp_directory_path(target_path)
53
+ run_ffmpeg(['-r', str(fps), '-i', os.path.join(temp_directory_path, '%04d.png'), '-c:v', modules.globals.video_encoder, '-crf', str(modules.globals.video_quality), '-pix_fmt', 'yuv420p', '-vf', 'colorspace=bt709:iall=bt601-6-625:fast=1', '-y', temp_output_path])
54
+
55
+
56
+ def restore_audio(target_path: str, output_path: str) -> None:
57
+ temp_output_path = get_temp_output_path(target_path)
58
+ done = run_ffmpeg(['-i', temp_output_path, '-i', target_path, '-c:v', 'copy', '-map', '0:v:0', '-map', '1:a:0', '-y', output_path])
59
+ if not done:
60
+ move_temp(target_path, output_path)
61
+
62
+
63
+ def get_temp_frame_paths(target_path: str) -> List[str]:
64
+ temp_directory_path = get_temp_directory_path(target_path)
65
+ return glob.glob((os.path.join(glob.escape(temp_directory_path), '*.png')))
66
+
67
+
68
+ def get_temp_directory_path(target_path: str) -> str:
69
+ target_name, _ = os.path.splitext(os.path.basename(target_path))
70
+ target_directory_path = os.path.dirname(target_path)
71
+ return os.path.join(target_directory_path, TEMP_DIRECTORY, target_name)
72
+
73
+
74
+ def get_temp_output_path(target_path: str) -> str:
75
+ temp_directory_path = get_temp_directory_path(target_path)
76
+ return os.path.join(temp_directory_path, TEMP_FILE)
77
+
78
+
79
+ def normalize_output_path(source_path: str, target_path: str, output_path: str) -> Any:
80
+ if source_path and target_path:
81
+ source_name, _ = os.path.splitext(os.path.basename(source_path))
82
+ target_name, target_extension = os.path.splitext(os.path.basename(target_path))
83
+ if os.path.isdir(output_path):
84
+ return os.path.join(output_path, source_name + '-' + target_name + target_extension)
85
+ return output_path
86
+
87
+
88
+ def create_temp(target_path: str) -> None:
89
+ temp_directory_path = get_temp_directory_path(target_path)
90
+ Path(temp_directory_path).mkdir(parents=True, exist_ok=True)
91
+
92
+
93
+ def move_temp(target_path: str, output_path: str) -> None:
94
+ temp_output_path = get_temp_output_path(target_path)
95
+ if os.path.isfile(temp_output_path):
96
+ if os.path.isfile(output_path):
97
+ os.remove(output_path)
98
+ shutil.move(temp_output_path, output_path)
99
+
100
+
101
+ def clean_temp(target_path: str) -> None:
102
+ temp_directory_path = get_temp_directory_path(target_path)
103
+ parent_directory_path = os.path.dirname(temp_directory_path)
104
+ if not modules.globals.keep_frames and os.path.isdir(temp_directory_path):
105
+ shutil.rmtree(temp_directory_path)
106
+ if os.path.exists(parent_directory_path) and not os.listdir(parent_directory_path):
107
+ os.rmdir(parent_directory_path)
108
+
109
+
110
+ def has_image_extension(image_path: str) -> bool:
111
+ return image_path.lower().endswith(('png', 'jpg', 'jpeg'))
112
+
113
+
114
+ def is_image(image_path: str) -> bool:
115
+ if image_path and os.path.isfile(image_path):
116
+ mimetype, _ = mimetypes.guess_type(image_path)
117
+ return bool(mimetype and mimetype.startswith('image/'))
118
+ return False
119
+
120
+
121
+ def is_video(video_path: str) -> bool:
122
+ if video_path and os.path.isfile(video_path):
123
+ mimetype, _ = mimetypes.guess_type(video_path)
124
+ return bool(mimetype and mimetype.startswith('video/'))
125
+ return False
126
+
127
+
128
+ def conditional_download(download_directory_path: str, urls: List[str]) -> None:
129
+ if not os.path.exists(download_directory_path):
130
+ os.makedirs(download_directory_path)
131
+ for url in urls:
132
+ download_file_path = os.path.join(download_directory_path, os.path.basename(url))
133
+ if not os.path.exists(download_file_path):
134
+ request = urllib.request.urlopen(url) # type: ignore[attr-defined]
135
+ total = int(request.headers.get('Content-Length', 0))
136
+ with tqdm(total=total, desc='Downloading', unit='B', unit_scale=True, unit_divisor=1024) as progress:
137
+ urllib.request.urlretrieve(url, download_file_path, reporthook=lambda count, block_size, total_size: progress.update(block_size)) # type: ignore[attr-defined]
138
+
139
+
140
+ def resolve_relative_path(path: str) -> str:
141
+ return os.path.abspath(os.path.join(os.path.dirname(__file__), path))
mypi.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 CHANGED
@@ -1,2 +1,22 @@
1
- fastapi
2
- uvicorn[standard]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cu118
2
+
3
+ numpy>=1.23.5,<2
4
+ opencv-python==4.8.1.78
5
+ onnx==1.16.0
6
+ insightface==0.7.3
7
+ psutil==5.9.8
8
+ tk==0.1.0
9
+ customtkinter==5.2.2
10
+ pillow==9.5.0
11
+ torch>=2.0.1
12
+ torchvision==0.15.2+cu118; sys_platform != 'darwin'
13
+ torchvision==0.15.2; sys_platform == 'darwin'
14
+ onnxruntime-silicon==1.16.3; sys_platform == 'darwin' and platform_machine == 'arm64'
15
+ onnxruntime-gpu==1.16.3; sys_platform != 'darwin'
16
+ tensorflow==2.12.1; sys_platform != 'darwin'
17
+ opennsfw2==0.10.2
18
+ protobuf==4.23.2
19
+ tqdm==4.66.4
20
+ gfpgan==1.3.8
21
+ tkinterdnd2==0.4.2
22
+ customtkinter==5.2.2
run-cuda.bat ADDED
@@ -0,0 +1 @@
 
 
1
+ python run.py --execution-provider cuda --execution-threads 60 --max-memory 60
run-laptop-gpu.bat ADDED
@@ -0,0 +1 @@
 
 
1
+ python run.py --execution-provider dml
run.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ from modules import core
4
+
5
+ if __name__ == '__main__':
6
+ core.run()
run_with_chocolatey.bat ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ :: Installing Microsoft Visual C++ Runtime - all versions 1.0.1 if it's not already installed
3
+ choco install vcredist-all
4
+ :: Installing CUDA if it's not already installed
5
+ choco install cuda
6
+ :: Inatalling ffmpeg if it's not already installed
7
+ choco install ffmpeg
8
+ :: Installing Python if it's not already installed
9
+ choco install python -y
10
+ :: Assuming successful installation, we ensure pip is upgraded
11
+ python -m ensurepip --upgrade
12
+ :: Use pip to install the packages listed in 'requirements.txt'
13
+ pip install -r requirements.txt
setup_deep_live_cam.bat ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ setlocal EnableDelayedExpansion
3
+
4
+ :: 1. Setup your platform
5
+ echo Setting up your platform...
6
+
7
+ :: Python
8
+ where python >nul 2>&1
9
+ if %ERRORLEVEL% neq 0 (
10
+ echo Python is not installed. Please install Python 3.10 or later.
11
+ pause
12
+ exit /b
13
+ )
14
+
15
+ :: Pip
16
+ where pip >nul 2>&1
17
+ if %ERRORLEVEL% neq 0 (
18
+ echo Pip is not installed. Please install Pip.
19
+ pause
20
+ exit /b
21
+ )
22
+
23
+ :: Git
24
+ where git >nul 2>&1
25
+ if %ERRORLEVEL% neq 0 (
26
+ echo Git is not installed. Installing Git...
27
+ winget install --id Git.Git -e --source winget
28
+ )
29
+
30
+ :: FFMPEG
31
+ where ffmpeg >nul 2>&1
32
+ if %ERRORLEVEL% neq 0 (
33
+ echo FFMPEG is not installed. Installing FFMPEG...
34
+ winget install --id Gyan.FFmpeg -e --source winget
35
+ )
36
+
37
+ :: Visual Studio 2022 Runtimes
38
+ echo Installing Visual Studio 2022 Runtimes...
39
+ winget install --id Microsoft.VC++2015-2022Redist-x64 -e --source winget
40
+
41
+ :: 2. Clone Repository
42
+ if exist Deep-Live-Cam (
43
+ echo Deep-Live-Cam directory already exists.
44
+ set /p overwrite="Do you want to overwrite? (Y/N): "
45
+ if /i "%overwrite%"=="Y" (
46
+ rmdir /s /q Deep-Live-Cam
47
+ git clone https://github.com/hacksider/Deep-Live-Cam.git
48
+ ) else (
49
+ echo Skipping clone, using existing directory.
50
+ )
51
+ ) else (
52
+ git clone https://github.com/hacksider/Deep-Live-Cam.git
53
+ )
54
+ cd Deep-Live-Cam
55
+
56
+ :: 3. Download Models
57
+ echo Downloading models...
58
+ mkdir models
59
+ curl -L -o models/GFPGANv1.4.pth https://path.to.model/GFPGANv1.4.pth
60
+ curl -L -o models/inswapper_128_fp16.onnx https://path.to.model/inswapper_128_fp16.onnx
61
+
62
+ :: 4. Install dependencies
63
+ echo Creating a virtual environment...
64
+ python -m venv venv
65
+ call venv\Scripts\activate
66
+
67
+ echo Installing required Python packages...
68
+ pip install --upgrade pip
69
+ pip install -r requirements.txt
70
+
71
+ echo Setup complete. You can now run the application.
72
+
73
+ :: GPU Acceleration Options
74
+ echo.
75
+ echo Choose the GPU Acceleration Option if applicable:
76
+ echo 1. CUDA (Nvidia)
77
+ echo 2. CoreML (Apple Silicon)
78
+ echo 3. CoreML (Apple Legacy)
79
+ echo 4. DirectML (Windows)
80
+ echo 5. OpenVINO (Intel)
81
+ echo 6. None
82
+ set /p choice="Enter your choice (1-6): "
83
+
84
+ if "%choice%"=="1" (
85
+ echo Installing CUDA dependencies...
86
+ pip uninstall -y onnxruntime onnxruntime-gpu
87
+ pip install onnxruntime-gpu==1.16.3
88
+ set exec_provider="cuda"
89
+ ) else if "%choice%"=="2" (
90
+ echo Installing CoreML (Apple Silicon) dependencies...
91
+ pip uninstall -y onnxruntime onnxruntime-silicon
92
+ pip install onnxruntime-silicon==1.13.1
93
+ set exec_provider="coreml"
94
+ ) else if "%choice%"=="3" (
95
+ echo Installing CoreML (Apple Legacy) dependencies...
96
+ pip uninstall -y onnxruntime onnxruntime-coreml
97
+ pip install onnxruntime-coreml==1.13.1
98
+ set exec_provider="coreml"
99
+ ) else if "%choice%"=="4" (
100
+ echo Installing DirectML dependencies...
101
+ pip uninstall -y onnxruntime onnxruntime-directml
102
+ pip install onnxruntime-directml==1.15.1
103
+ set exec_provider="directml"
104
+ ) else if "%choice%"=="5" (
105
+ echo Installing OpenVINO dependencies...
106
+ pip uninstall -y onnxruntime onnxruntime-openvino
107
+ pip install onnxruntime-openvino==1.15.0
108
+ set exec_provider="openvino"
109
+ ) else (
110
+ echo Skipping GPU acceleration setup.
111
+ )
112
+
113
+ :: Run the application
114
+ if defined exec_provider (
115
+ echo Running the application with %exec_provider% execution provider...
116
+ python run.py --execution-provider %exec_provider%
117
+ ) else (
118
+ echo Running the application...
119
+ python run.py
120
+ )
121
+
122
+ pause