Moibe commited on
Commit
f53c085
1 Parent(s): 35e399f

Roop Ready

Browse files
.gitignore ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ #.idea/
models/test.py DELETED
@@ -1 +0,0 @@
1
- print("Hola test")
 
 
roop/__init__.py ADDED
File without changes
roop/capturer.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+ import cv2
3
+
4
+ from roop.typing import Frame
5
+
6
+
7
+ def get_video_frame(video_path: str, frame_number: int = 0) -> Optional[Frame]:
8
+ capture = cv2.VideoCapture(video_path)
9
+ frame_total = capture.get(cv2.CAP_PROP_FRAME_COUNT)
10
+ capture.set(cv2.CAP_PROP_POS_FRAMES, min(frame_total, frame_number - 1))
11
+ has_frame, frame = capture.read()
12
+ capture.release()
13
+ if has_frame:
14
+ return frame
15
+ return None
16
+
17
+
18
+ def get_video_frame_total(video_path: str) -> int:
19
+ capture = cv2.VideoCapture(video_path)
20
+ video_frame_total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
21
+ capture.release()
22
+ return video_frame_total
roop/core.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import time
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
+ from roop.predictor import predict_image, predict_video
22
+ from roop.processors.frame.core import get_frame_processors_modules
23
+ 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
24
+
25
+ warnings.filterwarnings('ignore', category=FutureWarning, module='insightface')
26
+ warnings.filterwarnings('ignore', category=UserWarning, module='torchvision')
27
+
28
+
29
+ def parse_args() -> None:
30
+ signal.signal(signal.SIGINT, lambda signal_number, frame: destroy())
31
+ program = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=100))
32
+ program.add_argument('-s', '--source', help='select an source image', dest='source_path')
33
+ program.add_argument('-t', '--target', help='select an target image or video', dest='target_path')
34
+ program.add_argument('-o', '--output', help='select output file or directory', dest='output_path')
35
+ program.add_argument('--frame-processor', help='frame processors (choices: face_swapper, face_enhancer, ...)', dest='frame_processor', default=['face_swapper'], nargs='+')
36
+ program.add_argument('--keep-fps', help='keep target fps', dest='keep_fps', action='store_true')
37
+ program.add_argument('--keep-frames', help='keep temporary frames', dest='keep_frames', action='store_true')
38
+ program.add_argument('--skip-audio', help='skip target audio', dest='skip_audio', action='store_true')
39
+ program.add_argument('--many-faces', help='process every face', dest='many_faces', action='store_true')
40
+ program.add_argument('--reference-face-position', help='position of the reference face', dest='reference_face_position', type=int, default=0)
41
+ program.add_argument('--reference-frame-number', help='number of the reference frame', dest='reference_frame_number', type=int, default=0)
42
+ program.add_argument('--similar-face-distance', help='face distance used for recognition', dest='similar_face_distance', type=float, default=0.85)
43
+ program.add_argument('--temp-frame-format', help='image format used for frame extraction', dest='temp_frame_format', default='png', choices=['jpg', 'png'])
44
+ 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]')
45
+ 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'])
46
+ 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]')
47
+ program.add_argument('--max-memory', help='maximum amount of RAM in GB', dest='max_memory', type=int)
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.headless = roop.globals.source_path is not None and roop.globals.target_path is not None and roop.globals.output_path is not None
58
+ roop.globals.frame_processors = args.frame_processor
59
+ roop.globals.keep_fps = args.keep_fps
60
+ roop.globals.keep_frames = args.keep_frames
61
+ roop.globals.skip_audio = args.skip_audio
62
+ roop.globals.many_faces = args.many_faces
63
+ roop.globals.reference_face_position = args.reference_face_position
64
+ roop.globals.reference_frame_number = args.reference_frame_number
65
+ roop.globals.similar_face_distance = args.similar_face_distance
66
+ roop.globals.temp_frame_format = args.temp_frame_format
67
+ roop.globals.temp_frame_quality = args.temp_frame_quality
68
+ roop.globals.output_video_encoder = args.output_video_encoder
69
+ roop.globals.output_video_quality = args.output_video_quality
70
+ roop.globals.max_memory = args.max_memory
71
+ roop.globals.execution_providers = decode_execution_providers(args.execution_provider)
72
+ roop.globals.execution_threads = args.execution_threads
73
+
74
+
75
+ def encode_execution_providers(execution_providers: List[str]) -> List[str]:
76
+ return [execution_provider.replace('ExecutionProvider', '').lower() for execution_provider in execution_providers]
77
+
78
+
79
+ def decode_execution_providers(execution_providers: List[str]) -> List[str]:
80
+ return [provider for provider, encoded_execution_provider in zip(onnxruntime.get_available_providers(), encode_execution_providers(onnxruntime.get_available_providers()))
81
+ if any(execution_provider in encoded_execution_provider for execution_provider in execution_providers)]
82
+
83
+
84
+ def suggest_execution_providers() -> List[str]:
85
+ return encode_execution_providers(onnxruntime.get_available_providers())
86
+
87
+
88
+ def suggest_execution_threads() -> int:
89
+ if 'CUDAExecutionProvider' in onnxruntime.get_available_providers():
90
+ return 8
91
+ return 1
92
+
93
+
94
+ def limit_resources() -> None:
95
+ # prevent tensorflow memory leak
96
+ gpus = tensorflow.config.experimental.list_physical_devices('GPU')
97
+ for gpu in gpus:
98
+ tensorflow.config.experimental.set_virtual_device_configuration(gpu, [
99
+ tensorflow.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)
100
+ ])
101
+ # limit memory usage
102
+ if roop.globals.max_memory:
103
+ memory = roop.globals.max_memory * 1024 ** 3
104
+ if platform.system().lower() == 'darwin':
105
+ memory = roop.globals.max_memory * 1024 ** 6
106
+ if platform.system().lower() == 'windows':
107
+ import ctypes
108
+ kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
109
+ kernel32.SetProcessWorkingSetSize(-1, ctypes.c_size_t(memory), ctypes.c_size_t(memory))
110
+ else:
111
+ import resource
112
+ resource.setrlimit(resource.RLIMIT_DATA, (memory, memory))
113
+
114
+
115
+ def pre_check() -> bool:
116
+ if sys.version_info < (3, 9):
117
+ update_status('Python version is not supported - please upgrade to 3.9 or higher.')
118
+ return False
119
+ if not shutil.which('ffmpeg'):
120
+ update_status('ffmpeg is not installed.')
121
+ return False
122
+ return True
123
+
124
+
125
+ def update_status(message: str, scope: str = 'ROOP.CORE') -> None:
126
+ print(f'[{scope}] {message}')
127
+ if not roop.globals.headless:
128
+ ui.update_status(message)
129
+
130
+
131
+ def start() -> None:
132
+ for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
133
+ if not frame_processor.pre_start():
134
+ return
135
+ # process image to image
136
+ if has_image_extension(roop.globals.target_path):
137
+ if predict_image(roop.globals.target_path):
138
+ destroy()
139
+ shutil.copy2(roop.globals.target_path, roop.globals.output_path)
140
+ # process frame
141
+ for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
142
+ update_status('Progressing...', frame_processor.NAME)
143
+ frame_processor.process_image(roop.globals.source_path, roop.globals.output_path, roop.globals.output_path)
144
+ print("MOI: roop.globals.source_path es: ", roop.globals.source_path)
145
+ time.sleep(30)
146
+ frame_processor.post_process()
147
+ # validate image
148
+ if is_image(roop.globals.target_path):
149
+ update_status('Processing to image succeed!')
150
+ else:
151
+ update_status('Processing to image failed!')
152
+ return
153
+ # process image to videos
154
+ if predict_video(roop.globals.target_path):
155
+ destroy()
156
+ update_status('Creating temporary resources...')
157
+ create_temp(roop.globals.target_path)
158
+ # extract frames
159
+ if roop.globals.keep_fps:
160
+ fps = detect_fps(roop.globals.target_path)
161
+ update_status(f'Extracting frames with {fps} FPS...')
162
+ extract_frames(roop.globals.target_path, fps)
163
+ else:
164
+ update_status('Extracting frames with 30 FPS...')
165
+ extract_frames(roop.globals.target_path)
166
+ # process frame
167
+ temp_frame_paths = get_temp_frame_paths(roop.globals.target_path)
168
+ if temp_frame_paths:
169
+ for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
170
+ update_status('Progressing...', frame_processor.NAME)
171
+ frame_processor.process_video(roop.globals.source_path, temp_frame_paths)
172
+ frame_processor.post_process()
173
+ else:
174
+ update_status('Frames not found...')
175
+ return
176
+ # create video
177
+ if roop.globals.keep_fps:
178
+ fps = detect_fps(roop.globals.target_path)
179
+ update_status(f'Creating video with {fps} FPS...')
180
+ create_video(roop.globals.target_path, fps)
181
+ else:
182
+ update_status('Creating video with 30 FPS...')
183
+ create_video(roop.globals.target_path)
184
+ # handle audio
185
+ if roop.globals.skip_audio:
186
+ move_temp(roop.globals.target_path, roop.globals.output_path)
187
+ update_status('Skipping audio...')
188
+ else:
189
+ if roop.globals.keep_fps:
190
+ update_status('Restoring audio...')
191
+ else:
192
+ update_status('Restoring audio might cause issues as fps are not kept...')
193
+ restore_audio(roop.globals.target_path, roop.globals.output_path)
194
+ # clean temp
195
+ update_status('Cleaning temporary resources...')
196
+ print("No voy a limpiar el temp...")
197
+ time.sleep(3)
198
+ #clean_temp(roop.globals.target_path)
199
+ # validate video
200
+ if is_video(roop.globals.target_path):
201
+ update_status('Processing to video succeed!')
202
+ else:
203
+ update_status('Processing to video failed!')
204
+
205
+
206
+ def destroy() -> None:
207
+ if roop.globals.target_path:
208
+ clean_temp(roop.globals.target_path)
209
+ sys.exit()
210
+
211
+
212
+ def run() -> None:
213
+ parse_args()
214
+ if not pre_check():
215
+ return
216
+ for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
217
+ if not frame_processor.pre_check():
218
+ return
219
+ limit_resources()
220
+ if roop.globals.headless:
221
+ start()
222
+ else:
223
+ window = ui.init(start, destroy)
224
+ window.mainloop()
roop/face_analyser.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import threading
2
+ from typing import Any, Optional, List
3
+ import insightface
4
+ import numpy
5
+
6
+ import roop.globals
7
+ from roop.typing import Frame, Face
8
+
9
+ FACE_ANALYSER = None
10
+ THREAD_LOCK = threading.Lock()
11
+
12
+
13
+ def get_face_analyser() -> Any:
14
+ global FACE_ANALYSER
15
+
16
+ with THREAD_LOCK:
17
+ if FACE_ANALYSER is None:
18
+ FACE_ANALYSER = insightface.app.FaceAnalysis(name='buffalo_l', providers=roop.globals.execution_providers)
19
+ FACE_ANALYSER.prepare(ctx_id=0)
20
+ return FACE_ANALYSER
21
+
22
+
23
+ def clear_face_analyser() -> Any:
24
+ global FACE_ANALYSER
25
+
26
+ FACE_ANALYSER = None
27
+
28
+
29
+ def get_one_face(frame: Frame, position: int = 0) -> Optional[Face]:
30
+ many_faces = get_many_faces(frame)
31
+ if many_faces:
32
+ try:
33
+ return many_faces[position]
34
+ except IndexError:
35
+ return many_faces[-1]
36
+ return None
37
+
38
+
39
+ def get_many_faces(frame: Frame) -> Optional[List[Face]]:
40
+ try:
41
+ return get_face_analyser().get(frame)
42
+ except ValueError:
43
+ return None
44
+
45
+
46
+ def find_similar_face(frame: Frame, reference_face: Face) -> Optional[Face]:
47
+ many_faces = get_many_faces(frame)
48
+ if many_faces:
49
+ for face in many_faces:
50
+ if hasattr(face, 'normed_embedding') and hasattr(reference_face, 'normed_embedding'):
51
+ distance = numpy.sum(numpy.square(face.normed_embedding - reference_face.normed_embedding))
52
+ if distance < roop.globals.similar_face_distance:
53
+ return face
54
+ return None
roop/face_reference.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ from roop.typing import Face
4
+
5
+ FACE_REFERENCE = None
6
+
7
+
8
+ def get_face_reference() -> Optional[Face]:
9
+ return FACE_REFERENCE
10
+
11
+
12
+ def set_face_reference(face: Face) -> None:
13
+ global FACE_REFERENCE
14
+
15
+ FACE_REFERENCE = face
16
+
17
+
18
+ def clear_face_reference() -> None:
19
+ global FACE_REFERENCE
20
+
21
+ FACE_REFERENCE = None
roop/globals.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+
3
+ source_path: Optional[str] = None
4
+ target_path: Optional[str] = None
5
+ output_path: Optional[str] = None
6
+ headless: Optional[bool] = None
7
+ frame_processors: List[str] = []
8
+ keep_fps: Optional[bool] = None
9
+ keep_frames: Optional[bool] = None
10
+ skip_audio: Optional[bool] = None
11
+ many_faces: Optional[bool] = None
12
+ reference_face_position: Optional[int] = None
13
+ reference_frame_number: Optional[int] = None
14
+ similar_face_distance: Optional[float] = None
15
+ temp_frame_format: Optional[str] = None
16
+ temp_frame_quality: Optional[int] = None
17
+ output_video_encoder: Optional[str] = None
18
+ output_video_quality: Optional[int] = None
19
+ max_memory: Optional[int] = None
20
+ execution_providers: List[str] = []
21
+ execution_threads: Optional[int] = None
22
+ log_level: str = 'error'
roop/metadata.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ name = 'roop'
2
+ version = '1.3.2'
roop/predictor.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import threading
2
+ import numpy
3
+ import opennsfw2
4
+ from PIL import Image
5
+ from keras import Model
6
+
7
+ from roop.typing import Frame
8
+
9
+ PREDICTOR = None
10
+ THREAD_LOCK = threading.Lock()
11
+ MAX_PROBABILITY = 999
12
+
13
+
14
+ def get_predictor() -> Model:
15
+ global PREDICTOR
16
+
17
+ with THREAD_LOCK:
18
+ if PREDICTOR is None:
19
+ PREDICTOR = opennsfw2.make_open_nsfw_model()
20
+ return PREDICTOR
21
+
22
+
23
+ def clear_predictor() -> None:
24
+ global PREDICTOR
25
+
26
+ PREDICTOR = None
27
+
28
+
29
+ def predict_frame(target_frame: Frame) -> bool:
30
+ image = Image.fromarray(target_frame)
31
+ image = opennsfw2.preprocess_image(image, opennsfw2.Preprocessing.YAHOO)
32
+ views = numpy.expand_dims(image, axis=0)
33
+ _, probability = get_predictor().predict(views)[0]
34
+ return probability > MAX_PROBABILITY
35
+
36
+
37
+ def predict_image(target_path: str) -> bool:
38
+ return opennsfw2.predict_image(target_path) > MAX_PROBABILITY
39
+
40
+
41
+ def predict_video(target_path: str) -> bool:
42
+ _, probabilities = opennsfw2.predict_video_frames(video_path=target_path, frame_interval=100)
43
+ return any(probability > MAX_PROBABILITY for probability in probabilities)
roop/processors/__init__.py ADDED
File without changes
roop/processors/frame/__init__.py ADDED
File without changes
roop/processors/frame/core.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import importlib
4
+ import psutil
5
+ from concurrent.futures import ThreadPoolExecutor, as_completed
6
+ from queue import Queue
7
+ from types import ModuleType
8
+ from typing import Any, List, Callable
9
+ from tqdm import tqdm
10
+
11
+ import roop
12
+
13
+ FRAME_PROCESSORS_MODULES: List[ModuleType] = []
14
+ FRAME_PROCESSORS_INTERFACE = [
15
+ 'pre_check',
16
+ 'pre_start',
17
+ 'process_frame',
18
+ 'process_frames',
19
+ 'process_image',
20
+ 'process_video',
21
+ 'post_process'
22
+ ]
23
+
24
+
25
+ def load_frame_processor_module(frame_processor: str) -> Any:
26
+ try:
27
+ frame_processor_module = importlib.import_module(f'roop.processors.frame.{frame_processor}')
28
+ for method_name in FRAME_PROCESSORS_INTERFACE:
29
+ if not hasattr(frame_processor_module, method_name):
30
+ raise NotImplementedError
31
+ except ModuleNotFoundError:
32
+ sys.exit(f'Frame processor {frame_processor} not found.')
33
+ except NotImplementedError:
34
+ sys.exit(f'Frame processor {frame_processor} not implemented correctly.')
35
+ return frame_processor_module
36
+
37
+
38
+ def get_frame_processors_modules(frame_processors: List[str]) -> List[ModuleType]:
39
+ global FRAME_PROCESSORS_MODULES
40
+
41
+ if not FRAME_PROCESSORS_MODULES:
42
+ for frame_processor in frame_processors:
43
+ frame_processor_module = load_frame_processor_module(frame_processor)
44
+ FRAME_PROCESSORS_MODULES.append(frame_processor_module)
45
+ return FRAME_PROCESSORS_MODULES
46
+
47
+
48
+ def multi_process_frame(source_path: str, temp_frame_paths: List[str], process_frames: Callable[[str, List[str], Any], None], update: Callable[[], None]) -> None:
49
+ with ThreadPoolExecutor(max_workers=roop.globals.execution_threads) as executor:
50
+ futures = []
51
+ queue = create_queue(temp_frame_paths)
52
+ queue_per_future = max(len(temp_frame_paths) // roop.globals.execution_threads, 1)
53
+ while not queue.empty():
54
+ future = executor.submit(process_frames, source_path, pick_queue(queue, queue_per_future), update)
55
+ futures.append(future)
56
+ for future in as_completed(futures):
57
+ future.result()
58
+
59
+
60
+ def create_queue(temp_frame_paths: List[str]) -> Queue[str]:
61
+ queue: Queue[str] = Queue()
62
+ for frame_path in temp_frame_paths:
63
+ queue.put(frame_path)
64
+ return queue
65
+
66
+
67
+ def pick_queue(queue: Queue[str], queue_per_future: int) -> List[str]:
68
+ queues = []
69
+ for _ in range(queue_per_future):
70
+ if not queue.empty():
71
+ queues.append(queue.get())
72
+ return queues
73
+
74
+
75
+ def process_video(source_path: str, frame_paths: list[str], process_frames: Callable[[str, List[str], Any], None]) -> None:
76
+ progress_bar_format = '{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]'
77
+ total = len(frame_paths)
78
+ with tqdm(total=total, desc='Processing', unit='frame', dynamic_ncols=True, bar_format=progress_bar_format) as progress:
79
+ multi_process_frame(source_path, frame_paths, process_frames, lambda: update_progress(progress))
80
+
81
+
82
+ def update_progress(progress: Any = None) -> None:
83
+ process = psutil.Process(os.getpid())
84
+ memory_usage = process.memory_info().rss / 1024 / 1024 / 1024
85
+ progress.set_postfix({
86
+ 'memory_usage': '{:.2f}'.format(memory_usage).zfill(5) + 'GB',
87
+ 'execution_providers': roop.globals.execution_providers,
88
+ 'execution_threads': roop.globals.execution_threads
89
+ })
90
+ progress.refresh()
91
+ progress.update(1)
roop/processors/frame/face_enhancer.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Callable
2
+ import cv2
3
+ import threading
4
+ from gfpgan.utils import GFPGANer
5
+
6
+ import roop.globals
7
+ import roop.processors.frame.core
8
+ from roop.core import update_status
9
+ from roop.face_analyser import get_many_faces
10
+ from roop.typing import Frame, Face
11
+ from roop.utilities import conditional_download, resolve_relative_path, is_image, is_video
12
+
13
+ FACE_ENHANCER = None
14
+ THREAD_SEMAPHORE = threading.Semaphore()
15
+ THREAD_LOCK = threading.Lock()
16
+ NAME = 'ROOP.FACE-ENHANCER'
17
+
18
+
19
+ def get_face_enhancer() -> Any:
20
+ global FACE_ENHANCER
21
+
22
+ with THREAD_LOCK:
23
+ if FACE_ENHANCER is None:
24
+ model_path = resolve_relative_path('../models/GFPGANv1.4.pth')
25
+ # todo: set models path -> https://github.com/TencentARC/GFPGAN/issues/399
26
+ FACE_ENHANCER = GFPGANer(model_path=model_path, upscale=1, device=get_device())
27
+ return FACE_ENHANCER
28
+
29
+
30
+ def get_device() -> str:
31
+ if 'CUDAExecutionProvider' in roop.globals.execution_providers:
32
+ return 'cuda'
33
+ if 'CoreMLExecutionProvider' in roop.globals.execution_providers:
34
+ return 'mps'
35
+ return 'cpu'
36
+
37
+
38
+ def clear_face_enhancer() -> None:
39
+ global FACE_ENHANCER
40
+
41
+ FACE_ENHANCER = None
42
+
43
+
44
+ def pre_check() -> bool:
45
+ download_directory_path = resolve_relative_path('../models')
46
+ conditional_download(download_directory_path, ['https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/GFPGANv1.4.pth'])
47
+ return True
48
+
49
+
50
+ def pre_start() -> bool:
51
+ if not is_image(roop.globals.target_path) and not is_video(roop.globals.target_path):
52
+ update_status('Select an image or video for target path.', NAME)
53
+ return False
54
+ return True
55
+
56
+
57
+ def post_process() -> None:
58
+ clear_face_enhancer()
59
+
60
+
61
+ def enhance_face(target_face: Face, temp_frame: Frame) -> Frame:
62
+ start_x, start_y, end_x, end_y = map(int, target_face['bbox'])
63
+ padding_x = int((end_x - start_x) * 0.5)
64
+ padding_y = int((end_y - start_y) * 0.5)
65
+ start_x = max(0, start_x - padding_x)
66
+ start_y = max(0, start_y - padding_y)
67
+ end_x = max(0, end_x + padding_x)
68
+ end_y = max(0, end_y + padding_y)
69
+ temp_face = temp_frame[start_y:end_y, start_x:end_x]
70
+ if temp_face.size:
71
+ with THREAD_SEMAPHORE:
72
+ _, _, temp_face = get_face_enhancer().enhance(
73
+ temp_face,
74
+ paste_back=True
75
+ )
76
+ temp_frame[start_y:end_y, start_x:end_x] = temp_face
77
+ return temp_frame
78
+
79
+
80
+ def process_frame(source_face: Face, reference_face: Face, temp_frame: Frame) -> Frame:
81
+ many_faces = get_many_faces(temp_frame)
82
+ if many_faces:
83
+ for target_face in many_faces:
84
+ temp_frame = enhance_face(target_face, temp_frame)
85
+ return temp_frame
86
+
87
+
88
+ def process_frames(source_path: str, temp_frame_paths: List[str], update: Callable[[], None]) -> None:
89
+ for temp_frame_path in temp_frame_paths:
90
+ temp_frame = cv2.imread(temp_frame_path)
91
+ result = process_frame(None, None, temp_frame)
92
+ cv2.imwrite(temp_frame_path, result)
93
+ if update:
94
+ update()
95
+
96
+
97
+ def process_image(source_path: str, target_path: str, output_path: str) -> None:
98
+ target_frame = cv2.imread(target_path)
99
+ result = process_frame(None, None, target_frame)
100
+ cv2.imwrite(output_path, result)
101
+
102
+
103
+ def process_video(source_path: str, temp_frame_paths: List[str]) -> None:
104
+ roop.processors.frame.core.process_video(None, temp_frame_paths, process_frames)
roop/processors/frame/face_swapper.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Callable
2
+ import cv2
3
+ import insightface
4
+ import threading
5
+ import requests
6
+ import os
7
+ import time
8
+
9
+ import roop.globals
10
+ import roop.processors.frame.core
11
+ from roop.core import update_status
12
+ from roop.face_analyser import get_one_face, get_many_faces
13
+ from roop.typing import Face, Frame
14
+ from roop.utilities import conditional_download, resolve_relative_path, is_image, is_video
15
+
16
+ FACE_SWAPPER = None
17
+ THREAD_LOCK = threading.Lock()
18
+ NAME = 'ROOP.FACE-SWAPPER'
19
+
20
+
21
+ def get_face_swapper() -> Any:
22
+ global FACE_SWAPPER
23
+
24
+ with THREAD_LOCK:
25
+ if FACE_SWAPPER is None:
26
+
27
+ model_path = resolve_relative_path('../inswapper_128.onnx')
28
+ found = os.path.exists(model_path)
29
+ print("La ruta se encontró:", found)
30
+ time.sleep(4)
31
+
32
+ if found is True:
33
+ print("Es verdad que la ruta si se encontró...")
34
+ else:
35
+ print("La ruta no se encontró por cierto...")
36
+ time.sleep(5)
37
+ print("Lo bajaré remotamente...")
38
+ #Ésta es la forma de bajarlo si no se encuentra en su ruta.
39
+ url = "https://huggingface.co/countfloyd/deepfake/resolve/main/inswapper_128.onnx"
40
+ response = requests.get(url)
41
+ content = response.content
42
+ path = "inswapper_128.onnx"
43
+ with open(path, "wb") as f:
44
+ f.write(content)
45
+ model_path = os.path.join(os.getcwd(), path)
46
+
47
+ #También Probar cuando esté arriba en huggingface, si con la ruta relativa llega.
48
+
49
+
50
+ FACE_SWAPPER = insightface.model_zoo.get_model(model_path, providers=roop.globals.execution_providers)
51
+
52
+ return FACE_SWAPPER
53
+
54
+
55
+ def pre_check() -> bool:
56
+ download_directory_path = resolve_relative_path('../content/roop')
57
+ #Al parecer ésto no se usa.
58
+ conditional_download(download_directory_path, ['https://huggingface.co/countfloyd/deepfake/resolve/main/inswapper_128.onnx'])
59
+ return True
60
+
61
+
62
+ def pre_start() -> bool:
63
+ if not is_image(roop.globals.source_path):
64
+ update_status('Select an image for source path.', NAME)
65
+ return False
66
+ elif not get_one_face(cv2.imread(roop.globals.source_path)):
67
+ update_status('No face in source path detected.', NAME)
68
+ return False
69
+ if not is_image(roop.globals.target_path) and not is_video(roop.globals.target_path):
70
+ update_status('Select an image or video for target path.', NAME)
71
+ return False
72
+ return True
73
+
74
+
75
+ def post_process() -> None:
76
+ global FACE_SWAPPER
77
+
78
+ FACE_SWAPPER = None
79
+
80
+
81
+ def swap_face(source_face: Face, target_face: Face, temp_frame: Frame) -> Frame:
82
+ return get_face_swapper().get(temp_frame, target_face, source_face, paste_back=True)
83
+
84
+
85
+ def process_frame(source_face: Face, temp_frame: Frame) -> Frame:
86
+ if roop.globals.many_faces:
87
+ if many_faces := get_many_faces(temp_frame):
88
+ for target_face in many_faces:
89
+ temp_frame = swap_face(source_face, target_face, temp_frame)
90
+ elif target_face := get_one_face(temp_frame):
91
+ temp_frame = swap_face(source_face, target_face, temp_frame)
92
+ return temp_frame
93
+
94
+
95
+ def process_frames(source_path: str, temp_frame_paths: List[str], update: Callable[[], None]) -> None:
96
+ source_face = get_one_face(cv2.imread(source_path))
97
+ for temp_frame_path in temp_frame_paths:
98
+ temp_frame = cv2.imread(temp_frame_path)
99
+ result = process_frame(source_face, temp_frame)
100
+ cv2.imwrite(temp_frame_path, result)
101
+ if update:
102
+ update()
103
+
104
+
105
+ def process_image(source_path: str, target_path: str, output_path: str) -> None:
106
+ source_face = get_one_face(cv2.imread(source_path))
107
+ target_frame = cv2.imread(target_path)
108
+ result = process_frame(source_face, target_frame)
109
+ cv2.imwrite(output_path, result)
110
+
111
+
112
+ def process_video(source_path: str, temp_frame_paths: List[str]) -> None:
113
+ roop.processors.frame.core.process_video(source_path, temp_frame_paths, process_frames)
roop/typing.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ from insightface.app.common import Face
4
+ import numpy
5
+
6
+ Face = Face
7
+ Frame = numpy.ndarray[Any, Any]
roop/ui.json ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "CTk": {
3
+ "fg_color": ["gray95", "gray10"]
4
+ },
5
+ "CTkToplevel": {
6
+ "fg_color": ["gray95", "gray10"]
7
+ },
8
+ "CTkFrame": {
9
+ "corner_radius": 6,
10
+ "border_width": 0,
11
+ "fg_color": ["gray90", "gray13"],
12
+ "top_fg_color": ["gray85", "gray16"],
13
+ "border_color": ["gray65", "gray28"]
14
+ },
15
+ "CTkButton": {
16
+ "corner_radius": 6,
17
+ "border_width": 0,
18
+ "fg_color": ["#3a7ebf", "#1f538d"],
19
+ "hover_color": ["#325882", "#14375e"],
20
+ "border_color": ["#3E454A", "#949A9F"],
21
+ "text_color": ["#DCE4EE", "#DCE4EE"],
22
+ "text_color_disabled": ["gray74", "gray60"]
23
+ },
24
+ "CTkLabel": {
25
+ "corner_radius": 0,
26
+ "fg_color": "transparent",
27
+ "text_color": ["gray14", "gray84"]
28
+ },
29
+ "CTkEntry": {
30
+ "corner_radius": 6,
31
+ "border_width": 2,
32
+ "fg_color": ["#F9F9FA", "#343638"],
33
+ "border_color": ["#979DA2", "#565B5E"],
34
+ "text_color": ["gray14", "gray84"],
35
+ "placeholder_text_color": ["gray52", "gray62"]
36
+ },
37
+ "CTkCheckbox": {
38
+ "corner_radius": 6,
39
+ "border_width": 3,
40
+ "fg_color": ["#3a7ebf", "#1f538d"],
41
+ "border_color": ["#3E454A", "#949A9F"],
42
+ "hover_color": ["#325882", "#14375e"],
43
+ "checkmark_color": ["#DCE4EE", "gray90"],
44
+ "text_color": ["gray14", "gray84"],
45
+ "text_color_disabled": ["gray60", "gray45"]
46
+ },
47
+ "CTkSwitch": {
48
+ "corner_radius": 1000,
49
+ "border_width": 3,
50
+ "button_length": 0,
51
+ "fg_color": ["#939BA2", "#4A4D50"],
52
+ "progress_color": ["#3a7ebf", "#1f538d"],
53
+ "button_color": ["gray36", "#D5D9DE"],
54
+ "button_hover_color": ["gray20", "gray100"],
55
+ "text_color": ["gray14", "gray84"],
56
+ "text_color_disabled": ["gray60", "gray45"]
57
+ },
58
+ "CTkRadiobutton": {
59
+ "corner_radius": 1000,
60
+ "border_width_checked": 6,
61
+ "border_width_unchecked": 3,
62
+ "fg_color": ["#3a7ebf", "#1f538d"],
63
+ "border_color": ["#3E454A", "#949A9F"],
64
+ "hover_color": ["#325882", "#14375e"],
65
+ "text_color": ["gray14", "gray84"],
66
+ "text_color_disabled": ["gray60", "gray45"]
67
+ },
68
+ "CTkProgressBar": {
69
+ "corner_radius": 1000,
70
+ "border_width": 0,
71
+ "fg_color": ["#939BA2", "#4A4D50"],
72
+ "progress_color": ["#3a7ebf", "#1f538d"],
73
+ "border_color": ["gray", "gray"]
74
+ },
75
+ "CTkSlider": {
76
+ "corner_radius": 1000,
77
+ "button_corner_radius": 1000,
78
+ "border_width": 6,
79
+ "button_length": 0,
80
+ "fg_color": ["#939BA2", "#4A4D50"],
81
+ "progress_color": ["gray40", "#AAB0B5"],
82
+ "button_color": ["#3a7ebf", "#1f538d"],
83
+ "button_hover_color": ["#325882", "#14375e"]
84
+ },
85
+ "CTkOptionMenu": {
86
+ "corner_radius": 6,
87
+ "fg_color": ["#3a7ebf", "#1f538d"],
88
+ "button_color": ["#325882", "#14375e"],
89
+ "button_hover_color": ["#234567", "#1e2c40"],
90
+ "text_color": ["#DCE4EE", "#DCE4EE"],
91
+ "text_color_disabled": ["gray74", "gray60"]
92
+ },
93
+ "CTkComboBox": {
94
+ "corner_radius": 6,
95
+ "border_width": 2,
96
+ "fg_color": ["#F9F9FA", "#343638"],
97
+ "border_color": ["#979DA2", "#565B5E"],
98
+ "button_color": ["#979DA2", "#565B5E"],
99
+ "button_hover_color": ["#6E7174", "#7A848D"],
100
+ "text_color": ["gray14", "gray84"],
101
+ "text_color_disabled": ["gray50", "gray45"]
102
+ },
103
+ "CTkScrollbar": {
104
+ "corner_radius": 1000,
105
+ "border_spacing": 4,
106
+ "fg_color": "transparent",
107
+ "button_color": ["gray55", "gray41"],
108
+ "button_hover_color": ["gray40", "gray53"]
109
+ },
110
+ "CTkSegmentedButton": {
111
+ "corner_radius": 6,
112
+ "border_width": 2,
113
+ "fg_color": ["#979DA2", "gray29"],
114
+ "selected_color": ["#3a7ebf", "#1f538d"],
115
+ "selected_hover_color": ["#325882", "#14375e"],
116
+ "unselected_color": ["#979DA2", "gray29"],
117
+ "unselected_hover_color": ["gray70", "gray41"],
118
+ "text_color": ["#DCE4EE", "#DCE4EE"],
119
+ "text_color_disabled": ["gray74", "gray60"]
120
+ },
121
+ "CTkTextbox": {
122
+ "corner_radius": 6,
123
+ "border_width": 0,
124
+ "fg_color": ["gray100", "gray20"],
125
+ "border_color": ["#979DA2", "#565B5E"],
126
+ "text_color": ["gray14", "gray84"],
127
+ "scrollbar_button_color": ["gray55", "gray41"],
128
+ "scrollbar_button_hover_color": ["gray40", "gray53"]
129
+ },
130
+ "CTkScrollableFrame": {
131
+ "label_fg_color": ["gray80", "gray21"]
132
+ },
133
+ "DropdownMenu": {
134
+ "fg_color": ["gray90", "gray20"],
135
+ "hover_color": ["gray75", "gray28"],
136
+ "text_color": ["gray14", "gray84"]
137
+ },
138
+ "CTkFont": {
139
+ "macOS": {
140
+ "family": "Avenir",
141
+ "size": 12,
142
+ "weight": "normal"
143
+ },
144
+ "Windows": {
145
+ "family": "Corbel",
146
+ "size": 12,
147
+ "weight": "normal"
148
+ },
149
+ "Linux": {
150
+ "family": "Montserrat",
151
+ "size": 12,
152
+ "weight": "normal"
153
+ }
154
+ },
155
+ "RoopDropArea": {
156
+ "fg_color": ["gray90", "gray13"]
157
+ },
158
+ "RoopDonate": {
159
+ "text_color": ["#3a7ebf", "gray60"]
160
+ }
161
+ }
roop/ui.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import webbrowser
4
+ import customtkinter as ctk
5
+ from tkinterdnd2 import TkinterDnD, DND_ALL
6
+ from typing import Any, Callable, Tuple, Optional
7
+ import cv2
8
+ from PIL import Image, ImageOps
9
+
10
+ import roop.globals
11
+ import roop.metadata
12
+ from roop.face_analyser import get_one_face
13
+ from roop.capturer import get_video_frame, get_video_frame_total
14
+ from roop.face_reference import get_face_reference, set_face_reference, clear_face_reference
15
+ from roop.predictor import predict_frame, clear_predictor
16
+ from roop.processors.frame.core import get_frame_processors_modules
17
+ from roop.utilities import is_image, is_video, resolve_relative_path
18
+
19
+ ROOT = None
20
+ ROOT_HEIGHT = 700
21
+ ROOT_WIDTH = 600
22
+
23
+ PREVIEW = None
24
+ PREVIEW_MAX_HEIGHT = 700
25
+ PREVIEW_MAX_WIDTH = 1200
26
+
27
+ RECENT_DIRECTORY_SOURCE = None
28
+ RECENT_DIRECTORY_TARGET = None
29
+ RECENT_DIRECTORY_OUTPUT = None
30
+
31
+ preview_label = None
32
+ preview_slider = None
33
+ source_label = None
34
+ target_label = None
35
+ status_label = None
36
+
37
+
38
+ # todo: remove by native support -> https://github.com/TomSchimansky/CustomTkinter/issues/934
39
+ class CTk(ctk.CTk, TkinterDnD.DnDWrapper):
40
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
41
+ super().__init__(*args, **kwargs)
42
+ self.TkdndVersion = TkinterDnD._require(self)
43
+
44
+
45
+ def init(start: Callable[[], None], destroy: Callable[[], None]) -> ctk.CTk:
46
+ global ROOT, PREVIEW
47
+
48
+ ROOT = create_root(start, destroy)
49
+ PREVIEW = create_preview(ROOT)
50
+
51
+ return ROOT
52
+
53
+
54
+ def create_root(start: Callable[[], None], destroy: Callable[[], None]) -> ctk.CTk:
55
+ global source_label, target_label, status_label
56
+
57
+ ctk.deactivate_automatic_dpi_awareness()
58
+ ctk.set_appearance_mode('system')
59
+ ctk.set_default_color_theme(resolve_relative_path('ui.json'))
60
+
61
+ root = CTk()
62
+ root.minsize(ROOT_WIDTH, ROOT_HEIGHT)
63
+ root.title(f'{roop.metadata.name} {roop.metadata.version}')
64
+ root.configure()
65
+ root.protocol('WM_DELETE_WINDOW', lambda: destroy())
66
+
67
+ source_label = ctk.CTkLabel(root, text=None, fg_color=ctk.ThemeManager.theme.get('RoopDropArea').get('fg_color'))
68
+ source_label.place(relx=0.1, rely=0.1, relwidth=0.3, relheight=0.25)
69
+ source_label.drop_target_register(DND_ALL)
70
+ source_label.dnd_bind('<<Drop>>', lambda event: select_source_path(event.data))
71
+ if roop.globals.source_path:
72
+ select_source_path(roop.globals.source_path)
73
+
74
+ target_label = ctk.CTkLabel(root, text=None, fg_color=ctk.ThemeManager.theme.get('RoopDropArea').get('fg_color'))
75
+ target_label.place(relx=0.6, rely=0.1, relwidth=0.3, relheight=0.25)
76
+ target_label.drop_target_register(DND_ALL)
77
+ target_label.dnd_bind('<<Drop>>', lambda event: select_target_path(event.data))
78
+ if roop.globals.target_path:
79
+ select_target_path(roop.globals.target_path)
80
+
81
+ source_button = ctk.CTkButton(root, text='Select a face', cursor='hand2', command=lambda: select_source_path())
82
+ source_button.place(relx=0.1, rely=0.4, relwidth=0.3, relheight=0.1)
83
+
84
+ target_button = ctk.CTkButton(root, text='Select a target', cursor='hand2', command=lambda: select_target_path())
85
+ target_button.place(relx=0.6, rely=0.4, relwidth=0.3, relheight=0.1)
86
+
87
+ keep_fps_value = ctk.BooleanVar(value=roop.globals.keep_fps)
88
+ keep_fps_checkbox = ctk.CTkSwitch(root, text='Keep target fps', variable=keep_fps_value, cursor='hand2', command=lambda: setattr(roop.globals, 'keep_fps', not roop.globals.keep_fps))
89
+ keep_fps_checkbox.place(relx=0.1, rely=0.6)
90
+
91
+ keep_frames_value = ctk.BooleanVar(value=roop.globals.keep_frames)
92
+ keep_frames_switch = ctk.CTkSwitch(root, text='Keep temporary frames', variable=keep_frames_value, cursor='hand2', command=lambda: setattr(roop.globals, 'keep_frames', keep_frames_value.get()))
93
+ keep_frames_switch.place(relx=0.1, rely=0.65)
94
+
95
+ skip_audio_value = ctk.BooleanVar(value=roop.globals.skip_audio)
96
+ skip_audio_switch = ctk.CTkSwitch(root, text='Skip target audio', variable=skip_audio_value, cursor='hand2', command=lambda: setattr(roop.globals, 'skip_audio', skip_audio_value.get()))
97
+ skip_audio_switch.place(relx=0.6, rely=0.6)
98
+
99
+ many_faces_value = ctk.BooleanVar(value=roop.globals.many_faces)
100
+ many_faces_switch = ctk.CTkSwitch(root, text='Many faces', variable=many_faces_value, cursor='hand2', command=lambda: setattr(roop.globals, 'many_faces', many_faces_value.get()))
101
+ many_faces_switch.place(relx=0.6, rely=0.65)
102
+
103
+ start_button = ctk.CTkButton(root, text='Start', cursor='hand2', command=lambda: select_output_path(start))
104
+ start_button.place(relx=0.15, rely=0.75, relwidth=0.2, relheight=0.05)
105
+
106
+ stop_button = ctk.CTkButton(root, text='Destroy', cursor='hand2', command=lambda: destroy())
107
+ stop_button.place(relx=0.4, rely=0.75, relwidth=0.2, relheight=0.05)
108
+
109
+ preview_button = ctk.CTkButton(root, text='Preview', cursor='hand2', command=lambda: toggle_preview())
110
+ preview_button.place(relx=0.65, rely=0.75, relwidth=0.2, relheight=0.05)
111
+
112
+ status_label = ctk.CTkLabel(root, text=None, justify='center')
113
+ status_label.place(relx=0.1, rely=0.9, relwidth=0.8)
114
+
115
+ donate_label = ctk.CTkLabel(root, text='^_^ Donate to project ^_^', justify='center', cursor='hand2')
116
+ donate_label.place(relx=0.1, rely=0.95, relwidth=0.8)
117
+ donate_label.configure(text_color=ctk.ThemeManager.theme.get('RoopDonate').get('text_color'))
118
+ donate_label.bind('<Button>', lambda event: webbrowser.open('https://github.com/sponsors/s0md3v'))
119
+
120
+ return root
121
+
122
+
123
+ def create_preview(parent: ctk.CTkToplevel) -> ctk.CTkToplevel:
124
+ global preview_label, preview_slider
125
+
126
+ preview = ctk.CTkToplevel(parent)
127
+ preview.withdraw()
128
+ preview.configure()
129
+ preview.protocol('WM_DELETE_WINDOW', lambda: toggle_preview())
130
+ preview.resizable(width=False, height=False)
131
+
132
+ preview_label = ctk.CTkLabel(preview, text=None)
133
+ preview_label.pack(fill='both', expand=True)
134
+
135
+ preview_slider = ctk.CTkSlider(preview, from_=0, to=0, command=lambda frame_value: update_preview(frame_value))
136
+
137
+ preview.bind('<Up>', lambda event: update_face_reference(1))
138
+ preview.bind('<Down>', lambda event: update_face_reference(-1))
139
+ return preview
140
+
141
+
142
+ def update_status(text: str) -> None:
143
+ status_label.configure(text=text)
144
+ ROOT.update()
145
+
146
+
147
+ def select_source_path(source_path: Optional[str] = None) -> None:
148
+ global RECENT_DIRECTORY_SOURCE
149
+
150
+ if PREVIEW:
151
+ PREVIEW.withdraw()
152
+ if source_path is None:
153
+ source_path = ctk.filedialog.askopenfilename(title='select an source image', initialdir=RECENT_DIRECTORY_SOURCE)
154
+ if is_image(source_path):
155
+ roop.globals.source_path = source_path
156
+ RECENT_DIRECTORY_SOURCE = os.path.dirname(roop.globals.source_path)
157
+ image = render_image_preview(roop.globals.source_path, (200, 200))
158
+ source_label.configure(image=image)
159
+ else:
160
+ roop.globals.source_path = None
161
+ source_label.configure(image=None)
162
+
163
+
164
+ def select_target_path(target_path: Optional[str] = None) -> None:
165
+ global RECENT_DIRECTORY_TARGET
166
+
167
+ if PREVIEW:
168
+ PREVIEW.withdraw()
169
+ clear_face_reference()
170
+ if target_path is None:
171
+ target_path = ctk.filedialog.askopenfilename(title='select an target image or video', initialdir=RECENT_DIRECTORY_TARGET)
172
+ if is_image(target_path):
173
+ roop.globals.target_path = target_path
174
+ RECENT_DIRECTORY_TARGET = os.path.dirname(roop.globals.target_path)
175
+ image = render_image_preview(roop.globals.target_path, (200, 200))
176
+ target_label.configure(image=image)
177
+ elif is_video(target_path):
178
+ roop.globals.target_path = target_path
179
+ RECENT_DIRECTORY_TARGET = os.path.dirname(roop.globals.target_path)
180
+ video_frame = render_video_preview(target_path, (200, 200))
181
+ target_label.configure(image=video_frame)
182
+ else:
183
+ roop.globals.target_path = None
184
+ target_label.configure(image=None)
185
+
186
+
187
+ def select_output_path(start: Callable[[], None]) -> None:
188
+ global RECENT_DIRECTORY_OUTPUT
189
+
190
+ if is_image(roop.globals.target_path):
191
+ output_path = ctk.filedialog.asksaveasfilename(title='save image output file', defaultextension='.png', initialfile='output.png', initialdir=RECENT_DIRECTORY_OUTPUT)
192
+ elif is_video(roop.globals.target_path):
193
+ output_path = ctk.filedialog.asksaveasfilename(title='save video output file', defaultextension='.mp4', initialfile='output.mp4', initialdir=RECENT_DIRECTORY_OUTPUT)
194
+ else:
195
+ output_path = None
196
+ if output_path:
197
+ roop.globals.output_path = output_path
198
+ RECENT_DIRECTORY_OUTPUT = os.path.dirname(roop.globals.output_path)
199
+ start()
200
+
201
+
202
+ def render_image_preview(image_path: str, size: Tuple[int, int]) -> ctk.CTkImage:
203
+ image = Image.open(image_path)
204
+ if size:
205
+ image = ImageOps.fit(image, size, Image.LANCZOS)
206
+ return ctk.CTkImage(image, size=image.size)
207
+
208
+
209
+ def render_video_preview(video_path: str, size: Tuple[int, int], frame_number: int = 0) -> ctk.CTkImage:
210
+ capture = cv2.VideoCapture(video_path)
211
+ if frame_number:
212
+ capture.set(cv2.CAP_PROP_POS_FRAMES, frame_number)
213
+ has_frame, frame = capture.read()
214
+ if has_frame:
215
+ image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
216
+ if size:
217
+ image = ImageOps.fit(image, size, Image.LANCZOS)
218
+ return ctk.CTkImage(image, size=image.size)
219
+ capture.release()
220
+ cv2.destroyAllWindows()
221
+
222
+
223
+ def toggle_preview() -> None:
224
+ if PREVIEW.state() == 'normal':
225
+ PREVIEW.unbind('<Right>')
226
+ PREVIEW.unbind('<Left>')
227
+ PREVIEW.withdraw()
228
+ clear_predictor()
229
+ elif roop.globals.source_path and roop.globals.target_path:
230
+ init_preview()
231
+ update_preview(roop.globals.reference_frame_number)
232
+ PREVIEW.deiconify()
233
+
234
+
235
+ def init_preview() -> None:
236
+ PREVIEW.title('Preview [ ↕ Reference face ]')
237
+ if is_image(roop.globals.target_path):
238
+ preview_slider.pack_forget()
239
+ if is_video(roop.globals.target_path):
240
+ video_frame_total = get_video_frame_total(roop.globals.target_path)
241
+ if video_frame_total > 0:
242
+ PREVIEW.title('Preview [ ↕ Reference face ] [ ↔ Frame number ]')
243
+ PREVIEW.bind('<Right>', lambda event: update_frame(int(video_frame_total / 20)))
244
+ PREVIEW.bind('<Left>', lambda event: update_frame(int(video_frame_total / -20)))
245
+ preview_slider.configure(to=video_frame_total)
246
+ preview_slider.pack(fill='x')
247
+ preview_slider.set(roop.globals.reference_frame_number)
248
+
249
+
250
+ def update_preview(frame_number: int = 0) -> None:
251
+ if roop.globals.source_path and roop.globals.target_path:
252
+ temp_frame = get_video_frame(roop.globals.target_path, frame_number)
253
+ if predict_frame(temp_frame):
254
+ sys.exit()
255
+ source_face = get_one_face(cv2.imread(roop.globals.source_path))
256
+ if not get_face_reference():
257
+ reference_frame = get_video_frame(roop.globals.target_path, roop.globals.reference_frame_number)
258
+ reference_face = get_one_face(reference_frame, roop.globals.reference_face_position)
259
+ set_face_reference(reference_face)
260
+ else:
261
+ reference_face = get_face_reference()
262
+ for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
263
+ temp_frame = frame_processor.process_frame(
264
+ source_face,
265
+ reference_face,
266
+ temp_frame
267
+ )
268
+ image = Image.fromarray(cv2.cvtColor(temp_frame, cv2.COLOR_BGR2RGB))
269
+ image = ImageOps.contain(image, (PREVIEW_MAX_WIDTH, PREVIEW_MAX_HEIGHT), Image.LANCZOS)
270
+ image = ctk.CTkImage(image, size=image.size)
271
+ preview_label.configure(image=image)
272
+
273
+
274
+ def update_face_reference(steps: int) -> None:
275
+ clear_face_reference()
276
+ reference_frame_number = int(preview_slider.get())
277
+ roop.globals.reference_face_position += steps
278
+ roop.globals.reference_frame_number = reference_frame_number
279
+ update_preview(reference_frame_number)
280
+
281
+
282
+ def update_frame(steps: int) -> None:
283
+ frame_number = preview_slider.get() + steps
284
+ preview_slider.set(frame_number)
285
+ update_preview(preview_slider.get())
roop/utilities.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import time
3
+ import glob
4
+ import mimetypes
5
+ import os
6
+ import platform
7
+ import shutil
8
+ import ssl
9
+ import subprocess
10
+ import urllib
11
+ from pathlib import Path
12
+ from typing import List, Optional
13
+ from tqdm import tqdm
14
+
15
+ import roop.globals
16
+
17
+ TEMP_DIRECTORY = 'temp'
18
+ TEMP_VIDEO_FILE = 'temp.mp4'
19
+
20
+ # monkey patch ssl for mac
21
+ if platform.system().lower() == 'darwin':
22
+ ssl._create_default_https_context = ssl._create_unverified_context
23
+
24
+
25
+ def run_ffmpeg(args: List[str]) -> bool:
26
+ print("MOI: Entré a run_ffmpeg...")
27
+ commands = ['ffmpeg', '-hide_banner', '-loglevel', roop.globals.log_level]
28
+ commands.extend(args)
29
+ try:
30
+ print("MOI: Estoy en el try del subproceso.")
31
+ subprocess.check_output(commands, stderr=subprocess.STDOUT)
32
+ return True
33
+ except Exception:
34
+ print("Moi: Imprimiendo el error...")
35
+ print(sys.exc_info()[0])
36
+ pass
37
+ return False
38
+
39
+
40
+ def detect_fps(target_path: str) -> float:
41
+ command = ['ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=r_frame_rate', '-of', 'default=noprint_wrappers=1:nokey=1', target_path]
42
+ output = subprocess.check_output(command).decode().strip().split('/')
43
+ try:
44
+ numerator, denominator = map(int, output)
45
+ return numerator / denominator
46
+ except Exception:
47
+ pass
48
+ return 30
49
+
50
+
51
+ def extract_frames(target_path: str, fps: float = 30) -> bool:
52
+ temp_directory_path = get_temp_directory_path(target_path)
53
+ temp_frame_quality = roop.globals.temp_frame_quality * 31 // 100
54
+ return run_ffmpeg(['-hwaccel', 'auto', '-i', target_path, '-q:v', str(temp_frame_quality), '-pix_fmt', 'rgb24', '-vf', 'fps=' + str(fps), os.path.join(temp_directory_path, '%04d.' + roop.globals.temp_frame_format)])
55
+
56
+
57
+ def create_video(target_path: str, fps: float = 30) -> bool:
58
+ temp_output_path = get_temp_output_path(target_path)
59
+ temp_directory_path = get_temp_directory_path(target_path)
60
+ output_video_quality = (roop.globals.output_video_quality + 1) * 51 // 100
61
+ commands = ['-hwaccel', 'auto', '-r', str(fps), '-i', os.path.join(temp_directory_path, '%04d.' + roop.globals.temp_frame_format), '-c:v', roop.globals.output_video_encoder]
62
+ if roop.globals.output_video_encoder in ['libx264', 'libx265', 'libvpx']:
63
+ commands.extend(['-crf', str(output_video_quality)])
64
+ if roop.globals.output_video_encoder in ['h264_nvenc', 'hevc_nvenc']:
65
+ commands.extend(['-cq', str(output_video_quality)])
66
+ commands.extend(['-pix_fmt', 'yuv420p', '-vf', 'colorspace=bt709:iall=bt601-6-625:fast=1', '-y', temp_output_path])
67
+
68
+ print("Y así quedan los commands:", commands)
69
+ time.sleep(4)
70
+ print("MOI: Y se supone que aquí estará a punto de crear el video:")
71
+ time.sleep(4)
72
+
73
+ # while True:
74
+ # # Imprime un mensaje
75
+ # print("Pulsa la tecla Y para hacer el video...")
76
+
77
+ # # Espera un segundo
78
+ # time.sleep(1)
79
+
80
+ # # Lee un carácter de la entrada estándar
81
+ # key = input()
82
+
83
+ # # Si se presiona la tecla Y, sale del bucle
84
+ # if key == "Y":
85
+ # break
86
+
87
+ return run_ffmpeg(commands)
88
+
89
+
90
+ def restore_audio(target_path: str, output_path: str) -> None:
91
+ print("MOI: Estamos en restore_audio...")
92
+ print("Los parámetros recibidos son:")
93
+ print("target_path:", target_path)
94
+ time.sleep(1)
95
+ print("output_path:", output_path)
96
+ temp_output_path = get_temp_output_path(target_path)
97
+ print("MOI: Éste es el temp_output_path, es audio o video?:")
98
+ print(temp_output_path)
99
+ time.sleep(1)
100
+
101
+ try:
102
+ args = ['-i', temp_output_path, '-i', target_path, '-c:v', 'copy', '-map', '0:v:0', '-map', '1:a:0', '-y', output_path]
103
+ print("Estos son los args de audio:")
104
+ time.sleep(2)
105
+ print(args)
106
+ time.sleep(10)
107
+ done = run_ffmpeg(args)
108
+ #done = run_ffmpeg(['-i', temp_output_path, '-i', target_path, '-c:v', 'copy', '-map', '0:v:0', '-map', '1:a:0', '-y', output_path])
109
+
110
+ except:
111
+ print("Ocurrió un error")
112
+ print(sys.exc_info()[0])
113
+
114
+ if not done:
115
+ move_temp(target_path, output_path)
116
+ print("Entre a not done :(")
117
+ print("Terminé audio...")
118
+ time.sleep(3)
119
+
120
+
121
+ def get_temp_frame_paths(target_path: str) -> List[str]:
122
+ temp_directory_path = get_temp_directory_path(target_path)
123
+ return glob.glob((os.path.join(glob.escape(temp_directory_path), '*.' + roop.globals.temp_frame_format)))
124
+
125
+
126
+ def get_temp_directory_path(target_path: str) -> str:
127
+ target_name, _ = os.path.splitext(os.path.basename(target_path))
128
+ target_directory_path = os.path.dirname(target_path)
129
+ return os.path.join(target_directory_path, TEMP_DIRECTORY, target_name)
130
+
131
+
132
+ def get_temp_output_path(target_path: str) -> str:
133
+ temp_directory_path = get_temp_directory_path(target_path)
134
+ return os.path.join(temp_directory_path, TEMP_VIDEO_FILE)
135
+
136
+
137
+ def normalize_output_path(source_path: str, target_path: str, output_path: str) -> Optional[str]:
138
+ if source_path and target_path and output_path:
139
+ source_name, _ = os.path.splitext(os.path.basename(source_path))
140
+ target_name, target_extension = os.path.splitext(os.path.basename(target_path))
141
+ if os.path.isdir(output_path):
142
+ return os.path.join(output_path, source_name + '-' + target_name + target_extension)
143
+ return output_path
144
+
145
+
146
+ def create_temp(target_path: str) -> None:
147
+ temp_directory_path = get_temp_directory_path(target_path)
148
+ Path(temp_directory_path).mkdir(parents=True, exist_ok=True)
149
+
150
+
151
+ def move_temp(target_path: str, output_path: str) -> None:
152
+ temp_output_path = get_temp_output_path(target_path)
153
+ if os.path.isfile(temp_output_path):
154
+ if os.path.isfile(output_path):
155
+ os.remove(output_path)
156
+ shutil.move(temp_output_path, output_path)
157
+
158
+
159
+ def clean_temp(target_path: str) -> None:
160
+ temp_directory_path = get_temp_directory_path(target_path)
161
+ parent_directory_path = os.path.dirname(temp_directory_path)
162
+ if not roop.globals.keep_frames and os.path.isdir(temp_directory_path):
163
+ shutil.rmtree(temp_directory_path)
164
+ if os.path.exists(parent_directory_path) and not os.listdir(parent_directory_path):
165
+ os.rmdir(parent_directory_path)
166
+
167
+
168
+ def has_image_extension(image_path: str) -> bool:
169
+ return image_path.lower().endswith(('png', 'jpg', 'jpeg', 'webp'))
170
+
171
+
172
+ def is_image(image_path: str) -> bool:
173
+ if image_path and os.path.isfile(image_path):
174
+ mimetype, _ = mimetypes.guess_type(image_path)
175
+ return bool(mimetype and mimetype.startswith('image/'))
176
+ return False
177
+
178
+
179
+ def is_video(video_path: str) -> bool:
180
+ if video_path and os.path.isfile(video_path):
181
+ mimetype, _ = mimetypes.guess_type(video_path)
182
+ return bool(mimetype and mimetype.startswith('video/'))
183
+ return False
184
+
185
+
186
+ def conditional_download(download_directory_path: str, urls: List[str]) -> None:
187
+ if not os.path.exists(download_directory_path):
188
+ os.makedirs(download_directory_path)
189
+ for url in urls:
190
+ download_file_path = os.path.join(download_directory_path, os.path.basename(url))
191
+ if not os.path.exists(download_file_path):
192
+ request = urllib.request.urlopen(url) # type: ignore[attr-defined]
193
+ total = int(request.headers.get('Content-Length', 0))
194
+ with tqdm(total=total, desc='Downloading', unit='B', unit_scale=True, unit_divisor=1024) as progress:
195
+ urllib.request.urlretrieve(url, download_file_path, reporthook=lambda count, block_size, total_size: progress.update(block_size)) # type: ignore[attr-defined]
196
+
197
+
198
+ def resolve_relative_path(path: str) -> str:
199
+ return os.path.abspath(os.path.join(os.path.dirname(__file__), path))