import gradio as gr from PIL import Image, ImageDraw, ImageFont, ImageFilter import numpy as np # Background presets BACKGROUND_PRESETS = { "Studio White": "a clean white photography studio background with soft lighting", "Gradient Sunset": "a beautiful gradient sunset background with warm orange and pink colors", "Minimalist Gray": "a minimalist gray gradient background, professional and clean", "Nature Forest": "a blurred natural forest background with soft green bokeh", "Beach Paradise": "a tropical beach background with turquoise water and white sand", "City Skyline": "a modern city skyline at dusk with soft bokeh lights", "Marble Luxury": "a luxurious white marble background with gold veins", "Bokeh Lights": "a dreamy bokeh lights background with warm golden circles", "Pastel Pink": "a soft pastel pink gradient background, aesthetic and dreamy", "Dark Moody": "a dark moody background with dramatic lighting and shadows", "Wooden Texture": "a warm wooden texture background with natural grain", "Concrete Modern": "a modern concrete texture background, industrial style", } # Preset colors for visual demo PRESET_COLORS = { "Studio White": [(255, 255, 255), (245, 245, 245)], "Gradient Sunset": [(255, 140, 100), (255, 80, 150)], "Minimalist Gray": [(200, 200, 200), (150, 150, 150)], "Nature Forest": [(100, 180, 100), (60, 140, 80)], "Beach Paradise": [(100, 200, 255), (150, 220, 255)], "City Skyline": [(60, 80, 120), (40, 50, 80)], "Marble Luxury": [(240, 240, 240), (220, 215, 200)], "Bokeh Lights": [(255, 200, 100), (255, 180, 80)], "Pastel Pink": [(255, 200, 220), (255, 220, 240)], "Dark Moody": [(30, 30, 40), (50, 50, 60)], "Wooden Texture": [(160, 120, 80), (140, 100, 60)], "Concrete Modern": [(120, 120, 120), (100, 100, 100)], } def create_gradient_background(width, height, colors): """Create a gradient background""" img = Image.new('RGB', (width, height)) draw = ImageDraw.Draw(img) color1, color2 = colors for i in range(height): ratio = i / height r = int(color1[0] * (1 - ratio) + color2[0] * ratio) g = int(color1[1] * (1 - ratio) + color2[1] * ratio) b = int(color1[2] * (1 - ratio) + color2[2] * ratio) draw.line([(0, i), (width, i)], fill=(r, g, b)) return img def swap_background(image, preset_name, custom_prompt=None): """ Demo version: Simulates background swap with gradient overlay """ if image is None: return None, "❌ Please upload an image first!" # Get background description if custom_prompt and custom_prompt.strip(): background_desc = custom_prompt.strip() colors = PRESET_COLORS["Studio White"] # Default for custom else: background_desc = BACKGROUND_PRESETS.get(preset_name, BACKGROUND_PRESETS["Studio White"]) colors = PRESET_COLORS.get(preset_name, PRESET_COLORS["Studio White"]) # Create demo output with gradient overlay width, height = image.size # Create gradient background background = create_gradient_background(width, height, colors) # Apply slight blur to original image to simulate background effect result = image.copy() # Blend with gradient (subtle effect for demo) result = Image.blend(result, background, alpha=0.3) # Add watermark to show it's a demo draw = ImageDraw.Draw(result) watermark_text = f"DEMO: {preset_name}" # Simple text overlay try: # Try to use a font, fallback to default if not available font = ImageFont.truetype("arial.ttf", 30) except: font = ImageFont.load_default() # Add semi-transparent overlay for text overlay = Image.new('RGBA', result.size, (0, 0, 0, 0)) overlay_draw = ImageDraw.Draw(overlay) text_bbox = overlay_draw.textbbox((0, 0), watermark_text, font=font) text_width = text_bbox[2] - text_bbox[0] text_height = text_bbox[3] - text_bbox[1] x = (width - text_width) // 2 y = height - text_height - 20 overlay_draw.rectangle( [x - 10, y - 10, x + text_width + 10, y + text_height + 10], fill=(0, 0, 0, 128) ) overlay_draw.text((x, y), watermark_text, fill=(255, 255, 255, 255), font=font) result = Image.alpha_composite(result.convert('RGBA'), overlay).convert('RGB') status_msg = f"""✨ Demo Preview Generated! 🎨 **Selected Preset:** {preset_name} 📝 **Background Description:** {background_desc} âš ī¸ **This is a UI Demo Version** For actual AI-powered background swapping, this Space requires: â€ĸ GPU hardware (T4 or better) â€ĸ Upgrade to use the production version with real image editing **To enable full features:** 1. Go to Space Settings 2. Upgrade to GPU (T4 Small recommended) 3. The app will automatically use the advanced background removal + inpainting **Current Demo Mode:** â€ĸ Shows UI and workflow â€ĸ Simulates background with gradient overlay â€ĸ No actual AI model running (stays within 16GB CPU limit) **Production Mode Features:** â€ĸ Real background removal with RMBG-1.4 â€ĸ AI-generated backgrounds with Stable Diffusion â€ĸ Professional quality results """ return result, status_msg # Custom CSS for aesthetic design custom_css = """ .gradio-container { font-family: 'Inter', sans-serif; max-width: 1200px !important; margin: auto; } .preset-button { border-radius: 12px !important; padding: 10px 20px !important; font-weight: 500 !important; } #title { text-align: center; font-size: 2.5em; font-weight: 700; margin-bottom: 0.5em; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } #subtitle { text-align: center; font-size: 1.1em; color: #666; margin-bottom: 2em; } """ # Create Gradio interface with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo: gr.HTML("

🎨 Background Swap Studio

") gr.HTML("

Upload any image and instantly swap backgrounds with AI-powered presets

") gr.Markdown(""" ### â„šī¸ Demo Mode Active This Space is running in **Demo Mode** on CPU (free tier). Upgrade to GPU for full AI-powered background swapping! [See status message below after processing] """) with gr.Row(): with gr.Column(scale=1): input_image = gr.Image( label="📤 Upload Your Image", type="pil", height=400 ) gr.Markdown("### 🎭 Choose a Background Preset") preset_dropdown = gr.Dropdown( choices=list(BACKGROUND_PRESETS.keys()), value="Studio White", label="Background Style", interactive=True ) with gr.Accordion("✨ Custom Background (Optional)", open=False): custom_prompt = gr.Textbox( label="Describe Your Custom Background", placeholder="e.g., a magical starry night sky with northern lights", lines=2 ) swap_btn = gr.Button("đŸĒ„ Preview Background", variant="primary", size="lg") gr.Markdown("### 💡 Tips") gr.Markdown(""" - Works best with clear subjects (products, portraits, pets) - Upload high-quality images for best results - Try different presets to find your style """) with gr.Column(scale=1): output_image = gr.Image( label="✨ Preview (Demo Mode)", type="pil", height=400 ) status_text = gr.Textbox( label="📊 Status & Information", lines=12, interactive=False ) gr.Markdown("### 🎨 Quick Preset Gallery") preset_gallery = gr.Examples( examples=[ ["Studio White"], ["Gradient Sunset"], ["Nature Forest"], ["Bokeh Lights"], ], inputs=[preset_dropdown], label="Popular Presets" ) # Event handlers swap_btn.click( fn=swap_background, inputs=[input_image, preset_dropdown, custom_prompt], outputs=[output_image, status_text] ) gr.Markdown(""" --- ### 📖 About Background Swap Studio **What This App Does:** Professional background swapping for product photos, portraits, pets, and creative content. **Current Status: Demo Mode** - Running on CPU (free tier) with 16GB RAM - Shows UI, workflow, and preset system - Creates gradient overlay previews **Full Production Version Includes:** - 🤖 RMBG-1.4 for intelligent subject detection - 🎨 Stable Diffusion 2 Inpainting for realistic backgrounds - đŸ–ŧī¸ Professional quality results - ⚡ Fast processing with GPU acceleration **To Upgrade to Full Version:** 1. Go to Space Settings → Hardware 2. Select "T4 Small" GPU (~$0.60/hour) 3. App will automatically load full models **Use Cases:** - E-commerce product photography - Social media content creation - Professional headshots - Creative photo editing --- Built with â¤ī¸ using Gradio â€ĸ [Documentation](https://github.com) â€ĸ [Report Issues](https://github.com) """) # Launch if __name__ == "__main__": demo.launch()