github-actions[bot] commited on
Commit
c97431f
·
1 Parent(s): c591d3d

Automated Deploy: 909dd51229176b0c49faf7e3156f93b4eebe8cd7

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
.gitignore CHANGED
@@ -47,3 +47,4 @@ node_modules/
47
  playwright-report/
48
  test-results/
49
  *.tsbuildinfo
 
 
47
  playwright-report/
48
  test-results/
49
  *.tsbuildinfo
50
+ data/
app.py CHANGED
The diff for this file is too large to render. See raw diff
 
app_old.py ADDED
The diff for this file is too large to render. See raw diff
 
config/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Config package for floor visualizer backend.
config/gemini.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from config.loader import config_value
2
+
3
+ GEMINI_API_KEY = str(config_value(
4
+ "GEMINI_API_KEY", "gemini", "api_key", "",
5
+ )).strip()
6
+
7
+ GEMINI_IMAGE_MODEL = str(config_value(
8
+ "GEMINI_IMAGE_MODEL", "gemini", "image_model", "gemini-3.1-flash-image",
9
+ )).strip()
10
+
11
+ GEMINI_API_BASE_URL = str(config_value(
12
+ "GEMINI_API_BASE_URL", "gemini", "api_base_url",
13
+ "https://generativelanguage.googleapis.com/v1/models",
14
+ )).rstrip("/")
15
+
16
+ GEMINI_TIMEOUT_SECONDS = float(config_value(
17
+ "GEMINI_TIMEOUT_SECONDS", "gemini", "timeout_seconds", "120",
18
+ ))
config/lighting.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ LIGHTING_TRANSFER_VERSION = 4
2
+
3
+ SHADE_MAP_MIN = 0.08
4
+ SHADE_MAP_MAX = 1.85
5
+ SHOWROOM_SHADE_MAP_MIN = 0.85
6
+ SHOWROOM_SHADE_MAP_MAX = 1.12
7
+ SHADE_MAP_ENCODING = "linear-relative"
8
+
9
+ REFLECTION_MAP_MIN = 0.0
10
+ REFLECTION_MAP_MAX = 1.0
config/loader.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+
4
+ try:
5
+ import tomllib
6
+ except ImportError:
7
+ try:
8
+ import tomli as tomllib # type: ignore[no-redef]
9
+ except ImportError:
10
+ try:
11
+ import tomlkit as tomllib # type: ignore[no-redef]
12
+ except ImportError:
13
+ raise ImportError(
14
+ "No TOML library found. Please run on Python 3.11+, "
15
+ "or run 'pip install tomli' to support Python 3.10."
16
+ )
17
+
18
+ try:
19
+ from dotenv import load_dotenv
20
+ except ImportError:
21
+ load_dotenv = None
22
+
23
+ BACKEND_DIR = Path(__file__).resolve().parent.parent
24
+ REPO_ROOT = BACKEND_DIR.parent.parent
25
+
26
+ if load_dotenv is not None:
27
+ load_dotenv(BACKEND_DIR / ".env")
28
+
29
+
30
+ def load_config() -> dict:
31
+ config_path = os.getenv("VISUALIZER_CONFIG")
32
+ if not config_path:
33
+ return {}
34
+ path = Path(config_path).expanduser()
35
+ if not path.is_absolute():
36
+ path = BACKEND_DIR / path
37
+ if not path.exists():
38
+ raise RuntimeError(f"VISUALIZER_CONFIG does not exist: {path}")
39
+ with path.open("rb") as config_file:
40
+ return tomllib.load(config_file)
41
+
42
+
43
+ CONFIG = load_config()
44
+
45
+
46
+ def config_value(env_name: str, section: str, key: str, default):
47
+ if env_name in os.environ:
48
+ return os.environ[env_name]
49
+ return CONFIG.get(section, {}).get(key, default)
50
+
51
+
52
+ def config_bool(env_name: str, section: str, key: str, default: str = "0") -> bool:
53
+ return str(config_value(env_name, section, key, default)).lower() in {
54
+ "1", "true", "yes", "on",
55
+ }
config/models.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from config.loader import config_value
2
+
3
+ ONEFORMER_MODEL_NAME = str(config_value(
4
+ "ONEFORMER_MODEL_NAME",
5
+ "models",
6
+ "oneformer_model_name",
7
+ "shi-labs/oneformer_ade20k_swin_large",
8
+ ))
9
+
10
+ DEPTH_MODEL_NAME = str(config_value(
11
+ "DEPTH_MODEL_NAME",
12
+ "models",
13
+ "depth_model_name",
14
+ "depth-anything/Depth-Anything-V2-Metric-Indoor-Large-hf",
15
+ ))
16
+
17
+ GEOMETRY_MODEL = str(config_value(
18
+ "GEOMETRY_MODEL",
19
+ "models",
20
+ "geometry_model",
21
+ "depth",
22
+ )).lower()
23
+
24
+ MOGE_MODEL_NAME = str(config_value(
25
+ "MOGE_MODEL_NAME",
26
+ "models",
27
+ "moge_model_name",
28
+ "Ruicheng/moge-2-vitl-normal",
29
+ ))
30
+
31
+ SAM2_MODEL_CFG = str(config_value(
32
+ "SAM2_MODEL_CFG",
33
+ "models",
34
+ "sam2_model_cfg",
35
+ "",
36
+ ))
37
+
38
+ SAM2_CHECKPOINT = str(config_value(
39
+ "SAM2_CHECKPOINT",
40
+ "models",
41
+ "sam2_checkpoint",
42
+ "",
43
+ ))
44
+
45
+ SAM2_MODEL_NAME = str(config_value(
46
+ "SAM2_MODEL_NAME",
47
+ "models",
48
+ "sam2_model_name",
49
+ "facebook/sam2-hiera-large",
50
+ ))
51
+
52
+ INTRINSIC_MODEL_VERSION = str(config_value(
53
+ "INTRINSIC_MODEL_VERSION",
54
+ "models",
55
+ "intrinsic_model_version",
56
+ "v2",
57
+ ))
config/paths.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from config.runtime import VISUALIZER_DATA_DIR
3
+
4
+ DATA_DIR = Path(VISUALIZER_DATA_DIR).resolve()
5
+ UPLOAD_DIR = DATA_DIR / "uploads"
6
+ JOB_DIR = DATA_DIR / "jobs"
7
+ MATERIAL_DIR = DATA_DIR / "materials"
8
+ QA_RUN_DIR = DATA_DIR / "qa-runs"
9
+ TIMING_BASELINE_PATH = DATA_DIR / "conversion-timings.json"
10
+
11
+ UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
12
+ JOB_DIR.mkdir(parents=True, exist_ok=True)
13
+ MATERIAL_DIR.mkdir(parents=True, exist_ok=True)
14
+ QA_RUN_DIR.mkdir(parents=True, exist_ok=True)
config/qa.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from config.loader import REPO_ROOT, config_value
2
+ from pathlib import Path
3
+
4
+ QA_FRONTEND_URL = str(config_value(
5
+ "QA_FRONTEND_URL", "qa", "frontend_url", "",
6
+ )).strip().rstrip("/")
7
+
8
+ QA_BACKEND_URL = str(config_value(
9
+ "QA_BACKEND_URL", "qa", "backend_url", "",
10
+ )).strip().rstrip("/")
11
+
12
+ QA_FRONTEND_DIR = Path(str(config_value(
13
+ "QA_FRONTEND_DIR", "qa", "frontend_dir",
14
+ str(REPO_ROOT / "frontend" / "viz2d-demo"),
15
+ ))).expanduser()
16
+
17
+ QA_MAX_IMAGES = max(1, int(config_value(
18
+ "QA_MAX_IMAGES", "qa", "max_images", "50",
19
+ )))
20
+
21
+ QA_MAX_TESTS = max(1, int(config_value(
22
+ "QA_MAX_TESTS", "qa", "max_tests", "200",
23
+ )))
24
+
25
+ QA_RUN_TIMEOUT_SECONDS = max(60, int(config_value(
26
+ "QA_RUN_TIMEOUT_SECONDS", "qa", "run_timeout_seconds", "7200",
27
+ )))
28
+
29
+ QA_PRESIGNED_URL_EXPIRES_SECONDS = max(60, int(config_value(
30
+ "QA_PRESIGNED_URL_EXPIRES_SECONDS", "qa", "presigned_url_expires_seconds", "3600",
31
+ )))
config/runtime.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from config.loader import config_bool, config_value
2
+
3
+ ENABLE_MOGE_GEOMETRY = config_bool("ENABLE_MOGE_GEOMETRY", "runtime", "enable_moge_geometry", "0")
4
+ ENABLE_SAM_REFINEMENT = config_bool("ENABLE_SAM_REFINEMENT", "runtime", "enable_sam_refinement", "0")
5
+ ENABLE_FLOOR_MASK_CLEANUP = config_bool("ENABLE_FLOOR_MASK_CLEANUP", "runtime", "enable_floor_mask_cleanup", "1")
6
+ ENABLE_DEPTH_ESTIMATION = config_bool("ENABLE_DEPTH_ESTIMATION", "runtime", "enable_depth_estimation", "1")
7
+ ENABLE_PLANE_FIT = config_bool("ENABLE_PLANE_FIT", "runtime", "enable_plane_fit", "1")
8
+ ENABLE_MULTI_PLANE_SURFACES = config_bool("ENABLE_MULTI_PLANE_SURFACES", "runtime", "enable_multi_plane_surfaces", "1")
9
+ ENABLE_WALL_SEGMENTS = config_bool("ENABLE_WALL_SEGMENTS", "runtime", "enable_wall_segments", "1")
10
+ ENABLE_INTRINSIC_SHADING = config_bool("ENABLE_INTRINSIC_SHADING", "runtime", "enable_intrinsic_shading", "0")
11
+ ENABLE_SHADING_TRANSFER = config_bool("ENABLE_SHADING_TRANSFER", "runtime", "enable_shading_transfer", "1")
12
+ WARM_START_MODELS = config_bool("WARM_START_MODELS", "runtime", "warm_start_models", "1")
13
+
14
+ BUNDLE_IMAGE_FORMAT = str(config_value(
15
+ "BUNDLE_IMAGE_FORMAT", "runtime", "bundle_image_format", "jpeg",
16
+ )).lower()
17
+
18
+ BUNDLE_IMAGE_QUALITY = int(config_value(
19
+ "BUNDLE_IMAGE_QUALITY", "runtime", "bundle_image_quality", "92",
20
+ ))
21
+
22
+ ROOM_UPLOAD_MAX_DIMENSION = max(720, int(config_value(
23
+ "ROOM_UPLOAD_MAX_DIMENSION", "runtime", "room_upload_max_dimension", "1920",
24
+ )))
25
+
26
+ ROOM_UPLOAD_JPEG_QUALITY = min(95, max(50, int(config_value(
27
+ "ROOM_UPLOAD_JPEG_QUALITY", "runtime", "room_upload_jpeg_quality", "85",
28
+ ))))
29
+
30
+ DEBUG_ARTIFACTS_ENABLED = config_bool(
31
+ "DEBUG_ARTIFACTS_ENABLED", "runtime", "debug_artifacts_enabled", "1",
32
+ )
33
+
34
+ CONVERSION_TARGET_MS = max(5_000, int(config_value(
35
+ "CONVERSION_TARGET_MS", "runtime", "conversion_target_ms", "30000",
36
+ )))
37
+
38
+ DEBUG_ARTIFACTS_MAX_DIMENSION = max(320, int(config_value(
39
+ "DEBUG_ARTIFACTS_MAX_DIMENSION", "runtime", "debug_artifacts_max_dimension", "1600",
40
+ )))
41
+
42
+ DEBUG_ARTIFACTS_PREVIEW_DIMENSION = max(320, int(config_value(
43
+ "DEBUG_ARTIFACTS_PREVIEW_DIMENSION", "runtime", "debug_artifacts_preview_dimension", "720",
44
+ )))
45
+
46
+ VISUALIZER_DATA_DIR = str(config_value(
47
+ "VISUALIZER_DATA_DIR", "runtime", "data_dir", "data",
48
+ ))
config/spaces.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from config.loader import config_value
2
+
3
+ SPACES_BUCKET = str(config_value(
4
+ "SPACES_BUCKET", "spaces", "bucket", "",
5
+ )).strip()
6
+
7
+ SPACES_REGION = str(config_value(
8
+ "SPACES_REGION", "spaces", "region", "",
9
+ )).strip()
10
+
11
+ SPACES_ENDPOINT_URL = str(config_value(
12
+ "SPACES_ENDPOINT_URL", "spaces", "endpoint_url", "",
13
+ )).strip().rstrip("/")
14
+
15
+ SPACES_ACCESS_KEY_ID = str(config_value(
16
+ "SPACES_ACCESS_KEY_ID", "spaces", "access_key_id", "",
17
+ )).strip()
18
+
19
+ SPACES_SECRET_ACCESS_KEY = str(config_value(
20
+ "SPACES_SECRET_ACCESS_KEY", "spaces", "secret_access_key", "",
21
+ )).strip()
22
+
23
+ SPACES_UPLOAD_PREFIX = str(config_value(
24
+ "SPACES_UPLOAD_PREFIX", "spaces", "upload_prefix", "room-uploads",
25
+ )).strip().strip("/")
26
+
27
+ SPACES_ACL = str(config_value(
28
+ "SPACES_ACL", "spaces", "acl", "private",
29
+ )).strip()
config/surface.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from config.loader import config_bool, config_value
2
+
3
+ SURFACE_RANSAC_DISTANCE = float(config_value(
4
+ "SURFACE_RANSAC_DISTANCE", "surface_mapping", "ransac_distance_threshold", "0.04",
5
+ ))
6
+
7
+ SURFACE_MAX_PLANES = int(config_value(
8
+ "SURFACE_MAX_PLANES", "surface_mapping", "max_planes", "5",
9
+ ))
10
+
11
+ SURFACE_NORMAL_ANGLE_DEGREES = float(config_value(
12
+ "SURFACE_NORMAL_ANGLE_DEGREES", "surface_mapping", "normal_angle_threshold_degrees", "35",
13
+ ))
14
+
15
+ SURFACE_NORMAL_SMOOTHING_KERNEL = int(config_value(
16
+ "SURFACE_NORMAL_SMOOTHING_KERNEL", "surface_mapping", "normal_smoothing_kernel", "5",
17
+ ))
18
+
19
+ SURFACE_MIN_PLANE_PIXELS = int(config_value(
20
+ "SURFACE_MIN_PLANE_PIXELS", "surface_mapping", "min_plane_pixels", "1500",
21
+ ))
22
+
23
+ SURFACE_EDGE_CLOSE_RATIO = float(config_value(
24
+ "SURFACE_EDGE_CLOSE_RATIO", "surface_mapping", "edge_close_ratio", "0.009",
25
+ ))
26
+
27
+ SURFACE_EDGE_KERNEL_RATIO = float(config_value(
28
+ "SURFACE_EDGE_KERNEL_RATIO", "surface_mapping", "edge_kernel_ratio", "0.006",
29
+ ))
30
+
31
+ SURFACE_EDGE_DILATION_ITERATIONS = int(config_value(
32
+ "SURFACE_EDGE_DILATION_ITERATIONS", "surface_mapping", "edge_dilation_iterations", "2",
33
+ ))
34
+
35
+ ENABLE_SOFT_FLOOR_COVERING_EXPANSION = config_bool(
36
+ "ENABLE_SOFT_FLOOR_COVERING_EXPANSION", "surface_mapping",
37
+ "soft_floor_covering_expansion_enabled", "1",
38
+ )
39
+
40
+ SOFT_FLOOR_COVERING_KERNEL_RATIO = float(config_value(
41
+ "SOFT_FLOOR_COVERING_KERNEL_RATIO", "surface_mapping",
42
+ "soft_floor_covering_kernel_ratio", "0.008",
43
+ ))
44
+
45
+ SOFT_FLOOR_COVERING_DILATION_ITERATIONS = int(config_value(
46
+ "SOFT_FLOOR_COVERING_DILATION_ITERATIONS", "surface_mapping",
47
+ "soft_floor_covering_dilation_iterations", "2",
48
+ ))
49
+
50
+ SURFACE_UV_MIN_COVERAGE = float(config_value(
51
+ "SURFACE_UV_MIN_COVERAGE", "surface_mapping", "uv_min_coverage", "0.995",
52
+ ))
53
+
54
+ SURFACE_UV_MAX_BAD_NEIGHBOR_RATIO = float(config_value(
55
+ "SURFACE_UV_MAX_BAD_NEIGHBOR_RATIO", "surface_mapping", "uv_max_bad_neighbor_ratio", "0.035",
56
+ ))
57
+
58
+ SURFACE_UV_MAX_JUMP_RATIO = float(config_value(
59
+ "SURFACE_UV_MAX_JUMP_RATIO", "surface_mapping", "uv_max_jump_ratio", "8.0",
60
+ ))
61
+
62
+ SURFACE_UV_ABSOLUTE_JUMP_METERS = float(config_value(
63
+ "SURFACE_UV_ABSOLUTE_JUMP_METERS", "surface_mapping", "uv_absolute_jump_meters", "0.35",
64
+ ))
65
+
66
+ ENABLE_GEOMETRY_SURFACE_FILTER = config_bool(
67
+ "ENABLE_GEOMETRY_SURFACE_FILTER", "surface_mapping", "enable_geometry_surface_filter", "1",
68
+ )
69
+
70
+ SURFACE_PLANE_DISTANCE_METERS = float(config_value(
71
+ "SURFACE_PLANE_DISTANCE_METERS", "surface_mapping", "plane_distance_threshold_meters", "0.12",
72
+ ))
73
+
74
+ SURFACE_PLANE_NORMAL_MIN_COS = float(config_value(
75
+ "SURFACE_PLANE_NORMAL_MIN_COS", "surface_mapping", "plane_normal_min_cos", "0.45",
76
+ ))
77
+
78
+ SURFACE_PLANE_FILTER_MIN_KEEP_RATIO = float(config_value(
79
+ "SURFACE_PLANE_FILTER_MIN_KEEP_RATIO", "surface_mapping", "plane_filter_min_keep_ratio", "0.45",
80
+ ))
enums.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared string enumerations for the floor-visualizer backend."""
2
+
3
+ from enum import StrEnum
4
+
5
+
6
+ class JobStatus(StrEnum):
7
+ QUEUED = "QUEUED"
8
+ PROCESSING = "PROCESSING"
9
+ COMPLETED = "COMPLETED"
10
+ FAILED = "FAILED"
11
+
12
+
13
+ class PipelinePhase(StrEnum):
14
+ SEGMENTATION = "segmentation"
15
+ MASKING = "masking"
16
+ GEOMETRY = "geometry"
17
+ SURFACE_MAPPING = "surface-mapping"
18
+ LIGHTING = "lighting"
19
+ DIRECTION = "direction"
20
+ PACKAGING = "packaging"
21
+
22
+
23
+ class TextureMappingMode(StrEnum):
24
+ REGULARIZED_FLOOR_PLANE = "regularized-floor-plane"
25
+ SURFACE_UV = "surface-uv"
26
+ WALL_PLANE = "wall-plane"
27
+ WALL_CONTOUR_HOMOGRAPHY = "wall-contour-homography"
28
+
29
+
30
+ class TextureMappingReason(StrEnum):
31
+ SURFACE_UV_UNAVAILABLE = "surface-uv-unavailable"
32
+ EMPTY_SURFACE = "empty-surface"
33
+ INCOMPLETE_SURFACE_UV = "incomplete-surface-uv"
34
+ INSUFFICIENT_UV_NEIGHBORS = "insufficient-uv-neighbors"
35
+ NOISY_SURFACE_UV = "noisy-surface-uv"
36
+ SURFACE_UV_QUALITY_OK = "surface-uv-quality-ok"
37
+ MULTI_PLANE_SURFACE_UV_QUALITY_OK = "multi-plane-surface-uv-quality-ok"
38
+
39
+
40
+ class GeometryProvider(StrEnum):
41
+ HOMOGRAPHY = "homography"
42
+ MOGE_2 = "moge-2"
43
+ RELATIVE_DEPTH = "relative-depth"
44
+ DEPTH_ANYTHING_METRIC = "depth-anything-metric"
45
+ DEPTH_ANYTHING = "depth-anything"
46
+ METRIC_DEPTH = "metric-depth"
47
+ WALL_DEPTH = "wall-depth"
48
+ WALL_CONTOUR_HOMOGRAPHY = "wall-contour-homography"
49
+
50
+
51
+ class LightingSource(StrEnum):
52
+ LUMINANCE = "luminance"
53
+ INTRINSIC = "intrinsic" # prefix, actual value is f"intrinsic-{version}"
54
+
55
+
56
+ class FloorMaskSource(StrEnum):
57
+ PRIMARY_FLOOR = "primary-floor"
58
+ FLOOR_SURFACE_FALLBACK = "floor-surface-fallback"
59
+
60
+
61
+ class PlaneFitMode(StrEnum):
62
+ NORMAL_AWARE = "normal-aware"
63
+ RANSAC = "ransac"
64
+
65
+
66
+ class IntrinsicAlignment(StrEnum):
67
+ UNCHECKED = "intrinsic-unchecked"
68
+ ALIGNED = "intrinsic-aligned"
69
+ LOW_CONFIDENCE = "intrinsic-low-confidence"
70
+ INVERTED_CORRECTED = "intrinsic-inverted-corrected"
71
+
72
+
73
+ class QaStatus(StrEnum):
74
+ QUEUED = "queued"
75
+ RUNNING = "running"
76
+ COMPLETED = "completed"
77
+ FAILED = "failed"
78
+ CANCELLED = "cancelled"
79
+
80
+
81
+ class QaResult(StrEnum):
82
+ PASSED = "passed"
83
+ FAILED = "failed"
84
+ SKIPPED = "skipped"
85
+
86
+
87
+ class SurfaceType(StrEnum):
88
+ FLOOR = "floor"
89
+ WALL = "wall"
errors.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reusable HTTP error helpers."""
2
+
3
+ from fastapi import HTTPException
4
+
5
+
6
+ def bad_request(detail: str, cause: Exception | None = None) -> HTTPException:
7
+ exc = HTTPException(status_code=400, detail=detail)
8
+ if cause is not None:
9
+ raise exc from cause
10
+ raise exc
11
+
12
+
13
+ def not_found(detail: str = "Not found.") -> HTTPException:
14
+ raise HTTPException(status_code=404, detail=detail)
15
+
16
+
17
+ def conflict(detail: str) -> HTTPException:
18
+ raise HTTPException(status_code=409, detail=detail)
19
+
20
+
21
+ def server_error(detail: str) -> HTTPException:
22
+ raise HTTPException(status_code=500, detail=detail)
23
+
24
+
25
+ def service_unavailable(detail: str, cause: Exception | None = None) -> HTTPException:
26
+ exc = HTTPException(status_code=503, detail=detail)
27
+ if cause is not None:
28
+ raise exc from cause
29
+ raise exc
30
+
31
+
32
+ def bad_gateway(detail: str, cause: Exception | None = None) -> HTTPException:
33
+ exc = HTTPException(status_code=502, detail=detail)
34
+ if cause is not None:
35
+ raise exc from cause
36
+ raise exc
frontend/viz2d-demo/e2e/README.md DELETED
@@ -1,70 +0,0 @@
1
- # Real Browser QA
2
-
3
- This suite drives the visualizer through Playwright using every image in `frontend/viz2d-demo/test-images/`
4
- and the configured hosted backend.
5
-
6
- The default flow uploads each test image once, waits for detection once, then applies each selected tile in sequence
7
- to the same detected room. After each tile result is captured and judged, the suite removes that tile before applying
8
- the next one. It does not touch the user-only tile size or rotation sliders.
9
-
10
- Required CI secrets:
11
-
12
- - `QA_BACKEND_URL` or `API_URL`: hosted FastAPI backend URL.
13
- - `GEMINI_API_KEY`: Gemini API key for visual result judging.
14
-
15
- Optional variables:
16
-
17
- - `GEMINI_MODEL`: defaults to `gemini-3.1-flash-lite`.
18
- - `QA_SKIP_GEMINI=1`: run browser and canvas checks without the Gemini judge.
19
- - `QA_TEST_IMAGES_DIR`: image folder, defaults to `test-images`.
20
- - `QA_SCENARIOS`: optional JSON array of per-image overrides by sorted image order.
21
-
22
- Gemini explicitly checks for missed target-surface coverage, including thin untiled floor slivers around sofas,
23
- tables, table legs, cabinets, plants, wall bases, and room edges. It also checks whether the applied tile direction
24
- matches the floor perspective instead of looking rotated or misaligned. Coverage gaps and direction mismatches are
25
- treated as QA failures. Tune strictness per scenario with:
26
-
27
- - `minEdgeCompleteness`: defaults to `0.82`.
28
- - `minOcclusionBoundaryQuality`: defaults to `0.78`.
29
- - `minDirectionQuality`: defaults to `0.75`.
30
- - `expectedDirectionDescription`: describes the expected direction/orientation for that image and texture.
31
-
32
- Example `QA_SCENARIOS` for the first two sorted files in `test-images/`:
33
-
34
- ```json
35
- [
36
- {
37
- "roomName": "Living Room 1",
38
- "surfaceClass": "floor",
39
- "textureName": "Black White Marble Checkered",
40
- "keyword": "floor",
41
- "textureDescription": "black and white marble checkerboard tile",
42
- "expectedDirectionDescription": "checkerboard rows and columns follow the floor perspective toward the room vanishing direction",
43
- "minEdgeCompleteness": 0.82,
44
- "minOcclusionBoundaryQuality": 0.78,
45
- "minDirectionQuality": 0.75
46
- },
47
- {
48
- "roomName": "Kitchen 1",
49
- "surfaceClass": "floor",
50
- "textureName": "Natural Stone",
51
- "keyword": "floor"
52
- }
53
- ]
54
- ```
55
-
56
- Local command:
57
-
58
- ```bash
59
- API_URL=https://your-backend.example GEMINI_API_KEY=... npm run qa:real
60
- ```
61
-
62
- Create the compact Markdown summary after a run:
63
-
64
- ```bash
65
- npm run qa:report
66
- ```
67
-
68
- The GitHub artifact includes only `test-results/qa-summary.md`. The summary embeds each image's before/after
69
- screenshots and Gemini judgment directly in the Markdown, so you do not need to dig through traces and videos for
70
- the normal review.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/viz2d-demo/e2e/lighting-preservation.spec.ts DELETED
@@ -1,338 +0,0 @@
1
- import { expect, test, type Page } from "@playwright/test";
2
-
3
- const WIDTH = 120;
4
- const HEIGHT = 72;
5
-
6
- test("shows a persistent floor label without tinting the mask", async ({ page }) => {
7
- await page.goto("/");
8
- await page.getByTestId("room-file-input").setInputFiles({
9
- name: "surface-label.vizbundle.json",
10
- mimeType: "application/json",
11
- buffer: Buffer.from(JSON.stringify(buildLightingBundle())),
12
- });
13
-
14
- const canvas = page.getByTestId("visualizer-canvas");
15
- const label = page.getByTestId("surface-label").filter({ hasText: "Floor" });
16
- await expect(canvas).toBeVisible();
17
- await expect(label).toBeVisible();
18
- await expectLabelInsideCanvas(canvas, label);
19
-
20
- const beforeHover = await readCanvasPixel(canvas, WIDTH / 2, HEIGHT / 2);
21
- const canvasBox = await canvas.boundingBox();
22
- expect(canvasBox).not.toBeNull();
23
- await page.mouse.move(canvasBox!.x + canvasBox!.width / 2, canvasBox!.y + canvasBox!.height / 2);
24
- const afterHover = await readCanvasPixel(canvas, WIDTH / 2, HEIGHT / 2);
25
- expect(afterHover).toEqual(beforeHover);
26
-
27
- const labelBox = await label.boundingBox();
28
- expect(labelBox).not.toBeNull();
29
- await page.mouse.click(labelBox!.x + labelBox!.width / 2, labelBox!.y + labelBox!.height / 2);
30
- await expect(page.getByTestId("texture-selector")).toBeVisible();
31
- await page.getByLabel("Close", { exact: true }).click();
32
-
33
- await page.setViewportSize({ width: 390, height: 844 });
34
- await expectLabelInsideCanvas(canvas, label);
35
- });
36
-
37
- for (const renderer of ["webgl", "canvas"] as const) {
38
- test(`applied tile preserves scene lighting in ${renderer}`, async ({ page }) => {
39
- if (renderer === "canvas") {
40
- await disableWebGl(page);
41
- }
42
-
43
- await page.goto("/");
44
- await page.getByTestId("room-file-input").setInputFiles({
45
- name: "lighting.vizbundle.json",
46
- mimeType: "application/json",
47
- buffer: Buffer.from(JSON.stringify(buildLightingBundle())),
48
- });
49
-
50
- await expect(page.getByTestId("visualizer-editor")).toBeVisible();
51
- await expect(page.getByTestId("surface-card")).toBeVisible();
52
- await page.getByTestId("surface-card").click();
53
- await expect(page.getByTestId("texture-selector")).toBeVisible();
54
- await page.getByTestId("texture-card").filter({ hasText: "White Wood Flooring" }).click();
55
- await expect(page.getByTestId("texture-selector")).toBeHidden();
56
- await expect(page.getByTestId("surface-card").filter({ hasText: "White Wood Flooring" })).toBeVisible();
57
- await page.mouse.move(4, 4);
58
-
59
- const luminance = await readLightingRegions(page);
60
- expect(luminance.dark, "deep source shadow should fully cover the applied tile").toBeLessThan(luminance.neutral * 0.55);
61
- // Near-white tiles saturate before preserving a large relative ratio.
62
- expect(luminance.bright, "bright source region should remain visibly illuminated").toBeGreaterThan(luminance.neutral + 15);
63
- expect(luminance.bright, "bright source region should approach white").toBeGreaterThan(240);
64
- });
65
-
66
- test(`v4 keeps shadows unchanged and controls highlights on dark tile in ${renderer}`, async ({ page }) => {
67
- if (renderer === "canvas") {
68
- await disableWebGl(page);
69
- }
70
-
71
- const legacy = await renderLightingBundle(page, 3, false, "Dark Marble");
72
- const materialAware = await renderLightingBundle(page, 4, false, "Dark Marble");
73
- const materialAwareWithReflection = await renderLightingBundle(page, 4, true, "Dark Marble");
74
-
75
- expect(materialAware.dark, "v4 must not weaken or strengthen source shadows").toBeCloseTo(legacy.dark, 0);
76
- expect(materialAware.neutral, "v4 must not alter neutral source lighting").toBeCloseTo(legacy.neutral, 0);
77
- expect(materialAwareWithReflection.bright, "bright source lighting should remain visible").toBeGreaterThan(
78
- materialAwareWithReflection.neutral + 8,
79
- );
80
- expect(materialAwareWithReflection.bright, "dark tile highlights should retain material color").toBeLessThan(190);
81
- expect(materialAware.bright, "v4 should reduce additive whitening").toBeLessThan(legacy.bright);
82
- });
83
-
84
- test(`applied tile fully covers the floor-mask edge in ${renderer}`, async ({ page }) => {
85
- if (renderer === "canvas") {
86
- await disableWebGl(page);
87
- }
88
-
89
- await page.goto("/");
90
- await page.getByTestId("room-file-input").setInputFiles({
91
- name: "edge-coverage.vizbundle.json",
92
- mimeType: "application/json",
93
- buffer: Buffer.from(JSON.stringify(buildEdgeCoverageBundle())),
94
- });
95
-
96
- await expect(page.getByTestId("visualizer-editor")).toBeVisible();
97
- await page.getByTestId("surface-card").click();
98
- await page.getByTestId("texture-card").filter({ hasText: "White Wood Flooring" }).click();
99
- await expect(page.getByTestId("texture-selector")).toBeHidden();
100
-
101
- const colors = await readEdgeColors(page);
102
- expect(colors.boundary.green, "first floor pixels should have full tile coverage").toBeGreaterThan(
103
- colors.interior.green * 0.82,
104
- );
105
- expect(colors.outside.green, "tile should not bleed outside the floor mask").toBeLessThan(50);
106
- expect(colors.outside.red).toBeGreaterThan(200);
107
- expect(colors.outside.blue).toBeGreaterThan(200);
108
- });
109
- }
110
-
111
- async function readCanvasPixel(pageCanvas: ReturnType<import("@playwright/test").Page["getByTestId"]>, x: number, y: number) {
112
- return pageCanvas.evaluate((canvas, point) => {
113
- const context = (canvas as HTMLCanvasElement).getContext("2d");
114
- if (!context) throw new Error("Canvas context is unavailable.");
115
- return Array.from(context.getImageData(point.x, point.y, 1, 1).data);
116
- }, { x, y });
117
- }
118
-
119
- async function expectLabelInsideCanvas(
120
- canvas: ReturnType<import("@playwright/test").Page["getByTestId"]>,
121
- label: ReturnType<import("@playwright/test").Page["getByTestId"]>,
122
- ) {
123
- await expect.poll(async () => {
124
- const [canvasBox, labelBox] = await Promise.all([canvas.boundingBox(), label.boundingBox()]);
125
- if (!canvasBox || !labelBox) return false;
126
- return (
127
- labelBox.x >= canvasBox.x &&
128
- labelBox.y >= canvasBox.y &&
129
- labelBox.x + labelBox.width <= canvasBox.x + canvasBox.width &&
130
- labelBox.y + labelBox.height <= canvasBox.y + canvasBox.height
131
- );
132
- }).toBe(true);
133
- }
134
-
135
- function buildLightingBundle(lightingTransferVersion = 3, includeReflection = false) {
136
- const pixelCount = WIDTH * HEIGHT;
137
- const pixels = new Uint8Array(pixelCount * 4);
138
- const mask = new Uint32Array(pixelCount);
139
- const shadeMap = new Uint8Array(pixelCount);
140
- const reflectionMap = new Uint8Array(pixelCount);
141
-
142
- for (let index = 0; index < pixelCount; index += 1) {
143
- const x = index % WIDTH;
144
- const sourceValue = x < 40 ? 70 : x >= 80 ? 220 : 145;
145
- const shade = x < 40 ? 0.14 : x >= 80 ? 1.5 : 1;
146
- const pixelIndex = index * 4;
147
- pixels[pixelIndex] = sourceValue;
148
- pixels[pixelIndex + 1] = sourceValue;
149
- pixels[pixelIndex + 2] = sourceValue;
150
- pixels[pixelIndex + 3] = 255;
151
- mask[index] = index;
152
- shadeMap[index] = Math.round(((shade - 0.08) / (1.85 - 0.08)) * 255);
153
- reflectionMap[index] = includeReflection && x >= 80 ? 255 : 0;
154
- }
155
-
156
- return {
157
- format: "baetes-vizbundle",
158
- bundleVersion: 3,
159
- width: WIDTH,
160
- height: HEIGHT,
161
- pixels: Buffer.from(pixels).toString("base64"),
162
- segments: [
163
- {
164
- id: 0,
165
- className: "floor",
166
- mask: Buffer.from(mask.buffer).toString("base64"),
167
- homography: null,
168
- plane: null,
169
- shadeMap: Buffer.from(shadeMap).toString("base64"),
170
- showroomShadeMap: null,
171
- reflectionMap: includeReflection ? Buffer.from(reflectionMap).toString("base64") : null,
172
- metadata: {
173
- lightingSource: "synthetic-test",
174
- lightingTransferVersion,
175
- shadeMapEncoding: "linear-relative",
176
- shadeMapRange: [0.08, 1.85],
177
- renderPresetDefaults: {
178
- preset: "realistic",
179
- shadingStrength: 1,
180
- },
181
- },
182
- },
183
- ],
184
- };
185
- }
186
-
187
- function buildEdgeCoverageBundle() {
188
- const pixelCount = WIDTH * HEIGHT;
189
- const pixels = new Uint8Array(pixelCount * 4);
190
- const maskValues: number[] = [];
191
- const shadeMap = new Uint8Array(pixelCount);
192
- const neutralShade = Math.round(((1 - 0.08) / (1.85 - 0.08)) * 255);
193
-
194
- for (let index = 0; index < pixelCount; index += 1) {
195
- const x = index % WIDTH;
196
- const y = Math.floor(index / WIDTH);
197
- const pixelIndex = index * 4;
198
- pixels[pixelIndex] = 230;
199
- pixels[pixelIndex + 1] = 20;
200
- pixels[pixelIndex + 2] = 230;
201
- pixels[pixelIndex + 3] = 255;
202
- shadeMap[index] = neutralShade;
203
- if (x >= 10 && x < 110 && y >= 8 && y < 64) {
204
- maskValues.push(index);
205
- }
206
- }
207
-
208
- const mask = Uint32Array.from(maskValues);
209
- return {
210
- format: "baetes-vizbundle",
211
- bundleVersion: 3,
212
- width: WIDTH,
213
- height: HEIGHT,
214
- pixels: Buffer.from(pixels).toString("base64"),
215
- segments: [
216
- {
217
- id: 0,
218
- className: "floor",
219
- mask: Buffer.from(mask.buffer).toString("base64"),
220
- homography: null,
221
- plane: null,
222
- shadeMap: Buffer.from(shadeMap).toString("base64"),
223
- showroomShadeMap: null,
224
- reflectionMap: null,
225
- metadata: {
226
- lightingTransferVersion: 3,
227
- shadeMapEncoding: "linear-relative",
228
- shadeMapRange: [0.08, 1.85],
229
- renderPresetDefaults: {
230
- preset: "realistic",
231
- shadingStrength: 1,
232
- },
233
- },
234
- },
235
- ],
236
- };
237
- }
238
-
239
- async function disableWebGl(page: Page) {
240
- await page.addInitScript(() => {
241
- const originalGetContext = HTMLCanvasElement.prototype.getContext;
242
- HTMLCanvasElement.prototype.getContext = function getContext(
243
- this: HTMLCanvasElement,
244
- contextId: string,
245
- ...args: unknown[]
246
- ) {
247
- if (contextId === "webgl2") return null;
248
- return originalGetContext.call(this, contextId as "2d", ...args as []);
249
- } as typeof HTMLCanvasElement.prototype.getContext;
250
- });
251
- }
252
-
253
- async function renderLightingBundle(
254
- page: Page,
255
- lightingTransferVersion: number,
256
- includeReflection: boolean,
257
- textureName: string,
258
- ) {
259
- await page.goto("/");
260
- await page.getByTestId("room-file-input").setInputFiles({
261
- name: `lighting-v${lightingTransferVersion}.vizbundle.json`,
262
- mimeType: "application/json",
263
- buffer: Buffer.from(JSON.stringify(buildLightingBundle(lightingTransferVersion, includeReflection))),
264
- });
265
- await expect(page.getByTestId("visualizer-editor")).toBeVisible();
266
- await page.getByTestId("surface-card").click();
267
- await expect(page.getByTestId("texture-selector")).toBeVisible();
268
- await page.getByTestId("texture-card").filter({ hasText: textureName }).click();
269
- await expect(page.getByTestId("texture-selector")).toBeHidden();
270
- await page.mouse.move(4, 4);
271
- return readLightingRegions(page);
272
- }
273
-
274
- async function readLightingRegions(page: Page) {
275
- return page.getByTestId("visualizer-canvas").evaluate((node) => {
276
- const canvas = node as HTMLCanvasElement;
277
- const context = canvas.getContext("2d", { willReadFrequently: true });
278
- if (!context) throw new Error("Canvas does not expose a 2D context.");
279
- const image = context.getImageData(0, 0, canvas.width, canvas.height);
280
-
281
- const meanLuminance = (startX: number, endX: number) => {
282
- let total = 0;
283
- let count = 0;
284
- for (let y = 8; y < canvas.height - 8; y += 1) {
285
- for (let x = startX; x < endX; x += 1) {
286
- const index = (y * canvas.width + x) * 4;
287
- total += (
288
- image.data[index] * 0.2126 +
289
- image.data[index + 1] * 0.7152 +
290
- image.data[index + 2] * 0.0722
291
- );
292
- count += 1;
293
- }
294
- }
295
- return total / Math.max(count, 1);
296
- };
297
-
298
- return {
299
- dark: meanLuminance(8, 32),
300
- neutral: meanLuminance(48, 72),
301
- bright: meanLuminance(88, 112),
302
- };
303
- });
304
- }
305
-
306
- async function readEdgeColors(page: Page) {
307
- return page.getByTestId("visualizer-canvas").evaluate((node) => {
308
- const canvas = node as HTMLCanvasElement;
309
- const context = canvas.getContext("2d", { willReadFrequently: true });
310
- if (!context) throw new Error("Canvas does not expose a 2D context.");
311
- const image = context.getImageData(0, 0, canvas.width, canvas.height);
312
-
313
- const meanColor = (startX: number, endX: number) => {
314
- const total = [0, 0, 0];
315
- let count = 0;
316
- for (let y = 16; y < 56; y += 1) {
317
- for (let x = startX; x < endX; x += 1) {
318
- const index = (y * canvas.width + x) * 4;
319
- total[0] += image.data[index];
320
- total[1] += image.data[index + 1];
321
- total[2] += image.data[index + 2];
322
- count += 1;
323
- }
324
- }
325
- return {
326
- red: total[0] / count,
327
- green: total[1] / count,
328
- blue: total[2] / count,
329
- };
330
- };
331
-
332
- return {
333
- outside: meanColor(8, 10),
334
- boundary: meanColor(10, 12),
335
- interior: meanColor(14, 16),
336
- };
337
- });
338
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/viz2d-demo/e2e/real-room-qa.spec.ts DELETED
@@ -1,598 +0,0 @@
1
- import { existsSync, mkdirSync, readdirSync, renameSync, writeFileSync } from "node:fs";
2
- import path from "node:path";
3
-
4
- import { expect, test, type Locator, type Page, type TestInfo } from "@playwright/test";
5
-
6
- import {
7
- diffCanvasSignatures,
8
- expectUsableCanvas,
9
- readCanvasSignature,
10
- type CanvasSignature,
11
- } from "./support/image-checks";
12
- import { judgeTileApplicationWithGemini, type GeminiJudgeResult } from "./support/gemini-judge";
13
-
14
- type QaScenario = {
15
- detectionTimeoutMs: number;
16
- imagePath: string;
17
- keyword: string;
18
- expectedDirectionDescription: string;
19
- minAverageDelta: number;
20
- minChangedRatio: number;
21
- minDirectionQuality: number;
22
- minEdgeCompleteness: number;
23
- minLightingPreserved: number;
24
- minOcclusionBoundaryQuality: number;
25
- minPerspectiveQuality: number;
26
- minRealism: number;
27
- minSurfaceCorrectness: number;
28
- roomName: string;
29
- surfaceClass: string;
30
- textureDescription: string;
31
- textureName: string;
32
- };
33
-
34
- type QaScenarioCase = QaScenario & {
35
- qaCaseIndex: number;
36
- };
37
-
38
- type QaScenarioGroup = {
39
- imagePath: string;
40
- roomName: string;
41
- scenarios: QaScenarioCase[];
42
- };
43
-
44
- type QaCaseStatus = "passed" | "failed" | "skipped";
45
-
46
- const IMAGE_EXTENSIONS = new Set([".jpg", ".jpeg", ".png", ".webp"]);
47
- const TEST_IMAGES_DIR = path.resolve(process.env.QA_TEST_IMAGES_DIR ?? "test-images");
48
- const DEFAULT_SCENARIO_OPTIONS = {
49
- detectionTimeoutMs: 420_000,
50
- expectedDirectionDescription:
51
- "The checkerboard tile rows and columns should follow the floor perspective/direction and should not look arbitrarily rotated.",
52
- keyword: "floor",
53
- minAverageDelta: 2,
54
- minChangedRatio: 0.02,
55
- minDirectionQuality: 0.75,
56
- minEdgeCompleteness: 0.82,
57
- minLightingPreserved: 0.55,
58
- minOcclusionBoundaryQuality: 0.78,
59
- minPerspectiveQuality: 0.65,
60
- minRealism: 0.6,
61
- minSurfaceCorrectness: 0.7,
62
- surfaceClass: "floor",
63
- textureDescription: "black and white marble checkerboard tile",
64
- textureName: "Black White Marble Checkered",
65
- };
66
- const SCENARIO_GROUPS = groupScenarios(loadScenarios());
67
- const TOTAL_QA_CASES = SCENARIO_GROUPS.reduce((total, group) => total + group.scenarios.length, 0);
68
- const QA_CASE_PROGRESS = new Map<string, {
69
- durationMs: number;
70
- error: string | null;
71
- imageName: string;
72
- status: QaCaseStatus;
73
- title: string;
74
- tileName: string;
75
- }>();
76
-
77
- test.describe("real backend room visualizer QA", () => {
78
- for (const group of SCENARIO_GROUPS) {
79
- test(`${group.roomName}: apply ${group.scenarios.length} tile(s)`, async ({ page }, testInfo) => {
80
- requireBackendUrl();
81
- writeQaCaseProgress();
82
- const diagnostics = collectDiagnostics(page);
83
-
84
- await page.goto("/");
85
- await expect(page.getByText("Upload a Room Photo")).toBeVisible();
86
-
87
- await page.getByTestId("room-file-input").setInputFiles(group.imagePath);
88
- await expect(page.getByTestId("visualizer-editor")).toBeVisible({ timeout: 30_000 });
89
- await waitForSurfaceCards(page, maxDetectionTimeout(group.scenarios));
90
-
91
- const canvas = page.getByTestId("visualizer-canvas");
92
- const beforeSignature = await waitForUsableCanvas(page, canvas);
93
- const beforePath = testInfo.outputPath(`${slug(group.roomName)}-before.png`);
94
- await canvas.screenshot({ path: beforePath });
95
- await testInfo.attach("before-canvas", { contentType: "image/png", path: beforePath });
96
-
97
- const failures: string[] = [];
98
- for (const scenario of group.scenarios) {
99
- await test.step(`apply ${scenario.textureName}`, async () => {
100
- const startedAt = Date.now();
101
- const attachmentPrefix = qaCaseAttachmentPrefix(scenario);
102
- await testInfo.attach(`${attachmentPrefix}-before-canvas`, { contentType: "image/png", path: beforePath });
103
-
104
- try {
105
- await selectSurface(page, scenario.surfaceClass);
106
- await selectTexture(page, scenario);
107
- await waitForTextureToSettle(page, scenario.textureName);
108
- await page.mouse.move(8, 8);
109
-
110
- const afterTextureSignature = await waitForChangedCanvas(page, canvas, beforeSignature, scenario);
111
- expectUsableCanvas(afterTextureSignature);
112
- const afterTexturePath = testInfo.outputPath(
113
- `${slug(scenario.roomName)}-${scenario.qaCaseIndex}-${slug(scenario.textureName)}-after-texture.png`,
114
- );
115
- await canvas.screenshot({ path: afterTexturePath });
116
- await testInfo.attach(`${attachmentPrefix}-after-texture-canvas`, {
117
- contentType: "image/png",
118
- path: afterTexturePath,
119
- });
120
-
121
- await verifyDownload(page, testInfo, `${attachmentPrefix}-downloaded-render`);
122
- await runGeminiJudgeIfEnabled(scenario, beforePath, afterTexturePath, testInfo, attachmentPrefix);
123
- await attachQaCaseMeta(testInfo, scenario, attachmentPrefix, "passed", null, Date.now() - startedAt);
124
- recordQaCaseProgress(scenario, "passed", null, Date.now() - startedAt);
125
- } catch (caught) {
126
- const message = errorMessage(caught);
127
- failures.push(`${scenario.textureName}: ${message}`);
128
- await attachQaCaseMeta(testInfo, scenario, attachmentPrefix, "failed", message, Date.now() - startedAt);
129
- recordQaCaseProgress(scenario, "failed", message, Date.now() - startedAt);
130
- } finally {
131
- await removeTextureIfApplied(page, scenario.surfaceClass);
132
- }
133
- });
134
- }
135
-
136
- await attachDiagnostics(testInfo, diagnostics);
137
-
138
- expect(diagnostics.pageErrors, "browser page errors").toEqual([]);
139
- expect(failures, "tile QA failures").toEqual([]);
140
- });
141
- }
142
- });
143
-
144
- function maxDetectionTimeout(scenarios: QaScenario[]) {
145
- return scenarios.reduce((timeout, scenario) => Math.max(timeout, scenario.detectionTimeoutMs), 0);
146
- }
147
-
148
- async function waitForSurfaceCards(page: Page, timeoutMs: number) {
149
- const deadline = Date.now() + timeoutMs;
150
- while (Date.now() < deadline) {
151
- const failed = page.getByText("Detection failed");
152
- if (await failed.isVisible().catch(() => false)) {
153
- const status = await page.getByTestId("detection-status").innerText().catch(() => "Detection failed.");
154
- throw new Error(status);
155
- }
156
-
157
- if (await page.getByTestId("surface-card").first().isVisible().catch(() => false)) {
158
- return;
159
- }
160
-
161
- await page.waitForTimeout(1_000);
162
- }
163
-
164
- throw new Error(`No detected surfaces appeared within ${Math.round(timeoutMs / 1000)} seconds.`);
165
- }
166
-
167
- async function waitForUsableCanvas(page: Page, canvas: Locator) {
168
- let signature = await readCanvasSignature(canvas);
169
- const deadline = Date.now() + 60_000;
170
- while (Date.now() < deadline) {
171
- try {
172
- expectUsableCanvas(signature);
173
- return signature;
174
- } catch {
175
- await page.waitForTimeout(500);
176
- signature = await readCanvasSignature(canvas);
177
- }
178
- }
179
-
180
- expectUsableCanvas(signature);
181
- return signature;
182
- }
183
-
184
- async function selectSurface(page: Page, surfaceClass: string) {
185
- const exactSurface = page.locator(`[data-testid="surface-card"][data-surface-class="${surfaceClass}"]`).first();
186
- const fallbackSurface = page.getByTestId("surface-card").first();
187
- const target = await exactSurface.isVisible().catch(() => false) ? exactSurface : fallbackSurface;
188
-
189
- await expect(target).toBeVisible();
190
- await target.click();
191
- await expect(page.getByTestId("texture-selector")).toBeVisible();
192
- }
193
-
194
- async function selectTexture(page: Page, scenario: QaScenario) {
195
- if (scenario.keyword) {
196
- const keywordButton = page.getByTestId("texture-keyword").filter({ hasText: scenario.keyword }).first();
197
- if (await keywordButton.isVisible().catch(() => false)) {
198
- await keywordButton.click();
199
- }
200
- }
201
-
202
- const texture = page.getByTestId("texture-card").filter({ hasText: scenario.textureName }).first();
203
- await expect(texture).toBeVisible();
204
- await texture.scrollIntoViewIfNeeded();
205
- await texture.click();
206
- }
207
-
208
- async function waitForTextureToSettle(page: Page, textureName: string) {
209
- await expect(page.getByTestId("texture-selector")).toBeHidden({ timeout: 30_000 });
210
- await page.getByTestId("blocking-overlay").waitFor({ state: "hidden", timeout: 180_000 }).catch(() => undefined);
211
- await expect(page.getByTestId("surface-card").filter({ hasText: textureName }).first()).toBeVisible({
212
- timeout: 120_000,
213
- });
214
- }
215
-
216
- async function removeTextureIfApplied(page: Page, surfaceClass: string) {
217
- const selector = page.getByTestId("texture-selector");
218
- if (await selector.isVisible().catch(() => false)) {
219
- await page.getByLabel("Close texture selector").click().catch(async () => {
220
- await page.getByLabel("Close").click().catch(() => undefined);
221
- });
222
- await expect(selector).toBeHidden({ timeout: 10_000 }).catch(() => undefined);
223
- }
224
-
225
- const exactSurface = page.locator(`[data-testid="surface-card"][data-surface-class="${surfaceClass}"]`).first();
226
- const surface = await exactSurface.isVisible().catch(() => false) ? exactSurface : page.getByTestId("surface-card").first();
227
- const removeButton = surface.getByTestId("remove-surface-texture").first();
228
- const fallbackRemoveButton = surface.locator("button").first();
229
- const target = await removeButton.isVisible().catch(() => false) ? removeButton : fallbackRemoveButton;
230
-
231
- if (!(await target.isVisible().catch(() => false))) {
232
- return;
233
- }
234
-
235
- await target.click();
236
- await page.getByTestId("blocking-overlay").waitFor({ state: "hidden", timeout: 60_000 }).catch(() => undefined);
237
- await expect(surface.getByText("Click to apply texture")).toBeVisible({ timeout: 30_000 }).catch(() => undefined);
238
- await page.waitForTimeout(500);
239
- }
240
-
241
- async function waitForChangedCanvas(page: Page, canvas: Locator, previous: CanvasSignature, scenario: QaScenario) {
242
- const deadline = Date.now() + 60_000;
243
- let latest = await readCanvasSignature(canvas);
244
- let latestDiff = diffCanvasSignatures(previous, latest);
245
-
246
- while (Date.now() < deadline) {
247
- expectUsableCanvas(latest);
248
- if (latestDiff.changedRatio >= scenario.minChangedRatio && latestDiff.averageDelta >= scenario.minAverageDelta) {
249
- return latest;
250
- }
251
-
252
- await page.waitForTimeout(750);
253
- latest = await readCanvasSignature(canvas);
254
- latestDiff = diffCanvasSignatures(previous, latest);
255
- }
256
-
257
- expect(latestDiff.changedRatio, "canvas changed-pixel ratio after applying texture").toBeGreaterThanOrEqual(
258
- scenario.minChangedRatio,
259
- );
260
- expect(latestDiff.averageDelta, "average canvas color delta after applying texture").toBeGreaterThanOrEqual(
261
- scenario.minAverageDelta,
262
- );
263
- return latest;
264
- }
265
-
266
- async function verifyDownload(page: Page, testInfo: TestInfo, attachmentName: string) {
267
- const downloadPromise = page.waitForEvent("download", { timeout: 30_000 });
268
- await page.getByLabel("Download image").click();
269
- const download = await downloadPromise;
270
- expect(download.suggestedFilename()).toBe("download.png");
271
-
272
- const downloadPath = await download.path();
273
- if (downloadPath) {
274
- await testInfo.attach(attachmentName, { contentType: "image/png", path: downloadPath });
275
- }
276
- }
277
-
278
- async function runGeminiJudgeIfEnabled(
279
- scenario: QaScenario,
280
- beforeImagePath: string,
281
- afterImagePath: string,
282
- testInfo: TestInfo,
283
- attachmentPrefix: string,
284
- ) {
285
- if (flagEnabled("QA_SKIP_GEMINI")) {
286
- testInfo.annotations.push({ description: "QA_SKIP_GEMINI is enabled.", type: "gemini-skipped" });
287
- return;
288
- }
289
-
290
- const apiKey = process.env.GEMINI_API_KEY;
291
- if (!apiKey) {
292
- throw new Error("GEMINI_API_KEY is required for visual judging. Set QA_SKIP_GEMINI=1 for browser-only runs.");
293
- }
294
-
295
- const result = await judgeTileApplicationWithGemini({
296
- afterImagePath,
297
- apiKey,
298
- beforeImagePath,
299
- model: process.env.GEMINI_MODEL ?? "gemini-3.1-flash-lite",
300
- scenario,
301
- });
302
-
303
- await testInfo.attach(`${attachmentPrefix}-gemini-judge`, {
304
- body: JSON.stringify(result, null, 2),
305
- contentType: "application/json",
306
- });
307
-
308
- assertGeminiResult(result, scenario);
309
- }
310
-
311
- function assertGeminiResult(result: GeminiJudgeResult, scenario: QaScenario) {
312
- expect(result.tileApplied, `Gemini notes: ${result.notes}`).toBe(true);
313
- expect(result.bleedDetected, `Gemini notes: ${result.notes}`).toBe(false);
314
- expect(result.coverageGapDetected, `Gemini missed areas: ${result.missedFloorAreas.join("; ")}`).toBe(false);
315
- expect(result.directionMismatchDetected, `Gemini direction issues: ${result.directionIssues.join("; ")}`).toBe(false);
316
- expect(result.surfaceCorrectness, `Gemini notes: ${result.notes}`).toBeGreaterThanOrEqual(
317
- scenario.minSurfaceCorrectness,
318
- );
319
- expect(result.edgeCompleteness, `Gemini missed areas: ${result.missedFloorAreas.join("; ")}`).toBeGreaterThanOrEqual(
320
- scenario.minEdgeCompleteness,
321
- );
322
- expect(
323
- result.occlusionBoundaryQuality,
324
- `Gemini missed areas: ${result.missedFloorAreas.join("; ")}`,
325
- ).toBeGreaterThanOrEqual(
326
- scenario.minOcclusionBoundaryQuality,
327
- );
328
- expect(result.perspectiveQuality, `Gemini notes: ${result.notes}`).toBeGreaterThanOrEqual(
329
- scenario.minPerspectiveQuality,
330
- );
331
- expect(result.directionQuality, `Gemini direction issues: ${result.directionIssues.join("; ")}`).toBeGreaterThanOrEqual(
332
- scenario.minDirectionQuality,
333
- );
334
- expect(result.lightingPreserved, `Gemini notes: ${result.notes}`).toBeGreaterThanOrEqual(
335
- scenario.minLightingPreserved,
336
- );
337
- expect(result.realism, `Gemini notes: ${result.notes}`).toBeGreaterThanOrEqual(scenario.minRealism);
338
- expect(result.overallPass, `Gemini failure reasons: ${result.failureReasons.join("; ")}`).toBe(true);
339
- }
340
-
341
- async function attachQaCaseMeta(
342
- testInfo: TestInfo,
343
- scenario: QaScenarioCase,
344
- attachmentPrefix: string,
345
- status: QaCaseStatus,
346
- error: string | null,
347
- durationMs: number,
348
- ) {
349
- await testInfo.attach(`${attachmentPrefix}-meta`, {
350
- body: JSON.stringify({
351
- attachmentPrefix,
352
- caseIndex: scenario.qaCaseIndex,
353
- durationMs,
354
- error,
355
- imageName: scenario.roomName,
356
- imagePath: scenario.imagePath,
357
- roomName: scenario.roomName,
358
- status,
359
- surfaceClass: scenario.surfaceClass,
360
- tileName: scenario.textureName,
361
- }, null, 2),
362
- contentType: "application/json",
363
- });
364
- }
365
-
366
- function recordQaCaseProgress(
367
- scenario: QaScenarioCase,
368
- status: QaCaseStatus,
369
- error: string | null,
370
- durationMs: number,
371
- ) {
372
- QA_CASE_PROGRESS.set(qaCaseId(scenario), {
373
- durationMs,
374
- error,
375
- imageName: scenario.roomName,
376
- status,
377
- title: `${scenario.roomName}: apply ${scenario.textureName} to ${scenario.surfaceClass}`,
378
- tileName: scenario.textureName,
379
- });
380
- writeQaCaseProgress();
381
- }
382
-
383
- function writeQaCaseProgress() {
384
- const progressFile = process.env.QA_PROGRESS_FILE;
385
- if (!progressFile) return;
386
-
387
- const results = [...QA_CASE_PROGRESS.values()];
388
- const passed = results.filter((entry) => entry.status === "passed").length;
389
- const failed = results.filter((entry) => entry.status === "failed").length;
390
- const skipped = results.filter((entry) => entry.status === "skipped").length;
391
- const completed = passed + failed + skipped;
392
- const payload = {
393
- completed,
394
- failed,
395
- passed,
396
- results,
397
- skipped,
398
- status: "running",
399
- total: TOTAL_QA_CASES,
400
- updatedAt: new Date().toISOString(),
401
- };
402
-
403
- mkdirSync(path.dirname(progressFile), { recursive: true });
404
- const tempFile = `${progressFile}.${process.pid}.tmp`;
405
- writeFileSync(tempFile, JSON.stringify(payload, null, 2));
406
- renameSync(tempFile, progressFile);
407
- }
408
-
409
- function qaCaseId(scenario: QaScenarioCase) {
410
- return `${scenario.qaCaseIndex}:${scenario.imagePath}:${scenario.textureName}:${scenario.surfaceClass}`;
411
- }
412
-
413
- function qaCaseAttachmentPrefix(scenario: QaScenarioCase) {
414
- return `qa-case-${scenario.qaCaseIndex}`;
415
- }
416
-
417
- function loadScenarios() {
418
- const raw = process.env.QA_SCENARIOS?.trim();
419
- const overrides = raw ? parseScenarioOverrides(raw) : [];
420
-
421
- if (overrides.some(hasExplicitImagePath)) {
422
- return overrides.map((override, index) => {
423
- if (!hasExplicitImagePath(override)) {
424
- throw new Error(`QA_SCENARIOS[${index}] must include imagePath when any scenario uses explicit imagePath.`);
425
- }
426
-
427
- return normalizeScenario(path.resolve(override.imagePath), override, index);
428
- });
429
- }
430
-
431
- const images = findTestImages(TEST_IMAGES_DIR);
432
-
433
- return images.map((imagePath, index) => normalizeScenario(imagePath, overrides[index], index));
434
- }
435
-
436
- function groupScenarios(scenarios: QaScenario[]): QaScenarioGroup[] {
437
- const groups: QaScenarioGroup[] = [];
438
- const groupByImagePath = new Map<string, QaScenarioGroup>();
439
-
440
- for (const [index, scenario] of scenarios.entries()) {
441
- const qaCase = {
442
- ...scenario,
443
- qaCaseIndex: index + 1,
444
- };
445
- const existing = groupByImagePath.get(scenario.imagePath);
446
- if (existing) {
447
- existing.scenarios.push(qaCase);
448
- continue;
449
- }
450
-
451
- const group = {
452
- imagePath: scenario.imagePath,
453
- roomName: scenario.roomName,
454
- scenarios: [qaCase],
455
- };
456
- groupByImagePath.set(scenario.imagePath, group);
457
- groups.push(group);
458
- }
459
-
460
- return groups;
461
- }
462
-
463
- function parseScenarioOverrides(raw: string) {
464
- const parsed = JSON.parse(raw) as unknown;
465
- if (!Array.isArray(parsed)) {
466
- throw new Error("QA_SCENARIOS must be a JSON array.");
467
- }
468
-
469
- return parsed;
470
- }
471
-
472
- function hasExplicitImagePath(value: unknown): value is Record<string, unknown> & { imagePath: string } {
473
- return Boolean(
474
- value &&
475
- typeof value === "object" &&
476
- !Array.isArray(value) &&
477
- typeof (value as Record<string, unknown>).imagePath === "string" &&
478
- ((value as Record<string, unknown>).imagePath as string).trim(),
479
- );
480
- }
481
-
482
- function findTestImages(directory: string) {
483
- if (!existsSync(directory)) {
484
- throw new Error(`Test images directory does not exist: ${directory}`);
485
- }
486
-
487
- const images = readdirSync(directory)
488
- .filter((fileName) => IMAGE_EXTENSIONS.has(path.extname(fileName).toLowerCase()))
489
- .sort((a, b) => a.localeCompare(b))
490
- .map((fileName) => path.join(directory, fileName));
491
-
492
- if (images.length === 0) {
493
- throw new Error(`No test images found in ${directory}. Add .jpg, .jpeg, .png, or .webp files.`);
494
- }
495
-
496
- return images;
497
- }
498
-
499
- function normalizeScenario(imagePath: string, item: unknown, index: number): QaScenario {
500
- if (item != null && (!item || typeof item !== "object" || Array.isArray(item))) {
501
- throw new Error(`QA_SCENARIOS[${index}] must be an object when provided.`);
502
- }
503
-
504
- const value = (item ?? {}) as Record<string, unknown>;
505
- const roomName = stringValue(value.roomName, readableImageName(imagePath));
506
-
507
- return {
508
- detectionTimeoutMs: numberValue(value.detectionTimeoutMs, DEFAULT_SCENARIO_OPTIONS.detectionTimeoutMs),
509
- expectedDirectionDescription: stringValue(
510
- value.expectedDirectionDescription,
511
- DEFAULT_SCENARIO_OPTIONS.expectedDirectionDescription,
512
- ),
513
- imagePath,
514
- keyword: stringValue(value.keyword, DEFAULT_SCENARIO_OPTIONS.keyword),
515
- minAverageDelta: numberValue(value.minAverageDelta, DEFAULT_SCENARIO_OPTIONS.minAverageDelta),
516
- minChangedRatio: numberValue(value.minChangedRatio, DEFAULT_SCENARIO_OPTIONS.minChangedRatio),
517
- minDirectionQuality: numberValue(value.minDirectionQuality, DEFAULT_SCENARIO_OPTIONS.minDirectionQuality),
518
- minEdgeCompleteness: numberValue(value.minEdgeCompleteness, DEFAULT_SCENARIO_OPTIONS.minEdgeCompleteness),
519
- minLightingPreserved: numberValue(value.minLightingPreserved, DEFAULT_SCENARIO_OPTIONS.minLightingPreserved),
520
- minOcclusionBoundaryQuality: numberValue(
521
- value.minOcclusionBoundaryQuality,
522
- DEFAULT_SCENARIO_OPTIONS.minOcclusionBoundaryQuality,
523
- ),
524
- minPerspectiveQuality: numberValue(value.minPerspectiveQuality, DEFAULT_SCENARIO_OPTIONS.minPerspectiveQuality),
525
- minRealism: numberValue(value.minRealism, DEFAULT_SCENARIO_OPTIONS.minRealism),
526
- minSurfaceCorrectness: numberValue(value.minSurfaceCorrectness, DEFAULT_SCENARIO_OPTIONS.minSurfaceCorrectness),
527
- roomName,
528
- surfaceClass: stringValue(value.surfaceClass, DEFAULT_SCENARIO_OPTIONS.surfaceClass),
529
- textureDescription: stringValue(value.textureDescription, DEFAULT_SCENARIO_OPTIONS.textureDescription),
530
- textureName: stringValue(value.textureName, DEFAULT_SCENARIO_OPTIONS.textureName),
531
- };
532
- }
533
-
534
- function numberValue(value: unknown, fallback: number) {
535
- return typeof value === "number" && Number.isFinite(value) ? value : fallback;
536
- }
537
-
538
- function stringValue(value: unknown, fallback: string) {
539
- return typeof value === "string" && value.trim() ? value.trim() : fallback;
540
- }
541
-
542
- function readableImageName(imagePath: string) {
543
- return path.basename(imagePath, path.extname(imagePath));
544
- }
545
-
546
- function requireBackendUrl() {
547
- if (!process.env.API_URL && !process.env.VITE_API_URL) {
548
- throw new Error("API_URL or VITE_API_URL must point to the hosted backend for real-data QA.");
549
- }
550
- }
551
-
552
- function collectDiagnostics(page: Page) {
553
- const diagnostics = {
554
- consoleErrors: [] as string[],
555
- failedRequests: [] as string[],
556
- pageErrors: [] as string[],
557
- };
558
-
559
- page.on("console", (message) => {
560
- if (message.type() === "error") {
561
- diagnostics.consoleErrors.push(message.text());
562
- }
563
- });
564
- page.on("pageerror", (error) => {
565
- diagnostics.pageErrors.push(error.message);
566
- });
567
- page.on("requestfailed", (request) => {
568
- const url = request.url();
569
- if (!url.startsWith("data:") && !url.startsWith("blob:")) {
570
- diagnostics.failedRequests.push(`${request.method()} ${url} :: ${request.failure()?.errorText ?? "unknown"}`);
571
- }
572
- });
573
-
574
- return diagnostics;
575
- }
576
-
577
- async function attachDiagnostics(
578
- testInfo: TestInfo,
579
- diagnostics: { consoleErrors: string[]; failedRequests: string[]; pageErrors: string[] },
580
- ) {
581
- await testInfo.attach("browser-diagnostics", {
582
- body: JSON.stringify(diagnostics, null, 2),
583
- contentType: "application/json",
584
- });
585
- }
586
-
587
- function flagEnabled(name: string) {
588
- return ["1", "true", "yes", "on"].includes((process.env[name] ?? "").toLowerCase());
589
- }
590
-
591
- function errorMessage(error: unknown) {
592
- if (error instanceof Error) return error.message;
593
- return String(error);
594
- }
595
-
596
- function slug(value: string) {
597
- return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "") || "room";
598
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/viz2d-demo/e2e/support/gemini-judge.ts DELETED
@@ -1,202 +0,0 @@
1
- import { readFile } from "node:fs/promises";
2
-
3
- export type GeminiJudgeScenario = {
4
- expectedDirectionDescription?: string;
5
- roomName: string;
6
- surfaceClass: string;
7
- textureDescription?: string;
8
- textureName: string;
9
- };
10
-
11
- export type GeminiJudgeResult = {
12
- bleedDetected: boolean;
13
- coverageGapDetected: boolean;
14
- directionIssues: string[];
15
- directionMismatchDetected: boolean;
16
- directionQuality: number;
17
- edgeCompleteness: number;
18
- failureReasons: string[];
19
- lightingPreserved: number;
20
- missedFloorAreas: string[];
21
- notes: string;
22
- occlusionBoundaryQuality: number;
23
- overallPass: boolean;
24
- perspectiveQuality: number;
25
- realism: number;
26
- surfaceCorrectness: number;
27
- tileApplied: boolean;
28
- };
29
-
30
- type GeminiGenerateResponse = {
31
- candidates?: Array<{
32
- content?: {
33
- parts?: Array<{
34
- text?: string;
35
- }>;
36
- };
37
- }>;
38
- error?: {
39
- message?: string;
40
- };
41
- promptFeedback?: {
42
- blockReason?: string;
43
- };
44
- };
45
-
46
- type JudgeOptions = {
47
- afterImagePath: string;
48
- apiKey: string;
49
- beforeImagePath: string;
50
- model: string;
51
- scenario: GeminiJudgeScenario;
52
- };
53
-
54
- export async function judgeTileApplicationWithGemini(options: JudgeOptions): Promise<GeminiJudgeResult> {
55
- const beforeImage = await imagePart(options.beforeImagePath);
56
- const afterImage = await imagePart(options.afterImagePath);
57
- const modelName = options.model.replace(/^models\//, "");
58
- const endpoint = `https://generativelanguage.googleapis.com/v1beta/models/${modelName}:generateContent?key=${encodeURIComponent(options.apiKey)}`;
59
-
60
- const response = await fetch(endpoint, {
61
- body: JSON.stringify({
62
- contents: [
63
- {
64
- role: "user",
65
- parts: [
66
- { text: buildJudgePrompt(options.scenario) },
67
- beforeImage,
68
- afterImage,
69
- ],
70
- },
71
- ],
72
- generationConfig: {
73
- responseMimeType: "application/json",
74
- temperature: 0.1,
75
- },
76
- }),
77
- headers: {
78
- "Content-Type": "application/json",
79
- },
80
- method: "POST",
81
- });
82
-
83
- const payload = await response.json() as GeminiGenerateResponse;
84
- if (!response.ok) {
85
- throw new Error(payload.error?.message ?? `Gemini judge failed with HTTP ${response.status}.`);
86
- }
87
-
88
- const text = payload.candidates?.[0]?.content?.parts?.map((part) => part.text ?? "").join("\n").trim();
89
- if (!text) {
90
- throw new Error(payload.promptFeedback?.blockReason
91
- ? `Gemini judge returned no text. Block reason: ${payload.promptFeedback.blockReason}.`
92
- : "Gemini judge returned no text.");
93
- }
94
-
95
- return normalizeJudgeResult(parseJudgeJson(text));
96
- }
97
-
98
- async function imagePart(path: string) {
99
- const buffer = await readFile(path);
100
- return {
101
- inlineData: {
102
- data: buffer.toString("base64"),
103
- mimeType: "image/png",
104
- },
105
- };
106
- }
107
-
108
- function buildJudgePrompt(scenario: GeminiJudgeScenario) {
109
- return [
110
- "You are a strict visual QA judge for a room tile visualizer.",
111
- "You will receive two images: first is the room before applying texture, second is the room after applying texture.",
112
- `Expected room preset: ${scenario.roomName}.`,
113
- `Expected target surface: ${scenario.surfaceClass}.`,
114
- `Selected texture label: ${scenario.textureName}.`,
115
- scenario.textureDescription ? `Expected texture appearance: ${scenario.textureDescription}.` : "",
116
- scenario.expectedDirectionDescription
117
- ? `Expected tile direction/orientation: ${scenario.expectedDirectionDescription}.`
118
- : "",
119
- "Judge only the visual result in the room image, not UI chrome.",
120
- "Texture labels can be approximate product names; do not fail only because the visible color differs from the label when the pattern/material family is plausible.",
121
- "Compare the before and after images to identify the full visible target surface.",
122
- "For floor QA, inspect the entire visible bare floor, especially tight boundaries around sofas, armchairs, tables, table legs, cabinets, plants, doorways, wall bases, and room edges.",
123
- "Report visible bare floor areas that should receive the new material but remain as the original floor. These are coverage gaps, even when they are thin slivers around furniture or behind table legs.",
124
- "Set coverageGapDetected to true for any visible missed target-surface patches and list them in missedFloorAreas.",
125
- "Judge tile direction/orientation separately from surface coverage. For repeating tile patterns, the tile grid/veins should follow the target surface perspective and remain directionally consistent across the surface.",
126
- "Set directionMismatchDetected to true when the applied tile looks rotated in the wrong direction, inconsistent between floor regions, flipped against the expected surface direction, or visually misaligned with the floor perspective.",
127
- "Do not fail tile direction only because perspective causes natural convergence toward a vanishing point.",
128
- "Do not penalize unchanged furniture, rugs/carpets, table tops, plants, or other non-floor objects. Only penalize missed visible target-surface patches.",
129
- "Fail if the after image is blank, unchanged, the texture is not visible, the target surface is wrong, there is major bleed onto furniture/objects, coverage gaps are visible, tile direction is visibly wrong, or perspective is obviously broken.",
130
- "Return JSON only with this shape:",
131
- JSON.stringify({
132
- bleedDetected: false,
133
- coverageGapDetected: false,
134
- directionIssues: ["short direction/orientation issue locations when failing"],
135
- directionMismatchDetected: false,
136
- directionQuality: 0.0,
137
- edgeCompleteness: 0.0,
138
- failureReasons: ["short reason strings when failing"],
139
- lightingPreserved: 0.0,
140
- missedFloorAreas: ["short locations such as right sofa edge, behind coffee table, left cabinet"],
141
- notes: "one concise sentence",
142
- occlusionBoundaryQuality: 0.0,
143
- overallPass: true,
144
- perspectiveQuality: 0.0,
145
- realism: 0.0,
146
- surfaceCorrectness: 0.0,
147
- tileApplied: true,
148
- }),
149
- "Scores must be numbers from 0 to 1.",
150
- ].join("\n");
151
- }
152
-
153
- function parseJudgeJson(text: string): Record<string, unknown> {
154
- try {
155
- const parsed = JSON.parse(text) as unknown;
156
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
157
- return parsed as Record<string, unknown>;
158
- }
159
- } catch {
160
- const match = text.match(/\{[\s\S]*\}/);
161
- if (match) {
162
- const parsed = JSON.parse(match[0]) as unknown;
163
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
164
- return parsed as Record<string, unknown>;
165
- }
166
- }
167
- }
168
-
169
- throw new Error(`Gemini judge did not return valid JSON: ${text}`);
170
- }
171
-
172
- function normalizeJudgeResult(value: Record<string, unknown>): GeminiJudgeResult {
173
- return {
174
- bleedDetected: Boolean(value.bleedDetected),
175
- coverageGapDetected: Boolean(value.coverageGapDetected),
176
- directionIssues: Array.isArray(value.directionIssues)
177
- ? value.directionIssues.filter((item): item is string => typeof item === "string")
178
- : [],
179
- directionMismatchDetected: Boolean(value.directionMismatchDetected),
180
- directionQuality: score(value.directionQuality),
181
- edgeCompleteness: score(value.edgeCompleteness),
182
- failureReasons: Array.isArray(value.failureReasons)
183
- ? value.failureReasons.filter((item): item is string => typeof item === "string")
184
- : [],
185
- lightingPreserved: score(value.lightingPreserved),
186
- missedFloorAreas: Array.isArray(value.missedFloorAreas)
187
- ? value.missedFloorAreas.filter((item): item is string => typeof item === "string")
188
- : [],
189
- notes: typeof value.notes === "string" ? value.notes : "",
190
- occlusionBoundaryQuality: score(value.occlusionBoundaryQuality),
191
- overallPass: Boolean(value.overallPass),
192
- perspectiveQuality: score(value.perspectiveQuality),
193
- realism: score(value.realism),
194
- surfaceCorrectness: score(value.surfaceCorrectness),
195
- tileApplied: Boolean(value.tileApplied),
196
- };
197
- }
198
-
199
- function score(value: unknown) {
200
- if (typeof value !== "number" || !Number.isFinite(value)) return 0;
201
- return Math.max(0, Math.min(1, value));
202
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/viz2d-demo/e2e/support/image-checks.ts DELETED
@@ -1,104 +0,0 @@
1
- import { expect, type Locator } from "@playwright/test";
2
-
3
- export type CanvasSignature = {
4
- height: number;
5
- opaqueRatio: number;
6
- samples: number[];
7
- variance: number;
8
- width: number;
9
- };
10
-
11
- export type CanvasDiff = {
12
- averageDelta: number;
13
- changedRatio: number;
14
- };
15
-
16
- export async function readCanvasSignature(canvas: Locator): Promise<CanvasSignature> {
17
- return canvas.evaluate((node) => {
18
- const element = node as HTMLCanvasElement;
19
- const context = element.getContext("2d", { willReadFrequently: true });
20
- if (!context) {
21
- throw new Error("Visualizer canvas does not expose a 2D context.");
22
- }
23
-
24
- const width = element.width;
25
- const height = element.height;
26
- if (width <= 0 || height <= 0) {
27
- return {
28
- height,
29
- opaqueRatio: 0,
30
- samples: [],
31
- variance: 0,
32
- width,
33
- };
34
- }
35
-
36
- const grid = 48;
37
- const image = context.getImageData(0, 0, width, height);
38
- const samples: number[] = [];
39
- let opaque = 0;
40
- let luminanceTotal = 0;
41
- const luminanceValues: number[] = [];
42
-
43
- for (let gridY = 0; gridY < grid; gridY += 1) {
44
- const y = Math.min(height - 1, Math.round((gridY / Math.max(grid - 1, 1)) * (height - 1)));
45
- for (let gridX = 0; gridX < grid; gridX += 1) {
46
- const x = Math.min(width - 1, Math.round((gridX / Math.max(grid - 1, 1)) * (width - 1)));
47
- const index = (y * width + x) * 4;
48
- const red = image.data[index];
49
- const green = image.data[index + 1];
50
- const blue = image.data[index + 2];
51
- const alpha = image.data[index + 3];
52
- const luminance = red * 0.2126 + green * 0.7152 + blue * 0.0722;
53
-
54
- samples.push(red, green, blue, alpha);
55
- luminanceValues.push(luminance);
56
- luminanceTotal += luminance;
57
- if (alpha > 8) opaque += 1;
58
- }
59
- }
60
-
61
- const mean = luminanceTotal / Math.max(luminanceValues.length, 1);
62
- const variance = luminanceValues.reduce((total, value) => total + (value - mean) ** 2, 0) /
63
- Math.max(luminanceValues.length, 1);
64
-
65
- return {
66
- height,
67
- opaqueRatio: opaque / Math.max(luminanceValues.length, 1),
68
- samples,
69
- variance,
70
- width,
71
- };
72
- });
73
- }
74
-
75
- export function diffCanvasSignatures(before: CanvasSignature, after: CanvasSignature): CanvasDiff {
76
- const sampleLength = Math.min(before.samples.length, after.samples.length);
77
- let changed = 0;
78
- let totalDelta = 0;
79
- let compared = 0;
80
-
81
- for (let index = 0; index < sampleLength; index += 4) {
82
- const delta = (
83
- Math.abs(before.samples[index] - after.samples[index]) +
84
- Math.abs(before.samples[index + 1] - after.samples[index + 1]) +
85
- Math.abs(before.samples[index + 2] - after.samples[index + 2])
86
- ) / 3;
87
-
88
- totalDelta += delta;
89
- compared += 1;
90
- if (delta > 10) changed += 1;
91
- }
92
-
93
- return {
94
- averageDelta: compared > 0 ? totalDelta / compared : 0,
95
- changedRatio: compared > 0 ? changed / compared : 0,
96
- };
97
- }
98
-
99
- export function expectUsableCanvas(signature: CanvasSignature) {
100
- expect(signature.width, "canvas should have a rendered width").toBeGreaterThan(80);
101
- expect(signature.height, "canvas should have a rendered height").toBeGreaterThan(80);
102
- expect(signature.opaqueRatio, "canvas should not be transparent/blank").toBeGreaterThan(0.8);
103
- expect(signature.variance, "canvas should contain image detail").toBeGreaterThan(25);
104
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/viz2d-demo/e2e/support/qa-progress-reporter.cjs DELETED
@@ -1,76 +0,0 @@
1
- const fs = require("fs");
2
- const path = require("path");
3
-
4
- function normalizeStatus(status) {
5
- if (status === "passed" || status === "skipped") return status;
6
- return "failed";
7
- }
8
-
9
- class QaProgressReporter {
10
- constructor() {
11
- this.disabled = process.env.QA_PROGRESS_MODE === "cases";
12
- this.progressFile = process.env.QA_PROGRESS_FILE;
13
- this.resultByTest = new Map();
14
- this.testOrder = [];
15
- this.total = 0;
16
- }
17
-
18
- onBegin(_config, suite) {
19
- if (this.disabled) return;
20
- const tests = suite.allTests();
21
- this.testOrder = tests.map((test) => this.testKey(test));
22
- this.total = tests.length;
23
- this.write("running");
24
- }
25
-
26
- onTestEnd(test, result) {
27
- if (this.disabled) return;
28
- const key = this.testKey(test);
29
- if (!this.testOrder.includes(key)) this.testOrder.push(key);
30
- this.resultByTest.set(key, {
31
- durationMs: result.duration,
32
- error: result.error?.message || null,
33
- status: normalizeStatus(result.status),
34
- title: test.title,
35
- });
36
- this.write("running");
37
- }
38
-
39
- onEnd(result) {
40
- if (this.disabled) return;
41
- this.write(result.status === "passed" ? "completed" : "failed");
42
- }
43
-
44
- write(status) {
45
- if (!this.progressFile) return;
46
-
47
- const results = this.testOrder
48
- .map((key) => this.resultByTest.get(key))
49
- .filter(Boolean);
50
- const passed = results.filter((entry) => entry.status === "passed").length;
51
- const failed = results.filter((entry) => entry.status === "failed").length;
52
- const skipped = results.filter((entry) => entry.status === "skipped").length;
53
- const completed = passed + failed + skipped;
54
- const payload = {
55
- completed,
56
- failed,
57
- passed,
58
- results,
59
- skipped,
60
- status,
61
- total: this.total,
62
- updatedAt: new Date().toISOString(),
63
- };
64
-
65
- fs.mkdirSync(path.dirname(this.progressFile), { recursive: true });
66
- const tempFile = `${this.progressFile}.${process.pid}.tmp`;
67
- fs.writeFileSync(tempFile, JSON.stringify(payload, null, 2));
68
- fs.renameSync(tempFile, this.progressFile);
69
- }
70
-
71
- testKey(test) {
72
- return test.id || test.titlePath().join(" > ");
73
- }
74
- }
75
-
76
- module.exports = QaProgressReporter;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/viz2d-demo/playwright.config.ts DELETED
@@ -1,61 +0,0 @@
1
- import { defineConfig, devices } from "@playwright/test";
2
-
3
- const port = Number(process.env.PLAYWRIGHT_PORT ?? 4173);
4
- const baseURL = process.env.PLAYWRIGHT_BASE_URL ?? `http://127.0.0.1:${port}`;
5
- const backendUrl = process.env.API_URL ?? process.env.VITE_API_URL;
6
- const resultsDir = process.env.QA_RESULTS_DIR ?? "test-results";
7
- const htmlReportDir = process.env.QA_HTML_REPORT_DIR ?? "playwright-report";
8
- const outputDir = process.env.QA_PLAYWRIGHT_OUTPUT_DIR ?? resultsDir;
9
- const webServerEnv = backendUrl
10
- ? {
11
- API_URL: backendUrl,
12
- VITE_API_URL: backendUrl,
13
- }
14
- : {};
15
-
16
- export default defineConfig({
17
- testDir: "./e2e",
18
- timeout: Number(process.env.QA_TEST_TIMEOUT_MS ?? 900_000),
19
- expect: {
20
- timeout: 30_000,
21
- },
22
- fullyParallel: false,
23
- outputDir,
24
- workers: Number(process.env.QA_WORKERS ?? 1),
25
- retries: process.env.CI ? 1 : 0,
26
- reporter: [
27
- ["list"],
28
- ["./e2e/support/qa-progress-reporter.cjs"],
29
- ["html", { open: "never", outputFolder: htmlReportDir }],
30
- ["json", { outputFile: `${resultsDir}/real-qa.json` }],
31
- ],
32
- use: {
33
- baseURL,
34
- actionTimeout: 30_000,
35
- navigationTimeout: 60_000,
36
- screenshot: "only-on-failure",
37
- trace: "retain-on-failure",
38
- video: "retain-on-failure",
39
- viewport: {
40
- width: 1440,
41
- height: 1000,
42
- },
43
- },
44
- projects: [
45
- {
46
- name: "chromium",
47
- use: { ...devices["Desktop Chrome"] },
48
- },
49
- ],
50
- ...(process.env.PLAYWRIGHT_BASE_URL
51
- ? {}
52
- : {
53
- webServer: {
54
- command: `npm run preview -- --host 127.0.0.1 --port ${port}`,
55
- env: webServerEnv,
56
- reuseExistingServer: !process.env.CI,
57
- timeout: 120_000,
58
- url: baseURL,
59
- },
60
- }),
61
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Model loading, inference helpers, and metadata utilities.
models/depth.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Depth estimation and 3D geometry inference."""
2
+
3
+ import cv2
4
+ import numpy as np
5
+ import torch
6
+ from PIL import Image
7
+
8
+ import state
9
+ from config.models import DEPTH_MODEL_NAME, GEOMETRY_MODEL, MOGE_MODEL_NAME
10
+ from config.runtime import ENABLE_DEPTH_ESTIMATION, ENABLE_MOGE_GEOMETRY
11
+ from models.loader import _load_depth_model, _load_moge_model
12
+ from enums import GeometryProvider
13
+ from utils import to_numpy
14
+
15
+
16
+ def estimate_depth(img: Image.Image, width: int, height: int):
17
+ if not ENABLE_DEPTH_ESTIMATION:
18
+ return None
19
+
20
+ try:
21
+ if not _load_depth_model():
22
+ return None
23
+
24
+ inputs = state.depth_processor(images=img, return_tensors="pt").to(state.device)
25
+ with torch.no_grad():
26
+ outputs = state.depth_model(**inputs)
27
+ depth = torch.nn.functional.interpolate(
28
+ outputs.predicted_depth.unsqueeze(1),
29
+ size=(height, width),
30
+ mode="bicubic",
31
+ align_corners=False,
32
+ ).squeeze().cpu().numpy()
33
+ depth = cv2.GaussianBlur(depth.astype(np.float32), (0, 0), sigmaX=3)
34
+ if "metric" in DEPTH_MODEL_NAME.lower():
35
+ return depth
36
+ depth_min, depth_max = float(np.min(depth)), float(np.max(depth))
37
+ if depth_max - depth_min < 1e-6:
38
+ return None
39
+ return (depth - depth_min) / (depth_max - depth_min)
40
+ except Exception as exc:
41
+ print(f"Depth estimation skipped ({exc}).", flush=True)
42
+ return None
43
+
44
+
45
+ def estimate_moge_geometry(img_np: np.ndarray):
46
+ if not ENABLE_MOGE_GEOMETRY or GEOMETRY_MODEL != "moge" or state.device.type != "cuda":
47
+ return None
48
+
49
+ try:
50
+ if not _load_moge_model():
51
+ return None
52
+
53
+ image_tensor = torch.from_numpy(img_np.astype(np.float32) / 255.0).permute(2, 0, 1).to(state.device)
54
+ with torch.inference_mode(), torch.autocast(device_type="cuda", dtype=torch.float16):
55
+ output = state.moge_model.infer(image_tensor)
56
+
57
+ points = to_numpy(output.get("points"))
58
+ depth = to_numpy(output.get("depth"))
59
+ normals = to_numpy(output.get("normal"))
60
+ valid_mask = to_numpy(output.get("mask"))
61
+ intrinsics = to_numpy(output.get("intrinsics"))
62
+ if points is None or points.ndim != 3 or points.shape[2] != 3:
63
+ raise RuntimeError("MoGe did not return an HxWx3 point map.")
64
+ h, w = img_np.shape[:2]
65
+ if points.shape[:2] != (h, w):
66
+ points = cv2.resize(points, (w, h), interpolation=cv2.INTER_LINEAR)
67
+ if depth is not None and depth.shape[:2] != (h, w):
68
+ depth = cv2.resize(depth, (w, h), interpolation=cv2.INTER_LINEAR)
69
+ if normals is not None and normals.shape[:2] != (h, w):
70
+ normals = cv2.resize(normals, (w, h), interpolation=cv2.INTER_LINEAR)
71
+ if valid_mask is not None and valid_mask.shape[:2] != (h, w):
72
+ valid_mask = cv2.resize(
73
+ valid_mask.astype(np.uint8),
74
+ (w, h),
75
+ interpolation=cv2.INTER_NEAREST,
76
+ ).astype(bool)
77
+ if depth is None:
78
+ depth = points[:, :, 2]
79
+ if valid_mask is None:
80
+ valid_mask = np.isfinite(depth) & (depth > 0)
81
+
82
+ print(
83
+ "[FLOOR_3D_POINTS] generated raw MoGe HxWx3 point map "
84
+ f"shape={points.shape} validPixels={int(valid_mask.sum())} provider=moge-2",
85
+ flush=True,
86
+ )
87
+ return {
88
+ "provider": GeometryProvider.MOGE_2,
89
+ "points": points.astype(np.float32),
90
+ "depth": depth.astype(np.float32),
91
+ "normals": normals.astype(np.float32) if normals is not None else None,
92
+ "validMask": valid_mask.astype(bool),
93
+ "intrinsics": intrinsics.astype(np.float32) if intrinsics is not None else None,
94
+ }
95
+ except Exception as exc:
96
+ print(f"MoGe geometry estimation failed ({exc}); falling back to depth.", flush=True)
97
+ if state.device.type == "cuda":
98
+ torch.cuda.empty_cache()
99
+ return None
100
+
101
+
102
+ def estimate_scene_geometry(img: Image.Image, img_np: np.ndarray, width: int, height: int):
103
+ geometry = estimate_moge_geometry(img_np)
104
+ if geometry is not None:
105
+ return geometry
106
+
107
+ depth = estimate_depth(img, width, height)
108
+ depth_provider = GeometryProvider.HOMOGRAPHY
109
+ if depth is not None:
110
+ depth_provider = (
111
+ GeometryProvider.DEPTH_ANYTHING_METRIC
112
+ if "metric" in DEPTH_MODEL_NAME.lower()
113
+ else GeometryProvider.RELATIVE_DEPTH
114
+ )
115
+ return {
116
+ "provider": depth_provider,
117
+ "points": None,
118
+ "depth": depth,
119
+ "normals": None,
120
+ "validMask": np.isfinite(depth) & (depth > 0) if depth is not None else None,
121
+ "intrinsics": None,
122
+ }
models/loader.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Lazy model loading and warm-start logic."""
2
+
3
+ import time
4
+
5
+ import torch
6
+
7
+ import state
8
+ from config.models import (
9
+ ONEFORMER_MODEL_NAME,
10
+ DEPTH_MODEL_NAME,
11
+ GEOMETRY_MODEL,
12
+ MOGE_MODEL_NAME,
13
+ SAM2_MODEL_CFG,
14
+ SAM2_CHECKPOINT,
15
+ SAM2_MODEL_NAME,
16
+ INTRINSIC_MODEL_VERSION,
17
+ )
18
+ from config.runtime import (
19
+ ENABLE_MOGE_GEOMETRY,
20
+ ENABLE_SAM_REFINEMENT,
21
+ ENABLE_DEPTH_ESTIMATION,
22
+ ENABLE_INTRINSIC_SHADING,
23
+ ENABLE_SHADING_TRANSFER,
24
+ WARM_START_MODELS,
25
+ )
26
+ from transformers import (
27
+ AutoImageProcessor,
28
+ AutoModelForDepthEstimation,
29
+ OneFormerForUniversalSegmentation,
30
+ OneFormerProcessor,
31
+ )
32
+
33
+
34
+ def _load_segmentation_model():
35
+ if state.seg_processor is not None and state.seg_model is not None:
36
+ return
37
+
38
+ print(f"Loading OneFormer: {ONEFORMER_MODEL_NAME} ...", flush=True)
39
+ state.seg_processor = OneFormerProcessor.from_pretrained(
40
+ ONEFORMER_MODEL_NAME,
41
+ local_files_only=state.hf_offline(),
42
+ )
43
+ state.seg_model = OneFormerForUniversalSegmentation.from_pretrained(
44
+ ONEFORMER_MODEL_NAME,
45
+ local_files_only=state.hf_offline(),
46
+ ).to(state.device)
47
+ state.seg_model.eval()
48
+ print("OneFormer loaded.", flush=True)
49
+
50
+
51
+ def _load_intrinsic_model():
52
+ if ENABLE_INTRINSIC_SHADING and state.intrinsic_models is None:
53
+ try:
54
+ print(f"Loading Intrinsic Image Decomposition model: {INTRINSIC_MODEL_VERSION} ...", flush=True)
55
+ from intrinsic.pipeline import load_models
56
+ state.intrinsic_models = load_models(INTRINSIC_MODEL_VERSION, device=str(state.device))
57
+ print("Intrinsic model loaded.", flush=True)
58
+ except Exception as exc:
59
+ print(f"Intrinsic model failed to load ({exc}). Falling back to luminance shading.", flush=True)
60
+
61
+
62
+ def _load_depth_model() -> bool:
63
+ if not ENABLE_DEPTH_ESTIMATION:
64
+ return False
65
+ if state.depth_processor is not None and state.depth_model is not None:
66
+ return True
67
+
68
+ print(f"Loading depth model: {DEPTH_MODEL_NAME} ...", flush=True)
69
+ state.depth_processor = AutoImageProcessor.from_pretrained(
70
+ DEPTH_MODEL_NAME,
71
+ local_files_only=state.hf_offline(),
72
+ )
73
+ state.depth_model = AutoModelForDepthEstimation.from_pretrained(
74
+ DEPTH_MODEL_NAME,
75
+ local_files_only=state.hf_offline(),
76
+ ).to(state.device)
77
+ state.depth_model.eval()
78
+ print("Depth model loaded.", flush=True)
79
+ return True
80
+
81
+
82
+ def _load_moge_model() -> bool:
83
+ if not ENABLE_MOGE_GEOMETRY or GEOMETRY_MODEL != "moge" or state.device.type != "cuda":
84
+ return False
85
+ if state.moge_model is not None:
86
+ return True
87
+
88
+ print(f"Loading MoGe geometry model: {MOGE_MODEL_NAME} ...", flush=True)
89
+ from moge.model.v2 import MoGeModel
90
+ state.moge_model = MoGeModel.from_pretrained(MOGE_MODEL_NAME).to(state.device)
91
+ state.moge_model.eval()
92
+ print("MoGe geometry model loaded.", flush=True)
93
+ return True
94
+
95
+
96
+ def _load_sam2_predictor():
97
+ if not ENABLE_SAM_REFINEMENT:
98
+ return None
99
+ if state.sam2_predictor is not None:
100
+ return state.sam2_predictor
101
+ try:
102
+ from sam2.sam2_image_predictor import SAM2ImagePredictor
103
+
104
+ if SAM2_MODEL_CFG and SAM2_CHECKPOINT:
105
+ from sam2.build_sam import build_sam2
106
+
107
+ model = build_sam2(SAM2_MODEL_CFG, SAM2_CHECKPOINT, device=str(state.device))
108
+ model.eval()
109
+ state.sam2_predictor = SAM2ImagePredictor(model)
110
+ else:
111
+ state.sam2_predictor = SAM2ImagePredictor.from_pretrained(SAM2_MODEL_NAME)
112
+ if hasattr(state.sam2_predictor, "model"):
113
+ state.sam2_predictor.model.to(state.device)
114
+ state.sam2_predictor.model.eval()
115
+ print("SAM2 refinement model loaded.", flush=True)
116
+ return state.sam2_predictor
117
+ except Exception as exc:
118
+ print(f"SAM2 refinement unavailable ({exc}).", flush=True)
119
+ if state.device.type == "cuda":
120
+ torch.cuda.empty_cache()
121
+ return None
122
+
123
+
124
+ def warm_start_models():
125
+ if not WARM_START_MODELS:
126
+ print("Model warm start disabled; models will load on first use.", flush=True)
127
+ return
128
+
129
+ t_start = time.perf_counter()
130
+ print(f"Warm-starting visualizer models on {state.device} ...", flush=True)
131
+
132
+ _load_segmentation_model()
133
+
134
+ moge_loaded = False
135
+ if ENABLE_MOGE_GEOMETRY and GEOMETRY_MODEL == "moge":
136
+ try:
137
+ moge_loaded = _load_moge_model()
138
+ except Exception as exc:
139
+ print(f"MoGe warm start skipped ({exc}); depth fallback may be used.", flush=True)
140
+ if state.device.type == "cuda":
141
+ torch.cuda.empty_cache()
142
+
143
+ if ENABLE_DEPTH_ESTIMATION and not moge_loaded:
144
+ try:
145
+ _load_depth_model()
146
+ except Exception as exc:
147
+ print(f"Depth model warm start skipped ({exc}); depth will be retried on first use.", flush=True)
148
+ if state.device.type == "cuda":
149
+ torch.cuda.empty_cache()
150
+
151
+ if ENABLE_SAM_REFINEMENT:
152
+ _load_sam2_predictor()
153
+
154
+ if ENABLE_SHADING_TRANSFER and ENABLE_INTRINSIC_SHADING:
155
+ _load_intrinsic_model()
156
+
157
+ print(f"[TIMING] Model warm start took {time.perf_counter() - t_start:.3f} seconds", flush=True)
models/segmentation.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Segmentation inference and model metadata helpers."""
2
+
3
+ import numpy as np
4
+ import torch
5
+ from PIL import Image
6
+
7
+ import state
8
+ from config.models import (
9
+ DEPTH_MODEL_NAME,
10
+ INTRINSIC_MODEL_VERSION,
11
+ MOGE_MODEL_NAME,
12
+ ONEFORMER_MODEL_NAME,
13
+ )
14
+ from config.runtime import ENABLE_INTRINSIC_SHADING
15
+ from models.loader import _load_segmentation_model
16
+ from enums import GeometryProvider
17
+
18
+
19
+ def run_segmentation(img: Image.Image, img_np: np.ndarray):
20
+ if state.seg_model is None:
21
+ _load_segmentation_model()
22
+ h, w = img_np.shape[:2]
23
+ inputs = state.seg_processor(
24
+ images=img,
25
+ task_inputs=["semantic"],
26
+ return_tensors="pt",
27
+ ).to(state.device)
28
+ with torch.no_grad():
29
+ outputs = state.seg_model(**inputs)
30
+ result = state.seg_processor.post_process_semantic_segmentation(
31
+ outputs,
32
+ target_sizes=[(h, w)],
33
+ )[0]
34
+ return result.cpu().numpy().astype(np.uint8)
35
+
36
+
37
+ def segmenter_metadata_name() -> str:
38
+ return "oneformer-ade20k-swin-large"
39
+
40
+
41
+ def active_segmentation_model_name() -> str:
42
+ return ONEFORMER_MODEL_NAME
43
+
44
+
45
+ def active_geometry_model_name(provider: str | None) -> str | None:
46
+ if provider == GeometryProvider.MOGE_2:
47
+ return MOGE_MODEL_NAME
48
+ if provider and provider != GeometryProvider.HOMOGRAPHY:
49
+ return DEPTH_MODEL_NAME
50
+ return None
51
+
52
+
53
+ def active_model_metadata(
54
+ geometry: dict | None,
55
+ depth: np.ndarray | None,
56
+ shade_map: np.ndarray | None,
57
+ intrinsic_lighting_used: bool = False,
58
+ ) -> dict:
59
+ geometry_provider = geometry.get("provider") if geometry else None
60
+ intrinsic_enabled = ENABLE_INTRINSIC_SHADING and intrinsic_lighting_used and shade_map is not None
61
+ return {
62
+ "segmentation": {
63
+ "backend": state.segmentation_backend,
64
+ "name": active_segmentation_model_name(),
65
+ },
66
+ "geometry": {
67
+ "provider": geometry_provider,
68
+ "name": active_geometry_model_name(geometry_provider),
69
+ },
70
+ "depth": {
71
+ "enabled": depth is not None,
72
+ "name": DEPTH_MODEL_NAME if depth is not None else None,
73
+ },
74
+ "intrinsic": {
75
+ "enabled": intrinsic_enabled,
76
+ "name": INTRINSIC_MODEL_VERSION if intrinsic_enabled else None,
77
+ },
78
+ }
qa/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # QA subsystem for floor visualizer backend.
qa/constants.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """QA tile descriptions, aliases, and image extension whitelist."""
2
+
3
+ QA_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"}
4
+
5
+ QA_TILE_DESCRIPTIONS = {
6
+ "White Wood Flooring": "light plank flooring",
7
+ "Black White Marble Checkered": "black and white marble checkerboard tile",
8
+ "Grey Checkerboard": "grey checkerboard floor tile",
9
+ "Lilac 20x20 Ceramic": "lilac 20x20 ceramic tile",
10
+ }
11
+
12
+ QA_TILE_ALIASES = {
13
+ "Black White Marble Checker": "Black White Marble Checkered",
14
+ }
qa/images.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """QA image listing and deduplication via DigitalOcean Spaces."""
2
+
3
+ import mimetypes
4
+ import urllib.parse
5
+ from datetime import timedelta
6
+ from pathlib import Path
7
+
8
+ from config.qa import QA_PRESIGNED_URL_EXPIRES_SECONDS
9
+ from config.spaces import SPACES_BUCKET, SPACES_UPLOAD_PREFIX
10
+ from errors import bad_request
11
+ from qa.constants import QA_IMAGE_EXTENSIONS
12
+ from qa.store import qa_utc_now
13
+ from services.spaces.upload import spaces_client
14
+
15
+
16
+ def qa_parse_date(value: str | None, name: str):
17
+ if not value:
18
+ return None
19
+ try:
20
+ from datetime import datetime
21
+ return datetime.strptime(value, "%Y-%m-%d").date()
22
+ except ValueError as exc:
23
+ bad_request(f"{name} must use YYYY-MM-DD.", exc)
24
+
25
+
26
+ def qa_date_prefixes(range_name: str, from_value: str | None, to_value: str | None):
27
+ today = qa_utc_now().date()
28
+ range_key = (range_name or "week").lower()
29
+
30
+ if range_key == "all":
31
+ return [SPACES_UPLOAD_PREFIX] if SPACES_UPLOAD_PREFIX else [""]
32
+ if range_key == "today":
33
+ start = today
34
+ end = today
35
+ elif range_key == "week":
36
+ start = today - timedelta(days=6)
37
+ end = today
38
+ elif range_key == "month":
39
+ start = today.replace(day=1)
40
+ end = today
41
+ elif range_key == "custom":
42
+ start = qa_parse_date(from_value, "from") or today
43
+ end = qa_parse_date(to_value, "to") or start
44
+ else:
45
+ bad_request("range must be today, week, month, all, or custom.")
46
+
47
+ if start > end:
48
+ bad_request("from must be before or equal to to.")
49
+ if (end - start).days > 370:
50
+ bad_request("Date range is too large.")
51
+
52
+ prefixes = []
53
+ cursor = start
54
+ while cursor <= end:
55
+ prefixes.append("/".join(part for part in [SPACES_UPLOAD_PREFIX, cursor.strftime("%Y/%m/%d")] if part))
56
+ cursor += timedelta(days=1)
57
+ return prefixes
58
+
59
+
60
+ def qa_clean_etag(value) -> str:
61
+ return str(value or "").strip().strip('"')
62
+
63
+
64
+ def qa_object_fingerprint(etag, size) -> str | None:
65
+ clean_etag = qa_clean_etag(etag)
66
+ if not clean_etag:
67
+ return None
68
+ return f"{clean_etag}:{size or 0}"
69
+
70
+
71
+ def dedupe_qa_image_keys(image_keys: list[str]) -> list[str]:
72
+ client = spaces_client()
73
+ unique_keys: list[str] = []
74
+ seen_keys: set[str] = set()
75
+ seen_fingerprints: set[str] = set()
76
+
77
+ for key in image_keys:
78
+ if key in seen_keys:
79
+ continue
80
+ seen_keys.add(key)
81
+
82
+ try:
83
+ metadata = client.head_object(Bucket=SPACES_BUCKET, Key=key)
84
+ except Exception as exc:
85
+ bad_request(f"Could not read DigitalOcean image metadata for {key}.", exc)
86
+
87
+ fingerprint = qa_object_fingerprint(metadata.get("ETag"), metadata.get("ContentLength"))
88
+ if fingerprint and fingerprint in seen_fingerprints:
89
+ continue
90
+ if fingerprint:
91
+ seen_fingerprints.add(fingerprint)
92
+ unique_keys.append(key)
93
+
94
+ return unique_keys
95
+
96
+
97
+ def list_qa_spaces_images(range_name: str, from_value: str | None, to_value: str | None, max_items: int):
98
+ client = spaces_client()
99
+ paginator = client.get_paginator("list_objects_v2")
100
+ images: list[dict] = []
101
+ seen: set[str] = set()
102
+ seen_fingerprints: set[str] = set()
103
+
104
+ for prefix in qa_date_prefixes(range_name, from_value, to_value):
105
+ kwargs = {"Bucket": SPACES_BUCKET, "Prefix": prefix}
106
+ for page in paginator.paginate(**kwargs):
107
+ for item in page.get("Contents", []):
108
+ key = item.get("Key", "")
109
+ if not key or key in seen or Path(key).suffix.lower() not in QA_IMAGE_EXTENSIONS:
110
+ continue
111
+ fingerprint = qa_object_fingerprint(item.get("ETag"), item.get("Size"))
112
+ if fingerprint and fingerprint in seen_fingerprints:
113
+ continue
114
+ seen.add(key)
115
+ if fingerprint:
116
+ seen_fingerprints.add(fingerprint)
117
+ url = client.generate_presigned_url(
118
+ "get_object",
119
+ Params={"Bucket": SPACES_BUCKET, "Key": key},
120
+ ExpiresIn=QA_PRESIGNED_URL_EXPIRES_SECONDS,
121
+ )
122
+ last_modified = item.get("LastModified")
123
+ images.append({
124
+ "key": key,
125
+ "fileName": urllib.parse.unquote(Path(key).name),
126
+ "url": url,
127
+ "thumbnailUrl": url,
128
+ "uploadedAt": last_modified.isoformat().replace("+00:00", "Z") if last_modified else None,
129
+ "sizeBytes": item.get("Size"),
130
+ "contentType": mimetypes.guess_type(key)[0] or "application/octet-stream",
131
+ "etag": qa_clean_etag(item.get("ETag")),
132
+ })
133
+ if len(images) >= max_items:
134
+ return sorted(images, key=lambda image: image.get("uploadedAt") or "", reverse=True)
135
+
136
+ return sorted(images, key=lambda image: image.get("uploadedAt") or "", reverse=True)
qa/report.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """QA HTML report generation: build a standalone HTML report from run data."""
2
+
3
+ import html
4
+
5
+ from enums import QaResult, QaStatus
6
+ from qa.store import qa_int
7
+
8
+
9
+ def qa_html(value) -> str:
10
+ if value is None:
11
+ return ""
12
+ return html.escape(str(value), quote=True)
13
+
14
+
15
+ def qa_status_label(status) -> str:
16
+ value = str(status or "unknown").lower()
17
+ if value in {s.value for s in QaStatus} | {r.value for r in QaResult}:
18
+ return value
19
+ return "unknown"
20
+
21
+
22
+ def qa_yes_no(value) -> str:
23
+ if isinstance(value, bool):
24
+ return "yes" if value else "no"
25
+ return "n/a"
26
+
27
+
28
+ def qa_score_label(value) -> str:
29
+ if isinstance(value, (int, float)):
30
+ try:
31
+ import math
32
+ if math.isfinite(value):
33
+ return f"{float(value):.2f}"
34
+ except (TypeError, ValueError):
35
+ pass
36
+ return "n/a"
37
+
38
+
39
+ def qa_list_label(value) -> str:
40
+ if isinstance(value, list):
41
+ items = [str(item) for item in value if isinstance(item, str) and item.strip()]
42
+ if items:
43
+ return "; ".join(items)
44
+ return "none"
45
+
46
+
47
+ def qa_metric_html(label: str, value: str) -> str:
48
+ return f"<span><strong>{qa_html(value)}</strong>{qa_html(label)}</span>"
49
+
50
+
51
+ def qa_image_html(label: str, url) -> str:
52
+ if not isinstance(url, str) or not url.strip():
53
+ return f"""
54
+ <div class="image-panel missing">
55
+ <span>{qa_html(label)}</span>
56
+ <p>Missing screenshot</p>
57
+ </div>
58
+ """
59
+ return f"""
60
+ <div class="image-panel">
61
+ <span>{qa_html(label)}</span>
62
+ <img src="{qa_html(url)}" alt="{qa_html(label)} QA screenshot" loading="lazy" />
63
+ </div>
64
+ """
65
+
66
+
67
+ def qa_gemini_report_html(gemini) -> str:
68
+ if not isinstance(gemini, dict):
69
+ return '<p class="muted">Gemini was not used or did not return a judgment for this result.</p>'
70
+
71
+ issue_rows = []
72
+ if gemini.get("coverageGapDetected"):
73
+ issue_rows.append(f"<li>Coverage gaps: {qa_html(qa_list_label(gemini.get('missedFloorAreas')))}</li>")
74
+ if gemini.get("directionMismatchDetected"):
75
+ issue_rows.append(f"<li>Direction issues: {qa_html(qa_list_label(gemini.get('directionIssues')))}</li>")
76
+ if gemini.get("bleedDetected"):
77
+ issue_rows.append("<li>Bleed detected on non-target surfaces.</li>")
78
+ if isinstance(gemini.get("failureReasons"), list) and gemini.get("failureReasons"):
79
+ issue_rows.append(f"<li>Failure reasons: {qa_html(qa_list_label(gemini.get('failureReasons')))}</li>")
80
+
81
+ issues_html = f"<ul>{''.join(issue_rows)}</ul>" if issue_rows else ""
82
+ metrics_html = "".join([
83
+ qa_metric_html("overall", qa_yes_no(gemini.get("overallPass"))),
84
+ qa_metric_html("tile", qa_yes_no(gemini.get("tileApplied"))),
85
+ qa_metric_html("coverage gap", qa_yes_no(gemini.get("coverageGapDetected"))),
86
+ qa_metric_html("direction", qa_score_label(gemini.get("directionQuality"))),
87
+ qa_metric_html("surface", qa_score_label(gemini.get("surfaceCorrectness"))),
88
+ qa_metric_html("edge", qa_score_label(gemini.get("edgeCompleteness"))),
89
+ qa_metric_html("occlusion", qa_score_label(gemini.get("occlusionBoundaryQuality"))),
90
+ qa_metric_html("perspective", qa_score_label(gemini.get("perspectiveQuality"))),
91
+ qa_metric_html("lighting", qa_score_label(gemini.get("lightingPreserved"))),
92
+ qa_metric_html("realism", qa_score_label(gemini.get("realism"))),
93
+ ])
94
+
95
+ return f"""
96
+ <div class="gemini">
97
+ <div class="metrics">{metrics_html}</div>
98
+ <p>{qa_html(gemini.get("notes") or "No notes returned.")}</p>
99
+ {issues_html}
100
+ </div>
101
+ """
102
+
103
+
104
+ def qa_result_report_html(result: dict, index: int) -> str:
105
+ status = qa_status_label(result.get("status"))
106
+ image_name = result.get("imageName") or result.get("imageKey") or "Unknown image"
107
+ tile_name = result.get("tileName") or "Unknown tile"
108
+ error_html = f'<p class="error">{qa_html(result.get("error"))}</p>' if result.get("error") else ""
109
+ return f"""
110
+ <article class="result-card status-{status}">
111
+ <header>
112
+ <div>
113
+ <p class="eyebrow">{qa_html(tile_name)}</p>
114
+ <h2>{index}. {qa_html(image_name)}</h2>
115
+ </div>
116
+ <span class="badge status-{status}">{qa_html(status)}</span>
117
+ </header>
118
+ <div class="image-stack">
119
+ {qa_image_html("Before", result.get("beforeImageUrl"))}
120
+ {qa_image_html("After Tile Applied", result.get("afterImageUrl"))}
121
+ </div>
122
+ {error_html}
123
+ <section>
124
+ <h3>Gemini Judgment</h3>
125
+ {qa_gemini_report_html(result.get("gemini"))}
126
+ </section>
127
+ </article>
128
+ """
129
+
130
+
131
+ def build_qa_report_html(run: dict) -> str:
132
+ status = qa_status_label(run.get("status"))
133
+ results = run.get("results") if isinstance(run.get("results"), list) else []
134
+ result_cards = "\n".join(
135
+ qa_result_report_html(result, index)
136
+ for index, result in enumerate(results, start=1)
137
+ if isinstance(result, dict)
138
+ )
139
+ if not result_cards:
140
+ result_cards = """
141
+ <section class="empty">
142
+ <h2>No screenshots yet</h2>
143
+ <p>The report will include screenshots and Gemini judgment after Playwright writes the final report.</p>
144
+ </section>
145
+ """
146
+ error_html = f'<p class="error">{qa_html(run.get("error"))}</p>' if run.get("error") else ""
147
+ title = f"QA Report {run.get('id', '')}".strip()
148
+
149
+ return f"""<!doctype html>
150
+ <html lang="en">
151
+ <head>
152
+ <meta charset="utf-8" />
153
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
154
+ <title>{qa_html(title)}</title>
155
+ <style>
156
+ :root {{
157
+ color-scheme: light;
158
+ --bg: #f6f7fb;
159
+ --panel: #ffffff;
160
+ --ink: #172033;
161
+ --muted: #667085;
162
+ --line: #d8deea;
163
+ --passed: #177245;
164
+ --failed: #b4233a;
165
+ --running: #1d5fbf;
166
+ }}
167
+ * {{ box-sizing: border-box; }}
168
+ body {{
169
+ margin: 0;
170
+ background: var(--bg);
171
+ color: var(--ink);
172
+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
173
+ line-height: 1.5;
174
+ }}
175
+ main {{ width: min(1120px, calc(100% - 32px)); margin: 0 auto; padding: 32px 0 56px; }}
176
+ .topbar {{ display: flex; justify-content: space-between; gap: 16px; align-items: flex-start; margin-bottom: 20px; }}
177
+ h1, h2, h3, p {{ margin-top: 0; }}
178
+ h1 {{ font-size: clamp(28px, 4vw, 42px); margin-bottom: 8px; }}
179
+ h2 {{ font-size: 20px; margin-bottom: 4px; }}
180
+ h3 {{ font-size: 14px; margin-bottom: 10px; text-transform: uppercase; color: var(--muted); letter-spacing: .04em; }}
181
+ .eyebrow {{ color: var(--muted); font-size: 12px; font-weight: 800; letter-spacing: .06em; text-transform: uppercase; margin-bottom: 6px; }}
182
+ .summary, .metrics {{ display: flex; flex-wrap: wrap; gap: 8px; }}
183
+ .summary span, .metrics span {{
184
+ border: 1px solid var(--line);
185
+ border-radius: 8px;
186
+ background: #fff;
187
+ color: var(--muted);
188
+ display: inline-flex;
189
+ gap: 6px;
190
+ padding: 7px 10px;
191
+ font-size: 13px;
192
+ align-items: baseline;
193
+ }}
194
+ .summary strong, .metrics strong {{ color: var(--ink); }}
195
+ .badge {{
196
+ border: 1px solid var(--line);
197
+ border-radius: 999px;
198
+ background: #fff;
199
+ color: var(--muted);
200
+ padding: 6px 10px;
201
+ font-size: 12px;
202
+ font-weight: 800;
203
+ text-transform: uppercase;
204
+ white-space: nowrap;
205
+ }}
206
+ .status-passed, .status-completed {{ color: var(--passed); border-color: #9bd4b5; }}
207
+ .status-failed {{ color: var(--failed); border-color: #f0a4b3; }}
208
+ .status-running, .status-queued {{ color: var(--running); border-color: #a9c7ff; }}
209
+ .result-card, .empty {{
210
+ background: var(--panel);
211
+ border: 1px solid var(--line);
212
+ border-radius: 10px;
213
+ padding: 18px;
214
+ margin-top: 18px;
215
+ box-shadow: 0 10px 30px rgba(15, 23, 42, .06);
216
+ }}
217
+ .result-card > header {{ display: flex; justify-content: space-between; gap: 16px; align-items: flex-start; margin-bottom: 16px; }}
218
+ .image-stack {{ display: grid; gap: 16px; }}
219
+ .image-panel {{ border: 1px solid var(--line); border-radius: 8px; overflow: hidden; background: #f8fafc; }}
220
+ .image-panel span {{ display: block; padding: 8px 10px; color: var(--muted); font-size: 12px; font-weight: 800; text-transform: uppercase; }}
221
+ .image-panel img {{ display: block; width: 100%; height: auto; }}
222
+ .image-panel.missing {{ padding-bottom: 16px; }}
223
+ .image-panel.missing p {{ margin: 0; padding: 0 10px; color: var(--muted); }}
224
+ .gemini {{ margin-top: 8px; }}
225
+ .gemini p {{ color: var(--ink); margin: 12px 0 0; }}
226
+ .gemini ul {{ margin: 12px 0 0; padding-left: 20px; color: var(--failed); }}
227
+ .muted {{ color: var(--muted); }}
228
+ .error {{
229
+ border: 1px solid #f0a4b3;
230
+ border-radius: 8px;
231
+ background: #fff1f3;
232
+ color: var(--failed);
233
+ padding: 10px 12px;
234
+ white-space: pre-wrap;
235
+ }}
236
+ @media (max-width: 720px) {{
237
+ main {{ width: min(100% - 20px, 1120px); padding-top: 20px; }}
238
+ .topbar, .result-card > header {{ display: block; }}
239
+ .badge {{ display: inline-block; margin-top: 8px; }}
240
+ }}
241
+ </style>
242
+ </head>
243
+ <body>
244
+ <main>
245
+ <header class="topbar">
246
+ <div>
247
+ <p class="eyebrow">Real Browser QA Report</p>
248
+ <h1>{qa_html(run.get("id") or "QA run")}</h1>
249
+ <p class="muted">Generated from backend QA run data. Screenshots are served as report assets, not embedded base64.</p>
250
+ </div>
251
+ <span class="badge status-{status}">{qa_html(status)}</span>
252
+ </header>
253
+ <section class="summary">
254
+ {qa_metric_html("done", f"{qa_int(run.get('completed'))}/{qa_int(run.get('total'))}")}
255
+ {qa_metric_html("passed", str(qa_int(run.get("passed"))))}
256
+ {qa_metric_html("failed", str(qa_int(run.get("failed"))))}
257
+ {qa_metric_html("updated", str(run.get("updatedAt") or "unknown"))}
258
+ </section>
259
+ {error_html}
260
+ {result_cards}
261
+ </main>
262
+ </body>
263
+ </html>
264
+ """
qa/results.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """QA result parsing: extract structured results from Playwright JSON reports."""
2
+
3
+ import base64
4
+ import json
5
+ import shutil
6
+ import urllib.parse
7
+ from pathlib import Path
8
+
9
+ from config.qa import QA_FRONTEND_DIR
10
+ from enums import QaResult
11
+ from qa.store import qa_int, qa_run_root
12
+
13
+
14
+ def qa_status_from_playwright(result_status: str | None, test_status: str | None) -> str:
15
+ status = result_status or ""
16
+ if status == "passed":
17
+ return QaResult.PASSED
18
+ if status == "skipped":
19
+ return QaResult.SKIPPED
20
+ if status:
21
+ return QaResult.FAILED
22
+ if test_status == "expected":
23
+ return QaResult.PASSED
24
+ if test_status == "skipped":
25
+ return QaResult.SKIPPED
26
+ return QaResult.FAILED
27
+
28
+
29
+ def qa_find_attachment(result: dict, name: str):
30
+ for attachment in result.get("attachments", []) or []:
31
+ if attachment.get("name") == name:
32
+ return attachment
33
+ return None
34
+
35
+
36
+ def qa_attachment_path(attachment: dict | None, report_path: Path):
37
+ if not attachment or not attachment.get("path"):
38
+ return None
39
+ raw_path = Path(str(attachment["path"]))
40
+ candidates = [
41
+ raw_path if raw_path.is_absolute() else (QA_FRONTEND_DIR / raw_path),
42
+ raw_path if raw_path.is_absolute() else (report_path.parent / raw_path),
43
+ ]
44
+ for candidate in candidates:
45
+ if candidate.exists():
46
+ return candidate.resolve()
47
+ return None
48
+
49
+
50
+ def qa_asset_url(run_id: str, source_path: Path | None):
51
+ if source_path is None:
52
+ return None
53
+ root = qa_run_root(run_id).resolve()
54
+ try:
55
+ relative = source_path.resolve().relative_to(root)
56
+ except ValueError:
57
+ assets_dir = root / "assets"
58
+ assets_dir.mkdir(parents=True, exist_ok=True)
59
+ destination = assets_dir / source_path.name
60
+ if not destination.exists():
61
+ shutil.copy2(source_path, destination)
62
+ relative = destination.relative_to(root)
63
+ return f"/qa/runs/{run_id}/assets/{urllib.parse.quote(relative.as_posix())}"
64
+
65
+
66
+ def qa_read_attachment_text(attachment: dict | None, report_path: Path):
67
+ if not attachment:
68
+ return ""
69
+ source_path = qa_attachment_path(attachment, report_path)
70
+ if source_path is not None:
71
+ return source_path.read_text()
72
+ body = attachment.get("body")
73
+ if not isinstance(body, str):
74
+ return ""
75
+ stripped = body.strip()
76
+ if stripped.startswith("{") or stripped.startswith("["):
77
+ return body
78
+ try:
79
+ return base64.b64decode(body).decode("utf-8")
80
+ except Exception:
81
+ return ""
82
+
83
+
84
+ def qa_parse_json_text(text: str):
85
+ if not text.strip():
86
+ return None
87
+ try:
88
+ return json.loads(text)
89
+ except Exception:
90
+ start = text.find("{")
91
+ end = text.rfind("}")
92
+ if start >= 0 and end > start:
93
+ try:
94
+ return json.loads(text[start:end + 1])
95
+ except Exception:
96
+ return None
97
+ return None
98
+
99
+
100
+ def qa_title_parts(title: str):
101
+ if ": apply " not in title:
102
+ return title, "Unknown tile"
103
+ image_name, rest = title.split(": apply ", 1)
104
+ tile_name = rest.rsplit(" to ", 1)[0] if " to " in rest else rest
105
+ return image_name, tile_name
106
+
107
+
108
+ def qa_grouped_case_metas(result: dict, report_path: Path):
109
+ metas = []
110
+ for attachment in result.get("attachments", []) or []:
111
+ name = str(attachment.get("name") or "")
112
+ if not name.startswith("qa-case-") or not name.endswith("-meta"):
113
+ continue
114
+ meta = qa_parse_json_text(qa_read_attachment_text(attachment, report_path))
115
+ if not isinstance(meta, dict):
116
+ continue
117
+ prefix = str(meta.get("attachmentPrefix") or name.removesuffix("-meta"))
118
+ metas.append((prefix, meta))
119
+
120
+ def sort_key(item):
121
+ _, meta = item
122
+ return qa_int(meta.get("caseIndex"), 0)
123
+
124
+ return sorted(metas, key=sort_key)
125
+
126
+
127
+ def qa_case_status(meta: dict, fallback_status: str) -> str:
128
+ status = str(meta.get("status") or "").lower()
129
+ if status in {QaResult.PASSED, QaResult.FAILED, QaResult.SKIPPED}:
130
+ return status
131
+ return fallback_status
132
+
133
+
134
+ def collect_playwright_specs(suite: dict, entries: list[tuple[str, dict]]):
135
+ for spec in suite.get("specs", []) or []:
136
+ title = spec.get("title") or "Untitled QA case"
137
+ for test in spec.get("tests", []) or []:
138
+ entries.append((title, test))
139
+ for child in suite.get("suites", []) or []:
140
+ collect_playwright_specs(child, entries)
141
+
142
+
143
+ def parse_qa_results(run_id: str, report_path: Path):
144
+ if not report_path.exists():
145
+ return []
146
+ report = json.loads(report_path.read_text())
147
+ entries: list[tuple[str, dict]] = []
148
+ for suite in report.get("suites", []) or []:
149
+ collect_playwright_specs(suite, entries)
150
+
151
+ results = []
152
+ for index, (title, test) in enumerate(entries):
153
+ playwright_results = test.get("results", []) or [{}]
154
+ final_result = playwright_results[-1]
155
+ fallback_status = qa_status_from_playwright(final_result.get("status"), test.get("status"))
156
+ grouped_cases = qa_grouped_case_metas(final_result, report_path)
157
+ if grouped_cases:
158
+ has_case_failure = any(qa_case_status(meta, fallback_status) == "failed" for _, meta in grouped_cases)
159
+ global_error = final_result.get("error", {}).get("message") if isinstance(final_result.get("error"), dict) else None
160
+ for case_index, (prefix, meta) in enumerate(grouped_cases, start=1):
161
+ before_attachment = qa_find_attachment(final_result, f"{prefix}-before-canvas")
162
+ after_attachment = qa_find_attachment(final_result, f"{prefix}-after-texture-canvas")
163
+ gemini_attachment = qa_find_attachment(final_result, f"{prefix}-gemini-judge")
164
+ status = qa_case_status(meta, fallback_status)
165
+ if fallback_status == "failed" and not has_case_failure:
166
+ status = "failed"
167
+ case_id = qa_int(meta.get("caseIndex"), case_index)
168
+ results.append({
169
+ "id": f"{run_id}-{case_id}",
170
+ "imageKey": meta.get("imageName") or meta.get("roomName") or title,
171
+ "imageName": meta.get("imageName") or meta.get("roomName") or title,
172
+ "tileName": meta.get("tileName") or "Unknown tile",
173
+ "status": status,
174
+ "beforeImageUrl": qa_asset_url(run_id, qa_attachment_path(before_attachment, report_path)),
175
+ "afterImageUrl": qa_asset_url(run_id, qa_attachment_path(after_attachment, report_path)),
176
+ "gemini": qa_parse_json_text(qa_read_attachment_text(gemini_attachment, report_path)),
177
+ "error": meta.get("error") if isinstance(meta.get("error"), str) else global_error,
178
+ })
179
+ continue
180
+
181
+ image_name, tile_name = qa_title_parts(title)
182
+ before_attachment = qa_find_attachment(final_result, "before-canvas")
183
+ after_attachment = qa_find_attachment(final_result, "after-texture-canvas")
184
+ gemini_attachment = qa_find_attachment(final_result, "gemini-judge")
185
+ error = final_result.get("error", {}).get("message") if isinstance(final_result.get("error"), dict) else None
186
+
187
+ results.append({
188
+ "id": f"{run_id}-{index + 1}",
189
+ "imageKey": image_name,
190
+ "imageName": image_name,
191
+ "tileName": tile_name,
192
+ "status": fallback_status,
193
+ "beforeImageUrl": qa_asset_url(run_id, qa_attachment_path(before_attachment, report_path)),
194
+ "afterImageUrl": qa_asset_url(run_id, qa_attachment_path(after_attachment, report_path)),
195
+ "gemini": qa_parse_json_text(qa_read_attachment_text(gemini_attachment, report_path)),
196
+ "error": error,
197
+ })
198
+ return results
qa/runner.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """QA runner: execute Playwright tests, sync progress, finalize results."""
2
+
3
+ import json
4
+ import os
5
+ import subprocess
6
+ import time
7
+ from pathlib import Path
8
+
9
+ from config.gemini import GEMINI_API_KEY
10
+ from config.qa import QA_FRONTEND_DIR, QA_FRONTEND_URL, QA_RUN_TIMEOUT_SECONDS
11
+ from enums import QaStatus, QaResult
12
+ from qa.results import parse_qa_results
13
+ from qa.scenarios import build_qa_scenarios, download_qa_images
14
+ from qa.store import qa_int, qa_iso_now, qa_run_root, read_qa_run, write_qa_run
15
+
16
+
17
+ def qa_runner_env(run_root: Path, scenarios: list[dict], use_gemini: bool, backend_url: str):
18
+ env = os.environ.copy()
19
+ env.update({
20
+ "API_URL": backend_url,
21
+ "PLAYWRIGHT_BASE_URL": QA_FRONTEND_URL,
22
+ "QA_HTML_REPORT_DIR": str(run_root / "html-report"),
23
+ "QA_PLAYWRIGHT_OUTPUT_DIR": str(run_root / "artifacts"),
24
+ "QA_PROGRESS_FILE": str(run_root / "progress.json"),
25
+ "QA_PROGRESS_MODE": "cases",
26
+ "QA_RESULTS_DIR": str(run_root / "results"),
27
+ "QA_SCENARIOS": json.dumps(scenarios),
28
+ "QA_SKIP_GEMINI": "0" if use_gemini else "1",
29
+ "QA_TEST_IMAGES_DIR": str(run_root / "images"),
30
+ "QA_WORKERS": "1",
31
+ "VITE_API_URL": backend_url,
32
+ })
33
+ if use_gemini:
34
+ if not GEMINI_API_KEY:
35
+ raise RuntimeError("Gemini is enabled for this QA run, but GEMINI_API_KEY is not configured.")
36
+ env["GEMINI_API_KEY"] = GEMINI_API_KEY
37
+ env.setdefault("GEMINI_MODEL", "gemini-3.1-flash-lite")
38
+ return env
39
+
40
+
41
+ def finalize_qa_run_from_report(run: dict, report_path: Path):
42
+ results = parse_qa_results(run["id"], report_path)
43
+ passed = sum(1 for result in results if result["status"] == QaResult.PASSED)
44
+ failed = sum(1 for result in results if result["status"] == QaResult.FAILED)
45
+ completed = sum(1 for result in results if result["status"] in {QaResult.PASSED, QaResult.FAILED, QaResult.SKIPPED})
46
+ run.update({
47
+ "completed": completed,
48
+ "failed": failed,
49
+ "passed": passed,
50
+ "results": results,
51
+ "status": QaStatus.COMPLETED if report_path.exists() else QaStatus.FAILED,
52
+ })
53
+ if failed:
54
+ run["status"] = QaStatus.FAILED
55
+
56
+
57
+ def sync_qa_run_progress(run_id: str, progress_path: Path):
58
+ if not progress_path.exists():
59
+ return
60
+
61
+ try:
62
+ progress = json.loads(progress_path.read_text())
63
+ except Exception:
64
+ return
65
+
66
+ run = read_qa_run(run_id)
67
+ updates = {
68
+ "completed": qa_int(progress.get("completed"), qa_int(run.get("completed"))),
69
+ "failed": qa_int(progress.get("failed"), qa_int(run.get("failed"))),
70
+ "passed": qa_int(progress.get("passed"), qa_int(run.get("passed"))),
71
+ "progressUpdatedAt": progress.get("updatedAt"),
72
+ "skipped": qa_int(progress.get("skipped"), qa_int(run.get("skipped"))),
73
+ "total": qa_int(progress.get("total"), qa_int(run.get("total"))),
74
+ }
75
+ if run.get("status") == QaStatus.QUEUED:
76
+ updates["status"] = QaStatus.RUNNING
77
+ if all(run.get(key) == value for key, value in updates.items()):
78
+ return
79
+
80
+ run.update(updates)
81
+ write_qa_run(run)
82
+
83
+
84
+ def run_playwright_qa(run_id: str, run_root: Path, env: dict, log_file):
85
+ command = ["npm", "run", "qa:e2e"]
86
+ progress_path = run_root / "progress.json"
87
+ process = subprocess.Popen(
88
+ command,
89
+ cwd=QA_FRONTEND_DIR,
90
+ env=env,
91
+ stderr=subprocess.STDOUT,
92
+ stdout=log_file,
93
+ )
94
+ deadline = time.monotonic() + QA_RUN_TIMEOUT_SECONDS
95
+
96
+ while True:
97
+ return_code = process.poll()
98
+ sync_qa_run_progress(run_id, progress_path)
99
+ if return_code is not None:
100
+ return return_code
101
+
102
+ if time.monotonic() >= deadline:
103
+ process.terminate()
104
+ try:
105
+ process.wait(timeout=10)
106
+ except subprocess.TimeoutExpired:
107
+ process.kill()
108
+ process.wait(timeout=10)
109
+ sync_qa_run_progress(run_id, progress_path)
110
+ raise subprocess.TimeoutExpired(command, QA_RUN_TIMEOUT_SECONDS)
111
+
112
+ time.sleep(1)
113
+
114
+
115
+ def run_qa_task(run_id: str, image_keys: list[str], tiles: list[str], descriptions: dict[str, str], use_gemini: bool, backend_url: str):
116
+ run = read_qa_run(run_id)
117
+ run_root = qa_run_root(run_id)
118
+ log_path = run_root / "runner.log"
119
+ report_path = run_root / "results" / "real-qa.json"
120
+ summary_path = run_root / "qa-summary.md"
121
+ try:
122
+ if not QA_FRONTEND_URL:
123
+ raise RuntimeError("QA_FRONTEND_URL must point to the hosted frontend.")
124
+ if not QA_FRONTEND_DIR.exists():
125
+ raise RuntimeError(f"QA_FRONTEND_DIR does not exist: {QA_FRONTEND_DIR}")
126
+ if not (QA_FRONTEND_DIR / "package.json").exists():
127
+ raise RuntimeError(f"QA_FRONTEND_DIR must point to frontend/viz2d-demo: {QA_FRONTEND_DIR}")
128
+
129
+ run.update({"status": QaStatus.RUNNING, "startedAt": qa_iso_now()})
130
+ write_qa_run(run)
131
+
132
+ downloaded_images = download_qa_images(run_id, image_keys)
133
+ scenarios = build_qa_scenarios(downloaded_images, tiles, descriptions)
134
+ (run_root / "scenarios.json").write_text(json.dumps(scenarios, indent=2))
135
+ env = qa_runner_env(run_root, scenarios, use_gemini, backend_url)
136
+
137
+ with log_path.open("w") as log_file:
138
+ exit_code = run_playwright_qa(run_id, run_root, env, log_file)
139
+ log_file.write(f"\nqa:e2e exit code: {exit_code}\n")
140
+
141
+ subprocess.run(
142
+ ["npm", "run", "qa:report", "--", str(report_path), str(summary_path)],
143
+ cwd=QA_FRONTEND_DIR,
144
+ env=env,
145
+ stderr=subprocess.STDOUT,
146
+ stdout=log_file,
147
+ timeout=300,
148
+ )
149
+
150
+ run = read_qa_run(run_id)
151
+ finalize_qa_run_from_report(run, report_path)
152
+ if not report_path.exists():
153
+ run["error"] = "Playwright did not create a JSON report. Check runner.log."
154
+ run["reportUrl"] = f"/qa/runs/{run_id}/report"
155
+ write_qa_run(run)
156
+ except subprocess.TimeoutExpired:
157
+ run = read_qa_run(run_id)
158
+ run.update({"status": QaStatus.FAILED, "error": "QA run timed out.", "reportUrl": f"/qa/runs/{run_id}/report"})
159
+ write_qa_run(run)
160
+ except Exception as exc:
161
+ run = read_qa_run(run_id)
162
+ run.update({"status": QaStatus.FAILED, "error": str(exc), "reportUrl": f"/qa/runs/{run_id}/report"})
163
+ write_qa_run(run)
qa/scenarios.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """QA scenario building: tile normalization, image download, scenario generation."""
2
+
3
+ from pathlib import Path
4
+
5
+ from config.spaces import SPACES_BUCKET
6
+ from qa.constants import QA_IMAGE_EXTENSIONS, QA_TILE_ALIASES, QA_TILE_DESCRIPTIONS
7
+ from services.spaces.upload import spaces_client
8
+
9
+
10
+ def qa_safe_filename(value: str, fallback: str = "image") -> str:
11
+ stem = "".join(char.lower() if char.isalnum() else "-" for char in value).strip("-")
12
+ while "--" in stem:
13
+ stem = stem.replace("--", "-")
14
+ return (stem or fallback)[:90]
15
+
16
+
17
+ def normalize_qa_tile(tile_name: str) -> str:
18
+ name = str(tile_name).strip()
19
+ return QA_TILE_ALIASES.get(name, name)
20
+
21
+
22
+ def qa_tile_description(tile_name: str, supplied_descriptions: dict[str, str]) -> str:
23
+ return supplied_descriptions.get(tile_name) or QA_TILE_DESCRIPTIONS.get(tile_name) or f"{tile_name} flooring material"
24
+
25
+
26
+ def parse_tile_descriptions(values) -> dict[str, str]:
27
+ descriptions: dict[str, str] = {}
28
+ if not isinstance(values, list):
29
+ return descriptions
30
+ for value in values:
31
+ if not isinstance(value, str) or ":" not in value:
32
+ continue
33
+ name, description = value.split(":", 1)
34
+ normalized = normalize_qa_tile(name)
35
+ if normalized and description.strip():
36
+ descriptions[normalized] = description.strip()
37
+ return descriptions
38
+
39
+
40
+ def build_qa_scenarios(downloaded_images: list[dict], tiles: list[str], descriptions: dict[str, str]):
41
+ scenarios = []
42
+ for image in downloaded_images:
43
+ image_name = Path(image["key"]).stem
44
+ for tile in tiles:
45
+ scenarios.append({
46
+ "imagePath": str(image["path"]),
47
+ "keyword": "floor",
48
+ "roomName": f"{image_name}",
49
+ "surfaceClass": "floor",
50
+ "textureName": tile,
51
+ "textureDescription": qa_tile_description(tile, descriptions),
52
+ "expectedDirectionDescription": (
53
+ "The applied material direction should follow the floor perspective and should not look arbitrarily rotated."
54
+ ),
55
+ })
56
+ return scenarios
57
+
58
+
59
+ def download_qa_images(run_id: str, image_keys: list[str]):
60
+ from qa.store import qa_run_root
61
+
62
+ client = spaces_client()
63
+ images_dir = qa_run_root(run_id) / "images"
64
+ images_dir.mkdir(parents=True, exist_ok=True)
65
+ downloaded = []
66
+ for index, key in enumerate(image_keys, start=1):
67
+ extension = Path(key).suffix.lower()
68
+ if extension not in QA_IMAGE_EXTENSIONS:
69
+ extension = ".jpg"
70
+ destination = images_dir / f"{index:03d}-{qa_safe_filename(Path(key).stem)}{extension}"
71
+ client.download_file(SPACES_BUCKET, key, str(destination))
72
+ downloaded.append({"key": key, "path": destination})
73
+ return downloaded
qa/store.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """QA run persistence helpers: read/write run JSON, SSE formatting, utilities."""
2
+
3
+ import json
4
+ from datetime import datetime, timezone
5
+ from pathlib import Path
6
+
7
+ from config.paths import QA_RUN_DIR
8
+ from errors import bad_request, not_found
9
+
10
+
11
+ def qa_utc_now() -> datetime:
12
+ return datetime.now(timezone.utc)
13
+
14
+
15
+ def qa_iso_now() -> str:
16
+ return qa_utc_now().isoformat().replace("+00:00", "Z")
17
+
18
+
19
+ def qa_run_root(run_id: str) -> Path:
20
+ if Path(run_id).name != run_id or not run_id:
21
+ bad_request("Invalid QA run id.")
22
+ return QA_RUN_DIR / run_id
23
+
24
+
25
+ def qa_run_file(run_id: str) -> Path:
26
+ return qa_run_root(run_id) / "run.json"
27
+
28
+
29
+ def read_qa_run(run_id: str) -> dict:
30
+ path = qa_run_file(run_id)
31
+ if not path.exists():
32
+ not_found("QA run not found.")
33
+ return json.loads(path.read_text())
34
+
35
+
36
+ def write_qa_run(run: dict):
37
+ run["updatedAt"] = qa_iso_now()
38
+ root = qa_run_root(run["id"])
39
+ root.mkdir(parents=True, exist_ok=True)
40
+ qa_run_file(run["id"]).write_text(json.dumps(run, indent=2))
41
+
42
+
43
+ def qa_sse_event(event_name: str, payload: dict) -> str:
44
+ data = json.dumps(payload, separators=(",", ":"))
45
+ return f"event: {event_name}\ndata: {data}\n\n"
46
+
47
+
48
+ def qa_int(value, default: int = 0) -> int:
49
+ try:
50
+ return int(value)
51
+ except (TypeError, ValueError):
52
+ return default
routes/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Route modules for the floor-visualizer API.
routes/floor_direction.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Floor direction analysis route."""
2
+
3
+ import cv2
4
+ from fastapi import APIRouter, File, Form, UploadFile
5
+
6
+ from errors import bad_request
7
+ from floor_direction import (
8
+ analyze_floor_direction as analyze_floor_direction_from_segmentation,
9
+ parse_floor_segmentation,
10
+ )
11
+ from services.direction.response import floor_direction_response
12
+ from services.image.loading import load_uploaded_rgb_image
13
+ from routes.segmentation import build_oneformer_polygon_response
14
+
15
+ router = APIRouter(tags=["floor-direction"])
16
+
17
+
18
+ @router.post("/analyze-floor-direction")
19
+ async def analyze_floor_direction_endpoint(
20
+ file: UploadFile = File(...),
21
+ include_overlay: bool = Form(False),
22
+ threshold: float = Form(0.5),
23
+ mask_threshold: float = Form(0.5),
24
+ min_area: float = Form(32.0),
25
+ simplify_epsilon: float = Form(2.0),
26
+ ):
27
+ contents = await file.read()
28
+ if not contents:
29
+ bad_request("Upload a non-empty image file in the 'file' field.")
30
+
31
+ _img, img_np = load_uploaded_rgb_image(contents)
32
+ image_bgr = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)
33
+ segmentation_payload = build_oneformer_polygon_response(
34
+ contents,
35
+ threshold=threshold,
36
+ mask_threshold=mask_threshold,
37
+ min_area=min_area,
38
+ simplify_epsilon=simplify_epsilon,
39
+ )
40
+ floor_segmentation = parse_floor_segmentation(segmentation_payload)
41
+ result = analyze_floor_direction_from_segmentation(
42
+ image_bgr,
43
+ floor_segmentation,
44
+ include_overlay=include_overlay,
45
+ )
46
+ return floor_direction_response(result, floor_segmentation)
routes/gemini.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gemini tile-render refinement route."""
2
+
3
+ import asyncio
4
+
5
+ from fastapi import APIRouter
6
+
7
+ from config.gemini import GEMINI_IMAGE_MODEL
8
+ from errors import bad_request
9
+ from services.gemini.client import call_gemini_image_refinement, decode_inline_image_payload
10
+ from services.gemini.prompt import build_gemini_tile_refinement_prompt
11
+
12
+ router = APIRouter(prefix="/gemini", tags=["gemini"])
13
+
14
+
15
+ @router.post("/refine-tile-render")
16
+ async def refine_tile_render_with_gemini(payload: dict):
17
+ image_value = payload.get("image") if isinstance(payload, dict) else None
18
+ if not isinstance(image_value, str):
19
+ bad_request("Image is required.")
20
+
21
+ tile_name = payload.get("tileName") if isinstance(payload, dict) else None
22
+ if not isinstance(tile_name, str):
23
+ tile_name = None
24
+
25
+ image_bytes, mime_type = decode_inline_image_payload(image_value)
26
+ prompt = build_gemini_tile_refinement_prompt(tile_name)
27
+ output_b64, output_mime = await asyncio.to_thread(
28
+ call_gemini_image_refinement,
29
+ image_bytes,
30
+ mime_type,
31
+ prompt,
32
+ )
33
+ return {
34
+ "image": f"data:{output_mime};base64,{output_b64}",
35
+ "model": GEMINI_IMAGE_MODEL,
36
+ }
routes/materials.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Material map preparation route."""
2
+
3
+ from fastapi import APIRouter, File, Form, UploadFile
4
+
5
+ from errors import bad_request
6
+ from services.materials.cache import build_tile_material_package
7
+
8
+ router = APIRouter(prefix="/materials", tags=["materials"])
9
+
10
+
11
+ @router.post("/prepare")
12
+ async def prepare_material_maps(
13
+ file: UploadFile = File(...),
14
+ base_roughness: float = Form(0.42),
15
+ ):
16
+ if file.content_type and not file.content_type.startswith("image/"):
17
+ bad_request("Upload must be a tile image.")
18
+ contents = await file.read()
19
+ if not contents:
20
+ bad_request("Upload must not be empty.")
21
+ return build_tile_material_package(contents, base_roughness)
routes/qa.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """QA run management and reporting routes."""
2
+
3
+ import asyncio
4
+ import json
5
+ import mimetypes
6
+ import time
7
+ import uuid
8
+
9
+ from fastapi import APIRouter, BackgroundTasks, Body, Query, Request, Response
10
+ from fastapi.responses import StreamingResponse
11
+
12
+ from config.qa import QA_BACKEND_URL, QA_MAX_IMAGES, QA_MAX_TESTS
13
+ from enums import QaStatus
14
+ from errors import bad_request, not_found
15
+ from qa.constants import QA_TILE_DESCRIPTIONS
16
+ from qa.images import dedupe_qa_image_keys, list_qa_spaces_images
17
+ from qa.report import build_qa_report_html
18
+ from qa.runner import run_qa_task
19
+ from qa.scenarios import normalize_qa_tile, parse_tile_descriptions
20
+ from qa.store import qa_iso_now, qa_run_root, qa_sse_event, read_qa_run, write_qa_run
21
+
22
+ router = APIRouter(prefix="/qa", tags=["qa"])
23
+
24
+
25
+ @router.get("/images")
26
+ async def qa_images(
27
+ range: str = Query("week"),
28
+ from_value: str | None = Query(None, alias="from"),
29
+ to: str | None = Query(None),
30
+ max_items: int = Query(100, ge=1, le=500),
31
+ ):
32
+ return {"images": list_qa_spaces_images(range, from_value, to, min(max_items, QA_MAX_IMAGES))}
33
+
34
+
35
+ @router.post("/runs")
36
+ async def create_qa_run(
37
+ request: Request,
38
+ background_tasks: BackgroundTasks,
39
+ payload: dict = Body(...),
40
+ ):
41
+ raw_image_keys = payload.get("imageKeys")
42
+ if not isinstance(raw_image_keys, list):
43
+ bad_request("imageKeys must be a non-empty array.")
44
+ image_keys = [str(key).strip() for key in raw_image_keys if isinstance(key, str) and str(key).strip()]
45
+ if not image_keys:
46
+ bad_request("Select at least one image.")
47
+ image_keys = dedupe_qa_image_keys(image_keys)
48
+ if not image_keys:
49
+ bad_request("All selected images were duplicates.")
50
+ if len(image_keys) > QA_MAX_IMAGES:
51
+ bad_request(f"Select at most {QA_MAX_IMAGES} images.")
52
+
53
+ raw_tiles = payload.get("tiles")
54
+ if raw_tiles is None:
55
+ raw_tiles = list(QA_TILE_DESCRIPTIONS)
56
+ if not isinstance(raw_tiles, list):
57
+ bad_request("tiles must be an array.")
58
+ tiles = []
59
+ for tile in raw_tiles:
60
+ if not isinstance(tile, str) or not tile.strip():
61
+ continue
62
+ normalized = normalize_qa_tile(tile)
63
+ if normalized not in tiles:
64
+ tiles.append(normalized)
65
+ if not tiles:
66
+ bad_request("Select at least one tile.")
67
+
68
+ total = len(image_keys) * len(tiles)
69
+ if total > QA_MAX_TESTS:
70
+ bad_request(f"QA matrix is too large. Max tests: {QA_MAX_TESTS}.")
71
+
72
+ run_id = f"qa_{uuid.uuid4().hex}"
73
+ use_gemini = bool(payload.get("useGemini", True))
74
+ descriptions = parse_tile_descriptions(payload.get("tileDescriptions"))
75
+ backend_url = QA_BACKEND_URL or str(request.base_url).rstrip("/")
76
+ run = {
77
+ "id": run_id,
78
+ "status": QaStatus.QUEUED,
79
+ "createdAt": qa_iso_now(),
80
+ "updatedAt": qa_iso_now(),
81
+ "total": total,
82
+ "completed": 0,
83
+ "passed": 0,
84
+ "failed": 0,
85
+ "imageKeys": image_keys,
86
+ "tiles": tiles,
87
+ "useGemini": use_gemini,
88
+ "reportUrl": f"/qa/runs/{run_id}/report",
89
+ "results": [],
90
+ }
91
+ write_qa_run(run)
92
+ background_tasks.add_task(run_qa_task, run_id, image_keys, tiles, descriptions, use_gemini, backend_url)
93
+ return run
94
+
95
+
96
+ @router.get("/runs/{run_id}")
97
+ async def qa_run_status(run_id: str):
98
+ return read_qa_run(run_id)
99
+
100
+
101
+ @router.get("/runs/{run_id}/events")
102
+ async def qa_run_events(run_id: str, request: Request):
103
+ read_qa_run(run_id)
104
+
105
+ async def event_stream():
106
+ last_payload = ""
107
+ last_keepalive = time.monotonic()
108
+ while True:
109
+ if await request.is_disconnected():
110
+ break
111
+
112
+ run = read_qa_run(run_id)
113
+ payload = json.dumps(run, sort_keys=True)
114
+ if payload != last_payload:
115
+ last_payload = payload
116
+ yield qa_sse_event("run", run)
117
+ if run.get("status") not in {QaStatus.QUEUED, QaStatus.RUNNING}:
118
+ break
119
+ elif time.monotonic() - last_keepalive >= 15:
120
+ last_keepalive = time.monotonic()
121
+ yield ": keepalive\n\n"
122
+
123
+ await asyncio.sleep(1)
124
+
125
+ return StreamingResponse(
126
+ event_stream(),
127
+ media_type="text/event-stream",
128
+ headers={
129
+ "Cache-Control": "no-cache, no-transform",
130
+ "Connection": "keep-alive",
131
+ "X-Accel-Buffering": "no",
132
+ },
133
+ )
134
+
135
+
136
+ @router.get("/runs/{run_id}/report")
137
+ async def qa_run_report(run_id: str):
138
+ run = read_qa_run(run_id)
139
+ return Response(content=build_qa_report_html(run), media_type="text/html", headers={"Cache-Control": "no-store"})
140
+
141
+
142
+ @router.get("/runs/{run_id}/report.md")
143
+ async def qa_run_markdown_report(run_id: str):
144
+ root = qa_run_root(run_id)
145
+ report_path = root / "qa-summary.md"
146
+ if not report_path.exists():
147
+ run = read_qa_run(run_id)
148
+ content = "\n".join([
149
+ "# Real Browser QA Summary",
150
+ "",
151
+ f"Status: {run.get('status', 'unknown')}",
152
+ "",
153
+ run.get("error") or "The QA summary has not been generated yet.",
154
+ "",
155
+ ])
156
+ return Response(content=content, media_type="text/markdown", headers={"Cache-Control": "no-store"})
157
+ return Response(content=report_path.read_text(), media_type="text/markdown", headers={"Cache-Control": "no-store"})
158
+
159
+
160
+ @router.get("/runs/{run_id}/assets/{asset_path:path}")
161
+ async def qa_run_asset(run_id: str, asset_path: str):
162
+ root = qa_run_root(run_id).resolve()
163
+ target = (root / asset_path).resolve()
164
+ if root != target and root not in target.parents:
165
+ bad_request("Invalid QA asset path.")
166
+ if not target.exists() or not target.is_file():
167
+ not_found("QA asset not found.")
168
+ media_type = mimetypes.guess_type(target.name)[0] or "application/octet-stream"
169
+ return Response(content=target.read_bytes(), media_type=media_type, headers={"Cache-Control": "private, max-age=3600"})
routes/segmentation.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Segmentation routes: panoptic polygon extraction and bundle generation."""
2
+
3
+ import numpy as np
4
+ import torch
5
+ from fastapi import APIRouter, File, Form, UploadFile
6
+
7
+ from config.models import ONEFORMER_MODEL_NAME
8
+ from models.loader import _load_segmentation_model
9
+ from services.image.loading import load_uploaded_rgb_image
10
+ from services.image.polygons import mask_to_polygons
11
+ from services.pipeline.builder import build_segmentation_bundle
12
+ from state import class_name_for_id
13
+
14
+ router = APIRouter(tags=["segmentation"])
15
+
16
+
17
+ def build_oneformer_polygon_response(
18
+ contents: bytes,
19
+ *,
20
+ threshold: float = 0.5,
21
+ mask_threshold: float = 0.5,
22
+ min_area: float = 32.0,
23
+ simplify_epsilon: float = 2.0,
24
+ ) -> dict:
25
+ img, img_np = load_uploaded_rgb_image(contents)
26
+ h, w = img_np.shape[:2]
27
+
28
+ threshold = float(np.clip(threshold, 0.0, 1.0))
29
+ mask_threshold = float(np.clip(mask_threshold, 0.0, 1.0))
30
+ min_area = max(0.0, float(min_area))
31
+ simplify_epsilon = max(0.0, float(simplify_epsilon))
32
+
33
+ _load_segmentation_model()
34
+
35
+ import state as _state
36
+ inputs = _state.seg_processor(
37
+ images=img,
38
+ task_inputs=["panoptic"],
39
+ return_tensors="pt",
40
+ ).to(_state.device)
41
+ with torch.no_grad():
42
+ outputs = _state.seg_model(**inputs)
43
+
44
+ result = _state.seg_processor.post_process_panoptic_segmentation(
45
+ outputs,
46
+ threshold=threshold,
47
+ mask_threshold=mask_threshold,
48
+ target_sizes=[(h, w)],
49
+ )[0]
50
+ segmentation = result.get("segmentation")
51
+ if segmentation is None:
52
+ return {
53
+ "model": ONEFORMER_MODEL_NAME,
54
+ "task": "panoptic",
55
+ "width": int(w),
56
+ "height": int(h),
57
+ "segments": [],
58
+ }
59
+
60
+ if isinstance(segmentation, torch.Tensor):
61
+ segment_map = segmentation.cpu().numpy()
62
+ else:
63
+ segment_map = np.asarray(segmentation)
64
+
65
+ segments = []
66
+ for segment_info in result.get("segments_info", []):
67
+ segment_id = int(segment_info["id"])
68
+ label_id = int(segment_info["label_id"])
69
+ mask = segment_map == segment_id
70
+ polygons = mask_to_polygons(mask, min_area, simplify_epsilon)
71
+ if not polygons:
72
+ continue
73
+
74
+ score = segment_info.get("score")
75
+ segments.append({
76
+ "id": segment_id,
77
+ "labelId": label_id,
78
+ "label": class_name_for_id(label_id),
79
+ "confidence": float(score) if score is not None else None,
80
+ "wasFused": bool(segment_info.get("was_fused", False)),
81
+ "pixelArea": int(mask.sum()),
82
+ "polygons": polygons,
83
+ })
84
+
85
+ segments.sort(key=lambda item: item["pixelArea"], reverse=True)
86
+ return {
87
+ "model": ONEFORMER_MODEL_NAME,
88
+ "task": "panoptic",
89
+ "width": int(w),
90
+ "height": int(h),
91
+ "threshold": threshold,
92
+ "maskThreshold": mask_threshold,
93
+ "minArea": min_area,
94
+ "simplifyEpsilon": simplify_epsilon,
95
+ "segmentCount": len(segments),
96
+ "segments": segments,
97
+ }
98
+
99
+
100
+ @router.post("/oneformer/polygons")
101
+ async def oneformer_polygons(
102
+ file: UploadFile = File(...),
103
+ threshold: float = Form(0.5),
104
+ mask_threshold: float = Form(0.5),
105
+ min_area: float = Form(32.0),
106
+ simplify_epsilon: float = Form(2.0),
107
+ ):
108
+ contents = await file.read()
109
+ return build_oneformer_polygon_response(
110
+ contents,
111
+ threshold=threshold,
112
+ mask_threshold=mask_threshold,
113
+ min_area=min_area,
114
+ simplify_epsilon=simplify_epsilon,
115
+ )
116
+
117
+
118
+ @router.post("/segment")
119
+ async def segment(file: UploadFile = File(...)):
120
+ contents = await file.read()
121
+ return build_segmentation_bundle(contents)
routes/viz2d.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Viz2D conversion and job management routes."""
2
+
3
+ import uuid
4
+ from datetime import datetime, timezone
5
+ from pathlib import Path
6
+
7
+ from fastapi import APIRouter, BackgroundTasks, File, Response, UploadFile
8
+
9
+ from config.paths import JOB_DIR, UPLOAD_DIR
10
+ from config.runtime import CONVERSION_TARGET_MS, DEBUG_ARTIFACTS_ENABLED
11
+ from errors import bad_request, conflict, not_found
12
+ from services.image.loading import normalize_room_upload
13
+ from services.jobs.conversion import run_conversion_task
14
+ from services.jobs.store import read_job, write_job
15
+ from services.jobs.timing import estimate_conversion_ms
16
+ from services.spaces.upload import upload_input_image_to_spaces
17
+ from enums import JobStatus
18
+
19
+ router = APIRouter(prefix="/viz2d", tags=["viz2d"])
20
+
21
+
22
+ @router.post("/convert")
23
+ async def convert_to_viz2d(background_tasks: BackgroundTasks, file: UploadFile = File(...)):
24
+ if file.content_type and not file.content_type.startswith("image/"):
25
+ bad_request("Upload must be a JPG or PNG image.")
26
+
27
+ contents = await file.read()
28
+ if not contents:
29
+ bad_request("Upload must not be empty.")
30
+ normalized_contents = normalize_room_upload(contents)
31
+
32
+ job_id = uuid.uuid4().hex
33
+ original_filename = file.filename
34
+ content_type = "image/jpeg"
35
+ ext = ".jpg"
36
+ upload_path = UPLOAD_DIR / f"{job_id}{ext}"
37
+ upload_path.write_bytes(normalized_contents)
38
+
39
+ job = {
40
+ "id": job_id,
41
+ "status": JobStatus.QUEUED,
42
+ "phase": "queued",
43
+ "progress": 0,
44
+ "phaseProgress": 0,
45
+ "message": "Waiting for an analysis slot\u2026",
46
+ "createdAt": datetime.now(timezone.utc).isoformat(),
47
+ "estimatedTotalMs": estimate_conversion_ms(),
48
+ "estimatedRemainingMs": estimate_conversion_ms(),
49
+ "targetMs": CONVERSION_TARGET_MS,
50
+ "inputUrl": f"/uploads/{upload_path.name}",
51
+ "outputUrl": f"/viz2d/jobs/{job_id}/file",
52
+ "debugUrl": f"/viz2d/jobs/{job_id}/debug" if DEBUG_ARTIFACTS_ENABLED else None,
53
+ }
54
+ write_job(job)
55
+ background_tasks.add_task(run_conversion_task, job_id, upload_path)
56
+ background_tasks.add_task(upload_input_image_to_spaces, job_id, upload_path, original_filename, content_type)
57
+ return job
58
+
59
+
60
+ @router.get("/jobs/{job_id}")
61
+ async def viz2d_job_status(job_id: str):
62
+ return read_job(job_id)
63
+
64
+
65
+ @router.get("/jobs/{job_id}/debug")
66
+ async def viz2d_job_debug(job_id: str):
67
+ read_job(job_id)
68
+ if not DEBUG_ARTIFACTS_ENABLED:
69
+ not_found("Debug artifacts are disabled on this server.")
70
+ manifest_path = JOB_DIR / f"{job_id}.debug" / "manifest.json"
71
+ if not manifest_path.exists():
72
+ not_found("Debug artifacts are not available yet.")
73
+ return Response(
74
+ content=manifest_path.read_bytes(),
75
+ media_type="application/json",
76
+ headers={"Cache-Control": "no-store"},
77
+ )
78
+
79
+
80
+ @router.get("/jobs/{job_id}/debug/assets/{asset_name}")
81
+ async def viz2d_job_debug_asset(job_id: str, asset_name: str):
82
+ read_job(job_id)
83
+ if Path(asset_name).name != asset_name:
84
+ bad_request("Invalid debug asset name.")
85
+ asset_path = JOB_DIR / f"{job_id}.debug" / asset_name
86
+ if not asset_path.exists() or not asset_path.is_file():
87
+ not_found("Debug asset not found.")
88
+ media_type = "image/jpeg" if asset_path.suffix.lower() in {".jpg", ".jpeg"} else "application/octet-stream"
89
+ return Response(
90
+ content=asset_path.read_bytes(),
91
+ media_type=media_type,
92
+ headers={"Cache-Control": "private, max-age=3600"},
93
+ )
94
+
95
+
96
+ @router.get("/jobs/{job_id}/file")
97
+ async def viz2d_job_file(job_id: str):
98
+ job = read_job(job_id)
99
+ if job.get("status") != JobStatus.COMPLETED:
100
+ conflict("Job is not completed yet.")
101
+ binary_bundle_path = JOB_DIR / f"{job_id}.vizbundle"
102
+ if not binary_bundle_path.exists():
103
+ not_found("Job output not found.")
104
+ return Response(
105
+ content=binary_bundle_path.read_bytes(),
106
+ media_type="application/zip",
107
+ headers={"Content-Disposition": 'attachment; filename="visualizer.vizbundle"'},
108
+ )
109
+
110
+
111
+ @router.get("/jobs/{job_id}/assets/{asset_name}")
112
+ async def viz2d_job_asset(job_id: str, asset_name: str):
113
+ read_job(job_id)
114
+ if Path(asset_name).name != asset_name:
115
+ bad_request("Invalid asset name.")
116
+ asset_path = JOB_DIR / f"{job_id}.assets" / asset_name
117
+ if not asset_path.exists() or not asset_path.is_file():
118
+ not_found("Job asset not found.")
119
+ return Response(
120
+ content=asset_path.read_bytes(),
121
+ media_type="application/octet-stream",
122
+ headers={"Cache-Control": "private, max-age=3600"},
123
+ )
services/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Services package for floor visualizer backend.
services/debug/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Debug services package for pipeline inspection artifacts.
services/debug/capture.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PipelineDebugCapture – writes versioned inspection manifests for conversion jobs."""
2
+
3
+ import json
4
+ import time
5
+
6
+ import cv2
7
+ import numpy as np
8
+
9
+ from config.paths import JOB_DIR
10
+ from config.runtime import DEBUG_ARTIFACTS_ENABLED
11
+ from enums import JobStatus
12
+
13
+ from services.debug.helpers import (
14
+ _debug_json_default,
15
+ _debug_preview_rgb,
16
+ _debug_resize_rgb,
17
+ )
18
+
19
+
20
+ class PipelineDebugCapture:
21
+ """Writes a generic, versioned inspection manifest alongside a conversion job."""
22
+
23
+ def __init__(self, job_id: str):
24
+ self.job_id = job_id
25
+ self.root = JOB_DIR / f"{job_id}.debug"
26
+ self.root.mkdir(parents=True, exist_ok=True)
27
+ self.manifest_path = self.root / "manifest.json"
28
+ self.manifest = {
29
+ "schemaVersion": 2,
30
+ "jobId": job_id,
31
+ "status": JobStatus.PROCESSING,
32
+ "stages": [],
33
+ }
34
+ self._write_manifest()
35
+
36
+ def _write_manifest(self):
37
+ self.manifest["updatedAtMs"] = int(time.time() * 1000)
38
+ self.manifest_path.write_text(
39
+ json.dumps(self.manifest, separators=(",", ":"), default=_debug_json_default),
40
+ encoding="utf-8",
41
+ )
42
+
43
+ def record_images(
44
+ self,
45
+ stage_id: str,
46
+ title: str,
47
+ description: str,
48
+ images: list[tuple[str, np.ndarray]],
49
+ metrics: dict | None = None,
50
+ elapsed_ms: float | None = None,
51
+ ):
52
+ if not DEBUG_ARTIFACTS_ENABLED:
53
+ return
54
+ try:
55
+ artifacts = []
56
+ for index, (label, image_rgb) in enumerate(images):
57
+ filename = f"{len(self.manifest['stages']) + 1:02d}-{stage_id}-{index + 1}.jpg"
58
+ image_rgb = _debug_resize_rgb(image_rgb)
59
+ ok, encoded = cv2.imencode(".jpg", cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR), [cv2.IMWRITE_JPEG_QUALITY, 90])
60
+ if not ok:
61
+ continue
62
+ (self.root / filename).write_bytes(encoded.tobytes())
63
+ preview_filename = f"{filename[:-4]}.preview.jpg"
64
+ preview_rgb = _debug_preview_rgb(image_rgb)
65
+ preview_ok, preview_encoded = cv2.imencode(
66
+ ".jpg",
67
+ cv2.cvtColor(preview_rgb, cv2.COLOR_RGB2BGR),
68
+ [cv2.IMWRITE_JPEG_QUALITY, 82],
69
+ )
70
+ if preview_ok:
71
+ (self.root / preview_filename).write_bytes(preview_encoded.tobytes())
72
+ artifacts.append({
73
+ "type": "image",
74
+ "label": label,
75
+ "url": f"/viz2d/jobs/{self.job_id}/debug/assets/{filename}",
76
+ "previewUrl": (
77
+ f"/viz2d/jobs/{self.job_id}/debug/assets/{preview_filename}"
78
+ if preview_ok else None
79
+ ),
80
+ })
81
+ stage = {
82
+ "id": stage_id,
83
+ "title": title,
84
+ "description": description,
85
+ "artifacts": artifacts,
86
+ "metrics": metrics or {},
87
+ }
88
+ if elapsed_ms is not None:
89
+ stage["elapsedMs"] = round(float(elapsed_ms), 1)
90
+ self.manifest["stages"].append(stage)
91
+ self._write_manifest()
92
+ except Exception as exc:
93
+ print(f"[DEBUG] Could not capture {stage_id} for job {self.job_id}: {exc}", flush=True)
94
+
95
+ def complete(self, total_elapsed_ms: float):
96
+ if not DEBUG_ARTIFACTS_ENABLED:
97
+ return
98
+ self.manifest["status"] = JobStatus.COMPLETED
99
+ self.manifest["totalElapsedMs"] = round(float(total_elapsed_ms), 1)
100
+ self._write_manifest()
101
+
102
+ def fail(self, error: Exception):
103
+ if not DEBUG_ARTIFACTS_ENABLED:
104
+ return
105
+ self.manifest["status"] = JobStatus.FAILED
106
+ self.manifest["error"] = str(error)
107
+ self._write_manifest()
services/debug/helpers.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small helper utilities shared by debug capture and overlay modules."""
2
+
3
+ import numpy as np
4
+ import cv2
5
+
6
+ from config.runtime import (
7
+ DEBUG_ARTIFACTS_MAX_DIMENSION,
8
+ DEBUG_ARTIFACTS_PREVIEW_DIMENSION,
9
+ )
10
+
11
+
12
+ def _debug_resize_rgb(image_rgb: np.ndarray) -> np.ndarray:
13
+ height, width = image_rgb.shape[:2]
14
+ largest = max(height, width)
15
+ if largest <= DEBUG_ARTIFACTS_MAX_DIMENSION:
16
+ return image_rgb
17
+ scale = DEBUG_ARTIFACTS_MAX_DIMENSION / largest
18
+ return cv2.resize(
19
+ image_rgb,
20
+ (max(1, round(width * scale)), max(1, round(height * scale))),
21
+ interpolation=cv2.INTER_AREA,
22
+ )
23
+
24
+
25
+ def _debug_preview_rgb(image_rgb: np.ndarray) -> np.ndarray:
26
+ height, width = image_rgb.shape[:2]
27
+ largest = max(height, width)
28
+ if largest <= DEBUG_ARTIFACTS_PREVIEW_DIMENSION:
29
+ return image_rgb
30
+ scale = DEBUG_ARTIFACTS_PREVIEW_DIMENSION / largest
31
+ return cv2.resize(
32
+ image_rgb,
33
+ (max(1, round(width * scale)), max(1, round(height * scale))),
34
+ interpolation=cv2.INTER_AREA,
35
+ )
36
+
37
+
38
+ def _debug_json_default(value):
39
+ if isinstance(value, np.generic):
40
+ return value.item()
41
+ if isinstance(value, np.ndarray):
42
+ return value.tolist()
43
+ raise TypeError(f"Unsupported debug manifest value: {type(value).__name__}")
services/debug/overlays.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Debug overlay / visualization functions for pipeline stages."""
2
+
3
+ import numpy as np
4
+ import cv2
5
+
6
+
7
+ def debug_mask_overlay(
8
+ image_rgb: np.ndarray,
9
+ mask: np.ndarray,
10
+ color: tuple[int, int, int] = (45, 180, 255),
11
+ ) -> np.ndarray:
12
+ """Overlay a binary analysis mask without changing the uploaded image."""
13
+ output = image_rgb.copy()
14
+ valid = mask.astype(bool)
15
+ if valid.any():
16
+ overlay = np.empty_like(output)
17
+ overlay[:] = color
18
+ output[valid] = cv2.addWeighted(output, 0.42, overlay, 0.58, 0)[valid]
19
+ return output
20
+
21
+
22
+ def debug_segmentation_overlay(image_rgb: np.ndarray, seg_map: np.ndarray) -> np.ndarray:
23
+ labels = seg_map.astype(np.int32)
24
+ hsv = np.zeros((*labels.shape, 3), dtype=np.uint8)
25
+ hsv[..., 0] = (labels * 37) % 180
26
+ hsv[..., 1] = 180
27
+ hsv[..., 2] = 255
28
+ colors = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
29
+ return cv2.addWeighted(image_rgb, 0.42, colors, 0.58, 0)
30
+
31
+
32
+ def debug_scalar_map(values: np.ndarray, mask: np.ndarray | None = None) -> np.ndarray:
33
+ scalar = values.astype(np.float32)
34
+ finite = np.isfinite(scalar)
35
+ if mask is not None:
36
+ finite &= mask.astype(bool)
37
+ valid = scalar[finite]
38
+ if valid.size == 0:
39
+ return np.zeros((*scalar.shape[:2], 3), dtype=np.uint8)
40
+ low, high = np.percentile(valid, [2, 98])
41
+ if high <= low:
42
+ high = low + 1.0
43
+ normalized = np.clip((scalar - low) / (high - low), 0.0, 1.0)
44
+ normalized[~np.isfinite(normalized)] = 0.0
45
+ output = cv2.applyColorMap(np.round(normalized * 255).astype(np.uint8), cv2.COLORMAP_TURBO)
46
+ output = cv2.cvtColor(output, cv2.COLOR_BGR2RGB)
47
+ if mask is not None:
48
+ output[~mask.astype(bool)] = 0
49
+ return output
50
+
51
+
52
+ def debug_plane_overlay(image_rgb: np.ndarray, plane: dict | None) -> np.ndarray:
53
+ output = image_rgb.copy()
54
+ if not plane:
55
+ return output
56
+ raw_quad = plane.get("quad")
57
+ if not isinstance(raw_quad, list) or len(raw_quad) != 8:
58
+ return output
59
+ points = np.asarray(raw_quad, dtype=np.float32).reshape(-1, 2)
60
+ if not np.isfinite(points).all():
61
+ return output
62
+ points_i = np.round(points).astype(np.int32)
63
+ overlay = output.copy()
64
+ cv2.fillConvexPoly(overlay, points_i, (45, 180, 255))
65
+ output = cv2.addWeighted(output, 0.64, overlay, 0.36, 0)
66
+ cv2.polylines(output, [points_i], isClosed=True, color=(255, 255, 255), thickness=3, lineType=cv2.LINE_AA)
67
+ return output
68
+
69
+
70
+ def debug_surface_overlay(image_rgb: np.ndarray, floor_mask: np.ndarray, surface_mask: np.ndarray) -> np.ndarray:
71
+ output = image_rgb.copy()
72
+ removed = (floor_mask > 0) & (surface_mask == 0)
73
+ if removed.any():
74
+ red = np.empty_like(output)
75
+ red[:] = (220, 80, 80)
76
+ output[removed] = cv2.addWeighted(output, 0.42, red, 0.58, 0)[removed]
77
+ return debug_mask_overlay(output, surface_mask, (45, 180, 255))
78
+
79
+
80
+ def debug_floor_direction_overlay(image_rgb: np.ndarray, floor_direction: dict) -> np.ndarray:
81
+ output = image_rgb.copy()
82
+ direction_axis = floor_direction.get("directionAxis")
83
+ if isinstance(direction_axis, dict):
84
+ try:
85
+ start = (
86
+ round(float(direction_axis["startX"])),
87
+ round(float(direction_axis["startY"])),
88
+ )
89
+ end = (
90
+ round(float(direction_axis["endX"])),
91
+ round(float(direction_axis["endY"])),
92
+ )
93
+ cv2.arrowedLine(
94
+ output,
95
+ start,
96
+ end,
97
+ (45, 180, 255),
98
+ 4,
99
+ cv2.LINE_AA,
100
+ tipLength=0.08,
101
+ )
102
+ except (KeyError, TypeError, ValueError):
103
+ pass
104
+
105
+ geometry_axis = floor_direction.get("geometryAxis")
106
+ if isinstance(geometry_axis, dict):
107
+ try:
108
+ start = (
109
+ round(float(geometry_axis["nearX"])),
110
+ round(float(geometry_axis["nearY"])),
111
+ )
112
+ end = (
113
+ round(float(geometry_axis["farX"])),
114
+ round(float(geometry_axis["farY"])),
115
+ )
116
+ cv2.arrowedLine(
117
+ output,
118
+ start,
119
+ end,
120
+ (45, 180, 255),
121
+ 4,
122
+ cv2.LINE_AA,
123
+ tipLength=0.08,
124
+ )
125
+ except (KeyError, TypeError, ValueError):
126
+ pass
127
+
128
+ for line in floor_direction.get("dominantLines") or []:
129
+ try:
130
+ start = (round(float(line["x1"])), round(float(line["y1"])))
131
+ end = (round(float(line["x2"])), round(float(line["y2"])))
132
+ except (KeyError, TypeError, ValueError):
133
+ continue
134
+ cv2.line(output, start, end, (45, 180, 255), 3, cv2.LINE_AA)
135
+
136
+ label = floor_direction.get("directionLabel") or "unknown"
137
+ angle = floor_direction.get("renderAngleDegrees")
138
+ confidence = floor_direction.get("confidence")
139
+ detail = f"{label}"
140
+ if isinstance(angle, (int, float)):
141
+ detail += f" {angle:.1f} deg"
142
+ if isinstance(confidence, (int, float)):
143
+ detail += f" {confidence:.0%}"
144
+ cv2.putText(output, detail, (16, 34), cv2.FONT_HERSHEY_SIMPLEX, 0.72, (255, 255, 255), 3, cv2.LINE_AA)
145
+ cv2.putText(output, detail, (16, 34), cv2.FONT_HERSHEY_SIMPLEX, 0.72, (25, 25, 25), 1, cv2.LINE_AA)
146
+ return output
147
+
148
+
149
+ def debug_uv_checkerboard(
150
+ height: int,
151
+ width: int,
152
+ surface_indices: np.ndarray,
153
+ uv: np.ndarray,
154
+ ) -> np.ndarray:
155
+ output = np.zeros((height, width, 3), dtype=np.uint8)
156
+ valid = np.isfinite(uv).all(axis=1)
157
+ if not valid.any():
158
+ return output
159
+ coords = uv[valid]
160
+ cells = (np.floor(coords[:, 0] * 8) + np.floor(coords[:, 1] * 8)).astype(np.int32)
161
+ colors = np.where((cells % 2)[:, None] == 0, np.array([45, 180, 255]), np.array([45, 80, 180]))
162
+ output.reshape(-1, 3)[surface_indices[valid]] = colors.astype(np.uint8)
163
+ return output
164
+
165
+
166
+ def debug_plane_id_map(
167
+ height: int,
168
+ width: int,
169
+ surface_indices: np.ndarray,
170
+ plane_ids: np.ndarray,
171
+ ) -> np.ndarray:
172
+ output = np.zeros((height, width, 3), dtype=np.uint8)
173
+ valid = plane_ids >= 0
174
+ if not valid.any():
175
+ return output
176
+ ids = plane_ids[valid].astype(np.int32)
177
+ hsv = np.zeros((len(ids), 1, 3), dtype=np.uint8)
178
+ hsv[:, 0, 0] = (ids * 47) % 180
179
+ hsv[:, 0, 1] = 190
180
+ hsv[:, 0, 2] = 255
181
+ output.reshape(-1, 3)[surface_indices[valid]] = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB).reshape(-1, 3)
182
+ return output
services/direction/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Floor direction analysis and response formatting services.
services/direction/analysis.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Floor direction geometry helpers."""
2
+
3
+ import numpy as np
4
+
5
+ from services.geometry.camera import default_camera_intrinsics
6
+ from services.geometry.multi_plane import geometry_point_maps
7
+
8
+
9
+ def floor_direction_geometry_inputs(
10
+ surface_mask: np.ndarray,
11
+ geometry: dict | None,
12
+ plane: dict | None,
13
+ surface_mapping: dict | None,
14
+ *,
15
+ use_surface_uv: bool,
16
+ ) -> dict:
17
+ direction_maps = surface_mapping
18
+ if direction_maps is None:
19
+ raw_maps = geometry_point_maps(surface_mask, geometry)
20
+ if raw_maps is not None:
21
+ direction_maps = {
22
+ "normalMap": raw_maps["normals"],
23
+ "validMask": raw_maps["validMask"],
24
+ "intrinsics": raw_maps["intrinsics"],
25
+ "planes": [],
26
+ }
27
+
28
+ normal_map = direction_maps.get("normalMap") if direction_maps else None
29
+ valid_mask = direction_maps.get("validMask") if direction_maps else None
30
+ intrinsics = direction_maps.get("intrinsics") if direction_maps else None
31
+ surface_planes = direction_maps.get("planes") or [] if direction_maps else []
32
+ dominant_floor_plane = None
33
+ if surface_planes:
34
+ floor_planes = [item for item in surface_planes if item.get("isFloor")]
35
+ candidates = floor_planes or surface_planes
36
+ dominant_floor_plane = max(
37
+ candidates,
38
+ key=lambda item: int(item.get("assignedCount") or item.get("inlierCount") or 0),
39
+ )
40
+
41
+ floor_normal = None
42
+ render_u_axis = None
43
+ render_v_axis = None
44
+ if use_surface_uv and dominant_floor_plane is not None:
45
+ floor_normal = dominant_floor_plane.get("normal")
46
+ render_u_axis = dominant_floor_plane.get("uAxis")
47
+ render_v_axis = dominant_floor_plane.get("vAxis")
48
+ elif plane and plane.get("planeNormal"):
49
+ floor_normal = plane.get("planeNormal")
50
+ elif dominant_floor_plane is not None:
51
+ floor_normal = dominant_floor_plane.get("normal")
52
+
53
+ if floor_normal is None and normal_map is not None and normal_map.shape[:2] == surface_mask.shape:
54
+ lengths = np.linalg.norm(normal_map, axis=2)
55
+ valid_floor = (
56
+ (surface_mask > 0)
57
+ & np.isfinite(normal_map).all(axis=2)
58
+ & (lengths > 1e-4)
59
+ )
60
+ if valid_mask is not None and valid_mask.shape == surface_mask.shape:
61
+ valid_floor &= valid_mask.astype(bool)
62
+ floor_normals = normal_map[valid_floor]
63
+ if len(floor_normals) >= 200:
64
+ floor_normals = floor_normals / np.linalg.norm(floor_normals, axis=1, keepdims=True)
65
+ reference = np.median(floor_normals, axis=0)
66
+ if reference[1] < 0:
67
+ reference = -reference
68
+ floor_normal = reference.tolist()
69
+
70
+ if intrinsics is None and plane and plane.get("cameraIntrinsics"):
71
+ intrinsics = np.asarray(plane["cameraIntrinsics"], dtype=np.float32).reshape(3, 3)
72
+ if intrinsics is None:
73
+ height, width = surface_mask.shape[:2]
74
+ intrinsics = default_camera_intrinsics(width, height)
75
+
76
+ return {
77
+ "normalsMap": normal_map,
78
+ "validMask": valid_mask,
79
+ "intrinsics": intrinsics,
80
+ "floorNormal": floor_normal,
81
+ "renderUAxis": render_u_axis,
82
+ "renderVAxis": render_v_axis,
83
+ }
services/direction/response.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Floor direction response formatting: API payloads and metadata dicts."""
2
+
3
+ import base64
4
+
5
+ import cv2
6
+ import numpy as np
7
+
8
+ from errors import server_error
9
+
10
+
11
+ def encode_png_data_url(image_bgr: np.ndarray) -> str:
12
+ ok, encoded = cv2.imencode(".png", image_bgr)
13
+ if not ok:
14
+ server_error("Could not encode overlay image.")
15
+ payload = base64.b64encode(encoded.tobytes()).decode("ascii")
16
+ return f"data:image/png;base64,{payload}"
17
+
18
+
19
+ def floor_direction_response(result, segmentation) -> dict:
20
+ overlay_image_base64 = None
21
+ if result.overlay_bgr is not None:
22
+ overlay_image_base64 = encode_png_data_url(result.overlay_bgr)
23
+
24
+ return {
25
+ "angle_degrees": result.angle_degrees,
26
+ "render_angle_degrees": result.render_angle_degrees,
27
+ "secondary_angle_degrees": result.secondary_angle_degrees,
28
+ "direction_label": result.direction_label,
29
+ "confidence": result.confidence,
30
+ "segmentation": {
31
+ "label": segmentation.label,
32
+ "confidence": segmentation.confidence,
33
+ "polygon_count": len(segmentation.polygons),
34
+ "floor_area_ratio": result.floor_area_ratio,
35
+ "source_path": segmentation.source_path,
36
+ "raw_keys": segmentation.raw_keys or [],
37
+ },
38
+ "line_count": result.line_count,
39
+ "dominant_line_count": result.dominant_line_count,
40
+ "grid_pattern_detected": result.grid_pattern_detected,
41
+ "dominant_lines": [
42
+ {
43
+ "x1": line.x1,
44
+ "y1": line.y1,
45
+ "x2": line.x2,
46
+ "y2": line.y2,
47
+ "angle_degrees": line.angle_degrees,
48
+ "length": line.length,
49
+ }
50
+ for line in result.dominant_lines
51
+ ],
52
+ "warnings": result.warnings,
53
+ "overlay_image_base64": overlay_image_base64,
54
+ }
55
+
56
+
57
+ def floor_direction_metadata(result, segmentation) -> dict:
58
+ return {
59
+ "source": "backend-floor-direction",
60
+ "angleDegrees": result.angle_degrees,
61
+ "renderAngleDegrees": result.render_angle_degrees,
62
+ "secondaryAngleDegrees": result.secondary_angle_degrees,
63
+ "directionLabel": result.direction_label,
64
+ "confidence": result.confidence,
65
+ "floorAreaRatio": result.floor_area_ratio,
66
+ "lineCount": result.line_count,
67
+ "dominantLineCount": result.dominant_line_count,
68
+ "gridPatternDetected": result.grid_pattern_detected,
69
+ "warnings": result.warnings,
70
+ "dominantLines": [
71
+ {
72
+ "x1": line.x1,
73
+ "y1": line.y1,
74
+ "x2": line.x2,
75
+ "y2": line.y2,
76
+ "angleDegrees": line.angle_degrees,
77
+ "length": line.length,
78
+ }
79
+ for line in result.dominant_lines
80
+ ],
81
+ "segmentation": {
82
+ "label": segmentation.label,
83
+ "confidence": segmentation.confidence,
84
+ "polygonCount": len(segmentation.polygons),
85
+ "sourcePath": segmentation.source_path,
86
+ },
87
+ }
services/floor/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Floor surface detection, masking, and geometry services.