ishworrsubedii commited on
Commit
fd8a60f
·
verified ·
1 Parent(s): 8ab0539

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +130 -27
app.py CHANGED
@@ -1,5 +1,5 @@
1
  # -*- coding:UTF-8 -*-
2
- # !/usr/bin/env python
3
  import spaces
4
  import numpy as np
5
  import gradio as gr
@@ -18,47 +18,87 @@ 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
@@ -76,16 +116,79 @@ def swap_face(source_file, target_file, doFaceEnhancer):
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
  # -*- coding:UTF-8 -*-
2
+ #!/usr/bin/env python
3
  import spaces
4
  import numpy as np
5
  import gradio as gr
 
18
  import cv2
19
  from roop.face_analyser import get_one_face
20
 
21
+ # Set up the application theme and styling
22
+ custom_css = """
23
+ .gradio-container {
24
+ font-family: 'Arial', sans-serif;
25
+ }
26
+ .disclaimer {
27
+ background-color: #f8d7da;
28
+ border: 1px solid #f5c6cb;
29
+ color: #721c24;
30
+ padding: 10px;
31
+ margin-bottom: 20px;
32
+ border-radius: 5px;
33
+ }
34
+ .instructions {
35
+ background-color: #e2f0d9;
36
+ border: 1px solid #c5e0b4;
37
+ padding: 10px;
38
+ margin-bottom: 20px;
39
+ border-radius: 5px;
40
+ }
41
+ """
42
+
43
  @spaces.GPU
44
  def swap_face(source_file, target_file, doFaceEnhancer):
45
+ """
46
+ Swap faces between source and target images.
47
+
48
+ Args:
49
+ source_file: Image containing the face to be used
50
+ target_file: Image where the face will be swapped onto
51
+ doFaceEnhancer: Whether to enhance the resulting face
52
+
53
+ Returns:
54
+ Path to the output image with the swapped face
55
+ """
56
+ # Create a temporary directory for processing
57
+ session_dir = "temp"
58
  os.makedirs(session_dir, exist_ok=True)
59
+
60
+ # Generate random filenames to avoid conflicts
61
  source_filename = f"source_{random.randint(1000, 9999)}.jpg"
62
  target_filename = f"target_{random.randint(1000, 9999)}.jpg"
63
  output_filename = f"output_{random.randint(1000, 9999)}.jpg"
64
+
65
+ # Save uploaded images to the temporary directory
66
  source_path = os.path.join(session_dir, source_filename)
67
  target_path = os.path.join(session_dir, target_filename)
68
+
69
  source_image = Image.fromarray(source_file)
70
  source_image.save(source_path)
71
+
72
  target_image = Image.fromarray(target_file)
73
  target_image.save(target_path)
74
+
75
+ print("Processing source image:", source_path)
76
+ print("Processing target image:", target_path)
77
+
78
  # Check if a face is detected in the source image
79
  source_face = get_one_face(cv2.imread(source_path))
80
  if source_face is None:
81
+ raise gradio.exceptions.Error("No face detected in the source image. Please upload a clear photo with a face.")
82
+
83
  # Check if a face is detected in the target image
84
  target_face = get_one_face(cv2.imread(target_path))
85
  if target_face is None:
86
+ raise gradio.exceptions.Error("No face detected in the target image. Please upload a clear photo with a face.")
87
+
88
+ # Set up output path
89
  output_path = os.path.join(session_dir, output_filename)
90
  normalized_output_path = normalize_output_path(source_path, target_path, output_path)
91
+
92
+ # Determine which processors to use
93
  frame_processors = ["face_swapper", "face_enhancer"] if doFaceEnhancer else ["face_swapper"]
94
+
95
+ # Validate processors
96
  for frame_processor in get_frame_processors_modules(frame_processors):
97
  if not frame_processor.pre_check():
98
  print(f"Pre-check failed for {frame_processor}")
99
+ raise gradio.exceptions.Error(f"The {frame_processor} module failed to initialize. Please try again.")
100
+
101
+ # Configure roop settings
102
  roop.globals.source_path = source_path
103
  roop.globals.target_path = target_path
104
  roop.globals.output_path = normalized_output_path
 
116
  roop.globals.max_memory = 60
117
  roop.globals.execution_threads = 8
118
 
119
+ # Start the face swapping process
120
  start()
121
+
122
  return normalized_output_path
123
 
124
+ # Create the Gradio interface with improved descriptions and layout
125
+ with gr.Blocks(css=custom_css) as app:
126
+ gr.Markdown("# AI Face Swap Tool")
127
+
128
+ with gr.Row():
129
+ with gr.Column():
130
+ gr.Markdown("""
131
+ <div class="disclaimer">
132
+ <h3>⚠️ Ethical Usage Guidelines</h3>
133
+ <p>This tool is provided for educational and creative purposes only. Please use responsibly:</p>
134
+ <ul>
135
+ <li>Do not use to create misleading or deceptive content</li>
136
+ <li>Do not use for harassment or to misrepresent individuals</li>
137
+ <li>Always get consent when using someone's likeness</li>
138
+ <li>Be aware that creating deepfakes may violate laws in some jurisdictions</li>
139
+ </ul>
140
+ </div>
141
+ """)
142
+
143
+ gr.Markdown("""
144
+ <div class="instructions">
145
+ <h3>📝 How to Use This Tool</h3>
146
+ <ol>
147
+ <li><b>Source Image:</b> Upload a clear photo of the face you want to use</li>
148
+ <li><b>Target Image:</b> Upload the photo where you want to place the face</li>
149
+ <li><b>Face Enhancer:</b> Toggle this option to improve the quality of the swapped face</li>
150
+ <li>Click the "Swap Face" button and wait for processing to complete</li>
151
+ </ol>
152
+ <p><b>Tips for best results:</b></p>
153
+ <ul>
154
+ <li>Use high-resolution images with clear, front-facing faces</li>
155
+ <li>Ensure good lighting in both photos</li>
156
+ <li>Similar face angles work best</li>
157
+ <li>Processing may take 10-30 seconds depending on image size</li>
158
+ </ul>
159
+ </div>
160
+ """)
161
+
162
+ with gr.Row():
163
+ with gr.Column():
164
+ source_image = gr.Image(label="Source Face", info="Upload a photo with the face you want to use")
165
+ with gr.Column():
166
+ target_image = gr.Image(label="Target Image", info="Upload the photo where you want to place the face")
167
+
168
+ with gr.Row():
169
+ face_enhancer = gr.Checkbox(
170
+ label="Apply Face Enhancement",
171
+ info="Enable this to improve the quality and realism of the result",
172
+ value=True
173
+ )
174
+
175
+ with gr.Row():
176
+ swap_button = gr.Button("Swap Face", variant="primary")
177
+
178
+ output_image = gr.Image(label="Result")
179
+
180
+ swap_button.click(
181
+ fn=swap_face,
182
+ inputs=[source_image, target_image, face_enhancer],
183
+ outputs=output_image
184
+ )
185
+
186
+ gr.Markdown("""
187
+ ### How It Works
188
+ This application uses AI to detect faces in both images, then carefully transplants the face from
189
+ the source image onto the target image while preserving natural appearance. The optional face
190
+ enhancement feature uses additional AI processing to improve skin texture and details.
191
+ """)
192
+
193
+ # Launch the application
194
  app.launch()