Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,6 +7,7 @@ import numpy as np
|
|
| 7 |
from transformers import AutoModelForImageSegmentation
|
| 8 |
from io import BytesIO
|
| 9 |
from loadimg import load_img
|
|
|
|
| 10 |
|
| 11 |
# -------------------------
|
| 12 |
# Model Setup
|
|
@@ -14,19 +15,13 @@ from loadimg import load_img
|
|
| 14 |
MODEL_DIR = "models/BiRefNet"
|
| 15 |
os.makedirs(MODEL_DIR, exist_ok=True)
|
| 16 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 17 |
-
|
| 18 |
birefnet = None # will initialize on startup
|
| 19 |
|
| 20 |
# -------------------------
|
| 21 |
-
#
|
| 22 |
-
# -------------------------
|
| 23 |
-
app = FastAPI(title="Background Removal API")
|
| 24 |
-
|
| 25 |
-
# -------------------------
|
| 26 |
-
# Startup Event
|
| 27 |
# -------------------------
|
| 28 |
-
@
|
| 29 |
-
async def
|
| 30 |
global birefnet
|
| 31 |
if birefnet is None:
|
| 32 |
print("Loading BiRefNet model...")
|
|
@@ -34,10 +29,17 @@ async def load_model():
|
|
| 34 |
"ZhengPeng7/BiRefNet",
|
| 35 |
cache_dir=MODEL_DIR,
|
| 36 |
trust_remote_code=True,
|
| 37 |
-
revision="main"
|
| 38 |
)
|
| 39 |
birefnet.to(device).eval()
|
| 40 |
print("Model loaded successfully.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
# -------------------------
|
| 43 |
# Image Preprocessing
|
|
|
|
| 7 |
from transformers import AutoModelForImageSegmentation
|
| 8 |
from io import BytesIO
|
| 9 |
from loadimg import load_img
|
| 10 |
+
from contextlib import asynccontextmanager
|
| 11 |
|
| 12 |
# -------------------------
|
| 13 |
# Model Setup
|
|
|
|
| 15 |
MODEL_DIR = "models/BiRefNet"
|
| 16 |
os.makedirs(MODEL_DIR, exist_ok=True)
|
| 17 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
|
| 18 |
birefnet = None # will initialize on startup
|
| 19 |
|
| 20 |
# -------------------------
|
| 21 |
+
# Lifespan (Startup/Shutdown)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
# -------------------------
|
| 23 |
+
@asynccontextmanager
|
| 24 |
+
async def lifespan(app: FastAPI):
|
| 25 |
global birefnet
|
| 26 |
if birefnet is None:
|
| 27 |
print("Loading BiRefNet model...")
|
|
|
|
| 29 |
"ZhengPeng7/BiRefNet",
|
| 30 |
cache_dir=MODEL_DIR,
|
| 31 |
trust_remote_code=True,
|
| 32 |
+
revision="main"
|
| 33 |
)
|
| 34 |
birefnet.to(device).eval()
|
| 35 |
print("Model loaded successfully.")
|
| 36 |
+
yield
|
| 37 |
+
# Optional shutdown logic here (nothing needed for this model)
|
| 38 |
+
|
| 39 |
+
# -------------------------
|
| 40 |
+
# FastAPI App
|
| 41 |
+
# -------------------------
|
| 42 |
+
app = FastAPI(title="Background Removal API", lifespan=lifespan)
|
| 43 |
|
| 44 |
# -------------------------
|
| 45 |
# Image Preprocessing
|