-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathface_id.py
More file actions
1141 lines (913 loc) · 36.7 KB
/
face_id.py
File metadata and controls
1141 lines (913 loc) · 36.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
FaceID Module for Inpainting Pipeline
InsightFace-based face embedding extraction for IP-Adapter FaceID Plus v2
Supports multiple face swap models:
- InsightFace (inswapper_128): Fast, good quality
- Ghost (GHFV): High quality, slower
Usage:
face_id = FaceIDExtractor(device="mps")
embedding = face_id.get_embedding(face_image)
# With pipeline
pipe.load_ip_adapter(..., weight_name="ip-adapter-faceid-plusv2_sdxl.bin")
result = pipe(..., ip_adapter_image_embeds=embedding)
# Face swap with model selection
swapper = get_face_swapper(model="ghost", device="cuda")
result = swapper.swap_face(target_image, source_image)
"""
import os
import sys
import torch
import numpy as np
from PIL import Image
from typing import Optional, Tuple, Union, Literal
# Face swap model type
FaceSwapModel = Literal["insightface", "ghost"]
# InsightFace is optional
try:
print("[DEBUG face_id.py] Attempting to import insightface...")
from insightface.app import FaceAnalysis
HAS_INSIGHTFACE = True
print("[DEBUG face_id.py] ✅ InsightFace imported successfully!")
except ImportError as e:
HAS_INSIGHTFACE = False
print(f"[DEBUG face_id.py] ❌ InsightFace import failed: {e}")
print("insightface not installed. FaceID mode unavailable.")
print("Install: pip install insightface onnxruntime")
class FaceSwapper:
"""
InsightFace-based face swapper using inswapper_128.onnx model.
Swaps faces between source and target images for better likeness preservation.
"""
def __init__(self, device: str = "cpu"):
"""
Initialize face swapper.
Args:
device: "cuda", "mps", or "cpu"
"""
self.device = device
self.swapper = None
self.face_analyzer = None
self._initialized = False
def _get_providers(self) -> list:
"""Get ONNX Runtime providers based on device."""
if self.device == "cuda":
return ["CUDAExecutionProvider", "CPUExecutionProvider"]
elif self.device == "mps":
return ["CoreMLExecutionProvider", "CPUExecutionProvider"]
else:
return ["CPUExecutionProvider"]
def load(self, model_path: str = None) -> bool:
"""
Load face swapper model.
Args:
model_path: Path to inswapper_128.onnx (auto-download if None)
Returns:
True if loaded successfully
"""
if not HAS_INSIGHTFACE:
print("InsightFace not available for face swap")
return False
if self._initialized:
return True
try:
import insightface
from insightface.app import FaceAnalysis
providers = self._get_providers()
# Initialize face analyzer
print(f"Loading FaceSwapper on {self.device}...")
self.face_analyzer = FaceAnalysis(
name="buffalo_l",
providers=providers
)
self.face_analyzer.prepare(ctx_id=0, det_size=(640, 640))
# Load inswapper model (prefer 512 for higher quality)
if model_path is None:
# Try inswapper_512 first (higher quality), fallback to 128
try:
model_path = insightface.model_zoo.get_model(
"inswapper_512.onnx",
download=True,
providers=providers
)
self.swapper = model_path
self._model_name = "inswapper_512"
except Exception:
print("inswapper_512 not available, using inswapper_128")
model_path = insightface.model_zoo.get_model(
"inswapper_128.onnx",
download=True,
providers=providers
)
self.swapper = model_path
self._model_name = "inswapper_128"
else:
import onnxruntime as ort
self.swapper = insightface.model_zoo.get_model(
model_path,
providers=providers
)
self._model_name = os.path.basename(model_path)
self._initialized = True
print(f"FaceSwapper loaded successfully ({self._model_name})")
return True
except Exception as e:
print(f"Failed to load FaceSwapper: {e}")
import traceback
traceback.print_exc()
return False
def swap_face(
self,
target_image: Union[str, Image.Image, np.ndarray],
source_image: Union[str, Image.Image, np.ndarray],
) -> Optional[Image.Image]:
"""
Swap face from source to target image.
Args:
target_image: Image where face will be replaced
source_image: Image containing the source face
Returns:
Result image with swapped face, or None if failed
"""
if not self.load():
return None
# Convert to numpy arrays
if isinstance(target_image, str):
target_image = Image.open(target_image).convert("RGB")
if isinstance(source_image, str):
source_image = Image.open(source_image).convert("RGB")
if isinstance(target_image, Image.Image):
target_np = np.array(target_image)
else:
target_np = target_image
if isinstance(source_image, Image.Image):
source_np = np.array(source_image)
else:
source_np = source_image
# Convert RGB to BGR for InsightFace
target_bgr = target_np[:, :, ::-1].copy()
source_bgr = source_np[:, :, ::-1].copy()
# Detect faces
target_faces = self.face_analyzer.get(target_bgr)
source_faces = self.face_analyzer.get(source_bgr)
if len(target_faces) == 0:
print("No face detected in target image")
return None
if len(source_faces) == 0:
print("No face detected in source image")
return None
# Get largest faces
target_face = max(target_faces, key=lambda f: (f.bbox[2] - f.bbox[0]) * (f.bbox[3] - f.bbox[1]))
source_face = max(source_faces, key=lambda f: (f.bbox[2] - f.bbox[0]) * (f.bbox[3] - f.bbox[1]))
# Swap face
result_bgr = self.swapper.get(target_bgr, target_face, source_face, paste_back=True)
# Convert BGR back to RGB
result_rgb = result_bgr[:, :, ::-1]
return Image.fromarray(result_rgb)
# Ghost Face Swap imports (optional)
# Note: We use InsightFace for face alignment instead of mxnet-based CoordHandler
HAS_GHOST = False
GHOST_DIR = os.path.join(os.path.dirname(__file__), "ghost")
try:
if os.path.exists(GHOST_DIR):
sys.path.insert(0, GHOST_DIR)
from network.AEI_Net import AEI_Net
import kornia
HAS_GHOST = True
print("[DEBUG face_id.py] ✅ Ghost imported successfully!")
except ImportError as e:
print(f"[DEBUG face_id.py] Ghost not available: {e}")
print("Run: bash scripts/setup_ghost.sh to install Ghost")
# InsightFace-based face alignment (replaces mxnet-based CoordHandler)
class InsightFaceAligner:
"""
Face alignment using InsightFace landmarks.
This replaces Ghost's mxnet-based coordinate_reg module.
"""
# Standard face template for 112x112 aligned face
FACE_TEMPLATE = np.array([
[38.2946, 51.6963],
[73.5318, 51.5014],
[56.0252, 71.7366],
[41.5493, 92.3655],
[70.7299, 92.2041]
], dtype=np.float32)
def __init__(self):
self.face_analyzer = None
if HAS_INSIGHTFACE:
self.face_analyzer = FaceAnalysis(
name="buffalo_l",
providers=["CUDAExecutionProvider", "CPUExecutionProvider"]
)
self.face_analyzer.prepare(ctx_id=0, det_size=(640, 640))
def process(self, image_np: np.ndarray, output_size: int = 256) -> Tuple[Optional[np.ndarray], Optional[np.ndarray]]:
"""
Detect face and return aligned face image with transformation matrix.
Args:
image_np: RGB image as numpy array
output_size: Output size for aligned face
Returns:
(aligned_face, transform_matrix) or (None, None) if failed
"""
if self.face_analyzer is None:
return None, None
try:
from skimage import transform as trans
# Detect face (InsightFace expects BGR)
faces = self.face_analyzer.get(image_np[:, :, ::-1].copy())
if len(faces) == 0:
return None, None
# Get largest face
face = max(faces, key=lambda f: (f.bbox[2] - f.bbox[0]) * (f.bbox[3] - f.bbox[1]))
# Get 5-point landmarks (eyes, nose, mouth corners)
landmarks = face.kps # shape: (5, 2)
# Scale template to output size
scale = output_size / 112.0
scaled_template = self.FACE_TEMPLATE * scale
# Compute similarity transform
tform = trans.SimilarityTransform()
tform.estimate(landmarks, scaled_template)
# Get transformation matrix (2x3)
M = tform.params[0:2]
# Warp image
import cv2
aligned = cv2.warpAffine(
image_np,
M,
(output_size, output_size),
borderValue=(0, 0, 0)
)
return aligned, M
except Exception as e:
print(f"Face alignment failed: {e}")
return None, None
class GhostFaceSwapper:
"""
Ghost (GHFV) based high-quality face swapper.
Uses AEI-Net architecture with ArcFace embeddings for superior face swap quality.
Reference: https://github.com/ai-forever/ghost
"""
def __init__(self, device: str = "cuda"):
"""
Initialize Ghost face swapper.
Args:
device: "cuda" or "cpu" (MPS not fully supported)
"""
self.device = device if device != "mps" else "cpu"
self.generator = None
self.arcface = None
self.coord_handler = None
self._initialized = False
def load(self, model_dir: str = None) -> bool:
"""
Load Ghost models.
Args:
model_dir: Path to Ghost models directory
Returns:
True if loaded successfully
"""
if not HAS_GHOST:
print("Ghost not available. Run: bash setup_ghost.sh")
return False
if self._initialized:
return True
try:
if model_dir is None:
# Try ghost/weights first (setup_ghost.sh location), fallback to models/ghost
base_dir = os.path.dirname(__file__)
ghost_weights = os.path.join(base_dir, "ghost", "weights")
models_ghost = os.path.join(base_dir, "models", "ghost")
if os.path.exists(os.path.join(ghost_weights, "G_unet_2blocks.pth")):
model_dir = ghost_weights
elif os.path.exists(os.path.join(models_ghost, "G_unet_2blocks.pth")):
model_dir = models_ghost
else:
model_dir = ghost_weights # Default for error message
# Load Generator (AEI-Net)
generator_path = os.path.join(model_dir, "G_unet_2blocks.pth")
if not os.path.exists(generator_path):
print(f"Generator model not found: {generator_path}")
print("Run: bash scripts/setup_ghost.sh to download models")
return False
print(f"Loading Ghost Generator on {self.device}...")
# AEI_Net params: backbone="unet", num_blocks=2, c_id=512
# Model filename G_unet_2blocks.pth indicates backbone=unet, num_blocks=2
self.generator = AEI_Net(backbone="unet", num_blocks=2, c_id=512).to(self.device)
self.generator.load_state_dict(torch.load(generator_path, map_location=self.device))
self.generator.eval()
# Load ArcFace for face embeddings
arcface_path = os.path.join(model_dir, "arcface.pth")
if os.path.exists(arcface_path):
from network.arcface import iresnet100
self.arcface = iresnet100().to(self.device)
self.arcface.load_state_dict(torch.load(arcface_path, map_location=self.device))
self.arcface.eval()
else:
# Use InsightFace as fallback for embeddings
print("ArcFace not found, using InsightFace for embeddings")
if HAS_INSIGHTFACE:
self.arcface = FaceAnalysis(name="buffalo_l", providers=["CPUExecutionProvider"])
self.arcface.prepare(ctx_id=0)
# Initialize face aligner (InsightFace-based, no mxnet needed)
self.coord_handler = InsightFaceAligner()
self._initialized = True
print("Ghost loaded successfully")
return True
except Exception as e:
print(f"Failed to load Ghost: {e}")
import traceback
traceback.print_exc()
return False
def _get_face_embedding(self, image_np: np.ndarray) -> Optional[torch.Tensor]:
"""Extract face embedding using ArcFace."""
if self.arcface is None:
return None
# If using InsightFace fallback
if hasattr(self.arcface, 'get'):
faces = self.arcface.get(image_np[:, :, ::-1]) # RGB to BGR
if len(faces) == 0:
return None
face = max(faces, key=lambda f: (f.bbox[2] - f.bbox[0]) * (f.bbox[3] - f.bbox[1]))
return torch.from_numpy(face.normed_embedding).unsqueeze(0).to(self.device)
# Native ArcFace
try:
from PIL import Image
import torchvision.transforms as transforms
# Preprocess for ArcFace
transform = transforms.Compose([
transforms.Resize((112, 112)),
transforms.ToTensor(),
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
])
img = Image.fromarray(image_np)
img_tensor = transform(img).unsqueeze(0).to(self.device)
with torch.no_grad():
embedding = self.arcface(img_tensor)
return embedding
except Exception as e:
print(f"Face embedding extraction failed: {e}")
return None
def _align_face(self, image_np: np.ndarray) -> Tuple[Optional[np.ndarray], Optional[np.ndarray]]:
"""Align face and get transformation matrix."""
try:
aligned, matrix = self.coord_handler.process(image_np)
return aligned, matrix
except Exception as e:
print(f"Face alignment failed: {e}")
return None, None
def swap_face(
self,
target_image: Union[str, Image.Image, np.ndarray],
source_image: Union[str, Image.Image, np.ndarray],
) -> Optional[Image.Image]:
"""
Swap face from source to target image using Ghost.
Args:
target_image: Image where face will be replaced
source_image: Image containing the source face
Returns:
Result image with swapped face, or None if failed
"""
if not self.load():
return None
# Convert to numpy arrays
if isinstance(target_image, str):
target_image = Image.open(target_image).convert("RGB")
if isinstance(source_image, str):
source_image = Image.open(source_image).convert("RGB")
if isinstance(target_image, Image.Image):
target_np = np.array(target_image)
else:
target_np = target_image.copy()
if isinstance(source_image, Image.Image):
source_np = np.array(source_image)
else:
source_np = source_image.copy()
try:
# Align faces
target_aligned, target_matrix = self._align_face(target_np)
source_aligned, _ = self._align_face(source_np)
if target_aligned is None or source_aligned is None:
print("Face alignment failed, falling back to InsightFace")
return self._fallback_swap(target_np, source_np)
# Get source face embedding
source_embedding = self._get_face_embedding(source_aligned)
if source_embedding is None:
print("Face embedding failed, falling back to InsightFace")
return self._fallback_swap(target_np, source_np)
# Convert aligned images to tensors
target_tensor = torch.from_numpy(target_aligned).permute(2, 0, 1).unsqueeze(0).float().to(self.device) / 255.0
target_tensor = target_tensor * 2 - 1 # Normalize to [-1, 1]
# Generate swapped face
with torch.no_grad():
swapped_tensor, _ = self.generator(target_tensor, source_embedding)
# Convert back to numpy
swapped = ((swapped_tensor[0].permute(1, 2, 0).cpu().numpy() + 1) / 2 * 255).astype(np.uint8)
# Paste back to original image
result = self._paste_back(target_np, swapped, target_matrix)
return Image.fromarray(result)
except Exception as e:
print(f"Ghost swap failed: {e}")
import traceback
traceback.print_exc()
return self._fallback_swap(target_np, source_np)
def _fallback_swap(self, target_np: np.ndarray, source_np: np.ndarray) -> Optional[Image.Image]:
"""Fallback to InsightFace if Ghost fails."""
if HAS_INSIGHTFACE:
print("Using InsightFace fallback...")
fallback = FaceSwapper(device=self.device)
return fallback.swap_face(target_np, source_np)
return None
def _paste_back(self, original: np.ndarray, swapped: np.ndarray, matrix: np.ndarray) -> np.ndarray:
"""Paste swapped face back to original image."""
import cv2
# Inverse transform
h, w = original.shape[:2]
inv_matrix = cv2.invertAffineTransform(matrix)
# Warp swapped face back
warped = cv2.warpAffine(swapped, inv_matrix, (w, h))
# Create mask
mask = np.ones(swapped.shape[:2], dtype=np.float32)
mask_warped = cv2.warpAffine(mask, inv_matrix, (w, h))
# Blend with feathering
mask_warped = cv2.GaussianBlur(mask_warped, (21, 21), 0)
mask_3ch = np.stack([mask_warped] * 3, axis=-1)
result = original * (1 - mask_3ch) + warped * mask_3ch
return result.astype(np.uint8)
def get_face_swapper(model: FaceSwapModel = "insightface", device: str = "cuda"):
"""
Factory function to get face swapper by model name.
Args:
model: "insightface" or "ghost"
device: "cuda", "mps", or "cpu"
Returns:
Face swapper instance
"""
if model == "ghost":
if HAS_GHOST:
return GhostFaceSwapper(device=device)
else:
print("Ghost not available, falling back to InsightFace")
return FaceSwapper(device=device)
else:
return FaceSwapper(device=device)
class FaceIDExtractor:
"""
InsightFace-based face embedding extractor for IP-Adapter FaceID.
Extracts 512-dimensional face embeddings that capture identity features
much better than CLIP-based approaches.
"""
def __init__(self, device: str = "cpu", model_name: str = "buffalo_l"):
"""
Initialize FaceID extractor.
Args:
device: "cuda", "mps", or "cpu"
model_name: InsightFace model name (buffalo_l recommended)
"""
self.device = device
self.model_name = model_name
self.app = None
self._initialized = False
def _get_providers(self) -> Tuple[list, list]:
"""Get ONNX Runtime providers based on device."""
if self.device == "cuda":
providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
provider_options = [
{"device_id": 0},
{}
]
elif self.device == "mps":
# MPS uses CoreML on Apple Silicon
providers = ["CoreMLExecutionProvider", "CPUExecutionProvider"]
provider_options = [{}, {}]
else:
providers = ["CPUExecutionProvider"]
provider_options = [{}]
return providers, provider_options
def load(self) -> bool:
"""
Load InsightFace model.
Returns:
True if loaded successfully, False otherwise
"""
if not HAS_INSIGHTFACE:
print("InsightFace not available")
return False
if self._initialized:
return True
try:
providers, provider_options = self._get_providers()
print(f"Loading InsightFace ({self.model_name}) on {self.device}...")
print(f" Providers: {providers}")
self.app = FaceAnalysis(
name=self.model_name,
providers=providers,
provider_options=provider_options
)
self.app.prepare(ctx_id=0, det_size=(640, 640))
self._initialized = True
print(f"InsightFace loaded successfully")
return True
except Exception as e:
print(f"Failed to load InsightFace: {e}")
import traceback
traceback.print_exc()
return False
def detect_face(self, image: Union[str, Image.Image, np.ndarray]) -> Optional[dict]:
"""
Detect face in image.
Args:
image: PIL Image, numpy array, or path
Returns:
Face dict with bbox, embedding, landmarks, etc. or None
"""
if not self.load():
return None
# Convert to numpy array
if isinstance(image, str):
image = Image.open(image).convert("RGB")
if isinstance(image, Image.Image):
image = np.array(image)
# InsightFace expects BGR
if len(image.shape) == 3 and image.shape[2] == 3:
image_bgr = image[:, :, ::-1]
else:
image_bgr = image
faces = self.app.get(image_bgr)
if len(faces) == 0:
print("No face detected")
return None
# Return largest face
largest_face = max(faces, key=lambda f: (f.bbox[2] - f.bbox[0]) * (f.bbox[3] - f.bbox[1]))
return largest_face
def get_embedding(
self,
image: Union[str, Image.Image, np.ndarray],
return_tensor: bool = True
) -> Optional[Union[np.ndarray, torch.Tensor]]:
"""
Extract face embedding from image.
Args:
image: PIL Image, numpy array, or path
return_tensor: Return as torch.Tensor if True, numpy array if False
Returns:
512-dimensional face embedding or None if no face detected
"""
face = self.detect_face(image)
if face is None:
return None
embedding = face.normed_embedding # 512-dim normalized embedding
if return_tensor:
embedding = torch.from_numpy(embedding).unsqueeze(0)
return embedding
def get_embedding_for_ip_adapter(
self,
image: Union[str, Image.Image, np.ndarray],
dtype: torch.dtype = torch.float16,
device: str = None
) -> Optional[torch.Tensor]:
"""
Get face embedding formatted for IP-Adapter FaceID.
Args:
image: PIL Image, numpy array, or path
dtype: Tensor dtype (float16 for GPU, float32 for CPU)
device: Target device (uses self.device if None)
Returns:
Tensor of shape (1, 512) ready for IP-Adapter FaceID
"""
embedding = self.get_embedding(image, return_tensor=True)
if embedding is None:
return None
target_device = device or self.device
# Format for IP-Adapter: (batch, embedding_dim)
embedding = embedding.to(dtype=dtype, device=target_device)
return embedding
def get_face_bbox(
self,
image: Union[str, Image.Image, np.ndarray]
) -> Optional[Tuple[int, int, int, int]]:
"""
Get face bounding box.
Returns:
(x1, y1, x2, y2) or None
"""
face = self.detect_face(image)
if face is None:
return None
bbox = face.bbox.astype(int)
return tuple(bbox)
class FaceIDIPAdapter:
"""
Helper class to manage IP-Adapter FaceID loading and usage.
Wraps the diffusers pipeline to provide easy FaceID integration.
"""
# Model paths
FACEID_REPO = "h94/IP-Adapter-FaceID"
FACEID_WEIGHT = "ip-adapter-faceid-plusv2_sdxl.bin"
STANDARD_REPO = "h94/IP-Adapter"
STANDARD_SUBFOLDER = "sdxl_models"
STANDARD_WEIGHT = "ip-adapter_sdxl.bin"
def __init__(self, pipeline, device: str = "cpu"):
"""
Initialize FaceID IP-Adapter manager.
Args:
pipeline: Diffusers pipeline (AutoPipelineForInpainting, etc.)
device: Device string
"""
self.pipeline = pipeline
self.device = device
self.face_extractor = None
self.mode = None # "faceid" or "standard"
def load_faceid_mode(self, scale: float = 0.85) -> bool:
"""
Load IP-Adapter FaceID Plus v2 mode.
This mode uses InsightFace embeddings for better identity preservation.
Args:
scale: IP-Adapter scale (0.0-1.0)
Returns:
True if loaded successfully
"""
try:
# Initialize face extractor
if self.face_extractor is None:
self.face_extractor = FaceIDExtractor(device=self.device)
if not self.face_extractor.load():
print("FaceID mode requires InsightFace")
return False
print(f"Loading IP-Adapter FaceID Plus v2...")
self.pipeline.load_ip_adapter(
self.FACEID_REPO,
subfolder=None,
weight_name=self.FACEID_WEIGHT,
image_encoder_folder=None,
)
self.pipeline.set_ip_adapter_scale(scale)
self.mode = "faceid"
print(f"IP-Adapter FaceID loaded (scale={scale})")
return True
except Exception as e:
print(f"Failed to load FaceID mode: {e}")
import traceback
traceback.print_exc()
return False
def load_standard_mode(self, scale: float = 0.85) -> bool:
"""
Load Standard IP-Adapter mode.
This mode uses CLIP embeddings (less identity preservation).
Args:
scale: IP-Adapter scale (0.0-1.0)
Returns:
True if loaded successfully
"""
try:
print(f"Loading Standard IP-Adapter...")
self.pipeline.load_ip_adapter(
self.STANDARD_REPO,
subfolder=self.STANDARD_SUBFOLDER,
weight_name=self.STANDARD_WEIGHT,
)
self.pipeline.set_ip_adapter_scale(scale)
self.mode = "standard"
print(f"Standard IP-Adapter loaded (scale={scale})")
return True
except Exception as e:
print(f"Failed to load standard mode: {e}")
import traceback
traceback.print_exc()
return False
def prepare_ip_adapter_input(
self,
face_image: Union[str, Image.Image],
dtype: torch.dtype = torch.float16
) -> dict:
"""
Prepare IP-Adapter input based on current mode.
Args:
face_image: Source face image
dtype: Tensor dtype
Returns:
Dict with either 'ip_adapter_image' or 'ip_adapter_image_embeds'
"""
if isinstance(face_image, str):
face_image = Image.open(face_image).convert("RGB")
if self.mode == "faceid":
# FaceID mode: use InsightFace embedding
embedding = self.face_extractor.get_embedding_for_ip_adapter(
face_image,
dtype=dtype,
device=self.device
)
if embedding is None:
print("Warning: No face detected, falling back to image input")
return {"ip_adapter_image": face_image}
return {"ip_adapter_image_embeds": embedding}
else:
# Standard mode: use image directly (CLIP encodes internally)
return {"ip_adapter_image": face_image}
def set_scale(self, scale: float):
"""Set IP-Adapter scale."""
self.pipeline.set_ip_adapter_scale(scale)
def check_insightface_available() -> bool:
"""Check if InsightFace is available."""
return HAS_INSIGHTFACE
# GFPGAN is optional - requires compatibility shim for torchvision >= 0.24
# torchvision 0.24+ removed functional_tensor module, but GFPGAN still uses it
try:
# Add compatibility shim for torchvision >= 0.24
import torchvision
tv_version = tuple(map(int, torchvision.__version__.split('+')[0].split('.')[:2]))
if tv_version >= (0, 24):
import sys
import types
from torchvision.transforms import functional as F
# Create a fake functional_tensor module that redirects to functional
functional_tensor = types.ModuleType('torchvision.transforms.functional_tensor')
functional_tensor.__dict__.update({
name: getattr(F, name) for name in dir(F) if not name.startswith('_')
})
sys.modules['torchvision.transforms.functional_tensor'] = functional_tensor
print(f"[DEBUG face_id.py] Applied torchvision {torchvision.__version__} compatibility shim for GFPGAN")
from gfpgan import GFPGANer
HAS_GFPGAN = True
print("[DEBUG face_id.py] ✅ GFPGAN imported successfully!")
except ImportError as e:
HAS_GFPGAN = False
print(f"[DEBUG face_id.py] GFPGAN not installed: {e}")
print("Install: pip install gfpgan")
except Exception as e:
HAS_GFPGAN = False
print(f"[DEBUG face_id.py] GFPGAN load error: {e}")
print("This may be due to torchvision compatibility issues")
class FaceEnhancer:
"""
GFPGAN-based face enhancement/restoration.
Improves face quality after Face Swap or for general face enhancement.
Uses GFPGAN v1.4 model for high-quality face restoration.
"""
def __init__(self, device: str = "cuda", upscale: int = 2):
"""
Initialize face enhancer.
Args:
device: "cuda" or "cpu"
upscale: Upscale factor (1, 2, or 4)
"""
self.device = device
self.upscale = upscale
self.enhancer = None
self._initialized = False
def load(self, model_path: str = None) -> bool:
"""
Load GFPGAN model.
Args:
model_path: Path to GFPGAN model (auto-download if None)
Returns:
True if loaded successfully
"""
if not HAS_GFPGAN:
print("GFPGAN not available")
return False
if self._initialized:
return True
try:
import os
import urllib.request
# Default model path
if model_path is None:
model_dir = os.path.expanduser("~/.cache/gfpgan/weights")
os.makedirs(model_dir, exist_ok=True)
model_path = os.path.join(model_dir, "GFPGANv1.4.pth")
# Download if not exists
if not os.path.exists(model_path):
print("Downloading GFPGAN v1.4 model...")
url = "https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/GFPGANv1.4.pth"
urllib.request.urlretrieve(url, model_path)
print(f"Downloaded to {model_path}")
# Initialize GFPGAN
print(f"Loading GFPGAN on {self.device}...")
# GFPGAN needs detection model path
detection_model_path = os.path.join(
os.path.dirname(model_path),
"detection_Resnet50_Final.pth"
)
# Download detection model if needed
if not os.path.exists(detection_model_path):
print("Downloading face detection model...")
det_url = "https://github.com/xinntao/facexlib/releases/download/v0.1.0/detection_Resnet50_Final.pth"
urllib.request.urlretrieve(det_url, detection_model_path)
# Initialize enhancer
self.enhancer = GFPGANer(
model_path=model_path,
upscale=self.upscale,
arch='clean',
channel_multiplier=2,