Spaces:
Running
Running
Upload folder using huggingface_hub
#1
by imseldrith - opened
This view is limited to 50 files because it contains too many changes. See the raw diff here.
Files changed (50)
- .assets/models/GFPGANv1.4.pthAdded+3
- .assets/models/RealESRGAN_x4plus.pthAdded+3
- .assets/models/inswapper_128.onnxAdded+3
- .editorconfigAdded+8
- .flake8Added+3
- .gitattributes+1
- .github/FUNDING.ymlAdded+2
- .github/preview.pngAdded
- .github/workflows/ci.ymlAdded+34
- .gitignoreAdded+4
- 1685074910001_vtqikl_2_0-boy-dp-image-77-720x704.jpgAdded
- 1685074910001_vtqikl_2_0-images 2.jpegAdded
- 1685074910001_vtqikl_2_0-images.jpgAdded
- DeepFakeAI/__init__.pyAdded
- DeepFakeAI/__pycache__/__init__.cpython-310.pycAdded
- DeepFakeAI/__pycache__/capturer.cpython-310.pycAdded
- DeepFakeAI/__pycache__/choices.cpython-310.pycAdded
- DeepFakeAI/__pycache__/core.cpython-310.pycAdded
- DeepFakeAI/__pycache__/face_analyser.cpython-310.pycAdded
- DeepFakeAI/__pycache__/face_reference.cpython-310.pycAdded
- DeepFakeAI/__pycache__/globals.cpython-310.pycAdded
- DeepFakeAI/__pycache__/metadata.cpython-310.pycAdded
- DeepFakeAI/__pycache__/predictor.cpython-310.pycAdded
- DeepFakeAI/__pycache__/typing.cpython-310.pycAdded
- DeepFakeAI/__pycache__/utilities.cpython-310.pycAdded
- DeepFakeAI/__pycache__/wording.cpython-310.pycAdded
- DeepFakeAI/capturer.pyAdded+22
- DeepFakeAI/choices.pyAdded+10
- DeepFakeAI/core.pyAdded+222
- DeepFakeAI/face_analyser.pyAdded+106
- DeepFakeAI/face_reference.pyAdded+21
- DeepFakeAI/globals.pyAdded+30
- DeepFakeAI/metadata.pyAdded+13
- DeepFakeAI/predictor.pyAdded+43
- DeepFakeAI/processors/__init__.pyAdded
- DeepFakeAI/processors/__pycache__/__init__.cpython-310.pycAdded
- DeepFakeAI/processors/frame/__init__.pyAdded
- DeepFakeAI/processors/frame/__pycache__/__init__.cpython-310.pycAdded
- DeepFakeAI/processors/frame/__pycache__/core.cpython-310.pycAdded
- DeepFakeAI/processors/frame/core.pyAdded+113
- DeepFakeAI/processors/frame/modules/__init__.pyAdded
- DeepFakeAI/processors/frame/modules/__pycache__/__init__.cpython-310.pycAdded
- DeepFakeAI/processors/frame/modules/__pycache__/face_enhancer.cpython-310.pycAdded
- DeepFakeAI/processors/frame/modules/__pycache__/face_swapper.cpython-310.pycAdded
- DeepFakeAI/processors/frame/modules/__pycache__/frame_enhancer.cpython-310.pycAdded
- DeepFakeAI/processors/frame/modules/face_enhancer.pyAdded+100
- DeepFakeAI/processors/frame/modules/face_swapper.pyAdded+105
- DeepFakeAI/processors/frame/modules/frame_enhancer.pyAdded+88
- DeepFakeAI/typing.pyAdded+13
- DeepFakeAI/uis/__init__.pyAdded
123version https://git-lfs.github.com/spec/v1oid sha256:e2cd4703ab14f4d01fd1383a8a8b266f9a5833dacee8e6a79d3bf21a1b6be5adsize 348632874123version https://git-lfs.github.com/spec/v1oid sha256:4fa0d38905f75ac06eb49a7951b426670021be3018265fd191d2125df9d682f1size 67040989123version https://git-lfs.github.com/spec/v1oid sha256:e4a3f08c753cb72d04e10aa0f7dbe3deebbf39567d4ead6dce08e98aa49e16afsize 55425368112345678root = true
[*]end_of_line = lfinsert_final_newline = trueindent_size = 4indent_style = tabtrim_trailing_whitespace = true123[flake8]select = E3, E4, Fper-file-ignores = facefusion/core.py:E402,F40132 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text.github/preview.png filter=lfs diff=lfs merge=lfs -text
12github: henryruhscustom: https://paypal.me/henryruhs12345678910111213141516171819202122232425262728293031323334name: ci
on: [ push, pull_request ]
jobs: lint: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v2 - name: Set up Python 3.10 uses: actions/setup-python@v2 with: python-version: '3.10' - run: pip install flake8 - run: pip install mypy - run: flake8 run.py facefusion tests - run: mypy run.py facefusion tests test: strategy: matrix: os: [ macos-latest, ubuntu-latest, windows-latest ] runs-on: ${{ matrix.os }} steps: - name: Checkout uses: actions/checkout@v2 - name: Set up ffmpeg uses: FedericoCarboni/setup-ffmpeg@v2 - name: Set up Python 3.10 uses: actions/setup-python@v2 with: python-version: '3.10' - run: pip install -r requirements-ci.txt - run: pytest1234.assets.idea.vscode
12345678910111213141516171819202122from typing import Optionalimport cv2
from facefusion.typing import Frame
def get_video_frame(video_path : str, frame_number : int = 0) -> Optional[Frame]: capture = cv2.VideoCapture(video_path) frame_total = capture.get(cv2.CAP_PROP_FRAME_COUNT) capture.set(cv2.CAP_PROP_POS_FRAMES, min(frame_total, frame_number - 1)) has_frame, frame = capture.read() capture.release() if has_frame: return frame return None
def get_video_frame_total(video_path : str) -> int: capture = cv2.VideoCapture(video_path) video_frame_total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT)) capture.release() return video_frame_total12345678910from typing import List
from facefusion.typing import FaceRecognition, FaceAnalyserDirection, FaceAnalyserAge, FaceAnalyserGender, TempFrameFormat, OutputVideoEncoder
face_recognition : List[FaceRecognition] = [ 'reference', 'many' ]face_analyser_direction : List[FaceAnalyserDirection] = [ 'left-right', 'right-left', 'top-bottom', 'bottom-top', 'small-large', 'large-small']face_analyser_age : List[FaceAnalyserAge] = [ 'child', 'teen', 'adult', 'senior' ]face_analyser_gender : List[FaceAnalyserGender] = [ 'male', 'female' ]temp_frame_format : List[TempFrameFormat] = [ 'jpg', 'png' ]output_video_encoder : List[OutputVideoEncoder] = [ 'libx264', 'libx265', 'libvpx-vp9', 'h264_nvenc', 'hevc_nvenc' ]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222#!/usr/bin/env python3
import os# single thread doubles cuda performanceos.environ['OMP_NUM_THREADS'] = '1'# reduce tensorflow log levelos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'import sysimport warningsfrom typing import Listimport platformimport signalimport shutilimport argparseimport onnxruntimeimport tensorflow
import facefusion.choicesimport facefusion.globalsfrom facefusion import wording, metadatafrom facefusion.predictor import predict_image, predict_videofrom facefusion.processors.frame.core import get_frame_processors_modulesfrom facefusion.utilities import is_image, is_video, detect_fps, create_video, extract_frames, get_temp_frame_paths, restore_audio, create_temp, move_temp, clear_temp, normalize_output_path, list_module_names, decode_execution_providers, encode_execution_providers
warnings.filterwarnings('ignore', category = FutureWarning, module = 'insightface')warnings.filterwarnings('ignore', category = UserWarning, module = 'torchvision')
def parse_args() -> None: signal.signal(signal.SIGINT, lambda signal_number, frame: destroy()) program = argparse.ArgumentParser(formatter_class = lambda prog: argparse.HelpFormatter(prog, max_help_position = 120)) program.add_argument('-s', '--source', help = wording.get('source_help'), dest = 'source_path') program.add_argument('-t', '--target', help = wording.get('target_help'), dest = 'target_path') program.add_argument('-o', '--output', help = wording.get('output_help'), dest = 'output_path') program.add_argument('--frame-processors', help = wording.get('frame_processors_help').format(choices = ', '.join(list_module_names('facefusion/processors/frame/modules'))), dest = 'frame_processors', default = ['face_swapper'], nargs='+') program.add_argument('--ui-layouts', help = wording.get('ui_layouts_help').format(choices = ', '.join(list_module_names('facefusion/uis/layouts'))), dest = 'ui_layouts', default = ['default'], nargs='+') program.add_argument('--keep-fps', help = wording.get('keep_fps_help'), dest = 'keep_fps', action='store_true') program.add_argument('--keep-temp', help = wording.get('keep_temp_help'), dest = 'keep_temp', action='store_true') program.add_argument('--skip-audio', help = wording.get('skip_audio_help'), dest = 'skip_audio', action='store_true') program.add_argument('--face-recognition', help = wording.get('face_recognition_help'), dest = 'face_recognition', default = 'reference', choices = facefusion.choices.face_recognition) program.add_argument('--face-analyser-direction', help = wording.get('face_analyser_direction_help'), dest = 'face_analyser_direction', default = 'left-right', choices = facefusion.choices.face_analyser_direction) program.add_argument('--face-analyser-age', help = wording.get('face_analyser_age_help'), dest = 'face_analyser_age', choices = facefusion.choices.face_analyser_age) program.add_argument('--face-analyser-gender', help = wording.get('face_analyser_gender_help'), dest = 'face_analyser_gender', choices = facefusion.choices.face_analyser_gender) program.add_argument('--reference-face-position', help = wording.get('reference_face_position_help'), dest = 'reference_face_position', type = int, default = 0) program.add_argument('--reference-face-distance', help = wording.get('reference_face_distance_help'), dest = 'reference_face_distance', type = float, default = 1.5) program.add_argument('--reference-frame-number', help = wording.get('reference_frame_number_help'), dest = 'reference_frame_number', type = int, default = 0) program.add_argument('--trim-frame-start', help = wording.get('trim_frame_start_help'), dest = 'trim_frame_start', type = int) program.add_argument('--trim-frame-end', help = wording.get('trim_frame_end_help'), dest = 'trim_frame_end', type = int) program.add_argument('--temp-frame-format', help = wording.get('temp_frame_format_help'), dest = 'temp_frame_format', default = 'jpg', choices = facefusion.choices.temp_frame_format) program.add_argument('--temp-frame-quality', help = wording.get('temp_frame_quality_help'), dest = 'temp_frame_quality', type = int, default = 100, choices = range(101), metavar = '[0-100]') program.add_argument('--output-video-encoder', help = wording.get('output_video_encoder_help'), dest = 'output_video_encoder', default = 'libx264', choices = facefusion.choices.output_video_encoder) program.add_argument('--output-video-quality', help = wording.get('output_video_quality_help'), dest = 'output_video_quality', type = int, default = 90, choices = range(101), metavar = '[0-100]') program.add_argument('--max-memory', help = wording.get('max_memory_help'), dest = 'max_memory', type = int) program.add_argument('--execution-providers', help = wording.get('execution_providers_help').format(choices = 'cpu'), dest = 'execution_providers', default = ['cpu'], choices = suggest_execution_providers_choices(), nargs='+') program.add_argument('--execution-thread-count', help = wording.get('execution_thread_count_help'), dest = 'execution_thread_count', type = int, default = suggest_execution_thread_count_default()) program.add_argument('--execution-queue-count', help = wording.get('execution_queue_count_help'), dest = 'execution_queue_count', type = int, default = 1) program.add_argument('-v', '--version', action='version', version = metadata.get('name') + ' ' + metadata.get('version'))
args = program.parse_args()
facefusion.globals.source_path = args.source_path facefusion.globals.target_path = args.target_path facefusion.globals.output_path = normalize_output_path(facefusion.globals.source_path, facefusion.globals.target_path, args.output_path) facefusion.globals.headless = facefusion.globals.source_path is not None and facefusion.globals.target_path is not None and facefusion.globals.output_path is not None facefusion.globals.frame_processors = args.frame_processors facefusion.globals.ui_layouts = args.ui_layouts facefusion.globals.keep_fps = args.keep_fps facefusion.globals.keep_temp = args.keep_temp facefusion.globals.skip_audio = args.skip_audio facefusion.globals.face_recognition = args.face_recognition facefusion.globals.face_analyser_direction = args.face_analyser_direction facefusion.globals.face_analyser_age = args.face_analyser_age facefusion.globals.face_analyser_gender = args.face_analyser_gender facefusion.globals.reference_face_position = args.reference_face_position facefusion.globals.reference_frame_number = args.reference_frame_number facefusion.globals.reference_face_distance = args.reference_face_distance facefusion.globals.trim_frame_start = args.trim_frame_start facefusion.globals.trim_frame_end = args.trim_frame_end facefusion.globals.temp_frame_format = args.temp_frame_format facefusion.globals.temp_frame_quality = args.temp_frame_quality facefusion.globals.output_video_encoder = args.output_video_encoder facefusion.globals.output_video_quality = args.output_video_quality facefusion.globals.max_memory = args.max_memory facefusion.globals.execution_providers = decode_execution_providers(args.execution_providers) facefusion.globals.execution_thread_count = args.execution_thread_count facefusion.globals.execution_queue_count = args.execution_queue_count
def suggest_execution_providers_choices() -> List[str]: return encode_execution_providers(onnxruntime.get_available_providers())
def suggest_execution_thread_count_default() -> int: if 'CUDAExecutionProvider' in onnxruntime.get_available_providers(): return 8 return 1
def limit_resources() -> None: # prevent tensorflow memory leak gpus = tensorflow.config.experimental.list_physical_devices('GPU') for gpu in gpus: tensorflow.config.experimental.set_virtual_device_configuration(gpu, [ tensorflow.config.experimental.VirtualDeviceConfiguration(memory_limit = 1024) ]) # limit memory usage if facefusion.globals.max_memory: memory = facefusion.globals.max_memory * 1024 ** 3 if platform.system().lower() == 'darwin': memory = facefusion.globals.max_memory * 1024 ** 6 if platform.system().lower() == 'windows': import ctypes kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined] kernel32.SetProcessWorkingSetSize(-1, ctypes.c_size_t(memory), ctypes.c_size_t(memory)) else: import resource resource.setrlimit(resource.RLIMIT_DATA, (memory, memory))
def update_status(message : str, scope : str = 'FACEFUSION.CORE') -> None: print('[' + scope + '] ' + message)
def pre_check() -> bool: if sys.version_info < (3, 10): update_status(wording.get('python_not_supported').format(version = '3.10')) return False if not shutil.which('ffmpeg'): update_status(wording.get('ffmpeg_not_installed')) return False return True
def process_image() -> None: if predict_image(facefusion.globals.target_path): return shutil.copy2(facefusion.globals.target_path, facefusion.globals.output_path) # process frame for frame_processor_module in get_frame_processors_modules(facefusion.globals.frame_processors): update_status(wording.get('processing'), frame_processor_module.NAME) frame_processor_module.process_image(facefusion.globals.source_path, facefusion.globals.output_path, facefusion.globals.output_path) frame_processor_module.post_process() # validate image if is_image(facefusion.globals.target_path): update_status(wording.get('processing_image_succeed')) else: update_status(wording.get('processing_image_failed'))
def process_video() -> None: if predict_video(facefusion.globals.target_path): return fps = detect_fps(facefusion.globals.target_path) if facefusion.globals.keep_fps else 25.0 update_status(wording.get('creating_temp')) create_temp(facefusion.globals.target_path) # extract frames update_status(wording.get('extracting_frames_fps').format(fps = fps)) extract_frames(facefusion.globals.target_path, fps) # process frame temp_frame_paths = get_temp_frame_paths(facefusion.globals.target_path) if temp_frame_paths: for frame_processor_module in get_frame_processors_modules(facefusion.globals.frame_processors): update_status(wording.get('processing'), frame_processor_module.NAME) frame_processor_module.process_video(facefusion.globals.source_path, temp_frame_paths) frame_processor_module.post_process() else: update_status(wording.get('temp_frames_not_found')) return # create video update_status(wording.get('creating_video_fps').format(fps = fps)) if not create_video(facefusion.globals.target_path, fps): update_status(wording.get('creating_video_failed')) return # handle audio if facefusion.globals.skip_audio: update_status(wording.get('skipping_audio')) move_temp(facefusion.globals.target_path, facefusion.globals.output_path) else: update_status(wording.get('restoring_audio')) restore_audio(facefusion.globals.target_path, facefusion.globals.output_path) # clear temp update_status(wording.get('clearing_temp')) clear_temp(facefusion.globals.target_path) # validate video if is_video(facefusion.globals.target_path): update_status(wording.get('processing_video_succeed')) else: update_status(wording.get('processing_video_failed'))
def conditional_process() -> None: for frame_processor_module in get_frame_processors_modules(facefusion.globals.frame_processors): if not frame_processor_module.pre_process(): return if is_image(facefusion.globals.target_path): process_image() if is_video(facefusion.globals.target_path): process_video()
def run() -> None: parse_args() limit_resources() # pre check if not pre_check(): return for frame_processor in get_frame_processors_modules(facefusion.globals.frame_processors): if not frame_processor.pre_check(): return # process or launch if facefusion.globals.headless: conditional_process() else: import facefusion.uis.core as ui
ui.launch()
def destroy() -> None: if facefusion.globals.target_path: clear_temp(facefusion.globals.target_path) sys.exit()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106import threadingfrom typing import Any, Optional, Listimport insightfaceimport numpy
import facefusion.globalsfrom facefusion.typing import Frame, Face, FaceAnalyserDirection, FaceAnalyserAge, FaceAnalyserGender
FACE_ANALYSER = NoneTHREAD_LOCK = threading.Lock()
def get_face_analyser() -> Any: global FACE_ANALYSER
with THREAD_LOCK: if FACE_ANALYSER is None: FACE_ANALYSER = insightface.app.FaceAnalysis(name = 'buffalo_l', providers = facefusion.globals.execution_providers) FACE_ANALYSER.prepare(ctx_id = 0) return FACE_ANALYSER
def clear_face_analyser() -> Any: global FACE_ANALYSER
FACE_ANALYSER = None
def get_one_face(frame : Frame, position : int = 0) -> Optional[Face]: many_faces = get_many_faces(frame) if many_faces: try: return many_faces[position] except IndexError: return many_faces[-1] return None
def get_many_faces(frame : Frame) -> List[Face]: try: faces = get_face_analyser().get(frame) if facefusion.globals.face_analyser_direction: faces = sort_by_direction(faces, facefusion.globals.face_analyser_direction) if facefusion.globals.face_analyser_age: faces = filter_by_age(faces, facefusion.globals.face_analyser_age) if facefusion.globals.face_analyser_gender: faces = filter_by_gender(faces, facefusion.globals.face_analyser_gender) return faces except (AttributeError, ValueError): return []
def find_similar_faces(frame : Frame, reference_face : Face, face_distance : float) -> List[Face]: many_faces = get_many_faces(frame) similar_faces = [] if many_faces: for face in many_faces: if hasattr(face, 'normed_embedding') and hasattr(reference_face, 'normed_embedding'): current_face_distance = numpy.sum(numpy.square(face.normed_embedding - reference_face.normed_embedding)) if current_face_distance < face_distance: similar_faces.append(face) return similar_faces
def sort_by_direction(faces : List[Face], direction : FaceAnalyserDirection) -> List[Face]: if direction == 'left-right': return sorted(faces, key = lambda face: face['bbox'][0]) if direction == 'right-left': return sorted(faces, key = lambda face: face['bbox'][0], reverse = True) if direction == 'top-bottom': return sorted(faces, key = lambda face: face['bbox'][1]) if direction == 'bottom-top': return sorted(faces, key = lambda face: face['bbox'][1], reverse = True) if direction == 'small-large': return sorted(faces, key = lambda face: (face['bbox'][2] - face['bbox'][0]) * (face['bbox'][3] - face['bbox'][1])) if direction == 'large-small': return sorted(faces, key = lambda face: (face['bbox'][2] - face['bbox'][0]) * (face['bbox'][3] - face['bbox'][1]), reverse = True) return faces
def filter_by_age(faces : List[Face], age : FaceAnalyserAge) -> List[Face]: filter_faces = [] for face in faces: if face['age'] < 13 and age == 'child': filter_faces.append(face) elif face['age'] < 19 and age == 'teen': filter_faces.append(face) elif face['age'] < 60 and age == 'adult': filter_faces.append(face) elif face['age'] > 59 and age == 'senior': filter_faces.append(face) return filter_faces
def filter_by_gender(faces : List[Face], gender : FaceAnalyserGender) -> List[Face]: filter_faces = [] for face in faces: if face['gender'] == 1 and gender == 'male': filter_faces.append(face) if face['gender'] == 0 and gender == 'female': filter_faces.append(face) return filter_faces
def get_faces_total(frame : Frame) -> int: return len(get_many_faces(frame))123456789101112131415161718192021from typing import Optional
from facefusion.typing import Face
FACE_REFERENCE = None
def get_face_reference() -> Optional[Face]: return FACE_REFERENCE
def set_face_reference(face : Face) -> None: global FACE_REFERENCE
FACE_REFERENCE = face
def clear_face_reference() -> None: global FACE_REFERENCE
FACE_REFERENCE = None123456789101112131415161718192021222324252627282930from typing import List, Optional
from facefusion.typing import FaceRecognition, FaceAnalyserDirection, FaceAnalyserAge, FaceAnalyserGender, TempFrameFormat
source_path : Optional[str] = Nonetarget_path : Optional[str] = Noneoutput_path : Optional[str] = Noneheadless : Optional[bool] = Noneframe_processors : List[str] = []ui_layouts : List[str] = []keep_fps : Optional[bool] = Nonekeep_temp : Optional[bool] = Noneskip_audio : Optional[bool] = Noneface_recognition : Optional[FaceRecognition] = Noneface_analyser_direction : Optional[FaceAnalyserDirection] = Noneface_analyser_age : Optional[FaceAnalyserAge] = Noneface_analyser_gender : Optional[FaceAnalyserGender] = Nonereference_face_position : Optional[int] = Nonereference_frame_number : Optional[int] = Nonereference_face_distance : Optional[float] = Nonetrim_frame_start : Optional[int] = Nonetrim_frame_end : Optional[int] = Nonetemp_frame_format : Optional[TempFrameFormat] = Nonetemp_frame_quality : Optional[int] = Noneoutput_video_encoder : Optional[str] = Noneoutput_video_quality : Optional[int] = Nonemax_memory : Optional[int] = Noneexecution_providers : List[str] = []execution_thread_count : Optional[int] = Noneexecution_queue_count : Optional[int] = None12345678910111213METADATA =\{ 'name': 'FaceFusion', 'description': 'Next generation face swapper and enhancer', 'version': '1.0.0', 'license': 'MIT', 'author': 'Henry Ruhs', 'url': 'https://facefusion.io'}
def get(key : str) -> str: return METADATA[key]12345678910111213141516171819202122232425262728293031323334353637383940414243import threadingimport numpyimport opennsfw2from PIL import Imagefrom keras import Model
from facefusion.typing import Frame
PREDICTOR = NoneTHREAD_LOCK = threading.Lock()MAX_PROBABILITY = 0.75
def get_predictor() -> Model: global PREDICTOR
with THREAD_LOCK: if PREDICTOR is None: PREDICTOR = opennsfw2.make_open_nsfw_model() return PREDICTOR
def clear_predictor() -> None: global PREDICTOR
PREDICTOR = None
def predict_frame(target_frame : Frame) -> bool: image = Image.fromarray(target_frame) image = opennsfw2.preprocess_image(image, opennsfw2.Preprocessing.YAHOO) views = numpy.expand_dims(image, axis = 0) _, probability = get_predictor().predict(views)[0] return probability > MAX_PROBABILITY
def predict_image(target_path : str) -> bool: return opennsfw2.predict_image(target_path) > MAX_PROBABILITY
def predict_video(target_path : str) -> bool: _, probabilities = opennsfw2.predict_video_frames(video_path = target_path, frame_interval = 100) return any(probability > MAX_PROBABILITY for probability in probabilities)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113import osimport sysimport importlibimport psutilfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom queue import Queuefrom types import ModuleTypefrom typing import Any, List, Callablefrom tqdm import tqdm
import facefusion.globalsfrom facefusion import wording
FRAME_PROCESSORS_MODULES : List[ModuleType] = []FRAME_PROCESSORS_METHODS =\[ 'get_frame_processor', 'clear_frame_processor', 'pre_check', 'pre_process', 'process_frame', 'process_frames', 'process_image', 'process_video', 'post_process']
def load_frame_processor_module(frame_processor : str) -> Any: try: frame_processor_module = importlib.import_module('facefusion.processors.frame.modules.' + frame_processor) for method_name in FRAME_PROCESSORS_METHODS: if not hasattr(frame_processor_module, method_name): raise NotImplementedError except ModuleNotFoundError: sys.exit(wording.get('frame_processor_not_loaded').format(frame_processor = frame_processor)) except NotImplementedError: sys.exit(wording.get('frame_processor_not_implemented').format(frame_processor = frame_processor)) return frame_processor_module
def get_frame_processors_modules(frame_processors : List[str]) -> List[ModuleType]: global FRAME_PROCESSORS_MODULES
if not FRAME_PROCESSORS_MODULES: for frame_processor in frame_processors: frame_processor_module = load_frame_processor_module(frame_processor) FRAME_PROCESSORS_MODULES.append(frame_processor_module) return FRAME_PROCESSORS_MODULES
def clear_frame_processors_modules() -> None: global FRAME_PROCESSORS_MODULES
for frame_processor_module in get_frame_processors_modules(facefusion.globals.frame_processors): frame_processor_module.clear_frame_processor() FRAME_PROCESSORS_MODULES = []
def multi_process_frame(source_path : str, temp_frame_paths : List[str], process_frames: Callable[[str, List[str], Any], None], update: Callable[[], None]) -> None: with ThreadPoolExecutor(max_workers = facefusion.globals.execution_thread_count) as executor: futures = [] queue = create_queue(temp_frame_paths) queue_per_future = max(len(temp_frame_paths) // facefusion.globals.execution_thread_count * facefusion.globals.execution_queue_count, 1) while not queue.empty(): future = executor.submit(process_frames, source_path, pick_queue(queue, queue_per_future), update) futures.append(future) for future in as_completed(futures): future.result()
def create_queue(temp_frame_paths : List[str]) -> Queue[str]: queue: Queue[str] = Queue() for frame_path in temp_frame_paths: queue.put(frame_path) return queue
def pick_queue(queue : Queue[str], queue_per_future : int) -> List[str]: queues = [] for _ in range(queue_per_future): if not queue.empty(): queues.append(queue.get()) return queues
def process_video(source_path : str, frame_paths : List[str], process_frames : Callable[[str, List[str], Any], None]) -> None: progress_bar_format = '{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]' total = len(frame_paths) with tqdm(total = total, desc = wording.get('processing'), unit = 'frame', dynamic_ncols = True, bar_format = progress_bar_format) as progress: multi_process_frame(source_path, frame_paths, process_frames, lambda: update_progress(progress))
def update_progress(progress : Any = None) -> None: process = psutil.Process(os.getpid()) memory_usage = process.memory_info().rss / 1024 / 1024 / 1024 progress.set_postfix( { 'memory_usage': '{:.2f}'.format(memory_usage).zfill(5) + 'GB', 'execution_providers': facefusion.globals.execution_providers, 'execution_thread_count': facefusion.globals.execution_thread_count, 'execution_queue_count': facefusion.globals.execution_queue_count }) progress.refresh() progress.update(1)
def get_device() -> str: if 'CUDAExecutionProvider' in facefusion.globals.execution_providers: return 'cuda' if 'CoreMLExecutionProvider' in facefusion.globals.execution_providers: return 'mps' return 'cpu'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100from typing import Any, List, Callableimport cv2import threadingfrom gfpgan.utils import GFPGANer
import facefusion.globalsimport facefusion.processors.frame.core as frame_processorsfrom facefusion import wordingfrom facefusion.core import update_statusfrom facefusion.face_analyser import get_many_facesfrom facefusion.typing import Frame, Facefrom facefusion.utilities import conditional_download, resolve_relative_path, is_image, is_video
FRAME_PROCESSOR = NoneTHREAD_SEMAPHORE = threading.Semaphore()THREAD_LOCK = threading.Lock()NAME = 'FACEFUSION.FRAME_PROCESSOR.FACE_ENHANCER'
def get_frame_processor() -> Any: global FRAME_PROCESSOR
with THREAD_LOCK: if FRAME_PROCESSOR is None: model_path = resolve_relative_path('../.assets/models/GFPGANv1.4.pth') FRAME_PROCESSOR = GFPGANer( model_path = model_path, upscale = 1, device = frame_processors.get_device() ) return FRAME_PROCESSOR
def clear_frame_processor() -> None: global FRAME_PROCESSOR
FRAME_PROCESSOR = None
def pre_check() -> bool: download_directory_path = resolve_relative_path('../.assets/models') conditional_download(download_directory_path, ['https://github.com/facefusion/facefusion-assets/releases/download/models/GFPGANv1.4.pth']) return True
def pre_process() -> bool: if not is_image(facefusion.globals.target_path) and not is_video(facefusion.globals.target_path): update_status(wording.get('select_image_or_video_target') + wording.get('exclamation_mark'), NAME) return False return True
def post_process() -> None: clear_frame_processor()
def enhance_face(target_face : Face, temp_frame : Frame) -> Frame: start_x, start_y, end_x, end_y = map(int, target_face['bbox']) padding_x = int((end_x - start_x) * 0.5) padding_y = int((end_y - start_y) * 0.5) start_x = max(0, start_x - padding_x) start_y = max(0, start_y - padding_y) end_x = max(0, end_x + padding_x) end_y = max(0, end_y + padding_y) crop_frame = temp_frame[start_y:end_y, start_x:end_x] if crop_frame.size: with THREAD_SEMAPHORE: _, _, crop_frame = get_frame_processor().enhance( crop_frame, paste_back = True ) temp_frame[start_y:end_y, start_x:end_x] = crop_frame return temp_frame
def process_frame(source_face : Face, reference_face : Face, temp_frame : Frame) -> Frame: many_faces = get_many_faces(temp_frame) if many_faces: for target_face in many_faces: temp_frame = enhance_face(target_face, temp_frame) return temp_frame
def process_frames(source_path : str, temp_frame_paths : List[str], update: Callable[[], None]) -> None: for temp_frame_path in temp_frame_paths: temp_frame = cv2.imread(temp_frame_path) result_frame = process_frame(None, None, temp_frame) cv2.imwrite(temp_frame_path, result_frame) if update: update()
def process_image(source_path : str, target_path : str, output_path : str) -> None: target_frame = cv2.imread(target_path) result_frame = process_frame(None, None, target_frame) cv2.imwrite(output_path, result_frame)
def process_video(source_path : str, temp_frame_paths : List[str]) -> None: facefusion.processors.frame.core.process_video(None, temp_frame_paths, process_frames)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105from typing import Any, List, Callableimport cv2import insightfaceimport threading
import facefusion.globalsimport facefusion.processors.frame.core as frame_processorsfrom facefusion import wordingfrom facefusion.core import update_statusfrom facefusion.face_analyser import get_one_face, get_many_faces, find_similar_facesfrom facefusion.face_reference import get_face_reference, set_face_referencefrom facefusion.typing import Face, Framefrom facefusion.utilities import conditional_download, resolve_relative_path, is_image, is_video
FRAME_PROCESSOR = NoneTHREAD_LOCK = threading.Lock()NAME = 'FACEFUSION.FRAME_PROCESSOR.FACE_SWAPPER'
def get_frame_processor() -> Any: global FRAME_PROCESSOR
with THREAD_LOCK: if FRAME_PROCESSOR is None: model_path = resolve_relative_path('../.assets/models/inswapper_128.onnx') FRAME_PROCESSOR = insightface.model_zoo.get_model(model_path, providers = facefusion.globals.execution_providers) return FRAME_PROCESSOR
def clear_frame_processor() -> None: global FRAME_PROCESSOR
FRAME_PROCESSOR = None
def pre_check() -> bool: download_directory_path = resolve_relative_path('../.assets/models') conditional_download(download_directory_path, ['https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128.onnx']) return True
def pre_process() -> bool: if not is_image(facefusion.globals.source_path): update_status(wording.get('select_image_source') + wording.get('exclamation_mark'), NAME) return False elif not get_one_face(cv2.imread(facefusion.globals.source_path)): update_status(wording.get('no_source_face_detected') + wording.get('exclamation_mark'), NAME) return False if not is_image(facefusion.globals.target_path) and not is_video(facefusion.globals.target_path): update_status(wording.get('select_image_or_video_target') + wording.get('exclamation_mark'), NAME) return False return True
def post_process() -> None: clear_frame_processor()
def swap_face(source_face : Face, target_face : Face, temp_frame : Frame) -> Frame: return get_frame_processor().get(temp_frame, target_face, source_face, paste_back = True)
def process_frame(source_face : Face, reference_face : Face, temp_frame : Frame) -> Frame: if 'reference' in facefusion.globals.face_recognition: similar_faces = find_similar_faces(temp_frame, reference_face, facefusion.globals.reference_face_distance) if similar_faces: for similar_face in similar_faces: temp_frame = swap_face(source_face, similar_face, temp_frame) if 'many' in facefusion.globals.face_recognition: many_faces = get_many_faces(temp_frame) if many_faces: for target_face in many_faces: temp_frame = swap_face(source_face, target_face, temp_frame) return temp_frame
def process_frames(source_path : str, temp_frame_paths : List[str], update: Callable[[], None]) -> None: source_face = get_one_face(cv2.imread(source_path)) reference_face = get_face_reference() if 'reference' in facefusion.globals.face_recognition else None for temp_frame_path in temp_frame_paths: temp_frame = cv2.imread(temp_frame_path) result_frame = process_frame(source_face, reference_face, temp_frame) cv2.imwrite(temp_frame_path, result_frame) if update: update()
def process_image(source_path : str, target_path : str, output_path : str) -> None: source_face = get_one_face(cv2.imread(source_path)) target_frame = cv2.imread(target_path) reference_face = get_one_face(target_frame, facefusion.globals.reference_face_position) if 'reference' in facefusion.globals.face_recognition else None result_frame = process_frame(source_face, reference_face, target_frame) cv2.imwrite(output_path, result_frame)
def process_video(source_path : str, temp_frame_paths : List[str]) -> None: conditional_set_face_reference(temp_frame_paths) frame_processors.process_video(source_path, temp_frame_paths, process_frames)
def conditional_set_face_reference(temp_frame_paths : List[str]) -> None: if 'reference' in facefusion.globals.face_recognition and not get_face_reference(): reference_frame = cv2.imread(temp_frame_paths[facefusion.globals.reference_frame_number]) reference_face = get_one_face(reference_frame, facefusion.globals.reference_face_position) set_face_reference(reference_face)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788from typing import Any, List, Callableimport cv2import threadingfrom basicsr.archs.rrdbnet_arch import RRDBNetfrom realesrgan import RealESRGANer
import facefusion.processors.frame.core as frame_processorsfrom facefusion.typing import Frame, Facefrom facefusion.utilities import conditional_download, resolve_relative_path
FRAME_PROCESSOR = NoneTHREAD_SEMAPHORE = threading.Semaphore()THREAD_LOCK = threading.Lock()NAME = 'FACEFUSION.FRAME_PROCESSOR.FRAME_ENHANCER'
def get_frame_processor() -> Any: global FRAME_PROCESSOR
with THREAD_LOCK: if FRAME_PROCESSOR is None: model_path = resolve_relative_path('../.assets/models/RealESRGAN_x4plus.pth') FRAME_PROCESSOR = RealESRGANer( model_path = model_path, model = RRDBNet( num_in_ch = 3, num_out_ch = 3, num_feat = 64, num_block = 23, num_grow_ch = 32, scale = 4 ), device = frame_processors.get_device(), tile = 512, tile_pad = 32, pre_pad = 0, scale = 4 ) return FRAME_PROCESSOR
def clear_frame_processor() -> None: global FRAME_PROCESSOR
FRAME_PROCESSOR = None
def pre_check() -> bool: download_directory_path = resolve_relative_path('../.assets/models') conditional_download(download_directory_path, ['https://github.com/facefusion/facefusion-assets/releases/download/models/RealESRGAN_x4plus.pth']) return True
def pre_process() -> bool: return True
def post_process() -> None: clear_frame_processor()
def enhance_frame(temp_frame : Frame) -> Frame: with THREAD_SEMAPHORE: temp_frame, _ = get_frame_processor().enhance(temp_frame, outscale = 1) return temp_frame
def process_frame(source_face : Face, reference_face : Face, temp_frame : Frame) -> Frame: return enhance_frame(temp_frame)
def process_frames(source_path : str, temp_frame_paths : List[str], update: Callable[[], None]) -> None: for temp_frame_path in temp_frame_paths: temp_frame = cv2.imread(temp_frame_path) result_frame = process_frame(None, None, temp_frame) cv2.imwrite(temp_frame_path, result_frame) if update: update()
def process_image(source_path : str, target_path : str, output_path : str) -> None: target_frame = cv2.imread(target_path) result = process_frame(None, None, target_frame) cv2.imwrite(output_path, result)
def process_video(source_path : str, temp_frame_paths : List[str]) -> None: frame_processors.process_video(None, temp_frame_paths, process_frames)12345678910111213from typing import Any, Literalfrom insightface.app.common import Faceimport numpy
Face = FaceFrame = numpy.ndarray[Any, Any]
FaceRecognition = Literal[ 'reference', 'many' ]FaceAnalyserDirection = Literal[ 'left-right', 'right-left', 'top-bottom', 'bottom-top', 'small-large', 'large-small' ]FaceAnalyserAge = Literal[ 'child', 'teen', 'adult', 'senior' ]FaceAnalyserGender = Literal[ 'male', 'female' ]TempFrameFormat = Literal[ 'jpg', 'png' ]OutputVideoEncoder = Literal[ 'libx264', 'libx265', 'libvpx-vp9', 'h264_nvenc', 'hevc_nvenc' ].assets/models/GFPGANv1.4.pthAdded+3
.assets/models/RealESRGAN_x4plus.pthAdded+3
.assets/models/inswapper_128.onnxAdded+3
.editorconfigAdded+8
.flake8Added+3
.gitattributes+1
.github/FUNDING.ymlAdded+2
.github/preview.pngAdded

Large File Pointer Details
- SHA256: 90f9882b1a3fd51272d42384f5f7a84082749eaf2fb874125b942af077045801
- Pointer size: 132 Bytes
- Size of remote file: 1.1 MB
.github/workflows/ci.ymlAdded+34
.gitignoreAdded+4
1685074910001_vtqikl_2_0-boy-dp-image-77-720x704.jpgAdded

1685074910001_vtqikl_2_0-images 2.jpegAdded

1685074910001_vtqikl_2_0-images.jpgAdded

DeepFakeAI/__init__.pyAdded
DeepFakeAI/__pycache__/__init__.cpython-310.pycAdded
DeepFakeAI/__pycache__/capturer.cpython-310.pycAdded
DeepFakeAI/__pycache__/choices.cpython-310.pycAdded
DeepFakeAI/__pycache__/core.cpython-310.pycAdded
DeepFakeAI/__pycache__/face_analyser.cpython-310.pycAdded
DeepFakeAI/__pycache__/face_reference.cpython-310.pycAdded
DeepFakeAI/__pycache__/globals.cpython-310.pycAdded
DeepFakeAI/__pycache__/metadata.cpython-310.pycAdded
DeepFakeAI/__pycache__/predictor.cpython-310.pycAdded
DeepFakeAI/__pycache__/typing.cpython-310.pycAdded
DeepFakeAI/__pycache__/utilities.cpython-310.pycAdded
DeepFakeAI/__pycache__/wording.cpython-310.pycAdded
DeepFakeAI/capturer.pyAdded+22
DeepFakeAI/choices.pyAdded+10
DeepFakeAI/core.pyAdded+222
DeepFakeAI/face_analyser.pyAdded+106
DeepFakeAI/face_reference.pyAdded+21
DeepFakeAI/globals.pyAdded+30
DeepFakeAI/metadata.pyAdded+13
DeepFakeAI/predictor.pyAdded+43
DeepFakeAI/processors/__init__.pyAdded
DeepFakeAI/processors/__pycache__/__init__.cpython-310.pycAdded
DeepFakeAI/processors/frame/__init__.pyAdded
DeepFakeAI/processors/frame/__pycache__/__init__.cpython-310.pycAdded
DeepFakeAI/processors/frame/__pycache__/core.cpython-310.pycAdded
DeepFakeAI/processors/frame/core.pyAdded+113
DeepFakeAI/processors/frame/modules/__init__.pyAdded
DeepFakeAI/processors/frame/modules/__pycache__/__init__.cpython-310.pycAdded
DeepFakeAI/processors/frame/modules/__pycache__/face_enhancer.cpython-310.pycAdded
DeepFakeAI/processors/frame/modules/__pycache__/face_swapper.cpython-310.pycAdded
DeepFakeAI/processors/frame/modules/__pycache__/frame_enhancer.cpython-310.pycAdded
DeepFakeAI/processors/frame/modules/face_enhancer.pyAdded+100
DeepFakeAI/processors/frame/modules/face_swapper.pyAdded+105
DeepFakeAI/processors/frame/modules/frame_enhancer.pyAdded+88
DeepFakeAI/typing.pyAdded+13
DeepFakeAI/uis/__init__.pyAdded