Noursine commited on
Commit
2797b6f
·
verified ·
1 Parent(s): 859abfc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -0
app.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ import cv2
4
+ import numpy as np
5
+ import torch
6
+ from fastapi import FastAPI, UploadFile, File
7
+ from fastapi.responses import JSONResponse
8
+ from detectron2.config import get_cfg
9
+ from detectron2.engine import DefaultPredictor
10
+ from detectron2 import model_zoo
11
+ from PIL import Image
12
+ import io
13
+
14
+ app = FastAPI(title="Roof Segmentation API")
15
+
16
+ # -----------------------------
17
+ # 1. Download model from Google Drive
18
+ # -----------------------------
19
+ MODEL_URL = "https://drive.google.com/uc?export=download&id=1bazIVYG0CYMubDLoMu5pgH6ArC1sayzg"
20
+ MODEL_PATH = "model_final.pth"
21
+
22
+ if not os.path.exists(MODEL_PATH):
23
+ print("⏬ Downloading model...")
24
+ r = requests.get(MODEL_URL, allow_redirects=True)
25
+ open(MODEL_PATH, 'wb').write(r.content)
26
+ print("✅ Model downloaded!")
27
+
28
+ # -----------------------------
29
+ # 2. Configure Detectron2
30
+ # -----------------------------
31
+ cfg = get_cfg()
32
+ cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"))
33
+ cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
34
+ cfg.MODEL.ROI_HEADS.NUM_CLASSES = 1
35
+ cfg.MODEL.WEIGHTS = MODEL_PATH
36
+ cfg.MODEL.DEVICE = "cpu" # Hugging Face Spaces often has no GPU
37
+
38
+ predictor = DefaultPredictor(cfg)
39
+
40
+ # -----------------------------
41
+ # 3. API Endpoint
42
+ # -----------------------------
43
+ @app.post("/predict")
44
+ async def predict(file: UploadFile = File(...)):
45
+ # Read image
46
+ contents = await file.read()
47
+ image = Image.open(io.BytesIO(contents)).convert("RGB")
48
+ image = np.array(image)[:, :, ::-1] # to BGR for OpenCV/Detectron2
49
+
50
+ # Run inference
51
+ outputs = predictor(image)
52
+ instances = outputs["instances"].to("cpu")
53
+
54
+ results = []
55
+ if instances.has("pred_masks"):
56
+ masks = instances.pred_masks.numpy()
57
+ boxes = instances.pred_boxes.tensor.numpy()
58
+ scores = instances.scores.numpy()
59
+
60
+ for i in range(len(masks)):
61
+ results.append({
62
+ "box": boxes[i].tolist(),
63
+ "score": float(scores[i])
64
+ })
65
+
66
+ return JSONResponse({"predictions": results})