Upload 55 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- app_context.py +18 -0
- args.py +120 -0
- audio.py +143 -0
- benchmarker.py +111 -0
- camera_manager.py +53 -0
- choices.py +177 -0
- cli_helper.py +35 -0
- common_helper.py +90 -0
- conda.py +41 -0
- config.py +65 -0
- content_analyser.py +245 -0
- core.py +339 -0
- curl_builder.py +32 -0
- download.py +178 -0
- execution.py +194 -0
- exit_helper.py +34 -0
- face_classifier.py +140 -0
- face_creator.py +210 -0
- face_detector.py +458 -0
- face_helper.py +276 -0
- face_landmarker.py +240 -0
- face_masker.py +279 -0
- face_recognizer.py +93 -0
- face_selector.py +155 -0
- face_store.py +41 -0
- face_tracker.py +61 -0
- ffmpeg.py +360 -0
- ffmpeg_builder.py +309 -0
- ffprobe.py +130 -0
- ffprobe_builder.py +33 -0
- filesystem.py +190 -0
- frame_store.py +35 -0
- hash_helper.py +32 -0
- inference_manager.py +115 -0
- installer.py +74 -0
- json.py +22 -0
- locales.py +276 -0
- logger.py +48 -0
- metadata.py +15 -0
- model_helper.py +11 -0
- normalizer.py +33 -0
- process_manager.py +45 -0
- program.py +348 -0
- program_helper.py +31 -0
- sanitizer.py +21 -0
- state_manager.py +42 -0
- streamer.py +99 -0
- temp_helper.py +47 -0
- thread_helper.py +24 -0
- time_helper.py +33 -0
app_context.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
from facefusion.types import AppContext
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def detect_app_context() -> AppContext:
|
| 8 |
+
jobs_path = os.path.join('facefusion', 'jobs')
|
| 9 |
+
uis_path = os.path.join('facefusion', 'uis')
|
| 10 |
+
frame = sys._getframe(1)
|
| 11 |
+
|
| 12 |
+
while frame:
|
| 13 |
+
if jobs_path in frame.f_code.co_filename:
|
| 14 |
+
return 'cli'
|
| 15 |
+
if uis_path in frame.f_code.co_filename:
|
| 16 |
+
return 'ui'
|
| 17 |
+
frame = frame.f_back
|
| 18 |
+
return 'cli'
|
args.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from facefusion import state_manager
|
| 2 |
+
from facefusion.filesystem import get_file_name, is_video, resolve_file_paths
|
| 3 |
+
from facefusion.jobs import job_store
|
| 4 |
+
from facefusion.normalizer import normalize_fps, normalize_space
|
| 5 |
+
from facefusion.processors.core import get_processors_modules
|
| 6 |
+
from facefusion.types import ApplyStateItem, Args
|
| 7 |
+
from facefusion.vision import detect_video_fps
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
|
| 11 |
+
apply_state_item('command', args.get('command'))
|
| 12 |
+
apply_state_item('temp_path', args.get('temp_path'))
|
| 13 |
+
apply_state_item('jobs_path', args.get('jobs_path'))
|
| 14 |
+
apply_state_item('source_paths', args.get('source_paths'))
|
| 15 |
+
apply_state_item('target_path', args.get('target_path'))
|
| 16 |
+
apply_state_item('output_path', args.get('output_path'))
|
| 17 |
+
apply_state_item('source_pattern', args.get('source_pattern'))
|
| 18 |
+
apply_state_item('target_pattern', args.get('target_pattern'))
|
| 19 |
+
apply_state_item('output_pattern', args.get('output_pattern'))
|
| 20 |
+
apply_state_item('face_detector_model', args.get('face_detector_model'))
|
| 21 |
+
apply_state_item('face_detector_size', args.get('face_detector_size'))
|
| 22 |
+
apply_state_item('face_detector_margin', normalize_space(args.get('face_detector_margin')))
|
| 23 |
+
apply_state_item('face_detector_angles', args.get('face_detector_angles'))
|
| 24 |
+
apply_state_item('face_detector_score', args.get('face_detector_score'))
|
| 25 |
+
apply_state_item('face_landmarker_model', args.get('face_landmarker_model'))
|
| 26 |
+
apply_state_item('face_landmarker_score', args.get('face_landmarker_score'))
|
| 27 |
+
apply_state_item('face_selector_mode', args.get('face_selector_mode'))
|
| 28 |
+
apply_state_item('face_selector_order', args.get('face_selector_order'))
|
| 29 |
+
apply_state_item('face_selector_age_start', args.get('face_selector_age_start'))
|
| 30 |
+
apply_state_item('face_selector_age_end', args.get('face_selector_age_end'))
|
| 31 |
+
apply_state_item('face_selector_gender', args.get('face_selector_gender'))
|
| 32 |
+
apply_state_item('face_selector_race', args.get('face_selector_race'))
|
| 33 |
+
apply_state_item('reference_face_position', args.get('reference_face_position'))
|
| 34 |
+
apply_state_item('reference_face_distance', args.get('reference_face_distance'))
|
| 35 |
+
apply_state_item('reference_frame_number', args.get('reference_frame_number'))
|
| 36 |
+
apply_state_item('face_tracker_score', args.get('face_tracker_score'))
|
| 37 |
+
apply_state_item('face_occluder_model', args.get('face_occluder_model'))
|
| 38 |
+
apply_state_item('face_parser_model', args.get('face_parser_model'))
|
| 39 |
+
apply_state_item('face_mask_types', args.get('face_mask_types'))
|
| 40 |
+
apply_state_item('face_mask_areas', args.get('face_mask_areas'))
|
| 41 |
+
apply_state_item('face_mask_regions', args.get('face_mask_regions'))
|
| 42 |
+
apply_state_item('face_mask_blur', args.get('face_mask_blur'))
|
| 43 |
+
apply_state_item('face_mask_padding', normalize_space(args.get('face_mask_padding')))
|
| 44 |
+
apply_state_item('voice_extractor_model', args.get('voice_extractor_model'))
|
| 45 |
+
apply_state_item('trim_frame_start', args.get('trim_frame_start'))
|
| 46 |
+
apply_state_item('trim_frame_end', args.get('trim_frame_end'))
|
| 47 |
+
apply_state_item('temp_frame_format', args.get('temp_frame_format'))
|
| 48 |
+
apply_state_item('temp_pixel_format', args.get('temp_pixel_format'))
|
| 49 |
+
apply_state_item('target_frame_amount', args.get('target_frame_amount'))
|
| 50 |
+
apply_state_item('output_image_quality', args.get('output_image_quality'))
|
| 51 |
+
apply_state_item('output_image_scale', args.get('output_image_scale'))
|
| 52 |
+
apply_state_item('output_audio_encoder', args.get('output_audio_encoder'))
|
| 53 |
+
apply_state_item('output_audio_quality', args.get('output_audio_quality'))
|
| 54 |
+
apply_state_item('output_audio_volume', args.get('output_audio_volume'))
|
| 55 |
+
apply_state_item('output_video_encoder', args.get('output_video_encoder'))
|
| 56 |
+
apply_state_item('output_video_preset', args.get('output_video_preset'))
|
| 57 |
+
apply_state_item('output_video_quality', args.get('output_video_quality'))
|
| 58 |
+
apply_state_item('output_video_scale', args.get('output_video_scale'))
|
| 59 |
+
|
| 60 |
+
if args.get('output_video_fps') or is_video(args.get('target_path')):
|
| 61 |
+
output_video_fps = normalize_fps(args.get('output_video_fps')) or detect_video_fps(args.get('target_path'))
|
| 62 |
+
apply_state_item('output_video_fps', output_video_fps)
|
| 63 |
+
|
| 64 |
+
apply_state_item('workflow_mode', args.get('workflow_mode'))
|
| 65 |
+
apply_state_item('workflow_strategy', args.get('workflow_strategy'))
|
| 66 |
+
available_processors = [ get_file_name(file_path) for file_path in resolve_file_paths('facefusion/processors/modules') ]
|
| 67 |
+
apply_state_item('processors', args.get('processors'))
|
| 68 |
+
|
| 69 |
+
for processor_module in get_processors_modules(available_processors):
|
| 70 |
+
processor_module.apply_args(args, apply_state_item)
|
| 71 |
+
|
| 72 |
+
apply_state_item('open_browser', args.get('open_browser'))
|
| 73 |
+
apply_state_item('ui_layouts', args.get('ui_layouts'))
|
| 74 |
+
apply_state_item('ui_workflow', args.get('ui_workflow'))
|
| 75 |
+
apply_state_item('execution_device_ids', args.get('execution_device_ids'))
|
| 76 |
+
apply_state_item('execution_providers', args.get('execution_providers'))
|
| 77 |
+
apply_state_item('execution_thread_count', args.get('execution_thread_count'))
|
| 78 |
+
apply_state_item('download_providers', args.get('download_providers'))
|
| 79 |
+
apply_state_item('download_scope', args.get('download_scope'))
|
| 80 |
+
apply_state_item('benchmark_mode', args.get('benchmark_mode'))
|
| 81 |
+
apply_state_item('benchmark_resolutions', args.get('benchmark_resolutions'))
|
| 82 |
+
apply_state_item('benchmark_cycle_count', args.get('benchmark_cycle_count'))
|
| 83 |
+
apply_state_item('video_memory_strategy', args.get('video_memory_strategy'))
|
| 84 |
+
apply_state_item('log_level', args.get('log_level'))
|
| 85 |
+
apply_state_item('halt_on_error', args.get('halt_on_error'))
|
| 86 |
+
apply_state_item('job_id', args.get('job_id'))
|
| 87 |
+
apply_state_item('job_status', args.get('job_status'))
|
| 88 |
+
apply_state_item('step_index', args.get('step_index'))
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def reduce_step_args(args : Args) -> Args:
|
| 92 |
+
step_args =\
|
| 93 |
+
{
|
| 94 |
+
key: args[key] for key in args if key in job_store.get_step_keys()
|
| 95 |
+
}
|
| 96 |
+
return step_args
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def reduce_job_args(args : Args) -> Args:
|
| 100 |
+
job_args =\
|
| 101 |
+
{
|
| 102 |
+
key: args[key] for key in args if key in job_store.get_job_keys()
|
| 103 |
+
}
|
| 104 |
+
return job_args
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def collect_step_args() -> Args:
|
| 108 |
+
step_args =\
|
| 109 |
+
{
|
| 110 |
+
key: state_manager.get_item(key) for key in job_store.get_step_keys() #type:ignore[arg-type]
|
| 111 |
+
}
|
| 112 |
+
return step_args
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def collect_job_args() -> Args:
|
| 116 |
+
job_args =\
|
| 117 |
+
{
|
| 118 |
+
key: state_manager.get_item(key) for key in job_store.get_job_keys() #type:ignore[arg-type]
|
| 119 |
+
}
|
| 120 |
+
return job_args
|
audio.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
from typing import Any, List, Optional
|
| 3 |
+
|
| 4 |
+
import numpy
|
| 5 |
+
import scipy
|
| 6 |
+
from numpy.typing import NDArray
|
| 7 |
+
|
| 8 |
+
from facefusion import ffmpeg
|
| 9 |
+
from facefusion.filesystem import is_audio
|
| 10 |
+
from facefusion.types import Audio, AudioFrame, Fps, Mel, MelFilterBank, Spectrogram
|
| 11 |
+
from facefusion.voice_extractor import batch_extract_voice
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@lru_cache(maxsize = 64)
|
| 15 |
+
def read_static_audio(audio_path : str, fps : Fps) -> Optional[List[AudioFrame]]:
|
| 16 |
+
return read_audio(audio_path, fps)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def read_audio(audio_path : str, fps : Fps) -> Optional[List[AudioFrame]]:
|
| 20 |
+
audio_sample_rate = 48000
|
| 21 |
+
audio_sample_size = 16
|
| 22 |
+
audio_channel_total = 2
|
| 23 |
+
|
| 24 |
+
if is_audio(audio_path):
|
| 25 |
+
audio_buffer = ffmpeg.read_audio_buffer(audio_path, audio_sample_rate, audio_sample_size, audio_channel_total)
|
| 26 |
+
audio = numpy.frombuffer(audio_buffer, dtype = numpy.int16).reshape(-1, 2)
|
| 27 |
+
audio = prepare_audio(audio)
|
| 28 |
+
spectrogram = create_spectrogram(audio)
|
| 29 |
+
audio_frames = extract_audio_frames(spectrogram, fps)
|
| 30 |
+
return audio_frames
|
| 31 |
+
return None
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@lru_cache(maxsize = 64)
|
| 35 |
+
def read_static_voice(audio_path : str, fps : Fps) -> Optional[List[AudioFrame]]:
|
| 36 |
+
return read_voice(audio_path, fps)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def read_voice(audio_path : str, fps : Fps) -> Optional[List[AudioFrame]]:
|
| 40 |
+
voice_sample_rate = 48000
|
| 41 |
+
voice_sample_size = 16
|
| 42 |
+
voice_channel_total = 2
|
| 43 |
+
voice_chunk_size = 240 * 1024
|
| 44 |
+
voice_step_size = 180 * 1024
|
| 45 |
+
|
| 46 |
+
if is_audio(audio_path):
|
| 47 |
+
audio_buffer = ffmpeg.read_audio_buffer(audio_path, voice_sample_rate, voice_sample_size, voice_channel_total)
|
| 48 |
+
audio = numpy.frombuffer(audio_buffer, dtype = numpy.int16).reshape(-1, 2)
|
| 49 |
+
audio = batch_extract_voice(audio, voice_chunk_size, voice_step_size)
|
| 50 |
+
audio = prepare_voice(audio)
|
| 51 |
+
spectrogram = create_spectrogram(audio)
|
| 52 |
+
audio_frames = extract_audio_frames(spectrogram, fps)
|
| 53 |
+
return audio_frames
|
| 54 |
+
return None
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def get_audio_frame(audio_path : str, fps : Fps, frame_number : int = 0) -> Optional[AudioFrame]:
|
| 58 |
+
if is_audio(audio_path):
|
| 59 |
+
audio_frames = read_static_audio(audio_path, fps)
|
| 60 |
+
if frame_number in range(len(audio_frames)):
|
| 61 |
+
return audio_frames[frame_number]
|
| 62 |
+
return None
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def extract_audio_frames(spectrogram : Spectrogram, fps : Fps) -> List[AudioFrame]:
|
| 66 |
+
audio_frames = []
|
| 67 |
+
mel_filter_total = 80
|
| 68 |
+
audio_step_size = 16
|
| 69 |
+
indices = numpy.arange(0, spectrogram.shape[1], mel_filter_total / fps).astype(numpy.int16)
|
| 70 |
+
indices = indices[indices >= audio_step_size]
|
| 71 |
+
|
| 72 |
+
for index in indices:
|
| 73 |
+
start = max(0, index - audio_step_size)
|
| 74 |
+
audio_frames.append(spectrogram[:, start:index])
|
| 75 |
+
|
| 76 |
+
return audio_frames
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def get_voice_frame(audio_path : str, fps : Fps, frame_number : int = 0) -> Optional[AudioFrame]:
|
| 80 |
+
if is_audio(audio_path):
|
| 81 |
+
voice_frames = read_static_voice(audio_path, fps)
|
| 82 |
+
if frame_number in range(len(voice_frames)):
|
| 83 |
+
return voice_frames[frame_number]
|
| 84 |
+
return None
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def create_empty_audio_frame() -> AudioFrame:
|
| 88 |
+
mel_filter_total = 80
|
| 89 |
+
audio_step_size = 16
|
| 90 |
+
audio_frame = numpy.zeros((mel_filter_total, audio_step_size)).astype(numpy.int16)
|
| 91 |
+
return audio_frame
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def prepare_audio(audio : Audio) -> Audio:
|
| 95 |
+
if audio.ndim > 1:
|
| 96 |
+
audio = numpy.mean(audio, axis = 1)
|
| 97 |
+
audio = audio / numpy.max(numpy.abs(audio), axis = 0)
|
| 98 |
+
audio = scipy.signal.lfilter([ 1.0, -0.97 ], [ 1.0 ], audio)
|
| 99 |
+
return audio
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def prepare_voice(audio : Audio) -> Audio:
|
| 103 |
+
audio_sample_rate = 48000
|
| 104 |
+
audio_resample_rate = 16000
|
| 105 |
+
audio_resample_factor = round(len(audio) * audio_resample_rate / audio_sample_rate)
|
| 106 |
+
audio = scipy.signal.resample(audio, audio_resample_factor)
|
| 107 |
+
audio = prepare_audio(audio)
|
| 108 |
+
return audio
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def convert_hertz_to_mel(hertz : float) -> float:
|
| 112 |
+
return 2595 * numpy.log10(1 + hertz / 700)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def convert_mel_to_hertz(mel : Mel) -> NDArray[Any]:
|
| 116 |
+
return 700 * (10 ** (mel / 2595) - 1)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def create_mel_filter_bank() -> MelFilterBank:
|
| 120 |
+
audio_sample_rate = 16000
|
| 121 |
+
audio_frequency_min = 55.0
|
| 122 |
+
audio_frequency_max = 7600.0
|
| 123 |
+
mel_filter_total = 80
|
| 124 |
+
mel_bin_total = 800
|
| 125 |
+
mel_filter_bank = numpy.zeros((mel_filter_total, mel_bin_total // 2 + 1))
|
| 126 |
+
mel_frequency_range = numpy.linspace(convert_hertz_to_mel(audio_frequency_min), convert_hertz_to_mel(audio_frequency_max), mel_filter_total + 2)
|
| 127 |
+
indices = numpy.floor((mel_bin_total + 1) * convert_mel_to_hertz(mel_frequency_range) / audio_sample_rate).astype(numpy.int16)
|
| 128 |
+
|
| 129 |
+
for index in range(mel_filter_total):
|
| 130 |
+
start = indices[index]
|
| 131 |
+
end = indices[index + 1]
|
| 132 |
+
mel_filter_bank[index, start:end] = scipy.signal.windows.triang(end - start)
|
| 133 |
+
|
| 134 |
+
return mel_filter_bank
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def create_spectrogram(audio : Audio) -> Spectrogram:
|
| 138 |
+
mel_bin_total = 800
|
| 139 |
+
mel_bin_overlap = 600
|
| 140 |
+
mel_filter_bank = create_mel_filter_bank()
|
| 141 |
+
spectrogram = scipy.signal.stft(audio, nperseg = mel_bin_total, nfft = mel_bin_total, noverlap = mel_bin_overlap)[2]
|
| 142 |
+
spectrogram = numpy.dot(mel_filter_bank, numpy.abs(spectrogram))
|
| 143 |
+
return spectrogram
|
benchmarker.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
import os
|
| 3 |
+
import statistics
|
| 4 |
+
import tempfile
|
| 5 |
+
from time import perf_counter
|
| 6 |
+
from typing import Iterator, List
|
| 7 |
+
|
| 8 |
+
import facefusion.choices
|
| 9 |
+
from facefusion import content_analyser, core, state_manager
|
| 10 |
+
from facefusion.cli_helper import render_table
|
| 11 |
+
from facefusion.download import conditional_download, resolve_download_url
|
| 12 |
+
from facefusion.face_store import clear_faces
|
| 13 |
+
from facefusion.filesystem import get_file_extension
|
| 14 |
+
from facefusion.types import BenchmarkCycleSet
|
| 15 |
+
from facefusion.vision import count_video_frame_total, detect_video_fps
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def pre_check() -> bool:
|
| 19 |
+
conditional_download('.assets/examples',
|
| 20 |
+
[
|
| 21 |
+
resolve_download_url('examples-3.0.0', 'source.jpg'),
|
| 22 |
+
resolve_download_url('examples-3.0.0', 'source.mp3'),
|
| 23 |
+
resolve_download_url('examples-3.0.0', 'target-240p.mp4'),
|
| 24 |
+
resolve_download_url('examples-3.0.0', 'target-360p.mp4'),
|
| 25 |
+
resolve_download_url('examples-3.0.0', 'target-540p.mp4'),
|
| 26 |
+
resolve_download_url('examples-3.0.0', 'target-720p.mp4'),
|
| 27 |
+
resolve_download_url('examples-3.0.0', 'target-1080p.mp4'),
|
| 28 |
+
resolve_download_url('examples-3.0.0', 'target-1440p.mp4'),
|
| 29 |
+
resolve_download_url('examples-3.0.0', 'target-2160p.mp4')
|
| 30 |
+
])
|
| 31 |
+
return True
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def run() -> Iterator[List[BenchmarkCycleSet]]:
|
| 35 |
+
benchmark_resolutions = state_manager.get_item('benchmark_resolutions')
|
| 36 |
+
benchmark_cycle_count = state_manager.get_item('benchmark_cycle_count')
|
| 37 |
+
|
| 38 |
+
state_manager.init_item('source_paths', [ '.assets/examples/source.jpg', '.assets/examples/source.mp3' ])
|
| 39 |
+
state_manager.init_item('face_landmarker_score', 0)
|
| 40 |
+
state_manager.init_item('temp_frame_format', 'bmp')
|
| 41 |
+
state_manager.init_item('output_audio_volume', 0)
|
| 42 |
+
state_manager.init_item('output_video_preset', 'ultrafast')
|
| 43 |
+
state_manager.init_item('video_memory_strategy', 'tolerant')
|
| 44 |
+
|
| 45 |
+
benchmarks = []
|
| 46 |
+
target_paths = [ facefusion.choices.benchmark_set.get(benchmark_resolution) for benchmark_resolution in benchmark_resolutions if benchmark_resolution in facefusion.choices.benchmark_set ]
|
| 47 |
+
|
| 48 |
+
for target_path in target_paths:
|
| 49 |
+
state_manager.init_item('target_path', target_path)
|
| 50 |
+
state_manager.init_item('output_path', suggest_output_path(state_manager.get_item('target_path')))
|
| 51 |
+
benchmarks.append(cycle(benchmark_cycle_count))
|
| 52 |
+
yield benchmarks
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def cycle(cycle_count : int) -> BenchmarkCycleSet:
|
| 56 |
+
process_times = []
|
| 57 |
+
video_frame_total = count_video_frame_total(state_manager.get_item('target_path'))
|
| 58 |
+
state_manager.init_item('output_video_fps', detect_video_fps(state_manager.get_item('target_path')))
|
| 59 |
+
|
| 60 |
+
if state_manager.get_item('benchmark_mode') == 'warm':
|
| 61 |
+
core.conditional_process()
|
| 62 |
+
|
| 63 |
+
for index in range(cycle_count):
|
| 64 |
+
if state_manager.get_item('benchmark_mode') == 'cold':
|
| 65 |
+
content_analyser.analyse_image.cache_clear()
|
| 66 |
+
content_analyser.analyse_video.cache_clear()
|
| 67 |
+
clear_faces()
|
| 68 |
+
|
| 69 |
+
start_time = perf_counter()
|
| 70 |
+
core.conditional_process()
|
| 71 |
+
end_time = perf_counter()
|
| 72 |
+
process_times.append(end_time - start_time)
|
| 73 |
+
|
| 74 |
+
average_run = round(statistics.mean(process_times), 2)
|
| 75 |
+
fastest_run = round(min(process_times), 2)
|
| 76 |
+
slowest_run = round(max(process_times), 2)
|
| 77 |
+
relative_fps = round(video_frame_total * cycle_count / sum(process_times), 2)
|
| 78 |
+
|
| 79 |
+
return\
|
| 80 |
+
{
|
| 81 |
+
'target_path': state_manager.get_item('target_path'),
|
| 82 |
+
'cycle_count': cycle_count,
|
| 83 |
+
'average_run': average_run,
|
| 84 |
+
'fastest_run': fastest_run,
|
| 85 |
+
'slowest_run': slowest_run,
|
| 86 |
+
'relative_fps': relative_fps
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def suggest_output_path(target_path : str) -> str:
|
| 91 |
+
target_file_extension = get_file_extension(target_path)
|
| 92 |
+
return os.path.join(tempfile.gettempdir(), hashlib.sha1(target_path.encode()).hexdigest() + target_file_extension)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def render() -> None:
|
| 96 |
+
benchmarks = []
|
| 97 |
+
headers =\
|
| 98 |
+
[
|
| 99 |
+
'target_path',
|
| 100 |
+
'cycle_count',
|
| 101 |
+
'average_run',
|
| 102 |
+
'fastest_run',
|
| 103 |
+
'slowest_run',
|
| 104 |
+
'relative_fps'
|
| 105 |
+
]
|
| 106 |
+
|
| 107 |
+
for benchmark in run():
|
| 108 |
+
benchmarks = benchmark
|
| 109 |
+
|
| 110 |
+
contents = [ list(benchmark_set.values()) for benchmark_set in benchmarks ]
|
| 111 |
+
render_table(headers, contents)
|
camera_manager.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List
|
| 2 |
+
|
| 3 |
+
import cv2
|
| 4 |
+
|
| 5 |
+
from facefusion.types import CameraPoolSet
|
| 6 |
+
|
| 7 |
+
CAMERA_POOL_SET : CameraPoolSet =\
|
| 8 |
+
{
|
| 9 |
+
'capture': {}
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def get_local_camera_capture(camera_id : int) -> cv2.VideoCapture:
|
| 14 |
+
camera_key = str(camera_id)
|
| 15 |
+
|
| 16 |
+
if camera_key not in CAMERA_POOL_SET.get('capture'):
|
| 17 |
+
camera_capture = cv2.VideoCapture(camera_id)
|
| 18 |
+
|
| 19 |
+
if camera_capture.isOpened():
|
| 20 |
+
CAMERA_POOL_SET['capture'][camera_key] = camera_capture
|
| 21 |
+
|
| 22 |
+
return CAMERA_POOL_SET.get('capture').get(camera_key)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def get_remote_camera_capture(camera_url : str) -> cv2.VideoCapture:
|
| 26 |
+
if camera_url not in CAMERA_POOL_SET.get('capture'):
|
| 27 |
+
camera_capture = cv2.VideoCapture(camera_url)
|
| 28 |
+
|
| 29 |
+
if camera_capture.isOpened():
|
| 30 |
+
CAMERA_POOL_SET['capture'][camera_url] = camera_capture
|
| 31 |
+
|
| 32 |
+
return CAMERA_POOL_SET.get('capture').get(camera_url)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def clear_camera_pool() -> None:
|
| 36 |
+
for camera_capture in CAMERA_POOL_SET.get('capture').values():
|
| 37 |
+
camera_capture.release()
|
| 38 |
+
|
| 39 |
+
CAMERA_POOL_SET['capture'].clear()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def detect_local_camera_ids(id_start : int, id_end : int) -> List[int]:
|
| 43 |
+
local_camera_ids = []
|
| 44 |
+
|
| 45 |
+
for camera_id in range(id_start, id_end):
|
| 46 |
+
cv2.utils.logging.setLogLevel(0)
|
| 47 |
+
camera_capture = get_local_camera_capture(camera_id)
|
| 48 |
+
cv2.utils.logging.setLogLevel(3)
|
| 49 |
+
|
| 50 |
+
if camera_capture and camera_capture.isOpened():
|
| 51 |
+
local_camera_ids.append(camera_id)
|
| 52 |
+
|
| 53 |
+
return local_camera_ids
|
choices.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from typing import List, Sequence, get_args
|
| 3 |
+
|
| 4 |
+
from facefusion.common_helper import create_float_range, create_int_range
|
| 5 |
+
from facefusion.types import Angle, AudioEncoder, AudioFormat, AudioTypeSet, BenchmarkMode, BenchmarkResolution, BenchmarkSet, DownloadProvider, DownloadProviderSet, DownloadScope, EncoderSet, ExecutionProvider, ExecutionProviderSet, FaceDetectorModel, FaceDetectorSet, FaceLandmarkerModel, FaceMaskArea, FaceMaskAreaSet, FaceMaskRegion, FaceMaskRegionSet, FaceMaskType, FaceOccluderModel, FaceParserModel, FaceSelectorGender, FaceSelectorMode, FaceSelectorOrder, FaceSelectorRace, Gender, ImageFormat, ImageTypeSet, JobStatus, LogLevel, LogLevelSet, Race, Score, TempFrameFormat, TempPixelFormat, UiWorkflow, VideoEncoder, VideoFormat, VideoMemoryStrategy, VideoPreset, VideoTypeSet, VoiceExtractorModel, WorkflowMode, WorkflowStrategy
|
| 6 |
+
|
| 7 |
+
face_detector_set : FaceDetectorSet =\
|
| 8 |
+
{
|
| 9 |
+
'many': [ '640x640' ],
|
| 10 |
+
'retinaface': [ '160x160', '320x320', '480x480', '512x512', '640x640' ],
|
| 11 |
+
'scrfd': [ '160x160', '320x320', '480x480', '512x512', '640x640' ],
|
| 12 |
+
'yolo_face': [ '640x640' ],
|
| 13 |
+
'yunet': [ '640x640' ]
|
| 14 |
+
}
|
| 15 |
+
face_detector_models : List[FaceDetectorModel] = list(get_args(FaceDetectorModel))
|
| 16 |
+
face_landmarker_models : List[FaceLandmarkerModel] = list(get_args(FaceLandmarkerModel))
|
| 17 |
+
face_selector_modes : List[FaceSelectorMode] = list(get_args(FaceSelectorMode))
|
| 18 |
+
face_selector_orders : List[FaceSelectorOrder] = list(get_args(FaceSelectorOrder))
|
| 19 |
+
genders : List[Gender] = list(get_args(Gender))
|
| 20 |
+
races : List[Race] = list(get_args(Race))
|
| 21 |
+
face_selector_genders : List[FaceSelectorGender] = list(get_args(FaceSelectorGender))
|
| 22 |
+
face_selector_races : List[FaceSelectorRace] = list(get_args(FaceSelectorRace))
|
| 23 |
+
face_occluder_models : List[FaceOccluderModel] = list(get_args(FaceOccluderModel))
|
| 24 |
+
face_parser_models : List[FaceParserModel] = list(get_args(FaceParserModel))
|
| 25 |
+
face_mask_types : List[FaceMaskType] = list(get_args(FaceMaskType))
|
| 26 |
+
face_mask_area_set : FaceMaskAreaSet =\
|
| 27 |
+
{
|
| 28 |
+
'upper-face': [ 0, 1, 2, 31, 32, 33, 34, 35, 14, 15, 16, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17 ],
|
| 29 |
+
'lower-face': [ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 35, 34, 33, 32, 31 ],
|
| 30 |
+
'mouth': [ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67 ]
|
| 31 |
+
}
|
| 32 |
+
face_mask_region_set : FaceMaskRegionSet =\
|
| 33 |
+
{
|
| 34 |
+
'skin': 1,
|
| 35 |
+
'left-eyebrow': 2,
|
| 36 |
+
'right-eyebrow': 3,
|
| 37 |
+
'left-eye': 4,
|
| 38 |
+
'right-eye': 5,
|
| 39 |
+
'glasses': 6,
|
| 40 |
+
'nose': 10,
|
| 41 |
+
'mouth': 11,
|
| 42 |
+
'upper-lip': 12,
|
| 43 |
+
'lower-lip': 13
|
| 44 |
+
}
|
| 45 |
+
face_mask_areas : List[FaceMaskArea] = list(get_args(FaceMaskArea))
|
| 46 |
+
face_mask_regions : List[FaceMaskRegion] = list(get_args(FaceMaskRegion))
|
| 47 |
+
|
| 48 |
+
voice_extractor_models : List[VoiceExtractorModel] = list(get_args(VoiceExtractorModel))
|
| 49 |
+
|
| 50 |
+
audio_type_set : AudioTypeSet =\
|
| 51 |
+
{
|
| 52 |
+
'flac': 'audio/flac',
|
| 53 |
+
'm4a': 'audio/mp4',
|
| 54 |
+
'mp3': 'audio/mpeg',
|
| 55 |
+
'ogg': 'audio/ogg',
|
| 56 |
+
'opus': 'audio/opus',
|
| 57 |
+
'wav': 'audio/x-wav'
|
| 58 |
+
}
|
| 59 |
+
image_type_set : ImageTypeSet =\
|
| 60 |
+
{
|
| 61 |
+
'bmp': 'image/bmp',
|
| 62 |
+
'jpeg': 'image/jpeg',
|
| 63 |
+
'png': 'image/png',
|
| 64 |
+
'tiff': 'image/tiff',
|
| 65 |
+
'webp': 'image/webp'
|
| 66 |
+
}
|
| 67 |
+
video_type_set : VideoTypeSet =\
|
| 68 |
+
{
|
| 69 |
+
'avi': 'video/x-msvideo',
|
| 70 |
+
'm4v': 'video/mp4',
|
| 71 |
+
'mkv': 'video/x-matroska',
|
| 72 |
+
'mp4': 'video/mp4',
|
| 73 |
+
'mpeg': 'video/mpeg',
|
| 74 |
+
'mov': 'video/quicktime',
|
| 75 |
+
'mxf': 'application/mxf',
|
| 76 |
+
'webm': 'video/webm',
|
| 77 |
+
'wmv': 'video/x-ms-wmv'
|
| 78 |
+
}
|
| 79 |
+
workflow_modes : List[WorkflowMode] = list(get_args(WorkflowMode))
|
| 80 |
+
workflow_strategies : List[WorkflowStrategy] = list(get_args(WorkflowStrategy))
|
| 81 |
+
|
| 82 |
+
audio_formats : List[AudioFormat] = list(get_args(AudioFormat))
|
| 83 |
+
image_formats : List[ImageFormat] = list(get_args(ImageFormat))
|
| 84 |
+
video_formats : List[VideoFormat] = list(get_args(VideoFormat))
|
| 85 |
+
temp_frame_formats : List[TempFrameFormat] = list(get_args(TempFrameFormat))
|
| 86 |
+
temp_pixel_formats : List[TempPixelFormat] = list(get_args(TempPixelFormat))
|
| 87 |
+
|
| 88 |
+
output_audio_encoders : List[AudioEncoder] = list(get_args(AudioEncoder))
|
| 89 |
+
output_video_encoders : List[VideoEncoder] = list(get_args(VideoEncoder))
|
| 90 |
+
output_encoder_set : EncoderSet =\
|
| 91 |
+
{
|
| 92 |
+
'audio': output_audio_encoders,
|
| 93 |
+
'video': output_video_encoders
|
| 94 |
+
}
|
| 95 |
+
output_video_presets : List[VideoPreset] = list(get_args(VideoPreset))
|
| 96 |
+
|
| 97 |
+
benchmark_modes : List[BenchmarkMode] = list(get_args(BenchmarkMode))
|
| 98 |
+
benchmark_set : BenchmarkSet =\
|
| 99 |
+
{
|
| 100 |
+
'240p': '.assets/examples/target-240p.mp4',
|
| 101 |
+
'360p': '.assets/examples/target-360p.mp4',
|
| 102 |
+
'540p': '.assets/examples/target-540p.mp4',
|
| 103 |
+
'720p': '.assets/examples/target-720p.mp4',
|
| 104 |
+
'1080p': '.assets/examples/target-1080p.mp4',
|
| 105 |
+
'1440p': '.assets/examples/target-1440p.mp4',
|
| 106 |
+
'2160p': '.assets/examples/target-2160p.mp4'
|
| 107 |
+
}
|
| 108 |
+
benchmark_resolutions : List[BenchmarkResolution] = list(get_args(BenchmarkResolution))
|
| 109 |
+
|
| 110 |
+
execution_provider_set : ExecutionProviderSet =\
|
| 111 |
+
{
|
| 112 |
+
'cuda': 'CUDAExecutionProvider',
|
| 113 |
+
'tensorrt': 'TensorrtExecutionProvider',
|
| 114 |
+
'rocm': 'ROCMExecutionProvider',
|
| 115 |
+
'migraphx': 'MIGraphXExecutionProvider',
|
| 116 |
+
'coreml': 'CoreMLExecutionProvider',
|
| 117 |
+
'openvino': 'OpenVINOExecutionProvider',
|
| 118 |
+
'qnn': 'QNNExecutionProvider',
|
| 119 |
+
'directml': 'DmlExecutionProvider',
|
| 120 |
+
'cpu': 'CPUExecutionProvider'
|
| 121 |
+
}
|
| 122 |
+
execution_providers : List[ExecutionProvider] = list(get_args(ExecutionProvider))
|
| 123 |
+
download_provider_set : DownloadProviderSet =\
|
| 124 |
+
{
|
| 125 |
+
'github':
|
| 126 |
+
{
|
| 127 |
+
'urls':
|
| 128 |
+
[
|
| 129 |
+
'https://github.com'
|
| 130 |
+
],
|
| 131 |
+
'path': '/facefusion/facefusion-assets/releases/download/{base_name}/{file_name}'
|
| 132 |
+
},
|
| 133 |
+
'huggingface':
|
| 134 |
+
{
|
| 135 |
+
'urls':
|
| 136 |
+
[
|
| 137 |
+
'https://huggingface.co',
|
| 138 |
+
'https://hf-mirror.com'
|
| 139 |
+
],
|
| 140 |
+
'path': '/facefusion/{base_name}/resolve/main/{file_name}'
|
| 141 |
+
}
|
| 142 |
+
}
|
| 143 |
+
download_providers : List[DownloadProvider] = list(get_args(DownloadProvider))
|
| 144 |
+
download_scopes : List[DownloadScope] = list(get_args(DownloadScope))
|
| 145 |
+
|
| 146 |
+
video_memory_strategies : List[VideoMemoryStrategy] = list(get_args(VideoMemoryStrategy))
|
| 147 |
+
|
| 148 |
+
log_level_set : LogLevelSet =\
|
| 149 |
+
{
|
| 150 |
+
'error': logging.ERROR,
|
| 151 |
+
'warn': logging.WARNING,
|
| 152 |
+
'info': logging.INFO,
|
| 153 |
+
'debug': logging.DEBUG
|
| 154 |
+
}
|
| 155 |
+
log_levels : List[LogLevel] = list(get_args(LogLevel))
|
| 156 |
+
|
| 157 |
+
ui_workflows : List[UiWorkflow] = list(get_args(UiWorkflow))
|
| 158 |
+
job_statuses : List[JobStatus] = list(get_args(JobStatus))
|
| 159 |
+
|
| 160 |
+
benchmark_cycle_count_range : Sequence[int] = create_int_range(1, 10, 1)
|
| 161 |
+
execution_thread_count_range : Sequence[int] = create_int_range(1, 32, 1)
|
| 162 |
+
face_detector_margin_range : Sequence[int] = create_int_range(0, 100, 1)
|
| 163 |
+
face_detector_angles : Sequence[Angle] = create_int_range(0, 270, 90)
|
| 164 |
+
face_detector_score_range : Sequence[Score] = create_float_range(0.0, 1.0, 0.05)
|
| 165 |
+
face_landmarker_score_range : Sequence[Score] = create_float_range(0.0, 1.0, 0.05)
|
| 166 |
+
face_mask_blur_range : Sequence[float] = create_float_range(0.0, 1.0, 0.05)
|
| 167 |
+
face_mask_padding_range : Sequence[int] = create_int_range(0, 100, 1)
|
| 168 |
+
face_selector_age_range : Sequence[int] = create_int_range(0, 100, 1)
|
| 169 |
+
reference_face_distance_range : Sequence[float] = create_float_range(0.0, 1.0, 0.05)
|
| 170 |
+
face_tracker_score_range : Sequence[Score] = create_float_range(0.0, 0.5, 0.05)
|
| 171 |
+
target_frame_amount_range : Sequence[int] = create_int_range(0, 10, 1)
|
| 172 |
+
output_image_quality_range : Sequence[int] = create_int_range(0, 100, 1)
|
| 173 |
+
output_image_scale_range : Sequence[float] = create_float_range(0.25, 8.0, 0.25)
|
| 174 |
+
output_audio_quality_range : Sequence[int] = create_int_range(0, 100, 1)
|
| 175 |
+
output_audio_volume_range : Sequence[int] = create_int_range(0, 100, 1)
|
| 176 |
+
output_video_quality_range : Sequence[int] = create_int_range(0, 100, 1)
|
| 177 |
+
output_video_scale_range : Sequence[float] = create_float_range(0.25, 8.0, 0.25)
|
cli_helper.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Tuple
|
| 2 |
+
|
| 3 |
+
from facefusion.logger import get_package_logger
|
| 4 |
+
from facefusion.types import TableContent, TableHeader
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def render_table(headers : List[TableHeader], contents : List[List[TableContent]]) -> None:
|
| 8 |
+
package_logger = get_package_logger()
|
| 9 |
+
table_column, table_separator = create_table_parts(headers, contents)
|
| 10 |
+
|
| 11 |
+
package_logger.critical(table_separator)
|
| 12 |
+
package_logger.critical(table_column.format(*headers))
|
| 13 |
+
package_logger.critical(table_separator)
|
| 14 |
+
|
| 15 |
+
for content in contents:
|
| 16 |
+
content = [ str(value) for value in content ]
|
| 17 |
+
package_logger.critical(table_column.format(*content))
|
| 18 |
+
|
| 19 |
+
package_logger.critical(table_separator)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def create_table_parts(headers : List[TableHeader], contents : List[List[TableContent]]) -> Tuple[str, str]:
|
| 23 |
+
column_parts = []
|
| 24 |
+
separator_parts = []
|
| 25 |
+
widths = [ len(header) for header in headers ]
|
| 26 |
+
|
| 27 |
+
for content in contents:
|
| 28 |
+
for index, value in enumerate(content):
|
| 29 |
+
widths[index] = max(widths[index], len(str(value)))
|
| 30 |
+
|
| 31 |
+
for width in widths:
|
| 32 |
+
column_parts.append('{:<' + str(width) + '}')
|
| 33 |
+
separator_parts.append('-' * width)
|
| 34 |
+
|
| 35 |
+
return '| ' + ' | '.join(column_parts) + ' |', '+-' + '-+-'.join(separator_parts) + '-+'
|
common_helper.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import platform
|
| 2 |
+
from typing import Any, Iterable, Optional, Reversible, Sequence
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def is_linux() -> bool:
|
| 6 |
+
return platform.system().lower() == 'linux'
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def is_macos() -> bool:
|
| 10 |
+
return platform.system().lower() == 'darwin'
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def is_windows() -> bool:
|
| 14 |
+
return platform.system().lower() == 'windows'
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def create_int_metavar(int_range : Sequence[int]) -> str:
|
| 18 |
+
return '[' + str(int_range[0]) + '..' + str(int_range[-1]) + ':' + str(calculate_int_step(int_range)) + ']'
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def create_float_metavar(float_range : Sequence[float]) -> str:
|
| 22 |
+
return '[' + str(float_range[0]) + '..' + str(float_range[-1]) + ':' + str(calculate_float_step(float_range)) + ']'
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def create_int_range(start : int, end : int, step : int) -> Sequence[int]:
|
| 26 |
+
int_range = []
|
| 27 |
+
current = start
|
| 28 |
+
|
| 29 |
+
while current <= end:
|
| 30 |
+
int_range.append(current)
|
| 31 |
+
current += step
|
| 32 |
+
return int_range
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def create_float_range(start : float, end : float, step : float) -> Sequence[float]:
|
| 36 |
+
float_range = []
|
| 37 |
+
current = start
|
| 38 |
+
|
| 39 |
+
while current <= end:
|
| 40 |
+
float_range.append(round(current, 2))
|
| 41 |
+
current = round(current + step, 2)
|
| 42 |
+
return float_range
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def calculate_int_step(int_range : Sequence[int]) -> int:
|
| 46 |
+
return int_range[1] - int_range[0]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def calculate_float_step(float_range : Sequence[float]) -> float:
|
| 50 |
+
return round(float_range[1] - float_range[0], 2)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def cast_int(value : Any) -> Optional[int]:
|
| 54 |
+
try:
|
| 55 |
+
return int(value)
|
| 56 |
+
except (ValueError, TypeError):
|
| 57 |
+
return None
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def cast_float(value : Any) -> Optional[float]:
|
| 61 |
+
try:
|
| 62 |
+
return float(value)
|
| 63 |
+
except (ValueError, TypeError):
|
| 64 |
+
return None
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def cast_bool(value : Any) -> Optional[bool]:
|
| 68 |
+
if value == 'True':
|
| 69 |
+
return True
|
| 70 |
+
if value == 'False':
|
| 71 |
+
return False
|
| 72 |
+
return None
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def get_first(__list__ : Any) -> Any:
|
| 76 |
+
if isinstance(__list__, Iterable):
|
| 77 |
+
return next(iter(__list__), None)
|
| 78 |
+
return None
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def get_middle(__list__ : Any) -> Any:
|
| 82 |
+
if isinstance(__list__, Sequence) and __list__:
|
| 83 |
+
return __list__[len(__list__) // 2]
|
| 84 |
+
return None
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def get_last(__list__ : Any) -> Any:
|
| 88 |
+
if isinstance(__list__, Reversible):
|
| 89 |
+
return next(reversed(__list__), None)
|
| 90 |
+
return None
|
conda.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
from typing import List
|
| 4 |
+
|
| 5 |
+
from facefusion.common_helper import is_linux, is_windows
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def setup() -> None:
|
| 9 |
+
conda_prefix = os.getenv('CONDA_PREFIX')
|
| 10 |
+
conda_ready = os.getenv('CONDA_READY')
|
| 11 |
+
|
| 12 |
+
if conda_prefix and not conda_ready:
|
| 13 |
+
if is_linux():
|
| 14 |
+
python_id = 'python' + str(sys.version_info.major) + '.' + str(sys.version_info.minor)
|
| 15 |
+
library_paths : List[str] =\
|
| 16 |
+
[
|
| 17 |
+
os.path.join(conda_prefix, 'lib'),
|
| 18 |
+
os.path.join(conda_prefix, 'lib', python_id, 'site-packages', 'tensorrt_libs')
|
| 19 |
+
]
|
| 20 |
+
library_paths = list(filter(os.path.exists, library_paths))
|
| 21 |
+
|
| 22 |
+
if library_paths:
|
| 23 |
+
if os.getenv('LD_LIBRARY_PATH'):
|
| 24 |
+
library_paths.append(os.getenv('LD_LIBRARY_PATH'))
|
| 25 |
+
os.environ['LD_LIBRARY_PATH'] = os.pathsep.join(library_paths)
|
| 26 |
+
os.environ['CONDA_READY'] = '1'
|
| 27 |
+
os.execv(sys.executable, [ sys.executable ] + sys.argv)
|
| 28 |
+
|
| 29 |
+
if is_windows():
|
| 30 |
+
library_paths =\
|
| 31 |
+
[
|
| 32 |
+
os.path.join(conda_prefix, 'Lib'),
|
| 33 |
+
os.path.join(conda_prefix, 'Lib', 'site-packages', 'tensorrt_libs')
|
| 34 |
+
]
|
| 35 |
+
library_paths = list(filter(os.path.exists, library_paths))
|
| 36 |
+
|
| 37 |
+
if library_paths:
|
| 38 |
+
if os.getenv('PATH'):
|
| 39 |
+
library_paths.append(os.getenv('PATH'))
|
| 40 |
+
os.environ['PATH'] = os.pathsep.join(library_paths)
|
| 41 |
+
os.environ['CONDA_READY'] = '1'
|
config.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from configparser import ConfigParser
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
from typing import List, Optional
|
| 4 |
+
|
| 5 |
+
from facefusion import state_manager
|
| 6 |
+
from facefusion.common_helper import cast_bool, cast_float, cast_int
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@lru_cache
|
| 10 |
+
def get_static_config_parser() -> ConfigParser:
|
| 11 |
+
config_parser = ConfigParser()
|
| 12 |
+
config_parser.read(state_manager.get_item('config_path'), encoding = 'utf-8')
|
| 13 |
+
return config_parser
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def get_str_value(section : str, option : str, fallback : Optional[str] = None) -> Optional[str]:
|
| 17 |
+
config_parser = get_static_config_parser()
|
| 18 |
+
|
| 19 |
+
if config_parser.has_option(section, option) and config_parser.get(section, option).strip():
|
| 20 |
+
return config_parser.get(section, option)
|
| 21 |
+
return fallback
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def get_int_value(section : str, option : str, fallback : Optional[str] = None) -> Optional[int]:
|
| 25 |
+
config_parser = get_static_config_parser()
|
| 26 |
+
|
| 27 |
+
if config_parser.has_option(section, option) and config_parser.get(section, option).strip():
|
| 28 |
+
return config_parser.getint(section, option)
|
| 29 |
+
return cast_int(fallback)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def get_float_value(section : str, option : str, fallback : Optional[str] = None) -> Optional[float]:
|
| 33 |
+
config_parser = get_static_config_parser()
|
| 34 |
+
|
| 35 |
+
if config_parser.has_option(section, option) and config_parser.get(section, option).strip():
|
| 36 |
+
return config_parser.getfloat(section, option)
|
| 37 |
+
return cast_float(fallback)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def get_bool_value(section : str, option : str, fallback : Optional[str] = None) -> Optional[bool]:
|
| 41 |
+
config_parser = get_static_config_parser()
|
| 42 |
+
|
| 43 |
+
if config_parser.has_option(section, option) and config_parser.get(section, option).strip():
|
| 44 |
+
return config_parser.getboolean(section, option)
|
| 45 |
+
return cast_bool(fallback)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def get_str_list(section : str, option : str, fallback : Optional[str] = None) -> Optional[List[str]]:
|
| 49 |
+
config_parser = get_static_config_parser()
|
| 50 |
+
|
| 51 |
+
if config_parser.has_option(section, option) and config_parser.get(section, option).strip():
|
| 52 |
+
return config_parser.get(section, option).split()
|
| 53 |
+
if fallback:
|
| 54 |
+
return fallback.split()
|
| 55 |
+
return None
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def get_int_list(section : str, option : str, fallback : Optional[str] = None) -> Optional[List[int]]:
|
| 59 |
+
config_parser = get_static_config_parser()
|
| 60 |
+
|
| 61 |
+
if config_parser.has_option(section, option) and config_parser.get(section, option).strip():
|
| 62 |
+
return list(map(int, config_parser.get(section, option).split()))
|
| 63 |
+
if fallback:
|
| 64 |
+
return list(map(int, fallback.split()))
|
| 65 |
+
return None
|
content_analyser.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
from typing import Tuple
|
| 3 |
+
|
| 4 |
+
import numpy
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
|
| 7 |
+
from facefusion import inference_manager, state_manager, translator, video_manager
|
| 8 |
+
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
| 9 |
+
from facefusion.filesystem import resolve_relative_path
|
| 10 |
+
from facefusion.thread_helper import conditional_thread_semaphore
|
| 11 |
+
from facefusion.types import Detection, DownloadScope, DownloadSet, Fps, InferencePool, ModelSet, VisionFrame
|
| 12 |
+
from facefusion.vision import detect_video_fps, fit_contain_frame, is_vision_frame, read_image
|
| 13 |
+
|
| 14 |
+
STREAM_COUNTER = 0
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@lru_cache()
|
| 18 |
+
def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
| 19 |
+
return\
|
| 20 |
+
{
|
| 21 |
+
'nsfw_1':
|
| 22 |
+
{
|
| 23 |
+
'__metadata__':
|
| 24 |
+
{
|
| 25 |
+
'vendor': 'EraX',
|
| 26 |
+
'license': 'Apache-2.0',
|
| 27 |
+
'year': 2024
|
| 28 |
+
},
|
| 29 |
+
'hashes':
|
| 30 |
+
{
|
| 31 |
+
'content_analyser':
|
| 32 |
+
{
|
| 33 |
+
'url': resolve_download_url('models-3.3.0', 'nsfw_1.hash'),
|
| 34 |
+
'path': resolve_relative_path('../.assets/models/nsfw_1.hash')
|
| 35 |
+
}
|
| 36 |
+
},
|
| 37 |
+
'sources':
|
| 38 |
+
{
|
| 39 |
+
'content_analyser':
|
| 40 |
+
{
|
| 41 |
+
'url': resolve_download_url('models-3.3.0', 'nsfw_1.onnx'),
|
| 42 |
+
'path': resolve_relative_path('../.assets/models/nsfw_1.onnx')
|
| 43 |
+
}
|
| 44 |
+
},
|
| 45 |
+
'size': (640, 640),
|
| 46 |
+
'mean': (0.0, 0.0, 0.0),
|
| 47 |
+
'standard_deviation': (1.0, 1.0, 1.0)
|
| 48 |
+
},
|
| 49 |
+
'nsfw_2':
|
| 50 |
+
{
|
| 51 |
+
'__metadata__':
|
| 52 |
+
{
|
| 53 |
+
'vendor': 'Marqo',
|
| 54 |
+
'license': 'Apache-2.0',
|
| 55 |
+
'year': 2024
|
| 56 |
+
},
|
| 57 |
+
'hashes':
|
| 58 |
+
{
|
| 59 |
+
'content_analyser':
|
| 60 |
+
{
|
| 61 |
+
'url': resolve_download_url('models-3.3.0', 'nsfw_2.hash'),
|
| 62 |
+
'path': resolve_relative_path('../.assets/models/nsfw_2.hash')
|
| 63 |
+
}
|
| 64 |
+
},
|
| 65 |
+
'sources':
|
| 66 |
+
{
|
| 67 |
+
'content_analyser':
|
| 68 |
+
{
|
| 69 |
+
'url': resolve_download_url('models-3.3.0', 'nsfw_2.onnx'),
|
| 70 |
+
'path': resolve_relative_path('../.assets/models/nsfw_2.onnx')
|
| 71 |
+
}
|
| 72 |
+
},
|
| 73 |
+
'size': (384, 384),
|
| 74 |
+
'mean': (0.5, 0.5, 0.5),
|
| 75 |
+
'standard_deviation': (0.5, 0.5, 0.5)
|
| 76 |
+
},
|
| 77 |
+
'nsfw_3':
|
| 78 |
+
{
|
| 79 |
+
'__metadata__':
|
| 80 |
+
{
|
| 81 |
+
'vendor': 'Freepik',
|
| 82 |
+
'license': 'MIT',
|
| 83 |
+
'year': 2025
|
| 84 |
+
},
|
| 85 |
+
'hashes':
|
| 86 |
+
{
|
| 87 |
+
'content_analyser':
|
| 88 |
+
{
|
| 89 |
+
'url': resolve_download_url('models-3.3.0', 'nsfw_3.hash'),
|
| 90 |
+
'path': resolve_relative_path('../.assets/models/nsfw_3.hash')
|
| 91 |
+
}
|
| 92 |
+
},
|
| 93 |
+
'sources':
|
| 94 |
+
{
|
| 95 |
+
'content_analyser':
|
| 96 |
+
{
|
| 97 |
+
'url': resolve_download_url('models-3.3.0', 'nsfw_3.onnx'),
|
| 98 |
+
'path': resolve_relative_path('../.assets/models/nsfw_3.onnx')
|
| 99 |
+
}
|
| 100 |
+
},
|
| 101 |
+
'size': (448, 448),
|
| 102 |
+
'mean': (0.48145466, 0.4578275, 0.40821073),
|
| 103 |
+
'standard_deviation': (0.26862954, 0.26130258, 0.27577711)
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def get_inference_pool() -> InferencePool:
|
| 109 |
+
model_names = [ 'nsfw_1', 'nsfw_2', 'nsfw_3' ]
|
| 110 |
+
_, model_source_set = collect_model_downloads()
|
| 111 |
+
|
| 112 |
+
return inference_manager.get_inference_pool(__name__, model_names, model_source_set)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def clear_inference_pool() -> None:
|
| 116 |
+
model_names = [ 'nsfw_1', 'nsfw_2', 'nsfw_3' ]
|
| 117 |
+
inference_manager.clear_inference_pool(__name__, model_names)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def collect_model_downloads() -> Tuple[DownloadSet, DownloadSet]:
|
| 121 |
+
model_set = create_static_model_set('full')
|
| 122 |
+
model_hash_set = {}
|
| 123 |
+
model_source_set = {}
|
| 124 |
+
|
| 125 |
+
for content_analyser_model in [ 'nsfw_1', 'nsfw_2', 'nsfw_3' ]:
|
| 126 |
+
model_hash_set[content_analyser_model] = model_set.get(content_analyser_model).get('hashes').get('content_analyser')
|
| 127 |
+
model_source_set[content_analyser_model] = model_set.get(content_analyser_model).get('sources').get('content_analyser')
|
| 128 |
+
|
| 129 |
+
return model_hash_set, model_source_set
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def pre_check() -> bool:
|
| 133 |
+
model_hash_set, model_source_set = collect_model_downloads()
|
| 134 |
+
|
| 135 |
+
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def analyse_stream(vision_frame : VisionFrame, video_fps : Fps) -> bool:
|
| 139 |
+
global STREAM_COUNTER
|
| 140 |
+
|
| 141 |
+
STREAM_COUNTER = STREAM_COUNTER + 1
|
| 142 |
+
if STREAM_COUNTER % int(video_fps) == 0:
|
| 143 |
+
return analyse_frame(vision_frame)
|
| 144 |
+
return False
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def analyse_frame(vision_frame : VisionFrame) -> bool:
|
| 148 |
+
return detect_nsfw(vision_frame)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
@lru_cache()
|
| 152 |
+
def analyse_image(image_path : str) -> bool:
|
| 153 |
+
vision_frame = read_image(image_path)
|
| 154 |
+
return analyse_frame(vision_frame)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
@lru_cache()
|
| 158 |
+
def analyse_video(video_path : str, trim_frame_start : int, trim_frame_end : int) -> bool:
|
| 159 |
+
video_fps = detect_video_fps(video_path)
|
| 160 |
+
frame_range = range(trim_frame_start, trim_frame_end)
|
| 161 |
+
video_reader = video_manager.get_reader(video_path, 'analyse_video')
|
| 162 |
+
rate = 0.0
|
| 163 |
+
total = 0
|
| 164 |
+
counter = 0
|
| 165 |
+
|
| 166 |
+
if trim_frame_start > 0:
|
| 167 |
+
video_manager.seek_video_reader(video_reader, trim_frame_start)
|
| 168 |
+
|
| 169 |
+
with tqdm(total = len(frame_range), desc = translator.get('analysing'), unit = 'frame', ascii = ' =', disable = state_manager.get_item('log_level') in [ 'warn', 'error' ]) as progress:
|
| 170 |
+
|
| 171 |
+
for frame_number in frame_range:
|
| 172 |
+
vision_frame = video_manager.read_video_frame(video_reader)
|
| 173 |
+
|
| 174 |
+
if frame_number % int(video_fps) == 0:
|
| 175 |
+
if is_vision_frame(vision_frame):
|
| 176 |
+
total += 1
|
| 177 |
+
|
| 178 |
+
if analyse_frame(vision_frame):
|
| 179 |
+
counter += 1
|
| 180 |
+
|
| 181 |
+
if counter > 0 and total > 0:
|
| 182 |
+
rate = counter / total * 100
|
| 183 |
+
|
| 184 |
+
progress.set_postfix(rate = rate)
|
| 185 |
+
progress.update()
|
| 186 |
+
|
| 187 |
+
return bool(rate > 10.0)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def detect_nsfw(vision_frame : VisionFrame) -> bool:
|
| 191 |
+
is_nsfw_1 = detect_with_nsfw_1(vision_frame)
|
| 192 |
+
is_nsfw_2 = detect_with_nsfw_2(vision_frame)
|
| 193 |
+
is_nsfw_3 = detect_with_nsfw_3(vision_frame)
|
| 194 |
+
|
| 195 |
+
return is_nsfw_1 and is_nsfw_2 or is_nsfw_1 and is_nsfw_3 or is_nsfw_2 and is_nsfw_3
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def detect_with_nsfw_1(vision_frame : VisionFrame) -> bool:
|
| 199 |
+
detect_vision_frame = prepare_detect_frame(vision_frame, 'nsfw_1')
|
| 200 |
+
detection = forward_nsfw(detect_vision_frame, 'nsfw_1')
|
| 201 |
+
detection_score = numpy.max(numpy.amax(detection[:, 4:], axis = 1))
|
| 202 |
+
return bool(detection_score > 0.2)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def detect_with_nsfw_2(vision_frame : VisionFrame) -> bool:
|
| 206 |
+
detect_vision_frame = prepare_detect_frame(vision_frame, 'nsfw_2')
|
| 207 |
+
detection = forward_nsfw(detect_vision_frame, 'nsfw_2')
|
| 208 |
+
detection_score = detection[0] - detection[1]
|
| 209 |
+
return bool(detection_score > 0.25)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def detect_with_nsfw_3(vision_frame : VisionFrame) -> bool:
|
| 213 |
+
detect_vision_frame = prepare_detect_frame(vision_frame, 'nsfw_3')
|
| 214 |
+
detection = forward_nsfw(detect_vision_frame, 'nsfw_3')
|
| 215 |
+
detection_score = (detection[2] + detection[3]) - (detection[0] + detection[1])
|
| 216 |
+
return bool(detection_score > 10.5)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def forward_nsfw(vision_frame : VisionFrame, model_name : str) -> Detection:
|
| 220 |
+
content_analyser = get_inference_pool().get(model_name)
|
| 221 |
+
|
| 222 |
+
with conditional_thread_semaphore():
|
| 223 |
+
detection = content_analyser.run(None,
|
| 224 |
+
{
|
| 225 |
+
'input': vision_frame
|
| 226 |
+
})[0]
|
| 227 |
+
|
| 228 |
+
if model_name in [ 'nsfw_2', 'nsfw_3' ]:
|
| 229 |
+
return detection[0]
|
| 230 |
+
|
| 231 |
+
return detection
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def prepare_detect_frame(temp_vision_frame : VisionFrame, model_name : str) -> VisionFrame:
|
| 235 |
+
model_set = create_static_model_set('full').get(model_name)
|
| 236 |
+
model_size = model_set.get('size')
|
| 237 |
+
model_mean = model_set.get('mean')
|
| 238 |
+
model_standard_deviation = model_set.get('standard_deviation')
|
| 239 |
+
|
| 240 |
+
detect_vision_frame = fit_contain_frame(temp_vision_frame, model_size)
|
| 241 |
+
detect_vision_frame = detect_vision_frame[:, :, ::-1] / 255.0
|
| 242 |
+
detect_vision_frame -= model_mean
|
| 243 |
+
detect_vision_frame /= model_standard_deviation
|
| 244 |
+
detect_vision_frame = numpy.expand_dims(detect_vision_frame.transpose(2, 0, 1), axis = 0).astype(numpy.float32)
|
| 245 |
+
return detect_vision_frame
|
core.py
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import itertools
|
| 3 |
+
import shutil
|
| 4 |
+
import signal
|
| 5 |
+
import sys
|
| 6 |
+
from time import time
|
| 7 |
+
|
| 8 |
+
from facefusion import benchmarker, cli_helper, content_analyser, hash_helper, logger, state_manager, translator
|
| 9 |
+
from facefusion.args import apply_args, collect_job_args, reduce_job_args, reduce_step_args
|
| 10 |
+
from facefusion.download import conditional_download_hashes, conditional_download_sources
|
| 11 |
+
from facefusion.exit_helper import hard_exit, signal_exit
|
| 12 |
+
from facefusion.filesystem import get_file_extension, get_file_name, is_video, resolve_file_paths, resolve_file_pattern
|
| 13 |
+
from facefusion.jobs import job_helper, job_manager, job_runner
|
| 14 |
+
from facefusion.jobs.job_list import compose_job_list
|
| 15 |
+
from facefusion.processors.core import get_processors_modules
|
| 16 |
+
from facefusion.program import create_program
|
| 17 |
+
from facefusion.program_helper import validate_args
|
| 18 |
+
from facefusion.types import Args, ErrorCode, WorkflowMode
|
| 19 |
+
from facefusion.workflows import image_to_image, image_to_video
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def cli() -> None:
|
| 23 |
+
if pre_check():
|
| 24 |
+
signal.signal(signal.SIGINT, signal_exit)
|
| 25 |
+
program = create_program()
|
| 26 |
+
|
| 27 |
+
if validate_args(program):
|
| 28 |
+
args = vars(program.parse_args())
|
| 29 |
+
apply_args(args, state_manager.init_item)
|
| 30 |
+
|
| 31 |
+
if state_manager.get_item('command'):
|
| 32 |
+
logger.init(state_manager.get_item('log_level'))
|
| 33 |
+
route(args)
|
| 34 |
+
else:
|
| 35 |
+
program.print_help()
|
| 36 |
+
else:
|
| 37 |
+
hard_exit(2)
|
| 38 |
+
else:
|
| 39 |
+
hard_exit(2)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def route(args : Args) -> None:
|
| 43 |
+
if state_manager.get_item('command') == 'force-download':
|
| 44 |
+
error_code = force_download()
|
| 45 |
+
hard_exit(error_code)
|
| 46 |
+
|
| 47 |
+
if state_manager.get_item('command') == 'benchmark':
|
| 48 |
+
if not common_pre_check() or not processors_pre_check() or not benchmarker.pre_check():
|
| 49 |
+
hard_exit(2)
|
| 50 |
+
benchmarker.render()
|
| 51 |
+
|
| 52 |
+
if state_manager.get_item('command') in [ 'job-list', 'job-create', 'job-submit', 'job-submit-all', 'job-delete', 'job-delete-all', 'job-add-step', 'job-remix-step', 'job-insert-step', 'job-remove-step' ]:
|
| 53 |
+
if not job_manager.init_jobs(state_manager.get_item('jobs_path')):
|
| 54 |
+
hard_exit(1)
|
| 55 |
+
error_code = route_job_manager(args)
|
| 56 |
+
hard_exit(error_code)
|
| 57 |
+
|
| 58 |
+
if state_manager.get_item('command') == 'run':
|
| 59 |
+
import facefusion.uis.core as ui
|
| 60 |
+
|
| 61 |
+
if not common_pre_check() or not processors_pre_check():
|
| 62 |
+
hard_exit(2)
|
| 63 |
+
for ui_layout in ui.get_ui_layouts_modules(state_manager.get_item('ui_layouts')):
|
| 64 |
+
if not ui_layout.pre_check():
|
| 65 |
+
hard_exit(2)
|
| 66 |
+
ui.init()
|
| 67 |
+
ui.launch()
|
| 68 |
+
|
| 69 |
+
if state_manager.get_item('command') == 'headless-run':
|
| 70 |
+
if not job_manager.init_jobs(state_manager.get_item('jobs_path')):
|
| 71 |
+
hard_exit(1)
|
| 72 |
+
error_code = process_headless(args)
|
| 73 |
+
hard_exit(error_code)
|
| 74 |
+
|
| 75 |
+
if state_manager.get_item('command') == 'batch-run':
|
| 76 |
+
if not job_manager.init_jobs(state_manager.get_item('jobs_path')):
|
| 77 |
+
hard_exit(1)
|
| 78 |
+
error_code = process_batch(args)
|
| 79 |
+
hard_exit(error_code)
|
| 80 |
+
|
| 81 |
+
if state_manager.get_item('command') in [ 'job-run', 'job-run-all', 'job-retry', 'job-retry-all' ]:
|
| 82 |
+
if not job_manager.init_jobs(state_manager.get_item('jobs_path')):
|
| 83 |
+
hard_exit(1)
|
| 84 |
+
error_code = route_job_runner()
|
| 85 |
+
hard_exit(error_code)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def pre_check() -> bool:
|
| 89 |
+
if sys.version_info < (3, 10):
|
| 90 |
+
logger.error(translator.get('python_not_supported').format(version = '3.10'), __name__)
|
| 91 |
+
return False
|
| 92 |
+
|
| 93 |
+
for dependency in [ 'curl', 'ffmpeg', 'ffprobe' ]:
|
| 94 |
+
if not shutil.which(dependency):
|
| 95 |
+
logger.error(translator.get('dependency_not_installed').format(dependency = dependency), __name__)
|
| 96 |
+
return False
|
| 97 |
+
return True
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def common_pre_check() -> bool:
|
| 101 |
+
content_analyser_content = inspect.getsource(content_analyser).encode()
|
| 102 |
+
|
| 103 |
+
return hash_helper.create_hash(content_analyser_content) == '3c6ce25e'
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def processors_pre_check() -> bool:
|
| 107 |
+
for processor_module in get_processors_modules(state_manager.get_item('processors')):
|
| 108 |
+
if not processor_module.pre_check():
|
| 109 |
+
return False
|
| 110 |
+
return True
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def force_download() -> ErrorCode:
|
| 114 |
+
download_scope = state_manager.get_item('download_scope')
|
| 115 |
+
available_processors = [ get_file_name(file_path) for file_path in resolve_file_paths('facefusion/processors/modules') ]
|
| 116 |
+
processor_modules = get_processors_modules(available_processors)
|
| 117 |
+
common_modules = []
|
| 118 |
+
|
| 119 |
+
for processor_module in processor_modules:
|
| 120 |
+
for common_module in processor_module.get_common_modules():
|
| 121 |
+
if common_module not in common_modules:
|
| 122 |
+
common_modules.append(common_module)
|
| 123 |
+
|
| 124 |
+
for module in common_modules + processor_modules:
|
| 125 |
+
if hasattr(module, 'create_static_model_set'):
|
| 126 |
+
for model in module.create_static_model_set(download_scope).values():
|
| 127 |
+
model_hash_set = model.get('hashes')
|
| 128 |
+
model_source_set = model.get('sources')
|
| 129 |
+
|
| 130 |
+
if model_hash_set and model_source_set:
|
| 131 |
+
if not conditional_download_hashes(model_hash_set) or not conditional_download_sources(model_source_set):
|
| 132 |
+
return 1
|
| 133 |
+
|
| 134 |
+
return 0
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def route_job_manager(args : Args) -> ErrorCode:
|
| 138 |
+
if state_manager.get_item('command') == 'job-list':
|
| 139 |
+
job_headers, job_contents = compose_job_list(state_manager.get_item('job_status'))
|
| 140 |
+
|
| 141 |
+
if job_contents:
|
| 142 |
+
cli_helper.render_table(job_headers, job_contents)
|
| 143 |
+
return 0
|
| 144 |
+
return 1
|
| 145 |
+
|
| 146 |
+
if state_manager.get_item('command') == 'job-create':
|
| 147 |
+
if job_manager.create_job(state_manager.get_item('job_id')):
|
| 148 |
+
logger.info(translator.get('job_created').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 149 |
+
return 0
|
| 150 |
+
logger.error(translator.get('job_not_created').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 151 |
+
return 1
|
| 152 |
+
|
| 153 |
+
if state_manager.get_item('command') == 'job-submit':
|
| 154 |
+
if job_manager.submit_job(state_manager.get_item('job_id')):
|
| 155 |
+
logger.info(translator.get('job_submitted').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 156 |
+
return 0
|
| 157 |
+
logger.error(translator.get('job_not_submitted').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 158 |
+
return 1
|
| 159 |
+
|
| 160 |
+
if state_manager.get_item('command') == 'job-submit-all':
|
| 161 |
+
if job_manager.submit_jobs(state_manager.get_item('halt_on_error')):
|
| 162 |
+
logger.info(translator.get('job_all_submitted'), __name__)
|
| 163 |
+
return 0
|
| 164 |
+
logger.error(translator.get('job_all_not_submitted'), __name__)
|
| 165 |
+
return 1
|
| 166 |
+
|
| 167 |
+
if state_manager.get_item('command') == 'job-delete':
|
| 168 |
+
if job_manager.delete_job(state_manager.get_item('job_id')):
|
| 169 |
+
logger.info(translator.get('job_deleted').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 170 |
+
return 0
|
| 171 |
+
logger.error(translator.get('job_not_deleted').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 172 |
+
return 1
|
| 173 |
+
|
| 174 |
+
if state_manager.get_item('command') == 'job-delete-all':
|
| 175 |
+
if job_manager.delete_jobs(state_manager.get_item('halt_on_error')):
|
| 176 |
+
logger.info(translator.get('job_all_deleted'), __name__)
|
| 177 |
+
return 0
|
| 178 |
+
logger.error(translator.get('job_all_not_deleted'), __name__)
|
| 179 |
+
return 1
|
| 180 |
+
|
| 181 |
+
if state_manager.get_item('command') == 'job-add-step':
|
| 182 |
+
step_args = reduce_step_args(args)
|
| 183 |
+
|
| 184 |
+
if job_manager.add_step(state_manager.get_item('job_id'), step_args):
|
| 185 |
+
logger.info(translator.get('job_step_added').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 186 |
+
return 0
|
| 187 |
+
logger.error(translator.get('job_step_not_added').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 188 |
+
return 1
|
| 189 |
+
|
| 190 |
+
if state_manager.get_item('command') == 'job-remix-step':
|
| 191 |
+
step_args = reduce_step_args(args)
|
| 192 |
+
|
| 193 |
+
if job_manager.remix_step(state_manager.get_item('job_id'), state_manager.get_item('step_index'), step_args):
|
| 194 |
+
logger.info(translator.get('job_remix_step_added').format(job_id = state_manager.get_item('job_id'), step_index = state_manager.get_item('step_index')), __name__)
|
| 195 |
+
return 0
|
| 196 |
+
logger.error(translator.get('job_remix_step_not_added').format(job_id = state_manager.get_item('job_id'), step_index = state_manager.get_item('step_index')), __name__)
|
| 197 |
+
return 1
|
| 198 |
+
|
| 199 |
+
if state_manager.get_item('command') == 'job-insert-step':
|
| 200 |
+
step_args = reduce_step_args(args)
|
| 201 |
+
|
| 202 |
+
if job_manager.insert_step(state_manager.get_item('job_id'), state_manager.get_item('step_index'), step_args):
|
| 203 |
+
logger.info(translator.get('job_step_inserted').format(job_id = state_manager.get_item('job_id'), step_index = state_manager.get_item('step_index')), __name__)
|
| 204 |
+
return 0
|
| 205 |
+
logger.error(translator.get('job_step_not_inserted').format(job_id = state_manager.get_item('job_id'), step_index = state_manager.get_item('step_index')), __name__)
|
| 206 |
+
return 1
|
| 207 |
+
|
| 208 |
+
if state_manager.get_item('command') == 'job-remove-step':
|
| 209 |
+
if job_manager.remove_step(state_manager.get_item('job_id'), state_manager.get_item('step_index')):
|
| 210 |
+
logger.info(translator.get('job_step_removed').format(job_id = state_manager.get_item('job_id'), step_index = state_manager.get_item('step_index')), __name__)
|
| 211 |
+
return 0
|
| 212 |
+
logger.error(translator.get('job_step_not_removed').format(job_id = state_manager.get_item('job_id'), step_index = state_manager.get_item('step_index')), __name__)
|
| 213 |
+
return 1
|
| 214 |
+
return 1
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def route_job_runner() -> ErrorCode:
|
| 218 |
+
if state_manager.get_item('command') == 'job-run':
|
| 219 |
+
logger.info(translator.get('running_job').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 220 |
+
if job_runner.run_job(state_manager.get_item('job_id'), process_step):
|
| 221 |
+
logger.info(translator.get('processing_job_succeeded').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 222 |
+
return 0
|
| 223 |
+
logger.info(translator.get('processing_job_failed').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 224 |
+
return 1
|
| 225 |
+
|
| 226 |
+
if state_manager.get_item('command') == 'job-run-all':
|
| 227 |
+
logger.info(translator.get('running_jobs'), __name__)
|
| 228 |
+
if job_runner.run_jobs(process_step, state_manager.get_item('halt_on_error')):
|
| 229 |
+
logger.info(translator.get('processing_jobs_succeeded'), __name__)
|
| 230 |
+
return 0
|
| 231 |
+
logger.info(translator.get('processing_jobs_failed'), __name__)
|
| 232 |
+
return 1
|
| 233 |
+
|
| 234 |
+
if state_manager.get_item('command') == 'job-retry':
|
| 235 |
+
logger.info(translator.get('retrying_job').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 236 |
+
if job_runner.retry_job(state_manager.get_item('job_id'), process_step):
|
| 237 |
+
logger.info(translator.get('processing_job_succeeded').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 238 |
+
return 0
|
| 239 |
+
logger.info(translator.get('processing_job_failed').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 240 |
+
return 1
|
| 241 |
+
|
| 242 |
+
if state_manager.get_item('command') == 'job-retry-all':
|
| 243 |
+
logger.info(translator.get('retrying_jobs'), __name__)
|
| 244 |
+
if job_runner.retry_jobs(process_step, state_manager.get_item('halt_on_error')):
|
| 245 |
+
logger.info(translator.get('processing_jobs_succeeded'), __name__)
|
| 246 |
+
return 0
|
| 247 |
+
logger.info(translator.get('processing_jobs_failed'), __name__)
|
| 248 |
+
return 1
|
| 249 |
+
return 2
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def process_headless(args : Args) -> ErrorCode:
|
| 253 |
+
job_id = job_helper.suggest_job_id('headless')
|
| 254 |
+
step_args = reduce_step_args(args)
|
| 255 |
+
|
| 256 |
+
if job_manager.create_job(job_id) and job_manager.add_step(job_id, step_args) and job_manager.submit_job(job_id) and job_runner.run_job(job_id, process_step):
|
| 257 |
+
return 0
|
| 258 |
+
return 1
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def process_batch(args : Args) -> ErrorCode:
|
| 262 |
+
job_id = job_helper.suggest_job_id('batch')
|
| 263 |
+
step_args = reduce_step_args(args)
|
| 264 |
+
job_args = reduce_job_args(args)
|
| 265 |
+
source_paths = resolve_file_pattern(job_args.get('source_pattern'))
|
| 266 |
+
target_paths = resolve_file_pattern(job_args.get('target_pattern'))
|
| 267 |
+
|
| 268 |
+
if job_manager.create_job(job_id):
|
| 269 |
+
if source_paths and target_paths:
|
| 270 |
+
for index, (source_path, target_path) in enumerate(itertools.product(source_paths, target_paths)):
|
| 271 |
+
step_args['source_paths'] = [ source_path ]
|
| 272 |
+
step_args['target_path'] = target_path
|
| 273 |
+
|
| 274 |
+
try:
|
| 275 |
+
step_args['output_path'] = job_args.get('output_pattern').format(index = index, source_name = get_file_name(source_path), target_name = get_file_name(target_path), target_extension = get_file_extension(target_path))
|
| 276 |
+
except KeyError:
|
| 277 |
+
return 1
|
| 278 |
+
|
| 279 |
+
if not job_manager.add_step(job_id, step_args):
|
| 280 |
+
return 1
|
| 281 |
+
if job_manager.submit_job(job_id) and job_runner.run_job(job_id, process_step):
|
| 282 |
+
return 0
|
| 283 |
+
|
| 284 |
+
if not source_paths and target_paths:
|
| 285 |
+
for index, target_path in enumerate(target_paths):
|
| 286 |
+
step_args['target_path'] = target_path
|
| 287 |
+
|
| 288 |
+
try:
|
| 289 |
+
step_args['output_path'] = job_args.get('output_pattern').format(index = index, target_name = get_file_name(target_path), target_extension = get_file_extension(target_path))
|
| 290 |
+
except KeyError:
|
| 291 |
+
return 1
|
| 292 |
+
|
| 293 |
+
if not job_manager.add_step(job_id, step_args):
|
| 294 |
+
return 1
|
| 295 |
+
if job_manager.submit_job(job_id) and job_runner.run_job(job_id, process_step):
|
| 296 |
+
return 0
|
| 297 |
+
return 1
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def process_step(job_id : str, step_index : int, step_args : Args) -> bool:
|
| 301 |
+
step_total = job_manager.count_step_total(job_id)
|
| 302 |
+
step_args.update(collect_job_args())
|
| 303 |
+
apply_args(step_args, state_manager.set_item)
|
| 304 |
+
|
| 305 |
+
logger.info(translator.get('processing_step').format(step_current = step_index + 1, step_total = step_total), __name__)
|
| 306 |
+
if common_pre_check() and processors_pre_check():
|
| 307 |
+
error_code = conditional_process()
|
| 308 |
+
return error_code == 0
|
| 309 |
+
return False
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def conditional_process() -> ErrorCode:
|
| 313 |
+
start_time = time()
|
| 314 |
+
|
| 315 |
+
if state_manager.get_item('workflow_mode') == 'auto':
|
| 316 |
+
state_manager.set_item('workflow_mode', detect_workflow_mode())
|
| 317 |
+
|
| 318 |
+
if state_manager.get_item('workflow_mode') == detect_workflow_mode():
|
| 319 |
+
for processor_module in get_processors_modules(state_manager.get_item('processors')):
|
| 320 |
+
if not processor_module.pre_process('output'):
|
| 321 |
+
return 2
|
| 322 |
+
|
| 323 |
+
if state_manager.get_item('workflow_mode') == 'image-to-image':
|
| 324 |
+
return image_to_image.process(start_time)
|
| 325 |
+
if state_manager.get_item('workflow_mode') == 'image-to-video':
|
| 326 |
+
return image_to_video.process(start_time)
|
| 327 |
+
|
| 328 |
+
return 0
|
| 329 |
+
|
| 330 |
+
return 2
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def detect_workflow_mode() -> WorkflowMode:
|
| 334 |
+
if is_video(state_manager.get_item('target_path')):
|
| 335 |
+
return 'image-to-video'
|
| 336 |
+
|
| 337 |
+
return 'image-to-image'
|
| 338 |
+
|
| 339 |
+
|
curl_builder.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
import shutil
|
| 3 |
+
from typing import List
|
| 4 |
+
|
| 5 |
+
from facefusion import metadata
|
| 6 |
+
from facefusion.types import Command
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def run(commands : List[Command]) -> List[Command]:
|
| 10 |
+
user_agent = metadata.get('name') + '/' + metadata.get('version')
|
| 11 |
+
|
| 12 |
+
return [ shutil.which('curl'), '--user-agent', user_agent, '--location', '--silent', '--ssl-no-revoke' ] + commands
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def chain(*commands : List[Command]) -> List[Command]:
|
| 16 |
+
return list(itertools.chain(*commands))
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def ping(url : str) -> List[Command]:
|
| 20 |
+
return [ '-I', url ]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def download(url : str, download_file_path : str) -> List[Command]:
|
| 24 |
+
return [ '--create-dirs', '--continue-at', '-', '--output', download_file_path, url ]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def set_timeout(timeout : int) -> List[Command]:
|
| 28 |
+
return [ '--connect-timeout', str(timeout) ]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def set_retry(retry : int) -> List[Command]:
|
| 32 |
+
return [ '--retry', str(retry) ]
|
download.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import subprocess
|
| 3 |
+
from functools import lru_cache
|
| 4 |
+
from typing import List, Optional, Tuple
|
| 5 |
+
from urllib.parse import urlparse
|
| 6 |
+
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
|
| 9 |
+
import facefusion.choices
|
| 10 |
+
from facefusion import curl_builder, logger, process_manager, state_manager, translator
|
| 11 |
+
from facefusion.filesystem import get_file_name, get_file_size, is_file, remove_file
|
| 12 |
+
from facefusion.hash_helper import validate_hash
|
| 13 |
+
from facefusion.types import Command, DownloadProvider, DownloadSet
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def open_curl(commands : List[Command]) -> subprocess.Popen[bytes]:
|
| 17 |
+
commands = curl_builder.run(commands)
|
| 18 |
+
return subprocess.Popen(commands, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def conditional_download(download_directory_path : str, urls : List[str]) -> None:
|
| 22 |
+
for url in urls:
|
| 23 |
+
download_file_name = os.path.basename(urlparse(url).path)
|
| 24 |
+
download_file_path = os.path.join(download_directory_path, download_file_name)
|
| 25 |
+
initial_size = get_file_size(download_file_path)
|
| 26 |
+
download_size = get_static_download_size(url)
|
| 27 |
+
|
| 28 |
+
if initial_size < download_size:
|
| 29 |
+
with tqdm(total = download_size, initial = initial_size, desc = translator.get('downloading'), unit = 'B', unit_scale = True, unit_divisor = 1024, ascii = ' =', disable = state_manager.get_item('log_level') in [ 'warn', 'error' ]) as progress:
|
| 30 |
+
commands = curl_builder.chain(
|
| 31 |
+
curl_builder.download(url, download_file_path),
|
| 32 |
+
curl_builder.set_timeout(5),
|
| 33 |
+
curl_builder.set_retry(5)
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
open_curl(commands)
|
| 37 |
+
current_size = initial_size
|
| 38 |
+
progress.set_postfix(download_providers = state_manager.get_item('download_providers'), file_name = download_file_name)
|
| 39 |
+
|
| 40 |
+
while current_size < download_size:
|
| 41 |
+
if is_file(download_file_path):
|
| 42 |
+
current_size = get_file_size(download_file_path)
|
| 43 |
+
progress.update(current_size - progress.n)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@lru_cache(maxsize = 64)
|
| 47 |
+
def get_static_download_size(url : str) -> int:
|
| 48 |
+
commands = curl_builder.chain(
|
| 49 |
+
curl_builder.ping(url),
|
| 50 |
+
curl_builder.set_timeout(5)
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
process = open_curl(commands)
|
| 54 |
+
lines = reversed(process.stdout.readlines())
|
| 55 |
+
|
| 56 |
+
for line in lines:
|
| 57 |
+
__line__ = line.decode().lower()
|
| 58 |
+
if 'content-length:' in __line__:
|
| 59 |
+
_, content_length = __line__.split('content-length:')
|
| 60 |
+
return int(content_length)
|
| 61 |
+
|
| 62 |
+
return 0
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@lru_cache(maxsize = 64)
|
| 66 |
+
def ping_static_url(url : str) -> bool:
|
| 67 |
+
commands = curl_builder.chain(
|
| 68 |
+
curl_builder.ping(url),
|
| 69 |
+
curl_builder.set_timeout(5)
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
process = open_curl(commands)
|
| 73 |
+
process.communicate()
|
| 74 |
+
return process.returncode == 0
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def conditional_download_hashes(hash_set : DownloadSet) -> bool:
|
| 78 |
+
hash_paths = [ hash_set.get(hash_key).get('path') for hash_key in hash_set.keys() ]
|
| 79 |
+
|
| 80 |
+
process_manager.check()
|
| 81 |
+
_, invalid_hash_paths = validate_hash_paths(hash_paths)
|
| 82 |
+
if invalid_hash_paths:
|
| 83 |
+
for index in hash_set:
|
| 84 |
+
if hash_set.get(index).get('path') in invalid_hash_paths:
|
| 85 |
+
invalid_hash_url = hash_set.get(index).get('url')
|
| 86 |
+
if invalid_hash_url:
|
| 87 |
+
download_directory_path = os.path.dirname(hash_set.get(index).get('path'))
|
| 88 |
+
conditional_download(download_directory_path, [ invalid_hash_url ])
|
| 89 |
+
|
| 90 |
+
valid_hash_paths, invalid_hash_paths = validate_hash_paths(hash_paths)
|
| 91 |
+
|
| 92 |
+
for valid_hash_path in valid_hash_paths:
|
| 93 |
+
valid_hash_file_name = get_file_name(valid_hash_path)
|
| 94 |
+
logger.debug(translator.get('validating_hash_succeeded').format(hash_file_name = valid_hash_file_name), __name__)
|
| 95 |
+
for invalid_hash_path in invalid_hash_paths:
|
| 96 |
+
invalid_hash_file_name = get_file_name(invalid_hash_path)
|
| 97 |
+
logger.error(translator.get('validating_hash_failed').format(hash_file_name = invalid_hash_file_name), __name__)
|
| 98 |
+
|
| 99 |
+
if not invalid_hash_paths:
|
| 100 |
+
process_manager.end()
|
| 101 |
+
return not invalid_hash_paths
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def conditional_download_sources(source_set : DownloadSet) -> bool:
|
| 105 |
+
source_paths = [ source_set.get(source_key).get('path') for source_key in source_set.keys() ]
|
| 106 |
+
|
| 107 |
+
process_manager.check()
|
| 108 |
+
_, invalid_source_paths = validate_source_paths(source_paths)
|
| 109 |
+
if invalid_source_paths:
|
| 110 |
+
for index in source_set:
|
| 111 |
+
if source_set.get(index).get('path') in invalid_source_paths:
|
| 112 |
+
invalid_source_url = source_set.get(index).get('url')
|
| 113 |
+
if invalid_source_url:
|
| 114 |
+
download_directory_path = os.path.dirname(source_set.get(index).get('path'))
|
| 115 |
+
conditional_download(download_directory_path, [ invalid_source_url ])
|
| 116 |
+
|
| 117 |
+
valid_source_paths, invalid_source_paths = validate_source_paths(source_paths)
|
| 118 |
+
|
| 119 |
+
for valid_source_path in valid_source_paths:
|
| 120 |
+
valid_source_file_name = get_file_name(valid_source_path)
|
| 121 |
+
logger.debug(translator.get('validating_source_succeeded').format(source_file_name = valid_source_file_name), __name__)
|
| 122 |
+
for invalid_source_path in invalid_source_paths:
|
| 123 |
+
invalid_source_file_name = get_file_name(invalid_source_path)
|
| 124 |
+
logger.error(translator.get('validating_source_failed').format(source_file_name = invalid_source_file_name), __name__)
|
| 125 |
+
|
| 126 |
+
if remove_file(invalid_source_path):
|
| 127 |
+
logger.error(translator.get('deleting_corrupt_source').format(source_file_name = invalid_source_file_name), __name__)
|
| 128 |
+
|
| 129 |
+
if not invalid_source_paths:
|
| 130 |
+
process_manager.end()
|
| 131 |
+
return not invalid_source_paths
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def validate_hash_paths(hash_paths : List[str]) -> Tuple[List[str], List[str]]:
|
| 135 |
+
valid_hash_paths = []
|
| 136 |
+
invalid_hash_paths = []
|
| 137 |
+
|
| 138 |
+
for hash_path in hash_paths:
|
| 139 |
+
if is_file(hash_path):
|
| 140 |
+
valid_hash_paths.append(hash_path)
|
| 141 |
+
else:
|
| 142 |
+
invalid_hash_paths.append(hash_path)
|
| 143 |
+
|
| 144 |
+
return valid_hash_paths, invalid_hash_paths
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def validate_source_paths(source_paths : List[str]) -> Tuple[List[str], List[str]]:
|
| 148 |
+
valid_source_paths = []
|
| 149 |
+
invalid_source_paths = []
|
| 150 |
+
|
| 151 |
+
for source_path in source_paths:
|
| 152 |
+
if validate_hash(source_path):
|
| 153 |
+
valid_source_paths.append(source_path)
|
| 154 |
+
else:
|
| 155 |
+
invalid_source_paths.append(source_path)
|
| 156 |
+
|
| 157 |
+
return valid_source_paths, invalid_source_paths
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def resolve_download_url(base_name : str, file_name : str) -> Optional[str]:
|
| 161 |
+
download_providers = state_manager.get_item('download_providers')
|
| 162 |
+
|
| 163 |
+
for download_provider in download_providers:
|
| 164 |
+
download_url = resolve_download_url_by_provider(download_provider, base_name, file_name)
|
| 165 |
+
if download_url:
|
| 166 |
+
return download_url
|
| 167 |
+
|
| 168 |
+
return None
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def resolve_download_url_by_provider(download_provider : DownloadProvider, base_name : str, file_name : str) -> Optional[str]:
|
| 172 |
+
download_provider_value = facefusion.choices.download_provider_set.get(download_provider)
|
| 173 |
+
|
| 174 |
+
for download_provider_url in download_provider_value.get('urls'):
|
| 175 |
+
if ping_static_url(download_provider_url):
|
| 176 |
+
return download_provider_url + download_provider_value.get('path').format(base_name = base_name, file_name = file_name)
|
| 177 |
+
|
| 178 |
+
return None
|
execution.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import shutil
|
| 3 |
+
import subprocess
|
| 4 |
+
import xml.etree.ElementTree as ElementTree
|
| 5 |
+
from functools import lru_cache
|
| 6 |
+
from typing import List, Optional
|
| 7 |
+
|
| 8 |
+
import onnxruntime
|
| 9 |
+
|
| 10 |
+
import facefusion.choices
|
| 11 |
+
from facefusion.filesystem import create_directory, is_directory
|
| 12 |
+
from facefusion.types import ExecutionDevice, ExecutionProvider, InferenceOptionSet, InferenceProvider, ValueAndUnit
|
| 13 |
+
|
| 14 |
+
onnxruntime.set_default_logger_severity(3)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def has_execution_provider(execution_provider : ExecutionProvider) -> bool:
|
| 18 |
+
return execution_provider in get_available_execution_providers()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def get_available_execution_providers() -> List[ExecutionProvider]:
|
| 22 |
+
inference_session_providers = onnxruntime.get_available_providers()
|
| 23 |
+
available_execution_providers : List[ExecutionProvider] = []
|
| 24 |
+
|
| 25 |
+
for execution_provider, execution_provider_value in facefusion.choices.execution_provider_set.items():
|
| 26 |
+
if execution_provider_value in inference_session_providers:
|
| 27 |
+
index = facefusion.choices.execution_providers.index(execution_provider)
|
| 28 |
+
available_execution_providers.insert(index, execution_provider)
|
| 29 |
+
|
| 30 |
+
return available_execution_providers
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def create_inference_providers(execution_device_id : int, execution_providers : List[ExecutionProvider]) -> List[InferenceProvider]:
|
| 34 |
+
inference_providers : List[InferenceProvider] = []
|
| 35 |
+
cache_path = resolve_cache_path()
|
| 36 |
+
|
| 37 |
+
for execution_provider in execution_providers:
|
| 38 |
+
if execution_provider == 'cuda':
|
| 39 |
+
inference_providers.append((facefusion.choices.execution_provider_set.get(execution_provider),
|
| 40 |
+
{
|
| 41 |
+
'device_id': execution_device_id,
|
| 42 |
+
'cudnn_conv_algo_search': resolve_cudnn_conv_algo_search()
|
| 43 |
+
}))
|
| 44 |
+
|
| 45 |
+
if execution_provider == 'tensorrt':
|
| 46 |
+
inference_option_set : InferenceOptionSet =\
|
| 47 |
+
{
|
| 48 |
+
'device_id': execution_device_id
|
| 49 |
+
}
|
| 50 |
+
if is_directory(cache_path) or create_directory(cache_path):
|
| 51 |
+
inference_option_set.update(
|
| 52 |
+
{
|
| 53 |
+
'trt_engine_cache_enable': True,
|
| 54 |
+
'trt_engine_cache_path': cache_path,
|
| 55 |
+
'trt_timing_cache_enable': True,
|
| 56 |
+
'trt_timing_cache_path': cache_path,
|
| 57 |
+
'trt_builder_optimization_level': 4
|
| 58 |
+
})
|
| 59 |
+
inference_providers.append((facefusion.choices.execution_provider_set.get(execution_provider), inference_option_set))
|
| 60 |
+
|
| 61 |
+
if execution_provider in [ 'directml', 'rocm' ]:
|
| 62 |
+
inference_providers.append((facefusion.choices.execution_provider_set.get(execution_provider),
|
| 63 |
+
{
|
| 64 |
+
'device_id': execution_device_id
|
| 65 |
+
}))
|
| 66 |
+
|
| 67 |
+
if execution_provider == 'migraphx':
|
| 68 |
+
inference_option_set =\
|
| 69 |
+
{
|
| 70 |
+
'device_id': execution_device_id
|
| 71 |
+
}
|
| 72 |
+
if is_directory(cache_path) or create_directory(cache_path):
|
| 73 |
+
inference_option_set.update(
|
| 74 |
+
{
|
| 75 |
+
'migraphx_model_cache_dir': cache_path
|
| 76 |
+
})
|
| 77 |
+
inference_providers.append((facefusion.choices.execution_provider_set.get(execution_provider), inference_option_set))
|
| 78 |
+
|
| 79 |
+
if execution_provider == 'coreml':
|
| 80 |
+
inference_option_set =\
|
| 81 |
+
{
|
| 82 |
+
'SpecializationStrategy': 'FastPrediction'
|
| 83 |
+
}
|
| 84 |
+
if is_directory(cache_path) or create_directory(cache_path):
|
| 85 |
+
inference_option_set.update(
|
| 86 |
+
{
|
| 87 |
+
'ModelCacheDirectory': cache_path
|
| 88 |
+
})
|
| 89 |
+
inference_providers.append((facefusion.choices.execution_provider_set.get(execution_provider), inference_option_set))
|
| 90 |
+
|
| 91 |
+
if execution_provider == 'openvino':
|
| 92 |
+
inference_providers.append((facefusion.choices.execution_provider_set.get(execution_provider),
|
| 93 |
+
{
|
| 94 |
+
'device_type': resolve_openvino_device_type(execution_device_id),
|
| 95 |
+
'precision': 'FP32'
|
| 96 |
+
}))
|
| 97 |
+
|
| 98 |
+
if execution_provider == 'qnn':
|
| 99 |
+
inference_providers.append((facefusion.choices.execution_provider_set.get(execution_provider),
|
| 100 |
+
{
|
| 101 |
+
'device_id': execution_device_id,
|
| 102 |
+
'backend_type': 'htp'
|
| 103 |
+
}))
|
| 104 |
+
|
| 105 |
+
if 'cpu' in execution_providers:
|
| 106 |
+
inference_providers.append(facefusion.choices.execution_provider_set.get('cpu'))
|
| 107 |
+
|
| 108 |
+
return inference_providers
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def resolve_cache_path() -> str:
|
| 112 |
+
return os.path.join('.caches', onnxruntime.get_version_string())
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def resolve_cudnn_conv_algo_search() -> str:
|
| 116 |
+
execution_devices = detect_static_execution_devices()
|
| 117 |
+
product_names = ('GeForce GTX 1630', 'GeForce GTX 1650', 'GeForce GTX 1660')
|
| 118 |
+
|
| 119 |
+
for execution_device in execution_devices:
|
| 120 |
+
if execution_device.get('product').get('name').startswith(product_names):
|
| 121 |
+
return 'DEFAULT'
|
| 122 |
+
|
| 123 |
+
return 'EXHAUSTIVE'
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def resolve_openvino_device_type(execution_device_id : int) -> str:
|
| 127 |
+
if execution_device_id == 0:
|
| 128 |
+
return 'GPU'
|
| 129 |
+
return 'GPU.' + str(execution_device_id)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def run_nvidia_smi() -> subprocess.Popen[bytes]:
|
| 133 |
+
commands = [ shutil.which('nvidia-smi'), '--query', '--xml-format' ]
|
| 134 |
+
return subprocess.Popen(commands, stdout = subprocess.PIPE)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
@lru_cache()
|
| 138 |
+
def detect_static_execution_devices() -> List[ExecutionDevice]:
|
| 139 |
+
return detect_execution_devices()
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def detect_execution_devices() -> List[ExecutionDevice]:
|
| 143 |
+
execution_devices : List[ExecutionDevice] = []
|
| 144 |
+
|
| 145 |
+
try:
|
| 146 |
+
output, _ = run_nvidia_smi().communicate()
|
| 147 |
+
root_element = ElementTree.fromstring(output)
|
| 148 |
+
except Exception:
|
| 149 |
+
root_element = ElementTree.Element('xml')
|
| 150 |
+
|
| 151 |
+
for gpu_element in root_element.findall('gpu'):
|
| 152 |
+
execution_devices.append(
|
| 153 |
+
{
|
| 154 |
+
'driver_version': root_element.findtext('driver_version'),
|
| 155 |
+
'framework':
|
| 156 |
+
{
|
| 157 |
+
'name': 'CUDA',
|
| 158 |
+
'version': root_element.findtext('cuda_version')
|
| 159 |
+
},
|
| 160 |
+
'product':
|
| 161 |
+
{
|
| 162 |
+
'vendor': 'NVIDIA',
|
| 163 |
+
'name': gpu_element.findtext('product_name').replace('NVIDIA', '').strip()
|
| 164 |
+
},
|
| 165 |
+
'video_memory':
|
| 166 |
+
{
|
| 167 |
+
'total': create_value_and_unit(gpu_element.findtext('fb_memory_usage/total')),
|
| 168 |
+
'free': create_value_and_unit(gpu_element.findtext('fb_memory_usage/free'))
|
| 169 |
+
},
|
| 170 |
+
'temperature':
|
| 171 |
+
{
|
| 172 |
+
'gpu': create_value_and_unit(gpu_element.findtext('temperature/gpu_temp')),
|
| 173 |
+
'memory': create_value_and_unit(gpu_element.findtext('temperature/memory_temp'))
|
| 174 |
+
},
|
| 175 |
+
'utilization':
|
| 176 |
+
{
|
| 177 |
+
'gpu': create_value_and_unit(gpu_element.findtext('utilization/gpu_util')),
|
| 178 |
+
'memory': create_value_and_unit(gpu_element.findtext('utilization/memory_util'))
|
| 179 |
+
}
|
| 180 |
+
})
|
| 181 |
+
|
| 182 |
+
return execution_devices
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def create_value_and_unit(text : str) -> Optional[ValueAndUnit]:
|
| 186 |
+
if ' ' in text:
|
| 187 |
+
value, unit = text.split()
|
| 188 |
+
|
| 189 |
+
return\
|
| 190 |
+
{
|
| 191 |
+
'value': int(value),
|
| 192 |
+
'unit': str(unit)
|
| 193 |
+
}
|
| 194 |
+
return None
|
exit_helper.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import signal
|
| 3 |
+
import sys
|
| 4 |
+
from time import sleep
|
| 5 |
+
from types import FrameType
|
| 6 |
+
|
| 7 |
+
from facefusion import process_manager, state_manager
|
| 8 |
+
from facefusion.temp_helper import clear_temp_directory
|
| 9 |
+
from facefusion.types import ErrorCode
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def fatal_exit(error_code : ErrorCode) -> None:
|
| 13 |
+
os._exit(error_code)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def hard_exit(error_code : ErrorCode) -> None:
|
| 17 |
+
sys.exit(error_code)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def signal_exit(signum : int, frame : FrameType) -> None:
|
| 21 |
+
graceful_exit(0)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def graceful_exit(error_code : ErrorCode) -> None:
|
| 25 |
+
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
| 26 |
+
process_manager.stop()
|
| 27 |
+
|
| 28 |
+
while process_manager.is_processing():
|
| 29 |
+
sleep(0.5)
|
| 30 |
+
|
| 31 |
+
if state_manager.get_item('target_path'):
|
| 32 |
+
clear_temp_directory(state_manager.get_item('target_path'))
|
| 33 |
+
|
| 34 |
+
hard_exit(error_code)
|
face_classifier.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
from typing import List, Tuple
|
| 3 |
+
|
| 4 |
+
import numpy
|
| 5 |
+
|
| 6 |
+
from facefusion import inference_manager
|
| 7 |
+
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
| 8 |
+
from facefusion.face_helper import warp_face_by_face_landmark_5
|
| 9 |
+
from facefusion.filesystem import resolve_relative_path
|
| 10 |
+
from facefusion.thread_helper import conditional_thread_semaphore
|
| 11 |
+
from facefusion.types import Age, DownloadScope, FaceLandmark5, Gender, InferencePool, ModelOptions, ModelSet, Race, VisionFrame
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@lru_cache()
|
| 15 |
+
def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
| 16 |
+
return\
|
| 17 |
+
{
|
| 18 |
+
'fairface':
|
| 19 |
+
{
|
| 20 |
+
'__metadata__':
|
| 21 |
+
{
|
| 22 |
+
'vendor': 'dchen236',
|
| 23 |
+
'license': 'CC-BY-4.0',
|
| 24 |
+
'year': 2021
|
| 25 |
+
},
|
| 26 |
+
'hashes':
|
| 27 |
+
{
|
| 28 |
+
'face_classifier':
|
| 29 |
+
{
|
| 30 |
+
'url': resolve_download_url('models-3.0.0', 'fairface.hash'),
|
| 31 |
+
'path': resolve_relative_path('../.assets/models/fairface.hash')
|
| 32 |
+
}
|
| 33 |
+
},
|
| 34 |
+
'sources':
|
| 35 |
+
{
|
| 36 |
+
'face_classifier':
|
| 37 |
+
{
|
| 38 |
+
'url': resolve_download_url('models-3.0.0', 'fairface.onnx'),
|
| 39 |
+
'path': resolve_relative_path('../.assets/models/fairface.onnx')
|
| 40 |
+
}
|
| 41 |
+
},
|
| 42 |
+
'template': 'arcface_112_v2',
|
| 43 |
+
'size': (224, 224),
|
| 44 |
+
'mean': [ 0.485, 0.456, 0.406 ],
|
| 45 |
+
'standard_deviation': [ 0.229, 0.224, 0.225 ]
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def get_inference_pool() -> InferencePool:
|
| 51 |
+
model_names = [ 'fairface' ]
|
| 52 |
+
model_source_set = get_model_options().get('sources')
|
| 53 |
+
|
| 54 |
+
return inference_manager.get_inference_pool(__name__, model_names, model_source_set)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def clear_inference_pool() -> None:
|
| 58 |
+
model_names = [ 'fairface' ]
|
| 59 |
+
inference_manager.clear_inference_pool(__name__, model_names)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def get_model_options() -> ModelOptions:
|
| 63 |
+
return create_static_model_set('full').get('fairface')
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def pre_check() -> bool:
|
| 67 |
+
model_hash_set = get_model_options().get('hashes')
|
| 68 |
+
model_source_set = get_model_options().get('sources')
|
| 69 |
+
|
| 70 |
+
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def classify_face(temp_vision_frame : VisionFrame, face_landmark_5 : FaceLandmark5) -> Tuple[Gender, Age, Race]:
|
| 74 |
+
model_template = get_model_options().get('template')
|
| 75 |
+
model_size = get_model_options().get('size')
|
| 76 |
+
model_mean = get_model_options().get('mean')
|
| 77 |
+
model_standard_deviation = get_model_options().get('standard_deviation')
|
| 78 |
+
crop_vision_frame, _ = warp_face_by_face_landmark_5(temp_vision_frame, face_landmark_5, model_template, model_size)
|
| 79 |
+
crop_vision_frame = crop_vision_frame.astype(numpy.float32)[:, :, ::-1] / 255.0
|
| 80 |
+
crop_vision_frame -= model_mean
|
| 81 |
+
crop_vision_frame /= model_standard_deviation
|
| 82 |
+
crop_vision_frame = crop_vision_frame.transpose(2, 0, 1)
|
| 83 |
+
crop_vision_frame = numpy.expand_dims(crop_vision_frame, axis = 0)
|
| 84 |
+
gender_id, age_id, race_id = forward(crop_vision_frame)
|
| 85 |
+
gender = categorize_gender(gender_id[0])
|
| 86 |
+
age = categorize_age(age_id[0])
|
| 87 |
+
race = categorize_race(race_id[0])
|
| 88 |
+
return gender, age, race
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def forward(crop_vision_frame : VisionFrame) -> Tuple[List[int], List[int], List[int]]:
|
| 92 |
+
face_classifier = get_inference_pool().get('face_classifier')
|
| 93 |
+
|
| 94 |
+
with conditional_thread_semaphore():
|
| 95 |
+
race_id, gender_id, age_id = face_classifier.run(None,
|
| 96 |
+
{
|
| 97 |
+
'input': crop_vision_frame
|
| 98 |
+
})
|
| 99 |
+
|
| 100 |
+
return gender_id, age_id, race_id
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def categorize_gender(gender_id : int) -> Gender:
|
| 104 |
+
if gender_id == 1:
|
| 105 |
+
return 'female'
|
| 106 |
+
return 'male'
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def categorize_age(age_id : int) -> Age:
|
| 110 |
+
if age_id == 0:
|
| 111 |
+
return range(0, 2)
|
| 112 |
+
if age_id == 1:
|
| 113 |
+
return range(3, 9)
|
| 114 |
+
if age_id == 2:
|
| 115 |
+
return range(10, 19)
|
| 116 |
+
if age_id == 3:
|
| 117 |
+
return range(20, 29)
|
| 118 |
+
if age_id == 4:
|
| 119 |
+
return range(30, 39)
|
| 120 |
+
if age_id == 5:
|
| 121 |
+
return range(40, 49)
|
| 122 |
+
if age_id == 6:
|
| 123 |
+
return range(50, 59)
|
| 124 |
+
if age_id == 7:
|
| 125 |
+
return range(60, 69)
|
| 126 |
+
return range(70, 100)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def categorize_race(race_id : int) -> Race:
|
| 130 |
+
if race_id == 1:
|
| 131 |
+
return 'black'
|
| 132 |
+
if race_id == 2:
|
| 133 |
+
return 'latino'
|
| 134 |
+
if race_id == 3 or race_id == 4:
|
| 135 |
+
return 'asian'
|
| 136 |
+
if race_id == 5:
|
| 137 |
+
return 'indian'
|
| 138 |
+
if race_id == 6:
|
| 139 |
+
return 'arabic'
|
| 140 |
+
return 'white'
|
face_creator.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Optional
|
| 2 |
+
|
| 3 |
+
import numpy
|
| 4 |
+
|
| 5 |
+
from facefusion import face_store, state_manager
|
| 6 |
+
from facefusion.common_helper import get_first, get_middle
|
| 7 |
+
from facefusion.face_classifier import classify_face
|
| 8 |
+
from facefusion.face_detector import detect_faces, detect_faces_by_angle
|
| 9 |
+
from facefusion.face_helper import apply_nms, average_points, convert_to_face_landmark_5, estimate_face_angle, get_nms_threshold
|
| 10 |
+
from facefusion.face_landmarker import detect_face_landmark, estimate_face_landmark_68_5
|
| 11 |
+
from facefusion.face_recognizer import calculate_face_embedding
|
| 12 |
+
from facefusion.types import BoundingBox, Face, FaceLandmark5, FaceLandmarkSet, FaceScoreSet, Score, VisionFrame
|
| 13 |
+
from facefusion.vision import is_vision_frame
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def create_faces(vision_frame : VisionFrame, bounding_boxes : List[BoundingBox], face_scores : List[Score], face_landmarks_5 : List[FaceLandmark5]) -> List[Face]:
|
| 17 |
+
faces = []
|
| 18 |
+
nms_threshold = get_nms_threshold(state_manager.get_item('face_detector_model'), state_manager.get_item('face_detector_angles'))
|
| 19 |
+
keep_indices = apply_nms(bounding_boxes, face_scores, state_manager.get_item('face_detector_score'), nms_threshold)
|
| 20 |
+
|
| 21 |
+
for index in keep_indices:
|
| 22 |
+
bounding_box = bounding_boxes[index]
|
| 23 |
+
face_score = face_scores[index]
|
| 24 |
+
face_landmark_5 = face_landmarks_5[index]
|
| 25 |
+
face_landmark_5_68 = face_landmark_5
|
| 26 |
+
face_landmark_68_5 = estimate_face_landmark_68_5(face_landmark_5_68)
|
| 27 |
+
face_landmark_68 = face_landmark_68_5
|
| 28 |
+
face_landmark_score_68 = 0.0
|
| 29 |
+
face_angle = estimate_face_angle(face_landmark_68_5)
|
| 30 |
+
|
| 31 |
+
if state_manager.get_item('face_landmarker_score') > 0:
|
| 32 |
+
face_landmark_68, face_landmark_score_68 = detect_face_landmark(vision_frame, bounding_box, face_angle)
|
| 33 |
+
if face_landmark_score_68 > state_manager.get_item('face_landmarker_score'):
|
| 34 |
+
face_landmark_5_68 = convert_to_face_landmark_5(face_landmark_68)
|
| 35 |
+
|
| 36 |
+
face_landmark_set : FaceLandmarkSet =\
|
| 37 |
+
{
|
| 38 |
+
'5': face_landmark_5,
|
| 39 |
+
'5/68': face_landmark_5_68,
|
| 40 |
+
'68': face_landmark_68,
|
| 41 |
+
'68/5': face_landmark_68_5
|
| 42 |
+
}
|
| 43 |
+
face_score_set : FaceScoreSet =\
|
| 44 |
+
{
|
| 45 |
+
'detector': face_score,
|
| 46 |
+
'landmarker': face_landmark_score_68
|
| 47 |
+
}
|
| 48 |
+
face_embedding, face_embedding_norm = calculate_face_embedding(vision_frame, face_landmark_set.get('5/68'))
|
| 49 |
+
gender, age, race = classify_face(vision_frame, face_landmark_set.get('5/68'))
|
| 50 |
+
|
| 51 |
+
faces.append(Face(
|
| 52 |
+
origin = 'detect',
|
| 53 |
+
bounding_box = bounding_box,
|
| 54 |
+
score_set = face_score_set,
|
| 55 |
+
landmark_set = face_landmark_set,
|
| 56 |
+
angle = face_angle,
|
| 57 |
+
embedding = face_embedding,
|
| 58 |
+
embedding_norm = face_embedding_norm,
|
| 59 |
+
gender = gender,
|
| 60 |
+
age = age,
|
| 61 |
+
race = race
|
| 62 |
+
))
|
| 63 |
+
return faces
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def get_one_face(faces : List[Face], position : int = 0) -> Optional[Face]:
|
| 67 |
+
if faces:
|
| 68 |
+
position = min(position, len(faces) - 1)
|
| 69 |
+
return faces[position]
|
| 70 |
+
return None
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def get_many_faces(vision_frames : List[VisionFrame]) -> List[Face]:
|
| 74 |
+
many_faces : List[Face] = []
|
| 75 |
+
|
| 76 |
+
for vision_frame in vision_frames:
|
| 77 |
+
if is_vision_frame(vision_frame):
|
| 78 |
+
all_bounding_boxes = []
|
| 79 |
+
all_face_scores = []
|
| 80 |
+
all_face_landmarks_5 = []
|
| 81 |
+
|
| 82 |
+
for face_detector_angle in state_manager.get_item('face_detector_angles'):
|
| 83 |
+
if face_detector_angle == 0:
|
| 84 |
+
bounding_boxes, face_scores, face_landmarks_5 = detect_faces(vision_frame)
|
| 85 |
+
else:
|
| 86 |
+
bounding_boxes, face_scores, face_landmarks_5 = detect_faces_by_angle(vision_frame, face_detector_angle)
|
| 87 |
+
all_bounding_boxes.extend(bounding_boxes)
|
| 88 |
+
all_face_scores.extend(face_scores)
|
| 89 |
+
all_face_landmarks_5.extend(face_landmarks_5)
|
| 90 |
+
|
| 91 |
+
if all_bounding_boxes and all_face_scores and all_face_landmarks_5 and state_manager.get_item('face_detector_score') > 0:
|
| 92 |
+
faces = create_faces(vision_frame, all_bounding_boxes, all_face_scores, all_face_landmarks_5)
|
| 93 |
+
|
| 94 |
+
if faces:
|
| 95 |
+
many_faces.extend(faces)
|
| 96 |
+
|
| 97 |
+
return many_faces
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def get_static_faces(vision_frames : List[VisionFrame]) -> List[Face]:
|
| 101 |
+
many_faces : List[Face] = []
|
| 102 |
+
|
| 103 |
+
for vision_frame in vision_frames:
|
| 104 |
+
faces = face_store.get_faces(vision_frame)
|
| 105 |
+
|
| 106 |
+
if not faces:
|
| 107 |
+
with face_store.resolve_lock(vision_frame):
|
| 108 |
+
faces = face_store.get_faces(vision_frame)
|
| 109 |
+
|
| 110 |
+
if not faces:
|
| 111 |
+
faces = get_many_faces([ vision_frame ])
|
| 112 |
+
|
| 113 |
+
if faces:
|
| 114 |
+
face_store.set_faces(vision_frame, faces)
|
| 115 |
+
|
| 116 |
+
many_faces.extend(faces)
|
| 117 |
+
|
| 118 |
+
return many_faces
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def refill_faces(faces : List[Optional[Face]]) -> List[Face]:
|
| 122 |
+
fill_faces = []
|
| 123 |
+
anchor_index_previous = -1
|
| 124 |
+
|
| 125 |
+
for index, face in enumerate(faces):
|
| 126 |
+
if face:
|
| 127 |
+
for gap_index in range(anchor_index_previous + 1, index):
|
| 128 |
+
average_factor = (gap_index - anchor_index_previous) / (index - anchor_index_previous)
|
| 129 |
+
average_face = average_face_geometry([faces[anchor_index_previous], face], average_factor)
|
| 130 |
+
fill_faces.append(average_face)
|
| 131 |
+
|
| 132 |
+
fill_faces.append(face)
|
| 133 |
+
anchor_index_previous = index
|
| 134 |
+
|
| 135 |
+
return fill_faces
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def average_face_geometry(faces : List[Face], average_factor : float) -> Face:
|
| 139 |
+
face_first = get_first(faces)
|
| 140 |
+
face_middle = get_middle(faces)
|
| 141 |
+
face_anchor = face_middle
|
| 142 |
+
|
| 143 |
+
if average_factor < 0.5:
|
| 144 |
+
face_anchor = face_first
|
| 145 |
+
|
| 146 |
+
landmark_set : FaceLandmarkSet =\
|
| 147 |
+
{
|
| 148 |
+
'5': average_points(face_first.landmark_set.get('5'), face_middle.landmark_set.get('5'), average_factor),
|
| 149 |
+
'5/68': average_points(face_first.landmark_set.get('5/68'), face_middle.landmark_set.get('5/68'), average_factor),
|
| 150 |
+
'68': average_points(face_first.landmark_set.get('68'), face_middle.landmark_set.get('68'), average_factor),
|
| 151 |
+
'68/5': average_points(face_first.landmark_set.get('68/5'), face_middle.landmark_set.get('68/5'), average_factor)
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
return Face(
|
| 155 |
+
origin = 'refill',
|
| 156 |
+
bounding_box = average_points(face_first.bounding_box, face_middle.bounding_box, average_factor),
|
| 157 |
+
score_set = face_anchor.score_set,
|
| 158 |
+
landmark_set = landmark_set,
|
| 159 |
+
angle = estimate_face_angle(landmark_set.get('68/5')),
|
| 160 |
+
embedding = face_anchor.embedding,
|
| 161 |
+
embedding_norm = face_anchor.embedding_norm,
|
| 162 |
+
gender = face_anchor.gender,
|
| 163 |
+
age = face_anchor.age,
|
| 164 |
+
race = face_anchor.race
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def average_face_identity(faces : List[Face]) -> Optional[Face]:
|
| 169 |
+
face_embeddings = []
|
| 170 |
+
face_embeddings_norm = []
|
| 171 |
+
|
| 172 |
+
if faces:
|
| 173 |
+
first_face = get_first(faces)
|
| 174 |
+
|
| 175 |
+
for face in faces:
|
| 176 |
+
face_embeddings.append(face.embedding)
|
| 177 |
+
face_embeddings_norm.append(face.embedding_norm)
|
| 178 |
+
|
| 179 |
+
return Face(
|
| 180 |
+
origin = first_face.origin,
|
| 181 |
+
bounding_box = first_face.bounding_box,
|
| 182 |
+
score_set = first_face.score_set,
|
| 183 |
+
landmark_set = first_face.landmark_set,
|
| 184 |
+
angle = first_face.angle,
|
| 185 |
+
embedding = numpy.mean(face_embeddings, axis = 0),
|
| 186 |
+
embedding_norm = numpy.mean(face_embeddings_norm, axis = 0),
|
| 187 |
+
gender = first_face.gender,
|
| 188 |
+
age = first_face.age,
|
| 189 |
+
race = first_face.race
|
| 190 |
+
)
|
| 191 |
+
return None
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def scale_face(target_face : Face, target_vision_frame : VisionFrame, temp_vision_frame : VisionFrame) -> Face:
|
| 195 |
+
scale_x = temp_vision_frame.shape[1] / target_vision_frame.shape[1]
|
| 196 |
+
scale_y = temp_vision_frame.shape[0] / target_vision_frame.shape[0]
|
| 197 |
+
|
| 198 |
+
bounding_box = target_face.bounding_box * [ scale_x, scale_y, scale_x, scale_y ]
|
| 199 |
+
landmark_set =\
|
| 200 |
+
{
|
| 201 |
+
'5': target_face.landmark_set.get('5') * numpy.array([ scale_x, scale_y ]),
|
| 202 |
+
'5/68': target_face.landmark_set.get('5/68') * numpy.array([ scale_x, scale_y ]),
|
| 203 |
+
'68': target_face.landmark_set.get('68') * numpy.array([ scale_x, scale_y ]),
|
| 204 |
+
'68/5': target_face.landmark_set.get('68/5') * numpy.array([ scale_x, scale_y ])
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
return target_face._replace(
|
| 208 |
+
bounding_box = bounding_box,
|
| 209 |
+
landmark_set = landmark_set
|
| 210 |
+
)
|
face_detector.py
ADDED
|
@@ -0,0 +1,458 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
from typing import List, Sequence, Tuple
|
| 3 |
+
|
| 4 |
+
import cv2
|
| 5 |
+
import numpy
|
| 6 |
+
|
| 7 |
+
from facefusion import inference_manager, state_manager
|
| 8 |
+
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
| 9 |
+
from facefusion.face_helper import create_rotation_matrix_and_size, create_static_anchors, distance_to_bounding_box, distance_to_face_landmark_5, normalize_bounding_box, transform_bounding_box, transform_points
|
| 10 |
+
from facefusion.filesystem import resolve_relative_path
|
| 11 |
+
from facefusion.thread_helper import thread_semaphore
|
| 12 |
+
from facefusion.types import Angle, BoundingBox, Detection, DownloadScope, DownloadSet, FaceLandmark5, InferencePool, Margin, ModelSet, Score, VisionFrame
|
| 13 |
+
from facefusion.vision import restrict_frame, unpack_resolution
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@lru_cache()
|
| 17 |
+
def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
| 18 |
+
return\
|
| 19 |
+
{
|
| 20 |
+
'retinaface':
|
| 21 |
+
{
|
| 22 |
+
'__metadata__':
|
| 23 |
+
{
|
| 24 |
+
'vendor': 'InsightFace',
|
| 25 |
+
'license': 'Non-Commercial',
|
| 26 |
+
'year': 2020
|
| 27 |
+
},
|
| 28 |
+
'hashes':
|
| 29 |
+
{
|
| 30 |
+
'retinaface':
|
| 31 |
+
{
|
| 32 |
+
'url': resolve_download_url('models-3.0.0', 'retinaface_10g.hash'),
|
| 33 |
+
'path': resolve_relative_path('../.assets/models/retinaface_10g.hash')
|
| 34 |
+
}
|
| 35 |
+
},
|
| 36 |
+
'sources':
|
| 37 |
+
{
|
| 38 |
+
'retinaface':
|
| 39 |
+
{
|
| 40 |
+
'url': resolve_download_url('models-3.0.0', 'retinaface_10g.onnx'),
|
| 41 |
+
'path': resolve_relative_path('../.assets/models/retinaface_10g.onnx')
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
},
|
| 45 |
+
'scrfd':
|
| 46 |
+
{
|
| 47 |
+
'__metadata__':
|
| 48 |
+
{
|
| 49 |
+
'vendor': 'InsightFace',
|
| 50 |
+
'license': 'Non-Commercial',
|
| 51 |
+
'year': 2021
|
| 52 |
+
},
|
| 53 |
+
'hashes':
|
| 54 |
+
{
|
| 55 |
+
'scrfd':
|
| 56 |
+
{
|
| 57 |
+
'url': resolve_download_url('models-3.0.0', 'scrfd_2.5g.hash'),
|
| 58 |
+
'path': resolve_relative_path('../.assets/models/scrfd_2.5g.hash')
|
| 59 |
+
}
|
| 60 |
+
},
|
| 61 |
+
'sources':
|
| 62 |
+
{
|
| 63 |
+
'scrfd':
|
| 64 |
+
{
|
| 65 |
+
'url': resolve_download_url('models-3.0.0', 'scrfd_2.5g.onnx'),
|
| 66 |
+
'path': resolve_relative_path('../.assets/models/scrfd_2.5g.onnx')
|
| 67 |
+
}
|
| 68 |
+
}
|
| 69 |
+
},
|
| 70 |
+
'yolo_face':
|
| 71 |
+
{
|
| 72 |
+
'__metadata__':
|
| 73 |
+
{
|
| 74 |
+
'vendor': 'derronqi',
|
| 75 |
+
'license': 'GPL-3.0',
|
| 76 |
+
'year': 2022
|
| 77 |
+
},
|
| 78 |
+
'hashes':
|
| 79 |
+
{
|
| 80 |
+
'yolo_face':
|
| 81 |
+
{
|
| 82 |
+
'url': resolve_download_url('models-3.0.0', 'yoloface_8n.hash'),
|
| 83 |
+
'path': resolve_relative_path('../.assets/models/yoloface_8n.hash')
|
| 84 |
+
}
|
| 85 |
+
},
|
| 86 |
+
'sources':
|
| 87 |
+
{
|
| 88 |
+
'yolo_face':
|
| 89 |
+
{
|
| 90 |
+
'url': resolve_download_url('models-3.0.0', 'yoloface_8n.onnx'),
|
| 91 |
+
'path': resolve_relative_path('../.assets/models/yoloface_8n.onnx')
|
| 92 |
+
}
|
| 93 |
+
}
|
| 94 |
+
},
|
| 95 |
+
'yunet':
|
| 96 |
+
{
|
| 97 |
+
'__metadata__':
|
| 98 |
+
{
|
| 99 |
+
'vendor': 'OpenCV',
|
| 100 |
+
'license': 'MIT',
|
| 101 |
+
'year': 2023
|
| 102 |
+
},
|
| 103 |
+
'hashes':
|
| 104 |
+
{
|
| 105 |
+
'yunet':
|
| 106 |
+
{
|
| 107 |
+
'url': resolve_download_url('models-3.4.0', 'yunet_2023_mar.hash'),
|
| 108 |
+
'path': resolve_relative_path('../.assets/models/yunet_2023_mar.hash')
|
| 109 |
+
}
|
| 110 |
+
},
|
| 111 |
+
'sources':
|
| 112 |
+
{
|
| 113 |
+
'yunet':
|
| 114 |
+
{
|
| 115 |
+
'url': resolve_download_url('models-3.4.0', 'yunet_2023_mar.onnx'),
|
| 116 |
+
'path': resolve_relative_path('../.assets/models/yunet_2023_mar.onnx')
|
| 117 |
+
}
|
| 118 |
+
}
|
| 119 |
+
}
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def get_inference_pool() -> InferencePool:
|
| 124 |
+
model_names = [ state_manager.get_item('face_detector_model') ]
|
| 125 |
+
_, model_source_set = collect_model_downloads()
|
| 126 |
+
|
| 127 |
+
return inference_manager.get_inference_pool(__name__, model_names, model_source_set)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def clear_inference_pool() -> None:
|
| 131 |
+
model_names = [ state_manager.get_item('face_detector_model') ]
|
| 132 |
+
inference_manager.clear_inference_pool(__name__, model_names)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def collect_model_downloads() -> Tuple[DownloadSet, DownloadSet]:
|
| 136 |
+
model_set = create_static_model_set('full')
|
| 137 |
+
model_hash_set = {}
|
| 138 |
+
model_source_set = {}
|
| 139 |
+
|
| 140 |
+
for face_detector_model in [ 'retinaface', 'scrfd', 'yolo_face', 'yunet' ]:
|
| 141 |
+
if state_manager.get_item('face_detector_model') in [ 'many', face_detector_model ]:
|
| 142 |
+
model_hash_set[face_detector_model] = model_set.get(face_detector_model).get('hashes').get(face_detector_model)
|
| 143 |
+
model_source_set[face_detector_model] = model_set.get(face_detector_model).get('sources').get(face_detector_model)
|
| 144 |
+
|
| 145 |
+
return model_hash_set, model_source_set
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def pre_check() -> bool:
|
| 149 |
+
model_hash_set, model_source_set = collect_model_downloads()
|
| 150 |
+
|
| 151 |
+
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def detect_faces(vision_frame : VisionFrame) -> Tuple[List[BoundingBox], List[Score], List[FaceLandmark5]]:
|
| 155 |
+
margin_top, margin_right, margin_bottom, margin_left = prepare_margin(vision_frame)
|
| 156 |
+
margin_vision_frame = numpy.pad(vision_frame, ((margin_top, margin_bottom), (margin_left, margin_right), (0, 0)))
|
| 157 |
+
all_bounding_boxes : List[BoundingBox] = []
|
| 158 |
+
all_face_scores : List[Score] = []
|
| 159 |
+
all_face_landmarks_5 : List[FaceLandmark5] = []
|
| 160 |
+
|
| 161 |
+
if state_manager.get_item('face_detector_model') in [ 'many', 'retinaface' ]:
|
| 162 |
+
bounding_boxes, face_scores, face_landmarks_5 = detect_with_retinaface(margin_vision_frame, state_manager.get_item('face_detector_size'))
|
| 163 |
+
all_bounding_boxes.extend(bounding_boxes)
|
| 164 |
+
all_face_scores.extend(face_scores)
|
| 165 |
+
all_face_landmarks_5.extend(face_landmarks_5)
|
| 166 |
+
|
| 167 |
+
if state_manager.get_item('face_detector_model') in [ 'many', 'scrfd' ]:
|
| 168 |
+
bounding_boxes, face_scores, face_landmarks_5 = detect_with_scrfd(margin_vision_frame, state_manager.get_item('face_detector_size'))
|
| 169 |
+
all_bounding_boxes.extend(bounding_boxes)
|
| 170 |
+
all_face_scores.extend(face_scores)
|
| 171 |
+
all_face_landmarks_5.extend(face_landmarks_5)
|
| 172 |
+
|
| 173 |
+
if state_manager.get_item('face_detector_model') in [ 'many', 'yolo_face' ]:
|
| 174 |
+
bounding_boxes, face_scores, face_landmarks_5 = detect_with_yolo_face(margin_vision_frame, state_manager.get_item('face_detector_size'))
|
| 175 |
+
all_bounding_boxes.extend(bounding_boxes)
|
| 176 |
+
all_face_scores.extend(face_scores)
|
| 177 |
+
all_face_landmarks_5.extend(face_landmarks_5)
|
| 178 |
+
|
| 179 |
+
if state_manager.get_item('face_detector_model') == 'yunet':
|
| 180 |
+
bounding_boxes, face_scores, face_landmarks_5 = detect_with_yunet(margin_vision_frame, state_manager.get_item('face_detector_size'))
|
| 181 |
+
all_bounding_boxes.extend(bounding_boxes)
|
| 182 |
+
all_face_scores.extend(face_scores)
|
| 183 |
+
all_face_landmarks_5.extend(face_landmarks_5)
|
| 184 |
+
|
| 185 |
+
all_bounding_boxes = [ normalize_bounding_box(all_bounding_box) - numpy.array([ margin_left, margin_top, margin_left, margin_top ]) for all_bounding_box in all_bounding_boxes ]
|
| 186 |
+
all_face_landmarks_5 = [ all_face_landmark_5 - numpy.array([ margin_left, margin_top ]) for all_face_landmark_5 in all_face_landmarks_5 ]
|
| 187 |
+
return all_bounding_boxes, all_face_scores, all_face_landmarks_5
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def prepare_margin(vision_frame : VisionFrame) -> Margin:
|
| 191 |
+
margin_top = int(vision_frame.shape[0] * numpy.interp(state_manager.get_item('face_detector_margin')[0], [ 0, 100 ], [ 0, 0.5 ]))
|
| 192 |
+
margin_right = int(vision_frame.shape[1] * numpy.interp(state_manager.get_item('face_detector_margin')[1], [ 0, 100 ], [ 0, 0.5 ]))
|
| 193 |
+
margin_bottom = int(vision_frame.shape[0] * numpy.interp(state_manager.get_item('face_detector_margin')[2], [ 0, 100 ], [ 0, 0.5 ]))
|
| 194 |
+
margin_left = int(vision_frame.shape[1] * numpy.interp(state_manager.get_item('face_detector_margin')[3], [ 0, 100 ], [ 0, 0.5 ]))
|
| 195 |
+
return margin_top, margin_right, margin_bottom, margin_left
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def detect_faces_by_angle(vision_frame : VisionFrame, face_angle : Angle) -> Tuple[List[BoundingBox], List[Score], List[FaceLandmark5]]:
|
| 199 |
+
rotation_matrix, rotation_size = create_rotation_matrix_and_size(face_angle, vision_frame.shape[:2][::-1])
|
| 200 |
+
rotation_vision_frame = cv2.warpAffine(vision_frame, rotation_matrix, rotation_size)
|
| 201 |
+
rotation_inverse_matrix = cv2.invertAffineTransform(rotation_matrix)
|
| 202 |
+
bounding_boxes, face_scores, face_landmarks_5 = detect_faces(rotation_vision_frame)
|
| 203 |
+
bounding_boxes = [ transform_bounding_box(bounding_box, rotation_inverse_matrix) for bounding_box in bounding_boxes ]
|
| 204 |
+
face_landmarks_5 = [ transform_points(face_landmark_5, rotation_inverse_matrix) for face_landmark_5 in face_landmarks_5 ]
|
| 205 |
+
return bounding_boxes, face_scores, face_landmarks_5
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def detect_with_retinaface(vision_frame : VisionFrame, face_detector_size : str) -> Tuple[List[BoundingBox], List[Score], List[FaceLandmark5]]:
|
| 209 |
+
bounding_boxes = []
|
| 210 |
+
face_scores = []
|
| 211 |
+
face_landmarks_5 = []
|
| 212 |
+
feature_strides = [ 8, 16, 32 ]
|
| 213 |
+
feature_map_channel = 3
|
| 214 |
+
anchor_total = 2
|
| 215 |
+
face_detector_score = state_manager.get_item('face_detector_score')
|
| 216 |
+
face_detector_width, face_detector_height = unpack_resolution(face_detector_size)
|
| 217 |
+
temp_vision_frame = restrict_frame(vision_frame, (face_detector_width, face_detector_height))
|
| 218 |
+
ratio_height = vision_frame.shape[0] / temp_vision_frame.shape[0]
|
| 219 |
+
ratio_width = vision_frame.shape[1] / temp_vision_frame.shape[1]
|
| 220 |
+
detect_vision_frame = prepare_detect_frame(temp_vision_frame, face_detector_size)
|
| 221 |
+
detect_vision_frame = normalize_detect_frame(detect_vision_frame, [ -1, 1 ])
|
| 222 |
+
detection = forward_with_retinaface(detect_vision_frame)
|
| 223 |
+
|
| 224 |
+
for index, feature_stride in enumerate(feature_strides):
|
| 225 |
+
face_scores_raw = detection[index]
|
| 226 |
+
keep_indices = numpy.where(face_scores_raw >= face_detector_score)[0]
|
| 227 |
+
|
| 228 |
+
if numpy.any(keep_indices):
|
| 229 |
+
stride_height = face_detector_height // feature_stride
|
| 230 |
+
stride_width = face_detector_width // feature_stride
|
| 231 |
+
anchors = create_static_anchors(feature_stride, anchor_total, stride_height, stride_width)
|
| 232 |
+
bounding_boxes_raw = detection[index + feature_map_channel] * feature_stride
|
| 233 |
+
face_landmarks_5_raw = detection[index + feature_map_channel * 2] * feature_stride
|
| 234 |
+
|
| 235 |
+
for bounding_box_raw in distance_to_bounding_box(anchors, bounding_boxes_raw)[keep_indices]:
|
| 236 |
+
bounding_boxes.append(numpy.array(
|
| 237 |
+
[
|
| 238 |
+
bounding_box_raw[0] * ratio_width,
|
| 239 |
+
bounding_box_raw[1] * ratio_height,
|
| 240 |
+
bounding_box_raw[2] * ratio_width,
|
| 241 |
+
bounding_box_raw[3] * ratio_height
|
| 242 |
+
]))
|
| 243 |
+
|
| 244 |
+
for face_score_raw in face_scores_raw[keep_indices]:
|
| 245 |
+
face_scores.append(face_score_raw[0])
|
| 246 |
+
|
| 247 |
+
for face_landmark_raw_5 in distance_to_face_landmark_5(anchors, face_landmarks_5_raw)[keep_indices]:
|
| 248 |
+
face_landmarks_5.append(face_landmark_raw_5 * [ ratio_width, ratio_height ])
|
| 249 |
+
|
| 250 |
+
return bounding_boxes, face_scores, face_landmarks_5
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def detect_with_scrfd(vision_frame : VisionFrame, face_detector_size : str) -> Tuple[List[BoundingBox], List[Score], List[FaceLandmark5]]:
|
| 254 |
+
bounding_boxes = []
|
| 255 |
+
face_scores = []
|
| 256 |
+
face_landmarks_5 = []
|
| 257 |
+
feature_strides = [ 8, 16, 32 ]
|
| 258 |
+
feature_map_channel = 3
|
| 259 |
+
anchor_total = 2
|
| 260 |
+
face_detector_score = state_manager.get_item('face_detector_score')
|
| 261 |
+
face_detector_width, face_detector_height = unpack_resolution(face_detector_size)
|
| 262 |
+
temp_vision_frame = restrict_frame(vision_frame, (face_detector_width, face_detector_height))
|
| 263 |
+
ratio_height = vision_frame.shape[0] / temp_vision_frame.shape[0]
|
| 264 |
+
ratio_width = vision_frame.shape[1] / temp_vision_frame.shape[1]
|
| 265 |
+
detect_vision_frame = prepare_detect_frame(temp_vision_frame, face_detector_size)
|
| 266 |
+
detect_vision_frame = normalize_detect_frame(detect_vision_frame, [ -1, 1 ])
|
| 267 |
+
detection = forward_with_scrfd(detect_vision_frame)
|
| 268 |
+
|
| 269 |
+
for index, feature_stride in enumerate(feature_strides):
|
| 270 |
+
face_scores_raw = detection[index]
|
| 271 |
+
keep_indices = numpy.where(face_scores_raw >= face_detector_score)[0]
|
| 272 |
+
|
| 273 |
+
if numpy.any(keep_indices):
|
| 274 |
+
stride_height = face_detector_height // feature_stride
|
| 275 |
+
stride_width = face_detector_width // feature_stride
|
| 276 |
+
anchors = create_static_anchors(feature_stride, anchor_total, stride_height, stride_width)
|
| 277 |
+
bounding_boxes_raw = detection[index + feature_map_channel] * feature_stride
|
| 278 |
+
face_landmarks_5_raw = detection[index + feature_map_channel * 2] * feature_stride
|
| 279 |
+
|
| 280 |
+
for bounding_box_raw in distance_to_bounding_box(anchors, bounding_boxes_raw)[keep_indices]:
|
| 281 |
+
bounding_boxes.append(numpy.array(
|
| 282 |
+
[
|
| 283 |
+
bounding_box_raw[0] * ratio_width,
|
| 284 |
+
bounding_box_raw[1] * ratio_height,
|
| 285 |
+
bounding_box_raw[2] * ratio_width,
|
| 286 |
+
bounding_box_raw[3] * ratio_height
|
| 287 |
+
]))
|
| 288 |
+
|
| 289 |
+
for face_score_raw in face_scores_raw[keep_indices]:
|
| 290 |
+
face_scores.append(face_score_raw[0])
|
| 291 |
+
|
| 292 |
+
for face_landmark_raw_5 in distance_to_face_landmark_5(anchors, face_landmarks_5_raw)[keep_indices]:
|
| 293 |
+
face_landmarks_5.append(face_landmark_raw_5 * [ ratio_width, ratio_height ])
|
| 294 |
+
|
| 295 |
+
return bounding_boxes, face_scores, face_landmarks_5
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def detect_with_yolo_face(vision_frame : VisionFrame, face_detector_size : str) -> Tuple[List[BoundingBox], List[Score], List[FaceLandmark5]]:
|
| 299 |
+
bounding_boxes = []
|
| 300 |
+
face_scores = []
|
| 301 |
+
face_landmarks_5 = []
|
| 302 |
+
face_detector_score = state_manager.get_item('face_detector_score')
|
| 303 |
+
face_detector_width, face_detector_height = unpack_resolution(face_detector_size)
|
| 304 |
+
temp_vision_frame = restrict_frame(vision_frame, (face_detector_width, face_detector_height))
|
| 305 |
+
ratio_height = vision_frame.shape[0] / temp_vision_frame.shape[0]
|
| 306 |
+
ratio_width = vision_frame.shape[1] / temp_vision_frame.shape[1]
|
| 307 |
+
detect_vision_frame = prepare_detect_frame(temp_vision_frame, face_detector_size)
|
| 308 |
+
detect_vision_frame = normalize_detect_frame(detect_vision_frame, [ 0, 1 ])
|
| 309 |
+
detection = forward_with_yolo_face(detect_vision_frame)
|
| 310 |
+
detection = numpy.squeeze(detection).T
|
| 311 |
+
bounding_boxes_raw, face_scores_raw, face_landmarks_5_raw = numpy.split(detection, [ 4, 5 ], axis = 1)
|
| 312 |
+
keep_indices = numpy.where(face_scores_raw > face_detector_score)[0]
|
| 313 |
+
|
| 314 |
+
if numpy.any(keep_indices):
|
| 315 |
+
bounding_boxes_raw, face_scores_raw, face_landmarks_5_raw = bounding_boxes_raw[keep_indices], face_scores_raw[keep_indices], face_landmarks_5_raw[keep_indices]
|
| 316 |
+
|
| 317 |
+
for bounding_box_raw in bounding_boxes_raw:
|
| 318 |
+
bounding_boxes.append(numpy.array(
|
| 319 |
+
[
|
| 320 |
+
(bounding_box_raw[0] - bounding_box_raw[2] / 2) * ratio_width,
|
| 321 |
+
(bounding_box_raw[1] - bounding_box_raw[3] / 2) * ratio_height,
|
| 322 |
+
(bounding_box_raw[0] + bounding_box_raw[2] / 2) * ratio_width,
|
| 323 |
+
(bounding_box_raw[1] + bounding_box_raw[3] / 2) * ratio_height
|
| 324 |
+
]))
|
| 325 |
+
|
| 326 |
+
face_scores = face_scores_raw.ravel().tolist()
|
| 327 |
+
face_landmarks_5_raw[:, 0::3] = (face_landmarks_5_raw[:, 0::3]) * ratio_width
|
| 328 |
+
face_landmarks_5_raw[:, 1::3] = (face_landmarks_5_raw[:, 1::3]) * ratio_height
|
| 329 |
+
|
| 330 |
+
for face_landmark_raw_5 in face_landmarks_5_raw:
|
| 331 |
+
face_landmarks_5.append(numpy.array(face_landmark_raw_5.reshape(-1, 3)[:, :2]))
|
| 332 |
+
|
| 333 |
+
return bounding_boxes, face_scores, face_landmarks_5
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def detect_with_yunet(vision_frame : VisionFrame, face_detector_size : str) -> Tuple[List[BoundingBox], List[Score], List[FaceLandmark5]]:
|
| 337 |
+
bounding_boxes = []
|
| 338 |
+
face_scores = []
|
| 339 |
+
face_landmarks_5 = []
|
| 340 |
+
feature_strides = [ 8, 16, 32 ]
|
| 341 |
+
feature_map_channel = 3
|
| 342 |
+
anchor_total = 1
|
| 343 |
+
face_detector_score = state_manager.get_item('face_detector_score')
|
| 344 |
+
face_detector_width, face_detector_height = unpack_resolution(face_detector_size)
|
| 345 |
+
temp_vision_frame = restrict_frame(vision_frame, (face_detector_width, face_detector_height))
|
| 346 |
+
ratio_height = vision_frame.shape[0] / temp_vision_frame.shape[0]
|
| 347 |
+
ratio_width = vision_frame.shape[1] / temp_vision_frame.shape[1]
|
| 348 |
+
detect_vision_frame = prepare_detect_frame(temp_vision_frame, face_detector_size)
|
| 349 |
+
detect_vision_frame = normalize_detect_frame(detect_vision_frame, [ 0, 255 ])
|
| 350 |
+
detection = forward_with_yunet(detect_vision_frame)
|
| 351 |
+
|
| 352 |
+
for index, feature_stride in enumerate(feature_strides):
|
| 353 |
+
face_scores_raw = (detection[index] * detection[index + feature_map_channel]).reshape(-1)
|
| 354 |
+
keep_indices = numpy.where(face_scores_raw >= face_detector_score)[0]
|
| 355 |
+
|
| 356 |
+
if numpy.any(keep_indices):
|
| 357 |
+
stride_height = face_detector_height // feature_stride
|
| 358 |
+
stride_width = face_detector_width // feature_stride
|
| 359 |
+
anchors = create_static_anchors(feature_stride, anchor_total, stride_height, stride_width)
|
| 360 |
+
bounding_boxes_center = detection[index + feature_map_channel * 2].squeeze(0)[:, :2] * feature_stride + anchors
|
| 361 |
+
bounding_boxes_size = numpy.exp(detection[index + feature_map_channel * 2].squeeze(0)[:, 2:4]) * feature_stride
|
| 362 |
+
face_landmarks_5_raw = detection[index + feature_map_channel * 3].squeeze(0)
|
| 363 |
+
|
| 364 |
+
bounding_boxes_raw = numpy.stack(
|
| 365 |
+
[
|
| 366 |
+
bounding_boxes_center[:, 0] - bounding_boxes_size[:, 0] / 2,
|
| 367 |
+
bounding_boxes_center[:, 1] - bounding_boxes_size[:, 1] / 2,
|
| 368 |
+
bounding_boxes_center[:, 0] + bounding_boxes_size[:, 0] / 2,
|
| 369 |
+
bounding_boxes_center[:, 1] + bounding_boxes_size[:, 1] / 2
|
| 370 |
+
], axis = -1)
|
| 371 |
+
|
| 372 |
+
for bounding_box_raw in bounding_boxes_raw[keep_indices]:
|
| 373 |
+
bounding_boxes.append(numpy.array(
|
| 374 |
+
[
|
| 375 |
+
bounding_box_raw[0] * ratio_width,
|
| 376 |
+
bounding_box_raw[1] * ratio_height,
|
| 377 |
+
bounding_box_raw[2] * ratio_width,
|
| 378 |
+
bounding_box_raw[3] * ratio_height
|
| 379 |
+
]))
|
| 380 |
+
|
| 381 |
+
face_scores.extend(face_scores_raw[keep_indices])
|
| 382 |
+
face_landmarks_5_raw = numpy.concatenate(
|
| 383 |
+
[
|
| 384 |
+
face_landmarks_5_raw[:, [ 0, 1 ]] * feature_stride + anchors,
|
| 385 |
+
face_landmarks_5_raw[:, [ 2, 3 ]] * feature_stride + anchors,
|
| 386 |
+
face_landmarks_5_raw[:, [ 4, 5 ]] * feature_stride + anchors,
|
| 387 |
+
face_landmarks_5_raw[:, [ 6, 7 ]] * feature_stride + anchors,
|
| 388 |
+
face_landmarks_5_raw[:, [ 8, 9 ]] * feature_stride + anchors
|
| 389 |
+
], axis = -1).reshape(-1, 5, 2)
|
| 390 |
+
|
| 391 |
+
for face_landmark_raw_5 in face_landmarks_5_raw[keep_indices]:
|
| 392 |
+
face_landmarks_5.append(face_landmark_raw_5 * [ ratio_width, ratio_height ])
|
| 393 |
+
|
| 394 |
+
return bounding_boxes, face_scores, face_landmarks_5
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def forward_with_retinaface(detect_vision_frame : VisionFrame) -> Detection:
|
| 398 |
+
face_detector = get_inference_pool().get('retinaface')
|
| 399 |
+
|
| 400 |
+
with thread_semaphore():
|
| 401 |
+
detection = face_detector.run(None,
|
| 402 |
+
{
|
| 403 |
+
'input': detect_vision_frame
|
| 404 |
+
})
|
| 405 |
+
|
| 406 |
+
return detection
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def forward_with_scrfd(detect_vision_frame : VisionFrame) -> Detection:
|
| 410 |
+
face_detector = get_inference_pool().get('scrfd')
|
| 411 |
+
|
| 412 |
+
with thread_semaphore():
|
| 413 |
+
detection = face_detector.run(None,
|
| 414 |
+
{
|
| 415 |
+
'input': detect_vision_frame
|
| 416 |
+
})
|
| 417 |
+
|
| 418 |
+
return detection
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def forward_with_yolo_face(detect_vision_frame : VisionFrame) -> Detection:
|
| 422 |
+
face_detector = get_inference_pool().get('yolo_face')
|
| 423 |
+
|
| 424 |
+
with thread_semaphore():
|
| 425 |
+
detection = face_detector.run(None,
|
| 426 |
+
{
|
| 427 |
+
'input': detect_vision_frame
|
| 428 |
+
})
|
| 429 |
+
|
| 430 |
+
return detection
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def forward_with_yunet(detect_vision_frame : VisionFrame) -> Detection:
|
| 434 |
+
face_detector = get_inference_pool().get('yunet')
|
| 435 |
+
|
| 436 |
+
with thread_semaphore():
|
| 437 |
+
detection = face_detector.run(None,
|
| 438 |
+
{
|
| 439 |
+
'input': detect_vision_frame
|
| 440 |
+
})
|
| 441 |
+
|
| 442 |
+
return detection
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def prepare_detect_frame(temp_vision_frame : VisionFrame, face_detector_size : str) -> VisionFrame:
|
| 446 |
+
face_detector_width, face_detector_height = unpack_resolution(face_detector_size)
|
| 447 |
+
detect_vision_frame = numpy.zeros((face_detector_height, face_detector_width, 3))
|
| 448 |
+
detect_vision_frame[:temp_vision_frame.shape[0], :temp_vision_frame.shape[1], :] = temp_vision_frame
|
| 449 |
+
detect_vision_frame = numpy.expand_dims(detect_vision_frame.transpose(2, 0, 1), axis = 0).astype(numpy.float32)
|
| 450 |
+
return detect_vision_frame
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def normalize_detect_frame(detect_vision_frame : VisionFrame, normalize_range : Sequence[int]) -> VisionFrame:
|
| 454 |
+
if normalize_range == [ -1, 1 ]:
|
| 455 |
+
return (detect_vision_frame - 127.5) / 128.0
|
| 456 |
+
if normalize_range == [ 0, 1 ]:
|
| 457 |
+
return detect_vision_frame / 255.0
|
| 458 |
+
return detect_vision_frame
|
face_helper.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
from typing import List, Sequence, Tuple
|
| 3 |
+
|
| 4 |
+
import cv2
|
| 5 |
+
import numpy
|
| 6 |
+
from cv2.typing import Size
|
| 7 |
+
|
| 8 |
+
from facefusion.types import Anchors, Angle, BoundingBox, Distance, FaceDetectorModel, FaceLandmark5, FaceLandmark68, Mask, Matrix, Points, Scale, Score, Translation, VisionFrame, WarpTemplate, WarpTemplateSet
|
| 9 |
+
|
| 10 |
+
WARP_TEMPLATE_SET : WarpTemplateSet =\
|
| 11 |
+
{
|
| 12 |
+
'arcface_112_v1': numpy.array(
|
| 13 |
+
[
|
| 14 |
+
[ 0.35473214, 0.45658929 ],
|
| 15 |
+
[ 0.64526786, 0.45658929 ],
|
| 16 |
+
[ 0.50000000, 0.61154464 ],
|
| 17 |
+
[ 0.37913393, 0.77687500 ],
|
| 18 |
+
[ 0.62086607, 0.77687500 ]
|
| 19 |
+
]),
|
| 20 |
+
'arcface_112_v2': numpy.array(
|
| 21 |
+
[
|
| 22 |
+
[ 0.34191607, 0.46157411 ],
|
| 23 |
+
[ 0.65653393, 0.45983393 ],
|
| 24 |
+
[ 0.50022500, 0.64050536 ],
|
| 25 |
+
[ 0.37097589, 0.82469196 ],
|
| 26 |
+
[ 0.63151696, 0.82325089 ]
|
| 27 |
+
]),
|
| 28 |
+
'arcface_128': numpy.array(
|
| 29 |
+
[
|
| 30 |
+
[ 0.36167656, 0.40387734 ],
|
| 31 |
+
[ 0.63696719, 0.40235469 ],
|
| 32 |
+
[ 0.50019687, 0.56044219 ],
|
| 33 |
+
[ 0.38710391, 0.72160547 ],
|
| 34 |
+
[ 0.61507734, 0.72034453 ]
|
| 35 |
+
]),
|
| 36 |
+
'dfl_whole_face': numpy.array(
|
| 37 |
+
[
|
| 38 |
+
[ 0.35342266, 0.39285716 ],
|
| 39 |
+
[ 0.62797622, 0.39285716 ],
|
| 40 |
+
[ 0.48660713, 0.54017860 ],
|
| 41 |
+
[ 0.38839287, 0.68750011 ],
|
| 42 |
+
[ 0.59821427, 0.68750011 ]
|
| 43 |
+
]),
|
| 44 |
+
'ffhq_512': numpy.array(
|
| 45 |
+
[
|
| 46 |
+
[ 0.37691676, 0.46864664 ],
|
| 47 |
+
[ 0.62285697, 0.46912813 ],
|
| 48 |
+
[ 0.50123859, 0.61331904 ],
|
| 49 |
+
[ 0.39308822, 0.72541100 ],
|
| 50 |
+
[ 0.61150205, 0.72490465 ]
|
| 51 |
+
]),
|
| 52 |
+
'mtcnn_512': numpy.array(
|
| 53 |
+
[
|
| 54 |
+
[ 0.36562865, 0.46733799 ],
|
| 55 |
+
[ 0.63305391, 0.46585885 ],
|
| 56 |
+
[ 0.50019127, 0.61942959 ],
|
| 57 |
+
[ 0.39032951, 0.77598822 ],
|
| 58 |
+
[ 0.61178945, 0.77476328 ]
|
| 59 |
+
]),
|
| 60 |
+
'styleganex_384': numpy.array(
|
| 61 |
+
[
|
| 62 |
+
[ 0.42353745, 0.52289879 ],
|
| 63 |
+
[ 0.57725008, 0.52319972 ],
|
| 64 |
+
[ 0.50123859, 0.61331904 ],
|
| 65 |
+
[ 0.43364461, 0.68337652 ],
|
| 66 |
+
[ 0.57015325, 0.68306005 ]
|
| 67 |
+
])
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def estimate_matrix_by_face_landmark_5(face_landmark_5 : FaceLandmark5, warp_template : WarpTemplate, crop_size : Size) -> Matrix:
|
| 72 |
+
warp_template_norm = WARP_TEMPLATE_SET.get(warp_template) * crop_size
|
| 73 |
+
affine_matrix = cv2.estimateAffinePartial2D(face_landmark_5, warp_template_norm, method = cv2.RANSAC, ransacReprojThreshold = 100)[0]
|
| 74 |
+
return affine_matrix
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def warp_face_by_face_landmark_5(temp_vision_frame : VisionFrame, face_landmark_5 : FaceLandmark5, warp_template : WarpTemplate, crop_size : Size) -> Tuple[VisionFrame, Matrix]:
|
| 78 |
+
affine_matrix = estimate_matrix_by_face_landmark_5(face_landmark_5, warp_template, crop_size)
|
| 79 |
+
crop_vision_frame = cv2.warpAffine(temp_vision_frame, affine_matrix, crop_size, borderMode = cv2.BORDER_REPLICATE, flags = cv2.INTER_AREA)
|
| 80 |
+
return crop_vision_frame, affine_matrix
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def warp_face_by_bounding_box(temp_vision_frame : VisionFrame, bounding_box : BoundingBox, crop_size : Size) -> Tuple[VisionFrame, Matrix]:
|
| 84 |
+
source_points = numpy.array([ [ bounding_box[0], bounding_box[1] ], [ bounding_box[2], bounding_box[1] ], [ bounding_box[0], bounding_box[3] ] ]).astype(numpy.float32)
|
| 85 |
+
target_points = numpy.array([ [ 0, 0 ], [ crop_size[0], 0 ], [ 0, crop_size[1] ] ]).astype(numpy.float32)
|
| 86 |
+
affine_matrix = cv2.getAffineTransform(source_points, target_points)
|
| 87 |
+
if bounding_box[2] - bounding_box[0] > crop_size[0] or bounding_box[3] - bounding_box[1] > crop_size[1]:
|
| 88 |
+
interpolation_method = cv2.INTER_AREA
|
| 89 |
+
else:
|
| 90 |
+
interpolation_method = cv2.INTER_LINEAR
|
| 91 |
+
crop_vision_frame = cv2.warpAffine(temp_vision_frame, affine_matrix, crop_size, flags = interpolation_method)
|
| 92 |
+
return crop_vision_frame, affine_matrix
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def warp_face_by_translation(temp_vision_frame : VisionFrame, translation : Translation, scale : float, crop_size : Size) -> Tuple[VisionFrame, Matrix]:
|
| 96 |
+
affine_matrix = numpy.array([ [ scale, 0, translation[0] ], [ 0, scale, translation[1] ] ])
|
| 97 |
+
crop_vision_frame = cv2.warpAffine(temp_vision_frame, affine_matrix, crop_size)
|
| 98 |
+
return crop_vision_frame, affine_matrix
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def paste_back(temp_vision_frame : VisionFrame, crop_vision_frame : VisionFrame, crop_vision_mask : Mask, affine_matrix : Matrix) -> VisionFrame:
|
| 102 |
+
paste_bounding_box, paste_matrix = calculate_paste_area(temp_vision_frame, crop_vision_frame, affine_matrix)
|
| 103 |
+
x1, y1, x2, y2 = paste_bounding_box
|
| 104 |
+
paste_width = x2 - x1
|
| 105 |
+
paste_height = y2 - y1
|
| 106 |
+
inverse_vision_mask = cv2.warpAffine(crop_vision_mask, paste_matrix, (paste_width, paste_height)).clip(0, 1)
|
| 107 |
+
inverse_vision_mask = numpy.expand_dims(inverse_vision_mask, axis = -1)
|
| 108 |
+
inverse_vision_frame = cv2.warpAffine(crop_vision_frame, paste_matrix, (paste_width, paste_height), borderMode = cv2.BORDER_REPLICATE)
|
| 109 |
+
temp_vision_frame = temp_vision_frame.copy()
|
| 110 |
+
paste_vision_frame = temp_vision_frame[y1:y2, x1:x2]
|
| 111 |
+
paste_vision_frame = paste_vision_frame * (1 - inverse_vision_mask) + inverse_vision_frame * inverse_vision_mask
|
| 112 |
+
temp_vision_frame[y1:y2, x1:x2] = paste_vision_frame.astype(temp_vision_frame.dtype)
|
| 113 |
+
return temp_vision_frame
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def calculate_paste_area(temp_vision_frame : VisionFrame, crop_vision_frame : VisionFrame, affine_matrix : Matrix) -> Tuple[BoundingBox, Matrix]:
|
| 117 |
+
temp_height, temp_width = temp_vision_frame.shape[:2]
|
| 118 |
+
crop_height, crop_width = crop_vision_frame.shape[:2]
|
| 119 |
+
inverse_matrix = cv2.invertAffineTransform(affine_matrix)
|
| 120 |
+
crop_points = numpy.array([ [ 0, 0 ], [ crop_width, 0 ], [ crop_width, crop_height ], [ 0, crop_height ] ])
|
| 121 |
+
paste_region_points = transform_points(crop_points, inverse_matrix)
|
| 122 |
+
paste_region_point_min = numpy.floor(paste_region_points.min(axis = 0)).astype(int)
|
| 123 |
+
paste_region_point_max = numpy.ceil(paste_region_points.max(axis = 0)).astype(int)
|
| 124 |
+
x1, y1 = numpy.clip(paste_region_point_min, 0, [ temp_width, temp_height ])
|
| 125 |
+
x2, y2 = numpy.clip(paste_region_point_max, 0, [ temp_width, temp_height ])
|
| 126 |
+
paste_bounding_box = numpy.array([ x1, y1, x2, y2 ])
|
| 127 |
+
paste_matrix = inverse_matrix.copy()
|
| 128 |
+
paste_matrix[0, 2] -= x1
|
| 129 |
+
paste_matrix[1, 2] -= y1
|
| 130 |
+
return paste_bounding_box, paste_matrix
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@lru_cache()
|
| 134 |
+
def create_static_anchors(feature_stride : int, anchor_total : int, stride_height : int, stride_width : int) -> Anchors:
|
| 135 |
+
x, y = numpy.mgrid[:stride_width, :stride_height]
|
| 136 |
+
anchors = numpy.stack((y, x), axis = -1)
|
| 137 |
+
anchors = (anchors * feature_stride).reshape((-1, 2))
|
| 138 |
+
anchors = numpy.stack([ anchors ] * anchor_total, axis = 1).reshape((-1, 2))
|
| 139 |
+
return anchors
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def create_rotation_matrix_and_size(angle : Angle, size : Size) -> Tuple[Matrix, Size]:
|
| 143 |
+
rotation_matrix = cv2.getRotationMatrix2D((size[0] / 2, size[1] / 2), angle, 1)
|
| 144 |
+
rotation_size = numpy.dot(numpy.abs(rotation_matrix[:, :2]), size)
|
| 145 |
+
rotation_matrix[:, -1] += (rotation_size - size) * 0.5 #type:ignore[misc]
|
| 146 |
+
rotation_size = int(rotation_size[0]), int(rotation_size[1])
|
| 147 |
+
return rotation_matrix, rotation_size
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def create_bounding_box(face_landmark_68 : FaceLandmark68) -> BoundingBox:
|
| 151 |
+
x1, y1 = numpy.min(face_landmark_68, axis = 0)
|
| 152 |
+
x2, y2 = numpy.max(face_landmark_68, axis = 0)
|
| 153 |
+
bounding_box = normalize_bounding_box(numpy.array([ x1, y1, x2, y2 ]))
|
| 154 |
+
return bounding_box
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def normalize_bounding_box(bounding_box : BoundingBox) -> BoundingBox:
|
| 158 |
+
x1, y1, x2, y2 = bounding_box
|
| 159 |
+
x1, x2 = sorted([ x1, x2 ])
|
| 160 |
+
y1, y2 = sorted([ y1, y2 ])
|
| 161 |
+
return numpy.array([ x1, y1, x2, y2 ])
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def transform_points(points : Points, matrix : Matrix) -> Points:
|
| 165 |
+
points = points.reshape(-1, 1, 2)
|
| 166 |
+
points = cv2.transform(points, matrix) #type:ignore[assignment]
|
| 167 |
+
points = points.reshape(-1, 2)
|
| 168 |
+
return points
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def transform_bounding_box(bounding_box : BoundingBox, matrix : Matrix) -> BoundingBox:
|
| 172 |
+
points = numpy.array(
|
| 173 |
+
[
|
| 174 |
+
[ bounding_box[0], bounding_box[1] ],
|
| 175 |
+
[ bounding_box[2], bounding_box[1] ],
|
| 176 |
+
[ bounding_box[2], bounding_box[3] ],
|
| 177 |
+
[ bounding_box[0], bounding_box[3] ]
|
| 178 |
+
])
|
| 179 |
+
points = transform_points(points, matrix)
|
| 180 |
+
x1, y1 = numpy.min(points, axis = 0)
|
| 181 |
+
x2, y2 = numpy.max(points, axis = 0)
|
| 182 |
+
return normalize_bounding_box(numpy.array([ x1, y1, x2, y2 ]))
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def distance_to_bounding_box(points : Points, distance : Distance) -> BoundingBox:
|
| 186 |
+
x1 = points[:, 0] - distance[:, 0]
|
| 187 |
+
y1 = points[:, 1] - distance[:, 1]
|
| 188 |
+
x2 = points[:, 0] + distance[:, 2]
|
| 189 |
+
y2 = points[:, 1] + distance[:, 3]
|
| 190 |
+
bounding_box = numpy.column_stack([ x1, y1, x2, y2 ])
|
| 191 |
+
return bounding_box
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def distance_to_face_landmark_5(points : Points, distance : Distance) -> FaceLandmark5:
|
| 195 |
+
x = points[:, 0::2] + distance[:, 0::2]
|
| 196 |
+
y = points[:, 1::2] + distance[:, 1::2]
|
| 197 |
+
face_landmark_5 = numpy.stack((x, y), axis = -1)
|
| 198 |
+
return face_landmark_5
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def scale_face_landmark_5(face_landmark_5 : FaceLandmark5, scale : Scale) -> FaceLandmark5:
|
| 202 |
+
face_landmark_5_scale = face_landmark_5 - face_landmark_5[2]
|
| 203 |
+
face_landmark_5_scale *= scale
|
| 204 |
+
face_landmark_5_scale += face_landmark_5[2]
|
| 205 |
+
return face_landmark_5_scale
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def convert_to_face_landmark_5(face_landmark_68 : FaceLandmark68) -> FaceLandmark5:
|
| 209 |
+
face_landmark_5 = numpy.array(
|
| 210 |
+
[
|
| 211 |
+
numpy.mean(face_landmark_68[36:42], axis = 0),
|
| 212 |
+
numpy.mean(face_landmark_68[42:48], axis = 0),
|
| 213 |
+
face_landmark_68[30],
|
| 214 |
+
face_landmark_68[48],
|
| 215 |
+
face_landmark_68[54]
|
| 216 |
+
])
|
| 217 |
+
return face_landmark_5
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def estimate_face_angle(face_landmark_68 : FaceLandmark68) -> Angle:
|
| 221 |
+
x1, y1 = face_landmark_68[0]
|
| 222 |
+
x2, y2 = face_landmark_68[16]
|
| 223 |
+
theta = numpy.arctan2(y2 - y1, x2 - x1)
|
| 224 |
+
theta = numpy.degrees(theta) % 360
|
| 225 |
+
angles = numpy.linspace(0, 360, 5)
|
| 226 |
+
index = numpy.argmin(numpy.abs(angles - theta))
|
| 227 |
+
face_angle = int(angles[index] % 360)
|
| 228 |
+
return face_angle
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def apply_nms(bounding_boxes : List[BoundingBox], scores : List[Score], score_threshold : float, nms_threshold : float) -> Sequence[int]:
|
| 232 |
+
bounding_boxes_norm = [ (x1, y1, x2 - x1, y2 - y1) for (x1, y1, x2, y2) in bounding_boxes ]
|
| 233 |
+
keep_indices = cv2.dnn.NMSBoxes(bounding_boxes_norm, scores, score_threshold = score_threshold, nms_threshold = nms_threshold)
|
| 234 |
+
return keep_indices
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def get_nms_threshold(face_detector_model : FaceDetectorModel, face_detector_angles : List[Angle]) -> float:
|
| 238 |
+
if face_detector_model == 'many':
|
| 239 |
+
return 0.1
|
| 240 |
+
if len(face_detector_angles) == 2:
|
| 241 |
+
return 0.3
|
| 242 |
+
if len(face_detector_angles) == 3:
|
| 243 |
+
return 0.2
|
| 244 |
+
if len(face_detector_angles) == 4:
|
| 245 |
+
return 0.1
|
| 246 |
+
return 0.4
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def merge_matrix(temp_matrices : List[Matrix]) -> Matrix:
|
| 250 |
+
matrix = numpy.vstack([ temp_matrices[0], [ 0, 0, 1 ] ])
|
| 251 |
+
|
| 252 |
+
for temp_matrix in temp_matrices[1:]:
|
| 253 |
+
temp_matrix = numpy.vstack([ temp_matrix, [ 0, 0, 1 ] ])
|
| 254 |
+
matrix = numpy.dot(temp_matrix, matrix)
|
| 255 |
+
|
| 256 |
+
return matrix[:2, :]
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def calculate_bounding_box_overlap(bounding_box_a : BoundingBox, bounding_box_b : BoundingBox) -> float:
|
| 260 |
+
intersection_x1 = max(bounding_box_a[0], bounding_box_b[0])
|
| 261 |
+
intersection_y1 = max(bounding_box_a[1], bounding_box_b[1])
|
| 262 |
+
intersection_x2 = min(bounding_box_a[2], bounding_box_b[2])
|
| 263 |
+
intersection_y2 = min(bounding_box_a[3], bounding_box_b[3])
|
| 264 |
+
intersection = max(0, intersection_x2 - intersection_x1) * max(0, intersection_y2 - intersection_y1)
|
| 265 |
+
bounding_box_area = (bounding_box_a[2] - bounding_box_a[0]) * (bounding_box_a[3] - bounding_box_a[1])
|
| 266 |
+
reference_bounding_box_area = (bounding_box_b[2] - bounding_box_b[0]) * (bounding_box_b[3] - bounding_box_b[1])
|
| 267 |
+
union = bounding_box_area + reference_bounding_box_area - intersection
|
| 268 |
+
|
| 269 |
+
if union > 0:
|
| 270 |
+
return intersection / union
|
| 271 |
+
|
| 272 |
+
return 0.0
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def average_points(points_previous : Points, points_next : Points, average_factor : float) -> Points:
|
| 276 |
+
return points_previous * (1 - average_factor) + points_next * average_factor
|
face_landmarker.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
from typing import Tuple
|
| 3 |
+
|
| 4 |
+
import cv2
|
| 5 |
+
import numpy
|
| 6 |
+
|
| 7 |
+
from facefusion import inference_manager, state_manager
|
| 8 |
+
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
| 9 |
+
from facefusion.face_helper import create_rotation_matrix_and_size, estimate_matrix_by_face_landmark_5, transform_points, warp_face_by_translation
|
| 10 |
+
from facefusion.filesystem import resolve_relative_path
|
| 11 |
+
from facefusion.thread_helper import conditional_thread_semaphore
|
| 12 |
+
from facefusion.types import Angle, BoundingBox, DownloadScope, DownloadSet, FaceLandmark5, FaceLandmark68, InferencePool, ModelSet, Prediction, Score, VisionFrame
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@lru_cache()
|
| 16 |
+
def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
| 17 |
+
return\
|
| 18 |
+
{
|
| 19 |
+
'2dfan4':
|
| 20 |
+
{
|
| 21 |
+
'__metadata__':
|
| 22 |
+
{
|
| 23 |
+
'vendor': 'breadbread1984',
|
| 24 |
+
'license': 'MIT',
|
| 25 |
+
'year': 2018
|
| 26 |
+
},
|
| 27 |
+
'hashes':
|
| 28 |
+
{
|
| 29 |
+
'2dfan4':
|
| 30 |
+
{
|
| 31 |
+
'url': resolve_download_url('models-3.0.0', '2dfan4.hash'),
|
| 32 |
+
'path': resolve_relative_path('../.assets/models/2dfan4.hash')
|
| 33 |
+
}
|
| 34 |
+
},
|
| 35 |
+
'sources':
|
| 36 |
+
{
|
| 37 |
+
'2dfan4':
|
| 38 |
+
{
|
| 39 |
+
'url': resolve_download_url('models-3.0.0', '2dfan4.onnx'),
|
| 40 |
+
'path': resolve_relative_path('../.assets/models/2dfan4.onnx')
|
| 41 |
+
}
|
| 42 |
+
},
|
| 43 |
+
'size': (256, 256)
|
| 44 |
+
},
|
| 45 |
+
'peppa_wutz':
|
| 46 |
+
{
|
| 47 |
+
'__metadata__':
|
| 48 |
+
{
|
| 49 |
+
'vendor': 'Unknown',
|
| 50 |
+
'license': 'Apache-2.0',
|
| 51 |
+
'year': 2023
|
| 52 |
+
},
|
| 53 |
+
'hashes':
|
| 54 |
+
{
|
| 55 |
+
'peppa_wutz':
|
| 56 |
+
{
|
| 57 |
+
'url': resolve_download_url('models-3.0.0', 'peppa_wutz.hash'),
|
| 58 |
+
'path': resolve_relative_path('../.assets/models/peppa_wutz.hash')
|
| 59 |
+
}
|
| 60 |
+
},
|
| 61 |
+
'sources':
|
| 62 |
+
{
|
| 63 |
+
'peppa_wutz':
|
| 64 |
+
{
|
| 65 |
+
'url': resolve_download_url('models-3.0.0', 'peppa_wutz.onnx'),
|
| 66 |
+
'path': resolve_relative_path('../.assets/models/peppa_wutz.onnx')
|
| 67 |
+
}
|
| 68 |
+
},
|
| 69 |
+
'size': (256, 256)
|
| 70 |
+
},
|
| 71 |
+
'fan_68_5':
|
| 72 |
+
{
|
| 73 |
+
'__metadata__':
|
| 74 |
+
{
|
| 75 |
+
'vendor': 'FaceFusion',
|
| 76 |
+
'license': 'OpenRAIL-M',
|
| 77 |
+
'year': 2024
|
| 78 |
+
},
|
| 79 |
+
'hashes':
|
| 80 |
+
{
|
| 81 |
+
'fan_68_5':
|
| 82 |
+
{
|
| 83 |
+
'url': resolve_download_url('models-3.0.0', 'fan_68_5.hash'),
|
| 84 |
+
'path': resolve_relative_path('../.assets/models/fan_68_5.hash')
|
| 85 |
+
}
|
| 86 |
+
},
|
| 87 |
+
'sources':
|
| 88 |
+
{
|
| 89 |
+
'fan_68_5':
|
| 90 |
+
{
|
| 91 |
+
'url': resolve_download_url('models-3.0.0', 'fan_68_5.onnx'),
|
| 92 |
+
'path': resolve_relative_path('../.assets/models/fan_68_5.onnx')
|
| 93 |
+
}
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def get_inference_pool() -> InferencePool:
|
| 100 |
+
model_names = [ state_manager.get_item('face_landmarker_model'), 'fan_68_5' ]
|
| 101 |
+
_, model_source_set = collect_model_downloads()
|
| 102 |
+
|
| 103 |
+
return inference_manager.get_inference_pool(__name__, model_names, model_source_set)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def clear_inference_pool() -> None:
|
| 107 |
+
model_names = [ state_manager.get_item('face_landmarker_model'), 'fan_68_5' ]
|
| 108 |
+
inference_manager.clear_inference_pool(__name__, model_names)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def collect_model_downloads() -> Tuple[DownloadSet, DownloadSet]:
|
| 112 |
+
model_set = create_static_model_set('full')
|
| 113 |
+
model_hash_set =\
|
| 114 |
+
{
|
| 115 |
+
'fan_68_5': model_set.get('fan_68_5').get('hashes').get('fan_68_5')
|
| 116 |
+
}
|
| 117 |
+
model_source_set =\
|
| 118 |
+
{
|
| 119 |
+
'fan_68_5': model_set.get('fan_68_5').get('sources').get('fan_68_5')
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
for face_landmarker_model in [ '2dfan4', 'peppa_wutz' ]:
|
| 123 |
+
if state_manager.get_item('face_landmarker_model') in [ 'many', face_landmarker_model ]:
|
| 124 |
+
model_hash_set[face_landmarker_model] = model_set.get(face_landmarker_model).get('hashes').get(face_landmarker_model)
|
| 125 |
+
model_source_set[face_landmarker_model] = model_set.get(face_landmarker_model).get('sources').get(face_landmarker_model)
|
| 126 |
+
|
| 127 |
+
return model_hash_set, model_source_set
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def pre_check() -> bool:
|
| 131 |
+
model_hash_set, model_source_set = collect_model_downloads()
|
| 132 |
+
|
| 133 |
+
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def detect_face_landmark(vision_frame : VisionFrame, bounding_box : BoundingBox, face_angle : Angle) -> Tuple[FaceLandmark68, Score]:
|
| 137 |
+
face_landmark_2dfan4 = None
|
| 138 |
+
face_landmark_peppa_wutz = None
|
| 139 |
+
face_landmark_score_2dfan4 = 0.0
|
| 140 |
+
face_landmark_score_peppa_wutz = 0.0
|
| 141 |
+
|
| 142 |
+
if state_manager.get_item('face_landmarker_model') in [ 'many', '2dfan4' ]:
|
| 143 |
+
face_landmark_2dfan4, face_landmark_score_2dfan4 = detect_with_2dfan4(vision_frame, bounding_box, face_angle)
|
| 144 |
+
|
| 145 |
+
if state_manager.get_item('face_landmarker_model') in [ 'many', 'peppa_wutz' ]:
|
| 146 |
+
face_landmark_peppa_wutz, face_landmark_score_peppa_wutz = detect_with_peppa_wutz(vision_frame, bounding_box, face_angle)
|
| 147 |
+
|
| 148 |
+
if face_landmark_score_2dfan4 > face_landmark_score_peppa_wutz - 0.2:
|
| 149 |
+
return face_landmark_2dfan4, face_landmark_score_2dfan4
|
| 150 |
+
return face_landmark_peppa_wutz, face_landmark_score_peppa_wutz
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def detect_with_2dfan4(temp_vision_frame: VisionFrame, bounding_box: BoundingBox, face_angle: Angle) -> Tuple[FaceLandmark68, Score]:
|
| 154 |
+
model_size = create_static_model_set('full').get('2dfan4').get('size')
|
| 155 |
+
scale = 195 / numpy.subtract(bounding_box[2:], bounding_box[:2]).max().clip(1, None)
|
| 156 |
+
translation = (model_size[0] - numpy.add(bounding_box[2:], bounding_box[:2]) * scale) * 0.5
|
| 157 |
+
rotation_matrix, rotation_size = create_rotation_matrix_and_size(face_angle, model_size)
|
| 158 |
+
crop_vision_frame, affine_matrix = warp_face_by_translation(temp_vision_frame, translation, scale, model_size)
|
| 159 |
+
crop_vision_frame = cv2.warpAffine(crop_vision_frame, rotation_matrix, rotation_size)
|
| 160 |
+
crop_vision_frame = conditional_optimize_contrast(crop_vision_frame)
|
| 161 |
+
crop_vision_frame = crop_vision_frame.transpose(2, 0, 1).astype(numpy.float32) / 255.0
|
| 162 |
+
face_landmark_68, face_heatmap = forward_with_2dfan4(crop_vision_frame)
|
| 163 |
+
face_landmark_68 = face_landmark_68[:, :, :2][0] / 64 * 256
|
| 164 |
+
face_landmark_68 = transform_points(face_landmark_68, cv2.invertAffineTransform(rotation_matrix))
|
| 165 |
+
face_landmark_68 = transform_points(face_landmark_68, cv2.invertAffineTransform(affine_matrix))
|
| 166 |
+
face_landmark_score_68 = numpy.amax(face_heatmap, axis = (2, 3))
|
| 167 |
+
face_landmark_score_68 = numpy.mean(face_landmark_score_68)
|
| 168 |
+
face_landmark_score_68 = numpy.interp(face_landmark_score_68, [ 0, 0.9 ], [ 0, 1 ])
|
| 169 |
+
return face_landmark_68, face_landmark_score_68
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def detect_with_peppa_wutz(temp_vision_frame : VisionFrame, bounding_box : BoundingBox, face_angle : Angle) -> Tuple[FaceLandmark68, Score]:
|
| 173 |
+
model_size = create_static_model_set('full').get('peppa_wutz').get('size')
|
| 174 |
+
scale = 195 / numpy.subtract(bounding_box[2:], bounding_box[:2]).max().clip(1, None)
|
| 175 |
+
translation = (model_size[0] - numpy.add(bounding_box[2:], bounding_box[:2]) * scale) * 0.5
|
| 176 |
+
rotation_matrix, rotation_size = create_rotation_matrix_and_size(face_angle, model_size)
|
| 177 |
+
crop_vision_frame, affine_matrix = warp_face_by_translation(temp_vision_frame, translation, scale, model_size)
|
| 178 |
+
crop_vision_frame = cv2.warpAffine(crop_vision_frame, rotation_matrix, rotation_size)
|
| 179 |
+
crop_vision_frame = conditional_optimize_contrast(crop_vision_frame)
|
| 180 |
+
crop_vision_frame = crop_vision_frame.transpose(2, 0, 1).astype(numpy.float32) / 255.0
|
| 181 |
+
crop_vision_frame = numpy.expand_dims(crop_vision_frame, axis = 0)
|
| 182 |
+
prediction = forward_with_peppa_wutz(crop_vision_frame)
|
| 183 |
+
face_landmark_68 = prediction.reshape(-1, 3)[:, :2] / 64 * model_size[0]
|
| 184 |
+
face_landmark_68 = transform_points(face_landmark_68, cv2.invertAffineTransform(rotation_matrix))
|
| 185 |
+
face_landmark_68 = transform_points(face_landmark_68, cv2.invertAffineTransform(affine_matrix))
|
| 186 |
+
face_landmark_score_68 = prediction.reshape(-1, 3)[:, 2].mean()
|
| 187 |
+
face_landmark_score_68 = numpy.interp(face_landmark_score_68, [ 0, 0.95 ], [ 0, 1 ])
|
| 188 |
+
return face_landmark_68, face_landmark_score_68
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def conditional_optimize_contrast(crop_vision_frame : VisionFrame) -> VisionFrame:
|
| 192 |
+
crop_vision_frame = cv2.cvtColor(crop_vision_frame, cv2.COLOR_RGB2Lab)
|
| 193 |
+
if numpy.mean(crop_vision_frame[:, :, 0]) < 30: #type:ignore[arg-type]
|
| 194 |
+
crop_vision_frame[:, :, 0] = cv2.createCLAHE(clipLimit = 2).apply(crop_vision_frame[:, :, 0])
|
| 195 |
+
crop_vision_frame = cv2.cvtColor(crop_vision_frame, cv2.COLOR_Lab2RGB)
|
| 196 |
+
return crop_vision_frame
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def estimate_face_landmark_68_5(face_landmark_5 : FaceLandmark5) -> FaceLandmark68:
|
| 200 |
+
affine_matrix = estimate_matrix_by_face_landmark_5(face_landmark_5, 'ffhq_512', (1, 1))
|
| 201 |
+
face_landmark_5 = cv2.transform(face_landmark_5.reshape(1, -1, 2), affine_matrix).reshape(-1, 2)
|
| 202 |
+
face_landmark_68_5 = forward_fan_68_5(face_landmark_5)
|
| 203 |
+
face_landmark_68_5 = cv2.transform(face_landmark_68_5.reshape(1, -1, 2), cv2.invertAffineTransform(affine_matrix)).reshape(-1, 2)
|
| 204 |
+
return face_landmark_68_5
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def forward_with_2dfan4(crop_vision_frame : VisionFrame) -> Tuple[Prediction, Prediction]:
|
| 208 |
+
face_landmarker = get_inference_pool().get('2dfan4')
|
| 209 |
+
|
| 210 |
+
with conditional_thread_semaphore():
|
| 211 |
+
prediction = face_landmarker.run(None,
|
| 212 |
+
{
|
| 213 |
+
'input': [ crop_vision_frame ]
|
| 214 |
+
})
|
| 215 |
+
|
| 216 |
+
return prediction
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def forward_with_peppa_wutz(crop_vision_frame : VisionFrame) -> Prediction:
|
| 220 |
+
face_landmarker = get_inference_pool().get('peppa_wutz')
|
| 221 |
+
|
| 222 |
+
with conditional_thread_semaphore():
|
| 223 |
+
prediction = face_landmarker.run(None,
|
| 224 |
+
{
|
| 225 |
+
'input': crop_vision_frame
|
| 226 |
+
})[0]
|
| 227 |
+
|
| 228 |
+
return prediction
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def forward_fan_68_5(face_landmark_5 : FaceLandmark5) -> FaceLandmark68:
|
| 232 |
+
face_landmarker = get_inference_pool().get('fan_68_5')
|
| 233 |
+
|
| 234 |
+
with conditional_thread_semaphore():
|
| 235 |
+
face_landmark_68_5 = face_landmarker.run(None,
|
| 236 |
+
{
|
| 237 |
+
'input': [ face_landmark_5 ]
|
| 238 |
+
})[0][0]
|
| 239 |
+
|
| 240 |
+
return face_landmark_68_5
|
face_masker.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
from typing import List, Tuple
|
| 3 |
+
|
| 4 |
+
import cv2
|
| 5 |
+
import numpy
|
| 6 |
+
|
| 7 |
+
import facefusion.choices
|
| 8 |
+
from facefusion import inference_manager, state_manager
|
| 9 |
+
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
| 10 |
+
from facefusion.filesystem import resolve_relative_path
|
| 11 |
+
from facefusion.thread_helper import conditional_thread_semaphore
|
| 12 |
+
from facefusion.types import DownloadScope, DownloadSet, FaceLandmark68, FaceMaskArea, FaceMaskRegion, InferencePool, Mask, ModelSet, Padding, VisionFrame
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@lru_cache()
|
| 16 |
+
def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
| 17 |
+
return\
|
| 18 |
+
{
|
| 19 |
+
'xseg_1':
|
| 20 |
+
{
|
| 21 |
+
'__metadata__':
|
| 22 |
+
{
|
| 23 |
+
'vendor': 'DeepFaceLab',
|
| 24 |
+
'license': 'GPL-3.0',
|
| 25 |
+
'year': 2021
|
| 26 |
+
},
|
| 27 |
+
'hashes':
|
| 28 |
+
{
|
| 29 |
+
'face_occluder':
|
| 30 |
+
{
|
| 31 |
+
'url': resolve_download_url('models-3.1.0', 'xseg_1.hash'),
|
| 32 |
+
'path': resolve_relative_path('../.assets/models/xseg_1.hash')
|
| 33 |
+
}
|
| 34 |
+
},
|
| 35 |
+
'sources':
|
| 36 |
+
{
|
| 37 |
+
'face_occluder':
|
| 38 |
+
{
|
| 39 |
+
'url': resolve_download_url('models-3.1.0', 'xseg_1.onnx'),
|
| 40 |
+
'path': resolve_relative_path('../.assets/models/xseg_1.onnx')
|
| 41 |
+
}
|
| 42 |
+
},
|
| 43 |
+
'size': (256, 256)
|
| 44 |
+
},
|
| 45 |
+
'xseg_2':
|
| 46 |
+
{
|
| 47 |
+
'__metadata__':
|
| 48 |
+
{
|
| 49 |
+
'vendor': 'DeepFaceLab',
|
| 50 |
+
'license': 'GPL-3.0',
|
| 51 |
+
'year': 2021
|
| 52 |
+
},
|
| 53 |
+
'hashes':
|
| 54 |
+
{
|
| 55 |
+
'face_occluder':
|
| 56 |
+
{
|
| 57 |
+
'url': resolve_download_url('models-3.1.0', 'xseg_2.hash'),
|
| 58 |
+
'path': resolve_relative_path('../.assets/models/xseg_2.hash')
|
| 59 |
+
}
|
| 60 |
+
},
|
| 61 |
+
'sources':
|
| 62 |
+
{
|
| 63 |
+
'face_occluder':
|
| 64 |
+
{
|
| 65 |
+
'url': resolve_download_url('models-3.1.0', 'xseg_2.onnx'),
|
| 66 |
+
'path': resolve_relative_path('../.assets/models/xseg_2.onnx')
|
| 67 |
+
}
|
| 68 |
+
},
|
| 69 |
+
'size': (256, 256)
|
| 70 |
+
},
|
| 71 |
+
'xseg_3':
|
| 72 |
+
{
|
| 73 |
+
'__metadata__':
|
| 74 |
+
{
|
| 75 |
+
'vendor': 'DeepFaceLab',
|
| 76 |
+
'license': 'GPL-3.0',
|
| 77 |
+
'year': 2021
|
| 78 |
+
},
|
| 79 |
+
'hashes':
|
| 80 |
+
{
|
| 81 |
+
'face_occluder':
|
| 82 |
+
{
|
| 83 |
+
'url': resolve_download_url('models-3.2.0', 'xseg_3.hash'),
|
| 84 |
+
'path': resolve_relative_path('../.assets/models/xseg_3.hash')
|
| 85 |
+
}
|
| 86 |
+
},
|
| 87 |
+
'sources':
|
| 88 |
+
{
|
| 89 |
+
'face_occluder':
|
| 90 |
+
{
|
| 91 |
+
'url': resolve_download_url('models-3.2.0', 'xseg_3.onnx'),
|
| 92 |
+
'path': resolve_relative_path('../.assets/models/xseg_3.onnx')
|
| 93 |
+
}
|
| 94 |
+
},
|
| 95 |
+
'size': (256, 256)
|
| 96 |
+
},
|
| 97 |
+
'bisenet_resnet_18':
|
| 98 |
+
{
|
| 99 |
+
'__metadata__':
|
| 100 |
+
{
|
| 101 |
+
'vendor': 'yakhyo',
|
| 102 |
+
'license': 'MIT',
|
| 103 |
+
'year': 2024
|
| 104 |
+
},
|
| 105 |
+
'hashes':
|
| 106 |
+
{
|
| 107 |
+
'face_parser':
|
| 108 |
+
{
|
| 109 |
+
'url': resolve_download_url('models-3.1.0', 'bisenet_resnet_18.hash'),
|
| 110 |
+
'path': resolve_relative_path('../.assets/models/bisenet_resnet_18.hash')
|
| 111 |
+
}
|
| 112 |
+
},
|
| 113 |
+
'sources':
|
| 114 |
+
{
|
| 115 |
+
'face_parser':
|
| 116 |
+
{
|
| 117 |
+
'url': resolve_download_url('models-3.1.0', 'bisenet_resnet_18.onnx'),
|
| 118 |
+
'path': resolve_relative_path('../.assets/models/bisenet_resnet_18.onnx')
|
| 119 |
+
}
|
| 120 |
+
},
|
| 121 |
+
'size': (512, 512)
|
| 122 |
+
},
|
| 123 |
+
'bisenet_resnet_34':
|
| 124 |
+
{
|
| 125 |
+
'__metadata__':
|
| 126 |
+
{
|
| 127 |
+
'vendor': 'yakhyo',
|
| 128 |
+
'license': 'MIT',
|
| 129 |
+
'year': 2024
|
| 130 |
+
},
|
| 131 |
+
'hashes':
|
| 132 |
+
{
|
| 133 |
+
'face_parser':
|
| 134 |
+
{
|
| 135 |
+
'url': resolve_download_url('models-3.0.0', 'bisenet_resnet_34.hash'),
|
| 136 |
+
'path': resolve_relative_path('../.assets/models/bisenet_resnet_34.hash')
|
| 137 |
+
}
|
| 138 |
+
},
|
| 139 |
+
'sources':
|
| 140 |
+
{
|
| 141 |
+
'face_parser':
|
| 142 |
+
{
|
| 143 |
+
'url': resolve_download_url('models-3.0.0', 'bisenet_resnet_34.onnx'),
|
| 144 |
+
'path': resolve_relative_path('../.assets/models/bisenet_resnet_34.onnx')
|
| 145 |
+
}
|
| 146 |
+
},
|
| 147 |
+
'size': (512, 512)
|
| 148 |
+
}
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def get_inference_pool() -> InferencePool:
|
| 153 |
+
model_names = [ state_manager.get_item('face_occluder_model'), state_manager.get_item('face_parser_model') ]
|
| 154 |
+
_, model_source_set = collect_model_downloads()
|
| 155 |
+
|
| 156 |
+
return inference_manager.get_inference_pool(__name__, model_names, model_source_set)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def clear_inference_pool() -> None:
|
| 160 |
+
model_names = [ state_manager.get_item('face_occluder_model'), state_manager.get_item('face_parser_model') ]
|
| 161 |
+
inference_manager.clear_inference_pool(__name__, model_names)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def collect_model_downloads() -> Tuple[DownloadSet, DownloadSet]:
|
| 165 |
+
model_set = create_static_model_set('full')
|
| 166 |
+
model_hash_set = {}
|
| 167 |
+
model_source_set = {}
|
| 168 |
+
|
| 169 |
+
for face_occluder_model in [ 'xseg_1', 'xseg_2', 'xseg_3' ]:
|
| 170 |
+
if state_manager.get_item('face_occluder_model') in [ 'many', face_occluder_model ]:
|
| 171 |
+
model_hash_set[face_occluder_model] = model_set.get(face_occluder_model).get('hashes').get('face_occluder')
|
| 172 |
+
model_source_set[face_occluder_model] = model_set.get(face_occluder_model).get('sources').get('face_occluder')
|
| 173 |
+
|
| 174 |
+
for face_parser_model in [ 'bisenet_resnet_18', 'bisenet_resnet_34' ]:
|
| 175 |
+
if state_manager.get_item('face_parser_model') == face_parser_model:
|
| 176 |
+
model_hash_set[face_parser_model] = model_set.get(face_parser_model).get('hashes').get('face_parser')
|
| 177 |
+
model_source_set[face_parser_model] = model_set.get(face_parser_model).get('sources').get('face_parser')
|
| 178 |
+
|
| 179 |
+
return model_hash_set, model_source_set
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def pre_check() -> bool:
|
| 183 |
+
model_hash_set, model_source_set = collect_model_downloads()
|
| 184 |
+
|
| 185 |
+
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def create_box_mask(crop_vision_frame : VisionFrame, face_mask_blur : float, face_mask_padding : Padding) -> Mask:
|
| 189 |
+
crop_size = crop_vision_frame.shape[:2][::-1]
|
| 190 |
+
blur_amount = int(crop_size[0] * 0.5 * face_mask_blur)
|
| 191 |
+
blur_area = max(blur_amount // 2, 1)
|
| 192 |
+
box_mask : Mask = numpy.ones(crop_size).astype(numpy.float32)
|
| 193 |
+
box_mask[:max(blur_area, int(crop_size[1] * face_mask_padding[0] / 100)), :] = 0
|
| 194 |
+
box_mask[-max(blur_area, int(crop_size[1] * face_mask_padding[2] / 100)):, :] = 0
|
| 195 |
+
box_mask[:, :max(blur_area, int(crop_size[0] * face_mask_padding[3] / 100))] = 0
|
| 196 |
+
box_mask[:, -max(blur_area, int(crop_size[0] * face_mask_padding[1] / 100)):] = 0
|
| 197 |
+
|
| 198 |
+
if blur_amount > 0:
|
| 199 |
+
box_mask = cv2.GaussianBlur(box_mask, (0, 0), blur_amount * 0.25)
|
| 200 |
+
return box_mask
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def create_occlusion_mask(crop_vision_frame : VisionFrame) -> Mask:
|
| 204 |
+
temp_masks = []
|
| 205 |
+
|
| 206 |
+
if state_manager.get_item('face_occluder_model') == 'many':
|
| 207 |
+
model_names = [ 'xseg_1', 'xseg_2', 'xseg_3' ]
|
| 208 |
+
else:
|
| 209 |
+
model_names = [ state_manager.get_item('face_occluder_model') ]
|
| 210 |
+
|
| 211 |
+
for model_name in model_names:
|
| 212 |
+
model_size = create_static_model_set('full').get(model_name).get('size')
|
| 213 |
+
prepare_vision_frame = cv2.resize(crop_vision_frame, model_size)
|
| 214 |
+
prepare_vision_frame = numpy.expand_dims(prepare_vision_frame, axis = 0).astype(numpy.float32) / 255.0
|
| 215 |
+
prepare_vision_frame = prepare_vision_frame.transpose(0, 1, 2, 3)
|
| 216 |
+
temp_mask = forward_occlude_face(prepare_vision_frame, model_name)
|
| 217 |
+
temp_mask = temp_mask.transpose(0, 1, 2).clip(0, 1).astype(numpy.float32)
|
| 218 |
+
temp_mask = cv2.resize(temp_mask, crop_vision_frame.shape[:2][::-1])
|
| 219 |
+
temp_masks.append(temp_mask)
|
| 220 |
+
|
| 221 |
+
occlusion_mask = numpy.minimum.reduce(temp_masks)
|
| 222 |
+
occlusion_mask = (cv2.GaussianBlur(occlusion_mask.clip(0, 1), (0, 0), 5).clip(0.5, 1) - 0.5) * 2
|
| 223 |
+
return occlusion_mask
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def create_area_mask(crop_vision_frame : VisionFrame, face_landmark_68 : FaceLandmark68, face_mask_areas : List[FaceMaskArea]) -> Mask:
|
| 227 |
+
crop_size = crop_vision_frame.shape[:2][::-1]
|
| 228 |
+
landmark_points = []
|
| 229 |
+
|
| 230 |
+
for face_mask_area in face_mask_areas:
|
| 231 |
+
if face_mask_area in facefusion.choices.face_mask_area_set:
|
| 232 |
+
landmark_points.extend(facefusion.choices.face_mask_area_set.get(face_mask_area))
|
| 233 |
+
|
| 234 |
+
convex_hull = cv2.convexHull(face_landmark_68[landmark_points].astype(numpy.int32))
|
| 235 |
+
area_mask = numpy.zeros(crop_size).astype(numpy.float32)
|
| 236 |
+
cv2.fillConvexPoly(area_mask, convex_hull, 1.0) #type:ignore[call-overload]
|
| 237 |
+
area_mask = (cv2.GaussianBlur(area_mask.clip(0, 1), (0, 0), 5).clip(0.5, 1) - 0.5) * 2
|
| 238 |
+
return area_mask
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def create_region_mask(crop_vision_frame : VisionFrame, face_mask_regions : List[FaceMaskRegion]) -> Mask:
|
| 242 |
+
model_name = state_manager.get_item('face_parser_model')
|
| 243 |
+
model_size = create_static_model_set('full').get(model_name).get('size')
|
| 244 |
+
prepare_vision_frame = cv2.resize(crop_vision_frame, model_size)
|
| 245 |
+
prepare_vision_frame = prepare_vision_frame[:, :, ::-1].astype(numpy.float32) / 255.0
|
| 246 |
+
prepare_vision_frame = numpy.subtract(prepare_vision_frame, numpy.array([ 0.485, 0.456, 0.406 ]).astype(numpy.float32))
|
| 247 |
+
prepare_vision_frame = numpy.divide(prepare_vision_frame, numpy.array([ 0.229, 0.224, 0.225 ]).astype(numpy.float32))
|
| 248 |
+
prepare_vision_frame = numpy.expand_dims(prepare_vision_frame, axis = 0)
|
| 249 |
+
prepare_vision_frame = prepare_vision_frame.transpose(0, 3, 1, 2)
|
| 250 |
+
region_mask = forward_parse_face(prepare_vision_frame)
|
| 251 |
+
region_mask = numpy.isin(region_mask.argmax(0), [ facefusion.choices.face_mask_region_set.get(face_mask_region) for face_mask_region in face_mask_regions ])
|
| 252 |
+
region_mask = cv2.resize(region_mask.astype(numpy.float32), crop_vision_frame.shape[:2][::-1])
|
| 253 |
+
region_mask = (cv2.GaussianBlur(region_mask.clip(0, 1), (0, 0), 5).clip(0.5, 1) - 0.5) * 2
|
| 254 |
+
return region_mask
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def forward_occlude_face(prepare_vision_frame : VisionFrame, model_name : str) -> Mask:
|
| 258 |
+
face_occluder = get_inference_pool().get(model_name)
|
| 259 |
+
|
| 260 |
+
with conditional_thread_semaphore():
|
| 261 |
+
occlusion_mask : Mask = face_occluder.run(None,
|
| 262 |
+
{
|
| 263 |
+
'input': prepare_vision_frame
|
| 264 |
+
})[0][0]
|
| 265 |
+
|
| 266 |
+
return occlusion_mask
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def forward_parse_face(prepare_vision_frame : VisionFrame) -> Mask:
|
| 270 |
+
model_name = state_manager.get_item('face_parser_model')
|
| 271 |
+
face_parser = get_inference_pool().get(model_name)
|
| 272 |
+
|
| 273 |
+
with conditional_thread_semaphore():
|
| 274 |
+
region_mask : Mask = face_parser.run(None,
|
| 275 |
+
{
|
| 276 |
+
'input': prepare_vision_frame
|
| 277 |
+
})[0][0]
|
| 278 |
+
|
| 279 |
+
return region_mask
|
face_recognizer.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
from typing import Tuple
|
| 3 |
+
|
| 4 |
+
import numpy
|
| 5 |
+
|
| 6 |
+
from facefusion import inference_manager
|
| 7 |
+
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
| 8 |
+
from facefusion.face_helper import warp_face_by_face_landmark_5
|
| 9 |
+
from facefusion.filesystem import resolve_relative_path
|
| 10 |
+
from facefusion.thread_helper import conditional_thread_semaphore
|
| 11 |
+
from facefusion.types import DownloadScope, Embedding, FaceLandmark5, InferencePool, ModelOptions, ModelSet, VisionFrame
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@lru_cache()
|
| 15 |
+
def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
| 16 |
+
return\
|
| 17 |
+
{
|
| 18 |
+
'arcface':
|
| 19 |
+
{
|
| 20 |
+
'__metadata__':
|
| 21 |
+
{
|
| 22 |
+
'vendor': 'InsightFace',
|
| 23 |
+
'license': 'Non-Commercial',
|
| 24 |
+
'year': 2018
|
| 25 |
+
},
|
| 26 |
+
'hashes':
|
| 27 |
+
{
|
| 28 |
+
'face_recognizer':
|
| 29 |
+
{
|
| 30 |
+
'url': resolve_download_url('models-3.0.0', 'arcface_w600k_r50.hash'),
|
| 31 |
+
'path': resolve_relative_path('../.assets/models/arcface_w600k_r50.hash')
|
| 32 |
+
}
|
| 33 |
+
},
|
| 34 |
+
'sources':
|
| 35 |
+
{
|
| 36 |
+
'face_recognizer':
|
| 37 |
+
{
|
| 38 |
+
'url': resolve_download_url('models-3.0.0', 'arcface_w600k_r50.onnx'),
|
| 39 |
+
'path': resolve_relative_path('../.assets/models/arcface_w600k_r50.onnx')
|
| 40 |
+
}
|
| 41 |
+
},
|
| 42 |
+
'template': 'arcface_112_v2',
|
| 43 |
+
'size': (112, 112)
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def get_inference_pool() -> InferencePool:
|
| 49 |
+
model_names = [ 'arcface' ]
|
| 50 |
+
model_source_set = get_model_options().get('sources')
|
| 51 |
+
|
| 52 |
+
return inference_manager.get_inference_pool(__name__, model_names, model_source_set)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def clear_inference_pool() -> None:
|
| 56 |
+
model_names = [ 'arcface' ]
|
| 57 |
+
inference_manager.clear_inference_pool(__name__, model_names)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def get_model_options() -> ModelOptions:
|
| 61 |
+
return create_static_model_set('full').get('arcface')
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def pre_check() -> bool:
|
| 65 |
+
model_hash_set = get_model_options().get('hashes')
|
| 66 |
+
model_source_set = get_model_options().get('sources')
|
| 67 |
+
|
| 68 |
+
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def calculate_face_embedding(temp_vision_frame : VisionFrame, face_landmark_5 : FaceLandmark5) -> Tuple[Embedding, Embedding]:
|
| 72 |
+
model_template = get_model_options().get('template')
|
| 73 |
+
model_size = get_model_options().get('size')
|
| 74 |
+
crop_vision_frame, matrix = warp_face_by_face_landmark_5(temp_vision_frame, face_landmark_5, model_template, model_size)
|
| 75 |
+
crop_vision_frame = crop_vision_frame / 127.5 - 1
|
| 76 |
+
crop_vision_frame = crop_vision_frame[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32)
|
| 77 |
+
crop_vision_frame = numpy.expand_dims(crop_vision_frame, axis = 0)
|
| 78 |
+
face_embedding = forward(crop_vision_frame)
|
| 79 |
+
face_embedding = face_embedding.ravel()
|
| 80 |
+
face_embedding_norm = face_embedding / numpy.linalg.norm(face_embedding)
|
| 81 |
+
return face_embedding, face_embedding_norm
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def forward(crop_vision_frame : VisionFrame) -> Embedding:
|
| 85 |
+
face_recognizer = get_inference_pool().get('face_recognizer')
|
| 86 |
+
|
| 87 |
+
with conditional_thread_semaphore():
|
| 88 |
+
face_embedding = face_recognizer.run(None,
|
| 89 |
+
{
|
| 90 |
+
'input': crop_vision_frame
|
| 91 |
+
})[0]
|
| 92 |
+
|
| 93 |
+
return face_embedding
|
face_selector.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List
|
| 2 |
+
|
| 3 |
+
import numpy
|
| 4 |
+
|
| 5 |
+
import facefusion.choices
|
| 6 |
+
from facefusion import state_manager
|
| 7 |
+
from facefusion.common_helper import get_first, get_middle
|
| 8 |
+
from facefusion.face_creator import get_one_face, get_static_faces
|
| 9 |
+
from facefusion.face_tracker import track_faces
|
| 10 |
+
from facefusion.types import Face, FaceSelectorOrder, Gender, Race, Score, VisionFrame
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def select_faces(reference_vision_frame : VisionFrame, source_vision_frames : List[VisionFrame], target_vision_frames : List[VisionFrame]) -> List[Face]:
|
| 14 |
+
source_faces = get_static_faces(source_vision_frames)
|
| 15 |
+
|
| 16 |
+
if state_manager.get_item('face_tracker_score') > 0:
|
| 17 |
+
target_faces = track_faces(target_vision_frames, state_manager.get_item('face_tracker_score'))
|
| 18 |
+
else:
|
| 19 |
+
target_faces = get_static_faces([ get_middle(target_vision_frames) ])
|
| 20 |
+
|
| 21 |
+
if state_manager.get_item('face_selector_mode') == 'many':
|
| 22 |
+
return sort_and_filter_faces(source_faces, target_faces)
|
| 23 |
+
|
| 24 |
+
if state_manager.get_item('face_selector_mode') == 'one':
|
| 25 |
+
target_face = get_one_face(sort_and_filter_faces(source_faces, target_faces))
|
| 26 |
+
if target_face:
|
| 27 |
+
return [ target_face ]
|
| 28 |
+
|
| 29 |
+
if state_manager.get_item('face_selector_mode') == 'reference':
|
| 30 |
+
reference_faces = get_static_faces([ reference_vision_frame ])
|
| 31 |
+
reference_faces = sort_and_filter_faces(source_faces, reference_faces)
|
| 32 |
+
reference_face = get_one_face(reference_faces, state_manager.get_item('reference_face_position'))
|
| 33 |
+
|
| 34 |
+
if reference_face:
|
| 35 |
+
match_faces = find_match_faces([ reference_face ], target_faces, state_manager.get_item('reference_face_distance'))
|
| 36 |
+
return match_faces
|
| 37 |
+
|
| 38 |
+
return []
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def find_match_faces(reference_faces : List[Face], target_faces : List[Face], face_distance : float) -> List[Face]:
|
| 42 |
+
match_faces : List[Face] = []
|
| 43 |
+
|
| 44 |
+
for reference_face in reference_faces:
|
| 45 |
+
if reference_face:
|
| 46 |
+
for index, target_face in enumerate(target_faces):
|
| 47 |
+
if compare_faces(target_face, reference_face, face_distance):
|
| 48 |
+
match_faces.append(target_faces[index])
|
| 49 |
+
|
| 50 |
+
return match_faces
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def compare_faces(face : Face, reference_face : Face, face_distance : float) -> bool:
|
| 54 |
+
current_face_distance = calculate_face_distance(face, reference_face)
|
| 55 |
+
current_face_distance = float(numpy.interp(current_face_distance, [ 0, 2 ], [ 0, 1 ]))
|
| 56 |
+
return current_face_distance < face_distance
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def calculate_face_distance(face : Face, reference_face : Face) -> float:
|
| 60 |
+
if hasattr(face, 'embedding_norm') and hasattr(reference_face, 'embedding_norm'):
|
| 61 |
+
return 1 - numpy.dot(face.embedding_norm, reference_face.embedding_norm)
|
| 62 |
+
return 0
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def sort_and_filter_faces(source_faces : List[Face], target_faces : List[Face]) -> List[Face]:
|
| 66 |
+
if target_faces:
|
| 67 |
+
if state_manager.get_item('face_selector_order'):
|
| 68 |
+
target_faces = sort_faces_by_order(target_faces, state_manager.get_item('face_selector_order'))
|
| 69 |
+
|
| 70 |
+
face_selector_gender = state_manager.get_item('face_selector_gender')
|
| 71 |
+
face_selector_race = state_manager.get_item('face_selector_race')
|
| 72 |
+
|
| 73 |
+
if source_faces and face_selector_gender == 'auto' or face_selector_race == 'auto':
|
| 74 |
+
source_face = get_first(sort_faces_by_order(source_faces, 'large-small'))
|
| 75 |
+
|
| 76 |
+
if source_face:
|
| 77 |
+
if face_selector_gender == 'auto':
|
| 78 |
+
face_selector_gender = source_face.gender
|
| 79 |
+
if face_selector_race == 'auto':
|
| 80 |
+
face_selector_race = source_face.race
|
| 81 |
+
|
| 82 |
+
if face_selector_gender in facefusion.choices.genders:
|
| 83 |
+
target_faces = filter_faces_by_gender(target_faces, face_selector_gender)
|
| 84 |
+
|
| 85 |
+
if face_selector_race in facefusion.choices.races:
|
| 86 |
+
target_faces = filter_faces_by_race(target_faces, face_selector_race)
|
| 87 |
+
|
| 88 |
+
if state_manager.get_item('face_selector_age_start') or state_manager.get_item('face_selector_age_end'):
|
| 89 |
+
target_faces = filter_faces_by_age(target_faces, state_manager.get_item('face_selector_age_start'), state_manager.get_item('face_selector_age_end'))
|
| 90 |
+
|
| 91 |
+
return target_faces
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def sort_faces_by_order(faces : List[Face], order : FaceSelectorOrder) -> List[Face]:
|
| 95 |
+
if order == 'left-right':
|
| 96 |
+
return sorted(faces, key = get_bounding_box_left)
|
| 97 |
+
if order == 'right-left':
|
| 98 |
+
return sorted(faces, key = get_bounding_box_left, reverse = True)
|
| 99 |
+
if order == 'top-bottom':
|
| 100 |
+
return sorted(faces, key = get_bounding_box_top)
|
| 101 |
+
if order == 'bottom-top':
|
| 102 |
+
return sorted(faces, key = get_bounding_box_top, reverse = True)
|
| 103 |
+
if order == 'small-large':
|
| 104 |
+
return sorted(faces, key = get_bounding_box_area)
|
| 105 |
+
if order == 'large-small':
|
| 106 |
+
return sorted(faces, key = get_bounding_box_area, reverse = True)
|
| 107 |
+
if order == 'best-worst':
|
| 108 |
+
return sorted(faces, key = get_face_detector_score, reverse = True)
|
| 109 |
+
if order == 'worst-best':
|
| 110 |
+
return sorted(faces, key = get_face_detector_score)
|
| 111 |
+
return faces
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def get_bounding_box_left(face : Face) -> float:
|
| 115 |
+
return face.bounding_box[0]
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def get_bounding_box_top(face : Face) -> float:
|
| 119 |
+
return face.bounding_box[1]
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def get_bounding_box_area(face : Face) -> float:
|
| 123 |
+
return (face.bounding_box[2] - face.bounding_box[0]) * (face.bounding_box[3] - face.bounding_box[1])
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def get_face_detector_score(face : Face) -> Score:
|
| 127 |
+
return face.score_set.get('detector')
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def filter_faces_by_gender(faces : List[Face], gender : Gender) -> List[Face]:
|
| 131 |
+
filter_faces = []
|
| 132 |
+
|
| 133 |
+
for face in faces:
|
| 134 |
+
if face.gender == gender:
|
| 135 |
+
filter_faces.append(face)
|
| 136 |
+
return filter_faces
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def filter_faces_by_age(faces : List[Face], face_selector_age_start : int, face_selector_age_end : int) -> List[Face]:
|
| 140 |
+
filter_faces = []
|
| 141 |
+
age = range(face_selector_age_start, face_selector_age_end)
|
| 142 |
+
|
| 143 |
+
for face in faces:
|
| 144 |
+
if set(face.age) & set(age):
|
| 145 |
+
filter_faces.append(face)
|
| 146 |
+
return filter_faces
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def filter_faces_by_race(faces : List[Face], race : Race) -> List[Face]:
|
| 150 |
+
filter_faces = []
|
| 151 |
+
|
| 152 |
+
for face in faces:
|
| 153 |
+
if face.race == race:
|
| 154 |
+
filter_faces.append(face)
|
| 155 |
+
return filter_faces
|
face_store.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import threading
|
| 2 |
+
from typing import List, Optional
|
| 3 |
+
|
| 4 |
+
from facefusion.hash_helper import create_hash
|
| 5 |
+
from facefusion.types import Face, FaceStore, VisionFrame
|
| 6 |
+
from facefusion.vision import is_vision_frame
|
| 7 |
+
|
| 8 |
+
FACE_STORE : FaceStore = {}
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def get_faces(vision_frame : VisionFrame) -> Optional[List[Face]]:
|
| 12 |
+
if is_vision_frame(vision_frame):
|
| 13 |
+
vision_hash = create_hash(vision_frame.tobytes())
|
| 14 |
+
|
| 15 |
+
if FACE_STORE.get(vision_hash):
|
| 16 |
+
return FACE_STORE.get(vision_hash).get('faces')
|
| 17 |
+
|
| 18 |
+
return None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def set_faces(vision_frame : VisionFrame, faces : List[Face]) -> None:
|
| 22 |
+
if is_vision_frame(vision_frame):
|
| 23 |
+
vision_hash = create_hash(vision_frame.tobytes())
|
| 24 |
+
FACE_STORE.setdefault(vision_hash,
|
| 25 |
+
{
|
| 26 |
+
'lock': threading.Lock()
|
| 27 |
+
})['faces'] = faces
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def resolve_lock(vision_frame : VisionFrame) -> threading.Lock:
|
| 31 |
+
if is_vision_frame(vision_frame):
|
| 32 |
+
vision_hash = create_hash(vision_frame.tobytes())
|
| 33 |
+
return FACE_STORE.setdefault(vision_hash,
|
| 34 |
+
{
|
| 35 |
+
'lock': threading.Lock()
|
| 36 |
+
}).get('lock')
|
| 37 |
+
return threading.Lock()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def clear_faces() -> None:
|
| 41 |
+
FACE_STORE.clear()
|
face_tracker.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List
|
| 2 |
+
|
| 3 |
+
from facefusion.common_helper import get_first, get_last
|
| 4 |
+
from facefusion.face_creator import get_static_faces, refill_faces
|
| 5 |
+
from facefusion.face_helper import calculate_bounding_box_overlap
|
| 6 |
+
from facefusion.types import Face, FaceTrack, Score, VisionFrame
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def track_faces(vision_frames : List[VisionFrame], score : Score) -> List[Face]:
|
| 10 |
+
target_index = len(vision_frames) // 2
|
| 11 |
+
face_tracks = create_face_tracks(vision_frames, score)
|
| 12 |
+
temp_faces = []
|
| 13 |
+
|
| 14 |
+
for face_track in face_tracks:
|
| 15 |
+
track_indices = sorted(face_track)
|
| 16 |
+
track_index_first = get_first(track_indices)
|
| 17 |
+
track_index_last = get_last(track_indices)
|
| 18 |
+
track_range = range(track_index_first, track_index_last + 1)
|
| 19 |
+
|
| 20 |
+
if target_index in track_range:
|
| 21 |
+
fill_faces = []
|
| 22 |
+
|
| 23 |
+
for index in track_range:
|
| 24 |
+
fill_faces.append(face_track.get(index))
|
| 25 |
+
|
| 26 |
+
temp_faces.append(refill_faces(fill_faces)[target_index - track_index_first])
|
| 27 |
+
|
| 28 |
+
return temp_faces
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def create_face_tracks(vision_frames : List[VisionFrame], score : Score) -> List[FaceTrack]:
|
| 32 |
+
face_tracks : List[FaceTrack] = []
|
| 33 |
+
|
| 34 |
+
for frame_index, vision_frame in enumerate(vision_frames):
|
| 35 |
+
for face in get_static_faces([ vision_frame ]):
|
| 36 |
+
face_track = select_face_track(face_tracks, face, score)
|
| 37 |
+
|
| 38 |
+
if face_track:
|
| 39 |
+
face_track[frame_index] = face
|
| 40 |
+
else:
|
| 41 |
+
face_tracks.append(
|
| 42 |
+
{
|
| 43 |
+
frame_index : face
|
| 44 |
+
})
|
| 45 |
+
|
| 46 |
+
return face_tracks
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def select_face_track(face_tracks : List[FaceTrack], face : Face, score : Score) -> FaceTrack:
|
| 50 |
+
select_track : FaceTrack = {}
|
| 51 |
+
select_score = score
|
| 52 |
+
|
| 53 |
+
for face_track in face_tracks:
|
| 54 |
+
track_face = face_track.get(get_last(face_track))
|
| 55 |
+
track_score = calculate_bounding_box_overlap(face.bounding_box, track_face.bounding_box)
|
| 56 |
+
|
| 57 |
+
if track_score > select_score:
|
| 58 |
+
select_score = track_score
|
| 59 |
+
select_track = face_track
|
| 60 |
+
|
| 61 |
+
return select_track
|
ffmpeg.py
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import subprocess
|
| 3 |
+
import tempfile
|
| 4 |
+
from functools import partial
|
| 5 |
+
from typing import List, Optional, cast
|
| 6 |
+
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
|
| 9 |
+
import facefusion.choices
|
| 10 |
+
from facefusion import ffmpeg_builder, ffprobe, logger, process_manager, state_manager, translator, vision
|
| 11 |
+
from facefusion.filesystem import get_file_format, remove_file
|
| 12 |
+
from facefusion.temp_helper import get_temp_file_path, get_temp_frame_pattern
|
| 13 |
+
from facefusion.types import AudioBuffer, AudioEncoder, Command, EncoderSet, Fps, Resolution, UpdateProgress, VideoEncoder, VideoFormat, VideoReaderMetadata
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def run_ffmpeg_with_progress(commands : List[Command], update_progress : UpdateProgress) -> subprocess.Popen[bytes]:
|
| 17 |
+
log_level = state_manager.get_item('log_level')
|
| 18 |
+
commands.extend(ffmpeg_builder.set_progress())
|
| 19 |
+
commands.extend(ffmpeg_builder.cast_stream())
|
| 20 |
+
commands = ffmpeg_builder.run(commands)
|
| 21 |
+
process = subprocess.Popen(commands, stderr = subprocess.PIPE, stdout = subprocess.PIPE)
|
| 22 |
+
|
| 23 |
+
while process_manager.is_processing():
|
| 24 |
+
try:
|
| 25 |
+
while __line__ := process.stdout.readline().decode().lower():
|
| 26 |
+
if process_manager.is_stopping():
|
| 27 |
+
process.terminate()
|
| 28 |
+
|
| 29 |
+
if 'frame=' in __line__:
|
| 30 |
+
_, frame_number = __line__.split('frame=')
|
| 31 |
+
update_progress(int(frame_number))
|
| 32 |
+
|
| 33 |
+
if log_level == 'debug':
|
| 34 |
+
log_debug(process)
|
| 35 |
+
process.wait(timeout = 0.5)
|
| 36 |
+
except subprocess.TimeoutExpired:
|
| 37 |
+
continue
|
| 38 |
+
return process
|
| 39 |
+
|
| 40 |
+
return process
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def update_progress(progress : tqdm, frame_number : int) -> None:
|
| 44 |
+
progress.update(frame_number - progress.n)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def run_ffmpeg(commands : List[Command]) -> subprocess.Popen[bytes]:
|
| 48 |
+
log_level = state_manager.get_item('log_level')
|
| 49 |
+
commands = ffmpeg_builder.run(commands)
|
| 50 |
+
process = subprocess.Popen(commands, stderr = subprocess.PIPE, stdout = subprocess.PIPE)
|
| 51 |
+
|
| 52 |
+
while process_manager.is_processing():
|
| 53 |
+
try:
|
| 54 |
+
if log_level == 'debug':
|
| 55 |
+
log_debug(process)
|
| 56 |
+
process.wait(timeout = 0.5)
|
| 57 |
+
except subprocess.TimeoutExpired:
|
| 58 |
+
continue
|
| 59 |
+
return process
|
| 60 |
+
|
| 61 |
+
if process_manager.is_stopping():
|
| 62 |
+
process.terminate()
|
| 63 |
+
|
| 64 |
+
return process
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def open_ffmpeg(commands : List[Command]) -> subprocess.Popen[bytes]:
|
| 68 |
+
commands = ffmpeg_builder.run(commands)
|
| 69 |
+
return subprocess.Popen(commands, stdin = subprocess.PIPE, stderr = subprocess.DEVNULL, stdout = subprocess.PIPE)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def create_video_reader(video_path : str, frame_number : int, video_metadata : VideoReaderMetadata) -> subprocess.Popen[bytes]:
|
| 73 |
+
commands = ffmpeg_builder.chain(
|
| 74 |
+
ffmpeg_builder.seek_to(frame_number / video_metadata.get('fps')),
|
| 75 |
+
ffmpeg_builder.set_input(video_path),
|
| 76 |
+
ffmpeg_builder.restrict_color_transfer(video_metadata.get('color_transfer')),
|
| 77 |
+
ffmpeg_builder.prevent_frame_drop(),
|
| 78 |
+
ffmpeg_builder.enforce_pixel_format('bgr24'),
|
| 79 |
+
ffmpeg_builder.set_output_format('rawvideo'),
|
| 80 |
+
ffmpeg_builder.cast_stream()
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
return open_ffmpeg(commands)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def create_video_writer(target_path : str, temp_video_fps : Fps, temp_video_resolution : Resolution, output_video_resolution : Resolution, output_video_fps : Fps) -> subprocess.Popen[bytes]:
|
| 87 |
+
output_video_encoder = state_manager.get_item('output_video_encoder')
|
| 88 |
+
output_video_quality = state_manager.get_item('output_video_quality')
|
| 89 |
+
output_video_preset = state_manager.get_item('output_video_preset')
|
| 90 |
+
temp_video_path = get_temp_file_path(target_path)
|
| 91 |
+
temp_video_format = cast(VideoFormat, get_file_format(temp_video_path))
|
| 92 |
+
output_video_encoder = fix_video_encoder(temp_video_format, output_video_encoder)
|
| 93 |
+
|
| 94 |
+
commands = ffmpeg_builder.chain(
|
| 95 |
+
ffmpeg_builder.set_output_format('rawvideo'),
|
| 96 |
+
ffmpeg_builder.enforce_pixel_format(state_manager.get_item('temp_pixel_format')),
|
| 97 |
+
ffmpeg_builder.set_media_resolution(vision.pack_resolution(temp_video_resolution)),
|
| 98 |
+
ffmpeg_builder.set_input_fps(temp_video_fps),
|
| 99 |
+
ffmpeg_builder.set_input('pipe:0'),
|
| 100 |
+
ffmpeg_builder.set_media_resolution(vision.pack_resolution(output_video_resolution)),
|
| 101 |
+
ffmpeg_builder.set_video_encoder(output_video_encoder),
|
| 102 |
+
ffmpeg_builder.set_thread_count(16),
|
| 103 |
+
ffmpeg_builder.set_video_tag(output_video_encoder, temp_video_format),
|
| 104 |
+
ffmpeg_builder.set_video_quality(output_video_encoder, output_video_quality),
|
| 105 |
+
ffmpeg_builder.set_video_preset(output_video_encoder, output_video_preset),
|
| 106 |
+
ffmpeg_builder.concat(
|
| 107 |
+
ffmpeg_builder.set_video_fps(output_video_fps),
|
| 108 |
+
ffmpeg_builder.convert_color_space('bt709')
|
| 109 |
+
),
|
| 110 |
+
ffmpeg_builder.set_pixel_format(output_video_encoder),
|
| 111 |
+
ffmpeg_builder.force_output(temp_video_path)
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
return open_ffmpeg(commands)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def log_debug(process : subprocess.Popen[bytes]) -> None:
|
| 118 |
+
_, stderr = process.communicate()
|
| 119 |
+
errors = stderr.decode().split(os.linesep)
|
| 120 |
+
|
| 121 |
+
for error in errors:
|
| 122 |
+
if error.strip():
|
| 123 |
+
logger.debug(error.strip(), __name__)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def get_available_encoder_set() -> EncoderSet:
|
| 127 |
+
available_encoder_set : EncoderSet =\
|
| 128 |
+
{
|
| 129 |
+
'audio': [],
|
| 130 |
+
'video': []
|
| 131 |
+
}
|
| 132 |
+
commands = ffmpeg_builder.chain(
|
| 133 |
+
ffmpeg_builder.get_encoders()
|
| 134 |
+
)
|
| 135 |
+
process = run_ffmpeg(commands)
|
| 136 |
+
|
| 137 |
+
while line := process.stdout.readline().decode().lower():
|
| 138 |
+
if line.startswith(' a'):
|
| 139 |
+
audio_encoder = line.split()[1]
|
| 140 |
+
|
| 141 |
+
if audio_encoder in facefusion.choices.output_audio_encoders:
|
| 142 |
+
index = facefusion.choices.output_audio_encoders.index(audio_encoder) #type:ignore[arg-type]
|
| 143 |
+
available_encoder_set['audio'].insert(index, audio_encoder) #type:ignore[arg-type]
|
| 144 |
+
if line.startswith(' v'):
|
| 145 |
+
video_encoder = line.split()[1]
|
| 146 |
+
|
| 147 |
+
if video_encoder in facefusion.choices.output_video_encoders:
|
| 148 |
+
index = facefusion.choices.output_video_encoders.index(video_encoder) #type:ignore[arg-type]
|
| 149 |
+
available_encoder_set['video'].insert(index, video_encoder) #type:ignore[arg-type]
|
| 150 |
+
|
| 151 |
+
return available_encoder_set
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def extract_frames(target_path : str, temp_video_resolution : Resolution, temp_video_fps : Fps, trim_frame_start : int, trim_frame_end : int) -> bool:
|
| 155 |
+
color_transfer = ffprobe.extract_static_video_metadata(target_path).get('color_transfer')
|
| 156 |
+
extract_frame_total = vision.predict_video_frame_total(target_path, temp_video_fps, trim_frame_start, trim_frame_end)
|
| 157 |
+
temp_frame_pattern = get_temp_frame_pattern(target_path, '%08d')
|
| 158 |
+
|
| 159 |
+
commands = ffmpeg_builder.chain(
|
| 160 |
+
ffmpeg_builder.set_input(target_path),
|
| 161 |
+
ffmpeg_builder.set_media_resolution(vision.pack_resolution(temp_video_resolution)),
|
| 162 |
+
ffmpeg_builder.set_frame_quality(0),
|
| 163 |
+
ffmpeg_builder.enforce_pixel_format('rgb24'),
|
| 164 |
+
ffmpeg_builder.concat(
|
| 165 |
+
ffmpeg_builder.select_frame_range(trim_frame_start, trim_frame_end, temp_video_fps),
|
| 166 |
+
ffmpeg_builder.restrict_color_transfer(color_transfer)
|
| 167 |
+
),
|
| 168 |
+
ffmpeg_builder.prevent_frame_drop(),
|
| 169 |
+
ffmpeg_builder.set_start_number(trim_frame_start),
|
| 170 |
+
ffmpeg_builder.set_output(temp_frame_pattern)
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
with tqdm(total = extract_frame_total, desc = translator.get('extracting'), unit = 'frame', ascii = ' =', disable = state_manager.get_item('log_level') in [ 'warn', 'error' ]) as progress:
|
| 174 |
+
process = run_ffmpeg_with_progress(commands, partial(update_progress, progress))
|
| 175 |
+
return process.returncode == 0
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def copy_image(target_path : str, temp_image_resolution : Resolution) -> bool:
|
| 179 |
+
temp_image_path = get_temp_file_path(target_path)
|
| 180 |
+
|
| 181 |
+
commands = ffmpeg_builder.chain(
|
| 182 |
+
ffmpeg_builder.set_input(target_path),
|
| 183 |
+
ffmpeg_builder.set_media_resolution(vision.pack_resolution(temp_image_resolution)),
|
| 184 |
+
ffmpeg_builder.set_image_quality(target_path, 100),
|
| 185 |
+
ffmpeg_builder.force_output(temp_image_path)
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
return run_ffmpeg(commands).returncode == 0
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def finalize_image(target_path : str, output_path : str, output_image_resolution : Resolution) -> bool:
|
| 192 |
+
output_image_quality = state_manager.get_item('output_image_quality')
|
| 193 |
+
temp_image_path = get_temp_file_path(target_path)
|
| 194 |
+
|
| 195 |
+
commands = ffmpeg_builder.chain(
|
| 196 |
+
ffmpeg_builder.set_input(temp_image_path),
|
| 197 |
+
ffmpeg_builder.set_media_resolution(vision.pack_resolution(output_image_resolution)),
|
| 198 |
+
ffmpeg_builder.set_image_quality(target_path, output_image_quality),
|
| 199 |
+
ffmpeg_builder.force_output(output_path)
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
return run_ffmpeg(commands).returncode == 0
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def read_audio_buffer(target_path : str, audio_sample_rate : int, audio_sample_size : int, audio_channel_total : int) -> Optional[AudioBuffer]:
|
| 206 |
+
commands = ffmpeg_builder.chain(
|
| 207 |
+
ffmpeg_builder.set_input(target_path),
|
| 208 |
+
ffmpeg_builder.ignore_video_stream(),
|
| 209 |
+
ffmpeg_builder.set_audio_sample_rate(audio_sample_rate),
|
| 210 |
+
ffmpeg_builder.set_audio_sample_size(audio_sample_size),
|
| 211 |
+
ffmpeg_builder.set_audio_channel_total(audio_channel_total),
|
| 212 |
+
ffmpeg_builder.cast_stream()
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
process = open_ffmpeg(commands)
|
| 216 |
+
audio_buffer, _ = process.communicate()
|
| 217 |
+
if process.returncode == 0:
|
| 218 |
+
return audio_buffer
|
| 219 |
+
return None
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def restore_audio(target_path : str, output_path : str, trim_frame_start : int, trim_frame_end : int) -> bool:
|
| 223 |
+
output_audio_encoder = state_manager.get_item('output_audio_encoder')
|
| 224 |
+
output_audio_quality = state_manager.get_item('output_audio_quality')
|
| 225 |
+
output_audio_volume = state_manager.get_item('output_audio_volume')
|
| 226 |
+
target_video_fps = vision.detect_video_fps(target_path)
|
| 227 |
+
temp_video_path = get_temp_file_path(target_path)
|
| 228 |
+
temp_video_format = cast(VideoFormat, get_file_format(temp_video_path))
|
| 229 |
+
temp_video_duration = vision.detect_video_duration(temp_video_path)
|
| 230 |
+
output_video_format = cast(VideoFormat, get_file_format(output_path))
|
| 231 |
+
output_audio_encoder = fix_audio_encoder(temp_video_format, output_audio_encoder)
|
| 232 |
+
|
| 233 |
+
commands = ffmpeg_builder.chain(
|
| 234 |
+
ffmpeg_builder.set_input(temp_video_path),
|
| 235 |
+
ffmpeg_builder.select_media_range(trim_frame_start, trim_frame_end, target_video_fps),
|
| 236 |
+
ffmpeg_builder.set_input(target_path),
|
| 237 |
+
ffmpeg_builder.copy_video_encoder(),
|
| 238 |
+
ffmpeg_builder.set_audio_encoder(output_audio_encoder),
|
| 239 |
+
ffmpeg_builder.set_audio_quality(output_audio_encoder, output_audio_quality),
|
| 240 |
+
ffmpeg_builder.set_audio_volume(output_audio_volume),
|
| 241 |
+
ffmpeg_builder.select_media_stream('0:v:0'),
|
| 242 |
+
ffmpeg_builder.select_media_stream('1:a:0'),
|
| 243 |
+
ffmpeg_builder.set_video_duration(temp_video_duration),
|
| 244 |
+
ffmpeg_builder.set_faststart(output_video_format),
|
| 245 |
+
ffmpeg_builder.force_output(output_path)
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
return run_ffmpeg(commands).returncode == 0
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def replace_audio(target_path : str, audio_path : str, output_path : str) -> bool:
|
| 252 |
+
output_audio_encoder = state_manager.get_item('output_audio_encoder')
|
| 253 |
+
output_audio_quality = state_manager.get_item('output_audio_quality')
|
| 254 |
+
output_audio_volume = state_manager.get_item('output_audio_volume')
|
| 255 |
+
temp_video_path = get_temp_file_path(target_path)
|
| 256 |
+
temp_video_format = cast(VideoFormat, get_file_format(temp_video_path))
|
| 257 |
+
temp_video_duration = vision.detect_video_duration(temp_video_path)
|
| 258 |
+
output_video_format = cast(VideoFormat, get_file_format(output_path))
|
| 259 |
+
output_audio_encoder = fix_audio_encoder(temp_video_format, output_audio_encoder)
|
| 260 |
+
|
| 261 |
+
commands = ffmpeg_builder.chain(
|
| 262 |
+
ffmpeg_builder.set_input(temp_video_path),
|
| 263 |
+
ffmpeg_builder.set_input(audio_path),
|
| 264 |
+
ffmpeg_builder.copy_video_encoder(),
|
| 265 |
+
ffmpeg_builder.set_audio_encoder(output_audio_encoder),
|
| 266 |
+
ffmpeg_builder.set_audio_quality(output_audio_encoder, output_audio_quality),
|
| 267 |
+
ffmpeg_builder.set_audio_volume(output_audio_volume),
|
| 268 |
+
ffmpeg_builder.set_video_duration(temp_video_duration),
|
| 269 |
+
ffmpeg_builder.set_faststart(output_video_format),
|
| 270 |
+
ffmpeg_builder.force_output(output_path)
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
return run_ffmpeg(commands).returncode == 0
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def merge_video(target_path : str, temp_video_fps : Fps, output_video_resolution : Resolution, output_video_fps : Fps, trim_frame_start : int, trim_frame_end : int) -> bool:
|
| 277 |
+
output_video_encoder = state_manager.get_item('output_video_encoder')
|
| 278 |
+
output_video_quality = state_manager.get_item('output_video_quality')
|
| 279 |
+
output_video_preset = state_manager.get_item('output_video_preset')
|
| 280 |
+
merge_frame_total = vision.predict_video_frame_total(target_path, output_video_fps, trim_frame_start, trim_frame_end)
|
| 281 |
+
temp_video_path = get_temp_file_path(target_path)
|
| 282 |
+
temp_video_format = cast(VideoFormat, get_file_format(temp_video_path))
|
| 283 |
+
temp_frame_pattern = get_temp_frame_pattern(target_path, '%08d')
|
| 284 |
+
output_video_encoder = fix_video_encoder(temp_video_format, output_video_encoder)
|
| 285 |
+
|
| 286 |
+
commands = ffmpeg_builder.chain(
|
| 287 |
+
ffmpeg_builder.set_input_fps(temp_video_fps),
|
| 288 |
+
ffmpeg_builder.set_start_number(trim_frame_start),
|
| 289 |
+
ffmpeg_builder.set_input(temp_frame_pattern),
|
| 290 |
+
ffmpeg_builder.set_media_resolution(vision.pack_resolution(output_video_resolution)),
|
| 291 |
+
ffmpeg_builder.set_video_encoder(output_video_encoder),
|
| 292 |
+
ffmpeg_builder.set_video_tag(output_video_encoder, temp_video_format),
|
| 293 |
+
ffmpeg_builder.set_video_quality(output_video_encoder, output_video_quality),
|
| 294 |
+
ffmpeg_builder.set_video_preset(output_video_encoder, output_video_preset),
|
| 295 |
+
ffmpeg_builder.concat(
|
| 296 |
+
ffmpeg_builder.set_video_fps(output_video_fps),
|
| 297 |
+
ffmpeg_builder.keep_video_alpha(output_video_encoder),
|
| 298 |
+
ffmpeg_builder.convert_color_space('bt709')
|
| 299 |
+
),
|
| 300 |
+
ffmpeg_builder.set_pixel_format(output_video_encoder),
|
| 301 |
+
ffmpeg_builder.force_output(temp_video_path)
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
with tqdm(total = merge_frame_total, desc = translator.get('merging'), unit = 'frame', ascii = ' =', disable = state_manager.get_item('log_level') in [ 'warn', 'error' ]) as progress:
|
| 305 |
+
process = run_ffmpeg_with_progress(commands, partial(update_progress, progress))
|
| 306 |
+
return process.returncode == 0
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def concat_video(output_path : str, temp_output_paths : List[str]) -> bool:
|
| 310 |
+
file_descriptor, concat_video_path = tempfile.mkstemp()
|
| 311 |
+
os.close(file_descriptor)
|
| 312 |
+
|
| 313 |
+
with open(concat_video_path, 'w') as concat_video_file:
|
| 314 |
+
for temp_output_path in temp_output_paths:
|
| 315 |
+
concat_video_file.write('file \'' + os.path.abspath(temp_output_path) + '\'' + os.linesep)
|
| 316 |
+
concat_video_file.flush()
|
| 317 |
+
concat_video_file.close()
|
| 318 |
+
|
| 319 |
+
output_path = os.path.abspath(output_path)
|
| 320 |
+
output_video_format = cast(VideoFormat, get_file_format(output_path))
|
| 321 |
+
|
| 322 |
+
commands = ffmpeg_builder.chain(
|
| 323 |
+
ffmpeg_builder.unsafe_concat(),
|
| 324 |
+
ffmpeg_builder.set_input(concat_video_file.name),
|
| 325 |
+
ffmpeg_builder.copy_video_encoder(),
|
| 326 |
+
ffmpeg_builder.copy_audio_encoder(),
|
| 327 |
+
ffmpeg_builder.set_faststart(output_video_format),
|
| 328 |
+
ffmpeg_builder.force_output(output_path)
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
process = run_ffmpeg(commands)
|
| 332 |
+
process.communicate()
|
| 333 |
+
remove_file(concat_video_path)
|
| 334 |
+
return process.returncode == 0
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def fix_audio_encoder(video_format : VideoFormat, audio_encoder : AudioEncoder) -> AudioEncoder:
|
| 338 |
+
if video_format == 'avi' and audio_encoder == 'libopus':
|
| 339 |
+
return 'aac'
|
| 340 |
+
if video_format in [ 'm4v', 'mpeg', 'wmv' ]:
|
| 341 |
+
return 'aac'
|
| 342 |
+
if video_format == 'mov' and audio_encoder in [ 'flac', 'libopus' ]:
|
| 343 |
+
return 'aac'
|
| 344 |
+
if video_format == 'mxf':
|
| 345 |
+
return 'pcm_s16le'
|
| 346 |
+
if video_format == 'webm':
|
| 347 |
+
return 'libopus'
|
| 348 |
+
return audio_encoder
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def fix_video_encoder(video_format : VideoFormat, video_encoder : VideoEncoder) -> VideoEncoder:
|
| 352 |
+
if video_format in [ 'm4v', 'mpeg', 'mxf', 'wmv' ]:
|
| 353 |
+
return 'libx264'
|
| 354 |
+
if video_format in [ 'mkv', 'mp4' ] and video_encoder == 'rawvideo':
|
| 355 |
+
return 'libx264'
|
| 356 |
+
if video_format == 'mov' and video_encoder == 'libvpx-vp9':
|
| 357 |
+
return 'libx264'
|
| 358 |
+
if video_format == 'webm':
|
| 359 |
+
return 'libvpx-vp9'
|
| 360 |
+
return video_encoder
|
ffmpeg_builder.py
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
import shutil
|
| 3 |
+
from typing import List, Optional
|
| 4 |
+
|
| 5 |
+
import numpy
|
| 6 |
+
|
| 7 |
+
from facefusion.filesystem import get_file_format
|
| 8 |
+
from facefusion.types import AudioEncoder, ColorSpace, ColorTransfer, Command, CommandSet, Duration, Fps, StreamMode, VideoEncoder, VideoFormat, VideoPreset
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def run(commands : List[Command]) -> List[Command]:
|
| 12 |
+
return [ shutil.which('ffmpeg'), '-loglevel', 'error' ] + commands
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def chain(*commands : List[Command]) -> List[Command]:
|
| 16 |
+
return list(itertools.chain(*commands))
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def concat(*__commands__ : List[Command]) -> List[Command]:
|
| 20 |
+
commands = []
|
| 21 |
+
command_set : CommandSet = {}
|
| 22 |
+
|
| 23 |
+
for command in __commands__:
|
| 24 |
+
for argument, value in zip(command[::2], command[1::2]):
|
| 25 |
+
command_set.setdefault(argument, []).append(value)
|
| 26 |
+
|
| 27 |
+
for argument, values in command_set.items():
|
| 28 |
+
commands.append(argument)
|
| 29 |
+
commands.append(','.join(values))
|
| 30 |
+
|
| 31 |
+
return commands
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def get_encoders() -> List[Command]:
|
| 35 |
+
return [ '-encoders' ]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def set_hardware_accelerator(value : str) -> List[Command]:
|
| 39 |
+
return [ '-hwaccel', value ]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def set_progress() -> List[Command]:
|
| 43 |
+
return [ '-progress' ]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def set_input(input_path : str) -> List[Command]:
|
| 47 |
+
return [ '-i', input_path ]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def set_input_fps(input_fps : Fps) -> List[Command]:
|
| 51 |
+
return [ '-r', str(input_fps) ]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def set_start_number(frame_number : int) -> List[Command]:
|
| 55 |
+
return [ '-start_number', str(frame_number) ]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def set_output(output_path : str) -> List[Command]:
|
| 59 |
+
return [ output_path ]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def force_output(output_path : str) -> List[Command]:
|
| 63 |
+
return [ '-y', output_path ]
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def cast_stream() -> List[Command]:
|
| 67 |
+
return [ '-' ]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def set_stream_mode(stream_mode : StreamMode) -> List[Command]:
|
| 71 |
+
if stream_mode == 'udp':
|
| 72 |
+
return [ '-f', 'mpegts' ]
|
| 73 |
+
if stream_mode == 'v4l2':
|
| 74 |
+
return [ '-f', 'v4l2' ]
|
| 75 |
+
return []
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def set_stream_quality(stream_quality : int) -> List[Command]:
|
| 79 |
+
return [ '-b:v', str(stream_quality) + 'k' ]
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def unsafe_concat() -> List[Command]:
|
| 83 |
+
return [ '-f', 'concat', '-safe', '0' ]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def seek_to(time : float) -> List[Command]:
|
| 87 |
+
return [ '-ss', str(time)]
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def set_output_format(output_format : str) -> List[Command]:
|
| 91 |
+
return [ '-f', output_format ]
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def enforce_pixel_format(pixel_format : str) -> List[Command]:
|
| 95 |
+
return [ '-pix_fmt', pixel_format ]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def set_pixel_format(video_encoder : VideoEncoder) -> List[Command]:
|
| 99 |
+
if video_encoder == 'rawvideo':
|
| 100 |
+
return [ '-pix_fmt', 'rgb24' ]
|
| 101 |
+
if video_encoder == 'libvpx-vp9':
|
| 102 |
+
return [ '-pix_fmt', 'yuva420p' ]
|
| 103 |
+
return [ '-pix_fmt', 'yuv420p' ]
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def set_frame_quality(frame_quality : int) -> List[Command]:
|
| 107 |
+
return [ '-q:v', str(frame_quality) ]
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def select_frame_range(frame_start : int, frame_end : int, video_fps : Fps) -> List[Command]:
|
| 111 |
+
if isinstance(frame_start, int) and isinstance(frame_end, int):
|
| 112 |
+
return [ '-vf', 'trim=start_frame=' + str(frame_start) + ':end_frame=' + str(frame_end) + ',fps=' + str(video_fps) ]
|
| 113 |
+
if isinstance(frame_start, int):
|
| 114 |
+
return [ '-vf', 'trim=start_frame=' + str(frame_start) + ',fps=' + str(video_fps) ]
|
| 115 |
+
if isinstance(frame_end, int):
|
| 116 |
+
return [ '-vf', 'trim=end_frame=' + str(frame_end) + ',fps=' + str(video_fps) ]
|
| 117 |
+
return [ '-vf', 'fps=' + str(video_fps) ]
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def prevent_frame_drop() -> List[Command]:
|
| 121 |
+
return [ '-vsync', '0' ]
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def restrict_color_transfer(color_transfer : ColorTransfer) -> List[Command]:
|
| 125 |
+
if color_transfer in [ 'smpte2084', 'arib-std-b67' ]:
|
| 126 |
+
return [ '-vf', 'scale=out_primaries=bt709:out_transfer=bt709:intent=perceptual' ]
|
| 127 |
+
return []
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def convert_color_space(color_space : ColorSpace) -> List[Command]:
|
| 131 |
+
return [ '-vf', 'scale=out_color_matrix=' + color_space + ':out_range=tv,setparams=colorspace=' + color_space + ':color_primaries=' + color_space + ':color_trc=' + color_space ]
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def select_media_range(frame_start : int, frame_end : int, media_fps : Fps) -> List[Command]:
|
| 135 |
+
commands = []
|
| 136 |
+
|
| 137 |
+
if isinstance(frame_start, int):
|
| 138 |
+
commands.extend([ '-ss', str(frame_start / media_fps) ])
|
| 139 |
+
if isinstance(frame_end, int):
|
| 140 |
+
commands.extend([ '-to', str(frame_end / media_fps) ])
|
| 141 |
+
return commands
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def select_media_stream(media_stream : str) -> List[Command]:
|
| 145 |
+
return [ '-map', media_stream ]
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def set_media_resolution(video_resolution : str) -> List[Command]:
|
| 149 |
+
return [ '-s', video_resolution ]
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def set_image_quality(image_path : str, image_quality : int) -> List[Command]:
|
| 153 |
+
if get_file_format(image_path) == 'webp':
|
| 154 |
+
return [ '-q:v', str(image_quality) ]
|
| 155 |
+
|
| 156 |
+
image_compression = round(31 - (image_quality * 0.31))
|
| 157 |
+
return [ '-q:v', str(image_compression) ]
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def set_audio_encoder(audio_codec : str) -> List[Command]:
|
| 161 |
+
return [ '-c:a', audio_codec ]
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def copy_audio_encoder() -> List[Command]:
|
| 165 |
+
return set_audio_encoder('copy')
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def set_audio_sample_rate(audio_sample_rate : int) -> List[Command]:
|
| 169 |
+
return [ '-ar', str(audio_sample_rate) ]
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def set_audio_sample_size(audio_sample_size : int) -> List[Command]:
|
| 173 |
+
if audio_sample_size == 16:
|
| 174 |
+
return [ '-f', 's16le' ]
|
| 175 |
+
if audio_sample_size == 32:
|
| 176 |
+
return [ '-f', 's32le' ]
|
| 177 |
+
return []
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def set_audio_channel_total(audio_channel_total : int) -> List[Command]:
|
| 181 |
+
return [ '-ac', str(audio_channel_total) ]
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def set_audio_quality(audio_encoder : AudioEncoder, audio_quality : int) -> List[Command]:
|
| 185 |
+
if audio_encoder == 'aac':
|
| 186 |
+
audio_compression = numpy.round(numpy.interp(audio_quality, [ 0, 100 ], [ 0.1, 2.0 ]), 1).astype(float).item()
|
| 187 |
+
return [ '-q:a', str(audio_compression) ]
|
| 188 |
+
if audio_encoder == 'libmp3lame':
|
| 189 |
+
audio_compression = numpy.round(numpy.interp(audio_quality, [ 0, 100 ], [ 9, 0 ])).astype(int).item()
|
| 190 |
+
return [ '-q:a', str(audio_compression) ]
|
| 191 |
+
if audio_encoder == 'libopus':
|
| 192 |
+
audio_bit_rate = numpy.round(numpy.interp(audio_quality, [ 0, 100 ], [ 64, 256 ])).astype(int).item()
|
| 193 |
+
return [ '-b:a', str(audio_bit_rate) + 'k' ]
|
| 194 |
+
if audio_encoder == 'libvorbis':
|
| 195 |
+
audio_compression = numpy.round(numpy.interp(audio_quality, [ 0, 100 ], [ -1, 10 ]), 1).astype(float).item()
|
| 196 |
+
return [ '-q:a', str(audio_compression) ]
|
| 197 |
+
return []
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def set_audio_volume(audio_volume : int) -> List[Command]:
|
| 201 |
+
return [ '-filter:a', 'volume=' + str(audio_volume / 100) ]
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def set_thread_count(thread_count : int) -> List[Command]:
|
| 205 |
+
return [ '-threads', str(thread_count) ]
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def set_video_encoder(video_encoder : str) -> List[Command]:
|
| 209 |
+
return [ '-c:v', video_encoder ]
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def copy_video_encoder() -> List[Command]:
|
| 213 |
+
return set_video_encoder('copy')
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def set_faststart(video_format : VideoFormat) -> List[Command]:
|
| 217 |
+
if video_format in [ 'm4v', 'mov', 'mp4' ]:
|
| 218 |
+
return [ '-movflags', '+faststart' ]
|
| 219 |
+
return []
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def set_video_tag(video_encoder : VideoEncoder, video_format : VideoFormat) -> List[Command]:
|
| 223 |
+
if video_format in [ 'm4v', 'mov', 'mp4' ] and video_encoder in [ 'libx265', 'hevc_nvenc', 'hevc_amf', 'hevc_qsv', 'hevc_videotoolbox' ]:
|
| 224 |
+
return [ '-tag:v', 'hvc1' ]
|
| 225 |
+
return []
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def set_video_quality(video_encoder : VideoEncoder, video_quality : int) -> List[Command]:
|
| 229 |
+
if video_encoder in [ 'libx264', 'libx264rgb', 'libx265' ]:
|
| 230 |
+
video_compression = numpy.round(numpy.interp(video_quality, [ 0, 100 ], [ 51, 0 ])).astype(int).item()
|
| 231 |
+
return [ '-crf', str(video_compression) ]
|
| 232 |
+
if video_encoder == 'libvpx-vp9':
|
| 233 |
+
video_compression = numpy.round(numpy.interp(video_quality, [ 0, 100 ], [ 63, 0 ])).astype(int).item()
|
| 234 |
+
return [ '-crf', str(video_compression) ]
|
| 235 |
+
if video_encoder in [ 'h264_nvenc', 'hevc_nvenc' ]:
|
| 236 |
+
video_compression = numpy.round(numpy.interp(video_quality, [ 0, 100 ], [ 51, 0 ])).astype(int).item()
|
| 237 |
+
return [ '-cq', str(video_compression) ]
|
| 238 |
+
if video_encoder in [ 'h264_amf', 'hevc_amf' ]:
|
| 239 |
+
video_compression = numpy.round(numpy.interp(video_quality, [ 0, 100 ], [ 51, 0 ])).astype(int).item()
|
| 240 |
+
return [ '-qp_i', str(video_compression), '-qp_p', str(video_compression), '-qp_b', str(video_compression) ]
|
| 241 |
+
if video_encoder in [ 'h264_qsv', 'hevc_qsv' ]:
|
| 242 |
+
video_compression = numpy.round(numpy.interp(video_quality, [ 0, 100 ], [ 51, 0 ])).astype(int).item()
|
| 243 |
+
return [ '-qp', str(video_compression) ]
|
| 244 |
+
if video_encoder in [ 'h264_videotoolbox', 'hevc_videotoolbox' ]:
|
| 245 |
+
video_bit_rate = numpy.round(numpy.interp(video_quality, [ 0, 100 ], [ 1024, 50512 ])).astype(int).item()
|
| 246 |
+
return [ '-b:v', str(video_bit_rate) + 'k' ]
|
| 247 |
+
return []
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def set_video_preset(video_encoder : VideoEncoder, video_preset : VideoPreset) -> List[Command]:
|
| 251 |
+
if video_encoder in [ 'libx264', 'libx264rgb', 'libx265' ]:
|
| 252 |
+
return [ '-preset', video_preset ]
|
| 253 |
+
if video_encoder in [ 'h264_nvenc', 'hevc_nvenc' ]:
|
| 254 |
+
return [ '-preset', map_nvenc_preset(video_preset) ]
|
| 255 |
+
if video_encoder in [ 'h264_amf', 'hevc_amf' ]:
|
| 256 |
+
return [ '-quality', map_amf_preset(video_preset) ]
|
| 257 |
+
if video_encoder in [ 'h264_qsv', 'hevc_qsv' ]:
|
| 258 |
+
return [ '-preset', map_qsv_preset(video_preset) ]
|
| 259 |
+
return []
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def set_video_fps(video_fps : Fps) -> List[Command]:
|
| 263 |
+
return [ '-vf', 'fps=' + str(video_fps) ]
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def set_video_duration(video_duration : Duration) -> List[Command]:
|
| 267 |
+
return [ '-t', str(video_duration) ]
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def keep_video_alpha(video_encoder : VideoEncoder) -> List[Command]:
|
| 271 |
+
if video_encoder == 'libvpx-vp9':
|
| 272 |
+
return [ '-vf', 'format=yuva420p' ]
|
| 273 |
+
return []
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def capture_video() -> List[Command]:
|
| 277 |
+
return [ '-f', 'rawvideo', '-pix_fmt', 'rgb24' ]
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def ignore_video_stream() -> List[Command]:
|
| 281 |
+
return [ '-vn' ]
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def map_nvenc_preset(video_preset : VideoPreset) -> Optional[str]:
|
| 285 |
+
if video_preset in [ 'ultrafast', 'superfast', 'veryfast', 'faster', 'fast' ]:
|
| 286 |
+
return 'fast'
|
| 287 |
+
if video_preset == 'medium':
|
| 288 |
+
return 'medium'
|
| 289 |
+
if video_preset in [ 'slow', 'slower', 'veryslow' ]:
|
| 290 |
+
return 'slow'
|
| 291 |
+
return None
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def map_amf_preset(video_preset : VideoPreset) -> Optional[str]:
|
| 295 |
+
if video_preset in [ 'ultrafast', 'superfast', 'veryfast' ]:
|
| 296 |
+
return 'speed'
|
| 297 |
+
if video_preset in [ 'faster', 'fast', 'medium' ]:
|
| 298 |
+
return 'balanced'
|
| 299 |
+
if video_preset in [ 'slow', 'slower', 'veryslow' ]:
|
| 300 |
+
return 'quality'
|
| 301 |
+
return None
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def map_qsv_preset(video_preset : VideoPreset) -> Optional[str]:
|
| 305 |
+
if video_preset in [ 'ultrafast', 'superfast', 'veryfast' ]:
|
| 306 |
+
return 'veryfast'
|
| 307 |
+
if video_preset in [ 'faster', 'fast', 'medium', 'slow', 'slower', 'veryslow' ]:
|
| 308 |
+
return video_preset
|
| 309 |
+
return None
|
ffprobe.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import subprocess
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
from typing import Dict, List
|
| 4 |
+
|
| 5 |
+
from facefusion import ffprobe_builder
|
| 6 |
+
from facefusion.types import AudioMetadata, Buffer, Command, Fps, VideoMetadata
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def run_ffprobe(commands : List[Command]) -> subprocess.Popen[Buffer]:
|
| 10 |
+
commands = ffprobe_builder.run(commands)
|
| 11 |
+
return subprocess.Popen(commands, stderr = subprocess.PIPE, stdout = subprocess.PIPE)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def parse_entries(output : Buffer) -> Dict[str, str]:
|
| 15 |
+
media_entries = {}
|
| 16 |
+
|
| 17 |
+
if output:
|
| 18 |
+
lines = output.decode().strip().splitlines()
|
| 19 |
+
|
| 20 |
+
for line in lines:
|
| 21 |
+
if '=' in line:
|
| 22 |
+
key, value = line.split('=', 1)
|
| 23 |
+
media_entries[key] = value
|
| 24 |
+
|
| 25 |
+
return media_entries
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def probe_audio_entries(audio_path : str, entries : List[str]) -> Dict[str, str]:
|
| 29 |
+
commands = ffprobe_builder.chain(
|
| 30 |
+
ffprobe_builder.select_stream('a:0'),
|
| 31 |
+
ffprobe_builder.show_stream_entries(entries),
|
| 32 |
+
ffprobe_builder.format_to_key_value(),
|
| 33 |
+
ffprobe_builder.set_input(audio_path)
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
output, _ = run_ffprobe(commands).communicate()
|
| 37 |
+
|
| 38 |
+
return parse_entries(output)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def probe_video_entries(video_path : str, entries : List[str]) -> Dict[str, str]:
|
| 42 |
+
commands = ffprobe_builder.chain(
|
| 43 |
+
ffprobe_builder.select_stream('v:0'),
|
| 44 |
+
ffprobe_builder.show_stream_entries(entries),
|
| 45 |
+
ffprobe_builder.format_to_key_value(),
|
| 46 |
+
ffprobe_builder.set_input(video_path)
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
output, _ = run_ffprobe(commands).communicate()
|
| 50 |
+
|
| 51 |
+
return parse_entries(output)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def probe_format_entries(media_path : str, entries : List[str]) -> Dict[str, str]:
|
| 55 |
+
commands = ffprobe_builder.chain(
|
| 56 |
+
ffprobe_builder.show_format_entries(entries),
|
| 57 |
+
ffprobe_builder.format_to_key_value(),
|
| 58 |
+
ffprobe_builder.set_input(media_path)
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
output, _ = run_ffprobe(commands).communicate()
|
| 62 |
+
|
| 63 |
+
return parse_entries(output)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@lru_cache(maxsize = 128)
|
| 67 |
+
def extract_static_audio_metadata(audio_path : str) -> AudioMetadata:
|
| 68 |
+
return extract_audio_metadata(audio_path)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def extract_audio_metadata(audio_path : str) -> AudioMetadata:
|
| 72 |
+
audio_entries = probe_audio_entries(audio_path, [ 'sample_rate', 'channels' ])
|
| 73 |
+
format_entries = probe_format_entries(audio_path, [ 'duration', 'bit_rate' ])
|
| 74 |
+
|
| 75 |
+
duration = float(format_entries.get('duration'))
|
| 76 |
+
sample_rate = int(audio_entries.get('sample_rate'))
|
| 77 |
+
frame_total = round(duration * sample_rate)
|
| 78 |
+
channel_total = int(audio_entries.get('channels'))
|
| 79 |
+
bit_rate = int(format_entries.get('bit_rate'))
|
| 80 |
+
|
| 81 |
+
audio_metadata : AudioMetadata =\
|
| 82 |
+
{
|
| 83 |
+
'duration' : duration,
|
| 84 |
+
'frame_total' : frame_total,
|
| 85 |
+
'channel_total' : channel_total,
|
| 86 |
+
'sample_rate' : sample_rate,
|
| 87 |
+
'bit_rate' : bit_rate
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
return audio_metadata
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@lru_cache(maxsize = 128)
|
| 94 |
+
def extract_static_video_metadata(video_path : str) -> VideoMetadata:
|
| 95 |
+
return extract_video_metadata(video_path)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def extract_video_metadata(video_path : str) -> VideoMetadata:
|
| 99 |
+
video_entries = probe_video_entries(video_path, [ 'width', 'height', 'r_frame_rate', 'color_transfer' ])
|
| 100 |
+
format_entries = probe_format_entries(video_path, [ 'duration', 'bit_rate' ])
|
| 101 |
+
|
| 102 |
+
duration = float(format_entries.get('duration'))
|
| 103 |
+
fps = extract_video_fps(video_entries.get('r_frame_rate'))
|
| 104 |
+
frame_total = round(duration * fps)
|
| 105 |
+
width = int(video_entries.get('width'))
|
| 106 |
+
height = int(video_entries.get('height'))
|
| 107 |
+
bit_rate = int(format_entries.get('bit_rate'))
|
| 108 |
+
color_transfer = video_entries.get('color_transfer', 'unknown')
|
| 109 |
+
|
| 110 |
+
video_metadata : VideoMetadata =\
|
| 111 |
+
{
|
| 112 |
+
'duration' : duration,
|
| 113 |
+
'frame_total' : frame_total,
|
| 114 |
+
'fps' : fps,
|
| 115 |
+
'resolution' : (width, height),
|
| 116 |
+
'bit_rate' : bit_rate,
|
| 117 |
+
'color_transfer' : color_transfer
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
return video_metadata
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def extract_video_fps(frame_rate : str) -> Fps:
|
| 124 |
+
if frame_rate and '/' in frame_rate:
|
| 125 |
+
numerator, denominator = frame_rate.split('/')
|
| 126 |
+
|
| 127 |
+
if int(numerator) and int(denominator):
|
| 128 |
+
return int(numerator) / int(denominator)
|
| 129 |
+
|
| 130 |
+
return 0.0
|
ffprobe_builder.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
import shutil
|
| 3 |
+
from typing import List
|
| 4 |
+
|
| 5 |
+
from facefusion.types import Command
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def run(commands : List[Command]) -> List[Command]:
|
| 9 |
+
return [ shutil.which('ffprobe'), '-loglevel', 'error' ] + commands
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def chain(*commands : List[Command]) -> List[Command]:
|
| 13 |
+
return list(itertools.chain(*commands))
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def select_stream(stream : str) -> List[Command]:
|
| 17 |
+
return [ '-select_streams', stream ]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def show_stream_entries(entries : List[str]) -> List[Command]:
|
| 21 |
+
return [ '-show_entries', 'stream=' + ','.join(entries) ]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def show_format_entries(entries : List[str]) -> List[Command]:
|
| 25 |
+
return [ '-show_entries', 'format=' + ','.join(entries) ]
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def format_to_key_value() -> List[Command]:
|
| 29 |
+
return [ '-of', 'default=noprint_wrappers=1' ]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def set_input(input_path : str) -> List[Command]:
|
| 33 |
+
return [ '-i', input_path ]
|
filesystem.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import glob
|
| 2 |
+
import os
|
| 3 |
+
import shutil
|
| 4 |
+
from typing import List, Optional
|
| 5 |
+
|
| 6 |
+
import facefusion.choices
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def get_file_size(file_path : str) -> int:
|
| 10 |
+
if is_file(file_path):
|
| 11 |
+
return os.path.getsize(file_path)
|
| 12 |
+
return 0
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def get_file_name(file_path : str) -> Optional[str]:
|
| 16 |
+
file_name, _ = os.path.splitext(os.path.basename(file_path))
|
| 17 |
+
|
| 18 |
+
if file_name:
|
| 19 |
+
return file_name
|
| 20 |
+
return None
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def get_file_extension(file_path : str) -> Optional[str]:
|
| 24 |
+
_, file_extension = os.path.splitext(file_path)
|
| 25 |
+
|
| 26 |
+
if file_extension:
|
| 27 |
+
return file_extension.lower()
|
| 28 |
+
return None
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def get_file_format(file_path : str) -> Optional[str]:
|
| 32 |
+
file_extension = get_file_extension(file_path)
|
| 33 |
+
|
| 34 |
+
if file_extension:
|
| 35 |
+
if file_extension == '.jpg':
|
| 36 |
+
return 'jpeg'
|
| 37 |
+
if file_extension == '.tif':
|
| 38 |
+
return 'tiff'
|
| 39 |
+
if file_extension == '.mpg':
|
| 40 |
+
return 'mpeg'
|
| 41 |
+
return file_extension.lstrip('.')
|
| 42 |
+
return None
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def same_file_extension(first_file_path : str, second_file_path : str) -> bool:
|
| 46 |
+
first_file_extension = get_file_extension(first_file_path)
|
| 47 |
+
second_file_extension = get_file_extension(second_file_path)
|
| 48 |
+
|
| 49 |
+
if first_file_extension and second_file_extension:
|
| 50 |
+
return get_file_extension(first_file_path) == get_file_extension(second_file_path)
|
| 51 |
+
return False
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def is_file(file_path : str) -> bool:
|
| 55 |
+
if file_path:
|
| 56 |
+
return os.path.isfile(file_path)
|
| 57 |
+
return False
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def is_audio(audio_path : str) -> bool:
|
| 61 |
+
return is_file(audio_path) and get_file_format(audio_path) in facefusion.choices.audio_formats
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def has_audio(audio_paths : List[str]) -> bool:
|
| 65 |
+
if audio_paths:
|
| 66 |
+
return any(map(is_audio, audio_paths))
|
| 67 |
+
return False
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def are_audios(audio_paths : List[str]) -> bool:
|
| 71 |
+
if audio_paths:
|
| 72 |
+
return all(map(is_audio, audio_paths))
|
| 73 |
+
return False
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def is_image(image_path : str) -> bool:
|
| 77 |
+
return is_file(image_path) and get_file_format(image_path) in facefusion.choices.image_formats
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def has_image(image_paths : List[str]) -> bool:
|
| 81 |
+
if image_paths:
|
| 82 |
+
return any(is_image(image_path) for image_path in image_paths)
|
| 83 |
+
return False
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def are_images(image_paths : List[str]) -> bool:
|
| 87 |
+
if image_paths:
|
| 88 |
+
return all(map(is_image, image_paths))
|
| 89 |
+
return False
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def is_video(video_path : str) -> bool:
|
| 93 |
+
return is_file(video_path) and get_file_format(video_path) in facefusion.choices.video_formats
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def has_video(video_paths : List[str]) -> bool:
|
| 97 |
+
if video_paths:
|
| 98 |
+
return any(map(is_video, video_paths))
|
| 99 |
+
return False
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def are_videos(video_paths : List[str]) -> bool:
|
| 103 |
+
if video_paths:
|
| 104 |
+
return all(map(is_video, video_paths))
|
| 105 |
+
return False
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def filter_audio_paths(paths : List[str]) -> List[str]:
|
| 109 |
+
if paths:
|
| 110 |
+
return [ path for path in paths if is_audio(path) ]
|
| 111 |
+
return []
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def filter_image_paths(paths : List[str]) -> List[str]:
|
| 115 |
+
if paths:
|
| 116 |
+
return [ path for path in paths if is_image(path) ]
|
| 117 |
+
return []
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def copy_file(file_path : str, move_path : str) -> bool:
|
| 121 |
+
if is_file(file_path):
|
| 122 |
+
shutil.copy(file_path, move_path)
|
| 123 |
+
return is_file(move_path)
|
| 124 |
+
return False
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def move_file(file_path : str, move_path : str) -> bool:
|
| 128 |
+
if is_file(file_path):
|
| 129 |
+
shutil.move(file_path, move_path)
|
| 130 |
+
return not is_file(file_path) and is_file(move_path)
|
| 131 |
+
return False
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def remove_file(file_path : str) -> bool:
|
| 135 |
+
if is_file(file_path):
|
| 136 |
+
os.remove(file_path)
|
| 137 |
+
return not is_file(file_path)
|
| 138 |
+
return False
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def resolve_file_paths(directory_path : str) -> List[str]:
|
| 142 |
+
file_paths : List[str] = []
|
| 143 |
+
|
| 144 |
+
if is_directory(directory_path):
|
| 145 |
+
file_names_and_extensions = sorted(os.listdir(directory_path))
|
| 146 |
+
|
| 147 |
+
for file_name_and_extension in file_names_and_extensions:
|
| 148 |
+
if not file_name_and_extension.startswith(('.', '__')):
|
| 149 |
+
file_path = os.path.join(directory_path, file_name_and_extension)
|
| 150 |
+
file_paths.append(file_path)
|
| 151 |
+
|
| 152 |
+
return file_paths
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def resolve_file_pattern(file_pattern : str) -> List[str]:
|
| 156 |
+
if in_directory(file_pattern):
|
| 157 |
+
return sorted(glob.glob(file_pattern))
|
| 158 |
+
return []
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def is_directory(directory_path : str) -> bool:
|
| 162 |
+
if directory_path:
|
| 163 |
+
return os.path.isdir(directory_path)
|
| 164 |
+
return False
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def in_directory(file_path : str) -> bool:
|
| 168 |
+
if file_path:
|
| 169 |
+
directory_path = os.path.dirname(file_path)
|
| 170 |
+
if directory_path:
|
| 171 |
+
return not is_directory(file_path) and is_directory(directory_path)
|
| 172 |
+
return False
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def create_directory(directory_path : str) -> bool:
|
| 176 |
+
if directory_path and not is_file(directory_path):
|
| 177 |
+
os.makedirs(directory_path, exist_ok = True)
|
| 178 |
+
return is_directory(directory_path)
|
| 179 |
+
return False
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def remove_directory(directory_path : str) -> bool:
|
| 183 |
+
if is_directory(directory_path):
|
| 184 |
+
shutil.rmtree(directory_path, ignore_errors = True)
|
| 185 |
+
return not is_directory(directory_path)
|
| 186 |
+
return False
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def resolve_relative_path(path : str) -> str:
|
| 190 |
+
return os.path.abspath(os.path.join(os.path.dirname(__file__), path))
|
frame_store.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from facefusion.types import FrameStoreSet, VisionFrame, VisionFrameSet
|
| 2 |
+
|
| 3 |
+
FRAME_STORE_SET : FrameStoreSet = {}
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def get_frame_store(id : str) -> VisionFrameSet:
|
| 7 |
+
if id not in FRAME_STORE_SET:
|
| 8 |
+
FRAME_STORE_SET[id] = {}
|
| 9 |
+
|
| 10 |
+
return FRAME_STORE_SET.get(id)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def set_frame(id : str, frame_number : int, vision_frame : VisionFrame) -> None:
|
| 14 |
+
frame_store = get_frame_store(id)
|
| 15 |
+
frame_store[frame_number] = vision_frame
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def select_frame_set(id : str, frame_start : int, frame_end : int) -> VisionFrameSet:
|
| 19 |
+
frame_store = get_frame_store(id)
|
| 20 |
+
frame_set = {}
|
| 21 |
+
|
| 22 |
+
for frame_number in range(frame_start, frame_end + 1):
|
| 23 |
+
if frame_number in frame_store:
|
| 24 |
+
frame_set[frame_number] = frame_store.get(frame_number)
|
| 25 |
+
|
| 26 |
+
return frame_set
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def reduce_frames(id : str, frame_min : int, frame_max : int) -> None:
|
| 30 |
+
FRAME_STORE_SET[id] = select_frame_set(id, frame_min, frame_max)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def clear_frames(id : str) -> None:
|
| 34 |
+
if id in FRAME_STORE_SET:
|
| 35 |
+
del FRAME_STORE_SET[id]
|
hash_helper.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import zlib
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
from facefusion.filesystem import get_file_name, is_file
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def create_hash(content : bytes) -> str:
|
| 9 |
+
return format(zlib.crc32(content), '08x')
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def validate_hash(validate_path : str) -> bool:
|
| 13 |
+
hash_path = get_hash_path(validate_path)
|
| 14 |
+
|
| 15 |
+
if is_file(hash_path):
|
| 16 |
+
with open(hash_path) as hash_file:
|
| 17 |
+
hash_content = hash_file.read()
|
| 18 |
+
|
| 19 |
+
with open(validate_path, 'rb') as validate_file:
|
| 20 |
+
validate_content = validate_file.read()
|
| 21 |
+
|
| 22 |
+
return create_hash(validate_content) == hash_content
|
| 23 |
+
return False
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def get_hash_path(validate_path : str) -> Optional[str]:
|
| 27 |
+
if is_file(validate_path):
|
| 28 |
+
validate_directory_path, file_name_and_extension = os.path.split(validate_path)
|
| 29 |
+
validate_file_name = get_file_name(file_name_and_extension)
|
| 30 |
+
|
| 31 |
+
return os.path.join(validate_directory_path, validate_file_name + '.hash')
|
| 32 |
+
return None
|
inference_manager.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib
|
| 2 |
+
import random
|
| 3 |
+
from functools import lru_cache
|
| 4 |
+
from time import sleep, time
|
| 5 |
+
from typing import List
|
| 6 |
+
|
| 7 |
+
from onnxruntime import InferenceSession
|
| 8 |
+
|
| 9 |
+
from facefusion import logger, process_manager, state_manager, translator
|
| 10 |
+
from facefusion.app_context import detect_app_context
|
| 11 |
+
from facefusion.common_helper import is_windows
|
| 12 |
+
from facefusion.execution import create_inference_providers, has_execution_provider
|
| 13 |
+
from facefusion.exit_helper import fatal_exit
|
| 14 |
+
from facefusion.filesystem import get_file_name, is_file
|
| 15 |
+
from facefusion.time_helper import calculate_end_time
|
| 16 |
+
from facefusion.types import DownloadSet, ExecutionProvider, InferencePool, InferencePoolSet, InferenceProvider
|
| 17 |
+
|
| 18 |
+
INFERENCE_POOL_SET : InferencePoolSet =\
|
| 19 |
+
{
|
| 20 |
+
'cli': {},
|
| 21 |
+
'ui': {}
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def get_inference_pool(module_name : str, model_names : List[str], model_source_set : DownloadSet) -> InferencePool:
|
| 26 |
+
while process_manager.is_checking():
|
| 27 |
+
sleep(0.5)
|
| 28 |
+
execution_device_ids = state_manager.get_item('execution_device_ids')
|
| 29 |
+
execution_providers = state_manager.get_item('execution_providers')
|
| 30 |
+
app_context = detect_app_context()
|
| 31 |
+
|
| 32 |
+
for execution_device_id in execution_device_ids:
|
| 33 |
+
inference_context = get_inference_context(module_name, model_names, execution_device_id, execution_providers)
|
| 34 |
+
|
| 35 |
+
if app_context == 'cli' and INFERENCE_POOL_SET.get('ui').get(inference_context):
|
| 36 |
+
INFERENCE_POOL_SET['cli'][inference_context] = INFERENCE_POOL_SET.get('ui').get(inference_context)
|
| 37 |
+
if app_context == 'ui' and INFERENCE_POOL_SET.get('cli').get(inference_context):
|
| 38 |
+
INFERENCE_POOL_SET['ui'][inference_context] = INFERENCE_POOL_SET.get('cli').get(inference_context)
|
| 39 |
+
if not INFERENCE_POOL_SET.get(app_context).get(inference_context):
|
| 40 |
+
inference_providers = resolve_static_inference_providers(module_name, execution_device_id)
|
| 41 |
+
INFERENCE_POOL_SET[app_context][inference_context] = create_inference_pool(model_source_set, inference_providers)
|
| 42 |
+
|
| 43 |
+
current_inference_context = get_inference_context(module_name, model_names, random.choice(execution_device_ids), execution_providers)
|
| 44 |
+
return INFERENCE_POOL_SET.get(app_context).get(current_inference_context)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def create_inference_pool(model_source_set : DownloadSet, inference_providers : List[InferenceProvider]) -> InferencePool:
|
| 48 |
+
inference_pool : InferencePool = {}
|
| 49 |
+
|
| 50 |
+
for model_name in model_source_set.keys():
|
| 51 |
+
model_path = model_source_set.get(model_name).get('path')
|
| 52 |
+
if is_file(model_path):
|
| 53 |
+
inference_pool[model_name] = create_inference_session(model_path, inference_providers)
|
| 54 |
+
|
| 55 |
+
return inference_pool
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def clear_inference_pool(module_name : str, model_names : List[str]) -> None:
|
| 59 |
+
execution_device_ids = state_manager.get_item('execution_device_ids')
|
| 60 |
+
execution_providers = state_manager.get_item('execution_providers')
|
| 61 |
+
app_context = detect_app_context()
|
| 62 |
+
|
| 63 |
+
if is_windows() and has_execution_provider('directml'):
|
| 64 |
+
INFERENCE_POOL_SET[app_context].clear()
|
| 65 |
+
|
| 66 |
+
for execution_device_id in execution_device_ids:
|
| 67 |
+
inference_context = get_inference_context(module_name, model_names, execution_device_id, execution_providers)
|
| 68 |
+
if INFERENCE_POOL_SET.get(app_context).get(inference_context):
|
| 69 |
+
del INFERENCE_POOL_SET[app_context][inference_context]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def create_inference_session(model_path : str, inference_providers : List[InferenceProvider]) -> InferenceSession:
|
| 73 |
+
model_file_name = get_file_name(model_path)
|
| 74 |
+
start_time = time()
|
| 75 |
+
|
| 76 |
+
try:
|
| 77 |
+
inference_session = InferenceSession(model_path, providers = inference_providers)
|
| 78 |
+
logger.debug(translator.get('loading_model_succeeded').format(model_name = model_file_name, seconds = calculate_end_time(start_time)), __name__)
|
| 79 |
+
return inference_session
|
| 80 |
+
|
| 81 |
+
except Exception:
|
| 82 |
+
logger.error(translator.get('loading_model_failed').format(model_name = model_file_name), __name__)
|
| 83 |
+
fatal_exit(1)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def get_inference_context(module_name : str, model_names : List[str], execution_device_id : int, execution_providers : List[ExecutionProvider]) -> str:
|
| 87 |
+
inference_context = '.'.join([ module_name ] + model_names + [ str(execution_device_id) ] + list(execution_providers))
|
| 88 |
+
return inference_context
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@lru_cache()
|
| 92 |
+
def resolve_static_inference_providers(module_name : str, execution_device_id : int) -> List[InferenceProvider]:
|
| 93 |
+
module = importlib.import_module(module_name)
|
| 94 |
+
execution_providers = state_manager.get_item('execution_providers')
|
| 95 |
+
|
| 96 |
+
if hasattr(module, 'override_inference_providers'):
|
| 97 |
+
override_inference_providers = getattr(module, 'override_inference_providers')()
|
| 98 |
+
|
| 99 |
+
if override_inference_providers:
|
| 100 |
+
return override_inference_providers
|
| 101 |
+
|
| 102 |
+
if hasattr(module, 'adjust_inference_providers'):
|
| 103 |
+
adjust_inference_providers = getattr(module, 'adjust_inference_providers')()
|
| 104 |
+
|
| 105 |
+
if adjust_inference_providers:
|
| 106 |
+
inference_providers = create_inference_providers(execution_device_id, execution_providers)
|
| 107 |
+
|
| 108 |
+
for adjust_inference_provider in adjust_inference_providers:
|
| 109 |
+
for inference_provider in inference_providers:
|
| 110 |
+
if inference_provider[0] == adjust_inference_provider[0] and inference_provider[1]:
|
| 111 |
+
inference_provider[1].update(adjust_inference_provider[1])
|
| 112 |
+
|
| 113 |
+
return inference_providers
|
| 114 |
+
|
| 115 |
+
return create_inference_providers(execution_device_id, execution_providers)
|
installer.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import shutil
|
| 3 |
+
import signal
|
| 4 |
+
import subprocess
|
| 5 |
+
import sys
|
| 6 |
+
from argparse import ArgumentParser, HelpFormatter
|
| 7 |
+
from functools import partial
|
| 8 |
+
from types import FrameType
|
| 9 |
+
|
| 10 |
+
from facefusion import metadata
|
| 11 |
+
from facefusion.common_helper import is_linux, is_windows
|
| 12 |
+
|
| 13 |
+
LOCALES =\
|
| 14 |
+
{
|
| 15 |
+
'install_dependency': 'install the {dependency} package',
|
| 16 |
+
'force_reinstall': 'force reinstall of packages',
|
| 17 |
+
'skip_conda': 'skip the conda environment check',
|
| 18 |
+
'conda_not_activated': 'conda is not activated'
|
| 19 |
+
}
|
| 20 |
+
ONNXRUNTIME_SET =\
|
| 21 |
+
{
|
| 22 |
+
'default': ('onnxruntime', '1.26.0')
|
| 23 |
+
}
|
| 24 |
+
if is_windows() or is_linux():
|
| 25 |
+
ONNXRUNTIME_SET['cuda'] = ('onnxruntime-gpu', '1.26.0')
|
| 26 |
+
ONNXRUNTIME_SET['openvino'] = ('onnxruntime-openvino', '1.24.1')
|
| 27 |
+
if is_windows():
|
| 28 |
+
ONNXRUNTIME_SET['directml'] = ('onnxruntime-directml', '1.24.4')
|
| 29 |
+
ONNXRUNTIME_SET['qnn'] = ('onnxruntime-qnn', '1.24.4')
|
| 30 |
+
if is_linux():
|
| 31 |
+
ONNXRUNTIME_SET['migraphx'] = ('onnxruntime-migraphx', '1.26.0')
|
| 32 |
+
ONNXRUNTIME_SET['rocm'] = ('onnxruntime-rocm', '1.22.2.post3')
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def cli() -> None:
|
| 36 |
+
signal.signal(signal.SIGINT, signal_exit)
|
| 37 |
+
program = ArgumentParser(formatter_class = partial(HelpFormatter, max_help_position = 50))
|
| 38 |
+
program.add_argument('onnxruntime', help = LOCALES.get('install_dependency').format(dependency = 'onnxruntime'), choices = ONNXRUNTIME_SET.keys())
|
| 39 |
+
program.add_argument('--force-reinstall', help = LOCALES.get('force_reinstall'), action = 'store_true')
|
| 40 |
+
program.add_argument('--skip-conda', help = LOCALES.get('skip_conda'), action = 'store_true')
|
| 41 |
+
program.add_argument('-v', '--version', version = metadata.get('name') + ' ' + metadata.get('version'), action = 'version')
|
| 42 |
+
run(program)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def signal_exit(signum : int, frame : FrameType) -> None:
|
| 46 |
+
sys.exit(0)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def run(program : ArgumentParser) -> None:
|
| 50 |
+
args = program.parse_args()
|
| 51 |
+
has_conda = 'CONDA_PREFIX' in os.environ
|
| 52 |
+
|
| 53 |
+
if not args.skip_conda and not has_conda:
|
| 54 |
+
sys.stdout.write(LOCALES.get('conda_not_activated') + os.linesep)
|
| 55 |
+
sys.exit(1)
|
| 56 |
+
|
| 57 |
+
commands = [ shutil.which('pip'), 'install' ]
|
| 58 |
+
|
| 59 |
+
if args.force_reinstall:
|
| 60 |
+
commands.append('--force-reinstall')
|
| 61 |
+
|
| 62 |
+
with open('requirements.txt') as file:
|
| 63 |
+
|
| 64 |
+
for line in file.readlines():
|
| 65 |
+
__line__ = line.strip()
|
| 66 |
+
if not __line__.startswith('onnxruntime'):
|
| 67 |
+
commands.append(__line__)
|
| 68 |
+
|
| 69 |
+
onnxruntime_name, onnxruntime_version = ONNXRUNTIME_SET.get(args.onnxruntime)
|
| 70 |
+
commands.append(onnxruntime_name + '==' + onnxruntime_version)
|
| 71 |
+
|
| 72 |
+
subprocess.call([ shutil.which('pip'), 'uninstall', 'onnxruntime', onnxruntime_name, '-y', '-q' ])
|
| 73 |
+
|
| 74 |
+
subprocess.call(commands)
|
json.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from json import JSONDecodeError
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
from facefusion.filesystem import is_file
|
| 6 |
+
from facefusion.types import Content
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def read_json(json_path : str) -> Optional[Content]:
|
| 10 |
+
if is_file(json_path):
|
| 11 |
+
try:
|
| 12 |
+
with open(json_path) as json_file:
|
| 13 |
+
return json.load(json_file)
|
| 14 |
+
except JSONDecodeError:
|
| 15 |
+
pass
|
| 16 |
+
return None
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def write_json(json_path : str, content : Content) -> bool:
|
| 20 |
+
with open(json_path, 'w') as json_file:
|
| 21 |
+
json.dump(content, json_file, indent = 4)
|
| 22 |
+
return is_file(json_path)
|
locales.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from facefusion.types import Locales
|
| 2 |
+
|
| 3 |
+
LOCALES : Locales =\
|
| 4 |
+
{
|
| 5 |
+
'en':
|
| 6 |
+
{
|
| 7 |
+
'conda_not_activated': 'conda is not activated',
|
| 8 |
+
'python_not_supported': 'python version is not supported, upgrade to {version} or higher',
|
| 9 |
+
'dependency_not_installed': '{dependency} is not installed',
|
| 10 |
+
'creating_temp': 'creating temporary resources',
|
| 11 |
+
'extracting_frames': 'extracting frames with a resolution of {resolution} and {fps} frames per second',
|
| 12 |
+
'extracting_frames_succeeded': 'extracting frames succeeded',
|
| 13 |
+
'extracting_frames_failed': 'extracting frames failed',
|
| 14 |
+
'analysing': 'analysing',
|
| 15 |
+
'extracting': 'extracting',
|
| 16 |
+
'streaming': 'streaming',
|
| 17 |
+
'processing': 'processing',
|
| 18 |
+
'merging': 'merging',
|
| 19 |
+
'downloading': 'downloading',
|
| 20 |
+
'temp_frames_not_found': 'temporary frames not found',
|
| 21 |
+
'copying_image': 'copying image with a resolution of {resolution}',
|
| 22 |
+
'copying_image_succeeded': 'copying image succeeded',
|
| 23 |
+
'copying_image_failed': 'copying image failed',
|
| 24 |
+
'finalizing_image': 'finalizing image with a resolution of {resolution}',
|
| 25 |
+
'finalizing_image_succeeded': 'finalizing image succeeded',
|
| 26 |
+
'finalizing_image_skipped': 'finalizing image skipped',
|
| 27 |
+
'merging_video': 'merging video with a resolution of {resolution} and {fps} frames per second',
|
| 28 |
+
'merging_video_succeeded': 'merging video succeeded',
|
| 29 |
+
'merging_video_failed': 'merging video failed',
|
| 30 |
+
'skipping_audio': 'skipping audio',
|
| 31 |
+
'replacing_audio_succeeded': 'replacing audio succeeded',
|
| 32 |
+
'replacing_audio_skipped': 'replacing audio skipped',
|
| 33 |
+
'restoring_audio_succeeded': 'restoring audio succeeded',
|
| 34 |
+
'restoring_audio_skipped': 'restoring audio skipped',
|
| 35 |
+
'clearing_temp': 'clearing temporary resources',
|
| 36 |
+
'processing_stopped': 'processing stopped',
|
| 37 |
+
'processing_image_succeeded': 'processing to image succeeded in {seconds} seconds',
|
| 38 |
+
'processing_image_failed': 'processing to image failed',
|
| 39 |
+
'processing_video_succeeded': 'processing to video succeeded in {seconds} seconds',
|
| 40 |
+
'processing_video_failed': 'processing to video failed',
|
| 41 |
+
'choose_image_source': 'choose an image for the source',
|
| 42 |
+
'choose_audio_source': 'choose an audio for the source',
|
| 43 |
+
'choose_video_target': 'choose a video for the target',
|
| 44 |
+
'choose_image_or_video_target': 'choose an image or video for the target',
|
| 45 |
+
'specify_image_or_video_output': 'specify the output image or video within a directory',
|
| 46 |
+
'match_target_and_output_extension': 'match the target and output extension',
|
| 47 |
+
'no_source_face_detected': 'no source face detected',
|
| 48 |
+
'processor_not_loaded': 'processor {processor} could not be loaded',
|
| 49 |
+
'processor_not_implemented': 'processor {processor} not implemented correctly',
|
| 50 |
+
'ui_layout_not_loaded': 'ui layout {ui_layout} could not be loaded',
|
| 51 |
+
'ui_layout_not_implemented': 'ui layout {ui_layout} not implemented correctly',
|
| 52 |
+
'stream_not_loaded': 'stream {stream_mode} could not be loaded',
|
| 53 |
+
'stream_not_supported': 'stream not supported',
|
| 54 |
+
'job_created': 'job {job_id} created',
|
| 55 |
+
'job_not_created': 'job {job_id} not created',
|
| 56 |
+
'job_submitted': 'job {job_id} submitted',
|
| 57 |
+
'job_not_submitted': 'job {job_id} not submitted',
|
| 58 |
+
'job_all_submitted': 'jobs submitted',
|
| 59 |
+
'job_all_not_submitted': 'jobs not submitted',
|
| 60 |
+
'job_deleted': 'job {job_id} deleted',
|
| 61 |
+
'job_not_deleted': 'job {job_id} not deleted',
|
| 62 |
+
'job_all_deleted': 'jobs deleted',
|
| 63 |
+
'job_all_not_deleted': 'jobs not deleted',
|
| 64 |
+
'job_step_added': 'step added to job {job_id}',
|
| 65 |
+
'job_step_not_added': 'step not added to job {job_id}',
|
| 66 |
+
'job_remix_step_added': 'step {step_index} remixed from job {job_id}',
|
| 67 |
+
'job_remix_step_not_added': 'step {step_index} not remixed from job {job_id}',
|
| 68 |
+
'job_step_inserted': 'step {step_index} inserted to job {job_id}',
|
| 69 |
+
'job_step_not_inserted': 'step {step_index} not inserted to job {job_id}',
|
| 70 |
+
'job_step_removed': 'step {step_index} removed from job {job_id}',
|
| 71 |
+
'job_step_not_removed': 'step {step_index} not removed from job {job_id}',
|
| 72 |
+
'running_job': 'running queued job {job_id}',
|
| 73 |
+
'running_jobs': 'running all queued jobs',
|
| 74 |
+
'retrying_job': 'retrying failed job {job_id}',
|
| 75 |
+
'retrying_jobs': 'retrying all failed jobs',
|
| 76 |
+
'processing_job_succeeded': 'processing of job {job_id} succeeded',
|
| 77 |
+
'processing_jobs_succeeded': 'processing of all jobs succeeded',
|
| 78 |
+
'processing_job_failed': 'processing of job {job_id} failed',
|
| 79 |
+
'processing_jobs_failed': 'processing of all jobs failed',
|
| 80 |
+
'processing_step': 'processing step {step_current} of {step_total}',
|
| 81 |
+
'validating_hash_succeeded': 'validating hash for {hash_file_name} succeeded',
|
| 82 |
+
'validating_hash_failed': 'validating hash for {hash_file_name} failed',
|
| 83 |
+
'validating_source_succeeded': 'validating source for {source_file_name} succeeded',
|
| 84 |
+
'validating_source_failed': 'validating source for {source_file_name} failed',
|
| 85 |
+
'deleting_corrupt_source': 'deleting corrupt source for {source_file_name}',
|
| 86 |
+
'loading_model_succeeded': 'loading model {model_name} succeeded in {seconds} seconds',
|
| 87 |
+
'loading_model_failed': 'loading model {model_name} failed',
|
| 88 |
+
'time_ago_now': 'just now',
|
| 89 |
+
'time_ago_minutes': '{minutes} minutes ago',
|
| 90 |
+
'time_ago_hours': '{hours} hours and {minutes} minutes ago',
|
| 91 |
+
'time_ago_days': '{days} days, {hours} hours and {minutes} minutes ago',
|
| 92 |
+
'point': '.',
|
| 93 |
+
'comma': ',',
|
| 94 |
+
'colon': ':',
|
| 95 |
+
'question_mark': '?',
|
| 96 |
+
'exclamation_mark': '!',
|
| 97 |
+
'help':
|
| 98 |
+
{
|
| 99 |
+
'install_dependency': 'choose the variant of {dependency} to install',
|
| 100 |
+
'skip_conda': 'skip the conda environment check',
|
| 101 |
+
'config_path': 'choose the config file to override defaults',
|
| 102 |
+
'temp_path': 'specify the directory for the temporary resources',
|
| 103 |
+
'jobs_path': 'specify the directory to store jobs',
|
| 104 |
+
'source_paths': 'choose the image or audio paths',
|
| 105 |
+
'target_path': 'choose the image or video path',
|
| 106 |
+
'output_path': 'specify the image or video within a directory',
|
| 107 |
+
'source_pattern': 'choose the image or audio pattern',
|
| 108 |
+
'target_pattern': 'choose the image or video pattern',
|
| 109 |
+
'output_pattern': 'specify the image or video pattern',
|
| 110 |
+
'face_detector_model': 'choose the model responsible for detecting the faces',
|
| 111 |
+
'face_detector_size': 'specify the frame size provided to the face detector',
|
| 112 |
+
'face_detector_margin': 'apply top, right, bottom and left margin to the frame',
|
| 113 |
+
'face_detector_angles': 'specify the angles to rotate the frame before detecting faces',
|
| 114 |
+
'face_detector_score': 'filter the detected faces based on the confidence score',
|
| 115 |
+
'face_landmarker_model': 'choose the model responsible for detecting the face landmarks',
|
| 116 |
+
'face_landmarker_score': 'filter the detected face landmarks based on the confidence score',
|
| 117 |
+
'face_selector_mode': 'use reference based tracking or simple matching',
|
| 118 |
+
'face_selector_order': 'specify the order of the detected faces',
|
| 119 |
+
'face_selector_age_start': 'filter the detected faces based on the starting age',
|
| 120 |
+
'face_selector_age_end': 'filter the detected faces based on the ending age',
|
| 121 |
+
'face_selector_gender': 'filter the detected faces based on their gender',
|
| 122 |
+
'face_selector_race': 'filter the detected faces based on their race',
|
| 123 |
+
'reference_face_position': 'specify the position used to create the reference face',
|
| 124 |
+
'reference_face_distance': 'specify the similarity between the reference face and target face',
|
| 125 |
+
'reference_frame_number': 'specify the frame used to create the reference face',
|
| 126 |
+
'face_tracker_score': 'specify the overlap score used to match the tracked faces',
|
| 127 |
+
'face_occluder_model': 'choose the model responsible for the occlusion mask',
|
| 128 |
+
'face_parser_model': 'choose the model responsible for the region mask',
|
| 129 |
+
'face_mask_types': 'mix and match different face mask types (choices: {choices})',
|
| 130 |
+
'face_mask_areas': 'choose the items used for the area mask (choices: {choices})',
|
| 131 |
+
'face_mask_regions': 'choose the items used for the region mask (choices: {choices})',
|
| 132 |
+
'face_mask_blur': 'specify the degree of blur applied to the box mask',
|
| 133 |
+
'face_mask_padding': 'apply top, right, bottom and left padding to the box mask',
|
| 134 |
+
'voice_extractor_model': 'choose the model responsible for extracting the voices',
|
| 135 |
+
'trim_frame_start': 'specify the starting frame of the target video',
|
| 136 |
+
'trim_frame_end': 'specify the ending frame of the target video',
|
| 137 |
+
'temp_frame_format': 'specify the temporary frame format',
|
| 138 |
+
'temp_pixel_format': 'specify the temporary pixel format',
|
| 139 |
+
'target_frame_amount': 'specify the amount of target frames forwarded to the processor',
|
| 140 |
+
'output_image_quality': 'specify the image quality which translates to the image compression',
|
| 141 |
+
'output_image_scale': 'specify the image scale based on the target image',
|
| 142 |
+
'output_audio_encoder': 'specify the encoder used for the audio',
|
| 143 |
+
'output_audio_quality': 'specify the audio quality which translates to the audio compression',
|
| 144 |
+
'output_audio_volume': 'specify the audio volume based on the target video',
|
| 145 |
+
'output_video_encoder': 'specify the encoder used for the video',
|
| 146 |
+
'output_video_preset': 'balance fast video processing and video file size',
|
| 147 |
+
'output_video_quality': 'specify the video quality which translates to the video compression',
|
| 148 |
+
'output_video_scale': 'specify the video scale based on the target video',
|
| 149 |
+
'output_video_fps': 'specify the video fps based on the target video',
|
| 150 |
+
'workflow_mode': 'detect or enforce the workflow mode',
|
| 151 |
+
'workflow_strategy': 'process the temporary frames in memory or on disk',
|
| 152 |
+
'processors': 'load a single or multiple processors (choices: {choices}, ...)',
|
| 153 |
+
'background-remover-model': 'choose the model responsible for removing the background',
|
| 154 |
+
'background-remover-color': 'apply red, green blue and alpha values of the background',
|
| 155 |
+
'open_browser': 'open the browser once the program is ready',
|
| 156 |
+
'ui_layouts': 'launch a single or multiple UI layouts (choices: {choices}, ...)',
|
| 157 |
+
'ui_workflow': 'choose the ui workflow',
|
| 158 |
+
'download_providers': 'download using different providers (choices: {choices}, ...)',
|
| 159 |
+
'download_scope': 'specify the download scope',
|
| 160 |
+
'benchmark_mode': 'choose the benchmark mode',
|
| 161 |
+
'benchmark_resolutions': 'choose the resolutions for the benchmarks (choices: {choices}, ...)',
|
| 162 |
+
'benchmark_cycle_count': 'specify the amount of cycles per benchmark',
|
| 163 |
+
'execution_device_ids': 'specify the devices used for processing',
|
| 164 |
+
'execution_providers': 'inference using different providers (choices: {choices}, ...)',
|
| 165 |
+
'execution_thread_count': 'specify the amount of parallel threads while processing',
|
| 166 |
+
'video_memory_strategy': 'balance fast processing and low VRAM usage',
|
| 167 |
+
'log_level': 'adjust the message severity displayed in the terminal',
|
| 168 |
+
'halt_on_error': 'halt the program once an error occurred',
|
| 169 |
+
'run': 'run the program',
|
| 170 |
+
'headless_run': 'run the program in headless mode',
|
| 171 |
+
'batch_run': 'run the program in batch mode',
|
| 172 |
+
'force_download': 'force automate downloads and exit',
|
| 173 |
+
'benchmark': 'benchmark the program',
|
| 174 |
+
'job_id': 'specify the job id',
|
| 175 |
+
'job_status': 'specify the job status',
|
| 176 |
+
'step_index': 'specify the step index',
|
| 177 |
+
'job_list': 'list jobs by status',
|
| 178 |
+
'job_create': 'create a drafted job',
|
| 179 |
+
'job_submit': 'submit a drafted job to become a queued job',
|
| 180 |
+
'job_submit_all': 'submit all drafted jobs to become a queued jobs',
|
| 181 |
+
'job_delete': 'delete a drafted, queued, failed or completed job',
|
| 182 |
+
'job_delete_all': 'delete all drafted, queued, failed and completed jobs',
|
| 183 |
+
'job_add_step': 'add a step to a drafted job',
|
| 184 |
+
'job_remix_step': 'remix a previous step from a drafted job',
|
| 185 |
+
'job_insert_step': 'insert a step to a drafted job',
|
| 186 |
+
'job_remove_step': 'remove a step from a drafted job',
|
| 187 |
+
'job_run': 'run a queued job',
|
| 188 |
+
'job_run_all': 'run all queued jobs',
|
| 189 |
+
'job_retry': 'retry a failed job',
|
| 190 |
+
'job_retry_all': 'retry all failed jobs'
|
| 191 |
+
},
|
| 192 |
+
'about':
|
| 193 |
+
{
|
| 194 |
+
'fund': 'fund ai workstation',
|
| 195 |
+
'subscribe': 'become a member',
|
| 196 |
+
'join': 'join our community'
|
| 197 |
+
},
|
| 198 |
+
'uis':
|
| 199 |
+
{
|
| 200 |
+
'apply_button': 'APPLY',
|
| 201 |
+
'benchmark_mode_dropdown': 'BENCHMARK MODE',
|
| 202 |
+
'benchmark_cycle_count_slider': 'BENCHMARK CYCLE COUNT',
|
| 203 |
+
'benchmark_resolutions_checkbox_group': 'BENCHMARK RESOLUTIONS',
|
| 204 |
+
'clear_button': 'CLEAR',
|
| 205 |
+
'download_providers_checkbox_group': 'DOWNLOAD PROVIDERS',
|
| 206 |
+
'execution_providers_checkbox_group': 'EXECUTION PROVIDERS',
|
| 207 |
+
'workflow_strategy_dropdown': 'WORKFLOW STRATEGY',
|
| 208 |
+
'execution_thread_count_slider': 'EXECUTION THREAD COUNT',
|
| 209 |
+
'face_detector_angles_checkbox_group': 'FACE DETECTOR ANGLES',
|
| 210 |
+
'face_detector_model_dropdown': 'FACE DETECTOR MODEL',
|
| 211 |
+
'face_detector_margin_slider': 'FACE DETECTOR MARGIN',
|
| 212 |
+
'face_detector_score_slider': 'FACE DETECTOR SCORE',
|
| 213 |
+
'face_detector_size_dropdown': 'FACE DETECTOR SIZE',
|
| 214 |
+
'face_landmarker_model_dropdown': 'FACE LANDMARKER MODEL',
|
| 215 |
+
'face_landmarker_score_slider': 'FACE LANDMARKER SCORE',
|
| 216 |
+
'face_mask_blur_slider': 'FACE MASK BLUR',
|
| 217 |
+
'face_mask_padding_bottom_slider': 'FACE MASK PADDING BOTTOM',
|
| 218 |
+
'face_mask_padding_left_slider': 'FACE MASK PADDING LEFT',
|
| 219 |
+
'face_mask_padding_right_slider': 'FACE MASK PADDING RIGHT',
|
| 220 |
+
'face_mask_padding_top_slider': 'FACE MASK PADDING TOP',
|
| 221 |
+
'face_mask_areas_checkbox_group': 'FACE MASK AREAS',
|
| 222 |
+
'face_mask_regions_checkbox_group': 'FACE MASK REGIONS',
|
| 223 |
+
'face_mask_types_checkbox_group': 'FACE MASK TYPES',
|
| 224 |
+
'face_selector_age_range_slider': 'FACE SELECTOR AGE',
|
| 225 |
+
'face_selector_gender_dropdown': 'FACE SELECTOR GENDER',
|
| 226 |
+
'face_selector_mode_dropdown': 'FACE SELECTOR MODE',
|
| 227 |
+
'face_selector_order_dropdown': 'FACE SELECTOR ORDER',
|
| 228 |
+
'face_selector_race_dropdown': 'FACE SELECTOR RACE',
|
| 229 |
+
'face_tracker_score_slider': 'FACE TRACKER SCORE',
|
| 230 |
+
'face_occluder_model_dropdown': 'FACE OCCLUDER MODEL',
|
| 231 |
+
'face_parser_model_dropdown': 'FACE PARSER MODEL',
|
| 232 |
+
'voice_extractor_model_dropdown': 'VOICE EXTRACTOR MODEL',
|
| 233 |
+
'job_list_status_checkbox_group': 'JOB STATUS',
|
| 234 |
+
'job_manager_job_action_dropdown': 'JOB_ACTION',
|
| 235 |
+
'job_manager_job_id_dropdown': 'JOB ID',
|
| 236 |
+
'job_manager_step_index_dropdown': 'STEP INDEX',
|
| 237 |
+
'job_runner_job_action_dropdown': 'JOB ACTION',
|
| 238 |
+
'job_runner_job_id_dropdown': 'JOB ID',
|
| 239 |
+
'log_level_dropdown': 'LOG LEVEL',
|
| 240 |
+
'output_audio_encoder_dropdown': 'OUTPUT AUDIO ENCODER',
|
| 241 |
+
'output_audio_quality_slider': 'OUTPUT AUDIO QUALITY',
|
| 242 |
+
'output_audio_volume_slider': 'OUTPUT AUDIO VOLUME',
|
| 243 |
+
'output_image_or_video': 'OUTPUT',
|
| 244 |
+
'output_image_quality_slider': 'OUTPUT IMAGE QUALITY',
|
| 245 |
+
'output_image_scale_slider': 'OUTPUT IMAGE SCALE',
|
| 246 |
+
'output_path_textbox': 'OUTPUT PATH',
|
| 247 |
+
'output_video_encoder_dropdown': 'OUTPUT VIDEO ENCODER',
|
| 248 |
+
'output_video_fps_slider': 'OUTPUT VIDEO FPS',
|
| 249 |
+
'output_video_preset_dropdown': 'OUTPUT VIDEO PRESET',
|
| 250 |
+
'output_video_quality_slider': 'OUTPUT VIDEO QUALITY',
|
| 251 |
+
'output_video_scale_slider': 'OUTPUT VIDEO SCALE',
|
| 252 |
+
'preview_frame_slider': 'PREVIEW FRAME',
|
| 253 |
+
'preview_image': 'PREVIEW',
|
| 254 |
+
'preview_mode_dropdown': 'PREVIEW MODE',
|
| 255 |
+
'preview_resolution_dropdown': 'PREVIEW RESOLUTION',
|
| 256 |
+
'processors_checkbox_group': 'PROCESSORS',
|
| 257 |
+
'reference_face_distance_slider': 'REFERENCE FACE DISTANCE',
|
| 258 |
+
'reference_face_gallery': 'REFERENCE FACE',
|
| 259 |
+
'refresh_button': 'REFRESH',
|
| 260 |
+
'source_file': 'SOURCE',
|
| 261 |
+
'start_button': 'START',
|
| 262 |
+
'stop_button': 'STOP',
|
| 263 |
+
'target_file': 'TARGET',
|
| 264 |
+
'temp_frame_format_dropdown': 'TEMP FRAME FORMAT',
|
| 265 |
+
'terminal_textbox': 'TERMINAL',
|
| 266 |
+
'trim_frame_slider': 'TRIM FRAME',
|
| 267 |
+
'ui_workflow': 'UI WORKFLOW',
|
| 268 |
+
'video_memory_strategy_dropdown': 'VIDEO MEMORY STRATEGY',
|
| 269 |
+
'webcam_fps_slider': 'WEBCAM FPS',
|
| 270 |
+
'webcam_image': 'WEBCAM',
|
| 271 |
+
'webcam_device_id_dropdown': 'WEBCAM DEVICE ID',
|
| 272 |
+
'webcam_mode_radio': 'WEBCAM MODE',
|
| 273 |
+
'webcam_resolution_dropdown': 'WEBCAM RESOLUTION'
|
| 274 |
+
}
|
| 275 |
+
}
|
| 276 |
+
}
|
logger.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from logging import Logger, basicConfig, getLogger
|
| 2 |
+
|
| 3 |
+
import facefusion.choices
|
| 4 |
+
from facefusion.common_helper import get_first, get_last
|
| 5 |
+
from facefusion.types import LogLevel
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def init(log_level : LogLevel) -> None:
|
| 9 |
+
basicConfig(format = '%(message)s')
|
| 10 |
+
get_package_logger().setLevel(facefusion.choices.log_level_set.get(log_level))
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def get_package_logger() -> Logger:
|
| 14 |
+
return getLogger('facefusion')
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def debug(message : str, module_name : str) -> None:
|
| 18 |
+
get_package_logger().debug(create_message(message, module_name))
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def info(message : str, module_name : str) -> None:
|
| 22 |
+
get_package_logger().info(create_message(message, module_name))
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def warn(message : str, module_name : str) -> None:
|
| 26 |
+
get_package_logger().warning(create_message(message, module_name))
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def error(message : str, module_name : str) -> None:
|
| 30 |
+
get_package_logger().error(create_message(message, module_name))
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def create_message(message : str, module_name : str) -> str:
|
| 34 |
+
module_names = module_name.split('.')
|
| 35 |
+
first_module_name = get_first(module_names)
|
| 36 |
+
last_module_name = get_last(module_names)
|
| 37 |
+
|
| 38 |
+
if first_module_name and last_module_name:
|
| 39 |
+
return '[' + first_module_name.upper() + '.' + last_module_name.upper() + '] ' + message
|
| 40 |
+
return message
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def enable() -> None:
|
| 44 |
+
get_package_logger().disabled = False
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def disable() -> None:
|
| 48 |
+
get_package_logger().disabled = True
|
metadata.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
|
| 3 |
+
METADATA =\
|
| 4 |
+
{
|
| 5 |
+
'name': 'FaceFusion',
|
| 6 |
+
'description': 'Industry leading face manipulation platform',
|
| 7 |
+
'version': '3.8.0',
|
| 8 |
+
'license': 'OpenRAIL-AS',
|
| 9 |
+
'author': 'Henry Ruhs',
|
| 10 |
+
'url': 'https://facefusion.io'
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def get(key : str) -> Optional[str]:
|
| 15 |
+
return METADATA.get(key)
|
model_helper.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
|
| 3 |
+
import onnx
|
| 4 |
+
|
| 5 |
+
from facefusion.types import ModelInitializer
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@lru_cache()
|
| 9 |
+
def get_static_model_initializer(model_path : str) -> ModelInitializer:
|
| 10 |
+
model = onnx.load(model_path)
|
| 11 |
+
return onnx.numpy_helper.to_array(model.graph.initializer[-1])
|
normalizer.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Optional
|
| 2 |
+
|
| 3 |
+
from facefusion.types import Color, Fps, Padding
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def normalize_color(channels : Optional[List[int]]) -> Optional[Color]:
|
| 7 |
+
if channels and len(channels) == 1:
|
| 8 |
+
return tuple([ channels[0], channels[0], channels[0], 255 ]) #type:ignore[return-value]
|
| 9 |
+
if channels and len(channels) == 2:
|
| 10 |
+
return tuple([ channels[0], channels[1], channels[0], 255 ]) #type:ignore[return-value]
|
| 11 |
+
if channels and len(channels) == 3:
|
| 12 |
+
return tuple([ channels[0], channels[1], channels[2], 255 ]) #type:ignore[return-value]
|
| 13 |
+
if channels and len(channels) == 4:
|
| 14 |
+
return tuple(channels) #type:ignore[return-value]
|
| 15 |
+
return None
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def normalize_space(spaces : Optional[List[int]]) -> Optional[Padding]:
|
| 19 |
+
if spaces and len(spaces) == 1:
|
| 20 |
+
return tuple([spaces[0]] * 4) #type:ignore[return-value]
|
| 21 |
+
if spaces and len(spaces) == 2:
|
| 22 |
+
return tuple([ spaces[0], spaces[1], spaces[0], spaces[1] ]) #type:ignore[return-value]
|
| 23 |
+
if spaces and len(spaces) == 3:
|
| 24 |
+
return tuple([ spaces[0], spaces[1], spaces[2], spaces[1] ]) #type:ignore[return-value]
|
| 25 |
+
if spaces and len(spaces) == 4:
|
| 26 |
+
return tuple(spaces) #type:ignore[return-value]
|
| 27 |
+
return None
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def normalize_fps(fps : Optional[float]) -> Optional[Fps]:
|
| 31 |
+
if isinstance(fps, (int, float)):
|
| 32 |
+
return max(1.0, min(fps, 60.0))
|
| 33 |
+
return None
|
process_manager.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from facefusion.types import ProcessState
|
| 2 |
+
|
| 3 |
+
PROCESS_STATE : ProcessState = 'pending'
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def get_process_state() -> ProcessState:
|
| 7 |
+
return PROCESS_STATE
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def set_process_state(process_state : ProcessState) -> None:
|
| 11 |
+
global PROCESS_STATE
|
| 12 |
+
|
| 13 |
+
PROCESS_STATE = process_state
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def is_checking() -> bool:
|
| 17 |
+
return get_process_state() == 'checking'
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def is_processing() -> bool:
|
| 21 |
+
return get_process_state() == 'processing'
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def is_stopping() -> bool:
|
| 25 |
+
return get_process_state() == 'stopping'
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def is_pending() -> bool:
|
| 29 |
+
return get_process_state() == 'pending'
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def check() -> None:
|
| 33 |
+
set_process_state('checking')
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def start() -> None:
|
| 37 |
+
set_process_state('processing')
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def stop() -> None:
|
| 41 |
+
set_process_state('stopping')
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def end() -> None:
|
| 45 |
+
set_process_state('pending')
|
program.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tempfile
|
| 2 |
+
from argparse import ArgumentParser, HelpFormatter
|
| 3 |
+
from functools import partial
|
| 4 |
+
|
| 5 |
+
import facefusion.choices
|
| 6 |
+
from facefusion import config, metadata, state_manager, translator
|
| 7 |
+
from facefusion.common_helper import create_float_metavar, create_int_metavar, get_first, get_last
|
| 8 |
+
from facefusion.execution import get_available_execution_providers
|
| 9 |
+
from facefusion.ffmpeg import get_available_encoder_set
|
| 10 |
+
from facefusion.filesystem import get_file_name, resolve_file_paths
|
| 11 |
+
from facefusion.jobs import job_store
|
| 12 |
+
from facefusion.processors.core import get_processors_modules
|
| 13 |
+
from facefusion.sanitizer import sanitize_int_range, sanitize_job_id
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def create_help_formatter_small(prog : str) -> HelpFormatter:
|
| 17 |
+
return HelpFormatter(prog, max_help_position = 50)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def create_help_formatter_large(prog : str) -> HelpFormatter:
|
| 21 |
+
return HelpFormatter(prog, max_help_position = 300)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def create_config_path_program() -> ArgumentParser:
|
| 25 |
+
program = ArgumentParser(add_help = False)
|
| 26 |
+
group_paths = program.add_argument_group('paths')
|
| 27 |
+
group_paths.add_argument('--config-path', help = translator.get('help.config_path'), default = 'facefusion.ini')
|
| 28 |
+
job_store.register_job_keys([ 'config_path' ])
|
| 29 |
+
apply_config_path(program)
|
| 30 |
+
return program
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def create_temp_path_program() -> ArgumentParser:
|
| 34 |
+
program = ArgumentParser(add_help = False)
|
| 35 |
+
group_paths = program.add_argument_group('paths')
|
| 36 |
+
group_paths.add_argument('--temp-path', help = translator.get('help.temp_path'), default = config.get_str_value('paths', 'temp_path', tempfile.gettempdir()))
|
| 37 |
+
job_store.register_job_keys([ 'temp_path' ])
|
| 38 |
+
return program
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def create_jobs_path_program() -> ArgumentParser:
|
| 42 |
+
program = ArgumentParser(add_help = False)
|
| 43 |
+
group_paths = program.add_argument_group('paths')
|
| 44 |
+
group_paths.add_argument('--jobs-path', help = translator.get('help.jobs_path'), default = config.get_str_value('paths', 'jobs_path', '.jobs'))
|
| 45 |
+
job_store.register_job_keys([ 'jobs_path' ])
|
| 46 |
+
return program
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def create_source_paths_program() -> ArgumentParser:
|
| 50 |
+
program = ArgumentParser(add_help = False)
|
| 51 |
+
group_paths = program.add_argument_group('paths')
|
| 52 |
+
group_paths.add_argument('-s', '--source-paths', help = translator.get('help.source_paths'), default = config.get_str_list('paths', 'source_paths'), nargs = '+')
|
| 53 |
+
job_store.register_step_keys([ 'source_paths' ])
|
| 54 |
+
return program
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def create_target_path_program() -> ArgumentParser:
|
| 58 |
+
program = ArgumentParser(add_help = False)
|
| 59 |
+
group_paths = program.add_argument_group('paths')
|
| 60 |
+
group_paths.add_argument('-t', '--target-path', help = translator.get('help.target_path'), default = config.get_str_value('paths', 'target_path'))
|
| 61 |
+
job_store.register_step_keys([ 'target_path' ])
|
| 62 |
+
return program
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def create_output_path_program() -> ArgumentParser:
|
| 66 |
+
program = ArgumentParser(add_help = False)
|
| 67 |
+
group_paths = program.add_argument_group('paths')
|
| 68 |
+
group_paths.add_argument('-o', '--output-path', help = translator.get('help.output_path'), default = config.get_str_value('paths', 'output_path'))
|
| 69 |
+
job_store.register_step_keys([ 'output_path' ])
|
| 70 |
+
return program
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def create_source_pattern_program() -> ArgumentParser:
|
| 74 |
+
program = ArgumentParser(add_help = False)
|
| 75 |
+
group_patterns = program.add_argument_group('patterns')
|
| 76 |
+
group_patterns.add_argument('-s', '--source-pattern', help = translator.get('help.source_pattern'), default = config.get_str_value('patterns', 'source_pattern'))
|
| 77 |
+
job_store.register_job_keys([ 'source_pattern' ])
|
| 78 |
+
return program
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def create_target_pattern_program() -> ArgumentParser:
|
| 82 |
+
program = ArgumentParser(add_help = False)
|
| 83 |
+
group_patterns = program.add_argument_group('patterns')
|
| 84 |
+
group_patterns.add_argument('-t', '--target-pattern', help = translator.get('help.target_pattern'), default = config.get_str_value('patterns', 'target_pattern'))
|
| 85 |
+
job_store.register_job_keys([ 'target_pattern' ])
|
| 86 |
+
return program
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def create_output_pattern_program() -> ArgumentParser:
|
| 90 |
+
program = ArgumentParser(add_help = False)
|
| 91 |
+
group_patterns = program.add_argument_group('patterns')
|
| 92 |
+
group_patterns.add_argument('-o', '--output-pattern', help = translator.get('help.output_pattern'), default = config.get_str_value('patterns', 'output_pattern'))
|
| 93 |
+
job_store.register_job_keys([ 'output_pattern' ])
|
| 94 |
+
return program
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def create_face_detector_program() -> ArgumentParser:
|
| 98 |
+
program = ArgumentParser(add_help = False)
|
| 99 |
+
group_face_detector = program.add_argument_group('face detector')
|
| 100 |
+
group_face_detector.add_argument('--face-detector-model', help = translator.get('help.face_detector_model'), default = config.get_str_value('face_detector', 'face_detector_model', 'yolo_face'), choices = facefusion.choices.face_detector_models)
|
| 101 |
+
known_args, _ = program.parse_known_args()
|
| 102 |
+
face_detector_size_choices = facefusion.choices.face_detector_set.get(known_args.face_detector_model)
|
| 103 |
+
group_face_detector.add_argument('--face-detector-size', help = translator.get('help.face_detector_size'), default = config.get_str_value('face_detector', 'face_detector_size', get_last(face_detector_size_choices)), choices = face_detector_size_choices)
|
| 104 |
+
group_face_detector.add_argument('--face-detector-margin', help = translator.get('help.face_detector_margin'), type = partial(sanitize_int_range, int_range = facefusion.choices.face_detector_margin_range), default = config.get_int_list('face_detector', 'face_detector_margin', '0 0 0 0'), nargs = '+')
|
| 105 |
+
group_face_detector.add_argument('--face-detector-angles', help = translator.get('help.face_detector_angles'), type = int, default = config.get_int_list('face_detector', 'face_detector_angles', '0'), choices = facefusion.choices.face_detector_angles, nargs = '+', metavar = 'FACE_DETECTOR_ANGLES')
|
| 106 |
+
group_face_detector.add_argument('--face-detector-score', help = translator.get('help.face_detector_score'), type = float, default = config.get_float_value('face_detector', 'face_detector_score', '0.5'), choices = facefusion.choices.face_detector_score_range, metavar = create_float_metavar(facefusion.choices.face_detector_score_range))
|
| 107 |
+
job_store.register_step_keys([ 'face_detector_model', 'face_detector_size', 'face_detector_margin', 'face_detector_angles', 'face_detector_score' ])
|
| 108 |
+
return program
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def create_face_landmarker_program() -> ArgumentParser:
|
| 112 |
+
program = ArgumentParser(add_help = False)
|
| 113 |
+
group_face_landmarker = program.add_argument_group('face landmarker')
|
| 114 |
+
group_face_landmarker.add_argument('--face-landmarker-model', help = translator.get('help.face_landmarker_model'), default = config.get_str_value('face_landmarker', 'face_landmarker_model', '2dfan4'), choices = facefusion.choices.face_landmarker_models)
|
| 115 |
+
group_face_landmarker.add_argument('--face-landmarker-score', help = translator.get('help.face_landmarker_score'), type = float, default = config.get_float_value('face_landmarker', 'face_landmarker_score', '0.5'), choices = facefusion.choices.face_landmarker_score_range, metavar = create_float_metavar(facefusion.choices.face_landmarker_score_range))
|
| 116 |
+
job_store.register_step_keys([ 'face_landmarker_model', 'face_landmarker_score' ])
|
| 117 |
+
return program
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def create_face_selector_program() -> ArgumentParser:
|
| 121 |
+
program = ArgumentParser(add_help = False)
|
| 122 |
+
group_face_selector = program.add_argument_group('face selector')
|
| 123 |
+
group_face_selector.add_argument('--face-selector-mode', help = translator.get('help.face_selector_mode'), default = config.get_str_value('face_selector', 'face_selector_mode', 'reference'), choices = facefusion.choices.face_selector_modes)
|
| 124 |
+
group_face_selector.add_argument('--face-selector-order', help = translator.get('help.face_selector_order'), default = config.get_str_value('face_selector', 'face_selector_order', 'large-small'), choices = facefusion.choices.face_selector_orders)
|
| 125 |
+
group_face_selector.add_argument('--face-selector-age-start', help = translator.get('help.face_selector_age_start'), type = int, default = config.get_int_value('face_selector', 'face_selector_age_start'), choices = facefusion.choices.face_selector_age_range, metavar = create_int_metavar(facefusion.choices.face_selector_age_range))
|
| 126 |
+
group_face_selector.add_argument('--face-selector-age-end', help = translator.get('help.face_selector_age_end'), type = int, default = config.get_int_value('face_selector', 'face_selector_age_end'), choices = facefusion.choices.face_selector_age_range, metavar = create_int_metavar(facefusion.choices.face_selector_age_range))
|
| 127 |
+
group_face_selector.add_argument('--face-selector-gender', help = translator.get('help.face_selector_gender'), default = config.get_str_value('face_selector', 'face_selector_gender'), choices = facefusion.choices.face_selector_genders)
|
| 128 |
+
group_face_selector.add_argument('--face-selector-race', help = translator.get('help.face_selector_race'), default = config.get_str_value('face_selector', 'face_selector_race'), choices = facefusion.choices.face_selector_races)
|
| 129 |
+
group_face_selector.add_argument('--reference-face-position', help = translator.get('help.reference_face_position'), type = int, default = config.get_int_value('face_selector', 'reference_face_position', '0'))
|
| 130 |
+
group_face_selector.add_argument('--reference-face-distance', help = translator.get('help.reference_face_distance'), type = float, default = config.get_float_value('face_selector', 'reference_face_distance', '0.3'), choices = facefusion.choices.reference_face_distance_range, metavar = create_float_metavar(facefusion.choices.reference_face_distance_range))
|
| 131 |
+
group_face_selector.add_argument('--reference-frame-number', help = translator.get('help.reference_frame_number'), type = int, default = config.get_int_value('face_selector', 'reference_frame_number', '0'))
|
| 132 |
+
job_store.register_step_keys([ 'face_selector_mode', 'face_selector_order', 'face_selector_gender', 'face_selector_race', 'face_selector_age_start', 'face_selector_age_end', 'reference_face_position', 'reference_face_distance', 'reference_frame_number' ])
|
| 133 |
+
return program
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def create_face_tracker_program() -> ArgumentParser:
|
| 137 |
+
program = ArgumentParser(add_help = False)
|
| 138 |
+
group_face_tracker = program.add_argument_group('face tracker')
|
| 139 |
+
group_face_tracker.add_argument('--face-tracker-score', help = translator.get('help.face_tracker_score'), type = float, default = config.get_float_value('face_tracker', 'face_tracker_score', '0.0'), choices = facefusion.choices.face_tracker_score_range, metavar = create_float_metavar(facefusion.choices.face_tracker_score_range))
|
| 140 |
+
job_store.register_step_keys([ 'face_tracker_score' ])
|
| 141 |
+
return program
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def create_face_masker_program() -> ArgumentParser:
|
| 145 |
+
program = ArgumentParser(add_help = False)
|
| 146 |
+
group_face_masker = program.add_argument_group('face masker')
|
| 147 |
+
group_face_masker.add_argument('--face-occluder-model', help = translator.get('help.face_occluder_model'), default = config.get_str_value('face_masker', 'face_occluder_model', 'xseg_1'), choices = facefusion.choices.face_occluder_models)
|
| 148 |
+
group_face_masker.add_argument('--face-parser-model', help = translator.get('help.face_parser_model'), default = config.get_str_value('face_masker', 'face_parser_model', 'bisenet_resnet_34'), choices = facefusion.choices.face_parser_models)
|
| 149 |
+
group_face_masker.add_argument('--face-mask-types', help = translator.get('help.face_mask_types').format(choices = ', '.join(facefusion.choices.face_mask_types)), default = config.get_str_list('face_masker', 'face_mask_types', 'box'), choices = facefusion.choices.face_mask_types, nargs = '+', metavar = 'FACE_MASK_TYPES')
|
| 150 |
+
group_face_masker.add_argument('--face-mask-areas', help = translator.get('help.face_mask_areas').format(choices = ', '.join(facefusion.choices.face_mask_areas)), default = config.get_str_list('face_masker', 'face_mask_areas', ' '.join(facefusion.choices.face_mask_areas)), choices = facefusion.choices.face_mask_areas, nargs = '+', metavar = 'FACE_MASK_AREAS')
|
| 151 |
+
group_face_masker.add_argument('--face-mask-regions', help = translator.get('help.face_mask_regions').format(choices = ', '.join(facefusion.choices.face_mask_regions)), default = config.get_str_list('face_masker', 'face_mask_regions', ' '.join(facefusion.choices.face_mask_regions)), choices = facefusion.choices.face_mask_regions, nargs = '+', metavar = 'FACE_MASK_REGIONS')
|
| 152 |
+
group_face_masker.add_argument('--face-mask-blur', help = translator.get('help.face_mask_blur'), type = float, default = config.get_float_value('face_masker', 'face_mask_blur', '0.3'), choices = facefusion.choices.face_mask_blur_range, metavar = create_float_metavar(facefusion.choices.face_mask_blur_range))
|
| 153 |
+
group_face_masker.add_argument('--face-mask-padding', help = translator.get('help.face_mask_padding'), type = partial(sanitize_int_range, int_range = facefusion.choices.face_mask_padding_range), default = config.get_int_list('face_masker', 'face_mask_padding', '0 0 0 0'), nargs = '+')
|
| 154 |
+
job_store.register_step_keys([ 'face_occluder_model', 'face_parser_model', 'face_mask_types', 'face_mask_areas', 'face_mask_regions', 'face_mask_blur', 'face_mask_padding' ])
|
| 155 |
+
return program
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def create_voice_extractor_program() -> ArgumentParser:
|
| 159 |
+
program = ArgumentParser(add_help = False)
|
| 160 |
+
group_voice_extractor = program.add_argument_group('voice extractor')
|
| 161 |
+
group_voice_extractor.add_argument('--voice-extractor-model', help = translator.get('help.voice_extractor_model'), default = config.get_str_value('voice_extractor', 'voice_extractor_model', 'kim_vocal_2'), choices = facefusion.choices.voice_extractor_models)
|
| 162 |
+
job_store.register_step_keys([ 'voice_extractor_model' ])
|
| 163 |
+
return program
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def create_frame_extraction_program() -> ArgumentParser:
|
| 167 |
+
program = ArgumentParser(add_help = False)
|
| 168 |
+
group_frame_extraction = program.add_argument_group('frame extraction')
|
| 169 |
+
group_frame_extraction.add_argument('--trim-frame-start', help = translator.get('help.trim_frame_start'), type = int, default = facefusion.config.get_int_value('frame_extraction', 'trim_frame_start'))
|
| 170 |
+
group_frame_extraction.add_argument('--trim-frame-end', help = translator.get('help.trim_frame_end'), type = int, default = facefusion.config.get_int_value('frame_extraction', 'trim_frame_end'))
|
| 171 |
+
group_frame_extraction.add_argument('--temp-frame-format', help = translator.get('help.temp_frame_format'), default = config.get_str_value('frame_extraction', 'temp_frame_format', 'png'), choices = facefusion.choices.temp_frame_formats)
|
| 172 |
+
group_frame_extraction.add_argument('--temp-pixel-format', help = translator.get('help.temp_pixel_format'), default = config.get_str_value('frame_extraction', 'temp_pixel_format', 'bgr24'), choices = facefusion.choices.temp_pixel_formats)
|
| 173 |
+
job_store.register_step_keys([ 'trim_frame_start', 'trim_frame_end', 'temp_frame_format', 'temp_pixel_format' ])
|
| 174 |
+
return program
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def create_frame_distribution_program() -> ArgumentParser:
|
| 178 |
+
program = ArgumentParser(add_help = False)
|
| 179 |
+
group_frame_distribution = program.add_argument_group('frame distribution')
|
| 180 |
+
group_frame_distribution.add_argument('--target-frame-amount', help = translator.get('help.target_frame_amount'), type = int, default = config.get_int_value('frame_distribution', 'target_frame_amount', '2'), choices = facefusion.choices.target_frame_amount_range, metavar = create_int_metavar(facefusion.choices.target_frame_amount_range))
|
| 181 |
+
job_store.register_step_keys([ 'target_frame_amount' ])
|
| 182 |
+
return program
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def create_output_creation_program() -> ArgumentParser:
|
| 186 |
+
program = ArgumentParser(add_help = False)
|
| 187 |
+
available_encoder_set = get_available_encoder_set()
|
| 188 |
+
group_output_creation = program.add_argument_group('output creation')
|
| 189 |
+
group_output_creation.add_argument('--output-image-quality', help = translator.get('help.output_image_quality'), type = int, default = config.get_int_value('output_creation', 'output_image_quality', '80'), choices = facefusion.choices.output_image_quality_range, metavar = create_int_metavar(facefusion.choices.output_image_quality_range))
|
| 190 |
+
group_output_creation.add_argument('--output-image-scale', help = translator.get('help.output_image_scale'), type = float, default = config.get_float_value('output_creation', 'output_image_scale', '1.0'), choices = facefusion.choices.output_image_scale_range)
|
| 191 |
+
group_output_creation.add_argument('--output-audio-encoder', help = translator.get('help.output_audio_encoder'), default = config.get_str_value('output_creation', 'output_audio_encoder', get_first(available_encoder_set.get('audio'))), choices = available_encoder_set.get('audio'))
|
| 192 |
+
group_output_creation.add_argument('--output-audio-quality', help = translator.get('help.output_audio_quality'), type = int, default = config.get_int_value('output_creation', 'output_audio_quality', '80'), choices = facefusion.choices.output_audio_quality_range, metavar = create_int_metavar(facefusion.choices.output_audio_quality_range))
|
| 193 |
+
group_output_creation.add_argument('--output-audio-volume', help = translator.get('help.output_audio_volume'), type = int, default = config.get_int_value('output_creation', 'output_audio_volume', '100'), choices = facefusion.choices.output_audio_volume_range, metavar = create_int_metavar(facefusion.choices.output_audio_volume_range))
|
| 194 |
+
group_output_creation.add_argument('--output-video-encoder', help = translator.get('help.output_video_encoder'), default = config.get_str_value('output_creation', 'output_video_encoder', get_first(available_encoder_set.get('video'))), choices = available_encoder_set.get('video'))
|
| 195 |
+
group_output_creation.add_argument('--output-video-preset', help = translator.get('help.output_video_preset'), default = config.get_str_value('output_creation', 'output_video_preset', 'veryfast'), choices = facefusion.choices.output_video_presets)
|
| 196 |
+
group_output_creation.add_argument('--output-video-quality', help = translator.get('help.output_video_quality'), type = int, default = config.get_int_value('output_creation', 'output_video_quality', '80'), choices = facefusion.choices.output_video_quality_range, metavar = create_int_metavar(facefusion.choices.output_video_quality_range))
|
| 197 |
+
group_output_creation.add_argument('--output-video-scale', help = translator.get('help.output_video_scale'), type = float, default = config.get_float_value('output_creation', 'output_video_scale', '1.0'), choices = facefusion.choices.output_video_scale_range)
|
| 198 |
+
group_output_creation.add_argument('--output-video-fps', help = translator.get('help.output_video_fps'), type = float, default = config.get_float_value('output_creation', 'output_video_fps'))
|
| 199 |
+
job_store.register_step_keys([ 'output_image_quality', 'output_image_scale', 'output_audio_encoder', 'output_audio_quality', 'output_audio_volume', 'output_video_encoder', 'output_video_preset', 'output_video_quality', 'output_video_scale', 'output_video_fps' ])
|
| 200 |
+
return program
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def create_workflow_program() -> ArgumentParser:
|
| 204 |
+
program = ArgumentParser(add_help = False)
|
| 205 |
+
group_workflow = program.add_argument_group('workflow')
|
| 206 |
+
group_workflow.add_argument('--workflow-mode', help = translator.get('help.workflow_mode'), default = config.get_str_value('workflow', 'workflow_mode', 'auto'), choices = facefusion.choices.workflow_modes)
|
| 207 |
+
group_workflow.add_argument('--workflow-strategy', help = translator.get('help.workflow_strategy'), default = config.get_str_value('workflow', 'workflow_strategy', 'memory'), choices = facefusion.choices.workflow_strategies)
|
| 208 |
+
job_store.register_step_keys([ 'workflow_mode', 'workflow_strategy' ])
|
| 209 |
+
return program
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def create_processors_program() -> ArgumentParser:
|
| 213 |
+
program = ArgumentParser(add_help = False)
|
| 214 |
+
available_processors = [ get_file_name(file_path) for file_path in resolve_file_paths('facefusion/processors/modules') ]
|
| 215 |
+
group_processors = program.add_argument_group('processors')
|
| 216 |
+
group_processors.add_argument('--processors', help = translator.get('help.processors').format(choices = ', '.join(available_processors)), default = config.get_str_list('processors', 'processors', 'face_swapper'), choices = available_processors, nargs = '+', metavar = 'PROCESSORS')
|
| 217 |
+
job_store.register_step_keys([ 'processors' ])
|
| 218 |
+
for processor_module in get_processors_modules(available_processors):
|
| 219 |
+
processor_module.register_args(program)
|
| 220 |
+
return program
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def create_uis_program() -> ArgumentParser:
|
| 224 |
+
program = ArgumentParser(add_help = False)
|
| 225 |
+
available_ui_layouts = [ get_file_name(file_path) for file_path in resolve_file_paths('facefusion/uis/layouts') ]
|
| 226 |
+
group_uis = program.add_argument_group('uis')
|
| 227 |
+
group_uis.add_argument('--open-browser', help = translator.get('help.open_browser'), action = 'store_true', default = config.get_bool_value('uis', 'open_browser'))
|
| 228 |
+
group_uis.add_argument('--ui-layouts', help = translator.get('help.ui_layouts').format(choices = ', '.join(available_ui_layouts)), default = config.get_str_list('uis', 'ui_layouts', 'default'), choices = available_ui_layouts, nargs = '+', metavar = 'UI_LAYOUTS')
|
| 229 |
+
group_uis.add_argument('--ui-workflow', help = translator.get('help.ui_workflow'), default = config.get_str_value('uis', 'ui_workflow', 'instant_runner'), choices = facefusion.choices.ui_workflows)
|
| 230 |
+
return program
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def create_download_providers_program() -> ArgumentParser:
|
| 234 |
+
program = ArgumentParser(add_help = False)
|
| 235 |
+
group_download = program.add_argument_group('download')
|
| 236 |
+
group_download.add_argument('--download-providers', help = translator.get('help.download_providers').format(choices = ', '.join(facefusion.choices.download_providers)), default = config.get_str_list('download', 'download_providers', ' '.join(facefusion.choices.download_providers)), choices = facefusion.choices.download_providers, nargs = '+', metavar = 'DOWNLOAD_PROVIDERS')
|
| 237 |
+
job_store.register_job_keys([ 'download_providers' ])
|
| 238 |
+
return program
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def create_download_scope_program() -> ArgumentParser:
|
| 242 |
+
program = ArgumentParser(add_help = False)
|
| 243 |
+
group_download = program.add_argument_group('download')
|
| 244 |
+
group_download.add_argument('--download-scope', help = translator.get('help.download_scope'), default = config.get_str_value('download', 'download_scope', 'lite'), choices = facefusion.choices.download_scopes)
|
| 245 |
+
job_store.register_job_keys([ 'download_scope' ])
|
| 246 |
+
return program
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def create_benchmark_program() -> ArgumentParser:
|
| 250 |
+
program = ArgumentParser(add_help = False)
|
| 251 |
+
group_benchmark = program.add_argument_group('benchmark')
|
| 252 |
+
group_benchmark.add_argument('--benchmark-mode', help = translator.get('help.benchmark_mode'), default = config.get_str_value('benchmark', 'benchmark_mode', 'warm'), choices = facefusion.choices.benchmark_modes)
|
| 253 |
+
group_benchmark.add_argument('--benchmark-resolutions', help = translator.get('help.benchmark_resolutions'), default = config.get_str_list('benchmark', 'benchmark_resolutions', get_first(facefusion.choices.benchmark_resolutions)), choices = facefusion.choices.benchmark_resolutions, nargs = '+')
|
| 254 |
+
group_benchmark.add_argument('--benchmark-cycle-count', help = translator.get('help.benchmark_cycle_count'), type = int, default = config.get_int_value('benchmark', 'benchmark_cycle_count', '5'), choices = facefusion.choices.benchmark_cycle_count_range)
|
| 255 |
+
return program
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def create_execution_program() -> ArgumentParser:
|
| 259 |
+
program = ArgumentParser(add_help = False)
|
| 260 |
+
available_execution_providers = get_available_execution_providers()
|
| 261 |
+
group_execution = program.add_argument_group('execution')
|
| 262 |
+
group_execution.add_argument('--execution-device-ids', help = translator.get('help.execution_device_ids'), type = int, default = config.get_int_list('execution', 'execution_device_ids', '0'), nargs = '+', metavar = 'EXECUTION_DEVICE_IDS')
|
| 263 |
+
group_execution.add_argument('--execution-providers', help = translator.get('help.execution_providers').format(choices = ', '.join(available_execution_providers)), default = config.get_str_list('execution', 'execution_providers', get_first(available_execution_providers)), choices = available_execution_providers, nargs = '+', metavar = 'EXECUTION_PROVIDERS')
|
| 264 |
+
group_execution.add_argument('--execution-thread-count', help = translator.get('help.execution_thread_count'), type = int, default = config.get_int_value('execution', 'execution_thread_count', '8'), choices = facefusion.choices.execution_thread_count_range, metavar = create_int_metavar(facefusion.choices.execution_thread_count_range))
|
| 265 |
+
job_store.register_job_keys([ 'execution_device_ids', 'execution_providers', 'execution_thread_count' ])
|
| 266 |
+
return program
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def create_memory_program() -> ArgumentParser:
|
| 270 |
+
program = ArgumentParser(add_help = False)
|
| 271 |
+
group_memory = program.add_argument_group('memory')
|
| 272 |
+
group_memory.add_argument('--video-memory-strategy', help = translator.get('help.video_memory_strategy'), default = config.get_str_value('memory', 'video_memory_strategy', 'strict'), choices = facefusion.choices.video_memory_strategies)
|
| 273 |
+
job_store.register_job_keys([ 'video_memory_strategy' ])
|
| 274 |
+
return program
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def create_log_level_program() -> ArgumentParser:
|
| 278 |
+
program = ArgumentParser(add_help = False)
|
| 279 |
+
group_misc = program.add_argument_group('misc')
|
| 280 |
+
group_misc.add_argument('--log-level', help = translator.get('help.log_level'), default = config.get_str_value('misc', 'log_level', 'info'), choices = facefusion.choices.log_levels)
|
| 281 |
+
job_store.register_job_keys([ 'log_level' ])
|
| 282 |
+
return program
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def create_halt_on_error_program() -> ArgumentParser:
|
| 286 |
+
program = ArgumentParser(add_help = False)
|
| 287 |
+
group_misc = program.add_argument_group('misc')
|
| 288 |
+
group_misc.add_argument('--halt-on-error', help = translator.get('help.halt_on_error'), action = 'store_true', default = config.get_bool_value('misc', 'halt_on_error'))
|
| 289 |
+
job_store.register_job_keys([ 'halt_on_error' ])
|
| 290 |
+
return program
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def create_job_id_program() -> ArgumentParser:
|
| 294 |
+
program = ArgumentParser(add_help = False)
|
| 295 |
+
program.add_argument('job_id', help = translator.get('help.job_id'), type = sanitize_job_id)
|
| 296 |
+
return program
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def create_job_status_program() -> ArgumentParser:
|
| 300 |
+
program = ArgumentParser(add_help = False)
|
| 301 |
+
program.add_argument('job_status', help = translator.get('help.job_status'), choices = facefusion.choices.job_statuses)
|
| 302 |
+
return program
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def create_step_index_program() -> ArgumentParser:
|
| 306 |
+
program = ArgumentParser(add_help = False)
|
| 307 |
+
program.add_argument('step_index', help = translator.get('help.step_index'), type = int)
|
| 308 |
+
return program
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def collect_step_program() -> ArgumentParser:
|
| 312 |
+
return ArgumentParser(parents = [ create_face_detector_program(), create_face_landmarker_program(), create_face_selector_program(), create_face_tracker_program(), create_face_masker_program(), create_voice_extractor_program(), create_frame_extraction_program(), create_frame_distribution_program(), create_output_creation_program(), create_workflow_program(), create_processors_program() ], add_help = False)
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def collect_job_program() -> ArgumentParser:
|
| 316 |
+
return ArgumentParser(parents = [ create_execution_program(), create_download_providers_program(), create_memory_program(), create_log_level_program() ], add_help = False)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def create_program() -> ArgumentParser:
|
| 320 |
+
program = ArgumentParser(formatter_class = create_help_formatter_large, add_help = False)
|
| 321 |
+
program._positionals.title = 'commands'
|
| 322 |
+
program.add_argument('-v', '--version', version = metadata.get('name') + ' ' + metadata.get('version'), action = 'version')
|
| 323 |
+
sub_program = program.add_subparsers(dest = 'command')
|
| 324 |
+
sub_program.add_parser('run', help = translator.get('help.run'), parents = [ create_config_path_program(), create_temp_path_program(), create_jobs_path_program(), create_source_paths_program(), create_target_path_program(), create_output_path_program(), collect_step_program(), create_uis_program(), create_benchmark_program(), collect_job_program() ], formatter_class = create_help_formatter_large)
|
| 325 |
+
sub_program.add_parser('headless-run', help = translator.get('help.headless_run'), parents = [ create_config_path_program(), create_temp_path_program(), create_jobs_path_program(), create_source_paths_program(), create_target_path_program(), create_output_path_program(), collect_step_program(), collect_job_program() ], formatter_class = create_help_formatter_large)
|
| 326 |
+
sub_program.add_parser('batch-run', help = translator.get('help.batch_run'), parents = [ create_config_path_program(), create_temp_path_program(), create_jobs_path_program(), create_source_pattern_program(), create_target_pattern_program(), create_output_pattern_program(), collect_step_program(), collect_job_program() ], formatter_class = create_help_formatter_large)
|
| 327 |
+
sub_program.add_parser('force-download', help = translator.get('help.force_download'), parents = [ create_download_providers_program(), create_download_scope_program(), create_log_level_program() ], formatter_class = create_help_formatter_large)
|
| 328 |
+
sub_program.add_parser('benchmark', help = translator.get('help.benchmark'), parents = [ create_temp_path_program(), collect_step_program(), create_benchmark_program(), collect_job_program() ], formatter_class = create_help_formatter_large)
|
| 329 |
+
sub_program.add_parser('job-list', help = translator.get('help.job_list'), parents = [ create_job_status_program(), create_jobs_path_program(), create_log_level_program() ], formatter_class = create_help_formatter_large)
|
| 330 |
+
sub_program.add_parser('job-create', help = translator.get('help.job_create'), parents = [ create_job_id_program(), create_jobs_path_program(), create_log_level_program() ], formatter_class = create_help_formatter_large)
|
| 331 |
+
sub_program.add_parser('job-submit', help = translator.get('help.job_submit'), parents = [ create_job_id_program(), create_jobs_path_program(), create_log_level_program() ], formatter_class = create_help_formatter_large)
|
| 332 |
+
sub_program.add_parser('job-submit-all', help = translator.get('help.job_submit_all'), parents = [ create_jobs_path_program(), create_log_level_program(), create_halt_on_error_program() ], formatter_class = create_help_formatter_large)
|
| 333 |
+
sub_program.add_parser('job-delete', help = translator.get('help.job_delete'), parents = [ create_job_id_program(), create_jobs_path_program(), create_log_level_program() ], formatter_class = create_help_formatter_large)
|
| 334 |
+
sub_program.add_parser('job-delete-all', help = translator.get('help.job_delete_all'), parents = [ create_jobs_path_program(), create_log_level_program(), create_halt_on_error_program() ], formatter_class = create_help_formatter_large)
|
| 335 |
+
sub_program.add_parser('job-add-step', help = translator.get('help.job_add_step'), parents = [ create_job_id_program(), create_config_path_program(), create_jobs_path_program(), create_source_paths_program(), create_target_path_program(), create_output_path_program(), collect_step_program(), create_log_level_program() ], formatter_class = create_help_formatter_large)
|
| 336 |
+
sub_program.add_parser('job-remix-step', help = translator.get('help.job_remix_step'), parents = [ create_job_id_program(), create_step_index_program(), create_config_path_program(), create_jobs_path_program(), create_source_paths_program(), create_output_path_program(), collect_step_program(), create_log_level_program() ], formatter_class = create_help_formatter_large)
|
| 337 |
+
sub_program.add_parser('job-insert-step', help = translator.get('help.job_insert_step'), parents = [ create_job_id_program(), create_step_index_program(), create_config_path_program(), create_jobs_path_program(), create_source_paths_program(), create_target_path_program(), create_output_path_program(), collect_step_program(), create_log_level_program() ], formatter_class = create_help_formatter_large)
|
| 338 |
+
sub_program.add_parser('job-remove-step', help = translator.get('help.job_remove_step'), parents = [ create_job_id_program(), create_step_index_program(), create_jobs_path_program(), create_log_level_program() ], formatter_class = create_help_formatter_large)
|
| 339 |
+
sub_program.add_parser('job-run', help = translator.get('help.job_run'), parents = [ create_job_id_program(), create_config_path_program(), create_temp_path_program(), create_jobs_path_program(), collect_job_program() ], formatter_class = create_help_formatter_large)
|
| 340 |
+
sub_program.add_parser('job-run-all', help = translator.get('help.job_run_all'), parents = [ create_config_path_program(), create_temp_path_program(), create_jobs_path_program(), collect_job_program(), create_halt_on_error_program() ], formatter_class = create_help_formatter_large)
|
| 341 |
+
sub_program.add_parser('job-retry', help = translator.get('help.job_retry'), parents = [ create_job_id_program(), create_config_path_program(), create_temp_path_program(), create_jobs_path_program(), collect_job_program() ], formatter_class = create_help_formatter_large)
|
| 342 |
+
sub_program.add_parser('job-retry-all', help = translator.get('help.job_retry_all'), parents = [ create_config_path_program(), create_temp_path_program(), create_jobs_path_program(), collect_job_program(), create_halt_on_error_program() ], formatter_class = create_help_formatter_large)
|
| 343 |
+
return ArgumentParser(parents = [ program ], formatter_class = create_help_formatter_small)
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def apply_config_path(program : ArgumentParser) -> None:
|
| 347 |
+
known_args, _ = program.parse_known_args()
|
| 348 |
+
state_manager.init_item('config_path', known_args.config_path)
|
program_helper.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from argparse import ArgumentParser, _ArgumentGroup, _SubParsersAction
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def find_argument_group(program : ArgumentParser, group_name : str) -> Optional[_ArgumentGroup]:
|
| 6 |
+
for group in program._action_groups:
|
| 7 |
+
if group.title == group_name:
|
| 8 |
+
return group
|
| 9 |
+
return None
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def validate_args(program : ArgumentParser) -> bool:
|
| 13 |
+
if validate_actions(program):
|
| 14 |
+
for action in program._actions:
|
| 15 |
+
if isinstance(action, _SubParsersAction):
|
| 16 |
+
for _, sub_program in action._name_parser_map.items():
|
| 17 |
+
if not validate_args(sub_program):
|
| 18 |
+
return False
|
| 19 |
+
return True
|
| 20 |
+
return False
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def validate_actions(program : ArgumentParser) -> bool:
|
| 24 |
+
for action in program._actions:
|
| 25 |
+
if action.default and action.choices:
|
| 26 |
+
if isinstance(action.default, list):
|
| 27 |
+
if any(default not in action.choices for default in action.default):
|
| 28 |
+
return False
|
| 29 |
+
elif action.default not in action.choices:
|
| 30 |
+
return False
|
| 31 |
+
return True
|
sanitizer.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
from typing import Any, Sequence
|
| 3 |
+
|
| 4 |
+
from facefusion.common_helper import cast_int
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def sanitize_job_id(job_id : str) -> str:
|
| 8 |
+
__job_id__ = job_id.replace('-', '')
|
| 9 |
+
|
| 10 |
+
if __job_id__.isalnum():
|
| 11 |
+
return job_id
|
| 12 |
+
|
| 13 |
+
return hashlib.sha1(job_id.encode()).hexdigest()
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def sanitize_int_range(value : Any, int_range : Sequence[int]) -> int:
|
| 17 |
+
value = cast_int(value)
|
| 18 |
+
|
| 19 |
+
if value in int_range:
|
| 20 |
+
return value
|
| 21 |
+
return int_range[0]
|
state_manager.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Union
|
| 2 |
+
|
| 3 |
+
from facefusion.app_context import detect_app_context
|
| 4 |
+
from facefusion.processors.types import ProcessorState, ProcessorStateKey, ProcessorStateSet
|
| 5 |
+
from facefusion.types import State, StateKey, StateSet
|
| 6 |
+
|
| 7 |
+
STATE_SET : Union[StateSet, ProcessorStateSet] =\
|
| 8 |
+
{
|
| 9 |
+
'cli': {}, #type:ignore[assignment]
|
| 10 |
+
'ui': {} #type:ignore[assignment]
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def get_state() -> Union[State, ProcessorState]:
|
| 15 |
+
app_context = detect_app_context()
|
| 16 |
+
return STATE_SET.get(app_context)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def sync_state() -> None:
|
| 20 |
+
STATE_SET['cli'] = STATE_SET.get('ui') #type:ignore[assignment]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def init_item(key : Union[StateKey, ProcessorStateKey], value : Any) -> None:
|
| 24 |
+
STATE_SET['cli'][key] = value #type:ignore[literal-required]
|
| 25 |
+
STATE_SET['ui'][key] = value #type:ignore[literal-required]
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def get_item(key : Union[StateKey, ProcessorStateKey]) -> Any:
|
| 29 |
+
return get_state().get(key) #type:ignore[literal-required]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def set_item(key : Union[StateKey, ProcessorStateKey], value : Any) -> None:
|
| 33 |
+
app_context = detect_app_context()
|
| 34 |
+
STATE_SET[app_context][key] = value #type:ignore[literal-required]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def sync_item(key : Union[StateKey, ProcessorStateKey]) -> None:
|
| 38 |
+
STATE_SET['cli'][key] = STATE_SET.get('ui').get(key) #type:ignore[literal-required]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def clear_item(key : Union[StateKey, ProcessorStateKey]) -> None:
|
| 42 |
+
set_item(key, None)
|
streamer.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import subprocess
|
| 3 |
+
from collections import deque
|
| 4 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 5 |
+
from typing import Deque, Iterator, List
|
| 6 |
+
|
| 7 |
+
import cv2
|
| 8 |
+
from tqdm import tqdm
|
| 9 |
+
|
| 10 |
+
from facefusion import ffmpeg_builder, logger, state_manager, translator
|
| 11 |
+
from facefusion.audio import create_empty_audio_frame
|
| 12 |
+
from facefusion.content_analyser import analyse_stream
|
| 13 |
+
from facefusion.ffmpeg import open_ffmpeg
|
| 14 |
+
from facefusion.filesystem import is_directory
|
| 15 |
+
from facefusion.processors.core import get_processors_modules
|
| 16 |
+
from facefusion.types import Fps, StreamMode, VisionFrame
|
| 17 |
+
from facefusion.vision import extract_vision_mask, is_vision_frame, read_static_images
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def multi_process_capture(camera_capture : cv2.VideoCapture, camera_fps : Fps) -> Iterator[VisionFrame]:
|
| 21 |
+
capture_deque : Deque[VisionFrame] = deque()
|
| 22 |
+
source_vision_frames = read_static_images(state_manager.get_item('source_paths'))
|
| 23 |
+
|
| 24 |
+
with tqdm(desc = translator.get('streaming'), unit = 'frame', disable = state_manager.get_item('log_level') in [ 'warn', 'error' ]) as progress:
|
| 25 |
+
with ThreadPoolExecutor(max_workers = state_manager.get_item('execution_thread_count')) as executor:
|
| 26 |
+
futures = []
|
| 27 |
+
|
| 28 |
+
while camera_capture and camera_capture.isOpened():
|
| 29 |
+
_, capture_vision_frame = camera_capture.read()
|
| 30 |
+
if analyse_stream(capture_vision_frame, camera_fps):
|
| 31 |
+
camera_capture.release()
|
| 32 |
+
|
| 33 |
+
if is_vision_frame(capture_vision_frame):
|
| 34 |
+
future = executor.submit(process_stream_frame, source_vision_frames, capture_vision_frame)
|
| 35 |
+
futures.append(future)
|
| 36 |
+
|
| 37 |
+
for future_done in [ future for future in futures if future.done() ]:
|
| 38 |
+
capture_vision_frame = future_done.result()
|
| 39 |
+
capture_deque.append(capture_vision_frame)
|
| 40 |
+
futures.remove(future_done)
|
| 41 |
+
|
| 42 |
+
while capture_deque:
|
| 43 |
+
progress.update()
|
| 44 |
+
yield capture_deque.popleft()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def process_stream_frame(source_vision_frames : List[VisionFrame], target_vision_frame : VisionFrame) -> VisionFrame:
|
| 48 |
+
source_audio_frame = create_empty_audio_frame()
|
| 49 |
+
source_voice_frame = create_empty_audio_frame()
|
| 50 |
+
temp_vision_frame = target_vision_frame.copy()
|
| 51 |
+
temp_vision_mask = extract_vision_mask(temp_vision_frame)
|
| 52 |
+
|
| 53 |
+
for processor_module in get_processors_modules(state_manager.get_item('processors')):
|
| 54 |
+
logger.disable()
|
| 55 |
+
if processor_module.pre_process('stream'):
|
| 56 |
+
logger.enable()
|
| 57 |
+
temp_vision_frame, temp_vision_mask = processor_module.process_frame(
|
| 58 |
+
{
|
| 59 |
+
'source_vision_frames': source_vision_frames,
|
| 60 |
+
'source_audio_frame': source_audio_frame,
|
| 61 |
+
'source_voice_frame': source_voice_frame,
|
| 62 |
+
'target_vision_frames': [ target_vision_frame ],
|
| 63 |
+
'temp_vision_frame': temp_vision_frame,
|
| 64 |
+
'temp_vision_mask': temp_vision_mask
|
| 65 |
+
})
|
| 66 |
+
logger.enable()
|
| 67 |
+
|
| 68 |
+
return temp_vision_frame
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def open_stream(stream_mode : StreamMode, stream_resolution : str, stream_fps : Fps) -> subprocess.Popen[bytes]:
|
| 72 |
+
commands = ffmpeg_builder.chain(
|
| 73 |
+
ffmpeg_builder.capture_video(),
|
| 74 |
+
ffmpeg_builder.set_media_resolution(stream_resolution),
|
| 75 |
+
ffmpeg_builder.set_input_fps(stream_fps)
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
if stream_mode == 'udp':
|
| 79 |
+
commands.extend(ffmpeg_builder.set_input('-'))
|
| 80 |
+
commands.extend(ffmpeg_builder.set_stream_mode('udp'))
|
| 81 |
+
commands.extend(ffmpeg_builder.set_stream_quality(2000))
|
| 82 |
+
commands.extend(ffmpeg_builder.set_output('udp://localhost:27000?pkt_size=1316'))
|
| 83 |
+
|
| 84 |
+
if stream_mode == 'v4l2':
|
| 85 |
+
device_directory_path = '/sys/devices/virtual/video4linux'
|
| 86 |
+
commands.extend(ffmpeg_builder.set_input('-'))
|
| 87 |
+
commands.extend(ffmpeg_builder.set_stream_mode('v4l2'))
|
| 88 |
+
|
| 89 |
+
if is_directory(device_directory_path):
|
| 90 |
+
device_names = os.listdir(device_directory_path)
|
| 91 |
+
|
| 92 |
+
for device_name in device_names:
|
| 93 |
+
device_path = '/dev/' + device_name
|
| 94 |
+
commands.extend(ffmpeg_builder.set_output(device_path))
|
| 95 |
+
|
| 96 |
+
else:
|
| 97 |
+
logger.error(translator.get('stream_not_loaded').format(stream_mode = stream_mode), __name__)
|
| 98 |
+
|
| 99 |
+
return open_ffmpeg(commands)
|
temp_helper.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
from facefusion import state_manager
|
| 4 |
+
from facefusion.filesystem import create_directory, get_file_extension, get_file_name, move_file, remove_directory, resolve_file_pattern
|
| 5 |
+
from facefusion.types import FrameSet
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def get_temp_file_path(file_path : str) -> str:
|
| 9 |
+
temp_directory_path = get_temp_directory_path(file_path)
|
| 10 |
+
temp_file_extension = get_file_extension(file_path)
|
| 11 |
+
return os.path.join(temp_directory_path, 'temp' + temp_file_extension)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def move_temp_file(file_path : str, move_path : str) -> bool:
|
| 15 |
+
temp_file_path = get_temp_file_path(file_path)
|
| 16 |
+
return move_file(temp_file_path, move_path)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def resolve_temp_frame_set(target_path : str) -> FrameSet:
|
| 20 |
+
temp_frame_pattern = get_temp_frame_pattern(target_path, '*')
|
| 21 |
+
temp_frame_set = {}
|
| 22 |
+
|
| 23 |
+
for temp_frame_path in resolve_file_pattern(temp_frame_pattern):
|
| 24 |
+
frame_number = int(get_file_name(temp_frame_path))
|
| 25 |
+
temp_frame_set[frame_number] = temp_frame_path
|
| 26 |
+
|
| 27 |
+
return temp_frame_set
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def get_temp_frame_pattern(target_path : str, temp_frame_prefix : str) -> str:
|
| 31 |
+
temp_directory_path = get_temp_directory_path(target_path)
|
| 32 |
+
return os.path.join(temp_directory_path, temp_frame_prefix + '.' + state_manager.get_item('temp_frame_format'))
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def get_temp_directory_path(file_path : str) -> str:
|
| 36 |
+
temp_file_name = get_file_name(file_path)
|
| 37 |
+
return os.path.join(state_manager.get_item('temp_path'), 'facefusion', temp_file_name)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def create_temp_directory(file_path : str) -> bool:
|
| 41 |
+
temp_directory_path = get_temp_directory_path(file_path)
|
| 42 |
+
return create_directory(temp_directory_path)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def clear_temp_directory(file_path : str) -> bool:
|
| 46 |
+
temp_directory_path = get_temp_directory_path(file_path)
|
| 47 |
+
return remove_directory(temp_directory_path)
|
thread_helper.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import threading
|
| 2 |
+
from contextlib import nullcontext
|
| 3 |
+
from typing import ContextManager, Union
|
| 4 |
+
|
| 5 |
+
from facefusion.common_helper import is_linux, is_windows
|
| 6 |
+
from facefusion.execution import has_execution_provider
|
| 7 |
+
|
| 8 |
+
THREAD_LOCK : threading.Lock = threading.Lock()
|
| 9 |
+
THREAD_SEMAPHORE : threading.Semaphore = threading.Semaphore()
|
| 10 |
+
NULL_CONTEXT : ContextManager[None] = nullcontext()
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def thread_lock() -> threading.Lock:
|
| 14 |
+
return THREAD_LOCK
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def thread_semaphore() -> threading.Semaphore:
|
| 18 |
+
return THREAD_SEMAPHORE
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def conditional_thread_semaphore() -> Union[threading.Semaphore, ContextManager[None]]:
|
| 22 |
+
if is_windows() and has_execution_provider('directml') or is_linux() and has_execution_provider('migraphx') or is_linux() and has_execution_provider('rocm'):
|
| 23 |
+
return THREAD_SEMAPHORE
|
| 24 |
+
return NULL_CONTEXT
|
time_helper.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime, timedelta
|
| 2 |
+
from time import time
|
| 3 |
+
from typing import Optional, Tuple
|
| 4 |
+
|
| 5 |
+
from facefusion import translator
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def get_current_date_time() -> datetime:
|
| 9 |
+
return datetime.now().astimezone()
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def calculate_end_time(start_time : float) -> float:
|
| 13 |
+
return round(time() - start_time, 2)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def split_time_delta(time_delta : timedelta) -> Tuple[int, int, int, int]:
|
| 17 |
+
days, hours = divmod(time_delta.total_seconds(), 86400)
|
| 18 |
+
hours, minutes = divmod(hours, 3600)
|
| 19 |
+
minutes, seconds = divmod(minutes, 60)
|
| 20 |
+
return int(days), int(hours), int(minutes), int(seconds)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def describe_time_ago(date_time : datetime) -> Optional[str]:
|
| 24 |
+
time_ago = datetime.now(date_time.tzinfo) - date_time
|
| 25 |
+
days, hours, minutes, _ = split_time_delta(time_ago)
|
| 26 |
+
|
| 27 |
+
if timedelta(days = 1) < time_ago:
|
| 28 |
+
return translator.get('time_ago_days').format(days = days, hours = hours, minutes = minutes)
|
| 29 |
+
if timedelta(hours = 1) < time_ago:
|
| 30 |
+
return translator.get('time_ago_hours').format(hours = hours, minutes = minutes)
|
| 31 |
+
if timedelta(minutes = 1) < time_ago:
|
| 32 |
+
return translator.get('time_ago_minutes').format(minutes = minutes)
|
| 33 |
+
return translator.get('time_ago_now')
|