assile commited on
Commit
ae78b79
·
verified ·
1 Parent(s): 1b5bc6a

Update run.py

Browse files
Files changed (1) hide show
  1. run.py +64 -48
run.py CHANGED
@@ -3,70 +3,86 @@ import cv2
3
  import numpy as np
4
  from insightface.app import FaceAnalysis
5
 
6
- # Initialisation du détecteur de visages
7
- face_app = FaceAnalysis(name="buffalo_l")
8
- face_app.prepare(ctx_id=0, det_size=(640, 640))
 
 
 
 
9
 
10
- def face_swap(source_img, target_img):
11
  try:
12
- # Conversion des images Gradio en numpy arrays
13
- source = np.array(source_img)
14
- target = np.array(target_img)
15
 
16
- # Détection des visages
17
- source_faces = face_app.get(source)
18
- target_faces = face_app.get(target)
19
 
20
- if not source_faces or not target_faces:
21
- raise ValueError("Aucun visage détecté dans une des images")
 
 
 
 
 
22
 
23
- # Récupération du premier visage détecté
24
- src_face = source_faces[0]
25
- tgt_face = target_faces[0]
 
 
 
 
 
26
 
27
- # Extraction des zones de visage (simplifié)
28
- src_box = src_face.bbox.astype(int)
29
- tgt_box = tgt_face.bbox.astype(int)
30
-
31
- # Échange des visages
32
  result = target.copy()
33
- result[tgt_box[1]:tgt_box[3], tgt_box[0]:tgt_box[2]] = \
34
- source[src_box[1]:src_box[3], src_box[0]:src_box[2]]
 
35
 
36
- # Conversion BGR vers RGB pour Gradio
37
- result = cv2.cvtColor(result, cv2.COLOR_BGR2RGB)
38
  return result
39
-
40
  except Exception as e:
41
- print(f"ERREUR: {str(e)}")
42
- # Retourne l'image originale en cas d'erreur
43
- return cv2.cvtColor(target, cv2.COLOR_BGR2RGB)
 
 
44
 
45
- # Interface Gradio améliorée
46
- with gr.Blocks() as app:
47
- gr.Markdown("## 🔄 FaceSwap Pro - Powered by InsightFace")
 
 
 
48
 
49
  with gr.Row():
50
  with gr.Column():
51
- src_img = gr.Image(label="Image Source", type="numpy")
52
- tgt_img = gr.Image(label="Image Cible", type="numpy")
53
- result_img = gr.Image(label="Résultat", interactive=False)
 
54
 
55
- btn = gr.Button("Échanger les visages", variant="primary")
 
56
 
57
- # Exemples intégrés
58
- gr.Examples(
59
- examples=[
60
- ["exemples/source1.jpg", "exemples/target1.jpg"],
61
- ["exemples/source2.jpg", "exemples/target2.jpg"]
62
- ],
63
- inputs=[src_img, tgt_img],
64
- outputs=result_img,
65
- fn=face_swap,
66
- cache_examples=True
67
- )
68
 
69
- btn.click(face_swap, inputs=[src_img, tgt_img], outputs=result_img)
 
 
 
 
70
 
71
  if __name__ == "__main__":
72
- app.launch(server_name="0.0.0.0", server_port=7860)
 
 
 
 
 
 
3
  import numpy as np
4
  from insightface.app import FaceAnalysis
5
 
6
+ # Initialisation sécurisée
7
+ try:
8
+ face_app = FaceAnalysis(name="buffalo_l")
9
+ face_app.prepare(ctx_id=0, det_size=(640, 640))
10
+ except Exception as e:
11
+ print(f"ERREUR initialisation : {str(e)}")
12
+ face_app = None
13
 
14
+ def safe_face_swap(source_img, target_img):
15
  try:
16
+ if face_app is None:
17
+ raise ValueError("Le modèle de détection n'est pas chargé")
 
18
 
19
+ # Conversion robuste
20
+ source = np.array(source_img, dtype=np.uint8)
21
+ target = np.array(target_img, dtype=np.uint8)
22
 
23
+ # Vérification des dimensions
24
+ if source.ndim != 3 or target.ndim != 3:
25
+ raise ValueError("Format d'image invalide")
26
+
27
+ # Détection sécurisée
28
+ source_faces = face_app.get(cv2.cvtColor(source, cv2.COLOR_RGB2BGR))
29
+ target_faces = face_app.get(cv2.cvtColor(target, cv2.COLOR_RGB2BGR))
30
 
31
+ if not source_faces:
32
+ raise ValueError("Aucun visage détecté dans l'image source")
33
+ if not target_faces:
34
+ raise ValueError("Aucun visage détecté dans l'image cible")
35
+
36
+ # Swap simplifié mais stable
37
+ src_face = source_faces[0].bbox.astype(int)
38
+ tgt_face = target_faces[0].bbox.astype(int)
39
 
 
 
 
 
 
40
  result = target.copy()
41
+ result[tgt_face[1]:tgt_face[3], tgt_face[0]:tgt_face[2]] = \
42
+ cv2.resize(source[src_face[1]:src_face[3], src_face[0]:src_face[2]],
43
+ (tgt_face[2]-tgt_face[0], tgt_face[3]-tgt_face[1]))
44
 
 
 
45
  return result
 
46
  except Exception as e:
47
+ print(f"ERREUR traitement : {str(e)}")
48
+ # Retourne l'image cible avec message d'erreur
49
+ if target_img is not None:
50
+ return target_img
51
+ return None
52
 
53
+ # Interface renforcée
54
+ with gr.Blocks(title="FaceSwap Pro") as app:
55
+ gr.Markdown("""
56
+ ## 🔄 FaceSwap Professionnel
57
+ *Échange de visages stable et sécurisé*
58
+ """)
59
 
60
  with gr.Row():
61
  with gr.Column():
62
+ src = gr.Image(label="Source", type="numpy")
63
+ tgt = gr.Image(label="Cible", type="numpy")
64
+ btn = gr.Button("Exécuter", variant="primary")
65
+ result = gr.Image(label="Résultat", interactive=False)
66
 
67
+ # Gestion des erreurs dans l'UI
68
+ error_box = gr.Textbox(visible=False, label="Erreur")
69
 
70
+ def wrapped_face_swap(src_img, tgt_img):
71
+ try:
72
+ return safe_face_swap(src_img, tgt_img), ""
73
+ except Exception as e:
74
+ return None, f"Erreur : {str(e)}"
 
 
 
 
 
 
75
 
76
+ btn.click(
77
+ fn=wrapped_face_swap,
78
+ inputs=[src, tgt],
79
+ outputs=[result, error_box]
80
+ )
81
 
82
  if __name__ == "__main__":
83
+ app.launch(
84
+ server_name="0.0.0.0",
85
+ server_port=7860,
86
+ show_error=True,
87
+ debug=True
88
+ )