Spaces:
Paused
Paused
Download app.py from BTrain/Shnell: direct link, hf CLI and curl.
- Browser
- Download file 19 kB
-
https://huggingface.co/spaces/BTrain/Shnell/resolve/main/app.py
- Command line
-
hf download hf://spaces/BTrain/Shnell/app.py
-
curl -L -o app.py https://huggingface.co/spaces/BTrain/Shnell/resolve/main/app.py
19 kB
| import gradio as gr | |
| import numpy as np | |
| import random | |
| import spaces | |
| import torch | |
| from diffusers import DiffusionPipeline | |
| from huggingface_hub import upload_file | |
| from datetime import datetime | |
| import os | |
| dtype = torch.bfloat16 | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| pipe = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=dtype).to(device) | |
| MAX_SEED = np.iinfo(np.int32).max | |
| WIDTH = 700 | |
| HEIGHT = 900 | |
| PRESETS = { | |
| "Gothic Woman": "gothic woman, dark moody atmosphere, candlelit, pale skin, dramatic makeup, intricate clothing, professional photography", | |
| "D&D Warrior": "fantasy warrior woman, d&d style, armored, heroic pose, magical atmosphere, cinematic lighting, professional art", | |
| "Cinematic Portrait": "cinematic portrait, professional lighting, volumetric, warm tones, shallow depth of field, film camera aesthetic", | |
| "Monster/Horror": "dark creature, horror aesthetic, moody lighting, gothic, atmospheric, creepy, professional photography", | |
| "Superhero": "superhero woman, comic book style, powerful pose, vibrant colors, dramatic lighting, action packed", | |
| "Star Wars": "star wars character, sci-fi, futuristic, iconic lighting, spaceship interior, professional character design", | |
| "Grim Fairy Tale": "dark fairy tale character, gothic fantasy, moody shadows, intricate details, cinematic, atmospheric", | |
| } | |
| WILDCARDS = { | |
| "Gothic": [ | |
| "pale, porcelain skin, dark red lips", | |
| "black hair, gothic makeup, moody", | |
| "candlelit, shadows, dramatic lighting", | |
| "intricate black clothing, lace details", | |
| "dark gothic aesthetic, mysterious", | |
| ], | |
| "D&D Fantasy": [ | |
| "fantasy armor, metallic, intricate", | |
| "mystical aura, magical glowing effects", | |
| "heroic fantasy pose, epic lighting", | |
| "elaborate fantasy clothing, enchanted", | |
| "fantasy warrior, strong pose, determined", | |
| ], | |
| "Cinematic": [ | |
| "professional lighting, volumetric", | |
| "warm color grading, film aesthetic", | |
| "shallow depth of field, bokeh", | |
| "cinematic composition, framing", | |
| "professional color grading, warm tones", | |
| ], | |
| "Monster/Horror": [ | |
| "dark creature, unsettling, atmospheric", | |
| "creepy aesthetic, horror vibes", | |
| "moody shadows, low key lighting", | |
| "grotesque details, dark fantasy", | |
| "haunting appearance, eerie atmosphere", | |
| ], | |
| } | |
| def infer(prompt, steps, progress=gr.Progress(track_tqdm=True)): | |
| try: | |
| seed = random.randint(0, MAX_SEED) | |
| generator = torch.Generator().manual_seed(seed) | |
| image = pipe( | |
| prompt=prompt, | |
| width=WIDTH, | |
| height=HEIGHT, | |
| num_inference_steps=max(1, min(int(steps), 20)), | |
| generator=generator, | |
| guidance_scale=0.0, | |
| ).images[0] | |
| out_path = f"/tmp/generated_{seed}.png" | |
| image.save(out_path) | |
| try: | |
| hf_token = os.getenv("HF_TOKEN") | |
| if hf_token: | |
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") | |
| filename = f"generated_{timestamp}_{seed}.png" | |
| upload_file( | |
| path_or_fileobj=out_path, | |
| path_in_repo=filename, | |
| repo_id="BTrain/shnell-generated-images", | |
| repo_type="dataset", | |
| token=hf_token, | |
| commit_message=f"Generated: {prompt[:50]}" | |
| ) | |
| except Exception as e: | |
| pass | |
| return image, gr.update(value=out_path, visible=True) | |
| except Exception as e: | |
| error_msg = "⚠️ Out of GPU credits! Check back tomorrow for free quota reset." | |
| return None, gr.update(value=error_msg, visible=True) | |
| def randomize_wildcard(category): | |
| if category not in WILDCARDS: | |
| return "" | |
| entries = WILDCARDS[category] | |
| return random.choice(entries) if entries else "" | |
| def use_wildcard_prompt(wildcard_text, prompt_input): | |
| if wildcard_text: | |
| base = prompt_input.strip() | |
| return f"{base}, {wildcard_text}".strip() if base else wildcard_text | |
| return prompt_input | |
| def update_steps_display(steps_value): | |
| """Update the display HTML when steps change""" | |
| return f'<div id="steps-display">{int(steps_value)} steps</div>' | |
| css = """ | |
| [class*="toast"], [class*="notification"], [class*="info"], [class*="loading"] { | |
| display: none !important; | |
| } | |
| .gradio-container > div > div { | |
| min-height: auto !important; | |
| } | |
| [class*="progress"], [class*="spinner"], [class*="loader"] { | |
| display: none !important; | |
| } | |
| .gradio-container { | |
| max-width: 700px !important; | |
| padding: 2px !important; | |
| padding-top: 0 !important; | |
| } | |
| #col-container { | |
| margin: 0 auto; | |
| margin-top: 0 !important; | |
| max-width: 700px; | |
| width: 100%; | |
| gap: 0 !important; | |
| position: relative; | |
| } | |
| #sticky-controls { | |
| position: sticky; | |
| top: 0; | |
| z-index: 100; | |
| background: var(--body-background-fill); | |
| padding-top: 2px; | |
| padding-bottom: 2px; | |
| margin-bottom: 0 !important; | |
| flex-wrap: nowrap !important; | |
| flex-direction: row !important; | |
| gap: 8px !important; | |
| height: 60px !important; | |
| min-height: 60px !important; | |
| } | |
| #generate-btn, #save-btn { | |
| flex: 1 1 30% !important; | |
| min-width: 0 !important; | |
| } | |
| #generate-btn, #save-btn { | |
| font-size: 15px !important; | |
| } | |
| #combo-btn, #autoloop-btn { | |
| flex: 0 0 52px !important; | |
| min-width: 52px !important; | |
| max-width: 52px !important; | |
| padding: 0 !important; | |
| font-size: 18px !important; | |
| } | |
| #autoloop-btn { | |
| background-color: #e74c3c !important; | |
| border-color: #e74c3c !important; | |
| color: white !important; | |
| } | |
| #sticky-controls button { | |
| width: 100% !important; | |
| height: 44px !important; | |
| min-height: 44px !important; | |
| } | |
| #result-hidden { | |
| display: none !important; | |
| } | |
| #display-wrap { | |
| width: 100vw; | |
| max-width: 100vw; | |
| margin-left: calc(50% - 50vw); | |
| margin-right: calc(50% - 50vw); | |
| aspect-ratio: 700 / 900; | |
| background: #111; | |
| overflow: hidden; | |
| position: relative; | |
| } | |
| #display-img { | |
| width: 100%; | |
| height: 100%; | |
| object-fit: cover; | |
| display: block; | |
| } | |
| #side-controls-right, #side-controls-left { | |
| position: absolute; | |
| top: 50%; | |
| transform: translateY(-50%); | |
| display: flex; | |
| flex-direction: column; | |
| gap: 32px; | |
| z-index: 50; | |
| pointer-events: auto; | |
| } | |
| #side-controls-right { | |
| right: 2px; | |
| } | |
| #side-controls-left { | |
| left: 2px; | |
| } | |
| .side-btn { | |
| width: 24px; | |
| height: 64px; | |
| border: none; | |
| border-radius: 6px; | |
| font-size: 10px !important; | |
| font-weight: 600; | |
| cursor: pointer; | |
| opacity: 0.5; | |
| transition: opacity 0.2s ease, transform 0.1s ease; | |
| display: flex; | |
| align-items: center; | |
| justify-content: center; | |
| padding: 0 !important; | |
| user-select: none; | |
| -webkit-user-select: none; | |
| } | |
| .side-btn:active { | |
| opacity: 0.75; | |
| transform: scale(0.95); | |
| } | |
| .side-btn:hover { | |
| opacity: 0.65; | |
| } | |
| #side-gen-btn, #side-gen-btn-left { | |
| background-color: #ff9c3c !important; | |
| border-color: #ff9c3c !important; | |
| color: white !important; | |
| } | |
| #side-save-btn, #side-save-btn-left { | |
| background-color: #6c757d !important; | |
| border-color: #6c757d !important; | |
| color: white !important; | |
| } | |
| @media (min-width: 700px) { | |
| #display-wrap { | |
| width: 700px; | |
| max-width: 700px; | |
| margin-left: auto; | |
| margin-right: auto; | |
| } | |
| } | |
| #steps-row { | |
| margin-top: 16px; | |
| padding: 0 8px; | |
| } | |
| #steps-panel { | |
| display: flex; | |
| align-items: center; | |
| justify-content: center; | |
| gap: 16px; | |
| width: 100%; | |
| padding: 10px 0; | |
| } | |
| #steps-minus, #steps-plus { | |
| flex: 0 0 56px !important; | |
| max-width: 56px !important; | |
| height: 56px !important; | |
| min-height: 56px !important; | |
| font-size: 26px !important; | |
| font-weight: 700 !important; | |
| border-radius: 50% !important; | |
| } | |
| #steps-display { | |
| flex: 0 0 140px; | |
| text-align: center; | |
| font-size: 20px; | |
| font-weight: 600; | |
| } | |
| #steps-label { | |
| text-align: center; | |
| font-size: 13px; | |
| opacity: 0.7; | |
| margin-top: 2px; | |
| } | |
| #presets-section { | |
| margin-top: 24px; | |
| padding: 0 8px; | |
| border-top: 1px solid rgba(200, 200, 200, 0.2); | |
| padding-top: 16px; | |
| } | |
| #presets-label { | |
| text-align: center; | |
| font-size: 13px; | |
| opacity: 0.7; | |
| margin-bottom: 12px; | |
| } | |
| .preset-btn { | |
| flex: 1; | |
| height: 40px !important; | |
| min-height: 40px !important; | |
| font-size: 13px !important; | |
| } | |
| #wildcards-section { | |
| margin-top: 24px; | |
| padding: 0 8px; | |
| border-top: 1px solid rgba(200, 200, 200, 0.2); | |
| padding-top: 16px; | |
| margin-bottom: 40px; | |
| } | |
| #wildcards-label { | |
| text-align: center; | |
| font-size: 13px; | |
| opacity: 0.7; | |
| margin-bottom: 12px; | |
| } | |
| #wildcard-controls { | |
| display: flex; | |
| gap: 8px; | |
| margin-bottom: 12px; | |
| } | |
| #wildcard-category { | |
| flex: 1; | |
| } | |
| #randomize-btn { | |
| flex: 0 0 120px !important; | |
| max-width: 120px !important; | |
| height: 40px !important; | |
| min-height: 40px !important; | |
| font-size: 13px !important; | |
| } | |
| #wildcard-result { | |
| background: rgba(100, 100, 100, 0.1); | |
| border: 1px solid rgba(200, 200, 200, 0.3); | |
| border-radius: 6px; | |
| padding: 10px; | |
| margin-bottom: 8px; | |
| font-size: 13px; | |
| min-height: 40px; | |
| display: flex; | |
| align-items: center; | |
| word-break: break-word; | |
| } | |
| #use-wildcard-btn { | |
| width: 100% !important; | |
| height: 40px !important; | |
| min-height: 40px !important; | |
| font-size: 13px !important; | |
| } | |
| """ | |
| with gr.Blocks(css=css) as demo: | |
| with gr.Column(elem_id="col-container"): | |
| with gr.Row(elem_id="sticky-controls"): | |
| autoloop_button = gr.Button("\u27F3", elem_id="autoloop-btn") | |
| run_button = gr.Button("Generate", variant="primary", elem_id="generate-btn") | |
| download_button = gr.DownloadButton("Save", visible=False, elem_id="save-btn") | |
| combo_button = gr.Button("\u26A1", elem_id="combo-btn") | |
| result = gr.Image(show_label=False, elem_id="result-hidden") | |
| gr.HTML(''' | |
| <div id="display-wrap"> | |
| <img id="display-img" src=""> | |
| <div id="side-controls-left"> | |
| <button id="side-gen-btn-left" class="side-btn" title="Generate">GEN</button> | |
| <button id="side-save-btn-left" class="side-btn" title="Save">S</button> | |
| </div> | |
| <div id="side-controls-right"> | |
| <button id="side-gen-btn" class="side-btn" title="Generate">GEN</button> | |
| <button id="side-save-btn" class="side-btn" title="Save">S</button> | |
| </div> | |
| </div> | |
| ''') | |
| prompt = gr.Textbox( | |
| label=None, | |
| show_label=False, | |
| placeholder="Describe the image...", | |
| lines=2, | |
| ) | |
| steps_state = gr.Number(value=4, visible=False) | |
| with gr.Column(elem_id="steps-row"): | |
| gr.HTML('<div id="steps-label">Generation steps (quality)</div>') | |
| with gr.Row(elem_id="steps-panel"): | |
| steps_minus = gr.Button("\u2212", elem_id="steps-minus") | |
| steps_display = gr.HTML('<div id="steps-display">4 steps</div>', elem_id="steps-display-html") | |
| steps_plus = gr.Button("+", elem_id="steps-plus") | |
| with gr.Column(elem_id="presets-section"): | |
| gr.HTML('<div id="presets-label">Quick Presets</div>') | |
| with gr.Row(): | |
| preset_gothic = gr.Button("Gothic Woman", elem_classes="preset-btn") | |
| preset_dnd = gr.Button("D&D Warrior", elem_classes="preset-btn") | |
| with gr.Row(): | |
| preset_cinematic = gr.Button("Cinematic", elem_classes="preset-btn") | |
| preset_horror = gr.Button("Monster/Horror", elem_classes="preset-btn") | |
| with gr.Row(): | |
| preset_superhero = gr.Button("Superhero", elem_classes="preset-btn") | |
| preset_starwars = gr.Button("Star Wars", elem_classes="preset-btn") | |
| with gr.Row(): | |
| preset_grimfairy = gr.Button("Grim Fairy Tale", elem_classes="preset-btn") | |
| with gr.Column(elem_id="wildcards-section"): | |
| gr.HTML('<div id="wildcards-label">Wildcard Randomizer</div>') | |
| with gr.Row(elem_id="wildcard-controls"): | |
| wildcard_category = gr.Dropdown( | |
| choices=list(WILDCARDS.keys()), | |
| value="Gothic", | |
| label=None, | |
| elem_id="wildcard-category" | |
| ) | |
| randomize_btn = gr.Button("🎲 Randomize", elem_id="randomize-btn") | |
| wildcard_result = gr.HTML( | |
| '<div id="wildcard-result"><em>Select category and click Randomize</em></div>' | |
| ) | |
| use_wildcard_btn = gr.Button("✓ Use This", elem_id="use-wildcard-btn") | |
| wildcard_state = gr.Textbox(visible=False, value="") | |
| gr.on( | |
| triggers=[run_button.click, prompt.submit], | |
| fn=infer, | |
| inputs=[prompt, steps_state], | |
| outputs=[result, download_button], | |
| concurrency_limit=1, | |
| ) | |
| preset_gothic.click(fn=lambda: PRESETS["Gothic Woman"], outputs=prompt) | |
| preset_dnd.click(fn=lambda: PRESETS["D&D Warrior"], outputs=prompt) | |
| preset_cinematic.click(fn=lambda: PRESETS["Cinematic Portrait"], outputs=prompt) | |
| preset_horror.click(fn=lambda: PRESETS["Monster/Horror"], outputs=prompt) | |
| preset_superhero.click(fn=lambda: PRESETS["Superhero"], outputs=prompt) | |
| preset_starwars.click(fn=lambda: PRESETS["Star Wars"], outputs=prompt) | |
| preset_grimfairy.click(fn=lambda: PRESETS["Grim Fairy Tale"], outputs=prompt) | |
| randomize_btn.click( | |
| fn=randomize_wildcard, | |
| inputs=[wildcard_category], | |
| outputs=[wildcard_state], | |
| ).then( | |
| fn=lambda x: f'<div id="wildcard-result">{x}</div>', | |
| inputs=[wildcard_state], | |
| outputs=[wildcard_result], | |
| ) | |
| use_wildcard_btn.click( | |
| fn=use_wildcard_prompt, | |
| inputs=[wildcard_state, prompt], | |
| outputs=[prompt], | |
| ) | |
| # STEPS MINUS - pure Python, no JS nonsense | |
| steps_minus.click( | |
| fn=lambda s: max(1, s - 1), | |
| inputs=[steps_state], | |
| outputs=[steps_state], | |
| ).then( | |
| fn=update_steps_display, | |
| inputs=[steps_state], | |
| outputs=[steps_display], | |
| ) | |
| # STEPS PLUS - pure Python, no JS nonsense | |
| steps_plus.click( | |
| fn=lambda s: min(20, s + 1), | |
| inputs=[steps_state], | |
| outputs=[steps_state], | |
| ).then( | |
| fn=update_steps_display, | |
| inputs=[steps_state], | |
| outputs=[steps_display], | |
| ) | |
| result.change( | |
| fn=None, | |
| inputs=None, | |
| outputs=None, | |
| js=""" | |
| () => { | |
| const hiddenImg = document.querySelector('#result-hidden img'); | |
| const displayImg = document.querySelector('#display-img'); | |
| if (hiddenImg && displayImg && hiddenImg.src) { | |
| displayImg.src = hiddenImg.src; | |
| } | |
| if (!window.__fluxLoop) { window.__fluxLoop = { running: false, timer: null, interval: 2 }; } | |
| const state = window.__fluxLoop; | |
| if (state.running) { | |
| state.timer = setTimeout(() => { | |
| if (!state.running) return; | |
| const saveBtn = document.querySelector('#save-btn'); | |
| if (saveBtn) { saveBtn.click(); } | |
| state.timer = setTimeout(() => { | |
| if (!state.running) return; | |
| const genBtn = document.querySelector('#generate-btn'); | |
| if (genBtn) { genBtn.click(); } | |
| }, (state.interval || 2) * 1000); | |
| }, 1000); | |
| } | |
| const sideGenBtn = document.querySelector('#side-gen-btn'); | |
| const sideSaveBtn = document.querySelector('#side-save-btn'); | |
| const sideGenBtnLeft = document.querySelector('#side-gen-btn-left'); | |
| const sideSaveBtnLeft = document.querySelector('#side-save-btn-left'); | |
| if (sideGenBtn && !sideGenBtn.hasListener) { | |
| sideGenBtn.hasListener = true; | |
| sideGenBtn.addEventListener('click', () => { | |
| const genBtn = document.querySelector('#generate-btn'); | |
| if (genBtn) { genBtn.click(); } | |
| }); | |
| } | |
| if (sideSaveBtn && !sideSaveBtn.hasListener) { | |
| sideSaveBtn.hasListener = true; | |
| sideSaveBtn.addEventListener('click', () => { | |
| const saveBtn = document.querySelector('#save-btn'); | |
| if (saveBtn) { saveBtn.click(); } | |
| }); | |
| } | |
| if (sideGenBtnLeft && !sideGenBtnLeft.hasListener) { | |
| sideGenBtnLeft.hasListener = true; | |
| sideGenBtnLeft.addEventListener('click', () => { | |
| const genBtn = document.querySelector('#generate-btn'); | |
| if (genBtn) { genBtn.click(); } | |
| }); | |
| } | |
| if (sideSaveBtnLeft && !sideSaveBtnLeft.hasListener) { | |
| sideSaveBtnLeft.hasListener = true; | |
| sideSaveBtnLeft.addEventListener('click', () => { | |
| const saveBtn = document.querySelector('#save-btn'); | |
| if (saveBtn) { saveBtn.click(); } | |
| }); | |
| } | |
| } | |
| """, | |
| ) | |
| combo_button.click( | |
| fn=None, | |
| inputs=None, | |
| outputs=None, | |
| js=""" | |
| () => { | |
| const saveBtn = document.querySelector('#save-btn'); | |
| if (saveBtn) { saveBtn.click(); } | |
| setTimeout(() => { | |
| const genBtn = document.querySelector('#generate-btn'); | |
| if (genBtn) { genBtn.click(); } | |
| }, 1000); | |
| } | |
| """, | |
| ) | |
| autoloop_button.click( | |
| fn=None, | |
| inputs=None, | |
| outputs=None, | |
| js=""" | |
| () => { | |
| if (!window.__fluxLoop) { window.__fluxLoop = { running: false, timer: null, interval: 2 }; } | |
| const state = window.__fluxLoop; | |
| const btn = document.querySelector('#autoloop-btn'); | |
| function setColor(running) { | |
| if (btn) { | |
| btn.style.setProperty('background-color', running ? '#2ecc71' : '#e74c3c', 'important'); | |
| btn.style.setProperty('border-color', running ? '#2ecc71' : '#e74c3c', 'important'); | |
| } | |
| } | |
| if (state.running) { | |
| state.running = false; | |
| clearTimeout(state.timer); | |
| setColor(false); | |
| } else { | |
| state.running = true; | |
| setColor(true); | |
| const genBtn = document.querySelector('#generate-btn'); | |
| if (genBtn) { genBtn.click(); } | |
| } | |
| } | |
| """, | |
| ) | |
| demo.queue(max_size=10).launch() |