prithivMLmods commited on
Commit
29de0fc
1 Parent(s): 134672c

Update roop/core.py

Browse files
Files changed (1) hide show
  1. roop/core.py +221 -217
roop/core.py CHANGED
@@ -1,217 +1,221 @@
1
- #!/usr/bin/env python3
2
-
3
- import os
4
- import sys
5
- # single thread doubles cuda performance - needs to be set before torch import
6
- if any(arg.startswith('--execution-provider') for arg in sys.argv):
7
- os.environ['OMP_NUM_THREADS'] = '1'
8
- # reduce tensorflow log level
9
- os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
10
- import warnings
11
- from typing import List
12
- import platform
13
- import signal
14
- import shutil
15
- import argparse
16
- import torch
17
- import onnxruntime
18
- import tensorflow
19
-
20
- import roop.globals
21
- import roop.metadata
22
- import roop.ui as ui
23
- from roop.predicter import predict_image, predict_video
24
- from roop.processors.frame.core import get_frame_processors_modules
25
- from roop.utilities import has_image_extension, is_image, is_video, detect_fps, create_video, extract_frames, get_temp_frame_paths, restore_audio, create_temp, move_temp, clean_temp, normalize_output_path
26
-
27
- if 'ROCMExecutionProvider' in roop.globals.execution_providers:
28
- del torch
29
-
30
- warnings.filterwarnings('ignore', category=FutureWarning, module='insightface')
31
- warnings.filterwarnings('ignore', category=UserWarning, module='torchvision')
32
-
33
-
34
- def parse_args() -> None:
35
- signal.signal(signal.SIGINT, lambda signal_number, frame: destroy())
36
- program = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=100))
37
- program.add_argument('-s', '--source', help='select an source image', dest='source_path')
38
- program.add_argument('-t', '--target', help='select an target image or video', dest='target_path')
39
- program.add_argument('-o', '--output', help='select output file or directory', dest='output_path')
40
- program.add_argument('--frame-processor', help='frame processors (choices: face_swapper, face_enhancer, ...)', dest='frame_processor', default=['face_swapper'], nargs='+')
41
- program.add_argument('--keep-fps', help='keep original fps', dest='keep_fps', action='store_true', default=False)
42
- program.add_argument('--keep-audio', help='keep original audio', dest='keep_audio', action='store_true', default=True)
43
- program.add_argument('--keep-frames', help='keep temporary frames', dest='keep_frames', action='store_true', default=False)
44
- program.add_argument('--many-faces', help='process every face', dest='many_faces', action='store_true', default=False)
45
- program.add_argument('--video-encoder', help='adjust output video encoder', dest='video_encoder', default='libx264', choices=['libx264', 'libx265', 'libvpx-vp9'])
46
- program.add_argument('--video-quality', help='adjust output video quality', dest='video_quality', type=int, default=18, choices=range(52), metavar='[0-51]')
47
- program.add_argument('--max-memory', help='maximum amount of RAM in GB', dest='max_memory', type=int, default=suggest_max_memory())
48
- program.add_argument('--execution-provider', help='available execution provider (choices: cpu, ...)', dest='execution_provider', default=['cpu'], choices=suggest_execution_providers(), nargs='+')
49
- program.add_argument('--execution-threads', help='number of execution threads', dest='execution_threads', type=int, default=suggest_execution_threads())
50
- program.add_argument('-v', '--version', action='version', version=f'{roop.metadata.name} {roop.metadata.version}')
51
-
52
- args = program.parse_args()
53
-
54
- roop.globals.source_path = args.source_path
55
- roop.globals.target_path = args.target_path
56
- roop.globals.output_path = normalize_output_path(roop.globals.source_path, roop.globals.target_path, args.output_path)
57
- roop.globals.frame_processors = args.frame_processor
58
- roop.globals.headless = args.source_path or args.target_path or args.output_path
59
- roop.globals.keep_fps = args.keep_fps
60
- roop.globals.keep_audio = args.keep_audio
61
- roop.globals.keep_frames = args.keep_frames
62
- roop.globals.many_faces = args.many_faces
63
- roop.globals.video_encoder = args.video_encoder
64
- roop.globals.video_quality = args.video_quality
65
- roop.globals.max_memory = args.max_memory
66
- roop.globals.execution_providers = decode_execution_providers(args.execution_provider)
67
- roop.globals.execution_threads = args.execution_threads
68
-
69
-
70
- def encode_execution_providers(execution_providers: List[str]) -> List[str]:
71
- return [execution_provider.replace('ExecutionProvider', '').lower() for execution_provider in execution_providers]
72
-
73
-
74
- def decode_execution_providers(execution_providers: List[str]) -> List[str]:
75
- return [provider for provider, encoded_execution_provider in zip(onnxruntime.get_available_providers(), encode_execution_providers(onnxruntime.get_available_providers()))
76
- if any(execution_provider in encoded_execution_provider for execution_provider in execution_providers)]
77
-
78
-
79
- def suggest_max_memory() -> int:
80
- if platform.system().lower() == 'darwin':
81
- return 4
82
- return 16
83
-
84
-
85
- def suggest_execution_providers() -> List[str]:
86
- return encode_execution_providers(onnxruntime.get_available_providers())
87
-
88
-
89
- def suggest_execution_threads() -> int:
90
- if 'DmlExecutionProvider' in roop.globals.execution_providers:
91
- return 1
92
- if 'ROCMExecutionProvider' in roop.globals.execution_providers:
93
- return 1
94
- return 8
95
-
96
-
97
- def limit_resources() -> None:
98
- # prevent tensorflow memory leak
99
- gpus = tensorflow.config.experimental.list_physical_devices('GPU')
100
- for gpu in gpus:
101
- tensorflow.config.experimental.set_virtual_device_configuration(gpu, [
102
- tensorflow.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)
103
- ])
104
- # limit memory usage
105
- if roop.globals.max_memory:
106
- memory = roop.globals.max_memory * 1024 ** 3
107
- if platform.system().lower() == 'darwin':
108
- memory = roop.globals.max_memory * 1024 ** 6
109
- if platform.system().lower() == 'windows':
110
- import ctypes
111
- kernel32 = ctypes.windll.kernel32
112
- kernel32.SetProcessWorkingSetSize(-1, ctypes.c_size_t(memory), ctypes.c_size_t(memory))
113
- else:
114
- import resource
115
- resource.setrlimit(resource.RLIMIT_DATA, (memory, memory))
116
-
117
-
118
- def release_resources() -> None:
119
- if 'CUDAExecutionProvider' in roop.globals.execution_providers:
120
- torch.cuda.empty_cache()
121
-
122
-
123
- def pre_check() -> bool:
124
- if sys.version_info < (3, 9):
125
- update_status('Python version is not supported - please upgrade to 3.9 or higher.')
126
- return False
127
- if not shutil.which('ffmpeg'):
128
- update_status('ffmpeg is not installed.')
129
- return False
130
- return True
131
-
132
-
133
- def update_status(message: str, scope: str = 'ROOP.CORE') -> None:
134
- print(f'[{scope}] {message}')
135
- if not roop.globals.headless:
136
- ui.update_status(message)
137
-
138
-
139
- def start() -> None:
140
- for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
141
- if not frame_processor.pre_start():
142
- return
143
- # process image to image
144
- if has_image_extension(roop.globals.target_path):
145
- if predict_image(roop.globals.target_path):
146
- destroy()
147
- shutil.copy2(roop.globals.target_path, roop.globals.output_path)
148
- for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
149
- for frame_processor_name in roop.globals.frame_processors:
150
- if frame_processor_name == frame_processor.frame_name:
151
- update_status('Progressing...', frame_processor.NAME)
152
- frame_processor.process_image(roop.globals.source_path, roop.globals.output_path, roop.globals.output_path)
153
- frame_processor.post_process()
154
- release_resources()
155
- if is_image(roop.globals.target_path):
156
- update_status('Processing to image succeed!')
157
- else:
158
- update_status('Processing to image failed!')
159
- return
160
- # process image to videos
161
- if predict_video(roop.globals.target_path):
162
- destroy()
163
- update_status('Creating temp resources...')
164
- create_temp(roop.globals.target_path)
165
- update_status('Extracting frames...')
166
- extract_frames(roop.globals.target_path)
167
- temp_frame_paths = get_temp_frame_paths(roop.globals.target_path)
168
- for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
169
- update_status('Progressing...', frame_processor.NAME)
170
- frame_processor.process_video(roop.globals.source_path, temp_frame_paths)
171
- frame_processor.post_process()
172
- release_resources()
173
- # handles fps
174
- if roop.globals.keep_fps:
175
- update_status('Detecting fps...')
176
- fps = detect_fps(roop.globals.target_path)
177
- update_status(f'Creating video with {fps} fps...')
178
- create_video(roop.globals.target_path, fps)
179
- else:
180
- update_status('Creating video with 30.0 fps...')
181
- create_video(roop.globals.target_path)
182
- # handle audio
183
- if roop.globals.keep_audio:
184
- if roop.globals.keep_fps:
185
- update_status('Restoring audio...')
186
- else:
187
- update_status('Restoring audio might cause issues as fps are not kept...')
188
- restore_audio(roop.globals.target_path, roop.globals.output_path)
189
- else:
190
- move_temp(roop.globals.target_path, roop.globals.output_path)
191
- # clean and validate
192
- clean_temp(roop.globals.target_path)
193
- if is_video(roop.globals.target_path):
194
- update_status('Processing to video succeed!')
195
- else:
196
- update_status('Processing to video failed!')
197
-
198
-
199
- def destroy() -> None:
200
- if roop.globals.target_path:
201
- clean_temp(roop.globals.target_path)
202
- quit()
203
-
204
-
205
- def run() -> None:
206
- parse_args()
207
- if not pre_check():
208
- return
209
- for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
210
- if not frame_processor.pre_check():
211
- return
212
- limit_resources()
213
- if roop.globals.headless:
214
- start()
215
- else:
216
- window = ui.init(start, destroy)
217
- window.mainloop()
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ import os
4
+ import sys
5
+ # single thread doubles cuda performance - needs to be set before torch import
6
+ if any(arg.startswith('--execution-provider') for arg in sys.argv):
7
+ os.environ['OMP_NUM_THREADS'] = '1'
8
+ # reduce tensorflow log level
9
+ os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
10
+ import warnings
11
+ from typing import List
12
+ import platform
13
+ import signal
14
+ import shutil
15
+ import argparse
16
+ import onnxruntime
17
+ import tensorflow
18
+ import roop.globals
19
+ import roop.metadata
20
+ import roop.ui as ui
21
+ import spaces
22
+ from roop.predictor import predict_image, predict_video
23
+ from roop.processors.frame.core import get_frame_processors_modules
24
+ from roop.utilities import has_image_extension, is_image, is_video, detect_fps, create_video, extract_frames, get_temp_frame_paths, restore_audio, create_temp, move_temp, clean_temp, normalize_output_path
25
+
26
+ warnings.filterwarnings('ignore', category=FutureWarning, module='insightface')
27
+ warnings.filterwarnings('ignore', category=UserWarning, module='torchvision')
28
+
29
+ @spaces.GPU
30
+ def parse_args() -> None:
31
+ signal.signal(signal.SIGINT, lambda signal_number, frame: destroy())
32
+ program = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=100))
33
+ program.add_argument('-s', '--source', help='select an source image', dest='source_path')
34
+ program.add_argument('-t', '--target', help='select an target image or video', dest='target_path')
35
+ program.add_argument('-o', '--output', help='select output file or directory', dest='output_path')
36
+ program.add_argument('--frame-processor', help='frame processors (choices: face_swapper, face_enhancer, ...)', dest='frame_processor', default=['face_swapper'], nargs='+')
37
+ program.add_argument('--keep-fps', help='keep target fps', dest='keep_fps', action='store_true')
38
+ program.add.add_argument('--keep-frames', help='keep temporary frames', dest='keep_frames', action='store_true')
39
+ program.add.add.argument('--skip-audio', help='skip target audio', dest='skip_audio', action='store_true')
40
+ program.add.argument('--many-faces', help='process every face', dest='many_faces', action='store_true')
41
+ program.add.argument('--reference-face-position', help='position of the reference face', dest='reference_face_position', type=int, default=0)
42
+ program.add.argument('--reference-frame-number', help='number of the reference frame', dest='reference_frame_number', type=int, default=0)
43
+ program.add.argument('--similar-face-distance', help='face distance used for recognition', dest='similar_face_distance', type=float, default=0.85)
44
+ program.add.argument('--temp-frame-format', help='image format used for frame extraction', dest='temp_frame_format', default='png', choices=['jpg', 'png'])
45
+ program.add.argument('--temp-frame-quality', help='image quality used for frame extraction', dest='temp_frame_quality', type=int, default=0, choices=range(101), metavar='[0-100]')
46
+ program.add.argument('--output-video-encoder', help='encoder used for the output video', dest='output_video_encoder', default='libx264', choices=['libx264', 'libx265', 'libvpx-vp9', 'h264_nvenc', 'hevc_nvenc'])
47
+ program.add.argument('--output-video-quality', help='quality used for the output video', dest='output_video_quality', type=int, default=35, choices=range(101), metavar='[0-100]')
48
+ program.add.argument('--max-memory', help='maximum amount of RAM in GB', dest='max_memory', type=int)
49
+ program.add.argument('--execution-provider', help='available execution provider (choices: cpu, cuda, ...)', dest='execution_provider', default=['cuda'], choices=suggest_execution_providers(), nargs='+')
50
+ program.add.argument('--execution-threads', help='number of execution threads', dest='execution_threads', type=int, default=suggest_execution_threads())
51
+ program.add.argument('-v', '--version', action='version', version=f'{roop.metadata.name} {roop.metadata.version}')
52
+
53
+ args = program.parse_args()
54
+
55
+ roop.globals.source_path = args.source_path
56
+ roop.globals.target_path = args.target_path
57
+ roop.globals.output_path = normalize_output_path(roop.globals.source_path, roop.globals.target_path, args.output_path)
58
+ roop.globals.headless = roop.globals.source_path is not None and roop.globals.target_path is not None and roop.globals.output_path is not None
59
+ roop.globals.frame_processors = args.frame_processor
60
+ roop.globals.keep_fps = args.keep_fps
61
+ roop.globals.keep_frames = args.keep_frames
62
+ roop.globals.skip_audio = args.skip_audio
63
+ roop.globals.many_faces = args.many_faces
64
+ roop.globals.reference_face_position = args.reference_face_position
65
+ roop.globals.reference_frame_number = args.reference_frame_number
66
+ roop.globals.similar_face_distance = args.similar_face_distance
67
+ roop.globals.temp_frame_format = args.temp_frame_format
68
+ roop.globals.temp_frame_quality = args.temp_frame_quality
69
+ roop.globals.output_video_encoder = args.output_video_encoder
70
+ roop.globals.output_video_quality = args.output_video_quality
71
+ roop.globals.max_memory = args.max_memory
72
+ roop.globals.execution_providers = decode_execution_providers(args.execution_provider)
73
+ roop.globals.execution_threads = args.execution_threads
74
+
75
+
76
+ def encode_execution_providers(execution_providers: List[str]) -> List[str]:
77
+ return [execution_provider.replace('ExecutionProvider', '').lower() for execution_provider in execution_providers]
78
+
79
+
80
+ def decode_execution_providers(execution_providers: List[str]) -> List[str]:
81
+ return [provider for provider, encoded_execution_provider in zip(onnxruntime.get_available_providers(), encode_execution_providers(onnxruntime.get_available_providers()))
82
+ if any(execution_provider in encoded_execution_provider for execution_provider in execution_providers)]
83
+
84
+
85
+ def suggest_execution_providers() -> List[str]:
86
+ return encode_execution_providers(onnxruntime.get_available_providers())
87
+
88
+
89
+ def suggest_execution_threads() -> int:
90
+ if 'CUDAExecutionProvider' in onnxruntime.get_available_providers():
91
+ return 8
92
+ return 1
93
+
94
+
95
+ def limit_resources() -> None:
96
+ # prevent tensorflow memory leak
97
+ gpus = tensorflow.config.experimental.list_physical_devices('GPU')
98
+ for gpu in gpus:
99
+ tensorflow.config.experimental.set_virtual_device_configuration(gpu, [
100
+ tensorflow.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)
101
+ ])
102
+ # limit memory usage
103
+ if roop.globals.max_memory:
104
+ memory = roop.globals.max_memory * 1024 ** 3
105
+ if platform.system().lower() == 'darwin':
106
+ memory = roop.globals.max_memory * 1024 ** 6
107
+ if platform.system().lower() == 'windows':
108
+ import ctypes
109
+ kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
110
+ kernel32.SetProcessWorkingSetSize(-1, ctypes.c_size_t(memory), ctypes.c_size_t(memory))
111
+ else:
112
+ import resource
113
+ resource.setrlimit(resource.RLIMIT_DATA, (memory, memory))
114
+
115
+
116
+ def pre_check() -> bool:
117
+ if sys.version_info < (3, 9):
118
+ update_status('Python version is not supported - please upgrade to 3.9 or higher.')
119
+ return False
120
+ if not shutil.which('ffmpeg'):
121
+ update_status('ffmpeg is not installed.')
122
+ return False
123
+ return True
124
+
125
+
126
+ def update_status(message: str, scope: str = 'ROOP.CORE') -> None:
127
+ print(f'[{scope}] {message}')
128
+ if not roop.globals.headless:
129
+ ui.update_status(message)
130
+
131
+
132
+ def start() -> None:
133
+ for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
134
+ if not frame_processor.pre_start():
135
+ return
136
+ # process image to image
137
+ if has_image_extension(roop.globals.target_path):
138
+ if predict_image(roop.globals.target_path):
139
+ destroy()
140
+ shutil.copy2(roop.globals.target_path, roop.globals.output_path)
141
+ # process frame
142
+ for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
143
+ update_status('Progressing...', frame_processor.NAME)
144
+ frame_processor.process_image(roop.globals.source_path, roop.globals.output_path, roop.globals.output_path)
145
+ frame_processor.post_process()
146
+ # validate image
147
+ if is_image(roop.globals.target_path):
148
+ update_status('Processing to image succeed!')
149
+ else:
150
+ update_status('Processing to image failed!')
151
+ return
152
+ # process image to videos
153
+ if predict_video(roop.globals.target_path):
154
+ destroy()
155
+ update_status('Creating temporary resources...')
156
+ create_temp(roop.globals.target_path)
157
+ # extract frames
158
+ if roop.globals.keep_fps:
159
+ fps = detect_fps(roop.globals.target_path)
160
+ update_status(f'Extracting frames with {fps} FPS...')
161
+ extract_frames(roop.globals.target_path, fps)
162
+ else:
163
+ update_status('Extracting frames with 30 FPS...')
164
+ extract_frames(roop.globals.target_path)
165
+ # process frame
166
+ temp_frame_paths = get_temp_frame_paths(roop.globals.target_path)
167
+ if temp_frame_paths:
168
+ for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
169
+ update_status('Progressing...', frame_processor.NAME)
170
+ frame_processor.process_video(roop.globals.source_path, temp_frame_paths)
171
+ frame_processor.post_process()
172
+ else:
173
+ update_status('Frames not found...')
174
+ return
175
+ # create video
176
+ if roop.globals.keep_fps:
177
+ fps = detect_fps(roop.globals.target_path)
178
+ update_status(f'Creating video with {fps} FPS...')
179
+ create_video(roop.globals.target_path, fps)
180
+ else:
181
+ update_status('Creating video with 30 FPS...')
182
+ create_video(roop.globals.target_path)
183
+ # handle audio
184
+ if roop.globals.skip_audio:
185
+ move_temp(roop.globals.target_path, roop.globals.output_path)
186
+ update_status('Skipping audio...')
187
+ else:
188
+ if roop.globals.keep_fps:
189
+ update_status('Restoring audio...')
190
+ else:
191
+ update_status('Restoring audio might cause issues as fps are not kept...')
192
+ restore_audio(roop.globals.target_path, roop.globals.output_path)
193
+ # clean temp
194
+ update_status('Cleaning temporary resources...')
195
+ clean_temp(roop.globals.target_path)
196
+ # validate video
197
+ if is_video(roop.globals.target_path):
198
+ update_status('Processing to video succeed!')
199
+ else:
200
+ update_status('Processing to video failed!')
201
+
202
+
203
+ def destroy() -> None:
204
+ if roop.globals.target_path:
205
+ clean_temp(roop.globals.target_path)
206
+ sys.exit()
207
+
208
+
209
+ def run() -> None:
210
+ parse_args()
211
+ if not pre_check():
212
+ return
213
+ for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
214
+ if not frame_processor.pre_check():
215
+ return
216
+ limit_resources()
217
+ if roop.globals.headless:
218
+ start()
219
+ else:
220
+ window = ui.init(start, destroy)
221
+ window.mainloop()