Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, UploadFile, File
|
| 2 |
+
from fastapi.responses import JSONResponse
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import torch, torchvision.transforms as T
|
| 5 |
+
from transformers import MobileNetV2ForSemanticSegmentation
|
| 6 |
+
import io
|
| 7 |
+
|
| 8 |
+
# Load the model
|
| 9 |
+
model = MobileNetV2ForSemanticSegmentation.from_pretrained("seg_model")
|
| 10 |
+
model.eval()
|
| 11 |
+
|
| 12 |
+
preprocess = T.Compose([
|
| 13 |
+
T.Resize(513),
|
| 14 |
+
T.ToTensor(),
|
| 15 |
+
T.Normalize(mean=[0.485,0.456,0.406], std=[0.229,0.224,0.225])
|
| 16 |
+
])
|
| 17 |
+
|
| 18 |
+
app = FastAPI()
|
| 19 |
+
|
| 20 |
+
@app.get("/")
|
| 21 |
+
def root():
|
| 22 |
+
return {"status": "API up for segmentation"}
|
| 23 |
+
|
| 24 |
+
@app.post("/predict")
|
| 25 |
+
async def predict(file: UploadFile = File(...)):
|
| 26 |
+
img = Image.open(await file.read()).convert("RGB")
|
| 27 |
+
x = preprocess(img).unsqueeze(0)
|
| 28 |
+
with torch.no_grad():
|
| 29 |
+
outputs = model(x).logits
|
| 30 |
+
seg = outputs.argmax(1)[0].tolist()
|
| 31 |
+
return JSONResponse(content={"segmentation_mask": seg})
|