File size: 28,260 Bytes
7f4c99b
 
 
 
 
 
 
 
 
 
 
 
 
 
989c44e
 
7f4c99b
51b7c7d
 
7f4c99b
 
 
 
 
 
8d760b2
 
 
989c44e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f4c99b
06529b5
 
 
 
 
 
7f4c99b
06529b5
 
7f4c99b
 
 
aa0cb15
 
7f4c99b
 
 
 
 
 
 
 
 
 
 
 
8d760b2
 
 
4959628
8d760b2
 
724710e
caebab4
 
989c44e
7f4c99b
b695f49
 
7f4c99b
989c44e
 
 
 
 
0fb3ed4
989c44e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0fb3ed4
989c44e
 
 
 
 
 
 
 
 
 
 
02b00c0
5bb04db
02b00c0
5bb04db
02b00c0
5bb04db
02b00c0
 
 
 
5bb04db
02b00c0
 
5bb04db
02b00c0
 
 
 
 
 
 
 
 
 
 
8d760b2
989c44e
 
8d760b2
5bb04db
989c44e
0fb3ed4
 
8d760b2
989c44e
 
 
 
 
 
 
 
 
02b00c0
 
989c44e
 
8d760b2
 
5bb04db
8d760b2
 
 
989c44e
 
 
 
 
 
8d760b2
7f4c99b
 
 
 
 
 
 
 
 
989c44e
 
 
 
 
 
 
 
 
 
7f4c99b
989c44e
 
 
 
 
 
 
 
8d760b2
 
989c44e
 
7f4c99b
5bb04db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f4c99b
 
75ba08b
 
 
 
7f4c99b
 
 
 
 
 
5bb04db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f4c99b
5bb04db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
989c44e
7f4c99b
 
5bb04db
 
a1496c4
5bb04db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f4c99b
5bb04db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02b00c0
5bb04db
 
 
 
 
 
02b00c0
 
5bb04db
 
 
 
 
 
02b00c0
 
5bb04db
 
 
 
 
02b00c0
5bb04db
02b00c0
 
5bb04db
 
 
 
 
 
 
7f4c99b
5bb04db
 
 
 
 
 
 
 
 
7f4c99b
5bb04db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f4c99b
5bb04db
 
 
 
 
 
 
 
7f4c99b
02b00c0
 
 
 
 
 
 
7f4c99b
 
 
8d760b2
5bb04db
7f4c99b
 
5bb04db
 
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
import os
import subprocess
import sys
import io
import gradio as gr
import numpy as np
import random
import spaces
import torch
from diffusers import Flux2Pipeline, Flux2Transformer2DModel
from diffusers import BitsAndBytesConfig as DiffBitsAndBytesConfig
import requests
from PIL import Image
import json
import base64
from huggingface_hub import InferenceClient

subprocess.check_call([sys.executable, "-m", "pip", "install", "spaces==0.43.0"])

dtype = torch.bfloat16
device = "cuda" if torch.cuda.is_available() else "cpu"

MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 1024

# Pre-shifted custom sigmas for 8-step turbo inference
TURBO_SIGMAS = [1.0, 0.6509, 0.4374, 0.2932, 0.1893, 0.1108, 0.0495, 0.00031]

hf_client = InferenceClient(
    api_key=os.environ.get("HF_TOKEN"),
)
VLM_MODEL = "baidu/ERNIE-4.5-VL-424B-A47B-Base-PT"

SYSTEM_PROMPT_TEXT_ONLY = """You are an expert prompt engineer for FLUX.2 by Black Forest Labs. Rewrite user prompts to be more descriptive while strictly preserving their core subject and intent.

Guidelines:
1. Structure: Keep structured inputs structured (enhance within fields). Convert natural language to detailed paragraphs.
2. Details: Add concrete visual specifics - form, scale, textures, materials, lighting (quality, direction, color), shadows, spatial relationships, and environmental context.
3. Text in Images: Put ALL text in quotation marks, matching the prompt's language. Always provide explicit quoted text for objects that would contain text in reality (signs, labels, screens, etc.) - without it, the model generates gibberish.

Output only the revised prompt and nothing else."""

SYSTEM_PROMPT_WITH_IMAGES = """You are FLUX.2 by Black Forest Labs, an image-editing expert. You convert editing requests into one concise instruction (50-80 words, ~30 for brief requests).

Rules:
- Single instruction only, no commentary
- Use clear, analytical language (avoid "whimsical," "cascading," etc.)
- Specify what changes AND what stays the same (face, lighting, composition)
- Reference actual image elements
- Turn negatives into positives ("don't change X" โ†’ "keep X")
- Make abstractions concrete ("futuristic" โ†’ "glowing cyan neon, metallic panels")
- Keep content PG-13

Output only the final instruction in plain text and nothing else."""

def remote_text_encoder(prompts):
    from gradio_client import Client
    
    client = Client("multimodalart/mistral-text-encoder")
    result = client.predict(
        prompt=prompts,
        api_name="/encode_text"
    )
    
    prompt_embeds = torch.load(result[0])
    return prompt_embeds

# Load model
repo_id = "black-forest-labs/FLUX.2-dev"

dit = Flux2Transformer2DModel.from_pretrained(
    repo_id,
    subfolder="transformer",
    torch_dtype=torch.bfloat16
)

pipe = Flux2Pipeline.from_pretrained(
    repo_id,
    text_encoder=None,
    transformer=dit,
    torch_dtype=torch.bfloat16
)

# Load the Turbo LoRA
pipe.load_lora_weights(
    "fal/FLUX.2-dev-Turbo", 
    weight_name="flux.2-turbo-lora.safetensors"
)
pipe.fuse_lora()
pipe.unload_lora_weights()

pipe.to(device)

# Pull pre-compiled Flux2 Transformer blocks from HF hub
spaces.aoti_blocks_load(pipe.transformer, "zerogpu-aoti/FLUX.2", variant="fa3")

def image_to_data_uri(img):
    buffered = io.BytesIO()
    img.save(buffered, format="PNG")
    img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
    return f"data:image/png;base64,{img_str}"

def upsample_prompt_logic(prompt, image_list):
    try:
        if image_list and len(image_list) > 0:
            system_content = SYSTEM_PROMPT_WITH_IMAGES
            user_content = [{"type": "text", "text": prompt}]
            
            for img in image_list:
                data_uri = image_to_data_uri(img)
                user_content.append({
                    "type": "image_url",
                    "image_url": {"url": data_uri}
                })
                
            messages = [
                {"role": "system", "content": system_content},
                {"role": "user", "content": user_content}
            ]
        else:
            system_content = SYSTEM_PROMPT_TEXT_ONLY
            messages = [
                {"role": "system", "content": system_content},
                {"role": "user", "content": prompt}
            ]

        completion = hf_client.chat.completions.create(
            model=VLM_MODEL,
            messages=messages,
            max_tokens=1024
        )
        
        return completion.choices[0].message.content
    except Exception as e:
        print(f"Upsampling failed: {e}")
        return prompt

def update_dimensions_from_image(image_list):
    """Update width/height sliders based on uploaded image aspect ratio."""
    if image_list is None or len(image_list) == 0:
        return 1024, 1024
    
    img = image_list[0][0]
    img_width, img_height = img.size
    
    aspect_ratio = img_width / img_height
    
    if aspect_ratio >= 1:
        new_width = 1024
        new_height = int(1024 / aspect_ratio)
    else:
        new_height = 1024
        new_width = int(1024 * aspect_ratio)
    
    new_width = round(new_width / 8) * 8
    new_height = round(new_height / 8) * 8
    
    new_width = max(256, min(1024, new_width))
    new_height = max(256, min(1024, new_height))
    
    return new_width, new_height

def get_duration(prompt_embeds, image_list, width, height, num_inference_steps, guidance_scale, seed, use_turbo, progress=gr.Progress(track_tqdm=True)):
    num_images = 0 if image_list is None else len(image_list)
    step_duration = 1 + 0.8 * num_images
    if use_turbo:
        return max(30, 8 * step_duration + 10)
    return max(65, num_inference_steps * step_duration + 10)

@spaces.GPU(duration=get_duration)
def generate_image(prompt_embeds, image_list, width, height, num_inference_steps, guidance_scale, seed, use_turbo, progress=gr.Progress(track_tqdm=True)):
    prompt_embeds = prompt_embeds.to(device)
    
    generator = torch.Generator(device=device).manual_seed(seed)
    
    pipe_kwargs = {
        "prompt_embeds": prompt_embeds,
        "image": image_list,
        "guidance_scale": guidance_scale,
        "generator": generator,
        "width": width,
        "height": height,
    }
    
    if use_turbo:
        pipe_kwargs["sigmas"] = TURBO_SIGMAS
        pipe_kwargs["num_inference_steps"] = 8
    else:
        pipe_kwargs["num_inference_steps"] = num_inference_steps
    
    if progress:
        progress(0, desc="Starting generation...")
        
    image = pipe(**pipe_kwargs).images[0]
    return image

def infer(prompt, input_images=None, seed=42, randomize_seed=False, width=1024, height=1024, num_inference_steps=8, guidance_scale=2.5, prompt_upsampling=False, use_turbo=True, progress=gr.Progress(track_tqdm=True)):
    
    if randomize_seed:
        seed = random.randint(0, MAX_SEED)
    
    image_list = None
    if input_images is not None and len(input_images) > 0:
        image_list = []
        for item in input_images:
            image_list.append(item[0])

    final_prompt = prompt
    if prompt_upsampling:
        progress(0.05, desc="Upsampling prompt...")
        final_prompt = upsample_prompt_logic(prompt, image_list)
        print(f"Original Prompt: {prompt}")
        print(f"Upsampled Prompt: {final_prompt}")

    progress(0.1, desc="Encoding prompt...")
    prompt_embeds = remote_text_encoder(final_prompt)
    
    progress(0.3, desc="Waiting for GPU...")
    image = generate_image(
        prompt_embeds, 
        image_list, 
        width, 
        height, 
        num_inference_steps, 
        guidance_scale, 
        seed,
        use_turbo,
        progress
    )
    
    # ์ •๋ณด ๋กœ๊ทธ ์ƒ์„ฑ
    info_log = f"""โœ… GENERATION COMPLETE!
{'=' * 50}
๐Ÿ“ Prompt Info:
   โ€ข Original: {prompt[:50]}{'...' if len(prompt) > 50 else ''}
   โ€ข Upsampled: {'Yes' if prompt_upsampling else 'No'}
{'=' * 50}
โš™๏ธ Generation Settings:
   โ€ข Seed: {seed}
   โ€ข Size: {width} x {height}
   โ€ข Steps: {'8 (Turbo)' if use_turbo else num_inference_steps}
   โ€ข CFG Scale: {guidance_scale}
   โ€ข Input Images: {len(image_list) if image_list else 0}
{'=' * 50}
๐Ÿš€ Mode: {'โšก TURBO (8 steps)' if use_turbo else '๐ŸŽจ Standard'}
{'=' * 50}
๐Ÿ’พ Image ready to download!"""
    
    return image, seed, info_log

examples = [
    ["Create a vase on a table in living room, the color of the vase is a gradient of color, starting with #02eb3c color and finishing with #edfa3c. The flowers inside the vase have the color #ff0088"],
    ["Photorealistic infographic showing the complete Berlin TV Tower (Fernsehturm) from ground base to antenna tip, full vertical view with entire structure visible including concrete shaft, metallic sphere, and antenna spire. Slight upward perspective angle looking up toward the iconic sphere, perfectly centered on clean white background. Left side labels with thin horizontal connector lines: the text '368m' in extra large bold dark grey numerals (#2D3748) positioned at exactly the antenna tip with 'TOTAL HEIGHT' in small caps below. The text '207m' in extra large bold with 'TELECAFร‰' in small caps below, with connector line touching the sphere precisely at the window level. Right side label with horizontal connector line touching the sphere's equator: the text '32m' in extra large bold dark grey numerals with 'SPHERE DIAMETER' in small caps below. Bottom section arranged in three balanced columns: Left - Large text '986' in extra bold dark grey with 'STEPS' in caps below. Center - 'BERLIN TV TOWER' in bold caps with 'FERNSEHTURM' in lighter weight below. Right - 'INAUGURATED' in bold caps with 'OCTOBER 3, 1969' below. All typography in modern sans-serif font (such as Inter or Helvetica), color #2D3748, clean minimal technical diagram style. Horizontal connector lines are thin, precise, and clearly visible, touching the tower structure at exact corresponding measurement points. Professional architectural elevation drawing aesthetic with dynamic low angle perspective creating sense of height and grandeur, poster-ready infographic design with perfect visual hierarchy."],
    ["Soaking wet capybara taking shelter under a banana leaf in the rainy jungle, close up photo"],
    ["A kawaii die-cut sticker of a chubby orange cat, featuring big sparkly eyes and a happy smile with paws raised in greeting and a heart-shaped pink nose. The design should have smooth rounded lines with black outlines and soft gradient shading with pink cheeks."],
]

examples_images = [
    ["The person from image 1 is petting the cat from image 2, the bird from image 3 is next to them", ["woman1.webp", "cat_window.webp", "bird.webp"]]
]


# ============================================
# ๐ŸŽจ Comic Classic Theme - Toon Playground
# ============================================

css = """
/* ===== ๐ŸŽจ Google Fonts Import ===== */
@import url('https://fonts.googleapis.com/css2?family=Bangers&family=Comic+Neue:wght@400;700&display=swap');

/* ===== ๐ŸŽจ Comic Classic ๋ฐฐ๊ฒฝ - ๋นˆํ‹ฐ์ง€ ํŽ˜์ดํผ + ๋„ํŠธ ํŒจํ„ด ===== */
.gradio-container {
    background-color: #FEF9C3 !important;
    background-image: 
        radial-gradient(#1F2937 1px, transparent 1px) !important;
    background-size: 20px 20px !important;
    min-height: 100vh !important;
    font-family: 'Comic Neue', cursive, sans-serif !important;
}

/* ===== ํ—ˆ๊น…ํŽ˜์ด์Šค ์ƒ๋‹จ ์š”์†Œ ์ˆจ๊น€ ===== */
.huggingface-space-header,
#space-header,
.space-header,
[class*="space-header"],
.svelte-1ed2p3z,
.space-header-badge,
.header-badge,
[data-testid="space-header"],
.svelte-kqij2n,
.svelte-1ax1toq,
.embed-container > div:first-child {
    display: none !important;
    visibility: hidden !important;
    height: 0 !important;
    width: 0 !important;
    overflow: hidden !important;
    opacity: 0 !important;
    pointer-events: none !important;
}

/* ===== Footer ์™„์ „ ์ˆจ๊น€ ===== */
footer,
.footer,
.gradio-container footer,
.built-with,
[class*="footer"],
.gradio-footer,
.main-footer,
div[class*="footer"],
.show-api,
.built-with-gradio,
a[href*="gradio.app"],
a[href*="huggingface.co/spaces"] {
    display: none !important;
    visibility: hidden !important;
    height: 0 !important;
    padding: 0 !important;
    margin: 0 !important;
}

/* ===== ๋ฉ”์ธ ์ปจํ…Œ์ด๋„ˆ ===== */
#col-container { 
    max-width: 1200px; 
    margin: 0 auto; 
}

/* ===== ๐ŸŽจ ํ—ค๋” ํƒ€์ดํ‹€ - ์ฝ”๋ฏน ์Šคํƒ€์ผ ===== */
.header-text h1 {
    font-family: 'Bangers', cursive !important;
    color: #1F2937 !important;
    font-size: 3.5rem !important;
    font-weight: 400 !important;
    text-align: center !important;
    margin-bottom: 0.5rem !important;
    text-shadow: 
        4px 4px 0px #FACC15,
        6px 6px 0px #1F2937 !important;
    letter-spacing: 3px !important;
    -webkit-text-stroke: 2px #1F2937 !important;
}

/* ===== ๐ŸŽจ ์„œ๋ธŒํƒ€์ดํ‹€ ===== */
.subtitle {
    text-align: center !important;
    font-family: 'Comic Neue', cursive !important;
    font-size: 1.2rem !important;
    color: #1F2937 !important;
    margin-bottom: 1.5rem !important;
    font-weight: 700 !important;
}

.subtitle-small {
    text-align: center !important;
    font-family: 'Comic Neue', cursive !important;
    font-size: 1rem !important;
    color: #6B7280 !important;
    margin-bottom: 1rem !important;
    font-weight: 400 !important;
}

/* ===== ๐ŸŽจ ์นด๋“œ/ํŒจ๋„ - ๋งŒํ™” ํ”„๋ ˆ์ž„ ์Šคํƒ€์ผ ===== */
.gr-panel,
.gr-box,
.gr-form,
.block,
.gr-group {
    background: #FFFFFF !important;
    border: 3px solid #1F2937 !important;
    border-radius: 8px !important;
    box-shadow: 6px 6px 0px #1F2937 !important;
    transition: all 0.2s ease !important;
}

.gr-panel:hover,
.block:hover {
    transform: translate(-2px, -2px) !important;
    box-shadow: 8px 8px 0px #1F2937 !important;
}

/* ===== ๐ŸŽจ ์ž…๋ ฅ ํ•„๋“œ (Textbox) ===== */
textarea, 
input[type="text"], 
input[type="number"] {
    background: #FFFFFF !important;
    border: 3px solid #1F2937 !important;
    border-radius: 8px !important;
    color: #1F2937 !important;
    font-family: 'Comic Neue', cursive !important;
    font-size: 1rem !important;
    font-weight: 700 !important;
    transition: all 0.2s ease !important;
}

textarea:focus, 
input[type="text"]:focus, 
input[type="number"]:focus {
    border-color: #3B82F6 !important;
    box-shadow: 4px 4px 0px #3B82F6 !important;
    outline: none !important;
}

textarea::placeholder {
    color: #9CA3AF !important;
    font-weight: 400 !important;
}

/* ===== ๐ŸŽจ ํ”„๋กฌํ”„ํŠธ ์ž…๋ ฅ์ฐฝ ํŠน๋ณ„ ์Šคํƒ€์ผ ===== */
.prompt-input textarea {
    background: #FFFBEB !important;
    border: 4px solid #F59E0B !important;
    border-radius: 12px !important;
    font-size: 1.1rem !important;
    padding: 12px !important;
    box-shadow: 4px 4px 0px #1F2937 !important;
}

.prompt-input textarea:focus {
    border-color: #3B82F6 !important;
    box-shadow: 6px 6px 0px #3B82F6 !important;
}

/* ===== ๐ŸŽจ Primary ๋ฒ„ํŠผ - ์ฝ”๋ฏน ๋ธ”๋ฃจ ===== */
.gr-button-primary,
button.primary,
.gr-button.primary,
.generate-btn {
    background: #3B82F6 !important;
    border: 3px solid #1F2937 !important;
    border-radius: 8px !important;
    color: #FFFFFF !important;
    font-family: 'Bangers', cursive !important;
    font-weight: 400 !important;
    font-size: 1.3rem !important;
    letter-spacing: 2px !important;
    padding: 14px 28px !important;
    box-shadow: 5px 5px 0px #1F2937 !important;
    transition: all 0.1s ease !important;
    text-shadow: 1px 1px 0px #1F2937 !important;
}

.gr-button-primary:hover,
button.primary:hover,
.gr-button.primary:hover,
.generate-btn:hover {
    background: #2563EB !important;
    transform: translate(-2px, -2px) !important;
    box-shadow: 7px 7px 0px #1F2937 !important;
}

.gr-button-primary:active,
button.primary:active,
.gr-button.primary:active,
.generate-btn:active {
    transform: translate(3px, 3px) !important;
    box-shadow: 2px 2px 0px #1F2937 !important;
}

/* ===== ๐ŸŽจ Secondary ๋ฒ„ํŠผ - ์ฝ”๋ฏน ๋ ˆ๋“œ ===== */
.gr-button-secondary,
button.secondary {
    background: #EF4444 !important;
    border: 3px solid #1F2937 !important;
    border-radius: 8px !important;
    color: #FFFFFF !important;
    font-family: 'Bangers', cursive !important;
    font-weight: 400 !important;
    font-size: 1.1rem !important;
    letter-spacing: 1px !important;
    box-shadow: 4px 4px 0px #1F2937 !important;
    transition: all 0.1s ease !important;
    text-shadow: 1px 1px 0px #1F2937 !important;
}

.gr-button-secondary:hover,
button.secondary:hover {
    background: #DC2626 !important;
    transform: translate(-2px, -2px) !important;
    box-shadow: 6px 6px 0px #1F2937 !important;
}

/* ===== ๐ŸŽจ ๋กœ๊ทธ ์ถœ๋ ฅ ์˜์—ญ ===== */
.info-log textarea {
    background: #1F2937 !important;
    color: #10B981 !important;
    font-family: 'Courier New', monospace !important;
    font-size: 0.9rem !important;
    font-weight: 400 !important;
    border: 3px solid #10B981 !important;
    border-radius: 8px !important;
    box-shadow: 4px 4px 0px #10B981 !important;
}

/* ===== ๐ŸŽจ ์ด๋ฏธ์ง€ ์—…๋กœ๋“œ/๊ฐค๋Ÿฌ๋ฆฌ ์˜์—ญ ===== */
.image-upload,
.gr-gallery {
    border: 4px dashed #3B82F6 !important;
    border-radius: 12px !important;
    background: #EFF6FF !important;
    transition: all 0.2s ease !important;
}

.image-upload:hover,
.gr-gallery:hover {
    border-color: #EF4444 !important;
    background: #FEF2F2 !important;
}

.gr-gallery .thumbnail-item {
    border: 3px solid #1F2937 !important;
    border-radius: 6px !important;
    transition: all 0.2s ease !important;
}

.gr-gallery .thumbnail-item:hover {
    transform: scale(1.05) !important;
    box-shadow: 4px 4px 0px #3B82F6 !important;
}

/* ===== ๐ŸŽจ ์•„์ฝ”๋””์–ธ - ๋งํ’์„  ์Šคํƒ€์ผ ===== */
.gr-accordion {
    background: #FACC15 !important;
    border: 3px solid #1F2937 !important;
    border-radius: 8px !important;
    box-shadow: 4px 4px 0px #1F2937 !important;
}

.gr-accordion-header {
    color: #1F2937 !important;
    font-family: 'Comic Neue', cursive !important;
    font-weight: 700 !important;
    font-size: 1.1rem !important;
}

/* ===== ๐ŸŽจ ๊ฒฐ๊ณผ ์ด๋ฏธ์ง€ ์˜์—ญ ===== */
.result-image,
.gr-image {
    border: 4px solid #1F2937 !important;
    border-radius: 8px !important;
    box-shadow: 8px 8px 0px #1F2937 !important;
    overflow: hidden !important;
    background: #FFFFFF !important;
}

/* ===== ๐ŸŽจ ์Šฌ๋ผ์ด๋” ์Šคํƒ€์ผ ===== */
input[type="range"] {
    accent-color: #3B82F6 !important;
}

.gr-slider {
    background: #FFFFFF !important;
}

/* ===== ๐ŸŽจ ์ฒดํฌ๋ฐ•์Šค ์Šคํƒ€์ผ ===== */
input[type="checkbox"] {
    accent-color: #3B82F6 !important;
    width: 20px !important;
    height: 20px !important;
    border: 2px solid #1F2937 !important;
}

/* ===== ๐ŸŽจ ๋ผ๋ฒจ ์Šคํƒ€์ผ ===== */
label,
.gr-input-label,
.gr-block-label {
    color: #1F2937 !important;
    font-family: 'Comic Neue', cursive !important;
    font-weight: 700 !important;
    font-size: 1rem !important;
}

span.gr-label {
    color: #1F2937 !important;
}

/* ===== ๐ŸŽจ ์ •๋ณด ํ…์ŠคํŠธ ===== */
.gr-info,
.info {
    color: #6B7280 !important;
    font-family: 'Comic Neue', cursive !important;
    font-size: 0.9rem !important;
}

/* ===== ๐ŸŽจ ํ”„๋กœ๊ทธ๋ ˆ์Šค ๋ฐ” ===== */
.progress-bar,
.gr-progress-bar {
    background: #3B82F6 !important;
    border: 2px solid #1F2937 !important;
    border-radius: 4px !important;
}

/* ===== ๐ŸŽจ Examples ์„น์…˜ ===== */
.gr-examples {
    background: #FFFFFF !important;
    border: 3px solid #1F2937 !important;
    border-radius: 8px !important;
    box-shadow: 6px 6px 0px #1F2937 !important;
    padding: 1rem !important;
}

.gr-examples .gr-sample {
    border: 2px solid #1F2937 !important;
    border-radius: 6px !important;
    transition: all 0.2s ease !important;
}

.gr-examples .gr-sample:hover {
    transform: translate(-2px, -2px) !important;
    box-shadow: 4px 4px 0px #3B82F6 !important;
}

/* ===== ๐ŸŽจ Turbo ๋ฑƒ์ง€ ์Šคํƒ€์ผ ===== */
.turbo-badge {
    display: inline-block;
    background: linear-gradient(135deg, #F59E0B 0%, #EF4444 100%) !important;
    color: #FFFFFF !important;
    font-family: 'Bangers', cursive !important;
    font-size: 1rem !important;
    padding: 4px 12px !important;
    border: 2px solid #1F2937 !important;
    border-radius: 20px !important;
    box-shadow: 2px 2px 0px #1F2937 !important;
    margin-left: 8px !important;
}

/* ===== ๐ŸŽจ ์Šคํฌ๋กค๋ฐ” - ์ฝ”๋ฏน ์Šคํƒ€์ผ ===== */
::-webkit-scrollbar {
    width: 12px;
    height: 12px;
}

::-webkit-scrollbar-track {
    background: #FEF9C3;
    border: 2px solid #1F2937;
}

::-webkit-scrollbar-thumb {
    background: #3B82F6;
    border: 2px solid #1F2937;
    border-radius: 0px;
}

::-webkit-scrollbar-thumb:hover {
    background: #EF4444;
}

/* ===== ๐ŸŽจ ์„ ํƒ ํ•˜์ด๋ผ์ดํŠธ ===== */
::selection {
    background: #FACC15;
    color: #1F2937;
}

/* ===== ๐ŸŽจ ๋งํฌ ์Šคํƒ€์ผ ===== */
a {
    color: #3B82F6 !important;
    text-decoration: none !important;
    font-weight: 700 !important;
}

a:hover {
    color: #EF4444 !important;
}

/* ===== ๐ŸŽจ Row/Column ๊ฐ„๊ฒฉ ===== */
.gr-row {
    gap: 1.5rem !important;
}

.gr-column {
    gap: 1rem !important;
}

/* ===== ๋ฐ˜์‘ํ˜• ์กฐ์ • ===== */
@media (max-width: 768px) {
    .header-text h1 {
        font-size: 2.2rem !important;
        text-shadow: 
            3px 3px 0px #FACC15,
            4px 4px 0px #1F2937 !important;
    }
    
    .gr-button-primary,
    button.primary {
        padding: 12px 20px !important;
        font-size: 1.1rem !important;
    }
    
    .gr-panel,
    .block {
        box-shadow: 4px 4px 0px #1F2937 !important;
    }
}

/* ===== ๐ŸŽจ ๋‹คํฌ๋ชจ๋“œ ๋น„ํ™œ์„ฑํ™” (์ฝ”๋ฏน์€ ๋ฐ์•„์•ผ ํ•จ) ===== */
@media (prefers-color-scheme: dark) {
    .gradio-container {
        background-color: #FEF9C3 !important;
    }
}
"""

# Build the Gradio interface
with gr.Blocks(fill_height=True, css=css) as demo:
    gr.LoginButton(value="Option: HuggingFace 'Login' for extra GPU quota +", size="sm")       
    # HOME Badge
    gr.HTML("""
        <div style="text-align: center; margin: 20px 0 10px 0;">
            <a href="https://www.humangen.ai" target="_blank" style="text-decoration: none;">
                <img src="https://img.shields.io/static/v1?label=๐Ÿ  HOME&message=HUMANGEN.AI&color=0000ff&labelColor=ffcc00&style=for-the-badge" alt="HOME">
            </a>
        </div>
    """)
    
    # Header Title
    gr.Markdown(
        """
        # โšก FLUX.2 TURBO IMAGE GENERATOR ๐ŸŽจ
        """,
        elem_classes="header-text"
    )
    
    gr.Markdown(
        """
        <p class="subtitle">๐Ÿš€ 32B Rectified Flow Model โ€ข Generate, Edit & Combine Images in 8 Steps! โœจ</p>
        <p class="subtitle-small">Powered by <a href="https://huggingface.co/black-forest-labs/FLUX.2-dev" target="_blank">FLUX.2 [dev]</a> with <a href="https://huggingface.co/fal/FLUX.2-Turbo" target="_blank">Turbo LoRA by fal</a></p>
        """,
    )
    
    with gr.Row(equal_height=False):
        # Left column - Input
        with gr.Column(scale=1, min_width=400):
            prompt = gr.Textbox(
                label="โœ๏ธ Enter Your Prompt",
                placeholder="Describe the image you want to create...",
                lines=3,
                max_lines=5,
                elem_classes="prompt-input"
            )
            
            run_button = gr.Button(
                "โšก GENERATE IMAGE! ๐ŸŽจ",
                variant="primary",
                size="lg",
                elem_classes="generate-btn"
            )
            
            with gr.Accordion("๐Ÿ–ผ๏ธ Input Images (Optional)", open=True):
                input_images = gr.Gallery(
                    label="Upload reference images for editing/combining",
                    type="pil",
                    columns=3,
                    rows=1,
                    elem_classes="image-upload"
                )
            
            with gr.Accordion("โš™๏ธ Advanced Settings", open=False):
                use_turbo = gr.Checkbox(
                    label="โšก Use Turbo Mode (8 steps)",
                    value=True,
                    info="Enable Turbo LoRA for fast 8-step generation",
                    visible=False
                )
                
                prompt_upsampling = gr.Checkbox(
                    label="๐Ÿ”ฎ Prompt Upsampling",
                    value=False,
                    info="Automatically enhance the prompt using a VLM"
                )
    
                seed = gr.Slider(
                    label="๐ŸŽฒ Seed",
                    minimum=0,
                    maximum=MAX_SEED,
                    step=1,
                    value=0,
                )
                
                randomize_seed = gr.Checkbox(label="๐Ÿ”€ Randomize seed", value=True)
                
                with gr.Row():
                    width = gr.Slider(
                        label="๐Ÿ“ Width",
                        minimum=256,
                        maximum=MAX_IMAGE_SIZE,
                        step=8,
                        value=1024,
                    )
                    
                    height = gr.Slider(
                        label="๐Ÿ“ Height",
                        minimum=256,
                        maximum=MAX_IMAGE_SIZE,
                        step=8,
                        value=1024,
                    )
                
                with gr.Row():
                    num_inference_steps = gr.Slider(
                        label="๐Ÿ”„ Inference Steps (ignored in Turbo)",
                        minimum=1,
                        maximum=100,
                        step=1,
                        value=30,
                    )
                    
                    guidance_scale = gr.Slider(
                        label="๐ŸŽฏ Guidance Scale",
                        minimum=0.0,
                        maximum=10.0,
                        step=0.1,
                        value=2.5,
                    )
            
            with gr.Accordion("๐Ÿ“œ Generation Log", open=True):
                info_log = gr.Textbox(
                    label="",
                    placeholder="Enter a prompt and click generate to see info...",
                    lines=14,
                    max_lines=20,
                    interactive=False,
                    elem_classes="info-log"
                )
        
        # Right column - Output
        with gr.Column(scale=1, min_width=400):
            result = gr.Image(
                label="๐Ÿ–ผ๏ธ Generated Image",
                show_label=True,
                height=550,
                elem_classes="result-image"
            )
            
            gr.Markdown(
                """
                <p style="text-align: center; margin-top: 15px; font-weight: 700; color: #1F2937;">
                    ๐Ÿ’ก Right-click on the image to save, or use the download button!
                </p>
                """
            )

    # Examples Section
    gr.Markdown(
        """
        <p style="text-align: center; margin: 25px 0 15px 0; font-family: 'Bangers', cursive; font-size: 1.5rem; color: #1F2937;">
            ๐ŸŒŸ TRY THESE EXAMPLES! ๐ŸŒŸ
        </p>
        """
    )
    
    gr.Examples(
        examples=examples,
        fn=infer,
        inputs=[prompt],
        outputs=[result, seed, info_log],
        cache_examples=True,
        cache_mode="lazy"
    )

    gr.Examples(
        examples=examples_images,
        fn=infer,
        inputs=[prompt, input_images],
        outputs=[result, seed, info_log],
        cache_examples=True,
        cache_mode="lazy"
    )

    # Auto-update dimensions when images are uploaded
    input_images.upload(
        fn=update_dimensions_from_image,
        inputs=[input_images],
        outputs=[width, height]
    )

    gr.on(
        triggers=[run_button.click, prompt.submit],
        fn=infer,
        inputs=[prompt, input_images, seed, randomize_seed, width, height, num_inference_steps, guidance_scale, prompt_upsampling, use_turbo],
        outputs=[result, seed, info_log]
    )

if __name__ == "__main__":
    demo.launch()