Spaces:
Paused
Paused
Upload 45 files
Browse files- roop/FaceSet.py +20 -0
- roop/ProcessEntry.py +7 -0
- roop/ProcessMgr.py +911 -0
- roop/ProcessOptions.py +21 -0
- roop/StreamWriter.py +60 -0
- roop/__init__.py +0 -0
- roop/__pycache__/FaceSet.cpython-310.pyc +0 -0
- roop/__pycache__/ProcessEntry.cpython-310.pyc +0 -0
- roop/__pycache__/ProcessMgr.cpython-310.pyc +0 -0
- roop/__pycache__/ProcessOptions.cpython-310.pyc +0 -0
- roop/__pycache__/StreamWriter.cpython-310.pyc +0 -0
- roop/__pycache__/__init__.cpython-310.pyc +0 -0
- roop/__pycache__/capturer.cpython-310.pyc +0 -0
- roop/__pycache__/core.cpython-310.pyc +0 -0
- roop/__pycache__/face_util.cpython-310.pyc +0 -0
- roop/__pycache__/ffmpeg_writer.cpython-310.pyc +0 -0
- roop/__pycache__/globals.cpython-310.pyc +0 -0
- roop/__pycache__/metadata.cpython-310.pyc +0 -0
- roop/__pycache__/template_parser.cpython-310.pyc +0 -0
- roop/__pycache__/typing.cpython-310.pyc +0 -0
- roop/__pycache__/util_ffmpeg.cpython-310.pyc +0 -0
- roop/__pycache__/utilities.cpython-310.pyc +0 -0
- roop/__pycache__/virtualcam.cpython-310.pyc +0 -0
- roop/__pycache__/vr_util.cpython-310.pyc +0 -0
- roop/capturer.py +46 -0
- roop/core.py +406 -0
- roop/face_util.py +338 -0
- roop/ffmpeg_writer.py +218 -0
- roop/globals.py +56 -0
- roop/metadata.py +2 -0
- roop/processors/__pycache__/Enhance_CodeFormer.cpython-310.pyc +0 -0
- roop/processors/__pycache__/Enhance_GFPGAN.cpython-310.pyc +0 -0
- roop/processors/__pycache__/Enhance_GPEN.cpython-310.pyc +0 -0
- roop/processors/__pycache__/Enhance_RestoreFormerPPlus.cpython-310.pyc +0 -0
- roop/processors/__pycache__/FaceSwapInsightFace.cpython-310.pyc +0 -0
- roop/processors/__pycache__/Frame_Masking.cpython-310.pyc +0 -0
- roop/processors/__pycache__/Mask_Clip2Seg.cpython-310.pyc +0 -0
- roop/processors/__pycache__/Mask_XSeg.cpython-310.pyc +0 -0
- roop/processors/__pycache__/__init__.cpython-310.pyc +0 -0
- roop/template_parser.py +23 -0
- roop/typing.py +9 -0
- roop/util_ffmpeg.py +130 -0
- roop/utilities.py +393 -0
- roop/virtualcam.py +88 -0
- roop/vr_util.py +57 -0
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,911 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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_anticlockwise, rotate_clockwise, clamp_cut_values
|
9 |
+
from roop.utilities import compute_cosine_distance, get_device, str_to_class, shuffle_array
|
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 |
+
from roop.StreamWriter import StreamWriter
|
20 |
+
import roop.globals
|
21 |
+
|
22 |
+
|
23 |
+
|
24 |
+
# Poor man's enum to be able to compare to int
|
25 |
+
class eNoFaceAction():
|
26 |
+
USE_ORIGINAL_FRAME = 0
|
27 |
+
RETRY_ROTATED = 1
|
28 |
+
SKIP_FRAME = 2
|
29 |
+
SKIP_FRAME_IF_DISSIMILAR = 3,
|
30 |
+
USE_LAST_SWAPPED = 4
|
31 |
+
|
32 |
+
|
33 |
+
|
34 |
+
def create_queue(temp_frame_paths: List[str]) -> Queue[str]:
|
35 |
+
queue: Queue[str] = Queue()
|
36 |
+
for frame_path in temp_frame_paths:
|
37 |
+
queue.put(frame_path)
|
38 |
+
return queue
|
39 |
+
|
40 |
+
|
41 |
+
def pick_queue(queue: Queue[str], queue_per_future: int) -> List[str]:
|
42 |
+
queues = []
|
43 |
+
for _ in range(queue_per_future):
|
44 |
+
if not queue.empty():
|
45 |
+
queues.append(queue.get())
|
46 |
+
return queues
|
47 |
+
|
48 |
+
|
49 |
+
|
50 |
+
class ProcessMgr():
|
51 |
+
input_face_datas = []
|
52 |
+
target_face_datas = []
|
53 |
+
|
54 |
+
imagemask = None
|
55 |
+
|
56 |
+
processors = []
|
57 |
+
options : ProcessOptions = None
|
58 |
+
|
59 |
+
num_threads = 1
|
60 |
+
current_index = 0
|
61 |
+
processing_threads = 1
|
62 |
+
buffer_wait_time = 0.1
|
63 |
+
|
64 |
+
lock = Lock()
|
65 |
+
|
66 |
+
frames_queue = None
|
67 |
+
processed_queue = None
|
68 |
+
|
69 |
+
videowriter= None
|
70 |
+
streamwriter = None
|
71 |
+
|
72 |
+
progress_gradio = None
|
73 |
+
total_frames = 0
|
74 |
+
|
75 |
+
num_frames_no_face = 0
|
76 |
+
last_swapped_frame = None
|
77 |
+
|
78 |
+
output_to_file = None
|
79 |
+
output_to_cam = None
|
80 |
+
|
81 |
+
|
82 |
+
plugins = {
|
83 |
+
'faceswap' : 'FaceSwapInsightFace',
|
84 |
+
'mask_clip2seg' : 'Mask_Clip2Seg',
|
85 |
+
'mask_xseg' : 'Mask_XSeg',
|
86 |
+
'codeformer' : 'Enhance_CodeFormer',
|
87 |
+
'gfpgan' : 'Enhance_GFPGAN',
|
88 |
+
'dmdnet' : 'Enhance_DMDNet',
|
89 |
+
'gpen' : 'Enhance_GPEN',
|
90 |
+
'restoreformer++' : 'Enhance_RestoreFormerPPlus',
|
91 |
+
'colorizer' : 'Frame_Colorizer',
|
92 |
+
'filter_generic' : 'Frame_Filter',
|
93 |
+
'removebg' : 'Frame_Masking',
|
94 |
+
'upscale' : 'Frame_Upscale'
|
95 |
+
}
|
96 |
+
|
97 |
+
def __init__(self, progress):
|
98 |
+
if progress is not None:
|
99 |
+
self.progress_gradio = progress
|
100 |
+
|
101 |
+
def reuseOldProcessor(self, name:str):
|
102 |
+
for p in self.processors:
|
103 |
+
if p.processorname == name:
|
104 |
+
return p
|
105 |
+
|
106 |
+
return None
|
107 |
+
|
108 |
+
|
109 |
+
def initialize(self, input_faces, target_faces, options):
|
110 |
+
self.input_face_datas = input_faces
|
111 |
+
self.target_face_datas = target_faces
|
112 |
+
self.num_frames_no_face = 0
|
113 |
+
self.last_swapped_frame = None
|
114 |
+
self.options = options
|
115 |
+
devicename = get_device()
|
116 |
+
|
117 |
+
roop.globals.g_desired_face_analysis=["landmark_3d_68", "landmark_2d_106","detection","recognition"]
|
118 |
+
if options.swap_mode == "all_female" or options.swap_mode == "all_male":
|
119 |
+
roop.globals.g_desired_face_analysis.append("genderage")
|
120 |
+
elif options.swap_mode == "all_random":
|
121 |
+
# don't modify original list
|
122 |
+
self.input_face_datas = input_faces.copy()
|
123 |
+
shuffle_array(self.input_face_datas)
|
124 |
+
|
125 |
+
|
126 |
+
for p in self.processors:
|
127 |
+
newp = next((x for x in options.processors.keys() if x == p.processorname), None)
|
128 |
+
if newp is None:
|
129 |
+
p.Release()
|
130 |
+
del p
|
131 |
+
|
132 |
+
newprocessors = []
|
133 |
+
for key, extoption in options.processors.items():
|
134 |
+
p = self.reuseOldProcessor(key)
|
135 |
+
if p is None:
|
136 |
+
classname = self.plugins[key]
|
137 |
+
module = 'roop.processors.' + classname
|
138 |
+
p = str_to_class(module, classname)
|
139 |
+
if p is not None:
|
140 |
+
extoption.update({"devicename": devicename})
|
141 |
+
if p.type == "swap":
|
142 |
+
if self.options.swap_modelname == "InSwapper 128":
|
143 |
+
extoption.update({"modelname": "inswapper_128.onnx"})
|
144 |
+
elif self.options.swap_modelname == "ReSwapper 128":
|
145 |
+
extoption.update({"modelname": "reswapper_128.onnx"})
|
146 |
+
elif self.options.swap_modelname == "ReSwapper 256":
|
147 |
+
extoption.update({"modelname": "reswapper_256.onnx"})
|
148 |
+
|
149 |
+
p.Initialize(extoption)
|
150 |
+
newprocessors.append(p)
|
151 |
+
else:
|
152 |
+
print(f"Not using {module}")
|
153 |
+
self.processors = newprocessors
|
154 |
+
|
155 |
+
|
156 |
+
|
157 |
+
if isinstance(self.options.imagemask, dict) and self.options.imagemask.get("layers") and len(self.options.imagemask["layers"]) > 0:
|
158 |
+
self.options.imagemask = self.options.imagemask.get("layers")[0]
|
159 |
+
# Get rid of alpha
|
160 |
+
self.options.imagemask = cv2.cvtColor(self.options.imagemask, cv2.COLOR_RGBA2GRAY)
|
161 |
+
if np.any(self.options.imagemask):
|
162 |
+
mo = self.input_face_datas[0].faces[0].mask_offsets
|
163 |
+
self.options.imagemask = self.blur_area(self.options.imagemask, mo[4], mo[5])
|
164 |
+
self.options.imagemask = self.options.imagemask.astype(np.float32) / 255
|
165 |
+
self.options.imagemask = cv2.cvtColor(self.options.imagemask, cv2.COLOR_GRAY2RGB)
|
166 |
+
else:
|
167 |
+
self.options.imagemask = None
|
168 |
+
|
169 |
+
self.options.frame_processing = False
|
170 |
+
for p in self.processors:
|
171 |
+
if p.type.startswith("frame_"):
|
172 |
+
self.options.frame_processing = True
|
173 |
+
|
174 |
+
|
175 |
+
|
176 |
+
|
177 |
+
|
178 |
+
|
179 |
+
def run_batch(self, source_files, target_files, threads:int = 1):
|
180 |
+
progress_bar_format = '{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]'
|
181 |
+
self.total_frames = len(source_files)
|
182 |
+
self.num_threads = threads
|
183 |
+
with tqdm(total=self.total_frames, desc='Processing', unit='frame', dynamic_ncols=True, bar_format=progress_bar_format) as progress:
|
184 |
+
with ThreadPoolExecutor(max_workers=threads) as executor:
|
185 |
+
futures = []
|
186 |
+
queue = create_queue(source_files)
|
187 |
+
queue_per_future = max(len(source_files) // threads, 1)
|
188 |
+
while not queue.empty():
|
189 |
+
future = executor.submit(self.process_frames, source_files, target_files, pick_queue(queue, queue_per_future), lambda: self.update_progress(progress))
|
190 |
+
futures.append(future)
|
191 |
+
for future in as_completed(futures):
|
192 |
+
future.result()
|
193 |
+
|
194 |
+
|
195 |
+
def process_frames(self, source_files: List[str], target_files: List[str], current_files, update: Callable[[], None]) -> None:
|
196 |
+
for f in current_files:
|
197 |
+
if not roop.globals.processing:
|
198 |
+
return
|
199 |
+
|
200 |
+
# Decode the byte array into an OpenCV image
|
201 |
+
temp_frame = cv2.imdecode(np.fromfile(f, dtype=np.uint8), cv2.IMREAD_COLOR)
|
202 |
+
if temp_frame is not None:
|
203 |
+
if self.options.frame_processing:
|
204 |
+
for p in self.processors:
|
205 |
+
frame = p.Run(temp_frame)
|
206 |
+
resimg = frame
|
207 |
+
else:
|
208 |
+
resimg = self.process_frame(temp_frame)
|
209 |
+
if resimg is not None:
|
210 |
+
i = source_files.index(f)
|
211 |
+
# Also let numpy write the file to support utf-8/16 filenames
|
212 |
+
cv2.imencode(f'.{roop.globals.CFG.output_image_format}',resimg)[1].tofile(target_files[i])
|
213 |
+
if update:
|
214 |
+
update()
|
215 |
+
|
216 |
+
|
217 |
+
|
218 |
+
def read_frames_thread(self, cap, frame_start, frame_end, num_threads):
|
219 |
+
num_frame = 0
|
220 |
+
total_num = frame_end - frame_start
|
221 |
+
if frame_start > 0:
|
222 |
+
cap.set(cv2.CAP_PROP_POS_FRAMES,frame_start)
|
223 |
+
|
224 |
+
while True and roop.globals.processing:
|
225 |
+
ret, frame = cap.read()
|
226 |
+
if not ret:
|
227 |
+
break
|
228 |
+
|
229 |
+
self.frames_queue[num_frame % num_threads].put(frame, block=True)
|
230 |
+
num_frame += 1
|
231 |
+
if num_frame == total_num:
|
232 |
+
break
|
233 |
+
|
234 |
+
for i in range(num_threads):
|
235 |
+
self.frames_queue[i].put(None)
|
236 |
+
|
237 |
+
|
238 |
+
|
239 |
+
def process_videoframes(self, threadindex, progress) -> None:
|
240 |
+
while True:
|
241 |
+
frame = self.frames_queue[threadindex].get()
|
242 |
+
if frame is None:
|
243 |
+
self.processing_threads -= 1
|
244 |
+
self.processed_queue[threadindex].put((False, None))
|
245 |
+
return
|
246 |
+
else:
|
247 |
+
if self.options.frame_processing:
|
248 |
+
for p in self.processors:
|
249 |
+
frame = p.Run(frame)
|
250 |
+
resimg = frame
|
251 |
+
else:
|
252 |
+
resimg = self.process_frame(frame)
|
253 |
+
self.processed_queue[threadindex].put((True, resimg))
|
254 |
+
del frame
|
255 |
+
progress()
|
256 |
+
|
257 |
+
|
258 |
+
def write_frames_thread(self):
|
259 |
+
nextindex = 0
|
260 |
+
num_producers = self.num_threads
|
261 |
+
|
262 |
+
while True:
|
263 |
+
process, frame = self.processed_queue[nextindex % self.num_threads].get()
|
264 |
+
nextindex += 1
|
265 |
+
if frame is not None:
|
266 |
+
if self.output_to_file:
|
267 |
+
self.videowriter.write_frame(frame)
|
268 |
+
if self.output_to_cam:
|
269 |
+
self.streamwriter.WriteToStream(frame)
|
270 |
+
del frame
|
271 |
+
elif process == False:
|
272 |
+
num_producers -= 1
|
273 |
+
if num_producers < 1:
|
274 |
+
return
|
275 |
+
|
276 |
+
|
277 |
+
|
278 |
+
def run_batch_inmem(self, output_method, source_video, target_video, frame_start, frame_end, fps, threads:int = 1):
|
279 |
+
if len(self.processors) < 1:
|
280 |
+
print("No processor defined!")
|
281 |
+
return
|
282 |
+
|
283 |
+
cap = cv2.VideoCapture(source_video)
|
284 |
+
# frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
285 |
+
frame_count = (frame_end - frame_start) + 1
|
286 |
+
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
287 |
+
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
288 |
+
|
289 |
+
processed_resolution = None
|
290 |
+
for p in self.processors:
|
291 |
+
if hasattr(p, 'getProcessedResolution'):
|
292 |
+
processed_resolution = p.getProcessedResolution(width, height)
|
293 |
+
print(f"Processed resolution: {processed_resolution}")
|
294 |
+
if processed_resolution is not None:
|
295 |
+
width = processed_resolution[0]
|
296 |
+
height = processed_resolution[1]
|
297 |
+
|
298 |
+
|
299 |
+
self.total_frames = frame_count
|
300 |
+
self.num_threads = threads
|
301 |
+
|
302 |
+
self.processing_threads = self.num_threads
|
303 |
+
self.frames_queue = []
|
304 |
+
self.processed_queue = []
|
305 |
+
for _ in range(threads):
|
306 |
+
self.frames_queue.append(Queue(1))
|
307 |
+
self.processed_queue.append(Queue(1))
|
308 |
+
|
309 |
+
self.output_to_file = output_method != "Virtual Camera"
|
310 |
+
self.output_to_cam = output_method == "Virtual Camera" or output_method == "Both"
|
311 |
+
|
312 |
+
if self.output_to_file:
|
313 |
+
self.videowriter = FFMPEG_VideoWriter(target_video, (width, height), fps, codec=roop.globals.video_encoder, crf=roop.globals.video_quality, audiofile=None)
|
314 |
+
if self.output_to_cam:
|
315 |
+
self.streamwriter = StreamWriter((width, height), int(fps))
|
316 |
+
|
317 |
+
readthread = Thread(target=self.read_frames_thread, args=(cap, frame_start, frame_end, threads))
|
318 |
+
readthread.start()
|
319 |
+
|
320 |
+
writethread = Thread(target=self.write_frames_thread)
|
321 |
+
writethread.start()
|
322 |
+
|
323 |
+
progress_bar_format = '{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]'
|
324 |
+
with tqdm(total=self.total_frames, desc='Processing', unit='frames', dynamic_ncols=True, bar_format=progress_bar_format) as progress:
|
325 |
+
with ThreadPoolExecutor(thread_name_prefix='swap_proc', max_workers=self.num_threads) as executor:
|
326 |
+
futures = []
|
327 |
+
|
328 |
+
for threadindex in range(threads):
|
329 |
+
future = executor.submit(self.process_videoframes, threadindex, lambda: self.update_progress(progress))
|
330 |
+
futures.append(future)
|
331 |
+
|
332 |
+
for future in as_completed(futures):
|
333 |
+
future.result()
|
334 |
+
# wait for the task to complete
|
335 |
+
readthread.join()
|
336 |
+
writethread.join()
|
337 |
+
cap.release()
|
338 |
+
if self.output_to_file:
|
339 |
+
self.videowriter.close()
|
340 |
+
if self.output_to_cam:
|
341 |
+
self.streamwriter.Close()
|
342 |
+
|
343 |
+
self.frames_queue.clear()
|
344 |
+
self.processed_queue.clear()
|
345 |
+
|
346 |
+
|
347 |
+
|
348 |
+
|
349 |
+
def update_progress(self, progress: Any = None) -> None:
|
350 |
+
process = psutil.Process(os.getpid())
|
351 |
+
memory_usage = process.memory_info().rss / 1024 / 1024 / 1024
|
352 |
+
progress.set_postfix({
|
353 |
+
'memory_usage': '{:.2f}'.format(memory_usage).zfill(5) + 'GB',
|
354 |
+
'execution_threads': self.num_threads
|
355 |
+
})
|
356 |
+
progress.update(1)
|
357 |
+
if self.progress_gradio is not None:
|
358 |
+
self.progress_gradio((progress.n, self.total_frames), desc='Processing', total=self.total_frames, unit='frames')
|
359 |
+
|
360 |
+
|
361 |
+
|
362 |
+
def process_frame(self, frame:Frame):
|
363 |
+
if len(self.input_face_datas) < 1 and not self.options.show_face_masking:
|
364 |
+
return frame
|
365 |
+
temp_frame = frame.copy()
|
366 |
+
num_swapped, temp_frame = self.swap_faces(frame, temp_frame)
|
367 |
+
if num_swapped > 0:
|
368 |
+
if roop.globals.no_face_action == eNoFaceAction.SKIP_FRAME_IF_DISSIMILAR:
|
369 |
+
if len(self.input_face_datas) > num_swapped:
|
370 |
+
return None
|
371 |
+
self.num_frames_no_face = 0
|
372 |
+
self.last_swapped_frame = temp_frame.copy()
|
373 |
+
return temp_frame
|
374 |
+
if roop.globals.no_face_action == eNoFaceAction.USE_LAST_SWAPPED:
|
375 |
+
if self.last_swapped_frame is not None and self.num_frames_no_face < self.options.max_num_reuse_frame:
|
376 |
+
self.num_frames_no_face += 1
|
377 |
+
return self.last_swapped_frame.copy()
|
378 |
+
return frame
|
379 |
+
|
380 |
+
elif roop.globals.no_face_action == eNoFaceAction.USE_ORIGINAL_FRAME:
|
381 |
+
return frame
|
382 |
+
if roop.globals.no_face_action == eNoFaceAction.SKIP_FRAME:
|
383 |
+
#This only works with in-mem processing, as it simply skips the frame.
|
384 |
+
#For 'extract frames' it simply leaves the unprocessed frame unprocessed and it gets used in the final output by ffmpeg.
|
385 |
+
#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?????
|
386 |
+
#alternatively, it could mark all the necessary frames for deletion, delete them at the end, then rename the remaining frames that might work?
|
387 |
+
return None
|
388 |
+
else:
|
389 |
+
return self.retry_rotated(frame)
|
390 |
+
|
391 |
+
def retry_rotated(self, frame):
|
392 |
+
copyframe = frame.copy()
|
393 |
+
copyframe = rotate_clockwise(copyframe)
|
394 |
+
temp_frame = copyframe.copy()
|
395 |
+
num_swapped, temp_frame = self.swap_faces(copyframe, temp_frame)
|
396 |
+
if num_swapped > 0:
|
397 |
+
return rotate_anticlockwise(temp_frame)
|
398 |
+
|
399 |
+
copyframe = frame.copy()
|
400 |
+
copyframe = rotate_anticlockwise(copyframe)
|
401 |
+
temp_frame = copyframe.copy()
|
402 |
+
num_swapped, temp_frame = self.swap_faces(copyframe, temp_frame)
|
403 |
+
if num_swapped > 0:
|
404 |
+
return rotate_clockwise(temp_frame)
|
405 |
+
del copyframe
|
406 |
+
return frame
|
407 |
+
|
408 |
+
|
409 |
+
|
410 |
+
def swap_faces(self, frame, temp_frame):
|
411 |
+
num_faces_found = 0
|
412 |
+
|
413 |
+
if self.options.swap_mode == "first":
|
414 |
+
face = get_first_face(frame)
|
415 |
+
|
416 |
+
if face is None:
|
417 |
+
return num_faces_found, frame
|
418 |
+
|
419 |
+
num_faces_found += 1
|
420 |
+
temp_frame = self.process_face(self.options.selected_index, face, temp_frame)
|
421 |
+
del face
|
422 |
+
|
423 |
+
else:
|
424 |
+
faces = get_all_faces(frame)
|
425 |
+
if faces is None:
|
426 |
+
return num_faces_found, frame
|
427 |
+
|
428 |
+
if self.options.swap_mode == "all":
|
429 |
+
for face in faces:
|
430 |
+
num_faces_found += 1
|
431 |
+
temp_frame = self.process_face(self.options.selected_index, face, temp_frame)
|
432 |
+
|
433 |
+
elif self.options.swap_mode == "all_input" or self.options.swap_mode == "all_random":
|
434 |
+
for i,face in enumerate(faces):
|
435 |
+
num_faces_found += 1
|
436 |
+
if i < len(self.input_face_datas):
|
437 |
+
temp_frame = self.process_face(i, face, temp_frame)
|
438 |
+
else:
|
439 |
+
break
|
440 |
+
|
441 |
+
elif self.options.swap_mode == "selected":
|
442 |
+
num_targetfaces = len(self.target_face_datas)
|
443 |
+
use_index = num_targetfaces == 1
|
444 |
+
for i,tf in enumerate(self.target_face_datas):
|
445 |
+
for face in faces:
|
446 |
+
if compute_cosine_distance(tf.embedding, face.embedding) <= self.options.face_distance_threshold:
|
447 |
+
if i < len(self.input_face_datas):
|
448 |
+
if use_index:
|
449 |
+
temp_frame = self.process_face(self.options.selected_index, face, temp_frame)
|
450 |
+
else:
|
451 |
+
temp_frame = self.process_face(i, face, temp_frame)
|
452 |
+
num_faces_found += 1
|
453 |
+
if not roop.globals.vr_mode and num_faces_found == num_targetfaces:
|
454 |
+
break
|
455 |
+
elif self.options.swap_mode == "all_female" or self.options.swap_mode == "all_male":
|
456 |
+
gender = 'F' if self.options.swap_mode == "all_female" else 'M'
|
457 |
+
for face in faces:
|
458 |
+
if face.sex == gender:
|
459 |
+
num_faces_found += 1
|
460 |
+
temp_frame = self.process_face(self.options.selected_index, face, temp_frame)
|
461 |
+
|
462 |
+
# might be slower but way more clean to release everything here
|
463 |
+
for face in faces:
|
464 |
+
del face
|
465 |
+
faces.clear()
|
466 |
+
|
467 |
+
|
468 |
+
|
469 |
+
if roop.globals.vr_mode and num_faces_found % 2 > 0:
|
470 |
+
# stereo image, there has to be an even number of faces
|
471 |
+
num_faces_found = 0
|
472 |
+
return num_faces_found, frame
|
473 |
+
if num_faces_found == 0:
|
474 |
+
return num_faces_found, frame
|
475 |
+
|
476 |
+
#maskprocessor = next((x for x in self.processors if x.type == 'mask'), None)
|
477 |
+
|
478 |
+
if self.options.imagemask is not None and self.options.imagemask.shape == frame.shape:
|
479 |
+
temp_frame = self.simple_blend_with_mask(temp_frame, frame, self.options.imagemask)
|
480 |
+
return num_faces_found, temp_frame
|
481 |
+
|
482 |
+
|
483 |
+
def rotation_action(self, original_face:Face, frame:Frame):
|
484 |
+
(height, width) = frame.shape[:2]
|
485 |
+
|
486 |
+
bounding_box_width = original_face.bbox[2] - original_face.bbox[0]
|
487 |
+
bounding_box_height = original_face.bbox[3] - original_face.bbox[1]
|
488 |
+
horizontal_face = bounding_box_width > bounding_box_height
|
489 |
+
|
490 |
+
center_x = width // 2.0
|
491 |
+
start_x = original_face.bbox[0]
|
492 |
+
end_x = original_face.bbox[2]
|
493 |
+
bbox_center_x = start_x + (bounding_box_width // 2.0)
|
494 |
+
|
495 |
+
# need to leverage the array of landmarks as decribed here:
|
496 |
+
# https://github.com/deepinsight/insightface/tree/master/alignment/coordinate_reg
|
497 |
+
# basically, we should be able to check for the relative position of eyes and nose
|
498 |
+
# then use that to determine which way the face is actually facing when in a horizontal position
|
499 |
+
# and use that to determine the correct rotation_action
|
500 |
+
|
501 |
+
forehead_x = original_face.landmark_2d_106[72][0]
|
502 |
+
chin_x = original_face.landmark_2d_106[0][0]
|
503 |
+
|
504 |
+
if horizontal_face:
|
505 |
+
if chin_x < forehead_x:
|
506 |
+
# this is someone lying down with their face like this (:
|
507 |
+
return "rotate_anticlockwise"
|
508 |
+
elif forehead_x < chin_x:
|
509 |
+
# this is someone lying down with their face like this :)
|
510 |
+
return "rotate_clockwise"
|
511 |
+
if bbox_center_x >= center_x:
|
512 |
+
# this is someone lying down with their face in the right hand side of the frame
|
513 |
+
return "rotate_anticlockwise"
|
514 |
+
if bbox_center_x < center_x:
|
515 |
+
# this is someone lying down with their face in the left hand side of the frame
|
516 |
+
return "rotate_clockwise"
|
517 |
+
|
518 |
+
return None
|
519 |
+
|
520 |
+
|
521 |
+
def auto_rotate_frame(self, original_face, frame:Frame):
|
522 |
+
target_face = original_face
|
523 |
+
original_frame = frame
|
524 |
+
|
525 |
+
rotation_action = self.rotation_action(original_face, frame)
|
526 |
+
|
527 |
+
if rotation_action == "rotate_anticlockwise":
|
528 |
+
#face is horizontal, rotating frame anti-clockwise and getting face bounding box from rotated frame
|
529 |
+
frame = rotate_anticlockwise(frame)
|
530 |
+
elif rotation_action == "rotate_clockwise":
|
531 |
+
#face is horizontal, rotating frame clockwise and getting face bounding box from rotated frame
|
532 |
+
frame = rotate_clockwise(frame)
|
533 |
+
|
534 |
+
return target_face, frame, rotation_action
|
535 |
+
|
536 |
+
|
537 |
+
def auto_unrotate_frame(self, frame:Frame, rotation_action):
|
538 |
+
if rotation_action == "rotate_anticlockwise":
|
539 |
+
return rotate_clockwise(frame)
|
540 |
+
elif rotation_action == "rotate_clockwise":
|
541 |
+
return rotate_anticlockwise(frame)
|
542 |
+
|
543 |
+
return frame
|
544 |
+
|
545 |
+
|
546 |
+
|
547 |
+
def process_face(self,face_index, target_face:Face, frame:Frame):
|
548 |
+
from roop.face_util import align_crop
|
549 |
+
|
550 |
+
enhanced_frame = None
|
551 |
+
if(len(self.input_face_datas) > 0):
|
552 |
+
inputface = self.input_face_datas[face_index].faces[0]
|
553 |
+
else:
|
554 |
+
inputface = None
|
555 |
+
|
556 |
+
rotation_action = None
|
557 |
+
if roop.globals.autorotate_faces:
|
558 |
+
# check for sideways rotation of face
|
559 |
+
rotation_action = self.rotation_action(target_face, frame)
|
560 |
+
if rotation_action is not None:
|
561 |
+
(startX, startY, endX, endY) = target_face["bbox"].astype("int")
|
562 |
+
width = endX - startX
|
563 |
+
height = endY - startY
|
564 |
+
offs = int(max(width,height) * 0.25)
|
565 |
+
rotcutframe,startX, startY, endX, endY = self.cutout(frame, startX - offs, startY - offs, endX + offs, endY + offs)
|
566 |
+
if rotation_action == "rotate_anticlockwise":
|
567 |
+
rotcutframe = rotate_anticlockwise(rotcutframe)
|
568 |
+
elif rotation_action == "rotate_clockwise":
|
569 |
+
rotcutframe = rotate_clockwise(rotcutframe)
|
570 |
+
# rotate image and re-detect face to correct wonky landmarks
|
571 |
+
rotface = get_first_face(rotcutframe)
|
572 |
+
if rotface is None:
|
573 |
+
rotation_action = None
|
574 |
+
else:
|
575 |
+
saved_frame = frame.copy()
|
576 |
+
frame = rotcutframe
|
577 |
+
target_face = rotface
|
578 |
+
|
579 |
+
|
580 |
+
|
581 |
+
# if roop.globals.vr_mode:
|
582 |
+
# bbox = target_face.bbox
|
583 |
+
# [orig_width, orig_height, _] = frame.shape
|
584 |
+
|
585 |
+
# # Convert bounding box to ints
|
586 |
+
# x1, y1, x2, y2 = map(int, bbox)
|
587 |
+
|
588 |
+
# # Determine the center of the bounding box
|
589 |
+
# x_center = (x1 + x2) / 2
|
590 |
+
# y_center = (y1 + y2) / 2
|
591 |
+
|
592 |
+
# # Normalize coordinates to range [-1, 1]
|
593 |
+
# x_center_normalized = x_center / (orig_width / 2) - 1
|
594 |
+
# y_center_normalized = y_center / (orig_width / 2) - 1
|
595 |
+
|
596 |
+
# # Convert normalized coordinates to spherical (theta, phi)
|
597 |
+
# theta = x_center_normalized * 180 # Theta ranges from -180 to 180 degrees
|
598 |
+
# phi = -y_center_normalized * 90 # Phi ranges from -90 to 90 degrees
|
599 |
+
|
600 |
+
# img = vr.GetPerspective(frame, 90, theta, phi, 1280, 1280) # Generate perspective image
|
601 |
+
|
602 |
+
|
603 |
+
""" Code ported/adapted from Facefusion which borrowed the idea from Rope:
|
604 |
+
Kind of subsampling the cutout and aligned face image and faceswapping slices of it up to
|
605 |
+
the desired output resolution. This works around the current resolution limitations without using enhancers.
|
606 |
+
"""
|
607 |
+
model_output_size = self.options.swap_output_size
|
608 |
+
subsample_size = max(self.options.subsample_size, model_output_size)
|
609 |
+
subsample_total = subsample_size // model_output_size
|
610 |
+
aligned_img, M = align_crop(frame, target_face.kps, subsample_size)
|
611 |
+
|
612 |
+
fake_frame = aligned_img
|
613 |
+
target_face.matrix = M
|
614 |
+
|
615 |
+
for p in self.processors:
|
616 |
+
if p.type == 'swap':
|
617 |
+
swap_result_frames = []
|
618 |
+
subsample_frames = self.implode_pixel_boost(aligned_img, model_output_size, subsample_total)
|
619 |
+
for sliced_frame in subsample_frames:
|
620 |
+
for _ in range(0,self.options.num_swap_steps):
|
621 |
+
sliced_frame = self.prepare_crop_frame(sliced_frame)
|
622 |
+
sliced_frame = p.Run(inputface, target_face, sliced_frame)
|
623 |
+
sliced_frame = self.normalize_swap_frame(sliced_frame)
|
624 |
+
swap_result_frames.append(sliced_frame)
|
625 |
+
fake_frame = self.explode_pixel_boost(swap_result_frames, model_output_size, subsample_total, subsample_size)
|
626 |
+
fake_frame = fake_frame.astype(np.uint8)
|
627 |
+
scale_factor = 0.0
|
628 |
+
elif p.type == 'mask':
|
629 |
+
fake_frame = self.process_mask(p, aligned_img, fake_frame)
|
630 |
+
else:
|
631 |
+
enhanced_frame, scale_factor = p.Run(self.input_face_datas[face_index], target_face, fake_frame)
|
632 |
+
|
633 |
+
upscale = 512
|
634 |
+
orig_width = fake_frame.shape[1]
|
635 |
+
if orig_width != upscale:
|
636 |
+
fake_frame = cv2.resize(fake_frame, (upscale, upscale), cv2.INTER_CUBIC)
|
637 |
+
mask_offsets = (0,0,0,0,1,20) if inputface is None else inputface.mask_offsets
|
638 |
+
|
639 |
+
|
640 |
+
if enhanced_frame is None:
|
641 |
+
scale_factor = int(upscale / orig_width)
|
642 |
+
result = self.paste_upscale(fake_frame, fake_frame, target_face.matrix, frame, scale_factor, mask_offsets)
|
643 |
+
else:
|
644 |
+
result = self.paste_upscale(fake_frame, enhanced_frame, target_face.matrix, frame, scale_factor, mask_offsets)
|
645 |
+
|
646 |
+
# Restore mouth before unrotating
|
647 |
+
if self.options.restore_original_mouth:
|
648 |
+
mouth_cutout, mouth_bb = self.create_mouth_mask(target_face, frame)
|
649 |
+
result = self.apply_mouth_area(result, mouth_cutout, mouth_bb)
|
650 |
+
|
651 |
+
if rotation_action is not None:
|
652 |
+
fake_frame = self.auto_unrotate_frame(result, rotation_action)
|
653 |
+
result = self.paste_simple(fake_frame, saved_frame, startX, startY)
|
654 |
+
|
655 |
+
return result
|
656 |
+
|
657 |
+
|
658 |
+
|
659 |
+
|
660 |
+
def cutout(self, frame:Frame, start_x, start_y, end_x, end_y):
|
661 |
+
if start_x < 0:
|
662 |
+
start_x = 0
|
663 |
+
if start_y < 0:
|
664 |
+
start_y = 0
|
665 |
+
if end_x > frame.shape[1]:
|
666 |
+
end_x = frame.shape[1]
|
667 |
+
if end_y > frame.shape[0]:
|
668 |
+
end_y = frame.shape[0]
|
669 |
+
return frame[start_y:end_y, start_x:end_x], start_x, start_y, end_x, end_y
|
670 |
+
|
671 |
+
def paste_simple(self, src:Frame, dest:Frame, start_x, start_y):
|
672 |
+
end_x = start_x + src.shape[1]
|
673 |
+
end_y = start_y + src.shape[0]
|
674 |
+
|
675 |
+
start_x, end_x, start_y, end_y = clamp_cut_values(start_x, end_x, start_y, end_y, dest)
|
676 |
+
dest[start_y:end_y, start_x:end_x] = src
|
677 |
+
return dest
|
678 |
+
|
679 |
+
def simple_blend_with_mask(self, image1, image2, mask):
|
680 |
+
# Blend the images
|
681 |
+
blended_image = image1.astype(np.float32) * (1.0 - mask) + image2.astype(np.float32) * mask
|
682 |
+
return blended_image.astype(np.uint8)
|
683 |
+
|
684 |
+
|
685 |
+
def paste_upscale(self, fake_face, upsk_face, M, target_img, scale_factor, mask_offsets):
|
686 |
+
M_scale = M * scale_factor
|
687 |
+
IM = cv2.invertAffineTransform(M_scale)
|
688 |
+
|
689 |
+
face_matte = np.full((target_img.shape[0],target_img.shape[1]), 255, dtype=np.uint8)
|
690 |
+
# Generate white square sized as a upsk_face
|
691 |
+
img_matte = np.zeros((upsk_face.shape[0],upsk_face.shape[1]), dtype=np.uint8)
|
692 |
+
|
693 |
+
w = img_matte.shape[1]
|
694 |
+
h = img_matte.shape[0]
|
695 |
+
|
696 |
+
top = int(mask_offsets[0] * h)
|
697 |
+
bottom = int(h - (mask_offsets[1] * h))
|
698 |
+
left = int(mask_offsets[2] * w)
|
699 |
+
right = int(w - (mask_offsets[3] * w))
|
700 |
+
img_matte[top:bottom,left:right] = 255
|
701 |
+
|
702 |
+
# Transform white square back to target_img
|
703 |
+
img_matte = cv2.warpAffine(img_matte, IM, (target_img.shape[1], target_img.shape[0]), flags=cv2.INTER_NEAREST, borderValue=0.0)
|
704 |
+
##Blacken the edges of face_matte by 1 pixels (so the mask in not expanded on the image edges)
|
705 |
+
img_matte[:1,:] = img_matte[-1:,:] = img_matte[:,:1] = img_matte[:,-1:] = 0
|
706 |
+
|
707 |
+
img_matte = self.blur_area(img_matte, mask_offsets[4], mask_offsets[5])
|
708 |
+
#Normalize images to float values and reshape
|
709 |
+
img_matte = img_matte.astype(np.float32)/255
|
710 |
+
face_matte = face_matte.astype(np.float32)/255
|
711 |
+
img_matte = np.minimum(face_matte, img_matte)
|
712 |
+
if self.options.show_face_area_overlay:
|
713 |
+
# Additional steps for green overlay
|
714 |
+
green_overlay = np.zeros_like(target_img)
|
715 |
+
green_color = [0, 255, 0] # RGB for green
|
716 |
+
for i in range(3): # Apply green color where img_matte is not zero
|
717 |
+
green_overlay[:, :, i] = np.where(img_matte > 0, green_color[i], 0) ##Transform upcaled face back to target_img
|
718 |
+
img_matte = np.reshape(img_matte, [img_matte.shape[0],img_matte.shape[1],1])
|
719 |
+
paste_face = cv2.warpAffine(upsk_face, IM, (target_img.shape[1], target_img.shape[0]), borderMode=cv2.BORDER_REPLICATE)
|
720 |
+
if upsk_face is not fake_face:
|
721 |
+
fake_face = cv2.warpAffine(fake_face, IM, (target_img.shape[1], target_img.shape[0]), borderMode=cv2.BORDER_REPLICATE)
|
722 |
+
paste_face = cv2.addWeighted(paste_face, self.options.blend_ratio, fake_face, 1.0 - self.options.blend_ratio, 0)
|
723 |
+
|
724 |
+
# Re-assemble image
|
725 |
+
paste_face = img_matte * paste_face
|
726 |
+
paste_face = paste_face + (1-img_matte) * target_img.astype(np.float32)
|
727 |
+
if self.options.show_face_area_overlay:
|
728 |
+
# Overlay the green overlay on the final image
|
729 |
+
paste_face = cv2.addWeighted(paste_face.astype(np.uint8), 1 - 0.5, green_overlay, 0.5, 0)
|
730 |
+
return paste_face.astype(np.uint8)
|
731 |
+
|
732 |
+
|
733 |
+
def blur_area(self, img_matte, num_erosion_iterations, blur_amount):
|
734 |
+
# Detect the affine transformed white area
|
735 |
+
mask_h_inds, mask_w_inds = np.where(img_matte==255)
|
736 |
+
# Calculate the size (and diagonal size) of transformed white area width and height boundaries
|
737 |
+
mask_h = np.max(mask_h_inds) - np.min(mask_h_inds)
|
738 |
+
mask_w = np.max(mask_w_inds) - np.min(mask_w_inds)
|
739 |
+
mask_size = int(np.sqrt(mask_h*mask_w))
|
740 |
+
# Calculate the kernel size for eroding img_matte by kernel (insightface empirical guess for best size was max(mask_size//10,10))
|
741 |
+
# k = max(mask_size//12, 8)
|
742 |
+
k = max(mask_size//(blur_amount // 2) , blur_amount // 2)
|
743 |
+
kernel = np.ones((k,k),np.uint8)
|
744 |
+
img_matte = cv2.erode(img_matte,kernel,iterations = num_erosion_iterations)
|
745 |
+
#Calculate the kernel size for blurring img_matte by blur_size (insightface empirical guess for best size was max(mask_size//20, 5))
|
746 |
+
# k = max(mask_size//24, 4)
|
747 |
+
k = max(mask_size//blur_amount, blur_amount//5)
|
748 |
+
kernel_size = (k, k)
|
749 |
+
blur_size = tuple(2*i+1 for i in kernel_size)
|
750 |
+
return cv2.GaussianBlur(img_matte, blur_size, 0)
|
751 |
+
|
752 |
+
|
753 |
+
def prepare_crop_frame(self, swap_frame):
|
754 |
+
model_type = 'inswapper'
|
755 |
+
model_mean = [0.0, 0.0, 0.0]
|
756 |
+
model_standard_deviation = [1.0, 1.0, 1.0]
|
757 |
+
|
758 |
+
if model_type == 'ghost':
|
759 |
+
swap_frame = swap_frame[:, :, ::-1] / 127.5 - 1
|
760 |
+
else:
|
761 |
+
swap_frame = swap_frame[:, :, ::-1] / 255.0
|
762 |
+
swap_frame = (swap_frame - model_mean) / model_standard_deviation
|
763 |
+
swap_frame = swap_frame.transpose(2, 0, 1)
|
764 |
+
swap_frame = np.expand_dims(swap_frame, axis = 0).astype(np.float32)
|
765 |
+
return swap_frame
|
766 |
+
|
767 |
+
|
768 |
+
def normalize_swap_frame(self, swap_frame):
|
769 |
+
model_type = 'inswapper'
|
770 |
+
swap_frame = swap_frame.transpose(1, 2, 0)
|
771 |
+
|
772 |
+
if model_type == 'ghost':
|
773 |
+
swap_frame = (swap_frame * 127.5 + 127.5).round()
|
774 |
+
else:
|
775 |
+
swap_frame = (swap_frame * 255.0).round()
|
776 |
+
swap_frame = swap_frame[:, :, ::-1]
|
777 |
+
return swap_frame
|
778 |
+
|
779 |
+
def implode_pixel_boost(self, aligned_face_frame, model_size, pixel_boost_total : int):
|
780 |
+
subsample_frame = aligned_face_frame.reshape(model_size, pixel_boost_total, model_size, pixel_boost_total, 3)
|
781 |
+
subsample_frame = subsample_frame.transpose(1, 3, 0, 2, 4).reshape(pixel_boost_total ** 2, model_size, model_size, 3)
|
782 |
+
return subsample_frame
|
783 |
+
|
784 |
+
|
785 |
+
def explode_pixel_boost(self, subsample_frame, model_size, pixel_boost_total, pixel_boost_size):
|
786 |
+
final_frame = np.stack(subsample_frame, axis = 0).reshape(pixel_boost_total, pixel_boost_total, model_size, model_size, 3)
|
787 |
+
final_frame = final_frame.transpose(2, 0, 3, 1, 4).reshape(pixel_boost_size, pixel_boost_size, 3)
|
788 |
+
return final_frame
|
789 |
+
|
790 |
+
def process_mask(self, processor, frame:Frame, target:Frame):
|
791 |
+
img_mask = processor.Run(frame, self.options.masking_text)
|
792 |
+
img_mask = cv2.resize(img_mask, (target.shape[1], target.shape[0]))
|
793 |
+
img_mask = np.reshape(img_mask, [img_mask.shape[0],img_mask.shape[1],1])
|
794 |
+
|
795 |
+
if self.options.show_face_masking:
|
796 |
+
result = (1 - img_mask) * frame.astype(np.float32)
|
797 |
+
return np.uint8(result)
|
798 |
+
|
799 |
+
|
800 |
+
target = target.astype(np.float32)
|
801 |
+
result = (1-img_mask) * target
|
802 |
+
result += img_mask * frame.astype(np.float32)
|
803 |
+
return np.uint8(result)
|
804 |
+
|
805 |
+
|
806 |
+
# Code for mouth restoration adapted from https://github.com/iVideoGameBoss/iRoopDeepFaceCam
|
807 |
+
|
808 |
+
def create_mouth_mask(self, face: Face, frame: Frame):
|
809 |
+
mouth_cutout = None
|
810 |
+
|
811 |
+
landmarks = face.landmark_2d_106
|
812 |
+
if landmarks is not None:
|
813 |
+
# Get mouth landmarks (indices 52 to 71 typically represent the outer mouth)
|
814 |
+
mouth_points = landmarks[52:71].astype(np.int32)
|
815 |
+
|
816 |
+
# Add padding to mouth area
|
817 |
+
min_x, min_y = np.min(mouth_points, axis=0)
|
818 |
+
max_x, max_y = np.max(mouth_points, axis=0)
|
819 |
+
min_x = max(0, min_x - (15*6))
|
820 |
+
min_y = max(0, min_y - 22)
|
821 |
+
max_x = min(frame.shape[1], max_x + (15*6))
|
822 |
+
max_y = min(frame.shape[0], max_y + (90*6))
|
823 |
+
|
824 |
+
# Extract the mouth area from the frame using the calculated bounding box
|
825 |
+
mouth_cutout = frame[min_y:max_y, min_x:max_x].copy()
|
826 |
+
|
827 |
+
return mouth_cutout, (min_x, min_y, max_x, max_y)
|
828 |
+
|
829 |
+
|
830 |
+
|
831 |
+
def create_feathered_mask(self, shape, feather_amount=30):
|
832 |
+
mask = np.zeros(shape[:2], dtype=np.float32)
|
833 |
+
center = (shape[1] // 2, shape[0] // 2)
|
834 |
+
cv2.ellipse(mask, center, (shape[1] // 2 - feather_amount, shape[0] // 2 - feather_amount),
|
835 |
+
0, 0, 360, 1, -1)
|
836 |
+
mask = cv2.GaussianBlur(mask, (feather_amount*2+1, feather_amount*2+1), 0)
|
837 |
+
return mask / np.max(mask)
|
838 |
+
|
839 |
+
def apply_mouth_area(self, frame: np.ndarray, mouth_cutout: np.ndarray, mouth_box: tuple) -> np.ndarray:
|
840 |
+
min_x, min_y, max_x, max_y = mouth_box
|
841 |
+
box_width = max_x - min_x
|
842 |
+
box_height = max_y - min_y
|
843 |
+
|
844 |
+
|
845 |
+
# Resize the mouth cutout to match the mouth box size
|
846 |
+
if mouth_cutout is None or box_width is None or box_height is None:
|
847 |
+
return frame
|
848 |
+
try:
|
849 |
+
resized_mouth_cutout = cv2.resize(mouth_cutout, (box_width, box_height))
|
850 |
+
|
851 |
+
# Extract the region of interest (ROI) from the target frame
|
852 |
+
roi = frame[min_y:max_y, min_x:max_x]
|
853 |
+
|
854 |
+
# Ensure the ROI and resized_mouth_cutout have the same shape
|
855 |
+
if roi.shape != resized_mouth_cutout.shape:
|
856 |
+
resized_mouth_cutout = cv2.resize(resized_mouth_cutout, (roi.shape[1], roi.shape[0]))
|
857 |
+
|
858 |
+
# Apply color transfer from ROI to mouth cutout
|
859 |
+
color_corrected_mouth = self.apply_color_transfer(resized_mouth_cutout, roi)
|
860 |
+
|
861 |
+
# Create a feathered mask with increased feather amount
|
862 |
+
feather_amount = min(30, box_width // 15, box_height // 15)
|
863 |
+
mask = self.create_feathered_mask(resized_mouth_cutout.shape, feather_amount)
|
864 |
+
|
865 |
+
# Blend the color-corrected mouth cutout with the ROI using the feathered mask
|
866 |
+
mask = mask[:,:,np.newaxis] # Add channel dimension to mask
|
867 |
+
blended = (color_corrected_mouth * mask + roi * (1 - mask)).astype(np.uint8)
|
868 |
+
|
869 |
+
# Place the blended result back into the frame
|
870 |
+
frame[min_y:max_y, min_x:max_x] = blended
|
871 |
+
except Exception as e:
|
872 |
+
print(f'Error {e}')
|
873 |
+
pass
|
874 |
+
|
875 |
+
return frame
|
876 |
+
|
877 |
+
def apply_color_transfer(self, source, target):
|
878 |
+
"""
|
879 |
+
Apply color transfer from target to source image
|
880 |
+
"""
|
881 |
+
source = cv2.cvtColor(source, cv2.COLOR_BGR2LAB).astype("float32")
|
882 |
+
target = cv2.cvtColor(target, cv2.COLOR_BGR2LAB).astype("float32")
|
883 |
+
|
884 |
+
source_mean, source_std = cv2.meanStdDev(source)
|
885 |
+
target_mean, target_std = cv2.meanStdDev(target)
|
886 |
+
|
887 |
+
# Reshape mean and std to be broadcastable
|
888 |
+
source_mean = source_mean.reshape(1, 1, 3)
|
889 |
+
source_std = source_std.reshape(1, 1, 3)
|
890 |
+
target_mean = target_mean.reshape(1, 1, 3)
|
891 |
+
target_std = target_std.reshape(1, 1, 3)
|
892 |
+
|
893 |
+
# Perform the color transfer
|
894 |
+
source = (source - source_mean) * (target_std / source_std) + target_mean
|
895 |
+
return cv2.cvtColor(np.clip(source, 0, 255).astype("uint8"), cv2.COLOR_LAB2BGR)
|
896 |
+
|
897 |
+
|
898 |
+
|
899 |
+
def unload_models():
|
900 |
+
pass
|
901 |
+
|
902 |
+
|
903 |
+
def release_resources(self):
|
904 |
+
for p in self.processors:
|
905 |
+
p.Release()
|
906 |
+
self.processors.clear()
|
907 |
+
if self.videowriter is not None:
|
908 |
+
self.videowriter.close()
|
909 |
+
if self.streamwriter is not None:
|
910 |
+
self.streamwriter.Close()
|
911 |
+
|
roop/ProcessOptions.py
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
class ProcessOptions:
|
2 |
+
|
3 |
+
def __init__(self, swap_model, processordefines:dict, face_distance, blend_ratio, swap_mode, selected_index, masking_text, imagemask, num_steps, subsample_size, show_face_area, restore_original_mouth, show_mask=False):
|
4 |
+
if swap_model is not None:
|
5 |
+
self.swap_modelname = swap_model
|
6 |
+
self.swap_output_size = int(swap_model.split()[-1])
|
7 |
+
else:
|
8 |
+
self.swap_output_size = 128
|
9 |
+
self.processors = processordefines
|
10 |
+
self.face_distance_threshold = face_distance
|
11 |
+
self.blend_ratio = blend_ratio
|
12 |
+
self.swap_mode = swap_mode
|
13 |
+
self.selected_index = selected_index
|
14 |
+
self.masking_text = masking_text
|
15 |
+
self.imagemask = imagemask
|
16 |
+
self.num_swap_steps = num_steps
|
17 |
+
self.show_face_area_overlay = show_face_area
|
18 |
+
self.show_face_masking = show_mask
|
19 |
+
self.subsample_size = subsample_size
|
20 |
+
self.restore_original_mouth = restore_original_mouth
|
21 |
+
self.max_num_reuse_frame = 15
|
roop/StreamWriter.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import threading
|
2 |
+
import time
|
3 |
+
import pyvirtualcam
|
4 |
+
|
5 |
+
|
6 |
+
class StreamWriter():
|
7 |
+
FPS = 30
|
8 |
+
VCam = None
|
9 |
+
Active = False
|
10 |
+
THREAD_LOCK_STREAM = threading.Lock()
|
11 |
+
time_last_process = None
|
12 |
+
timespan_min = 0.0
|
13 |
+
|
14 |
+
def __enter__(self):
|
15 |
+
return self
|
16 |
+
|
17 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
18 |
+
self.Close()
|
19 |
+
|
20 |
+
def __init__(self, size, fps):
|
21 |
+
self.time_last_process = time.perf_counter()
|
22 |
+
self.FPS = fps
|
23 |
+
self.timespan_min = 1.0 / fps
|
24 |
+
print('Detecting virtual cam devices')
|
25 |
+
self.VCam = pyvirtualcam.Camera(width=size[0], height=size[1], fps=fps, fmt=pyvirtualcam.PixelFormat.BGR, print_fps=False)
|
26 |
+
if self.VCam is None:
|
27 |
+
print("No virtual camera found!")
|
28 |
+
return
|
29 |
+
print(f'Using virtual camera: {self.VCam.device}')
|
30 |
+
print(f'Using {self.VCam.native_fmt}')
|
31 |
+
self.Active = True
|
32 |
+
|
33 |
+
|
34 |
+
def LimitFrames(self):
|
35 |
+
while True:
|
36 |
+
current_time = time.perf_counter()
|
37 |
+
time_passed = current_time - self.time_last_process
|
38 |
+
if time_passed >= self.timespan_min:
|
39 |
+
break
|
40 |
+
|
41 |
+
# First version used a queue and threading. Surprisingly this
|
42 |
+
# totally simple, blocking version is 10 times faster!
|
43 |
+
def WriteToStream(self, frame):
|
44 |
+
if self.VCam is None:
|
45 |
+
return
|
46 |
+
with self.THREAD_LOCK_STREAM:
|
47 |
+
self.LimitFrames()
|
48 |
+
self.VCam.send(frame)
|
49 |
+
self.time_last_process = time.perf_counter()
|
50 |
+
|
51 |
+
|
52 |
+
def Close(self):
|
53 |
+
self.Active = False
|
54 |
+
if self.VCam is None:
|
55 |
+
self.VCam.close()
|
56 |
+
self.VCam = None
|
57 |
+
|
58 |
+
|
59 |
+
|
60 |
+
|
roop/__init__.py
ADDED
Binary file (1.02 kB). View file
|
|
roop/__pycache__/FaceSet.cpython-310.pyc
ADDED
Binary file (1.02 kB). View file
|
|
roop/__pycache__/ProcessEntry.cpython-310.pyc
ADDED
Binary file (595 Bytes). View file
|
|
roop/__pycache__/ProcessMgr.cpython-310.pyc
ADDED
Binary file (22.3 kB). View file
|
|
roop/__pycache__/ProcessOptions.cpython-310.pyc
ADDED
Binary file (987 Bytes). View file
|
|
roop/__pycache__/StreamWriter.cpython-310.pyc
ADDED
Binary file (2 kB). View file
|
|
roop/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (153 Bytes). View file
|
|
roop/__pycache__/capturer.cpython-310.pyc
ADDED
Binary file (1.4 kB). View file
|
|
roop/__pycache__/core.cpython-310.pyc
ADDED
Binary file (12.4 kB). View file
|
|
roop/__pycache__/face_util.cpython-310.pyc
ADDED
Binary file (8.05 kB). View file
|
|
roop/__pycache__/ffmpeg_writer.cpython-310.pyc
ADDED
Binary file (5.64 kB). View file
|
|
roop/__pycache__/globals.cpython-310.pyc
ADDED
Binary file (1.26 kB). View file
|
|
roop/__pycache__/metadata.cpython-310.pyc
ADDED
Binary file (198 Bytes). View file
|
|
roop/__pycache__/template_parser.cpython-310.pyc
ADDED
Binary file (1.11 kB). View file
|
|
roop/__pycache__/typing.cpython-310.pyc
ADDED
Binary file (341 Bytes). View file
|
|
roop/__pycache__/util_ffmpeg.cpython-310.pyc
ADDED
Binary file (4.65 kB). View file
|
|
roop/__pycache__/utilities.cpython-310.pyc
ADDED
Binary file (13.1 kB). View file
|
|
roop/__pycache__/virtualcam.cpython-310.pyc
ADDED
Binary file (2.21 kB). View file
|
|
roop/__pycache__/vr_util.cpython-310.pyc
ADDED
Binary file (1.44 kB). View file
|
|
roop/capturer.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Optional
|
2 |
+
import cv2
|
3 |
+
import numpy as np
|
4 |
+
|
5 |
+
from roop.typing import Frame
|
6 |
+
|
7 |
+
current_video_path = None
|
8 |
+
current_frame_total = 0
|
9 |
+
current_capture = None
|
10 |
+
|
11 |
+
def get_image_frame(filename: str):
|
12 |
+
try:
|
13 |
+
return cv2.imdecode(np.fromfile(filename, dtype=np.uint8), cv2.IMREAD_COLOR)
|
14 |
+
except:
|
15 |
+
print(f"Exception reading {filename}")
|
16 |
+
return None
|
17 |
+
|
18 |
+
|
19 |
+
def get_video_frame(video_path: str, frame_number: int = 0) -> Optional[Frame]:
|
20 |
+
global current_video_path, current_capture, current_frame_total
|
21 |
+
|
22 |
+
if video_path != current_video_path:
|
23 |
+
release_video()
|
24 |
+
current_capture = cv2.VideoCapture(video_path)
|
25 |
+
current_video_path = video_path
|
26 |
+
current_frame_total = current_capture.get(cv2.CAP_PROP_FRAME_COUNT)
|
27 |
+
|
28 |
+
current_capture.set(cv2.CAP_PROP_POS_FRAMES, min(current_frame_total, frame_number - 1))
|
29 |
+
has_frame, frame = current_capture.read()
|
30 |
+
if has_frame:
|
31 |
+
return frame
|
32 |
+
return None
|
33 |
+
|
34 |
+
def release_video():
|
35 |
+
global current_capture
|
36 |
+
|
37 |
+
if current_capture is not None:
|
38 |
+
current_capture.release()
|
39 |
+
current_capture = None
|
40 |
+
|
41 |
+
|
42 |
+
def get_video_frame_total(video_path: str) -> int:
|
43 |
+
capture = cv2.VideoCapture(video_path)
|
44 |
+
video_frame_total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
|
45 |
+
capture.release()
|
46 |
+
return video_frame_total
|
roop/core.py
ADDED
@@ -0,0 +1,406 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
import argparse
|
18 |
+
|
19 |
+
from time import time
|
20 |
+
|
21 |
+
import roop.globals
|
22 |
+
import roop.metadata
|
23 |
+
import roop.utilities as util
|
24 |
+
import roop.util_ffmpeg as ffmpeg
|
25 |
+
import ui.main as main
|
26 |
+
from settings import Settings
|
27 |
+
from roop.face_util import extract_face_images
|
28 |
+
from roop.ProcessEntry import ProcessEntry
|
29 |
+
from roop.ProcessMgr import ProcessMgr
|
30 |
+
from roop.ProcessOptions import ProcessOptions
|
31 |
+
from roop.capturer import get_video_frame_total, release_video
|
32 |
+
|
33 |
+
|
34 |
+
clip_text = None
|
35 |
+
|
36 |
+
call_display_ui = None
|
37 |
+
|
38 |
+
process_mgr = None
|
39 |
+
|
40 |
+
|
41 |
+
if 'ROCMExecutionProvider' in roop.globals.execution_providers:
|
42 |
+
del torch
|
43 |
+
|
44 |
+
warnings.filterwarnings('ignore', category=FutureWarning, module='insightface')
|
45 |
+
warnings.filterwarnings('ignore', category=UserWarning, module='torchvision')
|
46 |
+
|
47 |
+
|
48 |
+
def parse_args() -> None:
|
49 |
+
signal.signal(signal.SIGINT, lambda signal_number, frame: destroy())
|
50 |
+
roop.globals.headless = False
|
51 |
+
|
52 |
+
program = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=100))
|
53 |
+
program.add_argument('--server_share', help='Public server', dest='server_share', action='store_true', default=False)
|
54 |
+
program.add_argument('--cuda_device_id', help='Index of the cuda gpu to use', dest='cuda_device_id', type=int, default=0)
|
55 |
+
roop.globals.startup_args = program.parse_args()
|
56 |
+
# Always enable all processors when using GUI
|
57 |
+
roop.globals.frame_processors = ['face_swapper', 'face_enhancer']
|
58 |
+
|
59 |
+
|
60 |
+
def encode_execution_providers(execution_providers: List[str]) -> List[str]:
|
61 |
+
return [execution_provider.replace('ExecutionProvider', '').lower() for execution_provider in execution_providers]
|
62 |
+
|
63 |
+
|
64 |
+
def decode_execution_providers(execution_providers: List[str]) -> List[str]:
|
65 |
+
list_providers = [provider for provider, encoded_execution_provider in zip(onnxruntime.get_available_providers(), encode_execution_providers(onnxruntime.get_available_providers()))
|
66 |
+
if any(execution_provider in encoded_execution_provider for execution_provider in execution_providers)]
|
67 |
+
|
68 |
+
try:
|
69 |
+
for i in range(len(list_providers)):
|
70 |
+
if list_providers[i] == 'CUDAExecutionProvider':
|
71 |
+
list_providers[i] = ('CUDAExecutionProvider', {'device_id': roop.globals.cuda_device_id})
|
72 |
+
torch.cuda.set_device(roop.globals.cuda_device_id)
|
73 |
+
break
|
74 |
+
except:
|
75 |
+
pass
|
76 |
+
|
77 |
+
return list_providers
|
78 |
+
|
79 |
+
|
80 |
+
|
81 |
+
def suggest_max_memory() -> int:
|
82 |
+
if platform.system().lower() == 'darwin':
|
83 |
+
return 4
|
84 |
+
return 16
|
85 |
+
|
86 |
+
|
87 |
+
def suggest_execution_providers() -> List[str]:
|
88 |
+
return encode_execution_providers(onnxruntime.get_available_providers())
|
89 |
+
|
90 |
+
|
91 |
+
def suggest_execution_threads() -> int:
|
92 |
+
if 'DmlExecutionProvider' in roop.globals.execution_providers:
|
93 |
+
return 1
|
94 |
+
if 'ROCMExecutionProvider' in roop.globals.execution_providers:
|
95 |
+
return 1
|
96 |
+
return 8
|
97 |
+
|
98 |
+
|
99 |
+
def limit_resources() -> None:
|
100 |
+
# limit memory usage
|
101 |
+
if roop.globals.max_memory:
|
102 |
+
memory = roop.globals.max_memory * 1024 ** 3
|
103 |
+
if platform.system().lower() == 'darwin':
|
104 |
+
memory = roop.globals.max_memory * 1024 ** 6
|
105 |
+
if platform.system().lower() == 'windows':
|
106 |
+
import ctypes
|
107 |
+
kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
|
108 |
+
kernel32.SetProcessWorkingSetSize(-1, ctypes.c_size_t(memory), ctypes.c_size_t(memory))
|
109 |
+
else:
|
110 |
+
import resource
|
111 |
+
resource.setrlimit(resource.RLIMIT_DATA, (memory, memory))
|
112 |
+
|
113 |
+
|
114 |
+
|
115 |
+
def release_resources() -> None:
|
116 |
+
import gc
|
117 |
+
global process_mgr
|
118 |
+
|
119 |
+
if process_mgr is not None:
|
120 |
+
process_mgr.release_resources()
|
121 |
+
process_mgr = None
|
122 |
+
|
123 |
+
gc.collect()
|
124 |
+
if 'CUDAExecutionProvider' in roop.globals.execution_providers and torch.cuda.is_available():
|
125 |
+
with torch.cuda.device('cuda'):
|
126 |
+
torch.cuda.empty_cache()
|
127 |
+
torch.cuda.ipc_collect()
|
128 |
+
|
129 |
+
|
130 |
+
def pre_check() -> bool:
|
131 |
+
if sys.version_info < (3, 9):
|
132 |
+
update_status('Python version is not supported - please upgrade to 3.9 or higher.')
|
133 |
+
return False
|
134 |
+
|
135 |
+
download_directory_path = util.resolve_relative_path('../models')
|
136 |
+
util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/inswapper_128.onnx'])
|
137 |
+
util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/reswapper_128.onnx'])
|
138 |
+
util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/reswapper_256.onnx'])
|
139 |
+
util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/GFPGANv1.4.onnx'])
|
140 |
+
util.conditional_download(download_directory_path, ['https://github.com/csxmli2016/DMDNet/releases/download/v1/DMDNet.pth'])
|
141 |
+
util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/GPEN-BFR-512.onnx'])
|
142 |
+
util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/restoreformer_plus_plus.onnx'])
|
143 |
+
util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/xseg.onnx'])
|
144 |
+
download_directory_path = util.resolve_relative_path('../models/CLIP')
|
145 |
+
util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/rd64-uni-refined.pth'])
|
146 |
+
download_directory_path = util.resolve_relative_path('../models/CodeFormer')
|
147 |
+
util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/CodeFormerv0.1.onnx'])
|
148 |
+
download_directory_path = util.resolve_relative_path('../models/Frame')
|
149 |
+
util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/deoldify_artistic.onnx'])
|
150 |
+
util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/deoldify_stable.onnx'])
|
151 |
+
util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/isnet-general-use.onnx'])
|
152 |
+
util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/real_esrgan_x4.onnx'])
|
153 |
+
util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/real_esrgan_x2.onnx'])
|
154 |
+
util.conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/lsdir_x4.onnx'])
|
155 |
+
|
156 |
+
if not shutil.which('ffmpeg'):
|
157 |
+
update_status('ffmpeg is not installed.')
|
158 |
+
return True
|
159 |
+
|
160 |
+
def set_display_ui(function):
|
161 |
+
global call_display_ui
|
162 |
+
|
163 |
+
call_display_ui = function
|
164 |
+
|
165 |
+
|
166 |
+
def update_status(message: str) -> None:
|
167 |
+
global call_display_ui
|
168 |
+
|
169 |
+
print(message)
|
170 |
+
if call_display_ui is not None:
|
171 |
+
call_display_ui(message)
|
172 |
+
|
173 |
+
|
174 |
+
|
175 |
+
|
176 |
+
def start() -> None:
|
177 |
+
if roop.globals.headless:
|
178 |
+
print('Headless mode currently unsupported - starting UI!')
|
179 |
+
# faces = extract_face_images(roop.globals.source_path, (False, 0))
|
180 |
+
# roop.globals.INPUT_FACES.append(faces[roop.globals.source_face_index])
|
181 |
+
# faces = extract_face_images(roop.globals.target_path, (False, util.has_image_extension(roop.globals.target_path)))
|
182 |
+
# roop.globals.TARGET_FACES.append(faces[roop.globals.target_face_index])
|
183 |
+
# if 'face_enhancer' in roop.globals.frame_processors:
|
184 |
+
# roop.globals.selected_enhancer = 'GFPGAN'
|
185 |
+
|
186 |
+
batch_process_regular(None, False, None)
|
187 |
+
|
188 |
+
|
189 |
+
def get_processing_plugins(masking_engine):
|
190 |
+
processors = { "faceswap": {}}
|
191 |
+
if masking_engine is not None:
|
192 |
+
processors.update({masking_engine: {}})
|
193 |
+
|
194 |
+
if roop.globals.selected_enhancer == 'GFPGAN':
|
195 |
+
processors.update({"gfpgan": {}})
|
196 |
+
elif roop.globals.selected_enhancer == 'Codeformer':
|
197 |
+
processors.update({"codeformer": {}})
|
198 |
+
elif roop.globals.selected_enhancer == 'DMDNet':
|
199 |
+
processors.update({"dmdnet": {}})
|
200 |
+
elif roop.globals.selected_enhancer == 'GPEN':
|
201 |
+
processors.update({"gpen": {}})
|
202 |
+
elif roop.globals.selected_enhancer == 'Restoreformer++':
|
203 |
+
processors.update({"restoreformer++": {}})
|
204 |
+
return processors
|
205 |
+
|
206 |
+
|
207 |
+
def live_swap(frame, options):
|
208 |
+
global process_mgr
|
209 |
+
|
210 |
+
if frame is None:
|
211 |
+
return frame
|
212 |
+
|
213 |
+
if process_mgr is None:
|
214 |
+
process_mgr = ProcessMgr(None)
|
215 |
+
|
216 |
+
# if len(roop.globals.INPUT_FACESETS) <= selected_index:
|
217 |
+
# selected_index = 0
|
218 |
+
process_mgr.initialize(roop.globals.INPUT_FACESETS, roop.globals.TARGET_FACES, options)
|
219 |
+
newframe = process_mgr.process_frame(frame)
|
220 |
+
if newframe is None:
|
221 |
+
return frame
|
222 |
+
return newframe
|
223 |
+
|
224 |
+
|
225 |
+
def batch_process_regular(swap_model, output_method, files:list[ProcessEntry], masking_engine:str, new_clip_text:str, use_new_method, imagemask, restore_original_mouth, num_swap_steps, progress, selected_index = 0) -> None:
|
226 |
+
global clip_text, process_mgr
|
227 |
+
|
228 |
+
release_resources()
|
229 |
+
limit_resources()
|
230 |
+
if process_mgr is None:
|
231 |
+
process_mgr = ProcessMgr(progress)
|
232 |
+
mask = imagemask["layers"][0] if imagemask is not None else None
|
233 |
+
if len(roop.globals.INPUT_FACESETS) <= selected_index:
|
234 |
+
selected_index = 0
|
235 |
+
options = ProcessOptions(swap_model, get_processing_plugins(masking_engine), roop.globals.distance_threshold, roop.globals.blend_ratio,
|
236 |
+
roop.globals.face_swap_mode, selected_index, new_clip_text, mask, num_swap_steps,
|
237 |
+
roop.globals.subsample_size, False, restore_original_mouth)
|
238 |
+
process_mgr.initialize(roop.globals.INPUT_FACESETS, roop.globals.TARGET_FACES, options)
|
239 |
+
batch_process(output_method, files, use_new_method)
|
240 |
+
return
|
241 |
+
|
242 |
+
def batch_process_with_options(files:list[ProcessEntry], options, progress):
|
243 |
+
global clip_text, process_mgr
|
244 |
+
|
245 |
+
release_resources()
|
246 |
+
limit_resources()
|
247 |
+
if process_mgr is None:
|
248 |
+
process_mgr = ProcessMgr(progress)
|
249 |
+
process_mgr.initialize(roop.globals.INPUT_FACESETS, roop.globals.TARGET_FACES, options)
|
250 |
+
roop.globals.keep_frames = False
|
251 |
+
roop.globals.wait_after_extraction = False
|
252 |
+
roop.globals.skip_audio = False
|
253 |
+
batch_process("Files", files, True)
|
254 |
+
|
255 |
+
|
256 |
+
|
257 |
+
def batch_process(output_method, files:list[ProcessEntry], use_new_method) -> None:
|
258 |
+
global clip_text, process_mgr
|
259 |
+
|
260 |
+
roop.globals.processing = True
|
261 |
+
|
262 |
+
# limit threads for some providers
|
263 |
+
max_threads = suggest_execution_threads()
|
264 |
+
if max_threads == 1:
|
265 |
+
roop.globals.execution_threads = 1
|
266 |
+
|
267 |
+
imagefiles:list[ProcessEntry] = []
|
268 |
+
videofiles:list[ProcessEntry] = []
|
269 |
+
|
270 |
+
update_status('Sorting videos/images')
|
271 |
+
|
272 |
+
|
273 |
+
for index, f in enumerate(files):
|
274 |
+
fullname = f.filename
|
275 |
+
if util.has_image_extension(fullname):
|
276 |
+
destination = util.get_destfilename_from_path(fullname, roop.globals.output_path, f'.{roop.globals.CFG.output_image_format}')
|
277 |
+
destination = util.replace_template(destination, index=index)
|
278 |
+
pathlib.Path(os.path.dirname(destination)).mkdir(parents=True, exist_ok=True)
|
279 |
+
f.finalname = destination
|
280 |
+
imagefiles.append(f)
|
281 |
+
|
282 |
+
elif util.is_video(fullname) or util.has_extension(fullname, ['gif']):
|
283 |
+
destination = util.get_destfilename_from_path(fullname, roop.globals.output_path, f'__temp.{roop.globals.CFG.output_video_format}')
|
284 |
+
f.finalname = destination
|
285 |
+
videofiles.append(f)
|
286 |
+
|
287 |
+
|
288 |
+
|
289 |
+
if(len(imagefiles) > 0):
|
290 |
+
update_status('Processing image(s)')
|
291 |
+
origimages = []
|
292 |
+
fakeimages = []
|
293 |
+
for f in imagefiles:
|
294 |
+
origimages.append(f.filename)
|
295 |
+
fakeimages.append(f.finalname)
|
296 |
+
|
297 |
+
process_mgr.run_batch(origimages, fakeimages, roop.globals.execution_threads)
|
298 |
+
origimages.clear()
|
299 |
+
fakeimages.clear()
|
300 |
+
|
301 |
+
if(len(videofiles) > 0):
|
302 |
+
for index,v in enumerate(videofiles):
|
303 |
+
if not roop.globals.processing:
|
304 |
+
end_processing('Processing stopped!')
|
305 |
+
return
|
306 |
+
fps = v.fps if v.fps > 0 else util.detect_fps(v.filename)
|
307 |
+
if v.endframe == 0:
|
308 |
+
v.endframe = get_video_frame_total(v.filename)
|
309 |
+
|
310 |
+
is_streaming_only = output_method == "Virtual Camera"
|
311 |
+
if is_streaming_only == False:
|
312 |
+
update_status(f'Creating {os.path.basename(v.finalname)} with {fps} FPS...')
|
313 |
+
|
314 |
+
start_processing = time()
|
315 |
+
if is_streaming_only == False and roop.globals.keep_frames or not use_new_method:
|
316 |
+
util.create_temp(v.filename)
|
317 |
+
update_status('Extracting frames...')
|
318 |
+
ffmpeg.extract_frames(v.filename,v.startframe,v.endframe, fps)
|
319 |
+
if not roop.globals.processing:
|
320 |
+
end_processing('Processing stopped!')
|
321 |
+
return
|
322 |
+
|
323 |
+
temp_frame_paths = util.get_temp_frame_paths(v.filename)
|
324 |
+
process_mgr.run_batch(temp_frame_paths, temp_frame_paths, roop.globals.execution_threads)
|
325 |
+
if not roop.globals.processing:
|
326 |
+
end_processing('Processing stopped!')
|
327 |
+
return
|
328 |
+
if roop.globals.wait_after_extraction:
|
329 |
+
extract_path = os.path.dirname(temp_frame_paths[0])
|
330 |
+
util.open_folder(extract_path)
|
331 |
+
input("Press any key to continue...")
|
332 |
+
print("Resorting frames to create video")
|
333 |
+
util.sort_rename_frames(extract_path)
|
334 |
+
|
335 |
+
ffmpeg.create_video(v.filename, v.finalname, fps)
|
336 |
+
if not roop.globals.keep_frames:
|
337 |
+
util.delete_temp_frames(temp_frame_paths[0])
|
338 |
+
else:
|
339 |
+
if util.has_extension(v.filename, ['gif']):
|
340 |
+
skip_audio = True
|
341 |
+
else:
|
342 |
+
skip_audio = roop.globals.skip_audio
|
343 |
+
process_mgr.run_batch_inmem(output_method, v.filename, v.finalname, v.startframe, v.endframe, fps,roop.globals.execution_threads)
|
344 |
+
|
345 |
+
if not roop.globals.processing:
|
346 |
+
end_processing('Processing stopped!')
|
347 |
+
return
|
348 |
+
|
349 |
+
video_file_name = v.finalname
|
350 |
+
if os.path.isfile(video_file_name):
|
351 |
+
destination = ''
|
352 |
+
if util.has_extension(v.filename, ['gif']):
|
353 |
+
gifname = util.get_destfilename_from_path(v.filename, roop.globals.output_path, '.gif')
|
354 |
+
destination = util.replace_template(gifname, index=index)
|
355 |
+
pathlib.Path(os.path.dirname(destination)).mkdir(parents=True, exist_ok=True)
|
356 |
+
|
357 |
+
update_status('Creating final GIF')
|
358 |
+
ffmpeg.create_gif_from_video(video_file_name, destination)
|
359 |
+
if os.path.isfile(destination):
|
360 |
+
os.remove(video_file_name)
|
361 |
+
else:
|
362 |
+
skip_audio = roop.globals.skip_audio
|
363 |
+
destination = util.replace_template(video_file_name, index=index)
|
364 |
+
pathlib.Path(os.path.dirname(destination)).mkdir(parents=True, exist_ok=True)
|
365 |
+
|
366 |
+
if not skip_audio:
|
367 |
+
ffmpeg.restore_audio(video_file_name, v.filename, v.startframe, v.endframe, destination)
|
368 |
+
if os.path.isfile(destination):
|
369 |
+
os.remove(video_file_name)
|
370 |
+
else:
|
371 |
+
shutil.move(video_file_name, destination)
|
372 |
+
|
373 |
+
elif is_streaming_only == False:
|
374 |
+
update_status(f'Failed processing {os.path.basename(v.finalname)}!')
|
375 |
+
elapsed_time = time() - start_processing
|
376 |
+
average_fps = (v.endframe - v.startframe) / elapsed_time
|
377 |
+
update_status(f'\nProcessing {os.path.basename(destination)} took {elapsed_time:.2f} secs, {average_fps:.2f} frames/s')
|
378 |
+
end_processing('Finished')
|
379 |
+
|
380 |
+
|
381 |
+
def end_processing(msg:str):
|
382 |
+
update_status(msg)
|
383 |
+
roop.globals.target_folder_path = None
|
384 |
+
release_resources()
|
385 |
+
|
386 |
+
|
387 |
+
def destroy() -> None:
|
388 |
+
if roop.globals.target_path:
|
389 |
+
util.clean_temp(roop.globals.target_path)
|
390 |
+
release_resources()
|
391 |
+
sys.exit()
|
392 |
+
|
393 |
+
|
394 |
+
def run() -> None:
|
395 |
+
parse_args()
|
396 |
+
if not pre_check():
|
397 |
+
return
|
398 |
+
roop.globals.CFG = Settings('config.yaml')
|
399 |
+
roop.globals.cuda_device_id = roop.globals.startup_args.cuda_device_id
|
400 |
+
roop.globals.execution_threads = roop.globals.CFG.max_threads
|
401 |
+
roop.globals.video_encoder = roop.globals.CFG.output_video_codec
|
402 |
+
roop.globals.video_quality = roop.globals.CFG.video_quality
|
403 |
+
roop.globals.max_memory = roop.globals.CFG.memory_limit if roop.globals.CFG.memory_limit > 0 else None
|
404 |
+
if roop.globals.startup_args.server_share:
|
405 |
+
roop.globals.CFG.server_share = True
|
406 |
+
main.run()
|
roop/face_util.py
ADDED
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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_thread_semaphore
|
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 conditional_thread_semaphore():
|
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):
|
214 |
+
assert lmk.shape == (5, 2)
|
215 |
+
if image_size % 112 == 0:
|
216 |
+
ratio = float(image_size) / 112.0
|
217 |
+
diff_x = 0
|
218 |
+
elif image_size % 128 == 0:
|
219 |
+
ratio = float(image_size) / 128.0
|
220 |
+
diff_x = 8.0 * ratio
|
221 |
+
elif image_size % 512 == 0:
|
222 |
+
ratio = float(image_size) / 512.0
|
223 |
+
diff_x = 32.0 * ratio
|
224 |
+
|
225 |
+
dst = arcface_dst * ratio
|
226 |
+
dst[:, 0] += diff_x
|
227 |
+
tform = trans.SimilarityTransform()
|
228 |
+
tform.estimate(lmk, dst)
|
229 |
+
M = tform.params[0:2, :]
|
230 |
+
return M
|
231 |
+
"""
|
232 |
+
|
233 |
+
def estimate_norm(lmk, image_size=112):
|
234 |
+
if image_size%112==0:
|
235 |
+
ratio = float(image_size)/112.0
|
236 |
+
diff_x = 0
|
237 |
+
else:
|
238 |
+
ratio = float(image_size)/128.0
|
239 |
+
diff_x = 8.0*ratio
|
240 |
+
dst = arcface_dst * ratio
|
241 |
+
dst[:,0] += diff_x
|
242 |
+
|
243 |
+
if image_size == 160:
|
244 |
+
dst[:,0] += 0.1
|
245 |
+
dst[:,1] += 0.1
|
246 |
+
elif image_size == 256:
|
247 |
+
dst[:,0] += 0.5
|
248 |
+
dst[:,1] += 0.5
|
249 |
+
elif image_size == 320:
|
250 |
+
dst[:,0] += 0.75
|
251 |
+
dst[:,1] += 0.75
|
252 |
+
elif image_size == 512:
|
253 |
+
dst[:,0] += 1.5
|
254 |
+
dst[:,1] += 1.5
|
255 |
+
|
256 |
+
tform = trans.SimilarityTransform()
|
257 |
+
tform.estimate(lmk, dst)
|
258 |
+
M = tform.params[0:2, :]
|
259 |
+
return M
|
260 |
+
|
261 |
+
|
262 |
+
|
263 |
+
# aligned, M = norm_crop2(f[1], face.kps, 512)
|
264 |
+
def align_crop(img, landmark, image_size=112, mode="arcface"):
|
265 |
+
M = estimate_norm(landmark, image_size)
|
266 |
+
warped = cv2.warpAffine(img, M, (image_size, image_size), borderValue=0.0)
|
267 |
+
return warped, M
|
268 |
+
|
269 |
+
|
270 |
+
def square_crop(im, S):
|
271 |
+
if im.shape[0] > im.shape[1]:
|
272 |
+
height = S
|
273 |
+
width = int(float(im.shape[1]) / im.shape[0] * S)
|
274 |
+
scale = float(S) / im.shape[0]
|
275 |
+
else:
|
276 |
+
width = S
|
277 |
+
height = int(float(im.shape[0]) / im.shape[1] * S)
|
278 |
+
scale = float(S) / im.shape[1]
|
279 |
+
resized_im = cv2.resize(im, (width, height))
|
280 |
+
det_im = np.zeros((S, S, 3), dtype=np.uint8)
|
281 |
+
det_im[: resized_im.shape[0], : resized_im.shape[1], :] = resized_im
|
282 |
+
return det_im, scale
|
283 |
+
|
284 |
+
|
285 |
+
def transform(data, center, output_size, scale, rotation):
|
286 |
+
scale_ratio = scale
|
287 |
+
rot = float(rotation) * np.pi / 180.0
|
288 |
+
# translation = (output_size/2-center[0]*scale_ratio, output_size/2-center[1]*scale_ratio)
|
289 |
+
t1 = trans.SimilarityTransform(scale=scale_ratio)
|
290 |
+
cx = center[0] * scale_ratio
|
291 |
+
cy = center[1] * scale_ratio
|
292 |
+
t2 = trans.SimilarityTransform(translation=(-1 * cx, -1 * cy))
|
293 |
+
t3 = trans.SimilarityTransform(rotation=rot)
|
294 |
+
t4 = trans.SimilarityTransform(translation=(output_size / 2, output_size / 2))
|
295 |
+
t = t1 + t2 + t3 + t4
|
296 |
+
M = t.params[0:2]
|
297 |
+
cropped = cv2.warpAffine(data, M, (output_size, output_size), borderValue=0.0)
|
298 |
+
return cropped, M
|
299 |
+
|
300 |
+
|
301 |
+
def trans_points2d(pts, M):
|
302 |
+
new_pts = np.zeros(shape=pts.shape, dtype=np.float32)
|
303 |
+
for i in range(pts.shape[0]):
|
304 |
+
pt = pts[i]
|
305 |
+
new_pt = np.array([pt[0], pt[1], 1.0], dtype=np.float32)
|
306 |
+
new_pt = np.dot(M, new_pt)
|
307 |
+
# print('new_pt', new_pt.shape, new_pt)
|
308 |
+
new_pts[i] = new_pt[0:2]
|
309 |
+
|
310 |
+
return new_pts
|
311 |
+
|
312 |
+
|
313 |
+
def trans_points3d(pts, M):
|
314 |
+
scale = np.sqrt(M[0][0] * M[0][0] + M[0][1] * M[0][1])
|
315 |
+
# print(scale)
|
316 |
+
new_pts = np.zeros(shape=pts.shape, dtype=np.float32)
|
317 |
+
for i in range(pts.shape[0]):
|
318 |
+
pt = pts[i]
|
319 |
+
new_pt = np.array([pt[0], pt[1], 1.0], dtype=np.float32)
|
320 |
+
new_pt = np.dot(M, new_pt)
|
321 |
+
# print('new_pt', new_pt.shape, new_pt)
|
322 |
+
new_pts[i][0:2] = new_pt[0:2]
|
323 |
+
new_pts[i][2] = pts[i][2] * scale
|
324 |
+
|
325 |
+
return new_pts
|
326 |
+
|
327 |
+
|
328 |
+
def trans_points(pts, M):
|
329 |
+
if pts.shape[1] == 2:
|
330 |
+
return trans_points2d(pts, M)
|
331 |
+
else:
|
332 |
+
return trans_points3d(pts, M)
|
333 |
+
|
334 |
+
def create_blank_image(width, height):
|
335 |
+
img = np.zeros((height, width, 4), dtype=np.uint8)
|
336 |
+
img[:] = [0,0,0,0]
|
337 |
+
return img
|
338 |
+
|
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/globals.py
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
startup_args = None
|
9 |
+
|
10 |
+
cuda_device_id = 0
|
11 |
+
frame_processors: List[str] = []
|
12 |
+
keep_fps = None
|
13 |
+
keep_frames = None
|
14 |
+
autorotate_faces = None
|
15 |
+
vr_mode = None
|
16 |
+
skip_audio = None
|
17 |
+
wait_after_extraction = None
|
18 |
+
many_faces = None
|
19 |
+
use_batch = None
|
20 |
+
source_face_index = 0
|
21 |
+
target_face_index = 0
|
22 |
+
face_position = None
|
23 |
+
video_encoder = None
|
24 |
+
video_quality = None
|
25 |
+
max_memory = None
|
26 |
+
execution_providers: List[str] = []
|
27 |
+
execution_threads = None
|
28 |
+
headless = None
|
29 |
+
log_level = 'error'
|
30 |
+
selected_enhancer = None
|
31 |
+
subsample_size = 128
|
32 |
+
face_swap_mode = None
|
33 |
+
blend_ratio = 0.5
|
34 |
+
distance_threshold = 0.65
|
35 |
+
default_det_size = True
|
36 |
+
|
37 |
+
no_face_action = 0
|
38 |
+
|
39 |
+
processing = False
|
40 |
+
|
41 |
+
g_current_face_analysis = None
|
42 |
+
g_desired_face_analysis = None
|
43 |
+
|
44 |
+
FACE_ENHANCER = None
|
45 |
+
|
46 |
+
INPUT_FACESETS = []
|
47 |
+
TARGET_FACES = []
|
48 |
+
|
49 |
+
|
50 |
+
IMAGE_CHAIN_PROCESSOR = None
|
51 |
+
VIDEO_CHAIN_PROCESSOR = None
|
52 |
+
BATCH_IMAGE_CHAIN_PROCESSOR = None
|
53 |
+
|
54 |
+
CFG: Settings = None
|
55 |
+
|
56 |
+
|
roop/metadata.py
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
name = 'roop unleashed'
|
2 |
+
version = '4.4.1'
|
roop/processors/__pycache__/Enhance_CodeFormer.cpython-310.pyc
ADDED
Binary file (2.48 kB). View file
|
|
roop/processors/__pycache__/Enhance_GFPGAN.cpython-310.pyc
ADDED
Binary file (2.21 kB). View file
|
|
roop/processors/__pycache__/Enhance_GPEN.cpython-310.pyc
ADDED
Binary file (2.2 kB). View file
|
|
roop/processors/__pycache__/Enhance_RestoreFormerPPlus.cpython-310.pyc
ADDED
Binary file (2.4 kB). View file
|
|
roop/processors/__pycache__/FaceSwapInsightFace.cpython-310.pyc
ADDED
Binary file (2.07 kB). View file
|
|
roop/processors/__pycache__/Frame_Masking.cpython-310.pyc
ADDED
Binary file (2.32 kB). View file
|
|
roop/processors/__pycache__/Mask_Clip2Seg.cpython-310.pyc
ADDED
Binary file (2.76 kB). View file
|
|
roop/processors/__pycache__/Mask_XSeg.cpython-310.pyc
ADDED
Binary file (1.93 kB). View file
|
|
roop/processors/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (164 Bytes). View file
|
|
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,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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, release_video
|
77 |
+
|
78 |
+
fps = util.detect_fps(video_path)
|
79 |
+
frame = get_video_frame(video_path)
|
80 |
+
release_video()
|
81 |
+
|
82 |
+
scalex = frame.shape[0]
|
83 |
+
scaley = frame.shape[1]
|
84 |
+
|
85 |
+
if scalex >= scaley:
|
86 |
+
scaley = -1
|
87 |
+
else:
|
88 |
+
scalex = -1
|
89 |
+
|
90 |
+
run_ffmpeg(['-i', video_path, '-vf', f'fps={fps},scale={int(scalex)}:{int(scaley)}:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse', '-loop', '0', gif_path])
|
91 |
+
|
92 |
+
|
93 |
+
|
94 |
+
def create_video_from_gif(gif_path: str, output_path):
|
95 |
+
fps = util.detect_fps(gif_path)
|
96 |
+
filter = """scale='trunc(in_w/2)*2':'trunc(in_h/2)*2',format=yuv420p,fps=10"""
|
97 |
+
run_ffmpeg(['-i', gif_path, '-vf', f'"{filter}"', '-movflags', '+faststart', '-shortest', output_path])
|
98 |
+
|
99 |
+
|
100 |
+
def repair_video(original_video: str, final_video : str):
|
101 |
+
run_ffmpeg(['-i', original_video, '-movflags', 'faststart', '-acodec', 'copy', '-vcodec', 'copy', final_video])
|
102 |
+
|
103 |
+
|
104 |
+
def restore_audio(intermediate_video: str, original_video: str, trim_frame_start, trim_frame_end, final_video : str) -> None:
|
105 |
+
fps = util.detect_fps(original_video)
|
106 |
+
commands = [ '-i', intermediate_video ]
|
107 |
+
if trim_frame_start is None and trim_frame_end is None:
|
108 |
+
commands.extend([ '-c:a', 'copy' ])
|
109 |
+
else:
|
110 |
+
# if trim_frame_start is not None:
|
111 |
+
# start_time = trim_frame_start / fps
|
112 |
+
# commands.extend([ '-ss', format(start_time, ".2f")])
|
113 |
+
# else:
|
114 |
+
# commands.extend([ '-ss', '0' ])
|
115 |
+
# if trim_frame_end is not None:
|
116 |
+
# end_time = trim_frame_end / fps
|
117 |
+
# commands.extend([ '-to', format(end_time, ".2f")])
|
118 |
+
# commands.extend([ '-c:a', 'aac' ])
|
119 |
+
if trim_frame_start is not None:
|
120 |
+
start_time = trim_frame_start / fps
|
121 |
+
commands.extend([ '-ss', format(start_time, ".2f")])
|
122 |
+
else:
|
123 |
+
commands.extend([ '-ss', '0' ])
|
124 |
+
if trim_frame_end is not None:
|
125 |
+
end_time = trim_frame_end / fps
|
126 |
+
commands.extend([ '-to', format(end_time, ".2f")])
|
127 |
+
commands.extend([ '-i', original_video, "-c", "copy" ])
|
128 |
+
|
129 |
+
commands.extend([ '-map', '0:v:0', '-map', '1:a:0?', '-shortest', final_video ])
|
130 |
+
run_ffmpeg(commands)
|
roop/utilities.py
ADDED
@@ -0,0 +1,393 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
import threading
|
17 |
+
import threading
|
18 |
+
import random
|
19 |
+
|
20 |
+
from typing import Union, Any
|
21 |
+
from contextlib import nullcontext
|
22 |
+
|
23 |
+
from pathlib import Path
|
24 |
+
from typing import List, Any
|
25 |
+
from tqdm import tqdm
|
26 |
+
from scipy.spatial import distance
|
27 |
+
|
28 |
+
import roop.template_parser as template_parser
|
29 |
+
|
30 |
+
import roop.globals
|
31 |
+
|
32 |
+
TEMP_FILE = "temp.mp4"
|
33 |
+
TEMP_DIRECTORY = "temp"
|
34 |
+
|
35 |
+
THREAD_SEMAPHORE = threading.Semaphore()
|
36 |
+
NULL_CONTEXT = nullcontext()
|
37 |
+
|
38 |
+
|
39 |
+
# monkey patch ssl for mac
|
40 |
+
if platform.system().lower() == "darwin":
|
41 |
+
ssl._create_default_https_context = ssl._create_unverified_context
|
42 |
+
|
43 |
+
|
44 |
+
# https://github.com/facefusion/facefusion/blob/master/facefusion
|
45 |
+
def detect_fps(target_path: str) -> float:
|
46 |
+
fps = 24.0
|
47 |
+
cap = cv2.VideoCapture(target_path)
|
48 |
+
if cap.isOpened():
|
49 |
+
fps = cap.get(cv2.CAP_PROP_FPS)
|
50 |
+
cap.release()
|
51 |
+
return fps
|
52 |
+
|
53 |
+
|
54 |
+
# Gradio wants Images in RGB
|
55 |
+
def convert_to_gradio(image):
|
56 |
+
if image is None:
|
57 |
+
return None
|
58 |
+
return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
59 |
+
|
60 |
+
|
61 |
+
def sort_filenames_ignore_path(filenames):
|
62 |
+
"""Sorts a list of filenames containing a complete path by their filename,
|
63 |
+
while retaining their original path.
|
64 |
+
|
65 |
+
Args:
|
66 |
+
filenames: A list of filenames containing a complete path.
|
67 |
+
|
68 |
+
Returns:
|
69 |
+
A sorted list of filenames containing a complete path.
|
70 |
+
"""
|
71 |
+
filename_path_tuples = [
|
72 |
+
(os.path.split(filename)[1], filename) for filename in filenames
|
73 |
+
]
|
74 |
+
sorted_filename_path_tuples = sorted(filename_path_tuples, key=lambda x: x[0])
|
75 |
+
return [
|
76 |
+
filename_path_tuple[1] for filename_path_tuple in sorted_filename_path_tuples
|
77 |
+
]
|
78 |
+
|
79 |
+
|
80 |
+
def sort_rename_frames(path: str):
|
81 |
+
filenames = os.listdir(path)
|
82 |
+
filenames.sort()
|
83 |
+
for i in range(len(filenames)):
|
84 |
+
of = os.path.join(path, filenames[i])
|
85 |
+
newidx = i + 1
|
86 |
+
new_filename = os.path.join(
|
87 |
+
path, f"{newidx:06d}." + roop.globals.CFG.output_image_format
|
88 |
+
)
|
89 |
+
os.rename(of, new_filename)
|
90 |
+
|
91 |
+
|
92 |
+
def get_temp_frame_paths(target_path: str) -> List[str]:
|
93 |
+
temp_directory_path = get_temp_directory_path(target_path)
|
94 |
+
return glob.glob(
|
95 |
+
(
|
96 |
+
os.path.join(
|
97 |
+
glob.escape(temp_directory_path),
|
98 |
+
f"*.{roop.globals.CFG.output_image_format}",
|
99 |
+
)
|
100 |
+
)
|
101 |
+
)
|
102 |
+
|
103 |
+
|
104 |
+
def get_temp_directory_path(target_path: str) -> str:
|
105 |
+
target_name, _ = os.path.splitext(os.path.basename(target_path))
|
106 |
+
target_directory_path = os.path.dirname(target_path)
|
107 |
+
return os.path.join(target_directory_path, TEMP_DIRECTORY, target_name)
|
108 |
+
|
109 |
+
|
110 |
+
def get_temp_output_path(target_path: str) -> str:
|
111 |
+
temp_directory_path = get_temp_directory_path(target_path)
|
112 |
+
return os.path.join(temp_directory_path, TEMP_FILE)
|
113 |
+
|
114 |
+
|
115 |
+
def normalize_output_path(source_path: str, target_path: str, output_path: str) -> Any:
|
116 |
+
if source_path and target_path:
|
117 |
+
source_name, _ = os.path.splitext(os.path.basename(source_path))
|
118 |
+
target_name, target_extension = os.path.splitext(os.path.basename(target_path))
|
119 |
+
if os.path.isdir(output_path):
|
120 |
+
return os.path.join(
|
121 |
+
output_path, source_name + "-" + target_name + target_extension
|
122 |
+
)
|
123 |
+
return output_path
|
124 |
+
|
125 |
+
|
126 |
+
def get_destfilename_from_path(
|
127 |
+
srcfilepath: str, destfilepath: str, extension: str
|
128 |
+
) -> str:
|
129 |
+
fn, ext = os.path.splitext(os.path.basename(srcfilepath))
|
130 |
+
if "." in extension:
|
131 |
+
return os.path.join(destfilepath, f"{fn}{extension}")
|
132 |
+
return os.path.join(destfilepath, f"{fn}{extension}{ext}")
|
133 |
+
|
134 |
+
|
135 |
+
def replace_template(file_path: str, index: int = 0) -> str:
|
136 |
+
fn, ext = os.path.splitext(os.path.basename(file_path))
|
137 |
+
|
138 |
+
# Remove the "__temp" placeholder that was used as a temporary filename
|
139 |
+
fn = fn.replace("__temp", "")
|
140 |
+
|
141 |
+
template = roop.globals.CFG.output_template
|
142 |
+
replaced_filename = template_parser.parse(
|
143 |
+
template, {"index": str(index), "file": fn}
|
144 |
+
)
|
145 |
+
|
146 |
+
return os.path.join(roop.globals.output_path, f"{replaced_filename}{ext}")
|
147 |
+
|
148 |
+
|
149 |
+
def create_temp(target_path: str) -> None:
|
150 |
+
temp_directory_path = get_temp_directory_path(target_path)
|
151 |
+
Path(temp_directory_path).mkdir(parents=True, exist_ok=True)
|
152 |
+
|
153 |
+
|
154 |
+
def move_temp(target_path: str, output_path: str) -> None:
|
155 |
+
temp_output_path = get_temp_output_path(target_path)
|
156 |
+
if os.path.isfile(temp_output_path):
|
157 |
+
if os.path.isfile(output_path):
|
158 |
+
os.remove(output_path)
|
159 |
+
shutil.move(temp_output_path, output_path)
|
160 |
+
|
161 |
+
|
162 |
+
def clean_temp(target_path: str) -> None:
|
163 |
+
temp_directory_path = get_temp_directory_path(target_path)
|
164 |
+
parent_directory_path = os.path.dirname(temp_directory_path)
|
165 |
+
if not roop.globals.keep_frames and os.path.isdir(temp_directory_path):
|
166 |
+
shutil.rmtree(temp_directory_path)
|
167 |
+
if os.path.exists(parent_directory_path) and not os.listdir(parent_directory_path):
|
168 |
+
os.rmdir(parent_directory_path)
|
169 |
+
|
170 |
+
|
171 |
+
def delete_temp_frames(filename: str) -> None:
|
172 |
+
dir = os.path.dirname(os.path.dirname(filename))
|
173 |
+
shutil.rmtree(dir)
|
174 |
+
|
175 |
+
|
176 |
+
def has_image_extension(image_path: str) -> bool:
|
177 |
+
return image_path.lower().endswith(("png", "jpg", "jpeg", "webp"))
|
178 |
+
|
179 |
+
|
180 |
+
def has_extension(filepath: str, extensions: List[str]) -> bool:
|
181 |
+
return filepath.lower().endswith(tuple(extensions))
|
182 |
+
|
183 |
+
|
184 |
+
def is_image(image_path: str) -> bool:
|
185 |
+
if image_path and os.path.isfile(image_path):
|
186 |
+
if image_path.endswith(".webp"):
|
187 |
+
return True
|
188 |
+
mimetype, _ = mimetypes.guess_type(image_path)
|
189 |
+
return bool(mimetype and mimetype.startswith("image/"))
|
190 |
+
return False
|
191 |
+
|
192 |
+
|
193 |
+
def is_video(video_path: str) -> bool:
|
194 |
+
if video_path and os.path.isfile(video_path):
|
195 |
+
mimetype, _ = mimetypes.guess_type(video_path)
|
196 |
+
return bool(mimetype and mimetype.startswith("video/"))
|
197 |
+
return False
|
198 |
+
|
199 |
+
|
200 |
+
def conditional_download(download_directory_path: str, urls: List[str]) -> None:
|
201 |
+
if not os.path.exists(download_directory_path):
|
202 |
+
os.makedirs(download_directory_path)
|
203 |
+
for url in urls:
|
204 |
+
download_file_path = os.path.join(
|
205 |
+
download_directory_path, os.path.basename(url)
|
206 |
+
)
|
207 |
+
if not os.path.exists(download_file_path):
|
208 |
+
request = urllib.request.urlopen(url) # type: ignore[attr-defined]
|
209 |
+
total = int(request.headers.get("Content-Length", 0))
|
210 |
+
with tqdm(
|
211 |
+
total=total,
|
212 |
+
desc=f"Downloading {url}",
|
213 |
+
unit="B",
|
214 |
+
unit_scale=True,
|
215 |
+
unit_divisor=1024,
|
216 |
+
) as progress:
|
217 |
+
urllib.request.urlretrieve(url, download_file_path, reporthook=lambda count, block_size, total_size: progress.update(block_size)) # type: ignore[attr-defined]
|
218 |
+
|
219 |
+
|
220 |
+
def get_local_files_from_folder(folder: str) -> List[str]:
|
221 |
+
if not os.path.exists(folder) or not os.path.isdir(folder):
|
222 |
+
return None
|
223 |
+
files = [
|
224 |
+
os.path.join(folder, f)
|
225 |
+
for f in os.listdir(folder)
|
226 |
+
if os.path.isfile(os.path.join(folder, f))
|
227 |
+
]
|
228 |
+
return files
|
229 |
+
|
230 |
+
|
231 |
+
def resolve_relative_path(path: str) -> str:
|
232 |
+
return os.path.abspath(os.path.join(os.path.dirname(__file__), path))
|
233 |
+
|
234 |
+
|
235 |
+
def get_device() -> str:
|
236 |
+
if len(roop.globals.execution_providers) < 1:
|
237 |
+
roop.globals.execution_providers = ["CPUExecutionProvider"]
|
238 |
+
|
239 |
+
prov = roop.globals.execution_providers[0]
|
240 |
+
if "CoreMLExecutionProvider" in prov:
|
241 |
+
return "mps"
|
242 |
+
if "CUDAExecutionProvider" in prov or "ROCMExecutionProvider" in prov:
|
243 |
+
return "cuda"
|
244 |
+
if "OpenVINOExecutionProvider" in prov:
|
245 |
+
return "mkl"
|
246 |
+
return "cpu"
|
247 |
+
|
248 |
+
|
249 |
+
def str_to_class(module_name, class_name) -> Any:
|
250 |
+
from importlib import import_module
|
251 |
+
|
252 |
+
class_ = None
|
253 |
+
try:
|
254 |
+
module_ = import_module(module_name)
|
255 |
+
try:
|
256 |
+
class_ = getattr(module_, class_name)()
|
257 |
+
except AttributeError:
|
258 |
+
print(f"Class {class_name} does not exist")
|
259 |
+
except ImportError:
|
260 |
+
print(f"Module {module_name} does not exist")
|
261 |
+
return class_
|
262 |
+
|
263 |
+
def is_installed(name:str) -> bool:
|
264 |
+
return shutil.which(name);
|
265 |
+
|
266 |
+
# Taken from https://stackoverflow.com/a/68842705
|
267 |
+
def get_platform() -> str:
|
268 |
+
if sys.platform == "linux":
|
269 |
+
try:
|
270 |
+
proc_version = open("/proc/version").read()
|
271 |
+
if "Microsoft" in proc_version:
|
272 |
+
return "wsl"
|
273 |
+
except:
|
274 |
+
pass
|
275 |
+
return sys.platform
|
276 |
+
|
277 |
+
def open_with_default_app(filename:str):
|
278 |
+
if filename == None:
|
279 |
+
return
|
280 |
+
platform = get_platform()
|
281 |
+
if platform == "darwin":
|
282 |
+
subprocess.call(("open", filename))
|
283 |
+
elif platform in ["win64", "win32"]: os.startfile(filename.replace("/", "\\"))
|
284 |
+
elif platform == "wsl":
|
285 |
+
subprocess.call("cmd.exe /C start".split() + [filename])
|
286 |
+
else: # linux variants
|
287 |
+
subprocess.call("xdg-open", filename)
|
288 |
+
|
289 |
+
|
290 |
+
def prepare_for_batch(target_files) -> str:
|
291 |
+
print("Preparing temp files")
|
292 |
+
tempfolder = os.path.join(tempfile.gettempdir(), "rooptmp")
|
293 |
+
if os.path.exists(tempfolder):
|
294 |
+
shutil.rmtree(tempfolder)
|
295 |
+
Path(tempfolder).mkdir(parents=True, exist_ok=True)
|
296 |
+
for f in target_files:
|
297 |
+
newname = os.path.basename(f.name)
|
298 |
+
shutil.move(f.name, os.path.join(tempfolder, newname))
|
299 |
+
return tempfolder
|
300 |
+
|
301 |
+
|
302 |
+
def zip(files, zipname):
|
303 |
+
with zipfile.ZipFile(zipname, "w") as zip_file:
|
304 |
+
for f in files:
|
305 |
+
zip_file.write(f, os.path.basename(f))
|
306 |
+
|
307 |
+
|
308 |
+
def unzip(zipfilename: str, target_path: str):
|
309 |
+
with zipfile.ZipFile(zipfilename, "r") as zip_file:
|
310 |
+
zip_file.extractall(target_path)
|
311 |
+
|
312 |
+
|
313 |
+
def mkdir_with_umask(directory):
|
314 |
+
oldmask = os.umask(0)
|
315 |
+
# mode needs octal
|
316 |
+
os.makedirs(directory, mode=0o775, exist_ok=True)
|
317 |
+
os.umask(oldmask)
|
318 |
+
|
319 |
+
|
320 |
+
def open_folder(path: str):
|
321 |
+
platform = get_platform()
|
322 |
+
try:
|
323 |
+
if platform == "darwin":
|
324 |
+
subprocess.call(("open", path))
|
325 |
+
elif platform in ["win64", "win32"]:
|
326 |
+
open_with_default_app(path)
|
327 |
+
elif platform == "wsl":
|
328 |
+
subprocess.call("cmd.exe /C start".split() + [path])
|
329 |
+
else: # linux variants
|
330 |
+
subprocess.Popen(["xdg-open", path])
|
331 |
+
except Exception as e:
|
332 |
+
traceback.print_exc()
|
333 |
+
pass
|
334 |
+
# import webbrowser
|
335 |
+
# webbrowser.open(url)
|
336 |
+
|
337 |
+
|
338 |
+
def create_version_html() -> str:
|
339 |
+
python_version = ".".join([str(x) for x in sys.version_info[0:3]])
|
340 |
+
versions_html = f"""
|
341 |
+
python: <span title="{sys.version}">{python_version}</span>
|
342 |
+
•
|
343 |
+
torch: {getattr(torch, '__long_version__',torch.__version__)}
|
344 |
+
•
|
345 |
+
gradio: {gradio.__version__}
|
346 |
+
"""
|
347 |
+
return versions_html
|
348 |
+
|
349 |
+
|
350 |
+
def compute_cosine_distance(emb1, emb2) -> float:
|
351 |
+
return distance.cosine(emb1, emb2)
|
352 |
+
|
353 |
+
def has_cuda_device():
|
354 |
+
return torch.cuda is not None and torch.cuda.is_available()
|
355 |
+
|
356 |
+
|
357 |
+
def print_cuda_info():
|
358 |
+
try:
|
359 |
+
print(f'Number of CUDA devices: {torch.cuda.device_count()} Currently used Id: {torch.cuda.current_device()} Device Name: {torch.cuda.get_device_name(torch.cuda.current_device())}')
|
360 |
+
except:
|
361 |
+
print('No CUDA device found!')
|
362 |
+
|
363 |
+
def clean_dir(path: str):
|
364 |
+
contents = os.listdir(path)
|
365 |
+
for item in contents:
|
366 |
+
item_path = os.path.join(path, item)
|
367 |
+
try:
|
368 |
+
if os.path.isfile(item_path):
|
369 |
+
os.remove(item_path)
|
370 |
+
elif os.path.isdir(item_path):
|
371 |
+
shutil.rmtree(item_path)
|
372 |
+
except Exception as e:
|
373 |
+
print(e)
|
374 |
+
|
375 |
+
|
376 |
+
def conditional_thread_semaphore() -> Union[Any, Any]:
|
377 |
+
if 'DmlExecutionProvider' in roop.globals.execution_providers or 'ROCMExecutionProvider' in roop.globals.execution_providers:
|
378 |
+
return THREAD_SEMAPHORE
|
379 |
+
return NULL_CONTEXT
|
380 |
+
|
381 |
+
def shuffle_array(arr):
|
382 |
+
"""
|
383 |
+
Shuffles the given array in place using the Fisher-Yates shuffle algorithm.
|
384 |
+
|
385 |
+
Args:
|
386 |
+
arr: The array to be shuffled.
|
387 |
+
|
388 |
+
Returns:
|
389 |
+
None. The array is shuffled in place.
|
390 |
+
"""
|
391 |
+
for i in range(len(arr) - 1, 0, -1):
|
392 |
+
j = random.randint(0, i)
|
393 |
+
arr[i], arr[j] = arr[j], arr[i]
|
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 platform
|
7 |
+
|
8 |
+
|
9 |
+
cam_active = False
|
10 |
+
cam_thread = None
|
11 |
+
vcam = None
|
12 |
+
|
13 |
+
def virtualcamera(swap_model, streamobs, use_xseg, use_mouthrestore, cam_num,width,height):
|
14 |
+
from roop.ProcessOptions import ProcessOptions
|
15 |
+
from roop.core import live_swap, get_processing_plugins
|
16 |
+
|
17 |
+
global cam_active
|
18 |
+
|
19 |
+
#time.sleep(2)
|
20 |
+
print('Starting capture')
|
21 |
+
cap = cv2.VideoCapture(cam_num, cv2.CAP_DSHOW if platform.system() != 'Darwin' else cv2.CAP_AVFOUNDATION)
|
22 |
+
if not cap.isOpened():
|
23 |
+
print("Cannot open camera")
|
24 |
+
cap.release()
|
25 |
+
del cap
|
26 |
+
return
|
27 |
+
|
28 |
+
pref_width = width
|
29 |
+
pref_height = height
|
30 |
+
pref_fps_in = 30
|
31 |
+
cap.set(cv2.CAP_PROP_FRAME_WIDTH, pref_width)
|
32 |
+
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, pref_height)
|
33 |
+
cap.set(cv2.CAP_PROP_FPS, pref_fps_in)
|
34 |
+
cam_active = True
|
35 |
+
|
36 |
+
# native format UYVY
|
37 |
+
|
38 |
+
cam = None
|
39 |
+
if streamobs:
|
40 |
+
print('Detecting virtual cam devices')
|
41 |
+
cam = pyvirtualcam.Camera(width=pref_width, height=pref_height, fps=pref_fps_in, fmt=pyvirtualcam.PixelFormat.BGR, print_fps=False)
|
42 |
+
if cam:
|
43 |
+
print(f'Using virtual camera: {cam.device}')
|
44 |
+
print(f'Using {cam.native_fmt}')
|
45 |
+
else:
|
46 |
+
print(f'Not streaming to virtual camera!')
|
47 |
+
subsample_size = roop.globals.subsample_size
|
48 |
+
|
49 |
+
|
50 |
+
options = ProcessOptions(swap_model, get_processing_plugins("mask_xseg" if use_xseg else None), roop.globals.distance_threshold, roop.globals.blend_ratio,
|
51 |
+
"all", 0, None, None, 1, subsample_size, False, use_mouthrestore)
|
52 |
+
while cam_active:
|
53 |
+
ret, frame = cap.read()
|
54 |
+
if not ret:
|
55 |
+
break
|
56 |
+
|
57 |
+
if len(roop.globals.INPUT_FACESETS) > 0:
|
58 |
+
frame = live_swap(frame, options)
|
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(swap_model, streamobs, use_xseg, use_mouthrestore, 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=[swap_model, streamobs, use_xseg, use_mouthrestore, 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
|