mirror of
https://github.com/facefusion/facefusion.git
synced 2026-07-28 21:08:54 +02:00
* Replace audio whenever set via source * add H264_qsv&HEVC_qsv (#768) * Update ffmpeg.py * Update choices.py * Update typing.py * Fix spaces and newlines * Fix return type * Introduce hififace swapper * Disable stream for expression restorer * Webcam polishing part1 (#796) * Cosmetics on ignore comments * Testing for replace audio * Testing for restore audio * Testing for restore audio * Fix replace_audio() * Remove shortest and use fixed video duration * Remove shortest and use fixed video duration * Prevent duplicate entries to local PATH * Do hard exit on invalid args * Need for Python 3.10 * Fix state of face selector * Fix OpenVINO by aliasing GPU.0 to GPU * Fix OpenVINO by aliasing GPU.0 to GPU * Fix/age modifier styleganex 512 (#798) * fix * styleganex template * changes * changes * fix occlusion mask * add age modifier scale * change * change * hardcode * Cleanup * Use model_sizes and model_templates variables * No need for prepare when just 2 lines of code * Someone used spaces over tabs * Revert back [0][0] --------- Co-authored-by: harisreedhar <h4harisreedhar.s.s@gmail.com> * Feat/update gradio5 (#799) * Update to Gradio 5 * Remove overrides for Gradio * Fix dark mode for Gradio * Polish errors * More styles for tabs and co * Make slider inputs and reset like a unit * Make slider inputs and reset like a unit * Adjust naming * Improved color matching (#800) * aura fix * fix import * move to vision.py * changes * changes * changes * changes * further reduction * add test * better test * change name * Minor cleanup * Minor cleanup * Minor cleanup * changes (#801) * Switch to official assets repo * Add __pycache__ to gitignore * Gradio pinned python-multipart to 0.0.12 * Update dependencies * Feat/temp path second try (#802) * Terminate base directory from temp helper * Partial adjust program codebase * Move arguments around * Make `-j` absolete * Resolve args * Fix job register keys * Adjust date test * Finalize temp path * Update onnxruntime * Update dependencies * Adjust color for checkboxes * Revert due terrible performance * Fix/enforce vp9 for webm (#805) * Simple fix to enforce vp9 for webm * Remove suggest methods from program helper * Cleanup ffmpeg.py a bit * Update onnxruntime (second try) * Update onnxruntime (second try) * Remove cudnn_conv_algo_search tweaks * Remove cudnn_conv_algo_search tweaks * changes * add both mask instead of multiply * adaptive color correction * changes * remove model size requirement * changes * add to facefusion.ini * changes * changes * changes * Add namespace for dfm creators * Release five frame enhancer models * Remove vendor from model name * Remove vendor from model name * changes * changes * changes * changes * Feat/download providers (#809) * Introduce download providers * update processors download method * add ui * Fix CI * Adjust UI component order, Use download resolver for benchmark * Remove is_download_done() * Introduce download provider set, Remove choices method from execution, cast all dict keys() via list() * Fix spacing --------- Co-authored-by: harisreedhar <h4harisreedhar.s.s@gmail.com> * Fix model paths for 3.1.0 * Introduce bulk-run (#810) * Introduce bulk-run * Make bulk run bullet proof * Integration test for bulk-run * new alignment * Add safer global named resolve_file_pattern() (#811) * Allow bulk runner with target pattern only * changes * changes * Update Python to 3.12 for CI (#813) * changes * Improve NVIDIA device lookups * Rename template key to deepfacelive * Fix name * Improve resolve download * Rename bulk-run to batch-run * Make deep swapper inputs universal * Add more deepfacelive models * Use different morph value * Feat/simplify hashes sources download (#814) * Extract download directory path from assets path * Fix lint * Fix force-download command, Fix urls in frame enhancer * changes * fix warp_face_by_bounding_box dtype error * DFM Morph (#816) * changes * Improve wording, Replace [None], SideQuest: clean forward() of age modifier * SideQuest: clean forward() of face enhancer --------- Co-authored-by: henryruhs <info@henryruhs.com> * Fix preview refresh after slide * Add more deepfacelive models (#817) * Add more deepfacelive models * Add more deepfacelive models * Fix deep swapper sizes * Kill accent colors, Number input styles for Chrome * Simplify thumbnail-item looks * Fix first black screen * Introduce model helper * ci.yml: Add macOS on ARM64 to the testing (#818) * ci.yml: Add macOS on ARM64 to the testing * ci.yml: uses: AnimMouse/setup-ffmpeg@v1 * ci.yml: strategy: matrix: os: macos-latest, * - name: Set up FFmpeg * Update .github/workflows/ci.yml * Update ci.yml --------- Co-authored-by: Henry Ruhs <info@henryruhs.com> * Show/hide morph slider for deep swapper (#822) * remove dfl_head and update dfl_whole_face template * Add deep swapper models by Mats * Add deep swapper models by Druuzil * Add deep swapper models by Rumateus * Implement face enhancer weight for codeformer, Side Quest: has proces… (#823) * Implement face enhancer weight for codeformer, Side Quest: has processor checks * Fix typo * Fix face enhancer blend in UI * Use static model set creation * Add deep swapper models by Jen * Introduce create_static_model_set() everywhere (#824) * Move clear over to the UI (#825) * Fix model key * Undo restore_audio() * Switch to latest XSeg * Switch to latest XSeg * Switch to latest XSeg * Use resolve_download_url() everywhere, Vanish --skip-download flag * Fix resolve_download_url * Fix space * Kill resolve_execution_provider_keys() and move fallbacks where they belong * Kill resolve_execution_provider_keys() and move fallbacks where they belong * Remove as this does not work * Change TempFrameFormat order * Fix CoreML partially * Remove duplicates (Rumateus is the creator) * Add deep swapper models by Edel * Introduce download scopes (#826) * Introduce download scopes * Limit download scopes to force-download command * Change source-paths behaviour * Fix space * Update README * Rename create_log_level_program to create_misc_program * Fix wording * Fix wording * Update dependencies * Use tolerant for video_memory_strategy in benchmark * Feat/ffmpeg with progress (#827) * FFmpeg with progress bar * Fix typing * FFmpeg with progress bar part2 * Restore streaming wording * Change order in choices and typing * Introduce File using list_directory() (#830) * Feat/local deep swapper models (#832) * Local model support for deep swapper * Local model support for deep swapper part2 * Local model support for deep swapper part3 * Update yet another dfm by Druuzil * Refactor/choices and naming (#833) * Refactor choices, imports and naming * Refactor choices, imports and naming * Fix styles for tabs, Restore toast * Update yet another dfm by Druuzil * Feat/face masker models (#834) * Introduce face masker models * Introduce face masker models * Introduce face masker models * Register needed step keys * Provide different XSeg models * Simplify model context * Fix out of range for trim frame, Fix ffmpeg extraction count (#836) * Fix out of range for trim frame, Fix ffmpeg extraction count * Move restrict of trim frame to the core, Make sure all values are within the range * Fix and merge testing * Fix typing * Add region mask for deep swapper * Adjust wording * Move FACE_MASK_REGIONS to choices * Update dependencies * Feat/download provider fallback (#837) * Introduce download providers fallback, Use CURL everywhre * Fix CI * Use readlines() over readline() to avoid while * Use readlines() over readline() to avoid while * Use readlines() over readline() to avoid while * Use communicate() over wait() * Minor updates for testing * Stop webcam on source image change * Feat/webcam improvements (#838) * Detect available webcams * Fix CI, Move webcam id dropdown to the sidebar, Disable warnings * Fix CI * Remove signal on hard_exit() to prevent exceptions * Fix border color in toast timer * Prepare release * Update preview * Update preview * Hotfix progress bar --------- Co-authored-by: DDXDB <38449595+DDXDB@users.noreply.github.com> Co-authored-by: harisreedhar <h4harisreedhar.s.s@gmail.com> Co-authored-by: Harisreedhar <46858047+harisreedhar@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com>
192 lines
6.8 KiB
Python
192 lines
6.8 KiB
Python
import os
|
|
import subprocess
|
|
from collections import deque
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from typing import Deque, Generator, List, Optional
|
|
|
|
import cv2
|
|
import gradio
|
|
from tqdm import tqdm
|
|
|
|
from facefusion import logger, state_manager, wording
|
|
from facefusion.audio import create_empty_audio_frame
|
|
from facefusion.common_helper import get_first, is_windows
|
|
from facefusion.content_analyser import analyse_stream
|
|
from facefusion.face_analyser import get_average_face, get_many_faces
|
|
from facefusion.ffmpeg import open_ffmpeg
|
|
from facefusion.filesystem import filter_image_paths
|
|
from facefusion.processors.core import get_processors_modules
|
|
from facefusion.typing import Face, Fps, VisionFrame
|
|
from facefusion.uis.core import get_ui_component
|
|
from facefusion.uis.typing import StreamMode, WebcamMode
|
|
from facefusion.vision import normalize_frame_color, read_static_images, unpack_resolution
|
|
|
|
WEBCAM_CAPTURE : Optional[cv2.VideoCapture] = None
|
|
WEBCAM_IMAGE : Optional[gradio.Image] = None
|
|
WEBCAM_START_BUTTON : Optional[gradio.Button] = None
|
|
WEBCAM_STOP_BUTTON : Optional[gradio.Button] = None
|
|
|
|
|
|
def get_webcam_capture(webcam_device_id : int) -> Optional[cv2.VideoCapture]:
|
|
global WEBCAM_CAPTURE
|
|
|
|
if WEBCAM_CAPTURE is None:
|
|
cv2.setLogLevel(0)
|
|
if is_windows():
|
|
webcam_capture = cv2.VideoCapture(webcam_device_id, cv2.CAP_DSHOW)
|
|
else:
|
|
webcam_capture = cv2.VideoCapture(webcam_device_id)
|
|
cv2.setLogLevel(3)
|
|
|
|
if webcam_capture and webcam_capture.isOpened():
|
|
WEBCAM_CAPTURE = webcam_capture
|
|
return WEBCAM_CAPTURE
|
|
|
|
|
|
def clear_webcam_capture() -> None:
|
|
global WEBCAM_CAPTURE
|
|
|
|
if WEBCAM_CAPTURE and WEBCAM_CAPTURE.isOpened():
|
|
WEBCAM_CAPTURE.release()
|
|
WEBCAM_CAPTURE = None
|
|
|
|
|
|
def render() -> None:
|
|
global WEBCAM_IMAGE
|
|
global WEBCAM_START_BUTTON
|
|
global WEBCAM_STOP_BUTTON
|
|
|
|
WEBCAM_IMAGE = gradio.Image(
|
|
label = wording.get('uis.webcam_image')
|
|
)
|
|
WEBCAM_START_BUTTON = gradio.Button(
|
|
value = wording.get('uis.start_button'),
|
|
variant = 'primary',
|
|
size = 'sm'
|
|
)
|
|
WEBCAM_STOP_BUTTON = gradio.Button(
|
|
value = wording.get('uis.stop_button'),
|
|
size = 'sm'
|
|
)
|
|
|
|
|
|
def listen() -> None:
|
|
webcam_device_id_dropdown = get_ui_component('webcam_device_id_dropdown')
|
|
webcam_mode_radio = get_ui_component('webcam_mode_radio')
|
|
webcam_resolution_dropdown = get_ui_component('webcam_resolution_dropdown')
|
|
webcam_fps_slider = get_ui_component('webcam_fps_slider')
|
|
source_image = get_ui_component('source_image')
|
|
|
|
if webcam_device_id_dropdown and webcam_mode_radio and webcam_resolution_dropdown and webcam_fps_slider:
|
|
start_event = WEBCAM_START_BUTTON.click(start, inputs = [ webcam_device_id_dropdown, webcam_mode_radio, webcam_resolution_dropdown, webcam_fps_slider ], outputs = WEBCAM_IMAGE)
|
|
WEBCAM_STOP_BUTTON.click(stop, cancels = start_event, outputs = WEBCAM_IMAGE)
|
|
|
|
if source_image:
|
|
source_image.change(stop, cancels = start_event, outputs = WEBCAM_IMAGE)
|
|
|
|
|
|
def start(webcam_device_id : int, webcam_mode : WebcamMode, webcam_resolution : str, webcam_fps : Fps) -> Generator[VisionFrame, None, None]:
|
|
state_manager.set_item('face_selector_mode', 'one')
|
|
source_image_paths = filter_image_paths(state_manager.get_item('source_paths'))
|
|
source_frames = read_static_images(source_image_paths)
|
|
source_faces = get_many_faces(source_frames)
|
|
source_face = get_average_face(source_faces)
|
|
stream = None
|
|
webcam_capture = None
|
|
|
|
if webcam_mode in [ 'udp', 'v4l2' ]:
|
|
stream = open_stream(webcam_mode, webcam_resolution, webcam_fps) #type:ignore[arg-type]
|
|
webcam_width, webcam_height = unpack_resolution(webcam_resolution)
|
|
|
|
if isinstance(webcam_device_id, int):
|
|
webcam_capture = get_webcam_capture(webcam_device_id)
|
|
|
|
if webcam_capture and webcam_capture.isOpened():
|
|
webcam_capture.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG')) #type:ignore[attr-defined]
|
|
webcam_capture.set(cv2.CAP_PROP_FRAME_WIDTH, webcam_width)
|
|
webcam_capture.set(cv2.CAP_PROP_FRAME_HEIGHT, webcam_height)
|
|
webcam_capture.set(cv2.CAP_PROP_FPS, webcam_fps)
|
|
|
|
for capture_frame in multi_process_capture(source_face, webcam_capture, webcam_fps):
|
|
if webcam_mode == 'inline':
|
|
yield normalize_frame_color(capture_frame)
|
|
else:
|
|
try:
|
|
stream.stdin.write(capture_frame.tobytes())
|
|
except Exception:
|
|
clear_webcam_capture()
|
|
yield None
|
|
|
|
|
|
def multi_process_capture(source_face : Face, webcam_capture : cv2.VideoCapture, webcam_fps : Fps) -> Generator[VisionFrame, None, None]:
|
|
deque_capture_frames: Deque[VisionFrame] = deque()
|
|
|
|
with tqdm(desc = wording.get('streaming'), unit = 'frame', disable = state_manager.get_item('log_level') in [ 'warn', 'error' ]) as progress:
|
|
with ThreadPoolExecutor(max_workers = state_manager.get_item('execution_thread_count')) as executor:
|
|
futures = []
|
|
|
|
while webcam_capture and webcam_capture.isOpened():
|
|
_, capture_frame = webcam_capture.read()
|
|
if analyse_stream(capture_frame, webcam_fps):
|
|
yield None
|
|
future = executor.submit(process_stream_frame, source_face, capture_frame)
|
|
futures.append(future)
|
|
|
|
for future_done in [ future for future in futures if future.done() ]:
|
|
capture_frame = future_done.result()
|
|
deque_capture_frames.append(capture_frame)
|
|
futures.remove(future_done)
|
|
|
|
while deque_capture_frames:
|
|
progress.update()
|
|
yield deque_capture_frames.popleft()
|
|
|
|
|
|
def stop() -> gradio.Image:
|
|
clear_webcam_capture()
|
|
return gradio.Image(value = None)
|
|
|
|
|
|
def process_stream_frame(source_face : Face, target_vision_frame : VisionFrame) -> VisionFrame:
|
|
source_audio_frame = create_empty_audio_frame()
|
|
|
|
for processor_module in get_processors_modules(state_manager.get_item('processors')):
|
|
logger.disable()
|
|
if processor_module.pre_process('stream'):
|
|
target_vision_frame = processor_module.process_frame(
|
|
{
|
|
'source_face': source_face,
|
|
'source_audio_frame': source_audio_frame,
|
|
'target_vision_frame': target_vision_frame
|
|
})
|
|
logger.enable()
|
|
return target_vision_frame
|
|
|
|
|
|
def open_stream(stream_mode : StreamMode, stream_resolution : str, stream_fps : Fps) -> subprocess.Popen[bytes]:
|
|
commands = [ '-f', 'rawvideo', '-pix_fmt', 'bgr24', '-s', stream_resolution, '-r', str(stream_fps), '-i', '-']
|
|
|
|
if stream_mode == 'udp':
|
|
commands.extend([ '-b:v', '2000k', '-f', 'mpegts', 'udp://localhost:27000?pkt_size=1316' ])
|
|
if stream_mode == 'v4l2':
|
|
try:
|
|
device_name = get_first(os.listdir('/sys/devices/virtual/video4linux'))
|
|
if device_name:
|
|
commands.extend([ '-f', 'v4l2', '/dev/' + device_name ])
|
|
except FileNotFoundError:
|
|
logger.error(wording.get('stream_not_loaded').format(stream_mode = stream_mode), __name__)
|
|
return open_ffmpeg(commands)
|
|
|
|
|
|
def get_available_webcam_ids(webcam_id_start : int, webcam_id_end : int) -> List[int]:
|
|
available_webcam_ids = []
|
|
|
|
for index in range(webcam_id_start, webcam_id_end):
|
|
webcam_capture = get_webcam_capture(index)
|
|
|
|
if webcam_capture and webcam_capture.isOpened():
|
|
available_webcam_ids.append(index)
|
|
clear_webcam_capture()
|
|
|
|
return available_webcam_ids
|