Compare commits

...
54 Commits
Author SHA1 Message Date
henryruhs 2f388a4d1c vibe code to recent v4 changes 2026-06-15 15:18:21 +02:00
harisreedhar e003785ecb fix asset loading issue 2026-02-24 19:06:44 +05:30
HarisreedharandGitHub 6f70f51d5e Merge pull request #1028 from facefusion/poc/api-update
refactor api
2026-01-26 16:45:32 +05:30
harisreedhar b7b60c186f refactor api 2026-01-26 16:37:33 +05:30
henryruhs ed1c9b0b24 POC for API 2025-12-20 22:16:40 +01:00
henryruhs 72bb4b8865 POC for API 2025-12-20 18:47:38 +01:00
henryruhsandClaude 423fee9d7f feat: add API process functionality
This commit adds comprehensive API process functionality including:
- Remote streaming support
- Session management and context handling
- Media type support (video/audio/image)
- Asset management and path isolation
- Workflow refactoring and optimization
- Security improvements and state violation handling
- Gallery and image resolution features
- Audio support
- Analysis tools
- Version guard

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-20 14:35:07 +01:00
harisreedhar bed330f701 create to_image.py 2025-12-19 16:49:31 +05:30
HarisreedharandGitHub 3b93008906 Merge pull request #1009 from facefusion/feat/audio-to-image-as-frames
audio to image as frames
2025-12-19 16:41:21 +05:30
harisreedhar f9f3a9e62b audio to image as frames 2025-12-19 16:03:37 +05:30
harisreedhar 3479cd0af3 audio to image as frames 2025-12-18 19:56:31 +05:30
henryruhs 1e8e763516 Rename local(s) to locale(s) 2025-12-17 18:50:50 +01:00
harisreedharandhenryruhs b2a2f84c24 workflows rename 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs 0773403d4b workflows rename 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs 23f865640a image to video as sequence 2025-12-17 18:42:13 +01:00
Henry Ruhs 396610e88c feat/ping-endpoint (#1001)
* api: add WebSocket /ping endpoint and update session guard to support WebSocket subprotocol auth; add tests (test_api_ping.py)

* Initial websocket support using ping

* Initial websocket support using ping

* Initial websocket support using ping

* Combine imports
2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs 286d25e91d use common analyse_image method 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs deb5909f91 to video unification 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs 17f24784ad to video unification 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs e9d9dec598 detect workflow 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs 12ab871289 changes
restructure conditional methods to a fall-through pattern

common process_temp_frame for all workflow
2025-12-17 18:42:13 +01:00
Henry Ruhs 44830ffd9d Feat/session context (#993)
* Add simple session context

* Add simple session context
2025-12-17 18:42:13 +01:00
Henry Ruhs e13b81207c Add simple path isolation (#992) 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs c7e61d1678 update ffmpeg.set_loop
add test

introduce spawn_frames
2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs 50473df4c0 changes 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs 2dbf4523fe remove --keep-temp 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs 1cfabf6639 Part 2 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs 03d1555a6f Part 2 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs cba29311c1 fix 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs 35c2022700 part 1 2025-12-17 18:42:13 +01:00
henryruhs 549de72bef Switch workflow args order in tests, Remove old choices in processors 2025-12-17 18:42:13 +01:00
henryruhs 9e6c070629 Switch workflow args order in tests, Remove old choices in processors 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs d4a4cf71d4 add todo
add test

cleanup

remove -w

move --workflow position

fix test

add --worflow, audio-to-image, image-to-image, image-to-video
2025-12-17 18:42:13 +01:00
Henry Ruhs 6180ccf6e6 Scope for Args (#988)
* Add API scopes

* Add API scopes

* Add API scopes

* Add API scopes

* Add API scopes

* Add API scopes

* Add API scopes

* Add API scopes

* Remove system memory limit (#986)

# Conflicts:
#	facefusion/program.py

* Add session_id, make token size more reasonable (#983)

* Add session_id, make token size more reasonable

* Use more direct approach

* Fix more stuff

* Fix ignore comments

* Fix naming

* Fix lint
2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs 65a61d5001 changes 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs 7ccf4d5eda changes 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs b035f1a6e5 changes 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs 588eb049b0 rename to target_path 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs 0a4e1c639d fix exit-helper 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs 85b6d962f2 refactor temp handling from target-path to output-path 2025-12-17 18:42:13 +01:00
henryruhs 6f89e7db51 Burn it with fire 2025-12-17 18:42:13 +01:00
henryruhs 69ad7572c6 Burn it with fire 2025-12-17 18:42:13 +01:00
Henry Ruhs 68a56588e3 Remove system memory limit (#986) 2025-12-17 18:42:13 +01:00
Henry Ruhs 4b0d6c3333 Add session_id, make token size more reasonable (#983)
* Add session_id, make token size more reasonable

* Use more direct approach
2025-12-17 18:42:13 +01:00
Henry Ruhs 3daf049684 Local API (#982)
* Introduce API scelleton

* Raw impl for session

* Simple state endpoint

* Apply _body naming

* Finalize session testing and comment out tons of useless code

* Clean and refactor part1

* Clean and refactor part2

* Clean and refactor part2

* Clean and refactor part2

* Clean and refactor part2

* Refactor middleware

* Refactor middleware

* Clean and refactor part3

* TDD and 2 beers

* TDD and 2 beers

* Complete state endpoints

* You can only set what is already present

* Use only JSON as response

* Use default logger

* Improve auth extraction

* Extend api command with more args

* Adjust API messages
2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs f745ddc831 remove output_path argument 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs 8f27d5dd08 remove output_path argument from merge_video() 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs a6bd2cdcc7 remove output_video_fps argument from merge_video() 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs 3ef90673b5 rename method argument 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs 29e3014945 fix 2025-12-17 18:42:13 +01:00
harisreedharandhenryruhs 7e2f793cf4 remove same file extension constraint 2025-12-17 18:42:13 +01:00
Henry Ruhs 0d2a434e61 Refactor reusable workflow tasks (#980)
* Refactor reusable workflow tasks

* Refactor reusable workflow tasks

* Make it borderline again
2025-12-17 18:42:13 +01:00
Henry Ruhs cfa2216d0c Feels so good to get rid of Gradio (#978) 2025-12-17 18:42:13 +01:00
henryruhs 20293d1fa3 Mark es temporary v4 2025-12-17 18:42:13 +01:00
181 changed files with 5772 additions and 5301 deletions
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

+2
View File
@@ -35,6 +35,7 @@ jobs:
python-version: '3.12'
- run: python install.py --onnxruntime default --skip-conda
- run: pip install pytest
- run: pip install httpx
- run: pytest
report:
needs: test
@@ -52,6 +53,7 @@ jobs:
- run: pip install coveralls
- run: pip install pytest
- run: pip install pytest-cov
- run: pip install httpx
- run: pytest tests --cov facefusion
- run: coveralls --service github
env:
+1 -7
View File
@@ -8,12 +8,6 @@ FaceFusion
![License](https://img.shields.io/badge/license-OpenRAIL--AS-green)
Preview
-------
![Preview](https://raw.githubusercontent.com/facefusion/facefusion/master/.github/preview.png?sanitize=true)
Installation
------------
@@ -34,10 +28,10 @@ options:
commands:
run run the program
headless-run run the program in headless mode
batch-run run the program in batch mode
force-download force automate downloads and exit
benchmark benchmark the program
api start the API server
job-list list jobs by status
job-create create a drafted job
job-submit submit a drafted job to become a queued job
+7 -7
View File
@@ -1,3 +1,6 @@
[workflow]
workflow =
[paths]
temp_path =
jobs_path =
@@ -48,7 +51,6 @@ voice_extractor_model =
trim_frame_start =
trim_frame_end =
temp_frame_format =
keep_temp =
[output_creation]
output_image_quality =
@@ -103,11 +105,6 @@ frame_enhancer_blend =
lip_syncer_model =
lip_syncer_weight =
[uis]
open_browser =
ui_layouts =
ui_workflow =
[download]
download_providers =
download_scope =
@@ -117,6 +114,10 @@ benchmark_mode =
benchmark_resolutions =
benchmark_cycle_count =
[api]
api_host =
api_port =
[execution]
execution_device_ids =
execution_providers =
@@ -124,7 +125,6 @@ execution_thread_count =
[memory]
video_memory_strategy =
system_memory_limit =
[misc]
log_level =
+15
View File
@@ -0,0 +1,15 @@
from typing import Optional
from starlette.datastructures import Headers
from starlette.types import Scope
def get_sec_websocket_protocol(scope : Scope) -> Optional[str]:
protocol_header = Headers(scope = scope).get('Sec-WebSocket-Protocol')
if protocol_header:
protocol, _, _ = protocol_header.partition(',')
return protocol.strip()
return None
+50
View File
@@ -0,0 +1,50 @@
from typing import Optional
from facefusion.audio import detect_audio_duration
from facefusion.filesystem import is_audio, is_image, is_video
from facefusion.types import AudioMetadata, ImageMetadata, MediaType, VideoMetadata
from facefusion.vision import count_video_frame_total, detect_image_resolution, detect_video_duration, detect_video_fps, detect_video_resolution
def extract_audio_metadata(file_path : str) -> AudioMetadata:
metadata : AudioMetadata =\
{
'duration': detect_audio_duration(file_path),
'sample_rate': 0,
'frame_total': 0,
'channels': 0,
'format': ''
}
return metadata
def extract_image_metadata(file_path : str) -> ImageMetadata:
resolution = detect_image_resolution(file_path)
metadata : ImageMetadata =\
{
'resolution': resolution if resolution else (0, 0)
}
return metadata
def extract_video_metadata(file_path : str) -> VideoMetadata:
resolution = detect_video_resolution(file_path)
fps = detect_video_fps(file_path)
metadata : VideoMetadata =\
{
'duration': detect_video_duration(file_path),
'frame_total': count_video_frame_total(file_path),
'fps': fps if fps else 0.0,
'resolution': resolution if resolution else (0, 0)
}
return metadata
def detect_media_type(file_path : str) -> Optional[MediaType]:
if is_audio(file_path):
return 'audio'
if is_image(file_path):
return 'image'
if is_video(file_path):
return 'video'
return None
+92
View File
@@ -0,0 +1,92 @@
import os
import uuid
from datetime import datetime, timedelta
from typing import List, Optional, cast
from facefusion.apis.asset_helper import detect_media_type, extract_audio_metadata, extract_image_metadata, extract_video_metadata
from facefusion.filesystem import get_file_format, get_file_name
from facefusion.types import AssetId, AssetSet, AssetStore, AssetType, AudioAsset, AudioFormat, ImageAsset, ImageFormat, SessionId, VideoAsset, VideoFormat
ASSET_STORE : AssetStore = {}
def create_asset(session_id : SessionId, asset_type : AssetType, asset_path : str) -> Optional[AudioAsset | ImageAsset | VideoAsset]:
asset_id = str(uuid.uuid4())
asset_name = get_file_name(asset_path)
asset_format = get_file_format(asset_path)
asset_size = os.path.getsize(asset_path)
media_type = detect_media_type(asset_path)
created_at = datetime.now()
expires_at = created_at + timedelta(hours = 2)
if session_id not in ASSET_STORE:
ASSET_STORE[session_id] = {}
if media_type == 'audio':
ASSET_STORE[session_id][asset_id] = cast(AudioAsset,
{
'id': asset_id,
'created_at': created_at,
'expires_at': expires_at,
'type': asset_type,
'media': media_type,
'name': asset_name,
'format': cast(AudioFormat, asset_format),
'size': asset_size,
'path': asset_path,
'metadata': extract_audio_metadata(asset_path)
})
if media_type == 'image':
ASSET_STORE[session_id][asset_id] = cast(ImageAsset,
{
'id': asset_id,
'created_at': created_at,
'expires_at': expires_at,
'type': asset_type,
'media': media_type,
'name': asset_name,
'format': cast(ImageFormat, asset_format),
'size': asset_size,
'path': asset_path,
'metadata': extract_image_metadata(asset_path)
})
if media_type == 'video':
ASSET_STORE[session_id][asset_id] = cast(VideoAsset,
{
'id': asset_id,
'created_at': created_at,
'expires_at': expires_at,
'type': asset_type,
'media': media_type,
'name': asset_name,
'format': cast(VideoFormat, asset_format),
'size': asset_size,
'path': asset_path,
'metadata': extract_video_metadata(asset_path)
})
return ASSET_STORE[session_id].get(asset_id)
def get_assets(session_id : SessionId) -> Optional[AssetSet]:
return ASSET_STORE.get(session_id)
def get_asset(session_id : SessionId, asset_id : AssetId) -> Optional[AudioAsset | ImageAsset | VideoAsset]:
if session_id in ASSET_STORE:
return ASSET_STORE.get(session_id).get(asset_id)
return None
def delete_assets(session_id : SessionId, asset_ids : List[AssetId]) -> None:
if session_id in ASSET_STORE:
for asset_id in asset_ids:
if asset_id in ASSET_STORE.get(session_id):
del ASSET_STORE[session_id][asset_id]
return None
def clear() -> None:
ASSET_STORE.clear()
+162
View File
@@ -0,0 +1,162 @@
from typing import Any, Dict
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.status import HTTP_200_OK
import facefusion.choices
from facefusion.execution import get_available_execution_providers
from facefusion.ffmpeg import get_available_encoder_set
from facefusion.processors.modules.face_debugger import choices as face_debugger_choices
from facefusion.processors.modules.face_enhancer import choices as face_enhancer_choices
from facefusion.processors.modules.face_swapper import choices as face_swapper_choices
from facefusion.processors.modules.frame_enhancer import choices as frame_enhancer_choices
async def get_choices(request : Request) -> JSONResponse:
available_execution_providers = get_available_execution_providers()
available_encoder_set = get_available_encoder_set()
choices_data : Dict[str, Any] =\
{
'face_detector_models': facefusion.choices.face_detector_models,
'face_detector_set': facefusion.choices.face_detector_set,
'face_landmarker_models': facefusion.choices.face_landmarker_models,
'face_selector_modes': facefusion.choices.face_selector_modes,
'face_selector_orders': facefusion.choices.face_selector_orders,
'face_selector_genders': facefusion.choices.face_selector_genders,
'face_selector_races': facefusion.choices.face_selector_races,
'face_occluder_models': facefusion.choices.face_occluder_models,
'face_parser_models': facefusion.choices.face_parser_models,
'face_mask_types': facefusion.choices.face_mask_types,
'face_mask_areas': facefusion.choices.face_mask_areas,
'face_mask_regions': facefusion.choices.face_mask_regions,
'voice_extractor_models': facefusion.choices.voice_extractor_models,
'workflows': facefusion.choices.workflows,
'audio_formats': facefusion.choices.audio_formats,
'image_formats': facefusion.choices.image_formats,
'video_formats': facefusion.choices.video_formats,
'temp_frame_formats': facefusion.choices.temp_frame_formats,
'output_audio_encoders': available_encoder_set.get('audio'),
'output_video_encoders': available_encoder_set.get('video'),
'output_video_presets': facefusion.choices.output_video_presets,
'execution_providers': available_execution_providers,
'video_memory_strategies': facefusion.choices.video_memory_strategies,
'log_levels': facefusion.choices.log_levels,
'face_swapper_models': face_swapper_choices.face_swapper_models,
'face_swapper_set': face_swapper_choices.face_swapper_set,
'face_enhancer_models': face_enhancer_choices.face_enhancer_models,
'frame_enhancer_models': frame_enhancer_choices.frame_enhancer_models,
'face_debugger_items': face_debugger_choices.face_debugger_items,
'face_detector_angles': list(facefusion.choices.face_detector_angles),
'face_detector_score_range':
{
'min': min(facefusion.choices.face_detector_score_range),
'max': max(facefusion.choices.face_detector_score_range),
'step': facefusion.choices.face_detector_score_range[1] - facefusion.choices.face_detector_score_range[0]
},
'face_landmarker_score_range':
{
'min': min(facefusion.choices.face_landmarker_score_range),
'max': max(facefusion.choices.face_landmarker_score_range),
'step': facefusion.choices.face_landmarker_score_range[1] - facefusion.choices.face_landmarker_score_range[0]
},
'face_mask_blur_range':
{
'min': min(facefusion.choices.face_mask_blur_range),
'max': max(facefusion.choices.face_mask_blur_range),
'step': facefusion.choices.face_mask_blur_range[1] - facefusion.choices.face_mask_blur_range[0]
},
'face_mask_padding_range':
{
'min': min(facefusion.choices.face_mask_padding_range),
'max': max(facefusion.choices.face_mask_padding_range),
'step': 1
},
'face_selector_age_range':
{
'min': min(facefusion.choices.face_selector_age_range),
'max': max(facefusion.choices.face_selector_age_range),
'step': 1
},
'reference_face_distance_range':
{
'min': min(facefusion.choices.reference_face_distance_range),
'max': max(facefusion.choices.reference_face_distance_range),
'step': facefusion.choices.reference_face_distance_range[1] - facefusion.choices.reference_face_distance_range[0]
},
'output_image_quality_range':
{
'min': min(facefusion.choices.output_image_quality_range),
'max': max(facefusion.choices.output_image_quality_range),
'step': 1
},
'output_image_scale_range':
{
'min': min(facefusion.choices.output_image_scale_range),
'max': max(facefusion.choices.output_image_scale_range),
'step': facefusion.choices.output_image_scale_range[1] - facefusion.choices.output_image_scale_range[0]
},
'output_audio_quality_range':
{
'min': min(facefusion.choices.output_audio_quality_range),
'max': max(facefusion.choices.output_audio_quality_range),
'step': 1
},
'output_audio_volume_range':
{
'min': min(facefusion.choices.output_audio_volume_range),
'max': max(facefusion.choices.output_audio_volume_range),
'step': 1
},
'output_video_quality_range':
{
'min': min(facefusion.choices.output_video_quality_range),
'max': max(facefusion.choices.output_video_quality_range),
'step': 1
},
'output_video_scale_range':
{
'min': min(facefusion.choices.output_video_scale_range),
'max': max(facefusion.choices.output_video_scale_range),
'step': facefusion.choices.output_video_scale_range[1] - facefusion.choices.output_video_scale_range[0]
},
'execution_thread_count_range':
{
'min': min(facefusion.choices.execution_thread_count_range),
'max': max(facefusion.choices.execution_thread_count_range),
'step': 1
},
'face_detector_margin_range':
{
'min': min(facefusion.choices.face_detector_margin_range),
'max': max(facefusion.choices.face_detector_margin_range),
'step': 1
},
'face_swapper_weight_range':
{
'min': min(face_swapper_choices.face_swapper_weight_range),
'max': max(face_swapper_choices.face_swapper_weight_range),
'step': face_swapper_choices.face_swapper_weight_range[1] - face_swapper_choices.face_swapper_weight_range[0]
},
'face_enhancer_blend_range':
{
'min': min(face_enhancer_choices.face_enhancer_blend_range),
'max': max(face_enhancer_choices.face_enhancer_blend_range),
'step': 1
},
'face_enhancer_weight_range':
{
'min': min(face_enhancer_choices.face_enhancer_weight_range),
'max': max(face_enhancer_choices.face_enhancer_weight_range),
'step': face_enhancer_choices.face_enhancer_weight_range[1] - face_enhancer_choices.face_enhancer_weight_range[0]
},
'frame_enhancer_blend_range':
{
'min': min(frame_enhancer_choices.frame_enhancer_blend_range),
'max': max(frame_enhancer_choices.frame_enhancer_blend_range),
'step': 1
}
}
return JSONResponse(choices_data, status_code = HTTP_200_OK)
+47
View File
@@ -0,0 +1,47 @@
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
from starlette.routing import Route, WebSocketRoute
from facefusion.apis.choices import get_choices
from facefusion.apis.endpoints.assets import delete_asset, delete_assets, get_asset, get_assets, upload_asset
from facefusion.apis.endpoints.ping import websocket_ping
from facefusion.apis.endpoints.session import create_session, create_session_guard, destroy_session, get_session, refresh_session
from facefusion.apis.endpoints.state import get_state, set_state
from facefusion.apis.endpoints.stream import delete_stream, post_stream, websocket_stream
from facefusion.apis.metrics import websocket_metrics
from facefusion.apis.remote import remote
from facefusion.apis.timeline import get_timeline
from facefusion.apis.version import create_version_guard
def create_api() -> Starlette:
version_guard = Middleware(create_version_guard)
session_guard = Middleware(create_session_guard)
routes =\
[
Route('/session', create_session, methods = [ 'POST' ], middleware = [ version_guard ]),
Route('/session', get_session, methods = [ 'GET' ], middleware = [ version_guard, session_guard ]),
Route('/session', refresh_session, methods = [ 'PUT' ], middleware = [ version_guard ]),
Route('/session', destroy_session, methods = [ 'DELETE' ], middleware = [ version_guard, session_guard ]),
Route('/state', get_state, methods = [ 'GET' ], middleware = [ version_guard, session_guard ]),
Route('/state', set_state, methods = [ 'PUT' ], middleware = [ version_guard, session_guard ]),
Route('/assets', get_assets, methods = [ 'GET' ], middleware = [ version_guard, session_guard ]),
Route('/assets', upload_asset, methods = [ 'POST' ], middleware = [ version_guard, session_guard ]),
Route('/assets/{asset_id}', get_asset, methods = [ 'GET' ], middleware = [ version_guard, session_guard ]),
Route('/assets/{asset_id}', delete_asset, methods = [ 'DELETE' ], middleware = [ version_guard, session_guard ]),
Route('/assets', delete_assets, methods = [ 'DELETE' ], middleware = [ version_guard, session_guard ]),
Route('/choices', get_choices, methods = [ 'GET' ], middleware = [ version_guard, session_guard ]),
Route('/remote', remote, methods = [ 'POST' ], middleware = [ version_guard, session_guard ]),
Route('/timeline/{count:int}', get_timeline, methods = [ 'GET' ], middleware = [ version_guard, session_guard ]),
Route('/stream', post_stream, methods = [ 'POST' ], middleware = [ version_guard, session_guard ]),
Route('/stream', delete_stream, methods = [ 'DELETE' ], middleware = [ version_guard, session_guard ]),
WebSocketRoute('/stream', websocket_stream, middleware = [ version_guard, session_guard ]),
WebSocketRoute('/metrics', websocket_metrics, middleware = [ version_guard, session_guard ]),
WebSocketRoute('/ping', websocket_ping, middleware = [ version_guard, session_guard ])
]
api = Starlette(routes = routes)
api.add_middleware(CORSMiddleware, allow_origins = [ '*' ], allow_methods = [ '*' ], allow_headers = [ '*' ])
return api
+163
View File
@@ -0,0 +1,163 @@
import tempfile
from typing import Any, Dict, List, Optional
from starlette.datastructures import UploadFile
from starlette.requests import Request
from starlette.responses import FileResponse, JSONResponse, Response
from starlette.status import HTTP_200_OK, HTTP_201_CREATED, HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND
from facefusion import session_manager
from facefusion.apis import asset_store
from facefusion.apis.asset_helper import detect_media_type
from facefusion.apis.endpoints.session import extract_access_token
from facefusion.filesystem import get_file_extension, remove_file
from facefusion.types import AudioAsset, ImageAsset, VideoAsset
def translate_asset(asset : AudioAsset | ImageAsset | VideoAsset) -> Optional[Dict[str, Any]]:
return\
{
'id': asset.get('id'),
'created_at': asset.get('created_at').isoformat(),
'expires_at': asset.get('expires_at').isoformat(),
'type': asset.get('type'),
'media_type': asset.get('media'),
'filename': asset.get('name'),
'format': asset.get('format'),
'size': asset.get('size'),
'metadata': asset.get('metadata')
}
async def upload_asset(request : Request) -> Response:
access_token = extract_access_token(request.scope)
session_id = session_manager.find_session_id(access_token)
asset_type = request.query_params.get('type')
if session_id and asset_type in [ 'source', 'target' ]:
form = await request.form()
upload_files = form.getlist('file')
asset_paths = await save_asset_files(upload_files) # type: ignore[arg-type]
if asset_paths:
asset_ids : List[str] = []
for asset_path in asset_paths:
asset = asset_store.create_asset(session_id, asset_type, asset_path) # type: ignore[arg-type]
asset_id = asset.get('id')
if asset_id:
asset_ids.append(asset_id)
if asset_ids:
if asset_type == 'target':
return JSONResponse(
{
'asset_id': asset_ids[0]
}, status_code = HTTP_201_CREATED)
return JSONResponse(
{
'asset_ids': asset_ids
}, status_code = HTTP_201_CREATED)
return Response(status_code = HTTP_400_BAD_REQUEST)
async def save_asset_files(upload_files : List[UploadFile]) -> List[str]:
asset_paths : List[str] = []
for upload_file in upload_files:
upload_file_extension = get_file_extension(upload_file.filename)
with tempfile.NamedTemporaryFile(suffix = upload_file_extension, delete = False) as temp_file:
while upload_chunk := await upload_file.read(1024):
temp_file.write(upload_chunk)
temp_file.flush()
media_type = detect_media_type(temp_file.name)
if media_type:
asset_paths.append(temp_file.name)
else:
remove_file(temp_file.name)
return asset_paths
async def get_assets(request : Request) -> Response:
access_token = extract_access_token(request.scope)
session_id = session_manager.find_session_id(access_token)
asset_type = request.query_params.get('type')
if session_id:
asset_set = asset_store.get_assets(session_id)
assets = []
if asset_set:
for asset in asset_set.values():
if not asset_type or asset.get('type') == asset_type:
assets.append(translate_asset(asset))
return JSONResponse(
{
'assets': assets,
'count': len(assets)
}, status_code = HTTP_200_OK)
return Response(status_code = HTTP_400_BAD_REQUEST)
async def get_asset(request : Request) -> Response:
access_token = extract_access_token(request.scope)
session_id = session_manager.find_session_id(access_token)
asset_id = request.path_params.get('asset_id')
action = request.query_params.get('action')
if session_id and asset_id:
asset = asset_store.get_asset(session_id, asset_id)
if asset:
if action == 'download':
return FileResponse(asset.get('path'), filename = asset.get('name'))
return JSONResponse(translate_asset(asset), status_code = HTTP_200_OK)
return Response(status_code = HTTP_404_NOT_FOUND)
async def delete_asset(request : Request) -> Response:
access_token = extract_access_token(request.scope)
session_id = session_manager.find_session_id(access_token)
asset_id = request.path_params.get('asset_id')
if session_id and asset_id:
asset_set = asset_store.get_assets(session_id)
if asset_set and asset_id in asset_set:
remove_file(asset_set.get(asset_id).get('path'))
asset_store.delete_assets(session_id, [ asset_id ])
return Response(status_code = HTTP_200_OK)
return Response(status_code = HTTP_404_NOT_FOUND)
async def delete_assets(request : Request) -> Response:
access_token = extract_access_token(request.scope)
session_id = session_manager.find_session_id(access_token)
body = await request.json()
asset_ids = body.get('asset_ids')
if session_id and asset_ids:
asset_set = asset_store.get_assets(session_id)
if asset_set:
for asset_id in asset_ids:
if asset_id in asset_set:
remove_file(asset_set.get(asset_id).get('path'))
asset_store.delete_assets(session_id, asset_ids)
return Response(status_code = HTTP_200_OK)
return Response(status_code = HTTP_404_NOT_FOUND)
+16
View File
@@ -0,0 +1,16 @@
from starlette.websockets import WebSocket
from facefusion.apis.api_helper import get_sec_websocket_protocol
async def websocket_ping(websocket : WebSocket) -> None:
subprotocol = get_sec_websocket_protocol(websocket.scope)
await websocket.accept(subprotocol = subprotocol)
try:
while True:
await websocket.receive()
except Exception:
pass
+148
View File
@@ -0,0 +1,148 @@
import os
import secrets
from typing import Optional
from starlette.datastructures import Headers
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.status import HTTP_200_OK, HTTP_201_CREATED, HTTP_401_UNAUTHORIZED, HTTP_426_UPGRADE_REQUIRED
from starlette.types import ASGIApp, Receive, Scope, Send
from facefusion import session_context, session_manager, translator
from facefusion.apis.api_helper import get_sec_websocket_protocol
from facefusion.types import Token
async def create_session(request : Request) -> JSONResponse:
body = await request.json()
if not body.get('api_key') or body.get('api_key') == os.getenv('FACEFUSION_API_KEY'):
session_id = secrets.token_urlsafe(16)
session = session_manager.create_session()
session_context.set_session_id(session_id)
session_manager.set_session(session_id, session)
return JSONResponse(
{
'access_token': session.get('access_token'),
'refresh_token': session.get('refresh_token')
}, status_code = HTTP_201_CREATED)
return JSONResponse(
{
'message': translator.get('something_went_wrong', 'facefusion.apis')
}, status_code = HTTP_401_UNAUTHORIZED)
async def get_session(request : Request) -> JSONResponse:
access_token = extract_access_token(request.scope)
if access_token:
session_id = session_manager.find_session_id(access_token)
if session_id:
session = session_manager.get_session(session_id)
return JSONResponse(
{
'access_token': session.get('access_token'),
'refresh_token': session.get('refresh_token'),
'created_at': session.get('created_at').isoformat(),
'expires_at': session.get('expires_at').isoformat()
}, status_code = HTTP_200_OK)
return JSONResponse(
{
'message': translator.get('something_went_wrong', 'facefusion.apis')
}, status_code = HTTP_401_UNAUTHORIZED)
async def refresh_session(request : Request) -> JSONResponse:
body = await request.json()
for session_id, session in session_manager.SESSIONS.items():
if session.get('refresh_token') == body.get('refresh_token'):
__session__ = session_manager.create_session()
session_manager.set_session(session_id, __session__)
return JSONResponse(
{
'access_token': __session__.get('access_token'),
'refresh_token': __session__.get('refresh_token')
}, status_code = HTTP_200_OK)
return JSONResponse(
{
'message': translator.get('something_went_wrong', 'facefusion.apis')
}, status_code = HTTP_401_UNAUTHORIZED)
async def destroy_session(request : Request) -> JSONResponse:
access_token = extract_access_token(request.scope)
if access_token:
session_id = session_manager.find_session_id(access_token)
if session_id:
session_manager.clear_session(session_id)
return JSONResponse(
{
'message': translator.get('ok', 'facefusion.apis')
}, status_code = HTTP_200_OK)
return JSONResponse(
{
'message': translator.get('something_went_wrong', 'facefusion.apis')
}, status_code = HTTP_401_UNAUTHORIZED)
def create_session_guard(app : ASGIApp) -> ASGIApp:
async def middleware(scope : Scope, receive : Receive, send : Send) -> None:
access_token = extract_access_token(scope)
if access_token:
session_id = session_manager.find_session_id(access_token)
if session_id:
if session_manager.validate_session(session_id):
session_context.set_session_id(session_id)
return await app(scope, receive, send)
response = JSONResponse(
{
'message': translator.get('invalid_access_token', 'facefusion.apis')
}, status_code = HTTP_426_UPGRADE_REQUIRED)
return await response(scope, receive, send)
response = JSONResponse(
{
'message': translator.get('invalid_access_token', 'facefusion.apis')
}, status_code = HTTP_401_UNAUTHORIZED)
return await response(scope, receive, send)
return middleware
def extract_access_token(scope : Scope) -> Optional[Token]:
if scope.get('type') == 'http':
auth_header = Headers(scope = scope).get('Authorization')
if auth_header:
auth_prefix, _, access_token = auth_header.partition(' ')
if auth_prefix.lower() == 'bearer' and access_token:
return access_token
if scope.get('type') == 'websocket':
subprotocol = get_sec_websocket_protocol(scope)
if subprotocol:
protocol_prefix, _, access_token = subprotocol.partition('.')
if protocol_prefix == 'access_token' and access_token:
return access_token
return None
+80
View File
@@ -0,0 +1,80 @@
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.status import HTTP_200_OK, HTTP_404_NOT_FOUND
from facefusion import args_store, session_manager, state_manager, translator
from facefusion.apis import asset_store
from facefusion.apis.endpoints.session import extract_access_token
async def get_state(request : Request) -> JSONResponse:
api_args = args_store.filter_api_args(state_manager.get_state())
return JSONResponse(state_manager.collect_state(api_args), status_code = HTTP_200_OK)
async def set_state(request : Request) -> JSONResponse:
action = request.query_params.get('action')
asset_type = request.query_params.get('asset_type')
if action == 'select' and asset_type == 'source':
return await select_source(request)
if action == 'select' and asset_type == 'target':
return await select_target(request)
body = await request.json()
api_args = args_store.get_api_args()
for key, value in body.items():
if key in api_args:
state_manager.set_item(key, value)
__api_args__ = args_store.filter_api_args(state_manager.get_state())
return JSONResponse(state_manager.collect_state(__api_args__), status_code = HTTP_200_OK)
async def select_source(request : Request) -> JSONResponse:
body = await request.json()
asset_ids = body.get('asset_ids')
access_token = extract_access_token(request.scope)
session_id = session_manager.find_session_id(access_token)
if isinstance(asset_ids, list) and session_id:
source_paths = []
for asset_id in asset_ids:
asset = asset_store.get_asset(session_id, asset_id)
if asset:
source_paths.append(asset.get('path'))
state_manager.set_item('source_paths', source_paths)
__api_args__ = args_store.filter_api_args(state_manager.get_state())
return JSONResponse(state_manager.collect_state(__api_args__), status_code = HTTP_200_OK)
return JSONResponse(
{
'message': translator.get('source_asset_not_found', 'facefusion.apis')
}, status_code = HTTP_404_NOT_FOUND)
async def select_target(request : Request) -> JSONResponse:
body = await request.json()
asset_id = body.get('asset_id')
access_token = extract_access_token(request.scope)
session_id = session_manager.find_session_id(access_token)
if isinstance(asset_id, str) and session_id:
asset = asset_store.get_asset(session_id, asset_id)
if asset:
state_manager.set_item('target_path', asset.get('path'))
__api_args__ = args_store.filter_api_args(state_manager.get_state())
return JSONResponse(state_manager.collect_state(__api_args__), status_code = HTTP_200_OK)
return JSONResponse(
{
'message': translator.get('target_asset_not_found', 'facefusion.apis')
}, status_code = HTTP_404_NOT_FOUND)
+52
View File
@@ -0,0 +1,52 @@
from starlette.requests import Request
from starlette.responses import Response
from starlette.status import HTTP_200_OK, HTTP_201_CREATED, HTTP_404_NOT_FOUND
from starlette.websockets import WebSocket, WebSocketState
from facefusion import session_context, session_manager
from facefusion.apis.api_helper import get_sec_websocket_protocol
from facefusion.apis.endpoints.session import extract_access_token
from facefusion.apis.stream_manager import destroy_stream, process_image, process_video
async def websocket_stream(websocket : WebSocket) -> None:
subprotocol = get_sec_websocket_protocol(websocket.scope)
access_token = extract_access_token(websocket.scope)
session_id = session_manager.find_session_id(access_token)
session_context.set_session_id(session_id)
await websocket.accept(subprotocol = subprotocol)
await process_image(websocket)
if websocket.client_state == WebSocketState.CONNECTED:
await websocket.close()
async def post_stream(request : Request) -> Response:
headers =\
{
'Location': request.url_for('delete_stream').path
}
content_type = request.headers.get('content-type')
access_token = extract_access_token(request.scope)
session_id = session_manager.find_session_id(access_token)
session_context.set_session_id(session_id)
if session_id and content_type == 'application/sdp':
sdp_offer = await request.body()
sdp_answer = process_video(session_id, sdp_offer.decode())
if sdp_answer:
return Response(sdp_answer, status_code = HTTP_201_CREATED, media_type = 'application/sdp', headers = headers)
return Response(status_code = HTTP_404_NOT_FOUND)
async def delete_stream(request : Request) -> Response:
access_token = extract_access_token(request.scope)
session_id = session_manager.find_session_id(access_token)
if session_id and destroy_stream(session_id):
return Response(status_code = HTTP_200_OK)
return Response(status_code = HTTP_404_NOT_FOUND)
+14
View File
@@ -0,0 +1,14 @@
from facefusion.types import Locales
LOCALES : Locales =\
{
'en':
{
'ok': 'ok',
'something_went_wrong': 'something went wrong',
'invalid_access_token': 'invalid access token',
'invalid_refresh_token': 'invalid refresh token',
'source_asset_not_found': 'source asset not found',
'target_asset_not_found': 'target asset not found'
}
}
+12
View File
@@ -0,0 +1,12 @@
from facefusion.types import Locals
LOCALS : Locals =\
{
'en':
{
'ok': 'ok',
'something_went_wrong': 'something went wrong',
'invalid_access_token': 'invalid access token',
'invalid_refresh_token': 'invalid refresh token'
}
}
+76
View File
@@ -0,0 +1,76 @@
import asyncio
from functools import lru_cache
from typing import Any, Dict, Optional, cast
from starlette.datastructures import Headers
from starlette.websockets import WebSocket, WebSocketDisconnect
from facefusion import state_manager
from facefusion.execution import detect_execution_devices
from facefusion.system import get_cpu_info, get_disk_info, get_load_average, get_network_info
from facefusion.system import get_operating_system_info, get_python_info, get_ram_info, get_temperature_info
from facefusion.types import SystemInfo
@lru_cache(maxsize = 1)
def get_cached_static_system_info() -> Dict[str, Any]:
return\
{
'operating_system': get_operating_system_info(),
'python': get_python_info()
}
@lru_cache(maxsize = 1)
def get_cached_semi_static_system_info(temp_path : Optional[str]) -> Dict[str, Any]:
return\
{
'disk': get_disk_info(temp_path),
'network': get_network_info()
}
def get_optimized_system_info(temp_path : Optional[str] = None) -> SystemInfo:
static_data = get_cached_static_system_info()
semi_static_data = get_cached_semi_static_system_info(temp_path)
dynamic_data : Dict[str, Any] =\
{
'cpu': get_cpu_info(),
'ram': get_ram_info(),
'temperatures': get_temperature_info(),
'load_average': get_load_average()
}
return cast(SystemInfo, {**static_data, **semi_static_data, **dynamic_data})
async def websocket_metrics(websocket : WebSocket) -> None:
subprotocol = get_requested_subprotocol(websocket)
await websocket.accept(subprotocol = subprotocol)
try:
while True:
temp_path = state_manager.get_temp_path()
execution_devices = detect_execution_devices()
system_info = get_optimized_system_info(temp_path)
metrics =\
{
'devices': execution_devices,
'system': system_info
}
await websocket.send_json(metrics)
await asyncio.sleep(2)
except (WebSocketDisconnect, Exception):
pass
def get_requested_subprotocol(websocket : WebSocket) -> Optional[str]:
headers = Headers(scope = websocket.scope)
protocol_header = headers.get('Sec-WebSocket-Protocol')
if protocol_header:
protocol, _, _ = protocol_header.partition(',')
return protocol.strip()
return None
+384
View File
@@ -0,0 +1,384 @@
import os
import tempfile
from typing import Any, Dict, List
import httpx
import yt_dlp # type: ignore
from gallery_dl import config as gallery_config, extractor as gallery_extractor, job as gallery_job
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.status import HTTP_200_OK, HTTP_201_CREATED, HTTP_400_BAD_REQUEST, HTTP_500_INTERNAL_SERVER_ERROR
from facefusion import logger
from facefusion.apis import asset_store
from facefusion.choices import audio_formats
from facefusion.session_context import get_session_id
def resolve_image_urls(url : str) -> List[str]:
gallery_config.load()
image_urls : List[str] = []
try:
for extractor_instance in gallery_extractor.extractors():
if extractor_instance.pattern and extractor_instance.pattern.match(url):
logger.info(f'Detected gallery URL using extractor: {extractor_instance.__name__}', __name__)
extractor_obj = extractor_instance.from_url(url)
if extractor_obj:
for msg in extractor_obj:
if isinstance(msg, tuple) and len(msg) >= 2:
msg_type = msg[0]
if msg_type == 5:
image_data = msg[1]
image_url = image_data.get('url')
if image_url:
image_urls.append(image_url)
break
if not image_urls:
logger.info('Not a gallery URL, treating as direct image URL', __name__)
image_urls = [url]
except Exception as e:
logger.error(f'Failed to extract image URLs: {e}', __name__)
logger.info('Falling back to treating as direct image URL', __name__)
image_urls = [url]
return image_urls
def download_images_from_url(url : str, asset_type : str) -> List[str]:
gallery_config.load()
temp_dir = tempfile.gettempdir()
asset_ids : List[str] = []
is_gallery = False
for extractor_instance in gallery_extractor.extractors():
if extractor_instance.pattern and extractor_instance.pattern.match(url):
logger.info(f'Detected gallery URL using extractor: {extractor_instance.__name__}', __name__)
is_gallery = True
output_dir = os.path.join(temp_dir, f'facefusion_gallery_{os.urandom(8).hex()}')
os.makedirs(output_dir, exist_ok = True)
gallery_config.set((), 'base-directory', output_dir)
gallery_config.set((), 'skip', False)
gdl_job = gallery_job.DownloadJob(url)
gdl_job.run()
session_id = get_session_id()
for root, dirs, files in os.walk(output_dir):
for filename in files:
file_path = os.path.join(root, filename)
asset = asset_store.create_asset(session_id, asset_type, file_path)
if asset:
asset_ids.append(asset.get('id'))
logger.info(f'Registered image as asset {asset.get("id")}', __name__)
break
if not is_gallery:
logger.info('Not a gallery URL, treating as direct image URL', __name__)
with httpx.stream('GET', url, timeout = 30, follow_redirects = True) as response:
response.raise_for_status()
content_type = response.headers.get('content-type', '')
if not content_type.startswith('image/'):
raise ValueError(f'URL does not point to an image. Content-Type: {content_type}')
file_extension = None
if 'image/jpeg' in content_type or 'image/jpg' in content_type:
file_extension = '.jpg'
if 'image/png' in content_type:
file_extension = '.png'
if 'image/gif' in content_type:
file_extension = '.gif'
if 'image/webp' in content_type:
file_extension = '.webp'
if not file_extension:
url_path = url.split('?')[0]
if '.' in url_path:
file_extension = '.' + url_path.split('.')[-1].lower()
else:
file_extension = '.jpg'
filename = f'facefusion_image_{os.urandom(8).hex()}{file_extension}'
file_path = os.path.join(temp_dir, filename)
with open(file_path, 'wb') as f:
for chunk in response.iter_bytes(chunk_size = 8192):
f.write(chunk)
session_id = get_session_id()
asset = asset_store.create_asset(session_id, asset_type, file_path)
if asset:
asset_ids.append(asset.get('id'))
logger.info(f'Downloaded and registered image as asset {asset.get("id")}', __name__)
return asset_ids
def download_audio_from_url(url : str, asset_type : str) -> List[str]:
temp_dir = tempfile.gettempdir()
asset_ids : List[str] = []
# Extract file extension from URL
url_path = url.split('?')[0]
url_extension = os.path.splitext(url_path)[1].lstrip('.')
# Validate extension against supported audio formats
if url_extension not in audio_formats:
raise ValueError(f'Unsupported audio format: {url_extension}. Supported formats: {", ".join(audio_formats)}')
logger.info(f'Downloading audio from URL with extension: {url_extension}', __name__)
with httpx.stream('GET', url, timeout = 30, follow_redirects = True) as response:
response.raise_for_status()
filename = f'facefusion_audio_{os.urandom(8).hex()}.{url_extension}'
file_path = os.path.join(temp_dir, filename)
with open(file_path, 'wb') as f:
for chunk in response.iter_bytes(chunk_size = 8192):
f.write(chunk)
session_id = get_session_id()
asset = asset_store.create_asset(session_id, asset_type, file_path)
if asset:
asset_ids.append(asset.get('id'))
logger.info(f'Downloaded and registered audio as asset {asset.get("id")}', __name__)
return asset_ids
async def remote(request : Request) -> JSONResponse:
body = await request.json()
url = body.get('url')
action = request.query_params.get('action')
media_type = request.query_params.get('media_type', 'video')
asset_type = request.query_params.get('asset_type', 'target')
if not action:
return JSONResponse({'message': 'No action provided. Must be "resolve" or "download"'}, status_code = HTTP_400_BAD_REQUEST)
if action not in ['resolve', 'download']:
return JSONResponse({'message': 'Invalid action. Must be "resolve" or "download"'}, status_code = HTTP_400_BAD_REQUEST)
if media_type not in ['image', 'video', 'audio']:
return JSONResponse({'message': 'Invalid media_type. Must be "image", "video", or "audio"'}, status_code = HTTP_400_BAD_REQUEST)
if asset_type not in ['source', 'target']:
return JSONResponse({'message': 'Invalid asset_type. Must be "source" or "target"'}, status_code = HTTP_400_BAD_REQUEST)
if not url:
return JSONResponse({'message': 'No URL provided'}, status_code = HTTP_400_BAD_REQUEST)
if not isinstance(url, str):
return JSONResponse({'message': 'URL must be a string'}, status_code = HTTP_400_BAD_REQUEST)
url = url.strip()
if not url.startswith('http://') and not url.startswith('https://'):
return JSONResponse({'message': 'URL must start with http:// or https://'}, status_code = HTTP_400_BAD_REQUEST)
quality = body.get('quality', '720p')
if quality not in ['360p', '480p', '720p', '1080p']:
return JSONResponse({'message': 'Quality must be 360p, 480p, 720p, or 1080p'}, status_code = HTTP_400_BAD_REQUEST)
if action == 'resolve':
if media_type == 'image':
image_urls = resolve_image_urls(url)
logger.info(f'Resolved {len(image_urls)} image URL(s)', __name__)
response_data =\
{
'message': 'Image URL(s) resolved successfully',
'image_urls': image_urls,
'count': len(image_urls)
}
return JSONResponse(response_data, status_code = HTTP_200_OK)
quality_map =\
{
'360p': 'bestvideo[height<=360][ext=mp4]+bestaudio[ext=m4a]/best[height<=360]',
'480p': 'bestvideo[height<=480][ext=mp4]+bestaudio[ext=m4a]/best[height<=480]',
'720p': 'bestvideo[height<=720][ext=mp4]+bestaudio[ext=m4a]/best[height<=720]',
'1080p': 'bestvideo[height<=1080][ext=mp4]+bestaudio[ext=m4a]/best[height<=1080]'
}
ydl_opts : Dict[str, Any] =\
{
'format': quality_map[quality],
'quiet': True,
'no_warnings': True
}
logger.info(f'Extracting stream URL from {url} at {quality}', __name__)
try:
ydl = yt_dlp.YoutubeDL(ydl_opts)
info = ydl.extract_info(url, download = False)
except Exception as e:
logger.error(f'Failed to extract video information: {e}', __name__)
return JSONResponse({'message': f'Failed to extract video information: {str(e)}'}, status_code = HTTP_500_INTERNAL_SERVER_ERROR)
if not info:
logger.error('Failed to extract video information', __name__)
return JSONResponse({'message': 'Failed to extract video information'}, status_code = HTTP_500_INTERNAL_SERVER_ERROR)
stream_url = info.get('url')
if not stream_url:
if 'requested_formats' in info and len(info['requested_formats']) > 0:
stream_url = info['requested_formats'][0].get('url')
logger.info('Using URL from requested_formats (video track)', __name__)
elif 'formats' in info and len(info['formats']) > 0:
for fmt in reversed(info['formats']):
if fmt.get('url') and fmt.get('vcodec') != 'none':
stream_url = fmt['url']
logger.info(f'Using URL from format: {fmt.get("format_id")}', __name__)
break
if not stream_url:
logger.error('No stream URL found in any format', __name__)
logger.debug(f'Available keys in info: {list(info.keys())}', __name__)
return JSONResponse({'message': 'No stream URL found'}, status_code = HTTP_500_INTERNAL_SERVER_ERROR)
audio_url = None
if 'requested_formats' in info and len(info['requested_formats']) > 1:
audio_url = info['requested_formats'][1].get('url')
if audio_url:
logger.info('Found separate audio track URL', __name__)
duration = info.get('duration')
fps = info.get('fps')
width = info.get('width')
height = info.get('height')
total_frames = None
if duration and fps:
total_frames = int(duration * fps)
logger.info(f'Calculated total frames: {total_frames} ({duration}s * {fps} fps)', __name__)
logger.info('Stream URL extracted successfully', __name__)
response_data =\
{
'message': 'Stream URL resolved successfully',
'stream_url': stream_url,
'audio_url': audio_url,
'duration': duration,
'fps': fps,
'total_frames': total_frames,
'width': width,
'height': height
}
return JSONResponse(response_data, status_code = HTTP_200_OK)
if action == 'download':
if media_type == 'image':
try:
asset_ids = download_images_from_url(url, asset_type)
except ValueError as e:
return JSONResponse({'message': str(e)}, status_code = HTTP_400_BAD_REQUEST)
except Exception as e:
logger.error(f'Failed to download image(s): {e}', __name__)
return JSONResponse({'message': f'Failed to download image(s): {str(e)}'}, status_code = HTTP_500_INTERNAL_SERVER_ERROR)
response_data =\
{
'message': f'Downloaded and registered {len(asset_ids)} image(s)',
'asset_ids': asset_ids,
'count': len(asset_ids)
}
return JSONResponse(response_data, status_code = HTTP_201_CREATED)
if media_type == 'audio':
try:
asset_ids = download_audio_from_url(url, asset_type)
except ValueError as e:
return JSONResponse({'message': str(e)}, status_code = HTTP_400_BAD_REQUEST)
except Exception as e:
logger.error(f'Failed to download audio: {e}', __name__)
return JSONResponse({'message': f'Failed to download audio: {str(e)}'}, status_code = HTTP_500_INTERNAL_SERVER_ERROR)
response_data =\
{
'message': f'Downloaded and registered {len(asset_ids)} audio file(s)',
'asset_ids': asset_ids,
'count': len(asset_ids)
}
return JSONResponse(response_data, status_code = HTTP_201_CREATED)
quality_map =\
{
'360p': 'bestvideo[height<=360][ext=mp4]+bestaudio[ext=m4a]/best[height<=360][ext=mp4]/best[height<=360]',
'480p': 'bestvideo[height<=480][ext=mp4]+bestaudio[ext=m4a]/best[height<=480][ext=mp4]/best[height<=480]',
'720p': 'bestvideo[height<=720][ext=mp4]+bestaudio[ext=m4a]/best[height<=720][ext=mp4]/best[height<=720]',
'1080p': 'bestvideo[height<=1080][ext=mp4]+bestaudio[ext=m4a]/best[height<=1080][ext=mp4]/best[height<=1080]'
}
temp_dir = tempfile.gettempdir()
output_path = os.path.join(temp_dir, 'facefusion_remote_%(id)s.%(ext)s')
download_opts : Dict[str, Any] =\
{
'format': quality_map[quality],
'outtmpl': output_path,
'quiet': False,
'no_warnings': False
}
logger.info(f'Downloading video from {url} at {quality}', __name__)
ydl = yt_dlp.YoutubeDL(download_opts)
info = ydl.extract_info(url, download = True)
if not info:
logger.error('Failed to download video', __name__)
return JSONResponse({'message': 'Failed to download video'}, status_code = HTTP_500_INTERNAL_SERVER_ERROR)
downloaded_file = ydl.prepare_filename(info)
if not os.path.exists(downloaded_file):
logger.error(f'Downloaded file not found: {downloaded_file}', __name__)
return JSONResponse({'message': 'Downloaded file not found'}, status_code = HTTP_500_INTERNAL_SERVER_ERROR)
duration = info.get('duration')
fps = info.get('fps')
width = info.get('width')
height = info.get('height')
total_frames = None
if duration and fps:
total_frames = int(duration * fps)
logger.info(f'Calculated total frames: {total_frames} ({duration}s * {fps} fps)', __name__)
session_id = get_session_id()
asset = asset_store.create_asset(session_id, asset_type, downloaded_file)
asset_id = asset.get('id') if asset else None
logger.info(f'Video downloaded and registered as asset {asset_id}', __name__)
response_data =\
{
'message': 'Video downloaded and registered as asset',
'asset_id': asset_id,
'metadata':
{
'duration': duration,
'fps': fps,
'total_frames': total_frames,
'width': width,
'height': height
}
}
return JSONResponse(response_data, status_code = HTTP_201_CREATED)
return JSONResponse({'message': 'Invalid request'}, status_code = HTTP_400_BAD_REQUEST)
+71
View File
@@ -0,0 +1,71 @@
import ctypes
import time
from functools import partial
from queue import Queue
from typing import Optional, Tuple
import numpy
from facefusion import rtc
from facefusion.apis.stream_event import create_receive_event
from facefusion.codecs import opus_decoder, opus_encoder
from facefusion.types import AudioCodec, AudioFrame, OpusDecoder, RtcPeer, RtcPeerAudio
def run_audio_encode_loop(rtc_peer : RtcPeer, audio_queue : Queue[Tuple[float, AudioFrame]]) -> None:
temp_audio_time, temp_audio_frame = audio_queue.get()
audio_encoder = opus_encoder.create(48000, 2)
audio_timestamp = 0
while numpy.any(temp_audio_frame):
audio_frame_size = len(temp_audio_frame) // 2
audio_buffer = opus_encoder.encode(audio_encoder, temp_audio_frame.tobytes(), audio_frame_size)
if audio_buffer:
rtc.send_audio(rtc_peer, audio_buffer, audio_timestamp)
audio_timestamp += audio_frame_size
temp_audio_time, temp_audio_frame = audio_queue.get()
opus_encoder.destroy(audio_encoder)
def receive_audio_frames(rtc_peer_audio : RtcPeerAudio, audio_queue : Queue[Tuple[float, AudioFrame]]) -> None:
audio_track = rtc_peer_audio.get('receiver_track')
audio_codec = rtc_peer_audio.get('codec')
audio_decoder = create_audio_decoder(audio_codec)
audio_frame_handler = partial(handle_audio_frame, audio_codec, audio_decoder, audio_queue)
receive_event = create_receive_event(audio_track, audio_frame_handler)
receive_event.wait()
empty_audio_frame = numpy.empty(0)
audio_queue.put((0.0, empty_audio_frame))
destroy_audio_decoder(audio_codec, audio_decoder)
def decode_audio_frame(audio_codec : AudioCodec, audio_decoder : OpusDecoder, input_buffer : bytes) -> Optional[bytes]:
if audio_codec == 'opus':
return opus_decoder.decode(audio_decoder, input_buffer, 960, 2)
return None
def create_audio_decoder(audio_codec : AudioCodec) -> Optional[OpusDecoder]:
if audio_codec == 'opus':
return opus_decoder.create(48000, 2)
return None
def destroy_audio_decoder(audio_codec : AudioCodec, audio_decoder : OpusDecoder) -> None:
if audio_codec == 'opus':
opus_decoder.destroy(audio_decoder)
#todo: Alias Time for float
def handle_audio_frame(audio_codec : AudioCodec, audio_decoder : OpusDecoder, audio_queue : Queue[Tuple[float, AudioFrame]], track : int, data : ctypes.c_void_p, size : int, info : ctypes.c_void_p, pointer : ctypes.c_void_p) -> None:
audio_buffer = ctypes.string_at(data, size)
audio_frame = decode_audio_frame(audio_codec, audio_decoder, audio_buffer)
if audio_frame:
temp_audio_frame = numpy.frombuffer(audio_frame, dtype = numpy.float32)
audio_queue.put((time.monotonic(), temp_audio_frame))
+24
View File
@@ -0,0 +1,24 @@
import ctypes
import threading
from functools import partial
from facefusion.libraries import datachannel as datachannel_module
from facefusion.types import FrameHandler
def create_receive_event(track : int, frame_handler : FrameHandler) -> threading.Event:
datachannel_library = datachannel_module.create_static_library()
receive_event = threading.Event()
frame_callback = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p)(frame_handler)
close_callback = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_void_p)(partial(dispatch_event, receive_event))
datachannel_library.rtcSetFrameCallback(track, frame_callback)
datachannel_library.rtcSetClosedCallback(track, close_callback)
receive_event.frame_callback = frame_callback # type: ignore[attr-defined]
receive_event.close_callback = close_callback # type: ignore[attr-defined]
return receive_event
def dispatch_event(event : threading.Event, track : int, pointer : ctypes.c_void_p) -> None:
event.set()
+137
View File
@@ -0,0 +1,137 @@
import ctypes
import threading
from collections.abc import AsyncIterator
from concurrent.futures import Future, ThreadPoolExecutor
from queue import Queue
from typing import Optional, Tuple
import cv2
import numpy
from starlette.websockets import WebSocket
from facefusion import rtc, rtc_store, state_manager, streamer
from facefusion.apis.stream_audio import receive_audio_frames, run_audio_encode_loop
from facefusion.apis.stream_video import receive_video_frames, run_video_encode_loop
from facefusion.libraries import datachannel as datachannel_module
from facefusion.types import AudioCodec, AudioFrame, PeerConnection, Resolution, RtcPeer, RtcPeerAudio, SdpAnswer, SdpOffer, SessionId, VideoCodec, VisionFrame
async def process_image(websocket : WebSocket) -> None:
capture_vision_frame = await anext(receive_vision_frames(websocket), None)
if numpy.any(capture_vision_frame):
output_vision_frame = streamer.process_stream_frame(capture_vision_frame)
is_success, output_frame_buffer = cv2.imencode('.jpg', output_vision_frame)
if is_success:
await websocket.send_bytes(output_frame_buffer.tobytes())
async def receive_vision_frames(websocket : WebSocket) -> AsyncIterator[VisionFrame]:
websocket_event = await websocket.receive()
while websocket_event.get('type') == 'websocket.receive':
frame_buffer = websocket_event.get('bytes') or bytes()
vision_frame = cv2.imdecode(numpy.frombuffer(frame_buffer, numpy.uint8), cv2.IMREAD_COLOR)
if numpy.any(vision_frame):
yield vision_frame
websocket_event = await websocket.receive()
def process_video(session_id : SessionId, sdp_offer : SdpOffer) -> Optional[SdpAnswer]:
video_codec : VideoCodec = 'vp8'
if rtc.get_payload_type(sdp_offer, 'vp9'):
video_codec = 'vp9'
if rtc.get_payload_type(sdp_offer, 'av1'):
video_codec = 'av1'
video_payload_type = rtc.get_payload_type(sdp_offer, video_codec)
if video_payload_type:
peer_connection : PeerConnection = rtc.create_peer_connection()
video_receiver_track = rtc.add_video_track(peer_connection, 'recvonly', video_codec, video_payload_type)
video_sender_track = rtc.add_video_track(peer_connection, 'sendonly', video_codec, video_payload_type)
sender_bitrate = ctypes.c_uint(0)
receiver_bitrate = ctypes.c_uint(8000)
rtc.wire_sender_bitrate(video_sender_track, sender_bitrate)
audio_codec : AudioCodec = 'opus'
audio_payload_type = rtc.get_payload_type(sdp_offer, audio_codec)
if audio_payload_type:
audio_receiver_track = rtc.add_audio_track(peer_connection, 'recvonly', audio_codec, audio_payload_type)
audio_sender_track = rtc.add_audio_track(peer_connection, 'sendonly', audio_codec, audio_payload_type)
rtc.set_remote_description(peer_connection, sdp_offer)
sdp_answer = rtc.create_sdp_answer(peer_connection)
if sdp_answer:
rtc_peer : RtcPeer =\
{
'peer_connection': peer_connection,
'video':
{
'sender_track': video_sender_track,
'receiver_track': video_receiver_track,
'codec': video_codec
},
'sender_bitrate': sender_bitrate,
'receiver_bitrate': receiver_bitrate
}
if audio_payload_type:
rtc_peer['audio'] = RtcPeerAudio(
sender_track = audio_sender_track,
receiver_track = audio_receiver_track,
codec = audio_codec
)
rtc_store.init_peers(session_id)
rtc_store.get_peers(session_id).append(rtc_peer)
threading.Thread(target = run_peer_loop, args = (session_id, rtc_peer), daemon = True).start()
return sdp_answer
datachannel_module.create_static_library().rtcDeletePeerConnection(peer_connection)
return None
def run_peer_loop(session_id : SessionId, rtc_peer : RtcPeer) -> None:
execution_thread_count = state_manager.get_item('execution_thread_count')
#todo: is bytes, Resolution not a XXXPointer type
video_queue : Queue[Tuple[float, Future[Tuple[bytes, Resolution]]]] = Queue(maxsize = execution_thread_count)
audio_queue : Queue[Tuple[float, AudioFrame]] = Queue(maxsize = execution_thread_count * 10)
video_executor = ThreadPoolExecutor(max_workers = execution_thread_count)
video_receiver_thread = threading.Thread(target = receive_video_frames, args = (rtc_peer.get('video'), video_queue, video_executor), daemon = True)
video_encoder_thread = threading.Thread(target = run_video_encode_loop, args = (rtc_peer, video_queue), daemon = True)
video_receiver_thread.start()
video_encoder_thread.start()
if rtc_peer.get('audio'):
audio_receiver_thread = threading.Thread(target = receive_audio_frames, args = (rtc_peer.get('audio'), audio_queue), daemon = True)
audio_encoder_thread = threading.Thread(target = run_audio_encode_loop, args = (rtc_peer, audio_queue), daemon = True)
audio_receiver_thread.start()
audio_encoder_thread.start()
audio_receiver_thread.join()
audio_encoder_thread.join()
video_receiver_thread.join()
video_encoder_thread.join()
video_executor.shutdown(wait = True)
rtc_store.delete_peers(session_id)
def destroy_stream(session_id : SessionId) -> bool:
if rtc_store.has_peers(session_id):
rtc_store.delete_peers(session_id)
return not rtc_store.has_peers(session_id)
return False
+204
View File
@@ -0,0 +1,204 @@
import ctypes
import time
from concurrent.futures import Future, ThreadPoolExecutor
from functools import partial
from queue import Queue
from typing import Optional, Tuple
import cv2
import numpy
from facefusion import rtc, streamer
from facefusion.apis.stream_event import create_receive_event
from facefusion.codecs import aom_decoder, aom_encoder, vpx_decoder, vpx_encoder
from facefusion.types import AomDecoder, AomEncoder, AomPointer, BitRate, Resolution, RtcPeer, RtcPeerVideo, VideoCodec, VisionFrame, VpxDecoder, VpxEncoder, VpxPointer
def run_video_encode_loop(rtc_peer : RtcPeer, video_queue : Queue[Tuple[float, Future[Tuple[bytes, Resolution]]]]) -> None:
video_codec = rtc_peer.get('video').get('codec')
video_time, video_future = video_queue.get()
video_buffer, video_resolution = video_future.result()
if video_buffer:
temp_resolution : Resolution = video_resolution
temp_bitrate : BitRate = 8000
video_encoder = create_video_encoder(video_codec, temp_resolution, temp_bitrate)
temp_video_time = video_time
frame_index = 0
while video_buffer:
encode_start = time.monotonic()
sender_bitrate = calculate_sender_bitrate(rtc_peer, temp_bitrate)
if video_resolution[0] - temp_resolution[0] or video_resolution[1] - temp_resolution[1]:
temp_resolution = video_resolution
update_video_encoder_resolution(video_codec, video_encoder, temp_resolution)
if sender_bitrate - temp_bitrate:
temp_bitrate = sender_bitrate
update_video_encoder_bitrate(video_codec, video_encoder, temp_bitrate)
__video_buffer__ = encode_video_frame(video_codec, video_encoder, video_buffer, temp_resolution, frame_index)
if __video_buffer__:
video_timestamp = int(video_time * 90000)
rtc.send_video(rtc_peer, __video_buffer__, video_timestamp)
encode_time = time.monotonic() - encode_start
frame_interval = video_time - temp_video_time
temp_video_time = video_time
receiver_bitrate = calculate_receiver_bitrate(rtc_peer, encode_time, frame_interval)
rtc.adapt_receiver_bitrate(rtc_peer, receiver_bitrate)
frame_index += 1
video_time, video_future = video_queue.get()
video_buffer, video_resolution = video_future.result()
destroy_video_encoder(video_codec, video_encoder)
rtc.clear_bitrate(rtc_peer)
def receive_video_frames(rtc_peer_video : RtcPeerVideo, video_queue : Queue[Tuple[float, Future[Tuple[bytes, Resolution]]]], video_executor : ThreadPoolExecutor) -> None:
video_track = rtc_peer_video.get('receiver_track')
video_codec = rtc_peer_video.get('codec')
video_decoder = create_video_decoder(video_codec)
video_frame_handler = partial(handle_video_frame, video_codec, video_decoder, video_queue, video_executor)
receive_event = create_receive_event(video_track, video_frame_handler)
receive_event.wait()
empty_future : Future[Tuple[bytes, Resolution]] = Future()
empty_future.set_result((bytes(), (0, 0)))
video_queue.put((0.0, empty_future))
destroy_video_decoder(video_codec, video_decoder)
def process_video_frame(input_vision_frame : VisionFrame) -> Tuple[bytes, Resolution]:
output_vision_frame = streamer.process_stream_frame(input_vision_frame)
output_resolution : Resolution = (output_vision_frame.shape[1], output_vision_frame.shape[0])
output_buffer = cv2.cvtColor(output_vision_frame, cv2.COLOR_BGR2YUV_I420).tobytes()
return output_buffer, output_resolution
def calculate_receiver_bitrate(rtc_peer : RtcPeer, encode_time : float, frame_interval : float) -> BitRate:
min_bitrate : BitRate = 500
max_bitrate : BitRate = 8000
bitrate : BitRate = rtc_peer.get('receiver_bitrate').value
if frame_interval > 0:
scale = frame_interval / encode_time
bitrate = int(bitrate * scale)
bitrate = max(min_bitrate, min(max_bitrate, bitrate))
return bitrate
#todo: does not feel final as this is an clamp and not calculate
def calculate_sender_bitrate(rtc_peer : RtcPeer, bitrate : BitRate) -> BitRate:
min_bitrate : BitRate = 500
max_bitrate : BitRate = 8000
peer_bitrate : BitRate = rtc_peer.get('sender_bitrate').value
if peer_bitrate > 0:
bitrate = max(min_bitrate, min(max_bitrate, peer_bitrate))
return bitrate
def decode_video_frame(video_codec : VideoCodec, video_decoder : VpxDecoder | AomDecoder, input_buffer : bytes) -> Optional[VisionFrame]:
if video_codec == 'av1':
aom_pointer = aom_decoder.decode(video_decoder, input_buffer)
if aom_pointer:
return normalize_vision_frame(aom_pointer)
if video_codec in [ 'vp8', 'vp9' ]:
vpx_pointer = vpx_decoder.decode(video_decoder, input_buffer)
if vpx_pointer:
return normalize_vision_frame(vpx_pointer)
return None
def encode_video_frame(video_codec : VideoCodec, video_encoder : VpxEncoder | AomEncoder, input_buffer : bytes, frame_resolution : Resolution, frame_index : int) -> bytes:
if video_codec == 'av1':
return aom_encoder.encode(video_encoder, input_buffer, frame_resolution, frame_index)
if video_codec in [ 'vp8', 'vp9' ]:
return vpx_encoder.encode(video_encoder, input_buffer, frame_resolution, frame_index)
return bytes()
def normalize_vision_frame(frame_pointer : AomPointer | VpxPointer) -> VisionFrame:
frame_width, frame_height = frame_pointer.get('resolution')
vision_frame = numpy.frombuffer(frame_pointer.get('buffer'), dtype = numpy.uint8).reshape((frame_height * 3 // 2, frame_width))
return cv2.cvtColor(vision_frame, cv2.COLOR_YUV2BGR_I420)
def create_video_decoder(video_codec : VideoCodec) -> Optional[VpxDecoder | AomDecoder]:
if video_codec == 'av1':
return aom_decoder.create(8)
if video_codec in [ 'vp8', 'vp9' ]:
return vpx_decoder.create(video_codec, 8)
return None
def create_video_encoder(video_codec : VideoCodec, frame_resolution : Resolution, bitrate : BitRate) -> Optional[VpxEncoder | AomEncoder]:
if video_codec == 'av1':
return aom_encoder.create(frame_resolution, bitrate, 8, 10)
if video_codec in [ 'vp8', 'vp9' ]:
return vpx_encoder.create(video_codec, frame_resolution, bitrate, 8, 10)
return None
def destroy_video_decoder(video_codec : VideoCodec, video_decoder : VpxDecoder | AomDecoder) -> None:
if video_codec == 'av1':
aom_decoder.destroy(video_decoder)
if video_codec in [ 'vp8', 'vp9' ]:
vpx_decoder.destroy(video_decoder)
def destroy_video_encoder(video_codec : VideoCodec, video_encoder : VpxEncoder | AomEncoder) -> None:
if video_codec == 'av1':
aom_encoder.destroy(video_encoder)
if video_codec in [ 'vp8', 'vp9' ]:
vpx_encoder.destroy(video_encoder)
def update_video_encoder_resolution(video_codec : VideoCodec, video_encoder : VpxEncoder | AomEncoder, frame_resolution : Resolution) -> bool:
if video_codec == 'av1':
return aom_encoder.update_resolution(video_encoder, frame_resolution)
if video_codec in [ 'vp8', 'vp9' ]:
return vpx_encoder.update_resolution(video_encoder, frame_resolution)
return False
def update_video_encoder_bitrate(video_codec : VideoCodec, video_encoder : VpxEncoder | AomEncoder, bitrate : BitRate) -> bool:
if video_codec == 'av1':
return aom_encoder.update_bitrate(video_encoder, bitrate)
if video_codec in [ 'vp8', 'vp9' ]:
return vpx_encoder.update_bitrate(video_encoder, bitrate)
return False
#todo: we can remove the dead args or pass audio buffer
def handle_video_frame(video_codec : VideoCodec, video_decoder : VpxDecoder | AomDecoder, video_queue : Queue[Tuple[float, Future[Tuple[bytes, Resolution]]]], video_executor : ThreadPoolExecutor, track : int, data : ctypes.c_void_p, size : int, info : ctypes.c_void_p, pointer : ctypes.c_void_p) -> None:
video_buffer = ctypes.string_at(data, size)
vision_frame = decode_video_frame(video_codec, video_decoder, video_buffer)
if numpy.any(vision_frame) and video_queue.qsize() < video_queue.maxsize:
video_future = video_executor.submit(process_video_frame, vision_frame)
video_queue.put((time.monotonic(), video_future))
+207
View File
@@ -0,0 +1,207 @@
import base64
import subprocess
from typing import List, Optional
import cv2
import numpy
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.status import HTTP_200_OK, HTTP_400_BAD_REQUEST
from facefusion import logger
from facefusion.apis import asset_store
from facefusion.filesystem import is_video
from facefusion.video_manager import get_video_capture
from facefusion.vision import fit_contain_frame
def extract_frame_at_timestamp(stream_url : str, timestamp : float, width : int, height : int) -> Optional[numpy.ndarray]:
ffmpeg_command =\
[
'ffmpeg',
'-user_agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'-ss', str(timestamp),
'-i', stream_url,
'-vf', f'scale={width}:{height}',
'-frames:v', '1',
'-f', 'rawvideo',
'-pix_fmt', 'bgr24',
'-'
]
try:
result = subprocess.run(ffmpeg_command, capture_output = True, timeout = 10)
if result.returncode == 0 and result.stdout:
frame_size = width * height * 3
if len(result.stdout) >= frame_size:
frame = numpy.frombuffer(result.stdout[:frame_size], dtype = numpy.uint8).reshape((height, width, 3))
return frame
except Exception as e:
logger.debug(f'Failed to extract frame at {timestamp}s: {e}', __name__)
return None
async def get_timeline(request: Request) -> JSONResponse:
"""
Return N preview frames (as base64 JPEGs) from the target video,
resized to specified resolution for timeline preview.
Route: /timeline/{count:int}?target_path=...&is_remote_stream=true&duration=120&fps=30&target_width=1920&target_height=1080&width=160&height=120
"""
# Extract and validate requested count
try:
count = int(request.path_params.get('count', 0))
except (TypeError, ValueError):
return JSONResponse({'message': 'Invalid count parameter'}, status_code=HTTP_400_BAD_REQUEST)
if count <= 0:
return JSONResponse({'message': 'Count must be a positive integer'}, status_code=HTTP_400_BAD_REQUEST)
# Extract and validate preview resolution parameters
try:
preview_width = int(request.query_params.get('width', 160))
preview_height = int(request.query_params.get('height', 120))
except (TypeError, ValueError):
return JSONResponse({'message': 'Invalid width or height parameter'}, status_code=HTTP_400_BAD_REQUEST)
if preview_width <= 0 or preview_height <= 0 or preview_width > 1920 or preview_height > 1080:
return JSONResponse({'message': 'Width and height must be between 1 and 1920x1080'}, status_code=HTTP_400_BAD_REQUEST)
# Extract target_path or asset_id (one is required)
target_path = request.query_params.get('target_path')
asset_id = request.query_params.get('asset_id')
# Extract is_remote_stream flag
is_remote_stream_param = request.query_params.get('is_remote_stream', 'false').lower()
is_remote_stream = is_remote_stream_param in ['true', '1', 'yes']
# Resolve asset_id to path if provided (for local files)
if asset_id and not target_path:
from facefusion.session_context import get_session_id
session_id = get_session_id()
asset = asset_store.get_asset(session_id, asset_id)
if not asset:
return JSONResponse({'message': f'Asset not found: {asset_id}'}, status_code=HTTP_400_BAD_REQUEST)
target_path = asset.get('path')
if not target_path:
return JSONResponse({'message': 'Asset has no path'}, status_code=HTTP_400_BAD_REQUEST)
is_remote_stream = False # Assets are always local files
logger.debug(f'Resolved asset_id {asset_id} to path for timeline preview', __name__)
# Now check if we have a target_path
if not target_path:
return JSONResponse({'message': 'Missing required parameter: either target_path or asset_id'}, status_code=HTTP_400_BAD_REQUEST)
# Extract video metadata (optional for local files, required for remote streams)
duration = None
fps = None
width = 1280
height = 720
if request.query_params.get('duration'):
try:
duration = float(request.query_params.get('duration'))
except (TypeError, ValueError):
return JSONResponse({'message': 'Invalid duration parameter'}, status_code=HTTP_400_BAD_REQUEST)
if request.query_params.get('fps'):
try:
fps = float(request.query_params.get('fps'))
except (TypeError, ValueError):
return JSONResponse({'message': 'Invalid fps parameter'}, status_code=HTTP_400_BAD_REQUEST)
if request.query_params.get('target_width'):
try:
width = int(request.query_params.get('target_width'))
except (TypeError, ValueError):
return JSONResponse({'message': 'Invalid target_width parameter'}, status_code=HTTP_400_BAD_REQUEST)
if request.query_params.get('target_height'):
try:
height = int(request.query_params.get('target_height'))
except (TypeError, ValueError):
return JSONResponse({'message': 'Invalid target_height parameter'}, status_code=HTTP_400_BAD_REQUEST)
previews: List[str] = []
if is_remote_stream:
if not duration or duration <= 0:
return JSONResponse({'message': 'Duration not available for remote stream'}, status_code=HTTP_400_BAD_REQUEST)
frame_total = 0
if duration and fps:
try:
frame_total = int(float(duration) * float(fps))
except Exception:
frame_total = 0
sample_count = min(count, frame_total) if frame_total > 0 else count
timestamps = list(numpy.linspace(0, float(duration), num=sample_count, endpoint=False))
logger.info(f'Extracting {sample_count} frames from remote stream using ffmpeg', __name__)
for timestamp in timestamps:
frame = extract_frame_at_timestamp(target_path, timestamp, width, height)
if frame is None:
logger.warn(f'Failed to extract frame at {timestamp}s', __name__)
continue
thumb_bgr = fit_contain_frame(frame, (preview_width, preview_height))
if thumb_bgr.shape[1] != preview_width or thumb_bgr.shape[0] != preview_height:
thumb_bgr = cv2.resize(thumb_bgr, (preview_width, preview_height))
ok_enc, buf = cv2.imencode('.jpg', thumb_bgr, [cv2.IMWRITE_JPEG_QUALITY, 50])
if not ok_enc:
logger.warn(f'JPEG encode failed for timestamp {timestamp}s', __name__)
continue
b64 = base64.b64encode(buf.tobytes()).decode('ascii')
previews.append(b64)
else:
video_capture = get_video_capture(target_path)
if not video_capture or not video_capture.isOpened():
logger.error(f'Unable to open video capture for target: {target_path}', __name__)
return JSONResponse({'message': 'Unable to open target video'}, status_code=HTTP_400_BAD_REQUEST)
frame_total = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
if frame_total <= 0 and is_video(target_path):
return JSONResponse({'message': 'Could not determine frame count for target video'}, status_code=HTTP_400_BAD_REQUEST)
sample_count = min(count, frame_total)
indices: List[int] = list(numpy.linspace(1, frame_total, num=sample_count, endpoint=True, dtype=int))
for frame_number in indices:
video_capture.set(cv2.CAP_PROP_POS_FRAMES, max(0, frame_number - 1))
ok_read, frame = video_capture.read()
if not ok_read or frame is None:
logger.warn(f'Failed reading frame {frame_number}', __name__)
continue
thumb_bgr = fit_contain_frame(frame, (preview_width, preview_height))
if thumb_bgr.shape[1] != preview_width or thumb_bgr.shape[0] != preview_height:
thumb_bgr = cv2.resize(thumb_bgr, (preview_width, preview_height))
ok_enc, buf = cv2.imencode('.jpg', thumb_bgr, [cv2.IMWRITE_JPEG_QUALITY, 50])
if not ok_enc:
logger.warn(f'JPEG encode failed for frame {frame_number}', __name__)
continue
b64 = base64.b64encode(buf.tobytes()).decode('ascii')
previews.append(b64)
logger.info(f'Returned {len(previews)}/{sample_count} timeline frames at {preview_width}x{preview_height}', __name__)
return JSONResponse({
'message': 'ok',
'count': len(previews),
'requested': count,
'width': preview_width,
'height': preview_height,
'format': 'jpeg',
'frames': previews
}, status_code=HTTP_200_OK)
+98
View File
@@ -0,0 +1,98 @@
import subprocess
from functools import lru_cache
from typing import Optional
from starlette.datastructures import Headers
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.types import ASGIApp, Receive, Scope, Send
from starlette.websockets import WebSocket
@lru_cache(maxsize = 1)
def get_api_version() -> str:
try:
result = subprocess.run(['git', 'rev-parse', 'HEAD'], capture_output = True, text = True, check = True)
return result.stdout.strip()
except Exception:
return 'unknown'
def check_version_match(request : Request) -> Optional[JSONResponse]:
client_version = request.headers.get('X-API-Version')
server_version = get_api_version()
if not client_version:
return JSONResponse({'error': 'Missing X-API-Version header', 'server_version': server_version}, status_code = 400)
if client_version != server_version:
return JSONResponse({'error': 'Version mismatch', 'client_version': client_version, 'server_version': server_version}, status_code = 409)
return None
def check_version_match_websocket(websocket : WebSocket) -> Optional[str]:
client_version = websocket.headers.get('X-API-Version')
server_version = get_api_version()
if not client_version:
return f'Missing X-API-Version header, server version: {server_version}'
if client_version != server_version:
return f'Version mismatch: client={client_version}, server={server_version}'
return None
async def version_guard_middleware(scope : Scope, receive : Receive, send : Send, app : ASGIApp) -> None:
if scope['type'] == 'http':
# Skip version check for OPTIONS requests (CORS preflight)
if scope.get('method') == 'OPTIONS':
await app(scope, receive, send)
return
headers = Headers(scope = scope)
client_version = headers.get('X-API-Version')
server_version = get_api_version()
if not client_version:
response = JSONResponse({'error': 'Missing X-API-Version header', 'server_version': server_version}, status_code = 400)
await response(scope, receive, send)
return
if client_version != server_version:
response = JSONResponse({'error': 'Version mismatch', 'client_version': client_version, 'server_version': server_version}, status_code = 409)
await response(scope, receive, send)
return
if scope['type'] == 'websocket':
headers = Headers(scope = scope)
client_version = headers.get('X-API-Version')
# For WebSocket connections, also check subprotocols since browsers can't set custom headers
if not client_version:
protocol_header = headers.get('Sec-WebSocket-Protocol')
if protocol_header:
# Parse subprotocols to find api_version
protocols = [p.strip() for p in protocol_header.split(',')]
for protocol in protocols:
if protocol.startswith('api_version.'):
client_version = protocol.split('.', 1)[1]
break
server_version = get_api_version()
if not client_version or client_version != server_version:
websocket = WebSocket(scope, receive = receive, send = send)
reason = f'Missing X-API-Version header, server version: {server_version}' if not client_version else f'Version mismatch: client={client_version}, server={server_version}'
await websocket.close(code = 1008, reason = reason)
return
await app(scope, receive, send)
def create_version_guard(app : ASGIApp) -> ASGIApp:
async def version_guard_app(scope : Scope, receive : Receive, send : Send) -> None:
await version_guard_middleware(scope, receive, send, app)
return version_guard_app
+2 -2
View File
@@ -10,7 +10,7 @@ def detect_app_context() -> AppContext:
while frame:
if os.path.join('facefusion', 'jobs') in frame.f_code.co_filename:
return 'cli'
if os.path.join('facefusion', 'uis') in frame.f_code.co_filename:
return 'ui'
if os.path.join('facefusion', 'apis') in frame.f_code.co_filename:
return 'api'
frame = frame.f_back
return 'cli'
@@ -1,47 +1,15 @@
from facefusion import state_manager
from facefusion.filesystem import get_file_name, is_video, resolve_file_paths
from facefusion.jobs import job_store
from facefusion.normalizer import normalize_fps, normalize_space
from facefusion.processors.core import get_processors_modules
from facefusion.types import ApplyStateItem, Args
from facefusion.vision import detect_video_fps
def reduce_step_args(args : Args) -> Args:
step_args =\
{
key: args[key] for key in args if key in job_store.get_step_keys()
}
return step_args
def reduce_job_args(args : Args) -> Args:
job_args =\
{
key: args[key] for key in args if key in job_store.get_job_keys()
}
return job_args
def collect_step_args() -> Args:
step_args =\
{
key: state_manager.get_item(key) for key in job_store.get_step_keys() #type:ignore[arg-type]
}
return step_args
def collect_job_args() -> Args:
job_args =\
{
key: state_manager.get_item(key) for key in job_store.get_job_keys() #type:ignore[arg-type]
}
return job_args
def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
# general
apply_state_item('command', args.get('command'))
# workflow
apply_state_item('workflow', args.get('workflow'))
# paths
apply_state_item('temp_path', args.get('temp_path'))
apply_state_item('jobs_path', args.get('jobs_path'))
@@ -85,7 +53,6 @@ def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
apply_state_item('trim_frame_start', args.get('trim_frame_start'))
apply_state_item('trim_frame_end', args.get('trim_frame_end'))
apply_state_item('temp_frame_format', args.get('temp_frame_format'))
apply_state_item('keep_temp', args.get('keep_temp'))
# output creation
apply_state_item('output_image_quality', args.get('output_image_quality'))
apply_state_item('output_image_scale', args.get('output_image_scale'))
@@ -104,10 +71,6 @@ def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
apply_state_item('processors', args.get('processors'))
for processor_module in get_processors_modules(available_processors):
processor_module.apply_args(args, apply_state_item)
# uis
apply_state_item('open_browser', args.get('open_browser'))
apply_state_item('ui_layouts', args.get('ui_layouts'))
apply_state_item('ui_workflow', args.get('ui_workflow'))
# execution
apply_state_item('execution_device_ids', args.get('execution_device_ids'))
apply_state_item('execution_providers', args.get('execution_providers'))
@@ -119,9 +82,11 @@ def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
apply_state_item('benchmark_mode', args.get('benchmark_mode'))
apply_state_item('benchmark_resolutions', args.get('benchmark_resolutions'))
apply_state_item('benchmark_cycle_count', args.get('benchmark_cycle_count'))
# api
apply_state_item('api_host', args.get('api_host'))
apply_state_item('api_port', args.get('api_port'))
# memory
apply_state_item('video_memory_strategy', args.get('video_memory_strategy'))
apply_state_item('system_memory_limit', args.get('system_memory_limit'))
# misc
apply_state_item('log_level', args.get('log_level'))
apply_state_item('halt_on_error', args.get('halt_on_error'))
+66
View File
@@ -0,0 +1,66 @@
from typing import List
from facefusion.types import Args, ArgsStore, Scope
ARGS_STORE : ArgsStore =\
{
'api': [],
'cli': [],
'sys': []
}
def get_api_args() -> List[str]:
return ARGS_STORE.get('api')
def get_sys_args() -> List[str]:
return ARGS_STORE.get('sys')
def get_cli_args() -> List[str]:
return ARGS_STORE.get('cli')
def register_args(keys : List[str], scopes : List[Scope]) -> None:
for key in keys:
for scope in scopes:
if scope == 'api':
ARGS_STORE['api'].append(key)
if scope == 'cli':
ARGS_STORE['cli'].append(key)
if scope == 'sys':
ARGS_STORE['sys'].append(key)
def filter_api_args(args : Args) -> Args:
api_args =\
{
key: args.get(key) for key in args if key in get_api_args() #type:ignore[literal-required]
}
return api_args
def filter_sys_args(args : Args) -> Args:
sys_args =\
{
key: args.get(key) for key in args if key in get_sys_args() #type:ignore[literal-required]
}
return sys_args
def filter_cli_args(args : Args) -> Args:
cli_args =\
{
key: args.get(key) for key in args if key in get_cli_args() #type:ignore[literal-required]
}
return cli_args
def filter_step_args(args : Args) -> Args:
step_args =\
{
key: args.get(key) for key in args if key in get_cli_args() and key not in get_sys_args() #type:ignore[literal-required]
}
return step_args
+111
View File
@@ -0,0 +1,111 @@
import os
import uuid
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional, TypeAlias
from facefusion import filesystem, state_manager
from facefusion.session_context import get_session_id
AssetRegistry : TypeAlias = Dict[str, Dict[str, Any]]
def get_asset_registry() -> AssetRegistry:
registry = state_manager.get_item('asset_registry')
if not registry:
registry = {}
state_manager.set_item('asset_registry', registry)
return registry
def register(asset_type : str, file_path : str, filename : str = None, metadata : Optional[Dict[str, Any]] = None) -> str:
if asset_type not in ['source', 'target', 'output']:
raise ValueError(f"Invalid asset_type: {asset_type}. Must be 'source', 'target', or 'output'")
asset_id = str(uuid.uuid4())
session_id = get_session_id()
if not session_id:
raise ValueError("No active session - cannot register asset without session_id")
if not filename:
filename = os.path.basename(file_path)
file_size = os.path.getsize(file_path)
file_format = filesystem.get_file_format(file_path)
media_type = None
if filesystem.is_image(file_path):
media_type = 'image'
if filesystem.is_video(file_path):
media_type = 'video'
if filesystem.is_audio(file_path):
media_type = 'audio'
asset_data =\
{
'id': asset_id,
'session_id': session_id,
'type': asset_type,
'media_type': media_type,
'format': file_format,
'path': file_path,
'filename': filename,
'size': file_size,
'created_at': datetime.now(timezone.utc).isoformat()
}
if metadata:
asset_data['metadata'] = metadata
registry = get_asset_registry()
registry[asset_id] = asset_data
state_manager.set_item('asset_registry', registry)
return asset_id
def get_asset(asset_id : str) -> Optional[Dict[str, Any]]:
registry = get_asset_registry()
return registry.get(asset_id)
def list_assets(asset_type : Optional[str] = None) -> List[Dict[str, Any]]:
registry = get_asset_registry()
session_id = get_session_id()
assets = list(registry.values())
if session_id:
assets = [a for a in assets if a.get('session_id') == session_id]
if asset_type:
if asset_type not in ['source', 'target', 'output']:
raise ValueError(f"Invalid asset_type: {asset_type}")
assets = [a for a in assets if a.get('type') == asset_type]
return assets
def delete_asset(asset_id : str) -> bool:
registry = get_asset_registry()
asset = registry.get(asset_id)
if not asset:
return False
file_path = asset.get('path')
if file_path and os.path.exists(file_path):
os.remove(file_path)
del registry[asset_id]
state_manager.set_item('asset_registry', registry)
return True
def cleanup_session_assets(session_id : str) -> None:
registry = get_asset_registry()
assets_to_delete = [aid for aid, asset in registry.items() if asset.get('session_id') == session_id]
for asset_id in assets_to_delete:
delete_asset(asset_id)
+30 -2
View File
@@ -1,5 +1,6 @@
import math
from functools import lru_cache
from typing import Any, List, Optional
from typing import Any, List, Optional, Tuple
import numpy
import scipy
@@ -7,7 +8,8 @@ from numpy.typing import NDArray
from facefusion.ffmpeg import read_audio_buffer
from facefusion.filesystem import is_audio
from facefusion.types import Audio, AudioFrame, Fps, Mel, MelFilterBank, Spectrogram
from facefusion.media_helper import restrict_trim_frame
from facefusion.types import Audio, AudioFrame, Duration, Fps, Mel, MelFilterBank, Spectrogram
from facefusion.voice_extractor import batch_extract_voice
@@ -141,3 +143,29 @@ def create_spectrogram(audio : Audio) -> Spectrogram:
spectrogram = scipy.signal.stft(audio, nperseg = mel_bin_total, nfft = mel_bin_total, noverlap = mel_bin_overlap)[2]
spectrogram = numpy.dot(mel_filter_bank, numpy.abs(spectrogram))
return spectrogram
def count_audio_frame_total(audio_path : str, fps : Fps) -> int:
audio_duration = detect_audio_duration(audio_path)
if audio_duration > 0:
return math.ceil(audio_duration * fps)
return 0
def detect_audio_duration(audio_path : str) -> Duration:
audio_sample_rate = 48000
audio_sample_size = 16
audio_channel_total = 2
if is_audio(audio_path):
audio_buffer = read_audio_buffer(audio_path, audio_sample_rate, audio_sample_size, audio_channel_total)
if audio_buffer:
audio = numpy.frombuffer(audio_buffer, dtype = numpy.int16).reshape(-1, audio_channel_total)
audio_duration = len(audio) / audio_sample_rate
return audio_duration
return 0
def restrict_trim_audio_frame(audio_path : str, fps : Fps, trim_frame_start : Optional[int], trim_frame_end : Optional[int]) -> Tuple[int, int]:
audio_frame_total = count_audio_frame_total(audio_path, fps)
return restrict_trim_frame(audio_frame_total, trim_frame_start, trim_frame_end)
+3 -3
View File
@@ -2,7 +2,7 @@ import logging
from typing import List, Sequence
from facefusion.common_helper import create_float_range, create_int_range
from facefusion.types import Angle, AudioEncoder, AudioFormat, AudioTypeSet, BenchmarkMode, BenchmarkResolution, BenchmarkSet, DownloadProvider, DownloadProviderSet, DownloadScope, EncoderSet, ExecutionProvider, ExecutionProviderSet, FaceDetectorModel, FaceDetectorSet, FaceLandmarkerModel, FaceMaskArea, FaceMaskAreaSet, FaceMaskRegion, FaceMaskRegionSet, FaceMaskType, FaceOccluderModel, FaceParserModel, FaceSelectorMode, FaceSelectorOrder, Gender, ImageFormat, ImageTypeSet, JobStatus, LogLevel, LogLevelSet, Race, Score, TempFrameFormat, UiWorkflow, VideoEncoder, VideoFormat, VideoMemoryStrategy, VideoPreset, VideoTypeSet, VoiceExtractorModel
from facefusion.types import Angle, AudioEncoder, AudioFormat, AudioTypeSet, BenchmarkMode, BenchmarkResolution, BenchmarkSet, DownloadProvider, DownloadProviderSet, DownloadScope, EncoderSet, ExecutionProvider, ExecutionProviderSet, FaceDetectorModel, FaceDetectorSet, FaceLandmarkerModel, FaceMaskArea, FaceMaskAreaSet, FaceMaskRegion, FaceMaskRegionSet, FaceMaskType, FaceOccluderModel, FaceParserModel, FaceSelectorMode, FaceSelectorOrder, Gender, ImageFormat, ImageTypeSet, JobStatus, LogLevel, LogLevelSet, Race, Score, TempFrameFormat, VideoEncoder, VideoFormat, VideoMemoryStrategy, VideoPreset, VideoTypeSet, VoiceExtractorModel, WorkFlow
face_detector_set : FaceDetectorSet =\
{
@@ -45,6 +45,8 @@ face_mask_regions : List[FaceMaskRegion] = list(face_mask_region_set.keys())
voice_extractor_models : List[VoiceExtractorModel] = [ 'kim_vocal_1', 'kim_vocal_2', 'uvr_mdxnet' ]
workflows : List[WorkFlow] = [ 'auto', 'audio-to-image', 'image-to-image', 'image-to-video' ]
audio_type_set : AudioTypeSet =\
{
'flac': 'audio/flac',
@@ -147,12 +149,10 @@ log_level_set : LogLevelSet =\
}
log_levels : List[LogLevel] = list(log_level_set.keys())
ui_workflows : List[UiWorkflow] = [ 'instant_runner', 'job_runner', 'job_manager' ]
job_statuses : List[JobStatus] = [ 'drafted', 'queued', 'completed', 'failed' ]
benchmark_cycle_count_range : Sequence[int] = create_int_range(1, 10, 1)
execution_thread_count_range : Sequence[int] = create_int_range(1, 32, 1)
system_memory_limit_range : Sequence[int] = create_int_range(0, 128, 4)
face_detector_margin_range : Sequence[int] = create_int_range(0, 100, 1)
face_detector_angles : Sequence[Angle] = create_int_range(0, 270, 90)
face_detector_score_range : Sequence[Score] = create_float_range(0.0, 1.0, 0.05)
View File
+70
View File
@@ -0,0 +1,70 @@
import ctypes
import struct
from typing import Optional
from facefusion.libraries import aom as aom_module
from facefusion.types import AomDecoder, AomPointer
def create(thread_count : int) -> Optional[AomDecoder]:
aom_library = aom_module.create_static_library()
if aom_library:
aom_decoder = ctypes.create_string_buffer(128)
aom_codec = ctypes.c_void_p.in_dll(aom_library, 'aom_codec_av1_dx_algo')
config_buffer = ctypes.create_string_buffer(128)
struct.pack_into('I', config_buffer, 0, thread_count)
struct.pack_into('I', config_buffer, 12, 1)
if aom_library.aom_codec_dec_init_ver(aom_decoder, ctypes.byref(aom_codec), config_buffer, 0, 22) == 0:
return aom_decoder
return None
def decode(aom_decoder : AomDecoder, input_buffer : bytes) -> Optional[AomPointer]:
aom_library = aom_module.create_static_library()
if aom_library and input_buffer:
input_total = len(input_buffer)
temp_buffer = ctypes.create_string_buffer(input_buffer)
if aom_library.aom_codec_decode(aom_decoder, temp_buffer, input_total, None) == 0:
address = aom_library.aom_codec_get_frame(aom_decoder, ctypes.byref(ctypes.c_void_p(0)))
if address:
frame_width = ctypes.c_uint.from_address(address + 28).value & ~1
frame_height = ctypes.c_uint.from_address(address + 32).value & ~1
return AomPointer(
buffer = collect(address, frame_width, frame_height),
resolution = (frame_width, frame_height)
)
return None
def collect(address : int, frame_width : int, frame_height : int) -> bytes:
output_parts = []
for index in range(3):
plane_pointer = ctypes.c_void_p.from_address(address + 64 + index * 8).value
stride = ctypes.c_int.from_address(address + 88 + index * 4).value
plane_width = frame_width >> (index > 0)
plane_height = frame_height >> (index > 0)
if stride == plane_width:
output_parts.append(ctypes.string_at(plane_pointer, plane_width * plane_height))
else:
for row in range(plane_height):
output_parts.append(ctypes.string_at(plane_pointer + row * stride, plane_width))
return bytes().join(output_parts)
def destroy(aom_decoder : AomDecoder) -> None:
aom_library = aom_module.create_static_library()
if aom_library:
aom_library.aom_codec_destroy(aom_decoder)
+94
View File
@@ -0,0 +1,94 @@
import ctypes
import struct
from typing import Optional
from facefusion.libraries import aom as aom_module
from facefusion.types import AomEncoder, BitRate, Resolution
def create(frame_resolution : Resolution, bitrate : BitRate, thread_count : int, cpu_count : int) -> Optional[AomEncoder]:
aom_library = aom_module.create_static_library()
if aom_library:
aom_encoder = ctypes.create_string_buffer(1152)
aom_codec = ctypes.c_void_p.in_dll(aom_library, 'aom_codec_av1_cx_algo')
config_buffer = ctypes.create_string_buffer(1024)
if aom_library.aom_codec_enc_config_default(ctypes.byref(aom_codec), config_buffer, 1) == 0:
struct.pack_into('I', config_buffer, 4, thread_count)
struct.pack_into('I', config_buffer, 12, frame_resolution[0])
struct.pack_into('I', config_buffer, 16, frame_resolution[1])
struct.pack_into('I', config_buffer, 136, bitrate)
struct.pack_into('I', config_buffer, 192, 30)
if aom_library.aom_codec_enc_init_ver(aom_encoder, ctypes.byref(aom_codec), config_buffer, 0, 25) == 0:
aom_library.aom_codec_control(aom_encoder, 13, ctypes.c_int(cpu_count))
aom_library.aom_codec_control(aom_encoder, 75, ctypes.c_int(1))
aom_library.aom_codec_control(aom_encoder, 106, ctypes.c_int(0))
aom_library.aom_codec_control(aom_encoder, 122, ctypes.c_int(0))
aom_library.aom_codec_control(aom_encoder, 123, ctypes.c_int(0))
ctypes.memmove(ctypes.addressof(aom_encoder) + 128, config_buffer, 1024)
return aom_encoder
return None
def encode(aom_encoder : AomEncoder, input_buffer : bytes, frame_resolution : Resolution, frame_index : int) -> bytes:
aom_library = aom_module.create_static_library()
output_buffer = bytes()
if aom_library:
temp_buffer = ctypes.create_string_buffer(256)
encode_buffer = ctypes.create_string_buffer(input_buffer)
if aom_library.aom_img_wrap(temp_buffer, 0x102, frame_resolution[0], frame_resolution[1], 1, encode_buffer) and aom_library.aom_codec_encode(aom_encoder, temp_buffer, frame_index, 1, 0, 1) == 0:
output_buffer = collect(aom_encoder)
return output_buffer
def collect(aom_encoder : AomEncoder) -> bytes:
aom_library = aom_module.create_static_library()
output_parts = []
packet_cursor = ctypes.c_void_p(0)
packet = aom_library.aom_codec_get_cx_data(aom_encoder, ctypes.byref(packet_cursor))
while packet:
if ctypes.c_int.from_address(packet).value == 0:
buffer_pointer = ctypes.c_void_p.from_address(packet + 8).value
buffer_size = ctypes.c_size_t.from_address(packet + 16).value
output_parts.append(ctypes.string_at(buffer_pointer, buffer_size))
packet = aom_library.aom_codec_get_cx_data(aom_encoder, ctypes.byref(packet_cursor))
return bytes().join(output_parts)
def update_resolution(aom_encoder : AomEncoder, frame_resolution : Resolution) -> bool:
aom_library = aom_module.create_static_library()
if aom_library:
struct.pack_into('I', aom_encoder, 128 + 12, frame_resolution[0])
struct.pack_into('I', aom_encoder, 128 + 16, frame_resolution[1])
return aom_library.aom_codec_enc_config_set(aom_encoder, ctypes.cast(ctypes.addressof(aom_encoder) + 128, ctypes.c_void_p)) == 0
return False
def update_bitrate(aom_encoder : AomEncoder, bitrate : BitRate) -> bool:
aom_library = aom_module.create_static_library()
if aom_library:
struct.pack_into('I', aom_encoder, 128 + 136, bitrate)
return aom_library.aom_codec_enc_config_set(aom_encoder, ctypes.cast(ctypes.addressof(aom_encoder) + 128, ctypes.c_void_p)) == 0
return False
def destroy(aom_encoder : AomEncoder) -> None:
aom_library = aom_module.create_static_library()
if aom_library:
aom_library.aom_codec_destroy(aom_encoder)
+36
View File
@@ -0,0 +1,36 @@
import ctypes
from typing import Optional
from facefusion.libraries import opus as opus_module
from facefusion.types import OpusDecoder
def create(sample_rate : int, channel_total : int) -> Optional[OpusDecoder]:
opus_library = opus_module.create_static_library()
if opus_library:
return opus_library.opus_decoder_create(sample_rate, channel_total, ctypes.byref(ctypes.c_int(0)))
return None
def decode(opus_decoder : OpusDecoder, input_buffer : bytes, frame_size : int, channel_total : int) -> bytes:
opus_library = opus_module.create_static_library()
output_buffer = bytes()
if opus_library:
input_total = len(input_buffer)
decode_buffer = (ctypes.c_float * (frame_size * channel_total))()
decode_length = opus_library.opus_decode_float(opus_decoder, input_buffer, input_total, decode_buffer, frame_size, 0)
if decode_length:
output_buffer = ctypes.string_at(ctypes.addressof(decode_buffer), decode_length * channel_total * ctypes.sizeof(ctypes.c_float))
return output_buffer
def destroy(opus_decoder : OpusDecoder) -> None:
opus_library = opus_module.create_static_library()
if opus_library:
opus_library.opus_decoder_destroy(opus_decoder)
+36
View File
@@ -0,0 +1,36 @@
import ctypes
from typing import Optional
from facefusion.libraries import opus as opus_module
from facefusion.types import OpusEncoder
def create(sample_rate : int, channel_total : int) -> Optional[OpusEncoder]:
opus_library = opus_module.create_static_library()
if opus_library:
return opus_library.opus_encoder_create(sample_rate, channel_total, 2049, ctypes.byref(ctypes.c_int(0)))
return None
def encode(opus_encoder : OpusEncoder, input_buffer : bytes, frame_size : int) -> bytes:
opus_library = opus_module.create_static_library()
output_buffer = bytes()
if opus_library:
temp_buffer = ctypes.create_string_buffer(2048)
encode_buffer = ctypes.cast(ctypes.create_string_buffer(input_buffer), ctypes.POINTER(ctypes.c_float))
encode_length = opus_library.opus_encode_float(opus_encoder, encode_buffer, frame_size, temp_buffer, 2048)
if encode_length:
output_buffer = temp_buffer.raw[:encode_length]
return output_buffer
def destroy(opus_encoder : OpusEncoder) -> None:
opus_library = opus_module.create_static_library()
if opus_library:
opus_library.opus_encoder_destroy(opus_encoder)
+74
View File
@@ -0,0 +1,74 @@
import ctypes
import struct
from typing import Optional
from facefusion.libraries import vpx as vpx_module
from facefusion.types import VpxDecoder, VpxPointer, VxpVideoCodec
def create(video_codec : VxpVideoCodec, thread_count : int) -> Optional[VpxDecoder]:
vpx_library = vpx_module.create_static_library()
if vpx_library:
vpx_decoder = ctypes.create_string_buffer(64)
vpx_algo = 'vpx_codec_vp8_dx_algo'
if video_codec == 'vp9':
vpx_algo = 'vpx_codec_vp9_dx_algo'
vpx_codec = ctypes.c_void_p.in_dll(vpx_library, vpx_algo)
config_buffer = ctypes.create_string_buffer(128)
struct.pack_into('I', config_buffer, 0, thread_count)
if vpx_library.vpx_codec_dec_init_ver(vpx_decoder, ctypes.byref(vpx_codec), config_buffer, 0, 12) == 0:
return vpx_decoder
return None
def decode(vpx_decoder : VpxDecoder, input_buffer : bytes) -> Optional[VpxPointer]:
vpx_library = vpx_module.create_static_library()
if vpx_library and input_buffer:
input_total = len(input_buffer)
temp_buffer = ctypes.create_string_buffer(input_buffer)
if vpx_library.vpx_codec_decode(vpx_decoder, temp_buffer, input_total, None, 0) == 0:
address = vpx_library.vpx_codec_get_frame(vpx_decoder, ctypes.byref(ctypes.c_void_p(0)))
if address:
frame_width = ctypes.c_uint.from_address(address + 24).value & ~1
frame_height = ctypes.c_uint.from_address(address + 28).value & ~1
return VpxPointer(
buffer = collect(address, frame_width, frame_height),
resolution = (frame_width, frame_height)
)
return None
def collect(address : int, frame_width : int, frame_height : int) -> bytes:
output_parts = []
for index in range(3):
plane_pointer = ctypes.c_void_p.from_address(address + 48 + index * 8).value
stride = ctypes.c_int.from_address(address + 80 + index * 4).value
plane_width = frame_width >> (index > 0)
plane_height = frame_height >> (index > 0)
if stride == plane_width:
output_parts.append(ctypes.string_at(plane_pointer, plane_width * plane_height))
else:
for row in range(plane_height):
output_parts.append(ctypes.string_at(plane_pointer + row * stride, plane_width))
return bytes().join(output_parts)
def destroy(vpx_decoder : VpxDecoder) -> None:
vpx_library = vpx_module.create_static_library()
if vpx_library:
vpx_library.vpx_codec_destroy(vpx_decoder)
+104
View File
@@ -0,0 +1,104 @@
import ctypes
import struct
from typing import Optional
from facefusion.libraries import vpx as vpx_module
from facefusion.types import BitRate, Resolution, VpxEncoder, VxpVideoCodec
def create(video_codec : VxpVideoCodec, frame_resolution : Resolution, bitrate : BitRate, thread_count : int, cpu_count : int) -> Optional[VpxEncoder]:
vpx_library = vpx_module.create_static_library()
if vpx_library:
vpx_encoder = ctypes.create_string_buffer(640)
vpx_algo = 'vpx_codec_vp8_cx_algo'
if video_codec == 'vp9':
vpx_algo = 'vpx_codec_vp9_cx_algo'
vpx_codec = ctypes.c_void_p.in_dll(vpx_library, vpx_algo)
config_buffer = ctypes.create_string_buffer(512)
if vpx_library.vpx_codec_enc_config_default(ctypes.byref(vpx_codec), config_buffer, 0) == 0:
struct.pack_into('I', config_buffer, 4, thread_count)
struct.pack_into('I', config_buffer, 12, frame_resolution[0])
struct.pack_into('I', config_buffer, 16, frame_resolution[1])
struct.pack_into('I', config_buffer, 28, 1)
struct.pack_into('I', config_buffer, 36, 0)
struct.pack_into('I', config_buffer, 44, 0)
struct.pack_into('I', config_buffer, 72, 0)
struct.pack_into('I', config_buffer, 112, bitrate)
struct.pack_into('I', config_buffer, 116, 2)
struct.pack_into('I', config_buffer, 120, 50)
struct.pack_into('I', config_buffer, 124, 50)
struct.pack_into('I', config_buffer, 128, 50)
if vpx_library.vpx_codec_enc_init_ver(vpx_encoder, ctypes.byref(vpx_codec), config_buffer, 0, 39) == 0:
vpx_library.vpx_codec_control_(vpx_encoder, 13, ctypes.c_int(cpu_count))
vpx_library.vpx_codec_control_(vpx_encoder, 12, ctypes.c_int(0))
vpx_library.vpx_codec_control_(vpx_encoder, 27, ctypes.c_int(10))
ctypes.memmove(ctypes.addressof(vpx_encoder) + 64, config_buffer, 512)
return vpx_encoder
return None
def encode(vpx_encoder : VpxEncoder, input_buffer : bytes, frame_resolution : Resolution, frame_index : int) -> bytes:
vpx_library = vpx_module.create_static_library()
output_buffer = bytes()
if vpx_library:
temp_buffer = ctypes.create_string_buffer(256)
encode_buffer = ctypes.create_string_buffer(input_buffer)
if vpx_library.vpx_img_wrap(temp_buffer, 0x102, frame_resolution[0], frame_resolution[1], 1, encode_buffer) and vpx_library.vpx_codec_encode(vpx_encoder, temp_buffer, frame_index, 1, 0, 1) == 0:
output_buffer = collect(vpx_encoder)
return output_buffer
def collect(vpx_encoder : VpxEncoder) -> bytes:
vpx_library = vpx_module.create_static_library()
output_parts = []
packet_cursor = ctypes.c_void_p(0)
packet = vpx_library.vpx_codec_get_cx_data(vpx_encoder, ctypes.byref(packet_cursor))
while packet:
if ctypes.c_int.from_address(packet).value == 0:
buffer_pointer = ctypes.c_void_p.from_address(packet + 8).value
buffer_size = ctypes.c_size_t.from_address(packet + 16).value
output_parts.append(ctypes.string_at(buffer_pointer, buffer_size))
packet = vpx_library.vpx_codec_get_cx_data(vpx_encoder, ctypes.byref(packet_cursor))
return bytes().join(output_parts)
def update_resolution(vpx_encoder : VpxEncoder, frame_resolution : Resolution) -> bool:
vpx_library = vpx_module.create_static_library()
if vpx_library:
struct.pack_into('I', vpx_encoder, 64 + 12, frame_resolution[0])
struct.pack_into('I', vpx_encoder, 64 + 16, frame_resolution[1])
return vpx_library.vpx_codec_enc_config_set(vpx_encoder, ctypes.cast(ctypes.addressof(vpx_encoder) + 64, ctypes.c_void_p)) == 0
return False
def update_bitrate(vpx_encoder : VpxEncoder, bitrate : BitRate) -> bool:
vpx_library = vpx_module.create_static_library()
if vpx_library:
struct.pack_into('I', vpx_encoder, 64 + 112, bitrate)
return vpx_library.vpx_codec_enc_config_set(vpx_encoder, ctypes.cast(ctypes.addressof(vpx_encoder) + 64, ctypes.c_void_p)) == 0
return False
def destroy(vpx_encoder : VpxEncoder) -> None:
vpx_library = vpx_module.create_static_library()
if vpx_library:
vpx_library.vpx_codec_destroy(vpx_encoder)
+52 -41
View File
@@ -5,19 +5,23 @@ import signal
import sys
from time import time
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
from facefusion.args import apply_args, collect_job_args, reduce_job_args, reduce_step_args
import uvicorn
from facefusion import args_store, benchmarker, cli_helper, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, hash_helper, logger, state_manager, translator, voice_extractor
from facefusion.apis.core import create_api
from facefusion.args_helper import apply_args
from facefusion.download import conditional_download_hashes, conditional_download_sources
from facefusion.exit_helper import hard_exit, signal_exit
from facefusion.filesystem import get_file_extension, get_file_name, is_image, is_video, resolve_file_paths, resolve_file_pattern
from facefusion.filesystem import get_file_extension, get_file_name, resolve_file_paths, resolve_file_pattern
from facefusion.filesystem import has_audio, has_image, has_video
from facefusion.jobs import job_helper, job_manager, job_runner
from facefusion.jobs.job_list import compose_job_list
from facefusion.memory import limit_system_memory
from facefusion.libraries import aom as aom_module, datachannel as datachannel_module, opus as opus_module, vpx as vpx_module
from facefusion.processors.core import get_processors_modules
from facefusion.program import create_program
from facefusion.program_helper import validate_args
from facefusion.types import Args, ErrorCode
from facefusion.workflows import image_to_image, image_to_video
from facefusion.types import Args, ErrorCode, WorkFlow
from facefusion.workflows import audio_to_image, image_to_image, image_to_video
def cli() -> None:
@@ -41,11 +45,6 @@ def cli() -> None:
def route(args : Args) -> None:
system_memory_limit = state_manager.get_item('system_memory_limit')
if system_memory_limit and system_memory_limit > 0:
limit_system_memory(system_memory_limit)
if state_manager.get_item('command') == 'force-download':
error_code = force_download()
hard_exit(error_code)
@@ -55,37 +54,31 @@ def route(args : Args) -> None:
hard_exit(2)
benchmarker.render()
if state_manager.get_item('command') == 'api':
logger.info(translator.get('api_started').format(host = state_manager.get_item('api_host'), port = state_manager.get_item('api_port')), __name__)
uvicorn.run(create_api(), host = state_manager.get_item('api_host'), port = state_manager.get_item('api_port'))
hard_exit(1)
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' ]:
if not job_manager.init_jobs(state_manager.get_item('jobs_path')):
if not job_manager.init_jobs(state_manager.get_jobs_path()):
hard_exit(1)
error_code = route_job_manager(args)
hard_exit(error_code)
if state_manager.get_item('command') == 'run':
import facefusion.uis.core as ui
if not common_pre_check() or not processors_pre_check():
hard_exit(2)
for ui_layout in ui.get_ui_layouts_modules(state_manager.get_item('ui_layouts')):
if not ui_layout.pre_check():
hard_exit(2)
ui.init()
ui.launch()
if state_manager.get_item('command') == 'headless-run':
if not job_manager.init_jobs(state_manager.get_item('jobs_path')):
if not job_manager.init_jobs(state_manager.get_jobs_path()):
hard_exit(1)
error_code = process_headless(args)
hard_exit(error_code)
if state_manager.get_item('command') == 'batch-run':
if not job_manager.init_jobs(state_manager.get_item('jobs_path')):
if not job_manager.init_jobs(state_manager.get_jobs_path()):
hard_exit(1)
error_code = process_batch(args)
hard_exit(error_code)
if state_manager.get_item('command') in [ 'job-run', 'job-run-all', 'job-retry', 'job-retry-all' ]:
if not job_manager.init_jobs(state_manager.get_item('jobs_path')):
if not job_manager.init_jobs(state_manager.get_jobs_path()):
hard_exit(1)
error_code = route_job_runner()
hard_exit(error_code)
@@ -109,13 +102,17 @@ def pre_check() -> bool:
def common_pre_check() -> bool:
common_modules =\
[
aom_module,
datachannel_module,
content_analyser,
face_classifier,
face_detector,
face_landmarker,
face_masker,
face_recognizer,
voice_extractor
opus_module,
voice_extractor,
vpx_module
]
content_analyser_content = inspect.getsource(content_analyser).encode()
@@ -203,7 +200,7 @@ def route_job_manager(args : Args) -> ErrorCode:
return 1
if state_manager.get_item('command') == 'job-add-step':
step_args = reduce_step_args(args)
step_args = args_store.filter_step_args(args)
if job_manager.add_step(state_manager.get_item('job_id'), step_args):
logger.info(translator.get('job_step_added').format(job_id = state_manager.get_item('job_id')), __name__)
@@ -212,7 +209,7 @@ def route_job_manager(args : Args) -> ErrorCode:
return 1
if state_manager.get_item('command') == 'job-remix-step':
step_args = reduce_step_args(args)
step_args = args_store.filter_step_args(args)
if job_manager.remix_step(state_manager.get_item('job_id'), state_manager.get_item('step_index'), step_args):
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__)
@@ -221,7 +218,7 @@ def route_job_manager(args : Args) -> ErrorCode:
return 1
if state_manager.get_item('command') == 'job-insert-step':
step_args = reduce_step_args(args)
step_args = args_store.filter_step_args(args)
if job_manager.insert_step(state_manager.get_item('job_id'), state_manager.get_item('step_index'), step_args):
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__)
@@ -275,7 +272,7 @@ def route_job_runner() -> ErrorCode:
def process_headless(args : Args) -> ErrorCode:
job_id = job_helper.suggest_job_id('headless')
step_args = reduce_step_args(args)
step_args = args_store.filter_step_args(args)
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):
return 0
@@ -284,10 +281,9 @@ def process_headless(args : Args) -> ErrorCode:
def process_batch(args : Args) -> ErrorCode:
job_id = job_helper.suggest_job_id('batch')
step_args = reduce_step_args(args)
job_args = reduce_job_args(args)
source_paths = resolve_file_pattern(job_args.get('source_pattern'))
target_paths = resolve_file_pattern(job_args.get('target_pattern'))
step_args = args_store.filter_step_args(args)
source_paths = resolve_file_pattern(step_args.get('source_pattern'))
target_paths = resolve_file_pattern(step_args.get('target_pattern'))
if job_manager.create_job(job_id):
if source_paths and target_paths:
@@ -296,7 +292,7 @@ def process_batch(args : Args) -> ErrorCode:
step_args['target_path'] = target_path
try:
step_args['output_path'] = job_args.get('output_pattern').format(index = index, source_name = get_file_name(source_path), target_name = get_file_name(target_path), target_extension = get_file_extension(target_path))
step_args['output_path'] = step_args.get('output_pattern').format(index = index, source_name = get_file_name(source_path), target_name = get_file_name(target_path), target_extension = get_file_extension(target_path))
except KeyError:
return 1
@@ -310,7 +306,7 @@ def process_batch(args : Args) -> ErrorCode:
step_args['target_path'] = target_path
try:
step_args['output_path'] = job_args.get('output_pattern').format(index = index, target_name = get_file_name(target_path), target_extension = get_file_extension(target_path))
step_args['output_path'] = step_args.get('output_pattern').format(index = index, target_name = get_file_name(target_path), target_extension = get_file_extension(target_path))
except KeyError:
return 1
@@ -323,8 +319,10 @@ def process_batch(args : Args) -> ErrorCode:
def process_step(job_id : str, step_index : int, step_args : Args) -> bool:
step_total = job_manager.count_step_total(job_id)
step_args.update(collect_job_args())
apply_args(step_args, state_manager.set_item)
cli_args = args_store.filter_cli_args(state_manager.get_state()) #type:ignore[arg-type]
args = cli_args.copy()
args.update(step_args)
apply_args(args, state_manager.set_item)
logger.info(translator.get('processing_step').format(step_current = step_index + 1, step_total = step_total), __name__)
if common_pre_check() and processors_pre_check():
@@ -336,15 +334,28 @@ def process_step(job_id : str, step_index : int, step_args : Args) -> bool:
def conditional_process() -> ErrorCode:
start_time = time()
if state_manager.get_item('workflow') == 'auto':
state_manager.set_item('workflow', detect_workflow())
for processor_module in get_processors_modules(state_manager.get_item('processors')):
if not processor_module.pre_process('output'):
return 2
if is_image(state_manager.get_item('target_path')):
if state_manager.get_item('workflow') == 'audio-to-image':
return audio_to_image.process(start_time)
if state_manager.get_item('workflow') == 'image-to-image':
return image_to_image.process(start_time)
if is_video(state_manager.get_item('target_path')):
if state_manager.get_item('workflow') == 'image-to-video':
return image_to_video.process(start_time)
return 0
def detect_workflow() -> WorkFlow:
if has_video([ state_manager.get_item('target_path') ]):
return 'image-to-video'
if has_audio(state_manager.get_item('source_paths')) and has_image([ state_manager.get_item('target_path') ]):
return 'audio-to-image'
return 'image-to-image'
+1 -5
View File
@@ -16,7 +16,7 @@ def chain(*commands : List[Command]) -> List[Command]:
return list(itertools.chain(*commands))
def ping(url : str) -> List[Command]:
def head(url : str) -> List[Command]:
return [ '-I', url ]
@@ -26,7 +26,3 @@ def download(url : str, download_file_path : str) -> List[Command]:
def set_timeout(timeout : int) -> List[Command]:
return [ '--connect-timeout', str(timeout) ]
def set_retry(retry : int) -> List[Command]:
return [ '--retry', str(retry) ]
+3 -4
View File
@@ -29,8 +29,7 @@ def conditional_download(download_directory_path : str, urls : List[str]) -> Non
with tqdm(total = download_size, initial = initial_size, desc = translator.get('downloading'), unit = 'B', unit_scale = True, unit_divisor = 1024, ascii = ' =', disable = state_manager.get_item('log_level') in [ 'warn', 'error' ]) as progress:
commands = curl_builder.chain(
curl_builder.download(url, download_file_path),
curl_builder.set_timeout(5),
curl_builder.set_retry(5)
curl_builder.set_timeout(5)
)
open_curl(commands)
current_size = initial_size
@@ -45,7 +44,7 @@ def conditional_download(download_directory_path : str, urls : List[str]) -> Non
@lru_cache(maxsize = 64)
def get_static_download_size(url : str) -> int:
commands = curl_builder.chain(
curl_builder.ping(url),
curl_builder.head(url),
curl_builder.set_timeout(5)
)
process = open_curl(commands)
@@ -63,7 +62,7 @@ def get_static_download_size(url : str) -> int:
@lru_cache(maxsize = 64)
def ping_static_url(url : str) -> bool:
commands = curl_builder.chain(
curl_builder.ping(url),
curl_builder.head(url),
curl_builder.set_timeout(5)
)
process = open_curl(commands)
+2 -2
View File
@@ -28,7 +28,7 @@ def graceful_exit(error_code : ErrorCode) -> None:
while process_manager.is_processing():
sleep(0.5)
if state_manager.get_item('target_path'):
clear_temp_directory(state_manager.get_item('target_path'))
if state_manager.get_item('output_path'):
clear_temp_directory(state_manager.get_temp_path(), state_manager.get_item('output_path'))
hard_exit(error_code)
+35 -16
View File
@@ -107,9 +107,9 @@ def get_available_encoder_set() -> EncoderSet:
return available_encoder_set
def extract_frames(target_path : str, temp_video_resolution : Resolution, temp_video_fps : Fps, trim_frame_start : int, trim_frame_end : int) -> bool:
def extract_frames(target_path : str, output_path : str, temp_video_resolution : Resolution, temp_video_fps : Fps, trim_frame_start : int, trim_frame_end : int) -> bool:
extract_frame_total = predict_video_frame_total(target_path, temp_video_fps, trim_frame_start, trim_frame_end)
temp_frames_pattern = get_temp_frames_pattern(target_path, '%08d')
temp_frames_pattern = get_temp_frames_pattern(state_manager.get_temp_path(), output_path, state_manager.get_item('temp_frame_format'), '%08d')
commands = ffmpeg_builder.chain(
ffmpeg_builder.set_input(target_path),
ffmpeg_builder.set_media_resolution(pack_resolution(temp_video_resolution)),
@@ -124,8 +124,26 @@ def extract_frames(target_path : str, temp_video_resolution : Resolution, temp_v
return process.returncode == 0
def copy_image(target_path : str, temp_image_resolution : Resolution) -> bool:
temp_image_path = get_temp_file_path(target_path)
def spawn_frames(target_path : str, output_path : str, temp_video_resolution : Resolution, temp_video_fps : Fps, trim_frame_start : int, trim_frame_end : int) -> bool:
spawn_frame_total = trim_frame_end - trim_frame_start
duration = spawn_frame_total / temp_video_fps
temp_frames_pattern = get_temp_frames_pattern(state_manager.get_temp_path(), output_path, state_manager.get_item('temp_frame_format'), '%08d')
commands = ffmpeg_builder.chain(
ffmpeg_builder.set_loop(),
ffmpeg_builder.set_input(target_path),
ffmpeg_builder.set_video_duration(duration),
ffmpeg_builder.set_video_fps(temp_video_fps),
ffmpeg_builder.set_media_resolution(pack_resolution(temp_video_resolution)),
ffmpeg_builder.set_output(temp_frames_pattern)
)
with tqdm(total = spawn_frame_total, desc = translator.get('spawning'), unit = 'frame', ascii = ' =', disable = state_manager.get_item('log_level') in [ 'warn', 'error' ]) as progress:
process = run_ffmpeg_with_progress(commands, partial(update_progress, progress))
return process.returncode == 0
def copy_image(target_path : str, output_path : str, temp_image_resolution : Resolution) -> bool:
temp_image_path = get_temp_file_path(state_manager.get_temp_path(), output_path)
commands = ffmpeg_builder.chain(
ffmpeg_builder.set_input(target_path),
ffmpeg_builder.set_media_resolution(pack_resolution(temp_image_resolution)),
@@ -135,13 +153,13 @@ def copy_image(target_path : str, temp_image_resolution : Resolution) -> bool:
return run_ffmpeg(commands).returncode == 0
def finalize_image(target_path : str, output_path : str, output_image_resolution : Resolution) -> bool:
def finalize_image(output_path : str, output_image_resolution : Resolution) -> bool:
output_image_quality = state_manager.get_item('output_image_quality')
temp_image_path = get_temp_file_path(target_path)
temp_image_path = get_temp_file_path(state_manager.get_temp_path(), output_path)
commands = ffmpeg_builder.chain(
ffmpeg_builder.set_input(temp_image_path),
ffmpeg_builder.set_media_resolution(pack_resolution(output_image_resolution)),
ffmpeg_builder.set_image_quality(target_path, output_image_quality),
ffmpeg_builder.set_image_quality(output_path, output_image_quality),
ffmpeg_builder.force_output(output_path)
)
return run_ffmpeg(commands).returncode == 0
@@ -169,8 +187,8 @@ def restore_audio(target_path : str, output_path : str, trim_frame_start : int,
output_audio_quality = state_manager.get_item('output_audio_quality')
output_audio_volume = state_manager.get_item('output_audio_volume')
target_video_fps = detect_video_fps(target_path)
temp_video_path = get_temp_file_path(target_path)
temp_video_format = cast(VideoFormat, get_file_format(temp_video_path))
temp_video_path = get_temp_file_path(state_manager.get_temp_path(), output_path)
temp_video_format = cast(VideoFormat, get_file_format(output_path))
temp_video_duration = detect_video_duration(temp_video_path)
output_audio_encoder = fix_audio_encoder(temp_video_format, output_audio_encoder)
@@ -190,12 +208,12 @@ def restore_audio(target_path : str, output_path : str, trim_frame_start : int,
return run_ffmpeg(commands).returncode == 0
def replace_audio(target_path : str, audio_path : str, output_path : str) -> bool:
def replace_audio(audio_path : str, output_path : str) -> bool:
output_audio_encoder = state_manager.get_item('output_audio_encoder')
output_audio_quality = state_manager.get_item('output_audio_quality')
output_audio_volume = state_manager.get_item('output_audio_volume')
temp_video_path = get_temp_file_path(target_path)
temp_video_format = cast(VideoFormat, get_file_format(temp_video_path))
temp_video_path = get_temp_file_path(state_manager.get_temp_path(), output_path)
temp_video_format = cast(VideoFormat, get_file_format(output_path))
temp_video_duration = detect_video_duration(temp_video_path)
output_audio_encoder = fix_audio_encoder(temp_video_format, output_audio_encoder)
@@ -212,14 +230,15 @@ def replace_audio(target_path : str, audio_path : str, output_path : str) -> boo
return run_ffmpeg(commands).returncode == 0
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:
def merge_video(target_path : str, output_path : str, temp_video_fps : Fps, output_video_resolution : Resolution, trim_frame_start : int, trim_frame_end : int) -> bool:
output_video_fps = state_manager.get_item('output_video_fps')
output_video_encoder = state_manager.get_item('output_video_encoder')
output_video_quality = state_manager.get_item('output_video_quality')
output_video_preset = state_manager.get_item('output_video_preset')
merge_frame_total = predict_video_frame_total(target_path, output_video_fps, trim_frame_start, trim_frame_end)
temp_video_path = get_temp_file_path(target_path)
temp_video_format = cast(VideoFormat, get_file_format(temp_video_path))
temp_frames_pattern = get_temp_frames_pattern(target_path, '%08d')
temp_video_path = get_temp_file_path(state_manager.get_temp_path(), output_path)
temp_video_format = cast(VideoFormat, get_file_format(output_path))
temp_frames_pattern = get_temp_frames_pattern(state_manager.get_temp_path(), output_path, state_manager.get_item('temp_frame_format'), '%08d')
output_video_encoder = fix_video_encoder(temp_video_format, output_video_encoder)
commands = ffmpeg_builder.chain(
+4
View File
@@ -59,6 +59,10 @@ def force_output(output_path : str) -> List[Command]:
return [ '-y', output_path ]
def set_loop() -> List[Command]:
return [ '-loop', '1' ]
def cast_stream() -> List[Command]:
return [ '-' ]
-9
View File
@@ -42,15 +42,6 @@ def get_file_format(file_path : str) -> Optional[str]:
return None
def same_file_extension(first_file_path : str, second_file_path : str) -> bool:
first_file_extension = get_file_extension(first_file_path)
second_file_extension = get_file_extension(second_file_path)
if first_file_extension and second_file_extension:
return get_file_extension(first_file_path) == get_file_extension(second_file_path)
return False
def is_file(file_path : str) -> bool:
if file_path:
return os.path.isfile(file_path)
+5 -5
View File
@@ -17,7 +17,7 @@ from facefusion.types import DownloadSet, ExecutionProvider, InferencePool, Infe
INFERENCE_POOL_SET : InferencePoolSet =\
{
'cli': {},
'ui': {}
'api': {}
}
@@ -31,10 +31,10 @@ def get_inference_pool(module_name : str, model_names : List[str], model_source_
for execution_device_id in execution_device_ids:
inference_context = get_inference_context(module_name, model_names, execution_device_id, execution_providers)
if app_context == 'cli' and INFERENCE_POOL_SET.get('ui').get(inference_context):
INFERENCE_POOL_SET['cli'][inference_context] = INFERENCE_POOL_SET.get('ui').get(inference_context)
if app_context == 'ui' and INFERENCE_POOL_SET.get('cli').get(inference_context):
INFERENCE_POOL_SET['ui'][inference_context] = INFERENCE_POOL_SET.get('cli').get(inference_context)
if app_context == 'cli' and INFERENCE_POOL_SET.get('api').get(inference_context):
INFERENCE_POOL_SET['cli'][inference_context] = INFERENCE_POOL_SET.get('api').get(inference_context)
if app_context == 'api' and INFERENCE_POOL_SET.get('cli').get(inference_context):
INFERENCE_POOL_SET['api'][inference_context] = INFERENCE_POOL_SET.get('cli').get(inference_context)
if not INFERENCE_POOL_SET.get(app_context).get(inference_context):
INFERENCE_POOL_SET[app_context][inference_context] = create_inference_pool(model_source_set, execution_device_id, execution_providers)
+12 -21
View File
@@ -10,10 +10,9 @@ from types import FrameType
from facefusion import metadata
from facefusion.common_helper import is_linux, is_windows
LOCALES =\
LOCALS =\
{
'install_dependency': 'install the {dependency} package',
'force_reinstall': 'force reinstall of packages',
'skip_conda': 'skip the conda environment check',
'conda_not_activated': 'conda is not activated'
}
@@ -27,16 +26,14 @@ if is_windows() or is_linux():
if is_windows():
ONNXRUNTIME_SET['directml'] = ('onnxruntime-directml', '1.23.0')
if is_linux():
ONNXRUNTIME_SET['migraphx'] = ('onnxruntime-migraphx', '1.23.0')
ONNXRUNTIME_SET['rocm'] = ('onnxruntime_rocm', '1.22.1', '7.0.2') #type:ignore[assignment]
ONNXRUNTIME_SET['rocm'] = ('onnxruntime-rocm', '1.21.0')
def cli() -> None:
signal.signal(signal.SIGINT, signal_exit)
program = ArgumentParser(formatter_class = partial(HelpFormatter, max_help_position = 50))
program.add_argument('--onnxruntime', help = LOCALES.get('install_dependency').format(dependency = 'onnxruntime'), choices = ONNXRUNTIME_SET.keys(), required = True)
program.add_argument('--force-reinstall', help = LOCALES.get('force_reinstall'), action = 'store_true')
program.add_argument('--skip-conda', help = LOCALES.get('skip_conda'), action = 'store_true')
program.add_argument('--onnxruntime', help = LOCALS.get('install_dependency').format(dependency = 'onnxruntime'), choices = ONNXRUNTIME_SET.keys(), required = True)
program.add_argument('--skip-conda', help = LOCALS.get('skip_conda'), action = 'store_true')
program.add_argument('-v', '--version', version = metadata.get('name') + ' ' + metadata.get('version'), action = 'version')
run(program)
@@ -48,13 +45,10 @@ def signal_exit(signum : int, frame : FrameType) -> None:
def run(program : ArgumentParser) -> None:
args = program.parse_args()
has_conda = 'CONDA_PREFIX' in os.environ
commands = [ shutil.which('pip'), 'install' ]
if args.force_reinstall:
commands.append('--force-reinstall')
onnxruntime_name, onnxruntime_version = ONNXRUNTIME_SET.get(args.onnxruntime)
if not args.skip_conda and not has_conda:
sys.stdout.write(LOCALES.get('conda_not_activated') + os.linesep)
sys.stdout.write(LOCALS.get('conda_not_activated') + os.linesep)
sys.exit(1)
with open('requirements.txt') as file:
@@ -62,21 +56,17 @@ def run(program : ArgumentParser) -> None:
for line in file.readlines():
__line__ = line.strip()
if not __line__.startswith('onnxruntime'):
commands.append(__line__)
subprocess.call([ shutil.which('pip'), 'install', line, '--force-reinstall' ])
if args.onnxruntime == 'rocm':
onnxruntime_name, onnxruntime_version, rocm_version = ONNXRUNTIME_SET.get(args.onnxruntime) #type:ignore[misc]
python_id = 'cp' + str(sys.version_info.major) + str(sys.version_info.minor)
if python_id in [ 'cp310', 'cp312' ]:
wheel_name = onnxruntime_name + '-' + onnxruntime_version + '-' + python_id + '-' + python_id + '-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl'
wheel_url = 'https://repo.radeon.com/rocm/manylinux/rocm-rel-' + rocm_version + '/' + wheel_name
commands.append(wheel_url)
wheel_name = 'onnxruntime_rocm-' + onnxruntime_version + '-' + python_id + '-' + python_id + '-linux_x86_64.whl'
wheel_url = 'https://repo.radeon.com/rocm/manylinux/rocm-rel-6.4/' + wheel_name
subprocess.call([ shutil.which('pip'), 'install', wheel_url, '--force-reinstall' ])
else:
onnxruntime_name, onnxruntime_version = ONNXRUNTIME_SET.get(args.onnxruntime)
commands.append(onnxruntime_name + '==' + onnxruntime_version)
subprocess.call(commands)
subprocess.call([ shutil.which('pip'), 'install', onnxruntime_name + '==' + onnxruntime_version, '--force-reinstall' ])
if args.onnxruntime == 'cuda' and has_conda:
library_paths = []
@@ -107,3 +97,4 @@ def run(program : ArgumentParser) -> None:
library_paths = list(dict.fromkeys([ library_path for library_path in library_paths if os.path.exists(library_path) ]))
subprocess.call([ shutil.which('conda'), 'env', 'config', 'vars', 'set', 'PATH=' + os.pathsep.join(library_paths) ])
-27
View File
@@ -1,27 +0,0 @@
from typing import List
from facefusion.types import JobStore
JOB_STORE : JobStore =\
{
'job_keys': [],
'step_keys': []
}
def get_job_keys() -> List[str]:
return JOB_STORE.get('job_keys')
def get_step_keys() -> List[str]:
return JOB_STORE.get('step_keys')
def register_job_keys(job_keys : List[str]) -> None:
for job_key in job_keys:
JOB_STORE['job_keys'].append(job_key)
def register_step_keys(step_keys : List[str]) -> None:
for step_key in step_keys:
JOB_STORE['step_keys'].append(step_key)
+134
View File
@@ -0,0 +1,134 @@
import ctypes
from functools import lru_cache
from typing import Optional
from facefusion.common_helper import is_linux, is_macos, is_windows
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url_by_provider
from facefusion.filesystem import resolve_relative_path
from facefusion.types import LibrarySet
@lru_cache
def create_static_library_set() -> Optional[LibrarySet]:
if is_linux():
return\
{
'hashes':
{
'aom':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'linux/libaom.hash'),
'path': resolve_relative_path('../.libraries/libaom.hash')
}
},
'sources':
{
'aom':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'linux/libaom.so'),
'path': resolve_relative_path('../.libraries/libaom.so')
}
}
}
if is_macos():
return\
{
'hashes':
{
'aom':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'macos/libaom.hash'),
'path': resolve_relative_path('../.libraries/libaom.hash')
}
},
'sources':
{
'aom':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'macos/libaom.dylib'),
'path': resolve_relative_path('../.libraries/libaom.dylib')
}
}
}
if is_windows():
return\
{
'hashes':
{
'aom':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'windows/aom.hash'),
'path': resolve_relative_path('../.libraries/aom.hash')
}
},
'sources':
{
'aom':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'windows/aom.dll'),
'path': resolve_relative_path('../.libraries/aom.dll')
}
}
}
return None
def pre_check() -> bool:
library_hash_set = create_static_library_set().get('hashes')
library_source_set = create_static_library_set().get('sources')
return conditional_download_hashes(library_hash_set) and conditional_download_sources(library_source_set)
@lru_cache
def create_static_library() -> Optional[ctypes.CDLL]:
library_path = create_static_library_set().get('sources').get('aom').get('path')
if library_path:
if is_windows():
library = ctypes.CDLL(library_path, winmode = 0)
else:
library = ctypes.CDLL(library_path)
if library:
return init_ctypes(library)
return None
def init_ctypes(library : ctypes.CDLL) -> ctypes.CDLL:
library.aom_codec_enc_config_default.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint ]
library.aom_codec_enc_config_default.restype = ctypes.c_int
library.aom_codec_enc_init_ver.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_long, ctypes.c_int ]
library.aom_codec_enc_init_ver.restype = ctypes.c_int
library.aom_codec_encode.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64, ctypes.c_ulong, ctypes.c_long, ctypes.c_ulong ]
library.aom_codec_encode.restype = ctypes.c_int
library.aom_codec_get_cx_data.argtypes = [ ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p) ]
library.aom_codec_get_cx_data.restype = ctypes.c_void_p
library.aom_codec_enc_config_set.argtypes = [ ctypes.c_void_p, ctypes.c_void_p ]
library.aom_codec_enc_config_set.restype = ctypes.c_int
library.aom_codec_destroy.argtypes = [ ctypes.c_void_p ]
library.aom_codec_destroy.restype = ctypes.c_int
library.aom_img_wrap.argtypes = [ ctypes.c_void_p, ctypes.c_int, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint, ctypes.c_void_p ]
library.aom_img_wrap.restype = ctypes.c_void_p
library.aom_codec_control.argtypes = [ ctypes.c_void_p, ctypes.c_int, ctypes.c_int ]
library.aom_codec_control.restype = ctypes.c_int
library.aom_codec_dec_init_ver.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_long, ctypes.c_int ]
library.aom_codec_dec_init_ver.restype = ctypes.c_int
library.aom_codec_decode.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint, ctypes.c_void_p ]
library.aom_codec_decode.restype = ctypes.c_int
library.aom_codec_get_frame.argtypes = [ ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p) ]
library.aom_codec_get_frame.restype = ctypes.c_void_p
return library
+294
View File
@@ -0,0 +1,294 @@
import ctypes
from functools import lru_cache
from typing import Optional
from facefusion.common_helper import is_linux, is_macos, is_windows
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url_by_provider
from facefusion.filesystem import resolve_relative_path
from facefusion.types import LibrarySet
@lru_cache
def create_static_library_set() -> Optional[LibrarySet]:
if is_linux():
return\
{
'hashes':
{
'crypto':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'linux/libcrypto.hash'),
'path': resolve_relative_path('../.libraries/libcrypto.hash')
},
'datachannel':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'linux/libdatachannel_next.hash'),
'path': resolve_relative_path('../.libraries/libdatachannel_next.hash')
},
'ssl':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'linux/libssl.hash'),
'path': resolve_relative_path('../.libraries/libssl.hash')
}
},
'sources':
{
'crypto':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'linux/libcrypto.so'),
'path': resolve_relative_path('../.libraries/libcrypto.so')
},
'datachannel':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'linux/libdatachannel_next.so'),
'path': resolve_relative_path('../.libraries/libdatachannel_next.so')
},
'ssl':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'linux/libssl.so'),
'path': resolve_relative_path('../.libraries/libssl.so')
}
}
}
if is_macos():
return\
{
'hashes':
{
'crypto':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'macos/libcrypto.hash'),
'path': resolve_relative_path('../.libraries/libcrypto.hash')
},
'datachannel':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'macos/libdatachannel_next.hash'),
'path': resolve_relative_path('../.libraries/libdatachannel_next.hash')
},
'ssl':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'macos/libssl.hash'),
'path': resolve_relative_path('../.libraries/libssl.hash')
}
},
'sources':
{
'crypto':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'macos/libcrypto.dylib'),
'path': resolve_relative_path('../.libraries/libcrypto.dylib')
},
'datachannel':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'macos/libdatachannel_next.dylib'),
'path': resolve_relative_path('../.libraries/libdatachannel_next.dylib')
},
'ssl':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'macos/libssl.dylib'),
'path': resolve_relative_path('../.libraries/libssl.dylib')
}
}
}
if is_windows():
return\
{
'hashes':
{
'crypto':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'windows/crypto.hash'),
'path': resolve_relative_path('../.libraries/crypto.hash')
},
'datachannel':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'windows/datachannel_next.hash'),
'path': resolve_relative_path('../.libraries/datachannel_next.hash')
},
'ssl':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'windows/ssl.hash'),
'path': resolve_relative_path('../.libraries/ssl.hash')
}
},
'sources':
{
'crypto':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'windows/crypto.dll'),
'path': resolve_relative_path('../.libraries/crypto.dll')
},
'datachannel':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'windows/datachannel_next.dll'),
'path': resolve_relative_path('../.libraries/datachannel_next.dll')
},
'ssl':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'windows/ssl.dll'),
'path': resolve_relative_path('../.libraries/ssl.dll')
}
}
}
return None
def pre_check() -> bool:
library_hash_set = create_static_library_set().get('hashes')
library_source_set = create_static_library_set().get('sources')
return conditional_download_hashes(library_hash_set) and conditional_download_sources(library_source_set)
@lru_cache
def create_static_library() -> Optional[ctypes.CDLL]:
crypto_source_path = create_static_library_set().get('sources').get('crypto').get('path')
datachannel_source_path = create_static_library_set().get('sources').get('datachannel').get('path')
ssl_source_path = create_static_library_set().get('sources').get('ssl').get('path')
if crypto_source_path and datachannel_source_path and ssl_source_path:
if is_windows():
ctypes.CDLL(crypto_source_path, winmode = 0)
ctypes.CDLL(ssl_source_path, winmode = 0)
library = ctypes.CDLL(datachannel_source_path, winmode = 0)
else:
ctypes.CDLL(crypto_source_path)
ctypes.CDLL(ssl_source_path)
library = ctypes.CDLL(datachannel_source_path)
if library:
return init_ctypes(library)
return None
def init_ctypes(library : ctypes.CDLL) -> ctypes.CDLL:
library.rtcInitLogger.argtypes = [ ctypes.c_int, ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p) ]
library.rtcInitLogger.restype = None
library.rtcInitLogger(2, ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p)(0))
library.rtcCreatePeerConnection.restype = ctypes.c_int
library.rtcDeletePeerConnection.argtypes = [ ctypes.c_int ]
library.rtcDeletePeerConnection.restype = ctypes.c_int
library.rtcSetLocalDescription.argtypes = [ ctypes.c_int, ctypes.c_char_p ]
library.rtcSetLocalDescription.restype = ctypes.c_int
library.rtcSetRemoteDescription.argtypes = [ ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p ]
library.rtcSetRemoteDescription.restype = ctypes.c_int
library.rtcAddTrackEx.restype = ctypes.c_int
library.rtcSendMessage.argtypes = [ ctypes.c_int, ctypes.c_void_p, ctypes.c_int ]
library.rtcSendMessage.restype = ctypes.c_int
library.rtcSetAV1Packetizer.restype = ctypes.c_int
library.rtcSetVP8Packetizer.restype = ctypes.c_int
library.rtcSetVP9Packetizer.restype = ctypes.c_int
library.rtcChainRtcpSrReporter.argtypes = [ ctypes.c_int ]
library.rtcChainRtcpSrReporter.restype = ctypes.c_int
library.rtcSetTrackRtpTimestamp.argtypes = [ ctypes.c_int, ctypes.c_uint32 ]
library.rtcSetTrackRtpTimestamp.restype = ctypes.c_int
library.rtcIsOpen.argtypes = [ ctypes.c_int ]
library.rtcIsOpen.restype = ctypes.c_bool
library.rtcChainRtcpNackResponder.argtypes = [ ctypes.c_int, ctypes.c_uint ]
library.rtcChainRtcpNackResponder.restype = ctypes.c_int
library.rtcGetLocalDescription.argtypes = [ ctypes.c_int, ctypes.c_char_p, ctypes.c_int ]
library.rtcGetLocalDescription.restype = ctypes.c_int
library.rtcSetOpusPacketizer.restype = ctypes.c_int
library.rtcGetPayloadTypesForCodec.argtypes = [ ctypes.c_char_p, ctypes.c_char_p, ctypes.POINTER(ctypes.c_int), ctypes.c_int ]
library.rtcGetPayloadTypesForCodec.restype = ctypes.c_int
library.rtcSetAV1Depacketizer.argtypes = [ ctypes.c_int, ctypes.c_int ]
library.rtcSetAV1Depacketizer.restype = ctypes.c_int
library.rtcSetVP8Depacketizer.restype = ctypes.c_int
library.rtcSetVP9Depacketizer.restype = ctypes.c_int
library.rtcSetOpusDepacketizer.restype = ctypes.c_int
library.rtcChainRtcpReceivingSession.argtypes = [ ctypes.c_int ]
library.rtcChainRtcpReceivingSession.restype = ctypes.c_int
library.rtcSetFrameCallback.argtypes = [ ctypes.c_int, ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p) ]
library.rtcSetFrameCallback.restype = ctypes.c_int
library.rtcSetUserPointer.argtypes = [ ctypes.c_int, ctypes.c_void_p ]
library.rtcSetUserPointer.restype = None
library.rtcChainRembHandler.argtypes = [ ctypes.c_int, ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_uint, ctypes.c_void_p) ]
library.rtcChainRembHandler.restype = ctypes.c_int
library.rtcRequestBitrate.argtypes = [ ctypes.c_int, ctypes.c_uint ]
library.rtcRequestBitrate.restype = ctypes.c_int
library.rtcSetClosedCallback.argtypes = [ ctypes.c_int, ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_void_p) ]
library.rtcSetClosedCallback.restype = ctypes.c_int
return library
def define_rtc_configuration() -> ctypes.Structure:
return type('RTC_CONFIGURATION', (ctypes.Structure,),
{
'_fields_':
[
('iceServers', ctypes.POINTER(ctypes.c_char_p)),
('iceServersCount', ctypes.c_int),
('proxyServer', ctypes.c_char_p),
('bindAddress', ctypes.c_char_p),
('certificateType', ctypes.c_int),
('iceTransportPolicy', ctypes.c_int),
('enableIceTcp', ctypes.c_bool),
('enableIceUdpMux', ctypes.c_bool),
('disableAutoNegotiation', ctypes.c_bool),
('forceMediaTransport', ctypes.c_bool),
('portRangeBegin', ctypes.c_ushort),
('portRangeEnd', ctypes.c_ushort),
('mtu', ctypes.c_int),
('maxMessageSize', ctypes.c_int)
]
})()
def define_rtc_track_init() -> ctypes.Structure:
return type('RTC_TRACK_INIT', (ctypes.Structure,),
{
'_fields_':
[
('direction', ctypes.c_int),
('codec', ctypes.c_int),
('payloadType', ctypes.c_int),
('ssrc', ctypes.c_uint32),
('mid', ctypes.c_char_p),
('name', ctypes.c_char_p),
('msid', ctypes.c_char_p),
('trackId', ctypes.c_char_p),
('profile', ctypes.c_char_p)
]
})()
def define_rtc_packetizer_init() -> ctypes.Structure:
return type('RTC_PACKETIZER_INIT', (ctypes.Structure,),
{
'_fields_':
[
('ssrc', ctypes.c_uint32),
('cname', ctypes.c_char_p),
('payloadType', ctypes.c_uint8),
('clockRate', ctypes.c_uint32),
('sequenceNumber', ctypes.c_uint16),
('timestamp', ctypes.c_uint32),
('maxFragmentSize', ctypes.c_uint16),
('nalSeparator', ctypes.c_int),
('obuPacketization', ctypes.c_int)
]
})()
+121
View File
@@ -0,0 +1,121 @@
import ctypes
from functools import lru_cache
from typing import Optional
from facefusion.common_helper import is_linux, is_macos, is_windows
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url_by_provider
from facefusion.filesystem import resolve_relative_path
from facefusion.types import LibrarySet
@lru_cache
def create_static_library_set() -> Optional[LibrarySet]:
if is_linux():
return\
{
'hashes':
{
'opus':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'linux/libopus.hash'),
'path': resolve_relative_path('../.libraries/libopus.hash')
}
},
'sources':
{
'opus':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'linux/libopus.so'),
'path': resolve_relative_path('../.libraries/libopus.so')
}
}
}
if is_macos():
return\
{
'hashes':
{
'opus':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'macos/libopus.hash'),
'path': resolve_relative_path('../.libraries/libopus.hash')
}
},
'sources':
{
'opus':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'macos/libopus.dylib'),
'path': resolve_relative_path('../.libraries/libopus.dylib')
}
}
}
if is_windows():
return\
{
'hashes':
{
'opus':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'windows/opus.hash'),
'path': resolve_relative_path('../.libraries/opus.hash')
}
},
'sources':
{
'opus':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'windows/opus.dll'),
'path': resolve_relative_path('../.libraries/opus.dll')
}
}
}
return None
def pre_check() -> bool:
library_hash_set = create_static_library_set().get('hashes')
library_source_set = create_static_library_set().get('sources')
return conditional_download_hashes(library_hash_set) and conditional_download_sources(library_source_set)
@lru_cache
def create_static_library() -> Optional[ctypes.CDLL]:
library_path = create_static_library_set().get('sources').get('opus').get('path')
if library_path:
if is_windows():
library = ctypes.CDLL(library_path, winmode = 0)
else:
library = ctypes.CDLL(library_path)
if library:
return init_ctypes(library)
return None
def init_ctypes(library : ctypes.CDLL) -> ctypes.CDLL:
library.opus_encoder_create.argtypes = [ ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int) ]
library.opus_encoder_create.restype = ctypes.c_void_p
library.opus_encode_float.argtypes = [ ctypes.c_void_p, ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_char_p, ctypes.c_int ]
library.opus_encode_float.restype = ctypes.c_int
library.opus_encoder_destroy.argtypes = [ ctypes.c_void_p ]
library.opus_encoder_destroy.restype = None
library.opus_decoder_create.argtypes = [ ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int) ]
library.opus_decoder_create.restype = ctypes.c_void_p
library.opus_decode_float.argtypes = [ ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int, ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int ]
library.opus_decode_float.restype = ctypes.c_int
library.opus_decoder_destroy.argtypes = [ ctypes.c_void_p ]
library.opus_decoder_destroy.restype = None
return library
+134
View File
@@ -0,0 +1,134 @@
import ctypes
from functools import lru_cache
from typing import Optional
from facefusion.common_helper import is_linux, is_macos, is_windows
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url_by_provider
from facefusion.filesystem import resolve_relative_path
from facefusion.types import LibrarySet
@lru_cache
def create_static_library_set() -> Optional[LibrarySet]:
if is_linux():
return\
{
'hashes':
{
'vpx':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'linux/libvpx.hash'),
'path': resolve_relative_path('../.libraries/libvpx.hash')
}
},
'sources':
{
'vpx':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'linux/libvpx.so'),
'path': resolve_relative_path('../.libraries/libvpx.so')
}
}
}
if is_macos():
return\
{
'hashes':
{
'vpx':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'macos/libvpx.hash'),
'path': resolve_relative_path('../.libraries/libvpx.hash')
}
},
'sources':
{
'vpx':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'macos/libvpx.dylib'),
'path': resolve_relative_path('../.libraries/libvpx.dylib')
}
}
}
if is_windows():
return\
{
'hashes':
{
'vpx':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'windows/vpx.hash'),
'path': resolve_relative_path('../.libraries/vpx.hash')
}
},
'sources':
{
'vpx':
{
'url': resolve_download_url_by_provider('huggingface', 'libraries-4.0.0', 'windows/vpx.dll'),
'path': resolve_relative_path('../.libraries/vpx.dll')
}
}
}
return None
def pre_check() -> bool:
library_hash_set = create_static_library_set().get('hashes')
library_source_set = create_static_library_set().get('sources')
return conditional_download_hashes(library_hash_set) and conditional_download_sources(library_source_set)
@lru_cache
def create_static_library() -> Optional[ctypes.CDLL]:
library_path = create_static_library_set().get('sources').get('vpx').get('path')
if library_path:
if is_windows():
library = ctypes.CDLL(library_path, winmode = 0)
else:
library = ctypes.CDLL(library_path)
if library:
return init_ctypes(library)
return None
def init_ctypes(library : ctypes.CDLL) -> ctypes.CDLL:
library.vpx_codec_enc_config_default.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint ]
library.vpx_codec_enc_config_default.restype = ctypes.c_int
library.vpx_codec_enc_init_ver.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_long, ctypes.c_int ]
library.vpx_codec_enc_init_ver.restype = ctypes.c_int
library.vpx_codec_encode.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64, ctypes.c_ulong, ctypes.c_long, ctypes.c_ulong ]
library.vpx_codec_encode.restype = ctypes.c_int
library.vpx_codec_get_cx_data.argtypes = [ ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p) ]
library.vpx_codec_get_cx_data.restype = ctypes.c_void_p
library.vpx_codec_enc_config_set.argtypes = [ ctypes.c_void_p, ctypes.c_void_p ]
library.vpx_codec_enc_config_set.restype = ctypes.c_int
library.vpx_codec_destroy.argtypes = [ ctypes.c_void_p ]
library.vpx_codec_destroy.restype = ctypes.c_int
library.vpx_img_wrap.argtypes = [ ctypes.c_void_p, ctypes.c_int, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint, ctypes.c_void_p ]
library.vpx_img_wrap.restype = ctypes.c_void_p
library.vpx_codec_control_.argtypes = [ ctypes.c_void_p, ctypes.c_int, ctypes.c_int ]
library.vpx_codec_control_.restype = ctypes.c_int
library.vpx_codec_dec_init_ver.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_long, ctypes.c_int ]
library.vpx_codec_dec_init_ver.restype = ctypes.c_int
library.vpx_codec_decode.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint, ctypes.c_void_p, ctypes.c_long ]
library.vpx_codec_decode.restype = ctypes.c_int
library.vpx_codec_get_frame.argtypes = [ ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p) ]
library.vpx_codec_get_frame.restype = ctypes.c_void_p
return library
+10 -12
View File
@@ -1,6 +1,6 @@
from facefusion.types import Locales
from facefusion.types import Locals
LOCALES : Locales =\
LOCALS : Locals =\
{
'en':
{
@@ -12,8 +12,11 @@ LOCALES : Locales =\
'extracting_frames': 'extracting frames with a resolution of {resolution} and {fps} frames per second',
'extracting_frames_succeeded': 'extracting frames succeeded',
'extracting_frames_failed': 'extracting frames failed',
'spawning_frames_succeeded': 'spawning frames succeeded',
'spawning_frames_failed': 'spawning frames failed',
'analysing': 'analysing',
'extracting': 'extracting',
'spawning': 'spawning',
'streaming': 'streaming',
'processing': 'processing',
'merging': 'merging',
@@ -48,10 +51,9 @@ LOCALES : Locales =\
'no_source_face_detected': 'no source face detected',
'processor_not_loaded': 'processor {processor} could not be loaded',
'processor_not_implemented': 'processor {processor} not implemented correctly',
'ui_layout_not_loaded': 'ui layout {ui_layout} could not be loaded',
'ui_layout_not_implemented': 'ui layout {ui_layout} not implemented correctly',
'stream_not_loaded': 'stream {stream_mode} could not be loaded',
'stream_not_supported': 'stream not supported',
'api_started': 'started API on {host}:{port}',
'job_created': 'job {job_id} created',
'job_not_created': 'job {job_id} not created',
'job_submitted': 'job {job_id} submitted',
@@ -99,6 +101,7 @@ LOCALES : Locales =\
{
'install_dependency': 'choose the variant of {dependency} to install',
'skip_conda': 'skip the conda environment check',
'workflow': 'choose the workflow',
'config_path': 'choose the config file to override defaults',
'temp_path': 'specify the directory for the temporary resources',
'jobs_path': 'specify the directory to store jobs',
@@ -135,7 +138,6 @@ LOCALES : Locales =\
'trim_frame_start': 'specify the starting frame of the target video',
'trim_frame_end': 'specify the ending frame of the target video',
'temp_frame_format': 'specify the temporary resources format',
'keep_temp': 'keep the temporary resources after processing',
'output_image_quality': 'specify the image quality which translates to the image compression',
'output_image_scale': 'specify the image scale based on the target image',
'output_audio_encoder': 'specify the encoder used for the audio',
@@ -149,26 +151,24 @@ LOCALES : Locales =\
'processors': 'load a single or multiple processors (choices: {choices}, ...)',
'background-remover-model': 'choose the model responsible for removing the background',
'background-remover-color': 'apply red, green blue and alpha values of the background',
'open_browser': 'open the browser once the program is ready',
'ui_layouts': 'launch a single or multiple UI layouts (choices: {choices}, ...)',
'ui_workflow': 'choose the ui workflow',
'download_providers': 'download using different providers (choices: {choices}, ...)',
'download_scope': 'specify the download scope',
'benchmark_mode': 'choose the benchmark mode',
'benchmark_resolutions': 'choose the resolutions for the benchmarks (choices: {choices}, ...)',
'benchmark_cycle_count': 'specify the amount of cycles per benchmark',
'api_host': 'specify the API host',
'api_port': 'specify the API port',
'execution_device_ids': 'specify the devices used for processing',
'execution_providers': 'inference using different providers (choices: {choices}, ...)',
'execution_thread_count': 'specify the amount of parallel threads while processing',
'video_memory_strategy': 'balance fast processing and low VRAM usage',
'system_memory_limit': 'limit the available RAM that can be used while processing',
'log_level': 'adjust the message severity displayed in the terminal',
'halt_on_error': 'halt the program once an error occurred',
'run': 'run the program',
'headless_run': 'run the program in headless mode',
'batch_run': 'run the program in batch mode',
'force_download': 'force automate downloads and exit',
'benchmark': 'benchmark the program',
'api': 'start the API server',
'job_id': 'specify the job id',
'job_status': 'specify the job status',
'step_index': 'specify the step index',
@@ -257,12 +257,10 @@ LOCALES : Locales =\
'source_file': 'SOURCE',
'start_button': 'START',
'stop_button': 'STOP',
'system_memory_limit_slider': 'SYSTEM MEMORY LIMIT',
'target_file': 'TARGET',
'temp_frame_format_dropdown': 'TEMP FRAME FORMAT',
'terminal_textbox': 'TERMINAL',
'trim_frame_slider': 'TRIM FRAME',
'ui_workflow': 'UI WORKFLOW',
'video_memory_strategy_dropdown': 'VIDEO MEMORY STRATEGY',
'webcam_fps_slider': 'WEBCAM FPS',
'webcam_image': 'WEBCAM',
+17
View File
@@ -0,0 +1,17 @@
from typing import Optional, Tuple
def restrict_trim_frame(frame_total : int, trim_frame_start : Optional[int], trim_frame_end : Optional[int]) -> Tuple[int, int]:
if isinstance(trim_frame_start, int):
trim_frame_start = max(0, min(trim_frame_start, frame_total))
if isinstance(trim_frame_end, int):
trim_frame_end = max(0, min(trim_frame_end, frame_total))
if isinstance(trim_frame_start, int) and isinstance(trim_frame_end, int):
return trim_frame_start, trim_frame_end
if isinstance(trim_frame_start, int):
return trim_frame_start, frame_total
if isinstance(trim_frame_end, int):
return 0, trim_frame_end
return 0, frame_total
-21
View File
@@ -1,21 +0,0 @@
from facefusion.common_helper import is_macos, is_windows
if is_windows():
import ctypes
else:
import resource
def limit_system_memory(system_memory_limit : int = 1) -> bool:
if is_macos():
system_memory_limit = system_memory_limit * (1024 ** 6)
else:
system_memory_limit = system_memory_limit * (1024 ** 3)
try:
if is_windows():
ctypes.windll.kernel32.SetProcessWorkingSetSize(-1, ctypes.c_size_t(system_memory_limit), ctypes.c_size_t(system_memory_limit)) #type:ignore[attr-defined]
else:
resource.setrlimit(resource.RLIMIT_DATA, (system_memory_limit, system_memory_limit))
return True
except Exception:
return False
+1 -1
View File
@@ -4,7 +4,7 @@ METADATA =\
{
'name': 'FaceFusion',
'description': 'Industry leading face manipulation platform',
'version': '3.5.2',
'version': 'v4',
'license': 'OpenRAIL-AS',
'author': 'Henry Ruhs',
'url': 'https://facefusion.io'
@@ -4,9 +4,9 @@ from functools import lru_cache
import cv2
import numpy
import facefusion.args_store
import facefusion.choices
import facefusion.jobs.job_manager
import facefusion.jobs.job_store
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, inference_manager, logger, state_manager, translator, video_manager
from facefusion.common_helper import create_int_metavar, is_macos
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
@@ -15,7 +15,7 @@ from facefusion.face_analyser import scale_face
from facefusion.face_helper import merge_matrix, paste_back, scale_face_landmark_5, warp_face_by_face_landmark_5
from facefusion.face_masker import create_box_mask, create_occlusion_mask
from facefusion.face_selector import select_faces
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path, same_file_extension
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path
from facefusion.processors.modules.age_modifier import choices as age_modifier_choices
from facefusion.processors.modules.age_modifier.types import AgeModifierDirection, AgeModifierInputs
from facefusion.processors.types import ProcessorOutputs
@@ -89,7 +89,7 @@ def register_args(program : ArgumentParser) -> None:
if group_processors:
group_processors.add_argument('--age-modifier-model', help = translator.get('help.model', __package__), default = config.get_str_value('processors', 'age_modifier_model', 'styleganex_age'), choices = age_modifier_choices.age_modifier_models)
group_processors.add_argument('--age-modifier-direction', help = translator.get('help.direction', __package__), type = int, default = config.get_int_value('processors', 'age_modifier_direction', '0'), choices = age_modifier_choices.age_modifier_direction_range, metavar = create_int_metavar(age_modifier_choices.age_modifier_direction_range))
facefusion.jobs.job_store.register_step_keys([ 'age_modifier_model', 'age_modifier_direction' ])
facefusion.args_store.register_args([ 'age_modifier_model', 'age_modifier_direction' ], scopes = [ 'api', 'cli' ])
def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
@@ -111,9 +111,6 @@ def pre_process(mode : ProcessMode) -> bool:
if mode == 'output' and not in_directory(state_manager.get_item('output_path')):
logger.error(translator.get('specify_image_or_video_output') + translator.get('exclamation_mark'), __name__)
return False
if mode == 'output' and not same_file_extension(state_manager.get_item('target_path'), state_manager.get_item('output_path')):
logger.error(translator.get('match_target_and_output_extension') + translator.get('exclamation_mark'), __name__)
return False
return True
@@ -1,6 +1,6 @@
from facefusion.types import Locales
from facefusion.types import Locals
LOCALES : Locales =\
LOCALS : Locals =\
{
'en':
{
@@ -5,13 +5,13 @@ from typing import List, Tuple
import cv2
import numpy
import facefusion.args_store
import facefusion.jobs.job_manager
import facefusion.jobs.job_store
from facefusion import config, content_analyser, inference_manager, logger, state_manager, translator, video_manager
from facefusion.common_helper import is_macos
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
from facefusion.execution import has_execution_provider
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path, same_file_extension
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path
from facefusion.normalizer import normalize_color
from facefusion.processors.modules.background_remover import choices as background_remover_choices
from facefusion.processors.modules.background_remover.types import BackgroundRemoverInputs
@@ -421,8 +421,8 @@ def register_args(program : ArgumentParser) -> None:
group_processors = find_argument_group(program, 'processors')
if group_processors:
group_processors.add_argument('--background-remover-model', help = translator.get('help.model', __package__), default = config.get_str_value('processors', 'background_remover_model', 'rmbg_2.0'), choices = background_remover_choices.background_remover_models)
group_processors.add_argument('--background-remover-color', help = translator.get('help.color', __package__), type = partial(sanitize_int_range, int_range = background_remover_choices.background_remover_color_range), default = config.get_int_list('processors', 'background_remover_color', '0 0 0 0'), nargs = '+')
facefusion.jobs.job_store.register_step_keys([ 'background_remover_model', 'background_remover_color' ])
group_processors.add_argument('--background-remover-color', help = translator.get('help.color', __package__), type = partial(sanitize_int_range, int_range = background_remover_choices.background_remover_color_range), default = config.get_int_list('processors', 'background_remover_color', '0 0 0 0'), nargs ='+')
facefusion.args_store.register_args([ 'background_remover_model', 'background_remover_color' ], scopes = [ 'api', 'cli' ])
def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
@@ -444,9 +444,6 @@ def pre_process(mode : ProcessMode) -> bool:
if mode == 'output' and not in_directory(state_manager.get_item('output_path')):
logger.error(translator.get('specify_image_or_video_output') + translator.get('exclamation_mark'), __name__)
return False
if mode == 'output' and not same_file_extension(state_manager.get_item('target_path'), state_manager.get_item('output_path')):
logger.error(translator.get('match_target_and_output_extension') + translator.get('exclamation_mark'), __name__)
return False
return True
@@ -1,6 +1,6 @@
from facefusion.types import Locales
from facefusion.types import Locals
LOCALES : Locales =\
LOCALS : Locals =\
{
'en':
{
@@ -6,8 +6,8 @@ import cv2
import numpy
from cv2.typing import Size
import facefusion.args_store
import facefusion.jobs.job_manager
import facefusion.jobs.job_store
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, inference_manager, logger, state_manager, translator, video_manager
from facefusion.common_helper import create_int_metavar
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url_by_provider
@@ -15,7 +15,7 @@ from facefusion.face_analyser import scale_face
from facefusion.face_helper import paste_back, warp_face_by_face_landmark_5
from facefusion.face_masker import create_area_mask, create_box_mask, create_occlusion_mask, create_region_mask
from facefusion.face_selector import select_faces
from facefusion.filesystem import get_file_name, in_directory, is_image, is_video, resolve_file_paths, resolve_relative_path, same_file_extension
from facefusion.filesystem import get_file_name, in_directory, is_image, is_video, resolve_file_paths, resolve_relative_path
from facefusion.processors.modules.deep_swapper import choices as deep_swapper_choices
from facefusion.processors.modules.deep_swapper.types import DeepSwapperInputs, DeepSwapperMorph
from facefusion.processors.types import ProcessorOutputs
@@ -278,7 +278,7 @@ def register_args(program : ArgumentParser) -> None:
if group_processors:
group_processors.add_argument('--deep-swapper-model', help = translator.get('help.model', __package__), default = config.get_str_value('processors', 'deep_swapper_model', 'iperov/elon_musk_224'), choices = deep_swapper_choices.deep_swapper_models)
group_processors.add_argument('--deep-swapper-morph', help = translator.get('help.morph', __package__), type = int, default = config.get_int_value('processors', 'deep_swapper_morph', '100'), choices = deep_swapper_choices.deep_swapper_morph_range, metavar = create_int_metavar(deep_swapper_choices.deep_swapper_morph_range))
facefusion.jobs.job_store.register_step_keys([ 'deep_swapper_model', 'deep_swapper_morph' ])
facefusion.args_store.register_args([ 'deep_swapper_model', 'deep_swapper_morph' ], scopes = [ 'api', 'cli' ])
def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
@@ -302,9 +302,6 @@ def pre_process(mode : ProcessMode) -> bool:
if mode == 'output' and not in_directory(state_manager.get_item('output_path')):
logger.error(translator.get('specify_image_or_video_output') + translator.get('exclamation_mark'), __name__)
return False
if mode == 'output' and not same_file_extension(state_manager.get_item('target_path'), state_manager.get_item('output_path')):
logger.error(translator.get('match_target_and_output_extension') + translator.get('exclamation_mark'), __name__)
return False
return True
@@ -1,6 +1,6 @@
from facefusion.types import Locales
from facefusion.types import Locals
LOCALES : Locales =\
LOCALS : Locals =\
{
'en':
{
@@ -5,8 +5,8 @@ from typing import Tuple
import cv2
import numpy
import facefusion.args_store
import facefusion.jobs.job_manager
import facefusion.jobs.job_store
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, inference_manager, logger, state_manager, translator, video_manager
from facefusion.common_helper import create_int_metavar
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
@@ -14,7 +14,7 @@ from facefusion.face_analyser import scale_face
from facefusion.face_helper import paste_back, warp_face_by_face_landmark_5
from facefusion.face_masker import create_box_mask, create_occlusion_mask
from facefusion.face_selector import select_faces
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path, same_file_extension
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path
from facefusion.processors.live_portrait import create_rotation, limit_expression
from facefusion.processors.modules.expression_restorer import choices as expression_restorer_choices
from facefusion.processors.modules.expression_restorer.types import ExpressionRestorerInputs
@@ -101,8 +101,8 @@ def register_args(program : ArgumentParser) -> None:
if group_processors:
group_processors.add_argument('--expression-restorer-model', help = translator.get('help.model', __package__), default = config.get_str_value('processors', 'expression_restorer_model', 'live_portrait'), choices = expression_restorer_choices.expression_restorer_models)
group_processors.add_argument('--expression-restorer-factor', help = translator.get('help.factor', __package__), type = int, default = config.get_int_value('processors', 'expression_restorer_factor', '80'), choices = expression_restorer_choices.expression_restorer_factor_range, metavar = create_int_metavar(expression_restorer_choices.expression_restorer_factor_range))
group_processors.add_argument('--expression-restorer-areas', help = translator.get('help.areas', __package__).format(choices = ', '.join(expression_restorer_choices.expression_restorer_areas)), default = config.get_str_list('processors', 'expression_restorer_areas', ' '.join(expression_restorer_choices.expression_restorer_areas)), choices = expression_restorer_choices.expression_restorer_areas, nargs = '+', metavar = 'EXPRESSION_RESTORER_AREAS')
facefusion.jobs.job_store.register_step_keys([ 'expression_restorer_model', 'expression_restorer_factor', 'expression_restorer_areas' ])
group_processors.add_argument('--expression-restorer-areas', help = translator.get('help.areas', __package__).format(choices = ', '.join(expression_restorer_choices.expression_restorer_areas)), default = config.get_str_list('processors', 'expression_restorer_areas', ' '.join(expression_restorer_choices.expression_restorer_areas)), choices = expression_restorer_choices.expression_restorer_areas, nargs ='+', metavar ='EXPRESSION_RESTORER_AREAS')
facefusion.args_store.register_args([ 'expression_restorer_model', 'expression_restorer_factor', 'expression_restorer_areas' ], scopes = [ 'api', 'cli' ])
def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
@@ -128,9 +128,6 @@ def pre_process(mode : ProcessMode) -> bool:
if mode == 'output' and not in_directory(state_manager.get_item('output_path')):
logger.error(translator.get('specify_image_or_video_output') + translator.get('exclamation_mark'), __name__)
return False
if mode == 'output' and not same_file_extension(state_manager.get_item('target_path'), state_manager.get_item('output_path')):
logger.error(translator.get('match_target_and_output_extension') + translator.get('exclamation_mark'), __name__)
return False
return True
@@ -1,6 +1,6 @@
from facefusion.types import Locales
from facefusion.types import Locals
LOCALES : Locales =\
LOCALS : Locals =\
{
'en':
{
@@ -3,14 +3,14 @@ from argparse import ArgumentParser
import cv2
import numpy
import facefusion.args_store
import facefusion.jobs.job_manager
import facefusion.jobs.job_store
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, logger, state_manager, translator, video_manager
from facefusion.face_analyser import scale_face
from facefusion.face_helper import warp_face_by_face_landmark_5
from facefusion.face_masker import create_area_mask, create_box_mask, create_occlusion_mask, create_region_mask
from facefusion.face_selector import select_faces
from facefusion.filesystem import in_directory, is_image, is_video, same_file_extension
from facefusion.filesystem import in_directory, is_image, is_video
from facefusion.processors.modules.face_debugger import choices as face_debugger_choices
from facefusion.processors.modules.face_debugger.types import FaceDebuggerInputs
from facefusion.processors.types import ProcessorOutputs
@@ -31,7 +31,7 @@ def register_args(program : ArgumentParser) -> None:
group_processors = find_argument_group(program, 'processors')
if group_processors:
group_processors.add_argument('--face-debugger-items', help = translator.get('help.items', __package__).format(choices = ', '.join(face_debugger_choices.face_debugger_items)), default = config.get_str_list('processors', 'face_debugger_items', 'face-landmark-5/68 face-mask'), choices = face_debugger_choices.face_debugger_items, nargs = '+', metavar = 'FACE_DEBUGGER_ITEMS')
facefusion.jobs.job_store.register_step_keys([ 'face_debugger_items' ])
facefusion.args_store.register_args([ 'face_debugger_items' ], scopes = [ 'api', 'cli' ])
def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
@@ -49,9 +49,6 @@ def pre_process(mode : ProcessMode) -> bool:
if mode == 'output' and not in_directory(state_manager.get_item('output_path')):
logger.error(translator.get('specify_image_or_video_output') + translator.get('exclamation_mark'), __name__)
return False
if mode == 'output' and not same_file_extension(state_manager.get_item('target_path'), state_manager.get_item('output_path')):
logger.error(translator.get('match_target_and_output_extension') + translator.get('exclamation_mark'), __name__)
return False
return True
@@ -1,6 +1,6 @@
from facefusion.types import Locales
from facefusion.types import Locals
LOCALES : Locales =\
LOCALS : Locals =\
{
'en':
{
@@ -5,8 +5,8 @@ from typing import Tuple
import cv2
import numpy
import facefusion.args_store
import facefusion.jobs.job_manager
import facefusion.jobs.job_store
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, inference_manager, logger, state_manager, translator, video_manager
from facefusion.common_helper import create_float_metavar
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
@@ -14,7 +14,7 @@ from facefusion.face_analyser import scale_face
from facefusion.face_helper import paste_back, scale_face_landmark_5, warp_face_by_face_landmark_5
from facefusion.face_masker import create_box_mask
from facefusion.face_selector import select_faces
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path, same_file_extension
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path
from facefusion.processors.live_portrait import create_rotation, limit_angle, limit_expression
from facefusion.processors.modules.face_editor import choices as face_editor_choices
from facefusion.processors.modules.face_editor.types import FaceEditorInputs
@@ -144,7 +144,7 @@ def register_args(program : ArgumentParser) -> None:
group_processors.add_argument('--face-editor-head-pitch', help = translator.get('help.head_pitch', __package__), type = float, default = config.get_float_value('processors', 'face_editor_head_pitch', '0'), choices = face_editor_choices.face_editor_head_pitch_range, metavar = create_float_metavar(face_editor_choices.face_editor_head_pitch_range))
group_processors.add_argument('--face-editor-head-yaw', help = translator.get('help.head_yaw', __package__), type = float, default = config.get_float_value('processors', 'face_editor_head_yaw', '0'), choices = face_editor_choices.face_editor_head_yaw_range, metavar = create_float_metavar(face_editor_choices.face_editor_head_yaw_range))
group_processors.add_argument('--face-editor-head-roll', help = translator.get('help.head_roll', __package__), type = float, default = config.get_float_value('processors', 'face_editor_head_roll', '0'), choices = face_editor_choices.face_editor_head_roll_range, metavar = create_float_metavar(face_editor_choices.face_editor_head_roll_range))
facefusion.jobs.job_store.register_step_keys([ 'face_editor_model', 'face_editor_eyebrow_direction', 'face_editor_eye_gaze_horizontal', 'face_editor_eye_gaze_vertical', 'face_editor_eye_open_ratio', 'face_editor_lip_open_ratio', 'face_editor_mouth_grim', 'face_editor_mouth_pout', 'face_editor_mouth_purse', 'face_editor_mouth_smile', 'face_editor_mouth_position_horizontal', 'face_editor_mouth_position_vertical', 'face_editor_head_pitch', 'face_editor_head_yaw', 'face_editor_head_roll' ])
facefusion.args_store.register_args([ 'face_editor_model', 'face_editor_eyebrow_direction', 'face_editor_eye_gaze_horizontal', 'face_editor_eye_gaze_vertical', 'face_editor_eye_open_ratio', 'face_editor_lip_open_ratio', 'face_editor_mouth_grim', 'face_editor_mouth_pout', 'face_editor_mouth_purse', 'face_editor_mouth_smile', 'face_editor_mouth_position_horizontal', 'face_editor_mouth_position_vertical', 'face_editor_head_pitch', 'face_editor_head_yaw', 'face_editor_head_roll' ], scopes = [ 'api', 'cli' ])
def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
@@ -179,9 +179,6 @@ def pre_process(mode : ProcessMode) -> bool:
if mode == 'output' and not in_directory(state_manager.get_item('output_path')):
logger.error(translator.get('specify_image_or_video_output') + translator.get('exclamation_mark'), __name__)
return False
if mode == 'output' and not same_file_extension(state_manager.get_item('target_path'), state_manager.get_item('output_path')):
logger.error(translator.get('match_target_and_output_extension') + translator.get('exclamation_mark'), __name__)
return False
return True
@@ -1,6 +1,6 @@
from facefusion.types import Locales
from facefusion.types import Locals
LOCALES : Locales =\
LOCALS : Locals =\
{
'en':
{
@@ -3,8 +3,8 @@ from functools import lru_cache
import numpy
import facefusion.args_store
import facefusion.jobs.job_manager
import facefusion.jobs.job_store
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, inference_manager, logger, state_manager, translator, video_manager
from facefusion.common_helper import create_float_metavar, create_int_metavar
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
@@ -12,7 +12,7 @@ from facefusion.face_analyser import scale_face
from facefusion.face_helper import paste_back, warp_face_by_face_landmark_5
from facefusion.face_masker import create_box_mask, create_occlusion_mask
from facefusion.face_selector import select_faces
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path, same_file_extension
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path
from facefusion.processors.modules.face_enhancer import choices as face_enhancer_choices
from facefusion.processors.modules.face_enhancer.types import FaceEnhancerInputs, FaceEnhancerWeight
from facefusion.processors.types import ProcessorOutputs
@@ -295,7 +295,7 @@ def register_args(program : ArgumentParser) -> None:
group_processors.add_argument('--face-enhancer-model', help = translator.get('help.model', __package__), default = config.get_str_value('processors', 'face_enhancer_model', 'gfpgan_1.4'), choices = face_enhancer_choices.face_enhancer_models)
group_processors.add_argument('--face-enhancer-blend', help = translator.get('help.blend', __package__), type = int, default = config.get_int_value('processors', 'face_enhancer_blend', '80'), choices = face_enhancer_choices.face_enhancer_blend_range, metavar = create_int_metavar(face_enhancer_choices.face_enhancer_blend_range))
group_processors.add_argument('--face-enhancer-weight', help = translator.get('help.weight', __package__), type = float, default = config.get_float_value('processors', 'face_enhancer_weight', '0.5'), choices = face_enhancer_choices.face_enhancer_weight_range, metavar = create_float_metavar(face_enhancer_choices.face_enhancer_weight_range))
facefusion.jobs.job_store.register_step_keys([ 'face_enhancer_model', 'face_enhancer_blend', 'face_enhancer_weight' ])
facefusion.args_store.register_args([ 'face_enhancer_model', 'face_enhancer_blend', 'face_enhancer_weight' ], scopes = [ 'api', 'cli' ])
def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
@@ -318,9 +318,6 @@ def pre_process(mode : ProcessMode) -> bool:
if mode == 'output' and not in_directory(state_manager.get_item('output_path')):
logger.error(translator.get('specify_image_or_video_output') + translator.get('exclamation_mark'), __name__)
return False
if mode == 'output' and not same_file_extension(state_manager.get_item('target_path'), state_manager.get_item('output_path')):
logger.error(translator.get('match_target_and_output_extension') + translator.get('exclamation_mark'), __name__)
return False
return True
@@ -1,6 +1,6 @@
from facefusion.types import Locales
from facefusion.types import Locals
LOCALES : Locales =\
LOCALS : Locals =\
{
'en':
{
@@ -5,9 +5,9 @@ from typing import List, Optional, Tuple
import cv2
import numpy
import facefusion.args_store
import facefusion.choices
import facefusion.jobs.job_manager
import facefusion.jobs.job_store
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, inference_manager, logger, state_manager, translator, video_manager
from facefusion.common_helper import get_first, is_macos
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
@@ -16,7 +16,7 @@ from facefusion.face_analyser import get_average_face, get_many_faces, get_one_f
from facefusion.face_helper import paste_back, warp_face_by_face_landmark_5
from facefusion.face_masker import create_area_mask, create_box_mask, create_occlusion_mask, create_region_mask
from facefusion.face_selector import select_faces, sort_faces_by_order
from facefusion.filesystem import filter_image_paths, has_image, in_directory, is_image, is_video, resolve_relative_path, same_file_extension
from facefusion.filesystem import filter_image_paths, has_image, in_directory, is_image, is_video, resolve_relative_path
from facefusion.model_helper import get_static_model_initializer
from facefusion.processors.modules.face_swapper import choices as face_swapper_choices
from facefusion.processors.modules.face_swapper.types import FaceSwapperInputs
@@ -518,7 +518,7 @@ def register_args(program : ArgumentParser) -> None:
face_swapper_pixel_boost_choices = face_swapper_choices.face_swapper_set.get(known_args.face_swapper_model)
group_processors.add_argument('--face-swapper-pixel-boost', help = translator.get('help.pixel_boost', __package__), default = config.get_str_value('processors', 'face_swapper_pixel_boost', get_first(face_swapper_pixel_boost_choices)), choices = face_swapper_pixel_boost_choices)
group_processors.add_argument('--face-swapper-weight', help = translator.get('help.weight', __package__), type = float, default = config.get_float_value('processors', 'face_swapper_weight', '0.5'), choices = face_swapper_choices.face_swapper_weight_range)
facefusion.jobs.job_store.register_step_keys([ 'face_swapper_model', 'face_swapper_pixel_boost', 'face_swapper_weight' ])
facefusion.args_store.register_args([ 'face_swapper_model', 'face_swapper_pixel_boost', 'face_swapper_weight' ], scopes = [ 'api', 'cli' ])
def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
@@ -555,10 +555,6 @@ def pre_process(mode : ProcessMode) -> bool:
logger.error(translator.get('specify_image_or_video_output') + translator.get('exclamation_mark'), __name__)
return False
if mode == 'output' and not same_file_extension(state_manager.get_item('target_path'), state_manager.get_item('output_path')):
logger.error(translator.get('match_target_and_output_extension') + translator.get('exclamation_mark'), __name__)
return False
return True
@@ -579,10 +575,12 @@ def post_process() -> None:
def swap_face(source_face : Face, target_face : Face, temp_vision_frame : VisionFrame) -> VisionFrame:
logger.debug('swap_face - starting face swap', __name__)
model_template = get_model_options().get('template')
model_size = get_model_options().get('size')
pixel_boost_size = unpack_resolution(state_manager.get_item('face_swapper_pixel_boost'))
pixel_boost_total = pixel_boost_size[0] // model_size[0]
logger.debug(f'swap_face - model_template: {model_template}, model_size: {model_size}, pixel_boost: {pixel_boost_size}', __name__)
crop_vision_frame, affine_matrix = warp_face_by_face_landmark_5(temp_vision_frame, target_face.landmark_set.get('5/68'), model_template, pixel_boost_size)
temp_vision_frames = []
crop_masks = []
@@ -763,12 +761,19 @@ def process_frame(inputs : FaceSwapperInputs) -> ProcessorOutputs:
target_vision_frame = inputs.get('target_vision_frame')
temp_vision_frame = inputs.get('temp_vision_frame')
temp_vision_mask = inputs.get('temp_vision_mask')
logger.debug(f'process_frame - source_vision_frames count: {len(source_vision_frames) if source_vision_frames else 0}', __name__)
source_face = extract_source_face(source_vision_frames)
logger.debug(f'process_frame - source_face extracted: {source_face is not None}', __name__)
target_faces = select_faces(reference_vision_frame, target_vision_frame)
logger.debug(f'process_frame - target_faces count: {len(target_faces) if target_faces else 0}', __name__)
if source_face and target_faces:
logger.debug(f'process_frame - swapping {len(target_faces)} faces', __name__)
for target_face in target_faces:
target_face = scale_face(target_face, target_vision_frame, temp_vision_frame)
temp_vision_frame = swap_face(source_face, target_face, temp_vision_frame)
logger.debug('process_frame - swap completed', __name__)
else:
logger.debug(f'process_frame - skipping swap (source_face={source_face is not None}, target_faces={target_faces is not None})', __name__)
return temp_vision_frame, temp_vision_mask
@@ -1,6 +1,6 @@
from facefusion.types import Locales
from facefusion.types import Locals
LOCALES : Locales =\
LOCALS : Locals =\
{
'en':
{
@@ -5,13 +5,13 @@ from typing import List
import cv2
import numpy
import facefusion.args_store
import facefusion.jobs.job_manager
import facefusion.jobs.job_store
from facefusion import config, content_analyser, inference_manager, logger, state_manager, translator, video_manager
from facefusion.common_helper import create_int_metavar, is_macos
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
from facefusion.execution import has_execution_provider
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path, same_file_extension
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path
from facefusion.processors.modules.frame_colorizer import choices as frame_colorizer_choices
from facefusion.processors.modules.frame_colorizer.types import FrameColorizerInputs
from facefusion.processors.types import ProcessorOutputs
@@ -187,7 +187,7 @@ def register_args(program : ArgumentParser) -> None:
group_processors.add_argument('--frame-colorizer-model', help = translator.get('help.model', __package__), default = config.get_str_value('processors', 'frame_colorizer_model', 'ddcolor'), choices = frame_colorizer_choices.frame_colorizer_models)
group_processors.add_argument('--frame-colorizer-size', help = translator.get('help.size', __package__), type = str, default = config.get_str_value('processors', 'frame_colorizer_size', '256x256'), choices = frame_colorizer_choices.frame_colorizer_sizes)
group_processors.add_argument('--frame-colorizer-blend', help = translator.get('help.blend', __package__), type = int, default = config.get_int_value('processors', 'frame_colorizer_blend', '100'), choices = frame_colorizer_choices.frame_colorizer_blend_range, metavar = create_int_metavar(frame_colorizer_choices.frame_colorizer_blend_range))
facefusion.jobs.job_store.register_step_keys([ 'frame_colorizer_model', 'frame_colorizer_blend', 'frame_colorizer_size' ])
facefusion.args_store.register_args([ 'frame_colorizer_model', 'frame_colorizer_blend', 'frame_colorizer_size' ], scopes = [ 'api', 'cli' ])
def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
@@ -210,9 +210,6 @@ def pre_process(mode : ProcessMode) -> bool:
if mode == 'output' and not in_directory(state_manager.get_item('output_path')):
logger.error(translator.get('specify_image_or_video_output') + translator.get('exclamation_mark'), __name__)
return False
if mode == 'output' and not same_file_extension(state_manager.get_item('target_path'), state_manager.get_item('output_path')):
logger.error(translator.get('match_target_and_output_extension') + translator.get('exclamation_mark'), __name__)
return False
return True
@@ -1,6 +1,6 @@
from facefusion.types import Locales
from facefusion.types import Locals
LOCALES : Locales =\
LOCALS : Locals =\
{
'en':
{
@@ -4,13 +4,13 @@ from functools import lru_cache
import cv2
import numpy
import facefusion.args_store
import facefusion.jobs.job_manager
import facefusion.jobs.job_store
from facefusion import config, content_analyser, inference_manager, logger, state_manager, translator, video_manager
from facefusion.common_helper import create_int_metavar, is_macos
from facefusion.download import conditional_download_hashes, conditional_download_sources, resolve_download_url
from facefusion.execution import has_execution_provider
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path, same_file_extension
from facefusion.filesystem import in_directory, is_image, is_video, resolve_relative_path
from facefusion.processors.modules.frame_enhancer import choices as frame_enhancer_choices
from facefusion.processors.modules.frame_enhancer.types import FrameEnhancerInputs
from facefusion.processors.types import ProcessorOutputs
@@ -575,7 +575,7 @@ def register_args(program : ArgumentParser) -> None:
if group_processors:
group_processors.add_argument('--frame-enhancer-model', help = translator.get('help.model', __package__), default = config.get_str_value('processors', 'frame_enhancer_model', 'span_kendata_x4'), choices = frame_enhancer_choices.frame_enhancer_models)
group_processors.add_argument('--frame-enhancer-blend', help = translator.get('help.blend', __package__), type = int, default = config.get_int_value('processors', 'frame_enhancer_blend', '80'), choices = frame_enhancer_choices.frame_enhancer_blend_range, metavar = create_int_metavar(frame_enhancer_choices.frame_enhancer_blend_range))
facefusion.jobs.job_store.register_step_keys([ 'frame_enhancer_model', 'frame_enhancer_blend' ])
facefusion.args_store.register_args([ 'frame_enhancer_model', 'frame_enhancer_blend' ], scopes = [ 'api', 'cli' ])
def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
@@ -597,9 +597,6 @@ def pre_process(mode : ProcessMode) -> bool:
if mode == 'output' and not in_directory(state_manager.get_item('output_path')):
logger.error(translator.get('specify_image_or_video_output') + translator.get('exclamation_mark'), __name__)
return False
if mode == 'output' and not same_file_extension(state_manager.get_item('target_path'), state_manager.get_item('output_path')):
logger.error(translator.get('match_target_and_output_extension') + translator.get('exclamation_mark'), __name__)
return False
return True
@@ -1,6 +1,6 @@
from facefusion.types import Locales
from facefusion.types import Locals
LOCALES : Locales =\
LOCALS : Locals =\
{
'en':
{
@@ -4,8 +4,8 @@ from functools import lru_cache
import cv2
import numpy
import facefusion.args_store
import facefusion.jobs.job_manager
import facefusion.jobs.job_store
from facefusion import config, content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, inference_manager, logger, state_manager, translator, video_manager, voice_extractor
from facefusion.audio import read_static_voice
from facefusion.common_helper import create_float_metavar
@@ -134,7 +134,7 @@ def register_args(program : ArgumentParser) -> None:
if group_processors:
group_processors.add_argument('--lip-syncer-model', help = translator.get('help.model', __package__), default = config.get_str_value('processors', 'lip_syncer_model', 'wav2lip_gan_96'), choices = lip_syncer_choices.lip_syncer_models)
group_processors.add_argument('--lip-syncer-weight', help = translator.get('help.weight', __package__), type = float, default = config.get_float_value('processors', 'lip_syncer_weight', '0.5'), choices = lip_syncer_choices.lip_syncer_weight_range, metavar = create_float_metavar(lip_syncer_choices.lip_syncer_weight_range))
facefusion.jobs.job_store.register_step_keys([ 'lip_syncer_model', 'lip_syncer_weight' ])
facefusion.args_store.register_args([ 'lip_syncer_model', 'lip_syncer_weight' ], scopes = [ 'api', 'cli' ])
def apply_args(args : Args, apply_state_item : ApplyStateItem) -> None:
@@ -1,6 +1,6 @@
from facefusion.types import Locales
from facefusion.types import Locals
LOCALES : Locales =\
LOCALS : Locals =\
{
'en':
{
+47 -44
View File
@@ -3,12 +3,11 @@ from argparse import ArgumentParser, HelpFormatter
from functools import partial
import facefusion.choices
from facefusion import config, metadata, state_manager, translator
from facefusion import args_store, config, metadata, state_manager, translator
from facefusion.common_helper import create_float_metavar, create_int_metavar, get_first, get_last
from facefusion.execution import get_available_execution_providers
from facefusion.ffmpeg import get_available_encoder_set
from facefusion.filesystem import get_file_name, resolve_file_paths
from facefusion.jobs import job_store
from facefusion.processors.core import get_processors_modules
from facefusion.sanitizer import sanitize_int_range
@@ -25,16 +24,24 @@ def create_config_path_program() -> ArgumentParser:
program = ArgumentParser(add_help = False)
group_paths = program.add_argument_group('paths')
group_paths.add_argument('--config-path', help = translator.get('help.config_path'), default = 'facefusion.ini')
job_store.register_job_keys([ 'config_path' ])
args_store.register_args([ 'config_path' ], scopes = [ 'cli' ])
apply_config_path(program)
return program
def create_workflow_program() -> ArgumentParser:
program = ArgumentParser(add_help = False)
group_paths = program.add_argument_group('paths')
group_paths.add_argument('--workflow', help = translator.get('help.workflow'), default = config.get_str_value('workflow', 'workflow', 'auto'), choices = facefusion.choices.workflows)
args_store.register_args([ 'workflow' ], scopes = [ 'api', 'cli' ])
return program
def create_temp_path_program() -> ArgumentParser:
program = ArgumentParser(add_help = False)
group_paths = program.add_argument_group('paths')
group_paths.add_argument('--temp-path', help = translator.get('help.temp_path'), default = config.get_str_value('paths', 'temp_path', tempfile.gettempdir()))
job_store.register_job_keys([ 'temp_path' ])
args_store.register_args([ 'temp_path' ], scopes = [ 'cli' ])
return program
@@ -42,7 +49,7 @@ def create_jobs_path_program() -> ArgumentParser:
program = ArgumentParser(add_help = False)
group_paths = program.add_argument_group('paths')
group_paths.add_argument('--jobs-path', help = translator.get('help.jobs_path'), default = config.get_str_value('paths', 'jobs_path', '.jobs'))
job_store.register_job_keys([ 'jobs_path' ])
args_store.register_args([ 'jobs_path' ], scopes = [ 'cli' ])
return program
@@ -50,7 +57,7 @@ def create_source_paths_program() -> ArgumentParser:
program = ArgumentParser(add_help = False)
group_paths = program.add_argument_group('paths')
group_paths.add_argument('-s', '--source-paths', help = translator.get('help.source_paths'), default = config.get_str_list('paths', 'source_paths'), nargs = '+')
job_store.register_step_keys([ 'source_paths' ])
args_store.register_args([ 'source_paths' ], scopes = [ 'cli' ])
return program
@@ -58,7 +65,7 @@ def create_target_path_program() -> ArgumentParser:
program = ArgumentParser(add_help = False)
group_paths = program.add_argument_group('paths')
group_paths.add_argument('-t', '--target-path', help = translator.get('help.target_path'), default = config.get_str_value('paths', 'target_path'))
job_store.register_step_keys([ 'target_path' ])
args_store.register_args([ 'target_path' ], scopes = [ 'cli' ])
return program
@@ -66,7 +73,7 @@ def create_output_path_program() -> ArgumentParser:
program = ArgumentParser(add_help = False)
group_paths = program.add_argument_group('paths')
group_paths.add_argument('-o', '--output-path', help = translator.get('help.output_path'), default = config.get_str_value('paths', 'output_path'))
job_store.register_step_keys([ 'output_path' ])
args_store.register_args([ 'output_path' ], scopes = [ 'cli' ])
return program
@@ -74,7 +81,7 @@ def create_source_pattern_program() -> ArgumentParser:
program = ArgumentParser(add_help = False)
group_patterns = program.add_argument_group('patterns')
group_patterns.add_argument('-s', '--source-pattern', help = translator.get('help.source_pattern'), default = config.get_str_value('patterns', 'source_pattern'))
job_store.register_job_keys([ 'source_pattern' ])
args_store.register_args([ 'source_pattern' ], scopes = [ 'cli' ])
return program
@@ -82,7 +89,7 @@ def create_target_pattern_program() -> ArgumentParser:
program = ArgumentParser(add_help = False)
group_patterns = program.add_argument_group('patterns')
group_patterns.add_argument('-t', '--target-pattern', help = translator.get('help.target_pattern'), default = config.get_str_value('patterns', 'target_pattern'))
job_store.register_job_keys([ 'target_pattern' ])
args_store.register_args([ 'target_pattern' ], scopes = [ 'cli' ])
return program
@@ -90,7 +97,7 @@ def create_output_pattern_program() -> ArgumentParser:
program = ArgumentParser(add_help = False)
group_patterns = program.add_argument_group('patterns')
group_patterns.add_argument('-o', '--output-pattern', help = translator.get('help.output_pattern'), default = config.get_str_value('patterns', 'output_pattern'))
job_store.register_job_keys([ 'output_pattern' ])
args_store.register_args([ 'output_pattern' ], scopes = [ 'cli' ])
return program
@@ -104,7 +111,7 @@ def create_face_detector_program() -> ArgumentParser:
group_face_detector.add_argument('--face-detector-margin', help = translator.get('help.face_detector_margin'), type = partial(sanitize_int_range, int_range = facefusion.choices.face_detector_margin_range), default = config.get_int_list('face_detector', 'face_detector_margin', '0 0 0 0'), nargs = '+')
group_face_detector.add_argument('--face-detector-angles', help = translator.get('help.face_detector_angles'), type = int, default = config.get_int_list('face_detector', 'face_detector_angles', '0'), choices = facefusion.choices.face_detector_angles, nargs = '+', metavar = 'FACE_DETECTOR_ANGLES')
group_face_detector.add_argument('--face-detector-score', help = translator.get('help.face_detector_score'), type = float, default = config.get_float_value('face_detector', 'face_detector_score', '0.5'), choices = facefusion.choices.face_detector_score_range, metavar = create_float_metavar(facefusion.choices.face_detector_score_range))
job_store.register_step_keys([ 'face_detector_model', 'face_detector_size', 'face_detector_margin', 'face_detector_angles', 'face_detector_score' ])
args_store.register_args([ 'face_detector_model', 'face_detector_size', 'face_detector_margin', 'face_detector_angles', 'face_detector_score' ], scopes = [ 'api', 'cli' ])
return program
@@ -113,7 +120,7 @@ def create_face_landmarker_program() -> ArgumentParser:
group_face_landmarker = program.add_argument_group('face landmarker')
group_face_landmarker.add_argument('--face-landmarker-model', help = translator.get('help.face_landmarker_model'), default = config.get_str_value('face_landmarker', 'face_landmarker_model', '2dfan4'), choices = facefusion.choices.face_landmarker_models)
group_face_landmarker.add_argument('--face-landmarker-score', help = translator.get('help.face_landmarker_score'), type = float, default = config.get_float_value('face_landmarker', 'face_landmarker_score', '0.5'), choices = facefusion.choices.face_landmarker_score_range, metavar = create_float_metavar(facefusion.choices.face_landmarker_score_range))
job_store.register_step_keys([ 'face_landmarker_model', 'face_landmarker_score' ])
args_store.register_args([ 'face_landmarker_model', 'face_landmarker_score' ], scopes = [ 'api', 'cli' ])
return program
@@ -129,7 +136,7 @@ def create_face_selector_program() -> ArgumentParser:
group_face_selector.add_argument('--reference-face-position', help = translator.get('help.reference_face_position'), type = int, default = config.get_int_value('face_selector', 'reference_face_position', '0'))
group_face_selector.add_argument('--reference-face-distance', help = translator.get('help.reference_face_distance'), type = float, default = config.get_float_value('face_selector', 'reference_face_distance', '0.3'), choices = facefusion.choices.reference_face_distance_range, metavar = create_float_metavar(facefusion.choices.reference_face_distance_range))
group_face_selector.add_argument('--reference-frame-number', help = translator.get('help.reference_frame_number'), type = int, default = config.get_int_value('face_selector', 'reference_frame_number', '0'))
job_store.register_step_keys([ 'face_selector_mode', 'face_selector_order', 'face_selector_gender', 'face_selector_race', 'face_selector_age_start', 'face_selector_age_end', 'reference_face_position', 'reference_face_distance', 'reference_frame_number' ])
args_store.register_args([ 'face_selector_mode', 'face_selector_order', 'face_selector_gender', 'face_selector_race', 'face_selector_age_start', 'face_selector_age_end', 'reference_face_position', 'reference_face_distance', 'reference_frame_number' ], scopes = [ 'api', 'cli' ])
return program
@@ -143,7 +150,7 @@ def create_face_masker_program() -> ArgumentParser:
group_face_masker.add_argument('--face-mask-regions', help = translator.get('help.face_mask_regions').format(choices = ', '.join(facefusion.choices.face_mask_regions)), default = config.get_str_list('face_masker', 'face_mask_regions', ' '.join(facefusion.choices.face_mask_regions)), choices = facefusion.choices.face_mask_regions, nargs = '+', metavar = 'FACE_MASK_REGIONS')
group_face_masker.add_argument('--face-mask-blur', help = translator.get('help.face_mask_blur'), type = float, default = config.get_float_value('face_masker', 'face_mask_blur', '0.3'), choices = facefusion.choices.face_mask_blur_range, metavar = create_float_metavar(facefusion.choices.face_mask_blur_range))
group_face_masker.add_argument('--face-mask-padding', help = translator.get('help.face_mask_padding'), type = partial(sanitize_int_range, int_range = facefusion.choices.face_mask_padding_range), default = config.get_int_list('face_masker', 'face_mask_padding', '0 0 0 0'), nargs = '+')
job_store.register_step_keys([ 'face_occluder_model', 'face_parser_model', 'face_mask_types', 'face_mask_areas', 'face_mask_regions', 'face_mask_blur', 'face_mask_padding' ])
args_store.register_args([ 'face_occluder_model', 'face_parser_model', 'face_mask_types', 'face_mask_areas', 'face_mask_regions', 'face_mask_blur', 'face_mask_padding' ], scopes = [ 'api', 'cli' ])
return program
@@ -151,7 +158,7 @@ def create_voice_extractor_program() -> ArgumentParser:
program = ArgumentParser(add_help = False)
group_voice_extractor = program.add_argument_group('voice extractor')
group_voice_extractor.add_argument('--voice-extractor-model', help = translator.get('help.voice_extractor_model'), default = config.get_str_value('voice_extractor', 'voice_extractor_model', 'kim_vocal_2'), choices = facefusion.choices.voice_extractor_models)
job_store.register_step_keys([ 'voice_extractor_model' ])
args_store.register_args([ 'voice_extractor_model' ], scopes = [ 'api', 'cli' ])
return program
@@ -161,8 +168,7 @@ def create_frame_extraction_program() -> ArgumentParser:
group_frame_extraction.add_argument('--trim-frame-start', help = translator.get('help.trim_frame_start'), type = int, default = facefusion.config.get_int_value('frame_extraction', 'trim_frame_start'))
group_frame_extraction.add_argument('--trim-frame-end', help = translator.get('help.trim_frame_end'), type = int, default = facefusion.config.get_int_value('frame_extraction', 'trim_frame_end'))
group_frame_extraction.add_argument('--temp-frame-format', help = translator.get('help.temp_frame_format'), default = config.get_str_value('frame_extraction', 'temp_frame_format', 'png'), choices = facefusion.choices.temp_frame_formats)
group_frame_extraction.add_argument('--keep-temp', help = translator.get('help.keep_temp'), action = 'store_true', default = config.get_bool_value('frame_extraction', 'keep_temp'))
job_store.register_step_keys([ 'trim_frame_start', 'trim_frame_end', 'temp_frame_format', 'keep_temp' ])
args_store.register_args([ 'trim_frame_start', 'trim_frame_end', 'temp_frame_format' ], scopes = [ 'api', 'cli' ])
return program
@@ -180,7 +186,7 @@ def create_output_creation_program() -> ArgumentParser:
group_output_creation.add_argument('--output-video-quality', help = translator.get('help.output_video_quality'), type = int, default = config.get_int_value('output_creation', 'output_video_quality', '80'), choices = facefusion.choices.output_video_quality_range, metavar = create_int_metavar(facefusion.choices.output_video_quality_range))
group_output_creation.add_argument('--output-video-scale', help = translator.get('help.output_video_scale'), type = float, default = config.get_float_value('output_creation', 'output_video_scale', '1.0'), choices = facefusion.choices.output_video_scale_range)
group_output_creation.add_argument('--output-video-fps', help = translator.get('help.output_video_fps'), type = float, default = config.get_float_value('output_creation', 'output_video_fps'))
job_store.register_step_keys([ 'output_image_quality', 'output_image_scale', 'output_audio_encoder', 'output_audio_quality', 'output_audio_volume', 'output_video_encoder', 'output_video_preset', 'output_video_quality', 'output_video_scale', 'output_video_fps' ])
args_store.register_args([ 'output_image_quality', 'output_image_scale', 'output_audio_encoder', 'output_audio_quality', 'output_audio_volume', 'output_video_encoder', 'output_video_preset', 'output_video_quality', 'output_video_scale', 'output_video_fps' ], scopes = [ 'api', 'cli' ])
return program
@@ -189,27 +195,17 @@ def create_processors_program() -> ArgumentParser:
available_processors = [ get_file_name(file_path) for file_path in resolve_file_paths('facefusion/processors/modules') ]
group_processors = program.add_argument_group('processors')
group_processors.add_argument('--processors', help = translator.get('help.processors').format(choices = ', '.join(available_processors)), default = config.get_str_list('processors', 'processors', 'face_swapper'), nargs = '+')
job_store.register_step_keys([ 'processors' ])
args_store.register_args([ 'processors' ], scopes = [ 'api', 'cli' ])
for processor_module in get_processors_modules(available_processors):
processor_module.register_args(program)
return program
def create_uis_program() -> ArgumentParser:
program = ArgumentParser(add_help = False)
available_ui_layouts = [ get_file_name(file_path) for file_path in resolve_file_paths('facefusion/uis/layouts') ]
group_uis = program.add_argument_group('uis')
group_uis.add_argument('--open-browser', help = translator.get('help.open_browser'), action = 'store_true', default = config.get_bool_value('uis', 'open_browser'))
group_uis.add_argument('--ui-layouts', help = translator.get('help.ui_layouts').format(choices = ', '.join(available_ui_layouts)), default = config.get_str_list('uis', 'ui_layouts', 'default'), nargs = '+')
group_uis.add_argument('--ui-workflow', help = translator.get('help.ui_workflow'), default = config.get_str_value('uis', 'ui_workflow', 'instant_runner'), choices = facefusion.choices.ui_workflows)
return program
def create_download_providers_program() -> ArgumentParser:
program = ArgumentParser(add_help = False)
group_download = program.add_argument_group('download')
group_download.add_argument('--download-providers', help = translator.get('help.download_providers').format(choices = ', '.join(facefusion.choices.download_providers)), default = config.get_str_list('download', 'download_providers', ' '.join(facefusion.choices.download_providers)), choices = facefusion.choices.download_providers, nargs = '+', metavar = 'DOWNLOAD_PROVIDERS')
job_store.register_job_keys([ 'download_providers' ])
args_store.register_args([ 'download_providers' ], scopes = [ 'cli', 'sys' ])
return program
@@ -217,7 +213,7 @@ def create_download_scope_program() -> ArgumentParser:
program = ArgumentParser(add_help = False)
group_download = program.add_argument_group('download')
group_download.add_argument('--download-scope', help = translator.get('help.download_scope'), default = config.get_str_value('download', 'download_scope', 'lite'), choices = facefusion.choices.download_scopes)
job_store.register_job_keys([ 'download_scope' ])
args_store.register_args([ 'download_scope' ], scopes = [ 'cli', 'sys' ])
return program
@@ -230,14 +226,22 @@ def create_benchmark_program() -> ArgumentParser:
return program
def create_api_program() -> ArgumentParser:
program = ArgumentParser(add_help = False)
group_api = program.add_argument_group('api')
group_api.add_argument('--api-host', help = translator.get('help.api_host'), default = config.get_str_value('api', 'api_host', '127.0.0.1'))
group_api.add_argument('--api-port', help = translator.get('help.api_port'), type = int, default = config.get_int_value('api', 'api_port', '8000'))
return program
def create_execution_program() -> ArgumentParser:
program = ArgumentParser(add_help = False)
available_execution_providers = get_available_execution_providers()
group_execution = program.add_argument_group('execution')
group_execution.add_argument('--execution-device-ids', help = translator.get('help.execution_device_ids'), type = int, default = config.get_int_list('execution', 'execution_device_ids', '0'), nargs = '+', metavar = 'EXECUTION_DEVICE_IDS')
group_execution.add_argument('--execution-device-ids', help = translator.get('help.execution_device_ids'), type = int, default = config.get_str_list('execution', 'execution_device_ids', '0'), nargs = '+', metavar = 'EXECUTION_DEVICE_IDS')
group_execution.add_argument('--execution-providers', help = translator.get('help.execution_providers').format(choices = ', '.join(available_execution_providers)), default = config.get_str_list('execution', 'execution_providers', get_first(available_execution_providers)), choices = available_execution_providers, nargs = '+', metavar = 'EXECUTION_PROVIDERS')
group_execution.add_argument('--execution-thread-count', help = translator.get('help.execution_thread_count'), type = int, default = config.get_int_value('execution', 'execution_thread_count', '8'), choices = facefusion.choices.execution_thread_count_range, metavar = create_int_metavar(facefusion.choices.execution_thread_count_range))
job_store.register_job_keys([ 'execution_device_ids', 'execution_providers', 'execution_thread_count' ])
args_store.register_args([ 'execution_device_ids', 'execution_providers', 'execution_thread_count' ], scopes = [ 'api', 'cli', 'sys' ])
return program
@@ -245,8 +249,7 @@ def create_memory_program() -> ArgumentParser:
program = ArgumentParser(add_help = False)
group_memory = program.add_argument_group('memory')
group_memory.add_argument('--video-memory-strategy', help = translator.get('help.video_memory_strategy'), default = config.get_str_value('memory', 'video_memory_strategy', 'strict'), choices = facefusion.choices.video_memory_strategies)
group_memory.add_argument('--system-memory-limit', help = translator.get('help.system_memory_limit'), type = int, default = config.get_int_value('memory', 'system_memory_limit', '0'), choices = facefusion.choices.system_memory_limit_range, metavar = create_int_metavar(facefusion.choices.system_memory_limit_range))
job_store.register_job_keys([ 'video_memory_strategy', 'system_memory_limit' ])
args_store.register_args([ 'video_memory_strategy' ], scopes = [ 'cli', 'sys' ])
return program
@@ -254,7 +257,7 @@ def create_log_level_program() -> ArgumentParser:
program = ArgumentParser(add_help = False)
group_misc = program.add_argument_group('misc')
group_misc.add_argument('--log-level', help = translator.get('help.log_level'), default = config.get_str_value('misc', 'log_level', 'info'), choices = facefusion.choices.log_levels)
job_store.register_job_keys([ 'log_level' ])
args_store.register_args([ 'log_level' ], scopes = [ 'cli' ])
return program
@@ -262,7 +265,7 @@ def create_halt_on_error_program() -> ArgumentParser:
program = ArgumentParser(add_help = False)
group_misc = program.add_argument_group('misc')
group_misc.add_argument('--halt-on-error', help = translator.get('help.halt_on_error'), action = 'store_true', default = config.get_bool_value('misc', 'halt_on_error'))
job_store.register_job_keys([ 'halt_on_error' ])
args_store.register_args([ 'halt_on_error' ], scopes = [ 'cli' ])
return program
@@ -289,7 +292,7 @@ def collect_step_program() -> ArgumentParser:
def collect_job_program() -> ArgumentParser:
return ArgumentParser(parents = [ create_execution_program(), create_download_providers_program(), create_memory_program(), create_log_level_program() ], add_help = False)
return ArgumentParser(parents = [ create_workflow_program(), create_execution_program(), create_download_providers_program(), create_memory_program(), create_log_level_program() ], add_help = False)
def create_program() -> ArgumentParser:
@@ -298,11 +301,11 @@ def create_program() -> ArgumentParser:
program.add_argument('-v', '--version', version = metadata.get('name') + ' ' + metadata.get('version'), action = 'version')
sub_program = program.add_subparsers(dest = 'command')
# general
sub_program.add_parser('run', help = translator.get('help.run'), parents = [ create_config_path_program(), create_temp_path_program(), create_jobs_path_program(), create_source_paths_program(), create_target_path_program(), create_output_path_program(), collect_step_program(), create_uis_program(), create_benchmark_program(), collect_job_program() ], formatter_class = create_help_formatter_large)
sub_program.add_parser('headless-run', help = translator.get('help.headless_run'), parents = [ create_config_path_program(), create_temp_path_program(), create_jobs_path_program(), create_source_paths_program(), create_target_path_program(), create_output_path_program(), collect_step_program(), collect_job_program() ], formatter_class = create_help_formatter_large)
sub_program.add_parser('run', help = translator.get('help.run'), parents = [ create_config_path_program(), create_temp_path_program(), create_jobs_path_program(), create_source_paths_program(), create_target_path_program(), create_output_path_program(), collect_step_program(), collect_job_program() ], formatter_class = create_help_formatter_large)
sub_program.add_parser('batch-run', help = translator.get('help.batch_run'), parents = [ create_config_path_program(), create_temp_path_program(), create_jobs_path_program(), create_source_pattern_program(), create_target_pattern_program(), create_output_pattern_program(), collect_step_program(), collect_job_program() ], formatter_class = create_help_formatter_large)
sub_program.add_parser('force-download', help = translator.get('help.force_download'), parents = [ create_download_providers_program(), create_download_scope_program(), create_log_level_program() ], formatter_class = create_help_formatter_large)
sub_program.add_parser('benchmark', help = translator.get('help.benchmark'), parents = [ create_temp_path_program(), collect_step_program(), create_benchmark_program(), collect_job_program() ], formatter_class = create_help_formatter_large)
sub_program.add_parser('api', help = translator.get('help.api'), parents = [ create_config_path_program(), create_temp_path_program(), create_jobs_path_program(), create_api_program(), collect_step_program(), collect_job_program() ], formatter_class = create_help_formatter_large)
# job manager
sub_program.add_parser('job-list', help = translator.get('help.job_list'), parents = [ create_job_status_program(), create_jobs_path_program(), create_log_level_program() ], formatter_class = create_help_formatter_large)
sub_program.add_parser('job-create', help = translator.get('help.job_create'), parents = [ create_job_id_program(), create_jobs_path_program(), create_log_level_program() ], formatter_class = create_help_formatter_large)
@@ -310,9 +313,9 @@ def create_program() -> ArgumentParser:
sub_program.add_parser('job-submit-all', help = translator.get('help.job_submit_all'), parents = [ create_jobs_path_program(), create_log_level_program(), create_halt_on_error_program() ], formatter_class = create_help_formatter_large)
sub_program.add_parser('job-delete', help = translator.get('help.job_delete'), parents = [ create_job_id_program(), create_jobs_path_program(), create_log_level_program() ], formatter_class = create_help_formatter_large)
sub_program.add_parser('job-delete-all', help = translator.get('help.job_delete_all'), parents = [ create_jobs_path_program(), create_log_level_program(), create_halt_on_error_program() ], formatter_class = create_help_formatter_large)
sub_program.add_parser('job-add-step', help = translator.get('help.job_add_step'), parents = [ create_job_id_program(), create_config_path_program(), create_jobs_path_program(), create_source_paths_program(), create_target_path_program(), create_output_path_program(), collect_step_program(), create_log_level_program() ], formatter_class = create_help_formatter_large)
sub_program.add_parser('job-remix-step', help = translator.get('help.job_remix_step'), parents = [ create_job_id_program(), create_step_index_program(), create_config_path_program(), create_jobs_path_program(), create_source_paths_program(), create_output_path_program(), collect_step_program(), create_log_level_program() ], formatter_class = create_help_formatter_large)
sub_program.add_parser('job-insert-step', help = translator.get('help.job_insert_step'), parents = [ create_job_id_program(), create_step_index_program(), create_config_path_program(), create_jobs_path_program(), create_source_paths_program(), create_target_path_program(), create_output_path_program(), collect_step_program(), create_log_level_program() ], formatter_class = create_help_formatter_large)
sub_program.add_parser('job-add-step', help = translator.get('help.job_add_step'), parents = [ create_job_id_program(), create_workflow_program(), create_config_path_program(), create_jobs_path_program(), create_source_paths_program(), create_target_path_program(), create_output_path_program(), collect_step_program(), create_log_level_program() ], formatter_class = create_help_formatter_large)
sub_program.add_parser('job-remix-step', help = translator.get('help.job_remix_step'), parents = [ create_job_id_program(), create_workflow_program(), create_step_index_program(), create_config_path_program(), create_jobs_path_program(), create_source_paths_program(), create_output_path_program(), collect_step_program(), create_log_level_program() ], formatter_class = create_help_formatter_large)
sub_program.add_parser('job-insert-step', help = translator.get('help.job_insert_step'), parents = [ create_job_id_program(), create_workflow_program(), create_step_index_program(), create_config_path_program(), create_jobs_path_program(), create_source_paths_program(), create_target_path_program(), create_output_path_program(), collect_step_program(), create_log_level_program() ], formatter_class = create_help_formatter_large)
sub_program.add_parser('job-remove-step', help = translator.get('help.job_remove_step'), parents = [ create_job_id_program(), create_step_index_program(), create_jobs_path_program(), create_log_level_program() ], formatter_class = create_help_formatter_large)
# job runner
sub_program.add_parser('job-run', help = translator.get('help.job_run'), parents = [ create_job_id_program(), create_config_path_program(), create_temp_path_program(), create_jobs_path_program(), collect_job_program() ], formatter_class = create_help_formatter_large)
+263
View File
@@ -0,0 +1,263 @@
import ctypes
from typing import List, Optional
from facefusion.libraries import datachannel as datachannel_module
from facefusion.types import AudioCodec, BitRate, MediaDirection, PeerConnection, RtcAudioTrack, RtcPeer, RtcTrackInit, RtcVideoTrack, SdpAnswer, SdpOffer, VideoCodec
def create_peer_connection() -> PeerConnection:
datachannel_library = datachannel_module.create_static_library()
rtc_configuration = datachannel_module.define_rtc_configuration()
rtc_configuration.enableIceUdpMux = True
rtc_configuration.forceMediaTransport = True
rtc_configuration.disableAutoNegotiation = True
return datachannel_library.rtcCreatePeerConnection(ctypes.byref(rtc_configuration))
def create_sdp_offer(peer_connection : PeerConnection) -> Optional[SdpOffer]:
datachannel_library = datachannel_module.create_static_library()
datachannel_library.rtcSetLocalDescription(peer_connection, b'offer')
sdp_buffer = ctypes.create_string_buffer(8192)
if datachannel_library.rtcGetLocalDescription(peer_connection, sdp_buffer, 8192):
return sdp_buffer.value.decode()
return None
def create_sdp_answer(peer_connection : PeerConnection) -> Optional[SdpAnswer]:
datachannel_library = datachannel_module.create_static_library()
datachannel_library.rtcSetLocalDescription(peer_connection, b'answer')
sdp_buffer = ctypes.create_string_buffer(8192)
if datachannel_library.rtcGetLocalDescription(peer_connection, sdp_buffer, 8192):
return sdp_buffer.value.decode()
return None
def set_remote_description(peer_connection : PeerConnection, sdp_offer : SdpOffer) -> None:
datachannel_library = datachannel_module.create_static_library()
datachannel_library.rtcSetRemoteDescription(peer_connection, sdp_offer.encode(), b'offer')
return None
def send_video(rtc_peer : RtcPeer, video_buffer : bytes, video_timestamp : int) -> None:
datachannel_library = datachannel_module.create_static_library()
if rtc_peer.get('video'):
video_track = rtc_peer.get('video').get('sender_track')
if datachannel_library.rtcIsOpen(video_track):
video_total = len(video_buffer)
datachannel_library.rtcSetTrackRtpTimestamp(video_track, video_timestamp)
datachannel_library.rtcSendMessage(video_track, video_buffer, video_total)
return None
def send_audio(rtc_peer : RtcPeer, audio_buffer : bytes, audio_timestamp : int) -> None:
datachannel_library = datachannel_module.create_static_library()
if rtc_peer.get('audio'):
audio_track = rtc_peer.get('audio').get('sender_track')
if datachannel_library.rtcIsOpen(audio_track):
audio_total = len(audio_buffer)
datachannel_library.rtcSetTrackRtpTimestamp(audio_track, audio_timestamp)
datachannel_library.rtcSendMessage(audio_track, audio_buffer, audio_total)
return None
def delete_peers(rtc_peers : List[RtcPeer]) -> None:
datachannel_library = datachannel_module.create_static_library()
for rtc_peer in rtc_peers:
peer_connection = rtc_peer.get('peer_connection')
if peer_connection:
datachannel_library.rtcDeletePeerConnection(peer_connection)
return None
def add_audio_track(peer_connection : PeerConnection, media_direction : MediaDirection, audio_codec : AudioCodec, payload_type : int) -> RtcAudioTrack:
datachannel_library = datachannel_module.create_static_library()
audio_track_init = create_audio_track_init(media_direction, audio_codec, payload_type)
audio_track = datachannel_library.rtcAddTrackEx(peer_connection, audio_track_init)
if media_direction == 'sendonly':
audio_packetizer = datachannel_module.define_rtc_packetizer_init()
audio_packetizer.ssrc = 43
audio_packetizer.cname = b'audio'
audio_packetizer.payloadType = payload_type
audio_packetizer.clockRate = 48000
if audio_codec == 'opus':
datachannel_library.rtcSetOpusPacketizer(audio_track, ctypes.byref(audio_packetizer))
datachannel_library.rtcChainRtcpSrReporter(audio_track)
if media_direction == 'recvonly':
audio_depacketizer = datachannel_module.define_rtc_packetizer_init()
audio_depacketizer.ssrc = 0
audio_depacketizer.cname = b'audio'
audio_depacketizer.payloadType = payload_type
audio_depacketizer.clockRate = 48000
if audio_codec == 'opus':
datachannel_library.rtcSetOpusDepacketizer(audio_track, ctypes.byref(audio_depacketizer))
datachannel_library.rtcChainRtcpReceivingSession(audio_track)
return audio_track
def add_video_track(peer_connection : PeerConnection, media_direction : MediaDirection, video_codec : VideoCodec, payload_type : int) -> RtcVideoTrack:
datachannel_library = datachannel_module.create_static_library()
video_track_init = create_video_track_init(media_direction, video_codec, payload_type)
video_track = datachannel_library.rtcAddTrackEx(peer_connection, video_track_init)
if media_direction == 'sendonly':
video_packetizer = datachannel_module.define_rtc_packetizer_init()
video_packetizer.ssrc = 42
video_packetizer.cname = b'video'
video_packetizer.payloadType = payload_type
video_packetizer.clockRate = 90000
video_packetizer.maxFragmentSize = 1200
if video_codec == 'av1':
video_packetizer.obuPacketization = 1
datachannel_library.rtcSetAV1Packetizer(video_track, ctypes.byref(video_packetizer))
if video_codec == 'vp8':
datachannel_library.rtcSetVP8Packetizer(video_track, ctypes.byref(video_packetizer))
if video_codec == 'vp9':
datachannel_library.rtcSetVP9Packetizer(video_track, ctypes.byref(video_packetizer))
datachannel_library.rtcChainRtcpSrReporter(video_track)
datachannel_library.rtcChainRtcpNackResponder(video_track, 512)
if media_direction == 'recvonly':
if video_codec == 'av1':
datachannel_library.rtcSetAV1Depacketizer(video_track, 1)
if video_codec == 'vp8':
video_depacketizer = datachannel_module.define_rtc_packetizer_init()
video_depacketizer.ssrc = 0
video_depacketizer.cname = b'video'
video_depacketizer.payloadType = payload_type
video_depacketizer.clockRate = 90000
datachannel_library.rtcSetVP8Depacketizer(video_track, ctypes.byref(video_depacketizer))
if video_codec == 'vp9':
video_depacketizer = datachannel_module.define_rtc_packetizer_init()
video_depacketizer.ssrc = 0
video_depacketizer.cname = b'video'
video_depacketizer.payloadType = payload_type
video_depacketizer.clockRate = 90000
datachannel_library.rtcSetVP9Depacketizer(video_track, ctypes.byref(video_depacketizer))
datachannel_library.rtcChainRtcpReceivingSession(video_track)
return video_track
def create_audio_track_init(media_direction : MediaDirection, audio_codec : AudioCodec, payload_type : int) -> RtcTrackInit:
track_init = datachannel_module.define_rtc_track_init()
track_init.name = b'audio'
track_init.payloadType = payload_type
if media_direction == 'sendonly':
track_init.direction = 1
track_init.mid = b'3'
track_init.ssrc = 43
if media_direction == 'recvonly':
track_init.direction = 2
track_init.mid = b'2'
track_init.ssrc = 45
if media_direction == 'sendrecv':
track_init.direction = 3
track_init.mid = b'1'
track_init.ssrc = 43
if audio_codec == 'opus':
track_init.codec = 128
return ctypes.byref(track_init)
def create_video_track_init(media_direction : MediaDirection, video_codec : VideoCodec, payload_type : int) -> RtcTrackInit:
track_init = datachannel_module.define_rtc_track_init()
track_init.name = b'video'
track_init.payloadType = payload_type
if media_direction == 'sendonly':
track_init.direction = 1
track_init.mid = b'1'
track_init.ssrc = 42
if media_direction == 'recvonly':
track_init.direction = 2
track_init.mid = b'0'
track_init.ssrc = 44
if media_direction == 'sendrecv':
track_init.direction = 3
track_init.mid = b'0'
track_init.ssrc = 42
if video_codec == 'av1':
track_init.codec = 4
if video_codec == 'vp8':
track_init.codec = 1
if video_codec == 'vp9':
track_init.codec = 2
return ctypes.byref(track_init)
def get_payload_type(sdp_offer : SdpOffer, codec : AudioCodec | VideoCodec) -> int:
datachannel_library = datachannel_module.create_static_library()
payload_type_buffer = (ctypes.c_int * 16)()
payload_type_total = datachannel_library.rtcGetPayloadTypesForCodec(sdp_offer.encode(), codec.lower().encode(), payload_type_buffer, 16)
if payload_type_total:
return payload_type_buffer[0]
return 0
@ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_uint, ctypes.c_void_p)
def handle_sender_bitrate(_ : int, bitrate : BitRate, pointer : int) -> None:
ctypes.cast(pointer, ctypes.POINTER(ctypes.c_uint)).contents.value = bitrate // 1000
def wire_sender_bitrate(video_track : RtcVideoTrack, bitrate : ctypes.c_uint) -> None:
datachannel_library = datachannel_module.create_static_library()
datachannel_library.rtcSetUserPointer(video_track, ctypes.cast(ctypes.byref(bitrate), ctypes.c_void_p))
datachannel_library.rtcChainRembHandler(video_track, handle_sender_bitrate)
def adapt_receiver_bitrate(rtc_peer : RtcPeer, bitrate : BitRate) -> None:
datachannel_library = datachannel_module.create_static_library()
receiver_track = rtc_peer.get('video').get('receiver_track')
rtc_peer.get('receiver_bitrate').value = bitrate
datachannel_library.rtcRequestBitrate(receiver_track, bitrate * 1000)
def clear_bitrate(rtc_peer : RtcPeer) -> None:
rtc_peer.get('sender_bitrate').value = 0
rtc_peer.get('receiver_bitrate').value = 0
+33
View File
@@ -0,0 +1,33 @@
from typing import List
from facefusion import rtc
from facefusion.types import RtcPeer, RtcStore, SessionId
RTC_STORE : RtcStore = {}
def init_peers(session_id : SessionId) -> None:
RTC_STORE[session_id] = []
def has_peers(session_id : SessionId) -> bool:
return bool(RTC_STORE.get(session_id))
def get_peers(session_id : SessionId) -> List[RtcPeer]:
return RTC_STORE.get(session_id)
def delete_peers(session_id : SessionId) -> None:
if session_id in RTC_STORE:
rtc_peers = get_peers(session_id)
if rtc_peers:
rtc.delete_peers(rtc_peers)
del RTC_STORE[session_id]
return None
def clear() -> None:
RTC_STORE.clear()
+18
View File
@@ -0,0 +1,18 @@
from contextvars import ContextVar
from typing import Optional
from facefusion.types import SessionId
SESSION_ID : ContextVar[Optional[SessionId]] = ContextVar('SESSION_ID', default = None)
def set_session_id(session_id : SessionId) -> None:
SESSION_ID.set(session_id)
def get_session_id() -> Optional[SessionId]:
return SESSION_ID.get()
def clear_session_id() -> None:
SESSION_ID.set(None)
+46
View File
@@ -0,0 +1,46 @@
import secrets
from datetime import datetime, timedelta
from typing import Dict
from typing import Optional
from facefusion.types import Session, SessionId
SESSIONS : Dict[SessionId, Session] = {}
def create_session() -> Session:
session : Session =\
{
'access_token': secrets.token_urlsafe(64),
'refresh_token': secrets.token_urlsafe(64),
'created_at': datetime.now(),
'expires_at': datetime.now() + timedelta(minutes = 10)
}
return session
def get_session(session_id : SessionId) -> Optional[Session]:
return SESSIONS.get(session_id)
def find_session_id(access_token : str) -> Optional[SessionId]:
for session_id, session in SESSIONS.items():
if session.get('access_token') == access_token:
return session_id
return None
def set_session(session_id : SessionId, session : Session) -> None:
SESSIONS[session_id] = session
def validate_session(session_id : SessionId) -> bool:
session = get_session(session_id)
return session and datetime.now() <= session.get('expires_at')
def clear_session(session_id : SessionId) -> None:
if session_id in SESSIONS:
del SESSIONS[session_id]
+31 -11
View File
@@ -1,28 +1,34 @@
import os
from typing import Any, Union
from facefusion.app_context import detect_app_context
from facefusion.processors.types import ProcessorState, ProcessorStateKey, ProcessorStateSet
from facefusion.types import State, StateKey, StateSet
from facefusion.session_context import get_session_id
from facefusion.types import Args, State, StateKey, StateSet
STATE_SET : Union[StateSet, ProcessorStateSet] =\
{
'cli': {}, #type:ignore[assignment]
'ui': {} #type:ignore[assignment]
'api': {}, #type:ignore[assignment]
'cli': {} #type:ignore[assignment]
}
def get_state() -> Union[State, ProcessorState]:
app_context = detect_app_context()
return STATE_SET.get(app_context)
return STATE_SET.get(app_context) #type:ignore[return-value]
def sync_state() -> None:
STATE_SET['cli'] = STATE_SET.get('ui') #type:ignore[assignment]
def collect_state(args : Args) -> Union[State, ProcessorState]:
state =\
{
key: get_item(key) for key in args #type:ignore[arg-type]
}
return state #type:ignore[return-value]
def init_item(key : Union[StateKey, ProcessorStateKey], value : Any) -> None:
STATE_SET['api'][key] = value #type:ignore[literal-required]
STATE_SET['cli'][key] = value #type:ignore[literal-required]
STATE_SET['ui'][key] = value #type:ignore[literal-required]
def get_item(key : Union[StateKey, ProcessorStateKey]) -> Any:
@@ -34,9 +40,23 @@ def set_item(key : Union[StateKey, ProcessorStateKey], value : Any) -> None:
STATE_SET[app_context][key] = value #type:ignore[literal-required]
def sync_item(key : Union[StateKey, ProcessorStateKey]) -> None:
STATE_SET['cli'][key] = STATE_SET.get('ui').get(key) #type:ignore[literal-required]
def clear_item(key : Union[StateKey, ProcessorStateKey]) -> None:
set_item(key, None)
def get_jobs_path() -> str:
jobs_path = get_item('jobs_path')
session_id = get_session_id()
if session_id:
return os.path.join(jobs_path, session_id)
return jobs_path
def get_temp_path() -> str:
temp_path = get_item('temp_path')
session_id = get_session_id()
if session_id:
return os.path.join(temp_path, session_id)
return temp_path
+1 -3
View File
@@ -52,11 +52,10 @@ def process_stream_frame(target_vision_frame : VisionFrame) -> VisionFrame:
temp_vision_mask = extract_vision_mask(temp_vision_frame)
for processor_module in get_processors_modules(state_manager.get_item('processors')):
logger.disable()
if processor_module.pre_process('stream'):
logger.enable()
temp_vision_frame, temp_vision_mask = processor_module.process_frame(
{
'reference_vision_frame': target_vision_frame,
'source_vision_frames': source_vision_frames,
'source_audio_frame': source_audio_frame,
'source_voice_frame': source_voice_frame,
@@ -64,7 +63,6 @@ def process_stream_frame(target_vision_frame : VisionFrame) -> VisionFrame:
'temp_vision_frame': temp_vision_frame,
'temp_vision_mask': temp_vision_mask
})
logger.enable()
return temp_vision_frame
+207
View File
@@ -0,0 +1,207 @@
import os
import platform
from datetime import datetime
from functools import lru_cache
from typing import Optional
import psutil
from facefusion.types import CpuInfo, DiskInfo, LoadAverage, NetworkInfo, OperatingSystemInfo, PythonInfo, RamInfo, SystemInfo, TemperatureInfo
@lru_cache()
def detect_static_system_info() -> SystemInfo:
return detect_system_info()
def detect_system_info(temp_path : Optional[str] = None) -> SystemInfo:
return\
{
'operating_system': get_operating_system_info(),
'python': get_python_info(),
'cpu': get_cpu_info(),
'ram': get_ram_info(),
'disk': get_disk_info(temp_path),
'temperatures': get_temperature_info(),
'network': get_network_info(),
'load_average': get_load_average()
}
def get_operating_system_info() -> OperatingSystemInfo:
boot_timestamp = psutil.boot_time()
boot_time = datetime.fromtimestamp(boot_timestamp)
uptime_seconds = int((datetime.now() - boot_time).total_seconds())
return\
{
'name': platform.system(),
'architecture': platform.machine(),
'platform': platform.platform(),
'boot_time': boot_time.isoformat(),
'uptime_seconds': uptime_seconds
}
def get_python_info() -> PythonInfo:
return\
{
'version': platform.python_version(),
'implementation': platform.python_implementation()
}
def get_cpu_info() -> CpuInfo:
cpu_freq = psutil.cpu_freq()
cpu_percent = psutil.cpu_percent(interval = 0)
cpu_info : CpuInfo =\
{
'model': get_cpu_model(),
'physical_cores': psutil.cpu_count(logical = False),
'logical_cores': psutil.cpu_count(logical = True),
'usage_percent': cpu_percent
}
if cpu_freq:
cpu_info['frequency'] =\
{
'current': cpu_freq.current,
'min': cpu_freq.min,
'max': cpu_freq.max
}
return cpu_info
def get_cpu_model() -> Optional[str]:
if platform.system() == 'Linux':
try:
with open('/proc/cpuinfo', 'r') as f:
for line in f:
if line.startswith('model name'):
return line.split(':', 1)[1].strip()
except Exception:
pass
if platform.system() == 'Darwin':
try:
import subprocess
result = subprocess.run(['sysctl', '-n', 'machdep.cpu.brand_string'], capture_output = True, text = True)
if result.returncode == 0:
return result.stdout.strip()
except Exception:
pass
if platform.system() == 'Windows':
try:
import subprocess
result = subprocess.run(['wmic', 'cpu', 'get', 'name'], capture_output = True, text = True)
if result.returncode == 0:
lines = result.stdout.strip().split('\n')
if len(lines) > 1:
return lines[1].strip()
except Exception:
pass
return None
def get_ram_info() -> RamInfo:
virtual_memory = psutil.virtual_memory()
swap_memory = psutil.swap_memory()
return\
{
'total': virtual_memory.total,
'available': virtual_memory.available,
'used': virtual_memory.used,
'free': virtual_memory.free,
'percent': virtual_memory.percent,
'swap_total': swap_memory.total,
'swap_used': swap_memory.used,
'swap_free': swap_memory.free,
'swap_percent': swap_memory.percent
}
def get_disk_info(temp_path : Optional[str] = None) -> Optional[DiskInfo]:
if temp_path is None:
temp_path = os.getcwd()
target_mountpoint = None
target_mountpoint_len = 0
for partition in psutil.disk_partitions():
if temp_path.startswith(partition.mountpoint):
if len(partition.mountpoint) > target_mountpoint_len:
target_mountpoint = partition.mountpoint
target_mountpoint_len = len(partition.mountpoint)
if target_mountpoint:
try:
usage = psutil.disk_usage(target_mountpoint)
return\
{
'filesystem': next((p.fstype for p in psutil.disk_partitions() if p.mountpoint == target_mountpoint), 'unknown'),
'total': usage.total,
'used': usage.used,
'free': usage.free,
'percent': usage.percent
}
except PermissionError:
pass
return None
def get_temperature_info() -> Optional[TemperatureInfo]:
if not hasattr(psutil, 'sensors_temperatures'):
return None
try:
temps = psutil.sensors_temperatures()
if not temps:
return None
temp_info : TemperatureInfo = {}
for name, entries in temps.items():
for entry in entries:
sensor_key = f'{name}_{entry.label}' if entry.label else name
temp_info[sensor_key] =\
{
'current': entry.current,
'high': entry.high,
'critical': entry.critical
}
return temp_info
except Exception:
return None
def get_network_info() -> NetworkInfo:
net_io = psutil.net_io_counters()
return\
{
'bytes_sent': net_io.bytes_sent,
'bytes_recv': net_io.bytes_recv,
'packets_sent': net_io.packets_sent,
'packets_recv': net_io.packets_recv,
'errin': net_io.errin,
'errout': net_io.errout,
'dropin': net_io.dropin,
'dropout': net_io.dropout,
'interfaces': {}
}
def get_load_average() -> Optional[LoadAverage]:
if hasattr(os, 'getloadavg'):
load1, load5, load15 = os.getloadavg()
return\
{
'load1': load1,
'load5': load5,
'load15': load15
}
return None
+19 -22
View File
@@ -1,43 +1,40 @@
import os
from typing import List
from facefusion import state_manager
from facefusion.filesystem import create_directory, get_file_extension, get_file_name, move_file, remove_directory, resolve_file_pattern
def get_temp_file_path(file_path : str) -> str:
temp_directory_path = get_temp_directory_path(file_path)
temp_file_extension = get_file_extension(file_path)
def get_temp_file_path(temp_path : str, output_path : str) -> str:
temp_directory_path = get_temp_directory_path(temp_path, output_path)
temp_file_extension = get_file_extension(output_path)
return os.path.join(temp_directory_path, 'temp' + temp_file_extension)
def move_temp_file(file_path : str, move_path : str) -> bool:
temp_file_path = get_temp_file_path(file_path)
return move_file(temp_file_path, move_path)
def move_temp_file(temp_path : str, output_path : str) -> bool:
temp_file_path = get_temp_file_path(temp_path, output_path)
return move_file(temp_file_path, output_path)
def resolve_temp_frame_paths(target_path : str) -> List[str]:
temp_frames_pattern = get_temp_frames_pattern(target_path, '*')
def resolve_temp_frame_paths(temp_path : str, output_path : str, temp_frame_format : str) -> List[str]:
temp_frames_pattern = get_temp_frames_pattern(temp_path, output_path, temp_frame_format, '*')
return resolve_file_pattern(temp_frames_pattern)
def get_temp_frames_pattern(target_path : str, temp_frame_prefix : str) -> str:
temp_directory_path = get_temp_directory_path(target_path)
return os.path.join(temp_directory_path, temp_frame_prefix + '.' + state_manager.get_item('temp_frame_format'))
def get_temp_frames_pattern(temp_path : str, output_path : str, temp_frame_format : str, temp_frame_prefix : str) -> str:
temp_directory_path = get_temp_directory_path(temp_path, output_path)
return os.path.join(temp_directory_path, temp_frame_prefix + '.' + temp_frame_format)
def get_temp_directory_path(file_path : str) -> str:
temp_file_name = get_file_name(file_path)
return os.path.join(state_manager.get_item('temp_path'), 'facefusion', temp_file_name)
def get_temp_directory_path(temp_path : str, output_path : str) -> str:
temp_file_name = get_file_name(output_path)
return os.path.join(temp_path, 'facefusion', temp_file_name)
def create_temp_directory(file_path : str) -> bool:
temp_directory_path = get_temp_directory_path(file_path)
def create_temp_directory(temp_path : str, output_path : str) -> bool:
temp_directory_path = get_temp_directory_path(temp_path, output_path)
return create_directory(temp_directory_path)
def clear_temp_directory(file_path : str) -> bool:
if not state_manager.get_item('keep_temp'):
temp_directory_path = get_temp_directory_path(file_path)
return remove_directory(temp_directory_path)
return True
def clear_temp_directory(temp_path : str, output_path : str) -> bool:
temp_directory_path = get_temp_directory_path(temp_path, output_path)
return remove_directory(temp_directory_path)
+8 -8
View File
@@ -1,29 +1,29 @@
import importlib
from typing import Optional
from facefusion.types import Language, LocalePoolSet, Locales
from facefusion.types import Language, LocalPoolSet, Locals
LOCALE_POOL_SET : LocalePoolSet = {}
LOCAL_POOL_SET : LocalPoolSet = {}
CURRENT_LANGUAGE : Language = 'en'
def __autoload__(module_name : str) -> None:
try:
__locales__ = importlib.import_module(module_name + '.locales')
load(__locales__.LOCALES, module_name)
__locals__ = importlib.import_module(module_name + '.locals')
load(__locals__.LOCALS, module_name)
except ImportError:
pass
def load(__locales__ : Locales, module_name : str) -> None:
LOCALE_POOL_SET[module_name] = __locales__
def load(__locals__ : Locals, module_name : str) -> None:
LOCAL_POOL_SET[module_name] = __locals__
def get(notation : str, module_name : str = 'facefusion') -> Optional[str]:
if module_name not in LOCALE_POOL_SET:
if module_name not in LOCAL_POOL_SET:
__autoload__(module_name)
current = LOCALE_POOL_SET.get(module_name).get(CURRENT_LANGUAGE)
current = LOCAL_POOL_SET.get(module_name).get(CURRENT_LANGUAGE)
for fragment in notation.split('.'):
if fragment in current:
+247 -25
View File
@@ -1,5 +1,7 @@
import ctypes
from collections import namedtuple
from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, TypeAlias, TypedDict
from datetime import datetime
from typing import Any, Callable, Dict, List, Literal, NotRequired, Optional, Tuple, TypeAlias, TypedDict
import cv2
import numpy
@@ -51,20 +53,22 @@ FaceStore = TypedDict('FaceStore',
})
Language = Literal['en']
Locales : TypeAlias = Dict[Language, Dict[str, Any]]
LocalePoolSet : TypeAlias = Dict[str, Locales]
Locals : TypeAlias = Dict[Language, Dict[str, Any]]
LocalPoolSet : TypeAlias = Dict[str, Locals]
WorkFlow = Literal['auto', 'audio-to-image', 'image-to-image', 'image-to-video']
VideoCaptureSet : TypeAlias = Dict[str, cv2.VideoCapture]
VideoWriterSet : TypeAlias = Dict[str, cv2.VideoWriter]
CameraCaptureSet : TypeAlias = Dict[str, cv2.VideoCapture]
VideoPoolSet = TypedDict('VideoPoolSet',
{
'capture': VideoCaptureSet,
'writer': VideoWriterSet
'capture' : VideoCaptureSet,
'writer' : VideoWriterSet
})
CameraPoolSet = TypedDict('CameraPoolSet',
{
'capture': CameraCaptureSet
'capture' : CameraCaptureSet
})
ColorMode = Literal['rgb', 'rgba']
@@ -94,13 +98,32 @@ Margin : TypeAlias = Tuple[int, int, int, int]
Orientation = Literal['landscape', 'portrait']
Resolution : TypeAlias = Tuple[int, int]
ProcessState = Literal['checking', 'processing', 'stopping', 'pending']
Args : TypeAlias = Dict[str, Any]
Scope : TypeAlias = Literal['api', 'cli', 'sys']
ArgsStore = TypedDict('ArgsStore',
{
'api' : List[str],
'cli' : List[str],
'sys' : List[str]
})
ProcessState = Literal['checking', 'processing', 'stopping', 'pending']
UpdateProgress : TypeAlias = Callable[[int], None]
ProcessStep : TypeAlias = Callable[[str, int, Args], bool]
Content : TypeAlias = Dict[str, Any]
Token : TypeAlias = str
SessionId : TypeAlias = str
Session = TypedDict('Session',
{
'access_token' : Token,
'refresh_token' : Token,
'created_at' : datetime,
'expires_at' : datetime
})
Command : TypeAlias = str
CommandSet : TypeAlias = Dict[str, List[Command]]
@@ -130,14 +153,80 @@ FaceMaskAreaSet : TypeAlias = Dict[FaceMaskArea, List[int]]
VoiceExtractorModel = Literal['kim_vocal_1', 'kim_vocal_2', 'uvr_mdxnet']
MediaType = Literal['audio', 'image', 'video']
AudioFormat = Literal['flac', 'm4a', 'mp3', 'ogg', 'opus', 'wav']
ImageFormat = Literal['bmp', 'jpeg', 'png', 'tiff', 'webp']
VideoFormat = Literal['avi', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mxf', 'webm', 'wmv']
TempFrameFormat = Literal['bmp', 'jpeg', 'png', 'tiff']
StreamMediaType = Literal['video', 'image']
AudioTypeSet : TypeAlias = Dict[AudioFormat, str]
ImageTypeSet : TypeAlias = Dict[ImageFormat, str]
VideoTypeSet : TypeAlias = Dict[VideoFormat, str]
AssetId : TypeAlias = str
AssetType = Literal['source', 'target']
AudioMetadata = TypedDict('AudioMetadata',
{
'duration' : Duration,
'sample_rate': int,
'frame_total': int,
'channels': int,
'format': str
})
ImageMetadata = TypedDict('ImageMetadata',
{
'resolution' : Resolution
})
VideoMetadata = TypedDict('VideoMetadata',
{
'duration' : Duration,
'frame_total' : int,
'fps' : Fps,
'resolution' : Resolution
})
AudioAsset = TypedDict('AudioAsset',
{
'id' : AssetId,
'created_at' : datetime,
'expires_at' : datetime,
'type' : AssetType,
'media' : Literal['audio'],
'name' : str,
'format' : AudioFormat,
'size' : int,
'path' : str,
'metadata' : AudioMetadata
})
ImageAsset = TypedDict('ImageAsset',
{
'id' : AssetId,
'created_at' : datetime,
'expires_at' : datetime,
'type' : AssetType,
'media' : Literal['image'],
'name' : str,
'format' : ImageFormat,
'size' : int,
'path' : str,
'metadata' : ImageMetadata
})
VideoAsset = TypedDict('VideoAsset',
{
'id' : AssetId,
'created_at' : datetime,
'expires_at' : datetime,
'type' : AssetType,
'media' : Literal['video'],
'name' : str,
'format' : VideoFormat,
'size' : int,
'path' : str,
'metadata' : VideoMetadata
})
AssetMetadata : TypeAlias = AudioMetadata | ImageMetadata | VideoMetadata
AssetSet : TypeAlias = Dict[AssetId, AudioAsset | ImageAsset | VideoAsset]
AssetStore : TypeAlias = Dict[SessionId, AssetSet]
AudioEncoder = Literal['flac', 'aac', 'libmp3lame', 'libopus', 'libvorbis', 'pcm_s16le', 'pcm_s32le']
VideoEncoder = Literal['libx264', 'libx264rgb', 'libx265', 'libvpx-vp9', 'h264_nvenc', 'hevc_nvenc', 'h264_amf', 'hevc_amf', 'h264_qsv', 'hevc_qsv', 'h264_videotoolbox', 'hevc_videotoolbox', 'rawvideo']
EncoderSet = TypedDict('EncoderSet',
@@ -211,6 +300,90 @@ ExecutionDevice = TypedDict('ExecutionDevice',
'utilization' : ExecutionDeviceUtilization
})
OperatingSystemInfo = TypedDict('OperatingSystemInfo',
{
'name' : str,
'architecture' : str,
'platform' : str,
'boot_time' : str,
'uptime_seconds' : int
})
PythonInfo = TypedDict('PythonInfo',
{
'version' : str,
'implementation' : str
})
CpuFrequency = TypedDict('CpuFrequency',
{
'current' : float,
'min' : float,
'max' : float
})
CpuInfo = TypedDict('CpuInfo',
{
'model' : Optional[str],
'physical_cores' : Optional[int],
'logical_cores' : Optional[int],
'usage_percent' : float,
'frequency' : Optional[CpuFrequency]
}, total = False)
RamInfo = TypedDict('RamInfo',
{
'total' : int,
'available' : int,
'used' : int,
'free' : int,
'percent' : float,
'swap_total' : int,
'swap_used' : int,
'swap_free' : int,
'swap_percent' : float
})
DiskInfo = TypedDict('DiskInfo',
{
'filesystem' : str,
'total' : int,
'used' : int,
'free' : int,
'percent' : float
})
TemperatureSensor = TypedDict('TemperatureSensor',
{
'current' : float,
'high' : Optional[float],
'critical' : Optional[float]
})
TemperatureInfo : TypeAlias = Dict[str, TemperatureSensor]
NetworkInfo = TypedDict('NetworkInfo',
{
'bytes_sent' : int,
'bytes_recv' : int,
'packets_sent' : int,
'packets_recv' : int,
'errin' : int,
'errout' : int,
'dropin' : int,
'dropout' : int,
'interfaces' : Dict[str, Any]
})
LoadAverage = TypedDict('LoadAverage',
{
'load1' : float,
'load5' : float,
'load15' : float
})
SystemInfo = TypedDict('SystemInfo',
{
'operating_system' : OperatingSystemInfo,
'python' : PythonInfo,
'cpu' : CpuInfo,
'ram' : RamInfo,
'disk' : Optional[DiskInfo],
'temperatures' : Optional[TemperatureInfo],
'network' : NetworkInfo,
'load_average' : Optional[LoadAverage]
})
DownloadProvider = Literal['github', 'huggingface']
DownloadProviderValue = TypedDict('DownloadProviderValue',
{
@@ -227,18 +400,11 @@ Download = TypedDict('Download',
DownloadSet : TypeAlias = Dict[str, Download]
VideoMemoryStrategy = Literal['strict', 'moderate', 'tolerant']
AppContext = Literal['cli', 'ui']
AppContext = Literal['cli', 'api']
InferencePool : TypeAlias = Dict[str, InferenceSession]
InferencePoolSet : TypeAlias = Dict[AppContext, Dict[str, InferencePool]]
UiWorkflow = Literal['instant_runner', 'job_runner', 'job_manager']
JobStore = TypedDict('JobStore',
{
'job_keys' : List[str],
'step_keys' : List[str]
})
JobOutputSet : TypeAlias = Dict[str, List[str]]
JobStatus = Literal['drafted', 'queued', 'completed', 'failed']
JobStepStatus = Literal['drafted', 'queued', 'started', 'completed', 'failed']
@@ -312,14 +478,10 @@ StateKey = Literal\
'output_video_scale',
'output_video_fps',
'processors',
'open_browser',
'ui_layouts',
'ui_workflow',
'execution_device_ids',
'execution_providers',
'execution_thread_count',
'video_memory_strategy',
'system_memory_limit',
'log_level',
'halt_on_error',
'job_id',
@@ -345,7 +507,7 @@ State = TypedDict('State',
'benchmark_cycle_count' : int,
'face_detector_model' : FaceDetectorModel,
'face_detector_size' : str,
'face_detector_margin': Margin,
'face_detector_margin' : Margin,
'face_detector_angles' : List[Angle],
'face_detector_score' : Score,
'face_landmarker_model' : FaceLandmarkerModel,
@@ -366,7 +528,7 @@ State = TypedDict('State',
'face_mask_regions' : List[FaceMaskRegion],
'face_mask_blur' : float,
'face_mask_padding' : Padding,
'voice_extractor_model': VoiceExtractorModel,
'voice_extractor_model' : VoiceExtractorModel,
'trim_frame_start' : int,
'trim_frame_end' : int,
'temp_frame_format' : TempFrameFormat,
@@ -382,14 +544,10 @@ State = TypedDict('State',
'output_video_scale' : Scale,
'output_video_fps' : float,
'processors' : List[str],
'open_browser' : bool,
'ui_layouts' : List[str],
'ui_workflow' : UiWorkflow,
'execution_device_ids' : List[int],
'execution_providers' : List[ExecutionProvider],
'execution_thread_count' : int,
'video_memory_strategy' : VideoMemoryStrategy,
'system_memory_limit' : int,
'log_level' : LogLevel,
'halt_on_error' : bool,
'job_id' : str,
@@ -399,3 +557,67 @@ State = TypedDict('State',
ApplyStateItem : TypeAlias = Callable[[Any, Any], None]
StateSet : TypeAlias = Dict[AppContext, State]
BitRate : TypeAlias = int
AudioCodec : TypeAlias = Literal['opus']
VideoCodec : TypeAlias = Literal['av1', 'vp8', 'vp9']
AomVideoCodec : TypeAlias = Literal['av1']
VxpVideoCodec : TypeAlias = Literal['vp8', 'vp9']
FrameHandler : TypeAlias = Callable[..., None]
AomEncoder : TypeAlias = ctypes.Array[ctypes.c_char]
AomDecoder : TypeAlias = ctypes.Array[ctypes.c_char]
OpusEncoder : TypeAlias = ctypes.c_void_p
OpusDecoder : TypeAlias = ctypes.c_void_p
VpxEncoder : TypeAlias = ctypes.Array[ctypes.c_char]
VpxDecoder : TypeAlias = ctypes.Array[ctypes.c_char]
AomPointer = TypedDict('AomPointer',
{
'buffer' : bytes,
'resolution' : Resolution
})
VpxPointer = TypedDict('VpxPointer',
{
'buffer' : bytes,
'resolution' : Resolution
})
PeerConnection : TypeAlias = int
SdpOffer : TypeAlias = str
SdpAnswer : TypeAlias = str
MediaDirection : TypeAlias = Literal['sendonly', 'recvonly', 'sendrecv']
RtcTrackInit : TypeAlias = Any
RtcVideoTrack : TypeAlias = int
RtcAudioTrack : TypeAlias = int
RtcPeerAudio = TypedDict('RtcPeerAudio',
{
'sender_track': RtcAudioTrack,
'receiver_track': RtcAudioTrack,
'codec': AudioCodec,
})
RtcPeerVideo = TypedDict('RtcPeerVideo',
{
'sender_track': RtcVideoTrack,
'receiver_track': RtcVideoTrack,
'codec': VideoCodec,
})
RtcPeer = TypedDict('RtcPeer',
{
'peer_connection': PeerConnection,
'audio': NotRequired[RtcPeerAudio],
'video': RtcPeerVideo,
'sender_bitrate': ctypes.c_uint,
'receiver_bitrate': ctypes.c_uint
})
RtcStore : TypeAlias = Dict[SessionId, List[RtcPeer]]
LibraryOptions : TypeAlias = Dict[str, Any]
LibrarySet : TypeAlias = Dict[str, LibraryOptions]
-163
View File
@@ -1,163 +0,0 @@
:root:root:root:root .gradio-container
{
overflow: unset;
}
:root:root:root:root main
{
max-width: 110em;
}
:root:root:root:root .tab-like-container input[type="number"]
{
border-radius: unset;
text-align: center;
order: 1;
padding: unset
}
:root:root:root:root input[type="number"]
{
appearance: textfield;
}
:root:root:root:root input[type="number"]::-webkit-inner-spin-button
{
appearance: none;
}
:root:root:root:root input[type="number"]:focus
{
outline: unset;
}
:root:root:root:root .reset-button
{
background: var(--background-fill-secondary);
border: unset;
font-size: unset;
padding: unset;
}
:root:root:root:root [type="checkbox"],
:root:root:root:root [type="radio"]
{
border-radius: 50%;
height: 1.125rem;
width: 1.125rem;
}
:root:root:root:root input[type="range"]
{
background: transparent;
}
:root:root:root:root input[type="range"]::-moz-range-thumb,
:root:root:root:root input[type="range"]::-webkit-slider-thumb
{
background: var(--neutral-300);
box-shadow: unset;
border-radius: 50%;
height: 1.125rem;
width: 1.125rem;
}
:root:root:root:root .thumbnail-item
{
border: unset;
box-shadow: unset;
}
:root:root:root:root .grid-wrap.fixed-height
{
min-height: unset;
}
:root:root:root:root .box-face-selector .empty,
:root:root:root:root .box-face-selector .gallery-container
{
min-height: 7.375rem;
}
:root:root:root:root .tab-wrapper
{
padding: 0 0.625rem;
}
:root:root:root:root .tab-container
{
gap: 0.5em;
}
:root:root:root:root .tab-container button
{
background: unset;
border-bottom: 0.125rem solid;
}
:root:root:root:root .tab-container button.selected
{
color: var(--primary-500)
}
:root:root:root:root .toast-body
{
background: white;
color: var(--primary-500);
border: unset;
border-radius: unset;
}
:root:root:root:root .dark .toast-body
{
background: var(--neutral-900);
color: var(--primary-600);
}
:root:root:root:root .toast-icon,
:root:root:root:root .toast-title,
:root:root:root:root .toast-text,
:root:root:root:root .toast-close
{
color: unset;
}
:root:root:root:root .toast-body .timer
{
background: currentColor;
}
:root:root:root:root .slider_input_container > span,
:root:root:root:root .feather-upload,
:root:root:root:root footer
{
display: none;
}
:root:root:root:root .image-frame
{
background-image: conic-gradient(#fff 90deg, #999 90deg 180deg, #fff 180deg 270deg, #999 270deg);
background-size: 1.25rem 1.25rem;
background-repeat: repeat;
width: 100%;
}
:root:root:root:root .image-frame > img
{
object-fit: cover;
}
:root:root:root:root .image-preview.is-landscape
{
position: sticky;
top: 0;
z-index: 100;
}
:root:root:root:root .block .error
{
border: 0.125rem solid;
padding: 0.375rem 0.75rem;
font-size: 0.75rem;
text-transform: uppercase;
}
-25
View File
@@ -1,25 +0,0 @@
from typing import Dict, List
from facefusion.types import Color, WebcamMode
from facefusion.uis.types import JobManagerAction, JobRunnerAction, PreviewMode
job_manager_actions : List[JobManagerAction] = [ 'job-create', 'job-submit', 'job-delete', 'job-add-step', 'job-remix-step', 'job-insert-step', 'job-remove-step' ]
job_runner_actions : List[JobRunnerAction] = [ 'job-run', 'job-run-all', 'job-retry', 'job-retry-all' ]
common_options : List[str] = [ 'keep-temp' ]
preview_modes : List[PreviewMode] = [ 'default', 'frame-by-frame', 'face-by-face' ]
preview_resolutions : List[str] = [ '512x512', '768x768', '1024x1024' ]
webcam_modes : List[WebcamMode] = [ 'inline', 'udp', 'v4l2' ]
webcam_resolutions : List[str] = [ '320x240', '640x480', '800x600', '1024x768', '1280x720', '1280x960', '1920x1080' ]
background_remover_colors : Dict[str, Color] =\
{
'red' : (255, 0, 0, 255),
'green' : (0, 255, 0, 255),
'blue' : (0, 0, 255, 255),
'black' : (0, 0, 0, 255),
'white' : (255, 255, 255, 255),
'alpha' : (0, 0, 0, 0)
}
-41
View File
@@ -1,41 +0,0 @@
import random
from typing import Optional
import gradio
from facefusion import metadata, translator
METADATA_BUTTON : Optional[gradio.Button] = None
ACTION_BUTTON : Optional[gradio.Button] = None
def render() -> None:
global METADATA_BUTTON
global ACTION_BUTTON
action = random.choice(
[
{
'translator': translator.get('about.fund'),
'url': 'https://fund.facefusion.io'
},
{
'translator': translator.get('about.subscribe'),
'url': 'https://subscribe.facefusion.io'
},
{
'translator': translator.get('about.join'),
'url': 'https://join.facefusion.io'
}
])
METADATA_BUTTON = gradio.Button(
value = metadata.get('name') + ' ' + metadata.get('version'),
variant = 'primary',
link = metadata.get('url')
)
ACTION_BUTTON = gradio.Button(
value = action.get('translator'),
link = action.get('url'),
size = 'sm'
)
@@ -1,64 +0,0 @@
from typing import List, Optional, Tuple
import gradio
from facefusion import state_manager, translator
from facefusion.common_helper import calculate_float_step
from facefusion.processors.core import load_processor_module
from facefusion.processors.modules.age_modifier import choices as age_modifier_choices
from facefusion.processors.modules.age_modifier.types import AgeModifierModel
from facefusion.uis.core import get_ui_component, register_ui_component
AGE_MODIFIER_MODEL_DROPDOWN : Optional[gradio.Dropdown] = None
AGE_MODIFIER_DIRECTION_SLIDER : Optional[gradio.Slider] = None
def render() -> None:
global AGE_MODIFIER_MODEL_DROPDOWN
global AGE_MODIFIER_DIRECTION_SLIDER
has_age_modifier = 'age_modifier' in state_manager.get_item('processors')
AGE_MODIFIER_MODEL_DROPDOWN = gradio.Dropdown(
label = translator.get('uis.model_dropdown', 'facefusion.processors.modules.age_modifier'),
choices = age_modifier_choices.age_modifier_models,
value = state_manager.get_item('age_modifier_model'),
visible = has_age_modifier
)
AGE_MODIFIER_DIRECTION_SLIDER = gradio.Slider(
label = translator.get('uis.direction_slider', 'facefusion.processors.modules.age_modifier'),
value = state_manager.get_item('age_modifier_direction'),
step = calculate_float_step(age_modifier_choices.age_modifier_direction_range),
minimum = age_modifier_choices.age_modifier_direction_range[0],
maximum = age_modifier_choices.age_modifier_direction_range[-1],
visible = has_age_modifier
)
register_ui_component('age_modifier_model_dropdown', AGE_MODIFIER_MODEL_DROPDOWN)
register_ui_component('age_modifier_direction_slider', AGE_MODIFIER_DIRECTION_SLIDER)
def listen() -> None:
AGE_MODIFIER_MODEL_DROPDOWN.change(update_age_modifier_model, inputs = AGE_MODIFIER_MODEL_DROPDOWN, outputs = AGE_MODIFIER_MODEL_DROPDOWN)
AGE_MODIFIER_DIRECTION_SLIDER.release(update_age_modifier_direction, inputs = AGE_MODIFIER_DIRECTION_SLIDER)
processors_checkbox_group = get_ui_component('processors_checkbox_group')
if processors_checkbox_group:
processors_checkbox_group.change(remote_update, inputs = processors_checkbox_group, outputs = [ AGE_MODIFIER_MODEL_DROPDOWN, AGE_MODIFIER_DIRECTION_SLIDER ])
def remote_update(processors : List[str]) -> Tuple[gradio.Dropdown, gradio.Slider]:
has_age_modifier = 'age_modifier' in processors
return gradio.Dropdown(visible = has_age_modifier), gradio.Slider(visible = has_age_modifier)
def update_age_modifier_model(age_modifier_model : AgeModifierModel) -> gradio.Dropdown:
age_modifier_module = load_processor_module('age_modifier')
age_modifier_module.clear_inference_pool()
state_manager.set_item('age_modifier_model', age_modifier_model)
if age_modifier_module.pre_check():
return gradio.Dropdown(value = state_manager.get_item('age_modifier_model'))
return gradio.Dropdown()
def update_age_modifier_direction(age_modifier_direction : float) -> None:
state_manager.set_item('age_modifier_direction', int(age_modifier_direction))
@@ -1,107 +0,0 @@
from typing import List, Optional, Tuple
import gradio
from facefusion import state_manager, translator
from facefusion.common_helper import calculate_int_step
from facefusion.processors.core import load_processor_module
from facefusion.processors.modules.background_remover import choices as background_remover_choices
from facefusion.processors.modules.background_remover.types import BackgroundRemoverModel
from facefusion.sanitizer import sanitize_int_range
from facefusion.uis.core import get_ui_component, register_ui_component
BACKGROUND_REMOVER_MODEL_DROPDOWN : Optional[gradio.Dropdown] = None
BACKGROUND_REMOVER_COLOR_WRAPPER : Optional[gradio.Group] = None
BACKGROUND_REMOVER_COLOR_RED_NUMBER : Optional[gradio.Number] = None
BACKGROUND_REMOVER_COLOR_GREEN_NUMBER : Optional[gradio.Number] = None
BACKGROUND_REMOVER_COLOR_BLUE_NUMBER : Optional[gradio.Number] = None
BACKGROUND_REMOVER_COLOR_ALPHA_NUMBER : Optional[gradio.Number] = None
def render() -> None:
global BACKGROUND_REMOVER_MODEL_DROPDOWN
global BACKGROUND_REMOVER_COLOR_WRAPPER
global BACKGROUND_REMOVER_COLOR_RED_NUMBER
global BACKGROUND_REMOVER_COLOR_GREEN_NUMBER
global BACKGROUND_REMOVER_COLOR_BLUE_NUMBER
global BACKGROUND_REMOVER_COLOR_ALPHA_NUMBER
has_background_remover = 'background_remover' in state_manager.get_item('processors')
background_remover_color = state_manager.get_item('background_remover_color')
BACKGROUND_REMOVER_MODEL_DROPDOWN = gradio.Dropdown(
label = translator.get('uis.model_dropdown', 'facefusion.processors.modules.background_remover'),
choices = background_remover_choices.background_remover_models,
value = state_manager.get_item('background_remover_model'),
visible = has_background_remover
)
with gradio.Group(visible = has_background_remover) as BACKGROUND_REMOVER_COLOR_WRAPPER:
with gradio.Row():
BACKGROUND_REMOVER_COLOR_RED_NUMBER = gradio.Number(
label = translator.get('uis.color_red_number', 'facefusion.processors.modules.background_remover'),
value = background_remover_color[0],
minimum = background_remover_choices.background_remover_color_range[0],
maximum = background_remover_choices.background_remover_color_range[-1],
step = calculate_int_step(background_remover_choices.background_remover_color_range)
)
BACKGROUND_REMOVER_COLOR_GREEN_NUMBER = gradio.Number(
label = translator.get('uis.color_green_number', 'facefusion.processors.modules.background_remover'),
value = background_remover_color[1],
minimum = background_remover_choices.background_remover_color_range[0],
maximum = background_remover_choices.background_remover_color_range[-1],
step = calculate_int_step(background_remover_choices.background_remover_color_range)
)
with gradio.Row():
BACKGROUND_REMOVER_COLOR_BLUE_NUMBER = gradio.Number(
label = translator.get('uis.color_blue_number', 'facefusion.processors.modules.background_remover'),
value = background_remover_color[2],
minimum = background_remover_choices.background_remover_color_range[0],
maximum = background_remover_choices.background_remover_color_range[-1],
step = calculate_int_step(background_remover_choices.background_remover_color_range)
)
BACKGROUND_REMOVER_COLOR_ALPHA_NUMBER = gradio.Number(
label = translator.get('uis.color_alpha_number', 'facefusion.processors.modules.background_remover'),
value = background_remover_color[3],
minimum = background_remover_choices.background_remover_color_range[0],
maximum = background_remover_choices.background_remover_color_range[-1],
step = calculate_int_step(background_remover_choices.background_remover_color_range)
)
register_ui_component('background_remover_model_dropdown', BACKGROUND_REMOVER_MODEL_DROPDOWN)
register_ui_component('background_remover_color_red_number', BACKGROUND_REMOVER_COLOR_RED_NUMBER)
register_ui_component('background_remover_color_green_number', BACKGROUND_REMOVER_COLOR_GREEN_NUMBER)
register_ui_component('background_remover_color_blue_number', BACKGROUND_REMOVER_COLOR_BLUE_NUMBER)
register_ui_component('background_remover_color_alpha_number', BACKGROUND_REMOVER_COLOR_ALPHA_NUMBER)
def listen() -> None:
BACKGROUND_REMOVER_MODEL_DROPDOWN.change(update_background_remover_model, inputs = BACKGROUND_REMOVER_MODEL_DROPDOWN, outputs = BACKGROUND_REMOVER_MODEL_DROPDOWN)
background_remover_color_inputs = [ BACKGROUND_REMOVER_COLOR_RED_NUMBER, BACKGROUND_REMOVER_COLOR_GREEN_NUMBER, BACKGROUND_REMOVER_COLOR_BLUE_NUMBER, BACKGROUND_REMOVER_COLOR_ALPHA_NUMBER ]
for background_remover_color_input in background_remover_color_inputs:
background_remover_color_input.change(update_background_remover_color, inputs = background_remover_color_inputs)
processors_checkbox_group = get_ui_component('processors_checkbox_group')
if processors_checkbox_group:
processors_checkbox_group.change(remote_update, inputs = processors_checkbox_group, outputs = [BACKGROUND_REMOVER_MODEL_DROPDOWN, BACKGROUND_REMOVER_COLOR_WRAPPER])
def remote_update(processors : List[str]) -> Tuple[gradio.Dropdown, gradio.Group]:
has_background_remover = 'background_remover' in processors
return gradio.Dropdown(visible = has_background_remover), gradio.Group(visible = has_background_remover)
def update_background_remover_model(background_remover_model : BackgroundRemoverModel) -> gradio.Dropdown:
background_remover_module = load_processor_module('background_remover')
background_remover_module.clear_inference_pool()
state_manager.set_item('background_remover_model', background_remover_model)
if background_remover_module.pre_check():
return gradio.Dropdown(value = state_manager.get_item('background_remover_model'))
return gradio.Dropdown()
def update_background_remover_color(red : int, green : int, blue : int, alpha : int) -> None:
red = sanitize_int_range(red, background_remover_choices.background_remover_color_range)
green = sanitize_int_range(green, background_remover_choices.background_remover_color_range)
blue = sanitize_int_range(blue, background_remover_choices.background_remover_color_range)
alpha = sanitize_int_range(alpha, background_remover_choices.background_remover_color_range)
state_manager.set_item('background_remover_color', (red, green, blue, alpha))
-51
View File
@@ -1,51 +0,0 @@
from typing import Any, Iterator, List, Optional
import gradio
from facefusion import benchmarker, state_manager, translator
BENCHMARK_BENCHMARKS_DATAFRAME : Optional[gradio.Dataframe] = None
BENCHMARK_START_BUTTON : Optional[gradio.Button] = None
def render() -> None:
global BENCHMARK_BENCHMARKS_DATAFRAME
global BENCHMARK_START_BUTTON
BENCHMARK_BENCHMARKS_DATAFRAME = gradio.Dataframe(
headers =
[
'target_path',
'cycle_count',
'average_run',
'fastest_run',
'slowest_run',
'relative_fps'
],
datatype =
[
'str',
'number',
'number',
'number',
'number',
'number'
],
show_label = False
)
BENCHMARK_START_BUTTON = gradio.Button(
value = translator.get('uis.start_button'),
variant = 'primary',
size = 'sm'
)
def listen() -> None:
BENCHMARK_START_BUTTON.click(start, outputs = BENCHMARK_BENCHMARKS_DATAFRAME)
def start() -> Iterator[List[Any]]:
state_manager.sync_state()
for benchmark in benchmarker.run():
yield [ list(benchmark_set.values()) for benchmark_set in benchmark ]
@@ -1,54 +0,0 @@
from typing import List, Optional
import gradio
import facefusion.choices
from facefusion import state_manager, translator
from facefusion.common_helper import calculate_int_step
from facefusion.types import BenchmarkMode, BenchmarkResolution
BENCHMARK_MODE_DROPDOWN : Optional[gradio.Dropdown] = None
BENCHMARK_RESOLUTIONS_CHECKBOX_GROUP : Optional[gradio.CheckboxGroup] = None
BENCHMARK_CYCLE_COUNT_SLIDER : Optional[gradio.Button] = None
def render() -> None:
global BENCHMARK_MODE_DROPDOWN
global BENCHMARK_RESOLUTIONS_CHECKBOX_GROUP
global BENCHMARK_CYCLE_COUNT_SLIDER
BENCHMARK_MODE_DROPDOWN = gradio.Dropdown(
label = translator.get('uis.benchmark_mode_dropdown'),
choices = facefusion.choices.benchmark_modes,
value = state_manager.get_item('benchmark_mode')
)
BENCHMARK_RESOLUTIONS_CHECKBOX_GROUP = gradio.CheckboxGroup(
label = translator.get('uis.benchmark_resolutions_checkbox_group'),
choices = facefusion.choices.benchmark_resolutions,
value = state_manager.get_item('benchmark_resolutions')
)
BENCHMARK_CYCLE_COUNT_SLIDER = gradio.Slider(
label = translator.get('uis.benchmark_cycle_count_slider'),
value = state_manager.get_item('benchmark_cycle_count'),
step = calculate_int_step(facefusion.choices.benchmark_cycle_count_range),
minimum = facefusion.choices.benchmark_cycle_count_range[0],
maximum = facefusion.choices.benchmark_cycle_count_range[-1]
)
def listen() -> None:
BENCHMARK_MODE_DROPDOWN.change(update_benchmark_mode, inputs = BENCHMARK_MODE_DROPDOWN)
BENCHMARK_RESOLUTIONS_CHECKBOX_GROUP.change(update_benchmark_resolutions, inputs = BENCHMARK_RESOLUTIONS_CHECKBOX_GROUP)
BENCHMARK_CYCLE_COUNT_SLIDER.release(update_benchmark_cycle_count, inputs = BENCHMARK_CYCLE_COUNT_SLIDER)
def update_benchmark_mode(benchmark_mode : BenchmarkMode) -> None:
state_manager.set_item('benchmark_mode', benchmark_mode)
def update_benchmark_resolutions(benchmark_resolutions : List[BenchmarkResolution]) -> None:
state_manager.set_item('benchmark_resolutions', benchmark_resolutions)
def update_benchmark_cycle_count(benchmark_cycle_count : int) -> None:
state_manager.set_item('benchmark_cycle_count', benchmark_cycle_count)
@@ -1,32 +0,0 @@
from typing import List, Optional
import gradio
from facefusion import state_manager, translator
from facefusion.uis import choices as uis_choices
COMMON_OPTIONS_CHECKBOX_GROUP : Optional[gradio.Checkboxgroup] = None
def render() -> None:
global COMMON_OPTIONS_CHECKBOX_GROUP
common_options = []
if state_manager.get_item('keep_temp'):
common_options.append('keep-temp')
COMMON_OPTIONS_CHECKBOX_GROUP = gradio.Checkboxgroup(
label = translator.get('uis.common_options_checkbox_group'),
choices = uis_choices.common_options,
value = common_options
)
def listen() -> None:
COMMON_OPTIONS_CHECKBOX_GROUP.change(update, inputs = COMMON_OPTIONS_CHECKBOX_GROUP)
def update(common_options : List[str]) -> None:
keep_temp = 'keep-temp' in common_options
state_manager.set_item('keep_temp', keep_temp)
@@ -1,64 +0,0 @@
from typing import List, Optional, Tuple
import gradio
from facefusion import state_manager, translator
from facefusion.common_helper import calculate_int_step
from facefusion.processors.core import load_processor_module
from facefusion.processors.modules.deep_swapper import choices as deep_swapper_choices
from facefusion.processors.modules.deep_swapper.types import DeepSwapperModel
from facefusion.uis.core import get_ui_component, register_ui_component
DEEP_SWAPPER_MODEL_DROPDOWN : Optional[gradio.Dropdown] = None
DEEP_SWAPPER_MORPH_SLIDER : Optional[gradio.Slider] = None
def render() -> None:
global DEEP_SWAPPER_MODEL_DROPDOWN
global DEEP_SWAPPER_MORPH_SLIDER
has_deep_swapper = 'deep_swapper' in state_manager.get_item('processors')
DEEP_SWAPPER_MODEL_DROPDOWN = gradio.Dropdown(
label = translator.get('uis.model_dropdown', 'facefusion.processors.modules.deep_swapper'),
choices = deep_swapper_choices.deep_swapper_models,
value = state_manager.get_item('deep_swapper_model'),
visible = has_deep_swapper
)
DEEP_SWAPPER_MORPH_SLIDER = gradio.Slider(
label = translator.get('uis.morph_slider', 'facefusion.processors.modules.deep_swapper'),
value = state_manager.get_item('deep_swapper_morph'),
step = calculate_int_step(deep_swapper_choices.deep_swapper_morph_range),
minimum = deep_swapper_choices.deep_swapper_morph_range[0],
maximum = deep_swapper_choices.deep_swapper_morph_range[-1],
visible = has_deep_swapper and load_processor_module('deep_swapper').get_inference_pool() and load_processor_module('deep_swapper').has_morph_input()
)
register_ui_component('deep_swapper_model_dropdown', DEEP_SWAPPER_MODEL_DROPDOWN)
register_ui_component('deep_swapper_morph_slider', DEEP_SWAPPER_MORPH_SLIDER)
def listen() -> None:
DEEP_SWAPPER_MODEL_DROPDOWN.change(update_deep_swapper_model, inputs = DEEP_SWAPPER_MODEL_DROPDOWN, outputs = [ DEEP_SWAPPER_MODEL_DROPDOWN, DEEP_SWAPPER_MORPH_SLIDER ])
DEEP_SWAPPER_MORPH_SLIDER.release(update_deep_swapper_morph, inputs = DEEP_SWAPPER_MORPH_SLIDER)
processors_checkbox_group = get_ui_component('processors_checkbox_group')
if processors_checkbox_group:
processors_checkbox_group.change(remote_update, inputs = processors_checkbox_group, outputs = [ DEEP_SWAPPER_MODEL_DROPDOWN, DEEP_SWAPPER_MORPH_SLIDER ])
def remote_update(processors : List[str]) -> Tuple[gradio.Dropdown, gradio.Slider]:
has_deep_swapper = 'deep_swapper' in processors
return gradio.Dropdown(visible = has_deep_swapper), gradio.Slider(visible = has_deep_swapper and load_processor_module('deep_swapper').get_inference_pool() and load_processor_module('deep_swapper').has_morph_input())
def update_deep_swapper_model(deep_swapper_model : DeepSwapperModel) -> Tuple[gradio.Dropdown, gradio.Slider]:
deep_swapper_module = load_processor_module('deep_swapper')
deep_swapper_module.clear_inference_pool()
state_manager.set_item('deep_swapper_model', deep_swapper_model)
if deep_swapper_module.pre_check():
return gradio.Dropdown(value = state_manager.get_item('deep_swapper_model')), gradio.Slider(visible = deep_swapper_module.has_morph_input())
return gradio.Dropdown(), gradio.Slider()
def update_deep_swapper_morph(deep_swapper_morph : int) -> None:
state_manager.set_item('deep_swapper_morph', deep_swapper_morph)
-48
View File
@@ -1,48 +0,0 @@
from typing import List, Optional
import gradio
import facefusion.choices
from facefusion import content_analyser, face_classifier, face_detector, face_landmarker, face_masker, face_recognizer, state_manager, translator, voice_extractor
from facefusion.filesystem import get_file_name, resolve_file_paths
from facefusion.processors.core import get_processors_modules
from facefusion.types import DownloadProvider
DOWNLOAD_PROVIDERS_CHECKBOX_GROUP : Optional[gradio.CheckboxGroup] = None
def render() -> None:
global DOWNLOAD_PROVIDERS_CHECKBOX_GROUP
DOWNLOAD_PROVIDERS_CHECKBOX_GROUP = gradio.CheckboxGroup(
label = translator.get('uis.download_providers_checkbox_group'),
choices = facefusion.choices.download_providers,
value = state_manager.get_item('download_providers')
)
def listen() -> None:
DOWNLOAD_PROVIDERS_CHECKBOX_GROUP.change(update_download_providers, inputs = DOWNLOAD_PROVIDERS_CHECKBOX_GROUP, outputs = DOWNLOAD_PROVIDERS_CHECKBOX_GROUP)
def update_download_providers(download_providers : List[DownloadProvider]) -> gradio.CheckboxGroup:
common_modules =\
[
content_analyser,
face_classifier,
face_detector,
face_landmarker,
face_recognizer,
face_masker,
voice_extractor
]
available_processors = [ get_file_name(file_path) for file_path in resolve_file_paths('facefusion/processors/modules') ]
processor_modules = get_processors_modules(available_processors)
for module in common_modules + processor_modules:
if hasattr(module, 'create_static_model_set'):
module.create_static_model_set.cache_clear()
download_providers = download_providers or facefusion.choices.download_providers
state_manager.set_item('download_providers', download_providers)
return gradio.CheckboxGroup(value = state_manager.get_item('download_providers'))

Some files were not shown because too many files have changed in this diff Show More