github-actions[bot] commited on
Commit
f4744e4
·
1 Parent(s): 44808d4

Automated Deploy: 1177f317e28f4f0a450728a1162c0b57013fcb64

Browse files
.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,4 +41,10 @@ data/jobs/
38
  # Logs
39
  *.log
40
  uvicorn.log
 
 
 
 
 
 
41
  data/
 
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
50
  data/
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
@@ -51,6 +51,43 @@ SPACES_UPLOAD_PREFIX="room-uploads"
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
  GPU run:
55
 
56
  ```bash
 
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
+ `/qa/runs/{run_id}/events` streams run updates as Server-Sent Events so the
73
+ debug page does not need to poll while a run is active. Playwright writes
74
+ incremental progress after every completed test, so the `completed`, `passed`,
75
+ and `failed` counters update before the final report is generated.
76
+
77
+ On Hugging Face, the deploy workflow copies a minimal `frontend/viz2d-demo` QA
78
+ runner folder into the Space: npm manifests, Playwright config, e2e tests, and
79
+ the Markdown report script. It intentionally does not copy frontend image
80
+ assets or `test-images`; real QA images are downloaded from DigitalOcean during
81
+ each run. The Dockerfile installs Node, npm, Playwright, and Chromium during the
82
+ Space rebuild. For non-Hugging Face servers, install the Node runner
83
+ dependencies manually:
84
+
85
+ ```bash
86
+ cd /mnt/room-editor/frontend/viz2d-demo
87
+ npm install
88
+ npx playwright install --with-deps chromium
89
+ ```
90
+
91
  GPU run:
92
 
93
  ```bash
SETUP.md CHANGED
@@ -51,3 +51,45 @@ SPACES_UPLOAD_PREFIX="room-uploads"
51
  `SPACES_ENDPOINT_URL` is optional and defaults to
52
  `https://$SPACES_REGION.digitaloceanspaces.com`. `SPACES_ACL` defaults to
53
  `private`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ```
app.py CHANGED
@@ -1,14 +1,18 @@
1
  import asyncio
2
- import base64
3
- import hashlib
4
- import io
5
- import json
6
- import os
7
- import time
8
- import urllib.error
9
- import urllib.parse
10
- import urllib.request
11
- import zipfile
 
 
 
 
12
  try:
13
  import tomllib
14
  except ImportError:
@@ -22,7 +26,7 @@ except ImportError:
22
  "No TOML library found. Please run on Python 3.11+, or run 'pip install tomli' to support Python 3.10."
23
  )
24
  import uuid
25
- from pathlib import Path
26
 
27
  try:
28
  from dotenv import load_dotenv
@@ -32,9 +36,10 @@ except ImportError:
32
  import cv2
33
  import numpy as np
34
  import torch
35
- from fastapi import FastAPI, File, Form, HTTPException, Response, UploadFile, BackgroundTasks
36
- from fastapi.middleware.cors import CORSMiddleware
37
- from fastapi.middleware.gzip import GZipMiddleware
 
38
  from fastapi.staticfiles import StaticFiles
39
  from PIL import Image, ImageOps
40
  from transformers import (
@@ -94,7 +99,9 @@ def load_config() -> dict:
94
  return tomllib.load(config_file)
95
 
96
 
97
- CONFIG = load_config()
 
 
98
 
99
 
100
  def config_value(env_name: str, section: str, key: str, default):
@@ -328,13 +335,55 @@ GEMINI_API_BASE_URL = str(config_value(
328
  "api_base_url",
329
  "https://generativelanguage.googleapis.com/v1/models",
330
  )).rstrip("/")
331
- GEMINI_TIMEOUT_SECONDS = float(config_value(
332
- "GEMINI_TIMEOUT_SECONDS",
333
- "gemini",
334
- "timeout_seconds",
335
- "120",
336
- ))
337
- SURFACE_RANSAC_DISTANCE = float(config_value(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
338
  "SURFACE_RANSAC_DISTANCE",
339
  "surface_mapping",
340
  "ransac_distance_threshold",
@@ -656,14 +705,16 @@ app.add_middleware(GZipMiddleware, minimum_size=1024)
656
  def startup_warm_start_models():
657
  warm_start_models()
658
 
659
- DATA_DIR = Path(VISUALIZER_DATA_DIR).resolve()
660
- UPLOAD_DIR = DATA_DIR / "uploads"
661
- JOB_DIR = DATA_DIR / "jobs"
662
- MATERIAL_DIR = DATA_DIR / "materials"
663
- UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
664
- JOB_DIR.mkdir(parents=True, exist_ok=True)
665
- MATERIAL_DIR.mkdir(parents=True, exist_ok=True)
666
- app.mount("/uploads", StaticFiles(directory=UPLOAD_DIR), name="uploads")
 
 
667
 
668
 
669
  def _debug_resize_rgb(image_rgb: np.ndarray) -> np.ndarray:
@@ -3978,11 +4029,11 @@ def spaces_upload_key(job_id: str, upload_path: Path) -> str:
3978
  return "/".join(part for part in [SPACES_UPLOAD_PREFIX, date_prefix, filename] if part)
3979
 
3980
 
3981
- def upload_input_image_to_spaces(
3982
- job_id: str,
3983
- upload_path: Path,
3984
- original_filename: str | None,
3985
- content_type: str | None,
3986
  ):
3987
  if not spaces_upload_enabled():
3988
  return
@@ -4027,11 +4078,557 @@ def upload_input_image_to_spaces(
4027
  }
4028
  write_job(job)
4029
  print(f"Uploaded input image for job {job_id} to DigitalOcean Spaces: {SPACES_BUCKET}/{key}", flush=True)
4030
- except Exception as exc:
4031
- print(f"DigitalOcean Spaces upload failed for job {job_id}: {exc}", flush=True)
4032
-
4033
-
4034
- def run_conversion_task(job_id: str, upload_path: Path):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4035
  debug = PipelineDebugCapture(job_id) if DEBUG_ARTIFACTS_ENABLED else None
4036
  try:
4037
  t_start = time.perf_counter()
@@ -4211,19 +4808,160 @@ async def refine_tile_render_with_gemini(payload: dict):
4211
 
4212
 
4213
  @app.post("/materials/prepare")
4214
- async def prepare_material_maps(
4215
- file: UploadFile = File(...),
4216
- base_roughness: float = Form(0.42),
4217
- ):
4218
  if file.content_type and not file.content_type.startswith("image/"):
4219
  raise HTTPException(status_code=400, detail="Upload must be a tile image.")
4220
  contents = await file.read()
4221
  if not contents:
4222
- raise HTTPException(status_code=400, detail="Upload must not be empty.")
4223
- return build_tile_material_package(contents, base_roughness)
4224
-
4225
-
4226
- @app.post("/viz2d/convert")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4227
  async def convert_to_viz2d(background_tasks: BackgroundTasks, file: UploadFile = File(...)):
4228
  if file.content_type and not file.content_type.startswith("image/"):
4229
  raise HTTPException(status_code=400, detail="Upload must be a JPG or PNG image.")
 
1
  import asyncio
2
+ import base64
3
+ import hashlib
4
+ import io
5
+ import json
6
+ import mimetypes
7
+ import os
8
+ import shutil
9
+ import subprocess
10
+ import time
11
+ import urllib.error
12
+ import urllib.parse
13
+ import urllib.request
14
+ import zipfile
15
+ from datetime import datetime, timedelta, timezone
16
  try:
17
  import tomllib
18
  except ImportError:
 
26
  "No TOML library found. Please run on Python 3.11+, or run 'pip install tomli' to support Python 3.10."
27
  )
28
  import uuid
29
+ from pathlib import Path
30
 
31
  try:
32
  from dotenv import load_dotenv
 
36
  import cv2
37
  import numpy as np
38
  import torch
39
+ from fastapi import BackgroundTasks, Body, FastAPI, File, Form, HTTPException, Query, Request, Response, UploadFile
40
+ from fastapi.middleware.cors import CORSMiddleware
41
+ from fastapi.responses import StreamingResponse
42
+ from fastapi.middleware.gzip import GZipMiddleware
43
  from fastapi.staticfiles import StaticFiles
44
  from PIL import Image, ImageOps
45
  from transformers import (
 
99
  return tomllib.load(config_file)
100
 
101
 
102
+ CONFIG = load_config()
103
+ BACKEND_DIR = Path(__file__).resolve().parent
104
+ REPO_ROOT = BACKEND_DIR.parent.parent
105
 
106
 
107
  def config_value(env_name: str, section: str, key: str, default):
 
335
  "api_base_url",
336
  "https://generativelanguage.googleapis.com/v1/models",
337
  )).rstrip("/")
338
+ GEMINI_TIMEOUT_SECONDS = float(config_value(
339
+ "GEMINI_TIMEOUT_SECONDS",
340
+ "gemini",
341
+ "timeout_seconds",
342
+ "120",
343
+ ))
344
+ QA_FRONTEND_URL = str(config_value(
345
+ "QA_FRONTEND_URL",
346
+ "qa",
347
+ "frontend_url",
348
+ "",
349
+ )).strip().rstrip("/")
350
+ QA_BACKEND_URL = str(config_value(
351
+ "QA_BACKEND_URL",
352
+ "qa",
353
+ "backend_url",
354
+ "",
355
+ )).strip().rstrip("/")
356
+ QA_FRONTEND_DIR = Path(str(config_value(
357
+ "QA_FRONTEND_DIR",
358
+ "qa",
359
+ "frontend_dir",
360
+ str(REPO_ROOT / "frontend" / "viz2d-demo"),
361
+ ))).expanduser()
362
+ QA_MAX_IMAGES = max(1, int(config_value(
363
+ "QA_MAX_IMAGES",
364
+ "qa",
365
+ "max_images",
366
+ "50",
367
+ )))
368
+ QA_MAX_TESTS = max(1, int(config_value(
369
+ "QA_MAX_TESTS",
370
+ "qa",
371
+ "max_tests",
372
+ "200",
373
+ )))
374
+ QA_RUN_TIMEOUT_SECONDS = max(60, int(config_value(
375
+ "QA_RUN_TIMEOUT_SECONDS",
376
+ "qa",
377
+ "run_timeout_seconds",
378
+ "7200",
379
+ )))
380
+ QA_PRESIGNED_URL_EXPIRES_SECONDS = max(60, int(config_value(
381
+ "QA_PRESIGNED_URL_EXPIRES_SECONDS",
382
+ "qa",
383
+ "presigned_url_expires_seconds",
384
+ "3600",
385
+ )))
386
+ SURFACE_RANSAC_DISTANCE = float(config_value(
387
  "SURFACE_RANSAC_DISTANCE",
388
  "surface_mapping",
389
  "ransac_distance_threshold",
 
705
  def startup_warm_start_models():
706
  warm_start_models()
707
 
708
+ DATA_DIR = Path(VISUALIZER_DATA_DIR).resolve()
709
+ UPLOAD_DIR = DATA_DIR / "uploads"
710
+ JOB_DIR = DATA_DIR / "jobs"
711
+ MATERIAL_DIR = DATA_DIR / "materials"
712
+ QA_RUN_DIR = DATA_DIR / "qa-runs"
713
+ UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
714
+ JOB_DIR.mkdir(parents=True, exist_ok=True)
715
+ MATERIAL_DIR.mkdir(parents=True, exist_ok=True)
716
+ QA_RUN_DIR.mkdir(parents=True, exist_ok=True)
717
+ app.mount("/uploads", StaticFiles(directory=UPLOAD_DIR), name="uploads")
718
 
719
 
720
  def _debug_resize_rgb(image_rgb: np.ndarray) -> np.ndarray:
 
4029
  return "/".join(part for part in [SPACES_UPLOAD_PREFIX, date_prefix, filename] if part)
4030
 
4031
 
4032
+ def upload_input_image_to_spaces(
4033
+ job_id: str,
4034
+ upload_path: Path,
4035
+ original_filename: str | None,
4036
+ content_type: str | None,
4037
  ):
4038
  if not spaces_upload_enabled():
4039
  return
 
4078
  }
4079
  write_job(job)
4080
  print(f"Uploaded input image for job {job_id} to DigitalOcean Spaces: {SPACES_BUCKET}/{key}", flush=True)
4081
+ except Exception as exc:
4082
+ print(f"DigitalOcean Spaces upload failed for job {job_id}: {exc}", flush=True)
4083
+
4084
+
4085
+ QA_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"}
4086
+ QA_TILE_DESCRIPTIONS = {
4087
+ "White Wood Flooring": "light plank flooring",
4088
+ "Black White Marble Checkered": "black and white marble checkerboard tile",
4089
+ "Grey Checkerboard": "grey checkerboard floor tile",
4090
+ "Lilac 20x20 Ceramic": "lilac 20x20 ceramic tile",
4091
+ }
4092
+ QA_TILE_ALIASES = {
4093
+ "Black White Marble Checker": "Black White Marble Checkered",
4094
+ }
4095
+
4096
+
4097
+ def qa_utc_now() -> datetime:
4098
+ return datetime.now(timezone.utc)
4099
+
4100
+
4101
+ def qa_iso_now() -> str:
4102
+ return qa_utc_now().isoformat().replace("+00:00", "Z")
4103
+
4104
+
4105
+ def qa_run_root(run_id: str) -> Path:
4106
+ if Path(run_id).name != run_id or not run_id:
4107
+ raise HTTPException(status_code=400, detail="Invalid QA run id.")
4108
+ return QA_RUN_DIR / run_id
4109
+
4110
+
4111
+ def qa_run_file(run_id: str) -> Path:
4112
+ return qa_run_root(run_id) / "run.json"
4113
+
4114
+
4115
+ def read_qa_run(run_id: str) -> dict:
4116
+ path = qa_run_file(run_id)
4117
+ if not path.exists():
4118
+ raise HTTPException(status_code=404, detail="QA run not found.")
4119
+ return json.loads(path.read_text())
4120
+
4121
+
4122
+ def write_qa_run(run: dict):
4123
+ run["updatedAt"] = qa_iso_now()
4124
+ root = qa_run_root(run["id"])
4125
+ root.mkdir(parents=True, exist_ok=True)
4126
+ qa_run_file(run["id"]).write_text(json.dumps(run, indent=2))
4127
+
4128
+
4129
+ def qa_sse_event(event_name: str, payload: dict) -> str:
4130
+ data = json.dumps(payload, separators=(",", ":"))
4131
+ return f"event: {event_name}\ndata: {data}\n\n"
4132
+
4133
+
4134
+ def spaces_client():
4135
+ if not spaces_upload_enabled():
4136
+ raise HTTPException(status_code=503, detail="DigitalOcean Spaces is not configured.")
4137
+
4138
+ try:
4139
+ import boto3
4140
+ from botocore.config import Config
4141
+ except ImportError as exc:
4142
+ raise HTTPException(status_code=503, detail="Install boto3 to use DigitalOcean Spaces QA images.") from exc
4143
+
4144
+ return boto3.client(
4145
+ "s3",
4146
+ region_name=SPACES_REGION,
4147
+ endpoint_url=spaces_endpoint_url(),
4148
+ aws_access_key_id=SPACES_ACCESS_KEY_ID,
4149
+ aws_secret_access_key=SPACES_SECRET_ACCESS_KEY,
4150
+ config=Config(signature_version="s3v4"),
4151
+ )
4152
+
4153
+
4154
+ def qa_parse_date(value: str | None, name: str):
4155
+ if not value:
4156
+ return None
4157
+ try:
4158
+ return datetime.strptime(value, "%Y-%m-%d").date()
4159
+ except ValueError as exc:
4160
+ raise HTTPException(status_code=400, detail=f"{name} must use YYYY-MM-DD.") from exc
4161
+
4162
+
4163
+ def qa_date_prefixes(range_name: str, from_value: str | None, to_value: str | None):
4164
+ today = qa_utc_now().date()
4165
+ range_key = (range_name or "week").lower()
4166
+
4167
+ if range_key == "all":
4168
+ return [SPACES_UPLOAD_PREFIX] if SPACES_UPLOAD_PREFIX else [""]
4169
+ if range_key == "today":
4170
+ start = today
4171
+ end = today
4172
+ elif range_key == "week":
4173
+ start = today - timedelta(days=6)
4174
+ end = today
4175
+ elif range_key == "month":
4176
+ start = today.replace(day=1)
4177
+ end = today
4178
+ elif range_key == "custom":
4179
+ start = qa_parse_date(from_value, "from") or today
4180
+ end = qa_parse_date(to_value, "to") or start
4181
+ else:
4182
+ raise HTTPException(status_code=400, detail="range must be today, week, month, all, or custom.")
4183
+
4184
+ if start > end:
4185
+ raise HTTPException(status_code=400, detail="from must be before or equal to to.")
4186
+ if (end - start).days > 370:
4187
+ raise HTTPException(status_code=400, detail="Date range is too large.")
4188
+
4189
+ prefixes = []
4190
+ cursor = start
4191
+ while cursor <= end:
4192
+ prefixes.append("/".join(part for part in [SPACES_UPLOAD_PREFIX, cursor.strftime("%Y/%m/%d")] if part))
4193
+ cursor += timedelta(days=1)
4194
+ return prefixes
4195
+
4196
+
4197
+ def qa_clean_etag(value) -> str:
4198
+ return str(value or "").strip().strip('"')
4199
+
4200
+
4201
+ def qa_object_fingerprint(etag, size) -> str | None:
4202
+ clean_etag = qa_clean_etag(etag)
4203
+ if not clean_etag:
4204
+ return None
4205
+ return f"{clean_etag}:{size or 0}"
4206
+
4207
+
4208
+ def dedupe_qa_image_keys(image_keys: list[str]) -> list[str]:
4209
+ client = spaces_client()
4210
+ unique_keys: list[str] = []
4211
+ seen_keys: set[str] = set()
4212
+ seen_fingerprints: set[str] = set()
4213
+
4214
+ for key in image_keys:
4215
+ if key in seen_keys:
4216
+ continue
4217
+ seen_keys.add(key)
4218
+
4219
+ try:
4220
+ metadata = client.head_object(Bucket=SPACES_BUCKET, Key=key)
4221
+ except Exception as exc:
4222
+ raise HTTPException(status_code=400, detail=f"Could not read DigitalOcean image metadata for {key}.") from exc
4223
+
4224
+ fingerprint = qa_object_fingerprint(metadata.get("ETag"), metadata.get("ContentLength"))
4225
+ if fingerprint and fingerprint in seen_fingerprints:
4226
+ continue
4227
+ if fingerprint:
4228
+ seen_fingerprints.add(fingerprint)
4229
+ unique_keys.append(key)
4230
+
4231
+ return unique_keys
4232
+
4233
+
4234
+ def list_qa_spaces_images(range_name: str, from_value: str | None, to_value: str | None, max_items: int):
4235
+ client = spaces_client()
4236
+ paginator = client.get_paginator("list_objects_v2")
4237
+ images: list[dict] = []
4238
+ seen: set[str] = set()
4239
+ seen_fingerprints: set[str] = set()
4240
+
4241
+ for prefix in qa_date_prefixes(range_name, from_value, to_value):
4242
+ kwargs = {"Bucket": SPACES_BUCKET, "Prefix": prefix}
4243
+ for page in paginator.paginate(**kwargs):
4244
+ for item in page.get("Contents", []):
4245
+ key = item.get("Key", "")
4246
+ if not key or key in seen or Path(key).suffix.lower() not in QA_IMAGE_EXTENSIONS:
4247
+ continue
4248
+ fingerprint = qa_object_fingerprint(item.get("ETag"), item.get("Size"))
4249
+ if fingerprint and fingerprint in seen_fingerprints:
4250
+ continue
4251
+ seen.add(key)
4252
+ if fingerprint:
4253
+ seen_fingerprints.add(fingerprint)
4254
+ url = client.generate_presigned_url(
4255
+ "get_object",
4256
+ Params={"Bucket": SPACES_BUCKET, "Key": key},
4257
+ ExpiresIn=QA_PRESIGNED_URL_EXPIRES_SECONDS,
4258
+ )
4259
+ last_modified = item.get("LastModified")
4260
+ images.append({
4261
+ "key": key,
4262
+ "fileName": urllib.parse.unquote(Path(key).name),
4263
+ "url": url,
4264
+ "thumbnailUrl": url,
4265
+ "uploadedAt": last_modified.isoformat().replace("+00:00", "Z") if last_modified else None,
4266
+ "sizeBytes": item.get("Size"),
4267
+ "contentType": mimetypes.guess_type(key)[0] or "application/octet-stream",
4268
+ "etag": qa_clean_etag(item.get("ETag")),
4269
+ })
4270
+ if len(images) >= max_items:
4271
+ return sorted(images, key=lambda image: image.get("uploadedAt") or "", reverse=True)
4272
+
4273
+ return sorted(images, key=lambda image: image.get("uploadedAt") or "", reverse=True)
4274
+
4275
+
4276
+ def qa_safe_filename(value: str, fallback: str = "image") -> str:
4277
+ stem = "".join(char.lower() if char.isalnum() else "-" for char in value).strip("-")
4278
+ while "--" in stem:
4279
+ stem = stem.replace("--", "-")
4280
+ return (stem or fallback)[:90]
4281
+
4282
+
4283
+ def normalize_qa_tile(tile_name: str) -> str:
4284
+ name = str(tile_name).strip()
4285
+ return QA_TILE_ALIASES.get(name, name)
4286
+
4287
+
4288
+ def qa_tile_description(tile_name: str, supplied_descriptions: dict[str, str]) -> str:
4289
+ return supplied_descriptions.get(tile_name) or QA_TILE_DESCRIPTIONS.get(tile_name) or f"{tile_name} flooring material"
4290
+
4291
+
4292
+ def parse_tile_descriptions(values) -> dict[str, str]:
4293
+ descriptions: dict[str, str] = {}
4294
+ if not isinstance(values, list):
4295
+ return descriptions
4296
+ for value in values:
4297
+ if not isinstance(value, str) or ":" not in value:
4298
+ continue
4299
+ name, description = value.split(":", 1)
4300
+ normalized = normalize_qa_tile(name)
4301
+ if normalized and description.strip():
4302
+ descriptions[normalized] = description.strip()
4303
+ return descriptions
4304
+
4305
+
4306
+ def qa_status_from_playwright(result_status: str | None, test_status: str | None) -> str:
4307
+ status = result_status or ""
4308
+ if status == "passed":
4309
+ return "passed"
4310
+ if status == "skipped":
4311
+ return "skipped"
4312
+ if status:
4313
+ return "failed"
4314
+ if test_status == "expected":
4315
+ return "passed"
4316
+ if test_status == "skipped":
4317
+ return "skipped"
4318
+ return "failed"
4319
+
4320
+
4321
+ def qa_find_attachment(result: dict, name: str):
4322
+ for attachment in result.get("attachments", []) or []:
4323
+ if attachment.get("name") == name:
4324
+ return attachment
4325
+ return None
4326
+
4327
+
4328
+ def qa_attachment_path(attachment: dict | None, report_path: Path):
4329
+ if not attachment or not attachment.get("path"):
4330
+ return None
4331
+ raw_path = Path(str(attachment["path"]))
4332
+ candidates = [
4333
+ raw_path if raw_path.is_absolute() else (QA_FRONTEND_DIR / raw_path),
4334
+ raw_path if raw_path.is_absolute() else (report_path.parent / raw_path),
4335
+ ]
4336
+ for candidate in candidates:
4337
+ if candidate.exists():
4338
+ return candidate.resolve()
4339
+ return None
4340
+
4341
+
4342
+ def qa_asset_url(run_id: str, source_path: Path | None):
4343
+ if source_path is None:
4344
+ return None
4345
+ root = qa_run_root(run_id).resolve()
4346
+ try:
4347
+ relative = source_path.resolve().relative_to(root)
4348
+ except ValueError:
4349
+ assets_dir = root / "assets"
4350
+ assets_dir.mkdir(parents=True, exist_ok=True)
4351
+ destination = assets_dir / source_path.name
4352
+ if not destination.exists():
4353
+ shutil.copy2(source_path, destination)
4354
+ relative = destination.relative_to(root)
4355
+ return f"/qa/runs/{run_id}/assets/{urllib.parse.quote(relative.as_posix())}"
4356
+
4357
+
4358
+ def qa_read_attachment_text(attachment: dict | None, report_path: Path):
4359
+ if not attachment:
4360
+ return ""
4361
+ source_path = qa_attachment_path(attachment, report_path)
4362
+ if source_path is not None:
4363
+ return source_path.read_text()
4364
+ body = attachment.get("body")
4365
+ if not isinstance(body, str):
4366
+ return ""
4367
+ stripped = body.strip()
4368
+ if stripped.startswith("{") or stripped.startswith("["):
4369
+ return body
4370
+ try:
4371
+ return base64.b64decode(body).decode("utf-8")
4372
+ except Exception:
4373
+ return ""
4374
+
4375
+
4376
+ def qa_parse_json_text(text: str):
4377
+ if not text.strip():
4378
+ return None
4379
+ try:
4380
+ return json.loads(text)
4381
+ except Exception:
4382
+ start = text.find("{")
4383
+ end = text.rfind("}")
4384
+ if start >= 0 and end > start:
4385
+ try:
4386
+ return json.loads(text[start:end + 1])
4387
+ except Exception:
4388
+ return None
4389
+ return None
4390
+
4391
+
4392
+ def qa_title_parts(title: str):
4393
+ if ": apply " not in title:
4394
+ return title, "Unknown tile"
4395
+ image_name, rest = title.split(": apply ", 1)
4396
+ tile_name = rest.rsplit(" to ", 1)[0] if " to " in rest else rest
4397
+ return image_name, tile_name
4398
+
4399
+
4400
+ def collect_playwright_specs(suite: dict, entries: list[tuple[str, dict]]):
4401
+ for spec in suite.get("specs", []) or []:
4402
+ title = spec.get("title") or "Untitled QA case"
4403
+ for test in spec.get("tests", []) or []:
4404
+ entries.append((title, test))
4405
+ for child in suite.get("suites", []) or []:
4406
+ collect_playwright_specs(child, entries)
4407
+
4408
+
4409
+ def parse_qa_results(run_id: str, report_path: Path):
4410
+ if not report_path.exists():
4411
+ return []
4412
+ report = json.loads(report_path.read_text())
4413
+ entries: list[tuple[str, dict]] = []
4414
+ for suite in report.get("suites", []) or []:
4415
+ collect_playwright_specs(suite, entries)
4416
+
4417
+ results = []
4418
+ for index, (title, test) in enumerate(entries):
4419
+ playwright_results = test.get("results", []) or [{}]
4420
+ final_result = playwright_results[-1]
4421
+ image_name, tile_name = qa_title_parts(title)
4422
+ before_attachment = qa_find_attachment(final_result, "before-canvas")
4423
+ after_attachment = qa_find_attachment(final_result, "after-texture-canvas")
4424
+ gemini_attachment = qa_find_attachment(final_result, "gemini-judge")
4425
+ status = qa_status_from_playwright(final_result.get("status"), test.get("status"))
4426
+ error = final_result.get("error", {}).get("message") if isinstance(final_result.get("error"), dict) else None
4427
+
4428
+ results.append({
4429
+ "id": f"{run_id}-{index + 1}",
4430
+ "imageKey": image_name,
4431
+ "imageName": image_name,
4432
+ "tileName": tile_name,
4433
+ "status": status,
4434
+ "beforeImageUrl": qa_asset_url(run_id, qa_attachment_path(before_attachment, report_path)),
4435
+ "afterImageUrl": qa_asset_url(run_id, qa_attachment_path(after_attachment, report_path)),
4436
+ "gemini": qa_parse_json_text(qa_read_attachment_text(gemini_attachment, report_path)),
4437
+ "error": error,
4438
+ })
4439
+ return results
4440
+
4441
+
4442
+ def build_qa_scenarios(downloaded_images: list[dict], tiles: list[str], descriptions: dict[str, str]):
4443
+ scenarios = []
4444
+ for image in downloaded_images:
4445
+ image_name = Path(image["key"]).stem
4446
+ for tile in tiles:
4447
+ scenarios.append({
4448
+ "imagePath": str(image["path"]),
4449
+ "keyword": "floor",
4450
+ "roomName": f"{image_name}",
4451
+ "surfaceClass": "floor",
4452
+ "textureName": tile,
4453
+ "textureDescription": qa_tile_description(tile, descriptions),
4454
+ "expectedDirectionDescription": (
4455
+ "The applied material direction should follow the floor perspective and should not look arbitrarily rotated."
4456
+ ),
4457
+ })
4458
+ return scenarios
4459
+
4460
+
4461
+ def download_qa_images(run_id: str, image_keys: list[str]):
4462
+ client = spaces_client()
4463
+ images_dir = qa_run_root(run_id) / "images"
4464
+ images_dir.mkdir(parents=True, exist_ok=True)
4465
+ downloaded = []
4466
+ for index, key in enumerate(image_keys, start=1):
4467
+ extension = Path(key).suffix.lower()
4468
+ if extension not in QA_IMAGE_EXTENSIONS:
4469
+ extension = ".jpg"
4470
+ destination = images_dir / f"{index:03d}-{qa_safe_filename(Path(key).stem)}{extension}"
4471
+ client.download_file(SPACES_BUCKET, key, str(destination))
4472
+ downloaded.append({"key": key, "path": destination})
4473
+ return downloaded
4474
+
4475
+
4476
+ def qa_runner_env(run_root: Path, scenarios: list[dict], use_gemini: bool, backend_url: str):
4477
+ env = os.environ.copy()
4478
+ env.update({
4479
+ "API_URL": backend_url,
4480
+ "PLAYWRIGHT_BASE_URL": QA_FRONTEND_URL,
4481
+ "QA_HTML_REPORT_DIR": str(run_root / "html-report"),
4482
+ "QA_PLAYWRIGHT_OUTPUT_DIR": str(run_root / "artifacts"),
4483
+ "QA_PROGRESS_FILE": str(run_root / "progress.json"),
4484
+ "QA_RESULTS_DIR": str(run_root / "results"),
4485
+ "QA_SCENARIOS": json.dumps(scenarios),
4486
+ "QA_SKIP_GEMINI": "0" if use_gemini else "1",
4487
+ "QA_TEST_IMAGES_DIR": str(run_root / "images"),
4488
+ "QA_WORKERS": "1",
4489
+ "VITE_API_URL": backend_url,
4490
+ })
4491
+ if use_gemini:
4492
+ if not GEMINI_API_KEY:
4493
+ raise RuntimeError("Gemini is enabled for this QA run, but GEMINI_API_KEY is not configured.")
4494
+ env["GEMINI_API_KEY"] = GEMINI_API_KEY
4495
+ env.setdefault("GEMINI_MODEL", "gemini-3.1-flash-lite")
4496
+ return env
4497
+
4498
+
4499
+ def finalize_qa_run_from_report(run: dict, report_path: Path):
4500
+ results = parse_qa_results(run["id"], report_path)
4501
+ passed = sum(1 for result in results if result["status"] == "passed")
4502
+ failed = sum(1 for result in results if result["status"] == "failed")
4503
+ completed = sum(1 for result in results if result["status"] in {"passed", "failed", "skipped"})
4504
+ run.update({
4505
+ "completed": completed,
4506
+ "failed": failed,
4507
+ "passed": passed,
4508
+ "results": results,
4509
+ "status": "completed" if report_path.exists() else "failed",
4510
+ })
4511
+ if failed:
4512
+ run["status"] = "failed"
4513
+
4514
+
4515
+ def qa_int(value, default: int = 0) -> int:
4516
+ try:
4517
+ return int(value)
4518
+ except (TypeError, ValueError):
4519
+ return default
4520
+
4521
+
4522
+ def sync_qa_run_progress(run_id: str, progress_path: Path):
4523
+ if not progress_path.exists():
4524
+ return
4525
+
4526
+ try:
4527
+ progress = json.loads(progress_path.read_text())
4528
+ except Exception:
4529
+ return
4530
+
4531
+ run = read_qa_run(run_id)
4532
+ updates = {
4533
+ "completed": qa_int(progress.get("completed"), qa_int(run.get("completed"))),
4534
+ "failed": qa_int(progress.get("failed"), qa_int(run.get("failed"))),
4535
+ "passed": qa_int(progress.get("passed"), qa_int(run.get("passed"))),
4536
+ "progressUpdatedAt": progress.get("updatedAt"),
4537
+ "skipped": qa_int(progress.get("skipped"), qa_int(run.get("skipped"))),
4538
+ "total": qa_int(progress.get("total"), qa_int(run.get("total"))),
4539
+ }
4540
+ if run.get("status") == "queued":
4541
+ updates["status"] = "running"
4542
+ if all(run.get(key) == value for key, value in updates.items()):
4543
+ return
4544
+
4545
+ run.update(updates)
4546
+ write_qa_run(run)
4547
+
4548
+
4549
+ def run_playwright_qa(run_id: str, run_root: Path, env: dict, log_file):
4550
+ command = ["npm", "run", "qa:e2e"]
4551
+ progress_path = run_root / "progress.json"
4552
+ process = subprocess.Popen(
4553
+ command,
4554
+ cwd=QA_FRONTEND_DIR,
4555
+ env=env,
4556
+ stderr=subprocess.STDOUT,
4557
+ stdout=log_file,
4558
+ )
4559
+ deadline = time.monotonic() + QA_RUN_TIMEOUT_SECONDS
4560
+
4561
+ while True:
4562
+ return_code = process.poll()
4563
+ sync_qa_run_progress(run_id, progress_path)
4564
+ if return_code is not None:
4565
+ return return_code
4566
+
4567
+ if time.monotonic() >= deadline:
4568
+ process.terminate()
4569
+ try:
4570
+ process.wait(timeout=10)
4571
+ except subprocess.TimeoutExpired:
4572
+ process.kill()
4573
+ process.wait(timeout=10)
4574
+ sync_qa_run_progress(run_id, progress_path)
4575
+ raise subprocess.TimeoutExpired(command, QA_RUN_TIMEOUT_SECONDS)
4576
+
4577
+ time.sleep(1)
4578
+
4579
+
4580
+ def run_qa_task(run_id: str, image_keys: list[str], tiles: list[str], descriptions: dict[str, str], use_gemini: bool, backend_url: str):
4581
+ run = read_qa_run(run_id)
4582
+ run_root = qa_run_root(run_id)
4583
+ log_path = run_root / "runner.log"
4584
+ report_path = run_root / "results" / "real-qa.json"
4585
+ summary_path = run_root / "qa-summary.md"
4586
+ try:
4587
+ if not QA_FRONTEND_URL:
4588
+ raise RuntimeError("QA_FRONTEND_URL must point to the hosted frontend.")
4589
+ if not QA_FRONTEND_DIR.exists():
4590
+ raise RuntimeError(f"QA_FRONTEND_DIR does not exist: {QA_FRONTEND_DIR}")
4591
+ if not (QA_FRONTEND_DIR / "package.json").exists():
4592
+ raise RuntimeError(f"QA_FRONTEND_DIR must point to frontend/viz2d-demo: {QA_FRONTEND_DIR}")
4593
+
4594
+ run.update({"status": "running", "startedAt": qa_iso_now()})
4595
+ write_qa_run(run)
4596
+
4597
+ downloaded_images = download_qa_images(run_id, image_keys)
4598
+ scenarios = build_qa_scenarios(downloaded_images, tiles, descriptions)
4599
+ (run_root / "scenarios.json").write_text(json.dumps(scenarios, indent=2))
4600
+ env = qa_runner_env(run_root, scenarios, use_gemini, backend_url)
4601
+
4602
+ with log_path.open("w") as log_file:
4603
+ exit_code = run_playwright_qa(run_id, run_root, env, log_file)
4604
+ log_file.write(f"\nqa:e2e exit code: {exit_code}\n")
4605
+
4606
+ subprocess.run(
4607
+ ["npm", "run", "qa:report", "--", str(report_path), str(summary_path)],
4608
+ cwd=QA_FRONTEND_DIR,
4609
+ env=env,
4610
+ stderr=subprocess.STDOUT,
4611
+ stdout=log_file,
4612
+ timeout=300,
4613
+ )
4614
+
4615
+ run = read_qa_run(run_id)
4616
+ finalize_qa_run_from_report(run, report_path)
4617
+ if not report_path.exists():
4618
+ run["error"] = "Playwright did not create a JSON report. Check runner.log."
4619
+ run["reportUrl"] = f"/qa/runs/{run_id}/report"
4620
+ write_qa_run(run)
4621
+ except subprocess.TimeoutExpired:
4622
+ run = read_qa_run(run_id)
4623
+ run.update({"status": "failed", "error": "QA run timed out.", "reportUrl": f"/qa/runs/{run_id}/report"})
4624
+ write_qa_run(run)
4625
+ except Exception as exc:
4626
+ run = read_qa_run(run_id)
4627
+ run.update({"status": "failed", "error": str(exc), "reportUrl": f"/qa/runs/{run_id}/report"})
4628
+ write_qa_run(run)
4629
+
4630
+
4631
+ def run_conversion_task(job_id: str, upload_path: Path):
4632
  debug = PipelineDebugCapture(job_id) if DEBUG_ARTIFACTS_ENABLED else None
4633
  try:
4634
  t_start = time.perf_counter()
 
4808
 
4809
 
4810
  @app.post("/materials/prepare")
4811
+ async def prepare_material_maps(
4812
+ file: UploadFile = File(...),
4813
+ base_roughness: float = Form(0.42),
4814
+ ):
4815
  if file.content_type and not file.content_type.startswith("image/"):
4816
  raise HTTPException(status_code=400, detail="Upload must be a tile image.")
4817
  contents = await file.read()
4818
  if not contents:
4819
+ raise HTTPException(status_code=400, detail="Upload must not be empty.")
4820
+ return build_tile_material_package(contents, base_roughness)
4821
+
4822
+
4823
+ @app.get("/qa/images")
4824
+ async def qa_images(
4825
+ range: str = Query("week"),
4826
+ from_value: str | None = Query(None, alias="from"),
4827
+ to: str | None = Query(None),
4828
+ max_items: int = Query(100, ge=1, le=500),
4829
+ ):
4830
+ return {"images": list_qa_spaces_images(range, from_value, to, min(max_items, QA_MAX_IMAGES))}
4831
+
4832
+
4833
+ @app.post("/qa/runs")
4834
+ async def create_qa_run(
4835
+ request: Request,
4836
+ background_tasks: BackgroundTasks,
4837
+ payload: dict = Body(...),
4838
+ ):
4839
+ raw_image_keys = payload.get("imageKeys")
4840
+ if not isinstance(raw_image_keys, list):
4841
+ raise HTTPException(status_code=400, detail="imageKeys must be a non-empty array.")
4842
+ image_keys = [str(key).strip() for key in raw_image_keys if isinstance(key, str) and str(key).strip()]
4843
+ if not image_keys:
4844
+ raise HTTPException(status_code=400, detail="Select at least one image.")
4845
+ image_keys = dedupe_qa_image_keys(image_keys)
4846
+ if not image_keys:
4847
+ raise HTTPException(status_code=400, detail="All selected images were duplicates.")
4848
+ if len(image_keys) > QA_MAX_IMAGES:
4849
+ raise HTTPException(status_code=400, detail=f"Select at most {QA_MAX_IMAGES} images.")
4850
+
4851
+ raw_tiles = payload.get("tiles")
4852
+ if raw_tiles is None:
4853
+ raw_tiles = list(QA_TILE_DESCRIPTIONS)
4854
+ if not isinstance(raw_tiles, list):
4855
+ raise HTTPException(status_code=400, detail="tiles must be an array.")
4856
+ tiles = []
4857
+ for tile in raw_tiles:
4858
+ if not isinstance(tile, str) or not tile.strip():
4859
+ continue
4860
+ normalized = normalize_qa_tile(tile)
4861
+ if normalized not in tiles:
4862
+ tiles.append(normalized)
4863
+ if not tiles:
4864
+ raise HTTPException(status_code=400, detail="Select at least one tile.")
4865
+
4866
+ total = len(image_keys) * len(tiles)
4867
+ if total > QA_MAX_TESTS:
4868
+ raise HTTPException(status_code=400, detail=f"QA matrix is too large. Max tests: {QA_MAX_TESTS}.")
4869
+
4870
+ run_id = f"qa_{uuid.uuid4().hex}"
4871
+ use_gemini = bool(payload.get("useGemini", True))
4872
+ descriptions = parse_tile_descriptions(payload.get("tileDescriptions"))
4873
+ backend_url = QA_BACKEND_URL or str(request.base_url).rstrip("/")
4874
+ run = {
4875
+ "id": run_id,
4876
+ "status": "queued",
4877
+ "createdAt": qa_iso_now(),
4878
+ "updatedAt": qa_iso_now(),
4879
+ "total": total,
4880
+ "completed": 0,
4881
+ "passed": 0,
4882
+ "failed": 0,
4883
+ "imageKeys": image_keys,
4884
+ "tiles": tiles,
4885
+ "useGemini": use_gemini,
4886
+ "reportUrl": f"/qa/runs/{run_id}/report",
4887
+ "results": [],
4888
+ }
4889
+ write_qa_run(run)
4890
+ background_tasks.add_task(run_qa_task, run_id, image_keys, tiles, descriptions, use_gemini, backend_url)
4891
+ return run
4892
+
4893
+
4894
+ @app.get("/qa/runs/{run_id}")
4895
+ async def qa_run_status(run_id: str):
4896
+ return read_qa_run(run_id)
4897
+
4898
+
4899
+ @app.get("/qa/runs/{run_id}/events")
4900
+ async def qa_run_events(run_id: str, request: Request):
4901
+ read_qa_run(run_id)
4902
+
4903
+ async def event_stream():
4904
+ last_payload = ""
4905
+ last_keepalive = time.monotonic()
4906
+ while True:
4907
+ if await request.is_disconnected():
4908
+ break
4909
+
4910
+ run = read_qa_run(run_id)
4911
+ payload = json.dumps(run, sort_keys=True)
4912
+ if payload != last_payload:
4913
+ last_payload = payload
4914
+ yield qa_sse_event("run", run)
4915
+ if run.get("status") not in {"queued", "running"}:
4916
+ break
4917
+ elif time.monotonic() - last_keepalive >= 15:
4918
+ last_keepalive = time.monotonic()
4919
+ yield ": keepalive\n\n"
4920
+
4921
+ await asyncio.sleep(1)
4922
+
4923
+ return StreamingResponse(
4924
+ event_stream(),
4925
+ media_type="text/event-stream",
4926
+ headers={
4927
+ "Cache-Control": "no-cache, no-transform",
4928
+ "Connection": "keep-alive",
4929
+ "X-Accel-Buffering": "no",
4930
+ },
4931
+ )
4932
+
4933
+
4934
+ @app.get("/qa/runs/{run_id}/report")
4935
+ async def qa_run_report(run_id: str):
4936
+ root = qa_run_root(run_id)
4937
+ report_path = root / "qa-summary.md"
4938
+ if not report_path.exists():
4939
+ run = read_qa_run(run_id)
4940
+ content = "\n".join([
4941
+ "# Real Browser QA Summary",
4942
+ "",
4943
+ f"Status: {run.get('status', 'unknown')}",
4944
+ "",
4945
+ run.get("error") or "The QA summary has not been generated yet.",
4946
+ "",
4947
+ ])
4948
+ return Response(content=content, media_type="text/markdown", headers={"Cache-Control": "no-store"})
4949
+ return Response(content=report_path.read_text(), media_type="text/markdown", headers={"Cache-Control": "no-store"})
4950
+
4951
+
4952
+ @app.get("/qa/runs/{run_id}/assets/{asset_path:path}")
4953
+ async def qa_run_asset(run_id: str, asset_path: str):
4954
+ root = qa_run_root(run_id).resolve()
4955
+ target = (root / asset_path).resolve()
4956
+ if root != target and root not in target.parents:
4957
+ raise HTTPException(status_code=400, detail="Invalid QA asset path.")
4958
+ if not target.exists() or not target.is_file():
4959
+ raise HTTPException(status_code=404, detail="QA asset not found.")
4960
+ media_type = mimetypes.guess_type(target.name)[0] or "application/octet-stream"
4961
+ return Response(content=target.read_bytes(), media_type=media_type, headers={"Cache-Control": "private, max-age=3600"})
4962
+
4963
+
4964
+ @app.post("/viz2d/convert")
4965
  async def convert_to_viz2d(background_tasks: BackgroundTasks, file: UploadFile = File(...)):
4966
  if file.content_type and not file.content_type.startswith("image/"):
4967
  raise HTTPException(status_code=400, detail="Upload must be a JPG or PNG image.")
frontend/viz2d-demo/e2e/README.md ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, applies a selected tile, and judges that immediate result. It does not
7
+ touch the user-only tile size or rotation sliders.
8
+
9
+ Required CI secrets:
10
+
11
+ - `QA_BACKEND_URL` or `API_URL`: hosted FastAPI backend URL.
12
+ - `GEMINI_API_KEY`: Gemini API key for visual result judging.
13
+
14
+ Optional variables:
15
+
16
+ - `GEMINI_MODEL`: defaults to `gemini-3.1-flash-lite`.
17
+ - `QA_SKIP_GEMINI=1`: run browser and canvas checks without the Gemini judge.
18
+ - `QA_TEST_IMAGES_DIR`: image folder, defaults to `test-images`.
19
+ - `QA_SCENARIOS`: optional JSON array of per-image overrides by sorted image order.
20
+
21
+ Gemini explicitly checks for missed target-surface coverage, including thin untiled floor slivers around sofas,
22
+ tables, table legs, cabinets, plants, wall bases, and room edges. It also checks whether the applied tile direction
23
+ matches the floor perspective instead of looking rotated or misaligned. Coverage gaps and direction mismatches are
24
+ treated as QA failures. Tune strictness per scenario with:
25
+
26
+ - `minEdgeCompleteness`: defaults to `0.82`.
27
+ - `minOcclusionBoundaryQuality`: defaults to `0.78`.
28
+ - `minDirectionQuality`: defaults to `0.75`.
29
+ - `expectedDirectionDescription`: describes the expected direction/orientation for that image and texture.
30
+
31
+ Example `QA_SCENARIOS` for the first two sorted files in `test-images/`:
32
+
33
+ ```json
34
+ [
35
+ {
36
+ "roomName": "Living Room 1",
37
+ "surfaceClass": "floor",
38
+ "textureName": "Black White Marble Checkered",
39
+ "keyword": "floor",
40
+ "textureDescription": "black and white marble checkerboard tile",
41
+ "expectedDirectionDescription": "checkerboard rows and columns follow the floor perspective toward the room vanishing direction",
42
+ "minEdgeCompleteness": 0.82,
43
+ "minOcclusionBoundaryQuality": 0.78,
44
+ "minDirectionQuality": 0.75
45
+ },
46
+ {
47
+ "roomName": "Kitchen 1",
48
+ "surfaceClass": "floor",
49
+ "textureName": "Natural Stone",
50
+ "keyword": "floor"
51
+ }
52
+ ]
53
+ ```
54
+
55
+ Local command:
56
+
57
+ ```bash
58
+ API_URL=https://your-backend.example GEMINI_API_KEY=... npm run qa:real
59
+ ```
60
+
61
+ Create the compact Markdown summary after a run:
62
+
63
+ ```bash
64
+ npm run qa:report
65
+ ```
66
+
67
+ The GitHub artifact includes only `test-results/qa-summary.md`. The summary embeds each image's before/after
68
+ screenshots and Gemini judgment directly in the Markdown, so you do not need to dig through traces and videos for
69
+ the normal review.
frontend/viz2d-demo/e2e/real-room-qa.spec.ts ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { existsSync, readdirSync } 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
+ const IMAGE_EXTENSIONS = new Set([".jpg", ".jpeg", ".png", ".webp"]);
35
+ const TEST_IMAGES_DIR = path.resolve(process.env.QA_TEST_IMAGES_DIR ?? "test-images");
36
+ const DEFAULT_SCENARIO_OPTIONS = {
37
+ detectionTimeoutMs: 420_000,
38
+ expectedDirectionDescription:
39
+ "The checkerboard tile rows and columns should follow the floor perspective/direction and should not look arbitrarily rotated.",
40
+ keyword: "floor",
41
+ minAverageDelta: 2,
42
+ minChangedRatio: 0.02,
43
+ minDirectionQuality: 0.75,
44
+ minEdgeCompleteness: 0.82,
45
+ minLightingPreserved: 0.55,
46
+ minOcclusionBoundaryQuality: 0.78,
47
+ minPerspectiveQuality: 0.65,
48
+ minRealism: 0.6,
49
+ minSurfaceCorrectness: 0.7,
50
+ surfaceClass: "floor",
51
+ textureDescription: "black and white marble checkerboard tile",
52
+ textureName: "Black White Marble Checkered",
53
+ };
54
+
55
+ test.describe("real backend room visualizer QA", () => {
56
+ for (const scenario of loadScenarios()) {
57
+ test(`${scenario.roomName}: apply ${scenario.textureName} to ${scenario.surfaceClass}`, async ({ page }, testInfo) => {
58
+ requireBackendUrl();
59
+ const diagnostics = collectDiagnostics(page);
60
+
61
+ await page.goto("/");
62
+ await expect(page.getByText("Upload a Room Photo")).toBeVisible();
63
+
64
+ await page.getByTestId("room-file-input").setInputFiles(scenario.imagePath);
65
+ await expect(page.getByTestId("visualizer-editor")).toBeVisible({ timeout: 30_000 });
66
+ await waitForSurfaceCards(page, scenario.detectionTimeoutMs);
67
+
68
+ const canvas = page.getByTestId("visualizer-canvas");
69
+ const beforeSignature = await waitForUsableCanvas(page, canvas);
70
+ const beforePath = testInfo.outputPath(`${slug(scenario.roomName)}-before.png`);
71
+ await canvas.screenshot({ path: beforePath });
72
+ await testInfo.attach("before-canvas", { contentType: "image/png", path: beforePath });
73
+
74
+ await selectSurface(page, scenario.surfaceClass);
75
+ await selectTexture(page, scenario);
76
+ await waitForTextureToSettle(page, scenario.textureName);
77
+ await page.mouse.move(8, 8);
78
+
79
+ const afterTextureSignature = await waitForChangedCanvas(page, canvas, beforeSignature, scenario);
80
+ expectUsableCanvas(afterTextureSignature);
81
+ const afterTexturePath = testInfo.outputPath(`${slug(scenario.roomName)}-after-texture.png`);
82
+ await canvas.screenshot({ path: afterTexturePath });
83
+ await testInfo.attach("after-texture-canvas", { contentType: "image/png", path: afterTexturePath });
84
+
85
+ await verifyDownload(page, testInfo);
86
+ await runGeminiJudgeIfEnabled(scenario, beforePath, afterTexturePath, testInfo);
87
+ await attachDiagnostics(testInfo, diagnostics);
88
+
89
+ expect(diagnostics.pageErrors, "browser page errors").toEqual([]);
90
+ });
91
+ }
92
+ });
93
+
94
+ async function waitForSurfaceCards(page: Page, timeoutMs: number) {
95
+ const deadline = Date.now() + timeoutMs;
96
+ while (Date.now() < deadline) {
97
+ const failed = page.getByText("Detection failed");
98
+ if (await failed.isVisible().catch(() => false)) {
99
+ const status = await page.getByTestId("detection-status").innerText().catch(() => "Detection failed.");
100
+ throw new Error(status);
101
+ }
102
+
103
+ if (await page.getByTestId("surface-card").first().isVisible().catch(() => false)) {
104
+ return;
105
+ }
106
+
107
+ await page.waitForTimeout(1_000);
108
+ }
109
+
110
+ throw new Error(`No detected surfaces appeared within ${Math.round(timeoutMs / 1000)} seconds.`);
111
+ }
112
+
113
+ async function waitForUsableCanvas(page: Page, canvas: Locator) {
114
+ let signature = await readCanvasSignature(canvas);
115
+ const deadline = Date.now() + 60_000;
116
+ while (Date.now() < deadline) {
117
+ try {
118
+ expectUsableCanvas(signature);
119
+ return signature;
120
+ } catch {
121
+ await page.waitForTimeout(500);
122
+ signature = await readCanvasSignature(canvas);
123
+ }
124
+ }
125
+
126
+ expectUsableCanvas(signature);
127
+ return signature;
128
+ }
129
+
130
+ async function selectSurface(page: Page, surfaceClass: string) {
131
+ const exactSurface = page.locator(`[data-testid="surface-card"][data-surface-class="${surfaceClass}"]`).first();
132
+ const fallbackSurface = page.getByTestId("surface-card").first();
133
+ const target = await exactSurface.isVisible().catch(() => false) ? exactSurface : fallbackSurface;
134
+
135
+ await expect(target).toBeVisible();
136
+ await target.click();
137
+ await expect(page.getByTestId("texture-selector")).toBeVisible();
138
+ }
139
+
140
+ async function selectTexture(page: Page, scenario: QaScenario) {
141
+ if (scenario.keyword) {
142
+ const keywordButton = page.getByTestId("texture-keyword").filter({ hasText: scenario.keyword }).first();
143
+ if (await keywordButton.isVisible().catch(() => false)) {
144
+ await keywordButton.click();
145
+ }
146
+ }
147
+
148
+ const texture = page.getByTestId("texture-card").filter({ hasText: scenario.textureName }).first();
149
+ await expect(texture).toBeVisible();
150
+ await texture.scrollIntoViewIfNeeded();
151
+ await texture.click();
152
+ }
153
+
154
+ async function waitForTextureToSettle(page: Page, textureName: string) {
155
+ await expect(page.getByTestId("texture-selector")).toBeHidden({ timeout: 30_000 });
156
+ await page.getByTestId("blocking-overlay").waitFor({ state: "hidden", timeout: 180_000 }).catch(() => undefined);
157
+ await expect(page.getByTestId("surface-card").filter({ hasText: textureName }).first()).toBeVisible({
158
+ timeout: 120_000,
159
+ });
160
+ }
161
+
162
+ async function waitForChangedCanvas(page: Page, canvas: Locator, previous: CanvasSignature, scenario: QaScenario) {
163
+ const deadline = Date.now() + 60_000;
164
+ let latest = await readCanvasSignature(canvas);
165
+ let latestDiff = diffCanvasSignatures(previous, latest);
166
+
167
+ while (Date.now() < deadline) {
168
+ expectUsableCanvas(latest);
169
+ if (latestDiff.changedRatio >= scenario.minChangedRatio && latestDiff.averageDelta >= scenario.minAverageDelta) {
170
+ return latest;
171
+ }
172
+
173
+ await page.waitForTimeout(750);
174
+ latest = await readCanvasSignature(canvas);
175
+ latestDiff = diffCanvasSignatures(previous, latest);
176
+ }
177
+
178
+ expect(latestDiff.changedRatio, "canvas changed-pixel ratio after applying texture").toBeGreaterThanOrEqual(
179
+ scenario.minChangedRatio,
180
+ );
181
+ expect(latestDiff.averageDelta, "average canvas color delta after applying texture").toBeGreaterThanOrEqual(
182
+ scenario.minAverageDelta,
183
+ );
184
+ return latest;
185
+ }
186
+
187
+ async function verifyDownload(page: Page, testInfo: TestInfo) {
188
+ const downloadPromise = page.waitForEvent("download", { timeout: 30_000 });
189
+ await page.getByLabel("Download image").click();
190
+ const download = await downloadPromise;
191
+ expect(download.suggestedFilename()).toBe("download.png");
192
+
193
+ const downloadPath = await download.path();
194
+ if (downloadPath) {
195
+ await testInfo.attach("downloaded-render", { contentType: "image/png", path: downloadPath });
196
+ }
197
+ }
198
+
199
+ async function runGeminiJudgeIfEnabled(
200
+ scenario: QaScenario,
201
+ beforeImagePath: string,
202
+ afterImagePath: string,
203
+ testInfo: TestInfo,
204
+ ) {
205
+ if (flagEnabled("QA_SKIP_GEMINI")) {
206
+ testInfo.annotations.push({ description: "QA_SKIP_GEMINI is enabled.", type: "gemini-skipped" });
207
+ return;
208
+ }
209
+
210
+ const apiKey = process.env.GEMINI_API_KEY;
211
+ if (!apiKey) {
212
+ throw new Error("GEMINI_API_KEY is required for visual judging. Set QA_SKIP_GEMINI=1 for browser-only runs.");
213
+ }
214
+
215
+ const result = await judgeTileApplicationWithGemini({
216
+ afterImagePath,
217
+ apiKey,
218
+ beforeImagePath,
219
+ model: process.env.GEMINI_MODEL ?? "gemini-3.1-flash-lite",
220
+ scenario,
221
+ });
222
+
223
+ await testInfo.attach("gemini-judge", {
224
+ body: JSON.stringify(result, null, 2),
225
+ contentType: "application/json",
226
+ });
227
+
228
+ assertGeminiResult(result, scenario);
229
+ }
230
+
231
+ function assertGeminiResult(result: GeminiJudgeResult, scenario: QaScenario) {
232
+ expect(result.tileApplied, `Gemini notes: ${result.notes}`).toBe(true);
233
+ expect(result.bleedDetected, `Gemini notes: ${result.notes}`).toBe(false);
234
+ expect(result.coverageGapDetected, `Gemini missed areas: ${result.missedFloorAreas.join("; ")}`).toBe(false);
235
+ expect(result.directionMismatchDetected, `Gemini direction issues: ${result.directionIssues.join("; ")}`).toBe(false);
236
+ expect(result.surfaceCorrectness, `Gemini notes: ${result.notes}`).toBeGreaterThanOrEqual(
237
+ scenario.minSurfaceCorrectness,
238
+ );
239
+ expect(result.edgeCompleteness, `Gemini missed areas: ${result.missedFloorAreas.join("; ")}`).toBeGreaterThanOrEqual(
240
+ scenario.minEdgeCompleteness,
241
+ );
242
+ expect(
243
+ result.occlusionBoundaryQuality,
244
+ `Gemini missed areas: ${result.missedFloorAreas.join("; ")}`,
245
+ ).toBeGreaterThanOrEqual(
246
+ scenario.minOcclusionBoundaryQuality,
247
+ );
248
+ expect(result.perspectiveQuality, `Gemini notes: ${result.notes}`).toBeGreaterThanOrEqual(
249
+ scenario.minPerspectiveQuality,
250
+ );
251
+ expect(result.directionQuality, `Gemini direction issues: ${result.directionIssues.join("; ")}`).toBeGreaterThanOrEqual(
252
+ scenario.minDirectionQuality,
253
+ );
254
+ expect(result.lightingPreserved, `Gemini notes: ${result.notes}`).toBeGreaterThanOrEqual(
255
+ scenario.minLightingPreserved,
256
+ );
257
+ expect(result.realism, `Gemini notes: ${result.notes}`).toBeGreaterThanOrEqual(scenario.minRealism);
258
+ expect(result.overallPass, `Gemini failure reasons: ${result.failureReasons.join("; ")}`).toBe(true);
259
+ }
260
+
261
+ function loadScenarios() {
262
+ const raw = process.env.QA_SCENARIOS?.trim();
263
+ const overrides = raw ? parseScenarioOverrides(raw) : [];
264
+
265
+ if (overrides.some(hasExplicitImagePath)) {
266
+ return overrides.map((override, index) => {
267
+ if (!hasExplicitImagePath(override)) {
268
+ throw new Error(`QA_SCENARIOS[${index}] must include imagePath when any scenario uses explicit imagePath.`);
269
+ }
270
+
271
+ return normalizeScenario(path.resolve(override.imagePath), override, index);
272
+ });
273
+ }
274
+
275
+ const images = findTestImages(TEST_IMAGES_DIR);
276
+
277
+ return images.map((imagePath, index) => normalizeScenario(imagePath, overrides[index], index));
278
+ }
279
+
280
+ function parseScenarioOverrides(raw: string) {
281
+ const parsed = JSON.parse(raw) as unknown;
282
+ if (!Array.isArray(parsed)) {
283
+ throw new Error("QA_SCENARIOS must be a JSON array.");
284
+ }
285
+
286
+ return parsed;
287
+ }
288
+
289
+ function hasExplicitImagePath(value: unknown): value is Record<string, unknown> & { imagePath: string } {
290
+ return Boolean(
291
+ value &&
292
+ typeof value === "object" &&
293
+ !Array.isArray(value) &&
294
+ typeof (value as Record<string, unknown>).imagePath === "string" &&
295
+ ((value as Record<string, unknown>).imagePath as string).trim(),
296
+ );
297
+ }
298
+
299
+ function findTestImages(directory: string) {
300
+ if (!existsSync(directory)) {
301
+ throw new Error(`Test images directory does not exist: ${directory}`);
302
+ }
303
+
304
+ const images = readdirSync(directory)
305
+ .filter((fileName) => IMAGE_EXTENSIONS.has(path.extname(fileName).toLowerCase()))
306
+ .sort((a, b) => a.localeCompare(b))
307
+ .map((fileName) => path.join(directory, fileName));
308
+
309
+ if (images.length === 0) {
310
+ throw new Error(`No test images found in ${directory}. Add .jpg, .jpeg, .png, or .webp files.`);
311
+ }
312
+
313
+ return images;
314
+ }
315
+
316
+ function normalizeScenario(imagePath: string, item: unknown, index: number): QaScenario {
317
+ if (item != null && (!item || typeof item !== "object" || Array.isArray(item))) {
318
+ throw new Error(`QA_SCENARIOS[${index}] must be an object when provided.`);
319
+ }
320
+
321
+ const value = (item ?? {}) as Record<string, unknown>;
322
+ const roomName = stringValue(value.roomName, readableImageName(imagePath));
323
+
324
+ return {
325
+ detectionTimeoutMs: numberValue(value.detectionTimeoutMs, DEFAULT_SCENARIO_OPTIONS.detectionTimeoutMs),
326
+ expectedDirectionDescription: stringValue(
327
+ value.expectedDirectionDescription,
328
+ DEFAULT_SCENARIO_OPTIONS.expectedDirectionDescription,
329
+ ),
330
+ imagePath,
331
+ keyword: stringValue(value.keyword, DEFAULT_SCENARIO_OPTIONS.keyword),
332
+ minAverageDelta: numberValue(value.minAverageDelta, DEFAULT_SCENARIO_OPTIONS.minAverageDelta),
333
+ minChangedRatio: numberValue(value.minChangedRatio, DEFAULT_SCENARIO_OPTIONS.minChangedRatio),
334
+ minDirectionQuality: numberValue(value.minDirectionQuality, DEFAULT_SCENARIO_OPTIONS.minDirectionQuality),
335
+ minEdgeCompleteness: numberValue(value.minEdgeCompleteness, DEFAULT_SCENARIO_OPTIONS.minEdgeCompleteness),
336
+ minLightingPreserved: numberValue(value.minLightingPreserved, DEFAULT_SCENARIO_OPTIONS.minLightingPreserved),
337
+ minOcclusionBoundaryQuality: numberValue(
338
+ value.minOcclusionBoundaryQuality,
339
+ DEFAULT_SCENARIO_OPTIONS.minOcclusionBoundaryQuality,
340
+ ),
341
+ minPerspectiveQuality: numberValue(value.minPerspectiveQuality, DEFAULT_SCENARIO_OPTIONS.minPerspectiveQuality),
342
+ minRealism: numberValue(value.minRealism, DEFAULT_SCENARIO_OPTIONS.minRealism),
343
+ minSurfaceCorrectness: numberValue(value.minSurfaceCorrectness, DEFAULT_SCENARIO_OPTIONS.minSurfaceCorrectness),
344
+ roomName,
345
+ surfaceClass: stringValue(value.surfaceClass, DEFAULT_SCENARIO_OPTIONS.surfaceClass),
346
+ textureDescription: stringValue(value.textureDescription, DEFAULT_SCENARIO_OPTIONS.textureDescription),
347
+ textureName: stringValue(value.textureName, DEFAULT_SCENARIO_OPTIONS.textureName),
348
+ };
349
+ }
350
+
351
+ function numberValue(value: unknown, fallback: number) {
352
+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;
353
+ }
354
+
355
+ function stringValue(value: unknown, fallback: string) {
356
+ return typeof value === "string" && value.trim() ? value.trim() : fallback;
357
+ }
358
+
359
+ function readableImageName(imagePath: string) {
360
+ return path.basename(imagePath, path.extname(imagePath));
361
+ }
362
+
363
+ function requireBackendUrl() {
364
+ if (!process.env.API_URL && !process.env.VITE_API_URL) {
365
+ throw new Error("API_URL or VITE_API_URL must point to the hosted backend for real-data QA.");
366
+ }
367
+ }
368
+
369
+ function collectDiagnostics(page: Page) {
370
+ const diagnostics = {
371
+ consoleErrors: [] as string[],
372
+ failedRequests: [] as string[],
373
+ pageErrors: [] as string[],
374
+ };
375
+
376
+ page.on("console", (message) => {
377
+ if (message.type() === "error") {
378
+ diagnostics.consoleErrors.push(message.text());
379
+ }
380
+ });
381
+ page.on("pageerror", (error) => {
382
+ diagnostics.pageErrors.push(error.message);
383
+ });
384
+ page.on("requestfailed", (request) => {
385
+ const url = request.url();
386
+ if (!url.startsWith("data:") && !url.startsWith("blob:")) {
387
+ diagnostics.failedRequests.push(`${request.method()} ${url} :: ${request.failure()?.errorText ?? "unknown"}`);
388
+ }
389
+ });
390
+
391
+ return diagnostics;
392
+ }
393
+
394
+ async function attachDiagnostics(
395
+ testInfo: TestInfo,
396
+ diagnostics: { consoleErrors: string[]; failedRequests: string[]; pageErrors: string[] },
397
+ ) {
398
+ await testInfo.attach("browser-diagnostics", {
399
+ body: JSON.stringify(diagnostics, null, 2),
400
+ contentType: "application/json",
401
+ });
402
+ }
403
+
404
+ function flagEnabled(name: string) {
405
+ return ["1", "true", "yes", "on"].includes((process.env[name] ?? "").toLowerCase());
406
+ }
407
+
408
+ function slug(value: string) {
409
+ return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "") || "room";
410
+ }
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,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.progressFile = process.env.QA_PROGRESS_FILE;
12
+ this.resultByTest = new Map();
13
+ this.testOrder = [];
14
+ this.total = 0;
15
+ }
16
+
17
+ onBegin(_config, suite) {
18
+ const tests = suite.allTests();
19
+ this.testOrder = tests.map((test) => this.testKey(test));
20
+ this.total = tests.length;
21
+ this.write("running");
22
+ }
23
+
24
+ onTestEnd(test, result) {
25
+ const key = this.testKey(test);
26
+ if (!this.testOrder.includes(key)) this.testOrder.push(key);
27
+ this.resultByTest.set(key, {
28
+ durationMs: result.duration,
29
+ error: result.error?.message || null,
30
+ status: normalizeStatus(result.status),
31
+ title: test.title,
32
+ });
33
+ this.write("running");
34
+ }
35
+
36
+ onEnd(result) {
37
+ this.write(result.status === "passed" ? "completed" : "failed");
38
+ }
39
+
40
+ write(status) {
41
+ if (!this.progressFile) return;
42
+
43
+ const results = this.testOrder
44
+ .map((key) => this.resultByTest.get(key))
45
+ .filter(Boolean);
46
+ const passed = results.filter((entry) => entry.status === "passed").length;
47
+ const failed = results.filter((entry) => entry.status === "failed").length;
48
+ const skipped = results.filter((entry) => entry.status === "skipped").length;
49
+ const completed = passed + failed + skipped;
50
+ const payload = {
51
+ completed,
52
+ failed,
53
+ passed,
54
+ results,
55
+ skipped,
56
+ status,
57
+ total: this.total,
58
+ updatedAt: new Date().toISOString(),
59
+ };
60
+
61
+ fs.mkdirSync(path.dirname(this.progressFile), { recursive: true });
62
+ const tempFile = `${this.progressFile}.${process.pid}.tmp`;
63
+ fs.writeFileSync(tempFile, JSON.stringify(payload, null, 2));
64
+ fs.renameSync(tempFile, this.progressFile);
65
+ }
66
+
67
+ testKey(test) {
68
+ return test.id || test.titlePath().join(" > ");
69
+ }
70
+ }
71
+
72
+ 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,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 beforeImage = await imageAttachmentDataUri(result, "before-canvas");
45
+ const afterImage = await imageAttachmentDataUri(result, "after-texture-canvas");
46
+ const geminiAttachment = findAttachment(result, "gemini-judge");
47
+ const gemini = geminiAttachment ? parseJsonLoose(await readTextAttachment(geminiAttachment)) : null;
48
+
49
+ hydratedEntries.push({
50
+ ...entry,
51
+ afterImage,
52
+ beforeImage,
53
+ gemini,
54
+ result,
55
+ status: displayStatus(entry.test, result),
56
+ });
57
+ }
58
+
59
+ await writeFile(outputPath, buildMarkdown(hydratedEntries));
60
+ console.log(`QA markdown summary written to ${relativeToCwd(outputPath)}`);
61
+ }
62
+
63
+ function collectEntries(report) {
64
+ const entries = [];
65
+
66
+ for (const suite of asArray(report.suites)) {
67
+ collectSuite(suite, entries);
68
+ }
69
+
70
+ return entries;
71
+ }
72
+
73
+ async function writeFailureSummary(error) {
74
+ await mkdir(outputDir, { recursive: true });
75
+ const message = error instanceof Error ? error.stack ?? error.message : String(error);
76
+
77
+ await writeFile(
78
+ outputPath,
79
+ [
80
+ "# Real Browser QA Summary",
81
+ "",
82
+ "The compact Markdown summary could not be generated.",
83
+ "",
84
+ `Source report: \`${relativeToCwd(reportPath)}\``,
85
+ "",
86
+ "```text",
87
+ message,
88
+ "```",
89
+ "",
90
+ "The full Playwright artifacts are still available in this artifact bundle.",
91
+ "",
92
+ ].join("\n"),
93
+ );
94
+ }
95
+
96
+ function collectSuite(suite, entries) {
97
+ for (const spec of asArray(suite.specs)) {
98
+ const title = typeof spec.title === "string" && spec.title.trim() ? spec.title.trim() : "Untitled QA case";
99
+ for (const test of asArray(spec.tests)) {
100
+ entries.push({ spec, test, title });
101
+ }
102
+ }
103
+
104
+ for (const child of asArray(suite.suites)) {
105
+ collectSuite(child, entries);
106
+ }
107
+ }
108
+
109
+ function finalResult(test) {
110
+ const results = asArray(test.results);
111
+ return results[results.length - 1] ?? {};
112
+ }
113
+
114
+ function displayStatus(test, result) {
115
+ const resultStatus = typeof result.status === "string" ? result.status : "";
116
+ const testStatus = typeof test.status === "string" ? test.status : "";
117
+
118
+ if (resultStatus) return resultStatus;
119
+ if (testStatus === "expected") return "passed";
120
+ if (testStatus === "unexpected") return "failed";
121
+ return testStatus || "unknown";
122
+ }
123
+
124
+ async function imageAttachmentDataUri(result, attachmentName) {
125
+ const attachment = findAttachment(result, attachmentName);
126
+ if (!attachment) return null;
127
+
128
+ const sourcePath = resolveAttachmentPath(attachment.path);
129
+ const contentType = imageContentType(attachment);
130
+
131
+ if (sourcePath) {
132
+ const buffer = await readFile(sourcePath);
133
+ return `data:${contentType};base64,${buffer.toString("base64")}`;
134
+ }
135
+
136
+ if (typeof attachment.body === "string") {
137
+ return `data:${contentType};base64,${attachment.body}`;
138
+ }
139
+
140
+ return null;
141
+ }
142
+
143
+ function findAttachment(result, name) {
144
+ return asArray(result.attachments).find((attachment) => attachment?.name === name) ?? null;
145
+ }
146
+
147
+ async function readTextAttachment(attachment) {
148
+ const sourcePath = resolveAttachmentPath(attachment.path);
149
+ if (sourcePath) return readFile(sourcePath, "utf8");
150
+
151
+ if (typeof attachment.body !== "string") return "";
152
+
153
+ const direct = attachment.body.trim();
154
+ if (direct.startsWith("{") || direct.startsWith("[")) return attachment.body;
155
+
156
+ return Buffer.from(attachment.body, "base64").toString("utf8");
157
+ }
158
+
159
+ function resolveAttachmentPath(value) {
160
+ if (typeof value !== "string" || !value.trim()) return null;
161
+
162
+ const candidates = [
163
+ path.isAbsolute(value) ? value : path.resolve(cwd, value),
164
+ path.resolve(path.dirname(reportPath), value),
165
+ ];
166
+
167
+ return candidates.find((candidate) => existsSync(candidate)) ?? null;
168
+ }
169
+
170
+ function parseJsonLoose(text) {
171
+ if (!text.trim()) return null;
172
+
173
+ try {
174
+ return JSON.parse(text);
175
+ } catch {
176
+ const match = text.match(/\{[\s\S]*\}/);
177
+ if (!match) return null;
178
+ try {
179
+ return JSON.parse(match[0]);
180
+ } catch {
181
+ return null;
182
+ }
183
+ }
184
+ }
185
+
186
+ function buildMarkdown(entries) {
187
+ const passed = entries.filter((entry) => entry.status === "passed").length;
188
+ const skipped = entries.filter((entry) => entry.status === "skipped").length;
189
+ const needsReview = entries.length - passed - skipped;
190
+ const lines = [
191
+ "# Real Browser QA Summary",
192
+ "",
193
+ `Generated from \`${relativeToCwd(reportPath)}\`.`,
194
+ "",
195
+ `Total images: ${entries.length}`,
196
+ `Passed: ${passed}`,
197
+ `Needs review: ${needsReview}`,
198
+ `Skipped: ${skipped}`,
199
+ "",
200
+ ];
201
+
202
+ for (const [index, entry] of entries.entries()) {
203
+ lines.push("", `## ${index + 1}. ${escapeHeading(imageName(entry.title))}`, "");
204
+ lines.push(`Status: **${entry.status}**`, "");
205
+ lines.push("### Before", "");
206
+ lines.push(imageTag(entry.beforeImage), "");
207
+ lines.push("### After Tile Applied", "");
208
+ lines.push(imageTag(entry.afterImage), "");
209
+ lines.push("", "### Gemini Judgment", "");
210
+ lines.push(...geminiSummary(entry.gemini));
211
+ }
212
+
213
+ return `${lines.join("\n")}\n`;
214
+ }
215
+
216
+ function geminiSummary(gemini) {
217
+ if (!gemini) {
218
+ return ["No Gemini judgment attachment was found for this image.", ""];
219
+ }
220
+
221
+ const lines = [
222
+ `- Overall pass: ${yesNo(gemini.overallPass)}`,
223
+ `- Tile applied: ${yesNo(gemini.tileApplied)}`,
224
+ `- Coverage gap detected: ${yesNo(gemini.coverageGapDetected)}`,
225
+ `- Missed floor areas: ${listOrNone(gemini.missedFloorAreas)}`,
226
+ `- Direction mismatch detected: ${yesNo(gemini.directionMismatchDetected)}`,
227
+ `- Direction issues: ${listOrNone(gemini.directionIssues)}`,
228
+ `- Bleed detected: ${yesNo(gemini.bleedDetected)}`,
229
+ `- 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)}`,
230
+ `- Notes: ${gemini.notes ?? "none"}`,
231
+ "",
232
+ ];
233
+
234
+ return lines;
235
+ }
236
+
237
+ function imageTag(relativePath) {
238
+ if (!relativePath) return "Missing screenshot";
239
+ return `<img src="${relativePath}" width="720" />`;
240
+ }
241
+
242
+ function yesNo(value) {
243
+ return typeof value === "boolean" ? (value ? "yes" : "no") : "n/a";
244
+ }
245
+
246
+ function score(value) {
247
+ return typeof value === "number" && Number.isFinite(value) ? value.toFixed(2) : "n/a";
248
+ }
249
+
250
+ function listOrNone(value) {
251
+ return Array.isArray(value) && value.length > 0 ? value.join("; ") : "none";
252
+ }
253
+
254
+ function imageContentType(attachment) {
255
+ if (typeof attachment.contentType === "string" && attachment.contentType.startsWith("image/")) {
256
+ return attachment.contentType;
257
+ }
258
+
259
+ const extension = typeof attachment.path === "string" ? path.extname(attachment.path).toLowerCase() : "";
260
+ if (extension === ".jpg" || extension === ".jpeg") return "image/jpeg";
261
+ if (extension === ".webp") return "image/webp";
262
+ return "image/png";
263
+ }
264
+
265
+ function imageName(title) {
266
+ return title.split(": apply ")[0] || title;
267
+ }
268
+
269
+ function escapeHeading(value) {
270
+ return String(value).replace(/\n/g, " ").trim();
271
+ }
272
+
273
+ function asArray(value) {
274
+ return Array.isArray(value) ? value : [];
275
+ }
276
+
277
+ function relativeToCwd(value) {
278
+ return path.relative(cwd, value).replaceAll(path.sep, "/") || ".";
279
+ }