Spaces:
Sleeping

faceIntergrator / app.py
akashh89's picture
Make startup resilient: warm swapper only
14604b1
Raw History Blame Contribute Delete
5.32 kB
import gc
import os
import shutil
import time
import cv2
import gradio as gr
import numpy as np
from PIL import Image
import roop.globals
from roop.core import (
decode_execution_providers,
limit_resources,
start,
suggest_execution_threads,
suggest_max_memory,
)
from roop.processors.frame.core import get_frame_processors_modules
from roop.processors.frame.face_swapper import get_face_swapper
from roop.utilities import create_request_paths, is_image
try:
import torch
except ImportError:
torch = None
MAX_IMAGE_DIMENSION = 1500
PROCESS_TIMEOUT_SECONDS = 45
QUEUE_MAX_SIZE = 20
QUEUE_CONCURRENCY_LIMIT = 1
RESOURCES_INITIALIZED = False
def _validate_image_array(image_array, label: str) -> None:
if image_array is None:
raise gr.Error(f"{label} is missing.")
if not isinstance(image_array, np.ndarray):
raise gr.Error(f"{label} is invalid.")
if image_array.size == 0:
raise gr.Error(f"{label} is empty.")
def _resize_if_needed(image: Image.Image) -> Image.Image:
if image.width <= MAX_IMAGE_DIMENSION and image.height <= MAX_IMAGE_DIMENSION:
return image
resized = image.copy()
resized.thumbnail((MAX_IMAGE_DIMENSION, MAX_IMAGE_DIMENSION), Image.Resampling.LANCZOS)
return resized
def _save_and_validate_image(image_array: np.ndarray, output_path: str, label: str) -> None:
image = Image.fromarray(image_array).convert('RGB')
image = _resize_if_needed(image)
image.save(output_path)
decoded = cv2.imread(output_path)
if decoded is None:
raise gr.Error(f"{label} could not be decoded as a valid image.")
def _initialize_runtime(do_face_enhancer: bool) -> None:
global RESOURCES_INITIALIZED
roop.globals.frame_processors = ['face_swapper', 'face_enhancer'] if do_face_enhancer else ['face_swapper']
roop.globals.headless = True
roop.globals.keep_fps = True
roop.globals.keep_audio = True
roop.globals.keep_frames = False
roop.globals.many_faces = False
roop.globals.video_encoder = 'libx264'
roop.globals.video_quality = 18
roop.globals.max_memory = suggest_max_memory()
roop.globals.execution_providers = decode_execution_providers(['cpu'])
roop.globals.execution_threads = suggest_execution_threads()
if not RESOURCES_INITIALIZED:
limit_resources()
RESOURCES_INITIALIZED = True
def _run_prechecks(frame_processors) -> None:
for frame_processor in frame_processors:
if not frame_processor.pre_check():
raise gr.Error("Model pre-check failed.")
def _warmup_models() -> None:
# Keep startup resilient on Spaces:
# warm only mandatory swapper path, defer enhancer download/init to request time.
_initialize_runtime(do_face_enhancer=False)
frame_processors = get_frame_processors_modules(['face_swapper'])
_run_prechecks(frame_processors)
get_face_swapper()
def swap_face(source_file, target_file, do_face_enhancer):
_validate_image_array(source_file, "Source image")
_validate_image_array(target_file, "Target image")
request_paths = create_request_paths('.jpg')
source_path = request_paths['source_path']
target_path = request_paths['target_path']
output_path = request_paths['output_path']
request_directory = request_paths['request_directory']
roop.globals.request_timeout_deadline = time.monotonic() + PROCESS_TIMEOUT_SECONDS
try:
_save_and_validate_image(source_file, source_path, 'Source image')
_save_and_validate_image(target_file, target_path, 'Target image')
if not is_image(source_path) or not is_image(target_path):
raise gr.Error("Invalid input. Please upload valid image files.")
roop.globals.source_path = source_path
roop.globals.target_path = target_path
roop.globals.output_path = output_path
_initialize_runtime(do_face_enhancer=do_face_enhancer)
frame_processors = get_frame_processors_modules(roop.globals.frame_processors)
_run_prechecks(frame_processors)
start()
if not os.path.exists(output_path):
raise gr.Error("Swap failed. Check that both images contain a clear face.")
with Image.open(output_path) as result_image:
return np.array(result_image.convert('RGB'))
except TimeoutError as exc:
raise gr.Error(f"Swap timed out after {PROCESS_TIMEOUT_SECONDS}s: {exc}") from exc
except Exception as exc:
raise gr.Error(f"Swap failed: {exc}") from exc
finally:
roop.globals.request_timeout_deadline = None
shutil.rmtree(request_directory, ignore_errors=True)
gc.collect()
if torch is not None and torch.cuda.is_available():
torch.cuda.empty_cache()
title = 'Face Integrator'
description = (
'This project uses AI models (InsightFace inswapper, TencentARC GFPGAN). '
'Models are verified with checksums for safety.'
)
app = gr.Interface(
fn=swap_face,
title=title,
description=description,
inputs=[
gr.Image(label='Source Image'),
gr.Image(label='Target Image'),
gr.Checkbox(label='Apply Face Enhancement'),
],
outputs='image',
)
_warmup_models()
app.queue(max_size=QUEUE_MAX_SIZE, default_concurrency_limit=QUEUE_CONCURRENCY_LIMIT).launch()