Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files31 unmodified lines32333435363738396 unmodified lines464748495051525354555657585924 unmodified lines84858687888990919293949596979899100101102103102 unmodified lines20620720820921021121214 unmodified lines2272282292302312322338 unmodified lines2422432442452462472482492502512522532542551 unmodified line2572582592602612622632642652667 unmodified lines27427527627727827928028128228328453 unmodified lines3383393403413423433443453463473483496 unmodified lines35635735835936036136216 unmodified lines37938038138238338438512 unmodified lines39839940040140240340431 unmodified lines43643743843944044144244375 unmodified lines519520521522523524525526124 unmodified lines65165265365465565665765871 unmodified lines73073173273373473573673773873974074114 unmodified lines7567577587597607612 unmodified lines7647657667677687697707717727737747757767777787 unmodified lines78678778878979079179279379479579679779879980080180280380480537 unmodified lines84384484584684784884920 unmodified lines870871872873874875876139 unmodified lines101610171018101910201021102245 unmodified lines106810691070107110721073107450 unmodified lines11251126112711281129113011311132113311341135113613 unmodified lines115011511152115311541155115673 unmodified lines123012311232123312341235123631 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"SAM1_MODEL_ID = "facebook/sam-vit-base"SQM_TO_SQFT = 10.76391046 unmodified linesdepth_model = Nonegdino_processor = Nonegdino_model = Nonesam_processor = Nonesam_model = Nonedef get_models():global seg_processor, seg_model, seg_is_mask2formerglobal depth_processor, depth_modelglobal gdino_processor, gdino_model, sam_processor, sam_modeldevice = "cuda" if torch.cuda.is_available() else "cpu"24 unmodified lines)if gdino_model is None:gdino_processor = AutoProcessor.from_pretrained(GDINO_MODEL_ID)gdino_model = (AutoModelForZeroShotObjectDetection.from_pretrained(GDINO_MODEL_ID).to(device).eval())if sam_model is None:if HAS_SAM2:sam_processor = Sam2Processor.from_pretrained(SAM2_MODEL_ID)sam_model = Sam2Model.from_pretrained(SAM2_MODEL_ID).to(device).eval()else:sam_processor = SamProcessor.from_pretrained(SAM1_MODEL_ID)sam_model = SamModel.from_pretrained(SAM1_MODEL_ID).to(device).eval()return (seg_processor,102 unmodified linesis_dup = Falsefor 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 linesreturn kept@spaces.GPU(duration=90)def run_models(img_pil, prompt_terms):(s_proc,8 unmodified lines) = get_models()device = next(s_mod.parameters()).devicew, h = img_pil.sizes_inputs = s_proc(images=img_pil, return_tensors="pt").to(device)d_inputs = d_proc(images=img_pil, return_tensors="pt").to(device)with torch.inference_mode():s_out = s_mod(**s_inputs)if is_m2f:pred_map = (s_proc.post_process_semantic_segmentation(s_out, target_sizes=[(h, w)])[0]1 unmodified line.cpu().numpy())else:pred_map = s_out.logits.argmax(dim=1).squeeze(0).detach().cpu().numpy()d_pred = d_mod(**d_inputs).predicted_depth.squeeze(0).detach().cpu().numpy()id2label = getattr(s_mod.config, "id2label", {}) or {}7 unmodified lineswith torch.inference_mode():g_outputs = g_mod(**g_inputs)# Raised threshold from 0.30 -> 0.42 to suppress false-positive windows on TV/fluted panelsg_res = g_proc.post_process_grounded_object_detection(g_outputs,g_inputs.input_ids,threshold=0.42,text_threshold=0.30,target_sizes=[(h, w)],)[0]53 unmodified linesid2label,np.asarray(d_pred, dtype=np.float32),detected_objects,"Mask2Former-Swin-Large" if is_m2f else "SegFormer-B2",)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.shapecx, cy = w * 0.5, h * 0.5u = np.arange(w, dtype=np.float32)[None, :]6 unmodified linesdef 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 linesdef 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_Mh, w = masks["wall"].shape12 unmodified linesf"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 bottomceil_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 linesreturn 1.0, "Pure Metric Depth (unscaled)"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."""h, w = wall_mask.shapemin_px = int(h * w * min_area_ratio)remaining = (wall_mask > 0).copy()75 unmodified lines)remaining[plane_mask > 0] = Falseplanes.sort(key=lambda p: p["centroid"][0])return planesdef compute_3d_surface_area_sqft(mask, z_3d, focal_px, cos_theta=None):124 unmodified linesdef 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")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_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 clutterfloor_surface_keywords = ("floor", "rug", "carpet")floor_furn_keywords = ("sofa", "couch", "bed", "table", "chair",14 unmodified linesdoor_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(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 linesif 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()for obj in detected_objs:if "window" in obj["label"]: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)if sem_overlap > 0.10 or obj["score"] >= 0.55:window_mask = cv2.bitwise_or(window_mask, om)sam_ignored_mask = np.zeros((h, w), np.uint8)sam_target_mask = np.zeros((h, w), np.uint8)7 unmodified linesif omask_px == 0:continue# Ignore non-window/non-curtain detections sitting predominantly inside window glassif (np.count_nonzero(window_mask) > 0and not any(wk in lbl for wk in ("window", "pane", "curtain", "drape"))):inside_win = int(np.count_nonzero(cv2.bitwise_and(omask, window_mask)))if inside_win / float(omask_px) > 0.60:continue# Semantic verification for SAM window/door openings to block ghost windows on TV panelsis_opening_lbl = any(sok in lbl for sok in structural_opening_keywords)verified_opening = Trueif is_opening_lbl: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 linesmasks["floor"], cv2.bitwise_not(sam_ignored_mask))# Resize metric depth (metres) and back-project to 3Dd_2d = np.squeeze(d_pred_m)if d_2d.ndim == 3:d_2d = d_2d[0]20 unmodified linescv2.applyColorMap(depth_vis, cv2.COLORMAP_INFERNO), cv2.COLOR_BGR2RGB)# 3D RANSAC Wall Plane Segmentationwall_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 linesmasks["ceiling"], z_3d, normals, focal_px)# When furniture covers >85% of floor, use 3D ceiling footprint as sanity anchorif 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 linesf" - [{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","models": {"segmentation": seg_name,"depth": DEPTH_METRIC_ID,"detection": GDINO_MODEL_ID,"mask_refinement": SAM2_MODEL_ID if HAS_SAM2 else SAM1_MODEL_ID,},"intrinsics": {"focal_px": round(focal_px, 1), "source": focal_src},"calibration": cal_label,13 unmodified linesjson_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"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 linesgr.File(label="Download JSON Report"),gr.File(label="Download CSV Takeoff"),],title="Smart Area v20 — 3D Metric Depth, Mask2Former & Verified BOQ Analyzer",)if __name__ == "__main__":31 unmodified lines323334353637383940416 unmodified lines484950515253545556575859606162636424 unmodified lines8990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125102 unmodified lines22822923023123223314 unmodified lines2482492502512522532548 unmodified lines2632642652662672682692702712722732742752762772782792802811 unmodified line2832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203217 unmodified lines32933033133233333433533633733853 unmodified lines3923933943953963973983994004014026 unmodified lines40941041141241341416 unmodified lines43143243343443543612 unmodified lines44945045145245345431 unmodified lines48648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852975 unmodified lines605606607608609610611124 unmodified lines73673773873974074174274371 unmodified lines81581681781881982082182282382482582682714 unmodified lines8428438448458468478488492 unmodified lines8528538548558568578588598608618628638648658668678687 unmodified lines87687787887988088188288388488588688788888989089189289389489589689789889990090137 unmodified lines93994094194294394420 unmodified lines965966967968969970139 unmodified lines11101111111211131114111545 unmodified lines11611162116311641165116650 unmodified lines12171218121912201221122212231224122512261227122813 unmodified lines124212431244124512461247124873 unmodified lines132213231324132513261327132831 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_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_IDdef get_models():global seg_processor, seg_model, seg_is_mask2formerglobal depth_processor, depth_modelglobal gdino_processor, gdino_model, gdino_active_idglobal sam_processor, sam_model, sam_active_iddevice = "cuda" if torch.cuda.is_available() else "cpu"24 unmodified lines)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_IDexcept 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_IDif 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_IDexcept 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_IDelse:sam_processor = SamProcessor.from_pretrained(SAM1_MODEL_ID)sam_model = SamModel.from_pretrained(SAM1_MODEL_ID).to(device).eval()sam_active_id = SAM1_MODEL_IDreturn (seg_processor,102 unmodified linesis_dup = Falsefor k in kept:same_cls = (cand["label"] == k["label"]or cand["label"] in k["label"]14 unmodified linesreturn kept@spaces.GPU(duration=120)def run_models(img_pil, prompt_terms):(s_proc,8 unmodified lines) = get_models()device = next(s_mod.parameters()).devicew, h = img_pil.sizeimg_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 segmentations_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]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 filterpred_map = pred_orig.copy()disagree = pred_orig != pred_flipif np.any(disagree):med = cv2.medianBlur(pred_orig.astype(np.uint8), 5)pred_map[disagree] = med[disagree]else:logits_orig = s_out.logitslogits_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_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 lineswith 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.40,text_threshold=0.30,target_sizes=[(h, w)],)[0]53 unmodified linesid2label,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.shapecx, cy = w * 0.5, h * 0.5u = np.arange(w, dtype=np.float32)[None, :]6 unmodified linesdef 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)16 unmodified linesdef calibrate_metric_scale(masks, door_mask, floor_zone_mask, y_3d, cal_mode, ref_dim_ft):ref_m = float(ref_dim_ft) * FT_TO_Mh, w = masks["wall"].shape12 unmodified linesf"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))31 unmodified linesreturn 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 planesmerged = []used = [False] * len(planes)for i in range(len(planes)):if used[i]:continuebase = 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]:continuen_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] = Truepy, px = np.where(base_mask > 0)base["mask"] = base_maskbase["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 mergeddef 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.shapemin_px = int(h * w * min_area_ratio)remaining = (wall_mask > 0).copy()75 unmodified lines)remaining[plane_mask > 0] = Falsereturn merge_coplanar_planes(planes, z_3d)def compute_3d_surface_area_sqft(mask, z_3d, focal_px, cos_theta=None):124 unmodified linesdef export_takeoff_files(payload, rows):tmp_dir = tempfile.gettempdir()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")reflective_keywords = ("window", "pane", "mirror", "wardrobe", "closet")floor_surface_keywords = ("floor", "rug", "carpet")floor_furn_keywords = ("sofa", "couch", "bed", "table", "chair",14 unmodified linesdoor_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 linesif any(fk in lbl for fk in floor_furn_keywords):floor_furniture_mask = cv2.bitwise_or(floor_furniture_mask, m)# Build verified reflective/glass mask (windows, mirrors, mirrored wardrobes)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.55: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 linesif omask_px == 0:continue# Suppress outdoor objects through windows AND reflections inside mirrors/wardrobesif (np.count_nonzero(reflective_mask) > 0and not any(wk in lblfor 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:continueis_opening_lbl = any(sok in lbl for sok in structural_opening_keywords)verified_opening = Trueif is_opening_lbl: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 linesmasks["floor"], cv2.bitwise_not(sam_ignored_mask))d_2d = np.squeeze(d_pred_m)if d_2d.ndim == 3:d_2d = d_2d[0]20 unmodified linescv2.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)139 unmodified linesmasks["ceiling"], z_3d, normals, focal_px)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 linesf" - [{role}] {obj['label']} ({obj['score']:.0%}): ~{obj_sqft:.1f} sq.ft (~{obj_z:.2f}m)")paintable_sqft = total_net_wall_sqft + (ceil_sqft if boq_cfg["include_ceiling_paint"] else 0.0)50 unmodified lines)payload = {"pipeline_version": "v21-tta-gdino-base-sam2-plus","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,13 unmodified linesjson_path, csv_path = export_takeoff_files(payload, csv_rows)report_lines = [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 linesgr.File(label="Download JSON Report"),gr.File(label="Download CSV Takeoff"),],title="Smart Area v21 — Flip-TTA, Grounding DINO Base, SAM 2.1 & 3D BOQ Analyzer",)if __name__ == "__main__":
app.py+144-52