Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files217 unmodified lines2182192202212222232242252262272282292302312322332341 unmodified line2362372382392402412422432442455 unmodified lines2512522532542552562572582592602612622633 unmodified lines2672682692702712722732742752762779 unmodified lines2872882892902912922939 unmodified lines3033043053063073083093103116 unmodified lines31831932032132232332432532632732832933033133233333474 unmodified lines40941041141241341441513 unmodified lines42943043143243343443552 unmodified lines48848949049149249349427 unmodified lines52252352452552652752817 unmodified lines54654754854955055155210 unmodified lines56356456556656756856957057157257357457525 unmodified lines6016026036046056066072 unmodified lines61061161261361461561621 unmodified lines63863964064164264364428 unmodified lines67367467567667767867968068168268314 unmodified lines698699700701702703704217 unmodified linesdef compute_foreshortening(plane_mask, depth_norm, px_per_ft, ref_depth):"""Estimate perspective obliquity (sec theta) from horizontal depth gradient."""ys, xs = np.where(plane_mask > 0)if len(ys) < 100 or px_per_ft <= 1e-3:return 1.0, 0.0# Relative metric depth Z (in arbitrary units anchored to ref_depth = 1.0)d_vals = np.maximum(depth_norm[ys, xs].astype(np.float32), 25.0)z_rel = ref_depth / d_valsz_med = float(np.median(z_rel))# Fit linear slope dZ / dx_px across the wall's horizontal spanx_mean = float(np.mean(xs))z_mean = float(np.mean(z_rel))denom = float(np.sum((xs - x_mean) ** 2))1 unmodified linereturn 1.0, 0.0dz_dx_px = abs(float(np.sum((xs - x_mean) * (z_rel - z_mean))) / denom)# Approximate camera focal length in pixels (~0.85 * image width for typical interiors)h, w = plane_mask.shapefocal_px = 0.85 * float(max(h, w))# tan(theta) = (dZ/dx_px) * (focal_px / Z_med)tan_theta = (dz_dx_px * focal_px) / max(z_med, 0.25)sec_theta = float(np.clip(np.sqrt(1.0 + tan_theta * tan_theta), 1.0, 2.25))angle_deg = float(np.degrees(np.arccos(1.0 / sec_theta)))5 unmodified linesif len(ys) == 0 or px_per_ft <= 1e-3:return 0.0d_vals = np.maximum(depth_norm[ys, xs].astype(np.float32), 25.0)rel_scale = np.clip(ref_depth / d_vals, 0.6, 1.8)ft_per_px = (1.0 / px_per_ft) * rel_scalereturn float(np.sum(ft_per_px * ft_per_px)) * float(foreshortening)def estimate_gross_floor_mask(floor_mask, floor_furniture_mask, wall_mask):"""Reconstruct occluded floor footprint below the wall-floor horizon."""h, w = floor_mask.shapefloor_ys = np.where(floor_mask > 0)[0]if len(floor_ys) == 0:3 unmodified linesvalid_zone = np.zeros((h, w), np.uint8)valid_zone[horizon_y:, :] = 255# Include floor + furniture resting on the floor below the wall-floor horizoncombined = cv2.bitwise_or(floor_mask, cv2.bitwise_and(floor_furniture_mask, valid_zone))# Exclude upper wall pixels so the hull doesn't climb up wallscombined = cv2.bitwise_and(combined, cv2.bitwise_not(wall_mask))pts = cv2.findNonZero(combined)9 unmodified linesdef calibrate_scale(masks, door_mask, depth_norm, cal_mode, ref_dim_ft, h, w):"""Calibrate pixels-per-foot and reference depth from Ceiling Height or Door Height."""if cal_mode == "Door Height (ft)" and np.count_nonzero(door_mask) > 400:num_l, labels, stats, _ = cv2.connectedComponentsWithStats(door_mask)best_lbl = 09 unmodified linespx_per_ft = max(door_h_px / ref_dim_ft, 5.0)d_vals = depth_norm[labels == best_lbl]ref_depth = max(float(np.median(d_vals)), 30.0) if len(d_vals) > 0 else 128.0return px_per_ft, ref_depth, f"Door Height ({ref_dim_ft:.1f} ft)"# Default / fallback: Ceiling Height anchored to full-height wall columnswall_cols = np.where(np.any(masks["wall"] > 0, axis=0))[0]col_heights = []full_col_depths = []6 unmodified linesfull_col_depths.append(float(np.median(depth_norm[ys, x])))median_wall_px = float(np.percentile(col_heights, 65)) if col_heights else h * 0.55px_per_ft = max(median_wall_px / ref_dim_ft, 5.0)if full_col_depths:ref_depth = max(float(np.median(full_col_depths)), 30.0)else:w_depths = depth_norm[masks["wall"] > 0]ref_depth = max(float(np.median(w_depths)), 30.0) if len(w_depths) > 0 else 128.0note = f"Ceiling Height ({ref_dim_ft:.1f} ft)"if cal_mode == "Door Height (ft)":note += " [no door detected, fallback]"return px_per_ft, ref_depth, notedef export_takeoff_files(payload, rows):74 unmodified lines"carpet", "ottoman", "armchair", "desk", "bench",)display_keywords = ("television", "tv", "screen", "monitor", "painting", "picture")all_clutter_keywords = opening_keywords + floor_furn_keywords + display_keywords + ("cushion", "pillow", "curtain", "drape")for cls_id in np.unique(pred_resized).tolist():cid = int(cls_id)13 unmodified linesif any(ck in lbl for ck in all_clutter_keywords):clutter_mask = cv2.bitwise_or(clutter_mask, m)# Suppress corners on furniture (9x9) and TV/display bezels (21x21)corner_block_mask = cv2.bitwise_or(cv2.dilate(clutter_mask, np.ones((9, 9), np.uint8)),cv2.dilate(display_mask, np.ones((21, 21), np.uint8)),52 unmodified linesedge_candidates, gray, junction_lines, min_len=min_l)px_per_ft, ref_depth, cal_label = calibrate_scale(masks, door_mask, depth_norm, cal_mode, ref_val, h, w)27 unmodified linesfor x1, y1, x2, y2 in clean_lines:cv2.line(overlay, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 255), 2)# Per-wall foreshortened Net & Gross area calculationclaimed_openings = np.zeros((h, w), np.uint8)plane_lines = []wall_records = []17 unmodified linesplane["mask"], depth_norm, px_per_ft, ref_depth, foreshortening=sec_theta)# Find openings/built-ins adjacent to or embedded inside this wall's envelopewall_zone = cv2.dilate(plane["mask"], np.ones((21, 21), np.uint8))local_openings = cv2.bitwise_and(wall_zone, openings_builtins_mask)local_openings = cv2.bitwise_and(10 unmodified linestotal_deduct_sqft += deduct_sqftcx, cy = plane["centroid"]tag = f"W{idx + 1}: {net_sqft:.0f} sf ({sec_theta:.2f}x)"cv2.putText(overlay, tag, (max(8, cx - 65), cy),cv2.FONT_HERSHEY_SIMPLEX, 0.52, (0, 0, 0), 3, cv2.LINE_AA)cv2.putText(overlay, tag, (max(8, cx - 65), cy),cv2.FONT_HERSHEY_SIMPLEX, 0.52, (255, 255, 255), 1, cv2.LINE_AA)25 unmodified linestotal_gross_wall_sqft = total_net_wall_sqft + total_deduct_sqft# Floor (Visible vs. Gross Occlusion-Compensated) & Ceilingvis_floor_sqft = estimate_area_sqft(masks["floor"], depth_norm, px_per_ft, ref_depth)gross_floor_mask = estimate_gross_floor_mask(masks["floor"], floor_furniture_mask, masks["wall"]2 unmodified linesceil_sqft = estimate_area_sqft(masks["ceiling"], depth_norm, px_per_ft, ref_depth)est_gross_floor_sqft = max(vis_floor_sqft, hull_floor_sqft, ceil_sqft * 0.95)# Detect clean structural cornersscored_corners = []for i in range(len(clean_lines)):for j in range(i + 1, len(clean_lines)):21 unmodified linescv2.circle(overlay, (px, py), 8, (255, 50, 80), -1)cv2.circle(overlay, (px, py), 10, (255, 255, 255), 2)# Add summary rows to CSV & JSONcsv_rows.extend([{"Surface": "Total Walls",28 unmodified lines])payload = {"pipeline_version": "v10","image_size_px": {"width": w, "height": h},"calibration": {"anchor": cal_label,"reference_ft": round(ref_val, 2),"px_per_ft": round(px_per_ft, 2),},"summary": {14 unmodified linestotal_px = h * wreport_lines = [f"Pipeline v10 — Foreshortened Net/Gross Area & Takeoff ({cal_label})",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 * 0.0929:.1f} sq.m)",f"Floor ({np.count_nonzero(masks['floor']) / total_px * 100:.1f}%): Visible ~{vis_floor_sqft:.1f} sq.ft | Est. Gross Footprint ~{est_gross_floor_sqft:.1f} sq.ft ({est_gross_floor_sqft * 0.0929:.1f} sq.m)",f"Ceiling ({np.count_nonzero(masks['ceiling']) / total_px * 100:.1f}%): Est. ~{ceil_sqft:.1f} sq.ft ({ceil_sqft * 0.0929:.1f} sq.m)",217 unmodified lines2182192202212222232242252262272282292302311 unmodified line2332342352362372382392405 unmodified lines2462472482492502512522532542552562572583 unmodified lines2622632642652662672682692709 unmodified lines2802812822832842859 unmodified lines2952962972982993003013023033043056 unmodified lines31231331431531631731831932032132232332432532632732874 unmodified lines40340440540640740840941041141241341413 unmodified lines42842943043143243352 unmodified lines48648748848949049149227 unmodified lines52052152252352452517 unmodified lines54354454554654754810 unmodified lines55956056156256356456556656756856957057157225 unmodified lines5985996006016026032 unmodified lines60660760860961061121 unmodified lines63363463563663763828 unmodified lines66766866967067167267367467567667714 unmodified lines692693694695696697698217 unmodified linesdef compute_foreshortening(plane_mask, depth_norm, px_per_ft, ref_depth):ys, xs = np.where(plane_mask > 0)if len(ys) < 100 or px_per_ft <= 1e-3:return 1.0, 0.0d_vals = np.maximum(depth_norm[ys, xs].astype(np.float32), 25.0)z_rel = ref_depth / d_valsz_med = float(np.median(z_rel))x_mean = float(np.mean(xs))z_mean = float(np.mean(z_rel))denom = float(np.sum((xs - x_mean) ** 2))1 unmodified linereturn 1.0, 0.0dz_dx_px = abs(float(np.sum((xs - x_mean) * (z_rel - z_mean))) / denom)h, w = plane_mask.shapefocal_px = 0.85 * float(max(h, w))tan_theta = (dz_dx_px * focal_px) / max(z_med, 0.25)sec_theta = float(np.clip(np.sqrt(1.0 + tan_theta * tan_theta), 1.0, 2.25))angle_deg = float(np.degrees(np.arccos(1.0 / sec_theta)))5 unmodified linesif len(ys) == 0 or px_per_ft <= 1e-3:return 0.0d_vals = np.maximum(depth_norm[ys, xs].astype(np.float32), 25.0)# Allow up to 3.2x perspective scaling for deep back walls, floors, and ceilingsrel_scale = np.clip(ref_depth / d_vals, 0.55, 3.2)ft_per_px = (1.0 / px_per_ft) * rel_scalereturn float(np.sum(ft_per_px * ft_per_px)) * float(foreshortening)def estimate_gross_floor_mask(floor_mask, floor_furniture_mask, wall_mask):h, w = floor_mask.shapefloor_ys = np.where(floor_mask > 0)[0]if len(floor_ys) == 0:3 unmodified linesvalid_zone = np.zeros((h, w), np.uint8)valid_zone[horizon_y:, :] = 255combined = cv2.bitwise_or(floor_mask, cv2.bitwise_and(floor_furniture_mask, valid_zone))combined = cv2.bitwise_and(combined, cv2.bitwise_not(wall_mask))pts = cv2.findNonZero(combined)9 unmodified linesdef calibrate_scale(masks, door_mask, depth_norm, cal_mode, ref_dim_ft, h, w):if cal_mode == "Door Height (ft)" and np.count_nonzero(door_mask) > 400:num_l, labels, stats, _ = cv2.connectedComponentsWithStats(door_mask)best_lbl = 09 unmodified linespx_per_ft = max(door_h_px / ref_dim_ft, 5.0)d_vals = depth_norm[labels == best_lbl]ref_depth = max(float(np.median(d_vals)), 30.0) if len(d_vals) > 0 else 128.0return px_per_ft, ref_depth, ref_dim_ft, f"Door Height ({ref_dim_ft:.1f} ft)"# If Door Height was selected but no door exists in the image, default ceiling height to 10.0 fteffective_ceil_ft = 10.0 if cal_mode == "Door Height (ft)" else ref_dim_ftwall_cols = np.where(np.any(masks["wall"] > 0, axis=0))[0]col_heights = []full_col_depths = []6 unmodified linesfull_col_depths.append(float(np.median(depth_norm[ys, x])))median_wall_px = float(np.percentile(col_heights, 65)) if col_heights else h * 0.55px_per_ft = max(median_wall_px / effective_ceil_ft, 5.0)if full_col_depths:ref_depth = max(float(np.median(full_col_depths)), 30.0)else:w_depths = depth_norm[masks["wall"] > 0]ref_depth = max(float(np.median(w_depths)), 30.0) if len(w_depths) > 0 else 128.0note = f"Ceiling Height ({effective_ceil_ft:.1f} ft)"if cal_mode == "Door Height (ft)":note += " [no door detected, defaulted to 10.0 ft]"return px_per_ft, ref_depth, effective_ceil_ft, notedef export_takeoff_files(payload, rows):74 unmodified lines"carpet", "ottoman", "armchair", "desk", "bench",)display_keywords = ("television", "tv", "screen", "monitor", "painting", "picture")all_clutter_keywords = (opening_keywords+ floor_furn_keywords+ display_keywords+ ("cushion", "pillow", "curtain", "drape"))for cls_id in np.unique(pred_resized).tolist():cid = int(cls_id)13 unmodified linesif any(ck in lbl for ck in all_clutter_keywords):clutter_mask = cv2.bitwise_or(clutter_mask, m)corner_block_mask = cv2.bitwise_or(cv2.dilate(clutter_mask, np.ones((9, 9), np.uint8)),cv2.dilate(display_mask, np.ones((21, 21), np.uint8)),52 unmodified linesedge_candidates, gray, junction_lines, min_len=min_l)px_per_ft, ref_depth, used_ft, cal_label = calibrate_scale(masks, door_mask, depth_norm, cal_mode, ref_val, h, w)27 unmodified linesfor x1, y1, x2, y2 in clean_lines:cv2.line(overlay, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 255), 2)claimed_openings = np.zeros((h, w), np.uint8)plane_lines = []wall_records = []17 unmodified linesplane["mask"], depth_norm, px_per_ft, ref_depth, foreshortening=sec_theta)wall_zone = cv2.dilate(plane["mask"], np.ones((21, 21), np.uint8))local_openings = cv2.bitwise_and(wall_zone, openings_builtins_mask)local_openings = cv2.bitwise_and(10 unmodified linestotal_deduct_sqft += deduct_sqftcx, cy = plane["centroid"]tx = max(8, cx - 65)tag = f"W{idx + 1}: {net_sqft:.0f} sf ({sec_theta:.2f}x)"cv2.putText(overlay, tag, (tx + 2, cy + 2),cv2.FONT_HERSHEY_SIMPLEX, 0.52, (0, 0, 0), 3, cv2.LINE_AA)cv2.putText(overlay, tag, (tx, cy),cv2.FONT_HERSHEY_SIMPLEX, 0.52, (255, 255, 255), 1, cv2.LINE_AA)25 unmodified linestotal_gross_wall_sqft = total_net_wall_sqft + total_deduct_sqftvis_floor_sqft = estimate_area_sqft(masks["floor"], depth_norm, px_per_ft, ref_depth)gross_floor_mask = estimate_gross_floor_mask(masks["floor"], floor_furniture_mask, masks["wall"]2 unmodified linesceil_sqft = estimate_area_sqft(masks["ceiling"], depth_norm, px_per_ft, ref_depth)est_gross_floor_sqft = max(vis_floor_sqft, hull_floor_sqft, ceil_sqft * 0.95)scored_corners = []for i in range(len(clean_lines)):for j in range(i + 1, len(clean_lines)):21 unmodified linescv2.circle(overlay, (px, py), 8, (255, 50, 80), -1)cv2.circle(overlay, (px, py), 10, (255, 255, 255), 2)csv_rows.extend([{"Surface": "Total Walls",28 unmodified lines])payload = {"pipeline_version": "v11","image_size_px": {"width": w, "height": h},"calibration": {"anchor": cal_label,"reference_ft": round(used_ft, 2),"px_per_ft": round(px_per_ft, 2),},"summary": {14 unmodified linestotal_px = h * wreport_lines = [f"Pipeline v11 — Foreshortened Net/Gross Area & Takeoff ({cal_label})",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 * 0.0929:.1f} sq.m)",f"Floor ({np.count_nonzero(masks['floor']) / total_px * 100:.1f}%): Visible ~{vis_floor_sqft:.1f} sq.ft | Est. Gross Footprint ~{est_gross_floor_sqft:.1f} sq.ft ({est_gross_floor_sqft * 0.0929:.1f} sq.m)",f"Ceiling ({np.count_nonzero(masks['ceiling']) / total_px * 100:.1f}%): Est. ~{ceil_sqft:.1f} sq.ft ({ceil_sqft * 0.0929:.1f} sq.m)",
app.py+23-29