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 # 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) device = "cuda" if torch.cuda.is_available() else "cpu" repo_id = "black-forest-labs/FLUX.1-dev" adapter_id = "openfree/flux-lora-korea-palace" 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 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, 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] # Save the generated image filepath = save_generated_image(image, prompt) # Return the image, seed, and updated gallery return image, seed, load_generated_images() examples = [ "Geunjeongjeon Hall of Gyeongbokgung Palace in spring, with cherry blossoms in full bloom. The majestic throne hall stands proudly against a backdrop of pink petals, its vibrant dancheong colors harmonizing with the spring flowers. Traditional stone markers and carefully manicured royal gardens frame the scene, while Mount Bugaksan rises majestically in the background. [trigger]", "Summer sunrise at Geunjeongjeon Hall, Gyeongbokgung Palace. The golden morning light illuminates the grand wooden pillars and intricate roof tiles. Royal court musicians in traditional hanbok are preparing for the morning ceremony on the courtyard's stone steps, while the hall's reflection shimmers in the morning dew. [trigger]", "Autumn twilight at Geunjeongjeon Hall. The royal throne hall is surrounded by maple and ginkgo trees in brilliant red and gold. The traditional blue and red dancheong paintings contrast beautifully with the warm autumn colors, while palace lanterns begin to glow in the approaching dusk. [trigger]", "Winter scene at Geunjeongjeon Hall, with heavy snow blanketing the palace grounds. The hall's majestic double-tiered roof stands out against the pure white landscape, its dragon carvings dusted with snow. Frozen lotus ponds and snow-covered stone bridges create a serene winter wonderland. [trigger]", "Geunjeongjeon Hall during a traditional royal ceremony under the full moon. Palace guards in historical uniforms stand at attention as lantern light dances across the ancient wooden structures. The moonlight casts dramatic shadows of the throne hall's curved eaves onto the frost-covered courtyard. [trigger]", "Rainy season at Geunjeongjeon Hall. Mist shrouds the grand throne hall as summer rain falls softly on the ancient tiles. Water droplets cascade from the ornate roof dragons, while the wet stone steps gleam with reflected light from traditional palace lanterns. The rain creates a mystical atmosphere around the royal court architecture. [trigger]" ] css = """ footer { visibility: hidden; } """ with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", css=css, analytics_enabled=False) as demo: gr.HTML('