Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files23 unmodified lines242526272829303132338 unmodified lines4243444546474849505152535455561 unmodified line5859606162636465666768697071727374757623 unmodified lines10010110210310410510610710810911011111211311411511611711811912012112212312416 unmodified lines1411421431441451461476 unmodified lines15415515615715815916016116216316412 unmodified lines17717817918018118223 unmodified linesdevice = "cuda" if torch.cuda.is_available() else "cpu"if seg_model is None:seg_processor = AutoImageProcessor.from_pretrained(SEG_MODEL_ID)seg_model = AutoModelForSemanticSegmentation.from_pretrained(SEG_MODEL_ID).to(device).eval()if depth_model is None:depth_processor = AutoImageProcessor.from_pretrained(DEPTH_MODEL_ID)depth_model = AutoModelForDepthEstimation.from_pretrained(DEPTH_MODEL_ID).to(device).eval()return seg_processor, seg_model, depth_processor, depth_model8 unmodified lineswith torch.inference_mode():s_logits = s_mod(**s_inputs).logitspred_map = s_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 {}return pred_map, id2label, d_preddef fit_structural_lines(edge_map, min_len=60):lines = cv2.HoughLinesP(edge_map,rho=1,theta=np.pi / 180,1 unmodified lineminLineLength=max(20, int(min_len)),maxLineGap=20,)return lines if lines is not None else []def line_intersection(l1, l2):x1, y1, x2, y2 = [float(v) for v in l1]x3, y3, x4, y4 = [float(v) for v in l2]p1 = np.cross([x1, y1, 1.0], [x2, y2, 1.0])p2 = np.cross([x3, y3, 1.0], [x4, y4, 1.0])pt = np.cross(p1, p2)if not np.all(np.isfinite(pt)) or abs(pt[2]) < 1e-6:return Noneix = pt[0] / pt[2]iy = pt[1] / pt[2]if not (np.isfinite(ix) and np.isfinite(iy)) or abs(ix) > 1e6 or abs(iy) > 1e6:return Nonereturn (int(round(ix)), int(round(iy)))23 unmodified linespred_map, id2label, d_pred = run_models(img_pil)pred_resized = cv2.resize(pred_map.astype(np.int32), (w, h), interpolation=cv2.INTER_NEAREST)masks = {"wall": np.zeros((h, w), np.uint8),"ceiling": np.zeros((h, w), np.uint8),"floor": np.zeros((h, w), np.uint8),}for cls_id in np.unique(pred_resized):lbl = str(id2label.get(int(cls_id), id2label.get(str(int(cls_id)), ""))).lower()m = (pred_resized == cls_id).astype(np.uint8) * 255for k in masks:if k in lbl:masks[k] = cv2.bitwise_or(masks[k], m)depth_raw = cv2.resize(np.asarray(d_pred, dtype=np.float32), (w, h), interpolation=cv2.INTER_CUBIC)depth_raw = np.nan_to_num(depth_raw, nan=0.0, posinf=0.0, neginf=0.0)depth_norm = cv2.normalize(depth_raw, None, 0, 255, cv2.NORM_MINMAX).astype(16 unmodified linesboundary_candidates, cv2.bitwise_and(depth_edges, wall_d))lines = fit_structural_lines(boundary_candidates, min_len=min(h, w) * 0.1)overlay = work_np.copy()overlay[masks["wall"] > 0] = (6 unmodified lines0.72 * overlay[masks["ceiling"] > 0] + 0.28 * np.array([255, 195, 70])).astype(np.uint8)clean_lines = []for l in lines:x1, y1, x2, y2 = [int(v) for v in l[0]]clean_lines.append((x1, y1, x2, y2))cv2.line(overlay, (x1, y1), (x2, y2), (0, 255, 255), 2)corners = []for i in range(len(clean_lines)):12 unmodified linestotal_px = h * wreport = (f"Wall Coverage: {np.count_nonzero(masks['wall']) / total_px * 100:.1f}%\n"f"Ceiling Coverage: {np.count_nonzero(masks['ceiling']) / total_px * 100:.1f}%\n"f"Floor Coverage: {np.count_nonzero(masks['floor']) / total_px * 100:.1f}%\n"23 unmodified lines2425262728293031323334353637383940418 unmodified lines50515253545556575859606162631 unmodified line65666768697071727374757677787980818283848586878823 unmodified lines11211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214316 unmodified lines1601611621631641651666 unmodified lines17317417517617717817918012 unmodified lines19319419519619719819923 unmodified linesdevice = "cuda" if torch.cuda.is_available() else "cpu"if seg_model is None:seg_processor = AutoImageProcessor.from_pretrained(SEG_MODEL_ID)seg_model = (AutoModelForSemanticSegmentation.from_pretrained(SEG_MODEL_ID).to(device).eval())if depth_model is None:depth_processor = AutoImageProcessor.from_pretrained(DEPTH_MODEL_ID)depth_model = (AutoModelForDepthEstimation.from_pretrained(DEPTH_MODEL_ID).to(device).eval())return seg_processor, seg_model, depth_processor, depth_model8 unmodified lineswith torch.inference_mode():s_logits = s_mod(**s_inputs).logitspred_map = s_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 {}return np.asarray(pred_map), id2label, np.asarray(d_pred, dtype=np.float32)def fit_structural_lines(edge_map, min_len=60):raw = cv2.HoughLinesP(edge_map,rho=1,theta=np.pi / 180,1 unmodified lineminLineLength=max(20, int(min_len)),maxLineGap=20,)if raw is None:return []arr = np.asarray(raw)if arr.size == 0 or arr.ndim < 3:return []return arr.reshape(-1, 4).tolist()def line_intersection(l1, l2):x1, y1, x2, y2 = float(l1[0]), float(l1[1]), float(l1[2]), float(l1[3])x3, y3, x4, y4 = float(l2[0]), float(l2[1]), float(l2[2]), float(l2[3])p1 = np.cross([x1, y1, 1.0], [x2, y2, 1.0])p2 = np.cross([x3, y3, 1.0], [x4, y4, 1.0])pt = np.cross(p1, p2)if not np.all(np.isfinite(pt)) or abs(float(pt[2])) < 1e-6:return Noneix = float(pt[0]) / float(pt[2])iy = float(pt[1]) / float(pt[2])if not (np.isfinite(ix) and np.isfinite(iy)) or abs(ix) > 1e6 or abs(iy) > 1e6:return Nonereturn (int(round(ix)), int(round(iy)))23 unmodified linespred_map, id2label, d_pred = run_models(img_pil)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),}unique_ids = np.unique(pred_resized).tolist()for cls_id in unique_ids:cid = int(cls_id)lbl = str(id2label.get(cid, id2label.get(str(cid), ""))).lower()m = (pred_resized == cid).astype(np.uint8) * 255for k in masks:if k in lbl:masks[k] = cv2.bitwise_or(masks[k], m)d_2d = np.squeeze(d_pred)if d_2d.ndim == 3:d_2d = d_2d[0]depth_raw = cv2.resize(d_2d.astype(np.float32), (w, h), interpolation=cv2.INTER_CUBIC)depth_raw = np.nan_to_num(depth_raw, nan=0.0, posinf=0.0, neginf=0.0)depth_norm = cv2.normalize(depth_raw, None, 0, 255, cv2.NORM_MINMAX).astype(16 unmodified linesboundary_candidates, cv2.bitwise_and(depth_edges, wall_d))clean_lines = fit_structural_lines(boundary_candidates, min_len=min(h, w) * 0.1)overlay = work_np.copy()overlay[masks["wall"] > 0] = (6 unmodified lines0.72 * overlay[masks["ceiling"] > 0] + 0.28 * np.array([255, 195, 70])).astype(np.uint8)for x1, y1, x2, y2 in clean_lines:cv2.line(overlay, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 255), 2)corners = []for i in range(len(clean_lines)):12 unmodified linestotal_px = h * wreport = (f"Pipeline v3 — Direct Logits\n"f"Wall Coverage: {np.count_nonzero(masks['wall']) / total_px * 100:.1f}%\n"f"Ceiling Coverage: {np.count_nonzero(masks['ceiling']) / total_px * 100:.1f}%\n"f"Floor Coverage: {np.count_nonzero(masks['floor']) / total_px * 100:.1f}%\n"
app.py+42-25