Spaces:
Running
Running
Upload app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import insightface
|
| 3 |
+
from insightface.app import FaceAnalysis
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
# ---------- HTML description ----------
|
| 8 |
+
wellcomingMessage = """
|
| 9 |
+
<h1>Face Swap</h1>
|
| 10 |
+
<p>by <a href="https://www.tonyassi.com/" target="_blank" style="color:#97d8be;">Tony Assi</a></p>
|
| 11 |
+
<h2>Try out <a href="https://huggingface.co/spaces/tonyassi/video-face-swap" target="_blank">Video Face Swap</a> ❤️</h2>
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
# ---------- Check version ----------
|
| 15 |
+
assert insightface.__version__ >= '0.7'
|
| 16 |
+
|
| 17 |
+
# ---------- Initialize models ----------
|
| 18 |
+
app = FaceAnalysis(name='buffalo_l')
|
| 19 |
+
app.prepare(ctx_id=0, det_size=(640, 640))
|
| 20 |
+
|
| 21 |
+
# ensure model downloads fully; safer with download=True and zip=True like your working version
|
| 22 |
+
swapper = insightface.model_zoo.get_model('inswapper_128.onnx', download=True, download_zip=True)
|
| 23 |
+
|
| 24 |
+
# ---------- Swap logic ----------
|
| 25 |
+
def swap_faces(src_img, dest_img):
|
| 26 |
+
src_faces = app.get(src_img)
|
| 27 |
+
dest_faces = app.get(dest_img)
|
| 28 |
+
|
| 29 |
+
if len(src_faces) == 0 or len(dest_faces) == 0:
|
| 30 |
+
raise gr.Error("No faces detected in one of the images.")
|
| 31 |
+
|
| 32 |
+
# Just swap first detected face from each image
|
| 33 |
+
source_face = src_faces[0]
|
| 34 |
+
dest_face = dest_faces[0]
|
| 35 |
+
result = swapper.get(dest_img, dest_face, source_face, paste_back=True)
|
| 36 |
+
|
| 37 |
+
return Image.fromarray(np.uint8(result)).convert("RGB")
|
| 38 |
+
|
| 39 |
+
# ---------- Interface ----------
|
| 40 |
+
gr.Interface(
|
| 41 |
+
fn=swap_faces,
|
| 42 |
+
inputs=[gr.Image(), gr.Image()],
|
| 43 |
+
outputs=gr.Image(),
|
| 44 |
+
description=wellcomingMessage,
|
| 45 |
+
examples=[
|
| 46 |
+
['./Images/kim.jpg', './Images/marilyn.jpg'],
|
| 47 |
+
],
|
| 48 |
+
).launch()
|