Spaces:
Running on Zero

Smart_Area / app.py
Akshtheta's picture
Update app.py
0efbac7 verified
Raw History Blame Contribute Delete
57.1 kB
import csv import json import math import os import re import tempfile from datetime import datetime import cv2 import gradio as gr import numpy as np import spaces import torch from PIL import ExifTags, Image from transformers import ( AutoImageProcessor, AutoModelForDepthEstimation, AutoModelForSemanticSegmentation, AutoModelForZeroShotObjectDetection, AutoProcessor, Mask2FormerForUniversalSegmentation, ) try: from transformers import Sam2Model, Sam2Processor HAS_SAM2 = True except ImportError: from transformers import SamModel, SamProcessor HAS_SAM2 = False MASK2FORMER_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_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.7639104 FT_TO_M = 0.3048 CLADDING_PROMPTS = [ "wood paneling", "fluted panel", "marble wall", "wall cladding", ] AUTO_OPENING_PROMPTS = ["doorway", "archway", "mirror"] CALIBRATION_LOG_PATH = os.path.join(tempfile.gettempdir(), "smart_area_calibration_log.jsonl") seg_processor = None seg_model = None seg_is_mask2former = True depth_processor = None depth_model = None gdino_processor = None gdino_model = None gdino_active_id = GDINO_PRIMARY_ID sam_processor = None sam_model = None sam_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, gdino_active_id global sam_processor, sam_model, sam_active_id device = "cuda" if torch.cuda.is_available() else "cpu" if seg_model is None: try: seg_processor = AutoImageProcessor.from_pretrained(MASK2FORMER_ID) seg_model = ( Mask2FormerForUniversalSegmentation.from_pretrained(MASK2FORMER_ID) .to(device) .eval() ) seg_is_mask2former = True except Exception: seg_processor = AutoImageProcessor.from_pretrained(SEGFORMER_FALLBACK_ID) seg_model = ( AutoModelForSemanticSegmentation.from_pretrained(SEGFORMER_FALLBACK_ID) .to(device) .eval() ) seg_is_mask2former = False if depth_model is None: depth_processor = AutoImageProcessor.from_pretrained(DEPTH_METRIC_ID) depth_model = ( AutoModelForDepthEstimation.from_pretrained(DEPTH_METRIC_ID) .to(device) .eval() ) if gdino_model is None: try: 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_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, seg_model, seg_is_mask2former, depth_processor, depth_model, gdino_processor, gdino_model, sam_processor, sam_model, ) def _parse_terms(csv_text): if not csv_text: return [] return [t.strip().lower() for t in csv_text.split(",") if t.strip()] def extract_focal_px_from_exif(img_pil, width, height): try: exif = img_pil.getexif() if exif: tag_map = {ExifTags.TAGS.get(k, k): v for k, v in exif.items()} f35 = tag_map.get("FocalLengthIn35mmFilm") if f35 and float(f35) > 5.0: focal_px = (float(f35) / 36.0) * float(max(width, height)) return ( float( np.clip( focal_px, 0.55 * max(width, height), 1.8 * max(width, height), ) ), f"EXIF 35mm ({float(f35):.0f}mm)", ) except Exception: pass return 0.85 * float(max(width, height)), "Default FOV (~60°)" def parse_boq_scope(scope_text): txt = (scope_text or "").lower() coats_match = re.search(r"(\d+)\s*coat", txt) paint_coats = int(coats_match.group(1)) if coats_match else 2 wastage_match = re.search(r"(\d+(?:\.\d+)?)\s*%\s*wast", txt) wastage_pct = float(wastage_match.group(1)) if wastage_match else 10.0 gst_match = re.search(r"(\d+(?:\.\d+)?)\s*%\s*gst", txt) gst_pct = float(gst_match.group(1)) if gst_match else 18.0 tile_match = re.search( r"(\d+(?:\.\d+)?)\s*[x×]\s*(\d+(?:\.\d+)?)\s*(ft|feet|inch|in|mm)?", txt ) tile_sqft = 8.0 tile_label = "2x4 ft" if tile_match: a, b, unit = ( float(tile_match.group(1)), float(tile_match.group(2)), tile_match.group(3) or "ft", ) if unit in ("inch", "in"): tile_sqft = (a * b) / 144.0 tile_label = f"{a:g}x{b:g} in" elif unit == "mm": tile_sqft = (a * b) / 92903.04 tile_label = f"{a:g}x{b:g} mm" else: tile_sqft = a * b tile_label = f"{a:g}x{b:g} ft" include_ceiling_paint = ( "ceiling" in txt and "no ceiling" not in txt and "exclude ceiling" not in txt ) return { "paint_coats": max(1, min(paint_coats, 4)), "wastage_pct": float(np.clip(wastage_pct, 0.0, 35.0)), "gst_pct": float(np.clip(gst_pct, 0.0, 28.0)), "tile_sqft": max(tile_sqft, 0.25), "tile_label": tile_label, "include_ceiling_paint": include_ceiling_paint, } def apply_mask_nms(detected_objects, iou_thresh=0.45, contain_thresh=0.65): """Deduplicate overlapping and nested SAM masks per label using IoU + containment.""" if not detected_objects: return [] sorted_objs = sorted(detected_objects, key=lambda o: o["score"], reverse=True) kept = [] for cand in sorted_objs: cm = cand["mask"] > 0 c_area = int(np.count_nonzero(cm)) if c_area == 0: continue is_dup = False for k in kept: same_cls = ( cand["label"] == k["label"] or cand["label"] in k["label"] or k["label"] in cand["label"] ) if not same_cls: continue km = k["mask"] > 0 k_area = int(np.count_nonzero(km)) inter = int(np.count_nonzero(cm & km)) if inter == 0: continue union = int(np.count_nonzero(cm | km)) iou = inter / float(union) if union > 0 else 0.0 containment = inter / float(min(c_area, k_area)) if iou > iou_thresh or containment > contain_thresh: is_dup = True break if not is_dup: kept.append(cand) return kept @spaces.GPU(duration=120) def run_models(img_pil, prompt_terms): ( s_proc, s_mod, is_m2f, d_proc, d_mod, g_proc, g_mod, sam_proc, sam_mod, ) = 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(): s_out = s_mod(**s_inputs) s_out_flip = s_mod(**s_inputs_flip) if is_m2f: pred_orig = ( s_proc.post_process_semantic_segmentation( s_out, target_sizes=[(h, w)] )[0] .detach() .cpu() .numpy() ) pred_flip = np.fliplr( s_proc.post_process_semantic_segmentation( s_out_flip, target_sizes=[(h, w)] )[0] .detach() .cpu() .numpy() ) 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: 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() ) 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 {} detected_objects = [] clean_terms = list(dict.fromkeys([t for t in prompt_terms if t])) if clean_terms: text_prompt = ". ".join(clean_terms) + "." g_inputs = g_proc(images=img_pil, text=text_prompt, return_tensors="pt").to( device ) with torch.inference_mode(): g_outputs = g_mod(**g_inputs) g_res = g_proc.post_process_grounded_object_detection( g_outputs, g_inputs.input_ids, threshold=0.35, text_threshold=0.28, target_sizes=[(h, w)], )[0] boxes = g_res["boxes"].detach().cpu().numpy() scores = g_res["scores"].detach().cpu().numpy() raw_labels = ( g_res["text_labels"] if "text_labels" in g_res else g_res["labels"] ) if len(boxes) > 0: order = np.argsort(-scores)[:22] boxes = boxes[order] scores = scores[order] raw_labels = [str(raw_labels[i]).strip().lower() for i in order] boxes_list = boxes.tolist() sam_inputs = sam_proc( images=img_pil, input_boxes=[boxes_list], return_tensors="pt" ).to(device) with torch.inference_mode(): sam_outputs = sam_mod(**sam_inputs) if HAS_SAM2: masks_list = sam_proc.post_process_masks( sam_outputs.pred_masks.cpu(), sam_inputs["original_sizes"].cpu(), )[0] else: masks_list = sam_proc.post_process_masks( sam_outputs.pred_masks.cpu(), sam_inputs["original_sizes"].cpu(), sam_inputs["reshaped_input_sizes"].cpu(), )[0] iou_scores = sam_outputs.iou_scores.detach().cpu()[0] for idx in range(len(boxes_list)): best_k = int(iou_scores[idx].argmax()) m_np = (masks_list[idx, best_k].numpy() > 0).astype(np.uint8) * 255 if m_np.shape != (h, w): m_np = cv2.resize( m_np, (w, h), interpolation=cv2.INTER_NEAREST ) detected_objects.append( { "label": raw_labels[idx], "score": float(scores[idx]), "box": [int(round(v)) for v in boxes_list[idx]], "mask": m_np, } ) detected_objects = apply_mask_nms( detected_objects, iou_thresh=0.45, contain_thresh=0.65 ) return ( np.asarray(pred_map), id2label, np.asarray(d_pred, dtype=np.float32), detected_objects, "Mask2Former-Swin-Large (TTA)" if is_m2f else "SegFormer-B2 (TTA)", ) def backproject_depth_to_3d(depth_m, focal_px): h, w = depth_m.shape cx, cy = w * 0.5, h * 0.5 u = np.arange(w, dtype=np.float32)[None, :] v = np.arange(h, dtype=np.float32)[:, None] z = np.clip(depth_m.astype(np.float32), 0.35, 25.0) x = (u - cx) * z / focal_px y = (v - cy) * z / focal_px return x, y, z def compute_surface_normals(x, y, z): z_s = cv2.GaussianBlur(z, (9, 9), 0) x_s = cv2.GaussianBlur(x, (9, 9), 0) y_s = cv2.GaussianBlur(y, (9, 9), 0) dz_dx = cv2.Sobel(z_s, cv2.CV_32F, 1, 0, ksize=5) dz_dy = cv2.Sobel(z_s, cv2.CV_32F, 0, 1, ksize=5) dx_dx = cv2.Sobel(x_s, cv2.CV_32F, 1, 0, ksize=5) dx_dy = cv2.Sobel(x_s, cv2.CV_32F, 0, 1, ksize=5) dy_dx = cv2.Sobel(y_s, cv2.CV_32F, 1, 0, ksize=5) dy_dy = cv2.Sobel(y_s, cv2.CV_32F, 0, 1, ksize=5) tx = np.stack([dx_dx, dy_dx, dz_dx], axis=-1) ty = np.stack([dx_dy, dy_dy, dz_dy], axis=-1) normals = np.cross(tx, ty) norm_len = np.linalg.norm(normals, axis=-1, keepdims=True) + 1e-6 normals = normals / norm_len flip = normals[..., 2] > 0 normals[flip] *= -1.0 return normals def calibrate_metric_scale(masks, door_mask, floor_zone_mask, y_3d, cal_mode, ref_dim_ft): ref_m = float(ref_dim_ft) * FT_TO_M h, w = masks["wall"].shape if cal_mode == "Door Height (ft)" and np.count_nonzero(door_mask) > 400: num_l, labels, stats, _ = cv2.connectedComponentsWithStats(door_mask) best_lbl = max( range(1, num_l), key=lambda l: int(stats[l, cv2.CC_STAT_AREA]), default=0 ) if best_lbl > 0 and stats[best_lbl, cv2.CC_STAT_HEIGHT] >= h * 0.15: ys = y_3d[labels == best_lbl] est_h_m = float(np.percentile(ys, 97) - np.percentile(ys, 3)) if est_h_m > 0.5: scale = float(np.clip(ref_m / est_h_m, 0.75, 1.25)) return ( scale, f"Metric Depth + Door Ref ({ref_dim_ft:.1f} ft, scale {scale:.2f}x)", ) 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)) wall_cols = np.where(np.any(masks["wall"] > 0, axis=0))[0] strict_spans_m = [] fallback_spans_m = [] for col in wall_cols[::4]: ys_idx = np.where(masks["wall"][:, col] > 0)[0] if len(ys_idx) < int(h * 0.20): continue top_y, bot_y = int(ys_idx[0]), int(ys_idx[-1]) y_vals = y_3d[ys_idx, col] span = float(np.percentile(y_vals, 97) - np.percentile(y_vals, 3)) if span <= 0.8: continue touches_ceil = bool(ceil_dil[top_y, col] > 0) touches_floor = bool(floor_dil[bot_y, col] > 0) if touches_ceil and touches_floor: strict_spans_m.append(span) elif top_y > 8 and bot_y < h - 8: fallback_spans_m.append(span) chosen_spans = strict_spans_m if len(strict_spans_m) >= 5 else fallback_spans_m if chosen_spans: est_ceil_m = float(np.percentile(chosen_spans, 70)) scale = float(np.clip(ref_m / est_ceil_m, 0.75, 1.25)) tag = "strict" if chosen_spans is strict_spans_m else "fallback" return ( scale, f"Metric Depth + Ceiling Ref ({ref_dim_ft:.1f} ft, scale {scale:.2f}x, {tag})", ) return 1.0, "Pure Metric Depth (unscaled)" def merge_coplanar_planes(planes, z_3d, normal_angle_tol=15.0, depth_tol_m=0.35): 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.03): h, w = wall_mask.shape min_px = int(h * w * min_area_ratio) remaining = (wall_mask > 0).copy() planes = [] rng = np.random.default_rng(42) for _ in range(6): ys, xs = np.where(remaining) if len(ys) < min_px: break pts = np.stack([x_3d[ys, xs], y_3d[ys, xs], z_3d[ys, xs]], axis=1) n_pts = len(pts) sub_idx = rng.choice(n_pts, size=min(n_pts, 4000), replace=False) sub_pts = pts[sub_idx] best_normal = None best_d = 0.0 best_count = 0 for _it in range(140): sample = sub_pts[rng.choice(len(sub_pts), size=3, replace=False)] v1 = sample[1] - sample[0] v2 = sample[2] - sample[0] n = np.cross(v1, v2) n_norm = np.linalg.norm(n) if n_norm < 1e-5: continue n = n / n_norm if abs(n[1]) > 0.45: continue d = -np.dot(n, sample[0]) dist = np.abs(sub_pts @ n + d) count = int(np.sum(dist < 0.14)) if count > best_count: best_count = count best_normal = n best_d = d if best_normal is None or best_count < 80: break full_dist = np.abs(pts @ best_normal + best_d) inlier_mask_1d = full_dist < 0.18 if int(np.sum(inlier_mask_1d)) < min_px: break plane_mask = np.zeros((h, w), np.uint8) plane_mask[ys[inlier_mask_1d], xs[inlier_mask_1d]] = 255 plane_mask = cv2.morphologyEx( plane_mask, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8) ) plane_mask = cv2.morphologyEx( plane_mask, cv2.MORPH_OPEN, np.ones((5, 5), np.uint8) ) plane_mask = cv2.bitwise_and(plane_mask, wall_mask) area_px = int(np.count_nonzero(plane_mask)) if area_px < min_px: remaining[plane_mask > 0] = False continue if best_normal[2] > 0: best_normal = -best_normal cos_theta = float(np.clip(abs(best_normal[2]), 0.35, 1.0)) sec_theta = 1.0 / cos_theta angle_deg = float(np.degrees(np.arccos(cos_theta))) py, px = np.where(plane_mask > 0) planes.append( { "mask": plane_mask, "area_px": area_px, "centroid": (int(np.mean(px)), int(np.mean(py))), "normal": best_normal.tolist(), "sec_theta": sec_theta, "angle_deg": angle_deg, "median_depth_m": float(np.median(z_3d[plane_mask > 0])), } ) remaining[plane_mask > 0] = False return merge_coplanar_planes(planes, z_3d) def estimate_3d_room_footprint_sqft(wall_planes, x_3d, z_3d): if not wall_planes: return 0.0, 0.0, 0.0 xs_all, zs_all = [], [] for p in wall_planes: ys, xs = np.where(p["mask"] > 0) if len(ys) > 50: xs_all.append(x_3d[ys, xs]) zs_all.append(z_3d[ys, xs]) if not xs_all: return 0.0, 0.0, 0.0 x_cat = np.concatenate(xs_all) z_cat = np.concatenate(zs_all) span_x_m = float(np.clip(np.percentile(x_cat, 96) - np.percentile(x_cat, 4), 1.8, 10.0)) span_z_m = float(np.clip(np.percentile(z_cat, 96) - np.percentile(z_cat, 4), 1.8, 10.0)) return span_x_m * span_z_m * SQM_TO_SQFT, span_x_m / FT_TO_M, span_z_m / FT_TO_M def compute_3d_surface_area_sqft(mask, z_3d, focal_px, cos_theta=None): ys, xs = np.where(mask > 0) if len(ys) == 0: return 0.0 z_vals = z_3d[ys, xs] px_area_sqm = (z_vals / focal_px) ** 2 if cos_theta is not None: sec_factor = 1.0 / max(float(cos_theta), 0.35) total_sqm = float(np.sum(px_area_sqm)) * sec_factor else: total_sqm = float(np.sum(px_area_sqm)) return total_sqm * SQM_TO_SQFT def compute_horizontal_3d_area_sqft(mask, z_3d, normals, focal_px): ys, xs = np.where(mask > 0) if len(ys) == 0: return 0.0 z_vals = z_3d[ys, xs] nz = np.clip(np.abs(normals[ys, xs, 2]), 0.22, 0.95) px_area_sqm = ((z_vals / focal_px) ** 2) / nz return float(np.sum(px_area_sqm)) * SQM_TO_SQFT def assign_openings_to_walls(openings_mask, wall_planes): h, w = openings_mask.shape wall_openings = [np.zeros((h, w), np.uint8) for _ in wall_planes] if not wall_planes or np.count_nonzero(openings_mask) == 0: return wall_openings num_op, op_labels, op_stats, _ = cv2.connectedComponentsWithStats(openings_mask) k_border = np.ones((17, 17), np.uint8) for op_lbl in range(1, num_op): if int(op_stats[op_lbl, cv2.CC_STAT_AREA]) < 150: continue comp_mask = (op_labels == op_lbl).astype(np.uint8) * 255 comp_dilated = cv2.dilate(comp_mask, k_border) best_idx = -1 best_overlap = 0 for idx, plane in enumerate(wall_planes): overlap = int( np.count_nonzero(cv2.bitwise_and(comp_dilated, plane["mask"])) ) if overlap > best_overlap: best_overlap = overlap best_idx = idx if best_idx >= 0 and best_overlap >= 25: wall_openings[best_idx] = cv2.bitwise_or( wall_openings[best_idx], comp_mask ) return wall_openings def estimate_gross_floor_mask(floor_mask, floor_furniture_mask, wall_mask): h, w = floor_mask.shape floor_ys = np.where(floor_mask > 0)[0] if len(floor_ys) == 0: return floor_mask.copy() horizon_y = int(np.percentile(floor_ys, 5)) valid_zone = np.zeros((h, w), np.uint8) valid_zone[horizon_y:, :] = 255 clutter_on_floor = cv2.bitwise_and(floor_furniture_mask, valid_zone) clutter_on_floor = cv2.bitwise_and(clutter_on_floor, cv2.bitwise_not(wall_mask)) combined = cv2.bitwise_or(floor_mask, clutter_on_floor) pts = cv2.findNonZero(combined) if pts is None or len(pts) < 10: return floor_mask.copy() hull = cv2.convexHull(pts) gross_mask = np.zeros((h, w), np.uint8) cv2.fillConvexPoly(gross_mask, hull, 255) gross_mask = cv2.bitwise_and(gross_mask, valid_zone) gross_mask = cv2.bitwise_and(gross_mask, cv2.bitwise_not(wall_mask)) return cv2.bitwise_or(gross_mask, floor_mask) def _boxes_overlap(b1, b2, pad=5): return not ( b1[2] + pad < b2[0] or b1[0] - pad > b2[2] or b1[3] + pad < b2[1] or b1[1] - pad > b2[3] ) def draw_label_badge(img, text, cx, cy, placed_boxes, accent_bgr=None): h, w, _ = img.shape font = cv2.FONT_HERSHEY_SIMPLEX scale = 0.46 (tw, th), baseline = cv2.getTextSize(text, font, scale, 1) tx = int(np.clip(cx - tw // 2, 8, max(8, w - tw - 12))) chosen_box = None chosen_ty = int(np.clip(cy, th + 8, h - 8)) for dy in (0, -32, 32, -64, 64, -96, 96): ty = int(np.clip(cy + dy, th + 8, h - 8)) x0, y0 = max(0, tx - 6), max(0, ty - th - 5) x1, y1 = min(w, tx + tw + 6), min(h, ty + baseline + 3) cand = (x0, y0, x1, y1) if not any(_boxes_overlap(cand, b) for b in placed_boxes): chosen_box = cand chosen_ty = ty break if chosen_box is None: x0, y0 = max(0, tx - 6), max(0, chosen_ty - th - 5) x1, y1 = min(w, tx + tw + 6), min(h, chosen_ty + baseline + 3) chosen_box = (x0, y0, x1, y1) placed_boxes.append(chosen_box) x0, y0, x1, y1 = chosen_box img[y0:y1, x0:x1] = (0.35 * img[y0:y1, x0:x1]).astype(np.uint8) if accent_bgr is not None: cv2.rectangle(img, (x0, y0), (x1, y1), accent_bgr, 1) cv2.putText( img, text, (tx, chosen_ty), font, scale, (255, 255, 255), 1, cv2.LINE_AA ) def export_takeoff_files(payload, rows): tmp_dir = tempfile.gettempdir() json_path = os.path.join(tmp_dir, "smart_area_v23_report.json") csv_path = os.path.join(tmp_dir, "smart_area_v23_takeoff.csv") with open(json_path, "w", encoding="utf-8") as jf: json.dump(payload, jf, indent=2) fieldnames = [ "Surface", "Net_Paintable_SqFt", "Cladding_Feature_SqFt", "Deducted_Openings_SqFt", "Gross_Area_SqFt", "Net_Area_SqM", "Gross_Area_SqM", "Viewing_Angle_Deg", "Median_Depth_M", ] with open(csv_path, "w", newline="", encoding="utf-8") as cf: writer = csv.DictWriter(cf, fieldnames=fieldnames) writer.writeheader() writer.writerows(rows) return json_path, csv_path def log_ground_truth(last_payload, actual_wall_sqft, actual_floor_sqft, site_notes): """Append real laser-tape ground truth alongside v23 features for future regressor training.""" if not last_payload: return "Run an analysis first before logging ground truth.", None entry = { "timestamp_utc": datetime.utcnow().isoformat() + "Z", "site_notes": site_notes or "", "actual_laser_sqft": { "wall_net_sqft": float(actual_wall_sqft) if actual_wall_sqft else None, "floor_gross_sqft": float(actual_floor_sqft) if actual_floor_sqft else None, }, "predicted_summary": last_payload.get("summary", {}), "intrinsics": last_payload.get("intrinsics", {}), "calibration": last_payload.get("calibration", ""), } with open(CALIBRATION_LOG_PATH, "a", encoding="utf-8") as f: f.write(json.dumps(entry) + "\n") with open(CALIBRATION_LOG_PATH, "r", encoding="utf-8") as f: total_rows = sum(1 for _ in f) return f"Saved ground truth sample #{total_rows} to calibration log.", CALIBRATION_LOG_PATH def resize_max_side(img_pil, max_side=1024): w, h = img_pil.size scale = min(max_side / max(w, h), 1.0) if scale < 1.0: img_pil = img_pil.resize( (max(1, int(w * scale)), max(1, int(h * scale))), Image.Resampling.LANCZOS, ) return img_pil def analyze_room( input_img_path, cal_mode="Ceiling Height (ft)", ref_dim_ft=10.0, focus_mode="All Room Surfaces (Ignore Clutter)", ignore_objects="sofa, couch, bed, table, chair, wardrobe, cabinet, dresser, console, nightstand, shelf, television, curtain, chandelier, fan", target_query="door, window", boq_scope="2 coats paint, 10% wastage, 2x4 ft tiles, 18% GST", ): if input_img_path is None: return None, None, "Please upload an interior photo.", None, None, None try: ref_val = float(ref_dim_ft) if ref_dim_ft and ref_dim_ft > 0 else 10.0 raw_pil = Image.open(input_img_path) img_pil = resize_max_side(raw_pil.convert("RGB"), max_side=1024) work_np = np.array(img_pil) h, w, _ = work_np.shape focal_px, focal_src = extract_focal_px_from_exif(raw_pil, w, h) boq_cfg = parse_boq_scope(boq_scope) ignore_terms = _parse_terms(ignore_objects) target_terms = _parse_terms(target_query) combined_prompts = ( ignore_terms + target_terms + AUTO_OPENING_PROMPTS + CLADDING_PROMPTS ) pred_map, id2label, d_pred_m, detected_objs, seg_name = run_models( img_pil, combined_prompts ) pred_2d = np.squeeze(pred_map) if pred_2d.ndim == 3: pred_2d = pred_2d[0] pred_resized = cv2.resize( pred_2d.astype(np.float32), (w, h), interpolation=cv2.INTER_NEAREST ).astype(np.int32) masks = { "wall": np.zeros((h, w), np.uint8), "ceiling": np.zeros((h, w), np.uint8), "floor": np.zeros((h, w), np.uint8), } door_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", "doorway", "archway", "mirror", "wardrobe", "closet", ) reflective_keywords = ("window", "pane", "mirror", "wardrobe", "closet") floor_surface_keywords = ("floor", "rug", "carpet") floor_furn_keywords = ( "sofa", "couch", "bed", "table", "chair", "ottoman", "armchair", "desk", "bench", "dresser", "console", "nightstand", "cabinet", ) for cls_id in np.unique(pred_resized).tolist(): cid = int(cls_id) lbl = str(id2label.get(cid, id2label.get(str(cid), ""))).lower() m = (pred_resized == cid).astype(np.uint8) * 255 if "wall" in lbl: masks["wall"] = cv2.bitwise_or(masks["wall"], m) if "ceiling" in lbl: masks["ceiling"] = cv2.bitwise_or(masks["ceiling"], m) if any(fsk in lbl for fsk in floor_surface_keywords): masks["floor"] = cv2.bitwise_or(masks["floor"], m) if "door" in lbl or "windowpane" in lbl: door_mask = cv2.bitwise_or(door_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( wall_openings_source_mask, m ) if any(fk in lbl for fk in floor_furn_keywords): floor_furniture_mask = cv2.bitwise_or(floor_furniture_mask, m) reflective_mask = sem_reflective_mask.copy() for obj in detected_objs: 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_reflective_mask)) ) / float(om_px) if sem_overlap > 0.10 or obj["score"] >= 0.50: 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) cladding_mask = np.zeros((h, w), np.uint8) ignored_items = [] focused_items = [] cladding_items = [] for obj in detected_objs: lbl = obj["label"] omask = obj["mask"] omask_px = int(np.count_nonzero(omask)) if omask_px == 0: continue is_cladding = any( ck in lbl for ck in ("panel", "fluted", "marble", "cladding") ) if is_cladding: cladding_mask = cv2.bitwise_or(cladding_mask, omask) cladding_items.append(obj) continue if ( np.count_nonzero(reflective_mask) > 0 and not any( wk in lbl for wk in ( "window", "pane", "curtain", "drape", "mirror", "wardrobe", "closet", ) ) ): inside_ref = int( np.count_nonzero(cv2.bitwise_and(omask, reflective_mask)) ) if inside_ref / float(omask_px) > 0.55: continue 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) conf_gate = ( 0.42 if any(k in lbl for k in ("door", "arch", "mirror")) else 0.55 ) verified_opening = (sem_ov > 0.08) or (obj["score"] >= conf_gate) if not verified_opening: continue is_target = any(t in lbl or lbl in t for t in target_terms) is_ignored = any(ig in lbl or lbl in ig for ig in ignore_terms) if focus_mode == "Specific Object Only" and is_target: sam_target_mask = cv2.bitwise_or(sam_target_mask, omask) focused_items.append(obj) if "door" in lbl or "window" in lbl: door_mask = cv2.bitwise_or(door_mask, omask) if is_opening_lbl and verified_opening: wall_openings_source_mask = cv2.bitwise_or( wall_openings_source_mask, omask ) elif is_ignored: sam_ignored_mask = cv2.bitwise_or(sam_ignored_mask, omask) ignored_items.append(obj) if any(fk in lbl for fk in floor_furn_keywords): floor_furniture_mask = cv2.bitwise_or(floor_furniture_mask, omask) if is_opening_lbl and verified_opening: wall_openings_source_mask = cv2.bitwise_or( wall_openings_source_mask, omask ) if "door" in lbl: door_mask = cv2.bitwise_or(door_mask, omask) elif is_target or (is_opening_lbl and verified_opening): sam_target_mask = cv2.bitwise_or(sam_target_mask, omask) focused_items.append(obj) if is_opening_lbl and verified_opening: wall_openings_source_mask = cv2.bitwise_or( wall_openings_source_mask, omask ) if np.count_nonzero(sam_ignored_mask) > 0: masks["wall"] = cv2.bitwise_and( masks["wall"], cv2.bitwise_not(sam_ignored_mask) ) masks["floor"] = cv2.bitwise_and( masks["floor"], cv2.bitwise_not(sam_ignored_mask) ) d_2d = np.squeeze(d_pred_m) if d_2d.ndim == 3: d_2d = d_2d[0] depth_m = cv2.resize( d_2d.astype(np.float32), (w, h), interpolation=cv2.INTER_CUBIC ) depth_m = np.nan_to_num(depth_m, nan=2.0, posinf=10.0, neginf=0.5) depth_m = np.clip(depth_m, 0.35, 25.0) floor_zone_mask = cv2.bitwise_or(masks["floor"], floor_furniture_mask) x_raw, y_raw, z_raw = backproject_depth_to_3d(depth_m, focal_px) metric_scale, cal_label = calibrate_metric_scale( masks, door_mask, floor_zone_mask, y_raw, cal_mode, ref_val ) x_3d, y_3d, z_3d = ( x_raw * metric_scale, y_raw * metric_scale, z_raw * metric_scale, ) normals = compute_surface_normals(x_3d, y_3d, z_3d) depth_vis = cv2.normalize(z_3d, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8) depth_colored = cv2.cvtColor( cv2.applyColorMap(depth_vis, cv2.COLORMAP_INFERNO), cv2.COLOR_BGR2RGB ) 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) wall_planes = [ { "mask": masks["wall"], "area_px": int(len(ys)), "centroid": (int(np.mean(xs)), int(np.mean(ys))), "normal": [0.0, 0.0, -1.0], "sec_theta": 1.0, "angle_deg": 0.0, "median_depth_m": float(np.median(z_3d[ys, xs])), } ] wall_openings_masks = assign_openings_to_walls( wall_openings_source_mask, wall_planes ) wall_palette = [ np.array([65, 135, 255]), np.array([150, 100, 255]), np.array([50, 190, 230]), np.array([255, 120, 170]), np.array([100, 160, 255]), ] overlay = work_np.copy() placed_boxes = [] if focus_mode == "Specific Object Only": overlay = (0.45 * overlay).astype(np.uint8) if np.count_nonzero(sam_target_mask) > 0: tm = sam_target_mask > 0 overlay[tm] = np.clip( 0.55 * work_np[tm] + 0.45 * np.array([40, 230, 140]), 0, 255 ).astype(np.uint8) contours, _ = cv2.findContours( sam_target_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE ) cv2.drawContours(overlay, contours, -1, (40, 255, 140), 2) else: for idx, plane in enumerate(wall_planes): color = wall_palette[idx % len(wall_palette)] pm = plane["mask"] > 0 overlay[pm] = (0.72 * overlay[pm] + 0.28 * color).astype(np.uint8) cnts, _ = cv2.findContours( plane["mask"], cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE ) cv2.drawContours(overlay, cnts, -1, (0, 255, 255), 1) if np.count_nonzero(cladding_mask) > 0: cl_cnts, _ = cv2.findContours( cladding_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE ) cv2.drawContours(overlay, cl_cnts, -1, (255, 180, 40), 2) if focus_mode != "Walls Only (Ignore Floor & Ceiling)": overlay[masks["floor"] > 0] = ( 0.74 * overlay[masks["floor"] > 0] + 0.26 * np.array([75, 210, 130]) ).astype(np.uint8) overlay[masks["ceiling"] > 0] = ( 0.74 * overlay[masks["ceiling"] > 0] + 0.26 * np.array([255, 195, 70]) ).astype(np.uint8) if np.count_nonzero(sam_ignored_mask) > 0: ig_cnts, _ = cv2.findContours( sam_ignored_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE ) cv2.drawContours(overlay, ig_cnts, -1, (255, 110, 90), 1) plane_lines = [] wall_records = [] csv_rows = [] total_net_paint_sqft = 0.0 total_cladding_sqft = 0.0 total_deduct_sqft = 0.0 for idx, plane in enumerate(wall_planes): cos_theta = 1.0 / max(plane["sec_theta"], 1.0) plane_clad_mask = cv2.bitwise_and(plane["mask"], cladding_mask) plane_paint_mask = cv2.bitwise_and( plane["mask"], cv2.bitwise_not(cladding_mask) ) paint_sqft = compute_3d_surface_area_sqft( plane_paint_mask, z_3d, focal_px, cos_theta=cos_theta ) clad_sqft = compute_3d_surface_area_sqft( plane_clad_mask, z_3d, focal_px, cos_theta=cos_theta ) op_mask = wall_openings_masks[idx] op_px = int(np.count_nonzero(op_mask)) if op_px > 0: host_z = plane["median_depth_m"] raw_deduct_sqft = ( op_px * ((host_z / focal_px) ** 2) / max(cos_theta, 0.35) ) * SQM_TO_SQFT else: raw_deduct_sqft = 0.0 deduct_sqft = min(raw_deduct_sqft, (paint_sqft + clad_sqft) * 1.85) gross_sqft = paint_sqft + clad_sqft + deduct_sqft total_net_paint_sqft += paint_sqft total_cladding_sqft += clad_sqft total_deduct_sqft += deduct_sqft cx, cy = plane["centroid"] if focus_mode != "Specific Object Only": tag = f"W{idx + 1}: {paint_sqft:.0f} sf paint" + ( f" + {clad_sqft:.0f} sf clad" if clad_sqft >= 5 else "" ) draw_label_badge(overlay, tag, cx, cy, placed_boxes) plane_lines.append( f" - Wall {idx + 1}: Paintable ~{paint_sqft:.1f} sq.ft | Cladding ~{clad_sqft:.1f} sq.ft | " f"Openings ~{deduct_sqft:.1f} sq.ft | Gross ~{gross_sqft:.1f} sq.ft " f"(3D tilt ~{plane['angle_deg']:.0f}°, depth ~{plane['median_depth_m']:.2f}m)" ) wall_records.append( { "wall_id": f"Wall {idx + 1}", "net_paintable_sqft": round(paint_sqft, 2), "cladding_feature_sqft": round(clad_sqft, 2), "deducted_openings_sqft": round(deduct_sqft, 2), "gross_wall_sqft": round(gross_sqft, 2), "net_paintable_sqm": round(paint_sqft / SQM_TO_SQFT, 2), "gross_wall_sqm": round(gross_sqft / SQM_TO_SQFT, 2), "viewing_angle_deg": round(plane["angle_deg"], 1), "median_depth_m": round(plane["median_depth_m"], 2), } ) csv_rows.append( { "Surface": f"Wall {idx + 1}", "Net_Paintable_SqFt": round(paint_sqft, 2), "Cladding_Feature_SqFt": round(clad_sqft, 2), "Deducted_Openings_SqFt": round(deduct_sqft, 2), "Gross_Area_SqFt": round(gross_sqft, 2), "Net_Area_SqM": round(paint_sqft / SQM_TO_SQFT, 2), "Gross_Area_SqM": round(gross_sqft / SQM_TO_SQFT, 2), "Viewing_Angle_Deg": round(plane["angle_deg"], 1), "Median_Depth_M": round(plane["median_depth_m"], 2), } ) total_gross_wall_sqft = ( total_net_paint_sqft + total_cladding_sqft + total_deduct_sqft ) total_px = h * w vis_floor_ratio = np.count_nonzero(masks["floor"]) / float(total_px) vis_floor_sqft = compute_horizontal_3d_area_sqft( masks["floor"], z_3d, normals, focal_px ) gross_floor_mask = estimate_gross_floor_mask( masks["floor"], floor_furniture_mask, masks["wall"] ) hull_floor_sqft = compute_horizontal_3d_area_sqft( gross_floor_mask, z_3d, normals, focal_px ) ceil_sqft = compute_horizontal_3d_area_sqft( masks["ceiling"], z_3d, normals, focal_px ) inferred_3d_sqft, span_x_ft, span_z_ft = estimate_3d_room_footprint_sqft( wall_planes, x_3d, z_3d ) # Cap 3D inferred floor footprint against visible ceiling to prevent bounding-box blowup if vis_floor_ratio < 0.15: inferred_cap = ( min(inferred_3d_sqft * 0.85, ceil_sqft * 1.25) if ceil_sqft > 40.0 else inferred_3d_sqft * 0.85 ) est_gross_floor_sqft = max( vis_floor_sqft, hull_floor_sqft, ceil_sqft * 0.90, inferred_cap ) else: est_gross_floor_sqft = max(vis_floor_sqft, hull_floor_sqft) sam_obj_records = [] sam_report_lines = [] total_focused_sqft = 0.0 for obj in focused_items + cladding_items + ignored_items: if obj in focused_items: role = "Focused / Opening" elif obj in cladding_items: role = "Cladding / Panel" else: role = "Ignored Clutter" omask = obj["mask"] ys_o, xs_o = np.where(omask > 0) if len(ys_o) == 0: continue ring = cv2.bitwise_and( cv2.dilate(omask, np.ones((25, 25), np.uint8)), cv2.bitwise_not(omask), ) ring_z = z_3d[ring > 0] obj_z = ( float(np.median(ring_z)) if len(ring_z) > 20 else float(np.median(z_3d[ys_o, xs_o])) ) obj_sqft = (len(ys_o) * ((obj_z / focal_px) ** 2)) * SQM_TO_SQFT if role == "Focused / Opening": total_focused_sqft += obj_sqft ocx, ocy = int(np.mean(xs_o)), int(np.mean(ys_o)) draw_label_badge( overlay, f"{obj['label']}: ~{obj_sqft:.1f} sf", ocx, ocy, placed_boxes, accent_bgr=(40, 255, 140), ) sam_obj_records.append( { "label": obj["label"], "role": role, "confidence": round(obj["score"], 3), "est_area_sqft": round(obj_sqft, 2), "est_area_sqm": round(obj_sqft / SQM_TO_SQFT, 2), "est_depth_m": round(obj_z, 2), } ) sam_report_lines.append( f" - [{role}] {obj['label']} ({obj['score']:.0%}): ~{obj_sqft:.1f} sq.ft (~{obj_z:.2f}m)" ) paintable_sqft = total_net_paint_sqft + ( ceil_sqft if boq_cfg["include_ceiling_paint"] else 0.0 ) wastage_mult = 1.0 + boq_cfg["wastage_pct"] / 100.0 paint_litres = (paintable_sqft * boq_cfg["paint_coats"] * wastage_mult) / 130.0 primer_litres = (paintable_sqft * wastage_mult) / 150.0 tile_area_with_wastage = est_gross_floor_sqft * wastage_mult tiles_needed = int(math.ceil(tile_area_with_wastage / boq_cfg["tile_sqft"])) boq_summary = { "scope_parsed": boq_cfg, "paintable_area_sqft": round(paintable_sqft, 2), "cladding_excluded_sqft": round(total_cladding_sqft, 2), "est_primer_litres": round(primer_litres, 1), "est_paint_litres": round(paint_litres, 1), "floor_tile_area_with_wastage_sqft": round(tile_area_with_wastage, 2), "est_tile_count": tiles_needed, } csv_rows.extend( [ { "Surface": "Total Walls", "Net_Paintable_SqFt": round(total_net_paint_sqft, 2), "Cladding_Feature_SqFt": round(total_cladding_sqft, 2), "Deducted_Openings_SqFt": round(total_deduct_sqft, 2), "Gross_Area_SqFt": round(total_gross_wall_sqft, 2), "Net_Area_SqM": round(total_net_paint_sqft / SQM_TO_SQFT, 2), "Gross_Area_SqM": round(total_gross_wall_sqft / SQM_TO_SQFT, 2), "Viewing_Angle_Deg": "", "Median_Depth_M": "", }, { "Surface": "Floor (Visible / Est. Gross)", "Net_Paintable_SqFt": round(vis_floor_sqft, 2), "Cladding_Feature_SqFt": 0.0, "Deducted_Openings_SqFt": round( max(0.0, est_gross_floor_sqft - vis_floor_sqft), 2 ), "Gross_Area_SqFt": round(est_gross_floor_sqft, 2), "Net_Area_SqM": round(vis_floor_sqft / SQM_TO_SQFT, 2), "Gross_Area_SqM": round(est_gross_floor_sqft / SQM_TO_SQFT, 2), "Viewing_Angle_Deg": "", "Median_Depth_M": "", }, { "Surface": "Ceiling", "Net_Paintable_SqFt": round(ceil_sqft, 2), "Cladding_Feature_SqFt": 0.0, "Deducted_Openings_SqFt": 0.0, "Gross_Area_SqFt": round(ceil_sqft, 2), "Net_Area_SqM": round(ceil_sqft / SQM_TO_SQFT, 2), "Gross_Area_SqM": round(ceil_sqft / SQM_TO_SQFT, 2), "Viewing_Angle_Deg": "", "Median_Depth_M": "", }, ] ) payload = { "pipeline_version": "v23-containment-nms-capped-footprint", "models": { "segmentation": seg_name, "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, "summary": { "net_paintable_wall_sqft": round(total_net_paint_sqft, 2), "cladding_feature_wall_sqft": round(total_cladding_sqft, 2), "deducted_openings_sqft": round(total_deduct_sqft, 2), "gross_wall_sqft": round(total_gross_wall_sqft, 2), "visible_floor_sqft": round(vis_floor_sqft, 2), "est_gross_floor_sqft": round(est_gross_floor_sqft, 2), "inferred_3d_room_footprint_sqft": round(inferred_3d_sqft, 2), "inferred_3d_span_ft": [round(span_x_ft, 1), round(span_z_ft, 1)], "est_ceiling_sqft": round(ceil_sqft, 2), "focused_objects_sqft": round(total_focused_sqft, 2), }, "boq_estimate": boq_summary, "walls": wall_records, "detected_objects": sam_obj_records, } json_path, csv_path = export_takeoff_files(payload, csv_rows) report_lines = [ f"Pipeline v23 — {seg_name} + Metric Depth TTA + Containment NMS", f"Calibration: {cal_label} | Camera: {focal_src}", f"Walls ({np.count_nonzero(masks['wall']) / total_px * 100:.1f}%): Paintable ~{total_net_paint_sqft:.1f} sq.ft | Cladding ~{total_cladding_sqft:.1f} sq.ft | Openings ~{total_deduct_sqft:.1f} sq.ft | Gross ~{total_gross_wall_sqft:.1f} sq.ft", ] if focus_mode == "Specific Object Only": report_lines.append( f"Focused Target Objects ({len(focused_items)} found): Total ~{total_focused_sqft:.1f} sq.ft" ) elif focus_mode != "Walls Only (Ignore Floor & Ceiling)": report_lines.append( f"Floor ({vis_floor_ratio * 100:.1f}%): Visible ~{vis_floor_sqft:.1f} sq.ft | Est. Gross ~{est_gross_floor_sqft:.1f} sq.ft (3D Span ~{span_x_ft:.1f}x{span_z_ft:.1f} ft)" ) report_lines.append( f"Ceiling ({np.count_nonzero(masks['ceiling']) / total_px * 100:.1f}%): Visible ~{ceil_sqft:.1f} sq.ft ({ceil_sqft / SQM_TO_SQFT:.1f} sq.m)" ) report_lines.extend( [ "", f"BOQ Material Estimate ({boq_cfg['wastage_pct']:.0f}% wastage, {boq_cfg['gst_pct']:.0f}% GST applicable):", f" - Paint ({boq_cfg['paint_coats']} coats @ 130 sq.ft/L, excl. cladding): ~{paint_litres:.1f} L + Primer ~{primer_litres:.1f} L", f" - Flooring Tiles ({boq_cfg['tile_label']}): ~{tiles_needed} tiles (~{tile_area_with_wastage:.1f} sq.ft incl. wastage)", ] ) if plane_lines and focus_mode != "Specific Object Only": report_lines.append("") report_lines.append("3D RANSAC Per-Wall Breakdown:") report_lines.extend(plane_lines) if sam_report_lines: report_lines.append("") report_lines.append("Open-Vocabulary Detected Objects (Grounding DINO + SAM 2):") report_lines.extend(sam_report_lines) return overlay, depth_colored, "\n".join(report_lines), json_path, csv_path, payload except Exception as e: blank = np.zeros((256, 256, 3), dtype=np.uint8) return blank, blank, f"Error: {type(e).__name__}: {e}", None, None, None with gr.Blocks(title="Smart Area v23 — 3D Metric Depth & BOQ Analyzer") as demo: gr.Markdown("## Smart Area v23 — 3D Metric Depth, Containment NMS & BOQ Analyzer") last_payload_state = gr.State(None) with gr.Row(): with gr.Column(scale=1): img_in = gr.Image(type="filepath", label="Upload Interior Photo (EXIF Preserved)") cal_mode_in = gr.Radio( choices=["Ceiling Height (ft)", "Door Height (ft)"], value="Ceiling Height (ft)", label="Calibration Anchor", ) ref_dim_in = gr.Number(value=10.0, label="Reference Dimension (ft)", precision=1) focus_mode_in = gr.Radio( choices=[ "All Room Surfaces (Ignore Clutter)", "Walls Only (Ignore Floor & Ceiling)", "Specific Object Only", ], value="All Room Surfaces (Ignore Clutter)", label="Focus Mode", ) ignore_in = gr.Textbox( value="sofa, couch, bed, table, chair, wardrobe, cabinet, dresser, console, nightstand, shelf, television, curtain, chandelier, fan", label="Objects to Ignore / Subtract (comma-separated)", ) target_in = gr.Textbox( value="door, window", label="Target Objects (used in 'Specific Object Only' mode)", ) boq_in = gr.Textbox( value="2 coats paint, 10% wastage, 2x4 ft tiles, 18% GST", label="BOQ Scope (Natural Language)", ) run_btn = gr.Button("Analyze Room", variant="primary") with gr.Column(scale=1): overlay_out = gr.Image(label="3D RANSAC Spatial Overlay") depth_out = gr.Image(label="Metric Depth Map (Metres)") report_out = gr.Textbox(label="3D Geometric & BOQ Breakdown", lines=16) with gr.Row(): json_out = gr.File(label="Download JSON Report") csv_out = gr.File(label="Download CSV Takeoff") with gr.Accordion("Ground-Truth Calibration Logger (For Training Your Area Regressor)", open=False): with gr.Row(): actual_wall_in = gr.Number(label="Actual Laser Net Wall Area (sq.ft)", value=None) actual_floor_in = gr.Number(label="Actual Laser Gross Floor Area (sq.ft)", value=None) notes_in = gr.Textbox(label="Site / Room Notes (e.g. 2BHK Pune, bare plaster)") log_btn = gr.Button("Log Ground-Truth Sample") with gr.Row(): log_status = gr.Textbox(label="Log Status", interactive=False) log_file_out = gr.File(label="Download Calibration Log (.jsonl)") run_btn.click( fn=analyze_room, inputs=[img_in, cal_mode_in, ref_dim_in, focus_mode_in, ignore_in, target_in, boq_in], outputs=[overlay_out, depth_out, report_out, json_out, csv_out, last_payload_state], ) log_btn.click( fn=log_ground_truth, inputs=[last_payload_state, actual_wall_in, actual_floor_in, notes_in], outputs=[log_status, log_file_out], ) if __name__ == "__main__": demo.launch()
import csv
import json
import math
import os
import re
import tempfile
from datetime import datetime
import cv2
import gradio as gr
import numpy as np
import spaces
import torch
from PIL import ExifTags, Image
from transformers import (
AutoImageProcessor,
AutoModelForDepthEstimation,
AutoModelForSemanticSegmentation,
AutoModelForZeroShotObjectDetection,
AutoProcessor,
Mask2FormerForUniversalSegmentation,
)
try:
from transformers import Sam2Model, Sam2Processor
HAS_SAM2 = True
except ImportError:
from transformers import SamModel, SamProcessor
HAS_SAM2 = False
MASK2FORMER_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_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.7639104
FT_TO_M = 0.3048
CLADDING_PROMPTS = [
"wood paneling",
"fluted panel",
"marble wall",
"wall cladding",
]
AUTO_OPENING_PROMPTS = ["doorway", "archway", "mirror"]
CALIBRATION_LOG_PATH = os.path.join(tempfile.gettempdir(), "smart_area_calibration_log.jsonl")
seg_processor = None
seg_model = None
seg_is_mask2former = True
depth_processor = None
depth_model = None
gdino_processor = None
gdino_model = None
gdino_active_id = GDINO_PRIMARY_ID
sam_processor = None
sam_model = None
sam_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, gdino_active_id
global sam_processor, sam_model, sam_active_id
device = "cuda" if torch.cuda.is_available() else "cpu"
if seg_model is None:
try:
seg_processor = AutoImageProcessor.from_pretrained(MASK2FORMER_ID)
seg_model = (
Mask2FormerForUniversalSegmentation.from_pretrained(MASK2FORMER_ID)
.to(device)
.eval()
)
seg_is_mask2former = True
except Exception:
seg_processor = AutoImageProcessor.from_pretrained(SEGFORMER_FALLBACK_ID)
seg_model = (
AutoModelForSemanticSegmentation.from_pretrained(SEGFORMER_FALLBACK_ID)
.to(device)
.eval()
)
seg_is_mask2former = False
if depth_model is None:
depth_processor = AutoImageProcessor.from_pretrained(DEPTH_METRIC_ID)
depth_model = (
AutoModelForDepthEstimation.from_pretrained(DEPTH_METRIC_ID)
.to(device)
.eval()
)