Nymbo commited on
Commit
abfa6bf
·
verified ·
1 Parent(s): 0b96d72

Modernize: Gradio 6.29, CPU onnxruntime/torch, headless roop (no Tk), NSFW filter no longer kills the app

Browse files
Files changed (5) hide show
  1. README.md +2 -1
  2. app.py +31 -20
  3. packages.txt +1 -0
  4. requirements.txt +14 -23
  5. roop/core.py +221 -217
README.md CHANGED
@@ -4,8 +4,9 @@ emoji: 👦🏻👧🏼
4
  colorFrom: gray
5
  colorTo: indigo
6
  sdk: gradio
7
- sdk_version: 4.36.1
8
  app_file: app.py
 
9
  pinned: false
10
  header: mini
11
  license: creativeml-openrail-m
 
4
  colorFrom: gray
5
  colorTo: indigo
6
  sdk: gradio
7
+ sdk_version: 6.29.0
8
  app_file: app.py
9
+ python_version: "3.10"
10
  pinned: false
11
  header: mini
12
  license: creativeml-openrail-m
app.py CHANGED
@@ -1,6 +1,8 @@
1
  # -* coding:UTF-8 -*
2
  # !/usr/bin/env python
3
- import numpy as np
 
 
4
  import gradio as gr
5
  import roop.globals
6
  from roop.core import (
@@ -11,31 +13,32 @@ from roop.core import (
11
  )
12
  from roop.processors.frame.core import get_frame_processors_modules
13
  from roop.utilities import normalize_output_path
14
- import os
15
  from PIL import Image
16
 
17
 
18
- def swap_face(source_file, target_file,doFaceEnhancer):
 
 
19
 
20
- source_path = "input.jpg"
21
- target_path = "target.jpg"
 
 
22
 
23
- source_image = Image.fromarray(source_file)
24
- source_image.save(source_path)
25
- target_image = Image.fromarray(target_file)
26
- target_image.save(target_path)
27
 
28
  print("source_path: ", source_path)
29
  print("target_path: ", target_path)
30
 
31
  roop.globals.source_path = source_path
32
  roop.globals.target_path = target_path
33
- output_path = "output.jpg"
34
  roop.globals.output_path = normalize_output_path(
35
  roop.globals.source_path, roop.globals.target_path, output_path
36
  )
37
- if doFaceEnhancer == True:
38
- roop.globals.frame_processors = ["face_swapper","face_enhancer"]
39
  else:
40
  roop.globals.frame_processors = ["face_swapper"]
41
  roop.globals.headless = True
@@ -46,7 +49,8 @@ def swap_face(source_file, target_file,doFaceEnhancer):
46
  roop.globals.video_encoder = "libx264"
47
  roop.globals.video_quality = 18
48
  roop.globals.max_memory = suggest_max_memory()
49
- roop.globals.execution_providers = decode_execution_providers(["cuda"])
 
50
  roop.globals.execution_threads = suggest_execution_threads()
51
 
52
  print(
@@ -56,17 +60,24 @@ def swap_face(source_file, target_file,doFaceEnhancer):
56
  roop.globals.output_path,
57
  )
58
 
59
- for frame_processor in get_frame_processors_modules(
60
- roop.globals.frame_processors
61
- ):
62
  if not frame_processor.pre_check():
63
- return
64
 
65
  start()
66
- return output_path
 
 
67
 
68
 
69
  app = gr.Interface(
70
- fn=swap_face, inputs=[gr.Image(), gr.Image(),gr.Checkbox(label="face_enhancer?", info="do face enhancer?")], outputs="image", theme="Nymbo/Alyx_Theme"
 
 
 
 
 
 
 
71
  )
72
- app.launch()
 
1
  # -* coding:UTF-8 -*
2
  # !/usr/bin/env python
3
+ import os
4
+ import tempfile
5
+
6
  import gradio as gr
7
  import roop.globals
8
  from roop.core import (
 
13
  )
14
  from roop.processors.frame.core import get_frame_processors_modules
15
  from roop.utilities import normalize_output_path
 
16
  from PIL import Image
17
 
18
 
19
+ def swap_face(source_file, target_file, doFaceEnhancer):
20
+ if source_file is None or target_file is None:
21
+ raise gr.Error("Please provide both a source face and a target image.")
22
 
23
+ # Per-request working dir so concurrent users don't overwrite each other's files
24
+ work_dir = tempfile.mkdtemp()
25
+ source_path = os.path.join(work_dir, "input.jpg")
26
+ target_path = os.path.join(work_dir, "target.jpg")
27
 
28
+ Image.fromarray(source_file).convert("RGB").save(source_path)
29
+ Image.fromarray(target_file).convert("RGB").save(target_path)
 
 
30
 
31
  print("source_path: ", source_path)
32
  print("target_path: ", target_path)
33
 
34
  roop.globals.source_path = source_path
35
  roop.globals.target_path = target_path
36
+ output_path = os.path.join(work_dir, "output.jpg")
37
  roop.globals.output_path = normalize_output_path(
38
  roop.globals.source_path, roop.globals.target_path, output_path
39
  )
40
+ if doFaceEnhancer:
41
+ roop.globals.frame_processors = ["face_swapper", "face_enhancer"]
42
  else:
43
  roop.globals.frame_processors = ["face_swapper"]
44
  roop.globals.headless = True
 
49
  roop.globals.video_encoder = "libx264"
50
  roop.globals.video_quality = 18
51
  roop.globals.max_memory = suggest_max_memory()
52
+ # cpu-basic hardware: CPU execution provider
53
+ roop.globals.execution_providers = decode_execution_providers(["cpu"])
54
  roop.globals.execution_threads = suggest_execution_threads()
55
 
56
  print(
 
60
  roop.globals.output_path,
61
  )
62
 
63
+ for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
 
 
64
  if not frame_processor.pre_check():
65
+ raise gr.Error("Model download failed; please try again later.")
66
 
67
  start()
68
+ if not os.path.exists(roop.globals.output_path):
69
+ raise gr.Error("No result: no face was found, or the target image was rejected by the NSFW filter.")
70
+ return roop.globals.output_path
71
 
72
 
73
  app = gr.Interface(
74
+ fn=swap_face,
75
+ inputs=[
76
+ gr.Image(label="Source face"),
77
+ gr.Image(label="Target image"),
78
+ gr.Checkbox(label="face_enhancer?", info="do face enhancer?"),
79
+ ],
80
+ outputs=gr.Image(label="Result"),
81
+ flagging_mode="never",
82
  )
83
+ app.launch(theme="Nymbo/Alyx_Theme")
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ ffmpeg
requirements.txt CHANGED
@@ -1,23 +1,14 @@
1
- --extra-index-url https://download.pytorch.org/whl/cu118
2
-
3
- numpy==1.23.5
4
- opencv-python==4.7.0.72
5
- onnx==1.14.0
6
- insightface==0.7.3
7
- psutil==5.9.5
8
- tk==0.1.0
9
- customtkinter==5.1.3
10
- pillow==9.5.0
11
- torch==2.0.1+cu118; sys_platform != 'darwin'
12
- torch==2.0.1; sys_platform == 'darwin'
13
- torchvision==0.15.2+cu118; sys_platform != 'darwin'
14
- torchvision==0.15.2; sys_platform == 'darwin'
15
- onnxruntime==1.15.0; sys_platform == 'darwin' and platform_machine != 'arm64'
16
- onnxruntime-silicon==1.13.1; sys_platform == 'darwin' and platform_machine == 'arm64'
17
- onnxruntime-gpu==1.15.0; sys_platform != 'darwin'
18
- tensorflow==2.13.0rc1; sys_platform == 'darwin'
19
- tensorflow==2.12.0; sys_platform != 'darwin'
20
- opennsfw2==0.10.2
21
- protobuf==4.23.2
22
- tqdm==4.65.0
23
- gfpgan==1.3.8
 
1
+ --extra-index-url https://download.pytorch.org/whl/cpu
2
+ numpy<2
3
+ opencv-python-headless<4.11
4
+ onnx
5
+ insightface==0.7.3
6
+ psutil
7
+ pillow
8
+ torch==2.1.2
9
+ torchvision==0.16.2
10
+ onnxruntime
11
+ tensorflow==2.15.1
12
+ opennsfw2==0.10.2
13
+ tqdm
14
+ gfpgan==1.3.8
 
 
 
 
 
 
 
 
 
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 torch
17
+ import onnxruntime
18
+ import tensorflow
19
+
20
+ import roop.globals
21
+ import roop.metadata
22
+ # roop.ui (tkinter desktop UI) is imported lazily so the headless web app needs no Tk
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
+ import roop.ui as ui
137
+ ui.update_status(message)
138
+
139
+
140
+ def start() -> None:
141
+ for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
142
+ if not frame_processor.pre_start():
143
+ return
144
+ # process image to image
145
+ if has_image_extension(roop.globals.target_path):
146
+ if predict_image(roop.globals.target_path):
147
+ update_status("Target rejected by the NSFW filter.")
148
+ return
149
+ shutil.copy2(roop.globals.target_path, roop.globals.output_path)
150
+ for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
151
+ for frame_processor_name in roop.globals.frame_processors:
152
+ if frame_processor_name == frame_processor.frame_name:
153
+ update_status('Progressing...', frame_processor.NAME)
154
+ frame_processor.process_image(roop.globals.source_path, roop.globals.output_path, roop.globals.output_path)
155
+ frame_processor.post_process()
156
+ release_resources()
157
+ if is_image(roop.globals.target_path):
158
+ update_status('Processing to image succeed!')
159
+ else:
160
+ update_status('Processing to image failed!')
161
+ return
162
+ # process image to videos
163
+ if predict_video(roop.globals.target_path):
164
+ update_status("Target rejected by the NSFW filter.")
165
+ return
166
+ update_status('Creating temp resources...')
167
+ create_temp(roop.globals.target_path)
168
+ update_status('Extracting frames...')
169
+ extract_frames(roop.globals.target_path)
170
+ temp_frame_paths = get_temp_frame_paths(roop.globals.target_path)
171
+ for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
172
+ update_status('Progressing...', frame_processor.NAME)
173
+ frame_processor.process_video(roop.globals.source_path, temp_frame_paths)
174
+ frame_processor.post_process()
175
+ release_resources()
176
+ # handles fps
177
+ if roop.globals.keep_fps:
178
+ update_status('Detecting fps...')
179
+ fps = detect_fps(roop.globals.target_path)
180
+ update_status(f'Creating video with {fps} fps...')
181
+ create_video(roop.globals.target_path, fps)
182
+ else:
183
+ update_status('Creating video with 30.0 fps...')
184
+ create_video(roop.globals.target_path)
185
+ # handle audio
186
+ if roop.globals.keep_audio:
187
+ if roop.globals.keep_fps:
188
+ update_status('Restoring audio...')
189
+ else:
190
+ update_status('Restoring audio might cause issues as fps are not kept...')
191
+ restore_audio(roop.globals.target_path, roop.globals.output_path)
192
+ else:
193
+ move_temp(roop.globals.target_path, roop.globals.output_path)
194
+ # clean and validate
195
+ clean_temp(roop.globals.target_path)
196
+ if is_video(roop.globals.target_path):
197
+ update_status('Processing to video succeed!')
198
+ else:
199
+ update_status('Processing to video failed!')
200
+
201
+
202
+ def destroy() -> None:
203
+ if roop.globals.target_path:
204
+ clean_temp(roop.globals.target_path)
205
+ quit()
206
+
207
+
208
+ def run() -> None:
209
+ parse_args()
210
+ if not pre_check():
211
+ return
212
+ for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
213
+ if not frame_processor.pre_check():
214
+ return
215
+ limit_resources()
216
+ if roop.globals.headless:
217
+ start()
218
+ else:
219
+ import roop.ui as ui
220
+ window = ui.init(start, destroy)
221
+ window.mainloop()