NguyNhu commited on
Commit
3ba3e17
·
verified ·
1 Parent(s): f330d7c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -76
app.py CHANGED
@@ -1,91 +1,67 @@
1
- # -*- coding:UTF-8 -*-
2
- # !/usr/bin/env python
3
- import spaces
 
4
  import numpy as np
5
  import gradio as gr
6
- import gradio.exceptions
7
- import roop.globals
8
- from roop.core import (
9
- start,
10
- decode_execution_providers,
11
- )
12
- from roop.processors.frame.core import get_frame_processors_modules
13
- from roop.utilities import normalize_output_path
14
- import os
15
- import random
16
- from PIL import Image
17
- import onnxruntime as ort
18
- import cv2
19
- from roop.face_analyser import get_one_face
20
-
21
- @spaces.GPU
22
- def swap_face(source_file, target_file, doFaceEnhancer):
23
- session_dir = "temp" # Sử dụng thư mục cố định
24
- os.makedirs(session_dir, exist_ok=True)
25
 
26
- # Tạo tên file ngẫu nhiên
27
- source_filename = f"source_{random.randint(1000, 9999)}.jpg"
28
- target_filename = f"target_{random.randint(1000, 9999)}.jpg"
29
- output_filename = f"output_{random.randint(1000, 9999)}.jpg"
30
 
31
- source_path = os.path.join(session_dir, source_filename)
32
- target_path = os.path.join(session_dir, target_filename)
 
 
 
 
33
 
34
- source_image = Image.fromarray(source_file)
35
- source_image.save(source_path)
36
- target_image = Image.fromarray(target_file)
37
- target_image.save(target_path)
38
 
39
- print("source_path: ", source_path)
40
- print("target_path: ", target_path)
 
41
 
42
- # Check if a face is detected in the source image
43
- source_face = get_one_face(cv2.imread(source_path))
44
- if source_face is None:
45
- raise gradio.exceptions.Error("No face in source path detected.")
46
 
47
- # Check if a face is detected in the target image
48
- target_face = get_one_face(cv2.imread(target_path))
49
- if target_face is None:
50
- raise gradio.exceptions.Error("No face in target path detected.")
51
 
52
- output_path = os.path.join(session_dir, output_filename)
53
- normalized_output_path = normalize_output_path(source_path, target_path, output_path)
 
 
 
54
 
55
- frame_processors = ["face_swapper", "face_enhancer"] if doFaceEnhancer else ["face_swapper"]
 
56
 
57
- for frame_processor in get_frame_processors_modules(frame_processors):
58
- if not frame_processor.pre_check():
59
- print(f"Pre-check failed for {frame_processor}")
60
- raise gradio.exceptions.Error(f"Pre-check failed for {frame_processor}")
61
 
62
- roop.globals.source_path = source_path
63
- roop.globals.target_path = target_path
64
- roop.globals.output_path = normalized_output_path
65
- roop.globals.frame_processors = frame_processors
66
- roop.globals.headless = True
67
- roop.globals.keep_fps = True
68
- roop.globals.keep_audio = True
69
- roop.globals.keep_frames = False
70
- roop.globals.many_faces = False
71
- roop.globals.video_encoder = "libx264"
72
- roop.globals.video_quality = 18
73
- roop.globals.execution_providers = decode_execution_providers(['cpu'])
74
- roop.globals.reference_face_position = 0
75
- roop.globals.similar_face_distance = 0.6
76
- roop.globals.max_memory = 60
77
- roop.globals.execution_threads = 8
78
-
79
- start()
80
- return normalized_output_path
81
 
82
- app = gr.Interface(
83
- fn=swap_face,
 
84
  inputs=[
85
- gr.Image(),
86
- gr.Image(),
87
- gr.Checkbox(label="Face Enhancer?", info="Do face enhancement?")
88
- ],
89
- outputs="image"
 
90
  )
91
- app.launch()
 
 
 
1
+ import insightface
2
+ from insightface.app import FaceAnalysis
3
+ import cv2
4
+ import os
5
  import numpy as np
6
  import gradio as gr
7
+ import urllib.request
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
+ # URL đến hình hoán đổi khuôn mặt
10
+ model_url = "https://huggingface.co/ezioruan/inswapper_128.onnx/resolve/main/inswapper_128.onnx"
11
+ model_path = os.path.expanduser('~/.insightface/models/inswapper_128.onnx')
 
12
 
13
+ # Tải hình nếu chưa tồn tại
14
+ os.makedirs(os.path.dirname(model_path), exist_ok=True)
15
+ if not os.path.exists(model_path):
16
+ print("Đang tải mô hình từ URL...")
17
+ urllib.request.urlretrieve(model_url, model_path)
18
+ print("Hoàn tất tải mô hình!")
19
 
20
+ # Khởi tạo đối tượng INSwapper
21
+ swapper = insightface.model_zoo.get_model(model_path)
 
 
22
 
23
+ # Khởi tạo mô hình nhận diện khuôn mặt
24
+ app = FaceAnalysis(name='buffalo_l')
25
+ app.prepare(ctx_id=0, det_size=(640, 640))
26
 
27
+ def swap_faces(source_img, target_img):
28
+ # Đọc ảnh từ đầu vào Gradio
29
+ source_img = cv2.cvtColor(np.array(source_img), cv2.COLOR_RGB2BGR)
30
+ target_img = cv2.cvtColor(np.array(target_img), cv2.COLOR_RGB2BGR)
31
 
32
+ # Phát hiện khuôn mặt
33
+ source_faces = app.get(source_img)
34
+ target_faces = app.get(target_img)
 
35
 
36
+ # Kiểm tra xem có phát hiện được khuôn mặt hay không
37
+ if len(source_faces) == 0:
38
+ raise gr.Error("❌ Không tìm thấy khuôn mặt trong ảnh nguồn.")
39
+ if len(target_faces) == 0:
40
+ raise gr.Error("❌ Không tìm thấy khuôn mặt trong ảnh đích.")
41
 
42
+ # Chọn khuôn mặt đầu tiên trong ảnh nguồn
43
+ source_face = source_faces[0]
44
 
45
+ # Thực hiện hoán đổi khuôn mặt
46
+ result_img = target_img.copy()
47
+ for target_face in target_faces:
48
+ result_img = swapper.get(result_img, target_face, source_face, paste_back=True)
49
 
50
+ # Chuyển kết quả sang định dạng RGB để hiển thị trong Gradio
51
+ result_img = cv2.cvtColor(result_img, cv2.COLOR_BGR2RGB)
52
+ return result_img
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
+ # Tạo giao diện Gradio
55
+ iface = gr.Interface(
56
+ fn=swap_faces,
57
  inputs=[
58
+ gr.Image(type="pil", label="Ảnh Nguồn"),
59
+ gr.Image(type="pil", label="Ảnh Đích"),
60
+ ],
61
+ outputs=gr.Image(type="numpy", label="Kết Quả Hoán Đổi Khuôn Mặt"),
62
+ title="Hoán Đổi Khuôn Mặt",
63
+ description="Tải lên ảnh nguồn và ảnh đích để hoán đổi khuôn mặt.",
64
  )
65
+
66
+ # Chạy giao diện
67
+ iface.launch()