import gradio as gr import torch from diffusers import DiffusionPipeline import numpy as np from PIL import Image import random from typing import List, Tuple, Optional import time # Initialize the model def load_model(): """Load the Stable Diffusion XL model""" pipe = DiffusionPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16, use_safetensors=True, variant="fp16" ) if torch.cuda.is_available(): pipe = pipe.to("cuda") return pipe # Global model instance model = None def get_model(): """Get or create the model instance""" global model if model is None: model = load_model() return model def generate_images( prompt: str, negative_prompt: str = "", uploaded_images: Optional[List] = None, guidance_scale: float = 7.5, num_inference_steps: int = 50, strength: float = 0.8 ) -> Tuple[List[Image.Image], str]: """ Generate 4 images using Stable Diffusion XL """ try: pipe = get_model() # Default prompt if empty if not prompt.strip(): prompt = "a beautiful landscape, professional photography, high quality" # Check if we're doing img2img or text2img if uploaded_images and len(uploaded_images) > 0: # Use the first uploaded image for img2img init_image = uploaded_images[0] if isinstance(init_image, str): init_image = Image.open(init_image) # Generate 4 images with img2img images = [] for i in range(4): result = pipe( prompt=prompt, negative_prompt=negative_prompt, image=init_image, num_images_per_prompt=1, guidance_scale=guidance_scale, num_inference_steps=num_inference_steps, strength=strength ) images.append(result.images[0]) else: # Generate 4 images with text2img result = pipe( prompt=prompt, negative_prompt=negative_prompt, num_images_per_prompt=4, guidance_scale=guidance_scale, num_inference_steps=num_inference_steps ) images = result.images return images, "✅ Images generated successfully!" except Exception as e: error_msg = f"❌ Error generating images: {str(e)}" return [], error_msg def select_image_for_detail(gallery_data: List, evt: gr.SelectData) -> Tuple[Optional[Image.Image], str]: """ Handle image selection from gallery for detailed view """ if gallery_data and evt.index < len(gallery_data): selected_image = gallery_data[evt.index] if isinstance(selected_image, str): selected_image = Image.open(selected_image) return selected_image, f"📸 Selected image {evt.index + 1} for detailed view" return None, "No image selected" # Custom CSS for better styling custom_css = """ .main-container { max-width: 1200px; margin: 0 auto; } .gallery-container { border: 2px solid #e0e0e0; border-radius: 8px; padding: 10px; } .selected-image-container { border: 3px solid #4CAF50; border-radius: 8px; padding: 10px; } .generate-btn { background: linear-gradient(45deg, #667eea 0%, #764ba2 100%) !important; } """ # Create the Gradio interface with gr.Blocks(css=custom_css, title="Stable Diffusion XL Demo") as demo: gr.HTML("""
Generate amazing images with AI - Upload up to 4 images for img2img or use text prompts
Built with anycoder
Powered by Stability AI • Model: SDXL Base 1.0 • Built with anycoder