File size: 2,258 Bytes
5a3db6b
 
 
 
 
 
 
 
 
8f78e06
 
 
5a3db6b
 
 
 
 
 
 
 
 
8f78e06
 
5a3db6b
 
 
8f78e06
5a3db6b
 
 
 
 
8f78e06
 
 
4beab5e
8f78e06
5a3db6b
 
8f78e06
5a3db6b
 
 
 
 
 
 
8f78e06
5a3db6b
8f78e06
5a3db6b
 
 
 
 
 
 
 
 
 
8f78e06
5a3db6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4beab5e
5a3db6b
8f78e06
 
5a3db6b
 
 
 
 
 
 
 
8f78e06
4beab5e
8f78e06
 
5a3db6b
 
 
 
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
import os
import gc
import cv2
import gradio as gr
import numpy as np
from PIL import Image
from insightface.app import FaceAnalysis
from insightface.model_zoo import get_model

# -----------------------------
# OpenCV CPU control
# -----------------------------
cv2.setNumThreads(2)

# -----------------------------
# Model path (ROOT folder)
# -----------------------------
SWAP_MODEL_PATH = "inswapper_128.onnx"

if not os.path.exists(SWAP_MODEL_PATH):
    raise RuntimeError(
        "❌ inswapper_128.onnx not found.\n"
        "Upload it in the SAME folder as app.py"
    )

# -----------------------------
# Face detector (High Quality)
# -----------------------------
face_app = FaceAnalysis(
    providers=["CPUExecutionProvider"],
    allowed_modules=["detection", "recognition"]
)

face_app.prepare(
    ctx_id=0,
    det_size=(640, 640)  # 16 GB RAM safe
)

# -----------------------------
# Load face swap model (LOCAL)
# -----------------------------
swapper = get_model(
    SWAP_MODEL_PATH,
    providers=["CPUExecutionProvider"]
)

# -----------------------------
# Face swap function
# -----------------------------
def face_swap(source_img, target_img):
    try:
        if source_img is None or target_img is None:
            return None

        src = np.array(source_img.convert("RGB"))
        tgt = np.array(target_img.convert("RGB"))

        src_faces = face_app.get(src)
        tgt_faces = face_app.get(tgt)

        if len(src_faces) == 0 or len(tgt_faces) == 0:
            return None

        result = swapper.get(
            tgt,
            tgt_faces[0],
            src_faces[0],
            paste_back=True
        )

        return Image.fromarray(result)

    finally:
        del src, tgt, src_faces, tgt_faces
        gc.collect()

# -----------------------------
# Gradio Interface
# -----------------------------
demo = gr.Interface(
    fn=face_swap,
    inputs=[
        gr.Image(type="pil", label="Source Face"),
        gr.Image(type="pil", label="Target Image")
    ],
    outputs=gr.Image(type="pil"),
    analytics_enabled=False
)

# -----------------------------
# Launch (NO deprecated args)
# -----------------------------
demo.launch(
    server_name="0.0.0.0",
    server_port=7860,
    share=False
)