Spaces:
Running
Running
File size: 6,878 Bytes
49f1016 562254a 72cef1f 49f1016 72cef1f 49f1016 36df28d 49f1016 72cef1f 49f1016 72cef1f 562254a 72cef1f 49f1016 36df28d 49f1016 36df28d 7160c3c 72cef1f 562254a 72cef1f 49f1016 72cef1f 49f1016 562254a 72cef1f 49f1016 72cef1f 49f1016 72cef1f 49f1016 562254a 72cef1f 562254a 72cef1f 562254a 72cef1f 562254a 72cef1f 562254a 72cef1f 49f1016 72cef1f 49f1016 72cef1f 562254a 49f1016 72cef1f 562254a 36df28d 562254a 36df28d 7160c3c 562254a 49f1016 72cef1f 49f1016 72cef1f 562254a 49f1016 562254a 49f1016 72cef1f 49f1016 72cef1f 49f1016 72cef1f 562254a 49f1016 562254a 49f1016 72cef1f 49f1016 72cef1f 49f1016 36df28d 49f1016 72cef1f 49f1016 72cef1f 49f1016 72cef1f 49f1016 72cef1f 49f1016 562254a 49f1016 562254a 49f1016 562254a 49f1016 562254a 49f1016 562254a 36df28d 49f1016 562254a 36df28d 49f1016 562254a 49f1016 562254a 49f1016 562254a 49f1016 562254a 49f1016 36df28d 49f1016 36df28d 562254a 36df28d 49f1016 36df28d 49f1016 562254a 36df28d 49f1016 36df28d 49f1016 562254a 72cef1f 49f1016 562254a 49f1016 562254a | 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 | import os
import torch
import numpy as np
from fastapi import FastAPI, UploadFile, File, Form, HTTPException
from fastapi.responses import StreamingResponse, HTMLResponse
from PIL import Image
from io import BytesIO
import requests
from transformers import AutoModelForImageSegmentation
import uvicorn
# ---------------------------------------------------------
# CPU optimization (important for HF Spaces)
# ---------------------------------------------------------
os.environ["OMP_NUM_THREADS"] = "1"
os.environ["MKL_NUM_THREADS"] = "1"
torch.set_num_threads(1)
# ---------------------------------------------------------
# Config (speed focused)
# ---------------------------------------------------------
TARGET_SIZE = (320, 320) # π₯ faster inference
MAX_FILE_SIZE = 5 * 1024 * 1024 # 5MB
MAX_COMPRESS_DIM = 1400 # aggressive resize
# ---------------------------------------------------------
# Load model
# ---------------------------------------------------------
MODEL_DIR = "models/BiRefNet"
os.makedirs(MODEL_DIR, exist_ok=True)
device = "cuda" if torch.cuda.is_available() else "cpu"
dtype = torch.float16 if torch.cuda.is_available() else torch.float32
print("Loading model...")
model = AutoModelForImageSegmentation.from_pretrained(
"ZhengPeng7/BiRefNet",
cache_dir=MODEL_DIR,
trust_remote_code=True
)
model.to(device, dtype=dtype).eval()
print("Model ready")
# ---------------------------------------------------------
# Image helpers
# ---------------------------------------------------------
def load_image_from_url(url: str):
r = requests.get(url, timeout=10)
r.raise_for_status()
return Image.open(BytesIO(r.content)).convert("RGB")
# π₯ FAST compression (key part)
def compress_if_needed(img: Image.Image, raw_bytes: bytes):
if len(raw_bytes) <= MAX_FILE_SIZE:
return img
print("[INFO] Compressing image >5MB")
img = img.convert("RGB")
# Resize aggressively
w, h = img.size
scale = min(1.0, MAX_COMPRESS_DIM / max(w, h))
img = img.resize((int(w * scale), int(h * scale)), Image.BILINEAR)
# Reduce quality quickly (no loop β faster)
buffer = BytesIO()
img.save(buffer, format="JPEG", quality=70, optimize=True)
buffer.seek(0)
return Image.open(buffer).convert("RGB")
def transform(img):
img = img.resize(TARGET_SIZE, Image.BILINEAR)
arr = np.asarray(img, dtype=np.float32) / 255.0
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
arr = (arr - mean) / std
arr = np.transpose(arr, (2, 0, 1))
return torch.from_numpy(arr).unsqueeze(0).to(device=device, dtype=dtype)
# π₯ FAST inference
def remove_background(img: Image.Image):
orig_size = img.size
tensor = transform(img)
with torch.inference_mode():
pred = model(tensor)
pred = pred[-1] if isinstance(pred, (list, tuple)) else pred
pred = pred.sigmoid()[0, 0].cpu()
mask = Image.fromarray((pred.mul(255).byte().numpy()))
mask = mask.resize(orig_size, Image.BILINEAR)
img = img.convert("RGBA")
img.putalpha(mask)
return img
# ---------------------------------------------------------
# FastAPI
# ---------------------------------------------------------
app = FastAPI()
@app.post("/remove-background")
async def remove_bg(file: UploadFile = File(None), image_url: str = Form(None)):
try:
if file:
raw = await file.read()
img = Image.open(BytesIO(raw)).convert("RGB")
# β
Step 1: compress if >5MB
img = compress_if_needed(img, raw)
elif image_url:
img = load_image_from_url(image_url)
else:
raise HTTPException(400, "Provide file or URL")
# β
Step 2: remove background
result = remove_background(img)
buf = BytesIO()
result.save(buf, format="PNG")
buf.seek(0)
return StreamingResponse(buf, media_type="image/png")
except Exception as e:
raise HTTPException(500, str(e))
# ---------------------------------------------------------
# Simple UI
# ---------------------------------------------------------
@app.get("/", response_class=HTMLResponse)
async def home():
return """
<html>
<head>
<title>Fast Background Remover</title>
<link rel='stylesheet'
href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css'>
</head>
<body class='bg-light'>
<div class='container py-4 text-center'>
<h2>Fast Background Remover</h2>
<div class='row mt-4'>
<div class='col-md-6'>
<h5>Input</h5>
<img id='inputImg' style='max-width:100%; border-radius:10px;'>
</div>
<div class='col-md-6'>
<h5>Output</h5>
<img id='outputImg' style='max-width:100%; border-radius:10px;'>
</div>
</div>
<hr>
<form id="uploadForm">
<input type='file' id='fileInput' class='form-control mb-3'>
<button class='btn btn-primary'>Upload</button>
</form>
<hr>
<form id='urlForm'>
<input id='urlInput' class='form-control mb-3'
placeholder='Enter image URL'>
<button class='btn btn-success'>Use URL</button>
</form>
</div>
<script>
const inputImg = document.getElementById("inputImg");
const outputImg = document.getElementById("outputImg");
document.getElementById("uploadForm").addEventListener("submit", async e => {
e.preventDefault();
const file = document.getElementById("fileInput").files[0];
if (!file) return alert("Select file");
inputImg.src = URL.createObjectURL(file);
const fd = new FormData();
fd.append("file", file);
const r = await fetch("/remove-background", { method:"POST", body:fd });
outputImg.src = URL.createObjectURL(await r.blob());
});
document.getElementById("urlForm").addEventListener("submit", async e => {
e.preventDefault();
const url = document.getElementById("urlInput").value;
inputImg.src = url;
const fd = new FormData();
fd.append("image_url", url);
const r = await fetch("/remove-background", { method:"POST", body:fd });
outputImg.src = URL.createObjectURL(await r.blob());
});
</script>
</body>
</html>
"""
# ---------------------------------------------------------
# Run
# ---------------------------------------------------------
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860) |