File size: 19,747 Bytes
036dfc6
4c9a6f0
036dfc6
4c9a6f0
 
036dfc6
 
4c9a6f0
036dfc6
289e506
 
 
 
4c9a6f0
036dfc6
 
 
 
4c9a6f0
a8084f8
 
 
036dfc6
 
0cf7a7f
4c9a6f0
036dfc6
 
 
4c9a6f0
036dfc6
 
4c9a6f0
289e506
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff70eba
 
 
 
 
 
 
 
 
 
 
 
 
 
90456d7
ff70eba
90456d7
 
ff70eba
 
 
 
90456d7
 
ff70eba
90456d7
 
289e506
 
 
 
90456d7
ff70eba
 
289e506
 
 
 
 
 
90456d7
 
 
289e506
 
90456d7
 
289e506
 
 
90456d7
289e506
 
 
 
 
 
90456d7
289e506
90456d7
289e506
90456d7
 
 
 
 
 
 
 
289e506
 
 
 
 
 
 
 
 
90456d7
289e506
90456d7
289e506
 
 
036dfc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c9a6f0
036dfc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289e506
 
 
 
 
90456d7
 
036dfc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90456d7
 
 
ff70eba
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
 
 
 
 
 
 
 
ff70eba
90456d7
289e506
 
90456d7
289e506
90456d7
 
 
 
 
 
 
 
ff70eba
90456d7
289e506
 
90456d7
 
 
 
 
 
 
 
 
 
289e506
036dfc6
 
 
 
 
4c9a6f0
036dfc6
4c9a6f0
036dfc6
 
 
 
 
 
 
 
5a29a17
036dfc6
 
 
 
 
 
5a29a17
036dfc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c9a6f0
 
036dfc6
 
 
 
 
 
 
 
 
4c9a6f0
036dfc6
4c9a6f0
036dfc6
 
 
4c9a6f0
036dfc6
 
 
 
4c9a6f0
289e506
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c9a6f0
036dfc6
 
 
 
 
 
 
 
 
 
 
 
289e506
 
 
 
 
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
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

# 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_size):
    """Load NanumGothic font from the same directory as app.py"""
    try:
        # Try to load NanumGothic-Regular.ttf from the same directory
        font_path = "NanumGothic-Regular.ttf"
        return ImageFont.truetype(font_path, font_size)
    except:
        # If font file is not found, try alternative paths
        alternative_paths = [
            "./NanumGothic-Regular.ttf",
            os.path.join(os.path.dirname(__file__), "NanumGothic-Regular.ttf"),
        ]
        
        for path in alternative_paths:
            try:
                return ImageFont.truetype(path, font_size)
            except:
                continue
        
        # Final fallback to default font
        print("Warning: NanumGothic-Regular.ttf not found. Using default font.")
        return ImageFont.load_default()

def add_text_overlay(image, title_ko, author_ko, 
                    title_position, author_position, text_color,
                    title_size, author_size):
    """Add Korean text overlay to the generated image"""
    # 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(title_size)
    author_font = get_korean_font(author_size)
    
    # Get image dimensions
    img_width, img_height = img_with_text.size
    
    # Define position mappings
    position_coords = {
        "상단": (img_width // 2, img_height // 10),
        "쀑앙": (img_width // 2, img_height // 2),
        "ν•˜λ‹¨": (img_width // 2, img_height * 9 // 10)
    }
    
    # Draw title (Korean only)
    if title_ko:
        title_x, title_y = position_coords[title_position]
        
        # Get text bbox for centering
        bbox = draw.textbbox((0, 0), title_ko, font=title_font)
        text_width = bbox[2] - bbox[0]
        text_height = bbox[3] - bbox[1]
        
        # Draw text with shadow for better visibility
        shadow_offset = 2
        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)
    if author_ko:
        # Add "지은이: " prefix if not already present
        if not author_ko.startswith("지은이"):
            author_text = f"지은이: {author_ko}"
        else:
            author_text = author_ko
            
        author_x, author_y = position_coords[author_position]
        
        # Get text bbox for centering
        bbox = draw.textbbox((0, 0), author_text, font=author_font)
        text_width = bbox[2] - bbox[0]
        text_height = bbox[3] - bbox[1]
        
        # 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,
    title_size: int,
    author_size: int,
    progress: gr.Progress = gr.Progress(track_tqdm=True),
):
    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:
        image = add_text_overlay(image, title_ko, author_ko,
                               title_position, author_position, text_color,
                               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="상단"
                            )
                            title_size = gr.Slider(
                                label="제λͺ© κΈ€μž 크기",
                                minimum=20,
                                maximum=100,
                                value=48,
                                step=2
                            )
                        with gr.Column():
                            author_ko = gr.Textbox(label="지은이", placeholder="지은이 이름을 μž…λ ₯ν•˜μ„Έμš”")
                            author_position = gr.Radio(
                                label="지은이 μœ„μΉ˜",
                                choices=["상단", "쀑앙", "ν•˜λ‹¨"],
                                value="ν•˜λ‹¨"
                            )
                            author_size = gr.Slider(
                                label="지은이 κΈ€μž 크기",
                                minimum=16,
                                maximum=60,
                                value=32,
                                step=2
                            )
                    
                    with gr.Row():
                        font_name = gr.Dropdown(
                            label="폰트 선택",
                            choices=["λ‚˜λˆ”κ³ λ”•", "λ‚˜λˆ”λͺ…μ‘°", "맑은 κ³ λ”•", "바탕", "돋움", "κΈ°λ³Έ"],
                            value="λ‚˜λˆ”κ³ λ”•"
                        )
                        text_color = gr.ColorPicker(
                            label="κΈ€μž 색상",
                            value="#FFFFFF"
                        )

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

    refresh_btn.click(
        fn=refresh_gallery,
        inputs=None,
        outputs=generated_gallery,
    )
    
    # Augment button handler
    augment_button.click(
        fn=augment_prompt,
        inputs=[prompt],
        outputs=[prompt],
    )

    # Auto-augment Korean prompts
    def handle_prompt_change(prompt_text):
        if is_korean_only(prompt_text):
            return augment_prompt_with_llm(prompt_text)
        return prompt_text
    
    # Optional: Auto-augment on prompt change (commented out to avoid too many API calls)
    # prompt.change(
    #     fn=handle_prompt_change,
    #     inputs=[prompt],
    #     outputs=[prompt]
    # )

    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,
            title_size,
            author_size,
        ],
        outputs=[result, seed, generated_gallery],
    )

demo.queue()
demo.launch()