Update controlnet_module.py
Browse files- controlnet_module.py +81 -58
controlnet_module.py
CHANGED
|
@@ -7,23 +7,25 @@ import cv2
|
|
| 7 |
import numpy as np
|
| 8 |
import gradio as gr
|
| 9 |
|
|
|
|
| 10 |
class ControlNetProgressCallback:
|
| 11 |
def __init__(self, progress, total_steps):
|
| 12 |
self.progress = progress
|
| 13 |
self.total_steps = total_steps
|
| 14 |
self.current_step = 0
|
| 15 |
-
|
| 16 |
def __call__(self, pipe, step_index, timestep, callback_kwargs):
|
| 17 |
self.current_step = step_index + 1
|
| 18 |
progress_percentage = self.current_step / self.total_steps
|
| 19 |
-
|
| 20 |
# Fortschritt aktualisieren
|
| 21 |
if self.progress is not None:
|
| 22 |
self.progress(progress_percentage, desc=f"ControlNet: Schritt {self.current_step}/{self.total_steps}")
|
| 23 |
-
|
| 24 |
print(f"ControlNet Fortschritt: {self.current_step}/{self.total_steps} ({progress_percentage:.1%})")
|
| 25 |
return callback_kwargs
|
| 26 |
|
|
|
|
| 27 |
class ControlNetProcessor:
|
| 28 |
def __init__(self, device="cuda", torch_dtype=torch.float32):
|
| 29 |
self.device = device
|
|
@@ -31,99 +33,120 @@ class ControlNetProcessor:
|
|
| 31 |
self.pose_detector = None
|
| 32 |
self.controlnet = None
|
| 33 |
self.pipe = None
|
| 34 |
-
|
| 35 |
def load_pose_detector(self):
|
| 36 |
"""Lädt nur den Pose-Detector"""
|
| 37 |
if self.pose_detector is None:
|
| 38 |
print("Loading Pose Detector...")
|
| 39 |
try:
|
| 40 |
-
self.pose_detector = OpenposeDetector.from_pretrained(
|
| 41 |
-
"lllyasviel/ControlNet",
|
| 42 |
-
)
|
| 43 |
except Exception as e:
|
| 44 |
print(f"Warnung: Pose-Detector konnte nicht geladen werden: {e}")
|
| 45 |
return self.pose_detector
|
| 46 |
-
|
| 47 |
def extract_pose_simple(self, image):
|
| 48 |
"""Einfache Pose-Extraktion ohne komplexe Abhängigkeiten"""
|
| 49 |
try:
|
| 50 |
img_array = np.array(image.convert("RGB"))
|
| 51 |
edges = cv2.Canny(img_array, 100, 200)
|
| 52 |
pose_image = Image.fromarray(edges).convert("RGB")
|
| 53 |
-
print("⚠️
|
| 54 |
return pose_image
|
| 55 |
except Exception as e:
|
| 56 |
print(f"Fehler bei einfacher Pose-Extraktion: {e}")
|
| 57 |
return image.convert("RGB").resize((512, 512))
|
| 58 |
-
|
| 59 |
def extract_pose(self, image):
|
| 60 |
"""Extrahiert Pose-Map aus Bild mit Fallback"""
|
| 61 |
try:
|
| 62 |
detector = self.load_pose_detector()
|
| 63 |
if detector is None:
|
| 64 |
return self.extract_pose_simple(image)
|
| 65 |
-
|
| 66 |
-
#pose_image = detector(image, hand_and_face=True, detect_resolution=512)
|
| 67 |
pose_image = detector.detect(image, hand_and_face=True)
|
| 68 |
return pose_image
|
| 69 |
except Exception as e:
|
| 70 |
print(f"Fehler bei Pose-Extraktion: {e}")
|
| 71 |
return self.extract_pose_simple(image)
|
| 72 |
-
|
| 73 |
-
def generate_with_controlnet(
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
| 75 |
"""Generiert Bild mit ControlNet und Fortschrittsanzeige"""
|
| 76 |
try:
|
| 77 |
-
# Pipeline laden
|
| 78 |
pipe = self.load_controlnet_pipeline()
|
| 79 |
-
|
| 80 |
-
# Pose extrahieren
|
| 81 |
print("🔄 ControlNet: Extrahiere Pose...")
|
| 82 |
if progress:
|
| 83 |
progress(0.05, desc="ControlNet: Extrahiere Pose...")
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
# Zufälliger Seed
|
| 88 |
seed = random.randint(0, 2**32 - 1)
|
| 89 |
generator = torch.Generator(device=self.device).manual_seed(seed)
|
| 90 |
print(f"ControlNet Seed: {seed}")
|
| 91 |
-
|
| 92 |
-
#
|
| 93 |
-
callback = None
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
try:
|
| 117 |
scheduler = pipe.scheduler
|
| 118 |
-
if hasattr(scheduler,
|
| 119 |
actual_steps = len(scheduler.timesteps)
|
| 120 |
print(f"🎯 CONTROLNET TATSÄCHLICHE STEPS: {actual_steps} (von {steps} angefordert)")
|
| 121 |
except Exception as e:
|
| 122 |
-
print(f"⚠️
|
| 123 |
-
|
| 124 |
print("✅ ControlNet abgeschlossen!")
|
| 125 |
return result.images[0]
|
| 126 |
-
|
| 127 |
except Exception as e:
|
| 128 |
print(f"❌ Fehler in ControlNet: {e}")
|
| 129 |
import traceback
|
|
@@ -136,7 +159,7 @@ class ControlNetProcessor:
|
|
| 136 |
print("Loading ControlNet pipeline...")
|
| 137 |
try:
|
| 138 |
self.controlnet = ControlNetModel.from_pretrained(
|
| 139 |
-
"lllyasviel/sd-controlnet-openpose",
|
| 140 |
torch_dtype=self.torch_dtype
|
| 141 |
)
|
| 142 |
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
|
@@ -146,19 +169,19 @@ class ControlNetProcessor:
|
|
| 146 |
safety_checker=None,
|
| 147 |
requires_safety_checker=False
|
| 148 |
).to(self.device)
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
self.pipe.enable_attention_slicing()
|
| 156 |
-
print("ControlNet pipeline loaded successfully!")
|
| 157 |
except Exception as e:
|
| 158 |
print(f"Fehler beim Laden von ControlNet: {e}")
|
| 159 |
raise
|
| 160 |
return self.pipe
|
| 161 |
|
|
|
|
| 162 |
# Globale Instanz
|
| 163 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 164 |
torch_dtype = torch.float16 if device == "cuda" else torch.float32
|
|
|
|
| 7 |
import numpy as np
|
| 8 |
import gradio as gr
|
| 9 |
|
| 10 |
+
|
| 11 |
class ControlNetProgressCallback:
|
| 12 |
def __init__(self, progress, total_steps):
|
| 13 |
self.progress = progress
|
| 14 |
self.total_steps = total_steps
|
| 15 |
self.current_step = 0
|
| 16 |
+
|
| 17 |
def __call__(self, pipe, step_index, timestep, callback_kwargs):
|
| 18 |
self.current_step = step_index + 1
|
| 19 |
progress_percentage = self.current_step / self.total_steps
|
| 20 |
+
|
| 21 |
# Fortschritt aktualisieren
|
| 22 |
if self.progress is not None:
|
| 23 |
self.progress(progress_percentage, desc=f"ControlNet: Schritt {self.current_step}/{self.total_steps}")
|
| 24 |
+
|
| 25 |
print(f"ControlNet Fortschritt: {self.current_step}/{self.total_steps} ({progress_percentage:.1%})")
|
| 26 |
return callback_kwargs
|
| 27 |
|
| 28 |
+
|
| 29 |
class ControlNetProcessor:
|
| 30 |
def __init__(self, device="cuda", torch_dtype=torch.float32):
|
| 31 |
self.device = device
|
|
|
|
| 33 |
self.pose_detector = None
|
| 34 |
self.controlnet = None
|
| 35 |
self.pipe = None
|
| 36 |
+
|
| 37 |
def load_pose_detector(self):
|
| 38 |
"""Lädt nur den Pose-Detector"""
|
| 39 |
if self.pose_detector is None:
|
| 40 |
print("Loading Pose Detector...")
|
| 41 |
try:
|
| 42 |
+
self.pose_detector = OpenposeDetector.from_pretrained("lllyasviel/ControlNet")
|
|
|
|
|
|
|
| 43 |
except Exception as e:
|
| 44 |
print(f"Warnung: Pose-Detector konnte nicht geladen werden: {e}")
|
| 45 |
return self.pose_detector
|
| 46 |
+
|
| 47 |
def extract_pose_simple(self, image):
|
| 48 |
"""Einfache Pose-Extraktion ohne komplexe Abhängigkeiten"""
|
| 49 |
try:
|
| 50 |
img_array = np.array(image.convert("RGB"))
|
| 51 |
edges = cv2.Canny(img_array, 100, 200)
|
| 52 |
pose_image = Image.fromarray(edges).convert("RGB")
|
| 53 |
+
print("⚠️ Verwende Kanten-basierte Pose-Approximation")
|
| 54 |
return pose_image
|
| 55 |
except Exception as e:
|
| 56 |
print(f"Fehler bei einfacher Pose-Extraktion: {e}")
|
| 57 |
return image.convert("RGB").resize((512, 512))
|
| 58 |
+
|
| 59 |
def extract_pose(self, image):
|
| 60 |
"""Extrahiert Pose-Map aus Bild mit Fallback"""
|
| 61 |
try:
|
| 62 |
detector = self.load_pose_detector()
|
| 63 |
if detector is None:
|
| 64 |
return self.extract_pose_simple(image)
|
| 65 |
+
|
|
|
|
| 66 |
pose_image = detector.detect(image, hand_and_face=True)
|
| 67 |
return pose_image
|
| 68 |
except Exception as e:
|
| 69 |
print(f"Fehler bei Pose-Extraktion: {e}")
|
| 70 |
return self.extract_pose_simple(image)
|
| 71 |
+
|
| 72 |
+
def generate_with_controlnet(
|
| 73 |
+
self, image, prompt, negative_prompt,
|
| 74 |
+
steps, guidance_scale, controlnet_strength,
|
| 75 |
+
progress=None, keep_environment=False
|
| 76 |
+
):
|
| 77 |
"""Generiert Bild mit ControlNet und Fortschrittsanzeige"""
|
| 78 |
try:
|
|
|
|
| 79 |
pipe = self.load_controlnet_pipeline()
|
| 80 |
+
|
|
|
|
| 81 |
print("🔄 ControlNet: Extrahiere Pose...")
|
| 82 |
if progress:
|
| 83 |
progress(0.05, desc="ControlNet: Extrahiere Pose...")
|
| 84 |
+
|
| 85 |
+
# --- Fallunterscheidung ---
|
| 86 |
+
if keep_environment:
|
| 87 |
+
print("🎯 Modus: Umgebung beibehalten (nutze Originalbild als Quelle)")
|
| 88 |
+
input_image = image
|
| 89 |
+
conditioning_image = None
|
| 90 |
+
else:
|
| 91 |
+
print("🎯 Modus: Umgebung darf sich ändern (nutze Pose-Map)")
|
| 92 |
+
conditioning_image = self.extract_pose(image)
|
| 93 |
+
input_image = conditioning_image
|
| 94 |
+
|
| 95 |
# Zufälliger Seed
|
| 96 |
seed = random.randint(0, 2**32 - 1)
|
| 97 |
generator = torch.Generator(device=self.device).manual_seed(seed)
|
| 98 |
print(f"ControlNet Seed: {seed}")
|
| 99 |
+
|
| 100 |
+
# Fortschritt-Callback
|
| 101 |
+
callback = ControlNetProgressCallback(progress, int(steps)) if progress is not None else None
|
| 102 |
+
|
| 103 |
+
print("🔄 ControlNet: Starte Pipeline...")
|
| 104 |
+
|
| 105 |
+
if conditioning_image is not None:
|
| 106 |
+
# Umgebung darf sich ändern
|
| 107 |
+
result = pipe(
|
| 108 |
+
prompt=prompt,
|
| 109 |
+
image=conditioning_image,
|
| 110 |
+
negative_prompt=negative_prompt,
|
| 111 |
+
num_inference_steps=int(steps),
|
| 112 |
+
guidance_scale=guidance_scale,
|
| 113 |
+
generator=generator,
|
| 114 |
+
controlnet_conditioning_scale=controlnet_strength,
|
| 115 |
+
height=512,
|
| 116 |
+
width=512,
|
| 117 |
+
output_type="pil",
|
| 118 |
+
callback_on_step_end=callback,
|
| 119 |
+
callback_on_step_end_tensor_inputs=[],
|
| 120 |
+
)
|
| 121 |
+
else:
|
| 122 |
+
# Umgebung soll beibehalten werden
|
| 123 |
+
result = pipe(
|
| 124 |
+
prompt=prompt,
|
| 125 |
+
image=input_image,
|
| 126 |
+
negative_prompt=negative_prompt,
|
| 127 |
+
num_inference_steps=int(steps),
|
| 128 |
+
guidance_scale=guidance_scale,
|
| 129 |
+
generator=generator,
|
| 130 |
+
controlnet_conditioning_scale=controlnet_strength,
|
| 131 |
+
height=512,
|
| 132 |
+
width=512,
|
| 133 |
+
output_type="pil",
|
| 134 |
+
callback_on_step_end=callback,
|
| 135 |
+
callback_on_step_end_tensor_inputs=[],
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
# Debug-Ausgabe Scheduler Steps
|
| 139 |
try:
|
| 140 |
scheduler = pipe.scheduler
|
| 141 |
+
if hasattr(scheduler, "timesteps"):
|
| 142 |
actual_steps = len(scheduler.timesteps)
|
| 143 |
print(f"🎯 CONTROLNET TATSÄCHLICHE STEPS: {actual_steps} (von {steps} angefordert)")
|
| 144 |
except Exception as e:
|
| 145 |
+
print(f"⚠️ Konnte ControlNet Scheduler-Info nicht auslesen: {e}")
|
| 146 |
+
|
| 147 |
print("✅ ControlNet abgeschlossen!")
|
| 148 |
return result.images[0]
|
| 149 |
+
|
| 150 |
except Exception as e:
|
| 151 |
print(f"❌ Fehler in ControlNet: {e}")
|
| 152 |
import traceback
|
|
|
|
| 159 |
print("Loading ControlNet pipeline...")
|
| 160 |
try:
|
| 161 |
self.controlnet = ControlNetModel.from_pretrained(
|
| 162 |
+
"lllyasviel/sd-controlnet-openpose",
|
| 163 |
torch_dtype=self.torch_dtype
|
| 164 |
)
|
| 165 |
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
|
|
|
| 169 |
safety_checker=None,
|
| 170 |
requires_safety_checker=False
|
| 171 |
).to(self.device)
|
| 172 |
+
|
| 173 |
+
# Scheduler wechseln zu Euler Ancestral
|
| 174 |
+
from diffusers import EulerAncestralDiscreteScheduler
|
| 175 |
+
self.pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(self.pipe.scheduler.config)
|
| 176 |
+
|
|
|
|
| 177 |
self.pipe.enable_attention_slicing()
|
| 178 |
+
print("✅ ControlNet pipeline loaded successfully with EulerAncestralDiscreteScheduler!")
|
| 179 |
except Exception as e:
|
| 180 |
print(f"Fehler beim Laden von ControlNet: {e}")
|
| 181 |
raise
|
| 182 |
return self.pipe
|
| 183 |
|
| 184 |
+
|
| 185 |
# Globale Instanz
|
| 186 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 187 |
torch_dtype = torch.float16 if device == "cuda" else torch.float32
|