Spaces:
Sleeping
Sleeping
| import insightface | |
| from insightface.app import FaceAnalysis | |
| import cv2 | |
| import os | |
| import numpy as np | |
| import gradio as gr | |
| import urllib.request | |
| # URL đến mô hình hoán đổi khuôn mặt | |
| model_url = "https://huggingface.co/ezioruan/inswapper_128.onnx/resolve/main/inswapper_128.onnx" | |
| model_path = os.path.expanduser('~/.insightface/models/inswapper_128.onnx') | |
| # Tải mô hình nếu chưa tồn tại | |
| 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!") | |
| # Khởi tạo đối tượng INSwapper | |
| swapper = insightface.model_zoo.get_model(model_path) | |
| # Khởi tạo mô hình nhận diện khuôn mặt | |
| app = FaceAnalysis(name='buffalo_l') | |
| app.prepare(ctx_id=0, det_size=(640, 640)) | |
| def swap_faces(source_img, target_img): | |
| # Đọc ảnh từ đầu vào Gradio | |
| source_img = cv2.cvtColor(np.array(source_img), cv2.COLOR_RGB2BGR) | |
| target_img = cv2.cvtColor(np.array(target_img), cv2.COLOR_RGB2BGR) | |
| # Phát hiện khuôn mặt | |
| source_faces = app.get(source_img) | |
| target_faces = app.get(target_img) | |
| # Kiểm tra xem có phát hiện được khuôn mặt hay không | |
| 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.") | |
| # Chọn khuôn mặt đầu tiên trong ảnh nguồn | |
| source_face = source_faces[0] | |
| # Thực hiện hoán đổi khuôn mặt | |
| result_img = target_img.copy() | |
| for target_face in target_faces: | |
| result_img = swapper.get(result_img, target_face, source_face, paste_back=True) | |
| # Chuyển kết quả sang định dạng RGB để hiển thị trong Gradio | |
| result_img = cv2.cvtColor(result_img, cv2.COLOR_BGR2RGB) | |
| return result_img | |
| # Tạo giao diện Gradio | |
| 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.", | |
| ) | |
| # Chạy giao diện | |
| iface.launch() |