Files
facefusion/facefusion/processors/modules/frame_enhancer.py
T
da0da3a4b4 Next (#945)
* Rename calcXXX to calculateXXX

* Add migraphx support

* Add migraphx support

* Add migraphx support

* Add migraphx support

* Add migraphx support

* Add migraphx support

* Use True for the flags

* Add migraphx support

* add face-swapper-weight

* add face-swapper-weight to facefusion.ini

* changes

* change choice

* Fix typing for xxxWeight

* Feat/log inference session (#906)

* Log inference session, Introduce time helper

* Log inference session, Introduce time helper

* Log inference session, Introduce time helper

* Log inference session, Introduce time helper

* Mark as NEXT

* Follow industry standard x1, x2, y1 and y2

* Follow industry standard x1, x2, y1 and y2

* Follow industry standard in terms of naming (#908)

* Follow industry standard in terms of naming

* Improve xxx_embedding naming

* Fix norm vs. norms

* Reduce timeout to 5

* Sort out voice_extractor once again

* changes

* Introduce many to the occlusion mask (#910)

* Introduce many to the occlusion mask

* Then we use minimum

* Add support for wmv

* Run platform tests before has_execution_provider (#911)

* Add support for wmv

* Introduce benchmark mode (#912)

* Honestly makes no difference to me

* Honestly makes no difference to me

* Fix wording

* Bring back YuNet (#922)

* Reintroduce YuNet without cv2 dependency

* Fix variable naming

* Avoid RGB to YUV colorshift using libx264rgb

* Avoid RGB to YUV colorshift using libx264rgb

* Make libx264 the default again

* Make libx264 the default again

* Fix types in ffmpeg builder

* Fix quality stuff in ffmpeg builder

* Fix quality stuff in ffmpeg builder

* Add libx264rgb to test

* Revamp Processors (#923)

* Introduce new concept of pure target frames

* Radical refactoring of process flow

* Introduce new concept of pure target frames

* Fix webcam

* Minor improvements

* Minor improvements

* Use deque for video processing

* Use deque for video processing

* Extend the video manager

* Polish deque

* Polish deque

* Deque is not even used

* Improve speed with multiple futures

* Fix temp frame mutation and

* Fix RAM usage

* Remove old types and manage method

* Remove execution_queue_count

* Use init_state for benchmarker to avoid issues

* add voice extractor option

* Change the order of voice extractor in code

* Use official download urls

* Use official download urls

* add gui

* fix preview

* Add remote updates for voice extractor

* fix crash on headless-run

* update test_job_helper.py

* Fix it for good

* Remove pointless method

* Fix types and unused imports

* Revamp reference (#925)

* Initial revamp of face references

* Initial revamp of face references

* Initial revamp of face references

* Terminate find_similar_faces

* Improve find mutant faces

* Improve find mutant faces

* Move sort where it belongs

* Forward reference vision frame

* Forward reference vision frame also in preview

* Fix reference selection

* Use static video frame

* Fix CI

* Remove reference type from frame processors

* Improve some naming

* Fix types and unused imports

* Fix find mutant faces

* Fix find mutant faces

* Fix imports

* Correct naming

* Correct naming

* simplify pad

* Improve webcam performance on highres

* Camera manager (#932)

* Introduce webcam manager

* Fix order

* Rename to camera manager, improve video manager

* Fix CI

* Remove optional

* Fix naming in webcam options

* Avoid using temp faces (#933)

* output video scale

* Fix imports

* output image scale

* upscale fix (not limiter)

* add unit test scale_resolution & remove unused methods

* fix and add test

* fix

* change pack_resolution

* fix tests

* Simplify output scale testing

* Fix benchmark UI

* Fix benchmark UI

* Update dependencies

* Introduce REAL multi gpu support using multi dimensional inference pool (#935)

* Introduce REAL multi gpu support using multi dimensional inference pool

* Remove the MULTI:GPU flag

* Restore "processing stop"

* Restore "processing stop"

* Remove old templates

* Go fill in with caching

* add expression restorer areas

* re-arrange

* rename method

* Fix stop for extract frames and merge video

* Replace arcface_converter models with latest crossface models

* Replace arcface_converter models with latest crossface models

* Move module logs to debug mode

* Refactor/streamer (#938)

* Introduce webcam manager

* Fix order

* Rename to camera manager, improve video manager

* Fix CI

* Fix naming in webcam options

* Move logic over to streamer

* Fix streamer, improve webcam experience

* Improve webcam experience

* Revert method

* Revert method

* Improve webcam again

* Use release on capture instead

* Only forward valid frames

* Fix resolution logging

* Add AVIF support

* Add AVIF support

* Limit avif to unix systems

* Drop avif

* Drop avif

* Drop avif

* Default to Documents in the UI if output path is not set

* Update wording.py (#939)

"succeed" is grammatically incorrect in the given context. To succeed is the infinitive form of the verb. Correct would be either "succeeded" or alternatively a form involving the noun "success".

* Fix more grammar issue

* Fix more grammar issue

* Sort out caching

* Move webcam choices back to UI

* Move preview options to own file (#940)

* Fix Migraphx execution provider

* Fix benchmark

* Reuse blend frame method

* Fix CI

* Fix CI

* Fix CI

* Hotfix missing check in face debugger, Enable logger for preview

* Fix reference selection (#942)

* Fix reference selection

* Fix reference selection

* Fix reference selection

* Fix reference selection

* Side by side preview (#941)

* Initial side by side preview

* More work on preview, remove UI only stuff from vision.py

* Improve more

* Use fit frame

* Add different fit methods for vision

* Improve preview part2

* Improve preview part3

* Improve preview part4

* Remove none as choice

* Remove useless methods

* Fix CI

* Fix naming

* use 1024 as preview resolution default

* Fix fit_cover_frame

* Uniform fit_xxx_frame methods

* Add back disabled logger

* Use ui choices alias

* Extract select face logic from processors (#943)

* Extract select face logic from processors to use it for face by face in preview

* Fix order

* Remove old code

* Merge methods

* Refactor face debugger (#944)

* Refactor huge method of face debugger

* Remove text metrics from face debugger

* Remove useless copy of temp frame

* Resort methods

* Fix spacing

* Remove old method

* Fix hard exit to work without signals

* Prevent upscaling for face-by-face

* Switch to version

* Improve exiting

---------

Co-authored-by: harisreedhar <h4harisreedhar.s.s@gmail.com>
Co-authored-by: Harisreedhar <46858047+harisreedhar@users.noreply.github.com>
Co-authored-by: Rafael Tappe Maestro <rafael@tappemaestro.com>
2025-09-08 10:43:58 +02:00

531 lines
15 KiB
Python

from argparse import ArgumentParser
from functools import lru_cache
import cv2
import numpy
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.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.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
@lru_cache()
def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
return\
{
'clear_reality_x4':
{
'hashes':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'clear_reality_x4.hash'),
'path': resolve_relative_path('../.assets/models/clear_reality_x4.hash')
}
},
'sources':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'clear_reality_x4.onnx'),
'path': resolve_relative_path('../.assets/models/clear_reality_x4.onnx')
}
},
'size': (128, 8, 4),
'scale': 4
},
'lsdir_x4':
{
'hashes':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'lsdir_x4.hash'),
'path': resolve_relative_path('../.assets/models/lsdir_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')
}
},
'size': (128, 8, 4),
'scale': 4
},
'nomos8k_sc_x4':
{
'hashes':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'nomos8k_sc_x4.hash'),
'path': resolve_relative_path('../.assets/models/nomos8k_sc_x4.hash')
}
},
'sources':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'nomos8k_sc_x4.onnx'),
'path': resolve_relative_path('../.assets/models/nomos8k_sc_x4.onnx')
}
},
'size': (128, 8, 4),
'scale': 4
},
'real_esrgan_x2':
{
'hashes':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'real_esrgan_x2.hash'),
'path': resolve_relative_path('../.assets/models/real_esrgan_x2.hash')
}
},
'sources':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'real_esrgan_x2.onnx'),
'path': resolve_relative_path('../.assets/models/real_esrgan_x2.onnx')
}
},
'size': (256, 16, 8),
'scale': 2
},
'real_esrgan_x2_fp16':
{
'hashes':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'real_esrgan_x2_fp16.hash'),
'path': resolve_relative_path('../.assets/models/real_esrgan_x2_fp16.hash')
}
},
'sources':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'real_esrgan_x2_fp16.onnx'),
'path': resolve_relative_path('../.assets/models/real_esrgan_x2_fp16.onnx')
}
},
'size': (256, 16, 8),
'scale': 2
},
'real_esrgan_x4':
{
'hashes':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'real_esrgan_x4.hash'),
'path': resolve_relative_path('../.assets/models/real_esrgan_x4.hash')
}
},
'sources':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'real_esrgan_x4.onnx'),
'path': resolve_relative_path('../.assets/models/real_esrgan_x4.onnx')
}
},
'size': (256, 16, 8),
'scale': 4
},
'real_esrgan_x4_fp16':
{
'hashes':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'real_esrgan_x4_fp16.hash'),
'path': resolve_relative_path('../.assets/models/real_esrgan_x4_fp16.hash')
}
},
'sources':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'real_esrgan_x4_fp16.onnx'),
'path': resolve_relative_path('../.assets/models/real_esrgan_x4_fp16.onnx')
}
},
'size': (256, 16, 8),
'scale': 4
},
'real_esrgan_x8':
{
'hashes':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'real_esrgan_x8.hash'),
'path': resolve_relative_path('../.assets/models/real_esrgan_x8.hash')
}
},
'sources':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'real_esrgan_x8.onnx'),
'path': resolve_relative_path('../.assets/models/real_esrgan_x8.onnx')
}
},
'size': (256, 16, 8),
'scale': 8
},
'real_esrgan_x8_fp16':
{
'hashes':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'real_esrgan_x8_fp16.hash'),
'path': resolve_relative_path('../.assets/models/real_esrgan_x8_fp16.hash')
}
},
'sources':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'real_esrgan_x8_fp16.onnx'),
'path': resolve_relative_path('../.assets/models/real_esrgan_x8_fp16.onnx')
}
},
'size': (256, 16, 8),
'scale': 8
},
'real_hatgan_x4':
{
'hashes':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'real_hatgan_x4.hash'),
'path': resolve_relative_path('../.assets/models/real_hatgan_x4.hash')
}
},
'sources':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'real_hatgan_x4.onnx'),
'path': resolve_relative_path('../.assets/models/real_hatgan_x4.onnx')
}
},
'size': (256, 16, 8),
'scale': 4
},
'real_web_photo_x4':
{
'hashes':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.1.0', 'real_web_photo_x4.hash'),
'path': resolve_relative_path('../.assets/models/real_web_photo_x4.hash')
}
},
'sources':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.1.0', 'real_web_photo_x4.onnx'),
'path': resolve_relative_path('../.assets/models/real_web_photo_x4.onnx')
}
},
'size': (64, 4, 2),
'scale': 4
},
'realistic_rescaler_x4':
{
'hashes':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.1.0', 'realistic_rescaler_x4.hash'),
'path': resolve_relative_path('../.assets/models/realistic_rescaler_x4.hash')
}
},
'sources':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.1.0', 'realistic_rescaler_x4.onnx'),
'path': resolve_relative_path('../.assets/models/realistic_rescaler_x4.onnx')
}
},
'size': (128, 8, 4),
'scale': 4
},
'remacri_x4':
{
'hashes':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.1.0', 'remacri_x4.hash'),
'path': resolve_relative_path('../.assets/models/remacri_x4.hash')
}
},
'sources':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.1.0', 'remacri_x4.onnx'),
'path': resolve_relative_path('../.assets/models/remacri_x4.onnx')
}
},
'size': (128, 8, 4),
'scale': 4
},
'siax_x4':
{
'hashes':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.1.0', 'siax_x4.hash'),
'path': resolve_relative_path('../.assets/models/siax_x4.hash')
}
},
'sources':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.1.0', 'siax_x4.onnx'),
'path': resolve_relative_path('../.assets/models/siax_x4.onnx')
}
},
'size': (128, 8, 4),
'scale': 4
},
'span_kendata_x4':
{
'hashes':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'span_kendata_x4.hash'),
'path': resolve_relative_path('../.assets/models/span_kendata_x4.hash')
}
},
'sources':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'span_kendata_x4.onnx'),
'path': resolve_relative_path('../.assets/models/span_kendata_x4.onnx')
}
},
'size': (128, 8, 4),
'scale': 4
},
'swin2_sr_x4':
{
'hashes':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.1.0', 'swin2_sr_x4.hash'),
'path': resolve_relative_path('../.assets/models/swin2_sr_x4.hash')
}
},
'sources':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.1.0', 'swin2_sr_x4.onnx'),
'path': resolve_relative_path('../.assets/models/swin2_sr_x4.onnx')
}
},
'size': (128, 8, 4),
'scale': 4
},
'ultra_sharp_x4':
{
'hashes':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'ultra_sharp_x4.hash'),
'path': resolve_relative_path('../.assets/models/ultra_sharp_x4.hash')
}
},
'sources':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.0.0', 'ultra_sharp_x4.onnx'),
'path': resolve_relative_path('../.assets/models/ultra_sharp_x4.onnx')
}
},
'size': (128, 8, 4),
'scale': 4
},
'ultra_sharp_2_x4':
{
'hashes':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.3.0', 'ultra_sharp_2_x4.hash'),
'path': resolve_relative_path('../.assets/models/ultra_sharp_2_x4.hash')
}
},
'sources':
{
'frame_enhancer':
{
'url': resolve_download_url('models-3.3.0', 'ultra_sharp_2_x4.onnx'),
'path': resolve_relative_path('../.assets/models/ultra_sharp_2_x4.onnx')
}
},
'size': (1024, 64, 32),
'scale': 4
}
}
def get_inference_pool() -> InferencePool:
model_names = [ get_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() ]
inference_manager.clear_inference_pool(__name__, model_names)
def get_model_options() -> ModelOptions:
model_name = get_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))
facefusion.jobs.job_store.register_step_keys([ 'frame_enhancer_model', 'frame_enhancer_blend' ])
def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
apply_state_item('frame_enhancer_model', args.get('frame_enhancer_model'))
apply_state_item('frame_enhancer_blend', args.get('frame_enhancer_blend'))
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()
def enhance_frame(temp_vision_frame : VisionFrame) -> VisionFrame:
model_size = get_model_options().get('size')
model_scale = get_model_options().get('scale')
temp_height, temp_width = temp_vision_frame.shape[:2]
tile_vision_frames, pad_width, pad_height = create_tile_frames(temp_vision_frame, model_size)
for index, tile_vision_frame in enumerate(tile_vision_frames):
tile_vision_frame = prepare_tile_frame(tile_vision_frame)
tile_vision_frame = forward(tile_vision_frame)
tile_vision_frames[index] = normalize_tile_frame(tile_vision_frame)
merge_vision_frame = merge_tile_frames(tile_vision_frames, temp_width * model_scale, temp_height * model_scale, pad_width * model_scale, pad_height * model_scale, (model_size[0] * model_scale, model_size[1] * model_scale, model_size[2] * model_scale))
temp_vision_frame = blend_merge_frame(temp_vision_frame, merge_vision_frame)
return temp_vision_frame
def forward(tile_vision_frame : VisionFrame) -> VisionFrame:
frame_enhancer = get_inference_pool().get('frame_enhancer')
with conditional_thread_semaphore():
tile_vision_frame = frame_enhancer.run(None,
{
'input': tile_vision_frame
})[0]
return tile_vision_frame
def prepare_tile_frame(tile_vision_frame : VisionFrame) -> VisionFrame:
tile_vision_frame = numpy.expand_dims(tile_vision_frame[:, :, ::-1], axis = 0)
tile_vision_frame = tile_vision_frame.transpose(0, 3, 1, 2)
tile_vision_frame = tile_vision_frame.astype(numpy.float32) / 255.0
return tile_vision_frame
def normalize_tile_frame(tile_vision_frame : VisionFrame) -> VisionFrame:
tile_vision_frame = tile_vision_frame.transpose(0, 2, 3, 1).squeeze(0) * 255
tile_vision_frame = tile_vision_frame.clip(0, 255).astype(numpy.uint8)[:, :, ::-1]
return tile_vision_frame
def blend_merge_frame(temp_vision_frame : VisionFrame, merge_vision_frame : VisionFrame) -> VisionFrame:
frame_enhancer_blend = 1 - (state_manager.get_item('frame_enhancer_blend') / 100)
temp_vision_frame = cv2.resize(temp_vision_frame, (merge_vision_frame.shape[1], merge_vision_frame.shape[0]))
temp_vision_frame = blend_frame(temp_vision_frame, merge_vision_frame, 1 - frame_enhancer_blend)
return temp_vision_frame
def process_frame(inputs : FrameEnhancerInputs) -> VisionFrame:
temp_vision_frame = inputs.get('temp_vision_frame')
return enhance_frame(temp_vision_frame)