Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files31 unmodified lines3233343536353637383940416 unmodified lines48495051525354555657585956606162636424 unmodified lines89909192878889909192939495969798991001011021031041051061071081091101119697112113114115116117118119120121122123124125102 unmodified lines22822923020923123223314 unmodified lines2482492502302512522532548 unmodified lines2632642652662672682692702712722732742752762772522782792802811 unmodified line2832842852862872882892902912922932942952962972982993003012613023033043053063073083093103113123132633143153163173183193203217 unmodified lines32933033127733233333428133533633733853 unmodified lines3923933943413953963973983993464004014026 unmodified lines40941041135941241341416 unmodified lines43143243338243443543612 unmodified lines44945045140145245345431 unmodified lines48648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352443944052552652752852975 unmodified lines605606607522523608609610611124 unmodified lines73673773865465573974074174274371 unmodified lines81581681781881982082182282373882482582682714 unmodified lines8428438448458468478488492 unmodified lines8528538547677688558568577708588598607738618628638647758658668678687 unmodified lines87687787878987988079179288188288388488588679479588788888989089189279889389489580289689789889990090137 unmodified lines93994094184694294394420 unmodified lines965966967873968969970139 unmodified lines111011111112101911131114111545 unmodified lines116111621163107111641165116650 unmodified lines121712181219112812201221122211311132113312231224122512261227122813 unmodified lines1242124312441153124512461247124873 unmodified lines1322132313241233132513261327132831 unmodified linesMASK2FORMER_ID = "facebook/mask2former-swin-large-ade-semantic"SEGFORMER_FALLBACK_ID = "nvidia/segformer-b2-finetuned-ade-512-512"DEPTH_METRIC_ID = "depth-anything/Depth-Anything-V2-Metric-Indoor-Base-hf"GDINO_MODEL_ID = "IDEA-Research/grounding-dino-tiny"SAM2_MODEL_ID = "facebook/sam2.1-hiera-tiny"GDINO_PRIMARY_ID = "IDEA-Research/grounding-dino-base"GDINO_FALLBACK_ID = "IDEA-Research/grounding-dino-tiny"SAM2_PRIMARY_ID = "facebook/sam2.1-hiera-base-plus"SAM2_FALLBACK_ID = "facebook/sam2.1-hiera-tiny"SAM1_MODEL_ID = "facebook/sam-vit-base"
SQM_TO_SQFT = 10.76391046 unmodified linesdepth_model = Nonegdino_processor = Nonegdino_model = Nonegdino_active_id = GDINO_PRIMARY_IDsam_processor = Nonesam_model = Nonesam_active_id = SAM2_PRIMARY_ID
def get_models(): global seg_processor, seg_model, seg_is_mask2former global depth_processor, depth_model global gdino_processor, gdino_model, sam_processor, sam_model global gdino_processor, gdino_model, gdino_active_id global sam_processor, sam_model, sam_active_id
device = "cuda" if torch.cuda.is_available() else "cpu"
24 unmodified lines )
if gdino_model is None: try: gdino_processor = AutoProcessor.from_pretrained(GDINO_MODEL_ID) gdino_model = ( AutoModelForZeroShotObjectDetection.from_pretrained(GDINO_MODEL_ID) .to(device) .eval() ) gdino_processor = AutoProcessor.from_pretrained(GDINO_PRIMARY_ID) gdino_model = ( AutoModelForZeroShotObjectDetection.from_pretrained(GDINO_PRIMARY_ID) .to(device) .eval() ) gdino_active_id = GDINO_PRIMARY_ID except Exception: gdino_processor = AutoProcessor.from_pretrained(GDINO_FALLBACK_ID) gdino_model = ( AutoModelForZeroShotObjectDetection.from_pretrained(GDINO_FALLBACK_ID) .to(device) .eval() ) gdino_active_id = GDINO_FALLBACK_ID
if sam_model is None: if HAS_SAM2: try: sam_processor = Sam2Processor.from_pretrained(SAM2_MODEL_ID) sam_model = Sam2Model.from_pretrained(SAM2_MODEL_ID).to(device).eval() sam_processor = Sam2Processor.from_pretrained(SAM2_PRIMARY_ID) sam_model = Sam2Model.from_pretrained(SAM2_PRIMARY_ID).to(device).eval() sam_active_id = SAM2_PRIMARY_ID except Exception: sam_processor = Sam2Processor.from_pretrained(SAM2_FALLBACK_ID) sam_model = Sam2Model.from_pretrained(SAM2_FALLBACK_ID).to(device).eval() sam_active_id = SAM2_FALLBACK_ID else: sam_processor = SamProcessor.from_pretrained(SAM1_MODEL_ID) sam_model = SamModel.from_pretrained(SAM1_MODEL_ID).to(device).eval() sam_active_id = SAM1_MODEL_ID
return ( seg_processor,102 unmodified lines
is_dup = False for k in kept: # Match same label or overlapping substring (e.g., "door" vs "wardrobe door") same_cls = ( cand["label"] == k["label"] or cand["label"] in k["label"]14 unmodified lines return kept
@spaces.GPU(duration=90)@spaces.GPU(duration=120)def run_models(img_pil, prompt_terms): ( s_proc,8 unmodified lines ) = get_models() device = next(s_mod.parameters()).device w, h = img_pil.size img_flip = img_pil.transpose(Image.FLIP_LEFT_RIGHT)
s_inputs = s_proc(images=img_pil, return_tensors="pt").to(device) s_inputs_flip = s_proc(images=img_flip, return_tensors="pt").to(device) d_inputs = d_proc(images=img_pil, return_tensors="pt").to(device) d_inputs_flip = d_proc(images=img_flip, return_tensors="pt").to(device)
with torch.inference_mode(): # Flip-TTA for semantic segmentation s_out = s_mod(**s_inputs) s_out_flip = s_mod(**s_inputs_flip) if is_m2f: pred_map = ( pred_orig = ( s_proc.post_process_semantic_segmentation( s_out, target_sizes=[(h, w)] )[0]1 unmodified line .cpu() .numpy() ) pred_flip = ( s_proc.post_process_semantic_segmentation( s_out_flip, target_sizes=[(h, w)] )[0] .detach() .cpu() .numpy() ) pred_flip = np.fliplr(pred_flip) # Keep original where both agree; smooth disagreement via median filter pred_map = pred_orig.copy() disagree = pred_orig != pred_flip if np.any(disagree): med = cv2.medianBlur(pred_orig.astype(np.uint8), 5) pred_map[disagree] = med[disagree] else: pred_map = s_out.logits.argmax(dim=1).squeeze(0).detach().cpu().numpy() logits_orig = s_out.logits logits_flip = torch.flip(s_out_flip.logits, dims=[-1]) pred_map = ( ((logits_orig + logits_flip) * 0.5) .argmax(dim=1) .squeeze(0) .detach() .cpu() .numpy() )
# Flip-TTA for metric depth (averages out monocular left/right bias) d_pred = d_mod(**d_inputs).predicted_depth.squeeze(0).detach().cpu().numpy() d_orig = d_mod(**d_inputs).predicted_depth.squeeze(0).detach().cpu().numpy() d_flip = np.fliplr( d_mod(**d_inputs_flip).predicted_depth.squeeze(0).detach().cpu().numpy() ) d_pred = 0.5 * (d_orig + d_flip)
id2label = getattr(s_mod.config, "id2label", {}) or {}
7 unmodified lines with torch.inference_mode(): g_outputs = g_mod(**g_inputs)
# Raised threshold from 0.30 -> 0.42 to suppress false-positive windows on TV/fluted panels g_res = g_proc.post_process_grounded_object_detection( g_outputs, g_inputs.input_ids, threshold=0.42, threshold=0.40, text_threshold=0.30, target_sizes=[(h, w)], )[0]53 unmodified lines id2label, np.asarray(d_pred, dtype=np.float32), detected_objects, "Mask2Former-Swin-Large" if is_m2f else "SegFormer-B2", "Mask2Former-Swin-Large (TTA)" if is_m2f else "SegFormer-B2 (TTA)", )
def backproject_depth_to_3d(depth_m, focal_px): """Back-project metric depth (metres) to 3D camera coordinates (X, Y, Z) in metres.""" h, w = depth_m.shape cx, cy = w * 0.5, h * 0.5 u = np.arange(w, dtype=np.float32)[None, :]6 unmodified lines
def compute_surface_normals(x, y, z): """Estimate smooth per-pixel 3D unit surface normals from 3D coordinates.""" z_s = cv2.GaussianBlur(z, (9, 9), 0) x_s = cv2.GaussianBlur(x, (9, 9), 0) y_s = cv2.GaussianBlur(y, (9, 9), 0)16 unmodified lines
def calibrate_metric_scale(masks, door_mask, floor_zone_mask, y_3d, cal_mode, ref_dim_ft): """Align metric depth with user reference using only uncropped wall columns and tight clamp [0.75, 1.25].""" ref_m = float(ref_dim_ft) * FT_TO_M h, w = masks["wall"].shape
12 unmodified lines f"Metric Depth + Door Ref ({ref_dim_ft:.1f} ft, scale {scale:.2f}x)", )
# Only use wall columns that touch BOTH the ceiling mask at the top and floor/furniture at the bottom ceil_dil = cv2.dilate(masks["ceiling"], np.ones((15, 15), np.uint8)) floor_dil = cv2.dilate(floor_zone_mask, np.ones((19, 19), np.uint8))
31 unmodified lines return 1.0, "Pure Metric Depth (unscaled)"
def merge_coplanar_planes(planes, z_3d, normal_angle_tol=15.0, depth_tol_m=0.35): """Merge RANSAC wall planes that share nearly identical 3D normals and depth.""" if len(planes) <= 1: return planes
merged = [] used = [False] * len(planes) for i in range(len(planes)): if used[i]: continue base = planes[i].copy() base_mask = base["mask"].copy() n_i = np.array(base["normal"], dtype=np.float32)
for j in range(i + 1, len(planes)): if used[j]: continue n_j = np.array(planes[j]["normal"], dtype=np.float32) cos_sim = float(np.clip(np.dot(n_i, n_j), -1.0, 1.0)) ang_diff = float(np.degrees(np.arccos(abs(cos_sim)))) depth_diff = abs(base["median_depth_m"] - planes[j]["median_depth_m"]) if ang_diff <= normal_angle_tol and depth_diff <= depth_tol_m: base_mask = cv2.bitwise_or(base_mask, planes[j]["mask"]) used[j] = True
py, px = np.where(base_mask > 0) base["mask"] = base_mask base["area_px"] = int(len(py)) base["centroid"] = (int(np.mean(px)), int(np.mean(py))) base["median_depth_m"] = float(np.median(z_3d[py, px])) merged.append(base)
merged.sort(key=lambda p: p["centroid"][0]) return merged
def fit_3d_wall_planes_ransac(wall_mask, x_3d, y_3d, z_3d, min_area_ratio=0.02): """Segment distinct flat 3D wall planes via iterative RANSAC on 3D points."""def fit_3d_wall_planes_ransac(wall_mask, x_3d, y_3d, z_3d, min_area_ratio=0.03): """Segment distinct flat 3D wall planes via iterative RANSAC and merge coplanar fragments.""" h, w = wall_mask.shape min_px = int(h * w * min_area_ratio) remaining = (wall_mask > 0).copy()75 unmodified lines ) remaining[plane_mask > 0] = False
planes.sort(key=lambda p: p["centroid"][0]) return planes return merge_coplanar_planes(planes, z_3d)
def compute_3d_surface_area_sqft(mask, z_3d, focal_px, cos_theta=None):124 unmodified lines
def export_takeoff_files(payload, rows): tmp_dir = tempfile.gettempdir() json_path = os.path.join(tmp_dir, "smart_area_v20_report.json") csv_path = os.path.join(tmp_dir, "smart_area_v20_takeoff.csv") json_path = os.path.join(tmp_dir, "smart_area_v21_report.json") csv_path = os.path.join(tmp_dir, "smart_area_v21_takeoff.csv")
with open(json_path, "w", encoding="utf-8") as jf: json.dump(payload, jf, indent=2)71 unmodified lines } door_mask = np.zeros((h, w), np.uint8) sem_window_mask = np.zeros((h, w), np.uint8) sem_reflective_mask = np.zeros((h, w), np.uint8) sem_opening_mask = np.zeros((h, w), np.uint8) wall_openings_source_mask = np.zeros((h, w), np.uint8) floor_furniture_mask = np.zeros((h, w), np.uint8)
structural_opening_keywords = ("window", "pane", "door", "wardrobe", "closet") # Rugs and carpets belong to the floor footprint, not clutter reflective_keywords = ("window", "pane", "mirror", "wardrobe", "closet") floor_surface_keywords = ("floor", "rug", "carpet") floor_furn_keywords = ( "sofa", "couch", "bed", "table", "chair",14 unmodified lines door_mask = cv2.bitwise_or(door_mask, m) if "window" in lbl or "pane" in lbl: sem_window_mask = cv2.bitwise_or(sem_window_mask, m) if any(rk in lbl for rk in reflective_keywords): sem_reflective_mask = cv2.bitwise_or(sem_reflective_mask, m) if any(sok in lbl for sok in structural_opening_keywords): sem_opening_mask = cv2.bitwise_or(sem_opening_mask, m) wall_openings_source_mask = cv2.bitwise_or(2 unmodified lines if any(fk in lbl for fk in floor_furn_keywords): floor_furniture_mask = cv2.bitwise_or(floor_furniture_mask, m)
# Build verified window mask (semantic + high-confidence SAM windows) window_mask = sem_window_mask.copy() # Build verified reflective/glass mask (windows, mirrors, mirrored wardrobes) reflective_mask = sem_reflective_mask.copy() for obj in detected_objs: if "window" in obj["label"]: if any(rk in obj["label"] for rk in reflective_keywords): om = obj["mask"] om_px = max(1, int(np.count_nonzero(om))) sem_overlap = int(np.count_nonzero(cv2.bitwise_and(om, sem_window_mask))) / float(om_px) sem_overlap = int( np.count_nonzero(cv2.bitwise_and(om, sem_reflective_mask)) ) / float(om_px) if sem_overlap > 0.10 or obj["score"] >= 0.55: window_mask = cv2.bitwise_or(window_mask, om) reflective_mask = cv2.bitwise_or(reflective_mask, om)
sam_ignored_mask = np.zeros((h, w), np.uint8) sam_target_mask = np.zeros((h, w), np.uint8)7 unmodified lines if omask_px == 0: continue
# Ignore non-window/non-curtain detections sitting predominantly inside window glass # Suppress outdoor objects through windows AND reflections inside mirrors/wardrobes if ( np.count_nonzero(window_mask) > 0 and not any(wk in lbl for wk in ("window", "pane", "curtain", "drape")) np.count_nonzero(reflective_mask) > 0 and not any( wk in lbl for wk in ("window", "pane", "curtain", "drape", "mirror", "wardrobe", "closet") ) ): inside_win = int(np.count_nonzero(cv2.bitwise_and(omask, window_mask))) if inside_win / float(omask_px) > 0.60: inside_ref = int( np.count_nonzero(cv2.bitwise_and(omask, reflective_mask)) ) if inside_ref / float(omask_px) > 0.55: continue
# Semantic verification for SAM window/door openings to block ghost windows on TV panels is_opening_lbl = any(sok in lbl for sok in structural_opening_keywords) verified_opening = True if is_opening_lbl: sem_ov = int(np.count_nonzero(cv2.bitwise_and(omask, sem_opening_mask))) / float(omask_px) sem_ov = int( np.count_nonzero(cv2.bitwise_and(omask, sem_opening_mask)) ) / float(omask_px) verified_opening = (sem_ov > 0.10) or (obj["score"] >= 0.55) if not verified_opening: continue37 unmodified lines masks["floor"], cv2.bitwise_not(sam_ignored_mask) )
# Resize metric depth (metres) and back-project to 3D d_2d = np.squeeze(d_pred_m) if d_2d.ndim == 3: d_2d = d_2d[0]20 unmodified lines cv2.applyColorMap(depth_vis, cv2.COLORMAP_INFERNO), cv2.COLOR_BGR2RGB )
# 3D RANSAC Wall Plane Segmentation wall_planes = fit_3d_wall_planes_ransac(masks["wall"], x_3d, y_3d, z_3d) if not wall_planes and np.count_nonzero(masks["wall"]) > 0: ys, xs = np.where(masks["wall"] > 0)139 unmodified lines masks["ceiling"], z_3d, normals, focal_px )
# When furniture covers >85% of floor, use 3D ceiling footprint as sanity anchor if vis_floor_ratio < 0.15 and ceil_sqft > 0: est_gross_floor_sqft = max(vis_floor_sqft, hull_floor_sqft, ceil_sqft * 0.90) else:45 unmodified lines f" - [{role}] {obj['label']} ({obj['score']:.0%}): ~{obj_sqft:.1f} sq.ft (~{obj_z:.2f}m)" )
# BOQ Estimation (Paint & Flooring Tiles with Wastage) paintable_sqft = total_net_wall_sqft + ( ceil_sqft if boq_cfg["include_ceiling_paint"] else 0.0 )50 unmodified lines )
payload = { "pipeline_version": "v20-metric-3d-ransac-verified", "pipeline_version": "v21-tta-gdino-base-sam2-plus", "models": { "segmentation": seg_name, "depth": DEPTH_METRIC_ID, "detection": GDINO_MODEL_ID, "mask_refinement": SAM2_MODEL_ID if HAS_SAM2 else SAM1_MODEL_ID, "depth": DEPTH_METRIC_ID + " (Flip-TTA)", "detection": gdino_active_id, "mask_refinement": sam_active_id, }, "intrinsics": {"focal_px": round(focal_px, 1), "source": focal_src}, "calibration": cal_label,13 unmodified lines json_path, csv_path = export_takeoff_files(payload, csv_rows)
report_lines = [ f"Pipeline v20 — 3D Metric Depth + {seg_name} + RANSAC Planes (NMS & Verified Openings)", f"Pipeline v21 — {seg_name} + Metric Depth TTA + {gdino_active_id.split('/')[-1]}", f"Calibration: {cal_label} | Camera: {focal_src}", f"Walls ({np.count_nonzero(masks['wall']) / total_px * 100:.1f}%): Net Paintable ~{total_net_wall_sqft:.1f} sq.ft | Openings ~{total_deduct_sqft:.1f} sq.ft | Gross ~{total_gross_wall_sqft:.1f} sq.ft ({total_gross_wall_sqft / SQM_TO_SQFT:.1f} sq.m)", ]73 unmodified lines gr.File(label="Download JSON Report"), gr.File(label="Download CSV Takeoff"), ], title="Smart Area v20 — 3D Metric Depth, Mask2Former & Verified BOQ Analyzer", title="Smart Area v21 — Flip-TTA, Grounding DINO Base, SAM 2.1 & 3D BOQ Analyzer",)
if __name__ == "__main__":app.py+144-52