Astridkraft commited on
Commit
45a3eda
·
verified ·
1 Parent(s): 5e5594f

Update controlnet_facefix.py

Browse files
Files changed (1) hide show
  1. controlnet_facefix.py +52 -54
controlnet_facefix.py CHANGED
@@ -1,41 +1,34 @@
1
- # controlnet_facefix.py - KORRIGIERTE VERSION FÜR HF SPACES
2
  import torch
3
  from diffusers import StableDiffusionControlNetInpaintPipeline, ControlNetModel
4
  from PIL import Image
5
  import time
 
 
6
 
7
  print("="*60)
8
- print("CONTROLNET_FACEFIX START")
9
  print("="*60)
10
 
11
- # WICHTIG: Keine .to("cuda") beim Laden!
12
  _components_loaded = False
13
- _depth_processor = None
14
  _controlnet_depth = None
15
  _controlnet_pose = None
16
  _pipeline = None
17
 
18
  def _initialize_components():
19
- """Lade alle Komponenten mit Fehlerbehandlung"""
20
- global _components_loaded, _depth_processor, _controlnet_depth, _controlnet_pose
21
 
22
  if _components_loaded:
23
  return True
24
 
25
  try:
26
- print("1. Lade Depth Processor...")
27
- from controlnet_aux import ZoeDetector
28
- _depth_processor = ZoeDetector.from_pretrained("lllyasviel/ControlNet")
29
- print(" ✅ Depth Processor OK")
30
- except Exception as e:
31
- print(f" ❌ Depth Processor Fehler: {e}")
32
- return False
33
-
34
- try:
35
- print("2. Lade ControlNet Depth...")
36
  _controlnet_depth = ControlNetModel.from_pretrained(
37
- "lllyasviel/control_v11f1e_sd15_depth",
38
- torch_dtype=torch.float16 # KEIN .to("cuda") hier!
39
  )
40
  print(" ✅ ControlNet Depth OK")
41
  except Exception as e:
@@ -43,11 +36,11 @@ def _initialize_components():
43
  return False
44
 
45
  try:
46
- print("3. Lade ControlNet OpenPose...")
47
- # WICHTIG: KEIN subfolder="faceonly" - das gibt es nicht!
48
  _controlnet_pose = ControlNetModel.from_pretrained(
49
- "lllyasviel/control_v11p_sd15_openpose",
50
- torch_dtype=torch.float16 # KEIN .to("cuda") hier!
51
  )
52
  print(" ✅ ControlNet OpenPose OK")
53
  except Exception as e:
@@ -58,57 +51,63 @@ def _initialize_components():
58
  print("✅ ALLE KOMPONENTEN GELADEN")
59
  return True
60
 
61
- def _create_control_images(image):
62
- """Erstelle Depth und Pose Bilder"""
63
  try:
64
- print(" Erstelle Depth Map...")
65
- depth_img = _depth_processor(image)
66
-
67
- print(" Erstelle OpenPose...")
68
- from controlnet_aux import OpenposeDetector
69
- openpose = OpenposeDetector.from_pretrained("lllyasviel/ControlNet")
70
- pose_img = openpose(image)
71
-
72
- return pose_img, depth_img
73
  except Exception as e:
74
- print(f" Control Images Fehler: {e}")
75
- return None, None
 
 
 
 
 
 
 
 
 
 
 
76
 
77
  def apply_facefix(image: Image.Image, prompt: str, negative_prompt: str, seed: int, model_id: str):
78
- """HAUPTFUNKTION - Optimiert für HF Spaces"""
79
  print("\n" + "🎭"*50)
80
- print("FACE-FIX WIRD AUSGEFÜHRT")
81
  print(f" Model: {model_id}")
82
  print(f" Seed: {seed}")
83
  print("🎭"*50)
84
 
85
  start_time = time.time()
86
 
87
- # 1. Komponenten initialisieren
88
  if not _initialize_components():
89
  print("❌ Komponenten konnten nicht geladen werden")
90
  return image
91
 
92
- # 2. Control Images erstellen
93
- pose_img, depth_img = _create_control_images(image)
94
- if pose_img is None or depth_img is None:
95
- print("❌ Control Images konnten nicht erstellt werden")
96
- return image
97
 
98
- # 3. Pipeline erstellen (lazy)
99
  global _pipeline
100
  if _pipeline is None:
101
  try:
102
- print("🔄 Lade Pipeline...")
103
  _pipeline = StableDiffusionControlNetInpaintPipeline.from_pretrained(
104
  model_id,
105
- controlnet=[_controlnet_pose, _controlnet_depth],
106
  torch_dtype=torch.float16,
107
  safety_checker=None,
108
  requires_safety_checker=False,
109
  )
110
 
111
- # HF Spaces Optimierungen
112
  _pipeline.enable_attention_slicing()
113
  _pipeline.enable_vae_slicing()
114
 
@@ -118,26 +117,26 @@ def apply_facefix(image: Image.Image, prompt: str, negative_prompt: str, seed: i
118
  return image
119
 
120
  try:
121
- # 4. Auf GPU bewegen (erst JETZT!)
122
  device = "cuda" if torch.cuda.is_available() else "cpu"
123
  print(f" Device: {device}")
124
  pipeline = _pipeline.to(device)
125
 
126
  # 5. Prompts optimieren
127
  face_prompt = f"{prompt}, perfect face, detailed skin, realistic eyes, sharp focus"
128
- face_negative = f"{negative_prompt}, deformed face, blurry face, bad anatomy, ugly"
129
 
130
- print("⚡ Führe Face-Fix Inference aus...")
131
 
132
  # 6. Face-Fix ausführen
133
  result = pipeline(
134
  prompt=face_prompt,
135
  negative_prompt=face_negative,
136
  image=image,
137
- mask_image=None, # Ganzer Bildbereich
138
  control_image=[pose_img, depth_img],
139
  controlnet_conditioning_scale=[0.8, 0.6], # OpenPose stärker
140
- strength=0.4, # Mittlere Stärke
141
  num_inference_steps=20,
142
  guidance_scale=7.0,
143
  generator=torch.Generator(device).manual_seed(seed),
@@ -157,6 +156,5 @@ def apply_facefix(image: Image.Image, prompt: str, negative_prompt: str, seed: i
157
  return image
158
 
159
  print("="*60)
160
- print("CONTROLNET_FACEFIX INITIALISIERT")
161
- print(f"apply_facefix Funktion: {'apply_facefix' in globals()}")
162
  print("="*60)
 
1
+ # controlnet_facefix.py - BASIEREND AUF DEINEM FUNKTIONIERENDEN CODE
2
  import torch
3
  from diffusers import StableDiffusionControlNetInpaintPipeline, ControlNetModel
4
  from PIL import Image
5
  import time
6
+ import cv2
7
+ import numpy as np
8
 
9
  print("="*60)
10
+ print("FACE-FIX BASIEREND AUF CONTROLNET_MODULE")
11
  print("="*60)
12
 
13
+ # WICHTIG: Dieselben Modelle wie in controlnet_module.py!
14
  _components_loaded = False
 
15
  _controlnet_depth = None
16
  _controlnet_pose = None
17
  _pipeline = None
18
 
19
  def _initialize_components():
20
+ """Lade ControlNets genau wie in controlnet_module.py"""
21
+ global _components_loaded, _controlnet_depth, _controlnet_pose
22
 
23
  if _components_loaded:
24
  return True
25
 
26
  try:
27
+ print("1. Lade ControlNet Depth...")
28
+ # GLEICHES MODELL wie in controlnet_module.py!
 
 
 
 
 
 
 
 
29
  _controlnet_depth = ControlNetModel.from_pretrained(
30
+ "lllyasviel/sd-controlnet-depth", # ← HIER ÄNDERN!
31
+ torch_dtype=torch.float16
32
  )
33
  print(" ✅ ControlNet Depth OK")
34
  except Exception as e:
 
36
  return False
37
 
38
  try:
39
+ print("2. Lade ControlNet OpenPose...")
40
+ # GLEICHES MODELL wie in controlnet_module.py!
41
  _controlnet_pose = ControlNetModel.from_pretrained(
42
+ "lllyasviel/sd-controlnet-openpose", # ← HIER ÄNDERN!
43
+ torch_dtype=torch.float16
44
  )
45
  print(" ✅ ControlNet OpenPose OK")
46
  except Exception as e:
 
51
  print("✅ ALLE KOMPONENTEN GELADEN")
52
  return True
53
 
54
+ def _extract_depth_map(image):
55
+ """GENAU DIESELBE FUNKTION wie in controlnet_module.py"""
56
  try:
57
+ img_array = np.array(image.convert("RGB"))
58
+ gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY)
59
+ depth_map = cv2.GaussianBlur(gray, (5, 5), 0)
60
+ depth_rgb = cv2.cvtColor(depth_map, cv2.COLOR_GRAY2RGB)
61
+ return Image.fromarray(depth_rgb)
 
 
 
 
62
  except Exception as e:
63
+ print(f"Depth Map Fehler: {e}")
64
+ return image.convert("RGB")
65
+
66
+ def _extract_pose_simple(image):
67
+ """Einfache Pose-Extraktion basierend auf controlnet_module.py"""
68
+ try:
69
+ img_array = np.array(image.convert("RGB"))
70
+ edges = cv2.Canny(img_array, 100, 200)
71
+ pose_image = Image.fromarray(edges).convert("RGB")
72
+ return pose_image
73
+ except Exception as e:
74
+ print(f"Pose Extraction Fehler: {e}")
75
+ return image.convert("RGB")
76
 
77
  def apply_facefix(image: Image.Image, prompt: str, negative_prompt: str, seed: int, model_id: str):
78
+ """Face-Fix basierend auf deiner funktionierenden Logik"""
79
  print("\n" + "🎭"*50)
80
+ print("FACE-FIX MIT BEKANNT FUNKTIONIERENDEN MODELLEN")
81
  print(f" Model: {model_id}")
82
  print(f" Seed: {seed}")
83
  print("🎭"*50)
84
 
85
  start_time = time.time()
86
 
87
+ # 1. Komponenten initialisieren (mit bekannten Modellen)
88
  if not _initialize_components():
89
  print("❌ Komponenten konnten nicht geladen werden")
90
  return image
91
 
92
+ # 2. Control Images erstellen (mit deinen funktionierenden Methoden)
93
+ print("🎭 Erstelle Control Images...")
94
+ depth_img = _extract_depth_map(image)
95
+ pose_img = _extract_pose_simple(image)
 
96
 
97
+ # 3. Pipeline erstellen
98
  global _pipeline
99
  if _pipeline is None:
100
  try:
101
+ print("🔄 Lade Face-Fix Pipeline...")
102
  _pipeline = StableDiffusionControlNetInpaintPipeline.from_pretrained(
103
  model_id,
104
+ controlnet=[_controlnet_pose, _controlnet_depth], # OpenPose zuerst, dann Depth
105
  torch_dtype=torch.float16,
106
  safety_checker=None,
107
  requires_safety_checker=False,
108
  )
109
 
110
+ # Optimierungen
111
  _pipeline.enable_attention_slicing()
112
  _pipeline.enable_vae_slicing()
113
 
 
117
  return image
118
 
119
  try:
120
+ # 4. Auf Device bewegen
121
  device = "cuda" if torch.cuda.is_available() else "cpu"
122
  print(f" Device: {device}")
123
  pipeline = _pipeline.to(device)
124
 
125
  # 5. Prompts optimieren
126
  face_prompt = f"{prompt}, perfect face, detailed skin, realistic eyes, sharp focus"
127
+ face_negative = f"{negative_prompt}, deformed face, blurry face, bad anatomy"
128
 
129
+ print("⚡ Führe Face-Fix aus...")
130
 
131
  # 6. Face-Fix ausführen
132
  result = pipeline(
133
  prompt=face_prompt,
134
  negative_prompt=face_negative,
135
  image=image,
136
+ mask_image=None,
137
  control_image=[pose_img, depth_img],
138
  controlnet_conditioning_scale=[0.8, 0.6], # OpenPose stärker
139
+ strength=0.4,
140
  num_inference_steps=20,
141
  guidance_scale=7.0,
142
  generator=torch.Generator(device).manual_seed(seed),
 
156
  return image
157
 
158
  print("="*60)
159
+ print("FACE-FIX MODUL FERTIG INITIALISIERT")
 
160
  print("="*60)