msdhon393 commited on
Commit
2f8e688
·
verified ·
1 Parent(s): 38332f4

Upload 18 files

Browse files
roop/FaceSet.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ class FaceSet:
4
+ faces = []
5
+ ref_images = []
6
+ embedding_average = 'None'
7
+ embeddings_backup = None
8
+
9
+ def __init__(self):
10
+ self.faces = []
11
+ self.ref_images = []
12
+ self.embeddings_backup = None
13
+
14
+ def AverageEmbeddings(self):
15
+ if len(self.faces) > 1 and self.embeddings_backup is None:
16
+ self.embeddings_backup = self.faces[0]['embedding']
17
+ embeddings = [face.embedding for face in self.faces]
18
+
19
+ self.faces[0]['embedding'] = np.mean(embeddings, axis=0)
20
+ # try median too?
roop/ProcessEntry.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ class ProcessEntry:
2
+ def __init__(self, filename: str, start: int, end: int, fps: float):
3
+ self.filename = filename
4
+ self.finalname = None
5
+ self.startframe = start
6
+ self.endframe = end
7
+ self.fps = fps
roop/ProcessMgr.py ADDED
@@ -0,0 +1,663 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import numpy as np
4
+ import psutil
5
+
6
+ from roop.ProcessOptions import ProcessOptions
7
+
8
+ from roop.face_util import get_first_face, get_all_faces, rotate_image_180, rotate_anticlockwise, rotate_clockwise, clamp_cut_values
9
+ from roop.utilities import compute_cosine_distance, get_device, str_to_class
10
+ import roop.vr_util as vr
11
+
12
+ from typing import Any, List, Callable
13
+ from roop.typing import Frame, Face
14
+ from concurrent.futures import ThreadPoolExecutor, as_completed
15
+ from threading import Thread, Lock
16
+ from queue import Queue
17
+ from tqdm import tqdm
18
+ from roop.ffmpeg_writer import FFMPEG_VideoWriter
19
+ import roop.globals
20
+
21
+
22
+ def create_queue(temp_frame_paths: List[str]) -> Queue[str]:
23
+ queue: Queue[str] = Queue()
24
+ for frame_path in temp_frame_paths:
25
+ queue.put(frame_path)
26
+ return queue
27
+
28
+
29
+ def pick_queue(queue: Queue[str], queue_per_future: int) -> List[str]:
30
+ queues = []
31
+ for _ in range(queue_per_future):
32
+ if not queue.empty():
33
+ queues.append(queue.get())
34
+ return queues
35
+
36
+
37
+ class ProcessMgr():
38
+ input_face_datas = []
39
+ target_face_datas = []
40
+
41
+ imagemask = None
42
+
43
+ processors = []
44
+ options : ProcessOptions = None
45
+
46
+ num_threads = 1
47
+ current_index = 0
48
+ processing_threads = 1
49
+ buffer_wait_time = 0.1
50
+
51
+ lock = Lock()
52
+
53
+ frames_queue = None
54
+ processed_queue = None
55
+
56
+ videowriter= None
57
+
58
+ progress_gradio = None
59
+ total_frames = 0
60
+
61
+
62
+
63
+
64
+ plugins = {
65
+ 'faceswap' : 'FaceSwapInsightFace',
66
+ 'mask_clip2seg' : 'Mask_Clip2Seg',
67
+ 'mask_xseg' : 'Mask_XSeg',
68
+ 'codeformer' : 'Enhance_CodeFormer',
69
+ 'gfpgan' : 'Enhance_GFPGAN',
70
+ 'dmdnet' : 'Enhance_DMDNet',
71
+ 'gpen' : 'Enhance_GPEN',
72
+ 'restoreformer++' : 'Enhance_RestoreFormerPPlus',
73
+ }
74
+
75
+ def __init__(self, progress):
76
+ if progress is not None:
77
+ self.progress_gradio = progress
78
+
79
+
80
+ def initialize(self, input_faces, target_faces, options):
81
+ self.input_face_datas = input_faces
82
+ self.target_face_datas = target_faces
83
+ self.options = options
84
+
85
+ roop.globals.g_desired_face_analysis=["landmark_3d_68", "landmark_2d_106","detection","recognition"]
86
+ if options.swap_mode == "all_female" or options.swap_mode == "all_male":
87
+ roop.globals.g_desired_face_analysis.append("genderage")
88
+
89
+ processornames = options.processors.split(",")
90
+ devicename = get_device()
91
+ if len(self.processors) < 1:
92
+ for pn in processornames:
93
+ classname = self.plugins[pn]
94
+ module = 'roop.processors.' + classname
95
+ p = str_to_class(module, classname)
96
+ if p is not None:
97
+ p.Initialize(devicename)
98
+ self.processors.append(p)
99
+ else:
100
+ print(f"Not using {module}")
101
+ else:
102
+ for i in range(len(self.processors) -1, -1, -1):
103
+ if not self.processors[i].processorname in processornames:
104
+ self.processors[i].Release()
105
+ del self.processors[i]
106
+
107
+ for i,pn in enumerate(processornames):
108
+ if i >= len(self.processors) or self.processors[i].processorname != pn:
109
+ classname = self.plugins[pn]
110
+ module = 'roop.processors.' + classname
111
+ p = str_to_class(module, classname)
112
+ if p is not None:
113
+ p.Initialize(devicename)
114
+ self.processors.insert(i, p)
115
+ else:
116
+ print(f"Not using {module}")
117
+
118
+
119
+ if isinstance(self.options.imagemask, dict) and self.options.imagemask.get("layers") and len(self.options.imagemask["layers"]) > 0:
120
+ self.options.imagemask = self.options.imagemask.get("layers")[0]
121
+ # Get rid of alpha
122
+ self.options.imagemask = cv2.cvtColor(self.options.imagemask, cv2.COLOR_RGBA2GRAY)
123
+ if np.any(self.options.imagemask):
124
+ mo = self.input_face_datas[0].faces[0].mask_offsets
125
+ self.options.imagemask = self.blur_area(self.options.imagemask, mo[4], mo[5])
126
+ self.options.imagemask = self.options.imagemask.astype(np.float32) / 255
127
+ self.options.imagemask = cv2.cvtColor(self.options.imagemask, cv2.COLOR_GRAY2RGB)
128
+ else:
129
+ self.options.imagemask = None
130
+
131
+
132
+
133
+
134
+ def run_batch(self, source_files, target_files, threads:int = 1):
135
+ progress_bar_format = '{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]'
136
+ self.total_frames = len(source_files)
137
+ self.num_threads = threads
138
+ with tqdm(total=self.total_frames, desc='Processing', unit='frame', dynamic_ncols=True, bar_format=progress_bar_format) as progress:
139
+ with ThreadPoolExecutor(max_workers=threads) as executor:
140
+ futures = []
141
+ queue = create_queue(source_files)
142
+ queue_per_future = max(len(source_files) // threads, 1)
143
+ while not queue.empty():
144
+ future = executor.submit(self.process_frames, source_files, target_files, pick_queue(queue, queue_per_future), lambda: self.update_progress(progress))
145
+ futures.append(future)
146
+ for future in as_completed(futures):
147
+ future.result()
148
+
149
+
150
+ def process_frames(self, source_files: List[str], target_files: List[str], current_files, update: Callable[[], None]) -> None:
151
+ for f in current_files:
152
+ if not roop.globals.processing:
153
+ return
154
+
155
+ # Decode the byte array into an OpenCV image
156
+ temp_frame = cv2.imdecode(np.fromfile(f, dtype=np.uint8), cv2.IMREAD_COLOR)
157
+ if temp_frame is not None:
158
+ resimg = self.process_frame(temp_frame)
159
+ if resimg is not None:
160
+ i = source_files.index(f)
161
+ cv2.imwrite(target_files[i], resimg)
162
+ if update:
163
+ update()
164
+
165
+
166
+
167
+ def read_frames_thread(self, cap, frame_start, frame_end, num_threads):
168
+ num_frame = 0
169
+ total_num = frame_end - frame_start
170
+ if frame_start > 0:
171
+ cap.set(cv2.CAP_PROP_POS_FRAMES,frame_start)
172
+
173
+ while True and roop.globals.processing:
174
+ ret, frame = cap.read()
175
+ if not ret:
176
+ break
177
+
178
+ self.frames_queue[num_frame % num_threads].put(frame, block=True)
179
+ num_frame += 1
180
+ if num_frame == total_num:
181
+ break
182
+
183
+ for i in range(num_threads):
184
+ self.frames_queue[i].put(None)
185
+
186
+
187
+
188
+ def process_videoframes(self, threadindex, progress) -> None:
189
+ while True:
190
+ frame = self.frames_queue[threadindex].get()
191
+ if frame is None:
192
+ self.processing_threads -= 1
193
+ self.processed_queue[threadindex].put((False, None))
194
+ return
195
+ else:
196
+ resimg = self.process_frame(frame)
197
+ self.processed_queue[threadindex].put((True, resimg))
198
+ del frame
199
+ progress()
200
+
201
+
202
+ def write_frames_thread(self):
203
+ nextindex = 0
204
+ num_producers = self.num_threads
205
+
206
+ while True:
207
+ process, frame = self.processed_queue[nextindex % self.num_threads].get()
208
+ nextindex += 1
209
+ if frame is not None:
210
+ self.videowriter.write_frame(frame)
211
+ del frame
212
+ elif process == False:
213
+ num_producers -= 1
214
+ if num_producers < 1:
215
+ return
216
+
217
+
218
+
219
+ def run_batch_inmem(self, source_video, target_video, frame_start, frame_end, fps, threads:int = 1, skip_audio=False):
220
+ cap = cv2.VideoCapture(source_video)
221
+ # frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
222
+ frame_count = (frame_end - frame_start) + 1
223
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
224
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
225
+
226
+ self.total_frames = frame_count
227
+ self.num_threads = threads
228
+
229
+ self.processing_threads = self.num_threads
230
+ self.frames_queue = []
231
+ self.processed_queue = []
232
+ for _ in range(threads):
233
+ self.frames_queue.append(Queue(1))
234
+ self.processed_queue.append(Queue(1))
235
+
236
+ self.videowriter = FFMPEG_VideoWriter(target_video, (width, height), fps, codec=roop.globals.video_encoder, crf=roop.globals.video_quality, audiofile=None)
237
+
238
+ readthread = Thread(target=self.read_frames_thread, args=(cap, frame_start, frame_end, threads))
239
+ readthread.start()
240
+
241
+ writethread = Thread(target=self.write_frames_thread)
242
+ writethread.start()
243
+
244
+ progress_bar_format = '{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]'
245
+ with tqdm(total=self.total_frames, desc='Processing', unit='frames', dynamic_ncols=True, bar_format=progress_bar_format) as progress:
246
+ with ThreadPoolExecutor(thread_name_prefix='swap_proc', max_workers=self.num_threads) as executor:
247
+ futures = []
248
+
249
+ for threadindex in range(threads):
250
+ future = executor.submit(self.process_videoframes, threadindex, lambda: self.update_progress(progress))
251
+ futures.append(future)
252
+
253
+ for future in as_completed(futures):
254
+ future.result()
255
+ # wait for the task to complete
256
+ readthread.join()
257
+ writethread.join()
258
+ cap.release()
259
+ self.videowriter.close()
260
+ self.frames_queue.clear()
261
+ self.processed_queue.clear()
262
+
263
+
264
+
265
+
266
+ def update_progress(self, progress: Any = None) -> None:
267
+ process = psutil.Process(os.getpid())
268
+ memory_usage = process.memory_info().rss / 1024 / 1024 / 1024
269
+ progress.set_postfix({
270
+ 'memory_usage': '{:.2f}'.format(memory_usage).zfill(5) + 'GB',
271
+ 'execution_threads': self.num_threads
272
+ })
273
+ progress.update(1)
274
+ self.progress_gradio((progress.n, self.total_frames), desc='Processing', total=self.total_frames, unit='frames')
275
+
276
+
277
+ def on_no_face_action(self, frame:Frame):
278
+ if roop.globals.no_face_action == 0:
279
+ return None, frame
280
+ elif roop.globals.no_face_action == 2:
281
+ return None, None
282
+
283
+
284
+ faces = get_all_faces(frame)
285
+ if faces is not None:
286
+ return faces, frame
287
+ return None, frame
288
+
289
+ # https://github.com/deepinsight/insightface#third-party-re-implementation-of-arcface
290
+ # https://github.com/deepinsight/insightface/blob/master/alignment/coordinate_reg/image_infer.py
291
+ # https://github.com/deepinsight/insightface/issues/1350
292
+ # https://github.com/linghu8812/tensorrt_inference
293
+
294
+
295
+ def process_frame(self, frame:Frame):
296
+ use_original_frame = 0
297
+ skip_frame = 2
298
+
299
+ if len(self.input_face_datas) < 1 and not self.options.show_face_masking:
300
+ return frame
301
+ temp_frame = frame.copy()
302
+ num_swapped, temp_frame = self.swap_faces(frame, temp_frame)
303
+ if num_swapped > 0:
304
+ return temp_frame
305
+ if roop.globals.no_face_action == use_original_frame:
306
+ return frame
307
+ if roop.globals.no_face_action == skip_frame:
308
+ #This only works with in-mem processing, as it simply skips the frame.
309
+ #For 'extract frames' it simply leaves the unprocessed frame unprocessed and it gets used in the final output by ffmpeg.
310
+ #If we could delete that frame here, that'd work but that might cause ffmpeg to fail unless the frames are renamed, and I don't think we have the info on what frame it actually is?????
311
+ #alternatively, it could mark all the necessary frames for deletion, delete them at the end, then rename the remaining frames that might work?
312
+ return None
313
+ else:
314
+ copyframe = frame.copy()
315
+ copyframe = rotate_image_180(copyframe)
316
+ temp_frame = copyframe.copy()
317
+ num_swapped, temp_frame = self.swap_faces(copyframe, temp_frame)
318
+ if num_swapped == 0:
319
+ return frame
320
+ temp_frame = rotate_image_180(temp_frame)
321
+ return temp_frame
322
+
323
+
324
+ def swap_faces(self, frame, temp_frame):
325
+ num_faces_found = 0
326
+
327
+ if self.options.swap_mode == "first":
328
+ face = get_first_face(frame)
329
+
330
+ if face is None:
331
+ return num_faces_found, frame
332
+
333
+ num_faces_found += 1
334
+ temp_frame = self.process_face(self.options.selected_index, face, temp_frame)
335
+ else:
336
+ faces = get_all_faces(frame)
337
+ if faces is None:
338
+ return num_faces_found, frame
339
+
340
+ if self.options.swap_mode == "all":
341
+ for face in faces:
342
+ num_faces_found += 1
343
+ temp_frame = self.process_face(self.options.selected_index, face, temp_frame)
344
+ del face
345
+
346
+ elif self.options.swap_mode == "selected":
347
+ num_targetfaces = len(self.target_face_datas)
348
+ use_index = num_targetfaces == 1
349
+ for i,tf in enumerate(self.target_face_datas):
350
+ for face in faces:
351
+ if compute_cosine_distance(tf.embedding, face.embedding) <= self.options.face_distance_threshold:
352
+ if i < len(self.input_face_datas):
353
+ if use_index:
354
+ temp_frame = self.process_face(self.options.selected_index, face, temp_frame)
355
+ else:
356
+ temp_frame = self.process_face(i, face, temp_frame)
357
+ num_faces_found += 1
358
+ del face
359
+ if not roop.globals.vr_mode and num_faces_found == num_targetfaces:
360
+ break
361
+ elif self.options.swap_mode == "all_female" or self.options.swap_mode == "all_male":
362
+ gender = 'F' if self.options.swap_mode == "all_female" else 'M'
363
+ for face in faces:
364
+ if face.sex == gender:
365
+ num_faces_found += 1
366
+ temp_frame = self.process_face(self.options.selected_index, face, temp_frame)
367
+ del face
368
+
369
+ if roop.globals.vr_mode and num_faces_found % 2 > 0:
370
+ # stereo image, there has to be an even number of faces
371
+ num_faces_found = 0
372
+ return num_faces_found, frame
373
+ if num_faces_found == 0:
374
+ return num_faces_found, frame
375
+
376
+ #maskprocessor = next((x for x in self.processors if x.type == 'mask'), None)
377
+
378
+ if self.options.imagemask is not None and self.options.imagemask.shape == frame.shape:
379
+ temp_frame = self.simple_blend_with_mask(temp_frame, frame, self.options.imagemask)
380
+
381
+ #if maskprocessor is not None:
382
+ # temp_frame = self.process_mask(maskprocessor, frame, temp_frame)
383
+ return num_faces_found, temp_frame
384
+
385
+
386
+ def rotation_action(self, original_face:Face, frame:Frame):
387
+ (height, width) = frame.shape[:2]
388
+
389
+ bounding_box_width = original_face.bbox[2] - original_face.bbox[0]
390
+ bounding_box_height = original_face.bbox[3] - original_face.bbox[1]
391
+ horizontal_face = bounding_box_width > bounding_box_height
392
+
393
+ center_x = width // 2.0
394
+ start_x = original_face.bbox[0]
395
+ end_x = original_face.bbox[2]
396
+ bbox_center_x = start_x + (bounding_box_width // 2.0)
397
+
398
+ # need to leverage the array of landmarks as decribed here:
399
+ # https://github.com/deepinsight/insightface/tree/master/alignment/coordinate_reg
400
+ # basically, we should be able to check for the relative position of eyes and nose
401
+ # then use that to determine which way the face is actually facing when in a horizontal position
402
+ # and use that to determine the correct rotation_action
403
+
404
+ forehead_x = original_face.landmark_2d_106[72][0]
405
+ chin_x = original_face.landmark_2d_106[0][0]
406
+
407
+ if horizontal_face:
408
+ if chin_x < forehead_x:
409
+ # this is someone lying down with their face like this (:
410
+ return "rotate_anticlockwise"
411
+ elif forehead_x < chin_x:
412
+ # this is someone lying down with their face like this :)
413
+ return "rotate_clockwise"
414
+ if bbox_center_x >= center_x:
415
+ # this is someone lying down with their face in the right hand side of the frame
416
+ return "rotate_anticlockwise"
417
+ if bbox_center_x < center_x:
418
+ # this is someone lying down with their face in the left hand side of the frame
419
+ return "rotate_clockwise"
420
+
421
+ return None
422
+
423
+
424
+ def auto_rotate_frame(self, original_face, frame:Frame):
425
+ target_face = original_face
426
+ original_frame = frame
427
+
428
+ rotation_action = self.rotation_action(original_face, frame)
429
+
430
+ if rotation_action == "rotate_anticlockwise":
431
+ #face is horizontal, rotating frame anti-clockwise and getting face bounding box from rotated frame
432
+ frame = rotate_anticlockwise(frame)
433
+ elif rotation_action == "rotate_clockwise":
434
+ #face is horizontal, rotating frame clockwise and getting face bounding box from rotated frame
435
+ frame = rotate_clockwise(frame)
436
+
437
+ return target_face, frame, rotation_action
438
+
439
+
440
+ def auto_unrotate_frame(self, frame:Frame, rotation_action):
441
+ if rotation_action == "rotate_anticlockwise":
442
+ return rotate_clockwise(frame)
443
+ elif rotation_action == "rotate_clockwise":
444
+ return rotate_anticlockwise(frame)
445
+
446
+ return frame
447
+
448
+
449
+
450
+ def process_face(self,face_index, target_face:Face, frame:Frame):
451
+ from roop.face_util import align_crop
452
+
453
+ enhanced_frame = None
454
+ if(len(self.input_face_datas) > 0):
455
+ inputface = self.input_face_datas[face_index].faces[0]
456
+ else:
457
+ inputface = None
458
+
459
+ rotation_action = None
460
+ if roop.globals.autorotate_faces:
461
+ # check for sideways rotation of face
462
+ rotation_action = self.rotation_action(target_face, frame)
463
+ if rotation_action is not None:
464
+ (startX, startY, endX, endY) = target_face["bbox"].astype("int")
465
+ width = endX - startX
466
+ height = endY - startY
467
+ offs = int(max(width,height) * 0.25)
468
+ rotcutframe,startX, startY, endX, endY = self.cutout(frame, startX - offs, startY - offs, endX + offs, endY + offs)
469
+ if rotation_action == "rotate_anticlockwise":
470
+ rotcutframe = rotate_anticlockwise(rotcutframe)
471
+ elif rotation_action == "rotate_clockwise":
472
+ rotcutframe = rotate_clockwise(rotcutframe)
473
+ # rotate image and re-detect face to correct wonky landmarks
474
+ rotface = get_first_face(rotcutframe)
475
+ if rotface is None:
476
+ rotation_action = None
477
+ else:
478
+ saved_frame = frame.copy()
479
+ frame = rotcutframe
480
+ target_face = rotface
481
+
482
+
483
+
484
+ # if roop.globals.vr_mode:
485
+ # bbox = target_face.bbox
486
+ # [orig_width, orig_height, _] = frame.shape
487
+
488
+ # # Convert bounding box to ints
489
+ # x1, y1, x2, y2 = map(int, bbox)
490
+
491
+ # # Determine the center of the bounding box
492
+ # x_center = (x1 + x2) / 2
493
+ # y_center = (y1 + y2) / 2
494
+
495
+ # # Normalize coordinates to range [-1, 1]
496
+ # x_center_normalized = x_center / (orig_width / 2) - 1
497
+ # y_center_normalized = y_center / (orig_width / 2) - 1
498
+
499
+ # # Convert normalized coordinates to spherical (theta, phi)
500
+ # theta = x_center_normalized * 180 # Theta ranges from -180 to 180 degrees
501
+ # phi = -y_center_normalized * 90 # Phi ranges from -90 to 90 degrees
502
+
503
+ # img = vr.GetPerspective(frame, 90, theta, phi, 1280, 1280) # Generate perspective image
504
+
505
+ fake_frame = None
506
+ aligned_img, M = align_crop(frame, target_face.kps, 128)
507
+ fake_frame = aligned_img
508
+ swap_frame = aligned_img
509
+ target_face.matrix = M
510
+ for p in self.processors:
511
+ if p.type == 'swap':
512
+ if inputface is not None:
513
+ for _ in range(0,self.options.num_swap_steps):
514
+ swap_frame = p.Run(inputface, target_face, swap_frame)
515
+ fake_frame = swap_frame
516
+ scale_factor = 0.0
517
+ elif p.type == 'mask':
518
+ fake_frame = self.process_mask(p, aligned_img, fake_frame)
519
+ else:
520
+ enhanced_frame, scale_factor = p.Run(self.input_face_datas[face_index], target_face, fake_frame)
521
+
522
+ upscale = 512
523
+ orig_width = fake_frame.shape[1]
524
+
525
+ fake_frame = cv2.resize(fake_frame, (upscale, upscale), cv2.INTER_CUBIC)
526
+ mask_offsets = (0,0,0,0,1,20) if inputface is None else inputface.mask_offsets
527
+
528
+
529
+ if enhanced_frame is None:
530
+ scale_factor = int(upscale / orig_width)
531
+ result = self.paste_upscale(fake_frame, fake_frame, target_face.matrix, frame, scale_factor, mask_offsets)
532
+ else:
533
+ result = self.paste_upscale(fake_frame, enhanced_frame, target_face.matrix, frame, scale_factor, mask_offsets)
534
+
535
+ if rotation_action is not None:
536
+ fake_frame = self.auto_unrotate_frame(result, rotation_action)
537
+ return self.paste_simple(fake_frame, saved_frame, startX, startY)
538
+
539
+ return result
540
+
541
+
542
+
543
+
544
+ def cutout(self, frame:Frame, start_x, start_y, end_x, end_y):
545
+ if start_x < 0:
546
+ start_x = 0
547
+ if start_y < 0:
548
+ start_y = 0
549
+ if end_x > frame.shape[1]:
550
+ end_x = frame.shape[1]
551
+ if end_y > frame.shape[0]:
552
+ end_y = frame.shape[0]
553
+ return frame[start_y:end_y, start_x:end_x], start_x, start_y, end_x, end_y
554
+
555
+ def paste_simple(self, src:Frame, dest:Frame, start_x, start_y):
556
+ end_x = start_x + src.shape[1]
557
+ end_y = start_y + src.shape[0]
558
+
559
+ start_x, end_x, start_y, end_y = clamp_cut_values(start_x, end_x, start_y, end_y, dest)
560
+ dest[start_y:end_y, start_x:end_x] = src
561
+ return dest
562
+
563
+ def simple_blend_with_mask(self, image1, image2, mask):
564
+ # Blend the images
565
+ blended_image = image1.astype(np.float32) * (1.0 - mask) + image2.astype(np.float32) * mask
566
+ return blended_image.astype(np.uint8)
567
+
568
+
569
+ def paste_upscale(self, fake_face, upsk_face, M, target_img, scale_factor, mask_offsets):
570
+ M_scale = M * scale_factor
571
+ IM = cv2.invertAffineTransform(M_scale)
572
+
573
+ face_matte = np.full((target_img.shape[0],target_img.shape[1]), 255, dtype=np.uint8)
574
+ # Generate white square sized as a upsk_face
575
+ img_matte = np.zeros((upsk_face.shape[0],upsk_face.shape[1]), dtype=np.uint8)
576
+
577
+ w = img_matte.shape[1]
578
+ h = img_matte.shape[0]
579
+
580
+ top = int(mask_offsets[0] * h)
581
+ bottom = int(h - (mask_offsets[1] * h))
582
+ left = int(mask_offsets[2] * w)
583
+ right = int(w - (mask_offsets[3] * w))
584
+ img_matte[top:bottom,left:right] = 255
585
+
586
+ # Transform white square back to target_img
587
+ img_matte = cv2.warpAffine(img_matte, IM, (target_img.shape[1], target_img.shape[0]), flags=cv2.INTER_NEAREST, borderValue=0.0)
588
+ ##Blacken the edges of face_matte by 1 pixels (so the mask in not expanded on the image edges)
589
+ img_matte[:1,:] = img_matte[-1:,:] = img_matte[:,:1] = img_matte[:,-1:] = 0
590
+
591
+ img_matte = self.blur_area(img_matte, mask_offsets[4], mask_offsets[5])
592
+ #Normalize images to float values and reshape
593
+ img_matte = img_matte.astype(np.float32)/255
594
+ face_matte = face_matte.astype(np.float32)/255
595
+ img_matte = np.minimum(face_matte, img_matte)
596
+ if self.options.show_face_area_overlay:
597
+ # Additional steps for green overlay
598
+ green_overlay = np.zeros_like(target_img)
599
+ green_color = [0, 255, 0] # RGB for green
600
+ for i in range(3): # Apply green color where img_matte is not zero
601
+ green_overlay[:, :, i] = np.where(img_matte > 0, green_color[i], 0) ##Transform upcaled face back to target_img
602
+ img_matte = np.reshape(img_matte, [img_matte.shape[0],img_matte.shape[1],1])
603
+ paste_face = cv2.warpAffine(upsk_face, IM, (target_img.shape[1], target_img.shape[0]), borderMode=cv2.BORDER_REPLICATE)
604
+ if upsk_face is not fake_face:
605
+ fake_face = cv2.warpAffine(fake_face, IM, (target_img.shape[1], target_img.shape[0]), borderMode=cv2.BORDER_REPLICATE)
606
+ paste_face = cv2.addWeighted(paste_face, self.options.blend_ratio, fake_face, 1.0 - self.options.blend_ratio, 0)
607
+
608
+ # Re-assemble image
609
+ paste_face = img_matte * paste_face
610
+ paste_face = paste_face + (1-img_matte) * target_img.astype(np.float32)
611
+ if self.options.show_face_area_overlay:
612
+ # Overlay the green overlay on the final image
613
+ paste_face = cv2.addWeighted(paste_face.astype(np.uint8), 1 - 0.5, green_overlay, 0.5, 0)
614
+ return paste_face.astype(np.uint8)
615
+
616
+
617
+ def blur_area(self, img_matte, num_erosion_iterations, blur_amount):
618
+ # Detect the affine transformed white area
619
+ mask_h_inds, mask_w_inds = np.where(img_matte==255)
620
+ # Calculate the size (and diagonal size) of transformed white area width and height boundaries
621
+ mask_h = np.max(mask_h_inds) - np.min(mask_h_inds)
622
+ mask_w = np.max(mask_w_inds) - np.min(mask_w_inds)
623
+ mask_size = int(np.sqrt(mask_h*mask_w))
624
+ # Calculate the kernel size for eroding img_matte by kernel (insightface empirical guess for best size was max(mask_size//10,10))
625
+ # k = max(mask_size//12, 8)
626
+ k = max(mask_size//(blur_amount // 2) , blur_amount // 2)
627
+ kernel = np.ones((k,k),np.uint8)
628
+ img_matte = cv2.erode(img_matte,kernel,iterations = num_erosion_iterations)
629
+ #Calculate the kernel size for blurring img_matte by blur_size (insightface empirical guess for best size was max(mask_size//20, 5))
630
+ # k = max(mask_size//24, 4)
631
+ k = max(mask_size//blur_amount, blur_amount//5)
632
+ kernel_size = (k, k)
633
+ blur_size = tuple(2*i+1 for i in kernel_size)
634
+ return cv2.GaussianBlur(img_matte, blur_size, 0)
635
+
636
+
637
+ def process_mask(self, processor, frame:Frame, target:Frame):
638
+ img_mask = processor.Run(frame, self.options.masking_text)
639
+ img_mask = cv2.resize(img_mask, (target.shape[1], target.shape[0]))
640
+ img_mask = np.reshape(img_mask, [img_mask.shape[0],img_mask.shape[1],1])
641
+
642
+ if self.options.show_face_masking:
643
+ result = (1 - img_mask) * frame.astype(np.float32)
644
+ return np.uint8(result)
645
+
646
+
647
+ target = target.astype(np.float32)
648
+ result = (1-img_mask) * target
649
+ result += img_mask * frame.astype(np.float32)
650
+ return np.uint8(result)
651
+
652
+
653
+
654
+
655
+ def unload_models():
656
+ pass
657
+
658
+
659
+ def release_resources(self):
660
+ for p in self.processors:
661
+ p.Release()
662
+ self.processors.clear()
663
+
roop/ProcessOptions.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class ProcessOptions:
2
+
3
+ def __init__(self,processors, face_distance, blend_ratio, swap_mode, selected_index, masking_text, imagemask, num_steps, show_face_area, show_mask=False):
4
+ self.processors = processors
5
+ self.face_distance_threshold = face_distance
6
+ self.blend_ratio = blend_ratio
7
+ self.swap_mode = swap_mode
8
+ self.selected_index = selected_index
9
+ self.masking_text = masking_text
10
+ self.imagemask = imagemask
11
+ self.num_swap_steps = num_steps
12
+ self.show_face_area_overlay = show_face_area
13
+ self.show_face_masking = show_mask
roop/__init__.py ADDED
File without changes
roop/capturer.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+ import cv2
3
+ import numpy as np
4
+
5
+ from roop.typing import Frame
6
+
7
+ def get_image_frame(filename: str):
8
+ try:
9
+ return cv2.imdecode(np.fromfile(filename, dtype=np.uint8), cv2.IMREAD_COLOR)
10
+ except:
11
+ print(f"Exception reading {filename}")
12
+ return None
13
+
14
+
15
+ def get_video_frame(video_path: str, frame_number: int = 0) -> Optional[Frame]:
16
+ capture = cv2.VideoCapture(video_path)
17
+ frame_total = capture.get(cv2.CAP_PROP_FRAME_COUNT)
18
+ capture.set(cv2.CAP_PROP_POS_FRAMES, min(frame_total, frame_number - 1))
19
+ has_frame, frame = capture.read()
20
+ capture.release()
21
+ if has_frame:
22
+ return frame
23
+ return None
24
+
25
+
26
+ def get_video_frame_total(video_path: str) -> int:
27
+ capture = cv2.VideoCapture(video_path)
28
+ video_frame_total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
29
+ capture.release()
30
+ return video_frame_total
roop/core.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ import os
4
+ import sys
5
+ import shutil
6
+ # single thread doubles cuda performance - needs to be set before torch import
7
+ if any(arg.startswith('--execution-provider') for arg in sys.argv):
8
+ os.environ['OMP_NUM_THREADS'] = '1'
9
+
10
+ import warnings
11
+ from typing import List
12
+ import platform
13
+ import signal
14
+ import torch
15
+ import onnxruntime
16
+ import pathlib
17
+
18
+ from time import time
19
+
20
+ import roop.globals
21
+ import roop.metadata
22
+ import roop.utilities as util
23
+ import roop.util_ffmpeg as ffmpeg
24
+ import ui.main as main
25
+ from settings import Settings
26
+ from roop.face_util import extract_face_images
27
+ from roop.ProcessEntry import ProcessEntry
28
+ from roop.ProcessMgr import ProcessMgr
29
+ from roop.ProcessOptions import ProcessOptions
30
+ from roop.capturer import get_video_frame_total
31
+
32
+
33
+ clip_text = None
34
+
35
+ call_display_ui = None
36
+
37
+ process_mgr = None
38
+
39
+
40
+ if 'ROCMExecutionProvider' in roop.globals.execution_providers:
41
+ del torch
42
+
43
+ warnings.filterwarnings('ignore', category=FutureWarning, module='insightface')
44
+ warnings.filterwarnings('ignore', category=UserWarning, module='torchvision')
45
+
46
+
47
+ def parse_args() -> None:
48
+ signal.signal(signal.SIGINT, lambda signal_number, frame: destroy())
49
+ roop.globals.headless = False
50
+ # Always enable all processors when using GUI
51
+ if len(sys.argv) > 1:
52
+ print('No CLI args supported - use Settings Tab instead')
53
+ roop.globals.frame_processors = ['face_swapper', 'face_enhancer']
54
+
55
+
56
+ def encode_execution_providers(execution_providers: List[str]) -> List[str]:
57
+ return [execution_provider.replace('ExecutionProvider', '').lower() for execution_provider in execution_providers]
58
+
59
+
60
+ def decode_execution_providers(execution_providers: List[str]) -> List[str]:
61
+ return [provider for provider, encoded_execution_provider in zip(onnxruntime.get_available_providers(), encode_execution_providers(onnxruntime.get_available_providers()))
62
+ if any(execution_provider in encoded_execution_provider for execution_provider in execution_providers)]
63
+
64
+
65
+ def suggest_max_memory() -> int:
66
+ if platform.system().lower() == 'darwin':
67
+ return 4
68
+ return 16
69
+
70
+
71
+ def suggest_execution_providers() -> List[str]:
72
+ return encode_execution_providers(onnxruntime.get_available_providers())
73
+
74
+
75
+ def suggest_execution_threads() -> int:
76
+ if 'DmlExecutionProvider' in roop.globals.execution_providers:
77
+ return 1
78
+ if 'ROCMExecutionProvider' in roop.globals.execution_providers:
79
+ return 1
80
+ return 8
81
+
82
+
83
+ def limit_resources() -> None:
84
+ # limit memory usage
85
+ if roop.globals.max_memory:
86
+ memory = roop.globals.max_memory * 1024 ** 3
87
+ if platform.system().lower() == 'darwin':
88
+ memory = roop.globals.max_memory * 1024 ** 6
89
+ if platform.system().lower() == 'windows':
90
+ import ctypes
91
+ kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
92
+ kernel32.SetProcessWorkingSetSize(-1, ctypes.c_size_t(memory), ctypes.c_size_t(memory))
93
+ else:
94
+ import resource
95
+ resource.setrlimit(resource.RLIMIT_DATA, (memory, memory))
96
+
97
+
98
+
99
+ def release_resources() -> None:
100
+ import gc
101
+ global process_mgr
102
+
103
+ if process_mgr is not None:
104
+ process_mgr.release_resources()
105
+ process_mgr = None
106
+
107
+ gc.collect()
108
+ # if 'CUDAExecutionProvider' in roop.globals.execution_providers and torch.cuda.is_available():
109
+ # with torch.cuda.device('cuda'):
110
+ # torch.cuda.empty_cache()
111
+ # torch.cuda.ipc_collect()
112
+
113
+
114
+ def pre_check() -> bool:
115
+ if sys.version_info < (3, 9):
116
+ update_status('Python version is not supported - please upgrade to 3.9 or higher.')
117
+ return False
118
+
119
+ download_directory_path = util.resolve_relative_path('../models')
120
+ util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/inswapper_128.onnx'])
121
+ util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/GFPGANv1.4.onnx'])
122
+ util.conditional_download(download_directory_path, ['https://github.com/csxmli2016/DMDNet/releases/download/v1/DMDNet.pth'])
123
+ util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/GPEN-BFR-512.onnx'])
124
+ util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/restoreformer_plus_plus.onnx'])
125
+ util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/xseg.onnx'])
126
+ download_directory_path = util.resolve_relative_path('../models/CLIP')
127
+ util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/rd64-uni-refined.pth'])
128
+ download_directory_path = util.resolve_relative_path('../models/CodeFormer')
129
+ util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/CodeFormerv0.1.onnx'])
130
+
131
+ if not shutil.which('ffmpeg'):
132
+ update_status('ffmpeg is not installed.')
133
+ return True
134
+
135
+ def set_display_ui(function):
136
+ global call_display_ui
137
+
138
+ call_display_ui = function
139
+
140
+
141
+ def update_status(message: str) -> None:
142
+ global call_display_ui
143
+
144
+ print(message)
145
+ if call_display_ui is not None:
146
+ call_display_ui(message)
147
+
148
+
149
+
150
+
151
+ def start() -> None:
152
+ if roop.globals.headless:
153
+ print('Headless mode currently unsupported - starting UI!')
154
+ # faces = extract_face_images(roop.globals.source_path, (False, 0))
155
+ # roop.globals.INPUT_FACES.append(faces[roop.globals.source_face_index])
156
+ # faces = extract_face_images(roop.globals.target_path, (False, util.has_image_extension(roop.globals.target_path)))
157
+ # roop.globals.TARGET_FACES.append(faces[roop.globals.target_face_index])
158
+ # if 'face_enhancer' in roop.globals.frame_processors:
159
+ # roop.globals.selected_enhancer = 'GFPGAN'
160
+
161
+ batch_process(None, False, None)
162
+
163
+
164
+ def get_processing_plugins(masking_engine):
165
+ processors = "faceswap"
166
+ if masking_engine is not None:
167
+ processors += f",{masking_engine}"
168
+
169
+ if roop.globals.selected_enhancer == 'GFPGAN':
170
+ processors += ",gfpgan"
171
+ elif roop.globals.selected_enhancer == 'Codeformer':
172
+ processors += ",codeformer"
173
+ elif roop.globals.selected_enhancer == 'DMDNet':
174
+ processors += ",dmdnet"
175
+ elif roop.globals.selected_enhancer == 'GPEN':
176
+ processors += ",gpen"
177
+ elif roop.globals.selected_enhancer == 'Restoreformer++':
178
+ processors += ",restoreformer++"
179
+ return processors
180
+
181
+
182
+ def live_swap(frame, options):
183
+ global process_mgr
184
+
185
+ if frame is None:
186
+ return frame
187
+
188
+ if process_mgr is None:
189
+ process_mgr = ProcessMgr(None)
190
+
191
+ # if len(roop.globals.INPUT_FACESETS) <= selected_index:
192
+ # selected_index = 0
193
+ process_mgr.initialize(roop.globals.INPUT_FACESETS, roop.globals.TARGET_FACES, options)
194
+ newframe = process_mgr.process_frame(frame)
195
+ if newframe is None:
196
+ return frame
197
+ return newframe
198
+
199
+
200
+
201
+
202
+ def batch_process(files:list[ProcessEntry], masking_engine:str, new_clip_text:str, use_new_method, imagemask, num_swap_steps, progress, selected_index = 0) -> None:
203
+ global clip_text, process_mgr
204
+
205
+ roop.globals.processing = True
206
+ release_resources()
207
+ limit_resources()
208
+
209
+ # limit threads for some providers
210
+ max_threads = suggest_execution_threads()
211
+ if max_threads == 1:
212
+ roop.globals.execution_threads = 1
213
+
214
+ imagefiles:list[ProcessEntry] = []
215
+ videofiles:list[ProcessEntry] = []
216
+
217
+ update_status('Sorting videos/images')
218
+
219
+
220
+ for index, f in enumerate(files):
221
+ fullname = f.filename
222
+ if util.has_image_extension(fullname):
223
+ destination = util.get_destfilename_from_path(fullname, roop.globals.output_path, f'.{roop.globals.CFG.output_image_format}')
224
+ destination = util.replace_template(destination, index=index)
225
+ pathlib.Path(os.path.dirname(destination)).mkdir(parents=True, exist_ok=True)
226
+ f.finalname = destination
227
+ imagefiles.append(f)
228
+
229
+ elif util.is_video(fullname) or util.has_extension(fullname, ['gif']):
230
+ destination = util.get_destfilename_from_path(fullname, roop.globals.output_path, f'__temp.{roop.globals.CFG.output_video_format}')
231
+ f.finalname = destination
232
+ videofiles.append(f)
233
+
234
+
235
+ if process_mgr is None:
236
+ process_mgr = ProcessMgr(progress)
237
+ mask = imagemask["layers"][0] if imagemask is not None else None
238
+ if len(roop.globals.INPUT_FACESETS) <= selected_index:
239
+ selected_index = 0
240
+ options = ProcessOptions(get_processing_plugins(masking_engine), roop.globals.distance_threshold, roop.globals.blend_ratio, roop.globals.face_swap_mode, selected_index, new_clip_text, mask, num_swap_steps, False)
241
+ process_mgr.initialize(roop.globals.INPUT_FACESETS, roop.globals.TARGET_FACES, options)
242
+
243
+ if(len(imagefiles) > 0):
244
+ update_status('Processing image(s)')
245
+ origimages = []
246
+ fakeimages = []
247
+ for f in imagefiles:
248
+ origimages.append(f.filename)
249
+ fakeimages.append(f.finalname)
250
+
251
+ process_mgr.run_batch(origimages, fakeimages, roop.globals.execution_threads)
252
+ origimages.clear()
253
+ fakeimages.clear()
254
+
255
+ if(len(videofiles) > 0):
256
+ for index,v in enumerate(videofiles):
257
+ if not roop.globals.processing:
258
+ end_processing('Processing stopped!')
259
+ return
260
+ fps = v.fps if v.fps > 0 else util.detect_fps(v.filename)
261
+ if v.endframe == 0:
262
+ v.endframe = get_video_frame_total(v.filename)
263
+
264
+ update_status(f'Creating {os.path.basename(v.finalname)} with {fps} FPS...')
265
+ start_processing = time()
266
+ if roop.globals.keep_frames or not use_new_method:
267
+ util.create_temp(v.filename)
268
+ update_status('Extracting frames...')
269
+ ffmpeg.extract_frames(v.filename,v.startframe,v.endframe, fps)
270
+ if not roop.globals.processing:
271
+ end_processing('Processing stopped!')
272
+ return
273
+
274
+ temp_frame_paths = util.get_temp_frame_paths(v.filename)
275
+ process_mgr.run_batch(temp_frame_paths, temp_frame_paths, roop.globals.execution_threads)
276
+ if not roop.globals.processing:
277
+ end_processing('Processing stopped!')
278
+ return
279
+ if roop.globals.wait_after_extraction:
280
+ extract_path = os.path.dirname(temp_frame_paths[0])
281
+ util.open_folder(extract_path)
282
+ input("Press any key to continue...")
283
+ print("Resorting frames to create video")
284
+ util.sort_rename_frames(extract_path)
285
+
286
+ ffmpeg.create_video(v.filename, v.finalname, fps)
287
+ if not roop.globals.keep_frames:
288
+ util.delete_temp_frames(temp_frame_paths[0])
289
+ else:
290
+ if util.has_extension(v.filename, ['gif']):
291
+ skip_audio = True
292
+ else:
293
+ skip_audio = roop.globals.skip_audio
294
+ process_mgr.run_batch_inmem(v.filename, v.finalname, v.startframe, v.endframe, fps,roop.globals.execution_threads, skip_audio)
295
+
296
+ if not roop.globals.processing:
297
+ end_processing('Processing stopped!')
298
+ return
299
+
300
+ video_file_name = v.finalname
301
+ if os.path.isfile(video_file_name):
302
+ destination = ''
303
+ if util.has_extension(v.filename, ['gif']):
304
+ gifname = util.get_destfilename_from_path(v.filename, roop.globals.output_path, '.gif')
305
+ destination = util.replace_template(gifname, index=index)
306
+ pathlib.Path(os.path.dirname(destination)).mkdir(parents=True, exist_ok=True)
307
+
308
+ update_status('Creating final GIF')
309
+ ffmpeg.create_gif_from_video(video_file_name, destination)
310
+ if os.path.isfile(destination):
311
+ os.remove(video_file_name)
312
+ else:
313
+ skip_audio = roop.globals.skip_audio
314
+ destination = util.replace_template(video_file_name, index=index)
315
+ pathlib.Path(os.path.dirname(destination)).mkdir(parents=True, exist_ok=True)
316
+
317
+ if not skip_audio:
318
+ ffmpeg.restore_audio(video_file_name, v.filename, v.startframe, v.endframe, destination)
319
+ if os.path.isfile(destination):
320
+ os.remove(video_file_name)
321
+ else:
322
+ shutil.move(video_file_name, destination)
323
+ update_status(f'\nProcessing {os.path.basename(destination)} took {time() - start_processing} secs')
324
+
325
+ else:
326
+ update_status(f'Failed processing {os.path.basename(v.finalname)}!')
327
+ end_processing('Finished')
328
+
329
+
330
+ def end_processing(msg:str):
331
+ update_status(msg)
332
+ roop.globals.target_folder_path = None
333
+ release_resources()
334
+
335
+
336
+ def destroy() -> None:
337
+ if roop.globals.target_path:
338
+ util.clean_temp(roop.globals.target_path)
339
+ release_resources()
340
+ sys.exit()
341
+
342
+
343
+ def run() -> None:
344
+ parse_args()
345
+ if not pre_check():
346
+ return
347
+ roop.globals.CFG = Settings('config.yaml')
348
+ roop.globals.execution_threads = roop.globals.CFG.max_threads
349
+ roop.globals.video_encoder = roop.globals.CFG.output_video_codec
350
+ roop.globals.video_quality = roop.globals.CFG.video_quality
351
+ roop.globals.max_memory = roop.globals.CFG.memory_limit if roop.globals.CFG.memory_limit > 0 else None
352
+ main.run()
roop/face_util.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import threading
2
+ from typing import Any
3
+ import insightface
4
+
5
+ import roop.globals
6
+ from roop.typing import Frame, Face
7
+
8
+ import cv2
9
+ import numpy as np
10
+ from skimage import transform as trans
11
+ from roop.capturer import get_video_frame
12
+ from roop.utilities import resolve_relative_path, conditional_download
13
+
14
+ FACE_ANALYSER = None
15
+ THREAD_LOCK_ANALYSER = threading.Lock()
16
+ THREAD_LOCK_SWAPPER = threading.Lock()
17
+ FACE_SWAPPER = None
18
+
19
+
20
+ def get_face_analyser() -> Any:
21
+ global FACE_ANALYSER
22
+
23
+ with THREAD_LOCK_ANALYSER:
24
+ if FACE_ANALYSER is None or roop.globals.g_current_face_analysis != roop.globals.g_desired_face_analysis:
25
+ model_path = resolve_relative_path('..')
26
+ # removed genderage
27
+ allowed_modules = roop.globals.g_desired_face_analysis
28
+ roop.globals.g_current_face_analysis = roop.globals.g_desired_face_analysis
29
+ if roop.globals.CFG.force_cpu:
30
+ print("Forcing CPU for Face Analysis")
31
+ FACE_ANALYSER = insightface.app.FaceAnalysis(
32
+ name="buffalo_l",
33
+ root=model_path, providers=["CPUExecutionProvider"],allowed_modules=allowed_modules
34
+ )
35
+ else:
36
+ FACE_ANALYSER = insightface.app.FaceAnalysis(
37
+ name="buffalo_l", root=model_path, providers=roop.globals.execution_providers,allowed_modules=allowed_modules
38
+ )
39
+ FACE_ANALYSER.prepare(
40
+ ctx_id=0,
41
+ det_size=(640, 640) if roop.globals.default_det_size else (320, 320),
42
+ )
43
+ return FACE_ANALYSER
44
+
45
+
46
+ def get_first_face(frame: Frame) -> Any:
47
+ try:
48
+ faces = get_face_analyser().get(frame)
49
+ return min(faces, key=lambda x: x.bbox[0])
50
+ # return sorted(faces, reverse=True, key=lambda x: (x.bbox[2] - x.bbox[0]) * (x.bbox[3] - x.bbox[1]))[0]
51
+ except:
52
+ return None
53
+
54
+
55
+ def get_all_faces(frame: Frame) -> Any:
56
+ try:
57
+ faces = get_face_analyser().get(frame)
58
+ return sorted(faces, key=lambda x: x.bbox[0])
59
+ except:
60
+ return None
61
+
62
+
63
+ def extract_face_images(source_filename, video_info, extra_padding=-1.0):
64
+ face_data = []
65
+ source_image = None
66
+
67
+ if video_info[0]:
68
+ frame = get_video_frame(source_filename, video_info[1])
69
+ if frame is not None:
70
+ source_image = frame
71
+ else:
72
+ return face_data
73
+ else:
74
+ source_image = cv2.imdecode(np.fromfile(source_filename, dtype=np.uint8), cv2.IMREAD_COLOR)
75
+
76
+ faces = get_all_faces(source_image)
77
+ if faces is None:
78
+ return face_data
79
+
80
+ i = 0
81
+ for face in faces:
82
+ (startX, startY, endX, endY) = face["bbox"].astype("int")
83
+ startX, endX, startY, endY = clamp_cut_values(startX, endX, startY, endY, source_image)
84
+ if extra_padding > 0.0:
85
+ if source_image.shape[:2] == (512, 512):
86
+ i += 1
87
+ face_data.append([face, source_image])
88
+ continue
89
+
90
+ found = False
91
+ for i in range(1, 3):
92
+ (startX, startY, endX, endY) = face["bbox"].astype("int")
93
+ startX, endX, startY, endY = clamp_cut_values(startX, endX, startY, endY, source_image)
94
+ cutout_padding = extra_padding
95
+ # top needs extra room for detection
96
+ padding = int((endY - startY) * cutout_padding)
97
+ oldY = startY
98
+ startY -= padding
99
+
100
+ factor = 0.25 if i == 1 else 0.5
101
+ cutout_padding = factor
102
+ padding = int((endY - oldY) * cutout_padding)
103
+ endY += padding
104
+ padding = int((endX - startX) * cutout_padding)
105
+ startX -= padding
106
+ endX += padding
107
+ startX, endX, startY, endY = clamp_cut_values(
108
+ startX, endX, startY, endY, source_image
109
+ )
110
+ face_temp = source_image[startY:endY, startX:endX]
111
+ face_temp = resize_image_keep_content(face_temp)
112
+ testfaces = get_all_faces(face_temp)
113
+ if testfaces is not None and len(testfaces) > 0:
114
+ i += 1
115
+ face_data.append([testfaces[0], face_temp])
116
+ found = True
117
+ break
118
+
119
+ if not found:
120
+ print("No face found after resizing, this shouldn't happen!")
121
+ continue
122
+
123
+ face_temp = source_image[startY:endY, startX:endX]
124
+ if face_temp.size < 1:
125
+ continue
126
+
127
+ i += 1
128
+ face_data.append([face, face_temp])
129
+ return face_data
130
+
131
+
132
+ def clamp_cut_values(startX, endX, startY, endY, image):
133
+ if startX < 0:
134
+ startX = 0
135
+ if endX > image.shape[1]:
136
+ endX = image.shape[1]
137
+ if startY < 0:
138
+ startY = 0
139
+ if endY > image.shape[0]:
140
+ endY = image.shape[0]
141
+ return startX, endX, startY, endY
142
+
143
+
144
+
145
+ def face_offset_top(face: Face, offset):
146
+ face["bbox"][1] += offset
147
+ face["bbox"][3] += offset
148
+ lm106 = face.landmark_2d_106
149
+ add = np.full_like(lm106, [0, offset])
150
+ face["landmark_2d_106"] = lm106 + add
151
+ return face
152
+
153
+
154
+ def resize_image_keep_content(image, new_width=512, new_height=512):
155
+ dim = None
156
+ (h, w) = image.shape[:2]
157
+ if h > w:
158
+ r = new_height / float(h)
159
+ dim = (int(w * r), new_height)
160
+ else:
161
+ # Calculate the ratio of the width and construct the dimensions
162
+ r = new_width / float(w)
163
+ dim = (new_width, int(h * r))
164
+ image = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
165
+ (h, w) = image.shape[:2]
166
+ if h == new_height and w == new_width:
167
+ return image
168
+ resize_img = np.zeros(shape=(new_height, new_width, 3), dtype=image.dtype)
169
+ offs = (new_width - w) if h == new_height else (new_height - h)
170
+ startoffs = int(offs // 2) if offs % 2 == 0 else int(offs // 2) + 1
171
+ offs = int(offs // 2)
172
+
173
+ if h == new_height:
174
+ resize_img[0:new_height, startoffs : new_width - offs] = image
175
+ else:
176
+ resize_img[startoffs : new_height - offs, 0:new_width] = image
177
+ return resize_img
178
+
179
+
180
+ def rotate_image_90(image, rotate=True):
181
+ if rotate:
182
+ return np.rot90(image)
183
+ else:
184
+ return np.rot90(image, 1, (1, 0))
185
+
186
+
187
+ def rotate_anticlockwise(frame):
188
+ return rotate_image_90(frame)
189
+
190
+
191
+ def rotate_clockwise(frame):
192
+ return rotate_image_90(frame, False)
193
+
194
+
195
+ def rotate_image_180(image):
196
+ return np.flip(image, 0)
197
+
198
+
199
+ # alignment code from insightface https://github.com/deepinsight/insightface/blob/master/python-package/insightface/utils/face_align.py
200
+
201
+ arcface_dst = np.array(
202
+ [
203
+ [38.2946, 51.6963],
204
+ [73.5318, 51.5014],
205
+ [56.0252, 71.7366],
206
+ [41.5493, 92.3655],
207
+ [70.7299, 92.2041],
208
+ ],
209
+ dtype=np.float32,
210
+ )
211
+
212
+
213
+ def estimate_norm(lmk, image_size=112, mode="arcface"):
214
+ assert lmk.shape == (5, 2)
215
+ assert image_size % 112 == 0 or image_size % 128 == 0
216
+ if image_size % 112 == 0:
217
+ ratio = float(image_size) / 112.0
218
+ diff_x = 0
219
+ else:
220
+ ratio = float(image_size) / 128.0
221
+ diff_x = 8.0 * ratio
222
+ dst = arcface_dst * ratio
223
+ dst[:, 0] += diff_x
224
+ tform = trans.SimilarityTransform()
225
+ tform.estimate(lmk, dst)
226
+ M = tform.params[0:2, :]
227
+ return M
228
+
229
+
230
+
231
+ # aligned, M = norm_crop2(f[1], face.kps, 512)
232
+ def align_crop(img, landmark, image_size=112, mode="arcface"):
233
+ M = estimate_norm(landmark, image_size, mode)
234
+ warped = cv2.warpAffine(img, M, (image_size, image_size), borderValue=0.0)
235
+ return warped, M
236
+
237
+
238
+ def square_crop(im, S):
239
+ if im.shape[0] > im.shape[1]:
240
+ height = S
241
+ width = int(float(im.shape[1]) / im.shape[0] * S)
242
+ scale = float(S) / im.shape[0]
243
+ else:
244
+ width = S
245
+ height = int(float(im.shape[0]) / im.shape[1] * S)
246
+ scale = float(S) / im.shape[1]
247
+ resized_im = cv2.resize(im, (width, height))
248
+ det_im = np.zeros((S, S, 3), dtype=np.uint8)
249
+ det_im[: resized_im.shape[0], : resized_im.shape[1], :] = resized_im
250
+ return det_im, scale
251
+
252
+
253
+ def transform(data, center, output_size, scale, rotation):
254
+ scale_ratio = scale
255
+ rot = float(rotation) * np.pi / 180.0
256
+ # translation = (output_size/2-center[0]*scale_ratio, output_size/2-center[1]*scale_ratio)
257
+ t1 = trans.SimilarityTransform(scale=scale_ratio)
258
+ cx = center[0] * scale_ratio
259
+ cy = center[1] * scale_ratio
260
+ t2 = trans.SimilarityTransform(translation=(-1 * cx, -1 * cy))
261
+ t3 = trans.SimilarityTransform(rotation=rot)
262
+ t4 = trans.SimilarityTransform(translation=(output_size / 2, output_size / 2))
263
+ t = t1 + t2 + t3 + t4
264
+ M = t.params[0:2]
265
+ cropped = cv2.warpAffine(data, M, (output_size, output_size), borderValue=0.0)
266
+ return cropped, M
267
+
268
+
269
+ def trans_points2d(pts, M):
270
+ new_pts = np.zeros(shape=pts.shape, dtype=np.float32)
271
+ for i in range(pts.shape[0]):
272
+ pt = pts[i]
273
+ new_pt = np.array([pt[0], pt[1], 1.0], dtype=np.float32)
274
+ new_pt = np.dot(M, new_pt)
275
+ # print('new_pt', new_pt.shape, new_pt)
276
+ new_pts[i] = new_pt[0:2]
277
+
278
+ return new_pts
279
+
280
+
281
+ def trans_points3d(pts, M):
282
+ scale = np.sqrt(M[0][0] * M[0][0] + M[0][1] * M[0][1])
283
+ # print(scale)
284
+ new_pts = np.zeros(shape=pts.shape, dtype=np.float32)
285
+ for i in range(pts.shape[0]):
286
+ pt = pts[i]
287
+ new_pt = np.array([pt[0], pt[1], 1.0], dtype=np.float32)
288
+ new_pt = np.dot(M, new_pt)
289
+ # print('new_pt', new_pt.shape, new_pt)
290
+ new_pts[i][0:2] = new_pt[0:2]
291
+ new_pts[i][2] = pts[i][2] * scale
292
+
293
+ return new_pts
294
+
295
+
296
+ def trans_points(pts, M):
297
+ if pts.shape[1] == 2:
298
+ return trans_points2d(pts, M)
299
+ else:
300
+ return trans_points3d(pts, M)
301
+
302
+ def create_blank_image(width, height):
303
+ img = np.zeros((height, width, 4), dtype=np.uint8)
304
+ img[:] = [0,0,0,0]
305
+ return img
306
+
roop/ffmpeg_writer.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FFMPEG_Writer - write set of frames to video file
3
+
4
+ original from
5
+ https://github.com/Zulko/moviepy/blob/master/moviepy/video/io/ffmpeg_writer.py
6
+
7
+ removed unnecessary dependencies
8
+
9
+ The MIT License (MIT)
10
+
11
+ Copyright (c) 2015 Zulko
12
+ Copyright (c) 2023 Janvarev Vladislav
13
+ """
14
+
15
+ import os
16
+ import subprocess as sp
17
+
18
+ PIPE = -1
19
+ STDOUT = -2
20
+ DEVNULL = -3
21
+
22
+ FFMPEG_BINARY = "ffmpeg"
23
+
24
+ class FFMPEG_VideoWriter:
25
+ """ A class for FFMPEG-based video writing.
26
+
27
+ A class to write videos using ffmpeg. ffmpeg will write in a large
28
+ choice of formats.
29
+
30
+ Parameters
31
+ -----------
32
+
33
+ filename
34
+ Any filename like 'video.mp4' etc. but if you want to avoid
35
+ complications it is recommended to use the generic extension
36
+ '.avi' for all your videos.
37
+
38
+ size
39
+ Size (width,height) of the output video in pixels.
40
+
41
+ fps
42
+ Frames per second in the output video file.
43
+
44
+ codec
45
+ FFMPEG codec. It seems that in terms of quality the hierarchy is
46
+ 'rawvideo' = 'png' > 'mpeg4' > 'libx264'
47
+ 'png' manages the same lossless quality as 'rawvideo' but yields
48
+ smaller files. Type ``ffmpeg -codecs`` in a terminal to get a list
49
+ of accepted codecs.
50
+
51
+ Note for default 'libx264': by default the pixel format yuv420p
52
+ is used. If the video dimensions are not both even (e.g. 720x405)
53
+ another pixel format is used, and this can cause problem in some
54
+ video readers.
55
+
56
+ audiofile
57
+ Optional: The name of an audio file that will be incorporated
58
+ to the video.
59
+
60
+ preset
61
+ Sets the time that FFMPEG will take to compress the video. The slower,
62
+ the better the compression rate. Possibilities are: ultrafast,superfast,
63
+ veryfast, faster, fast, medium (default), slow, slower, veryslow,
64
+ placebo.
65
+
66
+ bitrate
67
+ Only relevant for codecs which accept a bitrate. "5000k" offers
68
+ nice results in general.
69
+
70
+ """
71
+
72
+ def __init__(self, filename, size, fps, codec="libx265", crf=14, audiofile=None,
73
+ preset="medium", bitrate=None,
74
+ logfile=None, threads=None, ffmpeg_params=None):
75
+
76
+ if logfile is None:
77
+ logfile = sp.PIPE
78
+
79
+ self.filename = filename
80
+ self.codec = codec
81
+ self.ext = self.filename.split(".")[-1]
82
+ w = size[0] - 1 if size[0] % 2 != 0 else size[0]
83
+ h = size[1] - 1 if size[1] % 2 != 0 else size[1]
84
+
85
+
86
+ # order is important
87
+ cmd = [
88
+ FFMPEG_BINARY,
89
+ '-hide_banner',
90
+ '-hwaccel', 'auto',
91
+ '-y',
92
+ '-loglevel', 'error' if logfile == sp.PIPE else 'info',
93
+ '-f', 'rawvideo',
94
+ '-vcodec', 'rawvideo',
95
+ '-s', '%dx%d' % (size[0], size[1]),
96
+ #'-pix_fmt', 'rgba' if withmask else 'rgb24',
97
+ '-pix_fmt', 'bgr24',
98
+ '-r', str(fps),
99
+ '-an', '-i', '-'
100
+ ]
101
+
102
+ if audiofile is not None:
103
+ cmd.extend([
104
+ '-i', audiofile,
105
+ '-acodec', 'copy'
106
+ ])
107
+
108
+ cmd.extend([
109
+ '-vcodec', codec,
110
+ '-crf', str(crf)
111
+ #'-preset', preset,
112
+ ])
113
+ if ffmpeg_params is not None:
114
+ cmd.extend(ffmpeg_params)
115
+ if bitrate is not None:
116
+ cmd.extend([
117
+ '-b', bitrate
118
+ ])
119
+
120
+ # scale to a resolution divisible by 2 if not even
121
+ cmd.extend(['-vf', f'scale={w}:{h}' if w != size[0] or h != size[1] else 'colorspace=bt709:iall=bt601-6-625:fast=1'])
122
+
123
+ if threads is not None:
124
+ cmd.extend(["-threads", str(threads)])
125
+
126
+ cmd.extend([
127
+ '-pix_fmt', 'yuv420p',
128
+
129
+ ])
130
+ cmd.extend([
131
+ filename
132
+ ])
133
+
134
+ test = str(cmd)
135
+ print(test)
136
+
137
+ popen_params = {"stdout": DEVNULL,
138
+ "stderr": logfile,
139
+ "stdin": sp.PIPE}
140
+
141
+ # This was added so that no extra unwanted window opens on windows
142
+ # when the child process is created
143
+ if os.name == "nt":
144
+ popen_params["creationflags"] = 0x08000000 # CREATE_NO_WINDOW
145
+
146
+ self.proc = sp.Popen(cmd, **popen_params)
147
+
148
+
149
+ def write_frame(self, img_array):
150
+ """ Writes one frame in the file."""
151
+ try:
152
+ #if PY3:
153
+ self.proc.stdin.write(img_array.tobytes())
154
+ # else:
155
+ # self.proc.stdin.write(img_array.tostring())
156
+ except IOError as err:
157
+ _, ffmpeg_error = self.proc.communicate()
158
+ error = (str(err) + ("\n\nroop unleashed error: FFMPEG encountered "
159
+ "the following error while writing file %s:"
160
+ "\n\n %s" % (self.filename, str(ffmpeg_error))))
161
+
162
+ if b"Unknown encoder" in ffmpeg_error:
163
+
164
+ error = error+("\n\nThe video export "
165
+ "failed because FFMPEG didn't find the specified "
166
+ "codec for video encoding (%s). Please install "
167
+ "this codec or change the codec when calling "
168
+ "write_videofile. For instance:\n"
169
+ " >>> clip.write_videofile('myvid.webm', codec='libvpx')")%(self.codec)
170
+
171
+ elif b"incorrect codec parameters ?" in ffmpeg_error:
172
+
173
+ error = error+("\n\nThe video export "
174
+ "failed, possibly because the codec specified for "
175
+ "the video (%s) is not compatible with the given "
176
+ "extension (%s). Please specify a valid 'codec' "
177
+ "argument in write_videofile. This would be 'libx264' "
178
+ "or 'mpeg4' for mp4, 'libtheora' for ogv, 'libvpx for webm. "
179
+ "Another possible reason is that the audio codec was not "
180
+ "compatible with the video codec. For instance the video "
181
+ "extensions 'ogv' and 'webm' only allow 'libvorbis' (default) as a"
182
+ "video codec."
183
+ )%(self.codec, self.ext)
184
+
185
+ elif b"encoder setup failed" in ffmpeg_error:
186
+
187
+ error = error+("\n\nThe video export "
188
+ "failed, possibly because the bitrate you specified "
189
+ "was too high or too low for the video codec.")
190
+
191
+ elif b"Invalid encoder type" in ffmpeg_error:
192
+
193
+ error = error + ("\n\nThe video export failed because the codec "
194
+ "or file extension you provided is not a video")
195
+
196
+
197
+ raise IOError(error)
198
+
199
+ def close(self):
200
+ if self.proc:
201
+ self.proc.stdin.close()
202
+ if self.proc.stderr is not None:
203
+ self.proc.stderr.close()
204
+ self.proc.wait()
205
+
206
+ self.proc = None
207
+
208
+ # Support the Context Manager protocol, to ensure that resources are cleaned up.
209
+
210
+ def __enter__(self):
211
+ return self
212
+
213
+ def __exit__(self, exc_type, exc_value, traceback):
214
+ self.close()
215
+
216
+
217
+
218
+
roop/filters.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import cv2
3
+
4
+ c64_palette = np.array([
5
+ [0, 0, 0],
6
+ [255, 255, 255],
7
+ [0x81, 0x33, 0x38],
8
+ [0x75, 0xce, 0xc8],
9
+ [0x8e, 0x3c, 0x97],
10
+ [0x56, 0xac, 0x4d],
11
+ [0x2e, 0x2c, 0x9b],
12
+ [0xed, 0xf1, 0x71],
13
+ [0x8e, 0x50, 0x29],
14
+ [0x55, 0x38, 0x00],
15
+ [0xc4, 0x6c, 0x71],
16
+ [0x4a, 0x4a, 0x4a],
17
+ [0x7b, 0x7b, 0x7b],
18
+ [0xa9, 0xff, 0x9f],
19
+ [0x70, 0x6d, 0xeb],
20
+ [0xb2, 0xb2, 0xb2]
21
+ ])
22
+
23
+ def fast_quantize_to_palette(image):
24
+ # Simply round the color values to the nearest color in the palette
25
+ palette = c64_palette / 255.0 # Normalize palette
26
+ img_normalized = image / 255.0 # Normalize image
27
+
28
+ # Calculate the index in the palette that is closest to each pixel in the image
29
+ indices = np.sqrt(((img_normalized[:, :, None, :] - palette[None, None, :, :]) ** 2).sum(axis=3)).argmin(axis=2)
30
+ # Map the image to the palette colors
31
+ mapped_image = palette[indices]
32
+
33
+ return (mapped_image * 255).astype(np.uint8) # Denormalize and return the image
34
+
35
+
36
+ '''
37
+ knn = None
38
+
39
+ def quantize_to_palette(image, palette):
40
+ global knn
41
+
42
+ NumColors = 16
43
+ quantized_image = None
44
+ cv2.pyrMeanShiftFiltering(image, NumColors / 4, NumColors / 2, quantized_image, 1, cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_MAX_ITER, 5, 1)
45
+
46
+ palette = c64_palette
47
+ X_query = image.reshape(-1, 3).astype(np.float32)
48
+
49
+ if(knn == None):
50
+ X_index = palette.astype(np.float32)
51
+ knn = cv2.ml.KNearest_create()
52
+ knn.train(X_index, cv2.ml.ROW_SAMPLE, np.arange(len(palette)))
53
+
54
+ ret, results, neighbours, dist = knn.findNearest(X_query, 1)
55
+
56
+ quantized_image = np.array([palette[idx] for idx in neighbours.astype(int)])
57
+ quantized_image = quantized_image.reshape(image.shape)
58
+ return quantized_image.astype(np.uint8)
59
+ '''
roop/globals.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from settings import Settings
2
+ from typing import List
3
+
4
+ source_path = None
5
+ target_path = None
6
+ output_path = None
7
+ target_folder_path = None
8
+
9
+ frame_processors: List[str] = []
10
+ keep_fps = None
11
+ keep_frames = None
12
+ autorotate_faces = None
13
+ vr_mode = None
14
+ skip_audio = None
15
+ wait_after_extraction = None
16
+ many_faces = None
17
+ use_batch = None
18
+ source_face_index = 0
19
+ target_face_index = 0
20
+ face_position = None
21
+ video_encoder = None
22
+ video_quality = None
23
+ max_memory = None
24
+ execution_providers: List[str] = []
25
+ execution_threads = None
26
+ headless = None
27
+ log_level = 'error'
28
+ selected_enhancer = None
29
+ face_swap_mode = None
30
+ blend_ratio = 0.5
31
+ distance_threshold = 0.65
32
+ default_det_size = True
33
+
34
+ no_face_action = 0
35
+
36
+ processing = False
37
+
38
+ g_current_face_analysis = None
39
+ g_desired_face_analysis = None
40
+
41
+ FACE_ENHANCER = None
42
+
43
+ INPUT_FACESETS = []
44
+ TARGET_FACES = []
45
+
46
+
47
+ IMAGE_CHAIN_PROCESSOR = None
48
+ VIDEO_CHAIN_PROCESSOR = None
49
+ BATCH_IMAGE_CHAIN_PROCESSOR = None
50
+
51
+ CFG: Settings = None
52
+
53
+
roop/metadata.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ name = 'roop unleashed'
2
+ version = '3.9.0'
roop/template_parser.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from datetime import datetime
3
+
4
+ template_functions = {
5
+ "timestamp": lambda data: str(int(datetime.now().timestamp())),
6
+ "i": lambda data: data.get("index", False),
7
+ "file": lambda data: data.get("file", False),
8
+ "date": lambda data: datetime.now().strftime("%Y-%m-%d"),
9
+ "time": lambda data: datetime.now().strftime("%H-%M-%S"),
10
+ }
11
+
12
+
13
+ def parse(text: str, data: dict):
14
+ pattern = r"\{([^}]+)\}"
15
+
16
+ matches = re.findall(pattern, text)
17
+
18
+ for match in matches:
19
+ replacement = template_functions[match](data)
20
+ if replacement is not False:
21
+ text = text.replace(f"{{{match}}}", replacement)
22
+
23
+ return text
roop/typing.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ from insightface.app.common import Face
4
+ from roop.FaceSet import FaceSet
5
+ import numpy
6
+
7
+ Face = Face
8
+ FaceSet = FaceSet
9
+ Frame = numpy.ndarray[Any, Any]
roop/util_ffmpeg.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import subprocess
4
+ import roop.globals
5
+ import roop.utilities as util
6
+
7
+ from typing import List, Any
8
+
9
+ def run_ffmpeg(args: List[str]) -> bool:
10
+ commands = ['ffmpeg', '-hide_banner', '-hwaccel', 'auto', '-y', '-loglevel', roop.globals.log_level]
11
+ commands.extend(args)
12
+ print ("Running ffmpeg")
13
+ try:
14
+ subprocess.check_output(commands, stderr=subprocess.STDOUT)
15
+ return True
16
+ except Exception as e:
17
+ print("Running ffmpeg failed! Commandline:")
18
+ print (" ".join(commands))
19
+ return False
20
+
21
+
22
+
23
+ def cut_video(original_video: str, cut_video: str, start_frame: int, end_frame: int, reencode: bool):
24
+ fps = util.detect_fps(original_video)
25
+ start_time = start_frame / fps
26
+ num_frames = end_frame - start_frame
27
+
28
+ if reencode:
29
+ run_ffmpeg(['-ss', format(start_time, ".2f"), '-i', original_video, '-c:v', roop.globals.video_encoder, '-c:a', 'aac', '-frames:v', str(num_frames), cut_video])
30
+ else:
31
+ run_ffmpeg(['-ss', format(start_time, ".2f"), '-i', original_video, '-frames:v', str(num_frames), '-c:v' ,'copy','-c:a' ,'copy', cut_video])
32
+
33
+ def join_videos(videos: List[str], dest_filename: str, simple: bool):
34
+ if simple:
35
+ txtfilename = util.resolve_relative_path('../temp')
36
+ txtfilename = os.path.join(txtfilename, 'joinvids.txt')
37
+ with open(txtfilename, "w", encoding="utf-8") as f:
38
+ for v in videos:
39
+ v = v.replace('\\', '/')
40
+ f.write(f"file {v}\n")
41
+ commands = ['-f', 'concat', '-safe', '0', '-i', f'{txtfilename}', '-vcodec', 'copy', f'{dest_filename}']
42
+ run_ffmpeg(commands)
43
+
44
+ else:
45
+ inputs = []
46
+ filter = ''
47
+ for i,v in enumerate(videos):
48
+ inputs.append('-i')
49
+ inputs.append(v)
50
+ filter += f'[{i}:v:0][{i}:a:0]'
51
+ run_ffmpeg([" ".join(inputs), '-filter_complex', f'"{filter}concat=n={len(videos)}:v=1:a=1[outv][outa]"', '-map', '"[outv]"', '-map', '"[outa]"', dest_filename])
52
+
53
+ # filter += f'[{i}:v:0][{i}:a:0]'
54
+ # run_ffmpeg([" ".join(inputs), '-filter_complex', f'"{filter}concat=n={len(videos)}:v=1:a=1[outv][outa]"', '-map', '"[outv]"', '-map', '"[outa]"', dest_filename])
55
+
56
+
57
+
58
+ def extract_frames(target_path : str, trim_frame_start, trim_frame_end, fps : float) -> bool:
59
+ util.create_temp(target_path)
60
+ temp_directory_path = util.get_temp_directory_path(target_path)
61
+ commands = ['-i', target_path, '-q:v', '1', '-pix_fmt', 'rgb24', ]
62
+ if trim_frame_start is not None and trim_frame_end is not None:
63
+ commands.extend([ '-vf', 'trim=start_frame=' + str(trim_frame_start) + ':end_frame=' + str(trim_frame_end) + ',fps=' + str(fps) ])
64
+ commands.extend(['-vsync', '0', os.path.join(temp_directory_path, '%06d.' + roop.globals.CFG.output_image_format)])
65
+ return run_ffmpeg(commands)
66
+
67
+
68
+ def create_video(target_path: str, dest_filename: str, fps: float = 24.0, temp_directory_path: str = None) -> None:
69
+ if temp_directory_path is None:
70
+ temp_directory_path = util.get_temp_directory_path(target_path)
71
+ run_ffmpeg(['-r', str(fps), '-i', os.path.join(temp_directory_path, f'%06d.{roop.globals.CFG.output_image_format}'), '-c:v', roop.globals.video_encoder, '-crf', str(roop.globals.video_quality), '-pix_fmt', 'yuv420p', '-vf', 'colorspace=bt709:iall=bt601-6-625:fast=1', '-y', dest_filename])
72
+ return dest_filename
73
+
74
+
75
+ def create_gif_from_video(video_path: str, gif_path):
76
+ from roop.capturer import get_video_frame
77
+
78
+ fps = util.detect_fps(video_path)
79
+ frame = get_video_frame(video_path)
80
+
81
+ run_ffmpeg(['-i', video_path, '-vf', f'fps={fps},scale={frame.shape[0]}:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse', '-loop', '0', gif_path])
82
+
83
+
84
+ def restore_audio(intermediate_video: str, original_video: str, trim_frame_start, trim_frame_end, final_video : str) -> None:
85
+ fps = util.detect_fps(original_video)
86
+ commands = [ '-i', intermediate_video ]
87
+ if trim_frame_start is None and trim_frame_end is None:
88
+ commands.extend([ '-c:a', 'copy' ])
89
+ else:
90
+ # if trim_frame_start is not None:
91
+ # start_time = trim_frame_start / fps
92
+ # commands.extend([ '-ss', format(start_time, ".2f")])
93
+ # else:
94
+ # commands.extend([ '-ss', '0' ])
95
+ # if trim_frame_end is not None:
96
+ # end_time = trim_frame_end / fps
97
+ # commands.extend([ '-to', format(end_time, ".2f")])
98
+ # commands.extend([ '-c:a', 'aac' ])
99
+ if trim_frame_start is not None:
100
+ start_time = trim_frame_start / fps
101
+ commands.extend([ '-ss', format(start_time, ".2f")])
102
+ else:
103
+ commands.extend([ '-ss', '0' ])
104
+ if trim_frame_end is not None:
105
+ end_time = trim_frame_end / fps
106
+ commands.extend([ '-to', format(end_time, ".2f")])
107
+ commands.extend([ '-i', original_video, "-c", "copy" ])
108
+
109
+ commands.extend([ '-map', '0:v:0', '-map', '1:a:0?', '-shortest', final_video ])
110
+ run_ffmpeg(commands)
roop/utilities.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import mimetypes
3
+ import os
4
+ import platform
5
+ import shutil
6
+ import ssl
7
+ import subprocess
8
+ import sys
9
+ import urllib
10
+ import torch
11
+ import gradio
12
+ import tempfile
13
+ import cv2
14
+ import zipfile
15
+ import traceback
16
+
17
+ from pathlib import Path
18
+ from typing import List, Any
19
+ from tqdm import tqdm
20
+ from scipy.spatial import distance
21
+
22
+ import roop.template_parser as template_parser
23
+
24
+ import roop.globals
25
+
26
+ TEMP_FILE = "temp.mp4"
27
+ TEMP_DIRECTORY = "temp"
28
+
29
+ # monkey patch ssl for mac
30
+ if platform.system().lower() == "darwin":
31
+ ssl._create_default_https_context = ssl._create_unverified_context
32
+
33
+
34
+ # https://github.com/facefusion/facefusion/blob/master/facefusion
35
+ def detect_fps(target_path: str) -> float:
36
+ fps = 24.0
37
+ cap = cv2.VideoCapture(target_path)
38
+ if cap.isOpened():
39
+ fps = cap.get(cv2.CAP_PROP_FPS)
40
+ cap.release()
41
+ return fps
42
+
43
+
44
+ # Gradio wants Images in RGB
45
+ def convert_to_gradio(image):
46
+ if image is None:
47
+ return None
48
+ return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
49
+
50
+
51
+ def sort_filenames_ignore_path(filenames):
52
+ """Sorts a list of filenames containing a complete path by their filename,
53
+ while retaining their original path.
54
+
55
+ Args:
56
+ filenames: A list of filenames containing a complete path.
57
+
58
+ Returns:
59
+ A sorted list of filenames containing a complete path.
60
+ """
61
+ filename_path_tuples = [
62
+ (os.path.split(filename)[1], filename) for filename in filenames
63
+ ]
64
+ sorted_filename_path_tuples = sorted(filename_path_tuples, key=lambda x: x[0])
65
+ return [
66
+ filename_path_tuple[1] for filename_path_tuple in sorted_filename_path_tuples
67
+ ]
68
+
69
+
70
+ def sort_rename_frames(path: str):
71
+ filenames = os.listdir(path)
72
+ filenames.sort()
73
+ for i in range(len(filenames)):
74
+ of = os.path.join(path, filenames[i])
75
+ newidx = i + 1
76
+ new_filename = os.path.join(
77
+ path, f"{newidx:06d}." + roop.globals.CFG.output_image_format
78
+ )
79
+ os.rename(of, new_filename)
80
+
81
+
82
+ def get_temp_frame_paths(target_path: str) -> List[str]:
83
+ temp_directory_path = get_temp_directory_path(target_path)
84
+ return glob.glob(
85
+ (
86
+ os.path.join(
87
+ glob.escape(temp_directory_path),
88
+ f"*.{roop.globals.CFG.output_image_format}",
89
+ )
90
+ )
91
+ )
92
+
93
+
94
+ def get_temp_directory_path(target_path: str) -> str:
95
+ target_name, _ = os.path.splitext(os.path.basename(target_path))
96
+ target_directory_path = os.path.dirname(target_path)
97
+ return os.path.join(target_directory_path, TEMP_DIRECTORY, target_name)
98
+
99
+
100
+ def get_temp_output_path(target_path: str) -> str:
101
+ temp_directory_path = get_temp_directory_path(target_path)
102
+ return os.path.join(temp_directory_path, TEMP_FILE)
103
+
104
+
105
+ def normalize_output_path(source_path: str, target_path: str, output_path: str) -> Any:
106
+ if source_path and target_path:
107
+ source_name, _ = os.path.splitext(os.path.basename(source_path))
108
+ target_name, target_extension = os.path.splitext(os.path.basename(target_path))
109
+ if os.path.isdir(output_path):
110
+ return os.path.join(
111
+ output_path, source_name + "-" + target_name + target_extension
112
+ )
113
+ return output_path
114
+
115
+
116
+ def get_destfilename_from_path(
117
+ srcfilepath: str, destfilepath: str, extension: str
118
+ ) -> str:
119
+ fn, ext = os.path.splitext(os.path.basename(srcfilepath))
120
+ if "." in extension:
121
+ return os.path.join(destfilepath, f"{fn}{extension}")
122
+ return os.path.join(destfilepath, f"{fn}{extension}{ext}")
123
+
124
+
125
+ def replace_template(file_path: str, index: int = 0) -> str:
126
+ fn, ext = os.path.splitext(os.path.basename(file_path))
127
+
128
+ # Remove the "__temp" placeholder that was used as a temporary filename
129
+ fn = fn.replace("__temp", "")
130
+
131
+ template = roop.globals.CFG.output_template
132
+ replaced_filename = template_parser.parse(
133
+ template, {"index": str(index), "file": fn}
134
+ )
135
+
136
+ return os.path.join(roop.globals.output_path, f"{replaced_filename}{ext}")
137
+
138
+
139
+ def create_temp(target_path: str) -> None:
140
+ temp_directory_path = get_temp_directory_path(target_path)
141
+ Path(temp_directory_path).mkdir(parents=True, exist_ok=True)
142
+
143
+
144
+ def move_temp(target_path: str, output_path: str) -> None:
145
+ temp_output_path = get_temp_output_path(target_path)
146
+ if os.path.isfile(temp_output_path):
147
+ if os.path.isfile(output_path):
148
+ os.remove(output_path)
149
+ shutil.move(temp_output_path, output_path)
150
+
151
+
152
+ def clean_temp(target_path: str) -> None:
153
+ temp_directory_path = get_temp_directory_path(target_path)
154
+ parent_directory_path = os.path.dirname(temp_directory_path)
155
+ if not roop.globals.keep_frames and os.path.isdir(temp_directory_path):
156
+ shutil.rmtree(temp_directory_path)
157
+ if os.path.exists(parent_directory_path) and not os.listdir(parent_directory_path):
158
+ os.rmdir(parent_directory_path)
159
+
160
+
161
+ def delete_temp_frames(filename: str) -> None:
162
+ dir = os.path.dirname(os.path.dirname(filename))
163
+ shutil.rmtree(dir)
164
+
165
+
166
+ def has_image_extension(image_path: str) -> bool:
167
+ return image_path.lower().endswith(("png", "jpg", "jpeg", "webp"))
168
+
169
+
170
+ def has_extension(filepath: str, extensions: List[str]) -> bool:
171
+ return filepath.lower().endswith(tuple(extensions))
172
+
173
+
174
+ def is_image(image_path: str) -> bool:
175
+ if image_path and os.path.isfile(image_path):
176
+ mimetype, _ = mimetypes.guess_type(image_path)
177
+ return bool(mimetype and mimetype.startswith("image/"))
178
+ return False
179
+
180
+
181
+ def is_video(video_path: str) -> bool:
182
+ if video_path and os.path.isfile(video_path):
183
+ mimetype, _ = mimetypes.guess_type(video_path)
184
+ return bool(mimetype and mimetype.startswith("video/"))
185
+ return False
186
+
187
+
188
+ def conditional_download(download_directory_path: str, urls: List[str]) -> None:
189
+ if not os.path.exists(download_directory_path):
190
+ os.makedirs(download_directory_path)
191
+ for url in urls:
192
+ download_file_path = os.path.join(
193
+ download_directory_path, os.path.basename(url)
194
+ )
195
+ if not os.path.exists(download_file_path):
196
+ request = urllib.request.urlopen(url) # type: ignore[attr-defined]
197
+ total = int(request.headers.get("Content-Length", 0))
198
+ with tqdm(
199
+ total=total,
200
+ desc=f"Downloading {url}",
201
+ unit="B",
202
+ unit_scale=True,
203
+ unit_divisor=1024,
204
+ ) as progress:
205
+ urllib.request.urlretrieve(url, download_file_path, reporthook=lambda count, block_size, total_size: progress.update(block_size)) # type: ignore[attr-defined]
206
+
207
+
208
+ def get_local_files_from_folder(folder: str) -> List[str]:
209
+ if not os.path.exists(folder) or not os.path.isdir(folder):
210
+ return None
211
+ files = [
212
+ os.path.join(folder, f)
213
+ for f in os.listdir(folder)
214
+ if os.path.isfile(os.path.join(folder, f))
215
+ ]
216
+ return files
217
+
218
+
219
+ def resolve_relative_path(path: str) -> str:
220
+ return os.path.abspath(os.path.join(os.path.dirname(__file__), path))
221
+
222
+
223
+ def get_device() -> str:
224
+ if len(roop.globals.execution_providers) < 1:
225
+ roop.globals.execution_providers = ["CPUExecutionProvider"]
226
+
227
+ prov = roop.globals.execution_providers[0]
228
+ if "CoreMLExecutionProvider" in prov:
229
+ return "mps"
230
+ if "CUDAExecutionProvider" in prov or "ROCMExecutionProvider" in prov:
231
+ return "cuda"
232
+ if "OpenVINOExecutionProvider" in prov:
233
+ return "mkl"
234
+ return "cpu"
235
+
236
+
237
+ def str_to_class(module_name, class_name) -> Any:
238
+ from importlib import import_module
239
+
240
+ class_ = None
241
+ try:
242
+ module_ = import_module(module_name)
243
+ try:
244
+ class_ = getattr(module_, class_name)()
245
+ except AttributeError:
246
+ print(f"Class {class_name} does not exist")
247
+ except ImportError:
248
+ print(f"Module {module_name} does not exist")
249
+ return class_
250
+
251
+ def is_installed(name:str) -> bool:
252
+ return shutil.which(name);
253
+
254
+ # Taken from https://stackoverflow.com/a/68842705
255
+ def get_platform() -> str:
256
+ if sys.platform == "linux":
257
+ try:
258
+ proc_version = open("/proc/version").read()
259
+ if "Microsoft" in proc_version:
260
+ return "wsl"
261
+ except:
262
+ pass
263
+ return sys.platform
264
+
265
+ def open_with_default_app(filename:str):
266
+ if filename == None:
267
+ return
268
+ platform = get_platform()
269
+ if platform == "darwin":
270
+ subprocess.call(("open", filename))
271
+ elif platform in ["win64", "win32"]: os.startfile(filename.replace("/", "\\"))
272
+ elif platform == "wsl":
273
+ subprocess.call("cmd.exe /C start".split() + [filename])
274
+ else: # linux variants
275
+ subprocess.call("xdg-open", filename)
276
+
277
+
278
+ def prepare_for_batch(target_files) -> str:
279
+ print("Preparing temp files")
280
+ tempfolder = os.path.join(tempfile.gettempdir(), "rooptmp")
281
+ if os.path.exists(tempfolder):
282
+ shutil.rmtree(tempfolder)
283
+ Path(tempfolder).mkdir(parents=True, exist_ok=True)
284
+ for f in target_files:
285
+ newname = os.path.basename(f.name)
286
+ shutil.move(f.name, os.path.join(tempfolder, newname))
287
+ return tempfolder
288
+
289
+
290
+ def zip(files, zipname):
291
+ with zipfile.ZipFile(zipname, "w") as zip_file:
292
+ for f in files:
293
+ zip_file.write(f, os.path.basename(f))
294
+
295
+
296
+ def unzip(zipfilename: str, target_path: str):
297
+ with zipfile.ZipFile(zipfilename, "r") as zip_file:
298
+ zip_file.extractall(target_path)
299
+
300
+
301
+ def mkdir_with_umask(directory):
302
+ oldmask = os.umask(0)
303
+ # mode needs octal
304
+ os.makedirs(directory, mode=0o775, exist_ok=True)
305
+ os.umask(oldmask)
306
+
307
+
308
+ def open_folder(path: str):
309
+ platform = get_platform()
310
+ try:
311
+ if platform == "darwin":
312
+ subprocess.call(("open", path))
313
+ elif platform in ["win64", "win32"]:
314
+ open_with_default_app(path)
315
+ elif platform == "wsl":
316
+ subprocess.call("cmd.exe /C start".split() + [path])
317
+ else: # linux variants
318
+ subprocess.Popen(["xdg-open", path])
319
+ except Exception as e:
320
+ traceback.print_exc()
321
+ pass
322
+ # import webbrowser
323
+ # webbrowser.open(url)
324
+
325
+
326
+ def create_version_html() -> str:
327
+ python_version = ".".join([str(x) for x in sys.version_info[0:3]])
328
+ versions_html = f"""
329
+ python: <span title="{sys.version}">{python_version}</span>
330
+
331
+ torch: {getattr(torch, '__long_version__',torch.__version__)}
332
+
333
+ gradio: {gradio.__version__}
334
+ """
335
+ return versions_html
336
+
337
+
338
+ def compute_cosine_distance(emb1, emb2) -> float:
339
+ return distance.cosine(emb1, emb2)
roop/virtualcam.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import roop.globals
3
+ import ui.globals
4
+ import pyvirtualcam
5
+ import threading
6
+ import time
7
+
8
+
9
+ cam_active = False
10
+ cam_thread = None
11
+ vcam = None
12
+
13
+ def virtualcamera(streamobs, cam_num,width,height):
14
+ from roop.ProcessOptions import ProcessOptions
15
+ from roop.core import live_swap, get_processing_plugins
16
+ from roop.filters import fast_quantize_to_palette
17
+
18
+ global cam_active
19
+
20
+ #time.sleep(2)
21
+ print('Starting capture')
22
+ cap = cv2.VideoCapture(cam_num, cv2.CAP_DSHOW)
23
+ if not cap.isOpened():
24
+ print("Cannot open camera")
25
+ cap.release()
26
+ del cap
27
+ return
28
+
29
+ pref_width = width
30
+ pref_height = height
31
+ pref_fps_in = 30
32
+ cap.set(cv2.CAP_PROP_FRAME_WIDTH, pref_width)
33
+ cap.set(cv2.CAP_PROP_FRAME_HEIGHT, pref_height)
34
+ cap.set(cv2.CAP_PROP_FPS, pref_fps_in)
35
+ cam_active = True
36
+
37
+ # native format UYVY
38
+
39
+ cam = None
40
+ if streamobs:
41
+ print('Detecting virtual cam devices')
42
+ cam = pyvirtualcam.Camera(width=pref_width, height=pref_height, fps=pref_fps_in, fmt=pyvirtualcam.PixelFormat.BGR, print_fps=False)
43
+ if cam:
44
+ print(f'Using virtual camera: {cam.device}')
45
+ print(f'Using {cam.native_fmt}')
46
+ else:
47
+ print(f'Not streaming to virtual camera!')
48
+
49
+ while cam_active:
50
+ ret, frame = cap.read()
51
+ if not ret:
52
+ break
53
+
54
+ if len(roop.globals.INPUT_FACESETS) > 0:
55
+ options = ProcessOptions(get_processing_plugins(None), roop.globals.distance_threshold, roop.globals.blend_ratio,
56
+ "all", 0, None, None, 1, False)
57
+ frame = live_swap(frame, options)
58
+ #frame = fast_quantize_to_palette(frame)
59
+ if cam:
60
+ cam.send(frame)
61
+ cam.sleep_until_next_frame()
62
+ ui.globals.ui_camera_frame = frame
63
+
64
+ if cam:
65
+ cam.close()
66
+ cap.release()
67
+ print('Camera stopped')
68
+
69
+
70
+
71
+ def start_virtual_cam(streamobs, cam_number, resolution):
72
+ global cam_thread, cam_active
73
+
74
+ if not cam_active:
75
+ width, height = map(int, resolution.split('x'))
76
+ cam_thread = threading.Thread(target=virtualcamera, args=[streamobs, cam_number, width, height])
77
+ cam_thread.start()
78
+
79
+
80
+
81
+ def stop_virtual_cam():
82
+ global cam_active, cam_thread
83
+
84
+ if cam_active:
85
+ cam_active = False
86
+ cam_thread.join()
87
+
88
+
roop/vr_util.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+
4
+ # VR Lense Distortion
5
+ # Taken from https://github.com/g0kuvonlange/vrswap
6
+
7
+
8
+ def get_perspective(img, FOV, THETA, PHI, height, width):
9
+ #
10
+ # THETA is left/right angle, PHI is up/down angle, both in degree
11
+ #
12
+ [orig_width, orig_height, _] = img.shape
13
+ equ_h = orig_height
14
+ equ_w = orig_width
15
+ equ_cx = (equ_w - 1) / 2.0
16
+ equ_cy = (equ_h - 1) / 2.0
17
+
18
+ wFOV = FOV
19
+ hFOV = float(height) / width * wFOV
20
+
21
+ w_len = np.tan(np.radians(wFOV / 2.0))
22
+ h_len = np.tan(np.radians(hFOV / 2.0))
23
+
24
+ x_map = np.ones([height, width], np.float32)
25
+ y_map = np.tile(np.linspace(-w_len, w_len, width), [height, 1])
26
+ z_map = -np.tile(np.linspace(-h_len, h_len, height), [width, 1]).T
27
+
28
+ D = np.sqrt(x_map**2 + y_map**2 + z_map**2)
29
+ xyz = np.stack((x_map, y_map, z_map), axis=2) / np.repeat(
30
+ D[:, :, np.newaxis], 3, axis=2
31
+ )
32
+
33
+ y_axis = np.array([0.0, 1.0, 0.0], np.float32)
34
+ z_axis = np.array([0.0, 0.0, 1.0], np.float32)
35
+ [R1, _] = cv2.Rodrigues(z_axis * np.radians(THETA))
36
+ [R2, _] = cv2.Rodrigues(np.dot(R1, y_axis) * np.radians(-PHI))
37
+
38
+ xyz = xyz.reshape([height * width, 3]).T
39
+ xyz = np.dot(R1, xyz)
40
+ xyz = np.dot(R2, xyz).T
41
+ lat = np.arcsin(xyz[:, 2])
42
+ lon = np.arctan2(xyz[:, 1], xyz[:, 0])
43
+
44
+ lon = lon.reshape([height, width]) / np.pi * 180
45
+ lat = -lat.reshape([height, width]) / np.pi * 180
46
+
47
+ lon = lon / 180 * equ_cx + equ_cx
48
+ lat = lat / 90 * equ_cy + equ_cy
49
+
50
+ persp = cv2.remap(
51
+ img,
52
+ lon.astype(np.float32),
53
+ lat.astype(np.float32),
54
+ cv2.INTER_CUBIC,
55
+ borderMode=cv2.BORDER_WRAP,
56
+ )
57
+ return persp