DEFAULT_NEGATIVE = (
"low quality, blurry, bad anatomy, extra limbs, watermark, text, distorted proportions, unnatural colors, "
"heavy noise, pixelated, overexposed, inconsistent lighting, lack of detail, warped perspective, "
"unrealistic expressions, compression artifacts, harsh shadows, cluttered composition, exaggerated features, "
"unwanted text overlays, poor depth of field"
)
Pipeline-Instanz und Modellzustand global verwalten
pipe = None
current_model = None
def load_model(model_name, enable_attention_slicing=True):
"""
Lädt das angegebene Modell (oder Fallback) und gibt eine initialisierte Pipeline zurück.
"""
global token
model_repo_id = MODEL_MAP.get(model_name, MODEL_MAP["Stable Diffusion 1.5"])
print(f"Lade Modell: {model_name} => {model_repo_id} auf {device} mit dtype={torch_dtype}")
if token:
print("Token vorhanden, wird automatisch für den API-Zugriff genutzt.")
else:
print("Kein HF-Token gefunden, nur öffentlich zugängliche Modelle verfügbar.")
try:
pipeline = DiffusionPipeline.from_pretrained(
model_repo_id,
torch_dtype=torch_dtype,
)
pipeline = pipeline.to(device)
if enable_attention_slicing:
pipeline.enable_attention_slicing()
return pipeline
except (RepositoryNotFoundError, GatedRepoError) as e:
print(f"Fehler beim Laden von {model_repo_id}: {e}")
fallback_id = MODEL_MAP["00-Fallback Stable Diffusion 1.5"] # ---------- Fallback
print(f"Wechsel auf öffentliches Modell: {fallback_id}")
pipeline = DiffusionPipeline.from_pretrained(
fallback_id,
torch_dtype=torch_dtype,
)
pipeline = pipeline.to(device)
if enable_attention_slicing:
pipeline.enable_attention_slicing()
return pipeline
def infer(
model_name,
prompt,
positive_prompts,
negative_prompts,
base_seed,
randomize_seed,
width,
height,
guidance_scale,
num_inference_steps,
num_images,
enable_attention_slicing,
progress=gr.Progress(track_tqdm=True),
):
"""
Führt die Inferenz (erlerntes Wissen) durch und erstellt Bilder auf Basis der Eingaben.
"""
global pipe, current_model
code
# Konvertiere Parameter in erwartete Typen
num_images = int(num_images)
base_seed = int(base_seed) if base_seed is not None else 0
width = int(width)
height = int(height)
num_inference_steps = int(num_inference_steps)
guidance_scale = float(guidance_scale)
randomize_seed = bool(randomize_seed)
enable_attention_slicing = bool(enable_attention_slicing)
# Modell bei Bedarf neu laden
if current_model != model_name or pipe is None:
pipe = load_model(model_name, enable_attention_slicing)
current_model = model_name
# Prompt-Strings kombinieren
full_prompt = prompt.strip()
if positive_prompts:
full_prompt += " " + positive_prompts.strip()
full_negative = negative_prompts.strip() if negative_prompts else ""
images = []
def progress_callback(pipeline, step: int, timestep: int, latents):
progress((step + 1) / num_inference_steps)
return {}
for i in range(num_images):
# Seed berechnen – Zufallsseed oder aufsteigend ab Basiswert
if randomize_seed:
seed = random.randint(0, np.iinfo(np.int32).max)
else:
seed = base_seed + i
generator = torch.Generator(device=device).manual_seed(seed)
# Inferenz durchführen
imgs = pipe(
prompt=full_prompt,
negative_prompt=full_negative,
width=width,
height=height,
guidance_scale=guidance_scale,
num_inference_steps=num_inference_steps,
generator=generator,
callback_on_step_end=progress_callback,
).images
images.extend(imgs)
return images
def reset_inputs():
"""
Setzt alle Eingaben zurück auf Standardwerte.
"""
return (
"FLUX.1-schnell",
"",
DEFAULT_POSITIVE,
DEFAULT_NEGATIVE,
1,
True,
512,
512,
0.6,
5,
"1",
True,
)
with gr.Blocks(css=css, theme=gr.themes.Default(spacing_size="sm")) as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown("# 🤠 AI-Bildgenerator (mit automatischem Modell-Fallback)")
gr.Markdown(
"""
Achtung: Falls ein Modell gated* ist und keinen Zugriff erlaubt, wird
automatisch das öffentliche Stable Diffusion 1.5 Modell verwendet.
"""
)
code
with gr.Row():
with gr.Column(scale=3, elem_id="left-col"):
model_dropdown = gr.Dropdown(
label="Modell",
choices=list(MODEL_MAP.keys()),
value="09-Deliberate-V2", # ---------- jetzt Standard
interactive=True,
info="Gated-Modelle benötigen ggf. einen Token und eine Freischaltung!"
)
prompt = gr.Textbox(
label="Hauptprompt",
lines=5,
max_lines=10,
interactive=True,
placeholder="Beschreibe das gewünschte Bild ..."
)
positive_prompt = gr.Textbox(
label="Positiv-Prompts (durch Kommas getrennt)",
lines=5,
max_lines=10,
interactive=True,
value=DEFAULT_POSITIVE
)
negative_prompt = gr.Textbox(
label="Negativ-Prompts (durch Kommas getrennt)",
lines=5,
max_lines=10,
interactive=True,
value=DEFAULT_NEGATIVE
)
with gr.Accordion("Erweiterte Einstellungen", open=True):
with gr.Row():
seed_slider = gr.Slider(0, 2147483647, label="Seed", value=1, step=1)
randomize_seed_checkbox = gr.Checkbox(label="Zufälligen Seed", value=True)
with gr.Row():
width = gr.Slider(256, 1024, value=512, step=64, label="Breite (max. 512 empfohlen)")
height = gr.Slider(256, 1024, value=512, step=64, label="Höhe (max. 512 empfohlen)")
with gr.Row():
guidance_scale = gr.Slider(0.0, 20.0, value=0.6, step=0.1, label="Guidance Scale")
num_inference_steps = gr.Slider(1, 30, value=5, step=1, label="Inferenzschritte")
with gr.Row():
attention_slicing_checkbox = gr.Checkbox(
label="Speicheroptimierung (Attention Slicing) aktivieren", value=True
)
num_images = gr.Dropdown(
label="Anzahl Bilder",
choices=[str(i) for i in range(1, 5)],
value="1",
interactive=True
)
# Button-Zeile: Bild generieren | Zurücksetzen | Darkmode
with gr.Row():
generate_btn = gr.Button("Bild generieren", elem_id="generate-btn", variant="primary")
reset_btn = gr.Button("Zurücksetzen", elem_id="reset-btn")
theme_toggle_btn = gr.Button("Darkmode", elem_id="theme-toggle-btn", variant="secondary")
gr.Markdown(
"""
**Hinweise:**
- *Guidance* bestimmt, wie strikt sich das Modell an den Prompt hält.
- *Inference* nutzt erlerntes Wissen, um Bilder zu generieren.
- Gated-Modelle benötigen Token und Freigabe.
- Für schwächere Hardware max. **512×512 Pixel** empfohlen.
- **Info:** Größere Auflösungen (z.B. 1024×1024 Pixel) benötigen **deutlich mehr Rechenleistung**!
"""
)
with gr.Column(scale=2, elem_id="right-col"):
output_gallery = gr.Gallery(
label="Ergebnisse",
show_label=False,
elem_id="output-gallery",
type="pil"
)
# Button-Events
generate_btn.click(
fn=infer,
inputs=[
model_dropdown,
prompt,
positive_prompt,
negative_prompt,
seed_slider,
randomize_seed_checkbox,
width,
height,
guidance_scale,
num_inference_steps,
num_images,
attention_slicing_checkbox,
],
outputs=[output_gallery],
show_progress=True,
)
reset_btn.click(
fn=lambda: None,
inputs=[],
outputs=[],
js="() => { window.location.reload(); }"
)
# Theme-Button: JS-Event für Theme-Umschaltung
theme_toggle_btn.click(
None, [], [], js=toggle_theme_js
)
# Theme-Status beim Laden setzen
demo.load(None, [], [], js=init_theme_js)
if name == "main":
demo.launch(debug=False, show_api=False)
Dein Code sieht insgesamt sehr gut und durchdacht aus, aber ich habe ein paar Punkte und Verbesserungsvorschläge gefunden, die du prüfen solltest:
Das lädt die Seite neu, also ist deine reset_inputs überflüssig oder wird nicht verwendet.
Wenn du doch die Eingaben über Gradio zurücksetzen willst, solltest du reset_inputs als fn angeben und passende Outputs.
4. Eventuell num_images als Int übergeben
num_images ist ein Dropdown mit Text-Strings:
python
num_images = gr.Dropdown(
label="Anzahl Bilder",
choices=[str(i) for i in range(1, 5)],
value="1",
interactive=True
)
In infer() konvertierst du das noch in Int, also ok. Alternativ könnte man choices als ints definieren.
5. callback_on_step_end funktioniert ggf. nicht
Die DiffusionPipeline unterstützt callback-Funktionen, das ist richtig. Eventuell kann man noch prüfen, ob die Signatur bei der installierten diffusers Version passt.
6. guidance_scale default-Wert 0.6 – vielleicht etwas niedrig?
Standard sind oft Werte zwischen 7.5 und 8.0. 0.6 ist sehr schwach - Das ist Geschmackssache, nur ein Hinweis.
Mögliche Korrektur:
python
0.6 # → eher 7.5 oder 8.0
7. token = os.getenv("HF_TOKEN") sollte dokumentiert sein
Falls die token nicht gesetzt ist, nutzt du nur öffentliche Modelle. Das ist gut, aber dokumentiere ggf. wie man das macht.
8. torch_dtype auch bei CPU richtig wählen
Du wählst:
python
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
Für CPUs ist float32 richtig, aber einige Modelle unterstützen ggf. float16 auch mit CPU (z.B. Apple M1/M2 Chips). Das kannst du anpassen, falls nötig.
9. Style / Lesbarkeit
Du hast die Kommentare und Dokumentationen sehr gut gemacht.
Beispiel Korrektur für wichtige Stellen:
python
def load_model(model_name, enable_attention_slicing=True):
"""
Lädt das angegebene Modell (oder Fallback) und gibt eine initialisierte Pipeline zurück.
"""
global token
model_repo_id = MODEL_MAP.get(model_name, MODEL_MAP["00-Fallback Stable Diffusion 1.5"])
print(f"Lade Modell: {model_name} => {model_repo_id} auf {device} mit dtype={torch_dtype}")
if token:
print("Token vorhanden, wird automatisch für den API-Zugriff genutzt.")
else:
print("Kein HF-Token gefunden, nur öffentlich zugängliche Modelle verfügbar.")
try:
pipeline = DiffusionPipeline.from_pretrained(
model_repo_id,
torch_dtype=torch_dtype,
use_auth_token=token if token else None,
)
pipeline = pipeline.to(device)
if enable_attention_slicing:
pipeline.enable_attention_slicing()
return pipeline
except (RepositoryNotFoundError, GatedRepoError) as e:
print(f"Fehler beim Laden von {model_repo_id}: {e}")
fallback_id = MODEL_MAP["00-Fallback Stable Diffusion 1.5"] # ---------- Fallback
print(f"Wechsel auf öffentliches Modell: {fallback_id}")
pipeline = DiffusionPipeline.from_pretrained(
fallback_id,
torch_dtype=torch_dtype,
use_auth_token=None,
)
pipeline = pipeline.to(device)
if enable_attention_slicing:
pipeline.enable_attention_slicing()
return pipeline
Fazit:
Dein Code ist größtenteils korrekt und gut strukturiert.
Du musst den Default-Key für das Fallback in load_model anpassen.
Die Token-Übergabe an from_pretrained fehlt.
Eventuell solltest du den Reset-Button anders gestalten, z.B. reset_inputs().
guidance_scale Standardwert ist sehr niedrig; du kannst den Wert erhöhen.
Wenn du möchtest, kann ich dir auch eine verbesserte Version des Codes schreiben. Meld dich gerne!
Gerne! Hier ist dein kompletter, korrigierter Code inklusive aller bisherigen Kommentare und mit den genannten Anpassungen (korrekter Fallback-Key, Token-Übergabe bei from_pretrained und ein minimal angehobener Default-Wert für guidance_scale):
python
import os
import gradio as gr
import numpy as np
import random
from diffusers import DiffusionPipeline
import torch
from huggingface_hub.utils import RepositoryNotFoundError, GatedRepoError # login-Import entfernt, da nicht verwendet
# Laden des Tokens aus Umgebungsvariable (z.B. HF_TOKEN)
token = os.getenv("HF_TOKEN")
# Auswahl des Geräts (GPU oder CPU) und des entsprechenden Datentyps
device = "cuda" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
# Modell-Auswahl → tatsächliches Hugging Face Model-Repository
MODEL_MAP = {
# -------- Fallback-Modell → Stable Diffusion 1.5
"00-Fallback Stable Diffusion 1.5": "runwayml/stable-diffusion-v1-5",
# Wird verwendet, falls das gewählte Modell nicht geladen werden kann.
# -------- 01-03: SDXL optimized GGUF-quantized Models
"01-SDXL-Base-GGUF": "gpustack/stable-diffusion-xl-base-1.0-gguf",
# Sehr hohe Qualität, aber langsam (ca. 1–2 tps), vollständig CPU-basiert.
"02-SDXL-Refiner-GGUF": "gpustack/stable-diffusion-xl-refiner-1.0-gguf",
# Für Feinschliff & Detailoptimierung, ähnlich 1–2 tps, als letzter Schritt.
"03-SDXL-Turbo-GGUF": "gpustack/stable-diffusion-xl-1.0-turbo-gguf",
# Leicht reduzierte Qualität vs. XL-Base, aber schneller (ca. 3–5 tps).
# -------- 04-05: SDXL Lightning & Hyper-SD
"04-SDXL-Lightning": "ByteDance/SDXL-Lightning",
# Kompakter SDXL-Runner, gute Detailtiefe, mittlere Geschwindigkeit auf CPU.
"05-Hyper-SD": "ByteDance/Hyper-SD",
# Fork von SD1.5 mit Qualitätsboost, moderat (ca. 1.5–2 tps).
# -------- 06-08: Stable Diffusion v2.1 Models
"06-Stable-Diffusion-2.1-Base": "stabilityai/stable-diffusion-2-1-base",
# Top-Fotorealismus, sehr langsam (< 1 tps), hohes RAM.
"07-Stable-Diffusion-2.1-v0": "stabilityai/stable-diffusion-2-1-v-0",
# Reduzierte Basis, gute Qualität, langsam (ca. 1 tps).
"08-SD-v2.1-GGUF": "gpustack/stable-diffusion-v2-1-gguf",
# Quantisierte v2.1, nahezu identisch zur Base, schneller (ca. 2–3 tps).
# -------- 09: Deliberate V2
"09-Deliberate-V2": "wavymulder/deliberate_v2",
# Optimiert für Fotorealismus, solide Geschwindigkeit (ca. 1 tps).
# -------- 10-13: Stable Diffusion v1.5 Models
"10-Stable-Diffusion-1.5": "runwayml/stable-diffusion-v1-5",
# Bewährter Allrounder, guter Kompromiss, moderat (ca. 1 tps).
"11-SD-1.5-GGUF-gpustack": "gpustack/stable-diffusion-v1-5-gguf",
# Quantisiert, gleiche Qualität, schnell (ca. 3 tps).
"12-SD-1.5-GGUF-SecondState": "second-state/stable-diffusion-v1-5-gguf",
# Alternative Quant-Implementation, ähnlich schnell (ca. 2–3 tps).
"13-HiDream-GGUF": "calcuis/hidream-gguf",
# Quantisierte HiDream, gute Qualität, flott (ca. 2 tps).
# -------- 14: CPU-optimierte schnelle Modelle
"14-FLUX.1-schnell": "black-forest-labs/FLUX.1-schnell",
# Sehr schnelle Inferenz (ca. 5–6 tps), geringere Detailtiefe.
# -------- Hinweise
# tps = Text-Prompts pro Sekunde
# Quantisierung beeinflusst die Detailgenauigkeit und Farbnuancen in KI-generierten Bildern.
# ✅ Hohe Quantisierung (Q6_K, Q8_0) → mehr Details, bessere Farbverläufe, weniger Artefakte.
# ❌ Niedrige Quantisierung (Q3_KM, Q4_KS) → geringere Präzision, sichtbare Unschärfen.
# GGUF (GPT-Generated Unified Format) ist ein optimiertes Dateiformat
# für effiziente Speicherung und Nutzung quantisierter KI-Modelle.
# Es ersetzt GGML und bietet schnelle Inferenz auf CPUs und GPUs.
# GPT (Generative Pre-trained Transformer, OpenAi) und SDXL (Stable Diffusion XL)
# sind KI-Modelle zur Text- und Bildverarbeitung:
# ✅ generativ – erstellt eigenständig Texte und Bilder;
# ✅ vortrainiert – trainiert mit riesigen Datenmengen;
# ✅ optimierte Modellarchitektur – effiziente Verarbeitung von Sprache und Bildern.
}
# Standard-Prompt für positive Eigenschaften – beeinflusst Stil & Qualität
DEFAULT_POSITIVE = (
"photorealistic, ultra detailed, 8K resolution, cinematic lighting, natural colors, sharp focus, "
"hyper-realistic, high-quality textures, intricate details, HDR, volumetric lighting, depth of field, "
"realistic reflections, dynamic composition, professional photography, soft shadows, vivid colors, "
"beautifully rendered, artistic masterpiece, lifelike portrayal"
)
# Standard-Negativ-Prompt – vermeidet unerwünschte Artefakte & Fehler
DEFAULT_NEGATIVE = (
"low quality, blurry, bad anatomy, extra limbs, watermark, text, distorted proportions, unnatural colors, "
"heavy noise, pixelated, overexposed, inconsistent lighting, lack of detail, warped perspective, "
"unrealistic expressions, compression artifacts, harsh shadows, cluttered composition, exaggerated features, "
"unwanted text overlays, poor depth of field"
)
# Pipeline-Instanz und Modellzustand global verwalten
pipe = None
current_model = None
def load_model(model_name, enable_attention_slicing=True):
"""
Lädt das angegebene Modell (oder Fallback) und gibt eine initialisierte Pipeline zurück.
"""
global token
model_repo_id = MODEL_MAP.get(model_name, MODEL_MAP["00-Fallback Stable Diffusion 1.5"])
print(f"Lade Modell: {model_name} => {model_repo_id} auf {device} mit dtype={torch_dtype}")
if token:
print("Token vorhanden, wird automatisch für den API-Zugriff genutzt.")
else:
print("Kein HF-Token gefunden, nur öffentlich zugängliche Modelle verfügbar.")
try:
pipeline = DiffusionPipeline.from_pretrained(
model_repo_id,
torch_dtype=torch_dtype,
use_auth_token=token if token else None,
)
pipeline = pipeline.to(device)
if enable_attention_slicing:
pipeline.enable_attention_slicing()
return pipeline
except (RepositoryNotFoundError, GatedRepoError) as e:
print(f"Fehler beim Laden von {model_repo_id}: {e}")
fallback_id = MODEL_MAP["00-Fallback Stable Diffusion 1.5"] # ---------- Fallback
print(f"Wechsel auf öffentliches Modell: {fallback_id}")
pipeline = DiffusionPipeline.from_pretrained(
fallback_id,
torch_dtype=torch_dtype,
use_auth_token=None,
)
pipeline = pipeline.to(device)
if enable_attention_slicing:
pipeline.enable_attention_slicing()
return pipeline
def infer(
model_name,
prompt,
positive_prompts,
negative_prompts,
base_seed,
randomize_seed,
width,
height,
guidance_scale,
num_inference_steps,
num_images,
enable_attention_slicing,
progress=gr.Progress(track_tqdm=True),
):
"""
Führt die Inferenz (erlerntes Wissen) durch und erstellt Bilder auf Basis der Eingaben.
"""
global pipe, current_model
# Konvertiere Parameter in erwartete Typen
num_images = int(num_images)
base_seed = int(base_seed) if base_seed is not None else 0
width = int(width)
height = int(height)
num_inference_steps = int(num_inference_steps)
guidance_scale = float(guidance_scale)
randomize_seed = bool(randomize_seed)
enable_attention_slicing = bool(enable_attention_slicing)
# Modell bei Bedarf neu laden
if current_model != model_name or pipe is None:
pipe = load_model(model_name, enable_attention_slicing)
current_model = model_name
# Prompt-Strings kombinieren
full_prompt = prompt.strip()
if positive_prompts:
full_prompt += " " + positive_prompts.strip()
full_negative = negative_prompts.strip() if negative_prompts else ""
images = []
def progress_callback(pipeline, step: int, timestep: int, latents):
progress((step + 1) / num_inference_steps)
return {}
for i in range(num_images):
# Seed berechnen – Zufallsseed oder aufsteigend ab Basiswert
if randomize_seed:
seed = random.randint(0, np.iinfo(np.int32).max)
else:
seed = base_seed + i
generator = torch.Generator(device=device).manual_seed(seed)
# Inferenz durchführen
imgs = pipe(
prompt=full_prompt,
negative_prompt=full_negative,
width=width,
height=height,
guidance_scale=guidance_scale,
num_inference_steps=num_inference_steps,
generator=generator,
callback_on_step_end=progress_callback,
).images
images.extend(imgs)
return images
def reset_inputs():
"""
Setzt alle Eingaben zurück auf Standardwerte.
"""
return (
"14-FLUX.1-schnell", # Modell-Key aus MODEL_MAP, angepasst
"",
DEFAULT_POSITIVE,
DEFAULT_NEGATIVE,
1,
True,
512,
512,
7.5, # guidance_scale hier auf standardmäßig realistisch angepasst
5,
"1",
True,
)
# Benutzerdefiniertes CSS für Design-Anpassungen
css = """
:root {
--loader-color: rgb(76, 175, 80);
--slider-color: rgb(76, 175, 80);
--checkbox-border-color-focus: rgb(76, 175, 80);
--checkbox-background-color-selected: rgb(76, 175, 80);
--border-color-primary: rgb(76, 175, 80);
--block-border-color: rgb(76, 175, 80);
--input-border-color: rgb(76, 175, 80);
--body-background-fill: rgb(240 255 220);
--progress-bar: rgb(240 255 220);
}
/* Auch im Darkmode alles grün! */
body.dark {
--loader-color: rgb(76, 175, 80) !important;
--slider-color: rgb(76, 175, 80) !important;
--checkbox-border-color-focus: rgb(76, 175, 80) !important;
--checkbox-background-color-selected: rgb(76, 175, 80) !important;
--border-color-primary: rgb(76, 175, 80) !important;
--block-border-color: rgb(76, 175, 80) !important;
--input-border-color: rgb(76, 175, 80) !important;
--progress-bar: rgb(240 255 220) !important;
}
#component-2 {
overflow: hidden !important;
}
#col-container {
max-width: 90%;
margin-left: auto;
margin-right: auto;
display: flex;
flex-direction: column;
align-items: center;
}
#output-gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 10px;
height: 406px !important;
}
.gr-row { width: 100%; max-width: 900px; margin-left: auto; margin-right: auto; }
#left-col { flex: 3 1 0; min-width: 0; }
#right-col { flex: 2 1 0; min-width: 0; }
@media (max-width: 1040px) and (min-width: 769px) {
#left-col { flex: 4 1 0; min-width: 0; }
#right-col { flex: 1 1 0; min-width: 0; }
}
@media (max-width: 768px) {
#left-col, #right-col {
flex: 1 1 100% !important;
max-width: 100% !important;
}
}
@media (max-width: 1280px) {
#col-container { max-width: 95%; }
}
button#generate-btn,
button#reset-btn,
button#theme-toggle-btn {
/* Gemeinsamer Stil für alle drei Buttons */
padding: 12px 24px;
font-size: 16px;
border: none;
border-radius: 6px;
cursor: pointer;
transition: background-color 0.3s ease, transform 0.1s ease;
font-weight: bold;
}
button#generate-btn {
background-color: #4CAF50;
color: white;
}
button#generate-btn:hover {
background-color: #45a049;
}
button#generate-btn:active {
background-color: #2e7031;
transform: scale(0.96);
}
button#reset-btn {
background-color: #f44336;
color: white;
}
button#reset-btn:hover { background-color: #d73830; }
button#reset-btn:active {
background-color: #a32d25;
transform: scale(0.96);
}
/* Darkmode/Lightmode Toggle Button Styles */
body:not(.dark) button#theme-toggle-btn {
background-color: #111111;
color: #ffffff;
}
body:not(.dark) button#theme-toggle-btn:hover {
background-color: #424242;
}
body:not(.dark) button#theme-toggle-btn:active {
background-color: #2c2c2c;
transform: scale(0.96);
}
body.dark button#theme-toggle-btn {
background-color: #ffffff;
color: #111;
border: 1px solid #111;
}
body.dark button#theme-toggle-btn:hover {
background-color: #e5e5e5;
}
body.dark button#theme-toggle-btn:active {
background-color: #b7b7b7;
transform: scale(0.96);
}
"""
# JavaScript für Theme-Umschaltung (Dark/Light)
toggle_theme_js = """
() => {
// Prüfe, ob body das dark-Attribut hat
const isDark = document.body.classList.contains('dark');
if (isDark) {
document.body.classList.remove('dark');
localStorage.setItem('gradio-theme', 'light');
} else {
document.body.classList.add('dark');
localStorage.setItem('gradio-theme', 'dark');
}
// Button-Text anpassen
const btn = document.getElementById('theme-toggle-btn');
if (btn) {
btn.textContent = isDark ? 'Darkmode' : 'Lightmode';
}
}
"""
# JavaScript, um Theme beim Laden zu setzen (optional, damit Einstellung erhalten bleibt)
init_theme_js = """
() => {
const saved = localStorage.getItem('gradio-theme');
if (saved === 'dark') {
document.body.classList.add('dark');
} else if (saved === 'light') {
document.body.classList.remove('dark');
}
// Button-Text setzen
const btn = document.getElementById('theme-toggle-btn');
if (btn) {
btn.textContent = document.body.classList.contains('dark') ? 'Lightmode' : 'Darkmode';
}
}
"""
# Gradio UI
with gr.Blocks(css=css, theme=gr.themes.Default(spacing_size="sm")) as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown("# 🤠 AI-Bildgenerator (mit automatischem Modell-Fallback)")
gr.Markdown(
"""
**Achtung:** Falls ein Modell gated* ist und keinen Zugriff erlaubt, wird
automatisch das öffentliche Stable Diffusion 1.5 Modell verwendet.
"""
)
with gr.Row():
with gr.Column(scale=3, elem_id="left-col"):
model_dropdown = gr.Dropdown(
label="Modell",
choices=list(MODEL_MAP.keys()),
value="09-Deliberate-V2", # ---------- jetzt Standard
interactive=True,
info="Gated-Modelle benötigen ggf. einen Token und eine Freischaltung!"
)
prompt = gr.Textbox(
label="Hauptprompt",
lines=5,
max_lines=10,
interactive=True,
placeholder="Beschreibe das gewünschte Bild ..."
)
positive_prompt = gr.Textbox(
label="Positiv-Prompts (durch Kommas getrennt)",
lines=5,
max_lines=10,
interactive=True,
value=DEFAULT_POSITIVE
)
negative_prompt = gr.Textbox(
label="Negativ-Prompts (durch Kommas getrennt)",
lines=5,
max_lines=10,
interactive=True,
value=DEFAULT_NEGATIVE
)
with gr.Accordion("Erweiterte Einstellungen", open=True):
with gr.Row():
seed_slider = gr.Slider(0, 2147483647, label="Seed", value=1, step=1)
randomize_seed_checkbox = gr.Checkbox(label="Zufälligen Seed", value=True)
with gr.Row():
width = gr.Slider(256, 1024, value=512, step=64, label="Breite (max. 512 empfohlen)")
height = gr.Slider(256, 1024, value=512, step=64, label="Höhe (max. 512 empfohlen)")
with gr.Row():
guidance_scale = gr.Slider(0.0, 20.0, value=7.5, step=0.1, label="Guidance Scale")
num_inference_steps = gr.Slider(1, 30, value=5, step=1, label="Inferenzschritte")
with gr.Row():
attention_slicing_checkbox = gr.Checkbox(
label="Speicheroptimierung (Attention Slicing) aktivieren", value=True
)
num_images = gr.Dropdown(
label="Anzahl Bilder",
choices=[str(i) for i in range(1, 5)],
value="1",
interactive=True
)
# Button-Zeile: Bild generieren | Zurücksetzen | Darkmode
with gr.Row():
generate_btn = gr.Button("Bild generieren", elem_id="generate-btn", variant="primary")
reset_btn = gr.Button("Zurücksetzen", elem_id="reset-btn")
theme_toggle_btn = gr.Button("Darkmode", elem_id="theme-toggle-btn", variant="secondary")
gr.Markdown(
"""
**Hinweise:**
- *Guidance* bestimmt, wie strikt sich das Modell an den Prompt hält.
- *Inference* nutzt erlerntes Wissen, um Bilder zu generieren.
- Gated-Modelle benötigen Token und Freigabe.
- Für schwächere Hardware max. **512×512 Pixel** empfohlen.
- **Info:** Größere Auflösungen (z.B. 1024×1024 Pixel) benötigen **deutlich mehr Rechenleistung**!
"""
)
with gr.Column(scale=2, elem_id="right-col"):
output_gallery = gr.Gallery(
label="Ergebnisse",
show_label=False,
elem_id="output-gallery",
type="pil"
)
# Button-Events
generate_btn.click(
fn=infer,
inputs=[
model_dropdown,
prompt,
positive_prompt,
negative_prompt,
seed_slider,
randomize_seed_checkbox,
width,
height,
guidance_scale,
num_inference_steps,
num_images,
attention_slicing_checkbox,
],
outputs=[output_gallery],
show_progress=True,
)
reset_btn.click(
fn=reset_inputs,
inputs=[],
outputs=[
model_dropdown,
prompt,
positive_prompt,
negative_prompt,
seed_slider,
randomize_seed_checkbox,
width,
height,
guidance_scale,
num_inference_steps,
num_images,
attention_slicing_checkbox,
],
)
# Theme-Button: JS-Event für Theme-Umschaltung
theme_toggle_btn.click(
None, [], [], js=toggle_theme_js
)
# Theme-Status beim Laden setzen
demo.load(None, [], [], js=init_theme_js)
if __name__ == "__main__":
demo.launch(debug=False, show_api=False)
Änderungen im Detail:
Fallback-Key im load_model korrekt auf "00-Fallback Stable Diffusion 1.5" angepasst
Übergabe von use_auth_token=token if token else None an DiffusionPipeline.from_pretrained
In reset_inputs den Wert des Modells auf einen gültigen Key "14-FLUX.1-schnell" geändert (kannst du natürlich auf dein Standardmodell anpassen)
Default guidance_scale auf 7.5 gebracht (übliches SD-Setting statt 0.6)
reset_btn setzt jetzt aktiv alle Eingabefelder auf ihre Standardwerte zurück, anstelle der kompletten Seite neu zu laden (mehr Benutzerfreundlichkeit)
Kommentare und Struktur wurden unverändert übernommen
Falls du den Reset statt per expliziter Funktion lieber per Seite-Neuladen möchtest, kannst du natürlich das alte Verhalten wiederherstellen.
Wenn du weitere Fragen hast oder noch eine Optimierung möchtest, melde dich gern!
Natürlich! Hier ist der komplette, aktualisierte Code mit den gewünschten Anpassungen:
Der Reset-Button lädt die Seite neu (statt Eingaben zurückzusetzen).
reset_inputs() wurde angepasst und gibt als Standardmodell "09-Deliberate-V2" zurück.
Alle bisherigen Kommentare und Verbesserungen sind enthalten.
python
import os
import gradio as gr
import numpy as np
import random
from diffusers import DiffusionPipeline
import torch
from huggingface_hub.utils import RepositoryNotFoundError, GatedRepoError # login-Import entfernt, da nicht verwendet
# Laden des Tokens aus Umgebungsvariable (z.B. HF_TOKEN)
token = os.getenv("HF_TOKEN")
# Auswahl des Geräts (GPU oder CPU) und des entsprechenden Datentyps
device = "cuda" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
# Modell-Auswahl → tatsächliches Hugging Face Model-Repository
MODEL_MAP = {
# -------- Fallback-Modell → Stable Diffusion 1.5
"00-Fallback Stable Diffusion 1.5": "runwayml/stable-diffusion-v1-5",
# Wird verwendet, falls das gewählte Modell nicht geladen werden kann.
# -------- 01-03: SDXL optimized GGUF-quantized Models
"01-SDXL-Base-GGUF": "gpustack/stable-diffusion-xl-base-1.0-gguf",
# Sehr hohe Qualität, aber langsam (ca. 1–2 tps), vollständig CPU-basiert.
"02-SDXL-Refiner-GGUF": "gpustack/stable-diffusion-xl-refiner-1.0-gguf",
# Für Feinschliff & Detailoptimierung, ähnlich 1–2 tps, als letzter Schritt.
"03-SDXL-Turbo-GGUF": "gpustack/stable-diffusion-xl-1.0-turbo-gguf",
# Leicht reduzierte Qualität vs. XL-Base, aber schneller (ca. 3–5 tps).
# -------- 04-05: SDXL Lightning & Hyper-SD
"04-SDXL-Lightning": "ByteDance/SDXL-Lightning",
# Kompakter SDXL-Runner, gute Detailtiefe, mittlere Geschwindigkeit auf CPU.
"05-Hyper-SD": "ByteDance/Hyper-SD",
# Fork von SD1.5 mit Qualitätsboost, moderat (ca. 1.5–2 tps).
# -------- 06-08: Stable Diffusion v2.1 Models
"06-Stable-Diffusion-2.1-Base": "stabilityai/stable-diffusion-2-1-base",
# Top-Fotorealismus, sehr langsam (< 1 tps), hohes RAM.
"07-Stable-Diffusion-2.1-v0": "stabilityai/stable-diffusion-2-1-v-0",
# Reduzierte Basis, gute Qualität, langsam (ca. 1 tps).
"08-SD-v2.1-GGUF": "gpustack/stable-diffusion-v2-1-gguf",
# Quantisierte v2.1, nahezu identisch zur Base, schneller (ca. 2–3 tps).
# -------- 09: Deliberate V2
"09-Deliberate-V2": "wavymulder/deliberate_v2",
# Optimiert für Fotorealismus, solide Geschwindigkeit (ca. 1 tps).
# -------- 10-13: Stable Diffusion v1.5 Models
"10-Stable-Diffusion-1.5": "runwayml/stable-diffusion-v1-5",
# Bewährter Allrounder, guter Kompromiss, moderat (ca. 1 tps).
"11-SD-1.5-GGUF-gpustack": "gpustack/stable-diffusion-v1-5-gguf",
# Quantisiert, gleiche Qualität, schnell (ca. 3 tps).
"12-SD-1.5-GGUF-SecondState": "second-state/stable-diffusion-v1-5-gguf",
# Alternative Quant-Implementation, ähnlich schnell (ca. 2–3 tps).
"13-HiDream-GGUF": "calcuis/hidream-gguf",
# Quantisierte HiDream, gute Qualität, flott (ca. 2 tps).
# -------- 14: CPU-optimierte schnelle Modelle
"14-FLUX.1-schnell": "black-forest-labs/FLUX.1-schnell",
# Sehr schnelle Inferenz (ca. 5–6 tps), geringere Detailtiefe.
# -------- Hinweise
# tps = Text-Prompts pro Sekunde
# Quantisierung beeinflusst die Detailgenauigkeit und Farbnuancen in KI-generierten Bildern.
# ✅ Hohe Quantisierung (Q6_K, Q8_0) → mehr Details, bessere Farbverläufe, weniger Artefakte.
# ❌ Niedrige Quantisierung (Q3_KM, Q4_KS) → geringere Präzision, sichtbare Unschärfen.
# GGUF (GPT-Generated Unified Format) ist ein optimiertes Dateiformat
# für effiziente Speicherung und Nutzung quantisierter KI-Modelle.
# Es ersetzt GGML und bietet schnelle Inferenz auf CPUs und GPUs.
# GPT (Generative Pre-trained Transformer, OpenAi) und SDXL (Stable Diffusion XL)
# sind KI-Modelle zur Text- und Bildverarbeitung:
# ✅ generativ – erstellt eigenständig Texte und Bilder;
# ✅ vortrainiert – trainiert mit riesigen Datenmengen;
# ✅ optimierte Modellarchitektur – effiziente Verarbeitung von Sprache und Bildern.
}
# Standard-Prompt für positive Eigenschaften – beeinflusst Stil & Qualität
DEFAULT_POSITIVE = (
"photorealistic, ultra detailed, 8K resolution, cinematic lighting, natural colors, sharp focus, "
"hyper-realistic, high-quality textures, intricate details, HDR, volumetric lighting, depth of field, "
"realistic reflections, dynamic composition, professional photography, soft shadows, vivid colors, "
"beautifully rendered, artistic masterpiece, lifelike portrayal"
)
# Standard-Negativ-Prompt – vermeidet unerwünschte Artefakte & Fehler
DEFAULT_NEGATIVE = (
"low quality, blurry, bad anatomy, extra limbs, watermark, text, distorted proportions, unnatural colors, "
"heavy noise, pixelated, overexposed, inconsistent lighting, lack of detail, warped perspective, "
"unrealistic expressions, compression artifacts, harsh shadows, cluttered composition, exaggerated features, "
"unwanted text overlays, poor depth of field"
)
# Pipeline-Instanz und Modellzustand global verwalten
pipe = None
current_model = None
def load_model(model_name, enable_attention_slicing=True):
"""
Lädt das angegebene Modell (oder Fallback) und gibt eine initialisierte Pipeline zurück.
"""
global token
model_repo_id = MODEL_MAP.get(model_name, MODEL_MAP["00-Fallback Stable Diffusion 1.5"])
print(f"Lade Modell: {model_name} => {model_repo_id} auf {device} mit dtype={torch_dtype}")
if token:
print("Token vorhanden, wird automatisch für den API-Zugriff genutzt.")
else:
print("Kein HF-Token gefunden, nur öffentlich zugängliche Modelle verfügbar.")
try:
pipeline = DiffusionPipeline.from_pretrained(
model_repo_id,
torch_dtype=torch_dtype,
use_auth_token=token if token else None,
)
pipeline = pipeline.to(device)
if enable_attention_slicing:
pipeline.enable_attention_slicing()
return pipeline
except (RepositoryNotFoundError, GatedRepoError) as e:
print(f"Fehler beim Laden von {model_repo_id}: {e}")
fallback_id = MODEL_MAP["00-Fallback Stable Diffusion 1.5"] # ---------- Fallback
print(f"Wechsel auf öffentliches Modell: {fallback_id}")
pipeline = DiffusionPipeline.from_pretrained(
fallback_id,
torch_dtype=torch_dtype,
use_auth_token=None,
)
pipeline = pipeline.to(device)
if enable_attention_slicing:
pipeline.enable_attention_slicing()
return pipeline
def infer(
model_name,
prompt,
positive_prompts,
negative_prompts,
base_seed,
randomize_seed,
width,
height,
guidance_scale,
num_inference_steps,
num_images,
enable_attention_slicing,
progress=gr.Progress(track_tqdm=True),
):
"""
Führt die Inferenz (erlerntes Wissen) durch und erstellt Bilder auf Basis der Eingaben.
"""
global pipe, current_model
# Konvertiere Parameter in erwartete Typen
num_images = int(num_images)
base_seed = int(base_seed) if base_seed is not None else 0
width = int(width)
height = int(height)
num_inference_steps = int(num_inference_steps)
guidance_scale = float(guidance_scale)
randomize_seed = bool(randomize_seed)
enable_attention_slicing = bool(enable_attention_slicing)
# Modell bei Bedarf neu laden
if current_model != model_name or pipe is None:
pipe = load_model(model_name, enable_attention_slicing)
current_model = model_name
# Prompt-Strings kombinieren
full_prompt = prompt.strip()
if positive_prompts:
full_prompt += " " + positive_prompts.strip()
full_negative = negative_prompts.strip() if negative_prompts else ""
images = []
def progress_callback(pipeline, step: int, timestep: int, latents):
progress((step + 1) / num_inference_steps)
return {}
for i in range(num_images):
# Seed berechnen – Zufallsseed oder aufsteigend ab Basiswert
if randomize_seed:
seed = random.randint(0, np.iinfo(np.int32).max)
else:
seed = base_seed + i
generator = torch.Generator(device=device).manual_seed(seed)
# Inferenz durchführen
imgs = pipe(
prompt=full_prompt,
negative_prompt=full_negative,
width=width,
height=height,
guidance_scale=guidance_scale,
num_inference_steps=num_inference_steps,
generator=generator,
callback_on_step_end=progress_callback,
).images
images.extend(imgs)
return images
def reset_inputs():
"""
Setzt alle Eingaben zurück auf Standardwerte.
(Wird aktuell nicht direkt benutzt, da Reset per Seitenreload erfolgt)
"""
return (
"09-Deliberate-V2", # Angepasstes Standardmodell
"",
DEFAULT_POSITIVE,
DEFAULT_NEGATIVE,
1,
True,
512,
512,
7.5, # realistischere guidance_scale
5,
"1",
True,
)
# Benutzerdefiniertes CSS für Design-Anpassungen
css = """
:root {
--loader-color: rgb(76, 175, 80);
--slider-color: rgb(76, 175, 80);
--checkbox-border-color-focus: rgb(76, 175, 80);
--checkbox-background-color-selected: rgb(76, 175, 80);
--border-color-primary: rgb(76, 175, 80);
--block-border-color: rgb(76, 175, 80);
--input-border-color: rgb(76, 175, 80);
--body-background-fill: rgb(240 255 220);
--progress-bar: rgb(240 255 220);
}
/* Auch im Darkmode alles grün! */
body.dark {
--loader-color: rgb(76, 175, 80) !important;
--slider-color: rgb(76, 175, 80) !important;
--checkbox-border-color-focus: rgb(76, 175, 80) !important;
--checkbox-background-color-selected: rgb(76, 175, 80) !important;
--border-color-primary: rgb(76, 175, 80) !important;
--block-border-color: rgb(76, 175, 80) !important;
--input-border-color: rgb(76, 175, 80) !important;
--progress-bar: rgb(240 255 220) !important;
}
#component-2 {
overflow: hidden !important;
}
#col-container {
max-width: 90%;
margin-left: auto;
margin-right: auto;
display: flex;
flex-direction: column;
align-items: center;
}
#output-gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 10px;
height: 406px !important;
}
.gr-row { width: 100%; max-width: 900px; margin-left: auto; margin-right: auto; }
#left-col { flex: 3 1 0; min-width: 0; }
#right-col { flex: 2 1 0; min-width: 0; }
@media (max-width: 1040px) and (min-width: 769px) {
#left-col { flex: 4 1 0; min-width: 0; }
#right-col { flex: 1 1 0; min-width: 0; }
}
@media (max-width: 768px) {
#left-col, #right-col {
flex: 1 1 100% !important;
max-width: 100% !important;
}
}
@media (max-width: 1280px) {
#col-container { max-width: 95%; }
}
button#generate-btn,
button#reset-btn,
button#theme-toggle-btn {
/* Gemeinsamer Stil für alle drei Buttons */
padding: 12px 24px;
font-size: 16px;
border: none;
border-radius: 6px;
cursor: pointer;
transition: background-color 0.3s ease, transform 0.1s ease;
font-weight: bold;
}
button#generate-btn {
background-color: #4CAF50;
color: white;
}
button#generate-btn:hover {
background-color: #45a049;
}
button#generate-btn:active {
background-color: #2e7031;
transform: scale(0.96);
}
button#reset-btn {
background-color: #f44336;
color: white;
}
button#reset-btn:hover { background-color: #d73830; }
button#reset-btn:active {
background-color: #a32d25;
transform: scale(0.96);
}
/* Darkmode/Lightmode Toggle Button Styles */
body:not(.dark) button#theme-toggle-btn {
background-color: #111111;
color: #ffffff;
}
body:not(.dark) button#theme-toggle-btn:hover {
background-color: #424242;
}
body:not(.dark) button#theme-toggle-btn:active {
background-color: #2c2c2c;
transform: scale(0.96);
}
body.dark button#theme-toggle-btn {
background-color: #ffffff;
color: #111;
border: 1px solid #111;
}
body.dark button#theme-toggle-btn:hover {
background-color: #e5e5e5;
}
body.dark button#theme-toggle-btn:active {
background-color: #b7b7b7;
transform: scale(0.96);
}
"""
# JavaScript für Theme-Umschaltung (Dark/Light)
toggle_theme_js = """
() => {
// Prüfe, ob body das dark-Attribut hat
const isDark = document.body.classList.contains('dark');
if (isDark) {
document.body.classList.remove('dark');
localStorage.setItem('gradio-theme', 'light');
} else {
document.body.classList.add('dark');
localStorage.setItem('gradio-theme', 'dark');
}
// Button-Text anpassen
const btn = document.getElementById('theme-toggle-btn');
if (btn) {
btn.textContent = isDark ? 'Darkmode' : 'Lightmode';
}
}
"""
# JavaScript, um Theme beim Laden zu setzen (optional, damit Einstellung erhalten bleibt)
init_theme_js = """
() => {
const saved = localStorage.getItem('gradio-theme');
if (saved === 'dark') {
document.body.classList.add('dark');
} else if (saved === 'light') {
document.body.classList.remove('dark');
}
// Button-Text setzen
const btn = document.getElementById('theme-toggle-btn');
if (btn) {
btn.textContent = document.body.classList.contains('dark') ? 'Lightmode' : 'Darkmode';
}
}
"""
# Gradio UI
with gr.Blocks(css=css, theme=gr.themes.Default(spacing_size="sm")) as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown("# 🤠 AI-Bildgenerator (mit automatischem Modell-Fallback)")
gr.Markdown(
"""
**Achtung:** Falls ein Modell gated* ist und keinen Zugriff erlaubt, wird
automatisch das öffentliche Stable Diffusion 1.5 Modell verwendet.
"""
)
with gr.Row():
with gr.Column(scale=3, elem_id="left-col"):
model_dropdown = gr.Dropdown(
label="Modell",
choices=list(MODEL_MAP.keys()),
value="09-Deliberate-V2", # ---------- jetzt Standard
interactive=True,
info="Gated-Modelle benötigen ggf. einen Token und eine Freischaltung!"
)
prompt = gr.Textbox(
label="Hauptprompt",
lines=5,
max_lines=10,
interactive=True,
placeholder="Beschreibe das gewünschte Bild ..."
)
positive_prompt = gr.Textbox(
label="Positiv-Prompts (durch Kommas getrennt)",
lines=5,
max_lines=10,
interactive=True,
value=DEFAULT_POSITIVE
)
negative_prompt = gr.Textbox(
label="Negativ-Prompts (durch Kommas getrennt)",
lines=5,
max_lines=10,
interactive=True,
value=DEFAULT_NEGATIVE
)
with gr.Accordion("Erweiterte Einstellungen", open=True):
with gr.Row():
seed_slider = gr.Slider(0, 2147483647, label="Seed", value=1, step=1)
randomize_seed_checkbox = gr.Checkbox(label="Zufälligen Seed", value=True)
with gr.Row():
width = gr.Slider(256, 1024, value=512, step=64, label="Breite (max. 512 empfohlen)")
height = gr.Slider(256, 1024, value=512, step=64, label="Höhe (max. 512 empfohlen)")
with gr.Row():
guidance_scale = gr.Slider(0.0, 20.0, value=7.5, step=0.1, label="Guidance Scale")
num_inference_steps = gr.Slider(1, 30, value=5, step=1, label="Inferenzschritte")
with gr.Row():
attention_slicing_checkbox = gr.Checkbox(
label="Speicheroptimierung (Attention Slicing) aktivieren", value=True
)
num_images = gr.Dropdown(
label="Anzahl Bilder",
choices=[str(i) for i in range(1, 5)],
value="1",
interactive=True
)
# Button-Zeile: Bild generieren | Zurücksetzen | Darkmode
with gr.Row():
generate_btn = gr.Button("Bild generieren", elem_id="generate-btn", variant="primary")
reset_btn = gr.Button("Zurücksetzen", elem_id="reset-btn")
theme_toggle_btn = gr.Button("Darkmode", elem_id="theme-toggle-btn", variant="secondary")
gr.Markdown(
"""
**Hinweise:**
- *Guidance* bestimmt, wie strikt sich das Modell an den Prompt hält.
- *Inference* nutzt erlerntes Wissen, um Bilder zu generieren.
- Gated-Modelle benötigen Token und Freigabe.
- Für schwächere Hardware max. **512×512 Pixel** empfohlen.
- **Info:** Größere Auflösungen (z.B. 1024×1024 Pixel) benötigen **deutlich mehr Rechenleistung**!
"""
)
with gr.Column(scale=2, elem_id="right-col"):
output_gallery = gr.Gallery(
label="Ergebnisse",
show_label=False,
elem_id="output-gallery",
type="pil"
)
# Button-Events
generate_btn.click(
fn=infer,
inputs=[
model_dropdown,
prompt,
positive_prompt,
negative_prompt,
seed_slider,
randomize_seed_checkbox,
width,
height,
guidance_scale,
num_inference_steps,
num_images,
attention_slicing_checkbox,
],
outputs=[output_gallery],
show_progress=True,
)
reset_btn.click(
fn=lambda: None, # kein Python-Funktion-Reset nötig, wird per JS neu geladen
inputs=[],
outputs=[],
js="() => { window.location.reload(); }"
)
# Theme-Button: JS-Event für Theme-Umschaltung
theme_toggle_btn.click(
None, [], [], js=toggle_theme_js
)
# Theme-Status beim Laden setzen
demo.load(None, [], [], js=init_theme_js)
if __name__ == "__main__":
demo.launch(debug=False, show_api=False)
Damit lädt der Reset-Button die Seite komplett neu und alle Eingaben werden auf Standardzustand zurückgesetzt. Die reset_inputs() Funktion wurde angepasst, steht aber aktuell nur als Referenz und für mögliche spätere Nutzung bereit.
Falls du weitere Anpassungen möchtest, helfe ich gern!
dann passt dieser code: import os
import gradio as gr
import numpy as np
import random
from diffusers import DiffusionPipeline
import torch
from huggingface_hub.utils import RepositoryNotFoundError, GatedRepoError # login-Import entfernt, da nicht verwendet
Laden des Tokens aus Umgebungsvariable (z.B. HF_TOKEN)
token = os.getenv("HF_TOKEN")
Auswahl des Geräts (GPU oder CPU) und des entsprechenden Datentyps
device = "cuda" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
Modell-Auswahl → tatsächliches Hugging Face Model-Repository
MODEL_MAP = {
code
# -------- Fallback-Modell → Stable Diffusion 1.5
"00-Fallback Stable Diffusion 1.5": "runwayml/stable-diffusion-v1-5",
# Wird verwendet, falls das gewählte Modell nicht geladen werden kann.
# -------- 01-03: SDXL optimized GGUF-quantized Models
"01-SDXL-Base-GGUF": "gpustack/stable-diffusion-xl-base-1.0-gguf",
# Sehr hohe Qualität, aber langsam (ca. 1–2 tps), vollständig CPU-basiert.
"02-SDXL-Refiner-GGUF": "gpustack/stable-diffusion-xl-refiner-1.0-gguf",
# Für Feinschliff & Detailoptimierung, ähnlich 1–2 tps, als letzter Schritt.
"03-SDXL-Turbo-GGUF": "gpustack/stable-diffusion-xl-1.0-turbo-gguf",
# Leicht reduzierte Qualität vs. XL-Base, aber schneller (ca. 3–5 tps).
# -------- 04-05: SDXL Lightning & Hyper-SD
"04-SDXL-Lightning": "ByteDance/SDXL-Lightning",
# Kompakter SDXL-Runner, gute Detailtiefe, mittlere Geschwindigkeit auf CPU.
"05-Hyper-SD": "ByteDance/Hyper-SD",
# Fork von SD1.5 mit Qualitätsboost, moderat (ca. 1.5–2 tps).
# -------- 06-08: Stable Diffusion v2.1 Models
"06-Stable-Diffusion-2.1-Base": "stabilityai/stable-diffusion-2-1-base",
# Top-Fotorealismus, sehr langsam (< 1 tps), hohes RAM.
"07-Stable-Diffusion-2.1-v0": "stabilityai/stable-diffusion-2-1-v-0",
# Reduzierte Basis, gute Qualität, langsam (ca. 1 tps).
"08-SD-v2.1-GGUF": "gpustack/stable-diffusion-v2-1-gguf",
# Quantisierte v2.1, nahezu identisch zur Base, schneller (ca. 2–3 tps).
# -------- 09: Deliberate V2
"09-Deliberate-V2": "wavymulder/deliberate_v2",
# Optimiert für Fotorealismus, solide Geschwindigkeit (ca. 1 tps).
# -------- 10-13: Stable Diffusion v1.5 Models
"10-Stable-Diffusion-1.5": "runwayml/stable-diffusion-v1-5",
# Bewährter Allrounder, guter Kompromiss, moderat (ca. 1 tps).
"11-SD-1.5-GGUF-gpustack": "gpustack/stable-diffusion-v1-5-gguf",
# Quantisiert, gleiche Qualität, schnell (ca. 3 tps).
"12-SD-1.5-GGUF-SecondState": "second-state/stable-diffusion-v1-5-gguf",
# Alternative Quant-Implementation, ähnlich schnell (ca. 2–3 tps).
"13-HiDream-GGUF": "calcuis/hidream-gguf",
# Quantisierte HiDream, gute Qualität, flott (ca. 2 tps).
# -------- 14: CPU-optimierte schnelle Modelle
"14-FLUX.1-schnell": "black-forest-labs/FLUX.1-schnell",
# Sehr schnelle Inferenz (ca. 5–6 tps), geringere Detailtiefe.
# -------- Hinweise
# tps = Text-Prompts pro Sekunde
# Quantisierung beeinflusst die Detailgenauigkeit und Farbnuancen in KI-generierten Bildern.
# ✅ Hohe Quantisierung (Q6_K, Q8_0) → mehr Details, bessere Farbverläufe, weniger Artefakte.
# ❌ Niedrige Quantisierung (Q3_KM, Q4_KS) → geringere Präzision, sichtbare Unschärfen.
# GGUF (GPT-Generated Unified Format) ist ein optimiertes Dateiformat
# für effiziente Speicherung und Nutzung quantisierter KI-Modelle.
# Es ersetzt GGML und bietet schnelle Inferenz auf CPUs und GPUs.
# GPT (Generative Pre-trained Transformer, OpenAi) und SDXL (Stable Diffusion XL)
# sind KI-Modelle zur Text- und Bildverarbeitung:
# ✅ generativ – erstellt eigenständig Texte und Bilder;
# ✅ vortrainiert – trainiert mit riesigen Datenmengen;
# ✅ optimierte Modellarchitektur – effiziente Verarbeitung von Sprache und Bildern.
}
Standard-Prompt für positive Eigenschaften – beeinflusst Stil & Qualität
DEFAULT_NEGATIVE = (
"low quality, blurry, bad anatomy, extra limbs, watermark, text, distorted proportions, unnatural colors, "
"heavy noise, pixelated, overexposed, inconsistent lighting, lack of detail, warped perspective, "
"unrealistic expressions, compression artifacts, harsh shadows, cluttered composition, exaggerated features, "
"unwanted text overlays, poor depth of field"
)
Pipeline-Instanz und Modellzustand global verwalten
pipe = None
current_model = None
def load_model(model_name, enable_attention_slicing=True):
"""
Lädt das angegebene Modell (oder Fallback) und gibt eine initialisierte Pipeline zurück.
"""
global token
model_repo_id = MODEL_MAP.get(model_name, MODEL_MAP["00-Fallback Stable Diffusion 1.5"])
print(f"Lade Modell: {model_name} => {model_repo_id} auf {device} mit dtype={torch_dtype}")
if token:
print("Token vorhanden, wird automatisch für den API-Zugriff genutzt.")
else:
print("Kein HF-Token gefunden, nur öffentlich zugängliche Modelle verfügbar.")
try:
pipeline = DiffusionPipeline.from_pretrained(
model_repo_id,
torch_dtype=torch_dtype,
use_auth_token=token if token else None,
)
pipeline = pipeline.to(device)
if enable_attention_slicing:
pipeline.enable_attention_slicing()
return pipeline
except (RepositoryNotFoundError, GatedRepoError) as e:
print(f"Fehler beim Laden von {model_repo_id}: {e}")
fallback_id = MODEL_MAP["00-Fallback Stable Diffusion 1.5"] # ---------- Fallback
print(f"Wechsel auf öffentliches Modell: {fallback_id}")
pipeline = DiffusionPipeline.from_pretrained(
fallback_id,
torch_dtype=torch_dtype,
use_auth_token=None,
)
pipeline = pipeline.to(device)
if enable_attention_slicing:
pipeline.enable_attention_slicing()
return pipeline
def infer(
model_name,
prompt,
positive_prompts,
negative_prompts,
base_seed,
randomize_seed,
width,
height,
guidance_scale,
num_inference_steps,
num_images,
enable_attention_slicing,
progress=gr.Progress(track_tqdm=True),
):
"""
Führt die Inferenz (erlerntes Wissen) durch und erstellt Bilder auf Basis der Eingaben.
"""
global pipe, current_model
code
# Konvertiere Parameter in erwartete Typen
num_images = int(num_images)
base_seed = int(base_seed) if base_seed is not None else 0
width = int(width)
height = int(height)
num_inference_steps = int(num_inference_steps)
guidance_scale = float(guidance_scale)
randomize_seed = bool(randomize_seed)
enable_attention_slicing = bool(enable_attention_slicing)
# Modell bei Bedarf neu laden
if current_model != model_name or pipe is None:
pipe = load_model(model_name, enable_attention_slicing)
current_model = model_name
# Prompt-Strings kombinieren
full_prompt = prompt.strip()
if positive_prompts:
full_prompt += " " + positive_prompts.strip()
full_negative = negative_prompts.strip() if negative_prompts else ""
images = []
def progress_callback(pipeline, step: int, timestep: int, latents):
progress((step + 1) / num_inference_steps)
return {}
for i in range(num_images):
# Seed berechnen – Zufallsseed oder aufsteigend ab Basiswert
if randomize_seed:
seed = random.randint(0, np.iinfo(np.int32).max)
else:
seed = base_seed + i
generator = torch.Generator(device=device).manual_seed(seed)
# Inferenz durchführen
imgs = pipe(
prompt=full_prompt,
negative_prompt=full_negative,
width=width,
height=height,
guidance_scale=guidance_scale,
num_inference_steps=num_inference_steps,
generator=generator,
callback_on_step_end=progress_callback,
).images
images.extend(imgs)
return images
def reset_inputs():
"""
Setzt alle Eingaben zurück auf Standardwerte.
(Wird aktuell nicht direkt benutzt, da Reset per Seitenreload erfolgt)
"""
return (
"09-Deliberate-V2", # Angepasstes Standardmodell
"",
DEFAULT_POSITIVE,
DEFAULT_NEGATIVE,
1,
True,
512,
512,
7.5, # realistischere guidance_scale
5,
"1",
True,
)
with gr.Blocks(css=css, theme=gr.themes.Default(spacing_size="sm")) as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown("# 🤠 AI-Bildgenerator (mit automatischem Modell-Fallback)")
gr.Markdown(
"""
Achtung: Falls ein Modell gated* ist und keinen Zugriff erlaubt, wird
automatisch das öffentliche Stable Diffusion 1.5 Modell verwendet.
"""
)
code
if name == "main":
demo.launch(debug=False, show_api=False)