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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
|
3 |
+
import os
|
4 |
+
import sys
|
5 |
+
# single thread doubles performance of gpu-mode - needs to be set before torch import
|
6 |
+
if any(arg.startswith('--gpu-vendor=') for arg in sys.argv):
|
7 |
+
os.environ['OMP_NUM_THREADS'] = '1'
|
8 |
+
import platform
|
9 |
+
import signal
|
10 |
+
import shutil
|
11 |
+
import glob
|
12 |
+
import argparse
|
13 |
+
import psutil
|
14 |
+
import torch
|
15 |
+
import tensorflow
|
16 |
+
from pathlib import Path
|
17 |
+
import multiprocessing as mp
|
18 |
+
|
19 |
+
import cv2
|
20 |
+
|
21 |
+
import roop.globals
|
22 |
+
from roop.swapper import process_video, process_img, process_faces, process_frames
|
23 |
+
from roop.utils import is_img, detect_fps, set_fps, create_video, add_audio, extract_frames, rreplace
|
24 |
+
from roop.analyser import get_face_single
|
25 |
+
import roop.ui as ui
|
26 |
+
|
27 |
+
signal.signal(signal.SIGINT, lambda signal_number, frame: quit())
|
28 |
+
parser = argparse.ArgumentParser()
|
29 |
+
parser.add_argument('-f', '--face', help='use this face', dest='source_img')
|
30 |
+
parser.add_argument('-t', '--target', help='replace this face', dest='target_path')
|
31 |
+
parser.add_argument('-o', '--output', help='save output to this file', dest='output_file')
|
32 |
+
parser.add_argument('--keep-fps', help='maintain original fps', dest='keep_fps', action='store_true', default=False)
|
33 |
+
parser.add_argument('--keep-frames', help='keep frames directory', dest='keep_frames', action='store_true', default=False)
|
34 |
+
parser.add_argument('--all-faces', help='swap all faces in frame', dest='all_faces', action='store_true', default=False)
|
35 |
+
parser.add_argument('--max-memory', help='maximum amount of RAM in GB to be used', dest='max_memory', type=int)
|
36 |
+
parser.add_argument('--cpu-cores', help='number of CPU cores to use', dest='cpu_cores', type=int, default=max(psutil.cpu_count() / 2, 1))
|
37 |
+
parser.add_argument('--gpu-threads', help='number of threads to be use for the GPU', dest='gpu_threads', type=int, default=8)
|
38 |
+
parser.add_argument('--gpu-vendor', help='choice your GPU vendor', dest='gpu_vendor', choices=['apple', 'amd', 'intel', 'nvidia'])
|
39 |
+
|
40 |
+
args = parser.parse_known_args()[0]
|
41 |
+
|
42 |
+
if 'all_faces' in args:
|
43 |
+
roop.globals.all_faces = True
|
44 |
+
|
45 |
+
if args.cpu_cores:
|
46 |
+
roop.globals.cpu_cores = int(args.cpu_cores)
|
47 |
+
|
48 |
+
# cpu thread fix for mac
|
49 |
+
if sys.platform == 'darwin':
|
50 |
+
roop.globals.cpu_cores = 1
|
51 |
+
|
52 |
+
if args.gpu_threads:
|
53 |
+
roop.globals.gpu_threads = int(args.gpu_threads)
|
54 |
+
|
55 |
+
# gpu thread fix for amd
|
56 |
+
if args.gpu_vendor == 'amd':
|
57 |
+
roop.globals.gpu_threads = 1
|
58 |
+
|
59 |
+
if args.gpu_vendor:
|
60 |
+
roop.globals.gpu_vendor = args.gpu_vendor
|
61 |
+
else:
|
62 |
+
roop.globals.providers = ['CPUExecutionProvider']
|
63 |
+
|
64 |
+
sep = "/"
|
65 |
+
if os.name == "nt":
|
66 |
+
sep = "\\"
|
67 |
+
|
68 |
+
|
69 |
+
def limit_resources():
|
70 |
+
# prevent tensorflow memory leak
|
71 |
+
gpus = tensorflow.config.experimental.list_physical_devices('GPU')
|
72 |
+
for gpu in gpus:
|
73 |
+
tensorflow.config.experimental.set_memory_growth(gpu, True)
|
74 |
+
if args.max_memory:
|
75 |
+
memory = args.max_memory * 1024 * 1024 * 1024
|
76 |
+
if str(platform.system()).lower() == 'windows':
|
77 |
+
import ctypes
|
78 |
+
kernel32 = ctypes.windll.kernel32
|
79 |
+
kernel32.SetProcessWorkingSetSize(-1, ctypes.c_size_t(memory), ctypes.c_size_t(memory))
|
80 |
+
else:
|
81 |
+
import resource
|
82 |
+
resource.setrlimit(resource.RLIMIT_DATA, (memory, memory))
|
83 |
+
|
84 |
+
|
85 |
+
def pre_check():
|
86 |
+
if sys.version_info < (3, 9):
|
87 |
+
quit('Python version is not supported - please upgrade to 3.9 or higher')
|
88 |
+
if not shutil.which('ffmpeg'):
|
89 |
+
quit('ffmpeg is not installed!')
|
90 |
+
model_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), '../inswapper_128.onnx')
|
91 |
+
if not os.path.isfile(model_path):
|
92 |
+
quit('File "inswapper_128.onnx" does not exist!')
|
93 |
+
if roop.globals.gpu_vendor == 'apple':
|
94 |
+
if 'CoreMLExecutionProvider' not in roop.globals.providers:
|
95 |
+
quit("You are using --gpu=apple flag but CoreML isn't available or properly installed on your system.")
|
96 |
+
if roop.globals.gpu_vendor == 'amd':
|
97 |
+
if 'ROCMExecutionProvider' not in roop.globals.providers:
|
98 |
+
quit("You are using --gpu=amd flag but ROCM isn't available or properly installed on your system.")
|
99 |
+
if roop.globals.gpu_vendor == 'nvidia':
|
100 |
+
CUDA_VERSION = torch.version.cuda
|
101 |
+
CUDNN_VERSION = torch.backends.cudnn.version()
|
102 |
+
if not torch.cuda.is_available():
|
103 |
+
quit("You are using --gpu=nvidia flag but CUDA isn't available or properly installed on your system.")
|
104 |
+
if CUDA_VERSION > '11.8':
|
105 |
+
quit(f"CUDA version {CUDA_VERSION} is not supported - please downgrade to 11.8")
|
106 |
+
if CUDA_VERSION < '11.4':
|
107 |
+
quit(f"CUDA version {CUDA_VERSION} is not supported - please upgrade to 11.8")
|
108 |
+
if CUDNN_VERSION < 8220:
|
109 |
+
quit(f"CUDNN version {CUDNN_VERSION} is not supported - please upgrade to 8.9.1")
|
110 |
+
if CUDNN_VERSION > 8910:
|
111 |
+
quit(f"CUDNN version {CUDNN_VERSION} is not supported - please downgrade to 8.9.1")
|
112 |
+
|
113 |
+
|
114 |
+
def get_video_frame(video_path, frame_number = 1):
|
115 |
+
cap = cv2.VideoCapture(video_path)
|
116 |
+
amount_of_frames = cap.get(cv2.CAP_PROP_FRAME_COUNT)
|
117 |
+
cap.set(cv2.CAP_PROP_POS_FRAMES, min(amount_of_frames, frame_number-1))
|
118 |
+
if not cap.isOpened():
|
119 |
+
print("Error opening video file")
|
120 |
+
return
|
121 |
+
ret, frame = cap.read()
|
122 |
+
if ret:
|
123 |
+
return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
124 |
+
|
125 |
+
cap.release()
|
126 |
+
|
127 |
+
|
128 |
+
def preview_video(video_path):
|
129 |
+
cap = cv2.VideoCapture(video_path)
|
130 |
+
if not cap.isOpened():
|
131 |
+
print("Error opening video file")
|
132 |
+
return 0
|
133 |
+
amount_of_frames = cap.get(cv2.CAP_PROP_FRAME_COUNT)
|
134 |
+
ret, frame = cap.read()
|
135 |
+
if ret:
|
136 |
+
frame = get_video_frame(video_path)
|
137 |
+
|
138 |
+
cap.release()
|
139 |
+
return (amount_of_frames, frame)
|
140 |
+
|
141 |
+
|
142 |
+
def status(string):
|
143 |
+
value = "Status: " + string
|
144 |
+
if 'cli_mode' in args:
|
145 |
+
print(value)
|
146 |
+
else:
|
147 |
+
ui.update_status_label(value)
|
148 |
+
|
149 |
+
|
150 |
+
def process_video_multi_cores(source_img, frame_paths):
|
151 |
+
n = len(frame_paths) // roop.globals.cpu_cores
|
152 |
+
if n > 2:
|
153 |
+
processes = []
|
154 |
+
for i in range(0, len(frame_paths), n):
|
155 |
+
p = POOL.apply_async(process_video, args=(source_img, frame_paths[i:i + n],))
|
156 |
+
processes.append(p)
|
157 |
+
for p in processes:
|
158 |
+
p.get()
|
159 |
+
POOL.close()
|
160 |
+
POOL.join()
|
161 |
+
|
162 |
+
|
163 |
+
def start(preview_callback = None):
|
164 |
+
if not args.source_img or not os.path.isfile(args.source_img):
|
165 |
+
print("\n[WARNING] Please select an image containing a face.")
|
166 |
+
return
|
167 |
+
elif not args.target_path or not os.path.isfile(args.target_path):
|
168 |
+
print("\n[WARNING] Please select a video/image to swap face in.")
|
169 |
+
return
|
170 |
+
if not args.output_file:
|
171 |
+
target_path = args.target_path
|
172 |
+
args.output_file = rreplace(target_path, "/", "/swapped-", 1) if "/" in target_path else "swapped-" + target_path
|
173 |
+
target_path = args.target_path
|
174 |
+
test_face = get_face_single(cv2.imread(args.source_img))
|
175 |
+
if not test_face:
|
176 |
+
print("\n[WARNING] No face detected in source image. Please try with another one.\n")
|
177 |
+
return
|
178 |
+
if is_img(target_path):
|
179 |
+
|
180 |
+
|
181 |
+
process_img(args.source_img, target_path, args.output_file)
|
182 |
+
status("swap successful!")
|
183 |
+
return
|
184 |
+
|
185 |
+
video_name_full = target_path.split("/")[-1]
|
186 |
+
video_name = os.path.splitext(video_name_full)[0]
|
187 |
+
output_dir = os.path.dirname(target_path) + "/" + video_name if os.path.dirname(target_path) else video_name
|
188 |
+
Path(output_dir).mkdir(exist_ok=True)
|
189 |
+
status("detecting video's FPS...")
|
190 |
+
fps, exact_fps = detect_fps(target_path)
|
191 |
+
if not args.keep_fps and fps > 30:
|
192 |
+
this_path = output_dir + "/" + video_name + ".mp4"
|
193 |
+
set_fps(target_path, this_path, 30)
|
194 |
+
target_path, exact_fps = this_path, 30
|
195 |
+
else:
|
196 |
+
shutil.copy(target_path, output_dir)
|
197 |
+
status("extracting frames...")
|
198 |
+
extract_frames(target_path, output_dir)
|
199 |
+
args.frame_paths = tuple(sorted(
|
200 |
+
glob.glob(output_dir + "/*.png"),
|
201 |
+
key=lambda x: int(x.split(sep)[-1].replace(".png", ""))
|
202 |
+
))
|
203 |
+
status("swapping in progress...")
|
204 |
+
if roop.globals.gpu_vendor is None and roop.globals.cpu_cores > 1:
|
205 |
+
global POOL
|
206 |
+
POOL = mp.Pool(roop.globals.cpu_cores)
|
207 |
+
process_video_multi_cores(args.source_img, args.frame_paths)
|
208 |
+
else:
|
209 |
+
process_video(args.source_img, args.frame_paths)
|
210 |
+
status("creating video...")
|
211 |
+
create_video(video_name, exact_fps, output_dir)
|
212 |
+
status("adding audio...")
|
213 |
+
add_audio(output_dir, target_path, video_name_full, args.keep_frames, args.output_file)
|
214 |
+
save_path = args.output_file if args.output_file else output_dir + "/" + video_name + ".mp4"
|
215 |
+
print("\n\nVideo saved as:", save_path, "\n\n")
|
216 |
+
status("swap successful!")
|
217 |
+
|
218 |
+
|
219 |
+
def select_face_handler(path: str):
|
220 |
+
args.source_img = path
|
221 |
+
|
222 |
+
|
223 |
+
def select_target_handler(path: str):
|
224 |
+
args.target_path = path
|
225 |
+
return preview_video(args.target_path)
|
226 |
+
|
227 |
+
|
228 |
+
def toggle_all_faces_handler(value: int):
|
229 |
+
roop.globals.all_faces = True if value == 1 else False
|
230 |
+
|
231 |
+
|
232 |
+
def toggle_fps_limit_handler(value: int):
|
233 |
+
args.keep_fps = int(value != 1)
|
234 |
+
|
235 |
+
|
236 |
+
def toggle_keep_frames_handler(value: int):
|
237 |
+
args.keep_frames = value
|
238 |
+
|
239 |
+
|
240 |
+
def save_file_handler(path: str):
|
241 |
+
args.output_file = path
|
242 |
+
|
243 |
+
|
244 |
+
def create_test_preview(frame_number):
|
245 |
+
return process_faces(
|
246 |
+
get_face_single(cv2.imread(args.source_img)),
|
247 |
+
get_video_frame(args.target_path, frame_number)
|
248 |
+
)
|
249 |
+
|
250 |
+
|
251 |
+
def run():
|
252 |
+
global all_faces, keep_frames, limit_fps
|
253 |
+
|
254 |
+
pre_check()
|
255 |
+
limit_resources()
|
256 |
+
if args.source_img:
|
257 |
+
args.cli_mode = True
|
258 |
+
start()
|
259 |
+
quit()
|
260 |
+
|
261 |
+
window = ui.init(
|
262 |
+
{
|
263 |
+
'all_faces': roop.globals.all_faces,
|
264 |
+
'keep_fps': args.keep_fps,
|
265 |
+
'keep_frames': args.keep_frames
|
266 |
+
},
|
267 |
+
select_face_handler,
|
268 |
+
select_target_handler,
|
269 |
+
toggle_all_faces_handler,
|
270 |
+
toggle_fps_limit_handler,
|
271 |
+
toggle_keep_frames_handler,
|
272 |
+
save_file_handler,
|
273 |
+
start,
|
274 |
+
get_video_frame,
|
275 |
+
create_test_preview
|
276 |
+
)
|
277 |
+
|
278 |
+
window.mainloop()
|