github-actions[bot] commited on
Commit ·
434eb27
1
Parent(s): b88d338
Automated Deploy: c777e34c31152b9f8587cbce10402dd59c6b454b
Browse files
app.py
CHANGED
|
@@ -232,6 +232,24 @@ BUNDLE_IMAGE_QUALITY = int(config_value(
|
|
| 232 |
"bundle_image_quality",
|
| 233 |
"92",
|
| 234 |
))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
VISUALIZER_DATA_DIR = str(config_value(
|
| 236 |
"VISUALIZER_DATA_DIR",
|
| 237 |
"runtime",
|
|
@@ -633,7 +651,263 @@ MATERIAL_DIR = DATA_DIR / "materials"
|
|
| 633 |
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
| 634 |
JOB_DIR.mkdir(parents=True, exist_ok=True)
|
| 635 |
MATERIAL_DIR.mkdir(parents=True, exist_ok=True)
|
| 636 |
-
app.mount("/uploads", StaticFiles(directory=UPLOAD_DIR), name="uploads")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 637 |
|
| 638 |
PRIMARY_FLOOR_CLASSES = {"floor"}
|
| 639 |
FLOOR_SURFACE_CLASSES = {
|
|
@@ -3116,55 +3390,158 @@ def build_manifest_segmentation_bundle(
|
|
| 3116 |
return buffer.getvalue()
|
| 3117 |
|
| 3118 |
|
| 3119 |
-
def build_segmentation_bundle(contents: bytes):
|
| 3120 |
t_start = time.perf_counter()
|
| 3121 |
-
|
| 3122 |
-
t0 = time.perf_counter()
|
| 3123 |
-
img = Image.open(io.BytesIO(contents)).convert("RGB")
|
| 3124 |
-
img_np = np.array(img)
|
| 3125 |
-
h, w = img_np.shape[:2]
|
| 3126 |
-
min_floor_area = max(1200, int(w * h * 0.015))
|
| 3127 |
-
|
| 3128 |
-
|
| 3129 |
-
|
| 3130 |
-
|
| 3131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3132 |
|
| 3133 |
t0 = time.perf_counter()
|
| 3134 |
pixels_b64 = encode_bundle_image_data_url(img_np)
|
| 3135 |
print(f"[TIMING] Image bundle encoding took {time.perf_counter() - t0:.3f} seconds", flush=True)
|
| 3136 |
|
| 3137 |
-
t0 = time.perf_counter()
|
| 3138 |
-
primary_floor_ids = class_ids(PRIMARY_FLOOR_CLASSES)
|
| 3139 |
-
floor_class_ids = class_ids(FLOOR_SURFACE_CLASSES)
|
| 3140 |
-
|
| 3141 |
-
floor_mask =
|
| 3142 |
-
floor_mask =
|
| 3143 |
-
|
| 3144 |
-
|
| 3145 |
-
|
| 3146 |
-
floor_mask =
|
| 3147 |
-
|
| 3148 |
-
|
| 3149 |
-
|
| 3150 |
-
|
| 3151 |
-
|
| 3152 |
-
|
| 3153 |
-
print(
|
| 3154 |
-
|
| 3155 |
-
|
| 3156 |
-
|
| 3157 |
-
|
| 3158 |
-
|
| 3159 |
-
|
| 3160 |
-
|
| 3161 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3162 |
|
| 3163 |
t0 = time.perf_counter()
|
| 3164 |
-
quad = np.asarray(plane["quad"], dtype=np.float32).reshape(4, 2) if plane and plane.get("quad") else None
|
| 3165 |
-
surface_mask, edge_metadata = build_floor_surface_mask(floor_mask, seg_map, quad, depth, geometry, plane)
|
| 3166 |
-
surface_indices = np.flatnonzero(surface_mask.ravel()).astype(np.uint32)
|
| 3167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3168 |
|
| 3169 |
t0 = time.perf_counter()
|
| 3170 |
surface_mapping = build_surface_uv_mapping(surface_mask, surface_indices, geometry)
|
|
@@ -3189,7 +3566,8 @@ def build_segmentation_bundle(contents: bytes):
|
|
| 3189 |
"surfaceUvAssignedPlaneCount": 0,
|
| 3190 |
}
|
| 3191 |
)
|
| 3192 |
-
|
|
|
|
| 3193 |
print(
|
| 3194 |
"[FLOOR_3D_BUNDLE] serialized derived floor geometry "
|
| 3195 |
f"rawPointMapSent=false floorTransformSent={bool(plane and plane.get('floorTransform'))} "
|
|
@@ -3198,8 +3576,27 @@ def build_segmentation_bundle(contents: bytes):
|
|
| 3198 |
f"{int(len(surface_indices))} "
|
| 3199 |
f"surfacePlaneCount={len(surface_mapping['planes']) if surface_mapping is not None else 0} "
|
| 3200 |
f"geometryProvider={plane.get('geometryProvider', geometry.get('provider')) if plane else geometry.get('provider')}",
|
| 3201 |
-
flush=True,
|
| 3202 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3203 |
|
| 3204 |
t0 = time.perf_counter()
|
| 3205 |
lighting_maps = None
|
|
@@ -3224,12 +3621,33 @@ def build_segmentation_bundle(contents: bytes):
|
|
| 3224 |
shade_map = lighting_maps.get("shadeMap")
|
| 3225 |
showroom_shade_map = lighting_maps.get("showroomShadeMap")
|
| 3226 |
reflection_map = lighting_maps.get("reflectionMap")
|
| 3227 |
-
|
| 3228 |
-
|
| 3229 |
-
|
| 3230 |
-
f"
|
| 3231 |
-
|
| 3232 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3233 |
|
| 3234 |
t0 = time.perf_counter()
|
| 3235 |
floor_direction_transform = (
|
|
@@ -3247,12 +3665,22 @@ def build_segmentation_bundle(contents: bytes):
|
|
| 3247 |
surface_indices=surface_indices if use_surface_uv else None,
|
| 3248 |
surface_plane_ids=surface_mapping["planeIds"] if use_surface_uv else None,
|
| 3249 |
)
|
| 3250 |
-
|
| 3251 |
-
|
| 3252 |
-
|
| 3253 |
-
f"
|
| 3254 |
-
|
| 3255 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3256 |
|
| 3257 |
t0 = time.perf_counter()
|
| 3258 |
segments = []
|
|
@@ -3352,7 +3780,10 @@ def build_segmentation_bundle(contents: bytes):
|
|
| 3352 |
},
|
| 3353 |
})
|
| 3354 |
|
| 3355 |
-
|
|
|
|
|
|
|
|
|
|
| 3356 |
return {
|
| 3357 |
"width": w,
|
| 3358 |
"height": h,
|
|
@@ -3449,10 +3880,11 @@ def upload_input_image_to_spaces(
|
|
| 3449 |
|
| 3450 |
|
| 3451 |
def run_conversion_task(job_id: str, upload_path: Path):
|
|
|
|
| 3452 |
try:
|
| 3453 |
t_start = time.perf_counter()
|
| 3454 |
image_bytes = upload_path.read_bytes()
|
| 3455 |
-
bundle = build_segmentation_bundle(image_bytes)
|
| 3456 |
binary_bundle = build_manifest_segmentation_bundle(
|
| 3457 |
bundle,
|
| 3458 |
job_id,
|
|
@@ -3469,7 +3901,9 @@ def run_conversion_task(job_id: str, upload_path: Path):
|
|
| 3469 |
print(f"[TIMING] Background conversion task for job {job_id} took {time.perf_counter() - t_start:.3f} seconds", flush=True)
|
| 3470 |
except Exception as exc:
|
| 3471 |
print(f"Background conversion failed: {exc}", flush=True)
|
| 3472 |
-
|
|
|
|
|
|
|
| 3473 |
job = read_job(job_id)
|
| 3474 |
job["status"] = "FAILED"
|
| 3475 |
job["error"] = str(exc)
|
|
@@ -3652,11 +4086,12 @@ async def convert_to_viz2d(background_tasks: BackgroundTasks, file: UploadFile =
|
|
| 3652 |
with upload_path.open("wb") as out:
|
| 3653 |
shutil.copyfileobj(file.file, out)
|
| 3654 |
|
| 3655 |
-
job = {
|
| 3656 |
-
"id": job_id,
|
| 3657 |
-
"status": "PROCESSING",
|
| 3658 |
-
"inputUrl": f"/uploads/{upload_path.name}",
|
| 3659 |
-
"outputUrl": f"/viz2d/jobs/{job_id}/file",
|
|
|
|
| 3660 |
}
|
| 3661 |
write_job(job)
|
| 3662 |
background_tasks.add_task(run_conversion_task, job_id, upload_path)
|
|
@@ -3664,9 +4099,40 @@ async def convert_to_viz2d(background_tasks: BackgroundTasks, file: UploadFile =
|
|
| 3664 |
return job
|
| 3665 |
|
| 3666 |
|
| 3667 |
-
@app.get("/viz2d/jobs/{job_id}")
|
| 3668 |
-
async def viz2d_job_status(job_id: str):
|
| 3669 |
-
return read_job(job_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3670 |
|
| 3671 |
|
| 3672 |
@app.get("/viz2d/jobs/{job_id}/file")
|
|
@@ -3831,7 +4297,7 @@ def floor_direction_response(result, segmentation) -> dict:
|
|
| 3831 |
|
| 3832 |
|
| 3833 |
def floor_direction_metadata(result, segmentation) -> dict:
|
| 3834 |
-
return {
|
| 3835 |
"source": "backend-floor-direction",
|
| 3836 |
"angleDegrees": result.angle_degrees,
|
| 3837 |
"renderAngleDegrees": result.render_angle_degrees,
|
|
@@ -3840,10 +4306,21 @@ def floor_direction_metadata(result, segmentation) -> dict:
|
|
| 3840 |
"confidence": result.confidence,
|
| 3841 |
"floorAreaRatio": result.floor_area_ratio,
|
| 3842 |
"lineCount": result.line_count,
|
| 3843 |
-
"dominantLineCount": result.dominant_line_count,
|
| 3844 |
-
"gridPatternDetected": result.grid_pattern_detected,
|
| 3845 |
-
"warnings": result.warnings,
|
| 3846 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3847 |
"label": segmentation.label,
|
| 3848 |
"confidence": segmentation.confidence,
|
| 3849 |
"polygonCount": len(segmentation.polygons),
|
|
|
|
| 232 |
"bundle_image_quality",
|
| 233 |
"92",
|
| 234 |
))
|
| 235 |
+
DEBUG_ARTIFACTS_ENABLED = str(config_value(
|
| 236 |
+
"DEBUG_ARTIFACTS_ENABLED",
|
| 237 |
+
"runtime",
|
| 238 |
+
"debug_artifacts_enabled",
|
| 239 |
+
"1",
|
| 240 |
+
)).lower() in {"1", "true", "yes", "on"}
|
| 241 |
+
DEBUG_ARTIFACTS_MAX_DIMENSION = max(320, int(config_value(
|
| 242 |
+
"DEBUG_ARTIFACTS_MAX_DIMENSION",
|
| 243 |
+
"runtime",
|
| 244 |
+
"debug_artifacts_max_dimension",
|
| 245 |
+
"1600",
|
| 246 |
+
)))
|
| 247 |
+
DEBUG_ARTIFACTS_PREVIEW_DIMENSION = max(320, int(config_value(
|
| 248 |
+
"DEBUG_ARTIFACTS_PREVIEW_DIMENSION",
|
| 249 |
+
"runtime",
|
| 250 |
+
"debug_artifacts_preview_dimension",
|
| 251 |
+
"720",
|
| 252 |
+
)))
|
| 253 |
VISUALIZER_DATA_DIR = str(config_value(
|
| 254 |
"VISUALIZER_DATA_DIR",
|
| 255 |
"runtime",
|
|
|
|
| 651 |
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
| 652 |
JOB_DIR.mkdir(parents=True, exist_ok=True)
|
| 653 |
MATERIAL_DIR.mkdir(parents=True, exist_ok=True)
|
| 654 |
+
app.mount("/uploads", StaticFiles(directory=UPLOAD_DIR), name="uploads")
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
def _debug_resize_rgb(image_rgb: np.ndarray) -> np.ndarray:
|
| 658 |
+
height, width = image_rgb.shape[:2]
|
| 659 |
+
largest = max(height, width)
|
| 660 |
+
if largest <= DEBUG_ARTIFACTS_MAX_DIMENSION:
|
| 661 |
+
return image_rgb
|
| 662 |
+
scale = DEBUG_ARTIFACTS_MAX_DIMENSION / largest
|
| 663 |
+
return cv2.resize(
|
| 664 |
+
image_rgb,
|
| 665 |
+
(max(1, round(width * scale)), max(1, round(height * scale))),
|
| 666 |
+
interpolation=cv2.INTER_AREA,
|
| 667 |
+
)
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
def _debug_preview_rgb(image_rgb: np.ndarray) -> np.ndarray:
|
| 671 |
+
height, width = image_rgb.shape[:2]
|
| 672 |
+
largest = max(height, width)
|
| 673 |
+
if largest <= DEBUG_ARTIFACTS_PREVIEW_DIMENSION:
|
| 674 |
+
return image_rgb
|
| 675 |
+
scale = DEBUG_ARTIFACTS_PREVIEW_DIMENSION / largest
|
| 676 |
+
return cv2.resize(
|
| 677 |
+
image_rgb,
|
| 678 |
+
(max(1, round(width * scale)), max(1, round(height * scale))),
|
| 679 |
+
interpolation=cv2.INTER_AREA,
|
| 680 |
+
)
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
def debug_mask_overlay(
|
| 684 |
+
image_rgb: np.ndarray,
|
| 685 |
+
mask: np.ndarray,
|
| 686 |
+
color: tuple[int, int, int] = (45, 180, 255),
|
| 687 |
+
) -> np.ndarray:
|
| 688 |
+
"""Overlay a binary analysis mask without changing the uploaded image."""
|
| 689 |
+
output = image_rgb.copy()
|
| 690 |
+
valid = mask.astype(bool)
|
| 691 |
+
if valid.any():
|
| 692 |
+
overlay = np.empty_like(output)
|
| 693 |
+
overlay[:] = color
|
| 694 |
+
output[valid] = cv2.addWeighted(output, 0.42, overlay, 0.58, 0)[valid]
|
| 695 |
+
return output
|
| 696 |
+
|
| 697 |
+
|
| 698 |
+
def debug_segmentation_overlay(image_rgb: np.ndarray, seg_map: np.ndarray) -> np.ndarray:
|
| 699 |
+
labels = seg_map.astype(np.int32)
|
| 700 |
+
hsv = np.zeros((*labels.shape, 3), dtype=np.uint8)
|
| 701 |
+
hsv[..., 0] = (labels * 37) % 180
|
| 702 |
+
hsv[..., 1] = 180
|
| 703 |
+
hsv[..., 2] = 255
|
| 704 |
+
colors = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
|
| 705 |
+
return cv2.addWeighted(image_rgb, 0.42, colors, 0.58, 0)
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
def debug_scalar_map(values: np.ndarray, mask: np.ndarray | None = None) -> np.ndarray:
|
| 709 |
+
scalar = values.astype(np.float32)
|
| 710 |
+
finite = np.isfinite(scalar)
|
| 711 |
+
if mask is not None:
|
| 712 |
+
finite &= mask.astype(bool)
|
| 713 |
+
valid = scalar[finite]
|
| 714 |
+
if valid.size == 0:
|
| 715 |
+
return np.zeros((*scalar.shape[:2], 3), dtype=np.uint8)
|
| 716 |
+
low, high = np.percentile(valid, [2, 98])
|
| 717 |
+
if high <= low:
|
| 718 |
+
high = low + 1.0
|
| 719 |
+
normalized = np.clip((scalar - low) / (high - low), 0.0, 1.0)
|
| 720 |
+
normalized[~np.isfinite(normalized)] = 0.0
|
| 721 |
+
output = cv2.applyColorMap(np.round(normalized * 255).astype(np.uint8), cv2.COLORMAP_TURBO)
|
| 722 |
+
output = cv2.cvtColor(output, cv2.COLOR_BGR2RGB)
|
| 723 |
+
if mask is not None:
|
| 724 |
+
output[~mask.astype(bool)] = 0
|
| 725 |
+
return output
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
def debug_plane_overlay(image_rgb: np.ndarray, plane: dict | None) -> np.ndarray:
|
| 729 |
+
output = image_rgb.copy()
|
| 730 |
+
if not plane:
|
| 731 |
+
return output
|
| 732 |
+
raw_quad = plane.get("quad")
|
| 733 |
+
if not isinstance(raw_quad, list) or len(raw_quad) != 8:
|
| 734 |
+
return output
|
| 735 |
+
points = np.asarray(raw_quad, dtype=np.float32).reshape(-1, 2)
|
| 736 |
+
if not np.isfinite(points).all():
|
| 737 |
+
return output
|
| 738 |
+
points_i = np.round(points).astype(np.int32)
|
| 739 |
+
overlay = output.copy()
|
| 740 |
+
cv2.fillConvexPoly(overlay, points_i, (45, 180, 255))
|
| 741 |
+
output = cv2.addWeighted(output, 0.64, overlay, 0.36, 0)
|
| 742 |
+
cv2.polylines(output, [points_i], isClosed=True, color=(255, 255, 255), thickness=3, lineType=cv2.LINE_AA)
|
| 743 |
+
return output
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
def debug_surface_overlay(image_rgb: np.ndarray, floor_mask: np.ndarray, surface_mask: np.ndarray) -> np.ndarray:
|
| 747 |
+
output = image_rgb.copy()
|
| 748 |
+
removed = (floor_mask > 0) & (surface_mask == 0)
|
| 749 |
+
if removed.any():
|
| 750 |
+
red = np.empty_like(output)
|
| 751 |
+
red[:] = (220, 80, 80)
|
| 752 |
+
output[removed] = cv2.addWeighted(output, 0.42, red, 0.58, 0)[removed]
|
| 753 |
+
return debug_mask_overlay(output, surface_mask, (45, 180, 255))
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
def debug_floor_direction_overlay(image_rgb: np.ndarray, floor_direction: dict) -> np.ndarray:
|
| 757 |
+
output = image_rgb.copy()
|
| 758 |
+
for line in floor_direction.get("dominantLines") or []:
|
| 759 |
+
try:
|
| 760 |
+
start = (round(float(line["x1"])), round(float(line["y1"])))
|
| 761 |
+
end = (round(float(line["x2"])), round(float(line["y2"])))
|
| 762 |
+
except (KeyError, TypeError, ValueError):
|
| 763 |
+
continue
|
| 764 |
+
cv2.line(output, start, end, (45, 180, 255), 3, cv2.LINE_AA)
|
| 765 |
+
|
| 766 |
+
label = floor_direction.get("directionLabel") or "unknown"
|
| 767 |
+
angle = floor_direction.get("renderAngleDegrees")
|
| 768 |
+
confidence = floor_direction.get("confidence")
|
| 769 |
+
detail = f"{label}"
|
| 770 |
+
if isinstance(angle, (int, float)):
|
| 771 |
+
detail += f" {angle:.1f} deg"
|
| 772 |
+
if isinstance(confidence, (int, float)):
|
| 773 |
+
detail += f" {confidence:.0%}"
|
| 774 |
+
cv2.putText(output, detail, (16, 34), cv2.FONT_HERSHEY_SIMPLEX, 0.72, (255, 255, 255), 3, cv2.LINE_AA)
|
| 775 |
+
cv2.putText(output, detail, (16, 34), cv2.FONT_HERSHEY_SIMPLEX, 0.72, (25, 25, 25), 1, cv2.LINE_AA)
|
| 776 |
+
return output
|
| 777 |
+
|
| 778 |
+
|
| 779 |
+
def debug_uv_checkerboard(
|
| 780 |
+
height: int,
|
| 781 |
+
width: int,
|
| 782 |
+
surface_indices: np.ndarray,
|
| 783 |
+
uv: np.ndarray,
|
| 784 |
+
) -> np.ndarray:
|
| 785 |
+
output = np.zeros((height, width, 3), dtype=np.uint8)
|
| 786 |
+
valid = np.isfinite(uv).all(axis=1)
|
| 787 |
+
if not valid.any():
|
| 788 |
+
return output
|
| 789 |
+
coords = uv[valid]
|
| 790 |
+
cells = (np.floor(coords[:, 0] * 8) + np.floor(coords[:, 1] * 8)).astype(np.int32)
|
| 791 |
+
colors = np.where((cells % 2)[:, None] == 0, np.array([45, 180, 255]), np.array([45, 80, 180]))
|
| 792 |
+
output.reshape(-1, 3)[surface_indices[valid]] = colors.astype(np.uint8)
|
| 793 |
+
return output
|
| 794 |
+
|
| 795 |
+
|
| 796 |
+
def debug_plane_id_map(
|
| 797 |
+
height: int,
|
| 798 |
+
width: int,
|
| 799 |
+
surface_indices: np.ndarray,
|
| 800 |
+
plane_ids: np.ndarray,
|
| 801 |
+
) -> np.ndarray:
|
| 802 |
+
output = np.zeros((height, width, 3), dtype=np.uint8)
|
| 803 |
+
valid = plane_ids >= 0
|
| 804 |
+
if not valid.any():
|
| 805 |
+
return output
|
| 806 |
+
ids = plane_ids[valid].astype(np.int32)
|
| 807 |
+
hsv = np.zeros((len(ids), 1, 3), dtype=np.uint8)
|
| 808 |
+
hsv[:, 0, 0] = (ids * 47) % 180
|
| 809 |
+
hsv[:, 0, 1] = 190
|
| 810 |
+
hsv[:, 0, 2] = 255
|
| 811 |
+
output.reshape(-1, 3)[surface_indices[valid]] = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB).reshape(-1, 3)
|
| 812 |
+
return output
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
def _debug_json_default(value):
|
| 816 |
+
if isinstance(value, np.generic):
|
| 817 |
+
return value.item()
|
| 818 |
+
if isinstance(value, np.ndarray):
|
| 819 |
+
return value.tolist()
|
| 820 |
+
raise TypeError(f"Unsupported debug manifest value: {type(value).__name__}")
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
class PipelineDebugCapture:
|
| 824 |
+
"""Writes a generic, versioned inspection manifest alongside a conversion job."""
|
| 825 |
+
|
| 826 |
+
def __init__(self, job_id: str):
|
| 827 |
+
self.job_id = job_id
|
| 828 |
+
self.root = JOB_DIR / f"{job_id}.debug"
|
| 829 |
+
self.root.mkdir(parents=True, exist_ok=True)
|
| 830 |
+
self.manifest_path = self.root / "manifest.json"
|
| 831 |
+
self.manifest = {
|
| 832 |
+
"schemaVersion": 2,
|
| 833 |
+
"jobId": job_id,
|
| 834 |
+
"status": "PROCESSING",
|
| 835 |
+
"stages": [],
|
| 836 |
+
}
|
| 837 |
+
self._write_manifest()
|
| 838 |
+
|
| 839 |
+
def _write_manifest(self):
|
| 840 |
+
self.manifest["updatedAtMs"] = int(time.time() * 1000)
|
| 841 |
+
self.manifest_path.write_text(
|
| 842 |
+
json.dumps(self.manifest, separators=(",", ":"), default=_debug_json_default),
|
| 843 |
+
encoding="utf-8",
|
| 844 |
+
)
|
| 845 |
+
|
| 846 |
+
def record_images(
|
| 847 |
+
self,
|
| 848 |
+
stage_id: str,
|
| 849 |
+
title: str,
|
| 850 |
+
description: str,
|
| 851 |
+
images: list[tuple[str, np.ndarray]],
|
| 852 |
+
metrics: dict | None = None,
|
| 853 |
+
elapsed_ms: float | None = None,
|
| 854 |
+
):
|
| 855 |
+
if not DEBUG_ARTIFACTS_ENABLED:
|
| 856 |
+
return
|
| 857 |
+
try:
|
| 858 |
+
artifacts = []
|
| 859 |
+
for index, (label, image_rgb) in enumerate(images):
|
| 860 |
+
filename = f"{len(self.manifest['stages']) + 1:02d}-{stage_id}-{index + 1}.jpg"
|
| 861 |
+
image_rgb = _debug_resize_rgb(image_rgb)
|
| 862 |
+
ok, encoded = cv2.imencode(".jpg", cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR), [cv2.IMWRITE_JPEG_QUALITY, 90])
|
| 863 |
+
if not ok:
|
| 864 |
+
continue
|
| 865 |
+
(self.root / filename).write_bytes(encoded.tobytes())
|
| 866 |
+
preview_filename = f"{filename[:-4]}.preview.jpg"
|
| 867 |
+
preview_rgb = _debug_preview_rgb(image_rgb)
|
| 868 |
+
preview_ok, preview_encoded = cv2.imencode(
|
| 869 |
+
".jpg",
|
| 870 |
+
cv2.cvtColor(preview_rgb, cv2.COLOR_RGB2BGR),
|
| 871 |
+
[cv2.IMWRITE_JPEG_QUALITY, 82],
|
| 872 |
+
)
|
| 873 |
+
if preview_ok:
|
| 874 |
+
(self.root / preview_filename).write_bytes(preview_encoded.tobytes())
|
| 875 |
+
artifacts.append({
|
| 876 |
+
"type": "image",
|
| 877 |
+
"label": label,
|
| 878 |
+
"url": f"/viz2d/jobs/{self.job_id}/debug/assets/{filename}",
|
| 879 |
+
"previewUrl": (
|
| 880 |
+
f"/viz2d/jobs/{self.job_id}/debug/assets/{preview_filename}"
|
| 881 |
+
if preview_ok else None
|
| 882 |
+
),
|
| 883 |
+
})
|
| 884 |
+
stage = {
|
| 885 |
+
"id": stage_id,
|
| 886 |
+
"title": title,
|
| 887 |
+
"description": description,
|
| 888 |
+
"artifacts": artifacts,
|
| 889 |
+
"metrics": metrics or {},
|
| 890 |
+
}
|
| 891 |
+
if elapsed_ms is not None:
|
| 892 |
+
stage["elapsedMs"] = round(float(elapsed_ms), 1)
|
| 893 |
+
self.manifest["stages"].append(stage)
|
| 894 |
+
self._write_manifest()
|
| 895 |
+
except Exception as exc:
|
| 896 |
+
print(f"[DEBUG] Could not capture {stage_id} for job {self.job_id}: {exc}", flush=True)
|
| 897 |
+
|
| 898 |
+
def complete(self, total_elapsed_ms: float):
|
| 899 |
+
if not DEBUG_ARTIFACTS_ENABLED:
|
| 900 |
+
return
|
| 901 |
+
self.manifest["status"] = "COMPLETED"
|
| 902 |
+
self.manifest["totalElapsedMs"] = round(float(total_elapsed_ms), 1)
|
| 903 |
+
self._write_manifest()
|
| 904 |
+
|
| 905 |
+
def fail(self, error: Exception):
|
| 906 |
+
if not DEBUG_ARTIFACTS_ENABLED:
|
| 907 |
+
return
|
| 908 |
+
self.manifest["status"] = "FAILED"
|
| 909 |
+
self.manifest["error"] = str(error)
|
| 910 |
+
self._write_manifest()
|
| 911 |
|
| 912 |
PRIMARY_FLOOR_CLASSES = {"floor"}
|
| 913 |
FLOOR_SURFACE_CLASSES = {
|
|
|
|
| 3390 |
return buffer.getvalue()
|
| 3391 |
|
| 3392 |
|
| 3393 |
+
def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | None = None):
|
| 3394 |
t_start = time.perf_counter()
|
| 3395 |
+
|
| 3396 |
+
t0 = time.perf_counter()
|
| 3397 |
+
img = Image.open(io.BytesIO(contents)).convert("RGB")
|
| 3398 |
+
img_np = np.array(img)
|
| 3399 |
+
h, w = img_np.shape[:2]
|
| 3400 |
+
min_floor_area = max(1200, int(w * h * 0.015))
|
| 3401 |
+
image_loading_elapsed = time.perf_counter() - t0
|
| 3402 |
+
print(f"[TIMING] Image loading/parsing took {image_loading_elapsed:.3f} seconds", flush=True)
|
| 3403 |
+
if debug is not None:
|
| 3404 |
+
debug.record_images(
|
| 3405 |
+
"source-image",
|
| 3406 |
+
"Uploaded image",
|
| 3407 |
+
"The RGB image passed to the analysis pipeline.",
|
| 3408 |
+
[("Source", img_np)],
|
| 3409 |
+
{"width": int(w), "height": int(h), "minimumFloorPixels": int(min_floor_area)},
|
| 3410 |
+
image_loading_elapsed * 1000,
|
| 3411 |
+
)
|
| 3412 |
+
|
| 3413 |
+
t0 = time.perf_counter()
|
| 3414 |
+
seg_map = run_segmentation(img, img_np)
|
| 3415 |
+
segmentation_elapsed = time.perf_counter() - t0
|
| 3416 |
+
print(f"[TIMING] Floor segmentation took {segmentation_elapsed:.3f} seconds", flush=True)
|
| 3417 |
+
if debug is not None:
|
| 3418 |
+
label_ids, label_counts = np.unique(seg_map, return_counts=True)
|
| 3419 |
+
class_areas = {
|
| 3420 |
+
class_name_for_id(int(label_id)): int(pixel_count)
|
| 3421 |
+
for label_id, pixel_count in zip(label_ids, label_counts)
|
| 3422 |
+
if int(pixel_count) >= max(128, int(w * h * 0.001))
|
| 3423 |
+
}
|
| 3424 |
+
debug.record_images(
|
| 3425 |
+
"semantic-segmentation",
|
| 3426 |
+
"Semantic segmentation",
|
| 3427 |
+
"Colour overlay of the ADE20K semantic labels used to find the floor and reject room objects.",
|
| 3428 |
+
[("Class overlay", debug_segmentation_overlay(img_np, seg_map))],
|
| 3429 |
+
{
|
| 3430 |
+
"backend": segmentation_backend,
|
| 3431 |
+
"model": active_segmentation_model_name(),
|
| 3432 |
+
"classPixels": class_areas,
|
| 3433 |
+
},
|
| 3434 |
+
segmentation_elapsed * 1000,
|
| 3435 |
+
)
|
| 3436 |
|
| 3437 |
t0 = time.perf_counter()
|
| 3438 |
pixels_b64 = encode_bundle_image_data_url(img_np)
|
| 3439 |
print(f"[TIMING] Image bundle encoding took {time.perf_counter() - t0:.3f} seconds", flush=True)
|
| 3440 |
|
| 3441 |
+
t0 = time.perf_counter()
|
| 3442 |
+
primary_floor_ids = class_ids(PRIMARY_FLOOR_CLASSES)
|
| 3443 |
+
floor_class_ids = class_ids(FLOOR_SURFACE_CLASSES)
|
| 3444 |
+
raw_primary_floor_mask = np.isin(seg_map, primary_floor_ids).astype(np.uint8)
|
| 3445 |
+
floor_mask = raw_primary_floor_mask.copy()
|
| 3446 |
+
floor_mask = wall_subtract(floor_mask, seg_map, dilation=1)
|
| 3447 |
+
floor_mask = clean_floor_mask(floor_mask)
|
| 3448 |
+
floor_mask_source = "primary-floor"
|
| 3449 |
+
if int(floor_mask.sum()) < min_floor_area:
|
| 3450 |
+
floor_mask = np.isin(seg_map, floor_class_ids).astype(np.uint8)
|
| 3451 |
+
floor_mask = wall_subtract(floor_mask, seg_map, dilation=1)
|
| 3452 |
+
floor_mask = clean_floor_mask(floor_mask)
|
| 3453 |
+
floor_mask_source = "floor-surface-fallback"
|
| 3454 |
+
cleaned_floor_mask = floor_mask.copy()
|
| 3455 |
+
floor_mask, sam_metadata = refine_floor_mask_with_sam2(img_np, floor_mask, seg_map)
|
| 3456 |
+
floor_mask_elapsed = time.perf_counter() - t0
|
| 3457 |
+
print(f"[TIMING] Floor masking/cleanup took {floor_mask_elapsed:.3f} seconds", flush=True)
|
| 3458 |
+
if debug is not None:
|
| 3459 |
+
debug.record_images(
|
| 3460 |
+
"floor-mask",
|
| 3461 |
+
"Floor mask selection",
|
| 3462 |
+
"Compare the raw floor prediction with cleanup and optional SAM refinement before geometry is estimated.",
|
| 3463 |
+
[
|
| 3464 |
+
("Raw floor class", debug_mask_overlay(img_np, raw_primary_floor_mask)),
|
| 3465 |
+
("Cleaned candidate", debug_mask_overlay(img_np, cleaned_floor_mask)),
|
| 3466 |
+
("Final floor mask", debug_mask_overlay(img_np, floor_mask)),
|
| 3467 |
+
],
|
| 3468 |
+
{
|
| 3469 |
+
"selection": floor_mask_source,
|
| 3470 |
+
"rawFloorPixels": int(raw_primary_floor_mask.sum()),
|
| 3471 |
+
"cleanedFloorPixels": int(cleaned_floor_mask.sum()),
|
| 3472 |
+
"finalFloorPixels": int(floor_mask.sum()),
|
| 3473 |
+
**sam_metadata,
|
| 3474 |
+
},
|
| 3475 |
+
floor_mask_elapsed * 1000,
|
| 3476 |
+
)
|
| 3477 |
+
|
| 3478 |
+
t0 = time.perf_counter()
|
| 3479 |
+
geometry = estimate_scene_geometry(img, img_np, w, h)
|
| 3480 |
+
depth = geometry.get("depth")
|
| 3481 |
+
geometry_elapsed = time.perf_counter() - t0
|
| 3482 |
+
print(
|
| 3483 |
+
f"[TIMING] Geometry estimation ({geometry.get('provider')}) took "
|
| 3484 |
+
f"{geometry_elapsed:.3f} seconds",
|
| 3485 |
+
flush=True,
|
| 3486 |
+
)
|
| 3487 |
+
if debug is not None:
|
| 3488 |
+
geometry_images: list[tuple[str, np.ndarray]] = []
|
| 3489 |
+
if depth is not None:
|
| 3490 |
+
geometry_images.append(("Depth", debug_scalar_map(depth, floor_mask)))
|
| 3491 |
+
debug.record_images(
|
| 3492 |
+
"scene-geometry",
|
| 3493 |
+
"Scene geometry",
|
| 3494 |
+
"Depth or metric geometry used to fit and validate the floor plane.",
|
| 3495 |
+
geometry_images,
|
| 3496 |
+
{
|
| 3497 |
+
"provider": geometry.get("provider"),
|
| 3498 |
+
"depthAvailable": depth is not None,
|
| 3499 |
+
"metric": bool(geometry.get("metric")),
|
| 3500 |
+
},
|
| 3501 |
+
geometry_elapsed * 1000,
|
| 3502 |
+
)
|
| 3503 |
+
|
| 3504 |
+
t0 = time.perf_counter()
|
| 3505 |
+
homography, plane = estimate_floor_plane(floor_mask, img_np, geometry)
|
| 3506 |
+
plane_elapsed = time.perf_counter() - t0
|
| 3507 |
+
print(f"[TIMING] Plane fitting / homography calculation took {plane_elapsed:.3f} seconds", flush=True)
|
| 3508 |
+
if debug is not None:
|
| 3509 |
+
debug.record_images(
|
| 3510 |
+
"floor-plane",
|
| 3511 |
+
"Floor plane and perspective",
|
| 3512 |
+
"The fitted floor quadrilateral is the source of the perspective transform used for tile placement.",
|
| 3513 |
+
[("Fitted quadrilateral", debug_plane_overlay(img_np, plane))],
|
| 3514 |
+
{
|
| 3515 |
+
"planeFound": plane is not None,
|
| 3516 |
+
"homographyAvailable": homography is not None,
|
| 3517 |
+
"geometryProvider": plane.get("geometryProvider") if plane else None,
|
| 3518 |
+
"geometryConfidence": plane.get("geometryConfidence") if plane else 0.0,
|
| 3519 |
+
"metricGeometry": bool(plane and plane.get("floorTransform")),
|
| 3520 |
+
"quad": plane.get("quad") if plane else None,
|
| 3521 |
+
},
|
| 3522 |
+
plane_elapsed * 1000,
|
| 3523 |
+
)
|
| 3524 |
|
| 3525 |
t0 = time.perf_counter()
|
| 3526 |
+
quad = np.asarray(plane["quad"], dtype=np.float32).reshape(4, 2) if plane and plane.get("quad") else None
|
| 3527 |
+
surface_mask, edge_metadata = build_floor_surface_mask(floor_mask, seg_map, quad, depth, geometry, plane)
|
| 3528 |
+
surface_indices = np.flatnonzero(surface_mask.ravel()).astype(np.uint32)
|
| 3529 |
+
surface_mask_elapsed = time.perf_counter() - t0
|
| 3530 |
+
print(f"[TIMING] Surface masking took {surface_mask_elapsed:.3f} seconds", flush=True)
|
| 3531 |
+
if debug is not None:
|
| 3532 |
+
debug.record_images(
|
| 3533 |
+
"renderable-surface",
|
| 3534 |
+
"Renderable floor surface",
|
| 3535 |
+
"Gold pixels are retained for rendering; red pixels were part of the floor mask but removed by protection, edge, or geometry filters.",
|
| 3536 |
+
[("Final surface", debug_surface_overlay(img_np, floor_mask, surface_mask))],
|
| 3537 |
+
{
|
| 3538 |
+
"floorPixels": int(floor_mask.sum()),
|
| 3539 |
+
"surfacePixels": int(surface_mask.sum()),
|
| 3540 |
+
"surfaceCoverage": round(float(surface_mask.sum()) / max(int(floor_mask.sum()), 1), 4),
|
| 3541 |
+
**edge_metadata,
|
| 3542 |
+
},
|
| 3543 |
+
surface_mask_elapsed * 1000,
|
| 3544 |
+
)
|
| 3545 |
|
| 3546 |
t0 = time.perf_counter()
|
| 3547 |
surface_mapping = build_surface_uv_mapping(surface_mask, surface_indices, geometry)
|
|
|
|
| 3566 |
"surfaceUvAssignedPlaneCount": 0,
|
| 3567 |
}
|
| 3568 |
)
|
| 3569 |
+
surface_mapping_elapsed = time.perf_counter() - t0
|
| 3570 |
+
print(f"[TIMING] Multi-plane surface mapping took {surface_mapping_elapsed:.3f} seconds", flush=True)
|
| 3571 |
print(
|
| 3572 |
"[FLOOR_3D_BUNDLE] serialized derived floor geometry "
|
| 3573 |
f"rawPointMapSent=false floorTransformSent={bool(plane and plane.get('floorTransform'))} "
|
|
|
|
| 3576 |
f"{int(len(surface_indices))} "
|
| 3577 |
f"surfacePlaneCount={len(surface_mapping['planes']) if surface_mapping is not None else 0} "
|
| 3578 |
f"geometryProvider={plane.get('geometryProvider', geometry.get('provider')) if plane else geometry.get('provider')}",
|
| 3579 |
+
flush=True,
|
| 3580 |
+
)
|
| 3581 |
+
if debug is not None:
|
| 3582 |
+
mapping_images: list[tuple[str, np.ndarray]] = []
|
| 3583 |
+
if use_surface_uv:
|
| 3584 |
+
mapping_images.append((
|
| 3585 |
+
"UV checkerboard",
|
| 3586 |
+
debug_uv_checkerboard(h, w, surface_indices, surface_mapping["uv"]),
|
| 3587 |
+
))
|
| 3588 |
+
mapping_images.append((
|
| 3589 |
+
"Surface planes",
|
| 3590 |
+
debug_plane_id_map(h, w, surface_indices, surface_mapping["planeIds"]),
|
| 3591 |
+
))
|
| 3592 |
+
debug.record_images(
|
| 3593 |
+
"surface-mapping",
|
| 3594 |
+
"Texture-coordinate mapping",
|
| 3595 |
+
"The checkerboard shows the coordinates sent to the renderer. Plane colours identify separately fitted surface planes.",
|
| 3596 |
+
mapping_images,
|
| 3597 |
+
mapping_metadata,
|
| 3598 |
+
surface_mapping_elapsed * 1000,
|
| 3599 |
+
)
|
| 3600 |
|
| 3601 |
t0 = time.perf_counter()
|
| 3602 |
lighting_maps = None
|
|
|
|
| 3621 |
shade_map = lighting_maps.get("shadeMap")
|
| 3622 |
showroom_shade_map = lighting_maps.get("showroomShadeMap")
|
| 3623 |
reflection_map = lighting_maps.get("reflectionMap")
|
| 3624 |
+
lighting_elapsed = time.perf_counter() - t0
|
| 3625 |
+
print(
|
| 3626 |
+
"[TIMING] Lighting map construction took "
|
| 3627 |
+
f"{lighting_elapsed:.3f} seconds "
|
| 3628 |
+
f"(source={lighting_source}, reflections={reflection_map is not None})",
|
| 3629 |
+
flush=True,
|
| 3630 |
+
)
|
| 3631 |
+
if debug is not None:
|
| 3632 |
+
lighting_images: list[tuple[str, np.ndarray]] = []
|
| 3633 |
+
if shade_map is not None:
|
| 3634 |
+
lighting_images.append(("Shade map", debug_scalar_map(shade_map, surface_mask)))
|
| 3635 |
+
if showroom_shade_map is not None:
|
| 3636 |
+
lighting_images.append(("Showroom shade map", debug_scalar_map(showroom_shade_map, surface_mask)))
|
| 3637 |
+
if reflection_map is not None:
|
| 3638 |
+
lighting_images.append(("Reflection map", debug_scalar_map(reflection_map, surface_mask)))
|
| 3639 |
+
debug.record_images(
|
| 3640 |
+
"lighting-transfer",
|
| 3641 |
+
"Lighting and reflections",
|
| 3642 |
+
"Maps transferred from the room image to make the replacement material fit its surrounding light.",
|
| 3643 |
+
lighting_images,
|
| 3644 |
+
{
|
| 3645 |
+
"source": lighting_source,
|
| 3646 |
+
"shadingAvailable": shade_map is not None,
|
| 3647 |
+
"reflectionsAvailable": reflection_map is not None,
|
| 3648 |
+
},
|
| 3649 |
+
lighting_elapsed * 1000,
|
| 3650 |
+
)
|
| 3651 |
|
| 3652 |
t0 = time.perf_counter()
|
| 3653 |
floor_direction_transform = (
|
|
|
|
| 3665 |
surface_indices=surface_indices if use_surface_uv else None,
|
| 3666 |
surface_plane_ids=surface_mapping["planeIds"] if use_surface_uv else None,
|
| 3667 |
)
|
| 3668 |
+
floor_direction_elapsed = time.perf_counter() - t0
|
| 3669 |
+
print(
|
| 3670 |
+
"[TIMING] Floor direction analysis took "
|
| 3671 |
+
f"{floor_direction_elapsed:.3f} seconds "
|
| 3672 |
+
f"(angle={floor_direction.get('angleDegrees')}, confidence={floor_direction.get('confidence')})",
|
| 3673 |
+
flush=True,
|
| 3674 |
+
)
|
| 3675 |
+
if debug is not None:
|
| 3676 |
+
debug.record_images(
|
| 3677 |
+
"floor-direction",
|
| 3678 |
+
"Floor direction",
|
| 3679 |
+
"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.",
|
| 3680 |
+
[("Direction analysis", debug_floor_direction_overlay(img_np, floor_direction))],
|
| 3681 |
+
floor_direction,
|
| 3682 |
+
floor_direction_elapsed * 1000,
|
| 3683 |
+
)
|
| 3684 |
|
| 3685 |
t0 = time.perf_counter()
|
| 3686 |
segments = []
|
|
|
|
| 3780 |
},
|
| 3781 |
})
|
| 3782 |
|
| 3783 |
+
total_elapsed = time.perf_counter() - t_start
|
| 3784 |
+
print(f"[TIMING] Total bundle processing completed in {total_elapsed:.3f} seconds", flush=True)
|
| 3785 |
+
if debug is not None:
|
| 3786 |
+
debug.complete(total_elapsed * 1000)
|
| 3787 |
return {
|
| 3788 |
"width": w,
|
| 3789 |
"height": h,
|
|
|
|
| 3880 |
|
| 3881 |
|
| 3882 |
def run_conversion_task(job_id: str, upload_path: Path):
|
| 3883 |
+
debug = PipelineDebugCapture(job_id) if DEBUG_ARTIFACTS_ENABLED else None
|
| 3884 |
try:
|
| 3885 |
t_start = time.perf_counter()
|
| 3886 |
image_bytes = upload_path.read_bytes()
|
| 3887 |
+
bundle = build_segmentation_bundle(image_bytes, debug=debug)
|
| 3888 |
binary_bundle = build_manifest_segmentation_bundle(
|
| 3889 |
bundle,
|
| 3890 |
job_id,
|
|
|
|
| 3901 |
print(f"[TIMING] Background conversion task for job {job_id} took {time.perf_counter() - t_start:.3f} seconds", flush=True)
|
| 3902 |
except Exception as exc:
|
| 3903 |
print(f"Background conversion failed: {exc}", flush=True)
|
| 3904 |
+
if debug is not None:
|
| 3905 |
+
debug.fail(exc)
|
| 3906 |
+
try:
|
| 3907 |
job = read_job(job_id)
|
| 3908 |
job["status"] = "FAILED"
|
| 3909 |
job["error"] = str(exc)
|
|
|
|
| 4086 |
with upload_path.open("wb") as out:
|
| 4087 |
shutil.copyfileobj(file.file, out)
|
| 4088 |
|
| 4089 |
+
job = {
|
| 4090 |
+
"id": job_id,
|
| 4091 |
+
"status": "PROCESSING",
|
| 4092 |
+
"inputUrl": f"/uploads/{upload_path.name}",
|
| 4093 |
+
"outputUrl": f"/viz2d/jobs/{job_id}/file",
|
| 4094 |
+
"debugUrl": f"/viz2d/jobs/{job_id}/debug" if DEBUG_ARTIFACTS_ENABLED else None,
|
| 4095 |
}
|
| 4096 |
write_job(job)
|
| 4097 |
background_tasks.add_task(run_conversion_task, job_id, upload_path)
|
|
|
|
| 4099 |
return job
|
| 4100 |
|
| 4101 |
|
| 4102 |
+
@app.get("/viz2d/jobs/{job_id}")
|
| 4103 |
+
async def viz2d_job_status(job_id: str):
|
| 4104 |
+
return read_job(job_id)
|
| 4105 |
+
|
| 4106 |
+
|
| 4107 |
+
@app.get("/viz2d/jobs/{job_id}/debug")
|
| 4108 |
+
async def viz2d_job_debug(job_id: str):
|
| 4109 |
+
read_job(job_id)
|
| 4110 |
+
if not DEBUG_ARTIFACTS_ENABLED:
|
| 4111 |
+
raise HTTPException(status_code=404, detail="Debug artifacts are disabled on this server.")
|
| 4112 |
+
manifest_path = JOB_DIR / f"{job_id}.debug" / "manifest.json"
|
| 4113 |
+
if not manifest_path.exists():
|
| 4114 |
+
raise HTTPException(status_code=404, detail="Debug artifacts are not available yet.")
|
| 4115 |
+
return Response(
|
| 4116 |
+
content=manifest_path.read_bytes(),
|
| 4117 |
+
media_type="application/json",
|
| 4118 |
+
headers={"Cache-Control": "no-store"},
|
| 4119 |
+
)
|
| 4120 |
+
|
| 4121 |
+
|
| 4122 |
+
@app.get("/viz2d/jobs/{job_id}/debug/assets/{asset_name}")
|
| 4123 |
+
async def viz2d_job_debug_asset(job_id: str, asset_name: str):
|
| 4124 |
+
read_job(job_id)
|
| 4125 |
+
if Path(asset_name).name != asset_name:
|
| 4126 |
+
raise HTTPException(status_code=400, detail="Invalid debug asset name.")
|
| 4127 |
+
asset_path = JOB_DIR / f"{job_id}.debug" / asset_name
|
| 4128 |
+
if not asset_path.exists() or not asset_path.is_file():
|
| 4129 |
+
raise HTTPException(status_code=404, detail="Debug asset not found.")
|
| 4130 |
+
media_type = "image/jpeg" if asset_path.suffix.lower() in {".jpg", ".jpeg"} else "application/octet-stream"
|
| 4131 |
+
return Response(
|
| 4132 |
+
content=asset_path.read_bytes(),
|
| 4133 |
+
media_type=media_type,
|
| 4134 |
+
headers={"Cache-Control": "private, max-age=3600"},
|
| 4135 |
+
)
|
| 4136 |
|
| 4137 |
|
| 4138 |
@app.get("/viz2d/jobs/{job_id}/file")
|
|
|
|
| 4297 |
|
| 4298 |
|
| 4299 |
def floor_direction_metadata(result, segmentation) -> dict:
|
| 4300 |
+
return {
|
| 4301 |
"source": "backend-floor-direction",
|
| 4302 |
"angleDegrees": result.angle_degrees,
|
| 4303 |
"renderAngleDegrees": result.render_angle_degrees,
|
|
|
|
| 4306 |
"confidence": result.confidence,
|
| 4307 |
"floorAreaRatio": result.floor_area_ratio,
|
| 4308 |
"lineCount": result.line_count,
|
| 4309 |
+
"dominantLineCount": result.dominant_line_count,
|
| 4310 |
+
"gridPatternDetected": result.grid_pattern_detected,
|
| 4311 |
+
"warnings": result.warnings,
|
| 4312 |
+
"dominantLines": [
|
| 4313 |
+
{
|
| 4314 |
+
"x1": line.x1,
|
| 4315 |
+
"y1": line.y1,
|
| 4316 |
+
"x2": line.x2,
|
| 4317 |
+
"y2": line.y2,
|
| 4318 |
+
"angleDegrees": line.angle_degrees,
|
| 4319 |
+
"length": line.length,
|
| 4320 |
+
}
|
| 4321 |
+
for line in result.dominant_lines
|
| 4322 |
+
],
|
| 4323 |
+
"segmentation": {
|
| 4324 |
"label": segmentation.label,
|
| 4325 |
"confidence": segmentation.confidence,
|
| 4326 |
"polygonCount": len(segmentation.polygons),
|