forked from Hillobar/Rope
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGUI.py
2149 lines (1663 loc) · 96.4 KB
/
GUI.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import cv2
import tkinter as tk
from tkinter import filedialog, font
import numpy as np
from PIL import Image, ImageTk
import json
import time
from skimage import transform as trans
from math import floor, ceil
import copy
import bisect
import torch
import torchvision
torchvision.disable_beta_transforms_warning()
from torchvision.transforms import v2
import mimetypes
#import inspect print(inspect.currentframe().f_back.f_code.co_name, 'resize_image')
from rope.Dicts import PARAM_BUTTONS_PARAMS, ACTIONS, PARAM_BUTTONS_CONSTANT
last_frame = 0
class GUI(tk.Tk):
def __init__( self):
super().__init__()
# Adding a title to the self
# self.call('tk', 'scaling', 0.5)
self.title('Rope-Ruby')
self.pixel = []
self.parameters = PARAM_BUTTONS_PARAMS
self.actions = ACTIONS
self.param_const = PARAM_BUTTONS_CONSTANT
self.parameters_buttons={}
self.num_threads = 1
self.video_quality = 18
self.target_media = []
self.target_video_file = []
self.action_q = []
self.video_image = []
self.x1 = []
self.y1 = []
self.found_faces_assignments = []
self.play_video = False
self.rec_video = False
# self.faceapp_model = []
self.video_loaded = False
self.docked = True
self.undock = []
self.image_file_name = []
self.stop_marker = []
self.stop_image = []
self.marker_icon = []
self.stop_marker_icon = []
self.video_length = []
# self.window_y = []
# self.window_width = []
# self.window_height = []
self.detection_model = []
self.recognition_model = []
self.arcface_dst = np.array( [[38.2946, 51.6963], [73.5318, 51.5014], [56.0252, 71.7366], [41.5493, 92.3655], [70.7299, 92.2041]], dtype=np.float32)
self.json_dict = {
"source videos": None,
"source faces": None,
"saved videos": None,
"threads": 1,
'dock_win_geom': [980, 1020, self.winfo_screenwidth()/2-400, self.winfo_screenheight()/2-510],
'undock_win_geom': [980, 517, self.winfo_screenwidth()/2-400, self.winfo_screenheight()/2-510],
'player_geom': [1024, 768, self.winfo_screenwidth()/2-400, self.winfo_screenheight()/2-510],
}
self.marker = {
'frame': '0',
'parameters': '',
'icon_ref': '',
}
self.markers = []
self.target_face = {
"TKButton": [],
"ButtonState": "off",
"Image": [],
"Embedding": [],
"SourceFaceAssignments": [],
"EmbeddingNumber": 0, #used for adding additional found faces
'AssignedEmbedding': [], #the currently assigned source embedding, including averaged ones
}
self.target_faces = []
self.source_face = {
"TKButton": [],
"ButtonState": "off",
"Image": [],
"Embedding": []
}
self.source_faces = []
self.button_highlight_style = {
'bg': 'light goldenrod',
'fg': 'black',
'activebackground': 'gray75',
'activeforeground': 'light goldenrod',
'relief': 'flat',
'border': '0',
'font': ("Cascadia Mono Light", 9)
}
self.inactive_button_style = {
'bg': 'gray20',
'fg': 'white',
'activebackground': 'gray10',
'activeforeground': 'white',
'relief': 'flat',
'border': '0',
'font': ("Cascadia Mono Light", 9)
}
self.active_button_style = {
'bg': 'black',
'fg': 'white',
'activebackground': 'gray10',
'activeforeground': 'white',
'relief': 'flat',
'border': '0',
'font': ("Cascadia Mono Light", 9)
}
self.need_button_style = {
'bg': 'gray30',
'fg': 'white',
'relief': 'flat',
'border': '0',
'font': ("Cascadia Mono Light", 9)
}
self.canvas_label_style = {
'bg': 'gray20',
'relief': 'flat',
'bd': '0',
'highlightthickness': '0'
}
self.canvas_style1 = {
'bg': 'gray20',
'relief': 'flat',
'bd': '0',
'highlightthickness': '0'
}
self.frame_style = {
'bg': 'gray20',
'relief': 'flat',
'bd': '0'
}
self.checkbox_style = {
'bg': 'gray40',
'fg': 'white',
'relief': 'flat',
'bd': '0',
'anchor': 'w',
'selectcolor': 'gray40'
}
self.label_style = {
'bg': 'gray20',
'fg': 'white',
'relief': 'flat',
'bd': '0',
'font': ("Cascadia Mono Light", 9),
'anchor': 'w'
}
self.slider_style = {
'bg': 'gray20',
'fg': 'white',
'activebackground': 'black',
'highlightthickness':'0',
'relief': 'flat',
'sliderrelief': 'flat',
'border': '0',
'width': '10',
'troughcolor': 'gray40',
'font': ("Cascadia Mono Light", 9)
}
# Pop up window
self.undock_video_window = tk.Toplevel()
self.undock_video_window.withdraw()
# Undocked Media frame
self.undock_video_frame = tk.Frame( self.undock_video_window, self.frame_style)
self.undock_video_frame.grid( row = 0, column = 0, sticky='NEWS', pady = 2 )
self.undock_video_frame.grid_columnconfigure(0, weight=1)
self.undock_video_frame.grid_rowconfigure(0, weight = 1)
# Video [0,0]
self.undock_video = tk.Label( self.undock_video_frame, self.label_style, bg='black')
self.undock_video.grid( row = 0, column = 0, sticky='NEWS', pady =0 )
self.undock_video.bind("<MouseWheel>", self.iterate_through_merged_embeddings)
self.undock_video.bind("<ButtonRelease-1>", lambda event: self.toggle_play_video())
# Docked Media frame
self.video_frame = tk.Frame( self, self.frame_style)
self.video_frame.grid( row = 0, column = 0, sticky='NEWS', pady = 0 )
self.video_frame.grid_columnconfigure(0, weight=1)
self.video_frame.grid_rowconfigure(0, weight = 1)
# Video [0,0]
self.video = tk.Label( self.video_frame, self.label_style, bg='black')
self.video.grid( row = 0, column = 0, sticky='NEWS', pady =0 )
self.video.bind("<MouseWheel>", self.iterate_through_merged_embeddings)
self.video.bind("<ButtonRelease-1>", lambda event: self.toggle_play_video())
######### Options
# Play bar
self.options_frame = tk.Frame( self, self.frame_style, height = 71)
self.options_frame.grid( row = 1, column = 0, sticky='NEWS', pady = 2 )
self.options_frame.grid_rowconfigure( 0, weight = 100 )
self.options_frame.grid_rowconfigure( 1, weight = 100 )
self.options_frame.grid_columnconfigure( 0, weight = 1 )
# Media control canvas
self.media_control_canvas = tk.Canvas( self.options_frame, self.canvas_style1, height = 40)
self.media_control_canvas.grid( row = 0, column = 0, sticky='NEWS', pady = 0)
self.media_control_canvas.grid_columnconfigure(1, weight = 1)
# Video button canvas
self.video_button_canvas = tk.Canvas( self.media_control_canvas, self.canvas_style1, width = 112, height = 40)
self.video_button_canvas.grid( row = 0, column = 0, sticky='NEWS', pady = 0)
# Buttons
self.create_ui_button_2('Dock', self.video_button_canvas, 8, 2, width=15, height=36)
self.create_ui_button_2('Play', self.video_button_canvas, 31, 2, width=36, height=36)
self.create_ui_button_2('Record', self.video_button_canvas, 69, 2, width=36, height=36)
# Video Slider canvas
self.video_slider_canvas = tk.Canvas( self.media_control_canvas, self.canvas_style1, height=40)
self.video_slider_canvas.grid( row = 0, column = 1, sticky='NEWS', pady = 0)
# Video Slider
self.video_slider = tk.Scale( self.video_slider_canvas, self.slider_style, orient='horizontal')
self.video_slider.bind("<B1-Motion>", lambda event: self.slider_move('motion', self.video_slider.get()))
self.video_slider.bind("<ButtonPress-1>", lambda event: self.slider_move('press', self.video_slider.get()))
self.video_slider.bind("<ButtonRelease-1>", lambda event: self.slider_move('release', self.video_slider.get()))
self.video_slider.bind("<ButtonRelease-3>", lambda event: self.slider_move('motion', self.video_slider.get()))
self.video_slider.bind("<MouseWheel>", lambda event: self.mouse_wheel(event, self.video_slider.get()))
self.video_slider.pack(fill=tk.X)
# Marker canvas
self.marker_canvas = tk.Canvas( self.media_control_canvas, self.canvas_style1, width = 180, height = 40)
self.marker_canvas.grid( row = 0, column = 2, sticky='news', pady = 0)
# Marker Buttons
self.create_ui_button_2('AddMarker', self.marker_canvas, 8, 2, width=36, height=36)
self.create_ui_button_2('RemoveMarker', self.marker_canvas, 35, 2, width=36, height=36)
self.create_ui_button_2('PrevMarker', self.marker_canvas, 69, 2, width=36, height=36)
self.create_ui_button_2('NextMarker', self.marker_canvas, 107, 2, width=36, height=36)
self.create_ui_button_2('ToggleStop', self.marker_canvas, 140, 2, width=36, height=36)
# Image control canvas
self.image_control_canvas = tk.Canvas( self.video_frame, self.canvas_style1, height = 40)
self.image_control_canvas.grid( row = 1, column = 0, sticky='NEWS', pady = 0)
self.image_control_canvas.grid_columnconfigure(1, weight = 1)
# Image Save
self.create_ui_button_2('ImgDock', self.image_control_canvas, 8, 2, width=15, height=36)
self.create_ui_button_2('SaveImage', self.image_control_canvas, 31, 2, width=36, height=36)
# Options Area
x_space = 40
# Left Canvas
self.options_frame_canvas1 = tk.Canvas( self.options_frame, self.canvas_style1, height = 71)
self.options_frame_canvas1.grid( row = 1, column = 0, sticky='NEWS', pady = 0 )
# Label Frame 1
self.label_frame1 = tk.LabelFrame( self.options_frame_canvas1, self.frame_style, height = 71, width = 1400 )
self.label_frame1.place(x=0, y=0)
column=8
self.create_ui_button('Upscale', self.label_frame1, column, 8)
self.create_ui_button('Threshold', self.label_frame1, column, 37)
column=column+125+x_space
self.create_ui_button('Strength', self.label_frame1, column, 8)
self.create_ui_button('Orientation', self.label_frame1, column, 37)
column=column+125+x_space
self.create_ui_button('Border', self.label_frame1, column, 8)
self.create_ui_button('Diff', self.label_frame1, column, 37)
column=column+125+x_space
self.create_ui_button('Occluder', self.label_frame1, column, 8)
self.create_ui_button('FaceParser', self.label_frame1, column, 37)
column=column+125+x_space
self.create_ui_button('CLIP', self.label_frame1, column, 8)
# CLIP-entry
self.temptkstr = tk.StringVar(value="")
self.CLIP_text = tk.Entry(self.label_frame1, relief='flat', bd=0, textvariable=self.temptkstr)
self.CLIP_text.place(x=column, y=40, width = 125, height=20)
self.CLIP_text.bind("<Return>", lambda event: self.update_CLIP_text(self.temptkstr))
self.CLIP_name = self.nametowidget(self.CLIP_text)
column=column+125+x_space
self.create_ui_button('Blur', self.label_frame1, column, 8)
self.create_ui_button('MaskView', self.label_frame1, column, 37)
column=column+125+x_space
self.create_ui_button('RefDel', self.label_frame1, column, 8)
self.create_ui_button('Transform', self.label_frame1, column, 37)
column=column+125+x_space
self.create_ui_button('Color', self.label_frame1, column, 8)
######## Target Faces
# Frame
self.found_faces_frame = tk.Frame( self, self.frame_style)
self.found_faces_frame.grid( row = 2, column = 0, sticky='NEWS', pady = 2 )
self.found_faces_frame.grid_columnconfigure( 0, minsize = 10 )
self.found_faces_frame.grid_columnconfigure( 1, weight = 1 )
self.found_faces_frame.grid_rowconfigure( 0, weight = 0 )
# Canvas
self.found_faces_buttons_canvas = tk.Canvas( self.found_faces_frame, self.canvas_style1, height = 100, width = 112)
self.found_faces_buttons_canvas.grid( row = 0, column = 0, )
# Buttons
self.create_ui_button_2('FindFaces', self.found_faces_buttons_canvas, 8, 8)
self.create_ui_button_2('ClearFaces', self.found_faces_buttons_canvas, 8, 37)
self.create_ui_button_2('SwapFaces', self.found_faces_buttons_canvas, 8, 66)
# Scroll Canvas
self.found_faces_canvas = tk.Canvas( self.found_faces_frame, self.canvas_style1, height = 100 )
self.found_faces_canvas.grid( row = 0, column = 1, sticky='NEWS')
self.found_faces_canvas.bind("<MouseWheel>", self.target_faces_mouse_wheel)
self.found_faces_canvas.create_text(8, 45, anchor='w', fill='grey25', font=("Arial italic", 50), text=" Target Faces")
######## Source Faces
# Frame
self.source_faces_frame = tk.Frame( self, self.frame_style)
self.source_faces_frame.grid( row = 3, column = 0, sticky='NEWS', pady = 2 )
self.source_faces_frame.grid_columnconfigure( 0, minsize = 10 )
self.source_faces_frame.grid_columnconfigure( 1, weight = 1 )
self.source_faces_frame.grid_rowconfigure( 0, weight = 0 )
# Canvas
self.source_faces_buttons = []
self.source_button_canvas = tk.Canvas( self.source_faces_frame, self.canvas_style1, height = 100, width = 112)
self.source_button_canvas.grid( row = 0, column = 0, sticky='NEWS')
# Buttons
self.create_ui_button_2('LoadSFaces', self.source_button_canvas, 8, 8)
self.create_ui_button_2('DelEmbed', self.source_button_canvas, 8, 66)
# Merged Embeddings Text
self.merged_embedding_name = tk.StringVar()
self.merged_embeddings_text = tk.Entry(self.source_button_canvas, relief='flat', bd=0, textvariable=self.merged_embedding_name)
self.merged_embeddings_text.place(x=8, y=37, width = 96, height=20)
self.merged_embeddings_text.bind("<Return>", lambda event: self.save_selected_source_faces(self.merged_embedding_name))
self.me_name = self.nametowidget(self.merged_embeddings_text)
# Scroll Canvas
self.source_faces_canvas = tk.Canvas( self.source_faces_frame, self.canvas_style1, height = 100)
self.source_faces_canvas.grid( row = 0, column = 1, sticky='NEWS')
self.source_faces_canvas.bind("<MouseWheel>", self.source_faces_mouse_wheel)
self.source_faces_canvas.create_text(8, 45, anchor='w', fill='grey25', font=("Arial italic", 50), text=' Source Faces')
######### Target Videos
# Frame
self.target_videos_frame = tk.Frame( self, self.frame_style)
self.target_videos_frame.grid( row = 4, column = 0, sticky='NEWS', pady = 2 )
self.target_videos_frame.grid_columnconfigure( 0, minsize = 10 )
self.target_videos_frame.grid_columnconfigure( 1, weight = 1 )
self.target_videos_frame.grid_rowconfigure( 0, weight = 0 )
# Canvas
self.target_media_buttons = []
self.target_button_canvas = tk.Canvas(self.target_videos_frame, self.canvas_style1, height = 100, width = 112)
self.target_button_canvas.grid( row = 0, column = 0, sticky='NEWS')
# Buttons
self.create_ui_button_2('LoadTVideos', self.target_button_canvas, 8, 8)
self.create_ui_button_2('ImgVid', self.target_button_canvas, 8, 37)
# self.create_ui_button_2('HoldFace', self.target_button_canvas, 8, 66)
# Video Canvas [0,1]
self.target_media_canvas = tk.Canvas( self.target_videos_frame, self.canvas_style1, height = 100)
self.target_media_canvas.grid( row = 0, column = 1, sticky='NEWS')
self.target_media_canvas.bind("<MouseWheel>", self.target_videos_mouse_wheel)
self.target_media_canvas.create_text(8, 45, anchor='w', fill='grey25', font=("Arial italic", 50), text=' Target Videos')
######### Options
self.program_options_frame = tk.Frame( self, self.frame_style, height = 42)
self.program_options_frame.grid( row = 5, column = 0, sticky='NEWS', pady = 2 )
self.program_options_frame.grid_rowconfigure( 0, weight = 100 )
self.program_options_frame.grid_columnconfigure( 0, weight = 1 )
# Left Canvas
self.program_options_frame_canvas = tk.Canvas( self.program_options_frame, self.canvas_style1, height = 42)
self.program_options_frame_canvas.grid( row = 0, column = 0, sticky='NEWS', pady = 0 )
# Label Frame 1
self.program_options_label = tk.LabelFrame( self.program_options_frame_canvas, self.frame_style, height = 42, width = 800 )
self.program_options_label.place(x=0, y=0)
# Buttons
column = 8
x_space = 40
self.create_ui_button_2('StartRope', self.program_options_label, column, 8, width = 125, height = 26)
column=column+125+x_space
self.create_ui_button_2('OutputFolder', self.program_options_label, column, 8, width = 125, height = 26)
column=column+125+x_space
self.create_ui_button_2('Threads', self.program_options_label, column, 8, width = 125, height = 26)
# column=column+125+x_space
# self.create_ui_button_2('VideoQuality', self.program_options_label, column, 8,width = 125, height = 26)
column=column+125+x_space
self.create_ui_button_2('PerfTest', self.program_options_label, column, 8,width = 125, height = 26)
# Status
self.status_frame = tk.Frame( self, bg='grey20', height = 15)
self.status_frame.grid( row = 6, column = 0, sticky='NEWS', pady = 2 )
self.status_label = tk.Label(self.status_frame, fg="white", bg='grey20')
self.status_label.pack()
def target_faces_mouse_wheel(self, event):
self.found_faces_canvas.xview_scroll(1*int(event.delta/120.0), "units")
def source_faces_mouse_wheel(self, event):
self.source_faces_canvas.xview_scroll(1*int(event.delta/120.0), "units")
def target_videos_mouse_wheel(self, event):
self.target_media_canvas.xview_scroll(1*int(event.delta/120.0), "units")
# focus_get()
def key_event(self, event):
# print(event.char, event.keysym, event.keycode)
if self.focus_get() != self.CLIP_name and self.focus_get() != self.me_name and self.actions['ImgVidMode'] == 0:
frame = self.video_slider.get()
if event.char == ' ':
self.toggle_play_video()
elif event.char == 'w':
frame += 1
elif event.char == 's':
frame -= 1
elif event.char == 'd':
frame += 30
elif event.char == 'a':
frame -= 30
if frame > self.video_length:
frame = self.video_length
elif frame < 0:
frame = 0
self.video_slider.set(frame)
self.add_action("get_requested_video_frame", frame)
self.parameter_update_from_marker(frame)
def initialize_gui( self ):
# check if data.json exists, if not then create it
try:
save_file = open("data.json", "r")
except:
with open("data.json", "w") as outfile:
json.dump(self.json_dict, outfile)
else:
save_file.close()
json_object = []
with open('data.json', 'r') as openfile:
json_object = json.load(openfile)
try:
self.json_dict["source videos"] = json_object["source videos"]
except KeyError:
self.actions['LoadTVideosButton'].configure(self.button_highlight_style, text=' Setup')
else:
if self.json_dict["source videos"] == None:
self.actions['LoadTVideosButton'].configure(self.button_highlight_style, text=' Setup')
else:
temp = self.json_dict["source videos"]
temp_len = len(temp)
temp = ' '+temp[temp_len-9:]
self.actions['LoadTVideosButton'].configure(self.inactive_button_style, text=temp)
try:
self.json_dict["source faces"] = json_object["source faces"]
except KeyError:
self.actions['LoadSFacesButton'].configure(self.button_highlight_style, text=' Setup')
else:
if self.json_dict["source faces"] == None:
self.actions['LoadSFacesButton'].configure(self.button_highlight_style, text=' Setup')
else:
temp = self.json_dict["source faces"]
temp_len = len(temp)
temp = ' '+temp[temp_len-9:]
self.actions['LoadSFacesButton'].configure(self.inactive_button_style, text=temp)
try:
self.json_dict["saved videos"] = json_object["saved videos"]
except KeyError:
self.actions['OutputFolderButton'].configure(self.button_highlight_style, text=' Setup')
else:
if self.json_dict["saved videos"] == None:
self.actions['OutputFolderButton'].configure(self.button_highlight_style, text=' Setup')
else:
temp = self.json_dict["saved videos"]
temp_len = len(temp)
temp = ' '+temp[temp_len-9:]
self.actions['OutputFolderButton'].configure(self.inactive_button_style, text=temp)
self.add_action("saved_video_path",self.json_dict["saved videos"])
try:
self.json_dict["threads"] = json_object["threads"]
except KeyError:
self.change_threads_amount(event)
else:
temp = self.json_dict["threads"]
self.num_threads = int(temp)
temp = ' Threads ' + str(self.num_threads)
self.actions['ThreadsButton'].configure(text=temp)
self.add_action("num_threads",int(self.num_threads))
try:
self.json_dict['dock_win_geom'] = json_object['dock_win_geom']
except:
self.json_dict['dock_win_geom'] = self.json_dict['dock_win_geom']
try:
self.json_dict["undock_win_geom"] = json_object["undock_win_geom"]
except:
self.json_dict["undock_win_geom"] = self.json_dict["undock_win_geom"]
try:
self.json_dict["player_geom"] = json_object["player_geom"]
except:
self.json_dict["player_geom"] = self.json_dict["player_geom"]
self.bind('<Key>', lambda event: self.key_event(event))
self.bind('<space>', lambda event: self.key_event(event))
self.undock_video_window.bind('<Key>', lambda event: self.key_event(event))
self.undock_video_window.bind('<space>', lambda event: self.key_event(event))
# self.overrideredirect(True)
self.configure(bg='grey10')
self.resizable(width=True, height=True)
self.geometry('%dx%d+%d+%d' % (self.json_dict['dock_win_geom'][0], self.json_dict['dock_win_geom'][1] , self.json_dict['dock_win_geom'][2], self.json_dict['dock_win_geom'][3]))
self.undock_video_window.grid_columnconfigure(0, weight = 1)
self.undock_video_window.grid_rowconfigure(0, weight = 10)
self.grid_columnconfigure(0, weight = 1)
self.grid_rowconfigure(0, weight = 10)
self.grid_rowconfigure(1, weight = 0)
self.grid_rowconfigure(2, weight = 0)
self.grid_rowconfigure(3, weight = 0)
self.grid_rowconfigure(4, weight = 0)
self.grid_rowconfigure(5, weight = 0)
self.grid_rowconfigure(6, weight = 0)
self.image_control_canvas.grid_remove()
self.media_control_canvas.grid()
self.actions['StartRopeButton'].configure(self.button_highlight_style, text=' Load Rope')
img = Image.open('./rope/media/marker.png')
resized_image= img.resize((15,30), Image.ANTIALIAS)
self.marker_icon = ImageTk.PhotoImage(resized_image)
img = Image.open('./rope/media/stop_marker.png')
resized_image= img.resize((15,30), Image.ANTIALIAS)
self.stop_marker_icon = ImageTk.PhotoImage(resized_image)
class empty:
def __init__(self):
self.delta = 0
event = empty()
self.update_ui_button('Upscale')
self.update_ui_button('Diff')
self.update_ui_button('Border')
self.update_ui_button('MaskView')
self.update_ui_button('CLIP')
self.update_ui_button('Occluder')
self.update_ui_button('FaceParser')
self.update_ui_button('Blur')
self.update_ui_button('Threshold')
self.update_ui_button('Strength')
self.update_ui_button('Orientation')
self.update_ui_button('RefDel')
self.update_ui_button('Transform')
self.update_ui_button('Color')
# self.change_video_quality(event)
self.change_threads_amount(event)
self.add_action("parameters", self.parameters)
self.set_status('Welcome to Rope-Ruby!')
def load_all(self):
if not self.json_dict["source videos"] or not self.json_dict["source faces"]:
print("Please set faces and videos folders first!")
return
self.add_action("load_faceapp_model")
self.add_action("load_models")
self.actions['StartRopeButton'].configure(self.inactive_button_style, text=" Rope Loaded")
def select_video_path(self):
temp = self.json_dict["source videos"]
self.json_dict["source videos"] = filedialog.askdirectory(title="Select Target Videos Folder", initialdir=temp)
temp = self.json_dict["source videos"]
temp_len = len(temp)
temp = ' '+temp[temp_len-9:]
self.actions['LoadTVideosButton'].configure(self.inactive_button_style, text=temp)
with open("data.json", "w") as outfile:
json.dump(self.json_dict, outfile)
self.populate_target_videos()
def select_save_video_path(self):
temp = self.json_dict["saved videos"]
self.json_dict["saved videos"] = filedialog.askdirectory(title="Select Save Video Folder", initialdir=temp)
temp = self.json_dict["saved videos"]
temp_len = len(temp)
temp = ' '+temp[temp_len-9:]
self.actions['OutputFolderButton'].configure(self.inactive_button_style, text=temp)
self.add_action("saved_video_path",self.json_dict["saved videos"])
with open("data.json", "w") as outfile:
json.dump(self.json_dict, outfile)
def select_faces_path(self):
temp = self.json_dict["source faces"]
self.json_dict["source faces"] = filedialog.askdirectory(title="Select Source Faces Folder", initialdir=temp)
temp = self.json_dict["source faces"]
temp_len = len(temp)
temp = ' '+temp[temp_len-9:]
self.actions['LoadSFacesButton'].configure(self.inactive_button_style, text=temp)
with open("data.json", "w") as outfile:
json.dump(self.json_dict, outfile)
self.load_source_faces()
def load_source_faces(self):
if not self.detection_model:
self.add_action('load_faceapp_model')
else:
self.source_faces = []
self.source_faces_canvas.delete("all")
# First load merged embeddings
try:
temp0 = []
with open("merged_embeddings.txt", "r") as embedfile:
temp = embedfile.read().splitlines()
for i in range(0, len(temp), 513):
to = [temp[i][6:], np.array(temp[i+1:i+513], dtype='float32')]
temp0.append(to)
self.pixel = tk.PhotoImage(height=0, width=0)
for j in range(len(temp0)):
new_source_face = self.source_face.copy()
self.source_faces.append(new_source_face)
self.source_faces[j]["ButtonState"] = False
self.source_faces[j]["Embedding"] = temp0[j][1]
self.source_faces[j]["TKButton"] = tk.Button(self.source_faces_canvas, self.inactive_button_style, image=self.pixel, text=temp0[j][0], height=14, width=84, compound='left')
self.source_faces[j]["TKButton"].bind("<ButtonRelease-1>", lambda event, arg=j: self.toggle_source_faces_buttons_state(event, arg))
self.source_faces[j]["TKButton"].bind("<Shift-ButtonRelease-1>", lambda event, arg=j: self.toggle_source_faces_buttons_state_shift(event, arg))
self.source_faces[j]["TKButton"].bind("<MouseWheel>", self.source_faces_mouse_wheel)
self.source_faces_canvas.create_window((j//4)*92,8+(22*(j%4)), window = self.source_faces[j]["TKButton"],anchor='nw')
# print((j//4)*92,8+(22*(j%4)))
except:
pass
directory = self.json_dict["source faces"]
filenames = [os.path.join(dirpath,f) for (dirpath, dirnames, filenames) in os.walk(directory) for f in filenames]
faces = []
for file in filenames: # Does not include full path
# Find all faces and ad to faces[]
# Guess File type based on extension
try:
file_type = mimetypes.guess_type(file)[0][:5]
except:
print('Unrecognized file type:', file)
else:
# Its an image
if file_type == 'image':
try:
img = cv2.imread(file)
except:
print('Bad file', file)
else:
img = torch.from_numpy(img).to('cuda')
img = img.permute(2,0,1)
kpss = self.detect(img, input_size = (640, 640), max_num=1, metric='default')
ret = []
for i in range(kpss.shape[0]):
if kpss is not None:
face_kps = kpss[i]
face_emb, img_out = self.recognize(img, face_kps)
ret.append([face_kps, face_emb, img_out])
if ret:
crop = cv2.cvtColor(ret[0][2].cpu().numpy(), cv2.COLOR_BGR2RGB)
crop = cv2.resize( crop, (82, 82))
faces.append([crop, ret[0][1]])
shift_i_len = len(self.source_faces)
# Add faces[] images to buttons
for i in range(len(faces)):
new_source_face = self.source_face.copy()
self.source_faces.append(new_source_face)
shift_i = i+ shift_i_len
self.source_faces[shift_i]["Image"] = ImageTk.PhotoImage(image=Image.fromarray(faces[i][0]))
self.source_faces[shift_i]["Embedding"] = faces[i][1]
self.source_faces[shift_i]["TKButton"] = tk.Button(self.source_faces_canvas, self.inactive_button_style, image= self.source_faces[shift_i]["Image"], height = 86, width = 86)
self.source_faces[shift_i]["ButtonState"] = False
self.source_faces[shift_i]["TKButton"].bind("<ButtonRelease-1>", lambda event, arg=shift_i: self.toggle_source_faces_buttons_state(event, arg))
self.source_faces[shift_i]["TKButton"].bind("<Shift-ButtonRelease-1>", lambda event, arg=shift_i: self.toggle_source_faces_buttons_state_shift(event, arg))
self.source_faces[shift_i]["TKButton"].bind("<MouseWheel>", self.source_faces_mouse_wheel)
self.source_faces_canvas.create_window(((shift_i_len//4)+i+1)*92,8, window = self.source_faces[shift_i]["TKButton"],anchor='nw')
self.source_faces_canvas.configure(scrollregion = self.source_faces_canvas.bbox("all"))
self.source_faces_canvas.xview_moveto(0)
def find_faces(self, scope):
try:
img = torch.from_numpy(self.video_image).to('cuda')
img = img.permute(2,0,1)
kpss = self.detect(img, input_size = (640, 640), max_num=10, metric='default')
ret = []
for i in range(kpss.shape[0]):
if kpss is not None:
face_kps = kpss[i]
face_emb, img_out = self.recognize(img, face_kps)
ret.append([face_kps, face_emb, img_out])
except Exception:
print(" No video selected")
else:
# Find all faces and add to target_faces[]
if ret:
# Apply threshold tolerence
threshhold = self.parameters["ThresholdAmount"][0]/100.0
if self.parameters["ThresholdState"]:
threshhold = 0.0
# Loop thgouh all faces in video frame
for face in ret:
found = False
# Check if this face has already been found
for emb in self.target_faces:
if self.findCosineDistance(emb['Embedding'], face[1]) < threshhold:
found = True
break
# If we dont find any existing simularities, it means that this is a new face and should be added to our found faces
if not found:
crop = cv2.resize(face[2].cpu().numpy(), (82, 82))
new_target_face = self.target_face.copy()
self.target_faces.append(new_target_face)
last_index = len(self.target_faces)-1
self.target_faces[last_index]["TKButton"] = tk.Button(self.found_faces_canvas, self.inactive_button_style, height = 86, width = 86)
self.target_faces[last_index]["TKButton"].bind("<MouseWheel>", self.target_faces_mouse_wheel)
self.target_faces[last_index]["ButtonState"] = False
self.target_faces[last_index]["Image"] = ImageTk.PhotoImage(image=Image.fromarray(crop))
self.target_faces[last_index]["Embedding"] = face[1]
self.target_faces[last_index]["EmbeddingNumber"] = 1
# Add image to button
self.target_faces[-1]["TKButton"].config( pady = 10, image = self.target_faces[last_index]["Image"], command=lambda k=last_index: self.toggle_found_faces_buttons_state(k))
# Add button to canvas
self.found_faces_canvas.create_window((last_index)*92, 8, window=self.target_faces[last_index]["TKButton"], anchor='nw')
self.found_faces_canvas.configure(scrollregion = self.found_faces_canvas.bbox("all"))
def clear_faces(self):
self.target_faces = []
self.found_faces_canvas.delete("all")
# toggle the target faces button and make assignments
def toggle_found_faces_buttons_state(self, button):
# Turn all Target faces off
for i in range(len(self.target_faces)):
self.target_faces[i]["ButtonState"] = False
self.target_faces[i]["TKButton"].config(self.inactive_button_style)
# Set only the selected target face to on
self.target_faces[button]["ButtonState"] = True
self.target_faces[button]["TKButton"].config(self.button_highlight_style)
# set all source face buttons to off
for i in range(len(self.source_faces)):
self.source_faces[i]["ButtonState"] = False
self.source_faces[i]["TKButton"].config(self.inactive_button_style)
# turn back on the ones that are assigned to the curent target face
for i in range(len(self.target_faces[button]["SourceFaceAssignments"])):
self.source_faces[self.target_faces[button]["SourceFaceAssignments"][i]]["ButtonState"] = True
self.source_faces[self.target_faces[button]["SourceFaceAssignments"][i]]["TKButton"].config(self.button_highlight_style)
def toggle_source_faces_buttons_state(self, event, button):
# jot down the current state of the button
state = self.source_faces[button]["ButtonState"]
# Set all Source Face buttons to False
for face in self.source_faces:
face["TKButton"].config(self.inactive_button_style)
face["ButtonState"] = False
# Toggle the selected Source Face
self.source_faces[button]["ButtonState"] = not state
# If the source face is now on
if self.source_faces[button]["ButtonState"]:
self.source_faces[button]["TKButton"].config(self.button_highlight_style)
else:
self.source_faces[button]["TKButton"].config(self.inactive_button_style)
# Determine which target face is selected
# If there are target faces
if self.target_faces:
for face in self.target_faces:
# Find the first target face that is highlighted
if face["ButtonState"]:
# Clear the assignments
face["SourceFaceAssignments"] = []
# If a source face is highlighted
if self.source_faces[button]["ButtonState"]:
# Append new assignment
face["SourceFaceAssignments"].append(button)
face['AssignedEmbedding'] = self.source_faces[button]['Embedding']
break
self.add_action("target_faces", self.target_faces, True, False)
def toggle_source_faces_buttons_state_shift(self, event, button):
# Set all Source Face buttons to False
for face in self.source_faces:
face["TKButton"].config(self.inactive_button_style)
# Toggle the selected Source Face
self.source_faces[button]["ButtonState"] = not self.source_faces[button]["ButtonState"]
# Highlight all True buttons
for face in self.source_faces:
if face["ButtonState"]:
face["TKButton"].config(self.button_highlight_style)
# If a target face is selected
for tface in self.target_faces:
if tface["ButtonState"]:
# Clear all of the assignments
tface["SourceFaceAssignments"] = []
tface['AssignedEmbedding'] = np.zeros(512, dtype=np.float32)
# Iterate through all Source faces
num = 0
for j in range(len(self.source_faces)):
# If the source face is active
if self.source_faces[j]["ButtonState"]:
tface["SourceFaceAssignments"].append(j)
tface['AssignedEmbedding'] += self.source_faces[j]['Embedding']
num +=1
if num>0:
tface['AssignedEmbedding'] /= float(num)
break
self.add_action("target_faces", self.target_faces, True, False)
def populate_target_videos(self):
# Recursively read all media files from directory
directory = self.json_dict["source videos"]
filenames = [os.path.join(dirpath,f) for (dirpath, dirnames, filenames) in os.walk(directory) for f in filenames]
videos = []
images = []
self.target_media = []
self.target_media_buttons = []
self.target_media_canvas.delete("all")
for file in filenames: # Does not include full path
# Guess File type based on extension
try:
file_type = mimetypes.guess_type(file)[0][:5]
except:
print('Unrecognized file type:', file)
else:
# Its an image
if file_type == 'image':
try:
image = cv2.imread(file)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
except:
print('Trouble reading file:', file)
else:
ratio = float(image.shape[0]) / image.shape[1]
if ratio>1:
new_height = 82
new_width = int(new_height / ratio)
else:
new_width = 82
new_height = int(new_width * ratio)
det_scale = float(new_height) / image.shape[0]
image = cv2.resize(image, (new_width, new_height))
det_img = np.zeros( (82, 82, 3), dtype=np.uint8 )
image[:new_height, :new_width, :] = image
images.append([image, file])
# Its a video
elif file_type == 'video':
try:
video = cv2.VideoCapture(file)
except:
print('Trouble reading file:', file)
else:
if video.isOpened():
# Grab a frame from the middle for a thumbnail
video.set(cv2.CAP_PROP_POS_FRAMES, int(video.get(cv2.CAP_PROP_FRAME_COUNT)/2))
success, video_frame = video.read()
if success:
video_frame = cv2.cvtColor(video_frame, cv2.COLOR_BGR2RGB)
ratio = float(video_frame.shape[0]) / video_frame.shape[1]