File size: 29,029 Bytes
036dfc6
4c9a6f0
036dfc6
4c9a6f0
 
036dfc6
 
4c9a6f0
036dfc6
289e506
 
 
 
4c9a6f0
90443db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c27458
90443db
 
 
036dfc6
 
 
 
4c9a6f0
a8084f8
 
 
036dfc6
 
0cf7a7f
4c9a6f0
036dfc6
 
 
4c9a6f0
036dfc6
 
4c9a6f0
289e506
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4583e7
 
 
 
 
 
 
 
 
 
 
 
90443db
b4583e7
90443db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4583e7
90443db
 
 
b4583e7
90443db
 
 
 
 
90456d7
 
b4583e7
90456d7
 
90443db
 
289e506
 
 
 
90456d7
b4583e7
 
289e506
 
 
 
0c364a7
 
90456d7
 
 
289e506
 
0c364a7
 
 
 
 
 
 
 
 
90456d7
 
0c364a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce9f340
 
 
0c364a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289e506
0c364a7
90456d7
 
 
 
 
 
289e506
0c364a7
 
 
 
 
 
 
ce9f340
0c364a7
ce9f340
 
0c364a7
 
 
 
 
 
 
 
 
 
 
 
 
ce9f340
 
 
0c364a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289e506
 
 
036dfc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c9a6f0
036dfc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289e506
 
 
 
 
b4583e7
90456d7
 
036dfc6
 
90443db
 
036dfc6
 
 
 
 
 
 
 
 
 
 
 
 
 
90456d7
 
90443db
90456d7
b4583e7
90456d7
289e506
036dfc6
 
 
 
 
4c9a6f0
289e506
 
 
 
 
 
 
4c9a6f0
a050e48
 
56360b9
5a29a17
56360b9
5a29a17
56360b9
5a29a17
56360b9
5a29a17
56360b9
5a29a17
56360b9
036dfc6
4c9a6f0
3718837
5a29a17
 
d1f2c3f
 
5a29a17
 
036dfc6
 
 
4c9a6f0
036dfc6
 
 
 
 
 
4c9a6f0
289e506
036dfc6
 
a8084f8
 
 
 
 
 
036dfc6
90456d7
289e506
 
90456d7
289e506
90456d7
0c364a7
 
 
90456d7
 
 
 
092f286
3c27458
90456d7
289e506
 
90456d7
289e506
90456d7
0c364a7
 
 
90456d7
 
 
 
 
092f286
90456d7
289e506
 
90456d7
3c27458
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
092f286
3c27458
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289e506
036dfc6
 
 
 
 
4c9a6f0
036dfc6
4c9a6f0
036dfc6
 
 
 
 
 
 
 
5a29a17
036dfc6
 
 
 
 
 
5a29a17
036dfc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c9a6f0
 
036dfc6
 
 
 
 
 
 
 
 
4c9a6f0
036dfc6
4c9a6f0
036dfc6
 
 
3c27458
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c9a6f0
036dfc6
 
 
 
4c9a6f0
289e506
 
 
 
 
 
3c27458
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c9a6f0
036dfc6
 
 
 
 
 
 
 
 
 
 
 
289e506
 
 
 
 
b4583e7
90456d7
 
036dfc6
 
4c9a6f0
 
036dfc6
 
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
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, ImageDraw, ImageFont
import requests
import json
import re

# At the beginning of the script, after imports
def check_available_fonts():
    """Check which font files are available"""
    font_files = {
        "λ‚˜λˆ”κ³ λ”•": "NanumGothic-Regular.ttf",
        "흑백사진": "BlackAndWhitePicture-Regular.ttf",
        "μΉ˜λ‘ μ„±": "ChironSungHK-VariableFont_wght.ttf",
        "독도": "Dokdo-Regular.ttf",
        "싱글데이": "SingleDay-Regular.ttf"
    }
    
    available_fonts = []
    for font_name, font_file in font_files.items():
        paths = [
            font_file,
            f"./{font_file}",
            os.path.join(os.getcwd(), font_file),
            os.path.join(os.path.dirname(os.path.abspath(__file__)), font_file)
        ]
        
        font_found = False
        for path in paths:
            if os.path.exists(path):
                available_fonts.append(font_name)
                print(f"βœ“ Found {font_name} at: {path}")
                font_found = True
                break
        
        if not font_found:
            print(f"βœ— {font_name} ({font_file}) not found")
    
    return available_fonts

# Check fonts at startup
print("Checking available fonts...")
available_fonts = check_available_fonts()
if not available_fonts:
    print("WARNING: No Korean fonts found! Please ensure font files are in the same directory as app.py")
    available_fonts = ["λ‚˜λˆ”κ³ λ”•"]  # Default fallback
else:
    print(f"Available fonts: {', '.join(available_fonts)}")

# Create permanent storage directory
SAVE_DIR = "saved_images"  # Gradio will handle the persistence
if not os.path.exists(SAVE_DIR):
    os.makedirs(SAVE_DIR, exist_ok=True)

# Load the default image
DEFAULT_IMAGE_PATH = "cover1.webp"

device = "cuda" if torch.cuda.is_available() else "cpu"
repo_id = "black-forest-labs/FLUX.1-dev"
adapter_id = "prithivMLmods/EBook-Creative-Cover-Flux-LoRA"

pipeline = DiffusionPipeline.from_pretrained(repo_id, torch_dtype=torch.bfloat16)
pipeline.load_lora_weights(adapter_id)
pipeline = pipeline.to(device)

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

def is_korean_only(text):
    """Check if text contains only Korean characters (excluding spaces and punctuation)"""
    # Remove spaces and common punctuation
    cleaned_text = re.sub(r'[\s\.,!?]', '', text)
    # Check if all remaining characters are Korean
    return bool(cleaned_text) and all('\uAC00' <= char <= '\uD7A3' for char in cleaned_text)

def augment_prompt_with_llm(prompt):
    """Augment Korean prompt using Friendli LLM API"""
    token = os.getenv("FRIENDLI_TOKEN")
    if not token:
        return prompt  # Return original if no token
    
    url = "https://api.friendli.ai/dedicated/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }
    
    # Create a system message for prompt augmentation
    system_message = """You are an expert at creating detailed, artistic prompts for ebook cover generation. 
    When given a Korean prompt, expand it into a detailed English description suitable for AI image generation.
    Focus on visual elements, artistic style, composition, lighting, and mood.
    Always end the prompt with '[trigger]' to activate the LoRA model."""
    
    payload = {
        "model": "dep89a2fld32mcm",
        "messages": [
            {
                "role": "system",
                "content": system_message
            },
            {
                "role": "user",
                "content": f"λ‹€μŒ ν•œκ΅­μ–΄ ν”„λ‘¬ν”„νŠΈλ₯Ό μ „μžμ±… ν‘œμ§€ 생성을 μœ„ν•œ μƒμ„Έν•œ μ˜μ–΄ ν”„λ‘¬ν”„νŠΈλ‘œ ν™•μž₯ν•΄μ£Όμ„Έμš”: {prompt}"
            }
        ],
        "max_tokens": 500,
        "top_p": 0.8,
        "stream": False
    }
    
    try:
        response = requests.post(url, json=payload, headers=headers, timeout=30)
        if response.status_code == 200:
            result = response.json()
            augmented_prompt = result['choices'][0]['message']['content']
            return augmented_prompt
        else:
            print(f"API Error: {response.status_code}")
            return prompt
    except Exception as e:
        print(f"Error calling LLM API: {e}")
        return prompt

def get_korean_font(font_name, font_size):
    """Load Korean font from the same directory as app.py"""
    font_files = {
        "λ‚˜λˆ”κ³ λ”•": "NanumGothic-Regular.ttf",
        "흑백사진": "BlackAndWhitePicture-Regular.ttf",
        "μΉ˜λ‘ μ„±": "ChironSungHK-VariableFont_wght.ttf",
        "독도": "Dokdo-Regular.ttf",
        "싱글데이": "SingleDay-Regular.ttf"
    }
    
    # Get the font file name
    font_file = font_files.get(font_name, "NanumGothic-Regular.ttf")
    print(f"Trying to load font: {font_name} -> {font_file}")  # Debug info
    
    # List of paths to try
    paths_to_try = [
        font_file,  # Current directory
        f"./{font_file}",  # Explicit current directory
        os.path.join(os.getcwd(), font_file),  # Full path from current working directory
        os.path.join(os.path.dirname(os.path.abspath(__file__)), font_file),  # Same directory as script
    ]
    
    # Try each path
    for path in paths_to_try:
        try:
            font = ImageFont.truetype(path, font_size)
            print(f"Successfully loaded font from: {path}")  # Debug info
            return font
        except Exception as e:
            print(f"Failed to load font from {path}: {e}")  # Debug info
            continue
    
    # If specific font not found, try to load NanumGothic as fallback
    print(f"Warning: {font_file} not found. Trying NanumGothic fallback...")  # Debug info
    for path in ["NanumGothic-Regular.ttf", "./NanumGothic-Regular.ttf"]:
        try:
            font = ImageFont.truetype(path, font_size)
            print(f"Loaded fallback font from: {path}")  # Debug info
            return font
        except:
            continue
    
    # Final fallback to default font
    print("Warning: No Korean fonts found. Using default font.")  # Debug info
    return ImageFont.load_default()

def add_text_overlay(image, title_ko, author_ko, 
                    title_position, author_position, text_color, font_name,
                    title_size, author_size):
    """Add Korean text overlay to the generated image"""
    print(f"add_text_overlay called with font_name: {font_name}")  # Debug info
    
    # Create a copy of the image to work with
    img_with_text = image.copy()
    draw = ImageDraw.Draw(img_with_text)
    
    # Load Korean fonts with custom sizes
    title_font = get_korean_font(font_name, title_size)
    author_font = get_korean_font(font_name, author_size)
    
    # Get image dimensions
    img_width, img_height = img_with_text.size
    
    # Define position mappings for horizontal text
    horizontal_position_coords = {
        "상단": (img_width // 2, img_height // 10),
        "쀑앙": (img_width // 2, img_height // 2),
        "ν•˜λ‹¨": (img_width // 2, img_height * 9 // 10)
    }
    
    # Define position mappings for vertical text
    vertical_position_coords = {
        "μ’ŒμΈ‘μƒλ‹¨": (img_width // 10, img_height // 10),
        "쀑앙상단": (img_width // 2, img_height // 10),
        "μš°μΈ‘μƒλ‹¨": (img_width * 9 // 10, img_height // 10)
    }
    
    shadow_offset = 2
    
    # Draw title (Korean only)
    if title_ko:
        # Check if title position is vertical
        if title_position in vertical_position_coords:
            # Vertical text rendering
            start_x, start_y = vertical_position_coords[title_position]
            
            # For vertical text, we need to draw each character separately
            for i, char in enumerate(title_ko):
                # Get character bbox
                try:
                    bbox = draw.textbbox((0, 0), char, font=title_font)
                    char_width = bbox[2] - bbox[0]
                    char_height = bbox[3] - bbox[1]
                except:
                    # Fallback for older PIL versions
                    char_width, char_height = draw.textsize(char, font=title_font)
                
                # Calculate position for this character
                char_x = start_x - char_width // 2
                # Use fixed spacing based on font size for consistent vertical spacing
                vertical_spacing = int(title_size * 1.2)  # 120% of font size for better spacing
                char_y = start_y + i * vertical_spacing
                
                # Draw shadow
                draw.text((char_x + shadow_offset, char_y + shadow_offset), 
                         char, font=title_font, fill="black")
                # Draw character
                draw.text((char_x, char_y), 
                         char, font=title_font, fill=text_color)
        else:
            # Horizontal text rendering (existing code)
            title_x, title_y = horizontal_position_coords[title_position]
            
            # Get text bbox for centering
            try:
                bbox = draw.textbbox((0, 0), title_ko, font=title_font)
                text_width = bbox[2] - bbox[0]
                text_height = bbox[3] - bbox[1]
            except:
                # Fallback for older PIL versions
                text_width, text_height = draw.textsize(title_ko, font=title_font)
            
            # Draw text with shadow for better visibility
            draw.text((title_x - text_width // 2 + shadow_offset, title_y - text_height // 2 + shadow_offset), 
                     title_ko, font=title_font, fill="black")
            draw.text((title_x - text_width // 2, title_y - text_height // 2), 
                     title_ko, font=title_font, fill=text_color)
    
    # Draw author (Korean only) - keeping horizontal only for now
    if author_ko:
        # Add "지은이: " prefix if not already present
        if not author_ko.startswith("지은이"):
            author_text = f"지은이: {author_ko}"
        else:
            author_text = author_ko
        
        # Check if author position is vertical
        if author_position in vertical_position_coords:
            # Vertical text rendering for author
            start_x, start_y = vertical_position_coords[author_position]
            
            # Adjust start_y for author (place it lower than title if both are vertical)
            if title_position in vertical_position_coords:
                # Calculate how much space the title takes with new spacing
                title_length = len(title_ko) if title_ko else 0
                vertical_spacing = int(title_size * 1.2)
                start_y += title_length * vertical_spacing + author_size
            
            for i, char in enumerate(author_text):
                # Get character bbox
                try:
                    bbox = draw.textbbox((0, 0), char, font=author_font)
                    char_width = bbox[2] - bbox[0]
                    char_height = bbox[3] - bbox[1]
                except:
                    # Fallback for older PIL versions
                    char_width, char_height = draw.textsize(char, font=author_font)
                
                # Calculate position for this character
                char_x = start_x - char_width // 2
                # Use fixed spacing based on font size for consistent vertical spacing
                vertical_spacing = int(author_size * 1.2)  # 120% of font size for better spacing
                char_y = start_y + i * vertical_spacing
                
                # Draw shadow
                draw.text((char_x + shadow_offset, char_y + shadow_offset), 
                         char, font=author_font, fill="black")
                # Draw character
                draw.text((char_x, char_y), 
                         char, font=author_font, fill=text_color)
        else:
            # Horizontal text rendering (existing code)
            author_x, author_y = horizontal_position_coords[author_position]
            
            # Get text bbox for centering
            try:
                bbox = draw.textbbox((0, 0), author_text, font=author_font)
                text_width = bbox[2] - bbox[0]
                text_height = bbox[3] - bbox[1]
            except:
                # Fallback for older PIL versions
                text_width, text_height = draw.textsize(author_text, font=author_font)
            
            # Draw text with shadow
            draw.text((author_x - text_width // 2 + shadow_offset, author_y - text_height // 2 + shadow_offset), 
                     author_text, font=author_font, fill="black")
            draw.text((author_x - text_width // 2, author_y - text_height // 2), 
                     author_text, font=author_font, fill=text_color)
    
    return img_with_text

def save_generated_image(image, prompt):
    # Generate unique filename with timestamp
    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)
    
    # Save the image
    image.save(filepath)
    
    # Save metadata
    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 []
    
    # Load all images from the directory
    image_files = [os.path.join(SAVE_DIR, f) for f in os.listdir(SAVE_DIR) 
                  if f.endswith(('.png', '.jpg', '.jpeg', '.webp'))]
    # Sort by creation time (newest first)
    image_files.sort(key=lambda x: os.path.getctime(x), reverse=True)
    return image_files

def load_predefined_images():
    # Return empty list since we're not using predefined images
    return []

@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,
    title_ko: str,
    author_ko: str,
    title_position: str,
    author_position: str,
    text_color: str,
    font_name: str,
    title_size: int,
    author_size: int,
    progress: gr.Progress = gr.Progress(track_tqdm=True),
):
    print(f"inference called with font_name: {font_name}")  # Debug info
    
    if randomize_seed:
        seed = random.randint(0, MAX_SEED)
    generator = torch.Generator(device=device).manual_seed(seed)
    
    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]
    
    # Add text overlay if any Korean text is provided
    if title_ko or author_ko:
        print(f"Adding text overlay with font: {font_name}")  # Debug info
        image = add_text_overlay(image, title_ko, author_ko,
                               title_position, author_position, text_color, font_name,
                               title_size, author_size)
    
    # Save the generated image
    filepath = save_generated_image(image, prompt)
    
    # Return the image, seed, and updated gallery
    return image, seed, load_generated_images()

def augment_prompt(prompt):
    """Handle prompt augmentation"""
    if is_korean_only(prompt):
        augmented = augment_prompt_with_llm(prompt)
        return augmented
    return prompt

examples = [
   "An anime-style illustration of a handsome male character with long, dark, flowing hair tied back partially with a traditional hairpiece. He wears a flowing, light-colored traditional East Asian robe with dark accents. His expression is thoughtful and slightly troubled, with his hand near his temple. In the blurred background, there are other figures in similar traditional attire, suggesting a scene of action or conflict in a fantasy setting. The overall mood is serious and dramatic, reminiscent of wuxia or xianxia genres.",
   "A fierce, action-oriented anime illustration of a male knight in full, dark, intricate armor. He has long, flowing dark hair and a confident, determined expression with a slight smirk. He wields a massive, ornate sword with a red glow on its blade, held high above his head in a striking pose. The background is a dramatic, desolate landscape with jagged mountains and a stormy, overcast sky, conveying a sense of epic conflict and adventure.",
   "A haunting cathedral ruins bathed in ethereal moonlight, with ancient stone archways stretching toward a starlit sky. The title 'WHISPERS OF ETERNITY' appears in weathered silver lettering that seems to float between the pillars. Ghostly wisps of fog curl around crumbling gothic sculptures, while 'By Alexander Blackwood' is inscribed in elegant script that glows with a subtle blue luminescence. Delicate patterns of celestial symbols and arcane runes border the edges. [trigger]",
   
   "A massive ancient tree with crystalline leaves dominates the composition, its translucent branches reaching across a sunset sky streaked with impossible colors. 'THE LUMINOUS Crown' is written in intricate golden calligraphy that intertwines with the branches. Mysterious glowing orbs float among the leaves, casting prismatic light. 'By Isabella Moonshadow' appears to be carved into the tree's bark. Sacred geometry patterns shimmer in the background. [trigger]",
   
   "A dramatic spiral staircase made of weathered copper and stained glass descends into swirling cosmic depths. The title 'CHRONICLES OF THE INFINITE' spans the spiral in bold art deco typography that seems to be crafted from constellations. Nebulae and galaxies swirl in the background, while 'By Marcus Starweaver' appears to be formed from falling stardust. Complex mechanical clockwork elements frame the corners. [trigger]",
   
   "An intricate doorway carved from ancient jade stands solitary in a field of shimmering black sand. 'GATES OF THE IMMORTAL' is emblazoned across the top in powerful metallic letters that seem to be forged from liquid mercury. Ethereal phoenix feathers drift across the scene, leaving trails of golden light. 'By Victoria Jade' flows along the bottom in brushstrokes that resemble living smoke. Sacred Chinese characters appear to float in the background. [trigger]",
   
   "A magnificent underwater city of pearl and coral rises from abyssal depths, illuminated by bioluminescent sea life. 'DEPTHS OF WONDER' ripples across the scene in iridescent letters that appear to be formed from living water. Schools of ethereal fish create flowing patterns of light, while 'By Neptune Rivers' shimmers like mother-of-pearl below. Ancient Atlantean symbols pulse with a subtle aqua glow around the borders. [trigger]",
   
   "A colossal steampunk clocktower pierces through storm clouds, its gears and mechanisms visible through crystalline walls. 'TIMEKEEPER'S LEGACY' is constructed from intricate brass and copper mechanisms that appear to be in constant motion. Lightning arcs between copper spires, while 'By Theodore Cogsworth' is etched in burnished bronze below. Mathematical equations and alchemical symbols float in the turbulent sky. [trigger]"
]

with gr.Blocks(theme=gr.themes.Soft(), analytics_enabled=False) as demo:
    gr.HTML('<div class="title"> eBOOK Cover generation </div>')
    
    gr.HTML("""<a href="https://visitorbadge.io/status?path=https%3A%2F%2Fginigen-Book-Cover.hf.space">
               <img src="https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Fginigen-Book-Cover.hf.space&countColor=%23263759" />
               </a>""")
    
    with gr.Tabs() as tabs:
        with gr.Tab("Generation"):
            with gr.Column(elem_id="col-container"):
                with gr.Row():
                    prompt = gr.Text(
                        label="Prompt",
                        show_label=False,
                        max_lines=1,
                        placeholder="Enter your prompt",
                        container=False,
                    )
                    augment_button = gr.Button("증강", scale=0)
                    run_button = gr.Button("Run", scale=0)

                # Modified to include the default image
                result = gr.Image(
                    label="Result",
                    show_label=False,
                    value=DEFAULT_IMAGE_PATH  # Set the default image
                )

                with gr.Accordion("Text Overlay Settings (ν•œκΈ€)", open=False):
                    with gr.Row():
                        with gr.Column():
                            title_ko = gr.Textbox(label="제λͺ©", placeholder="ν•œκΈ€ 제λͺ©μ„ μž…λ ₯ν•˜μ„Έμš”")
                            title_position = gr.Radio(
                                label="제λͺ© μœ„μΉ˜",
                                choices=["상단", "쀑앙", "ν•˜λ‹¨", "μ’ŒμΈ‘μƒλ‹¨", "쀑앙상단", "μš°μΈ‘μƒλ‹¨"],
                                value="상단",
                                info="μ’ŒμΈ‘μƒλ‹¨, 쀑앙상단, μš°μΈ‘μƒλ‹¨μ€ μ„Έλ‘œμ“°κΈ°μž…λ‹ˆλ‹€"
                            )
                            title_size = gr.Slider(
                                label="제λͺ© κΈ€μž 크기",
                                minimum=20,
                                maximum=200,
                                value=100,
                                step=2
                            )
                        with gr.Column():
                            author_ko = gr.Textbox(label="지은이", placeholder="지은이 이름을 μž…λ ₯ν•˜μ„Έμš”")
                            author_position = gr.Radio(
                                label="지은이 μœ„μΉ˜",
                                choices=["상단", "쀑앙", "ν•˜λ‹¨", "μ’ŒμΈ‘μƒλ‹¨", "쀑앙상단", "μš°μΈ‘μƒλ‹¨"],
                                value="ν•˜λ‹¨",
                                info="μ’ŒμΈ‘μƒλ‹¨, 쀑앙상단, μš°μΈ‘μƒλ‹¨μ€ μ„Έλ‘œμ“°κΈ°μž…λ‹ˆλ‹€"
                            )
                            author_size = gr.Slider(
                                label="지은이 κΈ€μž 크기",
                                minimum=16,
                                maximum=60,
                                value=32,
                                step=2
                            )
                    
                    with gr.Row():
                        with gr.Column():
                            font_name = gr.Dropdown(
                                label="폰트 선택",
                                choices=available_fonts,
                                value=available_fonts[0] if available_fonts else "λ‚˜λˆ”κ³ λ”•"
                            )
                        with gr.Column():
                            gr.Markdown("### κΈ€μž 색상 선택")
                            color_buttons = gr.Radio(
                                label="미리 μ •μ˜λœ 색상",
                                choices=[
                                    ("흰색", "#FFFFFF"),
                                    ("검정색", "#000000"),
                                    ("빨간색", "#FF0000"),
                                    ("νŒŒλž€μƒ‰", "#0000FF"),
                                    ("μ΄ˆλ‘μƒ‰", "#00FF00"),
                                    ("λ…Έλž€μƒ‰", "#FFFF00"),
                                    ("주황색", "#FFA500"),
                                    ("보라색", "#800080"),
                                    ("νšŒμƒ‰", "#808080"),
                                    ("κΈˆμƒ‰", "#FFD700"),
                                    ("은색", "#C0C0C0")
                                ],
                                value="#FFFFFF",
                                type="value"
                            )
                            
                            custom_color = gr.ColorPicker(
                                label="μ»€μŠ€ν…€ 색상 선택",
                                value="#FFFFFF",
                                visible=False
                            )
                            
                            text_color = gr.Textbox(
                                value="#FFFFFF",
                                visible=False
                            )

                with gr.Accordion("Advanced Settings", open=False):
                    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=768,
                        )
                        height = gr.Slider(
                            label="Height",
                            minimum=256,
                            maximum=MAX_IMAGE_SIZE,
                            step=32,
                            value=1024,
                        )

                    with gr.Row():
                        guidance_scale = gr.Slider(
                            label="Guidance scale",
                            minimum=0.0,
                            maximum=10.0,
                            step=0.1,
                            value=3.5,
                        )
                        num_inference_steps = gr.Slider(
                            label="Number of inference 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,
                        )

                gr.Examples(
                    examples=examples,
                    inputs=[prompt],
                    outputs=[result, seed],
                )

        with gr.Tab("Gallery"):
            gallery_header = gr.Markdown("### Generated Images Gallery")
            generated_gallery = gr.Gallery(
                label="Generated Images",
                columns=6,
                show_label=False,
                value=load_generated_images(),
                elem_id="generated_gallery",
                height="auto"
            )
            refresh_btn = gr.Button("πŸ”„ Refresh Gallery")

    # Event handlers
    def refresh_gallery():
        return load_generated_images()
    
    def update_color_visibility(selected_color):
        if selected_color == "custom":
            return gr.update(visible=True), gr.update(value="#FFFFFF")
        else:
            return gr.update(visible=False), gr.update(value=selected_color)
    
    def update_final_color(selected_color, custom_color_value):
        if selected_color == "custom":
            return custom_color_value
        else:
            return selected_color
    
    def on_font_change(font_name):
        print(f"Font changed to: {font_name}")
        return font_name

    refresh_btn.click(
        fn=refresh_gallery,
        inputs=None,
        outputs=generated_gallery,
    )
    
    augment_button.click(
        fn=augment_prompt,
        inputs=[prompt],
        outputs=[prompt],
    )
    
    font_name.change(
        fn=on_font_change,
        inputs=[font_name],
        outputs=[font_name]
    )
    
    color_buttons.change(
        fn=update_color_visibility,
        inputs=[color_buttons],
        outputs=[custom_color, text_color]
    )
    
    custom_color.change(
        fn=update_final_color,
        inputs=[color_buttons, custom_color],
        outputs=[text_color]
    )

    gr.on(
        triggers=[run_button.click, prompt.submit],
        fn=inference,
        inputs=[
            prompt,
            seed,
            randomize_seed,
            width,
            height,
            guidance_scale,
            num_inference_steps,
            lora_scale,
            title_ko,
            author_ko,
            title_position,
            author_position,
            text_color,
            font_name,
            title_size,
            author_size,
        ],
        outputs=[result, seed, generated_gallery],
    )

demo.queue()
demo.launch()