Spaces:
Paused
Paused
Codex Preview Deploy commited on
Commit ·
35e8281
1
Parent(s): 20e8cd7
Preview feature/realistic-floor-rendering at 51e5560
Browse files- .dockerignore +11 -0
- .gitignore +9 -0
- ARCHITECTURE.md +53 -0
- Dockerfile +19 -3
- Dockerfile.hf +19 -3
- README.md +65 -0
- SETUP.md +61 -0
- app.py +0 -0
- direction_finder.py +1009 -0
- floor_direction.py +1813 -0
- frontend/viz2d-demo/e2e/README.md +70 -0
- frontend/viz2d-demo/e2e/lighting-preservation.spec.ts +242 -0
- frontend/viz2d-demo/e2e/real-room-qa.spec.ts +598 -0
- frontend/viz2d-demo/e2e/support/gemini-judge.ts +202 -0
- frontend/viz2d-demo/e2e/support/image-checks.ts +104 -0
- frontend/viz2d-demo/e2e/support/qa-progress-reporter.cjs +76 -0
- frontend/viz2d-demo/package-lock.json +0 -0
- frontend/viz2d-demo/package.json +53 -0
- frontend/viz2d-demo/playwright.config.ts +61 -0
- frontend/viz2d-demo/scripts/build-qa-summary.mjs +329 -0
- requirements-base.txt +2 -0
- requirements-gpu-cu126.txt +1 -0
- test_floor_geometry.py +1064 -169
- visualizer.gpu.toml +21 -3
- visualizer.hf.toml +14 -3
- visualizer.local.toml +17 -3
- visualizer.segformer.toml +14 -3
.dockerignore
CHANGED
|
@@ -9,5 +9,16 @@ venv/
|
|
| 9 |
env/
|
| 10 |
data/uploads/
|
| 11 |
data/jobs/
|
|
|
|
| 12 |
.env
|
| 13 |
*.log
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
env/
|
| 10 |
data/uploads/
|
| 11 |
data/jobs/
|
| 12 |
+
data/qa-runs/
|
| 13 |
.env
|
| 14 |
*.log
|
| 15 |
+
node_modules/
|
| 16 |
+
frontend/viz2d-demo/node_modules/
|
| 17 |
+
frontend/viz2d-demo/dist/
|
| 18 |
+
frontend/viz2d-demo/dist-ssr/
|
| 19 |
+
frontend/viz2d-demo/playwright-report/
|
| 20 |
+
frontend/viz2d-demo/test-results/
|
| 21 |
+
frontend/viz2d-demo/.env
|
| 22 |
+
frontend/viz2d-demo/.env.local
|
| 23 |
+
frontend/viz2d-demo/.env.*.local
|
| 24 |
+
frontend/viz2d-demo/*.tsbuildinfo
|
.gitignore
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# Virtual environment
|
| 2 |
venv/
|
| 3 |
.venv/
|
|
@@ -38,3 +41,9 @@ data/jobs/
|
|
| 38 |
# Logs
|
| 39 |
*.log
|
| 40 |
uvicorn.log
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Build output
|
| 2 |
+
data/qa-runs
|
| 3 |
+
|
| 4 |
# Virtual environment
|
| 5 |
venv/
|
| 6 |
.venv/
|
|
|
|
| 41 |
# Logs
|
| 42 |
*.log
|
| 43 |
uvicorn.log
|
| 44 |
+
|
| 45 |
+
# Frontend QA runner artifacts when deployed into the Hugging Face Space
|
| 46 |
+
node_modules/
|
| 47 |
+
playwright-report/
|
| 48 |
+
test-results/
|
| 49 |
+
*.tsbuildinfo
|
ARCHITECTURE.md
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Floor Visualizer Architecture
|
| 2 |
+
|
| 3 |
+
This document summarizes the floor detection and tile rendering pipeline for client communication.
|
| 4 |
+
|
| 5 |
+
## Previous Pipeline
|
| 6 |
+
|
| 7 |
+
```mermaid
|
| 8 |
+
flowchart TD
|
| 9 |
+
A[Room image upload] --> B[OneFormer semantic segmentation]
|
| 10 |
+
B --> C[Initial floor mask]
|
| 11 |
+
C --> D[OpenCV mask cleanup]
|
| 12 |
+
D --> E[MoGe / Depth geometry]
|
| 13 |
+
E --> F[Floor plane + UV mapping]
|
| 14 |
+
F --> G[Canvas tile renderer]
|
| 15 |
+
G --> H[Final room preview]
|
| 16 |
+
```
|
| 17 |
+
|
| 18 |
+
The previous system mainly depended on semantic segmentation to identify the floor, then used geometry to place the tile texture in perspective. This worked well when the segmentation mask was clean, but weak floor edges, rugs, furniture bleed, and wall/floor boundary mistakes could make the tile placement look less realistic.
|
| 19 |
+
|
| 20 |
+
## Current GPU Pipeline
|
| 21 |
+
|
| 22 |
+
```mermaid
|
| 23 |
+
flowchart TD
|
| 24 |
+
A[Room image upload] --> B[OneFormer semantic segmentation]
|
| 25 |
+
B --> C[Initial floor class mask]
|
| 26 |
+
C --> D[OpenCV edge fixing and mask cleanup]
|
| 27 |
+
D --> E[SAM2 mask refinement]
|
| 28 |
+
E --> F[MoGe metric geometry]
|
| 29 |
+
F --> G[Dominant floor plane filtering]
|
| 30 |
+
G --> H[Surface UV / perspective mapping]
|
| 31 |
+
H --> I[Lighting and reflection transfer]
|
| 32 |
+
I --> J[Material-aware tile renderer]
|
| 33 |
+
J --> K[Final room preview]
|
| 34 |
+
|
| 35 |
+
E --> L{SAM2 unavailable or weak result?}
|
| 36 |
+
L -->|Yes| M[Fallback to cleaned OneFormer mask]
|
| 37 |
+
M --> F
|
| 38 |
+
L -->|No| F
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
## What Changed
|
| 42 |
+
|
| 43 |
+
- **OneFormer still detects the floor class.** It remains responsible for identifying which pixels are likely floor.
|
| 44 |
+
- **OpenCV edge fixing runs before refinement.** We clean the raw semantic mask with morphology, contour filling, protected wall/object removal, and edge coverage repair before using it downstream.
|
| 45 |
+
- **SAM2 now refines the cleaned floor mask on GPU deploy.** SAM2 receives the cleaned floor region as prompt context and improves the actual boundary quality.
|
| 46 |
+
- **MoGe geometry validates the floor plane.** After segmentation/refinement, MoGe provides metric geometry so we can reject pixels that do not belong to the dominant floor plane.
|
| 47 |
+
- **Rendering now uses material and lighting controls.** The canvas renderer supports tile scale, rotation, grout, roughness, gloss, room light, reflection transfer, and perspective-aware UV mapping.
|
| 48 |
+
- **Safe fallback is preserved.** If SAM2 fails to load or produces a weak mask, the backend falls back to the cleaned OneFormer + MoGe path instead of failing the job.
|
| 49 |
+
|
| 50 |
+
## Client Summary
|
| 51 |
+
|
| 52 |
+
Before, the system used semantic segmentation plus geometry. Now, the GPU pipeline adds a refinement stage: OneFormer finds the floor, OpenCV cleans and fixes the mask edges, SAM2 sharpens the floor boundary, MoGe validates the actual floor plane, and the renderer applies the tile with perspective, lighting, and material controls. This should reduce boundary errors and make the tile look more integrated with the original room.
|
| 53 |
+
|
Dockerfile
CHANGED
|
@@ -5,6 +5,8 @@ ENV PYTHONUNBUFFERED=1 \
|
|
| 5 |
PYTHONDONTWRITEBYTECODE=1 \
|
| 6 |
HF_HOME=/home/user/.cache/huggingface \
|
| 7 |
VISUALIZER_CONFIG=visualizer.gpu.toml \
|
|
|
|
|
|
|
| 8 |
HOME=/home/user
|
| 9 |
|
| 10 |
# Install system dependencies (git for compphoto/Intrinsic installation, ffmpeg, glib for OpenCV)
|
|
@@ -14,7 +16,10 @@ RUN apt-get update && \
|
|
| 14 |
ffmpeg \
|
| 15 |
libglib2.0-0 \
|
| 16 |
libgomp1 \
|
| 17 |
-
build-essential
|
|
|
|
|
|
|
|
|
|
| 18 |
rm -rf /var/lib/apt/lists/*
|
| 19 |
|
| 20 |
# Set up a new user named "user" with UID 1000 for Hugging Face permissions
|
|
@@ -32,9 +37,20 @@ RUN pip install --no-cache-dir --upgrade pip && \
|
|
| 32 |
# Copy the rest of the application files
|
| 33 |
COPY --chown=user:1000 . .
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
# Create writable data directories and change ownership
|
| 36 |
-
RUN mkdir -p data/uploads data/jobs && \
|
| 37 |
-
chown -R user:1000 /app
|
| 38 |
|
| 39 |
# Switch to the non-root user
|
| 40 |
USER user
|
|
|
|
| 5 |
PYTHONDONTWRITEBYTECODE=1 \
|
| 6 |
HF_HOME=/home/user/.cache/huggingface \
|
| 7 |
VISUALIZER_CONFIG=visualizer.gpu.toml \
|
| 8 |
+
PLAYWRIGHT_BROWSERS_PATH=/ms-playwright \
|
| 9 |
+
QA_FRONTEND_DIR=/app/frontend/viz2d-demo \
|
| 10 |
HOME=/home/user
|
| 11 |
|
| 12 |
# Install system dependencies (git for compphoto/Intrinsic installation, ffmpeg, glib for OpenCV)
|
|
|
|
| 16 |
ffmpeg \
|
| 17 |
libglib2.0-0 \
|
| 18 |
libgomp1 \
|
| 19 |
+
build-essential \
|
| 20 |
+
ca-certificates \
|
| 21 |
+
nodejs \
|
| 22 |
+
npm && \
|
| 23 |
rm -rf /var/lib/apt/lists/*
|
| 24 |
|
| 25 |
# Set up a new user named "user" with UID 1000 for Hugging Face permissions
|
|
|
|
| 37 |
# Copy the rest of the application files
|
| 38 |
COPY --chown=user:1000 . .
|
| 39 |
|
| 40 |
+
# Install optional Playwright QA runner dependencies when frontend/viz2d-demo
|
| 41 |
+
# is included in the Hugging Face Space.
|
| 42 |
+
RUN if [ -f frontend/viz2d-demo/package-lock.json ]; then \
|
| 43 |
+
cd frontend/viz2d-demo && \
|
| 44 |
+
npm ci && \
|
| 45 |
+
npx playwright install --with-deps chromium; \
|
| 46 |
+
else \
|
| 47 |
+
echo "frontend/viz2d-demo not found; skipping Playwright QA runner install"; \
|
| 48 |
+
fi && \
|
| 49 |
+
rm -rf /var/lib/apt/lists/*
|
| 50 |
+
|
| 51 |
# Create writable data directories and change ownership
|
| 52 |
+
RUN mkdir -p data/uploads data/jobs data/qa-runs /ms-playwright && \
|
| 53 |
+
chown -R user:1000 /app /ms-playwright
|
| 54 |
|
| 55 |
# Switch to the non-root user
|
| 56 |
USER user
|
Dockerfile.hf
CHANGED
|
@@ -5,6 +5,8 @@ ENV PYTHONUNBUFFERED=1 \
|
|
| 5 |
PYTHONDONTWRITEBYTECODE=1 \
|
| 6 |
HF_HOME=/home/user/.cache/huggingface \
|
| 7 |
VISUALIZER_CONFIG=visualizer.gpu.toml \
|
|
|
|
|
|
|
| 8 |
HOME=/home/user
|
| 9 |
|
| 10 |
# Install system dependencies (git for compphoto/Intrinsic installation, ffmpeg, glib for OpenCV)
|
|
@@ -14,7 +16,10 @@ RUN apt-get update && \
|
|
| 14 |
ffmpeg \
|
| 15 |
libglib2.0-0 \
|
| 16 |
libgomp1 \
|
| 17 |
-
build-essential
|
|
|
|
|
|
|
|
|
|
| 18 |
rm -rf /var/lib/apt/lists/*
|
| 19 |
|
| 20 |
# Set up a new user named "user" with UID 1000 for Hugging Face permissions
|
|
@@ -32,9 +37,20 @@ RUN pip install --no-cache-dir --upgrade pip && \
|
|
| 32 |
# Copy the rest of the application files
|
| 33 |
COPY --chown=user:1000 . .
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
# Create writable data directories and change ownership
|
| 36 |
-
RUN mkdir -p data/uploads data/jobs && \
|
| 37 |
-
chown -R user:1000 /app
|
| 38 |
|
| 39 |
# Switch to the non-root user
|
| 40 |
USER user
|
|
|
|
| 5 |
PYTHONDONTWRITEBYTECODE=1 \
|
| 6 |
HF_HOME=/home/user/.cache/huggingface \
|
| 7 |
VISUALIZER_CONFIG=visualizer.gpu.toml \
|
| 8 |
+
PLAYWRIGHT_BROWSERS_PATH=/ms-playwright \
|
| 9 |
+
QA_FRONTEND_DIR=/app/frontend/viz2d-demo \
|
| 10 |
HOME=/home/user
|
| 11 |
|
| 12 |
# Install system dependencies (git for compphoto/Intrinsic installation, ffmpeg, glib for OpenCV)
|
|
|
|
| 16 |
ffmpeg \
|
| 17 |
libglib2.0-0 \
|
| 18 |
libgomp1 \
|
| 19 |
+
build-essential \
|
| 20 |
+
ca-certificates \
|
| 21 |
+
nodejs \
|
| 22 |
+
npm && \
|
| 23 |
rm -rf /var/lib/apt/lists/*
|
| 24 |
|
| 25 |
# Set up a new user named "user" with UID 1000 for Hugging Face permissions
|
|
|
|
| 37 |
# Copy the rest of the application files
|
| 38 |
COPY --chown=user:1000 . .
|
| 39 |
|
| 40 |
+
# Install optional Playwright QA runner dependencies when frontend/viz2d-demo
|
| 41 |
+
# is included in the Hugging Face Space.
|
| 42 |
+
RUN if [ -f frontend/viz2d-demo/package-lock.json ]; then \
|
| 43 |
+
cd frontend/viz2d-demo && \
|
| 44 |
+
npm ci && \
|
| 45 |
+
npx playwright install --with-deps chromium; \
|
| 46 |
+
else \
|
| 47 |
+
echo "frontend/viz2d-demo not found; skipping Playwright QA runner install"; \
|
| 48 |
+
fi && \
|
| 49 |
+
rm -rf /var/lib/apt/lists/*
|
| 50 |
+
|
| 51 |
# Create writable data directories and change ownership
|
| 52 |
+
RUN mkdir -p data/uploads data/jobs data/qa-runs /ms-playwright && \
|
| 53 |
+
chown -R user:1000 /app /ms-playwright
|
| 54 |
|
| 55 |
# Switch to the non-root user
|
| 56 |
USER user
|
README.md
CHANGED
|
@@ -27,6 +27,71 @@ python -m pip install -r requirements-mac.txt
|
|
| 27 |
VISUALIZER_CONFIG=visualizer.local.toml uvicorn app:app --host 0.0.0.0 --port 8002
|
| 28 |
```
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
GPU run:
|
| 31 |
|
| 32 |
```bash
|
|
|
|
| 27 |
VISUALIZER_CONFIG=visualizer.local.toml uvicorn app:app --host 0.0.0.0 --port 8002
|
| 28 |
```
|
| 29 |
|
| 30 |
+
Optional Gemini tile refinement:
|
| 31 |
+
|
| 32 |
+
```bash
|
| 33 |
+
export GEMINI_API_KEY="your-google-ai-studio-key"
|
| 34 |
+
export GEMINI_IMAGE_MODEL="gemini-3.1-flash-image"
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
When configured, the frontend can send the final tile-rendered image to
|
| 38 |
+
`/gemini/refine-tile-render` for a conservative reflection, shadow, and detail
|
| 39 |
+
polish pass.
|
| 40 |
+
|
| 41 |
+
Optional DigitalOcean Spaces upload archive in `backend/floor-visualizer/.env`:
|
| 42 |
+
|
| 43 |
+
```bash
|
| 44 |
+
SPACES_BUCKET="your-space-name"
|
| 45 |
+
SPACES_REGION="nyc3"
|
| 46 |
+
SPACES_ACCESS_KEY_ID="your-spaces-access-key"
|
| 47 |
+
SPACES_SECRET_ACCESS_KEY="your-spaces-secret-key"
|
| 48 |
+
SPACES_UPLOAD_PREFIX="room-uploads"
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
When these are set, `/viz2d/convert` keeps the current frontend flow unchanged
|
| 52 |
+
and uploads a copy of each room image to Spaces in the background.
|
| 53 |
+
|
| 54 |
+
Visual QA runner:
|
| 55 |
+
|
| 56 |
+
```bash
|
| 57 |
+
QA_FRONTEND_URL="https://your-vercel-frontend.example"
|
| 58 |
+
QA_BACKEND_URL="https://your-backend.example"
|
| 59 |
+
QA_FRONTEND_DIR="/mnt/room-editor/frontend/viz2d-demo"
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
For Hugging Face, `QA_FRONTEND_DIR` defaults to
|
| 63 |
+
`/app/frontend/viz2d-demo` in the Dockerfile.
|
| 64 |
+
|
| 65 |
+
The debug visualizer QA page calls `/qa/images`, `/qa/runs`,
|
| 66 |
+
`/qa/runs/{run_id}/events`, and `/qa/runs/{run_id}`. `/qa/images` lists
|
| 67 |
+
DigitalOcean Spaces directly through the S3 API, deduplicates exact object
|
| 68 |
+
matches by `ETag` and size, and does not use a database. `/qa/runs` deduplicates
|
| 69 |
+
the selected image keys again, downloads the unique Spaces images into
|
| 70 |
+
`data/qa-runs/{run_id}/`, starts the Playwright test suite from
|
| 71 |
+
`QA_FRONTEND_DIR`, and stores file-backed run status/results in that run folder.
|
| 72 |
+
The Playwright suite uploads each selected image once, then applies the selected
|
| 73 |
+
tiles one by one, removing the previous tile before applying the next tile.
|
| 74 |
+
`/qa/runs/{run_id}/events` streams run updates as Server-Sent Events so the
|
| 75 |
+
debug page does not need to poll while a run is active. Playwright writes
|
| 76 |
+
incremental progress after every completed test, so the `completed`, `passed`,
|
| 77 |
+
and `failed` counters update before the final report is generated.
|
| 78 |
+
`/qa/runs/{run_id}/report` renders a shareable HTML report with screenshot URLs;
|
| 79 |
+
`/qa/runs/{run_id}/report.md` returns the compact Markdown summary.
|
| 80 |
+
|
| 81 |
+
On Hugging Face, the deploy workflow copies a minimal `frontend/viz2d-demo` QA
|
| 82 |
+
runner folder into the Space: npm manifests, Playwright config, e2e tests, and
|
| 83 |
+
the Markdown report script. It intentionally does not copy frontend image
|
| 84 |
+
assets or `test-images`; real QA images are downloaded from DigitalOcean during
|
| 85 |
+
each run. The Dockerfile installs Node, npm, Playwright, and Chromium during the
|
| 86 |
+
Space rebuild. For non-Hugging Face servers, install the Node runner
|
| 87 |
+
dependencies manually:
|
| 88 |
+
|
| 89 |
+
```bash
|
| 90 |
+
cd /mnt/room-editor/frontend/viz2d-demo
|
| 91 |
+
npm install
|
| 92 |
+
npx playwright install --with-deps chromium
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
GPU run:
|
| 96 |
|
| 97 |
```bash
|
SETUP.md
CHANGED
|
@@ -33,3 +33,64 @@ It also downloads `Ruicheng/moge-2-vitl-normal`, the primary GPU geometry model.
|
|
| 33 |
|
| 34 |
- Environment variables override TOML values, for example `SEGMENTATION_MODEL=segformer`.
|
| 35 |
- `requirements.txt` is a full freeze from an existing environment. Prefer the smaller platform files above when recreating `.venv`.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
- Environment variables override TOML values, for example `SEGMENTATION_MODEL=segformer`.
|
| 35 |
- `requirements.txt` is a full freeze from an existing environment. Prefer the smaller platform files above when recreating `.venv`.
|
| 36 |
+
|
| 37 |
+
## Optional DigitalOcean Spaces upload archive
|
| 38 |
+
|
| 39 |
+
The `/viz2d/convert` endpoint can copy each uploaded room image to a private
|
| 40 |
+
DigitalOcean Spaces bucket in the background without changing the frontend
|
| 41 |
+
flow. Add these values to `backend/floor-visualizer/.env`:
|
| 42 |
+
|
| 43 |
+
```bash
|
| 44 |
+
SPACES_BUCKET="your-space-name"
|
| 45 |
+
SPACES_REGION="nyc3"
|
| 46 |
+
SPACES_ACCESS_KEY_ID="your-spaces-access-key"
|
| 47 |
+
SPACES_SECRET_ACCESS_KEY="your-spaces-secret-key"
|
| 48 |
+
SPACES_UPLOAD_PREFIX="room-uploads"
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
`SPACES_ENDPOINT_URL` is optional and defaults to
|
| 52 |
+
`https://$SPACES_REGION.digitaloceanspaces.com`. `SPACES_ACL` defaults to
|
| 53 |
+
`private`.
|
| 54 |
+
|
| 55 |
+
## Optional visual QA runner
|
| 56 |
+
|
| 57 |
+
The backend can also power the debug visualizer QA page without adding a
|
| 58 |
+
database. It lists images directly from DigitalOcean Spaces and writes each QA
|
| 59 |
+
run under `data/qa-runs/{run_id}/`.
|
| 60 |
+
|
| 61 |
+
Backend env:
|
| 62 |
+
|
| 63 |
+
```bash
|
| 64 |
+
QA_FRONTEND_URL="https://your-vercel-frontend.example"
|
| 65 |
+
QA_BACKEND_URL="https://your-backend.example"
|
| 66 |
+
QA_FRONTEND_DIR="/mnt/room-editor/frontend/viz2d-demo"
|
| 67 |
+
QA_MAX_IMAGES="50"
|
| 68 |
+
QA_MAX_TESTS="200"
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
For Hugging Face, `QA_FRONTEND_DIR` defaults to
|
| 72 |
+
`/app/frontend/viz2d-demo` in the Dockerfile.
|
| 73 |
+
|
| 74 |
+
The backend server needs Node and Playwright because the test runner opens the
|
| 75 |
+
hosted frontend in Chromium. On Hugging Face, the deploy workflow copies only
|
| 76 |
+
the text-based `frontend/viz2d-demo` QA runner files into the Space and the
|
| 77 |
+
Dockerfile installs these during rebuild. Real QA images are downloaded from
|
| 78 |
+
DigitalOcean during each run. On non-Hugging Face servers, install them
|
| 79 |
+
manually:
|
| 80 |
+
|
| 81 |
+
```bash
|
| 82 |
+
cd /mnt/room-editor/frontend/viz2d-demo
|
| 83 |
+
npm install
|
| 84 |
+
npx playwright install --with-deps chromium
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
The QA endpoints are:
|
| 88 |
+
|
| 89 |
+
```text
|
| 90 |
+
GET /qa/images
|
| 91 |
+
POST /qa/runs
|
| 92 |
+
GET /qa/runs/{run_id}
|
| 93 |
+
GET /qa/runs/{run_id}/events
|
| 94 |
+
GET /qa/runs/{run_id}/report
|
| 95 |
+
GET /qa/runs/{run_id}/report.md
|
| 96 |
+
```
|
app.py
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
direction_finder.py
ADDED
|
@@ -0,0 +1,1009 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Multi-cue floor direction estimation in renderer coordinates."""
|
| 2 |
+
|
| 3 |
+
from dataclasses import asdict, dataclass
|
| 4 |
+
import math
|
| 5 |
+
|
| 6 |
+
import cv2
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass(frozen=True)
|
| 11 |
+
class DirectionCue:
|
| 12 |
+
source: str
|
| 13 |
+
angle_degrees: float
|
| 14 |
+
confidence: float
|
| 15 |
+
support: int
|
| 16 |
+
region_support: int
|
| 17 |
+
ambiguity_degrees: float | None
|
| 18 |
+
details: dict
|
| 19 |
+
|
| 20 |
+
def metadata(self) -> dict:
|
| 21 |
+
payload = asdict(self)
|
| 22 |
+
payload["angleDegrees"] = payload.pop("angle_degrees")
|
| 23 |
+
payload["regionSupport"] = payload.pop("region_support")
|
| 24 |
+
payload["ambiguityDegrees"] = payload.pop("ambiguity_degrees")
|
| 25 |
+
return payload
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def normalize_angle(angle_degrees: float, period: float = 180.0) -> float:
|
| 29 |
+
return float(angle_degrees % period)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def angular_distance(first: float, second: float, period: float = 180.0) -> float:
|
| 33 |
+
difference = abs((first - second) % period)
|
| 34 |
+
return float(min(difference, period - difference))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def periodic_mean(
|
| 38 |
+
angles_degrees: np.ndarray,
|
| 39 |
+
weights: np.ndarray,
|
| 40 |
+
*,
|
| 41 |
+
period: float,
|
| 42 |
+
) -> tuple[float, float]:
|
| 43 |
+
if len(angles_degrees) == 0:
|
| 44 |
+
return 0.0, 0.0
|
| 45 |
+
weights = np.maximum(np.asarray(weights, dtype=np.float64), 0.0)
|
| 46 |
+
total_weight = float(weights.sum())
|
| 47 |
+
if total_weight <= 1e-9:
|
| 48 |
+
return 0.0, 0.0
|
| 49 |
+
phase = np.asarray(angles_degrees, dtype=np.float64) * (2.0 * np.pi / period)
|
| 50 |
+
vector_x = float(np.sum(np.cos(phase) * weights))
|
| 51 |
+
vector_y = float(np.sum(np.sin(phase) * weights))
|
| 52 |
+
angle = math.atan2(vector_y, vector_x) * (period / (2.0 * np.pi))
|
| 53 |
+
concentration = math.hypot(vector_x, vector_y) / total_weight
|
| 54 |
+
return normalize_angle(angle, period), float(np.clip(concentration, 0.0, 1.0))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def build_surface_uv_grids(
|
| 58 |
+
*,
|
| 59 |
+
image_shape: tuple[int, int],
|
| 60 |
+
surface_uv: np.ndarray | None,
|
| 61 |
+
surface_indices: np.ndarray | None,
|
| 62 |
+
surface_plane_ids: np.ndarray | None,
|
| 63 |
+
) -> tuple[np.ndarray | None, np.ndarray | None]:
|
| 64 |
+
height, width = image_shape
|
| 65 |
+
if surface_uv is None or surface_indices is None:
|
| 66 |
+
return None, None
|
| 67 |
+
if surface_uv.ndim != 2 or surface_uv.shape[1] != 2:
|
| 68 |
+
return None, None
|
| 69 |
+
if len(surface_uv) != len(surface_indices):
|
| 70 |
+
return None, None
|
| 71 |
+
|
| 72 |
+
flat_size = height * width
|
| 73 |
+
indices = np.asarray(surface_indices, dtype=np.int64)
|
| 74 |
+
valid_indices = (indices >= 0) & (indices < flat_size)
|
| 75 |
+
uv_grid = np.full((flat_size, 2), np.nan, dtype=np.float32)
|
| 76 |
+
uv_grid[indices[valid_indices]] = surface_uv[valid_indices].astype(np.float32)
|
| 77 |
+
|
| 78 |
+
plane_grid = None
|
| 79 |
+
if surface_plane_ids is not None and len(surface_plane_ids) == len(indices):
|
| 80 |
+
plane_grid = np.full(flat_size, 255, dtype=np.uint8)
|
| 81 |
+
plane_grid[indices[valid_indices]] = surface_plane_ids[valid_indices].astype(np.uint8)
|
| 82 |
+
|
| 83 |
+
return (
|
| 84 |
+
uv_grid.reshape(height, width, 2),
|
| 85 |
+
plane_grid.reshape(height, width) if plane_grid is not None else None,
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def rectify_floor_image(
|
| 90 |
+
image_rgb: np.ndarray,
|
| 91 |
+
surface_mask: np.ndarray,
|
| 92 |
+
*,
|
| 93 |
+
render_transform: list[float] | np.ndarray | None,
|
| 94 |
+
surface_uv: np.ndarray | None,
|
| 95 |
+
surface_indices: np.ndarray | None,
|
| 96 |
+
surface_plane_ids: np.ndarray | None,
|
| 97 |
+
) -> tuple[np.ndarray, np.ndarray, dict] | None:
|
| 98 |
+
height, width = surface_mask.shape[:2]
|
| 99 |
+
uv_grid, plane_grid = build_surface_uv_grids(
|
| 100 |
+
image_shape=(height, width),
|
| 101 |
+
surface_uv=surface_uv,
|
| 102 |
+
surface_indices=surface_indices,
|
| 103 |
+
surface_plane_ids=surface_plane_ids,
|
| 104 |
+
)
|
| 105 |
+
if uv_grid is not None:
|
| 106 |
+
result = rectify_from_uv(image_rgb, uv_grid, plane_grid)
|
| 107 |
+
if result is not None:
|
| 108 |
+
gray, mask = result
|
| 109 |
+
return gray, mask, {"source": "surface-uv", "width": gray.shape[1], "height": gray.shape[0]}
|
| 110 |
+
|
| 111 |
+
transform = normalize_transform(render_transform)
|
| 112 |
+
if transform is None:
|
| 113 |
+
return None
|
| 114 |
+
result = rectify_from_transform(image_rgb, surface_mask, transform)
|
| 115 |
+
if result is None:
|
| 116 |
+
return None
|
| 117 |
+
gray, mask = result
|
| 118 |
+
return gray, mask, {"source": "floor-transform", "width": gray.shape[1], "height": gray.shape[0]}
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def rectify_from_uv(
|
| 122 |
+
image_rgb: np.ndarray,
|
| 123 |
+
uv_grid: np.ndarray,
|
| 124 |
+
plane_grid: np.ndarray | None,
|
| 125 |
+
) -> tuple[np.ndarray, np.ndarray] | None:
|
| 126 |
+
valid = np.isfinite(uv_grid).all(axis=2)
|
| 127 |
+
if plane_grid is not None:
|
| 128 |
+
plane_values = plane_grid[valid & (plane_grid != 255)]
|
| 129 |
+
if plane_values.size:
|
| 130 |
+
dominant_plane = int(np.bincount(plane_values).argmax())
|
| 131 |
+
valid &= plane_grid == dominant_plane
|
| 132 |
+
if int(valid.sum()) < 800:
|
| 133 |
+
return None
|
| 134 |
+
|
| 135 |
+
uv = uv_grid[valid].astype(np.float64)
|
| 136 |
+
lower = np.percentile(uv, 0.5, axis=0)
|
| 137 |
+
upper = np.percentile(uv, 99.5, axis=0)
|
| 138 |
+
span = upper - lower
|
| 139 |
+
if not np.isfinite(span).all() or float(np.min(span)) <= 1e-5:
|
| 140 |
+
return None
|
| 141 |
+
|
| 142 |
+
scale = choose_rectification_scale(span, int(valid.sum()))
|
| 143 |
+
output_width = int(np.clip(round(float(span[0]) * scale) + 1, 96, 896))
|
| 144 |
+
output_height = int(np.clip(round(float(span[1]) * scale) + 1, 96, 896))
|
| 145 |
+
if output_width < 96 or output_height < 96:
|
| 146 |
+
return None
|
| 147 |
+
|
| 148 |
+
gray = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY)
|
| 149 |
+
values = gray[valid].astype(np.float64)
|
| 150 |
+
xy = np.rint((uv - lower) * scale).astype(np.int32)
|
| 151 |
+
xs = np.clip(xy[:, 0], 0, output_width - 1)
|
| 152 |
+
ys = np.clip(xy[:, 1], 0, output_height - 1)
|
| 153 |
+
flat_indices = ys * output_width + xs
|
| 154 |
+
pixel_count = output_width * output_height
|
| 155 |
+
counts = np.bincount(flat_indices, minlength=pixel_count)
|
| 156 |
+
sums = np.bincount(flat_indices, weights=values, minlength=pixel_count)
|
| 157 |
+
covered = counts > 0
|
| 158 |
+
if int(covered.sum()) < max(600, int(pixel_count * 0.1)):
|
| 159 |
+
return None
|
| 160 |
+
|
| 161 |
+
fill_value = int(np.median(values))
|
| 162 |
+
output = np.full(pixel_count, fill_value, dtype=np.uint8)
|
| 163 |
+
output[covered] = np.clip(sums[covered] / counts[covered], 0, 255).astype(np.uint8)
|
| 164 |
+
mask = (covered.reshape(output_height, output_width).astype(np.uint8) * 255)
|
| 165 |
+
return output.reshape(output_height, output_width), mask
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def rectify_from_transform(
|
| 169 |
+
image_rgb: np.ndarray,
|
| 170 |
+
surface_mask: np.ndarray,
|
| 171 |
+
transform: np.ndarray,
|
| 172 |
+
) -> tuple[np.ndarray, np.ndarray] | None:
|
| 173 |
+
ys, xs = np.where(surface_mask > 0)
|
| 174 |
+
if len(xs) < 800:
|
| 175 |
+
return None
|
| 176 |
+
stride = max(1, len(xs) // 30000)
|
| 177 |
+
source_points = np.column_stack((xs[::stride], ys[::stride])).astype(np.float32).reshape(1, -1, 2)
|
| 178 |
+
mapped = cv2.perspectiveTransform(source_points, transform)[0]
|
| 179 |
+
mapped = mapped[np.isfinite(mapped).all(axis=1)]
|
| 180 |
+
if len(mapped) < 500:
|
| 181 |
+
return None
|
| 182 |
+
|
| 183 |
+
lower = np.percentile(mapped, 0.5, axis=0)
|
| 184 |
+
upper = np.percentile(mapped, 99.5, axis=0)
|
| 185 |
+
span = upper - lower
|
| 186 |
+
if not np.isfinite(span).all() or float(np.min(span)) <= 1e-5:
|
| 187 |
+
return None
|
| 188 |
+
|
| 189 |
+
scale = choose_rectification_scale(span, len(mapped))
|
| 190 |
+
output_width = int(np.clip(round(float(span[0]) * scale) + 1, 96, 896))
|
| 191 |
+
output_height = int(np.clip(round(float(span[1]) * scale) + 1, 96, 896))
|
| 192 |
+
if output_width < 96 or output_height < 96:
|
| 193 |
+
return None
|
| 194 |
+
|
| 195 |
+
normalization = np.array([
|
| 196 |
+
[scale, 0.0, -float(lower[0]) * scale],
|
| 197 |
+
[0.0, scale, -float(lower[1]) * scale],
|
| 198 |
+
[0.0, 0.0, 1.0],
|
| 199 |
+
], dtype=np.float64)
|
| 200 |
+
warp = normalization @ transform
|
| 201 |
+
gray = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY)
|
| 202 |
+
rectified = cv2.warpPerspective(
|
| 203 |
+
gray,
|
| 204 |
+
warp,
|
| 205 |
+
(output_width, output_height),
|
| 206 |
+
flags=cv2.INTER_LINEAR,
|
| 207 |
+
borderMode=cv2.BORDER_REPLICATE,
|
| 208 |
+
)
|
| 209 |
+
rectified_mask = cv2.warpPerspective(
|
| 210 |
+
(surface_mask > 0).astype(np.uint8) * 255,
|
| 211 |
+
warp,
|
| 212 |
+
(output_width, output_height),
|
| 213 |
+
flags=cv2.INTER_NEAREST,
|
| 214 |
+
)
|
| 215 |
+
return rectified, rectified_mask
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def choose_rectification_scale(span: np.ndarray, sample_count: int) -> float:
|
| 219 |
+
aspect = float(span[0] / span[1])
|
| 220 |
+
target_long_side = int(np.clip(
|
| 221 |
+
round(math.sqrt(sample_count * max(aspect, 1.0 / aspect))),
|
| 222 |
+
320,
|
| 223 |
+
896,
|
| 224 |
+
))
|
| 225 |
+
return target_long_side / max(float(np.max(span)), 1e-6)
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def estimate_material_cue(gray: np.ndarray, mask: np.ndarray) -> DirectionCue | None:
|
| 229 |
+
valid = mask > 0
|
| 230 |
+
if int(valid.sum()) < 1000:
|
| 231 |
+
return None
|
| 232 |
+
|
| 233 |
+
kernel_size = max(3, int(round(min(gray.shape) * 0.012))) | 1
|
| 234 |
+
inner_mask = cv2.erode(mask, np.ones((kernel_size, kernel_size), dtype=np.uint8))
|
| 235 |
+
if int(np.count_nonzero(inner_mask)) < 800:
|
| 236 |
+
inner_mask = mask
|
| 237 |
+
valid = inner_mask > 0
|
| 238 |
+
|
| 239 |
+
fill_value = int(np.median(gray[valid]))
|
| 240 |
+
prepared = gray.copy()
|
| 241 |
+
prepared[~valid] = fill_value
|
| 242 |
+
prepared = cv2.createCLAHE(clipLimit=1.8, tileGridSize=(8, 8)).apply(prepared)
|
| 243 |
+
sigma = max(3.0, min(gray.shape) / 36.0)
|
| 244 |
+
illumination = cv2.GaussianBlur(prepared, (0, 0), sigmaX=sigma)
|
| 245 |
+
detail = prepared.astype(np.float32) - illumination.astype(np.float32)
|
| 246 |
+
gx = cv2.Sobel(detail, cv2.CV_32F, 1, 0, ksize=3)
|
| 247 |
+
gy = cv2.Sobel(detail, cv2.CV_32F, 0, 1, ksize=3)
|
| 248 |
+
magnitude = np.hypot(gx, gy)
|
| 249 |
+
gradient_values = magnitude[valid]
|
| 250 |
+
if gradient_values.size < 800 or float(np.percentile(gradient_values, 90)) < 2.0:
|
| 251 |
+
return None
|
| 252 |
+
threshold = float(np.percentile(gradient_values, 68))
|
| 253 |
+
|
| 254 |
+
block_angles = []
|
| 255 |
+
block_weights = []
|
| 256 |
+
block_regions = []
|
| 257 |
+
rows, columns = 4, 4
|
| 258 |
+
height, width = gray.shape[:2]
|
| 259 |
+
for row in range(rows):
|
| 260 |
+
y0, y1 = row * height // rows, (row + 1) * height // rows
|
| 261 |
+
for column in range(columns):
|
| 262 |
+
x0, x1 = column * width // columns, (column + 1) * width // columns
|
| 263 |
+
block_valid = valid[y0:y1, x0:x1]
|
| 264 |
+
selected = block_valid & (magnitude[y0:y1, x0:x1] >= threshold)
|
| 265 |
+
if int(selected.sum()) < 45:
|
| 266 |
+
continue
|
| 267 |
+
angles = (
|
| 268 |
+
np.degrees(np.arctan2(
|
| 269 |
+
gy[y0:y1, x0:x1][selected],
|
| 270 |
+
gx[y0:y1, x0:x1][selected],
|
| 271 |
+
))
|
| 272 |
+
+ 90.0
|
| 273 |
+
) % 180.0
|
| 274 |
+
weights = magnitude[y0:y1, x0:x1][selected].astype(np.float64)
|
| 275 |
+
angle, concentration = periodic_mean(angles, weights, period=180.0)
|
| 276 |
+
if concentration < 0.22:
|
| 277 |
+
continue
|
| 278 |
+
block_angles.append(angle)
|
| 279 |
+
block_weights.append(float(weights.sum()) * concentration)
|
| 280 |
+
block_regions.append(row * columns + column)
|
| 281 |
+
|
| 282 |
+
tensor_cue = cue_from_region_angles(
|
| 283 |
+
source="rectified-structure-tensor",
|
| 284 |
+
angles=block_angles,
|
| 285 |
+
weights=block_weights,
|
| 286 |
+
regions=block_regions,
|
| 287 |
+
period=180.0,
|
| 288 |
+
minimum_regions=3,
|
| 289 |
+
)
|
| 290 |
+
line_cue = estimate_rectified_line_cue(gray, mask)
|
| 291 |
+
if line_cue is None:
|
| 292 |
+
line_cue = estimate_rectified_line_cue(prepared, mask)
|
| 293 |
+
return fuse_material_cues(tensor_cue, line_cue)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def estimate_rectified_line_cue(gray: np.ndarray, mask: np.ndarray) -> DirectionCue | None:
|
| 297 |
+
detector = cv2.createLineSegmentDetector(cv2.LSD_REFINE_STD)
|
| 298 |
+
detected = detector.detect(gray)[0]
|
| 299 |
+
if detected is None:
|
| 300 |
+
return None
|
| 301 |
+
|
| 302 |
+
height, width = gray.shape[:2]
|
| 303 |
+
min_length = max(18.0, min(height, width) * 0.055)
|
| 304 |
+
angles = []
|
| 305 |
+
weights = []
|
| 306 |
+
regions = []
|
| 307 |
+
for raw_line in detected.reshape(-1, 4):
|
| 308 |
+
x1, y1, x2, y2 = [float(value) for value in raw_line]
|
| 309 |
+
dx, dy = x2 - x1, y2 - y1
|
| 310 |
+
length = math.hypot(dx, dy)
|
| 311 |
+
if length < min_length:
|
| 312 |
+
continue
|
| 313 |
+
sample_x = np.clip(np.rint(np.linspace(x1, x2, 9)).astype(np.int32), 0, width - 1)
|
| 314 |
+
sample_y = np.clip(np.rint(np.linspace(y1, y2, 9)).astype(np.int32), 0, height - 1)
|
| 315 |
+
mask_support = float(np.mean(mask[sample_y, sample_x] > 0))
|
| 316 |
+
if mask_support < 0.78:
|
| 317 |
+
continue
|
| 318 |
+
midpoint_x = (x1 + x2) * 0.5
|
| 319 |
+
midpoint_y = (y1 + y2) * 0.5
|
| 320 |
+
angles.append(normalize_angle(math.degrees(math.atan2(dy, dx))))
|
| 321 |
+
weights.append(length * mask_support)
|
| 322 |
+
regions.append(
|
| 323 |
+
min(3, int(midpoint_y * 4 / max(height, 1))) * 4
|
| 324 |
+
+ min(3, int(midpoint_x * 4 / max(width, 1)))
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
return cue_from_region_angles(
|
| 328 |
+
source="rectified-repeated-lines",
|
| 329 |
+
angles=angles,
|
| 330 |
+
weights=weights,
|
| 331 |
+
regions=regions,
|
| 332 |
+
period=180.0,
|
| 333 |
+
minimum_regions=3,
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def cue_from_region_angles(
|
| 338 |
+
*,
|
| 339 |
+
source: str,
|
| 340 |
+
angles: list[float],
|
| 341 |
+
weights: list[float],
|
| 342 |
+
regions: list[int],
|
| 343 |
+
period: float,
|
| 344 |
+
minimum_regions: int,
|
| 345 |
+
) -> DirectionCue | None:
|
| 346 |
+
if len(angles) < 4:
|
| 347 |
+
return None
|
| 348 |
+
angle_array = np.asarray(angles, dtype=np.float64)
|
| 349 |
+
weight_array = np.asarray(weights, dtype=np.float64)
|
| 350 |
+
angle, concentration = periodic_mean(angle_array, weight_array, period=period)
|
| 351 |
+
tolerance = 12.0 if period == 180.0 else 9.0
|
| 352 |
+
agreement = np.array(
|
| 353 |
+
[angular_distance(float(value), angle, period) <= tolerance for value in angle_array],
|
| 354 |
+
dtype=bool,
|
| 355 |
+
)
|
| 356 |
+
if int(agreement.sum()) < 4:
|
| 357 |
+
return None
|
| 358 |
+
agreeing_regions = {region for region, keep in zip(regions, agreement, strict=False) if keep}
|
| 359 |
+
if len(agreeing_regions) < minimum_regions:
|
| 360 |
+
return None
|
| 361 |
+
|
| 362 |
+
agreement_ratio = float(weight_array[agreement].sum() / max(float(weight_array.sum()), 1e-6))
|
| 363 |
+
region_score = min(1.0, len(agreeing_regions) / 7.0)
|
| 364 |
+
support_score = min(1.0, int(agreement.sum()) / 12.0)
|
| 365 |
+
confidence = float(np.clip(
|
| 366 |
+
0.38 * concentration
|
| 367 |
+
+ 0.28 * agreement_ratio
|
| 368 |
+
+ 0.20 * region_score
|
| 369 |
+
+ 0.14 * support_score,
|
| 370 |
+
0.0,
|
| 371 |
+
1.0,
|
| 372 |
+
))
|
| 373 |
+
if confidence < 0.48:
|
| 374 |
+
return None
|
| 375 |
+
return DirectionCue(
|
| 376 |
+
source=source,
|
| 377 |
+
angle_degrees=round(angle, 3),
|
| 378 |
+
confidence=round(confidence, 3),
|
| 379 |
+
support=int(agreement.sum()),
|
| 380 |
+
region_support=len(agreeing_regions),
|
| 381 |
+
ambiguity_degrees=None,
|
| 382 |
+
details={
|
| 383 |
+
"concentration": round(concentration, 4),
|
| 384 |
+
"agreementRatio": round(agreement_ratio, 4),
|
| 385 |
+
},
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def fuse_material_cues(
|
| 390 |
+
tensor_cue: DirectionCue | None,
|
| 391 |
+
line_cue: DirectionCue | None,
|
| 392 |
+
) -> DirectionCue | None:
|
| 393 |
+
if tensor_cue is None:
|
| 394 |
+
return line_cue
|
| 395 |
+
if line_cue is None:
|
| 396 |
+
return tensor_cue
|
| 397 |
+
difference = angular_distance(tensor_cue.angle_degrees, line_cue.angle_degrees)
|
| 398 |
+
if difference > 15.0:
|
| 399 |
+
stronger = max((tensor_cue, line_cue), key=lambda cue: cue.confidence)
|
| 400 |
+
return DirectionCue(
|
| 401 |
+
source=stronger.source,
|
| 402 |
+
angle_degrees=stronger.angle_degrees,
|
| 403 |
+
confidence=round(stronger.confidence * 0.72, 3),
|
| 404 |
+
support=stronger.support,
|
| 405 |
+
region_support=stronger.region_support,
|
| 406 |
+
ambiguity_degrees=None,
|
| 407 |
+
details={**stronger.details, "cueDisagreementDegrees": round(difference, 3)},
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
angles = np.array([tensor_cue.angle_degrees, line_cue.angle_degrees])
|
| 411 |
+
weights = np.array([tensor_cue.confidence, line_cue.confidence])
|
| 412 |
+
angle, concentration = periodic_mean(angles, weights, period=180.0)
|
| 413 |
+
confidence = float(np.clip(
|
| 414 |
+
max(tensor_cue.confidence, line_cue.confidence) * 0.72
|
| 415 |
+
+ min(tensor_cue.confidence, line_cue.confidence) * 0.28
|
| 416 |
+
+ concentration * 0.08,
|
| 417 |
+
0.0,
|
| 418 |
+
1.0,
|
| 419 |
+
))
|
| 420 |
+
return DirectionCue(
|
| 421 |
+
source="rectified-material-consensus",
|
| 422 |
+
angle_degrees=round(angle, 3),
|
| 423 |
+
confidence=round(confidence, 3),
|
| 424 |
+
support=tensor_cue.support + line_cue.support,
|
| 425 |
+
region_support=max(tensor_cue.region_support, line_cue.region_support),
|
| 426 |
+
ambiguity_degrees=None,
|
| 427 |
+
details={
|
| 428 |
+
"tensorAngleDegrees": tensor_cue.angle_degrees,
|
| 429 |
+
"lineAngleDegrees": line_cue.angle_degrees,
|
| 430 |
+
"cueAgreementDegrees": round(difference, 3),
|
| 431 |
+
},
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def normalize_vector(vector: np.ndarray) -> np.ndarray | None:
|
| 436 |
+
vector = np.asarray(vector, dtype=np.float64)
|
| 437 |
+
length = float(np.linalg.norm(vector))
|
| 438 |
+
if not np.isfinite(vector).all() or length <= 1e-7:
|
| 439 |
+
return None
|
| 440 |
+
return vector / length
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def normalize_transform(value: list[float] | np.ndarray | None) -> np.ndarray | None:
|
| 444 |
+
if value is None:
|
| 445 |
+
return None
|
| 446 |
+
transform = np.asarray(value, dtype=np.float64)
|
| 447 |
+
if transform.size != 9:
|
| 448 |
+
return None
|
| 449 |
+
transform = transform.reshape(3, 3)
|
| 450 |
+
if not np.isfinite(transform).all() or abs(float(np.linalg.det(transform))) < 1e-12:
|
| 451 |
+
return None
|
| 452 |
+
return transform
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
def world_direction_to_render_angle(
|
| 456 |
+
direction: np.ndarray,
|
| 457 |
+
*,
|
| 458 |
+
render_u_axis: np.ndarray | None,
|
| 459 |
+
render_v_axis: np.ndarray | None,
|
| 460 |
+
intrinsics: np.ndarray | None,
|
| 461 |
+
render_transform: np.ndarray | None,
|
| 462 |
+
) -> float | None:
|
| 463 |
+
direction = normalize_vector(direction)
|
| 464 |
+
if direction is None:
|
| 465 |
+
return None
|
| 466 |
+
if render_u_axis is not None and render_v_axis is not None:
|
| 467 |
+
u_axis = normalize_vector(render_u_axis)
|
| 468 |
+
v_axis = normalize_vector(render_v_axis)
|
| 469 |
+
if u_axis is not None and v_axis is not None:
|
| 470 |
+
return normalize_angle(math.degrees(math.atan2(
|
| 471 |
+
float(direction @ v_axis),
|
| 472 |
+
float(direction @ u_axis),
|
| 473 |
+
)))
|
| 474 |
+
|
| 475 |
+
if intrinsics is None or render_transform is None:
|
| 476 |
+
return None
|
| 477 |
+
intrinsics = np.asarray(intrinsics, dtype=np.float64).reshape(3, 3)
|
| 478 |
+
vanishing_point = intrinsics @ direction
|
| 479 |
+
mapped = render_transform @ vanishing_point
|
| 480 |
+
if not np.isfinite(mapped).all() or float(np.linalg.norm(mapped[:2])) <= 1e-7:
|
| 481 |
+
return None
|
| 482 |
+
return normalize_angle(math.degrees(math.atan2(float(mapped[1]), float(mapped[0]))))
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def choose_depth_axis(
|
| 486 |
+
base_angle_degrees: float,
|
| 487 |
+
*,
|
| 488 |
+
floor_normal: np.ndarray,
|
| 489 |
+
render_u_axis: np.ndarray | None,
|
| 490 |
+
render_v_axis: np.ndarray | None,
|
| 491 |
+
intrinsics: np.ndarray | None,
|
| 492 |
+
render_transform: np.ndarray | None,
|
| 493 |
+
) -> float:
|
| 494 |
+
camera_forward = np.array([0.0, 0.0, 1.0], dtype=np.float64)
|
| 495 |
+
floor_normal = normalize_vector(floor_normal)
|
| 496 |
+
if floor_normal is None:
|
| 497 |
+
return normalize_angle(base_angle_degrees)
|
| 498 |
+
projected_forward = camera_forward - floor_normal * float(camera_forward @ floor_normal)
|
| 499 |
+
forward_angle = world_direction_to_render_angle(
|
| 500 |
+
projected_forward,
|
| 501 |
+
render_u_axis=render_u_axis,
|
| 502 |
+
render_v_axis=render_v_axis,
|
| 503 |
+
intrinsics=intrinsics,
|
| 504 |
+
render_transform=render_transform,
|
| 505 |
+
)
|
| 506 |
+
first = normalize_angle(base_angle_degrees)
|
| 507 |
+
second = normalize_angle(base_angle_degrees + 90.0)
|
| 508 |
+
if forward_angle is None:
|
| 509 |
+
return first
|
| 510 |
+
return first if angular_distance(first, forward_angle) <= angular_distance(second, forward_angle) else second
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
def estimate_wall_normal_cue(
|
| 514 |
+
normals_map: np.ndarray | None,
|
| 515 |
+
valid_mask: np.ndarray | None,
|
| 516 |
+
wall_mask: np.ndarray,
|
| 517 |
+
*,
|
| 518 |
+
floor_normal: np.ndarray,
|
| 519 |
+
render_u_axis: np.ndarray | None,
|
| 520 |
+
render_v_axis: np.ndarray | None,
|
| 521 |
+
intrinsics: np.ndarray | None,
|
| 522 |
+
render_transform: np.ndarray | None,
|
| 523 |
+
) -> DirectionCue | None:
|
| 524 |
+
if normals_map is None or normals_map.shape[:2] != wall_mask.shape:
|
| 525 |
+
return None
|
| 526 |
+
floor_normal = normalize_vector(floor_normal)
|
| 527 |
+
if floor_normal is None:
|
| 528 |
+
return None
|
| 529 |
+
|
| 530 |
+
lengths = np.linalg.norm(normals_map, axis=2)
|
| 531 |
+
valid = (wall_mask > 0) & np.isfinite(normals_map).all(axis=2) & (lengths > 1e-4)
|
| 532 |
+
if valid_mask is not None and valid_mask.shape == wall_mask.shape:
|
| 533 |
+
valid &= valid_mask.astype(bool)
|
| 534 |
+
normalized = np.zeros_like(normals_map, dtype=np.float64)
|
| 535 |
+
normalized[valid] = normals_map[valid] / lengths[valid, None]
|
| 536 |
+
vertical_alignment = np.abs(normalized @ floor_normal)
|
| 537 |
+
valid &= vertical_alignment <= 0.42
|
| 538 |
+
ys, xs = np.where(valid)
|
| 539 |
+
if len(xs) < 250:
|
| 540 |
+
return None
|
| 541 |
+
|
| 542 |
+
stride = max(1, len(xs) // 6000)
|
| 543 |
+
ys, xs = ys[::stride], xs[::stride]
|
| 544 |
+
normals = normalized[ys, xs]
|
| 545 |
+
horizontal = normals - (normals @ floor_normal)[:, None] * floor_normal
|
| 546 |
+
horizontal_lengths = np.linalg.norm(horizontal, axis=1)
|
| 547 |
+
keep = horizontal_lengths > 0.6
|
| 548 |
+
horizontal = horizontal[keep] / horizontal_lengths[keep, None]
|
| 549 |
+
ys, xs = ys[keep], xs[keep]
|
| 550 |
+
if len(horizontal) < 200:
|
| 551 |
+
return None
|
| 552 |
+
|
| 553 |
+
angles = []
|
| 554 |
+
weights = []
|
| 555 |
+
regions = []
|
| 556 |
+
height, width = wall_mask.shape
|
| 557 |
+
for direction, y, x in zip(horizontal, ys, xs, strict=False):
|
| 558 |
+
angle = world_direction_to_render_angle(
|
| 559 |
+
direction,
|
| 560 |
+
render_u_axis=render_u_axis,
|
| 561 |
+
render_v_axis=render_v_axis,
|
| 562 |
+
intrinsics=intrinsics,
|
| 563 |
+
render_transform=render_transform,
|
| 564 |
+
)
|
| 565 |
+
if angle is None:
|
| 566 |
+
continue
|
| 567 |
+
angles.append(angle % 90.0)
|
| 568 |
+
weights.append(1.0)
|
| 569 |
+
regions.append(min(3, int(y * 4 / max(height, 1))) * 4 + min(3, int(x * 4 / max(width, 1))))
|
| 570 |
+
if len(angles) < 200:
|
| 571 |
+
return None
|
| 572 |
+
|
| 573 |
+
base_angle, concentration = periodic_mean(
|
| 574 |
+
np.asarray(angles),
|
| 575 |
+
np.asarray(weights),
|
| 576 |
+
period=90.0,
|
| 577 |
+
)
|
| 578 |
+
agreement = np.array(
|
| 579 |
+
[angular_distance(angle, base_angle, 90.0) <= 10.0 for angle in angles],
|
| 580 |
+
dtype=bool,
|
| 581 |
+
)
|
| 582 |
+
agreeing_regions = {region for region, accepted in zip(regions, agreement, strict=False) if accepted}
|
| 583 |
+
if int(agreement.sum()) < 160 or len(agreeing_regions) < 2:
|
| 584 |
+
return None
|
| 585 |
+
agreement_ratio = float(agreement.mean())
|
| 586 |
+
confidence = float(np.clip(
|
| 587 |
+
0.46 * concentration
|
| 588 |
+
+ 0.30 * agreement_ratio
|
| 589 |
+
+ 0.14 * min(1.0, len(agreeing_regions) / 6.0)
|
| 590 |
+
+ 0.10 * min(1.0, int(agreement.sum()) / 1200.0),
|
| 591 |
+
0.0,
|
| 592 |
+
1.0,
|
| 593 |
+
))
|
| 594 |
+
angle = choose_depth_axis(
|
| 595 |
+
base_angle,
|
| 596 |
+
floor_normal=floor_normal,
|
| 597 |
+
render_u_axis=render_u_axis,
|
| 598 |
+
render_v_axis=render_v_axis,
|
| 599 |
+
intrinsics=intrinsics,
|
| 600 |
+
render_transform=render_transform,
|
| 601 |
+
)
|
| 602 |
+
return DirectionCue(
|
| 603 |
+
source="wall-normal-manhattan",
|
| 604 |
+
angle_degrees=round(angle, 3),
|
| 605 |
+
confidence=round(confidence, 3),
|
| 606 |
+
support=int(agreement.sum()),
|
| 607 |
+
region_support=len(agreeing_regions),
|
| 608 |
+
ambiguity_degrees=90.0,
|
| 609 |
+
details={
|
| 610 |
+
"baseAxisDegrees": round(base_angle, 3),
|
| 611 |
+
"concentration": round(concentration, 4),
|
| 612 |
+
"agreementRatio": round(agreement_ratio, 4),
|
| 613 |
+
},
|
| 614 |
+
)
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
def estimate_architectural_line_cue(
|
| 618 |
+
image_rgb: np.ndarray,
|
| 619 |
+
structure_mask: np.ndarray,
|
| 620 |
+
*,
|
| 621 |
+
floor_normal: np.ndarray,
|
| 622 |
+
render_u_axis: np.ndarray | None,
|
| 623 |
+
render_v_axis: np.ndarray | None,
|
| 624 |
+
intrinsics: np.ndarray | None,
|
| 625 |
+
render_transform: np.ndarray | None,
|
| 626 |
+
) -> DirectionCue | None:
|
| 627 |
+
if intrinsics is None:
|
| 628 |
+
return None
|
| 629 |
+
floor_normal = normalize_vector(floor_normal)
|
| 630 |
+
if floor_normal is None:
|
| 631 |
+
return None
|
| 632 |
+
intrinsics = np.asarray(intrinsics, dtype=np.float64).reshape(3, 3)
|
| 633 |
+
|
| 634 |
+
gray = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY)
|
| 635 |
+
detector = cv2.createLineSegmentDetector(cv2.LSD_REFINE_STD)
|
| 636 |
+
detected = detector.detect(gray)[0]
|
| 637 |
+
if detected is None:
|
| 638 |
+
return None
|
| 639 |
+
|
| 640 |
+
height, width = gray.shape
|
| 641 |
+
minimum_length = max(30.0, min(height, width) * 0.07)
|
| 642 |
+
vertical_vanishing = intrinsics @ floor_normal
|
| 643 |
+
finite_vertical = abs(float(vertical_vanishing[2])) > 1e-7
|
| 644 |
+
vertical_xy = (
|
| 645 |
+
vertical_vanishing[:2] / vertical_vanishing[2]
|
| 646 |
+
if finite_vertical
|
| 647 |
+
else vertical_vanishing[:2]
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
angles = []
|
| 651 |
+
weights = []
|
| 652 |
+
regions = []
|
| 653 |
+
for raw_line in detected.reshape(-1, 4):
|
| 654 |
+
x1, y1, x2, y2 = [float(value) for value in raw_line]
|
| 655 |
+
line_vector = np.array([x2 - x1, y2 - y1], dtype=np.float64)
|
| 656 |
+
length = float(np.linalg.norm(line_vector))
|
| 657 |
+
if length < minimum_length:
|
| 658 |
+
continue
|
| 659 |
+
line_unit = line_vector / length
|
| 660 |
+
sample_x = np.clip(np.rint(np.linspace(x1, x2, 11)).astype(np.int32), 0, width - 1)
|
| 661 |
+
sample_y = np.clip(np.rint(np.linspace(y1, y2, 11)).astype(np.int32), 0, height - 1)
|
| 662 |
+
structure_support = float(np.mean(structure_mask[sample_y, sample_x] > 0))
|
| 663 |
+
if structure_support < 0.58:
|
| 664 |
+
continue
|
| 665 |
+
|
| 666 |
+
midpoint = np.array([(x1 + x2) * 0.5, (y1 + y2) * 0.5], dtype=np.float64)
|
| 667 |
+
vertical_direction = vertical_xy - midpoint if finite_vertical else vertical_xy
|
| 668 |
+
vertical_length = float(np.linalg.norm(vertical_direction))
|
| 669 |
+
if vertical_length > 1e-6:
|
| 670 |
+
vertical_direction /= vertical_length
|
| 671 |
+
if abs(float(line_unit @ vertical_direction)) >= math.cos(math.radians(14.0)):
|
| 672 |
+
continue
|
| 673 |
+
|
| 674 |
+
p1 = np.array([x1, y1, 1.0], dtype=np.float64)
|
| 675 |
+
p2 = np.array([x2, y2, 1.0], dtype=np.float64)
|
| 676 |
+
image_line = np.cross(p1, p2)
|
| 677 |
+
interpretation_plane = intrinsics.T @ image_line
|
| 678 |
+
world_direction = np.cross(interpretation_plane, floor_normal)
|
| 679 |
+
angle = world_direction_to_render_angle(
|
| 680 |
+
world_direction,
|
| 681 |
+
render_u_axis=render_u_axis,
|
| 682 |
+
render_v_axis=render_v_axis,
|
| 683 |
+
intrinsics=intrinsics,
|
| 684 |
+
render_transform=render_transform,
|
| 685 |
+
)
|
| 686 |
+
if angle is None:
|
| 687 |
+
continue
|
| 688 |
+
angles.append(angle % 90.0)
|
| 689 |
+
weights.append(length * structure_support)
|
| 690 |
+
regions.append(
|
| 691 |
+
min(3, int(midpoint[1] * 4 / max(height, 1))) * 4
|
| 692 |
+
+ min(3, int(midpoint[0] * 4 / max(width, 1)))
|
| 693 |
+
)
|
| 694 |
+
|
| 695 |
+
base_cue = cue_from_region_angles(
|
| 696 |
+
source="architectural-manhattan",
|
| 697 |
+
angles=angles,
|
| 698 |
+
weights=weights,
|
| 699 |
+
regions=regions,
|
| 700 |
+
period=90.0,
|
| 701 |
+
minimum_regions=3,
|
| 702 |
+
)
|
| 703 |
+
if base_cue is None:
|
| 704 |
+
return None
|
| 705 |
+
angle = choose_depth_axis(
|
| 706 |
+
base_cue.angle_degrees,
|
| 707 |
+
floor_normal=floor_normal,
|
| 708 |
+
render_u_axis=render_u_axis,
|
| 709 |
+
render_v_axis=render_v_axis,
|
| 710 |
+
intrinsics=intrinsics,
|
| 711 |
+
render_transform=render_transform,
|
| 712 |
+
)
|
| 713 |
+
return DirectionCue(
|
| 714 |
+
source=base_cue.source,
|
| 715 |
+
angle_degrees=round(angle, 3),
|
| 716 |
+
confidence=base_cue.confidence,
|
| 717 |
+
support=base_cue.support,
|
| 718 |
+
region_support=base_cue.region_support,
|
| 719 |
+
ambiguity_degrees=90.0,
|
| 720 |
+
details={**base_cue.details, "baseAxisDegrees": base_cue.angle_degrees},
|
| 721 |
+
)
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
def fuse_structural_cues(cues: list[DirectionCue]) -> DirectionCue | None:
|
| 725 |
+
cues = [cue for cue in cues if cue is not None and cue.confidence >= 0.42]
|
| 726 |
+
if not cues:
|
| 727 |
+
return None
|
| 728 |
+
if len(cues) == 1:
|
| 729 |
+
return cues[0]
|
| 730 |
+
|
| 731 |
+
base_angles = np.array([cue.angle_degrees % 90.0 for cue in cues])
|
| 732 |
+
weights = np.array([cue.confidence for cue in cues])
|
| 733 |
+
angle, concentration = periodic_mean(base_angles, weights, period=90.0)
|
| 734 |
+
disagreement = max(
|
| 735 |
+
angular_distance(float(value), angle, 90.0)
|
| 736 |
+
for value in base_angles
|
| 737 |
+
)
|
| 738 |
+
if disagreement > 14.0:
|
| 739 |
+
strongest = max(cues, key=lambda cue: cue.confidence)
|
| 740 |
+
return DirectionCue(
|
| 741 |
+
source=strongest.source,
|
| 742 |
+
angle_degrees=strongest.angle_degrees,
|
| 743 |
+
confidence=round(strongest.confidence * 0.72, 3),
|
| 744 |
+
support=strongest.support,
|
| 745 |
+
region_support=strongest.region_support,
|
| 746 |
+
ambiguity_degrees=90.0,
|
| 747 |
+
details={**strongest.details, "structuralCueDisagreementDegrees": round(disagreement, 3)},
|
| 748 |
+
)
|
| 749 |
+
|
| 750 |
+
strongest = max(cues, key=lambda cue: cue.confidence)
|
| 751 |
+
representative = strongest.angle_degrees
|
| 752 |
+
if angular_distance(representative, angle) > angular_distance(representative + 90.0, angle):
|
| 753 |
+
representative += 90.0
|
| 754 |
+
confidence = float(np.clip(
|
| 755 |
+
np.average([cue.confidence for cue in cues], weights=weights)
|
| 756 |
+
+ concentration * 0.12,
|
| 757 |
+
0.0,
|
| 758 |
+
1.0,
|
| 759 |
+
))
|
| 760 |
+
return DirectionCue(
|
| 761 |
+
source="room-manhattan-consensus",
|
| 762 |
+
angle_degrees=round(normalize_angle(representative), 3),
|
| 763 |
+
confidence=round(confidence, 3),
|
| 764 |
+
support=sum(cue.support for cue in cues),
|
| 765 |
+
region_support=max(cue.region_support for cue in cues),
|
| 766 |
+
ambiguity_degrees=90.0,
|
| 767 |
+
details={
|
| 768 |
+
"cueSources": [cue.source for cue in cues],
|
| 769 |
+
"baseAxisDegrees": round(angle, 3),
|
| 770 |
+
"concentration": round(concentration, 4),
|
| 771 |
+
"cueDisagreementDegrees": round(disagreement, 3),
|
| 772 |
+
},
|
| 773 |
+
)
|
| 774 |
+
|
| 775 |
+
|
| 776 |
+
def select_direction(
|
| 777 |
+
material_cue: DirectionCue | None,
|
| 778 |
+
structural_cue: DirectionCue | None,
|
| 779 |
+
) -> tuple[DirectionCue | None, str]:
|
| 780 |
+
if material_cue is not None and material_cue.confidence >= 0.82:
|
| 781 |
+
if structural_cue is None:
|
| 782 |
+
return material_cue, "strong-material-direction"
|
| 783 |
+
axis_difference = min(
|
| 784 |
+
angular_distance(material_cue.angle_degrees, structural_cue.angle_degrees),
|
| 785 |
+
angular_distance(material_cue.angle_degrees, structural_cue.angle_degrees + 90.0),
|
| 786 |
+
)
|
| 787 |
+
if axis_difference <= 14.0:
|
| 788 |
+
boosted = DirectionCue(
|
| 789 |
+
source="material-room-consensus",
|
| 790 |
+
angle_degrees=material_cue.angle_degrees,
|
| 791 |
+
confidence=round(min(1.0, material_cue.confidence * 0.78 + structural_cue.confidence * 0.30), 3),
|
| 792 |
+
support=material_cue.support + structural_cue.support,
|
| 793 |
+
region_support=max(material_cue.region_support, structural_cue.region_support),
|
| 794 |
+
ambiguity_degrees=None,
|
| 795 |
+
details={
|
| 796 |
+
"materialSource": material_cue.source,
|
| 797 |
+
"structuralSource": structural_cue.source,
|
| 798 |
+
"axisDifferenceDegrees": round(axis_difference, 3),
|
| 799 |
+
},
|
| 800 |
+
)
|
| 801 |
+
return boosted, "material-and-room-agree"
|
| 802 |
+
return material_cue, "strong-diagonal-material-direction"
|
| 803 |
+
|
| 804 |
+
if structural_cue is not None and structural_cue.confidence >= 0.52:
|
| 805 |
+
return structural_cue, "room-structure-direction"
|
| 806 |
+
if material_cue is not None and material_cue.confidence >= 0.62:
|
| 807 |
+
return material_cue, "moderate-material-direction"
|
| 808 |
+
return None, "insufficient-observable-direction-evidence"
|
| 809 |
+
|
| 810 |
+
|
| 811 |
+
def direction_label(angle_degrees: float) -> str:
|
| 812 |
+
angle = normalize_angle(angle_degrees)
|
| 813 |
+
if angle < 12.0 or angle >= 168.0:
|
| 814 |
+
return "across_render_u"
|
| 815 |
+
if 78.0 <= angle < 102.0:
|
| 816 |
+
return "along_render_v"
|
| 817 |
+
return "diagonal"
|
| 818 |
+
|
| 819 |
+
|
| 820 |
+
def direction_axis_for_overlay(
|
| 821 |
+
*,
|
| 822 |
+
angle_degrees: float,
|
| 823 |
+
image_shape: tuple[int, int],
|
| 824 |
+
surface_mask: np.ndarray,
|
| 825 |
+
surface_uv: np.ndarray | None,
|
| 826 |
+
surface_indices: np.ndarray | None,
|
| 827 |
+
surface_plane_ids: np.ndarray | None,
|
| 828 |
+
render_transform: np.ndarray | None,
|
| 829 |
+
) -> dict | None:
|
| 830 |
+
height, width = image_shape
|
| 831 |
+
direction = np.array([
|
| 832 |
+
math.cos(math.radians(angle_degrees)),
|
| 833 |
+
math.sin(math.radians(angle_degrees)),
|
| 834 |
+
])
|
| 835 |
+
if surface_uv is not None and surface_indices is not None and len(surface_uv) == len(surface_indices):
|
| 836 |
+
valid = np.isfinite(surface_uv).all(axis=1)
|
| 837 |
+
if surface_plane_ids is not None and len(surface_plane_ids) == len(surface_uv):
|
| 838 |
+
plane_values = surface_plane_ids[valid & (surface_plane_ids != 255)]
|
| 839 |
+
if plane_values.size:
|
| 840 |
+
dominant_plane = int(np.bincount(plane_values.astype(np.int64)).argmax())
|
| 841 |
+
valid &= surface_plane_ids == dominant_plane
|
| 842 |
+
uv = surface_uv[valid]
|
| 843 |
+
indices = np.asarray(surface_indices)[valid]
|
| 844 |
+
if len(uv) >= 100:
|
| 845 |
+
center = np.median(uv, axis=0)
|
| 846 |
+
span = np.percentile(uv, 95, axis=0) - np.percentile(uv, 5, axis=0)
|
| 847 |
+
radius = max(float(np.min(span)) * 0.28, 1e-3)
|
| 848 |
+
endpoints = [center - direction * radius, center + direction * radius]
|
| 849 |
+
image_points = []
|
| 850 |
+
for endpoint in endpoints:
|
| 851 |
+
nearest = int(np.argmin(np.sum((uv - endpoint) ** 2, axis=1)))
|
| 852 |
+
pixel_index = int(indices[nearest])
|
| 853 |
+
image_points.append((float(pixel_index % width), float(pixel_index // width)))
|
| 854 |
+
return {
|
| 855 |
+
"startX": image_points[0][0],
|
| 856 |
+
"startY": image_points[0][1],
|
| 857 |
+
"endX": image_points[1][0],
|
| 858 |
+
"endY": image_points[1][1],
|
| 859 |
+
"source": "surface-uv",
|
| 860 |
+
}
|
| 861 |
+
|
| 862 |
+
if render_transform is None:
|
| 863 |
+
return None
|
| 864 |
+
ys, xs = np.where(surface_mask > 0)
|
| 865 |
+
if len(xs) < 50:
|
| 866 |
+
return None
|
| 867 |
+
sample_points = np.column_stack((xs, ys)).astype(np.float32).reshape(1, -1, 2)
|
| 868 |
+
mapped = cv2.perspectiveTransform(sample_points, render_transform.astype(np.float32))[0]
|
| 869 |
+
finite = np.isfinite(mapped).all(axis=1)
|
| 870 |
+
mapped = mapped[finite]
|
| 871 |
+
if len(mapped) < 50:
|
| 872 |
+
return None
|
| 873 |
+
center = np.median(mapped, axis=0)
|
| 874 |
+
span = np.percentile(mapped, 95, axis=0) - np.percentile(mapped, 5, axis=0)
|
| 875 |
+
radius = max(float(np.min(span)) * 0.28, 1e-3)
|
| 876 |
+
floor_points = np.array(
|
| 877 |
+
[[center - direction * radius, center + direction * radius]],
|
| 878 |
+
dtype=np.float32,
|
| 879 |
+
)
|
| 880 |
+
inverse = np.linalg.inv(render_transform).astype(np.float32)
|
| 881 |
+
image_points = cv2.perspectiveTransform(floor_points, inverse)[0]
|
| 882 |
+
if not np.isfinite(image_points).all():
|
| 883 |
+
return None
|
| 884 |
+
return {
|
| 885 |
+
"startX": float(image_points[0, 0]),
|
| 886 |
+
"startY": float(image_points[0, 1]),
|
| 887 |
+
"endX": float(image_points[1, 0]),
|
| 888 |
+
"endY": float(image_points[1, 1]),
|
| 889 |
+
"source": "floor-transform",
|
| 890 |
+
}
|
| 891 |
+
|
| 892 |
+
|
| 893 |
+
def find_floor_direction(
|
| 894 |
+
image_rgb: np.ndarray,
|
| 895 |
+
surface_mask: np.ndarray,
|
| 896 |
+
*,
|
| 897 |
+
wall_mask: np.ndarray,
|
| 898 |
+
structure_mask: np.ndarray,
|
| 899 |
+
normals_map: np.ndarray | None,
|
| 900 |
+
geometry_valid_mask: np.ndarray | None,
|
| 901 |
+
intrinsics: np.ndarray | list[float] | None,
|
| 902 |
+
floor_normal: np.ndarray | list[float] | None,
|
| 903 |
+
render_u_axis: np.ndarray | list[float] | None,
|
| 904 |
+
render_v_axis: np.ndarray | list[float] | None,
|
| 905 |
+
render_transform: np.ndarray | list[float] | None,
|
| 906 |
+
surface_uv: np.ndarray | None,
|
| 907 |
+
surface_indices: np.ndarray | None,
|
| 908 |
+
surface_plane_ids: np.ndarray | None,
|
| 909 |
+
) -> dict:
|
| 910 |
+
height, width = surface_mask.shape[:2]
|
| 911 |
+
transform = normalize_transform(render_transform)
|
| 912 |
+
camera_matrix = None
|
| 913 |
+
if intrinsics is not None:
|
| 914 |
+
raw_intrinsics = np.asarray(intrinsics, dtype=np.float64)
|
| 915 |
+
if raw_intrinsics.size == 9 and np.isfinite(raw_intrinsics).all():
|
| 916 |
+
camera_matrix = raw_intrinsics.reshape(3, 3)
|
| 917 |
+
normal = normalize_vector(np.asarray(floor_normal)) if floor_normal is not None else None
|
| 918 |
+
u_axis = normalize_vector(np.asarray(render_u_axis)) if render_u_axis is not None else None
|
| 919 |
+
v_axis = normalize_vector(np.asarray(render_v_axis)) if render_v_axis is not None else None
|
| 920 |
+
|
| 921 |
+
rectified = rectify_floor_image(
|
| 922 |
+
image_rgb,
|
| 923 |
+
surface_mask,
|
| 924 |
+
render_transform=transform,
|
| 925 |
+
surface_uv=surface_uv,
|
| 926 |
+
surface_indices=surface_indices,
|
| 927 |
+
surface_plane_ids=surface_plane_ids,
|
| 928 |
+
)
|
| 929 |
+
material_cue = estimate_material_cue(rectified[0], rectified[1]) if rectified is not None else None
|
| 930 |
+
|
| 931 |
+
wall_cue = None
|
| 932 |
+
architecture_cue = None
|
| 933 |
+
if normal is not None:
|
| 934 |
+
wall_cue = estimate_wall_normal_cue(
|
| 935 |
+
normals_map,
|
| 936 |
+
geometry_valid_mask,
|
| 937 |
+
wall_mask,
|
| 938 |
+
floor_normal=normal,
|
| 939 |
+
render_u_axis=u_axis,
|
| 940 |
+
render_v_axis=v_axis,
|
| 941 |
+
intrinsics=camera_matrix,
|
| 942 |
+
render_transform=transform,
|
| 943 |
+
)
|
| 944 |
+
architecture_cue = estimate_architectural_line_cue(
|
| 945 |
+
image_rgb,
|
| 946 |
+
structure_mask,
|
| 947 |
+
floor_normal=normal,
|
| 948 |
+
render_u_axis=u_axis,
|
| 949 |
+
render_v_axis=v_axis,
|
| 950 |
+
intrinsics=camera_matrix,
|
| 951 |
+
render_transform=transform,
|
| 952 |
+
)
|
| 953 |
+
structural_cue = fuse_structural_cues([
|
| 954 |
+
cue for cue in (wall_cue, architecture_cue) if cue is not None
|
| 955 |
+
])
|
| 956 |
+
selected, selection_reason = select_direction(material_cue, structural_cue)
|
| 957 |
+
|
| 958 |
+
warnings = []
|
| 959 |
+
needs_user_direction = selected is None
|
| 960 |
+
if selected is None:
|
| 961 |
+
selected = DirectionCue(
|
| 962 |
+
source="canonical-render-axis",
|
| 963 |
+
angle_degrees=0.0,
|
| 964 |
+
confidence=0.0,
|
| 965 |
+
support=0,
|
| 966 |
+
region_support=0,
|
| 967 |
+
ambiguity_degrees=90.0,
|
| 968 |
+
details={"reason": "direction-is-not-observable-in-this-image"},
|
| 969 |
+
)
|
| 970 |
+
warnings.append("direction_not_observable_user_rotation_recommended")
|
| 971 |
+
if selected.ambiguity_degrees is not None:
|
| 972 |
+
warnings.append("direction_has_90_degree_axis_ambiguity")
|
| 973 |
+
|
| 974 |
+
axis = direction_axis_for_overlay(
|
| 975 |
+
angle_degrees=selected.angle_degrees,
|
| 976 |
+
image_shape=(height, width),
|
| 977 |
+
surface_mask=surface_mask,
|
| 978 |
+
surface_uv=surface_uv,
|
| 979 |
+
surface_indices=surface_indices,
|
| 980 |
+
surface_plane_ids=surface_plane_ids,
|
| 981 |
+
render_transform=transform,
|
| 982 |
+
)
|
| 983 |
+
floor_area_ratio = float(np.count_nonzero(surface_mask)) / max(int(surface_mask.size), 1)
|
| 984 |
+
return {
|
| 985 |
+
"source": "backend-direction-finder-v2",
|
| 986 |
+
"directionMethod": selected.source,
|
| 987 |
+
"selectionReason": selection_reason,
|
| 988 |
+
"angleDegrees": selected.angle_degrees,
|
| 989 |
+
"renderAngleDegrees": selected.angle_degrees,
|
| 990 |
+
"secondaryAngleDegrees": normalize_angle(selected.angle_degrees + 90.0),
|
| 991 |
+
"directionLabel": direction_label(selected.angle_degrees),
|
| 992 |
+
"confidence": selected.confidence,
|
| 993 |
+
"floorAreaRatio": round(floor_area_ratio, 4),
|
| 994 |
+
"lineCount": 0,
|
| 995 |
+
"dominantLineCount": 0,
|
| 996 |
+
"gridPatternDetected": bool(material_cue and material_cue.ambiguity_degrees == 90.0),
|
| 997 |
+
"axisAmbiguous90": selected.ambiguity_degrees == 90.0,
|
| 998 |
+
"needsUserDirection": needs_user_direction,
|
| 999 |
+
"warnings": warnings,
|
| 1000 |
+
"dominantLines": [],
|
| 1001 |
+
"directionAxis": axis,
|
| 1002 |
+
"rectification": rectified[2] if rectified is not None else None,
|
| 1003 |
+
"cues": {
|
| 1004 |
+
"material": material_cue.metadata() if material_cue is not None else None,
|
| 1005 |
+
"wallNormals": wall_cue.metadata() if wall_cue is not None else None,
|
| 1006 |
+
"architecture": architecture_cue.metadata() if architecture_cue is not None else None,
|
| 1007 |
+
"structural": structural_cue.metadata() if structural_cue is not None else None,
|
| 1008 |
+
},
|
| 1009 |
+
}
|
floor_direction.py
ADDED
|
@@ -0,0 +1,1813 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Floor direction analysis helpers for the FastAPI room editor backend."""
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
import math
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
import cv2
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
@dataclass(frozen=True)
|
| 11 |
+
class FloorPolygon:
|
| 12 |
+
points: list[tuple[float, float]]
|
| 13 |
+
bbox: tuple[float, float, float, float] | None = None
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@dataclass(frozen=True)
|
| 17 |
+
class FloorSegmentation:
|
| 18 |
+
label: str
|
| 19 |
+
confidence: float
|
| 20 |
+
polygons: list[FloorPolygon]
|
| 21 |
+
source_path: str = "root"
|
| 22 |
+
raw_keys: list[str] | None = None
|
| 23 |
+
warnings: list[str] | None = None
|
| 24 |
+
source_width: int | None = None
|
| 25 |
+
source_height: int | None = None
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def parse_floor_segmentation(payload: Any) -> FloorSegmentation:
|
| 29 |
+
root_payload = payload
|
| 30 |
+
payload, source_path, parse_warnings = find_segmentation_payload(payload)
|
| 31 |
+
raw_keys = sorted(payload.keys()) if isinstance(payload, dict) else []
|
| 32 |
+
|
| 33 |
+
if not isinstance(payload, dict):
|
| 34 |
+
return FloorSegmentation(
|
| 35 |
+
label="unknown",
|
| 36 |
+
confidence=0.0,
|
| 37 |
+
polygons=[],
|
| 38 |
+
source_path=source_path,
|
| 39 |
+
raw_keys=raw_keys,
|
| 40 |
+
warnings=parse_warnings + ["segmentation_response_not_object"],
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
source_width = extract_int_value(payload.get("width")) or extract_int_value(
|
| 44 |
+
root_payload.get("width") if isinstance(root_payload, dict) else None
|
| 45 |
+
)
|
| 46 |
+
source_height = extract_int_value(payload.get("height")) or extract_int_value(
|
| 47 |
+
root_payload.get("height") if isinstance(root_payload, dict) else None
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
label = str(payload.get("label") or payload.get("class") or payload.get("name") or "unknown")
|
| 51 |
+
|
| 52 |
+
try:
|
| 53 |
+
confidence = float(payload.get("confidence", payload.get("score", 0.0)))
|
| 54 |
+
except (TypeError, ValueError):
|
| 55 |
+
confidence = 0.0
|
| 56 |
+
|
| 57 |
+
polygons: list[FloorPolygon] = []
|
| 58 |
+
for polygon_payload in extract_polygon_payloads(payload):
|
| 59 |
+
if not isinstance(polygon_payload, dict):
|
| 60 |
+
continue
|
| 61 |
+
|
| 62 |
+
raw_points = polygon_payload.get("points") or polygon_payload.get("polygon") or []
|
| 63 |
+
points: list[tuple[float, float]] = []
|
| 64 |
+
|
| 65 |
+
for point in raw_points:
|
| 66 |
+
if not isinstance(point, (list, tuple)) or len(point) < 2:
|
| 67 |
+
continue
|
| 68 |
+
try:
|
| 69 |
+
points.append((float(point[0]), float(point[1])))
|
| 70 |
+
except (TypeError, ValueError):
|
| 71 |
+
continue
|
| 72 |
+
|
| 73 |
+
raw_bbox = polygon_payload.get("bbox")
|
| 74 |
+
bbox = None
|
| 75 |
+
if isinstance(raw_bbox, (list, tuple)) and len(raw_bbox) >= 4:
|
| 76 |
+
try:
|
| 77 |
+
bbox = (
|
| 78 |
+
float(raw_bbox[0]),
|
| 79 |
+
float(raw_bbox[1]),
|
| 80 |
+
float(raw_bbox[2]),
|
| 81 |
+
float(raw_bbox[3]),
|
| 82 |
+
)
|
| 83 |
+
except (TypeError, ValueError):
|
| 84 |
+
bbox = None
|
| 85 |
+
|
| 86 |
+
if len(points) >= 3:
|
| 87 |
+
polygons.append(FloorPolygon(points=points, bbox=bbox))
|
| 88 |
+
|
| 89 |
+
return FloorSegmentation(
|
| 90 |
+
label=label,
|
| 91 |
+
confidence=max(0.0, min(1.0, confidence)),
|
| 92 |
+
polygons=polygons,
|
| 93 |
+
source_path=source_path,
|
| 94 |
+
raw_keys=raw_keys,
|
| 95 |
+
warnings=parse_warnings,
|
| 96 |
+
source_width=source_width,
|
| 97 |
+
source_height=source_height,
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def extract_int_value(value: Any) -> int | None:
|
| 102 |
+
try:
|
| 103 |
+
parsed = int(round(float(value)))
|
| 104 |
+
except (TypeError, ValueError):
|
| 105 |
+
return None
|
| 106 |
+
return parsed if parsed > 0 else None
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def find_segmentation_payload(payload: Any) -> tuple[Any, str, list[str]]:
|
| 110 |
+
warnings: list[str] = []
|
| 111 |
+
|
| 112 |
+
if isinstance(payload, list):
|
| 113 |
+
floor_item = find_floor_item(payload)
|
| 114 |
+
if floor_item is not None:
|
| 115 |
+
return floor_item, "root[floor]", warnings
|
| 116 |
+
if any(isinstance(item, dict) and has_polygon_data(item) for item in payload):
|
| 117 |
+
warnings.append("segmentation_response_list_without_floor_label")
|
| 118 |
+
return {"label": "unknown", "polygons": []}, "root", warnings
|
| 119 |
+
return payload, "root", warnings
|
| 120 |
+
|
| 121 |
+
if not isinstance(payload, dict):
|
| 122 |
+
return payload, "root", warnings
|
| 123 |
+
|
| 124 |
+
if has_polygon_data(payload):
|
| 125 |
+
return payload, "root", warnings
|
| 126 |
+
|
| 127 |
+
for key in (
|
| 128 |
+
"floor",
|
| 129 |
+
"data",
|
| 130 |
+
"result",
|
| 131 |
+
"results",
|
| 132 |
+
"prediction",
|
| 133 |
+
"predictions",
|
| 134 |
+
"segments",
|
| 135 |
+
"response",
|
| 136 |
+
"output",
|
| 137 |
+
):
|
| 138 |
+
nested = payload.get(key)
|
| 139 |
+
if nested is None:
|
| 140 |
+
continue
|
| 141 |
+
|
| 142 |
+
if isinstance(nested, dict) and has_polygon_data(nested):
|
| 143 |
+
return nested, f"root.{key}", warnings
|
| 144 |
+
|
| 145 |
+
if isinstance(nested, list):
|
| 146 |
+
floor_item = find_floor_item(nested)
|
| 147 |
+
if floor_item is not None:
|
| 148 |
+
return floor_item, f"root.{key}[floor]", warnings
|
| 149 |
+
if any(isinstance(item, dict) and has_polygon_data(item) for item in nested):
|
| 150 |
+
warnings.append("segmentation_response_list_without_floor_label")
|
| 151 |
+
|
| 152 |
+
warnings.append("segmentation_response_missing_polygons")
|
| 153 |
+
return payload, "root", warnings
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def has_polygon_data(payload: dict[str, Any]) -> bool:
|
| 157 |
+
return bool(extract_polygon_payloads(payload))
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def find_floor_item(items: list[Any]) -> dict[str, Any] | None:
|
| 161 |
+
for item in items:
|
| 162 |
+
if not isinstance(item, dict):
|
| 163 |
+
continue
|
| 164 |
+
label = str(item.get("label") or item.get("class") or item.get("name") or "").lower()
|
| 165 |
+
if label == "floor" and has_polygon_data(item):
|
| 166 |
+
return item
|
| 167 |
+
return None
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def extract_polygon_payloads(payload: dict[str, Any]) -> list[Any]:
|
| 171 |
+
raw_polygons = payload.get("polygons")
|
| 172 |
+
if isinstance(raw_polygons, list):
|
| 173 |
+
return raw_polygons
|
| 174 |
+
|
| 175 |
+
raw_polygon = payload.get("polygon")
|
| 176 |
+
if isinstance(raw_polygon, list):
|
| 177 |
+
if raw_polygon and all(isinstance(point, (list, tuple)) for point in raw_polygon):
|
| 178 |
+
return [{"points": raw_polygon}]
|
| 179 |
+
return raw_polygon
|
| 180 |
+
|
| 181 |
+
raw_points = payload.get("points")
|
| 182 |
+
if isinstance(raw_points, list):
|
| 183 |
+
return [{"points": raw_points}]
|
| 184 |
+
|
| 185 |
+
return []
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
@dataclass(frozen=True)
|
| 189 |
+
class DetectedLine:
|
| 190 |
+
x1: int
|
| 191 |
+
y1: int
|
| 192 |
+
x2: int
|
| 193 |
+
y2: int
|
| 194 |
+
angle_degrees: float
|
| 195 |
+
length: float
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
@dataclass(frozen=True)
|
| 199 |
+
class TextureOrientation:
|
| 200 |
+
angle_degrees: float
|
| 201 |
+
confidence: float
|
| 202 |
+
support: int
|
| 203 |
+
concentration: float
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
@dataclass(frozen=True)
|
| 207 |
+
class LineFamilyCluster:
|
| 208 |
+
line_indices: list[int]
|
| 209 |
+
angle_degrees: float
|
| 210 |
+
weight: float
|
| 211 |
+
concentration: float
|
| 212 |
+
distinct_offset_count: int
|
| 213 |
+
score: float
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
@dataclass(frozen=True)
|
| 217 |
+
class DirectionResult:
|
| 218 |
+
angle_degrees: float | None
|
| 219 |
+
secondary_angle_degrees: float | None
|
| 220 |
+
direction_label: str
|
| 221 |
+
confidence: float
|
| 222 |
+
floor_area_ratio: float
|
| 223 |
+
line_count: int
|
| 224 |
+
dominant_line_count: int
|
| 225 |
+
grid_pattern_detected: bool
|
| 226 |
+
dominant_lines: list[DetectedLine]
|
| 227 |
+
warnings: list[str]
|
| 228 |
+
overlay_bgr: np.ndarray | None = None
|
| 229 |
+
render_angle_degrees: float | None = None
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def analyze_floor_direction(
|
| 233 |
+
image_bgr: np.ndarray,
|
| 234 |
+
segmentation: FloorSegmentation,
|
| 235 |
+
*,
|
| 236 |
+
include_overlay: bool = False,
|
| 237 |
+
render_transform: list[float] | np.ndarray | None = None,
|
| 238 |
+
surface_uv: np.ndarray | None = None,
|
| 239 |
+
surface_indices: np.ndarray | None = None,
|
| 240 |
+
surface_plane_ids: np.ndarray | None = None,
|
| 241 |
+
) -> DirectionResult:
|
| 242 |
+
height, width = image_bgr.shape[:2]
|
| 243 |
+
warnings: list[str] = list(segmentation.warnings or [])
|
| 244 |
+
|
| 245 |
+
warnings.extend(uploaded_image_quality_warnings(image_bgr))
|
| 246 |
+
|
| 247 |
+
mask = build_floor_mask(
|
| 248 |
+
width=width,
|
| 249 |
+
height=height,
|
| 250 |
+
polygons=segmentation.polygons,
|
| 251 |
+
source_width=segmentation.source_width,
|
| 252 |
+
source_height=segmentation.source_height,
|
| 253 |
+
)
|
| 254 |
+
floor_pixels = int(np.count_nonzero(mask))
|
| 255 |
+
total_pixels = height * width
|
| 256 |
+
floor_area_ratio = floor_pixels / total_pixels if total_pixels else 0.0
|
| 257 |
+
|
| 258 |
+
if segmentation.confidence < 0.75:
|
| 259 |
+
warnings.append("low_segmentation_confidence")
|
| 260 |
+
if segmentation_dimensions_differ(segmentation.source_width, segmentation.source_height, width, height):
|
| 261 |
+
warnings.append("segmentation_coordinate_scale_applied")
|
| 262 |
+
if not segmentation.polygons or floor_pixels == 0:
|
| 263 |
+
warnings.append("no_floor_polygon_detected")
|
| 264 |
+
return DirectionResult(
|
| 265 |
+
angle_degrees=None,
|
| 266 |
+
secondary_angle_degrees=None,
|
| 267 |
+
direction_label="unknown",
|
| 268 |
+
confidence=0.0,
|
| 269 |
+
floor_area_ratio=0.0,
|
| 270 |
+
line_count=0,
|
| 271 |
+
dominant_line_count=0,
|
| 272 |
+
grid_pattern_detected=False,
|
| 273 |
+
dominant_lines=[],
|
| 274 |
+
warnings=warnings,
|
| 275 |
+
overlay_bgr=create_overlay(image_bgr, mask, [], None) if include_overlay else None,
|
| 276 |
+
)
|
| 277 |
+
if floor_area_ratio < 0.03:
|
| 278 |
+
warnings.append("floor_area_too_small")
|
| 279 |
+
|
| 280 |
+
inner_mask = erode_mask(mask)
|
| 281 |
+
if int(np.count_nonzero(inner_mask)) == 0:
|
| 282 |
+
inner_mask = mask
|
| 283 |
+
|
| 284 |
+
lines = detect_candidate_lines(image_bgr, inner_mask)
|
| 285 |
+
hough_orientation = dominant_orientation(lines, image_shape=inner_mask.shape[:2])
|
| 286 |
+
texture_orientation = estimate_texture_orientation(image_bgr, inner_mask)
|
| 287 |
+
selected_orientation = select_orientation(hough_orientation, texture_orientation, warnings)
|
| 288 |
+
|
| 289 |
+
if selected_orientation is None:
|
| 290 |
+
warnings.append("no_strong_floor_lines_detected")
|
| 291 |
+
return DirectionResult(
|
| 292 |
+
angle_degrees=None,
|
| 293 |
+
secondary_angle_degrees=None,
|
| 294 |
+
direction_label="unknown",
|
| 295 |
+
confidence=0.0,
|
| 296 |
+
floor_area_ratio=floor_area_ratio,
|
| 297 |
+
line_count=0,
|
| 298 |
+
dominant_line_count=0,
|
| 299 |
+
grid_pattern_detected=False,
|
| 300 |
+
dominant_lines=[],
|
| 301 |
+
warnings=warnings,
|
| 302 |
+
overlay_bgr=create_overlay(image_bgr, mask, [], None) if include_overlay else None,
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
angle_degrees, orientation_source = selected_orientation
|
| 306 |
+
render_angle_degrees = estimate_surface_uv_grout_rotation(
|
| 307 |
+
lines,
|
| 308 |
+
image_bgr=image_bgr,
|
| 309 |
+
surface_uv=surface_uv,
|
| 310 |
+
surface_indices=surface_indices,
|
| 311 |
+
surface_plane_ids=surface_plane_ids,
|
| 312 |
+
image_shape=(height, width),
|
| 313 |
+
)
|
| 314 |
+
if render_angle_degrees is not None:
|
| 315 |
+
warnings.append("grout_direction_projected_to_surface_uv")
|
| 316 |
+
else:
|
| 317 |
+
render_angle_degrees = estimate_rectified_grout_rotation(
|
| 318 |
+
lines,
|
| 319 |
+
render_transform=render_transform,
|
| 320 |
+
)
|
| 321 |
+
if render_angle_degrees is not None:
|
| 322 |
+
warnings.append("grout_direction_rectified_for_renderer")
|
| 323 |
+
dominant_lines: list[DetectedLine] = []
|
| 324 |
+
peak_weight_ratio = 0.0
|
| 325 |
+
concentration = 0.0
|
| 326 |
+
orthogonal_ratio = 0.0
|
| 327 |
+
if hough_orientation is not None:
|
| 328 |
+
(
|
| 329 |
+
_hough_angle,
|
| 330 |
+
dominant_lines,
|
| 331 |
+
peak_weight_ratio,
|
| 332 |
+
concentration,
|
| 333 |
+
orthogonal_ratio,
|
| 334 |
+
) = hough_orientation
|
| 335 |
+
secondary_angle_degrees = detect_secondary_grid_angle(
|
| 336 |
+
lines=lines,
|
| 337 |
+
primary_angle_degrees=angle_degrees,
|
| 338 |
+
primary_line_count=len(dominant_lines),
|
| 339 |
+
)
|
| 340 |
+
grid_pattern_detected = secondary_angle_degrees is not None
|
| 341 |
+
|
| 342 |
+
if len(dominant_lines) < 5:
|
| 343 |
+
warnings.append("weak_line_support")
|
| 344 |
+
if orthogonal_ratio > 0.65:
|
| 345 |
+
warnings.append("possible_square_tile_grid_or_ambiguous_perpendicular_lines")
|
| 346 |
+
if grid_pattern_detected:
|
| 347 |
+
warnings.append("grid_pattern_detected")
|
| 348 |
+
if orientation_source == "texture":
|
| 349 |
+
warnings.append("texture_orientation_used")
|
| 350 |
+
elif orientation_source == "combined":
|
| 351 |
+
warnings.append("hough_texture_orientation_combined")
|
| 352 |
+
|
| 353 |
+
hough_confidence = score_confidence(
|
| 354 |
+
segmentation_confidence=segmentation.confidence,
|
| 355 |
+
floor_area_ratio=floor_area_ratio,
|
| 356 |
+
line_count=len(lines),
|
| 357 |
+
dominant_line_count=len(dominant_lines),
|
| 358 |
+
peak_weight_ratio=peak_weight_ratio,
|
| 359 |
+
concentration=concentration,
|
| 360 |
+
)
|
| 361 |
+
texture_confidence = 0.0
|
| 362 |
+
if texture_orientation is not None:
|
| 363 |
+
texture_confidence = score_texture_confidence(
|
| 364 |
+
segmentation_confidence=segmentation.confidence,
|
| 365 |
+
floor_area_ratio=floor_area_ratio,
|
| 366 |
+
texture_confidence=texture_orientation.confidence,
|
| 367 |
+
)
|
| 368 |
+
confidence = final_orientation_confidence(
|
| 369 |
+
source=orientation_source,
|
| 370 |
+
hough_confidence=hough_confidence,
|
| 371 |
+
texture_confidence=texture_confidence,
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
direction_label = label_direction(angle_degrees)
|
| 375 |
+
overlay = (
|
| 376 |
+
create_overlay(image_bgr, mask, lines, angle_degrees, secondary_angle_degrees)
|
| 377 |
+
if include_overlay
|
| 378 |
+
else None
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
return DirectionResult(
|
| 382 |
+
angle_degrees=round(angle_degrees, 2),
|
| 383 |
+
secondary_angle_degrees=round(secondary_angle_degrees, 2)
|
| 384 |
+
if secondary_angle_degrees is not None
|
| 385 |
+
else None,
|
| 386 |
+
direction_label=direction_label,
|
| 387 |
+
confidence=round(confidence, 3),
|
| 388 |
+
floor_area_ratio=round(floor_area_ratio, 4),
|
| 389 |
+
line_count=len(lines),
|
| 390 |
+
dominant_line_count=len(dominant_lines),
|
| 391 |
+
grid_pattern_detected=grid_pattern_detected,
|
| 392 |
+
dominant_lines=dominant_lines[:30],
|
| 393 |
+
warnings=warnings,
|
| 394 |
+
overlay_bgr=overlay,
|
| 395 |
+
render_angle_degrees=render_angle_degrees,
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def build_floor_mask(
|
| 400 |
+
*,
|
| 401 |
+
width: int,
|
| 402 |
+
height: int,
|
| 403 |
+
polygons: list[FloorPolygon],
|
| 404 |
+
source_width: int | None = None,
|
| 405 |
+
source_height: int | None = None,
|
| 406 |
+
) -> np.ndarray:
|
| 407 |
+
mask = np.zeros((height, width), dtype=np.uint8)
|
| 408 |
+
scale_x = width / source_width if source_width and source_width > 0 else 1.0
|
| 409 |
+
scale_y = height / source_height if source_height and source_height > 0 else 1.0
|
| 410 |
+
|
| 411 |
+
for polygon in polygons:
|
| 412 |
+
points = np.array(polygon.points, dtype=np.float32)
|
| 413 |
+
if points.shape[0] < 3:
|
| 414 |
+
continue
|
| 415 |
+
|
| 416 |
+
points[:, 0] *= scale_x
|
| 417 |
+
points[:, 1] *= scale_y
|
| 418 |
+
points[:, 0] = np.clip(points[:, 0], 0, width - 1)
|
| 419 |
+
points[:, 1] = np.clip(points[:, 1], 0, height - 1)
|
| 420 |
+
int_points = np.round(points).astype(np.int32)
|
| 421 |
+
cv2.fillPoly(mask, [int_points], 255)
|
| 422 |
+
|
| 423 |
+
kernel_size = max(3, int(round(min(width, height) * 0.008)))
|
| 424 |
+
if kernel_size % 2 == 0:
|
| 425 |
+
kernel_size += 1
|
| 426 |
+
kernel = np.ones((kernel_size, kernel_size), dtype=np.uint8)
|
| 427 |
+
return cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def segmentation_dimensions_differ(
|
| 431 |
+
source_width: int | None,
|
| 432 |
+
source_height: int | None,
|
| 433 |
+
image_width: int,
|
| 434 |
+
image_height: int,
|
| 435 |
+
) -> bool:
|
| 436 |
+
if not source_width or not source_height:
|
| 437 |
+
return False
|
| 438 |
+
return abs(source_width - image_width) > 2 or abs(source_height - image_height) > 2
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
def uploaded_image_quality_warnings(image_bgr: np.ndarray) -> list[str]:
|
| 442 |
+
if largest_flat_row_region_ratio(image_bgr) >= 0.35:
|
| 443 |
+
return ["uploaded_image_contains_large_flat_filled_region"]
|
| 444 |
+
return []
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def largest_flat_row_region_ratio(image_bgr: np.ndarray) -> float:
|
| 448 |
+
height, width = image_bgr.shape[:2]
|
| 449 |
+
if height == 0 or width == 0:
|
| 450 |
+
return 0.0
|
| 451 |
+
|
| 452 |
+
gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)
|
| 453 |
+
row_std = np.std(gray, axis=1)
|
| 454 |
+
flat_rows = row_std < 4.0
|
| 455 |
+
|
| 456 |
+
longest_run = 0
|
| 457 |
+
current_run = 0
|
| 458 |
+
for is_flat in flat_rows:
|
| 459 |
+
if bool(is_flat):
|
| 460 |
+
current_run += 1
|
| 461 |
+
longest_run = max(longest_run, current_run)
|
| 462 |
+
else:
|
| 463 |
+
current_run = 0
|
| 464 |
+
|
| 465 |
+
return longest_run / height
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def erode_mask(mask: np.ndarray) -> np.ndarray:
|
| 469 |
+
height, width = mask.shape[:2]
|
| 470 |
+
kernel_size = max(5, int(round(min(width, height) * 0.015)))
|
| 471 |
+
if kernel_size % 2 == 0:
|
| 472 |
+
kernel_size += 1
|
| 473 |
+
kernel = np.ones((kernel_size, kernel_size), dtype=np.uint8)
|
| 474 |
+
return cv2.erode(mask, kernel, iterations=1)
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def detect_candidate_lines(image_bgr: np.ndarray, mask: np.ndarray) -> list[DetectedLine]:
|
| 478 |
+
height, width = image_bgr.shape[:2]
|
| 479 |
+
floor_pixels = max(1, int(np.count_nonzero(mask)))
|
| 480 |
+
gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)
|
| 481 |
+
|
| 482 |
+
inside_pixels = gray[mask > 0]
|
| 483 |
+
fill_value = int(np.median(inside_pixels)) if inside_pixels.size else int(np.median(gray))
|
| 484 |
+
prepared = gray.copy()
|
| 485 |
+
prepared[mask == 0] = fill_value
|
| 486 |
+
|
| 487 |
+
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
|
| 488 |
+
enhanced = clahe.apply(prepared)
|
| 489 |
+
blurred = cv2.GaussianBlur(enhanced, (5, 5), 0)
|
| 490 |
+
|
| 491 |
+
min_dimension = min(width, height)
|
| 492 |
+
min_line_length = max(28, int(min_dimension * 0.055))
|
| 493 |
+
max_line_gap = max(8, int(min_dimension * 0.025))
|
| 494 |
+
hough_threshold = max(18, int(math.sqrt(floor_pixels) * 0.035))
|
| 495 |
+
|
| 496 |
+
grout_edges = detect_grout_edges(enhanced, mask)
|
| 497 |
+
grout_lines = detect_hough_lines_from_edges(
|
| 498 |
+
grout_edges,
|
| 499 |
+
min_line_length=max(20, int(min_dimension * 0.045)),
|
| 500 |
+
max_line_gap=max(10, int(min_dimension * 0.03)),
|
| 501 |
+
thresholds=[
|
| 502 |
+
max(10, int(math.sqrt(floor_pixels) * 0.02)),
|
| 503 |
+
max(8, int(math.sqrt(floor_pixels) * 0.015)),
|
| 504 |
+
],
|
| 505 |
+
)
|
| 506 |
+
grout_lines = deduplicate_lines(grout_lines)
|
| 507 |
+
if has_usable_grout_line_support(grout_lines, image_shape=(height, width)):
|
| 508 |
+
return grout_lines
|
| 509 |
+
|
| 510 |
+
attempts = [
|
| 511 |
+
(50, 150, hough_threshold, min_line_length),
|
| 512 |
+
(30, 100, max(12, int(hough_threshold * 0.75)), max(20, int(min_line_length * 0.8))),
|
| 513 |
+
(80, 220, hough_threshold, min_line_length),
|
| 514 |
+
]
|
| 515 |
+
|
| 516 |
+
best_lines: list[DetectedLine] = []
|
| 517 |
+
for canny_low, canny_high, threshold, min_length in attempts:
|
| 518 |
+
edges = cv2.Canny(blurred, canny_low, canny_high)
|
| 519 |
+
edges = cv2.bitwise_and(edges, mask)
|
| 520 |
+
|
| 521 |
+
raw_lines = cv2.HoughLinesP(
|
| 522 |
+
edges,
|
| 523 |
+
rho=1,
|
| 524 |
+
theta=np.pi / 180,
|
| 525 |
+
threshold=threshold,
|
| 526 |
+
minLineLength=min_length,
|
| 527 |
+
maxLineGap=max_line_gap,
|
| 528 |
+
)
|
| 529 |
+
lines = normalize_hough_lines(raw_lines, min_length=min_length)
|
| 530 |
+
if len(lines) > len(best_lines):
|
| 531 |
+
best_lines = lines
|
| 532 |
+
if len(best_lines) >= 12:
|
| 533 |
+
break
|
| 534 |
+
|
| 535 |
+
return deduplicate_lines(best_lines)
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
def detect_grout_edges(enhanced_gray: np.ndarray, mask: np.ndarray) -> np.ndarray:
|
| 539 |
+
height, width = enhanced_gray.shape[:2]
|
| 540 |
+
min_dimension = min(width, height)
|
| 541 |
+
if min_dimension <= 0 or int(np.count_nonzero(mask)) < 100:
|
| 542 |
+
return np.zeros_like(enhanced_gray)
|
| 543 |
+
|
| 544 |
+
kernel_size = max(7, int(round(min_dimension * 0.018)))
|
| 545 |
+
if kernel_size % 2 == 0:
|
| 546 |
+
kernel_size += 1
|
| 547 |
+
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (kernel_size, kernel_size))
|
| 548 |
+
|
| 549 |
+
dark_response = cv2.morphologyEx(enhanced_gray, cv2.MORPH_BLACKHAT, kernel)
|
| 550 |
+
light_response = cv2.morphologyEx(enhanced_gray, cv2.MORPH_TOPHAT, kernel)
|
| 551 |
+
response = cv2.max(dark_response, light_response)
|
| 552 |
+
response = cv2.GaussianBlur(response, (3, 3), 0)
|
| 553 |
+
response = cv2.bitwise_and(response, mask)
|
| 554 |
+
|
| 555 |
+
valid_response = response[mask > 0]
|
| 556 |
+
valid_response = valid_response[valid_response > 0]
|
| 557 |
+
if valid_response.size < 80:
|
| 558 |
+
return np.zeros_like(enhanced_gray)
|
| 559 |
+
|
| 560 |
+
percentile_threshold = float(np.percentile(valid_response, 84))
|
| 561 |
+
spread_threshold = float(np.mean(valid_response) + np.std(valid_response) * 0.35)
|
| 562 |
+
threshold = max(5.0, min(percentile_threshold, spread_threshold))
|
| 563 |
+
|
| 564 |
+
binary = np.zeros_like(response)
|
| 565 |
+
binary[response >= threshold] = 255
|
| 566 |
+
cleanup_kernel = np.ones((3, 3), dtype=np.uint8)
|
| 567 |
+
binary = cv2.morphologyEx(binary, cv2.MORPH_OPEN, cleanup_kernel)
|
| 568 |
+
binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, cleanup_kernel)
|
| 569 |
+
|
| 570 |
+
low_threshold = max(3, int(round(threshold * 0.45)))
|
| 571 |
+
high_threshold = max(low_threshold + 3, int(round(threshold * 1.35)))
|
| 572 |
+
edges = cv2.Canny(response, low_threshold, high_threshold)
|
| 573 |
+
support = cv2.dilate(binary, cleanup_kernel, iterations=1)
|
| 574 |
+
edges = cv2.bitwise_and(edges, support)
|
| 575 |
+
return cv2.bitwise_and(edges, mask)
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
def detect_hough_lines_from_edges(
|
| 579 |
+
edges: np.ndarray,
|
| 580 |
+
*,
|
| 581 |
+
min_line_length: int,
|
| 582 |
+
max_line_gap: int,
|
| 583 |
+
thresholds: list[int],
|
| 584 |
+
) -> list[DetectedLine]:
|
| 585 |
+
if int(np.count_nonzero(edges)) < max(24, min_line_length):
|
| 586 |
+
return []
|
| 587 |
+
|
| 588 |
+
best_lines: list[DetectedLine] = []
|
| 589 |
+
for threshold in thresholds:
|
| 590 |
+
raw_lines = cv2.HoughLinesP(
|
| 591 |
+
edges,
|
| 592 |
+
rho=1,
|
| 593 |
+
theta=np.pi / 180,
|
| 594 |
+
threshold=threshold,
|
| 595 |
+
minLineLength=min_line_length,
|
| 596 |
+
maxLineGap=max_line_gap,
|
| 597 |
+
)
|
| 598 |
+
lines = normalize_hough_lines(raw_lines, min_length=min_line_length)
|
| 599 |
+
if len(lines) > len(best_lines):
|
| 600 |
+
best_lines = lines
|
| 601 |
+
|
| 602 |
+
return best_lines
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
def has_usable_grout_line_support(
|
| 606 |
+
lines: list[DetectedLine],
|
| 607 |
+
*,
|
| 608 |
+
image_shape: tuple[int, int],
|
| 609 |
+
) -> bool:
|
| 610 |
+
if len(lines) < 3:
|
| 611 |
+
return False
|
| 612 |
+
|
| 613 |
+
clusters = cluster_line_families(lines, image_shape=image_shape)
|
| 614 |
+
if not clusters:
|
| 615 |
+
return False
|
| 616 |
+
|
| 617 |
+
best_cluster = max(clusters, key=lambda cluster: cluster.score)
|
| 618 |
+
if best_cluster.concentration < 0.70:
|
| 619 |
+
return False
|
| 620 |
+
|
| 621 |
+
return (
|
| 622 |
+
len(best_cluster.line_indices) >= 4
|
| 623 |
+
and best_cluster.distinct_offset_count >= 2
|
| 624 |
+
) or (
|
| 625 |
+
len(best_cluster.line_indices) >= 3
|
| 626 |
+
and best_cluster.distinct_offset_count >= 3
|
| 627 |
+
)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def normalize_hough_lines(raw_lines: np.ndarray | None, *, min_length: int) -> list[DetectedLine]:
|
| 631 |
+
if raw_lines is None:
|
| 632 |
+
return []
|
| 633 |
+
|
| 634 |
+
lines: list[DetectedLine] = []
|
| 635 |
+
for raw_line in raw_lines.reshape(-1, 4):
|
| 636 |
+
x1, y1, x2, y2 = [int(value) for value in raw_line]
|
| 637 |
+
dx = x2 - x1
|
| 638 |
+
dy = y2 - y1
|
| 639 |
+
length = math.hypot(dx, dy)
|
| 640 |
+
if length < min_length:
|
| 641 |
+
continue
|
| 642 |
+
angle = normalized_line_angle(dx, dy)
|
| 643 |
+
lines.append(
|
| 644 |
+
DetectedLine(
|
| 645 |
+
x1=x1,
|
| 646 |
+
y1=y1,
|
| 647 |
+
x2=x2,
|
| 648 |
+
y2=y2,
|
| 649 |
+
angle_degrees=round(angle, 2),
|
| 650 |
+
length=round(length, 2),
|
| 651 |
+
)
|
| 652 |
+
)
|
| 653 |
+
return lines
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
def deduplicate_lines(lines: list[DetectedLine]) -> list[DetectedLine]:
|
| 657 |
+
seen: set[tuple[int, int, int, int, int]] = set()
|
| 658 |
+
unique: list[DetectedLine] = []
|
| 659 |
+
|
| 660 |
+
for line in sorted(lines, key=lambda item: item.length, reverse=True):
|
| 661 |
+
angle_bin = int(round(line.angle_degrees / 3.0))
|
| 662 |
+
midpoint_x = int(round(((line.x1 + line.x2) / 2) / 8.0))
|
| 663 |
+
midpoint_y = int(round(((line.y1 + line.y2) / 2) / 8.0))
|
| 664 |
+
length_bin = int(round(line.length / 12.0))
|
| 665 |
+
key = (angle_bin, midpoint_x, midpoint_y, length_bin, int(line.length > 80))
|
| 666 |
+
if key in seen:
|
| 667 |
+
continue
|
| 668 |
+
seen.add(key)
|
| 669 |
+
unique.append(line)
|
| 670 |
+
|
| 671 |
+
return unique[:200]
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def dominant_orientation(
|
| 675 |
+
lines: list[DetectedLine],
|
| 676 |
+
image_shape: tuple[int, int] | None = None,
|
| 677 |
+
) -> tuple[float, list[DetectedLine], float, float, float] | None:
|
| 678 |
+
if not lines:
|
| 679 |
+
return None
|
| 680 |
+
|
| 681 |
+
angles = np.array([line.angle_degrees for line in lines], dtype=np.float64)
|
| 682 |
+
weights = np.array([max(1.0, line.length) for line in lines], dtype=np.float64)
|
| 683 |
+
total_weight = float(np.sum(weights))
|
| 684 |
+
if total_weight <= 0:
|
| 685 |
+
return None
|
| 686 |
+
|
| 687 |
+
clusters = cluster_line_families(lines, image_shape=image_shape)
|
| 688 |
+
if not clusters:
|
| 689 |
+
return None
|
| 690 |
+
|
| 691 |
+
dominant_cluster = max(clusters, key=lambda cluster: cluster.score)
|
| 692 |
+
dominant_angle = dominant_cluster.angle_degrees
|
| 693 |
+
peak_weight_ratio = dominant_cluster.weight / total_weight
|
| 694 |
+
concentration = dominant_cluster.concentration
|
| 695 |
+
|
| 696 |
+
orthogonal_angle = (dominant_angle + 90.0) % 180.0
|
| 697 |
+
orthogonal_weight = float(
|
| 698 |
+
np.sum(
|
| 699 |
+
[
|
| 700 |
+
weight
|
| 701 |
+
for angle, weight in zip(angles, weights, strict=False)
|
| 702 |
+
if angular_distance_degrees(float(angle), orthogonal_angle) <= 12.0
|
| 703 |
+
]
|
| 704 |
+
)
|
| 705 |
+
)
|
| 706 |
+
orthogonal_ratio = orthogonal_weight / dominant_cluster.weight if dominant_cluster.weight else 0.0
|
| 707 |
+
|
| 708 |
+
dominant_lines = [lines[index] for index in dominant_cluster.line_indices]
|
| 709 |
+
dominant_lines = sorted(dominant_lines, key=lambda item: item.length, reverse=True)
|
| 710 |
+
|
| 711 |
+
return dominant_angle, dominant_lines, peak_weight_ratio, concentration, orthogonal_ratio
|
| 712 |
+
|
| 713 |
+
|
| 714 |
+
def estimate_rectified_grout_rotation(
|
| 715 |
+
lines: list[DetectedLine],
|
| 716 |
+
*,
|
| 717 |
+
render_transform: list[float] | np.ndarray | None,
|
| 718 |
+
) -> float | None:
|
| 719 |
+
"""Return a cardinal tile rotation in the renderer's floor-plane coordinates."""
|
| 720 |
+
transform = normalize_render_transform(render_transform)
|
| 721 |
+
if transform is None or len(lines) < 4:
|
| 722 |
+
return None
|
| 723 |
+
|
| 724 |
+
rectified_lines = transform_detected_lines(lines, transform)
|
| 725 |
+
orientation = dominant_orientation(rectified_lines)
|
| 726 |
+
if orientation is None:
|
| 727 |
+
return None
|
| 728 |
+
|
| 729 |
+
angle_degrees, dominant_lines, _peak_weight_ratio, concentration, _orthogonal_ratio = orientation
|
| 730 |
+
if len(dominant_lines) < 4 or concentration < 0.76:
|
| 731 |
+
return None
|
| 732 |
+
|
| 733 |
+
return snap_to_tile_axis(angle_degrees)
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
def estimate_surface_uv_grout_rotation(
|
| 737 |
+
lines: list[DetectedLine],
|
| 738 |
+
*,
|
| 739 |
+
image_bgr: np.ndarray | None = None,
|
| 740 |
+
surface_uv: np.ndarray | None,
|
| 741 |
+
surface_indices: np.ndarray | None,
|
| 742 |
+
surface_plane_ids: np.ndarray | None,
|
| 743 |
+
image_shape: tuple[int, int],
|
| 744 |
+
) -> float | None:
|
| 745 |
+
"""Measure grout in the same surface-UV plane sampled by the renderer."""
|
| 746 |
+
uv_grid, plane_grid = build_surface_uv_grids(
|
| 747 |
+
surface_uv=surface_uv,
|
| 748 |
+
surface_indices=surface_indices,
|
| 749 |
+
surface_plane_ids=surface_plane_ids,
|
| 750 |
+
image_shape=image_shape,
|
| 751 |
+
)
|
| 752 |
+
if uv_grid is None:
|
| 753 |
+
return None
|
| 754 |
+
|
| 755 |
+
# Image-space Hough families are unreliable for oblique views: parallel floor
|
| 756 |
+
# seams converge, while furniture edges remain parallel. Rectifying the source
|
| 757 |
+
# into surface UV makes the actual grout parallel before it is scored.
|
| 758 |
+
if image_bgr is not None:
|
| 759 |
+
rectified = rectify_floor_image_to_surface_uv(image_bgr, uv_grid, plane_grid)
|
| 760 |
+
if rectified is not None:
|
| 761 |
+
rectified_image, rectified_mask = rectified
|
| 762 |
+
rectified_lines = detect_candidate_lines(rectified_image, rectified_mask)
|
| 763 |
+
rectified_angle = estimate_repeated_grout_orientation(
|
| 764 |
+
rectified_lines,
|
| 765 |
+
image_shape=rectified_mask.shape[:2],
|
| 766 |
+
)
|
| 767 |
+
if rectified_angle is not None:
|
| 768 |
+
return rectified_angle
|
| 769 |
+
|
| 770 |
+
if len(lines) < 4:
|
| 771 |
+
return None
|
| 772 |
+
|
| 773 |
+
uv_lines = project_lines_to_surface_uv(lines, uv_grid, plane_grid)
|
| 774 |
+
return estimate_repeated_grout_orientation(uv_lines)
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
def rectify_floor_image_to_surface_uv(
|
| 778 |
+
image_bgr: np.ndarray,
|
| 779 |
+
uv_grid: np.ndarray,
|
| 780 |
+
plane_grid: np.ndarray | None,
|
| 781 |
+
) -> tuple[np.ndarray, np.ndarray] | None:
|
| 782 |
+
"""Splat source pixels into a uniform, metric surface-UV image.
|
| 783 |
+
|
| 784 |
+
The output uses one scale for U and V so line angles are directly usable as
|
| 785 |
+
renderer rotations. When the floor contains multiple surfaces, retain only
|
| 786 |
+
the largest assigned plane: their local UV bases are intentionally separate.
|
| 787 |
+
"""
|
| 788 |
+
if image_bgr.shape[:2] != uv_grid.shape[:2]:
|
| 789 |
+
return None
|
| 790 |
+
|
| 791 |
+
valid = np.isfinite(uv_grid).all(axis=2)
|
| 792 |
+
if plane_grid is not None:
|
| 793 |
+
plane_values = plane_grid[valid & (plane_grid != 255)]
|
| 794 |
+
if plane_values.size:
|
| 795 |
+
dominant_plane = int(np.bincount(plane_values).argmax())
|
| 796 |
+
valid &= plane_grid == dominant_plane
|
| 797 |
+
if int(valid.sum()) < 600:
|
| 798 |
+
return None
|
| 799 |
+
|
| 800 |
+
uv = uv_grid[valid].astype(np.float64)
|
| 801 |
+
lower = np.percentile(uv, 0.5, axis=0)
|
| 802 |
+
upper = np.percentile(uv, 99.5, axis=0)
|
| 803 |
+
span = upper - lower
|
| 804 |
+
if not np.isfinite(span).all() or float(np.min(span)) <= 1e-5:
|
| 805 |
+
return None
|
| 806 |
+
|
| 807 |
+
# Keep the rectified image detailed enough for grout, without making this
|
| 808 |
+
# CPU-only preprocessing grow with the uploaded image resolution.
|
| 809 |
+
aspect = float(span[0] / span[1])
|
| 810 |
+
target_long_side = int(
|
| 811 |
+
np.clip(
|
| 812 |
+
round(math.sqrt(int(valid.sum()) * max(aspect, 1.0 / aspect))),
|
| 813 |
+
256,
|
| 814 |
+
1024,
|
| 815 |
+
)
|
| 816 |
+
)
|
| 817 |
+
scale = target_long_side / float(np.max(span))
|
| 818 |
+
rectified_width = int(np.clip(round(float(span[0]) * scale) + 1, 96, 1024))
|
| 819 |
+
rectified_height = int(np.clip(round(float(span[1]) * scale) + 1, 96, 1024))
|
| 820 |
+
if rectified_width < 96 or rectified_height < 96:
|
| 821 |
+
return None
|
| 822 |
+
|
| 823 |
+
source_gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)
|
| 824 |
+
source_values = source_gray[valid].astype(np.float64)
|
| 825 |
+
local_u = uv[:, 0] - lower[0]
|
| 826 |
+
local_v = uv[:, 1] - lower[1]
|
| 827 |
+
xs = np.clip(np.rint(local_u * scale).astype(np.int32), 0, rectified_width - 1)
|
| 828 |
+
ys = np.clip(np.rint(local_v * scale).astype(np.int32), 0, rectified_height - 1)
|
| 829 |
+
flat_indices = ys * rectified_width + xs
|
| 830 |
+
pixel_count = rectified_width * rectified_height
|
| 831 |
+
counts = np.bincount(flat_indices, minlength=pixel_count)
|
| 832 |
+
values = np.bincount(flat_indices, weights=source_values, minlength=pixel_count)
|
| 833 |
+
covered = counts > 0
|
| 834 |
+
if int(covered.sum()) < max(500, int(pixel_count * 0.08)):
|
| 835 |
+
return None
|
| 836 |
+
|
| 837 |
+
fill_value = int(np.median(source_values)) if source_values.size else 0
|
| 838 |
+
rectified_gray = np.full(pixel_count, fill_value, dtype=np.uint8)
|
| 839 |
+
rectified_gray[covered] = np.clip(values[covered] / counts[covered], 0, 255).astype(np.uint8)
|
| 840 |
+
rectified_mask = (covered.reshape(rectified_height, rectified_width).astype(np.uint8) * 255)
|
| 841 |
+
rectified_gray = rectified_gray.reshape(rectified_height, rectified_width)
|
| 842 |
+
return cv2.cvtColor(rectified_gray, cv2.COLOR_GRAY2BGR), rectified_mask
|
| 843 |
+
|
| 844 |
+
|
| 845 |
+
def estimate_repeated_grout_orientation(
|
| 846 |
+
lines: list[DetectedLine],
|
| 847 |
+
*,
|
| 848 |
+
image_shape: tuple[int, int] | None = None,
|
| 849 |
+
) -> float | None:
|
| 850 |
+
"""Select a direction only when it has repeated, regularly spaced seams."""
|
| 851 |
+
if len(lines) < 4:
|
| 852 |
+
return None
|
| 853 |
+
|
| 854 |
+
candidates: list[tuple[float, float]] = []
|
| 855 |
+
for cluster in cluster_line_families(lines, image_shape=image_shape):
|
| 856 |
+
if len(cluster.line_indices) < 4 or cluster.concentration < 0.76:
|
| 857 |
+
continue
|
| 858 |
+
|
| 859 |
+
offsets, offset_weights, median_length = consolidated_line_offsets(
|
| 860 |
+
lines,
|
| 861 |
+
cluster.line_indices,
|
| 862 |
+
angle_degrees=cluster.angle_degrees,
|
| 863 |
+
image_shape=image_shape,
|
| 864 |
+
)
|
| 865 |
+
if len(offsets) < 3:
|
| 866 |
+
continue
|
| 867 |
+
|
| 868 |
+
periodicity = repeated_offset_periodicity(offsets, offset_weights)
|
| 869 |
+
if periodicity < 0.76:
|
| 870 |
+
continue
|
| 871 |
+
|
| 872 |
+
support = min(1.0, len(cluster.line_indices) / 12.0)
|
| 873 |
+
offset_support = min(1.0, (len(offsets) - 1) / 6.0)
|
| 874 |
+
length_support = min(1.0, median_length / max(1.0, offset_span_reference(offsets, image_shape)))
|
| 875 |
+
quality = (
|
| 876 |
+
0.28 * periodicity
|
| 877 |
+
+ 0.24 * cluster.concentration
|
| 878 |
+
+ 0.22 * support
|
| 879 |
+
+ 0.18 * offset_support
|
| 880 |
+
+ 0.08 * length_support
|
| 881 |
+
)
|
| 882 |
+
candidates.append((quality, cluster.angle_degrees))
|
| 883 |
+
|
| 884 |
+
if not candidates:
|
| 885 |
+
return None
|
| 886 |
+
quality, angle_degrees = max(candidates, key=lambda candidate: candidate[0])
|
| 887 |
+
return angle_degrees if quality >= 0.68 else None
|
| 888 |
+
|
| 889 |
+
|
| 890 |
+
def consolidated_line_offsets(
|
| 891 |
+
lines: list[DetectedLine],
|
| 892 |
+
line_indices: list[int],
|
| 893 |
+
*,
|
| 894 |
+
angle_degrees: float,
|
| 895 |
+
image_shape: tuple[int, int] | None,
|
| 896 |
+
) -> tuple[np.ndarray, np.ndarray, float]:
|
| 897 |
+
center_x, center_y, _min_dimension = hough_offset_reference_frame(
|
| 898 |
+
lines,
|
| 899 |
+
line_indices,
|
| 900 |
+
image_shape=image_shape,
|
| 901 |
+
)
|
| 902 |
+
radians = math.radians(angle_degrees)
|
| 903 |
+
normal_x = -math.sin(radians)
|
| 904 |
+
normal_y = math.cos(radians)
|
| 905 |
+
values = []
|
| 906 |
+
for index in line_indices:
|
| 907 |
+
line = lines[index]
|
| 908 |
+
midpoint_x = (line.x1 + line.x2) * 0.5
|
| 909 |
+
midpoint_y = (line.y1 + line.y2) * 0.5
|
| 910 |
+
offset = (midpoint_x - center_x) * normal_x + (midpoint_y - center_y) * normal_y
|
| 911 |
+
values.append((offset, max(1.0, line.length)))
|
| 912 |
+
if not values:
|
| 913 |
+
return np.empty(0), np.empty(0), 0.0
|
| 914 |
+
|
| 915 |
+
lengths = np.array([weight for _offset, weight in values], dtype=np.float64)
|
| 916 |
+
median_length = float(np.median(lengths))
|
| 917 |
+
tolerance = max(1.5, median_length * 0.035)
|
| 918 |
+
if image_shape is not None:
|
| 919 |
+
# Canny commonly returns the two sides of one grout seam as separate
|
| 920 |
+
# Hough segments after rectification. Merge that pair before testing
|
| 921 |
+
# inter-seam periodicity, while keeping adjacent physical seams apart.
|
| 922 |
+
tolerance = max(tolerance, min(image_shape) * 0.024)
|
| 923 |
+
groups: list[list[float]] = []
|
| 924 |
+
for offset, weight in sorted(values, key=lambda item: item[0]):
|
| 925 |
+
if not groups or abs(offset - groups[-1][0]) > tolerance:
|
| 926 |
+
groups.append([offset, weight])
|
| 927 |
+
continue
|
| 928 |
+
previous_offset, previous_weight = groups[-1]
|
| 929 |
+
total_weight = previous_weight + weight
|
| 930 |
+
groups[-1][0] = (previous_offset * previous_weight + offset * weight) / total_weight
|
| 931 |
+
groups[-1][1] = total_weight
|
| 932 |
+
|
| 933 |
+
return (
|
| 934 |
+
np.array([group[0] for group in groups], dtype=np.float64),
|
| 935 |
+
np.array([group[1] for group in groups], dtype=np.float64),
|
| 936 |
+
median_length,
|
| 937 |
+
)
|
| 938 |
+
|
| 939 |
+
|
| 940 |
+
def repeated_offset_periodicity(offsets: np.ndarray, weights: np.ndarray) -> float:
|
| 941 |
+
"""Return how well seam offsets fit one regularly repeating lattice."""
|
| 942 |
+
if len(offsets) < 3:
|
| 943 |
+
return 0.0
|
| 944 |
+
span = float(offsets[-1] - offsets[0])
|
| 945 |
+
if span <= 1e-6:
|
| 946 |
+
return 0.0
|
| 947 |
+
|
| 948 |
+
pairwise = offsets[np.newaxis, :] - offsets[:, np.newaxis]
|
| 949 |
+
distances = pairwise[np.triu_indices(len(offsets), k=1)]
|
| 950 |
+
distances = distances[distances > 1e-6]
|
| 951 |
+
if not len(distances):
|
| 952 |
+
return 0.0
|
| 953 |
+
|
| 954 |
+
minimum_spacing = span / max(40.0, float(len(offsets) * 4))
|
| 955 |
+
candidates = []
|
| 956 |
+
for distance in distances:
|
| 957 |
+
for divisor in range(1, 7):
|
| 958 |
+
spacing = float(distance / divisor)
|
| 959 |
+
if minimum_spacing <= spacing <= span * 0.85:
|
| 960 |
+
candidates.append(spacing)
|
| 961 |
+
if not candidates:
|
| 962 |
+
return 0.0
|
| 963 |
+
|
| 964 |
+
best = 0.0
|
| 965 |
+
weights = np.maximum(np.asarray(weights, dtype=np.float64), 1.0)
|
| 966 |
+
for spacing in candidates:
|
| 967 |
+
normalized = (offsets - offsets[0]) / spacing
|
| 968 |
+
residual = np.abs(normalized - np.rint(normalized))
|
| 969 |
+
alignment = np.exp(-((residual / 0.10) ** 2))
|
| 970 |
+
support = float(np.average(alignment, weights=weights))
|
| 971 |
+
occupied_steps = len(np.unique(np.rint(normalized)))
|
| 972 |
+
coverage = min(1.0, occupied_steps / max(3, len(offsets)))
|
| 973 |
+
best = max(best, support * (0.82 + 0.18 * coverage))
|
| 974 |
+
return best
|
| 975 |
+
|
| 976 |
+
|
| 977 |
+
def offset_span_reference(
|
| 978 |
+
offsets: np.ndarray,
|
| 979 |
+
image_shape: tuple[int, int] | None,
|
| 980 |
+
) -> float:
|
| 981 |
+
if image_shape is not None:
|
| 982 |
+
return float(min(image_shape)) * 0.20
|
| 983 |
+
return max(1e-6, float(offsets[-1] - offsets[0]))
|
| 984 |
+
|
| 985 |
+
|
| 986 |
+
def build_surface_uv_grids(
|
| 987 |
+
*,
|
| 988 |
+
surface_uv: np.ndarray | None,
|
| 989 |
+
surface_indices: np.ndarray | None,
|
| 990 |
+
surface_plane_ids: np.ndarray | None,
|
| 991 |
+
image_shape: tuple[int, int],
|
| 992 |
+
) -> tuple[np.ndarray | None, np.ndarray | None]:
|
| 993 |
+
if surface_uv is None or surface_indices is None:
|
| 994 |
+
return None, None
|
| 995 |
+
|
| 996 |
+
height, width = image_shape
|
| 997 |
+
uv_values = np.asarray(surface_uv, dtype=np.float32)
|
| 998 |
+
indices = np.asarray(surface_indices, dtype=np.int64).reshape(-1)
|
| 999 |
+
if uv_values.ndim != 2 or uv_values.shape[1] != 2 or len(uv_values) != len(indices):
|
| 1000 |
+
return None, None
|
| 1001 |
+
if not len(indices) or np.any(indices < 0) or np.any(indices >= height * width):
|
| 1002 |
+
return None, None
|
| 1003 |
+
|
| 1004 |
+
uv_grid = np.full((height * width, 2), np.nan, dtype=np.float32)
|
| 1005 |
+
uv_grid[indices] = uv_values
|
| 1006 |
+
uv_grid = uv_grid.reshape(height, width, 2)
|
| 1007 |
+
|
| 1008 |
+
plane_grid = None
|
| 1009 |
+
if surface_plane_ids is not None:
|
| 1010 |
+
plane_ids = np.asarray(surface_plane_ids, dtype=np.uint8).reshape(-1)
|
| 1011 |
+
if len(plane_ids) == len(indices):
|
| 1012 |
+
plane_grid = np.full(height * width, 255, dtype=np.uint8)
|
| 1013 |
+
plane_grid[indices] = plane_ids
|
| 1014 |
+
plane_grid = plane_grid.reshape(height, width)
|
| 1015 |
+
|
| 1016 |
+
return uv_grid, plane_grid
|
| 1017 |
+
|
| 1018 |
+
|
| 1019 |
+
def project_lines_to_surface_uv(
|
| 1020 |
+
lines: list[DetectedLine],
|
| 1021 |
+
uv_grid: np.ndarray,
|
| 1022 |
+
plane_grid: np.ndarray | None,
|
| 1023 |
+
) -> list[DetectedLine]:
|
| 1024 |
+
height, width = uv_grid.shape[:2]
|
| 1025 |
+
projected_lines: list[DetectedLine] = []
|
| 1026 |
+
|
| 1027 |
+
for line in lines:
|
| 1028 |
+
sample_count = int(np.clip(round(line.length / 8.0) + 1, 9, 64))
|
| 1029 |
+
fractions = np.linspace(0.0, 1.0, sample_count, dtype=np.float32)
|
| 1030 |
+
xs = np.clip(
|
| 1031 |
+
np.rint(line.x1 + (line.x2 - line.x1) * fractions).astype(np.int32),
|
| 1032 |
+
0,
|
| 1033 |
+
width - 1,
|
| 1034 |
+
)
|
| 1035 |
+
ys = np.clip(
|
| 1036 |
+
np.rint(line.y1 + (line.y2 - line.y1) * fractions).astype(np.int32),
|
| 1037 |
+
0,
|
| 1038 |
+
height - 1,
|
| 1039 |
+
)
|
| 1040 |
+
points = uv_grid[ys, xs]
|
| 1041 |
+
valid = np.isfinite(points).all(axis=1)
|
| 1042 |
+
|
| 1043 |
+
if plane_grid is not None:
|
| 1044 |
+
sampled_planes = plane_grid[ys, xs]
|
| 1045 |
+
valid_planes = sampled_planes[valid & (sampled_planes != 255)]
|
| 1046 |
+
if valid_planes.size:
|
| 1047 |
+
dominant_plane = int(np.bincount(valid_planes).argmax())
|
| 1048 |
+
valid &= sampled_planes == dominant_plane
|
| 1049 |
+
|
| 1050 |
+
if int(valid.sum()) < max(6, int(math.ceil(sample_count * 0.55))):
|
| 1051 |
+
continue
|
| 1052 |
+
|
| 1053 |
+
sampled_points = points[valid].astype(np.float64)
|
| 1054 |
+
center = np.mean(sampled_points, axis=0)
|
| 1055 |
+
_unused, _singular_values, basis = np.linalg.svd(sampled_points - center, full_matrices=False)
|
| 1056 |
+
direction = basis[0]
|
| 1057 |
+
distances = (sampled_points - center) @ direction
|
| 1058 |
+
start = center + direction * float(np.min(distances))
|
| 1059 |
+
end = center + direction * float(np.max(distances))
|
| 1060 |
+
dx = float(end[0] - start[0])
|
| 1061 |
+
dy = float(end[1] - start[1])
|
| 1062 |
+
length = math.hypot(dx, dy)
|
| 1063 |
+
if length <= 1e-5:
|
| 1064 |
+
continue
|
| 1065 |
+
|
| 1066 |
+
projected_lines.append(
|
| 1067 |
+
DetectedLine(
|
| 1068 |
+
x1=float(start[0]),
|
| 1069 |
+
y1=float(start[1]),
|
| 1070 |
+
x2=float(end[0]),
|
| 1071 |
+
y2=float(end[1]),
|
| 1072 |
+
angle_degrees=normalized_line_angle(dx, dy),
|
| 1073 |
+
length=length,
|
| 1074 |
+
)
|
| 1075 |
+
)
|
| 1076 |
+
|
| 1077 |
+
return projected_lines
|
| 1078 |
+
|
| 1079 |
+
|
| 1080 |
+
def normalize_render_transform(
|
| 1081 |
+
value: list[float] | np.ndarray | None,
|
| 1082 |
+
) -> np.ndarray | None:
|
| 1083 |
+
if value is None:
|
| 1084 |
+
return None
|
| 1085 |
+
|
| 1086 |
+
transform = np.asarray(value, dtype=np.float64)
|
| 1087 |
+
if transform.size != 9:
|
| 1088 |
+
return None
|
| 1089 |
+
transform = transform.reshape(3, 3)
|
| 1090 |
+
if not np.isfinite(transform).all() or abs(float(np.linalg.det(transform))) < 1e-10:
|
| 1091 |
+
return None
|
| 1092 |
+
return transform.astype(np.float32)
|
| 1093 |
+
|
| 1094 |
+
|
| 1095 |
+
def transform_detected_lines(
|
| 1096 |
+
lines: list[DetectedLine],
|
| 1097 |
+
transform: np.ndarray,
|
| 1098 |
+
) -> list[DetectedLine]:
|
| 1099 |
+
rectified_lines: list[DetectedLine] = []
|
| 1100 |
+
for line in lines:
|
| 1101 |
+
source_points = np.array([[[line.x1, line.y1], [line.x2, line.y2]]], dtype=np.float32)
|
| 1102 |
+
mapped_points = cv2.perspectiveTransform(source_points, transform)[0]
|
| 1103 |
+
if not np.isfinite(mapped_points).all():
|
| 1104 |
+
continue
|
| 1105 |
+
|
| 1106 |
+
start, end = mapped_points
|
| 1107 |
+
dx = float(end[0] - start[0])
|
| 1108 |
+
dy = float(end[1] - start[1])
|
| 1109 |
+
length = math.hypot(dx, dy)
|
| 1110 |
+
if length <= 1e-5:
|
| 1111 |
+
continue
|
| 1112 |
+
|
| 1113 |
+
rectified_lines.append(
|
| 1114 |
+
DetectedLine(
|
| 1115 |
+
x1=float(start[0]),
|
| 1116 |
+
y1=float(start[1]),
|
| 1117 |
+
x2=float(end[0]),
|
| 1118 |
+
y2=float(end[1]),
|
| 1119 |
+
angle_degrees=normalized_line_angle(dx, dy),
|
| 1120 |
+
length=length,
|
| 1121 |
+
)
|
| 1122 |
+
)
|
| 1123 |
+
|
| 1124 |
+
return rectified_lines
|
| 1125 |
+
|
| 1126 |
+
|
| 1127 |
+
def snap_to_tile_axis(angle_degrees: float) -> float | None:
|
| 1128 |
+
normalized_angle = angle_degrees % 180.0
|
| 1129 |
+
nearest_axis = 0.0 if angular_distance_degrees(normalized_angle, 0.0) <= 45.0 else 90.0
|
| 1130 |
+
if angular_distance_degrees(normalized_angle, nearest_axis) > 28.0:
|
| 1131 |
+
return None
|
| 1132 |
+
return nearest_axis
|
| 1133 |
+
|
| 1134 |
+
|
| 1135 |
+
def cluster_line_families(
|
| 1136 |
+
lines: list[DetectedLine],
|
| 1137 |
+
*,
|
| 1138 |
+
image_shape: tuple[int, int] | None = None,
|
| 1139 |
+
) -> list[LineFamilyCluster]:
|
| 1140 |
+
raw_clusters: list[list[int]] = []
|
| 1141 |
+
|
| 1142 |
+
for line_index in sorted(range(len(lines)), key=lambda index: lines[index].length, reverse=True):
|
| 1143 |
+
line_angle = lines[line_index].angle_degrees
|
| 1144 |
+
best_cluster_index = None
|
| 1145 |
+
best_distance = float("inf")
|
| 1146 |
+
|
| 1147 |
+
for cluster_index, cluster_indices in enumerate(raw_clusters):
|
| 1148 |
+
cluster_angle, _concentration, _weight = line_family_stats(lines, cluster_indices)
|
| 1149 |
+
distance = angular_distance_degrees(line_angle, cluster_angle)
|
| 1150 |
+
if distance <= 10.0 and distance < best_distance:
|
| 1151 |
+
best_cluster_index = cluster_index
|
| 1152 |
+
best_distance = distance
|
| 1153 |
+
|
| 1154 |
+
if best_cluster_index is None:
|
| 1155 |
+
raw_clusters.append([line_index])
|
| 1156 |
+
else:
|
| 1157 |
+
raw_clusters[best_cluster_index].append(line_index)
|
| 1158 |
+
|
| 1159 |
+
raw_clusters = merge_nearby_line_family_clusters(lines, raw_clusters)
|
| 1160 |
+
return [
|
| 1161 |
+
build_line_family_cluster(lines, cluster_indices, image_shape=image_shape)
|
| 1162 |
+
for cluster_indices in raw_clusters
|
| 1163 |
+
if cluster_indices
|
| 1164 |
+
]
|
| 1165 |
+
|
| 1166 |
+
|
| 1167 |
+
def merge_nearby_line_family_clusters(
|
| 1168 |
+
lines: list[DetectedLine],
|
| 1169 |
+
raw_clusters: list[list[int]],
|
| 1170 |
+
) -> list[list[int]]:
|
| 1171 |
+
merged_clusters = [list(cluster) for cluster in raw_clusters]
|
| 1172 |
+
changed = True
|
| 1173 |
+
|
| 1174 |
+
while changed and len(merged_clusters) > 1:
|
| 1175 |
+
changed = False
|
| 1176 |
+
for first_index in range(len(merged_clusters)):
|
| 1177 |
+
first_angle, _first_concentration, _first_weight = line_family_stats(
|
| 1178 |
+
lines,
|
| 1179 |
+
merged_clusters[first_index],
|
| 1180 |
+
)
|
| 1181 |
+
for second_index in range(first_index + 1, len(merged_clusters)):
|
| 1182 |
+
second_angle, _second_concentration, _second_weight = line_family_stats(
|
| 1183 |
+
lines,
|
| 1184 |
+
merged_clusters[second_index],
|
| 1185 |
+
)
|
| 1186 |
+
if angular_distance_degrees(first_angle, second_angle) > 8.0:
|
| 1187 |
+
continue
|
| 1188 |
+
|
| 1189 |
+
merged_clusters[first_index].extend(merged_clusters[second_index])
|
| 1190 |
+
del merged_clusters[second_index]
|
| 1191 |
+
changed = True
|
| 1192 |
+
break
|
| 1193 |
+
if changed:
|
| 1194 |
+
break
|
| 1195 |
+
|
| 1196 |
+
return merged_clusters
|
| 1197 |
+
|
| 1198 |
+
|
| 1199 |
+
def build_line_family_cluster(
|
| 1200 |
+
lines: list[DetectedLine],
|
| 1201 |
+
line_indices: list[int],
|
| 1202 |
+
*,
|
| 1203 |
+
image_shape: tuple[int, int] | None = None,
|
| 1204 |
+
) -> LineFamilyCluster:
|
| 1205 |
+
angle, concentration, weight = line_family_stats(lines, line_indices)
|
| 1206 |
+
distinct_offset_count = count_distinct_line_offsets(
|
| 1207 |
+
lines,
|
| 1208 |
+
line_indices,
|
| 1209 |
+
angle_degrees=angle,
|
| 1210 |
+
image_shape=image_shape,
|
| 1211 |
+
)
|
| 1212 |
+
score = line_family_selection_score(
|
| 1213 |
+
weight=weight,
|
| 1214 |
+
concentration=concentration,
|
| 1215 |
+
line_count=len(line_indices),
|
| 1216 |
+
distinct_offset_count=distinct_offset_count,
|
| 1217 |
+
)
|
| 1218 |
+
return LineFamilyCluster(
|
| 1219 |
+
line_indices=list(line_indices),
|
| 1220 |
+
angle_degrees=angle,
|
| 1221 |
+
weight=weight,
|
| 1222 |
+
concentration=concentration,
|
| 1223 |
+
distinct_offset_count=distinct_offset_count,
|
| 1224 |
+
score=score,
|
| 1225 |
+
)
|
| 1226 |
+
|
| 1227 |
+
|
| 1228 |
+
def line_family_stats(
|
| 1229 |
+
lines: list[DetectedLine],
|
| 1230 |
+
line_indices: list[int],
|
| 1231 |
+
) -> tuple[float, float, float]:
|
| 1232 |
+
angles = np.array([lines[index].angle_degrees for index in line_indices], dtype=np.float64)
|
| 1233 |
+
weights = np.array([max(1.0, lines[index].length) for index in line_indices], dtype=np.float64)
|
| 1234 |
+
total_weight = float(np.sum(weights))
|
| 1235 |
+
if total_weight <= 0.0:
|
| 1236 |
+
return 0.0, 0.0, 0.0
|
| 1237 |
+
|
| 1238 |
+
angle, concentration = circular_mean_with_concentration(angles, weights)
|
| 1239 |
+
return angle, concentration, total_weight
|
| 1240 |
+
|
| 1241 |
+
|
| 1242 |
+
def count_distinct_line_offsets(
|
| 1243 |
+
lines: list[DetectedLine],
|
| 1244 |
+
line_indices: list[int],
|
| 1245 |
+
*,
|
| 1246 |
+
angle_degrees: float,
|
| 1247 |
+
image_shape: tuple[int, int] | None = None,
|
| 1248 |
+
) -> int:
|
| 1249 |
+
if not line_indices:
|
| 1250 |
+
return 0
|
| 1251 |
+
|
| 1252 |
+
center_x, center_y, min_dimension = hough_offset_reference_frame(
|
| 1253 |
+
lines,
|
| 1254 |
+
line_indices,
|
| 1255 |
+
image_shape=image_shape,
|
| 1256 |
+
)
|
| 1257 |
+
tolerance = max(6.0, min_dimension * 0.018)
|
| 1258 |
+
radians = math.radians(angle_degrees)
|
| 1259 |
+
normal_x = -math.sin(radians)
|
| 1260 |
+
normal_y = math.cos(radians)
|
| 1261 |
+
|
| 1262 |
+
offsets = []
|
| 1263 |
+
for index in line_indices:
|
| 1264 |
+
line = lines[index]
|
| 1265 |
+
midpoint_x = (line.x1 + line.x2) * 0.5
|
| 1266 |
+
midpoint_y = (line.y1 + line.y2) * 0.5
|
| 1267 |
+
rho = (midpoint_x - center_x) * normal_x + (midpoint_y - center_y) * normal_y
|
| 1268 |
+
offsets.append((rho, max(1.0, line.length)))
|
| 1269 |
+
|
| 1270 |
+
offset_groups: list[list[float]] = []
|
| 1271 |
+
for rho, weight in sorted(offsets, key=lambda item: item[0]):
|
| 1272 |
+
if not offset_groups or abs(rho - offset_groups[-1][0]) > tolerance:
|
| 1273 |
+
offset_groups.append([rho, weight])
|
| 1274 |
+
continue
|
| 1275 |
+
|
| 1276 |
+
previous_rho, previous_weight = offset_groups[-1]
|
| 1277 |
+
combined_weight = previous_weight + weight
|
| 1278 |
+
offset_groups[-1][0] = (previous_rho * previous_weight + rho * weight) / combined_weight
|
| 1279 |
+
offset_groups[-1][1] = combined_weight
|
| 1280 |
+
|
| 1281 |
+
return len(offset_groups)
|
| 1282 |
+
|
| 1283 |
+
|
| 1284 |
+
def hough_offset_reference_frame(
|
| 1285 |
+
lines: list[DetectedLine],
|
| 1286 |
+
line_indices: list[int],
|
| 1287 |
+
*,
|
| 1288 |
+
image_shape: tuple[int, int] | None = None,
|
| 1289 |
+
) -> tuple[float, float, float]:
|
| 1290 |
+
if image_shape is not None:
|
| 1291 |
+
height, width = image_shape
|
| 1292 |
+
min_dimension = max(1.0, float(min(width, height)))
|
| 1293 |
+
return (width - 1) * 0.5, (height - 1) * 0.5, min_dimension
|
| 1294 |
+
|
| 1295 |
+
xs: list[float] = []
|
| 1296 |
+
ys: list[float] = []
|
| 1297 |
+
for index in line_indices:
|
| 1298 |
+
line = lines[index]
|
| 1299 |
+
xs.extend([float(line.x1), float(line.x2)])
|
| 1300 |
+
ys.extend([float(line.y1), float(line.y2)])
|
| 1301 |
+
|
| 1302 |
+
min_x = min(xs) if xs else 0.0
|
| 1303 |
+
max_x = max(xs) if xs else 1.0
|
| 1304 |
+
min_y = min(ys) if ys else 0.0
|
| 1305 |
+
max_y = max(ys) if ys else 1.0
|
| 1306 |
+
width = max(1.0, max_x - min_x)
|
| 1307 |
+
height = max(1.0, max_y - min_y)
|
| 1308 |
+
return min_x + width * 0.5, min_y + height * 0.5, min(width, height)
|
| 1309 |
+
|
| 1310 |
+
|
| 1311 |
+
def line_family_selection_score(
|
| 1312 |
+
*,
|
| 1313 |
+
weight: float,
|
| 1314 |
+
concentration: float,
|
| 1315 |
+
line_count: int,
|
| 1316 |
+
distinct_offset_count: int,
|
| 1317 |
+
) -> float:
|
| 1318 |
+
distinct_bonus = min(6, max(0, distinct_offset_count - 1))
|
| 1319 |
+
line_bonus = min(8, max(0, line_count - 1))
|
| 1320 |
+
repeated_line_multiplier = 1.0 + 0.18 * distinct_bonus + 0.05 * line_bonus
|
| 1321 |
+
return weight * max(0.35, concentration) * repeated_line_multiplier
|
| 1322 |
+
|
| 1323 |
+
|
| 1324 |
+
def detect_secondary_grid_angle(
|
| 1325 |
+
*,
|
| 1326 |
+
lines: list[DetectedLine],
|
| 1327 |
+
primary_angle_degrees: float,
|
| 1328 |
+
primary_line_count: int,
|
| 1329 |
+
) -> float | None:
|
| 1330 |
+
if len(lines) < 8 or primary_line_count < 4:
|
| 1331 |
+
return None
|
| 1332 |
+
|
| 1333 |
+
target_angle = (primary_angle_degrees + 90.0) % 180.0
|
| 1334 |
+
secondary_lines = [
|
| 1335 |
+
line
|
| 1336 |
+
for line in lines
|
| 1337 |
+
if angular_distance_degrees(line.angle_degrees, target_angle) <= 14.0
|
| 1338 |
+
]
|
| 1339 |
+
if len(secondary_lines) < max(4, int(round(primary_line_count * 0.35))):
|
| 1340 |
+
return None
|
| 1341 |
+
|
| 1342 |
+
primary_weight = sum(
|
| 1343 |
+
line.length
|
| 1344 |
+
for line in lines
|
| 1345 |
+
if angular_distance_degrees(line.angle_degrees, primary_angle_degrees) <= 14.0
|
| 1346 |
+
)
|
| 1347 |
+
secondary_weight = sum(line.length for line in secondary_lines)
|
| 1348 |
+
if secondary_weight < max(120.0, primary_weight * 0.24):
|
| 1349 |
+
return None
|
| 1350 |
+
|
| 1351 |
+
angle, concentration = circular_mean_with_concentration(
|
| 1352 |
+
np.array([line.angle_degrees for line in secondary_lines], dtype=np.float64),
|
| 1353 |
+
np.array([line.length for line in secondary_lines], dtype=np.float64),
|
| 1354 |
+
)
|
| 1355 |
+
if concentration < 0.76:
|
| 1356 |
+
return None
|
| 1357 |
+
|
| 1358 |
+
return angle
|
| 1359 |
+
|
| 1360 |
+
|
| 1361 |
+
def estimate_texture_orientation(
|
| 1362 |
+
image_bgr: np.ndarray,
|
| 1363 |
+
mask: np.ndarray,
|
| 1364 |
+
) -> TextureOrientation | None:
|
| 1365 |
+
component_mask = largest_mask_component(mask)
|
| 1366 |
+
texture_mask = erode_mask(component_mask)
|
| 1367 |
+
if int(np.count_nonzero(texture_mask)) == 0:
|
| 1368 |
+
texture_mask = component_mask
|
| 1369 |
+
|
| 1370 |
+
height, width = image_bgr.shape[:2]
|
| 1371 |
+
floor_pixels = int(np.count_nonzero(texture_mask))
|
| 1372 |
+
if floor_pixels < max(500, int(height * width * 0.015)):
|
| 1373 |
+
return None
|
| 1374 |
+
|
| 1375 |
+
gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)
|
| 1376 |
+
inside_pixels = gray[texture_mask > 0]
|
| 1377 |
+
fill_value = int(np.median(inside_pixels)) if inside_pixels.size else int(np.median(gray))
|
| 1378 |
+
prepared = gray.copy()
|
| 1379 |
+
prepared[texture_mask == 0] = fill_value
|
| 1380 |
+
|
| 1381 |
+
clahe = cv2.createCLAHE(clipLimit=1.7, tileGridSize=(8, 8))
|
| 1382 |
+
enhanced = clahe.apply(prepared)
|
| 1383 |
+
blurred = cv2.GaussianBlur(enhanced, (3, 3), 0)
|
| 1384 |
+
|
| 1385 |
+
gradient_x = cv2.Scharr(blurred, cv2.CV_32F, 1, 0)
|
| 1386 |
+
gradient_y = cv2.Scharr(blurred, cv2.CV_32F, 0, 1)
|
| 1387 |
+
gradient_magnitude = cv2.magnitude(gradient_x, gradient_y)
|
| 1388 |
+
|
| 1389 |
+
valid_magnitudes = gradient_magnitude[texture_mask > 0]
|
| 1390 |
+
valid_magnitudes = valid_magnitudes[valid_magnitudes > 0]
|
| 1391 |
+
if valid_magnitudes.size < 200:
|
| 1392 |
+
return None
|
| 1393 |
+
|
| 1394 |
+
low_threshold = max(3.0, float(np.percentile(valid_magnitudes, 45)))
|
| 1395 |
+
high_threshold = float(np.percentile(valid_magnitudes, 97))
|
| 1396 |
+
if high_threshold <= low_threshold:
|
| 1397 |
+
high_threshold = float(np.max(valid_magnitudes))
|
| 1398 |
+
|
| 1399 |
+
valid_texture = (
|
| 1400 |
+
(texture_mask > 0)
|
| 1401 |
+
& (gradient_magnitude >= low_threshold)
|
| 1402 |
+
& (gradient_magnitude <= high_threshold)
|
| 1403 |
+
)
|
| 1404 |
+
|
| 1405 |
+
cell_size = max(28, int(round(min(width, height) * 0.07)))
|
| 1406 |
+
angles: list[float] = []
|
| 1407 |
+
weights: list[float] = []
|
| 1408 |
+
|
| 1409 |
+
for y in range(0, height, cell_size):
|
| 1410 |
+
for x in range(0, width, cell_size):
|
| 1411 |
+
cell_valid = valid_texture[y : y + cell_size, x : x + cell_size]
|
| 1412 |
+
valid_count = int(np.count_nonzero(cell_valid))
|
| 1413 |
+
if valid_count < max(40, int(cell_size * cell_size * 0.08)):
|
| 1414 |
+
continue
|
| 1415 |
+
|
| 1416 |
+
cell_gx = gradient_x[y : y + cell_size, x : x + cell_size][cell_valid]
|
| 1417 |
+
cell_gy = gradient_y[y : y + cell_size, x : x + cell_size][cell_valid]
|
| 1418 |
+
cell_mag = gradient_magnitude[y : y + cell_size, x : x + cell_size][cell_valid]
|
| 1419 |
+
|
| 1420 |
+
tensor_xx = float(np.sum(cell_gx * cell_gx))
|
| 1421 |
+
tensor_yy = float(np.sum(cell_gy * cell_gy))
|
| 1422 |
+
tensor_xy = float(np.sum(cell_gx * cell_gy))
|
| 1423 |
+
energy = tensor_xx + tensor_yy
|
| 1424 |
+
if energy <= 0.0:
|
| 1425 |
+
continue
|
| 1426 |
+
|
| 1427 |
+
coherence = math.sqrt((tensor_xx - tensor_yy) ** 2 + 4.0 * tensor_xy**2) / energy
|
| 1428 |
+
if coherence < 0.12:
|
| 1429 |
+
continue
|
| 1430 |
+
|
| 1431 |
+
gradient_angle = math.degrees(
|
| 1432 |
+
0.5 * math.atan2(2.0 * tensor_xy, tensor_xx - tensor_yy)
|
| 1433 |
+
)
|
| 1434 |
+
line_angle = (gradient_angle + 90.0) % 180.0
|
| 1435 |
+
median_mag = float(np.median(cell_mag))
|
| 1436 |
+
weights.append(coherence * math.log1p(median_mag) * math.sqrt(valid_count))
|
| 1437 |
+
angles.append(line_angle)
|
| 1438 |
+
|
| 1439 |
+
if len(angles) < 4:
|
| 1440 |
+
return None
|
| 1441 |
+
|
| 1442 |
+
angle_array = np.array(angles, dtype=np.float64)
|
| 1443 |
+
weight_array = np.array(weights, dtype=np.float64)
|
| 1444 |
+
if float(np.sum(weight_array)) <= 0.0:
|
| 1445 |
+
return None
|
| 1446 |
+
|
| 1447 |
+
cap = float(np.percentile(weight_array, 85))
|
| 1448 |
+
if cap > 0:
|
| 1449 |
+
weight_array = np.minimum(weight_array, cap)
|
| 1450 |
+
|
| 1451 |
+
angle, concentration = circular_mean_with_concentration(angle_array, weight_array)
|
| 1452 |
+
support_score = min(1.0, len(angles) / 18.0)
|
| 1453 |
+
confidence = max(0.0, min(1.0, (0.65 * concentration + 0.35 * support_score)))
|
| 1454 |
+
confidence *= support_score
|
| 1455 |
+
|
| 1456 |
+
if confidence < 0.22 or concentration < 0.22:
|
| 1457 |
+
return None
|
| 1458 |
+
|
| 1459 |
+
return TextureOrientation(
|
| 1460 |
+
angle_degrees=angle,
|
| 1461 |
+
confidence=confidence,
|
| 1462 |
+
support=len(angles),
|
| 1463 |
+
concentration=concentration,
|
| 1464 |
+
)
|
| 1465 |
+
|
| 1466 |
+
|
| 1467 |
+
def select_orientation(
|
| 1468 |
+
hough_orientation: tuple[float, list[DetectedLine], float, float, float] | None,
|
| 1469 |
+
texture_orientation: TextureOrientation | None,
|
| 1470 |
+
warnings: list[str],
|
| 1471 |
+
) -> tuple[float, str] | None:
|
| 1472 |
+
if hough_orientation is None and texture_orientation is None:
|
| 1473 |
+
return None
|
| 1474 |
+
|
| 1475 |
+
if hough_orientation is None:
|
| 1476 |
+
return texture_orientation.angle_degrees, "texture" if texture_orientation else None
|
| 1477 |
+
|
| 1478 |
+
hough_angle, dominant_lines, peak_weight_ratio, concentration, orthogonal_ratio = hough_orientation
|
| 1479 |
+
if texture_orientation is None:
|
| 1480 |
+
return hough_angle, "hough"
|
| 1481 |
+
|
| 1482 |
+
hough_quality = hough_orientation_quality(
|
| 1483 |
+
dominant_line_count=len(dominant_lines),
|
| 1484 |
+
peak_weight_ratio=peak_weight_ratio,
|
| 1485 |
+
concentration=concentration,
|
| 1486 |
+
orthogonal_ratio=orthogonal_ratio,
|
| 1487 |
+
)
|
| 1488 |
+
texture_quality = texture_orientation.confidence
|
| 1489 |
+
distance = angular_distance_degrees(hough_angle, texture_orientation.angle_degrees)
|
| 1490 |
+
|
| 1491 |
+
if is_strong_hough_grout_orientation(
|
| 1492 |
+
dominant_line_count=len(dominant_lines),
|
| 1493 |
+
peak_weight_ratio=peak_weight_ratio,
|
| 1494 |
+
concentration=concentration,
|
| 1495 |
+
orthogonal_ratio=orthogonal_ratio,
|
| 1496 |
+
):
|
| 1497 |
+
if distance > 10.0:
|
| 1498 |
+
warnings.append("strong_grout_lines_used_over_texture")
|
| 1499 |
+
return hough_angle, "hough"
|
| 1500 |
+
|
| 1501 |
+
if distance <= 10.0:
|
| 1502 |
+
angle = circular_mean_degrees(
|
| 1503 |
+
[hough_angle, texture_orientation.angle_degrees],
|
| 1504 |
+
[max(hough_quality, 0.1), max(texture_quality, 0.1)],
|
| 1505 |
+
)
|
| 1506 |
+
return angle, "combined"
|
| 1507 |
+
|
| 1508 |
+
if (
|
| 1509 |
+
texture_quality >= 0.42
|
| 1510 |
+
and texture_orientation.support >= 6
|
| 1511 |
+
and (
|
| 1512 |
+
hough_quality < 0.62
|
| 1513 |
+
or len(dominant_lines) < 8
|
| 1514 |
+
or peak_weight_ratio < 0.56
|
| 1515 |
+
or orthogonal_ratio > 0.45
|
| 1516 |
+
)
|
| 1517 |
+
):
|
| 1518 |
+
warnings.append("hough_texture_disagreement_using_texture")
|
| 1519 |
+
return texture_orientation.angle_degrees, "texture"
|
| 1520 |
+
|
| 1521 |
+
if texture_quality >= hough_quality + 0.16 and texture_orientation.support >= 8:
|
| 1522 |
+
warnings.append("hough_texture_disagreement_using_texture")
|
| 1523 |
+
return texture_orientation.angle_degrees, "texture"
|
| 1524 |
+
|
| 1525 |
+
if hough_quality >= texture_quality + 0.18:
|
| 1526 |
+
warnings.append("hough_texture_disagreement_using_hough")
|
| 1527 |
+
return hough_angle, "hough"
|
| 1528 |
+
|
| 1529 |
+
angle = circular_mean_degrees(
|
| 1530 |
+
[hough_angle, texture_orientation.angle_degrees],
|
| 1531 |
+
[max(hough_quality, 0.1), max(texture_quality, 0.1)],
|
| 1532 |
+
)
|
| 1533 |
+
warnings.append("hough_texture_orientation_combined_after_disagreement")
|
| 1534 |
+
return angle, "combined"
|
| 1535 |
+
|
| 1536 |
+
|
| 1537 |
+
def hough_orientation_quality(
|
| 1538 |
+
*,
|
| 1539 |
+
dominant_line_count: int,
|
| 1540 |
+
peak_weight_ratio: float,
|
| 1541 |
+
concentration: float,
|
| 1542 |
+
orthogonal_ratio: float,
|
| 1543 |
+
) -> float:
|
| 1544 |
+
line_support = min(1.0, dominant_line_count / 12.0)
|
| 1545 |
+
orthogonal_penalty = max(0.0, 1.0 - min(1.0, orthogonal_ratio))
|
| 1546 |
+
return max(
|
| 1547 |
+
0.0,
|
| 1548 |
+
min(
|
| 1549 |
+
1.0,
|
| 1550 |
+
0.28 * line_support
|
| 1551 |
+
+ 0.32 * max(0.0, min(1.0, peak_weight_ratio))
|
| 1552 |
+
+ 0.30 * max(0.0, min(1.0, concentration))
|
| 1553 |
+
+ 0.10 * orthogonal_penalty,
|
| 1554 |
+
),
|
| 1555 |
+
)
|
| 1556 |
+
|
| 1557 |
+
|
| 1558 |
+
def is_strong_hough_grout_orientation(
|
| 1559 |
+
*,
|
| 1560 |
+
dominant_line_count: int,
|
| 1561 |
+
peak_weight_ratio: float,
|
| 1562 |
+
concentration: float,
|
| 1563 |
+
orthogonal_ratio: float,
|
| 1564 |
+
) -> bool:
|
| 1565 |
+
return (
|
| 1566 |
+
dominant_line_count >= 8
|
| 1567 |
+
and peak_weight_ratio >= 0.58
|
| 1568 |
+
and concentration >= 0.86
|
| 1569 |
+
and orthogonal_ratio <= 0.48
|
| 1570 |
+
) or (
|
| 1571 |
+
dominant_line_count >= 12
|
| 1572 |
+
and peak_weight_ratio >= 0.50
|
| 1573 |
+
and concentration >= 0.82
|
| 1574 |
+
and orthogonal_ratio <= 0.55
|
| 1575 |
+
)
|
| 1576 |
+
|
| 1577 |
+
|
| 1578 |
+
def circular_mean_degrees(angles: list[float], weights: list[float]) -> float:
|
| 1579 |
+
angle, _concentration = circular_mean_with_concentration(
|
| 1580 |
+
np.array(angles, dtype=np.float64),
|
| 1581 |
+
np.array(weights, dtype=np.float64),
|
| 1582 |
+
)
|
| 1583 |
+
return angle
|
| 1584 |
+
|
| 1585 |
+
|
| 1586 |
+
def circular_mean_with_concentration(
|
| 1587 |
+
angles: np.ndarray,
|
| 1588 |
+
weights: np.ndarray,
|
| 1589 |
+
) -> tuple[float, float]:
|
| 1590 |
+
total_weight = float(np.sum(weights))
|
| 1591 |
+
if total_weight <= 0.0:
|
| 1592 |
+
return 0.0, 0.0
|
| 1593 |
+
|
| 1594 |
+
doubled_angles = np.deg2rad(angles * 2.0)
|
| 1595 |
+
vector_x = float(np.sum(np.cos(doubled_angles) * weights))
|
| 1596 |
+
vector_y = float(np.sum(np.sin(doubled_angles) * weights))
|
| 1597 |
+
angle = (math.degrees(math.atan2(vector_y, vector_x)) / 2.0) % 180.0
|
| 1598 |
+
concentration = math.hypot(vector_x, vector_y) / total_weight
|
| 1599 |
+
return angle, concentration
|
| 1600 |
+
|
| 1601 |
+
|
| 1602 |
+
def normalized_line_angle(dx: float, dy: float) -> float:
|
| 1603 |
+
angle = math.degrees(math.atan2(dy, dx)) % 180.0
|
| 1604 |
+
if angle >= 180.0:
|
| 1605 |
+
angle -= 180.0
|
| 1606 |
+
return angle
|
| 1607 |
+
|
| 1608 |
+
|
| 1609 |
+
def angular_distance_degrees(first: float, second: float) -> float:
|
| 1610 |
+
diff = abs((first - second) % 180.0)
|
| 1611 |
+
return min(diff, 180.0 - diff)
|
| 1612 |
+
|
| 1613 |
+
|
| 1614 |
+
def score_confidence(
|
| 1615 |
+
*,
|
| 1616 |
+
segmentation_confidence: float,
|
| 1617 |
+
floor_area_ratio: float,
|
| 1618 |
+
line_count: int,
|
| 1619 |
+
dominant_line_count: int,
|
| 1620 |
+
peak_weight_ratio: float,
|
| 1621 |
+
concentration: float,
|
| 1622 |
+
) -> float:
|
| 1623 |
+
segmentation_score = max(0.0, min(1.0, segmentation_confidence))
|
| 1624 |
+
area_score = max(0.0, min(1.0, floor_area_ratio / 0.28))
|
| 1625 |
+
line_score = max(0.0, min(1.0, line_count / 30.0))
|
| 1626 |
+
dominant_count_score = max(0.0, min(1.0, dominant_line_count / 14.0))
|
| 1627 |
+
peak_score = max(0.0, min(1.0, peak_weight_ratio))
|
| 1628 |
+
concentration_score = max(0.0, min(1.0, concentration))
|
| 1629 |
+
|
| 1630 |
+
score = (
|
| 1631 |
+
0.18 * segmentation_score
|
| 1632 |
+
+ 0.10 * area_score
|
| 1633 |
+
+ 0.18 * line_score
|
| 1634 |
+
+ 0.16 * dominant_count_score
|
| 1635 |
+
+ 0.24 * peak_score
|
| 1636 |
+
+ 0.14 * concentration_score
|
| 1637 |
+
)
|
| 1638 |
+
return max(0.0, min(1.0, score))
|
| 1639 |
+
|
| 1640 |
+
|
| 1641 |
+
def score_texture_confidence(
|
| 1642 |
+
*,
|
| 1643 |
+
segmentation_confidence: float,
|
| 1644 |
+
floor_area_ratio: float,
|
| 1645 |
+
texture_confidence: float,
|
| 1646 |
+
) -> float:
|
| 1647 |
+
segmentation_score = max(0.0, min(1.0, segmentation_confidence))
|
| 1648 |
+
area_score = max(0.0, min(1.0, floor_area_ratio / 0.28))
|
| 1649 |
+
texture_score = max(0.0, min(1.0, texture_confidence))
|
| 1650 |
+
score = 0.20 * segmentation_score + 0.14 * area_score + 0.66 * texture_score
|
| 1651 |
+
return max(0.0, min(1.0, score))
|
| 1652 |
+
|
| 1653 |
+
|
| 1654 |
+
def final_orientation_confidence(
|
| 1655 |
+
*,
|
| 1656 |
+
source: str,
|
| 1657 |
+
hough_confidence: float,
|
| 1658 |
+
texture_confidence: float,
|
| 1659 |
+
) -> float:
|
| 1660 |
+
if source == "texture":
|
| 1661 |
+
return texture_confidence
|
| 1662 |
+
if source == "combined":
|
| 1663 |
+
return max(hough_confidence, texture_confidence) * 0.96
|
| 1664 |
+
return hough_confidence
|
| 1665 |
+
|
| 1666 |
+
|
| 1667 |
+
def label_direction(angle_degrees: float) -> str:
|
| 1668 |
+
if angle_degrees < 10.0 or angle_degrees >= 170.0:
|
| 1669 |
+
return "left_to_right"
|
| 1670 |
+
if angle_degrees < 35.0:
|
| 1671 |
+
return "slight_down_right"
|
| 1672 |
+
if angle_degrees < 70.0:
|
| 1673 |
+
return "diagonal_down_right"
|
| 1674 |
+
if angle_degrees < 110.0:
|
| 1675 |
+
return "top_to_bottom"
|
| 1676 |
+
if angle_degrees < 145.0:
|
| 1677 |
+
return "diagonal_up_right"
|
| 1678 |
+
return "slight_up_right"
|
| 1679 |
+
|
| 1680 |
+
|
| 1681 |
+
def create_overlay(
|
| 1682 |
+
image_bgr: np.ndarray,
|
| 1683 |
+
mask: np.ndarray,
|
| 1684 |
+
_lines: list[DetectedLine],
|
| 1685 |
+
angle_degrees: float | None,
|
| 1686 |
+
secondary_angle_degrees: float | None = None,
|
| 1687 |
+
) -> np.ndarray:
|
| 1688 |
+
overlay = image_bgr.copy()
|
| 1689 |
+
if secondary_angle_degrees is not None:
|
| 1690 |
+
draw_direction_line(overlay, mask, secondary_angle_degrees, color_bgr=(255, 210, 20))
|
| 1691 |
+
if angle_degrees is not None:
|
| 1692 |
+
draw_direction_line(overlay, mask, angle_degrees, color_bgr=(0, 255, 80))
|
| 1693 |
+
|
| 1694 |
+
return overlay
|
| 1695 |
+
|
| 1696 |
+
|
| 1697 |
+
def draw_direction_line(
|
| 1698 |
+
image_bgr: np.ndarray,
|
| 1699 |
+
mask: np.ndarray,
|
| 1700 |
+
angle_degrees: float,
|
| 1701 |
+
*,
|
| 1702 |
+
color_bgr: tuple[int, int, int],
|
| 1703 |
+
) -> None:
|
| 1704 |
+
endpoints = direction_line_endpoints(mask, angle_degrees)
|
| 1705 |
+
if endpoints is None:
|
| 1706 |
+
return
|
| 1707 |
+
|
| 1708 |
+
start, end = endpoints
|
| 1709 |
+
min_dimension = min(mask.shape[:2])
|
| 1710 |
+
thickness = max(5, int(round(min_dimension / 155)))
|
| 1711 |
+
|
| 1712 |
+
cv2.line(image_bgr, start, end, (0, 0, 0), thickness + 6, cv2.LINE_AA)
|
| 1713 |
+
cv2.line(image_bgr, start, end, color_bgr, thickness, cv2.LINE_AA)
|
| 1714 |
+
cv2.circle(image_bgr, start, thickness + 1, color_bgr, -1, cv2.LINE_AA)
|
| 1715 |
+
cv2.circle(image_bgr, end, thickness + 1, color_bgr, -1, cv2.LINE_AA)
|
| 1716 |
+
|
| 1717 |
+
|
| 1718 |
+
def direction_line_endpoints(
|
| 1719 |
+
mask: np.ndarray,
|
| 1720 |
+
angle_degrees: float,
|
| 1721 |
+
) -> tuple[tuple[int, int], tuple[int, int]] | None:
|
| 1722 |
+
component_mask = largest_mask_component(mask)
|
| 1723 |
+
points = cv2.findNonZero(component_mask)
|
| 1724 |
+
if points is None:
|
| 1725 |
+
return None
|
| 1726 |
+
|
| 1727 |
+
height, width = mask.shape[:2]
|
| 1728 |
+
floor_points = points.reshape(-1, 2).astype(np.float64)
|
| 1729 |
+
center = floor_points.mean(axis=0)
|
| 1730 |
+
center_x = int(round(center[0]))
|
| 1731 |
+
center_y = int(round(center[1]))
|
| 1732 |
+
|
| 1733 |
+
if (
|
| 1734 |
+
not (0 <= center_x < width and 0 <= center_y < height)
|
| 1735 |
+
or component_mask[center_y, center_x] == 0
|
| 1736 |
+
):
|
| 1737 |
+
distances = np.sum((floor_points - center) ** 2, axis=1)
|
| 1738 |
+
center = floor_points[int(np.argmin(distances))]
|
| 1739 |
+
|
| 1740 |
+
unit = np.array(
|
| 1741 |
+
[
|
| 1742 |
+
math.cos(math.radians(angle_degrees)),
|
| 1743 |
+
math.sin(math.radians(angle_degrees)),
|
| 1744 |
+
],
|
| 1745 |
+
dtype=np.float64,
|
| 1746 |
+
)
|
| 1747 |
+
projections = (floor_points - center) @ unit
|
| 1748 |
+
min_projection = float(np.percentile(projections, 1))
|
| 1749 |
+
max_projection = float(np.percentile(projections, 99))
|
| 1750 |
+
sample_count = max(2, int(round(max_projection - min_projection)) + 1)
|
| 1751 |
+
sample_count = min(sample_count, max(width, height) * 3)
|
| 1752 |
+
|
| 1753 |
+
samples = np.linspace(min_projection, max_projection, sample_count)
|
| 1754 |
+
active_samples: list[float] = []
|
| 1755 |
+
runs: list[list[float]] = []
|
| 1756 |
+
current_run: list[float] = []
|
| 1757 |
+
|
| 1758 |
+
for sample in samples:
|
| 1759 |
+
x, y = center + sample * unit
|
| 1760 |
+
ix = int(round(x))
|
| 1761 |
+
iy = int(round(y))
|
| 1762 |
+
is_inside = 0 <= ix < width and 0 <= iy < height and component_mask[iy, ix] > 0
|
| 1763 |
+
if is_inside:
|
| 1764 |
+
current_run.append(float(sample))
|
| 1765 |
+
active_samples.append(float(sample))
|
| 1766 |
+
elif current_run:
|
| 1767 |
+
runs.append(current_run)
|
| 1768 |
+
current_run = []
|
| 1769 |
+
|
| 1770 |
+
if current_run:
|
| 1771 |
+
runs.append(current_run)
|
| 1772 |
+
|
| 1773 |
+
if runs:
|
| 1774 |
+
best_run = max(runs, key=len)
|
| 1775 |
+
start_projection = best_run[0]
|
| 1776 |
+
end_projection = best_run[-1]
|
| 1777 |
+
elif active_samples:
|
| 1778 |
+
start_projection = min(active_samples)
|
| 1779 |
+
end_projection = max(active_samples)
|
| 1780 |
+
else:
|
| 1781 |
+
start_projection = min_projection
|
| 1782 |
+
end_projection = max_projection
|
| 1783 |
+
|
| 1784 |
+
minimum_length = max(30.0, min(width, height) * 0.08)
|
| 1785 |
+
if end_projection - start_projection < minimum_length:
|
| 1786 |
+
midpoint = (start_projection + end_projection) / 2.0
|
| 1787 |
+
start_projection = midpoint - minimum_length / 2.0
|
| 1788 |
+
end_projection = midpoint + minimum_length / 2.0
|
| 1789 |
+
|
| 1790 |
+
start = center + start_projection * unit
|
| 1791 |
+
end = center + end_projection * unit
|
| 1792 |
+
return clip_point_to_image(start, width, height), clip_point_to_image(end, width, height)
|
| 1793 |
+
|
| 1794 |
+
|
| 1795 |
+
def largest_mask_component(mask: np.ndarray) -> np.ndarray:
|
| 1796 |
+
binary_mask = np.where(mask > 0, 255, 0).astype(np.uint8)
|
| 1797 |
+
component_count, labels, stats, _centroids = cv2.connectedComponentsWithStats(binary_mask, 8)
|
| 1798 |
+
if component_count <= 1:
|
| 1799 |
+
return binary_mask
|
| 1800 |
+
|
| 1801 |
+
largest_label = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA]))
|
| 1802 |
+
return np.where(labels == largest_label, 255, 0).astype(np.uint8)
|
| 1803 |
+
|
| 1804 |
+
|
| 1805 |
+
def clip_point_to_image(
|
| 1806 |
+
point: np.ndarray,
|
| 1807 |
+
width: int,
|
| 1808 |
+
height: int,
|
| 1809 |
+
) -> tuple[int, int]:
|
| 1810 |
+
x = int(round(float(point[0])))
|
| 1811 |
+
y = int(round(float(point[1])))
|
| 1812 |
+
return max(0, min(width - 1, x)), max(0, min(height - 1, y))
|
| 1813 |
+
|
frontend/viz2d-demo/e2e/README.md
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { expect, test, type Page } from "@playwright/test";
|
| 2 |
+
|
| 3 |
+
const WIDTH = 120;
|
| 4 |
+
const HEIGHT = 72;
|
| 5 |
+
|
| 6 |
+
for (const renderer of ["webgl", "canvas"] as const) {
|
| 7 |
+
test(`applied tile preserves scene lighting in ${renderer}`, async ({ page }) => {
|
| 8 |
+
if (renderer === "canvas") {
|
| 9 |
+
await disableWebGl(page);
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
await page.goto("/");
|
| 13 |
+
await page.getByTestId("room-file-input").setInputFiles({
|
| 14 |
+
name: "lighting.vizbundle.json",
|
| 15 |
+
mimeType: "application/json",
|
| 16 |
+
buffer: Buffer.from(JSON.stringify(buildLightingBundle())),
|
| 17 |
+
});
|
| 18 |
+
|
| 19 |
+
await expect(page.getByTestId("visualizer-editor")).toBeVisible();
|
| 20 |
+
await expect(page.getByTestId("surface-card")).toBeVisible();
|
| 21 |
+
await page.getByTestId("surface-card").click();
|
| 22 |
+
await expect(page.getByTestId("texture-selector")).toBeVisible();
|
| 23 |
+
await page.getByTestId("texture-card").filter({ hasText: "White Wood Flooring" }).click();
|
| 24 |
+
await expect(page.getByTestId("texture-selector")).toBeHidden();
|
| 25 |
+
await expect(page.getByTestId("surface-card").filter({ hasText: "White Wood Flooring" })).toBeVisible();
|
| 26 |
+
await page.mouse.move(4, 4);
|
| 27 |
+
|
| 28 |
+
const luminance = await readLightingRegions(page);
|
| 29 |
+
expect(luminance.dark, "deep source shadow should fully cover the applied tile").toBeLessThan(luminance.neutral * 0.55);
|
| 30 |
+
// Near-white tiles saturate before preserving a large relative ratio.
|
| 31 |
+
expect(luminance.bright, "bright source region should remain visibly illuminated").toBeGreaterThan(luminance.neutral + 15);
|
| 32 |
+
expect(luminance.bright, "bright source region should approach white").toBeGreaterThan(240);
|
| 33 |
+
});
|
| 34 |
+
|
| 35 |
+
test(`applied tile fully covers the floor-mask edge in ${renderer}`, async ({ page }) => {
|
| 36 |
+
if (renderer === "canvas") {
|
| 37 |
+
await disableWebGl(page);
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
await page.goto("/");
|
| 41 |
+
await page.getByTestId("room-file-input").setInputFiles({
|
| 42 |
+
name: "edge-coverage.vizbundle.json",
|
| 43 |
+
mimeType: "application/json",
|
| 44 |
+
buffer: Buffer.from(JSON.stringify(buildEdgeCoverageBundle())),
|
| 45 |
+
});
|
| 46 |
+
|
| 47 |
+
await expect(page.getByTestId("visualizer-editor")).toBeVisible();
|
| 48 |
+
await page.getByTestId("surface-card").click();
|
| 49 |
+
await page.getByTestId("texture-card").filter({ hasText: "White Wood Flooring" }).click();
|
| 50 |
+
await expect(page.getByTestId("texture-selector")).toBeHidden();
|
| 51 |
+
|
| 52 |
+
const colors = await readEdgeColors(page);
|
| 53 |
+
expect(colors.boundary.green, "first floor pixels should have full tile coverage").toBeGreaterThan(
|
| 54 |
+
colors.interior.green * 0.82,
|
| 55 |
+
);
|
| 56 |
+
expect(colors.outside.green, "tile should not bleed outside the floor mask").toBeLessThan(50);
|
| 57 |
+
expect(colors.outside.red).toBeGreaterThan(200);
|
| 58 |
+
expect(colors.outside.blue).toBeGreaterThan(200);
|
| 59 |
+
});
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
function buildLightingBundle() {
|
| 63 |
+
const pixelCount = WIDTH * HEIGHT;
|
| 64 |
+
const pixels = new Uint8Array(pixelCount * 4);
|
| 65 |
+
const mask = new Uint32Array(pixelCount);
|
| 66 |
+
const shadeMap = new Uint8Array(pixelCount);
|
| 67 |
+
|
| 68 |
+
for (let index = 0; index < pixelCount; index += 1) {
|
| 69 |
+
const x = index % WIDTH;
|
| 70 |
+
const sourceValue = x < 40 ? 70 : x >= 80 ? 220 : 145;
|
| 71 |
+
const shade = x < 40 ? 0.14 : x >= 80 ? 1.5 : 1;
|
| 72 |
+
const pixelIndex = index * 4;
|
| 73 |
+
pixels[pixelIndex] = sourceValue;
|
| 74 |
+
pixels[pixelIndex + 1] = sourceValue;
|
| 75 |
+
pixels[pixelIndex + 2] = sourceValue;
|
| 76 |
+
pixels[pixelIndex + 3] = 255;
|
| 77 |
+
mask[index] = index;
|
| 78 |
+
shadeMap[index] = Math.round(((shade - 0.08) / (1.85 - 0.08)) * 255);
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
return {
|
| 82 |
+
format: "baetes-vizbundle",
|
| 83 |
+
bundleVersion: 3,
|
| 84 |
+
width: WIDTH,
|
| 85 |
+
height: HEIGHT,
|
| 86 |
+
pixels: Buffer.from(pixels).toString("base64"),
|
| 87 |
+
segments: [
|
| 88 |
+
{
|
| 89 |
+
id: 0,
|
| 90 |
+
className: "floor",
|
| 91 |
+
mask: Buffer.from(mask.buffer).toString("base64"),
|
| 92 |
+
homography: null,
|
| 93 |
+
plane: null,
|
| 94 |
+
shadeMap: Buffer.from(shadeMap).toString("base64"),
|
| 95 |
+
showroomShadeMap: null,
|
| 96 |
+
reflectionMap: null,
|
| 97 |
+
metadata: {
|
| 98 |
+
lightingSource: "synthetic-test",
|
| 99 |
+
lightingTransferVersion: 3,
|
| 100 |
+
shadeMapEncoding: "linear-relative",
|
| 101 |
+
shadeMapRange: [0.08, 1.85],
|
| 102 |
+
renderPresetDefaults: {
|
| 103 |
+
preset: "realistic",
|
| 104 |
+
shadingStrength: 1,
|
| 105 |
+
},
|
| 106 |
+
},
|
| 107 |
+
},
|
| 108 |
+
],
|
| 109 |
+
};
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
function buildEdgeCoverageBundle() {
|
| 113 |
+
const pixelCount = WIDTH * HEIGHT;
|
| 114 |
+
const pixels = new Uint8Array(pixelCount * 4);
|
| 115 |
+
const maskValues: number[] = [];
|
| 116 |
+
const shadeMap = new Uint8Array(pixelCount);
|
| 117 |
+
const neutralShade = Math.round(((1 - 0.08) / (1.85 - 0.08)) * 255);
|
| 118 |
+
|
| 119 |
+
for (let index = 0; index < pixelCount; index += 1) {
|
| 120 |
+
const x = index % WIDTH;
|
| 121 |
+
const y = Math.floor(index / WIDTH);
|
| 122 |
+
const pixelIndex = index * 4;
|
| 123 |
+
pixels[pixelIndex] = 230;
|
| 124 |
+
pixels[pixelIndex + 1] = 20;
|
| 125 |
+
pixels[pixelIndex + 2] = 230;
|
| 126 |
+
pixels[pixelIndex + 3] = 255;
|
| 127 |
+
shadeMap[index] = neutralShade;
|
| 128 |
+
if (x >= 10 && x < 110 && y >= 8 && y < 64) {
|
| 129 |
+
maskValues.push(index);
|
| 130 |
+
}
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
const mask = Uint32Array.from(maskValues);
|
| 134 |
+
return {
|
| 135 |
+
format: "baetes-vizbundle",
|
| 136 |
+
bundleVersion: 3,
|
| 137 |
+
width: WIDTH,
|
| 138 |
+
height: HEIGHT,
|
| 139 |
+
pixels: Buffer.from(pixels).toString("base64"),
|
| 140 |
+
segments: [
|
| 141 |
+
{
|
| 142 |
+
id: 0,
|
| 143 |
+
className: "floor",
|
| 144 |
+
mask: Buffer.from(mask.buffer).toString("base64"),
|
| 145 |
+
homography: null,
|
| 146 |
+
plane: null,
|
| 147 |
+
shadeMap: Buffer.from(shadeMap).toString("base64"),
|
| 148 |
+
showroomShadeMap: null,
|
| 149 |
+
reflectionMap: null,
|
| 150 |
+
metadata: {
|
| 151 |
+
lightingTransferVersion: 3,
|
| 152 |
+
shadeMapEncoding: "linear-relative",
|
| 153 |
+
shadeMapRange: [0.08, 1.85],
|
| 154 |
+
renderPresetDefaults: {
|
| 155 |
+
preset: "realistic",
|
| 156 |
+
shadingStrength: 1,
|
| 157 |
+
},
|
| 158 |
+
},
|
| 159 |
+
},
|
| 160 |
+
],
|
| 161 |
+
};
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
async function disableWebGl(page: Page) {
|
| 165 |
+
await page.addInitScript(() => {
|
| 166 |
+
const originalGetContext = HTMLCanvasElement.prototype.getContext;
|
| 167 |
+
HTMLCanvasElement.prototype.getContext = function getContext(
|
| 168 |
+
this: HTMLCanvasElement,
|
| 169 |
+
contextId: string,
|
| 170 |
+
...args: unknown[]
|
| 171 |
+
) {
|
| 172 |
+
if (contextId === "webgl2") return null;
|
| 173 |
+
return originalGetContext.call(this, contextId as "2d", ...args as []);
|
| 174 |
+
} as typeof HTMLCanvasElement.prototype.getContext;
|
| 175 |
+
});
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
async function readLightingRegions(page: Page) {
|
| 179 |
+
return page.getByTestId("visualizer-canvas").evaluate((node) => {
|
| 180 |
+
const canvas = node as HTMLCanvasElement;
|
| 181 |
+
const context = canvas.getContext("2d", { willReadFrequently: true });
|
| 182 |
+
if (!context) throw new Error("Canvas does not expose a 2D context.");
|
| 183 |
+
const image = context.getImageData(0, 0, canvas.width, canvas.height);
|
| 184 |
+
|
| 185 |
+
const meanLuminance = (startX: number, endX: number) => {
|
| 186 |
+
let total = 0;
|
| 187 |
+
let count = 0;
|
| 188 |
+
for (let y = 8; y < canvas.height - 8; y += 1) {
|
| 189 |
+
for (let x = startX; x < endX; x += 1) {
|
| 190 |
+
const index = (y * canvas.width + x) * 4;
|
| 191 |
+
total += (
|
| 192 |
+
image.data[index] * 0.2126 +
|
| 193 |
+
image.data[index + 1] * 0.7152 +
|
| 194 |
+
image.data[index + 2] * 0.0722
|
| 195 |
+
);
|
| 196 |
+
count += 1;
|
| 197 |
+
}
|
| 198 |
+
}
|
| 199 |
+
return total / Math.max(count, 1);
|
| 200 |
+
};
|
| 201 |
+
|
| 202 |
+
return {
|
| 203 |
+
dark: meanLuminance(8, 32),
|
| 204 |
+
neutral: meanLuminance(48, 72),
|
| 205 |
+
bright: meanLuminance(88, 112),
|
| 206 |
+
};
|
| 207 |
+
});
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
async function readEdgeColors(page: Page) {
|
| 211 |
+
return page.getByTestId("visualizer-canvas").evaluate((node) => {
|
| 212 |
+
const canvas = node as HTMLCanvasElement;
|
| 213 |
+
const context = canvas.getContext("2d", { willReadFrequently: true });
|
| 214 |
+
if (!context) throw new Error("Canvas does not expose a 2D context.");
|
| 215 |
+
const image = context.getImageData(0, 0, canvas.width, canvas.height);
|
| 216 |
+
|
| 217 |
+
const meanColor = (startX: number, endX: number) => {
|
| 218 |
+
const total = [0, 0, 0];
|
| 219 |
+
let count = 0;
|
| 220 |
+
for (let y = 16; y < 56; y += 1) {
|
| 221 |
+
for (let x = startX; x < endX; x += 1) {
|
| 222 |
+
const index = (y * canvas.width + x) * 4;
|
| 223 |
+
total[0] += image.data[index];
|
| 224 |
+
total[1] += image.data[index + 1];
|
| 225 |
+
total[2] += image.data[index + 2];
|
| 226 |
+
count += 1;
|
| 227 |
+
}
|
| 228 |
+
}
|
| 229 |
+
return {
|
| 230 |
+
red: total[0] / count,
|
| 231 |
+
green: total[1] / count,
|
| 232 |
+
blue: total[2] / count,
|
| 233 |
+
};
|
| 234 |
+
};
|
| 235 |
+
|
| 236 |
+
return {
|
| 237 |
+
outside: meanColor(8, 10),
|
| 238 |
+
boundary: meanColor(10, 12),
|
| 239 |
+
interior: meanColor(14, 16),
|
| 240 |
+
};
|
| 241 |
+
});
|
| 242 |
+
}
|
frontend/viz2d-demo/e2e/real-room-qa.spec.ts
ADDED
|
@@ -0,0 +1,598 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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/package-lock.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
frontend/viz2d-demo/package.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "@viz/admin",
|
| 3 |
+
"private": true,
|
| 4 |
+
"version": "0.0.0",
|
| 5 |
+
"type": "module",
|
| 6 |
+
"scripts": {
|
| 7 |
+
"dev": "vite --host",
|
| 8 |
+
"build": "tsc -b && vite build",
|
| 9 |
+
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
|
| 10 |
+
"preview": "vite preview",
|
| 11 |
+
"qa:e2e": "playwright test",
|
| 12 |
+
"qa:e2e:headed": "playwright test --headed",
|
| 13 |
+
"qa:report": "node scripts/build-qa-summary.mjs",
|
| 14 |
+
"qa:real": "npm run build && playwright test"
|
| 15 |
+
},
|
| 16 |
+
"dependencies": {
|
| 17 |
+
"@radix-ui/react-dialog": "^1.1.15",
|
| 18 |
+
"@radix-ui/react-popover": "^1.1.15",
|
| 19 |
+
"@radix-ui/react-scroll-area": "^1.2.10",
|
| 20 |
+
"@radix-ui/react-slot": "^1.2.4",
|
| 21 |
+
"@radix-ui/react-tooltip": "^1.2.8",
|
| 22 |
+
"@viz2d/core": "^0.1.0",
|
| 23 |
+
"@viz2d/sdk": "^0.1.3",
|
| 24 |
+
"class-variance-authority": "^0.7.1",
|
| 25 |
+
"clsx": "^2.1.1",
|
| 26 |
+
"lucide-react": "^0.424.0",
|
| 27 |
+
"react": "^18.3.1",
|
| 28 |
+
"react-dom": "^18.3.1",
|
| 29 |
+
"react-router-dom": "^6.26.0",
|
| 30 |
+
"sonner": "^2.0.7",
|
| 31 |
+
"tailwind-merge": "^3.4.0",
|
| 32 |
+
"vite-plugin-wasm": "^3.5.0"
|
| 33 |
+
},
|
| 34 |
+
"devDependencies": {
|
| 35 |
+
"@playwright/test": "^1.61.1",
|
| 36 |
+
"@types/node": "^22.1.0",
|
| 37 |
+
"@types/react": "^18.3.3",
|
| 38 |
+
"@types/react-beautiful-dnd": "^13.1.8",
|
| 39 |
+
"@types/react-dom": "^18.3.0",
|
| 40 |
+
"@typescript-eslint/eslint-plugin": "^7.15.0",
|
| 41 |
+
"@typescript-eslint/parser": "^7.15.0",
|
| 42 |
+
"@vitejs/plugin-react": "^4.3.1",
|
| 43 |
+
"autoprefixer": "^10.4.20",
|
| 44 |
+
"eslint": "^8.57.0",
|
| 45 |
+
"eslint-plugin-react-hooks": "^4.6.2",
|
| 46 |
+
"eslint-plugin-react-refresh": "^0.4.7",
|
| 47 |
+
"postcss": "^8.4.41",
|
| 48 |
+
"tailwindcss": "^3.4.7",
|
| 49 |
+
"tailwindcss-animate": "^1.0.7",
|
| 50 |
+
"typescript": "^5.2.2",
|
| 51 |
+
"vite": "^5.3.4"
|
| 52 |
+
}
|
| 53 |
+
}
|
frontend/viz2d-demo/playwright.config.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
});
|
frontend/viz2d-demo/scripts/build-qa-summary.mjs
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env node
|
| 2 |
+
|
| 3 |
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
| 4 |
+
import { existsSync } from "node:fs";
|
| 5 |
+
import path from "node:path";
|
| 6 |
+
|
| 7 |
+
const cwd = process.cwd();
|
| 8 |
+
const reportPath = path.resolve(cwd, process.argv[2] ?? "test-results/real-qa.json");
|
| 9 |
+
const outputPath = path.resolve(cwd, process.argv[3] ?? "test-results/qa-summary.md");
|
| 10 |
+
const outputDir = path.dirname(outputPath);
|
| 11 |
+
|
| 12 |
+
try {
|
| 13 |
+
await main();
|
| 14 |
+
} catch (error) {
|
| 15 |
+
await writeFailureSummary(error);
|
| 16 |
+
console.error(error);
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
async function main() {
|
| 20 |
+
await mkdir(outputDir, { recursive: true });
|
| 21 |
+
|
| 22 |
+
if (!existsSync(reportPath)) {
|
| 23 |
+
await writeFile(
|
| 24 |
+
outputPath,
|
| 25 |
+
[
|
| 26 |
+
"# Real Browser QA Summary",
|
| 27 |
+
"",
|
| 28 |
+
`Playwright JSON report was not found at \`${relativeToCwd(reportPath)}\`.`,
|
| 29 |
+
"",
|
| 30 |
+
"Run the Playwright suite first so this summary can include screenshots and Gemini judgments.",
|
| 31 |
+
"",
|
| 32 |
+
].join("\n"),
|
| 33 |
+
);
|
| 34 |
+
console.warn(`QA summary skipped source report: ${relativeToCwd(reportPath)}`);
|
| 35 |
+
return;
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
const report = JSON.parse(await readFile(reportPath, "utf8"));
|
| 39 |
+
const entries = collectEntries(report);
|
| 40 |
+
const hydratedEntries = [];
|
| 41 |
+
|
| 42 |
+
for (const entry of entries) {
|
| 43 |
+
const result = finalResult(entry.test);
|
| 44 |
+
const groupedEntries = await groupedCaseEntries(entry, result);
|
| 45 |
+
if (groupedEntries.length) {
|
| 46 |
+
hydratedEntries.push(...groupedEntries);
|
| 47 |
+
continue;
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
const beforeImage = await imageAttachmentDataUri(result, "before-canvas");
|
| 51 |
+
const afterImage = await imageAttachmentDataUri(result, "after-texture-canvas");
|
| 52 |
+
const geminiAttachment = findAttachment(result, "gemini-judge");
|
| 53 |
+
const gemini = geminiAttachment ? parseJsonLoose(await readTextAttachment(geminiAttachment)) : null;
|
| 54 |
+
|
| 55 |
+
hydratedEntries.push({
|
| 56 |
+
...entry,
|
| 57 |
+
afterImage,
|
| 58 |
+
beforeImage,
|
| 59 |
+
gemini,
|
| 60 |
+
result,
|
| 61 |
+
status: displayStatus(entry.test, result),
|
| 62 |
+
});
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
await writeFile(outputPath, buildMarkdown(hydratedEntries));
|
| 66 |
+
console.log(`QA markdown summary written to ${relativeToCwd(outputPath)}`);
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
function collectEntries(report) {
|
| 70 |
+
const entries = [];
|
| 71 |
+
|
| 72 |
+
for (const suite of asArray(report.suites)) {
|
| 73 |
+
collectSuite(suite, entries);
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
return entries;
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
async function writeFailureSummary(error) {
|
| 80 |
+
await mkdir(outputDir, { recursive: true });
|
| 81 |
+
const message = error instanceof Error ? error.stack ?? error.message : String(error);
|
| 82 |
+
|
| 83 |
+
await writeFile(
|
| 84 |
+
outputPath,
|
| 85 |
+
[
|
| 86 |
+
"# Real Browser QA Summary",
|
| 87 |
+
"",
|
| 88 |
+
"The compact Markdown summary could not be generated.",
|
| 89 |
+
"",
|
| 90 |
+
`Source report: \`${relativeToCwd(reportPath)}\``,
|
| 91 |
+
"",
|
| 92 |
+
"```text",
|
| 93 |
+
message,
|
| 94 |
+
"```",
|
| 95 |
+
"",
|
| 96 |
+
"The full Playwright artifacts are still available in this artifact bundle.",
|
| 97 |
+
"",
|
| 98 |
+
].join("\n"),
|
| 99 |
+
);
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
function collectSuite(suite, entries) {
|
| 103 |
+
for (const spec of asArray(suite.specs)) {
|
| 104 |
+
const title = typeof spec.title === "string" && spec.title.trim() ? spec.title.trim() : "Untitled QA case";
|
| 105 |
+
for (const test of asArray(spec.tests)) {
|
| 106 |
+
entries.push({ spec, test, title });
|
| 107 |
+
}
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
for (const child of asArray(suite.suites)) {
|
| 111 |
+
collectSuite(child, entries);
|
| 112 |
+
}
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
function finalResult(test) {
|
| 116 |
+
const results = asArray(test.results);
|
| 117 |
+
return results[results.length - 1] ?? {};
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
function displayStatus(test, result) {
|
| 121 |
+
const resultStatus = typeof result.status === "string" ? result.status : "";
|
| 122 |
+
const testStatus = typeof test.status === "string" ? test.status : "";
|
| 123 |
+
|
| 124 |
+
if (resultStatus) return resultStatus;
|
| 125 |
+
if (testStatus === "expected") return "passed";
|
| 126 |
+
if (testStatus === "unexpected") return "failed";
|
| 127 |
+
return testStatus || "unknown";
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
async function groupedCaseEntries(entry, result) {
|
| 131 |
+
const metas = await groupedCaseMetas(result);
|
| 132 |
+
const hydratedEntries = [];
|
| 133 |
+
|
| 134 |
+
for (const { meta, prefix } of metas) {
|
| 135 |
+
const beforeImage = await imageAttachmentDataUri(result, `${prefix}-before-canvas`);
|
| 136 |
+
const afterImage = await imageAttachmentDataUri(result, `${prefix}-after-texture-canvas`);
|
| 137 |
+
const geminiAttachment = findAttachment(result, `${prefix}-gemini-judge`);
|
| 138 |
+
const gemini = geminiAttachment ? parseJsonLoose(await readTextAttachment(geminiAttachment)) : null;
|
| 139 |
+
const imageTitle = meta.imageName || meta.roomName || imageName(entry.title);
|
| 140 |
+
const tileName = meta.tileName || "Unknown tile";
|
| 141 |
+
|
| 142 |
+
hydratedEntries.push({
|
| 143 |
+
...entry,
|
| 144 |
+
afterImage,
|
| 145 |
+
beforeImage,
|
| 146 |
+
gemini,
|
| 147 |
+
result,
|
| 148 |
+
status: typeof meta.status === "string" ? meta.status : displayStatus(entry.test, result),
|
| 149 |
+
title: `${imageTitle}: apply ${tileName}`,
|
| 150 |
+
});
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
return hydratedEntries;
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
async function groupedCaseMetas(result) {
|
| 157 |
+
const metas = [];
|
| 158 |
+
for (const attachment of asArray(result.attachments)) {
|
| 159 |
+
const name = typeof attachment?.name === "string" ? attachment.name : "";
|
| 160 |
+
if (!name.startsWith("qa-case-") || !name.endsWith("-meta")) continue;
|
| 161 |
+
const meta = parseJsonLoose(await readTextAttachment(attachment));
|
| 162 |
+
if (!meta || typeof meta !== "object" || Array.isArray(meta)) continue;
|
| 163 |
+
metas.push({
|
| 164 |
+
meta,
|
| 165 |
+
prefix: typeof meta.attachmentPrefix === "string" && meta.attachmentPrefix
|
| 166 |
+
? meta.attachmentPrefix
|
| 167 |
+
: name.slice(0, -"-meta".length),
|
| 168 |
+
});
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
return metas.sort((left, right) => Number(left.meta.caseIndex ?? 0) - Number(right.meta.caseIndex ?? 0));
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
async function imageAttachmentDataUri(result, attachmentName) {
|
| 175 |
+
const attachment = findAttachment(result, attachmentName);
|
| 176 |
+
if (!attachment) return null;
|
| 177 |
+
|
| 178 |
+
const sourcePath = resolveAttachmentPath(attachment.path);
|
| 179 |
+
const contentType = imageContentType(attachment);
|
| 180 |
+
|
| 181 |
+
if (sourcePath) {
|
| 182 |
+
const buffer = await readFile(sourcePath);
|
| 183 |
+
return `data:${contentType};base64,${buffer.toString("base64")}`;
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
if (typeof attachment.body === "string") {
|
| 187 |
+
return `data:${contentType};base64,${attachment.body}`;
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
return null;
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
function findAttachment(result, name) {
|
| 194 |
+
return asArray(result.attachments).find((attachment) => attachment?.name === name) ?? null;
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
async function readTextAttachment(attachment) {
|
| 198 |
+
const sourcePath = resolveAttachmentPath(attachment.path);
|
| 199 |
+
if (sourcePath) return readFile(sourcePath, "utf8");
|
| 200 |
+
|
| 201 |
+
if (typeof attachment.body !== "string") return "";
|
| 202 |
+
|
| 203 |
+
const direct = attachment.body.trim();
|
| 204 |
+
if (direct.startsWith("{") || direct.startsWith("[")) return attachment.body;
|
| 205 |
+
|
| 206 |
+
return Buffer.from(attachment.body, "base64").toString("utf8");
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
function resolveAttachmentPath(value) {
|
| 210 |
+
if (typeof value !== "string" || !value.trim()) return null;
|
| 211 |
+
|
| 212 |
+
const candidates = [
|
| 213 |
+
path.isAbsolute(value) ? value : path.resolve(cwd, value),
|
| 214 |
+
path.resolve(path.dirname(reportPath), value),
|
| 215 |
+
];
|
| 216 |
+
|
| 217 |
+
return candidates.find((candidate) => existsSync(candidate)) ?? null;
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
function parseJsonLoose(text) {
|
| 221 |
+
if (!text.trim()) return null;
|
| 222 |
+
|
| 223 |
+
try {
|
| 224 |
+
return JSON.parse(text);
|
| 225 |
+
} catch {
|
| 226 |
+
const match = text.match(/\{[\s\S]*\}/);
|
| 227 |
+
if (!match) return null;
|
| 228 |
+
try {
|
| 229 |
+
return JSON.parse(match[0]);
|
| 230 |
+
} catch {
|
| 231 |
+
return null;
|
| 232 |
+
}
|
| 233 |
+
}
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
function buildMarkdown(entries) {
|
| 237 |
+
const passed = entries.filter((entry) => entry.status === "passed").length;
|
| 238 |
+
const skipped = entries.filter((entry) => entry.status === "skipped").length;
|
| 239 |
+
const needsReview = entries.length - passed - skipped;
|
| 240 |
+
const lines = [
|
| 241 |
+
"# Real Browser QA Summary",
|
| 242 |
+
"",
|
| 243 |
+
`Generated from \`${relativeToCwd(reportPath)}\`.`,
|
| 244 |
+
"",
|
| 245 |
+
`Total images: ${entries.length}`,
|
| 246 |
+
`Passed: ${passed}`,
|
| 247 |
+
`Needs review: ${needsReview}`,
|
| 248 |
+
`Skipped: ${skipped}`,
|
| 249 |
+
"",
|
| 250 |
+
];
|
| 251 |
+
|
| 252 |
+
for (const [index, entry] of entries.entries()) {
|
| 253 |
+
lines.push("", `## ${index + 1}. ${escapeHeading(imageName(entry.title))}`, "");
|
| 254 |
+
lines.push(`Status: **${entry.status}**`, "");
|
| 255 |
+
lines.push("### Before", "");
|
| 256 |
+
lines.push(imageTag(entry.beforeImage), "");
|
| 257 |
+
lines.push("### After Tile Applied", "");
|
| 258 |
+
lines.push(imageTag(entry.afterImage), "");
|
| 259 |
+
lines.push("", "### Gemini Judgment", "");
|
| 260 |
+
lines.push(...geminiSummary(entry.gemini));
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
return `${lines.join("\n")}\n`;
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
function geminiSummary(gemini) {
|
| 267 |
+
if (!gemini) {
|
| 268 |
+
return ["No Gemini judgment attachment was found for this image.", ""];
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
const lines = [
|
| 272 |
+
`- Overall pass: ${yesNo(gemini.overallPass)}`,
|
| 273 |
+
`- Tile applied: ${yesNo(gemini.tileApplied)}`,
|
| 274 |
+
`- Coverage gap detected: ${yesNo(gemini.coverageGapDetected)}`,
|
| 275 |
+
`- Missed floor areas: ${listOrNone(gemini.missedFloorAreas)}`,
|
| 276 |
+
`- Direction mismatch detected: ${yesNo(gemini.directionMismatchDetected)}`,
|
| 277 |
+
`- Direction issues: ${listOrNone(gemini.directionIssues)}`,
|
| 278 |
+
`- Bleed detected: ${yesNo(gemini.bleedDetected)}`,
|
| 279 |
+
`- Scores: surface ${score(gemini.surfaceCorrectness)}, edge ${score(gemini.edgeCompleteness)}, occlusion ${score(gemini.occlusionBoundaryQuality)}, perspective ${score(gemini.perspectiveQuality)}, direction ${score(gemini.directionQuality)}, lighting ${score(gemini.lightingPreserved)}, realism ${score(gemini.realism)}`,
|
| 280 |
+
`- Notes: ${gemini.notes ?? "none"}`,
|
| 281 |
+
"",
|
| 282 |
+
];
|
| 283 |
+
|
| 284 |
+
return lines;
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
function imageTag(relativePath) {
|
| 288 |
+
if (!relativePath) return "Missing screenshot";
|
| 289 |
+
return `<img src="${relativePath}" width="720" />`;
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
function yesNo(value) {
|
| 293 |
+
return typeof value === "boolean" ? (value ? "yes" : "no") : "n/a";
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
function score(value) {
|
| 297 |
+
return typeof value === "number" && Number.isFinite(value) ? value.toFixed(2) : "n/a";
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
function listOrNone(value) {
|
| 301 |
+
return Array.isArray(value) && value.length > 0 ? value.join("; ") : "none";
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
function imageContentType(attachment) {
|
| 305 |
+
if (typeof attachment.contentType === "string" && attachment.contentType.startsWith("image/")) {
|
| 306 |
+
return attachment.contentType;
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
const extension = typeof attachment.path === "string" ? path.extname(attachment.path).toLowerCase() : "";
|
| 310 |
+
if (extension === ".jpg" || extension === ".jpeg") return "image/jpeg";
|
| 311 |
+
if (extension === ".webp") return "image/webp";
|
| 312 |
+
return "image/png";
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
function imageName(title) {
|
| 316 |
+
return title.split(": apply ")[0] || title;
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
function escapeHeading(value) {
|
| 320 |
+
return String(value).replace(/\n/g, " ").trim();
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
function asArray(value) {
|
| 324 |
+
return Array.isArray(value) ? value : [];
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
function relativeToCwd(value) {
|
| 328 |
+
return path.relative(cwd, value).replaceAll(path.sep, "/") || ".";
|
| 329 |
+
}
|
requirements-base.txt
CHANGED
|
@@ -1,10 +1,12 @@
|
|
| 1 |
aiofiles==24.1.0
|
|
|
|
| 2 |
fastapi==0.115.12
|
| 3 |
huggingface-hub==0.32.0
|
| 4 |
numpy==2.2.6
|
| 5 |
opencv-python-headless==4.11.0.86
|
| 6 |
pillow==11.2.1
|
| 7 |
python-multipart==0.0.20
|
|
|
|
| 8 |
safetensors==0.5.3
|
| 9 |
timm==1.0.15
|
| 10 |
tokenizers==0.20.3
|
|
|
|
| 1 |
aiofiles==24.1.0
|
| 2 |
+
boto3>=1.34,<2
|
| 3 |
fastapi==0.115.12
|
| 4 |
huggingface-hub==0.32.0
|
| 5 |
numpy==2.2.6
|
| 6 |
opencv-python-headless==4.11.0.86
|
| 7 |
pillow==11.2.1
|
| 8 |
python-multipart==0.0.20
|
| 9 |
+
python-dotenv>=1.0,<2
|
| 10 |
safetensors==0.5.3
|
| 11 |
timm==1.0.15
|
| 12 |
tokenizers==0.20.3
|
requirements-gpu-cu126.txt
CHANGED
|
@@ -4,3 +4,4 @@ torch==2.7.0+cu126
|
|
| 4 |
torchvision==0.22.0+cu126
|
| 5 |
triton==3.3.0
|
| 6 |
git+https://github.com/microsoft/MoGe.git
|
|
|
|
|
|
| 4 |
torchvision==0.22.0+cu126
|
| 5 |
triton==3.3.0
|
| 6 |
git+https://github.com/microsoft/MoGe.git
|
| 7 |
+
git+https://github.com/facebookresearch/sam2.git
|
test_floor_geometry.py
CHANGED
|
@@ -1,239 +1,1134 @@
|
|
| 1 |
-
import unittest
|
|
|
|
|
|
|
|
|
|
| 2 |
|
|
|
|
| 3 |
import numpy as np
|
|
|
|
|
|
|
| 4 |
|
| 5 |
import app
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
|
| 9 |
-
def test_surface_uv_quality_keeps_smooth_complete_uvs(self):
|
| 10 |
-
height, width = 60, 80
|
| 11 |
-
yy, xx = np.mgrid[0:height, 0:width]
|
| 12 |
-
surface = np.ones((height, width), dtype=np.uint8)
|
| 13 |
-
surface_indices = np.flatnonzero(surface.ravel()).astype(np.uint32)
|
| 14 |
-
uv = np.column_stack((
|
| 15 |
-
xx.ravel()[surface_indices] * 0.02,
|
| 16 |
-
yy.ravel()[surface_indices] * 0.02,
|
| 17 |
-
)).astype(np.float32)
|
| 18 |
-
plane_ids = np.zeros(len(surface_indices), dtype=np.uint8)
|
| 19 |
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
|
| 27 |
-
height, width = 60, 80
|
| 28 |
-
yy, xx = np.mgrid[0:height, 0:width]
|
| 29 |
-
surface = np.ones((height, width), dtype=np.uint8)
|
| 30 |
-
surface_indices = np.flatnonzero(surface.ravel()).astype(np.uint32)
|
| 31 |
-
uv_grid = np.dstack((xx * 0.02, yy * 0.02)).astype(np.float32)
|
| 32 |
-
uv_grid[:20, 40::2, 0] += 4.0
|
| 33 |
-
uv = uv_grid.reshape(-1, 2)[surface_indices]
|
| 34 |
-
plane_ids = np.zeros(len(surface_indices), dtype=np.uint8)
|
| 35 |
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
|
| 43 |
-
height, width = 60, 80
|
| 44 |
-
yy, xx = np.mgrid[0:height, 0:width]
|
| 45 |
-
surface = np.ones((height, width), dtype=np.uint8)
|
| 46 |
-
surface_indices = np.flatnonzero(surface.ravel()).astype(np.uint32)
|
| 47 |
-
uv = np.column_stack((
|
| 48 |
-
xx.ravel()[surface_indices] * 0.02,
|
| 49 |
-
yy.ravel()[surface_indices] * 0.02,
|
| 50 |
-
)).astype(np.float32)
|
| 51 |
-
uv[:80] = np.nan
|
| 52 |
-
plane_ids = np.zeros(len(surface_indices), dtype=np.uint8)
|
| 53 |
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
|
| 65 |
-
|
|
|
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
def test_surface_edge_coverage_respects_protected_pixels(self):
|
| 71 |
surface = np.zeros((80, 120), dtype=np.uint8)
|
| 72 |
surface[40:75, 20:100] = 1
|
| 73 |
protected = np.zeros_like(surface, dtype=bool)
|
| 74 |
protected[35:45, 95:110] = True
|
| 75 |
-
|
| 76 |
-
repaired, _ = app.improve_surface_edge_coverage(surface, protected)
|
| 77 |
|
| 78 |
self.assertFalse(repaired[protected].any())
|
| 79 |
self.assertEqual(int(repaired[42, 99]), 0)
|
| 80 |
|
| 81 |
-
def
|
| 82 |
-
height, width =
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
depth,
|
| 92 |
-
)).astype(np.float32)
|
| 93 |
-
normals = np.zeros_like(points)
|
| 94 |
-
normals[:, :, 1] = 1.0
|
| 95 |
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
)
|
| 104 |
|
| 105 |
-
self.
|
| 106 |
-
self.
|
| 107 |
-
self.assertEqual(len(result["cameraIntrinsics"]), 9)
|
| 108 |
-
self.assertGreater(result["geometryConfidence"], 0.35)
|
| 109 |
|
| 110 |
-
def
|
| 111 |
-
height, width =
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
|
|
|
| 120 |
try:
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
finally:
|
| 123 |
-
app.
|
|
|
|
|
|
|
| 124 |
|
| 125 |
-
self.
|
| 126 |
-
self.assertEqual(
|
| 127 |
-
self.
|
| 128 |
-
self.assertLess(result["fitResidualMeters"], 0.18)
|
| 129 |
|
| 130 |
-
def
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
|
|
|
| 136 |
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
|
|
|
|
|
|
| 140 |
|
| 141 |
-
self.
|
| 142 |
-
self.
|
| 143 |
-
self.assertTrue(np.isfinite(points[mask > 0]).all())
|
| 144 |
|
| 145 |
-
def
|
| 146 |
-
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
-
|
| 150 |
-
|
|
|
|
| 151 |
try:
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
finally:
|
| 154 |
-
app.
|
|
|
|
|
|
|
| 155 |
|
| 156 |
-
self.
|
|
|
|
|
|
|
| 157 |
|
| 158 |
-
def
|
| 159 |
-
height, width =
|
| 160 |
yy, xx = np.mgrid[0:height, 0:width]
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
points = np.zeros((height, width, 3), dtype=np.float32)
|
| 166 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
points[floor, 2] = (yy[floor] - 60) / 40.0 + 1.0
|
| 172 |
-
normals[floor] = np.array([0.0, 1.0, 0.0], dtype=np.float32)
|
| 173 |
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
geometry = {
|
| 181 |
"provider": "synthetic",
|
| 182 |
"points": points,
|
| 183 |
"normals": normals,
|
| 184 |
-
"validMask":
|
| 185 |
"intrinsics": np.eye(3, dtype=np.float32),
|
| 186 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
|
|
|
|
| 188 |
original_min = app.SURFACE_MIN_PLANE_PIXELS
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
| 190 |
try:
|
| 191 |
-
|
| 192 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
finally:
|
|
|
|
| 194 |
app.SURFACE_MIN_PLANE_PIXELS = original_min
|
|
|
|
|
|
|
|
|
|
|
|
|
| 195 |
|
| 196 |
-
self.
|
| 197 |
-
self.
|
| 198 |
-
self.assertEqual(
|
| 199 |
-
self.assertTrue(np.isfinite(mapping["uv"]).all())
|
| 200 |
-
self.assertGreaterEqual(len(set(mapping["planeIds"].tolist())), 2)
|
| 201 |
-
self.assertTrue(any(plane["isFloor"] for plane in mapping["planes"]))
|
| 202 |
|
| 203 |
-
def
|
| 204 |
-
height, width =
|
| 205 |
yy, xx = np.mgrid[0:height, 0:width]
|
| 206 |
-
mask = (yy >
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
}
|
| 222 |
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
|
| 231 |
-
self.
|
| 232 |
-
self.
|
| 233 |
-
self.
|
| 234 |
-
self.
|
| 235 |
-
self.
|
| 236 |
-
self.
|
| 237 |
|
| 238 |
|
| 239 |
if __name__ == "__main__":
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
import io
|
| 3 |
+
import tempfile
|
| 4 |
+
from pathlib import Path
|
| 5 |
|
| 6 |
+
import cv2
|
| 7 |
import numpy as np
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from fastapi.testclient import TestClient
|
| 10 |
|
| 11 |
import app
|
| 12 |
+
import direction_finder
|
| 13 |
+
import floor_direction
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class MetricFloorGeometryTests(unittest.TestCase):
|
| 17 |
+
def test_material_prepare_route_precedes_static_materials_mount(self):
|
| 18 |
+
prepare_index = None
|
| 19 |
+
static_index = None
|
| 20 |
+
for index, route in enumerate(app.app.routes):
|
| 21 |
+
if getattr(route, "path", None) == "/materials/prepare":
|
| 22 |
+
prepare_index = index
|
| 23 |
+
if getattr(route, "path", None) == "/materials":
|
| 24 |
+
static_index = index
|
| 25 |
+
|
| 26 |
+
self.assertIsNotNone(prepare_index)
|
| 27 |
+
self.assertIsNotNone(static_index)
|
| 28 |
+
self.assertLess(prepare_index, static_index)
|
| 29 |
+
|
| 30 |
+
def test_tile_material_generation_returns_pbr_maps(self):
|
| 31 |
+
height, width = 32, 48
|
| 32 |
+
yy, xx = np.mgrid[0:height, 0:width]
|
| 33 |
+
tile = np.zeros((height, width, 3), dtype=np.uint8)
|
| 34 |
+
tile[:, :, 0] = (xx * 255 / max(width - 1, 1)).astype(np.uint8)
|
| 35 |
+
tile[:, :, 1] = (yy * 255 / max(height - 1, 1)).astype(np.uint8)
|
| 36 |
+
tile[:, :, 2] = 128
|
| 37 |
+
|
| 38 |
+
maps, metadata = app.generate_tile_material_maps(tile, base_roughness=0.5)
|
| 39 |
+
|
| 40 |
+
self.assertEqual(metadata["generator"], app.MATERIAL_GENERATOR_VERSION)
|
| 41 |
+
self.assertEqual(metadata["generatedKinds"], ["normalMap", "heightMap", "roughnessMap", "aoMap", "specularMap"])
|
| 42 |
+
for key in ("albedoMap", "normalMap", "heightMap", "roughnessMap", "aoMap", "specularMap"):
|
| 43 |
+
self.assertIn(key, maps)
|
| 44 |
+
self.assertEqual(maps[key].shape, (height, width, 3))
|
| 45 |
+
self.assertEqual(maps[key].dtype, np.uint8)
|
| 46 |
+
self.assertGreaterEqual(int(maps[key].min()), 0)
|
| 47 |
+
self.assertLessEqual(int(maps[key].max()), 255)
|
| 48 |
+
|
| 49 |
+
def test_tile_material_package_is_cached(self):
|
| 50 |
+
tile = np.full((16, 16, 3), 160, dtype=np.uint8)
|
| 51 |
+
tile[:, :8, :] = 80
|
| 52 |
+
buffer = io.BytesIO()
|
| 53 |
+
Image.fromarray(tile).save(buffer, format="PNG")
|
| 54 |
+
contents = buffer.getvalue()
|
| 55 |
+
|
| 56 |
+
original_material_dir = app.MATERIAL_DIR
|
| 57 |
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
| 58 |
+
app.MATERIAL_DIR = Path(tmp_dir)
|
| 59 |
+
try:
|
| 60 |
+
first = app.build_tile_material_package(contents, base_roughness=0.45)
|
| 61 |
+
second = app.build_tile_material_package(contents, base_roughness=0.45)
|
| 62 |
+
finally:
|
| 63 |
+
app.MATERIAL_DIR = original_material_dir
|
| 64 |
+
|
| 65 |
+
self.assertEqual(first["id"], second["id"])
|
| 66 |
+
self.assertTrue(second["cached"])
|
| 67 |
+
self.assertIn("normalMap", second["maps"])
|
| 68 |
+
self.assertTrue(second["maps"]["normalMap"].endswith("/normal.png"))
|
| 69 |
+
|
| 70 |
+
def test_showroom_shade_map_clamps_harsh_floor_shadow(self):
|
| 71 |
+
height, width = 96, 128
|
| 72 |
+
image = np.full((height, width, 3), 180, dtype=np.uint8)
|
| 73 |
+
image[34:70, 46:82, :] = 45
|
| 74 |
+
mask = np.ones((height, width), dtype=np.uint8)
|
| 75 |
+
|
| 76 |
+
maps = app.build_luminance_lighting_maps(image, mask)
|
| 77 |
+
|
| 78 |
+
self.assertIsNotNone(maps)
|
| 79 |
+
showroom = maps["showroomShadeMap"]
|
| 80 |
+
self.assertIsNotNone(showroom)
|
| 81 |
+
decoded = (
|
| 82 |
+
app.SHOWROOM_SHADE_MAP_MIN
|
| 83 |
+
+ (showroom.astype(np.float32) / 255.0)
|
| 84 |
+
* (app.SHOWROOM_SHADE_MAP_MAX - app.SHOWROOM_SHADE_MAP_MIN)
|
| 85 |
+
)
|
| 86 |
+
self.assertGreaterEqual(float(decoded.min()), app.SHOWROOM_SHADE_MAP_MIN)
|
| 87 |
+
self.assertLessEqual(float(decoded.max()), app.SHOWROOM_SHADE_MAP_MAX)
|
| 88 |
+
self.assertGreater(float(decoded[52, 64]), 0.90)
|
| 89 |
|
| 90 |
+
def test_realistic_lighting_retains_dark_corner_and_bright_region(self):
|
| 91 |
+
height, width = 180, 240
|
| 92 |
+
image = np.full((height, width, 3), 150, dtype=np.uint8)
|
| 93 |
+
image[:, :80, :] = 55
|
| 94 |
+
image[:, 170:, :] = 225
|
| 95 |
+
mask = np.ones((height, width), dtype=np.uint8)
|
| 96 |
|
| 97 |
+
maps = app.build_luminance_lighting_maps(image, mask)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
+
self.assertIsNotNone(maps)
|
| 100 |
+
shade = maps["shadeMap"]
|
| 101 |
+
self.assertIsNotNone(shade)
|
| 102 |
+
decoded = (
|
| 103 |
+
app.SHADE_MAP_MIN
|
| 104 |
+
+ (shade.astype(np.float32) / 255.0)
|
| 105 |
+
* (app.SHADE_MAP_MAX - app.SHADE_MAP_MIN)
|
| 106 |
+
)
|
| 107 |
+
dark = float(np.median(decoded[:, 20:60]))
|
| 108 |
+
neutral = float(np.median(decoded[:, 105:135]))
|
| 109 |
+
bright = float(np.median(decoded[:, 190:225]))
|
| 110 |
+
self.assertLess(dark, neutral * 0.25)
|
| 111 |
+
self.assertGreater(bright, neutral * 1.25)
|
| 112 |
|
| 113 |
+
def test_realistic_lighting_suppresses_old_floor_texture(self):
|
| 114 |
+
height, width = 180, 240
|
| 115 |
+
image = np.full((height, width, 3), 165, dtype=np.uint8)
|
| 116 |
+
image[:, :90, :] = 75
|
| 117 |
+
for x in range(0, width, 8):
|
| 118 |
+
image[:, x:x + 3, :] = np.clip(image[:, x:x + 3, :].astype(np.int16) - 35, 0, 255)
|
| 119 |
+
mask = np.ones((height, width), dtype=np.uint8)
|
| 120 |
|
| 121 |
+
maps = app.build_luminance_lighting_maps(image, mask)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
| 123 |
+
self.assertIsNotNone(maps)
|
| 124 |
+
shade = maps["shadeMap"]
|
| 125 |
+
decoded = (
|
| 126 |
+
app.SHADE_MAP_MIN
|
| 127 |
+
+ (shade.astype(np.float32) / 255.0)
|
| 128 |
+
* (app.SHADE_MAP_MAX - app.SHADE_MAP_MIN)
|
| 129 |
+
)
|
| 130 |
+
shadow_contrast = float(np.median(decoded[:, 120:180]) - np.median(decoded[:, 20:70]))
|
| 131 |
+
stripe_contrast = float(np.mean(np.abs(np.diff(decoded[:, 120:180], axis=1))))
|
| 132 |
+
self.assertGreater(shadow_contrast, 0.25)
|
| 133 |
+
self.assertLess(stripe_contrast, 0.035)
|
| 134 |
|
| 135 |
+
def test_reflection_map_only_transfers_bright_highlights(self):
|
| 136 |
+
height, width = 128, 160
|
| 137 |
+
image = np.full((height, width, 3), 128, dtype=np.uint8)
|
| 138 |
+
image[42:86, 28:68, :] = 52
|
| 139 |
+
image[42:86, 92:132, :] = 218
|
| 140 |
+
mask = np.ones((height, width), dtype=np.uint8)
|
| 141 |
|
| 142 |
+
reflection = app.build_reflection_map(image, mask)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
+
self.assertIsNotNone(reflection)
|
| 145 |
+
decoded = app.REFLECTION_MAP_MIN + (reflection.astype(np.float32) / 255.0) * (
|
| 146 |
+
app.REFLECTION_MAP_MAX - app.REFLECTION_MAP_MIN
|
| 147 |
+
)
|
| 148 |
+
self.assertLessEqual(float(decoded[64, 48]), 0.02)
|
| 149 |
+
self.assertGreater(float(decoded[42:86, 92:132].max()), 0.0)
|
| 150 |
|
| 151 |
+
def test_intrinsic_shading_inversion_is_corrected_against_room_luminance(self):
|
| 152 |
+
height, width = 160, 180
|
| 153 |
+
image = np.zeros((height, width, 3), dtype=np.uint8)
|
| 154 |
+
image[: height // 2, :, :] = 210
|
| 155 |
+
image[height // 2 :, :, :] = 80
|
| 156 |
+
mask = np.ones((height, width), dtype=np.uint8)
|
| 157 |
+
inverted_intrinsic = np.ones((height, width), dtype=np.float32)
|
| 158 |
+
inverted_intrinsic[: height // 2, :] = 0.55
|
| 159 |
+
inverted_intrinsic[height // 2 :, :] = 1.45
|
| 160 |
|
| 161 |
+
aligned, source = app.align_intrinsic_shading_to_luminance(
|
| 162 |
+
inverted_intrinsic,
|
| 163 |
+
image,
|
| 164 |
+
mask,
|
| 165 |
+
)
|
| 166 |
|
| 167 |
+
self.assertEqual(source, "intrinsic-inverted-corrected")
|
| 168 |
+
self.assertGreater(float(aligned[32, width // 2]), float(aligned[128, width // 2]))
|
| 169 |
|
| 170 |
+
def test_intrinsic_shading_keeps_matching_room_luminance(self):
|
| 171 |
+
height, width = 160, 180
|
| 172 |
+
image = np.zeros((height, width, 3), dtype=np.uint8)
|
| 173 |
+
image[: height // 2, :, :] = 210
|
| 174 |
+
image[height // 2 :, :, :] = 80
|
| 175 |
+
mask = np.ones((height, width), dtype=np.uint8)
|
| 176 |
+
matching_intrinsic = np.ones((height, width), dtype=np.float32)
|
| 177 |
+
matching_intrinsic[: height // 2, :] = 1.45
|
| 178 |
+
matching_intrinsic[height // 2 :, :] = 0.55
|
| 179 |
|
| 180 |
+
aligned, source = app.align_intrinsic_shading_to_luminance(
|
| 181 |
+
matching_intrinsic,
|
| 182 |
+
image,
|
| 183 |
+
mask,
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
self.assertEqual(source, "intrinsic-aligned")
|
| 187 |
+
self.assertGreater(float(aligned[32, width // 2]), float(aligned[128, width // 2]))
|
| 188 |
+
|
| 189 |
+
def test_surface_uv_quality_keeps_smooth_complete_uvs(self):
|
| 190 |
+
height, width = 60, 80
|
| 191 |
+
yy, xx = np.mgrid[0:height, 0:width]
|
| 192 |
+
surface = np.ones((height, width), dtype=np.uint8)
|
| 193 |
+
surface_indices = np.flatnonzero(surface.ravel()).astype(np.uint32)
|
| 194 |
+
uv = np.column_stack((
|
| 195 |
+
xx.ravel()[surface_indices] * 0.02,
|
| 196 |
+
yy.ravel()[surface_indices] * 0.02,
|
| 197 |
+
)).astype(np.float32)
|
| 198 |
+
plane_ids = np.zeros(len(surface_indices), dtype=np.uint8)
|
| 199 |
+
|
| 200 |
+
quality = app.analyze_surface_uv_quality(surface, surface_indices, uv, plane_ids)
|
| 201 |
+
|
| 202 |
+
self.assertTrue(quality["surfaceUvEnabled"])
|
| 203 |
+
self.assertEqual(quality["textureMappingMode"], "surface-uv")
|
| 204 |
+
self.assertEqual(quality["textureMappingReason"], "surface-uv-quality-ok")
|
| 205 |
+
|
| 206 |
+
def test_surface_uv_quality_rejects_noisy_far_region_jumps(self):
|
| 207 |
+
height, width = 60, 80
|
| 208 |
+
yy, xx = np.mgrid[0:height, 0:width]
|
| 209 |
+
surface = np.ones((height, width), dtype=np.uint8)
|
| 210 |
+
surface_indices = np.flatnonzero(surface.ravel()).astype(np.uint32)
|
| 211 |
+
uv_grid = np.dstack((xx * 0.02, yy * 0.02)).astype(np.float32)
|
| 212 |
+
uv_grid[:20, 40::2, 0] += 4.0
|
| 213 |
+
uv = uv_grid.reshape(-1, 2)[surface_indices]
|
| 214 |
+
plane_ids = np.zeros(len(surface_indices), dtype=np.uint8)
|
| 215 |
+
|
| 216 |
+
quality = app.analyze_surface_uv_quality(surface, surface_indices, uv, plane_ids)
|
| 217 |
+
|
| 218 |
+
self.assertFalse(quality["surfaceUvEnabled"])
|
| 219 |
+
self.assertEqual(quality["textureMappingMode"], "regularized-floor-plane")
|
| 220 |
+
self.assertEqual(quality["textureMappingReason"], "noisy-surface-uv")
|
| 221 |
+
|
| 222 |
+
def test_surface_uv_quality_rejects_partial_invalid_uvs(self):
|
| 223 |
+
height, width = 60, 80
|
| 224 |
+
yy, xx = np.mgrid[0:height, 0:width]
|
| 225 |
+
surface = np.ones((height, width), dtype=np.uint8)
|
| 226 |
+
surface_indices = np.flatnonzero(surface.ravel()).astype(np.uint32)
|
| 227 |
+
uv = np.column_stack((
|
| 228 |
+
xx.ravel()[surface_indices] * 0.02,
|
| 229 |
+
yy.ravel()[surface_indices] * 0.02,
|
| 230 |
+
)).astype(np.float32)
|
| 231 |
+
uv[:80] = np.nan
|
| 232 |
+
plane_ids = np.zeros(len(surface_indices), dtype=np.uint8)
|
| 233 |
+
|
| 234 |
+
quality = app.analyze_surface_uv_quality(surface, surface_indices, uv, plane_ids)
|
| 235 |
+
|
| 236 |
+
self.assertFalse(quality["surfaceUvEnabled"])
|
| 237 |
+
self.assertEqual(quality["textureMappingReason"], "incomplete-surface-uv")
|
| 238 |
+
|
| 239 |
+
def test_surface_edge_coverage_closes_small_boundary_gaps(self):
|
| 240 |
+
surface = np.zeros((80, 120), dtype=np.uint8)
|
| 241 |
+
surface[40:75, 20:100] = 1
|
| 242 |
+
surface[40:48, 55:57] = 0
|
| 243 |
+
protected = np.zeros_like(surface, dtype=bool)
|
| 244 |
+
|
| 245 |
+
repaired, metadata = app.improve_surface_edge_coverage(surface, protected)
|
| 246 |
+
|
| 247 |
+
self.assertGreater(metadata["surfacePixelsAfterEdgeFix"], metadata["surfacePixelsBeforeEdgeFix"])
|
| 248 |
+
self.assertEqual(int(repaired[44, 56]), 1)
|
| 249 |
+
|
| 250 |
def test_surface_edge_coverage_respects_protected_pixels(self):
|
| 251 |
surface = np.zeros((80, 120), dtype=np.uint8)
|
| 252 |
surface[40:75, 20:100] = 1
|
| 253 |
protected = np.zeros_like(surface, dtype=bool)
|
| 254 |
protected[35:45, 95:110] = True
|
| 255 |
+
|
| 256 |
+
repaired, _ = app.improve_surface_edge_coverage(surface, protected)
|
| 257 |
|
| 258 |
self.assertFalse(repaired[protected].any())
|
| 259 |
self.assertEqual(int(repaired[42, 99]), 0)
|
| 260 |
|
| 261 |
+
def test_floor_surface_reaches_wall_and_door_contact_edges(self):
|
| 262 |
+
height, width = 80, 120
|
| 263 |
+
floor_id = app.class_ids({"floor"})[0]
|
| 264 |
+
wall_id = app.class_ids({"wall"})[0]
|
| 265 |
+
door_id = app.class_ids({"door"})[0]
|
| 266 |
+
floor_mask = np.zeros((height, width), dtype=np.uint8)
|
| 267 |
+
floor_mask[40:75, 15:105] = 1
|
| 268 |
+
seg_map = np.full((height, width), floor_id, dtype=np.uint8)
|
| 269 |
+
seg_map[:40, :] = wall_id
|
| 270 |
+
seg_map[15:40, 50:70] = door_id
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
|
| 272 |
+
surface, _ = app.build_floor_surface_mask(
|
| 273 |
+
floor_mask,
|
| 274 |
+
seg_map,
|
| 275 |
+
quad=None,
|
| 276 |
+
depth=None,
|
| 277 |
+
geometry=None,
|
| 278 |
+
plane=None,
|
| 279 |
)
|
| 280 |
|
| 281 |
+
self.assertTrue(surface[40, 20:100].all())
|
| 282 |
+
self.assertFalse(surface[:40].any())
|
|
|
|
|
|
|
| 283 |
|
| 284 |
+
def test_foreground_occlusion_does_not_create_floor_halo_below_door(self):
|
| 285 |
+
height, width = 80, 120
|
| 286 |
+
floor_id = app.class_ids({"floor"})[0]
|
| 287 |
+
door_id = app.class_ids({"door"})[0]
|
| 288 |
+
surface = np.zeros((height, width), dtype=np.uint8)
|
| 289 |
+
surface[40:75, 15:105] = 1
|
| 290 |
+
seg_map = np.full((height, width), floor_id, dtype=np.uint8)
|
| 291 |
+
seg_map[15:40, 50:70] = door_id
|
| 292 |
+
|
| 293 |
+
occlusion = app.foreground_occlusion_mask(surface, seg_map)
|
| 294 |
+
|
| 295 |
+
self.assertTrue(occlusion[30:40, 50:70].all())
|
| 296 |
+
self.assertFalse(occlusion[40:, 50:70].any())
|
| 297 |
+
|
| 298 |
+
def test_soft_floor_covering_expansion_adds_only_nearby_rug_pixels(self):
|
| 299 |
+
surface = np.zeros((80, 120), dtype=np.uint8)
|
| 300 |
+
surface[40:75, 20:100] = 1
|
| 301 |
+
rug = np.zeros_like(surface)
|
| 302 |
+
rug[45:70, 100:108] = 1
|
| 303 |
+
protected = np.zeros_like(surface, dtype=bool)
|
| 304 |
|
| 305 |
+
original_enabled = app.ENABLE_SOFT_FLOOR_COVERING_EXPANSION
|
| 306 |
+
original_ratio = app.SOFT_FLOOR_COVERING_KERNEL_RATIO
|
| 307 |
+
original_iterations = app.SOFT_FLOOR_COVERING_DILATION_ITERATIONS
|
| 308 |
try:
|
| 309 |
+
app.ENABLE_SOFT_FLOOR_COVERING_EXPANSION = True
|
| 310 |
+
app.SOFT_FLOOR_COVERING_KERNEL_RATIO = 0.008
|
| 311 |
+
app.SOFT_FLOOR_COVERING_DILATION_ITERATIONS = 2
|
| 312 |
+
expanded, metadata = app.expand_surface_over_soft_floor_coverings(
|
| 313 |
+
surface,
|
| 314 |
+
rug,
|
| 315 |
+
protected,
|
| 316 |
+
)
|
| 317 |
finally:
|
| 318 |
+
app.ENABLE_SOFT_FLOOR_COVERING_EXPANSION = original_enabled
|
| 319 |
+
app.SOFT_FLOOR_COVERING_KERNEL_RATIO = original_ratio
|
| 320 |
+
app.SOFT_FLOOR_COVERING_DILATION_ITERATIONS = original_iterations
|
| 321 |
|
| 322 |
+
self.assertTrue(metadata["softFloorCoveringExpansionApplied"])
|
| 323 |
+
self.assertEqual(int(expanded[50, 100]), 1)
|
| 324 |
+
self.assertEqual(int(expanded[50, 107]), 0)
|
|
|
|
| 325 |
|
| 326 |
+
def test_soft_floor_covering_expansion_respects_hard_protected_pixels(self):
|
| 327 |
+
surface = np.zeros((80, 120), dtype=np.uint8)
|
| 328 |
+
surface[40:75, 20:100] = 1
|
| 329 |
+
rug = np.zeros_like(surface)
|
| 330 |
+
rug[45:70, 100:104] = 1
|
| 331 |
+
protected = np.zeros_like(surface, dtype=bool)
|
| 332 |
+
protected[45:70, 100:104] = True
|
| 333 |
|
| 334 |
+
expanded, metadata = app.expand_surface_over_soft_floor_coverings(
|
| 335 |
+
surface,
|
| 336 |
+
rug,
|
| 337 |
+
protected,
|
| 338 |
+
)
|
| 339 |
|
| 340 |
+
self.assertFalse(metadata["softFloorCoveringExpansionApplied"])
|
| 341 |
+
self.assertFalse(expanded[protected].any())
|
|
|
|
| 342 |
|
| 343 |
+
def test_floor_surface_mask_keeps_replaceable_rug_pixels(self):
|
| 344 |
+
height, width = 80, 120
|
| 345 |
+
floor_id = app.class_ids({"floor"})[0]
|
| 346 |
+
rug_ids = app.class_ids({"rug"})
|
| 347 |
+
self.assertTrue(rug_ids)
|
| 348 |
+
rug_id = rug_ids[0]
|
| 349 |
+
floor_mask = np.zeros((height, width), dtype=np.uint8)
|
| 350 |
+
floor_mask[40:75, 20:108] = 1
|
| 351 |
+
seg_map = np.full((height, width), floor_id, dtype=np.uint8)
|
| 352 |
+
seg_map[45:70, 100:108] = rug_id
|
| 353 |
|
| 354 |
+
original_enabled = app.ENABLE_SOFT_FLOOR_COVERING_EXPANSION
|
| 355 |
+
original_ratio = app.SOFT_FLOOR_COVERING_KERNEL_RATIO
|
| 356 |
+
original_iterations = app.SOFT_FLOOR_COVERING_DILATION_ITERATIONS
|
| 357 |
try:
|
| 358 |
+
app.ENABLE_SOFT_FLOOR_COVERING_EXPANSION = True
|
| 359 |
+
app.SOFT_FLOOR_COVERING_KERNEL_RATIO = 0.008
|
| 360 |
+
app.SOFT_FLOOR_COVERING_DILATION_ITERATIONS = 2
|
| 361 |
+
surface, metadata = app.build_floor_surface_mask(
|
| 362 |
+
floor_mask,
|
| 363 |
+
seg_map,
|
| 364 |
+
quad=None,
|
| 365 |
+
depth=None,
|
| 366 |
+
geometry=None,
|
| 367 |
+
plane=None,
|
| 368 |
+
)
|
| 369 |
finally:
|
| 370 |
+
app.ENABLE_SOFT_FLOOR_COVERING_EXPANSION = original_enabled
|
| 371 |
+
app.SOFT_FLOOR_COVERING_KERNEL_RATIO = original_ratio
|
| 372 |
+
app.SOFT_FLOOR_COVERING_DILATION_ITERATIONS = original_iterations
|
| 373 |
|
| 374 |
+
self.assertFalse(metadata["softFloorCoveringExpansionApplied"])
|
| 375 |
+
self.assertEqual(int(surface[50, 100]), 1)
|
| 376 |
+
self.assertEqual(int(surface[50, 107]), 1)
|
| 377 |
|
| 378 |
+
def test_floor_surface_mask_does_not_readd_off_plane_edge_pixels(self):
|
| 379 |
+
height, width = 80, 120
|
| 380 |
yy, xx = np.mgrid[0:height, 0:width]
|
| 381 |
+
floor_mask = np.zeros((height, width), dtype=np.uint8)
|
| 382 |
+
floor_mask[45:74, 22:98] = 1
|
| 383 |
+
seg_map = np.full((height, width), app.class_ids({"floor"})[0], dtype=np.uint8)
|
| 384 |
+
|
| 385 |
+
points = np.zeros((height, width, 3), dtype=np.float32)
|
| 386 |
+
points[:, :, 0] = (xx - width / 2) / 40.0
|
| 387 |
+
points[:, :, 2] = (yy - 45) / 40.0 + 1.0
|
| 388 |
+
points[:, :, 1] = 0.0
|
| 389 |
+
points[:45, :, 1] = 0.5
|
| 390 |
+
normals = np.zeros_like(points)
|
| 391 |
+
normals[:, :, 1] = 1.0
|
| 392 |
+
geometry = {
|
| 393 |
+
"provider": "synthetic",
|
| 394 |
+
"points": points,
|
| 395 |
+
"normals": normals,
|
| 396 |
+
"validMask": np.ones((height, width), dtype=bool),
|
| 397 |
+
"intrinsics": np.eye(3, dtype=np.float32),
|
| 398 |
+
}
|
| 399 |
+
plane = {
|
| 400 |
+
"planeNormal": [0.0, 1.0, 0.0],
|
| 401 |
+
"planeOrigin": [0.0, 0.0, 0.0],
|
| 402 |
+
}
|
| 403 |
+
|
| 404 |
+
original_filter = app.ENABLE_GEOMETRY_SURFACE_FILTER
|
| 405 |
+
original_min = app.SURFACE_MIN_PLANE_PIXELS
|
| 406 |
+
original_distance = app.SURFACE_PLANE_DISTANCE_METERS
|
| 407 |
+
try:
|
| 408 |
+
app.ENABLE_GEOMETRY_SURFACE_FILTER = True
|
| 409 |
+
app.SURFACE_MIN_PLANE_PIXELS = 250
|
| 410 |
+
app.SURFACE_PLANE_DISTANCE_METERS = 0.12
|
| 411 |
+
surface, metadata = app.build_floor_surface_mask(
|
| 412 |
+
floor_mask,
|
| 413 |
+
seg_map,
|
| 414 |
+
quad=None,
|
| 415 |
+
depth=None,
|
| 416 |
+
geometry=geometry,
|
| 417 |
+
plane=plane,
|
| 418 |
+
)
|
| 419 |
+
finally:
|
| 420 |
+
app.ENABLE_GEOMETRY_SURFACE_FILTER = original_filter
|
| 421 |
+
app.SURFACE_MIN_PLANE_PIXELS = original_min
|
| 422 |
+
app.SURFACE_PLANE_DISTANCE_METERS = original_distance
|
| 423 |
|
| 424 |
+
self.assertGreater(metadata["surfacePixelsAfterEdgeFix"], metadata["surfacePixelsBeforeEdgeFix"])
|
| 425 |
+
self.assertTrue(metadata["postEdgeGeometrySurfaceFilterApplied"])
|
| 426 |
+
self.assertEqual(int(surface[:45].sum()), 0)
|
|
|
|
|
|
|
| 427 |
|
| 428 |
+
def test_floor_surface_mask_filters_off_plane_rug_expansion(self):
|
| 429 |
+
height, width = 80, 120
|
| 430 |
+
yy, xx = np.mgrid[0:height, 0:width]
|
| 431 |
+
floor_id = app.class_ids({"floor"})[0]
|
| 432 |
+
rug_id = app.class_ids({"rug"})[0]
|
| 433 |
+
floor_mask = np.zeros((height, width), dtype=np.uint8)
|
| 434 |
+
floor_mask[45:74, 22:98] = 1
|
| 435 |
+
seg_map = np.full((height, width), floor_id, dtype=np.uint8)
|
| 436 |
+
seg_map[42:45, 40:52] = rug_id
|
| 437 |
|
| 438 |
+
points = np.zeros((height, width, 3), dtype=np.float32)
|
| 439 |
+
points[:, :, 0] = (xx - width / 2) / 40.0
|
| 440 |
+
points[:, :, 2] = (yy - 45) / 40.0 + 1.0
|
| 441 |
+
points[:, :, 1] = 0.0
|
| 442 |
+
points[:45, :, 1] = 0.5
|
| 443 |
+
normals = np.zeros_like(points)
|
| 444 |
+
normals[:, :, 1] = 1.0
|
| 445 |
geometry = {
|
| 446 |
"provider": "synthetic",
|
| 447 |
"points": points,
|
| 448 |
"normals": normals,
|
| 449 |
+
"validMask": np.ones((height, width), dtype=bool),
|
| 450 |
"intrinsics": np.eye(3, dtype=np.float32),
|
| 451 |
}
|
| 452 |
+
plane = {
|
| 453 |
+
"planeNormal": [0.0, 1.0, 0.0],
|
| 454 |
+
"planeOrigin": [0.0, 0.0, 0.0],
|
| 455 |
+
}
|
| 456 |
|
| 457 |
+
original_filter = app.ENABLE_GEOMETRY_SURFACE_FILTER
|
| 458 |
original_min = app.SURFACE_MIN_PLANE_PIXELS
|
| 459 |
+
original_distance = app.SURFACE_PLANE_DISTANCE_METERS
|
| 460 |
+
original_enabled = app.ENABLE_SOFT_FLOOR_COVERING_EXPANSION
|
| 461 |
+
original_ratio = app.SOFT_FLOOR_COVERING_KERNEL_RATIO
|
| 462 |
+
original_iterations = app.SOFT_FLOOR_COVERING_DILATION_ITERATIONS
|
| 463 |
try:
|
| 464 |
+
app.ENABLE_GEOMETRY_SURFACE_FILTER = True
|
| 465 |
+
app.SURFACE_MIN_PLANE_PIXELS = 250
|
| 466 |
+
app.SURFACE_PLANE_DISTANCE_METERS = 0.12
|
| 467 |
+
app.ENABLE_SOFT_FLOOR_COVERING_EXPANSION = True
|
| 468 |
+
app.SOFT_FLOOR_COVERING_KERNEL_RATIO = 0.008
|
| 469 |
+
app.SOFT_FLOOR_COVERING_DILATION_ITERATIONS = 2
|
| 470 |
+
surface, metadata = app.build_floor_surface_mask(
|
| 471 |
+
floor_mask,
|
| 472 |
+
seg_map,
|
| 473 |
+
quad=None,
|
| 474 |
+
depth=None,
|
| 475 |
+
geometry=geometry,
|
| 476 |
+
plane=plane,
|
| 477 |
+
)
|
| 478 |
finally:
|
| 479 |
+
app.ENABLE_GEOMETRY_SURFACE_FILTER = original_filter
|
| 480 |
app.SURFACE_MIN_PLANE_PIXELS = original_min
|
| 481 |
+
app.SURFACE_PLANE_DISTANCE_METERS = original_distance
|
| 482 |
+
app.ENABLE_SOFT_FLOOR_COVERING_EXPANSION = original_enabled
|
| 483 |
+
app.SOFT_FLOOR_COVERING_KERNEL_RATIO = original_ratio
|
| 484 |
+
app.SOFT_FLOOR_COVERING_DILATION_ITERATIONS = original_iterations
|
| 485 |
|
| 486 |
+
self.assertFalse(metadata["softFloorCoveringExpansionApplied"])
|
| 487 |
+
self.assertTrue(metadata["postSoftFloorCoveringGeometrySurfaceFilterApplied"])
|
| 488 |
+
self.assertEqual(int(surface[:45].sum()), 0)
|
|
|
|
|
|
|
|
|
|
| 489 |
|
| 490 |
+
def test_point_map_produces_moge_transform(self):
|
| 491 |
+
height, width = 360, 640
|
| 492 |
yy, xx = np.mgrid[0:height, 0:width]
|
| 493 |
+
mask = (yy > 220).astype(np.uint8)
|
| 494 |
+
focal = max(height, width) * 0.95
|
| 495 |
+
depth = np.full((height, width), 20.0, dtype=np.float32)
|
| 496 |
+
depth[mask > 0] = 1.6 * focal / (yy[mask > 0] - (height - 1) * 0.5)
|
| 497 |
+
points = np.dstack((
|
| 498 |
+
(xx - (width - 1) * 0.5) * depth / focal,
|
| 499 |
+
(yy - (height - 1) * 0.5) * depth / focal,
|
| 500 |
+
depth,
|
| 501 |
+
)).astype(np.float32)
|
| 502 |
+
normals = np.zeros_like(points)
|
| 503 |
+
normals[:, :, 1] = 1.0
|
| 504 |
+
|
| 505 |
+
result = app.fit_metric_floor_transform(
|
| 506 |
+
mask,
|
| 507 |
+
points,
|
| 508 |
+
valid_mask=mask > 0,
|
| 509 |
+
normals_map=normals,
|
| 510 |
+
intrinsics=np.array([[focal, 0, width / 2], [0, focal, height / 2], [0, 0, 1]], dtype=np.float32),
|
| 511 |
+
provider="moge-2",
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
self.assertIsNotNone(result)
|
| 515 |
+
self.assertEqual(result["geometryProvider"], "moge-2")
|
| 516 |
+
self.assertEqual(len(result["cameraIntrinsics"]), 9)
|
| 517 |
+
self.assertGreater(result["geometryConfidence"], 0.35)
|
| 518 |
+
|
| 519 |
+
def test_metric_depth_produces_meter_space_transform(self):
|
| 520 |
+
height, width = 360, 640
|
| 521 |
+
yy, xx = np.mgrid[0:height, 0:width]
|
| 522 |
+
mask = (yy > 220).astype(np.uint8)
|
| 523 |
+
focal = max(height, width) * 0.95
|
| 524 |
+
depth = np.full((height, width), 20.0, dtype=np.float32)
|
| 525 |
+
depth[mask > 0] = 1.6 * focal / (yy[mask > 0] - (height - 1) * 0.5)
|
| 526 |
+
|
| 527 |
+
original_name = app.DEPTH_MODEL_NAME
|
| 528 |
+
app.DEPTH_MODEL_NAME = "depth-anything/Depth-Anything-V2-Metric-Indoor-Large-hf"
|
| 529 |
+
try:
|
| 530 |
+
result = app.estimate_metric_floor_transform(mask, depth)
|
| 531 |
+
finally:
|
| 532 |
+
app.DEPTH_MODEL_NAME = original_name
|
| 533 |
+
|
| 534 |
+
self.assertIsNotNone(result)
|
| 535 |
+
self.assertEqual(len(result["floorTransform"]), 9)
|
| 536 |
+
self.assertGreater(result["geometryConfidence"], 0.35)
|
| 537 |
+
self.assertLess(result["fitResidualMeters"], 0.18)
|
| 538 |
+
|
| 539 |
+
def test_relative_depth_is_normalized_for_backprojection(self):
|
| 540 |
+
height, width = 360, 640
|
| 541 |
+
yy, _ = np.mgrid[0:height, 0:width]
|
| 542 |
+
mask = (yy > 220).astype(np.uint8)
|
| 543 |
+
depth = np.zeros((height, width), dtype=np.float32)
|
| 544 |
+
depth[mask > 0] = (yy[mask > 0] - 220) / float(height - 220)
|
| 545 |
+
|
| 546 |
+
depth_for_points, depth_scale = app.prepare_depth_for_backprojection(depth, mask, False)
|
| 547 |
+
intrinsics = app.default_camera_intrinsics(width, height)
|
| 548 |
+
points = app.backproject_depth(depth_for_points, intrinsics)
|
| 549 |
+
|
| 550 |
+
self.assertEqual(depth_scale, "relative-normalized")
|
| 551 |
+
self.assertEqual(points.shape, (height, width, 3))
|
| 552 |
+
self.assertTrue(np.isfinite(points[mask > 0]).all())
|
| 553 |
+
|
| 554 |
+
def test_plane_fit_flag_preserves_homography_fallback(self):
|
| 555 |
+
mask = np.ones((100, 100), dtype=np.uint8)
|
| 556 |
+
depth = np.ones((100, 100), dtype=np.float32)
|
| 557 |
+
|
| 558 |
+
original_flag = app.ENABLE_PLANE_FIT
|
| 559 |
+
app.ENABLE_PLANE_FIT = False
|
| 560 |
+
try:
|
| 561 |
+
result = app.estimate_metric_floor_transform(mask, depth)
|
| 562 |
+
finally:
|
| 563 |
+
app.ENABLE_PLANE_FIT = original_flag
|
| 564 |
+
|
| 565 |
+
self.assertIsNone(result)
|
| 566 |
+
|
| 567 |
+
def test_multi_plane_surface_mapping_assigns_floor_and_wall(self):
|
| 568 |
+
height, width = 120, 120
|
| 569 |
+
yy, xx = np.mgrid[0:height, 0:width]
|
| 570 |
+
mask = np.zeros((height, width), dtype=np.uint8)
|
| 571 |
+
mask[60:, :] = 1
|
| 572 |
+
mask[20:60, 30:90] = 1
|
| 573 |
+
|
| 574 |
+
points = np.zeros((height, width, 3), dtype=np.float32)
|
| 575 |
+
normals = np.zeros_like(points)
|
| 576 |
+
|
| 577 |
+
floor = mask.astype(bool) & (yy >= 60)
|
| 578 |
+
points[floor, 0] = (xx[floor] - width / 2) / 40.0
|
| 579 |
+
points[floor, 1] = 1.0
|
| 580 |
+
points[floor, 2] = (yy[floor] - 60) / 40.0 + 1.0
|
| 581 |
+
normals[floor] = np.array([0.0, 1.0, 0.0], dtype=np.float32)
|
| 582 |
+
|
| 583 |
+
wall = mask.astype(bool) & (yy < 60)
|
| 584 |
+
points[wall, 0] = (xx[wall] - width / 2) / 40.0
|
| 585 |
+
points[wall, 1] = (60 - yy[wall]) / 40.0
|
| 586 |
+
points[wall, 2] = 1.0
|
| 587 |
+
normals[wall] = np.array([0.0, 0.0, 1.0], dtype=np.float32)
|
| 588 |
+
|
| 589 |
+
geometry = {
|
| 590 |
+
"provider": "synthetic",
|
| 591 |
+
"points": points,
|
| 592 |
+
"normals": normals,
|
| 593 |
+
"validMask": mask > 0,
|
| 594 |
+
"intrinsics": np.eye(3, dtype=np.float32),
|
| 595 |
+
}
|
| 596 |
+
|
| 597 |
+
original_min = app.SURFACE_MIN_PLANE_PIXELS
|
| 598 |
+
app.SURFACE_MIN_PLANE_PIXELS = 1000
|
| 599 |
+
try:
|
| 600 |
+
surface_indices = np.flatnonzero(mask.ravel()).astype(np.uint32)
|
| 601 |
+
mapping = app.build_surface_uv_mapping(mask, surface_indices, geometry)
|
| 602 |
+
finally:
|
| 603 |
+
app.SURFACE_MIN_PLANE_PIXELS = original_min
|
| 604 |
+
|
| 605 |
+
self.assertIsNotNone(mapping)
|
| 606 |
+
self.assertGreaterEqual(len(mapping["planes"]), 2)
|
| 607 |
+
self.assertEqual(mapping["uv"].shape, (len(surface_indices), 2))
|
| 608 |
+
self.assertTrue(np.isfinite(mapping["uv"]).all())
|
| 609 |
+
self.assertGreaterEqual(len(set(mapping["planeIds"].tolist())), 2)
|
| 610 |
+
self.assertTrue(any(plane["isFloor"] for plane in mapping["planes"]))
|
| 611 |
+
|
| 612 |
+
def test_surface_mapping_falls_back_when_normals_are_missing(self):
|
| 613 |
+
height, width = 120, 120
|
| 614 |
+
yy, xx = np.mgrid[0:height, 0:width]
|
| 615 |
+
mask = (yy >= 40).astype(np.uint8)
|
| 616 |
+
|
| 617 |
+
points = np.zeros((height, width, 3), dtype=np.float32)
|
| 618 |
+
floor = mask.astype(bool)
|
| 619 |
+
points[floor, 0] = (xx[floor] - width / 2) / 45.0
|
| 620 |
+
points[floor, 1] = 1.0
|
| 621 |
+
points[floor, 2] = (yy[floor] - 40) / 45.0 + 1.0
|
| 622 |
+
normals = np.zeros_like(points)
|
| 623 |
+
|
| 624 |
+
geometry = {
|
| 625 |
+
"provider": "synthetic",
|
| 626 |
+
"points": points,
|
| 627 |
+
"normals": normals,
|
| 628 |
+
"validMask": mask > 0,
|
| 629 |
+
"intrinsics": np.eye(3, dtype=np.float32),
|
| 630 |
+
}
|
| 631 |
+
|
| 632 |
+
original_min = app.SURFACE_MIN_PLANE_PIXELS
|
| 633 |
+
app.SURFACE_MIN_PLANE_PIXELS = 1000
|
| 634 |
+
try:
|
| 635 |
+
surface_indices = np.flatnonzero(mask.ravel()).astype(np.uint32)
|
| 636 |
+
mapping = app.build_surface_uv_mapping(mask, surface_indices, geometry)
|
| 637 |
+
finally:
|
| 638 |
+
app.SURFACE_MIN_PLANE_PIXELS = original_min
|
| 639 |
+
|
| 640 |
+
self.assertIsNotNone(mapping)
|
| 641 |
+
self.assertGreaterEqual(len(mapping["planes"]), 1)
|
| 642 |
+
self.assertFalse(mapping["normalsReliable"])
|
| 643 |
+
self.assertIn("distance-only", {plane["fitMode"] for plane in mapping["planes"]})
|
| 644 |
+
self.assertEqual(mapping["uv"].shape, (len(surface_indices), 2))
|
| 645 |
+
self.assertTrue(np.isfinite(mapping["uv"]).all())
|
| 646 |
+
|
| 647 |
+
def test_analyze_floor_direction_route_uses_local_segmentation(self):
|
| 648 |
+
height, width = 180, 240
|
| 649 |
+
image = np.full((height, width, 3), 225, dtype=np.uint8)
|
| 650 |
+
for y in range(35, height - 20, 32):
|
| 651 |
+
image[y:y + 2, 20:width - 20] = 70
|
| 652 |
+
buffer = io.BytesIO()
|
| 653 |
+
Image.fromarray(image).save(buffer, format="JPEG")
|
| 654 |
+
|
| 655 |
+
original_builder = app.build_oneformer_polygon_response
|
| 656 |
+
app.build_oneformer_polygon_response = lambda *_args, **_kwargs: {
|
| 657 |
+
"model": "test",
|
| 658 |
+
"task": "panoptic",
|
| 659 |
+
"width": width,
|
| 660 |
+
"height": height,
|
| 661 |
+
"segments": [
|
| 662 |
+
{
|
| 663 |
+
"label": "floor",
|
| 664 |
+
"confidence": 0.98,
|
| 665 |
+
"polygons": [
|
| 666 |
+
{
|
| 667 |
+
"points": [[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]],
|
| 668 |
+
"bbox": [0, 0, width, height],
|
| 669 |
+
}
|
| 670 |
+
],
|
| 671 |
+
}
|
| 672 |
+
],
|
| 673 |
+
}
|
| 674 |
+
try:
|
| 675 |
+
client = TestClient(app.app)
|
| 676 |
+
response = client.post(
|
| 677 |
+
"/analyze-floor-direction",
|
| 678 |
+
data={"include_overlay": "true"},
|
| 679 |
+
files={"file": ("room.jpg", buffer.getvalue(), "image/jpeg")},
|
| 680 |
+
)
|
| 681 |
+
finally:
|
| 682 |
+
app.build_oneformer_polygon_response = original_builder
|
| 683 |
+
|
| 684 |
+
self.assertEqual(response.status_code, 200)
|
| 685 |
+
payload = response.json()
|
| 686 |
+
self.assertIsNotNone(payload["angle_degrees"])
|
| 687 |
+
self.assertEqual(payload["segmentation"]["label"], "floor")
|
| 688 |
+
self.assertEqual(payload["segmentation"]["source_path"], "root.segments[floor]")
|
| 689 |
+
self.assertGreater(payload["line_count"], 0)
|
| 690 |
+
self.assertTrue(payload["overlay_image_base64"].startswith("data:image/png;base64,"))
|
| 691 |
|
| 692 |
+
def test_floor_direction_prefers_repeated_grout_family_over_single_long_line(self):
|
| 693 |
+
lines = [
|
| 694 |
+
floor_direction.DetectedLine(30, 80, 110, 80, 0.0, 80.0),
|
| 695 |
+
floor_direction.DetectedLine(30, 140, 110, 140, 0.0, 80.0),
|
| 696 |
+
floor_direction.DetectedLine(30, 200, 110, 200, 0.0, 80.0),
|
| 697 |
+
floor_direction.DetectedLine(30, 260, 110, 260, 0.0, 80.0),
|
| 698 |
+
floor_direction.DetectedLine(310, 20, 310, 380, 90.0, 360.0),
|
| 699 |
+
]
|
| 700 |
|
| 701 |
+
orientation = floor_direction.dominant_orientation(lines, image_shape=(420, 360))
|
| 702 |
+
|
| 703 |
+
self.assertIsNotNone(orientation)
|
| 704 |
+
angle_degrees, dominant_lines, _peak_weight_ratio, _concentration, orthogonal_ratio = orientation
|
| 705 |
+
self.assertLess(floor_direction.angular_distance_degrees(angle_degrees, 0.0), 1.0)
|
| 706 |
+
self.assertEqual(len(dominant_lines), 4)
|
| 707 |
+
self.assertGreater(orthogonal_ratio, 1.0)
|
| 708 |
+
|
| 709 |
+
def test_floor_direction_uses_original_image_grout_lines(self):
|
| 710 |
+
height, width = 220, 300
|
| 711 |
+
image_bgr = np.full((height, width, 3), 190, dtype=np.uint8)
|
| 712 |
+
grout_angle = 12.0
|
| 713 |
+
slope = np.tan(np.deg2rad(grout_angle))
|
| 714 |
+
|
| 715 |
+
for y in range(34, height - 32, 34):
|
| 716 |
+
start = (20, y)
|
| 717 |
+
end = (width - 24, int(round(y + (width - 44) * slope)))
|
| 718 |
+
cv2.line(image_bgr, start, end, (58, 58, 58), 2, cv2.LINE_AA)
|
| 719 |
+
|
| 720 |
+
cv2.line(image_bgr, (252, 18), (252, height - 18), (42, 42, 42), 5, cv2.LINE_AA)
|
| 721 |
+
|
| 722 |
+
segmentation = floor_direction.FloorSegmentation(
|
| 723 |
+
label="floor",
|
| 724 |
+
confidence=1.0,
|
| 725 |
+
polygons=[
|
| 726 |
+
floor_direction.FloorPolygon(
|
| 727 |
+
points=[(0, 0), (width - 1, 0), (width - 1, height - 1), (0, height - 1)]
|
| 728 |
+
)
|
| 729 |
+
],
|
| 730 |
+
source_width=width,
|
| 731 |
+
source_height=height,
|
| 732 |
+
)
|
| 733 |
+
|
| 734 |
+
result = floor_direction.analyze_floor_direction(image_bgr, segmentation)
|
| 735 |
+
|
| 736 |
+
self.assertIsNotNone(result.angle_degrees)
|
| 737 |
+
self.assertLess(
|
| 738 |
+
floor_direction.angular_distance_degrees(result.angle_degrees or 0.0, grout_angle),
|
| 739 |
+
5.0,
|
| 740 |
+
)
|
| 741 |
+
self.assertGreaterEqual(result.dominant_line_count, 4)
|
| 742 |
+
|
| 743 |
+
def test_rectified_grout_rotation_snaps_to_the_tile_axes(self):
|
| 744 |
+
lines = [
|
| 745 |
+
floor_direction.DetectedLine(20, 30, 180, 30, 0.0, 160.0),
|
| 746 |
+
floor_direction.DetectedLine(20, 70, 180, 70, 0.0, 160.0),
|
| 747 |
+
floor_direction.DetectedLine(20, 110, 180, 110, 0.0, 160.0),
|
| 748 |
+
floor_direction.DetectedLine(20, 150, 180, 150, 0.0, 160.0),
|
| 749 |
+
]
|
| 750 |
+
rotation_degrees = 14.0
|
| 751 |
+
radians = np.deg2rad(rotation_degrees)
|
| 752 |
+
render_transform = [
|
| 753 |
+
np.cos(radians), -np.sin(radians), 0.0,
|
| 754 |
+
np.sin(radians), np.cos(radians), 0.0,
|
| 755 |
+
0.0, 0.0, 1.0,
|
| 756 |
+
]
|
| 757 |
+
|
| 758 |
+
render_rotation = floor_direction.estimate_rectified_grout_rotation(
|
| 759 |
+
lines,
|
| 760 |
+
render_transform=render_transform,
|
| 761 |
+
)
|
| 762 |
+
|
| 763 |
+
self.assertEqual(render_rotation, 0.0)
|
| 764 |
+
|
| 765 |
+
def test_surface_uv_grout_rotation_uses_renderer_coordinates(self):
|
| 766 |
+
height, width = 180, 240
|
| 767 |
+
lines = [
|
| 768 |
+
floor_direction.DetectedLine(20, 30, 220, 30, 0.0, 200.0),
|
| 769 |
+
floor_direction.DetectedLine(20, 65, 220, 65, 0.0, 200.0),
|
| 770 |
+
floor_direction.DetectedLine(20, 100, 220, 100, 0.0, 200.0),
|
| 771 |
+
floor_direction.DetectedLine(20, 135, 220, 135, 0.0, 200.0),
|
| 772 |
+
]
|
| 773 |
+
yy, xx = np.mgrid[0:height, 0:width]
|
| 774 |
+
angle_radians = np.deg2rad(23.0)
|
| 775 |
+
surface_uv = np.column_stack((
|
| 776 |
+
xx.ravel() * np.cos(angle_radians) - yy.ravel() * np.sin(angle_radians),
|
| 777 |
+
xx.ravel() * np.sin(angle_radians) + yy.ravel() * np.cos(angle_radians),
|
| 778 |
+
)).astype(np.float32)
|
| 779 |
+
surface_indices = np.arange(height * width, dtype=np.uint32)
|
| 780 |
+
surface_plane_ids = np.zeros(height * width, dtype=np.uint8)
|
| 781 |
+
|
| 782 |
+
render_rotation = floor_direction.estimate_surface_uv_grout_rotation(
|
| 783 |
+
lines,
|
| 784 |
+
surface_uv=surface_uv,
|
| 785 |
+
surface_indices=surface_indices,
|
| 786 |
+
surface_plane_ids=surface_plane_ids,
|
| 787 |
+
image_shape=(height, width),
|
| 788 |
+
)
|
| 789 |
+
|
| 790 |
+
self.assertIsNotNone(render_rotation)
|
| 791 |
+
self.assertLess(floor_direction.angular_distance_degrees(render_rotation or 0.0, 23.0), 1.0)
|
| 792 |
+
|
| 793 |
+
def test_surface_uv_rotation_prefers_regular_grout_lattice_over_long_irregular_edges(self):
|
| 794 |
+
lines = [
|
| 795 |
+
floor_direction.DetectedLine(40, y, 280, y, 0.0, 240.0)
|
| 796 |
+
for y in (80, 125, 170, 215, 260)
|
| 797 |
+
]
|
| 798 |
+
for offset in (0, 17, 49, 91, 143, 208, 260, 313):
|
| 799 |
+
radians = np.deg2rad(45.0)
|
| 800 |
+
normal = np.array([-np.sin(radians), np.cos(radians)])
|
| 801 |
+
direction = np.array([np.cos(radians), np.sin(radians)])
|
| 802 |
+
center = np.array([500.0, 350.0]) + normal * offset
|
| 803 |
+
start, end = center - direction * 130.0, center + direction * 130.0
|
| 804 |
+
lines.append(
|
| 805 |
+
floor_direction.DetectedLine(
|
| 806 |
+
float(start[0]),
|
| 807 |
+
float(start[1]),
|
| 808 |
+
float(end[0]),
|
| 809 |
+
float(end[1]),
|
| 810 |
+
45.0,
|
| 811 |
+
260.0,
|
| 812 |
+
)
|
| 813 |
+
)
|
| 814 |
+
|
| 815 |
+
angle = floor_direction.estimate_repeated_grout_orientation(
|
| 816 |
+
lines,
|
| 817 |
+
image_shape=(700, 800),
|
| 818 |
+
)
|
| 819 |
+
|
| 820 |
+
self.assertIsNotNone(angle)
|
| 821 |
+
self.assertLess(floor_direction.angular_distance_degrees(angle or 0.0, 0.0), 1.0)
|
| 822 |
+
|
| 823 |
+
def test_surface_uv_rotation_rectifies_source_before_detecting_grout(self):
|
| 824 |
+
height, width = 180, 240
|
| 825 |
+
image = np.full((height, width, 3), 225, dtype=np.uint8)
|
| 826 |
+
for y in range(30, height - 20, 30):
|
| 827 |
+
cv2.line(image, (20, y), (width - 20, y), (55, 55, 55), 2, cv2.LINE_AA)
|
| 828 |
+
yy, xx = np.mgrid[0:height, 0:width]
|
| 829 |
+
surface_uv = np.column_stack((xx.ravel(), yy.ravel())).astype(np.float32)
|
| 830 |
+
surface_indices = np.arange(height * width, dtype=np.uint32)
|
| 831 |
+
source_lines = [
|
| 832 |
+
floor_direction.DetectedLine(20, 30, width - 20, 30, 0.0, width - 40.0),
|
| 833 |
+
floor_direction.DetectedLine(20, 60, width - 20, 60, 0.0, width - 40.0),
|
| 834 |
+
floor_direction.DetectedLine(20, 90, width - 20, 90, 0.0, width - 40.0),
|
| 835 |
+
floor_direction.DetectedLine(20, 120, width - 20, 120, 0.0, width - 40.0),
|
| 836 |
+
]
|
| 837 |
+
|
| 838 |
+
angle = floor_direction.estimate_surface_uv_grout_rotation(
|
| 839 |
+
source_lines,
|
| 840 |
+
image_bgr=image,
|
| 841 |
+
surface_uv=surface_uv,
|
| 842 |
+
surface_indices=surface_indices,
|
| 843 |
+
surface_plane_ids=np.zeros(height * width, dtype=np.uint8),
|
| 844 |
+
image_shape=(height, width),
|
| 845 |
+
)
|
| 846 |
+
|
| 847 |
+
self.assertIsNotNone(angle)
|
| 848 |
+
self.assertLess(floor_direction.angular_distance_degrees(angle or 0.0, 0.0), 2.0)
|
| 849 |
+
|
| 850 |
+
def test_surface_uv_rotation_handles_perspective_converging_grout(self):
|
| 851 |
+
floor_height, floor_width = 180, 240
|
| 852 |
+
source_height, source_width = 250, 320
|
| 853 |
+
floor = np.full((floor_height, floor_width, 3), 220, dtype=np.uint8)
|
| 854 |
+
for y in range(28, floor_height - 18, 30):
|
| 855 |
+
cv2.line(floor, (12, y), (floor_width - 12, y), (45, 45, 45), 2, cv2.LINE_AA)
|
| 856 |
+
|
| 857 |
+
source_corners = np.array([[62, 42], [278, 68], [248, 218], [24, 194]], dtype=np.float32)
|
| 858 |
+
floor_corners = np.array(
|
| 859 |
+
[[0, 0], [floor_width - 1, 0], [floor_width - 1, floor_height - 1], [0, floor_height - 1]],
|
| 860 |
+
dtype=np.float32,
|
| 861 |
+
)
|
| 862 |
+
uv_to_source = cv2.getPerspectiveTransform(floor_corners, source_corners)
|
| 863 |
+
source = cv2.warpPerspective(floor, uv_to_source, (source_width, source_height))
|
| 864 |
+
surface_mask = np.zeros((source_height, source_width), dtype=np.uint8)
|
| 865 |
+
cv2.fillConvexPoly(surface_mask, source_corners.astype(np.int32), 1)
|
| 866 |
+
yy, xx = np.mgrid[0:source_height, 0:source_width]
|
| 867 |
+
source_points = np.column_stack((xx.ravel(), yy.ravel())).astype(np.float32).reshape(1, -1, 2)
|
| 868 |
+
source_to_uv = np.linalg.inv(uv_to_source)
|
| 869 |
+
uv_all = cv2.perspectiveTransform(source_points, source_to_uv)[0]
|
| 870 |
+
surface_indices = np.flatnonzero(surface_mask.ravel()).astype(np.uint32)
|
| 871 |
+
surface_uv = uv_all[surface_indices]
|
| 872 |
+
distractor_lines = [
|
| 873 |
+
floor_direction.DetectedLine(30, y, 290, y + 45, 10.0, 264.0)
|
| 874 |
+
for y in (20, 54, 101, 158, 215)
|
| 875 |
+
]
|
| 876 |
+
|
| 877 |
+
angle = floor_direction.estimate_surface_uv_grout_rotation(
|
| 878 |
+
distractor_lines,
|
| 879 |
+
image_bgr=source,
|
| 880 |
+
surface_uv=surface_uv,
|
| 881 |
+
surface_indices=surface_indices,
|
| 882 |
+
surface_plane_ids=np.zeros(len(surface_indices), dtype=np.uint8),
|
| 883 |
+
image_shape=(source_height, source_width),
|
| 884 |
+
)
|
| 885 |
+
|
| 886 |
+
self.assertIsNotNone(angle)
|
| 887 |
+
self.assertLess(floor_direction.angular_distance_degrees(angle or 0.0, 0.0), 3.0)
|
| 888 |
+
|
| 889 |
+
def test_floor_direction_metadata_prefers_surface_uv_rotation(self):
|
| 890 |
+
height, width = 180, 240
|
| 891 |
+
image = np.full((height, width, 3), 225, dtype=np.uint8)
|
| 892 |
+
for y in range(30, height - 20, 30):
|
| 893 |
+
image[y:y + 2, 20:width - 20] = 65
|
| 894 |
+
yy, xx = np.mgrid[0:height, 0:width]
|
| 895 |
+
angle_radians = np.deg2rad(23.0)
|
| 896 |
+
surface_uv = np.column_stack((
|
| 897 |
+
xx.ravel() * np.cos(angle_radians) - yy.ravel() * np.sin(angle_radians),
|
| 898 |
+
xx.ravel() * np.sin(angle_radians) + yy.ravel() * np.cos(angle_radians),
|
| 899 |
+
)).astype(np.float32)
|
| 900 |
+
surface_indices = np.arange(height * width, dtype=np.uint32)
|
| 901 |
+
surface_plane_ids = np.zeros(height * width, dtype=np.uint8)
|
| 902 |
+
|
| 903 |
+
metadata = app.analyze_floor_direction_for_surface_mask(
|
| 904 |
+
image,
|
| 905 |
+
np.ones((height, width), dtype=np.uint8),
|
| 906 |
+
surface_uv=surface_uv,
|
| 907 |
+
surface_indices=surface_indices,
|
| 908 |
+
surface_plane_ids=surface_plane_ids,
|
| 909 |
+
)
|
| 910 |
+
|
| 911 |
+
self.assertLess(
|
| 912 |
+
floor_direction.angular_distance_degrees(metadata["renderAngleDegrees"] or 0.0, 23.0),
|
| 913 |
+
1.0,
|
| 914 |
+
)
|
| 915 |
+
self.assertIn("grout_direction_projected_to_surface_uv", metadata["warnings"])
|
| 916 |
+
|
| 917 |
+
def test_direction_finder_detects_multi_region_material_axis(self):
|
| 918 |
+
size = 320
|
| 919 |
+
gray = np.full((size, size), 205, dtype=np.uint8)
|
| 920 |
+
angle_degrees = 27.0
|
| 921 |
+
radians = np.deg2rad(angle_degrees)
|
| 922 |
+
direction = np.array([np.cos(radians), np.sin(radians)])
|
| 923 |
+
normal = np.array([-direction[1], direction[0]])
|
| 924 |
+
center = np.array([size / 2, size / 2])
|
| 925 |
+
for offset in range(-360, 361, 30):
|
| 926 |
+
line_center = center + normal * offset
|
| 927 |
+
start = np.rint(line_center - direction * 300).astype(int)
|
| 928 |
+
end = np.rint(line_center + direction * 300).astype(int)
|
| 929 |
+
cv2.line(gray, tuple(start), tuple(end), 45, 3, cv2.LINE_AA)
|
| 930 |
+
|
| 931 |
+
cue = direction_finder.estimate_material_cue(
|
| 932 |
+
gray,
|
| 933 |
+
np.full_like(gray, 255),
|
| 934 |
+
)
|
| 935 |
+
|
| 936 |
+
self.assertIsNotNone(cue)
|
| 937 |
+
self.assertLess(
|
| 938 |
+
direction_finder.angular_distance(cue.angle_degrees, angle_degrees),
|
| 939 |
+
4.0,
|
| 940 |
+
)
|
| 941 |
+
self.assertGreaterEqual(cue.region_support, 3)
|
| 942 |
+
|
| 943 |
+
def test_direction_finder_rejects_blank_material(self):
|
| 944 |
+
cue = direction_finder.estimate_material_cue(
|
| 945 |
+
np.full((240, 320), 180, dtype=np.uint8),
|
| 946 |
+
np.full((240, 320), 255, dtype=np.uint8),
|
| 947 |
+
)
|
| 948 |
+
|
| 949 |
+
self.assertIsNone(cue)
|
| 950 |
+
|
| 951 |
+
def test_direction_finder_uses_wall_normals_for_manhattan_axis(self):
|
| 952 |
+
height, width = 240, 320
|
| 953 |
+
wall_mask = np.ones((height, width), dtype=np.uint8)
|
| 954 |
+
normals = np.zeros((height, width, 3), dtype=np.float32)
|
| 955 |
+
radians = np.deg2rad(20.0)
|
| 956 |
+
normals[:, :, 0] = np.cos(radians)
|
| 957 |
+
normals[:, :, 2] = np.sin(radians)
|
| 958 |
+
|
| 959 |
+
cue = direction_finder.estimate_wall_normal_cue(
|
| 960 |
+
normals,
|
| 961 |
+
np.ones((height, width), dtype=bool),
|
| 962 |
+
wall_mask,
|
| 963 |
+
floor_normal=np.array([0.0, 1.0, 0.0]),
|
| 964 |
+
render_u_axis=np.array([1.0, 0.0, 0.0]),
|
| 965 |
+
render_v_axis=np.array([0.0, 0.0, 1.0]),
|
| 966 |
+
intrinsics=np.eye(3),
|
| 967 |
+
render_transform=np.eye(3),
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
self.assertIsNotNone(cue)
|
| 971 |
+
self.assertLess(
|
| 972 |
+
direction_finder.angular_distance(cue.angle_degrees, 20.0, period=90.0),
|
| 973 |
+
1.0,
|
| 974 |
+
)
|
| 975 |
+
self.assertGreater(cue.confidence, 0.7)
|
| 976 |
+
self.assertEqual(cue.ambiguity_degrees, 90.0)
|
| 977 |
+
|
| 978 |
+
def test_direction_finder_uses_room_architectural_lines(self):
|
| 979 |
+
height, width = 240, 320
|
| 980 |
+
image = np.full((height, width, 3), 220, dtype=np.uint8)
|
| 981 |
+
for y in (30, 75, 120, 165, 210):
|
| 982 |
+
cv2.line(image, (10, y), (width - 10, y), (30, 30, 30), 3, cv2.LINE_AA)
|
| 983 |
+
intrinsics = np.array(
|
| 984 |
+
[[300.0, 0.0, width / 2], [0.0, 300.0, height / 2], [0.0, 0.0, 1.0]],
|
| 985 |
+
dtype=np.float64,
|
| 986 |
+
)
|
| 987 |
+
|
| 988 |
+
cue = direction_finder.estimate_architectural_line_cue(
|
| 989 |
+
image,
|
| 990 |
+
np.ones((height, width), dtype=np.uint8),
|
| 991 |
+
floor_normal=np.array([0.0, 1.0, 0.0]),
|
| 992 |
+
render_u_axis=np.array([1.0, 0.0, 0.0]),
|
| 993 |
+
render_v_axis=np.array([0.0, 0.0, 1.0]),
|
| 994 |
+
intrinsics=intrinsics,
|
| 995 |
+
render_transform=np.eye(3),
|
| 996 |
+
)
|
| 997 |
+
|
| 998 |
+
self.assertIsNotNone(cue)
|
| 999 |
+
self.assertLess(
|
| 1000 |
+
direction_finder.angular_distance(cue.angle_degrees, 0.0, period=90.0),
|
| 1001 |
+
1.0,
|
| 1002 |
+
)
|
| 1003 |
+
self.assertGreater(cue.confidence, 0.7)
|
| 1004 |
+
self.assertGreaterEqual(cue.region_support, 3)
|
| 1005 |
+
|
| 1006 |
+
def test_direction_finder_rectifies_perspective_material_before_scoring(self):
|
| 1007 |
+
floor_height, floor_width = 190, 250
|
| 1008 |
+
source_height, source_width = 260, 340
|
| 1009 |
+
floor = np.full((floor_height, floor_width, 3), 210, dtype=np.uint8)
|
| 1010 |
+
angle_degrees = 24.0
|
| 1011 |
+
radians = np.deg2rad(angle_degrees)
|
| 1012 |
+
direction = np.array([np.cos(radians), np.sin(radians)])
|
| 1013 |
+
normal = np.array([-direction[1], direction[0]])
|
| 1014 |
+
center = np.array([floor_width / 2, floor_height / 2])
|
| 1015 |
+
for offset in range(-320, 321, 28):
|
| 1016 |
+
line_center = center + normal * offset
|
| 1017 |
+
start = np.rint(line_center - direction * 280).astype(int)
|
| 1018 |
+
end = np.rint(line_center + direction * 280).astype(int)
|
| 1019 |
+
cv2.line(floor, tuple(start), tuple(end), (45, 45, 45), 3, cv2.LINE_AA)
|
| 1020 |
+
|
| 1021 |
+
source_corners = np.array(
|
| 1022 |
+
[[72, 42], [290, 64], [310, 235], [28, 218]],
|
| 1023 |
+
dtype=np.float32,
|
| 1024 |
+
)
|
| 1025 |
+
floor_corners = np.array(
|
| 1026 |
+
[[0, 0], [floor_width - 1, 0], [floor_width - 1, floor_height - 1], [0, floor_height - 1]],
|
| 1027 |
+
dtype=np.float32,
|
| 1028 |
+
)
|
| 1029 |
+
uv_to_source = cv2.getPerspectiveTransform(floor_corners, source_corners)
|
| 1030 |
+
source = cv2.warpPerspective(floor, uv_to_source, (source_width, source_height))
|
| 1031 |
+
surface_mask = np.zeros((source_height, source_width), dtype=np.uint8)
|
| 1032 |
+
cv2.fillConvexPoly(surface_mask, source_corners.astype(np.int32), 1)
|
| 1033 |
+
yy, xx = np.mgrid[0:source_height, 0:source_width]
|
| 1034 |
+
source_points = np.column_stack((xx.ravel(), yy.ravel())).astype(np.float32).reshape(1, -1, 2)
|
| 1035 |
+
source_to_uv = np.linalg.inv(uv_to_source)
|
| 1036 |
+
all_uv = cv2.perspectiveTransform(source_points, source_to_uv)[0]
|
| 1037 |
+
surface_indices = np.flatnonzero(surface_mask.ravel()).astype(np.uint32)
|
| 1038 |
+
surface_uv = all_uv[surface_indices]
|
| 1039 |
+
|
| 1040 |
+
result = direction_finder.find_floor_direction(
|
| 1041 |
+
source,
|
| 1042 |
+
surface_mask,
|
| 1043 |
+
wall_mask=np.zeros_like(surface_mask),
|
| 1044 |
+
structure_mask=np.zeros_like(surface_mask),
|
| 1045 |
+
normals_map=None,
|
| 1046 |
+
geometry_valid_mask=None,
|
| 1047 |
+
intrinsics=np.eye(3),
|
| 1048 |
+
floor_normal=None,
|
| 1049 |
+
render_u_axis=None,
|
| 1050 |
+
render_v_axis=None,
|
| 1051 |
+
render_transform=source_to_uv,
|
| 1052 |
+
surface_uv=surface_uv,
|
| 1053 |
+
surface_indices=surface_indices,
|
| 1054 |
+
surface_plane_ids=np.zeros(len(surface_indices), dtype=np.uint8),
|
| 1055 |
+
)
|
| 1056 |
+
|
| 1057 |
+
self.assertFalse(result["needsUserDirection"])
|
| 1058 |
+
self.assertLess(
|
| 1059 |
+
direction_finder.angular_distance(result["renderAngleDegrees"], angle_degrees),
|
| 1060 |
+
4.0,
|
| 1061 |
+
)
|
| 1062 |
+
self.assertEqual(result["rectification"]["source"], "surface-uv")
|
| 1063 |
+
|
| 1064 |
+
def test_direction_finder_marks_unobservable_image(self):
|
| 1065 |
+
height, width = 180, 240
|
| 1066 |
+
surface_mask = np.ones((height, width), dtype=np.uint8)
|
| 1067 |
+
result = direction_finder.find_floor_direction(
|
| 1068 |
+
np.full((height, width, 3), 180, dtype=np.uint8),
|
| 1069 |
+
surface_mask,
|
| 1070 |
+
wall_mask=np.zeros_like(surface_mask),
|
| 1071 |
+
structure_mask=np.zeros_like(surface_mask),
|
| 1072 |
+
normals_map=None,
|
| 1073 |
+
geometry_valid_mask=None,
|
| 1074 |
+
intrinsics=np.eye(3),
|
| 1075 |
+
floor_normal=None,
|
| 1076 |
+
render_u_axis=None,
|
| 1077 |
+
render_v_axis=None,
|
| 1078 |
+
render_transform=np.eye(3),
|
| 1079 |
+
surface_uv=None,
|
| 1080 |
+
surface_indices=None,
|
| 1081 |
+
surface_plane_ids=None,
|
| 1082 |
+
)
|
| 1083 |
+
|
| 1084 |
+
self.assertEqual(result["source"], "backend-direction-finder-v2")
|
| 1085 |
+
self.assertEqual(result["directionMethod"], "canonical-render-axis")
|
| 1086 |
+
self.assertTrue(result["needsUserDirection"])
|
| 1087 |
+
self.assertEqual(result["confidence"], 0.0)
|
| 1088 |
+
|
| 1089 |
+
def test_floor_direction_parser_does_not_use_non_floor_segment(self):
|
| 1090 |
+
payload = {
|
| 1091 |
+
"width": 120,
|
| 1092 |
+
"height": 80,
|
| 1093 |
+
"segments": [
|
| 1094 |
+
{
|
| 1095 |
+
"label": "wall",
|
| 1096 |
+
"confidence": 0.98,
|
| 1097 |
+
"polygons": [
|
| 1098 |
+
{
|
| 1099 |
+
"points": [[0, 0], [119, 0], [119, 79], [0, 79]],
|
| 1100 |
+
"bbox": [0, 0, 120, 80],
|
| 1101 |
+
}
|
| 1102 |
+
],
|
| 1103 |
+
}
|
| 1104 |
+
],
|
| 1105 |
}
|
| 1106 |
|
| 1107 |
+
segmentation = app.parse_floor_segmentation(payload)
|
| 1108 |
+
|
| 1109 |
+
self.assertEqual(segmentation.label, "unknown")
|
| 1110 |
+
self.assertEqual(segmentation.polygons, [])
|
| 1111 |
+
self.assertIn("segmentation_response_list_without_floor_label", segmentation.warnings)
|
| 1112 |
+
|
| 1113 |
+
def test_floor_direction_metadata_from_surface_mask(self):
|
| 1114 |
+
height, width = 180, 240
|
| 1115 |
+
image = np.full((height, width, 3), 225, dtype=np.uint8)
|
| 1116 |
+
for y in range(35, height - 20, 32):
|
| 1117 |
+
image[y:y + 2, 20:width - 20] = 70
|
| 1118 |
+
surface_mask = np.ones((height, width), dtype=np.uint8)
|
| 1119 |
+
|
| 1120 |
+
metadata = app.analyze_floor_direction_for_surface_mask(
|
| 1121 |
+
image,
|
| 1122 |
+
surface_mask,
|
| 1123 |
+
render_transform=[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0],
|
| 1124 |
+
)
|
| 1125 |
|
| 1126 |
+
self.assertEqual(metadata["source"], "backend-floor-direction")
|
| 1127 |
+
self.assertIsNotNone(metadata["angleDegrees"])
|
| 1128 |
+
self.assertEqual(metadata["renderAngleDegrees"], 0.0)
|
| 1129 |
+
self.assertEqual(metadata["directionLabel"], "left_to_right")
|
| 1130 |
+
self.assertGreater(metadata["lineCount"], 0)
|
| 1131 |
+
self.assertEqual(metadata["segmentation"]["label"], "floor")
|
| 1132 |
|
| 1133 |
|
| 1134 |
if __name__ == "__main__":
|
visualizer.gpu.toml
CHANGED
|
@@ -11,6 +11,9 @@ mask2former_model_name = "facebook/mask2former-swin-small-ade-semantic"
|
|
| 11 |
segformer_model_name = "nvidia/segformer-b2-finetuned-ade-512-512"
|
| 12 |
depth_model_name = "depth-anything/Depth-Anything-V2-Metric-Indoor-Large-hf"
|
| 13 |
intrinsic_model_version = "v2"
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
[runtime]
|
| 16 |
enable_depth_estimation = true
|
|
@@ -19,6 +22,11 @@ enable_plane_fit = true
|
|
| 19 |
enable_multi_plane_surfaces = true
|
| 20 |
enable_intrinsic_shading = true
|
| 21 |
enable_shading_transfer = true
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
data_dir = "data"
|
| 23 |
|
| 24 |
[surface_mapping]
|
|
@@ -27,10 +35,20 @@ max_planes = 5
|
|
| 27 |
normal_angle_threshold_degrees = 35
|
| 28 |
normal_smoothing_kernel = 5
|
| 29 |
min_plane_pixels = 1500
|
| 30 |
-
edge_close_ratio = 0.
|
| 31 |
-
edge_kernel_ratio = 0.
|
| 32 |
-
edge_dilation_iterations =
|
|
|
|
|
|
|
|
|
|
| 33 |
uv_min_coverage = 0.995
|
| 34 |
uv_max_bad_neighbor_ratio = 0.035
|
| 35 |
uv_max_jump_ratio = 8.0
|
| 36 |
uv_absolute_jump_meters = 0.35
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
segformer_model_name = "nvidia/segformer-b2-finetuned-ade-512-512"
|
| 12 |
depth_model_name = "depth-anything/Depth-Anything-V2-Metric-Indoor-Large-hf"
|
| 13 |
intrinsic_model_version = "v2"
|
| 14 |
+
sam2_model_name = "facebook/sam2-hiera-large"
|
| 15 |
+
sam2_model_cfg = ""
|
| 16 |
+
sam2_checkpoint = ""
|
| 17 |
|
| 18 |
[runtime]
|
| 19 |
enable_depth_estimation = true
|
|
|
|
| 22 |
enable_multi_plane_surfaces = true
|
| 23 |
enable_intrinsic_shading = true
|
| 24 |
enable_shading_transfer = true
|
| 25 |
+
enable_sam_refinement = false
|
| 26 |
+
enable_floor_mask_cleanup = false
|
| 27 |
+
warm_start_models = true
|
| 28 |
+
bundle_image_format = "jpeg"
|
| 29 |
+
bundle_image_quality = 92
|
| 30 |
data_dir = "data"
|
| 31 |
|
| 32 |
[surface_mapping]
|
|
|
|
| 35 |
normal_angle_threshold_degrees = 35
|
| 36 |
normal_smoothing_kernel = 5
|
| 37 |
min_plane_pixels = 1500
|
| 38 |
+
edge_close_ratio = 0.009
|
| 39 |
+
edge_kernel_ratio = 0.006
|
| 40 |
+
edge_dilation_iterations = 2
|
| 41 |
+
soft_floor_covering_expansion_enabled = true
|
| 42 |
+
soft_floor_covering_kernel_ratio = 0.008
|
| 43 |
+
soft_floor_covering_dilation_iterations = 2
|
| 44 |
uv_min_coverage = 0.995
|
| 45 |
uv_max_bad_neighbor_ratio = 0.035
|
| 46 |
uv_max_jump_ratio = 8.0
|
| 47 |
uv_absolute_jump_meters = 0.35
|
| 48 |
+
enable_geometry_surface_filter = true
|
| 49 |
+
plane_distance_threshold_meters = 0.12
|
| 50 |
+
plane_normal_min_cos = 0.45
|
| 51 |
+
plane_filter_min_keep_ratio = 0.45
|
| 52 |
+
|
| 53 |
+
[gemini]
|
| 54 |
+
image_model = "gemini-3.1-flash-image"
|
visualizer.hf.toml
CHANGED
|
@@ -11,6 +11,9 @@ mask2former_model_name = "facebook/mask2former-swin-small-ade-semantic"
|
|
| 11 |
segformer_model_name = "nvidia/segformer-b2-finetuned-ade-512-512"
|
| 12 |
depth_model_name = "depth-anything/Depth-Anything-V2-Metric-Indoor-Large-hf"
|
| 13 |
intrinsic_model_version = "v2"
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
[runtime]
|
| 16 |
enable_depth_estimation = true
|
|
@@ -19,6 +22,7 @@ enable_plane_fit = true
|
|
| 19 |
enable_multi_plane_surfaces = true
|
| 20 |
enable_intrinsic_shading = true
|
| 21 |
enable_shading_transfer = true
|
|
|
|
| 22 |
data_dir = "data"
|
| 23 |
|
| 24 |
[surface_mapping]
|
|
@@ -27,10 +31,17 @@ max_planes = 5
|
|
| 27 |
normal_angle_threshold_degrees = 35
|
| 28 |
normal_smoothing_kernel = 5
|
| 29 |
min_plane_pixels = 1500
|
| 30 |
-
edge_close_ratio = 0.
|
| 31 |
-
edge_kernel_ratio = 0.
|
| 32 |
-
edge_dilation_iterations =
|
|
|
|
|
|
|
|
|
|
| 33 |
uv_min_coverage = 0.995
|
| 34 |
uv_max_bad_neighbor_ratio = 0.035
|
| 35 |
uv_max_jump_ratio = 8.0
|
| 36 |
uv_absolute_jump_meters = 0.35
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
segformer_model_name = "nvidia/segformer-b2-finetuned-ade-512-512"
|
| 12 |
depth_model_name = "depth-anything/Depth-Anything-V2-Metric-Indoor-Large-hf"
|
| 13 |
intrinsic_model_version = "v2"
|
| 14 |
+
sam2_model_name = "facebook/sam2-hiera-large"
|
| 15 |
+
sam2_model_cfg = ""
|
| 16 |
+
sam2_checkpoint = ""
|
| 17 |
|
| 18 |
[runtime]
|
| 19 |
enable_depth_estimation = true
|
|
|
|
| 22 |
enable_multi_plane_surfaces = true
|
| 23 |
enable_intrinsic_shading = true
|
| 24 |
enable_shading_transfer = true
|
| 25 |
+
enable_sam_refinement = true
|
| 26 |
data_dir = "data"
|
| 27 |
|
| 28 |
[surface_mapping]
|
|
|
|
| 31 |
normal_angle_threshold_degrees = 35
|
| 32 |
normal_smoothing_kernel = 5
|
| 33 |
min_plane_pixels = 1500
|
| 34 |
+
edge_close_ratio = 0.009
|
| 35 |
+
edge_kernel_ratio = 0.006
|
| 36 |
+
edge_dilation_iterations = 2
|
| 37 |
+
soft_floor_covering_expansion_enabled = true
|
| 38 |
+
soft_floor_covering_kernel_ratio = 0.008
|
| 39 |
+
soft_floor_covering_dilation_iterations = 2
|
| 40 |
uv_min_coverage = 0.995
|
| 41 |
uv_max_bad_neighbor_ratio = 0.035
|
| 42 |
uv_max_jump_ratio = 8.0
|
| 43 |
uv_absolute_jump_meters = 0.35
|
| 44 |
+
enable_geometry_surface_filter = true
|
| 45 |
+
plane_distance_threshold_meters = 0.12
|
| 46 |
+
plane_normal_min_cos = 0.45
|
| 47 |
+
plane_filter_min_keep_ratio = 0.45
|
visualizer.local.toml
CHANGED
|
@@ -6,6 +6,9 @@
|
|
| 6 |
segmentation_model = "segformer"
|
| 7 |
segformer_model_name = "nvidia/segformer-b2-finetuned-ade-512-512"
|
| 8 |
depth_model_name = "Intel/dpt-large"
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
[runtime]
|
| 11 |
enable_depth_estimation = false
|
|
@@ -13,6 +16,10 @@ enable_plane_fit = true
|
|
| 13 |
enable_multi_plane_surfaces = true
|
| 14 |
enable_intrinsic_shading = false
|
| 15 |
enable_shading_transfer = true
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
data_dir = "data"
|
| 17 |
|
| 18 |
[surface_mapping]
|
|
@@ -21,10 +28,17 @@ max_planes = 5
|
|
| 21 |
normal_angle_threshold_degrees = 35
|
| 22 |
normal_smoothing_kernel = 5
|
| 23 |
min_plane_pixels = 1500
|
| 24 |
-
edge_close_ratio = 0.
|
| 25 |
-
edge_kernel_ratio = 0.
|
| 26 |
-
edge_dilation_iterations =
|
|
|
|
|
|
|
|
|
|
| 27 |
uv_min_coverage = 0.995
|
| 28 |
uv_max_bad_neighbor_ratio = 0.035
|
| 29 |
uv_max_jump_ratio = 8.0
|
| 30 |
uv_absolute_jump_meters = 0.35
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
segmentation_model = "segformer"
|
| 7 |
segformer_model_name = "nvidia/segformer-b2-finetuned-ade-512-512"
|
| 8 |
depth_model_name = "Intel/dpt-large"
|
| 9 |
+
sam2_model_name = "facebook/sam2-hiera-large"
|
| 10 |
+
sam2_model_cfg = ""
|
| 11 |
+
sam2_checkpoint = ""
|
| 12 |
|
| 13 |
[runtime]
|
| 14 |
enable_depth_estimation = false
|
|
|
|
| 16 |
enable_multi_plane_surfaces = true
|
| 17 |
enable_intrinsic_shading = false
|
| 18 |
enable_shading_transfer = true
|
| 19 |
+
enable_sam_refinement = false
|
| 20 |
+
warm_start_models = true
|
| 21 |
+
bundle_image_format = "jpeg"
|
| 22 |
+
bundle_image_quality = 92
|
| 23 |
data_dir = "data"
|
| 24 |
|
| 25 |
[surface_mapping]
|
|
|
|
| 28 |
normal_angle_threshold_degrees = 35
|
| 29 |
normal_smoothing_kernel = 5
|
| 30 |
min_plane_pixels = 1500
|
| 31 |
+
edge_close_ratio = 0.009
|
| 32 |
+
edge_kernel_ratio = 0.006
|
| 33 |
+
edge_dilation_iterations = 2
|
| 34 |
+
soft_floor_covering_expansion_enabled = true
|
| 35 |
+
soft_floor_covering_kernel_ratio = 0.008
|
| 36 |
+
soft_floor_covering_dilation_iterations = 2
|
| 37 |
uv_min_coverage = 0.995
|
| 38 |
uv_max_bad_neighbor_ratio = 0.035
|
| 39 |
uv_max_jump_ratio = 8.0
|
| 40 |
uv_absolute_jump_meters = 0.35
|
| 41 |
+
enable_geometry_surface_filter = false
|
| 42 |
+
plane_distance_threshold_meters = 0.12
|
| 43 |
+
plane_normal_min_cos = 0.45
|
| 44 |
+
plane_filter_min_keep_ratio = 0.45
|
visualizer.segformer.toml
CHANGED
|
@@ -7,6 +7,9 @@
|
|
| 7 |
segmentation_model = "segformer"
|
| 8 |
segformer_model_name = "nvidia/segformer-b2-finetuned-ade-512-512"
|
| 9 |
depth_model_name = "Intel/dpt-large"
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
[runtime]
|
| 12 |
enable_depth_estimation = false
|
|
@@ -14,6 +17,7 @@ enable_plane_fit = true
|
|
| 14 |
enable_multi_plane_surfaces = true
|
| 15 |
enable_intrinsic_shading = false
|
| 16 |
enable_shading_transfer = true
|
|
|
|
| 17 |
data_dir = "data"
|
| 18 |
|
| 19 |
[surface_mapping]
|
|
@@ -22,10 +26,17 @@ max_planes = 5
|
|
| 22 |
normal_angle_threshold_degrees = 35
|
| 23 |
normal_smoothing_kernel = 5
|
| 24 |
min_plane_pixels = 1500
|
| 25 |
-
edge_close_ratio = 0.
|
| 26 |
-
edge_kernel_ratio = 0.
|
| 27 |
-
edge_dilation_iterations =
|
|
|
|
|
|
|
|
|
|
| 28 |
uv_min_coverage = 0.995
|
| 29 |
uv_max_bad_neighbor_ratio = 0.035
|
| 30 |
uv_max_jump_ratio = 8.0
|
| 31 |
uv_absolute_jump_meters = 0.35
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
segmentation_model = "segformer"
|
| 8 |
segformer_model_name = "nvidia/segformer-b2-finetuned-ade-512-512"
|
| 9 |
depth_model_name = "Intel/dpt-large"
|
| 10 |
+
sam2_model_name = "facebook/sam2-hiera-large"
|
| 11 |
+
sam2_model_cfg = ""
|
| 12 |
+
sam2_checkpoint = ""
|
| 13 |
|
| 14 |
[runtime]
|
| 15 |
enable_depth_estimation = false
|
|
|
|
| 17 |
enable_multi_plane_surfaces = true
|
| 18 |
enable_intrinsic_shading = false
|
| 19 |
enable_shading_transfer = true
|
| 20 |
+
enable_sam_refinement = false
|
| 21 |
data_dir = "data"
|
| 22 |
|
| 23 |
[surface_mapping]
|
|
|
|
| 26 |
normal_angle_threshold_degrees = 35
|
| 27 |
normal_smoothing_kernel = 5
|
| 28 |
min_plane_pixels = 1500
|
| 29 |
+
edge_close_ratio = 0.009
|
| 30 |
+
edge_kernel_ratio = 0.006
|
| 31 |
+
edge_dilation_iterations = 2
|
| 32 |
+
soft_floor_covering_expansion_enabled = true
|
| 33 |
+
soft_floor_covering_kernel_ratio = 0.008
|
| 34 |
+
soft_floor_covering_dilation_iterations = 2
|
| 35 |
uv_min_coverage = 0.995
|
| 36 |
uv_max_bad_neighbor_ratio = 0.035
|
| 37 |
uv_max_jump_ratio = 8.0
|
| 38 |
uv_absolute_jump_meters = 0.35
|
| 39 |
+
enable_geometry_surface_filter = false
|
| 40 |
+
plane_distance_threshold_meters = 0.12
|
| 41 |
+
plane_normal_min_cos = 0.45
|
| 42 |
+
plane_filter_min_keep_ratio = 0.45
|