File size: 7,681 Bytes
fd45fc3
 
7d9faed
9eb479d
fd45fc3
 
7d9faed
b3605aa
170887a
675613c
580f903
1ac1172
675613c
 
 
 
 
 
 
 
 
1ac1172
675613c
1ac1172
9eb479d
26c3131
675613c
9eb479d
b3605aa
93fae1d
ecd9a03
7d9faed
1ac1172
9941a23
1ac1172
9eb479d
 
8df6fdb
60acabe
26c3131
1ac1172
675613c
1ac1172
 
 
675613c
 
 
 
 
9941a23
675613c
 
 
 
 
 
1ac1172
9941a23
675613c
1ac1172
26c3131
 
1ac1172
 
93fae1d
1ac1172
9941a23
1ac1172
9941a23
26c3131
 
 
1ac1172
675613c
9eb479d
7500a66
ecd9a03
60acabe
1ac1172
 
 
9eb479d
 
ecd9a03
9eb479d
9941a23
 
 
9eb479d
 
1ac1172
 
9eb479d
 
9941a23
9eb479d
9941a23
 
aa99866
1ac1172
9eb479d
1ac1172
9eb479d
675613c
aa1f7cf
9eb479d
7d9faed
1ac1172
 
93fae1d
1ac1172
 
2492ee7
1ac1172
93fae1d
2492ee7
675613c
 
 
1ac1172
7500a66
675613c
 
 
9941a23
7d9faed
9eb479d
 
1ac1172
675613c
9eb479d
 
7d9faed
 
aa1f7cf
b3605aa
7d9faed
1ac1172
9eb479d
1ac1172
9eb479d
 
 
459af64
9941a23
459af64
 
fd45fc3
 
459af64
 
 
 
 
9941a23
459af64
 
9941a23
459af64
 
9941a23
 
 
459af64
 
 
 
 
 
9941a23
459af64
9941a23
459af64
 
9941a23
459af64
 
 
 
9941a23
 
 
 
 
 
 
 
459af64
 
 
9941a23
 
 
459af64
9941a23
 
 
459af64
9941a23
 
459af64
9941a23
 
 
 
459af64
9941a23
 
 
 
 
 
459af64
9941a23
 
f8a4ad9
9941a23
 
 
459af64
 
9941a23
459af64
9941a23
 
 
 
459af64
9941a23
459af64
9941a23
459af64
 
 
9941a23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459af64
 
 
 
 
 
60acabe
1ac1172
9941a23
1ac1172
9eb479d
 
675613c
 
 
 
 
aa1f7cf
70366f8
9eb479d
 
26c3131
 
 
459af64
 
675613c
 
26c3131
9eb479d
aa1f7cf
 
9eb479d
 
aa1f7cf
ecd9a03
aa1f7cf
93fae1d
aa1f7cf
93fae1d
 
9eb479d
 
1ac1172
 
 
9eb479d
7d9faed
675613c
 
 
9941a23
 
 
675613c
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import os
import cv2
import uuid
import time
import numpy as np
import insightface
import concurrent.futures
import traceback

from fastapi import FastAPI, UploadFile, File, HTTPException, Form
from fastapi.responses import HTMLResponse, StreamingResponse

# HEIC SUPPORT
try:
    import pillow_heif
    from PIL import Image
    pillow_heif.register_heif_opener()
    HEIC_SUPPORTED = True
except:
    HEIC_SUPPORTED = False

# ============================================================
# CONFIG
# ============================================================
MAX_FILE_MB = 10
MAX_DIM = 640
MAX_WORKERS = 3
CLEANUP_TIME = 300

TASKS = {}
executor = concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS)

# ============================================================
# LOAD MODELS
# ============================================================
face_app = insightface.app.FaceAnalysis(name="buffalo_l")
face_app.prepare(ctx_id=-1, det_size=(640, 640))

swapper = insightface.model_zoo.get_model("inswapper_128.onnx", root=".")

# ============================================================
# IMAGE HELPERS
# ============================================================

def decode_image(file_bytes):
    arr = np.frombuffer(file_bytes, np.uint8)
    img = cv2.imdecode(arr, cv2.IMREAD_COLOR)

    if img is None and HEIC_SUPPORTED:
        try:
            from PIL import Image
            import io
            pil_img = Image.open(io.BytesIO(file_bytes)).convert("RGB")
            img = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)
        except:
            pass

    if img is None:
        raise ValueError("Unsupported image format")

    return img


def compress_and_resize(file_bytes):
    img = decode_image(file_bytes)

    size_mb = len(file_bytes) / (1024 * 1024)

    if size_mb > MAX_FILE_MB:
        img = cv2.resize(img, None, fx=0.6, fy=0.6, interpolation=cv2.INTER_AREA)

    h, w = img.shape[:2]
    if max(h, w) > MAX_DIM:
        scale = MAX_DIM / max(h, w)
        img = cv2.resize(img, (int(w * scale), int(h * scale)))

    return img


def enhance(img):
    blur = cv2.GaussianBlur(img, (0, 0), 1.2)
    return cv2.addWeighted(img, 1.2, blur, -0.2, 0)


def cleanup():
    now = time.time()
    remove = []

    for k, v in TASKS.items():
        if "time" in v and now - v["time"] > CLEANUP_TIME:
            try:
                if "result" in v:
                    os.remove(v["result"])
            except:
                pass
            remove.append(k)

    for k in remove:
        TASKS.pop(k, None)

# ============================================================
# WORKER
# ============================================================

def run_task(tid, src_bytes, tgt_bytes, filename, face_index):
    TASKS[tid]["status"] = "processing"

    try:
        src = compress_and_resize(src_bytes)
        tgt = compress_and_resize(tgt_bytes)

        s_faces = face_app.get(src)
        t_faces = face_app.get(tgt)

        if not s_faces or not t_faces:
            raise ValueError("Face not detected")

        face_index = min(face_index, len(t_faces) - 1)

        result = swapper.get(tgt, t_faces[face_index], s_faces[0], paste_back=True)
        result = enhance(result)

        name = os.path.splitext(filename)[0]
        out_path = f"/tmp/{name}_{tid}.png"

        cv2.imwrite(out_path, result, [cv2.IMWRITE_PNG_COMPRESSION, 3])

        TASKS[tid] = {
            "status": "done",
            "result": out_path,
            "filename": f"{name}.png",
            "time": time.time()
        }

    except Exception as e:
        TASKS[tid] = {"status": "failed", "error": str(e)}
        print(traceback.format_exc())

# ============================================================
# FASTAPI
# ============================================================

app = FastAPI()

# ============================================================
# UI PAGE
# ============================================================

@app.get("/", response_class=HTMLResponse)
def home():
    return """
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Face Swap API Test</title>

<style>
body{font-family:sans-serif;background:#0f172a;color:white;text-align:center;padding:20px}
.box{border:2px dashed #444;padding:20px;margin:10px;border-radius:10px;cursor:pointer}
img{max-width:200px;margin-top:10px;border-radius:8px}
button{padding:12px 20px;background:#6366f1;color:white;border:none;border-radius:8px}
.progress{height:10px;background:#333;margin-top:10px;border-radius:10px;overflow:hidden;display:none}
.bar{height:100%;width:0;background:#22c55e}
</style>

</head>

<body>

<h2>⚡ Face Swap Test UI</h2>

<div class="box" onclick="src.click()">Upload Source<input type="file" id="src" hidden></div>
<img id="p1">

<div class="box" onclick="tgt.click()">Upload Target<input type="file" id="tgt" hidden></div>
<img id="p2">

<br>

<label>Select Face Index:</label>
<input type="number" id="faceIndex" value="0" min="0">

<br><br>

<button onclick="start()">Start Swap</button>

<div class="progress" id="progress"><div class="bar" id="bar"></div></div>

<br>

<img id="out">
<br>
<a id="dl" download="faceswap.png" style="display:none;color:lightgreen">Download PNG</a>

<script>
const src=document.getElementById("src");
const tgt=document.getElementById("tgt");

src.onchange=()=>p1.src=URL.createObjectURL(src.files[0]);
tgt.onchange=()=>p2.src=URL.createObjectURL(tgt.files[0]);

function upload(url,fd){
 return new Promise((res,rej)=>{
  let xhr=new XMLHttpRequest();
  xhr.open("POST",url);

  xhr.upload.onprogress=(e)=>{
    if(e.lengthComputable){
      progress.style.display="block";
      bar.style.width=(e.loaded/e.total*100)+"%";
    }
  };

  xhr.onload=()=>res(JSON.parse(xhr.responseText));
  xhr.onerror=rej;

  xhr.send(fd);
 });
}

async function start(){
 if(!src.files[0]||!tgt.files[0]) return alert("Upload both");

 let fd=new FormData();
 fd.append("source",src.files[0]);
 fd.append("target",tgt.files[0]);
 fd.append("face_index",document.getElementById("faceIndex").value);

 let data=await upload("/swap",fd);

 poll(data.task_id);
}

async function poll(id){
 let r=await fetch("/status/"+id);
 let j=await r.json();

 if(j.status==="done"){
   let img=await fetch("/result/"+id);
   let blob=await img.blob();
   let url=URL.createObjectURL(blob);

   out.src=url;
   dl.href=url;
   dl.style.display="block";

   bar.style.width="100%";
 }
 else if(j.status==="failed"){
   alert(j.error);
 }
 else{
   setTimeout(()=>poll(id),800);
 }
}
</script>

</body>
</html>
"""

# ============================================================
# API
# ============================================================

@app.post("/swap")
async def swap(
    source: UploadFile = File(...),
    target: UploadFile = File(...),
    face_index: int = Form(0)
):
    tid = str(uuid.uuid4())

    TASKS[tid] = {"status": "queued", "time": time.time()}

    executor.submit(
        run_task,
        tid,
        await source.read(),
        await target.read(),
        source.filename,
        face_index
    )

    return {"task_id": tid}


@app.get("/status/{tid}")
def status(tid: str):
    cleanup()
    if tid not in TASKS:
        raise HTTPException(404)
    return TASKS[tid]


@app.get("/result/{tid}")
def result(tid: str):
    task = TASKS.get(tid)

    if not task or task["status"] != "done":
        raise HTTPException(404)

    return StreamingResponse(
        open(task["result"], "rb"),
        media_type="image/png",
        headers={
            "Content-Disposition": f'attachment; filename="{task["filename"]}"'
        }
    )