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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -50
app.py CHANGED
@@ -1,13 +1,12 @@
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,6 +15,7 @@ IMG_SIZE = 512
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,49 +38,20 @@ def create_face_mask(image, bbox_coords):
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,16 +80,17 @@ def load_img2img():
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,7 +196,7 @@ def img_to_image(image, prompt, neg_prompt, strength, steps, guidance_scale, fac
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,
 
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
 
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
  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.4
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
  # === PIPELINES ===
57
  pipe_txt2img = None
 
80
  print("Loading Inpainting model...")
81
  try:
82
  pipe_img2img = StableDiffusionInpaintPipeline.from_pretrained(
83
+ "stabilityai/stable-diffusion-2-inpainting", # Neues Modell
84
  torch_dtype=torch_dtype,
85
+ use_safetensors=True, # Erzwinge .safetensors
86
+ allow_pickle=False, # Verhindere unsichere Serialisierung
87
  safety_checker=None
88
  ).to(device)
89
  except Exception as e:
90
  print(f"❌ Fehler beim Laden des Modells: {e}")
91
  raise
92
 
93
+
94
  from diffusers import DPMSolverMultistepScheduler
95
  pipe_img2img.scheduler = DPMSolverMultistepScheduler.from_config(
96
  pipe_img2img.scheduler.config,
 
196
  prompt=prompt,
197
  negative_prompt=neg_prompt,
198
  image=img_resized,
199
+ mask_image=mask, # None = gesamtes Bild verändern
200
  strength=adj_strength,
201
  num_inference_steps=int(steps),
202
  guidance_scale=adj_guidance,