Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

kann man in diesem code eine funktion einfügen, dass über eine tastatur per return die…

  1. User

    kann man in diesem code eine funktion einfügen, dass über eine tastatur per return die generierung gestartet wird: app.py: 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

    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

    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

    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 = """ #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; /* Höhe Bildausgabebereich */ height: 404px !important; }

    /* Zentriere die gradio Row-Container (optional) */ .gr-row { width: 100%; max-width: 900px; margin-left: auto; margin-right: auto; }

    /* Standardspaltenbreiten mit flex */ #left-col { flex: 3 1 0; min-width: 0; } #right-col { flex: 2 1 0; min-width: 0; }

    /* Für Bildschirmbreiten 1040px bis 769px linke Spalte breiter */ @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; } }

    /* Unter 768px: mobile Ansicht, Spalten 100% breit (untereinander) */ @media (max-width: 768px) { #left-col, #right-col { flex: 1 1 100% !important; max-width: 100% !important; } }

    /* Responsive Text & Button Anpassungen */ @media (max-width: 1280px) { #col-container { max-width: 95%; } }

    /* Höhe automatisch anpassend bei Positiv-/Negativ-Prompts / / autom. wachsende Textboxen mit mind 4 und max 10 Zeilen */ textarea#positive-prompt, textarea#negative-prompt { min-height: 9em; max-height: 18em; height: auto; overflow-y: hidden; resize: vertical; } """

    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():
            # Linke Spalte mit elem_id für CSS-Ziel
            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"
                )
                prompt = gr.Textbox(
                    label="Hauptprompt",
                    lines=5,  # 5 Zeilen Feldhöhe
                    max_lines=10,
                    placeholder="Beschreibe das gewünschte Bild..."
                )
                positive_prompt = gr.Textbox(
                    label="Positiv-Prompts (durch Kommas getrennt)",
                    lines=5,  # 5 Zeilen Feldhöhe
                    max_lines=10,
                    interactive=True,
                    elem_id="positive-prompt",
                    value=DEFAULT_POSITIVE
                )
                negative_prompt = gr.Textbox(
                    label="Negativ-Prompts (durch Kommas getrennt)",
                    lines=5,  # 5 Zeilen Feldhöhe
                    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"
                        )
                    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")
    
                gr.HTML(
                    """
                    <script>
                    document.addEventListener('DOMContentLoaded', () => {
                        ['positive-prompt', 'negative-prompt'].forEach(id => {
                            const container = document.getElementById(id);
                            if (!container) return;
                            const ta = container.querySelector('textarea');
                            if (!ta) return;
                            function adjustHeight() {
                                ta.style.height = 'auto';
                                ta.style.height = ta.scrollHeight + 'px';
                            }
                            adjustHeight();
                            ta.addEventListener('input', adjustHeight);
                        });
                    });
                    </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.
                    """
                )
    
            # Rechte Spalte mit elem_id für CSS
            with gr.Column(scale=2, elem_id="right-col"):
                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)

  2. Assistant

    Ja, das ist möglich. Gradio bietet eine Möglichkeit, Tastaturereignisse speziell via Textbox.submit() abzufangen, was dann bei Tastendruck auf Enter/Taste Return ein Event feuert.

    In deinem Code hast du mehrere Textboxes, z.B. das Hauptprompt-Feld prompt und die Positiv-/Negativ-Prompt-Felder. Am sinnvollsten ist wohl, die Return-Taste im Hauptprompt-Feld (prompt) abzufangen, und damit die Bild-Generierung auszulösen.

    Vorgehensweise:

    Im Gradio-Interface kannst du für die Textbox-Komponente die .submit()-Methode verwenden, wo du eine Funktion bzw. einen Callback angibst, der beim Drücken von Return ausgeführt werden soll.

    Du möchtest also ungefähr folgendes ergänzen, nach der Definition von prompt:

    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,
    )
    

    Damit wird die Funktion infer genau wie beim Klick auf den "Bild generieren"-Button per Return in der prompt-Textbox ausgelöst.

    Komplettes Beispiel für den Einbau:

    Direkt nach der Definition von prompt in deinem Block:

    prompt = gr.Textbox(
        label="Hauptprompt",
        lines=5,  # 5 Zeilen Feldhöhe
        max_lines=10,
        placeholder="Beschreibe das gewünschte Bild..."
    )
    
    # Hier Return drücken erkennen und infer auslösen
    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,
    )
    

    Anmerkungen:

    • Du kannst submit auch für andere Felder nutzen, z.B. positive_prompt oder negative_prompt, falls du möchtest, dass auch dort Enter die Generierung startet.
    • Die Funktion infer wird nun sowohl per Button Klick als auch per Enter in der prompt-Textbox getriggert.
    • Auf der UI-Seite merkt der User nicht den Unterschied, die Bilder werden einfach wie gewohnt generiert.

    Falls du möchtest, dass Enter in mehreren Feldern die Generierung startet, kannst du für diese Felder gleich .submit(...) analog definieren.


    Falls du dazu noch Fragen hast oder Hilfe beim detaillierten Einbau brauchst, melde dich gern!

  3. User

    bitte komplett ausgeben mit kommentaren ergänzt

  4. Assistant

    Natürlich! Hier ist dein app.py-Code komplett mit der Ergänzung, dass durch Drücken der Return-Taste im Hauptprompt (prompt) die Bildgenerierung gestartet wird. Ich habe die neue prompt.submit(...)-Zeile an der richtigen Stelle sowie erklärende Kommentare eingefügt:

    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
    
    # 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
    
    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
    
    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 = """
    #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;
        /* Höhe Bildausgabebereich */
        height: 404px !important;
    }
    
    /* Zentriere die gradio Row-Container (optional) */
    .gr-row {
        width: 100%;
        max-width: 900px;
        margin-left: auto;
        margin-right: auto;
    }
    
    /* Standardspaltenbreiten mit flex */
    #left-col {
        flex: 3 1 0;
        min-width: 0;
    }
    #right-col {
        flex: 2 1 0;
        min-width: 0;
    }
    
    /* Für Bildschirmbreiten 1040px bis 769px linke Spalte breiter */
    @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;
        }
    }
    
    /* Unter 768px: mobile Ansicht, Spalten 100% breit (untereinander) */
    @media (max-width: 768px) {
        #left-col, #right-col {
            flex: 1 1 100% !important;
            max-width: 100% !important;
        }
    }
    
    /* Responsive Text & Button Anpassungen */
    @media (max-width: 1280px) {
        #col-container {
            max-width: 95%;
        }
    }
    
    /* Höhe automatisch anpassend bei Positiv-/Negativ-Prompts */
    /* autom. wachsende Textboxen mit mind 4 und max 10 Zeilen */
    textarea#positive-prompt,
    textarea#negative-prompt {
        min-height: 9em;
        max-height: 18em;
        height: auto;
        overflow-y: hidden;
        resize: vertical;
    }
    """
    
    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():
                # Linke Spalte mit elem_id für CSS-Ziel
                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"
                    )
                    prompt = gr.Textbox(
                        label="Hauptprompt",
                        lines=5,  # 5 Zeilen Feldhöhe
                        max_lines=10,
                        placeholder="Beschreibe das gewünschte Bild..."
                    )
    
                    # --- WICHTIGER NEUER TEIL ---
                    # Erlaube mit Return (Enter) im prompt Textfeld die Bildgenerierung zu starten
                    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,
                    )
                    # --- ENDE Neuer Teil ---
    
                    positive_prompt = gr.Textbox(
                        label="Positiv-Prompts (durch Kommas getrennt)",
                        lines=5,  # 5 Zeilen Feldhöhe
                        max_lines=10,
                        interactive=True,
                        elem_id="positive-prompt",
                        value=DEFAULT_POSITIVE
                    )
                    negative_prompt = gr.Textbox(
                        label="Negativ-Prompts (durch Kommas getrennt)",
                        lines=5,  # 5 Zeilen Feldhöhe
                        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"
                            )
                        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")
    
                    gr.HTML(
                        """
                        <script>
                        document.addEventListener('DOMContentLoaded', () => {
                            ['positive-prompt', 'negative-prompt'].forEach(id => {
                                const container = document.getElementById(id);
                                if (!container) return;
                                const ta = container.querySelector('textarea');
                                if (!ta) return;
                                function adjustHeight() {
                                    ta.style.height = 'auto';
                                    ta.style.height = ta.scrollHeight + 'px';
                                }
                                adjustHeight();
                                ta.addEventListener('input', adjustHeight);
                            });
                        });
                        </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.
                        """
                    )
    
                # Rechte Spalte mit elem_id für CSS
                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 klickt ausgelöstes Bildgenerieren (funktioniert weiter wie bisher)
        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)
    

    Was wurde ergänzt?

    • Direkt nach der Definition des prompt-Textbox wurde eine prompt.submit(...)-Anbindung hinzugefügt.
    • Diese sorgt dafür, dass beim Drücken der Return-Taste in prompt die infer-Funktion aufgerufen wird, mit den gleichen Inputs und Outputs wie beim Klick auf "Bild generieren".
    • So kann der Nutzer einfach mit Return die Generierung starten, ohne den Button klicken zu müssen.

    Wenn du möchtest, kannst du analog auch z.B. für positive_prompt und negative_prompt diese .submit(...)-Events ergänzen, falls da das gleiche Verhalten gewünscht ist.


    Bei weiteren Fragen oder Problemen einfach melden!

  5. User

    runtime error Exit code: 1. Reason: Traceback (most recent call last): File "/home/user/app/app.py", line 267, in positive_prompt, NameError: name 'positive_prompt' is not defined

  6. Assistant

    Der Fehler NameError: name 'positive_prompt' is not defined deutet darauf hin, dass du positive_prompt im prompt.submit benutzt, aber dieses Widget im Code erst danach definiert wird.

    Im von mir gelieferten Beispiel steht prompt.submit() direkt nach der Definition von prompt, aber vor den Definitionen von positive_prompt und anderen Widgets. Das funktioniert nicht, weil positive_prompt zum Zeitpunkt des Aufrufs von prompt.submit() noch nicht existiert.


    Lösung:

    Definiere zuerst alle Widgets, bevor du .submit() verwendest, die auf diese Widgets als Inputs zugreifen!

    Lass uns die Widget-Definitionen in der Reihenfolge bringen, sodass zuerst alle Inputs vorhanden sind, dann erst prompt.submit() gesetzt wird.

    Überarbeiteter Ausschnitt:

    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"
        )
        prompt = gr.Textbox(
            label="Hauptprompt",
            lines=5,
            max_lines=10,
            placeholder="Beschreibe das gewünschte Bild..."
        )
        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):
            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")
            reset_btn = gr.Button("Zurücksetzen")
    
        # Jetzt, nachdem alle Widgets definiert sind, hier den submit-Handler hinzufügen
        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,
        )
    

    Wichtige Zusammenfassung:

    • Definiere alle verwendeten Widgets zuerst.
    • Dann rufe .submit() oder click() auf und verwende die Widgets als Input-/Output-Referenzen.
    • Das verhindert NameError, weil alle Variablen schon im Scope sind.

    Falls du möchtest, kann ich dir auch den kompletten Code nochmal mit der korrigierten Reihenfolge schicken. Einfach Bescheid geben!

  7. User

    ja korrigiert

  8. Assistant

    Hier ist dein komplett korrigierter und kommentierter app.py, bei dem alle Widgets zuerst definiert werden, und danach erst .submit() am prompt gesetzt wird, damit keine NameError auftreten. Außerdem ist die Funktionalität mit Return-Taste zum Starten der Bildgenerierung enthalten:

    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
    
    # 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
    
    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
    
    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 = """
    #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;
        /* Höhe Bildausgabebereich */
        height: 404px !important;
    }
    
    /* Zentriere die gradio Row-Container (optional) */
    .gr-row {
        width: 100%;
        max-width: 900px;
        margin-left: auto;
        margin-right: auto;
    }
    
    /* Standardspaltenbreiten mit flex */
    #left-col {
        flex: 3 1 0;
        min-width: 0;
    }
    #right-col {
        flex: 2 1 0;
        min-width: 0;
    }
    
    /* Für Bildschirmbreiten 1040px bis 769px linke Spalte breiter */
    @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;
        }
    }
    
    /* Unter 768px: mobile Ansicht, Spalten 100% breit (untereinander) */
    @media (max-width: 768px) {
        #left-col, #right-col {
            flex: 1 1 100% !important;
            max-width: 100% !important;
        }
    }
    
    /* Responsive Text & Button Anpassungen */
    @media (max-width: 1280px) {
        #col-container {
            max-width: 95%;
        }
    }
    
    /* Höhe automatisch anpassend bei Positiv-/Negativ-Prompts */
    /* autom. wachsende Textboxen mit mind 4 und max 10 Zeilen */
    textarea#positive-prompt,
    textarea#negative-prompt {
        min-height: 9em;
        max-height: 18em;
        height: auto;
        overflow-y: hidden;
        resize: vertical;
    }
    """
    
    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():
                # Linke Spalte mit elem_id für CSS-Ziel
                with gr.Column(scale=3, elem_id="left-col"):
                    # --- ALLE INPUT-WIDGETS ZUERST DEFINIEREN ---
                    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=5,  # 5 Zeilen Feldhöhe
                        max_lines=10,
                        placeholder="Beschreibe das gewünschte Bild..."
                    )
                    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")
                        reset_btn = gr.Button("Zurücksetzen")
    
                    # --- WICHTIGER NEUER TEIL ---
                    # Return (Enter) im 'prompt' Textfeld startet ebenfalls die Bildgenerierung
                    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,
                    )
                    # --- ENDE Neuer Teil ---
    
                    gr.HTML(
                        """
                        <script>
                        document.addEventListener('DOMContentLoaded', () => {
                            ['positive-prompt', 'negative-prompt'].forEach(id => {
                                const container = document.getElementById(id);
                                if (!container) return;
                                const ta = container.querySelector('textarea');
                                if (!ta) return;
                                function adjustHeight() {
                                    ta.style.height = 'auto';
                                    ta.style.height = ta.scrollHeight + 'px';
                                }
                                adjustHeight();
                                ta.addEventListener('input', adjustHeight);
                            });
                        });
                        </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.
                        """
                    )
    
                # Rechte Spalte mit elem_id für CSS
                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 Klick startet Bildgenerierung (weiterhin wie bisher)
        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)
    

    Zusammenfassung:

    • Alle Widgets werden vor .submit() und .click() definiert.
    • prompt.submit() ist nach Definition aller Inputs platziert.
    • So kannst du nun direkt mit Enter in der Eingabe (Hauptprompt) die Bildgenerierung auslösen.
    • Button-Klick bleibt weiterhin erhalten.

    Falls noch Fragen sind, helfe ich gern!

  9. User

    fehler: ===== Application Startup at 2025-05-13 13:54:55 =====

    Traceback (most recent call last): File "/home/user/app/app.py", line 322, in outputs=[output_gallery], NameError: name 'output_gallery' is not defined Traceback (most recent call last): File "/home/user/app/app.py", line 322, in outputs=[output_gallery], NameError: name 'output_gallery' is not defined

  10. Assistant

    Der Fehler NameError: name 'output_gallery' is not defined bedeutet, dass die Variable output_gallery an der Stelle, wo du sie als Output verwendest (z.B. in prompt.submit() oder generate_btn.click()), noch nicht definiert ist.

    Im Code, den ich dir geschickt habe, hast du output_gallery erst nach der ganzen linken Spalten-Struktur definiert, was nach der prompt.submit()-Verwendung liegt.


    Wie lösen?

    Definiere output_gallery vor der Verwendung in den Output-Listen, also vor den .submit() und .click() Calls!


    Konkrete Änderung:

    1. Verschiebe die Definition des Galleries (output_gallery = gr.Gallery(...)) weiter nach oben, vor alle .submit() und .click()-Zuweisungen, also direkt nach der rechten Spalte (oder am besten gleich vor allem, wo Outputs benötigt werden).

    2. Alternativ ist es sinnvoll, zuerst alle Widgets zu definieren, danach erst Events zu registrieren.


    Beispiel: Widget-Definition für output_gallery vor event-Handlern

    Hier ein Ausschnitt, wie Du es machen kannst:

    with gr.Row():
        with gr.Column(scale=3, elem_id="left-col"):
            # Alle Input-Widgets hier
            model_dropdown = ...
            prompt = ...
            positive_prompt = ...
            negative_prompt = ...
            # ... etc.
    
            with gr.Accordion("Erweiterte Einstellungen", open=True):
                # Einstellungen wie seed_slider, randomize_seed_checkbox, usw.
    
            with gr.Row():
                generate_btn = gr.Button("Bild generieren", variant="primary")
                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"
            )
    
        # Jetzt, nachdem alle Widgets existieren, setzen wir Events:
    
        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,
        )
    
        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,
            ],
        )
    

    Gesamt: Damit output_gallery im Code nicht „verpasst“ wird, musst Du:

    • output_gallery definieren, bevor Du es als Output in .submit() oder .click() verwendest.
    • Falls Du über die gesamte Struktur unsicher bist, am besten zuerst alle Widgets (Inputs & Outputs) deklarieren, danach alle Events.

    Falls Du möchtest, kann ich Dir auch gerne den gesamten Code nochmal genau mit korrekter Reihenfolge der Widget-Definitionen und Events zuschicken. Möchtest Du das?

  11. User

    ja

  12. Assistant

    Hier ist dein kompletter, korrigierter app.py-Code mit allen Widgets inklusive output_gallery vor den Event-Handlern definiert und der .submit()-Funktion für die Return-Taste im Hauptprompt:

    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
    
    # 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
    
    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
    
    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 = """
    #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;
        /* Höhe Bildausgabebereich */
        height: 404px !important;
    }
    
    /* Zentriere die gradio Row-Container (optional) */
    .gr-row {
        width: 100%;
        max-width: 900px;
        margin-left: auto;
        margin-right: auto;
    }
    
    /* Standardspaltenbreiten mit flex */
    #left-col {
        flex: 3 1 0;
        min-width: 0;
    }
    #right-col {
        flex: 2 1 0;
        min-width: 0;
    }
    
    /* Für Bildschirmbreiten 1040px bis 769px linke Spalte breiter */
    @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;
        }
    }
    
    /* Unter 768px: mobile Ansicht, Spalten 100% breit (untereinander) */
    @media (max-width: 768px) {
        #left-col, #right-col {
            flex: 1 1 100% !important;
            max-width: 100% !important;
        }
    }
    
    /* Responsive Text & Button Anpassungen */
    @media (max-width: 1280px) {
        #col-container {
            max-width: 95%;
        }
    }
    
    /* Höhe automatisch anpassend bei Positiv-/Negativ-Prompts */
    /* autom. wachsende Textboxen mit mind 4 und max 10 Zeilen */
    textarea#positive-prompt,
    textarea#negative-prompt {
        min-height: 9em;
        max-height: 18em;
        height: auto;
        overflow-y: hidden;
        resize: vertical;
    }
    """
    
    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():
                # Linke Spalte mit elem_id für CSS-Ziel
                with gr.Column(scale=3, elem_id="left-col"):
                    # Alle Eingabewidgets:
                    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=5,
                        max_lines=10,
                        placeholder="Beschreibe das gewünschte Bild..."
                    )
                    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")
                        reset_btn = gr.Button("Zurücksetzen")
    
                    # Return in prompt triggert Bildgenerierung
                    # **ACHTUNG: output_gallery MUSS vorher definiert sein!**
                    # Daher wird output_gallery in rechter Spalte definiert – wir benötigen hier Zugriff,
                    # darum definieren wir output_gallery ab jetzt außerhalb der linken Spalte.
    
                # Rechte Spalte mit elem_id für CSS
                with gr.Column(scale=2, elem_id="right-col"):
                    output_gallery = gr.Gallery(
                        label="Ergebnisse",
                        show_label=False,
                        elem_id="output-gallery",
                        type="pil"
                    )
    
                # *** Jetzt alle Events einrichten – prompt.submit, Button-Klicks ***
                # prompt.submit: Return/Enter in prompt startet Infer
                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 auf Generieren-Button startet Infer
                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,
                )
    
                # Klick auf 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,
                    ],
                )
    
    
            gr.HTML(
                """
                <script>
                document.addEventListener('DOMContentLoaded', () => {
                    ['positive-prompt', 'negative-prompt'].forEach(id => {
                        const container = document.getElementById(id);
                        if (!container) return;
                        const ta = container.querySelector('textarea');
                        if (!ta) return;
                        function adjustHeight() {
                            ta.style.height = 'auto';
                            ta.style.height = ta.scrollHeight + 'px';
                        }
                        adjustHeight();
                        ta.addEventListener('input', adjustHeight);
                    });
                });
                </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.
                """
            )
    
    if __name__ == "__main__":
        demo.launch(debug=False, show_api=False)
    

    Wichtige Punkte:

    • output_gallery ist vor allen .submit() und .click() Event-Zuweisungen definiert.
    • Alle Eingabe-Widgets sind vor den Events definiert.
    • .submit() am prompt startet die Bildgenerierung durch Enter.
    • Die Button-Klicks sind unverändert.

    Wenn du den Code so ausführst, sollten weder NameError für output_gallery noch andere Widget-Namen auftreten.


    Falls falls du noch Fragen oder weitere Anpassungen brauchst, gerne melden!

  13. User

    return funktioniert nicht

  14. Assistant

    Danke fürs Feedback! Wenn der Return/Enter-Key im prompt-Textfeld nicht die Bildgenerierung startet, liegt das meistens daran, dass Gradio das Event nicht richtig abfängt — z.B. weil:

    • .submit() nicht korrekt angebunden wurde,
    • oder das prompt Widget in einer Blocks-Umgebung nicht das gewünschte Verhalten hat,
    • oder weil im Browser JavaScript-Ereignisse das Standardverhalten verhindern.

    Checkliste und Lösungsvorschläge

    1. Überprüfe, dass prompt.submit(...) tatsächlich definiert ist — im richtigen Scope und Reihenfolge (wie im letzten Beispiel).

    (Das hast du wohl schon.)


    2. Teste mit minimalem Beispiel, ob prompt.submit() grundsätzlich funktioniert:

    Hier ein ganz kleines Beispiel, um zu prüfen, ob Enter überhaupt abgefangen wird:

    import gradio as gr
    
    def echo(text):
        return f"Du hast eingegeben: {text}"
    
    with gr.Blocks() as demo:
        txt = gr.Textbox(label="Eingabe")
        output = gr.Textbox(label="Ausgabe")
        
        txt.submit(fn=echo, inputs=txt, outputs=output)
        
    demo.launch()
    

    Falls hier Enter nicht funktioniert, liegt es an Gradio-Browser-Umgebung.


    3. Bei textarea (mehrzeiligen Eingabefeldern) kann Enter standardmäßig eine neue Zeile erzeugen; Return-Submit wird oft nur bei input Textboxen einzeilig sicher getriggert.

    Dein prompt ist eine mehrzeilige Textbox (lines=5, max_lines=10). Deshalb:

    • Enter erzeugt eine neue Zeile, aber triggert kein Submit.

    Gradio unterstützt kein Submit-Event auf textarea per Enter-Taste standardmäßig, weil Enter sonst zum Zeilenumbruch dient.


    Lösung:

    Variante A: Andere Taste zum Auslösen der Bildgenerierung wählen

    Z.B. einen separaten Button klicken, oder eine spezielle Tastenkombination.


    Variante B: Mit JavaScript Enter als Submit “umsetzen”

    Füge folgendes JavaScript (über gr.HTML) hinzu, das beim Drücken von Enter im prompt (textarea) ein Submit auslöst und Zeilenumbruch nur bei Shift+Enter erlaubt:

    gr.HTML(
        """
        <script>
        document.addEventListener('DOMContentLoaded', () => {
            let ta = document.querySelector('textarea[data-testid="textbox-prompt"]') || document.querySelector('#prompt textarea');
            if (ta) {
                ta.addEventListener('keydown', function(e) {
                    if (e.key === 'Enter' && !e.shiftKey) {
                        e.preventDefault();
                        ta.closest('form').dispatchEvent(new Event('submit', {cancelable: true}));
                    }
                });
            }
        });
        </script>
        """
    )
    

    Oder gezielter (da dein textbox vermutlich die id prompt hat, könnte das so gehen):

    <script>
    document.addEventListener('DOMContentLoaded', () => {
        const ta = document.querySelector('#prompt textarea');
        if (ta) {
            ta.addEventListener('keydown', (e) => {
                if(e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    ta.dispatchEvent(new Event('change', { bubbles: true }));
                    ta.closest('form').dispatchEvent(new Event('submit', {cancelable: true}));
                }
            });
        }
    });
    </script>
    

    Wichtig: Dieses JS löst beim Enter die Submit-Ausführung aus. Shift+Enter erzeugt einen Zeilenumbruch.


    Umsetzung in deinem Code

    Füge den JS-Block nach der prompt Definition und innerhalb deines Gradio Blocks als gr.HTML ein (etwa direkt nach den Widgets):

    gr.HTML(
        """
        <script>
        document.addEventListener('DOMContentLoaded', () => {
            const ta = document.querySelector('#prompt textarea');
            if (ta) {
                ta.addEventListener('keydown', (e) => {
                    if(e.key === 'Enter' && !e.shiftKey) {
                        e.preventDefault();
                        ta.dispatchEvent(new Event('change', { bubbles: true }));
                        ta.closest('form').dispatchEvent(new Event('submit', {cancelable: true}));
                    }
                });
            }
        });
        </script>
        """
    )
    

    Damit wird das prompt.submit()-Event tatsächlich ausgelöst, wenn du Enter drückst.


    Zusammenfassung

    • Mehrzeilige Gradio Textbox akzeptieren Enter als newline, nicht als Submit.
    • Das Verhalten per JS anpassen, um Enter (ohne Shift) als Submit auszuführen.
    • Shift+Enter bleibt normal für Zeilenumbruch.

    Falls du magst, kann ich dir den kompletten Code mit eingebautem JS nochmal anpassen — einfach Bescheid geben!

  15. User

    ja

  16. Assistant

    Hier ist dein vollständiger, korrigierter Code, inklusive dem JavaScript-Snippet, das im mehrzeiligen Eingabefeld (prompt Textbox) per Enter-Taste die Bildgenerierung auslöst (Return = Submit), wobei Shift+Enter weiterhin eine neue Zeile erzeugt:

    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
    
    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
    
    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 = """
    #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;
    }
    
    /* Zentriere die gradio Row-Container */
    .gr-row {
        width: 100%;
        max-width: 900px;
        margin-left: auto;
        margin-right: auto;
    }
    
    /* Flex Standardspaltenbreite */
    #left-col {
        flex: 3 1 0;
        min-width: 0;
    }
    #right-col {
        flex: 2 1 0;
        min-width: 0;
    }
    
    /* Responsive für verschiedene Bildschirmbreiten */
    @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;
        }
    }
    
    /* Textarea Höhe anpassen */
    textarea#positive-prompt,
    textarea#negative-prompt {
        min-height: 9em;
        max-height: 18em;
        height: auto;
        overflow-y: hidden;
        resize: vertical;
    }
    """
    
    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"
                    )
                    prompt = gr.Textbox(
                        label="Hauptprompt",
                        lines=5,
                        max_lines=10,
                        placeholder="Beschreibe das gewünschte Bild..."
                    )
                    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")
                        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"
                    )
    
                # --- Return-Taste in prompt macht Submit (Enter = Submit, Shift+Enter = Zeilenumbruch) ---
                gr.HTML(
                    """
                    <script>
                    document.addEventListener('DOMContentLoaded', () => {
                        const ta = document.querySelector('#prompt textarea');
                        if (ta) {
                            ta.addEventListener('keydown', (e) => {
                                if(e.key === 'Enter' && !e.shiftKey) {
                                    e.preventDefault();
                                    // Change Event auslösen, damit Gradio Kenntnis erhält
                                    ta.dispatchEvent(new Event('change', { bubbles: true }));
                                    // Submit Event auslösen
                                    ta.closest('form').dispatchEvent(new Event('submit', {cancelable: true}));
                                }
                            });
                        }
                    });
                    </script>
                    """
                )
    
                # Gradio-Events nur **nach** Bereich mit Widgets definieren!
                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,
                )
    
                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,
                    ],
                )
    
    
            gr.HTML(
                """
                <script>
                document.addEventListener('DOMContentLoaded', () => {
                    ['positive-prompt', 'negative-prompt'].forEach(id => {
                        const container = document.getElementById(id);
                        if (!container) return;
                        const ta = container.querySelector('textarea');
                        if (!ta) return;
                        function adjustHeight() {
                            ta.style.height = 'auto';
                            ta.style.height = ta.scrollHeight + 'px';
                        }
                        adjustHeight();
                        ta.addEventListener('input', adjustHeight);
                    });
                });
                </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.
                """
            )
    
    if __name__ == "__main__":
        demo.launch(debug=False, show_api=False)
    

    So funktioniert das:

    • Das JS-Event blockiert im prompt (mehrzeilig) die normale Enter-Taste.
    • Wenn Enter gedrückt wird ohne Shift, wird das Submit-Event ausgelöst (gradio führt infer() aus).
    • Shift+Enter erlaubt weiterhin den normalen Zeilenumbruch.

    Probiere das aus — jetzt sollte Return/Enter im Hauptprompt die Bildgenerierung anstoßen.

    Wenn noch Fragen sind oder du weitere Anpassungen brauchst, einfach Bescheid!

  17. User

    geht nicht

  18. Assistant

    Wenn die JavaScript-Lösung mit prompt als mehrzeilige Textbox nicht funktioniert, kann es an Gradio-Versionen, Framework-Änderungen oder eventuellen DOM-Unterschieden liegen.

    Ich habe hier eine einfache und robuste Alternative erarbeitet, mit der Enter die Funktion auslöst — und zwar indem wir anstelle einer mehrzeiligen Textbox für den Hauptprompt ein einzeiliges Textfeld mit gedrückter Eingabetaste als Trigger nutzen.


    Schritt 1: Hauptprompt als einzeilige Eingabe (gr.Textbox(lines=1))

    Ändere deine Definition so:

    prompt = gr.Textbox(
        label="Hauptprompt",
        lines=1,  # Nur eine Zeile!
        max_lines=1,
        placeholder="Beschreibe das gewünschte Bild..."
    )
    

    Jetzt ist es ein ganz normales Input-Feld, damit submit() automatisch bei Enter funktioniert.


    Schritt 2: .submit() unverändert verwenden

    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,
    )
    

    Damit wird jetzt Enter in der prompt Textbox zuverlässig ausgelöst.


    Schritt 3 (Optional): Mehrzeiliges Hauptprompt trotzdem möglich machen

    Falls dein Prompt mehrzeilig sein soll, dann kannst du es so gestalten, dass Enter nicht direkt generiert, sondern Shift+Enter für Zeilenumbruch, und ein extra Button oder Hotkey das Bild startet.

    Alternativ kann man ein zweites Feld für kurze Prompts machen oder das textuelle Eingabefeld verkürzen.


    Zusammenfassung

    • Enter als Submit bei einer mehrzeiligen gr.Textbox(lines>1) wird standardmäßig nicht unterstützt, weil Enter ein Zeilenumbruch sein soll.
    • Hauptprompt zu lines=1 ändern, dann .submit() wird durch Enter ausgelöst.
    • Wenn du mehrzeilige Eingabe möchtest, brauchst du eine andere UX — z.B. Button oder Hotkey.

    Falls du möchtest, kann ich den kompletten Code anpassen mit prompt als einzeiligem Textfeld — willst du das?

  19. User

    kompletten Code anpassen mit prompt als einzeiligem Textfeld

  20. Assistant

    Hier ist dein kompletter Code angepasst, so dass das Hauptprompt-Feld nur eine Zeile (lines=1) hat und Enter die Bildgenerierung auslöst – genau wie bei einem klassischen Eingabefeld:

    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
    
    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
    
    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 = """
    #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;
        }
    }
    """
    
    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"
                    )
                    # WICHTIG: Hauptprompt ist einzeilig, um Enter als Submit zu ermöglichen
                    prompt = gr.Textbox(
                        label="Hauptprompt",
                        lines=1,
                        max_lines=1,
                        placeholder="Beschreibe das gewünschte Bild..."
                    )
                    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")
                        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
    
                # Enter (Submit) im Hauptprompt löst infer aus
                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,
                )
    
                # Button-Klick für Bild generieren
                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,
                )
    
                # Button-Klick für Reset
                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,
                    ],
                )
    
    
            gr.HTML(
                """
                <script>
                document.addEventListener('DOMContentLoaded', () => {
                    ['positive-prompt', 'negative-prompt'].forEach(id => {
                        const container = document.getElementById(id);
                        if (!container) return;
                        const ta = container.querySelector('textarea');
                        if (!ta) return;
                        function adjustHeight() {
                            ta.style.height = 'auto';
                            ta.style.height = ta.scrollHeight + 'px';
                        }
                        adjustHeight();
                        ta.addEventListener('input', adjustHeight);
                    });
                });
                </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.
                """
            )
    
    if __name__ == "__main__":
        demo.launch(debug=False, show_api=False)
    

    Wichtig

    • Hauptprompt ist lines=1 und damit einzeilig.
    • prompt.submit(...) löst automatisiert das Event bei Enter-Taste aus.
    • Falls du mehrzeilige Prompts brauchst, ist Enter => neue Zeile und Submit per Button empfohlen.

    Wenn noch Fragen sind oder du weitere Wünsche hast, lass es mich wissen!