Noursine commited on
Commit
7040cbd
·
verified ·
1 Parent(s): 125e8a7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -3
app.py CHANGED
@@ -3,6 +3,7 @@ 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
@@ -33,12 +34,22 @@ cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rc
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(...)):
@@ -52,15 +63,24 @@ async def predict(file: UploadFile = File(...)):
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})
 
 
 
 
3
  import cv2
4
  import numpy as np
5
  import torch
6
+ import base64
7
  from fastapi import FastAPI, UploadFile, File
8
  from fastapi.responses import JSONResponse
9
  from detectron2.config import get_cfg
 
34
  cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
35
  cfg.MODEL.ROI_HEADS.NUM_CLASSES = 1
36
  cfg.MODEL.WEIGHTS = MODEL_PATH
37
+ cfg.MODEL.DEVICE = "cpu" # Hugging Face Spaces default (no GPU)
38
 
39
  predictor = DefaultPredictor(cfg)
40
 
41
  # -----------------------------
42
+ # 3. Helper: Encode mask to Base64
43
+ # -----------------------------
44
+ def encode_mask(mask: np.ndarray) -> str:
45
+ """Convert mask numpy array to base64 PNG string."""
46
+ mask_img = Image.fromarray(mask.astype(np.uint8))
47
+ buf = io.BytesIO()
48
+ mask_img.save(buf, format="PNG")
49
+ return base64.b64encode(buf.getvalue()).decode("utf-8")
50
+
51
+ # -----------------------------
52
+ # 4. API Endpoint
53
  # -----------------------------
54
  @app.post("/predict")
55
  async def predict(file: UploadFile = File(...)):
 
63
  instances = outputs["instances"].to("cpu")
64
 
65
  results = []
66
+ mask_b64 = None
67
+
68
  if instances.has("pred_masks"):
69
  masks = instances.pred_masks.numpy()
70
  boxes = instances.pred_boxes.tensor.numpy()
71
  scores = instances.scores.numpy()
72
 
73
+ # Combine masks into one
74
+ combined_mask = np.any(masks, axis=0).astype(np.uint8) * 255
75
+ mask_b64 = encode_mask(combined_mask)
76
+
77
  for i in range(len(masks)):
78
  results.append({
79
  "box": boxes[i].tolist(),
80
  "score": float(scores[i])
81
  })
82
 
83
+ return JSONResponse({
84
+ "predictions": results,
85
+ "mask": mask_b64 # base64 string (PNG)
86
+ })