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