mirror of
https://github.com/facefusion/facefusion.git
synced 2026-11-26 11:43:45 +01:00
validator constrains for the api (#1248)
* validator constrains for the api * fix lint
This commit is contained in:
1 parent
5a98e79c7b
commit
9fc5a09531
14 files changed
+209
-90
No files matched your search
@@ -1,7 +1,7 @@
|
||||
import asyncio
|
||||
import os
|
||||
import uuid
|
||||
from typing import List, Optional, cast
|
||||
from typing import List, Optional
|
||||
|
||||
from starlette.datastructures import UploadFile
|
||||
|
||||
@@ -10,7 +10,7 @@ from facefusion import ffmpeg, process_manager, state_manager
|
||||
from facefusion.face_creator import get_many_faces
|
||||
from facefusion.face_helper import warp_face_by_bounding_box
|
||||
from facefusion.filesystem import create_directory, get_file_extension, get_file_format, is_audio, is_image, is_video
|
||||
from facefusion.types import AudioFormat, ImageAsset, ImageFormat, ImageMetadata, MediaType, VideoAsset, VideoFormat, VisionFrame
|
||||
from facefusion.types import ImageAsset, ImageMetadata, MediaType, VideoAsset, VisionFrame
|
||||
from facefusion.vision import detect_image_resolution, fit_contain_frame, is_vision_frame, read_static_image, read_static_video_frame, unpack_resolution
|
||||
|
||||
|
||||
@@ -42,40 +42,6 @@ def detect_media_type_by_format(file_format : str) -> Optional[MediaType]:
|
||||
return None
|
||||
|
||||
|
||||
def validate_asset_files(upload_files : List[UploadFile]) -> bool:
|
||||
available_encoder_set = ffmpeg.get_static_available_encoder_set()
|
||||
|
||||
for upload_file in upload_files:
|
||||
file_format = get_file_format(upload_file.filename)
|
||||
media_type = detect_media_type_by_format(file_format)
|
||||
|
||||
if media_type == 'audio' and facefusion.choices.audio_set.get(cast(AudioFormat, file_format)) not in available_encoder_set.get('audio'):
|
||||
return False
|
||||
|
||||
if media_type == 'image' and facefusion.choices.image_set.get(cast(ImageFormat, file_format)) not in available_encoder_set.get('image'):
|
||||
return False
|
||||
|
||||
if media_type == 'video' and facefusion.choices.video_set.get(cast(VideoFormat, file_format)) not in available_encoder_set.get('video'):
|
||||
return False
|
||||
|
||||
return media_type in [ 'audio', 'image', 'video' ]
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def validate_frame_resolution(resolution : str) -> bool:
|
||||
resolution_min = 64
|
||||
resolution_max = 4096
|
||||
|
||||
if resolution:
|
||||
frame_width, frame_height = unpack_resolution(resolution)
|
||||
|
||||
if resolution_min < frame_width < resolution_max and resolution_min < frame_height < resolution_max:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
async def save_asset_files(upload_files : List[UploadFile]) -> List[str]:
|
||||
asset_paths : List[str] = []
|
||||
api_security_strategy = state_manager.get_item('api_security_strategy')
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
from typing import List, cast
|
||||
|
||||
from starlette.datastructures import UploadFile
|
||||
|
||||
import facefusion.choices
|
||||
from facefusion import ffmpeg
|
||||
from facefusion.apis.asset_helper import detect_media_type_by_format
|
||||
from facefusion.filesystem import get_file_format
|
||||
from facefusion.types import AudioFormat, ImageFormat, VideoFormat
|
||||
from facefusion.vision import unpack_resolution
|
||||
|
||||
|
||||
def validate_subject(subject : str) -> bool:
|
||||
return subject in [ 'frame', 'face' ]
|
||||
|
||||
|
||||
def validate_resolution(resolution : str) -> bool:
|
||||
resolution_min = 63
|
||||
resolution_max = 4097
|
||||
|
||||
if resolution:
|
||||
frame_width, frame_height = unpack_resolution(resolution)
|
||||
|
||||
return resolution_min < frame_width < resolution_max and resolution_min < frame_height < resolution_max
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def validate_frame_index(frame_indexes : List[str]) -> bool:
|
||||
frame_min = 0
|
||||
frame_max = 101
|
||||
frame_total = len(frame_indexes)
|
||||
|
||||
return frame_min < frame_total < frame_max
|
||||
|
||||
|
||||
def validate_asset_files(upload_files : List[UploadFile]) -> bool:
|
||||
available_encoder_set = ffmpeg.get_static_available_encoder_set()
|
||||
|
||||
for upload_file in upload_files:
|
||||
file_format = get_file_format(upload_file.filename)
|
||||
media_type = detect_media_type_by_format(file_format)
|
||||
|
||||
if media_type == 'audio' and facefusion.choices.audio_set.get(cast(AudioFormat, file_format)) not in available_encoder_set.get('audio'):
|
||||
return False
|
||||
|
||||
if media_type == 'image' and facefusion.choices.image_set.get(cast(ImageFormat, file_format)) not in available_encoder_set.get('image'):
|
||||
return False
|
||||
|
||||
if media_type == 'video' and facefusion.choices.video_set.get(cast(VideoFormat, file_format)) not in available_encoder_set.get('video'):
|
||||
return False
|
||||
|
||||
return media_type in [ 'audio', 'image', 'video' ]
|
||||
|
||||
return True
|
||||
@@ -9,7 +9,8 @@ from starlette.status import HTTP_200_OK, HTTP_201_CREATED, HTTP_400_BAD_REQUEST
|
||||
|
||||
from facefusion import translator
|
||||
from facefusion.apis import asset_store
|
||||
from facefusion.apis.asset_helper import capture_asset_faces, capture_asset_frames, save_asset_files, validate_asset_files, validate_frame_resolution
|
||||
from facefusion.apis.asset_helper import capture_asset_faces, capture_asset_frames, save_asset_files
|
||||
from facefusion.apis.asset_validator import validate_asset_files, validate_frame_index, validate_resolution, validate_subject
|
||||
from facefusion.filesystem import remove_file
|
||||
from facefusion.types import AssetType, ImageAsset, VideoAsset
|
||||
from facefusion.vision import is_vision_frames, to_strip_buffer
|
||||
@@ -47,16 +48,17 @@ async def get_asset(request : Request) -> Response:
|
||||
|
||||
if action == 'capture':
|
||||
if asset and asset.get('media') in [ 'image', 'video' ]:
|
||||
subject = request.query_params.get('subject')
|
||||
resolution = request.query_params.get('resolution')
|
||||
frame_indexes = request.query_params.getlist('frame_index')
|
||||
vision_frames = []
|
||||
|
||||
if validate_frame_resolution(resolution):
|
||||
if validate_frame_index(frame_indexes) and validate_subject(subject) and validate_resolution(resolution):
|
||||
|
||||
if request.query_params.get('subject') == 'frame':
|
||||
if subject == 'frame':
|
||||
vision_frames = await asyncio.to_thread(capture_asset_frames, cast(ImageAsset | VideoAsset, asset), frame_indexes, resolution)
|
||||
|
||||
if request.query_params.get('subject') == 'face':
|
||||
if subject == 'face':
|
||||
vision_frames = await asyncio.to_thread(capture_asset_faces, cast(ImageAsset | VideoAsset, asset), frame_indexes, resolution)
|
||||
|
||||
if is_vision_frames(vision_frames):
|
||||
|
||||
@@ -7,10 +7,10 @@ from starlette.requests import Request
|
||||
from starlette.responses import JSONResponse
|
||||
from starlette.status import HTTP_200_OK, HTTP_201_CREATED, HTTP_202_ACCEPTED, HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND, HTTP_409_CONFLICT
|
||||
|
||||
import facefusion.choices
|
||||
import facefusion.core
|
||||
from facefusion import args_helper, state_manager, translator
|
||||
from facefusion.apis import jobs_helper
|
||||
from facefusion.apis.job_validator import validate_status
|
||||
from facefusion.filesystem import create_directory, get_file_extension, is_directory
|
||||
from facefusion.jobs import job_helper, job_manager, job_runner
|
||||
from facefusion.types import JobStatus
|
||||
@@ -19,7 +19,7 @@ from facefusion.types import JobStatus
|
||||
async def get_jobs(request : Request) -> JSONResponse:
|
||||
job_status = cast(JobStatus, request.query_params.get('status'))
|
||||
|
||||
if job_status in facefusion.choices.job_statuses:
|
||||
if validate_status(job_status):
|
||||
__job_set__ = {}
|
||||
job_set = job_manager.find_jobs(job_status)
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ from starlette.status import HTTP_200_OK, HTTP_201_CREATED, HTTP_401_UNAUTHORIZE
|
||||
|
||||
from facefusion import content_store, face_store, inference_manager, process_manager, rtc_store, session_context, session_manager, state_manager, store_manager, translator, video_manager
|
||||
from facefusion.apis import asset_store, websocket_store
|
||||
from facefusion.apis.session_helper import validate_api_key
|
||||
from facefusion.apis.session_validator import validate_api_key
|
||||
from facefusion.filesystem import is_directory, remove_directory
|
||||
from facefusion.jobs import job_manager
|
||||
|
||||
|
||||
@@ -4,7 +4,8 @@ from starlette.status import HTTP_200_OK, HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOU
|
||||
|
||||
from facefusion import args_helper, state_manager, translator
|
||||
from facefusion.apis import asset_store
|
||||
from facefusion.apis.state_helper import normalize_argument_value, validate_argument_key, validate_argument_value
|
||||
from facefusion.apis.state_helper import normalize_argument_value
|
||||
from facefusion.apis.state_validator import validate_argument_key, validate_argument_value
|
||||
|
||||
|
||||
async def get_state(request : Request) -> JSONResponse:
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import facefusion.choices
|
||||
from facefusion.types import JobStatus
|
||||
|
||||
|
||||
def validate_status(job_status : JobStatus) -> bool:
|
||||
return job_status in facefusion.choices.job_statuses
|
||||
@@ -1,5 +1,3 @@
|
||||
import os
|
||||
import secrets
|
||||
from typing import Optional
|
||||
|
||||
from starlette.datastructures import Headers
|
||||
@@ -9,15 +7,6 @@ from facefusion.apis.api_helper import get_sec_websocket_protocol
|
||||
from facefusion.types import Token
|
||||
|
||||
|
||||
def validate_api_key(api_key : Optional[str]) -> bool:
|
||||
__api_key__ = os.getenv('FACEFUSION_API_KEY')
|
||||
|
||||
if api_key and __api_key__:
|
||||
return secrets.compare_digest(api_key, __api_key__)
|
||||
|
||||
return bool(api_key) == bool(__api_key__)
|
||||
|
||||
|
||||
def extract_access_token(scope : Scope) -> Optional[Token]:
|
||||
if scope.get('type') == 'http':
|
||||
auth_header = Headers(scope = scope).get('Authorization')
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import os
|
||||
import secrets
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def validate_api_key(api_key : Optional[str]) -> bool:
|
||||
__api_key__ = os.getenv('FACEFUSION_API_KEY')
|
||||
|
||||
if api_key and __api_key__:
|
||||
return secrets.compare_digest(api_key, __api_key__)
|
||||
|
||||
return bool(api_key) == bool(__api_key__)
|
||||
@@ -1,44 +1,9 @@
|
||||
from typing import Literal, get_origin
|
||||
|
||||
from facefusion import capability_store
|
||||
from facefusion.common_helper import cast_bool, cast_float, cast_int
|
||||
from facefusion.normalizer import normalize_color, normalize_space
|
||||
from facefusion.processors.types import ProcessorState
|
||||
from facefusion.types import State, StateKey, StateValue
|
||||
|
||||
|
||||
def validate_argument_key(key : StateKey) -> bool:
|
||||
return key in capability_store.get_api_arguments()
|
||||
|
||||
|
||||
def validate_argument_value(key : StateKey, value : StateValue) -> bool:
|
||||
argument_type = (State.__annotations__ | ProcessorState.__annotations__).get(key)
|
||||
choices = capability_store.get_api_capability_set().get(key).get('choices')
|
||||
|
||||
if argument_type in [ int, float, str ]:
|
||||
if choices:
|
||||
return isinstance(value, argument_type) and value in choices
|
||||
|
||||
return isinstance(value, argument_type)
|
||||
|
||||
if get_origin(argument_type) is list:
|
||||
if choices:
|
||||
return isinstance(value, list) and all(choice in choices for choice in value)
|
||||
|
||||
return isinstance(value, list)
|
||||
|
||||
if get_origin(argument_type) is tuple:
|
||||
return isinstance(value, tuple)
|
||||
|
||||
if get_origin(argument_type) is Literal:
|
||||
if choices:
|
||||
return isinstance(value, str) and value in choices
|
||||
|
||||
return isinstance(value, str)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def normalize_argument_value(key : StateKey, value : StateValue) -> StateValue:
|
||||
argument_type = (State.__annotations__ | ProcessorState.__annotations__).get(key)
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
from typing import Literal, get_origin
|
||||
|
||||
from facefusion import capability_store
|
||||
from facefusion.processors.types import ProcessorState
|
||||
from facefusion.types import State, StateKey, StateValue
|
||||
|
||||
|
||||
def validate_argument_key(key : StateKey) -> bool:
|
||||
return key in capability_store.get_api_arguments()
|
||||
|
||||
|
||||
def validate_argument_value(key : StateKey, value : StateValue) -> bool:
|
||||
argument_type = (State.__annotations__ | ProcessorState.__annotations__).get(key)
|
||||
choices = capability_store.get_api_capability_set().get(key).get('choices')
|
||||
|
||||
if argument_type in [ int, float, str ]:
|
||||
if choices:
|
||||
return isinstance(value, argument_type) and value in choices
|
||||
|
||||
return isinstance(value, argument_type)
|
||||
|
||||
if get_origin(argument_type) is list:
|
||||
if choices:
|
||||
return isinstance(value, list) and all(choice in choices for choice in value)
|
||||
|
||||
return isinstance(value, list)
|
||||
|
||||
if get_origin(argument_type) is tuple:
|
||||
return isinstance(value, tuple)
|
||||
|
||||
if get_origin(argument_type) is Literal:
|
||||
if choices:
|
||||
return isinstance(value, str) and value in choices
|
||||
|
||||
return isinstance(value, str)
|
||||
|
||||
return True
|
||||
@@ -0,0 +1,32 @@
|
||||
import pytest
|
||||
|
||||
from facefusion.apis.asset_validator import validate_frame_index, validate_resolution, validate_subject
|
||||
|
||||
|
||||
def test_validate_subject() -> None:
|
||||
assert validate_subject('frame') is True
|
||||
assert validate_subject('face') is True
|
||||
assert validate_subject('invalid') is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize('resolution, expected',
|
||||
[
|
||||
('63x63', False),
|
||||
('64x64', True),
|
||||
('4096x4096', True),
|
||||
('4097x4097', False),
|
||||
('invalid', False)
|
||||
])
|
||||
def test_validate_resolution(resolution : str, expected : bool) -> None:
|
||||
assert validate_resolution(resolution) is expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize('frame_index_total, expected',
|
||||
[
|
||||
(0, False),
|
||||
(1, True),
|
||||
(100, True),
|
||||
(101, False)
|
||||
])
|
||||
def test_validate_frame_index(frame_index_total : int, expected : bool) -> None:
|
||||
assert validate_frame_index([ '0' ] * frame_index_total) is expected
|
||||
@@ -0,0 +1,18 @@
|
||||
from typing import cast
|
||||
|
||||
import pytest
|
||||
|
||||
from facefusion.apis.job_validator import validate_status
|
||||
from facefusion.types import JobStatus
|
||||
|
||||
|
||||
@pytest.mark.parametrize('job_status, expected',
|
||||
[
|
||||
('drafted', True),
|
||||
('queued', True),
|
||||
('completed', True),
|
||||
('failed', True),
|
||||
('invalid', False)
|
||||
])
|
||||
def test_validate_status(job_status : str, expected : bool) -> None:
|
||||
assert validate_status(cast(JobStatus, job_status)) is expected
|
||||
@@ -0,0 +1,36 @@
|
||||
from argparse import ArgumentParser
|
||||
from typing import cast
|
||||
|
||||
import pytest
|
||||
|
||||
from facefusion import capability_store, state_manager
|
||||
from facefusion.apis.state_validator import validate_argument_key, validate_argument_value
|
||||
from facefusion.types import StateKey
|
||||
|
||||
|
||||
@pytest.fixture(scope = 'module', autouse = True)
|
||||
def before_all() -> None:
|
||||
state_manager.init()
|
||||
|
||||
program = ArgumentParser()
|
||||
capability_store.register_capability_set(
|
||||
[
|
||||
program.add_argument(
|
||||
'--execution-providers',
|
||||
nargs = '+',
|
||||
choices = [ 'cpu', 'cuda' ]
|
||||
)
|
||||
],
|
||||
scopes = [ 'api' ],
|
||||
groups = [ 'execution' ])
|
||||
|
||||
|
||||
def test_validate_argument_key() -> None:
|
||||
assert validate_argument_key(cast(StateKey, 'execution_providers')) is True
|
||||
assert validate_argument_key(cast(StateKey, 'invalid')) is False
|
||||
|
||||
|
||||
def test_validate_argument_value() -> None:
|
||||
assert validate_argument_value(cast(StateKey, 'execution_providers'), [ 'cpu' ]) is True
|
||||
assert validate_argument_value(cast(StateKey, 'execution_providers'), [ 'invalid' ]) is False
|
||||
assert validate_argument_value(cast(StateKey, 'execution_providers'), 'invalid') is False
|
||||
Reference in new issue
Block a user