prithivMLmods commited on
Commit
7aebbe8
1 Parent(s): b9268a9

Update roop/core.py

Browse files
Files changed (1) hide show
  1. roop/core.py +221 -221
roop/core.py CHANGED
@@ -1,221 +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 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()
 
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()