|
import insightface |
|
from insightface.app import FaceAnalysis |
|
import cv2 |
|
import os |
|
import numpy as np |
|
import gradio as gr |
|
import urllib.request |
|
|
|
|
|
model_url = "https://huggingface.co/ezioruan/inswapper_128.onnx/resolve/main/inswapper_128.onnx" |
|
model_path = os.path.expanduser('~/.insightface/models/inswapper_128.onnx') |
|
|
|
|
|
os.makedirs(os.path.dirname(model_path), exist_ok=True) |
|
if not os.path.exists(model_path): |
|
print("Đang tải mô hình từ URL...") |
|
urllib.request.urlretrieve(model_url, model_path) |
|
print("Hoàn tất tải mô hình!") |
|
|
|
|
|
swapper = insightface.model_zoo.get_model(model_path) |
|
|
|
|
|
app = FaceAnalysis(name='buffalo_l') |
|
app.prepare(ctx_id=0, det_size=(640, 640)) |
|
|
|
def swap_faces(source_img, target_img): |
|
|
|
source_img = cv2.cvtColor(np.array(source_img), cv2.COLOR_RGB2BGR) |
|
target_img = cv2.cvtColor(np.array(target_img), cv2.COLOR_RGB2BGR) |
|
|
|
|
|
source_faces = app.get(source_img) |
|
target_faces = app.get(target_img) |
|
|
|
|
|
if len(source_faces) == 0: |
|
raise gr.Error("❌ Không tìm thấy khuôn mặt trong ảnh nguồn.") |
|
if len(target_faces) == 0: |
|
raise gr.Error("❌ Không tìm thấy khuôn mặt trong ảnh đích.") |
|
|
|
|
|
source_face = source_faces[0] |
|
|
|
|
|
result_img = target_img.copy() |
|
for target_face in target_faces: |
|
result_img = swapper.get(result_img, target_face, source_face, paste_back=True) |
|
|
|
|
|
result_img = cv2.cvtColor(result_img, cv2.COLOR_BGR2RGB) |
|
return result_img |
|
|
|
|
|
iface = gr.Interface( |
|
fn=swap_faces, |
|
inputs=[ |
|
gr.Image(type="pil", label="Ảnh Nguồn"), |
|
gr.Image(type="pil", label="Ảnh Đích"), |
|
], |
|
outputs=gr.Image(type="numpy", label="Kết Quả Hoán Đổi Khuôn Mặt"), |
|
title="Hoán Đổi Khuôn Mặt", |
|
description="Tải lên ảnh nguồn và ảnh đích để hoán đổi khuôn mặt.", |
|
) |
|
|
|
|
|
iface.launch() |