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
 
 
 
 
 
 
 
 
 
 
 
 
 
18ec6c2
 
 
 
 
 
 
 
 
 
 
 
df0ecbf
18ec6c2
 
 
 
 
 
 
 
 
 
df0ecbf
18ec6c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df0ecbf
18ec6c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df0ecbf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
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",
    ],
}

@spaces.GPU()
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()