mirror of
https://github.com/facefusion/facefusion.git
synced 2026-07-28 12:59:03 +02:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3f81a8a784 | ||
|
|
b8f80460cf | ||
|
|
5305968de7 | ||
|
|
b6d740e64a | ||
|
|
75bd742858 | ||
|
|
a2cbfd73b1 | ||
|
|
5b7d145aa7 | ||
|
|
519360bcd6 | ||
|
|
57fcb86b82 | ||
|
|
2cc05d4fba | ||
|
|
a498f3d618 | ||
|
|
c7976ec9d4 | ||
|
|
8801668562 | ||
|
|
a7f3de3dbc | ||
|
|
666c15f9da | ||
|
|
420d738a6b | ||
|
|
81c5e85dea | ||
|
|
8bf9170577 | ||
|
|
189d750621 | ||
|
|
f3be23d19b |
@@ -0,0 +1,2 @@
|
||||
[run]
|
||||
patch = subprocess
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 1.3 MiB After Width: | Height: | Size: 1.1 MiB |
@@ -33,7 +33,7 @@ jobs:
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
- run: python install.py --onnxruntime default --skip-conda
|
||||
- run: python install.py default --skip-conda
|
||||
- run: pip install pytest
|
||||
- run: pytest
|
||||
report:
|
||||
@@ -48,7 +48,7 @@ jobs:
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
- run: python install.py --onnxruntime default --skip-conda
|
||||
- run: python install.py default --skip-conda
|
||||
- run: pip install coveralls
|
||||
- run: pip install pytest
|
||||
- run: pip install pytest-cov
|
||||
|
||||
+2
-1
@@ -1,6 +1,7 @@
|
||||
__pycache__
|
||||
.assets
|
||||
.claude
|
||||
.caches
|
||||
.jobs
|
||||
.idea
|
||||
.jobs
|
||||
.vscode
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
OpenRAIL-AS license
|
||||
|
||||
Copyright (c) 2025 Henry Ruhs
|
||||
Copyright (c) 2026 Henry Ruhs
|
||||
|
||||
+10
-1
@@ -13,6 +13,7 @@ output_pattern =
|
||||
[face_detector]
|
||||
face_detector_model =
|
||||
face_detector_size =
|
||||
face_detector_margin =
|
||||
face_detector_angles =
|
||||
face_detector_score =
|
||||
|
||||
@@ -31,6 +32,9 @@ reference_face_position =
|
||||
reference_face_distance =
|
||||
reference_frame_number =
|
||||
|
||||
[face_tracker]
|
||||
face_tracker_score =
|
||||
|
||||
[face_masker]
|
||||
face_occluder_model =
|
||||
face_parser_model =
|
||||
@@ -49,6 +53,9 @@ trim_frame_end =
|
||||
temp_frame_format =
|
||||
keep_temp =
|
||||
|
||||
[frame_distribution]
|
||||
target_frame_amount =
|
||||
|
||||
[output_creation]
|
||||
output_image_quality =
|
||||
output_image_scale =
|
||||
@@ -65,6 +72,9 @@ output_video_fps =
|
||||
processors =
|
||||
age_modifier_model =
|
||||
age_modifier_direction =
|
||||
background_remover_model =
|
||||
background_remover_fill_color =
|
||||
background_remover_despill_color =
|
||||
deep_swapper_model =
|
||||
deep_swapper_morph =
|
||||
expression_restorer_model =
|
||||
@@ -121,7 +131,6 @@ execution_thread_count =
|
||||
|
||||
[memory]
|
||||
video_memory_strategy =
|
||||
system_memory_limit =
|
||||
|
||||
[misc]
|
||||
log_level =
|
||||
|
||||
+2
-1
@@ -4,7 +4,8 @@ import os
|
||||
|
||||
os.environ['OMP_NUM_THREADS'] = '1'
|
||||
|
||||
from facefusion import core
|
||||
from facefusion import conda, core
|
||||
|
||||
if __name__ == '__main__':
|
||||
conda.setup()
|
||||
core.cli()
|
||||
|
||||
@@ -5,12 +5,14 @@ from facefusion.types import AppContext
|
||||
|
||||
|
||||
def detect_app_context() -> AppContext:
|
||||
jobs_path = os.path.join('facefusion', 'jobs')
|
||||
uis_path = os.path.join('facefusion', 'uis')
|
||||
frame = sys._getframe(1)
|
||||
|
||||
while frame:
|
||||
if os.path.join('facefusion', 'jobs') in frame.f_code.co_filename:
|
||||
if jobs_path in frame.f_code.co_filename:
|
||||
return 'cli'
|
||||
if os.path.join('facefusion', 'uis') in frame.f_code.co_filename:
|
||||
if uis_path in frame.f_code.co_filename:
|
||||
return 'ui'
|
||||
frame = frame.f_back
|
||||
return 'cli'
|
||||
|
||||
+80
-92
@@ -1,12 +1,91 @@
|
||||
from facefusion import state_manager
|
||||
from facefusion.filesystem import get_file_name, is_video, resolve_file_paths
|
||||
from facefusion.jobs import job_store
|
||||
from facefusion.normalizer import normalize_fps, normalize_padding
|
||||
from facefusion.normalizer import normalize_fps, normalize_space
|
||||
from facefusion.processors.core import get_processors_modules
|
||||
from facefusion.types import ApplyStateItem, Args
|
||||
from facefusion.vision import detect_video_fps
|
||||
|
||||
|
||||
def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
|
||||
apply_state_item('command', args.get('command'))
|
||||
apply_state_item('temp_path', args.get('temp_path'))
|
||||
apply_state_item('jobs_path', args.get('jobs_path'))
|
||||
apply_state_item('source_paths', args.get('source_paths'))
|
||||
apply_state_item('target_path', args.get('target_path'))
|
||||
apply_state_item('output_path', args.get('output_path'))
|
||||
apply_state_item('source_pattern', args.get('source_pattern'))
|
||||
apply_state_item('target_pattern', args.get('target_pattern'))
|
||||
apply_state_item('output_pattern', args.get('output_pattern'))
|
||||
apply_state_item('face_detector_model', args.get('face_detector_model'))
|
||||
apply_state_item('face_detector_size', args.get('face_detector_size'))
|
||||
apply_state_item('face_detector_margin', normalize_space(args.get('face_detector_margin')))
|
||||
apply_state_item('face_detector_angles', args.get('face_detector_angles'))
|
||||
apply_state_item('face_detector_score', args.get('face_detector_score'))
|
||||
apply_state_item('face_landmarker_model', args.get('face_landmarker_model'))
|
||||
apply_state_item('face_landmarker_score', args.get('face_landmarker_score'))
|
||||
apply_state_item('face_selector_mode', args.get('face_selector_mode'))
|
||||
apply_state_item('face_selector_order', args.get('face_selector_order'))
|
||||
apply_state_item('face_selector_age_start', args.get('face_selector_age_start'))
|
||||
apply_state_item('face_selector_age_end', args.get('face_selector_age_end'))
|
||||
apply_state_item('face_selector_gender', args.get('face_selector_gender'))
|
||||
apply_state_item('face_selector_race', args.get('face_selector_race'))
|
||||
apply_state_item('reference_face_position', args.get('reference_face_position'))
|
||||
apply_state_item('reference_face_distance', args.get('reference_face_distance'))
|
||||
apply_state_item('reference_frame_number', args.get('reference_frame_number'))
|
||||
apply_state_item('face_tracker_score', args.get('face_tracker_score'))
|
||||
apply_state_item('face_occluder_model', args.get('face_occluder_model'))
|
||||
apply_state_item('face_parser_model', args.get('face_parser_model'))
|
||||
apply_state_item('face_mask_types', args.get('face_mask_types'))
|
||||
apply_state_item('face_mask_areas', args.get('face_mask_areas'))
|
||||
apply_state_item('face_mask_regions', args.get('face_mask_regions'))
|
||||
apply_state_item('face_mask_blur', args.get('face_mask_blur'))
|
||||
apply_state_item('face_mask_padding', normalize_space(args.get('face_mask_padding')))
|
||||
apply_state_item('voice_extractor_model', args.get('voice_extractor_model'))
|
||||
apply_state_item('trim_frame_start', args.get('trim_frame_start'))
|
||||
apply_state_item('trim_frame_end', args.get('trim_frame_end'))
|
||||
apply_state_item('temp_frame_format', args.get('temp_frame_format'))
|
||||
apply_state_item('keep_temp', args.get('keep_temp'))
|
||||
apply_state_item('target_frame_amount', args.get('target_frame_amount'))
|
||||
apply_state_item('output_image_quality', args.get('output_image_quality'))
|
||||
apply_state_item('output_image_scale', args.get('output_image_scale'))
|
||||
apply_state_item('output_audio_encoder', args.get('output_audio_encoder'))
|
||||
apply_state_item('output_audio_quality', args.get('output_audio_quality'))
|
||||
apply_state_item('output_audio_volume', args.get('output_audio_volume'))
|
||||
apply_state_item('output_video_encoder', args.get('output_video_encoder'))
|
||||
apply_state_item('output_video_preset', args.get('output_video_preset'))
|
||||
apply_state_item('output_video_quality', args.get('output_video_quality'))
|
||||
apply_state_item('output_video_scale', args.get('output_video_scale'))
|
||||
|
||||
if args.get('output_video_fps') or is_video(args.get('target_path')):
|
||||
output_video_fps = normalize_fps(args.get('output_video_fps')) or detect_video_fps(args.get('target_path'))
|
||||
apply_state_item('output_video_fps', output_video_fps)
|
||||
|
||||
available_processors = [ get_file_name(file_path) for file_path in resolve_file_paths('facefusion/processors/modules') ]
|
||||
apply_state_item('processors', args.get('processors'))
|
||||
|
||||
for processor_module in get_processors_modules(available_processors):
|
||||
processor_module.apply_args(args, apply_state_item)
|
||||
|
||||
apply_state_item('open_browser', args.get('open_browser'))
|
||||
apply_state_item('ui_layouts', args.get('ui_layouts'))
|
||||
apply_state_item('ui_workflow', args.get('ui_workflow'))
|
||||
apply_state_item('execution_device_ids', args.get('execution_device_ids'))
|
||||
apply_state_item('execution_providers', args.get('execution_providers'))
|
||||
apply_state_item('execution_thread_count', args.get('execution_thread_count'))
|
||||
apply_state_item('download_providers', args.get('download_providers'))
|
||||
apply_state_item('download_scope', args.get('download_scope'))
|
||||
apply_state_item('benchmark_mode', args.get('benchmark_mode'))
|
||||
apply_state_item('benchmark_resolutions', args.get('benchmark_resolutions'))
|
||||
apply_state_item('benchmark_cycle_count', args.get('benchmark_cycle_count'))
|
||||
apply_state_item('video_memory_strategy', args.get('video_memory_strategy'))
|
||||
apply_state_item('log_level', args.get('log_level'))
|
||||
apply_state_item('halt_on_error', args.get('halt_on_error'))
|
||||
apply_state_item('job_id', args.get('job_id'))
|
||||
apply_state_item('job_status', args.get('job_status'))
|
||||
apply_state_item('step_index', args.get('step_index'))
|
||||
|
||||
|
||||
def reduce_step_args(args : Args) -> Args:
|
||||
step_args =\
|
||||
{
|
||||
@@ -37,94 +116,3 @@ def collect_job_args() -> Args:
|
||||
key: state_manager.get_item(key) for key in job_store.get_job_keys() #type:ignore[arg-type]
|
||||
}
|
||||
return job_args
|
||||
|
||||
|
||||
def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
|
||||
# general
|
||||
apply_state_item('command', args.get('command'))
|
||||
# paths
|
||||
apply_state_item('temp_path', args.get('temp_path'))
|
||||
apply_state_item('jobs_path', args.get('jobs_path'))
|
||||
apply_state_item('source_paths', args.get('source_paths'))
|
||||
apply_state_item('target_path', args.get('target_path'))
|
||||
apply_state_item('output_path', args.get('output_path'))
|
||||
# patterns
|
||||
apply_state_item('source_pattern', args.get('source_pattern'))
|
||||
apply_state_item('target_pattern', args.get('target_pattern'))
|
||||
apply_state_item('output_pattern', args.get('output_pattern'))
|
||||
# face detector
|
||||
apply_state_item('face_detector_model', args.get('face_detector_model'))
|
||||
apply_state_item('face_detector_size', args.get('face_detector_size'))
|
||||
apply_state_item('face_detector_angles', args.get('face_detector_angles'))
|
||||
apply_state_item('face_detector_score', args.get('face_detector_score'))
|
||||
# face landmarker
|
||||
apply_state_item('face_landmarker_model', args.get('face_landmarker_model'))
|
||||
apply_state_item('face_landmarker_score', args.get('face_landmarker_score'))
|
||||
# face selector
|
||||
apply_state_item('face_selector_mode', args.get('face_selector_mode'))
|
||||
apply_state_item('face_selector_order', args.get('face_selector_order'))
|
||||
apply_state_item('face_selector_age_start', args.get('face_selector_age_start'))
|
||||
apply_state_item('face_selector_age_end', args.get('face_selector_age_end'))
|
||||
apply_state_item('face_selector_gender', args.get('face_selector_gender'))
|
||||
apply_state_item('face_selector_race', args.get('face_selector_race'))
|
||||
apply_state_item('reference_face_position', args.get('reference_face_position'))
|
||||
apply_state_item('reference_face_distance', args.get('reference_face_distance'))
|
||||
apply_state_item('reference_frame_number', args.get('reference_frame_number'))
|
||||
# face masker
|
||||
apply_state_item('face_occluder_model', args.get('face_occluder_model'))
|
||||
apply_state_item('face_parser_model', args.get('face_parser_model'))
|
||||
apply_state_item('face_mask_types', args.get('face_mask_types'))
|
||||
apply_state_item('face_mask_areas', args.get('face_mask_areas'))
|
||||
apply_state_item('face_mask_regions', args.get('face_mask_regions'))
|
||||
apply_state_item('face_mask_blur', args.get('face_mask_blur'))
|
||||
apply_state_item('face_mask_padding', normalize_padding(args.get('face_mask_padding')))
|
||||
# voice extractor
|
||||
apply_state_item('voice_extractor_model', args.get('voice_extractor_model'))
|
||||
# frame extraction
|
||||
apply_state_item('trim_frame_start', args.get('trim_frame_start'))
|
||||
apply_state_item('trim_frame_end', args.get('trim_frame_end'))
|
||||
apply_state_item('temp_frame_format', args.get('temp_frame_format'))
|
||||
apply_state_item('keep_temp', args.get('keep_temp'))
|
||||
# output creation
|
||||
apply_state_item('output_image_quality', args.get('output_image_quality'))
|
||||
apply_state_item('output_image_scale', args.get('output_image_scale'))
|
||||
apply_state_item('output_audio_encoder', args.get('output_audio_encoder'))
|
||||
apply_state_item('output_audio_quality', args.get('output_audio_quality'))
|
||||
apply_state_item('output_audio_volume', args.get('output_audio_volume'))
|
||||
apply_state_item('output_video_encoder', args.get('output_video_encoder'))
|
||||
apply_state_item('output_video_preset', args.get('output_video_preset'))
|
||||
apply_state_item('output_video_quality', args.get('output_video_quality'))
|
||||
apply_state_item('output_video_scale', args.get('output_video_scale'))
|
||||
if args.get('output_video_fps') or is_video(args.get('target_path')):
|
||||
output_video_fps = normalize_fps(args.get('output_video_fps')) or detect_video_fps(args.get('target_path'))
|
||||
apply_state_item('output_video_fps', output_video_fps)
|
||||
# processors
|
||||
available_processors = [ get_file_name(file_path) for file_path in resolve_file_paths('facefusion/processors/modules') ]
|
||||
apply_state_item('processors', args.get('processors'))
|
||||
for processor_module in get_processors_modules(available_processors):
|
||||
processor_module.apply_args(args, apply_state_item)
|
||||
# uis
|
||||
apply_state_item('open_browser', args.get('open_browser'))
|
||||
apply_state_item('ui_layouts', args.get('ui_layouts'))
|
||||
apply_state_item('ui_workflow', args.get('ui_workflow'))
|
||||
# execution
|
||||
apply_state_item('execution_device_ids', args.get('execution_device_ids'))
|
||||
apply_state_item('execution_providers', args.get('execution_providers'))
|
||||
apply_state_item('execution_thread_count', args.get('execution_thread_count'))
|
||||
# download
|
||||
apply_state_item('download_providers', args.get('download_providers'))
|
||||
apply_state_item('download_scope', args.get('download_scope'))
|
||||
# benchmark
|
||||
apply_state_item('benchmark_mode', args.get('benchmark_mode'))
|
||||
apply_state_item('benchmark_resolutions', args.get('benchmark_resolutions'))
|
||||
apply_state_item('benchmark_cycle_count', args.get('benchmark_cycle_count'))
|
||||
# memory
|
||||
apply_state_item('video_memory_strategy', args.get('video_memory_strategy'))
|
||||
apply_state_item('system_memory_limit', args.get('system_memory_limit'))
|
||||
# misc
|
||||
apply_state_item('log_level', args.get('log_level'))
|
||||
apply_state_item('halt_on_error', args.get('halt_on_error'))
|
||||
# jobs
|
||||
apply_state_item('job_id', args.get('job_id'))
|
||||
apply_state_item('job_status', args.get('job_status'))
|
||||
apply_state_item('step_index', args.get('step_index'))
|
||||
|
||||
+2
-2
@@ -11,7 +11,7 @@ from facefusion.types import Audio, AudioFrame, Fps, Mel, MelFilterBank, Spectro
|
||||
from facefusion.voice_extractor import batch_extract_voice
|
||||
|
||||
|
||||
@lru_cache()
|
||||
@lru_cache(maxsize = 64)
|
||||
def read_static_audio(audio_path : str, fps : Fps) -> Optional[List[AudioFrame]]:
|
||||
return read_audio(audio_path, fps)
|
||||
|
||||
@@ -31,7 +31,7 @@ def read_audio(audio_path : str, fps : Fps) -> Optional[List[AudioFrame]]:
|
||||
return None
|
||||
|
||||
|
||||
@lru_cache()
|
||||
@lru_cache(maxsize = 64)
|
||||
def read_static_voice(audio_path : str, fps : Fps) -> Optional[List[AudioFrame]]:
|
||||
return read_voice(audio_path, fps)
|
||||
|
||||
|
||||
@@ -3,13 +3,13 @@ import os
|
||||
import statistics
|
||||
import tempfile
|
||||
from time import perf_counter
|
||||
from typing import Generator, List
|
||||
from typing import Iterator, List
|
||||
|
||||
import facefusion.choices
|
||||
from facefusion import content_analyser, core, state_manager
|
||||
from facefusion.cli_helper import render_table
|
||||
from facefusion.download import conditional_download, resolve_download_url
|
||||
from facefusion.face_store import clear_static_faces
|
||||
from facefusion.face_store import clear_faces
|
||||
from facefusion.filesystem import get_file_extension
|
||||
from facefusion.types import BenchmarkCycleSet
|
||||
from facefusion.vision import count_video_frame_total, detect_video_fps
|
||||
@@ -31,7 +31,7 @@ def pre_check() -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def run() -> Generator[List[BenchmarkCycleSet], None, None]:
|
||||
def run() -> Iterator[List[BenchmarkCycleSet]]:
|
||||
benchmark_resolutions = state_manager.get_item('benchmark_resolutions')
|
||||
benchmark_cycle_count = state_manager.get_item('benchmark_cycle_count')
|
||||
|
||||
@@ -64,7 +64,7 @@ def cycle(cycle_count : int) -> BenchmarkCycleSet:
|
||||
if state_manager.get_item('benchmark_mode') == 'cold':
|
||||
content_analyser.analyse_image.cache_clear()
|
||||
content_analyser.analyse_video.cache_clear()
|
||||
clear_static_faces()
|
||||
clear_faces()
|
||||
|
||||
start_time = perf_counter()
|
||||
core.conditional_process()
|
||||
@@ -89,7 +89,7 @@ def cycle(cycle_count : int) -> BenchmarkCycleSet:
|
||||
|
||||
def suggest_output_path(target_path : str) -> str:
|
||||
target_file_extension = get_file_extension(target_path)
|
||||
return os.path.join(tempfile.gettempdir(), hashlib.sha1().hexdigest()[:8] + target_file_extension)
|
||||
return os.path.join(tempfile.gettempdir(), hashlib.sha1(target_path.encode()).hexdigest() + target_file_extension)
|
||||
|
||||
|
||||
def render() -> None:
|
||||
|
||||
@@ -2,7 +2,6 @@ from typing import List
|
||||
|
||||
import cv2
|
||||
|
||||
from facefusion.common_helper import is_windows
|
||||
from facefusion.types import CameraPoolSet
|
||||
|
||||
CAMERA_POOL_SET : CameraPoolSet =\
|
||||
@@ -15,9 +14,6 @@ def get_local_camera_capture(camera_id : int) -> cv2.VideoCapture:
|
||||
camera_key = str(camera_id)
|
||||
|
||||
if camera_key not in CAMERA_POOL_SET.get('capture'):
|
||||
if is_windows():
|
||||
camera_capture = cv2.VideoCapture(camera_id, cv2.CAP_DSHOW)
|
||||
else:
|
||||
camera_capture = cv2.VideoCapture(camera_id)
|
||||
|
||||
if camera_capture.isOpened():
|
||||
@@ -47,9 +43,9 @@ def detect_local_camera_ids(id_start : int, id_end : int) -> List[int]:
|
||||
local_camera_ids = []
|
||||
|
||||
for camera_id in range(id_start, id_end):
|
||||
cv2.setLogLevel(0)
|
||||
cv2.utils.logging.setLogLevel(0)
|
||||
camera_capture = get_local_camera_capture(camera_id)
|
||||
cv2.setLogLevel(3)
|
||||
cv2.utils.logging.setLogLevel(3)
|
||||
|
||||
if camera_capture and camera_capture.isOpened():
|
||||
local_camera_ids.append(camera_id)
|
||||
|
||||
+42
-35
@@ -1,8 +1,8 @@
|
||||
import logging
|
||||
from typing import List, Sequence
|
||||
from typing import List, Sequence, get_args
|
||||
|
||||
from facefusion.common_helper import create_float_range, create_int_range
|
||||
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, FaceSelectorMode, FaceSelectorOrder, Gender, ImageFormat, ImageTypeSet, JobStatus, LogLevel, LogLevelSet, Race, Score, TempFrameFormat, UiWorkflow, VideoEncoder, VideoFormat, VideoMemoryStrategy, VideoPreset, VideoTypeSet, VoiceExtractorModel
|
||||
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, UiWorkflow, VideoEncoder, VideoFormat, VideoMemoryStrategy, VideoPreset, VideoTypeSet, VoiceExtractorModel
|
||||
|
||||
face_detector_set : FaceDetectorSet =\
|
||||
{
|
||||
@@ -12,15 +12,17 @@ face_detector_set : FaceDetectorSet =\
|
||||
'yolo_face': [ '640x640' ],
|
||||
'yunet': [ '640x640' ]
|
||||
}
|
||||
face_detector_models : List[FaceDetectorModel] = list(face_detector_set.keys())
|
||||
face_landmarker_models : List[FaceLandmarkerModel] = [ 'many', '2dfan4', 'peppa_wutz' ]
|
||||
face_selector_modes : List[FaceSelectorMode] = [ 'many', 'one', 'reference' ]
|
||||
face_selector_orders : List[FaceSelectorOrder] = [ 'left-right', 'right-left', 'top-bottom', 'bottom-top', 'small-large', 'large-small', 'best-worst', 'worst-best' ]
|
||||
face_selector_genders : List[Gender] = [ 'female', 'male' ]
|
||||
face_selector_races : List[Race] = [ 'white', 'black', 'latino', 'asian', 'indian', 'arabic' ]
|
||||
face_occluder_models : List[FaceOccluderModel] = [ 'many', 'xseg_1', 'xseg_2', 'xseg_3' ]
|
||||
face_parser_models : List[FaceParserModel] = [ 'bisenet_resnet_18', 'bisenet_resnet_34' ]
|
||||
face_mask_types : List[FaceMaskType] = [ 'box', 'occlusion', 'area', 'region' ]
|
||||
face_detector_models : List[FaceDetectorModel] = list(get_args(FaceDetectorModel))
|
||||
face_landmarker_models : List[FaceLandmarkerModel] = list(get_args(FaceLandmarkerModel))
|
||||
face_selector_modes : List[FaceSelectorMode] = list(get_args(FaceSelectorMode))
|
||||
face_selector_orders : List[FaceSelectorOrder] = list(get_args(FaceSelectorOrder))
|
||||
genders : List[Gender] = list(get_args(Gender))
|
||||
races : List[Race] = list(get_args(Race))
|
||||
face_selector_genders : List[FaceSelectorGender] = list(get_args(FaceSelectorGender))
|
||||
face_selector_races : List[FaceSelectorRace] = list(get_args(FaceSelectorRace))
|
||||
face_occluder_models : List[FaceOccluderModel] = list(get_args(FaceOccluderModel))
|
||||
face_parser_models : List[FaceParserModel] = list(get_args(FaceParserModel))
|
||||
face_mask_types : List[FaceMaskType] = list(get_args(FaceMaskType))
|
||||
face_mask_area_set : FaceMaskAreaSet =\
|
||||
{
|
||||
'upper-face': [ 0, 1, 2, 31, 32, 33, 34, 35, 14, 15, 16, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17 ],
|
||||
@@ -40,10 +42,10 @@ face_mask_region_set : FaceMaskRegionSet =\
|
||||
'upper-lip': 12,
|
||||
'lower-lip': 13
|
||||
}
|
||||
face_mask_areas : List[FaceMaskArea] = list(face_mask_area_set.keys())
|
||||
face_mask_regions : List[FaceMaskRegion] = list(face_mask_region_set.keys())
|
||||
face_mask_areas : List[FaceMaskArea] = list(get_args(FaceMaskArea))
|
||||
face_mask_regions : List[FaceMaskRegion] = list(get_args(FaceMaskRegion))
|
||||
|
||||
voice_extractor_models : List[VoiceExtractorModel] = [ 'kim_vocal_1', 'kim_vocal_2', 'uvr_mdxnet' ]
|
||||
voice_extractor_models : List[VoiceExtractorModel] = list(get_args(VoiceExtractorModel))
|
||||
|
||||
audio_type_set : AudioTypeSet =\
|
||||
{
|
||||
@@ -68,25 +70,27 @@ video_type_set : VideoTypeSet =\
|
||||
'm4v': 'video/mp4',
|
||||
'mkv': 'video/x-matroska',
|
||||
'mp4': 'video/mp4',
|
||||
'mpeg': 'video/mpeg',
|
||||
'mov': 'video/quicktime',
|
||||
'mxf': 'application/mxf',
|
||||
'webm': 'video/webm',
|
||||
'wmv': 'video/x-ms-wmv'
|
||||
}
|
||||
audio_formats : List[AudioFormat] = list(audio_type_set.keys())
|
||||
image_formats : List[ImageFormat] = list(image_type_set.keys())
|
||||
video_formats : List[VideoFormat] = list(video_type_set.keys())
|
||||
temp_frame_formats : List[TempFrameFormat] = [ 'bmp', 'jpeg', 'png', 'tiff' ]
|
||||
audio_formats : List[AudioFormat] = list(get_args(AudioFormat))
|
||||
image_formats : List[ImageFormat] = list(get_args(ImageFormat))
|
||||
video_formats : List[VideoFormat] = list(get_args(VideoFormat))
|
||||
temp_frame_formats : List[TempFrameFormat] = list(get_args(TempFrameFormat))
|
||||
|
||||
output_audio_encoders : List[AudioEncoder] = list(get_args(AudioEncoder))
|
||||
output_video_encoders : List[VideoEncoder] = list(get_args(VideoEncoder))
|
||||
output_encoder_set : EncoderSet =\
|
||||
{
|
||||
'audio': [ 'flac', 'aac', 'libmp3lame', 'libopus', 'libvorbis', 'pcm_s16le', 'pcm_s32le' ],
|
||||
'video': [ 'libx264', 'libx264rgb', 'libx265', 'libvpx-vp9', 'h264_nvenc', 'hevc_nvenc', 'h264_amf', 'hevc_amf', 'h264_qsv', 'hevc_qsv', 'h264_videotoolbox', 'hevc_videotoolbox', 'rawvideo' ]
|
||||
'audio': output_audio_encoders,
|
||||
'video': output_video_encoders
|
||||
}
|
||||
output_audio_encoders : List[AudioEncoder] = output_encoder_set.get('audio')
|
||||
output_video_encoders : List[VideoEncoder] = output_encoder_set.get('video')
|
||||
output_video_presets : List[VideoPreset] = [ 'ultrafast', 'superfast', 'veryfast', 'faster', 'fast', 'medium', 'slow', 'slower', 'veryslow' ]
|
||||
output_video_presets : List[VideoPreset] = list(get_args(VideoPreset))
|
||||
|
||||
benchmark_modes : List[BenchmarkMode] = [ 'warm', 'cold' ]
|
||||
benchmark_modes : List[BenchmarkMode] = list(get_args(BenchmarkMode))
|
||||
benchmark_set : BenchmarkSet =\
|
||||
{
|
||||
'240p': '.assets/examples/target-240p.mp4',
|
||||
@@ -97,20 +101,21 @@ benchmark_set : BenchmarkSet =\
|
||||
'1440p': '.assets/examples/target-1440p.mp4',
|
||||
'2160p': '.assets/examples/target-2160p.mp4'
|
||||
}
|
||||
benchmark_resolutions : List[BenchmarkResolution] = list(benchmark_set.keys())
|
||||
benchmark_resolutions : List[BenchmarkResolution] = list(get_args(BenchmarkResolution))
|
||||
|
||||
execution_provider_set : ExecutionProviderSet =\
|
||||
{
|
||||
'cuda': 'CUDAExecutionProvider',
|
||||
'tensorrt': 'TensorrtExecutionProvider',
|
||||
'directml': 'DmlExecutionProvider',
|
||||
'rocm': 'ROCMExecutionProvider',
|
||||
'migraphx': 'MIGraphXExecutionProvider',
|
||||
'openvino': 'OpenVINOExecutionProvider',
|
||||
'coreml': 'CoreMLExecutionProvider',
|
||||
'openvino': 'OpenVINOExecutionProvider',
|
||||
'qnn': 'QNNExecutionProvider',
|
||||
'directml': 'DmlExecutionProvider',
|
||||
'cpu': 'CPUExecutionProvider'
|
||||
}
|
||||
execution_providers : List[ExecutionProvider] = list(execution_provider_set.keys())
|
||||
execution_providers : List[ExecutionProvider] = list(get_args(ExecutionProvider))
|
||||
download_provider_set : DownloadProviderSet =\
|
||||
{
|
||||
'github':
|
||||
@@ -131,10 +136,10 @@ download_provider_set : DownloadProviderSet =\
|
||||
'path': '/facefusion/{base_name}/resolve/main/{file_name}'
|
||||
}
|
||||
}
|
||||
download_providers : List[DownloadProvider] = list(download_provider_set.keys())
|
||||
download_scopes : List[DownloadScope] = [ 'lite', 'full' ]
|
||||
download_providers : List[DownloadProvider] = list(get_args(DownloadProvider))
|
||||
download_scopes : List[DownloadScope] = list(get_args(DownloadScope))
|
||||
|
||||
video_memory_strategies : List[VideoMemoryStrategy] = [ 'strict', 'moderate', 'tolerant' ]
|
||||
video_memory_strategies : List[VideoMemoryStrategy] = list(get_args(VideoMemoryStrategy))
|
||||
|
||||
log_level_set : LogLevelSet =\
|
||||
{
|
||||
@@ -143,14 +148,14 @@ log_level_set : LogLevelSet =\
|
||||
'info': logging.INFO,
|
||||
'debug': logging.DEBUG
|
||||
}
|
||||
log_levels : List[LogLevel] = list(log_level_set.keys())
|
||||
log_levels : List[LogLevel] = list(get_args(LogLevel))
|
||||
|
||||
ui_workflows : List[UiWorkflow] = [ 'instant_runner', 'job_runner', 'job_manager' ]
|
||||
job_statuses : List[JobStatus] = [ 'drafted', 'queued', 'completed', 'failed' ]
|
||||
ui_workflows : List[UiWorkflow] = list(get_args(UiWorkflow))
|
||||
job_statuses : List[JobStatus] = list(get_args(JobStatus))
|
||||
|
||||
benchmark_cycle_count_range : Sequence[int] = create_int_range(1, 10, 1)
|
||||
execution_thread_count_range : Sequence[int] = create_int_range(1, 32, 1)
|
||||
system_memory_limit_range : Sequence[int] = create_int_range(0, 128, 4)
|
||||
face_detector_margin_range : Sequence[int] = create_int_range(0, 100, 1)
|
||||
face_detector_angles : Sequence[Angle] = create_int_range(0, 270, 90)
|
||||
face_detector_score_range : Sequence[Score] = create_float_range(0.0, 1.0, 0.05)
|
||||
face_landmarker_score_range : Sequence[Score] = create_float_range(0.0, 1.0, 0.05)
|
||||
@@ -158,6 +163,8 @@ face_mask_blur_range : Sequence[float] = create_float_range(0.0, 1.0, 0.05)
|
||||
face_mask_padding_range : Sequence[int] = create_int_range(0, 100, 1)
|
||||
face_selector_age_range : Sequence[int] = create_int_range(0, 100, 1)
|
||||
reference_face_distance_range : Sequence[float] = create_float_range(0.0, 1.0, 0.05)
|
||||
face_tracker_score_range : Sequence[Score] = create_float_range(0.0, 0.5, 0.05)
|
||||
target_frame_amount_range : Sequence[int] = create_int_range(0, 10, 1)
|
||||
output_image_quality_range : Sequence[int] = create_int_range(0, 100, 1)
|
||||
output_image_scale_range : Sequence[float] = create_float_range(0.25, 8.0, 0.25)
|
||||
output_audio_quality_range : Sequence[int] = create_int_range(0, 100, 1)
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
from typing import Tuple
|
||||
from typing import List, Tuple
|
||||
|
||||
from facefusion.logger import get_package_logger
|
||||
from facefusion.types import TableContents, TableHeaders
|
||||
from facefusion.types import TableContent, TableHeader
|
||||
|
||||
|
||||
def render_table(headers : TableHeaders, contents : TableContents) -> None:
|
||||
def render_table(headers : List[TableHeader], contents : List[List[TableContent]]) -> None:
|
||||
package_logger = get_package_logger()
|
||||
table_column, table_separator = create_table_parts(headers, contents)
|
||||
|
||||
@@ -19,7 +19,7 @@ def render_table(headers : TableHeaders, contents : TableContents) -> None:
|
||||
package_logger.critical(table_separator)
|
||||
|
||||
|
||||
def create_table_parts(headers : TableHeaders, contents : TableContents) -> Tuple[str, str]:
|
||||
def create_table_parts(headers : List[TableHeader], contents : List[List[TableContent]]) -> Tuple[str, str]:
|
||||
column_parts = []
|
||||
separator_parts = []
|
||||
widths = [ len(header) for header in headers ]
|
||||
|
||||
@@ -78,6 +78,12 @@ def get_first(__list__ : Any) -> Any:
|
||||
return None
|
||||
|
||||
|
||||
def get_middle(__list__ : Any) -> Any:
|
||||
if isinstance(__list__, Sequence) and __list__:
|
||||
return __list__[len(__list__) // 2]
|
||||
return None
|
||||
|
||||
|
||||
def get_last(__list__ : Any) -> Any:
|
||||
if isinstance(__list__, Reversible):
|
||||
return next(reversed(__list__), None)
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import os
|
||||
import sys
|
||||
from typing import List
|
||||
|
||||
from facefusion.common_helper import is_linux, is_windows
|
||||
|
||||
|
||||
def setup() -> None:
|
||||
conda_prefix = os.getenv('CONDA_PREFIX')
|
||||
conda_ready = os.getenv('CONDA_READY')
|
||||
|
||||
if conda_prefix and not conda_ready:
|
||||
if is_linux():
|
||||
python_id = 'python' + str(sys.version_info.major) + '.' + str(sys.version_info.minor)
|
||||
library_paths : List[str] =\
|
||||
[
|
||||
os.path.join(conda_prefix, 'lib'),
|
||||
os.path.join(conda_prefix, 'lib', python_id, 'site-packages', 'tensorrt_libs')
|
||||
]
|
||||
library_paths = list(filter(os.path.exists, library_paths))
|
||||
|
||||
if library_paths:
|
||||
if os.getenv('LD_LIBRARY_PATH'):
|
||||
library_paths.append(os.getenv('LD_LIBRARY_PATH'))
|
||||
os.environ['LD_LIBRARY_PATH'] = os.pathsep.join(library_paths)
|
||||
os.environ['CONDA_READY'] = '1'
|
||||
os.execv(sys.executable, [ sys.executable ] + sys.argv)
|
||||
|
||||
if is_windows():
|
||||
library_paths =\
|
||||
[
|
||||
os.path.join(conda_prefix, 'Lib'),
|
||||
os.path.join(conda_prefix, 'Lib', 'site-packages', 'tensorrt_libs')
|
||||
]
|
||||
library_paths = list(filter(os.path.exists, library_paths))
|
||||
|
||||
if library_paths:
|
||||
if os.getenv('PATH'):
|
||||
library_paths.append(os.getenv('PATH'))
|
||||
os.environ['PATH'] = os.pathsep.join(library_paths)
|
||||
os.environ['CONDA_READY'] = '1'
|
||||
+12
-21
@@ -1,29 +1,20 @@
|
||||
from configparser import ConfigParser
|
||||
from functools import lru_cache
|
||||
from typing import List, Optional
|
||||
|
||||
from facefusion import state_manager
|
||||
from facefusion.common_helper import cast_bool, cast_float, cast_int
|
||||
|
||||
CONFIG_PARSER = None
|
||||
|
||||
|
||||
def get_config_parser() -> ConfigParser:
|
||||
global CONFIG_PARSER
|
||||
|
||||
if CONFIG_PARSER is None:
|
||||
CONFIG_PARSER = ConfigParser()
|
||||
CONFIG_PARSER.read(state_manager.get_item('config_path'), encoding = 'utf-8')
|
||||
return CONFIG_PARSER
|
||||
|
||||
|
||||
def clear_config_parser() -> None:
|
||||
global CONFIG_PARSER
|
||||
|
||||
CONFIG_PARSER = None
|
||||
@lru_cache
|
||||
def get_static_config_parser() -> ConfigParser:
|
||||
config_parser = ConfigParser()
|
||||
config_parser.read(state_manager.get_item('config_path'), encoding = 'utf-8')
|
||||
return config_parser
|
||||
|
||||
|
||||
def get_str_value(section : str, option : str, fallback : Optional[str] = None) -> Optional[str]:
|
||||
config_parser = get_config_parser()
|
||||
config_parser = get_static_config_parser()
|
||||
|
||||
if config_parser.has_option(section, option) and config_parser.get(section, option).strip():
|
||||
return config_parser.get(section, option)
|
||||
@@ -31,7 +22,7 @@ def get_str_value(section : str, option : str, fallback : Optional[str] = None)
|
||||
|
||||
|
||||
def get_int_value(section : str, option : str, fallback : Optional[str] = None) -> Optional[int]:
|
||||
config_parser = get_config_parser()
|
||||
config_parser = get_static_config_parser()
|
||||
|
||||
if config_parser.has_option(section, option) and config_parser.get(section, option).strip():
|
||||
return config_parser.getint(section, option)
|
||||
@@ -39,7 +30,7 @@ def get_int_value(section : str, option : str, fallback : Optional[str] = None)
|
||||
|
||||
|
||||
def get_float_value(section : str, option : str, fallback : Optional[str] = None) -> Optional[float]:
|
||||
config_parser = get_config_parser()
|
||||
config_parser = get_static_config_parser()
|
||||
|
||||
if config_parser.has_option(section, option) and config_parser.get(section, option).strip():
|
||||
return config_parser.getfloat(section, option)
|
||||
@@ -47,7 +38,7 @@ def get_float_value(section : str, option : str, fallback : Optional[str] = None
|
||||
|
||||
|
||||
def get_bool_value(section : str, option : str, fallback : Optional[str] = None) -> Optional[bool]:
|
||||
config_parser = get_config_parser()
|
||||
config_parser = get_static_config_parser()
|
||||
|
||||
if config_parser.has_option(section, option) and config_parser.get(section, option).strip():
|
||||
return config_parser.getboolean(section, option)
|
||||
@@ -55,7 +46,7 @@ def get_bool_value(section : str, option : str, fallback : Optional[str] = None)
|
||||
|
||||
|
||||
def get_str_list(section : str, option : str, fallback : Optional[str] = None) -> Optional[List[str]]:
|
||||
config_parser = get_config_parser()
|
||||
config_parser = get_static_config_parser()
|
||||
|
||||
if config_parser.has_option(section, option) and config_parser.get(section, option).strip():
|
||||
return config_parser.get(section, option).split()
|
||||
@@ -65,7 +56,7 @@ def get_str_list(section : str, option : str, fallback : Optional[str] = None) -
|
||||
|
||||
|
||||
def get_int_list(section : str, option : str, fallback : Optional[str] = None) -> Optional[List[int]]:
|
||||
config_parser = get_config_parser()
|
||||
config_parser = get_static_config_parser()
|
||||
|
||||
if config_parser.has_option(section, option) and config_parser.get(section, option).strip():
|
||||
return list(map(int, config_parser.get(section, option).split()))
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
from functools import lru_cache
|
||||
from typing import List, Tuple
|
||||
from typing import Tuple
|
||||
|
||||
import numpy
|
||||
from tqdm import tqdm
|
||||
|
||||
from facefusion import inference_manager, state_manager, wording
|
||||
from facefusion.common_helper import is_macos
|
||||
from facefusion import inference_manager, state_manager, translator
|
||||
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
||||
from facefusion.execution import has_execution_provider
|
||||
from facefusion.filesystem import resolve_relative_path
|
||||
from facefusion.thread_helper import conditional_thread_semaphore
|
||||
from facefusion.types import Detection, DownloadScope, DownloadSet, ExecutionProvider, Fps, InferencePool, ModelSet, VisionFrame
|
||||
from facefusion.types import Detection, DownloadScope, DownloadSet, Fps, InferencePool, ModelSet, VisionFrame
|
||||
from facefusion.vision import detect_video_fps, fit_contain_frame, read_image, read_video_frame
|
||||
|
||||
STREAM_COUNTER = 0
|
||||
@@ -22,6 +20,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
{
|
||||
'nsfw_1':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'EraX',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2024
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'content_analyser':
|
||||
@@ -44,6 +48,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'nsfw_2':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'Marqo',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2024
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'content_analyser':
|
||||
@@ -66,6 +76,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'nsfw_3':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'Freepik',
|
||||
'license': 'MIT',
|
||||
'year': 2025
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'content_analyser':
|
||||
@@ -101,12 +117,6 @@ def clear_inference_pool() -> None:
|
||||
inference_manager.clear_inference_pool(__name__, model_names)
|
||||
|
||||
|
||||
def resolve_execution_providers() -> List[ExecutionProvider]:
|
||||
if is_macos() and has_execution_provider('coreml'):
|
||||
return [ 'cpu' ]
|
||||
return state_manager.get_item('execution_providers')
|
||||
|
||||
|
||||
def collect_model_downloads() -> Tuple[DownloadSet, DownloadSet]:
|
||||
model_set = create_static_model_set('full')
|
||||
model_hash_set = {}
|
||||
@@ -152,16 +162,21 @@ def analyse_video(video_path : str, trim_frame_start : int, trim_frame_end : int
|
||||
total = 0
|
||||
counter = 0
|
||||
|
||||
with tqdm(total = len(frame_range), desc = wording.get('analysing'), unit = 'frame', ascii = ' =', disable = state_manager.get_item('log_level') in [ 'warn', 'error' ]) as progress:
|
||||
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:
|
||||
|
||||
for frame_number in frame_range:
|
||||
if frame_number % int(video_fps) == 0:
|
||||
vision_frame = read_video_frame(video_path, frame_number)
|
||||
|
||||
if numpy.any(vision_frame):
|
||||
total += 1
|
||||
|
||||
if analyse_frame(vision_frame):
|
||||
counter += 1
|
||||
|
||||
if counter > 0 and total > 0:
|
||||
rate = counter / total * 100
|
||||
|
||||
progress.set_postfix(rate = rate)
|
||||
progress.update()
|
||||
|
||||
|
||||
+64
-293
@@ -3,31 +3,20 @@ import itertools
|
||||
import shutil
|
||||
import signal
|
||||
import sys
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from time import time
|
||||
|
||||
import numpy
|
||||
from tqdm import tqdm
|
||||
|
||||
from facefusion import benchmarker, cli_helper, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, hash_helper, logger, process_manager, state_manager, video_manager, voice_extractor, wording
|
||||
from facefusion import benchmarker, cli_helper, content_analyser, hash_helper, logger, state_manager, translator
|
||||
from facefusion.args import apply_args, collect_job_args, reduce_job_args, reduce_step_args
|
||||
from facefusion.audio import create_empty_audio_frame, get_audio_frame, get_voice_frame
|
||||
from facefusion.common_helper import get_first
|
||||
from facefusion.content_analyser import analyse_image, analyse_video
|
||||
from facefusion.download import conditional_download_hashes, conditional_download_sources
|
||||
from facefusion.exit_helper import hard_exit, signal_exit
|
||||
from facefusion.ffmpeg import copy_image, extract_frames, finalize_image, merge_video, replace_audio, restore_audio
|
||||
from facefusion.filesystem import filter_audio_paths, get_file_name, is_image, is_video, resolve_file_paths, resolve_file_pattern
|
||||
from facefusion.filesystem import get_file_extension, get_file_name, is_image, is_video, resolve_file_paths, resolve_file_pattern
|
||||
from facefusion.jobs import job_helper, job_manager, job_runner
|
||||
from facefusion.jobs.job_list import compose_job_list
|
||||
from facefusion.memory import limit_system_memory
|
||||
from facefusion.processors.core import get_processors_modules
|
||||
from facefusion.program import create_program
|
||||
from facefusion.program_helper import validate_args
|
||||
from facefusion.temp_helper import clear_temp_directory, create_temp_directory, get_temp_file_path, move_temp_file, resolve_temp_frame_paths
|
||||
from facefusion.time_helper import calculate_end_time
|
||||
from facefusion.types import Args, ErrorCode
|
||||
from facefusion.vision import detect_image_resolution, detect_video_resolution, pack_resolution, read_static_image, read_static_images, read_static_video_frame, restrict_image_resolution, restrict_trim_frame, restrict_video_fps, restrict_video_resolution, scale_resolution, write_image
|
||||
from facefusion.workflows import image_to_image, image_to_video
|
||||
|
||||
|
||||
def cli() -> None:
|
||||
@@ -51,11 +40,6 @@ def cli() -> None:
|
||||
|
||||
|
||||
def route(args : Args) -> None:
|
||||
system_memory_limit = state_manager.get_item('system_memory_limit')
|
||||
|
||||
if system_memory_limit and system_memory_limit > 0:
|
||||
limit_system_memory(system_memory_limit)
|
||||
|
||||
if state_manager.get_item('command') == 'force-download':
|
||||
error_code = force_download()
|
||||
hard_exit(error_code)
|
||||
@@ -85,14 +69,14 @@ def route(args : Args) -> None:
|
||||
if state_manager.get_item('command') == 'headless-run':
|
||||
if not job_manager.init_jobs(state_manager.get_item('jobs_path')):
|
||||
hard_exit(1)
|
||||
error_core = process_headless(args)
|
||||
hard_exit(error_core)
|
||||
error_code = process_headless(args)
|
||||
hard_exit(error_code)
|
||||
|
||||
if state_manager.get_item('command') == 'batch-run':
|
||||
if not job_manager.init_jobs(state_manager.get_item('jobs_path')):
|
||||
hard_exit(1)
|
||||
error_core = process_batch(args)
|
||||
hard_exit(error_core)
|
||||
error_code = process_batch(args)
|
||||
hard_exit(error_code)
|
||||
|
||||
if state_manager.get_item('command') in [ 'job-run', 'job-run-all', 'job-retry', 'job-retry-all' ]:
|
||||
if not job_manager.init_jobs(state_manager.get_item('jobs_path')):
|
||||
@@ -103,35 +87,23 @@ def route(args : Args) -> None:
|
||||
|
||||
def pre_check() -> bool:
|
||||
if sys.version_info < (3, 10):
|
||||
logger.error(wording.get('python_not_supported').format(version = '3.10'), __name__)
|
||||
logger.error(translator.get('python_not_supported').format(version = '3.10'), __name__)
|
||||
return False
|
||||
|
||||
if not shutil.which('curl'):
|
||||
logger.error(wording.get('curl_not_installed'), __name__)
|
||||
logger.error(translator.get('curl_not_installed'), __name__)
|
||||
return False
|
||||
|
||||
if not shutil.which('ffmpeg'):
|
||||
logger.error(wording.get('ffmpeg_not_installed'), __name__)
|
||||
logger.error(translator.get('ffmpeg_not_installed'), __name__)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def common_pre_check() -> bool:
|
||||
common_modules =\
|
||||
[
|
||||
content_analyser,
|
||||
face_classifier,
|
||||
face_detector,
|
||||
face_landmarker,
|
||||
face_masker,
|
||||
face_recognizer,
|
||||
voice_extractor
|
||||
]
|
||||
|
||||
content_analyser_content = inspect.getsource(content_analyser).encode()
|
||||
content_analyser_hash = hash_helper.create_hash(content_analyser_content)
|
||||
|
||||
return all(module.pre_check() for module in common_modules) and content_analyser_hash == '803b5ec7'
|
||||
return hash_helper.create_hash(content_analyser_content) == '975d67d6'
|
||||
|
||||
|
||||
def processors_pre_check() -> bool:
|
||||
@@ -142,22 +114,19 @@ def processors_pre_check() -> bool:
|
||||
|
||||
|
||||
def force_download() -> ErrorCode:
|
||||
common_modules =\
|
||||
[
|
||||
content_analyser,
|
||||
face_classifier,
|
||||
face_detector,
|
||||
face_landmarker,
|
||||
face_masker,
|
||||
face_recognizer,
|
||||
voice_extractor
|
||||
]
|
||||
download_scope = state_manager.get_item('download_scope')
|
||||
available_processors = [ get_file_name(file_path) for file_path in resolve_file_paths('facefusion/processors/modules') ]
|
||||
processor_modules = get_processors_modules(available_processors)
|
||||
common_modules = []
|
||||
|
||||
for processor_module in processor_modules:
|
||||
for common_module in processor_module.get_common_modules():
|
||||
if common_module not in common_modules:
|
||||
common_modules.append(common_module)
|
||||
|
||||
for module in common_modules + processor_modules:
|
||||
if hasattr(module, 'create_static_model_set'):
|
||||
for model in module.create_static_model_set(state_manager.get_item('download_scope')).values():
|
||||
for model in module.create_static_model_set(download_scope).values():
|
||||
model_hash_set = model.get('hashes')
|
||||
model_source_set = model.get('sources')
|
||||
|
||||
@@ -179,106 +148,106 @@ def route_job_manager(args : Args) -> ErrorCode:
|
||||
|
||||
if state_manager.get_item('command') == 'job-create':
|
||||
if job_manager.create_job(state_manager.get_item('job_id')):
|
||||
logger.info(wording.get('job_created').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
logger.info(translator.get('job_created').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
return 0
|
||||
logger.error(wording.get('job_not_created').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
logger.error(translator.get('job_not_created').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
return 1
|
||||
|
||||
if state_manager.get_item('command') == 'job-submit':
|
||||
if job_manager.submit_job(state_manager.get_item('job_id')):
|
||||
logger.info(wording.get('job_submitted').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
logger.info(translator.get('job_submitted').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
return 0
|
||||
logger.error(wording.get('job_not_submitted').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
logger.error(translator.get('job_not_submitted').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
return 1
|
||||
|
||||
if state_manager.get_item('command') == 'job-submit-all':
|
||||
if job_manager.submit_jobs(state_manager.get_item('halt_on_error')):
|
||||
logger.info(wording.get('job_all_submitted'), __name__)
|
||||
logger.info(translator.get('job_all_submitted'), __name__)
|
||||
return 0
|
||||
logger.error(wording.get('job_all_not_submitted'), __name__)
|
||||
logger.error(translator.get('job_all_not_submitted'), __name__)
|
||||
return 1
|
||||
|
||||
if state_manager.get_item('command') == 'job-delete':
|
||||
if job_manager.delete_job(state_manager.get_item('job_id')):
|
||||
logger.info(wording.get('job_deleted').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
logger.info(translator.get('job_deleted').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
return 0
|
||||
logger.error(wording.get('job_not_deleted').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
logger.error(translator.get('job_not_deleted').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
return 1
|
||||
|
||||
if state_manager.get_item('command') == 'job-delete-all':
|
||||
if job_manager.delete_jobs(state_manager.get_item('halt_on_error')):
|
||||
logger.info(wording.get('job_all_deleted'), __name__)
|
||||
logger.info(translator.get('job_all_deleted'), __name__)
|
||||
return 0
|
||||
logger.error(wording.get('job_all_not_deleted'), __name__)
|
||||
logger.error(translator.get('job_all_not_deleted'), __name__)
|
||||
return 1
|
||||
|
||||
if state_manager.get_item('command') == 'job-add-step':
|
||||
step_args = reduce_step_args(args)
|
||||
|
||||
if job_manager.add_step(state_manager.get_item('job_id'), step_args):
|
||||
logger.info(wording.get('job_step_added').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
logger.info(translator.get('job_step_added').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
return 0
|
||||
logger.error(wording.get('job_step_not_added').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
logger.error(translator.get('job_step_not_added').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
return 1
|
||||
|
||||
if state_manager.get_item('command') == 'job-remix-step':
|
||||
step_args = reduce_step_args(args)
|
||||
|
||||
if job_manager.remix_step(state_manager.get_item('job_id'), state_manager.get_item('step_index'), step_args):
|
||||
logger.info(wording.get('job_remix_step_added').format(job_id = state_manager.get_item('job_id'), step_index = state_manager.get_item('step_index')), __name__)
|
||||
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__)
|
||||
return 0
|
||||
logger.error(wording.get('job_remix_step_not_added').format(job_id = state_manager.get_item('job_id'), step_index = state_manager.get_item('step_index')), __name__)
|
||||
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__)
|
||||
return 1
|
||||
|
||||
if state_manager.get_item('command') == 'job-insert-step':
|
||||
step_args = reduce_step_args(args)
|
||||
|
||||
if job_manager.insert_step(state_manager.get_item('job_id'), state_manager.get_item('step_index'), step_args):
|
||||
logger.info(wording.get('job_step_inserted').format(job_id = state_manager.get_item('job_id'), step_index = state_manager.get_item('step_index')), __name__)
|
||||
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__)
|
||||
return 0
|
||||
logger.error(wording.get('job_step_not_inserted').format(job_id = state_manager.get_item('job_id'), step_index = state_manager.get_item('step_index')), __name__)
|
||||
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__)
|
||||
return 1
|
||||
|
||||
if state_manager.get_item('command') == 'job-remove-step':
|
||||
if job_manager.remove_step(state_manager.get_item('job_id'), state_manager.get_item('step_index')):
|
||||
logger.info(wording.get('job_step_removed').format(job_id = state_manager.get_item('job_id'), step_index = state_manager.get_item('step_index')), __name__)
|
||||
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__)
|
||||
return 0
|
||||
logger.error(wording.get('job_step_not_removed').format(job_id = state_manager.get_item('job_id'), step_index = state_manager.get_item('step_index')), __name__)
|
||||
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__)
|
||||
return 1
|
||||
return 1
|
||||
|
||||
|
||||
def route_job_runner() -> ErrorCode:
|
||||
if state_manager.get_item('command') == 'job-run':
|
||||
logger.info(wording.get('running_job').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
logger.info(translator.get('running_job').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
if job_runner.run_job(state_manager.get_item('job_id'), process_step):
|
||||
logger.info(wording.get('processing_job_succeeded').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
logger.info(translator.get('processing_job_succeeded').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
return 0
|
||||
logger.info(wording.get('processing_job_failed').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
logger.info(translator.get('processing_job_failed').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
return 1
|
||||
|
||||
if state_manager.get_item('command') == 'job-run-all':
|
||||
logger.info(wording.get('running_jobs'), __name__)
|
||||
logger.info(translator.get('running_jobs'), __name__)
|
||||
if job_runner.run_jobs(process_step, state_manager.get_item('halt_on_error')):
|
||||
logger.info(wording.get('processing_jobs_succeeded'), __name__)
|
||||
logger.info(translator.get('processing_jobs_succeeded'), __name__)
|
||||
return 0
|
||||
logger.info(wording.get('processing_jobs_failed'), __name__)
|
||||
logger.info(translator.get('processing_jobs_failed'), __name__)
|
||||
return 1
|
||||
|
||||
if state_manager.get_item('command') == 'job-retry':
|
||||
logger.info(wording.get('retrying_job').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
logger.info(translator.get('retrying_job').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
if job_runner.retry_job(state_manager.get_item('job_id'), process_step):
|
||||
logger.info(wording.get('processing_job_succeeded').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
logger.info(translator.get('processing_job_succeeded').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
return 0
|
||||
logger.info(wording.get('processing_job_failed').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
logger.info(translator.get('processing_job_failed').format(job_id = state_manager.get_item('job_id')), __name__)
|
||||
return 1
|
||||
|
||||
if state_manager.get_item('command') == 'job-retry-all':
|
||||
logger.info(wording.get('retrying_jobs'), __name__)
|
||||
logger.info(translator.get('retrying_jobs'), __name__)
|
||||
if job_runner.retry_jobs(process_step, state_manager.get_item('halt_on_error')):
|
||||
logger.info(wording.get('processing_jobs_succeeded'), __name__)
|
||||
logger.info(translator.get('processing_jobs_succeeded'), __name__)
|
||||
return 0
|
||||
logger.info(wording.get('processing_jobs_failed'), __name__)
|
||||
logger.info(translator.get('processing_jobs_failed'), __name__)
|
||||
return 1
|
||||
return 2
|
||||
|
||||
@@ -304,7 +273,12 @@ def process_batch(args : Args) -> ErrorCode:
|
||||
for index, (source_path, target_path) in enumerate(itertools.product(source_paths, target_paths)):
|
||||
step_args['source_paths'] = [ source_path ]
|
||||
step_args['target_path'] = target_path
|
||||
step_args['output_path'] = job_args.get('output_pattern').format(index = index)
|
||||
|
||||
try:
|
||||
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))
|
||||
except KeyError:
|
||||
return 1
|
||||
|
||||
if not job_manager.add_step(job_id, step_args):
|
||||
return 1
|
||||
if job_manager.submit_job(job_id) and job_runner.run_job(job_id, process_step):
|
||||
@@ -313,7 +287,12 @@ def process_batch(args : Args) -> ErrorCode:
|
||||
if not source_paths and target_paths:
|
||||
for index, target_path in enumerate(target_paths):
|
||||
step_args['target_path'] = target_path
|
||||
step_args['output_path'] = job_args.get('output_pattern').format(index = index)
|
||||
|
||||
try:
|
||||
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))
|
||||
except KeyError:
|
||||
return 1
|
||||
|
||||
if not job_manager.add_step(job_id, step_args):
|
||||
return 1
|
||||
if job_manager.submit_job(job_id) and job_runner.run_job(job_id, process_step):
|
||||
@@ -326,7 +305,7 @@ def process_step(job_id : str, step_index : int, step_args : Args) -> bool:
|
||||
step_args.update(collect_job_args())
|
||||
apply_args(step_args, state_manager.set_item)
|
||||
|
||||
logger.info(wording.get('processing_step').format(step_current = step_index + 1, step_total = step_total), __name__)
|
||||
logger.info(translator.get('processing_step').format(step_current = step_index + 1, step_total = step_total), __name__)
|
||||
if common_pre_check() and processors_pre_check():
|
||||
error_code = conditional_process()
|
||||
return error_code == 0
|
||||
@@ -341,218 +320,10 @@ def conditional_process() -> ErrorCode:
|
||||
return 2
|
||||
|
||||
if is_image(state_manager.get_item('target_path')):
|
||||
return process_image(start_time)
|
||||
return image_to_image.process(start_time)
|
||||
if is_video(state_manager.get_item('target_path')):
|
||||
return process_video(start_time)
|
||||
return image_to_video.process(start_time)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
def process_image(start_time : float) -> ErrorCode:
|
||||
if analyse_image(state_manager.get_item('target_path')):
|
||||
return 3
|
||||
|
||||
logger.debug(wording.get('clearing_temp'), __name__)
|
||||
clear_temp_directory(state_manager.get_item('target_path'))
|
||||
logger.debug(wording.get('creating_temp'), __name__)
|
||||
create_temp_directory(state_manager.get_item('target_path'))
|
||||
|
||||
process_manager.start()
|
||||
|
||||
output_image_resolution = scale_resolution(detect_image_resolution(state_manager.get_item('target_path')), state_manager.get_item('output_image_scale'))
|
||||
temp_image_resolution = restrict_image_resolution(state_manager.get_item('target_path'), output_image_resolution)
|
||||
logger.info(wording.get('copying_image').format(resolution = pack_resolution(temp_image_resolution)), __name__)
|
||||
if copy_image(state_manager.get_item('target_path'), temp_image_resolution):
|
||||
logger.debug(wording.get('copying_image_succeeded'), __name__)
|
||||
else:
|
||||
logger.error(wording.get('copying_image_failed'), __name__)
|
||||
process_manager.end()
|
||||
return 1
|
||||
|
||||
temp_image_path = get_temp_file_path(state_manager.get_item('target_path'))
|
||||
reference_vision_frame = read_static_image(temp_image_path)
|
||||
source_vision_frames = read_static_images(state_manager.get_item('source_paths'))
|
||||
source_audio_frame = create_empty_audio_frame()
|
||||
source_voice_frame = create_empty_audio_frame()
|
||||
target_vision_frame = read_static_image(temp_image_path)
|
||||
temp_vision_frame = target_vision_frame.copy()
|
||||
|
||||
for processor_module in get_processors_modules(state_manager.get_item('processors')):
|
||||
logger.info(wording.get('processing'), processor_module.__name__)
|
||||
|
||||
temp_vision_frame = processor_module.process_frame(
|
||||
{
|
||||
'reference_vision_frame': reference_vision_frame,
|
||||
'source_vision_frames': source_vision_frames,
|
||||
'source_audio_frame': source_audio_frame,
|
||||
'source_voice_frame': source_voice_frame,
|
||||
'target_vision_frame': target_vision_frame,
|
||||
'temp_vision_frame': temp_vision_frame
|
||||
})
|
||||
|
||||
processor_module.post_process()
|
||||
|
||||
write_image(temp_image_path, temp_vision_frame)
|
||||
if is_process_stopping():
|
||||
return 4
|
||||
|
||||
logger.info(wording.get('finalizing_image').format(resolution = pack_resolution(output_image_resolution)), __name__)
|
||||
if finalize_image(state_manager.get_item('target_path'), state_manager.get_item('output_path'), output_image_resolution):
|
||||
logger.debug(wording.get('finalizing_image_succeeded'), __name__)
|
||||
else:
|
||||
logger.warn(wording.get('finalizing_image_skipped'), __name__)
|
||||
|
||||
logger.debug(wording.get('clearing_temp'), __name__)
|
||||
clear_temp_directory(state_manager.get_item('target_path'))
|
||||
|
||||
if is_image(state_manager.get_item('output_path')):
|
||||
logger.info(wording.get('processing_image_succeeded').format(seconds = calculate_end_time(start_time)), __name__)
|
||||
else:
|
||||
logger.error(wording.get('processing_image_failed'), __name__)
|
||||
process_manager.end()
|
||||
return 1
|
||||
process_manager.end()
|
||||
return 0
|
||||
|
||||
|
||||
def process_video(start_time : float) -> ErrorCode:
|
||||
trim_frame_start, trim_frame_end = restrict_trim_frame(state_manager.get_item('target_path'), state_manager.get_item('trim_frame_start'), state_manager.get_item('trim_frame_end'))
|
||||
if analyse_video(state_manager.get_item('target_path'), trim_frame_start, trim_frame_end):
|
||||
return 3
|
||||
|
||||
logger.debug(wording.get('clearing_temp'), __name__)
|
||||
clear_temp_directory(state_manager.get_item('target_path'))
|
||||
logger.debug(wording.get('creating_temp'), __name__)
|
||||
create_temp_directory(state_manager.get_item('target_path'))
|
||||
|
||||
process_manager.start()
|
||||
output_video_resolution = scale_resolution(detect_video_resolution(state_manager.get_item('target_path')), state_manager.get_item('output_video_scale'))
|
||||
temp_video_resolution = restrict_video_resolution(state_manager.get_item('target_path'), output_video_resolution)
|
||||
temp_video_fps = restrict_video_fps(state_manager.get_item('target_path'), state_manager.get_item('output_video_fps'))
|
||||
logger.info(wording.get('extracting_frames').format(resolution = pack_resolution(temp_video_resolution), fps = temp_video_fps), __name__)
|
||||
|
||||
if extract_frames(state_manager.get_item('target_path'), temp_video_resolution, temp_video_fps, trim_frame_start, trim_frame_end):
|
||||
logger.debug(wording.get('extracting_frames_succeeded'), __name__)
|
||||
else:
|
||||
if is_process_stopping():
|
||||
return 4
|
||||
logger.error(wording.get('extracting_frames_failed'), __name__)
|
||||
process_manager.end()
|
||||
return 1
|
||||
|
||||
temp_frame_paths = resolve_temp_frame_paths(state_manager.get_item('target_path'))
|
||||
|
||||
if temp_frame_paths:
|
||||
with tqdm(total = len(temp_frame_paths), desc = wording.get('processing'), unit = 'frame', ascii = ' =', disable = state_manager.get_item('log_level') in [ 'warn', 'error' ]) as progress:
|
||||
progress.set_postfix(execution_providers = state_manager.get_item('execution_providers'))
|
||||
|
||||
with ThreadPoolExecutor(max_workers = state_manager.get_item('execution_thread_count')) as executor:
|
||||
futures = []
|
||||
|
||||
for frame_number, temp_frame_path in enumerate(temp_frame_paths):
|
||||
future = executor.submit(process_temp_frame, temp_frame_path, frame_number)
|
||||
futures.append(future)
|
||||
|
||||
for future in as_completed(futures):
|
||||
if is_process_stopping():
|
||||
for __future__ in futures:
|
||||
__future__.cancel()
|
||||
|
||||
if not future.cancelled():
|
||||
future.result()
|
||||
progress.update()
|
||||
|
||||
for processor_module in get_processors_modules(state_manager.get_item('processors')):
|
||||
processor_module.post_process()
|
||||
|
||||
if is_process_stopping():
|
||||
return 4
|
||||
else:
|
||||
logger.error(wording.get('temp_frames_not_found'), __name__)
|
||||
process_manager.end()
|
||||
return 1
|
||||
|
||||
logger.info(wording.get('merging_video').format(resolution = pack_resolution(output_video_resolution), fps = state_manager.get_item('output_video_fps')), __name__)
|
||||
if merge_video(state_manager.get_item('target_path'), temp_video_fps, output_video_resolution, state_manager.get_item('output_video_fps'), trim_frame_start, trim_frame_end):
|
||||
logger.debug(wording.get('merging_video_succeeded'), __name__)
|
||||
else:
|
||||
if is_process_stopping():
|
||||
return 4
|
||||
logger.error(wording.get('merging_video_failed'), __name__)
|
||||
process_manager.end()
|
||||
return 1
|
||||
|
||||
if state_manager.get_item('output_audio_volume') == 0:
|
||||
logger.info(wording.get('skipping_audio'), __name__)
|
||||
move_temp_file(state_manager.get_item('target_path'), state_manager.get_item('output_path'))
|
||||
else:
|
||||
source_audio_path = get_first(filter_audio_paths(state_manager.get_item('source_paths')))
|
||||
if source_audio_path:
|
||||
if replace_audio(state_manager.get_item('target_path'), source_audio_path, state_manager.get_item('output_path')):
|
||||
video_manager.clear_video_pool()
|
||||
logger.debug(wording.get('replacing_audio_succeeded'), __name__)
|
||||
else:
|
||||
video_manager.clear_video_pool()
|
||||
if is_process_stopping():
|
||||
return 4
|
||||
logger.warn(wording.get('replacing_audio_skipped'), __name__)
|
||||
move_temp_file(state_manager.get_item('target_path'), state_manager.get_item('output_path'))
|
||||
else:
|
||||
if restore_audio(state_manager.get_item('target_path'), state_manager.get_item('output_path'), trim_frame_start, trim_frame_end):
|
||||
video_manager.clear_video_pool()
|
||||
logger.debug(wording.get('restoring_audio_succeeded'), __name__)
|
||||
else:
|
||||
video_manager.clear_video_pool()
|
||||
if is_process_stopping():
|
||||
return 4
|
||||
logger.warn(wording.get('restoring_audio_skipped'), __name__)
|
||||
move_temp_file(state_manager.get_item('target_path'), state_manager.get_item('output_path'))
|
||||
|
||||
logger.debug(wording.get('clearing_temp'), __name__)
|
||||
clear_temp_directory(state_manager.get_item('target_path'))
|
||||
|
||||
if is_video(state_manager.get_item('output_path')):
|
||||
logger.info(wording.get('processing_video_succeeded').format(seconds = calculate_end_time(start_time)), __name__)
|
||||
else:
|
||||
logger.error(wording.get('processing_video_failed'), __name__)
|
||||
process_manager.end()
|
||||
return 1
|
||||
process_manager.end()
|
||||
return 0
|
||||
|
||||
|
||||
def process_temp_frame(temp_frame_path : str, frame_number : int) -> bool:
|
||||
reference_vision_frame = read_static_video_frame(state_manager.get_item('target_path'), state_manager.get_item('reference_frame_number'))
|
||||
source_vision_frames = read_static_images(state_manager.get_item('source_paths'))
|
||||
source_audio_path = get_first(filter_audio_paths(state_manager.get_item('source_paths')))
|
||||
temp_video_fps = restrict_video_fps(state_manager.get_item('target_path'), state_manager.get_item('output_video_fps'))
|
||||
target_vision_frame = read_static_image(temp_frame_path)
|
||||
temp_vision_frame = target_vision_frame.copy()
|
||||
|
||||
source_audio_frame = get_audio_frame(source_audio_path, temp_video_fps, frame_number)
|
||||
source_voice_frame = get_voice_frame(source_audio_path, temp_video_fps, frame_number)
|
||||
|
||||
if not numpy.any(source_audio_frame):
|
||||
source_audio_frame = create_empty_audio_frame()
|
||||
if not numpy.any(source_voice_frame):
|
||||
source_voice_frame = create_empty_audio_frame()
|
||||
|
||||
for processor_module in get_processors_modules(state_manager.get_item('processors')):
|
||||
temp_vision_frame = processor_module.process_frame(
|
||||
{
|
||||
'reference_vision_frame': reference_vision_frame,
|
||||
'source_vision_frames': source_vision_frames,
|
||||
'source_audio_frame': source_audio_frame,
|
||||
'source_voice_frame': source_voice_frame,
|
||||
'target_vision_frame': target_vision_frame,
|
||||
'temp_vision_frame': temp_vision_frame
|
||||
})
|
||||
|
||||
return write_image(temp_frame_path, temp_vision_frame)
|
||||
|
||||
|
||||
def is_process_stopping() -> bool:
|
||||
if process_manager.is_stopping():
|
||||
process_manager.end()
|
||||
logger.info(wording.get('processing_stopped'), __name__)
|
||||
return process_manager.is_pending()
|
||||
|
||||
@@ -1,27 +1,32 @@
|
||||
import itertools
|
||||
import shutil
|
||||
from typing import List
|
||||
|
||||
from facefusion import metadata
|
||||
from facefusion.types import Commands
|
||||
from facefusion.types import Command
|
||||
|
||||
|
||||
def run(commands : Commands) -> Commands:
|
||||
def run(commands : List[Command]) -> List[Command]:
|
||||
user_agent = metadata.get('name') + '/' + metadata.get('version')
|
||||
|
||||
return [ shutil.which('curl'), '--user-agent', user_agent, '--insecure', '--location', '--silent' ] + commands
|
||||
return [ shutil.which('curl'), '--user-agent', user_agent, '--location', '--silent', '--ssl-no-revoke' ] + commands
|
||||
|
||||
|
||||
def chain(*commands : Commands) -> Commands:
|
||||
def chain(*commands : List[Command]) -> List[Command]:
|
||||
return list(itertools.chain(*commands))
|
||||
|
||||
|
||||
def head(url : str) -> Commands:
|
||||
def ping(url : str) -> List[Command]:
|
||||
return [ '-I', url ]
|
||||
|
||||
|
||||
def download(url : str, download_file_path : str) -> Commands:
|
||||
def download(url : str, download_file_path : str) -> List[Command]:
|
||||
return [ '--create-dirs', '--continue-at', '-', '--output', download_file_path, url ]
|
||||
|
||||
|
||||
def set_timeout(timeout : int) -> Commands:
|
||||
def set_timeout(timeout : int) -> List[Command]:
|
||||
return [ '--connect-timeout', str(timeout) ]
|
||||
|
||||
|
||||
def set_retry(retry : int) -> List[Command]:
|
||||
return [ '--retry', str(retry) ]
|
||||
|
||||
+15
-14
@@ -7,13 +7,13 @@ from urllib.parse import urlparse
|
||||
from tqdm import tqdm
|
||||
|
||||
import facefusion.choices
|
||||
from facefusion import curl_builder, logger, process_manager, state_manager, wording
|
||||
from facefusion import curl_builder, logger, process_manager, state_manager, translator
|
||||
from facefusion.filesystem import get_file_name, get_file_size, is_file, remove_file
|
||||
from facefusion.hash_helper import validate_hash
|
||||
from facefusion.types import Commands, DownloadProvider, DownloadSet
|
||||
from facefusion.types import Command, DownloadProvider, DownloadSet
|
||||
|
||||
|
||||
def open_curl(commands : Commands) -> subprocess.Popen[bytes]:
|
||||
def open_curl(commands : List[Command]) -> subprocess.Popen[bytes]:
|
||||
commands = curl_builder.run(commands)
|
||||
return subprocess.Popen(commands, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
|
||||
|
||||
@@ -26,10 +26,11 @@ def conditional_download(download_directory_path : str, urls : List[str]) -> Non
|
||||
download_size = get_static_download_size(url)
|
||||
|
||||
if initial_size < download_size:
|
||||
with tqdm(total = download_size, initial = initial_size, desc = wording.get('downloading'), unit = 'B', unit_scale = True, unit_divisor = 1024, ascii = ' =', disable = state_manager.get_item('log_level') in [ 'warn', 'error' ]) as progress:
|
||||
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:
|
||||
commands = curl_builder.chain(
|
||||
curl_builder.download(url, download_file_path),
|
||||
curl_builder.set_timeout(5)
|
||||
curl_builder.set_timeout(5),
|
||||
curl_builder.set_retry(5)
|
||||
)
|
||||
open_curl(commands)
|
||||
current_size = initial_size
|
||||
@@ -41,10 +42,10 @@ def conditional_download(download_directory_path : str, urls : List[str]) -> Non
|
||||
progress.update(current_size - progress.n)
|
||||
|
||||
|
||||
@lru_cache(maxsize = 1024)
|
||||
@lru_cache(maxsize = 64)
|
||||
def get_static_download_size(url : str) -> int:
|
||||
commands = curl_builder.chain(
|
||||
curl_builder.head(url),
|
||||
curl_builder.ping(url),
|
||||
curl_builder.set_timeout(5)
|
||||
)
|
||||
process = open_curl(commands)
|
||||
@@ -59,10 +60,10 @@ def get_static_download_size(url : str) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
@lru_cache(maxsize = 1024)
|
||||
@lru_cache(maxsize = 64)
|
||||
def ping_static_url(url : str) -> bool:
|
||||
commands = curl_builder.chain(
|
||||
curl_builder.head(url),
|
||||
curl_builder.ping(url),
|
||||
curl_builder.set_timeout(5)
|
||||
)
|
||||
process = open_curl(commands)
|
||||
@@ -87,10 +88,10 @@ def conditional_download_hashes(hash_set : DownloadSet) -> bool:
|
||||
|
||||
for valid_hash_path in valid_hash_paths:
|
||||
valid_hash_file_name = get_file_name(valid_hash_path)
|
||||
logger.debug(wording.get('validating_hash_succeeded').format(hash_file_name = valid_hash_file_name), __name__)
|
||||
logger.debug(translator.get('validating_hash_succeeded').format(hash_file_name = valid_hash_file_name), __name__)
|
||||
for invalid_hash_path in invalid_hash_paths:
|
||||
invalid_hash_file_name = get_file_name(invalid_hash_path)
|
||||
logger.error(wording.get('validating_hash_failed').format(hash_file_name = invalid_hash_file_name), __name__)
|
||||
logger.error(translator.get('validating_hash_failed').format(hash_file_name = invalid_hash_file_name), __name__)
|
||||
|
||||
if not invalid_hash_paths:
|
||||
process_manager.end()
|
||||
@@ -114,13 +115,13 @@ def conditional_download_sources(source_set : DownloadSet) -> bool:
|
||||
|
||||
for valid_source_path in valid_source_paths:
|
||||
valid_source_file_name = get_file_name(valid_source_path)
|
||||
logger.debug(wording.get('validating_source_succeeded').format(source_file_name = valid_source_file_name), __name__)
|
||||
logger.debug(translator.get('validating_source_succeeded').format(source_file_name = valid_source_file_name), __name__)
|
||||
for invalid_source_path in invalid_source_paths:
|
||||
invalid_source_file_name = get_file_name(invalid_source_path)
|
||||
logger.error(wording.get('validating_source_failed').format(source_file_name = invalid_source_file_name), __name__)
|
||||
logger.error(translator.get('validating_source_failed').format(source_file_name = invalid_source_file_name), __name__)
|
||||
|
||||
if remove_file(invalid_source_path):
|
||||
logger.error(wording.get('deleting_corrupt_source').format(source_file_name = invalid_source_file_name), __name__)
|
||||
logger.error(translator.get('deleting_corrupt_source').format(source_file_name = invalid_source_file_name), __name__)
|
||||
|
||||
if not invalid_source_paths:
|
||||
process_manager.end()
|
||||
|
||||
+62
-28
@@ -1,15 +1,17 @@
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import xml.etree.ElementTree as ElementTree
|
||||
from functools import lru_cache
|
||||
from typing import List, Optional
|
||||
|
||||
from onnxruntime import get_available_providers, set_default_logger_severity
|
||||
import onnxruntime
|
||||
|
||||
import facefusion.choices
|
||||
from facefusion.types import ExecutionDevice, ExecutionProvider, InferenceSessionProvider, ValueAndUnit
|
||||
from facefusion.filesystem import create_directory, is_directory
|
||||
from facefusion.types import ExecutionDevice, ExecutionProvider, InferenceOptionSet, InferenceProvider, ValueAndUnit
|
||||
|
||||
set_default_logger_severity(3)
|
||||
onnxruntime.set_default_logger_severity(3)
|
||||
|
||||
|
||||
def has_execution_provider(execution_provider : ExecutionProvider) -> bool:
|
||||
@@ -17,7 +19,7 @@ def has_execution_provider(execution_provider : ExecutionProvider) -> bool:
|
||||
|
||||
|
||||
def get_available_execution_providers() -> List[ExecutionProvider]:
|
||||
inference_session_providers = get_available_providers()
|
||||
inference_session_providers = onnxruntime.get_available_providers()
|
||||
available_execution_providers : List[ExecutionProvider] = []
|
||||
|
||||
for execution_provider, execution_provider_value in facefusion.choices.execution_provider_set.items():
|
||||
@@ -28,54 +30,86 @@ def get_available_execution_providers() -> List[ExecutionProvider]:
|
||||
return available_execution_providers
|
||||
|
||||
|
||||
def create_inference_session_providers(execution_device_id : str, execution_providers : List[ExecutionProvider]) -> List[InferenceSessionProvider]:
|
||||
inference_session_providers : List[InferenceSessionProvider] = []
|
||||
def create_inference_providers(execution_device_id : int, execution_providers : List[ExecutionProvider]) -> List[InferenceProvider]:
|
||||
inference_providers : List[InferenceProvider] = []
|
||||
cache_path = resolve_cache_path()
|
||||
|
||||
for execution_provider in execution_providers:
|
||||
if execution_provider == 'cuda':
|
||||
inference_session_providers.append((facefusion.choices.execution_provider_set.get(execution_provider),
|
||||
inference_providers.append((facefusion.choices.execution_provider_set.get(execution_provider),
|
||||
{
|
||||
'device_id': execution_device_id,
|
||||
'cudnn_conv_algo_search': resolve_cudnn_conv_algo_search()
|
||||
}))
|
||||
|
||||
if execution_provider == 'tensorrt':
|
||||
inference_session_providers.append((facefusion.choices.execution_provider_set.get(execution_provider),
|
||||
inference_option_set : InferenceOptionSet =\
|
||||
{
|
||||
'device_id': execution_device_id
|
||||
}
|
||||
if is_directory(cache_path) or create_directory(cache_path):
|
||||
inference_option_set.update(
|
||||
{
|
||||
'device_id': execution_device_id,
|
||||
'trt_engine_cache_enable': True,
|
||||
'trt_engine_cache_path': '.caches',
|
||||
'trt_engine_cache_path': cache_path,
|
||||
'trt_timing_cache_enable': True,
|
||||
'trt_timing_cache_path': '.caches',
|
||||
'trt_builder_optimization_level': 5
|
||||
}))
|
||||
'trt_timing_cache_path': cache_path,
|
||||
'trt_builder_optimization_level': 4
|
||||
})
|
||||
inference_providers.append((facefusion.choices.execution_provider_set.get(execution_provider), inference_option_set))
|
||||
|
||||
if execution_provider in [ 'directml', 'rocm' ]:
|
||||
inference_session_providers.append((facefusion.choices.execution_provider_set.get(execution_provider),
|
||||
inference_providers.append((facefusion.choices.execution_provider_set.get(execution_provider),
|
||||
{
|
||||
'device_id': execution_device_id
|
||||
}))
|
||||
|
||||
if execution_provider == 'migraphx':
|
||||
inference_session_providers.append((facefusion.choices.execution_provider_set.get(execution_provider),
|
||||
inference_option_set =\
|
||||
{
|
||||
'device_id': execution_device_id,
|
||||
'migraphx_model_cache_dir': '.caches'
|
||||
}))
|
||||
'device_id': execution_device_id
|
||||
}
|
||||
if is_directory(cache_path) or create_directory(cache_path):
|
||||
inference_option_set.update(
|
||||
{
|
||||
'migraphx_model_cache_dir': cache_path
|
||||
})
|
||||
inference_providers.append((facefusion.choices.execution_provider_set.get(execution_provider), inference_option_set))
|
||||
|
||||
if execution_provider == 'coreml':
|
||||
inference_option_set =\
|
||||
{
|
||||
'SpecializationStrategy': 'FastPrediction'
|
||||
}
|
||||
if is_directory(cache_path) or create_directory(cache_path):
|
||||
inference_option_set.update(
|
||||
{
|
||||
'ModelCacheDirectory': cache_path
|
||||
})
|
||||
inference_providers.append((facefusion.choices.execution_provider_set.get(execution_provider), inference_option_set))
|
||||
|
||||
if execution_provider == 'openvino':
|
||||
inference_session_providers.append((facefusion.choices.execution_provider_set.get(execution_provider),
|
||||
inference_providers.append((facefusion.choices.execution_provider_set.get(execution_provider),
|
||||
{
|
||||
'device_type': resolve_openvino_device_type(execution_device_id),
|
||||
'precision': 'FP32'
|
||||
}))
|
||||
if execution_provider == 'coreml':
|
||||
inference_session_providers.append((facefusion.choices.execution_provider_set.get(execution_provider),
|
||||
|
||||
if execution_provider == 'qnn':
|
||||
inference_providers.append((facefusion.choices.execution_provider_set.get(execution_provider),
|
||||
{
|
||||
'SpecializationStrategy': 'FastPrediction',
|
||||
'ModelCacheDirectory': '.caches'
|
||||
'device_id': execution_device_id,
|
||||
'backend_type': 'htp'
|
||||
}))
|
||||
|
||||
if 'cpu' in execution_providers:
|
||||
inference_session_providers.append(facefusion.choices.execution_provider_set.get('cpu'))
|
||||
inference_providers.append(facefusion.choices.execution_provider_set.get('cpu'))
|
||||
|
||||
return inference_session_providers
|
||||
return inference_providers
|
||||
|
||||
|
||||
def resolve_cache_path() -> str:
|
||||
return os.path.join('.caches', onnxruntime.get_version_string())
|
||||
|
||||
|
||||
def resolve_cudnn_conv_algo_search() -> str:
|
||||
@@ -89,10 +123,10 @@ def resolve_cudnn_conv_algo_search() -> str:
|
||||
return 'EXHAUSTIVE'
|
||||
|
||||
|
||||
def resolve_openvino_device_type(execution_device_id : str) -> str:
|
||||
if execution_device_id == '0':
|
||||
def resolve_openvino_device_type(execution_device_id : int) -> str:
|
||||
if execution_device_id == 0:
|
||||
return 'GPU'
|
||||
return 'GPU.' + execution_device_id
|
||||
return 'GPU.' + str(execution_device_id)
|
||||
|
||||
|
||||
def run_nvidia_smi() -> subprocess.Popen[bytes]:
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
from typing import List, Optional
|
||||
|
||||
import numpy
|
||||
|
||||
from facefusion import state_manager
|
||||
from facefusion.common_helper import get_first
|
||||
from facefusion.face_classifier import classify_face
|
||||
from facefusion.face_detector import detect_faces, detect_faces_by_angle
|
||||
from facefusion.face_helper import apply_nms, convert_to_face_landmark_5, estimate_face_angle, get_nms_threshold
|
||||
from facefusion.face_landmarker import detect_face_landmark, estimate_face_landmark_68_5
|
||||
from facefusion.face_recognizer import calculate_face_embedding
|
||||
from facefusion.face_store import get_static_faces, set_static_faces
|
||||
from facefusion.types import BoundingBox, Face, FaceLandmark5, FaceLandmarkSet, FaceScoreSet, Score, VisionFrame
|
||||
|
||||
|
||||
def create_faces(vision_frame : VisionFrame, bounding_boxes : List[BoundingBox], face_scores : List[Score], face_landmarks_5 : List[FaceLandmark5]) -> List[Face]:
|
||||
faces = []
|
||||
nms_threshold = get_nms_threshold(state_manager.get_item('face_detector_model'), state_manager.get_item('face_detector_angles'))
|
||||
keep_indices = apply_nms(bounding_boxes, face_scores, state_manager.get_item('face_detector_score'), nms_threshold)
|
||||
|
||||
for index in keep_indices:
|
||||
bounding_box = bounding_boxes[index]
|
||||
face_score = face_scores[index]
|
||||
face_landmark_5 = face_landmarks_5[index]
|
||||
face_landmark_5_68 = face_landmark_5
|
||||
face_landmark_68_5 = estimate_face_landmark_68_5(face_landmark_5_68)
|
||||
face_landmark_68 = face_landmark_68_5
|
||||
face_landmark_score_68 = 0.0
|
||||
face_angle = estimate_face_angle(face_landmark_68_5)
|
||||
|
||||
if state_manager.get_item('face_landmarker_score') > 0:
|
||||
face_landmark_68, face_landmark_score_68 = detect_face_landmark(vision_frame, bounding_box, face_angle)
|
||||
if face_landmark_score_68 > state_manager.get_item('face_landmarker_score'):
|
||||
face_landmark_5_68 = convert_to_face_landmark_5(face_landmark_68)
|
||||
|
||||
face_landmark_set : FaceLandmarkSet =\
|
||||
{
|
||||
'5': face_landmark_5,
|
||||
'5/68': face_landmark_5_68,
|
||||
'68': face_landmark_68,
|
||||
'68/5': face_landmark_68_5
|
||||
}
|
||||
face_score_set : FaceScoreSet =\
|
||||
{
|
||||
'detector': face_score,
|
||||
'landmarker': face_landmark_score_68
|
||||
}
|
||||
face_embedding, face_embedding_norm = calculate_face_embedding(vision_frame, face_landmark_set.get('5/68'))
|
||||
gender, age, race = classify_face(vision_frame, face_landmark_set.get('5/68'))
|
||||
faces.append(Face(
|
||||
bounding_box = bounding_box,
|
||||
score_set = face_score_set,
|
||||
landmark_set = face_landmark_set,
|
||||
angle = face_angle,
|
||||
embedding = face_embedding,
|
||||
embedding_norm = face_embedding_norm,
|
||||
gender = gender,
|
||||
age = age,
|
||||
race = race
|
||||
))
|
||||
return faces
|
||||
|
||||
|
||||
def get_one_face(faces : List[Face], position : int = 0) -> Optional[Face]:
|
||||
if faces:
|
||||
position = min(position, len(faces) - 1)
|
||||
return faces[position]
|
||||
return None
|
||||
|
||||
|
||||
def get_average_face(faces : List[Face]) -> Optional[Face]:
|
||||
face_embeddings = []
|
||||
face_embeddings_norm = []
|
||||
|
||||
if faces:
|
||||
first_face = get_first(faces)
|
||||
|
||||
for face in faces:
|
||||
face_embeddings.append(face.embedding)
|
||||
face_embeddings_norm.append(face.embedding_norm)
|
||||
|
||||
return Face(
|
||||
bounding_box = first_face.bounding_box,
|
||||
score_set = first_face.score_set,
|
||||
landmark_set = first_face.landmark_set,
|
||||
angle = first_face.angle,
|
||||
embedding = numpy.mean(face_embeddings, axis = 0),
|
||||
embedding_norm = numpy.mean(face_embeddings_norm, axis = 0),
|
||||
gender = first_face.gender,
|
||||
age = first_face.age,
|
||||
race = first_face.race
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def get_many_faces(vision_frames : List[VisionFrame]) -> List[Face]:
|
||||
many_faces : List[Face] = []
|
||||
|
||||
for vision_frame in vision_frames:
|
||||
if numpy.any(vision_frame):
|
||||
static_faces = get_static_faces(vision_frame)
|
||||
if static_faces:
|
||||
many_faces.extend(static_faces)
|
||||
else:
|
||||
all_bounding_boxes = []
|
||||
all_face_scores = []
|
||||
all_face_landmarks_5 = []
|
||||
|
||||
for face_detector_angle in state_manager.get_item('face_detector_angles'):
|
||||
if face_detector_angle == 0:
|
||||
bounding_boxes, face_scores, face_landmarks_5 = detect_faces(vision_frame)
|
||||
else:
|
||||
bounding_boxes, face_scores, face_landmarks_5 = detect_faces_by_angle(vision_frame, face_detector_angle)
|
||||
all_bounding_boxes.extend(bounding_boxes)
|
||||
all_face_scores.extend(face_scores)
|
||||
all_face_landmarks_5.extend(face_landmarks_5)
|
||||
|
||||
if all_bounding_boxes and all_face_scores and all_face_landmarks_5 and state_manager.get_item('face_detector_score') > 0:
|
||||
faces = create_faces(vision_frame, all_bounding_boxes, all_face_scores, all_face_landmarks_5)
|
||||
|
||||
if faces:
|
||||
many_faces.extend(faces)
|
||||
set_static_faces(vision_frame, faces)
|
||||
return many_faces
|
||||
@@ -17,6 +17,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
{
|
||||
'fairface':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'dchen236',
|
||||
'license': 'CC-BY-4.0',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_classifier':
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
from typing import List, Optional
|
||||
|
||||
import numpy
|
||||
|
||||
from facefusion import face_store, state_manager
|
||||
from facefusion.common_helper import get_first, get_middle
|
||||
from facefusion.face_classifier import classify_face
|
||||
from facefusion.face_detector import detect_faces, detect_faces_by_angle
|
||||
from facefusion.face_helper import apply_nms, average_points, convert_to_face_landmark_5, estimate_face_angle, get_nms_threshold
|
||||
from facefusion.face_landmarker import detect_face_landmark, estimate_face_landmark_68_5
|
||||
from facefusion.face_recognizer import calculate_face_embedding
|
||||
from facefusion.types import BoundingBox, Face, FaceLandmark5, FaceLandmarkSet, FaceScoreSet, Score, VisionFrame
|
||||
|
||||
|
||||
def create_faces(vision_frame : VisionFrame, bounding_boxes : List[BoundingBox], face_scores : List[Score], face_landmarks_5 : List[FaceLandmark5]) -> List[Face]:
|
||||
faces = []
|
||||
nms_threshold = get_nms_threshold(state_manager.get_item('face_detector_model'), state_manager.get_item('face_detector_angles'))
|
||||
keep_indices = apply_nms(bounding_boxes, face_scores, state_manager.get_item('face_detector_score'), nms_threshold)
|
||||
|
||||
for index in keep_indices:
|
||||
bounding_box = bounding_boxes[index]
|
||||
face_score = face_scores[index]
|
||||
face_landmark_5 = face_landmarks_5[index]
|
||||
face_landmark_5_68 = face_landmark_5
|
||||
face_landmark_68_5 = estimate_face_landmark_68_5(face_landmark_5_68)
|
||||
face_landmark_68 = face_landmark_68_5
|
||||
face_landmark_score_68 = 0.0
|
||||
face_angle = estimate_face_angle(face_landmark_68_5)
|
||||
|
||||
if state_manager.get_item('face_landmarker_score') > 0:
|
||||
face_landmark_68, face_landmark_score_68 = detect_face_landmark(vision_frame, bounding_box, face_angle)
|
||||
if face_landmark_score_68 > state_manager.get_item('face_landmarker_score'):
|
||||
face_landmark_5_68 = convert_to_face_landmark_5(face_landmark_68)
|
||||
|
||||
face_landmark_set : FaceLandmarkSet =\
|
||||
{
|
||||
'5': face_landmark_5,
|
||||
'5/68': face_landmark_5_68,
|
||||
'68': face_landmark_68,
|
||||
'68/5': face_landmark_68_5
|
||||
}
|
||||
face_score_set : FaceScoreSet =\
|
||||
{
|
||||
'detector': face_score,
|
||||
'landmarker': face_landmark_score_68
|
||||
}
|
||||
face_embedding, face_embedding_norm = calculate_face_embedding(vision_frame, face_landmark_set.get('5/68'))
|
||||
gender, age, race = classify_face(vision_frame, face_landmark_set.get('5/68'))
|
||||
|
||||
faces.append(Face(
|
||||
origin = 'detect',
|
||||
bounding_box = bounding_box,
|
||||
score_set = face_score_set,
|
||||
landmark_set = face_landmark_set,
|
||||
angle = face_angle,
|
||||
embedding = face_embedding,
|
||||
embedding_norm = face_embedding_norm,
|
||||
gender = gender,
|
||||
age = age,
|
||||
race = race
|
||||
))
|
||||
return faces
|
||||
|
||||
|
||||
def get_one_face(faces : List[Face], position : int = 0) -> Optional[Face]:
|
||||
if faces:
|
||||
position = min(position, len(faces) - 1)
|
||||
return faces[position]
|
||||
return None
|
||||
|
||||
|
||||
def get_many_faces(vision_frames : List[VisionFrame]) -> List[Face]:
|
||||
many_faces : List[Face] = []
|
||||
|
||||
for vision_frame in vision_frames:
|
||||
if numpy.any(vision_frame):
|
||||
all_bounding_boxes = []
|
||||
all_face_scores = []
|
||||
all_face_landmarks_5 = []
|
||||
|
||||
for face_detector_angle in state_manager.get_item('face_detector_angles'):
|
||||
if face_detector_angle == 0:
|
||||
bounding_boxes, face_scores, face_landmarks_5 = detect_faces(vision_frame)
|
||||
else:
|
||||
bounding_boxes, face_scores, face_landmarks_5 = detect_faces_by_angle(vision_frame, face_detector_angle)
|
||||
all_bounding_boxes.extend(bounding_boxes)
|
||||
all_face_scores.extend(face_scores)
|
||||
all_face_landmarks_5.extend(face_landmarks_5)
|
||||
|
||||
if all_bounding_boxes and all_face_scores and all_face_landmarks_5 and state_manager.get_item('face_detector_score') > 0:
|
||||
faces = create_faces(vision_frame, all_bounding_boxes, all_face_scores, all_face_landmarks_5)
|
||||
|
||||
if faces:
|
||||
many_faces.extend(faces)
|
||||
|
||||
return many_faces
|
||||
|
||||
|
||||
def get_static_faces(vision_frames : List[VisionFrame]) -> List[Face]:
|
||||
many_faces : List[Face] = []
|
||||
|
||||
for vision_frame in vision_frames:
|
||||
faces = face_store.get_faces(vision_frame)
|
||||
|
||||
if not faces:
|
||||
with face_store.resolve_lock(vision_frame):
|
||||
faces = face_store.get_faces(vision_frame)
|
||||
|
||||
if not faces:
|
||||
faces = get_many_faces([ vision_frame ])
|
||||
|
||||
if faces:
|
||||
face_store.set_faces(vision_frame, faces)
|
||||
|
||||
many_faces.extend(faces)
|
||||
|
||||
return many_faces
|
||||
|
||||
|
||||
def refill_faces(faces : List[Optional[Face]]) -> List[Face]:
|
||||
fill_faces = []
|
||||
anchor_index_previous = -1
|
||||
|
||||
for index, face in enumerate(faces):
|
||||
if face:
|
||||
for gap_index in range(anchor_index_previous + 1, index):
|
||||
average_factor = (gap_index - anchor_index_previous) / (index - anchor_index_previous)
|
||||
average_face = average_face_geometry([faces[anchor_index_previous], face], average_factor)
|
||||
fill_faces.append(average_face)
|
||||
|
||||
fill_faces.append(face)
|
||||
anchor_index_previous = index
|
||||
|
||||
return fill_faces
|
||||
|
||||
|
||||
def average_face_geometry(faces : List[Face], average_factor : float) -> Face:
|
||||
face_first = get_first(faces)
|
||||
face_middle = get_middle(faces)
|
||||
face_anchor = face_middle
|
||||
|
||||
if average_factor < 0.5:
|
||||
face_anchor = face_first
|
||||
|
||||
landmark_set : FaceLandmarkSet =\
|
||||
{
|
||||
'5': average_points(face_first.landmark_set.get('5'), face_middle.landmark_set.get('5'), average_factor),
|
||||
'5/68': average_points(face_first.landmark_set.get('5/68'), face_middle.landmark_set.get('5/68'), average_factor),
|
||||
'68': average_points(face_first.landmark_set.get('68'), face_middle.landmark_set.get('68'), average_factor),
|
||||
'68/5': average_points(face_first.landmark_set.get('68/5'), face_middle.landmark_set.get('68/5'), average_factor)
|
||||
}
|
||||
|
||||
return Face(
|
||||
origin = 'refill',
|
||||
bounding_box = average_points(face_first.bounding_box, face_middle.bounding_box, average_factor),
|
||||
score_set = face_anchor.score_set,
|
||||
landmark_set = landmark_set,
|
||||
angle = estimate_face_angle(landmark_set.get('68/5')),
|
||||
embedding = face_anchor.embedding,
|
||||
embedding_norm = face_anchor.embedding_norm,
|
||||
gender = face_anchor.gender,
|
||||
age = face_anchor.age,
|
||||
race = face_anchor.race
|
||||
)
|
||||
|
||||
|
||||
def average_face_identity(faces : List[Face]) -> Optional[Face]:
|
||||
face_embeddings = []
|
||||
face_embeddings_norm = []
|
||||
|
||||
if faces:
|
||||
first_face = get_first(faces)
|
||||
|
||||
for face in faces:
|
||||
face_embeddings.append(face.embedding)
|
||||
face_embeddings_norm.append(face.embedding_norm)
|
||||
|
||||
return Face(
|
||||
origin = first_face.origin,
|
||||
bounding_box = first_face.bounding_box,
|
||||
score_set = first_face.score_set,
|
||||
landmark_set = first_face.landmark_set,
|
||||
angle = first_face.angle,
|
||||
embedding = numpy.mean(face_embeddings, axis = 0),
|
||||
embedding_norm = numpy.mean(face_embeddings_norm, axis = 0),
|
||||
gender = first_face.gender,
|
||||
age = first_face.age,
|
||||
race = first_face.race
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def scale_face(target_face : Face, target_vision_frame : VisionFrame, temp_vision_frame : VisionFrame) -> Face:
|
||||
scale_x = temp_vision_frame.shape[1] / target_vision_frame.shape[1]
|
||||
scale_y = temp_vision_frame.shape[0] / target_vision_frame.shape[0]
|
||||
|
||||
bounding_box = target_face.bounding_box * [ scale_x, scale_y, scale_x, scale_y ]
|
||||
landmark_set =\
|
||||
{
|
||||
'5': target_face.landmark_set.get('5') * numpy.array([ scale_x, scale_y ]),
|
||||
'5/68': target_face.landmark_set.get('5/68') * numpy.array([ scale_x, scale_y ]),
|
||||
'68': target_face.landmark_set.get('68') * numpy.array([ scale_x, scale_y ]),
|
||||
'68/5': target_face.landmark_set.get('68/5') * numpy.array([ scale_x, scale_y ])
|
||||
}
|
||||
|
||||
return target_face._replace(
|
||||
bounding_box = bounding_box,
|
||||
landmark_set = landmark_set
|
||||
)
|
||||
@@ -9,7 +9,7 @@ from facefusion.download import conditional_download_hashes, conditional_downloa
|
||||
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
|
||||
from facefusion.filesystem import resolve_relative_path
|
||||
from facefusion.thread_helper import thread_semaphore
|
||||
from facefusion.types import Angle, BoundingBox, Detection, DownloadScope, DownloadSet, FaceLandmark5, InferencePool, ModelSet, Score, VisionFrame
|
||||
from facefusion.types import Angle, BoundingBox, Detection, DownloadScope, DownloadSet, FaceLandmark5, InferencePool, Margin, ModelSet, Score, VisionFrame
|
||||
from facefusion.vision import restrict_frame, unpack_resolution
|
||||
|
||||
|
||||
@@ -19,6 +19,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
{
|
||||
'retinaface':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'InsightFace',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2020
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'retinaface':
|
||||
@@ -38,6 +44,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'scrfd':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'InsightFace',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'scrfd':
|
||||
@@ -57,6 +69,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'yolo_face':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'derronqi',
|
||||
'license': 'GPL-3.0',
|
||||
'year': 2022
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'yolo_face':
|
||||
@@ -76,6 +94,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'yunet':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'OpenCV',
|
||||
'license': 'MIT',
|
||||
'year': 2023
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'yunet':
|
||||
@@ -128,38 +152,49 @@ def pre_check() -> bool:
|
||||
|
||||
|
||||
def detect_faces(vision_frame : VisionFrame) -> Tuple[List[BoundingBox], List[Score], List[FaceLandmark5]]:
|
||||
margin_top, margin_right, margin_bottom, margin_left = prepare_margin(vision_frame)
|
||||
margin_vision_frame = numpy.pad(vision_frame, ((margin_top, margin_bottom), (margin_left, margin_right), (0, 0)))
|
||||
all_bounding_boxes : List[BoundingBox] = []
|
||||
all_face_scores : List[Score] = []
|
||||
all_face_landmarks_5 : List[FaceLandmark5] = []
|
||||
|
||||
if state_manager.get_item('face_detector_model') in [ 'many', 'retinaface' ]:
|
||||
bounding_boxes, face_scores, face_landmarks_5 = detect_with_retinaface(vision_frame, state_manager.get_item('face_detector_size'))
|
||||
bounding_boxes, face_scores, face_landmarks_5 = detect_with_retinaface(margin_vision_frame, state_manager.get_item('face_detector_size'))
|
||||
all_bounding_boxes.extend(bounding_boxes)
|
||||
all_face_scores.extend(face_scores)
|
||||
all_face_landmarks_5.extend(face_landmarks_5)
|
||||
|
||||
if state_manager.get_item('face_detector_model') in [ 'many', 'scrfd' ]:
|
||||
bounding_boxes, face_scores, face_landmarks_5 = detect_with_scrfd(vision_frame, state_manager.get_item('face_detector_size'))
|
||||
bounding_boxes, face_scores, face_landmarks_5 = detect_with_scrfd(margin_vision_frame, state_manager.get_item('face_detector_size'))
|
||||
all_bounding_boxes.extend(bounding_boxes)
|
||||
all_face_scores.extend(face_scores)
|
||||
all_face_landmarks_5.extend(face_landmarks_5)
|
||||
|
||||
if state_manager.get_item('face_detector_model') in [ 'many', 'yolo_face' ]:
|
||||
bounding_boxes, face_scores, face_landmarks_5 = detect_with_yolo_face(vision_frame, state_manager.get_item('face_detector_size'))
|
||||
bounding_boxes, face_scores, face_landmarks_5 = detect_with_yolo_face(margin_vision_frame, state_manager.get_item('face_detector_size'))
|
||||
all_bounding_boxes.extend(bounding_boxes)
|
||||
all_face_scores.extend(face_scores)
|
||||
all_face_landmarks_5.extend(face_landmarks_5)
|
||||
|
||||
if state_manager.get_item('face_detector_model') == 'yunet':
|
||||
bounding_boxes, face_scores, face_landmarks_5 = detect_with_yunet(vision_frame, state_manager.get_item('face_detector_size'))
|
||||
bounding_boxes, face_scores, face_landmarks_5 = detect_with_yunet(margin_vision_frame, state_manager.get_item('face_detector_size'))
|
||||
all_bounding_boxes.extend(bounding_boxes)
|
||||
all_face_scores.extend(face_scores)
|
||||
all_face_landmarks_5.extend(face_landmarks_5)
|
||||
|
||||
all_bounding_boxes = [ normalize_bounding_box(all_bounding_box) for all_bounding_box in all_bounding_boxes ]
|
||||
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 ]
|
||||
all_face_landmarks_5 = [ all_face_landmark_5 - numpy.array([ margin_left, margin_top ]) for all_face_landmark_5 in all_face_landmarks_5 ]
|
||||
return all_bounding_boxes, all_face_scores, all_face_landmarks_5
|
||||
|
||||
|
||||
def prepare_margin(vision_frame : VisionFrame) -> Margin:
|
||||
margin_top = int(vision_frame.shape[0] * numpy.interp(state_manager.get_item('face_detector_margin')[0], [ 0, 100 ], [ 0, 0.5 ]))
|
||||
margin_right = int(vision_frame.shape[1] * numpy.interp(state_manager.get_item('face_detector_margin')[1], [ 0, 100 ], [ 0, 0.5 ]))
|
||||
margin_bottom = int(vision_frame.shape[0] * numpy.interp(state_manager.get_item('face_detector_margin')[2], [ 0, 100 ], [ 0, 0.5 ]))
|
||||
margin_left = int(vision_frame.shape[1] * numpy.interp(state_manager.get_item('face_detector_margin')[3], [ 0, 100 ], [ 0, 0.5 ]))
|
||||
return margin_top, margin_right, margin_bottom, margin_left
|
||||
|
||||
|
||||
def detect_faces_by_angle(vision_frame : VisionFrame, face_angle : Angle) -> Tuple[List[BoundingBox], List[Score], List[FaceLandmark5]]:
|
||||
rotation_matrix, rotation_size = create_rotation_matrix_and_size(face_angle, vision_frame.shape[:2][::-1])
|
||||
rotation_vision_frame = cv2.warpAffine(vision_frame, rotation_matrix, rotation_size)
|
||||
|
||||
@@ -98,17 +98,17 @@ def warp_face_by_translation(temp_vision_frame : VisionFrame, translation : Tran
|
||||
return crop_vision_frame, affine_matrix
|
||||
|
||||
|
||||
def paste_back(temp_vision_frame : VisionFrame, crop_vision_frame : VisionFrame, crop_mask : Mask, affine_matrix : Matrix) -> VisionFrame:
|
||||
def paste_back(temp_vision_frame : VisionFrame, crop_vision_frame : VisionFrame, crop_vision_mask : Mask, affine_matrix : Matrix) -> VisionFrame:
|
||||
paste_bounding_box, paste_matrix = calculate_paste_area(temp_vision_frame, crop_vision_frame, affine_matrix)
|
||||
x1, y1, x2, y2 = paste_bounding_box
|
||||
paste_width = x2 - x1
|
||||
paste_height = y2 - y1
|
||||
inverse_mask = cv2.warpAffine(crop_mask, paste_matrix, (paste_width, paste_height)).clip(0, 1)
|
||||
inverse_mask = numpy.expand_dims(inverse_mask, axis = -1)
|
||||
inverse_vision_mask = cv2.warpAffine(crop_vision_mask, paste_matrix, (paste_width, paste_height)).clip(0, 1)
|
||||
inverse_vision_mask = numpy.expand_dims(inverse_vision_mask, axis = -1)
|
||||
inverse_vision_frame = cv2.warpAffine(crop_vision_frame, paste_matrix, (paste_width, paste_height), borderMode = cv2.BORDER_REPLICATE)
|
||||
temp_vision_frame = temp_vision_frame.copy()
|
||||
paste_vision_frame = temp_vision_frame[y1:y2, x1:x2]
|
||||
paste_vision_frame = paste_vision_frame * (1 - inverse_mask) + inverse_vision_frame * inverse_mask
|
||||
paste_vision_frame = paste_vision_frame * (1 - inverse_vision_mask) + inverse_vision_frame * inverse_vision_mask
|
||||
temp_vision_frame[y1:y2, x1:x2] = paste_vision_frame.astype(temp_vision_frame.dtype)
|
||||
return temp_vision_frame
|
||||
|
||||
@@ -254,3 +254,23 @@ def merge_matrix(temp_matrices : List[Matrix]) -> Matrix:
|
||||
matrix = numpy.dot(temp_matrix, matrix)
|
||||
|
||||
return matrix[:2, :]
|
||||
|
||||
|
||||
def calculate_bounding_box_overlap(bounding_box_a : BoundingBox, bounding_box_b : BoundingBox) -> float:
|
||||
intersection_x1 = max(bounding_box_a[0], bounding_box_b[0])
|
||||
intersection_y1 = max(bounding_box_a[1], bounding_box_b[1])
|
||||
intersection_x2 = min(bounding_box_a[2], bounding_box_b[2])
|
||||
intersection_y2 = min(bounding_box_a[3], bounding_box_b[3])
|
||||
intersection = max(0, intersection_x2 - intersection_x1) * max(0, intersection_y2 - intersection_y1)
|
||||
bounding_box_area = (bounding_box_a[2] - bounding_box_a[0]) * (bounding_box_a[3] - bounding_box_a[1])
|
||||
reference_bounding_box_area = (bounding_box_b[2] - bounding_box_b[0]) * (bounding_box_b[3] - bounding_box_b[1])
|
||||
union = bounding_box_area + reference_bounding_box_area - intersection
|
||||
|
||||
if union > 0:
|
||||
return intersection / union
|
||||
|
||||
return 0.0
|
||||
|
||||
|
||||
def average_points(points_previous : Points, points_next : Points, average_factor : float) -> Points:
|
||||
return points_previous * (1 - average_factor) + points_next * average_factor
|
||||
|
||||
@@ -18,6 +18,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
{
|
||||
'2dfan4':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'breadbread1984',
|
||||
'license': 'MIT',
|
||||
'year': 2018
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'2dfan4':
|
||||
@@ -38,6 +44,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'peppa_wutz':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'Unknown',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2023
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'peppa_wutz':
|
||||
@@ -58,6 +70,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'fan_68_5':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'FaceFusion',
|
||||
'license': 'OpenRAIL-M',
|
||||
'year': 2024
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'fan_68_5':
|
||||
|
||||
@@ -18,6 +18,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
{
|
||||
'xseg_1':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'DeepFaceLab',
|
||||
'license': 'GPL-3.0',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_occluder':
|
||||
@@ -38,6 +44,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'xseg_2':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'DeepFaceLab',
|
||||
'license': 'GPL-3.0',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_occluder':
|
||||
@@ -58,6 +70,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'xseg_3':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'DeepFaceLab',
|
||||
'license': 'GPL-3.0',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_occluder':
|
||||
@@ -78,6 +96,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'bisenet_resnet_18':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'yakhyo',
|
||||
'license': 'MIT',
|
||||
'year': 2024
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_parser':
|
||||
@@ -98,6 +122,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'bisenet_resnet_34':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'yakhyo',
|
||||
'license': 'MIT',
|
||||
'year': 2024
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_parser':
|
||||
|
||||
@@ -17,6 +17,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
{
|
||||
'arcface':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'InsightFace',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2018
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_recognizer':
|
||||
|
||||
+41
-16
@@ -2,26 +2,35 @@ from typing import List
|
||||
|
||||
import numpy
|
||||
|
||||
import facefusion.choices
|
||||
from facefusion import state_manager
|
||||
from facefusion.face_analyser import get_many_faces, get_one_face
|
||||
from facefusion.common_helper import get_first, get_middle
|
||||
from facefusion.face_creator import get_one_face, get_static_faces
|
||||
from facefusion.face_tracker import track_faces
|
||||
from facefusion.types import Face, FaceSelectorOrder, Gender, Race, Score, VisionFrame
|
||||
|
||||
|
||||
def select_faces(reference_vision_frame : VisionFrame, target_vision_frame : VisionFrame) -> List[Face]:
|
||||
target_faces = get_many_faces([ target_vision_frame ])
|
||||
def select_faces(reference_vision_frame : VisionFrame, source_vision_frames : List[VisionFrame], target_vision_frames : List[VisionFrame]) -> List[Face]:
|
||||
source_faces = get_static_faces(source_vision_frames)
|
||||
|
||||
if state_manager.get_item('face_tracker_score') > 0:
|
||||
target_faces = track_faces(target_vision_frames, state_manager.get_item('face_tracker_score'))
|
||||
else:
|
||||
target_faces = get_static_faces([ get_middle(target_vision_frames) ])
|
||||
|
||||
if state_manager.get_item('face_selector_mode') == 'many':
|
||||
return sort_and_filter_faces(target_faces)
|
||||
return sort_and_filter_faces(source_faces, target_faces)
|
||||
|
||||
if state_manager.get_item('face_selector_mode') == 'one':
|
||||
target_face = get_one_face(sort_and_filter_faces(target_faces))
|
||||
target_face = get_one_face(sort_and_filter_faces(source_faces, target_faces))
|
||||
if target_face:
|
||||
return [ target_face ]
|
||||
|
||||
if state_manager.get_item('face_selector_mode') == 'reference':
|
||||
reference_faces = get_many_faces([ reference_vision_frame ])
|
||||
reference_faces = sort_and_filter_faces(reference_faces)
|
||||
reference_faces = get_static_faces([ reference_vision_frame ])
|
||||
reference_faces = sort_and_filter_faces(source_faces, reference_faces)
|
||||
reference_face = get_one_face(reference_faces, state_manager.get_item('reference_face_position'))
|
||||
|
||||
if reference_face:
|
||||
match_faces = find_match_faces([ reference_face ], target_faces, state_manager.get_item('reference_face_distance'))
|
||||
return match_faces
|
||||
@@ -53,17 +62,33 @@ def calculate_face_distance(face : Face, reference_face : Face) -> float:
|
||||
return 0
|
||||
|
||||
|
||||
def sort_and_filter_faces(faces : List[Face]) -> List[Face]:
|
||||
if faces:
|
||||
def sort_and_filter_faces(source_faces : List[Face], target_faces : List[Face]) -> List[Face]:
|
||||
if target_faces:
|
||||
if state_manager.get_item('face_selector_order'):
|
||||
faces = sort_faces_by_order(faces, state_manager.get_item('face_selector_order'))
|
||||
if state_manager.get_item('face_selector_gender'):
|
||||
faces = filter_faces_by_gender(faces, state_manager.get_item('face_selector_gender'))
|
||||
if state_manager.get_item('face_selector_race'):
|
||||
faces = filter_faces_by_race(faces, state_manager.get_item('face_selector_race'))
|
||||
target_faces = sort_faces_by_order(target_faces, state_manager.get_item('face_selector_order'))
|
||||
|
||||
face_selector_gender = state_manager.get_item('face_selector_gender')
|
||||
face_selector_race = state_manager.get_item('face_selector_race')
|
||||
|
||||
if source_faces and face_selector_gender == 'auto' or face_selector_race == 'auto':
|
||||
source_face = get_first(sort_faces_by_order(source_faces, 'large-small'))
|
||||
|
||||
if source_face:
|
||||
if face_selector_gender == 'auto':
|
||||
face_selector_gender = source_face.gender
|
||||
if face_selector_race == 'auto':
|
||||
face_selector_race = source_face.race
|
||||
|
||||
if face_selector_gender in facefusion.choices.genders:
|
||||
target_faces = filter_faces_by_gender(target_faces, face_selector_gender)
|
||||
|
||||
if face_selector_race in facefusion.choices.races:
|
||||
target_faces = filter_faces_by_race(target_faces, face_selector_race)
|
||||
|
||||
if state_manager.get_item('face_selector_age_start') or state_manager.get_item('face_selector_age_end'):
|
||||
faces = filter_faces_by_age(faces, state_manager.get_item('face_selector_age_start'), state_manager.get_item('face_selector_age_end'))
|
||||
return faces
|
||||
target_faces = filter_faces_by_age(target_faces, state_manager.get_item('face_selector_age_start'), state_manager.get_item('face_selector_age_end'))
|
||||
|
||||
return target_faces
|
||||
|
||||
|
||||
def sort_faces_by_order(faces : List[Face], order : FaceSelectorOrder) -> List[Face]:
|
||||
|
||||
+31
-17
@@ -1,28 +1,42 @@
|
||||
import threading
|
||||
from typing import List, Optional
|
||||
|
||||
import numpy
|
||||
|
||||
from facefusion.hash_helper import create_hash
|
||||
from facefusion.types import Face, FaceStore, VisionFrame
|
||||
|
||||
FACE_STORE : FaceStore =\
|
||||
FACE_STORE : FaceStore = {}
|
||||
|
||||
|
||||
def get_faces(vision_frame : VisionFrame) -> Optional[List[Face]]:
|
||||
if numpy.any(vision_frame):
|
||||
vision_hash = create_hash(vision_frame.tobytes())
|
||||
|
||||
if FACE_STORE.get(vision_hash):
|
||||
return FACE_STORE.get(vision_hash).get('faces')
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def set_faces(vision_frame : VisionFrame, faces : List[Face]) -> None:
|
||||
if numpy.any(vision_frame):
|
||||
vision_hash = create_hash(vision_frame.tobytes())
|
||||
FACE_STORE.setdefault(vision_hash,
|
||||
{
|
||||
'static_faces': {}
|
||||
}
|
||||
'lock': threading.Lock()
|
||||
})['faces'] = faces
|
||||
|
||||
|
||||
def get_face_store() -> FaceStore:
|
||||
return FACE_STORE
|
||||
|
||||
|
||||
def get_static_faces(vision_frame : VisionFrame) -> Optional[List[Face]]:
|
||||
def resolve_lock(vision_frame : VisionFrame) -> threading.Lock:
|
||||
if numpy.any(vision_frame):
|
||||
vision_hash = create_hash(vision_frame.tobytes())
|
||||
return FACE_STORE.get('static_faces').get(vision_hash)
|
||||
return FACE_STORE.setdefault(vision_hash,
|
||||
{
|
||||
'lock': threading.Lock()
|
||||
}).get('lock')
|
||||
return threading.Lock()
|
||||
|
||||
|
||||
def set_static_faces(vision_frame : VisionFrame, faces : List[Face]) -> None:
|
||||
vision_hash = create_hash(vision_frame.tobytes())
|
||||
if vision_hash:
|
||||
FACE_STORE['static_faces'][vision_hash] = faces
|
||||
|
||||
|
||||
def clear_static_faces() -> None:
|
||||
FACE_STORE['static_faces'].clear()
|
||||
def clear_faces() -> None:
|
||||
FACE_STORE.clear()
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
from typing import List
|
||||
|
||||
from facefusion.common_helper import get_first, get_last
|
||||
from facefusion.face_creator import get_static_faces, refill_faces
|
||||
from facefusion.face_helper import calculate_bounding_box_overlap
|
||||
from facefusion.types import Face, FaceTrack, Score, VisionFrame
|
||||
|
||||
|
||||
def track_faces(vision_frames : List[VisionFrame], score : Score) -> List[Face]:
|
||||
target_index = len(vision_frames) // 2
|
||||
face_tracks = create_face_tracks(vision_frames, score)
|
||||
temp_faces = []
|
||||
|
||||
for face_track in face_tracks:
|
||||
track_indices = sorted(face_track)
|
||||
track_index_first = get_first(track_indices)
|
||||
track_index_last = get_last(track_indices)
|
||||
track_range = range(track_index_first, track_index_last + 1)
|
||||
|
||||
if target_index in track_range:
|
||||
fill_faces = []
|
||||
|
||||
for index in track_range:
|
||||
fill_faces.append(face_track.get(index))
|
||||
|
||||
temp_faces.append(refill_faces(fill_faces)[target_index - track_index_first])
|
||||
|
||||
return temp_faces
|
||||
|
||||
|
||||
def create_face_tracks(vision_frames : List[VisionFrame], score : Score) -> List[FaceTrack]:
|
||||
face_tracks : List[FaceTrack] = []
|
||||
|
||||
for frame_index, vision_frame in enumerate(vision_frames):
|
||||
for face in get_static_faces([ vision_frame ]):
|
||||
face_track = select_face_track(face_tracks, face, score)
|
||||
|
||||
if face_track:
|
||||
face_track[frame_index] = face
|
||||
else:
|
||||
face_tracks.append(
|
||||
{
|
||||
frame_index : face
|
||||
})
|
||||
|
||||
return face_tracks
|
||||
|
||||
|
||||
def select_face_track(face_tracks : List[FaceTrack], face : Face, score : Score) -> FaceTrack:
|
||||
select_track : FaceTrack = {}
|
||||
select_score = score
|
||||
|
||||
for face_track in face_tracks:
|
||||
track_face = face_track.get(get_last(face_track))
|
||||
track_score = calculate_bounding_box_overlap(face.bounding_box, track_face.bounding_box)
|
||||
|
||||
if track_score > select_score:
|
||||
select_score = track_score
|
||||
select_track = face_track
|
||||
|
||||
return select_track
|
||||
+31
-15
@@ -7,14 +7,14 @@ from typing import List, Optional, cast
|
||||
from tqdm import tqdm
|
||||
|
||||
import facefusion.choices
|
||||
from facefusion import ffmpeg_builder, logger, process_manager, state_manager, wording
|
||||
from facefusion import ffmpeg_builder, logger, process_manager, state_manager, translator
|
||||
from facefusion.filesystem import get_file_format, remove_file
|
||||
from facefusion.temp_helper import get_temp_file_path, get_temp_frames_pattern
|
||||
from facefusion.types import AudioBuffer, AudioEncoder, Commands, EncoderSet, Fps, Resolution, UpdateProgress, VideoEncoder, VideoFormat
|
||||
from facefusion.temp_helper import get_temp_file_path, get_temp_frame_pattern
|
||||
from facefusion.types import AudioBuffer, AudioEncoder, Command, EncoderSet, Fps, Resolution, UpdateProgress, VideoEncoder, VideoFormat
|
||||
from facefusion.vision import detect_video_duration, detect_video_fps, pack_resolution, predict_video_frame_total
|
||||
|
||||
|
||||
def run_ffmpeg_with_progress(commands : Commands, update_progress : UpdateProgress) -> subprocess.Popen[bytes]:
|
||||
def run_ffmpeg_with_progress(commands : List[Command], update_progress : UpdateProgress) -> subprocess.Popen[bytes]:
|
||||
log_level = state_manager.get_item('log_level')
|
||||
commands.extend(ffmpeg_builder.set_progress())
|
||||
commands.extend(ffmpeg_builder.cast_stream())
|
||||
@@ -45,7 +45,7 @@ def update_progress(progress : tqdm, frame_number : int) -> None:
|
||||
progress.update(frame_number - progress.n)
|
||||
|
||||
|
||||
def run_ffmpeg(commands : Commands) -> subprocess.Popen[bytes]:
|
||||
def run_ffmpeg(commands : List[Command]) -> subprocess.Popen[bytes]:
|
||||
log_level = state_manager.get_item('log_level')
|
||||
commands = ffmpeg_builder.run(commands)
|
||||
process = subprocess.Popen(commands, stderr = subprocess.PIPE, stdout = subprocess.PIPE)
|
||||
@@ -65,7 +65,7 @@ def run_ffmpeg(commands : Commands) -> subprocess.Popen[bytes]:
|
||||
return process
|
||||
|
||||
|
||||
def open_ffmpeg(commands : Commands) -> subprocess.Popen[bytes]:
|
||||
def open_ffmpeg(commands : List[Command]) -> subprocess.Popen[bytes]:
|
||||
commands = ffmpeg_builder.run(commands)
|
||||
return subprocess.Popen(commands, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
|
||||
|
||||
@@ -109,17 +109,19 @@ def get_available_encoder_set() -> EncoderSet:
|
||||
|
||||
def extract_frames(target_path : str, temp_video_resolution : Resolution, temp_video_fps : Fps, trim_frame_start : int, trim_frame_end : int) -> bool:
|
||||
extract_frame_total = predict_video_frame_total(target_path, temp_video_fps, trim_frame_start, trim_frame_end)
|
||||
temp_frames_pattern = get_temp_frames_pattern(target_path, '%08d')
|
||||
temp_frame_pattern = get_temp_frame_pattern(target_path, '%08d')
|
||||
commands = ffmpeg_builder.chain(
|
||||
ffmpeg_builder.set_input(target_path),
|
||||
ffmpeg_builder.set_media_resolution(pack_resolution(temp_video_resolution)),
|
||||
ffmpeg_builder.set_frame_quality(0),
|
||||
ffmpeg_builder.enforce_pixel_format('rgb24'),
|
||||
ffmpeg_builder.select_frame_range(trim_frame_start, trim_frame_end, temp_video_fps),
|
||||
ffmpeg_builder.prevent_frame_drop(),
|
||||
ffmpeg_builder.set_output(temp_frames_pattern)
|
||||
ffmpeg_builder.set_start_number(trim_frame_start),
|
||||
ffmpeg_builder.set_output(temp_frame_pattern)
|
||||
)
|
||||
|
||||
with tqdm(total = extract_frame_total, desc = wording.get('extracting'), unit = 'frame', ascii = ' =', disable = state_manager.get_item('log_level') in [ 'warn', 'error' ]) as progress:
|
||||
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:
|
||||
process = run_ffmpeg_with_progress(commands, partial(update_progress, progress))
|
||||
return process.returncode == 0
|
||||
|
||||
@@ -172,6 +174,7 @@ def restore_audio(target_path : str, output_path : str, trim_frame_start : int,
|
||||
temp_video_path = get_temp_file_path(target_path)
|
||||
temp_video_format = cast(VideoFormat, get_file_format(temp_video_path))
|
||||
temp_video_duration = detect_video_duration(temp_video_path)
|
||||
output_video_format = cast(VideoFormat, get_file_format(output_path))
|
||||
|
||||
output_audio_encoder = fix_audio_encoder(temp_video_format, output_audio_encoder)
|
||||
commands = ffmpeg_builder.chain(
|
||||
@@ -185,6 +188,7 @@ def restore_audio(target_path : str, output_path : str, trim_frame_start : int,
|
||||
ffmpeg_builder.select_media_stream('0:v:0'),
|
||||
ffmpeg_builder.select_media_stream('1:a:0'),
|
||||
ffmpeg_builder.set_video_duration(temp_video_duration),
|
||||
ffmpeg_builder.set_faststart(output_video_format),
|
||||
ffmpeg_builder.force_output(output_path)
|
||||
)
|
||||
return run_ffmpeg(commands).returncode == 0
|
||||
@@ -197,6 +201,7 @@ def replace_audio(target_path : str, audio_path : str, output_path : str) -> boo
|
||||
temp_video_path = get_temp_file_path(target_path)
|
||||
temp_video_format = cast(VideoFormat, get_file_format(temp_video_path))
|
||||
temp_video_duration = detect_video_duration(temp_video_path)
|
||||
output_video_format = cast(VideoFormat, get_file_format(output_path))
|
||||
|
||||
output_audio_encoder = fix_audio_encoder(temp_video_format, output_audio_encoder)
|
||||
commands = ffmpeg_builder.chain(
|
||||
@@ -207,6 +212,7 @@ def replace_audio(target_path : str, audio_path : str, output_path : str) -> boo
|
||||
ffmpeg_builder.set_audio_quality(output_audio_encoder, output_audio_quality),
|
||||
ffmpeg_builder.set_audio_volume(output_audio_volume),
|
||||
ffmpeg_builder.set_video_duration(temp_video_duration),
|
||||
ffmpeg_builder.set_faststart(output_video_format),
|
||||
ffmpeg_builder.force_output(output_path)
|
||||
)
|
||||
return run_ffmpeg(commands).returncode == 0
|
||||
@@ -219,28 +225,34 @@ def merge_video(target_path : str, temp_video_fps : Fps, output_video_resolution
|
||||
merge_frame_total = predict_video_frame_total(target_path, output_video_fps, trim_frame_start, trim_frame_end)
|
||||
temp_video_path = get_temp_file_path(target_path)
|
||||
temp_video_format = cast(VideoFormat, get_file_format(temp_video_path))
|
||||
temp_frames_pattern = get_temp_frames_pattern(target_path, '%08d')
|
||||
temp_frame_pattern = get_temp_frame_pattern(target_path, '%08d')
|
||||
|
||||
output_video_encoder = fix_video_encoder(temp_video_format, output_video_encoder)
|
||||
commands = ffmpeg_builder.chain(
|
||||
ffmpeg_builder.set_input_fps(temp_video_fps),
|
||||
ffmpeg_builder.set_input(temp_frames_pattern),
|
||||
ffmpeg_builder.set_start_number(trim_frame_start),
|
||||
ffmpeg_builder.set_input(temp_frame_pattern),
|
||||
ffmpeg_builder.set_media_resolution(pack_resolution(output_video_resolution)),
|
||||
ffmpeg_builder.set_video_encoder(output_video_encoder),
|
||||
ffmpeg_builder.set_video_tag(output_video_encoder, temp_video_format),
|
||||
ffmpeg_builder.set_video_quality(output_video_encoder, output_video_quality),
|
||||
ffmpeg_builder.set_video_preset(output_video_encoder, output_video_preset),
|
||||
ffmpeg_builder.concat(
|
||||
ffmpeg_builder.set_video_fps(output_video_fps),
|
||||
ffmpeg_builder.keep_video_alpha(output_video_encoder)
|
||||
),
|
||||
ffmpeg_builder.set_pixel_format(output_video_encoder),
|
||||
ffmpeg_builder.force_output(temp_video_path)
|
||||
)
|
||||
|
||||
with tqdm(total = merge_frame_total, desc = wording.get('merging'), unit = 'frame', ascii = ' =', disable = state_manager.get_item('log_level') in [ 'warn', 'error' ]) as progress:
|
||||
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:
|
||||
process = run_ffmpeg_with_progress(commands, partial(update_progress, progress))
|
||||
return process.returncode == 0
|
||||
|
||||
|
||||
def concat_video(output_path : str, temp_output_paths : List[str]) -> bool:
|
||||
concat_video_path = tempfile.mktemp()
|
||||
file_descriptor, concat_video_path = tempfile.mkstemp()
|
||||
os.close(file_descriptor)
|
||||
|
||||
with open(concat_video_path, 'w') as concat_video_file:
|
||||
for temp_output_path in temp_output_paths:
|
||||
@@ -249,11 +261,13 @@ def concat_video(output_path : str, temp_output_paths : List[str]) -> bool:
|
||||
concat_video_file.close()
|
||||
|
||||
output_path = os.path.abspath(output_path)
|
||||
output_video_format = cast(VideoFormat, get_file_format(output_path))
|
||||
commands = ffmpeg_builder.chain(
|
||||
ffmpeg_builder.unsafe_concat(),
|
||||
ffmpeg_builder.set_input(concat_video_file.name),
|
||||
ffmpeg_builder.copy_video_encoder(),
|
||||
ffmpeg_builder.copy_audio_encoder(),
|
||||
ffmpeg_builder.set_faststart(output_video_format),
|
||||
ffmpeg_builder.force_output(output_path)
|
||||
)
|
||||
process = run_ffmpeg(commands)
|
||||
@@ -265,17 +279,19 @@ def concat_video(output_path : str, temp_output_paths : List[str]) -> bool:
|
||||
def fix_audio_encoder(video_format : VideoFormat, audio_encoder : AudioEncoder) -> AudioEncoder:
|
||||
if video_format == 'avi' and audio_encoder == 'libopus':
|
||||
return 'aac'
|
||||
if video_format in [ 'm4v', 'wmv' ]:
|
||||
if video_format in [ 'm4v', 'mpeg', 'wmv' ]:
|
||||
return 'aac'
|
||||
if video_format == 'mov' and audio_encoder in [ 'flac', 'libopus' ]:
|
||||
return 'aac'
|
||||
if video_format == 'mxf':
|
||||
return 'pcm_s16le'
|
||||
if video_format == 'webm':
|
||||
return 'libopus'
|
||||
return audio_encoder
|
||||
|
||||
|
||||
def fix_video_encoder(video_format : VideoFormat, video_encoder : VideoEncoder) -> VideoEncoder:
|
||||
if video_format in [ 'm4v', 'wmv' ]:
|
||||
if video_format in [ 'm4v', 'mpeg', 'mxf', 'wmv' ]:
|
||||
return 'libx264'
|
||||
if video_format in [ 'mkv', 'mp4' ] and video_encoder == 'rawvideo':
|
||||
return 'libx264'
|
||||
|
||||
@@ -1,54 +1,73 @@
|
||||
import itertools
|
||||
import shutil
|
||||
from typing import Optional
|
||||
from typing import List, Optional
|
||||
|
||||
import numpy
|
||||
|
||||
from facefusion.filesystem import get_file_format
|
||||
from facefusion.types import AudioEncoder, Commands, Duration, Fps, StreamMode, VideoEncoder, VideoPreset
|
||||
from facefusion.types import AudioEncoder, Command, CommandSet, Duration, Fps, StreamMode, VideoEncoder, VideoFormat, VideoPreset
|
||||
|
||||
|
||||
def run(commands : Commands) -> Commands:
|
||||
def run(commands : List[Command]) -> List[Command]:
|
||||
return [ shutil.which('ffmpeg'), '-loglevel', 'error' ] + commands
|
||||
|
||||
|
||||
def chain(*commands : Commands) -> Commands:
|
||||
def chain(*commands : List[Command]) -> List[Command]:
|
||||
return list(itertools.chain(*commands))
|
||||
|
||||
|
||||
def get_encoders() -> Commands:
|
||||
def concat(*__commands__ : List[Command]) -> List[Command]:
|
||||
commands = []
|
||||
command_set : CommandSet = {}
|
||||
|
||||
for command in __commands__:
|
||||
for argument, value in zip(command[::2], command[1::2]):
|
||||
command_set.setdefault(argument, []).append(value)
|
||||
|
||||
for argument, values in command_set.items():
|
||||
commands.append(argument)
|
||||
commands.append(','.join(values))
|
||||
|
||||
return commands
|
||||
|
||||
|
||||
def get_encoders() -> List[Command]:
|
||||
return [ '-encoders' ]
|
||||
|
||||
|
||||
def set_hardware_accelerator(value : str) -> Commands:
|
||||
def set_hardware_accelerator(value : str) -> List[Command]:
|
||||
return [ '-hwaccel', value ]
|
||||
|
||||
|
||||
def set_progress() -> Commands:
|
||||
def set_progress() -> List[Command]:
|
||||
return [ '-progress' ]
|
||||
|
||||
|
||||
def set_input(input_path : str) -> Commands:
|
||||
def set_input(input_path : str) -> List[Command]:
|
||||
return [ '-i', input_path ]
|
||||
|
||||
|
||||
def set_input_fps(input_fps : Fps) -> Commands:
|
||||
def set_input_fps(input_fps : Fps) -> List[Command]:
|
||||
return [ '-r', str(input_fps) ]
|
||||
|
||||
|
||||
def set_output(output_path : str) -> Commands:
|
||||
def set_start_number(frame_number : int) -> List[Command]:
|
||||
return [ '-start_number', str(frame_number) ]
|
||||
|
||||
|
||||
def set_output(output_path : str) -> List[Command]:
|
||||
return [ output_path ]
|
||||
|
||||
|
||||
def force_output(output_path : str) -> Commands:
|
||||
def force_output(output_path : str) -> List[Command]:
|
||||
return [ '-y', output_path ]
|
||||
|
||||
|
||||
def cast_stream() -> Commands:
|
||||
def cast_stream() -> List[Command]:
|
||||
return [ '-' ]
|
||||
|
||||
|
||||
def set_stream_mode(stream_mode : StreamMode) -> Commands:
|
||||
def set_stream_mode(stream_mode : StreamMode) -> List[Command]:
|
||||
if stream_mode == 'udp':
|
||||
return [ '-f', 'mpegts' ]
|
||||
if stream_mode == 'v4l2':
|
||||
@@ -56,25 +75,31 @@ def set_stream_mode(stream_mode : StreamMode) -> Commands:
|
||||
return []
|
||||
|
||||
|
||||
def set_stream_quality(stream_quality : int) -> Commands:
|
||||
def set_stream_quality(stream_quality : int) -> List[Command]:
|
||||
return [ '-b:v', str(stream_quality) + 'k' ]
|
||||
|
||||
|
||||
def unsafe_concat() -> Commands:
|
||||
def unsafe_concat() -> List[Command]:
|
||||
return [ '-f', 'concat', '-safe', '0' ]
|
||||
|
||||
|
||||
def set_pixel_format(video_encoder : VideoEncoder) -> Commands:
|
||||
def enforce_pixel_format(pixel_format : str) -> List[Command]:
|
||||
return [ '-pix_fmt', pixel_format ]
|
||||
|
||||
|
||||
def set_pixel_format(video_encoder : VideoEncoder) -> List[Command]:
|
||||
if video_encoder == 'rawvideo':
|
||||
return [ '-pix_fmt', 'rgb24' ]
|
||||
if video_encoder == 'libvpx-vp9':
|
||||
return [ '-pix_fmt', 'yuva420p' ]
|
||||
return [ '-pix_fmt', 'yuv420p' ]
|
||||
|
||||
|
||||
def set_frame_quality(frame_quality : int) -> Commands:
|
||||
def set_frame_quality(frame_quality : int) -> List[Command]:
|
||||
return [ '-q:v', str(frame_quality) ]
|
||||
|
||||
|
||||
def select_frame_range(frame_start : int, frame_end : int, video_fps : Fps) -> Commands:
|
||||
def select_frame_range(frame_start : int, frame_end : int, video_fps : Fps) -> List[Command]:
|
||||
if isinstance(frame_start, int) and isinstance(frame_end, int):
|
||||
return [ '-vf', 'trim=start_frame=' + str(frame_start) + ':end_frame=' + str(frame_end) + ',fps=' + str(video_fps) ]
|
||||
if isinstance(frame_start, int):
|
||||
@@ -84,11 +109,11 @@ def select_frame_range(frame_start : int, frame_end : int, video_fps : Fps) -> C
|
||||
return [ '-vf', 'fps=' + str(video_fps) ]
|
||||
|
||||
|
||||
def prevent_frame_drop() -> Commands:
|
||||
def prevent_frame_drop() -> List[Command]:
|
||||
return [ '-vsync', '0' ]
|
||||
|
||||
|
||||
def select_media_range(frame_start : int, frame_end : int, media_fps : Fps) -> Commands:
|
||||
def select_media_range(frame_start : int, frame_end : int, media_fps : Fps) -> List[Command]:
|
||||
commands = []
|
||||
|
||||
if isinstance(frame_start, int):
|
||||
@@ -98,15 +123,15 @@ def select_media_range(frame_start : int, frame_end : int, media_fps : Fps) -> C
|
||||
return commands
|
||||
|
||||
|
||||
def select_media_stream(media_stream : str) -> Commands:
|
||||
def select_media_stream(media_stream : str) -> List[Command]:
|
||||
return [ '-map', media_stream ]
|
||||
|
||||
|
||||
def set_media_resolution(video_resolution : str) -> Commands:
|
||||
def set_media_resolution(video_resolution : str) -> List[Command]:
|
||||
return [ '-s', video_resolution ]
|
||||
|
||||
|
||||
def set_image_quality(image_path : str, image_quality : int) -> Commands:
|
||||
def set_image_quality(image_path : str, image_quality : int) -> List[Command]:
|
||||
if get_file_format(image_path) == 'webp':
|
||||
return [ '-q:v', str(image_quality) ]
|
||||
|
||||
@@ -114,19 +139,19 @@ def set_image_quality(image_path : str, image_quality : int) -> Commands:
|
||||
return [ '-q:v', str(image_compression) ]
|
||||
|
||||
|
||||
def set_audio_encoder(audio_codec : str) -> Commands:
|
||||
def set_audio_encoder(audio_codec : str) -> List[Command]:
|
||||
return [ '-c:a', audio_codec ]
|
||||
|
||||
|
||||
def copy_audio_encoder() -> Commands:
|
||||
def copy_audio_encoder() -> List[Command]:
|
||||
return set_audio_encoder('copy')
|
||||
|
||||
|
||||
def set_audio_sample_rate(audio_sample_rate : int) -> Commands:
|
||||
def set_audio_sample_rate(audio_sample_rate : int) -> List[Command]:
|
||||
return [ '-ar', str(audio_sample_rate) ]
|
||||
|
||||
|
||||
def set_audio_sample_size(audio_sample_size : int) -> Commands:
|
||||
def set_audio_sample_size(audio_sample_size : int) -> List[Command]:
|
||||
if audio_sample_size == 16:
|
||||
return [ '-f', 's16le' ]
|
||||
if audio_sample_size == 32:
|
||||
@@ -134,11 +159,11 @@ def set_audio_sample_size(audio_sample_size : int) -> Commands:
|
||||
return []
|
||||
|
||||
|
||||
def set_audio_channel_total(audio_channel_total : int) -> Commands:
|
||||
def set_audio_channel_total(audio_channel_total : int) -> List[Command]:
|
||||
return [ '-ac', str(audio_channel_total) ]
|
||||
|
||||
|
||||
def set_audio_quality(audio_encoder : AudioEncoder, audio_quality : int) -> Commands:
|
||||
def set_audio_quality(audio_encoder : AudioEncoder, audio_quality : int) -> List[Command]:
|
||||
if audio_encoder == 'aac':
|
||||
audio_compression = numpy.round(numpy.interp(audio_quality, [ 0, 100 ], [ 0.1, 2.0 ]), 1).astype(float).item()
|
||||
return [ '-q:a', str(audio_compression) ]
|
||||
@@ -154,19 +179,31 @@ def set_audio_quality(audio_encoder : AudioEncoder, audio_quality : int) -> Comm
|
||||
return []
|
||||
|
||||
|
||||
def set_audio_volume(audio_volume : int) -> Commands:
|
||||
def set_audio_volume(audio_volume : int) -> List[Command]:
|
||||
return [ '-filter:a', 'volume=' + str(audio_volume / 100) ]
|
||||
|
||||
|
||||
def set_video_encoder(video_encoder : str) -> Commands:
|
||||
def set_video_encoder(video_encoder : str) -> List[Command]:
|
||||
return [ '-c:v', video_encoder ]
|
||||
|
||||
|
||||
def copy_video_encoder() -> Commands:
|
||||
def copy_video_encoder() -> List[Command]:
|
||||
return set_video_encoder('copy')
|
||||
|
||||
|
||||
def set_video_quality(video_encoder : VideoEncoder, video_quality : int) -> Commands:
|
||||
def set_faststart(video_format : VideoFormat) -> List[Command]:
|
||||
if video_format in [ 'm4v', 'mov', 'mp4' ]:
|
||||
return [ '-movflags', '+faststart' ]
|
||||
return []
|
||||
|
||||
|
||||
def set_video_tag(video_encoder : VideoEncoder, video_format : VideoFormat) -> List[Command]:
|
||||
if video_format in [ 'm4v', 'mov', 'mp4' ] and video_encoder in [ 'libx265', 'hevc_nvenc', 'hevc_amf', 'hevc_qsv', 'hevc_videotoolbox' ]:
|
||||
return [ '-tag:v', 'hvc1' ]
|
||||
return []
|
||||
|
||||
|
||||
def set_video_quality(video_encoder : VideoEncoder, video_quality : int) -> List[Command]:
|
||||
if video_encoder in [ 'libx264', 'libx264rgb', 'libx265' ]:
|
||||
video_compression = numpy.round(numpy.interp(video_quality, [ 0, 100 ], [ 51, 0 ])).astype(int).item()
|
||||
return [ '-crf', str(video_compression) ]
|
||||
@@ -188,7 +225,7 @@ def set_video_quality(video_encoder : VideoEncoder, video_quality : int) -> Comm
|
||||
return []
|
||||
|
||||
|
||||
def set_video_preset(video_encoder : VideoEncoder, video_preset : VideoPreset) -> Commands:
|
||||
def set_video_preset(video_encoder : VideoEncoder, video_preset : VideoPreset) -> List[Command]:
|
||||
if video_encoder in [ 'libx264', 'libx264rgb', 'libx265' ]:
|
||||
return [ '-preset', video_preset ]
|
||||
if video_encoder in [ 'h264_nvenc', 'hevc_nvenc' ]:
|
||||
@@ -200,19 +237,25 @@ def set_video_preset(video_encoder : VideoEncoder, video_preset : VideoPreset) -
|
||||
return []
|
||||
|
||||
|
||||
def set_video_fps(video_fps : Fps) -> Commands:
|
||||
return [ '-vf', 'framerate=fps=' + str(video_fps) ]
|
||||
def set_video_fps(video_fps : Fps) -> List[Command]:
|
||||
return [ '-vf', 'fps=' + str(video_fps) ]
|
||||
|
||||
|
||||
def set_video_duration(video_duration : Duration) -> Commands:
|
||||
def set_video_duration(video_duration : Duration) -> List[Command]:
|
||||
return [ '-t', str(video_duration) ]
|
||||
|
||||
|
||||
def capture_video() -> Commands:
|
||||
def keep_video_alpha(video_encoder : VideoEncoder) -> List[Command]:
|
||||
if video_encoder == 'libvpx-vp9':
|
||||
return [ '-vf', 'format=yuva420p' ]
|
||||
return []
|
||||
|
||||
|
||||
def capture_video() -> List[Command]:
|
||||
return [ '-f', 'rawvideo', '-pix_fmt', 'rgb24' ]
|
||||
|
||||
|
||||
def ignore_video_stream() -> Commands:
|
||||
def ignore_video_stream() -> List[Command]:
|
||||
return [ '-vn' ]
|
||||
|
||||
|
||||
|
||||
@@ -36,6 +36,8 @@ def get_file_format(file_path : str) -> Optional[str]:
|
||||
return 'jpeg'
|
||||
if file_extension == '.tif':
|
||||
return 'tiff'
|
||||
if file_extension == '.mpg':
|
||||
return 'mpeg'
|
||||
return file_extension.lstrip('.')
|
||||
return None
|
||||
|
||||
@@ -99,7 +101,7 @@ def has_video(video_paths : List[str]) -> bool:
|
||||
|
||||
def are_videos(video_paths : List[str]) -> bool:
|
||||
if video_paths:
|
||||
return any(map(is_video, video_paths))
|
||||
return all(map(is_video, video_paths))
|
||||
return False
|
||||
|
||||
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
import importlib
|
||||
import random
|
||||
from functools import lru_cache
|
||||
from time import sleep, time
|
||||
from typing import List
|
||||
|
||||
from onnxruntime import InferenceSession
|
||||
|
||||
from facefusion import logger, process_manager, state_manager, wording
|
||||
from facefusion import logger, process_manager, state_manager, translator
|
||||
from facefusion.app_context import detect_app_context
|
||||
from facefusion.execution import create_inference_session_providers
|
||||
from facefusion.common_helper import is_windows
|
||||
from facefusion.execution import create_inference_providers, has_execution_provider
|
||||
from facefusion.exit_helper import fatal_exit
|
||||
from facefusion.filesystem import get_file_name, is_file
|
||||
from facefusion.time_helper import calculate_end_time
|
||||
from facefusion.types import DownloadSet, ExecutionProvider, InferencePool, InferencePoolSet
|
||||
from facefusion.types import DownloadSet, ExecutionProvider, InferencePool, InferencePoolSet, InferenceProvider
|
||||
|
||||
INFERENCE_POOL_SET : InferencePoolSet =\
|
||||
{
|
||||
@@ -24,7 +26,7 @@ def get_inference_pool(module_name : str, model_names : List[str], model_source_
|
||||
while process_manager.is_checking():
|
||||
sleep(0.5)
|
||||
execution_device_ids = state_manager.get_item('execution_device_ids')
|
||||
execution_providers = resolve_execution_providers(module_name)
|
||||
execution_providers = state_manager.get_item('execution_providers')
|
||||
app_context = detect_app_context()
|
||||
|
||||
for execution_device_id in execution_device_ids:
|
||||
@@ -35,58 +37,66 @@ def get_inference_pool(module_name : str, model_names : List[str], model_source_
|
||||
if app_context == 'ui' and INFERENCE_POOL_SET.get('cli').get(inference_context):
|
||||
INFERENCE_POOL_SET['ui'][inference_context] = INFERENCE_POOL_SET.get('cli').get(inference_context)
|
||||
if not INFERENCE_POOL_SET.get(app_context).get(inference_context):
|
||||
INFERENCE_POOL_SET[app_context][inference_context] = create_inference_pool(model_source_set, execution_device_id, execution_providers)
|
||||
inference_providers = resolve_static_inference_providers(module_name, execution_device_id)
|
||||
INFERENCE_POOL_SET[app_context][inference_context] = create_inference_pool(model_source_set, inference_providers)
|
||||
|
||||
current_inference_context = get_inference_context(module_name, model_names, random.choice(execution_device_ids), execution_providers)
|
||||
return INFERENCE_POOL_SET.get(app_context).get(current_inference_context)
|
||||
|
||||
|
||||
def create_inference_pool(model_source_set : DownloadSet, execution_device_id : str, execution_providers : List[ExecutionProvider]) -> InferencePool:
|
||||
def create_inference_pool(model_source_set : DownloadSet, inference_providers : List[InferenceProvider]) -> InferencePool:
|
||||
inference_pool : InferencePool = {}
|
||||
|
||||
for model_name in model_source_set.keys():
|
||||
model_path = model_source_set.get(model_name).get('path')
|
||||
if is_file(model_path):
|
||||
inference_pool[model_name] = create_inference_session(model_path, execution_device_id, execution_providers)
|
||||
inference_pool[model_name] = create_inference_session(model_path, inference_providers)
|
||||
|
||||
return inference_pool
|
||||
|
||||
|
||||
def clear_inference_pool(module_name : str, model_names : List[str]) -> None:
|
||||
execution_device_ids = state_manager.get_item('execution_device_ids')
|
||||
execution_providers = resolve_execution_providers(module_name)
|
||||
execution_providers = state_manager.get_item('execution_providers')
|
||||
app_context = detect_app_context()
|
||||
|
||||
if is_windows() and has_execution_provider('directml'):
|
||||
INFERENCE_POOL_SET[app_context].clear()
|
||||
|
||||
for execution_device_id in execution_device_ids:
|
||||
inference_context = get_inference_context(module_name, model_names, execution_device_id, execution_providers)
|
||||
|
||||
if INFERENCE_POOL_SET.get(app_context).get(inference_context):
|
||||
del INFERENCE_POOL_SET[app_context][inference_context]
|
||||
|
||||
|
||||
def create_inference_session(model_path : str, execution_device_id : str, execution_providers : List[ExecutionProvider]) -> InferenceSession:
|
||||
def create_inference_session(model_path : str, inference_providers : List[InferenceProvider]) -> InferenceSession:
|
||||
model_file_name = get_file_name(model_path)
|
||||
start_time = time()
|
||||
|
||||
try:
|
||||
inference_session_providers = create_inference_session_providers(execution_device_id, execution_providers)
|
||||
inference_session = InferenceSession(model_path, providers = inference_session_providers)
|
||||
logger.debug(wording.get('loading_model_succeeded').format(model_name = model_file_name, seconds = calculate_end_time(start_time)), __name__)
|
||||
inference_session = InferenceSession(model_path, providers = inference_providers)
|
||||
logger.debug(translator.get('loading_model_succeeded').format(model_name = model_file_name, seconds = calculate_end_time(start_time)), __name__)
|
||||
return inference_session
|
||||
|
||||
except Exception:
|
||||
logger.error(wording.get('loading_model_failed').format(model_name = model_file_name), __name__)
|
||||
logger.error(translator.get('loading_model_failed').format(model_name = model_file_name), __name__)
|
||||
fatal_exit(1)
|
||||
|
||||
|
||||
def get_inference_context(module_name : str, model_names : List[str], execution_device_id : str, execution_providers : List[ExecutionProvider]) -> str:
|
||||
inference_context = '.'.join([ module_name ] + model_names + [ execution_device_id ] + list(execution_providers))
|
||||
def get_inference_context(module_name : str, model_names : List[str], execution_device_id : int, execution_providers : List[ExecutionProvider]) -> str:
|
||||
inference_context = '.'.join([ module_name ] + model_names + [ str(execution_device_id) ] + list(execution_providers))
|
||||
return inference_context
|
||||
|
||||
|
||||
def resolve_execution_providers(module_name : str) -> List[ExecutionProvider]:
|
||||
@lru_cache()
|
||||
def resolve_static_inference_providers(module_name : str, execution_device_id : int) -> List[InferenceProvider]:
|
||||
module = importlib.import_module(module_name)
|
||||
execution_providers = state_manager.get_item('execution_providers')
|
||||
|
||||
if hasattr(module, 'resolve_execution_providers'):
|
||||
return getattr(module, 'resolve_execution_providers')()
|
||||
return state_manager.get_item('execution_providers')
|
||||
if hasattr(module, 'resolve_inference_providers'):
|
||||
inference_providers = getattr(module, 'resolve_inference_providers')()
|
||||
|
||||
if inference_providers:
|
||||
return inference_providers
|
||||
|
||||
return create_inference_providers(execution_device_id, execution_providers)
|
||||
|
||||
+29
-51
@@ -7,27 +7,37 @@ from argparse import ArgumentParser, HelpFormatter
|
||||
from functools import partial
|
||||
from types import FrameType
|
||||
|
||||
from facefusion import metadata, wording
|
||||
from facefusion import metadata
|
||||
from facefusion.common_helper import is_linux, is_windows
|
||||
|
||||
LOCALES =\
|
||||
{
|
||||
'install_dependency': 'install the {dependency} package',
|
||||
'force_reinstall': 'force reinstall of packages',
|
||||
'skip_conda': 'skip the conda environment check',
|
||||
'conda_not_activated': 'conda is not activated'
|
||||
}
|
||||
ONNXRUNTIME_SET =\
|
||||
{
|
||||
'default': ('onnxruntime', '1.22.0')
|
||||
'default': ('onnxruntime', '1.26.0')
|
||||
}
|
||||
if is_windows() or is_linux():
|
||||
ONNXRUNTIME_SET['cuda'] = ('onnxruntime-gpu', '1.22.0')
|
||||
ONNXRUNTIME_SET['openvino'] = ('onnxruntime-openvino', '1.22.0')
|
||||
ONNXRUNTIME_SET['cuda'] = ('onnxruntime-gpu', '1.26.0')
|
||||
ONNXRUNTIME_SET['openvino'] = ('onnxruntime-openvino', '1.24.1')
|
||||
if is_windows():
|
||||
ONNXRUNTIME_SET['directml'] = ('onnxruntime-directml', '1.17.3')
|
||||
ONNXRUNTIME_SET['directml'] = ('onnxruntime-directml', '1.24.4')
|
||||
ONNXRUNTIME_SET['qnn'] = ('onnxruntime-qnn', '1.24.4')
|
||||
if is_linux():
|
||||
ONNXRUNTIME_SET['rocm'] = ('onnxruntime-rocm', '1.21.0')
|
||||
ONNXRUNTIME_SET['migraphx'] = ('onnxruntime-migraphx', '1.25.0')
|
||||
ONNXRUNTIME_SET['rocm'] = ('onnxruntime-rocm', '1.22.2.post1')
|
||||
|
||||
|
||||
def cli() -> None:
|
||||
signal.signal(signal.SIGINT, signal_exit)
|
||||
program = ArgumentParser(formatter_class = partial(HelpFormatter, max_help_position = 50))
|
||||
program.add_argument('--onnxruntime', help = wording.get('help.install_dependency').format(dependency = 'onnxruntime'), choices = ONNXRUNTIME_SET.keys(), required = True)
|
||||
program.add_argument('--skip-conda', help = wording.get('help.skip_conda'), action = 'store_true')
|
||||
program.add_argument('onnxruntime', help = LOCALES.get('install_dependency').format(dependency = 'onnxruntime'), choices = ONNXRUNTIME_SET.keys())
|
||||
program.add_argument('--force-reinstall', help = LOCALES.get('force_reinstall'), action = 'store_true')
|
||||
program.add_argument('--skip-conda', help = LOCALES.get('skip_conda'), action = 'store_true')
|
||||
program.add_argument('-v', '--version', version = metadata.get('name') + ' ' + metadata.get('version'), action = 'version')
|
||||
run(program)
|
||||
|
||||
@@ -39,58 +49,26 @@ def signal_exit(signum : int, frame : FrameType) -> None:
|
||||
def run(program : ArgumentParser) -> None:
|
||||
args = program.parse_args()
|
||||
has_conda = 'CONDA_PREFIX' in os.environ
|
||||
onnxruntime_name, onnxruntime_version = ONNXRUNTIME_SET.get(args.onnxruntime)
|
||||
|
||||
if not args.skip_conda and not has_conda:
|
||||
sys.stdout.write(wording.get('conda_not_activated') + os.linesep)
|
||||
sys.stdout.write(LOCALES.get('conda_not_activated') + os.linesep)
|
||||
sys.exit(1)
|
||||
|
||||
commands = [ shutil.which('pip'), 'install' ]
|
||||
|
||||
if args.force_reinstall:
|
||||
commands.append('--force-reinstall')
|
||||
|
||||
with open('requirements.txt') as file:
|
||||
|
||||
for line in file.readlines():
|
||||
__line__ = line.strip()
|
||||
if not __line__.startswith('onnxruntime'):
|
||||
subprocess.call([ shutil.which('pip'), 'install', line, '--force-reinstall' ])
|
||||
commands.append(__line__)
|
||||
|
||||
if args.onnxruntime == 'rocm':
|
||||
python_id = 'cp' + str(sys.version_info.major) + str(sys.version_info.minor)
|
||||
onnxruntime_name, onnxruntime_version = ONNXRUNTIME_SET.get(args.onnxruntime)
|
||||
commands.append(onnxruntime_name + '==' + onnxruntime_version)
|
||||
|
||||
if python_id in [ 'cp310', 'cp312' ]:
|
||||
wheel_name = 'onnxruntime_rocm-' + onnxruntime_version + '-' + python_id + '-' + python_id + '-linux_x86_64.whl'
|
||||
wheel_url = 'https://repo.radeon.com/rocm/manylinux/rocm-rel-6.4/' + wheel_name
|
||||
subprocess.call([ shutil.which('pip'), 'install', wheel_url, '--force-reinstall' ])
|
||||
else:
|
||||
subprocess.call([ shutil.which('pip'), 'install', onnxruntime_name + '==' + onnxruntime_version, '--force-reinstall' ])
|
||||
subprocess.call([ shutil.which('pip'), 'uninstall', 'onnxruntime', onnxruntime_name, '-y', '-q' ])
|
||||
|
||||
if args.onnxruntime == 'cuda' and has_conda:
|
||||
library_paths = []
|
||||
|
||||
if is_linux():
|
||||
if os.getenv('LD_LIBRARY_PATH'):
|
||||
library_paths = os.getenv('LD_LIBRARY_PATH').split(os.pathsep)
|
||||
|
||||
python_id = 'python' + str(sys.version_info.major) + '.' + str(sys.version_info.minor)
|
||||
library_paths.extend(
|
||||
[
|
||||
os.path.join(os.getenv('CONDA_PREFIX'), 'lib'),
|
||||
os.path.join(os.getenv('CONDA_PREFIX'), 'lib', python_id, 'site-packages', 'tensorrt_libs')
|
||||
])
|
||||
library_paths = list(dict.fromkeys([ library_path for library_path in library_paths if os.path.exists(library_path) ]))
|
||||
|
||||
subprocess.call([ shutil.which('conda'), 'env', 'config', 'vars', 'set', 'LD_LIBRARY_PATH=' + os.pathsep.join(library_paths) ])
|
||||
|
||||
if is_windows():
|
||||
if os.getenv('PATH'):
|
||||
library_paths = os.getenv('PATH').split(os.pathsep)
|
||||
|
||||
library_paths.extend(
|
||||
[
|
||||
os.path.join(os.getenv('CONDA_PREFIX'), 'Lib'),
|
||||
os.path.join(os.getenv('CONDA_PREFIX'), 'Lib', 'site-packages', 'tensorrt_libs')
|
||||
])
|
||||
library_paths = list(dict.fromkeys([ library_path for library_path in library_paths if os.path.exists(library_path) ]))
|
||||
|
||||
subprocess.call([ shutil.which('conda'), 'env', 'config', 'vars', 'set', 'PATH=' + os.pathsep.join(library_paths) ])
|
||||
|
||||
if args.onnxruntime == 'directml':
|
||||
subprocess.call([ shutil.which('pip'), 'install', 'numpy==1.26.4', '--force-reinstall' ])
|
||||
subprocess.call(commands)
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional, Tuple
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
from facefusion.jobs import job_manager
|
||||
from facefusion.time_helper import describe_time_ago
|
||||
from facefusion.types import JobStatus, TableContents, TableHeaders
|
||||
from facefusion.types import JobStatus, TableContent, TableHeader
|
||||
|
||||
|
||||
def compose_job_list(job_status : JobStatus) -> Tuple[TableHeaders, TableContents]:
|
||||
def compose_job_list(job_status : JobStatus) -> Tuple[List[TableHeader], List[List[TableContent]]]:
|
||||
jobs = job_manager.find_jobs(job_status)
|
||||
job_headers : TableHeaders = [ 'job id', 'steps', 'date created', 'date updated', 'job status' ]
|
||||
job_contents : TableContents = []
|
||||
job_headers : List[TableHeader] = [ 'job id', 'steps', 'date created', 'date updated', 'job status' ]
|
||||
job_contents : List[List[TableContent]] = []
|
||||
|
||||
for index, job_id in enumerate(jobs):
|
||||
if job_manager.validate_job(job_id):
|
||||
|
||||
@@ -6,6 +6,7 @@ import facefusion.choices
|
||||
from facefusion.filesystem import create_directory, get_file_name, is_directory, is_file, move_file, remove_directory, remove_file, resolve_file_pattern
|
||||
from facefusion.jobs.job_helper import get_step_output_path
|
||||
from facefusion.json import read_json, write_json
|
||||
from facefusion.sanitizer import sanitize_job_id
|
||||
from facefusion.time_helper import get_current_date_time
|
||||
from facefusion.types import Args, Job, JobSet, JobStatus, JobStep, JobStepStatus
|
||||
|
||||
@@ -261,5 +262,6 @@ def find_job_path(job_id : str) -> Optional[str]:
|
||||
|
||||
def get_job_file_name(job_id : str) -> Optional[str]:
|
||||
if job_id:
|
||||
job_id = sanitize_job_id(job_id)
|
||||
return job_id + '.json'
|
||||
return None
|
||||
|
||||
@@ -17,11 +17,11 @@ def get_step_keys() -> List[str]:
|
||||
return JOB_STORE.get('step_keys')
|
||||
|
||||
|
||||
def register_job_keys(step_keys : List[str]) -> None:
|
||||
for step_key in step_keys:
|
||||
JOB_STORE['job_keys'].append(step_key)
|
||||
|
||||
|
||||
def register_step_keys(job_keys : List[str]) -> None:
|
||||
def register_job_keys(job_keys : List[str]) -> None:
|
||||
for job_key in job_keys:
|
||||
JOB_STORE['step_keys'].append(job_key)
|
||||
JOB_STORE['job_keys'].append(job_key)
|
||||
|
||||
|
||||
def register_step_keys(step_keys : List[str]) -> None:
|
||||
for step_key in step_keys:
|
||||
JOB_STORE['step_keys'].append(step_key)
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
from facefusion.types import Locales
|
||||
|
||||
LOCALES : Locales =\
|
||||
{
|
||||
'en':
|
||||
{
|
||||
'conda_not_activated': 'conda is not activated',
|
||||
'python_not_supported': 'python version is not supported, upgrade to {version} or higher',
|
||||
'curl_not_installed': 'curl is not installed',
|
||||
'ffmpeg_not_installed': 'ffmpeg is not installed',
|
||||
'creating_temp': 'creating temporary resources',
|
||||
'extracting_frames': 'extracting frames with a resolution of {resolution} and {fps} frames per second',
|
||||
'extracting_frames_succeeded': 'extracting frames succeeded',
|
||||
'extracting_frames_failed': 'extracting frames failed',
|
||||
'analysing': 'analysing',
|
||||
'extracting': 'extracting',
|
||||
'streaming': 'streaming',
|
||||
'processing': 'processing',
|
||||
'merging': 'merging',
|
||||
'downloading': 'downloading',
|
||||
'temp_frames_not_found': 'temporary frames not found',
|
||||
'copying_image': 'copying image with a resolution of {resolution}',
|
||||
'copying_image_succeeded': 'copying image succeeded',
|
||||
'copying_image_failed': 'copying image failed',
|
||||
'finalizing_image': 'finalizing image with a resolution of {resolution}',
|
||||
'finalizing_image_succeeded': 'finalizing image succeeded',
|
||||
'finalizing_image_skipped': 'finalizing image skipped',
|
||||
'merging_video': 'merging video with a resolution of {resolution} and {fps} frames per second',
|
||||
'merging_video_succeeded': 'merging video succeeded',
|
||||
'merging_video_failed': 'merging video failed',
|
||||
'skipping_audio': 'skipping audio',
|
||||
'replacing_audio_succeeded': 'replacing audio succeeded',
|
||||
'replacing_audio_skipped': 'replacing audio skipped',
|
||||
'restoring_audio_succeeded': 'restoring audio succeeded',
|
||||
'restoring_audio_skipped': 'restoring audio skipped',
|
||||
'clearing_temp': 'clearing temporary resources',
|
||||
'processing_stopped': 'processing stopped',
|
||||
'processing_image_succeeded': 'processing to image succeeded in {seconds} seconds',
|
||||
'processing_image_failed': 'processing to image failed',
|
||||
'processing_video_succeeded': 'processing to video succeeded in {seconds} seconds',
|
||||
'processing_video_failed': 'processing to video failed',
|
||||
'choose_image_source': 'choose an image for the source',
|
||||
'choose_audio_source': 'choose an audio for the source',
|
||||
'choose_video_target': 'choose a video for the target',
|
||||
'choose_image_or_video_target': 'choose an image or video for the target',
|
||||
'specify_image_or_video_output': 'specify the output image or video within a directory',
|
||||
'match_target_and_output_extension': 'match the target and output extension',
|
||||
'no_source_face_detected': 'no source face detected',
|
||||
'processor_not_loaded': 'processor {processor} could not be loaded',
|
||||
'processor_not_implemented': 'processor {processor} not implemented correctly',
|
||||
'ui_layout_not_loaded': 'ui layout {ui_layout} could not be loaded',
|
||||
'ui_layout_not_implemented': 'ui layout {ui_layout} not implemented correctly',
|
||||
'stream_not_loaded': 'stream {stream_mode} could not be loaded',
|
||||
'stream_not_supported': 'stream not supported',
|
||||
'job_created': 'job {job_id} created',
|
||||
'job_not_created': 'job {job_id} not created',
|
||||
'job_submitted': 'job {job_id} submitted',
|
||||
'job_not_submitted': 'job {job_id} not submitted',
|
||||
'job_all_submitted': 'jobs submitted',
|
||||
'job_all_not_submitted': 'jobs not submitted',
|
||||
'job_deleted': 'job {job_id} deleted',
|
||||
'job_not_deleted': 'job {job_id} not deleted',
|
||||
'job_all_deleted': 'jobs deleted',
|
||||
'job_all_not_deleted': 'jobs not deleted',
|
||||
'job_step_added': 'step added to job {job_id}',
|
||||
'job_step_not_added': 'step not added to job {job_id}',
|
||||
'job_remix_step_added': 'step {step_index} remixed from job {job_id}',
|
||||
'job_remix_step_not_added': 'step {step_index} not remixed from job {job_id}',
|
||||
'job_step_inserted': 'step {step_index} inserted to job {job_id}',
|
||||
'job_step_not_inserted': 'step {step_index} not inserted to job {job_id}',
|
||||
'job_step_removed': 'step {step_index} removed from job {job_id}',
|
||||
'job_step_not_removed': 'step {step_index} not removed from job {job_id}',
|
||||
'running_job': 'running queued job {job_id}',
|
||||
'running_jobs': 'running all queued jobs',
|
||||
'retrying_job': 'retrying failed job {job_id}',
|
||||
'retrying_jobs': 'retrying all failed jobs',
|
||||
'processing_job_succeeded': 'processing of job {job_id} succeeded',
|
||||
'processing_jobs_succeeded': 'processing of all jobs succeeded',
|
||||
'processing_job_failed': 'processing of job {job_id} failed',
|
||||
'processing_jobs_failed': 'processing of all jobs failed',
|
||||
'processing_step': 'processing step {step_current} of {step_total}',
|
||||
'validating_hash_succeeded': 'validating hash for {hash_file_name} succeeded',
|
||||
'validating_hash_failed': 'validating hash for {hash_file_name} failed',
|
||||
'validating_source_succeeded': 'validating source for {source_file_name} succeeded',
|
||||
'validating_source_failed': 'validating source for {source_file_name} failed',
|
||||
'deleting_corrupt_source': 'deleting corrupt source for {source_file_name}',
|
||||
'loading_model_succeeded': 'loading model {model_name} succeeded in {seconds} seconds',
|
||||
'loading_model_failed': 'loading model {model_name} failed',
|
||||
'time_ago_now': 'just now',
|
||||
'time_ago_minutes': '{minutes} minutes ago',
|
||||
'time_ago_hours': '{hours} hours and {minutes} minutes ago',
|
||||
'time_ago_days': '{days} days, {hours} hours and {minutes} minutes ago',
|
||||
'point': '.',
|
||||
'comma': ',',
|
||||
'colon': ':',
|
||||
'question_mark': '?',
|
||||
'exclamation_mark': '!',
|
||||
'help':
|
||||
{
|
||||
'install_dependency': 'choose the variant of {dependency} to install',
|
||||
'skip_conda': 'skip the conda environment check',
|
||||
'config_path': 'choose the config file to override defaults',
|
||||
'temp_path': 'specify the directory for the temporary resources',
|
||||
'jobs_path': 'specify the directory to store jobs',
|
||||
'source_paths': 'choose the image or audio paths',
|
||||
'target_path': 'choose the image or video path',
|
||||
'output_path': 'specify the image or video within a directory',
|
||||
'source_pattern': 'choose the image or audio pattern',
|
||||
'target_pattern': 'choose the image or video pattern',
|
||||
'output_pattern': 'specify the image or video pattern',
|
||||
'face_detector_model': 'choose the model responsible for detecting the faces',
|
||||
'face_detector_size': 'specify the frame size provided to the face detector',
|
||||
'face_detector_margin': 'apply top, right, bottom and left margin to the frame',
|
||||
'face_detector_angles': 'specify the angles to rotate the frame before detecting faces',
|
||||
'face_detector_score': 'filter the detected faces based on the confidence score',
|
||||
'face_landmarker_model': 'choose the model responsible for detecting the face landmarks',
|
||||
'face_landmarker_score': 'filter the detected face landmarks based on the confidence score',
|
||||
'face_selector_mode': 'use reference based tracking or simple matching',
|
||||
'face_selector_order': 'specify the order of the detected faces',
|
||||
'face_selector_age_start': 'filter the detected faces based on the starting age',
|
||||
'face_selector_age_end': 'filter the detected faces based on the ending age',
|
||||
'face_selector_gender': 'filter the detected faces based on their gender',
|
||||
'face_selector_race': 'filter the detected faces based on their race',
|
||||
'reference_face_position': 'specify the position used to create the reference face',
|
||||
'reference_face_distance': 'specify the similarity between the reference face and target face',
|
||||
'reference_frame_number': 'specify the frame used to create the reference face',
|
||||
'face_tracker_score': 'specify the overlap score used to match the tracked faces',
|
||||
'face_occluder_model': 'choose the model responsible for the occlusion mask',
|
||||
'face_parser_model': 'choose the model responsible for the region mask',
|
||||
'face_mask_types': 'mix and match different face mask types (choices: {choices})',
|
||||
'face_mask_areas': 'choose the items used for the area mask (choices: {choices})',
|
||||
'face_mask_regions': 'choose the items used for the region mask (choices: {choices})',
|
||||
'face_mask_blur': 'specify the degree of blur applied to the box mask',
|
||||
'face_mask_padding': 'apply top, right, bottom and left padding to the box mask',
|
||||
'voice_extractor_model': 'choose the model responsible for extracting the voices',
|
||||
'trim_frame_start': 'specify the starting frame of the target video',
|
||||
'trim_frame_end': 'specify the ending frame of the target video',
|
||||
'temp_frame_format': 'specify the temporary resources format',
|
||||
'keep_temp': 'keep the temporary resources after processing',
|
||||
'target_frame_amount': 'specify the amount of target frames forwarded to the processor',
|
||||
'output_image_quality': 'specify the image quality which translates to the image compression',
|
||||
'output_image_scale': 'specify the image scale based on the target image',
|
||||
'output_audio_encoder': 'specify the encoder used for the audio',
|
||||
'output_audio_quality': 'specify the audio quality which translates to the audio compression',
|
||||
'output_audio_volume': 'specify the audio volume based on the target video',
|
||||
'output_video_encoder': 'specify the encoder used for the video',
|
||||
'output_video_preset': 'balance fast video processing and video file size',
|
||||
'output_video_quality': 'specify the video quality which translates to the video compression',
|
||||
'output_video_scale': 'specify the video scale based on the target video',
|
||||
'output_video_fps': 'specify the video fps based on the target video',
|
||||
'processors': 'load a single or multiple processors (choices: {choices}, ...)',
|
||||
'background-remover-model': 'choose the model responsible for removing the background',
|
||||
'background-remover-color': 'apply red, green blue and alpha values of the background',
|
||||
'open_browser': 'open the browser once the program is ready',
|
||||
'ui_layouts': 'launch a single or multiple UI layouts (choices: {choices}, ...)',
|
||||
'ui_workflow': 'choose the ui workflow',
|
||||
'download_providers': 'download using different providers (choices: {choices}, ...)',
|
||||
'download_scope': 'specify the download scope',
|
||||
'benchmark_mode': 'choose the benchmark mode',
|
||||
'benchmark_resolutions': 'choose the resolutions for the benchmarks (choices: {choices}, ...)',
|
||||
'benchmark_cycle_count': 'specify the amount of cycles per benchmark',
|
||||
'execution_device_ids': 'specify the devices used for processing',
|
||||
'execution_providers': 'inference using different providers (choices: {choices}, ...)',
|
||||
'execution_thread_count': 'specify the amount of parallel threads while processing',
|
||||
'video_memory_strategy': 'balance fast processing and low VRAM usage',
|
||||
'log_level': 'adjust the message severity displayed in the terminal',
|
||||
'halt_on_error': 'halt the program once an error occurred',
|
||||
'run': 'run the program',
|
||||
'headless_run': 'run the program in headless mode',
|
||||
'batch_run': 'run the program in batch mode',
|
||||
'force_download': 'force automate downloads and exit',
|
||||
'benchmark': 'benchmark the program',
|
||||
'job_id': 'specify the job id',
|
||||
'job_status': 'specify the job status',
|
||||
'step_index': 'specify the step index',
|
||||
'job_list': 'list jobs by status',
|
||||
'job_create': 'create a drafted job',
|
||||
'job_submit': 'submit a drafted job to become a queued job',
|
||||
'job_submit_all': 'submit all drafted jobs to become a queued jobs',
|
||||
'job_delete': 'delete a drafted, queued, failed or completed job',
|
||||
'job_delete_all': 'delete all drafted, queued, failed and completed jobs',
|
||||
'job_add_step': 'add a step to a drafted job',
|
||||
'job_remix_step': 'remix a previous step from a drafted job',
|
||||
'job_insert_step': 'insert a step to a drafted job',
|
||||
'job_remove_step': 'remove a step from a drafted job',
|
||||
'job_run': 'run a queued job',
|
||||
'job_run_all': 'run all queued jobs',
|
||||
'job_retry': 'retry a failed job',
|
||||
'job_retry_all': 'retry all failed jobs'
|
||||
},
|
||||
'about':
|
||||
{
|
||||
'fund': 'fund ai workstation',
|
||||
'subscribe': 'become a member',
|
||||
'join': 'join our community'
|
||||
},
|
||||
'uis':
|
||||
{
|
||||
'apply_button': 'APPLY',
|
||||
'benchmark_mode_dropdown': 'BENCHMARK MODE',
|
||||
'benchmark_cycle_count_slider': 'BENCHMARK CYCLE COUNT',
|
||||
'benchmark_resolutions_checkbox_group': 'BENCHMARK RESOLUTIONS',
|
||||
'clear_button': 'CLEAR',
|
||||
'common_options_checkbox_group': 'OPTIONS',
|
||||
'download_providers_checkbox_group': 'DOWNLOAD PROVIDERS',
|
||||
'execution_providers_checkbox_group': 'EXECUTION PROVIDERS',
|
||||
'execution_thread_count_slider': 'EXECUTION THREAD COUNT',
|
||||
'face_detector_angles_checkbox_group': 'FACE DETECTOR ANGLES',
|
||||
'face_detector_model_dropdown': 'FACE DETECTOR MODEL',
|
||||
'face_detector_margin_slider': 'FACE DETECTOR MARGIN',
|
||||
'face_detector_score_slider': 'FACE DETECTOR SCORE',
|
||||
'face_detector_size_dropdown': 'FACE DETECTOR SIZE',
|
||||
'face_landmarker_model_dropdown': 'FACE LANDMARKER MODEL',
|
||||
'face_landmarker_score_slider': 'FACE LANDMARKER SCORE',
|
||||
'face_mask_blur_slider': 'FACE MASK BLUR',
|
||||
'face_mask_padding_bottom_slider': 'FACE MASK PADDING BOTTOM',
|
||||
'face_mask_padding_left_slider': 'FACE MASK PADDING LEFT',
|
||||
'face_mask_padding_right_slider': 'FACE MASK PADDING RIGHT',
|
||||
'face_mask_padding_top_slider': 'FACE MASK PADDING TOP',
|
||||
'face_mask_areas_checkbox_group': 'FACE MASK AREAS',
|
||||
'face_mask_regions_checkbox_group': 'FACE MASK REGIONS',
|
||||
'face_mask_types_checkbox_group': 'FACE MASK TYPES',
|
||||
'face_selector_age_range_slider': 'FACE SELECTOR AGE',
|
||||
'face_selector_gender_dropdown': 'FACE SELECTOR GENDER',
|
||||
'face_selector_mode_dropdown': 'FACE SELECTOR MODE',
|
||||
'face_selector_order_dropdown': 'FACE SELECTOR ORDER',
|
||||
'face_selector_race_dropdown': 'FACE SELECTOR RACE',
|
||||
'face_tracker_score_slider': 'FACE TRACKER SCORE',
|
||||
'face_occluder_model_dropdown': 'FACE OCCLUDER MODEL',
|
||||
'face_parser_model_dropdown': 'FACE PARSER MODEL',
|
||||
'voice_extractor_model_dropdown': 'VOICE EXTRACTOR MODEL',
|
||||
'job_list_status_checkbox_group': 'JOB STATUS',
|
||||
'job_manager_job_action_dropdown': 'JOB_ACTION',
|
||||
'job_manager_job_id_dropdown': 'JOB ID',
|
||||
'job_manager_step_index_dropdown': 'STEP INDEX',
|
||||
'job_runner_job_action_dropdown': 'JOB ACTION',
|
||||
'job_runner_job_id_dropdown': 'JOB ID',
|
||||
'log_level_dropdown': 'LOG LEVEL',
|
||||
'output_audio_encoder_dropdown': 'OUTPUT AUDIO ENCODER',
|
||||
'output_audio_quality_slider': 'OUTPUT AUDIO QUALITY',
|
||||
'output_audio_volume_slider': 'OUTPUT AUDIO VOLUME',
|
||||
'output_image_or_video': 'OUTPUT',
|
||||
'output_image_quality_slider': 'OUTPUT IMAGE QUALITY',
|
||||
'output_image_scale_slider': 'OUTPUT IMAGE SCALE',
|
||||
'output_path_textbox': 'OUTPUT PATH',
|
||||
'output_video_encoder_dropdown': 'OUTPUT VIDEO ENCODER',
|
||||
'output_video_fps_slider': 'OUTPUT VIDEO FPS',
|
||||
'output_video_preset_dropdown': 'OUTPUT VIDEO PRESET',
|
||||
'output_video_quality_slider': 'OUTPUT VIDEO QUALITY',
|
||||
'output_video_scale_slider': 'OUTPUT VIDEO SCALE',
|
||||
'preview_frame_slider': 'PREVIEW FRAME',
|
||||
'preview_image': 'PREVIEW',
|
||||
'preview_mode_dropdown': 'PREVIEW MODE',
|
||||
'preview_resolution_dropdown': 'PREVIEW RESOLUTION',
|
||||
'processors_checkbox_group': 'PROCESSORS',
|
||||
'reference_face_distance_slider': 'REFERENCE FACE DISTANCE',
|
||||
'reference_face_gallery': 'REFERENCE FACE',
|
||||
'refresh_button': 'REFRESH',
|
||||
'source_file': 'SOURCE',
|
||||
'start_button': 'START',
|
||||
'stop_button': 'STOP',
|
||||
'target_file': 'TARGET',
|
||||
'temp_frame_format_dropdown': 'TEMP FRAME FORMAT',
|
||||
'terminal_textbox': 'TERMINAL',
|
||||
'trim_frame_slider': 'TRIM FRAME',
|
||||
'ui_workflow': 'UI WORKFLOW',
|
||||
'video_memory_strategy_dropdown': 'VIDEO MEMORY STRATEGY',
|
||||
'webcam_fps_slider': 'WEBCAM FPS',
|
||||
'webcam_image': 'WEBCAM',
|
||||
'webcam_device_id_dropdown': 'WEBCAM DEVICE ID',
|
||||
'webcam_mode_radio': 'WEBCAM MODE',
|
||||
'webcam_resolution_dropdown': 'WEBCAM RESOLUTION'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
from facefusion.common_helper import is_macos, is_windows
|
||||
|
||||
if is_windows():
|
||||
import ctypes
|
||||
else:
|
||||
import resource
|
||||
|
||||
|
||||
def limit_system_memory(system_memory_limit : int = 1) -> bool:
|
||||
if is_macos():
|
||||
system_memory_limit = system_memory_limit * (1024 ** 6)
|
||||
else:
|
||||
system_memory_limit = system_memory_limit * (1024 ** 3)
|
||||
try:
|
||||
if is_windows():
|
||||
ctypes.windll.kernel32.SetProcessWorkingSetSize(-1, ctypes.c_size_t(system_memory_limit), ctypes.c_size_t(system_memory_limit)) #type:ignore[attr-defined]
|
||||
else:
|
||||
resource.setrlimit(resource.RLIMIT_DATA, (system_memory_limit, system_memory_limit))
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
@@ -4,7 +4,7 @@ METADATA =\
|
||||
{
|
||||
'name': 'FaceFusion',
|
||||
'description': 'Industry leading face manipulation platform',
|
||||
'version': '3.4.0',
|
||||
'version': '3.7.1',
|
||||
'license': 'OpenRAIL-AS',
|
||||
'author': 'Henry Ruhs',
|
||||
'url': 'https://facefusion.io'
|
||||
@@ -12,6 +12,4 @@ METADATA =\
|
||||
|
||||
|
||||
def get(key : str) -> Optional[str]:
|
||||
if key in METADATA:
|
||||
return METADATA.get(key)
|
||||
return None
|
||||
|
||||
+22
-10
@@ -1,17 +1,29 @@
|
||||
from typing import List, Optional
|
||||
|
||||
from facefusion.types import Fps, Padding
|
||||
from facefusion.types import Color, Fps, Padding
|
||||
|
||||
|
||||
def normalize_padding(padding : Optional[List[int]]) -> Optional[Padding]:
|
||||
if padding and len(padding) == 1:
|
||||
return tuple([ padding[0] ] * 4) #type:ignore[return-value]
|
||||
if padding and len(padding) == 2:
|
||||
return tuple([ padding[0], padding[1], padding[0], padding[1] ]) #type:ignore[return-value]
|
||||
if padding and len(padding) == 3:
|
||||
return tuple([ padding[0], padding[1], padding[2], padding[1] ]) #type:ignore[return-value]
|
||||
if padding and len(padding) == 4:
|
||||
return tuple(padding) #type:ignore[return-value]
|
||||
def normalize_color(channels : Optional[List[int]]) -> Optional[Color]:
|
||||
if channels and len(channels) == 1:
|
||||
return tuple([ channels[0], channels[0], channels[0], 255 ]) #type:ignore[return-value]
|
||||
if channels and len(channels) == 2:
|
||||
return tuple([ channels[0], channels[1], channels[0], 255 ]) #type:ignore[return-value]
|
||||
if channels and len(channels) == 3:
|
||||
return tuple([ channels[0], channels[1], channels[2], 255 ]) #type:ignore[return-value]
|
||||
if channels and len(channels) == 4:
|
||||
return tuple(channels) #type:ignore[return-value]
|
||||
return None
|
||||
|
||||
|
||||
def normalize_space(spaces : Optional[List[int]]) -> Optional[Padding]:
|
||||
if spaces and len(spaces) == 1:
|
||||
return tuple([spaces[0]] * 4) #type:ignore[return-value]
|
||||
if spaces and len(spaces) == 2:
|
||||
return tuple([ spaces[0], spaces[1], spaces[0], spaces[1] ]) #type:ignore[return-value]
|
||||
if spaces and len(spaces) == 3:
|
||||
return tuple([ spaces[0], spaces[1], spaces[2], spaces[1] ]) #type:ignore[return-value]
|
||||
if spaces and len(spaces) == 4:
|
||||
return tuple(spaces) #type:ignore[return-value]
|
||||
return None
|
||||
|
||||
|
||||
|
||||
@@ -2,15 +2,17 @@ import importlib
|
||||
from types import ModuleType
|
||||
from typing import Any, List
|
||||
|
||||
from facefusion import logger, wording
|
||||
from facefusion import logger, translator
|
||||
from facefusion.exit_helper import hard_exit
|
||||
|
||||
|
||||
PROCESSORS_METHODS =\
|
||||
[
|
||||
'get_inference_pool',
|
||||
'clear_inference_pool',
|
||||
'register_args',
|
||||
'apply_args',
|
||||
'get_common_modules',
|
||||
'pre_check',
|
||||
'pre_process',
|
||||
'post_process',
|
||||
@@ -20,16 +22,16 @@ PROCESSORS_METHODS =\
|
||||
|
||||
def load_processor_module(processor : str) -> Any:
|
||||
try:
|
||||
processor_module = importlib.import_module('facefusion.processors.modules.' + processor)
|
||||
processor_module = importlib.import_module('facefusion.processors.modules.' + processor + '.core')
|
||||
for method_name in PROCESSORS_METHODS:
|
||||
if not hasattr(processor_module, method_name):
|
||||
raise NotImplementedError
|
||||
except ModuleNotFoundError as exception:
|
||||
logger.error(wording.get('processor_not_loaded').format(processor = processor), __name__)
|
||||
logger.error(translator.get('processor_not_loaded').format(processor = processor), __name__)
|
||||
logger.debug(exception.msg, __name__)
|
||||
hard_exit(1)
|
||||
except NotImplementedError:
|
||||
logger.error(wording.get('processor_not_implemented').format(processor = processor), __name__)
|
||||
logger.error(translator.get('processor_not_implemented').format(processor = processor), __name__)
|
||||
hard_exit(1)
|
||||
return processor_module
|
||||
|
||||
|
||||
@@ -1,209 +0,0 @@
|
||||
from argparse import ArgumentParser
|
||||
from functools import lru_cache
|
||||
|
||||
import cv2
|
||||
import numpy
|
||||
|
||||
import facefusion.choices
|
||||
import facefusion.jobs.job_manager
|
||||
import facefusion.jobs.job_store
|
||||
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, inference_manager, logger, state_manager, video_manager, wording
|
||||
from facefusion.common_helper import create_int_metavar, is_macos
|
||||
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
||||
from facefusion.execution import has_execution_provider
|
||||
from facefusion.face_helper import merge_matrix, paste_back, scale_face_landmark_5, warp_face_by_face_landmark_5
|
||||
from facefusion.face_masker import create_box_mask, create_occlusion_mask
|
||||
from facefusion.face_selector import select_faces
|
||||
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path, same_file_extension
|
||||
from facefusion.processors import choices as processors_choices
|
||||
from facefusion.processors.types import AgeModifierDirection, AgeModifierInputs
|
||||
from facefusion.program_helper import find_argument_group
|
||||
from facefusion.thread_helper import thread_semaphore
|
||||
from facefusion.types import ApplyStateItem, Args, DownloadScope, Face, InferencePool, ModelOptions, ModelSet, ProcessMode, VisionFrame
|
||||
from facefusion.vision import match_frame_color, read_static_image, read_static_video_frame
|
||||
|
||||
|
||||
@lru_cache()
|
||||
def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
return\
|
||||
{
|
||||
'styleganex_age':
|
||||
{
|
||||
'hashes':
|
||||
{
|
||||
'age_modifier':
|
||||
{
|
||||
'url': resolve_download_url('models-3.1.0', 'styleganex_age.hash'),
|
||||
'path': resolve_relative_path('../.assets/models/styleganex_age.hash')
|
||||
}
|
||||
},
|
||||
'sources':
|
||||
{
|
||||
'age_modifier':
|
||||
{
|
||||
'url': resolve_download_url('models-3.1.0', 'styleganex_age.onnx'),
|
||||
'path': resolve_relative_path('../.assets/models/styleganex_age.onnx')
|
||||
}
|
||||
},
|
||||
'templates':
|
||||
{
|
||||
'target': 'ffhq_512',
|
||||
'target_with_background': 'styleganex_384'
|
||||
},
|
||||
'sizes':
|
||||
{
|
||||
'target': (256, 256),
|
||||
'target_with_background': (384, 384)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def get_inference_pool() -> InferencePool:
|
||||
model_names = [ state_manager.get_item('age_modifier_model') ]
|
||||
model_source_set = get_model_options().get('sources')
|
||||
|
||||
return inference_manager.get_inference_pool(__name__, model_names, model_source_set)
|
||||
|
||||
|
||||
def clear_inference_pool() -> None:
|
||||
model_names = [ state_manager.get_item('age_modifier_model') ]
|
||||
inference_manager.clear_inference_pool(__name__, model_names)
|
||||
|
||||
|
||||
def get_model_options() -> ModelOptions:
|
||||
model_name = state_manager.get_item('age_modifier_model')
|
||||
return create_static_model_set('full').get(model_name)
|
||||
|
||||
|
||||
def register_args(program : ArgumentParser) -> None:
|
||||
group_processors = find_argument_group(program, 'processors')
|
||||
if group_processors:
|
||||
group_processors.add_argument('--age-modifier-model', help = wording.get('help.age_modifier_model'), default = config.get_str_value('processors', 'age_modifier_model', 'styleganex_age'), choices = processors_choices.age_modifier_models)
|
||||
group_processors.add_argument('--age-modifier-direction', help = wording.get('help.age_modifier_direction'), type = int, default = config.get_int_value('processors', 'age_modifier_direction', '0'), choices = processors_choices.age_modifier_direction_range, metavar = create_int_metavar(processors_choices.age_modifier_direction_range))
|
||||
facefusion.jobs.job_store.register_step_keys([ 'age_modifier_model', 'age_modifier_direction' ])
|
||||
|
||||
|
||||
def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
|
||||
apply_state_item('age_modifier_model', args.get('age_modifier_model'))
|
||||
apply_state_item('age_modifier_direction', args.get('age_modifier_direction'))
|
||||
|
||||
|
||||
def pre_check() -> bool:
|
||||
model_hash_set = get_model_options().get('hashes')
|
||||
model_source_set = get_model_options().get('sources')
|
||||
|
||||
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
||||
|
||||
|
||||
def pre_process(mode : ProcessMode) -> bool:
|
||||
if mode in [ 'output', 'preview' ] and not is_image(state_manager.get_item('target_path')) and not is_video(state_manager.get_item('target_path')):
|
||||
logger.error(wording.get('choose_image_or_video_target') + wording.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
if mode == 'output' and not in_directory(state_manager.get_item('output_path')):
|
||||
logger.error(wording.get('specify_image_or_video_output') + wording.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
if mode == 'output' and not same_file_extension(state_manager.get_item('target_path'), state_manager.get_item('output_path')):
|
||||
logger.error(wording.get('match_target_and_output_extension') + wording.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def post_process() -> None:
|
||||
read_static_image.cache_clear()
|
||||
read_static_video_frame.cache_clear()
|
||||
video_manager.clear_video_pool()
|
||||
if state_manager.get_item('video_memory_strategy') in [ 'strict', 'moderate' ]:
|
||||
clear_inference_pool()
|
||||
if state_manager.get_item('video_memory_strategy') == 'strict':
|
||||
content_analyser.clear_inference_pool()
|
||||
face_classifier.clear_inference_pool()
|
||||
face_detector.clear_inference_pool()
|
||||
face_landmarker.clear_inference_pool()
|
||||
face_masker.clear_inference_pool()
|
||||
face_recognizer.clear_inference_pool()
|
||||
|
||||
|
||||
def modify_age(target_face : Face, temp_vision_frame : VisionFrame) -> VisionFrame:
|
||||
model_templates = get_model_options().get('templates')
|
||||
model_sizes = get_model_options().get('sizes')
|
||||
face_landmark_5 = target_face.landmark_set.get('5/68').copy()
|
||||
crop_vision_frame, affine_matrix = warp_face_by_face_landmark_5(temp_vision_frame, face_landmark_5, model_templates.get('target'), model_sizes.get('target'))
|
||||
extend_face_landmark_5 = scale_face_landmark_5(face_landmark_5, 0.875)
|
||||
extend_vision_frame, extend_affine_matrix = warp_face_by_face_landmark_5(temp_vision_frame, extend_face_landmark_5, model_templates.get('target_with_background'), model_sizes.get('target_with_background'))
|
||||
extend_vision_frame_raw = extend_vision_frame.copy()
|
||||
box_mask = create_box_mask(extend_vision_frame, state_manager.get_item('face_mask_blur'), (0, 0, 0, 0))
|
||||
crop_masks =\
|
||||
[
|
||||
box_mask
|
||||
]
|
||||
|
||||
if 'occlusion' in state_manager.get_item('face_mask_types'):
|
||||
occlusion_mask = create_occlusion_mask(crop_vision_frame)
|
||||
temp_matrix = merge_matrix([ extend_affine_matrix, cv2.invertAffineTransform(affine_matrix) ])
|
||||
occlusion_mask = cv2.warpAffine(occlusion_mask, temp_matrix, model_sizes.get('target_with_background'))
|
||||
crop_masks.append(occlusion_mask)
|
||||
|
||||
crop_vision_frame = prepare_vision_frame(crop_vision_frame)
|
||||
extend_vision_frame = prepare_vision_frame(extend_vision_frame)
|
||||
age_modifier_direction = numpy.array(numpy.interp(state_manager.get_item('age_modifier_direction'), [ -100, 100 ], [ 2.5, -2.5 ])).astype(numpy.float32)
|
||||
extend_vision_frame = forward(crop_vision_frame, extend_vision_frame, age_modifier_direction)
|
||||
extend_vision_frame = normalize_extend_frame(extend_vision_frame)
|
||||
extend_vision_frame = match_frame_color(extend_vision_frame_raw, extend_vision_frame)
|
||||
extend_affine_matrix *= (model_sizes.get('target')[0] * 4) / model_sizes.get('target_with_background')[0]
|
||||
crop_mask = numpy.minimum.reduce(crop_masks).clip(0, 1)
|
||||
crop_mask = cv2.resize(crop_mask, (model_sizes.get('target')[0] * 4, model_sizes.get('target')[1] * 4))
|
||||
paste_vision_frame = paste_back(temp_vision_frame, extend_vision_frame, crop_mask, extend_affine_matrix)
|
||||
return paste_vision_frame
|
||||
|
||||
|
||||
def forward(crop_vision_frame : VisionFrame, extend_vision_frame : VisionFrame, age_modifier_direction : AgeModifierDirection) -> VisionFrame:
|
||||
age_modifier = get_inference_pool().get('age_modifier')
|
||||
age_modifier_inputs = {}
|
||||
|
||||
if is_macos() and has_execution_provider('coreml'):
|
||||
age_modifier.set_providers([ facefusion.choices.execution_provider_set.get('cpu') ])
|
||||
|
||||
for age_modifier_input in age_modifier.get_inputs():
|
||||
if age_modifier_input.name == 'target':
|
||||
age_modifier_inputs[age_modifier_input.name] = crop_vision_frame
|
||||
if age_modifier_input.name == 'target_with_background':
|
||||
age_modifier_inputs[age_modifier_input.name] = extend_vision_frame
|
||||
if age_modifier_input.name == 'direction':
|
||||
age_modifier_inputs[age_modifier_input.name] = age_modifier_direction
|
||||
|
||||
with thread_semaphore():
|
||||
crop_vision_frame = age_modifier.run(None, age_modifier_inputs)[0][0]
|
||||
|
||||
return crop_vision_frame
|
||||
|
||||
|
||||
def prepare_vision_frame(vision_frame : VisionFrame) -> VisionFrame:
|
||||
vision_frame = vision_frame[:, :, ::-1] / 255.0
|
||||
vision_frame = (vision_frame - 0.5) / 0.5
|
||||
vision_frame = numpy.expand_dims(vision_frame.transpose(2, 0, 1), axis = 0).astype(numpy.float32)
|
||||
return vision_frame
|
||||
|
||||
|
||||
def normalize_extend_frame(extend_vision_frame : VisionFrame) -> VisionFrame:
|
||||
model_sizes = get_model_options().get('sizes')
|
||||
extend_vision_frame = numpy.clip(extend_vision_frame, -1, 1)
|
||||
extend_vision_frame = (extend_vision_frame + 1) / 2
|
||||
extend_vision_frame = extend_vision_frame.transpose(1, 2, 0).clip(0, 255)
|
||||
extend_vision_frame = (extend_vision_frame * 255.0)
|
||||
extend_vision_frame = extend_vision_frame.astype(numpy.uint8)[:, :, ::-1]
|
||||
extend_vision_frame = cv2.resize(extend_vision_frame, (model_sizes.get('target')[0] * 4, model_sizes.get('target')[1] * 4), interpolation = cv2.INTER_AREA)
|
||||
return extend_vision_frame
|
||||
|
||||
|
||||
def process_frame(inputs : AgeModifierInputs) -> VisionFrame:
|
||||
reference_vision_frame = inputs.get('reference_vision_frame')
|
||||
target_vision_frame = inputs.get('target_vision_frame')
|
||||
temp_vision_frame = inputs.get('temp_vision_frame')
|
||||
target_faces = select_faces(reference_vision_frame, target_vision_frame)
|
||||
|
||||
if target_faces:
|
||||
for target_face in target_faces:
|
||||
temp_vision_frame = modify_age(target_face, temp_vision_frame)
|
||||
|
||||
return temp_vision_frame
|
||||
@@ -0,0 +1,8 @@
|
||||
from typing import List, Sequence, get_args
|
||||
|
||||
from facefusion.common_helper import create_int_range
|
||||
from facefusion.processors.modules.age_modifier.types import AgeModifierModel
|
||||
|
||||
age_modifier_models : List[AgeModifierModel] = list(get_args(AgeModifierModel))
|
||||
|
||||
age_modifier_direction_range : Sequence[int] = create_int_range(-100, 100, 1)
|
||||
+301
@@ -0,0 +1,301 @@
|
||||
from argparse import ArgumentParser
|
||||
from functools import lru_cache
|
||||
from types import ModuleType
|
||||
from typing import List
|
||||
|
||||
import cv2
|
||||
import numpy
|
||||
|
||||
import facefusion.choices
|
||||
import facefusion.jobs.job_manager
|
||||
import facefusion.jobs.job_store
|
||||
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, inference_manager, logger, state_manager, translator, video_manager
|
||||
from facefusion.common_helper import create_int_metavar, get_middle
|
||||
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
||||
from facefusion.face_creator import scale_face
|
||||
from facefusion.face_helper import merge_matrix, paste_back, scale_face_landmark_5, warp_face_by_face_landmark_5
|
||||
from facefusion.face_masker import create_box_mask, create_occlusion_mask
|
||||
from facefusion.face_selector import select_faces
|
||||
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path, same_file_extension
|
||||
from facefusion.processors.modules.age_modifier import choices as age_modifier_choices
|
||||
from facefusion.processors.modules.age_modifier.types import AgeModifierDirection, AgeModifierInputs
|
||||
from facefusion.processors.types import ProcessorOutputs
|
||||
from facefusion.program_helper import find_argument_group
|
||||
from facefusion.thread_helper import thread_semaphore
|
||||
from facefusion.types import ApplyStateItem, Args, DownloadScope, Face, InferencePool, ModelOptions, ModelSet, ProcessMode, VisionFrame
|
||||
from facefusion.vision import match_frame_color, read_static_image, read_static_video_chunk, read_static_video_frame
|
||||
|
||||
|
||||
@lru_cache()
|
||||
def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
return\
|
||||
{
|
||||
'fran':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'ry-lu',
|
||||
'license': 'mit',
|
||||
'year': 2024
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'age_modifier':
|
||||
{
|
||||
'url': resolve_download_url('models-3.6.0', 'fran.hash'),
|
||||
'path': resolve_relative_path('../.assets/models/fran.hash')
|
||||
}
|
||||
},
|
||||
'sources':
|
||||
{
|
||||
'age_modifier':
|
||||
{
|
||||
'url': resolve_download_url('models-3.6.0', 'fran.onnx'),
|
||||
'path': resolve_relative_path('../.assets/models/fran.onnx')
|
||||
}
|
||||
},
|
||||
'templates':
|
||||
{
|
||||
'target': 'ffhq_512',
|
||||
},
|
||||
'sizes':
|
||||
{
|
||||
'target': (1024, 1024),
|
||||
},
|
||||
'mean': [ 0.0, 0.0, 0.0 ],
|
||||
'standard_deviation': [ 1.0, 1.0, 1.0 ]
|
||||
},
|
||||
'styleganex_age':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'williamyang1991',
|
||||
'license': 'S-Lab-1.0',
|
||||
'year': 2023
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'age_modifier':
|
||||
{
|
||||
'url': resolve_download_url('models-3.1.0', 'styleganex_age.hash'),
|
||||
'path': resolve_relative_path('../.assets/models/styleganex_age.hash')
|
||||
}
|
||||
},
|
||||
'sources':
|
||||
{
|
||||
'age_modifier':
|
||||
{
|
||||
'url': resolve_download_url('models-3.1.0', 'styleganex_age.onnx'),
|
||||
'path': resolve_relative_path('../.assets/models/styleganex_age.onnx')
|
||||
}
|
||||
},
|
||||
'templates':
|
||||
{
|
||||
'target': 'ffhq_512',
|
||||
'target_with_background': 'styleganex_384'
|
||||
},
|
||||
'sizes':
|
||||
{
|
||||
'target': (256, 256),
|
||||
'target_with_background': (384, 384)
|
||||
},
|
||||
'mean': [ 0.5, 0.5, 0.5 ],
|
||||
'standard_deviation': [ 0.5, 0.5, 0.5 ]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def get_inference_pool() -> InferencePool:
|
||||
model_names = [ state_manager.get_item('age_modifier_model') ]
|
||||
model_source_set = get_model_options().get('sources')
|
||||
|
||||
return inference_manager.get_inference_pool(__name__, model_names, model_source_set)
|
||||
|
||||
|
||||
def clear_inference_pool() -> None:
|
||||
model_names = [ state_manager.get_item('age_modifier_model') ]
|
||||
inference_manager.clear_inference_pool(__name__, model_names)
|
||||
|
||||
|
||||
def get_model_options() -> ModelOptions:
|
||||
model_name = state_manager.get_item('age_modifier_model')
|
||||
return create_static_model_set('full').get(model_name)
|
||||
|
||||
|
||||
def register_args(program : ArgumentParser) -> None:
|
||||
group_processors = find_argument_group(program, 'processors')
|
||||
if group_processors:
|
||||
group_processors.add_argument('--age-modifier-model', help = translator.get('help.model', __package__), default = config.get_str_value('processors', 'age_modifier_model', 'fran'), choices = age_modifier_choices.age_modifier_models)
|
||||
group_processors.add_argument('--age-modifier-direction', help = translator.get('help.direction', __package__), type = int, default = config.get_int_value('processors', 'age_modifier_direction', '0'), choices = age_modifier_choices.age_modifier_direction_range, metavar = create_int_metavar(age_modifier_choices.age_modifier_direction_range))
|
||||
facefusion.jobs.job_store.register_step_keys([ 'age_modifier_model', 'age_modifier_direction' ])
|
||||
|
||||
|
||||
def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
|
||||
apply_state_item('age_modifier_model', args.get('age_modifier_model'))
|
||||
apply_state_item('age_modifier_direction', args.get('age_modifier_direction'))
|
||||
|
||||
|
||||
def get_common_modules() -> List[ModuleType]:
|
||||
return [ content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer ]
|
||||
|
||||
|
||||
def pre_check() -> bool:
|
||||
model_hash_set = get_model_options().get('hashes')
|
||||
model_source_set = get_model_options().get('sources')
|
||||
|
||||
for common_module in get_common_modules():
|
||||
if not common_module.pre_check():
|
||||
return False
|
||||
|
||||
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
||||
|
||||
|
||||
def pre_process(mode : ProcessMode) -> bool:
|
||||
if mode in [ 'output', 'preview' ] and not is_image(state_manager.get_item('target_path')) and not is_video(state_manager.get_item('target_path')):
|
||||
logger.error(translator.get('choose_image_or_video_target') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
if mode == 'output' and not in_directory(state_manager.get_item('output_path')):
|
||||
logger.error(translator.get('specify_image_or_video_output') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
if mode == 'output' and not same_file_extension(state_manager.get_item('target_path'), state_manager.get_item('output_path')):
|
||||
logger.error(translator.get('match_target_and_output_extension') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def post_process() -> None:
|
||||
read_static_image.cache_clear()
|
||||
read_static_video_frame.cache_clear()
|
||||
read_static_video_chunk.cache_clear()
|
||||
video_manager.clear_video_pool()
|
||||
|
||||
if state_manager.get_item('video_memory_strategy') in [ 'strict', 'moderate' ]:
|
||||
clear_inference_pool()
|
||||
|
||||
if state_manager.get_item('video_memory_strategy') == 'strict':
|
||||
for common_module in get_common_modules():
|
||||
common_module.clear_inference_pool()
|
||||
|
||||
|
||||
def modify_age(target_face : Face, temp_vision_frame : VisionFrame) -> VisionFrame:
|
||||
model_templates = get_model_options().get('templates')
|
||||
model_sizes = get_model_options().get('sizes')
|
||||
face_landmark_5 = target_face.landmark_set.get('5/68').copy()
|
||||
crop_vision_frame, affine_matrix = warp_face_by_face_landmark_5(temp_vision_frame, face_landmark_5, model_templates.get('target'), model_sizes.get('target'))
|
||||
|
||||
if state_manager.get_item('age_modifier_model') == 'fran':
|
||||
box_mask = create_box_mask(crop_vision_frame, state_manager.get_item('face_mask_blur'), (0, 0, 0, 0))
|
||||
crop_masks =\
|
||||
[
|
||||
box_mask
|
||||
]
|
||||
|
||||
if 'occlusion' in state_manager.get_item('face_mask_types'):
|
||||
occlusion_mask = create_occlusion_mask(crop_vision_frame)
|
||||
crop_masks.append(occlusion_mask)
|
||||
|
||||
crop_vision_frame = prepare_vision_frame(crop_vision_frame)
|
||||
target_age = numpy.mean(target_face.age)
|
||||
age_modifier_direction = numpy.array([ target_age, target_age + state_manager.get_item('age_modifier_direction') ], dtype = numpy.float32) / 100
|
||||
age_modifier_direction = age_modifier_direction.clip(0, 1)
|
||||
crop_vision_frame = forward(crop_vision_frame, crop_vision_frame, age_modifier_direction)
|
||||
crop_vision_frame = normalize_vision_frame(crop_vision_frame)
|
||||
crop_mask = numpy.minimum.reduce(crop_masks).clip(0, 1)
|
||||
paste_vision_frame = paste_back(temp_vision_frame, crop_vision_frame, crop_mask, affine_matrix)
|
||||
return paste_vision_frame
|
||||
|
||||
if state_manager.get_item('age_modifier_model') == 'styleganex_age':
|
||||
extend_face_landmark_5 = scale_face_landmark_5(face_landmark_5, 0.875)
|
||||
extend_vision_frame, extend_affine_matrix = warp_face_by_face_landmark_5(temp_vision_frame, extend_face_landmark_5, model_templates.get('target_with_background'), model_sizes.get('target_with_background'))
|
||||
extend_vision_frame_raw = extend_vision_frame.copy()
|
||||
box_mask = create_box_mask(extend_vision_frame, state_manager.get_item('face_mask_blur'), (0, 0, 0, 0))
|
||||
crop_masks =\
|
||||
[
|
||||
box_mask
|
||||
]
|
||||
|
||||
if 'occlusion' in state_manager.get_item('face_mask_types'):
|
||||
occlusion_mask = create_occlusion_mask(crop_vision_frame)
|
||||
temp_matrix = merge_matrix([ extend_affine_matrix, cv2.invertAffineTransform(affine_matrix) ])
|
||||
occlusion_mask = cv2.warpAffine(occlusion_mask, temp_matrix, model_sizes.get('target_with_background'))
|
||||
crop_masks.append(occlusion_mask)
|
||||
|
||||
crop_vision_frame = prepare_vision_frame(crop_vision_frame)
|
||||
extend_vision_frame = prepare_vision_frame(extend_vision_frame)
|
||||
age_modifier_direction = numpy.array(numpy.interp(state_manager.get_item('age_modifier_direction'), [ -100, 100 ], [ 2.5, -2.5 ])).astype(numpy.float32)
|
||||
extend_vision_frame = forward(crop_vision_frame, extend_vision_frame, age_modifier_direction)
|
||||
extend_vision_frame = normalize_extend_frame(extend_vision_frame)
|
||||
extend_vision_frame = match_frame_color(extend_vision_frame_raw, extend_vision_frame)
|
||||
extend_affine_matrix *= (model_sizes.get('target')[0] * 4) / model_sizes.get('target_with_background')[0]
|
||||
crop_mask = numpy.minimum.reduce(crop_masks).clip(0, 1)
|
||||
crop_mask = cv2.resize(crop_mask, (model_sizes.get('target')[0] * 4, model_sizes.get('target')[1] * 4))
|
||||
paste_vision_frame = paste_back(temp_vision_frame, extend_vision_frame, crop_mask, extend_affine_matrix)
|
||||
return paste_vision_frame
|
||||
|
||||
return temp_vision_frame
|
||||
|
||||
|
||||
def forward(crop_vision_frame : VisionFrame, extend_vision_frame : VisionFrame, age_modifier_direction : AgeModifierDirection) -> VisionFrame:
|
||||
age_modifier = get_inference_pool().get('age_modifier')
|
||||
age_modifier_inputs = {}
|
||||
|
||||
for age_modifier_input in age_modifier.get_inputs():
|
||||
if age_modifier_input.name == 'target':
|
||||
age_modifier_inputs[age_modifier_input.name] = crop_vision_frame
|
||||
if age_modifier_input.name == 'target_with_background':
|
||||
age_modifier_inputs[age_modifier_input.name] = extend_vision_frame
|
||||
if age_modifier_input.name == 'direction':
|
||||
age_modifier_inputs[age_modifier_input.name] = age_modifier_direction
|
||||
|
||||
with thread_semaphore():
|
||||
crop_vision_frame = age_modifier.run(None, age_modifier_inputs)[0][0]
|
||||
|
||||
return crop_vision_frame
|
||||
|
||||
|
||||
def prepare_vision_frame(vision_frame : VisionFrame) -> VisionFrame:
|
||||
model_mean = get_model_options().get('mean')
|
||||
model_standard_deviation = get_model_options().get('standard_deviation')
|
||||
vision_frame = vision_frame[:, :, ::-1] / 255.0
|
||||
vision_frame = (vision_frame - model_mean) / model_standard_deviation
|
||||
vision_frame = numpy.expand_dims(vision_frame.transpose(2, 0, 1), axis = 0).astype(numpy.float32)
|
||||
return vision_frame
|
||||
|
||||
|
||||
def normalize_vision_frame(vision_frame : VisionFrame) -> VisionFrame:
|
||||
model_mean = get_model_options().get('mean')
|
||||
model_standard_deviation = get_model_options().get('standard_deviation')
|
||||
vision_frame = vision_frame.transpose(1, 2, 0)
|
||||
vision_frame = vision_frame * model_standard_deviation + model_mean
|
||||
vision_frame = vision_frame.clip(0, 1)
|
||||
vision_frame = vision_frame[:, :, ::-1] * 255
|
||||
return vision_frame
|
||||
|
||||
|
||||
def normalize_extend_frame(extend_vision_frame : VisionFrame) -> VisionFrame:
|
||||
model_sizes = get_model_options().get('sizes')
|
||||
extend_vision_frame = numpy.clip(extend_vision_frame, -1, 1)
|
||||
extend_vision_frame = (extend_vision_frame + 1) / 2
|
||||
extend_vision_frame = extend_vision_frame.transpose(1, 2, 0).clip(0, 255)
|
||||
extend_vision_frame = (extend_vision_frame * 255.0)
|
||||
extend_vision_frame = extend_vision_frame.astype(numpy.uint8)[:, :, ::-1]
|
||||
extend_vision_frame = cv2.resize(extend_vision_frame, (model_sizes.get('target')[0] * 4, model_sizes.get('target')[1] * 4), interpolation = cv2.INTER_AREA)
|
||||
return extend_vision_frame
|
||||
|
||||
|
||||
def process_frame(inputs : AgeModifierInputs) -> ProcessorOutputs:
|
||||
reference_vision_frame = inputs.get('reference_vision_frame')
|
||||
source_vision_frames = inputs.get('source_vision_frames')
|
||||
target_vision_frames = inputs.get('target_vision_frames')
|
||||
temp_vision_frame = inputs.get('temp_vision_frame')
|
||||
temp_vision_mask = inputs.get('temp_vision_mask')
|
||||
|
||||
target_vision_frame = get_middle(target_vision_frames)
|
||||
target_faces = select_faces(reference_vision_frame, source_vision_frames, target_vision_frames)
|
||||
|
||||
if target_faces:
|
||||
for target_face in target_faces:
|
||||
target_face = scale_face(target_face, target_vision_frame, temp_vision_frame)
|
||||
temp_vision_frame = modify_age(target_face, temp_vision_frame)
|
||||
|
||||
return temp_vision_frame, temp_vision_mask
|
||||
@@ -0,0 +1,18 @@
|
||||
from facefusion.types import Locales
|
||||
|
||||
LOCALES : Locales =\
|
||||
{
|
||||
'en':
|
||||
{
|
||||
'help':
|
||||
{
|
||||
'model': 'choose the model responsible for aging the face',
|
||||
'direction': 'specify the direction in which the age should be modified'
|
||||
},
|
||||
'uis':
|
||||
{
|
||||
'direction_slider': 'AGE MODIFIER DIRECTION',
|
||||
'model_dropdown': 'AGE MODIFIER MODEL'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
from typing import Any, List, Literal, TypeAlias, TypedDict
|
||||
|
||||
from numpy.typing import NDArray
|
||||
|
||||
from facefusion.types import Mask, VisionFrame
|
||||
|
||||
AgeModifierInputs = TypedDict('AgeModifierInputs',
|
||||
{
|
||||
'reference_vision_frame' : VisionFrame,
|
||||
'source_vision_frames' : List[VisionFrame],
|
||||
'target_vision_frames' : List[VisionFrame],
|
||||
'temp_vision_frame' : VisionFrame,
|
||||
'temp_vision_mask' : Mask
|
||||
})
|
||||
|
||||
AgeModifierModel = Literal['fran', 'styleganex_age']
|
||||
|
||||
AgeModifierDirection : TypeAlias = NDArray[Any]
|
||||
@@ -0,0 +1,8 @@
|
||||
from typing import List, Sequence, get_args
|
||||
|
||||
from facefusion.common_helper import create_int_range
|
||||
from facefusion.processors.modules.background_remover.types import BackgroundRemoverModel
|
||||
|
||||
background_remover_models : List[BackgroundRemoverModel] = list(get_args(BackgroundRemoverModel))
|
||||
|
||||
background_remover_color_range : Sequence[int] = create_int_range(0, 255, 1)
|
||||
@@ -0,0 +1,662 @@
|
||||
from argparse import ArgumentParser
|
||||
from functools import lru_cache, partial
|
||||
from types import ModuleType
|
||||
from typing import List, Tuple
|
||||
|
||||
import cv2
|
||||
import numpy
|
||||
|
||||
import facefusion.choices
|
||||
import facefusion.jobs.job_manager
|
||||
import facefusion.jobs.job_store
|
||||
from facefusion import config, content_analyser, inference_manager, logger, state_manager, translator, video_manager
|
||||
from facefusion.common_helper import is_macos, is_windows
|
||||
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
||||
from facefusion.execution import has_execution_provider
|
||||
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path, same_file_extension
|
||||
from facefusion.normalizer import normalize_color
|
||||
from facefusion.processors.modules.background_remover import choices as background_remover_choices
|
||||
from facefusion.processors.modules.background_remover.types import BackgroundRemoverInputs
|
||||
from facefusion.processors.types import ProcessorOutputs
|
||||
from facefusion.program_helper import find_argument_group
|
||||
from facefusion.sanitizer import sanitize_int_range
|
||||
from facefusion.thread_helper import thread_semaphore
|
||||
from facefusion.types import ApplyStateItem, Args, DownloadScope, InferencePool, InferenceProvider, Mask, ModelOptions, ModelSet, ProcessMode, VisionFrame
|
||||
from facefusion.vision import read_static_image, read_static_video_chunk, read_static_video_frame
|
||||
|
||||
|
||||
@lru_cache()
|
||||
def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
return\
|
||||
{
|
||||
'ben_2':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'PramaLLC',
|
||||
'license': 'MIT',
|
||||
'year': 2025
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'ben_2.hash'),
|
||||
'path': resolve_relative_path('../.assets/models/ben_2.hash')
|
||||
}
|
||||
},
|
||||
'sources':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'ben_2.onnx'),
|
||||
'path': resolve_relative_path('../.assets/models/ben_2.onnx')
|
||||
}
|
||||
},
|
||||
'type': 'ben',
|
||||
'size': (1024, 1024),
|
||||
'mean': [ 0.0, 0.0, 0.0 ],
|
||||
'standard_deviation': [ 1.0, 1.0, 1.0 ]
|
||||
},
|
||||
'birefnet_general':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'ZhengPeng7',
|
||||
'license': 'MIT',
|
||||
'year': 2024
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'birefnet_general.hash'),
|
||||
'path': resolve_relative_path('../.assets/models/birefnet_general.hash')
|
||||
}
|
||||
},
|
||||
'sources':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'birefnet_general.onnx'),
|
||||
'path': resolve_relative_path('../.assets/models/birefnet_general.onnx')
|
||||
}
|
||||
},
|
||||
'type': 'birefnet',
|
||||
'size': (1024, 1024),
|
||||
'mean': [ 0.0, 0.0, 0.0 ],
|
||||
'standard_deviation': [ 1.0, 1.0, 1.0 ]
|
||||
},
|
||||
'birefnet_portrait':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'ZhengPeng7',
|
||||
'license': 'MIT',
|
||||
'year': 2024
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'birefnet_portrait.hash'),
|
||||
'path': resolve_relative_path('../.assets/models/birefnet_portrait.hash')
|
||||
}
|
||||
},
|
||||
'sources':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'birefnet_portrait.onnx'),
|
||||
'path': resolve_relative_path('../.assets/models/birefnet_portrait.onnx')
|
||||
}
|
||||
},
|
||||
'type': 'birefnet',
|
||||
'size': (1024, 1024),
|
||||
'mean': [ 0.0, 0.0, 0.0 ],
|
||||
'standard_deviation': [ 1.0, 1.0, 1.0 ]
|
||||
},
|
||||
'corridor_key_1024':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'nikopueringer',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2025
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.6.0', 'corridor_key_1024.hash'),
|
||||
'path': resolve_relative_path('../.assets/models/corridor_key_1024.hash')
|
||||
}
|
||||
},
|
||||
'sources':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.6.0', 'corridor_key_1024.onnx'),
|
||||
'path': resolve_relative_path('../.assets/models/corridor_key_1024.onnx')
|
||||
}
|
||||
},
|
||||
'type': 'corridor_key',
|
||||
'size': (1024, 1024),
|
||||
'mean': [ 0.485, 0.456, 0.406 ],
|
||||
'standard_deviation': [ 0.229, 0.224, 0.225 ]
|
||||
},
|
||||
'corridor_key_2048':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'nikopueringer',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2025
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.6.0', 'corridor_key_2048.hash'),
|
||||
'path': resolve_relative_path('../.assets/models/corridor_key_2048.hash')
|
||||
}
|
||||
},
|
||||
'sources':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.6.0', 'corridor_key_2048.onnx'),
|
||||
'path': resolve_relative_path('../.assets/models/corridor_key_2048.onnx')
|
||||
}
|
||||
},
|
||||
'type': 'corridor_key',
|
||||
'size': (2048, 2048),
|
||||
'mean': [ 0.485, 0.456, 0.406 ],
|
||||
'standard_deviation': [ 0.229, 0.224, 0.225 ]
|
||||
},
|
||||
'isnet_general':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'xuebinqin',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2022
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'isnet_general.hash'),
|
||||
'path': resolve_relative_path('../.assets/models/isnet_general.hash')
|
||||
}
|
||||
},
|
||||
'sources':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'isnet_general.onnx'),
|
||||
'path': resolve_relative_path('../.assets/models/isnet_general.onnx')
|
||||
}
|
||||
},
|
||||
'type': 'isnet',
|
||||
'size': (1024, 1024),
|
||||
'mean': [ 0.5, 0.5, 0.5 ],
|
||||
'standard_deviation': [ 1.0, 1.0, 1.0 ]
|
||||
},
|
||||
'modnet':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'ZHKKKe',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2020
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'modnet.hash'),
|
||||
'path': resolve_relative_path('../.assets/models/modnet.hash')
|
||||
}
|
||||
},
|
||||
'sources':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'modnet.onnx'),
|
||||
'path': resolve_relative_path('../.assets/models/modnet.onnx')
|
||||
}
|
||||
},
|
||||
'type': 'modnet',
|
||||
'size': (512, 512),
|
||||
'mean': [ 0.5, 0.5, 0.5 ],
|
||||
'standard_deviation': [ 0.5, 0.5, 0.5 ]
|
||||
},
|
||||
'ormbg':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'schirrmacher',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2024
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'ormbg.hash'),
|
||||
'path': resolve_relative_path('../.assets/models/ormbg.hash')
|
||||
}
|
||||
},
|
||||
'sources':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'ormbg.onnx'),
|
||||
'path': resolve_relative_path('../.assets/models/ormbg.onnx')
|
||||
}
|
||||
},
|
||||
'type': 'ormbg',
|
||||
'size': (1024, 1024),
|
||||
'mean': [ 0.0, 0.0, 0.0 ],
|
||||
'standard_deviation': [ 1.0, 1.0, 1.0 ]
|
||||
},
|
||||
'rmbg_1.4':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'Bria',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2023
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'rmbg_1.4.hash'),
|
||||
'path': resolve_relative_path('../.assets/models/rmbg_1.4.hash')
|
||||
}
|
||||
},
|
||||
'sources':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'rmbg_1.4.onnx'),
|
||||
'path': resolve_relative_path('../.assets/models/rmbg_1.4.onnx')
|
||||
}
|
||||
},
|
||||
'type': 'rmbg',
|
||||
'size': (1024, 1024),
|
||||
'mean': [ 0.5, 0.5, 0.5 ],
|
||||
'standard_deviation': [ 1.0, 1.0, 1.0 ]
|
||||
},
|
||||
'rmbg_2.0':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'Bria',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2024
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'rmbg_2.0.hash'),
|
||||
'path': resolve_relative_path('../.assets/models/rmbg_2.0.hash')
|
||||
}
|
||||
},
|
||||
'sources':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'rmbg_2.0.onnx'),
|
||||
'path': resolve_relative_path('../.assets/models/rmbg_2.0.onnx')
|
||||
}
|
||||
},
|
||||
'type': 'rmbg',
|
||||
'size': (1024, 1024),
|
||||
'mean': [ 0.485, 0.456, 0.406 ],
|
||||
'standard_deviation': [ 0.229, 0.224, 0.225 ]
|
||||
},
|
||||
'silueta':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'Kikedao',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2022
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'silueta.hash'),
|
||||
'path': resolve_relative_path('../.assets/models/silueta.hash')
|
||||
}
|
||||
},
|
||||
'sources':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'silueta.onnx'),
|
||||
'path': resolve_relative_path('../.assets/models/silueta.onnx')
|
||||
}
|
||||
},
|
||||
'type': 'silueta',
|
||||
'size': (320, 320),
|
||||
'mean': [ 0.485, 0.456, 0.406 ],
|
||||
'standard_deviation': [ 0.229, 0.224, 0.225 ]
|
||||
},
|
||||
'u2net_cloth':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'levindabhi',
|
||||
'license': 'MIT',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'u2net_cloth.hash'),
|
||||
'path': resolve_relative_path('../.assets/models/u2net_cloth.hash')
|
||||
}
|
||||
},
|
||||
'sources':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'u2net_cloth.onnx'),
|
||||
'path': resolve_relative_path('../.assets/models/u2net_cloth.onnx')
|
||||
}
|
||||
},
|
||||
'type': 'u2net_cloth',
|
||||
'size': (768, 768),
|
||||
'mean': [ 0.485, 0.456, 0.406 ],
|
||||
'standard_deviation': [ 0.229, 0.224, 0.225 ]
|
||||
},
|
||||
'u2net_general':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'xuebinqin',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2020
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'u2net_general.hash'),
|
||||
'path': resolve_relative_path('../.assets/models/u2net_general.hash')
|
||||
}
|
||||
},
|
||||
'sources':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'u2net_general.onnx'),
|
||||
'path': resolve_relative_path('../.assets/models/u2net_general.onnx')
|
||||
}
|
||||
},
|
||||
'type': 'u2net',
|
||||
'size': (320, 320),
|
||||
'mean': [ 0.485, 0.456, 0.406 ],
|
||||
'standard_deviation': [ 0.229, 0.224, 0.225 ]
|
||||
},
|
||||
'u2net_human':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'xuebinqin',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'u2net_human.hash'),
|
||||
'path': resolve_relative_path('../.assets/models/u2net_human.hash')
|
||||
}
|
||||
},
|
||||
'sources':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'u2net_human.onnx'),
|
||||
'path': resolve_relative_path('../.assets/models/u2net_human.onnx')
|
||||
}
|
||||
},
|
||||
'type': 'u2net',
|
||||
'size': (320, 320),
|
||||
'mean': [ 0.485, 0.456, 0.406 ],
|
||||
'standard_deviation': [ 0.229, 0.224, 0.225 ]
|
||||
},
|
||||
'u2netp':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'xuebinqin',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'u2netp.hash'),
|
||||
'path': resolve_relative_path('../.assets/models/u2netp.hash')
|
||||
}
|
||||
},
|
||||
'sources':
|
||||
{
|
||||
'background_remover':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'u2netp.onnx'),
|
||||
'path': resolve_relative_path('../.assets/models/u2netp.onnx')
|
||||
}
|
||||
},
|
||||
'type': 'u2netp',
|
||||
'size': (320, 320),
|
||||
'mean': [ 0.485, 0.456, 0.406 ],
|
||||
'standard_deviation': [ 0.229, 0.224, 0.225 ]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def get_inference_pool() -> InferencePool:
|
||||
model_names = [ state_manager.get_item('background_remover_model') ]
|
||||
model_source_set = get_model_options().get('sources')
|
||||
|
||||
return inference_manager.get_inference_pool(__name__, model_names, model_source_set)
|
||||
|
||||
|
||||
def clear_inference_pool() -> None:
|
||||
model_names = [ state_manager.get_item('background_remover_model') ]
|
||||
inference_manager.clear_inference_pool(__name__, model_names)
|
||||
|
||||
|
||||
def resolve_inference_providers() -> List[InferenceProvider]:
|
||||
model_type = get_model_options().get('type')
|
||||
|
||||
if is_macos() and has_execution_provider('coreml') or is_windows() and has_execution_provider('directml') and model_type == 'corridor_key':
|
||||
return [ facefusion.choices.execution_provider_set.get('cpu') ]
|
||||
|
||||
return []
|
||||
|
||||
|
||||
def get_model_options() -> ModelOptions:
|
||||
model_name = state_manager.get_item('background_remover_model')
|
||||
return create_static_model_set('full').get(model_name)
|
||||
|
||||
|
||||
def register_args(program : ArgumentParser) -> None:
|
||||
group_processors = find_argument_group(program, 'processors')
|
||||
if group_processors:
|
||||
group_processors.add_argument('--background-remover-model', help = translator.get('help.model', __package__), default = config.get_str_value('processors', 'background_remover_model', 'modnet'), choices = background_remover_choices.background_remover_models)
|
||||
group_processors.add_argument('--background-remover-fill-color', help = translator.get('help.fill_color', __package__), type = partial(sanitize_int_range, int_range = background_remover_choices.background_remover_color_range), default = config.get_int_list('processors', 'background_remover_fill_color', '0 0 0 0'), nargs = '+')
|
||||
group_processors.add_argument('--background-remover-despill-color', help = translator.get('help.despill_color', __package__), type = partial(sanitize_int_range, int_range = background_remover_choices.background_remover_color_range), default = config.get_int_list('processors', 'background_remover_despill_color', '0 0 0 0'), nargs = '+')
|
||||
facefusion.jobs.job_store.register_step_keys([ 'background_remover_model', 'background_remover_fill_color', 'background_remover_despill_color' ])
|
||||
|
||||
|
||||
def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
|
||||
apply_state_item('background_remover_model', args.get('background_remover_model'))
|
||||
apply_state_item('background_remover_fill_color', normalize_color(args.get('background_remover_fill_color')))
|
||||
apply_state_item('background_remover_despill_color', normalize_color(args.get('background_remover_despill_color')))
|
||||
|
||||
|
||||
def get_common_modules() -> List[ModuleType]:
|
||||
return [ content_analyser ]
|
||||
|
||||
|
||||
def pre_check() -> bool:
|
||||
model_hash_set = get_model_options().get('hashes')
|
||||
model_source_set = get_model_options().get('sources')
|
||||
|
||||
for common_module in get_common_modules():
|
||||
if not common_module.pre_check():
|
||||
return False
|
||||
|
||||
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
||||
|
||||
|
||||
def pre_process(mode : ProcessMode) -> bool:
|
||||
if mode in [ 'output', 'preview' ] and not is_image(state_manager.get_item('target_path')) and not is_video(state_manager.get_item('target_path')):
|
||||
logger.error(translator.get('choose_image_or_video_target') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
if mode == 'output' and not in_directory(state_manager.get_item('output_path')):
|
||||
logger.error(translator.get('specify_image_or_video_output') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
if mode == 'output' and not same_file_extension(state_manager.get_item('target_path'), state_manager.get_item('output_path')):
|
||||
logger.error(translator.get('match_target_and_output_extension') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def post_process() -> None:
|
||||
read_static_image.cache_clear()
|
||||
read_static_video_frame.cache_clear()
|
||||
read_static_video_chunk.cache_clear()
|
||||
video_manager.clear_video_pool()
|
||||
|
||||
if state_manager.get_item('video_memory_strategy') in [ 'strict', 'moderate' ]:
|
||||
clear_inference_pool()
|
||||
|
||||
if state_manager.get_item('video_memory_strategy') == 'strict':
|
||||
for common_module in get_common_modules():
|
||||
common_module.clear_inference_pool()
|
||||
|
||||
|
||||
def remove_background(temp_vision_frame : VisionFrame) -> Tuple[VisionFrame, Mask]:
|
||||
model_type = get_model_options().get('type')
|
||||
|
||||
if model_type == 'corridor_key':
|
||||
remove_vision_mask, remove_vision_frame = forward_corridor_key(prepare_temp_frame(temp_vision_frame))
|
||||
remove_vision_frame = numpy.squeeze(remove_vision_frame).transpose(1, 2, 0)
|
||||
remove_vision_frame = numpy.clip(remove_vision_frame * 255, 0, 255).astype(numpy.uint8)
|
||||
temp_vision_frame = cv2.resize(remove_vision_frame[:, :, ::-1], temp_vision_frame.shape[:2][::-1])
|
||||
else:
|
||||
remove_vision_mask = forward(prepare_temp_frame(temp_vision_frame))
|
||||
|
||||
remove_vision_mask = normalize_vision_mask(remove_vision_mask)
|
||||
remove_vision_mask = cv2.resize(remove_vision_mask, temp_vision_frame.shape[:2][::-1])
|
||||
temp_vision_frame = apply_despill_color(temp_vision_frame)
|
||||
temp_vision_frame = apply_fill_color(temp_vision_frame, remove_vision_mask)
|
||||
return temp_vision_frame, remove_vision_mask
|
||||
|
||||
|
||||
def forward(temp_vision_frame : VisionFrame) -> VisionFrame:
|
||||
background_remover = get_inference_pool().get('background_remover')
|
||||
model_type = get_model_options().get('type')
|
||||
|
||||
with thread_semaphore():
|
||||
remove_vision_frame = background_remover.run(None,
|
||||
{
|
||||
'input': temp_vision_frame
|
||||
})[0]
|
||||
|
||||
if model_type == 'u2net_cloth':
|
||||
remove_vision_frame = numpy.argmax(remove_vision_frame, axis = 1)
|
||||
|
||||
return remove_vision_frame
|
||||
|
||||
|
||||
def forward_corridor_key(temp_vision_frame : VisionFrame) -> Tuple[Mask, VisionFrame]:
|
||||
background_remover = get_inference_pool().get('background_remover')
|
||||
|
||||
with thread_semaphore():
|
||||
remove_vision_mask, remove_vision_frame = background_remover.run(None,
|
||||
{
|
||||
'input': temp_vision_frame
|
||||
})
|
||||
|
||||
return remove_vision_mask, remove_vision_frame
|
||||
|
||||
|
||||
def prepare_temp_frame(temp_vision_frame : VisionFrame) -> VisionFrame:
|
||||
model_type = get_model_options().get('type')
|
||||
model_size = get_model_options().get('size')
|
||||
model_mean = get_model_options().get('mean')
|
||||
model_standard_deviation = get_model_options().get('standard_deviation')
|
||||
|
||||
if model_type == 'corridor_key':
|
||||
coarse_color = temp_vision_frame[:, :, ::-1].astype(numpy.float32) / 255.0
|
||||
coarse_bias = coarse_color[:, :, 1] - numpy.maximum(coarse_color[:, :, 0], coarse_color[:, :, 2])
|
||||
coarse_vision_mask = cv2.resize(1.0 - numpy.clip(coarse_bias * 2.0, 0, 1), model_size)[:, :, numpy.newaxis]
|
||||
|
||||
temp_vision_frame = cv2.resize(temp_vision_frame, model_size)
|
||||
temp_vision_frame = temp_vision_frame[:, :, ::-1] / 255.0
|
||||
temp_vision_frame = (temp_vision_frame - model_mean) / model_standard_deviation
|
||||
|
||||
if model_type == 'corridor_key':
|
||||
temp_vision_frame = numpy.concatenate([ temp_vision_frame, coarse_vision_mask ], axis = 2)
|
||||
|
||||
temp_vision_frame = temp_vision_frame.transpose(2, 0, 1)
|
||||
temp_vision_frame = numpy.expand_dims(temp_vision_frame, axis = 0).astype(numpy.float32)
|
||||
return temp_vision_frame
|
||||
|
||||
|
||||
def normalize_vision_mask(temp_vision_mask : Mask) -> Mask:
|
||||
temp_vision_mask = numpy.squeeze(temp_vision_mask).clip(0, 1) * 255
|
||||
temp_vision_mask = numpy.clip(temp_vision_mask, 0, 255).astype(numpy.uint8)
|
||||
return temp_vision_mask
|
||||
|
||||
|
||||
def apply_fill_color(temp_vision_frame : VisionFrame, temp_vision_mask : Mask) -> VisionFrame:
|
||||
background_remover_fill_color = state_manager.get_item('background_remover_fill_color')
|
||||
temp_vision_mask = temp_vision_mask.astype(numpy.float32) / 255
|
||||
temp_vision_mask = numpy.expand_dims(temp_vision_mask, axis = 2)
|
||||
temp_vision_mask = (1 - temp_vision_mask) * background_remover_fill_color[-1] / 255
|
||||
fill_vision_frame = numpy.zeros_like(temp_vision_frame)
|
||||
fill_vision_frame[:, :, 0] = background_remover_fill_color[2]
|
||||
fill_vision_frame[:, :, 1] = background_remover_fill_color[1]
|
||||
fill_vision_frame[:, :, 2] = background_remover_fill_color[0]
|
||||
temp_vision_frame = temp_vision_frame * (1 - temp_vision_mask) + fill_vision_frame * temp_vision_mask
|
||||
temp_vision_frame = temp_vision_frame.astype(numpy.uint8)
|
||||
return temp_vision_frame
|
||||
|
||||
|
||||
def apply_despill_color(temp_vision_frame : VisionFrame) -> VisionFrame:
|
||||
background_remover_despill_color = state_manager.get_item('background_remover_despill_color')
|
||||
temp_vision_frame = temp_vision_frame.astype(numpy.float32)
|
||||
color_alpha = background_remover_despill_color[3] / 255.0
|
||||
despill_vision_frame = numpy.zeros_like(temp_vision_frame)
|
||||
despill_vision_frame[:, :, 0] = background_remover_despill_color[2]
|
||||
despill_vision_frame[:, :, 1] = background_remover_despill_color[1]
|
||||
despill_vision_frame[:, :, 2] = background_remover_despill_color[0]
|
||||
color_weight = despill_vision_frame / numpy.maximum(numpy.max(background_remover_despill_color[:3]), 1)
|
||||
color_limit = numpy.roll(temp_vision_frame, 1, 2) + numpy.roll(temp_vision_frame, -1, 2)
|
||||
limit_vision_frame = numpy.minimum(temp_vision_frame, color_limit * 0.5)
|
||||
temp_vision_frame = temp_vision_frame + (limit_vision_frame - temp_vision_frame) * color_alpha * color_weight
|
||||
temp_vision_frame = temp_vision_frame.astype(numpy.uint8)
|
||||
return temp_vision_frame
|
||||
|
||||
|
||||
def process_frame(inputs : BackgroundRemoverInputs) -> ProcessorOutputs:
|
||||
temp_vision_frame = inputs.get('temp_vision_frame')
|
||||
temp_vision_frame, temp_vision_mask = remove_background(temp_vision_frame)
|
||||
temp_vision_mask = numpy.minimum.reduce([ temp_vision_mask, inputs.get('temp_vision_mask') ])
|
||||
return temp_vision_frame, temp_vision_mask
|
||||
@@ -0,0 +1,26 @@
|
||||
from facefusion.types import Locales
|
||||
|
||||
LOCALES : Locales =\
|
||||
{
|
||||
'en':
|
||||
{
|
||||
'help':
|
||||
{
|
||||
'model': 'choose the model responsible for removing the background',
|
||||
'fill_color': 'apply red, green, blue and alpha values to the background',
|
||||
'despill_color': 'remove red, green, blue and alpha values from the foreground'
|
||||
},
|
||||
'uis':
|
||||
{
|
||||
'model_dropdown': 'BACKGROUND REMOVER MODEL',
|
||||
'fill_color_red_number': 'FILL COLOR RED',
|
||||
'fill_color_green_number': 'FILL COLOR GREEN',
|
||||
'fill_color_blue_number': 'FILL COLOR BLUE',
|
||||
'fill_color_alpha_number': 'FILL COLOR ALPHA',
|
||||
'despill_color_red_number': 'DESPILL COLOR RED',
|
||||
'despill_color_green_number': 'DESPILL COLOR GREEN',
|
||||
'despill_color_blue_number': 'DESPILL COLOR BLUE',
|
||||
'despill_color_alpha_number': 'DESPILL COLOR ALPHA'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
from typing import List, Literal, TypedDict
|
||||
|
||||
from facefusion.types import Mask, VisionFrame
|
||||
|
||||
BackgroundRemoverInputs = TypedDict('BackgroundRemoverInputs',
|
||||
{
|
||||
'target_vision_frames' : List[VisionFrame],
|
||||
'temp_vision_frame' : VisionFrame,
|
||||
'temp_vision_mask' : Mask
|
||||
})
|
||||
|
||||
BackgroundRemoverModel = Literal['ben_2', 'birefnet_general', 'birefnet_portrait', 'corridor_key_1024', 'corridor_key_2048', 'isnet_general', 'modnet', 'ormbg', 'rmbg_1.4', 'rmbg_2.0', 'silueta', 'u2net_cloth', 'u2net_general', 'u2net_human', 'u2netp']
|
||||
Executable → Regular
+2
-52
@@ -1,10 +1,9 @@
|
||||
from typing import List, Sequence
|
||||
|
||||
from facefusion.common_helper import create_float_range, create_int_range
|
||||
from facefusion.common_helper import create_int_range
|
||||
from facefusion.filesystem import get_file_name, resolve_file_paths, resolve_relative_path
|
||||
from facefusion.processors.types import AgeModifierModel, DeepSwapperModel, ExpressionRestorerArea, ExpressionRestorerModel, FaceDebuggerItem, FaceEditorModel, FaceEnhancerModel, FaceSwapperModel, FaceSwapperSet, FaceSwapperWeight, FrameColorizerModel, FrameEnhancerModel, LipSyncerModel
|
||||
from facefusion.processors.modules.deep_swapper.types import DeepSwapperModel
|
||||
|
||||
age_modifier_models : List[AgeModifierModel] = [ 'styleganex_age' ]
|
||||
deep_swapper_models : List[DeepSwapperModel] =\
|
||||
[
|
||||
'druuzil/adam_levine_320',
|
||||
@@ -174,53 +173,4 @@ if custom_model_file_paths:
|
||||
model_id = '/'.join([ 'custom', get_file_name(model_file_path) ])
|
||||
deep_swapper_models.append(model_id)
|
||||
|
||||
expression_restorer_models : List[ExpressionRestorerModel] = [ 'live_portrait' ]
|
||||
expression_restorer_areas : List[ExpressionRestorerArea] = [ 'upper-face', 'lower-face' ]
|
||||
face_debugger_items : List[FaceDebuggerItem] = [ 'bounding-box', 'face-landmark-5', 'face-landmark-5/68', 'face-landmark-68', 'face-landmark-68/5', 'face-mask' ]
|
||||
face_editor_models : List[FaceEditorModel] = [ 'live_portrait' ]
|
||||
face_enhancer_models : List[FaceEnhancerModel] = [ 'codeformer', 'gfpgan_1.2', 'gfpgan_1.3', 'gfpgan_1.4', 'gpen_bfr_256', 'gpen_bfr_512', 'gpen_bfr_1024', 'gpen_bfr_2048', 'restoreformer_plus_plus' ]
|
||||
face_swapper_set : FaceSwapperSet =\
|
||||
{
|
||||
'blendswap_256': [ '256x256', '384x384', '512x512', '768x768', '1024x1024' ],
|
||||
'ghost_1_256': [ '256x256', '512x512', '768x768', '1024x1024' ],
|
||||
'ghost_2_256': [ '256x256', '512x512', '768x768', '1024x1024' ],
|
||||
'ghost_3_256': [ '256x256', '512x512', '768x768', '1024x1024' ],
|
||||
'hififace_unofficial_256': [ '256x256', '512x512', '768x768', '1024x1024' ],
|
||||
'hyperswap_1a_256': [ '256x256', '512x512', '768x768', '1024x1024' ],
|
||||
'hyperswap_1b_256': [ '256x256', '512x512', '768x768', '1024x1024' ],
|
||||
'hyperswap_1c_256': [ '256x256', '512x512', '768x768', '1024x1024' ],
|
||||
'inswapper_128': [ '128x128', '256x256', '384x384', '512x512', '768x768', '1024x1024' ],
|
||||
'inswapper_128_fp16': [ '128x128', '256x256', '384x384', '512x512', '768x768', '1024x1024' ],
|
||||
'simswap_256': [ '256x256', '512x512', '768x768', '1024x1024' ],
|
||||
'simswap_unofficial_512': [ '512x512', '768x768', '1024x1024' ],
|
||||
'uniface_256': [ '256x256', '512x512', '768x768', '1024x1024' ]
|
||||
}
|
||||
face_swapper_models : List[FaceSwapperModel] = list(face_swapper_set.keys())
|
||||
frame_colorizer_models : List[FrameColorizerModel] = [ 'ddcolor', 'ddcolor_artistic', 'deoldify', 'deoldify_artistic', 'deoldify_stable' ]
|
||||
frame_colorizer_sizes : List[str] = [ '192x192', '256x256', '384x384', '512x512' ]
|
||||
frame_enhancer_models : List[FrameEnhancerModel] = [ 'clear_reality_x4', 'lsdir_x4', 'nomos8k_sc_x4', 'real_esrgan_x2', 'real_esrgan_x2_fp16', 'real_esrgan_x4', 'real_esrgan_x4_fp16', 'real_esrgan_x8', 'real_esrgan_x8_fp16', 'real_hatgan_x4', 'real_web_photo_x4', 'realistic_rescaler_x4', 'remacri_x4', 'siax_x4', 'span_kendata_x4', 'swin2_sr_x4', 'ultra_sharp_x4', 'ultra_sharp_2_x4' ]
|
||||
lip_syncer_models : List[LipSyncerModel] = [ 'edtalk_256', 'wav2lip_96', 'wav2lip_gan_96' ]
|
||||
|
||||
age_modifier_direction_range : Sequence[int] = create_int_range(-100, 100, 1)
|
||||
deep_swapper_morph_range : Sequence[int] = create_int_range(0, 100, 1)
|
||||
expression_restorer_factor_range : Sequence[int] = create_int_range(0, 100, 1)
|
||||
face_editor_eyebrow_direction_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_eye_gaze_horizontal_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_eye_gaze_vertical_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_eye_open_ratio_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_lip_open_ratio_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_mouth_grim_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_mouth_pout_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_mouth_purse_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_mouth_smile_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_mouth_position_horizontal_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_mouth_position_vertical_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_head_pitch_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_head_yaw_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_head_roll_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_enhancer_blend_range : Sequence[int] = create_int_range(0, 100, 1)
|
||||
face_enhancer_weight_range : Sequence[float] = create_float_range(0.0, 1.0, 0.05)
|
||||
face_swapper_weight_range : Sequence[FaceSwapperWeight] = create_float_range(0.0, 1.0, 0.05)
|
||||
frame_colorizer_blend_range : Sequence[int] = create_int_range(0, 100, 1)
|
||||
frame_enhancer_blend_range : Sequence[int] = create_int_range(0, 100, 1)
|
||||
lip_syncer_weight_range : Sequence[float] = create_float_range(0.0, 1.0, 0.05)
|
||||
+36
-23
@@ -1,6 +1,7 @@
|
||||
from argparse import ArgumentParser
|
||||
from functools import lru_cache
|
||||
from typing import Tuple
|
||||
from types import ModuleType
|
||||
from typing import List, Tuple
|
||||
|
||||
import cv2
|
||||
import numpy
|
||||
@@ -8,19 +9,21 @@ from cv2.typing import Size
|
||||
|
||||
import facefusion.jobs.job_manager
|
||||
import facefusion.jobs.job_store
|
||||
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, inference_manager, logger, state_manager, video_manager, wording
|
||||
from facefusion.common_helper import create_int_metavar
|
||||
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, inference_manager, logger, state_manager, translator, video_manager
|
||||
from facefusion.common_helper import create_int_metavar, get_middle
|
||||
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url_by_provider
|
||||
from facefusion.face_creator import scale_face
|
||||
from facefusion.face_helper import paste_back, warp_face_by_face_landmark_5
|
||||
from facefusion.face_masker import create_area_mask, create_box_mask, create_occlusion_mask, create_region_mask
|
||||
from facefusion.face_selector import select_faces
|
||||
from facefusion.filesystem import get_file_name, in_directory, is_image, is_video, resolve_file_paths, resolve_relative_path, same_file_extension
|
||||
from facefusion.processors import choices as processors_choices
|
||||
from facefusion.processors.types import DeepSwapperInputs, DeepSwapperMorph
|
||||
from facefusion.processors.modules.deep_swapper import choices as deep_swapper_choices
|
||||
from facefusion.processors.modules.deep_swapper.types import DeepSwapperInputs, DeepSwapperMorph
|
||||
from facefusion.processors.types import ProcessorOutputs
|
||||
from facefusion.program_helper import find_argument_group
|
||||
from facefusion.thread_helper import thread_semaphore
|
||||
from facefusion.types import ApplyStateItem, Args, DownloadScope, Face, InferencePool, Mask, ModelOptions, ModelSet, ProcessMode, VisionFrame
|
||||
from facefusion.vision import conditional_match_frame_color, read_static_image, read_static_video_frame
|
||||
from facefusion.vision import conditional_match_frame_color, read_static_image, read_static_video_chunk, read_static_video_frame
|
||||
|
||||
|
||||
@lru_cache()
|
||||
@@ -274,8 +277,8 @@ def get_model_size() -> Size:
|
||||
def register_args(program : ArgumentParser) -> None:
|
||||
group_processors = find_argument_group(program, 'processors')
|
||||
if group_processors:
|
||||
group_processors.add_argument('--deep-swapper-model', help = wording.get('help.deep_swapper_model'), default = config.get_str_value('processors', 'deep_swapper_model', 'iperov/elon_musk_224'), choices = processors_choices.deep_swapper_models)
|
||||
group_processors.add_argument('--deep-swapper-morph', help = wording.get('help.deep_swapper_morph'), type = int, default = config.get_int_value('processors', 'deep_swapper_morph', '100'), choices = processors_choices.deep_swapper_morph_range, metavar = create_int_metavar(processors_choices.deep_swapper_morph_range))
|
||||
group_processors.add_argument('--deep-swapper-model', help = translator.get('help.model', __package__), default = config.get_str_value('processors', 'deep_swapper_model', 'iperov/elon_musk_224'), choices = deep_swapper_choices.deep_swapper_models)
|
||||
group_processors.add_argument('--deep-swapper-morph', help = translator.get('help.morph', __package__), type = int, default = config.get_int_value('processors', 'deep_swapper_morph', '100'), choices = deep_swapper_choices.deep_swapper_morph_range, metavar = create_int_metavar(deep_swapper_choices.deep_swapper_morph_range))
|
||||
facefusion.jobs.job_store.register_step_keys([ 'deep_swapper_model', 'deep_swapper_morph' ])
|
||||
|
||||
|
||||
@@ -284,10 +287,18 @@ def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
|
||||
apply_state_item('deep_swapper_morph', args.get('deep_swapper_morph'))
|
||||
|
||||
|
||||
def get_common_modules() -> List[ModuleType]:
|
||||
return [ content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer ]
|
||||
|
||||
|
||||
def pre_check() -> bool:
|
||||
model_hash_set = get_model_options().get('hashes')
|
||||
model_source_set = get_model_options().get('sources')
|
||||
|
||||
for common_module in get_common_modules():
|
||||
if not common_module.pre_check():
|
||||
return False
|
||||
|
||||
if model_hash_set and model_source_set:
|
||||
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
||||
return True
|
||||
@@ -295,13 +306,13 @@ def pre_check() -> bool:
|
||||
|
||||
def pre_process(mode : ProcessMode) -> bool:
|
||||
if mode in [ 'output', 'preview' ] and not is_image(state_manager.get_item('target_path')) and not is_video(state_manager.get_item('target_path')):
|
||||
logger.error(wording.get('choose_image_or_video_target') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('choose_image_or_video_target') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
if mode == 'output' and not in_directory(state_manager.get_item('output_path')):
|
||||
logger.error(wording.get('specify_image_or_video_output') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('specify_image_or_video_output') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
if mode == 'output' and not same_file_extension(state_manager.get_item('target_path'), state_manager.get_item('output_path')):
|
||||
logger.error(wording.get('match_target_and_output_extension') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('match_target_and_output_extension') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -309,16 +320,15 @@ def pre_process(mode : ProcessMode) -> bool:
|
||||
def post_process() -> None:
|
||||
read_static_image.cache_clear()
|
||||
read_static_video_frame.cache_clear()
|
||||
read_static_video_chunk.cache_clear()
|
||||
video_manager.clear_video_pool()
|
||||
|
||||
if state_manager.get_item('video_memory_strategy') in [ 'strict', 'moderate' ]:
|
||||
clear_inference_pool()
|
||||
|
||||
if state_manager.get_item('video_memory_strategy') == 'strict':
|
||||
content_analyser.clear_inference_pool()
|
||||
face_classifier.clear_inference_pool()
|
||||
face_detector.clear_inference_pool()
|
||||
face_landmarker.clear_inference_pool()
|
||||
face_masker.clear_inference_pool()
|
||||
face_recognizer.clear_inference_pool()
|
||||
for common_module in get_common_modules():
|
||||
common_module.clear_inference_pool()
|
||||
|
||||
|
||||
def swap_face(target_face : Face, temp_vision_frame : VisionFrame) -> VisionFrame:
|
||||
@@ -407,16 +417,19 @@ def prepare_crop_mask(crop_source_mask : Mask, crop_target_mask : Mask) -> Mask:
|
||||
return crop_mask
|
||||
|
||||
|
||||
def process_frame(inputs : DeepSwapperInputs) -> VisionFrame:
|
||||
def process_frame(inputs : DeepSwapperInputs) -> ProcessorOutputs:
|
||||
reference_vision_frame = inputs.get('reference_vision_frame')
|
||||
target_vision_frame = inputs.get('target_vision_frame')
|
||||
source_vision_frames = inputs.get('source_vision_frames')
|
||||
target_vision_frames = inputs.get('target_vision_frames')
|
||||
temp_vision_frame = inputs.get('temp_vision_frame')
|
||||
target_faces = select_faces(reference_vision_frame, target_vision_frame)
|
||||
temp_vision_mask = inputs.get('temp_vision_mask')
|
||||
|
||||
target_vision_frame = get_middle(target_vision_frames)
|
||||
target_faces = select_faces(reference_vision_frame, source_vision_frames, target_vision_frames)
|
||||
|
||||
if target_faces:
|
||||
for target_face in target_faces:
|
||||
target_face = scale_face(target_face, target_vision_frame, temp_vision_frame)
|
||||
temp_vision_frame = swap_face(target_face, temp_vision_frame)
|
||||
|
||||
return temp_vision_frame
|
||||
|
||||
|
||||
return temp_vision_frame, temp_vision_mask
|
||||
@@ -0,0 +1,18 @@
|
||||
from facefusion.types import Locales
|
||||
|
||||
LOCALES : Locales =\
|
||||
{
|
||||
'en':
|
||||
{
|
||||
'help':
|
||||
{
|
||||
'model': 'choose the model responsible for swapping the face',
|
||||
'morph': 'morph between source face and target faces'
|
||||
},
|
||||
'uis':
|
||||
{
|
||||
'model_dropdown': 'DEEP SWAPPER MODEL',
|
||||
'morph_slider': 'DEEP SWAPPER MORPH'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
from typing import Any, List, TypeAlias, TypedDict
|
||||
|
||||
from numpy.typing import NDArray
|
||||
|
||||
from facefusion.types import Mask, VisionFrame
|
||||
|
||||
DeepSwapperInputs = TypedDict('DeepSwapperInputs',
|
||||
{
|
||||
'reference_vision_frame' : VisionFrame,
|
||||
'source_vision_frames' : List[VisionFrame],
|
||||
'target_vision_frames' : List[VisionFrame],
|
||||
'temp_vision_frame' : VisionFrame,
|
||||
'temp_vision_mask' : Mask
|
||||
})
|
||||
|
||||
DeepSwapperModel : TypeAlias = str
|
||||
|
||||
DeepSwapperMorph : TypeAlias = NDArray[Any]
|
||||
@@ -0,0 +1,10 @@
|
||||
from typing import List, Sequence, get_args
|
||||
|
||||
from facefusion.common_helper import create_int_range
|
||||
from facefusion.processors.modules.expression_restorer.types import ExpressionRestorerArea, ExpressionRestorerModel
|
||||
|
||||
expression_restorer_models : List[ExpressionRestorerModel] = list(get_args(ExpressionRestorerModel))
|
||||
|
||||
expression_restorer_areas : List[ExpressionRestorerArea] = list(get_args(ExpressionRestorerArea))
|
||||
|
||||
expression_restorer_factor_range : Sequence[int] = create_int_range(0, 100, 1)
|
||||
+44
-23
@@ -1,26 +1,29 @@
|
||||
from argparse import ArgumentParser
|
||||
from functools import lru_cache
|
||||
from typing import Tuple
|
||||
from types import ModuleType
|
||||
from typing import List, Tuple
|
||||
|
||||
import cv2
|
||||
import numpy
|
||||
|
||||
import facefusion.jobs.job_manager
|
||||
import facefusion.jobs.job_store
|
||||
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, inference_manager, logger, state_manager, video_manager, wording
|
||||
from facefusion.common_helper import create_int_metavar
|
||||
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, inference_manager, logger, state_manager, translator, video_manager
|
||||
from facefusion.common_helper import create_int_metavar, get_middle
|
||||
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
||||
from facefusion.face_creator import scale_face
|
||||
from facefusion.face_helper import paste_back, warp_face_by_face_landmark_5
|
||||
from facefusion.face_masker import create_box_mask, create_occlusion_mask
|
||||
from facefusion.face_selector import select_faces
|
||||
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path, same_file_extension
|
||||
from facefusion.processors import choices as processors_choices
|
||||
from facefusion.processors.live_portrait import create_rotation, limit_expression
|
||||
from facefusion.processors.types import ExpressionRestorerInputs, LivePortraitExpression, LivePortraitFeatureVolume, LivePortraitMotionPoints, LivePortraitPitch, LivePortraitRoll, LivePortraitScale, LivePortraitTranslation, LivePortraitYaw
|
||||
from facefusion.processors.modules.expression_restorer import choices as expression_restorer_choices
|
||||
from facefusion.processors.modules.expression_restorer.types import ExpressionRestorerInputs
|
||||
from facefusion.processors.types import LivePortraitExpression, LivePortraitFeatureVolume, LivePortraitMotionPoints, LivePortraitPitch, LivePortraitRoll, LivePortraitScale, LivePortraitTranslation, LivePortraitYaw, ProcessorOutputs
|
||||
from facefusion.program_helper import find_argument_group
|
||||
from facefusion.thread_helper import conditional_thread_semaphore, thread_semaphore
|
||||
from facefusion.types import ApplyStateItem, Args, DownloadScope, Face, InferencePool, ModelOptions, ModelSet, ProcessMode, VisionFrame
|
||||
from facefusion.vision import read_static_image, read_static_video_frame
|
||||
from facefusion.vision import read_static_image, read_static_video_chunk, read_static_video_frame
|
||||
|
||||
|
||||
@lru_cache()
|
||||
@@ -29,6 +32,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
{
|
||||
'live_portrait':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'KwaiVGI',
|
||||
'license': 'MIT',
|
||||
'year': 2024
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'feature_extractor':
|
||||
@@ -91,9 +100,9 @@ def get_model_options() -> ModelOptions:
|
||||
def register_args(program : ArgumentParser) -> None:
|
||||
group_processors = find_argument_group(program, 'processors')
|
||||
if group_processors:
|
||||
group_processors.add_argument('--expression-restorer-model', help = wording.get('help.expression_restorer_model'), default = config.get_str_value('processors', 'expression_restorer_model', 'live_portrait'), choices = processors_choices.expression_restorer_models)
|
||||
group_processors.add_argument('--expression-restorer-factor', help = wording.get('help.expression_restorer_factor'), type = int, default = config.get_int_value('processors', 'expression_restorer_factor', '80'), choices = processors_choices.expression_restorer_factor_range, metavar = create_int_metavar(processors_choices.expression_restorer_factor_range))
|
||||
group_processors.add_argument('--expression-restorer-areas', help = wording.get('help.expression_restorer_areas').format(choices = ', '.join(processors_choices.expression_restorer_areas)), default = config.get_str_list('processors', 'expression_restorer_areas', ' '.join(processors_choices.expression_restorer_areas)), choices = processors_choices.expression_restorer_areas, nargs = '+', metavar = 'EXPRESSION_RESTORER_AREAS')
|
||||
group_processors.add_argument('--expression-restorer-model', help = translator.get('help.model', __package__), default = config.get_str_value('processors', 'expression_restorer_model', 'live_portrait'), choices = expression_restorer_choices.expression_restorer_models)
|
||||
group_processors.add_argument('--expression-restorer-factor', help = translator.get('help.factor', __package__), type = int, default = config.get_int_value('processors', 'expression_restorer_factor', '80'), choices = expression_restorer_choices.expression_restorer_factor_range, metavar = create_int_metavar(expression_restorer_choices.expression_restorer_factor_range))
|
||||
group_processors.add_argument('--expression-restorer-areas', help = translator.get('help.areas', __package__).format(choices = ', '.join(expression_restorer_choices.expression_restorer_areas)), default = config.get_str_list('processors', 'expression_restorer_areas', ' '.join(expression_restorer_choices.expression_restorer_areas)), choices = expression_restorer_choices.expression_restorer_areas, nargs = '+', metavar = 'EXPRESSION_RESTORER_AREAS')
|
||||
facefusion.jobs.job_store.register_step_keys([ 'expression_restorer_model', 'expression_restorer_factor', 'expression_restorer_areas' ])
|
||||
|
||||
|
||||
@@ -103,25 +112,33 @@ def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
|
||||
apply_state_item('expression_restorer_areas', args.get('expression_restorer_areas'))
|
||||
|
||||
|
||||
def get_common_modules() -> List[ModuleType]:
|
||||
return [ content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer ]
|
||||
|
||||
|
||||
def pre_check() -> bool:
|
||||
model_hash_set = get_model_options().get('hashes')
|
||||
model_source_set = get_model_options().get('sources')
|
||||
|
||||
for common_module in get_common_modules():
|
||||
if not common_module.pre_check():
|
||||
return False
|
||||
|
||||
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
||||
|
||||
|
||||
def pre_process(mode : ProcessMode) -> bool:
|
||||
if mode == 'stream':
|
||||
logger.error(wording.get('stream_not_supported') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('stream_not_supported') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
if mode in [ 'output', 'preview' ] and not is_image(state_manager.get_item('target_path')) and not is_video(state_manager.get_item('target_path')):
|
||||
logger.error(wording.get('choose_image_or_video_target') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('choose_image_or_video_target') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
if mode == 'output' and not in_directory(state_manager.get_item('output_path')):
|
||||
logger.error(wording.get('specify_image_or_video_output') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('specify_image_or_video_output') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
if mode == 'output' and not same_file_extension(state_manager.get_item('target_path'), state_manager.get_item('output_path')):
|
||||
logger.error(wording.get('match_target_and_output_extension') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('match_target_and_output_extension') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -129,16 +146,15 @@ def pre_process(mode : ProcessMode) -> bool:
|
||||
def post_process() -> None:
|
||||
read_static_image.cache_clear()
|
||||
read_static_video_frame.cache_clear()
|
||||
read_static_video_chunk.cache_clear()
|
||||
video_manager.clear_video_pool()
|
||||
|
||||
if state_manager.get_item('video_memory_strategy') in [ 'strict', 'moderate' ]:
|
||||
clear_inference_pool()
|
||||
|
||||
if state_manager.get_item('video_memory_strategy') == 'strict':
|
||||
content_analyser.clear_inference_pool()
|
||||
face_classifier.clear_inference_pool()
|
||||
face_detector.clear_inference_pool()
|
||||
face_landmarker.clear_inference_pool()
|
||||
face_masker.clear_inference_pool()
|
||||
face_recognizer.clear_inference_pool()
|
||||
for common_module in get_common_modules():
|
||||
common_module.clear_inference_pool()
|
||||
|
||||
|
||||
def restore_expression(target_face : Face, target_vision_frame : VisionFrame, temp_vision_frame : VisionFrame) -> VisionFrame:
|
||||
@@ -247,14 +263,19 @@ def normalize_crop_frame(crop_vision_frame : VisionFrame) -> VisionFrame:
|
||||
return crop_vision_frame
|
||||
|
||||
|
||||
def process_frame(inputs : ExpressionRestorerInputs) -> VisionFrame:
|
||||
def process_frame(inputs : ExpressionRestorerInputs) -> ProcessorOutputs:
|
||||
reference_vision_frame = inputs.get('reference_vision_frame')
|
||||
target_vision_frame = inputs.get('target_vision_frame')
|
||||
source_vision_frames = inputs.get('source_vision_frames')
|
||||
target_vision_frames = inputs.get('target_vision_frames')
|
||||
temp_vision_frame = inputs.get('temp_vision_frame')
|
||||
target_faces = select_faces(reference_vision_frame, target_vision_frame)
|
||||
temp_vision_mask = inputs.get('temp_vision_mask')
|
||||
|
||||
target_vision_frame = get_middle(target_vision_frames)
|
||||
target_faces = select_faces(reference_vision_frame, source_vision_frames, target_vision_frames)
|
||||
|
||||
if target_faces:
|
||||
for target_face in target_faces:
|
||||
target_face = scale_face(target_face, target_vision_frame, temp_vision_frame)
|
||||
temp_vision_frame = restore_expression(target_face, target_vision_frame, temp_vision_frame)
|
||||
|
||||
return temp_vision_frame
|
||||
return temp_vision_frame, temp_vision_mask
|
||||
@@ -0,0 +1,20 @@
|
||||
from facefusion.types import Locales
|
||||
|
||||
LOCALES : Locales =\
|
||||
{
|
||||
'en':
|
||||
{
|
||||
'help':
|
||||
{
|
||||
'model': 'choose the model responsible for restoring the expression',
|
||||
'factor': 'restore factor of expression from the target face',
|
||||
'areas': 'choose the items used for the expression areas (choices: {choices})'
|
||||
},
|
||||
'uis':
|
||||
{
|
||||
'model_dropdown': 'EXPRESSION RESTORER MODEL',
|
||||
'factor_slider': 'EXPRESSION RESTORER FACTOR',
|
||||
'areas_checkbox_group': 'EXPRESSION RESTORER AREAS'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
from typing import List, Literal, TypedDict
|
||||
|
||||
from facefusion.types import Mask, VisionFrame
|
||||
|
||||
ExpressionRestorerInputs = TypedDict('ExpressionRestorerInputs',
|
||||
{
|
||||
'reference_vision_frame' : VisionFrame,
|
||||
'source_vision_frames' : List[VisionFrame],
|
||||
'target_vision_frames' : List[VisionFrame],
|
||||
'temp_vision_frame' : VisionFrame,
|
||||
'temp_vision_mask' : Mask
|
||||
})
|
||||
|
||||
ExpressionRestorerModel = Literal['live_portrait']
|
||||
|
||||
ExpressionRestorerArea = Literal['upper-face', 'lower-face']
|
||||
@@ -0,0 +1,5 @@
|
||||
from typing import List, get_args
|
||||
|
||||
from facefusion.processors.modules.face_debugger.types import FaceDebuggerItem
|
||||
|
||||
face_debugger_items : List[FaceDebuggerItem] = list(get_args(FaceDebuggerItem))
|
||||
+78
-32
@@ -1,20 +1,25 @@
|
||||
from argparse import ArgumentParser
|
||||
from types import ModuleType
|
||||
from typing import List
|
||||
|
||||
import cv2
|
||||
import numpy
|
||||
|
||||
import facefusion.jobs.job_manager
|
||||
import facefusion.jobs.job_store
|
||||
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, logger, state_manager, video_manager, wording
|
||||
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, logger, state_manager, translator, video_manager
|
||||
from facefusion.common_helper import get_middle
|
||||
from facefusion.face_creator import scale_face
|
||||
from facefusion.face_helper import warp_face_by_face_landmark_5
|
||||
from facefusion.face_masker import create_area_mask, create_box_mask, create_occlusion_mask, create_region_mask
|
||||
from facefusion.face_selector import select_faces
|
||||
from facefusion.filesystem import in_directory, is_image, is_video, same_file_extension
|
||||
from facefusion.processors import choices as processors_choices
|
||||
from facefusion.processors.types import FaceDebuggerInputs
|
||||
from facefusion.processors.modules.face_debugger import choices as face_debugger_choices
|
||||
from facefusion.processors.modules.face_debugger.types import FaceDebuggerInputs
|
||||
from facefusion.processors.types import ProcessorOutputs
|
||||
from facefusion.program_helper import find_argument_group
|
||||
from facefusion.types import ApplyStateItem, Args, Face, InferencePool, ProcessMode, VisionFrame
|
||||
from facefusion.vision import read_static_image, read_static_video_frame
|
||||
from facefusion.vision import read_static_image, read_static_video_chunk, read_static_video_frame
|
||||
|
||||
|
||||
def get_inference_pool() -> InferencePool:
|
||||
@@ -28,7 +33,7 @@ def clear_inference_pool() -> None:
|
||||
def register_args(program : ArgumentParser) -> None:
|
||||
group_processors = find_argument_group(program, 'processors')
|
||||
if group_processors:
|
||||
group_processors.add_argument('--face-debugger-items', help = wording.get('help.face_debugger_items').format(choices = ', '.join(processors_choices.face_debugger_items)), default = config.get_str_list('processors', 'face_debugger_items', 'face-landmark-5/68 face-mask'), choices = processors_choices.face_debugger_items, nargs = '+', metavar = 'FACE_DEBUGGER_ITEMS')
|
||||
group_processors.add_argument('--face-debugger-items', help = translator.get('help.items', __package__).format(choices = ', '.join(face_debugger_choices.face_debugger_items)), default = config.get_str_list('processors', 'face_debugger_items', 'face-landmark-5/68 face-mask'), choices = face_debugger_choices.face_debugger_items, nargs = '+', metavar = 'FACE_DEBUGGER_ITEMS')
|
||||
facefusion.jobs.job_store.register_step_keys([ 'face_debugger_items' ])
|
||||
|
||||
|
||||
@@ -36,19 +41,26 @@ def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
|
||||
apply_state_item('face_debugger_items', args.get('face_debugger_items'))
|
||||
|
||||
|
||||
def get_common_modules() -> List[ModuleType]:
|
||||
return [ content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer ]
|
||||
|
||||
|
||||
def pre_check() -> bool:
|
||||
for common_module in get_common_modules():
|
||||
if not common_module.pre_check():
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def pre_process(mode : ProcessMode) -> bool:
|
||||
if mode in [ 'output', 'preview' ] and not is_image(state_manager.get_item('target_path')) and not is_video(state_manager.get_item('target_path')):
|
||||
logger.error(wording.get('choose_image_or_video_target') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('choose_image_or_video_target') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
if mode == 'output' and not in_directory(state_manager.get_item('output_path')):
|
||||
logger.error(wording.get('specify_image_or_video_output') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('specify_image_or_video_output') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
if mode == 'output' and not same_file_extension(state_manager.get_item('target_path'), state_manager.get_item('output_path')):
|
||||
logger.error(wording.get('match_target_and_output_extension') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('match_target_and_output_extension') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -56,14 +68,12 @@ def pre_process(mode : ProcessMode) -> bool:
|
||||
def post_process() -> None:
|
||||
read_static_image.cache_clear()
|
||||
read_static_video_frame.cache_clear()
|
||||
read_static_video_chunk.cache_clear()
|
||||
video_manager.clear_video_pool()
|
||||
|
||||
if state_manager.get_item('video_memory_strategy') == 'strict':
|
||||
content_analyser.clear_inference_pool()
|
||||
face_classifier.clear_inference_pool()
|
||||
face_detector.clear_inference_pool()
|
||||
face_landmarker.clear_inference_pool()
|
||||
face_masker.clear_inference_pool()
|
||||
face_recognizer.clear_inference_pool()
|
||||
for common_module in get_common_modules():
|
||||
common_module.clear_inference_pool()
|
||||
|
||||
|
||||
def debug_face(target_face : Face, temp_vision_frame : VisionFrame) -> VisionFrame:
|
||||
@@ -91,38 +101,45 @@ def debug_face(target_face : Face, temp_vision_frame : VisionFrame) -> VisionFra
|
||||
|
||||
|
||||
def draw_bounding_box(target_face : Face, temp_vision_frame : VisionFrame) -> VisionFrame:
|
||||
box_color = 0, 0, 255
|
||||
border_color = 100, 100, 255
|
||||
temp_vision_frame = numpy.ascontiguousarray(temp_vision_frame)
|
||||
bounding_box = target_face.bounding_box.astype(numpy.int32)
|
||||
x1, y1, x2, y2 = bounding_box
|
||||
box_color = 0, 0, 255
|
||||
border_scale = calculate_scale(temp_vision_frame)
|
||||
border_color = 100, 100, 255
|
||||
|
||||
cv2.rectangle(temp_vision_frame, (x1, y1), (x2, y2), box_color, 2)
|
||||
cv2.rectangle(temp_vision_frame, (x1, y1), (x2, y2), box_color, border_scale)
|
||||
|
||||
if target_face.angle == 0:
|
||||
cv2.line(temp_vision_frame, (x1, y1), (x2, y1), border_color, 3)
|
||||
cv2.line(temp_vision_frame, (x1, y1), (x2, y1), border_color, border_scale + 1)
|
||||
if target_face.angle == 180:
|
||||
cv2.line(temp_vision_frame, (x1, y2), (x2, y2), border_color, 3)
|
||||
cv2.line(temp_vision_frame, (x1, y2), (x2, y2), border_color, border_scale + 1)
|
||||
if target_face.angle == 90:
|
||||
cv2.line(temp_vision_frame, (x2, y1), (x2, y2), border_color, 3)
|
||||
cv2.line(temp_vision_frame, (x2, y1), (x2, y2), border_color, border_scale + 1)
|
||||
if target_face.angle == 270:
|
||||
cv2.line(temp_vision_frame, (x1, y1), (x1, y2), border_color, 3)
|
||||
cv2.line(temp_vision_frame, (x1, y1), (x1, y2), border_color, border_scale + 1)
|
||||
|
||||
return temp_vision_frame
|
||||
|
||||
|
||||
def draw_face_mask(target_face : Face, temp_vision_frame : VisionFrame) -> VisionFrame:
|
||||
crop_masks = []
|
||||
temp_vision_frame = numpy.ascontiguousarray(temp_vision_frame)
|
||||
face_landmark_5 = target_face.landmark_set.get('5')
|
||||
face_landmark_68 = target_face.landmark_set.get('68')
|
||||
face_landmark_5_68 = target_face.landmark_set.get('5/68')
|
||||
crop_vision_frame, affine_matrix = warp_face_by_face_landmark_5(temp_vision_frame, face_landmark_5_68, 'arcface_128', (512, 512))
|
||||
inverse_matrix = cv2.invertAffineTransform(affine_matrix)
|
||||
temp_size = temp_vision_frame.shape[:2][::-1]
|
||||
mask_scale = calculate_scale(temp_vision_frame)
|
||||
mask_color = 0, 255, 0
|
||||
|
||||
if numpy.array_equal(face_landmark_5, face_landmark_5_68):
|
||||
mask_color = 255, 255, 0
|
||||
|
||||
if target_face.origin == 'refill':
|
||||
mask_color = 0, 165, 255
|
||||
|
||||
if 'box' in state_manager.get_item('face_mask_types'):
|
||||
box_mask = create_box_mask(crop_vision_frame, 0, state_manager.get_item('face_mask_padding'))
|
||||
crop_masks.append(box_mask)
|
||||
@@ -145,81 +162,110 @@ def draw_face_mask(target_face : Face, temp_vision_frame : VisionFrame) -> Visio
|
||||
inverse_vision_frame = cv2.warpAffine(crop_mask, inverse_matrix, temp_size)
|
||||
inverse_vision_frame = cv2.threshold(inverse_vision_frame, 100, 255, cv2.THRESH_BINARY)[1]
|
||||
inverse_contours, _ = cv2.findContours(inverse_vision_frame, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
|
||||
cv2.drawContours(temp_vision_frame, inverse_contours, -1, mask_color, 2)
|
||||
cv2.drawContours(temp_vision_frame, inverse_contours, -1, mask_color, mask_scale)
|
||||
|
||||
return temp_vision_frame
|
||||
|
||||
|
||||
def draw_face_landmark_5(target_face : Face, temp_vision_frame : VisionFrame) -> VisionFrame:
|
||||
temp_vision_frame = numpy.ascontiguousarray(temp_vision_frame)
|
||||
face_landmark_5 = target_face.landmark_set.get('5')
|
||||
point_scale = calculate_scale(temp_vision_frame)
|
||||
point_color = 0, 0, 255
|
||||
|
||||
if target_face.origin == 'refill':
|
||||
point_color = 0, 165, 255
|
||||
|
||||
if numpy.any(face_landmark_5):
|
||||
face_landmark_5 = face_landmark_5.astype(numpy.int32)
|
||||
|
||||
for point in face_landmark_5:
|
||||
cv2.circle(temp_vision_frame, tuple(point), 3, point_color, -1)
|
||||
cv2.circle(temp_vision_frame, tuple(point), point_scale, point_color, -1)
|
||||
|
||||
return temp_vision_frame
|
||||
|
||||
|
||||
def draw_face_landmark_5_68(target_face : Face, temp_vision_frame : VisionFrame) -> VisionFrame:
|
||||
temp_vision_frame = numpy.ascontiguousarray(temp_vision_frame)
|
||||
face_landmark_5 = target_face.landmark_set.get('5')
|
||||
face_landmark_5_68 = target_face.landmark_set.get('5/68')
|
||||
point_scale = calculate_scale(temp_vision_frame)
|
||||
point_color = 0, 255, 0
|
||||
|
||||
if numpy.array_equal(face_landmark_5, face_landmark_5_68):
|
||||
point_color = 255, 255, 0
|
||||
|
||||
if target_face.origin == 'refill':
|
||||
point_color = 0, 165, 255
|
||||
|
||||
if numpy.any(face_landmark_5_68):
|
||||
face_landmark_5_68 = face_landmark_5_68.astype(numpy.int32)
|
||||
|
||||
for point in face_landmark_5_68:
|
||||
cv2.circle(temp_vision_frame, tuple(point), 3, point_color, -1)
|
||||
cv2.circle(temp_vision_frame, tuple(point), point_scale, point_color, -1)
|
||||
|
||||
return temp_vision_frame
|
||||
|
||||
|
||||
def draw_face_landmark_68(target_face : Face, temp_vision_frame : VisionFrame) -> VisionFrame:
|
||||
temp_vision_frame = numpy.ascontiguousarray(temp_vision_frame)
|
||||
face_landmark_68 = target_face.landmark_set.get('68')
|
||||
face_landmark_68_5 = target_face.landmark_set.get('68/5')
|
||||
point_scale = calculate_scale(temp_vision_frame)
|
||||
point_color = 0, 255, 0
|
||||
|
||||
if numpy.array_equal(face_landmark_68, face_landmark_68_5):
|
||||
point_color = 255, 255, 0
|
||||
|
||||
if target_face.origin == 'refill':
|
||||
point_color = 0, 165, 255
|
||||
|
||||
if numpy.any(face_landmark_68):
|
||||
face_landmark_68 = face_landmark_68.astype(numpy.int32)
|
||||
|
||||
for point in face_landmark_68:
|
||||
cv2.circle(temp_vision_frame, tuple(point), 3, point_color, -1)
|
||||
cv2.circle(temp_vision_frame, tuple(point), point_scale, point_color, -1)
|
||||
|
||||
return temp_vision_frame
|
||||
|
||||
|
||||
def draw_face_landmark_68_5(target_face : Face, temp_vision_frame : VisionFrame) -> VisionFrame:
|
||||
temp_vision_frame = numpy.ascontiguousarray(temp_vision_frame)
|
||||
face_landmark_68_5 = target_face.landmark_set.get('68/5')
|
||||
point_scale = calculate_scale(temp_vision_frame)
|
||||
point_color = 255, 255, 0
|
||||
|
||||
if target_face.origin == 'refill':
|
||||
point_color = 0, 165, 255
|
||||
|
||||
if numpy.any(face_landmark_68_5):
|
||||
face_landmark_68_5 = face_landmark_68_5.astype(numpy.int32)
|
||||
|
||||
for point in face_landmark_68_5:
|
||||
cv2.circle(temp_vision_frame, tuple(point), 3, point_color, -1)
|
||||
cv2.circle(temp_vision_frame, tuple(point), point_scale, point_color, -1)
|
||||
|
||||
return temp_vision_frame
|
||||
|
||||
|
||||
def process_frame(inputs : FaceDebuggerInputs) -> VisionFrame:
|
||||
def calculate_scale(temp_vision_frame : VisionFrame) -> int:
|
||||
frame_height, _ = temp_vision_frame.shape[:2]
|
||||
frame_scale = round(frame_height / 270)
|
||||
return max(1, min(10, frame_scale))
|
||||
|
||||
|
||||
def process_frame(inputs : FaceDebuggerInputs) -> ProcessorOutputs:
|
||||
reference_vision_frame = inputs.get('reference_vision_frame')
|
||||
target_vision_frame = inputs.get('target_vision_frame')
|
||||
source_vision_frames = inputs.get('source_vision_frames')
|
||||
target_vision_frames = inputs.get('target_vision_frames')
|
||||
temp_vision_frame = inputs.get('temp_vision_frame')
|
||||
target_faces = select_faces(reference_vision_frame, target_vision_frame)
|
||||
temp_vision_mask = inputs.get('temp_vision_mask')
|
||||
|
||||
target_vision_frame = get_middle(target_vision_frames)
|
||||
target_faces = select_faces(reference_vision_frame, source_vision_frames, target_vision_frames)
|
||||
|
||||
if target_faces:
|
||||
for target_face in target_faces:
|
||||
target_face = scale_face(target_face, target_vision_frame, temp_vision_frame)
|
||||
temp_vision_frame = debug_face(target_face, temp_vision_frame)
|
||||
|
||||
return temp_vision_frame
|
||||
|
||||
|
||||
return temp_vision_frame, temp_vision_mask
|
||||
@@ -0,0 +1,16 @@
|
||||
from facefusion.types import Locales
|
||||
|
||||
LOCALES : Locales =\
|
||||
{
|
||||
'en':
|
||||
{
|
||||
'help':
|
||||
{
|
||||
'items': 'load a single or multiple processors (choices: {choices})'
|
||||
},
|
||||
'uis':
|
||||
{
|
||||
'items_checkbox_group': 'FACE DEBUGGER ITEMS'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
from typing import List, Literal, TypedDict
|
||||
|
||||
from facefusion.types import Mask, VisionFrame
|
||||
|
||||
FaceDebuggerInputs = TypedDict('FaceDebuggerInputs',
|
||||
{
|
||||
'reference_vision_frame' : VisionFrame,
|
||||
'source_vision_frames' : List[VisionFrame],
|
||||
'target_vision_frames' : List[VisionFrame],
|
||||
'temp_vision_frame' : VisionFrame,
|
||||
'temp_vision_mask' : Mask
|
||||
})
|
||||
|
||||
FaceDebuggerItem = Literal['bounding-box', 'face-landmark-5', 'face-landmark-5/68', 'face-landmark-68', 'face-landmark-68/5', 'face-mask']
|
||||
@@ -0,0 +1,21 @@
|
||||
from typing import List, Sequence, get_args
|
||||
|
||||
from facefusion.common_helper import create_float_range
|
||||
from facefusion.processors.modules.face_editor.types import FaceEditorModel
|
||||
|
||||
face_editor_models : List[FaceEditorModel] = list(get_args(FaceEditorModel))
|
||||
|
||||
face_editor_eyebrow_direction_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_eye_gaze_horizontal_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_eye_gaze_vertical_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_eye_open_ratio_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_lip_open_ratio_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_mouth_grim_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_mouth_pout_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_mouth_purse_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_mouth_smile_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_mouth_position_horizontal_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_mouth_position_vertical_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_head_pitch_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_head_yaw_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
face_editor_head_roll_range : Sequence[float] = create_float_range(-1.0, 1.0, 0.05)
|
||||
+55
-34
@@ -1,26 +1,29 @@
|
||||
from argparse import ArgumentParser
|
||||
from functools import lru_cache
|
||||
from typing import Tuple
|
||||
from types import ModuleType
|
||||
from typing import List, Tuple
|
||||
|
||||
import cv2
|
||||
import numpy
|
||||
|
||||
import facefusion.jobs.job_manager
|
||||
import facefusion.jobs.job_store
|
||||
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, inference_manager, logger, state_manager, video_manager, wording
|
||||
from facefusion.common_helper import create_float_metavar
|
||||
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, inference_manager, logger, state_manager, translator, video_manager
|
||||
from facefusion.common_helper import create_float_metavar, get_middle
|
||||
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
||||
from facefusion.face_creator import scale_face
|
||||
from facefusion.face_helper import paste_back, scale_face_landmark_5, warp_face_by_face_landmark_5
|
||||
from facefusion.face_masker import create_box_mask
|
||||
from facefusion.face_selector import select_faces
|
||||
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path, same_file_extension
|
||||
from facefusion.processors import choices as processors_choices
|
||||
from facefusion.processors.live_portrait import create_rotation, limit_angle, limit_expression
|
||||
from facefusion.processors.types import FaceEditorInputs, LivePortraitExpression, LivePortraitFeatureVolume, LivePortraitMotionPoints, LivePortraitPitch, LivePortraitRoll, LivePortraitRotation, LivePortraitScale, LivePortraitTranslation, LivePortraitYaw
|
||||
from facefusion.processors.modules.face_editor import choices as face_editor_choices
|
||||
from facefusion.processors.modules.face_editor.types import FaceEditorInputs
|
||||
from facefusion.processors.types import LivePortraitExpression, LivePortraitFeatureVolume, LivePortraitMotionPoints, LivePortraitPitch, LivePortraitRoll, LivePortraitRotation, LivePortraitScale, LivePortraitTranslation, LivePortraitYaw, ProcessorOutputs
|
||||
from facefusion.program_helper import find_argument_group
|
||||
from facefusion.thread_helper import conditional_thread_semaphore, thread_semaphore
|
||||
from facefusion.types import ApplyStateItem, Args, DownloadScope, Face, FaceLandmark68, InferencePool, ModelOptions, ModelSet, ProcessMode, VisionFrame
|
||||
from facefusion.vision import read_static_image, read_static_video_frame
|
||||
from facefusion.vision import read_static_image, read_static_video_chunk, read_static_video_frame
|
||||
|
||||
|
||||
@lru_cache()
|
||||
@@ -29,6 +32,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
{
|
||||
'live_portrait':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'KwaiVGI',
|
||||
'license': 'MIT',
|
||||
'year': 2024
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'feature_extractor':
|
||||
@@ -121,21 +130,21 @@ def get_model_options() -> ModelOptions:
|
||||
def register_args(program : ArgumentParser) -> None:
|
||||
group_processors = find_argument_group(program, 'processors')
|
||||
if group_processors:
|
||||
group_processors.add_argument('--face-editor-model', help = wording.get('help.face_editor_model'), default = config.get_str_value('processors', 'face_editor_model', 'live_portrait'), choices = processors_choices.face_editor_models)
|
||||
group_processors.add_argument('--face-editor-eyebrow-direction', help = wording.get('help.face_editor_eyebrow_direction'), type = float, default = config.get_float_value('processors', 'face_editor_eyebrow_direction', '0'), choices = processors_choices.face_editor_eyebrow_direction_range, metavar = create_float_metavar(processors_choices.face_editor_eyebrow_direction_range))
|
||||
group_processors.add_argument('--face-editor-eye-gaze-horizontal', help = wording.get('help.face_editor_eye_gaze_horizontal'), type = float, default = config.get_float_value('processors', 'face_editor_eye_gaze_horizontal', '0'), choices = processors_choices.face_editor_eye_gaze_horizontal_range, metavar = create_float_metavar(processors_choices.face_editor_eye_gaze_horizontal_range))
|
||||
group_processors.add_argument('--face-editor-eye-gaze-vertical', help = wording.get('help.face_editor_eye_gaze_vertical'), type = float, default = config.get_float_value('processors', 'face_editor_eye_gaze_vertical', '0'), choices = processors_choices.face_editor_eye_gaze_vertical_range, metavar = create_float_metavar(processors_choices.face_editor_eye_gaze_vertical_range))
|
||||
group_processors.add_argument('--face-editor-eye-open-ratio', help = wording.get('help.face_editor_eye_open_ratio'), type = float, default = config.get_float_value('processors', 'face_editor_eye_open_ratio', '0'), choices = processors_choices.face_editor_eye_open_ratio_range, metavar = create_float_metavar(processors_choices.face_editor_eye_open_ratio_range))
|
||||
group_processors.add_argument('--face-editor-lip-open-ratio', help = wording.get('help.face_editor_lip_open_ratio'), type = float, default = config.get_float_value('processors', 'face_editor_lip_open_ratio', '0'), choices = processors_choices.face_editor_lip_open_ratio_range, metavar = create_float_metavar(processors_choices.face_editor_lip_open_ratio_range))
|
||||
group_processors.add_argument('--face-editor-mouth-grim', help = wording.get('help.face_editor_mouth_grim'), type = float, default = config.get_float_value('processors', 'face_editor_mouth_grim', '0'), choices = processors_choices.face_editor_mouth_grim_range, metavar = create_float_metavar(processors_choices.face_editor_mouth_grim_range))
|
||||
group_processors.add_argument('--face-editor-mouth-pout', help = wording.get('help.face_editor_mouth_pout'), type = float, default = config.get_float_value('processors', 'face_editor_mouth_pout', '0'), choices = processors_choices.face_editor_mouth_pout_range, metavar = create_float_metavar(processors_choices.face_editor_mouth_pout_range))
|
||||
group_processors.add_argument('--face-editor-mouth-purse', help = wording.get('help.face_editor_mouth_purse'), type = float, default = config.get_float_value('processors', 'face_editor_mouth_purse', '0'), choices = processors_choices.face_editor_mouth_purse_range, metavar = create_float_metavar(processors_choices.face_editor_mouth_purse_range))
|
||||
group_processors.add_argument('--face-editor-mouth-smile', help = wording.get('help.face_editor_mouth_smile'), type = float, default = config.get_float_value('processors', 'face_editor_mouth_smile', '0'), choices = processors_choices.face_editor_mouth_smile_range, metavar = create_float_metavar(processors_choices.face_editor_mouth_smile_range))
|
||||
group_processors.add_argument('--face-editor-mouth-position-horizontal', help = wording.get('help.face_editor_mouth_position_horizontal'), type = float, default = config.get_float_value('processors', 'face_editor_mouth_position_horizontal', '0'), choices = processors_choices.face_editor_mouth_position_horizontal_range, metavar = create_float_metavar(processors_choices.face_editor_mouth_position_horizontal_range))
|
||||
group_processors.add_argument('--face-editor-mouth-position-vertical', help = wording.get('help.face_editor_mouth_position_vertical'), type = float, default = config.get_float_value('processors', 'face_editor_mouth_position_vertical', '0'), choices = processors_choices.face_editor_mouth_position_vertical_range, metavar = create_float_metavar(processors_choices.face_editor_mouth_position_vertical_range))
|
||||
group_processors.add_argument('--face-editor-head-pitch', help = wording.get('help.face_editor_head_pitch'), type = float, default = config.get_float_value('processors', 'face_editor_head_pitch', '0'), choices = processors_choices.face_editor_head_pitch_range, metavar = create_float_metavar(processors_choices.face_editor_head_pitch_range))
|
||||
group_processors.add_argument('--face-editor-head-yaw', help = wording.get('help.face_editor_head_yaw'), type = float, default = config.get_float_value('processors', 'face_editor_head_yaw', '0'), choices = processors_choices.face_editor_head_yaw_range, metavar = create_float_metavar(processors_choices.face_editor_head_yaw_range))
|
||||
group_processors.add_argument('--face-editor-head-roll', help = wording.get('help.face_editor_head_roll'), type = float, default = config.get_float_value('processors', 'face_editor_head_roll', '0'), choices = processors_choices.face_editor_head_roll_range, metavar = create_float_metavar(processors_choices.face_editor_head_roll_range))
|
||||
group_processors.add_argument('--face-editor-model', help = translator.get('help.model', __package__), default = config.get_str_value('processors', 'face_editor_model', 'live_portrait'), choices = face_editor_choices.face_editor_models)
|
||||
group_processors.add_argument('--face-editor-eyebrow-direction', help = translator.get('help.eyebrow_direction', __package__), type = float, default = config.get_float_value('processors', 'face_editor_eyebrow_direction', '0'), choices = face_editor_choices.face_editor_eyebrow_direction_range, metavar = create_float_metavar(face_editor_choices.face_editor_eyebrow_direction_range))
|
||||
group_processors.add_argument('--face-editor-eye-gaze-horizontal', help = translator.get('help.eye_gaze_horizontal', __package__), type = float, default = config.get_float_value('processors', 'face_editor_eye_gaze_horizontal', '0'), choices = face_editor_choices.face_editor_eye_gaze_horizontal_range, metavar = create_float_metavar(face_editor_choices.face_editor_eye_gaze_horizontal_range))
|
||||
group_processors.add_argument('--face-editor-eye-gaze-vertical', help = translator.get('help.eye_gaze_vertical', __package__), type = float, default = config.get_float_value('processors', 'face_editor_eye_gaze_vertical', '0'), choices = face_editor_choices.face_editor_eye_gaze_vertical_range, metavar = create_float_metavar(face_editor_choices.face_editor_eye_gaze_vertical_range))
|
||||
group_processors.add_argument('--face-editor-eye-open-ratio', help = translator.get('help.eye_open_ratio', __package__), type = float, default = config.get_float_value('processors', 'face_editor_eye_open_ratio', '0'), choices = face_editor_choices.face_editor_eye_open_ratio_range, metavar = create_float_metavar(face_editor_choices.face_editor_eye_open_ratio_range))
|
||||
group_processors.add_argument('--face-editor-lip-open-ratio', help = translator.get('help.lip_open_ratio', __package__), type = float, default = config.get_float_value('processors', 'face_editor_lip_open_ratio', '0'), choices = face_editor_choices.face_editor_lip_open_ratio_range, metavar = create_float_metavar(face_editor_choices.face_editor_lip_open_ratio_range))
|
||||
group_processors.add_argument('--face-editor-mouth-grim', help = translator.get('help.mouth_grim', __package__), type = float, default = config.get_float_value('processors', 'face_editor_mouth_grim', '0'), choices = face_editor_choices.face_editor_mouth_grim_range, metavar = create_float_metavar(face_editor_choices.face_editor_mouth_grim_range))
|
||||
group_processors.add_argument('--face-editor-mouth-pout', help = translator.get('help.mouth_pout', __package__), type = float, default = config.get_float_value('processors', 'face_editor_mouth_pout', '0'), choices = face_editor_choices.face_editor_mouth_pout_range, metavar = create_float_metavar(face_editor_choices.face_editor_mouth_pout_range))
|
||||
group_processors.add_argument('--face-editor-mouth-purse', help = translator.get('help.mouth_purse', __package__), type = float, default = config.get_float_value('processors', 'face_editor_mouth_purse', '0'), choices = face_editor_choices.face_editor_mouth_purse_range, metavar = create_float_metavar(face_editor_choices.face_editor_mouth_purse_range))
|
||||
group_processors.add_argument('--face-editor-mouth-smile', help = translator.get('help.mouth_smile', __package__), type = float, default = config.get_float_value('processors', 'face_editor_mouth_smile', '0'), choices = face_editor_choices.face_editor_mouth_smile_range, metavar = create_float_metavar(face_editor_choices.face_editor_mouth_smile_range))
|
||||
group_processors.add_argument('--face-editor-mouth-position-horizontal', help = translator.get('help.mouth_position_horizontal', __package__), type = float, default = config.get_float_value('processors', 'face_editor_mouth_position_horizontal', '0'), choices = face_editor_choices.face_editor_mouth_position_horizontal_range, metavar = create_float_metavar(face_editor_choices.face_editor_mouth_position_horizontal_range))
|
||||
group_processors.add_argument('--face-editor-mouth-position-vertical', help = translator.get('help.mouth_position_vertical', __package__), type = float, default = config.get_float_value('processors', 'face_editor_mouth_position_vertical', '0'), choices = face_editor_choices.face_editor_mouth_position_vertical_range, metavar = create_float_metavar(face_editor_choices.face_editor_mouth_position_vertical_range))
|
||||
group_processors.add_argument('--face-editor-head-pitch', help = translator.get('help.head_pitch', __package__), type = float, default = config.get_float_value('processors', 'face_editor_head_pitch', '0'), choices = face_editor_choices.face_editor_head_pitch_range, metavar = create_float_metavar(face_editor_choices.face_editor_head_pitch_range))
|
||||
group_processors.add_argument('--face-editor-head-yaw', help = translator.get('help.head_yaw', __package__), type = float, default = config.get_float_value('processors', 'face_editor_head_yaw', '0'), choices = face_editor_choices.face_editor_head_yaw_range, metavar = create_float_metavar(face_editor_choices.face_editor_head_yaw_range))
|
||||
group_processors.add_argument('--face-editor-head-roll', help = translator.get('help.head_roll', __package__), type = float, default = config.get_float_value('processors', 'face_editor_head_roll', '0'), choices = face_editor_choices.face_editor_head_roll_range, metavar = create_float_metavar(face_editor_choices.face_editor_head_roll_range))
|
||||
facefusion.jobs.job_store.register_step_keys([ 'face_editor_model', 'face_editor_eyebrow_direction', 'face_editor_eye_gaze_horizontal', 'face_editor_eye_gaze_vertical', 'face_editor_eye_open_ratio', 'face_editor_lip_open_ratio', 'face_editor_mouth_grim', 'face_editor_mouth_pout', 'face_editor_mouth_purse', 'face_editor_mouth_smile', 'face_editor_mouth_position_horizontal', 'face_editor_mouth_position_vertical', 'face_editor_head_pitch', 'face_editor_head_yaw', 'face_editor_head_roll' ])
|
||||
|
||||
|
||||
@@ -157,22 +166,30 @@ def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
|
||||
apply_state_item('face_editor_head_roll', args.get('face_editor_head_roll'))
|
||||
|
||||
|
||||
def get_common_modules() -> List[ModuleType]:
|
||||
return [ content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer ]
|
||||
|
||||
|
||||
def pre_check() -> bool:
|
||||
model_hash_set = get_model_options().get('hashes')
|
||||
model_source_set = get_model_options().get('sources')
|
||||
|
||||
for common_module in get_common_modules():
|
||||
if not common_module.pre_check():
|
||||
return False
|
||||
|
||||
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
||||
|
||||
|
||||
def pre_process(mode : ProcessMode) -> bool:
|
||||
if mode in [ 'output', 'preview' ] and not is_image(state_manager.get_item('target_path')) and not is_video(state_manager.get_item('target_path')):
|
||||
logger.error(wording.get('choose_image_or_video_target') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('choose_image_or_video_target') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
if mode == 'output' and not in_directory(state_manager.get_item('output_path')):
|
||||
logger.error(wording.get('specify_image_or_video_output') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('specify_image_or_video_output') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
if mode == 'output' and not same_file_extension(state_manager.get_item('target_path'), state_manager.get_item('output_path')):
|
||||
logger.error(wording.get('match_target_and_output_extension') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('match_target_and_output_extension') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -180,16 +197,15 @@ def pre_process(mode : ProcessMode) -> bool:
|
||||
def post_process() -> None:
|
||||
read_static_image.cache_clear()
|
||||
read_static_video_frame.cache_clear()
|
||||
read_static_video_chunk.cache_clear()
|
||||
video_manager.clear_video_pool()
|
||||
|
||||
if state_manager.get_item('video_memory_strategy') in [ 'strict', 'moderate' ]:
|
||||
clear_inference_pool()
|
||||
|
||||
if state_manager.get_item('video_memory_strategy') == 'strict':
|
||||
content_analyser.clear_inference_pool()
|
||||
face_classifier.clear_inference_pool()
|
||||
face_detector.clear_inference_pool()
|
||||
face_landmarker.clear_inference_pool()
|
||||
face_masker.clear_inference_pool()
|
||||
face_recognizer.clear_inference_pool()
|
||||
for common_module in get_common_modules():
|
||||
common_module.clear_inference_pool()
|
||||
|
||||
|
||||
def edit_face(target_face : Face, temp_vision_frame : VisionFrame) -> VisionFrame:
|
||||
@@ -476,14 +492,19 @@ def normalize_crop_frame(crop_vision_frame : VisionFrame) -> VisionFrame:
|
||||
return crop_vision_frame
|
||||
|
||||
|
||||
def process_frame(inputs : FaceEditorInputs) -> VisionFrame:
|
||||
def process_frame(inputs : FaceEditorInputs) -> ProcessorOutputs:
|
||||
reference_vision_frame = inputs.get('reference_vision_frame')
|
||||
target_vision_frame = inputs.get('target_vision_frame')
|
||||
source_vision_frames = inputs.get('source_vision_frames')
|
||||
target_vision_frames = inputs.get('target_vision_frames')
|
||||
temp_vision_frame = inputs.get('temp_vision_frame')
|
||||
target_faces = select_faces(reference_vision_frame, target_vision_frame)
|
||||
temp_vision_mask = inputs.get('temp_vision_mask')
|
||||
|
||||
target_vision_frame = get_middle(target_vision_frames)
|
||||
target_faces = select_faces(reference_vision_frame, source_vision_frames, target_vision_frames)
|
||||
|
||||
if target_faces:
|
||||
for target_face in target_faces:
|
||||
target_face = scale_face(target_face, target_vision_frame, temp_vision_frame)
|
||||
temp_vision_frame = edit_face(target_face, temp_vision_frame)
|
||||
|
||||
return temp_vision_frame
|
||||
return temp_vision_frame, temp_vision_mask
|
||||
@@ -0,0 +1,44 @@
|
||||
from facefusion.types import Locales
|
||||
|
||||
LOCALES : Locales =\
|
||||
{
|
||||
'en':
|
||||
{
|
||||
'help':
|
||||
{
|
||||
'model': 'choose the model responsible for editing the face',
|
||||
'eyebrow_direction': 'specify the eyebrow direction',
|
||||
'eye_gaze_horizontal': 'specify the horizontal eye gaze',
|
||||
'eye_gaze_vertical': 'specify the vertical eye gaze',
|
||||
'eye_open_ratio': 'specify the ratio of eye opening',
|
||||
'lip_open_ratio': 'specify the ratio of lip opening',
|
||||
'mouth_grim': 'specify the mouth grim',
|
||||
'mouth_pout': 'specify the mouth pout',
|
||||
'mouth_purse': 'specify the mouth purse',
|
||||
'mouth_smile': 'specify the mouth smile',
|
||||
'mouth_position_horizontal': 'specify the horizontal mouth position',
|
||||
'mouth_position_vertical': 'specify the vertical mouth position',
|
||||
'head_pitch': 'specify the head pitch',
|
||||
'head_yaw': 'specify the head yaw',
|
||||
'head_roll': 'specify the head roll'
|
||||
},
|
||||
'uis':
|
||||
{
|
||||
'eyebrow_direction_slider': 'FACE EDITOR EYEBROW DIRECTION',
|
||||
'eye_gaze_horizontal_slider': 'FACE EDITOR EYE GAZE HORIZONTAL',
|
||||
'eye_gaze_vertical_slider': 'FACE EDITOR EYE GAZE VERTICAL',
|
||||
'eye_open_ratio_slider': 'FACE EDITOR EYE OPEN RATIO',
|
||||
'head_pitch_slider': 'FACE EDITOR HEAD PITCH',
|
||||
'head_roll_slider': 'FACE EDITOR HEAD ROLL',
|
||||
'head_yaw_slider': 'FACE EDITOR HEAD YAW',
|
||||
'lip_open_ratio_slider': 'FACE EDITOR LIP OPEN RATIO',
|
||||
'model_dropdown': 'FACE EDITOR MODEL',
|
||||
'mouth_grim_slider': 'FACE EDITOR MOUTH GRIM',
|
||||
'mouth_position_horizontal_slider': 'FACE EDITOR MOUTH POSITION HORIZONTAL',
|
||||
'mouth_position_vertical_slider': 'FACE EDITOR MOUTH POSITION VERTICAL',
|
||||
'mouth_pout_slider': 'FACE EDITOR MOUTH POUT',
|
||||
'mouth_purse_slider': 'FACE EDITOR MOUTH PURSE',
|
||||
'mouth_smile_slider': 'FACE EDITOR MOUTH SMILE'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
from typing import List, Literal, TypedDict
|
||||
|
||||
from facefusion.types import Mask, VisionFrame
|
||||
|
||||
FaceEditorInputs = TypedDict('FaceEditorInputs',
|
||||
{
|
||||
'reference_vision_frame' : VisionFrame,
|
||||
'source_vision_frames' : List[VisionFrame],
|
||||
'target_vision_frames' : List[VisionFrame],
|
||||
'temp_vision_frame' : VisionFrame,
|
||||
'temp_vision_mask' : Mask
|
||||
})
|
||||
|
||||
FaceEditorModel = Literal['live_portrait']
|
||||
@@ -0,0 +1,10 @@
|
||||
from typing import List, Sequence, get_args
|
||||
|
||||
from facefusion.common_helper import create_float_range, create_int_range
|
||||
from facefusion.processors.modules.face_enhancer.types import FaceEnhancerModel
|
||||
|
||||
face_enhancer_models : List[FaceEnhancerModel] = list(get_args(FaceEnhancerModel))
|
||||
|
||||
face_enhancer_blend_range : Sequence[int] = create_int_range(0, 100, 1)
|
||||
|
||||
face_enhancer_weight_range : Sequence[float] = create_float_range(0.0, 1.0, 0.05)
|
||||
+91
-21
@@ -1,23 +1,27 @@
|
||||
from argparse import ArgumentParser
|
||||
from functools import lru_cache
|
||||
from types import ModuleType
|
||||
from typing import List
|
||||
|
||||
import numpy
|
||||
|
||||
import facefusion.jobs.job_manager
|
||||
import facefusion.jobs.job_store
|
||||
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, inference_manager, logger, state_manager, video_manager, wording
|
||||
from facefusion.common_helper import create_float_metavar, create_int_metavar
|
||||
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, inference_manager, logger, state_manager, translator, video_manager
|
||||
from facefusion.common_helper import create_float_metavar, create_int_metavar, get_middle
|
||||
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
||||
from facefusion.face_creator import scale_face
|
||||
from facefusion.face_helper import paste_back, warp_face_by_face_landmark_5
|
||||
from facefusion.face_masker import create_box_mask, create_occlusion_mask
|
||||
from facefusion.face_selector import select_faces
|
||||
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path, same_file_extension
|
||||
from facefusion.processors import choices as processors_choices
|
||||
from facefusion.processors.types import FaceEnhancerInputs, FaceEnhancerWeight
|
||||
from facefusion.processors.modules.face_enhancer import choices as face_enhancer_choices
|
||||
from facefusion.processors.modules.face_enhancer.types import FaceEnhancerInputs, FaceEnhancerWeight
|
||||
from facefusion.processors.types import ProcessorOutputs
|
||||
from facefusion.program_helper import find_argument_group
|
||||
from facefusion.thread_helper import thread_semaphore
|
||||
from facefusion.types import ApplyStateItem, Args, DownloadScope, Face, InferencePool, ModelOptions, ModelSet, ProcessMode, VisionFrame
|
||||
from facefusion.vision import blend_frame, read_static_image, read_static_video_frame
|
||||
from facefusion.vision import blend_frame, read_static_image, read_static_video_chunk, read_static_video_frame
|
||||
|
||||
|
||||
@lru_cache()
|
||||
@@ -26,6 +30,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
{
|
||||
'codeformer':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'sczhou',
|
||||
'license': 'S-Lab-1.0',
|
||||
'year': 2022
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_enhancer':
|
||||
@@ -47,6 +57,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'gfpgan_1.2':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'TencentARC',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2022
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_enhancer':
|
||||
@@ -68,6 +84,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'gfpgan_1.3':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'TencentARC',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2022
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_enhancer':
|
||||
@@ -89,6 +111,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'gfpgan_1.4':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'TencentARC',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2022
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_enhancer':
|
||||
@@ -110,6 +138,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'gpen_bfr_256':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'yangxy',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_enhancer':
|
||||
@@ -131,6 +165,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'gpen_bfr_512':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'yangxy',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_enhancer':
|
||||
@@ -152,6 +192,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'gpen_bfr_1024':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'yangxy',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_enhancer':
|
||||
@@ -173,6 +219,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'gpen_bfr_2048':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'yangxy',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_enhancer':
|
||||
@@ -194,6 +246,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'restoreformer_plus_plus':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'wzhouxiff',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2022
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_enhancer':
|
||||
@@ -236,9 +294,9 @@ def get_model_options() -> ModelOptions:
|
||||
def register_args(program : ArgumentParser) -> None:
|
||||
group_processors = find_argument_group(program, 'processors')
|
||||
if group_processors:
|
||||
group_processors.add_argument('--face-enhancer-model', help = wording.get('help.face_enhancer_model'), default = config.get_str_value('processors', 'face_enhancer_model', 'gfpgan_1.4'), choices = processors_choices.face_enhancer_models)
|
||||
group_processors.add_argument('--face-enhancer-blend', help = wording.get('help.face_enhancer_blend'), type = int, default = config.get_int_value('processors', 'face_enhancer_blend', '80'), choices = processors_choices.face_enhancer_blend_range, metavar = create_int_metavar(processors_choices.face_enhancer_blend_range))
|
||||
group_processors.add_argument('--face-enhancer-weight', help = wording.get('help.face_enhancer_weight'), type = float, default = config.get_float_value('processors', 'face_enhancer_weight', '0.5'), choices = processors_choices.face_enhancer_weight_range, metavar = create_float_metavar(processors_choices.face_enhancer_weight_range))
|
||||
group_processors.add_argument('--face-enhancer-model', help = translator.get('help.model', __package__), default = config.get_str_value('processors', 'face_enhancer_model', 'gfpgan_1.4'), choices = face_enhancer_choices.face_enhancer_models)
|
||||
group_processors.add_argument('--face-enhancer-blend', help = translator.get('help.blend', __package__), type = int, default = config.get_int_value('processors', 'face_enhancer_blend', '80'), choices = face_enhancer_choices.face_enhancer_blend_range, metavar = create_int_metavar(face_enhancer_choices.face_enhancer_blend_range))
|
||||
group_processors.add_argument('--face-enhancer-weight', help = translator.get('help.weight', __package__), type = float, default = config.get_float_value('processors', 'face_enhancer_weight', '0.5'), choices = face_enhancer_choices.face_enhancer_weight_range, metavar = create_float_metavar(face_enhancer_choices.face_enhancer_weight_range))
|
||||
facefusion.jobs.job_store.register_step_keys([ 'face_enhancer_model', 'face_enhancer_blend', 'face_enhancer_weight' ])
|
||||
|
||||
|
||||
@@ -248,22 +306,30 @@ def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
|
||||
apply_state_item('face_enhancer_weight', args.get('face_enhancer_weight'))
|
||||
|
||||
|
||||
def get_common_modules() -> List[ModuleType]:
|
||||
return [ content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer ]
|
||||
|
||||
|
||||
def pre_check() -> bool:
|
||||
model_hash_set = get_model_options().get('hashes')
|
||||
model_source_set = get_model_options().get('sources')
|
||||
|
||||
for common_module in get_common_modules():
|
||||
if not common_module.pre_check():
|
||||
return False
|
||||
|
||||
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
||||
|
||||
|
||||
def pre_process(mode : ProcessMode) -> bool:
|
||||
if mode in [ 'output', 'preview' ] and not is_image(state_manager.get_item('target_path')) and not is_video(state_manager.get_item('target_path')):
|
||||
logger.error(wording.get('choose_image_or_video_target') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('choose_image_or_video_target') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
if mode == 'output' and not in_directory(state_manager.get_item('output_path')):
|
||||
logger.error(wording.get('specify_image_or_video_output') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('specify_image_or_video_output') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
if mode == 'output' and not same_file_extension(state_manager.get_item('target_path'), state_manager.get_item('output_path')):
|
||||
logger.error(wording.get('match_target_and_output_extension') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('match_target_and_output_extension') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -271,16 +337,15 @@ def pre_process(mode : ProcessMode) -> bool:
|
||||
def post_process() -> None:
|
||||
read_static_image.cache_clear()
|
||||
read_static_video_frame.cache_clear()
|
||||
read_static_video_chunk.cache_clear()
|
||||
video_manager.clear_video_pool()
|
||||
|
||||
if state_manager.get_item('video_memory_strategy') in [ 'strict', 'moderate' ]:
|
||||
clear_inference_pool()
|
||||
|
||||
if state_manager.get_item('video_memory_strategy') == 'strict':
|
||||
content_analyser.clear_inference_pool()
|
||||
face_classifier.clear_inference_pool()
|
||||
face_detector.clear_inference_pool()
|
||||
face_landmarker.clear_inference_pool()
|
||||
face_masker.clear_inference_pool()
|
||||
face_recognizer.clear_inference_pool()
|
||||
for common_module in get_common_modules():
|
||||
common_module.clear_inference_pool()
|
||||
|
||||
|
||||
def enhance_face(target_face : Face, temp_vision_frame : VisionFrame) -> VisionFrame:
|
||||
@@ -355,14 +420,19 @@ def blend_paste_frame(temp_vision_frame : VisionFrame, paste_vision_frame : Visi
|
||||
return temp_vision_frame
|
||||
|
||||
|
||||
def process_frame(inputs : FaceEnhancerInputs) -> VisionFrame:
|
||||
def process_frame(inputs : FaceEnhancerInputs) -> ProcessorOutputs:
|
||||
reference_vision_frame = inputs.get('reference_vision_frame')
|
||||
target_vision_frame = inputs.get('target_vision_frame')
|
||||
source_vision_frames = inputs.get('source_vision_frames')
|
||||
target_vision_frames = inputs.get('target_vision_frames')
|
||||
temp_vision_frame = inputs.get('temp_vision_frame')
|
||||
target_faces = select_faces(reference_vision_frame, target_vision_frame)
|
||||
temp_vision_mask = inputs.get('temp_vision_mask')
|
||||
|
||||
target_vision_frame = get_middle(target_vision_frames)
|
||||
target_faces = select_faces(reference_vision_frame, source_vision_frames, target_vision_frames)
|
||||
|
||||
if target_faces:
|
||||
for target_face in target_faces:
|
||||
target_face = scale_face(target_face, target_vision_frame, temp_vision_frame)
|
||||
temp_vision_frame = enhance_face(target_face, temp_vision_frame)
|
||||
|
||||
return temp_vision_frame
|
||||
return temp_vision_frame, temp_vision_mask
|
||||
@@ -0,0 +1,20 @@
|
||||
from facefusion.types import Locales
|
||||
|
||||
LOCALES : Locales =\
|
||||
{
|
||||
'en':
|
||||
{
|
||||
'help':
|
||||
{
|
||||
'model': 'choose the model responsible for enhancing the face',
|
||||
'blend': 'blend the enhanced into the previous face',
|
||||
'weight': 'specify the degree of weight applied to the face'
|
||||
},
|
||||
'uis':
|
||||
{
|
||||
'blend_slider': 'FACE ENHANCER BLEND',
|
||||
'model_dropdown': 'FACE ENHANCER MODEL',
|
||||
'weight_slider': 'FACE ENHANCER WEIGHT'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
from typing import Any, List, Literal, TypeAlias, TypedDict
|
||||
|
||||
from numpy.typing import NDArray
|
||||
|
||||
from facefusion.types import Mask, VisionFrame
|
||||
|
||||
FaceEnhancerInputs = TypedDict('FaceEnhancerInputs',
|
||||
{
|
||||
'reference_vision_frame' : VisionFrame,
|
||||
'source_vision_frames' : List[VisionFrame],
|
||||
'target_vision_frames' : List[VisionFrame],
|
||||
'temp_vision_frame' : VisionFrame,
|
||||
'temp_vision_mask' : Mask
|
||||
})
|
||||
|
||||
FaceEnhancerModel = Literal['codeformer', 'gfpgan_1.2', 'gfpgan_1.3', 'gfpgan_1.4', 'gpen_bfr_256', 'gpen_bfr_512', 'gpen_bfr_1024', 'gpen_bfr_2048', 'restoreformer_plus_plus']
|
||||
|
||||
FaceEnhancerWeight : TypeAlias = NDArray[Any]
|
||||
@@ -0,0 +1,26 @@
|
||||
from typing import List, Sequence, get_args
|
||||
|
||||
from facefusion.common_helper import create_float_range
|
||||
from facefusion.processors.modules.face_swapper.types import FaceSwapperModel, FaceSwapperSet, FaceSwapperWeight
|
||||
|
||||
|
||||
face_swapper_set : FaceSwapperSet =\
|
||||
{
|
||||
'blendswap_256': [ '256x256', '384x384', '512x512', '768x768', '1024x1024' ],
|
||||
'ghost_1_256': [ '256x256', '512x512', '768x768', '1024x1024' ],
|
||||
'ghost_2_256': [ '256x256', '512x512', '768x768', '1024x1024' ],
|
||||
'ghost_3_256': [ '256x256', '512x512', '768x768', '1024x1024' ],
|
||||
'hififace_unofficial_256': [ '256x256', '512x512', '768x768', '1024x1024' ],
|
||||
'hyperswap_1a_256': [ '256x256', '512x512', '768x768', '1024x1024' ],
|
||||
'hyperswap_1b_256': [ '256x256', '512x512', '768x768', '1024x1024' ],
|
||||
'hyperswap_1c_256': [ '256x256', '512x512', '768x768', '1024x1024' ],
|
||||
'inswapper_128': [ '128x128', '256x256', '384x384', '512x512', '768x768', '1024x1024' ],
|
||||
'inswapper_128_fp16': [ '128x128', '256x256', '384x384', '512x512', '768x768', '1024x1024' ],
|
||||
'simswap_256': [ '256x256', '512x512', '768x768', '1024x1024' ],
|
||||
'simswap_unofficial_512': [ '512x512', '768x768', '1024x1024' ],
|
||||
'uniface_256': [ '256x256', '512x512', '768x768', '1024x1024' ]
|
||||
}
|
||||
|
||||
face_swapper_models : List[FaceSwapperModel] = list(get_args(FaceSwapperModel))
|
||||
|
||||
face_swapper_weight_range : Sequence[FaceSwapperWeight] = create_float_range(0.0, 1.0, 0.05)
|
||||
+155
-52
@@ -1,5 +1,6 @@
|
||||
from argparse import ArgumentParser
|
||||
from functools import lru_cache
|
||||
from types import ModuleType
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
import cv2
|
||||
@@ -8,23 +9,24 @@ import numpy
|
||||
import facefusion.choices
|
||||
import facefusion.jobs.job_manager
|
||||
import facefusion.jobs.job_store
|
||||
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, inference_manager, logger, state_manager, video_manager, wording
|
||||
from facefusion.common_helper import get_first, is_macos
|
||||
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, inference_manager, logger, state_manager, translator, video_manager
|
||||
from facefusion.common_helper import get_first, get_middle, is_macos
|
||||
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
||||
from facefusion.execution import has_execution_provider
|
||||
from facefusion.face_analyser import get_average_face, get_many_faces, get_one_face
|
||||
from facefusion.face_creator import average_face_identity, get_one_face, get_static_faces, scale_face
|
||||
from facefusion.face_helper import paste_back, warp_face_by_face_landmark_5
|
||||
from facefusion.face_masker import create_area_mask, create_box_mask, create_occlusion_mask, create_region_mask
|
||||
from facefusion.face_selector import select_faces, sort_faces_by_order
|
||||
from facefusion.filesystem import filter_image_paths, has_image, in_directory, is_image, is_video, resolve_relative_path, same_file_extension
|
||||
from facefusion.model_helper import get_static_model_initializer
|
||||
from facefusion.processors import choices as processors_choices
|
||||
from facefusion.processors.modules.face_swapper import choices as face_swapper_choices
|
||||
from facefusion.processors.modules.face_swapper.types import FaceSwapperInputs
|
||||
from facefusion.processors.pixel_boost import explode_pixel_boost, implode_pixel_boost
|
||||
from facefusion.processors.types import FaceSwapperInputs
|
||||
from facefusion.processors.types import ProcessorOutputs
|
||||
from facefusion.program_helper import find_argument_group
|
||||
from facefusion.thread_helper import conditional_thread_semaphore
|
||||
from facefusion.types import ApplyStateItem, Args, DownloadScope, Embedding, Face, InferencePool, ModelOptions, ModelSet, ProcessMode, VisionFrame
|
||||
from facefusion.vision import read_static_image, read_static_images, read_static_video_frame, unpack_resolution
|
||||
from facefusion.types import ApplyStateItem, Args, DownloadScope, Embedding, Face, InferencePool, InferenceProvider, ModelOptions, ModelSet, ProcessMode, VisionFrame
|
||||
from facefusion.vision import read_static_image, read_static_images, read_static_video_chunk, read_static_video_frame, unpack_resolution
|
||||
|
||||
|
||||
@lru_cache()
|
||||
@@ -33,6 +35,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
{
|
||||
'blendswap_256':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'mapooon',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2023
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_swapper':
|
||||
@@ -57,6 +65,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'ghost_1_256':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'ai-forever',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2022
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_swapper':
|
||||
@@ -91,6 +105,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'ghost_2_256':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'ai-forever',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2022
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_swapper':
|
||||
@@ -125,6 +145,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'ghost_3_256':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'ai-forever',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2022
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_swapper':
|
||||
@@ -159,6 +185,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'hififace_unofficial_256':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'GuijiAI',
|
||||
'license': 'Unknown',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_swapper':
|
||||
@@ -193,6 +225,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'hyperswap_1a_256':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'FaceFusion',
|
||||
'license': 'ResearchRAIL',
|
||||
'year': 2025
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_swapper':
|
||||
@@ -209,6 +247,7 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
'path': resolve_relative_path('../.assets/models/hyperswap_1a_256.onnx')
|
||||
}
|
||||
},
|
||||
'precision': 'fp16',
|
||||
'type': 'hyperswap',
|
||||
'template': 'arcface_128',
|
||||
'size': (256, 256),
|
||||
@@ -217,6 +256,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'hyperswap_1b_256':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'FaceFusion',
|
||||
'license': 'ResearchRAIL',
|
||||
'year': 2025
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_swapper':
|
||||
@@ -233,6 +278,7 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
'path': resolve_relative_path('../.assets/models/hyperswap_1b_256.onnx')
|
||||
}
|
||||
},
|
||||
'precision': 'fp16',
|
||||
'type': 'hyperswap',
|
||||
'template': 'arcface_128',
|
||||
'size': (256, 256),
|
||||
@@ -241,6 +287,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'hyperswap_1c_256':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'FaceFusion',
|
||||
'license': 'ResearchRAIL',
|
||||
'year': 2025
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_swapper':
|
||||
@@ -257,6 +309,7 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
'path': resolve_relative_path('../.assets/models/hyperswap_1c_256.onnx')
|
||||
}
|
||||
},
|
||||
'precision': 'fp16',
|
||||
'type': 'hyperswap',
|
||||
'template': 'arcface_128',
|
||||
'size': (256, 256),
|
||||
@@ -265,6 +318,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'inswapper_128':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'InsightFace',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2023
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_swapper':
|
||||
@@ -289,6 +348,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'inswapper_128_fp16':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'InsightFace',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2023
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_swapper':
|
||||
@@ -305,6 +370,7 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
'path': resolve_relative_path('../.assets/models/inswapper_128_fp16.onnx')
|
||||
}
|
||||
},
|
||||
'precision': 'fp16',
|
||||
'type': 'inswapper',
|
||||
'template': 'arcface_128',
|
||||
'size': (128, 128),
|
||||
@@ -313,6 +379,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'simswap_256':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'neuralchen',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2020
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_swapper':
|
||||
@@ -347,6 +419,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'simswap_unofficial_512':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'neuralchen',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2020
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_swapper':
|
||||
@@ -381,6 +459,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'uniface_256':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'xc-csc101',
|
||||
'license': 'Unknown',
|
||||
'year': 2022
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'face_swapper':
|
||||
@@ -407,38 +491,48 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
|
||||
|
||||
def get_inference_pool() -> InferencePool:
|
||||
model_names = [ get_model_name() ]
|
||||
model_names = [ state_manager.get_item('face_swapper_model') ]
|
||||
model_source_set = get_model_options().get('sources')
|
||||
|
||||
return inference_manager.get_inference_pool(__name__, model_names, model_source_set)
|
||||
|
||||
|
||||
def clear_inference_pool() -> None:
|
||||
model_names = [ get_model_name() ]
|
||||
model_names = [ state_manager.get_item('face_swapper_model') ]
|
||||
inference_manager.clear_inference_pool(__name__, model_names)
|
||||
|
||||
|
||||
def resolve_inference_providers() -> List[InferenceProvider]:
|
||||
model_precision = get_model_options().get('precision')
|
||||
model_type = get_model_options().get('type')
|
||||
|
||||
if is_macos() and has_execution_provider('coreml'):
|
||||
if model_type in [ 'ghost', 'uniface' ] or model_precision == 'fp16':
|
||||
return\
|
||||
[
|
||||
(facefusion.choices.execution_provider_set.get('coreml'),
|
||||
{
|
||||
'ModelFormat': 'MLProgram',
|
||||
'SpecializationStrategy': 'FastPrediction'
|
||||
})
|
||||
]
|
||||
|
||||
return []
|
||||
|
||||
|
||||
def get_model_options() -> ModelOptions:
|
||||
model_name = get_model_name()
|
||||
return create_static_model_set('full').get(model_name)
|
||||
|
||||
|
||||
def get_model_name() -> str:
|
||||
model_name = state_manager.get_item('face_swapper_model')
|
||||
|
||||
if is_macos() and has_execution_provider('coreml') and model_name == 'inswapper_128_fp16':
|
||||
return 'inswapper_128'
|
||||
return model_name
|
||||
return create_static_model_set('full').get(model_name)
|
||||
|
||||
|
||||
def register_args(program : ArgumentParser) -> None:
|
||||
group_processors = find_argument_group(program, 'processors')
|
||||
if group_processors:
|
||||
group_processors.add_argument('--face-swapper-model', help = wording.get('help.face_swapper_model'), default = config.get_str_value('processors', 'face_swapper_model', 'hyperswap_1a_256'), choices = processors_choices.face_swapper_models)
|
||||
group_processors.add_argument('--face-swapper-model', help = translator.get('help.model', __package__), default = config.get_str_value('processors', 'face_swapper_model', 'hyperswap_1a_256'), choices = face_swapper_choices.face_swapper_models)
|
||||
known_args, _ = program.parse_known_args()
|
||||
face_swapper_pixel_boost_choices = processors_choices.face_swapper_set.get(known_args.face_swapper_model)
|
||||
group_processors.add_argument('--face-swapper-pixel-boost', help = wording.get('help.face_swapper_pixel_boost'), default = config.get_str_value('processors', 'face_swapper_pixel_boost', get_first(face_swapper_pixel_boost_choices)), choices = face_swapper_pixel_boost_choices)
|
||||
group_processors.add_argument('--face-swapper-weight', help = wording.get('help.face_swapper_weight'), type = float, default = config.get_float_value('processors', 'face_swapper_weight', '0.5'), choices = processors_choices.face_swapper_weight_range)
|
||||
face_swapper_pixel_boost_choices = face_swapper_choices.face_swapper_set.get(known_args.face_swapper_model)
|
||||
group_processors.add_argument('--face-swapper-pixel-boost', help = translator.get('help.pixel_boost', __package__), default = config.get_str_value('processors', 'face_swapper_pixel_boost', get_first(face_swapper_pixel_boost_choices)), choices = face_swapper_pixel_boost_choices)
|
||||
group_processors.add_argument('--face-swapper-weight', help = translator.get('help.weight', __package__), type = float, default = config.get_float_value('processors', 'face_swapper_weight', '0.5'), choices = face_swapper_choices.face_swapper_weight_range)
|
||||
facefusion.jobs.job_store.register_step_keys([ 'face_swapper_model', 'face_swapper_pixel_boost', 'face_swapper_weight' ])
|
||||
|
||||
|
||||
@@ -448,36 +542,44 @@ def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
|
||||
apply_state_item('face_swapper_weight', args.get('face_swapper_weight'))
|
||||
|
||||
|
||||
def get_common_modules() -> List[ModuleType]:
|
||||
return [ content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer ]
|
||||
|
||||
|
||||
def pre_check() -> bool:
|
||||
model_hash_set = get_model_options().get('hashes')
|
||||
model_source_set = get_model_options().get('sources')
|
||||
|
||||
for common_module in get_common_modules():
|
||||
if not common_module.pre_check():
|
||||
return False
|
||||
|
||||
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
||||
|
||||
|
||||
def pre_process(mode : ProcessMode) -> bool:
|
||||
if not has_image(state_manager.get_item('source_paths')):
|
||||
logger.error(wording.get('choose_image_source') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('choose_image_source') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
|
||||
source_image_paths = filter_image_paths(state_manager.get_item('source_paths'))
|
||||
source_frames = read_static_images(source_image_paths)
|
||||
source_faces = get_many_faces(source_frames)
|
||||
source_vision_frames = read_static_images(source_image_paths)
|
||||
source_faces = get_static_faces(source_vision_frames)
|
||||
|
||||
if not get_one_face(source_faces):
|
||||
logger.error(wording.get('no_source_face_detected') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('no_source_face_detected') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
|
||||
if mode in [ 'output', 'preview' ] and not is_image(state_manager.get_item('target_path')) and not is_video(state_manager.get_item('target_path')):
|
||||
logger.error(wording.get('choose_image_or_video_target') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('choose_image_or_video_target') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
|
||||
if mode == 'output' and not in_directory(state_manager.get_item('output_path')):
|
||||
logger.error(wording.get('specify_image_or_video_output') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('specify_image_or_video_output') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
|
||||
if mode == 'output' and not same_file_extension(state_manager.get_item('target_path'), state_manager.get_item('output_path')):
|
||||
logger.error(wording.get('match_target_and_output_extension') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('match_target_and_output_extension') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
|
||||
return True
|
||||
@@ -486,20 +588,19 @@ def pre_process(mode : ProcessMode) -> bool:
|
||||
def post_process() -> None:
|
||||
read_static_image.cache_clear()
|
||||
read_static_video_frame.cache_clear()
|
||||
read_static_video_chunk.cache_clear()
|
||||
video_manager.clear_video_pool()
|
||||
|
||||
if state_manager.get_item('video_memory_strategy') in [ 'strict', 'moderate' ]:
|
||||
get_static_model_initializer.cache_clear()
|
||||
clear_inference_pool()
|
||||
|
||||
if state_manager.get_item('video_memory_strategy') == 'strict':
|
||||
content_analyser.clear_inference_pool()
|
||||
face_classifier.clear_inference_pool()
|
||||
face_detector.clear_inference_pool()
|
||||
face_landmarker.clear_inference_pool()
|
||||
face_masker.clear_inference_pool()
|
||||
face_recognizer.clear_inference_pool()
|
||||
for common_module in get_common_modules():
|
||||
common_module.clear_inference_pool()
|
||||
|
||||
|
||||
def swap_face(source_face : Face, target_face : Face, temp_vision_frame : VisionFrame) -> VisionFrame:
|
||||
def swap_face(source_face : Face, target_face : Face, source_vision_frame : VisionFrame, temp_vision_frame : VisionFrame) -> VisionFrame:
|
||||
model_template = get_model_options().get('template')
|
||||
model_size = get_model_options().get('size')
|
||||
pixel_boost_size = unpack_resolution(state_manager.get_item('face_swapper_pixel_boost'))
|
||||
@@ -519,7 +620,7 @@ def swap_face(source_face : Face, target_face : Face, temp_vision_frame : Vision
|
||||
pixel_boost_vision_frames = implode_pixel_boost(crop_vision_frame, pixel_boost_total, model_size)
|
||||
for pixel_boost_vision_frame in pixel_boost_vision_frames:
|
||||
pixel_boost_vision_frame = prepare_crop_frame(pixel_boost_vision_frame)
|
||||
pixel_boost_vision_frame = forward_swap_face(source_face, target_face, pixel_boost_vision_frame)
|
||||
pixel_boost_vision_frame = forward_swap_face(source_face, target_face, source_vision_frame, pixel_boost_vision_frame)
|
||||
pixel_boost_vision_frame = normalize_crop_frame(pixel_boost_vision_frame)
|
||||
temp_vision_frames.append(pixel_boost_vision_frame)
|
||||
crop_vision_frame = explode_pixel_boost(temp_vision_frames, pixel_boost_total, model_size, pixel_boost_size)
|
||||
@@ -538,18 +639,15 @@ def swap_face(source_face : Face, target_face : Face, temp_vision_frame : Vision
|
||||
return paste_vision_frame
|
||||
|
||||
|
||||
def forward_swap_face(source_face : Face, target_face : Face, crop_vision_frame : VisionFrame) -> VisionFrame:
|
||||
def forward_swap_face(source_face : Face, target_face : Face, source_vision_frame : VisionFrame, crop_vision_frame : VisionFrame) -> VisionFrame:
|
||||
face_swapper = get_inference_pool().get('face_swapper')
|
||||
model_type = get_model_options().get('type')
|
||||
face_swapper_inputs = {}
|
||||
|
||||
if is_macos() and has_execution_provider('coreml') and model_type in [ 'ghost', 'uniface' ]:
|
||||
face_swapper.set_providers([ facefusion.choices.execution_provider_set.get('cpu') ])
|
||||
|
||||
for face_swapper_input in face_swapper.get_inputs():
|
||||
if face_swapper_input.name == 'source':
|
||||
if model_type in [ 'blendswap', 'uniface' ]:
|
||||
face_swapper_inputs[face_swapper_input.name] = prepare_source_frame(source_face)
|
||||
face_swapper_inputs[face_swapper_input.name] = prepare_source_frame(source_face, source_vision_frame)
|
||||
else:
|
||||
source_embedding = prepare_source_embedding(source_face)
|
||||
source_embedding = balance_source_embedding(source_embedding, target_face.embedding)
|
||||
@@ -575,9 +673,8 @@ def forward_convert_embedding(face_embedding : Embedding) -> Embedding:
|
||||
return face_embedding
|
||||
|
||||
|
||||
def prepare_source_frame(source_face : Face) -> VisionFrame:
|
||||
def prepare_source_frame(source_face : Face, source_vision_frame : VisionFrame) -> VisionFrame:
|
||||
model_type = get_model_options().get('type')
|
||||
source_vision_frame = read_static_image(get_first(state_manager.get_item('source_paths')))
|
||||
|
||||
if model_type == 'blendswap':
|
||||
source_vision_frame, _ = warp_face_by_face_landmark_5(source_vision_frame, source_face.landmark_set.get('5/68'), 'arcface_112_v2', (112, 112))
|
||||
@@ -669,25 +766,31 @@ def extract_source_face(source_vision_frames : List[VisionFrame]) -> Optional[Fa
|
||||
|
||||
if source_vision_frames:
|
||||
for source_vision_frame in source_vision_frames:
|
||||
temp_faces = get_many_faces([source_vision_frame])
|
||||
temp_faces = get_static_faces([ source_vision_frame ])
|
||||
temp_faces = sort_faces_by_order(temp_faces, 'large-small')
|
||||
|
||||
if temp_faces:
|
||||
source_faces.append(get_first(temp_faces))
|
||||
|
||||
return get_average_face(source_faces)
|
||||
return average_face_identity(source_faces)
|
||||
|
||||
|
||||
def process_frame(inputs : FaceSwapperInputs) -> VisionFrame:
|
||||
def process_frame(inputs : FaceSwapperInputs) -> ProcessorOutputs:
|
||||
reference_vision_frame = inputs.get('reference_vision_frame')
|
||||
source_vision_frames = inputs.get('source_vision_frames')
|
||||
target_vision_frame = inputs.get('target_vision_frame')
|
||||
target_vision_frames = inputs.get('target_vision_frames')
|
||||
temp_vision_frame = inputs.get('temp_vision_frame')
|
||||
temp_vision_mask = inputs.get('temp_vision_mask')
|
||||
|
||||
target_vision_frame = get_middle(target_vision_frames)
|
||||
source_face = extract_source_face(source_vision_frames)
|
||||
target_faces = select_faces(reference_vision_frame, target_vision_frame)
|
||||
target_faces = select_faces(reference_vision_frame, source_vision_frames, target_vision_frames)
|
||||
|
||||
if source_face and target_faces:
|
||||
for target_face in target_faces:
|
||||
temp_vision_frame = swap_face(source_face, target_face, temp_vision_frame)
|
||||
source_vision_frame = get_first(source_vision_frames)
|
||||
|
||||
return temp_vision_frame
|
||||
for target_face in target_faces:
|
||||
target_face = scale_face(target_face, target_vision_frame, temp_vision_frame)
|
||||
temp_vision_frame = swap_face(source_face, target_face, source_vision_frame, temp_vision_frame)
|
||||
|
||||
return temp_vision_frame, temp_vision_mask
|
||||
@@ -0,0 +1,20 @@
|
||||
from facefusion.types import Locales
|
||||
|
||||
LOCALES : Locales =\
|
||||
{
|
||||
'en':
|
||||
{
|
||||
'help':
|
||||
{
|
||||
'model': 'choose the model responsible for swapping the face',
|
||||
'pixel_boost': 'choose the pixel boost resolution for the face swapper',
|
||||
'weight': 'specify the degree of weight applied to the face'
|
||||
},
|
||||
'uis':
|
||||
{
|
||||
'model_dropdown': 'FACE SWAPPER MODEL',
|
||||
'pixel_boost_dropdown': 'FACE SWAPPER PIXEL BOOST',
|
||||
'weight_slider': 'FACE SWAPPER WEIGHT'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
from typing import Dict, List, Literal, TypeAlias, TypedDict
|
||||
|
||||
from facefusion.types import Mask, VisionFrame
|
||||
|
||||
FaceSwapperInputs = TypedDict('FaceSwapperInputs',
|
||||
{
|
||||
'reference_vision_frame' : VisionFrame,
|
||||
'source_vision_frames' : List[VisionFrame],
|
||||
'target_vision_frames' : List[VisionFrame],
|
||||
'temp_vision_frame' : VisionFrame,
|
||||
'temp_vision_mask' : Mask
|
||||
})
|
||||
|
||||
FaceSwapperModel = Literal['blendswap_256', 'ghost_1_256', 'ghost_2_256', 'ghost_3_256', 'hififace_unofficial_256', 'hyperswap_1a_256', 'hyperswap_1b_256', 'hyperswap_1c_256', 'inswapper_128', 'inswapper_128_fp16', 'simswap_256', 'simswap_unofficial_512', 'uniface_256']
|
||||
|
||||
FaceSwapperWeight : TypeAlias = float
|
||||
|
||||
FaceSwapperSet : TypeAlias = Dict[FaceSwapperModel, List[str]]
|
||||
@@ -0,0 +1,10 @@
|
||||
from typing import List, Sequence, get_args
|
||||
|
||||
from facefusion.common_helper import create_int_range
|
||||
from facefusion.processors.modules.frame_colorizer.types import FrameColorizerModel
|
||||
|
||||
frame_colorizer_models : List[FrameColorizerModel] = list(get_args(FrameColorizerModel))
|
||||
|
||||
frame_colorizer_sizes : List[str] = [ '192x192', '256x256', '384x384', '512x512' ]
|
||||
|
||||
frame_colorizer_blend_range : Sequence[int] = create_int_range(0, 100, 1)
|
||||
+65
-17
@@ -1,23 +1,26 @@
|
||||
from argparse import ArgumentParser
|
||||
from functools import lru_cache
|
||||
from types import ModuleType
|
||||
from typing import List
|
||||
|
||||
import cv2
|
||||
import numpy
|
||||
|
||||
import facefusion.choices
|
||||
import facefusion.jobs.job_manager
|
||||
import facefusion.jobs.job_store
|
||||
from facefusion import config, content_analyser, inference_manager, logger, state_manager, video_manager, wording
|
||||
from facefusion import config, content_analyser, inference_manager, logger, state_manager, translator, video_manager
|
||||
from facefusion.common_helper import create_int_metavar, is_macos
|
||||
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
||||
from facefusion.execution import has_execution_provider
|
||||
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path, same_file_extension
|
||||
from facefusion.processors import choices as processors_choices
|
||||
from facefusion.processors.types import FrameColorizerInputs
|
||||
from facefusion.processors.modules.frame_colorizer import choices as frame_colorizer_choices
|
||||
from facefusion.processors.modules.frame_colorizer.types import FrameColorizerInputs
|
||||
from facefusion.processors.types import ProcessorOutputs
|
||||
from facefusion.program_helper import find_argument_group
|
||||
from facefusion.thread_helper import thread_semaphore
|
||||
from facefusion.types import ApplyStateItem, Args, DownloadScope, ExecutionProvider, InferencePool, ModelOptions, ModelSet, ProcessMode, VisionFrame
|
||||
from facefusion.vision import blend_frame, read_static_image, read_static_video_frame, unpack_resolution
|
||||
from facefusion.types import ApplyStateItem, Args, DownloadScope, InferencePool, InferenceProvider, ModelOptions, ModelSet, ProcessMode, VisionFrame
|
||||
from facefusion.vision import blend_frame, read_static_image, read_static_video_chunk, read_static_video_frame, unpack_resolution
|
||||
|
||||
|
||||
@lru_cache()
|
||||
@@ -26,6 +29,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
{
|
||||
'ddcolor':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'piddnad',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2023
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_colorizer':
|
||||
@@ -46,6 +55,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'ddcolor_artistic':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'piddnad',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2023
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_colorizer':
|
||||
@@ -66,6 +81,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'deoldify':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'jantic',
|
||||
'license': 'MIT',
|
||||
'year': 2022
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_colorizer':
|
||||
@@ -86,6 +107,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'deoldify_artistic':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'jantic',
|
||||
'license': 'MIT',
|
||||
'year': 2022
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_colorizer':
|
||||
@@ -106,6 +133,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'deoldify_stable':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'jantic',
|
||||
'license': 'MIT',
|
||||
'year': 2022
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_colorizer':
|
||||
@@ -139,10 +172,11 @@ def clear_inference_pool() -> None:
|
||||
inference_manager.clear_inference_pool(__name__, model_names)
|
||||
|
||||
|
||||
def resolve_execution_providers() -> List[ExecutionProvider]:
|
||||
def resolve_inference_providers() -> List[InferenceProvider]:
|
||||
if is_macos() and has_execution_provider('coreml'):
|
||||
return [ 'cpu' ]
|
||||
return state_manager.get_item('execution_providers')
|
||||
return [ facefusion.choices.execution_provider_set.get('cpu') ]
|
||||
|
||||
return []
|
||||
|
||||
|
||||
def get_model_options() -> ModelOptions:
|
||||
@@ -153,9 +187,9 @@ def get_model_options() -> ModelOptions:
|
||||
def register_args(program : ArgumentParser) -> None:
|
||||
group_processors = find_argument_group(program, 'processors')
|
||||
if group_processors:
|
||||
group_processors.add_argument('--frame-colorizer-model', help = wording.get('help.frame_colorizer_model'), default = config.get_str_value('processors', 'frame_colorizer_model', 'ddcolor'), choices = processors_choices.frame_colorizer_models)
|
||||
group_processors.add_argument('--frame-colorizer-size', help = wording.get('help.frame_colorizer_size'), type = str, default = config.get_str_value('processors', 'frame_colorizer_size', '256x256'), choices = processors_choices.frame_colorizer_sizes)
|
||||
group_processors.add_argument('--frame-colorizer-blend', help = wording.get('help.frame_colorizer_blend'), type = int, default = config.get_int_value('processors', 'frame_colorizer_blend', '100'), choices = processors_choices.frame_colorizer_blend_range, metavar = create_int_metavar(processors_choices.frame_colorizer_blend_range))
|
||||
group_processors.add_argument('--frame-colorizer-model', help = translator.get('help.model', __package__), default = config.get_str_value('processors', 'frame_colorizer_model', 'ddcolor'), choices = frame_colorizer_choices.frame_colorizer_models)
|
||||
group_processors.add_argument('--frame-colorizer-size', help = translator.get('help.size', __package__), type = str, default = config.get_str_value('processors', 'frame_colorizer_size', '256x256'), choices = frame_colorizer_choices.frame_colorizer_sizes)
|
||||
group_processors.add_argument('--frame-colorizer-blend', help = translator.get('help.blend', __package__), type = int, default = config.get_int_value('processors', 'frame_colorizer_blend', '100'), choices = frame_colorizer_choices.frame_colorizer_blend_range, metavar = create_int_metavar(frame_colorizer_choices.frame_colorizer_blend_range))
|
||||
facefusion.jobs.job_store.register_step_keys([ 'frame_colorizer_model', 'frame_colorizer_blend', 'frame_colorizer_size' ])
|
||||
|
||||
|
||||
@@ -165,22 +199,30 @@ def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
|
||||
apply_state_item('frame_colorizer_size', args.get('frame_colorizer_size'))
|
||||
|
||||
|
||||
def get_common_modules() -> List[ModuleType]:
|
||||
return [ content_analyser ]
|
||||
|
||||
|
||||
def pre_check() -> bool:
|
||||
model_hash_set = get_model_options().get('hashes')
|
||||
model_source_set = get_model_options().get('sources')
|
||||
|
||||
for common_module in get_common_modules():
|
||||
if not common_module.pre_check():
|
||||
return False
|
||||
|
||||
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
||||
|
||||
|
||||
def pre_process(mode : ProcessMode) -> bool:
|
||||
if mode in [ 'output', 'preview' ] and not is_image(state_manager.get_item('target_path')) and not is_video(state_manager.get_item('target_path')):
|
||||
logger.error(wording.get('choose_image_or_video_target') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('choose_image_or_video_target') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
if mode == 'output' and not in_directory(state_manager.get_item('output_path')):
|
||||
logger.error(wording.get('specify_image_or_video_output') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('specify_image_or_video_output') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
if mode == 'output' and not same_file_extension(state_manager.get_item('target_path'), state_manager.get_item('output_path')):
|
||||
logger.error(wording.get('match_target_and_output_extension') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('match_target_and_output_extension') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -188,11 +230,15 @@ def pre_process(mode : ProcessMode) -> bool:
|
||||
def post_process() -> None:
|
||||
read_static_image.cache_clear()
|
||||
read_static_video_frame.cache_clear()
|
||||
read_static_video_chunk.cache_clear()
|
||||
video_manager.clear_video_pool()
|
||||
|
||||
if state_manager.get_item('video_memory_strategy') in [ 'strict', 'moderate' ]:
|
||||
clear_inference_pool()
|
||||
|
||||
if state_manager.get_item('video_memory_strategy') == 'strict':
|
||||
content_analyser.clear_inference_pool()
|
||||
for common_module in get_common_modules():
|
||||
common_module.clear_inference_pool()
|
||||
|
||||
|
||||
def colorize_frame(temp_vision_frame : VisionFrame) -> VisionFrame:
|
||||
@@ -261,6 +307,8 @@ def blend_color_frame(temp_vision_frame : VisionFrame, color_vision_frame : Visi
|
||||
return temp_vision_frame
|
||||
|
||||
|
||||
def process_frame(inputs : FrameColorizerInputs) -> VisionFrame:
|
||||
def process_frame(inputs : FrameColorizerInputs) -> ProcessorOutputs:
|
||||
temp_vision_frame = inputs.get('temp_vision_frame')
|
||||
return colorize_frame(temp_vision_frame)
|
||||
temp_vision_mask = inputs.get('temp_vision_mask')
|
||||
temp_vision_frame = colorize_frame(temp_vision_frame)
|
||||
return temp_vision_frame, temp_vision_mask
|
||||
@@ -0,0 +1,20 @@
|
||||
from facefusion.types import Locales
|
||||
|
||||
LOCALES : Locales =\
|
||||
{
|
||||
'en':
|
||||
{
|
||||
'help':
|
||||
{
|
||||
'model': 'choose the model responsible for colorizing the frame',
|
||||
'size': 'specify the frame size provided to the frame colorizer',
|
||||
'blend': 'blend the colorized into the previous frame'
|
||||
},
|
||||
'uis':
|
||||
{
|
||||
'blend_slider': 'FRAME COLORIZER BLEND',
|
||||
'model_dropdown': 'FRAME COLORIZER MODEL',
|
||||
'size_dropdown': 'FRAME COLORIZER SIZE'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
from typing import List, Literal, TypedDict
|
||||
|
||||
from facefusion.types import Mask, VisionFrame
|
||||
|
||||
FrameColorizerInputs = TypedDict('FrameColorizerInputs',
|
||||
{
|
||||
'target_vision_frames' : List[VisionFrame],
|
||||
'temp_vision_frame' : VisionFrame,
|
||||
'temp_vision_mask' : Mask
|
||||
})
|
||||
|
||||
FrameColorizerModel = Literal['ddcolor', 'ddcolor_artistic', 'deoldify', 'deoldify_artistic', 'deoldify_stable']
|
||||
@@ -0,0 +1,8 @@
|
||||
from typing import List, Sequence, get_args
|
||||
|
||||
from facefusion.common_helper import create_int_range
|
||||
from facefusion.processors.modules.frame_enhancer.types import FrameEnhancerModel
|
||||
|
||||
frame_enhancer_models : List[FrameEnhancerModel] = list(get_args(FrameEnhancerModel))
|
||||
|
||||
frame_enhancer_blend_range : Sequence[int] = create_int_range(0, 100, 1)
|
||||
+194
-34
@@ -1,22 +1,26 @@
|
||||
from argparse import ArgumentParser
|
||||
from functools import lru_cache
|
||||
from types import ModuleType
|
||||
from typing import List
|
||||
|
||||
import cv2
|
||||
import numpy
|
||||
|
||||
import facefusion.choices
|
||||
import facefusion.jobs.job_manager
|
||||
import facefusion.jobs.job_store
|
||||
from facefusion import config, content_analyser, inference_manager, logger, state_manager, video_manager, wording
|
||||
from facefusion import config, content_analyser, inference_manager, logger, state_manager, translator, video_manager
|
||||
from facefusion.common_helper import create_int_metavar, is_macos
|
||||
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
||||
from facefusion.execution import has_execution_provider
|
||||
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path, same_file_extension
|
||||
from facefusion.processors import choices as processors_choices
|
||||
from facefusion.processors.types import FrameEnhancerInputs
|
||||
from facefusion.processors.modules.frame_enhancer import choices as frame_enhancer_choices
|
||||
from facefusion.processors.modules.frame_enhancer.types import FrameEnhancerInputs
|
||||
from facefusion.processors.types import ProcessorOutputs
|
||||
from facefusion.program_helper import find_argument_group
|
||||
from facefusion.thread_helper import conditional_thread_semaphore
|
||||
from facefusion.types import ApplyStateItem, Args, DownloadScope, InferencePool, ModelOptions, ModelSet, ProcessMode, VisionFrame
|
||||
from facefusion.vision import blend_frame, create_tile_frames, merge_tile_frames, read_static_image, read_static_video_frame
|
||||
from facefusion.types import ApplyStateItem, Args, DownloadScope, InferencePool, InferenceProvider, ModelOptions, ModelSet, ProcessMode, VisionFrame
|
||||
from facefusion.vision import blend_frame, create_tile_frames, merge_tile_frames, read_static_image, read_static_video_chunk, read_static_video_frame
|
||||
|
||||
|
||||
@lru_cache()
|
||||
@@ -25,6 +29,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
{
|
||||
'clear_reality_x4':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'Kim2091',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2023
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_enhancer':
|
||||
@@ -44,22 +54,28 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
'size': (128, 8, 4),
|
||||
'scale': 4
|
||||
},
|
||||
'lsdir_x4':
|
||||
'face_dat_x4':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'Helaman',
|
||||
'license': 'CC-BY-4.0',
|
||||
'year': 2023
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_enhancer':
|
||||
{
|
||||
'url': resolve_download_url('models-3.0.0', 'lsdir_x4.hash'),
|
||||
'path': resolve_relative_path('../.assets/models/lsdir_x4.hash')
|
||||
'url': resolve_download_url('models-3.5.0', 'face_dat_x4.hash'),
|
||||
'path': resolve_relative_path('../.assets/models/face_dat_x4.hash')
|
||||
}
|
||||
},
|
||||
'sources':
|
||||
{
|
||||
'frame_enhancer':
|
||||
{
|
||||
'url': resolve_download_url('models-3.0.0', 'lsdir_x4.onnx'),
|
||||
'path': resolve_relative_path('../.assets/models/lsdir_x4.onnx')
|
||||
'url': resolve_download_url('models-3.5.0', 'face_dat_x4.onnx'),
|
||||
'path': resolve_relative_path('../.assets/models/face_dat_x4.onnx')
|
||||
}
|
||||
},
|
||||
'size': (128, 8, 4),
|
||||
@@ -67,6 +83,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'nomos8k_sc_x4':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'Phhofm',
|
||||
'license': 'CC-BY-4.0',
|
||||
'year': 2023
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_enhancer':
|
||||
@@ -88,6 +110,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'real_esrgan_x2':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'xinntao',
|
||||
'license': 'BSD-3-Clause',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_enhancer':
|
||||
@@ -109,6 +137,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'real_esrgan_x2_fp16':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'xinntao',
|
||||
'license': 'BSD-3-Clause',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_enhancer':
|
||||
@@ -125,11 +159,18 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
'path': resolve_relative_path('../.assets/models/real_esrgan_x2_fp16.onnx')
|
||||
}
|
||||
},
|
||||
'precision': 'fp16',
|
||||
'size': (256, 16, 8),
|
||||
'scale': 2
|
||||
},
|
||||
'real_esrgan_x4':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'xinntao',
|
||||
'license': 'BSD-3-Clause',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_enhancer':
|
||||
@@ -151,6 +192,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'real_esrgan_x4_fp16':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'xinntao',
|
||||
'license': 'BSD-3-Clause',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_enhancer':
|
||||
@@ -167,11 +214,18 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
'path': resolve_relative_path('../.assets/models/real_esrgan_x4_fp16.onnx')
|
||||
}
|
||||
},
|
||||
'precision': 'fp16',
|
||||
'size': (256, 16, 8),
|
||||
'scale': 4
|
||||
},
|
||||
'real_esrgan_x8':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'xinntao',
|
||||
'license': 'BSD-3-Clause',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_enhancer':
|
||||
@@ -193,6 +247,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'real_esrgan_x8_fp16':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'xinntao',
|
||||
'license': 'BSD-3-Clause',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_enhancer':
|
||||
@@ -209,11 +269,18 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
'path': resolve_relative_path('../.assets/models/real_esrgan_x8_fp16.onnx')
|
||||
}
|
||||
},
|
||||
'precision': 'fp16',
|
||||
'size': (256, 16, 8),
|
||||
'scale': 8
|
||||
},
|
||||
'real_hatgan_x4':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'XPixelGroup',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2023
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_enhancer':
|
||||
@@ -235,6 +302,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'real_web_photo_x4':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'Helaman',
|
||||
'license': 'CC-BY-4.0',
|
||||
'year': 2024
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_enhancer':
|
||||
@@ -256,6 +329,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'realistic_rescaler_x4':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'Mutin Choler',
|
||||
'license': 'WTFPL',
|
||||
'year': 2023
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_enhancer':
|
||||
@@ -277,6 +356,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'remacri_x4':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'FoolhardyVEVO',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_enhancer':
|
||||
@@ -298,6 +383,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'siax_x4':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'NMKD',
|
||||
'license': 'WTFPL',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_enhancer':
|
||||
@@ -319,6 +410,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'span_kendata_x4':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'terrainer',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2024
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_enhancer':
|
||||
@@ -340,6 +437,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'swin2_sr_x4':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'mv-lab',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2022
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_enhancer':
|
||||
@@ -359,8 +462,41 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
'size': (128, 8, 4),
|
||||
'scale': 4
|
||||
},
|
||||
'tghq_face_x8':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'TorrentGuy',
|
||||
'license': 'GPL-3.0',
|
||||
'year': 2019
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_enhancer':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'tghq_face_x8.hash'),
|
||||
'path': resolve_relative_path('../.assets/models/tghq_face_x8.hash')
|
||||
}
|
||||
},
|
||||
'sources':
|
||||
{
|
||||
'frame_enhancer':
|
||||
{
|
||||
'url': resolve_download_url('models-3.5.0', 'tghq_face_x8.onnx'),
|
||||
'path': resolve_relative_path('../.assets/models/tghq_face_x8.onnx')
|
||||
}
|
||||
},
|
||||
'size': (128, 8, 4),
|
||||
'scale': 8
|
||||
},
|
||||
'ultra_sharp_x4':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'Kim2091',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2021
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_enhancer':
|
||||
@@ -382,6 +518,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'ultra_sharp_2_x4':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'Kim2091',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2025
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'frame_enhancer':
|
||||
@@ -405,40 +547,43 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
|
||||
|
||||
def get_inference_pool() -> InferencePool:
|
||||
model_names = [ get_frame_enhancer_model() ]
|
||||
model_names = [ state_manager.get_item('frame_enhancer_model') ]
|
||||
model_source_set = get_model_options().get('sources')
|
||||
|
||||
return inference_manager.get_inference_pool(__name__, model_names, model_source_set)
|
||||
|
||||
|
||||
def clear_inference_pool() -> None:
|
||||
model_names = [ get_frame_enhancer_model() ]
|
||||
model_names = [ state_manager.get_item('frame_enhancer_model') ]
|
||||
inference_manager.clear_inference_pool(__name__, model_names)
|
||||
|
||||
|
||||
def resolve_inference_providers() -> List[InferenceProvider]:
|
||||
model_precision = get_model_options().get('precision')
|
||||
|
||||
if is_macos() and has_execution_provider('coreml') and model_precision == 'fp16':
|
||||
return\
|
||||
[
|
||||
(facefusion.choices.execution_provider_set.get('coreml'),
|
||||
{
|
||||
'ModelFormat': 'MLProgram',
|
||||
'SpecializationStrategy': 'FastPrediction'
|
||||
})
|
||||
]
|
||||
|
||||
return []
|
||||
|
||||
|
||||
def get_model_options() -> ModelOptions:
|
||||
model_name = get_frame_enhancer_model()
|
||||
model_name = state_manager.get_item('frame_enhancer_model')
|
||||
return create_static_model_set('full').get(model_name)
|
||||
|
||||
|
||||
def get_frame_enhancer_model() -> str:
|
||||
frame_enhancer_model = state_manager.get_item('frame_enhancer_model')
|
||||
|
||||
if is_macos() and has_execution_provider('coreml'):
|
||||
if frame_enhancer_model == 'real_esrgan_x2_fp16':
|
||||
return 'real_esrgan_x2'
|
||||
if frame_enhancer_model == 'real_esrgan_x4_fp16':
|
||||
return 'real_esrgan_x4'
|
||||
if frame_enhancer_model == 'real_esrgan_x8_fp16':
|
||||
return 'real_esrgan_x8'
|
||||
return frame_enhancer_model
|
||||
|
||||
|
||||
def register_args(program : ArgumentParser) -> None:
|
||||
group_processors = find_argument_group(program, 'processors')
|
||||
if group_processors:
|
||||
group_processors.add_argument('--frame-enhancer-model', help = wording.get('help.frame_enhancer_model'), default = config.get_str_value('processors', 'frame_enhancer_model', 'span_kendata_x4'), choices = processors_choices.frame_enhancer_models)
|
||||
group_processors.add_argument('--frame-enhancer-blend', help = wording.get('help.frame_enhancer_blend'), type = int, default = config.get_int_value('processors', 'frame_enhancer_blend', '80'), choices = processors_choices.frame_enhancer_blend_range, metavar = create_int_metavar(processors_choices.frame_enhancer_blend_range))
|
||||
group_processors.add_argument('--frame-enhancer-model', help = translator.get('help.model', __package__), default = config.get_str_value('processors', 'frame_enhancer_model', 'span_kendata_x4'), choices = frame_enhancer_choices.frame_enhancer_models)
|
||||
group_processors.add_argument('--frame-enhancer-blend', help = translator.get('help.blend', __package__), type = int, default = config.get_int_value('processors', 'frame_enhancer_blend', '80'), choices = frame_enhancer_choices.frame_enhancer_blend_range, metavar = create_int_metavar(frame_enhancer_choices.frame_enhancer_blend_range))
|
||||
facefusion.jobs.job_store.register_step_keys([ 'frame_enhancer_model', 'frame_enhancer_blend' ])
|
||||
|
||||
|
||||
@@ -447,22 +592,30 @@ def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
|
||||
apply_state_item('frame_enhancer_blend', args.get('frame_enhancer_blend'))
|
||||
|
||||
|
||||
def get_common_modules() -> List[ModuleType]:
|
||||
return [ content_analyser ]
|
||||
|
||||
|
||||
def pre_check() -> bool:
|
||||
model_hash_set = get_model_options().get('hashes')
|
||||
model_source_set = get_model_options().get('sources')
|
||||
|
||||
for common_module in get_common_modules():
|
||||
if not common_module.pre_check():
|
||||
return False
|
||||
|
||||
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
||||
|
||||
|
||||
def pre_process(mode : ProcessMode) -> bool:
|
||||
if mode in [ 'output', 'preview' ] and not is_image(state_manager.get_item('target_path')) and not is_video(state_manager.get_item('target_path')):
|
||||
logger.error(wording.get('choose_image_or_video_target') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('choose_image_or_video_target') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
if mode == 'output' and not in_directory(state_manager.get_item('output_path')):
|
||||
logger.error(wording.get('specify_image_or_video_output') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('specify_image_or_video_output') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
if mode == 'output' and not same_file_extension(state_manager.get_item('target_path'), state_manager.get_item('output_path')):
|
||||
logger.error(wording.get('match_target_and_output_extension') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('match_target_and_output_extension') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -470,11 +623,15 @@ def pre_process(mode : ProcessMode) -> bool:
|
||||
def post_process() -> None:
|
||||
read_static_image.cache_clear()
|
||||
read_static_video_frame.cache_clear()
|
||||
read_static_video_chunk.cache_clear()
|
||||
video_manager.clear_video_pool()
|
||||
|
||||
if state_manager.get_item('video_memory_strategy') in [ 'strict', 'moderate' ]:
|
||||
clear_inference_pool()
|
||||
|
||||
if state_manager.get_item('video_memory_strategy') == 'strict':
|
||||
content_analyser.clear_inference_pool()
|
||||
for common_module in get_common_modules():
|
||||
common_module.clear_inference_pool()
|
||||
|
||||
|
||||
def enhance_frame(temp_vision_frame : VisionFrame) -> VisionFrame:
|
||||
@@ -525,6 +682,9 @@ def blend_merge_frame(temp_vision_frame : VisionFrame, merge_vision_frame : Visi
|
||||
return temp_vision_frame
|
||||
|
||||
|
||||
def process_frame(inputs : FrameEnhancerInputs) -> VisionFrame:
|
||||
def process_frame(inputs : FrameEnhancerInputs) -> ProcessorOutputs:
|
||||
temp_vision_frame = inputs.get('temp_vision_frame')
|
||||
return enhance_frame(temp_vision_frame)
|
||||
temp_vision_mask = inputs.get('temp_vision_mask')
|
||||
temp_vision_frame = enhance_frame(temp_vision_frame)
|
||||
temp_vision_mask = cv2.resize(temp_vision_mask, temp_vision_frame.shape[:2][::-1])
|
||||
return temp_vision_frame, temp_vision_mask
|
||||
@@ -0,0 +1,18 @@
|
||||
from facefusion.types import Locales
|
||||
|
||||
LOCALES : Locales =\
|
||||
{
|
||||
'en':
|
||||
{
|
||||
'help':
|
||||
{
|
||||
'model': 'choose the model responsible for enhancing the frame',
|
||||
'blend': 'blend the enhanced into the previous frame'
|
||||
},
|
||||
'uis':
|
||||
{
|
||||
'blend_slider': 'FRAME ENHANCER BLEND',
|
||||
'model_dropdown': 'FRAME ENHANCER MODEL'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
from typing import List, Literal, TypedDict
|
||||
|
||||
from facefusion.types import Mask, VisionFrame
|
||||
|
||||
FrameEnhancerInputs = TypedDict('FrameEnhancerInputs',
|
||||
{
|
||||
'target_vision_frames' : List[VisionFrame],
|
||||
'temp_vision_frame' : VisionFrame,
|
||||
'temp_vision_mask' : Mask
|
||||
})
|
||||
|
||||
FrameEnhancerModel = Literal['clear_reality_x4', 'face_dat_x4', 'lsdir_x4', 'nomos8k_sc_x4', 'real_esrgan_x2', 'real_esrgan_x2_fp16', 'real_esrgan_x4', 'real_esrgan_x4_fp16', 'real_esrgan_x8', 'real_esrgan_x8_fp16', 'real_hatgan_x4', 'real_web_photo_x4', 'realistic_rescaler_x4', 'remacri_x4', 'siax_x4', 'span_kendata_x4', 'swin2_sr_x4', 'tghq_face_x8', 'ultra_sharp_x4', 'ultra_sharp_2_x4']
|
||||
@@ -0,0 +1,8 @@
|
||||
from typing import List, Sequence, get_args
|
||||
|
||||
from facefusion.common_helper import create_float_range
|
||||
from facefusion.processors.modules.lip_syncer.types import LipSyncerModel
|
||||
|
||||
lip_syncer_models : List[LipSyncerModel] = list(get_args(LipSyncerModel))
|
||||
|
||||
lip_syncer_weight_range : Sequence[float] = create_float_range(0.0, 1.0, 0.05)
|
||||
+52
-20
@@ -1,25 +1,29 @@
|
||||
from argparse import ArgumentParser
|
||||
from functools import lru_cache
|
||||
from types import ModuleType
|
||||
from typing import List
|
||||
|
||||
import cv2
|
||||
import numpy
|
||||
|
||||
import facefusion.jobs.job_manager
|
||||
import facefusion.jobs.job_store
|
||||
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, inference_manager, logger, state_manager, video_manager, voice_extractor, wording
|
||||
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, inference_manager, logger, state_manager, translator, video_manager, voice_extractor
|
||||
from facefusion.audio import read_static_voice
|
||||
from facefusion.common_helper import create_float_metavar
|
||||
from facefusion.common_helper import create_float_metavar, get_middle
|
||||
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
||||
from facefusion.face_creator import scale_face
|
||||
from facefusion.face_helper import create_bounding_box, paste_back, warp_face_by_bounding_box, warp_face_by_face_landmark_5
|
||||
from facefusion.face_masker import create_area_mask, create_box_mask, create_occlusion_mask
|
||||
from facefusion.face_selector import select_faces
|
||||
from facefusion.filesystem import has_audio, resolve_relative_path
|
||||
from facefusion.processors import choices as processors_choices
|
||||
from facefusion.processors.types import LipSyncerInputs, LipSyncerWeight
|
||||
from facefusion.processors.modules.lip_syncer import choices as lip_syncer_choices
|
||||
from facefusion.processors.modules.lip_syncer.types import LipSyncerInputs, LipSyncerWeight
|
||||
from facefusion.processors.types import ProcessorOutputs
|
||||
from facefusion.program_helper import find_argument_group
|
||||
from facefusion.thread_helper import conditional_thread_semaphore
|
||||
from facefusion.types import ApplyStateItem, Args, AudioFrame, DownloadScope, Face, InferencePool, ModelOptions, ModelSet, ProcessMode, VisionFrame
|
||||
from facefusion.vision import read_static_image, read_static_video_frame
|
||||
from facefusion.vision import read_static_image, read_static_video_chunk, read_static_video_frame
|
||||
|
||||
|
||||
@lru_cache()
|
||||
@@ -28,6 +32,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
{
|
||||
'edtalk_256':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'tanshuai0219',
|
||||
'license': 'Apache-2.0',
|
||||
'year': 2024
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'lip_syncer':
|
||||
@@ -49,6 +59,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'wav2lip_96':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'Rudrabha',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2020
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'lip_syncer':
|
||||
@@ -70,6 +86,12 @@ def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
||||
},
|
||||
'wav2lip_gan_96':
|
||||
{
|
||||
'__metadata__':
|
||||
{
|
||||
'vendor': 'Rudrabha',
|
||||
'license': 'Non-Commercial',
|
||||
'year': 2020
|
||||
},
|
||||
'hashes':
|
||||
{
|
||||
'lip_syncer':
|
||||
@@ -112,8 +134,8 @@ def get_model_options() -> ModelOptions:
|
||||
def register_args(program : ArgumentParser) -> None:
|
||||
group_processors = find_argument_group(program, 'processors')
|
||||
if group_processors:
|
||||
group_processors.add_argument('--lip-syncer-model', help = wording.get('help.lip_syncer_model'), default = config.get_str_value('processors', 'lip_syncer_model', 'wav2lip_gan_96'), choices = processors_choices.lip_syncer_models)
|
||||
group_processors.add_argument('--lip-syncer-weight', help = wording.get('help.lip_syncer_weight'), type = float, default = config.get_float_value('processors', 'lip_syncer_weight', '0.5'), choices = processors_choices.lip_syncer_weight_range, metavar = create_float_metavar(processors_choices.lip_syncer_weight_range))
|
||||
group_processors.add_argument('--lip-syncer-model', help = translator.get('help.model', __package__), default = config.get_str_value('processors', 'lip_syncer_model', 'wav2lip_gan_96'), choices = lip_syncer_choices.lip_syncer_models)
|
||||
group_processors.add_argument('--lip-syncer-weight', help = translator.get('help.weight', __package__), type = float, default = config.get_float_value('processors', 'lip_syncer_weight', '0.5'), choices = lip_syncer_choices.lip_syncer_weight_range, metavar = create_float_metavar(lip_syncer_choices.lip_syncer_weight_range))
|
||||
facefusion.jobs.job_store.register_step_keys([ 'lip_syncer_model', 'lip_syncer_weight' ])
|
||||
|
||||
|
||||
@@ -122,16 +144,24 @@ def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
|
||||
apply_state_item('lip_syncer_weight', args.get('lip_syncer_weight'))
|
||||
|
||||
|
||||
def get_common_modules() -> List[ModuleType]:
|
||||
return [ content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, voice_extractor ]
|
||||
|
||||
|
||||
def pre_check() -> bool:
|
||||
model_hash_set = get_model_options().get('hashes')
|
||||
model_source_set = get_model_options().get('sources')
|
||||
|
||||
for common_module in get_common_modules():
|
||||
if not common_module.pre_check():
|
||||
return False
|
||||
|
||||
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
||||
|
||||
|
||||
def pre_process(mode : ProcessMode) -> bool:
|
||||
if not has_audio(state_manager.get_item('source_paths')):
|
||||
logger.error(wording.get('choose_audio_source') + wording.get('exclamation_mark'), __name__)
|
||||
logger.error(translator.get('choose_audio_source') + translator.get('exclamation_mark'), __name__)
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -139,18 +169,16 @@ def pre_process(mode : ProcessMode) -> bool:
|
||||
def post_process() -> None:
|
||||
read_static_image.cache_clear()
|
||||
read_static_video_frame.cache_clear()
|
||||
read_static_video_chunk.cache_clear()
|
||||
read_static_voice.cache_clear()
|
||||
video_manager.clear_video_pool()
|
||||
|
||||
if state_manager.get_item('video_memory_strategy') in [ 'strict', 'moderate' ]:
|
||||
clear_inference_pool()
|
||||
|
||||
if state_manager.get_item('video_memory_strategy') == 'strict':
|
||||
content_analyser.clear_inference_pool()
|
||||
face_classifier.clear_inference_pool()
|
||||
face_detector.clear_inference_pool()
|
||||
face_landmarker.clear_inference_pool()
|
||||
face_masker.clear_inference_pool()
|
||||
face_recognizer.clear_inference_pool()
|
||||
voice_extractor.clear_inference_pool()
|
||||
for common_module in get_common_modules():
|
||||
common_module.clear_inference_pool()
|
||||
|
||||
|
||||
def sync_lip(target_face : Face, source_voice_frame : AudioFrame, temp_vision_frame : VisionFrame) -> VisionFrame:
|
||||
@@ -260,16 +288,20 @@ def normalize_crop_frame(crop_vision_frame : VisionFrame) -> VisionFrame:
|
||||
return crop_vision_frame
|
||||
|
||||
|
||||
def process_frame(inputs : LipSyncerInputs) -> VisionFrame:
|
||||
def process_frame(inputs : LipSyncerInputs) -> ProcessorOutputs:
|
||||
reference_vision_frame = inputs.get('reference_vision_frame')
|
||||
source_vision_frames = inputs.get('source_vision_frames')
|
||||
source_voice_frame = inputs.get('source_voice_frame')
|
||||
target_vision_frame = inputs.get('target_vision_frame')
|
||||
target_vision_frames = inputs.get('target_vision_frames')
|
||||
temp_vision_frame = inputs.get('temp_vision_frame')
|
||||
target_faces = select_faces(reference_vision_frame, target_vision_frame)
|
||||
temp_vision_mask = inputs.get('temp_vision_mask')
|
||||
|
||||
target_vision_frame = get_middle(target_vision_frames)
|
||||
target_faces = select_faces(reference_vision_frame, source_vision_frames, target_vision_frames)
|
||||
|
||||
if target_faces:
|
||||
for target_face in target_faces:
|
||||
target_face = scale_face(target_face, target_vision_frame, temp_vision_frame)
|
||||
temp_vision_frame = sync_lip(target_face, source_voice_frame, temp_vision_frame)
|
||||
|
||||
return temp_vision_frame
|
||||
|
||||
return temp_vision_frame, temp_vision_mask
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user