Spaces:
Runtime error
Runtime error
Upload 236 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .coveragerc +2 -0
- .editorconfig +8 -0
- .flake8 +6 -0
- .gitattributes +1 -0
- .github/FUNDING.yml +1 -0
- .github/preview.png +3 -0
- .github/workflows/ci.yml +58 -0
- .gitignore +7 -0
- LICENSE.md +3 -0
- README.md +26 -12
- app.py +74 -0
- facefusion.ico +0 -0
- facefusion.ini +131 -0
- facefusion.py +10 -0
- facefusion/__init__.py +0 -0
- facefusion/app_context.py +16 -0
- facefusion/args.py +131 -0
- facefusion/audio.py +143 -0
- facefusion/benchmarker.py +111 -0
- facefusion/camera_manager.py +53 -0
- facefusion/choices.py +169 -0
- facefusion/cli_helper.py +35 -0
- facefusion/common_helper.py +84 -0
- facefusion/config.py +74 -0
- facefusion/content_analyser.py +247 -0
- facefusion/core.py +350 -0
- facefusion/curl_builder.py +32 -0
- facefusion/download.py +175 -0
- facefusion/execution.py +160 -0
- facefusion/exit_helper.py +34 -0
- facefusion/face_analyser.py +143 -0
- facefusion/face_classifier.py +140 -0
- facefusion/face_detector.py +458 -0
- facefusion/face_helper.py +256 -0
- facefusion/face_landmarker.py +240 -0
- facefusion/face_masker.py +279 -0
- facefusion/face_recognizer.py +93 -0
- facefusion/face_selector.py +130 -0
- facefusion/face_store.py +28 -0
- facefusion/ffmpeg.py +291 -0
- facefusion/ffmpeg_builder.py +267 -0
- facefusion/filesystem.py +190 -0
- facefusion/hash_helper.py +32 -0
- facefusion/inference_manager.py +95 -0
- facefusion/installer.py +109 -0
- facefusion/jobs/__init__.py +0 -0
- facefusion/jobs/job_helper.py +20 -0
- facefusion/jobs/job_list.py +34 -0
- facefusion/jobs/job_manager.py +265 -0
- facefusion/jobs/job_runner.py +112 -0
.coveragerc
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[run]
|
| 2 |
+
patch = subprocess
|
.editorconfig
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
root = true
|
| 2 |
+
|
| 3 |
+
[*]
|
| 4 |
+
end_of_line = lf
|
| 5 |
+
insert_final_newline = true
|
| 6 |
+
indent_size = 4
|
| 7 |
+
indent_style = tab
|
| 8 |
+
trim_trailing_whitespace = true
|
.flake8
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[flake8]
|
| 2 |
+
select = E22, E23, E24, E27, E3, E4, E7, F, I1, I2
|
| 3 |
+
per-file-ignores = facefusion.py:E402, install.py:E402
|
| 4 |
+
plugins = flake8-import-order
|
| 5 |
+
application_import_names = facefusion
|
| 6 |
+
import-order-style = pycharm
|
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
.github/preview.png filter=lfs diff=lfs merge=lfs -text
|
.github/FUNDING.yml
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
custom: [ buymeacoffee.com/facefusion, ko-fi.com/facefusion ]
|
.github/preview.png
ADDED
|
Git LFS Details
|
.github/workflows/ci.yml
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: ci
|
| 2 |
+
|
| 3 |
+
on: [ push, pull_request ]
|
| 4 |
+
|
| 5 |
+
jobs:
|
| 6 |
+
lint:
|
| 7 |
+
runs-on: ubuntu-latest
|
| 8 |
+
steps:
|
| 9 |
+
- name: Checkout
|
| 10 |
+
uses: actions/checkout@v4
|
| 11 |
+
- name: Set up Python 3.12
|
| 12 |
+
uses: actions/setup-python@v5
|
| 13 |
+
with:
|
| 14 |
+
python-version: '3.12'
|
| 15 |
+
- run: pip install flake8
|
| 16 |
+
- run: pip install flake8-import-order
|
| 17 |
+
- run: pip install mypy
|
| 18 |
+
- run: flake8 facefusion.py install.py
|
| 19 |
+
- run: flake8 facefusion tests
|
| 20 |
+
- run: mypy facefusion.py install.py
|
| 21 |
+
- run: mypy facefusion tests
|
| 22 |
+
test:
|
| 23 |
+
strategy:
|
| 24 |
+
matrix:
|
| 25 |
+
os: [ macos-latest, ubuntu-latest, windows-latest ]
|
| 26 |
+
runs-on: ${{ matrix.os }}
|
| 27 |
+
steps:
|
| 28 |
+
- name: Checkout
|
| 29 |
+
uses: actions/checkout@v4
|
| 30 |
+
- name: Set up FFmpeg
|
| 31 |
+
uses: AnimMouse/setup-ffmpeg@v1
|
| 32 |
+
- name: Set up Python 3.12
|
| 33 |
+
uses: actions/setup-python@v5
|
| 34 |
+
with:
|
| 35 |
+
python-version: '3.12'
|
| 36 |
+
- run: python install.py --onnxruntime default --skip-conda
|
| 37 |
+
- run: pip install pytest
|
| 38 |
+
- run: pytest
|
| 39 |
+
report:
|
| 40 |
+
needs: test
|
| 41 |
+
runs-on: ubuntu-latest
|
| 42 |
+
steps:
|
| 43 |
+
- name: Checkout
|
| 44 |
+
uses: actions/checkout@v4
|
| 45 |
+
- name: Set up FFmpeg
|
| 46 |
+
uses: FedericoCarboni/setup-ffmpeg@v3
|
| 47 |
+
- name: Set up Python 3.12
|
| 48 |
+
uses: actions/setup-python@v5
|
| 49 |
+
with:
|
| 50 |
+
python-version: '3.12'
|
| 51 |
+
- run: python install.py --onnxruntime default --skip-conda
|
| 52 |
+
- run: pip install coveralls
|
| 53 |
+
- run: pip install pytest
|
| 54 |
+
- run: pip install pytest-cov
|
| 55 |
+
- run: pytest tests --cov facefusion
|
| 56 |
+
- run: coveralls --service github
|
| 57 |
+
env:
|
| 58 |
+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
.gitignore
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__
|
| 2 |
+
.assets
|
| 3 |
+
.claude
|
| 4 |
+
.caches
|
| 5 |
+
.idea
|
| 6 |
+
.jobs
|
| 7 |
+
.vscode
|
LICENSE.md
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
OpenRAIL-AS license
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2025 Henry Ruhs
|
README.md
CHANGED
|
@@ -1,12 +1,26 @@
|
|
| 1 |
-
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
-
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
-
app_file: app.py
|
| 9 |
-
pinned: false
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: FaceFusion
|
| 3 |
+
emoji: 🌖
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: pink
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 5.44.1
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
license: mit
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
# FaceFusion
|
| 14 |
+
|
| 15 |
+
> Industry leading face manipulation platform.
|
| 16 |
+
|
| 17 |
+
## Deployment on Hugging Face Spaces
|
| 18 |
+
This Space runs FaceFusion using the **Gradio SDK**.
|
| 19 |
+
|
| 20 |
+
**Hardware Recommendation:**
|
| 21 |
+
- **CPU Basic**: Slow, not recommended for video.
|
| 22 |
+
- **GPU (Zero/Pro)**: Recommended for reasonable speed.
|
| 23 |
+
|
| 24 |
+
## Configuration
|
| 25 |
+
The `packages.txt` file installs `ffmpeg` which is required for media processing.
|
| 26 |
+
`app.py` is configured to bypass CLI arguments and start the UI directly.
|
app.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import shutil
|
| 4 |
+
import gradio as gr
|
| 5 |
+
from typing import List
|
| 6 |
+
from types import ModuleType
|
| 7 |
+
|
| 8 |
+
# Force current directory into python path
|
| 9 |
+
sys.path.append(os.path.abspath("."))
|
| 10 |
+
|
| 11 |
+
# Mock or Setup FaceFusion imports
|
| 12 |
+
# We need to manually initialize state_manager because we are skipping the CLI argument parsing
|
| 13 |
+
from facefusion import state_manager, metadata, config
|
| 14 |
+
import facefusion.uis.core as ui_core
|
| 15 |
+
import facefusion.uis.layouts.default as default_layout
|
| 16 |
+
from facefusion import logger
|
| 17 |
+
|
| 18 |
+
# Set default state for FaceFusion
|
| 19 |
+
# These values mimic what 'python facefusion.py run' would produce with default args
|
| 20 |
+
state_manager.init_item('command', 'run')
|
| 21 |
+
state_manager.init_item('ui_layouts', ['default'])
|
| 22 |
+
state_manager.init_item('system_memory_limit', 0)
|
| 23 |
+
state_manager.init_item('face_selector_mode', 'reference')
|
| 24 |
+
state_manager.init_item('face_selector_order', 'large-small')
|
| 25 |
+
state_manager.init_item('face_selector_gender', None)
|
| 26 |
+
state_manager.init_item('face_selector_race', None)
|
| 27 |
+
state_manager.init_item('face_detector_model', 'yolo_face')
|
| 28 |
+
state_manager.init_item('face_detector_size', '640x640')
|
| 29 |
+
state_manager.init_item('face_detector_score', 0.5)
|
| 30 |
+
state_manager.init_item('face_landmarker_model', '2dfan4')
|
| 31 |
+
state_manager.init_item('face_landmarker_score', 0.5)
|
| 32 |
+
state_manager.init_item('face_mask_types', ['box'])
|
| 33 |
+
state_manager.init_item('face_mask_areas', ['skin', 'l-eyebrow', 'r-eyebrow', 'l-eye', 'r-eye', 'eye-g', 'l-ear', 'r-ear', 'ear-r', 'nose', 'mouth', 'u-lip', 'l-lip', 'neck', 'neck-l', 'cloth']) # Default all
|
| 34 |
+
state_manager.init_item('face_mask_regions', ['skin', 'l-eyebrow', 'r-eyebrow', 'l-eye', 'r-eye', 'eye-g', 'l-ear', 'r-ear', 'ear-r', 'nose', 'mouth', 'u-lip', 'l-lip', 'neck', 'neck-l', 'cloth'])
|
| 35 |
+
state_manager.init_item('face_mask_blur', 0.3)
|
| 36 |
+
state_manager.init_item('face_mask_padding', (0, 0, 0, 0))
|
| 37 |
+
state_manager.init_item('face_occluder_model', 'xseg_1')
|
| 38 |
+
state_manager.init_item('face_parser_model', 'bisenet_resnet_34')
|
| 39 |
+
state_manager.init_item('processors', ['face_swapper'])
|
| 40 |
+
state_manager.init_item('execution_providers', ['cpu']) # Change to 'cuda' if GPU space
|
| 41 |
+
state_manager.init_item('execution_thread_count', 4)
|
| 42 |
+
state_manager.init_item('execution_device_ids', [0])
|
| 43 |
+
state_manager.init_item('temp_path', os.path.join(os.getcwd(), '.tmp'))
|
| 44 |
+
state_manager.init_item('output_image_quality', 80)
|
| 45 |
+
state_manager.init_item('output_video_quality', 80)
|
| 46 |
+
state_manager.init_item('output_video_fps', 30)
|
| 47 |
+
state_manager.init_item('output_video_encoder', 'libx264')
|
| 48 |
+
state_manager.init_item('output_audio_encoder', 'aac')
|
| 49 |
+
state_manager.init_item('log_level', 'info')
|
| 50 |
+
|
| 51 |
+
# Helper to load layout
|
| 52 |
+
def get_theme() -> gr.Theme:
|
| 53 |
+
return ui_core.get_theme()
|
| 54 |
+
|
| 55 |
+
def get_css() -> str:
|
| 56 |
+
return ui_core.get_css()
|
| 57 |
+
|
| 58 |
+
# Initialize UI
|
| 59 |
+
ui_core.init()
|
| 60 |
+
|
| 61 |
+
# Launch logic adapted from facefusion.uis.core.launch
|
| 62 |
+
# We construct the Block here and expose it as 'demo' for Hugging Face
|
| 63 |
+
with gr.Blocks(theme=get_theme(), css=get_css(), title=metadata.get('name') + ' ' + metadata.get('version')) as demo:
|
| 64 |
+
# Render layout
|
| 65 |
+
# Since we only use 'default', we import it directly or load it
|
| 66 |
+
default_layout.render()
|
| 67 |
+
default_layout.listen()
|
| 68 |
+
|
| 69 |
+
# Run setup
|
| 70 |
+
default_layout.run(demo)
|
| 71 |
+
|
| 72 |
+
# Launch
|
| 73 |
+
if __name__ == "__main__":
|
| 74 |
+
demo.launch()
|
facefusion.ico
ADDED
|
|
facefusion.ini
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[paths]
|
| 2 |
+
temp_path =
|
| 3 |
+
jobs_path =
|
| 4 |
+
source_paths =
|
| 5 |
+
target_path =
|
| 6 |
+
output_path =
|
| 7 |
+
|
| 8 |
+
[patterns]
|
| 9 |
+
source_pattern =
|
| 10 |
+
target_pattern =
|
| 11 |
+
output_pattern =
|
| 12 |
+
|
| 13 |
+
[face_detector]
|
| 14 |
+
face_detector_model =
|
| 15 |
+
face_detector_size =
|
| 16 |
+
face_detector_margin =
|
| 17 |
+
face_detector_angles =
|
| 18 |
+
face_detector_score =
|
| 19 |
+
|
| 20 |
+
[face_landmarker]
|
| 21 |
+
face_landmarker_model =
|
| 22 |
+
face_landmarker_score =
|
| 23 |
+
|
| 24 |
+
[face_selector]
|
| 25 |
+
face_selector_mode =
|
| 26 |
+
face_selector_order =
|
| 27 |
+
face_selector_age_start =
|
| 28 |
+
face_selector_age_end =
|
| 29 |
+
face_selector_gender =
|
| 30 |
+
face_selector_race =
|
| 31 |
+
reference_face_position =
|
| 32 |
+
reference_face_distance =
|
| 33 |
+
reference_frame_number =
|
| 34 |
+
|
| 35 |
+
[face_masker]
|
| 36 |
+
face_occluder_model =
|
| 37 |
+
face_parser_model =
|
| 38 |
+
face_mask_types =
|
| 39 |
+
face_mask_areas =
|
| 40 |
+
face_mask_regions =
|
| 41 |
+
face_mask_blur =
|
| 42 |
+
face_mask_padding =
|
| 43 |
+
|
| 44 |
+
[voice_extractor]
|
| 45 |
+
voice_extractor_model =
|
| 46 |
+
|
| 47 |
+
[frame_extraction]
|
| 48 |
+
trim_frame_start =
|
| 49 |
+
trim_frame_end =
|
| 50 |
+
temp_frame_format =
|
| 51 |
+
keep_temp =
|
| 52 |
+
|
| 53 |
+
[output_creation]
|
| 54 |
+
output_image_quality =
|
| 55 |
+
output_image_scale =
|
| 56 |
+
output_audio_encoder =
|
| 57 |
+
output_audio_quality =
|
| 58 |
+
output_audio_volume =
|
| 59 |
+
output_video_encoder =
|
| 60 |
+
output_video_preset =
|
| 61 |
+
output_video_quality =
|
| 62 |
+
output_video_scale =
|
| 63 |
+
output_video_fps =
|
| 64 |
+
|
| 65 |
+
[processors]
|
| 66 |
+
processors =
|
| 67 |
+
age_modifier_model =
|
| 68 |
+
age_modifier_direction =
|
| 69 |
+
background_remover_model =
|
| 70 |
+
background_remover_color =
|
| 71 |
+
deep_swapper_model =
|
| 72 |
+
deep_swapper_morph =
|
| 73 |
+
expression_restorer_model =
|
| 74 |
+
expression_restorer_factor =
|
| 75 |
+
expression_restorer_areas =
|
| 76 |
+
face_debugger_items =
|
| 77 |
+
face_editor_model =
|
| 78 |
+
face_editor_eyebrow_direction =
|
| 79 |
+
face_editor_eye_gaze_horizontal =
|
| 80 |
+
face_editor_eye_gaze_vertical =
|
| 81 |
+
face_editor_eye_open_ratio =
|
| 82 |
+
face_editor_lip_open_ratio =
|
| 83 |
+
face_editor_mouth_grim =
|
| 84 |
+
face_editor_mouth_pout =
|
| 85 |
+
face_editor_mouth_purse =
|
| 86 |
+
face_editor_mouth_smile =
|
| 87 |
+
face_editor_mouth_position_horizontal =
|
| 88 |
+
face_editor_mouth_position_vertical =
|
| 89 |
+
face_editor_head_pitch =
|
| 90 |
+
face_editor_head_yaw =
|
| 91 |
+
face_editor_head_roll =
|
| 92 |
+
face_enhancer_model =
|
| 93 |
+
face_enhancer_blend =
|
| 94 |
+
face_enhancer_weight =
|
| 95 |
+
face_swapper_model =
|
| 96 |
+
face_swapper_pixel_boost =
|
| 97 |
+
face_swapper_weight =
|
| 98 |
+
frame_colorizer_model =
|
| 99 |
+
frame_colorizer_size =
|
| 100 |
+
frame_colorizer_blend =
|
| 101 |
+
frame_enhancer_model =
|
| 102 |
+
frame_enhancer_blend =
|
| 103 |
+
lip_syncer_model =
|
| 104 |
+
lip_syncer_weight =
|
| 105 |
+
|
| 106 |
+
[uis]
|
| 107 |
+
open_browser =
|
| 108 |
+
ui_layouts =
|
| 109 |
+
ui_workflow =
|
| 110 |
+
|
| 111 |
+
[download]
|
| 112 |
+
download_providers =
|
| 113 |
+
download_scope =
|
| 114 |
+
|
| 115 |
+
[benchmark]
|
| 116 |
+
benchmark_mode =
|
| 117 |
+
benchmark_resolutions =
|
| 118 |
+
benchmark_cycle_count =
|
| 119 |
+
|
| 120 |
+
[execution]
|
| 121 |
+
execution_device_ids =
|
| 122 |
+
execution_providers =
|
| 123 |
+
execution_thread_count =
|
| 124 |
+
|
| 125 |
+
[memory]
|
| 126 |
+
video_memory_strategy =
|
| 127 |
+
system_memory_limit =
|
| 128 |
+
|
| 129 |
+
[misc]
|
| 130 |
+
log_level =
|
| 131 |
+
halt_on_error =
|
facefusion.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
os.environ['OMP_NUM_THREADS'] = '1'
|
| 6 |
+
|
| 7 |
+
from facefusion import core
|
| 8 |
+
|
| 9 |
+
if __name__ == '__main__':
|
| 10 |
+
core.cli()
|
facefusion/__init__.py
ADDED
|
File without changes
|
facefusion/app_context.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
from facefusion.types import AppContext
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def detect_app_context() -> AppContext:
|
| 8 |
+
frame = sys._getframe(1)
|
| 9 |
+
|
| 10 |
+
while frame:
|
| 11 |
+
if os.path.join('facefusion', 'jobs') in frame.f_code.co_filename:
|
| 12 |
+
return 'cli'
|
| 13 |
+
if os.path.join('facefusion', 'uis') in frame.f_code.co_filename:
|
| 14 |
+
return 'ui'
|
| 15 |
+
frame = frame.f_back
|
| 16 |
+
return 'cli'
|
facefusion/args.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from facefusion import state_manager
|
| 2 |
+
from facefusion.filesystem import get_file_name, is_video, resolve_file_paths
|
| 3 |
+
from facefusion.jobs import job_store
|
| 4 |
+
from facefusion.normalizer import normalize_fps, normalize_space
|
| 5 |
+
from facefusion.processors.core import get_processors_modules
|
| 6 |
+
from facefusion.types import ApplyStateItem, Args
|
| 7 |
+
from facefusion.vision import detect_video_fps
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def reduce_step_args(args : Args) -> Args:
|
| 11 |
+
step_args =\
|
| 12 |
+
{
|
| 13 |
+
key: args[key] for key in args if key in job_store.get_step_keys()
|
| 14 |
+
}
|
| 15 |
+
return step_args
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def reduce_job_args(args : Args) -> Args:
|
| 19 |
+
job_args =\
|
| 20 |
+
{
|
| 21 |
+
key: args[key] for key in args if key in job_store.get_job_keys()
|
| 22 |
+
}
|
| 23 |
+
return job_args
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def collect_step_args() -> Args:
|
| 27 |
+
step_args =\
|
| 28 |
+
{
|
| 29 |
+
key: state_manager.get_item(key) for key in job_store.get_step_keys() #type:ignore[arg-type]
|
| 30 |
+
}
|
| 31 |
+
return step_args
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def collect_job_args() -> Args:
|
| 35 |
+
job_args =\
|
| 36 |
+
{
|
| 37 |
+
key: state_manager.get_item(key) for key in job_store.get_job_keys() #type:ignore[arg-type]
|
| 38 |
+
}
|
| 39 |
+
return job_args
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
|
| 43 |
+
# general
|
| 44 |
+
apply_state_item('command', args.get('command'))
|
| 45 |
+
# paths
|
| 46 |
+
apply_state_item('temp_path', args.get('temp_path'))
|
| 47 |
+
apply_state_item('jobs_path', args.get('jobs_path'))
|
| 48 |
+
apply_state_item('source_paths', args.get('source_paths'))
|
| 49 |
+
apply_state_item('target_path', args.get('target_path'))
|
| 50 |
+
apply_state_item('output_path', args.get('output_path'))
|
| 51 |
+
# patterns
|
| 52 |
+
apply_state_item('source_pattern', args.get('source_pattern'))
|
| 53 |
+
apply_state_item('target_pattern', args.get('target_pattern'))
|
| 54 |
+
apply_state_item('output_pattern', args.get('output_pattern'))
|
| 55 |
+
# face detector
|
| 56 |
+
apply_state_item('face_detector_model', args.get('face_detector_model'))
|
| 57 |
+
apply_state_item('face_detector_size', args.get('face_detector_size'))
|
| 58 |
+
apply_state_item('face_detector_margin', normalize_space(args.get('face_detector_margin')))
|
| 59 |
+
apply_state_item('face_detector_angles', args.get('face_detector_angles'))
|
| 60 |
+
apply_state_item('face_detector_score', args.get('face_detector_score'))
|
| 61 |
+
# face landmarker
|
| 62 |
+
apply_state_item('face_landmarker_model', args.get('face_landmarker_model'))
|
| 63 |
+
apply_state_item('face_landmarker_score', args.get('face_landmarker_score'))
|
| 64 |
+
# face selector
|
| 65 |
+
apply_state_item('face_selector_mode', args.get('face_selector_mode'))
|
| 66 |
+
apply_state_item('face_selector_order', args.get('face_selector_order'))
|
| 67 |
+
apply_state_item('face_selector_age_start', args.get('face_selector_age_start'))
|
| 68 |
+
apply_state_item('face_selector_age_end', args.get('face_selector_age_end'))
|
| 69 |
+
apply_state_item('face_selector_gender', args.get('face_selector_gender'))
|
| 70 |
+
apply_state_item('face_selector_race', args.get('face_selector_race'))
|
| 71 |
+
apply_state_item('reference_face_position', args.get('reference_face_position'))
|
| 72 |
+
apply_state_item('reference_face_distance', args.get('reference_face_distance'))
|
| 73 |
+
apply_state_item('reference_frame_number', args.get('reference_frame_number'))
|
| 74 |
+
# face masker
|
| 75 |
+
apply_state_item('face_occluder_model', args.get('face_occluder_model'))
|
| 76 |
+
apply_state_item('face_parser_model', args.get('face_parser_model'))
|
| 77 |
+
apply_state_item('face_mask_types', args.get('face_mask_types'))
|
| 78 |
+
apply_state_item('face_mask_areas', args.get('face_mask_areas'))
|
| 79 |
+
apply_state_item('face_mask_regions', args.get('face_mask_regions'))
|
| 80 |
+
apply_state_item('face_mask_blur', args.get('face_mask_blur'))
|
| 81 |
+
apply_state_item('face_mask_padding', normalize_space(args.get('face_mask_padding')))
|
| 82 |
+
# voice extractor
|
| 83 |
+
apply_state_item('voice_extractor_model', args.get('voice_extractor_model'))
|
| 84 |
+
# frame extraction
|
| 85 |
+
apply_state_item('trim_frame_start', args.get('trim_frame_start'))
|
| 86 |
+
apply_state_item('trim_frame_end', args.get('trim_frame_end'))
|
| 87 |
+
apply_state_item('temp_frame_format', args.get('temp_frame_format'))
|
| 88 |
+
apply_state_item('keep_temp', args.get('keep_temp'))
|
| 89 |
+
# output creation
|
| 90 |
+
apply_state_item('output_image_quality', args.get('output_image_quality'))
|
| 91 |
+
apply_state_item('output_image_scale', args.get('output_image_scale'))
|
| 92 |
+
apply_state_item('output_audio_encoder', args.get('output_audio_encoder'))
|
| 93 |
+
apply_state_item('output_audio_quality', args.get('output_audio_quality'))
|
| 94 |
+
apply_state_item('output_audio_volume', args.get('output_audio_volume'))
|
| 95 |
+
apply_state_item('output_video_encoder', args.get('output_video_encoder'))
|
| 96 |
+
apply_state_item('output_video_preset', args.get('output_video_preset'))
|
| 97 |
+
apply_state_item('output_video_quality', args.get('output_video_quality'))
|
| 98 |
+
apply_state_item('output_video_scale', args.get('output_video_scale'))
|
| 99 |
+
if args.get('output_video_fps') or is_video(args.get('target_path')):
|
| 100 |
+
output_video_fps = normalize_fps(args.get('output_video_fps')) or detect_video_fps(args.get('target_path'))
|
| 101 |
+
apply_state_item('output_video_fps', output_video_fps)
|
| 102 |
+
# processors
|
| 103 |
+
available_processors = [ get_file_name(file_path) for file_path in resolve_file_paths('facefusion/processors/modules') ]
|
| 104 |
+
apply_state_item('processors', args.get('processors'))
|
| 105 |
+
for processor_module in get_processors_modules(available_processors):
|
| 106 |
+
processor_module.apply_args(args, apply_state_item)
|
| 107 |
+
# uis
|
| 108 |
+
apply_state_item('open_browser', args.get('open_browser'))
|
| 109 |
+
apply_state_item('ui_layouts', args.get('ui_layouts'))
|
| 110 |
+
apply_state_item('ui_workflow', args.get('ui_workflow'))
|
| 111 |
+
# execution
|
| 112 |
+
apply_state_item('execution_device_ids', args.get('execution_device_ids'))
|
| 113 |
+
apply_state_item('execution_providers', args.get('execution_providers'))
|
| 114 |
+
apply_state_item('execution_thread_count', args.get('execution_thread_count'))
|
| 115 |
+
# download
|
| 116 |
+
apply_state_item('download_providers', args.get('download_providers'))
|
| 117 |
+
apply_state_item('download_scope', args.get('download_scope'))
|
| 118 |
+
# benchmark
|
| 119 |
+
apply_state_item('benchmark_mode', args.get('benchmark_mode'))
|
| 120 |
+
apply_state_item('benchmark_resolutions', args.get('benchmark_resolutions'))
|
| 121 |
+
apply_state_item('benchmark_cycle_count', args.get('benchmark_cycle_count'))
|
| 122 |
+
# memory
|
| 123 |
+
apply_state_item('video_memory_strategy', args.get('video_memory_strategy'))
|
| 124 |
+
apply_state_item('system_memory_limit', args.get('system_memory_limit'))
|
| 125 |
+
# misc
|
| 126 |
+
apply_state_item('log_level', args.get('log_level'))
|
| 127 |
+
apply_state_item('halt_on_error', args.get('halt_on_error'))
|
| 128 |
+
# jobs
|
| 129 |
+
apply_state_item('job_id', args.get('job_id'))
|
| 130 |
+
apply_state_item('job_status', args.get('job_status'))
|
| 131 |
+
apply_state_item('step_index', args.get('step_index'))
|
facefusion/audio.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
from typing import Any, List, Optional
|
| 3 |
+
|
| 4 |
+
import numpy
|
| 5 |
+
import scipy
|
| 6 |
+
from numpy.typing import NDArray
|
| 7 |
+
|
| 8 |
+
from facefusion.ffmpeg import read_audio_buffer
|
| 9 |
+
from facefusion.filesystem import is_audio
|
| 10 |
+
from facefusion.types import Audio, AudioFrame, Fps, Mel, MelFilterBank, Spectrogram
|
| 11 |
+
from facefusion.voice_extractor import batch_extract_voice
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@lru_cache(maxsize = 64)
|
| 15 |
+
def read_static_audio(audio_path : str, fps : Fps) -> Optional[List[AudioFrame]]:
|
| 16 |
+
return read_audio(audio_path, fps)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def read_audio(audio_path : str, fps : Fps) -> Optional[List[AudioFrame]]:
|
| 20 |
+
audio_sample_rate = 48000
|
| 21 |
+
audio_sample_size = 16
|
| 22 |
+
audio_channel_total = 2
|
| 23 |
+
|
| 24 |
+
if is_audio(audio_path):
|
| 25 |
+
audio_buffer = read_audio_buffer(audio_path, audio_sample_rate, audio_sample_size, audio_channel_total)
|
| 26 |
+
audio = numpy.frombuffer(audio_buffer, dtype = numpy.int16).reshape(-1, 2)
|
| 27 |
+
audio = prepare_audio(audio)
|
| 28 |
+
spectrogram = create_spectrogram(audio)
|
| 29 |
+
audio_frames = extract_audio_frames(spectrogram, fps)
|
| 30 |
+
return audio_frames
|
| 31 |
+
return None
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@lru_cache(maxsize = 64)
|
| 35 |
+
def read_static_voice(audio_path : str, fps : Fps) -> Optional[List[AudioFrame]]:
|
| 36 |
+
return read_voice(audio_path, fps)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def read_voice(audio_path : str, fps : Fps) -> Optional[List[AudioFrame]]:
|
| 40 |
+
voice_sample_rate = 48000
|
| 41 |
+
voice_sample_size = 16
|
| 42 |
+
voice_channel_total = 2
|
| 43 |
+
voice_chunk_size = 240 * 1024
|
| 44 |
+
voice_step_size = 180 * 1024
|
| 45 |
+
|
| 46 |
+
if is_audio(audio_path):
|
| 47 |
+
audio_buffer = read_audio_buffer(audio_path, voice_sample_rate, voice_sample_size, voice_channel_total)
|
| 48 |
+
audio = numpy.frombuffer(audio_buffer, dtype = numpy.int16).reshape(-1, 2)
|
| 49 |
+
audio = batch_extract_voice(audio, voice_chunk_size, voice_step_size)
|
| 50 |
+
audio = prepare_voice(audio)
|
| 51 |
+
spectrogram = create_spectrogram(audio)
|
| 52 |
+
audio_frames = extract_audio_frames(spectrogram, fps)
|
| 53 |
+
return audio_frames
|
| 54 |
+
return None
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def get_audio_frame(audio_path : str, fps : Fps, frame_number : int = 0) -> Optional[AudioFrame]:
|
| 58 |
+
if is_audio(audio_path):
|
| 59 |
+
audio_frames = read_static_audio(audio_path, fps)
|
| 60 |
+
if frame_number in range(len(audio_frames)):
|
| 61 |
+
return audio_frames[frame_number]
|
| 62 |
+
return None
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def extract_audio_frames(spectrogram : Spectrogram, fps : Fps) -> List[AudioFrame]:
|
| 66 |
+
audio_frames = []
|
| 67 |
+
mel_filter_total = 80
|
| 68 |
+
audio_step_size = 16
|
| 69 |
+
indices = numpy.arange(0, spectrogram.shape[1], mel_filter_total / fps).astype(numpy.int16)
|
| 70 |
+
indices = indices[indices >= audio_step_size]
|
| 71 |
+
|
| 72 |
+
for index in indices:
|
| 73 |
+
start = max(0, index - audio_step_size)
|
| 74 |
+
audio_frames.append(spectrogram[:, start:index])
|
| 75 |
+
|
| 76 |
+
return audio_frames
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def get_voice_frame(audio_path : str, fps : Fps, frame_number : int = 0) -> Optional[AudioFrame]:
|
| 80 |
+
if is_audio(audio_path):
|
| 81 |
+
voice_frames = read_static_voice(audio_path, fps)
|
| 82 |
+
if frame_number in range(len(voice_frames)):
|
| 83 |
+
return voice_frames[frame_number]
|
| 84 |
+
return None
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def create_empty_audio_frame() -> AudioFrame:
|
| 88 |
+
mel_filter_total = 80
|
| 89 |
+
audio_step_size = 16
|
| 90 |
+
audio_frame = numpy.zeros((mel_filter_total, audio_step_size)).astype(numpy.int16)
|
| 91 |
+
return audio_frame
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def prepare_audio(audio : Audio) -> Audio:
|
| 95 |
+
if audio.ndim > 1:
|
| 96 |
+
audio = numpy.mean(audio, axis = 1)
|
| 97 |
+
audio = audio / numpy.max(numpy.abs(audio), axis = 0)
|
| 98 |
+
audio = scipy.signal.lfilter([ 1.0, -0.97 ], [ 1.0 ], audio)
|
| 99 |
+
return audio
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def prepare_voice(audio : Audio) -> Audio:
|
| 103 |
+
audio_sample_rate = 48000
|
| 104 |
+
audio_resample_rate = 16000
|
| 105 |
+
audio_resample_factor = round(len(audio) * audio_resample_rate / audio_sample_rate)
|
| 106 |
+
audio = scipy.signal.resample(audio, audio_resample_factor)
|
| 107 |
+
audio = prepare_audio(audio)
|
| 108 |
+
return audio
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def convert_hertz_to_mel(hertz : float) -> float:
|
| 112 |
+
return 2595 * numpy.log10(1 + hertz / 700)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def convert_mel_to_hertz(mel : Mel) -> NDArray[Any]:
|
| 116 |
+
return 700 * (10 ** (mel / 2595) - 1)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def create_mel_filter_bank() -> MelFilterBank:
|
| 120 |
+
audio_sample_rate = 16000
|
| 121 |
+
audio_frequency_min = 55.0
|
| 122 |
+
audio_frequency_max = 7600.0
|
| 123 |
+
mel_filter_total = 80
|
| 124 |
+
mel_bin_total = 800
|
| 125 |
+
mel_filter_bank = numpy.zeros((mel_filter_total, mel_bin_total // 2 + 1))
|
| 126 |
+
mel_frequency_range = numpy.linspace(convert_hertz_to_mel(audio_frequency_min), convert_hertz_to_mel(audio_frequency_max), mel_filter_total + 2)
|
| 127 |
+
indices = numpy.floor((mel_bin_total + 1) * convert_mel_to_hertz(mel_frequency_range) / audio_sample_rate).astype(numpy.int16)
|
| 128 |
+
|
| 129 |
+
for index in range(mel_filter_total):
|
| 130 |
+
start = indices[index]
|
| 131 |
+
end = indices[index + 1]
|
| 132 |
+
mel_filter_bank[index, start:end] = scipy.signal.windows.triang(end - start)
|
| 133 |
+
|
| 134 |
+
return mel_filter_bank
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def create_spectrogram(audio : Audio) -> Spectrogram:
|
| 138 |
+
mel_bin_total = 800
|
| 139 |
+
mel_bin_overlap = 600
|
| 140 |
+
mel_filter_bank = create_mel_filter_bank()
|
| 141 |
+
spectrogram = scipy.signal.stft(audio, nperseg = mel_bin_total, nfft = mel_bin_total, noverlap = mel_bin_overlap)[2]
|
| 142 |
+
spectrogram = numpy.dot(mel_filter_bank, numpy.abs(spectrogram))
|
| 143 |
+
return spectrogram
|
facefusion/benchmarker.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
import os
|
| 3 |
+
import statistics
|
| 4 |
+
import tempfile
|
| 5 |
+
from time import perf_counter
|
| 6 |
+
from typing import Iterator, List
|
| 7 |
+
|
| 8 |
+
import facefusion.choices
|
| 9 |
+
from facefusion import content_analyser, core, state_manager
|
| 10 |
+
from facefusion.cli_helper import render_table
|
| 11 |
+
from facefusion.download import conditional_download, resolve_download_url
|
| 12 |
+
from facefusion.face_store import clear_static_faces
|
| 13 |
+
from facefusion.filesystem import get_file_extension
|
| 14 |
+
from facefusion.types import BenchmarkCycleSet
|
| 15 |
+
from facefusion.vision import count_video_frame_total, detect_video_fps
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def pre_check() -> bool:
|
| 19 |
+
conditional_download('.assets/examples',
|
| 20 |
+
[
|
| 21 |
+
resolve_download_url('examples-3.0.0', 'source.jpg'),
|
| 22 |
+
resolve_download_url('examples-3.0.0', 'source.mp3'),
|
| 23 |
+
resolve_download_url('examples-3.0.0', 'target-240p.mp4'),
|
| 24 |
+
resolve_download_url('examples-3.0.0', 'target-360p.mp4'),
|
| 25 |
+
resolve_download_url('examples-3.0.0', 'target-540p.mp4'),
|
| 26 |
+
resolve_download_url('examples-3.0.0', 'target-720p.mp4'),
|
| 27 |
+
resolve_download_url('examples-3.0.0', 'target-1080p.mp4'),
|
| 28 |
+
resolve_download_url('examples-3.0.0', 'target-1440p.mp4'),
|
| 29 |
+
resolve_download_url('examples-3.0.0', 'target-2160p.mp4')
|
| 30 |
+
])
|
| 31 |
+
return True
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def run() -> Iterator[List[BenchmarkCycleSet]]:
|
| 35 |
+
benchmark_resolutions = state_manager.get_item('benchmark_resolutions')
|
| 36 |
+
benchmark_cycle_count = state_manager.get_item('benchmark_cycle_count')
|
| 37 |
+
|
| 38 |
+
state_manager.init_item('source_paths', [ '.assets/examples/source.jpg', '.assets/examples/source.mp3' ])
|
| 39 |
+
state_manager.init_item('face_landmarker_score', 0)
|
| 40 |
+
state_manager.init_item('temp_frame_format', 'bmp')
|
| 41 |
+
state_manager.init_item('output_audio_volume', 0)
|
| 42 |
+
state_manager.init_item('output_video_preset', 'ultrafast')
|
| 43 |
+
state_manager.init_item('video_memory_strategy', 'tolerant')
|
| 44 |
+
|
| 45 |
+
benchmarks = []
|
| 46 |
+
target_paths = [ facefusion.choices.benchmark_set.get(benchmark_resolution) for benchmark_resolution in benchmark_resolutions if benchmark_resolution in facefusion.choices.benchmark_set ]
|
| 47 |
+
|
| 48 |
+
for target_path in target_paths:
|
| 49 |
+
state_manager.init_item('target_path', target_path)
|
| 50 |
+
state_manager.init_item('output_path', suggest_output_path(state_manager.get_item('target_path')))
|
| 51 |
+
benchmarks.append(cycle(benchmark_cycle_count))
|
| 52 |
+
yield benchmarks
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def cycle(cycle_count : int) -> BenchmarkCycleSet:
|
| 56 |
+
process_times = []
|
| 57 |
+
video_frame_total = count_video_frame_total(state_manager.get_item('target_path'))
|
| 58 |
+
state_manager.init_item('output_video_fps', detect_video_fps(state_manager.get_item('target_path')))
|
| 59 |
+
|
| 60 |
+
if state_manager.get_item('benchmark_mode') == 'warm':
|
| 61 |
+
core.conditional_process()
|
| 62 |
+
|
| 63 |
+
for index in range(cycle_count):
|
| 64 |
+
if state_manager.get_item('benchmark_mode') == 'cold':
|
| 65 |
+
content_analyser.analyse_image.cache_clear()
|
| 66 |
+
content_analyser.analyse_video.cache_clear()
|
| 67 |
+
clear_static_faces()
|
| 68 |
+
|
| 69 |
+
start_time = perf_counter()
|
| 70 |
+
core.conditional_process()
|
| 71 |
+
end_time = perf_counter()
|
| 72 |
+
process_times.append(end_time - start_time)
|
| 73 |
+
|
| 74 |
+
average_run = round(statistics.mean(process_times), 2)
|
| 75 |
+
fastest_run = round(min(process_times), 2)
|
| 76 |
+
slowest_run = round(max(process_times), 2)
|
| 77 |
+
relative_fps = round(video_frame_total * cycle_count / sum(process_times), 2)
|
| 78 |
+
|
| 79 |
+
return\
|
| 80 |
+
{
|
| 81 |
+
'target_path': state_manager.get_item('target_path'),
|
| 82 |
+
'cycle_count': cycle_count,
|
| 83 |
+
'average_run': average_run,
|
| 84 |
+
'fastest_run': fastest_run,
|
| 85 |
+
'slowest_run': slowest_run,
|
| 86 |
+
'relative_fps': relative_fps
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def suggest_output_path(target_path : str) -> str:
|
| 91 |
+
target_file_extension = get_file_extension(target_path)
|
| 92 |
+
return os.path.join(tempfile.gettempdir(), hashlib.sha1().hexdigest()[:8] + target_file_extension)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def render() -> None:
|
| 96 |
+
benchmarks = []
|
| 97 |
+
headers =\
|
| 98 |
+
[
|
| 99 |
+
'target_path',
|
| 100 |
+
'cycle_count',
|
| 101 |
+
'average_run',
|
| 102 |
+
'fastest_run',
|
| 103 |
+
'slowest_run',
|
| 104 |
+
'relative_fps'
|
| 105 |
+
]
|
| 106 |
+
|
| 107 |
+
for benchmark in run():
|
| 108 |
+
benchmarks = benchmark
|
| 109 |
+
|
| 110 |
+
contents = [ list(benchmark_set.values()) for benchmark_set in benchmarks ]
|
| 111 |
+
render_table(headers, contents)
|
facefusion/camera_manager.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List
|
| 2 |
+
|
| 3 |
+
import cv2
|
| 4 |
+
|
| 5 |
+
from facefusion.types import CameraPoolSet
|
| 6 |
+
|
| 7 |
+
CAMERA_POOL_SET : CameraPoolSet =\
|
| 8 |
+
{
|
| 9 |
+
'capture': {}
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def get_local_camera_capture(camera_id : int) -> cv2.VideoCapture:
|
| 14 |
+
camera_key = str(camera_id)
|
| 15 |
+
|
| 16 |
+
if camera_key not in CAMERA_POOL_SET.get('capture'):
|
| 17 |
+
camera_capture = cv2.VideoCapture(camera_id)
|
| 18 |
+
|
| 19 |
+
if camera_capture.isOpened():
|
| 20 |
+
CAMERA_POOL_SET['capture'][camera_key] = camera_capture
|
| 21 |
+
|
| 22 |
+
return CAMERA_POOL_SET.get('capture').get(camera_key)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def get_remote_camera_capture(camera_url : str) -> cv2.VideoCapture:
|
| 26 |
+
if camera_url not in CAMERA_POOL_SET.get('capture'):
|
| 27 |
+
camera_capture = cv2.VideoCapture(camera_url)
|
| 28 |
+
|
| 29 |
+
if camera_capture.isOpened():
|
| 30 |
+
CAMERA_POOL_SET['capture'][camera_url] = camera_capture
|
| 31 |
+
|
| 32 |
+
return CAMERA_POOL_SET.get('capture').get(camera_url)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def clear_camera_pool() -> None:
|
| 36 |
+
for camera_capture in CAMERA_POOL_SET.get('capture').values():
|
| 37 |
+
camera_capture.release()
|
| 38 |
+
|
| 39 |
+
CAMERA_POOL_SET['capture'].clear()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def detect_local_camera_ids(id_start : int, id_end : int) -> List[int]:
|
| 43 |
+
local_camera_ids = []
|
| 44 |
+
|
| 45 |
+
for camera_id in range(id_start, id_end):
|
| 46 |
+
cv2.setLogLevel(0)
|
| 47 |
+
camera_capture = get_local_camera_capture(camera_id)
|
| 48 |
+
cv2.setLogLevel(3)
|
| 49 |
+
|
| 50 |
+
if camera_capture and camera_capture.isOpened():
|
| 51 |
+
local_camera_ids.append(camera_id)
|
| 52 |
+
|
| 53 |
+
return local_camera_ids
|
facefusion/choices.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from typing import List, Sequence
|
| 3 |
+
|
| 4 |
+
from facefusion.common_helper import create_float_range, create_int_range
|
| 5 |
+
from facefusion.types import Angle, AudioEncoder, AudioFormat, AudioTypeSet, BenchmarkMode, BenchmarkResolution, BenchmarkSet, DownloadProvider, DownloadProviderSet, DownloadScope, EncoderSet, ExecutionProvider, ExecutionProviderSet, FaceDetectorModel, FaceDetectorSet, FaceLandmarkerModel, FaceMaskArea, FaceMaskAreaSet, FaceMaskRegion, FaceMaskRegionSet, FaceMaskType, FaceOccluderModel, FaceParserModel, FaceSelectorMode, FaceSelectorOrder, Gender, ImageFormat, ImageTypeSet, JobStatus, LogLevel, LogLevelSet, Race, Score, TempFrameFormat, UiWorkflow, VideoEncoder, VideoFormat, VideoMemoryStrategy, VideoPreset, VideoTypeSet, VoiceExtractorModel
|
| 6 |
+
|
| 7 |
+
face_detector_set : FaceDetectorSet =\
|
| 8 |
+
{
|
| 9 |
+
'many': [ '640x640' ],
|
| 10 |
+
'retinaface': [ '160x160', '320x320', '480x480', '512x512', '640x640' ],
|
| 11 |
+
'scrfd': [ '160x160', '320x320', '480x480', '512x512', '640x640' ],
|
| 12 |
+
'yolo_face': [ '640x640' ],
|
| 13 |
+
'yunet': [ '640x640' ]
|
| 14 |
+
}
|
| 15 |
+
face_detector_models : List[FaceDetectorModel] = list(face_detector_set.keys())
|
| 16 |
+
face_landmarker_models : List[FaceLandmarkerModel] = [ 'many', '2dfan4', 'peppa_wutz' ]
|
| 17 |
+
face_selector_modes : List[FaceSelectorMode] = [ 'many', 'one', 'reference' ]
|
| 18 |
+
face_selector_orders : List[FaceSelectorOrder] = [ 'left-right', 'right-left', 'top-bottom', 'bottom-top', 'small-large', 'large-small', 'best-worst', 'worst-best' ]
|
| 19 |
+
face_selector_genders : List[Gender] = [ 'female', 'male' ]
|
| 20 |
+
face_selector_races : List[Race] = [ 'white', 'black', 'latino', 'asian', 'indian', 'arabic' ]
|
| 21 |
+
face_occluder_models : List[FaceOccluderModel] = [ 'many', 'xseg_1', 'xseg_2', 'xseg_3' ]
|
| 22 |
+
face_parser_models : List[FaceParserModel] = [ 'bisenet_resnet_18', 'bisenet_resnet_34' ]
|
| 23 |
+
face_mask_types : List[FaceMaskType] = [ 'box', 'occlusion', 'area', 'region' ]
|
| 24 |
+
face_mask_area_set : FaceMaskAreaSet =\
|
| 25 |
+
{
|
| 26 |
+
'upper-face': [ 0, 1, 2, 31, 32, 33, 34, 35, 14, 15, 16, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17 ],
|
| 27 |
+
'lower-face': [ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 35, 34, 33, 32, 31 ],
|
| 28 |
+
'mouth': [ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67 ]
|
| 29 |
+
}
|
| 30 |
+
face_mask_region_set : FaceMaskRegionSet =\
|
| 31 |
+
{
|
| 32 |
+
'skin': 1,
|
| 33 |
+
'left-eyebrow': 2,
|
| 34 |
+
'right-eyebrow': 3,
|
| 35 |
+
'left-eye': 4,
|
| 36 |
+
'right-eye': 5,
|
| 37 |
+
'glasses': 6,
|
| 38 |
+
'nose': 10,
|
| 39 |
+
'mouth': 11,
|
| 40 |
+
'upper-lip': 12,
|
| 41 |
+
'lower-lip': 13
|
| 42 |
+
}
|
| 43 |
+
face_mask_areas : List[FaceMaskArea] = list(face_mask_area_set.keys())
|
| 44 |
+
face_mask_regions : List[FaceMaskRegion] = list(face_mask_region_set.keys())
|
| 45 |
+
|
| 46 |
+
voice_extractor_models : List[VoiceExtractorModel] = [ 'kim_vocal_1', 'kim_vocal_2', 'uvr_mdxnet' ]
|
| 47 |
+
|
| 48 |
+
audio_type_set : AudioTypeSet =\
|
| 49 |
+
{
|
| 50 |
+
'flac': 'audio/flac',
|
| 51 |
+
'm4a': 'audio/mp4',
|
| 52 |
+
'mp3': 'audio/mpeg',
|
| 53 |
+
'ogg': 'audio/ogg',
|
| 54 |
+
'opus': 'audio/opus',
|
| 55 |
+
'wav': 'audio/x-wav'
|
| 56 |
+
}
|
| 57 |
+
image_type_set : ImageTypeSet =\
|
| 58 |
+
{
|
| 59 |
+
'bmp': 'image/bmp',
|
| 60 |
+
'jpeg': 'image/jpeg',
|
| 61 |
+
'png': 'image/png',
|
| 62 |
+
'tiff': 'image/tiff',
|
| 63 |
+
'webp': 'image/webp'
|
| 64 |
+
}
|
| 65 |
+
video_type_set : VideoTypeSet =\
|
| 66 |
+
{
|
| 67 |
+
'avi': 'video/x-msvideo',
|
| 68 |
+
'm4v': 'video/mp4',
|
| 69 |
+
'mkv': 'video/x-matroska',
|
| 70 |
+
'mp4': 'video/mp4',
|
| 71 |
+
'mpeg': 'video/mpeg',
|
| 72 |
+
'mov': 'video/quicktime',
|
| 73 |
+
'mxf': 'application/mxf',
|
| 74 |
+
'webm': 'video/webm',
|
| 75 |
+
'wmv': 'video/x-ms-wmv'
|
| 76 |
+
}
|
| 77 |
+
audio_formats : List[AudioFormat] = list(audio_type_set.keys())
|
| 78 |
+
image_formats : List[ImageFormat] = list(image_type_set.keys())
|
| 79 |
+
video_formats : List[VideoFormat] = list(video_type_set.keys())
|
| 80 |
+
temp_frame_formats : List[TempFrameFormat] = [ 'bmp', 'jpeg', 'png', 'tiff' ]
|
| 81 |
+
|
| 82 |
+
output_encoder_set : EncoderSet =\
|
| 83 |
+
{
|
| 84 |
+
'audio': [ 'flac', 'aac', 'libmp3lame', 'libopus', 'libvorbis', 'pcm_s16le', 'pcm_s32le' ],
|
| 85 |
+
'video': [ 'libx264', 'libx264rgb', 'libx265', 'libvpx-vp9', 'h264_nvenc', 'hevc_nvenc', 'h264_amf', 'hevc_amf', 'h264_qsv', 'hevc_qsv', 'h264_videotoolbox', 'hevc_videotoolbox', 'rawvideo' ]
|
| 86 |
+
}
|
| 87 |
+
output_audio_encoders : List[AudioEncoder] = output_encoder_set.get('audio')
|
| 88 |
+
output_video_encoders : List[VideoEncoder] = output_encoder_set.get('video')
|
| 89 |
+
output_video_presets : List[VideoPreset] = [ 'ultrafast', 'superfast', 'veryfast', 'faster', 'fast', 'medium', 'slow', 'slower', 'veryslow' ]
|
| 90 |
+
|
| 91 |
+
benchmark_modes : List[BenchmarkMode] = [ 'warm', 'cold' ]
|
| 92 |
+
benchmark_set : BenchmarkSet =\
|
| 93 |
+
{
|
| 94 |
+
'240p': '.assets/examples/target-240p.mp4',
|
| 95 |
+
'360p': '.assets/examples/target-360p.mp4',
|
| 96 |
+
'540p': '.assets/examples/target-540p.mp4',
|
| 97 |
+
'720p': '.assets/examples/target-720p.mp4',
|
| 98 |
+
'1080p': '.assets/examples/target-1080p.mp4',
|
| 99 |
+
'1440p': '.assets/examples/target-1440p.mp4',
|
| 100 |
+
'2160p': '.assets/examples/target-2160p.mp4'
|
| 101 |
+
}
|
| 102 |
+
benchmark_resolutions : List[BenchmarkResolution] = list(benchmark_set.keys())
|
| 103 |
+
|
| 104 |
+
execution_provider_set : ExecutionProviderSet =\
|
| 105 |
+
{
|
| 106 |
+
'cuda': 'CUDAExecutionProvider',
|
| 107 |
+
'tensorrt': 'TensorrtExecutionProvider',
|
| 108 |
+
'directml': 'DmlExecutionProvider',
|
| 109 |
+
'rocm': 'ROCMExecutionProvider',
|
| 110 |
+
'migraphx': 'MIGraphXExecutionProvider',
|
| 111 |
+
'openvino': 'OpenVINOExecutionProvider',
|
| 112 |
+
'coreml': 'CoreMLExecutionProvider',
|
| 113 |
+
'cpu': 'CPUExecutionProvider'
|
| 114 |
+
}
|
| 115 |
+
execution_providers : List[ExecutionProvider] = list(execution_provider_set.keys())
|
| 116 |
+
download_provider_set : DownloadProviderSet =\
|
| 117 |
+
{
|
| 118 |
+
'github':
|
| 119 |
+
{
|
| 120 |
+
'urls':
|
| 121 |
+
[
|
| 122 |
+
'https://github.com'
|
| 123 |
+
],
|
| 124 |
+
'path': '/facefusion/facefusion-assets/releases/download/{base_name}/{file_name}'
|
| 125 |
+
},
|
| 126 |
+
'huggingface':
|
| 127 |
+
{
|
| 128 |
+
'urls':
|
| 129 |
+
[
|
| 130 |
+
'https://huggingface.co',
|
| 131 |
+
'https://hf-mirror.com'
|
| 132 |
+
],
|
| 133 |
+
'path': '/facefusion/{base_name}/resolve/main/{file_name}'
|
| 134 |
+
}
|
| 135 |
+
}
|
| 136 |
+
download_providers : List[DownloadProvider] = list(download_provider_set.keys())
|
| 137 |
+
download_scopes : List[DownloadScope] = [ 'lite', 'full' ]
|
| 138 |
+
|
| 139 |
+
video_memory_strategies : List[VideoMemoryStrategy] = [ 'strict', 'moderate', 'tolerant' ]
|
| 140 |
+
|
| 141 |
+
log_level_set : LogLevelSet =\
|
| 142 |
+
{
|
| 143 |
+
'error': logging.ERROR,
|
| 144 |
+
'warn': logging.WARNING,
|
| 145 |
+
'info': logging.INFO,
|
| 146 |
+
'debug': logging.DEBUG
|
| 147 |
+
}
|
| 148 |
+
log_levels : List[LogLevel] = list(log_level_set.keys())
|
| 149 |
+
|
| 150 |
+
ui_workflows : List[UiWorkflow] = [ 'instant_runner', 'job_runner', 'job_manager' ]
|
| 151 |
+
job_statuses : List[JobStatus] = [ 'drafted', 'queued', 'completed', 'failed' ]
|
| 152 |
+
|
| 153 |
+
benchmark_cycle_count_range : Sequence[int] = create_int_range(1, 10, 1)
|
| 154 |
+
execution_thread_count_range : Sequence[int] = create_int_range(1, 32, 1)
|
| 155 |
+
system_memory_limit_range : Sequence[int] = create_int_range(0, 128, 4)
|
| 156 |
+
face_detector_margin_range : Sequence[int] = create_int_range(0, 100, 1)
|
| 157 |
+
face_detector_angles : Sequence[Angle] = create_int_range(0, 270, 90)
|
| 158 |
+
face_detector_score_range : Sequence[Score] = create_float_range(0.0, 1.0, 0.05)
|
| 159 |
+
face_landmarker_score_range : Sequence[Score] = create_float_range(0.0, 1.0, 0.05)
|
| 160 |
+
face_mask_blur_range : Sequence[float] = create_float_range(0.0, 1.0, 0.05)
|
| 161 |
+
face_mask_padding_range : Sequence[int] = create_int_range(0, 100, 1)
|
| 162 |
+
face_selector_age_range : Sequence[int] = create_int_range(0, 100, 1)
|
| 163 |
+
reference_face_distance_range : Sequence[float] = create_float_range(0.0, 1.0, 0.05)
|
| 164 |
+
output_image_quality_range : Sequence[int] = create_int_range(0, 100, 1)
|
| 165 |
+
output_image_scale_range : Sequence[float] = create_float_range(0.25, 8.0, 0.25)
|
| 166 |
+
output_audio_quality_range : Sequence[int] = create_int_range(0, 100, 1)
|
| 167 |
+
output_audio_volume_range : Sequence[int] = create_int_range(0, 100, 1)
|
| 168 |
+
output_video_quality_range : Sequence[int] = create_int_range(0, 100, 1)
|
| 169 |
+
output_video_scale_range : Sequence[float] = create_float_range(0.25, 8.0, 0.25)
|
facefusion/cli_helper.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Tuple
|
| 2 |
+
|
| 3 |
+
from facefusion.logger import get_package_logger
|
| 4 |
+
from facefusion.types import TableContent, TableHeader
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def render_table(headers : List[TableHeader], contents : List[List[TableContent]]) -> None:
|
| 8 |
+
package_logger = get_package_logger()
|
| 9 |
+
table_column, table_separator = create_table_parts(headers, contents)
|
| 10 |
+
|
| 11 |
+
package_logger.critical(table_separator)
|
| 12 |
+
package_logger.critical(table_column.format(*headers))
|
| 13 |
+
package_logger.critical(table_separator)
|
| 14 |
+
|
| 15 |
+
for content in contents:
|
| 16 |
+
content = [ str(value) for value in content ]
|
| 17 |
+
package_logger.critical(table_column.format(*content))
|
| 18 |
+
|
| 19 |
+
package_logger.critical(table_separator)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def create_table_parts(headers : List[TableHeader], contents : List[List[TableContent]]) -> Tuple[str, str]:
|
| 23 |
+
column_parts = []
|
| 24 |
+
separator_parts = []
|
| 25 |
+
widths = [ len(header) for header in headers ]
|
| 26 |
+
|
| 27 |
+
for content in contents:
|
| 28 |
+
for index, value in enumerate(content):
|
| 29 |
+
widths[index] = max(widths[index], len(str(value)))
|
| 30 |
+
|
| 31 |
+
for width in widths:
|
| 32 |
+
column_parts.append('{:<' + str(width) + '}')
|
| 33 |
+
separator_parts.append('-' * width)
|
| 34 |
+
|
| 35 |
+
return '| ' + ' | '.join(column_parts) + ' |', '+-' + '-+-'.join(separator_parts) + '-+'
|
facefusion/common_helper.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import platform
|
| 2 |
+
from typing import Any, Iterable, Optional, Reversible, Sequence
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def is_linux() -> bool:
|
| 6 |
+
return platform.system().lower() == 'linux'
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def is_macos() -> bool:
|
| 10 |
+
return platform.system().lower() == 'darwin'
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def is_windows() -> bool:
|
| 14 |
+
return platform.system().lower() == 'windows'
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def create_int_metavar(int_range : Sequence[int]) -> str:
|
| 18 |
+
return '[' + str(int_range[0]) + '..' + str(int_range[-1]) + ':' + str(calculate_int_step(int_range)) + ']'
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def create_float_metavar(float_range : Sequence[float]) -> str:
|
| 22 |
+
return '[' + str(float_range[0]) + '..' + str(float_range[-1]) + ':' + str(calculate_float_step(float_range)) + ']'
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def create_int_range(start : int, end : int, step : int) -> Sequence[int]:
|
| 26 |
+
int_range = []
|
| 27 |
+
current = start
|
| 28 |
+
|
| 29 |
+
while current <= end:
|
| 30 |
+
int_range.append(current)
|
| 31 |
+
current += step
|
| 32 |
+
return int_range
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def create_float_range(start : float, end : float, step : float) -> Sequence[float]:
|
| 36 |
+
float_range = []
|
| 37 |
+
current = start
|
| 38 |
+
|
| 39 |
+
while current <= end:
|
| 40 |
+
float_range.append(round(current, 2))
|
| 41 |
+
current = round(current + step, 2)
|
| 42 |
+
return float_range
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def calculate_int_step(int_range : Sequence[int]) -> int:
|
| 46 |
+
return int_range[1] - int_range[0]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def calculate_float_step(float_range : Sequence[float]) -> float:
|
| 50 |
+
return round(float_range[1] - float_range[0], 2)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def cast_int(value : Any) -> Optional[int]:
|
| 54 |
+
try:
|
| 55 |
+
return int(value)
|
| 56 |
+
except (ValueError, TypeError):
|
| 57 |
+
return None
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def cast_float(value : Any) -> Optional[float]:
|
| 61 |
+
try:
|
| 62 |
+
return float(value)
|
| 63 |
+
except (ValueError, TypeError):
|
| 64 |
+
return None
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def cast_bool(value : Any) -> Optional[bool]:
|
| 68 |
+
if value == 'True':
|
| 69 |
+
return True
|
| 70 |
+
if value == 'False':
|
| 71 |
+
return False
|
| 72 |
+
return None
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def get_first(__list__ : Any) -> Any:
|
| 76 |
+
if isinstance(__list__, Iterable):
|
| 77 |
+
return next(iter(__list__), None)
|
| 78 |
+
return None
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def get_last(__list__ : Any) -> Any:
|
| 82 |
+
if isinstance(__list__, Reversible):
|
| 83 |
+
return next(reversed(__list__), None)
|
| 84 |
+
return None
|
facefusion/config.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from configparser import ConfigParser
|
| 2 |
+
from typing import List, Optional
|
| 3 |
+
|
| 4 |
+
from facefusion import state_manager
|
| 5 |
+
from facefusion.common_helper import cast_bool, cast_float, cast_int
|
| 6 |
+
|
| 7 |
+
CONFIG_PARSER = None
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def get_config_parser() -> ConfigParser:
|
| 11 |
+
global CONFIG_PARSER
|
| 12 |
+
|
| 13 |
+
if CONFIG_PARSER is None:
|
| 14 |
+
CONFIG_PARSER = ConfigParser()
|
| 15 |
+
CONFIG_PARSER.read(state_manager.get_item('config_path'), encoding = 'utf-8')
|
| 16 |
+
return CONFIG_PARSER
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def clear_config_parser() -> None:
|
| 20 |
+
global CONFIG_PARSER
|
| 21 |
+
|
| 22 |
+
CONFIG_PARSER = None
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def get_str_value(section : str, option : str, fallback : Optional[str] = None) -> Optional[str]:
|
| 26 |
+
config_parser = get_config_parser()
|
| 27 |
+
|
| 28 |
+
if config_parser.has_option(section, option) and config_parser.get(section, option).strip():
|
| 29 |
+
return config_parser.get(section, option)
|
| 30 |
+
return fallback
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def get_int_value(section : str, option : str, fallback : Optional[str] = None) -> Optional[int]:
|
| 34 |
+
config_parser = get_config_parser()
|
| 35 |
+
|
| 36 |
+
if config_parser.has_option(section, option) and config_parser.get(section, option).strip():
|
| 37 |
+
return config_parser.getint(section, option)
|
| 38 |
+
return cast_int(fallback)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def get_float_value(section : str, option : str, fallback : Optional[str] = None) -> Optional[float]:
|
| 42 |
+
config_parser = get_config_parser()
|
| 43 |
+
|
| 44 |
+
if config_parser.has_option(section, option) and config_parser.get(section, option).strip():
|
| 45 |
+
return config_parser.getfloat(section, option)
|
| 46 |
+
return cast_float(fallback)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def get_bool_value(section : str, option : str, fallback : Optional[str] = None) -> Optional[bool]:
|
| 50 |
+
config_parser = get_config_parser()
|
| 51 |
+
|
| 52 |
+
if config_parser.has_option(section, option) and config_parser.get(section, option).strip():
|
| 53 |
+
return config_parser.getboolean(section, option)
|
| 54 |
+
return cast_bool(fallback)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def get_str_list(section : str, option : str, fallback : Optional[str] = None) -> Optional[List[str]]:
|
| 58 |
+
config_parser = get_config_parser()
|
| 59 |
+
|
| 60 |
+
if config_parser.has_option(section, option) and config_parser.get(section, option).strip():
|
| 61 |
+
return config_parser.get(section, option).split()
|
| 62 |
+
if fallback:
|
| 63 |
+
return fallback.split()
|
| 64 |
+
return None
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def get_int_list(section : str, option : str, fallback : Optional[str] = None) -> Optional[List[int]]:
|
| 68 |
+
config_parser = get_config_parser()
|
| 69 |
+
|
| 70 |
+
if config_parser.has_option(section, option) and config_parser.get(section, option).strip():
|
| 71 |
+
return list(map(int, config_parser.get(section, option).split()))
|
| 72 |
+
if fallback:
|
| 73 |
+
return list(map(int, fallback.split()))
|
| 74 |
+
return None
|
facefusion/content_analyser.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
from typing import List, Tuple
|
| 3 |
+
|
| 4 |
+
import numpy
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
|
| 7 |
+
from facefusion import inference_manager, state_manager, translator
|
| 8 |
+
from facefusion.common_helper import is_macos
|
| 9 |
+
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
| 10 |
+
from facefusion.execution import has_execution_provider
|
| 11 |
+
from facefusion.filesystem import resolve_relative_path
|
| 12 |
+
from facefusion.thread_helper import conditional_thread_semaphore
|
| 13 |
+
from facefusion.types import Detection, DownloadScope, DownloadSet, ExecutionProvider, Fps, InferencePool, ModelSet, VisionFrame
|
| 14 |
+
from facefusion.vision import detect_video_fps, fit_contain_frame, read_image, read_video_frame
|
| 15 |
+
|
| 16 |
+
STREAM_COUNTER = 0
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@lru_cache()
|
| 20 |
+
def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
| 21 |
+
return\
|
| 22 |
+
{
|
| 23 |
+
'nsfw_1':
|
| 24 |
+
{
|
| 25 |
+
'__metadata__':
|
| 26 |
+
{
|
| 27 |
+
'vendor': 'EraX',
|
| 28 |
+
'license': 'Apache-2.0',
|
| 29 |
+
'year': 2024
|
| 30 |
+
},
|
| 31 |
+
'hashes':
|
| 32 |
+
{
|
| 33 |
+
'content_analyser':
|
| 34 |
+
{
|
| 35 |
+
'url': resolve_download_url('models-3.3.0', 'nsfw_1.hash'),
|
| 36 |
+
'path': resolve_relative_path('../.assets/models/nsfw_1.hash')
|
| 37 |
+
}
|
| 38 |
+
},
|
| 39 |
+
'sources':
|
| 40 |
+
{
|
| 41 |
+
'content_analyser':
|
| 42 |
+
{
|
| 43 |
+
'url': resolve_download_url('models-3.3.0', 'nsfw_1.onnx'),
|
| 44 |
+
'path': resolve_relative_path('../.assets/models/nsfw_1.onnx')
|
| 45 |
+
}
|
| 46 |
+
},
|
| 47 |
+
'size': (640, 640),
|
| 48 |
+
'mean': (0.0, 0.0, 0.0),
|
| 49 |
+
'standard_deviation': (1.0, 1.0, 1.0)
|
| 50 |
+
},
|
| 51 |
+
'nsfw_2':
|
| 52 |
+
{
|
| 53 |
+
'__metadata__':
|
| 54 |
+
{
|
| 55 |
+
'vendor': 'Marqo',
|
| 56 |
+
'license': 'Apache-2.0',
|
| 57 |
+
'year': 2024
|
| 58 |
+
},
|
| 59 |
+
'hashes':
|
| 60 |
+
{
|
| 61 |
+
'content_analyser':
|
| 62 |
+
{
|
| 63 |
+
'url': resolve_download_url('models-3.3.0', 'nsfw_2.hash'),
|
| 64 |
+
'path': resolve_relative_path('../.assets/models/nsfw_2.hash')
|
| 65 |
+
}
|
| 66 |
+
},
|
| 67 |
+
'sources':
|
| 68 |
+
{
|
| 69 |
+
'content_analyser':
|
| 70 |
+
{
|
| 71 |
+
'url': resolve_download_url('models-3.3.0', 'nsfw_2.onnx'),
|
| 72 |
+
'path': resolve_relative_path('../.assets/models/nsfw_2.onnx')
|
| 73 |
+
}
|
| 74 |
+
},
|
| 75 |
+
'size': (384, 384),
|
| 76 |
+
'mean': (0.5, 0.5, 0.5),
|
| 77 |
+
'standard_deviation': (0.5, 0.5, 0.5)
|
| 78 |
+
},
|
| 79 |
+
'nsfw_3':
|
| 80 |
+
{
|
| 81 |
+
'__metadata__':
|
| 82 |
+
{
|
| 83 |
+
'vendor': 'Freepik',
|
| 84 |
+
'license': 'MIT',
|
| 85 |
+
'year': 2025
|
| 86 |
+
},
|
| 87 |
+
'hashes':
|
| 88 |
+
{
|
| 89 |
+
'content_analyser':
|
| 90 |
+
{
|
| 91 |
+
'url': resolve_download_url('models-3.3.0', 'nsfw_3.hash'),
|
| 92 |
+
'path': resolve_relative_path('../.assets/models/nsfw_3.hash')
|
| 93 |
+
}
|
| 94 |
+
},
|
| 95 |
+
'sources':
|
| 96 |
+
{
|
| 97 |
+
'content_analyser':
|
| 98 |
+
{
|
| 99 |
+
'url': resolve_download_url('models-3.3.0', 'nsfw_3.onnx'),
|
| 100 |
+
'path': resolve_relative_path('../.assets/models/nsfw_3.onnx')
|
| 101 |
+
}
|
| 102 |
+
},
|
| 103 |
+
'size': (448, 448),
|
| 104 |
+
'mean': (0.48145466, 0.4578275, 0.40821073),
|
| 105 |
+
'standard_deviation': (0.26862954, 0.26130258, 0.27577711)
|
| 106 |
+
}
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def get_inference_pool() -> InferencePool:
|
| 111 |
+
model_names = [ 'nsfw_1', 'nsfw_2', 'nsfw_3' ]
|
| 112 |
+
_, model_source_set = collect_model_downloads()
|
| 113 |
+
|
| 114 |
+
return inference_manager.get_inference_pool(__name__, model_names, model_source_set)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def clear_inference_pool() -> None:
|
| 118 |
+
model_names = [ 'nsfw_1', 'nsfw_2', 'nsfw_3' ]
|
| 119 |
+
inference_manager.clear_inference_pool(__name__, model_names)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def resolve_execution_providers() -> List[ExecutionProvider]:
|
| 123 |
+
if is_macos() and has_execution_provider('coreml'):
|
| 124 |
+
return [ 'cpu' ]
|
| 125 |
+
return state_manager.get_item('execution_providers')
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def collect_model_downloads() -> Tuple[DownloadSet, DownloadSet]:
|
| 129 |
+
model_set = create_static_model_set('full')
|
| 130 |
+
model_hash_set = {}
|
| 131 |
+
model_source_set = {}
|
| 132 |
+
|
| 133 |
+
for content_analyser_model in [ 'nsfw_1', 'nsfw_2', 'nsfw_3' ]:
|
| 134 |
+
model_hash_set[content_analyser_model] = model_set.get(content_analyser_model).get('hashes').get('content_analyser')
|
| 135 |
+
model_source_set[content_analyser_model] = model_set.get(content_analyser_model).get('sources').get('content_analyser')
|
| 136 |
+
|
| 137 |
+
return model_hash_set, model_source_set
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def pre_check() -> bool:
|
| 141 |
+
model_hash_set, model_source_set = collect_model_downloads()
|
| 142 |
+
|
| 143 |
+
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def analyse_stream(vision_frame : VisionFrame, video_fps : Fps) -> bool:
|
| 147 |
+
global STREAM_COUNTER
|
| 148 |
+
|
| 149 |
+
STREAM_COUNTER = STREAM_COUNTER + 1
|
| 150 |
+
if STREAM_COUNTER % int(video_fps) == 0:
|
| 151 |
+
return analyse_frame(vision_frame)
|
| 152 |
+
return False
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def analyse_frame(vision_frame : VisionFrame) -> bool:
|
| 156 |
+
return detect_nsfw(vision_frame)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@lru_cache()
|
| 160 |
+
def analyse_image(image_path : str) -> bool:
|
| 161 |
+
vision_frame = read_image(image_path)
|
| 162 |
+
return analyse_frame(vision_frame)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@lru_cache()
|
| 166 |
+
def analyse_video(video_path : str, trim_frame_start : int, trim_frame_end : int) -> bool:
|
| 167 |
+
video_fps = detect_video_fps(video_path)
|
| 168 |
+
frame_range = range(trim_frame_start, trim_frame_end)
|
| 169 |
+
rate = 0.0
|
| 170 |
+
total = 0
|
| 171 |
+
counter = 0
|
| 172 |
+
|
| 173 |
+
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:
|
| 174 |
+
|
| 175 |
+
for frame_number in frame_range:
|
| 176 |
+
if frame_number % int(video_fps) == 0:
|
| 177 |
+
vision_frame = read_video_frame(video_path, frame_number)
|
| 178 |
+
total += 1
|
| 179 |
+
|
| 180 |
+
if analyse_frame(vision_frame):
|
| 181 |
+
counter += 1
|
| 182 |
+
|
| 183 |
+
if counter > 0 and total > 0:
|
| 184 |
+
rate = counter / total * 100
|
| 185 |
+
|
| 186 |
+
progress.set_postfix(rate = rate)
|
| 187 |
+
progress.update()
|
| 188 |
+
|
| 189 |
+
return bool(rate > 10.0)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def detect_nsfw(vision_frame : VisionFrame) -> bool:
|
| 193 |
+
is_nsfw_1 = detect_with_nsfw_1(vision_frame)
|
| 194 |
+
is_nsfw_2 = detect_with_nsfw_2(vision_frame)
|
| 195 |
+
is_nsfw_3 = detect_with_nsfw_3(vision_frame)
|
| 196 |
+
|
| 197 |
+
return is_nsfw_1 and is_nsfw_2 or is_nsfw_1 and is_nsfw_3 or is_nsfw_2 and is_nsfw_3
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def detect_with_nsfw_1(vision_frame : VisionFrame) -> bool:
|
| 201 |
+
detect_vision_frame = prepare_detect_frame(vision_frame, 'nsfw_1')
|
| 202 |
+
detection = forward_nsfw(detect_vision_frame, 'nsfw_1')
|
| 203 |
+
detection_score = numpy.max(numpy.amax(detection[:, 4:], axis = 1))
|
| 204 |
+
return bool(detection_score > 0.2)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def detect_with_nsfw_2(vision_frame : VisionFrame) -> bool:
|
| 208 |
+
detect_vision_frame = prepare_detect_frame(vision_frame, 'nsfw_2')
|
| 209 |
+
detection = forward_nsfw(detect_vision_frame, 'nsfw_2')
|
| 210 |
+
detection_score = detection[0] - detection[1]
|
| 211 |
+
return bool(detection_score > 0.25)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def detect_with_nsfw_3(vision_frame : VisionFrame) -> bool:
|
| 215 |
+
detect_vision_frame = prepare_detect_frame(vision_frame, 'nsfw_3')
|
| 216 |
+
detection = forward_nsfw(detect_vision_frame, 'nsfw_3')
|
| 217 |
+
detection_score = (detection[2] + detection[3]) - (detection[0] + detection[1])
|
| 218 |
+
return bool(detection_score > 10.5)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def forward_nsfw(vision_frame : VisionFrame, model_name : str) -> Detection:
|
| 222 |
+
content_analyser = get_inference_pool().get(model_name)
|
| 223 |
+
|
| 224 |
+
with conditional_thread_semaphore():
|
| 225 |
+
detection = content_analyser.run(None,
|
| 226 |
+
{
|
| 227 |
+
'input': vision_frame
|
| 228 |
+
})[0]
|
| 229 |
+
|
| 230 |
+
if model_name in [ 'nsfw_2', 'nsfw_3' ]:
|
| 231 |
+
return detection[0]
|
| 232 |
+
|
| 233 |
+
return detection
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def prepare_detect_frame(temp_vision_frame : VisionFrame, model_name : str) -> VisionFrame:
|
| 237 |
+
model_set = create_static_model_set('full').get(model_name)
|
| 238 |
+
model_size = model_set.get('size')
|
| 239 |
+
model_mean = model_set.get('mean')
|
| 240 |
+
model_standard_deviation = model_set.get('standard_deviation')
|
| 241 |
+
|
| 242 |
+
detect_vision_frame = fit_contain_frame(temp_vision_frame, model_size)
|
| 243 |
+
detect_vision_frame = detect_vision_frame[:, :, ::-1] / 255.0
|
| 244 |
+
detect_vision_frame -= model_mean
|
| 245 |
+
detect_vision_frame /= model_standard_deviation
|
| 246 |
+
detect_vision_frame = numpy.expand_dims(detect_vision_frame.transpose(2, 0, 1), axis = 0).astype(numpy.float32)
|
| 247 |
+
return detect_vision_frame
|
facefusion/core.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import itertools
|
| 3 |
+
import shutil
|
| 4 |
+
import signal
|
| 5 |
+
import sys
|
| 6 |
+
from time import time
|
| 7 |
+
|
| 8 |
+
from facefusion import benchmarker, cli_helper, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, hash_helper, logger, state_manager, translator, voice_extractor
|
| 9 |
+
from facefusion.args import apply_args, collect_job_args, reduce_job_args, reduce_step_args
|
| 10 |
+
from facefusion.download import conditional_download_hashes, conditional_download_sources
|
| 11 |
+
from facefusion.exit_helper import hard_exit, signal_exit
|
| 12 |
+
from facefusion.filesystem import get_file_extension, get_file_name, is_image, is_video, resolve_file_paths, resolve_file_pattern
|
| 13 |
+
from facefusion.jobs import job_helper, job_manager, job_runner
|
| 14 |
+
from facefusion.jobs.job_list import compose_job_list
|
| 15 |
+
from facefusion.memory import limit_system_memory
|
| 16 |
+
from facefusion.processors.core import get_processors_modules
|
| 17 |
+
from facefusion.program import create_program
|
| 18 |
+
from facefusion.program_helper import validate_args
|
| 19 |
+
from facefusion.types import Args, ErrorCode
|
| 20 |
+
from facefusion.workflows import image_to_image, image_to_video
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def cli() -> None:
|
| 24 |
+
if pre_check():
|
| 25 |
+
signal.signal(signal.SIGINT, signal_exit)
|
| 26 |
+
program = create_program()
|
| 27 |
+
|
| 28 |
+
if validate_args(program):
|
| 29 |
+
args = vars(program.parse_args())
|
| 30 |
+
apply_args(args, state_manager.init_item)
|
| 31 |
+
|
| 32 |
+
if state_manager.get_item('command'):
|
| 33 |
+
logger.init(state_manager.get_item('log_level'))
|
| 34 |
+
route(args)
|
| 35 |
+
else:
|
| 36 |
+
program.print_help()
|
| 37 |
+
else:
|
| 38 |
+
hard_exit(2)
|
| 39 |
+
else:
|
| 40 |
+
hard_exit(2)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def route(args : Args) -> None:
|
| 44 |
+
system_memory_limit = state_manager.get_item('system_memory_limit')
|
| 45 |
+
|
| 46 |
+
if system_memory_limit and system_memory_limit > 0:
|
| 47 |
+
limit_system_memory(system_memory_limit)
|
| 48 |
+
|
| 49 |
+
if state_manager.get_item('command') == 'force-download':
|
| 50 |
+
error_code = force_download()
|
| 51 |
+
hard_exit(error_code)
|
| 52 |
+
|
| 53 |
+
if state_manager.get_item('command') == 'benchmark':
|
| 54 |
+
if not common_pre_check() or not processors_pre_check() or not benchmarker.pre_check():
|
| 55 |
+
hard_exit(2)
|
| 56 |
+
benchmarker.render()
|
| 57 |
+
|
| 58 |
+
if state_manager.get_item('command') in [ 'job-list', 'job-create', 'job-submit', 'job-submit-all', 'job-delete', 'job-delete-all', 'job-add-step', 'job-remix-step', 'job-insert-step', 'job-remove-step' ]:
|
| 59 |
+
if not job_manager.init_jobs(state_manager.get_item('jobs_path')):
|
| 60 |
+
hard_exit(1)
|
| 61 |
+
error_code = route_job_manager(args)
|
| 62 |
+
hard_exit(error_code)
|
| 63 |
+
|
| 64 |
+
if state_manager.get_item('command') == 'run':
|
| 65 |
+
import facefusion.uis.core as ui
|
| 66 |
+
|
| 67 |
+
if not common_pre_check() or not processors_pre_check():
|
| 68 |
+
hard_exit(2)
|
| 69 |
+
for ui_layout in ui.get_ui_layouts_modules(state_manager.get_item('ui_layouts')):
|
| 70 |
+
if not ui_layout.pre_check():
|
| 71 |
+
hard_exit(2)
|
| 72 |
+
ui.init()
|
| 73 |
+
ui.launch()
|
| 74 |
+
|
| 75 |
+
if state_manager.get_item('command') == 'headless-run':
|
| 76 |
+
if not job_manager.init_jobs(state_manager.get_item('jobs_path')):
|
| 77 |
+
hard_exit(1)
|
| 78 |
+
error_code = process_headless(args)
|
| 79 |
+
hard_exit(error_code)
|
| 80 |
+
|
| 81 |
+
if state_manager.get_item('command') == 'batch-run':
|
| 82 |
+
if not job_manager.init_jobs(state_manager.get_item('jobs_path')):
|
| 83 |
+
hard_exit(1)
|
| 84 |
+
error_code = process_batch(args)
|
| 85 |
+
hard_exit(error_code)
|
| 86 |
+
|
| 87 |
+
if state_manager.get_item('command') in [ 'job-run', 'job-run-all', 'job-retry', 'job-retry-all' ]:
|
| 88 |
+
if not job_manager.init_jobs(state_manager.get_item('jobs_path')):
|
| 89 |
+
hard_exit(1)
|
| 90 |
+
error_code = route_job_runner()
|
| 91 |
+
hard_exit(error_code)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def pre_check() -> bool:
|
| 95 |
+
if sys.version_info < (3, 10):
|
| 96 |
+
logger.error(translator.get('python_not_supported').format(version = '3.10'), __name__)
|
| 97 |
+
return False
|
| 98 |
+
|
| 99 |
+
if not shutil.which('curl'):
|
| 100 |
+
logger.error(translator.get('curl_not_installed'), __name__)
|
| 101 |
+
return False
|
| 102 |
+
|
| 103 |
+
if not shutil.which('ffmpeg'):
|
| 104 |
+
logger.error(translator.get('ffmpeg_not_installed'), __name__)
|
| 105 |
+
return False
|
| 106 |
+
return True
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def common_pre_check() -> bool:
|
| 110 |
+
common_modules =\
|
| 111 |
+
[
|
| 112 |
+
content_analyser,
|
| 113 |
+
face_classifier,
|
| 114 |
+
face_detector,
|
| 115 |
+
face_landmarker,
|
| 116 |
+
face_masker,
|
| 117 |
+
face_recognizer,
|
| 118 |
+
voice_extractor
|
| 119 |
+
]
|
| 120 |
+
|
| 121 |
+
content_analyser_content = inspect.getsource(content_analyser).encode()
|
| 122 |
+
content_analyser_hash = hash_helper.create_hash(content_analyser_content)
|
| 123 |
+
|
| 124 |
+
return all(module.pre_check() for module in common_modules) and content_analyser_hash == 'b14e7b92'
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def processors_pre_check() -> bool:
|
| 128 |
+
for processor_module in get_processors_modules(state_manager.get_item('processors')):
|
| 129 |
+
if not processor_module.pre_check():
|
| 130 |
+
return False
|
| 131 |
+
return True
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def force_download() -> ErrorCode:
|
| 135 |
+
common_modules =\
|
| 136 |
+
[
|
| 137 |
+
content_analyser,
|
| 138 |
+
face_classifier,
|
| 139 |
+
face_detector,
|
| 140 |
+
face_landmarker,
|
| 141 |
+
face_masker,
|
| 142 |
+
face_recognizer,
|
| 143 |
+
voice_extractor
|
| 144 |
+
]
|
| 145 |
+
available_processors = [ get_file_name(file_path) for file_path in resolve_file_paths('facefusion/processors/modules') ]
|
| 146 |
+
processor_modules = get_processors_modules(available_processors)
|
| 147 |
+
|
| 148 |
+
for module in common_modules + processor_modules:
|
| 149 |
+
if hasattr(module, 'create_static_model_set'):
|
| 150 |
+
for model in module.create_static_model_set(state_manager.get_item('download_scope')).values():
|
| 151 |
+
model_hash_set = model.get('hashes')
|
| 152 |
+
model_source_set = model.get('sources')
|
| 153 |
+
|
| 154 |
+
if model_hash_set and model_source_set:
|
| 155 |
+
if not conditional_download_hashes(model_hash_set) or not conditional_download_sources(model_source_set):
|
| 156 |
+
return 1
|
| 157 |
+
|
| 158 |
+
return 0
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def route_job_manager(args : Args) -> ErrorCode:
|
| 162 |
+
if state_manager.get_item('command') == 'job-list':
|
| 163 |
+
job_headers, job_contents = compose_job_list(state_manager.get_item('job_status'))
|
| 164 |
+
|
| 165 |
+
if job_contents:
|
| 166 |
+
cli_helper.render_table(job_headers, job_contents)
|
| 167 |
+
return 0
|
| 168 |
+
return 1
|
| 169 |
+
|
| 170 |
+
if state_manager.get_item('command') == 'job-create':
|
| 171 |
+
if job_manager.create_job(state_manager.get_item('job_id')):
|
| 172 |
+
logger.info(translator.get('job_created').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 173 |
+
return 0
|
| 174 |
+
logger.error(translator.get('job_not_created').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 175 |
+
return 1
|
| 176 |
+
|
| 177 |
+
if state_manager.get_item('command') == 'job-submit':
|
| 178 |
+
if job_manager.submit_job(state_manager.get_item('job_id')):
|
| 179 |
+
logger.info(translator.get('job_submitted').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 180 |
+
return 0
|
| 181 |
+
logger.error(translator.get('job_not_submitted').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 182 |
+
return 1
|
| 183 |
+
|
| 184 |
+
if state_manager.get_item('command') == 'job-submit-all':
|
| 185 |
+
if job_manager.submit_jobs(state_manager.get_item('halt_on_error')):
|
| 186 |
+
logger.info(translator.get('job_all_submitted'), __name__)
|
| 187 |
+
return 0
|
| 188 |
+
logger.error(translator.get('job_all_not_submitted'), __name__)
|
| 189 |
+
return 1
|
| 190 |
+
|
| 191 |
+
if state_manager.get_item('command') == 'job-delete':
|
| 192 |
+
if job_manager.delete_job(state_manager.get_item('job_id')):
|
| 193 |
+
logger.info(translator.get('job_deleted').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 194 |
+
return 0
|
| 195 |
+
logger.error(translator.get('job_not_deleted').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 196 |
+
return 1
|
| 197 |
+
|
| 198 |
+
if state_manager.get_item('command') == 'job-delete-all':
|
| 199 |
+
if job_manager.delete_jobs(state_manager.get_item('halt_on_error')):
|
| 200 |
+
logger.info(translator.get('job_all_deleted'), __name__)
|
| 201 |
+
return 0
|
| 202 |
+
logger.error(translator.get('job_all_not_deleted'), __name__)
|
| 203 |
+
return 1
|
| 204 |
+
|
| 205 |
+
if state_manager.get_item('command') == 'job-add-step':
|
| 206 |
+
step_args = reduce_step_args(args)
|
| 207 |
+
|
| 208 |
+
if job_manager.add_step(state_manager.get_item('job_id'), step_args):
|
| 209 |
+
logger.info(translator.get('job_step_added').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 210 |
+
return 0
|
| 211 |
+
logger.error(translator.get('job_step_not_added').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 212 |
+
return 1
|
| 213 |
+
|
| 214 |
+
if state_manager.get_item('command') == 'job-remix-step':
|
| 215 |
+
step_args = reduce_step_args(args)
|
| 216 |
+
|
| 217 |
+
if job_manager.remix_step(state_manager.get_item('job_id'), state_manager.get_item('step_index'), step_args):
|
| 218 |
+
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__)
|
| 219 |
+
return 0
|
| 220 |
+
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__)
|
| 221 |
+
return 1
|
| 222 |
+
|
| 223 |
+
if state_manager.get_item('command') == 'job-insert-step':
|
| 224 |
+
step_args = reduce_step_args(args)
|
| 225 |
+
|
| 226 |
+
if job_manager.insert_step(state_manager.get_item('job_id'), state_manager.get_item('step_index'), step_args):
|
| 227 |
+
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__)
|
| 228 |
+
return 0
|
| 229 |
+
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__)
|
| 230 |
+
return 1
|
| 231 |
+
|
| 232 |
+
if state_manager.get_item('command') == 'job-remove-step':
|
| 233 |
+
if job_manager.remove_step(state_manager.get_item('job_id'), state_manager.get_item('step_index')):
|
| 234 |
+
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__)
|
| 235 |
+
return 0
|
| 236 |
+
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__)
|
| 237 |
+
return 1
|
| 238 |
+
return 1
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def route_job_runner() -> ErrorCode:
|
| 242 |
+
if state_manager.get_item('command') == 'job-run':
|
| 243 |
+
logger.info(translator.get('running_job').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 244 |
+
if job_runner.run_job(state_manager.get_item('job_id'), process_step):
|
| 245 |
+
logger.info(translator.get('processing_job_succeeded').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 246 |
+
return 0
|
| 247 |
+
logger.info(translator.get('processing_job_failed').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 248 |
+
return 1
|
| 249 |
+
|
| 250 |
+
if state_manager.get_item('command') == 'job-run-all':
|
| 251 |
+
logger.info(translator.get('running_jobs'), __name__)
|
| 252 |
+
if job_runner.run_jobs(process_step, state_manager.get_item('halt_on_error')):
|
| 253 |
+
logger.info(translator.get('processing_jobs_succeeded'), __name__)
|
| 254 |
+
return 0
|
| 255 |
+
logger.info(translator.get('processing_jobs_failed'), __name__)
|
| 256 |
+
return 1
|
| 257 |
+
|
| 258 |
+
if state_manager.get_item('command') == 'job-retry':
|
| 259 |
+
logger.info(translator.get('retrying_job').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 260 |
+
if job_runner.retry_job(state_manager.get_item('job_id'), process_step):
|
| 261 |
+
logger.info(translator.get('processing_job_succeeded').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 262 |
+
return 0
|
| 263 |
+
logger.info(translator.get('processing_job_failed').format(job_id = state_manager.get_item('job_id')), __name__)
|
| 264 |
+
return 1
|
| 265 |
+
|
| 266 |
+
if state_manager.get_item('command') == 'job-retry-all':
|
| 267 |
+
logger.info(translator.get('retrying_jobs'), __name__)
|
| 268 |
+
if job_runner.retry_jobs(process_step, state_manager.get_item('halt_on_error')):
|
| 269 |
+
logger.info(translator.get('processing_jobs_succeeded'), __name__)
|
| 270 |
+
return 0
|
| 271 |
+
logger.info(translator.get('processing_jobs_failed'), __name__)
|
| 272 |
+
return 1
|
| 273 |
+
return 2
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def process_headless(args : Args) -> ErrorCode:
|
| 277 |
+
job_id = job_helper.suggest_job_id('headless')
|
| 278 |
+
step_args = reduce_step_args(args)
|
| 279 |
+
|
| 280 |
+
if job_manager.create_job(job_id) and job_manager.add_step(job_id, step_args) and job_manager.submit_job(job_id) and job_runner.run_job(job_id, process_step):
|
| 281 |
+
return 0
|
| 282 |
+
return 1
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def process_batch(args : Args) -> ErrorCode:
|
| 286 |
+
job_id = job_helper.suggest_job_id('batch')
|
| 287 |
+
step_args = reduce_step_args(args)
|
| 288 |
+
job_args = reduce_job_args(args)
|
| 289 |
+
source_paths = resolve_file_pattern(job_args.get('source_pattern'))
|
| 290 |
+
target_paths = resolve_file_pattern(job_args.get('target_pattern'))
|
| 291 |
+
|
| 292 |
+
if job_manager.create_job(job_id):
|
| 293 |
+
if source_paths and target_paths:
|
| 294 |
+
for index, (source_path, target_path) in enumerate(itertools.product(source_paths, target_paths)):
|
| 295 |
+
step_args['source_paths'] = [ source_path ]
|
| 296 |
+
step_args['target_path'] = target_path
|
| 297 |
+
|
| 298 |
+
try:
|
| 299 |
+
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))
|
| 300 |
+
except KeyError:
|
| 301 |
+
return 1
|
| 302 |
+
|
| 303 |
+
if not job_manager.add_step(job_id, step_args):
|
| 304 |
+
return 1
|
| 305 |
+
if job_manager.submit_job(job_id) and job_runner.run_job(job_id, process_step):
|
| 306 |
+
return 0
|
| 307 |
+
|
| 308 |
+
if not source_paths and target_paths:
|
| 309 |
+
for index, target_path in enumerate(target_paths):
|
| 310 |
+
step_args['target_path'] = target_path
|
| 311 |
+
|
| 312 |
+
try:
|
| 313 |
+
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))
|
| 314 |
+
except KeyError:
|
| 315 |
+
return 1
|
| 316 |
+
|
| 317 |
+
if not job_manager.add_step(job_id, step_args):
|
| 318 |
+
return 1
|
| 319 |
+
if job_manager.submit_job(job_id) and job_runner.run_job(job_id, process_step):
|
| 320 |
+
return 0
|
| 321 |
+
return 1
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def process_step(job_id : str, step_index : int, step_args : Args) -> bool:
|
| 325 |
+
step_total = job_manager.count_step_total(job_id)
|
| 326 |
+
step_args.update(collect_job_args())
|
| 327 |
+
apply_args(step_args, state_manager.set_item)
|
| 328 |
+
|
| 329 |
+
logger.info(translator.get('processing_step').format(step_current = step_index + 1, step_total = step_total), __name__)
|
| 330 |
+
if common_pre_check() and processors_pre_check():
|
| 331 |
+
error_code = conditional_process()
|
| 332 |
+
return error_code == 0
|
| 333 |
+
return False
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def conditional_process() -> ErrorCode:
|
| 337 |
+
start_time = time()
|
| 338 |
+
|
| 339 |
+
for processor_module in get_processors_modules(state_manager.get_item('processors')):
|
| 340 |
+
if not processor_module.pre_process('output'):
|
| 341 |
+
return 2
|
| 342 |
+
|
| 343 |
+
if is_image(state_manager.get_item('target_path')):
|
| 344 |
+
return image_to_image.process(start_time)
|
| 345 |
+
if is_video(state_manager.get_item('target_path')):
|
| 346 |
+
return image_to_video.process(start_time)
|
| 347 |
+
|
| 348 |
+
return 0
|
| 349 |
+
|
| 350 |
+
|
facefusion/curl_builder.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
import shutil
|
| 3 |
+
from typing import List
|
| 4 |
+
|
| 5 |
+
from facefusion import metadata
|
| 6 |
+
from facefusion.types import Command
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def run(commands : List[Command]) -> List[Command]:
|
| 10 |
+
user_agent = metadata.get('name') + '/' + metadata.get('version')
|
| 11 |
+
|
| 12 |
+
return [ shutil.which('curl'), '--user-agent', user_agent, '--insecure', '--location', '--silent' ] + commands
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def chain(*commands : List[Command]) -> List[Command]:
|
| 16 |
+
return list(itertools.chain(*commands))
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def ping(url : str) -> List[Command]:
|
| 20 |
+
return [ '-I', url ]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def download(url : str, download_file_path : str) -> List[Command]:
|
| 24 |
+
return [ '--create-dirs', '--continue-at', '-', '--output', download_file_path, url ]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def set_timeout(timeout : int) -> List[Command]:
|
| 28 |
+
return [ '--connect-timeout', str(timeout) ]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def set_retry(retry : int) -> List[Command]:
|
| 32 |
+
return [ '--retry', str(retry) ]
|
facefusion/download.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import subprocess
|
| 3 |
+
from functools import lru_cache
|
| 4 |
+
from typing import List, Optional, Tuple
|
| 5 |
+
from urllib.parse import urlparse
|
| 6 |
+
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
|
| 9 |
+
import facefusion.choices
|
| 10 |
+
from facefusion import curl_builder, logger, process_manager, state_manager, translator
|
| 11 |
+
from facefusion.filesystem import get_file_name, get_file_size, is_file, remove_file
|
| 12 |
+
from facefusion.hash_helper import validate_hash
|
| 13 |
+
from facefusion.types import Command, DownloadProvider, DownloadSet
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def open_curl(commands : List[Command]) -> subprocess.Popen[bytes]:
|
| 17 |
+
commands = curl_builder.run(commands)
|
| 18 |
+
return subprocess.Popen(commands, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def conditional_download(download_directory_path : str, urls : List[str]) -> None:
|
| 22 |
+
for url in urls:
|
| 23 |
+
download_file_name = os.path.basename(urlparse(url).path)
|
| 24 |
+
download_file_path = os.path.join(download_directory_path, download_file_name)
|
| 25 |
+
initial_size = get_file_size(download_file_path)
|
| 26 |
+
download_size = get_static_download_size(url)
|
| 27 |
+
|
| 28 |
+
if initial_size < download_size:
|
| 29 |
+
with tqdm(total = download_size, initial = initial_size, desc = translator.get('downloading'), unit = 'B', unit_scale = True, unit_divisor = 1024, ascii = ' =', disable = state_manager.get_item('log_level') in [ 'warn', 'error' ]) as progress:
|
| 30 |
+
commands = curl_builder.chain(
|
| 31 |
+
curl_builder.download(url, download_file_path),
|
| 32 |
+
curl_builder.set_timeout(5),
|
| 33 |
+
curl_builder.set_retry(5)
|
| 34 |
+
)
|
| 35 |
+
open_curl(commands)
|
| 36 |
+
current_size = initial_size
|
| 37 |
+
progress.set_postfix(download_providers = state_manager.get_item('download_providers'), file_name = download_file_name)
|
| 38 |
+
|
| 39 |
+
while current_size < download_size:
|
| 40 |
+
if is_file(download_file_path):
|
| 41 |
+
current_size = get_file_size(download_file_path)
|
| 42 |
+
progress.update(current_size - progress.n)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@lru_cache(maxsize = 64)
|
| 46 |
+
def get_static_download_size(url : str) -> int:
|
| 47 |
+
commands = curl_builder.chain(
|
| 48 |
+
curl_builder.ping(url),
|
| 49 |
+
curl_builder.set_timeout(5)
|
| 50 |
+
)
|
| 51 |
+
process = open_curl(commands)
|
| 52 |
+
lines = reversed(process.stdout.readlines())
|
| 53 |
+
|
| 54 |
+
for line in lines:
|
| 55 |
+
__line__ = line.decode().lower()
|
| 56 |
+
if 'content-length:' in __line__:
|
| 57 |
+
_, content_length = __line__.split('content-length:')
|
| 58 |
+
return int(content_length)
|
| 59 |
+
|
| 60 |
+
return 0
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@lru_cache(maxsize = 64)
|
| 64 |
+
def ping_static_url(url : str) -> bool:
|
| 65 |
+
commands = curl_builder.chain(
|
| 66 |
+
curl_builder.ping(url),
|
| 67 |
+
curl_builder.set_timeout(5)
|
| 68 |
+
)
|
| 69 |
+
process = open_curl(commands)
|
| 70 |
+
process.communicate()
|
| 71 |
+
return process.returncode == 0
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def conditional_download_hashes(hash_set : DownloadSet) -> bool:
|
| 75 |
+
hash_paths = [ hash_set.get(hash_key).get('path') for hash_key in hash_set.keys() ]
|
| 76 |
+
|
| 77 |
+
process_manager.check()
|
| 78 |
+
_, invalid_hash_paths = validate_hash_paths(hash_paths)
|
| 79 |
+
if invalid_hash_paths:
|
| 80 |
+
for index in hash_set:
|
| 81 |
+
if hash_set.get(index).get('path') in invalid_hash_paths:
|
| 82 |
+
invalid_hash_url = hash_set.get(index).get('url')
|
| 83 |
+
if invalid_hash_url:
|
| 84 |
+
download_directory_path = os.path.dirname(hash_set.get(index).get('path'))
|
| 85 |
+
conditional_download(download_directory_path, [ invalid_hash_url ])
|
| 86 |
+
|
| 87 |
+
valid_hash_paths, invalid_hash_paths = validate_hash_paths(hash_paths)
|
| 88 |
+
|
| 89 |
+
for valid_hash_path in valid_hash_paths:
|
| 90 |
+
valid_hash_file_name = get_file_name(valid_hash_path)
|
| 91 |
+
logger.debug(translator.get('validating_hash_succeeded').format(hash_file_name = valid_hash_file_name), __name__)
|
| 92 |
+
for invalid_hash_path in invalid_hash_paths:
|
| 93 |
+
invalid_hash_file_name = get_file_name(invalid_hash_path)
|
| 94 |
+
logger.error(translator.get('validating_hash_failed').format(hash_file_name = invalid_hash_file_name), __name__)
|
| 95 |
+
|
| 96 |
+
if not invalid_hash_paths:
|
| 97 |
+
process_manager.end()
|
| 98 |
+
return not invalid_hash_paths
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def conditional_download_sources(source_set : DownloadSet) -> bool:
|
| 102 |
+
source_paths = [ source_set.get(source_key).get('path') for source_key in source_set.keys() ]
|
| 103 |
+
|
| 104 |
+
process_manager.check()
|
| 105 |
+
_, invalid_source_paths = validate_source_paths(source_paths)
|
| 106 |
+
if invalid_source_paths:
|
| 107 |
+
for index in source_set:
|
| 108 |
+
if source_set.get(index).get('path') in invalid_source_paths:
|
| 109 |
+
invalid_source_url = source_set.get(index).get('url')
|
| 110 |
+
if invalid_source_url:
|
| 111 |
+
download_directory_path = os.path.dirname(source_set.get(index).get('path'))
|
| 112 |
+
conditional_download(download_directory_path, [ invalid_source_url ])
|
| 113 |
+
|
| 114 |
+
valid_source_paths, invalid_source_paths = validate_source_paths(source_paths)
|
| 115 |
+
|
| 116 |
+
for valid_source_path in valid_source_paths:
|
| 117 |
+
valid_source_file_name = get_file_name(valid_source_path)
|
| 118 |
+
logger.debug(translator.get('validating_source_succeeded').format(source_file_name = valid_source_file_name), __name__)
|
| 119 |
+
for invalid_source_path in invalid_source_paths:
|
| 120 |
+
invalid_source_file_name = get_file_name(invalid_source_path)
|
| 121 |
+
logger.error(translator.get('validating_source_failed').format(source_file_name = invalid_source_file_name), __name__)
|
| 122 |
+
|
| 123 |
+
if remove_file(invalid_source_path):
|
| 124 |
+
logger.error(translator.get('deleting_corrupt_source').format(source_file_name = invalid_source_file_name), __name__)
|
| 125 |
+
|
| 126 |
+
if not invalid_source_paths:
|
| 127 |
+
process_manager.end()
|
| 128 |
+
return not invalid_source_paths
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def validate_hash_paths(hash_paths : List[str]) -> Tuple[List[str], List[str]]:
|
| 132 |
+
valid_hash_paths = []
|
| 133 |
+
invalid_hash_paths = []
|
| 134 |
+
|
| 135 |
+
for hash_path in hash_paths:
|
| 136 |
+
if is_file(hash_path):
|
| 137 |
+
valid_hash_paths.append(hash_path)
|
| 138 |
+
else:
|
| 139 |
+
invalid_hash_paths.append(hash_path)
|
| 140 |
+
|
| 141 |
+
return valid_hash_paths, invalid_hash_paths
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def validate_source_paths(source_paths : List[str]) -> Tuple[List[str], List[str]]:
|
| 145 |
+
valid_source_paths = []
|
| 146 |
+
invalid_source_paths = []
|
| 147 |
+
|
| 148 |
+
for source_path in source_paths:
|
| 149 |
+
if validate_hash(source_path):
|
| 150 |
+
valid_source_paths.append(source_path)
|
| 151 |
+
else:
|
| 152 |
+
invalid_source_paths.append(source_path)
|
| 153 |
+
|
| 154 |
+
return valid_source_paths, invalid_source_paths
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def resolve_download_url(base_name : str, file_name : str) -> Optional[str]:
|
| 158 |
+
download_providers = state_manager.get_item('download_providers')
|
| 159 |
+
|
| 160 |
+
for download_provider in download_providers:
|
| 161 |
+
download_url = resolve_download_url_by_provider(download_provider, base_name, file_name)
|
| 162 |
+
if download_url:
|
| 163 |
+
return download_url
|
| 164 |
+
|
| 165 |
+
return None
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def resolve_download_url_by_provider(download_provider : DownloadProvider, base_name : str, file_name : str) -> Optional[str]:
|
| 169 |
+
download_provider_value = facefusion.choices.download_provider_set.get(download_provider)
|
| 170 |
+
|
| 171 |
+
for download_provider_url in download_provider_value.get('urls'):
|
| 172 |
+
if ping_static_url(download_provider_url):
|
| 173 |
+
return download_provider_url + download_provider_value.get('path').format(base_name = base_name, file_name = file_name)
|
| 174 |
+
|
| 175 |
+
return None
|
facefusion/execution.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import shutil
|
| 2 |
+
import subprocess
|
| 3 |
+
import xml.etree.ElementTree as ElementTree
|
| 4 |
+
from functools import lru_cache
|
| 5 |
+
from typing import List, Optional
|
| 6 |
+
|
| 7 |
+
from onnxruntime import get_available_providers, set_default_logger_severity
|
| 8 |
+
|
| 9 |
+
import facefusion.choices
|
| 10 |
+
from facefusion.types import ExecutionDevice, ExecutionProvider, InferenceSessionProvider, ValueAndUnit
|
| 11 |
+
|
| 12 |
+
set_default_logger_severity(3)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def has_execution_provider(execution_provider : ExecutionProvider) -> bool:
|
| 16 |
+
return execution_provider in get_available_execution_providers()
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def get_available_execution_providers() -> List[ExecutionProvider]:
|
| 20 |
+
inference_session_providers = get_available_providers()
|
| 21 |
+
available_execution_providers : List[ExecutionProvider] = []
|
| 22 |
+
|
| 23 |
+
for execution_provider, execution_provider_value in facefusion.choices.execution_provider_set.items():
|
| 24 |
+
if execution_provider_value in inference_session_providers:
|
| 25 |
+
index = facefusion.choices.execution_providers.index(execution_provider)
|
| 26 |
+
available_execution_providers.insert(index, execution_provider)
|
| 27 |
+
|
| 28 |
+
return available_execution_providers
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def create_inference_session_providers(execution_device_id : int, execution_providers : List[ExecutionProvider]) -> List[InferenceSessionProvider]:
|
| 32 |
+
inference_session_providers : List[InferenceSessionProvider] = []
|
| 33 |
+
|
| 34 |
+
for execution_provider in execution_providers:
|
| 35 |
+
if execution_provider == 'cuda':
|
| 36 |
+
inference_session_providers.append((facefusion.choices.execution_provider_set.get(execution_provider),
|
| 37 |
+
{
|
| 38 |
+
'device_id': execution_device_id,
|
| 39 |
+
'cudnn_conv_algo_search': resolve_cudnn_conv_algo_search()
|
| 40 |
+
}))
|
| 41 |
+
if execution_provider == 'tensorrt':
|
| 42 |
+
inference_session_providers.append((facefusion.choices.execution_provider_set.get(execution_provider),
|
| 43 |
+
{
|
| 44 |
+
'device_id': execution_device_id,
|
| 45 |
+
'trt_engine_cache_enable': True,
|
| 46 |
+
'trt_engine_cache_path': '.caches',
|
| 47 |
+
'trt_timing_cache_enable': True,
|
| 48 |
+
'trt_timing_cache_path': '.caches',
|
| 49 |
+
'trt_builder_optimization_level': 5
|
| 50 |
+
}))
|
| 51 |
+
if execution_provider in [ 'directml', 'rocm' ]:
|
| 52 |
+
inference_session_providers.append((facefusion.choices.execution_provider_set.get(execution_provider),
|
| 53 |
+
{
|
| 54 |
+
'device_id': execution_device_id
|
| 55 |
+
}))
|
| 56 |
+
if execution_provider == 'migraphx':
|
| 57 |
+
inference_session_providers.append((facefusion.choices.execution_provider_set.get(execution_provider),
|
| 58 |
+
{
|
| 59 |
+
'device_id': execution_device_id,
|
| 60 |
+
'migraphx_model_cache_dir': '.caches'
|
| 61 |
+
}))
|
| 62 |
+
if execution_provider == 'openvino':
|
| 63 |
+
inference_session_providers.append((facefusion.choices.execution_provider_set.get(execution_provider),
|
| 64 |
+
{
|
| 65 |
+
'device_type': resolve_openvino_device_type(execution_device_id),
|
| 66 |
+
'precision': 'FP32'
|
| 67 |
+
}))
|
| 68 |
+
if execution_provider == 'coreml':
|
| 69 |
+
inference_session_providers.append((facefusion.choices.execution_provider_set.get(execution_provider),
|
| 70 |
+
{
|
| 71 |
+
'SpecializationStrategy': 'FastPrediction',
|
| 72 |
+
'ModelCacheDirectory': '.caches'
|
| 73 |
+
}))
|
| 74 |
+
|
| 75 |
+
if 'cpu' in execution_providers:
|
| 76 |
+
inference_session_providers.append(facefusion.choices.execution_provider_set.get('cpu'))
|
| 77 |
+
|
| 78 |
+
return inference_session_providers
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def resolve_cudnn_conv_algo_search() -> str:
|
| 82 |
+
execution_devices = detect_static_execution_devices()
|
| 83 |
+
product_names = ('GeForce GTX 1630', 'GeForce GTX 1650', 'GeForce GTX 1660')
|
| 84 |
+
|
| 85 |
+
for execution_device in execution_devices:
|
| 86 |
+
if execution_device.get('product').get('name').startswith(product_names):
|
| 87 |
+
return 'DEFAULT'
|
| 88 |
+
|
| 89 |
+
return 'EXHAUSTIVE'
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def resolve_openvino_device_type(execution_device_id : int) -> str:
|
| 93 |
+
if execution_device_id == 0:
|
| 94 |
+
return 'GPU'
|
| 95 |
+
return 'GPU.' + str(execution_device_id)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def run_nvidia_smi() -> subprocess.Popen[bytes]:
|
| 99 |
+
commands = [ shutil.which('nvidia-smi'), '--query', '--xml-format' ]
|
| 100 |
+
return subprocess.Popen(commands, stdout = subprocess.PIPE)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@lru_cache()
|
| 104 |
+
def detect_static_execution_devices() -> List[ExecutionDevice]:
|
| 105 |
+
return detect_execution_devices()
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def detect_execution_devices() -> List[ExecutionDevice]:
|
| 109 |
+
execution_devices : List[ExecutionDevice] = []
|
| 110 |
+
|
| 111 |
+
try:
|
| 112 |
+
output, _ = run_nvidia_smi().communicate()
|
| 113 |
+
root_element = ElementTree.fromstring(output)
|
| 114 |
+
except Exception:
|
| 115 |
+
root_element = ElementTree.Element('xml')
|
| 116 |
+
|
| 117 |
+
for gpu_element in root_element.findall('gpu'):
|
| 118 |
+
execution_devices.append(
|
| 119 |
+
{
|
| 120 |
+
'driver_version': root_element.findtext('driver_version'),
|
| 121 |
+
'framework':
|
| 122 |
+
{
|
| 123 |
+
'name': 'CUDA',
|
| 124 |
+
'version': root_element.findtext('cuda_version')
|
| 125 |
+
},
|
| 126 |
+
'product':
|
| 127 |
+
{
|
| 128 |
+
'vendor': 'NVIDIA',
|
| 129 |
+
'name': gpu_element.findtext('product_name').replace('NVIDIA', '').strip()
|
| 130 |
+
},
|
| 131 |
+
'video_memory':
|
| 132 |
+
{
|
| 133 |
+
'total': create_value_and_unit(gpu_element.findtext('fb_memory_usage/total')),
|
| 134 |
+
'free': create_value_and_unit(gpu_element.findtext('fb_memory_usage/free'))
|
| 135 |
+
},
|
| 136 |
+
'temperature':
|
| 137 |
+
{
|
| 138 |
+
'gpu': create_value_and_unit(gpu_element.findtext('temperature/gpu_temp')),
|
| 139 |
+
'memory': create_value_and_unit(gpu_element.findtext('temperature/memory_temp'))
|
| 140 |
+
},
|
| 141 |
+
'utilization':
|
| 142 |
+
{
|
| 143 |
+
'gpu': create_value_and_unit(gpu_element.findtext('utilization/gpu_util')),
|
| 144 |
+
'memory': create_value_and_unit(gpu_element.findtext('utilization/memory_util'))
|
| 145 |
+
}
|
| 146 |
+
})
|
| 147 |
+
|
| 148 |
+
return execution_devices
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def create_value_and_unit(text : str) -> Optional[ValueAndUnit]:
|
| 152 |
+
if ' ' in text:
|
| 153 |
+
value, unit = text.split()
|
| 154 |
+
|
| 155 |
+
return\
|
| 156 |
+
{
|
| 157 |
+
'value': int(value),
|
| 158 |
+
'unit': str(unit)
|
| 159 |
+
}
|
| 160 |
+
return None
|
facefusion/exit_helper.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import signal
|
| 3 |
+
import sys
|
| 4 |
+
from time import sleep
|
| 5 |
+
from types import FrameType
|
| 6 |
+
|
| 7 |
+
from facefusion import process_manager, state_manager
|
| 8 |
+
from facefusion.temp_helper import clear_temp_directory
|
| 9 |
+
from facefusion.types import ErrorCode
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def fatal_exit(error_code : ErrorCode) -> None:
|
| 13 |
+
os._exit(error_code)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def hard_exit(error_code : ErrorCode) -> None:
|
| 17 |
+
sys.exit(error_code)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def signal_exit(signum : int, frame : FrameType) -> None:
|
| 21 |
+
graceful_exit(0)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def graceful_exit(error_code : ErrorCode) -> None:
|
| 25 |
+
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
| 26 |
+
process_manager.stop()
|
| 27 |
+
|
| 28 |
+
while process_manager.is_processing():
|
| 29 |
+
sleep(0.5)
|
| 30 |
+
|
| 31 |
+
if state_manager.get_item('target_path'):
|
| 32 |
+
clear_temp_directory(state_manager.get_item('target_path'))
|
| 33 |
+
|
| 34 |
+
hard_exit(error_code)
|
facefusion/face_analyser.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Optional
|
| 2 |
+
|
| 3 |
+
import numpy
|
| 4 |
+
|
| 5 |
+
from facefusion import state_manager
|
| 6 |
+
from facefusion.common_helper import get_first
|
| 7 |
+
from facefusion.face_classifier import classify_face
|
| 8 |
+
from facefusion.face_detector import detect_faces, detect_faces_by_angle
|
| 9 |
+
from facefusion.face_helper import apply_nms, convert_to_face_landmark_5, estimate_face_angle, get_nms_threshold
|
| 10 |
+
from facefusion.face_landmarker import detect_face_landmark, estimate_face_landmark_68_5
|
| 11 |
+
from facefusion.face_recognizer import calculate_face_embedding
|
| 12 |
+
from facefusion.face_store import get_static_faces, set_static_faces
|
| 13 |
+
from facefusion.types import BoundingBox, Face, FaceLandmark5, FaceLandmarkSet, FaceScoreSet, Score, VisionFrame
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def create_faces(vision_frame : VisionFrame, bounding_boxes : List[BoundingBox], face_scores : List[Score], face_landmarks_5 : List[FaceLandmark5]) -> List[Face]:
|
| 17 |
+
faces = []
|
| 18 |
+
nms_threshold = get_nms_threshold(state_manager.get_item('face_detector_model'), state_manager.get_item('face_detector_angles'))
|
| 19 |
+
keep_indices = apply_nms(bounding_boxes, face_scores, state_manager.get_item('face_detector_score'), nms_threshold)
|
| 20 |
+
|
| 21 |
+
for index in keep_indices:
|
| 22 |
+
bounding_box = bounding_boxes[index]
|
| 23 |
+
face_score = face_scores[index]
|
| 24 |
+
face_landmark_5 = face_landmarks_5[index]
|
| 25 |
+
face_landmark_5_68 = face_landmark_5
|
| 26 |
+
face_landmark_68_5 = estimate_face_landmark_68_5(face_landmark_5_68)
|
| 27 |
+
face_landmark_68 = face_landmark_68_5
|
| 28 |
+
face_landmark_score_68 = 0.0
|
| 29 |
+
face_angle = estimate_face_angle(face_landmark_68_5)
|
| 30 |
+
|
| 31 |
+
if state_manager.get_item('face_landmarker_score') > 0:
|
| 32 |
+
face_landmark_68, face_landmark_score_68 = detect_face_landmark(vision_frame, bounding_box, face_angle)
|
| 33 |
+
if face_landmark_score_68 > state_manager.get_item('face_landmarker_score'):
|
| 34 |
+
face_landmark_5_68 = convert_to_face_landmark_5(face_landmark_68)
|
| 35 |
+
|
| 36 |
+
face_landmark_set : FaceLandmarkSet =\
|
| 37 |
+
{
|
| 38 |
+
'5': face_landmark_5,
|
| 39 |
+
'5/68': face_landmark_5_68,
|
| 40 |
+
'68': face_landmark_68,
|
| 41 |
+
'68/5': face_landmark_68_5
|
| 42 |
+
}
|
| 43 |
+
face_score_set : FaceScoreSet =\
|
| 44 |
+
{
|
| 45 |
+
'detector': face_score,
|
| 46 |
+
'landmarker': face_landmark_score_68
|
| 47 |
+
}
|
| 48 |
+
face_embedding, face_embedding_norm = calculate_face_embedding(vision_frame, face_landmark_set.get('5/68'))
|
| 49 |
+
gender, age, race = classify_face(vision_frame, face_landmark_set.get('5/68'))
|
| 50 |
+
faces.append(Face(
|
| 51 |
+
bounding_box = bounding_box,
|
| 52 |
+
score_set = face_score_set,
|
| 53 |
+
landmark_set = face_landmark_set,
|
| 54 |
+
angle = face_angle,
|
| 55 |
+
embedding = face_embedding,
|
| 56 |
+
embedding_norm = face_embedding_norm,
|
| 57 |
+
gender = gender,
|
| 58 |
+
age = age,
|
| 59 |
+
race = race
|
| 60 |
+
))
|
| 61 |
+
return faces
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def get_one_face(faces : List[Face], position : int = 0) -> Optional[Face]:
|
| 65 |
+
if faces:
|
| 66 |
+
position = min(position, len(faces) - 1)
|
| 67 |
+
return faces[position]
|
| 68 |
+
return None
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def get_average_face(faces : List[Face]) -> Optional[Face]:
|
| 72 |
+
face_embeddings = []
|
| 73 |
+
face_embeddings_norm = []
|
| 74 |
+
|
| 75 |
+
if faces:
|
| 76 |
+
first_face = get_first(faces)
|
| 77 |
+
|
| 78 |
+
for face in faces:
|
| 79 |
+
face_embeddings.append(face.embedding)
|
| 80 |
+
face_embeddings_norm.append(face.embedding_norm)
|
| 81 |
+
|
| 82 |
+
return Face(
|
| 83 |
+
bounding_box = first_face.bounding_box,
|
| 84 |
+
score_set = first_face.score_set,
|
| 85 |
+
landmark_set = first_face.landmark_set,
|
| 86 |
+
angle = first_face.angle,
|
| 87 |
+
embedding = numpy.mean(face_embeddings, axis = 0),
|
| 88 |
+
embedding_norm = numpy.mean(face_embeddings_norm, axis = 0),
|
| 89 |
+
gender = first_face.gender,
|
| 90 |
+
age = first_face.age,
|
| 91 |
+
race = first_face.race
|
| 92 |
+
)
|
| 93 |
+
return None
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def get_many_faces(vision_frames : List[VisionFrame]) -> List[Face]:
|
| 97 |
+
many_faces : List[Face] = []
|
| 98 |
+
|
| 99 |
+
for vision_frame in vision_frames:
|
| 100 |
+
if numpy.any(vision_frame):
|
| 101 |
+
static_faces = get_static_faces(vision_frame)
|
| 102 |
+
if static_faces:
|
| 103 |
+
many_faces.extend(static_faces)
|
| 104 |
+
else:
|
| 105 |
+
all_bounding_boxes = []
|
| 106 |
+
all_face_scores = []
|
| 107 |
+
all_face_landmarks_5 = []
|
| 108 |
+
|
| 109 |
+
for face_detector_angle in state_manager.get_item('face_detector_angles'):
|
| 110 |
+
if face_detector_angle == 0:
|
| 111 |
+
bounding_boxes, face_scores, face_landmarks_5 = detect_faces(vision_frame)
|
| 112 |
+
else:
|
| 113 |
+
bounding_boxes, face_scores, face_landmarks_5 = detect_faces_by_angle(vision_frame, face_detector_angle)
|
| 114 |
+
all_bounding_boxes.extend(bounding_boxes)
|
| 115 |
+
all_face_scores.extend(face_scores)
|
| 116 |
+
all_face_landmarks_5.extend(face_landmarks_5)
|
| 117 |
+
|
| 118 |
+
if all_bounding_boxes and all_face_scores and all_face_landmarks_5 and state_manager.get_item('face_detector_score') > 0:
|
| 119 |
+
faces = create_faces(vision_frame, all_bounding_boxes, all_face_scores, all_face_landmarks_5)
|
| 120 |
+
|
| 121 |
+
if faces:
|
| 122 |
+
many_faces.extend(faces)
|
| 123 |
+
set_static_faces(vision_frame, faces)
|
| 124 |
+
return many_faces
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def scale_face(target_face : Face, target_vision_frame : VisionFrame, temp_vision_frame : VisionFrame) -> Face:
|
| 128 |
+
scale_x = temp_vision_frame.shape[1] / target_vision_frame.shape[1]
|
| 129 |
+
scale_y = temp_vision_frame.shape[0] / target_vision_frame.shape[0]
|
| 130 |
+
|
| 131 |
+
bounding_box = target_face.bounding_box * [ scale_x, scale_y, scale_x, scale_y ]
|
| 132 |
+
landmark_set =\
|
| 133 |
+
{
|
| 134 |
+
'5': target_face.landmark_set.get('5') * numpy.array([ scale_x, scale_y ]),
|
| 135 |
+
'5/68': target_face.landmark_set.get('5/68') * numpy.array([ scale_x, scale_y ]),
|
| 136 |
+
'68': target_face.landmark_set.get('68') * numpy.array([ scale_x, scale_y ]),
|
| 137 |
+
'68/5': target_face.landmark_set.get('68/5') * numpy.array([ scale_x, scale_y ])
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
return target_face._replace(
|
| 141 |
+
bounding_box = bounding_box,
|
| 142 |
+
landmark_set = landmark_set
|
| 143 |
+
)
|
facefusion/face_classifier.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
from typing import List, Tuple
|
| 3 |
+
|
| 4 |
+
import numpy
|
| 5 |
+
|
| 6 |
+
from facefusion import inference_manager
|
| 7 |
+
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
| 8 |
+
from facefusion.face_helper import warp_face_by_face_landmark_5
|
| 9 |
+
from facefusion.filesystem import resolve_relative_path
|
| 10 |
+
from facefusion.thread_helper import conditional_thread_semaphore
|
| 11 |
+
from facefusion.types import Age, DownloadScope, FaceLandmark5, Gender, InferencePool, ModelOptions, ModelSet, Race, VisionFrame
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@lru_cache()
|
| 15 |
+
def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
| 16 |
+
return\
|
| 17 |
+
{
|
| 18 |
+
'fairface':
|
| 19 |
+
{
|
| 20 |
+
'__metadata__':
|
| 21 |
+
{
|
| 22 |
+
'vendor': 'dchen236',
|
| 23 |
+
'license': 'Non-Commercial',
|
| 24 |
+
'year': 2021
|
| 25 |
+
},
|
| 26 |
+
'hashes':
|
| 27 |
+
{
|
| 28 |
+
'face_classifier':
|
| 29 |
+
{
|
| 30 |
+
'url': resolve_download_url('models-3.0.0', 'fairface.hash'),
|
| 31 |
+
'path': resolve_relative_path('../.assets/models/fairface.hash')
|
| 32 |
+
}
|
| 33 |
+
},
|
| 34 |
+
'sources':
|
| 35 |
+
{
|
| 36 |
+
'face_classifier':
|
| 37 |
+
{
|
| 38 |
+
'url': resolve_download_url('models-3.0.0', 'fairface.onnx'),
|
| 39 |
+
'path': resolve_relative_path('../.assets/models/fairface.onnx')
|
| 40 |
+
}
|
| 41 |
+
},
|
| 42 |
+
'template': 'arcface_112_v2',
|
| 43 |
+
'size': (224, 224),
|
| 44 |
+
'mean': [ 0.485, 0.456, 0.406 ],
|
| 45 |
+
'standard_deviation': [ 0.229, 0.224, 0.225 ]
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def get_inference_pool() -> InferencePool:
|
| 51 |
+
model_names = [ 'fairface' ]
|
| 52 |
+
model_source_set = get_model_options().get('sources')
|
| 53 |
+
|
| 54 |
+
return inference_manager.get_inference_pool(__name__, model_names, model_source_set)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def clear_inference_pool() -> None:
|
| 58 |
+
model_names = [ 'fairface' ]
|
| 59 |
+
inference_manager.clear_inference_pool(__name__, model_names)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def get_model_options() -> ModelOptions:
|
| 63 |
+
return create_static_model_set('full').get('fairface')
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def pre_check() -> bool:
|
| 67 |
+
model_hash_set = get_model_options().get('hashes')
|
| 68 |
+
model_source_set = get_model_options().get('sources')
|
| 69 |
+
|
| 70 |
+
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def classify_face(temp_vision_frame : VisionFrame, face_landmark_5 : FaceLandmark5) -> Tuple[Gender, Age, Race]:
|
| 74 |
+
model_template = get_model_options().get('template')
|
| 75 |
+
model_size = get_model_options().get('size')
|
| 76 |
+
model_mean = get_model_options().get('mean')
|
| 77 |
+
model_standard_deviation = get_model_options().get('standard_deviation')
|
| 78 |
+
crop_vision_frame, _ = warp_face_by_face_landmark_5(temp_vision_frame, face_landmark_5, model_template, model_size)
|
| 79 |
+
crop_vision_frame = crop_vision_frame.astype(numpy.float32)[:, :, ::-1] / 255.0
|
| 80 |
+
crop_vision_frame -= model_mean
|
| 81 |
+
crop_vision_frame /= model_standard_deviation
|
| 82 |
+
crop_vision_frame = crop_vision_frame.transpose(2, 0, 1)
|
| 83 |
+
crop_vision_frame = numpy.expand_dims(crop_vision_frame, axis = 0)
|
| 84 |
+
gender_id, age_id, race_id = forward(crop_vision_frame)
|
| 85 |
+
gender = categorize_gender(gender_id[0])
|
| 86 |
+
age = categorize_age(age_id[0])
|
| 87 |
+
race = categorize_race(race_id[0])
|
| 88 |
+
return gender, age, race
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def forward(crop_vision_frame : VisionFrame) -> Tuple[List[int], List[int], List[int]]:
|
| 92 |
+
face_classifier = get_inference_pool().get('face_classifier')
|
| 93 |
+
|
| 94 |
+
with conditional_thread_semaphore():
|
| 95 |
+
race_id, gender_id, age_id = face_classifier.run(None,
|
| 96 |
+
{
|
| 97 |
+
'input': crop_vision_frame
|
| 98 |
+
})
|
| 99 |
+
|
| 100 |
+
return gender_id, age_id, race_id
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def categorize_gender(gender_id : int) -> Gender:
|
| 104 |
+
if gender_id == 1:
|
| 105 |
+
return 'female'
|
| 106 |
+
return 'male'
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def categorize_age(age_id : int) -> Age:
|
| 110 |
+
if age_id == 0:
|
| 111 |
+
return range(0, 2)
|
| 112 |
+
if age_id == 1:
|
| 113 |
+
return range(3, 9)
|
| 114 |
+
if age_id == 2:
|
| 115 |
+
return range(10, 19)
|
| 116 |
+
if age_id == 3:
|
| 117 |
+
return range(20, 29)
|
| 118 |
+
if age_id == 4:
|
| 119 |
+
return range(30, 39)
|
| 120 |
+
if age_id == 5:
|
| 121 |
+
return range(40, 49)
|
| 122 |
+
if age_id == 6:
|
| 123 |
+
return range(50, 59)
|
| 124 |
+
if age_id == 7:
|
| 125 |
+
return range(60, 69)
|
| 126 |
+
return range(70, 100)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def categorize_race(race_id : int) -> Race:
|
| 130 |
+
if race_id == 1:
|
| 131 |
+
return 'black'
|
| 132 |
+
if race_id == 2:
|
| 133 |
+
return 'latino'
|
| 134 |
+
if race_id == 3 or race_id == 4:
|
| 135 |
+
return 'asian'
|
| 136 |
+
if race_id == 5:
|
| 137 |
+
return 'indian'
|
| 138 |
+
if race_id == 6:
|
| 139 |
+
return 'arabic'
|
| 140 |
+
return 'white'
|
facefusion/face_detector.py
ADDED
|
@@ -0,0 +1,458 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
from typing import List, Sequence, Tuple
|
| 3 |
+
|
| 4 |
+
import cv2
|
| 5 |
+
import numpy
|
| 6 |
+
|
| 7 |
+
from facefusion import inference_manager, state_manager
|
| 8 |
+
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
| 9 |
+
from facefusion.face_helper import create_rotation_matrix_and_size, create_static_anchors, distance_to_bounding_box, distance_to_face_landmark_5, normalize_bounding_box, transform_bounding_box, transform_points
|
| 10 |
+
from facefusion.filesystem import resolve_relative_path
|
| 11 |
+
from facefusion.thread_helper import thread_semaphore
|
| 12 |
+
from facefusion.types import Angle, BoundingBox, Detection, DownloadScope, DownloadSet, FaceLandmark5, InferencePool, Margin, ModelSet, Score, VisionFrame
|
| 13 |
+
from facefusion.vision import restrict_frame, unpack_resolution
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@lru_cache()
|
| 17 |
+
def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
| 18 |
+
return\
|
| 19 |
+
{
|
| 20 |
+
'retinaface':
|
| 21 |
+
{
|
| 22 |
+
'__metadata__':
|
| 23 |
+
{
|
| 24 |
+
'vendor': 'InsightFace',
|
| 25 |
+
'license': 'Non-Commercial',
|
| 26 |
+
'year': 2020
|
| 27 |
+
},
|
| 28 |
+
'hashes':
|
| 29 |
+
{
|
| 30 |
+
'retinaface':
|
| 31 |
+
{
|
| 32 |
+
'url': resolve_download_url('models-3.0.0', 'retinaface_10g.hash'),
|
| 33 |
+
'path': resolve_relative_path('../.assets/models/retinaface_10g.hash')
|
| 34 |
+
}
|
| 35 |
+
},
|
| 36 |
+
'sources':
|
| 37 |
+
{
|
| 38 |
+
'retinaface':
|
| 39 |
+
{
|
| 40 |
+
'url': resolve_download_url('models-3.0.0', 'retinaface_10g.onnx'),
|
| 41 |
+
'path': resolve_relative_path('../.assets/models/retinaface_10g.onnx')
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
},
|
| 45 |
+
'scrfd':
|
| 46 |
+
{
|
| 47 |
+
'__metadata__':
|
| 48 |
+
{
|
| 49 |
+
'vendor': 'InsightFace',
|
| 50 |
+
'license': 'Non-Commercial',
|
| 51 |
+
'year': 2021
|
| 52 |
+
},
|
| 53 |
+
'hashes':
|
| 54 |
+
{
|
| 55 |
+
'scrfd':
|
| 56 |
+
{
|
| 57 |
+
'url': resolve_download_url('models-3.0.0', 'scrfd_2.5g.hash'),
|
| 58 |
+
'path': resolve_relative_path('../.assets/models/scrfd_2.5g.hash')
|
| 59 |
+
}
|
| 60 |
+
},
|
| 61 |
+
'sources':
|
| 62 |
+
{
|
| 63 |
+
'scrfd':
|
| 64 |
+
{
|
| 65 |
+
'url': resolve_download_url('models-3.0.0', 'scrfd_2.5g.onnx'),
|
| 66 |
+
'path': resolve_relative_path('../.assets/models/scrfd_2.5g.onnx')
|
| 67 |
+
}
|
| 68 |
+
}
|
| 69 |
+
},
|
| 70 |
+
'yolo_face':
|
| 71 |
+
{
|
| 72 |
+
'__metadata__':
|
| 73 |
+
{
|
| 74 |
+
'vendor': 'derronqi',
|
| 75 |
+
'license': 'GPL-3.0',
|
| 76 |
+
'year': 2022
|
| 77 |
+
},
|
| 78 |
+
'hashes':
|
| 79 |
+
{
|
| 80 |
+
'yolo_face':
|
| 81 |
+
{
|
| 82 |
+
'url': resolve_download_url('models-3.0.0', 'yoloface_8n.hash'),
|
| 83 |
+
'path': resolve_relative_path('../.assets/models/yoloface_8n.hash')
|
| 84 |
+
}
|
| 85 |
+
},
|
| 86 |
+
'sources':
|
| 87 |
+
{
|
| 88 |
+
'yolo_face':
|
| 89 |
+
{
|
| 90 |
+
'url': resolve_download_url('models-3.0.0', 'yoloface_8n.onnx'),
|
| 91 |
+
'path': resolve_relative_path('../.assets/models/yoloface_8n.onnx')
|
| 92 |
+
}
|
| 93 |
+
}
|
| 94 |
+
},
|
| 95 |
+
'yunet':
|
| 96 |
+
{
|
| 97 |
+
'__metadata__':
|
| 98 |
+
{
|
| 99 |
+
'vendor': 'OpenCV',
|
| 100 |
+
'license': 'MIT',
|
| 101 |
+
'year': 2023
|
| 102 |
+
},
|
| 103 |
+
'hashes':
|
| 104 |
+
{
|
| 105 |
+
'yunet':
|
| 106 |
+
{
|
| 107 |
+
'url': resolve_download_url('models-3.4.0', 'yunet_2023_mar.hash'),
|
| 108 |
+
'path': resolve_relative_path('../.assets/models/yunet_2023_mar.hash')
|
| 109 |
+
}
|
| 110 |
+
},
|
| 111 |
+
'sources':
|
| 112 |
+
{
|
| 113 |
+
'yunet':
|
| 114 |
+
{
|
| 115 |
+
'url': resolve_download_url('models-3.4.0', 'yunet_2023_mar.onnx'),
|
| 116 |
+
'path': resolve_relative_path('../.assets/models/yunet_2023_mar.onnx')
|
| 117 |
+
}
|
| 118 |
+
}
|
| 119 |
+
}
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def get_inference_pool() -> InferencePool:
|
| 124 |
+
model_names = [ state_manager.get_item('face_detector_model') ]
|
| 125 |
+
_, model_source_set = collect_model_downloads()
|
| 126 |
+
|
| 127 |
+
return inference_manager.get_inference_pool(__name__, model_names, model_source_set)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def clear_inference_pool() -> None:
|
| 131 |
+
model_names = [ state_manager.get_item('face_detector_model') ]
|
| 132 |
+
inference_manager.clear_inference_pool(__name__, model_names)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def collect_model_downloads() -> Tuple[DownloadSet, DownloadSet]:
|
| 136 |
+
model_set = create_static_model_set('full')
|
| 137 |
+
model_hash_set = {}
|
| 138 |
+
model_source_set = {}
|
| 139 |
+
|
| 140 |
+
for face_detector_model in [ 'retinaface', 'scrfd', 'yolo_face', 'yunet' ]:
|
| 141 |
+
if state_manager.get_item('face_detector_model') in [ 'many', face_detector_model ]:
|
| 142 |
+
model_hash_set[face_detector_model] = model_set.get(face_detector_model).get('hashes').get(face_detector_model)
|
| 143 |
+
model_source_set[face_detector_model] = model_set.get(face_detector_model).get('sources').get(face_detector_model)
|
| 144 |
+
|
| 145 |
+
return model_hash_set, model_source_set
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def pre_check() -> bool:
|
| 149 |
+
model_hash_set, model_source_set = collect_model_downloads()
|
| 150 |
+
|
| 151 |
+
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def detect_faces(vision_frame : VisionFrame) -> Tuple[List[BoundingBox], List[Score], List[FaceLandmark5]]:
|
| 155 |
+
margin_top, margin_right, margin_bottom, margin_left = prepare_margin(vision_frame)
|
| 156 |
+
margin_vision_frame = numpy.pad(vision_frame, ((margin_top, margin_bottom), (margin_left, margin_right), (0, 0)))
|
| 157 |
+
all_bounding_boxes : List[BoundingBox] = []
|
| 158 |
+
all_face_scores : List[Score] = []
|
| 159 |
+
all_face_landmarks_5 : List[FaceLandmark5] = []
|
| 160 |
+
|
| 161 |
+
if state_manager.get_item('face_detector_model') in [ 'many', 'retinaface' ]:
|
| 162 |
+
bounding_boxes, face_scores, face_landmarks_5 = detect_with_retinaface(margin_vision_frame, state_manager.get_item('face_detector_size'))
|
| 163 |
+
all_bounding_boxes.extend(bounding_boxes)
|
| 164 |
+
all_face_scores.extend(face_scores)
|
| 165 |
+
all_face_landmarks_5.extend(face_landmarks_5)
|
| 166 |
+
|
| 167 |
+
if state_manager.get_item('face_detector_model') in [ 'many', 'scrfd' ]:
|
| 168 |
+
bounding_boxes, face_scores, face_landmarks_5 = detect_with_scrfd(margin_vision_frame, state_manager.get_item('face_detector_size'))
|
| 169 |
+
all_bounding_boxes.extend(bounding_boxes)
|
| 170 |
+
all_face_scores.extend(face_scores)
|
| 171 |
+
all_face_landmarks_5.extend(face_landmarks_5)
|
| 172 |
+
|
| 173 |
+
if state_manager.get_item('face_detector_model') in [ 'many', 'yolo_face' ]:
|
| 174 |
+
bounding_boxes, face_scores, face_landmarks_5 = detect_with_yolo_face(margin_vision_frame, state_manager.get_item('face_detector_size'))
|
| 175 |
+
all_bounding_boxes.extend(bounding_boxes)
|
| 176 |
+
all_face_scores.extend(face_scores)
|
| 177 |
+
all_face_landmarks_5.extend(face_landmarks_5)
|
| 178 |
+
|
| 179 |
+
if state_manager.get_item('face_detector_model') == 'yunet':
|
| 180 |
+
bounding_boxes, face_scores, face_landmarks_5 = detect_with_yunet(margin_vision_frame, state_manager.get_item('face_detector_size'))
|
| 181 |
+
all_bounding_boxes.extend(bounding_boxes)
|
| 182 |
+
all_face_scores.extend(face_scores)
|
| 183 |
+
all_face_landmarks_5.extend(face_landmarks_5)
|
| 184 |
+
|
| 185 |
+
all_bounding_boxes = [ normalize_bounding_box(all_bounding_box) - numpy.array([ margin_left, margin_top, margin_left, margin_top ]) for all_bounding_box in all_bounding_boxes ]
|
| 186 |
+
all_face_landmarks_5 = [ all_face_landmark_5 - numpy.array([ margin_left, margin_top ]) for all_face_landmark_5 in all_face_landmarks_5 ]
|
| 187 |
+
return all_bounding_boxes, all_face_scores, all_face_landmarks_5
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def prepare_margin(vision_frame : VisionFrame) -> Margin:
|
| 191 |
+
margin_top = int(vision_frame.shape[0] * numpy.interp(state_manager.get_item('face_detector_margin')[0], [ 0, 100 ], [ 0, 0.5 ]))
|
| 192 |
+
margin_right = int(vision_frame.shape[1] * numpy.interp(state_manager.get_item('face_detector_margin')[1], [ 0, 100 ], [ 0, 0.5 ]))
|
| 193 |
+
margin_bottom = int(vision_frame.shape[0] * numpy.interp(state_manager.get_item('face_detector_margin')[2], [ 0, 100 ], [ 0, 0.5 ]))
|
| 194 |
+
margin_left = int(vision_frame.shape[1] * numpy.interp(state_manager.get_item('face_detector_margin')[3], [ 0, 100 ], [ 0, 0.5 ]))
|
| 195 |
+
return margin_top, margin_right, margin_bottom, margin_left
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def detect_faces_by_angle(vision_frame : VisionFrame, face_angle : Angle) -> Tuple[List[BoundingBox], List[Score], List[FaceLandmark5]]:
|
| 199 |
+
rotation_matrix, rotation_size = create_rotation_matrix_and_size(face_angle, vision_frame.shape[:2][::-1])
|
| 200 |
+
rotation_vision_frame = cv2.warpAffine(vision_frame, rotation_matrix, rotation_size)
|
| 201 |
+
rotation_inverse_matrix = cv2.invertAffineTransform(rotation_matrix)
|
| 202 |
+
bounding_boxes, face_scores, face_landmarks_5 = detect_faces(rotation_vision_frame)
|
| 203 |
+
bounding_boxes = [ transform_bounding_box(bounding_box, rotation_inverse_matrix) for bounding_box in bounding_boxes ]
|
| 204 |
+
face_landmarks_5 = [ transform_points(face_landmark_5, rotation_inverse_matrix) for face_landmark_5 in face_landmarks_5 ]
|
| 205 |
+
return bounding_boxes, face_scores, face_landmarks_5
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def detect_with_retinaface(vision_frame : VisionFrame, face_detector_size : str) -> Tuple[List[BoundingBox], List[Score], List[FaceLandmark5]]:
|
| 209 |
+
bounding_boxes = []
|
| 210 |
+
face_scores = []
|
| 211 |
+
face_landmarks_5 = []
|
| 212 |
+
feature_strides = [ 8, 16, 32 ]
|
| 213 |
+
feature_map_channel = 3
|
| 214 |
+
anchor_total = 2
|
| 215 |
+
face_detector_score = state_manager.get_item('face_detector_score')
|
| 216 |
+
face_detector_width, face_detector_height = unpack_resolution(face_detector_size)
|
| 217 |
+
temp_vision_frame = restrict_frame(vision_frame, (face_detector_width, face_detector_height))
|
| 218 |
+
ratio_height = vision_frame.shape[0] / temp_vision_frame.shape[0]
|
| 219 |
+
ratio_width = vision_frame.shape[1] / temp_vision_frame.shape[1]
|
| 220 |
+
detect_vision_frame = prepare_detect_frame(temp_vision_frame, face_detector_size)
|
| 221 |
+
detect_vision_frame = normalize_detect_frame(detect_vision_frame, [ -1, 1 ])
|
| 222 |
+
detection = forward_with_retinaface(detect_vision_frame)
|
| 223 |
+
|
| 224 |
+
for index, feature_stride in enumerate(feature_strides):
|
| 225 |
+
face_scores_raw = detection[index]
|
| 226 |
+
keep_indices = numpy.where(face_scores_raw >= face_detector_score)[0]
|
| 227 |
+
|
| 228 |
+
if numpy.any(keep_indices):
|
| 229 |
+
stride_height = face_detector_height // feature_stride
|
| 230 |
+
stride_width = face_detector_width // feature_stride
|
| 231 |
+
anchors = create_static_anchors(feature_stride, anchor_total, stride_height, stride_width)
|
| 232 |
+
bounding_boxes_raw = detection[index + feature_map_channel] * feature_stride
|
| 233 |
+
face_landmarks_5_raw = detection[index + feature_map_channel * 2] * feature_stride
|
| 234 |
+
|
| 235 |
+
for bounding_box_raw in distance_to_bounding_box(anchors, bounding_boxes_raw)[keep_indices]:
|
| 236 |
+
bounding_boxes.append(numpy.array(
|
| 237 |
+
[
|
| 238 |
+
bounding_box_raw[0] * ratio_width,
|
| 239 |
+
bounding_box_raw[1] * ratio_height,
|
| 240 |
+
bounding_box_raw[2] * ratio_width,
|
| 241 |
+
bounding_box_raw[3] * ratio_height
|
| 242 |
+
]))
|
| 243 |
+
|
| 244 |
+
for face_score_raw in face_scores_raw[keep_indices]:
|
| 245 |
+
face_scores.append(face_score_raw[0])
|
| 246 |
+
|
| 247 |
+
for face_landmark_raw_5 in distance_to_face_landmark_5(anchors, face_landmarks_5_raw)[keep_indices]:
|
| 248 |
+
face_landmarks_5.append(face_landmark_raw_5 * [ ratio_width, ratio_height ])
|
| 249 |
+
|
| 250 |
+
return bounding_boxes, face_scores, face_landmarks_5
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def detect_with_scrfd(vision_frame : VisionFrame, face_detector_size : str) -> Tuple[List[BoundingBox], List[Score], List[FaceLandmark5]]:
|
| 254 |
+
bounding_boxes = []
|
| 255 |
+
face_scores = []
|
| 256 |
+
face_landmarks_5 = []
|
| 257 |
+
feature_strides = [ 8, 16, 32 ]
|
| 258 |
+
feature_map_channel = 3
|
| 259 |
+
anchor_total = 2
|
| 260 |
+
face_detector_score = state_manager.get_item('face_detector_score')
|
| 261 |
+
face_detector_width, face_detector_height = unpack_resolution(face_detector_size)
|
| 262 |
+
temp_vision_frame = restrict_frame(vision_frame, (face_detector_width, face_detector_height))
|
| 263 |
+
ratio_height = vision_frame.shape[0] / temp_vision_frame.shape[0]
|
| 264 |
+
ratio_width = vision_frame.shape[1] / temp_vision_frame.shape[1]
|
| 265 |
+
detect_vision_frame = prepare_detect_frame(temp_vision_frame, face_detector_size)
|
| 266 |
+
detect_vision_frame = normalize_detect_frame(detect_vision_frame, [ -1, 1 ])
|
| 267 |
+
detection = forward_with_scrfd(detect_vision_frame)
|
| 268 |
+
|
| 269 |
+
for index, feature_stride in enumerate(feature_strides):
|
| 270 |
+
face_scores_raw = detection[index]
|
| 271 |
+
keep_indices = numpy.where(face_scores_raw >= face_detector_score)[0]
|
| 272 |
+
|
| 273 |
+
if numpy.any(keep_indices):
|
| 274 |
+
stride_height = face_detector_height // feature_stride
|
| 275 |
+
stride_width = face_detector_width // feature_stride
|
| 276 |
+
anchors = create_static_anchors(feature_stride, anchor_total, stride_height, stride_width)
|
| 277 |
+
bounding_boxes_raw = detection[index + feature_map_channel] * feature_stride
|
| 278 |
+
face_landmarks_5_raw = detection[index + feature_map_channel * 2] * feature_stride
|
| 279 |
+
|
| 280 |
+
for bounding_box_raw in distance_to_bounding_box(anchors, bounding_boxes_raw)[keep_indices]:
|
| 281 |
+
bounding_boxes.append(numpy.array(
|
| 282 |
+
[
|
| 283 |
+
bounding_box_raw[0] * ratio_width,
|
| 284 |
+
bounding_box_raw[1] * ratio_height,
|
| 285 |
+
bounding_box_raw[2] * ratio_width,
|
| 286 |
+
bounding_box_raw[3] * ratio_height
|
| 287 |
+
]))
|
| 288 |
+
|
| 289 |
+
for face_score_raw in face_scores_raw[keep_indices]:
|
| 290 |
+
face_scores.append(face_score_raw[0])
|
| 291 |
+
|
| 292 |
+
for face_landmark_raw_5 in distance_to_face_landmark_5(anchors, face_landmarks_5_raw)[keep_indices]:
|
| 293 |
+
face_landmarks_5.append(face_landmark_raw_5 * [ ratio_width, ratio_height ])
|
| 294 |
+
|
| 295 |
+
return bounding_boxes, face_scores, face_landmarks_5
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def detect_with_yolo_face(vision_frame : VisionFrame, face_detector_size : str) -> Tuple[List[BoundingBox], List[Score], List[FaceLandmark5]]:
|
| 299 |
+
bounding_boxes = []
|
| 300 |
+
face_scores = []
|
| 301 |
+
face_landmarks_5 = []
|
| 302 |
+
face_detector_score = state_manager.get_item('face_detector_score')
|
| 303 |
+
face_detector_width, face_detector_height = unpack_resolution(face_detector_size)
|
| 304 |
+
temp_vision_frame = restrict_frame(vision_frame, (face_detector_width, face_detector_height))
|
| 305 |
+
ratio_height = vision_frame.shape[0] / temp_vision_frame.shape[0]
|
| 306 |
+
ratio_width = vision_frame.shape[1] / temp_vision_frame.shape[1]
|
| 307 |
+
detect_vision_frame = prepare_detect_frame(temp_vision_frame, face_detector_size)
|
| 308 |
+
detect_vision_frame = normalize_detect_frame(detect_vision_frame, [ 0, 1 ])
|
| 309 |
+
detection = forward_with_yolo_face(detect_vision_frame)
|
| 310 |
+
detection = numpy.squeeze(detection).T
|
| 311 |
+
bounding_boxes_raw, face_scores_raw, face_landmarks_5_raw = numpy.split(detection, [ 4, 5 ], axis = 1)
|
| 312 |
+
keep_indices = numpy.where(face_scores_raw > face_detector_score)[0]
|
| 313 |
+
|
| 314 |
+
if numpy.any(keep_indices):
|
| 315 |
+
bounding_boxes_raw, face_scores_raw, face_landmarks_5_raw = bounding_boxes_raw[keep_indices], face_scores_raw[keep_indices], face_landmarks_5_raw[keep_indices]
|
| 316 |
+
|
| 317 |
+
for bounding_box_raw in bounding_boxes_raw:
|
| 318 |
+
bounding_boxes.append(numpy.array(
|
| 319 |
+
[
|
| 320 |
+
(bounding_box_raw[0] - bounding_box_raw[2] / 2) * ratio_width,
|
| 321 |
+
(bounding_box_raw[1] - bounding_box_raw[3] / 2) * ratio_height,
|
| 322 |
+
(bounding_box_raw[0] + bounding_box_raw[2] / 2) * ratio_width,
|
| 323 |
+
(bounding_box_raw[1] + bounding_box_raw[3] / 2) * ratio_height
|
| 324 |
+
]))
|
| 325 |
+
|
| 326 |
+
face_scores = face_scores_raw.ravel().tolist()
|
| 327 |
+
face_landmarks_5_raw[:, 0::3] = (face_landmarks_5_raw[:, 0::3]) * ratio_width
|
| 328 |
+
face_landmarks_5_raw[:, 1::3] = (face_landmarks_5_raw[:, 1::3]) * ratio_height
|
| 329 |
+
|
| 330 |
+
for face_landmark_raw_5 in face_landmarks_5_raw:
|
| 331 |
+
face_landmarks_5.append(numpy.array(face_landmark_raw_5.reshape(-1, 3)[:, :2]))
|
| 332 |
+
|
| 333 |
+
return bounding_boxes, face_scores, face_landmarks_5
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def detect_with_yunet(vision_frame : VisionFrame, face_detector_size : str) -> Tuple[List[BoundingBox], List[Score], List[FaceLandmark5]]:
|
| 337 |
+
bounding_boxes = []
|
| 338 |
+
face_scores = []
|
| 339 |
+
face_landmarks_5 = []
|
| 340 |
+
feature_strides = [ 8, 16, 32 ]
|
| 341 |
+
feature_map_channel = 3
|
| 342 |
+
anchor_total = 1
|
| 343 |
+
face_detector_score = state_manager.get_item('face_detector_score')
|
| 344 |
+
face_detector_width, face_detector_height = unpack_resolution(face_detector_size)
|
| 345 |
+
temp_vision_frame = restrict_frame(vision_frame, (face_detector_width, face_detector_height))
|
| 346 |
+
ratio_height = vision_frame.shape[0] / temp_vision_frame.shape[0]
|
| 347 |
+
ratio_width = vision_frame.shape[1] / temp_vision_frame.shape[1]
|
| 348 |
+
detect_vision_frame = prepare_detect_frame(temp_vision_frame, face_detector_size)
|
| 349 |
+
detect_vision_frame = normalize_detect_frame(detect_vision_frame, [ 0, 255 ])
|
| 350 |
+
detection = forward_with_yunet(detect_vision_frame)
|
| 351 |
+
|
| 352 |
+
for index, feature_stride in enumerate(feature_strides):
|
| 353 |
+
face_scores_raw = (detection[index] * detection[index + feature_map_channel]).reshape(-1)
|
| 354 |
+
keep_indices = numpy.where(face_scores_raw >= face_detector_score)[0]
|
| 355 |
+
|
| 356 |
+
if numpy.any(keep_indices):
|
| 357 |
+
stride_height = face_detector_height // feature_stride
|
| 358 |
+
stride_width = face_detector_width // feature_stride
|
| 359 |
+
anchors = create_static_anchors(feature_stride, anchor_total, stride_height, stride_width)
|
| 360 |
+
bounding_boxes_center = detection[index + feature_map_channel * 2].squeeze(0)[:, :2] * feature_stride + anchors
|
| 361 |
+
bounding_boxes_size = numpy.exp(detection[index + feature_map_channel * 2].squeeze(0)[:, 2:4]) * feature_stride
|
| 362 |
+
face_landmarks_5_raw = detection[index + feature_map_channel * 3].squeeze(0)
|
| 363 |
+
|
| 364 |
+
bounding_boxes_raw = numpy.stack(
|
| 365 |
+
[
|
| 366 |
+
bounding_boxes_center[:, 0] - bounding_boxes_size[:, 0] / 2,
|
| 367 |
+
bounding_boxes_center[:, 1] - bounding_boxes_size[:, 1] / 2,
|
| 368 |
+
bounding_boxes_center[:, 0] + bounding_boxes_size[:, 0] / 2,
|
| 369 |
+
bounding_boxes_center[:, 1] + bounding_boxes_size[:, 1] / 2
|
| 370 |
+
], axis = -1)
|
| 371 |
+
|
| 372 |
+
for bounding_box_raw in bounding_boxes_raw[keep_indices]:
|
| 373 |
+
bounding_boxes.append(numpy.array(
|
| 374 |
+
[
|
| 375 |
+
bounding_box_raw[0] * ratio_width,
|
| 376 |
+
bounding_box_raw[1] * ratio_height,
|
| 377 |
+
bounding_box_raw[2] * ratio_width,
|
| 378 |
+
bounding_box_raw[3] * ratio_height
|
| 379 |
+
]))
|
| 380 |
+
|
| 381 |
+
face_scores.extend(face_scores_raw[keep_indices])
|
| 382 |
+
face_landmarks_5_raw = numpy.concatenate(
|
| 383 |
+
[
|
| 384 |
+
face_landmarks_5_raw[:, [0, 1]] * feature_stride + anchors,
|
| 385 |
+
face_landmarks_5_raw[:, [2, 3]] * feature_stride + anchors,
|
| 386 |
+
face_landmarks_5_raw[:, [4, 5]] * feature_stride + anchors,
|
| 387 |
+
face_landmarks_5_raw[:, [6, 7]] * feature_stride + anchors,
|
| 388 |
+
face_landmarks_5_raw[:, [8, 9]] * feature_stride + anchors
|
| 389 |
+
], axis = -1).reshape(-1, 5, 2)
|
| 390 |
+
|
| 391 |
+
for face_landmark_raw_5 in face_landmarks_5_raw[keep_indices]:
|
| 392 |
+
face_landmarks_5.append(face_landmark_raw_5 * [ ratio_width, ratio_height ])
|
| 393 |
+
|
| 394 |
+
return bounding_boxes, face_scores, face_landmarks_5
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def forward_with_retinaface(detect_vision_frame : VisionFrame) -> Detection:
|
| 398 |
+
face_detector = get_inference_pool().get('retinaface')
|
| 399 |
+
|
| 400 |
+
with thread_semaphore():
|
| 401 |
+
detection = face_detector.run(None,
|
| 402 |
+
{
|
| 403 |
+
'input': detect_vision_frame
|
| 404 |
+
})
|
| 405 |
+
|
| 406 |
+
return detection
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def forward_with_scrfd(detect_vision_frame : VisionFrame) -> Detection:
|
| 410 |
+
face_detector = get_inference_pool().get('scrfd')
|
| 411 |
+
|
| 412 |
+
with thread_semaphore():
|
| 413 |
+
detection = face_detector.run(None,
|
| 414 |
+
{
|
| 415 |
+
'input': detect_vision_frame
|
| 416 |
+
})
|
| 417 |
+
|
| 418 |
+
return detection
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def forward_with_yolo_face(detect_vision_frame : VisionFrame) -> Detection:
|
| 422 |
+
face_detector = get_inference_pool().get('yolo_face')
|
| 423 |
+
|
| 424 |
+
with thread_semaphore():
|
| 425 |
+
detection = face_detector.run(None,
|
| 426 |
+
{
|
| 427 |
+
'input': detect_vision_frame
|
| 428 |
+
})
|
| 429 |
+
|
| 430 |
+
return detection
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def forward_with_yunet(detect_vision_frame : VisionFrame) -> Detection:
|
| 434 |
+
face_detector = get_inference_pool().get('yunet')
|
| 435 |
+
|
| 436 |
+
with thread_semaphore():
|
| 437 |
+
detection = face_detector.run(None,
|
| 438 |
+
{
|
| 439 |
+
'input': detect_vision_frame
|
| 440 |
+
})
|
| 441 |
+
|
| 442 |
+
return detection
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def prepare_detect_frame(temp_vision_frame : VisionFrame, face_detector_size : str) -> VisionFrame:
|
| 446 |
+
face_detector_width, face_detector_height = unpack_resolution(face_detector_size)
|
| 447 |
+
detect_vision_frame = numpy.zeros((face_detector_height, face_detector_width, 3))
|
| 448 |
+
detect_vision_frame[:temp_vision_frame.shape[0], :temp_vision_frame.shape[1], :] = temp_vision_frame
|
| 449 |
+
detect_vision_frame = numpy.expand_dims(detect_vision_frame.transpose(2, 0, 1), axis = 0).astype(numpy.float32)
|
| 450 |
+
return detect_vision_frame
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def normalize_detect_frame(detect_vision_frame : VisionFrame, normalize_range : Sequence[int]) -> VisionFrame:
|
| 454 |
+
if normalize_range == [ -1, 1 ]:
|
| 455 |
+
return (detect_vision_frame - 127.5) / 128.0
|
| 456 |
+
if normalize_range == [ 0, 1 ]:
|
| 457 |
+
return detect_vision_frame / 255.0
|
| 458 |
+
return detect_vision_frame
|
facefusion/face_helper.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
from typing import List, Sequence, Tuple
|
| 3 |
+
|
| 4 |
+
import cv2
|
| 5 |
+
import numpy
|
| 6 |
+
from cv2.typing import Size
|
| 7 |
+
|
| 8 |
+
from facefusion.types import Anchors, Angle, BoundingBox, Distance, FaceDetectorModel, FaceLandmark5, FaceLandmark68, Mask, Matrix, Points, Scale, Score, Translation, VisionFrame, WarpTemplate, WarpTemplateSet
|
| 9 |
+
|
| 10 |
+
WARP_TEMPLATE_SET : WarpTemplateSet =\
|
| 11 |
+
{
|
| 12 |
+
'arcface_112_v1': numpy.array(
|
| 13 |
+
[
|
| 14 |
+
[ 0.35473214, 0.45658929 ],
|
| 15 |
+
[ 0.64526786, 0.45658929 ],
|
| 16 |
+
[ 0.50000000, 0.61154464 ],
|
| 17 |
+
[ 0.37913393, 0.77687500 ],
|
| 18 |
+
[ 0.62086607, 0.77687500 ]
|
| 19 |
+
]),
|
| 20 |
+
'arcface_112_v2': numpy.array(
|
| 21 |
+
[
|
| 22 |
+
[ 0.34191607, 0.46157411 ],
|
| 23 |
+
[ 0.65653393, 0.45983393 ],
|
| 24 |
+
[ 0.50022500, 0.64050536 ],
|
| 25 |
+
[ 0.37097589, 0.82469196 ],
|
| 26 |
+
[ 0.63151696, 0.82325089 ]
|
| 27 |
+
]),
|
| 28 |
+
'arcface_128': numpy.array(
|
| 29 |
+
[
|
| 30 |
+
[ 0.36167656, 0.40387734 ],
|
| 31 |
+
[ 0.63696719, 0.40235469 ],
|
| 32 |
+
[ 0.50019687, 0.56044219 ],
|
| 33 |
+
[ 0.38710391, 0.72160547 ],
|
| 34 |
+
[ 0.61507734, 0.72034453 ]
|
| 35 |
+
]),
|
| 36 |
+
'dfl_whole_face': numpy.array(
|
| 37 |
+
[
|
| 38 |
+
[ 0.35342266, 0.39285716 ],
|
| 39 |
+
[ 0.62797622, 0.39285716 ],
|
| 40 |
+
[ 0.48660713, 0.54017860 ],
|
| 41 |
+
[ 0.38839287, 0.68750011 ],
|
| 42 |
+
[ 0.59821427, 0.68750011 ]
|
| 43 |
+
]),
|
| 44 |
+
'ffhq_512': numpy.array(
|
| 45 |
+
[
|
| 46 |
+
[ 0.37691676, 0.46864664 ],
|
| 47 |
+
[ 0.62285697, 0.46912813 ],
|
| 48 |
+
[ 0.50123859, 0.61331904 ],
|
| 49 |
+
[ 0.39308822, 0.72541100 ],
|
| 50 |
+
[ 0.61150205, 0.72490465 ]
|
| 51 |
+
]),
|
| 52 |
+
'mtcnn_512': numpy.array(
|
| 53 |
+
[
|
| 54 |
+
[ 0.36562865, 0.46733799 ],
|
| 55 |
+
[ 0.63305391, 0.46585885 ],
|
| 56 |
+
[ 0.50019127, 0.61942959 ],
|
| 57 |
+
[ 0.39032951, 0.77598822 ],
|
| 58 |
+
[ 0.61178945, 0.77476328 ]
|
| 59 |
+
]),
|
| 60 |
+
'styleganex_384': numpy.array(
|
| 61 |
+
[
|
| 62 |
+
[ 0.42353745, 0.52289879 ],
|
| 63 |
+
[ 0.57725008, 0.52319972 ],
|
| 64 |
+
[ 0.50123859, 0.61331904 ],
|
| 65 |
+
[ 0.43364461, 0.68337652 ],
|
| 66 |
+
[ 0.57015325, 0.68306005 ]
|
| 67 |
+
])
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def estimate_matrix_by_face_landmark_5(face_landmark_5 : FaceLandmark5, warp_template : WarpTemplate, crop_size : Size) -> Matrix:
|
| 72 |
+
warp_template_norm = WARP_TEMPLATE_SET.get(warp_template) * crop_size
|
| 73 |
+
affine_matrix = cv2.estimateAffinePartial2D(face_landmark_5, warp_template_norm, method = cv2.RANSAC, ransacReprojThreshold = 100)[0]
|
| 74 |
+
return affine_matrix
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def warp_face_by_face_landmark_5(temp_vision_frame : VisionFrame, face_landmark_5 : FaceLandmark5, warp_template : WarpTemplate, crop_size : Size) -> Tuple[VisionFrame, Matrix]:
|
| 78 |
+
affine_matrix = estimate_matrix_by_face_landmark_5(face_landmark_5, warp_template, crop_size)
|
| 79 |
+
crop_vision_frame = cv2.warpAffine(temp_vision_frame, affine_matrix, crop_size, borderMode = cv2.BORDER_REPLICATE, flags = cv2.INTER_AREA)
|
| 80 |
+
return crop_vision_frame, affine_matrix
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def warp_face_by_bounding_box(temp_vision_frame : VisionFrame, bounding_box : BoundingBox, crop_size : Size) -> Tuple[VisionFrame, Matrix]:
|
| 84 |
+
source_points = numpy.array([ [ bounding_box[0], bounding_box[1] ], [bounding_box[2], bounding_box[1] ], [ bounding_box[0], bounding_box[3] ] ]).astype(numpy.float32)
|
| 85 |
+
target_points = numpy.array([ [ 0, 0 ], [ crop_size[0], 0 ], [ 0, crop_size[1] ] ]).astype(numpy.float32)
|
| 86 |
+
affine_matrix = cv2.getAffineTransform(source_points, target_points)
|
| 87 |
+
if bounding_box[2] - bounding_box[0] > crop_size[0] or bounding_box[3] - bounding_box[1] > crop_size[1]:
|
| 88 |
+
interpolation_method = cv2.INTER_AREA
|
| 89 |
+
else:
|
| 90 |
+
interpolation_method = cv2.INTER_LINEAR
|
| 91 |
+
crop_vision_frame = cv2.warpAffine(temp_vision_frame, affine_matrix, crop_size, flags = interpolation_method)
|
| 92 |
+
return crop_vision_frame, affine_matrix
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def warp_face_by_translation(temp_vision_frame : VisionFrame, translation : Translation, scale : float, crop_size : Size) -> Tuple[VisionFrame, Matrix]:
|
| 96 |
+
affine_matrix = numpy.array([ [ scale, 0, translation[0] ], [ 0, scale, translation[1] ] ])
|
| 97 |
+
crop_vision_frame = cv2.warpAffine(temp_vision_frame, affine_matrix, crop_size)
|
| 98 |
+
return crop_vision_frame, affine_matrix
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def paste_back(temp_vision_frame : VisionFrame, crop_vision_frame : VisionFrame, crop_vision_mask : Mask, affine_matrix : Matrix) -> VisionFrame:
|
| 102 |
+
paste_bounding_box, paste_matrix = calculate_paste_area(temp_vision_frame, crop_vision_frame, affine_matrix)
|
| 103 |
+
x1, y1, x2, y2 = paste_bounding_box
|
| 104 |
+
paste_width = x2 - x1
|
| 105 |
+
paste_height = y2 - y1
|
| 106 |
+
inverse_vision_mask = cv2.warpAffine(crop_vision_mask, paste_matrix, (paste_width, paste_height)).clip(0, 1)
|
| 107 |
+
inverse_vision_mask = numpy.expand_dims(inverse_vision_mask, axis = -1)
|
| 108 |
+
inverse_vision_frame = cv2.warpAffine(crop_vision_frame, paste_matrix, (paste_width, paste_height), borderMode = cv2.BORDER_REPLICATE)
|
| 109 |
+
temp_vision_frame = temp_vision_frame.copy()
|
| 110 |
+
paste_vision_frame = temp_vision_frame[y1:y2, x1:x2]
|
| 111 |
+
paste_vision_frame = paste_vision_frame * (1 - inverse_vision_mask) + inverse_vision_frame * inverse_vision_mask
|
| 112 |
+
temp_vision_frame[y1:y2, x1:x2] = paste_vision_frame.astype(temp_vision_frame.dtype)
|
| 113 |
+
return temp_vision_frame
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def calculate_paste_area(temp_vision_frame : VisionFrame, crop_vision_frame : VisionFrame, affine_matrix : Matrix) -> Tuple[BoundingBox, Matrix]:
|
| 117 |
+
temp_height, temp_width = temp_vision_frame.shape[:2]
|
| 118 |
+
crop_height, crop_width = crop_vision_frame.shape[:2]
|
| 119 |
+
inverse_matrix = cv2.invertAffineTransform(affine_matrix)
|
| 120 |
+
crop_points = numpy.array([ [ 0, 0 ], [ crop_width, 0 ], [ crop_width, crop_height ], [ 0, crop_height ] ])
|
| 121 |
+
paste_region_points = transform_points(crop_points, inverse_matrix)
|
| 122 |
+
paste_region_point_min = numpy.floor(paste_region_points.min(axis = 0)).astype(int)
|
| 123 |
+
paste_region_point_max = numpy.ceil(paste_region_points.max(axis = 0)).astype(int)
|
| 124 |
+
x1, y1 = numpy.clip(paste_region_point_min, 0, [ temp_width, temp_height ])
|
| 125 |
+
x2, y2 = numpy.clip(paste_region_point_max, 0, [ temp_width, temp_height ])
|
| 126 |
+
paste_bounding_box = numpy.array([ x1, y1, x2, y2 ])
|
| 127 |
+
paste_matrix = inverse_matrix.copy()
|
| 128 |
+
paste_matrix[0, 2] -= x1
|
| 129 |
+
paste_matrix[1, 2] -= y1
|
| 130 |
+
return paste_bounding_box, paste_matrix
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@lru_cache()
|
| 134 |
+
def create_static_anchors(feature_stride : int, anchor_total : int, stride_height : int, stride_width : int) -> Anchors:
|
| 135 |
+
x, y = numpy.mgrid[:stride_width, :stride_height]
|
| 136 |
+
anchors = numpy.stack((y, x), axis = -1)
|
| 137 |
+
anchors = (anchors * feature_stride).reshape((-1, 2))
|
| 138 |
+
anchors = numpy.stack([ anchors ] * anchor_total, axis = 1).reshape((-1, 2))
|
| 139 |
+
return anchors
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def create_rotation_matrix_and_size(angle : Angle, size : Size) -> Tuple[Matrix, Size]:
|
| 143 |
+
rotation_matrix = cv2.getRotationMatrix2D((size[0] / 2, size[1] / 2), angle, 1)
|
| 144 |
+
rotation_size = numpy.dot(numpy.abs(rotation_matrix[:, :2]), size)
|
| 145 |
+
rotation_matrix[:, -1] += (rotation_size - size) * 0.5 #type:ignore[misc]
|
| 146 |
+
rotation_size = int(rotation_size[0]), int(rotation_size[1])
|
| 147 |
+
return rotation_matrix, rotation_size
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def create_bounding_box(face_landmark_68 : FaceLandmark68) -> BoundingBox:
|
| 151 |
+
x1, y1 = numpy.min(face_landmark_68, axis = 0)
|
| 152 |
+
x2, y2 = numpy.max(face_landmark_68, axis = 0)
|
| 153 |
+
bounding_box = normalize_bounding_box(numpy.array([ x1, y1, x2, y2 ]))
|
| 154 |
+
return bounding_box
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def normalize_bounding_box(bounding_box : BoundingBox) -> BoundingBox:
|
| 158 |
+
x1, y1, x2, y2 = bounding_box
|
| 159 |
+
x1, x2 = sorted([ x1, x2 ])
|
| 160 |
+
y1, y2 = sorted([ y1, y2 ])
|
| 161 |
+
return numpy.array([ x1, y1, x2, y2 ])
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def transform_points(points : Points, matrix : Matrix) -> Points:
|
| 165 |
+
points = points.reshape(-1, 1, 2)
|
| 166 |
+
points = cv2.transform(points, matrix) #type:ignore[assignment]
|
| 167 |
+
points = points.reshape(-1, 2)
|
| 168 |
+
return points
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def transform_bounding_box(bounding_box : BoundingBox, matrix : Matrix) -> BoundingBox:
|
| 172 |
+
points = numpy.array(
|
| 173 |
+
[
|
| 174 |
+
[ bounding_box[0], bounding_box[1] ],
|
| 175 |
+
[ bounding_box[2], bounding_box[1] ],
|
| 176 |
+
[ bounding_box[2], bounding_box[3] ],
|
| 177 |
+
[ bounding_box[0], bounding_box[3] ]
|
| 178 |
+
])
|
| 179 |
+
points = transform_points(points, matrix)
|
| 180 |
+
x1, y1 = numpy.min(points, axis = 0)
|
| 181 |
+
x2, y2 = numpy.max(points, axis = 0)
|
| 182 |
+
return normalize_bounding_box(numpy.array([ x1, y1, x2, y2 ]))
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def distance_to_bounding_box(points : Points, distance : Distance) -> BoundingBox:
|
| 186 |
+
x1 = points[:, 0] - distance[:, 0]
|
| 187 |
+
y1 = points[:, 1] - distance[:, 1]
|
| 188 |
+
x2 = points[:, 0] + distance[:, 2]
|
| 189 |
+
y2 = points[:, 1] + distance[:, 3]
|
| 190 |
+
bounding_box = numpy.column_stack([ x1, y1, x2, y2 ])
|
| 191 |
+
return bounding_box
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def distance_to_face_landmark_5(points : Points, distance : Distance) -> FaceLandmark5:
|
| 195 |
+
x = points[:, 0::2] + distance[:, 0::2]
|
| 196 |
+
y = points[:, 1::2] + distance[:, 1::2]
|
| 197 |
+
face_landmark_5 = numpy.stack((x, y), axis = -1)
|
| 198 |
+
return face_landmark_5
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def scale_face_landmark_5(face_landmark_5 : FaceLandmark5, scale : Scale) -> FaceLandmark5:
|
| 202 |
+
face_landmark_5_scale = face_landmark_5 - face_landmark_5[2]
|
| 203 |
+
face_landmark_5_scale *= scale
|
| 204 |
+
face_landmark_5_scale += face_landmark_5[2]
|
| 205 |
+
return face_landmark_5_scale
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def convert_to_face_landmark_5(face_landmark_68 : FaceLandmark68) -> FaceLandmark5:
|
| 209 |
+
face_landmark_5 = numpy.array(
|
| 210 |
+
[
|
| 211 |
+
numpy.mean(face_landmark_68[36:42], axis = 0),
|
| 212 |
+
numpy.mean(face_landmark_68[42:48], axis = 0),
|
| 213 |
+
face_landmark_68[30],
|
| 214 |
+
face_landmark_68[48],
|
| 215 |
+
face_landmark_68[54]
|
| 216 |
+
])
|
| 217 |
+
return face_landmark_5
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def estimate_face_angle(face_landmark_68 : FaceLandmark68) -> Angle:
|
| 221 |
+
x1, y1 = face_landmark_68[0]
|
| 222 |
+
x2, y2 = face_landmark_68[16]
|
| 223 |
+
theta = numpy.arctan2(y2 - y1, x2 - x1)
|
| 224 |
+
theta = numpy.degrees(theta) % 360
|
| 225 |
+
angles = numpy.linspace(0, 360, 5)
|
| 226 |
+
index = numpy.argmin(numpy.abs(angles - theta))
|
| 227 |
+
face_angle = int(angles[index] % 360)
|
| 228 |
+
return face_angle
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def apply_nms(bounding_boxes : List[BoundingBox], scores : List[Score], score_threshold : float, nms_threshold : float) -> Sequence[int]:
|
| 232 |
+
bounding_boxes_norm = [ (x1, y1, x2 - x1, y2 - y1) for (x1, y1, x2, y2) in bounding_boxes ]
|
| 233 |
+
keep_indices = cv2.dnn.NMSBoxes(bounding_boxes_norm, scores, score_threshold = score_threshold, nms_threshold = nms_threshold)
|
| 234 |
+
return keep_indices
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def get_nms_threshold(face_detector_model : FaceDetectorModel, face_detector_angles : List[Angle]) -> float:
|
| 238 |
+
if face_detector_model == 'many':
|
| 239 |
+
return 0.1
|
| 240 |
+
if len(face_detector_angles) == 2:
|
| 241 |
+
return 0.3
|
| 242 |
+
if len(face_detector_angles) == 3:
|
| 243 |
+
return 0.2
|
| 244 |
+
if len(face_detector_angles) == 4:
|
| 245 |
+
return 0.1
|
| 246 |
+
return 0.4
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def merge_matrix(temp_matrices : List[Matrix]) -> Matrix:
|
| 250 |
+
matrix = numpy.vstack([temp_matrices[0], [0, 0, 1]])
|
| 251 |
+
|
| 252 |
+
for temp_matrix in temp_matrices[1:]:
|
| 253 |
+
temp_matrix = numpy.vstack([ temp_matrix, [ 0, 0, 1 ] ])
|
| 254 |
+
matrix = numpy.dot(temp_matrix, matrix)
|
| 255 |
+
|
| 256 |
+
return matrix[:2, :]
|
facefusion/face_landmarker.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
from typing import Tuple
|
| 3 |
+
|
| 4 |
+
import cv2
|
| 5 |
+
import numpy
|
| 6 |
+
|
| 7 |
+
from facefusion import inference_manager, state_manager
|
| 8 |
+
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
| 9 |
+
from facefusion.face_helper import create_rotation_matrix_and_size, estimate_matrix_by_face_landmark_5, transform_points, warp_face_by_translation
|
| 10 |
+
from facefusion.filesystem import resolve_relative_path
|
| 11 |
+
from facefusion.thread_helper import conditional_thread_semaphore
|
| 12 |
+
from facefusion.types import Angle, BoundingBox, DownloadScope, DownloadSet, FaceLandmark5, FaceLandmark68, InferencePool, ModelSet, Prediction, Score, VisionFrame
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@lru_cache()
|
| 16 |
+
def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
| 17 |
+
return\
|
| 18 |
+
{
|
| 19 |
+
'2dfan4':
|
| 20 |
+
{
|
| 21 |
+
'__metadata__':
|
| 22 |
+
{
|
| 23 |
+
'vendor': 'breadbread1984',
|
| 24 |
+
'license': 'MIT',
|
| 25 |
+
'year': 2018
|
| 26 |
+
},
|
| 27 |
+
'hashes':
|
| 28 |
+
{
|
| 29 |
+
'2dfan4':
|
| 30 |
+
{
|
| 31 |
+
'url': resolve_download_url('models-3.0.0', '2dfan4.hash'),
|
| 32 |
+
'path': resolve_relative_path('../.assets/models/2dfan4.hash')
|
| 33 |
+
}
|
| 34 |
+
},
|
| 35 |
+
'sources':
|
| 36 |
+
{
|
| 37 |
+
'2dfan4':
|
| 38 |
+
{
|
| 39 |
+
'url': resolve_download_url('models-3.0.0', '2dfan4.onnx'),
|
| 40 |
+
'path': resolve_relative_path('../.assets/models/2dfan4.onnx')
|
| 41 |
+
}
|
| 42 |
+
},
|
| 43 |
+
'size': (256, 256)
|
| 44 |
+
},
|
| 45 |
+
'peppa_wutz':
|
| 46 |
+
{
|
| 47 |
+
'__metadata__':
|
| 48 |
+
{
|
| 49 |
+
'vendor': 'Unknown',
|
| 50 |
+
'license': 'Apache-2.0',
|
| 51 |
+
'year': 2023
|
| 52 |
+
},
|
| 53 |
+
'hashes':
|
| 54 |
+
{
|
| 55 |
+
'peppa_wutz':
|
| 56 |
+
{
|
| 57 |
+
'url': resolve_download_url('models-3.0.0', 'peppa_wutz.hash'),
|
| 58 |
+
'path': resolve_relative_path('../.assets/models/peppa_wutz.hash')
|
| 59 |
+
}
|
| 60 |
+
},
|
| 61 |
+
'sources':
|
| 62 |
+
{
|
| 63 |
+
'peppa_wutz':
|
| 64 |
+
{
|
| 65 |
+
'url': resolve_download_url('models-3.0.0', 'peppa_wutz.onnx'),
|
| 66 |
+
'path': resolve_relative_path('../.assets/models/peppa_wutz.onnx')
|
| 67 |
+
}
|
| 68 |
+
},
|
| 69 |
+
'size': (256, 256)
|
| 70 |
+
},
|
| 71 |
+
'fan_68_5':
|
| 72 |
+
{
|
| 73 |
+
'__metadata__':
|
| 74 |
+
{
|
| 75 |
+
'vendor': 'FaceFusion',
|
| 76 |
+
'license': 'OpenRAIL-M',
|
| 77 |
+
'year': 2024
|
| 78 |
+
},
|
| 79 |
+
'hashes':
|
| 80 |
+
{
|
| 81 |
+
'fan_68_5':
|
| 82 |
+
{
|
| 83 |
+
'url': resolve_download_url('models-3.0.0', 'fan_68_5.hash'),
|
| 84 |
+
'path': resolve_relative_path('../.assets/models/fan_68_5.hash')
|
| 85 |
+
}
|
| 86 |
+
},
|
| 87 |
+
'sources':
|
| 88 |
+
{
|
| 89 |
+
'fan_68_5':
|
| 90 |
+
{
|
| 91 |
+
'url': resolve_download_url('models-3.0.0', 'fan_68_5.onnx'),
|
| 92 |
+
'path': resolve_relative_path('../.assets/models/fan_68_5.onnx')
|
| 93 |
+
}
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def get_inference_pool() -> InferencePool:
|
| 100 |
+
model_names = [ state_manager.get_item('face_landmarker_model'), 'fan_68_5' ]
|
| 101 |
+
_, model_source_set = collect_model_downloads()
|
| 102 |
+
|
| 103 |
+
return inference_manager.get_inference_pool(__name__, model_names, model_source_set)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def clear_inference_pool() -> None:
|
| 107 |
+
model_names = [ state_manager.get_item('face_landmarker_model'), 'fan_68_5' ]
|
| 108 |
+
inference_manager.clear_inference_pool(__name__, model_names)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def collect_model_downloads() -> Tuple[DownloadSet, DownloadSet]:
|
| 112 |
+
model_set = create_static_model_set('full')
|
| 113 |
+
model_hash_set =\
|
| 114 |
+
{
|
| 115 |
+
'fan_68_5': model_set.get('fan_68_5').get('hashes').get('fan_68_5')
|
| 116 |
+
}
|
| 117 |
+
model_source_set =\
|
| 118 |
+
{
|
| 119 |
+
'fan_68_5': model_set.get('fan_68_5').get('sources').get('fan_68_5')
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
for face_landmarker_model in [ '2dfan4', 'peppa_wutz' ]:
|
| 123 |
+
if state_manager.get_item('face_landmarker_model') in [ 'many', face_landmarker_model ]:
|
| 124 |
+
model_hash_set[face_landmarker_model] = model_set.get(face_landmarker_model).get('hashes').get(face_landmarker_model)
|
| 125 |
+
model_source_set[face_landmarker_model] = model_set.get(face_landmarker_model).get('sources').get(face_landmarker_model)
|
| 126 |
+
|
| 127 |
+
return model_hash_set, model_source_set
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def pre_check() -> bool:
|
| 131 |
+
model_hash_set, model_source_set = collect_model_downloads()
|
| 132 |
+
|
| 133 |
+
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def detect_face_landmark(vision_frame : VisionFrame, bounding_box : BoundingBox, face_angle : Angle) -> Tuple[FaceLandmark68, Score]:
|
| 137 |
+
face_landmark_2dfan4 = None
|
| 138 |
+
face_landmark_peppa_wutz = None
|
| 139 |
+
face_landmark_score_2dfan4 = 0.0
|
| 140 |
+
face_landmark_score_peppa_wutz = 0.0
|
| 141 |
+
|
| 142 |
+
if state_manager.get_item('face_landmarker_model') in [ 'many', '2dfan4' ]:
|
| 143 |
+
face_landmark_2dfan4, face_landmark_score_2dfan4 = detect_with_2dfan4(vision_frame, bounding_box, face_angle)
|
| 144 |
+
|
| 145 |
+
if state_manager.get_item('face_landmarker_model') in [ 'many', 'peppa_wutz' ]:
|
| 146 |
+
face_landmark_peppa_wutz, face_landmark_score_peppa_wutz = detect_with_peppa_wutz(vision_frame, bounding_box, face_angle)
|
| 147 |
+
|
| 148 |
+
if face_landmark_score_2dfan4 > face_landmark_score_peppa_wutz - 0.2:
|
| 149 |
+
return face_landmark_2dfan4, face_landmark_score_2dfan4
|
| 150 |
+
return face_landmark_peppa_wutz, face_landmark_score_peppa_wutz
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def detect_with_2dfan4(temp_vision_frame: VisionFrame, bounding_box: BoundingBox, face_angle: Angle) -> Tuple[FaceLandmark68, Score]:
|
| 154 |
+
model_size = create_static_model_set('full').get('2dfan4').get('size')
|
| 155 |
+
scale = 195 / numpy.subtract(bounding_box[2:], bounding_box[:2]).max().clip(1, None)
|
| 156 |
+
translation = (model_size[0] - numpy.add(bounding_box[2:], bounding_box[:2]) * scale) * 0.5
|
| 157 |
+
rotation_matrix, rotation_size = create_rotation_matrix_and_size(face_angle, model_size)
|
| 158 |
+
crop_vision_frame, affine_matrix = warp_face_by_translation(temp_vision_frame, translation, scale, model_size)
|
| 159 |
+
crop_vision_frame = cv2.warpAffine(crop_vision_frame, rotation_matrix, rotation_size)
|
| 160 |
+
crop_vision_frame = conditional_optimize_contrast(crop_vision_frame)
|
| 161 |
+
crop_vision_frame = crop_vision_frame.transpose(2, 0, 1).astype(numpy.float32) / 255.0
|
| 162 |
+
face_landmark_68, face_heatmap = forward_with_2dfan4(crop_vision_frame)
|
| 163 |
+
face_landmark_68 = face_landmark_68[:, :, :2][0] / 64 * 256
|
| 164 |
+
face_landmark_68 = transform_points(face_landmark_68, cv2.invertAffineTransform(rotation_matrix))
|
| 165 |
+
face_landmark_68 = transform_points(face_landmark_68, cv2.invertAffineTransform(affine_matrix))
|
| 166 |
+
face_landmark_score_68 = numpy.amax(face_heatmap, axis = (2, 3))
|
| 167 |
+
face_landmark_score_68 = numpy.mean(face_landmark_score_68)
|
| 168 |
+
face_landmark_score_68 = numpy.interp(face_landmark_score_68, [ 0, 0.9 ], [ 0, 1 ])
|
| 169 |
+
return face_landmark_68, face_landmark_score_68
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def detect_with_peppa_wutz(temp_vision_frame : VisionFrame, bounding_box : BoundingBox, face_angle : Angle) -> Tuple[FaceLandmark68, Score]:
|
| 173 |
+
model_size = create_static_model_set('full').get('peppa_wutz').get('size')
|
| 174 |
+
scale = 195 / numpy.subtract(bounding_box[2:], bounding_box[:2]).max().clip(1, None)
|
| 175 |
+
translation = (model_size[0] - numpy.add(bounding_box[2:], bounding_box[:2]) * scale) * 0.5
|
| 176 |
+
rotation_matrix, rotation_size = create_rotation_matrix_and_size(face_angle, model_size)
|
| 177 |
+
crop_vision_frame, affine_matrix = warp_face_by_translation(temp_vision_frame, translation, scale, model_size)
|
| 178 |
+
crop_vision_frame = cv2.warpAffine(crop_vision_frame, rotation_matrix, rotation_size)
|
| 179 |
+
crop_vision_frame = conditional_optimize_contrast(crop_vision_frame)
|
| 180 |
+
crop_vision_frame = crop_vision_frame.transpose(2, 0, 1).astype(numpy.float32) / 255.0
|
| 181 |
+
crop_vision_frame = numpy.expand_dims(crop_vision_frame, axis = 0)
|
| 182 |
+
prediction = forward_with_peppa_wutz(crop_vision_frame)
|
| 183 |
+
face_landmark_68 = prediction.reshape(-1, 3)[:, :2] / 64 * model_size[0]
|
| 184 |
+
face_landmark_68 = transform_points(face_landmark_68, cv2.invertAffineTransform(rotation_matrix))
|
| 185 |
+
face_landmark_68 = transform_points(face_landmark_68, cv2.invertAffineTransform(affine_matrix))
|
| 186 |
+
face_landmark_score_68 = prediction.reshape(-1, 3)[:, 2].mean()
|
| 187 |
+
face_landmark_score_68 = numpy.interp(face_landmark_score_68, [ 0, 0.95 ], [ 0, 1 ])
|
| 188 |
+
return face_landmark_68, face_landmark_score_68
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def conditional_optimize_contrast(crop_vision_frame : VisionFrame) -> VisionFrame:
|
| 192 |
+
crop_vision_frame = cv2.cvtColor(crop_vision_frame, cv2.COLOR_RGB2Lab)
|
| 193 |
+
if numpy.mean(crop_vision_frame[:, :, 0]) < 30: #type:ignore[arg-type]
|
| 194 |
+
crop_vision_frame[:, :, 0] = cv2.createCLAHE(clipLimit = 2).apply(crop_vision_frame[:, :, 0])
|
| 195 |
+
crop_vision_frame = cv2.cvtColor(crop_vision_frame, cv2.COLOR_Lab2RGB)
|
| 196 |
+
return crop_vision_frame
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def estimate_face_landmark_68_5(face_landmark_5 : FaceLandmark5) -> FaceLandmark68:
|
| 200 |
+
affine_matrix = estimate_matrix_by_face_landmark_5(face_landmark_5, 'ffhq_512', (1, 1))
|
| 201 |
+
face_landmark_5 = cv2.transform(face_landmark_5.reshape(1, -1, 2), affine_matrix).reshape(-1, 2)
|
| 202 |
+
face_landmark_68_5 = forward_fan_68_5(face_landmark_5)
|
| 203 |
+
face_landmark_68_5 = cv2.transform(face_landmark_68_5.reshape(1, -1, 2), cv2.invertAffineTransform(affine_matrix)).reshape(-1, 2)
|
| 204 |
+
return face_landmark_68_5
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def forward_with_2dfan4(crop_vision_frame : VisionFrame) -> Tuple[Prediction, Prediction]:
|
| 208 |
+
face_landmarker = get_inference_pool().get('2dfan4')
|
| 209 |
+
|
| 210 |
+
with conditional_thread_semaphore():
|
| 211 |
+
prediction = face_landmarker.run(None,
|
| 212 |
+
{
|
| 213 |
+
'input': [ crop_vision_frame ]
|
| 214 |
+
})
|
| 215 |
+
|
| 216 |
+
return prediction
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def forward_with_peppa_wutz(crop_vision_frame : VisionFrame) -> Prediction:
|
| 220 |
+
face_landmarker = get_inference_pool().get('peppa_wutz')
|
| 221 |
+
|
| 222 |
+
with conditional_thread_semaphore():
|
| 223 |
+
prediction = face_landmarker.run(None,
|
| 224 |
+
{
|
| 225 |
+
'input': crop_vision_frame
|
| 226 |
+
})[0]
|
| 227 |
+
|
| 228 |
+
return prediction
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def forward_fan_68_5(face_landmark_5 : FaceLandmark5) -> FaceLandmark68:
|
| 232 |
+
face_landmarker = get_inference_pool().get('fan_68_5')
|
| 233 |
+
|
| 234 |
+
with conditional_thread_semaphore():
|
| 235 |
+
face_landmark_68_5 = face_landmarker.run(None,
|
| 236 |
+
{
|
| 237 |
+
'input': [ face_landmark_5 ]
|
| 238 |
+
})[0][0]
|
| 239 |
+
|
| 240 |
+
return face_landmark_68_5
|
facefusion/face_masker.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
from typing import List, Tuple
|
| 3 |
+
|
| 4 |
+
import cv2
|
| 5 |
+
import numpy
|
| 6 |
+
|
| 7 |
+
import facefusion.choices
|
| 8 |
+
from facefusion import inference_manager, state_manager
|
| 9 |
+
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
| 10 |
+
from facefusion.filesystem import resolve_relative_path
|
| 11 |
+
from facefusion.thread_helper import conditional_thread_semaphore
|
| 12 |
+
from facefusion.types import DownloadScope, DownloadSet, FaceLandmark68, FaceMaskArea, FaceMaskRegion, InferencePool, Mask, ModelSet, Padding, VisionFrame
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@lru_cache()
|
| 16 |
+
def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
| 17 |
+
return\
|
| 18 |
+
{
|
| 19 |
+
'xseg_1':
|
| 20 |
+
{
|
| 21 |
+
'__metadata__':
|
| 22 |
+
{
|
| 23 |
+
'vendor': 'DeepFaceLab',
|
| 24 |
+
'license': 'GPL-3.0',
|
| 25 |
+
'year': 2021
|
| 26 |
+
},
|
| 27 |
+
'hashes':
|
| 28 |
+
{
|
| 29 |
+
'face_occluder':
|
| 30 |
+
{
|
| 31 |
+
'url': resolve_download_url('models-3.1.0', 'xseg_1.hash'),
|
| 32 |
+
'path': resolve_relative_path('../.assets/models/xseg_1.hash')
|
| 33 |
+
}
|
| 34 |
+
},
|
| 35 |
+
'sources':
|
| 36 |
+
{
|
| 37 |
+
'face_occluder':
|
| 38 |
+
{
|
| 39 |
+
'url': resolve_download_url('models-3.1.0', 'xseg_1.onnx'),
|
| 40 |
+
'path': resolve_relative_path('../.assets/models/xseg_1.onnx')
|
| 41 |
+
}
|
| 42 |
+
},
|
| 43 |
+
'size': (256, 256)
|
| 44 |
+
},
|
| 45 |
+
'xseg_2':
|
| 46 |
+
{
|
| 47 |
+
'__metadata__':
|
| 48 |
+
{
|
| 49 |
+
'vendor': 'DeepFaceLab',
|
| 50 |
+
'license': 'GPL-3.0',
|
| 51 |
+
'year': 2021
|
| 52 |
+
},
|
| 53 |
+
'hashes':
|
| 54 |
+
{
|
| 55 |
+
'face_occluder':
|
| 56 |
+
{
|
| 57 |
+
'url': resolve_download_url('models-3.1.0', 'xseg_2.hash'),
|
| 58 |
+
'path': resolve_relative_path('../.assets/models/xseg_2.hash')
|
| 59 |
+
}
|
| 60 |
+
},
|
| 61 |
+
'sources':
|
| 62 |
+
{
|
| 63 |
+
'face_occluder':
|
| 64 |
+
{
|
| 65 |
+
'url': resolve_download_url('models-3.1.0', 'xseg_2.onnx'),
|
| 66 |
+
'path': resolve_relative_path('../.assets/models/xseg_2.onnx')
|
| 67 |
+
}
|
| 68 |
+
},
|
| 69 |
+
'size': (256, 256)
|
| 70 |
+
},
|
| 71 |
+
'xseg_3':
|
| 72 |
+
{
|
| 73 |
+
'__metadata__':
|
| 74 |
+
{
|
| 75 |
+
'vendor': 'DeepFaceLab',
|
| 76 |
+
'license': 'GPL-3.0',
|
| 77 |
+
'year': 2021
|
| 78 |
+
},
|
| 79 |
+
'hashes':
|
| 80 |
+
{
|
| 81 |
+
'face_occluder':
|
| 82 |
+
{
|
| 83 |
+
'url': resolve_download_url('models-3.2.0', 'xseg_3.hash'),
|
| 84 |
+
'path': resolve_relative_path('../.assets/models/xseg_3.hash')
|
| 85 |
+
}
|
| 86 |
+
},
|
| 87 |
+
'sources':
|
| 88 |
+
{
|
| 89 |
+
'face_occluder':
|
| 90 |
+
{
|
| 91 |
+
'url': resolve_download_url('models-3.2.0', 'xseg_3.onnx'),
|
| 92 |
+
'path': resolve_relative_path('../.assets/models/xseg_3.onnx')
|
| 93 |
+
}
|
| 94 |
+
},
|
| 95 |
+
'size': (256, 256)
|
| 96 |
+
},
|
| 97 |
+
'bisenet_resnet_18':
|
| 98 |
+
{
|
| 99 |
+
'__metadata__':
|
| 100 |
+
{
|
| 101 |
+
'vendor': 'yakhyo',
|
| 102 |
+
'license': 'MIT',
|
| 103 |
+
'year': 2024
|
| 104 |
+
},
|
| 105 |
+
'hashes':
|
| 106 |
+
{
|
| 107 |
+
'face_parser':
|
| 108 |
+
{
|
| 109 |
+
'url': resolve_download_url('models-3.1.0', 'bisenet_resnet_18.hash'),
|
| 110 |
+
'path': resolve_relative_path('../.assets/models/bisenet_resnet_18.hash')
|
| 111 |
+
}
|
| 112 |
+
},
|
| 113 |
+
'sources':
|
| 114 |
+
{
|
| 115 |
+
'face_parser':
|
| 116 |
+
{
|
| 117 |
+
'url': resolve_download_url('models-3.1.0', 'bisenet_resnet_18.onnx'),
|
| 118 |
+
'path': resolve_relative_path('../.assets/models/bisenet_resnet_18.onnx')
|
| 119 |
+
}
|
| 120 |
+
},
|
| 121 |
+
'size': (512, 512)
|
| 122 |
+
},
|
| 123 |
+
'bisenet_resnet_34':
|
| 124 |
+
{
|
| 125 |
+
'__metadata__':
|
| 126 |
+
{
|
| 127 |
+
'vendor': 'yakhyo',
|
| 128 |
+
'license': 'MIT',
|
| 129 |
+
'year': 2024
|
| 130 |
+
},
|
| 131 |
+
'hashes':
|
| 132 |
+
{
|
| 133 |
+
'face_parser':
|
| 134 |
+
{
|
| 135 |
+
'url': resolve_download_url('models-3.0.0', 'bisenet_resnet_34.hash'),
|
| 136 |
+
'path': resolve_relative_path('../.assets/models/bisenet_resnet_34.hash')
|
| 137 |
+
}
|
| 138 |
+
},
|
| 139 |
+
'sources':
|
| 140 |
+
{
|
| 141 |
+
'face_parser':
|
| 142 |
+
{
|
| 143 |
+
'url': resolve_download_url('models-3.0.0', 'bisenet_resnet_34.onnx'),
|
| 144 |
+
'path': resolve_relative_path('../.assets/models/bisenet_resnet_34.onnx')
|
| 145 |
+
}
|
| 146 |
+
},
|
| 147 |
+
'size': (512, 512)
|
| 148 |
+
}
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def get_inference_pool() -> InferencePool:
|
| 153 |
+
model_names = [ state_manager.get_item('face_occluder_model'), state_manager.get_item('face_parser_model') ]
|
| 154 |
+
_, model_source_set = collect_model_downloads()
|
| 155 |
+
|
| 156 |
+
return inference_manager.get_inference_pool(__name__, model_names, model_source_set)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def clear_inference_pool() -> None:
|
| 160 |
+
model_names = [ state_manager.get_item('face_occluder_model'), state_manager.get_item('face_parser_model') ]
|
| 161 |
+
inference_manager.clear_inference_pool(__name__, model_names)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def collect_model_downloads() -> Tuple[DownloadSet, DownloadSet]:
|
| 165 |
+
model_set = create_static_model_set('full')
|
| 166 |
+
model_hash_set = {}
|
| 167 |
+
model_source_set = {}
|
| 168 |
+
|
| 169 |
+
for face_occluder_model in [ 'xseg_1', 'xseg_2', 'xseg_3' ]:
|
| 170 |
+
if state_manager.get_item('face_occluder_model') in [ 'many', face_occluder_model ]:
|
| 171 |
+
model_hash_set[face_occluder_model] = model_set.get(face_occluder_model).get('hashes').get('face_occluder')
|
| 172 |
+
model_source_set[face_occluder_model] = model_set.get(face_occluder_model).get('sources').get('face_occluder')
|
| 173 |
+
|
| 174 |
+
for face_parser_model in [ 'bisenet_resnet_18', 'bisenet_resnet_34' ]:
|
| 175 |
+
if state_manager.get_item('face_parser_model') == face_parser_model:
|
| 176 |
+
model_hash_set[face_parser_model] = model_set.get(face_parser_model).get('hashes').get('face_parser')
|
| 177 |
+
model_source_set[face_parser_model] = model_set.get(face_parser_model).get('sources').get('face_parser')
|
| 178 |
+
|
| 179 |
+
return model_hash_set, model_source_set
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def pre_check() -> bool:
|
| 183 |
+
model_hash_set, model_source_set = collect_model_downloads()
|
| 184 |
+
|
| 185 |
+
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def create_box_mask(crop_vision_frame : VisionFrame, face_mask_blur : float, face_mask_padding : Padding) -> Mask:
|
| 189 |
+
crop_size = crop_vision_frame.shape[:2][::-1]
|
| 190 |
+
blur_amount = int(crop_size[0] * 0.5 * face_mask_blur)
|
| 191 |
+
blur_area = max(blur_amount // 2, 1)
|
| 192 |
+
box_mask : Mask = numpy.ones(crop_size).astype(numpy.float32)
|
| 193 |
+
box_mask[:max(blur_area, int(crop_size[1] * face_mask_padding[0] / 100)), :] = 0
|
| 194 |
+
box_mask[-max(blur_area, int(crop_size[1] * face_mask_padding[2] / 100)):, :] = 0
|
| 195 |
+
box_mask[:, :max(blur_area, int(crop_size[0] * face_mask_padding[3] / 100))] = 0
|
| 196 |
+
box_mask[:, -max(blur_area, int(crop_size[0] * face_mask_padding[1] / 100)):] = 0
|
| 197 |
+
|
| 198 |
+
if blur_amount > 0:
|
| 199 |
+
box_mask = cv2.GaussianBlur(box_mask, (0, 0), blur_amount * 0.25)
|
| 200 |
+
return box_mask
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def create_occlusion_mask(crop_vision_frame : VisionFrame) -> Mask:
|
| 204 |
+
temp_masks = []
|
| 205 |
+
|
| 206 |
+
if state_manager.get_item('face_occluder_model') == 'many':
|
| 207 |
+
model_names = [ 'xseg_1', 'xseg_2', 'xseg_3' ]
|
| 208 |
+
else:
|
| 209 |
+
model_names = [ state_manager.get_item('face_occluder_model') ]
|
| 210 |
+
|
| 211 |
+
for model_name in model_names:
|
| 212 |
+
model_size = create_static_model_set('full').get(model_name).get('size')
|
| 213 |
+
prepare_vision_frame = cv2.resize(crop_vision_frame, model_size)
|
| 214 |
+
prepare_vision_frame = numpy.expand_dims(prepare_vision_frame, axis = 0).astype(numpy.float32) / 255.0
|
| 215 |
+
prepare_vision_frame = prepare_vision_frame.transpose(0, 1, 2, 3)
|
| 216 |
+
temp_mask = forward_occlude_face(prepare_vision_frame, model_name)
|
| 217 |
+
temp_mask = temp_mask.transpose(0, 1, 2).clip(0, 1).astype(numpy.float32)
|
| 218 |
+
temp_mask = cv2.resize(temp_mask, crop_vision_frame.shape[:2][::-1])
|
| 219 |
+
temp_masks.append(temp_mask)
|
| 220 |
+
|
| 221 |
+
occlusion_mask = numpy.minimum.reduce(temp_masks)
|
| 222 |
+
occlusion_mask = (cv2.GaussianBlur(occlusion_mask.clip(0, 1), (0, 0), 5).clip(0.5, 1) - 0.5) * 2
|
| 223 |
+
return occlusion_mask
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def create_area_mask(crop_vision_frame : VisionFrame, face_landmark_68 : FaceLandmark68, face_mask_areas : List[FaceMaskArea]) -> Mask:
|
| 227 |
+
crop_size = crop_vision_frame.shape[:2][::-1]
|
| 228 |
+
landmark_points = []
|
| 229 |
+
|
| 230 |
+
for face_mask_area in face_mask_areas:
|
| 231 |
+
if face_mask_area in facefusion.choices.face_mask_area_set:
|
| 232 |
+
landmark_points.extend(facefusion.choices.face_mask_area_set.get(face_mask_area))
|
| 233 |
+
|
| 234 |
+
convex_hull = cv2.convexHull(face_landmark_68[landmark_points].astype(numpy.int32))
|
| 235 |
+
area_mask = numpy.zeros(crop_size).astype(numpy.float32)
|
| 236 |
+
cv2.fillConvexPoly(area_mask, convex_hull, 1.0) # type: ignore[call-overload]
|
| 237 |
+
area_mask = (cv2.GaussianBlur(area_mask.clip(0, 1), (0, 0), 5).clip(0.5, 1) - 0.5) * 2
|
| 238 |
+
return area_mask
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def create_region_mask(crop_vision_frame : VisionFrame, face_mask_regions : List[FaceMaskRegion]) -> Mask:
|
| 242 |
+
model_name = state_manager.get_item('face_parser_model')
|
| 243 |
+
model_size = create_static_model_set('full').get(model_name).get('size')
|
| 244 |
+
prepare_vision_frame = cv2.resize(crop_vision_frame, model_size)
|
| 245 |
+
prepare_vision_frame = prepare_vision_frame[:, :, ::-1].astype(numpy.float32) / 255.0
|
| 246 |
+
prepare_vision_frame = numpy.subtract(prepare_vision_frame, numpy.array([ 0.485, 0.456, 0.406 ]).astype(numpy.float32))
|
| 247 |
+
prepare_vision_frame = numpy.divide(prepare_vision_frame, numpy.array([ 0.229, 0.224, 0.225 ]).astype(numpy.float32))
|
| 248 |
+
prepare_vision_frame = numpy.expand_dims(prepare_vision_frame, axis = 0)
|
| 249 |
+
prepare_vision_frame = prepare_vision_frame.transpose(0, 3, 1, 2)
|
| 250 |
+
region_mask = forward_parse_face(prepare_vision_frame)
|
| 251 |
+
region_mask = numpy.isin(region_mask.argmax(0), [ facefusion.choices.face_mask_region_set.get(face_mask_region) for face_mask_region in face_mask_regions ])
|
| 252 |
+
region_mask = cv2.resize(region_mask.astype(numpy.float32), crop_vision_frame.shape[:2][::-1])
|
| 253 |
+
region_mask = (cv2.GaussianBlur(region_mask.clip(0, 1), (0, 0), 5).clip(0.5, 1) - 0.5) * 2
|
| 254 |
+
return region_mask
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def forward_occlude_face(prepare_vision_frame : VisionFrame, model_name : str) -> Mask:
|
| 258 |
+
face_occluder = get_inference_pool().get(model_name)
|
| 259 |
+
|
| 260 |
+
with conditional_thread_semaphore():
|
| 261 |
+
occlusion_mask : Mask = face_occluder.run(None,
|
| 262 |
+
{
|
| 263 |
+
'input': prepare_vision_frame
|
| 264 |
+
})[0][0]
|
| 265 |
+
|
| 266 |
+
return occlusion_mask
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def forward_parse_face(prepare_vision_frame : VisionFrame) -> Mask:
|
| 270 |
+
model_name = state_manager.get_item('face_parser_model')
|
| 271 |
+
face_parser = get_inference_pool().get(model_name)
|
| 272 |
+
|
| 273 |
+
with conditional_thread_semaphore():
|
| 274 |
+
region_mask : Mask = face_parser.run(None,
|
| 275 |
+
{
|
| 276 |
+
'input': prepare_vision_frame
|
| 277 |
+
})[0][0]
|
| 278 |
+
|
| 279 |
+
return region_mask
|
facefusion/face_recognizer.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
from typing import Tuple
|
| 3 |
+
|
| 4 |
+
import numpy
|
| 5 |
+
|
| 6 |
+
from facefusion import inference_manager
|
| 7 |
+
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
|
| 8 |
+
from facefusion.face_helper import warp_face_by_face_landmark_5
|
| 9 |
+
from facefusion.filesystem import resolve_relative_path
|
| 10 |
+
from facefusion.thread_helper import conditional_thread_semaphore
|
| 11 |
+
from facefusion.types import DownloadScope, Embedding, FaceLandmark5, InferencePool, ModelOptions, ModelSet, VisionFrame
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@lru_cache()
|
| 15 |
+
def create_static_model_set(download_scope : DownloadScope) -> ModelSet:
|
| 16 |
+
return\
|
| 17 |
+
{
|
| 18 |
+
'arcface':
|
| 19 |
+
{
|
| 20 |
+
'__metadata__':
|
| 21 |
+
{
|
| 22 |
+
'vendor': 'InsightFace',
|
| 23 |
+
'license': 'Non-Commercial',
|
| 24 |
+
'year': 2018
|
| 25 |
+
},
|
| 26 |
+
'hashes':
|
| 27 |
+
{
|
| 28 |
+
'face_recognizer':
|
| 29 |
+
{
|
| 30 |
+
'url': resolve_download_url('models-3.0.0', 'arcface_w600k_r50.hash'),
|
| 31 |
+
'path': resolve_relative_path('../.assets/models/arcface_w600k_r50.hash')
|
| 32 |
+
}
|
| 33 |
+
},
|
| 34 |
+
'sources':
|
| 35 |
+
{
|
| 36 |
+
'face_recognizer':
|
| 37 |
+
{
|
| 38 |
+
'url': resolve_download_url('models-3.0.0', 'arcface_w600k_r50.onnx'),
|
| 39 |
+
'path': resolve_relative_path('../.assets/models/arcface_w600k_r50.onnx')
|
| 40 |
+
}
|
| 41 |
+
},
|
| 42 |
+
'template': 'arcface_112_v2',
|
| 43 |
+
'size': (112, 112)
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def get_inference_pool() -> InferencePool:
|
| 49 |
+
model_names = [ 'arcface' ]
|
| 50 |
+
model_source_set = get_model_options().get('sources')
|
| 51 |
+
|
| 52 |
+
return inference_manager.get_inference_pool(__name__, model_names, model_source_set)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def clear_inference_pool() -> None:
|
| 56 |
+
model_names = [ 'arcface' ]
|
| 57 |
+
inference_manager.clear_inference_pool(__name__, model_names)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def get_model_options() -> ModelOptions:
|
| 61 |
+
return create_static_model_set('full').get('arcface')
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def pre_check() -> bool:
|
| 65 |
+
model_hash_set = get_model_options().get('hashes')
|
| 66 |
+
model_source_set = get_model_options().get('sources')
|
| 67 |
+
|
| 68 |
+
return conditional_download_hashes(model_hash_set) and conditional_download_sources(model_source_set)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def calculate_face_embedding(temp_vision_frame : VisionFrame, face_landmark_5 : FaceLandmark5) -> Tuple[Embedding, Embedding]:
|
| 72 |
+
model_template = get_model_options().get('template')
|
| 73 |
+
model_size = get_model_options().get('size')
|
| 74 |
+
crop_vision_frame, matrix = warp_face_by_face_landmark_5(temp_vision_frame, face_landmark_5, model_template, model_size)
|
| 75 |
+
crop_vision_frame = crop_vision_frame / 127.5 - 1
|
| 76 |
+
crop_vision_frame = crop_vision_frame[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32)
|
| 77 |
+
crop_vision_frame = numpy.expand_dims(crop_vision_frame, axis = 0)
|
| 78 |
+
face_embedding = forward(crop_vision_frame)
|
| 79 |
+
face_embedding = face_embedding.ravel()
|
| 80 |
+
face_embedding_norm = face_embedding / numpy.linalg.norm(face_embedding)
|
| 81 |
+
return face_embedding, face_embedding_norm
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def forward(crop_vision_frame : VisionFrame) -> Embedding:
|
| 85 |
+
face_recognizer = get_inference_pool().get('face_recognizer')
|
| 86 |
+
|
| 87 |
+
with conditional_thread_semaphore():
|
| 88 |
+
face_embedding = face_recognizer.run(None,
|
| 89 |
+
{
|
| 90 |
+
'input': crop_vision_frame
|
| 91 |
+
})[0]
|
| 92 |
+
|
| 93 |
+
return face_embedding
|
facefusion/face_selector.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List
|
| 2 |
+
|
| 3 |
+
import numpy
|
| 4 |
+
|
| 5 |
+
from facefusion import state_manager
|
| 6 |
+
from facefusion.face_analyser import get_many_faces, get_one_face
|
| 7 |
+
from facefusion.types import Face, FaceSelectorOrder, Gender, Race, Score, VisionFrame
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def select_faces(reference_vision_frame : VisionFrame, target_vision_frame : VisionFrame) -> List[Face]:
|
| 11 |
+
target_faces = get_many_faces([ target_vision_frame ])
|
| 12 |
+
|
| 13 |
+
if state_manager.get_item('face_selector_mode') == 'many':
|
| 14 |
+
return sort_and_filter_faces(target_faces)
|
| 15 |
+
|
| 16 |
+
if state_manager.get_item('face_selector_mode') == 'one':
|
| 17 |
+
target_face = get_one_face(sort_and_filter_faces(target_faces))
|
| 18 |
+
if target_face:
|
| 19 |
+
return [ target_face ]
|
| 20 |
+
|
| 21 |
+
if state_manager.get_item('face_selector_mode') == 'reference':
|
| 22 |
+
reference_faces = get_many_faces([ reference_vision_frame ])
|
| 23 |
+
reference_faces = sort_and_filter_faces(reference_faces)
|
| 24 |
+
reference_face = get_one_face(reference_faces, state_manager.get_item('reference_face_position'))
|
| 25 |
+
if reference_face:
|
| 26 |
+
match_faces = find_match_faces([ reference_face ], target_faces, state_manager.get_item('reference_face_distance'))
|
| 27 |
+
return match_faces
|
| 28 |
+
|
| 29 |
+
return []
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def find_match_faces(reference_faces : List[Face], target_faces : List[Face], face_distance : float) -> List[Face]:
|
| 33 |
+
match_faces : List[Face] = []
|
| 34 |
+
|
| 35 |
+
for reference_face in reference_faces:
|
| 36 |
+
if reference_face:
|
| 37 |
+
for index, target_face in enumerate(target_faces):
|
| 38 |
+
if compare_faces(target_face, reference_face, face_distance):
|
| 39 |
+
match_faces.append(target_faces[index])
|
| 40 |
+
|
| 41 |
+
return match_faces
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def compare_faces(face : Face, reference_face : Face, face_distance : float) -> bool:
|
| 45 |
+
current_face_distance = calculate_face_distance(face, reference_face)
|
| 46 |
+
current_face_distance = float(numpy.interp(current_face_distance, [ 0, 2 ], [ 0, 1 ]))
|
| 47 |
+
return current_face_distance < face_distance
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def calculate_face_distance(face : Face, reference_face : Face) -> float:
|
| 51 |
+
if hasattr(face, 'embedding_norm') and hasattr(reference_face, 'embedding_norm'):
|
| 52 |
+
return 1 - numpy.dot(face.embedding_norm, reference_face.embedding_norm)
|
| 53 |
+
return 0
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def sort_and_filter_faces(faces : List[Face]) -> List[Face]:
|
| 57 |
+
if faces:
|
| 58 |
+
if state_manager.get_item('face_selector_order'):
|
| 59 |
+
faces = sort_faces_by_order(faces, state_manager.get_item('face_selector_order'))
|
| 60 |
+
if state_manager.get_item('face_selector_gender'):
|
| 61 |
+
faces = filter_faces_by_gender(faces, state_manager.get_item('face_selector_gender'))
|
| 62 |
+
if state_manager.get_item('face_selector_race'):
|
| 63 |
+
faces = filter_faces_by_race(faces, state_manager.get_item('face_selector_race'))
|
| 64 |
+
if state_manager.get_item('face_selector_age_start') or state_manager.get_item('face_selector_age_end'):
|
| 65 |
+
faces = filter_faces_by_age(faces, state_manager.get_item('face_selector_age_start'), state_manager.get_item('face_selector_age_end'))
|
| 66 |
+
return faces
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def sort_faces_by_order(faces : List[Face], order : FaceSelectorOrder) -> List[Face]:
|
| 70 |
+
if order == 'left-right':
|
| 71 |
+
return sorted(faces, key = get_bounding_box_left)
|
| 72 |
+
if order == 'right-left':
|
| 73 |
+
return sorted(faces, key = get_bounding_box_left, reverse = True)
|
| 74 |
+
if order == 'top-bottom':
|
| 75 |
+
return sorted(faces, key = get_bounding_box_top)
|
| 76 |
+
if order == 'bottom-top':
|
| 77 |
+
return sorted(faces, key = get_bounding_box_top, reverse = True)
|
| 78 |
+
if order == 'small-large':
|
| 79 |
+
return sorted(faces, key = get_bounding_box_area)
|
| 80 |
+
if order == 'large-small':
|
| 81 |
+
return sorted(faces, key = get_bounding_box_area, reverse = True)
|
| 82 |
+
if order == 'best-worst':
|
| 83 |
+
return sorted(faces, key = get_face_detector_score, reverse = True)
|
| 84 |
+
if order == 'worst-best':
|
| 85 |
+
return sorted(faces, key = get_face_detector_score)
|
| 86 |
+
return faces
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def get_bounding_box_left(face : Face) -> float:
|
| 90 |
+
return face.bounding_box[0]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def get_bounding_box_top(face : Face) -> float:
|
| 94 |
+
return face.bounding_box[1]
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def get_bounding_box_area(face : Face) -> float:
|
| 98 |
+
return (face.bounding_box[2] - face.bounding_box[0]) * (face.bounding_box[3] - face.bounding_box[1])
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def get_face_detector_score(face : Face) -> Score:
|
| 102 |
+
return face.score_set.get('detector')
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def filter_faces_by_gender(faces : List[Face], gender : Gender) -> List[Face]:
|
| 106 |
+
filter_faces = []
|
| 107 |
+
|
| 108 |
+
for face in faces:
|
| 109 |
+
if face.gender == gender:
|
| 110 |
+
filter_faces.append(face)
|
| 111 |
+
return filter_faces
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def filter_faces_by_age(faces : List[Face], face_selector_age_start : int, face_selector_age_end : int) -> List[Face]:
|
| 115 |
+
filter_faces = []
|
| 116 |
+
age = range(face_selector_age_start, face_selector_age_end)
|
| 117 |
+
|
| 118 |
+
for face in faces:
|
| 119 |
+
if set(face.age) & set(age):
|
| 120 |
+
filter_faces.append(face)
|
| 121 |
+
return filter_faces
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def filter_faces_by_race(faces : List[Face], race : Race) -> List[Face]:
|
| 125 |
+
filter_faces = []
|
| 126 |
+
|
| 127 |
+
for face in faces:
|
| 128 |
+
if face.race == race:
|
| 129 |
+
filter_faces.append(face)
|
| 130 |
+
return filter_faces
|
facefusion/face_store.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Optional
|
| 2 |
+
|
| 3 |
+
from facefusion.hash_helper import create_hash
|
| 4 |
+
from facefusion.types import Face, FaceStore, VisionFrame
|
| 5 |
+
|
| 6 |
+
FACE_STORE : FaceStore =\
|
| 7 |
+
{
|
| 8 |
+
'static_faces': {}
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def get_face_store() -> FaceStore:
|
| 13 |
+
return FACE_STORE
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def get_static_faces(vision_frame : VisionFrame) -> Optional[List[Face]]:
|
| 17 |
+
vision_hash = create_hash(vision_frame.tobytes())
|
| 18 |
+
return FACE_STORE.get('static_faces').get(vision_hash)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def set_static_faces(vision_frame : VisionFrame, faces : List[Face]) -> None:
|
| 22 |
+
vision_hash = create_hash(vision_frame.tobytes())
|
| 23 |
+
if vision_hash:
|
| 24 |
+
FACE_STORE['static_faces'][vision_hash] = faces
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def clear_static_faces() -> None:
|
| 28 |
+
FACE_STORE['static_faces'].clear()
|
facefusion/ffmpeg.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import subprocess
|
| 3 |
+
import tempfile
|
| 4 |
+
from functools import partial
|
| 5 |
+
from typing import List, Optional, cast
|
| 6 |
+
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
|
| 9 |
+
import facefusion.choices
|
| 10 |
+
from facefusion import ffmpeg_builder, logger, process_manager, state_manager, translator
|
| 11 |
+
from facefusion.filesystem import get_file_format, remove_file
|
| 12 |
+
from facefusion.temp_helper import get_temp_file_path, get_temp_frames_pattern
|
| 13 |
+
from facefusion.types import AudioBuffer, AudioEncoder, Command, EncoderSet, Fps, Resolution, UpdateProgress, VideoEncoder, VideoFormat
|
| 14 |
+
from facefusion.vision import detect_video_duration, detect_video_fps, pack_resolution, predict_video_frame_total
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def run_ffmpeg_with_progress(commands : List[Command], update_progress : UpdateProgress) -> subprocess.Popen[bytes]:
|
| 18 |
+
log_level = state_manager.get_item('log_level')
|
| 19 |
+
commands.extend(ffmpeg_builder.set_progress())
|
| 20 |
+
commands.extend(ffmpeg_builder.cast_stream())
|
| 21 |
+
commands = ffmpeg_builder.run(commands)
|
| 22 |
+
process = subprocess.Popen(commands, stderr = subprocess.PIPE, stdout = subprocess.PIPE)
|
| 23 |
+
|
| 24 |
+
while process_manager.is_processing():
|
| 25 |
+
try:
|
| 26 |
+
while __line__ := process.stdout.readline().decode().lower():
|
| 27 |
+
if process_manager.is_stopping():
|
| 28 |
+
process.terminate()
|
| 29 |
+
|
| 30 |
+
if 'frame=' in __line__:
|
| 31 |
+
_, frame_number = __line__.split('frame=')
|
| 32 |
+
update_progress(int(frame_number))
|
| 33 |
+
|
| 34 |
+
if log_level == 'debug':
|
| 35 |
+
log_debug(process)
|
| 36 |
+
process.wait(timeout = 0.5)
|
| 37 |
+
except subprocess.TimeoutExpired:
|
| 38 |
+
continue
|
| 39 |
+
return process
|
| 40 |
+
|
| 41 |
+
return process
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def update_progress(progress : tqdm, frame_number : int) -> None:
|
| 45 |
+
progress.update(frame_number - progress.n)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def run_ffmpeg(commands : List[Command]) -> subprocess.Popen[bytes]:
|
| 49 |
+
log_level = state_manager.get_item('log_level')
|
| 50 |
+
commands = ffmpeg_builder.run(commands)
|
| 51 |
+
process = subprocess.Popen(commands, stderr = subprocess.PIPE, stdout = subprocess.PIPE)
|
| 52 |
+
|
| 53 |
+
while process_manager.is_processing():
|
| 54 |
+
try:
|
| 55 |
+
if log_level == 'debug':
|
| 56 |
+
log_debug(process)
|
| 57 |
+
process.wait(timeout = 0.5)
|
| 58 |
+
except subprocess.TimeoutExpired:
|
| 59 |
+
continue
|
| 60 |
+
return process
|
| 61 |
+
|
| 62 |
+
if process_manager.is_stopping():
|
| 63 |
+
process.terminate()
|
| 64 |
+
|
| 65 |
+
return process
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def open_ffmpeg(commands : List[Command]) -> subprocess.Popen[bytes]:
|
| 69 |
+
commands = ffmpeg_builder.run(commands)
|
| 70 |
+
return subprocess.Popen(commands, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def log_debug(process : subprocess.Popen[bytes]) -> None:
|
| 74 |
+
_, stderr = process.communicate()
|
| 75 |
+
errors = stderr.decode().split(os.linesep)
|
| 76 |
+
|
| 77 |
+
for error in errors:
|
| 78 |
+
if error.strip():
|
| 79 |
+
logger.debug(error.strip(), __name__)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def get_available_encoder_set() -> EncoderSet:
|
| 83 |
+
available_encoder_set : EncoderSet =\
|
| 84 |
+
{
|
| 85 |
+
'audio': [],
|
| 86 |
+
'video': []
|
| 87 |
+
}
|
| 88 |
+
commands = ffmpeg_builder.chain(
|
| 89 |
+
ffmpeg_builder.get_encoders()
|
| 90 |
+
)
|
| 91 |
+
process = run_ffmpeg(commands)
|
| 92 |
+
|
| 93 |
+
while line := process.stdout.readline().decode().lower():
|
| 94 |
+
if line.startswith(' a'):
|
| 95 |
+
audio_encoder = line.split()[1]
|
| 96 |
+
|
| 97 |
+
if audio_encoder in facefusion.choices.output_audio_encoders:
|
| 98 |
+
index = facefusion.choices.output_audio_encoders.index(audio_encoder) #type:ignore[arg-type]
|
| 99 |
+
available_encoder_set['audio'].insert(index, audio_encoder) #type:ignore[arg-type]
|
| 100 |
+
if line.startswith(' v'):
|
| 101 |
+
video_encoder = line.split()[1]
|
| 102 |
+
|
| 103 |
+
if video_encoder in facefusion.choices.output_video_encoders:
|
| 104 |
+
index = facefusion.choices.output_video_encoders.index(video_encoder) #type:ignore[arg-type]
|
| 105 |
+
available_encoder_set['video'].insert(index, video_encoder) #type:ignore[arg-type]
|
| 106 |
+
|
| 107 |
+
return available_encoder_set
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def extract_frames(target_path : str, temp_video_resolution : Resolution, temp_video_fps : Fps, trim_frame_start : int, trim_frame_end : int) -> bool:
|
| 111 |
+
extract_frame_total = predict_video_frame_total(target_path, temp_video_fps, trim_frame_start, trim_frame_end)
|
| 112 |
+
temp_frames_pattern = get_temp_frames_pattern(target_path, '%08d')
|
| 113 |
+
commands = ffmpeg_builder.chain(
|
| 114 |
+
ffmpeg_builder.set_input(target_path),
|
| 115 |
+
ffmpeg_builder.set_media_resolution(pack_resolution(temp_video_resolution)),
|
| 116 |
+
ffmpeg_builder.set_frame_quality(0),
|
| 117 |
+
ffmpeg_builder.select_frame_range(trim_frame_start, trim_frame_end, temp_video_fps),
|
| 118 |
+
ffmpeg_builder.prevent_frame_drop(),
|
| 119 |
+
ffmpeg_builder.set_output(temp_frames_pattern)
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
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:
|
| 123 |
+
process = run_ffmpeg_with_progress(commands, partial(update_progress, progress))
|
| 124 |
+
return process.returncode == 0
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def copy_image(target_path : str, temp_image_resolution : Resolution) -> bool:
|
| 128 |
+
temp_image_path = get_temp_file_path(target_path)
|
| 129 |
+
commands = ffmpeg_builder.chain(
|
| 130 |
+
ffmpeg_builder.set_input(target_path),
|
| 131 |
+
ffmpeg_builder.set_media_resolution(pack_resolution(temp_image_resolution)),
|
| 132 |
+
ffmpeg_builder.set_image_quality(target_path, 100),
|
| 133 |
+
ffmpeg_builder.force_output(temp_image_path)
|
| 134 |
+
)
|
| 135 |
+
return run_ffmpeg(commands).returncode == 0
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def finalize_image(target_path : str, output_path : str, output_image_resolution : Resolution) -> bool:
|
| 139 |
+
output_image_quality = state_manager.get_item('output_image_quality')
|
| 140 |
+
temp_image_path = get_temp_file_path(target_path)
|
| 141 |
+
commands = ffmpeg_builder.chain(
|
| 142 |
+
ffmpeg_builder.set_input(temp_image_path),
|
| 143 |
+
ffmpeg_builder.set_media_resolution(pack_resolution(output_image_resolution)),
|
| 144 |
+
ffmpeg_builder.set_image_quality(target_path, output_image_quality),
|
| 145 |
+
ffmpeg_builder.force_output(output_path)
|
| 146 |
+
)
|
| 147 |
+
return run_ffmpeg(commands).returncode == 0
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def read_audio_buffer(target_path : str, audio_sample_rate : int, audio_sample_size : int, audio_channel_total : int) -> Optional[AudioBuffer]:
|
| 151 |
+
commands = ffmpeg_builder.chain(
|
| 152 |
+
ffmpeg_builder.set_input(target_path),
|
| 153 |
+
ffmpeg_builder.ignore_video_stream(),
|
| 154 |
+
ffmpeg_builder.set_audio_sample_rate(audio_sample_rate),
|
| 155 |
+
ffmpeg_builder.set_audio_sample_size(audio_sample_size),
|
| 156 |
+
ffmpeg_builder.set_audio_channel_total(audio_channel_total),
|
| 157 |
+
ffmpeg_builder.cast_stream()
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
process = open_ffmpeg(commands)
|
| 161 |
+
audio_buffer, _ = process.communicate()
|
| 162 |
+
if process.returncode == 0:
|
| 163 |
+
return audio_buffer
|
| 164 |
+
return None
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def restore_audio(target_path : str, output_path : str, trim_frame_start : int, trim_frame_end : int) -> bool:
|
| 168 |
+
output_audio_encoder = state_manager.get_item('output_audio_encoder')
|
| 169 |
+
output_audio_quality = state_manager.get_item('output_audio_quality')
|
| 170 |
+
output_audio_volume = state_manager.get_item('output_audio_volume')
|
| 171 |
+
target_video_fps = detect_video_fps(target_path)
|
| 172 |
+
temp_video_path = get_temp_file_path(target_path)
|
| 173 |
+
temp_video_format = cast(VideoFormat, get_file_format(temp_video_path))
|
| 174 |
+
temp_video_duration = detect_video_duration(temp_video_path)
|
| 175 |
+
|
| 176 |
+
output_audio_encoder = fix_audio_encoder(temp_video_format, output_audio_encoder)
|
| 177 |
+
commands = ffmpeg_builder.chain(
|
| 178 |
+
ffmpeg_builder.set_input(temp_video_path),
|
| 179 |
+
ffmpeg_builder.select_media_range(trim_frame_start, trim_frame_end, target_video_fps),
|
| 180 |
+
ffmpeg_builder.set_input(target_path),
|
| 181 |
+
ffmpeg_builder.copy_video_encoder(),
|
| 182 |
+
ffmpeg_builder.set_audio_encoder(output_audio_encoder),
|
| 183 |
+
ffmpeg_builder.set_audio_quality(output_audio_encoder, output_audio_quality),
|
| 184 |
+
ffmpeg_builder.set_audio_volume(output_audio_volume),
|
| 185 |
+
ffmpeg_builder.select_media_stream('0:v:0'),
|
| 186 |
+
ffmpeg_builder.select_media_stream('1:a:0'),
|
| 187 |
+
ffmpeg_builder.set_video_duration(temp_video_duration),
|
| 188 |
+
ffmpeg_builder.force_output(output_path)
|
| 189 |
+
)
|
| 190 |
+
return run_ffmpeg(commands).returncode == 0
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def replace_audio(target_path : str, audio_path : str, output_path : str) -> bool:
|
| 194 |
+
output_audio_encoder = state_manager.get_item('output_audio_encoder')
|
| 195 |
+
output_audio_quality = state_manager.get_item('output_audio_quality')
|
| 196 |
+
output_audio_volume = state_manager.get_item('output_audio_volume')
|
| 197 |
+
temp_video_path = get_temp_file_path(target_path)
|
| 198 |
+
temp_video_format = cast(VideoFormat, get_file_format(temp_video_path))
|
| 199 |
+
temp_video_duration = detect_video_duration(temp_video_path)
|
| 200 |
+
|
| 201 |
+
output_audio_encoder = fix_audio_encoder(temp_video_format, output_audio_encoder)
|
| 202 |
+
commands = ffmpeg_builder.chain(
|
| 203 |
+
ffmpeg_builder.set_input(temp_video_path),
|
| 204 |
+
ffmpeg_builder.set_input(audio_path),
|
| 205 |
+
ffmpeg_builder.copy_video_encoder(),
|
| 206 |
+
ffmpeg_builder.set_audio_encoder(output_audio_encoder),
|
| 207 |
+
ffmpeg_builder.set_audio_quality(output_audio_encoder, output_audio_quality),
|
| 208 |
+
ffmpeg_builder.set_audio_volume(output_audio_volume),
|
| 209 |
+
ffmpeg_builder.set_video_duration(temp_video_duration),
|
| 210 |
+
ffmpeg_builder.force_output(output_path)
|
| 211 |
+
)
|
| 212 |
+
return run_ffmpeg(commands).returncode == 0
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def merge_video(target_path : str, temp_video_fps : Fps, output_video_resolution : Resolution, output_video_fps : Fps, trim_frame_start : int, trim_frame_end : int) -> bool:
|
| 216 |
+
output_video_encoder = state_manager.get_item('output_video_encoder')
|
| 217 |
+
output_video_quality = state_manager.get_item('output_video_quality')
|
| 218 |
+
output_video_preset = state_manager.get_item('output_video_preset')
|
| 219 |
+
merge_frame_total = predict_video_frame_total(target_path, output_video_fps, trim_frame_start, trim_frame_end)
|
| 220 |
+
temp_video_path = get_temp_file_path(target_path)
|
| 221 |
+
temp_video_format = cast(VideoFormat, get_file_format(temp_video_path))
|
| 222 |
+
temp_frames_pattern = get_temp_frames_pattern(target_path, '%08d')
|
| 223 |
+
|
| 224 |
+
output_video_encoder = fix_video_encoder(temp_video_format, output_video_encoder)
|
| 225 |
+
commands = ffmpeg_builder.chain(
|
| 226 |
+
ffmpeg_builder.set_input_fps(temp_video_fps),
|
| 227 |
+
ffmpeg_builder.set_input(temp_frames_pattern),
|
| 228 |
+
ffmpeg_builder.set_media_resolution(pack_resolution(output_video_resolution)),
|
| 229 |
+
ffmpeg_builder.set_video_encoder(output_video_encoder),
|
| 230 |
+
ffmpeg_builder.set_video_quality(output_video_encoder, output_video_quality),
|
| 231 |
+
ffmpeg_builder.set_video_preset(output_video_encoder, output_video_preset),
|
| 232 |
+
ffmpeg_builder.concat(
|
| 233 |
+
ffmpeg_builder.set_video_fps(output_video_fps),
|
| 234 |
+
ffmpeg_builder.keep_video_alpha(output_video_encoder)
|
| 235 |
+
),
|
| 236 |
+
ffmpeg_builder.set_pixel_format(output_video_encoder),
|
| 237 |
+
ffmpeg_builder.force_output(temp_video_path)
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
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:
|
| 241 |
+
process = run_ffmpeg_with_progress(commands, partial(update_progress, progress))
|
| 242 |
+
return process.returncode == 0
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def concat_video(output_path : str, temp_output_paths : List[str]) -> bool:
|
| 246 |
+
concat_video_path = tempfile.mktemp()
|
| 247 |
+
|
| 248 |
+
with open(concat_video_path, 'w') as concat_video_file:
|
| 249 |
+
for temp_output_path in temp_output_paths:
|
| 250 |
+
concat_video_file.write('file \'' + os.path.abspath(temp_output_path) + '\'' + os.linesep)
|
| 251 |
+
concat_video_file.flush()
|
| 252 |
+
concat_video_file.close()
|
| 253 |
+
|
| 254 |
+
output_path = os.path.abspath(output_path)
|
| 255 |
+
commands = ffmpeg_builder.chain(
|
| 256 |
+
ffmpeg_builder.unsafe_concat(),
|
| 257 |
+
ffmpeg_builder.set_input(concat_video_file.name),
|
| 258 |
+
ffmpeg_builder.copy_video_encoder(),
|
| 259 |
+
ffmpeg_builder.copy_audio_encoder(),
|
| 260 |
+
ffmpeg_builder.force_output(output_path)
|
| 261 |
+
)
|
| 262 |
+
process = run_ffmpeg(commands)
|
| 263 |
+
process.communicate()
|
| 264 |
+
remove_file(concat_video_path)
|
| 265 |
+
return process.returncode == 0
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def fix_audio_encoder(video_format : VideoFormat, audio_encoder : AudioEncoder) -> AudioEncoder:
|
| 269 |
+
if video_format == 'avi' and audio_encoder == 'libopus':
|
| 270 |
+
return 'aac'
|
| 271 |
+
if video_format in [ 'm4v', 'mpeg', 'wmv' ]:
|
| 272 |
+
return 'aac'
|
| 273 |
+
if video_format == 'mov' and audio_encoder in [ 'flac', 'libopus' ]:
|
| 274 |
+
return 'aac'
|
| 275 |
+
if video_format == 'mxf':
|
| 276 |
+
return 'pcm_s16le'
|
| 277 |
+
if video_format == 'webm':
|
| 278 |
+
return 'libopus'
|
| 279 |
+
return audio_encoder
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def fix_video_encoder(video_format : VideoFormat, video_encoder : VideoEncoder) -> VideoEncoder:
|
| 283 |
+
if video_format in [ 'm4v', 'mpeg', 'mxf', 'wmv' ]:
|
| 284 |
+
return 'libx264'
|
| 285 |
+
if video_format in [ 'mkv', 'mp4' ] and video_encoder == 'rawvideo':
|
| 286 |
+
return 'libx264'
|
| 287 |
+
if video_format == 'mov' and video_encoder == 'libvpx-vp9':
|
| 288 |
+
return 'libx264'
|
| 289 |
+
if video_format == 'webm':
|
| 290 |
+
return 'libvpx-vp9'
|
| 291 |
+
return video_encoder
|
facefusion/ffmpeg_builder.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
import shutil
|
| 3 |
+
from typing import List, Optional
|
| 4 |
+
|
| 5 |
+
import numpy
|
| 6 |
+
|
| 7 |
+
from facefusion.filesystem import get_file_format
|
| 8 |
+
from facefusion.types import AudioEncoder, Command, CommandSet, Duration, Fps, StreamMode, VideoEncoder, VideoPreset
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def run(commands : List[Command]) -> List[Command]:
|
| 12 |
+
return [ shutil.which('ffmpeg'), '-loglevel', 'error' ] + commands
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def chain(*commands : List[Command]) -> List[Command]:
|
| 16 |
+
return list(itertools.chain(*commands))
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def concat(*__commands__ : List[Command]) -> List[Command]:
|
| 20 |
+
commands = []
|
| 21 |
+
command_set : CommandSet = {}
|
| 22 |
+
|
| 23 |
+
for command in __commands__:
|
| 24 |
+
for argument, value in zip(command[::2], command[1::2]):
|
| 25 |
+
command_set.setdefault(argument, []).append(value)
|
| 26 |
+
|
| 27 |
+
for argument, values in command_set.items():
|
| 28 |
+
commands.append(argument)
|
| 29 |
+
commands.append(','.join(values))
|
| 30 |
+
|
| 31 |
+
return commands
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def get_encoders() -> List[Command]:
|
| 35 |
+
return [ '-encoders' ]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def set_hardware_accelerator(value : str) -> List[Command]:
|
| 39 |
+
return [ '-hwaccel', value ]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def set_progress() -> List[Command]:
|
| 43 |
+
return [ '-progress' ]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def set_input(input_path : str) -> List[Command]:
|
| 47 |
+
return [ '-i', input_path ]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def set_input_fps(input_fps : Fps) -> List[Command]:
|
| 51 |
+
return [ '-r', str(input_fps)]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def set_output(output_path : str) -> List[Command]:
|
| 55 |
+
return [ output_path ]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def force_output(output_path : str) -> List[Command]:
|
| 59 |
+
return [ '-y', output_path ]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def cast_stream() -> List[Command]:
|
| 63 |
+
return [ '-' ]
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def set_stream_mode(stream_mode : StreamMode) -> List[Command]:
|
| 67 |
+
if stream_mode == 'udp':
|
| 68 |
+
return [ '-f', 'mpegts' ]
|
| 69 |
+
if stream_mode == 'v4l2':
|
| 70 |
+
return [ '-f', 'v4l2' ]
|
| 71 |
+
return []
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def set_stream_quality(stream_quality : int) -> List[Command]:
|
| 75 |
+
return [ '-b:v', str(stream_quality) + 'k' ]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def unsafe_concat() -> List[Command]:
|
| 79 |
+
return [ '-f', 'concat', '-safe', '0' ]
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def set_pixel_format(video_encoder : VideoEncoder) -> List[Command]:
|
| 83 |
+
if video_encoder == 'rawvideo':
|
| 84 |
+
return [ '-pix_fmt', 'rgb24' ]
|
| 85 |
+
if video_encoder == 'libvpx-vp9':
|
| 86 |
+
return [ '-pix_fmt', 'yuva420p' ]
|
| 87 |
+
return [ '-pix_fmt', 'yuv420p' ]
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def set_frame_quality(frame_quality : int) -> List[Command]:
|
| 91 |
+
return [ '-q:v', str(frame_quality) ]
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def select_frame_range(frame_start : int, frame_end : int, video_fps : Fps) -> List[Command]:
|
| 95 |
+
if isinstance(frame_start, int) and isinstance(frame_end, int):
|
| 96 |
+
return [ '-vf', 'trim=start_frame=' + str(frame_start) + ':end_frame=' + str(frame_end) + ',fps=' + str(video_fps) ]
|
| 97 |
+
if isinstance(frame_start, int):
|
| 98 |
+
return [ '-vf', 'trim=start_frame=' + str(frame_start) + ',fps=' + str(video_fps) ]
|
| 99 |
+
if isinstance(frame_end, int):
|
| 100 |
+
return [ '-vf', 'trim=end_frame=' + str(frame_end) + ',fps=' + str(video_fps) ]
|
| 101 |
+
return [ '-vf', 'fps=' + str(video_fps) ]
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def prevent_frame_drop() -> List[Command]:
|
| 105 |
+
return [ '-vsync', '0' ]
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def select_media_range(frame_start : int, frame_end : int, media_fps : Fps) -> List[Command]:
|
| 109 |
+
commands = []
|
| 110 |
+
|
| 111 |
+
if isinstance(frame_start, int):
|
| 112 |
+
commands.extend([ '-ss', str(frame_start / media_fps) ])
|
| 113 |
+
if isinstance(frame_end, int):
|
| 114 |
+
commands.extend([ '-to', str(frame_end / media_fps) ])
|
| 115 |
+
return commands
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def select_media_stream(media_stream : str) -> List[Command]:
|
| 119 |
+
return [ '-map', media_stream ]
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def set_media_resolution(video_resolution : str) -> List[Command]:
|
| 123 |
+
return [ '-s', video_resolution ]
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def set_image_quality(image_path : str, image_quality : int) -> List[Command]:
|
| 127 |
+
if get_file_format(image_path) == 'webp':
|
| 128 |
+
return [ '-q:v', str(image_quality) ]
|
| 129 |
+
|
| 130 |
+
image_compression = round(31 - (image_quality * 0.31))
|
| 131 |
+
return [ '-q:v', str(image_compression) ]
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def set_audio_encoder(audio_codec : str) -> List[Command]:
|
| 135 |
+
return [ '-c:a', audio_codec ]
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def copy_audio_encoder() -> List[Command]:
|
| 139 |
+
return set_audio_encoder('copy')
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def set_audio_sample_rate(audio_sample_rate : int) -> List[Command]:
|
| 143 |
+
return [ '-ar', str(audio_sample_rate) ]
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def set_audio_sample_size(audio_sample_size : int) -> List[Command]:
|
| 147 |
+
if audio_sample_size == 16:
|
| 148 |
+
return [ '-f', 's16le' ]
|
| 149 |
+
if audio_sample_size == 32:
|
| 150 |
+
return [ '-f', 's32le' ]
|
| 151 |
+
return []
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def set_audio_channel_total(audio_channel_total : int) -> List[Command]:
|
| 155 |
+
return [ '-ac', str(audio_channel_total) ]
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def set_audio_quality(audio_encoder : AudioEncoder, audio_quality : int) -> List[Command]:
|
| 159 |
+
if audio_encoder == 'aac':
|
| 160 |
+
audio_compression = numpy.round(numpy.interp(audio_quality, [ 0, 100 ], [ 0.1, 2.0 ]), 1).astype(float).item()
|
| 161 |
+
return [ '-q:a', str(audio_compression) ]
|
| 162 |
+
if audio_encoder == 'libmp3lame':
|
| 163 |
+
audio_compression = numpy.round(numpy.interp(audio_quality, [ 0, 100 ], [ 9, 0 ])).astype(int).item()
|
| 164 |
+
return [ '-q:a', str(audio_compression) ]
|
| 165 |
+
if audio_encoder == 'libopus':
|
| 166 |
+
audio_bit_rate = numpy.round(numpy.interp(audio_quality, [ 0, 100 ], [ 64, 256 ])).astype(int).item()
|
| 167 |
+
return [ '-b:a', str(audio_bit_rate) + 'k' ]
|
| 168 |
+
if audio_encoder == 'libvorbis':
|
| 169 |
+
audio_compression = numpy.round(numpy.interp(audio_quality, [ 0, 100 ], [ -1, 10 ]), 1).astype(float).item()
|
| 170 |
+
return [ '-q:a', str(audio_compression) ]
|
| 171 |
+
return []
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def set_audio_volume(audio_volume : int) -> List[Command]:
|
| 175 |
+
return [ '-filter:a', 'volume=' + str(audio_volume / 100) ]
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def set_video_encoder(video_encoder : str) -> List[Command]:
|
| 179 |
+
return [ '-c:v', video_encoder ]
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def copy_video_encoder() -> List[Command]:
|
| 183 |
+
return set_video_encoder('copy')
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def set_video_quality(video_encoder : VideoEncoder, video_quality : int) -> List[Command]:
|
| 187 |
+
if video_encoder in [ 'libx264', 'libx264rgb', 'libx265' ]:
|
| 188 |
+
video_compression = numpy.round(numpy.interp(video_quality, [ 0, 100 ], [ 51, 0 ])).astype(int).item()
|
| 189 |
+
return [ '-crf', str(video_compression) ]
|
| 190 |
+
if video_encoder == 'libvpx-vp9':
|
| 191 |
+
video_compression = numpy.round(numpy.interp(video_quality, [ 0, 100 ], [ 63, 0 ])).astype(int).item()
|
| 192 |
+
return [ '-crf', str(video_compression) ]
|
| 193 |
+
if video_encoder in [ 'h264_nvenc', 'hevc_nvenc' ]:
|
| 194 |
+
video_compression = numpy.round(numpy.interp(video_quality, [ 0, 100 ], [ 51, 0 ])).astype(int).item()
|
| 195 |
+
return [ '-cq', str(video_compression) ]
|
| 196 |
+
if video_encoder in [ 'h264_amf', 'hevc_amf' ]:
|
| 197 |
+
video_compression = numpy.round(numpy.interp(video_quality, [ 0, 100 ], [ 51, 0 ])).astype(int).item()
|
| 198 |
+
return [ '-qp_i', str(video_compression), '-qp_p', str(video_compression), '-qp_b', str(video_compression) ]
|
| 199 |
+
if video_encoder in [ 'h264_qsv', 'hevc_qsv' ]:
|
| 200 |
+
video_compression = numpy.round(numpy.interp(video_quality, [ 0, 100 ], [ 51, 0 ])).astype(int).item()
|
| 201 |
+
return [ '-qp', str(video_compression) ]
|
| 202 |
+
if video_encoder in [ 'h264_videotoolbox', 'hevc_videotoolbox' ]:
|
| 203 |
+
video_bit_rate = numpy.round(numpy.interp(video_quality, [ 0, 100 ], [ 1024, 50512 ])).astype(int).item()
|
| 204 |
+
return [ '-b:v', str(video_bit_rate) + 'k' ]
|
| 205 |
+
return []
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def set_video_preset(video_encoder : VideoEncoder, video_preset : VideoPreset) -> List[Command]:
|
| 209 |
+
if video_encoder in [ 'libx264', 'libx264rgb', 'libx265' ]:
|
| 210 |
+
return [ '-preset', video_preset ]
|
| 211 |
+
if video_encoder in [ 'h264_nvenc', 'hevc_nvenc' ]:
|
| 212 |
+
return [ '-preset', map_nvenc_preset(video_preset) ]
|
| 213 |
+
if video_encoder in [ 'h264_amf', 'hevc_amf' ]:
|
| 214 |
+
return [ '-quality', map_amf_preset(video_preset) ]
|
| 215 |
+
if video_encoder in [ 'h264_qsv', 'hevc_qsv' ]:
|
| 216 |
+
return [ '-preset', map_qsv_preset(video_preset) ]
|
| 217 |
+
return []
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def set_video_fps(video_fps : Fps) -> List[Command]:
|
| 221 |
+
return [ '-vf', 'fps=' + str(video_fps) ]
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def set_video_duration(video_duration : Duration) -> List[Command]:
|
| 225 |
+
return [ '-t', str(video_duration) ]
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def keep_video_alpha(video_encoder : VideoEncoder) -> List[Command]:
|
| 229 |
+
if video_encoder == 'libvpx-vp9':
|
| 230 |
+
return [ '-vf', 'format=yuva420p' ]
|
| 231 |
+
return []
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def capture_video() -> List[Command]:
|
| 235 |
+
return [ '-f', 'rawvideo', '-pix_fmt', 'rgb24' ]
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def ignore_video_stream() -> List[Command]:
|
| 239 |
+
return [ '-vn' ]
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def map_nvenc_preset(video_preset : VideoPreset) -> Optional[str]:
|
| 243 |
+
if video_preset in [ 'ultrafast', 'superfast', 'veryfast', 'faster', 'fast' ]:
|
| 244 |
+
return 'fast'
|
| 245 |
+
if video_preset == 'medium':
|
| 246 |
+
return 'medium'
|
| 247 |
+
if video_preset in [ 'slow', 'slower', 'veryslow' ]:
|
| 248 |
+
return 'slow'
|
| 249 |
+
return None
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def map_amf_preset(video_preset : VideoPreset) -> Optional[str]:
|
| 253 |
+
if video_preset in [ 'ultrafast', 'superfast', 'veryfast' ]:
|
| 254 |
+
return 'speed'
|
| 255 |
+
if video_preset in [ 'faster', 'fast', 'medium' ]:
|
| 256 |
+
return 'balanced'
|
| 257 |
+
if video_preset in [ 'slow', 'slower', 'veryslow' ]:
|
| 258 |
+
return 'quality'
|
| 259 |
+
return None
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def map_qsv_preset(video_preset : VideoPreset) -> Optional[str]:
|
| 263 |
+
if video_preset in [ 'ultrafast', 'superfast', 'veryfast' ]:
|
| 264 |
+
return 'veryfast'
|
| 265 |
+
if video_preset in [ 'faster', 'fast', 'medium', 'slow', 'slower', 'veryslow' ]:
|
| 266 |
+
return video_preset
|
| 267 |
+
return None
|
facefusion/filesystem.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import glob
|
| 2 |
+
import os
|
| 3 |
+
import shutil
|
| 4 |
+
from typing import List, Optional
|
| 5 |
+
|
| 6 |
+
import facefusion.choices
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def get_file_size(file_path : str) -> int:
|
| 10 |
+
if is_file(file_path):
|
| 11 |
+
return os.path.getsize(file_path)
|
| 12 |
+
return 0
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def get_file_name(file_path : str) -> Optional[str]:
|
| 16 |
+
file_name, _ = os.path.splitext(os.path.basename(file_path))
|
| 17 |
+
|
| 18 |
+
if file_name:
|
| 19 |
+
return file_name
|
| 20 |
+
return None
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def get_file_extension(file_path : str) -> Optional[str]:
|
| 24 |
+
_, file_extension = os.path.splitext(file_path)
|
| 25 |
+
|
| 26 |
+
if file_extension:
|
| 27 |
+
return file_extension.lower()
|
| 28 |
+
return None
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def get_file_format(file_path : str) -> Optional[str]:
|
| 32 |
+
file_extension = get_file_extension(file_path)
|
| 33 |
+
|
| 34 |
+
if file_extension:
|
| 35 |
+
if file_extension == '.jpg':
|
| 36 |
+
return 'jpeg'
|
| 37 |
+
if file_extension == '.tif':
|
| 38 |
+
return 'tiff'
|
| 39 |
+
if file_extension == '.mpg':
|
| 40 |
+
return 'mpeg'
|
| 41 |
+
return file_extension.lstrip('.')
|
| 42 |
+
return None
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def same_file_extension(first_file_path : str, second_file_path : str) -> bool:
|
| 46 |
+
first_file_extension = get_file_extension(first_file_path)
|
| 47 |
+
second_file_extension = get_file_extension(second_file_path)
|
| 48 |
+
|
| 49 |
+
if first_file_extension and second_file_extension:
|
| 50 |
+
return get_file_extension(first_file_path) == get_file_extension(second_file_path)
|
| 51 |
+
return False
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def is_file(file_path : str) -> bool:
|
| 55 |
+
if file_path:
|
| 56 |
+
return os.path.isfile(file_path)
|
| 57 |
+
return False
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def is_audio(audio_path : str) -> bool:
|
| 61 |
+
return is_file(audio_path) and get_file_format(audio_path) in facefusion.choices.audio_formats
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def has_audio(audio_paths : List[str]) -> bool:
|
| 65 |
+
if audio_paths:
|
| 66 |
+
return any(map(is_audio, audio_paths))
|
| 67 |
+
return False
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def are_audios(audio_paths : List[str]) -> bool:
|
| 71 |
+
if audio_paths:
|
| 72 |
+
return all(map(is_audio, audio_paths))
|
| 73 |
+
return False
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def is_image(image_path : str) -> bool:
|
| 77 |
+
return is_file(image_path) and get_file_format(image_path) in facefusion.choices.image_formats
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def has_image(image_paths : List[str]) -> bool:
|
| 81 |
+
if image_paths:
|
| 82 |
+
return any(is_image(image_path) for image_path in image_paths)
|
| 83 |
+
return False
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def are_images(image_paths : List[str]) -> bool:
|
| 87 |
+
if image_paths:
|
| 88 |
+
return all(map(is_image, image_paths))
|
| 89 |
+
return False
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def is_video(video_path : str) -> bool:
|
| 93 |
+
return is_file(video_path) and get_file_format(video_path) in facefusion.choices.video_formats
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def has_video(video_paths : List[str]) -> bool:
|
| 97 |
+
if video_paths:
|
| 98 |
+
return any(map(is_video, video_paths))
|
| 99 |
+
return False
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def are_videos(video_paths : List[str]) -> bool:
|
| 103 |
+
if video_paths:
|
| 104 |
+
return all(map(is_video, video_paths))
|
| 105 |
+
return False
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def filter_audio_paths(paths : List[str]) -> List[str]:
|
| 109 |
+
if paths:
|
| 110 |
+
return [ path for path in paths if is_audio(path) ]
|
| 111 |
+
return []
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def filter_image_paths(paths : List[str]) -> List[str]:
|
| 115 |
+
if paths:
|
| 116 |
+
return [ path for path in paths if is_image(path) ]
|
| 117 |
+
return []
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def copy_file(file_path : str, move_path : str) -> bool:
|
| 121 |
+
if is_file(file_path):
|
| 122 |
+
shutil.copy(file_path, move_path)
|
| 123 |
+
return is_file(move_path)
|
| 124 |
+
return False
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def move_file(file_path : str, move_path : str) -> bool:
|
| 128 |
+
if is_file(file_path):
|
| 129 |
+
shutil.move(file_path, move_path)
|
| 130 |
+
return not is_file(file_path) and is_file(move_path)
|
| 131 |
+
return False
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def remove_file(file_path : str) -> bool:
|
| 135 |
+
if is_file(file_path):
|
| 136 |
+
os.remove(file_path)
|
| 137 |
+
return not is_file(file_path)
|
| 138 |
+
return False
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def resolve_file_paths(directory_path : str) -> List[str]:
|
| 142 |
+
file_paths : List[str] = []
|
| 143 |
+
|
| 144 |
+
if is_directory(directory_path):
|
| 145 |
+
file_names_and_extensions = sorted(os.listdir(directory_path))
|
| 146 |
+
|
| 147 |
+
for file_name_and_extension in file_names_and_extensions:
|
| 148 |
+
if not file_name_and_extension.startswith(('.', '__')):
|
| 149 |
+
file_path = os.path.join(directory_path, file_name_and_extension)
|
| 150 |
+
file_paths.append(file_path)
|
| 151 |
+
|
| 152 |
+
return file_paths
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def resolve_file_pattern(file_pattern : str) -> List[str]:
|
| 156 |
+
if in_directory(file_pattern):
|
| 157 |
+
return sorted(glob.glob(file_pattern))
|
| 158 |
+
return []
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def is_directory(directory_path : str) -> bool:
|
| 162 |
+
if directory_path:
|
| 163 |
+
return os.path.isdir(directory_path)
|
| 164 |
+
return False
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def in_directory(file_path : str) -> bool:
|
| 168 |
+
if file_path:
|
| 169 |
+
directory_path = os.path.dirname(file_path)
|
| 170 |
+
if directory_path:
|
| 171 |
+
return not is_directory(file_path) and is_directory(directory_path)
|
| 172 |
+
return False
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def create_directory(directory_path : str) -> bool:
|
| 176 |
+
if directory_path and not is_file(directory_path):
|
| 177 |
+
os.makedirs(directory_path, exist_ok = True)
|
| 178 |
+
return is_directory(directory_path)
|
| 179 |
+
return False
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def remove_directory(directory_path : str) -> bool:
|
| 183 |
+
if is_directory(directory_path):
|
| 184 |
+
shutil.rmtree(directory_path, ignore_errors = True)
|
| 185 |
+
return not is_directory(directory_path)
|
| 186 |
+
return False
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def resolve_relative_path(path : str) -> str:
|
| 190 |
+
return os.path.abspath(os.path.join(os.path.dirname(__file__), path))
|
facefusion/hash_helper.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import zlib
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
from facefusion.filesystem import get_file_name, is_file
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def create_hash(content : bytes) -> str:
|
| 9 |
+
return format(zlib.crc32(content), '08x')
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def validate_hash(validate_path : str) -> bool:
|
| 13 |
+
hash_path = get_hash_path(validate_path)
|
| 14 |
+
|
| 15 |
+
if is_file(hash_path):
|
| 16 |
+
with open(hash_path) as hash_file:
|
| 17 |
+
hash_content = hash_file.read()
|
| 18 |
+
|
| 19 |
+
with open(validate_path, 'rb') as validate_file:
|
| 20 |
+
validate_content = validate_file.read()
|
| 21 |
+
|
| 22 |
+
return create_hash(validate_content) == hash_content
|
| 23 |
+
return False
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def get_hash_path(validate_path : str) -> Optional[str]:
|
| 27 |
+
if is_file(validate_path):
|
| 28 |
+
validate_directory_path, file_name_and_extension = os.path.split(validate_path)
|
| 29 |
+
validate_file_name = get_file_name(file_name_and_extension)
|
| 30 |
+
|
| 31 |
+
return os.path.join(validate_directory_path, validate_file_name + '.hash')
|
| 32 |
+
return None
|
facefusion/inference_manager.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib
|
| 2 |
+
import random
|
| 3 |
+
from time import sleep, time
|
| 4 |
+
from typing import List
|
| 5 |
+
|
| 6 |
+
from onnxruntime import InferenceSession
|
| 7 |
+
|
| 8 |
+
from facefusion import logger, process_manager, state_manager, translator
|
| 9 |
+
from facefusion.app_context import detect_app_context
|
| 10 |
+
from facefusion.common_helper import is_windows
|
| 11 |
+
from facefusion.execution import create_inference_session_providers, has_execution_provider
|
| 12 |
+
from facefusion.exit_helper import fatal_exit
|
| 13 |
+
from facefusion.filesystem import get_file_name, is_file
|
| 14 |
+
from facefusion.time_helper import calculate_end_time
|
| 15 |
+
from facefusion.types import DownloadSet, ExecutionProvider, InferencePool, InferencePoolSet
|
| 16 |
+
|
| 17 |
+
INFERENCE_POOL_SET : InferencePoolSet =\
|
| 18 |
+
{
|
| 19 |
+
'cli': {},
|
| 20 |
+
'ui': {}
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def get_inference_pool(module_name : str, model_names : List[str], model_source_set : DownloadSet) -> InferencePool:
|
| 25 |
+
while process_manager.is_checking():
|
| 26 |
+
sleep(0.5)
|
| 27 |
+
execution_device_ids = state_manager.get_item('execution_device_ids')
|
| 28 |
+
execution_providers = resolve_execution_providers(module_name)
|
| 29 |
+
app_context = detect_app_context()
|
| 30 |
+
|
| 31 |
+
for execution_device_id in execution_device_ids:
|
| 32 |
+
inference_context = get_inference_context(module_name, model_names, execution_device_id, execution_providers)
|
| 33 |
+
|
| 34 |
+
if app_context == 'cli' and INFERENCE_POOL_SET.get('ui').get(inference_context):
|
| 35 |
+
INFERENCE_POOL_SET['cli'][inference_context] = INFERENCE_POOL_SET.get('ui').get(inference_context)
|
| 36 |
+
if app_context == 'ui' and INFERENCE_POOL_SET.get('cli').get(inference_context):
|
| 37 |
+
INFERENCE_POOL_SET['ui'][inference_context] = INFERENCE_POOL_SET.get('cli').get(inference_context)
|
| 38 |
+
if not INFERENCE_POOL_SET.get(app_context).get(inference_context):
|
| 39 |
+
INFERENCE_POOL_SET[app_context][inference_context] = create_inference_pool(model_source_set, execution_device_id, execution_providers)
|
| 40 |
+
|
| 41 |
+
current_inference_context = get_inference_context(module_name, model_names, random.choice(execution_device_ids), execution_providers)
|
| 42 |
+
return INFERENCE_POOL_SET.get(app_context).get(current_inference_context)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def create_inference_pool(model_source_set : DownloadSet, execution_device_id : int, execution_providers : List[ExecutionProvider]) -> InferencePool:
|
| 46 |
+
inference_pool : InferencePool = {}
|
| 47 |
+
|
| 48 |
+
for model_name in model_source_set.keys():
|
| 49 |
+
model_path = model_source_set.get(model_name).get('path')
|
| 50 |
+
if is_file(model_path):
|
| 51 |
+
inference_pool[model_name] = create_inference_session(model_path, execution_device_id, execution_providers)
|
| 52 |
+
|
| 53 |
+
return inference_pool
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def clear_inference_pool(module_name : str, model_names : List[str]) -> None:
|
| 57 |
+
execution_device_ids = state_manager.get_item('execution_device_ids')
|
| 58 |
+
execution_providers = resolve_execution_providers(module_name)
|
| 59 |
+
app_context = detect_app_context()
|
| 60 |
+
|
| 61 |
+
if is_windows() and has_execution_provider('directml'):
|
| 62 |
+
INFERENCE_POOL_SET[app_context].clear()
|
| 63 |
+
|
| 64 |
+
for execution_device_id in execution_device_ids:
|
| 65 |
+
inference_context = get_inference_context(module_name, model_names, execution_device_id, execution_providers)
|
| 66 |
+
if INFERENCE_POOL_SET.get(app_context).get(inference_context):
|
| 67 |
+
del INFERENCE_POOL_SET[app_context][inference_context]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def create_inference_session(model_path : str, execution_device_id : int, execution_providers : List[ExecutionProvider]) -> InferenceSession:
|
| 71 |
+
model_file_name = get_file_name(model_path)
|
| 72 |
+
start_time = time()
|
| 73 |
+
|
| 74 |
+
try:
|
| 75 |
+
inference_session_providers = create_inference_session_providers(execution_device_id, execution_providers)
|
| 76 |
+
inference_session = InferenceSession(model_path, providers = inference_session_providers)
|
| 77 |
+
logger.debug(translator.get('loading_model_succeeded').format(model_name = model_file_name, seconds = calculate_end_time(start_time)), __name__)
|
| 78 |
+
return inference_session
|
| 79 |
+
|
| 80 |
+
except Exception:
|
| 81 |
+
logger.error(translator.get('loading_model_failed').format(model_name = model_file_name), __name__)
|
| 82 |
+
fatal_exit(1)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def get_inference_context(module_name : str, model_names : List[str], execution_device_id : int, execution_providers : List[ExecutionProvider]) -> str:
|
| 86 |
+
inference_context = '.'.join([ module_name ] + model_names + [ str(execution_device_id) ] + list(execution_providers))
|
| 87 |
+
return inference_context
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def resolve_execution_providers(module_name : str) -> List[ExecutionProvider]:
|
| 91 |
+
module = importlib.import_module(module_name)
|
| 92 |
+
|
| 93 |
+
if hasattr(module, 'resolve_execution_providers'):
|
| 94 |
+
return getattr(module, 'resolve_execution_providers')()
|
| 95 |
+
return state_manager.get_item('execution_providers')
|
facefusion/installer.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import shutil
|
| 3 |
+
import signal
|
| 4 |
+
import subprocess
|
| 5 |
+
import sys
|
| 6 |
+
from argparse import ArgumentParser, HelpFormatter
|
| 7 |
+
from functools import partial
|
| 8 |
+
from types import FrameType
|
| 9 |
+
|
| 10 |
+
from facefusion import metadata
|
| 11 |
+
from facefusion.common_helper import is_linux, is_windows
|
| 12 |
+
|
| 13 |
+
LOCALES =\
|
| 14 |
+
{
|
| 15 |
+
'install_dependency': 'install the {dependency} package',
|
| 16 |
+
'force_reinstall': 'force reinstall of packages',
|
| 17 |
+
'skip_conda': 'skip the conda environment check',
|
| 18 |
+
'conda_not_activated': 'conda is not activated'
|
| 19 |
+
}
|
| 20 |
+
ONNXRUNTIME_SET =\
|
| 21 |
+
{
|
| 22 |
+
'default': ('onnxruntime', '1.23.2')
|
| 23 |
+
}
|
| 24 |
+
if is_windows() or is_linux():
|
| 25 |
+
ONNXRUNTIME_SET['cuda'] = ('onnxruntime-gpu', '1.23.2')
|
| 26 |
+
ONNXRUNTIME_SET['openvino'] = ('onnxruntime-openvino', '1.23.0')
|
| 27 |
+
if is_windows():
|
| 28 |
+
ONNXRUNTIME_SET['directml'] = ('onnxruntime-directml', '1.23.0')
|
| 29 |
+
if is_linux():
|
| 30 |
+
ONNXRUNTIME_SET['migraphx'] = ('onnxruntime-migraphx', '1.23.0')
|
| 31 |
+
ONNXRUNTIME_SET['rocm'] = ('onnxruntime_rocm', '1.22.1', '7.0.2') #type:ignore[assignment]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def cli() -> None:
|
| 35 |
+
signal.signal(signal.SIGINT, signal_exit)
|
| 36 |
+
program = ArgumentParser(formatter_class = partial(HelpFormatter, max_help_position = 50))
|
| 37 |
+
program.add_argument('--onnxruntime', help = LOCALES.get('install_dependency').format(dependency = 'onnxruntime'), choices = ONNXRUNTIME_SET.keys(), required = True)
|
| 38 |
+
program.add_argument('--force-reinstall', help = LOCALES.get('force_reinstall'), action = 'store_true')
|
| 39 |
+
program.add_argument('--skip-conda', help = LOCALES.get('skip_conda'), action = 'store_true')
|
| 40 |
+
program.add_argument('-v', '--version', version = metadata.get('name') + ' ' + metadata.get('version'), action = 'version')
|
| 41 |
+
run(program)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def signal_exit(signum : int, frame : FrameType) -> None:
|
| 45 |
+
sys.exit(0)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def run(program : ArgumentParser) -> None:
|
| 49 |
+
args = program.parse_args()
|
| 50 |
+
has_conda = 'CONDA_PREFIX' in os.environ
|
| 51 |
+
commands = [ shutil.which('pip'), 'install' ]
|
| 52 |
+
|
| 53 |
+
if args.force_reinstall:
|
| 54 |
+
commands.append('--force-reinstall')
|
| 55 |
+
|
| 56 |
+
if not args.skip_conda and not has_conda:
|
| 57 |
+
sys.stdout.write(LOCALES.get('conda_not_activated') + os.linesep)
|
| 58 |
+
sys.exit(1)
|
| 59 |
+
|
| 60 |
+
with open('requirements.txt') as file:
|
| 61 |
+
|
| 62 |
+
for line in file.readlines():
|
| 63 |
+
__line__ = line.strip()
|
| 64 |
+
if not __line__.startswith('onnxruntime'):
|
| 65 |
+
commands.append(__line__)
|
| 66 |
+
|
| 67 |
+
if args.onnxruntime == 'rocm':
|
| 68 |
+
onnxruntime_name, onnxruntime_version, rocm_version = ONNXRUNTIME_SET.get(args.onnxruntime) #type:ignore[misc]
|
| 69 |
+
python_id = 'cp' + str(sys.version_info.major) + str(sys.version_info.minor)
|
| 70 |
+
|
| 71 |
+
if python_id in [ 'cp310', 'cp312' ]:
|
| 72 |
+
wheel_name = onnxruntime_name + '-' + onnxruntime_version + '-' + python_id + '-' + python_id + '-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl'
|
| 73 |
+
wheel_url = 'https://repo.radeon.com/rocm/manylinux/rocm-rel-' + rocm_version + '/' + wheel_name
|
| 74 |
+
commands.append(wheel_url)
|
| 75 |
+
else:
|
| 76 |
+
onnxruntime_name, onnxruntime_version = ONNXRUNTIME_SET.get(args.onnxruntime)
|
| 77 |
+
commands.append(onnxruntime_name + '==' + onnxruntime_version)
|
| 78 |
+
|
| 79 |
+
subprocess.call(commands)
|
| 80 |
+
|
| 81 |
+
if args.onnxruntime == 'cuda' and has_conda:
|
| 82 |
+
library_paths = []
|
| 83 |
+
|
| 84 |
+
if is_linux():
|
| 85 |
+
if os.getenv('LD_LIBRARY_PATH'):
|
| 86 |
+
library_paths = os.getenv('LD_LIBRARY_PATH').split(os.pathsep)
|
| 87 |
+
|
| 88 |
+
python_id = 'python' + str(sys.version_info.major) + '.' + str(sys.version_info.minor)
|
| 89 |
+
library_paths.extend(
|
| 90 |
+
[
|
| 91 |
+
os.path.join(os.getenv('CONDA_PREFIX'), 'lib'),
|
| 92 |
+
os.path.join(os.getenv('CONDA_PREFIX'), 'lib', python_id, 'site-packages', 'tensorrt_libs')
|
| 93 |
+
])
|
| 94 |
+
library_paths = list(dict.fromkeys([ library_path for library_path in library_paths if os.path.exists(library_path) ]))
|
| 95 |
+
|
| 96 |
+
subprocess.call([ shutil.which('conda'), 'env', 'config', 'vars', 'set', 'LD_LIBRARY_PATH=' + os.pathsep.join(library_paths) ])
|
| 97 |
+
|
| 98 |
+
if is_windows():
|
| 99 |
+
if os.getenv('PATH'):
|
| 100 |
+
library_paths = os.getenv('PATH').split(os.pathsep)
|
| 101 |
+
|
| 102 |
+
library_paths.extend(
|
| 103 |
+
[
|
| 104 |
+
os.path.join(os.getenv('CONDA_PREFIX'), 'Lib'),
|
| 105 |
+
os.path.join(os.getenv('CONDA_PREFIX'), 'Lib', 'site-packages', 'tensorrt_libs')
|
| 106 |
+
])
|
| 107 |
+
library_paths = list(dict.fromkeys([ library_path for library_path in library_paths if os.path.exists(library_path) ]))
|
| 108 |
+
|
| 109 |
+
subprocess.call([ shutil.which('conda'), 'env', 'config', 'vars', 'set', 'PATH=' + os.pathsep.join(library_paths) ])
|
facefusion/jobs/__init__.py
ADDED
|
File without changes
|
facefusion/jobs/job_helper.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
from facefusion.filesystem import get_file_extension, get_file_name
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def get_step_output_path(job_id : str, step_index : int, output_path : str) -> Optional[str]:
|
| 9 |
+
if output_path:
|
| 10 |
+
output_directory_path, output_file_path = os.path.split(output_path)
|
| 11 |
+
output_file_name = get_file_name(output_file_path)
|
| 12 |
+
output_file_extension = get_file_extension(output_file_path)
|
| 13 |
+
|
| 14 |
+
if output_file_name and output_file_extension:
|
| 15 |
+
return os.path.join(output_directory_path, output_file_name + '-' + job_id + '-' + str(step_index) + output_file_extension)
|
| 16 |
+
return None
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def suggest_job_id(job_prefix : str = 'job') -> str:
|
| 20 |
+
return job_prefix + '-' + datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
|
facefusion/jobs/job_list.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from typing import List, Optional, Tuple
|
| 3 |
+
|
| 4 |
+
from facefusion.jobs import job_manager
|
| 5 |
+
from facefusion.time_helper import describe_time_ago
|
| 6 |
+
from facefusion.types import JobStatus, TableContent, TableHeader
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def compose_job_list(job_status : JobStatus) -> Tuple[List[TableHeader], List[List[TableContent]]]:
|
| 10 |
+
jobs = job_manager.find_jobs(job_status)
|
| 11 |
+
job_headers : List[TableHeader] = [ 'job id', 'steps', 'date created', 'date updated', 'job status' ]
|
| 12 |
+
job_contents : List[List[TableContent]] = []
|
| 13 |
+
|
| 14 |
+
for index, job_id in enumerate(jobs):
|
| 15 |
+
if job_manager.validate_job(job_id):
|
| 16 |
+
job = jobs[job_id]
|
| 17 |
+
step_total = job_manager.count_step_total(job_id)
|
| 18 |
+
date_created = prepare_describe_datetime(job.get('date_created'))
|
| 19 |
+
date_updated = prepare_describe_datetime(job.get('date_updated'))
|
| 20 |
+
job_contents.append(
|
| 21 |
+
[
|
| 22 |
+
job_id,
|
| 23 |
+
step_total,
|
| 24 |
+
date_created,
|
| 25 |
+
date_updated,
|
| 26 |
+
job_status
|
| 27 |
+
])
|
| 28 |
+
return job_headers, job_contents
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def prepare_describe_datetime(date_time : Optional[str]) -> Optional[str]:
|
| 32 |
+
if date_time:
|
| 33 |
+
return describe_time_ago(datetime.fromisoformat(date_time))
|
| 34 |
+
return None
|
facefusion/jobs/job_manager.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from copy import copy
|
| 3 |
+
from typing import List, Optional
|
| 4 |
+
|
| 5 |
+
import facefusion.choices
|
| 6 |
+
from facefusion.filesystem import create_directory, get_file_name, is_directory, is_file, move_file, remove_directory, remove_file, resolve_file_pattern
|
| 7 |
+
from facefusion.jobs.job_helper import get_step_output_path
|
| 8 |
+
from facefusion.json import read_json, write_json
|
| 9 |
+
from facefusion.time_helper import get_current_date_time
|
| 10 |
+
from facefusion.types import Args, Job, JobSet, JobStatus, JobStep, JobStepStatus
|
| 11 |
+
|
| 12 |
+
JOBS_PATH : Optional[str] = None
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def init_jobs(jobs_path : str) -> bool:
|
| 16 |
+
global JOBS_PATH
|
| 17 |
+
|
| 18 |
+
JOBS_PATH = jobs_path
|
| 19 |
+
job_status_paths = [ os.path.join(JOBS_PATH, job_status) for job_status in facefusion.choices.job_statuses ]
|
| 20 |
+
|
| 21 |
+
for job_status_path in job_status_paths:
|
| 22 |
+
create_directory(job_status_path)
|
| 23 |
+
return all(is_directory(status_path) for status_path in job_status_paths)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def clear_jobs(jobs_path : str) -> bool:
|
| 27 |
+
return remove_directory(jobs_path)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def create_job(job_id : str) -> bool:
|
| 31 |
+
job : Job =\
|
| 32 |
+
{
|
| 33 |
+
'version': '1',
|
| 34 |
+
'date_created': get_current_date_time().isoformat(),
|
| 35 |
+
'date_updated': None,
|
| 36 |
+
'steps': []
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
return create_job_file(job_id, job)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def submit_job(job_id : str) -> bool:
|
| 43 |
+
drafted_job_ids = find_job_ids('drafted')
|
| 44 |
+
steps = get_steps(job_id)
|
| 45 |
+
|
| 46 |
+
if job_id in drafted_job_ids and steps:
|
| 47 |
+
return set_steps_status(job_id, 'queued') and move_job_file(job_id, 'queued')
|
| 48 |
+
return False
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def submit_jobs(halt_on_error : bool) -> bool:
|
| 52 |
+
drafted_job_ids = find_job_ids('drafted')
|
| 53 |
+
has_error = False
|
| 54 |
+
|
| 55 |
+
if drafted_job_ids:
|
| 56 |
+
for job_id in drafted_job_ids:
|
| 57 |
+
if not submit_job(job_id):
|
| 58 |
+
has_error = True
|
| 59 |
+
if halt_on_error:
|
| 60 |
+
return False
|
| 61 |
+
return not has_error
|
| 62 |
+
return False
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def delete_job(job_id : str) -> bool:
|
| 66 |
+
return delete_job_file(job_id)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def delete_jobs(halt_on_error : bool) -> bool:
|
| 70 |
+
job_ids = find_job_ids('drafted') + find_job_ids('queued') + find_job_ids('failed') + find_job_ids('completed')
|
| 71 |
+
has_error = False
|
| 72 |
+
|
| 73 |
+
if job_ids:
|
| 74 |
+
for job_id in job_ids:
|
| 75 |
+
if not delete_job(job_id):
|
| 76 |
+
has_error = True
|
| 77 |
+
if halt_on_error:
|
| 78 |
+
return False
|
| 79 |
+
return not has_error
|
| 80 |
+
return False
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def find_jobs(job_status : JobStatus) -> JobSet:
|
| 84 |
+
job_ids = find_job_ids(job_status)
|
| 85 |
+
job_set : JobSet = {}
|
| 86 |
+
|
| 87 |
+
for job_id in job_ids:
|
| 88 |
+
job_set[job_id] = read_job_file(job_id)
|
| 89 |
+
return job_set
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def find_job_ids(job_status : JobStatus) -> List[str]:
|
| 93 |
+
job_pattern = os.path.join(JOBS_PATH, job_status, '*.json')
|
| 94 |
+
job_paths = resolve_file_pattern(job_pattern)
|
| 95 |
+
job_paths.sort(key = os.path.getmtime)
|
| 96 |
+
job_ids = []
|
| 97 |
+
|
| 98 |
+
for job_path in job_paths:
|
| 99 |
+
job_id = get_file_name(job_path)
|
| 100 |
+
job_ids.append(job_id)
|
| 101 |
+
return job_ids
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def validate_job(job_id : str) -> bool:
|
| 105 |
+
job = read_job_file(job_id)
|
| 106 |
+
return bool(job and 'version' in job and 'date_created' in job and 'date_updated' in job and 'steps' in job)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def has_step(job_id : str, step_index : int) -> bool:
|
| 110 |
+
step_total = count_step_total(job_id)
|
| 111 |
+
return step_index in range(step_total)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def add_step(job_id : str, step_args : Args) -> bool:
|
| 115 |
+
job = read_job_file(job_id)
|
| 116 |
+
|
| 117 |
+
if job:
|
| 118 |
+
job.get('steps').append(
|
| 119 |
+
{
|
| 120 |
+
'args': step_args,
|
| 121 |
+
'status': 'drafted'
|
| 122 |
+
})
|
| 123 |
+
return update_job_file(job_id, job)
|
| 124 |
+
return False
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def remix_step(job_id : str, step_index : int, step_args : Args) -> bool:
|
| 128 |
+
steps = get_steps(job_id)
|
| 129 |
+
step_args = copy(step_args)
|
| 130 |
+
|
| 131 |
+
if step_index and step_index < 0:
|
| 132 |
+
step_index = count_step_total(job_id) - 1
|
| 133 |
+
|
| 134 |
+
if has_step(job_id, step_index):
|
| 135 |
+
output_path = steps[step_index].get('args').get('output_path')
|
| 136 |
+
step_args['target_path'] = get_step_output_path(job_id, step_index, output_path)
|
| 137 |
+
return add_step(job_id, step_args)
|
| 138 |
+
return False
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def insert_step(job_id : str, step_index : int, step_args : Args) -> bool:
|
| 142 |
+
job = read_job_file(job_id)
|
| 143 |
+
step_args = copy(step_args)
|
| 144 |
+
|
| 145 |
+
if step_index and step_index < 0:
|
| 146 |
+
step_index = count_step_total(job_id) - 1
|
| 147 |
+
|
| 148 |
+
if job and has_step(job_id, step_index):
|
| 149 |
+
job.get('steps').insert(step_index,
|
| 150 |
+
{
|
| 151 |
+
'args': step_args,
|
| 152 |
+
'status': 'drafted'
|
| 153 |
+
})
|
| 154 |
+
return update_job_file(job_id, job)
|
| 155 |
+
return False
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def remove_step(job_id : str, step_index : int) -> bool:
|
| 159 |
+
job = read_job_file(job_id)
|
| 160 |
+
|
| 161 |
+
if step_index and step_index < 0:
|
| 162 |
+
step_index = count_step_total(job_id) - 1
|
| 163 |
+
|
| 164 |
+
if job and has_step(job_id, step_index):
|
| 165 |
+
job.get('steps').pop(step_index)
|
| 166 |
+
return update_job_file(job_id, job)
|
| 167 |
+
return False
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def get_steps(job_id : str) -> List[JobStep]:
|
| 171 |
+
job = read_job_file(job_id)
|
| 172 |
+
|
| 173 |
+
if job:
|
| 174 |
+
return job.get('steps')
|
| 175 |
+
return []
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def count_step_total(job_id : str) -> int:
|
| 179 |
+
steps = get_steps(job_id)
|
| 180 |
+
|
| 181 |
+
if steps:
|
| 182 |
+
return len(steps)
|
| 183 |
+
return 0
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def set_step_status(job_id : str, step_index : int, step_status : JobStepStatus) -> bool:
|
| 187 |
+
job = read_job_file(job_id)
|
| 188 |
+
|
| 189 |
+
if job:
|
| 190 |
+
steps = job.get('steps')
|
| 191 |
+
if has_step(job_id, step_index):
|
| 192 |
+
steps[step_index]['status'] = step_status
|
| 193 |
+
return update_job_file(job_id, job)
|
| 194 |
+
return False
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def set_steps_status(job_id : str, step_status : JobStepStatus) -> bool:
|
| 198 |
+
job = read_job_file(job_id)
|
| 199 |
+
|
| 200 |
+
if job:
|
| 201 |
+
for step in job.get('steps'):
|
| 202 |
+
step['status'] = step_status
|
| 203 |
+
return update_job_file(job_id, job)
|
| 204 |
+
return False
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def read_job_file(job_id : str) -> Optional[Job]:
|
| 208 |
+
job_path = find_job_path(job_id)
|
| 209 |
+
return read_json(job_path) #type:ignore[return-value]
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def create_job_file(job_id : str, job : Job) -> bool:
|
| 213 |
+
job_path = find_job_path(job_id)
|
| 214 |
+
|
| 215 |
+
if not is_file(job_path):
|
| 216 |
+
job_create_path = suggest_job_path(job_id, 'drafted')
|
| 217 |
+
return write_json(job_create_path, job) #type:ignore[arg-type]
|
| 218 |
+
return False
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def update_job_file(job_id : str, job : Job) -> bool:
|
| 222 |
+
job_path = find_job_path(job_id)
|
| 223 |
+
|
| 224 |
+
if is_file(job_path):
|
| 225 |
+
job['date_updated'] = get_current_date_time().isoformat()
|
| 226 |
+
return write_json(job_path, job) #type:ignore[arg-type]
|
| 227 |
+
return False
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def move_job_file(job_id : str, job_status : JobStatus) -> bool:
|
| 231 |
+
job_path = find_job_path(job_id)
|
| 232 |
+
job_move_path = suggest_job_path(job_id, job_status)
|
| 233 |
+
return move_file(job_path, job_move_path)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def delete_job_file(job_id : str) -> bool:
|
| 237 |
+
job_path = find_job_path(job_id)
|
| 238 |
+
return remove_file(job_path)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def suggest_job_path(job_id : str, job_status : JobStatus) -> Optional[str]:
|
| 242 |
+
job_file_name = get_job_file_name(job_id)
|
| 243 |
+
|
| 244 |
+
if job_file_name:
|
| 245 |
+
return os.path.join(JOBS_PATH, job_status, job_file_name)
|
| 246 |
+
return None
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def find_job_path(job_id : str) -> Optional[str]:
|
| 250 |
+
job_file_name = get_job_file_name(job_id)
|
| 251 |
+
|
| 252 |
+
if job_file_name:
|
| 253 |
+
for job_status in facefusion.choices.job_statuses:
|
| 254 |
+
job_pattern = os.path.join(JOBS_PATH, job_status, job_file_name)
|
| 255 |
+
job_paths = resolve_file_pattern(job_pattern)
|
| 256 |
+
|
| 257 |
+
for job_path in job_paths:
|
| 258 |
+
return job_path
|
| 259 |
+
return None
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def get_job_file_name(job_id : str) -> Optional[str]:
|
| 263 |
+
if job_id:
|
| 264 |
+
return job_id + '.json'
|
| 265 |
+
return None
|
facefusion/jobs/job_runner.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from facefusion.ffmpeg import concat_video
|
| 2 |
+
from facefusion.filesystem import are_images, are_videos, move_file, remove_file
|
| 3 |
+
from facefusion.jobs import job_helper, job_manager
|
| 4 |
+
from facefusion.types import JobOutputSet, JobStep, ProcessStep
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def run_job(job_id : str, process_step : ProcessStep) -> bool:
|
| 8 |
+
queued_job_ids = job_manager.find_job_ids('queued')
|
| 9 |
+
|
| 10 |
+
if job_id in queued_job_ids:
|
| 11 |
+
if run_steps(job_id, process_step) and finalize_steps(job_id):
|
| 12 |
+
clean_steps(job_id)
|
| 13 |
+
return job_manager.move_job_file(job_id, 'completed')
|
| 14 |
+
clean_steps(job_id)
|
| 15 |
+
job_manager.move_job_file(job_id, 'failed')
|
| 16 |
+
return False
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def run_jobs(process_step : ProcessStep, halt_on_error : bool) -> bool:
|
| 20 |
+
queued_job_ids = job_manager.find_job_ids('queued')
|
| 21 |
+
has_error = False
|
| 22 |
+
|
| 23 |
+
if queued_job_ids:
|
| 24 |
+
for job_id in queued_job_ids:
|
| 25 |
+
if not run_job(job_id, process_step):
|
| 26 |
+
has_error = True
|
| 27 |
+
if halt_on_error:
|
| 28 |
+
return False
|
| 29 |
+
return not has_error
|
| 30 |
+
return False
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def retry_job(job_id : str, process_step : ProcessStep) -> bool:
|
| 34 |
+
failed_job_ids = job_manager.find_job_ids('failed')
|
| 35 |
+
|
| 36 |
+
if job_id in failed_job_ids:
|
| 37 |
+
return job_manager.set_steps_status(job_id, 'queued') and job_manager.move_job_file(job_id, 'queued') and run_job(job_id, process_step)
|
| 38 |
+
return False
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def retry_jobs(process_step : ProcessStep, halt_on_error : bool) -> bool:
|
| 42 |
+
failed_job_ids = job_manager.find_job_ids('failed')
|
| 43 |
+
has_error = False
|
| 44 |
+
|
| 45 |
+
if failed_job_ids:
|
| 46 |
+
for job_id in failed_job_ids:
|
| 47 |
+
if not retry_job(job_id, process_step):
|
| 48 |
+
has_error = True
|
| 49 |
+
if halt_on_error:
|
| 50 |
+
return False
|
| 51 |
+
return not has_error
|
| 52 |
+
return False
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def run_step(job_id : str, step_index : int, step : JobStep, process_step : ProcessStep) -> bool:
|
| 56 |
+
step_args = step.get('args')
|
| 57 |
+
|
| 58 |
+
if job_manager.set_step_status(job_id, step_index, 'started') and process_step(job_id, step_index, step_args):
|
| 59 |
+
output_path = step_args.get('output_path')
|
| 60 |
+
step_output_path = job_helper.get_step_output_path(job_id, step_index, output_path)
|
| 61 |
+
|
| 62 |
+
return move_file(output_path, step_output_path) and job_manager.set_step_status(job_id, step_index, 'completed')
|
| 63 |
+
job_manager.set_step_status(job_id, step_index, 'failed')
|
| 64 |
+
return False
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def run_steps(job_id : str, process_step : ProcessStep) -> bool:
|
| 68 |
+
steps = job_manager.get_steps(job_id)
|
| 69 |
+
|
| 70 |
+
if steps:
|
| 71 |
+
for index, step in enumerate(steps):
|
| 72 |
+
if not run_step(job_id, index, step, process_step):
|
| 73 |
+
return False
|
| 74 |
+
return True
|
| 75 |
+
return False
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def finalize_steps(job_id : str) -> bool:
|
| 79 |
+
output_set = collect_output_set(job_id)
|
| 80 |
+
|
| 81 |
+
for output_path, temp_output_paths in output_set.items():
|
| 82 |
+
if are_videos(temp_output_paths):
|
| 83 |
+
if not concat_video(output_path, temp_output_paths):
|
| 84 |
+
return False
|
| 85 |
+
if are_images(temp_output_paths):
|
| 86 |
+
for temp_output_path in temp_output_paths:
|
| 87 |
+
if not move_file(temp_output_path, output_path):
|
| 88 |
+
return False
|
| 89 |
+
return True
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def clean_steps(job_id: str) -> bool:
|
| 93 |
+
output_set = collect_output_set(job_id)
|
| 94 |
+
|
| 95 |
+
for temp_output_paths in output_set.values():
|
| 96 |
+
for temp_output_path in temp_output_paths:
|
| 97 |
+
if not remove_file(temp_output_path):
|
| 98 |
+
return False
|
| 99 |
+
return True
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def collect_output_set(job_id : str) -> JobOutputSet:
|
| 103 |
+
steps = job_manager.get_steps(job_id)
|
| 104 |
+
job_output_set : JobOutputSet = {}
|
| 105 |
+
|
| 106 |
+
for index, step in enumerate(steps):
|
| 107 |
+
output_path = step.get('args').get('output_path')
|
| 108 |
+
|
| 109 |
+
if output_path:
|
| 110 |
+
step_output_path = job_manager.get_step_output_path(job_id, index, output_path)
|
| 111 |
+
job_output_set.setdefault(output_path, []).append(step_output_path)
|
| 112 |
+
return job_output_set
|