Hier ist dein kompletter, lauffähiger Code, der alle bisherigen Anforderungen erfüllt:
- Beim Hauptprompt eine mehrzeilige Eingabe (5 Zeilen)
- Enter (ohne Shift) löst Bildgenerierung aus (Submit)
- Shift+Enter fügt eine neue Zeile ein
- Alle Variablen und Funktionen sind enthalten
- Button für Bild generieren hat eine eindeutige ID
- JavaScript sorgt für das gewünschte Tastaturverhalten
import os
import gradio as gr
import numpy as np
import random
from diffusers import DiffusionPipeline
import torch
from huggingface_hub import login
from huggingface_hub.utils import RepositoryNotFoundError, GatedRepoError
# --- Konstanten und Einstellungen ---
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
MODEL_MAP = {
"FLUX.1-schnell": "black-forest-labs/FLUX.1-schnell",
"Stable Diffusion 1.5": "runwayml/stable-diffusion-v1-5",
"DreamShaper v8": "Lykon/DreamShaper-v8",
"Anything-v4": "andite/anything-v4",
"Anything-v5": "andite/anything-v5",
"OpenJourney v4": "prompthero/openjourney-v4",
}
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, poor depth of field"
)
pipe = None
current_model = None
# --- Funktionen ---
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}")
if token:
print("Authentifiziere mit Hugging Face Token...")
login(token)
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["Stable Diffusion 1.5"]
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),
):
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 = []
def progress_callback(pipeline, step: int, timestep: int, latents):
progress((step + 1) / num_inference_steps)
return {}
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_on_step_end=progress_callback,
).images
images.extend(imgs)
return images
def reset_inputs():
return (
"FLUX.1-schnell",
"",
DEFAULT_POSITIVE,
DEFAULT_NEGATIVE,
1,
True,
512,
512,
0.6,
5,
"1",
True,
)
# --- CSS ---
css = """
#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: 404px !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;
}
}
"""
# --- 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 du keinen Zugriff hast, 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="FLUX.1-schnell",
interactive=True,
info="Gated Modelle benötigen ggf. Token & Freischaltung"
)
# Hauptprompt mehrzeilig mit 5 Zeilen + elem_id für JS
prompt = gr.Textbox(
label="Hauptprompt",
lines=5,
max_lines=5,
placeholder="Beschreibe das gewünschte Bild...",
elem_id="prompt"
)
positive_prompt = gr.Textbox(
label="Positiv-Prompts (durch Kommas getrennt)",
lines=5,
max_lines=10,
interactive=True,
elem_id="positive-prompt",
value=DEFAULT_POSITIVE
)
negative_prompt = gr.Textbox(
label="Negativ-Prompts (durch Kommas getrennt)",
lines=5,
max_lines=10,
interactive=True,
elem_id="negative-prompt",
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"
)
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", elem_id="generate-btn")
reset_btn = gr.Button("Zurücksetzen")
with gr.Column(scale=2, elem_id="right-col"):
output_gallery = gr.Gallery(
label="Ergebnisse",
show_label=False,
elem_id="output-gallery",
type="pil"
)
# Events erst nach allen Widgets
# Submit via Enter im Prompt (wird durch JS getriggert)
prompt.submit(
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,
)
# Klick am Button
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,
)
# Zurücksetzen Button
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,
],
)
# JavaScript sorgt für Enter=Submit & Shift+Enter=Zeilenumbruch
gr.HTML(
"""
<script>
document.addEventListener('DOMContentLoaded', () => {
const promptContainer = document.getElementById('prompt');
if (!promptContainer) return;
const textarea = promptContainer.querySelector('textarea');
if (!textarea) return;
textarea.addEventListener('keydown', function(event) {
// Enter ohne Shift --> Submit auslösen
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault(); // Zeilenumbruch verhindern
const generateBtn = document.getElementById('generate-btn');
if (generateBtn) {
generateBtn.click();
}
}
// Shift+Enter erlaubt normalen Zeilenumbruch => keine Aktion hier
});
});
</script>
"""
)
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 (zugangs-/funktionsbeschränkt) Zugriff und Token prüfen.
- Für niedrige Hardware max. 512x512 Pixel einstellen und Attention Slicing aktivieren.
- **Shift+Enter** fügt eine neue Zeile ein, **Enter** startet die Bildgenerierung.
"""
)
if __name__ == "__main__":
demo.launch(debug=False, show_api=False)
Zum Start
- Installiere nötige Pakete wenn nicht vorhanden:
pip install gradio diffusers transformers huggingface_hub accelerate torch
- Optional: Setze dein Huggingface-Token als Umgebungsvariable
HF_TOKEN, wenn du gated Modelle nutzt:
export HF_TOKEN="dein_token"
- Starte das Skript mit Python.
Bei Fragen oder weiteren Anpassungen melde dich gern!