Spaces:
Build error
Build error
Delete samv4.py
Browse files
samv4.py
DELETED
|
@@ -1,171 +0,0 @@
|
|
| 1 |
-
# ===============================
|
| 2 |
-
# rooftop_obstacle_detection_optimized.py
|
| 3 |
-
# ===============================
|
| 4 |
-
|
| 5 |
-
import io
|
| 6 |
-
import os
|
| 7 |
-
import base64
|
| 8 |
-
import cv2
|
| 9 |
-
import numpy as np
|
| 10 |
-
from fastapi import FastAPI, UploadFile, File
|
| 11 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 12 |
-
from fastapi.responses import JSONResponse
|
| 13 |
-
from inference_sdk import InferenceHTTPClient
|
| 14 |
-
from PIL import Image, ImageDraw
|
| 15 |
-
|
| 16 |
-
# -------------------------------
|
| 17 |
-
# Model setup (Roboflow)
|
| 18 |
-
# -------------------------------
|
| 19 |
-
MODEL_API_KEY = os.environ.get("API_KEY")
|
| 20 |
-
MODEL_API_URL = "https://serverless.roboflow.com"
|
| 21 |
-
MODEL_ID = "gable_rectangular_rooftop-p9ose/2"
|
| 22 |
-
|
| 23 |
-
if not MODEL_API_KEY:
|
| 24 |
-
raise ValueError("MODEL_API_KEY not set")
|
| 25 |
-
|
| 26 |
-
CLIENT = InferenceHTTPClient(api_key=MODEL_API_KEY, api_url=MODEL_API_URL)
|
| 27 |
-
|
| 28 |
-
# -------------------------------
|
| 29 |
-
# SAM2 imports
|
| 30 |
-
# -------------------------------
|
| 31 |
-
from sam2.build_sam import build_sam2
|
| 32 |
-
from sam2.automatic_mask_generator import SAM2AutomaticMaskGenerator
|
| 33 |
-
from hydra import initialize
|
| 34 |
-
from hydra.core.global_hydra import GlobalHydra
|
| 35 |
-
|
| 36 |
-
# -------------------------------
|
| 37 |
-
# Load SAM2 model (CPU)
|
| 38 |
-
# -------------------------------
|
| 39 |
-
if GlobalHydra.instance().is_initialized():
|
| 40 |
-
GlobalHydra.instance().clear()
|
| 41 |
-
|
| 42 |
-
with initialize(version_base=None, config_path="segment-anything-2/sam2/configs"):
|
| 43 |
-
sam2_model = build_sam2(
|
| 44 |
-
"sam2.1/sam2.1_hiera_l",
|
| 45 |
-
"sam2.1_hiera_large.pt",
|
| 46 |
-
device="cpu"
|
| 47 |
-
)
|
| 48 |
-
|
| 49 |
-
mask_generator = SAM2AutomaticMaskGenerator(
|
| 50 |
-
sam2_model,
|
| 51 |
-
points_per_side=16,
|
| 52 |
-
pred_iou_thresh=0.5, # lower to detect tiny obstacles
|
| 53 |
-
stability_score_thresh=0.5
|
| 54 |
-
)
|
| 55 |
-
|
| 56 |
-
# -------------------------------
|
| 57 |
-
# FastAPI app
|
| 58 |
-
# -------------------------------
|
| 59 |
-
app = FastAPI(
|
| 60 |
-
title="Rooftop Obstacle Detection",
|
| 61 |
-
description="Detect rooftop obstacles using Roboflow + SAM2",
|
| 62 |
-
version="1.0"
|
| 63 |
-
)
|
| 64 |
-
|
| 65 |
-
app.add_middleware(
|
| 66 |
-
CORSMiddleware,
|
| 67 |
-
allow_origins=["*"],
|
| 68 |
-
allow_credentials=True,
|
| 69 |
-
allow_methods=["*"],
|
| 70 |
-
allow_headers=["*"]
|
| 71 |
-
)
|
| 72 |
-
|
| 73 |
-
@app.get("/")
|
| 74 |
-
def root():
|
| 75 |
-
return {
|
| 76 |
-
"status": "running",
|
| 77 |
-
"message": "Rooftop Obstacle Detection API",
|
| 78 |
-
"note": "POST an image to /process/"
|
| 79 |
-
}
|
| 80 |
-
|
| 81 |
-
# -------------------------------
|
| 82 |
-
# Helper functions
|
| 83 |
-
# -------------------------------
|
| 84 |
-
|
| 85 |
-
def resize_image(image: Image.Image, max_size=1024) -> Image.Image:
|
| 86 |
-
"""
|
| 87 |
-
Resize image to max dimension while keeping aspect ratio.
|
| 88 |
-
"""
|
| 89 |
-
w, h = image.size
|
| 90 |
-
if max(w, h) <= max_size:
|
| 91 |
-
return image
|
| 92 |
-
if w > h:
|
| 93 |
-
h = int(h * max_size / w)
|
| 94 |
-
w = max_size
|
| 95 |
-
else:
|
| 96 |
-
w = int(w * max_size / h)
|
| 97 |
-
h = max_size
|
| 98 |
-
return image.resize((w, h), Image.ANTIALIAS)
|
| 99 |
-
|
| 100 |
-
def generate_rooftop_mask(image: Image.Image) -> np.ndarray:
|
| 101 |
-
img_np = np.array(image)
|
| 102 |
-
result = CLIENT.infer(img_np, model_id=MODEL_ID)
|
| 103 |
-
|
| 104 |
-
mask = Image.new("L", image.size, 0)
|
| 105 |
-
draw = ImageDraw.Draw(mask)
|
| 106 |
-
|
| 107 |
-
for pred in result.get("predictions", []):
|
| 108 |
-
points = [(p["x"], p["y"]) for p in pred["points"]]
|
| 109 |
-
draw.polygon(points, fill=255)
|
| 110 |
-
|
| 111 |
-
return np.array(mask)
|
| 112 |
-
|
| 113 |
-
def generate_obstacle_overlay(image: Image.Image, rooftop_mask: np.ndarray):
|
| 114 |
-
img_np = np.array(image)
|
| 115 |
-
overlay = img_np.copy()
|
| 116 |
-
|
| 117 |
-
sam_masks = mask_generator.generate(img_np)
|
| 118 |
-
obstacle_polygons = []
|
| 119 |
-
|
| 120 |
-
for m in sam_masks:
|
| 121 |
-
seg = np.logical_and(m["segmentation"], rooftop_mask > 0)
|
| 122 |
-
if seg.sum() == 0:
|
| 123 |
-
continue
|
| 124 |
-
|
| 125 |
-
seg_uint8 = (seg * 255).astype(np.uint8)
|
| 126 |
-
contours, _ = cv2.findContours(seg_uint8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 127 |
-
|
| 128 |
-
for cnt in contours:
|
| 129 |
-
if cv2.contourArea(cnt) < 20: # include tiny obstacles
|
| 130 |
-
continue
|
| 131 |
-
|
| 132 |
-
epsilon = 0.01 * cv2.arcLength(cnt, True)
|
| 133 |
-
poly = cv2.approxPolyDP(cnt, epsilon, True)
|
| 134 |
-
|
| 135 |
-
mask_layer = overlay.copy()
|
| 136 |
-
cv2.fillPoly(mask_layer, [poly], (0, 255, 0))
|
| 137 |
-
overlay = cv2.addWeighted(mask_layer, 0.3, overlay, 0.7, 0)
|
| 138 |
-
|
| 139 |
-
cv2.polylines(overlay, [poly], isClosed=True, color=(0, 120, 0), thickness=1)
|
| 140 |
-
obstacle_polygons.append(poly.reshape(-1, 2).tolist())
|
| 141 |
-
|
| 142 |
-
return overlay, obstacle_polygons
|
| 143 |
-
|
| 144 |
-
def encode_overlay_image(overlay: np.ndarray) -> str:
|
| 145 |
-
"""
|
| 146 |
-
Convert NumPy overlay to compressed JPEG Base64 for safe transmission.
|
| 147 |
-
"""
|
| 148 |
-
buf = io.BytesIO()
|
| 149 |
-
Image.fromarray(overlay).save(buf, format="JPEG", quality=85)
|
| 150 |
-
return base64.b64encode(buf.getvalue()).decode()
|
| 151 |
-
|
| 152 |
-
# -------------------------------
|
| 153 |
-
# API endpoint
|
| 154 |
-
# -------------------------------
|
| 155 |
-
|
| 156 |
-
@app.post("/process/")
|
| 157 |
-
async def process_image_endpoint(file: UploadFile = File(...)):
|
| 158 |
-
image_bytes = await file.read()
|
| 159 |
-
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 160 |
-
image = resize_image(image, max_size=1024) # resize to reduce JSON size
|
| 161 |
-
|
| 162 |
-
rooftop_mask = generate_rooftop_mask(image)
|
| 163 |
-
overlay, polygons = generate_obstacle_overlay(image, rooftop_mask)
|
| 164 |
-
|
| 165 |
-
overlay_b64 = encode_overlay_image(overlay)
|
| 166 |
-
|
| 167 |
-
return JSONResponse({
|
| 168 |
-
"num_obstacles": len(polygons),
|
| 169 |
-
"overlay_base64": overlay_b64,
|
| 170 |
-
"obstacle_polygons": polygons
|
| 171 |
-
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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