Astridkraft commited on
Commit
f4a8606
·
verified ·
1 Parent(s): 8644a82

Update controlnet_module.py

Browse files
Files changed (1) hide show
  1. controlnet_module.py +66 -87
controlnet_module.py CHANGED
@@ -254,96 +254,75 @@ class ControlNetProcessor:
254
  raise
255
  return self.pipe_multi_outside
256
 
257
- def generate_with_controlnet(
258
- self, image, prompt, negative_prompt,
259
- steps, guidance_scale, controlnet_strength,
260
- progress=None, keep_environment=False
261
- ):
262
- """
263
- GENERIERT BILD MIT CONTROLNET
264
- WICHTIG: Diese Funktion wird von app.py aufgerufen
265
-
266
- Parameter keep_environment bestimmt:
267
- - True: "Umgebung ändern" und "Ausschließlich Gesicht" → Depth+Canny
268
- - False: "Focus verändern" → OpenPose+Canny
269
-
270
- Die eigentliche Maskenlogik wird in app.py (create_face_mask) gehandhabt
271
- """
272
- try:
273
- # --- LOGIK FÜR 3 MODI (VON APP.PY GESTEUERT) ---
274
- if keep_environment:
275
- # FALL 1 & 3: Umgebung ändern ODER Ausschließlich Gesicht → Depth + Canny
276
- print("🎯 ControlNet: Depth + Canny (keep_environment=True)")
277
-
278
- # Beide Conditioning Maps erstellen
279
- depth_image = self.extract_depth_map(image)
280
- canny_image = self.extract_canny_edges(image)
281
- print("✅ Depth + Canny Maps für Outside/Inside-Box erstellt")
282
-
283
- # Multi-ControlNet für Outside verwenden
284
- conditioning_images = [depth_image, canny_image]
285
- controlnet_type = "multi_outside"
286
-
287
- # Gewichtung: Depth 60%, Canny 40%
288
- controlnet_conditioning_scale = [controlnet_strength * 0.6, # Depth: 60% für räumliche Tiefe
289
- controlnet_strength * 0.4] # Canny: 40% für Strukturen
290
-
291
- else:
292
- # FALL 2: Focus verändern → OpenPose + Canny
293
- print("🎯 ControlNet: OpenPose + Canny (keep_environment=False)")
294
-
295
- # Beide Conditioning Maps erstellen
296
- pose_image = self.extract_pose(image)
297
- canny_image = self.extract_canny_edges(image)
298
- print("✅ OpenPose + Canny Maps für Inside-Box erstellt")
299
-
300
- # Multi-ControlNet für Inside verwenden
301
- conditioning_images = [pose_image, canny_image]
302
- controlnet_type = "multi_inside"
303
-
304
- # Gewichtung: OpenPose 70%, Canny 30%
305
- controlnet_conditioning_scale = [controlnet_strength * 0.7, # OpenPose: 70% für Person
306
- controlnet_strength * 0.3] # Canny: 30% für Konturen
307
-
308
- # Zufälliger Seed
309
- seed = random.randint(0, 2**32 - 1)
310
- generator = torch.Generator(device=self.device).manual_seed(seed)
311
- print(f"ControlNet Seed: {seed}")
312
 
313
- pipe = self.load_controlnet_pipeline(controlnet_type)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
 
315
- # Fortschritt-Callback
316
- callback = ControlNetProgressCallback(progress, int(steps)) if progress is not None else None
317
 
318
- print("🔄 ControlNet: Starte Pipeline...")
319
-
320
- # ControlNet Generierung
321
- result = pipe(
322
- prompt=prompt,
323
- image=conditioning_images,
324
- negative_prompt=negative_prompt,
325
- num_inference_steps=int(steps),
326
- guidance_scale=guidance_scale,
327
- generator=generator,
328
- controlnet_conditioning_scale=controlnet_conditioning_scale,
329
- height=512,
330
- width=512,
331
- output_type="pil",
332
- callback_on_step_end=callback,
333
- callback_on_step_end_tensor_inputs=[],
334
- )
335
-
336
- print("✅ ControlNet abgeschlossen!")
337
-
338
- # Rückgabe: ControlNet-Output + Originalbild (für Inpaint)
339
- return result.images[0], image
340
-
341
- except Exception as e:
342
- print(f"❌ Fehler in ControlNet: {e}")
343
- import traceback
344
- traceback.print_exc()
345
- error_image = image.convert("RGB").resize((512, 512))
346
- return error_image, error_image
347
 
348
  def prepare_inpaint_input(self, image, keep_environment=False):
349
  """
 
254
  raise
255
  return self.pipe_multi_outside
256
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
 
258
+ def prepare_conditioning_maps(self, image, keep_environment=False):
259
+ """
260
+ NEUE METHODE: Erstellt und speichert Conditioning-Maps basierend auf Bild und Modus.
261
+ Wird von app.py EINMAL am Anfang aufgerufen.
262
+ """
263
+ print("🎯 ControlNet: Erstelle und speichere Conditioning-Maps...")
264
+
265
+ if keep_environment:
266
+ # FALL: Umgebung ändern oder nur Gesicht -> Depth + Canny
267
+ print(" Modus: Depth + Canny")
268
+ self.conditioning_maps = [
269
+ self.extract_depth_map(image),
270
+ self.extract_canny_edges(image)
271
+ ]
272
+ self.controlnet_type = "multi_outside"
273
+ self.controlnet_scales = [0.6, 0.4] # Gewichtung Depth vs Canny
274
+ else:
275
+ # FALL: Focus verändern -> OpenPose + Canny
276
+ print(" Modus: OpenPose + Canny")
277
+ self.conditioning_maps = [
278
+ self.extract_pose(image),
279
+ self.extract_canny_edges(image)
280
+ ]
281
+ self.controlnet_type = "multi_inside"
282
+ self.controlnet_scales = [0.7, 0.3] # Gewichtung Pose vs Canny
283
+
284
+ print(f"✅ {len(self.conditioning_maps)} Conditioning-Maps gespeichert.")
285
+ return self.conditioning_maps
286
+
287
+ def get_controlnet_conditioning(self, noisy_latents, timestep, prompt_embeds, controlnet_strength=1.0):
288
+ """
289
+ NEUE KERNMETHODE: Berechnet Steuersignale für einen spezifischen Denoising-Step.
290
+ Wird von app.py in JEDEM Denoising-Schritt aufgerufen.
291
+
292
+ Args:
293
+ noisy_latents: Aktuelle verrauschte Latents (Shape: [1, 4, 64, 64])
294
+ timestep: Aktueller Timestep (z.B. tensor([818]))
295
+ prompt_embeds: Embeddings des Prompts
296
+ controlnet_strength: Globale Stärke der ControlNet-Wirkung
297
+
298
+ Returns:
299
+ controlnet_outputs: Steuersignale, die an UNet übergeben werden
300
+ """
301
+ if not hasattr(self, 'conditioning_maps') or self.conditioning_maps is None:
302
+ raise ValueError("Conditioning-Maps nicht vorhanden. Rufen Sie zuerst prepare_conditioning_maps() auf.")
303
+
304
+ # Lade die passende Multi-ControlNet Pipeline
305
+ pipe = self.load_controlnet_pipeline(self.controlnet_type)
306
+
307
+ # Skaliere die Conditioning-Stärken mit der globalen controlnet_strength
308
+ scaled_conditioning_scales = [scale * controlnet_strength for scale in self.controlnet_scales]
309
+
310
+ # WICHTIG: ControlNet-Aufruf für EINEN Step
311
+ # Die Pipeline muss im "Single-Step-Modus" konfiguriert sein
312
+ with torch.no_grad():
313
+ controlnet_outputs = pipe.controlnet(
314
+ noisy_latents,
315
+ timestep,
316
+ encoder_hidden_states=prompt_embeds,
317
+ controlnet_cond=self.conditioning_maps,
318
+ conditioning_scale=scaled_conditioning_scales,
319
+ return_dict=True,
320
+ )
321
+
322
+ # Gib die Steuersignale zurück (z.B. mid_block_res_sample, down_block_res_samples)
323
+ return controlnet_outputs
324
 
 
 
325
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326
 
327
  def prepare_inpaint_input(self, image, keep_environment=False):
328
  """