Hier der vollständige Code mit korrigierter Einrückung beim gr.Markdown (die Hilfetexte befinden sich jetzt immer außerhalb vom with gr.Row(): Block, richtig eingerückt):
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
# Token aus Umgebungsvariable (z.B. HF_TOKEN) laden
token = os.getenv("HF_TOKEN")
device = "cuda" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
# Modell Liste mit Fallback
MODEL_MAP = {
"FLUX.1-schnell": "black-forest-labs/FLUX.1-schnell", # schnellstes, kleines Modell
"Stable Diffusion 1.5": "runwayml/stable-diffusion-v1-5", # Standardmodell, schnell und effizient
"DreamShaper v8": "Lykon/DreamShaper-v8", # künstlerisch, mittlere Geschwindigkeit
"Anything-v4": "andite/anything-v4", # mittlere bis langsame Geschwindigkeit
"Anything-v5": "andite/anything-v5", # größer als v4, etwas langsamer
"OpenJourney v4": "prompthero/openjourney-v4", # meist am langsamsten wegen Komplexitä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"
)
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"
)
pipe = None
current_model = None
def load_model(model_name, enable_attention_slicing=True):
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}")
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:
# Zugriff verweigert / Modell gated -> fallback auf SD 1.5 ohne Token nötig
print(f"Fehler beim Laden von {model_repo_id}: {e}")
fallback_id = MODEL_MAP["Stable Diffusion 1.5"]
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),
):
global pipe, current_model
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)
if current_model != model_name or pipe is None:
pipe = load_model(model_name, enable_attention_slicing)
current_model = model_name
full_prompt = prompt.strip()
if positive_prompts:
full_prompt += " " + positive_prompts.strip()
full_negative = negative_prompts.strip() if negative_prompts else ""
images = []
for i in range(num_images):
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)
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=progress,
).images
images.extend(imgs)
return images
def reset_inputs():
return (
"FLUX.1-schnell",
"",
DEFAULT_POSITIVE,
DEFAULT_NEGATIVE,
1,
True,
512,
512,
0.6, # guidance standardmäßig 0.6
5, # inference standardmäßig 5
"1",
True,
)
css = """
#col-container {
max-width: 80%;
margin: 0 auto;
}
#output-gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 16px;
}
/* Dunklere Farbe für Range-Slider */
input[type=range] {
accent-color: #444444;
}
/* Responsive Text & Button Anpassungen */
@media (max-width: 768px) {
#col-container {
max-width: 95%;
}
}
"""
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 automat. Modell-Fallback)")
gr.Markdown(
"""
**Achtung:** Falls ein Modell gated ist und du keinen Zugriff hast, wird
automatisch das öffentliche Stable Diffusion 1.5 Modell verwendet.
"""
)
with gr.Row():
with gr.Column(scale=2):
model_dropdown = gr.Dropdown(
label="Modell",
choices=list(MODEL_MAP.keys()),
value="FLUX.1-schnell",
interactive=True,
info="Gated Modelle benötigen ggf. Token & Freischaltung"
)
prompt = gr.Textbox(
label="Hauptprompt",
lines=4,
max_lines=10,
placeholder="Beschreibe das gewünschte Bild..."
)
positive_prompt = gr.Textbox(
label="Positiv-Prompts (durch Kommas getrennt)",
lines=2,
value=DEFAULT_POSITIVE
)
negative_prompt = gr.Textbox(
label="Negativ-Prompts (durch Kommas getrennt)",
lines=2,
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, 512, value=512, step=64, label="Breite (max. 512 empfohlen)")
height = gr.Slider(256, 512, 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
)
with gr.Row():
generate_btn = gr.Button("Bild generieren", variant="primary")
reset_btn = gr.Button("Zurücksetzen")
# <-- hier keine Einrückung! Markdown außerhalb der Row:
gr.Markdown(
"""
**Hinweise:**
- *Guidance* bestimmt, wie strikt sich das Modell an den Prompt hält.
- *Inference* nutzt erlerntes Wissen, um Bilder zu generieren.
- Bei gated Modellen prüfe deinen Zugriff und Token.
- Für niedrige Hardware: max. 512x512 und Attention Slicing aktivieren.
"""
)
with gr.Column(scale=2):
output_gallery = gr.Gallery(
label="Ergebnisse",
show_label=False,
elem_id="output-gallery",
type="pil"
)
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,
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,
],
)
if __name__ == "__main__":
demo.launch(debug=False, show_api=False)
Jetzt liegt das gr.Markdown() außerhalb des with gr.Row() Blocks, genau so, dass der Fehler IndentationError: unexpected indent nicht mehr auftritt.
Falls du weitere Fragen hast, gern melden!