Athagi commited on
Commit
bf2fc31
·
1 Parent(s): 4dbee63

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -40
app.py CHANGED
@@ -6,6 +6,7 @@ from insightface.app import FaceAnalysis
6
  import onnxruntime
7
  from PIL import Image
8
  import tempfile
 
9
 
10
  # --- Global Configurations and Model Loading ---
11
  # Determine the appropriate provider for ONNX Runtime.
@@ -29,17 +30,21 @@ SIMSWAP_INPUT_SIZE = 256 # SimSwap models typically expect 256x256 input
29
 
30
  if not os.path.exists(SIMSWAP_MODEL_PATH):
31
  raise FileNotFoundError(f"SimSwap model not found at: {SIMSWAP_MODEL_PATH}. "
32
- "Please place 'simswap_256.onnx' in the 'models/' directory.")
33
  try:
34
  simswap_session = onnxruntime.InferenceSession(SIMSWAP_MODEL_PATH, providers=providers)
35
- simswap_input_name = simswap_session.get_inputs()[0].name
 
 
36
  simswap_output_name = simswap_session.get_outputs()[0].name
37
  print(f"SimSwap model '{SIMSWAP_MODEL_PATH}' loaded successfully.")
38
- print(f"SimSwap expected input: {simswap_session.get_inputs()[0].shape}")
39
- print(f"SimSwap output shape: {simswap_session.get_outputs()[0].shape}")
 
40
  except Exception as e:
41
  raise RuntimeError(f"Failed to load SimSwap model from {SIMSWAP_MODEL_PATH}: {e}. "
42
- "Check the model file's integrity and ONNX Runtime compatibility.")
 
43
 
44
 
45
  # --- Helper Functions ---
@@ -120,6 +125,7 @@ def update_faces_preview(target_img_pil: Image.Image):
120
  """
121
  if target_img_pil is None:
122
  # Return default states for all outputs when input is None
 
123
  return None, gr.Slider(minimum=0, maximum=0, value=0, interactive=False), gr.File(value=None, interactive=False), "Please upload a target image first."
124
 
125
  target_np_rgb = np.array(target_img_pil)
@@ -129,13 +135,17 @@ def update_faces_preview(target_img_pil: Image.Image):
129
  num_faces = len(faces)
130
 
131
  if num_faces == 0:
 
 
132
  return None, gr.Slider(minimum=0, maximum=0, value=0, interactive=False), gr.File(value=None, interactive=False), "No faces detected in the target image. Please try another image."
 
 
 
 
133
 
134
- preview_img_bgr = draw_faces(target_np_bgr, faces)
135
- preview_img_rgb = cv2.cvtColor(preview_img_bgr, cv2.COLOR_BGR2RGB)
136
-
137
- # Set the max value of the slider to (number of faces - 1) as indices are 0-based
138
- return preview_img_rgb, gr.Slider(minimum=0, maximum=num_faces - 1, value=0, interactive=True), gr.File(value=None, interactive=False), f"Detected {num_faces} face(s). Select the face to swap using the slider (0-indexed)."
139
 
140
  def face_swap_simswap(source_img_pil: Image.Image, target_img_pil: Image.Image, face_index: int):
141
  """
@@ -164,18 +174,13 @@ def face_swap_simswap(source_img_pil: Image.Image, target_img_pil: Image.Image,
164
  "You might need to click 'Preview Detected Faces' again to update the slider range.")
165
  target_face_info = target_faces[face_index]
166
 
167
- # Crop and align faces using InsightFace's bbox/kps (for robust preprocessing)
168
- # InsightFace's face.embedding is typically derived from an aligned face.
169
- # To get the aligned face itself, you might need to use its ArcFace models or a custom aligner.
170
- # For simplicity, we'll extract the bounding box and then resize/align
171
-
172
- # Extract source face region
173
  x1s, y1s, x2s, y2s = source_face_info.bbox.astype(int)
174
  source_face_crop = source_np_bgr[y1s:y2s, x1s:x2s]
175
  if source_face_crop.size == 0:
176
  raise gr.Error("Could not crop source face properly. Image might be too small or face too close to edge.")
177
 
178
- # Extract target face region
179
  x1t, y1t, x2t, y2t = target_face_info.bbox.astype(int)
180
  target_face_crop = target_np_bgr[y1t:y2t, x1t:x2t]
181
  if target_face_crop.size == 0:
@@ -187,39 +192,31 @@ def face_swap_simswap(source_img_pil: Image.Image, target_img_pil: Image.Image,
187
 
188
  # --- 3. Run SimSwap Inference ---
189
  try:
190
- # SimSwap typically takes two inputs: source face and target face
191
- # Input names might vary based on the specific ONNX export. Common names are 'src' and 'dst' or 'source' and 'target'.
192
- # Let's assume input names are 'src' and 'dst' based on common SimSwap ONNX exports.
193
- # If your model has different names, you'll need to inspect it using:
194
- # for inp in simswap_session.get_inputs(): print(inp.name)
195
  simswap_inputs = {
196
- simswap_session.get_inputs()[0].name: source_input_tensor, # This is often the driving (source) identity
197
- simswap_session.get_inputs()[1].name: target_input_tensor # This is often the target pose/expression
198
  }
199
 
200
  simswap_raw_output = simswap_session.run([simswap_output_name], simswap_inputs)[0]
201
  except Exception as e:
202
- raise gr.Error(f"SimSwap inference failed: {e}. Check model inputs/outputs and ensure images are suitable.")
 
203
 
204
  # --- 4. Postprocess SimSwap Output ---
205
  swapped_face_simswap_output = postprocess_simswap_output(simswap_raw_output)
206
 
207
  # --- 5. Blend Swapped Face back into Original Target Image ---
208
  # We'll use OpenCV's seamlessClone for a natural blend.
209
- # This requires:
210
- # 1. The original target image (target_np_bgr)
211
- # 2. The swapped face image (swapped_face_simswap_output)
212
- # 3. A mask for the swapped face (often a simple ellipse or a full white mask if blending is good)
213
- # 4. The center point where the swapped face should be placed
214
 
215
  # Resize swapped face output to original target face bounding box dimensions
216
  target_face_width = x2t - x1t
217
  target_face_height = y2t - y1t
218
  swapped_face_resized = cv2.resize(swapped_face_simswap_output, (target_face_width, target_face_height))
219
 
220
- # Create a mask for seamless cloning
221
- # A simple white rectangle covering the area is often sufficient for seamlessClone
222
- # For more advanced blending, a precise face parsing mask is ideal.
223
  mask = np.full(swapped_face_resized.shape[:2], 255, dtype=np.uint8) # White mask
224
 
225
  # Calculate the center of the target face bounding box
@@ -228,20 +225,19 @@ def face_swap_simswap(source_img_pil: Image.Image, target_img_pil: Image.Image,
228
  center_point = (center_x, center_y)
229
 
230
  try:
231
- # Perform seamless cloning
232
- # FLAG_NORMAL_CLONE often gives the best results for face swapping
233
  final_swapped_img_bgr = cv2.seamlessClone(
234
  swapped_face_resized,
235
  target_np_bgr,
236
  mask,
237
  center_point,
238
- cv2.MIXED_CLONE # or cv2.NORMAL_CLONE
239
  )
240
  except Exception as e:
241
- # Fallback to simple paste if seamlessClone fails (e.g., due to size mismatch issues)
242
- print(f"Seamless cloning failed: {e}. Attempting simple paste.")
243
  final_swapped_img_bgr = target_np_bgr.copy()
244
- # Simple paste (less visually appealing than seamlessClone)
245
  final_swapped_img_bgr[y1t:y2t, x1t:x2t] = swapped_face_resized
246
 
247
 
@@ -314,7 +310,7 @@ with gr.Blocks(title="Face Swap App (SimSwap)") as demo:
314
  )
315
 
316
  swap_button.click(
317
- fn=face_swap_simswap, # Changed to the new SimSwap function
318
  inputs=[source_image, target_image, face_index_slider],
319
  outputs=[output_image, download_output, status_message]
320
  )
 
6
  import onnxruntime
7
  from PIL import Image
8
  import tempfile
9
+ import math # Import math for debugging if needed, but not directly used in the fixed slider logic
10
 
11
  # --- Global Configurations and Model Loading ---
12
  # Determine the appropriate provider for ONNX Runtime.
 
30
 
31
  if not os.path.exists(SIMSWAP_MODEL_PATH):
32
  raise FileNotFoundError(f"SimSwap model not found at: {SIMSWAP_MODEL_PATH}. "
33
+ "Please place 'simswap_256.onnx' in the 'models/' directory relative to this script.")
34
  try:
35
  simswap_session = onnxruntime.InferenceSession(SIMSWAP_MODEL_PATH, providers=providers)
36
+ # Get input and output names from the ONNX model
37
+ simswap_input_name_0 = simswap_session.get_inputs()[0].name
38
+ simswap_input_name_1 = simswap_session.get_inputs()[1].name
39
  simswap_output_name = simswap_session.get_outputs()[0].name
40
  print(f"SimSwap model '{SIMSWAP_MODEL_PATH}' loaded successfully.")
41
+ print(f"SimSwap expected input 0: {simswap_session.get_inputs()[0].shape} (name: {simswap_input_name_0})")
42
+ print(f"SimSwap expected input 1: {simswap_session.get_inputs()[1].shape} (name: {simswap_input_name_1})")
43
+ print(f"SimSwap output shape: {simswap_session.get_outputs()[0].shape} (name: {simswap_output_name})")
44
  except Exception as e:
45
  raise RuntimeError(f"Failed to load SimSwap model from {SIMSWAP_MODEL_PATH}: {e}. "
46
+ "Check the model file's integrity and ONNX Runtime compatibility. "
47
+ "Also ensure it's a 2-input SimSwap model.")
48
 
49
 
50
  # --- Helper Functions ---
 
125
  """
126
  if target_img_pil is None:
127
  # Return default states for all outputs when input is None
128
+ # When no image, no faces, so slider remains at 0-0 non-interactive
129
  return None, gr.Slider(minimum=0, maximum=0, value=0, interactive=False), gr.File(value=None, interactive=False), "Please upload a target image first."
130
 
131
  target_np_rgb = np.array(target_img_pil)
 
135
  num_faces = len(faces)
136
 
137
  if num_faces == 0:
138
+ # If no faces are detected, set slider range to 0 to 0 and make it non-interactive.
139
+ # This prevents maximum < minimum, which causes math domain error in Gradio Slider.
140
  return None, gr.Slider(minimum=0, maximum=0, value=0, interactive=False), gr.File(value=None, interactive=False), "No faces detected in the target image. Please try another image."
141
+ else:
142
+ # If faces are detected, set the slider range appropriately
143
+ preview_img_bgr = draw_faces(target_np_bgr, faces)
144
+ preview_img_rgb = cv2.cvtColor(preview_img_bgr, cv2.COLOR_BGR2RGB)
145
 
146
+ # Set the max value of the slider to (number of faces - 1) as indices are 0-based
147
+ # This ensures minimum=0 and maximum >= 0, avoiding the math domain error.
148
+ return preview_img_rgb, gr.Slider(minimum=0, maximum=num_faces - 1, value=0, interactive=True), gr.File(value=None, interactive=False), f"Detected {num_faces} face(s). Select the face to swap using the slider (0-indexed)."
 
 
149
 
150
  def face_swap_simswap(source_img_pil: Image.Image, target_img_pil: Image.Image, face_index: int):
151
  """
 
174
  "You might need to click 'Preview Detected Faces' again to update the slider range.")
175
  target_face_info = target_faces[face_index]
176
 
177
+ # Crop source face region using bounding box
 
 
 
 
 
178
  x1s, y1s, x2s, y2s = source_face_info.bbox.astype(int)
179
  source_face_crop = source_np_bgr[y1s:y2s, x1s:x2s]
180
  if source_face_crop.size == 0:
181
  raise gr.Error("Could not crop source face properly. Image might be too small or face too close to edge.")
182
 
183
+ # Crop target face region using bounding box
184
  x1t, y1t, x2t, y2t = target_face_info.bbox.astype(int)
185
  target_face_crop = target_np_bgr[y1t:y2t, x1t:x2t]
186
  if target_face_crop.size == 0:
 
192
 
193
  # --- 3. Run SimSwap Inference ---
194
  try:
195
+ # SimSwap typically takes two inputs: source face and target face.
196
+ # Ensure the input names match your specific ONNX model (e.g., 'src', 'dst', 'input.1', 'input.2').
197
+ # The variables `simswap_input_name_0` and `simswap_input_name_1` were retrieved from the model dynamically.
 
 
198
  simswap_inputs = {
199
+ simswap_input_name_0: source_input_tensor, # Often the driving (source) identity
200
+ simswap_input_name_1: target_input_tensor # Often the target pose/expression
201
  }
202
 
203
  simswap_raw_output = simswap_session.run([simswap_output_name], simswap_inputs)[0]
204
  except Exception as e:
205
+ raise gr.Error(f"SimSwap inference failed: {e}. Check model inputs/outputs and ensure images are suitable. "
206
+ "Common issues include incorrect input tensor names or shapes.")
207
 
208
  # --- 4. Postprocess SimSwap Output ---
209
  swapped_face_simswap_output = postprocess_simswap_output(simswap_raw_output)
210
 
211
  # --- 5. Blend Swapped Face back into Original Target Image ---
212
  # We'll use OpenCV's seamlessClone for a natural blend.
 
 
 
 
 
213
 
214
  # Resize swapped face output to original target face bounding box dimensions
215
  target_face_width = x2t - x1t
216
  target_face_height = y2t - y1t
217
  swapped_face_resized = cv2.resize(swapped_face_simswap_output, (target_face_width, target_face_height))
218
 
219
+ # Create a mask for seamless cloning. A simple white rectangle covering the area is often sufficient.
 
 
220
  mask = np.full(swapped_face_resized.shape[:2], 255, dtype=np.uint8) # White mask
221
 
222
  # Calculate the center of the target face bounding box
 
225
  center_point = (center_x, center_y)
226
 
227
  try:
228
+ # Perform seamless cloning. MIXED_CLONE often works well for blending.
 
229
  final_swapped_img_bgr = cv2.seamlessClone(
230
  swapped_face_resized,
231
  target_np_bgr,
232
  mask,
233
  center_point,
234
+ cv2.MIXED_CLONE # or cv2.NORMAL_CLONE for sharper edges
235
  )
236
  except Exception as e:
237
+ # Fallback to simple paste if seamlessClone fails (e.g., due to size mismatch issues or OpenCV errors)
238
+ print(f"Seamless cloning failed: {e}. Attempting simple paste as a fallback.")
239
  final_swapped_img_bgr = target_np_bgr.copy()
240
+ # Simple paste (less visually appealing than seamlessClone, but avoids crash)
241
  final_swapped_img_bgr[y1t:y2t, x1t:x2t] = swapped_face_resized
242
 
243
 
 
310
  )
311
 
312
  swap_button.click(
313
+ fn=face_swap_simswap, # The function using SimSwap
314
  inputs=[source_image, target_image, face_index_slider],
315
  outputs=[output_image, download_output, status_message]
316
  )