MonsterMMORPG
commited on
Commit
•
17eddbd
1
Parent(s):
df03c5d
Upload folder using huggingface_hub (#1)
Browse files- ad12ac56454a9863a1f84a63e67f93672e88c7bc4f53fe03c54d3305d6ac72b2 (bab3d3dbc225dfeb967ae66261f34adf3e8ba327)
- 08f4ccb5459ba8d71ac7e1cb832d4f5e480338e9d9664a469baa1b1252917877 (d8e8a96d11e44ea9a06e58113e02a4b60bf1f548)
This view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +2 -0
- .gitignore +11 -0
- LICENSE +674 -0
- README.md +72 -0
- Rope.bat +2 -0
- Rope.py +5 -0
- benchmark/target-1080p.mp4 +3 -0
- models/meanshape_68.pkl +3 -0
- models/place_model_files_here +1 -0
- requirements.txt +17 -0
- rope/Coordinator.py +177 -0
- rope/Dicts.py +441 -0
- rope/FaceUtil.py +405 -0
- rope/GUI.py +0 -0
- rope/GUIElements.py +1248 -0
- rope/Models.py +1961 -0
- rope/Styles.py +293 -0
- rope/VideoManager.py +1242 -0
- rope/external/cliplib/__init__.py +1 -0
- rope/external/cliplib/bpe_simple_vocab_16e6.txt.gz +3 -0
- rope/external/cliplib/clip.py +245 -0
- rope/external/cliplib/model.py +436 -0
- rope/external/cliplib/simple_tokenizer.py +132 -0
- rope/external/clipseg.py +538 -0
- rope/external/resnet.py +109 -0
- rope/media/OffState.png +0 -0
- rope/media/OnState.png +0 -0
- rope/media/add_marker_hover.png +0 -0
- rope/media/add_marker_off.png +0 -0
- rope/media/marker.png +0 -0
- rope/media/marker_save.png +0 -0
- rope/media/next_marker_hover.png +0 -0
- rope/media/next_marker_off.png +0 -0
- rope/media/play_hover.png +0 -0
- rope/media/play_off.png +0 -0
- rope/media/play_on.png +0 -0
- rope/media/previous_marker_hover.png +0 -0
- rope/media/previous_marker_off.png +0 -0
- rope/media/rec_hover.png +0 -0
- rope/media/rec_off.png +0 -0
- rope/media/rec_on.png +0 -0
- rope/media/remove_marker_hover.png +0 -0
- rope/media/remove_marker_off.png +0 -0
- rope/media/rope.ico +0 -0
- rope/media/rope.png +0 -0
- rope/media/save.png +0 -0
- rope/media/splash.png +3 -0
- rope/media/stop_hover.png +0 -0
- rope/media/stop_off.png +0 -0
- rope/media/stop_on.png +0 -0
.gitattributes
CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
benchmark/target-1080p.mp4 filter=lfs diff=lfs merge=lfs -text
|
37 |
+
rope/media/splash.png filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
**/__pycache__/**
|
2 |
+
|
3 |
+
models/*.ckpt
|
4 |
+
models/*.pth
|
5 |
+
models/*.onnx
|
6 |
+
saved_parameters.json
|
7 |
+
data.json
|
8 |
+
merged_embeddings.txt
|
9 |
+
.vs
|
10 |
+
*.sln
|
11 |
+
*.pyproj
|
LICENSE
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 29 June 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works.
|
12 |
+
|
13 |
+
The licenses for most software and other practical works are designed
|
14 |
+
to take away your freedom to share and change the works. By contrast,
|
15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
16 |
+
share and change all versions of a program--to make sure it remains free
|
17 |
+
software for all its users. We, the Free Software Foundation, use the
|
18 |
+
GNU General Public License for most of our software; it applies also to
|
19 |
+
any other work released this way by its authors. You can apply it to
|
20 |
+
your programs, too.
|
21 |
+
|
22 |
+
When we speak of free software, we are referring to freedom, not
|
23 |
+
price. Our General Public Licenses are designed to make sure that you
|
24 |
+
have the freedom to distribute copies of free software (and charge for
|
25 |
+
them if you wish), that you receive source code or can get it if you
|
26 |
+
want it, that you can change the software or use pieces of it in new
|
27 |
+
free programs, and that you know you can do these things.
|
28 |
+
|
29 |
+
To protect your rights, we need to prevent others from denying you
|
30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
31 |
+
certain responsibilities if you distribute copies of the software, or if
|
32 |
+
you modify it: responsibilities to respect the freedom of others.
|
33 |
+
|
34 |
+
For example, if you distribute copies of such a program, whether
|
35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
36 |
+
freedoms that you received. You must make sure that they, too, receive
|
37 |
+
or can get the source code. And you must show them these terms so they
|
38 |
+
know their rights.
|
39 |
+
|
40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
43 |
+
|
44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
45 |
+
that there is no warranty for this free software. For both users' and
|
46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
47 |
+
changed, so that their problems will not be attributed erroneously to
|
48 |
+
authors of previous versions.
|
49 |
+
|
50 |
+
Some devices are designed to deny users access to install or run
|
51 |
+
modified versions of the software inside them, although the manufacturer
|
52 |
+
can do so. This is fundamentally incompatible with the aim of
|
53 |
+
protecting users' freedom to change the software. The systematic
|
54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
56 |
+
have designed this version of the GPL to prohibit the practice for those
|
57 |
+
products. If such problems arise substantially in other domains, we
|
58 |
+
stand ready to extend this provision to those domains in future versions
|
59 |
+
of the GPL, as needed to protect the freedom of users.
|
60 |
+
|
61 |
+
Finally, every program is threatened constantly by software patents.
|
62 |
+
States should not allow patents to restrict development and use of
|
63 |
+
software on general-purpose computers, but in those that do, we wish to
|
64 |
+
avoid the special danger that patents applied to a free program could
|
65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
66 |
+
patents cannot be used to render the program non-free.
|
67 |
+
|
68 |
+
The precise terms and conditions for copying, distribution and
|
69 |
+
modification follow.
|
70 |
+
|
71 |
+
TERMS AND CONDITIONS
|
72 |
+
|
73 |
+
0. Definitions.
|
74 |
+
|
75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
76 |
+
|
77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
78 |
+
works, such as semiconductor masks.
|
79 |
+
|
80 |
+
"The Program" refers to any copyrightable work licensed under this
|
81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
82 |
+
"recipients" may be individuals or organizations.
|
83 |
+
|
84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
85 |
+
in a fashion requiring copyright permission, other than the making of an
|
86 |
+
exact copy. The resulting work is called a "modified version" of the
|
87 |
+
earlier work or a work "based on" the earlier work.
|
88 |
+
|
89 |
+
A "covered work" means either the unmodified Program or a work based
|
90 |
+
on the Program.
|
91 |
+
|
92 |
+
To "propagate" a work means to do anything with it that, without
|
93 |
+
permission, would make you directly or secondarily liable for
|
94 |
+
infringement under applicable copyright law, except executing it on a
|
95 |
+
computer or modifying a private copy. Propagation includes copying,
|
96 |
+
distribution (with or without modification), making available to the
|
97 |
+
public, and in some countries other activities as well.
|
98 |
+
|
99 |
+
To "convey" a work means any kind of propagation that enables other
|
100 |
+
parties to make or receive copies. Mere interaction with a user through
|
101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
102 |
+
|
103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
104 |
+
to the extent that it includes a convenient and prominently visible
|
105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
106 |
+
tells the user that there is no warranty for the work (except to the
|
107 |
+
extent that warranties are provided), that licensees may convey the
|
108 |
+
work under this License, and how to view a copy of this License. If
|
109 |
+
the interface presents a list of user commands or options, such as a
|
110 |
+
menu, a prominent item in the list meets this criterion.
|
111 |
+
|
112 |
+
1. Source Code.
|
113 |
+
|
114 |
+
The "source code" for a work means the preferred form of the work
|
115 |
+
for making modifications to it. "Object code" means any non-source
|
116 |
+
form of a work.
|
117 |
+
|
118 |
+
A "Standard Interface" means an interface that either is an official
|
119 |
+
standard defined by a recognized standards body, or, in the case of
|
120 |
+
interfaces specified for a particular programming language, one that
|
121 |
+
is widely used among developers working in that language.
|
122 |
+
|
123 |
+
The "System Libraries" of an executable work include anything, other
|
124 |
+
than the work as a whole, that (a) is included in the normal form of
|
125 |
+
packaging a Major Component, but which is not part of that Major
|
126 |
+
Component, and (b) serves only to enable use of the work with that
|
127 |
+
Major Component, or to implement a Standard Interface for which an
|
128 |
+
implementation is available to the public in source code form. A
|
129 |
+
"Major Component", in this context, means a major essential component
|
130 |
+
(kernel, window system, and so on) of the specific operating system
|
131 |
+
(if any) on which the executable work runs, or a compiler used to
|
132 |
+
produce the work, or an object code interpreter used to run it.
|
133 |
+
|
134 |
+
The "Corresponding Source" for a work in object code form means all
|
135 |
+
the source code needed to generate, install, and (for an executable
|
136 |
+
work) run the object code and to modify the work, including scripts to
|
137 |
+
control those activities. However, it does not include the work's
|
138 |
+
System Libraries, or general-purpose tools or generally available free
|
139 |
+
programs which are used unmodified in performing those activities but
|
140 |
+
which are not part of the work. For example, Corresponding Source
|
141 |
+
includes interface definition files associated with source files for
|
142 |
+
the work, and the source code for shared libraries and dynamically
|
143 |
+
linked subprograms that the work is specifically designed to require,
|
144 |
+
such as by intimate data communication or control flow between those
|
145 |
+
subprograms and other parts of the work.
|
146 |
+
|
147 |
+
The Corresponding Source need not include anything that users
|
148 |
+
can regenerate automatically from other parts of the Corresponding
|
149 |
+
Source.
|
150 |
+
|
151 |
+
The Corresponding Source for a work in source code form is that
|
152 |
+
same work.
|
153 |
+
|
154 |
+
2. Basic Permissions.
|
155 |
+
|
156 |
+
All rights granted under this License are granted for the term of
|
157 |
+
copyright on the Program, and are irrevocable provided the stated
|
158 |
+
conditions are met. This License explicitly affirms your unlimited
|
159 |
+
permission to run the unmodified Program. The output from running a
|
160 |
+
covered work is covered by this License only if the output, given its
|
161 |
+
content, constitutes a covered work. This License acknowledges your
|
162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
163 |
+
|
164 |
+
You may make, run and propagate covered works that you do not
|
165 |
+
convey, without conditions so long as your license otherwise remains
|
166 |
+
in force. You may convey covered works to others for the sole purpose
|
167 |
+
of having them make modifications exclusively for you, or provide you
|
168 |
+
with facilities for running those works, provided that you comply with
|
169 |
+
the terms of this License in conveying all material for which you do
|
170 |
+
not control copyright. Those thus making or running the covered works
|
171 |
+
for you must do so exclusively on your behalf, under your direction
|
172 |
+
and control, on terms that prohibit them from making any copies of
|
173 |
+
your copyrighted material outside their relationship with you.
|
174 |
+
|
175 |
+
Conveying under any other circumstances is permitted solely under
|
176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
177 |
+
makes it unnecessary.
|
178 |
+
|
179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
180 |
+
|
181 |
+
No covered work shall be deemed part of an effective technological
|
182 |
+
measure under any applicable law fulfilling obligations under article
|
183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
184 |
+
similar laws prohibiting or restricting circumvention of such
|
185 |
+
measures.
|
186 |
+
|
187 |
+
When you convey a covered work, you waive any legal power to forbid
|
188 |
+
circumvention of technological measures to the extent such circumvention
|
189 |
+
is effected by exercising rights under this License with respect to
|
190 |
+
the covered work, and you disclaim any intention to limit operation or
|
191 |
+
modification of the work as a means of enforcing, against the work's
|
192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
193 |
+
technological measures.
|
194 |
+
|
195 |
+
4. Conveying Verbatim Copies.
|
196 |
+
|
197 |
+
You may convey verbatim copies of the Program's source code as you
|
198 |
+
receive it, in any medium, provided that you conspicuously and
|
199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
200 |
+
keep intact all notices stating that this License and any
|
201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
202 |
+
keep intact all notices of the absence of any warranty; and give all
|
203 |
+
recipients a copy of this License along with the Program.
|
204 |
+
|
205 |
+
You may charge any price or no price for each copy that you convey,
|
206 |
+
and you may offer support or warranty protection for a fee.
|
207 |
+
|
208 |
+
5. Conveying Modified Source Versions.
|
209 |
+
|
210 |
+
You may convey a work based on the Program, or the modifications to
|
211 |
+
produce it from the Program, in the form of source code under the
|
212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
213 |
+
|
214 |
+
a) The work must carry prominent notices stating that you modified
|
215 |
+
it, and giving a relevant date.
|
216 |
+
|
217 |
+
b) The work must carry prominent notices stating that it is
|
218 |
+
released under this License and any conditions added under section
|
219 |
+
7. This requirement modifies the requirement in section 4 to
|
220 |
+
"keep intact all notices".
|
221 |
+
|
222 |
+
c) You must license the entire work, as a whole, under this
|
223 |
+
License to anyone who comes into possession of a copy. This
|
224 |
+
License will therefore apply, along with any applicable section 7
|
225 |
+
additional terms, to the whole of the work, and all its parts,
|
226 |
+
regardless of how they are packaged. This License gives no
|
227 |
+
permission to license the work in any other way, but it does not
|
228 |
+
invalidate such permission if you have separately received it.
|
229 |
+
|
230 |
+
d) If the work has interactive user interfaces, each must display
|
231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
233 |
+
work need not make them do so.
|
234 |
+
|
235 |
+
A compilation of a covered work with other separate and independent
|
236 |
+
works, which are not by their nature extensions of the covered work,
|
237 |
+
and which are not combined with it such as to form a larger program,
|
238 |
+
in or on a volume of a storage or distribution medium, is called an
|
239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
240 |
+
used to limit the access or legal rights of the compilation's users
|
241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
242 |
+
in an aggregate does not cause this License to apply to the other
|
243 |
+
parts of the aggregate.
|
244 |
+
|
245 |
+
6. Conveying Non-Source Forms.
|
246 |
+
|
247 |
+
You may convey a covered work in object code form under the terms
|
248 |
+
of sections 4 and 5, provided that you also convey the
|
249 |
+
machine-readable Corresponding Source under the terms of this License,
|
250 |
+
in one of these ways:
|
251 |
+
|
252 |
+
a) Convey the object code in, or embodied in, a physical product
|
253 |
+
(including a physical distribution medium), accompanied by the
|
254 |
+
Corresponding Source fixed on a durable physical medium
|
255 |
+
customarily used for software interchange.
|
256 |
+
|
257 |
+
b) Convey the object code in, or embodied in, a physical product
|
258 |
+
(including a physical distribution medium), accompanied by a
|
259 |
+
written offer, valid for at least three years and valid for as
|
260 |
+
long as you offer spare parts or customer support for that product
|
261 |
+
model, to give anyone who possesses the object code either (1) a
|
262 |
+
copy of the Corresponding Source for all the software in the
|
263 |
+
product that is covered by this License, on a durable physical
|
264 |
+
medium customarily used for software interchange, for a price no
|
265 |
+
more than your reasonable cost of physically performing this
|
266 |
+
conveying of source, or (2) access to copy the
|
267 |
+
Corresponding Source from a network server at no charge.
|
268 |
+
|
269 |
+
c) Convey individual copies of the object code with a copy of the
|
270 |
+
written offer to provide the Corresponding Source. This
|
271 |
+
alternative is allowed only occasionally and noncommercially, and
|
272 |
+
only if you received the object code with such an offer, in accord
|
273 |
+
with subsection 6b.
|
274 |
+
|
275 |
+
d) Convey the object code by offering access from a designated
|
276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
277 |
+
Corresponding Source in the same way through the same place at no
|
278 |
+
further charge. You need not require recipients to copy the
|
279 |
+
Corresponding Source along with the object code. If the place to
|
280 |
+
copy the object code is a network server, the Corresponding Source
|
281 |
+
may be on a different server (operated by you or a third party)
|
282 |
+
that supports equivalent copying facilities, provided you maintain
|
283 |
+
clear directions next to the object code saying where to find the
|
284 |
+
Corresponding Source. Regardless of what server hosts the
|
285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
286 |
+
available for as long as needed to satisfy these requirements.
|
287 |
+
|
288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
289 |
+
you inform other peers where the object code and Corresponding
|
290 |
+
Source of the work are being offered to the general public at no
|
291 |
+
charge under subsection 6d.
|
292 |
+
|
293 |
+
A separable portion of the object code, whose source code is excluded
|
294 |
+
from the Corresponding Source as a System Library, need not be
|
295 |
+
included in conveying the object code work.
|
296 |
+
|
297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
298 |
+
tangible personal property which is normally used for personal, family,
|
299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
302 |
+
product received by a particular user, "normally used" refers to a
|
303 |
+
typical or common use of that class of product, regardless of the status
|
304 |
+
of the particular user or of the way in which the particular user
|
305 |
+
actually uses, or expects or is expected to use, the product. A product
|
306 |
+
is a consumer product regardless of whether the product has substantial
|
307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
308 |
+
the only significant mode of use of the product.
|
309 |
+
|
310 |
+
"Installation Information" for a User Product means any methods,
|
311 |
+
procedures, authorization keys, or other information required to install
|
312 |
+
and execute modified versions of a covered work in that User Product from
|
313 |
+
a modified version of its Corresponding Source. The information must
|
314 |
+
suffice to ensure that the continued functioning of the modified object
|
315 |
+
code is in no case prevented or interfered with solely because
|
316 |
+
modification has been made.
|
317 |
+
|
318 |
+
If you convey an object code work under this section in, or with, or
|
319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
320 |
+
part of a transaction in which the right of possession and use of the
|
321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
322 |
+
fixed term (regardless of how the transaction is characterized), the
|
323 |
+
Corresponding Source conveyed under this section must be accompanied
|
324 |
+
by the Installation Information. But this requirement does not apply
|
325 |
+
if neither you nor any third party retains the ability to install
|
326 |
+
modified object code on the User Product (for example, the work has
|
327 |
+
been installed in ROM).
|
328 |
+
|
329 |
+
The requirement to provide Installation Information does not include a
|
330 |
+
requirement to continue to provide support service, warranty, or updates
|
331 |
+
for a work that has been modified or installed by the recipient, or for
|
332 |
+
the User Product in which it has been modified or installed. Access to a
|
333 |
+
network may be denied when the modification itself materially and
|
334 |
+
adversely affects the operation of the network or violates the rules and
|
335 |
+
protocols for communication across the network.
|
336 |
+
|
337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
338 |
+
in accord with this section must be in a format that is publicly
|
339 |
+
documented (and with an implementation available to the public in
|
340 |
+
source code form), and must require no special password or key for
|
341 |
+
unpacking, reading or copying.
|
342 |
+
|
343 |
+
7. Additional Terms.
|
344 |
+
|
345 |
+
"Additional permissions" are terms that supplement the terms of this
|
346 |
+
License by making exceptions from one or more of its conditions.
|
347 |
+
Additional permissions that are applicable to the entire Program shall
|
348 |
+
be treated as though they were included in this License, to the extent
|
349 |
+
that they are valid under applicable law. If additional permissions
|
350 |
+
apply only to part of the Program, that part may be used separately
|
351 |
+
under those permissions, but the entire Program remains governed by
|
352 |
+
this License without regard to the additional permissions.
|
353 |
+
|
354 |
+
When you convey a copy of a covered work, you may at your option
|
355 |
+
remove any additional permissions from that copy, or from any part of
|
356 |
+
it. (Additional permissions may be written to require their own
|
357 |
+
removal in certain cases when you modify the work.) You may place
|
358 |
+
additional permissions on material, added by you to a covered work,
|
359 |
+
for which you have or can give appropriate copyright permission.
|
360 |
+
|
361 |
+
Notwithstanding any other provision of this License, for material you
|
362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
363 |
+
that material) supplement the terms of this License with terms:
|
364 |
+
|
365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
366 |
+
terms of sections 15 and 16 of this License; or
|
367 |
+
|
368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
369 |
+
author attributions in that material or in the Appropriate Legal
|
370 |
+
Notices displayed by works containing it; or
|
371 |
+
|
372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
373 |
+
requiring that modified versions of such material be marked in
|
374 |
+
reasonable ways as different from the original version; or
|
375 |
+
|
376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
377 |
+
authors of the material; or
|
378 |
+
|
379 |
+
e) Declining to grant rights under trademark law for use of some
|
380 |
+
trade names, trademarks, or service marks; or
|
381 |
+
|
382 |
+
f) Requiring indemnification of licensors and authors of that
|
383 |
+
material by anyone who conveys the material (or modified versions of
|
384 |
+
it) with contractual assumptions of liability to the recipient, for
|
385 |
+
any liability that these contractual assumptions directly impose on
|
386 |
+
those licensors and authors.
|
387 |
+
|
388 |
+
All other non-permissive additional terms are considered "further
|
389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
390 |
+
received it, or any part of it, contains a notice stating that it is
|
391 |
+
governed by this License along with a term that is a further
|
392 |
+
restriction, you may remove that term. If a license document contains
|
393 |
+
a further restriction but permits relicensing or conveying under this
|
394 |
+
License, you may add to a covered work material governed by the terms
|
395 |
+
of that license document, provided that the further restriction does
|
396 |
+
not survive such relicensing or conveying.
|
397 |
+
|
398 |
+
If you add terms to a covered work in accord with this section, you
|
399 |
+
must place, in the relevant source files, a statement of the
|
400 |
+
additional terms that apply to those files, or a notice indicating
|
401 |
+
where to find the applicable terms.
|
402 |
+
|
403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
404 |
+
form of a separately written license, or stated as exceptions;
|
405 |
+
the above requirements apply either way.
|
406 |
+
|
407 |
+
8. Termination.
|
408 |
+
|
409 |
+
You may not propagate or modify a covered work except as expressly
|
410 |
+
provided under this License. Any attempt otherwise to propagate or
|
411 |
+
modify it is void, and will automatically terminate your rights under
|
412 |
+
this License (including any patent licenses granted under the third
|
413 |
+
paragraph of section 11).
|
414 |
+
|
415 |
+
However, if you cease all violation of this License, then your
|
416 |
+
license from a particular copyright holder is reinstated (a)
|
417 |
+
provisionally, unless and until the copyright holder explicitly and
|
418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
419 |
+
holder fails to notify you of the violation by some reasonable means
|
420 |
+
prior to 60 days after the cessation.
|
421 |
+
|
422 |
+
Moreover, your license from a particular copyright holder is
|
423 |
+
reinstated permanently if the copyright holder notifies you of the
|
424 |
+
violation by some reasonable means, this is the first time you have
|
425 |
+
received notice of violation of this License (for any work) from that
|
426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
427 |
+
your receipt of the notice.
|
428 |
+
|
429 |
+
Termination of your rights under this section does not terminate the
|
430 |
+
licenses of parties who have received copies or rights from you under
|
431 |
+
this License. If your rights have been terminated and not permanently
|
432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
433 |
+
material under section 10.
|
434 |
+
|
435 |
+
9. Acceptance Not Required for Having Copies.
|
436 |
+
|
437 |
+
You are not required to accept this License in order to receive or
|
438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
440 |
+
to receive a copy likewise does not require acceptance. However,
|
441 |
+
nothing other than this License grants you permission to propagate or
|
442 |
+
modify any covered work. These actions infringe copyright if you do
|
443 |
+
not accept this License. Therefore, by modifying or propagating a
|
444 |
+
covered work, you indicate your acceptance of this License to do so.
|
445 |
+
|
446 |
+
10. Automatic Licensing of Downstream Recipients.
|
447 |
+
|
448 |
+
Each time you convey a covered work, the recipient automatically
|
449 |
+
receives a license from the original licensors, to run, modify and
|
450 |
+
propagate that work, subject to this License. You are not responsible
|
451 |
+
for enforcing compliance by third parties with this License.
|
452 |
+
|
453 |
+
An "entity transaction" is a transaction transferring control of an
|
454 |
+
organization, or substantially all assets of one, or subdividing an
|
455 |
+
organization, or merging organizations. If propagation of a covered
|
456 |
+
work results from an entity transaction, each party to that
|
457 |
+
transaction who receives a copy of the work also receives whatever
|
458 |
+
licenses to the work the party's predecessor in interest had or could
|
459 |
+
give under the previous paragraph, plus a right to possession of the
|
460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
461 |
+
the predecessor has it or can get it with reasonable efforts.
|
462 |
+
|
463 |
+
You may not impose any further restrictions on the exercise of the
|
464 |
+
rights granted or affirmed under this License. For example, you may
|
465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
466 |
+
rights granted under this License, and you may not initiate litigation
|
467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
468 |
+
any patent claim is infringed by making, using, selling, offering for
|
469 |
+
sale, or importing the Program or any portion of it.
|
470 |
+
|
471 |
+
11. Patents.
|
472 |
+
|
473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
474 |
+
License of the Program or a work on which the Program is based. The
|
475 |
+
work thus licensed is called the contributor's "contributor version".
|
476 |
+
|
477 |
+
A contributor's "essential patent claims" are all patent claims
|
478 |
+
owned or controlled by the contributor, whether already acquired or
|
479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
480 |
+
by this License, of making, using, or selling its contributor version,
|
481 |
+
but do not include claims that would be infringed only as a
|
482 |
+
consequence of further modification of the contributor version. For
|
483 |
+
purposes of this definition, "control" includes the right to grant
|
484 |
+
patent sublicenses in a manner consistent with the requirements of
|
485 |
+
this License.
|
486 |
+
|
487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
488 |
+
patent license under the contributor's essential patent claims, to
|
489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
490 |
+
propagate the contents of its contributor version.
|
491 |
+
|
492 |
+
In the following three paragraphs, a "patent license" is any express
|
493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
494 |
+
(such as an express permission to practice a patent or covenant not to
|
495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
496 |
+
party means to make such an agreement or commitment not to enforce a
|
497 |
+
patent against the party.
|
498 |
+
|
499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
500 |
+
and the Corresponding Source of the work is not available for anyone
|
501 |
+
to copy, free of charge and under the terms of this License, through a
|
502 |
+
publicly available network server or other readily accessible means,
|
503 |
+
then you must either (1) cause the Corresponding Source to be so
|
504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
506 |
+
consistent with the requirements of this License, to extend the patent
|
507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
508 |
+
actual knowledge that, but for the patent license, your conveying the
|
509 |
+
covered work in a country, or your recipient's use of the covered work
|
510 |
+
in a country, would infringe one or more identifiable patents in that
|
511 |
+
country that you have reason to believe are valid.
|
512 |
+
|
513 |
+
If, pursuant to or in connection with a single transaction or
|
514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
515 |
+
covered work, and grant a patent license to some of the parties
|
516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
517 |
+
or convey a specific copy of the covered work, then the patent license
|
518 |
+
you grant is automatically extended to all recipients of the covered
|
519 |
+
work and works based on it.
|
520 |
+
|
521 |
+
A patent license is "discriminatory" if it does not include within
|
522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
524 |
+
specifically granted under this License. You may not convey a covered
|
525 |
+
work if you are a party to an arrangement with a third party that is
|
526 |
+
in the business of distributing software, under which you make payment
|
527 |
+
to the third party based on the extent of your activity of conveying
|
528 |
+
the work, and under which the third party grants, to any of the
|
529 |
+
parties who would receive the covered work from you, a discriminatory
|
530 |
+
patent license (a) in connection with copies of the covered work
|
531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
532 |
+
for and in connection with specific products or compilations that
|
533 |
+
contain the covered work, unless you entered into that arrangement,
|
534 |
+
or that patent license was granted, prior to 28 March 2007.
|
535 |
+
|
536 |
+
Nothing in this License shall be construed as excluding or limiting
|
537 |
+
any implied license or other defenses to infringement that may
|
538 |
+
otherwise be available to you under applicable patent law.
|
539 |
+
|
540 |
+
12. No Surrender of Others' Freedom.
|
541 |
+
|
542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
543 |
+
otherwise) that contradict the conditions of this License, they do not
|
544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
546 |
+
License and any other pertinent obligations, then as a consequence you may
|
547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
548 |
+
to collect a royalty for further conveying from those to whom you convey
|
549 |
+
the Program, the only way you could satisfy both those terms and this
|
550 |
+
License would be to refrain entirely from conveying the Program.
|
551 |
+
|
552 |
+
13. Use with the GNU Affero General Public License.
|
553 |
+
|
554 |
+
Notwithstanding any other provision of this License, you have
|
555 |
+
permission to link or combine any covered work with a work licensed
|
556 |
+
under version 3 of the GNU Affero General Public License into a single
|
557 |
+
combined work, and to convey the resulting work. The terms of this
|
558 |
+
License will continue to apply to the part which is the covered work,
|
559 |
+
but the special requirements of the GNU Affero General Public License,
|
560 |
+
section 13, concerning interaction through a network will apply to the
|
561 |
+
combination as such.
|
562 |
+
|
563 |
+
14. Revised Versions of this License.
|
564 |
+
|
565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
566 |
+
the GNU General Public License from time to time. Such new versions will
|
567 |
+
be similar in spirit to the present version, but may differ in detail to
|
568 |
+
address new problems or concerns.
|
569 |
+
|
570 |
+
Each version is given a distinguishing version number. If the
|
571 |
+
Program specifies that a certain numbered version of the GNU General
|
572 |
+
Public License "or any later version" applies to it, you have the
|
573 |
+
option of following the terms and conditions either of that numbered
|
574 |
+
version or of any later version published by the Free Software
|
575 |
+
Foundation. If the Program does not specify a version number of the
|
576 |
+
GNU General Public License, you may choose any version ever published
|
577 |
+
by the Free Software Foundation.
|
578 |
+
|
579 |
+
If the Program specifies that a proxy can decide which future
|
580 |
+
versions of the GNU General Public License can be used, that proxy's
|
581 |
+
public statement of acceptance of a version permanently authorizes you
|
582 |
+
to choose that version for the Program.
|
583 |
+
|
584 |
+
Later license versions may give you additional or different
|
585 |
+
permissions. However, no additional obligations are imposed on any
|
586 |
+
author or copyright holder as a result of your choosing to follow a
|
587 |
+
later version.
|
588 |
+
|
589 |
+
15. Disclaimer of Warranty.
|
590 |
+
|
591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
599 |
+
|
600 |
+
16. Limitation of Liability.
|
601 |
+
|
602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
610 |
+
SUCH DAMAGES.
|
611 |
+
|
612 |
+
17. Interpretation of Sections 15 and 16.
|
613 |
+
|
614 |
+
If the disclaimer of warranty and limitation of liability provided
|
615 |
+
above cannot be given local legal effect according to their terms,
|
616 |
+
reviewing courts shall apply local law that most closely approximates
|
617 |
+
an absolute waiver of all civil liability in connection with the
|
618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
619 |
+
copy of the Program in return for a fee.
|
620 |
+
|
621 |
+
END OF TERMS AND CONDITIONS
|
622 |
+
|
623 |
+
How to Apply These Terms to Your New Programs
|
624 |
+
|
625 |
+
If you develop a new program, and you want it to be of the greatest
|
626 |
+
possible use to the public, the best way to achieve this is to make it
|
627 |
+
free software which everyone can redistribute and change under these terms.
|
628 |
+
|
629 |
+
To do so, attach the following notices to the program. It is safest
|
630 |
+
to attach them to the start of each source file to most effectively
|
631 |
+
state the exclusion of warranty; and each file should have at least
|
632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
633 |
+
|
634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
635 |
+
Copyright (C) <year> <name of author>
|
636 |
+
|
637 |
+
This program is free software: you can redistribute it and/or modify
|
638 |
+
it under the terms of the GNU General Public License as published by
|
639 |
+
the Free Software Foundation, either version 3 of the License, or
|
640 |
+
(at your option) any later version.
|
641 |
+
|
642 |
+
This program is distributed in the hope that it will be useful,
|
643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
645 |
+
GNU General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU General Public License
|
648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
649 |
+
|
650 |
+
Also add information on how to contact you by electronic and paper mail.
|
651 |
+
|
652 |
+
If the program does terminal interaction, make it output a short
|
653 |
+
notice like this when it starts in an interactive mode:
|
654 |
+
|
655 |
+
<program> Copyright (C) <year> <name of author>
|
656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
657 |
+
This is free software, and you are welcome to redistribute it
|
658 |
+
under certain conditions; type `show c' for details.
|
659 |
+
|
660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
661 |
+
parts of the General Public License. Of course, your program's commands
|
662 |
+
might be different; for a GUI interface, you would use an "about box".
|
663 |
+
|
664 |
+
You should also get your employer (if you work as a programmer) or school,
|
665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
667 |
+
<https://www.gnu.org/licenses/>.
|
668 |
+
|
669 |
+
The GNU General Public License does not permit incorporating your program
|
670 |
+
into proprietary programs. If your program is a subroutine library, you
|
671 |
+
may consider it more useful to permit linking proprietary applications with
|
672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
673 |
+
Public License instead of this License. But first, please read
|
674 |
+
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
README.md
ADDED
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
![image](https://github.com/Hillobar/Rope/assets/63615199/40f7397f-713c-4813-ac86-bab36f6bd5ba)
|
2 |
+
|
3 |
+
|
4 |
+
Rope implements the insightface inswapper_128 model with a helpful GUI.
|
5 |
+
### [Discord](https://discord.gg/EcdVAFJzqp)
|
6 |
+
|
7 |
+
### [Donate](https://www.paypal.com/donate/?hosted_button_id=Y5SB9LSXFGRF2)
|
8 |
+
|
9 |
+
### [Wiki with install instructions and usage](https://github.com/Hillobar/Rope/wiki)
|
10 |
+
|
11 |
+
### [Demo Video (Rope-Ruby)](https://www.youtube.com/watch?v=4Y4U0TZ8cWY)
|
12 |
+
|
13 |
+
### ${{\color{Goldenrod}{\textsf{Last Updated 2024-05-27}}}}$ ###
|
14 |
+
### ${{\color{Goldenrod}{\textsf{Welcome to Rope-Pearl!}}}}$ ###
|
15 |
+
|
16 |
+
![Screenshot 2024-02-10 104718](https://github.com/Hillobar/Rope/assets/63615199/4b2ee574-c91e-4db2-ad66-5b775a049a6b)
|
17 |
+
|
18 |
+
### Updates for Rope-Pearl-00: ###
|
19 |
+
### To update from Opal-03a, just need to replace the rope folder.
|
20 |
+
* (feature) Selectable model swapping output resolution - 128, 256, 512
|
21 |
+
* (feature) Better selection of input images (ctrl and shift modifiers work mostly like windows behavior)
|
22 |
+
* (feature) Toggle between mean and median merging withou having to save to compare
|
23 |
+
* (feature) Added back keyboard controls (q, w, a, s, d, space)
|
24 |
+
* (feature) Gamma slider
|
25 |
+
*
|
26 |
+
![image](https://github.com/Hillobar/Rope/assets/63615199/9d89fded-addb-46fe-b2d7-bfe6f1a88188)
|
27 |
+
|
28 |
+
### Performance: ###
|
29 |
+
Machine: 3090Ti (24GB), i5-13600K
|
30 |
+
|
31 |
+
<img src="https://github.com/Hillobar/Rope/assets/63615199/3e3505db-bc76-48df-b8ac-1e7e86c8d751" width="200">
|
32 |
+
|
33 |
+
File: benchmark/target-1080p.mp4, 2048x1080, 269 frames, 25 fps, 10s
|
34 |
+
|
35 |
+
Rendering time in seconds (5 threads):
|
36 |
+
|
37 |
+
| Option | Crystal | Sapphire | Ruby | Opal | Pearl |
|
38 |
+
| --- | --- | --- | --- | --- | --- |
|
39 |
+
| Only Swap (128) | 7.3 | 7.5 | 4.4 | 4.3 | 4.4 |
|
40 |
+
| Swap (256) | --- | --- | --- | --- | 8.6 |
|
41 |
+
| Swap (512) | --- | --- | --- | --- | 28.6 |
|
42 |
+
| Swap+GFPGAN | 10.7 | 11.0 | 9.0 | 9.8 | 9.3 |
|
43 |
+
| Swap+Codeformer | 12.4 | 13.5 | 11.1 | 11.1 | 11.3 |
|
44 |
+
| Swap+one word CLIP | 10.4 | 11.2 | 9.1 | 9.3 | 9.3 |
|
45 |
+
| Swap+Occluder | 7.8 | 7.8 | 4.4 | 4.7 | 4.7 |
|
46 |
+
| Swap+MouthParser | 13.9 | 12.1 | 5.0 | 4.9 | 5.1 |
|
47 |
+
|
48 |
+
### Disclaimer: ###
|
49 |
+
Rope is a personal project that I'm making available to the community as a thank you for all of the contributors ahead of me.
|
50 |
+
I've copied the disclaimer from [Swap-Mukham](https://github.com/harisreedhar/Swap-Mukham) here since it is well-written and applies 100% to this repo.
|
51 |
+
|
52 |
+
I would like to emphasize that our swapping software is intended for responsible and ethical use only. I must stress that users are solely responsible for their actions when using our software.
|
53 |
+
|
54 |
+
Intended Usage: This software is designed to assist users in creating realistic and entertaining content, such as movies, visual effects, virtual reality experiences, and other creative applications. I encourage users to explore these possibilities within the boundaries of legality, ethical considerations, and respect for others' privacy.
|
55 |
+
|
56 |
+
Ethical Guidelines: Users are expected to adhere to a set of ethical guidelines when using our software. These guidelines include, but are not limited to:
|
57 |
+
|
58 |
+
Not creating or sharing content that could harm, defame, or harass individuals. Obtaining proper consent and permissions from individuals featured in the content before using their likeness. Avoiding the use of this technology for deceptive purposes, including misinformation or malicious intent. Respecting and abiding by applicable laws, regulations, and copyright restrictions.
|
59 |
+
|
60 |
+
Privacy and Consent: Users are responsible for ensuring that they have the necessary permissions and consents from individuals whose likeness they intend to use in their creations. We strongly discourage the creation of content without explicit consent, particularly if it involves non-consensual or private content. It is essential to respect the privacy and dignity of all individuals involved.
|
61 |
+
|
62 |
+
Legal Considerations: Users must understand and comply with all relevant local, regional, and international laws pertaining to this technology. This includes laws related to privacy, defamation, intellectual property rights, and other relevant legislation. Users should consult legal professionals if they have any doubts regarding the legal implications of their creations.
|
63 |
+
|
64 |
+
Liability and Responsibility: We, as the creators and providers of the deep fake software, cannot be held responsible for the actions or consequences resulting from the usage of our software. Users assume full liability and responsibility for any misuse, unintended effects, or abusive behavior associated with the content they create.
|
65 |
+
|
66 |
+
By using this software, users acknowledge that they have read, understood, and agreed to abide by the above guidelines and disclaimers. We strongly encourage users to approach this technology with caution, integrity, and respect for the well-being and rights of others.
|
67 |
+
|
68 |
+
Remember, technology should be used to empower and inspire, not to harm or deceive. Let's strive for ethical and responsible use of deep fake technology for the betterment of society.
|
69 |
+
|
70 |
+
|
71 |
+
|
72 |
+
|
Rope.bat
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
call conda activate Rope && python Rope.py
|
2 |
+
pause
|
Rope.py
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
|
3 |
+
from rope import Coordinator
|
4 |
+
if __name__ == "__main__":
|
5 |
+
Coordinator.run()
|
benchmark/target-1080p.mp4
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a52edb2d7905ad57770e3d1953432573dc584b7fdee9367024773b0d4cf0de32
|
3 |
+
size 3323493
|
models/meanshape_68.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:39ffecf84ba73f0d0d7e49380833ba88713c9fcdec51df4f7ac45a48b8f4cc51
|
3 |
+
size 974
|
models/place_model_files_here
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
|
requirements.txt
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
--extra-index-url https://download.pytorch.org/whl/cu118
|
2 |
+
|
3 |
+
numpy==1.23.5
|
4 |
+
opencv-python==4.9.0.80
|
5 |
+
scikit-image==0.21.0
|
6 |
+
tk==0.1.0
|
7 |
+
pillow==9.5.0
|
8 |
+
onnx==1.14.0
|
9 |
+
onnxruntime-gpu==1.16.2
|
10 |
+
protobuf==4.23.2
|
11 |
+
torch==2.0.1+cu118
|
12 |
+
torchvision==0.15.2
|
13 |
+
torchaudio==2.0.2
|
14 |
+
tqdm
|
15 |
+
ftfy
|
16 |
+
regex
|
17 |
+
customtkinter
|
rope/Coordinator.py
ADDED
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# #!/usr/bin/env python3
|
2 |
+
|
3 |
+
import time
|
4 |
+
import torch
|
5 |
+
from torchvision import transforms
|
6 |
+
|
7 |
+
import rope.GUI as GUI
|
8 |
+
import rope.VideoManager as VM
|
9 |
+
import rope.Models as Models
|
10 |
+
from rope.external.clipseg import CLIPDensePredT
|
11 |
+
|
12 |
+
resize_delay = 1
|
13 |
+
mem_delay = 1
|
14 |
+
|
15 |
+
# @profile
|
16 |
+
def coordinator():
|
17 |
+
global gui, vm, action, frame, r_frame, load_notice, resize_delay, mem_delay
|
18 |
+
# start = time.time()
|
19 |
+
|
20 |
+
|
21 |
+
if gui.get_action_length() > 0:
|
22 |
+
action.append(gui.get_action())
|
23 |
+
if vm.get_action_length() > 0:
|
24 |
+
action.append(vm.get_action())
|
25 |
+
##################
|
26 |
+
if vm.get_frame_length() > 0:
|
27 |
+
frame.append(vm.get_frame())
|
28 |
+
|
29 |
+
if len(frame) > 0:
|
30 |
+
gui.set_image(frame[0], False)
|
31 |
+
frame.pop(0)
|
32 |
+
####################
|
33 |
+
if vm.get_requested_frame_length() > 0:
|
34 |
+
r_frame.append(vm.get_requested_frame())
|
35 |
+
if len(r_frame) > 0:
|
36 |
+
gui.set_image(r_frame[0], True)
|
37 |
+
r_frame=[]
|
38 |
+
####################
|
39 |
+
if len(action) > 0:
|
40 |
+
# print('Action:', action[0][0])
|
41 |
+
# print('Value:', action[0][1])
|
42 |
+
if action[0][0] == "load_target_video":
|
43 |
+
vm.load_target_video(action[0][1])
|
44 |
+
action.pop(0)
|
45 |
+
elif action[0][0] == "load_target_image":
|
46 |
+
vm.load_target_image(action[0][1])
|
47 |
+
action.pop(0)
|
48 |
+
elif action[0][0] == "play_video":
|
49 |
+
vm.play_video(action[0][1])
|
50 |
+
action.pop(0)
|
51 |
+
elif action[0][0] == "get_requested_video_frame":
|
52 |
+
vm.get_requested_video_frame(action[0][1], marker=True)
|
53 |
+
action.pop(0)
|
54 |
+
elif action[0][0] == "get_requested_video_frame_without_markers":
|
55 |
+
vm.get_requested_video_frame(action[0][1], marker=False)
|
56 |
+
action.pop(0)
|
57 |
+
elif action[0][0] == "get_requested_image":
|
58 |
+
vm.get_requested_image()
|
59 |
+
action.pop(0)
|
60 |
+
# elif action[0][0] == "swap":
|
61 |
+
# vm.swap = action[0][1]
|
62 |
+
# action.pop(0)
|
63 |
+
elif action[0][0] == "target_faces":
|
64 |
+
vm.assign_found_faces(action[0][1])
|
65 |
+
action.pop(0)
|
66 |
+
elif action [0][0] == "saved_video_path":
|
67 |
+
vm.saved_video_path = action[0][1]
|
68 |
+
action.pop(0)
|
69 |
+
elif action [0][0] == "vid_qual":
|
70 |
+
vm.vid_qual = int(action[0][1])
|
71 |
+
action.pop(0)
|
72 |
+
elif action [0][0] == "set_stop":
|
73 |
+
vm.stop_marker = action[0][1]
|
74 |
+
action.pop(0)
|
75 |
+
elif action [0][0] == "perf_test":
|
76 |
+
vm.perf_test = action[0][1]
|
77 |
+
action.pop(0)
|
78 |
+
elif action [0][0] == 'ui_vars':
|
79 |
+
vm.ui_data = action[0][1]
|
80 |
+
action.pop(0)
|
81 |
+
elif action [0][0] == 'control':
|
82 |
+
vm.control = action[0][1]
|
83 |
+
action.pop(0)
|
84 |
+
elif action [0][0] == "parameters":
|
85 |
+
if action[0][1]["CLIPSwitch"]:
|
86 |
+
if not vm.clip_session:
|
87 |
+
vm.clip_session = load_clip_model()
|
88 |
+
|
89 |
+
vm.parameters = action[0][1]
|
90 |
+
action.pop(0)
|
91 |
+
elif action [0][0] == "markers":
|
92 |
+
vm.markers = action[0][1]
|
93 |
+
action.pop(0)
|
94 |
+
|
95 |
+
|
96 |
+
elif action[0][0] == "function":
|
97 |
+
eval(action[0][1])
|
98 |
+
action.pop(0)
|
99 |
+
elif action [0][0] == "clear_mem":
|
100 |
+
vm.clear_mem()
|
101 |
+
action.pop(0)
|
102 |
+
|
103 |
+
|
104 |
+
# From VM
|
105 |
+
elif action[0][0] == "stop_play":
|
106 |
+
gui.set_player_buttons_to_inactive()
|
107 |
+
action.pop(0)
|
108 |
+
|
109 |
+
elif action[0][0] == "set_slider_length":
|
110 |
+
gui.set_video_slider_length(action[0][1])
|
111 |
+
action.pop(0)
|
112 |
+
|
113 |
+
elif action[0][0] == "update_markers_canvas":
|
114 |
+
gui.update_markers_canvas()
|
115 |
+
action.pop(0)
|
116 |
+
|
117 |
+
|
118 |
+
else:
|
119 |
+
print("Action not found: "+action[0][0]+" "+str(action[0][1]))
|
120 |
+
action.pop(0)
|
121 |
+
|
122 |
+
|
123 |
+
|
124 |
+
|
125 |
+
if resize_delay > 100:
|
126 |
+
gui.check_for_video_resize()
|
127 |
+
resize_delay = 0
|
128 |
+
else:
|
129 |
+
resize_delay +=1
|
130 |
+
|
131 |
+
if mem_delay > 1000:
|
132 |
+
gui.update_vram_indicator()
|
133 |
+
mem_delay = 0
|
134 |
+
else:
|
135 |
+
mem_delay +=1
|
136 |
+
|
137 |
+
vm.process()
|
138 |
+
gui.after(1, coordinator)
|
139 |
+
# print(time.time() - start)
|
140 |
+
|
141 |
+
|
142 |
+
|
143 |
+
|
144 |
+
|
145 |
+
def load_clip_model():
|
146 |
+
# https://github.com/timojl/clipseg
|
147 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
148 |
+
clip_session = CLIPDensePredT(version='ViT-B/16', reduce_dim=64, complex_trans_conv=True)
|
149 |
+
# clip_session = CLIPDensePredTMasked(version='ViT-B/16', reduce_dim=64)
|
150 |
+
clip_session.eval();
|
151 |
+
clip_session.load_state_dict(torch.load('./models/rd64-uni-refined.pth'), strict=False)
|
152 |
+
clip_session.to(device)
|
153 |
+
return clip_session
|
154 |
+
|
155 |
+
|
156 |
+
|
157 |
+
|
158 |
+
def run():
|
159 |
+
global gui, vm, action, frame, r_frame, resize_delay, mem_delay
|
160 |
+
|
161 |
+
models = Models.Models()
|
162 |
+
gui = GUI.GUI(models)
|
163 |
+
vm = VM.VideoManager(models)
|
164 |
+
|
165 |
+
|
166 |
+
action = []
|
167 |
+
frame = []
|
168 |
+
r_frame = []
|
169 |
+
|
170 |
+
gui.initialize_gui()
|
171 |
+
|
172 |
+
|
173 |
+
coordinator()
|
174 |
+
|
175 |
+
gui.mainloop()
|
176 |
+
|
177 |
+
|
rope/Dicts.py
ADDED
@@ -0,0 +1,441 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
DEFAULT_DATA = {
|
2 |
+
# Buttons
|
3 |
+
'AddMarkerButtonDisplay': 'icon',
|
4 |
+
'AddMarkerButtonIconHover': './rope/media/add_marker_hover.png',
|
5 |
+
'AddMarkerButtonIconOff': './rope/media/add_marker_off.png',
|
6 |
+
'AddMarkerButtonIconOn': './rope/media/add_marker_off.png',
|
7 |
+
'AddMarkerButtonInfoText': 'ADD MARKER:\nAttaches a parameter marker to the current frame. Markers copy all parameter settings and apply them to all future frames, or until another marker is encountered.',
|
8 |
+
'AddMarkerButtonState': False,
|
9 |
+
|
10 |
+
'SaveMarkerButtonDisplay': 'icon',
|
11 |
+
'SaveMarkerButtonIconHover': './rope/media/marker_save.png',
|
12 |
+
'SaveMarkerButtonIconOff': './rope/media/marker_save.png',
|
13 |
+
'SaveMarkerButtonIconOn': './rope/media/marker_save.png',
|
14 |
+
'SaveMarkerButtonInfoText': 'SAVE MARKERS:\nSave markers for this source video. The markers will be saved as a json file in the same folder as your source video.',
|
15 |
+
'SaveMarkerButtonState': False,
|
16 |
+
|
17 |
+
'AudioDisplay': 'text',
|
18 |
+
'AudioInfoText': 'ENABLE REAL-TIME AUDIO:\nAdds audio from the input video during preview playback. If you are unable to maintain the input video frame rate, the audio will lag.',
|
19 |
+
'AudioState': False,
|
20 |
+
'AudioText': 'Enable Audio',
|
21 |
+
'AutoSwapState': False,
|
22 |
+
'ClearFacesDisplay': 'text',
|
23 |
+
'ClearFacesIcon': './rope/media/tarfacedel.png',
|
24 |
+
'ClearFacesIconHover': './rope/media/rec.png',
|
25 |
+
'ClearFacesIconOff': './rope/media/rec.png',
|
26 |
+
'ClearFacesIconOn': './rope/media/rec.png',
|
27 |
+
'ClearFacesInfoText': 'REMOVE FACES:\nRemove all currently found faces.',
|
28 |
+
'ClearFacesState': False,
|
29 |
+
'ClearFacesText': 'Clear Faces',
|
30 |
+
'ClearmemState': False,
|
31 |
+
'DefaultParamsButtonDisplay': 'text',
|
32 |
+
'DefaultParamsButtonInfoText': 'LOAD DEFAULT PARAMETERS:\nLoad the Rope default parameters for this column.',
|
33 |
+
'DefaultParamsButtonState': False,
|
34 |
+
'DefaultParamsButtonText': 'Load Defaults',
|
35 |
+
'DelEmbedDisplay': 'text',
|
36 |
+
'DelEmbedIconHover': './rope/media/rec.png',
|
37 |
+
'DelEmbedIconOff': './rope/media/rec.png',
|
38 |
+
'DelEmbedIconOn': './rope/media/rec.png',
|
39 |
+
'DelEmbedInfoText': 'DELETE EMBEDDING:\nDelete the currently selected embedding',
|
40 |
+
'DelEmbedState': False,
|
41 |
+
'DelEmbedText': 'Delete Emb',
|
42 |
+
'DelMarkerButtonDisplay': 'icon',
|
43 |
+
'DelMarkerButtonIconHover': './rope/media/remove_marker_hover.png',
|
44 |
+
'DelMarkerButtonIconOff': './rope/media/remove_marker_off.png',
|
45 |
+
'DelMarkerButtonIconOn': './rope/media/remove_marker_off.png',
|
46 |
+
'DelMarkerButtonInfoText': 'REMOVE MARKER:\nRemoves the parameter marker from the current frame.',
|
47 |
+
'DelMarkerButtonState': False,
|
48 |
+
'FindFacesDisplay': 'text',
|
49 |
+
'FindFacesIcon': './rope/media/tarface.png',
|
50 |
+
'FindFacesIconHover': './rope/media/rec.png',
|
51 |
+
'FindFacesIconOff': './rope/media/rec.png',
|
52 |
+
'FindFacesIconOn': './rope/media/rec.png',
|
53 |
+
'FindFacesInfoText': 'FIND FACES:\nFinds all new faces in the current frame.',
|
54 |
+
'FindFacesState': False,
|
55 |
+
'FindFacesText': 'Find Faces',
|
56 |
+
'ImgDockState': False,
|
57 |
+
'ImgVidMode': 'Videos',
|
58 |
+
'ImgVidState': False,
|
59 |
+
'LoadParamsButtonDisplay': 'text',
|
60 |
+
'LoadParamsButtonInfoText': 'LOAD SAVED PARAMETERS:\nLoads all parameters from this column if they have been previously saved. ',
|
61 |
+
'LoadParamsButtonState': False,
|
62 |
+
'LoadParamsButtonText': 'Load Params',
|
63 |
+
'LoadSFacesDisplay': 'both',
|
64 |
+
'LoadSFacesIcon': './rope/media/save.png',
|
65 |
+
'LoadSFacesIconHover': './rope/media/save.png',
|
66 |
+
'LoadSFacesIconOff': './rope/media/save.png',
|
67 |
+
'LoadSFacesIconOn': './rope/media/save.png',
|
68 |
+
'LoadSFacesInfoText': 'SELECT SOURCE FACES FOLDER:\nSelects and loads Source Faces from Folder. Make sure the folder only contains <good> images.',
|
69 |
+
'LoadSFacesState': False,
|
70 |
+
'LoadSFacesText': 'Select Faces Folder',
|
71 |
+
'LoadTVideosDisplay': 'both',
|
72 |
+
'LoadTVideosIconHover': './rope/media/save.png',
|
73 |
+
'LoadTVideosIconOff': './rope/media/save.png',
|
74 |
+
'LoadTVideosIconOn': './rope/media/save.png',
|
75 |
+
'LoadTVideosInfoText': 'SELECT INPUT VIDEOS/IMAGES FOLDER:\nSelect and load media from folder.',
|
76 |
+
'LoadTVideosState': False,
|
77 |
+
'LoadTVideosText': 'Select Videos Folder',
|
78 |
+
'MaskViewDisplay': 'text',
|
79 |
+
'MaskViewInfoText': 'SHOW MASKS:\nDisplays the mask for a face side-by-side with the face. Useful for understanding the masking behaviors and results.',
|
80 |
+
'MaskViewState': False,
|
81 |
+
'MaskViewText': 'Show Mask',
|
82 |
+
'NextMarkerButtonDisplay': 'icon',
|
83 |
+
'NextMarkerButtonIconHover': './rope/media/next_marker_hover.png',
|
84 |
+
'NextMarkerButtonIconOff': './rope/media/next_marker_off.png',
|
85 |
+
'NextMarkerButtonIconOn': './rope/media/next_marker_off.png',
|
86 |
+
'NextMarkerButtonInfoText': 'NEXT MARKER:\nMove to the next marker.',
|
87 |
+
'NextMarkerButtonState': False,
|
88 |
+
'OutputFolderDisplay': 'both',
|
89 |
+
'OutputFolderIconHover': './rope/media/save.png',
|
90 |
+
'OutputFolderIconOff': './rope/media/save.png',
|
91 |
+
'OutputFolderIconOn': './rope/media/save.png',
|
92 |
+
'OutputFolderInfoText': 'SELECT SAVE FOLDER:\nSelect folder for saved videos and images.',
|
93 |
+
'OutputFolderState': False,
|
94 |
+
'OutputFolderText': 'Select Output Folder',
|
95 |
+
'PerfTestState': False,
|
96 |
+
'PlayDisplay': 'icon',
|
97 |
+
'PlayIconHover': './rope/media/play_hover.png',
|
98 |
+
'PlayIconOff': './rope/media/play_off.png',
|
99 |
+
'PlayIconOn': './rope/media/play_on.png',
|
100 |
+
'PlayInfoText': 'PLAY:\nPlays the video. Press again to stop playing',
|
101 |
+
'PlayState': False,
|
102 |
+
'PrevMarkerButtonDisplay': 'icon',
|
103 |
+
'PrevMarkerButtonIconHover': './rope/media/previous_marker_hover.png',
|
104 |
+
'PrevMarkerButtonIconOff': './rope/media/previous_marker_off.png',
|
105 |
+
'PrevMarkerButtonIconOn': './rope/media/previous_marker_off.png',
|
106 |
+
'PrevMarkerButtonInfoText': 'PREVIOUS MARKER:\nMove to the previous marker.',
|
107 |
+
'PrevMarkerButtonState': False,
|
108 |
+
'RecordDisplay': 'icon',
|
109 |
+
'RecordIconHover': './rope/media/rec_hover.png',
|
110 |
+
'RecordIconOff': './rope/media/rec_off.png',
|
111 |
+
'RecordIconOn': './rope/media/rec_on.png',
|
112 |
+
'RecordInfoText': 'RECORD:\nArms the PLAY button for recording. Press RECORD, then PLAY to record. Press PLAY again to stop recording.',
|
113 |
+
'RecordState': False,
|
114 |
+
'SaveImageState': False,
|
115 |
+
'SaveParamsButtonDisplay': 'text',
|
116 |
+
'SaveParamsButtonInfoText': 'SAVE PARAMETERS:\nSaves all parameters in this column.',
|
117 |
+
'SaveParamsButtonState': False,
|
118 |
+
'SaveParamsButtonText': 'Save Params',
|
119 |
+
'StartRopeDisplay': 'both',
|
120 |
+
'StartRopeIconHover': './rope/media/rope.png',
|
121 |
+
'StartRopeIconOff': './rope/media/rope.png',
|
122 |
+
'StartRopeIconOn': './rope/media/rope.png',
|
123 |
+
'StartRopeInfoText': 'STARTS ROPE:\nStarts up the Rope application.',
|
124 |
+
'StartRopeState': False,
|
125 |
+
'StartRopeText': 'Start Rope',
|
126 |
+
'SwapFacesDisplay': 'text',
|
127 |
+
'SwapFacesInfoText': 'SWAP:\nSwap assigned Source Faces and Target Faces.',
|
128 |
+
'SwapFacesState': False,
|
129 |
+
'SwapFacesText': 'Swap Faces',
|
130 |
+
'TLBeginningDisplay': 'icon',
|
131 |
+
'TLBeginningIconHover': './rope/media/tl_beg_hover.png',
|
132 |
+
'TLBeginningIconOff': './rope/media/tl_beg_off.png',
|
133 |
+
'TLBeginningIconOn': './rope/media/tl_beg_on.png',
|
134 |
+
'TLBeginningInfoText': 'TIMELINE START:\nMove the timeline handle to the first frame.',
|
135 |
+
'TLBeginningState': False,
|
136 |
+
'TLLeftDisplay': 'icon',
|
137 |
+
'TLLeftIconHover': './rope/media/tl_left_hover.png',
|
138 |
+
'TLLeftIconOff': './rope/media/tl_left_off.png',
|
139 |
+
'TLLeftIconOn': './rope/media/tl_left_on.png',
|
140 |
+
'TLLeftInfoText': 'TIMELEFT NUDGE LEFT:\nMove the timeline handle to the left 30 frames.',
|
141 |
+
'TLLeftState': False,
|
142 |
+
'TLRightDisplay': 'icon',
|
143 |
+
'TLRightIconHover': './rope/media/tl_right_hover.png',
|
144 |
+
'TLRightIconOff': './rope/media/tl_right_off.png',
|
145 |
+
'TLRightIconOn': './rope/media/tl_right_on.png',
|
146 |
+
'TLRightInfoText': 'TIMELEFT NUDGE RIGHT:\nMove the timeline handle to the RIGHT 30 frames.',
|
147 |
+
'TLRightState': False,
|
148 |
+
|
149 |
+
'SaveImageButtonDisplay': 'text',
|
150 |
+
'SaveImageButtonInfoText': 'SAVE IMAGE:\nSaves the current image to your Output Folder.',
|
151 |
+
'SaveImageButtonState': False,
|
152 |
+
'SaveImageButtonText': 'Save Image',
|
153 |
+
|
154 |
+
'AutoSwapButtonDisplay': 'text',
|
155 |
+
'AutoSwapButtonInfoText': 'AUTOSWAP:\nAutomatcially applies your currently selected Input Face to new images.',
|
156 |
+
'AutoSwapButtonState': False,
|
157 |
+
'AutoSwapButtonText': 'Auto Swap',
|
158 |
+
|
159 |
+
'ClearVramButtonDisplay': 'text',
|
160 |
+
'ClearVramButtonInfoText': 'CLEAR VRAM:\nClears models from your VRAM.',
|
161 |
+
'ClearVramButtonState': False,
|
162 |
+
'ClearVramButtonText': 'Clear VRAM',
|
163 |
+
|
164 |
+
'GetNewEmbButtonDisplay': 'text',
|
165 |
+
'GetNewEmbButtonInfoText': 'CLEAR VRAM:\nClears models from your VRAM.',
|
166 |
+
'GetNewEmbButtonState': False,
|
167 |
+
'GetNewEmbButtonText': 'Clear VRAM',
|
168 |
+
|
169 |
+
|
170 |
+
'StopMarkerButtonnDisplay': 'icon',
|
171 |
+
'StopMarkerButtonIconHover': './rope/media/previous_marker_hover.png',
|
172 |
+
'StopMarkerButtonIconOff': './rope/media/previous_marker_off.png',
|
173 |
+
'StopMarkerButtonIconOn': './rope/media/previous_marker_off.png',
|
174 |
+
'StopMarkerButtonInfoText': 'CLEAR VRAM:\nClears models from your VRAM.',
|
175 |
+
'StopMarkerButtonState': False,
|
176 |
+
'StopMarkerButtonText': 'Clear VRAM',
|
177 |
+
|
178 |
+
#Switches
|
179 |
+
'ColorSwitchInfoText': 'RGB ADJUSTMENT:\nFine-tune the RGB color values of the swap.',
|
180 |
+
'ColorSwitchState': False,
|
181 |
+
'DiffSwitchInfoText': 'DIFFERENCER:\nAllow some of the original face to show in the swapped result when the difference between the two images is small. Can help bring back some texture to the swapped face',
|
182 |
+
'DiffSwitchState': False,
|
183 |
+
'FaceAdjSwitchInfoText': 'KPS and SCALE ADJUSTMENT:\nThis is an experimental feature to perform direct adjustments to the face landmarks found by the detector. There is also an option to adjust the scale of the swapped face.',
|
184 |
+
'FaceAdjSwitchState': False,
|
185 |
+
#
|
186 |
+
'LandmarksDetectionAdjSwitchInfoText': 'KPS ADJUSTMENT:\nThis is an experimental feature to perform direct adjustments to the face landmarks found by the detector. ',
|
187 |
+
'LandmarksDetectionAdjSwitchState': False,
|
188 |
+
'LandmarksAlignModeFromPointsSwitchInfoText': 'KPS ADJUSTMENT ALIGN MODE FROM POINTS:\nThis is an experimental feature to perform direct adjustments to the face landmarks found from detector key points.',
|
189 |
+
'LandmarksAlignModeFromPointsSwitchState': False,
|
190 |
+
'ShowLandmarksSwitchInfoText': 'Show Landmarks in realtime.',
|
191 |
+
'ShowLandmarksSwitchState': False,
|
192 |
+
#
|
193 |
+
'FaceParserSwitchInfoText': 'BACKGROUND MASK:\nAllow the unprocessed background from the orginal image to show in the final swap.',
|
194 |
+
'FaceParserSwitchState': False,
|
195 |
+
'MouthParserSwitchInfoText': 'MOUTH MASK:\nAllow the mouth from the original face to show on the swapped face.',
|
196 |
+
'MouthParserSwitchState': False,
|
197 |
+
'OccluderSwitchInfoText': 'OCCLUSION MASK:\nAllow objects occluding the face to show up in the swapped image.',
|
198 |
+
'OccluderSwitchState': False,
|
199 |
+
'OrientSwitchInfoText': 'ORIENTATION:\nRotate the face detector to better detect faces at different angles',
|
200 |
+
'OrientSwitchState': False,
|
201 |
+
'RestorerSwitchInfoText': 'FACE RESTORER:\nRestore the swapped image by upscaling.',
|
202 |
+
'RestorerSwitchState': False,
|
203 |
+
'StrengthSwitchInfoText': 'SWAPPER STRENGTH:\nApply additional swapping iterations to increase the strength of the result, which may increase likeness',
|
204 |
+
'StrengthSwitchState': False,
|
205 |
+
'CLIPSwitchInfoText': 'TEXT MASKING:\nUse descriptions to identify objects that will be present in the final swapped image.',
|
206 |
+
'CLIPSwitchState': False,
|
207 |
+
|
208 |
+
# Sliders
|
209 |
+
'BlendSliderAmount': 5,
|
210 |
+
'BlendSliderInc': 1,
|
211 |
+
'BlendSliderInfoText': 'BLEND:\nCombined masks blending distance. Is not applied to the border masks.',
|
212 |
+
'BlendSliderMax': 100,
|
213 |
+
'BlendSliderMin': 0,
|
214 |
+
'BorderBlurSliderAmount': 10,
|
215 |
+
'BorderBlurSliderInc': 1,
|
216 |
+
'BorderBlurSliderInfoText': 'BORDER MASK BLEND:\nBorder mask blending distance.',
|
217 |
+
'BorderBlurSliderMax': 64,
|
218 |
+
'BorderBlurSliderMin': 0,
|
219 |
+
'BorderBottomSliderAmount': 10,
|
220 |
+
'BorderBottomSliderInc': 1,
|
221 |
+
'BorderBottomSliderInfoText': 'BOTTOM BORDER DISTANCE:\nA rectangle with adjustable top, bottom, and sides that blends the swapped face rseult back into the original image.',
|
222 |
+
'BorderBottomSliderMax': 64,
|
223 |
+
'BorderBottomSliderMin': 0,
|
224 |
+
'BorderSidesSliderAmount': 10,
|
225 |
+
'BorderSidesSliderInc': 1,
|
226 |
+
'BorderSidesSliderInfoText': 'SIDES BORDER DISTANCE:\nA rectangle with adjustable top, bottom, and sides that blends the swapped face result back into the original image.',
|
227 |
+
'BorderSidesSliderMax': 64,
|
228 |
+
'BorderSidesSliderMin': 0,
|
229 |
+
'BorderTopSliderAmount': 10,
|
230 |
+
'BorderTopSliderInc': 1,
|
231 |
+
'BorderTopSliderInfoText': 'TOP BORDER DISTANCE:\nA rectangle with adjustable top, bottom, and sides that blends the swapped face result back into the original image.',
|
232 |
+
'BorderTopSliderMax': 64,
|
233 |
+
'BorderTopSliderMin': 0,
|
234 |
+
'ColorBlueSliderAmount': 0,
|
235 |
+
'ColorBlueSliderInc': 1,
|
236 |
+
'ColorBlueSliderInfoText': 'RGB BLUE ADJUSTMENT',
|
237 |
+
'ColorBlueSliderMax': 100,
|
238 |
+
'ColorBlueSliderMin': -100,
|
239 |
+
'ColorGreenSliderAmount': 0,
|
240 |
+
'ColorGreenSliderInc': 1,
|
241 |
+
'ColorGreenSliderInfoText': 'RGB GREEN ADJUSTMENT',
|
242 |
+
'ColorGreenSliderMax': 100,
|
243 |
+
'ColorGreenSliderMin': -100,
|
244 |
+
'ColorRedSliderAmount': 0,
|
245 |
+
'ColorRedSliderInc': 1,
|
246 |
+
'ColorRedSliderInfoText': 'RGB RED ADJUSTMENT',
|
247 |
+
'ColorRedSliderMax': 100,
|
248 |
+
'ColorRedSliderMin': -100,
|
249 |
+
'DetectScoreSliderAmount': 50,
|
250 |
+
'DetectScoreSliderInc': 1,
|
251 |
+
'DetectScoreSliderInfoText': 'DETECTION SCORE LIMIT:\nDetermines the minimum score required for a face to be detected. Higher values require higher quality faces. E.g., if faces are flickering when at extreme angles, raising this will limit swapping attempts.',
|
252 |
+
'DetectScoreSliderMax': 100,
|
253 |
+
'DetectScoreSliderMin': 1,
|
254 |
+
#
|
255 |
+
'LandmarksDetectScoreSliderAmount': 50,
|
256 |
+
'LandmarksDetectScoreSliderInc': 1,
|
257 |
+
'LandmarksDetectScoreSliderInfoText':'LANDMARKS DETECTION SCORE LIMIT:\nDetermines the minimum score required for a face to be detected. Higher values require higher quality faces. E.g., if faces are flickering when at extreme angles, raising this will limit swapping attempts.',
|
258 |
+
'LandmarksDetectScoreSliderMax': 100,
|
259 |
+
'LandmarksDetectScoreSliderMin': 1,
|
260 |
+
#
|
261 |
+
'DiffSliderAmount': 4,
|
262 |
+
'DiffSliderInc': 1,
|
263 |
+
'DiffSliderInfoText': 'DIFFERENCING AMOUNT:\nHigher values relaxes the similarity constraint.',
|
264 |
+
'DiffSliderMax': 100,
|
265 |
+
'DiffSliderMin': 0,
|
266 |
+
'FaceParserSliderAmount': 0,
|
267 |
+
'FaceParserSliderInc': 1,
|
268 |
+
'FaceParserSliderInfoText': 'BACKGROUND MASK AMOUNT:\nNegative/Positive values shrink and grow the mask.',
|
269 |
+
'FaceParserSliderMax': 50,
|
270 |
+
'FaceParserSliderMin': -50,
|
271 |
+
'FaceScaleSliderAmount': 0,
|
272 |
+
'FaceScaleSliderInc': 1,
|
273 |
+
'FaceScaleSliderInfoText': 'FACE SCALE AMOUNT',
|
274 |
+
'FaceScaleSliderMax': 20,
|
275 |
+
'FaceScaleSliderMin': -20,
|
276 |
+
'KPSScaleSliderAmount': 0,
|
277 |
+
'KPSScaleSliderInc': 1,
|
278 |
+
'KPSScaleSliderInfoText': 'KPS SCALE AMOUNT:\nGrows and shrinks the detection point distances.',
|
279 |
+
'KPSScaleSliderMax': 100,
|
280 |
+
'KPSScaleSliderMin': -100,
|
281 |
+
'KPSXSliderAmount': 0,
|
282 |
+
'KPSXSliderInc': 1,
|
283 |
+
'KPSXSliderInfoText': 'KPS X-DIRECTION AMOUNT:\nShifts the detection points left and right',
|
284 |
+
'KPSXSliderMax': 100,
|
285 |
+
'KPSXSliderMin': -100,
|
286 |
+
'KPSYSliderAmount': 0,
|
287 |
+
'KPSYSliderInc': 1,
|
288 |
+
'KPSYSliderInfoText': 'KPS Y-DIRECTION AMOUNT:\nShifts the detection points lup and down',
|
289 |
+
'KPSYSliderMax': 100,
|
290 |
+
'KPSYSliderMin': -100,
|
291 |
+
'MouthParserSliderAmount': 0,
|
292 |
+
'MouthParserSliderInc': 1,
|
293 |
+
'MouthParserSliderInfoText': 'MOUTH MASK AMOUNT:\nAdjust the size of the mask. Negative values only mask the inside of the mouth, including the tongue. Positive values also include lips',
|
294 |
+
'MouthParserSliderMax': 50,
|
295 |
+
'MouthParserSliderMin': -50,
|
296 |
+
'OccluderSliderAmount': 0,
|
297 |
+
'OccluderSliderInc': 1,
|
298 |
+
'OccluderSliderInfoText': 'OCCLUDER AMOUNT:\nGrows or shrinks the occluded region',
|
299 |
+
'OccluderSliderMax': 100,
|
300 |
+
'OccluderSliderMin': -100,
|
301 |
+
'OrientSliderAmount': 0,
|
302 |
+
'OrientSliderInc': 90,
|
303 |
+
'OrientSliderInfoText': 'ORIENTATION ANGLE:\nSet this to the angle of the input face angle to help with laying down/upside down/etc. Angles are read clockwise.',
|
304 |
+
'OrientSliderMax': 270,
|
305 |
+
'OrientSliderMin': 0,
|
306 |
+
'RestorerSliderAmount': 100,
|
307 |
+
'RestorerSliderInc': 5,
|
308 |
+
'RestorerSliderInfoText': 'RESTORER AMOUNT:\nBlends the Restored results back into the original swap.',
|
309 |
+
'RestorerSliderMax': 100,
|
310 |
+
'RestorerSliderMin': 0,
|
311 |
+
'StrengthSliderAmount': 100,
|
312 |
+
'StrengthSliderInc': 25,
|
313 |
+
'StrengthSliderInfoText': 'STRENGTH AMOUNT:\nIncrease up to 5x additional swaps (500%). 200% is generally a good result. Set to 0 to turn off swapping but allow the rest of the pipeline to apply to the original image.',
|
314 |
+
'StrengthSliderMax': 500,
|
315 |
+
'StrengthSliderMin': 0,
|
316 |
+
'ThreadsSliderAmount': 5,
|
317 |
+
'ThreadsSliderInc': 1,
|
318 |
+
'ThreadsSliderInfoText': 'EXECUTION THREADS:\nSet number of execution threads while playing and recording. Depends strongly on GPU VRAM. 5 threads for 24GB.',
|
319 |
+
'ThreadsSliderMax': 20,
|
320 |
+
'ThreadsSliderMin': 1,
|
321 |
+
'ThresholdSliderAmount': 55,
|
322 |
+
'ThresholdSliderInc': 1,
|
323 |
+
'ThresholdSliderInfoText': 'THRESHHOLD AMOUNT:\nRaise to reduce faces hopping around when swapping multiple people. A higher value is stricter.',
|
324 |
+
'ThresholdSliderMax': 100,
|
325 |
+
'ThresholdSliderMin': 0,
|
326 |
+
'VideoQualSliderAmount': 18,
|
327 |
+
'VideoQualSliderInc': 1,
|
328 |
+
'VideoQualSliderInfoText': 'VIDEO QUALITY:\nThe encoding quality of the recorded video. 0 is best, 50 is worst, 18 is mostly lossless. File size increases with a lower quality number.',
|
329 |
+
'VideoQualSliderMax': 50,
|
330 |
+
'VideoQualSliderMin': 0,
|
331 |
+
|
332 |
+
'CLIPSliderAmount': 50,
|
333 |
+
'CLIPSliderInc': 1,
|
334 |
+
'CLIPSliderInfoText': 'TEXT MASKING STENGTH:\nIncrease to strengthen the effect.',
|
335 |
+
'CLIPSliderMax': 100,
|
336 |
+
'CLIPSliderMin': 0,
|
337 |
+
|
338 |
+
'ColorGammaSliderAmount': 1,
|
339 |
+
'ColorGammaSliderInc': 0.02,
|
340 |
+
'ColorGammaSliderInfoText': 'GAMMA VALUE:\nChanges Gamma.',
|
341 |
+
'ColorGammaSliderMax': 2,
|
342 |
+
'ColorGammaSliderMin': 0,
|
343 |
+
|
344 |
+
|
345 |
+
# Text Selection
|
346 |
+
'DetectTypeTextSelInfoText': 'FACE DETECTION MODEL:\nSelect the face detection model. Mostly only subtle differences, but can significant differences when the face is at extreme angles or covered.',
|
347 |
+
'DetectTypeTextSelMode': 'Retinaface',
|
348 |
+
'DetectTypeTextSelModes': ['Retinaface', 'Yolov8', 'SCRDF', 'Yunet'],
|
349 |
+
#
|
350 |
+
'LandmarksDetectTypeTextSelInfoText': 'LANDMARKS FACE DETECTION MODEL:\nSelect the landmarks face detection model. Mostly only subtle differences, but can significant differences when the face is at extreme angles or covered.',
|
351 |
+
'LandmarksDetectTypeTextSelMode': '98',
|
352 |
+
'LandmarksDetectTypeTextSelModes': ['5', '68', '3d68', '98', '106', '478'],
|
353 |
+
#
|
354 |
+
'PreviewModeTextSelInfoText': '',
|
355 |
+
'PreviewModeTextSelMode': 'Video',
|
356 |
+
'PreviewModeTextSelModes': ['Video', 'Image','Theater'],
|
357 |
+
'RecordTypeTextSelInfoText': 'VIDEO RECORDING LIBRARY:\nSelect the recording library used for video recording. FFMPEG uses the Video Quality slider to adjust the size and quality of the final video. OPENCV has no options but is faster and produces good results.',
|
358 |
+
'RecordTypeTextSelMode': 'FFMPEG',
|
359 |
+
'RecordTypeTextSelModes': ['FFMPEG', 'OPENCV'],
|
360 |
+
'RestorerDetTypeTextSelInfoText': 'ALIGNMENT:\nSelect how the face is aligned for the Restorer. Original preserves facial features and expressions, but can show some artifacts. Reference softens features. Blend is closer to Reference but is much faster.',
|
361 |
+
'RestorerDetTypeTextSelMode': 'Blend',
|
362 |
+
'RestorerDetTypeTextSelModes': ['Original', 'Blend', 'Reference'],
|
363 |
+
'RestorerTypeTextSelInfoText': 'RESTORER TYPE:\nSelect the Restorer type.\nSpeed: GPEN256>GFPGAN>CF>GPEN512',
|
364 |
+
'RestorerTypeTextSelMode': 'GFPGAN',
|
365 |
+
'RestorerTypeTextSelModes': ['GFPGAN', 'CF', 'GPEN256', 'GPEN512', 'GPEN1024'],
|
366 |
+
'MergeTextSelInfoText': 'INPUT FACES MERGE MATH:\nWhen shift-clicking face for merging, determines how the embedding vectors are combined.',
|
367 |
+
'MergeTextSelMode': 'Mean',
|
368 |
+
'MergeTextSelModes': ['Mean', 'Median'],
|
369 |
+
'SwapperTypeTextSelInfoText': 'SWAPPER OUTPUT RESOLUTION:\nDetermines the resolution of the swapper output.',
|
370 |
+
'SwapperTypeTextSelMode': '128',
|
371 |
+
'SwapperTypeTextSelModes': ['128', '256', '512'],
|
372 |
+
|
373 |
+
|
374 |
+
|
375 |
+
# Text Entry
|
376 |
+
'CLIPTextEntry': '',
|
377 |
+
'CLIPTextEntryInfoText': 'TEXT MASKING ENTRY:\nTo use, type a word(s) in the box separated by commas and press <enter>.',
|
378 |
+
}
|
379 |
+
|
380 |
+
PARAM_VARS = {
|
381 |
+
|
382 |
+
'CLIPState': False,
|
383 |
+
'CLIPMode': 0,
|
384 |
+
'CLIPModes': ['CLIP'],
|
385 |
+
'CLIPAmount': [50],
|
386 |
+
'CLIPMin': 0,
|
387 |
+
'CLIPMax': 100,
|
388 |
+
'CLIPInc': 1,
|
389 |
+
'CLIPUnit': '%',
|
390 |
+
'CLIPIcon': './rope/media/CLIP.png',
|
391 |
+
'CLIPMessage': 'CLIP - Text based occluder. Occluded objects are visible in the final image (occluded from the mask). [LB: on/off, MW: strength]',
|
392 |
+
'CLIPFunction': False,
|
393 |
+
|
394 |
+
"CLIPText": '',
|
395 |
+
}
|
396 |
+
|
397 |
+
PARAMS = {
|
398 |
+
|
399 |
+
'ClearmemFunction': 'self.clear_mem()',
|
400 |
+
'PerfTestFunction': 'self.toggle_perf_test()',
|
401 |
+
'ImgVidFunction': 'self.toggle_vid_img()',
|
402 |
+
'AutoSwapFunction': 'self.toggle_auto_swap()',
|
403 |
+
'SaveImageFunction': 'self.save_image()',
|
404 |
+
|
405 |
+
'ClearmemIcon': './rope/media/clear_mem.png',
|
406 |
+
'SaveImageIcon': './rope/media/save_disk.png',
|
407 |
+
'PerfTestIcon': './rope/media/test.png',
|
408 |
+
'RefDelIcon': './rope/media/construction.png',
|
409 |
+
'TransformIcon': './rope/media/scale.png',
|
410 |
+
'ThresholdIcon': './rope/media/thresh.png',
|
411 |
+
'LoadSFacesIcon': './rope/media/save.png',
|
412 |
+
'BorderIcon': './rope/media/maskup.png',
|
413 |
+
'OccluderIcon': './rope/media/occluder.png',
|
414 |
+
'ColorIcon': './rope/media/rgb.png',
|
415 |
+
'StrengthIcon': './rope/media/strength.png',
|
416 |
+
'OrientationIcon': './rope/media/orient.png',
|
417 |
+
'DiffIcon': './rope/media/diff.png',
|
418 |
+
'MouthParserIcon': './rope/media/parse.png',
|
419 |
+
'AudioIcon': './rope/media/rgb.png',
|
420 |
+
'VideoQualityIcon': './rope/media/tarface.png',
|
421 |
+
'MaskViewIcon': './rope/media/maskblur.png',
|
422 |
+
'BlurIcon': './rope/media/blur.png',
|
423 |
+
'ToggleStopIcon': './rope/media/STOP.png',
|
424 |
+
'DelEmbedIcon': './rope/media/delemb.png',
|
425 |
+
'ImgVidIcon': './rope/media/imgvid.png',
|
426 |
+
|
427 |
+
|
428 |
+
|
429 |
+
'ImgVidMessage': 'IMAGE/VIDEO - Toggle between Image and Video folder view.',
|
430 |
+
'ToggleStopMessage': 'STOP MARKER - Sets a frame that will stop the video playing/recording.',
|
431 |
+
'AutoSwapMessage': 'AUTO SWAP - Automatically swaps the first person in an image to the selcted source faces [LB: Turn on/off]',
|
432 |
+
'SaveImageMessage': 'SAVE IMAGE - Save image to output folder',
|
433 |
+
'ClearmemMessage': 'CLEAR VRAM - Clears all models from VRAM [LB: Clear]',
|
434 |
+
'PerfTestMessage': 'PERFORMANCE DATA - Displays timing data in the console for critical Rope functions. [LB: on/off]',
|
435 |
+
'RefDelMessage': 'REFERENCE DELTA - Modify the reference points. Turn on mask preview to see adjustments. [LB: on/off, RB: translate x/y, and scale, MW: amount]' ,
|
436 |
+
'ThresholdMessage': 'THRESHOLD - Threshold for determining if Target Faces match faces in a frame. Lower is stricter. [LB: use amount/match all, MW: value]',
|
437 |
+
'TransformMessage': 'SCALE - Adjust the scale of the face. Use with Background parser to blend into the image. [LB: on/off, MW: amount]',
|
438 |
+
'PlayMessage': 'PLAY - Plays the video. Press again to stop playing',
|
439 |
+
|
440 |
+
}
|
441 |
+
|
rope/FaceUtil.py
ADDED
@@ -0,0 +1,405 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import math
|
3 |
+
import numpy as np
|
4 |
+
from skimage import transform as trans
|
5 |
+
import torch
|
6 |
+
import torchvision
|
7 |
+
torchvision.disable_beta_transforms_warning()
|
8 |
+
from torchvision.transforms import v2
|
9 |
+
from numpy.linalg import norm as l2norm
|
10 |
+
|
11 |
+
arcface_src = np.array(
|
12 |
+
[[38.2946, 51.6963], [73.5318, 51.5014], [56.0252, 71.7366],
|
13 |
+
[41.5493, 92.3655], [70.7299, 92.2041]],
|
14 |
+
dtype=np.float32)
|
15 |
+
|
16 |
+
arcface_src = np.expand_dims(arcface_src, axis=0)
|
17 |
+
|
18 |
+
def pad_image_by_size(img, image_size):
|
19 |
+
w, h = math.ceil(img.size(dim=2)), math.ceil(img.size(dim=1))
|
20 |
+
if w < image_size or h < image_size:
|
21 |
+
# add right, bottom pading to the image if its size is less than image_size value
|
22 |
+
add = image_size - min(w, h)
|
23 |
+
img = torch.nn.functional.pad(img, (0, add, 0, add), 'constant', 0)
|
24 |
+
|
25 |
+
return img
|
26 |
+
|
27 |
+
def transform(img, center, output_size, scale, rotation):
|
28 |
+
# pad image by image size
|
29 |
+
img = pad_image_by_size(img, output_size)
|
30 |
+
|
31 |
+
scale_ratio = scale
|
32 |
+
rot = float(rotation) * np.pi / 180.0
|
33 |
+
t1 = trans.SimilarityTransform(scale=scale_ratio)
|
34 |
+
cx = center[0] * scale_ratio
|
35 |
+
cy = center[1] * scale_ratio
|
36 |
+
t2 = trans.SimilarityTransform(translation=(-1 * cx, -1 * cy))
|
37 |
+
t3 = trans.SimilarityTransform(rotation=rot)
|
38 |
+
t4 = trans.SimilarityTransform(translation=(output_size / 2,
|
39 |
+
output_size / 2))
|
40 |
+
t = t1 + t2 + t3 + t4
|
41 |
+
M = t.params[0:2]
|
42 |
+
|
43 |
+
cropped = v2.functional.affine(img, t.rotation, (t.translation[0], t.translation[1]) , t.scale, 0, interpolation=v2.InterpolationMode.BILINEAR, center = (0,0) )
|
44 |
+
cropped = v2.functional.crop(cropped, 0,0, output_size, output_size)
|
45 |
+
|
46 |
+
return cropped, M
|
47 |
+
|
48 |
+
def trans_points2d(pts, M):
|
49 |
+
new_pts = np.zeros(shape=pts.shape, dtype=np.float32)
|
50 |
+
for i in range(pts.shape[0]):
|
51 |
+
pt = pts[i]
|
52 |
+
new_pt = np.array([pt[0], pt[1], 1.], dtype=np.float32)
|
53 |
+
new_pt = np.dot(M, new_pt)
|
54 |
+
#print('new_pt', new_pt.shape, new_pt)
|
55 |
+
new_pts[i] = new_pt[0:2]
|
56 |
+
|
57 |
+
return new_pts
|
58 |
+
|
59 |
+
def trans_points3d(pts, M):
|
60 |
+
scale = np.sqrt(M[0][0] * M[0][0] + M[0][1] * M[0][1])
|
61 |
+
new_pts = np.zeros(shape=pts.shape, dtype=np.float32)
|
62 |
+
for i in range(pts.shape[0]):
|
63 |
+
pt = pts[i]
|
64 |
+
new_pt = np.array([pt[0], pt[1], 1.], dtype=np.float32)
|
65 |
+
new_pt = np.dot(M, new_pt)
|
66 |
+
#print('new_pt', new_pt.shape, new_pt)
|
67 |
+
new_pts[i][0:2] = new_pt[0:2]
|
68 |
+
new_pts[i][2] = pts[i][2] * scale
|
69 |
+
|
70 |
+
return new_pts
|
71 |
+
|
72 |
+
def trans_points(pts, M):
|
73 |
+
if pts.shape[1] == 2:
|
74 |
+
return trans_points2d(pts, M)
|
75 |
+
else:
|
76 |
+
return trans_points3d(pts, M)
|
77 |
+
|
78 |
+
def estimate_affine_matrix_3d23d(X, Y):
|
79 |
+
''' Using least-squares solution
|
80 |
+
Args:
|
81 |
+
X: [n, 3]. 3d points(fixed)
|
82 |
+
Y: [n, 3]. corresponding 3d points(moving). Y = PX
|
83 |
+
Returns:
|
84 |
+
P_Affine: (3, 4). Affine camera matrix (the third row is [0, 0, 0, 1]).
|
85 |
+
'''
|
86 |
+
X_homo = np.hstack((X, np.ones([X.shape[0],1]))) #n x 4
|
87 |
+
P = np.linalg.lstsq(X_homo, Y,rcond=None)[0].T # Affine matrix. 3 x 4
|
88 |
+
return P
|
89 |
+
|
90 |
+
def P2sRt(P):
|
91 |
+
''' decompositing camera matrix P
|
92 |
+
Args:
|
93 |
+
P: (3, 4). Affine Camera Matrix.
|
94 |
+
Returns:
|
95 |
+
s: scale factor.
|
96 |
+
R: (3, 3). rotation matrix.
|
97 |
+
t: (3,). translation.
|
98 |
+
'''
|
99 |
+
t = P[:, 3]
|
100 |
+
R1 = P[0:1, :3]
|
101 |
+
R2 = P[1:2, :3]
|
102 |
+
s = (np.linalg.norm(R1) + np.linalg.norm(R2))/2.0
|
103 |
+
r1 = R1/np.linalg.norm(R1)
|
104 |
+
r2 = R2/np.linalg.norm(R2)
|
105 |
+
r3 = np.cross(r1, r2)
|
106 |
+
|
107 |
+
R = np.concatenate((r1, r2, r3), 0)
|
108 |
+
return s, R, t
|
109 |
+
|
110 |
+
def matrix2angle(R):
|
111 |
+
''' get three Euler angles from Rotation Matrix
|
112 |
+
Args:
|
113 |
+
R: (3,3). rotation matrix
|
114 |
+
Returns:
|
115 |
+
x: pitch
|
116 |
+
y: yaw
|
117 |
+
z: roll
|
118 |
+
'''
|
119 |
+
sy = math.sqrt(R[0,0] * R[0,0] + R[1,0] * R[1,0])
|
120 |
+
|
121 |
+
singular = sy < 1e-6
|
122 |
+
|
123 |
+
if not singular :
|
124 |
+
x = math.atan2(R[2,1] , R[2,2])
|
125 |
+
y = math.atan2(-R[2,0], sy)
|
126 |
+
z = math.atan2(R[1,0], R[0,0])
|
127 |
+
else :
|
128 |
+
x = math.atan2(-R[1,2], R[1,1])
|
129 |
+
y = math.atan2(-R[2,0], sy)
|
130 |
+
z = 0
|
131 |
+
|
132 |
+
# rx, ry, rz = np.rad2deg(x), np.rad2deg(y), np.rad2deg(z)
|
133 |
+
rx, ry, rz = x*180/np.pi, y*180/np.pi, z*180/np.pi
|
134 |
+
return rx, ry, rz
|
135 |
+
|
136 |
+
def warp_face_by_bounding_box(img, bboxes, image_size=112):
|
137 |
+
# pad image by image size
|
138 |
+
img = pad_image_by_size(img, image_size)
|
139 |
+
|
140 |
+
# Set source points from bounding boxes
|
141 |
+
source_points = np.array([ [ bboxes[0], bboxes[1] ], [ bboxes[2], bboxes[1] ], [ bboxes[0], bboxes[3] ], [ bboxes[2], bboxes[3] ] ]).astype(np.float32)
|
142 |
+
|
143 |
+
# Set target points from image size
|
144 |
+
target_points = np.array([ [ 0, 0 ], [ image_size, 0 ], [ 0, image_size ], [ image_size, image_size ] ]).astype(np.float32)
|
145 |
+
|
146 |
+
# Find transform
|
147 |
+
tform = trans.SimilarityTransform()
|
148 |
+
tform.estimate(source_points, target_points)
|
149 |
+
|
150 |
+
# Transform
|
151 |
+
img = v2.functional.affine(img, tform.rotation, (tform.translation[0], tform.translation[1]) , tform.scale, 0, interpolation=v2.InterpolationMode.BILINEAR, center = (0,0) )
|
152 |
+
img = v2.functional.crop(img, 0,0, image_size, image_size)
|
153 |
+
M = tform.params[0:2]
|
154 |
+
|
155 |
+
return img, M
|
156 |
+
|
157 |
+
def warp_face_by_face_landmark_5(img, kpss, image_size=112, normalized = False, interpolation=v2.InterpolationMode.BILINEAR, custom_arcface_src = None):
|
158 |
+
# pad image by image size
|
159 |
+
img = pad_image_by_size(img, image_size)
|
160 |
+
|
161 |
+
M, pose_index = estimate_norm(kpss, image_size, normalized, custom_arcface_src)
|
162 |
+
#warped = cv2.warpAffine(img, M, (image_size, image_size), borderValue=0.0)
|
163 |
+
t = trans.SimilarityTransform()
|
164 |
+
t.params[0:2] = M
|
165 |
+
img = v2.functional.affine(img, t.rotation*57.2958, (t.translation[0], t.translation[1]) , t.scale, 0, interpolation=interpolation, center = (0, 0) )
|
166 |
+
img = v2.functional.crop(img, 0,0, image_size, image_size)
|
167 |
+
|
168 |
+
return img, M
|
169 |
+
|
170 |
+
# lmk is prediction; src is template
|
171 |
+
def estimate_norm(lmk, image_size=112, normalized = False, custom_arcface_src = None):
|
172 |
+
assert lmk.shape == (5, 2)
|
173 |
+
tform = trans.SimilarityTransform()
|
174 |
+
lmk_tran = np.insert(lmk, 2, values=np.ones(5), axis=1)
|
175 |
+
min_M = []
|
176 |
+
min_index = []
|
177 |
+
min_error = float('inf')
|
178 |
+
|
179 |
+
if custom_arcface_src is None:
|
180 |
+
if normalized == False:
|
181 |
+
if image_size == 112:
|
182 |
+
src = arcface_src
|
183 |
+
else:
|
184 |
+
src = float(image_size) / 112.0 * arcface_src
|
185 |
+
else:
|
186 |
+
factor = float(image_size) / 128.0
|
187 |
+
src = arcface_src * factor
|
188 |
+
src[:, 0] += (factor * 8.0)
|
189 |
+
else:
|
190 |
+
src = custom_arcface_src
|
191 |
+
|
192 |
+
for i in np.arange(src.shape[0]):
|
193 |
+
tform.estimate(lmk, src[i])
|
194 |
+
M = tform.params[0:2, :]
|
195 |
+
results = np.dot(M, lmk_tran.T)
|
196 |
+
results = results.T
|
197 |
+
error = np.sum(np.sqrt(np.sum((results - src[i])**2, axis=1)))
|
198 |
+
# print(error)
|
199 |
+
if error < min_error:
|
200 |
+
min_error = error
|
201 |
+
min_M = M
|
202 |
+
min_index = i
|
203 |
+
return min_M, min_index
|
204 |
+
|
205 |
+
def invertAffineTransform(M):
|
206 |
+
t = trans.SimilarityTransform()
|
207 |
+
t.params[0:2] = M
|
208 |
+
IM = t.inverse.params[0:2, :]
|
209 |
+
|
210 |
+
return IM
|
211 |
+
|
212 |
+
def warp_face_by_bounding_box_for_landmark_68(img, bbox, input_size):
|
213 |
+
"""
|
214 |
+
:param img: raw image
|
215 |
+
:param bbox: the bbox for the face
|
216 |
+
:param input_size: tuple input image size
|
217 |
+
:return:
|
218 |
+
"""
|
219 |
+
# pad image by image size
|
220 |
+
img = pad_image_by_size(img, input_size[0])
|
221 |
+
|
222 |
+
scale = 195 / np.subtract(bbox[2:], bbox[:2]).max()
|
223 |
+
translation = (256 - np.add(bbox[2:], bbox[:2]) * scale) * 0.5
|
224 |
+
rotation = 0
|
225 |
+
|
226 |
+
t1 = trans.SimilarityTransform(scale=scale)
|
227 |
+
t2 = trans.SimilarityTransform(rotation=rotation)
|
228 |
+
t3 = trans.SimilarityTransform(translation=translation)
|
229 |
+
|
230 |
+
t = t1 + t2 + t3
|
231 |
+
affine_matrix = np.array([ [ scale, 0, translation[0] ], [ 0, scale, translation[1] ] ])
|
232 |
+
|
233 |
+
crop_image = v2.functional.affine(img, t.rotation, (t.translation[0], t.translation[1]) , t.scale, 0, interpolation=v2.InterpolationMode.BILINEAR, center = (0,0) )
|
234 |
+
crop_image = v2.functional.crop(crop_image, 0,0, input_size[1], input_size[0])
|
235 |
+
|
236 |
+
if torch.mean(crop_image.to(dtype=torch.float32)[0, :, :]) < 30:
|
237 |
+
crop_image = cv2.cvtColor(crop_image.permute(1, 2, 0).to('cpu').numpy(), cv2.COLOR_RGB2Lab)
|
238 |
+
crop_image[:, :, 0] = cv2.createCLAHE(clipLimit = 2).apply(crop_image[:, :, 0])
|
239 |
+
crop_image = torch.from_numpy(cv2.cvtColor(crop_image, cv2.COLOR_Lab2RGB)).to('cuda').permute(2, 0, 1)
|
240 |
+
|
241 |
+
return crop_image, affine_matrix
|
242 |
+
|
243 |
+
def warp_face_by_bounding_box_for_landmark_98(img, bbox_org, input_size):
|
244 |
+
"""
|
245 |
+
:param img: raw image
|
246 |
+
:param bbox: the bbox for the face
|
247 |
+
:param input_size: tuple input image size
|
248 |
+
:return:
|
249 |
+
"""
|
250 |
+
# pad image by image size
|
251 |
+
img = pad_image_by_size(img, input_size[0])
|
252 |
+
|
253 |
+
##preprocess
|
254 |
+
bbox = bbox_org.copy()
|
255 |
+
min_face = 20
|
256 |
+
base_extend_range = [0.2, 0.3]
|
257 |
+
bbox_width = bbox[2] - bbox[0]
|
258 |
+
bbox_height = bbox[3] - bbox[1]
|
259 |
+
if bbox_width <= min_face or bbox_height <= min_face:
|
260 |
+
return None, None
|
261 |
+
add = int(max(bbox_width, bbox_height))
|
262 |
+
|
263 |
+
bimg = torch.nn.functional.pad(img, (add, add, add, add), 'constant', 0)
|
264 |
+
|
265 |
+
bbox += add
|
266 |
+
|
267 |
+
face_width = (1 + 2 * base_extend_range[0]) * bbox_width
|
268 |
+
center = [(bbox[0] + bbox[2]) // 2, (bbox[1] + bbox[3]) // 2]
|
269 |
+
|
270 |
+
### make the box as square
|
271 |
+
bbox[0] = center[0] - face_width // 2
|
272 |
+
bbox[1] = center[1] - face_width // 2
|
273 |
+
bbox[2] = center[0] + face_width // 2
|
274 |
+
bbox[3] = center[1] + face_width // 2
|
275 |
+
|
276 |
+
# crop
|
277 |
+
bbox = bbox.astype(np.int32)
|
278 |
+
crop_image = bimg[:, bbox[1]:bbox[3], bbox[0]:bbox[2]]
|
279 |
+
|
280 |
+
h, w = (crop_image.size(dim=1), crop_image.size(dim=2))
|
281 |
+
|
282 |
+
t_resize = v2.Resize((input_size[1], input_size[0]), antialias=False)
|
283 |
+
crop_image = t_resize(crop_image)
|
284 |
+
|
285 |
+
return crop_image, [h, w, bbox[1], bbox[0], add]
|
286 |
+
|
287 |
+
def create_bounding_box_from_face_landmark_106_98_68(face_landmark_106_98_68):
|
288 |
+
min_x, min_y = np.min(face_landmark_106_98_68, axis = 0)
|
289 |
+
max_x, max_y = np.max(face_landmark_106_98_68, axis = 0)
|
290 |
+
bounding_box = np.array([ min_x, min_y, max_x, max_y ]).astype(np.int16)
|
291 |
+
return bounding_box
|
292 |
+
|
293 |
+
def convert_face_landmark_68_to_5(face_landmark_68, face_landmark_68_score):
|
294 |
+
face_landmark_5 = np.array(
|
295 |
+
[
|
296 |
+
np.mean(face_landmark_68[36:42], axis = 0),
|
297 |
+
np.mean(face_landmark_68[42:48], axis = 0),
|
298 |
+
face_landmark_68[30],
|
299 |
+
face_landmark_68[48],
|
300 |
+
face_landmark_68[54]
|
301 |
+
])
|
302 |
+
|
303 |
+
if np.any(face_landmark_68_score):
|
304 |
+
face_landmark_5_score = np.array(
|
305 |
+
[
|
306 |
+
np.mean(face_landmark_68_score[36:42], axis = 0),
|
307 |
+
np.mean(face_landmark_68_score[42:48], axis = 0),
|
308 |
+
face_landmark_68_score[30],
|
309 |
+
face_landmark_68_score[48],
|
310 |
+
face_landmark_68_score[54]
|
311 |
+
])
|
312 |
+
else:
|
313 |
+
face_landmark_5_score = np.array([])
|
314 |
+
|
315 |
+
return face_landmark_5, face_landmark_5_score
|
316 |
+
|
317 |
+
def convert_face_landmark_98_to_5(face_landmark_98, face_landmark_98_score):
|
318 |
+
face_landmark_5 = np.array(
|
319 |
+
[
|
320 |
+
face_landmark_98[96], # eye left
|
321 |
+
face_landmark_98[97], # eye-right
|
322 |
+
face_landmark_98[54], # nose,
|
323 |
+
face_landmark_98[76], # lip left
|
324 |
+
face_landmark_98[82] # lip right
|
325 |
+
])
|
326 |
+
|
327 |
+
face_landmark_5_score = np.array(
|
328 |
+
[
|
329 |
+
face_landmark_98_score[96], # eye left
|
330 |
+
face_landmark_98_score[97], # eye-right
|
331 |
+
face_landmark_98_score[54], # nose,
|
332 |
+
face_landmark_98_score[76], # lip left
|
333 |
+
face_landmark_98_score[82] # lip right
|
334 |
+
])
|
335 |
+
|
336 |
+
return face_landmark_5, face_landmark_5_score
|
337 |
+
|
338 |
+
def convert_face_landmark_106_to_5(face_landmark_106):
|
339 |
+
face_landmark_5 = np.array(
|
340 |
+
[
|
341 |
+
face_landmark_106[38], # eye left
|
342 |
+
face_landmark_106[88], # eye-right
|
343 |
+
face_landmark_106[86], # nose,
|
344 |
+
face_landmark_106[52], # lip left
|
345 |
+
face_landmark_106[61] # lip right
|
346 |
+
])
|
347 |
+
|
348 |
+
return face_landmark_5
|
349 |
+
|
350 |
+
def convert_face_landmark_478_to_5(face_landmark_478):
|
351 |
+
face_landmark_5 = np.array(
|
352 |
+
[
|
353 |
+
face_landmark_478[468], # eye left
|
354 |
+
#np.array([(face_landmark_478[159][0] + face_landmark_478[145][0]) / 2, (face_landmark_478[159][1] + face_landmark_478[145][1]) / 2]), # eye left (145-159)
|
355 |
+
face_landmark_478[473], # eye-right
|
356 |
+
#np.array([(face_landmark_478[386][0] + face_landmark_478[374][0]) / 2, (face_landmark_478[386][1] + face_landmark_478[374][1]) / 2]), # eye-right (374-386)
|
357 |
+
face_landmark_478[4], # nose, 4, 1
|
358 |
+
face_landmark_478[61], # lip left ? 61, 57
|
359 |
+
face_landmark_478[291] # lip right ? 291, 287
|
360 |
+
])
|
361 |
+
|
362 |
+
return face_landmark_5
|
363 |
+
|
364 |
+
def test_bbox_landmarks(img, bbox, kpss):
|
365 |
+
image = img.permute(1,2,0).to('cpu').numpy().copy()
|
366 |
+
if len(bbox) > 0:
|
367 |
+
box = bbox.astype(int)
|
368 |
+
color = (255, 0, 0)
|
369 |
+
cv2.rectangle(image, (box[0], box[1]), (box[2], box[3]), color, 2)
|
370 |
+
|
371 |
+
if len(kpss) > 0:
|
372 |
+
for i in range(kpss.shape[0]):
|
373 |
+
kps = kpss[i].astype(int)
|
374 |
+
color = (0, 0, 255)
|
375 |
+
cv2.circle(image, (kps[0], kps[1]), 1, color,
|
376 |
+
2)
|
377 |
+
|
378 |
+
cv2.imshow('image', image)
|
379 |
+
cv2.waitKey(0)
|
380 |
+
cv2.destroyAllWindows()
|
381 |
+
|
382 |
+
def test_multi_bbox_landmarks(img, bboxes, kpss):
|
383 |
+
if len(bboxes) > 0 and len(kpss) > 0:
|
384 |
+
for i in range(np.array(kpss).shape[0]):
|
385 |
+
test_bbox_landmarks(img, bboxes[i], kpss[i])
|
386 |
+
|
387 |
+
def detect_img_color(img):
|
388 |
+
frame = img.permute(1,2,0)
|
389 |
+
|
390 |
+
b = frame[:, :, :1]
|
391 |
+
g = frame[:, :, 1:2]
|
392 |
+
r = frame[:, :, 2:]
|
393 |
+
|
394 |
+
# computing the mean
|
395 |
+
b_mean = torch.mean(b.to(float))
|
396 |
+
g_mean = torch.mean(g.to(float))
|
397 |
+
r_mean = torch.mean(r.to(float))
|
398 |
+
|
399 |
+
# displaying the most prominent color
|
400 |
+
if (b_mean > g_mean and b_mean > r_mean):
|
401 |
+
return 'BGR'
|
402 |
+
elif (g_mean > r_mean and g_mean > b_mean):
|
403 |
+
return 'GBR'
|
404 |
+
|
405 |
+
return 'RGB'
|
rope/GUI.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
rope/GUIElements.py
ADDED
@@ -0,0 +1,1248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import tkinter as tk
|
2 |
+
from tkinter import font
|
3 |
+
from PIL import Image, ImageTk
|
4 |
+
|
5 |
+
from rope.Dicts import DEFAULT_DATA
|
6 |
+
import rope.Styles as style
|
7 |
+
|
8 |
+
#import inspect print(inspect.currentframe().f_back.f_code.co_name, 'resize_image')
|
9 |
+
|
10 |
+
class Separator_x():
|
11 |
+
def __init__(self, parent, x, y):
|
12 |
+
self.parent = parent
|
13 |
+
self.x = x
|
14 |
+
self.y = y
|
15 |
+
self.parent.update()
|
16 |
+
self.blank = tk.PhotoImage()
|
17 |
+
self.sep = tk.Label(self.parent, bg='#090909', image=self.blank, compound='c', border=0, width=self.parent.winfo_width(), height=1)
|
18 |
+
self.sep.place(x=self.x, y=self.y)
|
19 |
+
# self.parent.bind('<Configure>', self.update_sep_after_window_resize)
|
20 |
+
|
21 |
+
# def update_sep_after_window_resize(self, event):
|
22 |
+
# self.parent.update()
|
23 |
+
# self.sep.configure(width=self.parent.winfo_width())
|
24 |
+
|
25 |
+
def hide(self):
|
26 |
+
self.sep.place_forget()
|
27 |
+
|
28 |
+
def unhide(self):
|
29 |
+
self.parent.update()
|
30 |
+
self.sep.place(x=self.x, y=self.y)
|
31 |
+
self.sep.configure(width=self.parent.winfo_width())
|
32 |
+
|
33 |
+
|
34 |
+
class Separator_y():
|
35 |
+
def __init__(self, parent, x, y):
|
36 |
+
self.parent = parent
|
37 |
+
self.x = x
|
38 |
+
self.y = y
|
39 |
+
self.parent.update()
|
40 |
+
self.blank = tk.PhotoImage()
|
41 |
+
self.sep = tk.Label(self.parent, bg='#090909', image=self.blank, compound='c', border=0, width=1, height=self.parent.winfo_height())
|
42 |
+
self.sep.place(x=self.x, y=self.y)
|
43 |
+
# self.parent.bind('<Configure>', self.update_sep_after_window_resize)
|
44 |
+
|
45 |
+
# def update_sep_after_window_resize(self, event):
|
46 |
+
# self.parent.update()
|
47 |
+
# self.sep.configure(height=self.parent.winfo_height())
|
48 |
+
|
49 |
+
def hide(self):
|
50 |
+
self.sep.place_forget()
|
51 |
+
|
52 |
+
def unhide(self):
|
53 |
+
self.parent.update()
|
54 |
+
self.sep.place(x=self.x, y=self.y)
|
55 |
+
self.sep.configure(height=self.parent.winfo_height())
|
56 |
+
|
57 |
+
class Text():
|
58 |
+
def __init__(self, parent, text, style_level, x, y, width, height):
|
59 |
+
self.blank = tk.PhotoImage()
|
60 |
+
|
61 |
+
if style_level == 1:
|
62 |
+
self.style = style.text_1
|
63 |
+
elif style_level == 2:
|
64 |
+
self.style = style.text_2
|
65 |
+
elif style_level == 3:
|
66 |
+
self.style = style.text_3
|
67 |
+
|
68 |
+
self.label = tk.Label(parent, self.style, image=self.blank, compound='c', text=text, anchor='w', width=width, height=height)
|
69 |
+
self.label.place(x=x, y=y)
|
70 |
+
|
71 |
+
def configure(self, text):
|
72 |
+
self.label.configure(text=text)
|
73 |
+
|
74 |
+
class Scrollbar_y():
|
75 |
+
def __init__(self, parent, child):
|
76 |
+
|
77 |
+
self.child = child
|
78 |
+
|
79 |
+
self.trough_short_dim = 15
|
80 |
+
self.trough_long_dim = []
|
81 |
+
self.handle_short_dim = self.trough_short_dim*0.5
|
82 |
+
|
83 |
+
self.top_of_handle = []
|
84 |
+
self.middle_of_handle = []
|
85 |
+
self.bottom_of_handle = []
|
86 |
+
|
87 |
+
self.old_coord = 0
|
88 |
+
|
89 |
+
# Child data
|
90 |
+
self.child.bind('<Configure>', self.resize_scrollbar)
|
91 |
+
|
92 |
+
# Set the canvas
|
93 |
+
self.scrollbar_canvas = parent
|
94 |
+
self.scrollbar_canvas.configure(width=self.trough_short_dim)
|
95 |
+
self.scrollbar_canvas.bind("<MouseWheel>", self.scroll)
|
96 |
+
self.scrollbar_canvas.bind("<ButtonPress-1>", self.scroll)
|
97 |
+
self.scrollbar_canvas.bind("<B1-Motion>", self.scroll)
|
98 |
+
|
99 |
+
# Draw handle
|
100 |
+
self.resize_scrollbar(None)
|
101 |
+
|
102 |
+
def resize_scrollbar(self, event): # on window updates
|
103 |
+
self.child.update()
|
104 |
+
self.child.configure(scrollregion=self.child.bbox("all"))
|
105 |
+
|
106 |
+
# Reconfigure data
|
107 |
+
self.trough_long_dim = self.child.winfo_height()
|
108 |
+
self.scrollbar_canvas.delete('all')
|
109 |
+
self.scrollbar_canvas.configure(height=self.trough_long_dim)
|
110 |
+
|
111 |
+
# Redraw the scrollbar
|
112 |
+
x1 = (self.trough_short_dim-self.handle_short_dim)/2
|
113 |
+
x2 = self.trough_short_dim-x1
|
114 |
+
y1 = self.child.yview()[0]*self.trough_long_dim
|
115 |
+
y2 = self.child.yview()[1]*self.trough_long_dim
|
116 |
+
|
117 |
+
self.middle_of_handle = self.scrollbar_canvas.create_rectangle(x1, y1, x2, y2, fill='grey25', outline='')
|
118 |
+
|
119 |
+
def scroll(self, event):
|
120 |
+
delta = 0
|
121 |
+
|
122 |
+
# Get handle dimensions
|
123 |
+
handle_y1 = self.scrollbar_canvas.coords(self.middle_of_handle)[1]
|
124 |
+
handle_y2 = self.scrollbar_canvas.coords(self.middle_of_handle)[3]
|
125 |
+
handle_center = (handle_y2-handle_y1)/2 + handle_y1
|
126 |
+
handle_length = handle_y2-handle_y1
|
127 |
+
|
128 |
+
if event.type == '38': # mousewheel
|
129 |
+
delta = -int(event.delta/20.0)
|
130 |
+
|
131 |
+
elif event.type == '4': # l-button press
|
132 |
+
# If the mouse coord is within the handle dont jump the handle
|
133 |
+
if event.y > handle_y1 and event.y<handle_y2:
|
134 |
+
self.old_coord = event.y
|
135 |
+
else:
|
136 |
+
self.old_coord = handle_center
|
137 |
+
|
138 |
+
delta = event.y-self.old_coord
|
139 |
+
|
140 |
+
elif event.type == '6': # l-button drag
|
141 |
+
delta = event.y-self.old_coord
|
142 |
+
|
143 |
+
# Do some bounding
|
144 |
+
if handle_y1+delta<0:
|
145 |
+
delta = -handle_y1
|
146 |
+
elif handle_y2+delta>self.trough_long_dim:
|
147 |
+
delta = self.trough_long_dim-handle_y2
|
148 |
+
|
149 |
+
# update the scrollbar
|
150 |
+
self.scrollbar_canvas.move(self.middle_of_handle, 0, delta)
|
151 |
+
|
152 |
+
# Get the new handle postition to calculate the change for the child
|
153 |
+
handle_y1 = self.scrollbar_canvas.coords(self.middle_of_handle)[1]
|
154 |
+
|
155 |
+
# Move the child
|
156 |
+
self.child.yview_moveto(handle_y1/self.trough_long_dim)
|
157 |
+
|
158 |
+
self.old_coord = event.y
|
159 |
+
|
160 |
+
def set(self, value):
|
161 |
+
handle_y1 = self.scrollbar_canvas.coords(self.middle_of_handle)[1]
|
162 |
+
handle_y2 = self.scrollbar_canvas.coords(self.middle_of_handle)[3]
|
163 |
+
handle_center = (handle_y2-handle_y1)/2 + handle_y1
|
164 |
+
|
165 |
+
coord_del = self.scrollbar_canvas.winfo_height()*value-handle_center
|
166 |
+
self.old_coord = self.scrollbar_canvas.winfo_height()*value
|
167 |
+
|
168 |
+
self.scrollbar_canvas.move(self.middle_of_handle, 0, coord_del)
|
169 |
+
|
170 |
+
def hide(self):
|
171 |
+
pass
|
172 |
+
|
173 |
+
def unhide(self):
|
174 |
+
pass
|
175 |
+
|
176 |
+
class Timeline():
|
177 |
+
def __init__(self, parent, widget, temp_toggle_swapper, add_action):
|
178 |
+
self.parent = parent
|
179 |
+
self.add_action = add_action
|
180 |
+
self.temp_toggle_swapper = temp_toggle_swapper
|
181 |
+
|
182 |
+
self.frame_length = 0
|
183 |
+
self.height = 20
|
184 |
+
self.counter_width = 40
|
185 |
+
|
186 |
+
self.entry_string = tk.StringVar()
|
187 |
+
self.entry_string.set(0)
|
188 |
+
|
189 |
+
self.last_position = 0
|
190 |
+
|
191 |
+
# Widget variables
|
192 |
+
self.max_ = 100#video_length
|
193 |
+
|
194 |
+
self.handle = []
|
195 |
+
self.slider_left = []
|
196 |
+
self.slider_right = []
|
197 |
+
|
198 |
+
# Event trigget for window resize
|
199 |
+
self.parent.bind('<Configure>', self.window_resize)
|
200 |
+
|
201 |
+
# Add the Slider Canvas to the frame
|
202 |
+
self.slider = tk.Canvas(self.parent, style.timeline_canvas, height=self.height)
|
203 |
+
self.slider.place(x=0, y=0)
|
204 |
+
self.slider.bind('<B1-Motion>', lambda e: self.update_timeline_handle(e, True))
|
205 |
+
self.slider.bind('<ButtonPress-1>', lambda e: self.update_timeline_handle(e, True))
|
206 |
+
self.slider.bind('<ButtonRelease-1>', lambda e: self.update_timeline_handle(e, True))
|
207 |
+
self.slider.bind('<MouseWheel>', lambda e: self.update_timeline_handle(e, True))
|
208 |
+
|
209 |
+
# Add the Entry to the frame
|
210 |
+
self.entry_width = 40
|
211 |
+
self.entry = tk.Entry(self.parent, style.entry_3, textvariable=self.entry_string)
|
212 |
+
self.entry.bind('<Return>', lambda event: self.entry_input(event))
|
213 |
+
|
214 |
+
def draw_timeline(self):
|
215 |
+
self.slider.delete('all')
|
216 |
+
|
217 |
+
# Configure widths and placements
|
218 |
+
self.slider.configure(width=self.frame_length)
|
219 |
+
self.entry.place(x=self.parent.winfo_width()-self.counter_width, y=0)
|
220 |
+
|
221 |
+
# Draw the slider
|
222 |
+
slider_pad = 20
|
223 |
+
entry_pad = 20
|
224 |
+
self.slider_left = slider_pad
|
225 |
+
self.slider_right = self.frame_length-entry_pad-self.entry_width
|
226 |
+
slider_center = (self.height)/2
|
227 |
+
|
228 |
+
line_loc = self.pos2coord(self.last_position)
|
229 |
+
|
230 |
+
line_height = 8
|
231 |
+
line_width = 1.5
|
232 |
+
line_x1 = line_loc-line_width
|
233 |
+
line_y1 = slider_center -line_height
|
234 |
+
line_x2 = line_loc+line_width
|
235 |
+
line_y2 = slider_center +line_height
|
236 |
+
|
237 |
+
|
238 |
+
trough_x1 = self.slider_left
|
239 |
+
trough_y1 = slider_center-1
|
240 |
+
trough_x2 = self.slider_right
|
241 |
+
trough_y2 = slider_center+1
|
242 |
+
|
243 |
+
self.slider.create_rectangle(trough_x1, trough_y1, trough_x2, trough_y2, fill='#43474D', outline='')
|
244 |
+
self.handle = self.slider.create_rectangle(line_x1, line_y1, line_x2, line_y2, fill='#FFFFFF', outline='')
|
245 |
+
|
246 |
+
def coord2pos(self, coord):
|
247 |
+
return float(coord-self.slider_left)*self.max_/(self.slider_right-self.slider_left)
|
248 |
+
|
249 |
+
def pos2coord(self, pos):
|
250 |
+
return float(float(pos)*(self.slider_right-self.slider_left)/self.max_ + self.slider_left)
|
251 |
+
|
252 |
+
|
253 |
+
def update_timeline_handle(self, event, also_update_entry=False):
|
254 |
+
requested = True
|
255 |
+
|
256 |
+
if isinstance(event, float):
|
257 |
+
position = event
|
258 |
+
requested = False
|
259 |
+
else:
|
260 |
+
if event.type == '38': # mousewheel
|
261 |
+
position = self.last_position+int(event.delta/120.0)
|
262 |
+
|
263 |
+
elif event.type == '4': # l-button press
|
264 |
+
x_coord = float(event.x)
|
265 |
+
position = self.coord2pos(x_coord)
|
266 |
+
|
267 |
+
# Turn off swapping
|
268 |
+
self.temp_toggle_swapper('off')
|
269 |
+
self.add_action("play_video", "stop")
|
270 |
+
|
271 |
+
elif event.type == '5': # l-button release
|
272 |
+
x_coord = float(event.x)
|
273 |
+
position = self.coord2pos(x_coord)
|
274 |
+
|
275 |
+
# Turn on swapping, if it was already on and request new frame
|
276 |
+
self.temp_toggle_swapper('on')
|
277 |
+
|
278 |
+
elif event.type == '6': # l-button drag
|
279 |
+
x_coord = float(event.x)
|
280 |
+
position = self.coord2pos(x_coord)
|
281 |
+
|
282 |
+
# constrain mousewheel movement
|
283 |
+
if position < 0: position = 0
|
284 |
+
elif position > self.max_: position = self.max_
|
285 |
+
|
286 |
+
# Find closest position increment
|
287 |
+
position = round(position)
|
288 |
+
|
289 |
+
# moving sends many events, so only update when the next frame is reached
|
290 |
+
if position != self.last_position:
|
291 |
+
# Move handle to coordinate based on position
|
292 |
+
self.slider.move(self.handle, self.pos2coord(position) - self.pos2coord(self.last_position), 0)
|
293 |
+
|
294 |
+
if requested:
|
295 |
+
self.add_action("get_requested_video_frame", position)
|
296 |
+
|
297 |
+
# Save for next time
|
298 |
+
self.last_position = position
|
299 |
+
|
300 |
+
if also_update_entry:
|
301 |
+
self.entry_string.set(str(position))
|
302 |
+
|
303 |
+
def entry_input(self, event):
|
304 |
+
# event.char
|
305 |
+
self.entry.update()
|
306 |
+
try:
|
307 |
+
input_num = float(self.entry_string.get())
|
308 |
+
self.update_timeline_handle(input_num, False)
|
309 |
+
except:
|
310 |
+
return
|
311 |
+
|
312 |
+
def set(self, value):
|
313 |
+
self.update_timeline_handle(float(value), also_update_entry=True)
|
314 |
+
|
315 |
+
def get(self):
|
316 |
+
return int(self.last_position)
|
317 |
+
|
318 |
+
|
319 |
+
def set_length(self, value):
|
320 |
+
self.max_ = value
|
321 |
+
self.update_timeline_handle(float(self.last_position), also_update_entry=True)
|
322 |
+
|
323 |
+
def get_length(self):
|
324 |
+
return int(self.max_)
|
325 |
+
|
326 |
+
# Event when the window is resized
|
327 |
+
def window_resize(self, event):
|
328 |
+
self.parent.update()
|
329 |
+
self.frame_length = self.parent.winfo_width()
|
330 |
+
self.draw_timeline()
|
331 |
+
|
332 |
+
|
333 |
+
|
334 |
+
|
335 |
+
class Button():
|
336 |
+
def __init__(self, parent, name, style_level, function, args, data_type, x, y, width=125, height=20):
|
337 |
+
self.default_data = DEFAULT_DATA
|
338 |
+
self.name = name
|
339 |
+
self.function = function
|
340 |
+
self.args = args
|
341 |
+
self.info = []
|
342 |
+
self.state = []
|
343 |
+
self.hold_state = []
|
344 |
+
self.error = []
|
345 |
+
self.data_type = data_type
|
346 |
+
|
347 |
+
if style_level == 1:
|
348 |
+
self.button_style = style.button_1
|
349 |
+
elif style_level == 2:
|
350 |
+
self.button_style = style.button_2
|
351 |
+
elif style_level == 3:
|
352 |
+
self.button_style = style.button_3
|
353 |
+
|
354 |
+
|
355 |
+
# Add Icon
|
356 |
+
if self.default_data[self.name+'Display'] == 'both':
|
357 |
+
img = Image.open(self.default_data[self.name+'IconOn'])
|
358 |
+
resized_image= img.resize((20,20), Image.ANTIALIAS)
|
359 |
+
self.icon_on = ImageTk.PhotoImage(resized_image)
|
360 |
+
img = Image.open(self.default_data[self.name+'IconOff'])
|
361 |
+
resized_image= img.resize((20,20), Image.ANTIALIAS)
|
362 |
+
self.icon_off = ImageTk.PhotoImage(resized_image)
|
363 |
+
img = Image.open(self.default_data[self.name+'IconHover'])
|
364 |
+
resized_image= img.resize((20,20), Image.ANTIALIAS)
|
365 |
+
self.icon_hover = ImageTk.PhotoImage(resized_image)
|
366 |
+
|
367 |
+
text = ' '+self.default_data[self.name+'Text']
|
368 |
+
|
369 |
+
elif self.default_data[self.name+'Display'] == 'icon':
|
370 |
+
img = Image.open(self.default_data[self.name+'IconOn'])
|
371 |
+
resized_image= img.resize((20,20), Image.ANTIALIAS)
|
372 |
+
self.icon_on = ImageTk.PhotoImage(resized_image)
|
373 |
+
img = Image.open(self.default_data[self.name+'IconOff'])
|
374 |
+
resized_image= img.resize((20,20), Image.ANTIALIAS)
|
375 |
+
self.icon_off = ImageTk.PhotoImage(resized_image)
|
376 |
+
img = Image.open(self.default_data[self.name+'IconHover'])
|
377 |
+
resized_image= img.resize((20,20), Image.ANTIALIAS)
|
378 |
+
self.icon_hover = ImageTk.PhotoImage(resized_image)
|
379 |
+
|
380 |
+
text = ''
|
381 |
+
|
382 |
+
elif self.default_data[self.name+'Display'] == 'text':
|
383 |
+
self.icon_on = tk.PhotoImage()
|
384 |
+
self.icon_off = tk.PhotoImage()
|
385 |
+
self.icon_hover = tk.PhotoImage()
|
386 |
+
|
387 |
+
text = ' '+self.default_data[self.name+'Text']
|
388 |
+
|
389 |
+
# Create Button and place
|
390 |
+
self.button = tk.Button(parent, self.button_style, compound='left', text=text, anchor='w')
|
391 |
+
self.button.configure(width=width, height=height)
|
392 |
+
self.button.place(x=x, y=y)
|
393 |
+
|
394 |
+
self.button.bind("<Enter>", lambda event: self.on_enter())
|
395 |
+
self.button.bind("<Leave>", lambda event: self.on_leave())
|
396 |
+
|
397 |
+
if self.function != None:
|
398 |
+
if self.args != None:
|
399 |
+
self.button.configure(command=lambda: self.function(self.args))
|
400 |
+
else:
|
401 |
+
self.button.configure(command=lambda: self.function())
|
402 |
+
|
403 |
+
# Set inital state
|
404 |
+
self.button.configure(image=self.icon_on)
|
405 |
+
|
406 |
+
if self.default_data[self.name+'State']:
|
407 |
+
self.enable_button()
|
408 |
+
|
409 |
+
else:
|
410 |
+
self.disable_button()
|
411 |
+
|
412 |
+
def add_info_frame(self, info):
|
413 |
+
self.info = info
|
414 |
+
|
415 |
+
|
416 |
+
def on_enter(self):
|
417 |
+
if self.info:
|
418 |
+
self.info.configure(text=self.default_data[self.name+'InfoText'])
|
419 |
+
|
420 |
+
if not self.state and not self.error:
|
421 |
+
self.button.configure(image=self.icon_hover)
|
422 |
+
self.button.configure(fg='#B1B1B2')
|
423 |
+
|
424 |
+
def on_leave(self):
|
425 |
+
if not self.state and not self.error:
|
426 |
+
|
427 |
+
self.button.configure(image=self.icon_off)
|
428 |
+
self.button.configure(fg='#828282')
|
429 |
+
|
430 |
+
def enable_button(self):
|
431 |
+
|
432 |
+
self.button.configure(image=self.icon_on)
|
433 |
+
self.button.configure(fg='#FFFFFF')
|
434 |
+
self.state = True
|
435 |
+
self.error = False
|
436 |
+
|
437 |
+
def disable_button(self):
|
438 |
+
|
439 |
+
self.button.configure(image=self.icon_off)
|
440 |
+
self.button.configure(fg='#828282')
|
441 |
+
self.state = False
|
442 |
+
self.error = False
|
443 |
+
|
444 |
+
def toggle_button(self):
|
445 |
+
self.state = not self.state
|
446 |
+
|
447 |
+
if self.state:
|
448 |
+
self.button.configure(image=self.icon_on)
|
449 |
+
self.button.configure(fg='#FFFFFF')
|
450 |
+
else:
|
451 |
+
self.button.configure(image=self.icon_off)
|
452 |
+
self.button.configure(fg='#828282')
|
453 |
+
|
454 |
+
def temp_disable_button(self):
|
455 |
+
self.hold_state = self.state
|
456 |
+
self.state = False
|
457 |
+
|
458 |
+
def temp_enable_button(self):
|
459 |
+
self.state = self.hold_state
|
460 |
+
|
461 |
+
def error_button(self):
|
462 |
+
|
463 |
+
self.button.configure(image=self.icon_off)
|
464 |
+
self.button.configure(fg='light goldenrod')
|
465 |
+
self.state = False
|
466 |
+
self.error = True
|
467 |
+
|
468 |
+
def get(self):
|
469 |
+
return self.state
|
470 |
+
|
471 |
+
def set(self, value, request_frame=True):
|
472 |
+
if value:
|
473 |
+
self.enable_button()
|
474 |
+
|
475 |
+
elif not value:
|
476 |
+
self.disable_button()
|
477 |
+
if request_frame:
|
478 |
+
if self.function != None:
|
479 |
+
if self.args != None:
|
480 |
+
self.function(self.args)
|
481 |
+
else:
|
482 |
+
self.function()
|
483 |
+
|
484 |
+
def hide(self):
|
485 |
+
pass
|
486 |
+
|
487 |
+
def unhide(self):
|
488 |
+
pass
|
489 |
+
|
490 |
+
def get_data_type(self):
|
491 |
+
return self.data_type
|
492 |
+
|
493 |
+
def load_default(self):
|
494 |
+
self.set(self.default_data[self.name+'State'])
|
495 |
+
|
496 |
+
class TextSelection():
|
497 |
+
def __init__(self, parent, name, display_text, style_level, function, argument, data_type, width, height, x, y, text_percent):
|
498 |
+
self.blank = tk.PhotoImage()
|
499 |
+
|
500 |
+
self.default_data = DEFAULT_DATA
|
501 |
+
# Capture inputs as instance variables
|
502 |
+
self.parent = parent
|
503 |
+
self.name = name
|
504 |
+
self.function = function
|
505 |
+
self.argument = argument
|
506 |
+
self.data_type = data_type
|
507 |
+
self.width = width
|
508 |
+
self.height = height
|
509 |
+
self.style = []
|
510 |
+
self.info = []
|
511 |
+
|
512 |
+
if style_level == 3:
|
513 |
+
self.frame_style = style.canvas_frame_label_3
|
514 |
+
self.text_style = style.text_3
|
515 |
+
self.sel_off_style = style.text_selection_off_3
|
516 |
+
self.sel_on_style = style.text_selection_on_3
|
517 |
+
|
518 |
+
if style_level == 2:
|
519 |
+
self.frame_style = style.canvas_frame_label_2
|
520 |
+
self.text_style = style.text_2
|
521 |
+
self.sel_off_style = style.text_selection_off_2
|
522 |
+
self.sel_on_style = style.text_selection_on_2
|
523 |
+
|
524 |
+
self.display_text = display_text+' '
|
525 |
+
|
526 |
+
self.textselect_label = {}
|
527 |
+
|
528 |
+
# Initial data
|
529 |
+
self.selection = self.default_data[self.name+'Mode']
|
530 |
+
|
531 |
+
# Frame to hold everything
|
532 |
+
self.ts_frame = tk.Frame(self.parent, self.frame_style, width=self.width, height=self.height)
|
533 |
+
self.ts_frame.place(x=x, y=y)
|
534 |
+
self.ts_frame.bind("<Enter>", lambda event: self.on_enter())
|
535 |
+
|
536 |
+
self.text_width = int(width*(1.0-text_percent))
|
537 |
+
|
538 |
+
# Create the text on the left
|
539 |
+
self.text_label = tk.Label(self.ts_frame, self.text_style, image=self.blank, compound='c', text=self.display_text, anchor='e', width=self.text_width, height=height)
|
540 |
+
self.text_label.place(x=0, y=0)
|
541 |
+
|
542 |
+
# Loop through the parameter modes, create a label
|
543 |
+
# Gotta find the size of the buttons according to the font
|
544 |
+
self.font = tk.font.Font(family="Segoe UI", size=10, weight="normal")
|
545 |
+
x_spacing = self.text_width + 10
|
546 |
+
|
547 |
+
|
548 |
+
for mode in self.default_data[self.name+'Modes']:
|
549 |
+
# Get size of text in pixels
|
550 |
+
m_len = self.font.measure(mode)
|
551 |
+
|
552 |
+
# Create a label with the text
|
553 |
+
self.textselect_label[mode] = tk.Label(self.ts_frame, self.sel_off_style, text=mode, image=self.blank, compound='c', anchor='c', width=m_len, height=height)
|
554 |
+
self.textselect_label[mode].place(x=x_spacing, y=0)
|
555 |
+
self.textselect_label[mode].bind("<ButtonRelease-1>", lambda event, mode=mode: self.select_ui_text_selection(mode))
|
556 |
+
|
557 |
+
# Initial value
|
558 |
+
if mode==self.selection:
|
559 |
+
self.textselect_label[mode].configure(self.sel_on_style)
|
560 |
+
|
561 |
+
x_spacing = x_spacing + m_len+10
|
562 |
+
|
563 |
+
def select_ui_text_selection(self, selection, request_frame=True):
|
564 |
+
# Loop over all of the Modes
|
565 |
+
for mode in self.default_data[self.name+'Modes']:
|
566 |
+
|
567 |
+
# If the Mode has been selected
|
568 |
+
if mode==selection:
|
569 |
+
# Set state to true
|
570 |
+
self.textselect_label[mode].configure(self.sel_on_style)
|
571 |
+
self.selection = mode
|
572 |
+
if request_frame:
|
573 |
+
self.function(self.argument, self.name)
|
574 |
+
|
575 |
+
else:
|
576 |
+
self.textselect_label[mode].configure(self.sel_off_style)
|
577 |
+
|
578 |
+
def add_info_frame(self, info):
|
579 |
+
self.info = info
|
580 |
+
|
581 |
+
def on_enter(self):
|
582 |
+
if self.info:
|
583 |
+
self.info.configure(text=self.default_data[self.name+'InfoText'])
|
584 |
+
|
585 |
+
def get(self):
|
586 |
+
return self.selection
|
587 |
+
|
588 |
+
def set(self, value, request_frame=True):
|
589 |
+
self.select_ui_text_selection(value, request_frame)
|
590 |
+
|
591 |
+
def hide(self):
|
592 |
+
pass
|
593 |
+
|
594 |
+
def unhide(self):
|
595 |
+
pass
|
596 |
+
|
597 |
+
def get_data_type(self):
|
598 |
+
return self.data_type
|
599 |
+
|
600 |
+
def load_default(self):
|
601 |
+
self.set(self.default_data[self.name+'Mode'])
|
602 |
+
|
603 |
+
|
604 |
+
class Switch2():
|
605 |
+
def __init__(self, parent, name, display_text, style_level, function, argument, width, height, x, y, toggle_x=0, toggle_width=40):
|
606 |
+
self.blank = tk.PhotoImage()
|
607 |
+
self.default_data = DEFAULT_DATA
|
608 |
+
# Capture inputs as instance variables
|
609 |
+
self.parent = parent
|
610 |
+
self.name = name
|
611 |
+
self.function = function
|
612 |
+
self.argument = argument
|
613 |
+
self.data_type = argument
|
614 |
+
self.width = width
|
615 |
+
self.height = height
|
616 |
+
self.x = x
|
617 |
+
self.y = y
|
618 |
+
self.style = []
|
619 |
+
self.info = []
|
620 |
+
|
621 |
+
# Initial Value
|
622 |
+
self.state = self.default_data[name+'State']
|
623 |
+
|
624 |
+
if style_level == 3:
|
625 |
+
self.frame_style = style.canvas_frame_label_3
|
626 |
+
self.text_style = style.text_3
|
627 |
+
self.entry_style = style.entry_3
|
628 |
+
|
629 |
+
self.display_text = display_text
|
630 |
+
# Load Icons
|
631 |
+
self.img = Image.open(style.icon['IconOff'])
|
632 |
+
self.img = self.img.resize((40,40), Image.ANTIALIAS)
|
633 |
+
self.icon_off = ImageTk.PhotoImage(self.img)
|
634 |
+
|
635 |
+
self.img = Image.open(style.icon['IconOn'])
|
636 |
+
self.img = self.img.resize((40,40), Image.ANTIALIAS)
|
637 |
+
self.icon_on = ImageTk.PhotoImage(self.img)
|
638 |
+
|
639 |
+
# Frame to hold everything
|
640 |
+
self.switch_frame = tk.Frame(self.parent, self.frame_style, width=self.width, height=self.height)
|
641 |
+
self.switch_frame.place(x=self.x, y=self.y)
|
642 |
+
self.switch_frame.bind("<Enter>", lambda event: self.on_enter())
|
643 |
+
|
644 |
+
|
645 |
+
#toggle_width = 40
|
646 |
+
text_width = self.width-toggle_width
|
647 |
+
|
648 |
+
# Toggle Switch
|
649 |
+
self.switch = tk.Label(self.switch_frame, style.parameter_switch_3, image=self.icon_off, width=toggle_width, height=self.height)
|
650 |
+
if self.state:
|
651 |
+
self.switch.configure(image=self.icon_on)
|
652 |
+
#self.switch.place(x=0, y=2)
|
653 |
+
self.switch.place(x=toggle_x, y=2)
|
654 |
+
self.switch.bind("<ButtonRelease-1>", lambda event: self.toggle_switch(event))
|
655 |
+
|
656 |
+
# Text
|
657 |
+
self.switch_text = tk.Label(self.switch_frame, style.parameter_switch_3, image=self.blank, compound='right', text=self.display_text, anchor='w', width=text_width, height=height-2)
|
658 |
+
#self.switch_text.place(x=50, y=0)
|
659 |
+
self.switch_text.place(x=toggle_x + toggle_width + 10, y=0)
|
660 |
+
|
661 |
+
def toggle_switch(self, event, set_value=None, request_frame=True):
|
662 |
+
# flip state
|
663 |
+
if set_value==None:
|
664 |
+
self.state = not self.state
|
665 |
+
else:
|
666 |
+
self.state = set_value
|
667 |
+
|
668 |
+
if self.state:
|
669 |
+
self.switch.configure(image=self.icon_on)
|
670 |
+
|
671 |
+
else:
|
672 |
+
self.switch.configure(image=self.icon_off)
|
673 |
+
|
674 |
+
if request_frame:
|
675 |
+
self.function(self.argument, self.name, use_markers=False)
|
676 |
+
|
677 |
+
def add_info_frame(self, info):
|
678 |
+
self.info = info
|
679 |
+
|
680 |
+
def on_enter(self):
|
681 |
+
if self.info:
|
682 |
+
self.info.configure(text=self.default_data[self.name+'InfoText'])
|
683 |
+
|
684 |
+
def hide(self):
|
685 |
+
self.switch_frame.place_forget()
|
686 |
+
self.switch.place_forget()
|
687 |
+
self.switch_text.place_forget()
|
688 |
+
|
689 |
+
def unhide(self):
|
690 |
+
self.switch_frame.place(x=self.x, y=self.y)
|
691 |
+
self.switch.place(x=0, y=2)
|
692 |
+
self.switch_text.place(x=50, y=0)
|
693 |
+
|
694 |
+
def set(self, value, request_frame=True):
|
695 |
+
self.toggle_switch(None, value, request_frame)
|
696 |
+
|
697 |
+
def get(self):
|
698 |
+
return self.state
|
699 |
+
|
700 |
+
def get_data_type(self):
|
701 |
+
return self.data_type
|
702 |
+
|
703 |
+
def load_default(self):
|
704 |
+
self.set(self.default_data[self.name+'State'])
|
705 |
+
|
706 |
+
class Slider2():
|
707 |
+
def __init__(self, parent, name, display_text, style_level, function, argument, width, height, x, y, slider_percent):
|
708 |
+
|
709 |
+
# self.constants = CONSTANTS
|
710 |
+
self.default_data = DEFAULT_DATA
|
711 |
+
self.blank = tk.PhotoImage()
|
712 |
+
|
713 |
+
# Capture inputs as instance variables
|
714 |
+
self.parent = parent
|
715 |
+
self.name = name
|
716 |
+
self.function = function
|
717 |
+
self.data_type = argument
|
718 |
+
self.x = x
|
719 |
+
self.y = y
|
720 |
+
self.slider_percent = slider_percent
|
721 |
+
self.width = width
|
722 |
+
self.height = height
|
723 |
+
self.info = []
|
724 |
+
|
725 |
+
# Initial Value
|
726 |
+
self.amount = self.default_data[name+'Amount']
|
727 |
+
|
728 |
+
if style_level == 1:
|
729 |
+
self.frame_style = style.canvas_frame_label_1
|
730 |
+
self.text_style = style.text_1
|
731 |
+
self.entry_style = style.entry_3
|
732 |
+
|
733 |
+
elif style_level == 3:
|
734 |
+
self.frame_style = style.canvas_frame_label_3
|
735 |
+
self.text_style = style.text_3
|
736 |
+
self.entry_style = style.entry_3
|
737 |
+
|
738 |
+
# UI-controlled variables
|
739 |
+
self.entry_string = tk.StringVar()
|
740 |
+
self.entry_string.set(self.amount)
|
741 |
+
|
742 |
+
# Widget variables
|
743 |
+
self.min_ = self.default_data[name+'Min']
|
744 |
+
self.max_ = self.default_data[name+'Max']
|
745 |
+
self.inc_ = self.default_data[name+'Inc']
|
746 |
+
self.display_text = display_text+' '
|
747 |
+
|
748 |
+
# Set up spacing
|
749 |
+
# |----------------------|slider_pad|-slider-|entry_pad|-|
|
750 |
+
# |---1-slider_percent---|---slider_percent---|
|
751 |
+
# |--------------------width------------------|
|
752 |
+
|
753 |
+
# Create a frame to hold it all
|
754 |
+
self.frame_x = x
|
755 |
+
self.frame_y = y
|
756 |
+
self.frame_width = width
|
757 |
+
self.frame_height = height
|
758 |
+
|
759 |
+
self.frame = tk.Frame(self.parent, self.frame_style, width=self.frame_width, height=self.frame_height)
|
760 |
+
self.frame.place(x=self.frame_x, y=self.frame_y)
|
761 |
+
self.frame.bind("<Enter>", lambda event: self.on_enter())
|
762 |
+
|
763 |
+
|
764 |
+
# Add the slider Label text to the frame
|
765 |
+
self.txt_label_x = 0
|
766 |
+
self.txt_label_y = 0
|
767 |
+
self.txt_label_width = int(width*(1.0-slider_percent))
|
768 |
+
|
769 |
+
self.label = tk.Label(self.frame, self.text_style, image=self.blank, compound='c', text=self.display_text, anchor='e', width=self.txt_label_width, height=self.height)
|
770 |
+
self.label.place(x=self.txt_label_x, y=self.txt_label_y)
|
771 |
+
|
772 |
+
# Add the Slider Canvas to the frame
|
773 |
+
self.slider_canvas_x = self.txt_label_width
|
774 |
+
self.slider_canvas_y = 0
|
775 |
+
self.slider_canvas_width = width-self.txt_label_width
|
776 |
+
|
777 |
+
self.slider = tk.Canvas(self.frame, self.frame_style, width=self.slider_canvas_width, height=self.height)
|
778 |
+
self.slider.place(x=self.slider_canvas_x, y=self.slider_canvas_y)
|
779 |
+
self.slider.bind('<B1-Motion>', lambda e: self.update_handle(e, True))
|
780 |
+
self.slider.bind('<MouseWheel>', lambda e: self.update_handle(e, True))
|
781 |
+
|
782 |
+
# Add the Entry to the frame
|
783 |
+
self.entry_width = 60
|
784 |
+
self.entry_x = self.frame_width-self.entry_width
|
785 |
+
self.entry_y = 0
|
786 |
+
|
787 |
+
self.entry = tk.Entry(self.frame, self.entry_style, textvariable=self.entry_string)
|
788 |
+
self.entry.place(x=self.entry_x, y=self.entry_y)
|
789 |
+
self.entry.bind('<Return>', lambda event: self.entry_input(event))
|
790 |
+
|
791 |
+
# Draw the slider
|
792 |
+
self.slider_pad = 20
|
793 |
+
self.entry_pad = 20
|
794 |
+
self.slider_left = self.slider_pad
|
795 |
+
self.slider_right = self.slider_canvas_width-self.entry_pad-self.entry_width
|
796 |
+
self.slider_center = (self.height+1)/2
|
797 |
+
|
798 |
+
self.oval_loc = self.pos2coord(self.amount)
|
799 |
+
self.oval_radius = 5
|
800 |
+
self.oval_x1 = self.oval_loc-self.oval_radius
|
801 |
+
self.oval_y1 = self.slider_center-self.oval_radius
|
802 |
+
self.oval_x2 = self.oval_loc+self.oval_radius
|
803 |
+
self.oval_y2 = self.slider_center+self.oval_radius
|
804 |
+
|
805 |
+
self.trough_x1 = self.slider_left
|
806 |
+
self.trough_y1 = self.slider_center-2
|
807 |
+
self.trough_x2 = self.slider_right
|
808 |
+
self.trough_y2 = self.slider_center+2
|
809 |
+
|
810 |
+
self.slider.create_rectangle(self.trough_x1, self.trough_y1, self.trough_x2, self.trough_y2, fill='#1F1F1F', outline='')
|
811 |
+
self.handle = self.slider.create_oval(self.oval_x1, self.oval_y1, self.oval_x2, self.oval_y2, fill='#919191', outline='')
|
812 |
+
|
813 |
+
def coord2pos(self, coord):
|
814 |
+
return float((coord-self.slider_left)*(self.max_-self.min_)/(self.slider_right-self.slider_left) + self.min_)
|
815 |
+
|
816 |
+
def pos2coord(self, pos):
|
817 |
+
return float((float(pos)-self.min_)*(self.slider_right-self.slider_left)/(self.max_-self.min_) + self.slider_left)
|
818 |
+
|
819 |
+
def update_handle(self, event, also_update_entry=False, request_frame=True):
|
820 |
+
if isinstance(event, float):
|
821 |
+
position = event
|
822 |
+
|
823 |
+
elif event.type == '38':
|
824 |
+
position = self.amount+self.inc_*int(event.delta/120.0)
|
825 |
+
|
826 |
+
elif event.type == '6':
|
827 |
+
x_coord = float(event.x)
|
828 |
+
position = self.coord2pos(x_coord)
|
829 |
+
|
830 |
+
# constrain mousewheel movement
|
831 |
+
if position < self.min_: position = self.min_
|
832 |
+
elif position > self.max_: position = self.max_
|
833 |
+
|
834 |
+
# Find closest position increment
|
835 |
+
position_inc = round((position-self.min_) / self.inc_)
|
836 |
+
position = (position_inc * self.inc_)+self.min_
|
837 |
+
|
838 |
+
# moving sends many events, so only update when the next frame is reached
|
839 |
+
if position != self.amount:
|
840 |
+
# Move handle to coordinate based on position
|
841 |
+
self.slider.move(self.handle, self.pos2coord(position) - self.pos2coord(self.amount), 0)
|
842 |
+
|
843 |
+
# Save for next time
|
844 |
+
self.amount = position
|
845 |
+
|
846 |
+
if also_update_entry:
|
847 |
+
self.entry_string.set(str(position))
|
848 |
+
|
849 |
+
if request_frame:
|
850 |
+
self.function(self.data_type, self.name, use_markers=False)
|
851 |
+
|
852 |
+
# return True
|
853 |
+
# return False
|
854 |
+
|
855 |
+
def add_info_frame(self, info):
|
856 |
+
self.info = info
|
857 |
+
|
858 |
+
def on_enter(self):
|
859 |
+
if self.info:
|
860 |
+
self.info.configure(text=self.default_data[self.name+'InfoText'])
|
861 |
+
|
862 |
+
def entry_input(self, event):
|
863 |
+
# event.char
|
864 |
+
self.entry.update()
|
865 |
+
try:
|
866 |
+
input_num = float(self.entry_string.get())
|
867 |
+
self.update_handle(input_num, False)
|
868 |
+
except:
|
869 |
+
return
|
870 |
+
|
871 |
+
def set(self, value, request_frame=True):
|
872 |
+
self.update_handle(float(value), True)
|
873 |
+
|
874 |
+
def get(self):
|
875 |
+
return self.amount
|
876 |
+
|
877 |
+
def hide(self):
|
878 |
+
self.frame.place_forget()
|
879 |
+
self.label.place_forget()
|
880 |
+
self.slider.place_forget()
|
881 |
+
self.entry.place_forget()
|
882 |
+
|
883 |
+
def unhide(self):
|
884 |
+
self.frame.place(x=self.frame_x, y=self.frame_y)
|
885 |
+
self.label.place(x=self.txt_label_x, y=self.txt_label_y)
|
886 |
+
self.slider.place(x=self.slider_canvas_x, y=self.slider_canvas_y)
|
887 |
+
self.entry.place(x=self.entry_x, y=self.entry_y)
|
888 |
+
|
889 |
+
# def save_to_file(self, filename, data):
|
890 |
+
# with open(filename, 'w') as outfile:
|
891 |
+
# json.dump(data, outfile)
|
892 |
+
|
893 |
+
def get_data_type(self):
|
894 |
+
return self.data_type
|
895 |
+
|
896 |
+
def load_default(self):
|
897 |
+
self.set(self.default_data[self.name+'Amount'])
|
898 |
+
|
899 |
+
|
900 |
+
class Slider3():
|
901 |
+
def __init__(self, parent, name, display_text, style_level, function, argument, width, height, x, y, slider_percent):
|
902 |
+
|
903 |
+
# self.constants = CONSTANTS
|
904 |
+
# self.default_data = DEFAULT_DATA
|
905 |
+
self.blank = tk.PhotoImage()
|
906 |
+
|
907 |
+
# Capture inputs as instance variables
|
908 |
+
self.parent = parent
|
909 |
+
self.name = name
|
910 |
+
self.function = function
|
911 |
+
self.data_type = argument
|
912 |
+
self.x = x
|
913 |
+
self.y = y
|
914 |
+
self.slider_percent = slider_percent
|
915 |
+
self.width = width
|
916 |
+
self.height = height
|
917 |
+
self.info = []
|
918 |
+
|
919 |
+
# Initial Value
|
920 |
+
self.amount = 0
|
921 |
+
|
922 |
+
if style_level == 1:
|
923 |
+
self.frame_style = style.canvas_frame_label_1
|
924 |
+
self.text_style = style.text_1
|
925 |
+
self.entry_style = style.entry_3
|
926 |
+
|
927 |
+
elif style_level == 3:
|
928 |
+
self.frame_style = style.canvas_frame_label_3
|
929 |
+
self.text_style = style.text_3
|
930 |
+
self.entry_style = style.entry_3
|
931 |
+
|
932 |
+
# UI-controlled variables
|
933 |
+
self.entry_string = tk.StringVar()
|
934 |
+
self.entry_string.set(self.amount)
|
935 |
+
|
936 |
+
# Widget variables
|
937 |
+
self.min_ = -2
|
938 |
+
self.max_ = 2
|
939 |
+
self.inc_ = 0.001
|
940 |
+
self.display_text = display_text + ' '
|
941 |
+
|
942 |
+
# Set up spacing
|
943 |
+
# |----------------------|slider_pad|-slider-|entry_pad|-|
|
944 |
+
# |---1-slider_percent---|---slider_percent---|
|
945 |
+
# |--------------------width------------------|
|
946 |
+
|
947 |
+
# Create a frame to hold it all
|
948 |
+
self.frame_x = x
|
949 |
+
self.frame_y = y
|
950 |
+
self.frame_width = width
|
951 |
+
self.frame_height = height
|
952 |
+
|
953 |
+
self.frame = tk.Frame(self.parent, self.frame_style, width=self.frame_width, height=self.frame_height)
|
954 |
+
self.frame.place(x=self.frame_x, y=self.frame_y)
|
955 |
+
# self.frame.bind("<Enter>", lambda event: self.on_enter())
|
956 |
+
|
957 |
+
|
958 |
+
# Add the slider Label text to the frame
|
959 |
+
self.txt_label_x = 0
|
960 |
+
self.txt_label_y = 0
|
961 |
+
self.txt_label_width = int(width * (1.0 - slider_percent))
|
962 |
+
|
963 |
+
self.label = tk.Label(self.frame, self.text_style, image=self.blank, compound='c', text=self.display_text, anchor='e', width=self.txt_label_width, height=self.height)
|
964 |
+
self.label.place(x=self.txt_label_x, y=self.txt_label_y)
|
965 |
+
|
966 |
+
# Add the Slider Canvas to the frame
|
967 |
+
self.slider_canvas_x = self.txt_label_width
|
968 |
+
self.slider_canvas_y = 0
|
969 |
+
self.slider_canvas_width = width - self.txt_label_width
|
970 |
+
|
971 |
+
self.slider = tk.Canvas(self.frame, self.frame_style, width=self.slider_canvas_width, height=self.height)
|
972 |
+
self.slider.place(x=self.slider_canvas_x, y=self.slider_canvas_y)
|
973 |
+
self.slider.bind('<B1-Motion>', lambda e: self.update_handle(e, True))
|
974 |
+
self.slider.bind('<MouseWheel>', lambda e: self.update_handle(e, True))
|
975 |
+
|
976 |
+
# Add the Entry to the frame
|
977 |
+
self.entry_width = 60
|
978 |
+
self.entry_x = self.frame_width - self.entry_width
|
979 |
+
self.entry_y = 0
|
980 |
+
|
981 |
+
self.entry = tk.Entry(self.frame, self.entry_style, textvariable=self.entry_string)
|
982 |
+
self.entry.place(x=self.entry_x, y=self.entry_y)
|
983 |
+
self.entry.bind('<Return>', lambda event: self.entry_input(event))
|
984 |
+
|
985 |
+
# Draw the slider
|
986 |
+
self.slider_pad = 20
|
987 |
+
self.entry_pad = 20
|
988 |
+
self.slider_left = self.slider_pad
|
989 |
+
self.slider_right = self.slider_canvas_width - self.entry_pad - self.entry_width
|
990 |
+
self.slider_center = (self.height + 1) / 2
|
991 |
+
|
992 |
+
self.oval_loc = self.pos2coord(self.amount)
|
993 |
+
self.oval_radius = 5
|
994 |
+
self.oval_x1 = self.oval_loc - self.oval_radius
|
995 |
+
self.oval_y1 = self.slider_center - self.oval_radius
|
996 |
+
self.oval_x2 = self.oval_loc + self.oval_radius
|
997 |
+
self.oval_y2 = self.slider_center + self.oval_radius
|
998 |
+
|
999 |
+
self.trough_x1 = self.slider_left
|
1000 |
+
self.trough_y1 = self.slider_center - 2
|
1001 |
+
self.trough_x2 = self.slider_right
|
1002 |
+
self.trough_y2 = self.slider_center + 2
|
1003 |
+
|
1004 |
+
self.slider.create_rectangle(self.trough_x1, self.trough_y1, self.trough_x2, self.trough_y2, fill='#1F1F1F', outline='')
|
1005 |
+
self.handle = self.slider.create_oval(self.oval_x1, self.oval_y1, self.oval_x2, self.oval_y2, fill='#919191', outline='')
|
1006 |
+
|
1007 |
+
def coord2pos(self, coord):
|
1008 |
+
return float((coord - self.slider_left) * (self.max_ - self.min_) / (self.slider_right - self.slider_left) + self.min_)
|
1009 |
+
|
1010 |
+
def pos2coord(self, pos):
|
1011 |
+
return float((float(pos) - self.min_) * (self.slider_right - self.slider_left) / (self.max_ - self.min_) + self.slider_left)
|
1012 |
+
|
1013 |
+
def update_handle(self, event, also_update_entry=False, request_frame=True):
|
1014 |
+
if isinstance(event, float):
|
1015 |
+
position = event
|
1016 |
+
|
1017 |
+
elif event.type == '38':
|
1018 |
+
position = self.amount + self.inc_ * int(event.delta / 120.0)
|
1019 |
+
|
1020 |
+
elif event.type == '6':
|
1021 |
+
x_coord = float(event.x)
|
1022 |
+
position = self.coord2pos(x_coord)
|
1023 |
+
|
1024 |
+
# constrain mousewheel movement
|
1025 |
+
if position < self.min_:
|
1026 |
+
position = self.min_
|
1027 |
+
elif position > self.max_:
|
1028 |
+
position = self.max_
|
1029 |
+
|
1030 |
+
# Find closest position increment
|
1031 |
+
position_inc = round((position - self.min_) / self.inc_)
|
1032 |
+
position = (position_inc * self.inc_) + self.min_
|
1033 |
+
|
1034 |
+
# moving sends many events, so only update when the next frame is reached
|
1035 |
+
if position != self.amount:
|
1036 |
+
# Move handle to coordinate based on position
|
1037 |
+
self.slider.move(self.handle, self.pos2coord(position) - self.pos2coord(self.amount), 0)
|
1038 |
+
|
1039 |
+
# Save for next time
|
1040 |
+
self.amount = position
|
1041 |
+
|
1042 |
+
if also_update_entry:
|
1043 |
+
self.entry_string.set(str(position))
|
1044 |
+
|
1045 |
+
if request_frame:
|
1046 |
+
self.function(self.data_type)
|
1047 |
+
|
1048 |
+
# return True
|
1049 |
+
# return False
|
1050 |
+
|
1051 |
+
def add_info_frame(self, info):
|
1052 |
+
self.info = info
|
1053 |
+
|
1054 |
+
# def on_enter(self):
|
1055 |
+
# if self.info:
|
1056 |
+
# self.info.configure(text=self.default_data[self.name + 'InfoText'])
|
1057 |
+
|
1058 |
+
def entry_input(self, event):
|
1059 |
+
# event.char
|
1060 |
+
self.entry.update()
|
1061 |
+
try:
|
1062 |
+
input_num = float(self.entry_string.get())
|
1063 |
+
self.update_handle(input_num, False)
|
1064 |
+
except:
|
1065 |
+
return
|
1066 |
+
|
1067 |
+
def set(self, value, request_frame=True):
|
1068 |
+
self.update_handle(float(value), True, request_frame)
|
1069 |
+
|
1070 |
+
def get(self):
|
1071 |
+
return self.amount
|
1072 |
+
|
1073 |
+
def hide(self):
|
1074 |
+
self.frame.place_forget()
|
1075 |
+
self.label.place_forget()
|
1076 |
+
self.slider.place_forget()
|
1077 |
+
self.entry.place_forget()
|
1078 |
+
|
1079 |
+
def unhide(self):
|
1080 |
+
self.frame.place(x=self.frame_x, y=self.frame_y)
|
1081 |
+
self.label.place(x=self.txt_label_x, y=self.txt_label_y)
|
1082 |
+
self.slider.place(x=self.slider_canvas_x, y=self.slider_canvas_y)
|
1083 |
+
self.entry.place(x=self.entry_x, y=self.entry_y)
|
1084 |
+
|
1085 |
+
# def save_to_file(self, filename, data):
|
1086 |
+
# with open(filename, 'w') as outfile:
|
1087 |
+
# json.dump(data, outfile)
|
1088 |
+
|
1089 |
+
def get_data_type(self):
|
1090 |
+
return self.data_type
|
1091 |
+
|
1092 |
+
def load_default(self):
|
1093 |
+
self.set(0)
|
1094 |
+
|
1095 |
+
class Text_Entry():
|
1096 |
+
def __init__(self, parent, name, display_text, style_level, function, data_type, width, height, x, y, text_percent):
|
1097 |
+
self.blank = tk.PhotoImage()
|
1098 |
+
|
1099 |
+
self.default_data = DEFAULT_DATA
|
1100 |
+
# Capture inputs as instance variables
|
1101 |
+
self.parent = parent
|
1102 |
+
self.name = name
|
1103 |
+
self.function = function
|
1104 |
+
self.data_type = data_type
|
1105 |
+
self.width = width
|
1106 |
+
self.height = height
|
1107 |
+
self.style = []
|
1108 |
+
self.info = []
|
1109 |
+
|
1110 |
+
if style_level == 3:
|
1111 |
+
self.frame_style = style.canvas_frame_label_3
|
1112 |
+
self.text_style = style.text_3
|
1113 |
+
self.sel_off_style = style.text_selection_off_3
|
1114 |
+
self.sel_on_style = style.text_selection_on_3
|
1115 |
+
|
1116 |
+
if style_level == 2:
|
1117 |
+
self.frame_style = style.canvas_frame_label_2
|
1118 |
+
self.text_style = style.text_2
|
1119 |
+
self.sel_off_style = style.text_selection_off_2
|
1120 |
+
self.sel_on_style = style.text_selection_on_2
|
1121 |
+
|
1122 |
+
self.display_text = display_text+' '
|
1123 |
+
|
1124 |
+
|
1125 |
+
# Initial data
|
1126 |
+
self.entry_text = tk.StringVar()
|
1127 |
+
self.entry_text.set(self.default_data[self.name])
|
1128 |
+
|
1129 |
+
# Frame to hold everything
|
1130 |
+
self.ts_frame = tk.Frame(self.parent, self.frame_style, width=self.width, height=self.height)
|
1131 |
+
self.ts_frame.place(x=x, y=y)
|
1132 |
+
self.ts_frame.bind("<Enter>", lambda event: self.on_enter())
|
1133 |
+
|
1134 |
+
self.text_width = int(width*(1.0-text_percent))
|
1135 |
+
|
1136 |
+
# Create the text on the left
|
1137 |
+
self.text_label = tk.Label(self.ts_frame, self.text_style, image=self.blank, compound='c', text=self.display_text, anchor='e', width=self.text_width, height=height)
|
1138 |
+
self.text_label.place(x=0, y=0)
|
1139 |
+
|
1140 |
+
|
1141 |
+
|
1142 |
+
self.entry = tk.Entry(self.ts_frame, style.entry_2, textvariable=self.entry_text)
|
1143 |
+
self.entry.place(x=self.text_width+20, y=0, width = self.width-self.text_width-50, height=15)
|
1144 |
+
self.entry.bind("<Return>", lambda event: self.send_text(self.entry_text.get()))
|
1145 |
+
|
1146 |
+
def send_text(self, text):
|
1147 |
+
self.function(self.data_type, self.name, use_markers=False)
|
1148 |
+
|
1149 |
+
def add_info_frame(self, info):
|
1150 |
+
self.info = info
|
1151 |
+
|
1152 |
+
def on_enter(self):
|
1153 |
+
if self.info:
|
1154 |
+
self.info.configure(text=self.default_data[self.name+'InfoText'])
|
1155 |
+
|
1156 |
+
def get(self):
|
1157 |
+
return self.entry_text.get()
|
1158 |
+
|
1159 |
+
def set(self, value, request_frame=True):
|
1160 |
+
pass
|
1161 |
+
# self.select_ui_text_selection(value, request_frame)
|
1162 |
+
|
1163 |
+
def hide(self):
|
1164 |
+
pass
|
1165 |
+
|
1166 |
+
def unhide(self):
|
1167 |
+
pass
|
1168 |
+
|
1169 |
+
def get_data_type(self):
|
1170 |
+
return self.data_type
|
1171 |
+
|
1172 |
+
def load_default(self):
|
1173 |
+
pass
|
1174 |
+
# self.set(self.default_data[self.name+'Mode'])
|
1175 |
+
|
1176 |
+
class VRAM_Indicator():
|
1177 |
+
def __init__(self, parent, style_level, width, height, x, y):
|
1178 |
+
self.parent = parent
|
1179 |
+
self.width = width
|
1180 |
+
self.height = height
|
1181 |
+
self.x = x
|
1182 |
+
self.y = y
|
1183 |
+
self.blank = tk.PhotoImage()
|
1184 |
+
|
1185 |
+
self.used = 0
|
1186 |
+
self.total = 1
|
1187 |
+
|
1188 |
+
if style_level == 3:
|
1189 |
+
self.frame_style = style.canvas_frame_label_3
|
1190 |
+
self.text_style = style.text_3
|
1191 |
+
self.sel_off_style = style.text_selection_off_3
|
1192 |
+
self.sel_on_style = style.text_selection_on_3
|
1193 |
+
|
1194 |
+
if style_level == 2:
|
1195 |
+
self.frame_style = style.canvas_frame_label_2
|
1196 |
+
self.text_style = style.text_2
|
1197 |
+
self.sel_off_style = style.text_selection_off_2
|
1198 |
+
self.sel_on_style = style.text_selection_on_2
|
1199 |
+
|
1200 |
+
if style_level == 1:
|
1201 |
+
self.frame_style = style.canvas_frame_label_1
|
1202 |
+
|
1203 |
+
self.frame = tk.Frame(self.parent, self.frame_style, width=self.width, height=self.height)
|
1204 |
+
self.frame.place(x=self.x, y=self.y)
|
1205 |
+
|
1206 |
+
self.label_name = tk.Label(self.frame, self.frame_style, image=self.blank, compound='c', fg='#b1b1b2', font=("Segoe UI", 9), width=50, text='VRAM', height=self.height)
|
1207 |
+
self.label_name.place(x=0, y=0)
|
1208 |
+
|
1209 |
+
|
1210 |
+
# self.label_value = tk.Label(self.frame, self.frame_style, bg='yellow', image=self.blank, compound='c', fg='#D0D0D0', font=("Segoe UI", 9), justify='right', width=100, text='VRAM', height=self.height)
|
1211 |
+
# self.label_value.place(x=200, y=0)
|
1212 |
+
|
1213 |
+
|
1214 |
+
self.canvas = tk.Canvas(self.frame, self.frame_style, highlightthickness =2, highlightbackground='#b1b1b2', width=self.width-60, height=self.height-4)
|
1215 |
+
self.canvas.place(x=50, y=0)
|
1216 |
+
|
1217 |
+
def update_display(self):
|
1218 |
+
self.canvas.delete('all')
|
1219 |
+
width = self.canvas.winfo_width()
|
1220 |
+
|
1221 |
+
try:
|
1222 |
+
ratio = self.used/self.total
|
1223 |
+
except ZeroDivisionError:
|
1224 |
+
ratio = 1
|
1225 |
+
|
1226 |
+
if ratio>0.9:
|
1227 |
+
color = '#d10303'
|
1228 |
+
else:
|
1229 |
+
color = '#b1b1b2'
|
1230 |
+
width = ratio*width
|
1231 |
+
|
1232 |
+
self.canvas.create_rectangle(0, 0, width, self.height, fill=color)
|
1233 |
+
|
1234 |
+
# text = str(self.used)+' / '+str(self.total)+' MB'
|
1235 |
+
# self.label_value.configure(text=text)
|
1236 |
+
|
1237 |
+
def set(self, used, total):
|
1238 |
+
self.used = used
|
1239 |
+
self.total = total
|
1240 |
+
|
1241 |
+
self.update_display()
|
1242 |
+
|
1243 |
+
def hide(self):
|
1244 |
+
pass
|
1245 |
+
|
1246 |
+
def unhide(self):
|
1247 |
+
pass
|
1248 |
+
|
rope/Models.py
ADDED
@@ -0,0 +1,1961 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import numpy as np
|
3 |
+
from skimage import transform as trans
|
4 |
+
import torch
|
5 |
+
import torchvision
|
6 |
+
torchvision.disable_beta_transforms_warning()
|
7 |
+
from torchvision.transforms import v2
|
8 |
+
from numpy.linalg import norm as l2norm
|
9 |
+
import onnxruntime
|
10 |
+
import onnx
|
11 |
+
from itertools import product as product
|
12 |
+
import subprocess as sp
|
13 |
+
onnxruntime.set_default_logger_severity(4)
|
14 |
+
onnxruntime.log_verbosity_level = -1
|
15 |
+
import rope.FaceUtil as faceutil
|
16 |
+
import pickle
|
17 |
+
|
18 |
+
class Models():
|
19 |
+
def __init__(self):
|
20 |
+
self.arcface_dst = np.array( [[38.2946, 51.6963], [73.5318, 51.5014], [56.0252, 71.7366], [41.5493, 92.3655], [70.7299, 92.2041]], dtype=np.float32)
|
21 |
+
self.providers = ['CUDAExecutionProvider', 'CPUExecutionProvider']
|
22 |
+
|
23 |
+
self.retinaface_model = []
|
24 |
+
self.yoloface_model = []
|
25 |
+
self.scrdf_model = []
|
26 |
+
self.yunet_model = []
|
27 |
+
self.face_landmark_68_model = []
|
28 |
+
self.face_landmark_3d68_model = []
|
29 |
+
self.mean_lmk = []
|
30 |
+
self.face_landmark_98_model = []
|
31 |
+
self.face_landmark_106_model = []
|
32 |
+
self.face_landmark_478_model = []
|
33 |
+
self.face_blendshapes_model = []
|
34 |
+
self.resnet50_model, self.anchors = [], []
|
35 |
+
|
36 |
+
self.insight106_model = []
|
37 |
+
|
38 |
+
self.recognition_model = []
|
39 |
+
self.swapper_model = []
|
40 |
+
self.swapper_model_kps = []
|
41 |
+
self.swapper_model_swap = []
|
42 |
+
|
43 |
+
self.emap = []
|
44 |
+
self.GFPGAN_model = []
|
45 |
+
self.GPEN_256_model = []
|
46 |
+
self.GPEN_512_model = []
|
47 |
+
self.GPEN_1024_model = []
|
48 |
+
self.codeformer_model = []
|
49 |
+
|
50 |
+
self.occluder_model = []
|
51 |
+
self.faceparser_model = []
|
52 |
+
|
53 |
+
self.syncvec = torch.empty((1,1), dtype=torch.float32, device='cuda:0')
|
54 |
+
|
55 |
+
self.normalize = v2.Normalize(mean = [ 0., 0., 0. ],
|
56 |
+
std = [ 1/1.0, 1/1.0, 1/1.0 ])
|
57 |
+
|
58 |
+
self.LandmarksSubsetIdxs = [
|
59 |
+
0, 1, 4, 5, 6, 7, 8, 10, 13, 14, 17, 21, 33, 37, 39,
|
60 |
+
40, 46, 52, 53, 54, 55, 58, 61, 63, 65, 66, 67, 70, 78, 80,
|
61 |
+
81, 82, 84, 87, 88, 91, 93, 95, 103, 105, 107, 109, 127, 132, 133,
|
62 |
+
136, 144, 145, 146, 148, 149, 150, 152, 153, 154, 155, 157, 158, 159, 160,
|
63 |
+
161, 162, 163, 168, 172, 173, 176, 178, 181, 185, 191, 195, 197, 234, 246,
|
64 |
+
249, 251, 263, 267, 269, 270, 276, 282, 283, 284, 285, 288, 291, 293, 295,
|
65 |
+
296, 297, 300, 308, 310, 311, 312, 314, 317, 318, 321, 323, 324, 332, 334,
|
66 |
+
336, 338, 356, 361, 362, 365, 373, 374, 375, 377, 378, 379, 380, 381, 382,
|
67 |
+
384, 385, 386, 387, 388, 389, 390, 397, 398, 400, 402, 405, 409, 415, 454,
|
68 |
+
466, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477
|
69 |
+
]
|
70 |
+
|
71 |
+
def get_gpu_memory(self):
|
72 |
+
command = "nvidia-smi --query-gpu=memory.total --format=csv"
|
73 |
+
memory_total_info = sp.check_output(command.split()).decode('ascii').split('\n')[:-1][1:]
|
74 |
+
memory_total = [int(x.split()[0]) for i, x in enumerate(memory_total_info)]
|
75 |
+
|
76 |
+
command = "nvidia-smi --query-gpu=memory.free --format=csv"
|
77 |
+
memory_free_info = sp.check_output(command.split()).decode('ascii').split('\n')[:-1][1:]
|
78 |
+
memory_free = [int(x.split()[0]) for i, x in enumerate(memory_free_info)]
|
79 |
+
|
80 |
+
memory_used = memory_total[0] - memory_free[0]
|
81 |
+
|
82 |
+
return memory_used, memory_total[0]
|
83 |
+
|
84 |
+
def run_detect(self, img, detect_mode='Retinaface', max_num=1, score=0.5, use_landmark_detection=False, landmark_detect_mode='98', landmark_score=0.5, from_points=False):
|
85 |
+
bboxes = []
|
86 |
+
kpss = []
|
87 |
+
|
88 |
+
if detect_mode=='Retinaface':
|
89 |
+
if not self.retinaface_model:
|
90 |
+
self.retinaface_model = onnxruntime.InferenceSession('./models/det_10g.onnx', providers=self.providers)
|
91 |
+
|
92 |
+
bboxes, kpss = self.detect_retinaface(img, max_num=max_num, score=score, use_landmark_detection=use_landmark_detection, landmark_detect_mode=landmark_detect_mode, landmark_score=landmark_score, from_points=from_points)
|
93 |
+
|
94 |
+
elif detect_mode=='SCRDF':
|
95 |
+
if not self.scrdf_model:
|
96 |
+
self.scrdf_model = onnxruntime.InferenceSession('./models/scrfd_2.5g_bnkps.onnx', providers=self.providers)
|
97 |
+
|
98 |
+
bboxes, kpss = self.detect_scrdf(img, max_num=max_num, score=score, use_landmark_detection=use_landmark_detection, landmark_detect_mode=landmark_detect_mode, landmark_score=landmark_score, from_points=from_points)
|
99 |
+
|
100 |
+
elif detect_mode=='Yolov8':
|
101 |
+
if not self.yoloface_model:
|
102 |
+
self.yoloface_model = onnxruntime.InferenceSession('./models/yoloface_8n.onnx', providers=self.providers)
|
103 |
+
#self.insight106_model = onnxruntime.InferenceSession('./models/2d106det.onnx', providers=self.providers)
|
104 |
+
|
105 |
+
bboxes, kpss = self.detect_yoloface(img, max_num=max_num, score=score, use_landmark_detection=use_landmark_detection, landmark_detect_mode=landmark_detect_mode, landmark_score=landmark_score, from_points=from_points)
|
106 |
+
|
107 |
+
elif detect_mode=='Yunet':
|
108 |
+
if not self.yunet_model:
|
109 |
+
self.yunet_model = onnxruntime.InferenceSession('./models/yunet_n_640_640.onnx', providers=self.providers)
|
110 |
+
|
111 |
+
bboxes, kpss = self.detect_yunet(img, max_num=max_num, score=score, use_landmark_detection=use_landmark_detection, landmark_detect_mode=landmark_detect_mode, landmark_score=landmark_score, from_points=from_points)
|
112 |
+
|
113 |
+
return bboxes, kpss
|
114 |
+
|
115 |
+
def run_detect_landmark(self, img, bbox, det_kpss, detect_mode='98', score=0.5, from_points=False):
|
116 |
+
kpss = []
|
117 |
+
scores = []
|
118 |
+
|
119 |
+
if detect_mode=='5':
|
120 |
+
if not self.resnet50_model:
|
121 |
+
self.resnet50_model = onnxruntime.InferenceSession("./models/res50.onnx", providers=self.providers)
|
122 |
+
|
123 |
+
feature_maps = [[64, 64], [32, 32], [16, 16]]
|
124 |
+
min_sizes = [[16, 32], [64, 128], [256, 512]]
|
125 |
+
steps = [8, 16, 32]
|
126 |
+
image_size = 512
|
127 |
+
|
128 |
+
for k, f in enumerate(feature_maps):
|
129 |
+
min_size_array = min_sizes[k]
|
130 |
+
for i, j in product(range(f[0]), range(f[1])):
|
131 |
+
for min_size in min_size_array:
|
132 |
+
s_kx = min_size / image_size
|
133 |
+
s_ky = min_size / image_size
|
134 |
+
dense_cx = [x * steps[k] / image_size for x in [j + 0.5]]
|
135 |
+
dense_cy = [y * steps[k] / image_size for y in [i + 0.5]]
|
136 |
+
for cy, cx in product(dense_cy, dense_cx):
|
137 |
+
self.anchors += [cx, cy, s_kx, s_ky]
|
138 |
+
|
139 |
+
kpss, scores = self.detect_face_landmark_5(img, bbox=bbox, det_kpss=det_kpss, from_points=from_points)
|
140 |
+
|
141 |
+
elif detect_mode=='68':
|
142 |
+
if not self.face_landmark_68_model:
|
143 |
+
self.face_landmark_68_model = onnxruntime.InferenceSession('./models/2dfan4.onnx', providers=self.providers)
|
144 |
+
|
145 |
+
kpss, scores = self.detect_face_landmark_68(img, bbox=bbox, det_kpss=det_kpss, convert68_5=True, from_points=from_points)
|
146 |
+
|
147 |
+
elif detect_mode=='3d68':
|
148 |
+
if not self.face_landmark_3d68_model:
|
149 |
+
self.face_landmark_3d68_model = onnxruntime.InferenceSession('./models/1k3d68.onnx', providers=self.providers)
|
150 |
+
with open('./models/meanshape_68.pkl', 'rb') as f:
|
151 |
+
self.mean_lmk = pickle.load(f)
|
152 |
+
|
153 |
+
kpss, scores = self.detect_face_landmark_3d68(img, bbox=bbox, det_kpss=det_kpss, convert68_5=True, from_points=from_points)
|
154 |
+
|
155 |
+
return kpss, scores
|
156 |
+
|
157 |
+
elif detect_mode=='98':
|
158 |
+
if not self.face_landmark_98_model:
|
159 |
+
self.face_landmark_98_model = onnxruntime.InferenceSession('./models/peppapig_teacher_Nx3x256x256.onnx', providers=self.providers)
|
160 |
+
|
161 |
+
kpss, scores = self.detect_face_landmark_98(img, bbox=bbox, det_kpss=det_kpss, convert98_5=True, from_points=from_points)
|
162 |
+
|
163 |
+
elif detect_mode=='106':
|
164 |
+
if not self.face_landmark_106_model:
|
165 |
+
self.face_landmark_106_model = onnxruntime.InferenceSession('./models/2d106det.onnx', providers=self.providers)
|
166 |
+
|
167 |
+
kpss, scores = self.detect_face_landmark_106(img, bbox=bbox, det_kpss=det_kpss, convert106_5=True, from_points=from_points)
|
168 |
+
|
169 |
+
return kpss, scores
|
170 |
+
|
171 |
+
elif detect_mode=='478':
|
172 |
+
if not self.face_landmark_478_model:
|
173 |
+
self.face_landmark_478_model = onnxruntime.InferenceSession('./models/face_landmarks_detector_Nx3x256x256.onnx', providers=self.providers)
|
174 |
+
|
175 |
+
if not self.face_blendshapes_model:
|
176 |
+
self.face_blendshapes_model = onnxruntime.InferenceSession('./models/face_blendshapes_Nx146x2.onnx', providers=self.providers)
|
177 |
+
|
178 |
+
kpss, scores = self.detect_face_landmark_478(img, bbox=bbox, det_kpss=det_kpss, convert478_5=True, from_points=from_points)
|
179 |
+
|
180 |
+
return kpss, scores
|
181 |
+
|
182 |
+
if len(kpss) > 0:
|
183 |
+
if len(scores) > 0:
|
184 |
+
if np.mean(scores) >= score:
|
185 |
+
return kpss, scores
|
186 |
+
else:
|
187 |
+
return kpss, scores
|
188 |
+
|
189 |
+
return [], []
|
190 |
+
|
191 |
+
def delete_models(self):
|
192 |
+
self.retinaface_model = []
|
193 |
+
self.yoloface_model = []
|
194 |
+
self.scrdf_model = []
|
195 |
+
self.yunet_model = []
|
196 |
+
self.face_landmark_68_model = []
|
197 |
+
self.face_landmark_3d68_model = []
|
198 |
+
self.mean_lmk = []
|
199 |
+
self.face_landmark_98_model = []
|
200 |
+
self.face_landmark_106_model = []
|
201 |
+
self.face_landmark_478_model = []
|
202 |
+
self.face_blendshapes_model = []
|
203 |
+
self.resnet50_model = []
|
204 |
+
self.insight106_model = []
|
205 |
+
self.recognition_model = []
|
206 |
+
self.swapper_model = []
|
207 |
+
self.GFPGAN_model = []
|
208 |
+
self.GPEN_256_model = []
|
209 |
+
self.GPEN_512_model = []
|
210 |
+
self.GPEN_1024_model = []
|
211 |
+
self.codeformer_model = []
|
212 |
+
self.occluder_model = []
|
213 |
+
self.faceparser_model = []
|
214 |
+
|
215 |
+
def run_recognize(self, img, kps):
|
216 |
+
if not self.recognition_model:
|
217 |
+
self.recognition_model = onnxruntime.InferenceSession('./models/w600k_r50.onnx', providers=self.providers)
|
218 |
+
|
219 |
+
embedding, cropped_image = self.recognize(img, kps)
|
220 |
+
return embedding, cropped_image
|
221 |
+
|
222 |
+
def calc_swapper_latent(self, source_embedding):
|
223 |
+
if not self.swapper_model:
|
224 |
+
graph = onnx.load("./models/inswapper_128.fp16.onnx").graph
|
225 |
+
self.emap = onnx.numpy_helper.to_array(graph.initializer[-1])
|
226 |
+
|
227 |
+
n_e = source_embedding / l2norm(source_embedding)
|
228 |
+
latent = n_e.reshape((1,-1))
|
229 |
+
latent = np.dot(latent, self.emap)
|
230 |
+
latent /= np.linalg.norm(latent)
|
231 |
+
return latent
|
232 |
+
|
233 |
+
def run_swapper(self, image, embedding, output):
|
234 |
+
if not self.swapper_model:
|
235 |
+
cuda_options = {"arena_extend_strategy": "kSameAsRequested", 'cudnn_conv_algo_search': 'DEFAULT'}
|
236 |
+
sess_options = onnxruntime.SessionOptions()
|
237 |
+
sess_options.enable_cpu_mem_arena = False
|
238 |
+
|
239 |
+
# self.swapper_model = onnxruntime.InferenceSession( "./models/inswapper_128_last_cubic.onnx", sess_options, providers=[('CUDAExecutionProvider', cuda_options), 'CPUExecutionProvider'])
|
240 |
+
|
241 |
+
self.swapper_model = onnxruntime.InferenceSession( "./models/inswapper_128.fp16.onnx", providers=self.providers)
|
242 |
+
|
243 |
+
io_binding = self.swapper_model.io_binding()
|
244 |
+
io_binding.bind_input(name='target', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,3,128,128), buffer_ptr=image.data_ptr())
|
245 |
+
io_binding.bind_input(name='source', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,512), buffer_ptr=embedding.data_ptr())
|
246 |
+
io_binding.bind_output(name='output', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,3,128,128), buffer_ptr=output.data_ptr())
|
247 |
+
|
248 |
+
self.syncvec.cpu()
|
249 |
+
self.swapper_model.run_with_iobinding(io_binding)
|
250 |
+
|
251 |
+
def run_swap_stg1(self, embedding):
|
252 |
+
|
253 |
+
# Load model
|
254 |
+
if not self.swapper_model_kps:
|
255 |
+
self.swapper_model_kps = onnxruntime.InferenceSession( "./models/inswapper_kps.onnx", providers=self.providers)
|
256 |
+
|
257 |
+
# Wacky data structure
|
258 |
+
io_binding = self.swapper_model_kps.io_binding()
|
259 |
+
kps_1 = torch.ones((1, 2048), dtype=torch.float16, device='cuda').contiguous()
|
260 |
+
kps_2 = torch.ones((1, 2048), dtype=torch.float16, device='cuda').contiguous()
|
261 |
+
kps_3 = torch.ones((1, 2048), dtype=torch.float16, device='cuda').contiguous()
|
262 |
+
kps_4 = torch.ones((1, 2048), dtype=torch.float16, device='cuda').contiguous()
|
263 |
+
kps_5 = torch.ones((1, 2048), dtype=torch.float16, device='cuda').contiguous()
|
264 |
+
kps_6 = torch.ones((1, 2048), dtype=torch.float16, device='cuda').contiguous()
|
265 |
+
kps_7 = torch.ones((1, 2048), dtype=torch.float16, device='cuda').contiguous()
|
266 |
+
kps_8 = torch.ones((1, 2048), dtype=torch.float16, device='cuda').contiguous()
|
267 |
+
kps_9 = torch.ones((1, 2048), dtype=torch.float16, device='cuda').contiguous()
|
268 |
+
kps_10 = torch.ones((1, 2048), dtype=torch.float16, device='cuda').contiguous()
|
269 |
+
kps_11 = torch.ones((1, 2048), dtype=torch.float16, device='cuda').contiguous()
|
270 |
+
kps_12 = torch.ones((1, 2048), dtype=torch.float16, device='cuda').contiguous()
|
271 |
+
|
272 |
+
# Bind the data structures
|
273 |
+
io_binding.bind_input(name='source', device_type='cuda', device_id=0, element_type=np.float32, shape=(1, 512), buffer_ptr=embedding.data_ptr())
|
274 |
+
io_binding.bind_output(name='1', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=kps_1.data_ptr())
|
275 |
+
io_binding.bind_output(name='2', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=kps_2.data_ptr())
|
276 |
+
io_binding.bind_output(name='3', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=kps_3.data_ptr())
|
277 |
+
io_binding.bind_output(name='4', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=kps_4.data_ptr())
|
278 |
+
io_binding.bind_output(name='5', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=kps_5.data_ptr())
|
279 |
+
io_binding.bind_output(name='6', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=kps_6.data_ptr())
|
280 |
+
io_binding.bind_output(name='7', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=kps_7.data_ptr())
|
281 |
+
io_binding.bind_output(name='8', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=kps_8.data_ptr())
|
282 |
+
io_binding.bind_output(name='9', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=kps_9.data_ptr())
|
283 |
+
io_binding.bind_output(name='10', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=kps_10.data_ptr())
|
284 |
+
io_binding.bind_output(name='11', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=kps_11.data_ptr())
|
285 |
+
io_binding.bind_output(name='12', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=kps_12.data_ptr())
|
286 |
+
|
287 |
+
self.syncvec.cpu()
|
288 |
+
self.swapper_model_kps.run_with_iobinding(io_binding)
|
289 |
+
|
290 |
+
# List of pointers
|
291 |
+
holder = []
|
292 |
+
holder.append(kps_1)
|
293 |
+
holder.append(kps_2)
|
294 |
+
holder.append(kps_3)
|
295 |
+
holder.append(kps_4)
|
296 |
+
holder.append(kps_5)
|
297 |
+
holder.append(kps_6)
|
298 |
+
holder.append(kps_7)
|
299 |
+
holder.append(kps_8)
|
300 |
+
holder.append(kps_9)
|
301 |
+
holder.append(kps_10)
|
302 |
+
holder.append(kps_11)
|
303 |
+
holder.append(kps_12)
|
304 |
+
|
305 |
+
return holder
|
306 |
+
|
307 |
+
|
308 |
+
def run_swap_stg2(self, image, holder, output):
|
309 |
+
if not self.swapper_model_swap:
|
310 |
+
self.swapper_model_swap = onnxruntime.InferenceSession( "./models/inswapper_swap.onnx", providers=self.providers)
|
311 |
+
|
312 |
+
io_binding = self.swapper_model_swap.io_binding()
|
313 |
+
io_binding.bind_input(name='target', device_type='cuda', device_id=0, element_type=np.float32, shape=(1, 3, 128, 128), buffer_ptr=image.data_ptr())
|
314 |
+
io_binding.bind_input(name='onnx::Unsqueeze_170', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=holder[0].data_ptr())
|
315 |
+
io_binding.bind_input(name='onnx::Unsqueeze_224', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=holder[1].data_ptr())
|
316 |
+
io_binding.bind_input(name='onnx::Unsqueeze_278', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=holder[2].data_ptr())
|
317 |
+
io_binding.bind_input(name='onnx::Unsqueeze_332', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=holder[3].data_ptr())
|
318 |
+
io_binding.bind_input(name='onnx::Unsqueeze_386', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=holder[4].data_ptr())
|
319 |
+
io_binding.bind_input(name='onnx::Unsqueeze_440', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=holder[5].data_ptr())
|
320 |
+
io_binding.bind_input(name='onnx::Unsqueeze_494', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=holder[6].data_ptr())
|
321 |
+
io_binding.bind_input(name='onnx::Unsqueeze_548', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=holder[7].data_ptr())
|
322 |
+
io_binding.bind_input(name='onnx::Unsqueeze_602', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=holder[8].data_ptr())
|
323 |
+
io_binding.bind_input(name='onnx::Unsqueeze_656', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=holder[9].data_ptr())
|
324 |
+
io_binding.bind_input(name='onnx::Unsqueeze_710', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=holder[10].data_ptr())
|
325 |
+
io_binding.bind_input(name='onnx::Unsqueeze_764', device_type='cuda', device_id=0, element_type=np.float16, shape=(1, 2048), buffer_ptr=holder[11].data_ptr())
|
326 |
+
io_binding.bind_output(name='output', device_type='cuda', device_id=0, element_type=np.float32, shape=(1, 3, 128, 128), buffer_ptr=output.data_ptr())
|
327 |
+
|
328 |
+
self.syncvec.cpu()
|
329 |
+
self.swapper_model_swap.run_with_iobinding(io_binding)
|
330 |
+
def run_GFPGAN(self, image, output):
|
331 |
+
if not self.GFPGAN_model:
|
332 |
+
# cuda_options = {"arena_extend_strategy": "kSameAsRequested", 'cudnn_conv_algo_search': 'DEFAULT'}
|
333 |
+
# sess_options = onnxruntime.SessionOptions()
|
334 |
+
# sess_options.enable_cpu_mem_arena = False
|
335 |
+
|
336 |
+
# self.GFPGAN_model = onnxruntime.InferenceSession( "./models/GFPGANv1.4.onnx", sess_options, providers=[("CUDAExecutionProvider", cuda_options), 'CPUExecutionProvider'])
|
337 |
+
|
338 |
+
self.GFPGAN_model = onnxruntime.InferenceSession( "./models/GFPGANv1.4.onnx", providers=self.providers)
|
339 |
+
|
340 |
+
io_binding = self.GFPGAN_model.io_binding()
|
341 |
+
io_binding.bind_input(name='input', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,3,512,512), buffer_ptr=image.data_ptr())
|
342 |
+
io_binding.bind_output(name='output', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,3,512,512), buffer_ptr=output.data_ptr())
|
343 |
+
|
344 |
+
self.syncvec.cpu()
|
345 |
+
self.GFPGAN_model.run_with_iobinding(io_binding)
|
346 |
+
|
347 |
+
def run_GPEN_1024(self, image, output):
|
348 |
+
if not self.GPEN_1024_model:
|
349 |
+
self.GPEN_1024_model = onnxruntime.InferenceSession( "./models/GPEN-BFR-1024.onnx", providers=self.providers)
|
350 |
+
|
351 |
+
io_binding = self.GPEN_1024_model.io_binding()
|
352 |
+
io_binding.bind_input(name='input', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,3,1024,1024), buffer_ptr=image.data_ptr())
|
353 |
+
io_binding.bind_output(name='output', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,3,1024,1024), buffer_ptr=output.data_ptr())
|
354 |
+
|
355 |
+
self.syncvec.cpu()
|
356 |
+
self.GPEN_1024_model.run_with_iobinding(io_binding)
|
357 |
+
|
358 |
+
def run_GPEN_512(self, image, output):
|
359 |
+
if not self.GPEN_512_model:
|
360 |
+
self.GPEN_512_model = onnxruntime.InferenceSession( "./models/GPEN-BFR-512.onnx", providers=self.providers)
|
361 |
+
|
362 |
+
io_binding = self.GPEN_512_model.io_binding()
|
363 |
+
io_binding.bind_input(name='input', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,3,512,512), buffer_ptr=image.data_ptr())
|
364 |
+
io_binding.bind_output(name='output', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,3,512,512), buffer_ptr=output.data_ptr())
|
365 |
+
|
366 |
+
self.syncvec.cpu()
|
367 |
+
self.GPEN_512_model.run_with_iobinding(io_binding)
|
368 |
+
|
369 |
+
def run_GPEN_256(self, image, output):
|
370 |
+
if not self.GPEN_256_model:
|
371 |
+
self.GPEN_256_model = onnxruntime.InferenceSession( "./models/GPEN-BFR-256.onnx", providers=self.providers)
|
372 |
+
|
373 |
+
io_binding = self.GPEN_256_model.io_binding()
|
374 |
+
io_binding.bind_input(name='input', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,3,256,256), buffer_ptr=image.data_ptr())
|
375 |
+
io_binding.bind_output(name='output', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,3,256,256), buffer_ptr=output.data_ptr())
|
376 |
+
|
377 |
+
self.syncvec.cpu()
|
378 |
+
self.GPEN_256_model.run_with_iobinding(io_binding)
|
379 |
+
|
380 |
+
def run_codeformer(self, image, output):
|
381 |
+
if not self.codeformer_model:
|
382 |
+
self.codeformer_model = onnxruntime.InferenceSession( "./models/codeformer_fp16.onnx", providers=self.providers)
|
383 |
+
|
384 |
+
io_binding = self.codeformer_model.io_binding()
|
385 |
+
io_binding.bind_input(name='x', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,3,512,512), buffer_ptr=image.data_ptr())
|
386 |
+
w = np.array([0.9], dtype=np.double)
|
387 |
+
io_binding.bind_cpu_input('w', w)
|
388 |
+
io_binding.bind_output(name='y', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,3,512,512), buffer_ptr=output.data_ptr())
|
389 |
+
|
390 |
+
self.syncvec.cpu()
|
391 |
+
self.codeformer_model.run_with_iobinding(io_binding)
|
392 |
+
|
393 |
+
def run_occluder(self, image, output):
|
394 |
+
if not self.occluder_model:
|
395 |
+
self.occluder_model = onnxruntime.InferenceSession("./models/occluder.onnx", providers=self.providers)
|
396 |
+
|
397 |
+
io_binding = self.occluder_model.io_binding()
|
398 |
+
io_binding.bind_input(name='img', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,3,256,256), buffer_ptr=image.data_ptr())
|
399 |
+
io_binding.bind_output(name='output', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,1,256,256), buffer_ptr=output.data_ptr())
|
400 |
+
|
401 |
+
# torch.cuda.synchronize('cuda')
|
402 |
+
self.syncvec.cpu()
|
403 |
+
self.occluder_model.run_with_iobinding(io_binding)
|
404 |
+
|
405 |
+
def run_faceparser(self, image, output):
|
406 |
+
if not self.faceparser_model:
|
407 |
+
self.faceparser_model = onnxruntime.InferenceSession("./models/faceparser_fp16.onnx", providers=self.providers)
|
408 |
+
|
409 |
+
io_binding = self.faceparser_model.io_binding()
|
410 |
+
io_binding.bind_input(name='input', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,3,512,512), buffer_ptr=image.data_ptr())
|
411 |
+
io_binding.bind_output(name='out', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,19,512,512), buffer_ptr=output.data_ptr())
|
412 |
+
|
413 |
+
# torch.cuda.synchronize('cuda')
|
414 |
+
self.syncvec.cpu()
|
415 |
+
self.faceparser_model.run_with_iobinding(io_binding)
|
416 |
+
|
417 |
+
def detect_retinaface(self, img, max_num, score, use_landmark_detection, landmark_detect_mode, landmark_score, from_points):
|
418 |
+
if use_landmark_detection:
|
419 |
+
img_landmark = img.clone()
|
420 |
+
|
421 |
+
# Resize image to fit within the input_size
|
422 |
+
input_size = (640, 640)
|
423 |
+
im_ratio = torch.div(img.size()[1], img.size()[2])
|
424 |
+
|
425 |
+
# model_ratio = float(input_size[1]) / input_size[0]
|
426 |
+
model_ratio = 1.0
|
427 |
+
if im_ratio>model_ratio:
|
428 |
+
new_height = input_size[1]
|
429 |
+
new_width = int(new_height / im_ratio)
|
430 |
+
else:
|
431 |
+
new_width = input_size[0]
|
432 |
+
new_height = int(new_width * im_ratio)
|
433 |
+
det_scale = torch.div(new_height, img.size()[1])
|
434 |
+
|
435 |
+
resize = v2.Resize((new_height, new_width), antialias=True)
|
436 |
+
img = resize(img)
|
437 |
+
img = img.permute(1,2,0)
|
438 |
+
|
439 |
+
det_img = torch.zeros((input_size[1], input_size[0], 3), dtype=torch.float32, device='cuda:0')
|
440 |
+
det_img[:new_height,:new_width, :] = img
|
441 |
+
|
442 |
+
# Switch to BGR and normalize
|
443 |
+
det_img = det_img[:, :, [2,1,0]]
|
444 |
+
det_img = torch.sub(det_img, 127.5)
|
445 |
+
det_img = torch.div(det_img, 128.0)
|
446 |
+
det_img = det_img.permute(2, 0, 1) #3,128,128
|
447 |
+
|
448 |
+
# Prepare data and find model parameters
|
449 |
+
det_img = torch.unsqueeze(det_img, 0).contiguous()
|
450 |
+
|
451 |
+
io_binding = self.retinaface_model.io_binding()
|
452 |
+
io_binding.bind_input(name='input.1', device_type='cuda', device_id=0, element_type=np.float32, shape=det_img.size(), buffer_ptr=det_img.data_ptr())
|
453 |
+
|
454 |
+
io_binding.bind_output('448', 'cuda')
|
455 |
+
io_binding.bind_output('471', 'cuda')
|
456 |
+
io_binding.bind_output('494', 'cuda')
|
457 |
+
io_binding.bind_output('451', 'cuda')
|
458 |
+
io_binding.bind_output('474', 'cuda')
|
459 |
+
io_binding.bind_output('497', 'cuda')
|
460 |
+
io_binding.bind_output('454', 'cuda')
|
461 |
+
io_binding.bind_output('477', 'cuda')
|
462 |
+
io_binding.bind_output('500', 'cuda')
|
463 |
+
|
464 |
+
# Sync and run model
|
465 |
+
self.syncvec.cpu()
|
466 |
+
self.retinaface_model.run_with_iobinding(io_binding)
|
467 |
+
|
468 |
+
net_outs = io_binding.copy_outputs_to_cpu()
|
469 |
+
|
470 |
+
input_height = det_img.shape[2]
|
471 |
+
input_width = det_img.shape[3]
|
472 |
+
|
473 |
+
fmc = 3
|
474 |
+
center_cache = {}
|
475 |
+
scores_list = []
|
476 |
+
bboxes_list = []
|
477 |
+
kpss_list = []
|
478 |
+
for idx, stride in enumerate([8, 16, 32]):
|
479 |
+
scores = net_outs[idx]
|
480 |
+
bbox_preds = net_outs[idx+fmc]
|
481 |
+
bbox_preds = bbox_preds * stride
|
482 |
+
|
483 |
+
kps_preds = net_outs[idx+fmc*2] * stride
|
484 |
+
height = input_height // stride
|
485 |
+
width = input_width // stride
|
486 |
+
K = height * width
|
487 |
+
key = (height, width, stride)
|
488 |
+
if key in center_cache:
|
489 |
+
anchor_centers = center_cache[key]
|
490 |
+
else:
|
491 |
+
anchor_centers = np.stack(np.mgrid[:height, :width][::-1], axis=-1).astype(np.float32)
|
492 |
+
anchor_centers = (anchor_centers * stride).reshape( (-1, 2) )
|
493 |
+
anchor_centers = np.stack([anchor_centers]*2, axis=1).reshape( (-1,2) )
|
494 |
+
if len(center_cache)<100:
|
495 |
+
center_cache[key] = anchor_centers
|
496 |
+
|
497 |
+
pos_inds = np.where(scores>=score)[0]
|
498 |
+
|
499 |
+
x1 = anchor_centers[:, 0] - bbox_preds[:, 0]
|
500 |
+
y1 = anchor_centers[:, 1] - bbox_preds[:, 1]
|
501 |
+
x2 = anchor_centers[:, 0] + bbox_preds[:, 2]
|
502 |
+
y2 = anchor_centers[:, 1] + bbox_preds[:, 3]
|
503 |
+
|
504 |
+
bboxes = np.stack([x1, y1, x2, y2], axis=-1)
|
505 |
+
|
506 |
+
pos_scores = scores[pos_inds]
|
507 |
+
pos_bboxes = bboxes[pos_inds]
|
508 |
+
scores_list.append(pos_scores)
|
509 |
+
bboxes_list.append(pos_bboxes)
|
510 |
+
|
511 |
+
preds = []
|
512 |
+
for i in range(0, kps_preds.shape[1], 2):
|
513 |
+
px = anchor_centers[:, i%2] + kps_preds[:, i]
|
514 |
+
py = anchor_centers[:, i%2+1] + kps_preds[:, i+1]
|
515 |
+
|
516 |
+
preds.append(px)
|
517 |
+
preds.append(py)
|
518 |
+
kpss = np.stack(preds, axis=-1)
|
519 |
+
#kpss = kps_preds
|
520 |
+
kpss = kpss.reshape( (kpss.shape[0], -1, 2) )
|
521 |
+
pos_kpss = kpss[pos_inds]
|
522 |
+
kpss_list.append(pos_kpss)
|
523 |
+
|
524 |
+
scores = np.vstack(scores_list)
|
525 |
+
scores_ravel = scores.ravel()
|
526 |
+
order = scores_ravel.argsort()[::-1]
|
527 |
+
|
528 |
+
det_scale = det_scale.numpy()###
|
529 |
+
|
530 |
+
bboxes = np.vstack(bboxes_list) / det_scale
|
531 |
+
|
532 |
+
kpss = np.vstack(kpss_list) / det_scale
|
533 |
+
pre_det = np.hstack((bboxes, scores)).astype(np.float32, copy=False)
|
534 |
+
pre_det = pre_det[order, :]
|
535 |
+
|
536 |
+
dets = pre_det
|
537 |
+
thresh = 0.4
|
538 |
+
x1 = dets[:, 0]
|
539 |
+
y1 = dets[:, 1]
|
540 |
+
x2 = dets[:, 2]
|
541 |
+
y2 = dets[:, 3]
|
542 |
+
scoresb = dets[:, 4]
|
543 |
+
|
544 |
+
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
|
545 |
+
orderb = scoresb.argsort()[::-1]
|
546 |
+
|
547 |
+
keep = []
|
548 |
+
while orderb.size > 0:
|
549 |
+
i = orderb[0]
|
550 |
+
keep.append(i)
|
551 |
+
xx1 = np.maximum(x1[i], x1[orderb[1:]])
|
552 |
+
yy1 = np.maximum(y1[i], y1[orderb[1:]])
|
553 |
+
xx2 = np.minimum(x2[i], x2[orderb[1:]])
|
554 |
+
yy2 = np.minimum(y2[i], y2[orderb[1:]])
|
555 |
+
|
556 |
+
w = np.maximum(0.0, xx2 - xx1 + 1)
|
557 |
+
h = np.maximum(0.0, yy2 - yy1 + 1)
|
558 |
+
|
559 |
+
inter = w * h
|
560 |
+
ovr = inter / (areas[i] + areas[orderb[1:]] - inter)
|
561 |
+
|
562 |
+
inds = np.where(ovr <= thresh)[0]
|
563 |
+
orderb = orderb[inds + 1]
|
564 |
+
|
565 |
+
det = pre_det[keep, :]
|
566 |
+
|
567 |
+
kpss = kpss[order,:,:]
|
568 |
+
kpss = kpss[keep,:,:]
|
569 |
+
|
570 |
+
if max_num > 0 and det.shape[0] > max_num:
|
571 |
+
area = (det[:, 2] - det[:, 0]) * (det[:, 3] - det[:, 1])
|
572 |
+
det_img_center = det_img.shape[0] // 2, det_img.shape[1] // 2
|
573 |
+
offsets = np.vstack([
|
574 |
+
(det[:, 0] + det[:, 2]) / 2 - det_img_center[1],
|
575 |
+
(det[:, 1] + det[:, 3]) / 2 - det_img_center[0]
|
576 |
+
])
|
577 |
+
offset_dist_squared = np.sum(np.power(offsets, 2.0), 0)
|
578 |
+
|
579 |
+
values = area - offset_dist_squared * 2.0 # some extra weight on the centering
|
580 |
+
bindex = np.argsort(values)[::-1] # some extra weight on the centering
|
581 |
+
bindex = bindex[0:max_num]
|
582 |
+
|
583 |
+
det = det[bindex, :]
|
584 |
+
if kpss is not None:
|
585 |
+
kpss = kpss[bindex, :]
|
586 |
+
|
587 |
+
score_values = det[:, 4]
|
588 |
+
# delete score column
|
589 |
+
det = np.delete(det, 4, 1)
|
590 |
+
|
591 |
+
if use_landmark_detection and len(kpss) > 0:
|
592 |
+
for i in range(kpss.shape[0]):
|
593 |
+
landmark_kpss, landmark_scores = self.run_detect_landmark(img_landmark, det[i], kpss[i], landmark_detect_mode, landmark_score, from_points)
|
594 |
+
if len(landmark_kpss) > 0:
|
595 |
+
if len(landmark_scores) > 0:
|
596 |
+
#print(np.mean(landmark_scores))
|
597 |
+
#print(np.mean(score_values[i]))
|
598 |
+
if np.mean(landmark_scores) > np.mean(score_values[i]):
|
599 |
+
kpss[i] = landmark_kpss
|
600 |
+
else:
|
601 |
+
kpss[i] = landmark_kpss
|
602 |
+
|
603 |
+
return det, kpss
|
604 |
+
|
605 |
+
def detect_retinaface2(self, img, max_num, score):
|
606 |
+
|
607 |
+
# Resize image to fit within the input_size
|
608 |
+
input_size = (640, 640)
|
609 |
+
im_ratio = torch.div(img.size()[1], img.size()[2])
|
610 |
+
|
611 |
+
# model_ratio = float(input_size[1]) / input_size[0]
|
612 |
+
model_ratio = 1.0
|
613 |
+
if im_ratio > model_ratio:
|
614 |
+
new_height = input_size[1]
|
615 |
+
new_width = int(new_height / im_ratio)
|
616 |
+
else:
|
617 |
+
new_width = input_size[0]
|
618 |
+
new_height = int(new_width * im_ratio)
|
619 |
+
det_scale = torch.div(new_height, img.size()[1])
|
620 |
+
|
621 |
+
resize = v2.Resize((new_height, new_width), antialias=True)
|
622 |
+
img = resize(img)
|
623 |
+
img = img.permute(1, 2, 0)
|
624 |
+
|
625 |
+
det_img = torch.zeros((input_size[1], input_size[0], 3), dtype=torch.float32, device='cuda:0')
|
626 |
+
det_img[:new_height, :new_width, :] = img
|
627 |
+
|
628 |
+
# Switch to BGR and normalize
|
629 |
+
det_img = det_img[:, :, [2, 1, 0]]
|
630 |
+
det_img = torch.sub(det_img, 127.5)
|
631 |
+
det_img = torch.div(det_img, 128.0)
|
632 |
+
det_img = det_img.permute(2, 0, 1) # 3,128,128
|
633 |
+
|
634 |
+
# Prepare data and find model parameters
|
635 |
+
det_img = torch.unsqueeze(det_img, 0).contiguous()
|
636 |
+
|
637 |
+
io_binding = self.retinaface_model.io_binding()
|
638 |
+
io_binding.bind_input(name='input.1', device_type='cuda', device_id=0, element_type=np.float32, shape=det_img.size(), buffer_ptr=det_img.data_ptr())
|
639 |
+
|
640 |
+
io_binding.bind_output('448', 'cuda')
|
641 |
+
io_binding.bind_output('471', 'cuda')
|
642 |
+
io_binding.bind_output('494', 'cuda')
|
643 |
+
io_binding.bind_output('451', 'cuda')
|
644 |
+
io_binding.bind_output('474', 'cuda')
|
645 |
+
io_binding.bind_output('497', 'cuda')
|
646 |
+
io_binding.bind_output('454', 'cuda')
|
647 |
+
io_binding.bind_output('477', 'cuda')
|
648 |
+
io_binding.bind_output('500', 'cuda')
|
649 |
+
|
650 |
+
# Sync and run model
|
651 |
+
self.syncvec.cpu()
|
652 |
+
self.retinaface_model.run_with_iobinding(io_binding)
|
653 |
+
|
654 |
+
net_outs = io_binding.copy_outputs_to_cpu()
|
655 |
+
|
656 |
+
input_height = det_img.shape[2]
|
657 |
+
input_width = det_img.shape[3]
|
658 |
+
|
659 |
+
fmc = 3
|
660 |
+
center_cache = {}
|
661 |
+
scores_list = []
|
662 |
+
bboxes_list = []
|
663 |
+
kpss_list = []
|
664 |
+
for idx, stride in enumerate([8, 16, 32]):
|
665 |
+
scores = net_outs[idx]
|
666 |
+
bbox_preds = net_outs[idx + fmc]
|
667 |
+
bbox_preds = bbox_preds * stride
|
668 |
+
|
669 |
+
kps_preds = net_outs[idx + fmc * 2] * stride
|
670 |
+
height = input_height // stride
|
671 |
+
width = input_width // stride
|
672 |
+
K = height * width
|
673 |
+
key = (height, width, stride)
|
674 |
+
if key in center_cache:
|
675 |
+
anchor_centers = center_cache[key]
|
676 |
+
else:
|
677 |
+
anchor_centers = np.stack(np.mgrid[:height, :width][::-1], axis=-1).astype(np.float32)
|
678 |
+
anchor_centers = (anchor_centers * stride).reshape((-1, 2))
|
679 |
+
anchor_centers = np.stack([anchor_centers] * 2, axis=1).reshape((-1, 2))
|
680 |
+
if len(center_cache) < 100:
|
681 |
+
center_cache[key] = anchor_centers
|
682 |
+
|
683 |
+
pos_inds = np.where(scores >= score)[0]
|
684 |
+
|
685 |
+
x1 = anchor_centers[:, 0] - bbox_preds[:, 0]
|
686 |
+
y1 = anchor_centers[:, 1] - bbox_preds[:, 1]
|
687 |
+
x2 = anchor_centers[:, 0] + bbox_preds[:, 2]
|
688 |
+
y2 = anchor_centers[:, 1] + bbox_preds[:, 3]
|
689 |
+
|
690 |
+
bboxes = np.stack([x1, y1, x2, y2], axis=-1)
|
691 |
+
|
692 |
+
pos_scores = scores[pos_inds]
|
693 |
+
pos_bboxes = bboxes[pos_inds]
|
694 |
+
scores_list.append(pos_scores)
|
695 |
+
bboxes_list.append(pos_bboxes)
|
696 |
+
|
697 |
+
preds = []
|
698 |
+
for i in range(0, kps_preds.shape[1], 2):
|
699 |
+
px = anchor_centers[:, i % 2] + kps_preds[:, i]
|
700 |
+
py = anchor_centers[:, i % 2 + 1] + kps_preds[:, i + 1]
|
701 |
+
|
702 |
+
preds.append(px)
|
703 |
+
preds.append(py)
|
704 |
+
kpss = np.stack(preds, axis=-1)
|
705 |
+
# kpss = kps_preds
|
706 |
+
kpss = kpss.reshape((kpss.shape[0], -1, 2))
|
707 |
+
pos_kpss = kpss[pos_inds]
|
708 |
+
kpss_list.append(pos_kpss)
|
709 |
+
# result_boxes = cv2.dnn.NMSBoxes(bboxes_list, scores_list, 0.25, 0.45, 0.5)
|
710 |
+
# print(result_boxes)
|
711 |
+
scores = np.vstack(scores_list)
|
712 |
+
scores_ravel = scores.ravel()
|
713 |
+
order = scores_ravel.argsort()[::-1]
|
714 |
+
|
715 |
+
det_scale = det_scale.numpy() ###
|
716 |
+
|
717 |
+
bboxes = np.vstack(bboxes_list) / det_scale
|
718 |
+
|
719 |
+
kpss = np.vstack(kpss_list) / det_scale
|
720 |
+
pre_det = np.hstack((bboxes, scores)).astype(np.float32, copy=False)
|
721 |
+
pre_det = pre_det[order, :]
|
722 |
+
|
723 |
+
|
724 |
+
|
725 |
+
dets = pre_det
|
726 |
+
thresh = 0.4
|
727 |
+
x1 = dets[:, 0]
|
728 |
+
y1 = dets[:, 1]
|
729 |
+
x2 = dets[:, 2]
|
730 |
+
y2 = dets[:, 3]
|
731 |
+
scoresb = dets[:, 4]
|
732 |
+
|
733 |
+
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
|
734 |
+
orderb = scoresb.argsort()[::-1]
|
735 |
+
|
736 |
+
keep = []
|
737 |
+
person_id = 0
|
738 |
+
people = {}
|
739 |
+
|
740 |
+
while orderb.size > 0:
|
741 |
+
# Add first box in list
|
742 |
+
i = orderb[0]
|
743 |
+
keep.append(i)
|
744 |
+
|
745 |
+
people[person_id] = orderb[0]
|
746 |
+
|
747 |
+
|
748 |
+
# Find overlap of remaining boxes
|
749 |
+
xx1 = np.maximum(x1[i], x1[orderb[1:]])
|
750 |
+
yy1 = np.maximum(y1[i], y1[orderb[1:]])
|
751 |
+
xx2 = np.minimum(x2[i], x2[orderb[1:]])
|
752 |
+
yy2 = np.minimum(y2[i], y2[orderb[1:]])
|
753 |
+
|
754 |
+
w = np.maximum(0.0, xx2 - xx1 + 1)
|
755 |
+
h = np.maximum(0.0, yy2 - yy1 + 1)
|
756 |
+
|
757 |
+
inter = w * h
|
758 |
+
|
759 |
+
|
760 |
+
ovr = inter / (areas[i] + areas[orderb[1:]] - inter)
|
761 |
+
|
762 |
+
|
763 |
+
inds0 = np.where(ovr > thresh)[0]
|
764 |
+
people[person_id] = np.hstack((people[person_id], orderb[inds0+1])).astype(np.int, copy=False)
|
765 |
+
|
766 |
+
|
767 |
+
# identify where there is no overlap (<thresh)
|
768 |
+
inds = np.where(ovr <= thresh)[0]
|
769 |
+
# print(len(inds))
|
770 |
+
|
771 |
+
|
772 |
+
orderb = orderb[inds+1]
|
773 |
+
person_id += 1
|
774 |
+
|
775 |
+
|
776 |
+
|
777 |
+
det = pre_det[keep, :]
|
778 |
+
|
779 |
+
|
780 |
+
kpss = kpss[order, :, :]
|
781 |
+
# print('order', kpss)
|
782 |
+
# kpss = kpss[keep, :, :]
|
783 |
+
# print('keep',kpss)
|
784 |
+
|
785 |
+
kpss_ave = []
|
786 |
+
for person in people:
|
787 |
+
# print(kpss[people[person], :, :])
|
788 |
+
# print('mean', np.mean(kpss[people[person], :, :], axis=0))
|
789 |
+
# print(kpss[people[person], :, :].shape)
|
790 |
+
kpss_ave.append(np.mean(kpss[people[person], :, :], axis=0).tolist())
|
791 |
+
|
792 |
+
|
793 |
+
if max_num > 0 and det.shape[0] > max_num:
|
794 |
+
area = (det[:, 2] - det[:, 0]) * (det[:, 3] - det[:, 1])
|
795 |
+
det_img_center = det_img.shape[0] // 2, det_img.shape[1] // 2
|
796 |
+
offsets = np.vstack([
|
797 |
+
(det[:, 0] + det[:, 2]) / 2 - det_img_center[1],
|
798 |
+
(det[:, 1] + det[:, 3]) / 2 - det_img_center[0]
|
799 |
+
])
|
800 |
+
offset_dist_squared = np.sum(np.power(offsets, 2.0), 0)
|
801 |
+
|
802 |
+
values = area - offset_dist_squared * 2.0 # some extra weight on the centering
|
803 |
+
bindex = np.argsort(values)[::-1] # some extra weight on the centering
|
804 |
+
bindex = bindex[0:max_num]
|
805 |
+
|
806 |
+
det = det[bindex, :]
|
807 |
+
if kpss is not None:
|
808 |
+
kpss = kpss[bindex, :]
|
809 |
+
|
810 |
+
# return kpss_ave
|
811 |
+
|
812 |
+
# delete score column
|
813 |
+
det = np.delete(det, 4, 1)
|
814 |
+
|
815 |
+
return kpss_ave
|
816 |
+
|
817 |
+
def detect_scrdf(self, img, max_num, score, use_landmark_detection, landmark_detect_mode, landmark_score, from_points):
|
818 |
+
if use_landmark_detection:
|
819 |
+
img_landmark = img.clone()
|
820 |
+
|
821 |
+
# Resize image to fit within the input_size
|
822 |
+
input_size = (640, 640)
|
823 |
+
im_ratio = torch.div(img.size()[1], img.size()[2])
|
824 |
+
|
825 |
+
model_ratio = float(input_size[1]) / input_size[0]
|
826 |
+
if im_ratio>model_ratio:
|
827 |
+
new_height = input_size[1]
|
828 |
+
new_width = int(new_height / im_ratio)
|
829 |
+
else:
|
830 |
+
new_width = input_size[0]
|
831 |
+
new_height = int(new_width * im_ratio)
|
832 |
+
det_scale = torch.div(new_height, img.size()[1])
|
833 |
+
|
834 |
+
resize = v2.Resize((new_height, new_width), antialias=True)
|
835 |
+
img = resize(img)
|
836 |
+
img = img.permute(1,2,0)
|
837 |
+
|
838 |
+
det_img = torch.zeros((input_size[1], input_size[0], 3), dtype=torch.float32, device='cuda:0')
|
839 |
+
det_img[:new_height,:new_width, :] = img
|
840 |
+
|
841 |
+
# Switch to BGR and normalize
|
842 |
+
det_img = det_img[:, :, [2,1,0]]
|
843 |
+
det_img = torch.sub(det_img, 127.5)
|
844 |
+
det_img = torch.div(det_img, 128.0)
|
845 |
+
det_img = det_img.permute(2, 0, 1) #3,128,128
|
846 |
+
|
847 |
+
# Prepare data and find model parameters
|
848 |
+
det_img = torch.unsqueeze(det_img, 0).contiguous()
|
849 |
+
input_name = self.scrdf_model.get_inputs()[0].name
|
850 |
+
|
851 |
+
outputs = self.scrdf_model.get_outputs()
|
852 |
+
output_names = []
|
853 |
+
for o in outputs:
|
854 |
+
output_names.append(o.name)
|
855 |
+
|
856 |
+
io_binding = self.scrdf_model.io_binding()
|
857 |
+
io_binding.bind_input(name=input_name, device_type='cuda', device_id=0, element_type=np.float32, shape=det_img.size(), buffer_ptr=det_img.data_ptr())
|
858 |
+
|
859 |
+
for i in range(len(output_names)):
|
860 |
+
io_binding.bind_output(output_names[i], 'cuda')
|
861 |
+
|
862 |
+
# Sync and run model
|
863 |
+
syncvec = self.syncvec.cpu()
|
864 |
+
self.scrdf_model.run_with_iobinding(io_binding)
|
865 |
+
|
866 |
+
net_outs = io_binding.copy_outputs_to_cpu()
|
867 |
+
|
868 |
+
input_height = det_img.shape[2]
|
869 |
+
input_width = det_img.shape[3]
|
870 |
+
|
871 |
+
fmc = 3
|
872 |
+
center_cache = {}
|
873 |
+
scores_list = []
|
874 |
+
bboxes_list = []
|
875 |
+
kpss_list = []
|
876 |
+
for idx, stride in enumerate([8, 16, 32]):
|
877 |
+
scores = net_outs[idx]
|
878 |
+
bbox_preds = net_outs[idx+fmc]
|
879 |
+
bbox_preds = bbox_preds * stride
|
880 |
+
|
881 |
+
kps_preds = net_outs[idx+fmc*2] * stride
|
882 |
+
height = input_height // stride
|
883 |
+
width = input_width // stride
|
884 |
+
K = height * width
|
885 |
+
key = (height, width, stride)
|
886 |
+
if key in center_cache:
|
887 |
+
anchor_centers = center_cache[key]
|
888 |
+
else:
|
889 |
+
anchor_centers = np.stack(np.mgrid[:height, :width][::-1], axis=-1).astype(np.float32)
|
890 |
+
anchor_centers = (anchor_centers * stride).reshape( (-1, 2) )
|
891 |
+
anchor_centers = np.stack([anchor_centers]*2, axis=1).reshape( (-1,2) )
|
892 |
+
if len(center_cache)<100:
|
893 |
+
center_cache[key] = anchor_centers
|
894 |
+
|
895 |
+
pos_inds = np.where(scores>=score)[0]
|
896 |
+
|
897 |
+
x1 = anchor_centers[:, 0] - bbox_preds[:, 0]
|
898 |
+
y1 = anchor_centers[:, 1] - bbox_preds[:, 1]
|
899 |
+
x2 = anchor_centers[:, 0] + bbox_preds[:, 2]
|
900 |
+
y2 = anchor_centers[:, 1] + bbox_preds[:, 3]
|
901 |
+
|
902 |
+
bboxes = np.stack([x1, y1, x2, y2], axis=-1)
|
903 |
+
|
904 |
+
pos_scores = scores[pos_inds]
|
905 |
+
pos_bboxes = bboxes[pos_inds]
|
906 |
+
scores_list.append(pos_scores)
|
907 |
+
bboxes_list.append(pos_bboxes)
|
908 |
+
|
909 |
+
preds = []
|
910 |
+
for i in range(0, kps_preds.shape[1], 2):
|
911 |
+
px = anchor_centers[:, i%2] + kps_preds[:, i]
|
912 |
+
py = anchor_centers[:, i%2+1] + kps_preds[:, i+1]
|
913 |
+
|
914 |
+
preds.append(px)
|
915 |
+
preds.append(py)
|
916 |
+
kpss = np.stack(preds, axis=-1)
|
917 |
+
#kpss = kps_preds
|
918 |
+
kpss = kpss.reshape( (kpss.shape[0], -1, 2) )
|
919 |
+
pos_kpss = kpss[pos_inds]
|
920 |
+
kpss_list.append(pos_kpss)
|
921 |
+
|
922 |
+
scores = np.vstack(scores_list)
|
923 |
+
scores_ravel = scores.ravel()
|
924 |
+
order = scores_ravel.argsort()[::-1]
|
925 |
+
|
926 |
+
det_scale = det_scale.numpy()###
|
927 |
+
|
928 |
+
bboxes = np.vstack(bboxes_list) / det_scale
|
929 |
+
|
930 |
+
kpss = np.vstack(kpss_list) / det_scale
|
931 |
+
pre_det = np.hstack((bboxes, scores)).astype(np.float32, copy=False)
|
932 |
+
pre_det = pre_det[order, :]
|
933 |
+
|
934 |
+
dets = pre_det
|
935 |
+
thresh = 0.4
|
936 |
+
x1 = dets[:, 0]
|
937 |
+
y1 = dets[:, 1]
|
938 |
+
x2 = dets[:, 2]
|
939 |
+
y2 = dets[:, 3]
|
940 |
+
scoresb = dets[:, 4]
|
941 |
+
|
942 |
+
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
|
943 |
+
orderb = scoresb.argsort()[::-1]
|
944 |
+
|
945 |
+
keep = []
|
946 |
+
while orderb.size > 0:
|
947 |
+
i = orderb[0]
|
948 |
+
keep.append(i)
|
949 |
+
xx1 = np.maximum(x1[i], x1[orderb[1:]])
|
950 |
+
yy1 = np.maximum(y1[i], y1[orderb[1:]])
|
951 |
+
xx2 = np.minimum(x2[i], x2[orderb[1:]])
|
952 |
+
yy2 = np.minimum(y2[i], y2[orderb[1:]])
|
953 |
+
|
954 |
+
w = np.maximum(0.0, xx2 - xx1 + 1)
|
955 |
+
h = np.maximum(0.0, yy2 - yy1 + 1)
|
956 |
+
|
957 |
+
inter = w * h
|
958 |
+
ovr = inter / (areas[i] + areas[orderb[1:]] - inter)
|
959 |
+
|
960 |
+
inds = np.where(ovr <= thresh)[0]
|
961 |
+
orderb = orderb[inds + 1]
|
962 |
+
|
963 |
+
det = pre_det[keep, :]
|
964 |
+
|
965 |
+
kpss = kpss[order,:,:]
|
966 |
+
kpss = kpss[keep,:,:]
|
967 |
+
|
968 |
+
if max_num > 0 and det.shape[0] > max_num:
|
969 |
+
area = (det[:, 2] - det[:, 0]) * (det[:, 3] -
|
970 |
+
det[:, 1])
|
971 |
+
det_img_center = det_img.shape[0] // 2, det_img.shape[1] // 2
|
972 |
+
offsets = np.vstack([
|
973 |
+
(det[:, 0] + det[:, 2]) / 2 - det_img_center[1],
|
974 |
+
(det[:, 1] + det[:, 3]) / 2 - det_img_center[0]
|
975 |
+
])
|
976 |
+
offset_dist_squared = np.sum(np.power(offsets, 2.0), 0)
|
977 |
+
|
978 |
+
values = area - offset_dist_squared * 2.0 # some extra weight on the centering
|
979 |
+
bindex = np.argsort(values)[::-1] # some extra weight on the centering
|
980 |
+
bindex = bindex[0:max_num]
|
981 |
+
|
982 |
+
det = det[bindex, :]
|
983 |
+
if kpss is not None:
|
984 |
+
kpss = kpss[bindex, :]
|
985 |
+
|
986 |
+
score_values = det[:, 4]
|
987 |
+
# delete score column
|
988 |
+
det = np.delete(det, 4, 1)
|
989 |
+
|
990 |
+
if use_landmark_detection and len(kpss) > 0:
|
991 |
+
for i in range(kpss.shape[0]):
|
992 |
+
landmark_kpss, landmark_scores = self.run_detect_landmark(img_landmark, det[i], kpss[i], landmark_detect_mode, landmark_score, from_points)
|
993 |
+
if len(landmark_kpss) > 0:
|
994 |
+
if len(landmark_scores) > 0:
|
995 |
+
#print(np.mean(landmark_scores))
|
996 |
+
#print(np.mean(score_values[i]))
|
997 |
+
if np.mean(landmark_scores) > np.mean(score_values[i]):
|
998 |
+
kpss[i] = landmark_kpss
|
999 |
+
else:
|
1000 |
+
kpss[i] = landmark_kpss
|
1001 |
+
|
1002 |
+
return det, kpss
|
1003 |
+
|
1004 |
+
def detect_yoloface(self, img, max_num, score, use_landmark_detection, landmark_detect_mode, landmark_score, from_points):
|
1005 |
+
if use_landmark_detection:
|
1006 |
+
img_landmark = img.clone()
|
1007 |
+
|
1008 |
+
height = img.size(dim=1)
|
1009 |
+
width = img.size(dim=2)
|
1010 |
+
length = max((height, width))
|
1011 |
+
|
1012 |
+
image = torch.zeros((length, length, 3), dtype=torch.uint8, device='cuda')
|
1013 |
+
img = img.permute(1,2,0)
|
1014 |
+
|
1015 |
+
image[0:height, 0:width] = img
|
1016 |
+
scale = length/640.0
|
1017 |
+
image = torch.div(image, 255.0)
|
1018 |
+
|
1019 |
+
t640 = v2.Resize((640, 640), antialias=False)
|
1020 |
+
image = image.permute(2, 0, 1)
|
1021 |
+
image = t640(image)
|
1022 |
+
|
1023 |
+
image = torch.unsqueeze(image, 0).contiguous()
|
1024 |
+
|
1025 |
+
io_binding = self.yoloface_model.io_binding()
|
1026 |
+
io_binding.bind_input(name='images', device_type='cuda', device_id=0, element_type=np.float32, shape=image.size(), buffer_ptr=image.data_ptr())
|
1027 |
+
io_binding.bind_output('output0', 'cuda')
|
1028 |
+
|
1029 |
+
# Sync and run model
|
1030 |
+
self.syncvec.cpu()
|
1031 |
+
self.yoloface_model.run_with_iobinding(io_binding)
|
1032 |
+
|
1033 |
+
net_outs = io_binding.copy_outputs_to_cpu()
|
1034 |
+
|
1035 |
+
outputs = np.squeeze(net_outs).T
|
1036 |
+
|
1037 |
+
bbox_raw, score_raw, kps_raw = np.split(outputs, [4, 5], axis=1)
|
1038 |
+
|
1039 |
+
bbox_list = []
|
1040 |
+
score_list = []
|
1041 |
+
kps_list = []
|
1042 |
+
keep_indices = np.where(score_raw > score)[0]
|
1043 |
+
|
1044 |
+
if keep_indices.any():
|
1045 |
+
bbox_raw, kps_raw, score_raw = bbox_raw[keep_indices], kps_raw[keep_indices], score_raw[keep_indices]
|
1046 |
+
|
1047 |
+
bbox_raw = bbox_raw * scale
|
1048 |
+
|
1049 |
+
for bbox in bbox_raw:
|
1050 |
+
bbox_list.append(np.array([(bbox[0]-bbox[2]/2), (bbox[1]-bbox[3]/2), (bbox[0]+bbox[2]/2), (bbox[1]+bbox[3]/2)]))
|
1051 |
+
|
1052 |
+
kps_raw = kps_raw * scale
|
1053 |
+
|
1054 |
+
for kps in kps_raw:
|
1055 |
+
indexes = np.arange(0, len(kps), 3)
|
1056 |
+
temp_kps = []
|
1057 |
+
for index in indexes:
|
1058 |
+
temp_kps.append([kps[index], kps[index + 1]])
|
1059 |
+
kps_list.append(np.array(temp_kps))
|
1060 |
+
score_list = score_raw.ravel().tolist()
|
1061 |
+
|
1062 |
+
result_boxes = cv2.dnn.NMSBoxes(bbox_list, score_list, 0.25, 0.45, 0.5)
|
1063 |
+
|
1064 |
+
bboxes_list = []
|
1065 |
+
kpss_list = []
|
1066 |
+
for r in result_boxes:
|
1067 |
+
if r==max_num:
|
1068 |
+
break
|
1069 |
+
if use_landmark_detection and len(kps_list[r]) > 0:
|
1070 |
+
landmark_kpss, landmark_scores = self.run_detect_landmark(img_landmark, bbox_list[r], kps_list[r], landmark_detect_mode, landmark_score, from_points)
|
1071 |
+
if len(landmark_kpss) > 0:
|
1072 |
+
if len(landmark_scores) > 0:
|
1073 |
+
#print(np.mean(landmark_scores))
|
1074 |
+
#print(np.mean(score_list[r]))
|
1075 |
+
if np.mean(landmark_scores) > np.mean(score_list[r]):
|
1076 |
+
kps_list[r] = landmark_kpss
|
1077 |
+
else:
|
1078 |
+
kps_list[r] = landmark_kpss
|
1079 |
+
|
1080 |
+
bboxes_list.append(bbox_list[r])
|
1081 |
+
kpss_list.append(kps_list[r])
|
1082 |
+
|
1083 |
+
return np.array(bboxes_list), np.array(kpss_list)
|
1084 |
+
|
1085 |
+
def detect_yoloface2(self, image_in, max_num, score):
|
1086 |
+
img = image_in.detach().clone()
|
1087 |
+
|
1088 |
+
height = img.size(dim=1)
|
1089 |
+
width = img.size(dim=2)
|
1090 |
+
length = max((height, width))
|
1091 |
+
|
1092 |
+
image = torch.zeros((length, length, 3), dtype=torch.uint8,
|
1093 |
+
device='cuda')
|
1094 |
+
img = img.permute(1, 2, 0)
|
1095 |
+
|
1096 |
+
image[0:height, 0:width] = img
|
1097 |
+
scale = length / 640.0
|
1098 |
+
image = torch.div(image, 255.0)
|
1099 |
+
|
1100 |
+
t640 = v2.Resize((640, 640), antialias=False)
|
1101 |
+
image = image.permute(2, 0, 1)
|
1102 |
+
image = t640(image)
|
1103 |
+
|
1104 |
+
image = torch.unsqueeze(image, 0).contiguous()
|
1105 |
+
|
1106 |
+
io_binding = self.yoloface_model.io_binding()
|
1107 |
+
io_binding.bind_input(name='images', device_type='cuda', device_id=0,
|
1108 |
+
element_type=np.float32, shape=image.size(),
|
1109 |
+
buffer_ptr=image.data_ptr())
|
1110 |
+
io_binding.bind_output('output0', 'cuda')
|
1111 |
+
|
1112 |
+
# Sync and run model
|
1113 |
+
self.syncvec.cpu()
|
1114 |
+
self.yoloface_model.run_with_iobinding(io_binding)
|
1115 |
+
|
1116 |
+
net_outs = io_binding.copy_outputs_to_cpu()
|
1117 |
+
|
1118 |
+
outputs = np.squeeze(net_outs).T
|
1119 |
+
|
1120 |
+
bbox_raw, score_raw, kps_raw = np.split(outputs, [4, 5], axis=1)
|
1121 |
+
|
1122 |
+
bbox_list = []
|
1123 |
+
score_list = []
|
1124 |
+
kps_list = []
|
1125 |
+
keep_indices = np.where(score_raw > score)[0]
|
1126 |
+
|
1127 |
+
if keep_indices.any():
|
1128 |
+
bbox_raw, kps_raw, score_raw = bbox_raw[keep_indices], kps_raw[
|
1129 |
+
keep_indices], score_raw[keep_indices]
|
1130 |
+
for bbox in bbox_raw:
|
1131 |
+
bbox_list.append(np.array(
|
1132 |
+
[(bbox[0] - bbox[2] / 2), (bbox[1] - bbox[3] / 2),
|
1133 |
+
(bbox[0] + bbox[2] / 2), (bbox[1] + bbox[3] / 2)]))
|
1134 |
+
kps_raw = kps_raw * scale
|
1135 |
+
|
1136 |
+
for kps in kps_raw:
|
1137 |
+
indexes = np.arange(0, len(kps), 3)
|
1138 |
+
temp_kps = []
|
1139 |
+
for index in indexes:
|
1140 |
+
temp_kps.append([kps[index], kps[index + 1]])
|
1141 |
+
kps_list.append(np.array(temp_kps))
|
1142 |
+
score_list = score_raw.ravel().tolist()
|
1143 |
+
|
1144 |
+
result_boxes = cv2.dnn.NMSBoxes(bbox_list, score_list, 0.25, 0.45, 0.5)
|
1145 |
+
|
1146 |
+
result = []
|
1147 |
+
for r in result_boxes:
|
1148 |
+
if r == max_num:
|
1149 |
+
break
|
1150 |
+
bbox_list = bbox_list[r]
|
1151 |
+
result.append(kps_list[r])
|
1152 |
+
bbox_list = bbox_list*scale
|
1153 |
+
# print(bbox_list)
|
1154 |
+
# print(bbox_list*scale)
|
1155 |
+
|
1156 |
+
# img = image_in.detach().clone()
|
1157 |
+
# test = image_in.permute(1, 2, 0)
|
1158 |
+
# test = test.cpu().numpy()
|
1159 |
+
# cv2.imwrite('1.jpg', test)
|
1160 |
+
|
1161 |
+
# b_scale = 50
|
1162 |
+
# bbox_list[0] = bbox_list[0] - b_scale
|
1163 |
+
# bbox_list[1] = bbox_list[1] - b_scale
|
1164 |
+
# bbox_list[2] = bbox_list[2] + b_scale
|
1165 |
+
# bbox_list[3] = bbox_list[3] + b_scale
|
1166 |
+
|
1167 |
+
img = image_in.detach().clone()
|
1168 |
+
|
1169 |
+
img = img[:, int(bbox_list[1]):int(bbox_list[3]), int(bbox_list[0]):int(bbox_list[2])]
|
1170 |
+
# print(img.size())
|
1171 |
+
|
1172 |
+
|
1173 |
+
height = img.size(dim=1)
|
1174 |
+
width = img.size(dim=2)
|
1175 |
+
length = max((height, width))
|
1176 |
+
|
1177 |
+
image = torch.zeros((length, length, 3), dtype=torch.uint8, device='cuda')
|
1178 |
+
img = img.permute(1,2,0)
|
1179 |
+
|
1180 |
+
image[0:height, 0:width] = img
|
1181 |
+
scale = length/192
|
1182 |
+
image = torch.div(image, 255.0)
|
1183 |
+
|
1184 |
+
|
1185 |
+
t192 = v2.Resize((192, 192), antialias=False)
|
1186 |
+
image = image.permute(2, 0, 1)
|
1187 |
+
image = t192(image)
|
1188 |
+
|
1189 |
+
test = image_in.detach().clone().permute(1, 2, 0)
|
1190 |
+
test = test.cpu().numpy()
|
1191 |
+
|
1192 |
+
input_mean = 0.0
|
1193 |
+
input_std = 1.0
|
1194 |
+
|
1195 |
+
self.lmk_dim = 2
|
1196 |
+
self.lmk_num = 106
|
1197 |
+
|
1198 |
+
bbox = bbox_list
|
1199 |
+
w, h = (bbox[2] - bbox[0]), (bbox[3] - bbox[1])
|
1200 |
+
center = (bbox[2] + bbox[0]) / 2, (bbox[3] + bbox[1]) / 2
|
1201 |
+
rotate = 0
|
1202 |
+
_scale = 192 / (max(w, h) * 1.5)
|
1203 |
+
# print('param:', img.shape, bbox, center, self.input_size, _scale, rotate)
|
1204 |
+
aimg, M = self.transform(test, center, 192, _scale, rotate)
|
1205 |
+
input_size = tuple(aimg.shape[0:2][::-1])
|
1206 |
+
# assert input_size==self.input_size
|
1207 |
+
blob = cv2.dnn.blobFromImage(aimg, 1.0 / input_std, input_size, ( input_mean, input_mean, input_mean), swapRB=True)
|
1208 |
+
pred = self.insight106_model.run(['fc1'], {'data': blob})[0][0]
|
1209 |
+
if pred.shape[0] >= 3000:
|
1210 |
+
pred = pred.reshape((-1, 3))
|
1211 |
+
else:
|
1212 |
+
pred = pred.reshape((-1, 2))
|
1213 |
+
if self.lmk_num < pred.shape[0]:
|
1214 |
+
pred = pred[self.lmk_num * -1:, :]
|
1215 |
+
pred[:, 0:2] += 1
|
1216 |
+
pred[:, 0:2] *= 96
|
1217 |
+
if pred.shape[1] == 3:
|
1218 |
+
pred[:, 2] *= (106)
|
1219 |
+
|
1220 |
+
IM = cv2.invertAffineTransform(M)
|
1221 |
+
pred = self.trans_points2d(pred, IM)
|
1222 |
+
# face[self.taskname] = pred
|
1223 |
+
# if self.require_pose:
|
1224 |
+
# P = transform.estimate_affine_matrix_3d23d(self.mean_lmk, pred)
|
1225 |
+
# s, R, t = transform.P2sRt(P)
|
1226 |
+
# rx, ry, rz = transform.matrix2angle(R)
|
1227 |
+
# pose = np.array([rx, ry, rz], dtype=np.float32)
|
1228 |
+
# face['pose'] = pose # pitch, yaw, roll
|
1229 |
+
# print(pred.shape)
|
1230 |
+
# print(pred)
|
1231 |
+
|
1232 |
+
for point in pred:
|
1233 |
+
test[int(point[1])] [int(point[0])] [0] = 255
|
1234 |
+
test[int(point[1])] [int(point[0])] [1] = 255
|
1235 |
+
test[int(point[1])] [int(point[0])] [2] = 255
|
1236 |
+
cv2.imwrite('2.jpg', test)
|
1237 |
+
|
1238 |
+
predd = []
|
1239 |
+
predd.append(pred[38])
|
1240 |
+
predd.append(pred[88])
|
1241 |
+
# predd.append(pred[86])
|
1242 |
+
# predd.append(pred[52])
|
1243 |
+
# predd.append(pred[61])
|
1244 |
+
|
1245 |
+
predd.append(kps_list[0][2])
|
1246 |
+
predd.append(kps_list[0][3])
|
1247 |
+
predd.append(kps_list[0][4])
|
1248 |
+
|
1249 |
+
# for point in predd:
|
1250 |
+
# test[int(point[1])] [int(point[0])] [0] = 255
|
1251 |
+
# test[int(point[1])] [int(point[0])] [1] = 255
|
1252 |
+
# test[int(point[1])] [int(point[0])] [2] = 255
|
1253 |
+
# cv2.imwrite('2.jpg', test)
|
1254 |
+
preddd=[]
|
1255 |
+
preddd.append(predd)
|
1256 |
+
return np.array(preddd)
|
1257 |
+
def transform(self, data, center, output_size, scale, rotation):
|
1258 |
+
scale_ratio = scale
|
1259 |
+
rot = float(rotation) * np.pi / 180.0
|
1260 |
+
# translation = (output_size/2-center[0]*scale_ratio, output_size/2-center[1]*scale_ratio)
|
1261 |
+
t1 = trans.SimilarityTransform(scale=scale_ratio)
|
1262 |
+
cx = center[0] * scale_ratio
|
1263 |
+
cy = center[1] * scale_ratio
|
1264 |
+
t2 = trans.SimilarityTransform(translation=(-1 * cx, -1 * cy))
|
1265 |
+
t3 = trans.SimilarityTransform(rotation=rot)
|
1266 |
+
t4 = trans.SimilarityTransform(translation=(output_size / 2,
|
1267 |
+
output_size / 2))
|
1268 |
+
t = t1 + t2 + t3 + t4
|
1269 |
+
M = t.params[0:2]
|
1270 |
+
cropped = cv2.warpAffine(data,
|
1271 |
+
M, (output_size, output_size),
|
1272 |
+
borderValue=0.0)
|
1273 |
+
return cropped, M
|
1274 |
+
|
1275 |
+
def trans_points2d(self, pts, M):
|
1276 |
+
new_pts = np.zeros(shape=pts.shape, dtype=np.float32)
|
1277 |
+
for i in range(pts.shape[0]):
|
1278 |
+
pt = pts[i]
|
1279 |
+
new_pt = np.array([pt[0], pt[1], 1.], dtype=np.float32)
|
1280 |
+
new_pt = np.dot(M, new_pt)
|
1281 |
+
# print('new_pt', new_pt.shape, new_pt)
|
1282 |
+
new_pts[i] = new_pt[0:2]
|
1283 |
+
|
1284 |
+
return new_pts
|
1285 |
+
|
1286 |
+
# image = torch.unsqueeze(image, 0).contiguous()
|
1287 |
+
#
|
1288 |
+
# io_binding = self.insight106_model.io_binding()
|
1289 |
+
# io_binding.bind_input(name='data', device_type='cuda', device_id=0, element_type=np.float32, shape=image.size(), buffer_ptr=image.data_ptr())
|
1290 |
+
# io_binding.bind_output('fc1', 'cuda')
|
1291 |
+
#
|
1292 |
+
# # Sync and run model
|
1293 |
+
# self.syncvec.cpu()
|
1294 |
+
# self.insight106_model.run_with_iobinding(io_binding)
|
1295 |
+
#
|
1296 |
+
# net_outs = io_binding.copy_outputs_to_cpu()
|
1297 |
+
# print(net_outs)
|
1298 |
+
# net_outs[0][0] = net_outs[0][0]+1.
|
1299 |
+
# net_outs[0][0] = net_outs[0][0]/2.
|
1300 |
+
# net_outs[0][0] = net_outs[0][0]*96
|
1301 |
+
#
|
1302 |
+
# # net_outs[0] = net_outs[0]*scale
|
1303 |
+
# # print(net_outs)
|
1304 |
+
# test=test*255.0
|
1305 |
+
# for i in range(0, len(net_outs[0][0]), 2):
|
1306 |
+
# test[int(net_outs[0][0][i+1])] [int(net_outs[0][0][i])] [0] = 255
|
1307 |
+
# test[int(net_outs[0][0][i+1])] [int(net_outs[0][0][i])] [1] = 255
|
1308 |
+
# test[int(net_outs[0][0][i+1])] [int(net_outs[0][0][i])] [2] = 255
|
1309 |
+
# cv2.imwrite('2.jpg', test)
|
1310 |
+
#
|
1311 |
+
# return np.array(result)
|
1312 |
+
def detect_yunet(self, img, max_num, score, use_landmark_detection, landmark_detect_mode, landmark_score, from_points):
|
1313 |
+
if use_landmark_detection:
|
1314 |
+
img_landmark = img.clone()
|
1315 |
+
|
1316 |
+
height = img.size(dim=1)
|
1317 |
+
width = img.size(dim=2)
|
1318 |
+
input_size = (640, 640)
|
1319 |
+
im_ratio = float(height) / width
|
1320 |
+
model_ratio = float(input_size[1]) / input_size[0]
|
1321 |
+
if im_ratio > model_ratio:
|
1322 |
+
new_height = input_size[1]
|
1323 |
+
new_width = int(new_height / im_ratio)
|
1324 |
+
else:
|
1325 |
+
new_width = input_size[0]
|
1326 |
+
new_height = int(new_width * im_ratio)
|
1327 |
+
det_scale = float(new_height) / height
|
1328 |
+
|
1329 |
+
t640 = v2.Resize((new_height, new_width), antialias=False)
|
1330 |
+
img = t640(img)
|
1331 |
+
|
1332 |
+
# Switch to BGR
|
1333 |
+
img = img.permute(1,2,0)
|
1334 |
+
img = img[:, :, [2,1,0]]
|
1335 |
+
|
1336 |
+
image = torch.zeros((input_size[1], input_size[0], 3), dtype=torch.uint8, device='cuda')
|
1337 |
+
image[:new_height, :new_width, :] = img
|
1338 |
+
|
1339 |
+
image = image.permute(2, 0, 1)
|
1340 |
+
image = torch.unsqueeze(image, 0).contiguous()
|
1341 |
+
image = image.to(dtype=torch.float32)
|
1342 |
+
|
1343 |
+
input_name = self.yunet_model.get_inputs()[0].name
|
1344 |
+
outputs = self.yunet_model.get_outputs()
|
1345 |
+
output_names = []
|
1346 |
+
for o in outputs:
|
1347 |
+
output_names.append(o.name)
|
1348 |
+
|
1349 |
+
io_binding = self.yunet_model.io_binding()
|
1350 |
+
io_binding.bind_input(name=input_name, device_type='cuda', device_id=0, element_type=np.float32, shape=image.size(), buffer_ptr=image.data_ptr())
|
1351 |
+
|
1352 |
+
for i in range(len(output_names)):
|
1353 |
+
io_binding.bind_output(output_names[i], 'cuda')
|
1354 |
+
|
1355 |
+
# Sync and run model
|
1356 |
+
syncvec = self.syncvec.cpu()
|
1357 |
+
self.yunet_model.run_with_iobinding(io_binding)
|
1358 |
+
net_outs = io_binding.copy_outputs_to_cpu()
|
1359 |
+
|
1360 |
+
strides = [8, 16, 32]
|
1361 |
+
scores, bboxes, kpss = [], [], []
|
1362 |
+
for idx, stride in enumerate(strides):
|
1363 |
+
cls_pred = net_outs[idx].reshape(-1, 1)
|
1364 |
+
obj_pred = net_outs[idx + len(strides)].reshape(-1, 1)
|
1365 |
+
reg_pred = net_outs[idx + len(strides) * 2].reshape(-1, 4)
|
1366 |
+
kps_pred = net_outs[idx + len(strides) * 3].reshape(
|
1367 |
+
-1, 5 * 2)
|
1368 |
+
|
1369 |
+
anchor_centers = np.stack(
|
1370 |
+
np.mgrid[:(input_size[1] // stride), :(input_size[0] //
|
1371 |
+
stride)][::-1],
|
1372 |
+
axis=-1)
|
1373 |
+
anchor_centers = (anchor_centers * stride).astype(
|
1374 |
+
np.float32).reshape(-1, 2)
|
1375 |
+
|
1376 |
+
bbox_cxy = reg_pred[:, :2] * stride + anchor_centers[:]
|
1377 |
+
bbox_wh = np.exp(reg_pred[:, 2:]) * stride
|
1378 |
+
tl_x = (bbox_cxy[:, 0] - bbox_wh[:, 0] / 2.)
|
1379 |
+
tl_y = (bbox_cxy[:, 1] - bbox_wh[:, 1] / 2.)
|
1380 |
+
br_x = (bbox_cxy[:, 0] + bbox_wh[:, 0] / 2.)
|
1381 |
+
br_y = (bbox_cxy[:, 1] + bbox_wh[:, 1] / 2.)
|
1382 |
+
|
1383 |
+
bboxes.append(np.stack([tl_x, tl_y, br_x, br_y], -1))
|
1384 |
+
# for nk in range(5):
|
1385 |
+
per_kps = np.concatenate(
|
1386 |
+
[((kps_pred[:, [2 * i, 2 * i + 1]] * stride) + anchor_centers)
|
1387 |
+
for i in range(5)],
|
1388 |
+
axis=-1)
|
1389 |
+
|
1390 |
+
kpss.append(per_kps)
|
1391 |
+
scores.append(cls_pred * obj_pred)
|
1392 |
+
|
1393 |
+
scores = np.concatenate(scores, axis=0).reshape(-1)
|
1394 |
+
bboxes = np.concatenate(bboxes, axis=0)
|
1395 |
+
kpss = np.concatenate(kpss, axis=0)
|
1396 |
+
score_mask = (scores > score)
|
1397 |
+
scores = scores[score_mask]
|
1398 |
+
bboxes = bboxes[score_mask]
|
1399 |
+
kpss = kpss[score_mask]
|
1400 |
+
|
1401 |
+
bboxes /= det_scale
|
1402 |
+
kpss /= det_scale
|
1403 |
+
pre_det = np.hstack((bboxes, scores[:, None]))
|
1404 |
+
|
1405 |
+
dets = pre_det
|
1406 |
+
thresh = 0.4
|
1407 |
+
x1 = dets[:, 0]
|
1408 |
+
y1 = dets[:, 1]
|
1409 |
+
x2 = dets[:, 2]
|
1410 |
+
y2 = dets[:, 3]
|
1411 |
+
scoresb = dets[:, -1]
|
1412 |
+
|
1413 |
+
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
|
1414 |
+
order = scoresb.argsort()[::-1]
|
1415 |
+
|
1416 |
+
keep = []
|
1417 |
+
while order.size > 0:
|
1418 |
+
i = order[0]
|
1419 |
+
keep.append(i)
|
1420 |
+
xx1 = np.maximum(x1[i], x1[order[1:]])
|
1421 |
+
yy1 = np.maximum(y1[i], y1[order[1:]])
|
1422 |
+
xx2 = np.minimum(x2[i], x2[order[1:]])
|
1423 |
+
yy2 = np.minimum(y2[i], y2[order[1:]])
|
1424 |
+
|
1425 |
+
w = np.maximum(0.0, xx2 - xx1 + 1)
|
1426 |
+
h = np.maximum(0.0, yy2 - yy1 + 1)
|
1427 |
+
inter = w * h
|
1428 |
+
ovr = inter / (areas[i] + areas[order[1:]] - inter)
|
1429 |
+
|
1430 |
+
inds = np.where(ovr <= thresh)[0]
|
1431 |
+
order = order[inds + 1]
|
1432 |
+
|
1433 |
+
kpss = kpss[keep, :]
|
1434 |
+
bboxes = pre_det[keep, :]
|
1435 |
+
score_values = bboxes[:, 4]
|
1436 |
+
|
1437 |
+
bbox_list = []
|
1438 |
+
kps_list = []
|
1439 |
+
for i in range(bboxes.shape[0]):
|
1440 |
+
if i==max_num:
|
1441 |
+
break
|
1442 |
+
box = np.array((bboxes[i][0], bboxes[i][1], bboxes[i][2], bboxes[i][3]))
|
1443 |
+
bbox_list.append(box)
|
1444 |
+
|
1445 |
+
if kpss is not None:
|
1446 |
+
kps = kpss[i].reshape(-1, 2)
|
1447 |
+
if use_landmark_detection and len(kps) > 0:
|
1448 |
+
landmark_kpss, landmark_scores = self.run_detect_landmark(img_landmark, box, kps, landmark_detect_mode, landmark_score, from_points)
|
1449 |
+
if len(landmark_kpss) > 0:
|
1450 |
+
if len(landmark_scores) > 0:
|
1451 |
+
#print(np.mean(landmark_scores))
|
1452 |
+
#print(np.mean(score_values[i]))
|
1453 |
+
if np.mean(landmark_scores) > np.mean(score_values[i]):
|
1454 |
+
kps = landmark_kpss
|
1455 |
+
else:
|
1456 |
+
kps = landmark_kpss
|
1457 |
+
|
1458 |
+
kps_list.append(kps)
|
1459 |
+
|
1460 |
+
return np.array(bbox_list), np.array(kps_list)
|
1461 |
+
|
1462 |
+
def detect_face_landmark_5(self, img, bbox, det_kpss, from_points=False):
|
1463 |
+
if from_points == False:
|
1464 |
+
w, h = (bbox[2] - bbox[0]), (bbox[3] - bbox[1])
|
1465 |
+
center = (bbox[2] + bbox[0]) / 2, (bbox[3] + bbox[1]) / 2
|
1466 |
+
rotate = 0
|
1467 |
+
_scale = 512.0 / (max(w, h)*1.5)
|
1468 |
+
image, M = faceutil.transform(img, center, 512, _scale, rotate)
|
1469 |
+
else:
|
1470 |
+
image, M = faceutil.warp_face_by_face_landmark_5(img, det_kpss, 512, normalized=True)
|
1471 |
+
|
1472 |
+
image = image.permute(1,2,0)
|
1473 |
+
|
1474 |
+
mean = torch.tensor([104, 117, 123], dtype=torch.float32, device='cuda')
|
1475 |
+
image = torch.sub(image, mean)
|
1476 |
+
|
1477 |
+
image = image.permute(2,0,1)
|
1478 |
+
image = torch.reshape(image, (1, 3, 512, 512))
|
1479 |
+
|
1480 |
+
height, width = (512, 512)
|
1481 |
+
tmp = [width, height, width, height, width, height, width, height, width, height]
|
1482 |
+
scale1 = torch.tensor(tmp, dtype=torch.float32, device='cuda')
|
1483 |
+
|
1484 |
+
conf = torch.empty((1,10752,2), dtype=torch.float32, device='cuda').contiguous()
|
1485 |
+
landmarks = torch.empty((1,10752,10), dtype=torch.float32, device='cuda').contiguous()
|
1486 |
+
|
1487 |
+
io_binding = self.resnet50_model.io_binding()
|
1488 |
+
io_binding.bind_input(name='input', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,3,512,512), buffer_ptr=image.data_ptr())
|
1489 |
+
io_binding.bind_output(name='conf', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,10752,2), buffer_ptr=conf.data_ptr())
|
1490 |
+
io_binding.bind_output(name='landmarks', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,10752,10), buffer_ptr=landmarks.data_ptr())
|
1491 |
+
|
1492 |
+
torch.cuda.synchronize('cuda')
|
1493 |
+
self.resnet50_model.run_with_iobinding(io_binding)
|
1494 |
+
|
1495 |
+
scores = torch.squeeze(conf)[:, 1]
|
1496 |
+
priors = torch.tensor(self.anchors).view(-1, 4)
|
1497 |
+
priors = priors.to('cuda')
|
1498 |
+
|
1499 |
+
pre = torch.squeeze(landmarks, 0)
|
1500 |
+
|
1501 |
+
tmp = (priors[:, :2] + pre[:, :2] * 0.1 * priors[:, 2:], priors[:, :2] + pre[:, 2:4] * 0.1 * priors[:, 2:], priors[:, :2] + pre[:, 4:6] * 0.1 * priors[:, 2:], priors[:, :2] + pre[:, 6:8] * 0.1 * priors[:, 2:], priors[:, :2] + pre[:, 8:10] * 0.1 * priors[:, 2:])
|
1502 |
+
landmarks = torch.cat(tmp, dim=1)
|
1503 |
+
landmarks = torch.mul(landmarks, scale1)
|
1504 |
+
|
1505 |
+
landmarks = landmarks.cpu().numpy()
|
1506 |
+
|
1507 |
+
# ignore low scores
|
1508 |
+
score=.1
|
1509 |
+
inds = torch.where(scores>score)[0]
|
1510 |
+
inds = inds.cpu().numpy()
|
1511 |
+
scores = scores.cpu().numpy()
|
1512 |
+
|
1513 |
+
landmarks, scores = landmarks[inds], scores[inds]
|
1514 |
+
|
1515 |
+
# sort
|
1516 |
+
order = scores.argsort()[::-1]
|
1517 |
+
|
1518 |
+
if len(order) > 0:
|
1519 |
+
landmarks = landmarks[order][0]
|
1520 |
+
scores = scores[order][0]
|
1521 |
+
|
1522 |
+
landmarks = np.array([[landmarks[i], landmarks[i + 1]] for i in range(0,10,2)])
|
1523 |
+
|
1524 |
+
IM = faceutil.invertAffineTransform(M)
|
1525 |
+
landmarks = faceutil.trans_points2d(landmarks, IM)
|
1526 |
+
scores = np.array([scores])
|
1527 |
+
|
1528 |
+
#faceutil.test_bbox_landmarks(img, bbox, landmarks)
|
1529 |
+
#print(scores)
|
1530 |
+
|
1531 |
+
return landmarks, scores
|
1532 |
+
|
1533 |
+
return [], []
|
1534 |
+
|
1535 |
+
def detect_face_landmark_68(self, img, bbox, det_kpss, convert68_5=True, from_points=False):
|
1536 |
+
if from_points == False:
|
1537 |
+
crop_image, affine_matrix = faceutil.warp_face_by_bounding_box_for_landmark_68(img, bbox, (256, 256))
|
1538 |
+
else:
|
1539 |
+
crop_image, affine_matrix = faceutil.warp_face_by_face_landmark_5(img, det_kpss, 256, normalized=True)
|
1540 |
+
'''
|
1541 |
+
cv2.imshow('image', crop_image.permute(1, 2, 0).to('cpu').numpy())
|
1542 |
+
cv2.waitKey(0)
|
1543 |
+
cv2.destroyAllWindows()
|
1544 |
+
'''
|
1545 |
+
crop_image = crop_image.to(dtype=torch.float32)
|
1546 |
+
crop_image = torch.div(crop_image, 255.0)
|
1547 |
+
crop_image = torch.unsqueeze(crop_image, 0).contiguous()
|
1548 |
+
|
1549 |
+
io_binding = self.face_landmark_68_model.io_binding()
|
1550 |
+
io_binding.bind_input(name='input', device_type='cuda', device_id=0, element_type=np.float32, shape=crop_image.size(), buffer_ptr=crop_image.data_ptr())
|
1551 |
+
|
1552 |
+
io_binding.bind_output('landmarks_xyscore', 'cuda')
|
1553 |
+
io_binding.bind_output('heatmaps', 'cuda')
|
1554 |
+
|
1555 |
+
# Sync and run model
|
1556 |
+
syncvec = self.syncvec.cpu()
|
1557 |
+
self.face_landmark_68_model.run_with_iobinding(io_binding)
|
1558 |
+
net_outs = io_binding.copy_outputs_to_cpu()
|
1559 |
+
face_landmark_68 = net_outs[0]
|
1560 |
+
face_heatmap = net_outs[1]
|
1561 |
+
|
1562 |
+
face_landmark_68 = face_landmark_68[:, :, :2][0] / 64.0
|
1563 |
+
face_landmark_68 = face_landmark_68.reshape(1, -1, 2) * 256.0
|
1564 |
+
face_landmark_68 = cv2.transform(face_landmark_68, cv2.invertAffineTransform(affine_matrix))
|
1565 |
+
|
1566 |
+
face_landmark_68 = face_landmark_68.reshape(-1, 2)
|
1567 |
+
face_landmark_68_score = np.amax(face_heatmap, axis = (2, 3))
|
1568 |
+
face_landmark_68_score = face_landmark_68_score.reshape(-1, 1)
|
1569 |
+
|
1570 |
+
if convert68_5:
|
1571 |
+
face_landmark_68, face_landmark_68_score = faceutil.convert_face_landmark_68_to_5(face_landmark_68, face_landmark_68_score)
|
1572 |
+
|
1573 |
+
#faceutil.test_bbox_landmarks(img, bbox, face_landmark_68)
|
1574 |
+
|
1575 |
+
return face_landmark_68, face_landmark_68_score
|
1576 |
+
|
1577 |
+
def detect_face_landmark_3d68(self, img, bbox, det_kpss, convert68_5=True, from_points=False):
|
1578 |
+
if from_points == False:
|
1579 |
+
w, h = (bbox[2] - bbox[0]), (bbox[3] - bbox[1])
|
1580 |
+
center = (bbox[2] + bbox[0]) / 2, (bbox[3] + bbox[1]) / 2
|
1581 |
+
rotate = 0
|
1582 |
+
_scale = 192 / (max(w, h)*1.5)
|
1583 |
+
#print('param:', img.size(), bbox, center, (192, 192), _scale, rotate)
|
1584 |
+
aimg, M = faceutil.transform(img, center, 192, _scale, rotate)
|
1585 |
+
else:
|
1586 |
+
aimg, M = faceutil.warp_face_by_face_landmark_5(img, det_kpss, image_size=192, normalized=True)
|
1587 |
+
'''
|
1588 |
+
cv2.imshow('image', aimg.permute(1.2.0).to('cpu').numpy())
|
1589 |
+
cv2.waitKey(0)
|
1590 |
+
cv2.destroyAllWindows()
|
1591 |
+
'''
|
1592 |
+
aimg = torch.unsqueeze(aimg, 0).contiguous()
|
1593 |
+
aimg = aimg.to(dtype=torch.float32)
|
1594 |
+
aimg = self.normalize(aimg)
|
1595 |
+
io_binding = self.face_landmark_3d68_model.io_binding()
|
1596 |
+
io_binding.bind_input(name='data', device_type='cuda', device_id=0, element_type=np.float32, shape=aimg.size(), buffer_ptr=aimg.data_ptr())
|
1597 |
+
|
1598 |
+
io_binding.bind_output('fc1', 'cuda')
|
1599 |
+
|
1600 |
+
# Sync and run model
|
1601 |
+
syncvec = self.syncvec.cpu()
|
1602 |
+
self.face_landmark_3d68_model.run_with_iobinding(io_binding)
|
1603 |
+
pred = io_binding.copy_outputs_to_cpu()[0][0]
|
1604 |
+
|
1605 |
+
if pred.shape[0] >= 3000:
|
1606 |
+
pred = pred.reshape((-1, 3))
|
1607 |
+
else:
|
1608 |
+
pred = pred.reshape((-1, 2))
|
1609 |
+
if 68 < pred.shape[0]:
|
1610 |
+
pred = pred[68*-1:,:]
|
1611 |
+
pred[:, 0:2] += 1
|
1612 |
+
pred[:, 0:2] *= (192 // 2)
|
1613 |
+
if pred.shape[1] == 3:
|
1614 |
+
pred[:, 2] *= (192 // 2)
|
1615 |
+
|
1616 |
+
#IM = cv2.invertAffineTransform(M)
|
1617 |
+
IM = faceutil.invertAffineTransform(M)
|
1618 |
+
pred = faceutil.trans_points3d(pred, IM)
|
1619 |
+
|
1620 |
+
# at moment we don't use 3d points
|
1621 |
+
'''
|
1622 |
+
P = faceutil.estimate_affine_matrix_3d23d(self.mean_lmk, pred)
|
1623 |
+
s, R, t = faceutil.P2sRt(P)
|
1624 |
+
rx, ry, rz = faceutil.matrix2angle(R)
|
1625 |
+
pose = np.array( [rx, ry, rz], dtype=np.float32 ) #pitch, yaw, roll
|
1626 |
+
'''
|
1627 |
+
|
1628 |
+
# convert from 3d68 to 2d68 keypoints
|
1629 |
+
landmark2d68 = np.array(pred[:, [0, 1]])
|
1630 |
+
|
1631 |
+
if convert68_5:
|
1632 |
+
# convert from 68 to 5 keypoints
|
1633 |
+
landmark2d68, _ = faceutil.convert_face_landmark_68_to_5(landmark2d68, [])
|
1634 |
+
|
1635 |
+
#faceutil.test_bbox_landmarks(img, bbox, landmark2d68)
|
1636 |
+
|
1637 |
+
return landmark2d68, []
|
1638 |
+
|
1639 |
+
def detect_face_landmark_98(self, img, bbox, det_kpss, convert98_5=True, from_points=False):
|
1640 |
+
if from_points == False:
|
1641 |
+
crop_image, detail = faceutil.warp_face_by_bounding_box_for_landmark_98(img, bbox, (256, 256))
|
1642 |
+
else:
|
1643 |
+
crop_image, M = faceutil.warp_face_by_face_landmark_5(img, det_kpss, image_size=256, normalized=True)
|
1644 |
+
#crop_image2 = crop_image.clone()
|
1645 |
+
h, w = (crop_image.size(dim=1), crop_image.size(dim=2))
|
1646 |
+
'''
|
1647 |
+
cv2.imshow('image', crop_image.permute(1, 2, 0).to('cpu').numpy())
|
1648 |
+
cv2.waitKey(0)
|
1649 |
+
cv2.destroyAllWindows()
|
1650 |
+
'''
|
1651 |
+
landmark = []
|
1652 |
+
landmark_score = []
|
1653 |
+
if crop_image is not None:
|
1654 |
+
crop_image = crop_image.to(dtype=torch.float32)
|
1655 |
+
crop_image = torch.div(crop_image, 255.0)
|
1656 |
+
crop_image = torch.unsqueeze(crop_image, 0).contiguous()
|
1657 |
+
|
1658 |
+
io_binding = self.face_landmark_98_model.io_binding()
|
1659 |
+
io_binding.bind_input(name='input', device_type='cuda', device_id=0, element_type=np.float32, shape=crop_image.size(), buffer_ptr=crop_image.data_ptr())
|
1660 |
+
|
1661 |
+
io_binding.bind_output('landmarks_xyscore', 'cuda')
|
1662 |
+
|
1663 |
+
# Sync and run model
|
1664 |
+
syncvec = self.syncvec.cpu()
|
1665 |
+
self.face_landmark_98_model.run_with_iobinding(io_binding)
|
1666 |
+
landmarks_xyscore = io_binding.copy_outputs_to_cpu()[0]
|
1667 |
+
|
1668 |
+
if len(landmarks_xyscore) > 0:
|
1669 |
+
for one_face_landmarks in landmarks_xyscore:
|
1670 |
+
landmark_score = one_face_landmarks[:, [2]].reshape(-1)
|
1671 |
+
landmark = one_face_landmarks[:, [0, 1]].reshape(-1,2)
|
1672 |
+
|
1673 |
+
##recorver, and grouped as [98,2]
|
1674 |
+
if from_points == False:
|
1675 |
+
landmark[:, 0] = landmark[:, 0] * detail[1] + detail[3] - detail[4]
|
1676 |
+
landmark[:, 1] = landmark[:, 1] * detail[0] + detail[2] - detail[4]
|
1677 |
+
else:
|
1678 |
+
landmark[:, 0] = landmark[:, 0] * w
|
1679 |
+
landmark[:, 1] = landmark[:, 1] * h
|
1680 |
+
#lmk = landmark.copy()
|
1681 |
+
#lmk_score = landmark_score.copy()
|
1682 |
+
|
1683 |
+
#IM = cv2.invertAffineTransform(M)
|
1684 |
+
IM = faceutil.invertAffineTransform(M)
|
1685 |
+
landmark = faceutil.trans_points2d(landmark, IM)
|
1686 |
+
|
1687 |
+
if convert98_5:
|
1688 |
+
landmark, landmark_score = faceutil.convert_face_landmark_98_to_5(landmark, landmark_score)
|
1689 |
+
#lmk, lmk_score = faceutil.convert_face_landmark_98_to_5(lmk, lmk_score)
|
1690 |
+
|
1691 |
+
#faceutil.test_bbox_landmarks(crop_image2, [], lmk)
|
1692 |
+
#faceutil.test_bbox_landmarks(img, bbox, landmark)
|
1693 |
+
#faceutil.test_bbox_landmarks(img, bbox, det_kpss)
|
1694 |
+
|
1695 |
+
return landmark, landmark_score
|
1696 |
+
|
1697 |
+
def detect_face_landmark_106(self, img, bbox, det_kpss, convert106_5=True, from_points=False):
|
1698 |
+
if from_points == False:
|
1699 |
+
w, h = (bbox[2] - bbox[0]), (bbox[3] - bbox[1])
|
1700 |
+
center = (bbox[2] + bbox[0]) / 2, (bbox[3] + bbox[1]) / 2
|
1701 |
+
rotate = 0
|
1702 |
+
_scale = 192 / (max(w, h)*1.5)
|
1703 |
+
#print('param:', img.size(), bbox, center, (192, 192), _scale, rotate)
|
1704 |
+
aimg, M = faceutil.transform(img, center, 192, _scale, rotate)
|
1705 |
+
else:
|
1706 |
+
aimg, M = faceutil.warp_face_by_face_landmark_5(img, det_kpss, image_size=192, normalized=True)
|
1707 |
+
'''
|
1708 |
+
cv2.imshow('image', aimg.permute(1.2.0).to('cpu').numpy())
|
1709 |
+
cv2.waitKey(0)
|
1710 |
+
cv2.destroyAllWindows()
|
1711 |
+
'''
|
1712 |
+
aimg = torch.unsqueeze(aimg, 0).contiguous()
|
1713 |
+
aimg = aimg.to(dtype=torch.float32)
|
1714 |
+
aimg = self.normalize(aimg)
|
1715 |
+
io_binding = self.face_landmark_106_model.io_binding()
|
1716 |
+
io_binding.bind_input(name='data', device_type='cuda', device_id=0, element_type=np.float32, shape=aimg.size(), buffer_ptr=aimg.data_ptr())
|
1717 |
+
|
1718 |
+
io_binding.bind_output('fc1', 'cuda')
|
1719 |
+
|
1720 |
+
# Sync and run model
|
1721 |
+
syncvec = self.syncvec.cpu()
|
1722 |
+
self.face_landmark_106_model.run_with_iobinding(io_binding)
|
1723 |
+
pred = io_binding.copy_outputs_to_cpu()[0][0]
|
1724 |
+
|
1725 |
+
if pred.shape[0] >= 3000:
|
1726 |
+
pred = pred.reshape((-1, 3))
|
1727 |
+
else:
|
1728 |
+
pred = pred.reshape((-1, 2))
|
1729 |
+
|
1730 |
+
if 106 < pred.shape[0]:
|
1731 |
+
pred = pred[106*-1:,:]
|
1732 |
+
|
1733 |
+
pred[:, 0:2] += 1
|
1734 |
+
pred[:, 0:2] *= (192 // 2)
|
1735 |
+
if pred.shape[1] == 3:
|
1736 |
+
pred[:, 2] *= (192 // 2)
|
1737 |
+
|
1738 |
+
#IM = cv2.invertAffineTransform(M)
|
1739 |
+
IM = faceutil.invertAffineTransform(M)
|
1740 |
+
pred = faceutil.trans_points(pred, IM)
|
1741 |
+
|
1742 |
+
if pred is not None:
|
1743 |
+
if convert106_5:
|
1744 |
+
# convert from 106 to 5 keypoints
|
1745 |
+
pred = faceutil.convert_face_landmark_106_to_5(pred)
|
1746 |
+
|
1747 |
+
#faceutil.test_bbox_landmarks(img, bbox, pred)
|
1748 |
+
|
1749 |
+
return pred, []
|
1750 |
+
|
1751 |
+
def detect_face_landmark_478(self, img, bbox, det_kpss, convert478_5=True, from_points=False):
|
1752 |
+
if from_points == False:
|
1753 |
+
w, h = (bbox[2] - bbox[0]), (bbox[3] - bbox[1])
|
1754 |
+
center = (bbox[2] + bbox[0]) / 2, (bbox[3] + bbox[1]) / 2
|
1755 |
+
rotate = 0
|
1756 |
+
_scale = 256.0 / (max(w, h)*1.5)
|
1757 |
+
#print('param:', img.size(), bbox, center, (192, 192), _scale, rotate)
|
1758 |
+
aimg, M = faceutil.transform(img, center, 256, _scale, rotate)
|
1759 |
+
else:
|
1760 |
+
aimg, M = faceutil.warp_face_by_face_landmark_5(img, det_kpss, 256, normalized=False)
|
1761 |
+
#aimg2 = aimg.clone()
|
1762 |
+
'''
|
1763 |
+
cv2.imshow('image', aimg.permute(1,2,0).to('cpu').numpy())
|
1764 |
+
cv2.waitKey(0)
|
1765 |
+
cv2.destroyAllWindows()
|
1766 |
+
'''
|
1767 |
+
aimg = torch.unsqueeze(aimg, 0).contiguous()
|
1768 |
+
aimg = aimg.to(dtype=torch.float32)
|
1769 |
+
aimg = torch.div(aimg, 255.0)
|
1770 |
+
io_binding = self.face_landmark_478_model.io_binding()
|
1771 |
+
io_binding.bind_input(name='input_12', device_type='cuda', device_id=0, element_type=np.float32, shape=aimg.size(), buffer_ptr=aimg.data_ptr())
|
1772 |
+
|
1773 |
+
io_binding.bind_output('Identity', 'cuda')
|
1774 |
+
io_binding.bind_output('Identity_1', 'cuda')
|
1775 |
+
io_binding.bind_output('Identity_2', 'cuda')
|
1776 |
+
|
1777 |
+
# Sync and run model
|
1778 |
+
syncvec = self.syncvec.cpu()
|
1779 |
+
self.face_landmark_478_model.run_with_iobinding(io_binding)
|
1780 |
+
landmarks, faceflag, blendshapes = io_binding.copy_outputs_to_cpu()
|
1781 |
+
landmarks = landmarks.reshape( (1,478,3))
|
1782 |
+
|
1783 |
+
landmark = []
|
1784 |
+
landmark_score = []
|
1785 |
+
if len(landmarks) > 0:
|
1786 |
+
for one_face_landmarks in landmarks:
|
1787 |
+
#lmk = one_face_landmarks.copy()
|
1788 |
+
landmark = one_face_landmarks
|
1789 |
+
#IM = cv2.invertAffineTransform(M)
|
1790 |
+
IM = faceutil.invertAffineTransform(M)
|
1791 |
+
landmark = faceutil.trans_points3d(landmark, IM)
|
1792 |
+
'''
|
1793 |
+
P = faceutil.estimate_affine_matrix_3d23d(self.mean_lmk, landmark)
|
1794 |
+
s, R, t = faceutil.P2sRt(P)
|
1795 |
+
rx, ry, rz = faceutil.matrix2angle(R)
|
1796 |
+
pose = np.array( [rx, ry, rz], dtype=np.float32 ) #pitch, yaw, roll
|
1797 |
+
'''
|
1798 |
+
landmark = landmark[:, [0, 1]].reshape(-1,2)
|
1799 |
+
#lmk = lmk[:, [0, 1]].reshape(-1,2)
|
1800 |
+
|
1801 |
+
#get scores
|
1802 |
+
landmark_for_score = landmark[self.LandmarksSubsetIdxs]
|
1803 |
+
landmark_for_score = landmark_for_score[:, :2]
|
1804 |
+
landmark_for_score = np.expand_dims(landmark_for_score, axis=0)
|
1805 |
+
landmark_for_score = landmark_for_score.astype(np.float32)
|
1806 |
+
landmark_for_score = torch.from_numpy(landmark_for_score).to('cuda')
|
1807 |
+
|
1808 |
+
io_binding_bs = self.face_blendshapes_model.io_binding()
|
1809 |
+
io_binding_bs.bind_input(name='input_points', device_type='cuda', device_id=0, element_type=np.float32, shape=tuple(landmark_for_score.shape), buffer_ptr=landmark_for_score.data_ptr())
|
1810 |
+
io_binding_bs.bind_output('output', 'cuda')
|
1811 |
+
|
1812 |
+
# Sync and run model
|
1813 |
+
syncvec = self.syncvec.cpu()
|
1814 |
+
self.face_blendshapes_model.run_with_iobinding(io_binding_bs)
|
1815 |
+
landmark_score = io_binding_bs.copy_outputs_to_cpu()[0]
|
1816 |
+
|
1817 |
+
if convert478_5:
|
1818 |
+
# convert from 478 to 5 keypoints
|
1819 |
+
landmark = faceutil.convert_face_landmark_478_to_5(landmark)
|
1820 |
+
#lmk = faceutil.convert_face_landmark_478_to_5(lmk)
|
1821 |
+
|
1822 |
+
#faceutil.test_bbox_landmarks(aimg2, [], lmk)
|
1823 |
+
#faceutil.test_bbox_landmarks(img, bbox, landmark)
|
1824 |
+
#faceutil.test_bbox_landmarks(img, bbox, det_kpss)
|
1825 |
+
|
1826 |
+
#return landmark, landmark_score
|
1827 |
+
return landmark, []
|
1828 |
+
|
1829 |
+
def recognize(self, img, face_kps):
|
1830 |
+
'''
|
1831 |
+
# Find transform
|
1832 |
+
dst = self.arcface_dst.copy()
|
1833 |
+
dst[:, 0] += 8.0
|
1834 |
+
|
1835 |
+
tform = trans.SimilarityTransform()
|
1836 |
+
tform.estimate(face_kps, dst)
|
1837 |
+
|
1838 |
+
# Transform
|
1839 |
+
img = v2.functional.affine(img, tform.rotation*57.2958, (tform.translation[0], tform.translation[1]) , tform.scale, 0, center = (0,0) )
|
1840 |
+
img = v2.functional.crop(img, 0,0, 128, 128)
|
1841 |
+
img = v2.Resize((112, 112), interpolation=v2.InterpolationMode.BILINEAR, antialias=False)(img)
|
1842 |
+
'''
|
1843 |
+
# Find transform
|
1844 |
+
tform = trans.SimilarityTransform()
|
1845 |
+
tform.estimate(face_kps, self.arcface_dst)
|
1846 |
+
|
1847 |
+
# Transform
|
1848 |
+
img = v2.functional.affine(img, tform.rotation*57.2958, (tform.translation[0], tform.translation[1]) , tform.scale, 0, center = (0,0) )
|
1849 |
+
img = v2.functional.crop(img, 0,0, 112, 112)
|
1850 |
+
|
1851 |
+
cropped_image = img
|
1852 |
+
# Switch to BGR and normalize
|
1853 |
+
img = img.permute(1,2,0) #112,112,3
|
1854 |
+
img = img[:, :, [2,1,0]]
|
1855 |
+
img = torch.sub(img, 127.5)
|
1856 |
+
img = torch.div(img, 127.5)
|
1857 |
+
img = img.permute(2, 0, 1) #3,112,112
|
1858 |
+
|
1859 |
+
# Prepare data and find model parameters
|
1860 |
+
img = torch.unsqueeze(img, 0).contiguous()
|
1861 |
+
input_name = self.recognition_model.get_inputs()[0].name
|
1862 |
+
|
1863 |
+
outputs = self.recognition_model.get_outputs()
|
1864 |
+
output_names = []
|
1865 |
+
for o in outputs:
|
1866 |
+
output_names.append(o.name)
|
1867 |
+
|
1868 |
+
io_binding = self.recognition_model.io_binding()
|
1869 |
+
io_binding.bind_input(name=input_name, device_type='cuda', device_id=0, element_type=np.float32, shape=img.size(), buffer_ptr=img.data_ptr())
|
1870 |
+
|
1871 |
+
for i in range(len(output_names)):
|
1872 |
+
io_binding.bind_output(output_names[i], 'cuda')
|
1873 |
+
|
1874 |
+
# Sync and run model
|
1875 |
+
self.syncvec.cpu()
|
1876 |
+
self.recognition_model.run_with_iobinding(io_binding)
|
1877 |
+
|
1878 |
+
# Return embedding
|
1879 |
+
return np.array(io_binding.copy_outputs_to_cpu()).flatten(), cropped_image
|
1880 |
+
|
1881 |
+
def resnet50(self, image, score=.5):
|
1882 |
+
if not self.resnet50_model:
|
1883 |
+
self.resnet50_model = onnxruntime.InferenceSession("./models/res50.onnx", providers=self.providers)
|
1884 |
+
|
1885 |
+
feature_maps = [[64, 64], [32, 32], [16, 16]]
|
1886 |
+
min_sizes = [[16, 32], [64, 128], [256, 512]]
|
1887 |
+
steps = [8, 16, 32]
|
1888 |
+
image_size = 512
|
1889 |
+
|
1890 |
+
for k, f in enumerate(feature_maps):
|
1891 |
+
min_size_array = min_sizes[k]
|
1892 |
+
for i, j in product(range(f[0]), range(f[1])):
|
1893 |
+
for min_size in min_size_array:
|
1894 |
+
s_kx = min_size / image_size
|
1895 |
+
s_ky = min_size / image_size
|
1896 |
+
dense_cx = [x * steps[k] / image_size for x in [j + 0.5]]
|
1897 |
+
dense_cy = [y * steps[k] / image_size for y in [i + 0.5]]
|
1898 |
+
for cy, cx in product(dense_cy, dense_cx):
|
1899 |
+
self.anchors += [cx, cy, s_kx, s_ky]
|
1900 |
+
|
1901 |
+
# image = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)
|
1902 |
+
image = image.permute(1,2,0)
|
1903 |
+
|
1904 |
+
# image = image - [104, 117, 123]
|
1905 |
+
mean = torch.tensor([104, 117, 123], dtype=torch.float32, device='cuda')
|
1906 |
+
image = torch.sub(image, mean)
|
1907 |
+
|
1908 |
+
# image = image.transpose(2, 0, 1)
|
1909 |
+
# image = np.float32(image[np.newaxis,:,:,:])
|
1910 |
+
image = image.permute(2,0,1)
|
1911 |
+
image = torch.reshape(image, (1, 3, 512, 512))
|
1912 |
+
|
1913 |
+
height, width = (512, 512)
|
1914 |
+
tmp = [width, height, width, height, width, height, width, height, width, height]
|
1915 |
+
scale1 = torch.tensor(tmp, dtype=torch.float32, device='cuda')
|
1916 |
+
|
1917 |
+
# ort_inputs = {"input": image}
|
1918 |
+
conf = torch.empty((1,10752,2), dtype=torch.float32, device='cuda').contiguous()
|
1919 |
+
landmarks = torch.empty((1,10752,10), dtype=torch.float32, device='cuda').contiguous()
|
1920 |
+
|
1921 |
+
io_binding = self.resnet50_model.io_binding()
|
1922 |
+
io_binding.bind_input(name='input', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,3,512,512), buffer_ptr=image.data_ptr())
|
1923 |
+
io_binding.bind_output(name='conf', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,10752,2), buffer_ptr=conf.data_ptr())
|
1924 |
+
io_binding.bind_output(name='landmarks', device_type='cuda', device_id=0, element_type=np.float32, shape=(1,10752,10), buffer_ptr=landmarks.data_ptr())
|
1925 |
+
|
1926 |
+
# _, conf, landmarks = self.resnet_model.run(None, ort_inputs)
|
1927 |
+
torch.cuda.synchronize('cuda')
|
1928 |
+
self.resnet50_model.run_with_iobinding(io_binding)
|
1929 |
+
|
1930 |
+
# conf = torch.from_numpy(conf)
|
1931 |
+
# scores = conf.squeeze(0).numpy()[:, 1]
|
1932 |
+
scores = torch.squeeze(conf)[:, 1]
|
1933 |
+
|
1934 |
+
# landmarks = torch.from_numpy(landmarks)
|
1935 |
+
# landmarks = landmarks.to('cuda')
|
1936 |
+
|
1937 |
+
priors = torch.tensor(self.anchors).view(-1, 4)
|
1938 |
+
priors = priors.to('cuda')
|
1939 |
+
|
1940 |
+
# pre = landmarks.squeeze(0)
|
1941 |
+
pre = torch.squeeze(landmarks, 0)
|
1942 |
+
|
1943 |
+
tmp = (priors[:, :2] + pre[:, :2] * 0.1 * priors[:, 2:], priors[:, :2] + pre[:, 2:4] * 0.1 * priors[:, 2:], priors[:, :2] + pre[:, 4:6] * 0.1 * priors[:, 2:], priors[:, :2] + pre[:, 6:8] * 0.1 * priors[:, 2:], priors[:, :2] + pre[:, 8:10] * 0.1 * priors[:, 2:])
|
1944 |
+
landmarks = torch.cat(tmp, dim=1)
|
1945 |
+
# landmarks = landmarks * scale1
|
1946 |
+
landmarks = torch.mul(landmarks, scale1)
|
1947 |
+
|
1948 |
+
landmarks = landmarks.cpu().numpy()
|
1949 |
+
|
1950 |
+
# ignore low scores
|
1951 |
+
inds = torch.where(scores>score)[0]
|
1952 |
+
inds = inds.cpu().numpy()
|
1953 |
+
scores = scores.cpu().numpy()
|
1954 |
+
|
1955 |
+
landmarks, scores = landmarks[inds], scores[inds]
|
1956 |
+
|
1957 |
+
# sort
|
1958 |
+
order = scores.argsort()[::-1]
|
1959 |
+
landmarks = landmarks[order][0]
|
1960 |
+
|
1961 |
+
return np.array([[landmarks[i], landmarks[i + 1]] for i in range(0,10,2)])
|
rope/Styles.py
ADDED
@@ -0,0 +1,293 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
bg = 'black'
|
2 |
+
main = '#1A1A1A' #Not as Dark Grey '#1A1A1A'
|
3 |
+
main2 = '#151515' #Dark Grey '#151515'
|
4 |
+
main3 = '#28282E' #Light Grey '#28282E'
|
5 |
+
|
6 |
+
|
7 |
+
|
8 |
+
canvas_frame_label_1 = {
|
9 |
+
'bg': main2,
|
10 |
+
'bd': '0',
|
11 |
+
'relief': 'flat',
|
12 |
+
'highlightthickness': '0'
|
13 |
+
}
|
14 |
+
|
15 |
+
canvas_frame_label_2 = {
|
16 |
+
'bg': main2,
|
17 |
+
'bd': '0',
|
18 |
+
'relief': 'flat',
|
19 |
+
'highlightthickness': '0'
|
20 |
+
}
|
21 |
+
|
22 |
+
canvas_frame_label_3 = {
|
23 |
+
'bg': main,
|
24 |
+
'bd': '0',
|
25 |
+
'relief': 'flat',
|
26 |
+
'highlightthickness': '0'
|
27 |
+
}
|
28 |
+
|
29 |
+
info_label = {
|
30 |
+
'bg': main2,
|
31 |
+
'fg': '#BCBCBC',
|
32 |
+
'bd': '5',
|
33 |
+
'relief': 'flat',
|
34 |
+
'highlightthickness': '0',
|
35 |
+
'font': ("Segoe UI", 9),
|
36 |
+
'anchor': 'nw',
|
37 |
+
'justify': 'left',
|
38 |
+
}
|
39 |
+
|
40 |
+
text_1 = {
|
41 |
+
'bg': main2,
|
42 |
+
'fg': 'white',
|
43 |
+
'activebackground': main2,
|
44 |
+
'activeforeground': 'white',
|
45 |
+
'relief': 'flat',
|
46 |
+
'border': '0',
|
47 |
+
'font': ("Segoe UI", 9)
|
48 |
+
}
|
49 |
+
text_2 = {
|
50 |
+
'bg': main2,
|
51 |
+
'fg': '#D0D0D0',
|
52 |
+
'activebackground': main2,
|
53 |
+
'activeforeground': 'white',
|
54 |
+
'relief': 'flat',
|
55 |
+
'border': '0',
|
56 |
+
'font': ("Segoe UI", 9)
|
57 |
+
}
|
58 |
+
text_3 = {
|
59 |
+
'bg': main,
|
60 |
+
'fg': '#979797',
|
61 |
+
'activebackground': main,
|
62 |
+
'activeforeground': 'white',
|
63 |
+
'relief': 'flat',
|
64 |
+
'border': '0',
|
65 |
+
'font': ("Segoe UI", 9)
|
66 |
+
}
|
67 |
+
|
68 |
+
|
69 |
+
|
70 |
+
option_slider_style = {
|
71 |
+
'bg': main,
|
72 |
+
'activebackground': main,
|
73 |
+
'highlightcolor': 'white',
|
74 |
+
'highlightthickness': '0',
|
75 |
+
'relief': 'flat',
|
76 |
+
'sliderrelief': 'flat',
|
77 |
+
'border': '0',
|
78 |
+
'width': '3',
|
79 |
+
'troughcolor': '#1F1F1F',
|
80 |
+
}
|
81 |
+
|
82 |
+
|
83 |
+
entry_3 = {
|
84 |
+
'bg': '#1F1F1F',
|
85 |
+
'fg': '#FFFFFF',
|
86 |
+
'relief': 'flat',
|
87 |
+
'border': '0',
|
88 |
+
'width': '5',
|
89 |
+
'justify': 'c',
|
90 |
+
'font': ("Segoe UI", 9),
|
91 |
+
'highlightthickness': '1',
|
92 |
+
'highlightbackground': '#17181A',
|
93 |
+
}
|
94 |
+
|
95 |
+
entry_2 = {
|
96 |
+
'bg': '#1F1F1F',
|
97 |
+
'fg': '#FFFFFF',
|
98 |
+
'relief': 'flat',
|
99 |
+
'border': '0',
|
100 |
+
'highlightthickness': '1',
|
101 |
+
'highlightbackground': '#17181A',
|
102 |
+
'width': '5',
|
103 |
+
'justify': 'l',
|
104 |
+
'font': ("Segoe UI", 9)
|
105 |
+
}
|
106 |
+
|
107 |
+
text_selection_off_3 = {
|
108 |
+
'bg': main,
|
109 |
+
'fg': '#7A7A7A',
|
110 |
+
'activebackground': main,
|
111 |
+
'activeforeground': 'white',
|
112 |
+
'relief': 'flat',
|
113 |
+
'border': '0',
|
114 |
+
'font': ("Segoe UI", 10)
|
115 |
+
}
|
116 |
+
text_selection_on_3 = {
|
117 |
+
'bg': main,
|
118 |
+
'fg': '#FFFFFF',
|
119 |
+
'activebackground': main,
|
120 |
+
'activeforeground': 'white',
|
121 |
+
'relief': 'flat',
|
122 |
+
'border': '0',
|
123 |
+
'font': ("Segoe UI", 10)
|
124 |
+
}
|
125 |
+
text_selection_off_2 = {
|
126 |
+
'bg': main2,
|
127 |
+
'fg': '#7A7A7A',
|
128 |
+
'activebackground': main2,
|
129 |
+
'activeforeground': 'white',
|
130 |
+
'relief': 'flat',
|
131 |
+
'border': '0',
|
132 |
+
'font': ("Segoe UI", 10)
|
133 |
+
}
|
134 |
+
text_selection_on_2 = {
|
135 |
+
'bg': main2,
|
136 |
+
'fg': '#FFFFFF',
|
137 |
+
'activebackground': main2,
|
138 |
+
'activeforeground': 'white',
|
139 |
+
'relief': 'flat',
|
140 |
+
'border': '0',
|
141 |
+
'font': ("Segoe UI", 10)
|
142 |
+
}
|
143 |
+
|
144 |
+
|
145 |
+
parameter_switch_3 = {
|
146 |
+
'bg': main,
|
147 |
+
'fg': '#FFFFFF',
|
148 |
+
'activebackground': main,
|
149 |
+
'activeforeground': 'white',
|
150 |
+
'relief': 'flat',
|
151 |
+
'border': '0',
|
152 |
+
'font': ("Segoe UI", 10)
|
153 |
+
}
|
154 |
+
|
155 |
+
|
156 |
+
|
157 |
+
|
158 |
+
canvas_bg = {
|
159 |
+
'bg': bg,
|
160 |
+
'relief': 'flat',
|
161 |
+
'bd': '0',
|
162 |
+
'highlightthickness': '0'
|
163 |
+
}
|
164 |
+
|
165 |
+
icon = {
|
166 |
+
'IconOn': './rope/media/OnState.png',
|
167 |
+
'IconOff': './rope/media/OffState.png',
|
168 |
+
}
|
169 |
+
|
170 |
+
|
171 |
+
frame_style_bg = {
|
172 |
+
'bg': bg,
|
173 |
+
'relief': 'flat',
|
174 |
+
'bd': '0'
|
175 |
+
}
|
176 |
+
|
177 |
+
button_3 = {
|
178 |
+
'bg': main2,
|
179 |
+
'fg': '#FFFFFF',
|
180 |
+
'activebackground': main2,
|
181 |
+
'activeforeground': 'white',
|
182 |
+
'relief': 'flat',
|
183 |
+
'border': '0',
|
184 |
+
'font': ("Segoe UI", 10)
|
185 |
+
}
|
186 |
+
button_2 = {
|
187 |
+
'bg': main2,
|
188 |
+
'fg': '#FFFFFF',
|
189 |
+
'activebackground': main2,
|
190 |
+
'activeforeground': 'white',
|
191 |
+
'relief': 'flat',
|
192 |
+
'border': '0',
|
193 |
+
'font': ("Segoe UI", 10)
|
194 |
+
}
|
195 |
+
button_1 = {
|
196 |
+
'bg': main2,
|
197 |
+
'fg': '#FFFFFF',
|
198 |
+
'activebackground': main2,
|
199 |
+
'activeforeground': 'white',
|
200 |
+
'relief': 'flat',
|
201 |
+
'border': '0',
|
202 |
+
'font': ("Segoe UI", 10)
|
203 |
+
}
|
204 |
+
|
205 |
+
button_inactive = {
|
206 |
+
'bg': main2,
|
207 |
+
'fg': '#FFFFFF',
|
208 |
+
'activebackground': main2,
|
209 |
+
'activeforeground': 'white',
|
210 |
+
'relief': 'flat',
|
211 |
+
'border': '0',
|
212 |
+
'font': ("Segoe UI", 10)
|
213 |
+
}
|
214 |
+
|
215 |
+
button_active = {
|
216 |
+
'bg': main2,
|
217 |
+
'fg': '#FFFFFF',
|
218 |
+
'activebackground': main2,
|
219 |
+
'activeforeground': 'white',
|
220 |
+
'relief': 'flat',
|
221 |
+
'border': '0',
|
222 |
+
'font': ("Segoe UI", 10)
|
223 |
+
}
|
224 |
+
|
225 |
+
|
226 |
+
media_button_off_3= {
|
227 |
+
'bg': main2,
|
228 |
+
'fg': '#7A7A7A',
|
229 |
+
'activebackground': main2,
|
230 |
+
'activeforeground': 'white',
|
231 |
+
'relief': 'flat',
|
232 |
+
'border': '0',
|
233 |
+
'font': ("Segoe UI", 8)
|
234 |
+
}
|
235 |
+
|
236 |
+
media_button_on_3= {
|
237 |
+
'bg': '#4a57ee',
|
238 |
+
'fg': '#FFFFFF',
|
239 |
+
'activebackground': '#4a57ee',
|
240 |
+
'activeforeground': 'white',
|
241 |
+
'relief': 'flat',
|
242 |
+
'border': '0',
|
243 |
+
'font': ("Segoe UI", 8)
|
244 |
+
}
|
245 |
+
|
246 |
+
ui_text_na_2 = {
|
247 |
+
'bg': main,
|
248 |
+
'fg': '#7A7A7A',
|
249 |
+
'activebackground': main,
|
250 |
+
'activeforeground': 'white',
|
251 |
+
'relief': 'flat',
|
252 |
+
'border': '0',
|
253 |
+
'font': ("Segoe UI", 9)
|
254 |
+
}
|
255 |
+
|
256 |
+
timeline_canvas = {
|
257 |
+
'bg': main,
|
258 |
+
'relief': 'flat',
|
259 |
+
'bd': '0',
|
260 |
+
'highlightthickness': '0'
|
261 |
+
}
|
262 |
+
|
263 |
+
donate_1 = {
|
264 |
+
'bg': main,
|
265 |
+
'fg': '#7562ee',
|
266 |
+
'relief': 'flat',
|
267 |
+
'border': '0',
|
268 |
+
'font': ("Segoe UI Semibold", 10),
|
269 |
+
'cursor': "hand2",
|
270 |
+
}
|
271 |
+
|
272 |
+
# Panes
|
273 |
+
# 3:#28282E
|
274 |
+
# 2:#212126
|
275 |
+
# 1:#17181A
|
276 |
+
|
277 |
+
# preview background: #1A1A1A
|
278 |
+
|
279 |
+
# Num Fields, slider bg: #1F1F1F
|
280 |
+
# slider ball: #919191
|
281 |
+
# Borders:#090909
|
282 |
+
# Text
|
283 |
+
# On/off:#FFFFFF
|
284 |
+
# labels: #D0D0D0
|
285 |
+
# notActive: #7A7A7A
|
286 |
+
# active:#FFFFFF
|
287 |
+
|
288 |
+
# highlighted button: #B1B1B2
|
289 |
+
# Button off: #828282
|
290 |
+
|
291 |
+
# on: #FFFFFF
|
292 |
+
# hover: #b1b1b2
|
293 |
+
# off: #828282
|
rope/VideoManager.py
ADDED
@@ -0,0 +1,1242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import cv2
|
3 |
+
import tkinter as tk
|
4 |
+
from PIL import Image, ImageTk
|
5 |
+
import threading
|
6 |
+
import time
|
7 |
+
import numpy as np
|
8 |
+
from skimage import transform as trans
|
9 |
+
import subprocess
|
10 |
+
from math import floor, ceil
|
11 |
+
import bisect
|
12 |
+
import onnxruntime
|
13 |
+
import torchvision
|
14 |
+
from torchvision.transforms.functional import normalize #update to v2
|
15 |
+
import torch
|
16 |
+
from torchvision import transforms
|
17 |
+
torchvision.disable_beta_transforms_warning()
|
18 |
+
from torchvision.transforms import v2
|
19 |
+
torch.set_grad_enabled(False)
|
20 |
+
onnxruntime.set_default_logger_severity(4)
|
21 |
+
|
22 |
+
import inspect #print(inspect.currentframe().f_back.f_code.co_name, 'resize_image')
|
23 |
+
|
24 |
+
device = 'cuda'
|
25 |
+
|
26 |
+
lock=threading.Lock()
|
27 |
+
|
28 |
+
class VideoManager():
|
29 |
+
def __init__(self, models ):
|
30 |
+
self.models = models
|
31 |
+
# Model related
|
32 |
+
self.swapper_model = [] # insightface swapper model
|
33 |
+
# self.faceapp_model = [] # insight faceapp model
|
34 |
+
self.input_names = [] # names of the inswapper.onnx inputs
|
35 |
+
self.input_size = [] # size of the inswapper.onnx inputs
|
36 |
+
|
37 |
+
self.output_names = [] # names of the inswapper.onnx outputs
|
38 |
+
self.arcface_dst = np.array( [[38.2946, 51.6963], [73.5318, 51.5014], [56.0252, 71.7366], [41.5493, 92.3655], [70.7299, 92.2041]], dtype=np.float32)
|
39 |
+
|
40 |
+
self.video_file = []
|
41 |
+
|
42 |
+
self.FFHQ_kps = np.array([[ 192.98138, 239.94708 ], [ 318.90277, 240.1936 ], [ 256.63416, 314.01935 ], [ 201.26117, 371.41043 ], [ 313.08905, 371.15118 ] ])
|
43 |
+
|
44 |
+
|
45 |
+
|
46 |
+
#Video related
|
47 |
+
self.capture = [] # cv2 video
|
48 |
+
self.is_video_loaded = False # flag for video loaded state
|
49 |
+
self.video_frame_total = None # length of currently loaded video
|
50 |
+
self.play = False # flag for the play button toggle
|
51 |
+
self.current_frame = 0 # the current frame of the video
|
52 |
+
self.create_video = False
|
53 |
+
self.output_video = []
|
54 |
+
self.file_name = []
|
55 |
+
|
56 |
+
|
57 |
+
# Play related
|
58 |
+
# self.set_read_threads = [] # Name of threaded function
|
59 |
+
self.frame_timer = 0.0 # used to set the framerate during playing
|
60 |
+
|
61 |
+
# Queues
|
62 |
+
self.action_q = [] # queue for sending to the coordinator
|
63 |
+
self.frame_q = [] # queue for frames that are ready for coordinator
|
64 |
+
|
65 |
+
self.r_frame_q = [] # queue for frames that are requested by the GUI
|
66 |
+
self.read_video_frame_q = []
|
67 |
+
|
68 |
+
# swapping related
|
69 |
+
# self.source_embedding = [] # array with indexed source embeddings
|
70 |
+
|
71 |
+
self.found_faces = [] # array that maps the found faces to source faces
|
72 |
+
|
73 |
+
self.parameters = []
|
74 |
+
|
75 |
+
|
76 |
+
self.target_video = []
|
77 |
+
|
78 |
+
self.fps = 1.0
|
79 |
+
self.temp_file = []
|
80 |
+
|
81 |
+
|
82 |
+
self.clip_session = []
|
83 |
+
|
84 |
+
self.start_time = []
|
85 |
+
self.record = False
|
86 |
+
self.output = []
|
87 |
+
self.image = []
|
88 |
+
|
89 |
+
self.saved_video_path = []
|
90 |
+
self.sp = []
|
91 |
+
self.timer = []
|
92 |
+
self.fps_average = []
|
93 |
+
self.total_thread_time = 0.0
|
94 |
+
|
95 |
+
self.start_play_time = []
|
96 |
+
self.start_play_frame = []
|
97 |
+
|
98 |
+
self.rec_thread = []
|
99 |
+
self.markers = []
|
100 |
+
self.is_image_loaded = False
|
101 |
+
self.stop_marker = -1
|
102 |
+
self.perf_test = False
|
103 |
+
|
104 |
+
self.control = []
|
105 |
+
|
106 |
+
|
107 |
+
|
108 |
+
|
109 |
+
|
110 |
+
self.process_q = {
|
111 |
+
"Thread": [],
|
112 |
+
"FrameNumber": [],
|
113 |
+
"ProcessedFrame": [],
|
114 |
+
"Status": 'clear',
|
115 |
+
"ThreadTime": []
|
116 |
+
}
|
117 |
+
self.process_qs = []
|
118 |
+
self.rec_q = {
|
119 |
+
"Thread": [],
|
120 |
+
"FrameNumber": [],
|
121 |
+
"Status": 'clear'
|
122 |
+
}
|
123 |
+
self.rec_qs = []
|
124 |
+
|
125 |
+
def assign_found_faces(self, found_faces):
|
126 |
+
self.found_faces = found_faces
|
127 |
+
|
128 |
+
|
129 |
+
def load_target_video( self, file ):
|
130 |
+
# If we already have a video loaded, release it
|
131 |
+
if self.capture:
|
132 |
+
self.capture.release()
|
133 |
+
|
134 |
+
# Open file
|
135 |
+
self.video_file = file
|
136 |
+
self.capture = cv2.VideoCapture(file)
|
137 |
+
self.fps = self.capture.get(cv2.CAP_PROP_FPS)
|
138 |
+
|
139 |
+
if not self.capture.isOpened():
|
140 |
+
print("Cannot open file: ", file)
|
141 |
+
|
142 |
+
else:
|
143 |
+
self.target_video = file
|
144 |
+
self.is_video_loaded = True
|
145 |
+
self.is_image_loaded = False
|
146 |
+
self.video_frame_total = int(self.capture.get(cv2.CAP_PROP_FRAME_COUNT))
|
147 |
+
self.play = False
|
148 |
+
self.current_frame = 0
|
149 |
+
self.frame_timer = time.time()
|
150 |
+
self.frame_q = []
|
151 |
+
self.r_frame_q = []
|
152 |
+
self.found_faces = []
|
153 |
+
self.add_action("set_slider_length",self.video_frame_total-1)
|
154 |
+
|
155 |
+
self.capture.set(cv2.CAP_PROP_POS_FRAMES, self.current_frame)
|
156 |
+
success, image = self.capture.read()
|
157 |
+
|
158 |
+
if success:
|
159 |
+
crop = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # RGB
|
160 |
+
temp = [crop, False]
|
161 |
+
self.r_frame_q.append(temp)
|
162 |
+
self.capture.set(cv2.CAP_PROP_POS_FRAMES, self.current_frame)
|
163 |
+
|
164 |
+
def load_target_image(self, file):
|
165 |
+
if self.capture:
|
166 |
+
self.capture.release()
|
167 |
+
self.is_video_loaded = False
|
168 |
+
self.play = False
|
169 |
+
self.frame_q = []
|
170 |
+
self.r_frame_q = []
|
171 |
+
self.found_faces = []
|
172 |
+
self.image = cv2.imread(file) # BGR
|
173 |
+
self.image = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB) # RGB
|
174 |
+
temp = [self.image, False]
|
175 |
+
self.frame_q.append(temp)
|
176 |
+
|
177 |
+
self.is_image_loaded = True
|
178 |
+
|
179 |
+
|
180 |
+
## Action queue
|
181 |
+
def add_action(self, action, param):
|
182 |
+
# print(inspect.currentframe().f_back.f_code.co_name, '->add_action: '+action)
|
183 |
+
temp = [action, param]
|
184 |
+
self.action_q.append(temp)
|
185 |
+
|
186 |
+
def get_action_length(self):
|
187 |
+
return len(self.action_q)
|
188 |
+
|
189 |
+
def get_action(self):
|
190 |
+
action = self.action_q[0]
|
191 |
+
self.action_q.pop(0)
|
192 |
+
return action
|
193 |
+
|
194 |
+
## Queues for the Coordinator
|
195 |
+
def get_frame(self):
|
196 |
+
frame = self.frame_q[0]
|
197 |
+
self.frame_q.pop(0)
|
198 |
+
return frame
|
199 |
+
|
200 |
+
def get_frame_length(self):
|
201 |
+
return len(self.frame_q)
|
202 |
+
|
203 |
+
def get_requested_frame(self):
|
204 |
+
frame = self.r_frame_q[0]
|
205 |
+
self.r_frame_q.pop(0)
|
206 |
+
return frame
|
207 |
+
|
208 |
+
def get_requested_frame_length(self):
|
209 |
+
return len(self.r_frame_q)
|
210 |
+
|
211 |
+
|
212 |
+
def get_requested_video_frame(self, frame, marker=True):
|
213 |
+
temp = []
|
214 |
+
if self.is_video_loaded:
|
215 |
+
|
216 |
+
if self.play == True:
|
217 |
+
self.play_video("stop")
|
218 |
+
self.process_qs = []
|
219 |
+
|
220 |
+
self.current_frame = int(frame)
|
221 |
+
|
222 |
+
self.capture.set(cv2.CAP_PROP_POS_FRAMES, self.current_frame)
|
223 |
+
success, target_image = self.capture.read() #BGR
|
224 |
+
|
225 |
+
if success:
|
226 |
+
target_image = cv2.cvtColor(target_image, cv2.COLOR_BGR2RGB) #RGB
|
227 |
+
if not self.control['SwapFacesButton']:
|
228 |
+
temp = [target_image, self.current_frame] #temp = RGB
|
229 |
+
else:
|
230 |
+
temp = [self.swap_video(target_image, self.current_frame, marker), self.current_frame] # temp = RGB
|
231 |
+
|
232 |
+
self.r_frame_q.append(temp)
|
233 |
+
|
234 |
+
elif self.is_image_loaded:
|
235 |
+
if not self.control['SwapFacesButton']:
|
236 |
+
temp = [self.image, self.current_frame] # image = RGB
|
237 |
+
|
238 |
+
else:
|
239 |
+
temp = [self.swap_video(self.image, self.current_frame, False), self.current_frame] # image = RGB
|
240 |
+
|
241 |
+
self.r_frame_q.append(temp)
|
242 |
+
|
243 |
+
|
244 |
+
def find_lowest_frame(self, queues):
|
245 |
+
min_frame=999999999
|
246 |
+
index=-1
|
247 |
+
|
248 |
+
for idx, thread in enumerate(queues):
|
249 |
+
frame = thread['FrameNumber']
|
250 |
+
if frame != []:
|
251 |
+
if frame < min_frame:
|
252 |
+
min_frame = frame
|
253 |
+
index=idx
|
254 |
+
return index, min_frame
|
255 |
+
|
256 |
+
|
257 |
+
def play_video(self, command):
|
258 |
+
# print(inspect.currentframe().f_back.f_code.co_name, '->play_video: ')
|
259 |
+
if command == "play":
|
260 |
+
# Initialization
|
261 |
+
self.play = True
|
262 |
+
self.fps_average = []
|
263 |
+
self.process_qs = []
|
264 |
+
self.capture.set(cv2.CAP_PROP_POS_FRAMES, self.current_frame)
|
265 |
+
self.frame_timer = time.time()
|
266 |
+
|
267 |
+
# Create reusable queue based on number of threads
|
268 |
+
for i in range(self.parameters['ThreadsSlider']):
|
269 |
+
new_process_q = self.process_q.copy()
|
270 |
+
self.process_qs.append(new_process_q)
|
271 |
+
|
272 |
+
|
273 |
+
# Start up audio if requested
|
274 |
+
if self.control['AudioButton']:
|
275 |
+
seek_time = (self.current_frame)/self.fps
|
276 |
+
args = ["ffplay",
|
277 |
+
'-vn',
|
278 |
+
'-ss', str(seek_time),
|
279 |
+
'-nodisp',
|
280 |
+
'-stats',
|
281 |
+
'-loglevel', 'quiet',
|
282 |
+
'-sync', 'audio',
|
283 |
+
self.video_file]
|
284 |
+
|
285 |
+
|
286 |
+
self.audio_sp = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
287 |
+
|
288 |
+
# Parse the console to find where the audio started
|
289 |
+
while True:
|
290 |
+
temp = self.audio_sp.stdout.read(69)
|
291 |
+
if temp[:7] != b' nan':
|
292 |
+
sought_time = float(temp[:7])
|
293 |
+
self.current_frame = int(self.fps*sought_time)
|
294 |
+
|
295 |
+
self.capture.set(cv2.CAP_PROP_POS_FRAMES, self.current_frame)
|
296 |
+
|
297 |
+
break
|
298 |
+
|
299 |
+
|
300 |
+
#' nan : 0.000
|
301 |
+
#' 1.25 M-A: 0.000 fd= 0 aq= 12KB vq= 0KB sq= 0B f=0/0'
|
302 |
+
|
303 |
+
|
304 |
+
elif command == "stop":
|
305 |
+
self.play = False
|
306 |
+
self.add_action("stop_play", True)
|
307 |
+
|
308 |
+
index, min_frame = self.find_lowest_frame(self.process_qs)
|
309 |
+
|
310 |
+
if index != -1:
|
311 |
+
self.current_frame = min_frame-1
|
312 |
+
|
313 |
+
if self.control['AudioButton']:
|
314 |
+
self.audio_sp.terminate()
|
315 |
+
|
316 |
+
torch.cuda.empty_cache()
|
317 |
+
|
318 |
+
elif command=='stop_from_gui':
|
319 |
+
self.play = False
|
320 |
+
|
321 |
+
# Find the lowest frame in the current render queue and set the current frame to the one before it
|
322 |
+
index, min_frame = self.find_lowest_frame(self.process_qs)
|
323 |
+
if index != -1:
|
324 |
+
self.current_frame = min_frame-1
|
325 |
+
|
326 |
+
if self.control['AudioButton']:
|
327 |
+
self.audio_sp.terminate()
|
328 |
+
|
329 |
+
torch.cuda.empty_cache()
|
330 |
+
|
331 |
+
elif command == "record":
|
332 |
+
self.record = True
|
333 |
+
self.play = True
|
334 |
+
self.total_thread_time = 0.0
|
335 |
+
self.process_qs = []
|
336 |
+
self.capture.set(cv2.CAP_PROP_POS_FRAMES, self.current_frame)
|
337 |
+
|
338 |
+
for i in range(self.parameters['ThreadsSlider']):
|
339 |
+
new_process_q = self.process_q.copy()
|
340 |
+
self.process_qs.append(new_process_q)
|
341 |
+
|
342 |
+
# Initialize
|
343 |
+
self.timer = time.time()
|
344 |
+
frame_width = int(self.capture.get(3))
|
345 |
+
frame_width = int(self.capture.get(3))
|
346 |
+
frame_height = int(self.capture.get(4))
|
347 |
+
|
348 |
+
self.start_time = float(self.capture.get(cv2.CAP_PROP_POS_FRAMES) / float(self.fps))
|
349 |
+
|
350 |
+
self.file_name = os.path.splitext(os.path.basename(self.target_video))
|
351 |
+
base_filename = self.file_name[0]+"_"+str(time.time())[:10]
|
352 |
+
self.output = os.path.join(self.saved_video_path, base_filename)
|
353 |
+
self.temp_file = self.output+"_temp"+self.file_name[1]
|
354 |
+
|
355 |
+
if self.parameters['RecordTypeTextSel']=='FFMPEG':
|
356 |
+
args = ["ffmpeg",
|
357 |
+
'-hide_banner',
|
358 |
+
'-loglevel', 'error',
|
359 |
+
"-an",
|
360 |
+
"-r", str(self.fps),
|
361 |
+
"-i", "pipe:",
|
362 |
+
# '-g', '25',
|
363 |
+
"-vf", "format=yuvj420p",
|
364 |
+
"-c:v", "libx264",
|
365 |
+
"-crf", str(self.parameters['VideoQualSlider']),
|
366 |
+
"-r", str(self.fps),
|
367 |
+
"-s", str(frame_width)+"x"+str(frame_height),
|
368 |
+
self.temp_file]
|
369 |
+
|
370 |
+
self.sp = subprocess.Popen(args, stdin=subprocess.PIPE)
|
371 |
+
|
372 |
+
elif self.parameters['RecordTypeTextSel']=='OPENCV':
|
373 |
+
size = (frame_width, frame_height)
|
374 |
+
self.sp = cv2.VideoWriter(self.temp_file, cv2.VideoWriter_fourcc(*'mp4v') , self.fps, size)
|
375 |
+
|
376 |
+
# @profile
|
377 |
+
def process(self):
|
378 |
+
process_qs_len = range(len(self.process_qs))
|
379 |
+
|
380 |
+
# Add threads to Queue
|
381 |
+
if self.play == True and self.is_video_loaded == True:
|
382 |
+
for item in self.process_qs:
|
383 |
+
if item['Status'] == 'clear' and self.current_frame < self.video_frame_total:
|
384 |
+
item['Thread'] = threading.Thread(target=self.thread_video_read, args = [self.current_frame]).start()
|
385 |
+
item['FrameNumber'] = self.current_frame
|
386 |
+
item['Status'] = 'started'
|
387 |
+
item['ThreadTime'] = time.time()
|
388 |
+
|
389 |
+
self.current_frame += 1
|
390 |
+
break
|
391 |
+
|
392 |
+
else:
|
393 |
+
self.play = False
|
394 |
+
|
395 |
+
# Always be emptying the queues
|
396 |
+
time_diff = time.time() - self.frame_timer
|
397 |
+
|
398 |
+
if not self.record and time_diff >= 1.0/float(self.fps) and self.play:
|
399 |
+
|
400 |
+
index, min_frame = self.find_lowest_frame(self.process_qs)
|
401 |
+
|
402 |
+
if index != -1:
|
403 |
+
if self.process_qs[index]['Status'] == 'finished':
|
404 |
+
temp = [self.process_qs[index]['ProcessedFrame'], self.process_qs[index]['FrameNumber']]
|
405 |
+
self.frame_q.append(temp)
|
406 |
+
|
407 |
+
# Report fps, other data
|
408 |
+
self.fps_average.append(1.0/time_diff)
|
409 |
+
if len(self.fps_average) >= floor(self.fps):
|
410 |
+
fps = round(np.average(self.fps_average), 2)
|
411 |
+
msg = "%s fps, %s process time" % (fps, round(self.process_qs[index]['ThreadTime'], 4))
|
412 |
+
self.fps_average = []
|
413 |
+
|
414 |
+
if self.process_qs[index]['FrameNumber'] >= self.video_frame_total-1 or self.process_qs[index]['FrameNumber'] == self.stop_marker:
|
415 |
+
self.play_video('stop')
|
416 |
+
|
417 |
+
self.process_qs[index]['Status'] = 'clear'
|
418 |
+
self.process_qs[index]['Thread'] = []
|
419 |
+
self.process_qs[index]['FrameNumber'] = []
|
420 |
+
self.process_qs[index]['ThreadTime'] = []
|
421 |
+
self.frame_timer += 1.0/self.fps
|
422 |
+
|
423 |
+
elif self.record:
|
424 |
+
|
425 |
+
index, min_frame = self.find_lowest_frame(self.process_qs)
|
426 |
+
|
427 |
+
if index != -1:
|
428 |
+
|
429 |
+
# If the swapper thread has finished generating a frame
|
430 |
+
if self.process_qs[index]['Status'] == 'finished':
|
431 |
+
image = self.process_qs[index]['ProcessedFrame']
|
432 |
+
|
433 |
+
if self.parameters['RecordTypeTextSel']=='FFMPEG':
|
434 |
+
pil_image = Image.fromarray(image)
|
435 |
+
pil_image.save(self.sp.stdin, 'BMP')
|
436 |
+
|
437 |
+
elif self.parameters['RecordTypeTextSel']=='OPENCV':
|
438 |
+
self.sp.write(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
|
439 |
+
|
440 |
+
temp = [image, self.process_qs[index]['FrameNumber']]
|
441 |
+
self.frame_q.append(temp)
|
442 |
+
|
443 |
+
# Close video and process
|
444 |
+
if self.process_qs[index]['FrameNumber'] >= self.video_frame_total-1 or self.process_qs[index]['FrameNumber'] == self.stop_marker or self.play == False:
|
445 |
+
self.play_video("stop")
|
446 |
+
stop_time = float(self.capture.get(cv2.CAP_PROP_POS_FRAMES) / float(self.fps))
|
447 |
+
if stop_time == 0:
|
448 |
+
stop_time = float(self.video_frame_total) / float(self.fps)
|
449 |
+
|
450 |
+
if self.parameters['RecordTypeTextSel']=='FFMPEG':
|
451 |
+
self.sp.stdin.close()
|
452 |
+
self.sp.wait()
|
453 |
+
elif self.parameters['RecordTypeTextSel']=='OPENCV':
|
454 |
+
self.sp.release()
|
455 |
+
|
456 |
+
orig_file = self.target_video
|
457 |
+
final_file = self.output+self.file_name[1]
|
458 |
+
print("adding audio...")
|
459 |
+
args = ["ffmpeg",
|
460 |
+
'-hide_banner',
|
461 |
+
'-loglevel', 'error',
|
462 |
+
"-i", self.temp_file,
|
463 |
+
"-ss", str(self.start_time), "-to", str(stop_time), "-i", orig_file,
|
464 |
+
"-c", "copy", # may be c:v
|
465 |
+
"-map", "0:v:0", "-map", "1:a:0?",
|
466 |
+
"-shortest",
|
467 |
+
final_file]
|
468 |
+
|
469 |
+
four = subprocess.run(args)
|
470 |
+
os.remove(self.temp_file)
|
471 |
+
|
472 |
+
timef= time.time() - self.timer
|
473 |
+
self.record = False
|
474 |
+
print('Video saved as:', final_file)
|
475 |
+
msg = "Total time: %s s." % (round(timef,1))
|
476 |
+
print(msg)
|
477 |
+
|
478 |
+
|
479 |
+
self.total_thread_time = []
|
480 |
+
self.process_qs[index]['Status'] = 'clear'
|
481 |
+
self.process_qs[index]['FrameNumber'] = []
|
482 |
+
self.process_qs[index]['Thread'] = []
|
483 |
+
self.frame_timer = time.time()
|
484 |
+
# @profile
|
485 |
+
def thread_video_read(self, frame_number):
|
486 |
+
with lock:
|
487 |
+
success, target_image = self.capture.read()
|
488 |
+
|
489 |
+
if success:
|
490 |
+
target_image = cv2.cvtColor(target_image, cv2.COLOR_BGR2RGB)
|
491 |
+
if not self.control['SwapFacesButton']:
|
492 |
+
temp = [target_image, frame_number]
|
493 |
+
|
494 |
+
else:
|
495 |
+
temp = [self.swap_video(target_image, frame_number, True), frame_number]
|
496 |
+
|
497 |
+
for item in self.process_qs:
|
498 |
+
if item['FrameNumber'] == frame_number:
|
499 |
+
item['ProcessedFrame'] = temp[0]
|
500 |
+
item['Status'] = 'finished'
|
501 |
+
item['ThreadTime'] = time.time() - item['ThreadTime']
|
502 |
+
break
|
503 |
+
|
504 |
+
|
505 |
+
|
506 |
+
|
507 |
+
# @profile
|
508 |
+
def swap_video(self, target_image, frame_number, use_markers):
|
509 |
+
# Grab a local copy of the parameters to prevent threading issues
|
510 |
+
parameters = self.parameters.copy()
|
511 |
+
control = self.control.copy()
|
512 |
+
|
513 |
+
# Find out if the frame is in a marker zone and copy the parameters if true
|
514 |
+
if self.markers and use_markers:
|
515 |
+
temp=[]
|
516 |
+
for i in range(len(self.markers)):
|
517 |
+
temp.append(self.markers[i]['frame'])
|
518 |
+
idx = bisect.bisect(temp, frame_number)
|
519 |
+
|
520 |
+
parameters = self.markers[idx-1]['parameters'].copy()
|
521 |
+
|
522 |
+
# Load frame into VRAM
|
523 |
+
img = torch.from_numpy(target_image.astype('uint8')).to('cuda') #HxWxc
|
524 |
+
img = img.permute(2,0,1)#cxHxW
|
525 |
+
|
526 |
+
#Scale up frame if it is smaller than 512
|
527 |
+
img_x = img.size()[2]
|
528 |
+
img_y = img.size()[1]
|
529 |
+
|
530 |
+
if img_x<512 and img_y<512:
|
531 |
+
# if x is smaller, set x to 512
|
532 |
+
if img_x <= img_y:
|
533 |
+
tscale = v2.Resize((int(512*img_y/img_x), 512), antialias=True)
|
534 |
+
else:
|
535 |
+
tscale = v2.Resize((512, int(512*img_x/img_y)), antialias=True)
|
536 |
+
|
537 |
+
img = tscale(img)
|
538 |
+
|
539 |
+
elif img_x<512:
|
540 |
+
tscale = v2.Resize((int(512*img_y/img_x), 512), antialias=True)
|
541 |
+
img = tscale(img)
|
542 |
+
|
543 |
+
elif img_y<512:
|
544 |
+
tscale = v2.Resize((512, int(512*img_x/img_y)), antialias=True)
|
545 |
+
img = tscale(img)
|
546 |
+
|
547 |
+
# Rotate the frame
|
548 |
+
if parameters['OrientSwitch']:
|
549 |
+
img = v2.functional.rotate(img, angle=parameters['OrientSlider'], interpolation=v2.InterpolationMode.BILINEAR, expand=True)
|
550 |
+
|
551 |
+
# Find all faces in frame and return a list of 5-pt kpss
|
552 |
+
bboxes, kpss = self.func_w_test("detect", self.models.run_detect, img, parameters['DetectTypeTextSel'], max_num=20, score=parameters['DetectScoreSlider']/100.0, use_landmark_detection=parameters['LandmarksDetectionAdjSwitch'], landmark_detect_mode=parameters["LandmarksDetectTypeTextSel"], landmark_score=parameters["LandmarksDetectScoreSlider"]/100.0, from_points=parameters["LandmarksAlignModeFromPointsSwitch"])
|
553 |
+
|
554 |
+
# Get embeddings for all faces found in the frame
|
555 |
+
ret = []
|
556 |
+
for face_kps in kpss:
|
557 |
+
face_emb, _ = self.func_w_test('recognize', self.models.run_recognize, img, face_kps)
|
558 |
+
ret.append([face_kps, face_emb])
|
559 |
+
|
560 |
+
if ret:
|
561 |
+
# Loop through target faces to see if they match our found face embeddings
|
562 |
+
for fface in ret:
|
563 |
+
for found_face in self.found_faces:
|
564 |
+
# sim between face in video and already found face
|
565 |
+
sim = self.findCosineDistance(fface[1], found_face["Embedding"])
|
566 |
+
# if the face[i] in the frame matches afound face[j] AND the found face is active (not [])
|
567 |
+
if sim>=float(parameters["ThresholdSlider"]) and found_face["SourceFaceAssignments"]:
|
568 |
+
s_e = found_face["AssignedEmbedding"]
|
569 |
+
# s_e = found_face['ptrdata']
|
570 |
+
img = self.func_w_test("swap_video", self.swap_core, img, fface[0], s_e, parameters, control)
|
571 |
+
# img = img.permute(2,0,1)
|
572 |
+
|
573 |
+
img = img.permute(1,2,0)
|
574 |
+
if not control['MaskViewButton'] and parameters['OrientSwitch']:
|
575 |
+
img = img.permute(2,0,1)
|
576 |
+
img = transforms.functional.rotate(img, angle=-parameters['OrientSlider'], expand=True)
|
577 |
+
img = img.permute(1,2,0)
|
578 |
+
|
579 |
+
else:
|
580 |
+
img = img.permute(1,2,0)
|
581 |
+
if parameters['OrientSwitch']:
|
582 |
+
img = img.permute(2,0,1)
|
583 |
+
img = v2.functional.rotate(img, angle=-parameters['OrientSlider'], interpolation=v2.InterpolationMode.BILINEAR, expand=True)
|
584 |
+
img = img.permute(1,2,0)
|
585 |
+
|
586 |
+
if self.perf_test:
|
587 |
+
print('------------------------')
|
588 |
+
|
589 |
+
# Unscale small videos
|
590 |
+
if img_x <512 or img_y < 512:
|
591 |
+
tscale = v2.Resize((img_y, img_x), antialias=True)
|
592 |
+
img = img.permute(2,0,1)
|
593 |
+
img = tscale(img)
|
594 |
+
img = img.permute(1,2,0)
|
595 |
+
|
596 |
+
|
597 |
+
img = img.cpu().numpy()
|
598 |
+
|
599 |
+
if parameters["ShowLandmarksSwitch"]:
|
600 |
+
if ret:
|
601 |
+
if img_y <= 720:
|
602 |
+
p = 1
|
603 |
+
else:
|
604 |
+
p = 2
|
605 |
+
|
606 |
+
for face in ret:
|
607 |
+
for kpoint in face[0]:
|
608 |
+
for i in range(-1, p):
|
609 |
+
for j in range(-1, p):
|
610 |
+
try:
|
611 |
+
img[int(kpoint[1])+i][int(kpoint[0])+j][0] = 0
|
612 |
+
img[int(kpoint[1])+i][int(kpoint[0])+j][1] = 255
|
613 |
+
img[int(kpoint[1])+i][int(kpoint[0])+j][2] = 255
|
614 |
+
except:
|
615 |
+
print("Key-points value {} exceed the image size {}.".format(kpoint, (img_x, img_y)))
|
616 |
+
continue
|
617 |
+
|
618 |
+
return img.astype(np.uint8)
|
619 |
+
|
620 |
+
def findCosineDistance(self, vector1, vector2):
|
621 |
+
vector1 = vector1.ravel()
|
622 |
+
vector2 = vector2.ravel()
|
623 |
+
cos_dist = 1.0 - np.dot(vector1, vector2)/(np.linalg.norm(vector1)*np.linalg.norm(vector2)) # 2..0
|
624 |
+
|
625 |
+
return 100.0-cos_dist*50.0
|
626 |
+
'''
|
627 |
+
vector1 = vector1.ravel()
|
628 |
+
vector2 = vector2.ravel()
|
629 |
+
|
630 |
+
return 1 - np.dot(vector1, vector2)/(np.linalg.norm(vector1)*np.linalg.norm(vector2))
|
631 |
+
'''
|
632 |
+
|
633 |
+
def func_w_test(self, name, func, *args, **argsv):
|
634 |
+
timing = time.time()
|
635 |
+
result = func(*args, **argsv)
|
636 |
+
if self.perf_test:
|
637 |
+
print(name, round(time.time()-timing, 5), 's')
|
638 |
+
return result
|
639 |
+
|
640 |
+
# @profile
|
641 |
+
def swap_core(self, img, kps, s_e, parameters, control): # img = RGB
|
642 |
+
# 512 transforms
|
643 |
+
dst = self.arcface_dst * 4.0
|
644 |
+
dst[:,0] += 32.0
|
645 |
+
|
646 |
+
# Change the ref points
|
647 |
+
if parameters['FaceAdjSwitch']:
|
648 |
+
dst[:,0] += parameters['KPSXSlider']
|
649 |
+
dst[:,1] += parameters['KPSYSlider']
|
650 |
+
dst[:,0] -= 255
|
651 |
+
dst[:,0] *= (1+parameters['KPSScaleSlider']/100)
|
652 |
+
dst[:,0] += 255
|
653 |
+
dst[:,1] -= 255
|
654 |
+
dst[:,1] *= (1+parameters['KPSScaleSlider']/100)
|
655 |
+
dst[:,1] += 255
|
656 |
+
|
657 |
+
tform = trans.SimilarityTransform()
|
658 |
+
tform.estimate(kps, dst)
|
659 |
+
|
660 |
+
# Scaling Transforms
|
661 |
+
t512 = v2.Resize((512, 512), interpolation=v2.InterpolationMode.BILINEAR, antialias=False)
|
662 |
+
t256 = v2.Resize((256, 256), interpolation=v2.InterpolationMode.BILINEAR, antialias=False)
|
663 |
+
t128 = v2.Resize((128, 128), interpolation=v2.InterpolationMode.BILINEAR, antialias=False)
|
664 |
+
|
665 |
+
# Grab 512 face from image and create 256 and 128 copys
|
666 |
+
original_face_512 = v2.functional.affine(img, tform.rotation*57.2958, (tform.translation[0], tform.translation[1]) , tform.scale, 0, center = (0,0), interpolation=v2.InterpolationMode.BILINEAR )
|
667 |
+
original_face_512 = v2.functional.crop(original_face_512, 0,0, 512, 512)# 3, 512, 512
|
668 |
+
original_face_256 = t256(original_face_512)
|
669 |
+
original_face_128 = t128(original_face_256)
|
670 |
+
|
671 |
+
latent = torch.from_numpy(self.models.calc_swapper_latent(s_e)).float().to('cuda')
|
672 |
+
|
673 |
+
dim = 1
|
674 |
+
if parameters['SwapperTypeTextSel'] == '128':
|
675 |
+
dim = 1
|
676 |
+
input_face_affined = original_face_128
|
677 |
+
elif parameters['SwapperTypeTextSel'] == '256':
|
678 |
+
dim = 2
|
679 |
+
input_face_affined = original_face_256
|
680 |
+
elif parameters['SwapperTypeTextSel'] == '512':
|
681 |
+
dim = 4
|
682 |
+
input_face_affined = original_face_512
|
683 |
+
|
684 |
+
# Optional Scaling # change the thransform matrix
|
685 |
+
if parameters['FaceAdjSwitch']:
|
686 |
+
input_face_affined = v2.functional.affine(input_face_affined, 0, (0, 0), 1 + parameters['FaceScaleSlider'] / 100, 0, center=(dim*128-1, dim*128-1), interpolation=v2.InterpolationMode.BILINEAR)
|
687 |
+
|
688 |
+
itex = 1
|
689 |
+
if parameters['StrengthSwitch']:
|
690 |
+
itex = ceil(parameters['StrengthSlider'] / 100.)
|
691 |
+
|
692 |
+
output_size = int(128 * dim)
|
693 |
+
output = torch.zeros((output_size, output_size, 3), dtype=torch.float32, device='cuda')
|
694 |
+
input_face_affined = input_face_affined.permute(1, 2, 0)
|
695 |
+
input_face_affined = torch.div(input_face_affined, 255.0)
|
696 |
+
|
697 |
+
for k in range(itex):
|
698 |
+
for j in range(dim):
|
699 |
+
for i in range(dim):
|
700 |
+
input_face_disc = input_face_affined[j::dim,i::dim]
|
701 |
+
input_face_disc = input_face_disc.permute(2, 0, 1)
|
702 |
+
input_face_disc = torch.unsqueeze(input_face_disc, 0).contiguous()
|
703 |
+
|
704 |
+
swapper_output = torch.empty((1,3,128,128), dtype=torch.float32, device='cuda').contiguous()
|
705 |
+
self.models.run_swapper(input_face_disc, latent, swapper_output)
|
706 |
+
|
707 |
+
swapper_output = torch.squeeze(swapper_output)
|
708 |
+
swapper_output = swapper_output.permute(1, 2, 0)
|
709 |
+
|
710 |
+
|
711 |
+
output[j::dim, i::dim] = swapper_output.clone()
|
712 |
+
prev_face = input_face_affined.clone()
|
713 |
+
input_face_affined = output.clone()
|
714 |
+
output = torch.mul(output, 255)
|
715 |
+
output = torch.clamp(output, 0, 255)
|
716 |
+
|
717 |
+
|
718 |
+
output = output.permute(2, 0, 1)
|
719 |
+
|
720 |
+
|
721 |
+
swap = t512(output)
|
722 |
+
|
723 |
+
if parameters['StrengthSwitch']:
|
724 |
+
if itex == 0:
|
725 |
+
swap = original_face_512.clone()
|
726 |
+
else:
|
727 |
+
alpha = np.mod(parameters['StrengthSlider'], 100)*0.01
|
728 |
+
if alpha==0:
|
729 |
+
alpha=1
|
730 |
+
|
731 |
+
# Blend the images
|
732 |
+
prev_face = torch.mul(prev_face, 255)
|
733 |
+
prev_face = torch.clamp(prev_face, 0, 255)
|
734 |
+
prev_face = prev_face.permute(2, 0, 1)
|
735 |
+
prev_face = t512(prev_face)
|
736 |
+
swap = torch.mul(swap, alpha)
|
737 |
+
prev_face = torch.mul(prev_face, 1-alpha)
|
738 |
+
swap = torch.add(swap, prev_face)
|
739 |
+
|
740 |
+
|
741 |
+
|
742 |
+
|
743 |
+
# swap = torch.squeeze(swap)
|
744 |
+
# swap = torch.mul(swap, 255)
|
745 |
+
# swap = torch.clamp(swap, 0, 255)
|
746 |
+
# # swap_128 = swap
|
747 |
+
# swap = t256(swap)
|
748 |
+
# swap = t512(swap)
|
749 |
+
|
750 |
+
|
751 |
+
# Apply color corerctions
|
752 |
+
if parameters['ColorSwitch']:
|
753 |
+
# print(parameters['ColorGammaSlider'])
|
754 |
+
swap = torch.unsqueeze(swap,0)
|
755 |
+
swap = v2.functional.adjust_gamma(swap, parameters['ColorGammaSlider'], 1.0)
|
756 |
+
swap = torch.squeeze(swap)
|
757 |
+
swap = swap.permute(1, 2, 0).type(torch.float32)
|
758 |
+
|
759 |
+
del_color = torch.tensor([parameters['ColorRedSlider'], parameters['ColorGreenSlider'], parameters['ColorBlueSlider']], device=device)
|
760 |
+
swap += del_color
|
761 |
+
swap = torch.clamp(swap, min=0., max=255.)
|
762 |
+
swap = swap.permute(2, 0, 1).type(torch.uint8)
|
763 |
+
|
764 |
+
# Create border mask
|
765 |
+
border_mask = torch.ones((128, 128), dtype=torch.float32, device=device)
|
766 |
+
border_mask = torch.unsqueeze(border_mask,0)
|
767 |
+
|
768 |
+
# if parameters['BorderState']:
|
769 |
+
top = parameters['BorderTopSlider']
|
770 |
+
left = parameters['BorderSidesSlider']
|
771 |
+
right = 128-parameters['BorderSidesSlider']
|
772 |
+
bottom = 128-parameters['BorderBottomSlider']
|
773 |
+
|
774 |
+
border_mask[:, :top, :] = 0
|
775 |
+
border_mask[:, bottom:, :] = 0
|
776 |
+
border_mask[:, :, :left] = 0
|
777 |
+
border_mask[:, :, right:] = 0
|
778 |
+
|
779 |
+
gauss = transforms.GaussianBlur(parameters['BorderBlurSlider']*2+1, (parameters['BorderBlurSlider']+1)*0.2)
|
780 |
+
border_mask = gauss(border_mask)
|
781 |
+
|
782 |
+
# Create image mask
|
783 |
+
swap_mask = torch.ones((128, 128), dtype=torch.float32, device=device)
|
784 |
+
swap_mask = torch.unsqueeze(swap_mask,0)
|
785 |
+
|
786 |
+
# Face Diffing
|
787 |
+
if parameters["DiffSwitch"]:
|
788 |
+
mask = self.apply_fake_diff(swap, original_face_512, parameters["DiffSlider"])
|
789 |
+
# mask = t128(mask)
|
790 |
+
gauss = transforms.GaussianBlur(parameters['BlendSlider']*2+1, (parameters['BlendSlider']+1)*0.2)
|
791 |
+
mask = gauss(mask.type(torch.float32))
|
792 |
+
swap = swap*mask + original_face_512*(1-mask)
|
793 |
+
|
794 |
+
# Restorer
|
795 |
+
if parameters["RestorerSwitch"]:
|
796 |
+
swap = self.func_w_test('Restorer', self.apply_restorer, swap, parameters)
|
797 |
+
|
798 |
+
|
799 |
+
# Occluder
|
800 |
+
if parameters["OccluderSwitch"]:
|
801 |
+
mask = self.func_w_test('occluder', self.apply_occlusion , original_face_256, parameters["OccluderSlider"])
|
802 |
+
mask = t128(mask)
|
803 |
+
swap_mask = torch.mul(swap_mask, mask)
|
804 |
+
|
805 |
+
|
806 |
+
if parameters["FaceParserSwitch"]:
|
807 |
+
mask = self.apply_face_parser(swap, parameters["FaceParserSlider"], parameters['MouthParserSlider'])
|
808 |
+
mask = t128(mask)
|
809 |
+
swap_mask = torch.mul(swap_mask, mask)
|
810 |
+
|
811 |
+
# CLIPs
|
812 |
+
if parameters["CLIPSwitch"]:
|
813 |
+
with lock:
|
814 |
+
mask = self.func_w_test('CLIP', self.apply_CLIPs, original_face_512, parameters["CLIPTextEntry"], parameters["CLIPSlider"])
|
815 |
+
mask = cv2.resize(mask, (128,128))
|
816 |
+
mask = torch.from_numpy(mask).to('cuda')
|
817 |
+
swap_mask *= mask
|
818 |
+
|
819 |
+
|
820 |
+
# Add blur to swap_mask results
|
821 |
+
gauss = transforms.GaussianBlur(parameters['BlendSlider']*2+1, (parameters['BlendSlider']+1)*0.2)
|
822 |
+
swap_mask = gauss(swap_mask)
|
823 |
+
|
824 |
+
|
825 |
+
# Combine border and swap mask, scale, and apply to swap
|
826 |
+
swap_mask = torch.mul(swap_mask, border_mask)
|
827 |
+
swap_mask = t512(swap_mask)
|
828 |
+
swap = torch.mul(swap, swap_mask)
|
829 |
+
|
830 |
+
if not control['MaskViewButton']:
|
831 |
+
# Cslculate the area to be mergerd back to the original frame
|
832 |
+
IM512 = tform.inverse.params[0:2, :]
|
833 |
+
corners = np.array([[0,0], [0,511], [511, 0], [511, 511]])
|
834 |
+
|
835 |
+
x = (IM512[0][0]*corners[:,0] + IM512[0][1]*corners[:,1] + IM512[0][2])
|
836 |
+
y = (IM512[1][0]*corners[:,0] + IM512[1][1]*corners[:,1] + IM512[1][2])
|
837 |
+
|
838 |
+
left = floor(np.min(x))
|
839 |
+
if left<0:
|
840 |
+
left=0
|
841 |
+
top = floor(np.min(y))
|
842 |
+
if top<0:
|
843 |
+
top=0
|
844 |
+
right = ceil(np.max(x))
|
845 |
+
if right>img.shape[2]:
|
846 |
+
right=img.shape[2]
|
847 |
+
bottom = ceil(np.max(y))
|
848 |
+
if bottom>img.shape[1]:
|
849 |
+
bottom=img.shape[1]
|
850 |
+
|
851 |
+
# Untransform the swap
|
852 |
+
swap = v2.functional.pad(swap, (0,0,img.shape[2]-512, img.shape[1]-512))
|
853 |
+
swap = v2.functional.affine(swap, tform.inverse.rotation*57.2958, (tform.inverse.translation[0], tform.inverse.translation[1]), tform.inverse.scale, 0,interpolation=v2.InterpolationMode.BILINEAR, center = (0,0) )
|
854 |
+
swap = swap[0:3, top:bottom, left:right]
|
855 |
+
swap = swap.permute(1, 2, 0)
|
856 |
+
|
857 |
+
# Untransform the swap mask
|
858 |
+
swap_mask = v2.functional.pad(swap_mask, (0,0,img.shape[2]-512, img.shape[1]-512))
|
859 |
+
swap_mask = v2.functional.affine(swap_mask, tform.inverse.rotation*57.2958, (tform.inverse.translation[0], tform.inverse.translation[1]), tform.inverse.scale, 0, interpolation=v2.InterpolationMode.BILINEAR, center = (0,0) )
|
860 |
+
swap_mask = swap_mask[0:1, top:bottom, left:right]
|
861 |
+
swap_mask = swap_mask.permute(1, 2, 0)
|
862 |
+
swap_mask = torch.sub(1, swap_mask)
|
863 |
+
|
864 |
+
# Apply the mask to the original image areas
|
865 |
+
img_crop = img[0:3, top:bottom, left:right]
|
866 |
+
img_crop = img_crop.permute(1,2,0)
|
867 |
+
img_crop = torch.mul(swap_mask,img_crop)
|
868 |
+
|
869 |
+
#Add the cropped areas and place them back into the original image
|
870 |
+
swap = torch.add(swap, img_crop)
|
871 |
+
swap = swap.type(torch.uint8)
|
872 |
+
swap = swap.permute(2,0,1)
|
873 |
+
img[0:3, top:bottom, left:right] = swap
|
874 |
+
|
875 |
+
else:
|
876 |
+
# Invert swap mask
|
877 |
+
swap_mask = torch.sub(1, swap_mask)
|
878 |
+
|
879 |
+
# Combine preswapped face with swap
|
880 |
+
original_face_512 = torch.mul(swap_mask, original_face_512)
|
881 |
+
original_face_512 = torch.add(swap, original_face_512)
|
882 |
+
original_face_512 = original_face_512.type(torch.uint8)
|
883 |
+
original_face_512 = original_face_512.permute(1, 2, 0)
|
884 |
+
|
885 |
+
# Uninvert and create image from swap mask
|
886 |
+
swap_mask = torch.sub(1, swap_mask)
|
887 |
+
swap_mask = torch.cat((swap_mask,swap_mask,swap_mask),0)
|
888 |
+
swap_mask = swap_mask.permute(1, 2, 0)
|
889 |
+
|
890 |
+
# Place them side by side
|
891 |
+
img = torch.hstack([original_face_512, swap_mask*255])
|
892 |
+
img = img.permute(2,0,1)
|
893 |
+
|
894 |
+
return img
|
895 |
+
|
896 |
+
# @profile
|
897 |
+
def apply_occlusion(self, img, amount):
|
898 |
+
img = torch.div(img, 255)
|
899 |
+
img = torch.unsqueeze(img, 0)
|
900 |
+
outpred = torch.ones((256,256), dtype=torch.float32, device=device).contiguous()
|
901 |
+
|
902 |
+
self.models.run_occluder(img, outpred)
|
903 |
+
|
904 |
+
outpred = torch.squeeze(outpred)
|
905 |
+
outpred = (outpred > 0)
|
906 |
+
outpred = torch.unsqueeze(outpred, 0).type(torch.float32)
|
907 |
+
|
908 |
+
if amount >0:
|
909 |
+
kernel = torch.ones((1,1,3,3), dtype=torch.float32, device=device)
|
910 |
+
|
911 |
+
for i in range(int(amount)):
|
912 |
+
outpred = torch.nn.functional.conv2d(outpred, kernel, padding=(1, 1))
|
913 |
+
outpred = torch.clamp(outpred, 0, 1)
|
914 |
+
|
915 |
+
outpred = torch.squeeze(outpred)
|
916 |
+
|
917 |
+
if amount <0:
|
918 |
+
outpred = torch.neg(outpred)
|
919 |
+
outpred = torch.add(outpred, 1)
|
920 |
+
kernel = torch.ones((1,1,3,3), dtype=torch.float32, device=device)
|
921 |
+
|
922 |
+
for i in range(int(-amount)):
|
923 |
+
outpred = torch.nn.functional.conv2d(outpred, kernel, padding=(1, 1))
|
924 |
+
outpred = torch.clamp(outpred, 0, 1)
|
925 |
+
|
926 |
+
outpred = torch.squeeze(outpred)
|
927 |
+
outpred = torch.neg(outpred)
|
928 |
+
outpred = torch.add(outpred, 1)
|
929 |
+
|
930 |
+
outpred = torch.reshape(outpred, (1, 256, 256))
|
931 |
+
return outpred
|
932 |
+
|
933 |
+
|
934 |
+
def apply_CLIPs(self, img, CLIPText, CLIPAmount):
|
935 |
+
clip_mask = np.ones((352, 352))
|
936 |
+
img = img.permute(1,2,0)
|
937 |
+
img = img.cpu().numpy()
|
938 |
+
# img = img.to(torch.float)
|
939 |
+
# img = img.permute(1,2,0)
|
940 |
+
transform = transforms.Compose([transforms.ToTensor(),
|
941 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
942 |
+
transforms.Resize((352, 352))])
|
943 |
+
CLIPimg = transform(img).unsqueeze(0)
|
944 |
+
|
945 |
+
if CLIPText != "":
|
946 |
+
prompts = CLIPText.split(',')
|
947 |
+
|
948 |
+
with torch.no_grad():
|
949 |
+
preds = self.clip_session(CLIPimg.repeat(len(prompts),1,1,1), prompts)[0]
|
950 |
+
# preds = self.clip_session(CLIPimg, maskimg, True)[0]
|
951 |
+
|
952 |
+
clip_mask = 1 - torch.sigmoid(preds[0][0])
|
953 |
+
for i in range(len(prompts)-1):
|
954 |
+
clip_mask *= 1-torch.sigmoid(preds[i+1][0])
|
955 |
+
clip_mask = clip_mask.data.cpu().numpy()
|
956 |
+
|
957 |
+
thresh = CLIPAmount/100.0
|
958 |
+
clip_mask[clip_mask>thresh] = 1.0
|
959 |
+
clip_mask[clip_mask<=thresh] = 0.0
|
960 |
+
return clip_mask
|
961 |
+
|
962 |
+
# @profile
|
963 |
+
def apply_face_parser(self, img, FaceAmount, MouthAmount):
|
964 |
+
|
965 |
+
# atts = [1 'skin', 2 'l_brow', 3 'r_brow', 4 'l_eye', 5 'r_eye', 6 'eye_g', 7 'l_ear', 8 'r_ear', 9 'ear_r', 10 'nose', 11 'mouth', 12 'u_lip', 13 'l_lip', 14 'neck', 15 'neck_l', 16 'cloth', 17 'hair', 18 'hat']
|
966 |
+
|
967 |
+
outpred = torch.ones((512,512), dtype=torch.float32, device='cuda').contiguous()
|
968 |
+
|
969 |
+
|
970 |
+
img = torch.div(img, 255)
|
971 |
+
img = v2.functional.normalize(img, (0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
|
972 |
+
img = torch.reshape(img, (1, 3, 512, 512))
|
973 |
+
outpred = torch.empty((1,19,512,512), dtype=torch.float32, device='cuda').contiguous()
|
974 |
+
|
975 |
+
self.models.run_faceparser(img, outpred)
|
976 |
+
|
977 |
+
outpred = torch.squeeze(outpred)
|
978 |
+
outpred = torch.argmax(outpred, 0)
|
979 |
+
|
980 |
+
# Mouth Parse
|
981 |
+
if MouthAmount <0:
|
982 |
+
mouth_idxs = torch.tensor([11], device='cuda')
|
983 |
+
iters = int(-MouthAmount)
|
984 |
+
|
985 |
+
mouth_parse = torch.isin(outpred, mouth_idxs)
|
986 |
+
mouth_parse = torch.clamp(~mouth_parse, 0, 1).type(torch.float32)
|
987 |
+
mouth_parse = torch.reshape(mouth_parse, (1, 1, 512, 512))
|
988 |
+
mouth_parse = torch.neg(mouth_parse)
|
989 |
+
mouth_parse = torch.add(mouth_parse, 1)
|
990 |
+
|
991 |
+
kernel = torch.ones((1, 1, 3, 3), dtype=torch.float32,
|
992 |
+
device='cuda')
|
993 |
+
|
994 |
+
for i in range(iters):
|
995 |
+
mouth_parse = torch.nn.functional.conv2d(mouth_parse, kernel,
|
996 |
+
padding=(1, 1))
|
997 |
+
mouth_parse = torch.clamp(mouth_parse, 0, 1)
|
998 |
+
|
999 |
+
mouth_parse = torch.squeeze(mouth_parse)
|
1000 |
+
mouth_parse = torch.neg(mouth_parse)
|
1001 |
+
mouth_parse = torch.add(mouth_parse, 1)
|
1002 |
+
mouth_parse = torch.reshape(mouth_parse, (1, 512, 512))
|
1003 |
+
|
1004 |
+
elif MouthAmount >0:
|
1005 |
+
mouth_idxs = torch.tensor([11,12,13], device='cuda')
|
1006 |
+
iters = int(MouthAmount)
|
1007 |
+
|
1008 |
+
mouth_parse = torch.isin(outpred, mouth_idxs)
|
1009 |
+
mouth_parse = torch.clamp(~mouth_parse, 0, 1).type(torch.float32)
|
1010 |
+
mouth_parse = torch.reshape(mouth_parse, (1,1,512,512))
|
1011 |
+
mouth_parse = torch.neg(mouth_parse)
|
1012 |
+
mouth_parse = torch.add(mouth_parse, 1)
|
1013 |
+
|
1014 |
+
kernel = torch.ones((1,1,3,3), dtype=torch.float32, device='cuda')
|
1015 |
+
|
1016 |
+
for i in range(iters):
|
1017 |
+
mouth_parse = torch.nn.functional.conv2d(mouth_parse, kernel, padding=(1, 1))
|
1018 |
+
mouth_parse = torch.clamp(mouth_parse, 0, 1)
|
1019 |
+
|
1020 |
+
mouth_parse = torch.squeeze(mouth_parse)
|
1021 |
+
mouth_parse = torch.neg(mouth_parse)
|
1022 |
+
mouth_parse = torch.add(mouth_parse, 1)
|
1023 |
+
mouth_parse = torch.reshape(mouth_parse, (1, 512, 512))
|
1024 |
+
|
1025 |
+
else:
|
1026 |
+
mouth_parse = torch.ones((1, 512, 512), dtype=torch.float32, device='cuda')
|
1027 |
+
|
1028 |
+
# BG Parse
|
1029 |
+
bg_idxs = torch.tensor([0, 14, 15, 16, 17, 18], device=device)
|
1030 |
+
bg_parse = torch.isin(outpred, bg_idxs)
|
1031 |
+
bg_parse = torch.clamp(~bg_parse, 0, 1).type(torch.float32)
|
1032 |
+
bg_parse = torch.reshape(bg_parse, (1, 1, 512, 512))
|
1033 |
+
|
1034 |
+
if FaceAmount > 0:
|
1035 |
+
kernel = torch.ones((1, 1, 3, 3), dtype=torch.float32, device=device)
|
1036 |
+
|
1037 |
+
for i in range(int(FaceAmount)):
|
1038 |
+
bg_parse = torch.nn.functional.conv2d(bg_parse, kernel, padding=(1, 1))
|
1039 |
+
bg_parse = torch.clamp(bg_parse, 0, 1)
|
1040 |
+
|
1041 |
+
bg_parse = torch.squeeze(bg_parse)
|
1042 |
+
|
1043 |
+
elif FaceAmount < 0:
|
1044 |
+
bg_parse = torch.neg(bg_parse)
|
1045 |
+
bg_parse = torch.add(bg_parse, 1)
|
1046 |
+
|
1047 |
+
kernel = torch.ones((1, 1, 3, 3), dtype=torch.float32, device=device)
|
1048 |
+
|
1049 |
+
for i in range(int(-FaceAmount)):
|
1050 |
+
bg_parse = torch.nn.functional.conv2d(bg_parse, kernel, padding=(1, 1))
|
1051 |
+
bg_parse = torch.clamp(bg_parse, 0, 1)
|
1052 |
+
|
1053 |
+
bg_parse = torch.squeeze(bg_parse)
|
1054 |
+
bg_parse = torch.neg(bg_parse)
|
1055 |
+
bg_parse = torch.add(bg_parse, 1)
|
1056 |
+
bg_parse = torch.reshape(bg_parse, (1, 512, 512))
|
1057 |
+
else:
|
1058 |
+
bg_parse = torch.ones((1,512,512), dtype=torch.float32, device='cuda')
|
1059 |
+
|
1060 |
+
out_parse = torch.mul(bg_parse, mouth_parse)
|
1061 |
+
|
1062 |
+
return out_parse
|
1063 |
+
|
1064 |
+
def apply_bg_face_parser(self, img, FaceParserAmount):
|
1065 |
+
|
1066 |
+
# atts = [1 'skin', 2 'l_brow', 3 'r_brow', 4 'l_eye', 5 'r_eye', 6 'eye_g', 7 'l_ear', 8 'r_ear', 9 'ear_r', 10 'nose', 11 'mouth', 12 'u_lip', 13 'l_lip', 14 'neck', 15 'neck_l', 16 'cloth', 17 'hair', 18 'hat']
|
1067 |
+
# out = np.ones((512, 512), dtype=np.float32)
|
1068 |
+
|
1069 |
+
outpred = torch.ones((512,512), dtype=torch.float32, device='cuda').contiguous()
|
1070 |
+
|
1071 |
+
# turn mouth parser off at 0 so someone can just use the mouth parser
|
1072 |
+
if FaceParserAmount != 0:
|
1073 |
+
img = torch.div(img, 255)
|
1074 |
+
img = v2.functional.normalize(img, (0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
|
1075 |
+
img = torch.reshape(img, (1, 3, 512, 512))
|
1076 |
+
outpred = torch.empty((1,19,512,512), dtype=torch.float32, device=device).contiguous()
|
1077 |
+
|
1078 |
+
self.models.run_faceparser(img, outpred)
|
1079 |
+
|
1080 |
+
outpred = torch.squeeze(outpred)
|
1081 |
+
outpred = torch.argmax(outpred, 0)
|
1082 |
+
|
1083 |
+
test = torch.tensor([ 0, 14, 15, 16, 17, 18], device=device)
|
1084 |
+
outpred = torch.isin(outpred, test)
|
1085 |
+
outpred = torch.clamp(~outpred, 0, 1).type(torch.float32)
|
1086 |
+
outpred = torch.reshape(outpred, (1,1,512,512))
|
1087 |
+
|
1088 |
+
if FaceParserAmount >0:
|
1089 |
+
kernel = torch.ones((1,1,3,3), dtype=torch.float32, device=device)
|
1090 |
+
|
1091 |
+
for i in range(int(FaceParserAmount)):
|
1092 |
+
outpred = torch.nn.functional.conv2d(outpred, kernel, padding=(1, 1))
|
1093 |
+
outpred = torch.clamp(outpred, 0, 1)
|
1094 |
+
|
1095 |
+
outpred = torch.squeeze(outpred)
|
1096 |
+
|
1097 |
+
if FaceParserAmount <0:
|
1098 |
+
outpred = torch.neg(outpred)
|
1099 |
+
outpred = torch.add(outpred, 1)
|
1100 |
+
|
1101 |
+
kernel = torch.ones((1,1,3,3), dtype=torch.float32, device=device)
|
1102 |
+
|
1103 |
+
for i in range(int(-FaceParserAmount)):
|
1104 |
+
outpred = torch.nn.functional.conv2d(outpred, kernel, padding=(1, 1))
|
1105 |
+
outpred = torch.clamp(outpred, 0, 1)
|
1106 |
+
|
1107 |
+
outpred = torch.squeeze(outpred)
|
1108 |
+
outpred = torch.neg(outpred)
|
1109 |
+
outpred = torch.add(outpred, 1)
|
1110 |
+
|
1111 |
+
outpred = torch.reshape(outpred, (1, 512, 512))
|
1112 |
+
|
1113 |
+
return outpred
|
1114 |
+
|
1115 |
+
|
1116 |
+
|
1117 |
+
def apply_restorer(self, swapped_face_upscaled, parameters):
|
1118 |
+
temp = swapped_face_upscaled
|
1119 |
+
t512 = v2.Resize((512, 512), antialias=False)
|
1120 |
+
t256 = v2.Resize((256, 256), antialias=False)
|
1121 |
+
t1024 = v2.Resize((1024, 1024), antialias=False)
|
1122 |
+
|
1123 |
+
# If using a separate detection mode
|
1124 |
+
if parameters['RestorerDetTypeTextSel'] == 'Blend' or parameters['RestorerDetTypeTextSel'] == 'Reference':
|
1125 |
+
if parameters['RestorerDetTypeTextSel'] == 'Blend':
|
1126 |
+
# Set up Transformation
|
1127 |
+
dst = self.arcface_dst * 4.0
|
1128 |
+
dst[:,0] += 32.0
|
1129 |
+
|
1130 |
+
elif parameters['RestorerDetTypeTextSel'] == 'Reference':
|
1131 |
+
try:
|
1132 |
+
dst = self.models.resnet50(swapped_face_upscaled, score=parameters['DetectScoreSlider']/100.0)
|
1133 |
+
except:
|
1134 |
+
return swapped_face_upscaled
|
1135 |
+
|
1136 |
+
tform = trans.SimilarityTransform()
|
1137 |
+
tform.estimate(dst, self.FFHQ_kps)
|
1138 |
+
|
1139 |
+
# Transform, scale, and normalize
|
1140 |
+
temp = v2.functional.affine(swapped_face_upscaled, tform.rotation*57.2958, (tform.translation[0], tform.translation[1]) , tform.scale, 0, center = (0,0) )
|
1141 |
+
temp = v2.functional.crop(temp, 0,0, 512, 512)
|
1142 |
+
|
1143 |
+
temp = torch.div(temp, 255)
|
1144 |
+
temp = v2.functional.normalize(temp, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=False)
|
1145 |
+
if parameters['RestorerTypeTextSel'] == 'GPEN256':
|
1146 |
+
temp = t256(temp)
|
1147 |
+
temp = torch.unsqueeze(temp, 0).contiguous()
|
1148 |
+
|
1149 |
+
# Bindings
|
1150 |
+
outpred = torch.empty((1,3,512,512), dtype=torch.float32, device=device).contiguous()
|
1151 |
+
|
1152 |
+
if parameters['RestorerTypeTextSel'] == 'GFPGAN':
|
1153 |
+
self.models.run_GFPGAN(temp, outpred)
|
1154 |
+
|
1155 |
+
elif parameters['RestorerTypeTextSel'] == 'CF':
|
1156 |
+
self.models.run_codeformer(temp, outpred)
|
1157 |
+
|
1158 |
+
elif parameters['RestorerTypeTextSel'] == 'GPEN256':
|
1159 |
+
outpred = torch.empty((1,3,256,256), dtype=torch.float32, device=device).contiguous()
|
1160 |
+
self.models.run_GPEN_256(temp, outpred)
|
1161 |
+
|
1162 |
+
elif parameters['RestorerTypeTextSel'] == 'GPEN512':
|
1163 |
+
self.models.run_GPEN_512(temp, outpred)
|
1164 |
+
|
1165 |
+
elif parameters['RestorerTypeTextSel'] == 'GPEN1024':
|
1166 |
+
temp = t1024(temp)
|
1167 |
+
outpred = torch.empty((1, 3, 1024, 1024), dtype=torch.float32, device=device).contiguous()
|
1168 |
+
self.models.run_GPEN_1024(temp, outpred)
|
1169 |
+
|
1170 |
+
# Format back to cxHxW @ 255
|
1171 |
+
outpred = torch.squeeze(outpred)
|
1172 |
+
outpred = torch.clamp(outpred, -1, 1)
|
1173 |
+
outpred = torch.add(outpred, 1)
|
1174 |
+
outpred = torch.div(outpred, 2)
|
1175 |
+
outpred = torch.mul(outpred, 255)
|
1176 |
+
if parameters['RestorerTypeTextSel'] == 'GPEN256':
|
1177 |
+
outpred = t512(outpred)
|
1178 |
+
elif parameters['RestorerTypeTextSel'] == 'GPEN1024':
|
1179 |
+
outpred = t512(outpred)
|
1180 |
+
# Invert Transform
|
1181 |
+
if parameters['RestorerDetTypeTextSel'] == 'Blend' or parameters['RestorerDetTypeTextSel'] == 'Reference':
|
1182 |
+
outpred = v2.functional.affine(outpred, tform.inverse.rotation*57.2958, (tform.inverse.translation[0], tform.inverse.translation[1]), tform.inverse.scale, 0, interpolation=v2.InterpolationMode.BILINEAR, center = (0,0) )
|
1183 |
+
|
1184 |
+
# Blend
|
1185 |
+
alpha = float(parameters["RestorerSlider"])/100.0
|
1186 |
+
outpred = torch.add(torch.mul(outpred, alpha), torch.mul(swapped_face_upscaled, 1-alpha))
|
1187 |
+
|
1188 |
+
return outpred
|
1189 |
+
|
1190 |
+
def apply_fake_diff(self, swapped_face, original_face, DiffAmount):
|
1191 |
+
swapped_face = swapped_face.permute(1,2,0)
|
1192 |
+
original_face = original_face.permute(1,2,0)
|
1193 |
+
|
1194 |
+
diff = swapped_face-original_face
|
1195 |
+
diff = torch.abs(diff)
|
1196 |
+
|
1197 |
+
# Find the diffrence between the swap and original, per channel
|
1198 |
+
fthresh = DiffAmount*2.55
|
1199 |
+
|
1200 |
+
# Bimodal
|
1201 |
+
diff[diff<fthresh] = 0
|
1202 |
+
diff[diff>=fthresh] = 1
|
1203 |
+
|
1204 |
+
# If any of the channels exceeded the threshhold, them add them to the mask
|
1205 |
+
diff = torch.sum(diff, dim=2)
|
1206 |
+
diff = torch.unsqueeze(diff, 2)
|
1207 |
+
diff[diff>0] = 1
|
1208 |
+
|
1209 |
+
diff = diff.permute(2,0,1)
|
1210 |
+
|
1211 |
+
return diff
|
1212 |
+
|
1213 |
+
|
1214 |
+
|
1215 |
+
def clear_mem(self):
|
1216 |
+
del self.swapper_model
|
1217 |
+
del self.GFPGAN_model
|
1218 |
+
del self.occluder_model
|
1219 |
+
del self.face_parsing_model
|
1220 |
+
del self.codeformer_model
|
1221 |
+
del self.GPEN_256_model
|
1222 |
+
del self.GPEN_512_model
|
1223 |
+
del self.GPEN_1024_model
|
1224 |
+
del self.resnet_model
|
1225 |
+
del self.detection_model
|
1226 |
+
del self.recognition_model
|
1227 |
+
|
1228 |
+
self.swapper_model = []
|
1229 |
+
self.GFPGAN_model = []
|
1230 |
+
self.occluder_model = []
|
1231 |
+
self.face_parsing_model = []
|
1232 |
+
self.codeformer_model = []
|
1233 |
+
self.GPEN_256_model = []
|
1234 |
+
self.GPEN_512_model = []
|
1235 |
+
self.GPEN_1024_model = []
|
1236 |
+
self.resnet_model = []
|
1237 |
+
self.detection_model = []
|
1238 |
+
self.recognition_model = []
|
1239 |
+
|
1240 |
+
# test = swap.permute(1, 2, 0)
|
1241 |
+
# test = test.cpu().numpy()
|
1242 |
+
# cv2.imwrite('2.jpg', test)
|
rope/external/cliplib/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
from .clip import *
|
rope/external/cliplib/bpe_simple_vocab_16e6.txt.gz
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a
|
3 |
+
size 1356917
|
rope/external/cliplib/clip.py
ADDED
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import hashlib
|
2 |
+
import os
|
3 |
+
import urllib
|
4 |
+
import warnings
|
5 |
+
from typing import Any, Union, List
|
6 |
+
from pkg_resources import packaging
|
7 |
+
|
8 |
+
import torch
|
9 |
+
from PIL import Image
|
10 |
+
from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
|
11 |
+
from tqdm import tqdm
|
12 |
+
|
13 |
+
from .model import build_model
|
14 |
+
from .simple_tokenizer import SimpleTokenizer as _Tokenizer
|
15 |
+
|
16 |
+
try:
|
17 |
+
from torchvision.transforms import InterpolationMode
|
18 |
+
BICUBIC = InterpolationMode.BICUBIC
|
19 |
+
except ImportError:
|
20 |
+
BICUBIC = Image.BICUBIC
|
21 |
+
|
22 |
+
|
23 |
+
if packaging.version.parse(torch.__version__) < packaging.version.parse("1.7.1"):
|
24 |
+
warnings.warn("PyTorch version 1.7.1 or higher is recommended")
|
25 |
+
|
26 |
+
|
27 |
+
__all__ = ["available_models", "load", "tokenize"]
|
28 |
+
_tokenizer = _Tokenizer()
|
29 |
+
|
30 |
+
_MODELS = {
|
31 |
+
"RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt",
|
32 |
+
"RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt",
|
33 |
+
"RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt",
|
34 |
+
"RN50x16": "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt",
|
35 |
+
"RN50x64": "https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt",
|
36 |
+
"ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt",
|
37 |
+
"ViT-B/16": "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt",
|
38 |
+
"ViT-L/14": "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt",
|
39 |
+
"ViT-L/14@336px": "https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt",
|
40 |
+
}
|
41 |
+
|
42 |
+
|
43 |
+
def _download(url: str, root: str):
|
44 |
+
os.makedirs(root, exist_ok=True)
|
45 |
+
filename = os.path.basename(url)
|
46 |
+
|
47 |
+
expected_sha256 = url.split("/")[-2]
|
48 |
+
download_target = os.path.join(root, filename)
|
49 |
+
|
50 |
+
if os.path.exists(download_target) and not os.path.isfile(download_target):
|
51 |
+
raise RuntimeError(f"{download_target} exists and is not a regular file")
|
52 |
+
|
53 |
+
if os.path.isfile(download_target):
|
54 |
+
if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256:
|
55 |
+
return download_target
|
56 |
+
else:
|
57 |
+
warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
|
58 |
+
|
59 |
+
with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
|
60 |
+
with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True, unit_divisor=1024) as loop:
|
61 |
+
while True:
|
62 |
+
buffer = source.read(8192)
|
63 |
+
if not buffer:
|
64 |
+
break
|
65 |
+
|
66 |
+
output.write(buffer)
|
67 |
+
loop.update(len(buffer))
|
68 |
+
|
69 |
+
if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256:
|
70 |
+
raise RuntimeError("Model has been downloaded but the SHA256 checksum does not not match")
|
71 |
+
|
72 |
+
return download_target
|
73 |
+
|
74 |
+
|
75 |
+
def _convert_image_to_rgb(image):
|
76 |
+
return image.convert("RGB")
|
77 |
+
|
78 |
+
|
79 |
+
def _transform(n_px):
|
80 |
+
return Compose([
|
81 |
+
Resize(n_px, interpolation=BICUBIC),
|
82 |
+
CenterCrop(n_px),
|
83 |
+
_convert_image_to_rgb,
|
84 |
+
ToTensor(),
|
85 |
+
Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
|
86 |
+
])
|
87 |
+
|
88 |
+
|
89 |
+
def available_models() -> List[str]:
|
90 |
+
"""Returns the names of available CLIP models"""
|
91 |
+
return list(_MODELS.keys())
|
92 |
+
|
93 |
+
|
94 |
+
def load(name: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", jit: bool = False, download_root: str = None):
|
95 |
+
"""Load a CLIP model
|
96 |
+
|
97 |
+
Parameters
|
98 |
+
----------
|
99 |
+
name : str
|
100 |
+
A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
|
101 |
+
|
102 |
+
device : Union[str, torch.device]
|
103 |
+
The device to put the loaded model
|
104 |
+
|
105 |
+
jit : bool
|
106 |
+
Whether to load the optimized JIT model or more hackable non-JIT model (default).
|
107 |
+
|
108 |
+
download_root: str
|
109 |
+
path to download the model files; by default, it uses "~/.cache/clip"
|
110 |
+
|
111 |
+
Returns
|
112 |
+
-------
|
113 |
+
model : torch.nn.Module
|
114 |
+
The CLIP model
|
115 |
+
|
116 |
+
preprocess : Callable[[PIL.Image], torch.Tensor]
|
117 |
+
A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
|
118 |
+
"""
|
119 |
+
if name in _MODELS:
|
120 |
+
model_path = _download(_MODELS[name], download_root or os.path.expanduser("~/.cache/clip"))
|
121 |
+
elif os.path.isfile(name):
|
122 |
+
model_path = name
|
123 |
+
else:
|
124 |
+
raise RuntimeError(f"Model {name} not found; available models = {available_models()}")
|
125 |
+
|
126 |
+
with open(model_path, 'rb') as opened_file:
|
127 |
+
try:
|
128 |
+
# loading JIT archive
|
129 |
+
model = torch.jit.load(opened_file, map_location=device if jit else "cpu").eval()
|
130 |
+
state_dict = None
|
131 |
+
except RuntimeError:
|
132 |
+
# loading saved state dict
|
133 |
+
if jit:
|
134 |
+
warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead")
|
135 |
+
jit = False
|
136 |
+
state_dict = torch.load(opened_file, map_location="cpu")
|
137 |
+
|
138 |
+
if not jit:
|
139 |
+
model = build_model(state_dict or model.state_dict()).to(device)
|
140 |
+
if str(device) == "cpu":
|
141 |
+
model.float()
|
142 |
+
return model, _transform(model.visual.input_resolution)
|
143 |
+
|
144 |
+
# patch the device names
|
145 |
+
device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[])
|
146 |
+
device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1]
|
147 |
+
|
148 |
+
def _node_get(node: torch._C.Node, key: str):
|
149 |
+
"""Gets attributes of a node which is polymorphic over return type.
|
150 |
+
|
151 |
+
From https://github.com/pytorch/pytorch/pull/82628
|
152 |
+
"""
|
153 |
+
sel = node.kindOf(key)
|
154 |
+
return getattr(node, sel)(key)
|
155 |
+
|
156 |
+
def patch_device(module):
|
157 |
+
try:
|
158 |
+
graphs = [module.graph] if hasattr(module, "graph") else []
|
159 |
+
except RuntimeError:
|
160 |
+
graphs = []
|
161 |
+
|
162 |
+
if hasattr(module, "forward1"):
|
163 |
+
graphs.append(module.forward1.graph)
|
164 |
+
|
165 |
+
for graph in graphs:
|
166 |
+
for node in graph.findAllNodes("prim::Constant"):
|
167 |
+
if "value" in node.attributeNames() and str(_node_get(node, "value")).startswith("cuda"):
|
168 |
+
node.copyAttributes(device_node)
|
169 |
+
|
170 |
+
model.apply(patch_device)
|
171 |
+
patch_device(model.encode_image)
|
172 |
+
patch_device(model.encode_text)
|
173 |
+
|
174 |
+
# patch dtype to float32 on CPU
|
175 |
+
if str(device) == "cpu":
|
176 |
+
float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[])
|
177 |
+
float_input = list(float_holder.graph.findNode("aten::to").inputs())[1]
|
178 |
+
float_node = float_input.node()
|
179 |
+
|
180 |
+
def patch_float(module):
|
181 |
+
try:
|
182 |
+
graphs = [module.graph] if hasattr(module, "graph") else []
|
183 |
+
except RuntimeError:
|
184 |
+
graphs = []
|
185 |
+
|
186 |
+
if hasattr(module, "forward1"):
|
187 |
+
graphs.append(module.forward1.graph)
|
188 |
+
|
189 |
+
for graph in graphs:
|
190 |
+
for node in graph.findAllNodes("aten::to"):
|
191 |
+
inputs = list(node.inputs())
|
192 |
+
for i in [1, 2]: # dtype can be the second or third argument to aten::to()
|
193 |
+
if _node_get(inputs[i].node(), "value") == 5:
|
194 |
+
inputs[i].node().copyAttributes(float_node)
|
195 |
+
|
196 |
+
model.apply(patch_float)
|
197 |
+
patch_float(model.encode_image)
|
198 |
+
patch_float(model.encode_text)
|
199 |
+
|
200 |
+
model.float()
|
201 |
+
|
202 |
+
return model, _transform(model.input_resolution.item())
|
203 |
+
|
204 |
+
|
205 |
+
def tokenize(texts: Union[str, List[str]], context_length: int = 77, truncate: bool = False) -> Union[torch.IntTensor, torch.LongTensor]:
|
206 |
+
"""
|
207 |
+
Returns the tokenized representation of given input string(s)
|
208 |
+
|
209 |
+
Parameters
|
210 |
+
----------
|
211 |
+
texts : Union[str, List[str]]
|
212 |
+
An input string or a list of input strings to tokenize
|
213 |
+
|
214 |
+
context_length : int
|
215 |
+
The context length to use; all CLIP models use 77 as the context length
|
216 |
+
|
217 |
+
truncate: bool
|
218 |
+
Whether to truncate the text in case its encoding is longer than the context length
|
219 |
+
|
220 |
+
Returns
|
221 |
+
-------
|
222 |
+
A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length].
|
223 |
+
We return LongTensor when torch version is <1.8.0, since older index_select requires indices to be long.
|
224 |
+
"""
|
225 |
+
if isinstance(texts, str):
|
226 |
+
texts = [texts]
|
227 |
+
|
228 |
+
sot_token = _tokenizer.encoder["<|startoftext|>"]
|
229 |
+
eot_token = _tokenizer.encoder["<|endoftext|>"]
|
230 |
+
all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts]
|
231 |
+
if packaging.version.parse(torch.__version__) < packaging.version.parse("1.8.0"):
|
232 |
+
result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
|
233 |
+
else:
|
234 |
+
result = torch.zeros(len(all_tokens), context_length, dtype=torch.int)
|
235 |
+
|
236 |
+
for i, tokens in enumerate(all_tokens):
|
237 |
+
if len(tokens) > context_length:
|
238 |
+
if truncate:
|
239 |
+
tokens = tokens[:context_length]
|
240 |
+
tokens[-1] = eot_token
|
241 |
+
else:
|
242 |
+
raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}")
|
243 |
+
result[i, :len(tokens)] = torch.tensor(tokens)
|
244 |
+
|
245 |
+
return result
|
rope/external/cliplib/model.py
ADDED
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from collections import OrderedDict
|
2 |
+
from typing import Tuple, Union
|
3 |
+
|
4 |
+
import numpy as np
|
5 |
+
import torch
|
6 |
+
import torch.nn.functional as F
|
7 |
+
from torch import nn
|
8 |
+
|
9 |
+
|
10 |
+
class Bottleneck(nn.Module):
|
11 |
+
expansion = 4
|
12 |
+
|
13 |
+
def __init__(self, inplanes, planes, stride=1):
|
14 |
+
super().__init__()
|
15 |
+
|
16 |
+
# all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
|
17 |
+
self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
|
18 |
+
self.bn1 = nn.BatchNorm2d(planes)
|
19 |
+
self.relu1 = nn.ReLU(inplace=True)
|
20 |
+
|
21 |
+
self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
|
22 |
+
self.bn2 = nn.BatchNorm2d(planes)
|
23 |
+
self.relu2 = nn.ReLU(inplace=True)
|
24 |
+
|
25 |
+
self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
|
26 |
+
|
27 |
+
self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
|
28 |
+
self.bn3 = nn.BatchNorm2d(planes * self.expansion)
|
29 |
+
self.relu3 = nn.ReLU(inplace=True)
|
30 |
+
|
31 |
+
self.downsample = None
|
32 |
+
self.stride = stride
|
33 |
+
|
34 |
+
if stride > 1 or inplanes != planes * Bottleneck.expansion:
|
35 |
+
# downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
|
36 |
+
self.downsample = nn.Sequential(OrderedDict([
|
37 |
+
("-1", nn.AvgPool2d(stride)),
|
38 |
+
("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
|
39 |
+
("1", nn.BatchNorm2d(planes * self.expansion))
|
40 |
+
]))
|
41 |
+
|
42 |
+
def forward(self, x: torch.Tensor):
|
43 |
+
identity = x
|
44 |
+
|
45 |
+
out = self.relu1(self.bn1(self.conv1(x)))
|
46 |
+
out = self.relu2(self.bn2(self.conv2(out)))
|
47 |
+
out = self.avgpool(out)
|
48 |
+
out = self.bn3(self.conv3(out))
|
49 |
+
|
50 |
+
if self.downsample is not None:
|
51 |
+
identity = self.downsample(x)
|
52 |
+
|
53 |
+
out += identity
|
54 |
+
out = self.relu3(out)
|
55 |
+
return out
|
56 |
+
|
57 |
+
|
58 |
+
class AttentionPool2d(nn.Module):
|
59 |
+
def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
|
60 |
+
super().__init__()
|
61 |
+
self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
|
62 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim)
|
63 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim)
|
64 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim)
|
65 |
+
self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
|
66 |
+
self.num_heads = num_heads
|
67 |
+
|
68 |
+
def forward(self, x):
|
69 |
+
x = x.flatten(start_dim=2).permute(2, 0, 1) # NCHW -> (HW)NC
|
70 |
+
x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
|
71 |
+
x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
|
72 |
+
x, _ = F.multi_head_attention_forward(
|
73 |
+
query=x[:1], key=x, value=x,
|
74 |
+
embed_dim_to_check=x.shape[-1],
|
75 |
+
num_heads=self.num_heads,
|
76 |
+
q_proj_weight=self.q_proj.weight,
|
77 |
+
k_proj_weight=self.k_proj.weight,
|
78 |
+
v_proj_weight=self.v_proj.weight,
|
79 |
+
in_proj_weight=None,
|
80 |
+
in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
|
81 |
+
bias_k=None,
|
82 |
+
bias_v=None,
|
83 |
+
add_zero_attn=False,
|
84 |
+
dropout_p=0,
|
85 |
+
out_proj_weight=self.c_proj.weight,
|
86 |
+
out_proj_bias=self.c_proj.bias,
|
87 |
+
use_separate_proj_weight=True,
|
88 |
+
training=self.training,
|
89 |
+
need_weights=False
|
90 |
+
)
|
91 |
+
return x.squeeze(0)
|
92 |
+
|
93 |
+
|
94 |
+
class ModifiedResNet(nn.Module):
|
95 |
+
"""
|
96 |
+
A ResNet class that is similar to torchvision's but contains the following changes:
|
97 |
+
- There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
|
98 |
+
- Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
|
99 |
+
- The final pooling layer is a QKV attention instead of an average pool
|
100 |
+
"""
|
101 |
+
|
102 |
+
def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
|
103 |
+
super().__init__()
|
104 |
+
self.output_dim = output_dim
|
105 |
+
self.input_resolution = input_resolution
|
106 |
+
|
107 |
+
# the 3-layer stem
|
108 |
+
self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
|
109 |
+
self.bn1 = nn.BatchNorm2d(width // 2)
|
110 |
+
self.relu1 = nn.ReLU(inplace=True)
|
111 |
+
self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
|
112 |
+
self.bn2 = nn.BatchNorm2d(width // 2)
|
113 |
+
self.relu2 = nn.ReLU(inplace=True)
|
114 |
+
self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
|
115 |
+
self.bn3 = nn.BatchNorm2d(width)
|
116 |
+
self.relu3 = nn.ReLU(inplace=True)
|
117 |
+
self.avgpool = nn.AvgPool2d(2)
|
118 |
+
|
119 |
+
# residual layers
|
120 |
+
self._inplanes = width # this is a *mutable* variable used during construction
|
121 |
+
self.layer1 = self._make_layer(width, layers[0])
|
122 |
+
self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
|
123 |
+
self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
|
124 |
+
self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
|
125 |
+
|
126 |
+
embed_dim = width * 32 # the ResNet feature dimension
|
127 |
+
self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
|
128 |
+
|
129 |
+
def _make_layer(self, planes, blocks, stride=1):
|
130 |
+
layers = [Bottleneck(self._inplanes, planes, stride)]
|
131 |
+
|
132 |
+
self._inplanes = planes * Bottleneck.expansion
|
133 |
+
for _ in range(1, blocks):
|
134 |
+
layers.append(Bottleneck(self._inplanes, planes))
|
135 |
+
|
136 |
+
return nn.Sequential(*layers)
|
137 |
+
|
138 |
+
def forward(self, x):
|
139 |
+
def stem(x):
|
140 |
+
x = self.relu1(self.bn1(self.conv1(x)))
|
141 |
+
x = self.relu2(self.bn2(self.conv2(x)))
|
142 |
+
x = self.relu3(self.bn3(self.conv3(x)))
|
143 |
+
x = self.avgpool(x)
|
144 |
+
return x
|
145 |
+
|
146 |
+
x = x.type(self.conv1.weight.dtype)
|
147 |
+
x = stem(x)
|
148 |
+
x = self.layer1(x)
|
149 |
+
x = self.layer2(x)
|
150 |
+
x = self.layer3(x)
|
151 |
+
x = self.layer4(x)
|
152 |
+
x = self.attnpool(x)
|
153 |
+
|
154 |
+
return x
|
155 |
+
|
156 |
+
|
157 |
+
class LayerNorm(nn.LayerNorm):
|
158 |
+
"""Subclass torch's LayerNorm to handle fp16."""
|
159 |
+
|
160 |
+
def forward(self, x: torch.Tensor):
|
161 |
+
orig_type = x.dtype
|
162 |
+
ret = super().forward(x.type(torch.float32))
|
163 |
+
return ret.type(orig_type)
|
164 |
+
|
165 |
+
|
166 |
+
class QuickGELU(nn.Module):
|
167 |
+
def forward(self, x: torch.Tensor):
|
168 |
+
return x * torch.sigmoid(1.702 * x)
|
169 |
+
|
170 |
+
|
171 |
+
class ResidualAttentionBlock(nn.Module):
|
172 |
+
def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
|
173 |
+
super().__init__()
|
174 |
+
|
175 |
+
self.attn = nn.MultiheadAttention(d_model, n_head)
|
176 |
+
self.ln_1 = LayerNorm(d_model)
|
177 |
+
self.mlp = nn.Sequential(OrderedDict([
|
178 |
+
("c_fc", nn.Linear(d_model, d_model * 4)),
|
179 |
+
("gelu", QuickGELU()),
|
180 |
+
("c_proj", nn.Linear(d_model * 4, d_model))
|
181 |
+
]))
|
182 |
+
self.ln_2 = LayerNorm(d_model)
|
183 |
+
self.attn_mask = attn_mask
|
184 |
+
|
185 |
+
def attention(self, x: torch.Tensor):
|
186 |
+
self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
|
187 |
+
return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
|
188 |
+
|
189 |
+
def forward(self, x: torch.Tensor):
|
190 |
+
x = x + self.attention(self.ln_1(x))
|
191 |
+
x = x + self.mlp(self.ln_2(x))
|
192 |
+
return x
|
193 |
+
|
194 |
+
|
195 |
+
class Transformer(nn.Module):
|
196 |
+
def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):
|
197 |
+
super().__init__()
|
198 |
+
self.width = width
|
199 |
+
self.layers = layers
|
200 |
+
self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])
|
201 |
+
|
202 |
+
def forward(self, x: torch.Tensor):
|
203 |
+
return self.resblocks(x)
|
204 |
+
|
205 |
+
|
206 |
+
class VisionTransformer(nn.Module):
|
207 |
+
def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int):
|
208 |
+
super().__init__()
|
209 |
+
self.input_resolution = input_resolution
|
210 |
+
self.output_dim = output_dim
|
211 |
+
self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
|
212 |
+
|
213 |
+
scale = width ** -0.5
|
214 |
+
self.class_embedding = nn.Parameter(scale * torch.randn(width))
|
215 |
+
self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
|
216 |
+
self.ln_pre = LayerNorm(width)
|
217 |
+
|
218 |
+
self.transformer = Transformer(width, layers, heads)
|
219 |
+
|
220 |
+
self.ln_post = LayerNorm(width)
|
221 |
+
self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
|
222 |
+
|
223 |
+
def forward(self, x: torch.Tensor):
|
224 |
+
x = self.conv1(x) # shape = [*, width, grid, grid]
|
225 |
+
x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
|
226 |
+
x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
|
227 |
+
x = torch.cat([self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width]
|
228 |
+
x = x + self.positional_embedding.to(x.dtype)
|
229 |
+
x = self.ln_pre(x)
|
230 |
+
|
231 |
+
x = x.permute(1, 0, 2) # NLD -> LND
|
232 |
+
x = self.transformer(x)
|
233 |
+
x = x.permute(1, 0, 2) # LND -> NLD
|
234 |
+
|
235 |
+
x = self.ln_post(x[:, 0, :])
|
236 |
+
|
237 |
+
if self.proj is not None:
|
238 |
+
x = x @ self.proj
|
239 |
+
|
240 |
+
return x
|
241 |
+
|
242 |
+
|
243 |
+
class CLIP(nn.Module):
|
244 |
+
def __init__(self,
|
245 |
+
embed_dim: int,
|
246 |
+
# vision
|
247 |
+
image_resolution: int,
|
248 |
+
vision_layers: Union[Tuple[int, int, int, int], int],
|
249 |
+
vision_width: int,
|
250 |
+
vision_patch_size: int,
|
251 |
+
# text
|
252 |
+
context_length: int,
|
253 |
+
vocab_size: int,
|
254 |
+
transformer_width: int,
|
255 |
+
transformer_heads: int,
|
256 |
+
transformer_layers: int
|
257 |
+
):
|
258 |
+
super().__init__()
|
259 |
+
|
260 |
+
self.context_length = context_length
|
261 |
+
|
262 |
+
if isinstance(vision_layers, (tuple, list)):
|
263 |
+
vision_heads = vision_width * 32 // 64
|
264 |
+
self.visual = ModifiedResNet(
|
265 |
+
layers=vision_layers,
|
266 |
+
output_dim=embed_dim,
|
267 |
+
heads=vision_heads,
|
268 |
+
input_resolution=image_resolution,
|
269 |
+
width=vision_width
|
270 |
+
)
|
271 |
+
else:
|
272 |
+
vision_heads = vision_width // 64
|
273 |
+
self.visual = VisionTransformer(
|
274 |
+
input_resolution=image_resolution,
|
275 |
+
patch_size=vision_patch_size,
|
276 |
+
width=vision_width,
|
277 |
+
layers=vision_layers,
|
278 |
+
heads=vision_heads,
|
279 |
+
output_dim=embed_dim
|
280 |
+
)
|
281 |
+
|
282 |
+
self.transformer = Transformer(
|
283 |
+
width=transformer_width,
|
284 |
+
layers=transformer_layers,
|
285 |
+
heads=transformer_heads,
|
286 |
+
attn_mask=self.build_attention_mask()
|
287 |
+
)
|
288 |
+
|
289 |
+
self.vocab_size = vocab_size
|
290 |
+
self.token_embedding = nn.Embedding(vocab_size, transformer_width)
|
291 |
+
self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))
|
292 |
+
self.ln_final = LayerNorm(transformer_width)
|
293 |
+
|
294 |
+
self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
|
295 |
+
self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
|
296 |
+
|
297 |
+
self.initialize_parameters()
|
298 |
+
|
299 |
+
def initialize_parameters(self):
|
300 |
+
nn.init.normal_(self.token_embedding.weight, std=0.02)
|
301 |
+
nn.init.normal_(self.positional_embedding, std=0.01)
|
302 |
+
|
303 |
+
if isinstance(self.visual, ModifiedResNet):
|
304 |
+
if self.visual.attnpool is not None:
|
305 |
+
std = self.visual.attnpool.c_proj.in_features ** -0.5
|
306 |
+
nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std)
|
307 |
+
nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std)
|
308 |
+
nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std)
|
309 |
+
nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)
|
310 |
+
|
311 |
+
for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]:
|
312 |
+
for name, param in resnet_block.named_parameters():
|
313 |
+
if name.endswith("bn3.weight"):
|
314 |
+
nn.init.zeros_(param)
|
315 |
+
|
316 |
+
proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
|
317 |
+
attn_std = self.transformer.width ** -0.5
|
318 |
+
fc_std = (2 * self.transformer.width) ** -0.5
|
319 |
+
for block in self.transformer.resblocks:
|
320 |
+
nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
|
321 |
+
nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
|
322 |
+
nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
|
323 |
+
nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
|
324 |
+
|
325 |
+
if self.text_projection is not None:
|
326 |
+
nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
|
327 |
+
|
328 |
+
def build_attention_mask(self):
|
329 |
+
# lazily create causal attention mask, with full attention between the vision tokens
|
330 |
+
# pytorch uses additive attention mask; fill with -inf
|
331 |
+
mask = torch.empty(self.context_length, self.context_length)
|
332 |
+
mask.fill_(float("-inf"))
|
333 |
+
mask.triu_(1) # zero out the lower diagonal
|
334 |
+
return mask
|
335 |
+
|
336 |
+
@property
|
337 |
+
def dtype(self):
|
338 |
+
return self.visual.conv1.weight.dtype
|
339 |
+
|
340 |
+
def encode_image(self, image):
|
341 |
+
return self.visual(image.type(self.dtype))
|
342 |
+
|
343 |
+
def encode_text(self, text):
|
344 |
+
x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
|
345 |
+
|
346 |
+
x = x + self.positional_embedding.type(self.dtype)
|
347 |
+
x = x.permute(1, 0, 2) # NLD -> LND
|
348 |
+
x = self.transformer(x)
|
349 |
+
x = x.permute(1, 0, 2) # LND -> NLD
|
350 |
+
x = self.ln_final(x).type(self.dtype)
|
351 |
+
|
352 |
+
# x.shape = [batch_size, n_ctx, transformer.width]
|
353 |
+
# take features from the eot embedding (eot_token is the highest number in each sequence)
|
354 |
+
x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
|
355 |
+
|
356 |
+
return x
|
357 |
+
|
358 |
+
def forward(self, image, text):
|
359 |
+
image_features = self.encode_image(image)
|
360 |
+
text_features = self.encode_text(text)
|
361 |
+
|
362 |
+
# normalized features
|
363 |
+
image_features = image_features / image_features.norm(dim=1, keepdim=True)
|
364 |
+
text_features = text_features / text_features.norm(dim=1, keepdim=True)
|
365 |
+
|
366 |
+
# cosine similarity as logits
|
367 |
+
logit_scale = self.logit_scale.exp()
|
368 |
+
logits_per_image = logit_scale * image_features @ text_features.t()
|
369 |
+
logits_per_text = logits_per_image.t()
|
370 |
+
|
371 |
+
# shape = [global_batch_size, global_batch_size]
|
372 |
+
return logits_per_image, logits_per_text
|
373 |
+
|
374 |
+
|
375 |
+
def convert_weights(model: nn.Module):
|
376 |
+
"""Convert applicable model parameters to fp16"""
|
377 |
+
|
378 |
+
def _convert_weights_to_fp16(l):
|
379 |
+
if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
|
380 |
+
l.weight.data = l.weight.data.half()
|
381 |
+
if l.bias is not None:
|
382 |
+
l.bias.data = l.bias.data.half()
|
383 |
+
|
384 |
+
if isinstance(l, nn.MultiheadAttention):
|
385 |
+
for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
|
386 |
+
tensor = getattr(l, attr)
|
387 |
+
if tensor is not None:
|
388 |
+
tensor.data = tensor.data.half()
|
389 |
+
|
390 |
+
for name in ["text_projection", "proj"]:
|
391 |
+
if hasattr(l, name):
|
392 |
+
attr = getattr(l, name)
|
393 |
+
if attr is not None:
|
394 |
+
attr.data = attr.data.half()
|
395 |
+
|
396 |
+
model.apply(_convert_weights_to_fp16)
|
397 |
+
|
398 |
+
|
399 |
+
def build_model(state_dict: dict):
|
400 |
+
vit = "visual.proj" in state_dict
|
401 |
+
|
402 |
+
if vit:
|
403 |
+
vision_width = state_dict["visual.conv1.weight"].shape[0]
|
404 |
+
vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
|
405 |
+
vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
|
406 |
+
grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
|
407 |
+
image_resolution = vision_patch_size * grid_size
|
408 |
+
else:
|
409 |
+
counts: list = [len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]]
|
410 |
+
vision_layers = tuple(counts)
|
411 |
+
vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
|
412 |
+
output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
|
413 |
+
vision_patch_size = None
|
414 |
+
assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
|
415 |
+
image_resolution = output_width * 32
|
416 |
+
|
417 |
+
embed_dim = state_dict["text_projection"].shape[1]
|
418 |
+
context_length = state_dict["positional_embedding"].shape[0]
|
419 |
+
vocab_size = state_dict["token_embedding.weight"].shape[0]
|
420 |
+
transformer_width = state_dict["ln_final.weight"].shape[0]
|
421 |
+
transformer_heads = transformer_width // 64
|
422 |
+
transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith("transformer.resblocks")))
|
423 |
+
|
424 |
+
model = CLIP(
|
425 |
+
embed_dim,
|
426 |
+
image_resolution, vision_layers, vision_width, vision_patch_size,
|
427 |
+
context_length, vocab_size, transformer_width, transformer_heads, transformer_layers
|
428 |
+
)
|
429 |
+
|
430 |
+
for key in ["input_resolution", "context_length", "vocab_size"]:
|
431 |
+
if key in state_dict:
|
432 |
+
del state_dict[key]
|
433 |
+
|
434 |
+
convert_weights(model)
|
435 |
+
model.load_state_dict(state_dict)
|
436 |
+
return model.eval()
|
rope/external/cliplib/simple_tokenizer.py
ADDED
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gzip
|
2 |
+
import html
|
3 |
+
import os
|
4 |
+
from functools import lru_cache
|
5 |
+
|
6 |
+
import ftfy
|
7 |
+
import regex as re
|
8 |
+
|
9 |
+
|
10 |
+
@lru_cache()
|
11 |
+
def default_bpe():
|
12 |
+
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
|
13 |
+
|
14 |
+
|
15 |
+
@lru_cache()
|
16 |
+
def bytes_to_unicode():
|
17 |
+
"""
|
18 |
+
Returns list of utf-8 byte and a corresponding list of unicode strings.
|
19 |
+
The reversible bpe codes work on unicode strings.
|
20 |
+
This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
|
21 |
+
When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
|
22 |
+
This is a signficant percentage of your normal, say, 32K bpe vocab.
|
23 |
+
To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
|
24 |
+
And avoids mapping to whitespace/control characters the bpe code barfs on.
|
25 |
+
"""
|
26 |
+
bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1))
|
27 |
+
cs = bs[:]
|
28 |
+
n = 0
|
29 |
+
for b in range(2**8):
|
30 |
+
if b not in bs:
|
31 |
+
bs.append(b)
|
32 |
+
cs.append(2**8+n)
|
33 |
+
n += 1
|
34 |
+
cs = [chr(n) for n in cs]
|
35 |
+
return dict(zip(bs, cs))
|
36 |
+
|
37 |
+
|
38 |
+
def get_pairs(word):
|
39 |
+
"""Return set of symbol pairs in a word.
|
40 |
+
Word is represented as tuple of symbols (symbols being variable-length strings).
|
41 |
+
"""
|
42 |
+
pairs = set()
|
43 |
+
prev_char = word[0]
|
44 |
+
for char in word[1:]:
|
45 |
+
pairs.add((prev_char, char))
|
46 |
+
prev_char = char
|
47 |
+
return pairs
|
48 |
+
|
49 |
+
|
50 |
+
def basic_clean(text):
|
51 |
+
text = ftfy.fix_text(text)
|
52 |
+
text = html.unescape(html.unescape(text))
|
53 |
+
return text.strip()
|
54 |
+
|
55 |
+
|
56 |
+
def whitespace_clean(text):
|
57 |
+
text = re.sub(r'\s+', ' ', text)
|
58 |
+
text = text.strip()
|
59 |
+
return text
|
60 |
+
|
61 |
+
|
62 |
+
class SimpleTokenizer(object):
|
63 |
+
def __init__(self, bpe_path: str = default_bpe()):
|
64 |
+
self.byte_encoder = bytes_to_unicode()
|
65 |
+
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
|
66 |
+
merges = gzip.open(bpe_path).read().decode("utf-8").split('\n')
|
67 |
+
merges = merges[1:49152-256-2+1]
|
68 |
+
merges = [tuple(merge.split()) for merge in merges]
|
69 |
+
vocab = list(bytes_to_unicode().values())
|
70 |
+
vocab = vocab + [v+'</w>' for v in vocab]
|
71 |
+
for merge in merges:
|
72 |
+
vocab.append(''.join(merge))
|
73 |
+
vocab.extend(['<|startoftext|>', '<|endoftext|>'])
|
74 |
+
self.encoder = dict(zip(vocab, range(len(vocab))))
|
75 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
76 |
+
self.bpe_ranks = dict(zip(merges, range(len(merges))))
|
77 |
+
self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'}
|
78 |
+
self.pat = re.compile(r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE)
|
79 |
+
|
80 |
+
def bpe(self, token):
|
81 |
+
if token in self.cache:
|
82 |
+
return self.cache[token]
|
83 |
+
word = tuple(token[:-1]) + ( token[-1] + '</w>',)
|
84 |
+
pairs = get_pairs(word)
|
85 |
+
|
86 |
+
if not pairs:
|
87 |
+
return token+'</w>'
|
88 |
+
|
89 |
+
while True:
|
90 |
+
bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf')))
|
91 |
+
if bigram not in self.bpe_ranks:
|
92 |
+
break
|
93 |
+
first, second = bigram
|
94 |
+
new_word = []
|
95 |
+
i = 0
|
96 |
+
while i < len(word):
|
97 |
+
try:
|
98 |
+
j = word.index(first, i)
|
99 |
+
new_word.extend(word[i:j])
|
100 |
+
i = j
|
101 |
+
except:
|
102 |
+
new_word.extend(word[i:])
|
103 |
+
break
|
104 |
+
|
105 |
+
if word[i] == first and i < len(word)-1 and word[i+1] == second:
|
106 |
+
new_word.append(first+second)
|
107 |
+
i += 2
|
108 |
+
else:
|
109 |
+
new_word.append(word[i])
|
110 |
+
i += 1
|
111 |
+
new_word = tuple(new_word)
|
112 |
+
word = new_word
|
113 |
+
if len(word) == 1:
|
114 |
+
break
|
115 |
+
else:
|
116 |
+
pairs = get_pairs(word)
|
117 |
+
word = ' '.join(word)
|
118 |
+
self.cache[token] = word
|
119 |
+
return word
|
120 |
+
|
121 |
+
def encode(self, text):
|
122 |
+
bpe_tokens = []
|
123 |
+
text = whitespace_clean(basic_clean(text)).lower()
|
124 |
+
for token in re.findall(self.pat, text):
|
125 |
+
token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))
|
126 |
+
bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))
|
127 |
+
return bpe_tokens
|
128 |
+
|
129 |
+
def decode(self, tokens):
|
130 |
+
text = ''.join([self.decoder[token] for token in tokens])
|
131 |
+
text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('</w>', ' ')
|
132 |
+
return text
|
rope/external/clipseg.py
ADDED
@@ -0,0 +1,538 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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os.path import basename, dirname, join, isfile
|
3 |
+
import torch
|
4 |
+
from torch import nn
|
5 |
+
from torch.nn import functional as nnf
|
6 |
+
from torch.nn.modules.activation import ReLU
|
7 |
+
|
8 |
+
|
9 |
+
def get_prompt_list(prompt):
|
10 |
+
if prompt == 'plain':
|
11 |
+
return ['{}']
|
12 |
+
elif prompt == 'fixed':
|
13 |
+
return ['a photo of a {}.']
|
14 |
+
elif prompt == 'shuffle':
|
15 |
+
return ['a photo of a {}.', 'a photograph of a {}.', 'an image of a {}.', '{}.']
|
16 |
+
elif prompt == 'shuffle+':
|
17 |
+
return ['a photo of a {}.', 'a photograph of a {}.', 'an image of a {}.', '{}.',
|
18 |
+
'a cropped photo of a {}.', 'a good photo of a {}.', 'a photo of one {}.',
|
19 |
+
'a bad photo of a {}.', 'a photo of the {}.']
|
20 |
+
else:
|
21 |
+
raise ValueError('Invalid value for prompt')
|
22 |
+
|
23 |
+
|
24 |
+
def forward_multihead_attention(x, b, with_aff=False, attn_mask=None):
|
25 |
+
"""
|
26 |
+
Simplified version of multihead attention (taken from torch source code but without tons of if clauses).
|
27 |
+
The mlp and layer norm come from CLIP.
|
28 |
+
x: input.
|
29 |
+
b: multihead attention module.
|
30 |
+
"""
|
31 |
+
|
32 |
+
x_ = b.ln_1(x)
|
33 |
+
q, k, v = nnf.linear(x_, b.attn.in_proj_weight, b.attn.in_proj_bias).chunk(3, dim=-1)
|
34 |
+
tgt_len, bsz, embed_dim = q.size()
|
35 |
+
|
36 |
+
head_dim = embed_dim // b.attn.num_heads
|
37 |
+
scaling = float(head_dim) ** -0.5
|
38 |
+
|
39 |
+
q = q.contiguous().view(tgt_len, bsz * b.attn.num_heads, b.attn.head_dim).transpose(0, 1)
|
40 |
+
k = k.contiguous().view(-1, bsz * b.attn.num_heads, b.attn.head_dim).transpose(0, 1)
|
41 |
+
v = v.contiguous().view(-1, bsz * b.attn.num_heads, b.attn.head_dim).transpose(0, 1)
|
42 |
+
|
43 |
+
q = q * scaling
|
44 |
+
|
45 |
+
attn_output_weights = torch.bmm(q, k.transpose(1, 2)) # n_heads * batch_size, tokens^2, tokens^2
|
46 |
+
if attn_mask is not None:
|
47 |
+
|
48 |
+
|
49 |
+
attn_mask_type, attn_mask = attn_mask
|
50 |
+
n_heads = attn_output_weights.size(0) // attn_mask.size(0)
|
51 |
+
attn_mask = attn_mask.repeat(n_heads, 1)
|
52 |
+
|
53 |
+
if attn_mask_type == 'cls_token':
|
54 |
+
# the mask only affects similarities compared to the readout-token.
|
55 |
+
attn_output_weights[:, 0, 1:] = attn_output_weights[:, 0, 1:] * attn_mask[None,...]
|
56 |
+
# attn_output_weights[:, 0, 0] = 0*attn_output_weights[:, 0, 0]
|
57 |
+
|
58 |
+
if attn_mask_type == 'all':
|
59 |
+
# print(attn_output_weights.shape, attn_mask[:, None].shape)
|
60 |
+
attn_output_weights[:, 1:, 1:] = attn_output_weights[:, 1:, 1:] * attn_mask[:, None]
|
61 |
+
|
62 |
+
|
63 |
+
attn_output_weights = torch.softmax(attn_output_weights, dim=-1)
|
64 |
+
|
65 |
+
attn_output = torch.bmm(attn_output_weights, v)
|
66 |
+
attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
|
67 |
+
attn_output = b.attn.out_proj(attn_output)
|
68 |
+
|
69 |
+
x = x + attn_output
|
70 |
+
x = x + b.mlp(b.ln_2(x))
|
71 |
+
|
72 |
+
if with_aff:
|
73 |
+
return x, attn_output_weights
|
74 |
+
else:
|
75 |
+
return x
|
76 |
+
|
77 |
+
|
78 |
+
class CLIPDenseBase(nn.Module):
|
79 |
+
|
80 |
+
def __init__(self, version, reduce_cond, reduce_dim, prompt, n_tokens):
|
81 |
+
super().__init__()
|
82 |
+
|
83 |
+
from rope.external.cliplib import clip
|
84 |
+
|
85 |
+
# prec = torch.FloatTensor
|
86 |
+
self.clip_model, _ = clip.load(version, device='cpu', jit=False)
|
87 |
+
self.model = self.clip_model.visual
|
88 |
+
|
89 |
+
# if not None, scale conv weights such that we obtain n_tokens.
|
90 |
+
self.n_tokens = n_tokens
|
91 |
+
|
92 |
+
for p in self.clip_model.parameters():
|
93 |
+
p.requires_grad_(False)
|
94 |
+
|
95 |
+
# conditional
|
96 |
+
if reduce_cond is not None:
|
97 |
+
self.reduce_cond = nn.Linear(512, reduce_cond)
|
98 |
+
for p in self.reduce_cond.parameters():
|
99 |
+
p.requires_grad_(False)
|
100 |
+
else:
|
101 |
+
self.reduce_cond = None
|
102 |
+
|
103 |
+
self.film_mul = nn.Linear(512 if reduce_cond is None else reduce_cond, reduce_dim)
|
104 |
+
self.film_add = nn.Linear(512 if reduce_cond is None else reduce_cond, reduce_dim)
|
105 |
+
|
106 |
+
self.reduce = nn.Linear(768, reduce_dim)
|
107 |
+
|
108 |
+
self.prompt_list = get_prompt_list(prompt)
|
109 |
+
|
110 |
+
# precomputed prompts
|
111 |
+
import pickle
|
112 |
+
if isfile('precomputed_prompt_vectors.pickle'):
|
113 |
+
precomp = pickle.load(open('precomputed_prompt_vectors.pickle', 'rb'))
|
114 |
+
self.precomputed_prompts = {k: torch.from_numpy(v) for k, v in precomp.items()}
|
115 |
+
else:
|
116 |
+
self.precomputed_prompts = dict()
|
117 |
+
|
118 |
+
def rescaled_pos_emb(self, new_size):
|
119 |
+
assert len(new_size) == 2
|
120 |
+
|
121 |
+
a = self.model.positional_embedding[1:].T.view(1, 768, *self.token_shape)
|
122 |
+
b = nnf.interpolate(a, new_size, mode='bicubic', align_corners=False).squeeze(0).view(768, new_size[0]*new_size[1]).T
|
123 |
+
return torch.cat([self.model.positional_embedding[:1], b])
|
124 |
+
|
125 |
+
def visual_forward(self, x_inp, extract_layers=(), skip=False, mask=None):
|
126 |
+
|
127 |
+
|
128 |
+
with torch.no_grad():
|
129 |
+
|
130 |
+
inp_size = x_inp.shape[2:]
|
131 |
+
|
132 |
+
if self.n_tokens is not None:
|
133 |
+
stride2 = x_inp.shape[2] // self.n_tokens
|
134 |
+
conv_weight2 = nnf.interpolate(self.model.conv1.weight, (stride2, stride2), mode='bilinear', align_corners=True)
|
135 |
+
x = nnf.conv2d(x_inp, conv_weight2, bias=self.model.conv1.bias, stride=stride2, dilation=self.model.conv1.dilation)
|
136 |
+
else:
|
137 |
+
x = self.model.conv1(x_inp) # shape = [*, width, grid, grid]
|
138 |
+
|
139 |
+
x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
|
140 |
+
x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
|
141 |
+
|
142 |
+
x = torch.cat([self.model.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width]
|
143 |
+
|
144 |
+
standard_n_tokens = 50 if self.model.conv1.kernel_size[0] == 32 else 197
|
145 |
+
|
146 |
+
if x.shape[1] != standard_n_tokens:
|
147 |
+
new_shape = int(math.sqrt(x.shape[1]-1))
|
148 |
+
x = x + self.rescaled_pos_emb((new_shape, new_shape)).to(x.dtype)[None,:,:]
|
149 |
+
else:
|
150 |
+
x = x + self.model.positional_embedding.to(x.dtype)
|
151 |
+
|
152 |
+
x = self.model.ln_pre(x)
|
153 |
+
|
154 |
+
x = x.permute(1, 0, 2) # NLD -> LND
|
155 |
+
|
156 |
+
activations, affinities = [], []
|
157 |
+
for i, res_block in enumerate(self.model.transformer.resblocks):
|
158 |
+
|
159 |
+
if mask is not None:
|
160 |
+
mask_layer, mask_type, mask_tensor = mask
|
161 |
+
if mask_layer == i or mask_layer == 'all':
|
162 |
+
# import ipdb; ipdb.set_trace()
|
163 |
+
size = int(math.sqrt(x.shape[0] - 1))
|
164 |
+
|
165 |
+
attn_mask = (mask_type, nnf.interpolate(mask_tensor.unsqueeze(1).float(), (size, size)).view(mask_tensor.shape[0], size * size))
|
166 |
+
|
167 |
+
else:
|
168 |
+
attn_mask = None
|
169 |
+
else:
|
170 |
+
attn_mask = None
|
171 |
+
|
172 |
+
x, aff_per_head = forward_multihead_attention(x, res_block, with_aff=True, attn_mask=attn_mask)
|
173 |
+
|
174 |
+
if i in extract_layers:
|
175 |
+
affinities += [aff_per_head]
|
176 |
+
|
177 |
+
#if self.n_tokens is not None:
|
178 |
+
# activations += [nnf.interpolate(x, inp_size, mode='bilinear', align_corners=True)]
|
179 |
+
#else:
|
180 |
+
activations += [x]
|
181 |
+
|
182 |
+
if len(extract_layers) > 0 and i == max(extract_layers) and skip:
|
183 |
+
print('early skip')
|
184 |
+
break
|
185 |
+
|
186 |
+
x = x.permute(1, 0, 2) # LND -> NLD
|
187 |
+
x = self.model.ln_post(x[:, 0, :])
|
188 |
+
|
189 |
+
if self.model.proj is not None:
|
190 |
+
x = x @ self.model.proj
|
191 |
+
|
192 |
+
return x, activations, affinities
|
193 |
+
|
194 |
+
def sample_prompts(self, words, prompt_list=None):
|
195 |
+
|
196 |
+
prompt_list = prompt_list if prompt_list is not None else self.prompt_list
|
197 |
+
|
198 |
+
prompt_indices = torch.multinomial(torch.ones(len(prompt_list)), len(words), replacement=True)
|
199 |
+
prompts = [prompt_list[i] for i in prompt_indices]
|
200 |
+
return [promt.format(w) for promt, w in zip(prompts, words)]
|
201 |
+
|
202 |
+
def get_cond_vec(self, conditional, batch_size):
|
203 |
+
# compute conditional from a single string
|
204 |
+
if conditional is not None and type(conditional) == str:
|
205 |
+
cond = self.compute_conditional(conditional)
|
206 |
+
cond = cond.repeat(batch_size, 1)
|
207 |
+
|
208 |
+
# compute conditional from string list/tuple
|
209 |
+
elif conditional is not None and type(conditional) in {list, tuple} and type(conditional[0]) == str:
|
210 |
+
assert len(conditional) == batch_size
|
211 |
+
cond = self.compute_conditional(conditional)
|
212 |
+
|
213 |
+
# use conditional directly
|
214 |
+
elif conditional is not None and type(conditional) == torch.Tensor and conditional.ndim == 2:
|
215 |
+
cond = conditional
|
216 |
+
|
217 |
+
# compute conditional from image
|
218 |
+
elif conditional is not None and type(conditional) == torch.Tensor:
|
219 |
+
with torch.no_grad():
|
220 |
+
cond, _, _ = self.visual_forward(conditional)
|
221 |
+
else:
|
222 |
+
raise ValueError('invalid conditional')
|
223 |
+
return cond
|
224 |
+
|
225 |
+
def compute_conditional(self, conditional):
|
226 |
+
from rope.external.cliplib import clip
|
227 |
+
|
228 |
+
dev = next(self.parameters()).device
|
229 |
+
|
230 |
+
if type(conditional) in {list, tuple}:
|
231 |
+
text_tokens = clip.tokenize(conditional).to(dev)
|
232 |
+
cond = self.clip_model.encode_text(text_tokens)
|
233 |
+
else:
|
234 |
+
if conditional in self.precomputed_prompts:
|
235 |
+
cond = self.precomputed_prompts[conditional].float().to(dev)
|
236 |
+
else:
|
237 |
+
text_tokens = clip.tokenize([conditional]).to(dev)
|
238 |
+
cond = self.clip_model.encode_text(text_tokens)[0]
|
239 |
+
|
240 |
+
if self.shift_vector is not None:
|
241 |
+
return cond + self.shift_vector
|
242 |
+
else:
|
243 |
+
return cond
|
244 |
+
|
245 |
+
|
246 |
+
def clip_load_untrained(version):
|
247 |
+
assert version == 'ViT-B/16'
|
248 |
+
from clip.model import CLIP
|
249 |
+
from clip.clip import _MODELS, _download
|
250 |
+
model = torch.jit.load(_download(_MODELS['ViT-B/16'])).eval()
|
251 |
+
state_dict = model.state_dict()
|
252 |
+
|
253 |
+
vision_width = state_dict["visual.conv1.weight"].shape[0]
|
254 |
+
vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
|
255 |
+
vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
|
256 |
+
grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
|
257 |
+
image_resolution = vision_patch_size * grid_size
|
258 |
+
embed_dim = state_dict["text_projection"].shape[1]
|
259 |
+
context_length = state_dict["positional_embedding"].shape[0]
|
260 |
+
vocab_size = state_dict["token_embedding.weight"].shape[0]
|
261 |
+
transformer_width = state_dict["ln_final.weight"].shape[0]
|
262 |
+
transformer_heads = transformer_width // 64
|
263 |
+
transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks")))
|
264 |
+
|
265 |
+
return CLIP(embed_dim, image_resolution, vision_layers, vision_width, vision_patch_size,
|
266 |
+
context_length, vocab_size, transformer_width, transformer_heads, transformer_layers)
|
267 |
+
|
268 |
+
|
269 |
+
class CLIPDensePredT(CLIPDenseBase):
|
270 |
+
|
271 |
+
def __init__(self, version='ViT-B/32', extract_layers=(3, 6, 9), cond_layer=0, reduce_dim=128, n_heads=4, prompt='fixed',
|
272 |
+
extra_blocks=0, reduce_cond=None, fix_shift=False,
|
273 |
+
learn_trans_conv_only=False, limit_to_clip_only=False, upsample=False,
|
274 |
+
add_calibration=False, rev_activations=False, trans_conv=None, n_tokens=None, complex_trans_conv=False):
|
275 |
+
|
276 |
+
super().__init__(version, reduce_cond, reduce_dim, prompt, n_tokens)
|
277 |
+
# device = 'cpu'
|
278 |
+
|
279 |
+
self.extract_layers = extract_layers
|
280 |
+
self.cond_layer = cond_layer
|
281 |
+
self.limit_to_clip_only = limit_to_clip_only
|
282 |
+
self.process_cond = None
|
283 |
+
self.rev_activations = rev_activations
|
284 |
+
|
285 |
+
depth = len(extract_layers)
|
286 |
+
|
287 |
+
if add_calibration:
|
288 |
+
self.calibration_conds = 1
|
289 |
+
|
290 |
+
self.upsample_proj = nn.Conv2d(reduce_dim, 1, kernel_size=1) if upsample else None
|
291 |
+
|
292 |
+
self.add_activation1 = True
|
293 |
+
|
294 |
+
self.version = version
|
295 |
+
|
296 |
+
self.token_shape = {'ViT-B/32': (7, 7), 'ViT-B/16': (14, 14)}[version]
|
297 |
+
|
298 |
+
if fix_shift:
|
299 |
+
# self.shift_vector = nn.Parameter(torch.load(join(dirname(basename(__file__)), 'clip_text_shift_vector.pth')), requires_grad=False)
|
300 |
+
self.shift_vector = nn.Parameter(torch.load(join(dirname(basename(__file__)), 'shift_text_to_vis.pth')), requires_grad=False)
|
301 |
+
# self.shift_vector = nn.Parameter(-1*torch.load(join(dirname(basename(__file__)), 'shift2.pth')), requires_grad=False)
|
302 |
+
else:
|
303 |
+
self.shift_vector = None
|
304 |
+
|
305 |
+
if trans_conv is None:
|
306 |
+
trans_conv_ks = {'ViT-B/32': (32, 32), 'ViT-B/16': (16, 16)}[version]
|
307 |
+
else:
|
308 |
+
# explicitly define transposed conv kernel size
|
309 |
+
trans_conv_ks = (trans_conv, trans_conv)
|
310 |
+
|
311 |
+
if not complex_trans_conv:
|
312 |
+
self.trans_conv = nn.ConvTranspose2d(reduce_dim, 1, trans_conv_ks, stride=trans_conv_ks)
|
313 |
+
else:
|
314 |
+
assert trans_conv_ks[0] == trans_conv_ks[1]
|
315 |
+
|
316 |
+
tp_kernels = (trans_conv_ks[0] // 4, trans_conv_ks[0] // 4)
|
317 |
+
|
318 |
+
self.trans_conv = nn.Sequential(
|
319 |
+
nn.Conv2d(reduce_dim, reduce_dim, kernel_size=3, padding=1),
|
320 |
+
nn.ReLU(),
|
321 |
+
nn.ConvTranspose2d(reduce_dim, reduce_dim // 2, kernel_size=tp_kernels[0], stride=tp_kernels[0]),
|
322 |
+
nn.ReLU(),
|
323 |
+
nn.ConvTranspose2d(reduce_dim // 2, 1, kernel_size=tp_kernels[1], stride=tp_kernels[1]),
|
324 |
+
)
|
325 |
+
|
326 |
+
# self.trans_conv = nn.ConvTranspose2d(reduce_dim, 1, trans_conv_ks, stride=trans_conv_ks)
|
327 |
+
|
328 |
+
assert len(self.extract_layers) == depth
|
329 |
+
|
330 |
+
self.reduces = nn.ModuleList([nn.Linear(768, reduce_dim) for _ in range(depth)])
|
331 |
+
self.blocks = nn.ModuleList([nn.TransformerEncoderLayer(d_model=reduce_dim, nhead=n_heads) for _ in range(len(self.extract_layers))])
|
332 |
+
self.extra_blocks = nn.ModuleList([nn.TransformerEncoderLayer(d_model=reduce_dim, nhead=n_heads) for _ in range(extra_blocks)])
|
333 |
+
|
334 |
+
# refinement and trans conv
|
335 |
+
|
336 |
+
if learn_trans_conv_only:
|
337 |
+
for p in self.parameters():
|
338 |
+
p.requires_grad_(False)
|
339 |
+
|
340 |
+
for p in self.trans_conv.parameters():
|
341 |
+
p.requires_grad_(True)
|
342 |
+
|
343 |
+
self.prompt_list = get_prompt_list(prompt)
|
344 |
+
|
345 |
+
|
346 |
+
def forward(self, inp_image, conditional=None, return_features=False, mask=None):
|
347 |
+
|
348 |
+
assert type(return_features) == bool
|
349 |
+
|
350 |
+
inp_image = inp_image.to(self.model.positional_embedding.device)
|
351 |
+
|
352 |
+
if mask is not None:
|
353 |
+
raise ValueError('mask not supported')
|
354 |
+
|
355 |
+
# x_inp = normalize(inp_image)
|
356 |
+
x_inp = inp_image
|
357 |
+
|
358 |
+
bs, dev = inp_image.shape[0], x_inp.device
|
359 |
+
|
360 |
+
cond = self.get_cond_vec(conditional, bs)
|
361 |
+
|
362 |
+
visual_q, activations, _ = self.visual_forward(x_inp, extract_layers=[0] + list(self.extract_layers))
|
363 |
+
|
364 |
+
activation1 = activations[0]
|
365 |
+
activations = activations[1:]
|
366 |
+
|
367 |
+
_activations = activations[::-1] if not self.rev_activations else activations
|
368 |
+
|
369 |
+
a = None
|
370 |
+
for i, (activation, block, reduce) in enumerate(zip(_activations, self.blocks, self.reduces)):
|
371 |
+
|
372 |
+
if a is not None:
|
373 |
+
a = reduce(activation) + a
|
374 |
+
else:
|
375 |
+
a = reduce(activation)
|
376 |
+
|
377 |
+
if i == self.cond_layer:
|
378 |
+
if self.reduce_cond is not None:
|
379 |
+
cond = self.reduce_cond(cond)
|
380 |
+
|
381 |
+
a = self.film_mul(cond) * a + self.film_add(cond)
|
382 |
+
|
383 |
+
a = block(a)
|
384 |
+
|
385 |
+
for block in self.extra_blocks:
|
386 |
+
a = a + block(a)
|
387 |
+
|
388 |
+
a = a[1:].permute(1, 2, 0) # rm cls token and -> BS, Feats, Tokens
|
389 |
+
|
390 |
+
size = int(math.sqrt(a.shape[2]))
|
391 |
+
|
392 |
+
a = a.view(bs, a.shape[1], size, size)
|
393 |
+
|
394 |
+
a = self.trans_conv(a)
|
395 |
+
|
396 |
+
if self.n_tokens is not None:
|
397 |
+
a = nnf.interpolate(a, x_inp.shape[2:], mode='bilinear', align_corners=True)
|
398 |
+
|
399 |
+
if self.upsample_proj is not None:
|
400 |
+
a = self.upsample_proj(a)
|
401 |
+
a = nnf.interpolate(a, x_inp.shape[2:], mode='bilinear')
|
402 |
+
|
403 |
+
if return_features:
|
404 |
+
return a, visual_q, cond, [activation1] + activations
|
405 |
+
else:
|
406 |
+
return a,
|
407 |
+
|
408 |
+
|
409 |
+
|
410 |
+
class CLIPDensePredTMasked(CLIPDensePredT):
|
411 |
+
|
412 |
+
def __init__(self, version='ViT-B/32', extract_layers=(3, 6, 9), cond_layer=0, reduce_dim=128, n_heads=4,
|
413 |
+
prompt='fixed', extra_blocks=0, reduce_cond=None, fix_shift=False, learn_trans_conv_only=False,
|
414 |
+
refine=None, limit_to_clip_only=False, upsample=False, add_calibration=False, n_tokens=None):
|
415 |
+
|
416 |
+
super().__init__(version=version, extract_layers=extract_layers, cond_layer=cond_layer, reduce_dim=reduce_dim,
|
417 |
+
n_heads=n_heads, prompt=prompt, extra_blocks=extra_blocks, reduce_cond=reduce_cond,
|
418 |
+
fix_shift=fix_shift, learn_trans_conv_only=learn_trans_conv_only,
|
419 |
+
limit_to_clip_only=limit_to_clip_only, upsample=upsample, add_calibration=add_calibration,
|
420 |
+
n_tokens=n_tokens)
|
421 |
+
|
422 |
+
def visual_forward_masked(self, img_s, seg_s):
|
423 |
+
return super().visual_forward(img_s, mask=('all', 'cls_token', seg_s))
|
424 |
+
|
425 |
+
def forward(self, img_q, cond_or_img_s, seg_s=None, return_features=False):
|
426 |
+
|
427 |
+
if seg_s is None:
|
428 |
+
cond = cond_or_img_s
|
429 |
+
else:
|
430 |
+
img_s = cond_or_img_s
|
431 |
+
|
432 |
+
with torch.no_grad():
|
433 |
+
cond, _, _ = self.visual_forward_masked(img_s, seg_s)
|
434 |
+
|
435 |
+
return super().forward(img_q, cond, return_features=return_features)
|
436 |
+
|
437 |
+
|
438 |
+
|
439 |
+
class CLIPDenseBaseline(CLIPDenseBase):
|
440 |
+
|
441 |
+
def __init__(self, version='ViT-B/32', cond_layer=0,
|
442 |
+
extract_layer=9, reduce_dim=128, reduce2_dim=None, prompt='fixed',
|
443 |
+
reduce_cond=None, limit_to_clip_only=False, n_tokens=None):
|
444 |
+
|
445 |
+
super().__init__(version, reduce_cond, reduce_dim, prompt, n_tokens)
|
446 |
+
device = 'cpu'
|
447 |
+
|
448 |
+
# self.cond_layer = cond_layer
|
449 |
+
self.extract_layer = extract_layer
|
450 |
+
self.limit_to_clip_only = limit_to_clip_only
|
451 |
+
self.shift_vector = None
|
452 |
+
|
453 |
+
self.token_shape = {'ViT-B/32': (7, 7), 'ViT-B/16': (14, 14)}[version]
|
454 |
+
|
455 |
+
assert reduce2_dim is not None
|
456 |
+
|
457 |
+
self.reduce2 = nn.Sequential(
|
458 |
+
nn.Linear(reduce_dim, reduce2_dim),
|
459 |
+
nn.ReLU(),
|
460 |
+
nn.Linear(reduce2_dim, reduce_dim)
|
461 |
+
)
|
462 |
+
|
463 |
+
trans_conv_ks = {'ViT-B/32': (32, 32), 'ViT-B/16': (16, 16)}[version]
|
464 |
+
self.trans_conv = nn.ConvTranspose2d(reduce_dim, 1, trans_conv_ks, stride=trans_conv_ks)
|
465 |
+
|
466 |
+
|
467 |
+
def forward(self, inp_image, conditional=None, return_features=False):
|
468 |
+
|
469 |
+
inp_image = inp_image.to(self.model.positional_embedding.device)
|
470 |
+
|
471 |
+
# x_inp = normalize(inp_image)
|
472 |
+
x_inp = inp_image
|
473 |
+
|
474 |
+
bs, dev = inp_image.shape[0], x_inp.device
|
475 |
+
|
476 |
+
cond = self.get_cond_vec(conditional, bs)
|
477 |
+
|
478 |
+
visual_q, activations, affinities = self.visual_forward(x_inp, extract_layers=[self.extract_layer])
|
479 |
+
|
480 |
+
a = activations[0]
|
481 |
+
a = self.reduce(a)
|
482 |
+
a = self.film_mul(cond) * a + self.film_add(cond)
|
483 |
+
|
484 |
+
if self.reduce2 is not None:
|
485 |
+
a = self.reduce2(a)
|
486 |
+
|
487 |
+
# the original model would execute a transformer block here
|
488 |
+
|
489 |
+
a = a[1:].permute(1, 2, 0) # rm cls token and -> BS, Feats, Tokens
|
490 |
+
|
491 |
+
size = int(math.sqrt(a.shape[2]))
|
492 |
+
|
493 |
+
a = a.view(bs, a.shape[1], size, size)
|
494 |
+
a = self.trans_conv(a)
|
495 |
+
|
496 |
+
if return_features:
|
497 |
+
return a, visual_q, cond, activations
|
498 |
+
else:
|
499 |
+
return a,
|
500 |
+
|
501 |
+
|
502 |
+
class CLIPSegMultiLabel(nn.Module):
|
503 |
+
|
504 |
+
def __init__(self, model) -> None:
|
505 |
+
super().__init__()
|
506 |
+
|
507 |
+
from third_party.JoEm.data_loader import get_seen_idx, get_unseen_idx, VOC
|
508 |
+
|
509 |
+
self.pascal_classes = VOC
|
510 |
+
|
511 |
+
from models.clipseg import CLIPDensePredT
|
512 |
+
from general_utils import load_model
|
513 |
+
# self.clipseg = load_model('rd64-vit16-neg0.2-phrasecut', strict=False)
|
514 |
+
self.clipseg = load_model(model, strict=False)
|
515 |
+
|
516 |
+
self.clipseg.eval()
|
517 |
+
|
518 |
+
def forward(self, x):
|
519 |
+
|
520 |
+
bs = x.shape[0]
|
521 |
+
out = torch.ones(21, bs, 352, 352).to(x.device) * -10
|
522 |
+
|
523 |
+
for class_id, class_name in enumerate(self.pascal_classes):
|
524 |
+
|
525 |
+
fac = 3 if class_name == 'background' else 1
|
526 |
+
|
527 |
+
with torch.no_grad():
|
528 |
+
pred = torch.sigmoid(self.clipseg(x, class_name)[0][:,0]) * fac
|
529 |
+
|
530 |
+
out[class_id] += pred
|
531 |
+
|
532 |
+
|
533 |
+
out = out.permute(1, 0, 2, 3)
|
534 |
+
|
535 |
+
return out
|
536 |
+
|
537 |
+
# construct output tensor
|
538 |
+
|
rope/external/resnet.py
ADDED
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/python
|
2 |
+
# -*- encoding: utf-8 -*-
|
3 |
+
|
4 |
+
import torch
|
5 |
+
import torch.nn as nn
|
6 |
+
import torch.nn.functional as F
|
7 |
+
import torch.utils.model_zoo as modelzoo
|
8 |
+
|
9 |
+
# from modules.bn import InPlaceABNSync as BatchNorm2d
|
10 |
+
|
11 |
+
resnet18_url = 'https://download.pytorch.org/models/resnet18-5c106cde.pth'
|
12 |
+
|
13 |
+
|
14 |
+
def conv3x3(in_planes, out_planes, stride=1):
|
15 |
+
"""3x3 convolution with padding"""
|
16 |
+
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
|
17 |
+
padding=1, bias=False)
|
18 |
+
|
19 |
+
|
20 |
+
class BasicBlock(nn.Module):
|
21 |
+
def __init__(self, in_chan, out_chan, stride=1):
|
22 |
+
super(BasicBlock, self).__init__()
|
23 |
+
self.conv1 = conv3x3(in_chan, out_chan, stride)
|
24 |
+
self.bn1 = nn.BatchNorm2d(out_chan)
|
25 |
+
self.conv2 = conv3x3(out_chan, out_chan)
|
26 |
+
self.bn2 = nn.BatchNorm2d(out_chan)
|
27 |
+
self.relu = nn.ReLU(inplace=True)
|
28 |
+
self.downsample = None
|
29 |
+
if in_chan != out_chan or stride != 1:
|
30 |
+
self.downsample = nn.Sequential(
|
31 |
+
nn.Conv2d(in_chan, out_chan,
|
32 |
+
kernel_size=1, stride=stride, bias=False),
|
33 |
+
nn.BatchNorm2d(out_chan),
|
34 |
+
)
|
35 |
+
|
36 |
+
def forward(self, x):
|
37 |
+
residual = self.conv1(x)
|
38 |
+
residual = F.relu(self.bn1(residual))
|
39 |
+
residual = self.conv2(residual)
|
40 |
+
residual = self.bn2(residual)
|
41 |
+
|
42 |
+
shortcut = x
|
43 |
+
if self.downsample is not None:
|
44 |
+
shortcut = self.downsample(x)
|
45 |
+
|
46 |
+
out = shortcut + residual
|
47 |
+
out = self.relu(out)
|
48 |
+
return out
|
49 |
+
|
50 |
+
|
51 |
+
def create_layer_basic(in_chan, out_chan, bnum, stride=1):
|
52 |
+
layers = [BasicBlock(in_chan, out_chan, stride=stride)]
|
53 |
+
for i in range(bnum-1):
|
54 |
+
layers.append(BasicBlock(out_chan, out_chan, stride=1))
|
55 |
+
return nn.Sequential(*layers)
|
56 |
+
|
57 |
+
|
58 |
+
class Resnet18(nn.Module):
|
59 |
+
def __init__(self):
|
60 |
+
super(Resnet18, self).__init__()
|
61 |
+
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
|
62 |
+
bias=False)
|
63 |
+
self.bn1 = nn.BatchNorm2d(64)
|
64 |
+
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
|
65 |
+
self.layer1 = create_layer_basic(64, 64, bnum=2, stride=1)
|
66 |
+
self.layer2 = create_layer_basic(64, 128, bnum=2, stride=2)
|
67 |
+
self.layer3 = create_layer_basic(128, 256, bnum=2, stride=2)
|
68 |
+
self.layer4 = create_layer_basic(256, 512, bnum=2, stride=2)
|
69 |
+
self.init_weight()
|
70 |
+
|
71 |
+
def forward(self, x):
|
72 |
+
x = self.conv1(x)
|
73 |
+
x = F.relu(self.bn1(x))
|
74 |
+
x = self.maxpool(x)
|
75 |
+
|
76 |
+
x = self.layer1(x)
|
77 |
+
feat8 = self.layer2(x) # 1/8
|
78 |
+
feat16 = self.layer3(feat8) # 1/16
|
79 |
+
feat32 = self.layer4(feat16) # 1/32
|
80 |
+
return feat8, feat16, feat32
|
81 |
+
|
82 |
+
def init_weight(self):
|
83 |
+
state_dict = modelzoo.load_url(resnet18_url)
|
84 |
+
self_state_dict = self.state_dict()
|
85 |
+
for k, v in state_dict.items():
|
86 |
+
if 'fc' in k: continue
|
87 |
+
self_state_dict.update({k: v})
|
88 |
+
self.load_state_dict(self_state_dict)
|
89 |
+
|
90 |
+
def get_params(self):
|
91 |
+
wd_params, nowd_params = [], []
|
92 |
+
for name, module in self.named_modules():
|
93 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
94 |
+
wd_params.append(module.weight)
|
95 |
+
if not module.bias is None:
|
96 |
+
nowd_params.append(module.bias)
|
97 |
+
elif isinstance(module, nn.BatchNorm2d):
|
98 |
+
nowd_params += list(module.parameters())
|
99 |
+
return wd_params, nowd_params
|
100 |
+
|
101 |
+
|
102 |
+
if __name__ == "__main__":
|
103 |
+
net = Resnet18()
|
104 |
+
x = torch.randn(16, 3, 224, 224)
|
105 |
+
out = net(x)
|
106 |
+
print(out[0].size())
|
107 |
+
print(out[1].size())
|
108 |
+
print(out[2].size())
|
109 |
+
net.get_params()
|
rope/media/OffState.png
ADDED
rope/media/OnState.png
ADDED
rope/media/add_marker_hover.png
ADDED
rope/media/add_marker_off.png
ADDED
rope/media/marker.png
ADDED
rope/media/marker_save.png
ADDED
rope/media/next_marker_hover.png
ADDED
rope/media/next_marker_off.png
ADDED
rope/media/play_hover.png
ADDED
rope/media/play_off.png
ADDED
rope/media/play_on.png
ADDED
rope/media/previous_marker_hover.png
ADDED
rope/media/previous_marker_off.png
ADDED
rope/media/rec_hover.png
ADDED
rope/media/rec_off.png
ADDED
rope/media/rec_on.png
ADDED
rope/media/remove_marker_hover.png
ADDED
rope/media/remove_marker_off.png
ADDED
rope/media/rope.ico
ADDED
rope/media/rope.png
ADDED
rope/media/save.png
ADDED
rope/media/splash.png
ADDED
Git LFS Details
|
rope/media/stop_hover.png
ADDED
rope/media/stop_off.png
ADDED
rope/media/stop_on.png
ADDED