Spaces:
Sleeping

File size: 5,324 Bytes
bbb3afa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14604b1
 
 
 
bbb3afa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
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()