Spaces:
Sleeping
Sleeping
File size: 5,923 Bytes
1cbc077 116136a 1cbc077 ac34b16 6629ac2 1cbc077 6629ac2 1cbc077 6629ac2 801557d 6629ac2 595ca84 579622d 5ddafad 595ca84 801557d 595ca84 801557d 595ca84 579622d 6629ac2 579622d 6629ac2 801557d 6629ac2 801557d 116136a c0a712f 556fa9a 801557d 556fa9a f0b227c e730218 116136a |
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 |
import numpy as np
import torch
import torch.nn.functional as F
from torchvision.transforms.functional import normalize
import gradio as gr
from briarmbg import BriaRMBG
import PIL
from PIL import Image
import tempfile
import os
import time
import uuid
import shutil
# Load the pre-trained model
print("Loading model...")
net = BriaRMBG.from_pretrained("briaai/RMBG-1.4")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
net.to(device)
net.eval()
print(f"Model loaded on {device}")
# Create output directory if it doesn't exist
OUTPUT_DIR = "output_images"
os.makedirs(OUTPUT_DIR, exist_ok=True)
def process(image, progress=gr.Progress()):
if image is None:
return None, None, None
try:
progress(0, desc="Starting processing...")
orig_image = Image.fromarray(image)
original_size = orig_image.size
progress(0.2, desc="Preparing image...")
process_image = orig_image.resize(original_size, Image.LANCZOS)
w, h = process_image.size
im_np = np.array(process_image)
im_tensor = torch.tensor(im_np, dtype=torch.float32).permute(2, 0, 1)
im_tensor = torch.unsqueeze(im_tensor, 0)
im_tensor = torch.divide(im_tensor, 255.0)
im_tensor = normalize(im_tensor, [0.5, 0.5, 0.5], [1.0, 1.0, 1.0])
progress(0.4, desc="Processing with AI model...")
if torch.cuda.is_available():
im_tensor = im_tensor.cuda()
with torch.no_grad():
result = net(im_tensor)
progress(0.6, desc="Post-processing...")
result = torch.squeeze(F.interpolate(result[0][0], size=(h, w), mode='bilinear'), 0)
ma = torch.max(result)
mi = torch.min(result)
result = (result - mi) / (ma - mi)
result_array = (result * 255).cpu().data.numpy().astype(np.uint8)
pil_mask = Image.fromarray(np.squeeze(result_array))
if pil_mask.size != original_size:
pil_mask = pil_mask.resize(original_size, Image.LANCZOS)
new_im = orig_image.copy()
new_im.putalpha(pil_mask)
progress(0.8, desc="Saving result...")
unique_id = str(uuid.uuid4())[:8]
filename = f"background_removed_{unique_id}.png"
filepath = os.path.join(OUTPUT_DIR, filename)
new_im.save(filepath, format='PNG', quality=100)
# Convert to numpy array for display
output_array = np.array(new_im.convert('RGBA'))
progress(1.0, desc="Done!")
return (
output_array,
gr.update(value=filepath, visible=True),
gr.update(value=f"""
<script>
setTimeout(function() {{
window.location.href = '/file={filepath}';
}}, 1000);
</script>
""")
)
except Exception as e:
print(f"Error processing image: {str(e)}")
return None, None, None
css = """
@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;500;700&display=swap');
.title-text {
color: #ff00de;
font-family: 'Orbitron', sans-serif;
font-size: 2.5em;
text-align: center;
margin: 20px 0;
text-shadow: 0 0 10px rgba(255, 0, 222, 0.7);
animation: glow 2s ease-in-out infinite alternate;
}
.subtitle-text {
color: #00ffff;
text-align: center;
margin-bottom: 30px;
font-size: 1.2em;
text-shadow: 0 0 8px rgba(0, 255, 255, 0.7);
}
.image-container {
background: rgba(10, 10, 30, 0.3);
border-radius: 15px;
padding: 20px;
margin: 10px 0;
border: 2px solid #00ffff;
box-shadow: 0 0 15px rgba(0, 255, 255, 0.2);
transition: all 0.3s ease;
}
.image-container img {
max-width: 100%;
height: auto;
display: block;
margin: 0 auto;
}
.image-container:hover {
box-shadow: 0 0 20px rgba(0, 255, 255, 0.4);
transform: translateY(-2px);
}
.download-btn {
background: linear-gradient(45deg, #00ffff, #ff00de);
border: none;
padding: 12px 25px;
border-radius: 8px;
color: white;
font-family: 'Orbitron', sans-serif;
cursor: pointer;
transition: all 0.3s ease;
margin-top: 10px;
text-align: center;
text-transform: uppercase;
letter-spacing: 1px;
width: 100%;
display: block;
}
.download-btn:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(0, 255, 255, 0.4);
}
@keyframes glow {
from { text-shadow: 0 0 5px #ff00de, 0 0 10px #ff00de; }
to { text-shadow: 0 0 10px #ff00de, 0 0 20px #ff00de; }
}
@media (max-width: 768px) {
.title-text { font-size: 1.8em; }
.subtitle-text { font-size: 1em; }
.image-container { padding: 10px; }
.download-btn { padding: 10px 20px; }
}
"""
with gr.Blocks(css=css) as demo:
gr.Markdown("""
<h1 class="title-text">AI Background Removal</h1>
<p class="subtitle-text">Remove backgrounds instantly using advanced AI technology</p>
""")
with gr.Row():
with gr.Column():
input_image = gr.Image(
label="Upload Image",
type="numpy",
elem_classes="image-container"
)
output_image = gr.Image(
label="Result",
type="numpy",
show_label=True,
elem_classes="image-container"
)
download_button = gr.File(
label="Download Processed Image",
visible=True,
elem_classes="download-btn"
)
auto_download = gr.HTML(visible=False)
input_image.change(
fn=process,
inputs=input_image,
outputs=[output_image, download_button, auto_download]
)
if __name__ == "__main__":
demo.launch() |