import gradio as gr
from diffusers import StableDiffusionPipeline, StableDiffusionImg2ImgPipeline
from diffusers import StableDiffusionInpaintPipeline
import torch
from PIL import Image, ImageDraw, ImageFont
import time
import os
import tempfile
import random
import re # Für reguläre Ausdrücke zur Gewichtserkennung
#Der Code ist perfekt für 512x512. Keine Verarbeitung großer Bilder, keine variablen Slider!
# === AUTOMATISCHE NEGATIVE PROMPT GENERIERUNG ===
def auto_negative_prompt(positive_prompt):
"""Generiert automatisch negative Prompts basierend auf dem positiven Prompt"""
p = positive_prompt.lower()
negatives = []
# Personen / Portraits
if any(w in p for w in [
"person", "man", "woman", "face", "portrait", "team", "employee",
"people", "crowd", "character", "figure", "human", "child", "baby",
"girl", "boy", "lady", "gentleman", "fairy", "elf", "dwarf", "santa claus",
"mermaid", "angel", "demon", "witch", "wizard", "creature", "being",
"model", "actor", "actress", "celebrity", "avatar"]):
negatives.append(
"blurry face, lowres face, deformed pupils, bad anatomy, malformed hands, extra fingers, uneven eyes, distorted face, "
"unrealistic skin, mutated, deformed, ugly, disfigured, poorly drawn face, "
"missing limbs, extra limbs, fused fingers, too many fingers, bad teeth, "
"mutated hands, long neck, extra wings, multiple wings, grainy face, noisy face, "
"compression artifacts, rendering artifacts, digital artifacts, overprocessed face, oversmoothed face "
)
# Business / Corporate
if any(w in p for w in ["office", "business", "team", "meeting", "corporate", "company", "workplace"]):
negatives.append(
"overexposed, oversaturated, harsh lighting, watermark, text, logo, amateur photo, lens flare, chromatic aberration, brand"
)
# Produkt / CGI
if any(w in p for w in ["product", "packshot", "mockup", "render", "3d", "cgi", "packaging"]):
negatives.append(
"plastic texture, noisy, overly reflective surfaces, watermark, text, render artifacts, unrealistic shadows, 3d model artifacts, low poly"
)
# Landschaft / Umgebung
if any(w in p for w in ["landscape", "nature", "mountain", "forest", "outdoor", "beach", "sky"]):
negatives.append(
"blurry, oversaturated, unnatural colors, distorted horizon, repeating patterns, plastic grass, unrealistic water, floating objects"
)
# Logos / Symbole
if any(w in p for w in ["logo", "symbol", "icon", "typography", "badge", "emblem"]):
negatives.append(
"watermark, signature, username, text, writing, scribble, pixelated, distorted shapes, misaligned elements, messy"
)
# Architektur / Gebäude
if any(w in p for w in ["building", "architecture", "house", "interior", "room", "facade"]):
negatives.append(
"deformed, distorted perspective, floating objects, unrealistic materials, leaning building, warped surfaces, collapsing structure"
)
# Kunst / Stil (NEUE KATEGORIE)
if any(w in p for w in ["art", "painting", "drawing", "illustration", "sketch", "artwork", "creative", "style"]):
negatives.append(
"3d render, cgi, cartoon, anime, painting, drawing, sketch, plastic look, digital painting, unrealistic"
)
# Basis negative Prompts für alle Fälle
base_negatives = "low quality, worst quality, blurry, jpeg artifacts, ugly, deformed"
if negatives:
result = base_negatives + ", " + ", ".join(negatives)
else:
result = base_negatives
print(f"🔍 Automatischer Negativ-Prompt generiert: {result[:100]}...")
return result
# === OPTIMIERTE EINSTELLUNGEN ===
device = "cuda" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if device == "cuda" else torch.float32
IMG_SIZE = 512
print(f"Running on: {device}")
# === AUDIO-URL ===
AUDIO_URL = "https://dn721801.ca.archive.org/0/items/emotional-soft-piano-music-413513-2/emotional-soft-piano-music-413513%202.mp3"
# === TEXT INTEGRATION IMPORT ===
from text_integration import (
add_text_to_image,
create_text_integration_section_t2i,
create_text_integration_section_i2i,
capture_click,
update_text_preview_i2i,
update_text_preview_t2i
)
# === GESICHTSMASKEN-FUNKTIONEN ===
def create_face_mask(image, bbox_coords, face_preserve):
"""Erzeugt eine Gesichtsmaske - WEIßE Bereiche werden VERÄNDERT, SCHWARZE BLEIBEN"""
mask = Image.new("L", image.size, 0)
if bbox_coords and all(coord is not None for coord in bbox_coords):
x1, y1, x2, y2 = bbox_coords
draw = ImageDraw.Draw(mask)
if face_preserve:
draw.rectangle([0, 0, image.size[0], image.size[1]], fill=255)
draw.rectangle([x1, y1, x2, y2], fill=0)
print("Gesicht wird GESCHÜTZT - Umgebung wird verändert")
else:
draw.rectangle([x1, y1, x2, y2], fill=255)
print("Nur Gesicht wird verändert - Umgebung bleibt erhalten")
return mask
def auto_detect_face_area(image):
"""Optimierten Vorschlag für Gesichtsbereich ohne externe Bibliotheken"""
width, height = image.size
face_size = min(width, height) * 0.4
x1 = (width - face_size) / 2
y1 = (height - face_size) / 4
x2 = x1 + face_size
y2 = y1 + face_size * 1.2
x1, y1 = max(0, int(x1)), max(0, int(y1))
x2, y2 = min(width, int(x2)), min(height, int(y2))
print(f"Geschätzte Gesichtskoordinaten: [{x1}, {y1}, {x2}, {y2}]")
return [x1, y1, x2, y2]
# === PIPELINES ===
pipe_txt2img = None
pipe_img2img = None
def load_txt2img():
global pipe_txt2img
if pipe_txt2img is None:
print("Loading Text-to-Image model...")
pipe_txt2img = StableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
torch_dtype=torch_dtype,
use_safetensors=True,
safety_checker=None,
requires_safety_checker=False,
).to(device)
from diffusers import DPMSolverMultistepScheduler
pipe_txt2img.scheduler = DPMSolverMultistepScheduler.from_config(pipe_txt2img.scheduler.config)
pipe_txt2img.enable_attention_slicing()
return pipe_txt2img
def load_img2img():
global pipe_img2img
if pipe_img2img is None:
print("Loading Inpainting model...")
try:
pipe_img2img = StableDiffusionInpaintPipeline.from_pretrained(
"runwayml/stable-diffusion-inpainting",
torch_dtype=torch_dtype,
allow_pickle=False,
safety_checker=None,
).to(device)
except Exception as e:
print(f"Fehler beim Laden des Modells: {e}")
raise
from diffusers import DPMSolverMultistepScheduler
pipe_img2img.scheduler = DPMSolverMultistepScheduler.from_config(
pipe_img2img.scheduler.config,
algorithm_type="sde-dpmsolver++",
use_karras_sigmas=True,
timestep_spacing="trailing"
)
pipe_img2img.enable_attention_slicing()
pipe_img2img.enable_vae_tiling()
pipe_img2img.vae_slicing = True
return pipe_img2img
# === CALLBACK-FUNKTIONEN ===
class TextToImageProgressCallback:
def __init__(self, progress, total_steps):
self.progress = progress
self.total_steps = total_steps
self.current_step = 0
def __call__(self, pipe, step, timestep, callback_kwargs):
self.current_step = step + 1
progress_percent = (step / self.total_steps) * 100
self.progress(progress_percent / 100, desc="Generierung läuft - CPU benötigt bis zu 10 Minuten!")
return callback_kwargs
class ImageToImageProgressCallback:
def __init__(self, progress, total_steps, strength):
self.progress = progress
self.total_steps = total_steps
self.current_step = 0
self.strength = strength
self.actual_total_steps = None
def __call__(self, pipe, step, timestep, callback_kwargs):
self.current_step = step + 1
if self.actual_total_steps is None:
if self.strength < 1.0:
self.actual_total_steps = int(self.total_steps * self.strength)
else:
self.actual_total_steps = self.total_steps
print(f"🎯 INTERNE STEP-AUSGABE: Strength {self.strength} → {self.actual_total_steps} tatsächliche Denoising-Schritte")
progress_percent = (step / self.actual_total_steps) * 100
self.progress(progress_percent / 100, desc="Generierung läuft - CPU benötigt bis zu 10 Minuten!")
return callback_kwargs
# === VORSCHAU-FUNKTIONEN ===
def create_preview_image(image, bbox_coords, face_preserve, mode_color):
"""Erstellt eine Vorschau mit farbigem Rahmen basierend auf dem Modus"""
if image is None:
return None
preview = image.copy()
draw = ImageDraw.Draw(preview)
if mode_color == "red":
border_color = (255, 0, 0, 180)
mode_text = "NUR BILDELEMENT VERÄNDERN"
else:
border_color = (0, 255, 0, 180)
mode_text = "BILDELEMENT BEIBEHALTEN"
border_width = 8
draw.rectangle([0, 0, preview.width-1, preview.height-1],
outline=border_color, width=border_width)
if bbox_coords and all(coord is not None for coord in bbox_coords):
x1, y1, x2, y2 = bbox_coords
box_color = (255, 255, 0, 200)
draw.rectangle([x1, y1, x2, y2], outline=box_color, width=3)
text_color = (255, 255, 255)
bg_color = (0, 0, 0, 160)
text_bbox = draw.textbbox((x1, y1 - 25), mode_text)
draw.rectangle([text_bbox[0]-5, text_bbox[1]-2, text_bbox[2]+5, text_bbox[3]+2],
fill=bg_color)
draw.text((x1, y1 - 25), mode_text, fill=text_color)
return preview
def update_live_preview(image, bbox_x1, bbox_y1, bbox_x2, bbox_y2, face_preserve):
"""Aktualisiert die Live-Vorschau bei Koordinaten-Änderungen"""
if image is None:
return None
bbox_coords = [bbox_x1, bbox_y1, bbox_x2, bbox_y2]
mode_color = "green" if face_preserve else "red"
return create_preview_image(image, bbox_coords, face_preserve, mode_color)
# === AUDIO-FUNKTION ===
def play_audio_on_image_click():
"""Startet die Musikwiedergabe bei Klick auf das Bild"""
print("🎵 Musikwiedergabe wird gestartet...")
return gr.Audio(AUDIO_URL, autoplay=True, visible=True, label="Hintergrundmusik")
# === NEUE FUNKTION: STOP AUDIO BEIM TAB-WECHSEL ===
def stop_audio_on_tab_change():
"""Stoppt die Musik beim Tab-Wechsel"""
print("🔇 Musik wird beim Tab-Wechsel gestoppt")
return None
def process_image_upload(image):
"""Verarbeitet Bild-Upload und gibt Bild + Koordinaten zurück"""
if image is None:
return None, None, None, None, None
width, height = image.size
if width > 512 or height > 512:
# Große Bilder: Keine bbox benötigt, nur Vorschau
preview = create_preview_image(image, None, True, "green") #create_preview_image Funktion erstellt nur die visuelle Vorschau
return preview, None, None, None, None
else:
# Kleine Bilder: bbox wie gehabt berechnen
bbox = auto_detect_face_area(image)
bbox_x1, bbox_y1, bbox_x2, bbox_y2 = bbox
preview = create_preview_image(image, bbox, True, "green")
return preview, bbox_x1, bbox_y1, bbox_x2, bbox_y2
# === HAUPTPROZESSE ===
def text_to_image(prompt, steps, guidance_scale, progress=gr.Progress()):
try:
if not prompt or not prompt.strip():
return None, None
print(f"Starting generation for: {prompt}")
start_time = time.time()
# Liste von Qualitätswörtern/Gewichten, die auf Benutzereingaben prüfen
quality_keywords = ['masterpiece', 'best quality', 'high quality', 'highly detailed',
'exquisite', 'detailed', 'ultra detailed', 'professional',
'perfect', 'excellent', 'amazing', 'stunning', 'beautiful']
# Prüfe, ob der Benutzer bereits Qualitätswörter/Gewichte verwendet hat
user_has_quality_words = False
# Konvertiere Prompt zu Kleinbuchstaben für die Prüfung
prompt_lower = prompt.lower()
# Prüfe auf einfache Qualitätswörter
for keyword in quality_keywords:
if keyword in prompt_lower:
user_has_quality_words = True
print(f"✓ Benutzer verwendet bereits Qualitätswort: {keyword}")
break
# Prüfe auf Gewichte (z.B. (word:1.5), [word], etc.)
weight_patterns = [r'\([^)]+:\d+(\.\d+)?\)', r'\[[^\]]+\]']
for pattern in weight_patterns:
if re.search(pattern, prompt):
user_has_quality_words = True
print("✓ Benutzer verwendet bereits Gewichte im Prompt")
break
# Prompt basierend auf Prüfung anpassen
if not user_has_quality_words:
enhanced_prompt = f"masterpiece, raw, best quality, highly detailed, {prompt}"
print(f"🔄 Verbesserter Prompt: {enhanced_prompt}")
else:
enhanced_prompt = prompt
print("✓ Benutzerprompt wird unverändert verwendet")
print(f"Finaler Prompt für Generation: {enhanced_prompt}")
progress(0, desc="Generierung läuft - CPU benötigt bis zu 10 Minuten!")
pipe = load_txt2img()
# Automatischen Negativ-Prompt generieren
neg_prompt = auto_negative_prompt(prompt)
print(f"🔍 Verwendeter Negativ-Prompt: {neg_prompt}")
seed = random.randint(0, 2**32 - 1)
generator = torch.Generator(device=device).manual_seed(seed)
print(f"Using seed: {seed}")
callback = TextToImageProgressCallback(progress, steps)
image = pipe(
prompt=enhanced_prompt,
negative_prompt=neg_prompt, # Automatischen Negativ-Prompt verwenden
height=IMG_SIZE,
width=IMG_SIZE,
num_inference_steps=int(steps),
guidance_scale=guidance_scale,
generator=generator,
callback_on_step_end=callback,
callback_on_step_end_tensor_inputs=[],
).images[0]
end_time = time.time()
print(f"Bild generiert in {end_time - start_time:.2f} Sekunden")
return image, image
except Exception as e:
print(f"Fehler: {e}")
import traceback
traceback.print_exc()
return None, None
def img_to_image(image, prompt, neg_prompt, strength, steps, guidance_scale, face_preserve, bbox_x1, bbox_y1, bbox_x2, bbox_y2, progress=gr.Progress()):
try:
if image is None:
return None
print(f"Img2Img Start → Strength: {strength}, Steps: {steps}, Guidance: {guidance_scale}")
start_time = time.time()
# ===== NEU: AUTOMATISCHEN NEGATIV-PROMPT GENERIEREN =====
auto_negatives = auto_negative_prompt(prompt)
print(f"🤖 Automatisch generierter Negativ-Prompt: {auto_negatives}")
# ===== NEU: KOMBINIERE MANUELLEN UND AUTOMATISCHEN PROMPT =====
combined_negative_prompt = ""
if neg_prompt and neg_prompt.strip():
# Benutzer hat einen Negativ-Prompt eingegeben
user_neg = neg_prompt.strip()
print(f"👤 Benutzer Negativ-Prompt: {user_neg}")
# Entferne Duplikate zwischen automatischen und manuellen Prompts
# Konvertiere beide in Sets für einfachen Duplikatvergleich
user_words = [word.strip().lower() for word in user_neg.split(",")]
auto_words = [word.strip().lower() for word in auto_negatives.split(",")]
# Starte mit dem Benutzer-Prompt
combined_words = user_words.copy()
# Füge automatische Wörter hinzu, die nicht bereits vorhanden sind
for auto_word in auto_words:
if auto_word and auto_word not in user_words:
combined_words.append(auto_word)
# Zusammenfügen und Duplikate entfernen (für den Fall von Duplikaten innerhalb des gleichen Prompts)
unique_words = []
seen_words = set()
for word in combined_words:
if word and word not in seen_words:
unique_words.append(word)
seen_words.add(word)
combined_negative_prompt = ", ".join(unique_words)
else:
# Kein Benutzer-Prompt, verwende nur den automatischen
combined_negative_prompt = auto_negatives
print(f"ℹ️ Kein manueller Negativ-Prompt, verwende nur automatischen: {combined_negative_prompt}")
print(f"✅ Finaler kombinierter Negativ-Prompt: {combined_negative_prompt}")
# ===== ENDE DER NEUEN LOGIK =====
progress(0, desc="Generierung läuft - CPU benötigt bis zu 10 Minuten!")
pipe = load_img2img()
img_resized = image.convert("RGB").resize((IMG_SIZE, IMG_SIZE))
adj_strength = min(0.85, strength * 1.3)
adj_guidance = min(guidance_scale, 12.0)
seed = random.randint(0, 2**32 - 1)
generator = torch.Generator(device=device).manual_seed(seed)
print(f"Using seed: {seed}")
mask = None
bbox_coords = None
if bbox_x1 is not None and bbox_y1 is not None and bbox_x2 is not None and bbox_y2 is not None:
orig_width, orig_height = image.size
scale_x = IMG_SIZE / orig_width
scale_y = IMG_SIZE / orig_height
scaled_coords = [
int(bbox_x1 * scale_x),
int(bbox_y1 * scale_y),
int(bbox_x2 * scale_x),
int(bbox_y2 * scale_y)
]
bbox_coords = scaled_coords
if bbox_coords:
mask = create_face_mask(img_resized, bbox_coords, face_preserve)
callback = ImageToImageProgressCallback(progress, int(steps), adj_strength)
result = pipe(
prompt=prompt,
negative_prompt=combined_negative_prompt,
image=img_resized,
mask_image=mask,
strength=adj_strength,
num_inference_steps=int(steps),
guidance_scale=adj_guidance,
generator=generator,
callback_on_step_end=callback,
callback_on_step_end_tensor_inputs=[],
)
end_time = time.time()
print(f"Bild transformiert in {end_time - start_time:.2f} Sekunden")
generated_image = result.images[0]
return generated_image
except Exception as e:
print(f"Fehler: {e}")
import traceback
traceback.print_exc()
return None
# === TEXT INTEGRATION HANDLER ===
def handle_text_integration_i2i(original_image, generated_image, text, text_x, text_y, font_size, font_family, font_color, target_selector):
"""Verwaltet Text-Integration für Bild-zu-Bild basierend auf Auswahl"""
if target_selector == "Originalbild":
target_image = original_image
else: # "Generiertes Bild"
target_image = generated_image
result = add_text_to_image(target_image, text, text_x, text_y, font_size, font_family, font_color)
# Rückgabe: Original bleibt unverändert, Text-Bild kommt in Download-Bereich
return original_image, result
def handle_text_integration_t2i(generated_image, text, text_x, text_y, font_size, font_family, font_color):
"""Verwaltet Text-Integration für Text-zu-Bild"""
result = add_text_to_image(generated_image, text, text_x, text_y, font_size, font_family, font_color)
return result
def main_ui():
with gr.Blocks(
title="AI Image Generator",
theme=gr.themes.Base(),
css="""
.info-box {
background-color: #f8f4f0;
padding: 15px;
border-radius: 8px;
border-left: 4px solid #8B7355;
margin: 20px 0;
}
.text-integration-section {
background: #e8f5e8;
padding: 15px;
border-radius: 8px;
margin: 15px 0;
border-left: 4px solid #4caf50;
}
.clickable-file {
color: #8B7355;
text-decoration: underline;
font-weight: bold;
}
.clickable-file:hover {
color: #6b5a45;
}
/* === CSS SCROLL-LÖSUNG === */
.tab-nav {
scroll-margin-top: 0 !important;
}
[data-testid="tab-text-zu-bild"] {
scroll-margin-top: 0 !important;
}
.tab-button {
scroll-margin-top: 0 !important;
}
.gr-tab-item {
scroll-margin-top: 0 !important;
}
.gr-block {
scroll-margin-top: 0 !important;
}
.gr-column {
scroll-margin-top: 0 !important;
scroll-padding-top: 0 !important;
}
"""
) as demo:
# --- Info-Bereich (Startseite) ---
gr.Markdown(
"""
# Demo-Projekt: Stable Diffusion Text-to-Image / Image-to-Image