Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,7 +2,7 @@ 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
|
|
@@ -15,38 +15,41 @@ IMG_SIZE = 512
|
|
| 15 |
|
| 16 |
print(f"Running on: {device}")
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
# === GESICHTSMASKEN-FUNKTIONEN ===
|
| 19 |
def create_face_mask(image, bbox_coords, face_preserve):
|
| 20 |
"""Erzeugt eine Gesichtsmaske - WEIßE Bereiche werden VERÄNDERT, SCHWARZE BLEIBEN"""
|
| 21 |
-
mask = Image.new("L", image.size, 0)
|
| 22 |
|
| 23 |
if bbox_coords and all(coord is not None for coord in bbox_coords):
|
| 24 |
x1, y1, x2, y2 = bbox_coords
|
| 25 |
draw = ImageDraw.Draw(mask)
|
| 26 |
|
| 27 |
if face_preserve:
|
| 28 |
-
|
| 29 |
-
draw.rectangle([
|
| 30 |
-
|
| 31 |
-
print("Gesicht wird GESCHÜTZT - Umgebung wird verändert (rechteckige Maske)")
|
| 32 |
else:
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
print("Nur Gesicht wird verändert - Umgebung bleibt erhalten (rechteckige Maske)")
|
| 36 |
|
| 37 |
return mask
|
| 38 |
|
| 39 |
def auto_detect_face_area(image):
|
| 40 |
"""Optimierten Vorschlag für Gesichtsbereich ohne externe Bibliotheken"""
|
| 41 |
width, height = image.size
|
| 42 |
-
# Größere Bounding Box für bessere Abdeckung (50% statt 40%)
|
| 43 |
face_size = min(width, height) * 0.4
|
| 44 |
-
# Verschiebe y1 nach oben, um Stirn und Kinn besser abzudecken
|
| 45 |
x1 = (width - face_size) / 2
|
| 46 |
-
y1 = (height - face_size) / 4
|
| 47 |
x2 = x1 + face_size
|
| 48 |
-
y2 = y1 + face_size * 1.2
|
| 49 |
-
# Stelle sicher, dass Koordinaten innerhalb des Bildes liegen
|
| 50 |
x1, y1 = max(0, int(x1)), max(0, int(y1))
|
| 51 |
x2, y2 = min(width, int(x2)), min(height, int(y2))
|
| 52 |
print(f"Geschätzte Gesichtskoordinaten: [{x1}, {y1}, {x2}, {y2}]")
|
|
@@ -66,7 +69,6 @@ def load_txt2img():
|
|
| 66 |
use_safetensors=True,
|
| 67 |
safety_checker=None,
|
| 68 |
requires_safety_checker=False,
|
| 69 |
-
#clean_up_tokenization_spaces=False #bei der neuen Version ändert sich die Architektur, Clip wird ersetzt/erweitert/integriert. Tokenizer nicht mehr nur auf englisch, kein 77-Token Limit!
|
| 70 |
).to(device)
|
| 71 |
|
| 72 |
from diffusers import DPMSolverMultistepScheduler
|
|
@@ -81,18 +83,14 @@ def load_img2img():
|
|
| 81 |
try:
|
| 82 |
pipe_img2img = StableDiffusionInpaintPipeline.from_pretrained(
|
| 83 |
"runwayml/stable-diffusion-inpainting",
|
| 84 |
-
#"stabilityai/stable-diffusion-2-inpainting", # Modell Download auf HF nicht immer möglich
|
| 85 |
torch_dtype=torch_dtype,
|
| 86 |
-
|
| 87 |
-
allow_pickle=False, # Verhindere unsichere Serialisierung
|
| 88 |
safety_checker=None,
|
| 89 |
-
#clean_up_tokenization_spaces=False #benötigt neue Transformer-Version
|
| 90 |
).to(device)
|
| 91 |
except Exception as e:
|
| 92 |
print(f"Fehler beim Laden des Modells: {e}")
|
| 93 |
raise
|
| 94 |
|
| 95 |
-
|
| 96 |
from diffusers import DPMSolverMultistepScheduler
|
| 97 |
pipe_img2img.scheduler = DPMSolverMultistepScheduler.from_config(
|
| 98 |
pipe_img2img.scheduler.config,
|
|
@@ -107,7 +105,7 @@ def load_img2img():
|
|
| 107 |
|
| 108 |
return pipe_img2img
|
| 109 |
|
| 110 |
-
# ===
|
| 111 |
class TextToImageProgressCallback:
|
| 112 |
def __init__(self, progress, total_steps):
|
| 113 |
self.progress = progress
|
|
@@ -115,7 +113,6 @@ class TextToImageProgressCallback:
|
|
| 115 |
self.current_step = 0
|
| 116 |
|
| 117 |
def __call__(self, pipe, step, timestep, callback_kwargs):
|
| 118 |
-
"""Neue Callback-Signatur für diffusers >= 1.0.0"""
|
| 119 |
self.current_step = step + 1
|
| 120 |
progress_percent = (step / self.total_steps) * 100
|
| 121 |
self.progress(progress_percent / 100, desc="Generierung läuft - CPU benötigt bis zu 20 Minuten!")
|
|
@@ -130,12 +127,9 @@ class ImageToImageProgressCallback:
|
|
| 130 |
self.actual_total_steps = None
|
| 131 |
|
| 132 |
def __call__(self, pipe, step, timestep, callback_kwargs):
|
| 133 |
-
"""Neue Callback-Signatur für diffusers >= 1.0.0"""
|
| 134 |
self.current_step = step + 1
|
| 135 |
|
| 136 |
-
# Korrekte Berechnung der tatsächlichen Steps
|
| 137 |
if self.actual_total_steps is None:
|
| 138 |
-
# Bei Strength < 1.0 werden weniger Steps verwendet
|
| 139 |
if self.strength < 1.0:
|
| 140 |
self.actual_total_steps = int(self.total_steps * self.strength)
|
| 141 |
else:
|
|
@@ -147,47 +141,39 @@ class ImageToImageProgressCallback:
|
|
| 147 |
self.progress(progress_percent / 100, desc="Generierung läuft - CPU benötigt bis zu 20 Minuten!")
|
| 148 |
return callback_kwargs
|
| 149 |
|
| 150 |
-
# ===
|
| 151 |
def create_preview_image(image, bbox_coords, face_preserve, mode_color):
|
| 152 |
"""Erstellt eine Vorschau mit farbigem Rahmen basierend auf dem Modus"""
|
| 153 |
if image is None:
|
| 154 |
return None
|
| 155 |
|
| 156 |
-
# Erstelle eine Kopie für die Vorschau
|
| 157 |
preview = image.copy()
|
| 158 |
draw = ImageDraw.Draw(preview)
|
| 159 |
|
| 160 |
-
# Rahmenfarbe basierend auf Modus
|
| 161 |
if mode_color == "red":
|
| 162 |
-
border_color = (255, 0, 0, 180)
|
| 163 |
mode_text = "NUR BILDELEMENT VERÄNDERN"
|
| 164 |
else:
|
| 165 |
-
border_color = (0, 255, 0, 180)
|
| 166 |
mode_text = "BILDELEMENT BEIBEHALTEN"
|
| 167 |
|
| 168 |
-
# Zeichne den Rahmen um das gesamte Bild
|
| 169 |
border_width = 8
|
| 170 |
draw.rectangle([0, 0, preview.width-1, preview.height-1],
|
| 171 |
outline=border_color, width=border_width)
|
| 172 |
|
| 173 |
-
# Zeichne Bounding Box wenn Koordinaten vorhanden
|
| 174 |
if bbox_coords and all(coord is not None for coord in bbox_coords):
|
| 175 |
x1, y1, x2, y2 = bbox_coords
|
| 176 |
|
| 177 |
-
|
| 178 |
-
box_color = (255, 255, 0, 200) # Gelb für Bounding Box
|
| 179 |
draw.rectangle([x1, y1, x2, y2], outline=box_color, width=3)
|
| 180 |
|
| 181 |
-
# Text-Label für den Modus
|
| 182 |
text_color = (255, 255, 255)
|
| 183 |
bg_color = (0, 0, 0, 160)
|
| 184 |
|
| 185 |
-
# Hintergrund für Text
|
| 186 |
text_bbox = draw.textbbox((x1, y1 - 25), mode_text)
|
| 187 |
draw.rectangle([text_bbox[0]-5, text_bbox[1]-2, text_bbox[2]+5, text_bbox[3]+2],
|
| 188 |
fill=bg_color)
|
| 189 |
|
| 190 |
-
# Text zeichnen
|
| 191 |
draw.text((x1, y1 - 25), mode_text, fill=text_color)
|
| 192 |
|
| 193 |
return preview
|
|
@@ -198,8 +184,6 @@ def update_live_preview(image, bbox_x1, bbox_y1, bbox_x2, bbox_y2, face_preserve
|
|
| 198 |
return None
|
| 199 |
|
| 200 |
bbox_coords = [bbox_x1, bbox_y1, bbox_x2, bbox_y2]
|
| 201 |
-
|
| 202 |
-
# Bestimme Rahmenfarbe basierend auf Modus
|
| 203 |
mode_color = "green" if face_preserve else "red"
|
| 204 |
|
| 205 |
return create_preview_image(image, bbox_coords, face_preserve, mode_color)
|
|
@@ -209,16 +193,13 @@ def process_image_upload(image):
|
|
| 209 |
if image is None:
|
| 210 |
return None, None, None, None, None
|
| 211 |
|
| 212 |
-
# Auto-Koordinaten generieren
|
| 213 |
bbox = auto_detect_face_area(image)
|
| 214 |
bbox_x1, bbox_y1, bbox_x2, bbox_y2 = bbox
|
| 215 |
-
|
| 216 |
-
# Vorschau mit grünem Rahmen (Standard: Gesicht beibehalten)
|
| 217 |
preview = create_preview_image(image, bbox, True, "green")
|
| 218 |
|
| 219 |
return preview, bbox_x1, bbox_y1, bbox_x2, bbox_y2
|
| 220 |
|
| 221 |
-
# ===
|
| 222 |
def text_to_image(prompt, steps, guidance_scale, progress=gr.Progress()):
|
| 223 |
try:
|
| 224 |
if not prompt or not prompt.strip():
|
|
@@ -227,17 +208,14 @@ def text_to_image(prompt, steps, guidance_scale, progress=gr.Progress()):
|
|
| 227 |
print(f"Starting generation for: {prompt}")
|
| 228 |
start_time = time.time()
|
| 229 |
|
| 230 |
-
# Statusmeldung anzeigen
|
| 231 |
progress(0, desc="Generierung läuft - CPU benötigt bis zu 20 Minuten!")
|
| 232 |
|
| 233 |
pipe = load_txt2img()
|
| 234 |
|
| 235 |
-
# ZUFÄLLIGER SEED für Variation
|
| 236 |
seed = random.randint(0, 2**32 - 1)
|
| 237 |
generator = torch.Generator(device=device).manual_seed(seed)
|
| 238 |
print(f"Using seed: {seed}")
|
| 239 |
|
| 240 |
-
# NEUE Callback-Implementierung
|
| 241 |
callback = TextToImageProgressCallback(progress, steps)
|
| 242 |
|
| 243 |
image = pipe(
|
|
@@ -247,14 +225,13 @@ def text_to_image(prompt, steps, guidance_scale, progress=gr.Progress()):
|
|
| 247 |
num_inference_steps=int(steps),
|
| 248 |
guidance_scale=guidance_scale,
|
| 249 |
generator=generator,
|
| 250 |
-
callback_on_step_end=callback,
|
| 251 |
-
callback_on_step_end_tensor_inputs=[],
|
| 252 |
).images[0]
|
| 253 |
|
| 254 |
end_time = time.time()
|
| 255 |
print(f"Bild generiert in {end_time - start_time:.2f} Sekunden")
|
| 256 |
|
| 257 |
-
# Robuste Zwischenspeicherung
|
| 258 |
return image
|
| 259 |
|
| 260 |
except Exception as e:
|
|
@@ -269,33 +246,24 @@ def img_to_image(image, prompt, neg_prompt, strength, steps, guidance_scale, fac
|
|
| 269 |
return None
|
| 270 |
|
| 271 |
print(f"Img2Img Start → Strength: {strength}, Steps: {steps}, Guidance: {guidance_scale}")
|
| 272 |
-
print(f"Prompt: {prompt}")
|
| 273 |
-
print(f"Negativ-Prompt: {neg_prompt}")
|
| 274 |
-
print(f"Gesicht beibehalten: {face_preserve}")
|
| 275 |
start_time = time.time()
|
| 276 |
|
| 277 |
-
# Statusmeldung anzeigen zur Zeitüberbrückung - Callback wird erst nach ersten Step aufgerufen!
|
| 278 |
progress(0, desc="Generierung läuft - CPU benötigt bis zu 20 Minuten!")
|
| 279 |
|
| 280 |
pipe = load_img2img()
|
| 281 |
img_resized = image.convert("RGB").resize((IMG_SIZE, IMG_SIZE))
|
| 282 |
|
| 283 |
-
|
| 284 |
-
adj_strength = min(0.85, strength * 1.3) #die optimierten Werte von GPT, Grok sind nicht optimal besser strength vergrößern!
|
| 285 |
adj_guidance = min(guidance_scale, 12.0)
|
| 286 |
|
| 287 |
-
|
| 288 |
-
# ZUFÄLLIGER SEED für Variation
|
| 289 |
seed = random.randint(0, 2**32 - 1)
|
| 290 |
generator = torch.Generator(device=device).manual_seed(seed)
|
| 291 |
print(f"Using seed: {seed}")
|
| 292 |
|
| 293 |
-
# --- GESICHTSMASKE ---
|
| 294 |
mask = None
|
| 295 |
bbox_coords = None
|
| 296 |
|
| 297 |
if bbox_x1 is not None and bbox_y1 is not None and bbox_x2 is not None and bbox_y2 is not None:
|
| 298 |
-
# Skaliere Koordinaten auf die neue Bildgröße
|
| 299 |
orig_width, orig_height = image.size
|
| 300 |
scale_x = IMG_SIZE / orig_width
|
| 301 |
scale_y = IMG_SIZE / orig_height
|
|
@@ -307,58 +275,25 @@ def img_to_image(image, prompt, neg_prompt, strength, steps, guidance_scale, fac
|
|
| 307 |
int(bbox_y2 * scale_y)
|
| 308 |
]
|
| 309 |
bbox_coords = scaled_coords
|
| 310 |
-
print(f"Skalierte Koordinaten: {scaled_coords}")
|
| 311 |
|
| 312 |
-
# Maskenlogik basierend auf face_preserve
|
| 313 |
if bbox_coords:
|
| 314 |
mask = create_face_mask(img_resized, bbox_coords, face_preserve)
|
| 315 |
-
if mask:
|
| 316 |
-
print("Maske erfolgreich erstellt")
|
| 317 |
-
else:
|
| 318 |
-
print("Keine gültigen Koordinaten - keine Maske angewendet")
|
| 319 |
-
mask = None
|
| 320 |
-
|
| 321 |
-
# Detaillierte Debug-Informationen vor dem Pipeline-Aufruf
|
| 322 |
-
print(f"⚙️ PIPELINE-KONFIGURATION:")
|
| 323 |
-
print(f" - Angefordert: {int(steps)} Steps")
|
| 324 |
-
print(f" - Strength: {adj_strength:.3f}")
|
| 325 |
-
print(f" - Scheduler: {pipe.scheduler.__class__.__name__}")
|
| 326 |
-
|
| 327 |
-
# Korrekte Berechnung der tatsächlichen Steps
|
| 328 |
-
actual_steps_from_strength = int(steps * adj_strength)
|
| 329 |
-
print(f"🎯 KORREKTE INTERNE STEP-AUSGABE: {int(steps)} Steps × Strength {adj_strength:.3f} = {actual_steps_from_strength} tatsächliche Schritte")
|
| 330 |
|
| 331 |
-
# NEUE Callback-Implementierung
|
| 332 |
callback = ImageToImageProgressCallback(progress, int(steps), adj_strength)
|
| 333 |
|
| 334 |
-
# --- PIPELINE-AUFRUF MIT NEUER API ---
|
| 335 |
result = pipe(
|
| 336 |
prompt=prompt,
|
| 337 |
negative_prompt=neg_prompt,
|
| 338 |
image=img_resized,
|
| 339 |
-
mask_image=mask,
|
| 340 |
strength=adj_strength,
|
| 341 |
num_inference_steps=int(steps),
|
| 342 |
guidance_scale=adj_guidance,
|
| 343 |
generator=generator,
|
| 344 |
-
callback_on_step_end=callback,
|
| 345 |
-
callback_on_step_end_tensor_inputs=[],
|
| 346 |
)
|
| 347 |
|
| 348 |
-
# ZUSÄTZLICHE AUSGABE: Tatsächliche Steps vom Sceduler-Inpaint berechnet steps intern. Max_step ist aus UI-Übergabe.
|
| 349 |
-
# Der Sceduler von Inpaint berechnet steps in Abhängigkeit von strength. Bei text_to_image kein Problem da andere Pipeline!
|
| 350 |
-
try:
|
| 351 |
-
scheduler = pipe.scheduler
|
| 352 |
-
print(f"🔧 SCHEDULER-INFO: {scheduler.__class__.__name__}")
|
| 353 |
-
print(f"📊 TATSÄCHLICHE STEP-KONFIGURATION: {int(steps)} Schritte mit Strength {adj_strength:.3f}")
|
| 354 |
-
|
| 355 |
-
if hasattr(scheduler, 'timesteps'):
|
| 356 |
-
actual_steps = len(scheduler.timesteps)
|
| 357 |
-
print(f"🎯 BESTÄTIGTE INTERNE STEP-AUSGABE: Scheduler verwendete {actual_steps} tatsächliche Denoising-Schritte")
|
| 358 |
-
|
| 359 |
-
except Exception as e:
|
| 360 |
-
print(f"⚠️ Konnte Scheduler-Info nicht auslesen: {e}")
|
| 361 |
-
|
| 362 |
end_time = time.time()
|
| 363 |
print(f"Bild transformiert in {end_time - start_time:.2f} Sekunden")
|
| 364 |
|
|
@@ -372,13 +307,18 @@ def img_to_image(image, prompt, neg_prompt, strength, steps, guidance_scale, fac
|
|
| 372 |
traceback.print_exc()
|
| 373 |
return None
|
| 374 |
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 379 |
|
| 380 |
-
|
| 381 |
-
return
|
| 382 |
|
| 383 |
def main_ui():
|
| 384 |
with gr.Blocks(
|
|
@@ -392,169 +332,51 @@ def main_ui():
|
|
| 392 |
border-left: 4px solid #8B7355;
|
| 393 |
margin: 20px 0;
|
| 394 |
}
|
| 395 |
-
.
|
| 396 |
-
|
| 397 |
-
cursor: pointer;
|
| 398 |
-
text-decoration: none;
|
| 399 |
-
font-family: 'Monaco', 'Consolas', monospace;
|
| 400 |
-
background: #e3f2fd;
|
| 401 |
-
padding: 2px 6px;
|
| 402 |
-
border-radius: 4px;
|
| 403 |
-
border: 1px solid #bbdefb;
|
| 404 |
-
}
|
| 405 |
-
.clickable-file:hover {
|
| 406 |
-
background: #bbdefb;
|
| 407 |
-
text-decoration: underline;
|
| 408 |
-
}
|
| 409 |
-
#start-button {
|
| 410 |
-
background-color: #0080FF !important;
|
| 411 |
-
border: none !important;
|
| 412 |
-
margin: 50px auto !important;
|
| 413 |
-
display: block !important;
|
| 414 |
-
font-weight: 600;
|
| 415 |
-
width: 280px;
|
| 416 |
-
}
|
| 417 |
-
#start-button:hover {
|
| 418 |
-
background-color: #D3D3D3 !important;
|
| 419 |
-
}
|
| 420 |
-
.hint-box {
|
| 421 |
-
margin-top: 20px;
|
| 422 |
-
}
|
| 423 |
-
.custom-text {
|
| 424 |
-
font-size: 25px !important;
|
| 425 |
-
}
|
| 426 |
-
.image-upload .svelte-1p4f8co {
|
| 427 |
-
display: block !important;
|
| 428 |
-
}
|
| 429 |
-
.preview-box {
|
| 430 |
-
border: 2px dashed #ccc;
|
| 431 |
-
padding: 10px;
|
| 432 |
-
border-radius: 8px;
|
| 433 |
-
margin: 10px 0;
|
| 434 |
-
}
|
| 435 |
-
.mode-red {
|
| 436 |
-
border: 3px solid #ff4444 !important;
|
| 437 |
-
}
|
| 438 |
-
.mode-green {
|
| 439 |
-
border: 3px solid #44ff44 !important;
|
| 440 |
-
}
|
| 441 |
-
.coordinate-sliders {
|
| 442 |
-
background: #f8f9fa;
|
| 443 |
padding: 15px;
|
| 444 |
border-radius: 8px;
|
| 445 |
-
margin:
|
|
|
|
| 446 |
}
|
| 447 |
"""
|
| 448 |
) as demo:
|
| 449 |
|
| 450 |
-
# --- Info-Bereich
|
| 451 |
-
gr.Markdown(
|
| 452 |
-
|
| 453 |
-
# Demo-Projekt: Stable Diffusion Text-to-Image / Image-to-Image
|
| 454 |
-
<br>
|
| 455 |
-
|
| 456 |
-
<div class="info-box">
|
| 457 |
-
Dieses Projekt ist ein kleines <strong>Demo</strong> um meine Fähigkeiten als <strong>AI-Engineer</strong>
|
| 458 |
-
in technischer Kompetenz und selbstständiger Projektstrukturierung zu zeigen.<br>
|
| 459 |
-
Der Fokus liegt auf <strong>Struktur, Konzept und technischer Umsetzung</strong>
|
| 460 |
-
im Bereich Text-to-Image / Image-to-Image mit dem Diffusionsmodell "Stable Diffusion" <br>
|
| 461 |
-
<strong>nicht</strong> auf einer vollständigen Produktionsversion.
|
| 462 |
-
</div>
|
| 463 |
-
<br>
|
| 464 |
-
|
| 465 |
-
<div class="info-box">
|
| 466 |
-
Zudem führt der Link
|
| 467 |
-
<a class="clickable-file" href="https://huggingface.co/spaces/Astridkraft/Dokumentation" target="_blank">Roadmap</a>
|
| 468 |
-
zu einer <strong>durchdachten, skalierbaren, professionellen Code-Architektur</strong> für Text-to-Image- und Image-to-Image-Entwicklung <br>
|
| 469 |
-
die die <strong>gesamte Komplexität einer professionellen Umsetzung</strong> verdeutlicht.<br><br>
|
| 470 |
-
Die damit gezeigten Fähigkeiten meinerseits sind <strong>sicherlich auf andere Projekte übertragbar</strong>.
|
| 471 |
-
</div>
|
| 472 |
-
<br><br>
|
| 473 |
-
|
| 474 |
-
<div class="info-box">
|
| 475 |
-
<strong>Hinweis:</strong><br>
|
| 476 |
-
Die Anwendung läuft derzeit auf <strong>CPU</strong> ist jedoch <strong>vollständig GPU-fähig </strong>.
|
| 477 |
-
Deshalb muss bei jeder Generierung eine <strong>längere Wartezeit</strong> eingeplant werden.<br>
|
| 478 |
-
Bei <strong>Verbindungsabbrüchen</strong> -insbesondere bei CPU-Nutzung- wird die aktuelle Generierung zunächst serverseitig vollständig abgeschlossen, <br>
|
| 479 |
-
bevor neue Anfragen bearbeitet werden. Das generierte Bild wird in diesem Fall <strong>nicht angezeigt</strong>.
|
| 480 |
-
Die Meldung <strong>Connection re-established</strong> signalisiert, dass <br>
|
| 481 |
-
die Verbindung wiederhergestellt wurde, die laufende Verarbeitung jedoch priorisiert wird. In der Konsequenz werden neue <br>
|
| 482 |
-
Generierungsanfragen in eine Warteschlange gestellt und erst nach vollständigem Abschluss der aktuellen serverseitigen Berechnung verarbeitet.
|
| 483 |
-
</div>
|
| 484 |
-
<br>
|
| 485 |
-
|
| 486 |
-
<div class="info-box">
|
| 487 |
-
<strong>Technischer Hintergrund:</strong> <br>
|
| 488 |
-
Es handelt sich um einen bekannten <strong>Gradio-Bug</strong> - das Framework bietet keine Möglichkeit, generierte Bilder zwischenzuspeichern <br>
|
| 489 |
-
um sie bei UI-Neuladung aus dem Zwischenspeicher zurückzugeben. Dies macht sich <strong>besonders bei CPU-Nutzung bemerkbar</strong>, <br>
|
| 490 |
-
da die Transformationszeiten hier deutlich länger sind und es dadurch vermehrt zu Timeouts und daraus resultierenden UI-Abbrüchen kommen kann.<br>
|
| 491 |
-
Aus diesem Grund kann das Ergebnis nicht an die neu geladene Benutzeroberfläche übermittelt werden obwohl die Bildgenerierung serverseitig <br>
|
| 492 |
-
vollständig abgeschlossen wird.
|
| 493 |
-
</div>
|
| 494 |
-
<br>
|
| 495 |
-
|
| 496 |
-
<div class="info-box">
|
| 497 |
-
<strong>Anwendungsbereich:</strong><br>
|
| 498 |
-
Die <strong>Bild-zu-Bild-Funktion</strong> ermöglicht eine gezielte Bearbeitung eines <strong>beliebigen Objektes oder Bereiches</strong> in einem Bild.<br>
|
| 499 |
-
Sie unterstützt zwei Modi:<br>
|
| 500 |
-
• <strong>Beibehaltung eines ausgewählten Bildbereiches innerhalb eines Rechtecks</strong> (z. B. Gesicht, Objekt, Tier, Gegenstand) bei Veränderung des Rests,<br>
|
| 501 |
-
• oder <strong>Veränderung des rechteckigen Bildbereiches</strong> bei Erhaltung der Umgebung.<br>
|
| 502 |
-
<br>
|
| 503 |
-
<strong>Wichtig:</strong> Das Objekt das beibehalten oder verändert werden soll - je nach gewähltem Modus - muss <strong>im Prompt</strong> klar beschrieben werden.<br>
|
| 504 |
-
Die Verwendung eines <strong>Negativ-Promptes</strong> ist sinnvoll, um unerwünschte Veränderungen zu vermeiden.
|
| 505 |
-
</div>
|
| 506 |
-
<br>
|
| 507 |
-
|
| 508 |
-
<div class="info-box">
|
| 509 |
-
<strong>Empfehlung:</strong><br>
|
| 510 |
-
Für eine präzise Abstimmung der zentralen Parameter – Prompt, Negativ-Prompt, Veränderungsstärke (Strength), Inferenz-Schritte (Steps) <br>
|
| 511 |
-
und Prompt-Stärke (Guidance) – liefern leistungsfähige Sprachmodelle wie GPT, Grok oder DeepSeek hochqualitative, kontextbezogene Vorschläge.<br>
|
| 512 |
-
Prompt und Negativ-Prompt sollten auf <strong>Englisch</strong> eingegeben werden, da "Stable Diffusion" mit Bild-Text-Paaren auf Englisch trainiert <br>
|
| 513 |
-
wurde und CLIP einen Tokenizer für ein englisches Vokabular nutzt. Der CLIP-Tokenizer hat außerdem ein <strong>Limit von 77 Token</strong>, wodurch längere <br>
|
| 514 |
-
Prompteingaben automatisch abgeschnitten werden. Deutsche Wörter werden zwar übersetzt, führen aber zu Verzerrungen.
|
| 515 |
-
</div>
|
| 516 |
-
"""
|
| 517 |
-
)
|
| 518 |
-
|
| 519 |
-
# --- Button zentriert im unteren Drittel, Taupe-Farbe ---
|
| 520 |
with gr.Row():
|
| 521 |
-
with gr.Column(scale=1):
|
| 522 |
pass
|
| 523 |
-
with gr.Column(scale=1, min_width=300):
|
| 524 |
-
start_btn = gr.Button(
|
| 525 |
-
|
| 526 |
-
variant="primary",
|
| 527 |
-
size="lg",
|
| 528 |
-
elem_id="start-button"
|
| 529 |
-
)
|
| 530 |
-
with gr.Column(scale=1): # Rechter Leerraum
|
| 531 |
pass
|
| 532 |
|
| 533 |
-
# --- Hauptanwendungsbereich
|
| 534 |
with gr.Column(visible=False) as content_area:
|
|
|
|
|
|
|
| 535 |
with gr.Tab("Text zu Bild"):
|
| 536 |
-
gr.Markdown("**Beschreibe dein gewünschtes Bild
|
| 537 |
|
| 538 |
with gr.Row():
|
| 539 |
txt_input = gr.Textbox(
|
| 540 |
-
placeholder="z.B. ultra realistic mountain landscape at sunrise
|
| 541 |
lines=2,
|
| 542 |
-
label="Prompt (Englisch)"
|
| 543 |
-
info="Beschreibe detailliert, was du sehen möchtest. Verwende Kommas zur Trennung."
|
| 544 |
)
|
| 545 |
|
| 546 |
with gr.Row():
|
| 547 |
with gr.Column():
|
| 548 |
txt_steps = gr.Slider(
|
| 549 |
minimum=10, maximum=100, value=35, step=1,
|
| 550 |
-
label="Inferenz-Schritte"
|
| 551 |
-
info="Mehr Schritte = bessere Qualität, aber langsamer (20-50 empfohlen)"
|
| 552 |
)
|
| 553 |
with gr.Column():
|
| 554 |
txt_guidance = gr.Slider(
|
| 555 |
minimum=1.0, maximum=20.0, value=7.5, step=0.5,
|
| 556 |
-
label="Prompt-Stärke"
|
| 557 |
-
info="Wie stark der Prompt befolgt wird (7-12 für gute Balance)"
|
| 558 |
)
|
| 559 |
|
| 560 |
generate_btn = gr.Button("Bild generieren", variant="primary")
|
|
@@ -564,121 +386,96 @@ def main_ui():
|
|
| 564 |
type="pil"
|
| 565 |
)
|
| 566 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 567 |
generate_btn.click(
|
| 568 |
fn=text_to_image,
|
| 569 |
inputs=[txt_input, txt_steps, txt_guidance],
|
| 570 |
-
outputs=txt_output,
|
| 571 |
concurrency_limit=1
|
| 572 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 573 |
|
|
|
|
| 574 |
with gr.Tab("Bild zu Bild"):
|
| 575 |
gr.Markdown("**Lade ein Bild hoch und beschreibe die gewünschte Veränderung:**")
|
| 576 |
|
| 577 |
-
# NEUE ANORDNUNG: Eingabebild und Live-Vorschau nebeneinander
|
| 578 |
with gr.Row():
|
| 579 |
with gr.Column():
|
| 580 |
img_input = gr.Image(
|
| 581 |
type="pil",
|
| 582 |
label="Eingabebild",
|
| 583 |
height=300,
|
| 584 |
-
sources=["upload"]
|
| 585 |
-
elem_id="image-upload"
|
| 586 |
)
|
| 587 |
with gr.Column():
|
| 588 |
preview_output = gr.Image(
|
| 589 |
-
label="Live-Vorschau mit Maske",
|
| 590 |
height=300,
|
| 591 |
-
interactive=
|
| 592 |
show_download_button=False
|
| 593 |
)
|
| 594 |
|
| 595 |
-
# DARUNTER: Checkbox Gesicht/Person oder Umgebung ändern
|
| 596 |
with gr.Row():
|
| 597 |
face_preserve = gr.Checkbox(
|
| 598 |
label="Schutz",
|
| 599 |
value=True,
|
| 600 |
-
info="🟢
|
| 601 |
)
|
| 602 |
|
| 603 |
-
# DARUNTER: Bildelementbereich anpassen
|
| 604 |
-
with gr.Row():
|
| 605 |
-
gr.Markdown("**Bildelementbereich anpassen**")
|
| 606 |
-
|
| 607 |
with gr.Row():
|
| 608 |
with gr.Column():
|
| 609 |
-
bbox_x1 = gr.Slider(
|
| 610 |
-
label="Links (x1)",
|
| 611 |
-
minimum=0, maximum=512, value=100, step=1,
|
| 612 |
-
info="Linke Kante des Bildelementbereichs"
|
| 613 |
-
)
|
| 614 |
with gr.Column():
|
| 615 |
-
bbox_y1 = gr.Slider(
|
| 616 |
-
label="Oben (y1)",
|
| 617 |
-
minimum=0, maximum=512, value=100, step=1,
|
| 618 |
-
info="Obere Kante des Bildelementbereichs"
|
| 619 |
-
)
|
| 620 |
with gr.Row():
|
| 621 |
with gr.Column():
|
| 622 |
-
bbox_x2 = gr.Slider(
|
| 623 |
-
label="Rechts (x2)",
|
| 624 |
-
minimum=0, maximum=512, value=300, step=1,
|
| 625 |
-
info="Rechte Kante des Bildelementbereichs"
|
| 626 |
-
)
|
| 627 |
with gr.Column():
|
| 628 |
-
bbox_y2 = gr.Slider(
|
| 629 |
-
label="Unten (y2)",
|
| 630 |
-
minimum=0, maximum=512, value=300, step=1,
|
| 631 |
-
info="Untere Kante des Bildelementbereichs"
|
| 632 |
-
)
|
| 633 |
|
| 634 |
-
# DARUNTER: Prompt und Negativ-Prompt
|
| 635 |
with gr.Row():
|
| 636 |
with gr.Column():
|
| 637 |
img_prompt = gr.Textbox(
|
| 638 |
-
placeholder="change background to beach with palm trees
|
| 639 |
lines=2,
|
| 640 |
-
label="Transformations-Prompt
|
| 641 |
-
info="Was soll verändert werden? Sei spezifisch."
|
| 642 |
)
|
| 643 |
with gr.Column():
|
| 644 |
img_neg_prompt = gr.Textbox(
|
| 645 |
-
placeholder="blurry, deformed, ugly
|
| 646 |
lines=2,
|
| 647 |
-
label="Negativ-Prompt
|
| 648 |
-
info="Was soll vermieden werden? Unerwünschte Elemente auflisten."
|
| 649 |
)
|
| 650 |
|
| 651 |
-
# DARUNTER: Veränderungsstärke, Inferenzschritte, Promptstärke
|
| 652 |
with gr.Row():
|
| 653 |
with gr.Column():
|
| 654 |
-
strength_slider = gr.Slider(
|
| 655 |
-
minimum=0.1, maximum=0.9, value=0.4, step=0.05,
|
| 656 |
-
label="Veränderungs-Stärke",
|
| 657 |
-
info="0.1-0.3: Leichte Anpassungen, 0.4-0.6: Mittlere Veränderungen, 0.7-0.9: Starke Umgestaltung"
|
| 658 |
-
)
|
| 659 |
with gr.Column():
|
| 660 |
-
img_steps = gr.Slider(
|
| 661 |
-
minimum=10, maximum=100, value=35, step=1,
|
| 662 |
-
label="Inferenz-Schritte",
|
| 663 |
-
info="Anzahl der Verarbeitungsschritte (25-45 für gute Ergebnisse)"
|
| 664 |
-
)
|
| 665 |
with gr.Column():
|
| 666 |
-
img_guidance = gr.Slider(
|
| 667 |
-
minimum=1.0, maximum=20.0, value=7.5, step=0.5,
|
| 668 |
-
label="Prompt-Stärke",
|
| 669 |
-
info="Einfluss des Prompts auf das Ergebnis (6-10 für natürliche Ergebnisse)"
|
| 670 |
-
)
|
| 671 |
-
|
| 672 |
-
with gr.Row():
|
| 673 |
-
gr.Markdown(
|
| 674 |
-
"**Achtung:**\n"
|
| 675 |
-
"• **🆕 Automatische Bildelementerkennung** setzt Koordinaten beim Upload\n"
|
| 676 |
-
"• **🆕 Live-Vorschau** zeigt farbige Rahmen je nach Modus (🔴 Rot / 🟢 Grün)\n"
|
| 677 |
-
"• **🆕 Koordinaten-Schieberegler** für präzise Anpassung mit Live-Update\n"
|
| 678 |
-
"• **Koordinaten nur bei erkennbaren Verzerrungen anpassen** (Bereiche leicht verschieben)"
|
| 679 |
-
)
|
| 680 |
|
| 681 |
-
|
| 682 |
transform_btn = gr.Button("Bild transformieren", variant="primary")
|
| 683 |
|
| 684 |
with gr.Row():
|
|
@@ -688,49 +485,36 @@ def main_ui():
|
|
| 688 |
type="pil"
|
| 689 |
)
|
| 690 |
|
| 691 |
-
#
|
| 692 |
-
|
|
|
|
|
|
|
| 693 |
img_input.change(
|
| 694 |
fn=process_image_upload,
|
| 695 |
inputs=[img_input],
|
| 696 |
outputs=[preview_output, bbox_x1, bbox_y1, bbox_x2, bbox_y2]
|
| 697 |
)
|
| 698 |
|
| 699 |
-
# Live-Updates bei Koordinaten-Änderungen
|
| 700 |
coordinate_inputs = [img_input, bbox_x1, bbox_y1, bbox_x2, bbox_y2, face_preserve]
|
| 701 |
|
| 702 |
-
bbox_x1
|
| 703 |
-
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
bbox_y1.change(
|
| 709 |
-
fn=update_live_preview,
|
| 710 |
-
inputs=coordinate_inputs,
|
| 711 |
-
outputs=preview_output
|
| 712 |
-
)
|
| 713 |
-
|
| 714 |
-
bbox_x2.change(
|
| 715 |
-
fn=update_live_preview,
|
| 716 |
-
inputs=coordinate_inputs,
|
| 717 |
-
outputs=preview_output
|
| 718 |
-
)
|
| 719 |
|
| 720 |
-
|
| 721 |
fn=update_live_preview,
|
| 722 |
inputs=coordinate_inputs,
|
| 723 |
outputs=preview_output
|
| 724 |
)
|
| 725 |
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
inputs=coordinate_inputs,
|
| 730 |
-
outputs=preview_output
|
| 731 |
)
|
| 732 |
|
| 733 |
-
# Transform-Button (UNVERÄNDERT - gibt OUTPUT zurück)
|
| 734 |
transform_btn.click(
|
| 735 |
fn=img_to_image,
|
| 736 |
inputs=[
|
|
@@ -741,14 +525,16 @@ def main_ui():
|
|
| 741 |
outputs=img_output,
|
| 742 |
concurrency_limit=1
|
| 743 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 744 |
|
| 745 |
-
#
|
| 746 |
-
info_components = []
|
| 747 |
-
|
| 748 |
-
if child != content_area:
|
| 749 |
-
info_components.append(child)
|
| 750 |
-
|
| 751 |
-
# Event-Handler für Start-Button
|
| 752 |
start_btn.click(
|
| 753 |
fn=lambda: gr.update(visible=True),
|
| 754 |
inputs=None,
|
|
@@ -761,7 +547,6 @@ def main_ui():
|
|
| 761 |
|
| 762 |
return demo
|
| 763 |
|
| 764 |
-
|
| 765 |
if __name__ == "__main__":
|
| 766 |
demo = main_ui()
|
| 767 |
demo.queue()
|
|
|
|
| 2 |
from diffusers import StableDiffusionPipeline, StableDiffusionImg2ImgPipeline
|
| 3 |
from diffusers import StableDiffusionInpaintPipeline
|
| 4 |
import torch
|
| 5 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 6 |
import time
|
| 7 |
import os
|
| 8 |
import tempfile
|
|
|
|
| 15 |
|
| 16 |
print(f"Running on: {device}")
|
| 17 |
|
| 18 |
+
# === TEXT INTEGRATION IMPORT ===
|
| 19 |
+
from text_integration import (
|
| 20 |
+
add_text_to_image,
|
| 21 |
+
set_text_position,
|
| 22 |
+
create_text_integration_section_t2i,
|
| 23 |
+
create_text_integration_section_i2i
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
# === GESICHTSMASKEN-FUNKTIONEN ===
|
| 27 |
def create_face_mask(image, bbox_coords, face_preserve):
|
| 28 |
"""Erzeugt eine Gesichtsmaske - WEIßE Bereiche werden VERÄNDERT, SCHWARZE BLEIBEN"""
|
| 29 |
+
mask = Image.new("L", image.size, 0)
|
| 30 |
|
| 31 |
if bbox_coords and all(coord is not None for coord in bbox_coords):
|
| 32 |
x1, y1, x2, y2 = bbox_coords
|
| 33 |
draw = ImageDraw.Draw(mask)
|
| 34 |
|
| 35 |
if face_preserve:
|
| 36 |
+
draw.rectangle([0, 0, image.size[0], image.size[1]], fill=255)
|
| 37 |
+
draw.rectangle([x1, y1, x2, y2], fill=0)
|
| 38 |
+
print("Gesicht wird GESCHÜTZT - Umgebung wird verändert")
|
|
|
|
| 39 |
else:
|
| 40 |
+
draw.rectangle([x1, y1, x2, y2], fill=255)
|
| 41 |
+
print("Nur Gesicht wird verändert - Umgebung bleibt erhalten")
|
|
|
|
| 42 |
|
| 43 |
return mask
|
| 44 |
|
| 45 |
def auto_detect_face_area(image):
|
| 46 |
"""Optimierten Vorschlag für Gesichtsbereich ohne externe Bibliotheken"""
|
| 47 |
width, height = image.size
|
|
|
|
| 48 |
face_size = min(width, height) * 0.4
|
|
|
|
| 49 |
x1 = (width - face_size) / 2
|
| 50 |
+
y1 = (height - face_size) / 4
|
| 51 |
x2 = x1 + face_size
|
| 52 |
+
y2 = y1 + face_size * 1.2
|
|
|
|
| 53 |
x1, y1 = max(0, int(x1)), max(0, int(y1))
|
| 54 |
x2, y2 = min(width, int(x2)), min(height, int(y2))
|
| 55 |
print(f"Geschätzte Gesichtskoordinaten: [{x1}, {y1}, {x2}, {y2}]")
|
|
|
|
| 69 |
use_safetensors=True,
|
| 70 |
safety_checker=None,
|
| 71 |
requires_safety_checker=False,
|
|
|
|
| 72 |
).to(device)
|
| 73 |
|
| 74 |
from diffusers import DPMSolverMultistepScheduler
|
|
|
|
| 83 |
try:
|
| 84 |
pipe_img2img = StableDiffusionInpaintPipeline.from_pretrained(
|
| 85 |
"runwayml/stable-diffusion-inpainting",
|
|
|
|
| 86 |
torch_dtype=torch_dtype,
|
| 87 |
+
allow_pickle=False,
|
|
|
|
| 88 |
safety_checker=None,
|
|
|
|
| 89 |
).to(device)
|
| 90 |
except Exception as e:
|
| 91 |
print(f"Fehler beim Laden des Modells: {e}")
|
| 92 |
raise
|
| 93 |
|
|
|
|
| 94 |
from diffusers import DPMSolverMultistepScheduler
|
| 95 |
pipe_img2img.scheduler = DPMSolverMultistepScheduler.from_config(
|
| 96 |
pipe_img2img.scheduler.config,
|
|
|
|
| 105 |
|
| 106 |
return pipe_img2img
|
| 107 |
|
| 108 |
+
# === CALLBACK-FUNKTIONEN ===
|
| 109 |
class TextToImageProgressCallback:
|
| 110 |
def __init__(self, progress, total_steps):
|
| 111 |
self.progress = progress
|
|
|
|
| 113 |
self.current_step = 0
|
| 114 |
|
| 115 |
def __call__(self, pipe, step, timestep, callback_kwargs):
|
|
|
|
| 116 |
self.current_step = step + 1
|
| 117 |
progress_percent = (step / self.total_steps) * 100
|
| 118 |
self.progress(progress_percent / 100, desc="Generierung läuft - CPU benötigt bis zu 20 Minuten!")
|
|
|
|
| 127 |
self.actual_total_steps = None
|
| 128 |
|
| 129 |
def __call__(self, pipe, step, timestep, callback_kwargs):
|
|
|
|
| 130 |
self.current_step = step + 1
|
| 131 |
|
|
|
|
| 132 |
if self.actual_total_steps is None:
|
|
|
|
| 133 |
if self.strength < 1.0:
|
| 134 |
self.actual_total_steps = int(self.total_steps * self.strength)
|
| 135 |
else:
|
|
|
|
| 141 |
self.progress(progress_percent / 100, desc="Generierung läuft - CPU benötigt bis zu 20 Minuten!")
|
| 142 |
return callback_kwargs
|
| 143 |
|
| 144 |
+
# === VORSCHAU-FUNKTIONEN ===
|
| 145 |
def create_preview_image(image, bbox_coords, face_preserve, mode_color):
|
| 146 |
"""Erstellt eine Vorschau mit farbigem Rahmen basierend auf dem Modus"""
|
| 147 |
if image is None:
|
| 148 |
return None
|
| 149 |
|
|
|
|
| 150 |
preview = image.copy()
|
| 151 |
draw = ImageDraw.Draw(preview)
|
| 152 |
|
|
|
|
| 153 |
if mode_color == "red":
|
| 154 |
+
border_color = (255, 0, 0, 180)
|
| 155 |
mode_text = "NUR BILDELEMENT VERÄNDERN"
|
| 156 |
else:
|
| 157 |
+
border_color = (0, 255, 0, 180)
|
| 158 |
mode_text = "BILDELEMENT BEIBEHALTEN"
|
| 159 |
|
|
|
|
| 160 |
border_width = 8
|
| 161 |
draw.rectangle([0, 0, preview.width-1, preview.height-1],
|
| 162 |
outline=border_color, width=border_width)
|
| 163 |
|
|
|
|
| 164 |
if bbox_coords and all(coord is not None for coord in bbox_coords):
|
| 165 |
x1, y1, x2, y2 = bbox_coords
|
| 166 |
|
| 167 |
+
box_color = (255, 255, 0, 200)
|
|
|
|
| 168 |
draw.rectangle([x1, y1, x2, y2], outline=box_color, width=3)
|
| 169 |
|
|
|
|
| 170 |
text_color = (255, 255, 255)
|
| 171 |
bg_color = (0, 0, 0, 160)
|
| 172 |
|
|
|
|
| 173 |
text_bbox = draw.textbbox((x1, y1 - 25), mode_text)
|
| 174 |
draw.rectangle([text_bbox[0]-5, text_bbox[1]-2, text_bbox[2]+5, text_bbox[3]+2],
|
| 175 |
fill=bg_color)
|
| 176 |
|
|
|
|
| 177 |
draw.text((x1, y1 - 25), mode_text, fill=text_color)
|
| 178 |
|
| 179 |
return preview
|
|
|
|
| 184 |
return None
|
| 185 |
|
| 186 |
bbox_coords = [bbox_x1, bbox_y1, bbox_x2, bbox_y2]
|
|
|
|
|
|
|
| 187 |
mode_color = "green" if face_preserve else "red"
|
| 188 |
|
| 189 |
return create_preview_image(image, bbox_coords, face_preserve, mode_color)
|
|
|
|
| 193 |
if image is None:
|
| 194 |
return None, None, None, None, None
|
| 195 |
|
|
|
|
| 196 |
bbox = auto_detect_face_area(image)
|
| 197 |
bbox_x1, bbox_y1, bbox_x2, bbox_y2 = bbox
|
|
|
|
|
|
|
| 198 |
preview = create_preview_image(image, bbox, True, "green")
|
| 199 |
|
| 200 |
return preview, bbox_x1, bbox_y1, bbox_x2, bbox_y2
|
| 201 |
|
| 202 |
+
# === HAUPTPROZESSE ===
|
| 203 |
def text_to_image(prompt, steps, guidance_scale, progress=gr.Progress()):
|
| 204 |
try:
|
| 205 |
if not prompt or not prompt.strip():
|
|
|
|
| 208 |
print(f"Starting generation for: {prompt}")
|
| 209 |
start_time = time.time()
|
| 210 |
|
|
|
|
| 211 |
progress(0, desc="Generierung läuft - CPU benötigt bis zu 20 Minuten!")
|
| 212 |
|
| 213 |
pipe = load_txt2img()
|
| 214 |
|
|
|
|
| 215 |
seed = random.randint(0, 2**32 - 1)
|
| 216 |
generator = torch.Generator(device=device).manual_seed(seed)
|
| 217 |
print(f"Using seed: {seed}")
|
| 218 |
|
|
|
|
| 219 |
callback = TextToImageProgressCallback(progress, steps)
|
| 220 |
|
| 221 |
image = pipe(
|
|
|
|
| 225 |
num_inference_steps=int(steps),
|
| 226 |
guidance_scale=guidance_scale,
|
| 227 |
generator=generator,
|
| 228 |
+
callback_on_step_end=callback,
|
| 229 |
+
callback_on_step_end_tensor_inputs=[],
|
| 230 |
).images[0]
|
| 231 |
|
| 232 |
end_time = time.time()
|
| 233 |
print(f"Bild generiert in {end_time - start_time:.2f} Sekunden")
|
| 234 |
|
|
|
|
| 235 |
return image
|
| 236 |
|
| 237 |
except Exception as e:
|
|
|
|
| 246 |
return None
|
| 247 |
|
| 248 |
print(f"Img2Img Start → Strength: {strength}, Steps: {steps}, Guidance: {guidance_scale}")
|
|
|
|
|
|
|
|
|
|
| 249 |
start_time = time.time()
|
| 250 |
|
|
|
|
| 251 |
progress(0, desc="Generierung läuft - CPU benötigt bis zu 20 Minuten!")
|
| 252 |
|
| 253 |
pipe = load_img2img()
|
| 254 |
img_resized = image.convert("RGB").resize((IMG_SIZE, IMG_SIZE))
|
| 255 |
|
| 256 |
+
adj_strength = min(0.85, strength * 1.3)
|
|
|
|
| 257 |
adj_guidance = min(guidance_scale, 12.0)
|
| 258 |
|
|
|
|
|
|
|
| 259 |
seed = random.randint(0, 2**32 - 1)
|
| 260 |
generator = torch.Generator(device=device).manual_seed(seed)
|
| 261 |
print(f"Using seed: {seed}")
|
| 262 |
|
|
|
|
| 263 |
mask = None
|
| 264 |
bbox_coords = None
|
| 265 |
|
| 266 |
if bbox_x1 is not None and bbox_y1 is not None and bbox_x2 is not None and bbox_y2 is not None:
|
|
|
|
| 267 |
orig_width, orig_height = image.size
|
| 268 |
scale_x = IMG_SIZE / orig_width
|
| 269 |
scale_y = IMG_SIZE / orig_height
|
|
|
|
| 275 |
int(bbox_y2 * scale_y)
|
| 276 |
]
|
| 277 |
bbox_coords = scaled_coords
|
|
|
|
| 278 |
|
|
|
|
| 279 |
if bbox_coords:
|
| 280 |
mask = create_face_mask(img_resized, bbox_coords, face_preserve)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
|
|
|
|
| 282 |
callback = ImageToImageProgressCallback(progress, int(steps), adj_strength)
|
| 283 |
|
|
|
|
| 284 |
result = pipe(
|
| 285 |
prompt=prompt,
|
| 286 |
negative_prompt=neg_prompt,
|
| 287 |
image=img_resized,
|
| 288 |
+
mask_image=mask,
|
| 289 |
strength=adj_strength,
|
| 290 |
num_inference_steps=int(steps),
|
| 291 |
guidance_scale=adj_guidance,
|
| 292 |
generator=generator,
|
| 293 |
+
callback_on_step_end=callback,
|
| 294 |
+
callback_on_step_end_tensor_inputs=[],
|
| 295 |
)
|
| 296 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
end_time = time.time()
|
| 298 |
print(f"Bild transformiert in {end_time - start_time:.2f} Sekunden")
|
| 299 |
|
|
|
|
| 307 |
traceback.print_exc()
|
| 308 |
return None
|
| 309 |
|
| 310 |
+
# === TEXT INTEGRATION HANDLER ===
|
| 311 |
+
def handle_text_integration_i2i(original_image, generated_image, text, text_x, text_y, target_selector):
|
| 312 |
+
"""Verwaltet Text-Integration für Bild-zu-Bild basierend auf Auswahl"""
|
| 313 |
+
if target_selector == "Originalbild":
|
| 314 |
+
target_image = original_image
|
| 315 |
+
output_component = original_image
|
| 316 |
+
else: # "Generiertes Bild"
|
| 317 |
+
target_image = generated_image
|
| 318 |
+
output_component = generated_image
|
| 319 |
|
| 320 |
+
result = add_text_to_image(target_image, text, text_x, text_y)
|
| 321 |
+
return result, output_component
|
| 322 |
|
| 323 |
def main_ui():
|
| 324 |
with gr.Blocks(
|
|
|
|
| 332 |
border-left: 4px solid #8B7355;
|
| 333 |
margin: 20px 0;
|
| 334 |
}
|
| 335 |
+
.text-integration-section {
|
| 336 |
+
background: #e8f5e8;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
padding: 15px;
|
| 338 |
border-radius: 8px;
|
| 339 |
+
margin: 15px 0;
|
| 340 |
+
border-left: 4px solid #4caf50;
|
| 341 |
}
|
| 342 |
"""
|
| 343 |
) as demo:
|
| 344 |
|
| 345 |
+
# --- Info-Bereich ---
|
| 346 |
+
gr.Markdown("# AI Image Generator")
|
| 347 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
with gr.Row():
|
| 349 |
+
with gr.Column(scale=1):
|
| 350 |
pass
|
| 351 |
+
with gr.Column(scale=1, min_width=300):
|
| 352 |
+
start_btn = gr.Button("Weiter zur Anwendung", variant="primary", size="lg")
|
| 353 |
+
with gr.Column(scale=1):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 354 |
pass
|
| 355 |
|
| 356 |
+
# --- Hauptanwendungsbereich ---
|
| 357 |
with gr.Column(visible=False) as content_area:
|
| 358 |
+
|
| 359 |
+
# === TAB: TEXT ZU BILD ===
|
| 360 |
with gr.Tab("Text zu Bild"):
|
| 361 |
+
gr.Markdown("**Beschreibe dein gewünschtes Bild:**")
|
| 362 |
|
| 363 |
with gr.Row():
|
| 364 |
txt_input = gr.Textbox(
|
| 365 |
+
placeholder="z.B. ultra realistic mountain landscape at sunrise...",
|
| 366 |
lines=2,
|
| 367 |
+
label="Prompt (Englisch)"
|
|
|
|
| 368 |
)
|
| 369 |
|
| 370 |
with gr.Row():
|
| 371 |
with gr.Column():
|
| 372 |
txt_steps = gr.Slider(
|
| 373 |
minimum=10, maximum=100, value=35, step=1,
|
| 374 |
+
label="Inferenz-Schritte"
|
|
|
|
| 375 |
)
|
| 376 |
with gr.Column():
|
| 377 |
txt_guidance = gr.Slider(
|
| 378 |
minimum=1.0, maximum=20.0, value=7.5, step=0.5,
|
| 379 |
+
label="Prompt-Stärke"
|
|
|
|
| 380 |
)
|
| 381 |
|
| 382 |
generate_btn = gr.Button("Bild generieren", variant="primary")
|
|
|
|
| 386 |
type="pil"
|
| 387 |
)
|
| 388 |
|
| 389 |
+
# TEXT INTEGRATION FÜR TEXT-zu-BILD
|
| 390 |
+
text_input_t2i, text_x_t2i, text_y_t2i, text_btn_t2i = create_text_integration_section_t2i()
|
| 391 |
+
|
| 392 |
+
# VORSCHAU FÜR TEXT POSITION
|
| 393 |
+
preview_t2i = gr.Image(
|
| 394 |
+
label="Vorschau für Textposition (Klicken/Tippen um Position zu wählen)",
|
| 395 |
+
interactive=True,
|
| 396 |
+
show_download_button=False,
|
| 397 |
+
type="pil"
|
| 398 |
+
)
|
| 399 |
+
|
| 400 |
+
# EVENT-HANDLER TEXT-zu-BILD
|
| 401 |
generate_btn.click(
|
| 402 |
fn=text_to_image,
|
| 403 |
inputs=[txt_input, txt_steps, txt_guidance],
|
| 404 |
+
outputs=[txt_output, preview_t2i],
|
| 405 |
concurrency_limit=1
|
| 406 |
)
|
| 407 |
+
|
| 408 |
+
preview_t2i.select(
|
| 409 |
+
fn=set_text_position,
|
| 410 |
+
outputs=[text_x_t2i, text_y_t2i]
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
text_btn_t2i.click(
|
| 414 |
+
fn=add_text_to_image,
|
| 415 |
+
inputs=[txt_output, text_input_t2i, text_x_t2i, text_y_t2i],
|
| 416 |
+
outputs=txt_output
|
| 417 |
+
)
|
| 418 |
|
| 419 |
+
# === TAB: BILD ZU BILD ===
|
| 420 |
with gr.Tab("Bild zu Bild"):
|
| 421 |
gr.Markdown("**Lade ein Bild hoch und beschreibe die gewünschte Veränderung:**")
|
| 422 |
|
|
|
|
| 423 |
with gr.Row():
|
| 424 |
with gr.Column():
|
| 425 |
img_input = gr.Image(
|
| 426 |
type="pil",
|
| 427 |
label="Eingabebild",
|
| 428 |
height=300,
|
| 429 |
+
sources=["upload"]
|
|
|
|
| 430 |
)
|
| 431 |
with gr.Column():
|
| 432 |
preview_output = gr.Image(
|
| 433 |
+
label="Live-Vorschau mit Maske (Klicken/Tippen für Textposition)",
|
| 434 |
height=300,
|
| 435 |
+
interactive=True,
|
| 436 |
show_download_button=False
|
| 437 |
)
|
| 438 |
|
|
|
|
| 439 |
with gr.Row():
|
| 440 |
face_preserve = gr.Checkbox(
|
| 441 |
label="Schutz",
|
| 442 |
value=True,
|
| 443 |
+
info="🟢 AN: Umgebung verändern | 🔴 AUS: Objekt verändern"
|
| 444 |
)
|
| 445 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 446 |
with gr.Row():
|
| 447 |
with gr.Column():
|
| 448 |
+
bbox_x1 = gr.Slider(label="Links (x1)", minimum=0, maximum=512, value=100, step=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 449 |
with gr.Column():
|
| 450 |
+
bbox_y1 = gr.Slider(label="Oben (y1)", minimum=0, maximum=512, value=100, step=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 451 |
with gr.Row():
|
| 452 |
with gr.Column():
|
| 453 |
+
bbox_x2 = gr.Slider(label="Rechts (x2)", minimum=0, maximum=512, value=300, step=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 454 |
with gr.Column():
|
| 455 |
+
bbox_y2 = gr.Slider(label="Unten (y2)", minimum=0, maximum=512, value=300, step=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 456 |
|
|
|
|
| 457 |
with gr.Row():
|
| 458 |
with gr.Column():
|
| 459 |
img_prompt = gr.Textbox(
|
| 460 |
+
placeholder="change background to beach with palm trees...",
|
| 461 |
lines=2,
|
| 462 |
+
label="Transformations-Prompt"
|
|
|
|
| 463 |
)
|
| 464 |
with gr.Column():
|
| 465 |
img_neg_prompt = gr.Textbox(
|
| 466 |
+
placeholder="blurry, deformed, ugly...",
|
| 467 |
lines=2,
|
| 468 |
+
label="Negativ-Prompt"
|
|
|
|
| 469 |
)
|
| 470 |
|
|
|
|
| 471 |
with gr.Row():
|
| 472 |
with gr.Column():
|
| 473 |
+
strength_slider = gr.Slider(minimum=0.1, maximum=0.9, value=0.4, step=0.05, label="Veränderungs-Stärke")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 474 |
with gr.Column():
|
| 475 |
+
img_steps = gr.Slider(minimum=10, maximum=100, value=35, step=1, label="Inferenz-Schritte")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 476 |
with gr.Column():
|
| 477 |
+
img_guidance = gr.Slider(minimum=1.0, maximum=20.0, value=7.5, step=0.5, label="Prompt-Stärke")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 478 |
|
|
|
|
| 479 |
transform_btn = gr.Button("Bild transformieren", variant="primary")
|
| 480 |
|
| 481 |
with gr.Row():
|
|
|
|
| 485 |
type="pil"
|
| 486 |
)
|
| 487 |
|
| 488 |
+
# TEXT INTEGRATION FÜR BILD-zu-BILD
|
| 489 |
+
text_input_i2i, text_x_i2i, text_y_i2i, target_selector, text_btn_i2i = create_text_integration_section_i2i()
|
| 490 |
+
|
| 491 |
+
# EVENT-HANDLER BILD-zu-BILD
|
| 492 |
img_input.change(
|
| 493 |
fn=process_image_upload,
|
| 494 |
inputs=[img_input],
|
| 495 |
outputs=[preview_output, bbox_x1, bbox_y1, bbox_x2, bbox_y2]
|
| 496 |
)
|
| 497 |
|
|
|
|
| 498 |
coordinate_inputs = [img_input, bbox_x1, bbox_y1, bbox_x2, bbox_y2, face_preserve]
|
| 499 |
|
| 500 |
+
for coord in [bbox_x1, bbox_y1, bbox_x2, bbox_y2]:
|
| 501 |
+
coord.change(
|
| 502 |
+
fn=update_live_preview,
|
| 503 |
+
inputs=coordinate_inputs,
|
| 504 |
+
outputs=preview_output
|
| 505 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 506 |
|
| 507 |
+
face_preserve.change(
|
| 508 |
fn=update_live_preview,
|
| 509 |
inputs=coordinate_inputs,
|
| 510 |
outputs=preview_output
|
| 511 |
)
|
| 512 |
|
| 513 |
+
preview_output.select(
|
| 514 |
+
fn=set_text_position,
|
| 515 |
+
outputs=[text_x_i2i, text_y_i2i]
|
|
|
|
|
|
|
| 516 |
)
|
| 517 |
|
|
|
|
| 518 |
transform_btn.click(
|
| 519 |
fn=img_to_image,
|
| 520 |
inputs=[
|
|
|
|
| 525 |
outputs=img_output,
|
| 526 |
concurrency_limit=1
|
| 527 |
)
|
| 528 |
+
|
| 529 |
+
text_btn_i2i.click(
|
| 530 |
+
fn=handle_text_integration_i2i,
|
| 531 |
+
inputs=[img_input, img_output, text_input_i2i, text_x_i2i, text_y_i2i, target_selector],
|
| 532 |
+
outputs=[img_input, img_output]
|
| 533 |
+
)
|
| 534 |
|
| 535 |
+
# === START-BUTTON HANDLER ===
|
| 536 |
+
info_components = [child for child in demo.children if child != content_area]
|
| 537 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 538 |
start_btn.click(
|
| 539 |
fn=lambda: gr.update(visible=True),
|
| 540 |
inputs=None,
|
|
|
|
| 547 |
|
| 548 |
return demo
|
| 549 |
|
|
|
|
| 550 |
if __name__ == "__main__":
|
| 551 |
demo = main_ui()
|
| 552 |
demo.queue()
|