Astridkraft commited on
Commit
f6548dc
·
verified ·
1 Parent(s): 26a123d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -35
app.py CHANGED
@@ -1,12 +1,13 @@
1
  import gradio as gr
2
- from diffusers import StableDiffusionPipeline, StableDiffusionImg2ImgPipeline
3
- from diffusers import StableDiffusionInpaintPipeline
4
  import torch
5
  from PIL import Image, ImageDraw
6
  import time
7
  import os
8
  import tempfile
9
  import random
 
 
10
 
11
  # === OPTIMIERTE EINSTELLUNGEN ===
12
  device = "cuda" if torch.cuda.is_available() else "cpu"
@@ -15,7 +16,6 @@ IMG_SIZE = 512
15
 
16
  print(f"Running on: {device}")
17
 
18
-
19
  # === GESICHTSMASKEN-FUNKTIONEN ===
20
  def create_face_mask(image, bbox_coords):
21
  """Erzeugt eine Gesichtsmaske - WEIßE Bereiche werden VERÄNDERT, SCHWARZE BLEIBEN"""
@@ -38,33 +38,49 @@ def create_face_mask(image, bbox_coords):
38
  return mask
39
 
40
  def auto_detect_face_area(image):
41
- """Optimierten Vorschlag für Gesichtsbereich ohne externe Bibliotheken"""
42
- width, height = image.size
43
- # Größere Bounding Box für bessere Abdeckung (50% statt 40%)
44
- face_size = min(width, height) * 0.5
45
- # Verschiebe y1 nach oben, um Stirn und Kinn besser abzudecken
46
- x1 = (width - face_size) / 2
47
- y1 = (height - face_size) / 4 # Höher positioniert (25% statt 33%)
48
- x2 = x1 + face_size
49
- y2 = y1 + face_size * 1.2 # Leicht länglicher für ovale Gesichter
50
- # Stelle sicher, dass Koordinaten innerhalb des Bildes liegen
51
- x1, y1 = max(0, int(x1)), max(0, int(y1))
52
- x2, y2 = min(width, int(x2)), min(height, int(y2))
53
- print(f"✅ Geschätzte Gesichtskoordinaten: [{x1}, {y1}, {x2}, {y2}]")
54
- return [x1, y1, x2, y2]
55
-
56
-
57
-
58
-
59
- def auto_detect_face_area(image):
60
- """Vorschlag für Gesichtsbereich"""
61
- width, height = image.size
62
- face_size = min(width, height) * 0.4
63
- x1 = (width - face_size) / 2
64
- y1 = (height - face_size) / 3
65
- x2 = x1 + face_size
66
- y2 = y1 + face_size
67
- return [int(x1), int(y1), int(x2), int(y2)]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
  # === PIPELINES ===
70
  pipe_txt2img = None
@@ -93,17 +109,16 @@ def load_img2img():
93
  print("Loading Inpainting model...")
94
  try:
95
  pipe_img2img = StableDiffusionInpaintPipeline.from_pretrained(
96
- "stabilityai/stable-diffusion-2-inpainting", # Neues Modell
97
  torch_dtype=torch_dtype,
98
- use_safetensors=True, # Erzwinge .safetensors
99
- allow_pickle=False, # Verhindere unsichere Serialisierung
100
  safety_checker=None
101
  ).to(device)
102
  except Exception as e:
103
  print(f"❌ Fehler beim Laden des Modells: {e}")
104
  raise
105
 
106
-
107
  from diffusers import DPMSolverMultistepScheduler
108
  pipe_img2img.scheduler = DPMSolverMultistepScheduler.from_config(
109
  pipe_img2img.scheduler.config,
@@ -209,7 +224,7 @@ def img_to_image(image, prompt, neg_prompt, strength, steps, guidance_scale, fac
209
  prompt=prompt,
210
  negative_prompt=neg_prompt,
211
  image=img_resized,
212
- mask_image=mask, # None = gesamtes Bild verändern
213
  strength=adj_strength,
214
  num_inference_steps=int(steps),
215
  guidance_scale=adj_guidance,
 
1
  import gradio as gr
2
+ from diffusers import StableDiffusionPipeline, StableDiffusionInpaintPipeline
 
3
  import torch
4
  from PIL import Image, ImageDraw
5
  import time
6
  import os
7
  import tempfile
8
  import random
9
+ import numpy as np # Neu für DeepFace
10
+ from deepface import DeepFace # Neu für präzise Gesichtsdetektion
11
 
12
  # === OPTIMIERTE EINSTELLUNGEN ===
13
  device = "cuda" if torch.cuda.is_available() else "cpu"
 
16
 
17
  print(f"Running on: {device}")
18
 
 
19
  # === GESICHTSMASKEN-FUNKTIONEN ===
20
  def create_face_mask(image, bbox_coords):
21
  """Erzeugt eine Gesichtsmaske - WEIßE Bereiche werden VERÄNDERT, SCHWARZE BLEIBEN"""
 
38
  return mask
39
 
40
  def auto_detect_face_area(image):
41
+ """Präzise Gesichtsdetektion mit DeepFace, Fallback auf grobe Schätzung"""
42
+ try:
43
+ # Konvertiere PIL-Image zu NumPy-Array (DeepFace benötigt das)
44
+ img_array = np.array(image.convert("RGB"))
45
+
46
+ # Detektiere Gesichter mit DeepFace
47
+ face_objs = DeepFace.extract_faces(
48
+ img_path=img_array,
49
+ detector_backend="retinaface", # Genau, aber CUDA-kompatibel
50
+ align=False # Kein Alignment nötig, nur Bounding Box
51
+ )
52
+
53
+ if not face_objs:
54
+ print("⚠️ Kein Gesicht erkannt - Fallback auf grobe Schätzung")
55
+ # Fallback auf alte Methode
56
+ width, height = image.size
57
+ face_size = min(width, height) * 0.4
58
+ x1 = (width - face_size) / 2
59
+ y1 = (height - face_size) / 3
60
+ x2 = x1 + face_size
61
+ y2 = y1 + face_size
62
+ return [int(x1), int(y1), int(x2), int(y2)]
63
+
64
+ # Nimm das erste (größte) Gesicht
65
+ facial_area = face_objs[0]["facial_area"]
66
+ x1 = facial_area["x"]
67
+ y1 = facial_area["y"]
68
+ x2 = x1 + facial_area["w"]
69
+ y2 = y1 + facial_area["h"]
70
+
71
+ print(f"✅ Gesicht erkannt: [{x1}, {y1}, {x2}, {y2}]")
72
+ return [int(x1), int(y1), int(x2), int(y2)]
73
+
74
+ except Exception as e:
75
+ print(f"❌ Fehler bei Gesichtsdetektion: {e}")
76
+ # Fallback auf alte Methode
77
+ width, height = image.size
78
+ face_size = min(width, height) * 0.4
79
+ x1 = (width - face_size) / 2
80
+ y1 = (height - face_size) / 3
81
+ x2 = x1 + face_size
82
+ y2 = y1 + face_size
83
+ return [int(x1), int(y1), int(x2), int(y2)]
84
 
85
  # === PIPELINES ===
86
  pipe_txt2img = None
 
109
  print("Loading Inpainting model...")
110
  try:
111
  pipe_img2img = StableDiffusionInpaintPipeline.from_pretrained(
112
+ "stabilityai/stable-diffusion-2-inpainting",
113
  torch_dtype=torch_dtype,
114
+ use_safetensors=True,
115
+ allow_pickle=False,
116
  safety_checker=None
117
  ).to(device)
118
  except Exception as e:
119
  print(f"❌ Fehler beim Laden des Modells: {e}")
120
  raise
121
 
 
122
  from diffusers import DPMSolverMultistepScheduler
123
  pipe_img2img.scheduler = DPMSolverMultistepScheduler.from_config(
124
  pipe_img2img.scheduler.config,
 
224
  prompt=prompt,
225
  negative_prompt=neg_prompt,
226
  image=img_resized,
227
+ mask_image=mask,
228
  strength=adj_strength,
229
  num_inference_steps=int(steps),
230
  guidance_scale=adj_guidance,