Spaces:
Runtime error
Runtime error
File size: 9,607 Bytes
8e8f8be cc419bc 8e8f8be cc419bc 8e8f8be cc419bc 8e8f8be cc419bc 8e8f8be cc419bc 8e8f8be cc419bc 8e8f8be cc419bc 8e8f8be cc419bc 8e8f8be cc419bc 8e8f8be cc419bc 8e8f8be cc419bc 8e8f8be cc419bc 8e8f8be cc419bc 8e8f8be cc419bc 8e8f8be cc419bc 8e8f8be cc419bc 8e8f8be | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | 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("<h1 id='title'>π¨ Background Swap Studio</h1>")
gr.HTML("<p id='subtitle'>Upload any image and instantly swap backgrounds with AI-powered presets</p>")
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()
|