File size: 27,198 Bytes
bce439c
9632d12
 
 
0e14842
 
bce439c
0e14842
bce439c
fda85af
0e14842
da1235d
 
 
 
3407b2a
5132eef
 
 
 
 
3407b2a
da1235d
 
5132eef
 
 
 
da1235d
 
5132eef
da1235d
5132eef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da1235d
 
5132eef
da1235d
 
 
 
 
5132eef
 
 
da1235d
5132eef
da1235d
 
5132eef
 
 
 
 
 
 
 
da1235d
5132eef
da1235d
 
5132eef
 
 
 
da1235d
5132eef
 
da1235d
 
 
5132eef
 
 
da1235d
 
 
5132eef
da1235d
 
5132eef
 
 
 
 
da1235d
 
5132eef
 
 
da1235d
 
5132eef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da1235d
5132eef
 
 
 
da1235d
 
5132eef
 
 
 
da1235d
5132eef
 
 
 
 
 
3407b2a
 
 
da1235d
 
 
 
 
 
 
 
5132eef
da1235d
 
5132eef
da1235d
 
 
 
 
5132eef
da1235d
 
 
 
 
 
5132eef
da1235d
 
5132eef
da1235d
 
 
 
 
 
5132eef
 
 
3407b2a
da1235d
 
5132eef
da1235d
 
5132eef
 
 
 
 
da1235d
 
 
 
 
 
 
5132eef
 
da1235d
 
 
 
 
5132eef
 
 
772fb9a
da1235d
9632d12
 
 
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
 
 
 
0e14842
9632d12
 
 
 
 
 
0e14842
 
bce439c
471d662
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf65a8f
471d662
0e14842
471d662
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da1235d
 
 
471d662
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af92840
471d662
 
 
 
76a0dbd
5132eef
da1235d
 
 
 
 
471d662
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af92840
471d662
5132eef
89db92b
76a0dbd
471d662
af92840
5132eef
 
 
76a0dbd
471d662
 
53c6344
471d662
 
 
 
 
 
 
 
 
 
bb4e06a
5132eef
 
 
9632d12
 
bb4e06a
76a0dbd
471d662
 
 
 
 
5132eef
 
76a0dbd
5132eef
 
 
9632d12
 
 
 
 
76a0dbd
 
 
 
471d662
76a0dbd
471d662
5132eef
 
 
 
76a0dbd
471d662
 
 
 
76a0dbd
 
 
 
 
 
 
 
 
 
 
 
471d662
 
 
 
da1235d
 
 
5132eef
76a0dbd
 
5132eef
76a0dbd
471d662
 
 
 
bb4e06a
bce439c
 
 
 
 
 
 
 
fda85af
bce439c
76a0dbd
471d662
 
 
 
da1235d
 
 
5132eef
0e14842
471d662
5132eef
471d662
 
 
 
 
 
 
 
 
 
 
 
 
da1235d
471d662
 
 
0e14842
5132eef
 
 
975601a
471d662
76a0dbd
975601a
5132eef
 
da1235d
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
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

# -----------------------------
# Google Gemini API ๊ด€๋ จ
# -----------------------------
import google.generativeai as genai
import google.generativeai.types as genai_types

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

###############################################################################
# 1. ํ…์ŠคํŠธ(ํ•œ๊ธ€ โ†’ ์˜์–ด) ๋ณ€ํ™˜ ๋ณด์กฐ ํ•จ์ˆ˜
###############################################################################

def maybe_translate_to_english(text: str) -> str:
    """
    ํ…์ŠคํŠธ์— ํ•œ๊ตญ์–ด๊ฐ€ ์žˆ์œผ๋ฉด ๊ฐ„๋‹จํ•œ ์น˜ํ™˜ ๊ทœ์น™์— ๋”ฐ๋ผ ์˜์–ด๋กœ ๋ณ€ํ™˜.
    """
    translations = {
        "์•ˆ๋…•ํ•˜์„ธ์š”": "Hello",
        "ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค": "Welcome",
        "์•ˆ๋…•": "Hello",
        "๋ฐฐ๋„ˆ": "Banner",
        # ํ•„์š”์— ๋”ฐ๋ผ ์ถ”๊ฐ€
    }
    for kr, en in translations.items():
        if kr in text:
            text = text.replace(kr, en)
    return text

###############################################################################
# 2. Gemini API ํ˜ธ์ถœ์„ ์œ„ํ•œ ์ค€๋น„
###############################################################################

def save_binary_file(file_name, data):
    """ ์ด์ง„ ํŒŒ์ผ์„ ์ €์žฅํ•˜๋Š” ํ—ฌํผ ํ•จ์ˆ˜ """
    with open(file_name, "wb") as f:
        f.write(data)

def generate_by_google_genai(text, file_name, model="gemini-2.0-flash-exp"):
    """
    Google Gemini API๋ฅผ ํ˜ธ์ถœํ•ด ํ…์ŠคํŠธ ๊ธฐ๋ฐ˜ ์ด๋ฏธ์ง€ ํŽธ์ง‘/์ƒ์„ฑ์„ ์ˆ˜ํ–‰.
    file_name: ์›๋ณธ ์ด๋ฏธ์ง€๋ฅผ ์ž„์‹œ ์—…๋กœ๋“œํ•˜์—ฌ API๋กœ ์ „๋‹ฌ
    text: ์ ์šฉํ•  ํ…์ŠคํŠธ ์ง€์‹œ์‚ฌํ•ญ
    """
    api_key = os.getenv("GAPI_TOKEN")
    if not api_key:
        raise ValueError("GAPI_TOKEN is missing. Please set an API key.")

    # Gemini API ์ธ์ฆ ์„ค์ •
    genai.configure(api_key=api_key)

    # ์ด๋ฏธ์ง€ ํŒŒ์ผ ์—…๋กœ๋“œ
    uploaded_file = genai.upload_file(path=file_name)

    # API์— ์ „๋‹ฌํ•  content ๊ตฌ์„ฑ
    contents = [
        genai_types.Content(
            role="user",
            parts=[
                # ๋จผ์ € ์—…๋กœ๋“œ๋œ ํŒŒ์ผ URI๋ฅผ ํฌํ•จ
                genai_types.Part.from_uri(
                    file_uri=uploaded_file.uri,
                    mime_type=uploaded_file.mime_type,
                ),
                # ์ด์–ด์„œ text ์ง€์‹œ์‚ฌํ•ญ์„ ํฌํ•จ
                genai_types.Part.from_text(text=text),
            ],
        ),
    ]

    # ์ƒ์„ฑ(ํŽธ์ง‘) ์„ค์ •
    generation_config = genai_types.GenerationConfig(
        temperature=1,
        top_p=0.95,
        top_k=40,
        max_output_tokens=8192,      # ์ถœ๋ ฅ ํ† ํฐ ์ œํ•œ
        response_mime_type="text/plain",
    )

    text_response = ""   # API๊ฐ€ ๋ฐ˜ํ™˜ํ•œ ํ…์ŠคํŠธ ๋ˆ„์ 
    image_path = None    # API๊ฐ€ ๋ฐ˜ํ™˜ํ•œ ์ด๋ฏธ์ง€ ํŒŒ์ผ์˜ ๋กœ์ปฌ ๊ฒฝ๋กœ

    # ์ž„์‹œ ํŒŒ์ผ์— ํŽธ์ง‘๋œ ์ด๋ฏธ์ง€ ์ €์žฅ
    with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
        temp_path = tmp.name

        # ์ŠคํŠธ๋ฆฌ๋ฐ ํ˜•ํƒœ๋กœ ์‘๋‹ต์„ ๋ฐ›์Œ
        response = genai.generate_content(
            model=model,
            contents=contents,
            generation_config=generation_config,
            stream=True
        )

        # ์ŠคํŠธ๋ฆฌ๋ฐ๋œ chunk๋“ค์—์„œ ์ด๋ฏธ์ง€์™€ ํ…์ŠคํŠธ๋ฅผ ์ถ”์ถœ
        for chunk in response:
            for candidate in chunk.candidates:
                for part in candidate.content.parts:
                    # ์ด๋ฏธ์ง€์ธ ๊ฒฝ์šฐ
                    if hasattr(part, 'inline_data') and part.inline_data:
                        save_binary_file(temp_path, part.inline_data.data)
                        image_path = temp_path
                        break
                    # ํ…์ŠคํŠธ์ธ ๊ฒฝ์šฐ
                    elif hasattr(part, 'text'):
                        text_response += part.text + "\n"

                if image_path:
                    break
            if image_path:
                break

    # ์—…๋กœ๋“œ๋œ ์ž„์‹œ ํŒŒ์ผ ์‚ญ์ œ
    genai.delete_file(uploaded_file.name)

    return image_path, text_response

###############################################################################
# 3. ์ด๋ฏธ์ง€์— ํ…์ŠคํŠธ๋ฅผ ์‚ฝ์ž…/์ˆ˜์ •ํ•˜๋Š” ํ•จ์ˆ˜ (Gemini API 2ํšŒ ํ˜ธ์ถœ)
###############################################################################

def change_text_in_image_two_times(original_image, instruction):
    """
    Gemini API๋ฅผ ๋‘ ๋ฒˆ ํ˜ธ์ถœํ•˜์—ฌ ๋‘ ๊ฐœ์˜ ๋ฒ„์ „์„ ์ƒ์„ฑํ•œ๋‹ค.
    """
    import numpy as np

    # ๋งŒ์•ฝ ์ด๋ฏธ์ง€๊ฐ€ numpy.ndarray ํƒ€์ž…์ด๋ฉด PIL๋กœ ๋ณ€ํ™˜
    if isinstance(original_image, np.ndarray):
        original_image = Image.fromarray(original_image)
    
    results = []
    for version_tag in ["(A)", "(B)"]:
        mod_instruction = f"{instruction} {version_tag}"
        try:
            with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
                original_path = tmp.name
                if isinstance(original_image, Image.Image):
                    original_image.save(original_path, format="PNG")
                    logging.debug(f"[DEBUG] Saved image to temporary file: {original_path}")
                else:
                    raise gr.Error(f"์˜ˆ์ƒ๋œ PIL Image๊ฐ€ ์•„๋‹Œ {type(original_image)} ํƒ€์ž…์ด ์ œ๊ณต๋˜์—ˆ์Šต๋‹ˆ๋‹ค.")
            # Gemini API ํ˜ธ์ถœ
            image_path, text_response = generate_by_google_genai(
                text=mod_instruction,
                file_name=original_path
            )
            if image_path:
                # ๋ฐ˜ํ™˜๋œ ์ด๋ฏธ์ง€ ๋กœ๋“œ
                try:
                    with open(image_path, "rb") as f:
                        image_data = f.read()
                    new_img = Image.open(io.BytesIO(image_data))
                    results.append(new_img)
                except Exception as img_err:
                    logging.error(f"[ERROR] Failed to process Gemini image: {img_err}")
                    results.append(original_image)
            else:
                logging.warning(f"[WARNING] ์ด๋ฏธ์ง€๊ฐ€ ๋ฐ˜ํ™˜๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. ํ…์ŠคํŠธ ์‘๋‹ต: {text_response}")
                results.append(original_image)
        except Exception as e:
            logging.exception(f"Text modification error: {e}")
            results.append(original_image)
    return results

###############################################################################
# 4. ํ…์ŠคํŠธ ๋ Œ๋”๋ง(๋ฌธ์ž ์‚ฝ์ž…)์šฉ ํ•จ์ˆ˜
###############################################################################

def gemini_text_rendering(image, rendering_text):
    """
    ์ฃผ์–ด์ง„ image์— ๋Œ€ํ•ด Gemini API๋กœ text_rendering์„ ์ ์šฉ
    """
    rendering_text_en = maybe_translate_to_english(rendering_text)
    instruction = (
        f"Render the following text on the image in a clear, visually appealing manner: "
        f"{rendering_text_en}."
    )
    # ์ด๋ฏธ์ง€์— ํ…์ŠคํŠธ ์‚ฝ์ž…(A/B ๋ฒ„์ „ 2ํšŒ ์ƒ์„ฑ) โ†’ ์—ฌ๊ธฐ์„œ๋Š” 2ํšŒ ์ค‘ ์ฒซ ๋ฒˆ์งธ๋งŒ ๋ฐ˜ํ™˜
    rendered_images = change_text_in_image_two_times(image, instruction)
    if rendered_images and len(rendered_images) > 0:
        return rendered_images[0]
    return image

def apply_text_rendering(image, rendering_text):
    """
    rendering_text๊ฐ€ ์กด์žฌํ•˜๋ฉด Gemini API๋กœ ํ…์ŠคํŠธ ์‚ฝ์ž…์„ ์ ์šฉ.
    ์—†์œผ๋ฉด ์›๋ณธ ์ด๋ฏธ์ง€๋ฅผ ๊ทธ๋Œ€๋กœ ๋ฐ˜ํ™˜.
    """
    if rendering_text and rendering_text.strip():
        return gemini_text_rendering(image, rendering_text)
    return image

###############################################################################
# 5. 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 = "openfree/flux-chatgpt-ghibli-lora"

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

###############################################################################
# 6. Gradio UI
###############################################################################

examples = [
    "Ghibli style futuristic stormtrooper with glossy white armor and a sleek helmet, standing heroically on a lush alien planet, vibrant flowers blooming around, soft sunlight illuminating the scene, a gentle breeze rustling the leaves. The armor reflects the pink and purple hues of the alien sunset, creating an ethereal glow around the figure. [trigger]",
    "Ghibli style young mechanic girl in a floating workshop, surrounded by hovering tools and glowing mechanical parts, her blue overalls covered in oil stains, tinkering with a semi-transparent robot companion. Magical sparks fly as she works, while floating islands with waterfalls drift past her open workshop window. [trigger]",
    "Ghibli style ancient forest guardian robot, covered in moss and flowering vines, sitting peacefully in a crystal-clear lake. Its gentle eyes glow with soft blue light, while bioluminescent dragonflies dance around its weathered metal frame. Ancient tech symbols on its surface pulse with a gentle rhythm. [trigger]",
    "Ghibli style sky whale transport ship, its metallic skin adorned with traditional Japanese patterns, gliding through cotton candy clouds at sunrise. Small floating gardens hang from its sides, where workers in futuristic kimonos tend to glowing plants. Rainbow auroras shimmer in the background. [trigger]",
    "Ghibli style cyber-shrine maiden with flowing holographic robes, performing a ritual dance among floating lanterns and digital cherry blossoms. Her traditional headdress emits soft light patterns, while spirit-like AI constructs swirl around her in elegant patterns. The scene is set in a modern shrine with both ancient wood and sleek chrome elements. [trigger]",
    "Ghibli style robot farmer tending to floating rice paddies in the sky, wearing a traditional straw hat with advanced sensors. Its gentle movements create ripples in the water as it plants glowing rice seedlings. Flying fish leap between the terraced fields, leaving trails of sparkles in their wake, while future Tokyo's spires gleam in the distance. [trigger]"
]

css = """
:root {
    --primary-color: #6a92cc;
    --primary-hover: #557ab8;
    --secondary-color: #f4c062;
    --background-color: #f7f9fc;
    --panel-background: #ffffff;
    --text-color: #333333;
    --border-radius: 12px;
    --shadow: 0 4px 12px rgba(0,0,0,0.08);
    --font-main: 'Poppins', -apple-system, BlinkMacSystemFont, sans-serif;
}
body {
    background-color: var(--background-color);
    font-family: var(--font-main);
}
.gradio-container {
    margin: 0 auto;
    max-width: 1200px !important;
}
.main-header {
    text-align: center;
    padding: 2rem 1rem 1rem;
    background: linear-gradient(90deg, #6a92cc 0%, #8f7fc8 100%);
    color: white;
    margin-bottom: 2rem;
    border-radius: var(--border-radius);
    box-shadow: var(--shadow);
}
.main-header h1 {
    font-size: 2.5rem;
    margin-bottom: 0.5rem;
    font-weight: 700;
    text-shadow: 0 2px 4px rgba(0,0,0,0.2);
}
.main-header p {
    font-size: 1rem;
    margin-bottom: 0.5rem;
    opacity: 0.9;
}
.main-header a {
    color: var(--secondary-color);
    text-decoration: none;
    font-weight: 600;
    transition: all 0.2s ease;
}
.main-header a:hover {
    text-decoration: underline;
    opacity: 0.9;
}
.container {
    background-color: var(--panel-background);
    padding: 1.5rem;
    border-radius: var(--border-radius);
    box-shadow: var(--shadow);
    margin-bottom: 1.5rem;
}
button.primary {
    background: var(--primary-color) !important;
    border: none !important;
    color: white !important;
    padding: 10px 20px !important;
    border-radius: 8px !important;
    font-weight: 600 !important;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1) !important;
    transition: all 0.2s ease !important;
}
button.primary:hover {
    background: var(--primary-hover) !important;
    transform: translateY(-2px) !important;
    box-shadow: 0 4px 8px rgba(0,0,0,0.15) !important;
}
button.secondary {
    background: white !important;
    border: 1px solid #ddd !important;
    color: var(--text-color) !important;
    padding: 10px 20px !important;
    border-radius: 8px !important;
    font-weight: 500 !important;
    box-shadow: 0 2px 5px rgba(0,0,0,0.05) !important;
    transition: all 0.2s ease !important;
}
button.secondary:hover {
    background: #f5f5f5 !important;
    transform: translateY(-2px) !important;
}
.gr-box {
    border-radius: var(--border-radius) !important;
    border: 1px solid #e0e0e0 !important;
}
.gr-panel {
    border-radius: var(--border-radius) !important;
}
.gr-input {
    border-radius: 8px !important;
    border: 1px solid #ddd !important;
    padding: 12px !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;
}
.gr-button {
    border-radius: 8px !important;
}
.gallery-item {
    border-radius: var(--border-radius) !important;
    transition: all 0.3s ease !important;
}
.gallery-item:hover {
    transform: scale(1.02) !important;
    box-shadow: 0 6px 15px rgba(0,0,0,0.1) !important;
}
.tabs {
    border-radius: var(--border-radius) !important;
    overflow: hidden !important;
}
footer {
    display: none !important;
}
.settings-accordion legend span {
    font-weight: 600 !important;
}
.example-prompt {
    font-size: 0.9rem;
    color: #555;
    padding: 8px;
    background: #f5f7fa;
    border-radius: 6px;
    border-left: 3px solid var(--primary-color);
    margin-bottom: 8px;
    cursor: pointer;
    transition: all 0.2s;
}
.example-prompt:hover {
    background: #eef2f8;
}
.status-generating {
    color: #ffa200;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 8px;
}
.status-generating::before {
    content: "";
    display: inline-block;
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background-color: #ffa200;
    animation: pulse 1.5s infinite;
}
.status-complete {
    color: #00c853;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 8px;
}
.status-complete::before {
    content: "";
    display: inline-block;
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background-color: #00c853;
}
@keyframes pulse {
    0% { opacity: 0.6; }
    50% { opacity: 1; }
    100% { opacity: 0.6; }
}
.gr-accordion-title {
    font-weight: 600 !important;
    color: var(--text-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(106, 146, 204, 0.1) !important;
}
.gr-slider-container {
    padding: 10px 0 !important;
}
.gr-prose h3 {
    font-weight: 600 !important;
    color: var(--primary-color) !important;
    margin-bottom: 1rem !important;
}
"""

with gr.Blocks(css=css, analytics_enabled=False, theme="soft") as demo:
    with gr.Column():
        gr.HTML('''
        <div class="main-header">
            <h1>โœจ FLUX Ghibli LoRA Generator โœจ</h1>
            <p>Community: <a href="https://discord.gg/openfreeai" target="_blank">https://discord.gg/openfreeai</a></p>
        </div>
        ''')
        
        with gr.Row():
            with gr.Column(scale=3):
                with gr.Group(elem_classes="container"):
                    prompt = gr.Textbox(
                        label="Enter your imagination",
                        placeholder="Describe your Ghibli-style image here...",
                        lines=3
                    )
                    # Text Rendering ์ž…๋ ฅ๋ž€
                    text_rendering = gr.Textbox(
                        label="Text Rendering (Multilingual: English, Korean...)",
                        placeholder="Man saying '์•ˆ๋…•' in 'speech bubble'",
                        lines=1
                    )
                    
                    with gr.Row():
                        run_button = gr.Button("โœจ Generate 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("### โœจ Example 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 Image", elem_id="result-image")
                    seed_text = gr.Number(label="Used Seed", value=42)
    
    with gr.Tabs(elem_classes="tabs") as tabs:
        with gr.TabItem("Gallery"):
            with gr.Group(elem_classes="container"):
                gallery_header = gr.Markdown("### ๐Ÿ–ผ๏ธ Your Generated Masterpieces")
                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">Generating image...</div>'
    
    def after_generate(image, seed_num, gallery):
        return image, seed_num, gallery, '<div class="status-complete">Generation 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]
    )
    
    # 1) ์ƒํƒœ ํ‘œ์‹œ
    # 2) ์ด๋ฏธ์ง€ ์ƒ์„ฑ
    # 3) ์ƒํƒœ ์—…๋ฐ์ดํŠธ
    # 4) ํ…์ŠคํŠธ ๋ Œ๋”๋ง(์žˆ๋‹ค๋ฉด)
    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],
    ).then(
        fn=apply_text_rendering,
        inputs=[result, text_rendering],
        outputs=result
    )
    
    # prompt submit ์‹œ์—๋„ ๋™์ผํ•œ ์ฒด์ธ ์‹คํ–‰
    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],
    ).then(
        fn=apply_text_rendering,
        inputs=[result, text_rendering],
        outputs=result
    )
    
    # 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>
    """)

###############################################################################
# 7. ์‹คํ–‰
###############################################################################
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)