File size: 24,742 Bytes
bce439c
9632d12
 
 
0e14842
 
bce439c
0e14842
bce439c
fda85af
0e14842
da1235d
 
 
 
3407b2a
da1235d
 
5132eef
bb26c11
5132eef
772fb9a
da1235d
9632d12
 
 
76a0dbd
 
40c5d1c
76a0dbd
975601a
5132eef
 
 
975601a
 
5132eef
975601a
5132eef
975601a
 
 
 
5132eef
975601a
 
5132eef
76a0dbd
 
975601a
76a0dbd
5132eef
76a0dbd
975601a
 
76a0dbd
0e14842
76a0dbd
0e14842
 
 
 
9632d12
5132eef
 
 
9632d12
 
 
 
 
5132eef
9632d12
 
 
 
 
 
5132eef
 
 
9632d12
 
5132eef
 
 
 
 
9632d12
 
 
bce439c
bb4e06a
bce439c
 
 
 
 
 
 
 
 
 
5132eef
 
 
0e14842
 
fda85af
5132eef
76a0dbd
 
 
 
 
 
 
 
 
 
5132eef
76a0dbd
 
5132eef
76a0dbd
5132eef
76a0dbd
 
bce439c
5132eef
bb26c11
5132eef
 
0e14842
a87b19e
 
 
 
 
 
0e14842
 
bce439c
471d662
a87b19e
 
 
 
 
471d662
a87b19e
 
 
471d662
 
 
 
 
a87b19e
471d662
 
 
 
 
 
 
a87b19e
 
471d662
 
 
 
a87b19e
 
 
 
 
 
 
 
 
 
 
 
 
471d662
 
a87b19e
471d662
a87b19e
 
 
471d662
 
a87b19e
 
 
 
 
 
 
 
 
 
 
 
471d662
a87b19e
 
 
471d662
 
a87b19e
471d662
 
 
a87b19e
471d662
 
 
 
 
 
 
a87b19e
471d662
 
a87b19e
 
471d662
 
 
a87b19e
471d662
 
a87b19e
 
471d662
a87b19e
 
 
 
471d662
 
a87b19e
 
 
471d662
 
 
a87b19e
 
 
 
471d662
a87b19e
 
471d662
 
a87b19e
471d662
a87b19e
471d662
 
 
a87b19e
471d662
 
 
 
 
a87b19e
 
471d662
a87b19e
 
 
 
 
 
471d662
 
 
 
 
 
 
 
a87b19e
471d662
 
a87b19e
471d662
 
 
 
a87b19e
 
471d662
 
a87b19e
 
 
471d662
 
 
 
 
bf65a8f
471d662
0e14842
471d662
 
a87b19e
471d662
 
a87b19e
 
 
 
 
 
 
471d662
a87b19e
 
471d662
 
a87b19e
 
 
471d662
 
a87b19e
 
471d662
 
 
a87b19e
471d662
 
 
 
a87b19e
 
471d662
a87b19e
471d662
 
 
a87b19e
 
471d662
 
 
a87b19e
471d662
 
 
 
a87b19e
 
471d662
a87b19e
471d662
 
a87b19e
 
 
471d662
 
 
a87b19e
471d662
 
 
 
 
 
 
 
a87b19e
471d662
 
 
 
 
a87b19e
471d662
 
a87b19e
471d662
bb26c11
 
 
 
 
 
a87b19e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
471d662
 
 
 
 
 
a87b19e
 
 
471d662
 
 
 
a87b19e
 
 
 
 
 
 
 
 
 
bb26c11
a87b19e
 
 
 
 
bb26c11
a87b19e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb26c11
a87b19e
 
 
 
 
 
 
 
 
 
bb26c11
 
 
a87b19e
 
bb26c11
 
 
 
 
 
 
 
 
bb4e06a
5132eef
 
 
9632d12
 
bb4e06a
76a0dbd
bb26c11
 
471d662
a87b19e
bb26c11
5132eef
a87b19e
76a0dbd
5132eef
 
 
9632d12
 
 
 
 
76a0dbd
bb26c11
76a0dbd
 
 
bb26c11
76a0dbd
471d662
76a0dbd
471d662
 
 
 
76a0dbd
 
 
 
 
 
 
 
 
 
 
 
471d662
 
 
 
76a0dbd
 
 
471d662
 
 
 
bb4e06a
bce439c
 
 
 
 
 
 
 
fda85af
bce439c
76a0dbd
471d662
 
 
 
bb26c11
 
5132eef
471d662
 
 
 
 
 
 
 
 
 
 
 
 
da1235d
471d662
 
 
0e14842
5132eef
bb26c11
5132eef
975601a
471d662
76a0dbd
975601a
5132eef
 
2cf6049
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
import random
import os
import uuid
from datetime import datetime
import gradio as gr
import numpy as np
import spaces
import torch
from diffusers import DiffusionPipeline
from PIL import Image

import re
import tempfile
import io
import logging

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

###############################################################################
# 1. Diffusion Pipeline 로드 및 기본 세팅
###############################################################################

SAVE_DIR = "saved_images"
if not os.path.exists(SAVE_DIR):
    os.makedirs(SAVE_DIR, exist_ok=True)

device = "cuda" if torch.cuda.is_available() else "cpu"
repo_id = "black-forest-labs/FLUX.1-dev"
adapter_id = "ginipick/flux-lora-eric-cat"

def load_model_with_retry(max_retries=5):
    """
    로컬 또는 Hugging Face로부터 모델(FLUX.1-dev) + LoRA 어댑터(weights)를 불러온다.
    """
    for attempt in range(max_retries):
        try:
            logging.info(f"Loading model attempt {attempt+1}/{max_retries}...")
            pipeline = DiffusionPipeline.from_pretrained(
                repo_id,
                torch_dtype=torch.bfloat16,
                use_safetensors=True,
                resume_download=True
            )
            logging.info("Model loaded successfully, loading LoRA weights...")
            pipeline.load_lora_weights(adapter_id)
            pipeline = pipeline.to(device)
            logging.info("Pipeline ready!")
            return pipeline
        except Exception as e:
            if attempt < max_retries - 1:
                wait_time = 10 * (attempt + 1)
                logging.error(f"Error loading model: {e}. Retrying in {wait_time} seconds...")
                import time
                time.sleep(wait_time)
            else:
                raise Exception(f"Failed to load model after {max_retries} attempts: {e}")

pipeline = load_model_with_retry()

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

def save_generated_image(image, prompt):
    """
    생성된 이미지를 저장하면서 메타 정보를 기록한다.
    """
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    unique_id = str(uuid.uuid4())[:8]
    filename = f"{timestamp}_{unique_id}.png"
    filepath = os.path.join(SAVE_DIR, filename)
    image.save(filepath)

    metadata_file = os.path.join(SAVE_DIR, "metadata.txt")
    with open(metadata_file, "a", encoding="utf-8") as f:
        f.write(f"{filename}|{prompt}|{timestamp}\n")
    return filepath

def load_generated_images():
    """
    저장된 이미지를 최신순으로 불러온다.
    """
    if not os.path.exists(SAVE_DIR):
        return []
    image_files = [
        os.path.join(SAVE_DIR, f)
        for f in os.listdir(SAVE_DIR)
        if f.endswith(('.png', '.jpg', '.jpeg', '.webp'))
    ]
    image_files.sort(key=lambda x: os.path.getctime(x), reverse=True)
    return image_files

@spaces.GPU(duration=120)
def inference(
    prompt: str,
    seed: int,
    randomize_seed: bool,
    width: int,
    height: int,
    guidance_scale: float,
    num_inference_steps: int,
    lora_scale: float,
    progress: gr.Progress = gr.Progress(track_tqdm=True),
):
    """
    Diffusion Pipeline을 사용해 이미지를 생성. (LoRA 스케일, Steps 등 설정 가능)
    """
    if randomize_seed:
        seed = random.randint(0, MAX_SEED)
    generator = torch.Generator(device=device).manual_seed(seed)

    try:
        image = pipeline(
            prompt=prompt,
            guidance_scale=guidance_scale,
            num_inference_steps=num_inference_steps,
            width=width,
            height=height,
            generator=generator,
            joint_attention_kwargs={"scale": lora_scale},
        ).images[0]

        filepath = save_generated_image(image, prompt)
        return image, seed, load_generated_images()

    except Exception as e:
        logging.error(f"Error during inference: {e}")
        error_img = Image.new('RGB', (width, height), color='red')
        return error_img, seed, load_generated_images()

###############################################################################
# 3. Gradio UI
###############################################################################

examples = [
    "cat style cosmic explorer with starry fur, floating in a nebula of vibrant pink and purple clouds, mystical glowing eyes, surrounded by tiny planets and cosmic dust. Extremely detailed, artistic masterpiece. [trigger]",
    "cat style samurai warrior with ornate armor decorated with cherry blossoms, sitting in meditation under a moonlit waterfall, katana resting beside, glowing spiritual aura, ultra-detailed metallic reflections. [trigger]",
    "cat style magical librarian in an ancient floating library, surrounded by flying books with glowing runes, wearing wizards robes with star patterns, soft magical lighting, shelves extending to infinity, detailed bookbindings. [trigger]",
    "cat style royal empress with jeweled crown and elaborate golden silk robes, sitting on a throne made of jade and cherry blossoms, palace backdrop with ornate architecture, atmospheric lighting, ultra-detailed embroidery patterns. [trigger]",
    "cat style mystical forest guardian, fur intertwined with vines and flowers, ancient moss-covered stone artifacts floating around, emerald glowing eyes, sunbeams filtering through dense canopy, magical particles in the air, studio quality. [trigger]",
    "cat style space astronaut on an alien planet, exploring crystal caves with bioluminescent plants, helmet reflecting the colorful surroundings, paw prints leaving glowing marks, scientific equipment, cinematic lighting, highly detailed suit. [trigger]"
]

css = """
:root {
    --primary-color: #ff7e5f;
    --primary-hover: #ff6347;
    --secondary-color: #feb47b;
    --tertiary-color: #ffead0;
    --background-color: #f9f4f0;
    --panel-background: #ffffff;
    --text-color: #4a3933;
    --border-radius: 16px;
    --shadow: 0 8px 24px rgba(255, 126, 95, 0.12);
    --font-main: 'Poppins', -apple-system, BlinkMacSystemFont, sans-serif;
}
body {
    background-color: var(--background-color);
    font-family: var(--font-main);
    color: var(--text-color);
}
.gradio-container {
    margin: 0 auto;
    max-width: 1200px !important;
}
.main-header {
    text-align: center;
    padding: 2.5rem 1.5rem 1.5rem;
    background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
    color: white;
    margin-bottom: 2rem;
    border-radius: var(--border-radius);
    box-shadow: var(--shadow);
    position: relative;
    overflow: hidden;
}
.main-header::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200"><path d="M44,98.1c0.1-17.7,7.2-31.9,18.9-43.5c7.5-7.3,16.5-12,26.5-15c29.9-8.8,59.7,4.9,73.2,33.2c8.1,17,7.1,34.2-0.7,51c-8.3,17.8-22.4,29.5-41.4,34.7c-18.5,5-36.1,1.4-51.7-9.8C51.7,136.6,43.9,118.9,44,98.1z M172.8,96.6c0-14.2-2.3-27.1-8.3-39.1c-12.7-25.4-33.9-37.7-61.8-37C74.2,21.1,50.8,46.9,46,75.5c-4.7,28.4,8.5,59.6,45.2,72.7c15.5,5.6,31.2,5.3,46.5-0.8C162.6,138.1,172.9,119.4,172.8,96.6z" fill="rgba(255,255,255,0.05)"/><path d="M117.3,75.5c-0.5-4.7-0.4-9.8-2.9-14c-7.3-12.3-30.9-12.8-37.4,2.1c-2.5,5.8-1.2,12.2-1.8,18.3c-0.2,1.1-0.1,2.3-0.6,3.2c-2.2,5-4.3,10.1-2.5,15.7c0.1,0.3,0.2,0.6,0.2,0.9c0.5,4.2-0.5,7.1-5.5,8c-1.7,0.3-3.3,1-4.9,1.5c0.4,2.6,0.6,5.2,1.3,7.8c0.7,2.6,2.5,5.2,1.5,8.1c-0.5,1.4-2.9,2.7-4.4,2.7c-12.9-0.2-12.5,7.2-13.5,15.9c-0.9,7.9-2,14.4,7.1,19.5c1.7,1,2.1,4.5,2.3,6.9c0.7,9.3,7.1,14.4,15.6,16c4.4,0.8,9.1,1.9,13.5,1.1c5.5-1,9-9.6,7.7-19.2c-0.6-4.6,0.4-8.2,4.9-10.2c1.8-0.8,3.9-1.3,5.8-1.4c6-0.2,12.1-0.3,18.1-0.5c8.8-0.2,16.5-3.4,22.1-10.3c8.3-10.1,17.6-15.1,30.9-11.1c0.6,0.2,1.3,0.1,2.5,0.2c-0.4-9.3-1.4-18.3-10.8-22.7c-2.8-1.3-5.9-2.6-7.9-4.8c-9.3-10.5-18.2-21.3-27.5-31.8c-4.9-5.5-10.4-10.4-15.8-15.5c-2.7-2.5-6.9-4.4-6.3-8.8c0.6-4.4,5.2-5.1,8.8-5.9c6.3-1.4,12-3.7,11.4-11.4c-0.5-5.2-5.5-10.4-11.7-9.8c-3.2,0.3-6.4,0.8-9.6,1.5c-10,2.5-11.8,12.1-17.5,19c-1.5,1.7-2.5,4.4-6,2.9c-3.1-1.3-6.4-3.1-6.3-7c0.1-4.1,3.7-5.7,6.9-7.2c10.3-5,18.2-12.2,19.6-24.2c0.3-2.5,0.9-4.9-0.7-7.2c-1.2-1.7-2.7-3.1-4.2-4.6c-0.6-0.6-1.5-1.1-2.3-1.1c-6.8,0-11.5,5.4-16.9,7c-0.1-0.3-0.3-0.5-0.4-0.8c5.2-4.6,10.5-9.1,16.7-14.5c-1.6-2.2-2.9-5.1-5.1-6.5c-1.4-0.9-5.6,0.1-7.1,1.7c-5.3,5.6-10.2,11.5-14.3,18.9c-1.1-1.3-1.3-2.2-1.8-2.2c-6.9,0.7-13.7,1.4-20.6,2.3c-2.2,0.3-5.7,1.5-6.2,3c-0.9,2.8,0.5,6.3,1.3,9.5c2.4,0.8,4.9,1.5,7.3,2.2c10.1,2.5,16.9,13.6,14.8,24.2c-1.9,9.6-9.3,15.6-19.1,15.4c-2.6-0.1-5.1-1.2-7.6-1.9c-3.2-0.9-6.5-2.3-9.6-2.1c-3.8,0.2-4.8,4.3-4.9,8c-0.2,5.2,3.1,6.6,7.1,6.9c6.9,0.5,13.9,0.5,20.8,1c6.1,0.4,10.8,3.7,14.7,8.1C112.6,69.5,115,72.4,117.3,75.5z M94.5,100.5c0.2,13.8,11.7,25,25.6,24.8c13.9-0.1,25.1-11.3,25.1-25c0-14-11.3-25.3-25.2-25.3C106.1,75.1,94.3,86.7,94.5,100.5z" fill="rgba(255,255,255,0.08)"/></svg>') no-repeat center center;
    background-size: 180px;
    opacity: 0.5;
}
.main-header h1 {
    font-size: 3rem;
    margin-bottom: 0.5rem;
    font-weight: 800;
    text-shadow: 0 2px 5px rgba(0,0,0,0.2);
    position: relative;
}
.main-header p {
    font-size: 1.1rem;
    margin: 1rem 0;
    opacity: 0.95;
    position: relative;
    font-weight: 500;
    max-width: 800px;
    margin-left: auto;
    margin-right: auto;
    line-height: 1.6;
}
.main-header .tribute {
    font-style: italic;
    opacity: 0.9;
    font-size: 1rem;
    margin-top: 1rem;
    position: relative;
}
.main-header a {
    color: var(--tertiary-color);
    text-decoration: none;
    font-weight: 600;
    transition: all 0.2s ease;
    position: relative;
}
.main-header a:hover {
    text-decoration: underline;
    opacity: 0.9;
}
.container {
    background-color: var(--panel-background);
    padding: 2rem;
    border-radius: var(--border-radius);
    box-shadow: var(--shadow);
    margin-bottom: 2rem;
    border: 1px solid rgba(255, 126, 95, 0.1);
}
button.primary {
    background: var(--primary-color) !important;
    background: linear-gradient(90deg, var(--primary-color) 0%, var(--secondary-color) 100%) !important;
    border: none !important;
    color: white !important;
    padding: 12px 24px !important;
    border-radius: 12px !important;
    font-weight: 600 !important;
    box-shadow: 0 4px 10px rgba(255, 126, 95, 0.3) !important;
    transition: all 0.3s ease !important;
    font-size: 1.05rem !important;
    letter-spacing: 0.5px !important;
}
button.primary:hover {
    background: linear-gradient(90deg, var(--primary-hover) 0%, var(--secondary-color) 100%) !important;
    transform: translateY(-3px) !important;
    box-shadow: 0 6px 15px rgba(255, 126, 95, 0.4) !important;
}
button.secondary {
    background: white !important;
    border: 1px solid rgba(255, 126, 95, 0.3) !important;
    color: var(--primary-color) !important;
    padding: 12px 24px !important;
    border-radius: 12px !important;
    font-weight: 500 !important;
    box-shadow: 0 2px 5px rgba(255, 126, 95, 0.1) !important;
    transition: all 0.3s ease !important;
}
button.secondary:hover {
    background: rgba(255, 126, 95, 0.05) !important;
    transform: translateY(-2px) !important;
    box-shadow: 0 4px 8px rgba(255, 126, 95, 0.15) !important;
}
.gr-box {
    border-radius: var(--border-radius) !important;
    border: 1px solid rgba(255, 126, 95, 0.2) !important;
}
.gr-panel {
    border-radius: var(--border-radius) !important;
}
.gr-input {
    border-radius: 12px !important;
    border: 1px solid rgba(255, 126, 95, 0.3) !important;
    padding: 12px !important;
    transition: all 0.3s ease !important;
    font-size: 1rem !important;
}
.gr-input:focus {
    border-color: var(--primary-color) !important;
    box-shadow: 0 0 0 2px rgba(255, 126, 95, 0.2) !important;
}
.gr-form {
    border-radius: var(--border-radius) !important;
    background-color: var(--panel-background) !important;
}
.gr-accordion {
    border-radius: var(--border-radius) !important;
    overflow: hidden !important;
    border: 1px solid rgba(255, 126, 95, 0.15) !important;
}
.gr-button {
    border-radius: 12px !important;
}
.gallery-item {
    border-radius: var(--border-radius) !important;
    transition: all 0.3s ease !important;
    overflow: hidden !important;
    border: 3px solid transparent !important;
}
.gallery-item:hover {
    transform: scale(1.03) !important;
    box-shadow: 0 8px 20px rgba(255, 126, 95, 0.2) !important;
    border: 3px solid var(--primary-color) !important;
}
.tabs {
    border-radius: var(--border-radius) !important;
    overflow: hidden !important;
}
footer {
    display: none !important;
}
.settings-accordion legend span {
    font-weight: 600 !important;
    color: var(--primary-color) !important;
}
.example-prompt {
    font-size: 0.95rem;
    color: var(--text-color);
    padding: 12px 16px;
    background: linear-gradient(to right, rgba(255, 126, 95, 0.05), rgba(254, 180, 123, 0.1));
    border-radius: 12px;
    border-left: 4px solid var(--primary-color);
    margin-bottom: 12px;
    cursor: pointer;
    transition: all 0.3s;
    box-shadow: 0 2px 5px rgba(255, 126, 95, 0.05);
}
.example-prompt:hover {
    background: linear-gradient(to right, rgba(255, 126, 95, 0.1), rgba(254, 180, 123, 0.15));
    transform: translateX(5px);
    box-shadow: 0 3px 8px rgba(255, 126, 95, 0.1);
}
.status-generating {
    color: var(--secondary-color);
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 1.05rem;
}
.status-generating::before {
    content: "";
    display: inline-block;
    width: 14px;
    height: 14px;
    border-radius: 50%;
    background-color: var(--secondary-color);
    animation: pulse 1.5s infinite;
}
.status-complete {
    color: #4caf50;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 1.05rem;
}
.status-complete::before {
    content: "";
    display: inline-block;
    width: 14px;
    height: 14px;
    border-radius: 50%;
    background-color: #4caf50;
}
@keyframes pulse {
    0% { opacity: 0.6; transform: scale(0.9); }
    50% { opacity: 1; transform: scale(1.1); }
    100% { opacity: 0.6; transform: scale(0.9); }
}
.gr-accordion-title {
    font-weight: 600 !important;
    color: var(--primary-color) !important;
}
.tabs button {
    font-weight: 500 !important;
    padding: 10px 16px !important;
}
.tabs button.selected {
    font-weight: 600 !important;
    color: var(--primary-color) !important;
    background: rgba(255, 126, 95, 0.1) !important;
}
.gr-slider-container {
    padding: 10px 0 !important;
}
.gr-prose h3 {
    font-weight: 700 !important;
    color: var(--primary-color) !important;
    margin-bottom: 1rem !important;
    font-size: 1.2rem !important;
}
.tab-nav {
    margin-bottom: 1rem !important;
    background-color: var(--panel-background) !important;
    border-radius: var(--border-radius) !important;
    overflow: hidden !important;
}
.gr-slider-thumb {
    background: var(--primary-color) !important;
}
.gr-slider-track {
    background: linear-gradient(90deg, var(--primary-color) 0%, var(--secondary-color) 100%) !important;
}
.cat-icon {
    display: inline-block;
    font-size: 1.8em;
    margin-right: 0.3em;
    vertical-align: middle;
}
.gr-gallery {
    display: grid !important;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)) !important;
    gap: 16px !important;
    padding: 16px !important;
}
#result-image .gr-image-viewer {
    border-radius: var(--border-radius);
    overflow: hidden;
    box-shadow: 0 5px 15px rgba(255, 126, 95, 0.1);
    transition: all 0.3s ease;
}
#result-image .gr-image-viewer:hover {
    box-shadow: 0 8px 25px rgba(255, 126, 95, 0.2);
}
.gr-padded {
    padding: 0 !important;
}
"""

with gr.Blocks(css=css, analytics_enabled=False, theme="soft") as demo:
    with gr.Column():
        gr.HTML('''
        <div class="main-header">
            <h1><span class="cat-icon">🐱✨</span> FLUX Cat LoRA Generator</h1>
            <p>Generate beautiful cat-styled images with this specialized LoRA model. Simply enter your prompt and watch the magic happen!</p>
            <p class="tribute">This project is a tribute to the first-ever "cat" LoRA model on Hugging Face, honoring its pioneering contribution to stylized AI image generation.</p>
            <p>Community: <a href="https://discord.gg/openfreeai" target="_blank">https://discord.gg/openfreeai</a></p>
        </div>
        ''')
        
        # Text-to-Image tab only (removed Image-to-Image tab)
        with gr.Column():
            with gr.Row():
                with gr.Column(scale=3):
                    with gr.Group(elem_classes="container"):
                        prompt = gr.Textbox(
                            label="Enter your imagination",
                            placeholder="Describe your cat-style image here... (e.g., 'cat style majestic warrior with armor')",
                            lines=3
                        )
                        
                        with gr.Row():
                            run_button = gr.Button("✨ Generate Purrfect Image", elem_classes="primary")
                            clear_button = gr.Button("Clear", elem_classes="secondary")
                        
                        with gr.Accordion("Advanced Settings", open=False, elem_classes="settings-accordion"):
                            with gr.Row():
                                seed = gr.Slider(
                                    label="Seed",
                                    minimum=0,
                                    maximum=MAX_SEED,
                                    step=1,
                                    value=42,
                                )
                                randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
                            with gr.Row():
                                width = gr.Slider(
                                    label="Width",
                                    minimum=256,
                                    maximum=MAX_IMAGE_SIZE,
                                    step=32,
                                    value=1024,
                                )
                                height = gr.Slider(
                                    label="Height",
                                    minimum=256,
                                    maximum=MAX_IMAGE_SIZE,
                                    step=32,
                                    value=768,
                                )
                            with gr.Row():
                                guidance_scale = gr.Slider(
                                    label="Guidance scale",
                                    minimum=0.0,
                                    maximum=10.0,
                                    step=0.1,
                                    value=3.5,
                                )
                            with gr.Row():
                                num_inference_steps = gr.Slider(
                                    label="Steps",
                                    minimum=1,
                                    maximum=50,
                                    step=1,
                                    value=30,
                                )
                                lora_scale = gr.Slider(
                                    label="LoRA scale",
                                    minimum=0.0,
                                    maximum=1.0,
                                    step=0.1,
                                    value=1.0,
                                )
                    
                    with gr.Group(elem_classes="container"):
                        gr.Markdown("### ✨ Inspirational Cat Prompts")
                        examples_html = '\n'.join([f'<div class="example-prompt">{ex}</div>' for ex in examples])
                        example_container = gr.HTML(examples_html)
                
                with gr.Column(scale=4):
                    with gr.Group(elem_classes="container"):
                        generation_status = gr.HTML('<div class="status-complete">Ready to generate</div>')
                        result = gr.Image(label="Generated Cat Image", elem_id="result-image")
                        seed_text = gr.Number(label="Used Seed", value=42)
        
        with gr.Group(elem_classes="container"):
            with gr.Tabs(elem_classes="tabs") as gallery_tabs:
                with gr.TabItem("Cat Gallery"):
                    gallery_header = gr.Markdown("### 🖼️ Your Cat-tastic Creations")
                    with gr.Row():
                        refresh_btn = gr.Button("🔄 Refresh Gallery", elem_classes="secondary")
                    generated_gallery = gr.Gallery(
                        label="Generated Images",
                        columns=3,
                        value=load_generated_images(),
                        height="500px",
                        elem_classes="gallery-item"
                    )

    ###########################################################################
    # Gradio Helper Functions
    ###########################################################################
    def refresh_gallery():
        return load_generated_images()

    def clear_output():
        return "", gr.update(value=None), seed, '<div class="status-complete">Ready to generate</div>'
    
    def before_generate():
        return '<div class="status-generating">Creating cat masterpiece...</div>'
    
    def after_generate(image, seed_num, gallery):
        return image, seed_num, gallery, '<div class="status-complete">Meow-gnificent creation complete!</div>'

    ###########################################################################
    # Gradio Event Wiring
    ###########################################################################
    refresh_btn.click(
        fn=refresh_gallery,
        inputs=None,
        outputs=generated_gallery,
    )
    
    # 텍스트-이미지 생성 이벤트
    clear_button.click(
        fn=clear_output,
        inputs=None,
        outputs=[prompt, result, seed_text, generation_status]
    )
    
    run_button.click(
        fn=before_generate,
        inputs=None,
        outputs=generation_status,
    ).then(
        fn=inference,
        inputs=[
            prompt,
            seed,
            randomize_seed,
            width,
            height,
            guidance_scale,
            num_inference_steps,
            lora_scale,
        ],
        outputs=[result, seed_text, generated_gallery],
    ).then(
        fn=after_generate,
        inputs=[result, seed_text, generated_gallery],
        outputs=[result, seed_text, generated_gallery, generation_status],
    )
    
    prompt.submit(
        fn=before_generate,
        inputs=None,
        outputs=generation_status,
    ).then(
        fn=inference,
        inputs=[
            prompt,
            seed,
            randomize_seed,
            width,
            height,
            guidance_scale,
            num_inference_steps,
            lora_scale,
        ],
        outputs=[result, seed_text, generated_gallery],
    ).then(
        fn=after_generate,
        inputs=[result, seed_text, generated_gallery],
        outputs=[result, seed_text, generated_gallery, generation_status],
    )
    
    # JS로 예시 prompt 클릭 시 자동 채우기
    gr.HTML("""
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        setTimeout(() => {
            const examples = document.querySelectorAll('.example-prompt');
            const promptInput = document.querySelector('textarea');
            examples.forEach(example => {
                example.addEventListener('click', function() {
                    promptInput.value = this.textContent.trim();
                    const event = new Event('input', { bubbles: true });
                    promptInput.dispatchEvent(event);
                });
            });
        }, 1000);
    });
    </script>
    """)

###############################################################################
# 4. 실행
###############################################################################
try:
    demo.queue(concurrency_count=1, max_size=20)
    demo.launch(debug=True, show_api=False)
except Exception as e:
    logging.error(f"Error during launch: {e}")
    logging.info("Trying alternative launch configuration...")
    demo.launch(debug=True, show_api=False, share=False)