Spaces:
Runtime error
Runtime error
| # TÊN TỆP: app.py (Mã đã được dọn dẹp và sử dụng cache) | |
| import gradio as gr | |
| import cv2 | |
| import numpy as np | |
| import insightface | |
| from insightface.app import FaceAnalysis | |
| # KHỞI TẠO MÔ HÌNH (Chỉ chạy một lần khi ứng dụng khởi động) | |
| # Sử dụng hàm get_model_path để buộc InsightFace sử dụng các mô hình đã tải | |
| # LƯU Ý: Nếu lỗi, hãy xóa file model.py đã tạo trước đó (nếu có) | |
| try: | |
| # Tải mô hình Face Analysis để phát hiện khuôn mặt | |
| app = FaceAnalysis( | |
| name='buffalo_l', | |
| providers=['CPUExecutionProvider'] | |
| ) | |
| app.prepare(ctx_id=0, det_size=(640, 640)) | |
| # Tải mô hình Face Swapper (InSwapper) | |
| # Vì quá trình tải xuống trước đó đã thành công, tệp phải tồn tại trong cache | |
| swapper = insightface.model_zoo.get_model('inswapper_128.onnx', providers=['CPUExecutionProvider']) | |
| except Exception as e: | |
| print(f"FATAL ERROR during model initialization: {e}") | |
| # Nếu lỗi, ứng dụng sẽ không chạy, nhưng chúng ta đã loại bỏ nguyên nhân gây lỗi bên ngoài. | |
| raise e | |
| # HÀM HOÁN ĐỔI KHUÔN MẶT THỰC TẾ | |
| def face_swap_function(source_path, target_path): | |
| # ... (Giữ nguyên logic hàm) | |
| try: | |
| img_source = cv2.imread(source_path) | |
| img_target = cv2.imread(target_path) | |
| except Exception: | |
| return cv2.cvtColor(np.zeros((200, 200, 3), dtype=np.uint8), cv2.COLOR_BGR2RGB) | |
| if img_source is None or img_target is None: | |
| return cv2.cvtColor(np.zeros((200, 200, 3), dtype=np.uint8), cv2.COLOR_BGR2RGB) | |
| faces_source = app.get(img_source) | |
| if not faces_source: | |
| return cv2.cvtColor(img_target, cv2.COLOR_BGR2RGB) | |
| source_face = faces_source[0] | |
| faces_target = app.get(img_target) | |
| if not faces_target: | |
| return cv2.cvtColor(img_target, cv2.COLOR_BGR2RGB) | |
| target_face = faces_target[0] | |
| result_img = swapper.get(img_target, target_face, source_face, paste_back=True) | |
| return cv2.cvtColor(result_img, cv2.COLOR_BGR2RGB) | |
| # TẠO GIAO DIỆN GRADIO | |
| demo = gr.Interface( | |
| fn=face_swap_function, | |
| inputs=[ | |
| gr.Image(type="filepath", label="Ảnh Nguồn (Khuôn mặt bạn muốn dùng)"), | |
| gr.Image(type="filepath", label="Ảnh Đích (Khuôn mặt bạn muốn thay thế)") | |
| ], | |
| outputs=gr.Image(type="numpy", label="Kết quả Hoán đổi Khuôn mặt (Face Swap)"), | |
| title="Ứng dụng Hoán đổi Khuôn mặt INSIGHTFACE Hoàn chỉnh" | |
| ) | |
| # Chạy ứng dụng | |
| demo.launch() | |