MonsterMMORPG commited on
Commit
bab3d3d
1 Parent(s): df03c5d

ad12ac56454a9863a1f84a63e67f93672e88c7bc4f53fe03c54d3305d6ac72b2

Browse files
.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 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
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 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/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 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from os.path import basename, dirname, join, isfile
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as nnf
6
+ from torch.nn.modules.activation import ReLU
7
+
8
+
9
+ def get_prompt_list(prompt):
10
+ if prompt == 'plain':
11
+ return ['{}']
12
+ elif prompt == 'fixed':
13
+ return ['a photo of a {}.']
14
+ elif prompt == 'shuffle':
15
+ return ['a photo of a {}.', 'a photograph of a {}.', 'an image of a {}.', '{}.']
16
+ elif prompt == 'shuffle+':
17
+ return ['a photo of a {}.', 'a photograph of a {}.', 'an image of a {}.', '{}.',
18
+ 'a cropped photo of a {}.', 'a good photo of a {}.', 'a photo of one {}.',
19
+ 'a bad photo of a {}.', 'a photo of the {}.']
20
+ else:
21
+ raise ValueError('Invalid value for prompt')
22
+
23
+
24
+ def forward_multihead_attention(x, b, with_aff=False, attn_mask=None):
25
+ """
26
+ Simplified version of multihead attention (taken from torch source code but without tons of if clauses).
27
+ The mlp and layer norm come from CLIP.
28
+ x: input.
29
+ b: multihead attention module.
30
+ """
31
+
32
+ x_ = b.ln_1(x)
33
+ q, k, v = nnf.linear(x_, b.attn.in_proj_weight, b.attn.in_proj_bias).chunk(3, dim=-1)
34
+ tgt_len, bsz, embed_dim = q.size()
35
+
36
+ head_dim = embed_dim // b.attn.num_heads
37
+ scaling = float(head_dim) ** -0.5
38
+
39
+ q = q.contiguous().view(tgt_len, bsz * b.attn.num_heads, b.attn.head_dim).transpose(0, 1)
40
+ k = k.contiguous().view(-1, bsz * b.attn.num_heads, b.attn.head_dim).transpose(0, 1)
41
+ v = v.contiguous().view(-1, bsz * b.attn.num_heads, b.attn.head_dim).transpose(0, 1)
42
+
43
+ q = q * scaling
44
+
45
+ attn_output_weights = torch.bmm(q, k.transpose(1, 2)) # n_heads * batch_size, tokens^2, tokens^2
46
+ if attn_mask is not None:
47
+
48
+
49
+ attn_mask_type, attn_mask = attn_mask
50
+ n_heads = attn_output_weights.size(0) // attn_mask.size(0)
51
+ attn_mask = attn_mask.repeat(n_heads, 1)
52
+
53
+ if attn_mask_type == 'cls_token':
54
+ # the mask only affects similarities compared to the readout-token.
55
+ attn_output_weights[:, 0, 1:] = attn_output_weights[:, 0, 1:] * attn_mask[None,...]
56
+ # attn_output_weights[:, 0, 0] = 0*attn_output_weights[:, 0, 0]
57
+
58
+ if attn_mask_type == 'all':
59
+ # print(attn_output_weights.shape, attn_mask[:, None].shape)
60
+ attn_output_weights[:, 1:, 1:] = attn_output_weights[:, 1:, 1:] * attn_mask[:, None]
61
+
62
+
63
+ attn_output_weights = torch.softmax(attn_output_weights, dim=-1)
64
+
65
+ attn_output = torch.bmm(attn_output_weights, v)
66
+ attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
67
+ attn_output = b.attn.out_proj(attn_output)
68
+
69
+ x = x + attn_output
70
+ x = x + b.mlp(b.ln_2(x))
71
+
72
+ if with_aff:
73
+ return x, attn_output_weights
74
+ else:
75
+ return x
76
+
77
+
78
+ class CLIPDenseBase(nn.Module):
79
+
80
+ def __init__(self, version, reduce_cond, reduce_dim, prompt, n_tokens):
81
+ super().__init__()
82
+
83
+ 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

  • SHA256: 48ae8b5a56a0a7f959a115b23c53fd02f04a4671e30b7eccf8136a7e42fc8092
  • Pointer size: 132 Bytes
  • Size of remote file: 1.34 MB
rope/media/stop_hover.png ADDED
rope/media/stop_off.png ADDED
rope/media/stop_on.png ADDED
rope/media/tl_beg_hover.png ADDED