import os import gc import re import gradio as gr import numpy as np import torch import json import spaces import config import utils import logging import time from datetime import datetime from typing import List, Dict, Tuple, Optional from PIL import Image, PngImagePlugin from diffusers.models import AutoencoderKL from diffusers import StableDiffusionXLPipeline, StableDiffusionXLImg2ImgPipeline from transformers import pipeline as translation_pipeline from config import ( MODEL, MIN_IMAGE_SIZE, MAX_IMAGE_SIZE, USE_TORCH_COMPILE, ENABLE_CPU_OFFLOAD, OUTPUT_DIR, DEFAULT_NEGATIVE_PROMPT, DEFAULT_ASPECT_RATIO, examples, sampler_list, aspect_ratios, style_list, ) # Enhanced logging configuration logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) logger = logging.getLogger(__name__) # Constants IS_COLAB = utils.is_google_colab() or os.getenv("IS_COLAB") == "1" HF_TOKEN = os.getenv("HF_TOKEN") CACHE_EXAMPLES = torch.cuda.is_available() and os.getenv("CACHE_EXAMPLES") == "1" # PyTorch settings for better performance and determinism torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False torch.backends.cuda.matmul.allow_tf32 = True device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") logger.info(f"Using device: {device}") # 번역 파이프라인 초기화 (한글 → 영어) translator = translation_pipeline("translation", model="Helsinki-NLP/opus-mt-ko-en") class GenerationError(Exception): """Custom exception for generation errors""" pass def translate_if_korean(prompt: str) -> str: """프롬프트에 한글이 포함되어 있으면 영어로 번역""" if re.search(r'[ㄱ-ㅎㅏ-ㅣ가-힣]', prompt): logger.info("Korean detected in prompt. Translating to English...") try: translation = translator(prompt)[0]['translation_text'] logger.info(f"Translation result: {translation}") return translation except Exception as e: logger.error(f"Translation error: {e}") # 번역 실패 시 원본 프롬프트 사용 return prompt return prompt def validate_prompt(prompt: str) -> str: """Validate and clean up the input prompt.""" if not isinstance(prompt, str): raise GenerationError("Prompt must be a string") try: # Ensure proper UTF-8 encoding/decoding prompt = prompt.encode('utf-8').decode('utf-8') # Add space between ! and , prompt = prompt.replace("!,", "! ,") except UnicodeError: raise GenerationError("Invalid characters in prompt") # Only check if the prompt is completely empty or only whitespace if not prompt or prompt.isspace(): raise GenerationError("Prompt cannot be empty") # 번역 적용: 한글이 감지되면 영어로 변환 prompt = translate_if_korean(prompt) return prompt.strip() def validate_dimensions(width: int, height: int) -> None: """Validate image dimensions.""" if not MIN_IMAGE_SIZE <= width <= MAX_IMAGE_SIZE: raise GenerationError(f"Width must be between {MIN_IMAGE_SIZE} and {MAX_IMAGE_SIZE}") if not MIN_IMAGE_SIZE <= height <= MAX_IMAGE_SIZE: raise GenerationError(f"Height must be between {MIN_IMAGE_SIZE} and {MAX_IMAGE_SIZE}") @spaces.GPU def generate( prompt: str, negative_prompt: str = DEFAULT_NEGATIVE_PROMPT, seed: int = 0, custom_width: int = 1024, # 기본 크기를 1024로 설정 custom_height: int = 1024, # 기본 크기를 1024로 설정 guidance_scale: float = 6.0, num_inference_steps: int = 25, sampler: str = "Euler a", aspect_ratio_selector: str = DEFAULT_ASPECT_RATIO, style_selector: str = "(None)", use_upscaler: bool = False, upscaler_strength: float = 0.55, upscale_by: float = 1.5, add_quality_tags: bool = True, progress: gr.Progress = gr.Progress(track_tqdm=True), ) -> Tuple[List[str], Dict]: """Generate images based on the given parameters.""" start_time = time.time() upscaler_pipe = None backup_scheduler = None try: # Memory management torch.cuda.empty_cache() gc.collect() # Input validation prompt = validate_prompt(prompt) if negative_prompt: negative_prompt = negative_prompt.encode('utf-8').decode('utf-8') validate_dimensions(custom_width, custom_height) # Set up generation generator = utils.seed_everything(seed) width, height = utils.aspect_ratio_handler( aspect_ratio_selector, custom_width, custom_height, ) # Process prompts if add_quality_tags: prompt = f"masterpiece, high score, great score, absurdres, {prompt}" prompt, negative_prompt = utils.preprocess_prompt( styles, style_selector, prompt, negative_prompt ) width, height = utils.preprocess_image_dimensions(width, height) # Set up pipeline backup_scheduler = pipe.scheduler pipe.scheduler = utils.get_scheduler(pipe.scheduler.config, sampler) if use_upscaler: upscaler_pipe = StableDiffusionXLImg2ImgPipeline(**pipe.components) # Prepare metadata metadata = { "prompt": prompt, "negative_prompt": negative_prompt, "resolution": f"{width} x {height}", "guidance_scale": guidance_scale, "num_inference_steps": num_inference_steps, "style_preset": style_selector, "seed": seed, "sampler": sampler, "Model": "Animagine XL 4.0", "Model hash": "e3c47aedb0", } if use_upscaler: new_width = int(width * upscale_by) new_height = int(height * upscale_by) metadata["use_upscaler"] = { "upscale_method": "nearest-exact", "upscaler_strength": upscaler_strength, "upscale_by": upscale_by, "new_resolution": f"{new_width} x {new_height}", } else: metadata["use_upscaler"] = None logger.info(f"Starting generation with parameters: {json.dumps(metadata, indent=4)}") # Generate images if use_upscaler: latents = pipe( prompt=prompt, negative_prompt=negative_prompt, width=width, height=height, guidance_scale=guidance_scale, num_inference_steps=num_inference_steps, generator=generator, output_type="latent", ).images upscaled_latents = utils.upscale(latents, "nearest-exact", upscale_by) images = upscaler_pipe( prompt=prompt, negative_prompt=negative_prompt, image=upscaled_latents, guidance_scale=guidance_scale, num_inference_steps=num_inference_steps, strength=upscaler_strength, generator=generator, output_type="pil", ).images else: images = pipe( prompt=prompt, negative_prompt=negative_prompt, width=width, height=height, guidance_scale=guidance_scale, num_inference_steps=num_inference_steps, generator=generator, output_type="pil", ).images # Save images if images: total = len(images) image_paths = [] for idx, image in enumerate(images, 1): progress(idx/total, desc="Saving images...") path = utils.save_image(image, metadata, OUTPUT_DIR, IS_COLAB) image_paths.append(path) logger.info(f"Image {idx}/{total} saved as {path}") generation_time = time.time() - start_time logger.info(f"Generation completed successfully in {generation_time:.2f} seconds") metadata["generation_time"] = f"{generation_time:.2f}s" return image_paths, metadata except GenerationError as e: logger.warning(f"Generation validation error: {str(e)}") raise gr.Error(str(e)) except Exception as e: logger.exception("Unexpected error during generation") raise gr.Error(f"Generation failed: {str(e)}") finally: # Cleanup torch.cuda.empty_cache() gc.collect() if upscaler_pipe is not None: del upscaler_pipe if backup_scheduler is not None and pipe is not None: pipe.scheduler = backup_scheduler utils.free_memory() # Model initialization if torch.cuda.is_available(): try: logger.info("Loading VAE and pipeline...") vae = AutoencoderKL.from_pretrained( "madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16, ) pipe = utils.load_pipeline(MODEL, device, vae=vae) logger.info("Pipeline loaded successfully on GPU!") except Exception as e: logger.error(f"Error loading VAE, falling back to default: {e}") pipe = utils.load_pipeline(MODEL, device) else: logger.warning("CUDA not available, running on CPU") pipe = None # Process styles styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list} # 사용자 인터페이스 (UI) 개선: CSS 스타일 및 레이아웃 수정 custom_css = """ /* 배경 및 글자 색상 변경 */ body { background-color: #f7f9fc; color: #333; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } /* 헤더 스타일 */ .header { text-align: center; padding: 20px; } .header .title { font-size: 3em; font-weight: bold; color: #2c3e50; } .header .subtitle { font-size: 1.2em; color: #7f8c8d; } a { text-decoration: none; color: #3498db; } /* Discord 버튼 스타일 */ .discord-btn { display: flex; align-items: center; justify-content: center; padding: 10px 20px; background: #7289da; color: white; border-radius: 8px; font-weight: bold; margin-top: 20px; } .discord-btn:hover { background: #5b6eae; } .discord-icon { width: 24px; height: 24px; margin-right: 8px; } /* Gradio 갤러리 스타일 개선 */ .gradio-gallery { border: none; box-shadow: none; } """ with gr.Blocks(css=custom_css, theme="default") as demo: # 상단 헤더 gr.HTML( """