Book-Cover / app.py
ginipick's picture
Update app.py
ff70eba verified
raw
history blame
19.7 kB
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()