modventures commited on
Commit
1126480
·
verified ·
1 Parent(s): e69b499

Dev Deploy: dc5f47d

Browse files
Files changed (3) hide show
  1. app.py +0 -141
  2. visualizer.gpu.toml +0 -5
  3. visualizer.hf.toml +2 -5
app.py CHANGED
@@ -33,8 +33,6 @@ from transformers import (
33
  Mask2FormerForUniversalSegmentation,
34
  OneFormerForUniversalSegmentation,
35
  OneFormerProcessor,
36
- SamModel,
37
- SamProcessor,
38
  SegformerForSemanticSegmentation,
39
  )
40
 
@@ -124,41 +122,6 @@ SEGMENTATION_LONGEST_EDGE = int(config_value(
124
  "segmentation_longest_edge",
125
  "2048",
126
  ))
127
- # SAM boundary refinement: re-segment the coarse OneFormer floor mask with a promptable
128
- # SAM model so the floor edge snaps to true object silhouettes (fixes the pale rim).
129
- # Checkpoint is swappable (SAM-HQ / SAM2 weights) without code changes.
130
- ENABLE_SAM_REFINE = str(config_value(
131
- "ENABLE_SAM_REFINE",
132
- "models",
133
- "enable_sam_refine",
134
- "1",
135
- )).lower() not in ("0", "false", "no", "off", "")
136
- SAM_REFINE_MODEL = str(config_value(
137
- "SAM_REFINE_MODEL",
138
- "models",
139
- "sam_refine_model",
140
- "facebook/sam-vit-base",
141
- ))
142
- SAM_REFINE_POS_POINTS = int(config_value(
143
- "SAM_REFINE_POS_POINTS",
144
- "models",
145
- "sam_refine_pos_points",
146
- "16",
147
- ))
148
- SAM_REFINE_NEG_POINTS = int(config_value(
149
- "SAM_REFINE_NEG_POINTS",
150
- "models",
151
- "sam_refine_neg_points",
152
- "12",
153
- ))
154
- # Minimum IoU between the SAM mask and the OneFormer floor for SAM's result to be trusted;
155
- # below this we keep the original mask (SAM latched onto the wrong region).
156
- SAM_REFINE_MIN_IOU = float(config_value(
157
- "SAM_REFINE_MIN_IOU",
158
- "models",
159
- "sam_refine_min_iou",
160
- "0.45",
161
- ))
162
  DEPTH_MODEL_NAME = str(config_value(
163
  "DEPTH_MODEL_NAME",
164
  "models",
@@ -356,8 +319,6 @@ depth_processor = None
356
  depth_model = None
357
  moge_model = None
358
  intrinsic_models = None
359
- sam_processor = None
360
- sam_model = None
361
 
362
 
363
  def hf_offline() -> bool:
@@ -2082,103 +2043,6 @@ def active_model_metadata(geometry: dict | None, depth: np.ndarray | None, shade
2082
  }
2083
 
2084
 
2085
- def _load_sam_model():
2086
- global sam_processor, sam_model
2087
- print(f"Loading SAM refiner: {SAM_REFINE_MODEL} ...", flush=True)
2088
- sam_processor = SamProcessor.from_pretrained(SAM_REFINE_MODEL, local_files_only=hf_offline())
2089
- sam_model = SamModel.from_pretrained(SAM_REFINE_MODEL, local_files_only=hf_offline()).to(device)
2090
- sam_model.eval()
2091
- print("SAM refiner loaded.", flush=True)
2092
-
2093
-
2094
- def _sample_mask_points(mask: np.ndarray, count: int) -> list:
2095
- """Evenly sample up to `count` (x, y) points from the set region of a mask."""
2096
- ys, xs = np.where(mask > 0)
2097
- if len(xs) == 0 or count <= 0:
2098
- return []
2099
- if len(xs) <= count:
2100
- idx = np.arange(len(xs))
2101
- else:
2102
- idx = np.linspace(0, len(xs) - 1, count).astype(np.int64)
2103
- return [[int(xs[i]), int(ys[i])] for i in idx]
2104
-
2105
-
2106
- def refine_floor_with_sam(
2107
- floor_mask: np.ndarray,
2108
- img_np: np.ndarray,
2109
- seg_map: np.ndarray,
2110
- ) -> tuple[np.ndarray, dict]:
2111
- """Re-segment the coarse OneFormer floor mask with SAM so its boundary snaps to true
2112
- object silhouettes (the pale-rim fix). SAM is prompted with points sampled from the
2113
- floor interior (positive) and from occluders/walls (negative). Falls back to the input
2114
- mask on any error, or if SAM's mask disagrees with the floor too much (wrong region)."""
2115
- if not ENABLE_SAM_REFINE or not floor_mask.any():
2116
- return floor_mask, {"samRefineEnabled": False}
2117
- try:
2118
- if sam_model is None:
2119
- _load_sam_model()
2120
- h, w = floor_mask.shape[:2]
2121
- side = max(3, min(h, w) // 100) | 1
2122
- interior = cv2.erode(floor_mask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (side, side)))
2123
- if not interior.any():
2124
- interior = floor_mask
2125
- reject = np.isin(seg_map, class_ids(OCCLUDER_CLASSES | REJECT_SURFACE_CLASSES)).astype(np.uint8)
2126
- pos = _sample_mask_points(interior, SAM_REFINE_POS_POINTS)
2127
- neg = _sample_mask_points(reject, SAM_REFINE_NEG_POINTS)
2128
- if not pos:
2129
- return floor_mask, {"samRefineEnabled": True, "samRefineApplied": False, "samRefineReason": "no-points"}
2130
- points = pos + neg
2131
- labels = [1] * len(pos) + [0] * len(neg)
2132
-
2133
- inputs = sam_processor(
2134
- Image.fromarray(img_np),
2135
- input_points=[[points]],
2136
- input_labels=[[labels]],
2137
- return_tensors="pt",
2138
- ).to(device)
2139
- with torch.no_grad():
2140
- outputs = sam_model(**inputs, multimask_output=True)
2141
- masks = sam_processor.image_processor.post_process_masks(
2142
- outputs.pred_masks.cpu(),
2143
- inputs["original_sizes"].cpu(),
2144
- inputs["reshaped_input_sizes"].cpu(),
2145
- )[0][0].numpy() # (num_masks, H, W)
2146
-
2147
- floor_bool = floor_mask > 0
2148
- best_mask, best_iou = None, 0.0
2149
- for cand in masks:
2150
- cand_bool = cand.astype(bool)
2151
- union = np.logical_or(cand_bool, floor_bool).sum()
2152
- iou = float(np.logical_and(cand_bool, floor_bool).sum()) / float(union) if union else 0.0
2153
- if iou > best_iou:
2154
- best_iou, best_mask = iou, cand_bool
2155
-
2156
- if best_mask is None or best_iou < SAM_REFINE_MIN_IOU:
2157
- return floor_mask, {
2158
- "samRefineEnabled": True,
2159
- "samRefineApplied": False,
2160
- "samRefineIou": round(best_iou, 3),
2161
- "samRefineModel": SAM_REFINE_MODEL,
2162
- }
2163
-
2164
- refined = best_mask.astype(np.uint8)
2165
- refined[reject > 0] = 0
2166
- refined = clean_floor_mask(refined)
2167
- if not refined.any():
2168
- return floor_mask, {"samRefineEnabled": True, "samRefineApplied": False, "samRefineIou": round(best_iou, 3)}
2169
- return refined, {
2170
- "samRefineEnabled": True,
2171
- "samRefineApplied": True,
2172
- "samRefineIou": round(best_iou, 3),
2173
- "samRefineModel": SAM_REFINE_MODEL,
2174
- "samRefinePosPoints": len(pos),
2175
- "samRefineNegPoints": len(neg),
2176
- }
2177
- except Exception as exc:
2178
- print(f"SAM refine failed ({exc}); keeping original floor mask.", flush=True)
2179
- return floor_mask, {"samRefineEnabled": True, "samRefineApplied": False, "samRefineError": str(exc)[:200]}
2180
-
2181
-
2182
  def build_segmentation_bundle(contents: bytes):
2183
  t_start = time.perf_counter()
2184
 
@@ -2210,10 +2074,6 @@ def build_segmentation_bundle(contents: bytes):
2210
  floor_mask = clean_floor_mask(floor_mask)
2211
  print(f"[TIMING] Floor masking/cleanup took {time.perf_counter() - t0:.3f} seconds", flush=True)
2212
 
2213
- t0 = time.perf_counter()
2214
- floor_mask, sam_refine_metadata = refine_floor_with_sam(floor_mask, img_np, seg_map)
2215
- print(f"[TIMING] SAM floor refinement took {time.perf_counter() - t0:.3f} seconds", flush=True)
2216
-
2217
  t0 = time.perf_counter()
2218
  geometry = estimate_scene_geometry(img, img_np, w, h)
2219
  depth = geometry.get("depth")
@@ -2295,7 +2155,6 @@ def build_segmentation_bundle(contents: bytes):
2295
  "segmenter": segmenter_metadata_name(),
2296
  "segmentationModel": models["segmentation"]["name"],
2297
  "segmentationShortestEdge": SEGMENTATION_SHORTEST_EDGE,
2298
- **sam_refine_metadata,
2299
  "floorPixels": int(floor_mask.sum()),
2300
  "surfacePixels": int(surface_mask.sum()),
2301
  **edge_metadata,
 
33
  Mask2FormerForUniversalSegmentation,
34
  OneFormerForUniversalSegmentation,
35
  OneFormerProcessor,
 
 
36
  SegformerForSemanticSegmentation,
37
  )
38
 
 
122
  "segmentation_longest_edge",
123
  "2048",
124
  ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  DEPTH_MODEL_NAME = str(config_value(
126
  "DEPTH_MODEL_NAME",
127
  "models",
 
319
  depth_model = None
320
  moge_model = None
321
  intrinsic_models = None
 
 
322
 
323
 
324
  def hf_offline() -> bool:
 
2043
  }
2044
 
2045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2046
  def build_segmentation_bundle(contents: bytes):
2047
  t_start = time.perf_counter()
2048
 
 
2074
  floor_mask = clean_floor_mask(floor_mask)
2075
  print(f"[TIMING] Floor masking/cleanup took {time.perf_counter() - t0:.3f} seconds", flush=True)
2076
 
 
 
 
 
2077
  t0 = time.perf_counter()
2078
  geometry = estimate_scene_geometry(img, img_np, w, h)
2079
  depth = geometry.get("depth")
 
2155
  "segmenter": segmenter_metadata_name(),
2156
  "segmentationModel": models["segmentation"]["name"],
2157
  "segmentationShortestEdge": SEGMENTATION_SHORTEST_EDGE,
 
2158
  "floorPixels": int(floor_mask.sum()),
2159
  "surfacePixels": int(surface_mask.sum()),
2160
  **edge_metadata,
visualizer.gpu.toml CHANGED
@@ -11,11 +11,6 @@ mask2former_model_name = "facebook/mask2former-swin-small-ade-semantic"
11
  segformer_model_name = "nvidia/segformer-b2-finetuned-ade-512-512"
12
  segmentation_shortest_edge = 1024
13
  segmentation_longest_edge = 2048
14
- enable_sam_refine = 1
15
- sam_refine_model = "facebook/sam-vit-base"
16
- sam_refine_pos_points = 16
17
- sam_refine_neg_points = 12
18
- sam_refine_min_iou = 0.45
19
  depth_model_name = "depth-anything/Depth-Anything-V2-Metric-Indoor-Large-hf"
20
  intrinsic_model_version = "v2"
21
 
 
11
  segformer_model_name = "nvidia/segformer-b2-finetuned-ade-512-512"
12
  segmentation_shortest_edge = 1024
13
  segmentation_longest_edge = 2048
 
 
 
 
 
14
  depth_model_name = "depth-anything/Depth-Anything-V2-Metric-Indoor-Large-hf"
15
  intrinsic_model_version = "v2"
16
 
visualizer.hf.toml CHANGED
@@ -11,11 +11,6 @@ mask2former_model_name = "facebook/mask2former-swin-small-ade-semantic"
11
  segformer_model_name = "nvidia/segformer-b2-finetuned-ade-512-512"
12
  segmentation_shortest_edge = 1024
13
  segmentation_longest_edge = 2048
14
- enable_sam_refine = 1
15
- sam_refine_model = "facebook/sam-vit-base"
16
- sam_refine_pos_points = 16
17
- sam_refine_neg_points = 12
18
- sam_refine_min_iou = 0.45
19
  depth_model_name = "depth-anything/Depth-Anything-V2-Metric-Indoor-Large-hf"
20
  intrinsic_model_version = "v2"
21
 
@@ -48,3 +43,5 @@ uv_min_coverage = 0.995
48
  uv_max_bad_neighbor_ratio = 0.035
49
  uv_max_jump_ratio = 8.0
50
  uv_absolute_jump_meters = 0.35
 
 
 
11
  segformer_model_name = "nvidia/segformer-b2-finetuned-ade-512-512"
12
  segmentation_shortest_edge = 1024
13
  segmentation_longest_edge = 2048
 
 
 
 
 
14
  depth_model_name = "depth-anything/Depth-Anything-V2-Metric-Indoor-Large-hf"
15
  intrinsic_model_version = "v2"
16
 
 
43
  uv_max_bad_neighbor_ratio = 0.035
44
  uv_max_jump_ratio = 8.0
45
  uv_absolute_jump_meters = 0.35
46
+
47
+ # redeploy trigger: SAM reverted, restore 1024 baseline