diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -2,14 +2,14 @@ import asyncio import base64 import hashlib import io -import json -import os -import shutil -import time -import urllib.error -import urllib.parse -import urllib.request -import zipfile +import json +import os +import shutil +import time +import urllib.error +import urllib.parse +import urllib.request +import zipfile try: import tomllib except ImportError: @@ -22,21 +22,21 @@ except ImportError: raise ImportError( "No TOML library found. Please run on Python 3.11+, or run 'pip install tomli' to support Python 3.10." ) -import uuid -from pathlib import Path - -try: - from dotenv import load_dotenv -except ImportError: - load_dotenv = None - -import cv2 +import uuid +from pathlib import Path + +try: + from dotenv import load_dotenv +except ImportError: + load_dotenv = None + +import cv2 import numpy as np import torch -from fastapi import FastAPI, File, Form, HTTPException, Response, UploadFile, BackgroundTasks -from fastapi.middleware.cors import CORSMiddleware -from fastapi.middleware.gzip import GZipMiddleware -from fastapi.staticfiles import StaticFiles +from fastapi import FastAPI, File, Form, HTTPException, Response, UploadFile, BackgroundTasks +from fastapi.middleware.cors import CORSMiddleware +from fastapi.middleware.gzip import GZipMiddleware +from fastapi.staticfiles import StaticFiles from PIL import Image from transformers import ( AutoImageProcessor, @@ -46,10 +46,11 @@ from transformers import ( OneFormerProcessor, SegformerForSemanticSegmentation, ) -from floor_direction import ( - analyze_floor_direction as analyze_floor_direction_from_segmentation, - parse_floor_segmentation, -) +from floor_direction import ( + analyze_floor_direction as analyze_floor_direction_from_segmentation, + parse_floor_segmentation, +) +from direction_finder import find_floor_direction ADE20K_CLASSES = [ @@ -75,12 +76,12 @@ ADE20K_CLASSES = [ "vase", "traffic light", "tray", "ashcan", "fan", "pier", "crt screen", "plate", "monitor", "bulletin board", "shower", "radiator", "glass", "clock", "flag", -] - -if load_dotenv is not None: - load_dotenv(Path(__file__).resolve().parent / ".env") - -def load_config() -> dict: +] + +if load_dotenv is not None: + load_dotenv(Path(__file__).resolve().parent / ".env") + +def load_config() -> dict: config_path = os.getenv("VISUALIZER_CONFIG") if not config_path: return {} @@ -208,100 +209,100 @@ ENABLE_INTRINSIC_SHADING = str(config_value( "enable_intrinsic_shading", "0", )).lower() in {"1", "true", "yes", "on"} -ENABLE_SHADING_TRANSFER = str(config_value( - "ENABLE_SHADING_TRANSFER", - "runtime", - "enable_shading_transfer", - "1", -)).lower() in {"1", "true", "yes", "on"} -WARM_START_MODELS = str(config_value( - "WARM_START_MODELS", - "runtime", - "warm_start_models", - "1", -)).lower() in {"1", "true", "yes", "on"} -BUNDLE_IMAGE_FORMAT = str(config_value( - "BUNDLE_IMAGE_FORMAT", - "runtime", - "bundle_image_format", - "jpeg", -)).lower() -BUNDLE_IMAGE_QUALITY = int(config_value( - "BUNDLE_IMAGE_QUALITY", - "runtime", - "bundle_image_quality", - "92", -)) -DEBUG_ARTIFACTS_ENABLED = str(config_value( - "DEBUG_ARTIFACTS_ENABLED", - "runtime", - "debug_artifacts_enabled", - "1", -)).lower() in {"1", "true", "yes", "on"} -DEBUG_ARTIFACTS_MAX_DIMENSION = max(320, int(config_value( - "DEBUG_ARTIFACTS_MAX_DIMENSION", - "runtime", - "debug_artifacts_max_dimension", - "1600", -))) -DEBUG_ARTIFACTS_PREVIEW_DIMENSION = max(320, int(config_value( - "DEBUG_ARTIFACTS_PREVIEW_DIMENSION", - "runtime", - "debug_artifacts_preview_dimension", - "720", -))) -VISUALIZER_DATA_DIR = str(config_value( - "VISUALIZER_DATA_DIR", - "runtime", - "data_dir", - "data", -)) -SPACES_BUCKET = str(config_value( - "SPACES_BUCKET", - "spaces", - "bucket", - "", -)).strip() -SPACES_REGION = str(config_value( - "SPACES_REGION", - "spaces", - "region", - "", -)).strip() -SPACES_ENDPOINT_URL = str(config_value( - "SPACES_ENDPOINT_URL", - "spaces", - "endpoint_url", - "", -)).strip().rstrip("/") -SPACES_ACCESS_KEY_ID = str(config_value( - "SPACES_ACCESS_KEY_ID", - "spaces", - "access_key_id", - "", -)).strip() -SPACES_SECRET_ACCESS_KEY = str(config_value( - "SPACES_SECRET_ACCESS_KEY", - "spaces", - "secret_access_key", - "", -)).strip() -SPACES_UPLOAD_PREFIX = str(config_value( - "SPACES_UPLOAD_PREFIX", - "spaces", - "upload_prefix", - "room-uploads", -)).strip().strip("/") -SPACES_ACL = str(config_value( - "SPACES_ACL", - "spaces", - "acl", - "private", -)).strip() -GEMINI_API_KEY = str(config_value( - "GEMINI_API_KEY", - "gemini", - "api_key", +ENABLE_SHADING_TRANSFER = str(config_value( + "ENABLE_SHADING_TRANSFER", + "runtime", + "enable_shading_transfer", + "1", +)).lower() in {"1", "true", "yes", "on"} +WARM_START_MODELS = str(config_value( + "WARM_START_MODELS", + "runtime", + "warm_start_models", + "1", +)).lower() in {"1", "true", "yes", "on"} +BUNDLE_IMAGE_FORMAT = str(config_value( + "BUNDLE_IMAGE_FORMAT", + "runtime", + "bundle_image_format", + "jpeg", +)).lower() +BUNDLE_IMAGE_QUALITY = int(config_value( + "BUNDLE_IMAGE_QUALITY", + "runtime", + "bundle_image_quality", + "92", +)) +DEBUG_ARTIFACTS_ENABLED = str(config_value( + "DEBUG_ARTIFACTS_ENABLED", + "runtime", + "debug_artifacts_enabled", + "1", +)).lower() in {"1", "true", "yes", "on"} +DEBUG_ARTIFACTS_MAX_DIMENSION = max(320, int(config_value( + "DEBUG_ARTIFACTS_MAX_DIMENSION", + "runtime", + "debug_artifacts_max_dimension", + "1600", +))) +DEBUG_ARTIFACTS_PREVIEW_DIMENSION = max(320, int(config_value( + "DEBUG_ARTIFACTS_PREVIEW_DIMENSION", + "runtime", + "debug_artifacts_preview_dimension", + "720", +))) +VISUALIZER_DATA_DIR = str(config_value( + "VISUALIZER_DATA_DIR", + "runtime", + "data_dir", + "data", +)) +SPACES_BUCKET = str(config_value( + "SPACES_BUCKET", + "spaces", + "bucket", + "", +)).strip() +SPACES_REGION = str(config_value( + "SPACES_REGION", + "spaces", + "region", + "", +)).strip() +SPACES_ENDPOINT_URL = str(config_value( + "SPACES_ENDPOINT_URL", + "spaces", + "endpoint_url", + "", +)).strip().rstrip("/") +SPACES_ACCESS_KEY_ID = str(config_value( + "SPACES_ACCESS_KEY_ID", + "spaces", + "access_key_id", + "", +)).strip() +SPACES_SECRET_ACCESS_KEY = str(config_value( + "SPACES_SECRET_ACCESS_KEY", + "spaces", + "secret_access_key", + "", +)).strip() +SPACES_UPLOAD_PREFIX = str(config_value( + "SPACES_UPLOAD_PREFIX", + "spaces", + "upload_prefix", + "room-uploads", +)).strip().strip("/") +SPACES_ACL = str(config_value( + "SPACES_ACL", + "spaces", + "acl", + "private", +)).strip() +GEMINI_API_KEY = str(config_value( + "GEMINI_API_KEY", + "gemini", + "api_key", "", )).strip() GEMINI_IMAGE_MODEL = str(config_value( @@ -453,27 +454,27 @@ SHADE_MAP_MIN = 0.35 SHADE_MAP_MAX = 1.85 SHOWROOM_SHADE_MAP_MIN = 0.85 SHOWROOM_SHADE_MAP_MAX = 1.12 -REFLECTION_RELATIVE_FLOOR = 1.04 -REFLECTION_RELATIVE_CEILING = 1.95 -REFLECTION_MAP_MIN = 0.0 -REFLECTION_MAP_MAX = 1.0 +REFLECTION_RELATIVE_FLOOR = 1.04 +REFLECTION_RELATIVE_CEILING = 1.95 +REFLECTION_MAP_MIN = 0.0 +REFLECTION_MAP_MAX = 1.0 def hf_offline() -> bool: return os.getenv("HF_HUB_OFFLINE") == "1" or os.getenv("TRANSFORMERS_OFFLINE") == "1" -def _load_segmentation_model(): - global seg_processor, seg_model, segmentation_backend - - if seg_processor is not None and seg_model is not None: - return - - if SEGMENTATION_MODEL == "oneformer": - try: - print(f"Loading OneFormer: {ONEFORMER_MODEL_NAME} ...", flush=True) - seg_processor = OneFormerProcessor.from_pretrained( - ONEFORMER_MODEL_NAME, +def _load_segmentation_model(): + global seg_processor, seg_model, segmentation_backend + + if seg_processor is not None and seg_model is not None: + return + + if SEGMENTATION_MODEL == "oneformer": + try: + print(f"Loading OneFormer: {ONEFORMER_MODEL_NAME} ...", flush=True) + seg_processor = OneFormerProcessor.from_pretrained( + ONEFORMER_MODEL_NAME, local_files_only=hf_offline(), ) seg_model = OneFormerForUniversalSegmentation.from_pretrained( @@ -554,368 +555,414 @@ def _load_intrinsic_model(): from intrinsic.pipeline import load_models intrinsic_models = load_models(INTRINSIC_MODEL_VERSION, device=str(device)) print("Intrinsic model loaded.", flush=True) - except Exception as exc: - print(f"Intrinsic model failed to load ({exc}). Falling back to luminance shading.", flush=True) - - -def _load_depth_model() -> bool: - global depth_processor, depth_model - if not ENABLE_DEPTH_ESTIMATION: - return False - if depth_processor is not None and depth_model is not None: - return True - - print(f"Loading depth model: {DEPTH_MODEL_NAME} ...", flush=True) - depth_processor = AutoImageProcessor.from_pretrained( - DEPTH_MODEL_NAME, - local_files_only=hf_offline(), - ) - depth_model = AutoModelForDepthEstimation.from_pretrained( - DEPTH_MODEL_NAME, - local_files_only=hf_offline(), - ).to(device) - depth_model.eval() - print("Depth model loaded.", flush=True) - return True - - -def _load_moge_model() -> bool: - global moge_model - if not ENABLE_MOGE_GEOMETRY or GEOMETRY_MODEL != "moge" or device.type != "cuda": - return False - if moge_model is not None: - return True - - print(f"Loading MoGe geometry model: {MOGE_MODEL_NAME} ...", flush=True) - from moge.model.v2 import MoGeModel - moge_model = MoGeModel.from_pretrained(MOGE_MODEL_NAME).to(device) - moge_model.eval() - print("MoGe geometry model loaded.", flush=True) - return True - - -def warm_start_models(): - if not WARM_START_MODELS: - print("Model warm start disabled; models will load on first use.", flush=True) - return - - t_start = time.perf_counter() - print(f"Warm-starting visualizer models on {device} ...", flush=True) - - _load_segmentation_model() - - moge_loaded = False - if ENABLE_MOGE_GEOMETRY and GEOMETRY_MODEL == "moge": - try: - moge_loaded = _load_moge_model() - except Exception as exc: - print(f"MoGe warm start skipped ({exc}); depth fallback may be used.", flush=True) - if device.type == "cuda": - torch.cuda.empty_cache() - - if ENABLE_DEPTH_ESTIMATION and not moge_loaded: - try: - _load_depth_model() - except Exception as exc: - print(f"Depth model warm start skipped ({exc}); depth will be retried on first use.", flush=True) - if device.type == "cuda": - torch.cuda.empty_cache() - - if ENABLE_SAM_REFINEMENT: - _load_sam2_predictor() - - if ENABLE_SHADING_TRANSFER and ENABLE_INTRINSIC_SHADING: - _load_intrinsic_model() - - print(f"[TIMING] Model warm start took {time.perf_counter() - t_start:.3f} seconds", flush=True) - - -app = FastAPI() -app.add_middleware( - CORSMiddleware, - allow_origins=["*"], - allow_methods=["*"], - allow_headers=["*"], -) -app.add_middleware(GZipMiddleware, minimum_size=1024) - - -@app.on_event("startup") -def startup_warm_start_models(): - warm_start_models() - -DATA_DIR = Path(VISUALIZER_DATA_DIR).resolve() -UPLOAD_DIR = DATA_DIR / "uploads" -JOB_DIR = DATA_DIR / "jobs" -MATERIAL_DIR = DATA_DIR / "materials" + except Exception as exc: + print(f"Intrinsic model failed to load ({exc}). Falling back to luminance shading.", flush=True) + + +def _load_depth_model() -> bool: + global depth_processor, depth_model + if not ENABLE_DEPTH_ESTIMATION: + return False + if depth_processor is not None and depth_model is not None: + return True + + print(f"Loading depth model: {DEPTH_MODEL_NAME} ...", flush=True) + depth_processor = AutoImageProcessor.from_pretrained( + DEPTH_MODEL_NAME, + local_files_only=hf_offline(), + ) + depth_model = AutoModelForDepthEstimation.from_pretrained( + DEPTH_MODEL_NAME, + local_files_only=hf_offline(), + ).to(device) + depth_model.eval() + print("Depth model loaded.", flush=True) + return True + + +def _load_moge_model() -> bool: + global moge_model + if not ENABLE_MOGE_GEOMETRY or GEOMETRY_MODEL != "moge" or device.type != "cuda": + return False + if moge_model is not None: + return True + + print(f"Loading MoGe geometry model: {MOGE_MODEL_NAME} ...", flush=True) + from moge.model.v2 import MoGeModel + moge_model = MoGeModel.from_pretrained(MOGE_MODEL_NAME).to(device) + moge_model.eval() + print("MoGe geometry model loaded.", flush=True) + return True + + +def warm_start_models(): + if not WARM_START_MODELS: + print("Model warm start disabled; models will load on first use.", flush=True) + return + + t_start = time.perf_counter() + print(f"Warm-starting visualizer models on {device} ...", flush=True) + + _load_segmentation_model() + + moge_loaded = False + if ENABLE_MOGE_GEOMETRY and GEOMETRY_MODEL == "moge": + try: + moge_loaded = _load_moge_model() + except Exception as exc: + print(f"MoGe warm start skipped ({exc}); depth fallback may be used.", flush=True) + if device.type == "cuda": + torch.cuda.empty_cache() + + if ENABLE_DEPTH_ESTIMATION and not moge_loaded: + try: + _load_depth_model() + except Exception as exc: + print(f"Depth model warm start skipped ({exc}); depth will be retried on first use.", flush=True) + if device.type == "cuda": + torch.cuda.empty_cache() + + if ENABLE_SAM_REFINEMENT: + _load_sam2_predictor() + + if ENABLE_SHADING_TRANSFER and ENABLE_INTRINSIC_SHADING: + _load_intrinsic_model() + + print(f"[TIMING] Model warm start took {time.perf_counter() - t_start:.3f} seconds", flush=True) + + +app = FastAPI() +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_methods=["*"], + allow_headers=["*"], +) +app.add_middleware(GZipMiddleware, minimum_size=1024) + + +@app.on_event("startup") +def startup_warm_start_models(): + warm_start_models() + +DATA_DIR = Path(VISUALIZER_DATA_DIR).resolve() +UPLOAD_DIR = DATA_DIR / "uploads" +JOB_DIR = DATA_DIR / "jobs" +MATERIAL_DIR = DATA_DIR / "materials" UPLOAD_DIR.mkdir(parents=True, exist_ok=True) JOB_DIR.mkdir(parents=True, exist_ok=True) MATERIAL_DIR.mkdir(parents=True, exist_ok=True) -app.mount("/uploads", StaticFiles(directory=UPLOAD_DIR), name="uploads") - - -def _debug_resize_rgb(image_rgb: np.ndarray) -> np.ndarray: - height, width = image_rgb.shape[:2] - largest = max(height, width) - if largest <= DEBUG_ARTIFACTS_MAX_DIMENSION: - return image_rgb - scale = DEBUG_ARTIFACTS_MAX_DIMENSION / largest - return cv2.resize( - image_rgb, - (max(1, round(width * scale)), max(1, round(height * scale))), - interpolation=cv2.INTER_AREA, - ) - - -def _debug_preview_rgb(image_rgb: np.ndarray) -> np.ndarray: - height, width = image_rgb.shape[:2] - largest = max(height, width) - if largest <= DEBUG_ARTIFACTS_PREVIEW_DIMENSION: - return image_rgb - scale = DEBUG_ARTIFACTS_PREVIEW_DIMENSION / largest - return cv2.resize( - image_rgb, - (max(1, round(width * scale)), max(1, round(height * scale))), - interpolation=cv2.INTER_AREA, - ) - - -def debug_mask_overlay( - image_rgb: np.ndarray, - mask: np.ndarray, - color: tuple[int, int, int] = (45, 180, 255), -) -> np.ndarray: - """Overlay a binary analysis mask without changing the uploaded image.""" - output = image_rgb.copy() - valid = mask.astype(bool) - if valid.any(): - overlay = np.empty_like(output) - overlay[:] = color - output[valid] = cv2.addWeighted(output, 0.42, overlay, 0.58, 0)[valid] - return output - - -def debug_segmentation_overlay(image_rgb: np.ndarray, seg_map: np.ndarray) -> np.ndarray: - labels = seg_map.astype(np.int32) - hsv = np.zeros((*labels.shape, 3), dtype=np.uint8) - hsv[..., 0] = (labels * 37) % 180 - hsv[..., 1] = 180 - hsv[..., 2] = 255 - colors = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB) - return cv2.addWeighted(image_rgb, 0.42, colors, 0.58, 0) - - -def debug_scalar_map(values: np.ndarray, mask: np.ndarray | None = None) -> np.ndarray: - scalar = values.astype(np.float32) - finite = np.isfinite(scalar) - if mask is not None: - finite &= mask.astype(bool) - valid = scalar[finite] - if valid.size == 0: - return np.zeros((*scalar.shape[:2], 3), dtype=np.uint8) - low, high = np.percentile(valid, [2, 98]) - if high <= low: - high = low + 1.0 - normalized = np.clip((scalar - low) / (high - low), 0.0, 1.0) - normalized[~np.isfinite(normalized)] = 0.0 - output = cv2.applyColorMap(np.round(normalized * 255).astype(np.uint8), cv2.COLORMAP_TURBO) - output = cv2.cvtColor(output, cv2.COLOR_BGR2RGB) - if mask is not None: - output[~mask.astype(bool)] = 0 - return output - - -def debug_plane_overlay(image_rgb: np.ndarray, plane: dict | None) -> np.ndarray: - output = image_rgb.copy() - if not plane: - return output - raw_quad = plane.get("quad") - if not isinstance(raw_quad, list) or len(raw_quad) != 8: - return output - points = np.asarray(raw_quad, dtype=np.float32).reshape(-1, 2) - if not np.isfinite(points).all(): - return output - points_i = np.round(points).astype(np.int32) - overlay = output.copy() - cv2.fillConvexPoly(overlay, points_i, (45, 180, 255)) - output = cv2.addWeighted(output, 0.64, overlay, 0.36, 0) - cv2.polylines(output, [points_i], isClosed=True, color=(255, 255, 255), thickness=3, lineType=cv2.LINE_AA) - return output - - -def debug_surface_overlay(image_rgb: np.ndarray, floor_mask: np.ndarray, surface_mask: np.ndarray) -> np.ndarray: +app.mount("/uploads", StaticFiles(directory=UPLOAD_DIR), name="uploads") + + +def _debug_resize_rgb(image_rgb: np.ndarray) -> np.ndarray: + height, width = image_rgb.shape[:2] + largest = max(height, width) + if largest <= DEBUG_ARTIFACTS_MAX_DIMENSION: + return image_rgb + scale = DEBUG_ARTIFACTS_MAX_DIMENSION / largest + return cv2.resize( + image_rgb, + (max(1, round(width * scale)), max(1, round(height * scale))), + interpolation=cv2.INTER_AREA, + ) + + +def _debug_preview_rgb(image_rgb: np.ndarray) -> np.ndarray: + height, width = image_rgb.shape[:2] + largest = max(height, width) + if largest <= DEBUG_ARTIFACTS_PREVIEW_DIMENSION: + return image_rgb + scale = DEBUG_ARTIFACTS_PREVIEW_DIMENSION / largest + return cv2.resize( + image_rgb, + (max(1, round(width * scale)), max(1, round(height * scale))), + interpolation=cv2.INTER_AREA, + ) + + +def debug_mask_overlay( + image_rgb: np.ndarray, + mask: np.ndarray, + color: tuple[int, int, int] = (45, 180, 255), +) -> np.ndarray: + """Overlay a binary analysis mask without changing the uploaded image.""" + output = image_rgb.copy() + valid = mask.astype(bool) + if valid.any(): + overlay = np.empty_like(output) + overlay[:] = color + output[valid] = cv2.addWeighted(output, 0.42, overlay, 0.58, 0)[valid] + return output + + +def debug_segmentation_overlay(image_rgb: np.ndarray, seg_map: np.ndarray) -> np.ndarray: + labels = seg_map.astype(np.int32) + hsv = np.zeros((*labels.shape, 3), dtype=np.uint8) + hsv[..., 0] = (labels * 37) % 180 + hsv[..., 1] = 180 + hsv[..., 2] = 255 + colors = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB) + return cv2.addWeighted(image_rgb, 0.42, colors, 0.58, 0) + + +def debug_scalar_map(values: np.ndarray, mask: np.ndarray | None = None) -> np.ndarray: + scalar = values.astype(np.float32) + finite = np.isfinite(scalar) + if mask is not None: + finite &= mask.astype(bool) + valid = scalar[finite] + if valid.size == 0: + return np.zeros((*scalar.shape[:2], 3), dtype=np.uint8) + low, high = np.percentile(valid, [2, 98]) + if high <= low: + high = low + 1.0 + normalized = np.clip((scalar - low) / (high - low), 0.0, 1.0) + normalized[~np.isfinite(normalized)] = 0.0 + output = cv2.applyColorMap(np.round(normalized * 255).astype(np.uint8), cv2.COLORMAP_TURBO) + output = cv2.cvtColor(output, cv2.COLOR_BGR2RGB) + if mask is not None: + output[~mask.astype(bool)] = 0 + return output + + +def debug_plane_overlay(image_rgb: np.ndarray, plane: dict | None) -> np.ndarray: + output = image_rgb.copy() + if not plane: + return output + raw_quad = plane.get("quad") + if not isinstance(raw_quad, list) or len(raw_quad) != 8: + return output + points = np.asarray(raw_quad, dtype=np.float32).reshape(-1, 2) + if not np.isfinite(points).all(): + return output + points_i = np.round(points).astype(np.int32) + overlay = output.copy() + cv2.fillConvexPoly(overlay, points_i, (45, 180, 255)) + output = cv2.addWeighted(output, 0.64, overlay, 0.36, 0) + cv2.polylines(output, [points_i], isClosed=True, color=(255, 255, 255), thickness=3, lineType=cv2.LINE_AA) + return output + + +def debug_surface_overlay(image_rgb: np.ndarray, floor_mask: np.ndarray, surface_mask: np.ndarray) -> np.ndarray: + output = image_rgb.copy() + removed = (floor_mask > 0) & (surface_mask == 0) + if removed.any(): + red = np.empty_like(output) + red[:] = (220, 80, 80) + output[removed] = cv2.addWeighted(output, 0.42, red, 0.58, 0)[removed] + return debug_mask_overlay(output, surface_mask, (45, 180, 255)) + + +def debug_floor_direction_overlay(image_rgb: np.ndarray, floor_direction: dict) -> np.ndarray: output = image_rgb.copy() - removed = (floor_mask > 0) & (surface_mask == 0) - if removed.any(): - red = np.empty_like(output) - red[:] = (220, 80, 80) - output[removed] = cv2.addWeighted(output, 0.42, red, 0.58, 0)[removed] - return debug_mask_overlay(output, surface_mask, (45, 180, 255)) + direction_axis = floor_direction.get("directionAxis") + if isinstance(direction_axis, dict): + try: + start = ( + round(float(direction_axis["startX"])), + round(float(direction_axis["startY"])), + ) + end = ( + round(float(direction_axis["endX"])), + round(float(direction_axis["endY"])), + ) + cv2.arrowedLine( + output, + start, + end, + (45, 180, 255), + 4, + cv2.LINE_AA, + tipLength=0.08, + ) + except (KeyError, TypeError, ValueError): + pass + geometry_axis = floor_direction.get("geometryAxis") + if isinstance(geometry_axis, dict): + try: + start = ( + round(float(geometry_axis["nearX"])), + round(float(geometry_axis["nearY"])), + ) + end = ( + round(float(geometry_axis["farX"])), + round(float(geometry_axis["farY"])), + ) + cv2.arrowedLine( + output, + start, + end, + (45, 180, 255), + 4, + cv2.LINE_AA, + tipLength=0.08, + ) + except (KeyError, TypeError, ValueError): + pass -def debug_floor_direction_overlay(image_rgb: np.ndarray, floor_direction: dict) -> np.ndarray: - output = image_rgb.copy() for line in floor_direction.get("dominantLines") or []: try: start = (round(float(line["x1"])), round(float(line["y1"]))) end = (round(float(line["x2"])), round(float(line["y2"]))) except (KeyError, TypeError, ValueError): - continue - cv2.line(output, start, end, (45, 180, 255), 3, cv2.LINE_AA) - - label = floor_direction.get("directionLabel") or "unknown" - angle = floor_direction.get("renderAngleDegrees") - confidence = floor_direction.get("confidence") - detail = f"{label}" - if isinstance(angle, (int, float)): - detail += f" {angle:.1f} deg" - if isinstance(confidence, (int, float)): - detail += f" {confidence:.0%}" - cv2.putText(output, detail, (16, 34), cv2.FONT_HERSHEY_SIMPLEX, 0.72, (255, 255, 255), 3, cv2.LINE_AA) - cv2.putText(output, detail, (16, 34), cv2.FONT_HERSHEY_SIMPLEX, 0.72, (25, 25, 25), 1, cv2.LINE_AA) - return output - - -def debug_uv_checkerboard( - height: int, - width: int, - surface_indices: np.ndarray, - uv: np.ndarray, -) -> np.ndarray: - output = np.zeros((height, width, 3), dtype=np.uint8) - valid = np.isfinite(uv).all(axis=1) - if not valid.any(): - return output - coords = uv[valid] - cells = (np.floor(coords[:, 0] * 8) + np.floor(coords[:, 1] * 8)).astype(np.int32) - colors = np.where((cells % 2)[:, None] == 0, np.array([45, 180, 255]), np.array([45, 80, 180])) - output.reshape(-1, 3)[surface_indices[valid]] = colors.astype(np.uint8) - return output - - -def debug_plane_id_map( - height: int, - width: int, - surface_indices: np.ndarray, - plane_ids: np.ndarray, -) -> np.ndarray: - output = np.zeros((height, width, 3), dtype=np.uint8) - valid = plane_ids >= 0 - if not valid.any(): - return output - ids = plane_ids[valid].astype(np.int32) - hsv = np.zeros((len(ids), 1, 3), dtype=np.uint8) - hsv[:, 0, 0] = (ids * 47) % 180 - hsv[:, 0, 1] = 190 - hsv[:, 0, 2] = 255 - output.reshape(-1, 3)[surface_indices[valid]] = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB).reshape(-1, 3) - return output - - -def _debug_json_default(value): - if isinstance(value, np.generic): - return value.item() - if isinstance(value, np.ndarray): - return value.tolist() - raise TypeError(f"Unsupported debug manifest value: {type(value).__name__}") - - -class PipelineDebugCapture: - """Writes a generic, versioned inspection manifest alongside a conversion job.""" - - def __init__(self, job_id: str): - self.job_id = job_id - self.root = JOB_DIR / f"{job_id}.debug" - self.root.mkdir(parents=True, exist_ok=True) - self.manifest_path = self.root / "manifest.json" - self.manifest = { - "schemaVersion": 2, - "jobId": job_id, - "status": "PROCESSING", - "stages": [], - } - self._write_manifest() - - def _write_manifest(self): - self.manifest["updatedAtMs"] = int(time.time() * 1000) - self.manifest_path.write_text( - json.dumps(self.manifest, separators=(",", ":"), default=_debug_json_default), - encoding="utf-8", - ) - - def record_images( - self, - stage_id: str, - title: str, - description: str, - images: list[tuple[str, np.ndarray]], - metrics: dict | None = None, - elapsed_ms: float | None = None, - ): - if not DEBUG_ARTIFACTS_ENABLED: - return - try: - artifacts = [] - for index, (label, image_rgb) in enumerate(images): - filename = f"{len(self.manifest['stages']) + 1:02d}-{stage_id}-{index + 1}.jpg" - image_rgb = _debug_resize_rgb(image_rgb) - ok, encoded = cv2.imencode(".jpg", cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR), [cv2.IMWRITE_JPEG_QUALITY, 90]) - if not ok: - continue - (self.root / filename).write_bytes(encoded.tobytes()) - preview_filename = f"{filename[:-4]}.preview.jpg" - preview_rgb = _debug_preview_rgb(image_rgb) - preview_ok, preview_encoded = cv2.imencode( - ".jpg", - cv2.cvtColor(preview_rgb, cv2.COLOR_RGB2BGR), - [cv2.IMWRITE_JPEG_QUALITY, 82], - ) - if preview_ok: - (self.root / preview_filename).write_bytes(preview_encoded.tobytes()) - artifacts.append({ - "type": "image", - "label": label, - "url": f"/viz2d/jobs/{self.job_id}/debug/assets/{filename}", - "previewUrl": ( - f"/viz2d/jobs/{self.job_id}/debug/assets/{preview_filename}" - if preview_ok else None - ), - }) - stage = { - "id": stage_id, - "title": title, - "description": description, - "artifacts": artifacts, - "metrics": metrics or {}, - } - if elapsed_ms is not None: - stage["elapsedMs"] = round(float(elapsed_ms), 1) - self.manifest["stages"].append(stage) - self._write_manifest() - except Exception as exc: - print(f"[DEBUG] Could not capture {stage_id} for job {self.job_id}: {exc}", flush=True) - - def complete(self, total_elapsed_ms: float): - if not DEBUG_ARTIFACTS_ENABLED: - return - self.manifest["status"] = "COMPLETED" - self.manifest["totalElapsedMs"] = round(float(total_elapsed_ms), 1) - self._write_manifest() - - def fail(self, error: Exception): - if not DEBUG_ARTIFACTS_ENABLED: - return - self.manifest["status"] = "FAILED" - self.manifest["error"] = str(error) - self._write_manifest() - -PRIMARY_FLOOR_CLASSES = {"floor"} -FLOOR_SURFACE_CLASSES = { - "floor", "road", "sidewalk", "ground", "field", "grass", "sand", - "runway", "dirt track", "land", "stairs", "step", -} -REJECT_SURFACE_CLASSES = {"wall", "ceiling", "building", "sky", "window"} -SOFT_FLOOR_COVERING_CLASSES = {"rug", "carpet"} + continue + cv2.line(output, start, end, (45, 180, 255), 3, cv2.LINE_AA) + + label = floor_direction.get("directionLabel") or "unknown" + angle = floor_direction.get("renderAngleDegrees") + confidence = floor_direction.get("confidence") + detail = f"{label}" + if isinstance(angle, (int, float)): + detail += f" {angle:.1f} deg" + if isinstance(confidence, (int, float)): + detail += f" {confidence:.0%}" + cv2.putText(output, detail, (16, 34), cv2.FONT_HERSHEY_SIMPLEX, 0.72, (255, 255, 255), 3, cv2.LINE_AA) + cv2.putText(output, detail, (16, 34), cv2.FONT_HERSHEY_SIMPLEX, 0.72, (25, 25, 25), 1, cv2.LINE_AA) + return output + + +def debug_uv_checkerboard( + height: int, + width: int, + surface_indices: np.ndarray, + uv: np.ndarray, +) -> np.ndarray: + output = np.zeros((height, width, 3), dtype=np.uint8) + valid = np.isfinite(uv).all(axis=1) + if not valid.any(): + return output + coords = uv[valid] + cells = (np.floor(coords[:, 0] * 8) + np.floor(coords[:, 1] * 8)).astype(np.int32) + colors = np.where((cells % 2)[:, None] == 0, np.array([45, 180, 255]), np.array([45, 80, 180])) + output.reshape(-1, 3)[surface_indices[valid]] = colors.astype(np.uint8) + return output + + +def debug_plane_id_map( + height: int, + width: int, + surface_indices: np.ndarray, + plane_ids: np.ndarray, +) -> np.ndarray: + output = np.zeros((height, width, 3), dtype=np.uint8) + valid = plane_ids >= 0 + if not valid.any(): + return output + ids = plane_ids[valid].astype(np.int32) + hsv = np.zeros((len(ids), 1, 3), dtype=np.uint8) + hsv[:, 0, 0] = (ids * 47) % 180 + hsv[:, 0, 1] = 190 + hsv[:, 0, 2] = 255 + output.reshape(-1, 3)[surface_indices[valid]] = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB).reshape(-1, 3) + return output + + +def _debug_json_default(value): + if isinstance(value, np.generic): + return value.item() + if isinstance(value, np.ndarray): + return value.tolist() + raise TypeError(f"Unsupported debug manifest value: {type(value).__name__}") + + +class PipelineDebugCapture: + """Writes a generic, versioned inspection manifest alongside a conversion job.""" + + def __init__(self, job_id: str): + self.job_id = job_id + self.root = JOB_DIR / f"{job_id}.debug" + self.root.mkdir(parents=True, exist_ok=True) + self.manifest_path = self.root / "manifest.json" + self.manifest = { + "schemaVersion": 2, + "jobId": job_id, + "status": "PROCESSING", + "stages": [], + } + self._write_manifest() + + def _write_manifest(self): + self.manifest["updatedAtMs"] = int(time.time() * 1000) + self.manifest_path.write_text( + json.dumps(self.manifest, separators=(",", ":"), default=_debug_json_default), + encoding="utf-8", + ) + + def record_images( + self, + stage_id: str, + title: str, + description: str, + images: list[tuple[str, np.ndarray]], + metrics: dict | None = None, + elapsed_ms: float | None = None, + ): + if not DEBUG_ARTIFACTS_ENABLED: + return + try: + artifacts = [] + for index, (label, image_rgb) in enumerate(images): + filename = f"{len(self.manifest['stages']) + 1:02d}-{stage_id}-{index + 1}.jpg" + image_rgb = _debug_resize_rgb(image_rgb) + ok, encoded = cv2.imencode(".jpg", cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR), [cv2.IMWRITE_JPEG_QUALITY, 90]) + if not ok: + continue + (self.root / filename).write_bytes(encoded.tobytes()) + preview_filename = f"{filename[:-4]}.preview.jpg" + preview_rgb = _debug_preview_rgb(image_rgb) + preview_ok, preview_encoded = cv2.imencode( + ".jpg", + cv2.cvtColor(preview_rgb, cv2.COLOR_RGB2BGR), + [cv2.IMWRITE_JPEG_QUALITY, 82], + ) + if preview_ok: + (self.root / preview_filename).write_bytes(preview_encoded.tobytes()) + artifacts.append({ + "type": "image", + "label": label, + "url": f"/viz2d/jobs/{self.job_id}/debug/assets/{filename}", + "previewUrl": ( + f"/viz2d/jobs/{self.job_id}/debug/assets/{preview_filename}" + if preview_ok else None + ), + }) + stage = { + "id": stage_id, + "title": title, + "description": description, + "artifacts": artifacts, + "metrics": metrics or {}, + } + if elapsed_ms is not None: + stage["elapsedMs"] = round(float(elapsed_ms), 1) + self.manifest["stages"].append(stage) + self._write_manifest() + except Exception as exc: + print(f"[DEBUG] Could not capture {stage_id} for job {self.job_id}: {exc}", flush=True) + + def complete(self, total_elapsed_ms: float): + if not DEBUG_ARTIFACTS_ENABLED: + return + self.manifest["status"] = "COMPLETED" + self.manifest["totalElapsedMs"] = round(float(total_elapsed_ms), 1) + self._write_manifest() + + def fail(self, error: Exception): + if not DEBUG_ARTIFACTS_ENABLED: + return + self.manifest["status"] = "FAILED" + self.manifest["error"] = str(error) + self._write_manifest() + +PRIMARY_FLOOR_CLASSES = {"floor", "rug", "carpet", "mat"} +FLOOR_SURFACE_CLASSES = { + "floor", "road", "sidewalk", "ground", "field", "grass", "sand", + "runway", "dirt track", "land", "stairs", "step", "rug", "carpet", "mat", +} +REJECT_SURFACE_CLASSES = {"wall", "ceiling", "building", "sky", "window"} +SOFT_FLOOR_COVERING_CLASSES = set() OCCLUDER_CLASSES = { "bed", "cabinet", "person", "door", "table", "plant", "curtain", "chair", "car", "painting", "sofa", "shelf", "mirror", "armchair", "seat", "desk", @@ -938,54 +985,54 @@ def class_ids(names: set[str]) -> list[int]: return [idx for idx, name in enumerate(ADE20K_CLASSES) if name in names] -def estimate_depth(img: Image.Image, width: int, height: int): - if not ENABLE_DEPTH_ESTIMATION: - return None - - try: - if not _load_depth_model(): - return None - - inputs = depth_processor(images=img, return_tensors="pt").to(device) - with torch.no_grad(): - outputs = depth_model(**inputs) +def estimate_depth(img: Image.Image, width: int, height: int): + if not ENABLE_DEPTH_ESTIMATION: + return None + + try: + if not _load_depth_model(): + return None + + inputs = depth_processor(images=img, return_tensors="pt").to(device) + with torch.no_grad(): + outputs = depth_model(**inputs) depth = torch.nn.functional.interpolate( outputs.predicted_depth.unsqueeze(1), size=(height, width), mode="bicubic", align_corners=False, - ).squeeze().cpu().numpy() - depth = cv2.GaussianBlur(depth.astype(np.float32), (0, 0), sigmaX=3) - if "metric" in DEPTH_MODEL_NAME.lower(): - return depth - depth_min, depth_max = float(np.min(depth)), float(np.max(depth)) - if depth_max - depth_min < 1e-6: - return None + ).squeeze().cpu().numpy() + depth = cv2.GaussianBlur(depth.astype(np.float32), (0, 0), sigmaX=3) + if "metric" in DEPTH_MODEL_NAME.lower(): + return depth + depth_min, depth_max = float(np.min(depth)), float(np.max(depth)) + if depth_max - depth_min < 1e-6: + return None return (depth - depth_min) / (depth_max - depth_min) except Exception as exc: print(f"Depth estimation skipped ({exc}).", flush=True) return None -def _to_numpy(value): - if value is None: - return None - if isinstance(value, torch.Tensor): - return value.detach().float().cpu().numpy() - return np.asarray(value) - - -def estimate_moge_geometry(img_np: np.ndarray): - if not ENABLE_MOGE_GEOMETRY or GEOMETRY_MODEL != "moge" or device.type != "cuda": +def _to_numpy(value): + if value is None: return None + if isinstance(value, torch.Tensor): + return value.detach().float().cpu().numpy() + return np.asarray(value) - try: - if not _load_moge_model(): - return None - image_tensor = torch.from_numpy(img_np.astype(np.float32) / 255.0).permute(2, 0, 1).to(device) - with torch.inference_mode(), torch.autocast(device_type="cuda", dtype=torch.float16): - output = moge_model.infer(image_tensor) +def estimate_moge_geometry(img_np: np.ndarray): + if not ENABLE_MOGE_GEOMETRY or GEOMETRY_MODEL != "moge" or device.type != "cuda": + return None + + try: + if not _load_moge_model(): + return None + + image_tensor = torch.from_numpy(img_np.astype(np.float32) / 255.0).permute(2, 0, 1).to(device) + with torch.inference_mode(), torch.autocast(device_type="cuda", dtype=torch.float16): + output = moge_model.infer(image_tensor) points = _to_numpy(output.get("points")) depth = _to_numpy(output.get("depth")) @@ -1290,7 +1337,7 @@ def build_showroom_shade_map_from_luminance( return build_showroom_shade_map_from_relative(relative, surface_mask) -def build_reflection_map( +def build_reflection_map( img_np: np.ndarray, surface_mask: np.ndarray, relative_shading: np.ndarray | None = None, @@ -1300,7 +1347,7 @@ def build_reflection_map( mask = surface_mask.astype(np.uint8) h, w = mask.shape[:2] - reflection_candidates: list[np.ndarray] = [] + reflection_candidates: list[np.ndarray] = [] if relative_shading is not None: rel = relative_shading.astype(np.float32).copy() @@ -1308,7 +1355,7 @@ def build_reflection_map( broad_sigma = max(6.0, min(h, w) / 44.0) broad = cv2.GaussianBlur(rel, (0, 0), sigmaX=broad_sigma, sigmaY=broad_sigma) detail = rel / np.maximum(broad, 1e-3) - reflection_candidates.append(np.clip((detail - 1.05) / 0.30, 0.0, 1.0)) + reflection_candidates.append(np.clip((detail - 1.05) / 0.30, 0.0, 1.0)) luminance = image_luminance(img_np) / 255.0 floor_values = luminance[mask > 0] @@ -1321,24 +1368,24 @@ def build_reflection_map( broad_sigma = max(8.0, min(h, w) / 36.0) broad = cv2.GaussianBlur(filled, (0, 0), sigmaX=broad_sigma, sigmaY=broad_sigma) detail = filled / np.maximum(broad, 1e-3) - reflection_candidates.append(np.clip((detail - 1.08) / 0.30, 0.0, 1.0)) - - if not reflection_candidates: - return None - - # A reflection is additive light. Dark source-floor detail belongs to the - # illumination map; transferring it here would turn old material color or - # texture into an artificial dark reflection on the replacement material. - reflection = np.maximum.reduce(reflection_candidates).astype(np.float32) - if min(h, w) > 120: - sigma = max(0.6, min(h, w) / 520.0) - reflection = cv2.GaussianBlur(reflection, (0, 0), sigmaX=sigma, sigmaY=sigma) - reflection = np.clip(reflection, REFLECTION_MAP_MIN, REFLECTION_MAP_MAX) - reflection[mask == 0] = 0.0 - if float(np.max(np.abs(reflection[mask > 0]))) < 0.025: - return None - encoded = (reflection - REFLECTION_MAP_MIN) / (REFLECTION_MAP_MAX - REFLECTION_MAP_MIN) - return np.round(encoded * 255.0).clip(0, 255).astype(np.uint8) + reflection_candidates.append(np.clip((detail - 1.08) / 0.30, 0.0, 1.0)) + + if not reflection_candidates: + return None + + # A reflection is additive light. Dark source-floor detail belongs to the + # illumination map; transferring it here would turn old material color or + # texture into an artificial dark reflection on the replacement material. + reflection = np.maximum.reduce(reflection_candidates).astype(np.float32) + if min(h, w) > 120: + sigma = max(0.6, min(h, w) / 520.0) + reflection = cv2.GaussianBlur(reflection, (0, 0), sigmaX=sigma, sigmaY=sigma) + reflection = np.clip(reflection, REFLECTION_MAP_MIN, REFLECTION_MAP_MAX) + reflection[mask == 0] = 0.0 + if float(np.max(np.abs(reflection[mask > 0]))) < 0.025: + return None + encoded = (reflection - REFLECTION_MAP_MIN) / (REFLECTION_MAP_MAX - REFLECTION_MAP_MIN) + return np.round(encoded * 255.0).clip(0, 255).astype(np.uint8) def build_luminance_lighting_maps( @@ -1404,7 +1451,7 @@ def extract_intrinsic_shading(results: dict) -> np.ndarray | None: return shading.astype(np.float32) -def normalize_relative_shading( +def normalize_relative_shading( shading: np.ndarray, surface_mask: np.ndarray, ) -> np.ndarray | None: @@ -1424,139 +1471,139 @@ def normalize_relative_shading( relative = shading / median_val relative[~np.isfinite(relative)] = 1.0 - relative[surface_mask == 0] = 1.0 - return relative.astype(np.float32) - - -def masked_gaussian_blur( - values: np.ndarray, - surface_mask: np.ndarray, - sigma: float, -) -> np.ndarray: - mask = surface_mask.astype(np.float32) - numerator = cv2.GaussianBlur(values.astype(np.float32) * mask, (0, 0), sigmaX=sigma, sigmaY=sigma) - denominator = cv2.GaussianBlur(mask, (0, 0), sigmaX=sigma, sigmaY=sigma) - return numerator / np.maximum(denominator, 1e-4) - - -def normalize_relative_field(values: np.ndarray, surface_mask: np.ndarray) -> np.ndarray | None: - relative = values.astype(np.float32).copy() - valid = relative[surface_mask > 0] - valid = valid[np.isfinite(valid) & (valid > 1e-6)] - if valid.size == 0: - return None - median = float(np.median(valid)) - if median < 1e-6: - return None - relative /= median - relative[~np.isfinite(relative)] = 1.0 - relative[surface_mask == 0] = 1.0 - return relative - - -def broad_luminance_relative( - img_np: np.ndarray, - surface_mask: np.ndarray, -) -> np.ndarray | None: - luminance = image_luminance(img_np) / 255.0 - floor_values = luminance[surface_mask > 0] - floor_values = floor_values[np.isfinite(floor_values) & (floor_values > 1e-6)] - if floor_values.size == 0: - return None - sigma = max(12.0, min(surface_mask.shape[:2]) / 32.0) - broad = masked_gaussian_blur(luminance, surface_mask, sigma) - return normalize_relative_field(broad, surface_mask) - - -def align_intrinsic_shading_to_luminance( - relative_shading: np.ndarray, - img_np: np.ndarray, - surface_mask: np.ndarray, -) -> tuple[np.ndarray, str]: - """Correct intrinsic maps that encode lightness with the opposite polarity.""" - observed = broad_luminance_relative(img_np, surface_mask) - if observed is None: - return relative_shading, "intrinsic-unchecked" - - sigma = max(12.0, min(surface_mask.shape[:2]) / 32.0) - intrinsic_broad = masked_gaussian_blur(relative_shading, surface_mask, sigma) - intrinsic_broad = normalize_relative_field(intrinsic_broad, surface_mask) - if intrinsic_broad is None: - return relative_shading, "intrinsic-unchecked" - - valid = ( - (surface_mask > 0) - & np.isfinite(observed) - & np.isfinite(intrinsic_broad) - & (observed > 1e-4) - & (intrinsic_broad > 1e-4) - ) - if int(valid.sum()) < 256: - return relative_shading, "intrinsic-unchecked" - - observed_log = np.log(observed[valid]) - intrinsic_log = np.log(intrinsic_broad[valid]) - if float(np.std(observed_log)) < 1e-4 or float(np.std(intrinsic_log)) < 1e-4: - return relative_shading, "intrinsic-unchecked" - - correlation = float(np.corrcoef(observed_log, intrinsic_log)[0, 1]) - if correlation < -0.12: - corrected = normalize_relative_field(1.0 / np.maximum(relative_shading, 1e-4), surface_mask) - if corrected is not None: - return corrected, "intrinsic-inverted-corrected" - return relative_shading, "intrinsic-aligned" if correlation >= 0.10 else "intrinsic-low-confidence" - - -def smooth_relative_lighting(relative_shading: np.ndarray, surface_mask: np.ndarray) -> np.ndarray | None: - """Keep room-scale illumination while rejecting old floor texture and grout.""" - sigma = max(12.0, min(surface_mask.shape[:2]) / 32.0) - bounded = np.clip(relative_shading.astype(np.float32), 0.25, 4.0) - smooth = masked_gaussian_blur(bounded, surface_mask, sigma) - normalized = normalize_relative_field(smooth, surface_mask) - if normalized is None: - return None - normalized = np.clip(normalized, 0.60, 1.45) - normalized[surface_mask == 0] = 1.0 - return normalized + relative[surface_mask == 0] = 1.0 + return relative.astype(np.float32) -def build_intrinsic_lighting_maps( - img_np: np.ndarray, +def masked_gaussian_blur( + values: np.ndarray, surface_mask: np.ndarray, -) -> dict[str, np.ndarray | None] | None: - if not surface_mask.any() or intrinsic_models is None: - return None + sigma: float, +) -> np.ndarray: + mask = surface_mask.astype(np.float32) + numerator = cv2.GaussianBlur(values.astype(np.float32) * mask, (0, 0), sigmaX=sigma, sigmaY=sigma) + denominator = cv2.GaussianBlur(mask, (0, 0), sigmaX=sigma, sigmaY=sigma) + return numerator / np.maximum(denominator, 1e-4) - try: - img_float = img_np.astype(np.float32) / 255.0 - from intrinsic.pipeline import run_pipeline - results = run_pipeline(intrinsic_models, img_float, device=str(device)) - shading = extract_intrinsic_shading(results) - if shading is None: - return None - relative = normalize_relative_shading(shading, surface_mask) - if relative is None: - return None - relative, alignment = align_intrinsic_shading_to_luminance(relative, img_np, surface_mask) - smoothed = smooth_relative_lighting(relative, surface_mask) - if smoothed is None: - return None - print(f"[LIGHTING] intrinsic shading alignment={alignment}", flush=True) - - return { - "shadeMap": encode_relative_map(smoothed, SHADE_MAP_MIN, SHADE_MAP_MAX), - "showroomShadeMap": build_showroom_shade_map_from_relative(smoothed, surface_mask), - "reflectionMap": build_reflection_map(img_np, surface_mask, smoothed), - } - except Exception as exc: - print(f"Intrinsic shading decomposition failed: {exc}. Falling back to default luminance shading.", flush=True) +def normalize_relative_field(values: np.ndarray, surface_mask: np.ndarray) -> np.ndarray | None: + relative = values.astype(np.float32).copy() + valid = relative[surface_mask > 0] + valid = valid[np.isfinite(valid) & (valid > 1e-6)] + if valid.size == 0: + return None + median = float(np.median(valid)) + if median < 1e-6: return None + relative /= median + relative[~np.isfinite(relative)] = 1.0 + relative[surface_mask == 0] = 1.0 + return relative -def build_shade_map(img_np: np.ndarray, surface_mask: np.ndarray) -> np.ndarray | None: - lighting_maps = build_luminance_lighting_maps(img_np, surface_mask) - return lighting_maps.get("shadeMap") if lighting_maps else None +def broad_luminance_relative( + img_np: np.ndarray, + surface_mask: np.ndarray, +) -> np.ndarray | None: + luminance = image_luminance(img_np) / 255.0 + floor_values = luminance[surface_mask > 0] + floor_values = floor_values[np.isfinite(floor_values) & (floor_values > 1e-6)] + if floor_values.size == 0: + return None + sigma = max(12.0, min(surface_mask.shape[:2]) / 32.0) + broad = masked_gaussian_blur(luminance, surface_mask, sigma) + return normalize_relative_field(broad, surface_mask) + + +def align_intrinsic_shading_to_luminance( + relative_shading: np.ndarray, + img_np: np.ndarray, + surface_mask: np.ndarray, +) -> tuple[np.ndarray, str]: + """Correct intrinsic maps that encode lightness with the opposite polarity.""" + observed = broad_luminance_relative(img_np, surface_mask) + if observed is None: + return relative_shading, "intrinsic-unchecked" + + sigma = max(12.0, min(surface_mask.shape[:2]) / 32.0) + intrinsic_broad = masked_gaussian_blur(relative_shading, surface_mask, sigma) + intrinsic_broad = normalize_relative_field(intrinsic_broad, surface_mask) + if intrinsic_broad is None: + return relative_shading, "intrinsic-unchecked" + + valid = ( + (surface_mask > 0) + & np.isfinite(observed) + & np.isfinite(intrinsic_broad) + & (observed > 1e-4) + & (intrinsic_broad > 1e-4) + ) + if int(valid.sum()) < 256: + return relative_shading, "intrinsic-unchecked" + + observed_log = np.log(observed[valid]) + intrinsic_log = np.log(intrinsic_broad[valid]) + if float(np.std(observed_log)) < 1e-4 or float(np.std(intrinsic_log)) < 1e-4: + return relative_shading, "intrinsic-unchecked" + + correlation = float(np.corrcoef(observed_log, intrinsic_log)[0, 1]) + if correlation < -0.12: + corrected = normalize_relative_field(1.0 / np.maximum(relative_shading, 1e-4), surface_mask) + if corrected is not None: + return corrected, "intrinsic-inverted-corrected" + return relative_shading, "intrinsic-aligned" if correlation >= 0.10 else "intrinsic-low-confidence" + + +def smooth_relative_lighting(relative_shading: np.ndarray, surface_mask: np.ndarray) -> np.ndarray | None: + """Keep room-scale illumination while rejecting old floor texture and grout.""" + sigma = max(12.0, min(surface_mask.shape[:2]) / 32.0) + bounded = np.clip(relative_shading.astype(np.float32), 0.25, 4.0) + smooth = masked_gaussian_blur(bounded, surface_mask, sigma) + normalized = normalize_relative_field(smooth, surface_mask) + if normalized is None: + return None + normalized = np.clip(normalized, 0.60, 1.45) + normalized[surface_mask == 0] = 1.0 + return normalized + + +def build_intrinsic_lighting_maps( + img_np: np.ndarray, + surface_mask: np.ndarray, +) -> dict[str, np.ndarray | None] | None: + if not surface_mask.any() or intrinsic_models is None: + return None + + try: + img_float = img_np.astype(np.float32) / 255.0 + from intrinsic.pipeline import run_pipeline + results = run_pipeline(intrinsic_models, img_float, device=str(device)) + shading = extract_intrinsic_shading(results) + if shading is None: + return None + + relative = normalize_relative_shading(shading, surface_mask) + if relative is None: + return None + relative, alignment = align_intrinsic_shading_to_luminance(relative, img_np, surface_mask) + smoothed = smooth_relative_lighting(relative, surface_mask) + if smoothed is None: + return None + print(f"[LIGHTING] intrinsic shading alignment={alignment}", flush=True) + + return { + "shadeMap": encode_relative_map(smoothed, SHADE_MAP_MIN, SHADE_MAP_MAX), + "showroomShadeMap": build_showroom_shade_map_from_relative(smoothed, surface_mask), + "reflectionMap": build_reflection_map(img_np, surface_mask, smoothed), + } + except Exception as exc: + print(f"Intrinsic shading decomposition failed: {exc}. Falling back to default luminance shading.", flush=True) + return None + + +def build_shade_map(img_np: np.ndarray, surface_mask: np.ndarray) -> np.ndarray | None: + lighting_maps = build_luminance_lighting_maps(img_np, surface_mask) + return lighting_maps.get("shadeMap") if lighting_maps else None def build_intrinsic_shade_map(img_np: np.ndarray, surface_mask: np.ndarray) -> np.ndarray | None: @@ -3229,319 +3276,336 @@ def build_tile_material_package(contents: bytes, base_roughness: float = 0.42) - } -def material_map_urls(cache_key: str) -> dict[str, str]: - return { - "albedoMap": f"/materials/{cache_key}/albedo.png", - "normalMap": f"/materials/{cache_key}/normal.png", - "heightMap": f"/materials/{cache_key}/height.png", - "roughnessMap": f"/materials/{cache_key}/roughness.png", - "aoMap": f"/materials/{cache_key}/ao.png", - "specularMap": f"/materials/{cache_key}/specular.png", - } - - -def encode_bundle_image_data_url(img_np: np.ndarray) -> str: - image_format = BUNDLE_IMAGE_FORMAT - if image_format in {"jpg", "jpeg"}: - pil_format = "JPEG" - mime_type = "image/jpeg" - extension = "jpg" - elif image_format == "webp": - pil_format = "WEBP" - mime_type = "image/webp" - extension = "webp" - else: - pil_format = "JPEG" - mime_type = "image/jpeg" - extension = "jpg" - - image = Image.fromarray(img_np.astype(np.uint8)) - buffer = io.BytesIO() - try: - save_kwargs = { - "quality": int(np.clip(BUNDLE_IMAGE_QUALITY, 1, 100)), - "optimize": True, - } - if pil_format == "WEBP": - save_kwargs["method"] = 4 - image.save(buffer, format=pil_format, **save_kwargs) - except Exception as exc: - print(f"Bundle {extension} encoding failed ({exc}); falling back to JPEG.", flush=True) - buffer = io.BytesIO() - image.save(buffer, format="JPEG", quality=92, optimize=True) - mime_type = "image/jpeg" - - encoded = base64.b64encode(buffer.getvalue()).decode() - return f"data:{mime_type};base64,{encoded}" - - -def data_url_to_bytes(value: str) -> tuple[str, bytes]: - if value.startswith("data:"): - header, encoded = value.split(",", 1) - mime_type = header[5:].split(";", 1)[0] or "application/octet-stream" - return mime_type, base64.b64decode(encoded) - return "application/octet-stream", base64.b64decode(value) - - -def bundle_image_extension(mime_type: str) -> str: - if mime_type == "image/webp": - return "webp" - if mime_type == "image/png": - return "png" - return "jpg" - - -def make_binary_ref(path: str, data: bytes, dtype: str) -> dict: - return { - "path": path, - "dtype": dtype, - "byteLength": len(data), - } - - +def material_map_urls(cache_key: str) -> dict[str, str]: + return { + "albedoMap": f"/materials/{cache_key}/albedo.png", + "normalMap": f"/materials/{cache_key}/normal.png", + "heightMap": f"/materials/{cache_key}/height.png", + "roughnessMap": f"/materials/{cache_key}/roughness.png", + "aoMap": f"/materials/{cache_key}/ao.png", + "specularMap": f"/materials/{cache_key}/specular.png", + } + + +def encode_bundle_image_data_url(img_np: np.ndarray) -> str: + image_format = BUNDLE_IMAGE_FORMAT + if image_format in {"jpg", "jpeg"}: + pil_format = "JPEG" + mime_type = "image/jpeg" + extension = "jpg" + elif image_format == "webp": + pil_format = "WEBP" + mime_type = "image/webp" + extension = "webp" + else: + pil_format = "JPEG" + mime_type = "image/jpeg" + extension = "jpg" + + image = Image.fromarray(img_np.astype(np.uint8)) + buffer = io.BytesIO() + try: + save_kwargs = { + "quality": int(np.clip(BUNDLE_IMAGE_QUALITY, 1, 100)), + "optimize": True, + } + if pil_format == "WEBP": + save_kwargs["method"] = 4 + image.save(buffer, format=pil_format, **save_kwargs) + except Exception as exc: + print(f"Bundle {extension} encoding failed ({exc}); falling back to JPEG.", flush=True) + buffer = io.BytesIO() + image.save(buffer, format="JPEG", quality=92, optimize=True) + mime_type = "image/jpeg" + + encoded = base64.b64encode(buffer.getvalue()).decode() + return f"data:{mime_type};base64,{encoded}" + + +def data_url_to_bytes(value: str) -> tuple[str, bytes]: + if value.startswith("data:"): + header, encoded = value.split(",", 1) + mime_type = header[5:].split(";", 1)[0] or "application/octet-stream" + return mime_type, base64.b64decode(encoded) + return "application/octet-stream", base64.b64decode(value) + + +def bundle_image_extension(mime_type: str) -> str: + if mime_type == "image/webp": + return "webp" + if mime_type == "image/png": + return "png" + return "jpg" + + +def make_binary_ref(path: str, data: bytes, dtype: str) -> dict: + return { + "path": path, + "dtype": dtype, + "byteLength": len(data), + } + + def encode_mask_bitset(mask_bytes: bytes, pixel_count: int) -> bytes: """Encode uint32 pixel indices as an exact, least-significant-bit-first bitset.""" indices = np.frombuffer(mask_bytes, dtype=np.uint32) - if indices.size and int(indices.max()) >= pixel_count: - raise ValueError("Mask contains a pixel index outside the source image.") - - bits = np.zeros(pixel_count, dtype=np.uint8) + if indices.size and int(indices.max()) >= pixel_count: + raise ValueError("Mask contains a pixel index outside the source image.") + + bits = np.zeros(pixel_count, dtype=np.uint8) bits[indices] = 1 return np.packbits(bits, bitorder="little").tobytes() -def build_manifest_segmentation_bundle( - bundle: dict, - job_id: str, - *, - image_url: str | None = None, - include_image: bool = False, -) -> bytes: - metadata = dict(bundle) - metadata["format"] = "baetes-vizbundle" - metadata["bundleVersion"] = 3 - metadata["encoding"] = "zip-store" - metadata["assetBaseUrl"] = f"/viz2d/jobs/{job_id}/assets/" - metadata["pixels"] = None - if image_url: - metadata["imageUrl"] = image_url - metadata["segments"] = [] - asset_dir = JOB_DIR / f"{job_id}.assets" - asset_dir.mkdir(parents=True, exist_ok=True) - - buffer = io.BytesIO() - with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_STORED) as archive: - if include_image: - pixels_mime, pixels = data_url_to_bytes(bundle["pixels"]) - image_path = f"image.{bundle_image_extension(pixels_mime)}" - archive.writestr(image_path, pixels) - metadata["pixels"] = { - "path": image_path, - "mimeType": pixels_mime, - "byteLength": len(pixels), - } +def foreground_occlusion_mask(surface_mask: np.ndarray, seg_map: np.ndarray) -> np.ndarray: + h, w = surface_mask.shape[:2] + kern_size = max(5, min(h, w) // 180) | 1 + kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kern_size, kern_size)) + occluder_mask = np.isin(seg_map, class_ids(OCCLUDER_CLASSES)).astype(np.uint8) + if not occluder_mask.any() or not surface_mask.any(): + return np.zeros((h, w), dtype=np.uint8) - lazy_asset_fields = { - "surfaceUv": ("surface-uv.f32", "float32"), - "surfacePlaneIds": ("surface-plane-ids.u8", "uint8"), - "shadeMap": ("shade.u8", "uint8"), - "showroomShadeMap": ("showroom-shade.u8", "uint8"), - "reflectionMap": ("reflection.u8", "uint8"), - } + near_surface = cv2.dilate(surface_mask.astype(np.uint8), kern, iterations=5) + occluders = cv2.dilate(occluder_mask, kern, iterations=1) + return ((occluders > 0) & (near_surface > 0)).astype(np.uint8) - for segment_index, segment in enumerate(bundle.get("segments", [])): - segment_metadata = dict(segment) - mask_value = segment.get("mask") - if mask_value: - mask_bytes = base64.b64decode(mask_value) - pixel_count = int(metadata["width"]) * int(metadata["height"]) - mask_bitset = encode_mask_bitset(mask_bytes, pixel_count) - mask_path = f"segments/{segment_index}/mask.bitset" - archive.writestr(mask_path, mask_bitset) - segment_metadata["mask"] = { - **make_binary_ref(mask_path, mask_bitset, "bitset"), - "encoding": "bitset-lsb0", - "pixelCount": pixel_count, - } - print( - f"[BUNDLE] Compressed mask for job {job_id}: " - f"{len(mask_bytes)} -> {len(mask_bitset)} bytes", - flush=True, - ) - for field, (filename, dtype) in lazy_asset_fields.items(): - value = segment.get(field) - if not value: - continue - data = base64.b64decode(value) - asset_name = f"s{segment_index}-{filename}" - (asset_dir / asset_name).write_bytes(data) - segment_metadata[field] = { - **make_binary_ref(asset_name, data, dtype), - "url": f"/viz2d/jobs/{job_id}/assets/{asset_name}", - "lazy": True, - } - metadata["segments"].append(segment_metadata) - - archive.writestr( - "metadata.json", - json.dumps(metadata, separators=(",", ":")).encode("utf-8"), - ) - - return buffer.getvalue() - - -def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | None = None): - t_start = time.perf_counter() - - t0 = time.perf_counter() - img = Image.open(io.BytesIO(contents)).convert("RGB") - img_np = np.array(img) - h, w = img_np.shape[:2] - min_floor_area = max(1200, int(w * h * 0.015)) - image_loading_elapsed = time.perf_counter() - t0 - print(f"[TIMING] Image loading/parsing took {image_loading_elapsed:.3f} seconds", flush=True) - if debug is not None: - debug.record_images( - "source-image", - "Uploaded image", - "The RGB image passed to the analysis pipeline.", - [("Source", img_np)], - {"width": int(w), "height": int(h), "minimumFloorPixels": int(min_floor_area)}, - image_loading_elapsed * 1000, - ) - t0 = time.perf_counter() - seg_map = run_segmentation(img, img_np) - segmentation_elapsed = time.perf_counter() - t0 - print(f"[TIMING] Floor segmentation took {segmentation_elapsed:.3f} seconds", flush=True) - if debug is not None: - label_ids, label_counts = np.unique(seg_map, return_counts=True) - class_areas = { - class_name_for_id(int(label_id)): int(pixel_count) - for label_id, pixel_count in zip(label_ids, label_counts) - if int(pixel_count) >= max(128, int(w * h * 0.001)) - } - debug.record_images( - "semantic-segmentation", - "Semantic segmentation", - "Colour overlay of the ADE20K semantic labels used to find the floor and reject room objects.", - [("Class overlay", debug_segmentation_overlay(img_np, seg_map))], - { - "backend": segmentation_backend, - "model": active_segmentation_model_name(), - "classPixels": class_areas, - }, - segmentation_elapsed * 1000, - ) +def build_manifest_segmentation_bundle( + bundle: dict, + job_id: str, + *, + image_url: str | None = None, + include_image: bool = False, +) -> bytes: + metadata = dict(bundle) + metadata["format"] = "baetes-vizbundle" + metadata["bundleVersion"] = 3 + metadata["encoding"] = "zip-store" + metadata["assetBaseUrl"] = f"/viz2d/jobs/{job_id}/assets/" + metadata["pixels"] = None + if image_url: + metadata["imageUrl"] = image_url + metadata["segments"] = [] + asset_dir = JOB_DIR / f"{job_id}.assets" + asset_dir.mkdir(parents=True, exist_ok=True) + + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_STORED) as archive: + if include_image: + pixels_mime, pixels = data_url_to_bytes(bundle["pixels"]) + image_path = f"image.{bundle_image_extension(pixels_mime)}" + archive.writestr(image_path, pixels) + metadata["pixels"] = { + "path": image_path, + "mimeType": pixels_mime, + "byteLength": len(pixels), + } + + lazy_asset_fields = { + "surfaceUv": ("surface-uv.f32", "float32"), + "surfacePlaneIds": ("surface-plane-ids.u8", "uint8"), + "shadeMap": ("shade.u8", "uint8"), + "showroomShadeMap": ("showroom-shade.u8", "uint8"), + "reflectionMap": ("reflection.u8", "uint8"), + } + + for segment_index, segment in enumerate(bundle.get("segments", [])): + segment_metadata = dict(segment) + pixel_count = int(metadata["width"]) * int(metadata["height"]) + for mask_field in ("mask", "occlusionMask"): + mask_value = segment.get(mask_field) + if mask_value: + mask_bytes = base64.b64decode(mask_value) + mask_bitset = encode_mask_bitset(mask_bytes, pixel_count) + mask_path = f"segments/{segment_index}/{mask_field}.bitset" + archive.writestr(mask_path, mask_bitset) + segment_metadata[mask_field] = { + **make_binary_ref(mask_path, mask_bitset, "bitset"), + "encoding": "bitset-lsb0", + "pixelCount": pixel_count, + } + print( + f"[BUNDLE] Compressed {mask_field} for job {job_id}: " + f"{len(mask_bytes)} -> {len(mask_bitset)} bytes", + flush=True, + ) + for field, (filename, dtype) in lazy_asset_fields.items(): + value = segment.get(field) + if not value: + continue + data = base64.b64decode(value) + asset_name = f"s{segment_index}-{filename}" + (asset_dir / asset_name).write_bytes(data) + segment_metadata[field] = { + **make_binary_ref(asset_name, data, dtype), + "url": f"/viz2d/jobs/{job_id}/assets/{asset_name}", + "lazy": True, + } + metadata["segments"].append(segment_metadata) + + archive.writestr( + "metadata.json", + json.dumps(metadata, separators=(",", ":")).encode("utf-8"), + ) + + return buffer.getvalue() + + +def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | None = None): + t_start = time.perf_counter() + + t0 = time.perf_counter() + img = Image.open(io.BytesIO(contents)).convert("RGB") + img_np = np.array(img) + h, w = img_np.shape[:2] + min_floor_area = max(1200, int(w * h * 0.015)) + image_loading_elapsed = time.perf_counter() - t0 + print(f"[TIMING] Image loading/parsing took {image_loading_elapsed:.3f} seconds", flush=True) + if debug is not None: + debug.record_images( + "source-image", + "Uploaded image", + "The RGB image passed to the analysis pipeline.", + [("Source", img_np)], + {"width": int(w), "height": int(h), "minimumFloorPixels": int(min_floor_area)}, + image_loading_elapsed * 1000, + ) t0 = time.perf_counter() - pixels_b64 = encode_bundle_image_data_url(img_np) - print(f"[TIMING] Image bundle encoding took {time.perf_counter() - t0:.3f} seconds", flush=True) + seg_map = run_segmentation(img, img_np) + segmentation_elapsed = time.perf_counter() - t0 + print(f"[TIMING] Floor segmentation took {segmentation_elapsed:.3f} seconds", flush=True) + if debug is not None: + label_ids, label_counts = np.unique(seg_map, return_counts=True) + class_areas = { + class_name_for_id(int(label_id)): int(pixel_count) + for label_id, pixel_count in zip(label_ids, label_counts) + if int(pixel_count) >= max(128, int(w * h * 0.001)) + } + debug.record_images( + "semantic-segmentation", + "Semantic segmentation", + "Colour overlay of the ADE20K semantic labels used to find the floor and reject room objects.", + [("Class overlay", debug_segmentation_overlay(img_np, seg_map))], + { + "backend": segmentation_backend, + "model": active_segmentation_model_name(), + "classPixels": class_areas, + }, + segmentation_elapsed * 1000, + ) - t0 = time.perf_counter() - primary_floor_ids = class_ids(PRIMARY_FLOOR_CLASSES) - floor_class_ids = class_ids(FLOOR_SURFACE_CLASSES) - raw_primary_floor_mask = np.isin(seg_map, primary_floor_ids).astype(np.uint8) - floor_mask = raw_primary_floor_mask.copy() - floor_mask = wall_subtract(floor_mask, seg_map, dilation=1) - floor_mask = clean_floor_mask(floor_mask) - floor_mask_source = "primary-floor" - if int(floor_mask.sum()) < min_floor_area: - floor_mask = np.isin(seg_map, floor_class_ids).astype(np.uint8) - floor_mask = wall_subtract(floor_mask, seg_map, dilation=1) - floor_mask = clean_floor_mask(floor_mask) - floor_mask_source = "floor-surface-fallback" - cleaned_floor_mask = floor_mask.copy() - floor_mask, sam_metadata = refine_floor_mask_with_sam2(img_np, floor_mask, seg_map) - floor_mask_elapsed = time.perf_counter() - t0 - print(f"[TIMING] Floor masking/cleanup took {floor_mask_elapsed:.3f} seconds", flush=True) - if debug is not None: - debug.record_images( - "floor-mask", - "Floor mask selection", - "Compare the raw floor prediction with cleanup and optional SAM refinement before geometry is estimated.", - [ - ("Raw floor class", debug_mask_overlay(img_np, raw_primary_floor_mask)), - ("Cleaned candidate", debug_mask_overlay(img_np, cleaned_floor_mask)), - ("Final floor mask", debug_mask_overlay(img_np, floor_mask)), - ], - { - "selection": floor_mask_source, - "rawFloorPixels": int(raw_primary_floor_mask.sum()), - "cleanedFloorPixels": int(cleaned_floor_mask.sum()), - "finalFloorPixels": int(floor_mask.sum()), - **sam_metadata, - }, - floor_mask_elapsed * 1000, - ) - - t0 = time.perf_counter() - geometry = estimate_scene_geometry(img, img_np, w, h) - depth = geometry.get("depth") - geometry_elapsed = time.perf_counter() - t0 - print( - f"[TIMING] Geometry estimation ({geometry.get('provider')}) took " - f"{geometry_elapsed:.3f} seconds", - flush=True, - ) - if debug is not None: - geometry_images: list[tuple[str, np.ndarray]] = [] - if depth is not None: - geometry_images.append(("Depth", debug_scalar_map(depth, floor_mask))) - debug.record_images( - "scene-geometry", - "Scene geometry", - "Depth or metric geometry used to fit and validate the floor plane.", - geometry_images, - { - "provider": geometry.get("provider"), - "depthAvailable": depth is not None, - "metric": bool(geometry.get("metric")), - }, - geometry_elapsed * 1000, - ) - - t0 = time.perf_counter() - homography, plane = estimate_floor_plane(floor_mask, img_np, geometry) - plane_elapsed = time.perf_counter() - t0 - print(f"[TIMING] Plane fitting / homography calculation took {plane_elapsed:.3f} seconds", flush=True) - if debug is not None: - debug.record_images( - "floor-plane", - "Floor plane and perspective", - "The fitted floor quadrilateral is the source of the perspective transform used for tile placement.", - [("Fitted quadrilateral", debug_plane_overlay(img_np, plane))], - { - "planeFound": plane is not None, - "homographyAvailable": homography is not None, - "geometryProvider": plane.get("geometryProvider") if plane else None, - "geometryConfidence": plane.get("geometryConfidence") if plane else 0.0, - "metricGeometry": bool(plane and plane.get("floorTransform")), - "quad": plane.get("quad") if plane else None, - }, - plane_elapsed * 1000, - ) + t0 = time.perf_counter() + pixels_b64 = encode_bundle_image_data_url(img_np) + print(f"[TIMING] Image bundle encoding took {time.perf_counter() - t0:.3f} seconds", flush=True) t0 = time.perf_counter() - quad = np.asarray(plane["quad"], dtype=np.float32).reshape(4, 2) if plane and plane.get("quad") else None + primary_floor_ids = class_ids(PRIMARY_FLOOR_CLASSES) + floor_class_ids = class_ids(FLOOR_SURFACE_CLASSES) + raw_primary_floor_mask = np.isin(seg_map, primary_floor_ids).astype(np.uint8) + floor_mask = raw_primary_floor_mask.copy() + floor_mask = wall_subtract(floor_mask, seg_map, dilation=1) + floor_mask = clean_floor_mask(floor_mask) + floor_mask_source = "primary-floor" + if int(floor_mask.sum()) < min_floor_area: + floor_mask = np.isin(seg_map, floor_class_ids).astype(np.uint8) + floor_mask = wall_subtract(floor_mask, seg_map, dilation=1) + floor_mask = clean_floor_mask(floor_mask) + floor_mask_source = "floor-surface-fallback" + cleaned_floor_mask = floor_mask.copy() + floor_mask, sam_metadata = refine_floor_mask_with_sam2(img_np, floor_mask, seg_map) + floor_mask_elapsed = time.perf_counter() - t0 + print(f"[TIMING] Floor masking/cleanup took {floor_mask_elapsed:.3f} seconds", flush=True) + if debug is not None: + debug.record_images( + "floor-mask", + "Floor mask selection", + "Compare the raw floor prediction with cleanup and optional SAM refinement before geometry is estimated.", + [ + ("Raw floor class", debug_mask_overlay(img_np, raw_primary_floor_mask)), + ("Cleaned candidate", debug_mask_overlay(img_np, cleaned_floor_mask)), + ("Final floor mask", debug_mask_overlay(img_np, floor_mask)), + ], + { + "selection": floor_mask_source, + "rawFloorPixels": int(raw_primary_floor_mask.sum()), + "cleanedFloorPixels": int(cleaned_floor_mask.sum()), + "finalFloorPixels": int(floor_mask.sum()), + **sam_metadata, + }, + floor_mask_elapsed * 1000, + ) + + t0 = time.perf_counter() + geometry = estimate_scene_geometry(img, img_np, w, h) + depth = geometry.get("depth") + geometry_elapsed = time.perf_counter() - t0 + print( + f"[TIMING] Geometry estimation ({geometry.get('provider')}) took " + f"{geometry_elapsed:.3f} seconds", + flush=True, + ) + if debug is not None: + geometry_images: list[tuple[str, np.ndarray]] = [] + if depth is not None: + geometry_images.append(("Depth", debug_scalar_map(depth, floor_mask))) + debug.record_images( + "scene-geometry", + "Scene geometry", + "Depth or metric geometry used to fit and validate the floor plane.", + geometry_images, + { + "provider": geometry.get("provider"), + "depthAvailable": depth is not None, + "metric": bool(geometry.get("metric")), + }, + geometry_elapsed * 1000, + ) + + t0 = time.perf_counter() + homography, plane = estimate_floor_plane(floor_mask, img_np, geometry) + plane_elapsed = time.perf_counter() - t0 + print(f"[TIMING] Plane fitting / homography calculation took {plane_elapsed:.3f} seconds", flush=True) + if debug is not None: + debug.record_images( + "floor-plane", + "Floor plane and perspective", + "The fitted floor quadrilateral is the source of the perspective transform used for tile placement.", + [("Fitted quadrilateral", debug_plane_overlay(img_np, plane))], + { + "planeFound": plane is not None, + "homographyAvailable": homography is not None, + "geometryProvider": plane.get("geometryProvider") if plane else None, + "geometryConfidence": plane.get("geometryConfidence") if plane else 0.0, + "metricGeometry": bool(plane and plane.get("floorTransform")), + "quad": plane.get("quad") if plane else None, + }, + plane_elapsed * 1000, + ) + + t0 = time.perf_counter() + quad = np.asarray(plane["quad"], dtype=np.float32).reshape(4, 2) if plane and plane.get("quad") else None surface_mask, edge_metadata = build_floor_surface_mask(floor_mask, seg_map, quad, depth, geometry, plane) surface_indices = np.flatnonzero(surface_mask.ravel()).astype(np.uint32) + occlusion_mask = foreground_occlusion_mask(surface_mask, seg_map) + occlusion_indices = np.flatnonzero(occlusion_mask.ravel()).astype(np.uint32) surface_mask_elapsed = time.perf_counter() - t0 print(f"[TIMING] Surface masking took {surface_mask_elapsed:.3f} seconds", flush=True) if debug is not None: - debug.record_images( - "renderable-surface", - "Renderable floor surface", - "Gold pixels are retained for rendering; red pixels were part of the floor mask but removed by protection, edge, or geometry filters.", - [("Final surface", debug_surface_overlay(img_np, floor_mask, surface_mask))], - { + debug.record_images( + "renderable-surface", + "Renderable floor surface", + "Gold pixels are retained for rendering; red pixels were part of the floor mask but removed by protection, edge, or geometry filters.", + [("Final surface", debug_surface_overlay(img_np, floor_mask, surface_mask))], + { "floorPixels": int(floor_mask.sum()), "surfacePixels": int(surface_mask.sum()), + "occlusionPixels": int(occlusion_mask.sum()), "surfaceCoverage": round(float(surface_mask.sum()) / max(int(floor_mask.sum()), 1), 4), **edge_metadata, }, - surface_mask_elapsed * 1000, - ) + surface_mask_elapsed * 1000, + ) t0 = time.perf_counter() surface_mapping = build_surface_uv_mapping(surface_mask, surface_indices, geometry) @@ -3566,8 +3630,8 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non "surfaceUvAssignedPlaneCount": 0, } ) - surface_mapping_elapsed = time.perf_counter() - t0 - print(f"[TIMING] Multi-plane surface mapping took {surface_mapping_elapsed:.3f} seconds", flush=True) + surface_mapping_elapsed = time.perf_counter() - t0 + print(f"[TIMING] Multi-plane surface mapping took {surface_mapping_elapsed:.3f} seconds", flush=True) print( "[FLOOR_3D_BUNDLE] serialized derived floor geometry " f"rawPointMapSent=false floorTransformSent={bool(plane and plane.get('floorTransform'))} " @@ -3576,27 +3640,27 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non f"{int(len(surface_indices))} " f"surfacePlaneCount={len(surface_mapping['planes']) if surface_mapping is not None else 0} " f"geometryProvider={plane.get('geometryProvider', geometry.get('provider')) if plane else geometry.get('provider')}", - flush=True, - ) - if debug is not None: - mapping_images: list[tuple[str, np.ndarray]] = [] - if use_surface_uv: - mapping_images.append(( - "UV checkerboard", - debug_uv_checkerboard(h, w, surface_indices, surface_mapping["uv"]), - )) - mapping_images.append(( - "Surface planes", - debug_plane_id_map(h, w, surface_indices, surface_mapping["planeIds"]), - )) - debug.record_images( - "surface-mapping", - "Texture-coordinate mapping", - "The checkerboard shows the coordinates sent to the renderer. Plane colours identify separately fitted surface planes.", - mapping_images, - mapping_metadata, - surface_mapping_elapsed * 1000, - ) + flush=True, + ) + if debug is not None: + mapping_images: list[tuple[str, np.ndarray]] = [] + if use_surface_uv: + mapping_images.append(( + "UV checkerboard", + debug_uv_checkerboard(h, w, surface_indices, surface_mapping["uv"]), + )) + mapping_images.append(( + "Surface planes", + debug_plane_id_map(h, w, surface_indices, surface_mapping["planeIds"]), + )) + debug.record_images( + "surface-mapping", + "Texture-coordinate mapping", + "The checkerboard shows the coordinates sent to the renderer. Plane colours identify separately fitted surface planes.", + mapping_images, + mapping_metadata, + surface_mapping_elapsed * 1000, + ) t0 = time.perf_counter() lighting_maps = None @@ -3621,46 +3685,72 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non shade_map = lighting_maps.get("shadeMap") showroom_shade_map = lighting_maps.get("showroomShadeMap") reflection_map = lighting_maps.get("reflectionMap") - lighting_elapsed = time.perf_counter() - t0 - print( - "[TIMING] Lighting map construction took " - f"{lighting_elapsed:.3f} seconds " - f"(source={lighting_source}, reflections={reflection_map is not None})", - flush=True, - ) - if debug is not None: - lighting_images: list[tuple[str, np.ndarray]] = [] - if shade_map is not None: - lighting_images.append(("Shade map", debug_scalar_map(shade_map, surface_mask))) - if showroom_shade_map is not None: - lighting_images.append(("Showroom shade map", debug_scalar_map(showroom_shade_map, surface_mask))) - if reflection_map is not None: - lighting_images.append(("Reflection map", debug_scalar_map(reflection_map, surface_mask))) - debug.record_images( - "lighting-transfer", - "Lighting and reflections", - "Maps transferred from the room image to make the replacement material fit its surrounding light.", - lighting_images, - { - "source": lighting_source, - "shadingAvailable": shade_map is not None, - "reflectionsAvailable": reflection_map is not None, - }, - lighting_elapsed * 1000, - ) + lighting_elapsed = time.perf_counter() - t0 + print( + "[TIMING] Lighting map construction took " + f"{lighting_elapsed:.3f} seconds " + f"(source={lighting_source}, reflections={reflection_map is not None})", + flush=True, + ) + if debug is not None: + lighting_images: list[tuple[str, np.ndarray]] = [] + if shade_map is not None: + lighting_images.append(("Shade map", debug_scalar_map(shade_map, surface_mask))) + if showroom_shade_map is not None: + lighting_images.append(("Showroom shade map", debug_scalar_map(showroom_shade_map, surface_mask))) + if reflection_map is not None: + lighting_images.append(("Reflection map", debug_scalar_map(reflection_map, surface_mask))) + debug.record_images( + "lighting-transfer", + "Lighting and reflections", + "Maps transferred from the room image to make the replacement material fit its surrounding light.", + lighting_images, + { + "source": lighting_source, + "shadingAvailable": shade_map is not None, + "reflectionsAvailable": reflection_map is not None, + }, + lighting_elapsed * 1000, + ) - t0 = time.perf_counter() - floor_direction_transform = ( + t0 = time.perf_counter() + direction_transform = ( plane.get("floorTransform") if plane and plane.get("floorTransform") and float(plane.get("geometryConfidence") or 0.0) >= 0.35 else homography ) - floor_direction = analyze_floor_direction_for_surface_mask( + direction_inputs = floor_direction_geometry_inputs( + surface_mask, + geometry, + plane, + surface_mapping, + use_surface_uv=use_surface_uv, + ) + wall_mask = np.isin(seg_map, class_ids({"wall"})).astype(np.uint8) + structure_mask = np.isin( + seg_map, + class_ids({"wall", "ceiling", "door", "window", "column", "base", "railing"}), + ).astype(np.uint8) + structure_kernel_size = scaled_odd_kernel_size(h, w, 0.006, minimum=3) + structure_kernel = cv2.getStructuringElement( + cv2.MORPH_ELLIPSE, + (structure_kernel_size, structure_kernel_size), + ) + structure_mask = cv2.dilate(structure_mask, structure_kernel, iterations=1) + floor_direction = find_floor_direction( img_np, surface_mask, - render_transform=floor_direction_transform, + wall_mask=wall_mask, + structure_mask=structure_mask, + normals_map=direction_inputs["normalsMap"], + geometry_valid_mask=direction_inputs["validMask"], + intrinsics=direction_inputs["intrinsics"], + floor_normal=direction_inputs["floorNormal"], + render_u_axis=direction_inputs["renderUAxis"], + render_v_axis=direction_inputs["renderVAxis"], + render_transform=direction_transform, surface_uv=surface_mapping["uv"] if use_surface_uv else None, surface_indices=surface_indices if use_surface_uv else None, surface_plane_ids=surface_mapping["planeIds"] if use_surface_uv else None, @@ -3669,18 +3759,20 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non print( "[TIMING] Floor direction analysis took " f"{floor_direction_elapsed:.3f} seconds " - f"(angle={floor_direction.get('angleDegrees')}, confidence={floor_direction.get('confidence')})", + f"(method={floor_direction.get('directionMethod')}, " + f"angle={floor_direction.get('angleDegrees')}, " + f"confidence={floor_direction.get('confidence')})", flush=True, ) if debug is not None: debug.record_images( "floor-direction", "Floor direction", - "Detected floor lines and the resulting texture rotation. This stage is intentionally independent so future direction changes can add metrics or artifacts without changing the viewer.", + "Independent material, 3D wall-normal, and architectural cues are scored in renderer coordinates. Low-evidence images are marked as ambiguous.", [("Direction analysis", debug_floor_direction_overlay(img_np, floor_direction))], floor_direction, floor_direction_elapsed * 1000, - ) + ) t0 = time.perf_counter() segments = [] @@ -3689,11 +3781,15 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non if len(surface_indices) >= min_floor_area: segments.append({ "id": 0, - "className": "floor", - "mask": base64.b64encode(surface_indices.tobytes()).decode(), - "homography": homography, - "floorTransform": plane.get("floorTransform") if plane else None, - "plane": plane, + "className": "floor", + "mask": base64.b64encode(surface_indices.tobytes()).decode(), + "occlusionMask": ( + base64.b64encode(occlusion_indices.tobytes()).decode() + if len(occlusion_indices) else None + ), + "homography": homography, + "floorTransform": plane.get("floorTransform") if plane else None, + "plane": plane, "surfaceUv": ( base64.b64encode(surface_mapping["uv"].astype(np.float32).tobytes()).decode() if use_surface_uv else None @@ -3715,10 +3811,11 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non "metadata": { "segmenter": segmenter_metadata_name(), "segmentationModel": models["segmentation"]["name"], - "floorPixels": int(floor_mask.sum()), - "surfacePixels": int(surface_mask.sum()), - "floorDirection": floor_direction, - **sam_metadata, + "floorPixels": int(floor_mask.sum()), + "surfacePixels": int(surface_mask.sum()), + "occlusionPixels": int(occlusion_mask.sum()), + "floorDirection": floor_direction, + **sam_metadata, **edge_metadata, **mapping_metadata, "depthEnabled": depth is not None, @@ -3738,14 +3835,14 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non "lightingSource": lighting_source, "shadeMapRange": [SHADE_MAP_MIN, SHADE_MAP_MAX], "showroomShadeMapRange": [SHOWROOM_SHADE_MAP_MIN, SHOWROOM_SHADE_MAP_MAX], - "renderPresetDefaults": { - "preset": "realistic", - "shadingStrength": 0.55, - "reflectionTransfer": True, + "renderPresetDefaults": { + "preset": "realistic", + "shadingStrength": 0.55, + "reflectionTransfer": True, "edgeFeatherPixels": 2, }, "reflectionTransferEnabled": reflection_map is not None, - "reflectionMapRange": [REFLECTION_MAP_MIN, REFLECTION_MAP_MAX], + "reflectionMapRange": [REFLECTION_MAP_MIN, REFLECTION_MAP_MAX], "geometryConfidence": plane.get("geometryConfidence", 0.0) if plane else 0.0, "metricGeometry": bool(plane and plane.get("floorTransform")), "geometryProvider": plane.get("geometryProvider", geometry.get("provider")) if plane else geometry.get("provider"), @@ -3780,10 +3877,10 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non }, }) - total_elapsed = time.perf_counter() - t_start - print(f"[TIMING] Total bundle processing completed in {total_elapsed:.3f} seconds", flush=True) - if debug is not None: - debug.complete(total_elapsed * 1000) + total_elapsed = time.perf_counter() - t_start + print(f"[TIMING] Total bundle processing completed in {total_elapsed:.3f} seconds", flush=True) + if debug is not None: + debug.complete(total_elapsed * 1000) return { "width": w, "height": h, @@ -3805,105 +3902,105 @@ def read_job(job_id: str): return json.loads(path.read_text()) -def write_job(job: dict): - job_path(job["id"]).write_text(json.dumps(job)) - - -def spaces_upload_enabled() -> bool: - return bool(SPACES_BUCKET and SPACES_REGION and SPACES_ACCESS_KEY_ID and SPACES_SECRET_ACCESS_KEY) - - -def spaces_endpoint_url() -> str: - return SPACES_ENDPOINT_URL or f"https://{SPACES_REGION}.digitaloceanspaces.com" - - -def spaces_upload_key(job_id: str, upload_path: Path) -> str: - suffix = upload_path.suffix.lower() - if suffix not in {".jpg", ".jpeg", ".png", ".webp"}: - suffix = ".jpg" - date_prefix = time.strftime("%Y/%m/%d", time.gmtime()) - filename = f"{job_id}{suffix}" - return "/".join(part for part in [SPACES_UPLOAD_PREFIX, date_prefix, filename] if part) - - -def upload_input_image_to_spaces( - job_id: str, - upload_path: Path, - original_filename: str | None, - content_type: str | None, -): - if not spaces_upload_enabled(): - return - - try: - import boto3 - from botocore.config import Config - except ImportError: - print("DigitalOcean Spaces upload skipped; install boto3 to enable object storage.", flush=True) - return - - try: - key = spaces_upload_key(job_id, upload_path) - metadata = {"job-id": job_id} - if original_filename: - metadata["original-filename"] = urllib.parse.quote(original_filename)[:900] - - extra_args = { - "ContentType": content_type or "application/octet-stream", - "Metadata": metadata, - } - if SPACES_ACL: - extra_args["ACL"] = SPACES_ACL - - client = boto3.client( - "s3", - region_name=SPACES_REGION, - endpoint_url=spaces_endpoint_url(), - aws_access_key_id=SPACES_ACCESS_KEY_ID, - aws_secret_access_key=SPACES_SECRET_ACCESS_KEY, - config=Config(signature_version="s3v4"), - ) - client.upload_file(str(upload_path), SPACES_BUCKET, key, ExtraArgs=extra_args) - - job = read_job(job_id) - job["inputObjectStorage"] = { - "provider": "digitalocean-spaces", - "bucket": SPACES_BUCKET, - "region": SPACES_REGION, - "key": key, - "endpointUrl": spaces_endpoint_url(), - } - write_job(job) - print(f"Uploaded input image for job {job_id} to DigitalOcean Spaces: {SPACES_BUCKET}/{key}", flush=True) - except Exception as exc: - print(f"DigitalOcean Spaces upload failed for job {job_id}: {exc}", flush=True) - - -def run_conversion_task(job_id: str, upload_path: Path): - debug = PipelineDebugCapture(job_id) if DEBUG_ARTIFACTS_ENABLED else None - try: - t_start = time.perf_counter() - image_bytes = upload_path.read_bytes() - bundle = build_segmentation_bundle(image_bytes, debug=debug) - binary_bundle = build_manifest_segmentation_bundle( - bundle, - job_id, - image_url=f"/uploads/{upload_path.name}", - include_image=False, - ) - (JOB_DIR / f"{job_id}.vizbundle").write_bytes(binary_bundle) - job = read_job(job_id) - job["status"] = "COMPLETED" - job["modelName"] = bundle.get("modelName") - job["models"] = bundle.get("models") - job["outputFormat"] = "split-vizbundle" - write_job(job) - print(f"[TIMING] Background conversion task for job {job_id} took {time.perf_counter() - t_start:.3f} seconds", flush=True) - except Exception as exc: - print(f"Background conversion failed: {exc}", flush=True) - if debug is not None: - debug.fail(exc) - try: +def write_job(job: dict): + job_path(job["id"]).write_text(json.dumps(job)) + + +def spaces_upload_enabled() -> bool: + return bool(SPACES_BUCKET and SPACES_REGION and SPACES_ACCESS_KEY_ID and SPACES_SECRET_ACCESS_KEY) + + +def spaces_endpoint_url() -> str: + return SPACES_ENDPOINT_URL or f"https://{SPACES_REGION}.digitaloceanspaces.com" + + +def spaces_upload_key(job_id: str, upload_path: Path) -> str: + suffix = upload_path.suffix.lower() + if suffix not in {".jpg", ".jpeg", ".png", ".webp"}: + suffix = ".jpg" + date_prefix = time.strftime("%Y/%m/%d", time.gmtime()) + filename = f"{job_id}{suffix}" + return "/".join(part for part in [SPACES_UPLOAD_PREFIX, date_prefix, filename] if part) + + +def upload_input_image_to_spaces( + job_id: str, + upload_path: Path, + original_filename: str | None, + content_type: str | None, +): + if not spaces_upload_enabled(): + return + + try: + import boto3 + from botocore.config import Config + except ImportError: + print("DigitalOcean Spaces upload skipped; install boto3 to enable object storage.", flush=True) + return + + try: + key = spaces_upload_key(job_id, upload_path) + metadata = {"job-id": job_id} + if original_filename: + metadata["original-filename"] = urllib.parse.quote(original_filename)[:900] + + extra_args = { + "ContentType": content_type or "application/octet-stream", + "Metadata": metadata, + } + if SPACES_ACL: + extra_args["ACL"] = SPACES_ACL + + client = boto3.client( + "s3", + region_name=SPACES_REGION, + endpoint_url=spaces_endpoint_url(), + aws_access_key_id=SPACES_ACCESS_KEY_ID, + aws_secret_access_key=SPACES_SECRET_ACCESS_KEY, + config=Config(signature_version="s3v4"), + ) + client.upload_file(str(upload_path), SPACES_BUCKET, key, ExtraArgs=extra_args) + + job = read_job(job_id) + job["inputObjectStorage"] = { + "provider": "digitalocean-spaces", + "bucket": SPACES_BUCKET, + "region": SPACES_REGION, + "key": key, + "endpointUrl": spaces_endpoint_url(), + } + write_job(job) + print(f"Uploaded input image for job {job_id} to DigitalOcean Spaces: {SPACES_BUCKET}/{key}", flush=True) + except Exception as exc: + print(f"DigitalOcean Spaces upload failed for job {job_id}: {exc}", flush=True) + + +def run_conversion_task(job_id: str, upload_path: Path): + debug = PipelineDebugCapture(job_id) if DEBUG_ARTIFACTS_ENABLED else None + try: + t_start = time.perf_counter() + image_bytes = upload_path.read_bytes() + bundle = build_segmentation_bundle(image_bytes, debug=debug) + binary_bundle = build_manifest_segmentation_bundle( + bundle, + job_id, + image_url=f"/uploads/{upload_path.name}", + include_image=False, + ) + (JOB_DIR / f"{job_id}.vizbundle").write_bytes(binary_bundle) + job = read_job(job_id) + job["status"] = "COMPLETED" + job["modelName"] = bundle.get("modelName") + job["models"] = bundle.get("models") + job["outputFormat"] = "split-vizbundle" + write_job(job) + print(f"[TIMING] Background conversion task for job {job_id} took {time.perf_counter() - t_start:.3f} seconds", flush=True) + except Exception as exc: + print(f"Background conversion failed: {exc}", flush=True) + if debug is not None: + debug.fail(exc) + try: job = read_job(job_id) job["status"] = "FAILED" job["error"] = str(exc) @@ -4072,97 +4169,97 @@ async def prepare_material_maps( @app.post("/viz2d/convert") -async def convert_to_viz2d(background_tasks: BackgroundTasks, file: UploadFile = File(...)): - if file.content_type and not file.content_type.startswith("image/"): - raise HTTPException(status_code=400, detail="Upload must be a JPG or PNG image.") - - job_id = uuid.uuid4().hex - original_filename = file.filename - content_type = file.content_type - ext = Path(file.filename or "room.jpg").suffix.lower() - if ext not in {".jpg", ".jpeg", ".png", ".webp"}: - ext = ".jpg" +async def convert_to_viz2d(background_tasks: BackgroundTasks, file: UploadFile = File(...)): + if file.content_type and not file.content_type.startswith("image/"): + raise HTTPException(status_code=400, detail="Upload must be a JPG or PNG image.") + + job_id = uuid.uuid4().hex + original_filename = file.filename + content_type = file.content_type + ext = Path(file.filename or "room.jpg").suffix.lower() + if ext not in {".jpg", ".jpeg", ".png", ".webp"}: + ext = ".jpg" upload_path = UPLOAD_DIR / f"{job_id}{ext}" with upload_path.open("wb") as out: shutil.copyfileobj(file.file, out) - job = { - "id": job_id, - "status": "PROCESSING", - "inputUrl": f"/uploads/{upload_path.name}", - "outputUrl": f"/viz2d/jobs/{job_id}/file", - "debugUrl": f"/viz2d/jobs/{job_id}/debug" if DEBUG_ARTIFACTS_ENABLED else None, - } - write_job(job) - background_tasks.add_task(run_conversion_task, job_id, upload_path) - background_tasks.add_task(upload_input_image_to_spaces, job_id, upload_path, original_filename, content_type) - return job + job = { + "id": job_id, + "status": "PROCESSING", + "inputUrl": f"/uploads/{upload_path.name}", + "outputUrl": f"/viz2d/jobs/{job_id}/file", + "debugUrl": f"/viz2d/jobs/{job_id}/debug" if DEBUG_ARTIFACTS_ENABLED else None, + } + write_job(job) + background_tasks.add_task(run_conversion_task, job_id, upload_path) + background_tasks.add_task(upload_input_image_to_spaces, job_id, upload_path, original_filename, content_type) + return job + + +@app.get("/viz2d/jobs/{job_id}") +async def viz2d_job_status(job_id: str): + return read_job(job_id) + + +@app.get("/viz2d/jobs/{job_id}/debug") +async def viz2d_job_debug(job_id: str): + read_job(job_id) + if not DEBUG_ARTIFACTS_ENABLED: + raise HTTPException(status_code=404, detail="Debug artifacts are disabled on this server.") + manifest_path = JOB_DIR / f"{job_id}.debug" / "manifest.json" + if not manifest_path.exists(): + raise HTTPException(status_code=404, detail="Debug artifacts are not available yet.") + return Response( + content=manifest_path.read_bytes(), + media_type="application/json", + headers={"Cache-Control": "no-store"}, + ) -@app.get("/viz2d/jobs/{job_id}") -async def viz2d_job_status(job_id: str): - return read_job(job_id) - - -@app.get("/viz2d/jobs/{job_id}/debug") -async def viz2d_job_debug(job_id: str): - read_job(job_id) - if not DEBUG_ARTIFACTS_ENABLED: - raise HTTPException(status_code=404, detail="Debug artifacts are disabled on this server.") - manifest_path = JOB_DIR / f"{job_id}.debug" / "manifest.json" - if not manifest_path.exists(): - raise HTTPException(status_code=404, detail="Debug artifacts are not available yet.") - return Response( - content=manifest_path.read_bytes(), - media_type="application/json", - headers={"Cache-Control": "no-store"}, - ) - - -@app.get("/viz2d/jobs/{job_id}/debug/assets/{asset_name}") -async def viz2d_job_debug_asset(job_id: str, asset_name: str): - read_job(job_id) - if Path(asset_name).name != asset_name: - raise HTTPException(status_code=400, detail="Invalid debug asset name.") - asset_path = JOB_DIR / f"{job_id}.debug" / asset_name - if not asset_path.exists() or not asset_path.is_file(): - raise HTTPException(status_code=404, detail="Debug asset not found.") - media_type = "image/jpeg" if asset_path.suffix.lower() in {".jpg", ".jpeg"} else "application/octet-stream" - return Response( - content=asset_path.read_bytes(), - media_type=media_type, - headers={"Cache-Control": "private, max-age=3600"}, - ) +@app.get("/viz2d/jobs/{job_id}/debug/assets/{asset_name}") +async def viz2d_job_debug_asset(job_id: str, asset_name: str): + read_job(job_id) + if Path(asset_name).name != asset_name: + raise HTTPException(status_code=400, detail="Invalid debug asset name.") + asset_path = JOB_DIR / f"{job_id}.debug" / asset_name + if not asset_path.exists() or not asset_path.is_file(): + raise HTTPException(status_code=404, detail="Debug asset not found.") + media_type = "image/jpeg" if asset_path.suffix.lower() in {".jpg", ".jpeg"} else "application/octet-stream" + return Response( + content=asset_path.read_bytes(), + media_type=media_type, + headers={"Cache-Control": "private, max-age=3600"}, + ) @app.get("/viz2d/jobs/{job_id}/file") -async def viz2d_job_file(job_id: str): - job = read_job(job_id) - if job.get("status") != "COMPLETED": - raise HTTPException(status_code=409, detail="Job is not completed yet.") - binary_bundle_path = JOB_DIR / f"{job_id}.vizbundle" - if not binary_bundle_path.exists(): - raise HTTPException(status_code=404, detail="Job output not found.") - return Response( - content=binary_bundle_path.read_bytes(), - media_type="application/zip", - headers={"Content-Disposition": 'attachment; filename="visualizer.vizbundle"'}, - ) - - -@app.get("/viz2d/jobs/{job_id}/assets/{asset_name}") -async def viz2d_job_asset(job_id: str, asset_name: str): - read_job(job_id) - if Path(asset_name).name != asset_name: - raise HTTPException(status_code=400, detail="Invalid asset name.") - asset_path = JOB_DIR / f"{job_id}.assets" / asset_name - if not asset_path.exists() or not asset_path.is_file(): - raise HTTPException(status_code=404, detail="Job asset not found.") - return Response( - content=asset_path.read_bytes(), - media_type="application/octet-stream", - headers={"Cache-Control": "private, max-age=3600"}, - ) +async def viz2d_job_file(job_id: str): + job = read_job(job_id) + if job.get("status") != "COMPLETED": + raise HTTPException(status_code=409, detail="Job is not completed yet.") + binary_bundle_path = JOB_DIR / f"{job_id}.vizbundle" + if not binary_bundle_path.exists(): + raise HTTPException(status_code=404, detail="Job output not found.") + return Response( + content=binary_bundle_path.read_bytes(), + media_type="application/zip", + headers={"Content-Disposition": 'attachment; filename="visualizer.vizbundle"'}, + ) + + +@app.get("/viz2d/jobs/{job_id}/assets/{asset_name}") +async def viz2d_job_asset(job_id: str, asset_name: str): + read_job(job_id) + if Path(asset_name).name != asset_name: + raise HTTPException(status_code=400, detail="Invalid asset name.") + asset_path = JOB_DIR / f"{job_id}.assets" / asset_name + if not asset_path.exists() or not asset_path.is_file(): + raise HTTPException(status_code=404, detail="Job asset not found.") + return Response( + content=asset_path.read_bytes(), + media_type="application/octet-stream", + headers={"Cache-Control": "private, max-age=3600"}, + ) def build_oneformer_polygon_response( @@ -4258,14 +4355,14 @@ def encode_png_data_url(image_bgr: np.ndarray) -> str: return f"data:image/png;base64,{payload}" -def floor_direction_response(result, segmentation) -> dict: +def floor_direction_response(result, segmentation) -> dict: overlay_image_base64 = None if result.overlay_bgr is not None: overlay_image_base64 = encode_png_data_url(result.overlay_bgr) return { - "angle_degrees": result.angle_degrees, - "render_angle_degrees": result.render_angle_degrees, + "angle_degrees": result.angle_degrees, + "render_angle_degrees": result.render_angle_degrees, "secondary_angle_degrees": result.secondary_angle_degrees, "direction_label": result.direction_label, "confidence": result.confidence, @@ -4298,46 +4395,123 @@ def floor_direction_response(result, segmentation) -> dict: def floor_direction_metadata(result, segmentation) -> dict: return { - "source": "backend-floor-direction", - "angleDegrees": result.angle_degrees, - "renderAngleDegrees": result.render_angle_degrees, + "source": "backend-floor-direction", + "angleDegrees": result.angle_degrees, + "renderAngleDegrees": result.render_angle_degrees, "secondaryAngleDegrees": result.secondary_angle_degrees, "directionLabel": result.direction_label, "confidence": result.confidence, "floorAreaRatio": result.floor_area_ratio, "lineCount": result.line_count, - "dominantLineCount": result.dominant_line_count, - "gridPatternDetected": result.grid_pattern_detected, - "warnings": result.warnings, - "dominantLines": [ - { - "x1": line.x1, - "y1": line.y1, - "x2": line.x2, - "y2": line.y2, - "angleDegrees": line.angle_degrees, - "length": line.length, - } - for line in result.dominant_lines - ], - "segmentation": { + "dominantLineCount": result.dominant_line_count, + "gridPatternDetected": result.grid_pattern_detected, + "warnings": result.warnings, + "dominantLines": [ + { + "x1": line.x1, + "y1": line.y1, + "x2": line.x2, + "y2": line.y2, + "angleDegrees": line.angle_degrees, + "length": line.length, + } + for line in result.dominant_lines + ], + "segmentation": { "label": segmentation.label, "confidence": segmentation.confidence, "polygonCount": len(segmentation.polygons), "sourcePath": segmentation.source_path, }, - } - - -def analyze_floor_direction_for_surface_mask( - img_np: np.ndarray, + } + + +def floor_direction_geometry_inputs( surface_mask: np.ndarray, + geometry: dict | None, + plane: dict | None, + surface_mapping: dict | None, *, - render_transform: list[float] | np.ndarray | None = None, - surface_uv: np.ndarray | None = None, - surface_indices: np.ndarray | None = None, - surface_plane_ids: np.ndarray | None = None, + use_surface_uv: bool, ) -> dict: + direction_maps = surface_mapping + if direction_maps is None: + raw_maps = geometry_point_maps(surface_mask, geometry) + if raw_maps is not None: + direction_maps = { + "normalMap": raw_maps["normals"], + "validMask": raw_maps["validMask"], + "intrinsics": raw_maps["intrinsics"], + "planes": [], + } + + normal_map = direction_maps.get("normalMap") if direction_maps else None + valid_mask = direction_maps.get("validMask") if direction_maps else None + intrinsics = direction_maps.get("intrinsics") if direction_maps else None + surface_planes = direction_maps.get("planes") or [] if direction_maps else [] + dominant_floor_plane = None + if surface_planes: + floor_planes = [item for item in surface_planes if item.get("isFloor")] + candidates = floor_planes or surface_planes + dominant_floor_plane = max( + candidates, + key=lambda item: int(item.get("assignedCount") or item.get("inlierCount") or 0), + ) + + floor_normal = None + render_u_axis = None + render_v_axis = None + if use_surface_uv and dominant_floor_plane is not None: + floor_normal = dominant_floor_plane.get("normal") + render_u_axis = dominant_floor_plane.get("uAxis") + render_v_axis = dominant_floor_plane.get("vAxis") + elif plane and plane.get("planeNormal"): + floor_normal = plane.get("planeNormal") + elif dominant_floor_plane is not None: + floor_normal = dominant_floor_plane.get("normal") + + if floor_normal is None and normal_map is not None and normal_map.shape[:2] == surface_mask.shape: + lengths = np.linalg.norm(normal_map, axis=2) + valid_floor = ( + (surface_mask > 0) + & np.isfinite(normal_map).all(axis=2) + & (lengths > 1e-4) + ) + if valid_mask is not None and valid_mask.shape == surface_mask.shape: + valid_floor &= valid_mask.astype(bool) + floor_normals = normal_map[valid_floor] + if len(floor_normals) >= 200: + floor_normals = floor_normals / np.linalg.norm(floor_normals, axis=1, keepdims=True) + reference = np.median(floor_normals, axis=0) + if reference[1] < 0: + reference = -reference + floor_normal = reference.tolist() + + if intrinsics is None and plane and plane.get("cameraIntrinsics"): + intrinsics = np.asarray(plane["cameraIntrinsics"], dtype=np.float32).reshape(3, 3) + if intrinsics is None: + height, width = surface_mask.shape[:2] + intrinsics = default_camera_intrinsics(width, height) + + return { + "normalsMap": normal_map, + "validMask": valid_mask, + "intrinsics": intrinsics, + "floorNormal": floor_normal, + "renderUAxis": render_u_axis, + "renderVAxis": render_v_axis, + } + + +def analyze_floor_direction_for_surface_mask( + img_np: np.ndarray, + surface_mask: np.ndarray, + *, + render_transform: list[float] | np.ndarray | None = None, + surface_uv: np.ndarray | None = None, + surface_indices: np.ndarray | None = None, + surface_plane_ids: np.ndarray | None = None, +) -> dict: h, w = img_np.shape[:2] polygons = mask_to_polygons( surface_mask, @@ -4351,15 +4525,15 @@ def analyze_floor_direction_for_surface_mask( "height": int(h), "polygons": polygons, }) - result = analyze_floor_direction_from_segmentation( - cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR), - floor_segmentation, - include_overlay=False, - render_transform=render_transform, - surface_uv=surface_uv, - surface_indices=surface_indices, - surface_plane_ids=surface_plane_ids, - ) + result = analyze_floor_direction_from_segmentation( + cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR), + floor_segmentation, + include_overlay=False, + render_transform=render_transform, + surface_uv=surface_uv, + surface_indices=surface_indices, + surface_plane_ids=surface_plane_ids, + ) return floor_direction_metadata(result, floor_segmentation)