diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..f2a09172e12f96b951bb7394745f90d7c6c6b964 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +*.jpg filter=lfs diff=lfs merge=lfs -text +*.jpeg filter=lfs diff=lfs merge=lfs -text +*.png filter=lfs diff=lfs merge=lfs -text +*.webp filter=lfs diff=lfs merge=lfs -text diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7f70dcdd609709ebe57ca898ec6e51fc8bffccc7 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,65 @@ +FROM node:22-slim AS prevision-api +WORKDIR /repo +RUN corepack enable +COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ +COPY apps/prevision-api/package.json apps/prevision-api/ +RUN pnpm install --frozen-lockfile --filter @prevision/api +COPY apps/prevision-api/ apps/prevision-api/ +RUN pnpm --filter @prevision/api generate && \ + pnpm --filter @prevision/api build && \ + pnpm --filter @prevision/api deploy --prod --legacy /out + +FROM python:3.12-slim + +# A Space exposes one port (7860), so nginx owns it and the renderer moves to 7861. +ENV PYTHONUNBUFFERED=1 \ + PYTHONDONTWRITEBYTECODE=1 \ + HF_HOME=/home/user/.cache/huggingface \ + VISUALIZER_CONFIG=visualizer.gpu.toml \ + VISUALIZER_PORT=7861 \ + PREVISION_API_PORT=8001 \ + PREVISION_API_INTERNAL_URL=http://127.0.0.1:8001 \ + AUTH_ENFORCEMENT=on \ + PROCESSING_TOKEN_AUDIENCE=prevision-processing \ + HOME=/home/user + +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + bash \ + curl \ + git \ + git-lfs \ + procps \ + wget \ + ffmpeg \ + libglib2.0-0 \ + libgomp1 \ + build-essential \ + ca-certificates \ + nginx && \ + rm -rf /var/lib/apt/lists/* + +RUN useradd -m -u 1000 user + +WORKDIR /app + +COPY apps/renderer/requirements-base.txt apps/renderer/requirements-gpu-cu126.txt ./ +RUN pip install --no-cache-dir --upgrade pip && \ + pip install --no-cache-dir -r requirements-gpu-cu126.txt + +COPY --chown=user:1000 apps/renderer/ /app/ + +COPY --from=prevision-api /usr/local/bin/node /usr/local/bin/node +COPY --chown=user:1000 --from=prevision-api /out /srv/prevision +COPY infra/runpod/start.sh /usr/local/bin/start-services +COPY infra/huggingface/start.sh /usr/local/bin/start-space +COPY infra/huggingface/nginx.conf /etc/prevision/nginx.conf +RUN chmod 0755 /usr/local/bin/start-services /usr/local/bin/start-space && \ + mkdir -p data/uploads data/jobs data/qa-runs && \ + chown -R user:1000 /app /srv/prevision + +USER user + +EXPOSE 7860 + +CMD ["/usr/local/bin/start-space"] diff --git a/README.md b/README.md index b23694ebccd65707211827e6f2fe21b74fddad6a..bc5bb23d892776affd94085bbc3a35e606853439 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,13 @@ --- title: Prevision -emoji: 🐨 -colorFrom: green -colorTo: yellow +emoji: 🏠 +colorFrom: indigo +colorTo: purple sdk: docker +app_port: 7860 pinned: false -license: mit +short_description: Prevision account API and GPU room renderer --- -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +Deployed from the PREVISION repository by the `Deploy Hugging Face Space` GitHub workflow. +`/api/*` is the account API; every other path is the renderer. diff --git a/apps/prevision-api/.env.example b/apps/prevision-api/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..92584ad300402f3a2435d69c0f05bc508d1b866c --- /dev/null +++ b/apps/prevision-api/.env.example @@ -0,0 +1,12 @@ +ENVIRONMENT=development +PREVISION_DATABASE_URL=postgresql://postgres:postgres@localhost:55432/prevision_dev +PREVISION_API_PORT=8001 +PREVISION_ALLOWED_ORIGINS=http://localhost:5173 +PREVISION_APP_URL=http://localhost:5173 +CLERK_SECRET_KEY=replace-with-development-clerk-secret +PROCESSING_TOKEN_SECRET=local-development-processing-secret-change-me +PROCESSING_TOKEN_AUDIENCE=prevision-processing +STRIPE_SECRET_KEY=replace-with-stripe-test-secret +STRIPE_WEBHOOK_SECRET=replace-with-webhook-signing-secret +STRIPE_PRICE_STARTER=replace-with-starter-price-id +STRIPE_PRICE_GROWTH=replace-with-growth-price-id diff --git a/apps/prevision-api/.gitignore b/apps/prevision-api/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a460b849930cf9f4c9332d55148241807318daa5 --- /dev/null +++ b/apps/prevision-api/.gitignore @@ -0,0 +1,4 @@ +src/generated/ +dist/ +.env +*.tsbuildinfo diff --git a/apps/prevision-api/.oxlintrc.json b/apps/prevision-api/.oxlintrc.json new file mode 100644 index 0000000000000000000000000000000000000000..554f9be8a99adbe00bad60c890a228ec732fbdea --- /dev/null +++ b/apps/prevision-api/.oxlintrc.json @@ -0,0 +1,10 @@ +{ + "$schema": "./node_modules/oxlint/configuration_schema.json", + "rules": { + "typescript/no-explicit-any": "off", + "typescript/no-floating-promises": "error" + }, + "env": { + "node": true + } +} diff --git a/apps/prevision-api/README.md b/apps/prevision-api/README.md new file mode 100644 index 0000000000000000000000000000000000000000..87ac9a43cbb8a77bd542b026c8357402d7970e5e --- /dev/null +++ b/apps/prevision-api/README.md @@ -0,0 +1,82 @@ +# Prevision API + +NestJS 12 + Prisma 7 (PostgreSQL). Serves the Prevision web app at `/api/*`: + +| Route | | +|---|---| +| `GET /api/me` | the signed-in account and its free tries `{limit, used, remaining}` | +| `GET /api/tiles`, `/api/tiles/facets`, `/api/tiles/:slug` | the studio's tile library (paginated list, facet counts, one tile) | +| `POST /api/processing-token` | a 10-minute token for the renderer (issuer `prevision-api`) | +| `POST /internal/generations`, `/internal/generations/:id/refund` | the renderer charging and refunding a free try (internal token) | +| `GET /api/subscriptions/current` | the active plan, or null | +| `POST /api/subscriptions/checkout` `{plan}` | a Stripe Checkout URL for Starter or Growth | +| `POST /api/subscriptions/portal` | a Stripe billing portal URL | +| `POST /api/webhooks/stripe` | Stripe events (signature checked), keeps `subscriptions` in sync | +| `GET /health`, `/ready` | liveness, database readiness | + +## Responses + +Success: `{ "success": true, "data": ..., "meta"?: { "page", "pageSize", "total", "totalPages" } }` (`meta` on paginated lists). Error: `{ "success": false, "error": { "code", "message" } }`. `ResponseInterceptor` and `HttpExceptionFilter` in `src/common` produce both. + +## Layout + +``` +src/ + common/ interceptors, filters, exceptions, pagination DTOs, shared interfaces + config/ env loading (APP_CONFIG) and its interface + prisma/ PrismaService, soft-delete extension + clerk/ Clerk token verification and profile lookup + users/ account from a Clerk sign-in, ClerkAuthGuard, GET /me + generations/ free tries (renderer charges/refunds via /internal) + catalog/ seeds the tiles table from prisma/catalog.json + tiles/ tile library reads + scripts/ seed-catalog, set-user-role (run from dist/) + rendering/ renderer processing tokens + stripe/ the shared Stripe client + subscriptions/ checkout, billing portal, current plan; the only writer of subscriptions + webhooks/ Stripe webhook: signature guard, event → subscription sync + health/ /health, /ready +test/ e2e specs per feature (real Postgres) +``` + +## Auth + +Clerk owns sign-in. Every `/api` route needs `Authorization: Bearer `; `ClerkAuthGuard` verifies it (signature, expiry, `azp` in `PREVISION_ALLOWED_ORIGINS`) and loads the account, creating it on the first request. No waitlist, approval or onboarding. + +`CLERK_SECRET_KEY` is a comma-separated list, one key per Clerk instance (staging: `sk_live_…,sk_test_…`). `ClerkService` accepts a token signed by any of them and looks a new user up in whichever instance owns it, so the custom domain (production instance) and `vercel.app` previews (development instance) share one API. Accounts are matched by Clerk id, then by verified email, so the same person signing in through both instances gets one account. + +## Free tries + +Each account gets `FREE_GENERATIONS` (10) room-photo visualizations; admins are unlimited. The renderer calls `POST /internal/generations` before accepting a job from a Prevision token; `GenerationsService.create` locks the user row, counts `generations` without `refunded_at` and answers 402 `NO_FREE_TRIES` at the limit. A failed job is refunded once (`refunded_at`). Sample rooms are never charged. + +## Billing (Stripe) + +Plans: Starter $70/month (`STARTER_MONTHLY_GENERATIONS`, 150) and Growth $140/month (`GROWTH_MONTHLY_GENERATIONS`, 600). `subscriptions/` creates Checkout sessions (Prevision branding, USD only) and billing-portal sessions; `webhooks/` verifies the signature on the raw body and re-syncs the subscription from Stripe for `checkout.session.completed` and `customer.subscription.created|updated|deleted`. The allowance (`generations/allowance.ts`) is: admin unlimited, active subscription = monthly plan limit since `current_period_start`, otherwise the lifetime free tries. + +Local testing: `stripe listen --forward-to localhost:/api/webhooks/stripe` and put the printed `whsec_…` in `STRIPE_WEBHOOK_SECRET`; pay with card `4242 4242 4242 4242`. Staging's endpoint is `we_1UMUCpFuPzalTB3Q6226EaDs` (pod :8001); its secrets come from `STRIPE_SECRET_KEY_STAGING` / `STRIPE_WEBHOOK_SECRET_STAGING`. + +## Database + +Prevision has its own database (`PREVISION_DATABASE_URL`, Supabase project `mceapsmuhgupvksxmtis` on staging, session pooler URL), fully owned by Prisma: `users` (with `role`: `user` or `admin`, `stripe_customer_id`), `subscriptions`, `generations` and `tiles`. Migrations live in `prisma/migrations`; RLS is enabled on every table. The tiles are the 19 shared demo tiles in `prisma/catalog.json`, upserted on every start. Users and tiles are soft-deleted (`deleted_at`), never removed; `PrismaService.db` hides them automatically. + +## Admins + +No admin panel: an admin is a user with `role = admin`, which removes the free-try limit. After the person has signed in once: `pnpm build && pnpm user:role admin` (or `user` to revert), with `PREVISION_DATABASE_URL` set. + +## Commands + +```bash +pnpm dev # nest start --watch, port PREVISION_API_PORT (8001) +pnpm generate # prisma generate (turbo runs it before build, lint and test) +pnpm build # nest build +pnpm lint # oxlint + tsc +pnpm test # unit + e2e (real Postgres; TEST_DATABASE_URL, default localhost:55432/prevision_api_test) +pnpm db:migrate # prisma migrate dev (review the SQL; enable RLS on new tables) +pnpm db:deploy # prisma migrate deploy (the pod runs this on start) +``` + +Local `.env` (git-ignored): `PREVISION_DATABASE_URL`, `CLERK_SECRET_KEY` (comma-separated to accept several Clerk instances, e.g. `sk_live_…,sk_test_…`), `PROCESSING_TOKEN_SECRET`, `PREVISION_ALLOWED_ORIGINS`, `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`, `STRIPE_PRICE_STARTER`, `STRIPE_PRICE_GROWTH`, optionally `PREVISION_API_PORT`, `PREVISION_APP_URL`, `STRIPE_LOGO_URL`, `STRIPE_PORTAL_CONFIGURATION_ID`, `CLERK_JWT_KEY`. Full list: `src/config/app-config.ts`. + +## Deployment + +See [the deployment runbook](../../docs/DEPLOYMENT.md). Backend builds and deployments are manual. diff --git a/apps/prevision-api/nest-cli.json b/apps/prevision-api/nest-cli.json new file mode 100644 index 0000000000000000000000000000000000000000..f9aa683b1ad5cffc76da9ad4b77c562ac4c2b399 --- /dev/null +++ b/apps/prevision-api/nest-cli.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://json.schemastore.org/nest-cli", + "collection": "@nestjs/schematics", + "sourceRoot": "src", + "compilerOptions": { + "deleteOutDir": true + } +} diff --git a/apps/prevision-api/package.json b/apps/prevision-api/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f888d61f055b41dede587f5c67e495e41412b439 --- /dev/null +++ b/apps/prevision-api/package.json @@ -0,0 +1,66 @@ +{ + "name": "@prevision/api", + "version": "0.0.0", + "description": "Prevision API: Clerk sign-in, free visualizer tries, the tile catalog and renderer tokens.", + "private": true, + "type": "module", + "files": [ + "dist", + "prisma", + "prisma.config.ts" + ], + "scripts": { + "build": "nest build", + "start": "nest start", + "start:dev": "nest start --watch", + "start:debug": "nest start --debug --watch", + "start:prod": "node dist/main", + "lint": "oxlint --type-aware src/ test/ && tsc --noEmit -p tsconfig.json", + "test": "vitest run && vitest run --config ./vitest.config.e2e.ts", + "test:watch": "vitest", + "test:cov": "vitest run --coverage", + "test:debug": "vitest --inspect-brk --no-file-parallelism", + "test:e2e": "vitest run --config ./vitest.config.e2e.ts", + "dev": "nest start --watch", + "test:unit": "vitest run", + "db:migrate": "prisma migrate dev", + "db:deploy": "prisma migrate deploy", + "generate": "prisma generate", + "db:seed": "node dist/scripts/seed-catalog.js", + "user:role": "node dist/scripts/set-user-role.js" + }, + "dependencies": { + "@clerk/backend": "^3.22.0", + "@nestjs/common": "^12.0.1", + "@nestjs/core": "^12.0.1", + "@nestjs/platform-express": "^12.0.1", + "@prisma/adapter-pg": "^7.10.0", + "@prisma/client": "^7.10.0", + "class-transformer": "^0.5.1", + "class-validator": "^0.15.1", + "dotenv": "^18.0.5", + "jose": "^6.2.12", + "pg": "^8.23.1", + "prisma": "^7.10.0", + "reflect-metadata": "^0.2.2", + "rxjs": "^7.8.1", + "stripe": "^23.0.0" + }, + "devDependencies": { + "@nestjs/cli": "^12.0.0", + "@nestjs/schematics": "^12.0.0", + "@nestjs/testing": "^12.0.1", + "@types/express": "^5.0.0", + "@types/node": "^24.0.0", + "@types/pg": "^8.23.1", + "@types/supertest": "^7.0.0", + "@vitest/coverage-v8": "^4.1.2", + "oxlint": "^1.58.0", + "oxlint-tsgolint": "^7.0.2001", + "prettier": "^3.4.2", + "supertest": "^7.0.0", + "typescript": "^6.0.2", + "vite": "^8.3.2", + "vitest": "^4.1.2" + } +} diff --git a/apps/prevision-api/prisma.config.ts b/apps/prevision-api/prisma.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..5aa10872425fd308dad6ba5ad22bbf5dac5cfb8a --- /dev/null +++ b/apps/prevision-api/prisma.config.ts @@ -0,0 +1,9 @@ +import 'dotenv/config'; +import { defineConfig } from 'prisma/config'; + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { path: 'prisma/migrations' }, + // `prisma generate` needs no database; migrate commands fail clearly without one. + datasource: { url: process.env.PREVISION_DATABASE_URL ?? '' }, +}); diff --git a/apps/prevision-api/prisma/catalog.json b/apps/prevision-api/prisma/catalog.json new file mode 100644 index 0000000000000000000000000000000000000000..c2ae8d98809c77d5e1b9029effbd3d13e44aed17 --- /dev/null +++ b/apps/prevision-api/prisma/catalog.json @@ -0,0 +1,699 @@ +{ + "tiles": [ + { + "slug": "black-marble-herringbone", + "name": "Black Marble Herringbone", + "collection": null, + "surfaces": [ + "floor" + ], + "widthMm": 75, + "heightMm": 300, + "position": 11, + "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/black-marble-herringbone/image-57508b5a7b735517.jpg", + "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/black-marble-herringbone/thumbnail-57508b5a7b735517.jpg", + "assets": {}, + "render": { + "scale": 1, + "keywords": [ + "floor" + ], + "tileWidthInches": 3, + "tileHeightInches": 12, + "patternWidthInches": 48, + "patternHeightInches": 48, + "tileWidthMeters": 0.075, + "tileHeightMeters": 0.3, + "patternWidthMeters": 1.2, + "patternHeightMeters": 1.2, + "patternUnit": "multi-tile", + "groutWidthMeters": 0, + "layout": "grid", + "roughness": 0.3, + "reflectivity": 0.28, + "normalStrength": 0.1, + "roughnessMapStrength": 0.2, + "specularStrength": 0.38, + "tileVariationStrength": 0.04 + } + }, + { + "slug": "black-white-encaustic", + "name": "Black White Encaustic", + "collection": null, + "surfaces": [ + "floor" + ], + "widthMm": 200, + "heightMm": 200, + "position": 8, + "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/black-white-encaustic/image-016f0dba398638a3.jpg", + "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/black-white-encaustic/thumbnail-016f0dba398638a3.jpg", + "assets": {}, + "render": { + "scale": 1, + "keywords": [ + "floor" + ], + "tileWidthInches": 8, + "tileHeightInches": 8, + "patternWidthInches": 16, + "patternHeightInches": 16, + "tileWidthMeters": 0.2, + "tileHeightMeters": 0.2, + "patternWidthMeters": 0.4, + "patternHeightMeters": 0.4, + "patternUnit": "multi-tile", + "groutWidthMeters": 0, + "layout": "grid", + "roughness": 0.64, + "reflectivity": 0.04, + "tileVariationStrength": 0.1 + } + }, + { + "slug": "black-white-marble-checker", + "name": "Black White Marble Checkered", + "collection": null, + "surfaces": [ + "floor" + ], + "widthMm": 300, + "heightMm": 300, + "position": 2, + "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/black-white-marble-checker/image-d3bef9925d890c2d.jpg", + "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/black-white-marble-checker/thumbnail-d3bef9925d890c2d.jpg", + "assets": {}, + "render": { + "scale": 1, + "keywords": [ + "floor" + ], + "tileWidthInches": 12, + "tileHeightInches": 12, + "patternWidthInches": 72, + "patternHeightInches": 72, + "tileWidthMeters": 0.3, + "tileHeightMeters": 0.3, + "patternWidthMeters": 1.8, + "patternHeightMeters": 1.8, + "patternUnit": "multi-tile", + "groutWidthMeters": 0, + "layout": "diamond", + "roughness": 0.34, + "reflectivity": 0.24, + "normalStrength": 0.08, + "roughnessMapStrength": 0.2, + "specularStrength": 0.36, + "tileVariationStrength": 0.06 + } + }, + { + "slug": "circular-geometric-marble", + "name": "Circular Geometric Marble", + "collection": null, + "surfaces": [ + "floor" + ], + "widthMm": 300, + "heightMm": 300, + "position": 1, + "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/circular-geometric-marble/image-7b161b5b7f104f51.jpg", + "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/circular-geometric-marble/thumbnail-7b161b5b7f104f51.jpg", + "assets": {}, + "render": { + "scale": 1, + "keywords": [ + "floor" + ], + "tileWidthInches": 12, + "tileHeightInches": 12, + "patternWidthInches": 72, + "patternHeightInches": 72, + "tileWidthMeters": 0.3, + "tileHeightMeters": 0.3, + "patternWidthMeters": 1.8, + "patternHeightMeters": 1.8, + "patternUnit": "multi-tile", + "groutWidthMeters": 0, + "layout": "grid", + "roughness": 0.3, + "reflectivity": 0.25, + "normalStrength": 0.08, + "roughnessMapStrength": 0.18, + "specularStrength": 0.38, + "tileVariationStrength": 0.03 + } + }, + { + "slug": "extra-grey-checkerboard", + "name": "Grey Checkerboard", + "collection": null, + "surfaces": [ + "floor" + ], + "widthMm": 300, + "heightMm": 300, + "position": 4, + "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/extra-grey-checkerboard/image-f6126641a925b7af.jpg", + "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/extra-grey-checkerboard/thumbnail-cf85253dd52c5391.webp", + "assets": {}, + "render": { + "scale": 1, + "keywords": [ + "floor" + ], + "tileWidthInches": 12, + "tileHeightInches": 12, + "patternWidthInches": 96, + "patternHeightInches": 96, + "tileWidthMeters": 0.3, + "tileHeightMeters": 0.3, + "patternWidthMeters": 2.4, + "patternHeightMeters": 2.4, + "patternUnit": "multi-tile", + "groutWidthMeters": 0, + "layout": "grid", + "roughness": 0.74, + "reflectivity": 0.07, + "tileVariationStrength": 0.14 + } + }, + { + "slug": "extra-light-marble", + "name": "Light Marble", + "collection": null, + "surfaces": [ + "floor" + ], + "widthMm": 610, + "heightMm": 610, + "position": 6, + "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/extra-light-marble/image-2a845e5b7f1830cc.jpg", + "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/extra-light-marble/thumbnail-95b32fe1601db21c.webp", + "assets": {}, + "render": { + "scale": 1, + "keywords": [ + "floor" + ], + "tileWidthInches": 24, + "tileHeightInches": 24, + "patternWidthInches": 48, + "patternHeightInches": 48 + } + }, + { + "slug": "extra-ornate-cement", + "name": "Ornate Cement", + "collection": null, + "surfaces": [ + "floor" + ], + "widthMm": 200, + "heightMm": 200, + "position": 5, + "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/extra-ornate-cement/image-85cfc6cd1e75ac1c.jpg", + "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/extra-ornate-cement/thumbnail-be398c51ce9f9b08.webp", + "assets": {}, + "render": { + "scale": 1, + "keywords": [ + "floor" + ], + "tileWidthInches": 8, + "tileHeightInches": 8, + "patternWidthInches": 72, + "patternHeightInches": 72, + "tileWidthMeters": 0.2, + "tileHeightMeters": 0.2, + "patternWidthMeters": 1.8, + "patternHeightMeters": 1.8, + "patternUnit": "multi-tile", + "groutWidthMeters": 0, + "layout": "grid", + "roughness": 0.78, + "reflectivity": 0.06, + "tileVariationStrength": 0.14 + } + }, + { + "slug": "green-white-marble-inlay", + "name": "Green White Marble Inlay", + "collection": null, + "surfaces": [ + "floor" + ], + "widthMm": 300, + "heightMm": 300, + "position": 9, + "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/green-white-marble-inlay/image-62d3b131e38bd305.jpg", + "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/green-white-marble-inlay/thumbnail-62d3b131e38bd305.jpg", + "assets": {}, + "render": { + "scale": 1, + "keywords": [ + "floor" + ], + "tileWidthInches": 12, + "tileHeightInches": 12, + "patternWidthInches": 96, + "patternHeightInches": 96, + "tileWidthMeters": 0.3, + "tileHeightMeters": 0.3, + "patternWidthMeters": 2.4, + "patternHeightMeters": 2.4, + "patternUnit": "multi-tile", + "groutWidthMeters": 0, + "layout": "grid", + "roughness": 0.28, + "reflectivity": 0.3, + "normalStrength": 0.08, + "roughnessMapStrength": 0.18, + "specularStrength": 0.4, + "tileVariationStrength": 0.02 + } + }, + { + "slug": "ivory-gold-marble-slab", + "name": "Ivory Gold Marble Slab", + "collection": null, + "surfaces": [ + "floor" + ], + "widthMm": 1800, + "heightMm": 1200, + "position": 7, + "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/ivory-gold-marble-slab/image-9aeb915f6518f5ae.webp", + "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/ivory-gold-marble-slab/thumbnail-6a027fa9a7c66aea.webp", + "assets": { + "variantImages": [ + "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/ivory-gold-marble-slab/variant-1-0939d306001635bd.webp", + "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/ivory-gold-marble-slab/variant-2-fb437c7012479a74.webp", + "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/ivory-gold-marble-slab/variant-3-9aeb915f6518f5ae.webp" + ] + }, + "render": { + "scale": 1, + "keywords": [ + "floor" + ], + "tileWidthInches": 70.87, + "tileHeightInches": 47.24, + "patternWidthInches": 425.2, + "patternHeightInches": 188.98, + "tileWidthMeters": 1.8, + "tileHeightMeters": 1.2, + "patternWidthMeters": 10.8, + "patternHeightMeters": 4.8, + "patternUnit": "multi-tile", + "groutWidthMeters": 0, + "layout": "grid", + "roughness": 0.24, + "reflectivity": 0.34, + "normalStrength": 0.08, + "roughnessMapStrength": 0.2, + "specularStrength": 0.4, + "tileVariationStrength": 0.02 + } + }, + { + "slug": "marble-diamond-tile-floor-pbr0001", + "name": "Marble Diamond Tile Floor", + "collection": null, + "surfaces": [ + "floor" + ], + "widthMm": 300, + "heightMm": 300, + "position": 12, + "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/marble-diamond-tile-floor-pbr0001/image-cabfe7d334f03cae.jpg", + "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/marble-diamond-tile-floor-pbr0001/thumbnail-cabfe7d334f03cae.jpg", + "assets": {}, + "render": { + "scale": 1, + "keywords": [ + "floor" + ], + "tileWidthInches": 12, + "tileHeightInches": 12, + "patternWidthInches": 60, + "patternHeightInches": 60, + "tileWidthMeters": 0.3, + "tileHeightMeters": 0.3, + "patternWidthMeters": 1.5, + "patternHeightMeters": 1.5, + "patternUnit": "multi-tile", + "groutWidthMeters": 0, + "layout": "grid", + "roughness": 0.34, + "reflectivity": 0.24, + "normalStrength": 0.1, + "heightStrength": 0.04, + "roughnessMapStrength": 0.2, + "specularStrength": 0.34, + "tileVariationStrength": 0.04 + } + }, + { + "slug": "old-french-fan-mosaic", + "name": "Old French Fan Mosaic", + "collection": null, + "surfaces": [ + "floor" + ], + "widthMm": 38, + "heightMm": 38, + "position": 0, + "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/old-french-fan-mosaic/image-175f1522576e9cd6.jpg", + "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/old-french-fan-mosaic/thumbnail-175f1522576e9cd6.jpg", + "assets": {}, + "render": { + "scale": 1, + "keywords": [ + "floor" + ], + "tileWidthInches": 1.5, + "tileHeightInches": 1.5, + "patternWidthInches": 70.87, + "patternHeightInches": 94.49, + "tileWidthMeters": 0.038, + "tileHeightMeters": 0.038, + "patternWidthMeters": 1.8, + "patternHeightMeters": 2.4, + "patternUnit": "multi-tile", + "groutWidthMeters": 0, + "layout": "grid", + "roughness": 0.68, + "reflectivity": 0.05, + "normalStrength": 0.18, + "heightStrength": 0.06, + "roughnessMapStrength": 0.28, + "specularStrength": 0.12, + "tileVariationStrength": 0.04 + } + }, + { + "slug": "old-stone-star-medallion", + "name": "Old Stone Star Medallion", + "collection": null, + "surfaces": [ + "floor" + ], + "widthMm": 600, + "heightMm": 600, + "position": 10, + "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/old-stone-star-medallion/image-acfb1e7bee783454.jpg", + "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/old-stone-star-medallion/thumbnail-acfb1e7bee783454.jpg", + "assets": {}, + "render": { + "scale": 1, + "keywords": [ + "floor" + ], + "tileWidthInches": 24, + "tileHeightInches": 24, + "patternWidthInches": 96, + "patternHeightInches": 96, + "tileWidthMeters": 0.6, + "tileHeightMeters": 0.6, + "patternWidthMeters": 2.4, + "patternHeightMeters": 2.4, + "patternUnit": "multi-tile", + "groutWidthMeters": 0, + "layout": "grid", + "roughness": 0.5, + "reflectivity": 0.12, + "normalStrength": 0.16, + "heightStrength": 0.05, + "roughnessMapStrength": 0.25, + "specularStrength": 0.18 + } + }, + { + "slug": "old-wooden-square-flooring-pbr0668", + "name": "Old Wooden Square Flooring", + "collection": null, + "surfaces": [ + "floor" + ], + "widthMm": 300, + "heightMm": 300, + "position": 14, + "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/old-wooden-square-flooring-pbr0668/image-50f823c4ada0839f.jpg", + "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/old-wooden-square-flooring-pbr0668/thumbnail-50f823c4ada0839f.jpg", + "assets": {}, + "render": { + "scale": 1, + "keywords": [ + "floor" + ], + "tileWidthInches": 12, + "tileHeightInches": 12, + "patternWidthInches": 48, + "patternHeightInches": 48, + "tileWidthMeters": 0.3, + "tileHeightMeters": 0.3, + "patternWidthMeters": 1.2, + "patternHeightMeters": 1.2, + "patternUnit": "multi-tile", + "groutWidthMeters": 0, + "layout": "grid", + "roughness": 0.58, + "reflectivity": 0.08, + "normalStrength": 0.2, + "heightStrength": 0.08, + "roughnessMapStrength": 0.32, + "specularStrength": 0.12, + "tileVariationStrength": 0.08 + } + }, + { + "slug": "portuguese-tiles-pbr0674", + "name": "Portuguese Tiles", + "collection": null, + "surfaces": [ + "floor" + ], + "widthMm": 200, + "heightMm": 200, + "position": 13, + "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/portuguese-tiles-pbr0674/image-45e483c3b6506825.jpg", + "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/portuguese-tiles-pbr0674/thumbnail-45e483c3b6506825.jpg", + "assets": {}, + "render": { + "scale": 1, + "keywords": [ + "floor" + ], + "tileWidthInches": 8, + "tileHeightInches": 8, + "patternWidthInches": 24, + "patternHeightInches": 24, + "tileWidthMeters": 0.2, + "tileHeightMeters": 0.2, + "patternWidthMeters": 0.6, + "patternHeightMeters": 0.6, + "patternUnit": "multi-tile", + "groutWidthMeters": 0, + "layout": "grid", + "roughness": 0.58, + "reflectivity": 0.1, + "normalStrength": 0.14, + "heightStrength": 0.05, + "roughnessMapStrength": 0.24, + "specularStrength": 0.14, + "tileVariationStrength": 0.03 + } + }, + { + "slug": "terracotta-ivory-marble-checker", + "name": "Terracotta Ivory Marble Checker", + "collection": null, + "surfaces": [ + "floor" + ], + "widthMm": 300, + "heightMm": 300, + "position": 3, + "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/terracotta-ivory-marble-checker/image-163cb191dc8ba5f4.jpg", + "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/terracotta-ivory-marble-checker/thumbnail-163cb191dc8ba5f4.jpg", + "assets": {}, + "render": { + "scale": 1, + "keywords": [ + "floor" + ], + "tileWidthInches": 12, + "tileHeightInches": 12, + "patternWidthInches": 72, + "patternHeightInches": 72, + "tileWidthMeters": 0.3, + "tileHeightMeters": 0.3, + "patternWidthMeters": 1.8, + "patternHeightMeters": 1.8, + "patternUnit": "multi-tile", + "groutWidthMeters": 0, + "layout": "grid", + "roughness": 0.4, + "reflectivity": 0.18, + "normalStrength": 0.12, + "roughnessMapStrength": 0.24, + "specularStrength": 0.28, + "tileVariationStrength": 0.04 + } + }, + { + "slug": "versailles-parquet-floor-10-pbr0790", + "name": "Versailles Parquet Floor 10", + "collection": null, + "surfaces": [ + "floor" + ], + "widthMm": 1000, + "heightMm": 1000, + "position": 15, + "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/versailles-parquet-floor-10-pbr0790/image-a7260a9aeee7225e.jpg", + "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/versailles-parquet-floor-10-pbr0790/thumbnail-a7260a9aeee7225e.jpg", + "assets": {}, + "render": { + "scale": 0.5, + "keywords": [ + "floor" + ], + "tileWidthInches": 39.37, + "tileHeightInches": 39.37, + "patternWidthInches": 157.48, + "patternHeightInches": 157.48, + "tileWidthMeters": 1, + "tileHeightMeters": 1, + "patternWidthMeters": 4, + "patternHeightMeters": 4, + "patternUnit": "multi-tile", + "groutWidthMeters": 0, + "layout": "grid", + "roughness": 0.36, + "reflectivity": 0.18, + "normalStrength": 0.16, + "heightStrength": 0.06, + "roughnessMapStrength": 0.24, + "specularStrength": 0.28, + "tileVariationStrength": 0.04 + } + }, + { + "slug": "wallpaper-olive-floral-damask", + "name": "Olive Floral Damask", + "collection": null, + "surfaces": [ + "walls" + ], + "widthMm": 530, + "heightMm": 530, + "position": 196, + "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/wallpaper-olive-floral-damask/image-3df71399fb8818a3.jpg", + "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/wallpaper-olive-floral-damask/thumbnail-05467054368b5e42.jpg", + "assets": {}, + "render": { + "scale": 1, + "keywords": [ + "walls" + ], + "tileWidthInches": 20.866141732283467, + "tileHeightInches": 20.866141732283467, + "patternWidthInches": 20.866141732283467, + "patternHeightInches": 20.866141732283467, + "tileWidthMeters": 0.53, + "tileHeightMeters": 0.53, + "patternWidthMeters": 0.53, + "patternHeightMeters": 0.53, + "patternUnit": "material", + "groutWidthMeters": 0, + "layout": "grid", + "roughness": 0.86, + "reflectivity": 0.03, + "normalStrength": 0.02, + "heightStrength": 0, + "roughnessMapStrength": 0.05, + "specularStrength": 0.03, + "tileVariationStrength": 0 + } + }, + { + "slug": "wallpaper-sage-diamond-medallion", + "name": "Sage Diamond Medallion", + "collection": null, + "surfaces": [ + "walls" + ], + "widthMm": 530, + "heightMm": 530, + "position": 195, + "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/wallpaper-sage-diamond-medallion/image-0138ff65535a726e.jpg", + "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/wallpaper-sage-diamond-medallion/thumbnail-4bf8d54ea97a2ab9.jpg", + "assets": {}, + "render": { + "scale": 1, + "keywords": [ + "walls" + ], + "tileWidthInches": 20.866141732283467, + "tileHeightInches": 20.866141732283467, + "patternWidthInches": 20.866141732283467, + "patternHeightInches": 20.866141732283467, + "tileWidthMeters": 0.53, + "tileHeightMeters": 0.53, + "patternWidthMeters": 0.53, + "patternHeightMeters": 0.53, + "patternUnit": "material", + "groutWidthMeters": 0, + "layout": "grid", + "roughness": 0.86, + "reflectivity": 0.03, + "normalStrength": 0.02, + "heightStrength": 0, + "roughnessMapStrength": 0.05, + "specularStrength": 0.03, + "tileVariationStrength": 0 + } + }, + { + "slug": "wallpaper-sage-ticking-stripe", + "name": "Sage Ticking Stripe", + "collection": null, + "surfaces": [ + "walls" + ], + "widthMm": 530, + "heightMm": 530, + "position": 194, + "imageUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/wallpaper-sage-ticking-stripe/image-f841f9653591e1eb.jpg", + "thumbnailUrl": "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/baetes/wallpaper-sage-ticking-stripe/thumbnail-d5d3ee999cab10ad.jpg", + "assets": {}, + "render": { + "scale": 1, + "keywords": [ + "walls" + ], + "tileWidthInches": 20.866141732283467, + "tileHeightInches": 20.866141732283467, + "patternWidthInches": 20.866141732283467, + "patternHeightInches": 20.866141732283467, + "tileWidthMeters": 0.53, + "tileHeightMeters": 0.53, + "patternWidthMeters": 0.53, + "patternHeightMeters": 0.53, + "patternUnit": "material", + "groutWidthMeters": 0, + "layout": "grid", + "roughness": 0.86, + "reflectivity": 0.03, + "normalStrength": 0.02, + "heightStrength": 0, + "roughnessMapStrength": 0.05, + "specularStrength": 0.03, + "tileVariationStrength": 0 + } + } + ] +} diff --git a/apps/prevision-api/prisma/migrations/20261003131649_init/migration.sql b/apps/prevision-api/prisma/migrations/20261003131649_init/migration.sql new file mode 100644 index 0000000000000000000000000000000000000000..d6d2230578e98ae2a1767af1ad1c1f045de0a29a --- /dev/null +++ b/apps/prevision-api/prisma/migrations/20261003131649_init/migration.sql @@ -0,0 +1,74 @@ +-- CreateEnum +CREATE TYPE "user_role" AS ENUM ('user', 'admin'); + +-- CreateTable +CREATE TABLE "users" ( + "id" UUID NOT NULL, + "clerk_user_id" VARCHAR(64) NOT NULL, + "email" VARCHAR(255) NOT NULL, + "name" VARCHAR(255), + "role" "user_role" NOT NULL DEFAULT 'user', + "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ NOT NULL, + "deleted_at" TIMESTAMPTZ, + + CONSTRAINT "users_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "generations" ( + "id" UUID NOT NULL, + "user_id" UUID NOT NULL, + "job_id" VARCHAR(64) NOT NULL, + "refunded_at" TIMESTAMPTZ, + "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "generations_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "tiles" ( + "id" UUID NOT NULL, + "slug" VARCHAR(120) NOT NULL, + "name" VARCHAR(255) NOT NULL, + "collection" VARCHAR(120), + "surfaces" VARCHAR(20)[], + "width_mm" INTEGER, + "height_mm" INTEGER, + "image_url" VARCHAR(1024) NOT NULL, + "thumbnail_url" VARCHAR(1024), + "assets" JSONB NOT NULL DEFAULT '{}', + "render" JSONB NOT NULL DEFAULT '{}', + "position" INTEGER, + "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ NOT NULL, + "deleted_at" TIMESTAMPTZ, + + CONSTRAINT "tiles_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "users_clerk_user_id_key" ON "users"("clerk_user_id"); + +-- CreateIndex +CREATE UNIQUE INDEX "users_email_key" ON "users"("email"); + +-- CreateIndex +CREATE UNIQUE INDEX "generations_job_id_key" ON "generations"("job_id"); + +-- CreateIndex +CREATE INDEX "generations_user_id_idx" ON "generations"("user_id"); + +-- CreateIndex +CREATE UNIQUE INDEX "tiles_slug_key" ON "tiles"("slug"); + +-- CreateIndex +CREATE INDEX "tiles_name_idx" ON "tiles"("name"); + +-- AddForeignKey +ALTER TABLE "generations" ADD CONSTRAINT "generations_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- No Supabase Data API access to these tables. +ALTER TABLE "users" ENABLE ROW LEVEL SECURITY; +ALTER TABLE "generations" ENABLE ROW LEVEL SECURITY; +ALTER TABLE "tiles" ENABLE ROW LEVEL SECURITY; diff --git a/apps/prevision-api/prisma/migrations/20261003143919_subscriptions/migration.sql b/apps/prevision-api/prisma/migrations/20261003143919_subscriptions/migration.sql new file mode 100644 index 0000000000000000000000000000000000000000..b6bd11883811ab4ea0930164e3d37221de1feab6 --- /dev/null +++ b/apps/prevision-api/prisma/migrations/20261003143919_subscriptions/migration.sql @@ -0,0 +1,41 @@ +-- CreateEnum +CREATE TYPE "subscription_plan" AS ENUM ('starter', 'growth'); + +-- CreateEnum +CREATE TYPE "subscription_status" AS ENUM ('incomplete', 'incomplete_expired', 'trialing', 'active', 'past_due', 'canceled', 'unpaid', 'paused'); + +-- AlterTable +ALTER TABLE "users" ADD COLUMN "stripe_customer_id" VARCHAR(64); + +-- CreateTable +CREATE TABLE "subscriptions" ( + "id" UUID NOT NULL, + "user_id" UUID NOT NULL, + "stripe_subscription_id" VARCHAR(64) NOT NULL, + "stripe_price_id" VARCHAR(64) NOT NULL, + "plan" "subscription_plan" NOT NULL, + "status" "subscription_status" NOT NULL, + "current_period_start" TIMESTAMPTZ NOT NULL, + "current_period_end" TIMESTAMPTZ NOT NULL, + "cancel_at_period_end" BOOLEAN NOT NULL DEFAULT false, + "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ NOT NULL, + + CONSTRAINT "subscriptions_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "subscriptions_stripe_subscription_id_key" ON "subscriptions"("stripe_subscription_id"); + +-- CreateIndex +CREATE INDEX "subscriptions_user_id_status_idx" ON "subscriptions"("user_id", "status"); + +-- CreateIndex +CREATE UNIQUE INDEX "users_stripe_customer_id_key" ON "users"("stripe_customer_id"); + +-- AddForeignKey +ALTER TABLE "subscriptions" ADD CONSTRAINT "subscriptions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE; + + +-- No Supabase Data API access. +ALTER TABLE "subscriptions" ENABLE ROW LEVEL SECURITY; diff --git a/apps/prevision-api/prisma/migrations/migration_lock.toml b/apps/prevision-api/prisma/migrations/migration_lock.toml new file mode 100644 index 0000000000000000000000000000000000000000..044d57cdb0d5b5bff3475112359a4ee70439bf78 --- /dev/null +++ b/apps/prevision-api/prisma/migrations/migration_lock.toml @@ -0,0 +1,3 @@ +# Please do not edit this file manually +# It should be added in your version-control system (e.g., Git) +provider = "postgresql" diff --git a/apps/prevision-api/prisma/schema.prisma b/apps/prevision-api/prisma/schema.prisma new file mode 100644 index 0000000000000000000000000000000000000000..588bceb3a9174abbc425c2511077a9afb697573b --- /dev/null +++ b/apps/prevision-api/prisma/schema.prisma @@ -0,0 +1,108 @@ +generator client { + provider = "prisma-client" + output = "../src/generated/prisma" + moduleFormat = "esm" +} + +datasource db { + provider = "postgresql" +} + +enum UserRole { + user + admin + + @@map("user_role") +} + +model User { + id String @id @default(uuid()) @db.Uuid + clerkUserId String @unique @map("clerk_user_id") @db.VarChar(64) + email String @unique @db.VarChar(255) + name String? @db.VarChar(255) + /// Admins have unlimited generations. Set with `pnpm user:role admin`. + role UserRole @default(user) + stripeCustomerId String? @unique @map("stripe_customer_id") @db.VarChar(64) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz + updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz + deletedAt DateTime? @map("deleted_at") @db.Timestamptz + generations Generation[] + subscriptions Subscription[] + + @@map("users") +} + +enum SubscriptionPlan { + starter + growth + + @@map("subscription_plan") +} + +/// Mirrors Stripe's subscription statuses. +enum SubscriptionStatus { + incomplete + incomplete_expired + trialing + active + past_due + canceled + unpaid + paused + + @@map("subscription_status") +} + +/// A Stripe subscription, kept in sync by the Stripe webhook. Rows are never deleted. +model Subscription { + id String @id @default(uuid()) @db.Uuid + userId String @map("user_id") @db.Uuid + user User @relation(fields: [userId], references: [id], onDelete: Restrict) + stripeSubscriptionId String @unique @map("stripe_subscription_id") @db.VarChar(64) + stripePriceId String @map("stripe_price_id") @db.VarChar(64) + plan SubscriptionPlan + status SubscriptionStatus + currentPeriodStart DateTime @map("current_period_start") @db.Timestamptz + currentPeriodEnd DateTime @map("current_period_end") @db.Timestamptz + cancelAtPeriodEnd Boolean @default(false) @map("cancel_at_period_end") + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz + updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz + + @@index([userId, status]) + @@map("subscriptions") +} + +/// One room visualization the renderer accepted. Tries used = rows without refundedAt. +model Generation { + id String @id @default(uuid()) @db.Uuid + userId String @map("user_id") @db.Uuid + user User @relation(fields: [userId], references: [id], onDelete: Restrict) + jobId String @unique @map("job_id") @db.VarChar(64) + refundedAt DateTime? @map("refunded_at") @db.Timestamptz + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz + + @@index([userId]) + @@map("generations") +} + +/// The studio's material library: the shared demo tiles, seeded from prisma/catalog.json. +model Tile { + id String @id @default(uuid()) @db.Uuid + slug String @unique @db.VarChar(120) + name String @db.VarChar(255) + collection String? @db.VarChar(120) + surfaces String[] @db.VarChar(20) + widthMm Int? @map("width_mm") + heightMm Int? @map("height_mm") + imageUrl String @map("image_url") @db.VarChar(1024) + thumbnailUrl String? @map("thumbnail_url") @db.VarChar(1024) + assets Json @default("{}") + render Json @default("{}") + position Int? + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz + updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz + deletedAt DateTime? @map("deleted_at") @db.Timestamptz + + @@index([name]) + @@map("tiles") +} diff --git a/apps/prevision-api/src/app.module.ts b/apps/prevision-api/src/app.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..7b29c7a4893bd806be3f26600c2967134541d5da --- /dev/null +++ b/apps/prevision-api/src/app.module.ts @@ -0,0 +1,27 @@ +import { Module } from '@nestjs/common'; +import { ConfigModule } from './config/config.module.js'; +import { GenerationsModule } from './generations/generations.module.js'; +import { HealthModule } from './health/health.module.js'; +import { PrismaModule } from './prisma/prisma.module.js'; +import { RenderingModule } from './rendering/rendering.module.js'; +import { StripeModule } from './stripe/stripe.module.js'; +import { SubscriptionsModule } from './subscriptions/subscriptions.module.js'; +import { TilesModule } from './tiles/tiles.module.js'; +import { UsersModule } from './users/users.module.js'; +import { WebhooksModule } from './webhooks/webhooks.module.js'; + +@Module({ + imports: [ + ConfigModule, + PrismaModule, + StripeModule, + UsersModule, + GenerationsModule, + SubscriptionsModule, + WebhooksModule, + TilesModule, + RenderingModule, + HealthModule, + ], +}) +export class AppModule {} diff --git a/apps/prevision-api/src/app.setup.ts b/apps/prevision-api/src/app.setup.ts new file mode 100644 index 0000000000000000000000000000000000000000..99c5472348ad975d92bc8acadd4ea084ffc0b933 --- /dev/null +++ b/apps/prevision-api/src/app.setup.ts @@ -0,0 +1,28 @@ +import { type INestApplication, RequestMethod, ValidationPipe } from '@nestjs/common'; +import { HttpExceptionFilter } from './common/filters/http-exception.filter.js'; +import { ResponseInterceptor } from './common/interceptors/response.interceptor.js'; +import { APP_CONFIG, isOriginAllowed } from './config/app-config.js'; +import type { AppConfig } from './config/app-config.interface.js'; + +/** Shared by main.ts and the e2e tests. */ +export function setupApp(app: INestApplication): INestApplication { + const config = app.get(APP_CONFIG); + app.setGlobalPrefix('api', { + exclude: [ + { path: 'health', method: RequestMethod.GET }, + { path: 'ready', method: RequestMethod.GET }, + { path: 'internal/{*path}', method: RequestMethod.ALL }, + ], + }); + app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true })); + app.useGlobalInterceptors(new ResponseInterceptor()); + app.useGlobalFilters(new HttpExceptionFilter()); + app.enableCors({ + origin: (origin: string | undefined, done: (error: Error | null, allow?: boolean) => void) => + done(null, !origin || isOriginAllowed(config, origin)), + methods: ['GET', 'POST'], + allowedHeaders: ['Authorization', 'Content-Type'], + maxAge: 600, + }); + return app; +} diff --git a/apps/prevision-api/src/catalog/catalog.module.ts b/apps/prevision-api/src/catalog/catalog.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..1fa1fbcad1dfa1fcbb3ee78ac0d34fd8b0f998ae --- /dev/null +++ b/apps/prevision-api/src/catalog/catalog.module.ts @@ -0,0 +1,11 @@ +import { Module } from '@nestjs/common'; +import { ConfigModule } from '../config/config.module.js'; +import { PrismaModule } from '../prisma/prisma.module.js'; +import { CatalogService } from './catalog.service.js'; + +@Module({ + imports: [ConfigModule, PrismaModule], + providers: [CatalogService], + exports: [CatalogService], +}) +export class CatalogModule {} diff --git a/apps/prevision-api/src/catalog/catalog.service.ts b/apps/prevision-api/src/catalog/catalog.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..322f9485c330152638432726f87d8567490629e4 --- /dev/null +++ b/apps/prevision-api/src/catalog/catalog.service.ts @@ -0,0 +1,38 @@ +import { Injectable } from '@nestjs/common'; +import { readFile } from 'node:fs/promises'; +import { PrismaService } from '../prisma/prisma.service.js'; +import type { CatalogEntry } from './interfaces/catalog-entry.interface.js'; + +export const CATALOG_PATH = new URL('../../prisma/catalog.json', import.meta.url); + +@Injectable() +export class CatalogService { + constructor(private readonly prisma: PrismaService) {} + + async load(path: URL | string = CATALOG_PATH): Promise { + return (JSON.parse(await readFile(path, 'utf8')) as { tiles: CatalogEntry[] }).tiles; + } + + /** + * Inserts new tiles and refreshes existing ones in one statement. Entries without an + * image are skipped, and a soft-deleted tile is never brought back. + */ + async seed(entries: CatalogEntry[]): Promise { + const rows = entries.filter((entry) => entry.imageUrl); + if (!rows.length) return 0; + return this.prisma.db.$executeRaw` + INSERT INTO tiles (id, slug, name, collection, surfaces, width_mm, height_mm, + image_url, thumbnail_url, assets, render, position, updated_at) + SELECT gen_random_uuid(), slug, name, collection, surfaces, "widthMm", "heightMm", + "imageUrl", "thumbnailUrl", coalesce(assets, '{}'), coalesce(render, '{}'), position, now() + FROM jsonb_to_recordset(${JSON.stringify(rows)}::jsonb) AS entry( + slug text, name text, collection text, surfaces varchar(20)[], "widthMm" int, "heightMm" int, + "imageUrl" text, "thumbnailUrl" text, assets jsonb, render jsonb, position int) + ON CONFLICT (slug) DO UPDATE SET + name = excluded.name, collection = excluded.collection, + surfaces = excluded.surfaces, width_mm = excluded.width_mm, height_mm = excluded.height_mm, + image_url = excluded.image_url, thumbnail_url = excluded.thumbnail_url, + assets = excluded.assets, render = excluded.render, position = excluded.position, updated_at = now() + WHERE tiles.deleted_at IS NULL`; + } +} diff --git a/apps/prevision-api/src/catalog/interfaces/catalog-entry.interface.ts b/apps/prevision-api/src/catalog/interfaces/catalog-entry.interface.ts new file mode 100644 index 0000000000000000000000000000000000000000..dc347ee3e4816de258d8e909f8cd0971c7380ee1 --- /dev/null +++ b/apps/prevision-api/src/catalog/interfaces/catalog-entry.interface.ts @@ -0,0 +1,13 @@ +export interface CatalogEntry { + slug: string; + name: string; + collection: string | null; + surfaces: string[]; + widthMm: number | null; + heightMm: number | null; + position: number | null; + imageUrl: string | null; + thumbnailUrl: string | null; + assets: Record; + render: Record; +} diff --git a/apps/prevision-api/src/clerk/clerk.module.ts b/apps/prevision-api/src/clerk/clerk.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..bd5fb1fb72d9430afcaf09902d65776760773e41 --- /dev/null +++ b/apps/prevision-api/src/clerk/clerk.module.ts @@ -0,0 +1,8 @@ +import { Module } from '@nestjs/common'; +import { ClerkService } from './clerk.service.js'; + +@Module({ + providers: [ClerkService], + exports: [ClerkService], +}) +export class ClerkModule {} diff --git a/apps/prevision-api/src/clerk/clerk.service.spec.ts b/apps/prevision-api/src/clerk/clerk.service.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..597915e3042a99ad3b437a8bedbe7cccc268d8a3 --- /dev/null +++ b/apps/prevision-api/src/clerk/clerk.service.spec.ts @@ -0,0 +1,41 @@ +import { createClerkClient, verifyToken } from '@clerk/backend'; +import { testConfig } from '../../test/support/test-config.js'; +import { ClerkService } from './clerk.service.js'; + +vi.mock('@clerk/backend', () => ({ verifyToken: vi.fn(), createClerkClient: vi.fn() })); + +const config = testConfig({ clerk: { secretKeys: ['sk_live_prod', 'sk_test_dev'] } }); +const getUser = { sk_live_prod: vi.fn(), sk_test_dev: vi.fn() }; + +describe('ClerkService', () => { + beforeEach(() => { + vi.mocked(createClerkClient).mockImplementation( + ({ secretKey }) => ({ users: { getUser: getUser[secretKey as keyof typeof getUser] } }) as never, + ); + }); + + it('accepts a token from any configured instance', async () => { + vi.mocked(verifyToken) + .mockRejectedValueOnce(new Error('kid not found')) + .mockResolvedValueOnce({ sub: 'user_1', sid: 'sess_1', azp: 'http://app.test' } as never); + await expect(new ClerkService(config).verifySessionToken('token')).resolves.toEqual({ userId: 'user_1', sessionId: 'sess_1' }); + expect(vi.mocked(verifyToken).mock.calls.map(([, options]) => options.secretKey)).toEqual(['sk_live_prod', 'sk_test_dev']); + }); + + it('refuses a token no instance signed, or from another origin', async () => { + vi.mocked(verifyToken).mockRejectedValue(new Error('invalid')); + await expect(new ClerkService(config).verifySessionToken('token')).rejects.toMatchObject({ status: 401 }); + vi.mocked(verifyToken).mockResolvedValue({ sub: 'user_1', sid: 'sess_1', azp: 'https://evil.test' } as never); + await expect(new ClerkService(config).verifySessionToken('token')).rejects.toMatchObject({ status: 401 }); + }); + + it('finds the user in whichever instance owns it', async () => { + getUser.sk_live_prod.mockRejectedValue(new Error('not found')); + getUser.sk_test_dev.mockResolvedValue({ + firstName: 'Ann', + lastName: null, + primaryEmailAddress: { emailAddress: 'Ann@Example.com ', verification: { status: 'verified' } }, + }); + await expect(new ClerkService(config).getVerifiedProfile('user_1')).resolves.toEqual({ email: 'ann@example.com', name: 'Ann' }); + }); +}); diff --git a/apps/prevision-api/src/clerk/clerk.service.ts b/apps/prevision-api/src/clerk/clerk.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..c2615c8dac9dcb8a4adbf50004875bc92756c359 --- /dev/null +++ b/apps/prevision-api/src/clerk/clerk.service.ts @@ -0,0 +1,62 @@ +import { Inject, Injectable, Logger } from '@nestjs/common'; +import { createClerkClient, verifyToken, type ClerkClient } from '@clerk/backend'; +import { AppException, unauthenticated } from '../common/exceptions/app.exception.js'; +import { APP_CONFIG, isOriginAllowed } from '../config/app-config.js'; +import type { AppConfig } from '../config/app-config.interface.js'; +import type { ClerkProfile, ClerkSession } from './interfaces/clerk.interface.js'; + +interface ClerkInstance { + secretKey: string; + client: ClerkClient; +} + +@Injectable() +export class ClerkService { + private readonly logger = new Logger(ClerkService.name); + private readonly instances: ClerkInstance[]; + + constructor(@Inject(APP_CONFIG) private readonly config: AppConfig) { + this.instances = config.clerk.secretKeys.map((secretKey) => ({ secretKey, client: createClerkClient({ secretKey }) })); + } + + /** Signature, expiry and `azp` (the frontend origin that requested the token). */ + async verifySessionToken(token: string): Promise { + const claims = await this.verifyWithAnyInstance(token); + if (!claims?.sub || !claims.sid || !isOriginAllowed(this.config, claims.azp)) throw unauthenticated(); + return { userId: claims.sub, sessionId: claims.sid }; + } + + async getVerifiedProfile(clerkUserId: string): Promise { + const user = await this.findUser(clerkUserId); + const email = user.primaryEmailAddress; + if (!email || email.verification?.status !== 'verified') { + throw new AppException(403, 'EMAIL_NOT_VERIFIED', 'Please verify your email address to continue.'); + } + const name = [user.firstName, user.lastName].filter(Boolean).join(' ').trim(); + return { email: email.emailAddress.trim().toLowerCase(), name: name || null }; + } + + private async verifyWithAnyInstance(token: string) { + for (const { secretKey } of this.instances) { + try { + return await verifyToken(token, { secretKey, jwtKey: this.config.clerk.jwtKey }); + } catch { + // Signed by another instance (or invalid); try the next one. + } + } + return null; + } + + private async findUser(clerkUserId: string) { + let failure: unknown; + for (const { client } of this.instances) { + try { + return await client.users.getUser(clerkUserId); + } catch (error) { + failure = error; + } + } + this.logger.error(`Clerk user lookup failed: ${failure instanceof Error ? failure.message : String(failure)}`); + throw new AppException(503, 'AUTH_UNAVAILABLE', 'Sign-in is temporarily unavailable. Please try again.'); + } +} diff --git a/apps/prevision-api/src/clerk/interfaces/clerk.interface.ts b/apps/prevision-api/src/clerk/interfaces/clerk.interface.ts new file mode 100644 index 0000000000000000000000000000000000000000..8dcade8a4f85ab0d036ead57e97b4ca543a65fbb --- /dev/null +++ b/apps/prevision-api/src/clerk/interfaces/clerk.interface.ts @@ -0,0 +1,9 @@ +export interface ClerkSession { + userId: string; + sessionId: string; +} + +export interface ClerkProfile { + email: string; + name: string | null; +} diff --git a/apps/prevision-api/src/common/dto/paginated.dto.ts b/apps/prevision-api/src/common/dto/paginated.dto.ts new file mode 100644 index 0000000000000000000000000000000000000000..8efea31503fb06390fa0554a5abed38737518590 --- /dev/null +++ b/apps/prevision-api/src/common/dto/paginated.dto.ts @@ -0,0 +1,15 @@ +import type { PaginationMeta } from '../interfaces/api-response.interface.js'; +import type { PaginationQueryDto } from './pagination-query.dto.js'; + +/** Returned by list endpoints; ResponseInterceptor turns it into `{ data, meta }`. */ +export class Paginated { + readonly meta: PaginationMeta; + + constructor( + readonly items: T[], + total: number, + { page, pageSize }: Pick, + ) { + this.meta = { page, pageSize, total, totalPages: Math.ceil(total / pageSize) }; + } +} diff --git a/apps/prevision-api/src/common/dto/pagination-query.dto.ts b/apps/prevision-api/src/common/dto/pagination-query.dto.ts new file mode 100644 index 0000000000000000000000000000000000000000..77303d876b5e6bf4042782ee800109b04ba47c64 --- /dev/null +++ b/apps/prevision-api/src/common/dto/pagination-query.dto.ts @@ -0,0 +1,22 @@ +import { Type } from 'class-transformer'; +import { IsInt, IsOptional, Max, Min } from 'class-validator'; + +export class PaginationQueryDto { + @IsOptional() + @Type(() => Number) + @IsInt() + @Min(1) + @Max(100_000) + page = 1; + + @IsOptional() + @Type(() => Number) + @IsInt() + @Min(1) + @Max(96) + pageSize = 24; + + get offset(): number { + return (this.page - 1) * this.pageSize; + } +} diff --git a/apps/prevision-api/src/common/exceptions/app.exception.ts b/apps/prevision-api/src/common/exceptions/app.exception.ts new file mode 100644 index 0000000000000000000000000000000000000000..586b8769a5f5f06f262091ded7699adbc9027c73 --- /dev/null +++ b/apps/prevision-api/src/common/exceptions/app.exception.ts @@ -0,0 +1,14 @@ +import { HttpException } from '@nestjs/common'; + +/** An error with a stable code the frontend can act on. */ +export class AppException extends HttpException { + constructor( + status: number, + readonly code: string, + message: string, + ) { + super(message, status); + } +} + +export const unauthenticated = () => new AppException(401, 'UNAUTHENTICATED', 'Please sign in to continue.'); diff --git a/apps/prevision-api/src/common/filters/http-exception.filter.spec.ts b/apps/prevision-api/src/common/filters/http-exception.filter.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..dcea2dab055273a497d15975db7f1cdb4bb5cfe1 --- /dev/null +++ b/apps/prevision-api/src/common/filters/http-exception.filter.spec.ts @@ -0,0 +1,37 @@ +import { BadRequestException, Logger, NotFoundException, type ArgumentsHost } from '@nestjs/common'; +import { AppException } from '../exceptions/app.exception.js'; +import { HttpExceptionFilter } from './http-exception.filter.js'; + +function respond(exception: unknown) { + const response = { status: vi.fn().mockReturnThis(), json: vi.fn() }; + const host = { switchToHttp: () => ({ getResponse: () => response }) } as unknown as ArgumentsHost; + new HttpExceptionFilter().catch(exception, host); + return { status: response.status.mock.calls[0][0], body: response.json.mock.calls[0][0] }; +} + +describe('HttpExceptionFilter', () => { + beforeAll(() => Logger.overrideLogger(false)); + + it('keeps the code of an AppException', () => { + expect(respond(new AppException(402, 'NO_FREE_TRIES', 'None left.'))).toEqual({ + status: 402, + body: { success: false, error: { code: 'NO_FREE_TRIES', message: 'None left.' } }, + }); + }); + + it('joins validation messages', () => { + const { status, body } = respond(new BadRequestException(['page must be an integer', 'q is too long'])); + expect(status).toBe(400); + expect(body.error).toEqual({ code: 'BAD_REQUEST', message: 'page must be an integer; q is too long' }); + }); + + it('maps other HTTP errors by status', () => { + expect(respond(new NotFoundException()).body.error.code).toBe('NOT_FOUND'); + }); + + it('hides unexpected errors', () => { + const { status, body } = respond(new Error('database password is wrong')); + expect(status).toBe(500); + expect(body.error).toEqual({ code: 'INTERNAL_ERROR', message: 'Something went wrong. Please try again.' }); + }); +}); diff --git a/apps/prevision-api/src/common/filters/http-exception.filter.ts b/apps/prevision-api/src/common/filters/http-exception.filter.ts new file mode 100644 index 0000000000000000000000000000000000000000..58cf0d0580facc6f28c1401309ddb1e615513cc1 --- /dev/null +++ b/apps/prevision-api/src/common/filters/http-exception.filter.ts @@ -0,0 +1,42 @@ +import { ArgumentsHost, Catch, ExceptionFilter, HttpException, Logger } from '@nestjs/common'; +import type { Response } from 'express'; +import { AppException } from '../exceptions/app.exception.js'; +import type { ApiFailure } from '../interfaces/api-response.interface.js'; + +const CODES: Record = { + 400: 'BAD_REQUEST', + 401: 'UNAUTHENTICATED', + 403: 'FORBIDDEN', + 404: 'NOT_FOUND', + 409: 'CONFLICT', + 429: 'RATE_LIMITED', + 503: 'SERVICE_UNAVAILABLE', +}; + +/** Every error becomes `{ success: false, error: { code, message } }`; unexpected ones are logged, never echoed. */ +@Catch() +export class HttpExceptionFilter implements ExceptionFilter { + private readonly logger = new Logger(HttpExceptionFilter.name); + + catch(exception: unknown, host: ArgumentsHost) { + const response = host.switchToHttp().getResponse(); + const [status, body] = this.toBody(exception); + response.status(status).json(body); + } + + private toBody(exception: unknown): [number, ApiFailure] { + if (exception instanceof AppException) { + return [exception.getStatus(), failure(exception.code, exception.message)]; + } + if (exception instanceof HttpException) { + const status = exception.getStatus(); + const detail = exception.getResponse(); + const message = typeof detail === 'object' && detail && 'message' in detail ? (detail as { message: unknown }).message : exception.message; + return [status, failure(CODES[status] ?? 'ERROR', Array.isArray(message) ? message.join('; ') : String(message))]; + } + this.logger.error(exception instanceof Error ? exception.stack : String(exception)); + return [500, failure('INTERNAL_ERROR', 'Something went wrong. Please try again.')]; + } +} + +const failure = (code: string, message: string): ApiFailure => ({ success: false, error: { code, message } }); diff --git a/apps/prevision-api/src/common/interceptors/response.interceptor.spec.ts b/apps/prevision-api/src/common/interceptors/response.interceptor.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..767b4486857659ea0118b9a1022449730e5590d2 --- /dev/null +++ b/apps/prevision-api/src/common/interceptors/response.interceptor.spec.ts @@ -0,0 +1,26 @@ +import { lastValueFrom, of } from 'rxjs'; +import type { CallHandler, ExecutionContext } from '@nestjs/common'; +import { Paginated } from '../dto/paginated.dto.js'; +import { ResponseInterceptor } from './response.interceptor.js'; + +const run = (body: unknown) => + lastValueFrom(new ResponseInterceptor().intercept({} as ExecutionContext, { handle: () => of(body) } as CallHandler)); + +describe('ResponseInterceptor', () => { + it('wraps a body in { success, data }', async () => { + expect(await run({ id: 1 })).toEqual({ success: true, data: { id: 1 } }); + }); + + it('turns a page into data plus pagination meta', async () => { + const page = new Paginated(['a', 'b'], 5, { page: 2, pageSize: 2 }); + expect(await run(page)).toEqual({ + success: true, + data: ['a', 'b'], + meta: { page: 2, pageSize: 2, total: 5, totalPages: 3 }, + }); + }); + + it('leaves empty responses empty', async () => { + expect(await run(undefined)).toBeUndefined(); + }); +}); diff --git a/apps/prevision-api/src/common/interceptors/response.interceptor.ts b/apps/prevision-api/src/common/interceptors/response.interceptor.ts new file mode 100644 index 0000000000000000000000000000000000000000..a7b5625067e9eaa2a56f57562e0ff1c91c8df85f --- /dev/null +++ b/apps/prevision-api/src/common/interceptors/response.interceptor.ts @@ -0,0 +1,18 @@ +import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common'; +import { map, type Observable } from 'rxjs'; +import { Paginated } from '../dto/paginated.dto.js'; +import type { ApiSuccess } from '../interfaces/api-response.interface.js'; + +/** Every successful response becomes `{ success: true, data, meta? }`; empty (204) responses stay empty. */ +@Injectable() +export class ResponseInterceptor implements NestInterceptor | undefined> { + intercept(_: ExecutionContext, next: CallHandler): Observable | undefined> { + return next.handle().pipe( + map((body) => { + if (body === undefined) return undefined; + if (body instanceof Paginated) return { success: true, data: body.items, meta: body.meta }; + return { success: true, data: body }; + }), + ); + } +} diff --git a/apps/prevision-api/src/common/interfaces/api-response.interface.ts b/apps/prevision-api/src/common/interfaces/api-response.interface.ts new file mode 100644 index 0000000000000000000000000000000000000000..1fee44c76a0dc7660d65fa038f3757c1307bebb1 --- /dev/null +++ b/apps/prevision-api/src/common/interfaces/api-response.interface.ts @@ -0,0 +1,17 @@ +export interface PaginationMeta { + page: number; + pageSize: number; + total: number; + totalPages: number; +} + +export interface ApiSuccess { + success: true; + data: T; + meta?: PaginationMeta; +} + +export interface ApiFailure { + success: false; + error: { code: string; message: string }; +} diff --git a/apps/prevision-api/src/common/utils/bearer-token.ts b/apps/prevision-api/src/common/utils/bearer-token.ts new file mode 100644 index 0000000000000000000000000000000000000000..5bfea24802c867f91753da47e4ae49baee458b9e --- /dev/null +++ b/apps/prevision-api/src/common/utils/bearer-token.ts @@ -0,0 +1,6 @@ +import type { Request } from 'express'; + +export function bearerToken(request: Request): string | null { + const [scheme, token] = (request.headers.authorization ?? '').split(' '); + return scheme?.toLowerCase() === 'bearer' && token?.trim() ? token.trim() : null; +} diff --git a/apps/prevision-api/src/config/app-config.interface.ts b/apps/prevision-api/src/config/app-config.interface.ts new file mode 100644 index 0000000000000000000000000000000000000000..01d4bfc9220e45fdd6aea34890792ea0311f5858 --- /dev/null +++ b/apps/prevision-api/src/config/app-config.interface.ts @@ -0,0 +1,39 @@ +export type Environment = 'development' | 'test' | 'staging' | 'production'; + +export interface AppConfig { + environment: Environment; + port: number; + databaseUrl: string; + allowedOrigins: string[]; + allowedOriginRegex: RegExp | null; + clerk: { + /** One per Clerk instance the API accepts, e.g. production and development. */ + secretKeys: string[]; + jwtKey?: string; + }; + processingToken: { + secret: string; + ttlSeconds: number; + audience: string; + issuer: string; + }; + internalTokenAudience: string; + /** Lifetime free generations for accounts without a subscription. */ + freeGenerations: number; + /** The Prevision site, for Stripe's success, cancel and portal return links. */ + appUrl: string; + stripe: StripeConfig; +} + +export type PlanId = 'starter' | 'growth'; + +export interface StripeConfig { + secretKey: string; + webhookSecret: string; + /** Stripe Price id and monthly generation allowance of each plan. */ + plans: Record; + /** Public URL of the logo shown on Stripe Checkout. Optional. */ + logoUrl?: string; + /** The branded billing portal configuration (bpc_...). Optional: Stripe's default otherwise. */ + portalConfigurationId?: string; +} diff --git a/apps/prevision-api/src/config/app-config.spec.ts b/apps/prevision-api/src/config/app-config.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..fbe7d4a8431d9d815807d6166936ee889c70d3ad --- /dev/null +++ b/apps/prevision-api/src/config/app-config.spec.ts @@ -0,0 +1,50 @@ +import { isOriginAllowed, loadConfig } from './app-config.js'; + +const base = { + PREVISION_DATABASE_URL: 'postgresql://u:p@db.test:5432/app', + CLERK_SECRET_KEY: 'sk_test_x', + PROCESSING_TOKEN_SECRET: 'x'.repeat(40), + STRIPE_SECRET_KEY: 'sk_test_x', + STRIPE_WEBHOOK_SECRET: 'whsec_x', + STRIPE_PRICE_STARTER: 'price_s', + STRIPE_PRICE_GROWTH: 'price_g', +}; + +describe('loadConfig', () => { + it('applies defaults', () => { + const config = loadConfig(base); + expect(config.port).toBe(8001); + expect(config.freeGenerations).toBe(10); + expect(config.processingToken).toMatchObject({ issuer: 'prevision-api', audience: 'prevision-processing', ttlSeconds: 600 }); + expect(config.stripe.plans).toEqual({ + starter: { priceId: 'price_s', monthlyGenerations: 150 }, + growth: { priceId: 'price_g', monthlyGenerations: 600 }, + }); + expect(config.appUrl).toBe('http://localhost:5173'); + }); + + it('accepts a comma-separated list of Clerk secret keys', () => { + expect(loadConfig({ ...base, CLERK_SECRET_KEY: 'sk_live_a, sk_test_b' }).clerk.secretKeys).toEqual(['sk_live_a', 'sk_test_b']); + expect(() => loadConfig({ ...base, ENVIRONMENT: 'staging', CLERK_SECRET_KEY: 'sk_live_a,pk_live_b' })).toThrow(/Clerk secret keys/); + }); + + it('matches exact origins and the preview regex', () => { + const config = loadConfig({ + ...base, + PREVISION_ALLOWED_ORIGINS: 'https://a.test/, https://b.test', + PREVISION_ALLOWED_ORIGIN_REGEX: '^https://prevision-[a-z0-9]+-team\\.vercel\\.app$', + }); + expect(isOriginAllowed(config, 'https://a.test')).toBe(true); + expect(isOriginAllowed(config, 'https://prevision-abc-team.vercel.app')).toBe(true); + expect(isOriginAllowed(config, 'https://prevision-abc-team.vercel.app.evil.test')).toBe(false); + expect(isOriginAllowed(config, undefined)).toBe(false); + }); + + it('refuses missing or weak settings', () => { + expect(() => loadConfig({})).toThrow(/PREVISION_DATABASE_URL is required.*CLERK_SECRET_KEY is required/); + expect(() => loadConfig({ ...base, ENVIRONMENT: 'staging', PROCESSING_TOKEN_SECRET: 'short' })).toThrow(/at least 32/); + expect(() => loadConfig({ ...base, FREE_GENERATIONS: 'many' })).toThrow(/whole number/); + expect(() => loadConfig({ ...base, STRIPE_PRICE_GROWTH: '' })).toThrow(/STRIPE_PRICE_GROWTH is required/); + expect(() => loadConfig({ ...base, ENVIRONMENT: 'staging', STRIPE_WEBHOOK_SECRET: 'nope' })).toThrow(/webhook signing secret/); + }); +}); diff --git a/apps/prevision-api/src/config/app-config.ts b/apps/prevision-api/src/config/app-config.ts new file mode 100644 index 0000000000000000000000000000000000000000..f3d9c50addc7a060f44fab6f7e6308a5fd7d56bb --- /dev/null +++ b/apps/prevision-api/src/config/app-config.ts @@ -0,0 +1,88 @@ +import type { AppConfig, Environment } from './app-config.interface.js'; + +export const APP_CONFIG = Symbol('APP_CONFIG'); + +const ENVIRONMENTS: Environment[] = ['development', 'test', 'staging', 'production']; + +export function loadConfig(env: NodeJS.ProcessEnv = process.env): AppConfig { + const problems: string[] = []; + const required = (name: string) => { + const value = env[name]?.trim(); + if (!value) problems.push(`${name} is required`); + return value ?? ''; + }; + const integer = (name: string, fallback: number) => { + const raw = env[name]?.trim(); + if (!raw) return fallback; + const value = Number(raw); + if (!Number.isInteger(value) || value < 0) problems.push(`${name} must be a whole number`); + return value; + }; + + const environment = (env.ENVIRONMENT ?? 'development') as Environment; + if (!ENVIRONMENTS.includes(environment)) problems.push(`ENVIRONMENT must be one of ${ENVIRONMENTS.join(', ')}`); + + let allowedOriginRegex: RegExp | null = null; + const regex = env.PREVISION_ALLOWED_ORIGIN_REGEX?.trim(); + if (regex) { + try { + allowedOriginRegex = new RegExp(`^(?:${regex.replace(/^\^|\$$/g, '')})$`); + } catch { + problems.push('PREVISION_ALLOWED_ORIGIN_REGEX is not a valid regular expression'); + } + } + + const config: AppConfig = { + environment, + port: integer('PREVISION_API_PORT', 8001), + databaseUrl: required('PREVISION_DATABASE_URL'), + allowedOrigins: (env.PREVISION_ALLOWED_ORIGINS ?? 'http://localhost:5173') + .split(',') + .map((origin) => origin.trim().replace(/\/$/, '')) + .filter(Boolean), + allowedOriginRegex, + clerk: { + secretKeys: required('CLERK_SECRET_KEY') + .split(',') + .map((key) => key.trim()) + .filter(Boolean), + jwtKey: env.CLERK_JWT_KEY?.trim() || undefined, + }, + processingToken: { + secret: required('PROCESSING_TOKEN_SECRET'), + ttlSeconds: integer('PROCESSING_TOKEN_TTL_SECONDS', 600), + audience: env.PROCESSING_TOKEN_AUDIENCE?.trim() || 'prevision-processing', + issuer: 'prevision-api', + }, + internalTokenAudience: 'prevision-internal', + freeGenerations: integer('FREE_GENERATIONS', 10), + appUrl: (env.PREVISION_APP_URL?.trim() || 'http://localhost:5173').replace(/\/$/, ''), + stripe: { + secretKey: required('STRIPE_SECRET_KEY'), + webhookSecret: required('STRIPE_WEBHOOK_SECRET'), + plans: { + starter: { priceId: required('STRIPE_PRICE_STARTER'), monthlyGenerations: integer('STARTER_MONTHLY_GENERATIONS', 150) }, + growth: { priceId: required('STRIPE_PRICE_GROWTH'), monthlyGenerations: integer('GROWTH_MONTHLY_GENERATIONS', 600) }, + }, + logoUrl: env.STRIPE_LOGO_URL?.trim() || undefined, + portalConfigurationId: env.STRIPE_PORTAL_CONFIGURATION_ID?.trim() || undefined, + }, + }; + + if (environment === 'staging' || environment === 'production') { + if (config.processingToken.secret.length < 32) problems.push('PROCESSING_TOKEN_SECRET must be at least 32 characters'); + if (config.allowedOrigins.some((origin) => origin.includes('*'))) problems.push('PREVISION_ALLOWED_ORIGINS must list exact origins'); + if (!config.clerk.secretKeys.every((key) => key.startsWith('sk_'))) problems.push('CLERK_SECRET_KEY must list Clerk secret keys'); + if (!/^(sk|rk)_/.test(config.stripe.secretKey)) problems.push('STRIPE_SECRET_KEY must be a Stripe secret key'); + if (!config.stripe.webhookSecret.startsWith('whsec_')) problems.push('STRIPE_WEBHOOK_SECRET must be a webhook signing secret'); + if (!config.appUrl.startsWith('https://')) problems.push('PREVISION_APP_URL must be an https URL'); + } + if (problems.length) throw new Error(`Invalid configuration: ${problems.join('; ')}`); + return config; +} + +export function isOriginAllowed(config: AppConfig, origin: string | null | undefined): boolean { + if (!origin) return false; + const normalized = origin.replace(/\/$/, ''); + return config.allowedOrigins.includes(normalized) || Boolean(config.allowedOriginRegex?.test(normalized)); +} diff --git a/apps/prevision-api/src/config/config.module.ts b/apps/prevision-api/src/config/config.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee6ed0b3f5d046cd9ff6c8894483117f9593c8bb --- /dev/null +++ b/apps/prevision-api/src/config/config.module.ts @@ -0,0 +1,9 @@ +import { Global, Module } from '@nestjs/common'; +import { APP_CONFIG, loadConfig } from './app-config.js'; + +@Global() +@Module({ + providers: [{ provide: APP_CONFIG, useFactory: () => loadConfig() }], + exports: [APP_CONFIG], +}) +export class ConfigModule {} diff --git a/apps/prevision-api/src/generations/allowance.spec.ts b/apps/prevision-api/src/generations/allowance.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..bea6b697b9be44e9048cc880a9d4bb88dfbeedc0 --- /dev/null +++ b/apps/prevision-api/src/generations/allowance.spec.ts @@ -0,0 +1,28 @@ +import { testConfig } from '../../test/support/test-config.js'; +import type { Subscription } from '../generated/prisma/client.js'; +import { allowanceFor } from './allowance.js'; + +const subscription = (plan: Subscription['plan']) => + ({ plan, currentPeriodStart: new Date('2026-10-01'), currentPeriodEnd: new Date('2026-11-01') }) as Subscription; + +describe('allowanceFor', () => { + const config = testConfig(); + + it('gives free accounts their lifetime tries', () => { + expect(allowanceFor('user', null, config)).toEqual({ plan: 'free', limit: 5, countFrom: null, renewsAt: null }); + }); + + it('gives subscribers their plan for the current billing period', () => { + expect(allowanceFor('user', subscription('starter'), config)).toEqual({ + plan: 'starter', + limit: 150, + countFrom: new Date('2026-10-01'), + renewsAt: new Date('2026-11-01'), + }); + expect(allowanceFor('user', subscription('growth'), config).limit).toBe(600); + }); + + it('never limits admins', () => { + expect(allowanceFor('admin', subscription('starter'), config)).toMatchObject({ plan: 'unlimited', limit: null }); + }); +}); diff --git a/apps/prevision-api/src/generations/allowance.ts b/apps/prevision-api/src/generations/allowance.ts new file mode 100644 index 0000000000000000000000000000000000000000..325430c4b2e7da78cd874f8b1d3bb52f77e37170 --- /dev/null +++ b/apps/prevision-api/src/generations/allowance.ts @@ -0,0 +1,17 @@ +import type { AppConfig } from '../config/app-config.interface.js'; +import { UserRole, type Subscription } from '../generated/prisma/client.js'; +import type { Allowance } from './interfaces/allowance.interface.js'; + +/** Admins: unlimited. Subscribers: the plan's monthly allowance. Everyone else: the lifetime free tries. */ +export function allowanceFor(role: UserRole, subscription: Subscription | null, config: AppConfig): Allowance { + if (role === UserRole.admin) return { plan: 'unlimited', limit: null, countFrom: null, renewsAt: null }; + if (subscription) { + return { + plan: subscription.plan, + limit: config.stripe.plans[subscription.plan].monthlyGenerations, + countFrom: subscription.currentPeriodStart, + renewsAt: subscription.currentPeriodEnd, + }; + } + return { plan: 'free', limit: config.freeGenerations, countFrom: null, renewsAt: null }; +} diff --git a/apps/prevision-api/src/generations/dto/create-generation.dto.ts b/apps/prevision-api/src/generations/dto/create-generation.dto.ts new file mode 100644 index 0000000000000000000000000000000000000000..ddcc954a745a4c40671a0abcfd5105a7d4e2b471 --- /dev/null +++ b/apps/prevision-api/src/generations/dto/create-generation.dto.ts @@ -0,0 +1,11 @@ +import { IsString, IsUUID, Matches, MaxLength } from 'class-validator'; + +export class CreateGenerationDto { + @IsUUID() + userId: string; + + @IsString() + @MaxLength(64) + @Matches(/^[A-Za-z0-9_-]+$/) + jobId: string; +} diff --git a/apps/prevision-api/src/generations/dto/generation-created.dto.ts b/apps/prevision-api/src/generations/dto/generation-created.dto.ts new file mode 100644 index 0000000000000000000000000000000000000000..791ec85cdab0b73579b671d62d8a99a970789ba9 --- /dev/null +++ b/apps/prevision-api/src/generations/dto/generation-created.dto.ts @@ -0,0 +1,6 @@ +import { UsageDto } from './usage.dto.js'; + +export class GenerationCreatedDto { + generationId: string; + usage: UsageDto; +} diff --git a/apps/prevision-api/src/generations/dto/usage.dto.ts b/apps/prevision-api/src/generations/dto/usage.dto.ts new file mode 100644 index 0000000000000000000000000000000000000000..486458d6a4465058784cf52c40173e53c1e70709 --- /dev/null +++ b/apps/prevision-api/src/generations/dto/usage.dto.ts @@ -0,0 +1,10 @@ +import type { AllowancePlan } from '../interfaces/allowance.interface.js'; + +/** Generations used against the current allowance. `limit` and `remaining` are null when unlimited. */ +export class UsageDto { + plan: AllowancePlan; + limit: number | null; + used: number; + remaining: number | null; + renewsAt: Date | null; +} diff --git a/apps/prevision-api/src/generations/generations.controller.ts b/apps/prevision-api/src/generations/generations.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..2a4db878fe369c286dd4f99d174d639caa6810a3 --- /dev/null +++ b/apps/prevision-api/src/generations/generations.controller.ts @@ -0,0 +1,23 @@ +import { Body, Controller, HttpCode, Param, ParseUUIDPipe, Post, UseGuards } from '@nestjs/common'; +import { CreateGenerationDto } from './dto/create-generation.dto.js'; +import type { GenerationCreatedDto } from './dto/generation-created.dto.js'; +import { GenerationsService } from './generations.service.js'; +import { InternalTokenGuard } from './guards/internal-token.guard.js'; + +/** Called by the renderer; outside /api, so the frontend proxy never reaches it. */ +@Controller('internal/generations') +@UseGuards(InternalTokenGuard) +export class GenerationsController { + constructor(private readonly generations: GenerationsService) {} + + @Post() + create(@Body() { userId, jobId }: CreateGenerationDto): Promise { + return this.generations.create(userId, jobId); + } + + @Post(':id/refund') + @HttpCode(204) + refund(@Param('id', ParseUUIDPipe) id: string): Promise { + return this.generations.refund(id); + } +} diff --git a/apps/prevision-api/src/generations/generations.module.ts b/apps/prevision-api/src/generations/generations.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..97b3c662a86c9a4ddb56acdf83015a35303729a9 --- /dev/null +++ b/apps/prevision-api/src/generations/generations.module.ts @@ -0,0 +1,11 @@ +import { Module } from '@nestjs/common'; +import { GenerationsController } from './generations.controller.js'; +import { GenerationsService } from './generations.service.js'; +import { InternalTokenGuard } from './guards/internal-token.guard.js'; + +@Module({ + controllers: [GenerationsController], + providers: [GenerationsService, InternalTokenGuard], + exports: [GenerationsService], +}) +export class GenerationsModule {} diff --git a/apps/prevision-api/src/generations/generations.service.spec.ts b/apps/prevision-api/src/generations/generations.service.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..761a6be416d2ba9491c9e4a96cab69cd588adce6 --- /dev/null +++ b/apps/prevision-api/src/generations/generations.service.spec.ts @@ -0,0 +1,87 @@ +import { Test } from '@nestjs/testing'; +import { testConfig } from '../../test/support/test-config.js'; +import { APP_CONFIG } from '../config/app-config.js'; +import { PrismaService } from '../prisma/prisma.service.js'; +import { GenerationsService } from './generations.service.js'; + +describe('GenerationsService', () => { + const period = { plan: 'starter', currentPeriodStart: new Date('2026-10-01'), currentPeriodEnd: new Date('2026-11-01') }; + const tx = { $queryRaw: vi.fn(), subscription: { findFirst: vi.fn() }, generation: { count: vi.fn(), create: vi.fn() } }; + const db = { + $transaction: vi.fn((work: (client: typeof tx) => unknown) => work(tx)), + subscription: { findFirst: vi.fn() }, + generation: { count: vi.fn(), updateMany: vi.fn() }, + }; + let service: GenerationsService; + + beforeEach(async () => { + vi.clearAllMocks(); + db.subscription.findFirst.mockResolvedValue(null); + tx.subscription.findFirst.mockResolvedValue(null); + const moduleRef = await Test.createTestingModule({ + providers: [GenerationsService, { provide: PrismaService, useValue: { db } }, { provide: APP_CONFIG, useValue: testConfig() }], + }).compile(); + service = moduleRef.get(GenerationsService); + }); + + it('counts all-time generations for free accounts', async () => { + db.generation.count.mockResolvedValue(2); + expect(await service.usage({ id: 'u1', role: 'user' })).toEqual({ plan: 'free', limit: 5, used: 2, remaining: 3, renewsAt: null }); + expect(db.generation.count).toHaveBeenCalledWith({ where: { userId: 'u1', refundedAt: null } }); + }); + + it('counts only this billing period for subscribers', async () => { + db.subscription.findFirst.mockResolvedValue(period); + db.generation.count.mockResolvedValue(10); + expect(await service.usage({ id: 'u1', role: 'user' })).toEqual({ + plan: 'starter', + limit: 150, + used: 10, + remaining: 140, + renewsAt: period.currentPeriodEnd, + }); + expect(db.generation.count).toHaveBeenCalledWith({ where: { userId: 'u1', refundedAt: null, createdAt: { gte: period.currentPeriodStart } } }); + }); + + it('records a generation while tries remain', async () => { + tx.$queryRaw.mockResolvedValue([{ role: 'user' }]); + tx.generation.count.mockResolvedValue(4); + tx.generation.create.mockResolvedValue({ id: 'g1' }); + expect(await service.create('u1', 'job-1')).toEqual({ + generationId: 'g1', + usage: { plan: 'free', limit: 5, used: 5, remaining: 0, renewsAt: null }, + }); + expect(tx.generation.create).toHaveBeenCalledWith({ data: { userId: 'u1', jobId: 'job-1' } }); + }); + + it('answers 402 NO_FREE_TRIES once the free tries are used', async () => { + tx.$queryRaw.mockResolvedValue([{ role: 'user' }]); + tx.generation.count.mockResolvedValue(5); + await expect(service.create('u1', 'job-6')).rejects.toMatchObject({ code: 'NO_FREE_TRIES', status: 402 }); + expect(tx.generation.create).not.toHaveBeenCalled(); + }); + + it('answers 402 PLAN_LIMIT_REACHED at a plan limit', async () => { + tx.$queryRaw.mockResolvedValue([{ role: 'user' }]); + tx.subscription.findFirst.mockResolvedValue(period); + tx.generation.count.mockResolvedValue(150); + await expect(service.create('u1', 'job-151')).rejects.toMatchObject({ code: 'PLAN_LIMIT_REACHED', status: 402 }); + }); + + it('never limits admins', async () => { + tx.$queryRaw.mockResolvedValue([{ role: 'admin' }]); + tx.generation.count.mockResolvedValue(40); + tx.generation.create.mockResolvedValue({ id: 'g41' }); + expect((await service.create('admin', 'job-41')).usage).toEqual({ plan: 'unlimited', limit: null, used: 41, remaining: null, renewsAt: null }); + }); + + it('refuses unknown or deleted users', async () => { + tx.$queryRaw.mockResolvedValue([]); + await expect(service.create('gone', 'job-1')).rejects.toMatchObject({ status: 403 }); + }); + + it('refunds only generations that are not refunded yet', async () => { + await service.refund('g1'); + expect(db.generation.updateMany).toHaveBeenCalledWith({ where: { id: 'g1', refundedAt: null }, data: { refundedAt: expect.any(Date) } }); + }); +}); diff --git a/apps/prevision-api/src/generations/generations.service.ts b/apps/prevision-api/src/generations/generations.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..ed480e5dca0fa0f06ac696a6e4727a20211c78fa --- /dev/null +++ b/apps/prevision-api/src/generations/generations.service.ts @@ -0,0 +1,71 @@ +import { Inject, Injectable } from '@nestjs/common'; +import { AppException } from '../common/exceptions/app.exception.js'; +import { APP_CONFIG } from '../config/app-config.js'; +import type { AppConfig } from '../config/app-config.interface.js'; +import type { Prisma, User, UserRole } from '../generated/prisma/client.js'; +import { PrismaService } from '../prisma/prisma.service.js'; +import { activeSubscriptionWhere } from '../subscriptions/active-subscription.js'; +import { allowanceFor } from './allowance.js'; +import type { GenerationCreatedDto } from './dto/generation-created.dto.js'; +import type { UsageDto } from './dto/usage.dto.js'; +import type { Allowance } from './interfaces/allowance.interface.js'; + +type Db = Pick; + +@Injectable() +export class GenerationsService { + constructor( + private readonly prisma: PrismaService, + @Inject(APP_CONFIG) private readonly config: AppConfig, + ) {} + + async usage(user: Pick): Promise { + const allowance = await this.allowance(this.prisma.db, user.id, user.role); + return this.toUsage(allowance, await this.used(this.prisma.db, user.id, allowance)); + } + + /** + * Records a job the renderer is about to accept, against the user's allowance. + * The user row lock serializes concurrent jobs, so the limit can't be passed. + */ + async create(userId: string, jobId: string): Promise { + return this.prisma.db.$transaction(async (tx) => { + const [user] = await tx.$queryRaw<{ role: UserRole }[]>` + SELECT role FROM users WHERE id = ${userId}::uuid AND deleted_at IS NULL FOR UPDATE`; + if (!user) throw new AppException(403, 'FORBIDDEN', 'This account cannot create visualizations.'); + const allowance = await this.allowance(tx, userId, user.role); + const used = await this.used(tx, userId, allowance); + if (allowance.limit !== null && used >= allowance.limit) throw limitReached(allowance); + const generation = await tx.generation.create({ data: { userId, jobId } }); + return { generationId: generation.id, usage: this.toUsage(allowance, used + 1) }; + }); + } + + /** Gives the try back after a failed job. Repeating it changes nothing. */ + async refund(generationId: string): Promise { + await this.prisma.db.generation.updateMany({ + where: { id: generationId, refundedAt: null }, + data: { refundedAt: new Date() }, + }); + } + + private async allowance(db: Db, userId: string, role: UserRole): Promise { + const subscription = await db.subscription.findFirst({ where: activeSubscriptionWhere(userId), orderBy: { currentPeriodEnd: 'desc' } }); + return allowanceFor(role, subscription, this.config); + } + + private used(db: Db, userId: string, allowance: Allowance): Promise { + const where: Prisma.GenerationWhereInput = { userId, refundedAt: null }; + if (allowance.countFrom) where.createdAt = { gte: allowance.countFrom }; + return db.generation.count({ where }); + } + + private toUsage({ plan, limit, renewsAt }: Allowance, used: number): UsageDto { + return { plan, limit, used, remaining: limit === null ? null : Math.max(0, limit - used), renewsAt }; + } +} + +const limitReached = (allowance: Allowance) => + allowance.plan === 'free' + ? new AppException(402, 'NO_FREE_TRIES', "You've used all your free visualizations.") + : new AppException(402, 'PLAN_LIMIT_REACHED', "You've used this month's visualizations. They renew with your plan."); diff --git a/apps/prevision-api/src/generations/guards/internal-token.guard.spec.ts b/apps/prevision-api/src/generations/guards/internal-token.guard.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..59e6e7cc26a062b5d3e21d5b29995606916027fc --- /dev/null +++ b/apps/prevision-api/src/generations/guards/internal-token.guard.spec.ts @@ -0,0 +1,30 @@ +import type { ExecutionContext } from '@nestjs/common'; +import { SignJWT } from 'jose'; +import type { AppConfig } from '../../config/app-config.interface.js'; +import { InternalTokenGuard } from './internal-token.guard.js'; + +const SECRET = 'test-processing-secret-0123456789abcdef012'; +const guard = new InternalTokenGuard({ processingToken: { secret: SECRET }, internalTokenAudience: 'prevision-internal' } as AppConfig); + +const sign = (audience: string, expiresIn = 60) => { + const now = Math.floor(Date.now() / 1000); + return new SignJWT({}).setProtectedHeader({ alg: 'HS256' }).setAudience(audience).setIssuedAt(now).setExpirationTime(now + expiresIn).sign(new TextEncoder().encode(SECRET)); +}; +const check = (token?: string) => + guard.canActivate({ + switchToHttp: () => ({ getRequest: () => ({ headers: token ? { authorization: `Bearer ${token}` } : {} }) }), + } as ExecutionContext); + +describe('InternalTokenGuard', () => { + it('accepts the renderer token', async () => { + expect(await check(await sign('prevision-internal'))).toBe(true); + }); + + it.each([ + ['missing', async () => undefined], + ['browser processing token', () => sign('prevision-processing')], + ['expired', () => sign('prevision-internal', -120)], + ])('refuses a %s token', async (_, token) => { + await expect(check(await token())).rejects.toMatchObject({ status: 401 }); + }); +}); diff --git a/apps/prevision-api/src/generations/guards/internal-token.guard.ts b/apps/prevision-api/src/generations/guards/internal-token.guard.ts new file mode 100644 index 0000000000000000000000000000000000000000..c36e4766439811789a212c4ad484c8a4eb60904d --- /dev/null +++ b/apps/prevision-api/src/generations/guards/internal-token.guard.ts @@ -0,0 +1,32 @@ +import { CanActivate, ExecutionContext, Inject, Injectable } from '@nestjs/common'; +import type { Request } from 'express'; +import { jwtVerify } from 'jose'; +import { unauthenticated } from '../../common/exceptions/app.exception.js'; +import { bearerToken } from '../../common/utils/bearer-token.js'; +import { APP_CONFIG } from '../../config/app-config.js'; +import type { AppConfig } from '../../config/app-config.interface.js'; + +/** The renderer in the same pod: a short HS256 token for the internal audience (never a browser token). */ +@Injectable() +export class InternalTokenGuard implements CanActivate { + private readonly key: Uint8Array; + + constructor(@Inject(APP_CONFIG) private readonly config: AppConfig) { + this.key = new TextEncoder().encode(config.processingToken.secret); + } + + async canActivate(context: ExecutionContext): Promise { + const token = bearerToken(context.switchToHttp().getRequest()); + if (!token) throw unauthenticated(); + try { + await jwtVerify(token, this.key, { + algorithms: ['HS256'], + audience: this.config.internalTokenAudience, + requiredClaims: ['exp', 'iat'], + }); + } catch { + throw unauthenticated(); + } + return true; + } +} diff --git a/apps/prevision-api/src/generations/interfaces/allowance.interface.ts b/apps/prevision-api/src/generations/interfaces/allowance.interface.ts new file mode 100644 index 0000000000000000000000000000000000000000..341be1eeb1f6adcfd04708a3320f23759e0f9c61 --- /dev/null +++ b/apps/prevision-api/src/generations/interfaces/allowance.interface.ts @@ -0,0 +1,11 @@ +export type AllowancePlan = 'free' | 'starter' | 'growth' | 'unlimited'; + +export interface Allowance { + plan: AllowancePlan; + /** null = unlimited. */ + limit: number | null; + /** Generations since this date count against the limit (null = all time). */ + countFrom: Date | null; + /** When a subscription's allowance renews. */ + renewsAt: Date | null; +} diff --git a/apps/prevision-api/src/health/health.controller.ts b/apps/prevision-api/src/health/health.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..14da14cb88253473928b4ea613fc20e25b97512e --- /dev/null +++ b/apps/prevision-api/src/health/health.controller.ts @@ -0,0 +1,22 @@ +import { Controller, Get, ServiceUnavailableException } from '@nestjs/common'; +import { PrismaService } from '../prisma/prisma.service.js'; + +@Controller() +export class HealthController { + constructor(private readonly prisma: PrismaService) {} + + @Get('health') + health() { + return { status: 'ok' }; + } + + @Get('ready') + async ready() { + try { + await this.prisma.db.$queryRaw`SELECT 1`; + } catch { + throw new ServiceUnavailableException('Database is unavailable.'); + } + return { status: 'ready' }; + } +} diff --git a/apps/prevision-api/src/health/health.module.ts b/apps/prevision-api/src/health/health.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..4bc65273f0e943e291b712774fa14a69e42d816e --- /dev/null +++ b/apps/prevision-api/src/health/health.module.ts @@ -0,0 +1,5 @@ +import { Module } from '@nestjs/common'; +import { HealthController } from './health.controller.js'; + +@Module({ controllers: [HealthController] }) +export class HealthModule {} diff --git a/apps/prevision-api/src/main.ts b/apps/prevision-api/src/main.ts new file mode 100644 index 0000000000000000000000000000000000000000..6d02e33f842b6c473f030f14d8f11ede4c9efad5 --- /dev/null +++ b/apps/prevision-api/src/main.ts @@ -0,0 +1,12 @@ +import 'dotenv/config'; +import { NestFactory } from '@nestjs/core'; +import { AppModule } from './app.module.js'; +import { setupApp } from './app.setup.js'; +import { APP_CONFIG } from './config/app-config.js'; +import type { AppConfig } from './config/app-config.interface.js'; + +// rawBody: Stripe webhook signatures are computed over the exact bytes received. +const app = setupApp(await NestFactory.create(AppModule, { rawBody: true })); +app.getHttpAdapter().getInstance().set('trust proxy', true); +app.enableShutdownHooks(); +await app.listen(app.get(APP_CONFIG).port, '0.0.0.0'); diff --git a/apps/prevision-api/src/prisma/connection-string.spec.ts b/apps/prevision-api/src/prisma/connection-string.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..91445a1672b3d937e9d924891717151aefd6df02 --- /dev/null +++ b/apps/prevision-api/src/prisma/connection-string.spec.ts @@ -0,0 +1,8 @@ +import { pgConnectionString } from './connection-string.js'; + +describe('pgConnectionString', () => { + it('keeps the libpq meaning of sslmode', () => { + expect(pgConnectionString('postgresql://u:p@h:5432/d?sslmode=require')).toContain('uselibpqcompat=true'); + expect(pgConnectionString('postgresql://u:p@h:5432/d')).not.toContain('uselibpqcompat'); + }); +}); \ No newline at end of file diff --git a/apps/prevision-api/src/prisma/connection-string.ts b/apps/prevision-api/src/prisma/connection-string.ts new file mode 100644 index 0000000000000000000000000000000000000000..93c04e0123d3fcb356b11d9961bff6833bb044f2 --- /dev/null +++ b/apps/prevision-api/src/prisma/connection-string.ts @@ -0,0 +1,11 @@ +/** + * node-postgres reads `sslmode=require` as "verify the certificate"; libpq (and the + * BAETES API) only require encryption. Keep the libpq meaning so both APIs share DATABASE_URL. + */ +export function pgConnectionString(url: string): string { + const parsed = new URL(url); + if (parsed.searchParams.has('sslmode') && !parsed.searchParams.has('uselibpqcompat')) { + parsed.searchParams.set('uselibpqcompat', 'true'); + } + return parsed.toString(); +} diff --git a/apps/prevision-api/src/prisma/prisma.module.ts b/apps/prevision-api/src/prisma/prisma.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..efb7a8dc0bb83ba5f2c99547abdd2c5023d1072d --- /dev/null +++ b/apps/prevision-api/src/prisma/prisma.module.ts @@ -0,0 +1,9 @@ +import { Global, Module } from '@nestjs/common'; +import { PrismaService } from './prisma.service.js'; + +@Global() +@Module({ + providers: [PrismaService], + exports: [PrismaService], +}) +export class PrismaModule {} diff --git a/apps/prevision-api/src/prisma/prisma.service.ts b/apps/prevision-api/src/prisma/prisma.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..a01587cfd9eecea8875f01f93f75646f366ca917 --- /dev/null +++ b/apps/prevision-api/src/prisma/prisma.service.ts @@ -0,0 +1,25 @@ +import { Inject, Injectable, OnModuleDestroy } from '@nestjs/common'; +import { PrismaPg } from '@prisma/adapter-pg'; +import { APP_CONFIG } from '../config/app-config.js'; +import type { AppConfig } from '../config/app-config.interface.js'; +import { PrismaClient } from '../generated/prisma/client.js'; +import { pgConnectionString } from './connection-string.js'; +import { softDelete } from './soft-delete.extension.js'; + +const createClient = (url: string) => + new PrismaClient({ adapter: new PrismaPg({ connectionString: pgConnectionString(url) }) }).$extends(softDelete); + +type Database = ReturnType; + +@Injectable() +export class PrismaService implements OnModuleDestroy { + readonly db: Database; + + constructor(@Inject(APP_CONFIG) config: AppConfig) { + this.db = createClient(config.databaseUrl); + } + + async onModuleDestroy() { + await this.db.$disconnect(); + } +} diff --git a/apps/prevision-api/src/prisma/soft-delete.extension.ts b/apps/prevision-api/src/prisma/soft-delete.extension.ts new file mode 100644 index 0000000000000000000000000000000000000000..2ec1a99bdc88f8863a2abb6de647d512186198f4 --- /dev/null +++ b/apps/prevision-api/src/prisma/soft-delete.extension.ts @@ -0,0 +1,30 @@ +import { Prisma } from '../generated/prisma/client.js'; + +const SCOPED_OPERATIONS = new Set([ + 'findUnique', + 'findUniqueOrThrow', + 'findFirst', + 'findFirstOrThrow', + 'findMany', + 'count', + 'update', + 'updateMany', +]); + +const SOFT_DELETE_MODELS = new Set(['User', 'Tile']); + +/** Users and tiles are never removed: queries skip soft-deleted rows unless they filter `deletedAt` themselves. */ +export const softDelete = Prisma.defineExtension({ + name: 'soft-delete', + query: { + $allModels: { + $allOperations({ model, operation, args, query }) { + if (SOFT_DELETE_MODELS.has(model) && SCOPED_OPERATIONS.has(operation)) { + const scoped = args as { where?: Record }; + scoped.where = { deletedAt: null, ...scoped.where }; + } + return query(args); + }, + }, + }, +}); diff --git a/apps/prevision-api/src/rendering/dto/processing-token.dto.ts b/apps/prevision-api/src/rendering/dto/processing-token.dto.ts new file mode 100644 index 0000000000000000000000000000000000000000..e4c428afed0dfe0c1232366403b4df2cc24360ab --- /dev/null +++ b/apps/prevision-api/src/rendering/dto/processing-token.dto.ts @@ -0,0 +1,4 @@ +export class ProcessingTokenDto { + token: string; + expiresAt: string; +} diff --git a/apps/prevision-api/src/rendering/processing-token.service.spec.ts b/apps/prevision-api/src/rendering/processing-token.service.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..088ca4e108abaf34e94e179233c78f5eb6d221a3 --- /dev/null +++ b/apps/prevision-api/src/rendering/processing-token.service.spec.ts @@ -0,0 +1,21 @@ +import { jwtVerify } from 'jose'; +import type { AppConfig } from '../config/app-config.interface.js'; +import { ProcessingTokenService } from './processing-token.service.js'; + +const SECRET = 'test-processing-secret-0123456789abcdef012'; + +describe('ProcessingTokenService', () => { + it('issues a renderer token for the account, marked as Prevision', async () => { + const service = new ProcessingTokenService({ + processingToken: { secret: SECRET, ttlSeconds: 600, audience: 'prevision-processing', issuer: 'prevision-api' }, + } as AppConfig); + const { token, expiresAt } = await service.issue('u1', 'sess_1'); + const { payload } = await jwtVerify(token, new TextEncoder().encode(SECRET), { + audience: 'prevision-processing', + issuer: 'prevision-api', + }); + expect(payload).toMatchObject({ sub: 'u1', sid: 'sess_1', role: 'client' }); + expect(payload.exp! - payload.iat!).toBe(600); + expect(new Date(expiresAt).getTime()).toBe(payload.exp! * 1000); + }); +}); diff --git a/apps/prevision-api/src/rendering/processing-token.service.ts b/apps/prevision-api/src/rendering/processing-token.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..686b9671d6a69500c2e5aefb3745b0ce812f0943 --- /dev/null +++ b/apps/prevision-api/src/rendering/processing-token.service.ts @@ -0,0 +1,32 @@ +import { Inject, Injectable } from '@nestjs/common'; +import { randomUUID } from 'node:crypto'; +import { SignJWT } from 'jose'; +import { APP_CONFIG } from '../config/app-config.js'; +import type { AppConfig } from '../config/app-config.interface.js'; +import type { ProcessingTokenDto } from './dto/processing-token.dto.js'; + +/** Short-lived token the renderer verifies with the shared secret; the issuer marks jobs as Prevision's. */ +@Injectable() +export class ProcessingTokenService { + private readonly key: Uint8Array; + + constructor(@Inject(APP_CONFIG) private readonly config: AppConfig) { + this.key = new TextEncoder().encode(config.processingToken.secret); + } + + async issue(userId: string, sessionId: string): Promise { + const { audience, issuer, ttlSeconds } = this.config.processingToken; + const now = Math.floor(Date.now() / 1000); + const token = await new SignJWT({ role: 'client', sid: sessionId }) + .setProtectedHeader({ alg: 'HS256' }) + .setIssuer(issuer) + .setAudience(audience) + .setSubject(userId) + .setIssuedAt(now) + .setNotBefore(now) + .setExpirationTime(now + ttlSeconds) + .setJti(randomUUID()) + .sign(this.key); + return { token, expiresAt: new Date((now + ttlSeconds) * 1000).toISOString() }; + } +} diff --git a/apps/prevision-api/src/rendering/rendering.controller.ts b/apps/prevision-api/src/rendering/rendering.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..23fc71b0cf168559f9a8ae78ef3636078663789f --- /dev/null +++ b/apps/prevision-api/src/rendering/rendering.controller.ts @@ -0,0 +1,18 @@ +import { Controller, HttpCode, Post, UseGuards } from '@nestjs/common'; +import { CurrentAuth } from '../users/decorators/current-auth.decorator.js'; +import { ClerkAuthGuard } from '../users/guards/clerk-auth.guard.js'; +import type { AuthContext } from '../users/interfaces/authenticated-request.interface.js'; +import type { ProcessingTokenDto } from './dto/processing-token.dto.js'; +import { ProcessingTokenService } from './processing-token.service.js'; + +@Controller('processing-token') +@UseGuards(ClerkAuthGuard) +export class RenderingController { + constructor(private readonly tokens: ProcessingTokenService) {} + + @Post() + @HttpCode(200) + issue(@CurrentAuth() { user, sessionId }: AuthContext): Promise { + return this.tokens.issue(user.id, sessionId); + } +} diff --git a/apps/prevision-api/src/rendering/rendering.module.ts b/apps/prevision-api/src/rendering/rendering.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..fb2faa66e99961e173cd6b64f9d0d85378efec42 --- /dev/null +++ b/apps/prevision-api/src/rendering/rendering.module.ts @@ -0,0 +1,11 @@ +import { Module } from '@nestjs/common'; +import { UsersModule } from '../users/users.module.js'; +import { ProcessingTokenService } from './processing-token.service.js'; +import { RenderingController } from './rendering.controller.js'; + +@Module({ + imports: [UsersModule], + controllers: [RenderingController], + providers: [ProcessingTokenService], +}) +export class RenderingModule {} diff --git a/apps/prevision-api/src/scripts/seed-catalog.ts b/apps/prevision-api/src/scripts/seed-catalog.ts new file mode 100644 index 0000000000000000000000000000000000000000..366bb685bbdc09fd9a42c177aa95c59e21925e16 --- /dev/null +++ b/apps/prevision-api/src/scripts/seed-catalog.ts @@ -0,0 +1,9 @@ +import 'dotenv/config'; +import { NestFactory } from '@nestjs/core'; +import { CatalogModule } from '../catalog/catalog.module.js'; +import { CatalogService } from '../catalog/catalog.service.js'; + +const app = await NestFactory.createApplicationContext(CatalogModule, { logger: ['error'] }); +const catalog = app.get(CatalogService); +console.log(`catalog: ${await catalog.seed(await catalog.load())} tiles inserted or updated`); +await app.close(); diff --git a/apps/prevision-api/src/scripts/set-user-role.ts b/apps/prevision-api/src/scripts/set-user-role.ts new file mode 100644 index 0000000000000000000000000000000000000000..ed9497ee8bbe22816cd5fc6079aab577b9909d29 --- /dev/null +++ b/apps/prevision-api/src/scripts/set-user-role.ts @@ -0,0 +1,28 @@ +import 'dotenv/config'; +import { Module } from '@nestjs/common'; +import { NestFactory } from '@nestjs/core'; +import { ConfigModule } from '../config/config.module.js'; +import { UserRole } from '../generated/prisma/client.js'; +import { PrismaModule } from '../prisma/prisma.module.js'; +import { UsersModule } from '../users/users.module.js'; +import { UsersService } from '../users/users.service.js'; + +const [email, role] = process.argv.slice(2); +if (!email || !(role in UserRole)) { + console.error('Usage: pnpm user:role '); + process.exit(1); +} + +@Module({ imports: [ConfigModule, PrismaModule, UsersModule] }) +class SetUserRoleModule {} + +const app = await NestFactory.createApplicationContext(SetUserRoleModule, { logger: ['error'] }); +try { + const user = await app.get(UsersService).setRole(email, role as UserRole); + console.log(`${user.email} is now ${user.role}`); +} catch (error) { + console.error(error instanceof Error ? error.message : error); + process.exitCode = 1; +} finally { + await app.close(); +} diff --git a/apps/prevision-api/src/stripe/stripe.constants.ts b/apps/prevision-api/src/stripe/stripe.constants.ts new file mode 100644 index 0000000000000000000000000000000000000000..1854f8d4cdd383b0aef9611be7400cdb9690226b --- /dev/null +++ b/apps/prevision-api/src/stripe/stripe.constants.ts @@ -0,0 +1 @@ +export const STRIPE_CLIENT = Symbol('STRIPE_CLIENT'); diff --git a/apps/prevision-api/src/stripe/stripe.module.ts b/apps/prevision-api/src/stripe/stripe.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..1ba37c187c9066a364e1dc0bbd1b93494555ac9e --- /dev/null +++ b/apps/prevision-api/src/stripe/stripe.module.ts @@ -0,0 +1,18 @@ +import { Global, Module } from '@nestjs/common'; +import Stripe from 'stripe'; +import { APP_CONFIG } from '../config/app-config.js'; +import type { AppConfig } from '../config/app-config.interface.js'; +import { STRIPE_CLIENT } from './stripe.constants.js'; + +@Global() +@Module({ + providers: [ + { + provide: STRIPE_CLIENT, + inject: [APP_CONFIG], + useFactory: (config: AppConfig) => new Stripe(config.stripe.secretKey, { maxNetworkRetries: 2, appInfo: { name: 'prevision-api' } }), + }, + ], + exports: [STRIPE_CLIENT], +}) +export class StripeModule {} diff --git a/apps/prevision-api/src/subscriptions/active-subscription.ts b/apps/prevision-api/src/subscriptions/active-subscription.ts new file mode 100644 index 0000000000000000000000000000000000000000..5d4368003bb9d5f84cd01ead7de82d39889653d0 --- /dev/null +++ b/apps/prevision-api/src/subscriptions/active-subscription.ts @@ -0,0 +1,8 @@ +import { Prisma } from '../generated/prisma/client.js'; + +/** A subscription that currently grants its plan's allowance. */ +export const activeSubscriptionWhere = (userId: string, now = new Date()): Prisma.SubscriptionWhereInput => ({ + userId, + status: { in: ['active', 'trialing'] }, + currentPeriodEnd: { gt: now }, +}); diff --git a/apps/prevision-api/src/subscriptions/dto/create-checkout.dto.ts b/apps/prevision-api/src/subscriptions/dto/create-checkout.dto.ts new file mode 100644 index 0000000000000000000000000000000000000000..0e0c5da8b5936997d68818b2fae7b4ae2e85452f --- /dev/null +++ b/apps/prevision-api/src/subscriptions/dto/create-checkout.dto.ts @@ -0,0 +1,7 @@ +import { IsIn } from 'class-validator'; +import type { PlanId } from '../../config/app-config.interface.js'; + +export class CreateCheckoutDto { + @IsIn(['starter', 'growth']) + plan: PlanId; +} diff --git a/apps/prevision-api/src/subscriptions/dto/redirect-url.dto.ts b/apps/prevision-api/src/subscriptions/dto/redirect-url.dto.ts new file mode 100644 index 0000000000000000000000000000000000000000..89751bb3d0b3361adbb6d5687a732321ead03ae0 --- /dev/null +++ b/apps/prevision-api/src/subscriptions/dto/redirect-url.dto.ts @@ -0,0 +1,4 @@ +/** A Stripe-hosted page (Checkout or the billing portal) to send the browser to. */ +export class RedirectUrlDto { + url: string; +} diff --git a/apps/prevision-api/src/subscriptions/dto/subscription.dto.ts b/apps/prevision-api/src/subscriptions/dto/subscription.dto.ts new file mode 100644 index 0000000000000000000000000000000000000000..d304bd713bb8461320510fcbf862880c59b02ce0 --- /dev/null +++ b/apps/prevision-api/src/subscriptions/dto/subscription.dto.ts @@ -0,0 +1,13 @@ +import type { Subscription } from '../../generated/prisma/client.js'; + +export class SubscriptionDto { + plan: Subscription['plan']; + status: Subscription['status']; + currentPeriodEnd: Date; + cancelAtPeriodEnd: boolean; + + static from(subscription: Subscription): SubscriptionDto { + const { plan, status, currentPeriodEnd, cancelAtPeriodEnd } = subscription; + return { plan, status, currentPeriodEnd, cancelAtPeriodEnd }; + } +} diff --git a/apps/prevision-api/src/subscriptions/subscriptions.controller.ts b/apps/prevision-api/src/subscriptions/subscriptions.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..d7f0292141ea9c2ccc0bcb7f3a17dfbbde2aaa7f --- /dev/null +++ b/apps/prevision-api/src/subscriptions/subscriptions.controller.ts @@ -0,0 +1,32 @@ +import { Body, Controller, Get, HttpCode, Post, UseGuards } from '@nestjs/common'; +import { CurrentAuth } from '../users/decorators/current-auth.decorator.js'; +import { ClerkAuthGuard } from '../users/guards/clerk-auth.guard.js'; +import type { AuthContext } from '../users/interfaces/authenticated-request.interface.js'; +import { CreateCheckoutDto } from './dto/create-checkout.dto.js'; +import type { RedirectUrlDto } from './dto/redirect-url.dto.js'; +import { SubscriptionDto } from './dto/subscription.dto.js'; +import { SubscriptionsService } from './subscriptions.service.js'; + +@Controller('subscriptions') +@UseGuards(ClerkAuthGuard) +export class SubscriptionsController { + constructor(private readonly subscriptions: SubscriptionsService) {} + + @Get('current') + async current(@CurrentAuth() { user }: AuthContext): Promise { + const subscription = await this.subscriptions.current(user.id); + return subscription && SubscriptionDto.from(subscription); + } + + @Post('checkout') + @HttpCode(200) + checkout(@CurrentAuth() { user }: AuthContext, @Body() { plan }: CreateCheckoutDto): Promise { + return this.subscriptions.createCheckout(user, plan); + } + + @Post('portal') + @HttpCode(200) + portal(@CurrentAuth() { user }: AuthContext): Promise { + return this.subscriptions.createPortal(user); + } +} diff --git a/apps/prevision-api/src/subscriptions/subscriptions.module.ts b/apps/prevision-api/src/subscriptions/subscriptions.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..1f1932192352a3168a7b71336dda32a0d1ead84f --- /dev/null +++ b/apps/prevision-api/src/subscriptions/subscriptions.module.ts @@ -0,0 +1,12 @@ +import { Module } from '@nestjs/common'; +import { UsersModule } from '../users/users.module.js'; +import { SubscriptionsController } from './subscriptions.controller.js'; +import { SubscriptionsService } from './subscriptions.service.js'; + +@Module({ + imports: [UsersModule], + controllers: [SubscriptionsController], + providers: [SubscriptionsService], + exports: [SubscriptionsService], +}) +export class SubscriptionsModule {} diff --git a/apps/prevision-api/src/subscriptions/subscriptions.service.spec.ts b/apps/prevision-api/src/subscriptions/subscriptions.service.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..df476bac1ce4c8c8c810028b3e2412511d8cc7ba --- /dev/null +++ b/apps/prevision-api/src/subscriptions/subscriptions.service.spec.ts @@ -0,0 +1,138 @@ +import { Test } from '@nestjs/testing'; +import { testConfig } from '../../test/support/test-config.js'; +import { APP_CONFIG } from '../config/app-config.js'; +import type { User } from '../generated/prisma/client.js'; +import { PrismaService } from '../prisma/prisma.service.js'; +import { STRIPE_CLIENT } from '../stripe/stripe.constants.js'; +import { SubscriptionsService } from './subscriptions.service.js'; + +const user = { id: 'u1', email: 'ann@example.com', name: 'Ann', stripeCustomerId: null } as User; + +const stripeSubscription = (overrides: Record = {}) => ({ + id: 'sub_1', + status: 'active', + customer: 'cus_1', + metadata: { userId: 'u1' }, + cancel_at_period_end: false, + items: { data: [{ price: { id: 'price_growth' }, current_period_start: 1_790_000_000, current_period_end: 1_792_592_000 }] }, + ...overrides, +}); + +describe('SubscriptionsService', () => { + const db = { + subscription: { findFirst: vi.fn(), upsert: vi.fn() }, + user: { update: vi.fn(), findUnique: vi.fn() }, + }; + const stripe = { + customers: { create: vi.fn() }, + checkout: { sessions: { create: vi.fn() } }, + billingPortal: { sessions: { create: vi.fn() } }, + subscriptions: { retrieve: vi.fn() }, + }; + let service: SubscriptionsService; + + beforeEach(async () => { + vi.clearAllMocks(); + db.subscription.findFirst.mockResolvedValue(null); + stripe.customers.create.mockResolvedValue({ id: 'cus_new' }); + stripe.checkout.sessions.create.mockResolvedValue({ url: 'https://checkout.stripe.test/s' }); + const moduleRef = await Test.createTestingModule({ + providers: [ + SubscriptionsService, + { provide: PrismaService, useValue: { db } }, + { provide: STRIPE_CLIENT, useValue: stripe }, + { provide: APP_CONFIG, useValue: testConfig() }, + ], + }).compile(); + service = moduleRef.get(SubscriptionsService); + }); + + describe('createCheckout', () => { + it('creates the Stripe customer once and opens a branded subscription checkout', async () => { + expect(await service.createCheckout(user, 'starter')).toEqual({ url: 'https://checkout.stripe.test/s' }); + expect(stripe.customers.create).toHaveBeenCalledWith( + { email: 'ann@example.com', name: 'Ann', metadata: { userId: 'u1' } }, + { idempotencyKey: 'customer-u1' }, + ); + expect(db.user.update).toHaveBeenCalledWith({ where: { id: 'u1' }, data: { stripeCustomerId: 'cus_new' } }); + expect(stripe.checkout.sessions.create).toHaveBeenCalledWith( + expect.objectContaining({ + mode: 'subscription', + adaptive_pricing: { enabled: false }, + customer: 'cus_new', + client_reference_id: 'u1', + line_items: [{ price: 'price_starter', quantity: 1 }], + subscription_data: { metadata: { userId: 'u1' } }, + success_url: 'https://app.test/studio?checkout=success', + cancel_url: 'https://app.test/studio?checkout=cancelled', + branding_settings: expect.objectContaining({ display_name: 'Prevision', logo: { type: 'url', url: 'https://cdn.test/prevision-logo.png' } }), + }), + ); + }); + + it('reuses an existing Stripe customer', async () => { + await service.createCheckout({ ...user, stripeCustomerId: 'cus_1' }, 'growth'); + expect(stripe.customers.create).not.toHaveBeenCalled(); + expect(stripe.checkout.sessions.create).toHaveBeenCalledWith(expect.objectContaining({ customer: 'cus_1' })); + }); + + it('refuses a second plan', async () => { + db.subscription.findFirst.mockResolvedValue({ id: 's1' }); + await expect(service.createCheckout(user, 'growth')).rejects.toMatchObject({ status: 409, code: 'ALREADY_SUBSCRIBED' }); + }); + }); + + describe('createPortal', () => { + it('opens the billing portal for a customer', async () => { + stripe.billingPortal.sessions.create.mockResolvedValue({ url: 'https://billing.stripe.test/p' }); + expect(await service.createPortal({ ...user, stripeCustomerId: 'cus_1' })).toEqual({ url: 'https://billing.stripe.test/p' }); + expect(stripe.billingPortal.sessions.create).toHaveBeenCalledWith({ + customer: 'cus_1', + return_url: 'https://app.test/studio', + configuration: 'bpc_test', + }); + }); + + it('refuses accounts that never subscribed', async () => { + await expect(service.createPortal(user)).rejects.toMatchObject({ status: 404, code: 'NO_SUBSCRIPTION' }); + }); + }); + + describe('syncFromStripe', () => { + it('upserts the subscription with its plan and billing period', async () => { + stripe.subscriptions.retrieve.mockResolvedValue(stripeSubscription()); + await service.syncFromStripe('sub_1'); + const data = { + userId: 'u1', + stripePriceId: 'price_growth', + plan: 'growth', + status: 'active', + currentPeriodStart: new Date(1_790_000_000 * 1000), + currentPeriodEnd: new Date(1_792_592_000 * 1000), + cancelAtPeriodEnd: false, + }; + expect(db.subscription.upsert).toHaveBeenCalledWith({ + where: { stripeSubscriptionId: 'sub_1' }, + create: { stripeSubscriptionId: 'sub_1', ...data }, + update: data, + }); + }); + + it('finds the account by Stripe customer when metadata is missing', async () => { + stripe.subscriptions.retrieve.mockResolvedValue(stripeSubscription({ metadata: {} })); + db.user.findUnique.mockResolvedValue({ id: 'u9' }); + await service.syncFromStripe('sub_1'); + expect(db.user.findUnique).toHaveBeenCalledWith({ where: { stripeCustomerId: 'cus_1' }, select: { id: true } }); + expect(db.subscription.upsert).toHaveBeenCalledWith(expect.objectContaining({ update: expect.objectContaining({ userId: 'u9' }) })); + }); + + it.each([ + ['an unknown price', { items: { data: [{ price: { id: 'price_other' }, current_period_start: 1, current_period_end: 2 }] } }], + ['an unknown status', { status: 'brand_new_status' }], + ])('skips a subscription with %s', async (_, overrides) => { + stripe.subscriptions.retrieve.mockResolvedValue(stripeSubscription(overrides)); + await service.syncFromStripe('sub_1'); + expect(db.subscription.upsert).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/apps/prevision-api/src/subscriptions/subscriptions.service.ts b/apps/prevision-api/src/subscriptions/subscriptions.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..87a9af57e1e9e92928af325b3ad93ab626bd2ba0 --- /dev/null +++ b/apps/prevision-api/src/subscriptions/subscriptions.service.ts @@ -0,0 +1,124 @@ +import { Inject, Injectable, Logger } from '@nestjs/common'; +import type Stripe from 'stripe'; +import { AppException } from '../common/exceptions/app.exception.js'; +import { APP_CONFIG } from '../config/app-config.js'; +import type { AppConfig, PlanId } from '../config/app-config.interface.js'; +import { SubscriptionStatus, type Subscription, type User } from '../generated/prisma/client.js'; +import { PrismaService } from '../prisma/prisma.service.js'; +import { STRIPE_CLIENT } from '../stripe/stripe.constants.js'; +import { activeSubscriptionWhere } from './active-subscription.js'; +import type { RedirectUrlDto } from './dto/redirect-url.dto.js'; + +@Injectable() +export class SubscriptionsService { + private readonly logger = new Logger(SubscriptionsService.name); + + constructor( + private readonly prisma: PrismaService, + @Inject(STRIPE_CLIENT) private readonly stripe: Stripe, + @Inject(APP_CONFIG) private readonly config: AppConfig, + ) {} + + current(userId: string): Promise { + return this.prisma.db.subscription.findFirst({ where: activeSubscriptionWhere(userId), orderBy: { currentPeriodEnd: 'desc' } }); + } + + async createCheckout(user: User, plan: PlanId): Promise { + if (await this.current(user.id)) { + throw new AppException(409, 'ALREADY_SUBSCRIBED', 'You already have a plan. Manage it from your account.'); + } + const { stripe: stripeConfig, appUrl } = this.config; + const session = await this.stripe.checkout.sessions.create({ + mode: 'subscription', + customer: await this.customerFor(user), + client_reference_id: user.id, + line_items: [{ price: stripeConfig.plans[plan].priceId, quantity: 1 }], + subscription_data: { metadata: { userId: user.id } }, + allow_promotion_codes: true, + // Prices are in US dollars; don't convert them to the visitor's local currency. + adaptive_pricing: { enabled: false }, + success_url: `${appUrl}/studio?checkout=success`, + cancel_url: `${appUrl}/studio?checkout=cancelled`, + branding_settings: { + display_name: 'Prevision', + button_color: '#4263eb', + background_color: '#f6f6f4', + border_style: 'rounded', + font_family: 'inter', + ...(stripeConfig.logoUrl && { logo: { type: 'url', url: stripeConfig.logoUrl } }), + }, + }); + if (!session.url) throw new AppException(502, 'CHECKOUT_UNAVAILABLE', 'Checkout is unavailable. Please try again.'); + return { url: session.url }; + } + + async createPortal(user: User): Promise { + if (!user.stripeCustomerId) throw new AppException(404, 'NO_SUBSCRIPTION', 'You have no plan to manage yet.'); + const session = await this.stripe.billingPortal.sessions.create({ + customer: user.stripeCustomerId, + return_url: `${this.config.appUrl}/studio`, + configuration: this.config.stripe.portalConfigurationId, + }); + return { url: session.url }; + } + + /** Copies a subscription's current state from Stripe. Safe to repeat and to receive out of order. */ + async syncFromStripe(stripeSubscriptionId: string): Promise { + const subscription = await this.stripe.subscriptions.retrieve(stripeSubscriptionId); + const userId = await this.userIdFor(subscription); + if (!userId) { + this.logger.warn(`No account for Stripe subscription ${subscription.id}`); + return; + } + const item = subscription.items.data[0]; + const plan = this.planFor(item.price.id); + if (!plan) { + this.logger.warn(`Stripe subscription ${subscription.id} uses an unknown price ${item.price.id}`); + return; + } + const status = toStatus(subscription.status); + if (!status) { + this.logger.warn(`Stripe subscription ${subscription.id} has an unknown status ${subscription.status}`); + return; + } + const data = { + userId, + stripePriceId: item.price.id, + plan, + status, + currentPeriodStart: new Date(item.current_period_start * 1000), + currentPeriodEnd: new Date(item.current_period_end * 1000), + cancelAtPeriodEnd: subscription.cancel_at_period_end, + }; + await this.prisma.db.subscription.upsert({ + where: { stripeSubscriptionId: subscription.id }, + create: { stripeSubscriptionId: subscription.id, ...data }, + update: data, + }); + } + + private async customerFor(user: User): Promise { + if (user.stripeCustomerId) return user.stripeCustomerId; + const customer = await this.stripe.customers.create( + { email: user.email, name: user.name ?? undefined, metadata: { userId: user.id } }, + { idempotencyKey: `customer-${user.id}` }, + ); + await this.prisma.db.user.update({ where: { id: user.id }, data: { stripeCustomerId: customer.id } }); + return customer.id; + } + + private async userIdFor(subscription: Stripe.Subscription): Promise { + if (subscription.metadata.userId) return subscription.metadata.userId; + const customerId = typeof subscription.customer === 'string' ? subscription.customer : subscription.customer.id; + const user = await this.prisma.db.user.findUnique({ where: { stripeCustomerId: customerId }, select: { id: true } }); + return user?.id ?? null; + } + + private planFor(priceId: string): PlanId | null { + const entry = Object.entries(this.config.stripe.plans).find(([, plan]) => plan.priceId === priceId); + return (entry?.[0] as PlanId | undefined) ?? null; + } +} + +const STATUSES = new Set(Object.values(SubscriptionStatus)); +const toStatus = (status: string): SubscriptionStatus | null => (STATUSES.has(status) ? (status as SubscriptionStatus) : null); diff --git a/apps/prevision-api/src/tiles/dto/list-tiles-query.dto.spec.ts b/apps/prevision-api/src/tiles/dto/list-tiles-query.dto.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..4bf45277301c78aacd18894f3c933d3d4272a900 --- /dev/null +++ b/apps/prevision-api/src/tiles/dto/list-tiles-query.dto.spec.ts @@ -0,0 +1,29 @@ +import { plainToInstance } from 'class-transformer'; +import { validateSync } from 'class-validator'; +import { ListTilesQueryDto } from './list-tiles-query.dto.js'; + +const parse = (query: Record) => { + const dto = plainToInstance(ListTilesQueryDto, query); + return { dto, errors: validateSync(dto, { whitelist: true, forbidNonWhitelisted: true }) }; +}; + +describe('ListTilesQueryDto', () => { + it('applies defaults and trims text filters', () => { + const { dto, errors } = parse({ q: ' jura ', collection: ' ' }); + expect(errors).toEqual([]); + expect(dto).toMatchObject({ q: 'jura', collection: undefined, sort: 'name', page: 1, pageSize: 24 }); + expect(dto.offset).toBe(0); + }); + + it('converts paging and computes the offset', () => { + const { dto } = parse({ page: '3', pageSize: '10' }); + expect(dto.offset).toBe(20); + }); + + it.each([{ pageSize: '500' }, { page: '0' }, { sort: 'price' }, { surface: 'ceiling' }, { unknown: 'x' }])( + 'rejects %o', + (query) => { + expect(parse(query).errors).not.toEqual([]); + }, + ); +}); diff --git a/apps/prevision-api/src/tiles/dto/list-tiles-query.dto.ts b/apps/prevision-api/src/tiles/dto/list-tiles-query.dto.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a4cf541b181475ea121130523cd776344a915da --- /dev/null +++ b/apps/prevision-api/src/tiles/dto/list-tiles-query.dto.ts @@ -0,0 +1,33 @@ +import { IsIn, IsOptional, IsString, MaxLength } from 'class-validator'; +import { Transform } from 'class-transformer'; +import { PaginationQueryDto } from '../../common/dto/pagination-query.dto.js'; + +export const TILE_SORTS = ['name', '-name', 'newest', 'oldest'] as const; +const SURFACES = ['floor', 'walls'] as const; + +export type TileSort = (typeof TILE_SORTS)[number]; +type Surface = (typeof SURFACES)[number]; + +const trimmed = ({ value }: { value: unknown }) => (typeof value === 'string' ? value.trim() || undefined : value); + +export class ListTilesQueryDto extends PaginationQueryDto { + @IsOptional() + @Transform(trimmed) + @IsString() + @MaxLength(100) + q?: string; + + @IsOptional() + @IsIn(SURFACES) + surface?: Surface; + + @IsOptional() + @Transform(trimmed) + @IsString() + @MaxLength(120) + collection?: string; + + @IsOptional() + @IsIn(TILE_SORTS) + sort: TileSort = 'name'; +} diff --git a/apps/prevision-api/src/tiles/dto/tile-facets.dto.ts b/apps/prevision-api/src/tiles/dto/tile-facets.dto.ts new file mode 100644 index 0000000000000000000000000000000000000000..e3da09d020fd9a4bcc35479362d2165f9260607d --- /dev/null +++ b/apps/prevision-api/src/tiles/dto/tile-facets.dto.ts @@ -0,0 +1,10 @@ +export class FacetCountDto { + value: string; + count: number; +} + +export class TileFacetsDto { + total: number; + surfaces: FacetCountDto[]; + collections: FacetCountDto[]; +} diff --git a/apps/prevision-api/src/tiles/dto/tile-slug-params.dto.ts b/apps/prevision-api/src/tiles/dto/tile-slug-params.dto.ts new file mode 100644 index 0000000000000000000000000000000000000000..3a8983e8aa15cba7c69b6c82321c88d1fac5f2ad --- /dev/null +++ b/apps/prevision-api/src/tiles/dto/tile-slug-params.dto.ts @@ -0,0 +1,6 @@ +import { Matches } from 'class-validator'; + +export class TileSlugParamsDto { + @Matches(/^[a-z0-9][a-z0-9-]{0,119}$/) + slug: string; +} diff --git a/apps/prevision-api/src/tiles/dto/tile.dto.ts b/apps/prevision-api/src/tiles/dto/tile.dto.ts new file mode 100644 index 0000000000000000000000000000000000000000..da0f44db67ab6466a62d3b8e046fb42e925ed9cb --- /dev/null +++ b/apps/prevision-api/src/tiles/dto/tile.dto.ts @@ -0,0 +1,15 @@ +export class TileDto { + slug: string; + name: string; + collection: string | null; + surfaces: string[]; + widthMm: number | null; + heightMm: number | null; + imageUrl: string; + thumbnailUrl: string | null; + assets: Record; + render: Record; + position: number | null; + createdAt: Date; + updatedAt: Date; +} diff --git a/apps/prevision-api/src/tiles/tiles.controller.ts b/apps/prevision-api/src/tiles/tiles.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..d311488e9cfb1000d0f9760c1ec1f0222df6a6f3 --- /dev/null +++ b/apps/prevision-api/src/tiles/tiles.controller.ts @@ -0,0 +1,29 @@ +import { Controller, Get, Param, Query, UseGuards } from '@nestjs/common'; +import type { Paginated } from '../common/dto/paginated.dto.js'; +import { ClerkAuthGuard } from '../users/guards/clerk-auth.guard.js'; +import { ListTilesQueryDto } from './dto/list-tiles-query.dto.js'; +import type { TileFacetsDto } from './dto/tile-facets.dto.js'; +import { TileSlugParamsDto } from './dto/tile-slug-params.dto.js'; +import type { TileDto } from './dto/tile.dto.js'; +import { TilesService } from './tiles.service.js'; + +@Controller('tiles') +@UseGuards(ClerkAuthGuard) +export class TilesController { + constructor(private readonly tiles: TilesService) {} + + @Get() + list(@Query() query: ListTilesQueryDto): Promise> { + return this.tiles.list(query); + } + + @Get('facets') + facets(): Promise { + return this.tiles.facets(); + } + + @Get(':slug') + findOne(@Param() { slug }: TileSlugParamsDto): Promise { + return this.tiles.findBySlug(slug); + } +} diff --git a/apps/prevision-api/src/tiles/tiles.module.ts b/apps/prevision-api/src/tiles/tiles.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..a46c332d4c9a0c7e8697cc511405ebdea7dbead0 --- /dev/null +++ b/apps/prevision-api/src/tiles/tiles.module.ts @@ -0,0 +1,11 @@ +import { Module } from '@nestjs/common'; +import { UsersModule } from '../users/users.module.js'; +import { TilesController } from './tiles.controller.js'; +import { TilesService } from './tiles.service.js'; + +@Module({ + imports: [UsersModule], + controllers: [TilesController], + providers: [TilesService], +}) +export class TilesModule {} diff --git a/apps/prevision-api/src/tiles/tiles.service.ts b/apps/prevision-api/src/tiles/tiles.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..9c126946eb8e20d3e413c3ef5fa632531161175a --- /dev/null +++ b/apps/prevision-api/src/tiles/tiles.service.ts @@ -0,0 +1,85 @@ +import { Injectable } from '@nestjs/common'; +import { Paginated } from '../common/dto/paginated.dto.js'; +import { AppException } from '../common/exceptions/app.exception.js'; +import type { Prisma } from '../generated/prisma/client.js'; +import { PrismaService } from '../prisma/prisma.service.js'; +import type { ListTilesQueryDto, TileSort } from './dto/list-tiles-query.dto.js'; +import type { TileFacetsDto } from './dto/tile-facets.dto.js'; +import type { TileDto } from './dto/tile.dto.js'; + +const ORDER_BY: Record = { + name: [{ name: 'asc' }, { id: 'asc' }], + '-name': [{ name: 'desc' }, { id: 'desc' }], + newest: [{ createdAt: 'desc' }, { id: 'desc' }], + oldest: [{ createdAt: 'asc' }, { id: 'asc' }], +}; + +const SELECT = { + slug: true, + name: true, + collection: true, + surfaces: true, + widthMm: true, + heightMm: true, + imageUrl: true, + thumbnailUrl: true, + assets: true, + render: true, + position: true, + createdAt: true, + updatedAt: true, +} satisfies Prisma.TileSelect; + +/** Prisma passes `contains` to ILIKE unescaped; make % and _ literal. */ +const literal = (value: string) => value.replace(/[\\%_]/g, (char) => `\\${char}`); + +@Injectable() +export class TilesService { + constructor(private readonly prisma: PrismaService) {} + + async list(query: ListTilesQueryDto): Promise> { + const where: Prisma.TileWhereInput = { + ...(query.q && { + OR: [ + { name: { contains: literal(query.q), mode: 'insensitive' } }, + { collection: { contains: literal(query.q), mode: 'insensitive' } }, + ], + }), + ...(query.surface && { surfaces: { has: query.surface } }), + ...(query.collection && { collection: query.collection }), + }; + const [items, total] = await this.prisma.db.$transaction([ + this.prisma.db.tile.findMany({ where, select: SELECT, orderBy: ORDER_BY[query.sort], skip: query.offset, take: query.pageSize }), + this.prisma.db.tile.count({ where }), + ]); + return new Paginated(items as TileDto[], total, query); + } + + async facets(): Promise { + const [total, floor, walls, collections] = await this.prisma.db.$transaction([ + this.prisma.db.tile.count(), + this.prisma.db.tile.count({ where: { surfaces: { has: 'floor' } } }), + this.prisma.db.tile.count({ where: { surfaces: { has: 'walls' } } }), + this.prisma.db.tile.groupBy({ + by: ['collection'], + where: { collection: { not: null } }, + _count: { _all: true }, + orderBy: { collection: 'asc' }, + }), + ]); + return { + total, + surfaces: [ + { value: 'floor', count: floor }, + { value: 'walls', count: walls }, + ].filter((facet) => facet.count > 0), + collections: collections.map((row) => ({ value: row.collection!, count: row._count._all })), + }; + } + + async findBySlug(slug: string): Promise { + const tile = await this.prisma.db.tile.findUnique({ where: { slug }, select: SELECT }); + if (!tile) throw new AppException(404, 'TILE_NOT_FOUND', 'This tile could not be found.'); + return tile as TileDto; + } +} diff --git a/apps/prevision-api/src/users/decorators/current-auth.decorator.ts b/apps/prevision-api/src/users/decorators/current-auth.decorator.ts new file mode 100644 index 0000000000000000000000000000000000000000..2e2398e006fd0809e7c1ab9d457426da7a0335df --- /dev/null +++ b/apps/prevision-api/src/users/decorators/current-auth.decorator.ts @@ -0,0 +1,6 @@ +import { createParamDecorator, ExecutionContext } from '@nestjs/common'; +import type { AuthContext, AuthenticatedRequest } from '../interfaces/authenticated-request.interface.js'; + +export const CurrentAuth = createParamDecorator( + (_: unknown, context: ExecutionContext): AuthContext => context.switchToHttp().getRequest().auth, +); diff --git a/apps/prevision-api/src/users/dto/me.dto.ts b/apps/prevision-api/src/users/dto/me.dto.ts new file mode 100644 index 0000000000000000000000000000000000000000..87bb81d05e291f882178e9f3b84b8e5523dcdc41 --- /dev/null +++ b/apps/prevision-api/src/users/dto/me.dto.ts @@ -0,0 +1,19 @@ +import type { User, UserRole } from '../../generated/prisma/client.js'; +import { UsageDto } from '../../generations/dto/usage.dto.js'; + +export class UserDto { + id: string; + email: string; + name: string | null; + role: UserRole; + createdAt: Date; + + static from(user: User): UserDto { + return { id: user.id, email: user.email, name: user.name, role: user.role, createdAt: user.createdAt }; + } +} + +export class MeDto { + user: UserDto; + usage: UsageDto; +} diff --git a/apps/prevision-api/src/users/guards/clerk-auth.guard.spec.ts b/apps/prevision-api/src/users/guards/clerk-auth.guard.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..ec3552912813961cf507bda9c679d869a6949d07 --- /dev/null +++ b/apps/prevision-api/src/users/guards/clerk-auth.guard.spec.ts @@ -0,0 +1,25 @@ +import type { ExecutionContext } from '@nestjs/common'; +import type { ClerkService } from '../../clerk/clerk.service.js'; +import type { UsersService } from '../users.service.js'; +import { ClerkAuthGuard } from './clerk-auth.guard.js'; + +const contextFor = (request: object) => ({ switchToHttp: () => ({ getRequest: () => request }) }) as ExecutionContext; + +describe('ClerkAuthGuard', () => { + const clerk = { verifySessionToken: vi.fn() }; + const users = { findOrCreateFromClerk: vi.fn() }; + const guard = new ClerkAuthGuard(clerk as unknown as ClerkService, users as unknown as UsersService); + + it('refuses requests without a bearer token', async () => { + await expect(guard.canActivate(contextFor({ headers: {} }))).rejects.toMatchObject({ status: 401 }); + expect(clerk.verifySessionToken).not.toHaveBeenCalled(); + }); + + it('attaches the account and Clerk session to the request', async () => { + clerk.verifySessionToken.mockResolvedValue({ userId: 'user_1', sessionId: 'sess_1' }); + users.findOrCreateFromClerk.mockResolvedValue({ id: 'u1' }); + const request = { headers: { authorization: 'Bearer token' } } as { headers: object; auth?: unknown }; + expect(await guard.canActivate(contextFor(request))).toBe(true); + expect(request.auth).toEqual({ user: { id: 'u1' }, sessionId: 'sess_1' }); + }); +}); diff --git a/apps/prevision-api/src/users/guards/clerk-auth.guard.ts b/apps/prevision-api/src/users/guards/clerk-auth.guard.ts new file mode 100644 index 0000000000000000000000000000000000000000..ddb12658a6492162da8bceae07cedc6471fce98d --- /dev/null +++ b/apps/prevision-api/src/users/guards/clerk-auth.guard.ts @@ -0,0 +1,23 @@ +import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; +import { ClerkService } from '../../clerk/clerk.service.js'; +import { unauthenticated } from '../../common/exceptions/app.exception.js'; +import { bearerToken } from '../../common/utils/bearer-token.js'; +import type { AuthenticatedRequest } from '../interfaces/authenticated-request.interface.js'; +import { UsersService } from '../users.service.js'; + +@Injectable() +export class ClerkAuthGuard implements CanActivate { + constructor( + private readonly clerk: ClerkService, + private readonly users: UsersService, + ) {} + + async canActivate(context: ExecutionContext): Promise { + const request = context.switchToHttp().getRequest(); + const token = bearerToken(request); + if (!token) throw unauthenticated(); + const session = await this.clerk.verifySessionToken(token); + request.auth = { user: await this.users.findOrCreateFromClerk(session.userId), sessionId: session.sessionId }; + return true; + } +} diff --git a/apps/prevision-api/src/users/interfaces/authenticated-request.interface.ts b/apps/prevision-api/src/users/interfaces/authenticated-request.interface.ts new file mode 100644 index 0000000000000000000000000000000000000000..0b56634e9a7b3abe226f1e123de44b1a9ee69046 --- /dev/null +++ b/apps/prevision-api/src/users/interfaces/authenticated-request.interface.ts @@ -0,0 +1,11 @@ +import type { Request } from 'express'; +import type { User } from '../../generated/prisma/client.js'; + +export interface AuthContext { + user: User; + sessionId: string; +} + +export interface AuthenticatedRequest extends Request { + auth: AuthContext; +} diff --git a/apps/prevision-api/src/users/users.controller.ts b/apps/prevision-api/src/users/users.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..3c49c52514fc44a0705bb0909cd47980bd2d87f7 --- /dev/null +++ b/apps/prevision-api/src/users/users.controller.ts @@ -0,0 +1,17 @@ +import { Controller, Get, UseGuards } from '@nestjs/common'; +import { GenerationsService } from '../generations/generations.service.js'; +import { CurrentAuth } from './decorators/current-auth.decorator.js'; +import { MeDto, UserDto } from './dto/me.dto.js'; +import { ClerkAuthGuard } from './guards/clerk-auth.guard.js'; +import type { AuthContext } from './interfaces/authenticated-request.interface.js'; + +@Controller('me') +@UseGuards(ClerkAuthGuard) +export class UsersController { + constructor(private readonly generations: GenerationsService) {} + + @Get() + async me(@CurrentAuth() { user }: AuthContext): Promise { + return { user: UserDto.from(user), usage: await this.generations.usage(user) }; + } +} diff --git a/apps/prevision-api/src/users/users.module.ts b/apps/prevision-api/src/users/users.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..993c0c0cb7aec1ee7165c966b226f019ccfb3ba3 --- /dev/null +++ b/apps/prevision-api/src/users/users.module.ts @@ -0,0 +1,14 @@ +import { Module } from '@nestjs/common'; +import { ClerkModule } from '../clerk/clerk.module.js'; +import { GenerationsModule } from '../generations/generations.module.js'; +import { ClerkAuthGuard } from './guards/clerk-auth.guard.js'; +import { UsersController } from './users.controller.js'; +import { UsersService } from './users.service.js'; + +@Module({ + imports: [ClerkModule, GenerationsModule], + controllers: [UsersController], + providers: [UsersService, ClerkAuthGuard], + exports: [UsersService, ClerkAuthGuard, ClerkModule], +}) +export class UsersModule {} diff --git a/apps/prevision-api/src/users/users.service.spec.ts b/apps/prevision-api/src/users/users.service.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..e1684129b7d8028e084c383eabf62c08eb520b0e --- /dev/null +++ b/apps/prevision-api/src/users/users.service.spec.ts @@ -0,0 +1,74 @@ +import { Test } from '@nestjs/testing'; +import { ClerkService } from '../clerk/clerk.service.js'; +import { Prisma } from '../generated/prisma/client.js'; +import { PrismaService } from '../prisma/prisma.service.js'; +import { UsersService } from './users.service.js'; + +describe('UsersService', () => { + const user = { id: 'u1', clerkUserId: 'user_1', email: 'a@example.com', name: 'Ann' }; + const tx = { user: { findUnique: vi.fn(), update: vi.fn(), count: vi.fn(), create: vi.fn() } }; + const db = { user: { findUnique: vi.fn(), update: vi.fn() }, $transaction: vi.fn((work: (client: typeof tx) => unknown) => work(tx)) }; + const clerk = { getVerifiedProfile: vi.fn() }; + let service: UsersService; + + beforeEach(async () => { + vi.clearAllMocks(); + clerk.getVerifiedProfile.mockResolvedValue({ email: 'a@example.com', name: 'Ann' }); + const moduleRef = await Test.createTestingModule({ + providers: [UsersService, { provide: PrismaService, useValue: { db } }, { provide: ClerkService, useValue: clerk }], + }).compile(); + service = moduleRef.get(UsersService); + }); + + it('returns a known Clerk user without calling Clerk', async () => { + db.user.findUnique.mockResolvedValue(user); + expect(await service.findOrCreateFromClerk('user_1')).toBe(user); + expect(clerk.getVerifiedProfile).not.toHaveBeenCalled(); + }); + + it('creates the account on first sign-in', async () => { + db.user.findUnique.mockResolvedValue(null); + tx.user.findUnique.mockResolvedValue(null); + tx.user.count.mockResolvedValue(0); + tx.user.create.mockResolvedValue(user); + expect(await service.findOrCreateFromClerk('user_1')).toBe(user); + expect(tx.user.create).toHaveBeenCalledWith({ data: { clerkUserId: 'user_1', email: 'a@example.com', name: 'Ann' } }); + }); + + it('links a recreated Clerk account to the existing account with the same email', async () => { + db.user.findUnique.mockResolvedValue(null); + tx.user.findUnique.mockResolvedValue({ ...user, clerkUserId: 'user_old' }); + tx.user.update.mockResolvedValue(user); + await service.findOrCreateFromClerk('user_1'); + expect(tx.user.update).toHaveBeenCalledWith({ where: { id: 'u1' }, data: { clerkUserId: 'user_1', name: 'Ann' } }); + expect(tx.user.create).not.toHaveBeenCalled(); + }); + + it('keeps a soft-deleted account closed', async () => { + db.user.findUnique.mockResolvedValue(null); + tx.user.findUnique.mockResolvedValue(null); + tx.user.count.mockResolvedValue(1); + await expect(service.findOrCreateFromClerk('user_1')).rejects.toMatchObject({ code: 'ACCOUNT_DISABLED' }); + }); + + it('changes the role of an existing account by email', async () => { + db.user.findUnique.mockResolvedValue(user); + db.user.update = vi.fn().mockResolvedValue({ ...user, role: 'admin' }); + expect((await service.setRole(' A@Example.com ', 'admin')).role).toBe('admin'); + expect(db.user.findUnique).toHaveBeenCalledWith({ where: { email: 'a@example.com' } }); + expect(db.user.update).toHaveBeenCalledWith({ where: { id: 'u1' }, data: { role: 'admin' } }); + }); + + it('refuses a role for an email that never signed in', async () => { + db.user.findUnique.mockResolvedValue(null); + await expect(service.setRole('nobody@example.com', 'admin')).rejects.toMatchObject({ code: 'USER_NOT_FOUND' }); + }); + + it('returns the winner when a concurrent first request created the account', async () => { + db.user.findUnique.mockResolvedValueOnce(null).mockResolvedValueOnce(user); + db.$transaction.mockRejectedValueOnce( + new Prisma.PrismaClientKnownRequestError('unique', { code: 'P2002', clientVersion: 'test' }), + ); + expect(await service.findOrCreateFromClerk('user_1')).toBe(user); + }); +}); diff --git a/apps/prevision-api/src/users/users.service.ts b/apps/prevision-api/src/users/users.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..cc1a82121a7602b51a8ec0f1506b3f66e3d30cd9 --- /dev/null +++ b/apps/prevision-api/src/users/users.service.ts @@ -0,0 +1,46 @@ +import { Injectable } from '@nestjs/common'; +import { ClerkService } from '../clerk/clerk.service.js'; +import { AppException } from '../common/exceptions/app.exception.js'; +import { Prisma, type User, type UserRole } from '../generated/prisma/client.js'; +import { PrismaService } from '../prisma/prisma.service.js'; + +@Injectable() +export class UsersService { + constructor( + private readonly prisma: PrismaService, + private readonly clerk: ClerkService, + ) {} + + /** + * The account behind a Clerk user, created on first sign-in. Matched by Clerk id, + * then by verified email, so a recreated Clerk account keeps its account and usage. + */ + async findOrCreateFromClerk(clerkUserId: string): Promise { + const existing = await this.prisma.db.user.findUnique({ where: { clerkUserId } }); + if (existing) return existing; + + const { email, name } = await this.clerk.getVerifiedProfile(clerkUserId); + try { + return await this.prisma.db.$transaction(async (tx) => { + const byEmail = await tx.user.findUnique({ where: { email } }); + if (byEmail) return tx.user.update({ where: { id: byEmail.id }, data: { clerkUserId, name: byEmail.name ?? name } }); + if (await tx.user.count({ where: { email, deletedAt: { not: null } } })) { + throw new AppException(403, 'ACCOUNT_DISABLED', 'This account has been closed. Please contact us.'); + } + return tx.user.create({ data: { clerkUserId, email, name } }); + }); + } catch (error) { + const raced = error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002'; + const winner = raced ? await this.prisma.db.user.findUnique({ where: { clerkUserId } }) : null; + if (winner) return winner; + throw error; + } + } + + /** Accounts are created by signing in; this only changes the role of an existing one. */ + async setRole(email: string, role: UserRole): Promise { + const user = await this.prisma.db.user.findUnique({ where: { email: email.trim().toLowerCase() } }); + if (!user) throw new AppException(404, 'USER_NOT_FOUND', `No account for ${email}. Sign in to Prevision once first.`); + return this.prisma.db.user.update({ where: { id: user.id }, data: { role } }); + } +} diff --git a/apps/prevision-api/src/webhooks/stripe-event.decorator.ts b/apps/prevision-api/src/webhooks/stripe-event.decorator.ts new file mode 100644 index 0000000000000000000000000000000000000000..797505c06173d1b4272ed0a33a21eaf31abc8fc8 --- /dev/null +++ b/apps/prevision-api/src/webhooks/stripe-event.decorator.ts @@ -0,0 +1,7 @@ +import { createParamDecorator, ExecutionContext } from '@nestjs/common'; +import type Stripe from 'stripe'; +import type { StripeWebhookRequest } from './stripe-webhook-request.interface.js'; + +export const StripeEvent = createParamDecorator( + (_: unknown, context: ExecutionContext): Stripe.Event => context.switchToHttp().getRequest().stripeEvent, +); diff --git a/apps/prevision-api/src/webhooks/stripe-webhook-request.interface.ts b/apps/prevision-api/src/webhooks/stripe-webhook-request.interface.ts new file mode 100644 index 0000000000000000000000000000000000000000..639a7326b4d8d468daa44b77002ba5d837e1761f --- /dev/null +++ b/apps/prevision-api/src/webhooks/stripe-webhook-request.interface.ts @@ -0,0 +1,6 @@ +import type Stripe from 'stripe'; + +export interface StripeWebhookRequest { + rawBody?: Buffer; + stripeEvent: Stripe.Event; +} diff --git a/apps/prevision-api/src/webhooks/stripe-webhook.guard.spec.ts b/apps/prevision-api/src/webhooks/stripe-webhook.guard.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..3afd1a5dfffeb7ea6d0b38d76d69d136c251e34f --- /dev/null +++ b/apps/prevision-api/src/webhooks/stripe-webhook.guard.spec.ts @@ -0,0 +1,27 @@ +import type { ExecutionContext } from '@nestjs/common'; +import Stripe from 'stripe'; +import { testConfig } from '../../test/support/test-config.js'; +import { StripeWebhookGuard } from './stripe-webhook.guard.js'; + +const stripe = new Stripe('sk_test_fake'); +const guard = new StripeWebhookGuard(stripe, testConfig()); +const payload = JSON.stringify({ id: 'evt_1', object: 'event', type: 'customer.subscription.updated', data: { object: { id: 'sub_1' } } }); + +const contextFor = (request: object) => ({ switchToHttp: () => ({ getRequest: () => request }) }) as ExecutionContext; +const sign = (secret = 'whsec_test_secret') => stripe.webhooks.generateTestHeaderString({ payload, secret }); + +describe('StripeWebhookGuard', () => { + it('accepts an event signed with our secret and attaches it', () => { + const request: Record = { rawBody: Buffer.from(payload), headers: { 'stripe-signature': sign() } }; + expect(guard.canActivate(contextFor(request))).toBe(true); + expect((request.stripeEvent as Stripe.Event).id).toBe('evt_1'); + }); + + it.each([ + ['a wrong secret', { rawBody: Buffer.from(payload), headers: { 'stripe-signature': sign('whsec_other') } }], + ['a tampered body', { rawBody: Buffer.from(payload.replace('sub_1', 'sub_2')), headers: { 'stripe-signature': sign() } }], + ['no signature', { rawBody: Buffer.from(payload), headers: {} }], + ])('refuses %s', (_, request) => { + expect(() => guard.canActivate(contextFor(request))).toThrow(expect.objectContaining({ code: 'INVALID_SIGNATURE' })); + }); +}); diff --git a/apps/prevision-api/src/webhooks/stripe-webhook.guard.ts b/apps/prevision-api/src/webhooks/stripe-webhook.guard.ts new file mode 100644 index 0000000000000000000000000000000000000000..b42273402211d591b6d197676522cd979fec316f --- /dev/null +++ b/apps/prevision-api/src/webhooks/stripe-webhook.guard.ts @@ -0,0 +1,31 @@ +import { CanActivate, ExecutionContext, Inject, Injectable } from '@nestjs/common'; +import type { Request } from 'express'; +import type Stripe from 'stripe'; +import { AppException } from '../common/exceptions/app.exception.js'; +import { APP_CONFIG } from '../config/app-config.js'; +import type { AppConfig } from '../config/app-config.interface.js'; +import { STRIPE_CLIENT } from '../stripe/stripe.constants.js'; +import type { StripeWebhookRequest } from './stripe-webhook-request.interface.js'; + +/** Accepts only events signed by Stripe for our endpoint; the verified event is attached to the request. */ +@Injectable() +export class StripeWebhookGuard implements CanActivate { + constructor( + @Inject(STRIPE_CLIENT) private readonly stripe: Stripe, + @Inject(APP_CONFIG) private readonly config: AppConfig, + ) {} + + canActivate(context: ExecutionContext): boolean { + const request = context.switchToHttp().getRequest(); + const signature = request.headers['stripe-signature']; + if (!request.rawBody || typeof signature !== 'string') throw invalidSignature(); + try { + request.stripeEvent = this.stripe.webhooks.constructEvent(request.rawBody, signature, this.config.stripe.webhookSecret); + } catch { + throw invalidSignature(); + } + return true; + } +} + +const invalidSignature = () => new AppException(400, 'INVALID_SIGNATURE', 'Invalid Stripe signature.'); diff --git a/apps/prevision-api/src/webhooks/webhooks.controller.ts b/apps/prevision-api/src/webhooks/webhooks.controller.ts new file mode 100644 index 0000000000000000000000000000000000000000..2c089464c219d9e1fc572761fa217ac9761f48b6 --- /dev/null +++ b/apps/prevision-api/src/webhooks/webhooks.controller.ts @@ -0,0 +1,18 @@ +import { Controller, HttpCode, Post, UseGuards } from '@nestjs/common'; +import type Stripe from 'stripe'; +import { StripeEvent } from './stripe-event.decorator.js'; +import { StripeWebhookGuard } from './stripe-webhook.guard.js'; +import { WebhooksService } from './webhooks.service.js'; + +@Controller('webhooks') +export class WebhooksController { + constructor(private readonly webhooks: WebhooksService) {} + + @Post('stripe') + @HttpCode(200) + @UseGuards(StripeWebhookGuard) + async stripe(@StripeEvent() event: Stripe.Event): Promise<{ received: true }> { + await this.webhooks.handle(event); + return { received: true }; + } +} diff --git a/apps/prevision-api/src/webhooks/webhooks.module.ts b/apps/prevision-api/src/webhooks/webhooks.module.ts new file mode 100644 index 0000000000000000000000000000000000000000..a8812329ecb14e24a919cf0ec7c0bcd1bf43cc37 --- /dev/null +++ b/apps/prevision-api/src/webhooks/webhooks.module.ts @@ -0,0 +1,12 @@ +import { Module } from '@nestjs/common'; +import { SubscriptionsModule } from '../subscriptions/subscriptions.module.js'; +import { StripeWebhookGuard } from './stripe-webhook.guard.js'; +import { WebhooksController } from './webhooks.controller.js'; +import { WebhooksService } from './webhooks.service.js'; + +@Module({ + imports: [SubscriptionsModule], + controllers: [WebhooksController], + providers: [WebhooksService, StripeWebhookGuard], +}) +export class WebhooksModule {} diff --git a/apps/prevision-api/src/webhooks/webhooks.service.spec.ts b/apps/prevision-api/src/webhooks/webhooks.service.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..878c166d99fb30ad8a3d4b88be2ed3c0ce335db8 --- /dev/null +++ b/apps/prevision-api/src/webhooks/webhooks.service.spec.ts @@ -0,0 +1,31 @@ +import type Stripe from 'stripe'; +import type { SubscriptionsService } from '../subscriptions/subscriptions.service.js'; +import { WebhooksService } from './webhooks.service.js'; + +const event = (type: string, object: object) => ({ type, data: { object } }) as unknown as Stripe.Event; + +describe('WebhooksService', () => { + const subscriptions = { syncFromStripe: vi.fn() }; + const service = new WebhooksService(subscriptions as unknown as SubscriptionsService); + + beforeEach(() => vi.clearAllMocks()); + + it.each(['customer.subscription.created', 'customer.subscription.updated', 'customer.subscription.deleted'])( + 'syncs the subscription on %s', + async (type) => { + await service.handle(event(type, { id: 'sub_1' })); + expect(subscriptions.syncFromStripe).toHaveBeenCalledWith('sub_1'); + }, + ); + + it('syncs the subscription a completed checkout created', async () => { + await service.handle(event('checkout.session.completed', { subscription: 'sub_2' })); + expect(subscriptions.syncFromStripe).toHaveBeenCalledWith('sub_2'); + }); + + it('ignores other events and checkouts without a subscription', async () => { + await service.handle(event('invoice.paid', { id: 'in_1' })); + await service.handle(event('checkout.session.completed', { subscription: null })); + expect(subscriptions.syncFromStripe).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/prevision-api/src/webhooks/webhooks.service.ts b/apps/prevision-api/src/webhooks/webhooks.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..650fcf9c574c0b28b047a899f5fde31952f866a3 --- /dev/null +++ b/apps/prevision-api/src/webhooks/webhooks.service.ts @@ -0,0 +1,37 @@ +import { Injectable } from '@nestjs/common'; +import type Stripe from 'stripe'; +import { SubscriptionsService } from '../subscriptions/subscriptions.service.js'; + +export const HANDLED_EVENTS = [ + 'checkout.session.completed', + 'customer.subscription.created', + 'customer.subscription.updated', + 'customer.subscription.deleted', +] as const; + +@Injectable() +export class WebhooksService { + constructor(private readonly subscriptions: SubscriptionsService) {} + + /** Every handled event resolves to "sync this subscription from Stripe", so retries and reordering are harmless. */ + async handle(event: Stripe.Event): Promise { + const subscriptionId = this.subscriptionIdOf(event); + if (subscriptionId) await this.subscriptions.syncFromStripe(subscriptionId); + } + + private subscriptionIdOf(event: Stripe.Event): string | null { + switch (event.type) { + case 'checkout.session.completed': { + const { subscription } = event.data.object; + if (!subscription) return null; + return typeof subscription === 'string' ? subscription : subscription.id; + } + case 'customer.subscription.created': + case 'customer.subscription.updated': + case 'customer.subscription.deleted': + return event.data.object.id; + default: + return null; + } + } +} diff --git a/apps/prevision-api/test/catalog.e2e-spec.ts b/apps/prevision-api/test/catalog.e2e-spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..4a0fc34feb9cb4ee7daba55a8944bf921661cd31 --- /dev/null +++ b/apps/prevision-api/test/catalog.e2e-spec.ts @@ -0,0 +1,54 @@ +import { Test } from '@nestjs/testing'; +import type { INestApplicationContext } from '@nestjs/common'; +import { CatalogModule } from '../src/catalog/catalog.module.js'; +import { CatalogService } from '../src/catalog/catalog.service.js'; +import type { CatalogEntry } from '../src/catalog/interfaces/catalog-entry.interface.js'; +import { resetDatabase, sql } from './helpers.js'; + +const entry = (slug: string, overrides: Partial = {}): CatalogEntry => ({ + slug, + name: slug, + collection: null, + surfaces: ['floor'], + widthMm: 600, + heightMm: 600, + position: null, + imageUrl: `https://cdn.test/${slug}.jpg`, + thumbnailUrl: null, + assets: {}, + render: { layout: 'grid' }, + ...overrides, +}); + +describe('Catalog seed (e2e)', () => { + let app: INestApplicationContext; + let catalog: CatalogService; + + beforeAll(async () => { + const moduleRef = await Test.createTestingModule({ imports: [CatalogModule] }).compile(); + app = moduleRef; + catalog = moduleRef.get(CatalogService); + }); + afterAll(() => app.close()); + beforeEach(resetDatabase); + + it('seeds the committed catalog and can run again', async () => { + const entries = await catalog.load(); + expect(entries.length).toBeGreaterThan(0); + expect(new Set(entries.map((tile) => tile.slug)).size).toBe(entries.length); + expect(await catalog.seed(entries)).toBe(entries.length); + expect(await catalog.seed(entries)).toBe(entries.length); + expect((await sql('SELECT count(*)::int AS n FROM tiles'))[0].n).toBe(entries.length); + }); + + it('updates details, skips tiles without an image and never revives a deleted tile', async () => { + await catalog.seed([entry('a'), entry('b')]); + await sql("UPDATE tiles SET deleted_at = now() WHERE slug = 'b'"); + await catalog.seed([entry('a', { name: 'A renamed' }), entry('b', { name: 'B renamed' }), entry('c', { imageUrl: null })]); + const rows = await sql('SELECT slug, name, deleted_at IS NOT NULL AS deleted FROM tiles ORDER BY slug'); + expect(rows).toEqual([ + { slug: 'a', name: 'A renamed', deleted: false }, + { slug: 'b', name: 'b', deleted: true }, + ]); + }); +}); diff --git a/apps/prevision-api/test/generations.e2e-spec.ts b/apps/prevision-api/test/generations.e2e-spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..d19fa103c17a968b9e28e96e41494dfba8ecc7bd --- /dev/null +++ b/apps/prevision-api/test/generations.e2e-spec.ts @@ -0,0 +1,72 @@ +import type { INestApplication } from '@nestjs/common'; +import { api, createApp, internalToken, resetDatabase, signIn, sql } from './helpers.js'; + +describe('Generations (e2e)', () => { + let app: INestApplication; + let userId: string; + let headers: Record; + + const create = async (jobId: string, token?: string) => + api(app) + .post('/internal/generations') + .set('Authorization', `Bearer ${token ?? (await internalToken())}`) + .send({ userId, jobId }); + + beforeAll(async () => { + app = await createApp(); + }); + afterAll(() => app.close()); + beforeEach(async () => { + await resetDatabase(); + headers = await signIn('user_t'); + userId = (await api(app).get('/api/me').set(headers)).body.data.user.id; + }); + + it('allows 5 generations, then answers 402', async () => { + for (let n = 1; n <= 5; n++) expect((await create(`job${n}`)).status).toBe(201); + const refused = await create('job6'); + expect(refused.status).toBe(402); + expect(refused.body).toEqual({ success: false, error: { code: 'NO_FREE_TRIES', message: expect.any(String) } }); + expect((await api(app).get('/api/me').set(headers)).body.data.usage).toEqual({ plan: 'free', limit: 5, used: 5, remaining: 0, renewsAt: null }); + }); + + it('lets admins generate without a limit', async () => { + await sql("UPDATE users SET role = 'admin' WHERE id = $1", [userId]); + for (let n = 1; n <= 7; n++) expect((await create(`job${n}`)).status).toBe(201); + expect((await api(app).get('/api/me').set(headers)).body.data.usage).toEqual({ plan: 'unlimited', limit: null, used: 7, remaining: null, renewsAt: null }); + }); + + it('gives a try back once when a generation is refunded', async () => { + const created = await create('job1'); + expect(created.body.data).toEqual({ generationId: expect.any(String), usage: { plan: 'free', limit: 5, used: 1, remaining: 4, renewsAt: null } }); + const token = await internalToken(); + for (let n = 0; n < 2; n++) { + await api(app).post(`/internal/generations/${created.body.data.generationId}/refund`).set('Authorization', `Bearer ${token}`).expect(204); + } + expect((await api(app).get('/api/me').set(headers)).body.data.usage.used).toBe(0); + }); + + it('never passes the limit with simultaneous jobs', async () => { + const token = await internalToken(); + const responses = await Promise.all(Array.from({ length: 12 }, (_, n) => create(`burst${n}`, token))); + expect(responses.filter((response) => response.status === 201)).toHaveLength(5); + expect(responses.filter((response) => response.status === 402)).toHaveLength(7); + }); + + it('accepts only the internal token', async () => { + await api(app).post('/internal/generations').send({ userId, jobId: 'j' }).expect(401); + expect((await create('j', await internalToken('prevision-internal', -120))).status).toBe(401); + const browserToken = (await api(app).post('/api/processing-token').set(headers)).body.data.token; + expect((await create('j', browserToken)).status).toBe(401); + }); + + it('validates the request', async () => { + const token = await internalToken(); + await api(app).post('/internal/generations').set('Authorization', `Bearer ${token}`).send({ userId: 'nope', jobId: 'j' }).expect(400); + await api(app).post('/internal/generations').set('Authorization', `Bearer ${token}`).send({ userId, jobId: '../x' }).expect(400); + }); + + it('is not reachable through the /api proxy', async () => { + await api(app).post('/api/internal/generations').expect(404); + }); +}); diff --git a/apps/prevision-api/test/global-setup.ts b/apps/prevision-api/test/global-setup.ts new file mode 100644 index 0000000000000000000000000000000000000000..9fa08e9f7493a90f87335fcd79134cf2ef1d4bdf --- /dev/null +++ b/apps/prevision-api/test/global-setup.ts @@ -0,0 +1,16 @@ +import { execSync } from 'node:child_process'; +import pg from 'pg'; + +const url = process.env.TEST_DATABASE_URL ?? 'postgresql://postgres:postgres@localhost:55432/prevision_api_test'; + +/** A fresh database with the real Prisma migrations. */ +export default async function setup() { + const database = new URL(url).pathname.slice(1); + const admin = new pg.Client({ connectionString: Object.assign(new URL(url), { pathname: '/postgres' }).toString() }); + await admin.connect(); + await admin.query(`DROP DATABASE IF EXISTS "${database}" WITH (FORCE)`); + await admin.query(`CREATE DATABASE "${database}"`); + await admin.end(); + + execSync('pnpm exec prisma migrate deploy', { env: { ...process.env, PREVISION_DATABASE_URL: url }, stdio: 'pipe' }); +} diff --git a/apps/prevision-api/test/helpers.ts b/apps/prevision-api/test/helpers.ts new file mode 100644 index 0000000000000000000000000000000000000000..3082f6b6d90c0b4566506708af9c88a57f4195d1 --- /dev/null +++ b/apps/prevision-api/test/helpers.ts @@ -0,0 +1,124 @@ +import type { INestApplication } from '@nestjs/common'; +import { Test } from '@nestjs/testing'; +import { exportSPKI, generateKeyPair, SignJWT } from 'jose'; +import pg from 'pg'; +import request from 'supertest'; +import { AppModule } from '../src/app.module.js'; +import { setupApp } from '../src/app.setup.js'; +import Stripe from 'stripe'; +import type { Mock } from 'vitest'; +import { ClerkService } from '../src/clerk/clerk.service.js'; +import { STRIPE_CLIENT } from '../src/stripe/stripe.constants.js'; +import type { ClerkProfile } from '../src/clerk/interfaces/clerk.interface.js'; + +const ORIGIN = 'http://app.test'; +const SECRET = new TextEncoder().encode('test-processing-secret-0123456789abcdef012'); +const KID = 'test-key'; +const clerkKeys = await generateKeyPair('RS256'); +export const otherKeys = await generateKeyPair('RS256'); + +// Networkless Clerk verification with a test key (CLERK_JWT_KEY in production). +process.env.CLERK_JWT_KEY = await exportSPKI(clerkKeys.publicKey); + +export const clerkUsers = new Map(); + +/** Stripe in e2e: real webhook signing, stubbed API calls. */ +const realStripe = new Stripe('sk_test_fake'); +interface StripeStub { + webhooks: Stripe['webhooks']; + customers: { create: Mock }; + checkout: { sessions: { create: Mock } }; + billingPortal: { sessions: { create: Mock } }; + subscriptions: { retrieve: Mock }; +} + +export const stripeStub: StripeStub = { + webhooks: realStripe.webhooks, + customers: { create: vi.fn(async () => ({ id: 'cus_e2e' })) }, + checkout: { sessions: { create: vi.fn(async () => ({ url: 'https://checkout.stripe.test/session' })) } }, + billingPortal: { sessions: { create: vi.fn(async () => ({ url: 'https://billing.stripe.test/portal' })) } }, + subscriptions: { retrieve: vi.fn() }, +}; + +export function signedStripeEvent(type: string, object: object) { + const payload = JSON.stringify({ id: `evt_${Date.now()}`, object: 'event', type, data: { object } }); + return { payload, signature: realStripe.webhooks.generateTestHeaderString({ payload, secret: 'whsec_test_secret' }) }; +} + +export async function sessionToken( + sub: string, + { key = clerkKeys.privateKey, azp = ORIGIN, expiresIn = 60, sid = 'sess_1' }: { key?: CryptoKey; azp?: string; expiresIn?: number; sid?: string } = {}, +) { + const now = Math.floor(Date.now() / 1000); + return new SignJWT({ sid, azp }) + .setProtectedHeader({ alg: 'RS256', kid: KID }) + .setIssuer('https://clerk.app.test') + .setSubject(sub) + .setIssuedAt(now - 5) + .setNotBefore(now - 5) + .setExpirationTime(now + expiresIn) + .sign(key); +} + +/** Headers of a signed-in Clerk user that the fake Clerk backend knows. */ +export async function signIn(clerkId: string, email = `${clerkId}@example.com`, name: string | null = 'Test Person') { + clerkUsers.set(clerkId, { email, name }); + return { Authorization: `Bearer ${await sessionToken(clerkId)}`, Origin: ORIGIN }; +} + +export async function internalToken(audience = 'prevision-internal', expiresIn = 60) { + const now = Math.floor(Date.now() / 1000); + return new SignJWT({}).setProtectedHeader({ alg: 'HS256' }).setAudience(audience).setIssuedAt(now).setExpirationTime(now + expiresIn).sign(SECRET); +} + +export async function createApp(): Promise { + const moduleRef = await Test.createTestingModule({ imports: [AppModule] }) + .overrideProvider(ClerkService) + .useFactory({ + factory: (config) => { + const service = new ClerkService(config); + service.getVerifiedProfile = async (id: string) => { + const profile = clerkUsers.get(id); + if (!profile) throw new Error(`unknown Clerk user ${id}`); + return profile; + }; + return service; + }, + inject: [(await import('../src/config/app-config.js')).APP_CONFIG], + }) + .overrideProvider(STRIPE_CLIENT) + .useValue(stripeStub) + .compile(); + const app = setupApp(moduleRef.createNestApplication({ logger: false, rawBody: true })); + await app.listen(0); + return app; +} + +export const api = (app: INestApplication) => request(app.getHttpServer()); + +export async function sql(query: string, values: unknown[] = []) { + const db = new pg.Client({ connectionString: process.env.PREVISION_DATABASE_URL }); + await db.connect(); + try { + return (await db.query(query, values)).rows; + } finally { + await db.end(); + } +} + +export async function resetDatabase() { + await sql('TRUNCATE subscriptions, generations, users, tiles CASCADE'); + clerkUsers.clear(); +} + +export async function insertTiles( + ...tiles: { slug: string; name: string; surfaces?: string[]; deleted?: boolean; collection?: string }[] +) { + for (const tile of tiles) { + await sql( + `INSERT INTO tiles (id, slug, name, surfaces, image_url, deleted_at, collection, render, updated_at) + VALUES (gen_random_uuid(), $1, $2, $3, $4, $5, $6, '{"layout": "grid"}', now())`, + [tile.slug, tile.name, tile.surfaces ?? ['floor'], `https://cdn.test/${tile.slug}.jpg`, tile.deleted ? new Date() : null, tile.collection ?? null], + ); + } +} diff --git a/apps/prevision-api/test/rendering.e2e-spec.ts b/apps/prevision-api/test/rendering.e2e-spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..afec044a3afea3d470eeff25772e508c6fa63779 --- /dev/null +++ b/apps/prevision-api/test/rendering.e2e-spec.ts @@ -0,0 +1,28 @@ +import type { INestApplication } from '@nestjs/common'; +import { jwtVerify } from 'jose'; +import { api, createApp, resetDatabase, signIn } from './helpers.js'; + +const SECRET = new TextEncoder().encode('test-processing-secret-0123456789abcdef012'); + +describe('Rendering (e2e)', () => { + let app: INestApplication; + + beforeAll(async () => { + app = await createApp(); + }); + afterAll(() => app.close()); + beforeEach(resetDatabase); + + it('issues a renderer token for the signed-in account', async () => { + const headers = await signIn('user_r'); + const userId = (await api(app).get('/api/me').set(headers)).body.data.user.id; + const response = await api(app).post('/api/processing-token').set(headers).expect(200); + const { payload } = await jwtVerify(response.body.data.token, SECRET, { audience: 'prevision-processing', issuer: 'prevision-api' }); + expect(payload.sub).toBe(userId); + }); + + it('serves health checks outside /api', async () => { + await api(app).get('/health').expect(200); + expect((await api(app).get('/ready').expect(200)).body).toEqual({ success: true, data: { status: 'ready' } }); + }); +}); diff --git a/apps/prevision-api/test/subscriptions.e2e-spec.ts b/apps/prevision-api/test/subscriptions.e2e-spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..400b88f7c7cd7872d5a24fec3375d325002f4547 --- /dev/null +++ b/apps/prevision-api/test/subscriptions.e2e-spec.ts @@ -0,0 +1,94 @@ +import type { INestApplication } from '@nestjs/common'; +import { api, createApp, internalToken, resetDatabase, signedStripeEvent, signIn, sql, stripeStub } from './helpers.js'; + +describe('Subscriptions (e2e)', () => { + let app: INestApplication; + let headers: Record; + let userId: string; + const now = Math.floor(Date.now() / 1000); + + const stripeSubscription = (overrides: Record = {}) => ({ + id: 'sub_e2e', + status: 'active', + customer: 'cus_e2e', + metadata: { userId }, + cancel_at_period_end: false, + items: { data: [{ price: { id: 'price_starter' }, current_period_start: now - 60, current_period_end: now + 30 * 86_400 }] }, + ...overrides, + }); + + const deliver = (type: string, object: object) => { + const { payload, signature } = signedStripeEvent(type, object); + return api(app).post('/api/webhooks/stripe').set('stripe-signature', signature).set('content-type', 'application/json').send(payload); + }; + + beforeAll(async () => { + app = await createApp(); + }); + afterAll(() => app.close()); + beforeEach(async () => { + await resetDatabase(); + vi.clearAllMocks(); + headers = await signIn('user_pay', 'pay@example.com'); + userId = (await api(app).get('/api/me').set(headers)).body.data.user.id; + }); + + it('opens a Stripe checkout for a plan', async () => { + const response = await api(app).post('/api/subscriptions/checkout').set(headers).send({ plan: 'starter' }).expect(200); + expect(response.body.data).toEqual({ url: 'https://checkout.stripe.test/session' }); + expect((await sql('SELECT stripe_customer_id FROM users WHERE id = $1', [userId]))[0].stripe_customer_id).toBe('cus_e2e'); + await api(app).post('/api/subscriptions/checkout').set(headers).send({ plan: 'platinum' }).expect(400); + }); + + it('activates the plan from a signed webhook and applies its monthly allowance', async () => { + stripeStub.subscriptions.retrieve.mockResolvedValue(stripeSubscription()); + await deliver('checkout.session.completed', { id: 'cs_1', subscription: 'sub_e2e' }).expect(200); + + const current = await api(app).get('/api/subscriptions/current').set(headers).expect(200); + expect(current.body.data).toMatchObject({ plan: 'starter', status: 'active', cancelAtPeriodEnd: false }); + expect((await api(app).get('/api/me').set(headers)).body.data.usage).toMatchObject({ plan: 'starter', limit: 3, used: 0, remaining: 3 }); + + const token = await internalToken(); + const create = (jobId: string) => api(app).post('/internal/generations').set('Authorization', `Bearer ${token}`).send({ userId, jobId }); + for (let n = 1; n <= 3; n++) expect((await create(`job${n}`)).status).toBe(201); + const refused = await create('job4'); + expect(refused.status).toBe(402); + expect(refused.body.error.code).toBe('PLAN_LIMIT_REACHED'); + + await api(app).post('/api/subscriptions/checkout').set(headers).send({ plan: 'growth' }).expect(409); + }); + + it('ends the plan when Stripe cancels the subscription', async () => { + stripeStub.subscriptions.retrieve.mockResolvedValue(stripeSubscription()); + await deliver('customer.subscription.created', { id: 'sub_e2e' }).expect(200); + stripeStub.subscriptions.retrieve.mockResolvedValue(stripeSubscription({ status: 'canceled' })); + await deliver('customer.subscription.deleted', { id: 'sub_e2e' }).expect(200); + expect((await api(app).get('/api/subscriptions/current').set(headers)).body.data).toBeNull(); + expect((await api(app).get('/api/me').set(headers)).body.data.usage.plan).toBe('free'); + expect((await sql('SELECT count(*)::int AS n FROM subscriptions'))[0].n).toBe(1); + }); + + it('refuses webhooks without a valid signature', async () => { + const { payload } = signedStripeEvent('customer.subscription.updated', { id: 'sub_e2e' }); + const response = await api(app) + .post('/api/webhooks/stripe') + .set('stripe-signature', 't=1,v1=forged') + .set('content-type', 'application/json') + .send(payload) + .expect(400); + expect(response.body.error.code).toBe('INVALID_SIGNATURE'); + expect(stripeStub.subscriptions.retrieve).not.toHaveBeenCalled(); + }); + + it('opens the billing portal only for customers', async () => { + await api(app).post('/api/subscriptions/portal').set(headers).expect(404); + await api(app).post('/api/subscriptions/checkout').set(headers).send({ plan: 'growth' }); + const portal = await api(app).post('/api/subscriptions/portal').set(headers).expect(200); + expect(portal.body.data.url).toBe('https://billing.stripe.test/portal'); + }); + + it('requires sign-in for subscription routes', async () => { + await api(app).get('/api/subscriptions/current').expect(401); + await api(app).post('/api/subscriptions/checkout').send({ plan: 'starter' }).expect(401); + }); +}); diff --git a/apps/prevision-api/test/support/test-config.ts b/apps/prevision-api/test/support/test-config.ts new file mode 100644 index 0000000000000000000000000000000000000000..790b7d9fbdbd066f00763393d8cbcd70a6166012 --- /dev/null +++ b/apps/prevision-api/test/support/test-config.ts @@ -0,0 +1,23 @@ +import type { AppConfig } from '../../src/config/app-config.interface.js'; + +/** A complete config for unit tests; override what a test cares about. */ +export const testConfig = (overrides: Partial = {}): AppConfig => ({ + environment: 'test', + port: 0, + databaseUrl: 'postgresql://test', + allowedOrigins: ['http://app.test'], + allowedOriginRegex: null, + clerk: { secretKeys: ['sk_test_fake'] }, + processingToken: { secret: 'test-processing-secret-0123456789abcdef012', ttlSeconds: 600, audience: 'prevision-processing', issuer: 'prevision-api' }, + internalTokenAudience: 'prevision-internal', + freeGenerations: 5, + appUrl: 'https://app.test', + stripe: { + secretKey: 'sk_test_fake', + webhookSecret: 'whsec_test_secret', + plans: { starter: { priceId: 'price_starter', monthlyGenerations: 150 }, growth: { priceId: 'price_growth', monthlyGenerations: 600 } }, + logoUrl: 'https://cdn.test/prevision-logo.png', + portalConfigurationId: 'bpc_test', + }, + ...overrides, +}); diff --git a/apps/prevision-api/test/tiles.e2e-spec.ts b/apps/prevision-api/test/tiles.e2e-spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc4ae3821ed8a2efd569ea49cddc91e066ef02ac --- /dev/null +++ b/apps/prevision-api/test/tiles.e2e-spec.ts @@ -0,0 +1,63 @@ +import type { INestApplication } from '@nestjs/common'; +import { api, createApp, insertTiles, resetDatabase, signIn } from './helpers.js'; + +describe('Tiles (e2e)', () => { + let app: INestApplication; + let headers: Record; + + beforeAll(async () => { + app = await createApp(); + }); + afterAll(() => app.close()); + beforeEach(async () => { + await resetDatabase(); + headers = await signIn('user_tiles'); + await insertTiles( + { slug: 'kd-1', name: 'Juraworld Grey', surfaces: ['floor', 'walls'], collection: 'Juraworld' }, + { slug: 'kd-2', name: 'Juraworld White', surfaces: ['walls'], collection: 'Juraworld' }, + { slug: 'marble', name: 'Black Marble' }, + { slug: 'deleted', name: 'Deleted', deleted: true }, + ); + }); + + it('lists tiles that are not deleted, paginated', async () => { + const response = await api(app).get('/api/tiles').query({ pageSize: 2 }).set(headers).expect(200); + expect(response.body.success).toBe(true); + expect(response.body.data.map((tile: { slug: string }) => tile.slug)).toEqual(['marble', 'kd-1']); + expect(response.body.meta).toEqual({ page: 1, pageSize: 2, total: 3, totalPages: 2 }); + expect(response.body.data[0]).toMatchObject({ imageUrl: 'https://cdn.test/marble.jpg', render: { layout: 'grid' } }); + + const second = await api(app).get('/api/tiles').query({ pageSize: 2, page: 2 }).set(headers); + expect(second.body.data.map((tile: { slug: string }) => tile.slug)).toEqual(['kd-2']); + }); + + it('filters by search, surface and collection, and sorts', async () => { + const response = await api(app).get('/api/tiles').query({ q: 'jura', surface: 'walls', sort: '-name' }).set(headers); + expect(response.body.data.map((tile: { slug: string }) => tile.slug)).toEqual(['kd-2', 'kd-1']); + expect((await api(app).get('/api/tiles').query({ collection: 'Juraworld' }).set(headers)).body.meta.total).toBe(2); + expect((await api(app).get('/api/tiles').query({ q: '%' }).set(headers)).body.meta.total).toBe(0); + }); + + it('counts facets in one response', async () => { + const response = await api(app).get('/api/tiles/facets').set(headers).expect(200); + expect(response.body.data).toEqual({ + total: 3, + surfaces: [ + { value: 'floor', count: 2 }, + { value: 'walls', count: 2 }, + ], + collections: [{ value: 'Juraworld', count: 2 }], + }); + }); + + it('finds one tile by slug', async () => { + expect((await api(app).get('/api/tiles/kd-1').set(headers).expect(200)).body.data.slug).toBe('kd-1'); + expect((await api(app).get('/api/tiles/deleted').set(headers).expect(404)).body.error.code).toBe('TILE_NOT_FOUND'); + }); + + it('rejects invalid queries', async () => { + await api(app).get('/api/tiles').query({ pageSize: 500 }).set(headers).expect(400); + await api(app).get('/api/tiles').query({ sort: 'price' }).set(headers).expect(400); + await api(app).get('/api/tiles/Not_A_Slug').set(headers).expect(400); + }); +}); diff --git a/apps/prevision-api/test/users.e2e-spec.ts b/apps/prevision-api/test/users.e2e-spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..095609d13838e35d5e782901e0f1baef2ed7d886 --- /dev/null +++ b/apps/prevision-api/test/users.e2e-spec.ts @@ -0,0 +1,67 @@ +import type { INestApplication } from '@nestjs/common'; +import { api, clerkUsers, createApp, otherKeys, resetDatabase, sessionToken, signIn, sql } from './helpers.js'; + +describe('Users (e2e)', () => { + let app: INestApplication; + + beforeAll(async () => { + app = await createApp(); + }); + afterAll(() => app.close()); + beforeEach(resetDatabase); + + it('creates the account on the first request with 5 free tries', async () => { + const response = await api(app).get('/api/me').set(await signIn('user_new', 'new@example.com', 'New Person')).expect(200); + expect(response.body).toEqual({ + success: true, + data: { + user: { id: expect.any(String), email: 'new@example.com', name: 'New Person', role: 'user', createdAt: expect.any(String) }, + usage: { plan: 'free', limit: 5, used: 0, remaining: 5, renewsAt: null }, + }, + }); + }); + + it('finds the same account on every later sign-in', async () => { + const headers = await signIn('user_a'); + const first = await api(app).get('/api/me').set(headers); + const again = await api(app) + .get('/api/me') + .set({ Authorization: `Bearer ${await sessionToken('user_a', { sid: 'sess_other_device' })}` }); + expect(again.body.data.user.id).toBe(first.body.data.user.id); + }); + + it('creates a single account when first requests arrive together', async () => { + const headers = await signIn('user_race'); + const responses = await Promise.all(Array.from({ length: 5 }, () => api(app).get('/api/me').set(headers))); + expect(responses.map((response) => response.status)).toEqual([200, 200, 200, 200, 200]); + expect(new Set(responses.map((response) => response.body.data.user.id)).size).toBe(1); + }); + + it('keeps a soft-deleted account closed', async () => { + const me = await api(app).get('/api/me').set(await signIn('user_gone', 'gone@example.com')); + await sql('UPDATE users SET deleted_at = now() WHERE id = $1', [me.body.data.user.id]); + const again = await api(app).get('/api/me').set(await signIn('user_gone_2', 'gone@example.com')).expect(403); + expect(again.body).toEqual({ success: false, error: { code: 'ACCOUNT_DISABLED', message: expect.any(String) } }); + }); + + it.each([ + ['forged', () => sessionToken('user_x', { key: otherKeys.privateKey })], + ['another site', () => sessionToken('user_x', { azp: 'https://evil.test' })], + ['expired', () => sessionToken('user_x', { expiresIn: -120 })], + ['malformed', async () => 'not-a-jwt'], + ])('refuses a %s Clerk token', async (_, token) => { + clerkUsers.set('user_x', { email: 'x@example.com', name: null }); + const response = await api(app).get('/api/me').set('Authorization', `Bearer ${await token()}`).expect(401); + expect(response.body.error.code).toBe('UNAUTHENTICATED'); + }); + + it.each([ + ['get', '/api/me'], + ['get', '/api/tiles'], + ['get', '/api/tiles/facets'], + ['get', '/api/tiles/marble'], + ['post', '/api/processing-token'], + ] as const)('requires sign-in for %s %s', async (method, path) => { + await api(app)[method](path).expect(401); + }); +}); diff --git a/apps/prevision-api/tsconfig.build.json b/apps/prevision-api/tsconfig.build.json new file mode 100644 index 0000000000000000000000000000000000000000..2eafee0e6dbe69f94da01f70cf871e13ff74e8f9 --- /dev/null +++ b/apps/prevision-api/tsconfig.build.json @@ -0,0 +1,8 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src" + }, + "include": ["src"], + "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] +} diff --git a/apps/prevision-api/tsconfig.json b/apps/prevision-api/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..83a904fb0522417a728f814e1111d448543b9442 --- /dev/null +++ b/apps/prevision-api/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "nodenext", + "moduleResolution": "nodenext", + "resolvePackageJsonExports": true, + "esModuleInterop": true, + "isolatedModules": true, + "declaration": true, + "removeComments": true, + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "allowSyntheticDefaultImports": true, + "target": "ES2023", + "sourceMap": true, + "outDir": "./dist", + "rootDir": ".", + "incremental": true, + "skipLibCheck": true, + "strict": true, + "strictPropertyInitialization": false, + "types": ["vitest/globals", "node"] + } +} diff --git a/apps/prevision-api/vitest.config.e2e.ts b/apps/prevision-api/vitest.config.e2e.ts new file mode 100644 index 0000000000000000000000000000000000000000..5cca1906723e930fe8eabb07c4879659a72cf63c --- /dev/null +++ b/apps/prevision-api/vitest.config.e2e.ts @@ -0,0 +1,26 @@ +import { defineConfig } from 'vitest/config'; + +// End-to-end: the real app over HTTP against a real Postgres (see test/setup.ts). +export default defineConfig({ + test: { + globals: true, + root: './', + include: ['test/**/*.e2e-spec.ts'], + globalSetup: ['test/global-setup.ts'], + fileParallelism: false, + env: { + ENVIRONMENT: 'test', + PREVISION_DATABASE_URL: process.env.TEST_DATABASE_URL ?? 'postgresql://postgres:postgres@localhost:55432/prevision_api_test', + CLERK_SECRET_KEY: 'sk_test_fake', + PROCESSING_TOKEN_SECRET: 'test-processing-secret-0123456789abcdef012', + PREVISION_ALLOWED_ORIGINS: 'http://app.test', + FREE_GENERATIONS: '5', + PREVISION_APP_URL: 'https://app.test', + STRIPE_SECRET_KEY: 'sk_test_fake', + STRIPE_WEBHOOK_SECRET: 'whsec_test_secret', + STRIPE_PRICE_STARTER: 'price_starter', + STRIPE_PRICE_GROWTH: 'price_growth', + STARTER_MONTHLY_GENERATIONS: '3', + }, + }, +}); diff --git a/apps/prevision-api/vitest.config.ts b/apps/prevision-api/vitest.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..0f02e4a7563be3b93ae444c2b49c164e0f5531ea --- /dev/null +++ b/apps/prevision-api/vitest.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + globals: true, + root: './', + include: ['src/**/*.spec.ts'], + setupFiles: ['reflect-metadata'], + }, +}); diff --git a/apps/renderer/.devcontainer/Dockerfile b/apps/renderer/.devcontainer/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e1825dce9b1c3d53b748e079ae561d462f817e10 --- /dev/null +++ b/apps/renderer/.devcontainer/Dockerfile @@ -0,0 +1,12 @@ +FROM python:3.12-slim + +RUN apt-get update && \ + apt-get install -y --no-install-recommends ffmpeg libglib2.0-0 && \ + rm -rf /var/lib/apt/lists/* + +COPY requirements-mac.txt . +RUN pip install --no-cache-dir --upgrade pip && \ + pip install --no-cache-dir -r requirements-mac.txt + +WORKDIR /workspace +CMD ["python", "app.py"] diff --git a/apps/renderer/.devcontainer/devcontainer.json b/apps/renderer/.devcontainer/devcontainer.json new file mode 100644 index 0000000000000000000000000000000000000000..33052eebcd935339512de01f9e36849d5b0d51b7 --- /dev/null +++ b/apps/renderer/.devcontainer/devcontainer.json @@ -0,0 +1,22 @@ +{ + "name": "Room-Tiler-Dev", + "build": { + "dockerfile": "Dockerfile", + "context": ".." + }, + + // Forward the Gradio port + "forwardPorts": [7860], + + // Automatically start the app when the container boots + "postCreateCommand": "python /workspace/app.py --share --server-name 0.0.0.0", + + // VS Code features: Python extension, auto-formatting, etc. + "features": { + "ghcr.io/devcontainers/features/python:1": { "version": "3.10" } + }, + + // Sets the default shell + "remoteUser": "root" + } + \ No newline at end of file diff --git a/apps/renderer/.dockerignore b/apps/renderer/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..a88494e1bc717939f13789e1d3803e8dbec70f1a --- /dev/null +++ b/apps/renderer/.dockerignore @@ -0,0 +1,24 @@ +.git +.devcontainer +.cache +__pycache__ +*.py[cod] +*.egg-info +venv/ +.venv/ +env/ +data/uploads/ +data/jobs/ +data/qa-runs/ +.env +*.log +node_modules/ +frontend/viz2d-demo/node_modules/ +frontend/viz2d-demo/dist/ +frontend/viz2d-demo/dist-ssr/ +frontend/viz2d-demo/playwright-report/ +frontend/viz2d-demo/test-results/ +frontend/viz2d-demo/.env +frontend/viz2d-demo/.env.local +frontend/viz2d-demo/.env.*.local +frontend/viz2d-demo/*.tsbuildinfo diff --git a/apps/renderer/.env.example b/apps/renderer/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..d5535e7bd103227dc564e0c142249e70c72fa106 --- /dev/null +++ b/apps/renderer/.env.example @@ -0,0 +1,6 @@ +VISUALIZER_CONFIG=visualizer.local.toml +AUTH_ENFORCEMENT=on +PROCESSING_TOKEN_SECRET=local-development-processing-secret-change-me +PROCESSING_TOKEN_AUDIENCE=prevision-processing +CORS_ALLOWED_ORIGINS=http://localhost:5173 +PREVISION_API_INTERNAL_URL=http://127.0.0.1:8001 diff --git a/apps/renderer/.gitattributes b/apps/renderer/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..a6344aac8c09253b3b630fb776ae94478aa0275b --- /dev/null +++ b/apps/renderer/.gitattributes @@ -0,0 +1,35 @@ +*.7z filter=lfs diff=lfs merge=lfs -text +*.arrow filter=lfs diff=lfs merge=lfs -text +*.bin filter=lfs diff=lfs merge=lfs -text +*.bz2 filter=lfs diff=lfs merge=lfs -text +*.ckpt filter=lfs diff=lfs merge=lfs -text +*.ftz filter=lfs diff=lfs merge=lfs -text +*.gz filter=lfs diff=lfs merge=lfs -text +*.h5 filter=lfs diff=lfs merge=lfs -text +*.joblib filter=lfs diff=lfs merge=lfs -text +*.lfs.* filter=lfs diff=lfs merge=lfs -text +*.mlmodel filter=lfs diff=lfs merge=lfs -text +*.model filter=lfs diff=lfs merge=lfs -text +*.msgpack filter=lfs diff=lfs merge=lfs -text +*.npy filter=lfs diff=lfs merge=lfs -text +*.npz filter=lfs diff=lfs merge=lfs -text +*.onnx filter=lfs diff=lfs merge=lfs -text +*.ot filter=lfs diff=lfs merge=lfs -text +*.parquet filter=lfs diff=lfs merge=lfs -text +*.pb filter=lfs diff=lfs merge=lfs -text +*.pickle filter=lfs diff=lfs merge=lfs -text +*.pkl filter=lfs diff=lfs merge=lfs -text +*.pt filter=lfs diff=lfs merge=lfs -text +*.pth filter=lfs diff=lfs merge=lfs -text +*.rar filter=lfs diff=lfs merge=lfs -text +*.safetensors filter=lfs diff=lfs merge=lfs -text +saved_model/**/* filter=lfs diff=lfs merge=lfs -text +*.tar.* filter=lfs diff=lfs merge=lfs -text +*.tar filter=lfs diff=lfs merge=lfs -text +*.tflite filter=lfs diff=lfs merge=lfs -text +*.tgz filter=lfs diff=lfs merge=lfs -text +*.wasm filter=lfs diff=lfs merge=lfs -text +*.xz filter=lfs diff=lfs merge=lfs -text +*.zip filter=lfs diff=lfs merge=lfs -text +*.zst filter=lfs diff=lfs merge=lfs -text +*tfevents* filter=lfs diff=lfs merge=lfs -text diff --git a/apps/renderer/.gitignore b/apps/renderer/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..1c5d6fe987c490ad1daa51f4c176a829fec0e282 --- /dev/null +++ b/apps/renderer/.gitignore @@ -0,0 +1,52 @@ +# Build output +data/qa-runs + +# Virtual environment +venv/ +.venv/ +env/ + +# Python +__pycache__/ +*.py[cod] +*.pyo +*.pyd +.Python +*.egg-info/ +dist/ +build/ + +# Model cache +.cache/ +~/.cache/huggingface/ + +# ONNX exported models +onnx_models/ + +# Environment variables +.env +.env.local + +# OS +.DS_Store +Thumbs.db + +# IDE +.vscode/ +.idea/ +*.swp +*.swo + +# Runtime data (uploads and processed job files) +data/uploads/ +data/jobs/ + +# Logs +*.log +uvicorn.log + +# Frontend QA runner artifacts when deployed into the Hugging Face Space +node_modules/ +playwright-report/ +test-results/ +*.tsbuildinfo diff --git a/apps/renderer/ARCHITECTURE.md b/apps/renderer/ARCHITECTURE.md new file mode 100644 index 0000000000000000000000000000000000000000..94692a11caef1a2a2a7d13ffdb0627a15b219e0c --- /dev/null +++ b/apps/renderer/ARCHITECTURE.md @@ -0,0 +1,53 @@ +# Floor Visualizer Architecture + +This document summarizes the floor detection and tile rendering pipeline for client communication. + +## Previous Pipeline + +```mermaid +flowchart TD + A[Room image upload] --> B[OneFormer semantic segmentation] + B --> C[Initial floor mask] + C --> D[OpenCV mask cleanup] + D --> E[MoGe / Depth geometry] + E --> F[Floor plane + UV mapping] + F --> G[Canvas tile renderer] + G --> H[Final room preview] +``` + +The previous system mainly depended on semantic segmentation to identify the floor, then used geometry to place the tile texture in perspective. This worked well when the segmentation mask was clean, but weak floor edges, rugs, furniture bleed, and wall/floor boundary mistakes could make the tile placement look less realistic. + +## Current GPU Pipeline + +```mermaid +flowchart TD + A[Room image upload] --> B[OneFormer semantic segmentation] + B --> C[Initial floor class mask] + C --> D[OpenCV edge fixing and mask cleanup] + D --> E[SAM2 mask refinement] + E --> F[MoGe metric geometry] + F --> G[Dominant floor plane filtering] + G --> H[Surface UV / perspective mapping] + H --> I[Lighting and reflection transfer] + I --> J[Material-aware tile renderer] + J --> K[Final room preview] + + E --> L{SAM2 unavailable or weak result?} + L -->|Yes| M[Fallback to cleaned OneFormer mask] + M --> F + L -->|No| F +``` + +## What Changed + +- **OneFormer still detects the floor class.** It remains responsible for identifying which pixels are likely floor. +- **OpenCV edge fixing runs before refinement.** We clean the raw semantic mask with morphology, contour filling, protected wall/object removal, and edge coverage repair before using it downstream. +- **SAM2 now refines the cleaned floor mask on GPU deploy.** SAM2 receives the cleaned floor region as prompt context and improves the actual boundary quality. +- **MoGe geometry validates the floor plane.** After segmentation/refinement, MoGe provides metric geometry so we can reject pixels that do not belong to the dominant floor plane. +- **Rendering now uses material and lighting controls.** The canvas renderer supports tile scale, rotation, grout, roughness, gloss, room light, reflection transfer, and perspective-aware UV mapping. +- **Safe fallback is preserved.** If SAM2 fails to load or produces a weak mask, the backend falls back to the cleaned OneFormer + MoGe path instead of failing the job. + +## Client Summary + +Before, the system used semantic segmentation plus geometry. Now, the GPU pipeline adds a refinement stage: OneFormer finds the floor, OpenCV cleans and fixes the mask edges, SAM2 sharpens the floor boundary, MoGe validates the actual floor plane, and the renderer applies the tile with perspective, lighting, and material controls. This should reduce boundary errors and make the tile look more integrated with the original room. + diff --git a/apps/renderer/Dockerfile b/apps/renderer/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ade52914481906efb5cfe0b756b4220005d8b2a1 --- /dev/null +++ b/apps/renderer/Dockerfile @@ -0,0 +1,68 @@ +FROM python:3.12-slim + +# Set environment variables +ENV PYTHONUNBUFFERED=1 \ + PYTHONDONTWRITEBYTECODE=1 \ + HF_HOME=/home/user/.cache/huggingface \ + VISUALIZER_CONFIG=visualizer.gpu.toml \ + PLAYWRIGHT_BROWSERS_PATH=/ms-playwright \ + QA_FRONTEND_DIR=/app/frontend/viz2d-demo \ + HOME=/home/user + +# Install runtime dependencies plus the tools required by Hugging Face Spaces +# Dev Mode. Dev Mode is enabled only on the staging Space. +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + bash \ + curl \ + git \ + git-lfs \ + procps \ + rsync \ + wget \ + ffmpeg \ + libglib2.0-0 \ + libgomp1 \ + build-essential \ + ca-certificates \ + nodejs \ + npm && \ + rm -rf /var/lib/apt/lists/* + +# Set up a new user named "user" with UID 1000 for Hugging Face permissions +RUN useradd -m -u 1000 user + +WORKDIR /app + +# Copy requirements files first +COPY requirements-base.txt requirements-gpu-cu126.txt ./ + +# Install CUDA PyTorch, MoGe, and the visualizer dependencies for GPU Spaces +RUN pip install --no-cache-dir --upgrade pip && \ + pip install --no-cache-dir -r requirements-gpu-cu126.txt + +# Copy the rest of the application files +COPY --chown=user:1000 . . + +# Install optional Playwright QA runner dependencies when frontend/viz2d-demo +# is included in the Hugging Face Space. +RUN if [ -f frontend/viz2d-demo/package-lock.json ]; then \ + cd frontend/viz2d-demo && \ + npm ci && \ + npx playwright install --with-deps chromium; \ + else \ + echo "frontend/viz2d-demo not found; skipping Playwright QA runner install"; \ + fi && \ + rm -rf /var/lib/apt/lists/* + +# Create writable data directories and change ownership +RUN mkdir -p data/uploads data/jobs data/qa-runs /ms-playwright && \ + chown -R user:1000 /app /ms-playwright + +# Switch to the non-root user +USER user + +# Hugging Face Spaces expects the application on port 7860 +EXPOSE 7860 + +CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "1"] diff --git a/apps/renderer/Dockerfile.hf b/apps/renderer/Dockerfile.hf new file mode 100644 index 0000000000000000000000000000000000000000..ade52914481906efb5cfe0b756b4220005d8b2a1 --- /dev/null +++ b/apps/renderer/Dockerfile.hf @@ -0,0 +1,68 @@ +FROM python:3.12-slim + +# Set environment variables +ENV PYTHONUNBUFFERED=1 \ + PYTHONDONTWRITEBYTECODE=1 \ + HF_HOME=/home/user/.cache/huggingface \ + VISUALIZER_CONFIG=visualizer.gpu.toml \ + PLAYWRIGHT_BROWSERS_PATH=/ms-playwright \ + QA_FRONTEND_DIR=/app/frontend/viz2d-demo \ + HOME=/home/user + +# Install runtime dependencies plus the tools required by Hugging Face Spaces +# Dev Mode. Dev Mode is enabled only on the staging Space. +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + bash \ + curl \ + git \ + git-lfs \ + procps \ + rsync \ + wget \ + ffmpeg \ + libglib2.0-0 \ + libgomp1 \ + build-essential \ + ca-certificates \ + nodejs \ + npm && \ + rm -rf /var/lib/apt/lists/* + +# Set up a new user named "user" with UID 1000 for Hugging Face permissions +RUN useradd -m -u 1000 user + +WORKDIR /app + +# Copy requirements files first +COPY requirements-base.txt requirements-gpu-cu126.txt ./ + +# Install CUDA PyTorch, MoGe, and the visualizer dependencies for GPU Spaces +RUN pip install --no-cache-dir --upgrade pip && \ + pip install --no-cache-dir -r requirements-gpu-cu126.txt + +# Copy the rest of the application files +COPY --chown=user:1000 . . + +# Install optional Playwright QA runner dependencies when frontend/viz2d-demo +# is included in the Hugging Face Space. +RUN if [ -f frontend/viz2d-demo/package-lock.json ]; then \ + cd frontend/viz2d-demo && \ + npm ci && \ + npx playwright install --with-deps chromium; \ + else \ + echo "frontend/viz2d-demo not found; skipping Playwright QA runner install"; \ + fi && \ + rm -rf /var/lib/apt/lists/* + +# Create writable data directories and change ownership +RUN mkdir -p data/uploads data/jobs data/qa-runs /ms-playwright && \ + chown -R user:1000 /app /ms-playwright + +# Switch to the non-root user +USER user + +# Hugging Face Spaces expects the application on port 7860 +EXPOSE 7860 + +CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "1"] diff --git a/apps/renderer/README.md b/apps/renderer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..47de7c98e7a88c7ca4ed9f3e405aa1ec5d83629f --- /dev/null +++ b/apps/renderer/README.md @@ -0,0 +1,114 @@ +--- +title: Floor Visualizer +emoji: 🏆 +colorFrom: indigo +colorTo: purple +sdk: docker +app_port: 7860 +pinned: false +license: mit +short_description: Visualize custom texture or tiles on your floor +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference + +## Local setup + +The Python virtual environment is disposable. To recreate it after deleting `.venv`, +use the platform-specific commands in [SETUP.md](SETUP.md). + +Quick macOS CPU run: + +```bash +python3.12 -m venv .venv +source .venv/bin/activate +python -m pip install --upgrade pip +python -m pip install -r requirements-mac.txt +VISUALIZER_CONFIG=visualizer.local.toml uvicorn app:app --host 0.0.0.0 --port 8002 +``` + +Optional Gemini tile refinement: + +```bash +export GEMINI_API_KEY="your-google-ai-studio-key" +export GEMINI_IMAGE_MODEL="gemini-3.1-flash-image" +``` + +When configured, the frontend can send the final tile-rendered image to +`/gemini/refine-tile-render` for a conservative reflection, shadow, and detail +polish pass. + +Optional DigitalOcean Spaces upload archive in `apps/renderer/.env`: + +```bash +SPACES_BUCKET="your-space-name" +SPACES_REGION="nyc3" +SPACES_ACCESS_KEY_ID="your-spaces-access-key" +SPACES_SECRET_ACCESS_KEY="your-spaces-secret-key" +SPACES_UPLOAD_PREFIX="room-uploads" +``` + +When these are set, `/viz2d/convert` keeps the current frontend flow unchanged +and uploads a copy of each room image to Spaces in the background. + +Visual QA runner: + +```bash +QA_FRONTEND_URL="https://your-vercel-frontend.example" +QA_BACKEND_URL="https://your-backend.example" +QA_FRONTEND_DIR="/mnt/room-editor/frontend/viz2d-demo" +``` + +For Hugging Face, `QA_FRONTEND_DIR` defaults to +`/app/frontend/viz2d-demo` in the Dockerfile. + +The debug visualizer QA page calls `/qa/images`, `/qa/runs`, +`/qa/runs/{run_id}/events`, and `/qa/runs/{run_id}`. `/qa/images` lists +DigitalOcean Spaces directly through the S3 API, deduplicates exact object +matches by `ETag` and size, and does not use a database. `/qa/runs` deduplicates +the selected image keys again, downloads the unique Spaces images into +`data/qa-runs/{run_id}/`, starts the Playwright test suite from +`QA_FRONTEND_DIR`, and stores file-backed run status/results in that run folder. +The Playwright suite uploads each selected image once, then applies the selected +tiles one by one, removing the previous tile before applying the next tile. +`/qa/runs/{run_id}/events` streams run updates as Server-Sent Events so the +debug page does not need to poll while a run is active. Playwright writes +incremental progress after every completed test, so the `completed`, `passed`, +and `failed` counters update before the final report is generated. +`/qa/runs/{run_id}/report` renders a shareable HTML report with screenshot URLs; +`/qa/runs/{run_id}/report.md` returns the compact Markdown summary. + +On Hugging Face, the deploy workflow copies a minimal `frontend/viz2d-demo` QA +runner folder into the Space: npm manifests, Playwright config, e2e tests, and +the Markdown report script. It intentionally does not copy frontend image +assets or `test-images`; real QA images are downloaded from DigitalOcean during +each run. The Dockerfile installs Node, npm, Playwright, and Chromium during the +Space rebuild. For non-Hugging Face servers, install the Node runner +dependencies manually: + +```bash +cd /mnt/room-editor/frontend/viz2d-demo +npm install +npx playwright install --with-deps chromium +``` + +GPU run: + +```bash +python3.12 -m venv .venv +source .venv/bin/activate +python -m pip install --upgrade pip +python -m pip install -r requirements-gpu-cu126.txt +VISUALIZER_CONFIG=visualizer.gpu.toml uvicorn app:app --host 0.0.0.0 --port 8002 +``` + +Hugging Face GPU Spaces use the Dockerfile in this directory. It installs the +CUDA 12.6 PyTorch stack and starts FastAPI on port `7860` with +`visualizer.gpu.toml`. + +The GPU profile uses `shi-labs/oneformer_ade20k_swin_large` for segmentation, +`Ruicheng/moge-2-vitl-normal` for metric point maps, surface normals, and camera +intrinsics, and `depth-anything/Depth-Anything-V2-Metric-Indoor-Large-hf` for +metric depth. If MoGe cannot load or its floor-plane fit is unreliable, the +service falls back to Depth Anything V2 metric depth, then to the existing +image-space homography. diff --git a/apps/renderer/SETUP.md b/apps/renderer/SETUP.md new file mode 100644 index 0000000000000000000000000000000000000000..47a06aa4a0bb4a6b0992afc476f2e41be197a1e9 --- /dev/null +++ b/apps/renderer/SETUP.md @@ -0,0 +1,96 @@ +# Backend Environment Setup + +Use Python 3.12. The `.venv/` directory is disposable and ignored by git. + +## macOS CPU setup + +```bash +cd apps/renderer +python3.12 -m venv .venv +source .venv/bin/activate +python -m pip install --upgrade pip +python -m pip install -r requirements-mac.txt +VISUALIZER_CONFIG=visualizer.local.toml uvicorn app:app --host 0.0.0.0 --port 8002 +``` + +## NVIDIA GPU setup + +Use this on the GPU machine. This installs the CUDA 12.6 PyTorch wheels. + +```bash +cd apps/renderer +python3.12 -m venv .venv +source .venv/bin/activate +python -m pip install --upgrade pip +python -m pip install -r requirements-gpu-cu126.txt +VISUALIZER_CONFIG=visualizer.gpu.toml uvicorn app:app --host 0.0.0.0 --port 8002 +``` + +The first GPU run downloads `shi-labs/oneformer_ade20k_swin_large` and the depth model into the Hugging Face cache. +It also downloads `Ruicheng/moge-2-vitl-normal`, the primary GPU geometry model. + +## Notes + +- Environment variables override TOML values, for example `SEGMENTATION_MODEL=segformer`. +- `requirements.txt` is a full freeze from an existing environment. Prefer the smaller platform files above when recreating `.venv`. + +## Optional DigitalOcean Spaces upload archive + +The `/viz2d/convert` endpoint can copy each uploaded room image to a private +DigitalOcean Spaces bucket in the background without changing the frontend +flow. Add these values to `apps/renderer/.env`: + +```bash +SPACES_BUCKET="your-space-name" +SPACES_REGION="nyc3" +SPACES_ACCESS_KEY_ID="your-spaces-access-key" +SPACES_SECRET_ACCESS_KEY="your-spaces-secret-key" +SPACES_UPLOAD_PREFIX="room-uploads" +``` + +`SPACES_ENDPOINT_URL` is optional and defaults to +`https://$SPACES_REGION.digitaloceanspaces.com`. `SPACES_ACL` defaults to +`private`. + +## Optional visual QA runner + +The backend can also power the debug visualizer QA page without adding a +database. It lists images directly from DigitalOcean Spaces and writes each QA +run under `data/qa-runs/{run_id}/`. + +Backend env: + +```bash +QA_FRONTEND_URL="https://your-vercel-frontend.example" +QA_BACKEND_URL="https://your-backend.example" +QA_FRONTEND_DIR="/mnt/room-editor/frontend/viz2d-demo" +QA_MAX_IMAGES="50" +QA_MAX_TESTS="200" +``` + +For Hugging Face, `QA_FRONTEND_DIR` defaults to +`/app/frontend/viz2d-demo` in the Dockerfile. + +The backend server needs Node and Playwright because the test runner opens the +hosted frontend in Chromium. On Hugging Face, the deploy workflow copies only +the text-based `frontend/viz2d-demo` QA runner files into the Space and the +Dockerfile installs these during rebuild. Real QA images are downloaded from +DigitalOcean during each run. On non-Hugging Face servers, install them +manually: + +```bash +cd /mnt/room-editor/frontend/viz2d-demo +npm install +npx playwright install --with-deps chromium +``` + +The QA endpoints are: + +```text +GET /qa/images +POST /qa/runs +GET /qa/runs/{run_id} +GET /qa/runs/{run_id}/events +GET /qa/runs/{run_id}/report +GET /qa/runs/{run_id}/report.md +``` diff --git a/apps/renderer/app.py b/apps/renderer/app.py new file mode 100644 index 0000000000000000000000000000000000000000..b3770fd466dc01be646557f7cb2bb897c62318c7 --- /dev/null +++ b/apps/renderer/app.py @@ -0,0 +1,56 @@ +"""Floor Visualizer Backend — FastAPI entry point.""" + +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from fastapi.middleware.gzip import GZipMiddleware +from fastapi.staticfiles import StaticFiles + +from config.auth import AUTH_ENFORCED, CORS_ALLOWED_ORIGINS +from config.paths import MATERIAL_DIR, UPLOAD_DIR +from models.loader import warm_start_models +from routes import floor_direction, gemini, materials, qa, segmentation, viz2d + +app = FastAPI() + +app.add_middleware( + CORSMiddleware, + allow_origins=CORS_ALLOWED_ORIGINS, + allow_methods=["*"], + allow_headers=["*"], +) +app.add_middleware(GZipMiddleware, minimum_size=1024, compresslevel=4) + +app.include_router(viz2d.router) +app.include_router(qa.router) +app.include_router(gemini.router) +app.include_router(materials.router) +app.include_router(segmentation.router) +app.include_router(floor_direction.router) + + +@app.get("/health") +def health(): + """Readiness probe for deploy automation. + + Model warm-start runs as a startup event, so uvicorn does not accept + connections until it finishes. A 200 here therefore means "serving", + not merely "container started". + """ + return {"ok": True} + + +@app.on_event("startup") +def startup_warm_start_models(): + warm_start_models() + + +# Uploaded room photos are private once access control is enforced; they are +# then served by the owner-checked /viz2d/jobs/{id}/input route instead. +if not AUTH_ENFORCED: + app.mount("/uploads", StaticFiles(directory=UPLOAD_DIR), name="uploads") +app.mount("/materials", StaticFiles(directory=MATERIAL_DIR), name="materials") + +if __name__ == "__main__": + import uvicorn + + uvicorn.run(app, host="0.0.0.0", port=8002) diff --git a/apps/renderer/config/__init__.py b/apps/renderer/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3871d692f9c2b35c6872a1c4521199d47a93259f --- /dev/null +++ b/apps/renderer/config/__init__.py @@ -0,0 +1 @@ +# Config package for floor visualizer backend. diff --git a/apps/renderer/config/auth.py b/apps/renderer/config/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..9ba2876715db52aefb821ccdf9ee5844c78c8240 --- /dev/null +++ b/apps/renderer/config/auth.py @@ -0,0 +1,35 @@ +"""Prevision renderer authentication and internal allowance service configuration.""" + +from config.loader import config_value + +AUTH_ENFORCEMENT = str(config_value("AUTH_ENFORCEMENT", "auth", "enforcement", "off")).strip().lower() +if AUTH_ENFORCEMENT not in {"off", "on"}: + raise RuntimeError("AUTH_ENFORCEMENT must be 'off' or 'on'") +AUTH_ENFORCED = AUTH_ENFORCEMENT == "on" + +PROCESSING_TOKEN_SECRET = str(config_value("PROCESSING_TOKEN_SECRET", "auth", "processing_token_secret", "")) +PROCESSING_TOKEN_AUDIENCE = str(config_value( + "PROCESSING_TOKEN_AUDIENCE", "auth", "processing_token_audience", "prevision-processing", +)) +TOKEN_ISSUER = str(config_value("TOKEN_ISSUER", "auth", "token_issuer", "prevision-api")) +# The Prevision API (apps/prevision-api) issues processing tokens. Its users have free +# tries: each accepted job is charged to that API, and refunded if it fails. +PREVISION_TOKEN_ISSUER = "prevision-api" +TOKEN_ISSUERS = (TOKEN_ISSUER,) +PREVISION_API_INTERNAL_URL = str(config_value( + "PREVISION_API_INTERNAL_URL", "auth", "prevision_api_internal_url", "http://127.0.0.1:8001", +)).rstrip("/") +PREVISION_INTERNAL_AUDIENCE = "prevision-internal" +# Allowed clock drift between the account API and this service. +TOKEN_LEEWAY_SECONDS = int(config_value("TOKEN_LEEWAY_SECONDS", "auth", "token_leeway_seconds", "30")) + +if AUTH_ENFORCED and len(PROCESSING_TOKEN_SECRET) < 32: + raise RuntimeError("AUTH_ENFORCEMENT=on requires PROCESSING_TOKEN_SECRET (32+ characters)") + +# Comma-separated browser origins. Tokens travel in the Authorization header, +# never in cookies, so a wildcard does not expose ambient credentials. +CORS_ALLOWED_ORIGINS = [ + origin.strip().rstrip("/") + for origin in str(config_value("CORS_ALLOWED_ORIGINS", "auth", "cors_allowed_origins", "*")).split(",") + if origin.strip() +] diff --git a/apps/renderer/config/gemini.py b/apps/renderer/config/gemini.py new file mode 100644 index 0000000000000000000000000000000000000000..f3b30955f7b60eab59c91239bdeb1f86d0745ab7 --- /dev/null +++ b/apps/renderer/config/gemini.py @@ -0,0 +1,56 @@ +from config.loader import config_value + +GEMINI_API_KEY = str(config_value( + "GEMINI_API_KEY", "gemini", "api_key", "", +)).strip() + +GEMINI_IMAGE_MODEL = str(config_value( + "GEMINI_IMAGE_MODEL", "gemini", "image_model", "gemini-3.1-flash-image", +)).strip() + +GEMINI_API_BASE_URL = str(config_value( + "GEMINI_API_BASE_URL", "gemini", "api_base_url", + "https://generativelanguage.googleapis.com/v1beta/models", +)).rstrip("/") + +GEMINI_TIMEOUT_SECONDS = float(config_value( + "GEMINI_TIMEOUT_SECONDS", "gemini", "timeout_seconds", "60", +)) + +# "Enhance with AI" (routes/gemini.py). Smaller requests come back faster: the +# render is sent at most this many pixels on its long side, and the answer is +# requested at this size ("1K" or "2K"; empty = the model's default). +GEMINI_MAX_INPUT_SIDE = int(config_value( + "GEMINI_MAX_INPUT_SIDE", "gemini", "max_input_side", "1536", +)) +GEMINI_IMAGE_SIZE = str(config_value( + "GEMINI_IMAGE_SIZE", "gemini", "image_size", "1K", +)).strip() +# Pattern-drift guard: how much of the render's structure the answer must keep +# (0..1). Below it the answer is retried once, then refused. +GEMINI_MIN_SIMILARITY = float(config_value( + "GEMINI_MIN_SIMILARITY", "gemini", "min_similarity", "0.5", +)) +# Invented-design guard: the largest area (fraction of the image) that was plain +# in the render and patterned in the answer, e.g. a wall the shopper left plain. +GEMINI_MAX_NEW_PATTERN = float(config_value( + "GEMINI_MAX_NEW_PATTERN", "gemini", "max_new_pattern", "0.004", +)) +# Swapped-design guard: the largest area (fraction of the image) whose colour, +# not brightness, changed, e.g. one wall's design repainted with another's. +GEMINI_MAX_RECOLOURED = float(config_value( + "GEMINI_MAX_RECOLOURED", "gemini", "max_recoloured", "0.06", +)) +# Enhancements per organization (or user) per hour, per renderer process. +GEMINI_ENHANCE_PER_HOUR = int(config_value( + "GEMINI_ENHANCE_PER_HOUR", "gemini", "enhance_per_hour", "60", +)) +# Hosts the reference tile images may come from (our tile CDN). +GEMINI_REFERENCE_HOSTS = tuple( + host.strip().lower() + for host in str(config_value( + "GEMINI_REFERENCE_HOSTS", "gemini", "reference_hosts", + "baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com,baetes-space-bucket.sfo3.digitaloceanspaces.com", + )).split(",") + if host.strip() +) diff --git a/apps/renderer/config/lighting.py b/apps/renderer/config/lighting.py new file mode 100644 index 0000000000000000000000000000000000000000..11b982deaeefe42e1b0ef3ec4bf6fb435ee23c1c --- /dev/null +++ b/apps/renderer/config/lighting.py @@ -0,0 +1,10 @@ +LIGHTING_TRANSFER_VERSION = 5 + +SHADE_MAP_MIN = 0.15 +SHADE_MAP_MAX = 1.10 +SHOWROOM_SHADE_MAP_MIN = 0.85 +SHOWROOM_SHADE_MAP_MAX = 1.12 +SHADE_MAP_ENCODING = "linear-relative" + +REFLECTION_MAP_MIN = 0.0 +REFLECTION_MAP_MAX = 1.0 diff --git a/apps/renderer/config/loader.py b/apps/renderer/config/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..98ee433d680e72233004488297c4f0d8e7a95f38 --- /dev/null +++ b/apps/renderer/config/loader.py @@ -0,0 +1,55 @@ +import os +from pathlib import Path + +try: + import tomllib +except ImportError: + try: + import tomli as tomllib # type: ignore[no-redef] + except ImportError: + try: + import tomlkit as tomllib # type: ignore[no-redef] + except ImportError: + raise ImportError( + "No TOML library found. Please run on Python 3.11+, " + "or run 'pip install tomli' to support Python 3.10." + ) + +try: + from dotenv import load_dotenv +except ImportError: + load_dotenv = None + +BACKEND_DIR = Path(__file__).resolve().parent.parent +REPO_ROOT = BACKEND_DIR.parent.parent + +if load_dotenv is not None: + load_dotenv(BACKEND_DIR / ".env") + + +def load_config() -> dict: + config_path = os.getenv("VISUALIZER_CONFIG") + if not config_path: + return {} + path = Path(config_path).expanduser() + if not path.is_absolute(): + path = BACKEND_DIR / path + if not path.exists(): + raise RuntimeError(f"VISUALIZER_CONFIG does not exist: {path}") + with path.open("rb") as config_file: + return tomllib.load(config_file) + + +CONFIG = load_config() + + +def config_value(env_name: str, section: str, key: str, default): + if env_name in os.environ: + return os.environ[env_name] + return CONFIG.get(section, {}).get(key, default) + + +def config_bool(env_name: str, section: str, key: str, default: str = "0") -> bool: + return str(config_value(env_name, section, key, default)).lower() in { + "1", "true", "yes", "on", + } diff --git a/apps/renderer/config/models.py b/apps/renderer/config/models.py new file mode 100644 index 0000000000000000000000000000000000000000..24ca9c0e98332455b071d5772a582636706b37ba --- /dev/null +++ b/apps/renderer/config/models.py @@ -0,0 +1,57 @@ +from config.loader import config_value + +ONEFORMER_MODEL_NAME = str(config_value( + "ONEFORMER_MODEL_NAME", + "models", + "oneformer_model_name", + "shi-labs/oneformer_ade20k_swin_large", +)) + +DEPTH_MODEL_NAME = str(config_value( + "DEPTH_MODEL_NAME", + "models", + "depth_model_name", + "depth-anything/Depth-Anything-V2-Metric-Indoor-Large-hf", +)) + +GEOMETRY_MODEL = str(config_value( + "GEOMETRY_MODEL", + "models", + "geometry_model", + "depth", +)).lower() + +MOGE_MODEL_NAME = str(config_value( + "MOGE_MODEL_NAME", + "models", + "moge_model_name", + "Ruicheng/moge-2-vitl-normal", +)) + +SAM2_MODEL_CFG = str(config_value( + "SAM2_MODEL_CFG", + "models", + "sam2_model_cfg", + "", +)) + +SAM2_CHECKPOINT = str(config_value( + "SAM2_CHECKPOINT", + "models", + "sam2_checkpoint", + "", +)) + +SAM2_MODEL_NAME = str(config_value( + "SAM2_MODEL_NAME", + "models", + "sam2_model_name", + "facebook/sam2-hiera-large", +)) + +INTRINSIC_MODEL_VERSION = str(config_value( + "INTRINSIC_MODEL_VERSION", + "models", + "intrinsic_model_version", + "v2", +)) diff --git a/apps/renderer/config/paths.py b/apps/renderer/config/paths.py new file mode 100644 index 0000000000000000000000000000000000000000..bebd790ee292aa76beccd84f2b79abcb311be859 --- /dev/null +++ b/apps/renderer/config/paths.py @@ -0,0 +1,16 @@ +from pathlib import Path +from config.runtime import VISUALIZER_DATA_DIR + +DATA_DIR = Path(VISUALIZER_DATA_DIR).resolve() +# Sample room photos the frontends offer ("Try a sample room"); free to process. +SAMPLE_DIR = Path(__file__).resolve().parent.parent / "samples" +UPLOAD_DIR = DATA_DIR / "uploads" +JOB_DIR = DATA_DIR / "jobs" +MATERIAL_DIR = DATA_DIR / "materials" +QA_RUN_DIR = DATA_DIR / "qa-runs" +TIMING_BASELINE_PATH = DATA_DIR / "conversion-timings.json" + +UPLOAD_DIR.mkdir(parents=True, exist_ok=True) +JOB_DIR.mkdir(parents=True, exist_ok=True) +MATERIAL_DIR.mkdir(parents=True, exist_ok=True) +QA_RUN_DIR.mkdir(parents=True, exist_ok=True) diff --git a/apps/renderer/config/qa.py b/apps/renderer/config/qa.py new file mode 100644 index 0000000000000000000000000000000000000000..9fb35aa3322e053c44214729903b7293a7618944 --- /dev/null +++ b/apps/renderer/config/qa.py @@ -0,0 +1,31 @@ +from config.loader import REPO_ROOT, config_value +from pathlib import Path + +QA_FRONTEND_URL = str(config_value( + "QA_FRONTEND_URL", "qa", "frontend_url", "", +)).strip().rstrip("/") + +QA_BACKEND_URL = str(config_value( + "QA_BACKEND_URL", "qa", "backend_url", "", +)).strip().rstrip("/") + +QA_FRONTEND_DIR = Path(str(config_value( + "QA_FRONTEND_DIR", "qa", "frontend_dir", + str(REPO_ROOT / "frontend" / "viz2d-demo"), +))).expanduser() + +QA_MAX_IMAGES = max(1, int(config_value( + "QA_MAX_IMAGES", "qa", "max_images", "50", +))) + +QA_MAX_TESTS = max(1, int(config_value( + "QA_MAX_TESTS", "qa", "max_tests", "200", +))) + +QA_RUN_TIMEOUT_SECONDS = max(60, int(config_value( + "QA_RUN_TIMEOUT_SECONDS", "qa", "run_timeout_seconds", "7200", +))) + +QA_PRESIGNED_URL_EXPIRES_SECONDS = max(60, int(config_value( + "QA_PRESIGNED_URL_EXPIRES_SECONDS", "qa", "presigned_url_expires_seconds", "3600", +))) diff --git a/apps/renderer/config/runtime.py b/apps/renderer/config/runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..e218f28ea416eb6461014bab463364178638f9aa --- /dev/null +++ b/apps/renderer/config/runtime.py @@ -0,0 +1,72 @@ +from config.loader import config_bool, config_value + +ENABLE_MOGE_GEOMETRY = config_bool("ENABLE_MOGE_GEOMETRY", "runtime", "enable_moge_geometry", "0") +ENABLE_SAM_REFINEMENT = config_bool("ENABLE_SAM_REFINEMENT", "runtime", "enable_sam_refinement", "0") +ENABLE_FLOOR_MASK_CLEANUP = config_bool("ENABLE_FLOOR_MASK_CLEANUP", "runtime", "enable_floor_mask_cleanup", "1") +ENABLE_DEPTH_ESTIMATION = config_bool("ENABLE_DEPTH_ESTIMATION", "runtime", "enable_depth_estimation", "1") +ENABLE_PLANE_FIT = config_bool("ENABLE_PLANE_FIT", "runtime", "enable_plane_fit", "1") +ENABLE_MULTI_PLANE_SURFACES = config_bool("ENABLE_MULTI_PLANE_SURFACES", "runtime", "enable_multi_plane_surfaces", "1") +ENABLE_WALL_SEGMENTS = config_bool("ENABLE_WALL_SEGMENTS", "runtime", "enable_wall_segments", "0") +ENABLE_INTRINSIC_SHADING = config_bool("ENABLE_INTRINSIC_SHADING", "runtime", "enable_intrinsic_shading", "0") +ENABLE_SHADING_TRANSFER = config_bool("ENABLE_SHADING_TRANSFER", "runtime", "enable_shading_transfer", "1") +ENABLE_FAST_SHADOW_TRANSFER = config_bool( + "ENABLE_FAST_SHADOW_TRANSFER", "runtime", "enable_fast_shadow_transfer", "0", +) +WARM_START_MODELS = config_bool("WARM_START_MODELS", "runtime", "warm_start_models", "1") + +ENABLE_ONNX_INFERENCE = config_bool("ENABLE_ONNX_INFERENCE", "runtime", "enable_onnx_inference", "0") + +ONNX_MODEL_DIR = str(config_value( + "ONNX_MODEL_DIR", "runtime", "onnx_model_dir", "onnx_models", +)) + +BUNDLE_IMAGE_FORMAT = str(config_value( + "BUNDLE_IMAGE_FORMAT", "runtime", "bundle_image_format", "jpeg", +)).lower() + +BUNDLE_IMAGE_QUALITY = int(config_value( + "BUNDLE_IMAGE_QUALITY", "runtime", "bundle_image_quality", "92", +)) + +ROOM_UPLOAD_MAX_DIMENSION = max(720, int(config_value( + "ROOM_UPLOAD_MAX_DIMENSION", "runtime", "room_upload_max_dimension", "1920", +))) + +INFERENCE_MAX_DIMENSION = max(512, int(config_value( + "INFERENCE_MAX_DIMENSION", "runtime", "inference_max_dimension", "1024", +))) + +FAST_SHADOW_MAX_DIMENSION = max(256, min(1024, int(config_value( + "FAST_SHADOW_MAX_DIMENSION", "runtime", "fast_shadow_max_dimension", "640", +)))) + +ROOM_UPLOAD_JPEG_QUALITY = min(95, max(50, int(config_value( + "ROOM_UPLOAD_JPEG_QUALITY", "runtime", "room_upload_jpeg_quality", "85", +)))) + +DEBUG_ARTIFACTS_ENABLED = config_bool( + "DEBUG_ARTIFACTS_ENABLED", "runtime", "debug_artifacts_enabled", "1", +) + +CONVERSION_TARGET_MS = max(5_000, int(config_value( + "CONVERSION_TARGET_MS", "runtime", "conversion_target_ms", "30000", +))) + +# Conversions allowed in flight at once. GPU inference is serialised separately +# (state.gpu_inference), so extra slots overlap one job's CPU stages with +# another's inference; the cap bounds peak memory from full-resolution arrays. +MAX_CONCURRENT_CONVERSIONS = max(1, int(config_value( + "MAX_CONCURRENT_CONVERSIONS", "runtime", "max_concurrent_conversions", "2", +))) + +DEBUG_ARTIFACTS_MAX_DIMENSION = max(320, int(config_value( + "DEBUG_ARTIFACTS_MAX_DIMENSION", "runtime", "debug_artifacts_max_dimension", "1600", +))) + +DEBUG_ARTIFACTS_PREVIEW_DIMENSION = max(320, int(config_value( + "DEBUG_ARTIFACTS_PREVIEW_DIMENSION", "runtime", "debug_artifacts_preview_dimension", "720", +))) + +VISUALIZER_DATA_DIR = str(config_value( + "VISUALIZER_DATA_DIR", "runtime", "data_dir", "data", +)) diff --git a/apps/renderer/config/spaces.py b/apps/renderer/config/spaces.py new file mode 100644 index 0000000000000000000000000000000000000000..b55111510c9963b360a8119ba68b6c2c31d84bec --- /dev/null +++ b/apps/renderer/config/spaces.py @@ -0,0 +1,29 @@ +from config.loader import config_value + +SPACES_BUCKET = str(config_value( + "SPACES_BUCKET", "spaces", "bucket", "", +)).strip() + +SPACES_REGION = str(config_value( + "SPACES_REGION", "spaces", "region", "", +)).strip() + +SPACES_ENDPOINT_URL = str(config_value( + "SPACES_ENDPOINT_URL", "spaces", "endpoint_url", "", +)).strip().rstrip("/") + +SPACES_ACCESS_KEY_ID = str(config_value( + "SPACES_ACCESS_KEY_ID", "spaces", "access_key_id", "", +)).strip() + +SPACES_SECRET_ACCESS_KEY = str(config_value( + "SPACES_SECRET_ACCESS_KEY", "spaces", "secret_access_key", "", +)).strip() + +SPACES_UPLOAD_PREFIX = str(config_value( + "SPACES_UPLOAD_PREFIX", "spaces", "upload_prefix", "room-uploads", +)).strip().strip("/") + +SPACES_ACL = str(config_value( + "SPACES_ACL", "spaces", "acl", "private", +)).strip() diff --git a/apps/renderer/config/surface.py b/apps/renderer/config/surface.py new file mode 100644 index 0000000000000000000000000000000000000000..3362e5a8581717199563740bbbbce280c8994932 --- /dev/null +++ b/apps/renderer/config/surface.py @@ -0,0 +1,162 @@ +from config.loader import config_bool, config_value + +SURFACE_RANSAC_DISTANCE = float(config_value( + "SURFACE_RANSAC_DISTANCE", "surface_mapping", "ransac_distance_threshold", "0.04", +)) + +SURFACE_MAX_PLANES = int(config_value( + "SURFACE_MAX_PLANES", "surface_mapping", "max_planes", "5", +)) + +SURFACE_NORMAL_ANGLE_DEGREES = float(config_value( + "SURFACE_NORMAL_ANGLE_DEGREES", "surface_mapping", "normal_angle_threshold_degrees", "35", +)) + +SURFACE_NORMAL_SMOOTHING_KERNEL = int(config_value( + "SURFACE_NORMAL_SMOOTHING_KERNEL", "surface_mapping", "normal_smoothing_kernel", "5", +)) + +SURFACE_MIN_PLANE_PIXELS = int(config_value( + "SURFACE_MIN_PLANE_PIXELS", "surface_mapping", "min_plane_pixels", "1500", +)) + +SURFACE_EDGE_CLOSE_RATIO = float(config_value( + "SURFACE_EDGE_CLOSE_RATIO", "surface_mapping", "edge_close_ratio", "0.009", +)) + +SURFACE_EDGE_KERNEL_RATIO = float(config_value( + "SURFACE_EDGE_KERNEL_RATIO", "surface_mapping", "edge_kernel_ratio", "0.006", +)) + +# Growing the floor past the segmentation and cutting it back with other class +# masks leaves spikes; edge refinement (below) reaches the real edge instead. +SURFACE_EDGE_DILATION_ITERATIONS = int(config_value( + "SURFACE_EDGE_DILATION_ITERATIONS", "surface_mapping", "edge_dilation_iterations", "0", +)) + +# Floor edge refinement (services/floor/edge_refinement.py): a guided filter +# snaps the low-resolution segmentation edge to the photo's own edges, and the +# floor's edge along walls and doors is redrawn as straight lines. +ENABLE_SURFACE_EDGE_REFINEMENT = config_bool( + "ENABLE_SURFACE_EDGE_REFINEMENT", "surface_mapping", "edge_refinement_enabled", "1", +) + +# Guided filter window radius as a fraction of the short image side (~36px at 1200): +# the segmentation edge can be 10-20px off, and the filter corrects about half its radius. +SURFACE_EDGE_REFINE_RADIUS_RATIO = float(config_value( + "SURFACE_EDGE_REFINE_RADIUS_RATIO", "surface_mapping", "edge_refine_radius_ratio", "0.03", +)) + +# Guided filter regularisation: higher ignores weaker photo edges (floor grain). +SURFACE_EDGE_REFINE_EPS = float(config_value( + "SURFACE_EDGE_REFINE_EPS", "surface_mapping", "edge_refine_eps", "0.002", +)) + +# Wobble within this tolerance (fraction of the short side) along a wall or +# door becomes one straight line. 0 disables straightening. +SURFACE_EDGE_STRAIGHTEN_RATIO = max(0.0, float(config_value( + "SURFACE_EDGE_STRAIGHTEN_RATIO", "surface_mapping", "edge_straighten_ratio", "0.006", +))) + +# Only edge runs along a wall at least this long (fraction of the short side) are straightened. +SURFACE_EDGE_STRAIGHTEN_MIN_RUN_RATIO = float(config_value( + "SURFACE_EDGE_STRAIGHTEN_MIN_RUN_RATIO", "surface_mapping", "edge_straighten_min_run_ratio", "0.04", +)) + +ENABLE_SOFT_FLOOR_COVERING_EXPANSION = config_bool( + "ENABLE_SOFT_FLOOR_COVERING_EXPANSION", "surface_mapping", + "soft_floor_covering_expansion_enabled", "1", +) + +SOFT_FLOOR_COVERING_KERNEL_RATIO = float(config_value( + "SOFT_FLOOR_COVERING_KERNEL_RATIO", "surface_mapping", + "soft_floor_covering_kernel_ratio", "0.008", +)) + +SOFT_FLOOR_COVERING_DILATION_ITERATIONS = int(config_value( + "SOFT_FLOOR_COVERING_DILATION_ITERATIONS", "surface_mapping", + "soft_floor_covering_dilation_iterations", "2", +)) + +SURFACE_UV_MIN_COVERAGE = float(config_value( + "SURFACE_UV_MIN_COVERAGE", "surface_mapping", "uv_min_coverage", "0.995", +)) + +# Within this distance of the floor's edge (fraction of the short image side, +# ~36px at 1200, the edge refinement's reach) UVs blend from the measured depth +# to the fitted floor plane: edge pixels often carry a wall's or a furniture +# foot's 3D point, which smears the tile. 0 disables. +SURFACE_UV_EDGE_BAND_RATIO = max(0.0, float(config_value( + "SURFACE_UV_EDGE_BAND_RATIO", "surface_mapping", "uv_edge_band_ratio", "0.03", +))) + +SURFACE_UV_MAX_BAD_NEIGHBOR_RATIO = float(config_value( + "SURFACE_UV_MAX_BAD_NEIGHBOR_RATIO", "surface_mapping", "uv_max_bad_neighbor_ratio", "0.035", +)) + +SURFACE_UV_MAX_JUMP_RATIO = float(config_value( + "SURFACE_UV_MAX_JUMP_RATIO", "surface_mapping", "uv_max_jump_ratio", "8.0", +)) + +SURFACE_UV_ABSOLUTE_JUMP_METERS = float(config_value( + "SURFACE_UV_ABSOLUTE_JUMP_METERS", "surface_mapping", "uv_absolute_jump_meters", "0.35", +)) + +ENABLE_GEOMETRY_SURFACE_FILTER = config_bool( + "ENABLE_GEOMETRY_SURFACE_FILTER", "surface_mapping", "enable_geometry_surface_filter", "1", +) + +SURFACE_PLANE_DISTANCE_METERS = float(config_value( + "SURFACE_PLANE_DISTANCE_METERS", "surface_mapping", "plane_distance_threshold_meters", "0.12", +)) + +SURFACE_PLANE_NORMAL_MIN_COS = float(config_value( + "SURFACE_PLANE_NORMAL_MIN_COS", "surface_mapping", "plane_normal_min_cos", "0.45", +)) + +SURFACE_PLANE_FILTER_MIN_KEEP_RATIO = float(config_value( + "SURFACE_PLANE_FILTER_MIN_KEEP_RATIO", "surface_mapping", "plane_filter_min_keep_ratio", "0.45", +)) + +# --- Walls ----------------------------------------------------------------- +# Walls use their own plane budget so the floor keeps `max_planes` (1 on GPU) +# no matter how many walls a room has. +WALL_MAX_PLANES = max(1, int(config_value( + "WALL_MAX_PLANES", "surface_mapping", "wall_max_planes", "4", +))) + +WALL_MAX_SEGMENTS = max(1, int(config_value( + "WALL_MAX_SEGMENTS", "surface_mapping", "max_walls", "6", +))) + +# Long-side resolution wall discovery and plane fitting run at. Only the final +# per-wall masks and UVs are produced at full resolution. +WALL_WORK_MAX_DIMENSION = max(256, int(config_value( + "WALL_WORK_MAX_DIMENSION", "surface_mapping", "wall_work_max_dimension", "768", +))) + +# A plane counts as a wall when |normal.y| (camera up component) is at most this. +WALL_MAX_NORMAL_Y = float(config_value( + "WALL_MAX_NORMAL_Y", "surface_mapping", "wall_max_normal_y", "0.45", +)) + +# Planes closer than both limits are merged so one flat wall is never split. +WALL_COPLANAR_ANGLE_DEGREES = float(config_value( + "WALL_COPLANAR_ANGLE_DEGREES", "surface_mapping", "wall_coplanar_angle_degrees", "10", +)) + +WALL_COPLANAR_OFFSET_METERS = float(config_value( + "WALL_COPLANAR_OFFSET_METERS", "surface_mapping", "wall_coplanar_offset_meters", "0.15", +)) + +# Wall outlines are redrawn with straight edges; zig-zag within this tolerance +# (fraction of the short image side, ~6px at 1440) becomes one line. 0 disables. +WALL_EDGE_STRAIGHTEN_RATIO = max(0.0, float(config_value( + "WALL_EDGE_STRAIGHTEN_RATIO", "surface_mapping", "wall_edge_straighten_ratio", "0.004", +))) + +# Minimum share of a wall's pixels that must get a ray/plane UV; below this the +# wall falls back to its contour homography. +WALL_UV_MIN_COVERAGE = float(config_value( + "WALL_UV_MIN_COVERAGE", "surface_mapping", "wall_uv_min_coverage", "0.9", +)) diff --git a/apps/renderer/direction_finder.py b/apps/renderer/direction_finder.py new file mode 100644 index 0000000000000000000000000000000000000000..21f59fa6502195d1852e65ce59ebb3c13bfc386a --- /dev/null +++ b/apps/renderer/direction_finder.py @@ -0,0 +1,1009 @@ +"""Multi-cue floor direction estimation in renderer coordinates.""" + +from dataclasses import asdict, dataclass +import math + +import cv2 +import numpy as np + + +@dataclass(frozen=True) +class DirectionCue: + source: str + angle_degrees: float + confidence: float + support: int + region_support: int + ambiguity_degrees: float | None + details: dict + + def metadata(self) -> dict: + payload = asdict(self) + payload["angleDegrees"] = payload.pop("angle_degrees") + payload["regionSupport"] = payload.pop("region_support") + payload["ambiguityDegrees"] = payload.pop("ambiguity_degrees") + return payload + + +def normalize_angle(angle_degrees: float, period: float = 180.0) -> float: + return float(angle_degrees % period) + + +def angular_distance(first: float, second: float, period: float = 180.0) -> float: + difference = abs((first - second) % period) + return float(min(difference, period - difference)) + + +def periodic_mean( + angles_degrees: np.ndarray, + weights: np.ndarray, + *, + period: float, +) -> tuple[float, float]: + if len(angles_degrees) == 0: + return 0.0, 0.0 + weights = np.maximum(np.asarray(weights, dtype=np.float64), 0.0) + total_weight = float(weights.sum()) + if total_weight <= 1e-9: + return 0.0, 0.0 + phase = np.asarray(angles_degrees, dtype=np.float64) * (2.0 * np.pi / period) + vector_x = float(np.sum(np.cos(phase) * weights)) + vector_y = float(np.sum(np.sin(phase) * weights)) + angle = math.atan2(vector_y, vector_x) * (period / (2.0 * np.pi)) + concentration = math.hypot(vector_x, vector_y) / total_weight + return normalize_angle(angle, period), float(np.clip(concentration, 0.0, 1.0)) + + +def build_surface_uv_grids( + *, + image_shape: tuple[int, int], + surface_uv: np.ndarray | None, + surface_indices: np.ndarray | None, + surface_plane_ids: np.ndarray | None, +) -> tuple[np.ndarray | None, np.ndarray | None]: + height, width = image_shape + if surface_uv is None or surface_indices is None: + return None, None + if surface_uv.ndim != 2 or surface_uv.shape[1] != 2: + return None, None + if len(surface_uv) != len(surface_indices): + return None, None + + flat_size = height * width + indices = np.asarray(surface_indices, dtype=np.int64) + valid_indices = (indices >= 0) & (indices < flat_size) + uv_grid = np.full((flat_size, 2), np.nan, dtype=np.float32) + uv_grid[indices[valid_indices]] = surface_uv[valid_indices].astype(np.float32) + + plane_grid = None + if surface_plane_ids is not None and len(surface_plane_ids) == len(indices): + plane_grid = np.full(flat_size, 255, dtype=np.uint8) + plane_grid[indices[valid_indices]] = surface_plane_ids[valid_indices].astype(np.uint8) + + return ( + uv_grid.reshape(height, width, 2), + plane_grid.reshape(height, width) if plane_grid is not None else None, + ) + + +def rectify_floor_image( + image_rgb: np.ndarray, + surface_mask: np.ndarray, + *, + render_transform: list[float] | np.ndarray | None, + surface_uv: np.ndarray | None, + surface_indices: np.ndarray | None, + surface_plane_ids: np.ndarray | None, +) -> tuple[np.ndarray, np.ndarray, dict] | None: + height, width = surface_mask.shape[:2] + uv_grid, plane_grid = build_surface_uv_grids( + image_shape=(height, width), + surface_uv=surface_uv, + surface_indices=surface_indices, + surface_plane_ids=surface_plane_ids, + ) + if uv_grid is not None: + result = rectify_from_uv(image_rgb, uv_grid, plane_grid) + if result is not None: + gray, mask = result + return gray, mask, {"source": "surface-uv", "width": gray.shape[1], "height": gray.shape[0]} + + transform = normalize_transform(render_transform) + if transform is None: + return None + result = rectify_from_transform(image_rgb, surface_mask, transform) + if result is None: + return None + gray, mask = result + return gray, mask, {"source": "floor-transform", "width": gray.shape[1], "height": gray.shape[0]} + + +def rectify_from_uv( + image_rgb: np.ndarray, + uv_grid: np.ndarray, + plane_grid: np.ndarray | None, +) -> tuple[np.ndarray, np.ndarray] | None: + valid = np.isfinite(uv_grid).all(axis=2) + if plane_grid is not None: + plane_values = plane_grid[valid & (plane_grid != 255)] + if plane_values.size: + dominant_plane = int(np.bincount(plane_values).argmax()) + valid &= plane_grid == dominant_plane + if int(valid.sum()) < 800: + return None + + uv = uv_grid[valid].astype(np.float64) + lower = np.percentile(uv, 0.5, axis=0) + upper = np.percentile(uv, 99.5, axis=0) + span = upper - lower + if not np.isfinite(span).all() or float(np.min(span)) <= 1e-5: + return None + + scale = choose_rectification_scale(span, int(valid.sum())) + output_width = int(np.clip(round(float(span[0]) * scale) + 1, 96, 896)) + output_height = int(np.clip(round(float(span[1]) * scale) + 1, 96, 896)) + if output_width < 96 or output_height < 96: + return None + + gray = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY) + values = gray[valid].astype(np.float64) + xy = np.rint((uv - lower) * scale).astype(np.int32) + xs = np.clip(xy[:, 0], 0, output_width - 1) + ys = np.clip(xy[:, 1], 0, output_height - 1) + flat_indices = ys * output_width + xs + pixel_count = output_width * output_height + counts = np.bincount(flat_indices, minlength=pixel_count) + sums = np.bincount(flat_indices, weights=values, minlength=pixel_count) + covered = counts > 0 + if int(covered.sum()) < max(600, int(pixel_count * 0.1)): + return None + + fill_value = int(np.median(values)) + output = np.full(pixel_count, fill_value, dtype=np.uint8) + output[covered] = np.clip(sums[covered] / counts[covered], 0, 255).astype(np.uint8) + mask = (covered.reshape(output_height, output_width).astype(np.uint8) * 255) + return output.reshape(output_height, output_width), mask + + +def rectify_from_transform( + image_rgb: np.ndarray, + surface_mask: np.ndarray, + transform: np.ndarray, +) -> tuple[np.ndarray, np.ndarray] | None: + ys, xs = np.where(surface_mask > 0) + if len(xs) < 800: + return None + stride = max(1, len(xs) // 30000) + source_points = np.column_stack((xs[::stride], ys[::stride])).astype(np.float32).reshape(1, -1, 2) + mapped = cv2.perspectiveTransform(source_points, transform)[0] + mapped = mapped[np.isfinite(mapped).all(axis=1)] + if len(mapped) < 500: + return None + + lower = np.percentile(mapped, 0.5, axis=0) + upper = np.percentile(mapped, 99.5, axis=0) + span = upper - lower + if not np.isfinite(span).all() or float(np.min(span)) <= 1e-5: + return None + + scale = choose_rectification_scale(span, len(mapped)) + output_width = int(np.clip(round(float(span[0]) * scale) + 1, 96, 896)) + output_height = int(np.clip(round(float(span[1]) * scale) + 1, 96, 896)) + if output_width < 96 or output_height < 96: + return None + + normalization = np.array([ + [scale, 0.0, -float(lower[0]) * scale], + [0.0, scale, -float(lower[1]) * scale], + [0.0, 0.0, 1.0], + ], dtype=np.float64) + warp = normalization @ transform + gray = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY) + rectified = cv2.warpPerspective( + gray, + warp, + (output_width, output_height), + flags=cv2.INTER_LINEAR, + borderMode=cv2.BORDER_REPLICATE, + ) + rectified_mask = cv2.warpPerspective( + (surface_mask > 0).astype(np.uint8) * 255, + warp, + (output_width, output_height), + flags=cv2.INTER_NEAREST, + ) + return rectified, rectified_mask + + +def choose_rectification_scale(span: np.ndarray, sample_count: int) -> float: + aspect = float(span[0] / span[1]) + target_long_side = int(np.clip( + round(math.sqrt(sample_count * max(aspect, 1.0 / aspect))), + 320, + 896, + )) + return target_long_side / max(float(np.max(span)), 1e-6) + + +def estimate_material_cue(gray: np.ndarray, mask: np.ndarray) -> DirectionCue | None: + valid = mask > 0 + if int(valid.sum()) < 1000: + return None + + kernel_size = max(3, int(round(min(gray.shape) * 0.012))) | 1 + inner_mask = cv2.erode(mask, np.ones((kernel_size, kernel_size), dtype=np.uint8)) + if int(np.count_nonzero(inner_mask)) < 800: + inner_mask = mask + valid = inner_mask > 0 + + fill_value = int(np.median(gray[valid])) + prepared = gray.copy() + prepared[~valid] = fill_value + prepared = cv2.createCLAHE(clipLimit=1.8, tileGridSize=(8, 8)).apply(prepared) + sigma = max(3.0, min(gray.shape) / 36.0) + illumination = cv2.GaussianBlur(prepared, (0, 0), sigmaX=sigma) + detail = prepared.astype(np.float32) - illumination.astype(np.float32) + gx = cv2.Sobel(detail, cv2.CV_32F, 1, 0, ksize=3) + gy = cv2.Sobel(detail, cv2.CV_32F, 0, 1, ksize=3) + magnitude = np.hypot(gx, gy) + gradient_values = magnitude[valid] + if gradient_values.size < 800 or float(np.percentile(gradient_values, 90)) < 2.0: + return None + threshold = float(np.percentile(gradient_values, 68)) + + block_angles = [] + block_weights = [] + block_regions = [] + rows, columns = 4, 4 + height, width = gray.shape[:2] + for row in range(rows): + y0, y1 = row * height // rows, (row + 1) * height // rows + for column in range(columns): + x0, x1 = column * width // columns, (column + 1) * width // columns + block_valid = valid[y0:y1, x0:x1] + selected = block_valid & (magnitude[y0:y1, x0:x1] >= threshold) + if int(selected.sum()) < 45: + continue + angles = ( + np.degrees(np.arctan2( + gy[y0:y1, x0:x1][selected], + gx[y0:y1, x0:x1][selected], + )) + + 90.0 + ) % 180.0 + weights = magnitude[y0:y1, x0:x1][selected].astype(np.float64) + angle, concentration = periodic_mean(angles, weights, period=180.0) + if concentration < 0.22: + continue + block_angles.append(angle) + block_weights.append(float(weights.sum()) * concentration) + block_regions.append(row * columns + column) + + tensor_cue = cue_from_region_angles( + source="rectified-structure-tensor", + angles=block_angles, + weights=block_weights, + regions=block_regions, + period=180.0, + minimum_regions=3, + ) + line_cue = estimate_rectified_line_cue(gray, mask) + if line_cue is None: + line_cue = estimate_rectified_line_cue(prepared, mask) + return fuse_material_cues(tensor_cue, line_cue) + + +def estimate_rectified_line_cue(gray: np.ndarray, mask: np.ndarray) -> DirectionCue | None: + detector = cv2.createLineSegmentDetector(cv2.LSD_REFINE_STD) + detected = detector.detect(gray)[0] + if detected is None: + return None + + height, width = gray.shape[:2] + min_length = max(18.0, min(height, width) * 0.055) + angles = [] + weights = [] + regions = [] + for raw_line in detected.reshape(-1, 4): + x1, y1, x2, y2 = [float(value) for value in raw_line] + dx, dy = x2 - x1, y2 - y1 + length = math.hypot(dx, dy) + if length < min_length: + continue + sample_x = np.clip(np.rint(np.linspace(x1, x2, 9)).astype(np.int32), 0, width - 1) + sample_y = np.clip(np.rint(np.linspace(y1, y2, 9)).astype(np.int32), 0, height - 1) + mask_support = float(np.mean(mask[sample_y, sample_x] > 0)) + if mask_support < 0.78: + continue + midpoint_x = (x1 + x2) * 0.5 + midpoint_y = (y1 + y2) * 0.5 + angles.append(normalize_angle(math.degrees(math.atan2(dy, dx)))) + weights.append(length * mask_support) + regions.append( + min(3, int(midpoint_y * 4 / max(height, 1))) * 4 + + min(3, int(midpoint_x * 4 / max(width, 1))) + ) + + return cue_from_region_angles( + source="rectified-repeated-lines", + angles=angles, + weights=weights, + regions=regions, + period=180.0, + minimum_regions=3, + ) + + +def cue_from_region_angles( + *, + source: str, + angles: list[float], + weights: list[float], + regions: list[int], + period: float, + minimum_regions: int, +) -> DirectionCue | None: + if len(angles) < 4: + return None + angle_array = np.asarray(angles, dtype=np.float64) + weight_array = np.asarray(weights, dtype=np.float64) + angle, concentration = periodic_mean(angle_array, weight_array, period=period) + tolerance = 12.0 if period == 180.0 else 9.0 + agreement = np.array( + [angular_distance(float(value), angle, period) <= tolerance for value in angle_array], + dtype=bool, + ) + if int(agreement.sum()) < 4: + return None + agreeing_regions = {region for region, keep in zip(regions, agreement, strict=False) if keep} + if len(agreeing_regions) < minimum_regions: + return None + + agreement_ratio = float(weight_array[agreement].sum() / max(float(weight_array.sum()), 1e-6)) + region_score = min(1.0, len(agreeing_regions) / 7.0) + support_score = min(1.0, int(agreement.sum()) / 12.0) + confidence = float(np.clip( + 0.38 * concentration + + 0.28 * agreement_ratio + + 0.20 * region_score + + 0.14 * support_score, + 0.0, + 1.0, + )) + if confidence < 0.48: + return None + return DirectionCue( + source=source, + angle_degrees=round(angle, 3), + confidence=round(confidence, 3), + support=int(agreement.sum()), + region_support=len(agreeing_regions), + ambiguity_degrees=None, + details={ + "concentration": round(concentration, 4), + "agreementRatio": round(agreement_ratio, 4), + }, + ) + + +def fuse_material_cues( + tensor_cue: DirectionCue | None, + line_cue: DirectionCue | None, +) -> DirectionCue | None: + if tensor_cue is None: + return line_cue + if line_cue is None: + return tensor_cue + difference = angular_distance(tensor_cue.angle_degrees, line_cue.angle_degrees) + if difference > 15.0: + stronger = max((tensor_cue, line_cue), key=lambda cue: cue.confidence) + return DirectionCue( + source=stronger.source, + angle_degrees=stronger.angle_degrees, + confidence=round(stronger.confidence * 0.72, 3), + support=stronger.support, + region_support=stronger.region_support, + ambiguity_degrees=None, + details={**stronger.details, "cueDisagreementDegrees": round(difference, 3)}, + ) + + angles = np.array([tensor_cue.angle_degrees, line_cue.angle_degrees]) + weights = np.array([tensor_cue.confidence, line_cue.confidence]) + angle, concentration = periodic_mean(angles, weights, period=180.0) + confidence = float(np.clip( + max(tensor_cue.confidence, line_cue.confidence) * 0.72 + + min(tensor_cue.confidence, line_cue.confidence) * 0.28 + + concentration * 0.08, + 0.0, + 1.0, + )) + return DirectionCue( + source="rectified-material-consensus", + angle_degrees=round(angle, 3), + confidence=round(confidence, 3), + support=tensor_cue.support + line_cue.support, + region_support=max(tensor_cue.region_support, line_cue.region_support), + ambiguity_degrees=None, + details={ + "tensorAngleDegrees": tensor_cue.angle_degrees, + "lineAngleDegrees": line_cue.angle_degrees, + "cueAgreementDegrees": round(difference, 3), + }, + ) + + +def normalize_vector(vector: np.ndarray) -> np.ndarray | None: + vector = np.asarray(vector, dtype=np.float64) + length = float(np.linalg.norm(vector)) + if not np.isfinite(vector).all() or length <= 1e-7: + return None + return vector / length + + +def normalize_transform(value: list[float] | np.ndarray | None) -> np.ndarray | None: + if value is None: + return None + transform = np.asarray(value, dtype=np.float64) + if transform.size != 9: + return None + transform = transform.reshape(3, 3) + if not np.isfinite(transform).all() or abs(float(np.linalg.det(transform))) < 1e-12: + return None + return transform + + +def world_direction_to_render_angle( + direction: np.ndarray, + *, + render_u_axis: np.ndarray | None, + render_v_axis: np.ndarray | None, + intrinsics: np.ndarray | None, + render_transform: np.ndarray | None, +) -> float | None: + direction = normalize_vector(direction) + if direction is None: + return None + if render_u_axis is not None and render_v_axis is not None: + u_axis = normalize_vector(render_u_axis) + v_axis = normalize_vector(render_v_axis) + if u_axis is not None and v_axis is not None: + return normalize_angle(math.degrees(math.atan2( + float(direction @ v_axis), + float(direction @ u_axis), + ))) + + if intrinsics is None or render_transform is None: + return None + intrinsics = np.asarray(intrinsics, dtype=np.float64).reshape(3, 3) + vanishing_point = intrinsics @ direction + mapped = render_transform @ vanishing_point + if not np.isfinite(mapped).all() or float(np.linalg.norm(mapped[:2])) <= 1e-7: + return None + return normalize_angle(math.degrees(math.atan2(float(mapped[1]), float(mapped[0])))) + + +def choose_depth_axis( + base_angle_degrees: float, + *, + floor_normal: np.ndarray, + render_u_axis: np.ndarray | None, + render_v_axis: np.ndarray | None, + intrinsics: np.ndarray | None, + render_transform: np.ndarray | None, +) -> float: + camera_forward = np.array([0.0, 0.0, 1.0], dtype=np.float64) + floor_normal = normalize_vector(floor_normal) + if floor_normal is None: + return normalize_angle(base_angle_degrees) + projected_forward = camera_forward - floor_normal * float(camera_forward @ floor_normal) + forward_angle = world_direction_to_render_angle( + projected_forward, + render_u_axis=render_u_axis, + render_v_axis=render_v_axis, + intrinsics=intrinsics, + render_transform=render_transform, + ) + first = normalize_angle(base_angle_degrees) + second = normalize_angle(base_angle_degrees + 90.0) + if forward_angle is None: + return first + return first if angular_distance(first, forward_angle) <= angular_distance(second, forward_angle) else second + + +def estimate_wall_normal_cue( + normals_map: np.ndarray | None, + valid_mask: np.ndarray | None, + wall_mask: np.ndarray, + *, + floor_normal: np.ndarray, + render_u_axis: np.ndarray | None, + render_v_axis: np.ndarray | None, + intrinsics: np.ndarray | None, + render_transform: np.ndarray | None, +) -> DirectionCue | None: + if normals_map is None or normals_map.shape[:2] != wall_mask.shape: + return None + floor_normal = normalize_vector(floor_normal) + if floor_normal is None: + return None + + lengths = np.linalg.norm(normals_map, axis=2) + valid = (wall_mask > 0) & np.isfinite(normals_map).all(axis=2) & (lengths > 1e-4) + if valid_mask is not None and valid_mask.shape == wall_mask.shape: + valid &= valid_mask.astype(bool) + normalized = np.zeros_like(normals_map, dtype=np.float64) + normalized[valid] = normals_map[valid] / lengths[valid, None] + vertical_alignment = np.abs(normalized @ floor_normal) + valid &= vertical_alignment <= 0.42 + ys, xs = np.where(valid) + if len(xs) < 250: + return None + + stride = max(1, len(xs) // 6000) + ys, xs = ys[::stride], xs[::stride] + normals = normalized[ys, xs] + horizontal = normals - (normals @ floor_normal)[:, None] * floor_normal + horizontal_lengths = np.linalg.norm(horizontal, axis=1) + keep = horizontal_lengths > 0.6 + horizontal = horizontal[keep] / horizontal_lengths[keep, None] + ys, xs = ys[keep], xs[keep] + if len(horizontal) < 200: + return None + + angles = [] + weights = [] + regions = [] + height, width = wall_mask.shape + for direction, y, x in zip(horizontal, ys, xs, strict=False): + angle = world_direction_to_render_angle( + direction, + render_u_axis=render_u_axis, + render_v_axis=render_v_axis, + intrinsics=intrinsics, + render_transform=render_transform, + ) + if angle is None: + continue + angles.append(angle % 90.0) + weights.append(1.0) + regions.append(min(3, int(y * 4 / max(height, 1))) * 4 + min(3, int(x * 4 / max(width, 1)))) + if len(angles) < 200: + return None + + base_angle, concentration = periodic_mean( + np.asarray(angles), + np.asarray(weights), + period=90.0, + ) + agreement = np.array( + [angular_distance(angle, base_angle, 90.0) <= 10.0 for angle in angles], + dtype=bool, + ) + agreeing_regions = {region for region, accepted in zip(regions, agreement, strict=False) if accepted} + if int(agreement.sum()) < 160 or len(agreeing_regions) < 2: + return None + agreement_ratio = float(agreement.mean()) + confidence = float(np.clip( + 0.46 * concentration + + 0.30 * agreement_ratio + + 0.14 * min(1.0, len(agreeing_regions) / 6.0) + + 0.10 * min(1.0, int(agreement.sum()) / 1200.0), + 0.0, + 1.0, + )) + angle = choose_depth_axis( + base_angle, + floor_normal=floor_normal, + render_u_axis=render_u_axis, + render_v_axis=render_v_axis, + intrinsics=intrinsics, + render_transform=render_transform, + ) + return DirectionCue( + source="wall-normal-manhattan", + angle_degrees=round(angle, 3), + confidence=round(confidence, 3), + support=int(agreement.sum()), + region_support=len(agreeing_regions), + ambiguity_degrees=90.0, + details={ + "baseAxisDegrees": round(base_angle, 3), + "concentration": round(concentration, 4), + "agreementRatio": round(agreement_ratio, 4), + }, + ) + + +def estimate_architectural_line_cue( + image_rgb: np.ndarray, + structure_mask: np.ndarray, + *, + floor_normal: np.ndarray, + render_u_axis: np.ndarray | None, + render_v_axis: np.ndarray | None, + intrinsics: np.ndarray | None, + render_transform: np.ndarray | None, +) -> DirectionCue | None: + if intrinsics is None: + return None + floor_normal = normalize_vector(floor_normal) + if floor_normal is None: + return None + intrinsics = np.asarray(intrinsics, dtype=np.float64).reshape(3, 3) + + gray = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY) + detector = cv2.createLineSegmentDetector(cv2.LSD_REFINE_STD) + detected = detector.detect(gray)[0] + if detected is None: + return None + + height, width = gray.shape + minimum_length = max(30.0, min(height, width) * 0.07) + vertical_vanishing = intrinsics @ floor_normal + finite_vertical = abs(float(vertical_vanishing[2])) > 1e-7 + vertical_xy = ( + vertical_vanishing[:2] / vertical_vanishing[2] + if finite_vertical + else vertical_vanishing[:2] + ) + + angles = [] + weights = [] + regions = [] + for raw_line in detected.reshape(-1, 4): + x1, y1, x2, y2 = [float(value) for value in raw_line] + line_vector = np.array([x2 - x1, y2 - y1], dtype=np.float64) + length = float(np.linalg.norm(line_vector)) + if length < minimum_length: + continue + line_unit = line_vector / length + sample_x = np.clip(np.rint(np.linspace(x1, x2, 11)).astype(np.int32), 0, width - 1) + sample_y = np.clip(np.rint(np.linspace(y1, y2, 11)).astype(np.int32), 0, height - 1) + structure_support = float(np.mean(structure_mask[sample_y, sample_x] > 0)) + if structure_support < 0.58: + continue + + midpoint = np.array([(x1 + x2) * 0.5, (y1 + y2) * 0.5], dtype=np.float64) + vertical_direction = vertical_xy - midpoint if finite_vertical else vertical_xy + vertical_length = float(np.linalg.norm(vertical_direction)) + if vertical_length > 1e-6: + vertical_direction /= vertical_length + if abs(float(line_unit @ vertical_direction)) >= math.cos(math.radians(14.0)): + continue + + p1 = np.array([x1, y1, 1.0], dtype=np.float64) + p2 = np.array([x2, y2, 1.0], dtype=np.float64) + image_line = np.cross(p1, p2) + interpretation_plane = intrinsics.T @ image_line + world_direction = np.cross(interpretation_plane, floor_normal) + angle = world_direction_to_render_angle( + world_direction, + render_u_axis=render_u_axis, + render_v_axis=render_v_axis, + intrinsics=intrinsics, + render_transform=render_transform, + ) + if angle is None: + continue + angles.append(angle % 90.0) + weights.append(length * structure_support) + regions.append( + min(3, int(midpoint[1] * 4 / max(height, 1))) * 4 + + min(3, int(midpoint[0] * 4 / max(width, 1))) + ) + + base_cue = cue_from_region_angles( + source="architectural-manhattan", + angles=angles, + weights=weights, + regions=regions, + period=90.0, + minimum_regions=3, + ) + if base_cue is None: + return None + angle = choose_depth_axis( + base_cue.angle_degrees, + floor_normal=floor_normal, + render_u_axis=render_u_axis, + render_v_axis=render_v_axis, + intrinsics=intrinsics, + render_transform=render_transform, + ) + return DirectionCue( + source=base_cue.source, + angle_degrees=round(angle, 3), + confidence=base_cue.confidence, + support=base_cue.support, + region_support=base_cue.region_support, + ambiguity_degrees=90.0, + details={**base_cue.details, "baseAxisDegrees": base_cue.angle_degrees}, + ) + + +def fuse_structural_cues(cues: list[DirectionCue]) -> DirectionCue | None: + cues = [cue for cue in cues if cue is not None and cue.confidence >= 0.42] + if not cues: + return None + if len(cues) == 1: + return cues[0] + + base_angles = np.array([cue.angle_degrees % 90.0 for cue in cues]) + weights = np.array([cue.confidence for cue in cues]) + angle, concentration = periodic_mean(base_angles, weights, period=90.0) + disagreement = max( + angular_distance(float(value), angle, 90.0) + for value in base_angles + ) + if disagreement > 14.0: + strongest = max(cues, key=lambda cue: cue.confidence) + return DirectionCue( + source=strongest.source, + angle_degrees=strongest.angle_degrees, + confidence=round(strongest.confidence * 0.72, 3), + support=strongest.support, + region_support=strongest.region_support, + ambiguity_degrees=90.0, + details={**strongest.details, "structuralCueDisagreementDegrees": round(disagreement, 3)}, + ) + + strongest = max(cues, key=lambda cue: cue.confidence) + representative = strongest.angle_degrees + if angular_distance(representative, angle) > angular_distance(representative + 90.0, angle): + representative += 90.0 + confidence = float(np.clip( + np.average([cue.confidence for cue in cues], weights=weights) + + concentration * 0.12, + 0.0, + 1.0, + )) + return DirectionCue( + source="room-manhattan-consensus", + angle_degrees=round(normalize_angle(representative), 3), + confidence=round(confidence, 3), + support=sum(cue.support for cue in cues), + region_support=max(cue.region_support for cue in cues), + ambiguity_degrees=90.0, + details={ + "cueSources": [cue.source for cue in cues], + "baseAxisDegrees": round(angle, 3), + "concentration": round(concentration, 4), + "cueDisagreementDegrees": round(disagreement, 3), + }, + ) + + +def select_direction( + material_cue: DirectionCue | None, + structural_cue: DirectionCue | None, +) -> tuple[DirectionCue | None, str]: + if material_cue is not None and material_cue.confidence >= 0.82: + if structural_cue is None: + return material_cue, "strong-material-direction" + axis_difference = min( + angular_distance(material_cue.angle_degrees, structural_cue.angle_degrees), + angular_distance(material_cue.angle_degrees, structural_cue.angle_degrees + 90.0), + ) + if axis_difference <= 14.0: + boosted = DirectionCue( + source="material-room-consensus", + angle_degrees=material_cue.angle_degrees, + confidence=round(min(1.0, material_cue.confidence * 0.78 + structural_cue.confidence * 0.30), 3), + support=material_cue.support + structural_cue.support, + region_support=max(material_cue.region_support, structural_cue.region_support), + ambiguity_degrees=None, + details={ + "materialSource": material_cue.source, + "structuralSource": structural_cue.source, + "axisDifferenceDegrees": round(axis_difference, 3), + }, + ) + return boosted, "material-and-room-agree" + return material_cue, "strong-diagonal-material-direction" + + if structural_cue is not None and structural_cue.confidence >= 0.52: + return structural_cue, "room-structure-direction" + if material_cue is not None and material_cue.confidence >= 0.62: + return material_cue, "moderate-material-direction" + return None, "insufficient-observable-direction-evidence" + + +def direction_label(angle_degrees: float) -> str: + angle = normalize_angle(angle_degrees) + if angle < 12.0 or angle >= 168.0: + return "across_render_u" + if 78.0 <= angle < 102.0: + return "along_render_v" + return "diagonal" + + +def direction_axis_for_overlay( + *, + angle_degrees: float, + image_shape: tuple[int, int], + surface_mask: np.ndarray, + surface_uv: np.ndarray | None, + surface_indices: np.ndarray | None, + surface_plane_ids: np.ndarray | None, + render_transform: np.ndarray | None, +) -> dict | None: + height, width = image_shape + direction = np.array([ + math.cos(math.radians(angle_degrees)), + math.sin(math.radians(angle_degrees)), + ]) + if surface_uv is not None and surface_indices is not None and len(surface_uv) == len(surface_indices): + valid = np.isfinite(surface_uv).all(axis=1) + if surface_plane_ids is not None and len(surface_plane_ids) == len(surface_uv): + plane_values = surface_plane_ids[valid & (surface_plane_ids != 255)] + if plane_values.size: + dominant_plane = int(np.bincount(plane_values.astype(np.int64)).argmax()) + valid &= surface_plane_ids == dominant_plane + uv = surface_uv[valid] + indices = np.asarray(surface_indices)[valid] + if len(uv) >= 100: + center = np.median(uv, axis=0) + span = np.percentile(uv, 95, axis=0) - np.percentile(uv, 5, axis=0) + radius = max(float(np.min(span)) * 0.28, 1e-3) + endpoints = [center - direction * radius, center + direction * radius] + image_points = [] + for endpoint in endpoints: + nearest = int(np.argmin(np.sum((uv - endpoint) ** 2, axis=1))) + pixel_index = int(indices[nearest]) + image_points.append((float(pixel_index % width), float(pixel_index // width))) + return { + "startX": image_points[0][0], + "startY": image_points[0][1], + "endX": image_points[1][0], + "endY": image_points[1][1], + "source": "surface-uv", + } + + if render_transform is None: + return None + ys, xs = np.where(surface_mask > 0) + if len(xs) < 50: + return None + sample_points = np.column_stack((xs, ys)).astype(np.float32).reshape(1, -1, 2) + mapped = cv2.perspectiveTransform(sample_points, render_transform.astype(np.float32))[0] + finite = np.isfinite(mapped).all(axis=1) + mapped = mapped[finite] + if len(mapped) < 50: + return None + center = np.median(mapped, axis=0) + span = np.percentile(mapped, 95, axis=0) - np.percentile(mapped, 5, axis=0) + radius = max(float(np.min(span)) * 0.28, 1e-3) + floor_points = np.array( + [[center - direction * radius, center + direction * radius]], + dtype=np.float32, + ) + inverse = np.linalg.inv(render_transform).astype(np.float32) + image_points = cv2.perspectiveTransform(floor_points, inverse)[0] + if not np.isfinite(image_points).all(): + return None + return { + "startX": float(image_points[0, 0]), + "startY": float(image_points[0, 1]), + "endX": float(image_points[1, 0]), + "endY": float(image_points[1, 1]), + "source": "floor-transform", + } + + +def find_floor_direction( + image_rgb: np.ndarray, + surface_mask: np.ndarray, + *, + wall_mask: np.ndarray, + structure_mask: np.ndarray, + normals_map: np.ndarray | None, + geometry_valid_mask: np.ndarray | None, + intrinsics: np.ndarray | list[float] | None, + floor_normal: np.ndarray | list[float] | None, + render_u_axis: np.ndarray | list[float] | None, + render_v_axis: np.ndarray | list[float] | None, + render_transform: np.ndarray | list[float] | None, + surface_uv: np.ndarray | None, + surface_indices: np.ndarray | None, + surface_plane_ids: np.ndarray | None, +) -> dict: + height, width = surface_mask.shape[:2] + transform = normalize_transform(render_transform) + camera_matrix = None + if intrinsics is not None: + raw_intrinsics = np.asarray(intrinsics, dtype=np.float64) + if raw_intrinsics.size == 9 and np.isfinite(raw_intrinsics).all(): + camera_matrix = raw_intrinsics.reshape(3, 3) + normal = normalize_vector(np.asarray(floor_normal)) if floor_normal is not None else None + u_axis = normalize_vector(np.asarray(render_u_axis)) if render_u_axis is not None else None + v_axis = normalize_vector(np.asarray(render_v_axis)) if render_v_axis is not None else None + + rectified = rectify_floor_image( + image_rgb, + surface_mask, + render_transform=transform, + surface_uv=surface_uv, + surface_indices=surface_indices, + surface_plane_ids=surface_plane_ids, + ) + material_cue = estimate_material_cue(rectified[0], rectified[1]) if rectified is not None else None + + wall_cue = None + architecture_cue = None + if normal is not None: + wall_cue = estimate_wall_normal_cue( + normals_map, + geometry_valid_mask, + wall_mask, + floor_normal=normal, + render_u_axis=u_axis, + render_v_axis=v_axis, + intrinsics=camera_matrix, + render_transform=transform, + ) + architecture_cue = estimate_architectural_line_cue( + image_rgb, + structure_mask, + floor_normal=normal, + render_u_axis=u_axis, + render_v_axis=v_axis, + intrinsics=camera_matrix, + render_transform=transform, + ) + structural_cue = fuse_structural_cues([ + cue for cue in (wall_cue, architecture_cue) if cue is not None + ]) + selected, selection_reason = select_direction(material_cue, structural_cue) + + warnings = [] + needs_user_direction = selected is None + if selected is None: + selected = DirectionCue( + source="canonical-render-axis", + angle_degrees=0.0, + confidence=0.0, + support=0, + region_support=0, + ambiguity_degrees=90.0, + details={"reason": "direction-is-not-observable-in-this-image"}, + ) + warnings.append("direction_not_observable_user_rotation_recommended") + if selected.ambiguity_degrees is not None: + warnings.append("direction_has_90_degree_axis_ambiguity") + + axis = direction_axis_for_overlay( + angle_degrees=selected.angle_degrees, + image_shape=(height, width), + surface_mask=surface_mask, + surface_uv=surface_uv, + surface_indices=surface_indices, + surface_plane_ids=surface_plane_ids, + render_transform=transform, + ) + floor_area_ratio = float(np.count_nonzero(surface_mask)) / max(int(surface_mask.size), 1) + return { + "source": "backend-direction-finder-v2", + "directionMethod": selected.source, + "selectionReason": selection_reason, + "angleDegrees": selected.angle_degrees, + "renderAngleDegrees": selected.angle_degrees, + "secondaryAngleDegrees": normalize_angle(selected.angle_degrees + 90.0), + "directionLabel": direction_label(selected.angle_degrees), + "confidence": selected.confidence, + "floorAreaRatio": round(floor_area_ratio, 4), + "lineCount": 0, + "dominantLineCount": 0, + "gridPatternDetected": bool(material_cue and material_cue.ambiguity_degrees == 90.0), + "axisAmbiguous90": selected.ambiguity_degrees == 90.0, + "needsUserDirection": needs_user_direction, + "warnings": warnings, + "dominantLines": [], + "directionAxis": axis, + "rectification": rectified[2] if rectified is not None else None, + "cues": { + "material": material_cue.metadata() if material_cue is not None else None, + "wallNormals": wall_cue.metadata() if wall_cue is not None else None, + "architecture": architecture_cue.metadata() if architecture_cue is not None else None, + "structural": structural_cue.metadata() if structural_cue is not None else None, + }, + } diff --git a/apps/renderer/enums.py b/apps/renderer/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..8c45f40edcff35ad1621a73f2032d3665cd9bf99 --- /dev/null +++ b/apps/renderer/enums.py @@ -0,0 +1,90 @@ +"""Shared string enumerations for the floor-visualizer backend.""" + +from enum import StrEnum + + +class JobStatus(StrEnum): + QUEUED = "QUEUED" + PROCESSING = "PROCESSING" + PREVIEW_READY = "PREVIEW_READY" + COMPLETED = "COMPLETED" + FAILED = "FAILED" + + +class PipelinePhase(StrEnum): + SEGMENTATION = "segmentation" + MASKING = "masking" + GEOMETRY = "geometry" + SURFACE_MAPPING = "surface-mapping" + LIGHTING = "lighting" + DIRECTION = "direction" + PACKAGING = "packaging" + + +class TextureMappingMode(StrEnum): + REGULARIZED_FLOOR_PLANE = "regularized-floor-plane" + SURFACE_UV = "surface-uv" + WALL_PLANE = "wall-plane" + WALL_CONTOUR_HOMOGRAPHY = "wall-contour-homography" + + +class TextureMappingReason(StrEnum): + SURFACE_UV_UNAVAILABLE = "surface-uv-unavailable" + EMPTY_SURFACE = "empty-surface" + INCOMPLETE_SURFACE_UV = "incomplete-surface-uv" + INSUFFICIENT_UV_NEIGHBORS = "insufficient-uv-neighbors" + NOISY_SURFACE_UV = "noisy-surface-uv" + SURFACE_UV_QUALITY_OK = "surface-uv-quality-ok" + MULTI_PLANE_SURFACE_UV_QUALITY_OK = "multi-plane-surface-uv-quality-ok" + + +class GeometryProvider(StrEnum): + HOMOGRAPHY = "homography" + MOGE_2 = "moge-2" + RELATIVE_DEPTH = "relative-depth" + DEPTH_ANYTHING_METRIC = "depth-anything-metric" + DEPTH_ANYTHING = "depth-anything" + METRIC_DEPTH = "metric-depth" + WALL_DEPTH = "wall-depth" + WALL_CONTOUR_HOMOGRAPHY = "wall-contour-homography" + + +class LightingSource(StrEnum): + LUMINANCE = "luminance" + INTRINSIC = "intrinsic" # prefix, actual value is f"intrinsic-{version}" + + +class FloorMaskSource(StrEnum): + PRIMARY_FLOOR = "primary-floor" + FLOOR_SURFACE_FALLBACK = "floor-surface-fallback" + + +class PlaneFitMode(StrEnum): + NORMAL_AWARE = "normal-aware" + RANSAC = "ransac" + + +class IntrinsicAlignment(StrEnum): + UNCHECKED = "intrinsic-unchecked" + ALIGNED = "intrinsic-aligned" + LOW_CONFIDENCE = "intrinsic-low-confidence" + INVERTED_CORRECTED = "intrinsic-inverted-corrected" + + +class QaStatus(StrEnum): + QUEUED = "queued" + RUNNING = "running" + COMPLETED = "completed" + FAILED = "failed" + CANCELLED = "cancelled" + + +class QaResult(StrEnum): + PASSED = "passed" + FAILED = "failed" + SKIPPED = "skipped" + + +class SurfaceType(StrEnum): + FLOOR = "floor" + WALL = "wall" diff --git a/apps/renderer/errors.py b/apps/renderer/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..4f2f892ec357c83c5084994ab4ab2ef34492943a --- /dev/null +++ b/apps/renderer/errors.py @@ -0,0 +1,36 @@ +"""Reusable HTTP error helpers.""" + +from fastapi import HTTPException + + +def bad_request(detail: str, cause: Exception | None = None) -> HTTPException: + exc = HTTPException(status_code=400, detail=detail) + if cause is not None: + raise exc from cause + raise exc + + +def not_found(detail: str = "Not found.") -> HTTPException: + raise HTTPException(status_code=404, detail=detail) + + +def conflict(detail: str) -> HTTPException: + raise HTTPException(status_code=409, detail=detail) + + +def server_error(detail: str) -> HTTPException: + raise HTTPException(status_code=500, detail=detail) + + +def service_unavailable(detail: str, cause: Exception | None = None) -> HTTPException: + exc = HTTPException(status_code=503, detail=detail) + if cause is not None: + raise exc from cause + raise exc + + +def bad_gateway(detail: str, cause: Exception | None = None) -> HTTPException: + exc = HTTPException(status_code=502, detail=detail) + if cause is not None: + raise exc from cause + raise exc diff --git a/apps/renderer/floor_direction.py b/apps/renderer/floor_direction.py new file mode 100644 index 0000000000000000000000000000000000000000..a8d0e4c776f51db7c5d99f1a80b2c695fc62e6af --- /dev/null +++ b/apps/renderer/floor_direction.py @@ -0,0 +1,1813 @@ +"""Floor direction analysis helpers for the FastAPI room editor backend.""" + +from dataclasses import dataclass +import math +from typing import Any + +import cv2 +import numpy as np + +@dataclass(frozen=True) +class FloorPolygon: + points: list[tuple[float, float]] + bbox: tuple[float, float, float, float] | None = None + + +@dataclass(frozen=True) +class FloorSegmentation: + label: str + confidence: float + polygons: list[FloorPolygon] + source_path: str = "root" + raw_keys: list[str] | None = None + warnings: list[str] | None = None + source_width: int | None = None + source_height: int | None = None + + +def parse_floor_segmentation(payload: Any) -> FloorSegmentation: + root_payload = payload + payload, source_path, parse_warnings = find_segmentation_payload(payload) + raw_keys = sorted(payload.keys()) if isinstance(payload, dict) else [] + + if not isinstance(payload, dict): + return FloorSegmentation( + label="unknown", + confidence=0.0, + polygons=[], + source_path=source_path, + raw_keys=raw_keys, + warnings=parse_warnings + ["segmentation_response_not_object"], + ) + + source_width = extract_int_value(payload.get("width")) or extract_int_value( + root_payload.get("width") if isinstance(root_payload, dict) else None + ) + source_height = extract_int_value(payload.get("height")) or extract_int_value( + root_payload.get("height") if isinstance(root_payload, dict) else None + ) + + label = str(payload.get("label") or payload.get("class") or payload.get("name") or "unknown") + + try: + confidence = float(payload.get("confidence", payload.get("score", 0.0))) + except (TypeError, ValueError): + confidence = 0.0 + + polygons: list[FloorPolygon] = [] + for polygon_payload in extract_polygon_payloads(payload): + if not isinstance(polygon_payload, dict): + continue + + raw_points = polygon_payload.get("points") or polygon_payload.get("polygon") or [] + points: list[tuple[float, float]] = [] + + for point in raw_points: + if not isinstance(point, (list, tuple)) or len(point) < 2: + continue + try: + points.append((float(point[0]), float(point[1]))) + except (TypeError, ValueError): + continue + + raw_bbox = polygon_payload.get("bbox") + bbox = None + if isinstance(raw_bbox, (list, tuple)) and len(raw_bbox) >= 4: + try: + bbox = ( + float(raw_bbox[0]), + float(raw_bbox[1]), + float(raw_bbox[2]), + float(raw_bbox[3]), + ) + except (TypeError, ValueError): + bbox = None + + if len(points) >= 3: + polygons.append(FloorPolygon(points=points, bbox=bbox)) + + return FloorSegmentation( + label=label, + confidence=max(0.0, min(1.0, confidence)), + polygons=polygons, + source_path=source_path, + raw_keys=raw_keys, + warnings=parse_warnings, + source_width=source_width, + source_height=source_height, + ) + + +def extract_int_value(value: Any) -> int | None: + try: + parsed = int(round(float(value))) + except (TypeError, ValueError): + return None + return parsed if parsed > 0 else None + + +def find_segmentation_payload(payload: Any) -> tuple[Any, str, list[str]]: + warnings: list[str] = [] + + if isinstance(payload, list): + floor_item = find_floor_item(payload) + if floor_item is not None: + return floor_item, "root[floor]", warnings + if any(isinstance(item, dict) and has_polygon_data(item) for item in payload): + warnings.append("segmentation_response_list_without_floor_label") + return {"label": "unknown", "polygons": []}, "root", warnings + return payload, "root", warnings + + if not isinstance(payload, dict): + return payload, "root", warnings + + if has_polygon_data(payload): + return payload, "root", warnings + + for key in ( + "floor", + "data", + "result", + "results", + "prediction", + "predictions", + "segments", + "response", + "output", + ): + nested = payload.get(key) + if nested is None: + continue + + if isinstance(nested, dict) and has_polygon_data(nested): + return nested, f"root.{key}", warnings + + if isinstance(nested, list): + floor_item = find_floor_item(nested) + if floor_item is not None: + return floor_item, f"root.{key}[floor]", warnings + if any(isinstance(item, dict) and has_polygon_data(item) for item in nested): + warnings.append("segmentation_response_list_without_floor_label") + + warnings.append("segmentation_response_missing_polygons") + return payload, "root", warnings + + +def has_polygon_data(payload: dict[str, Any]) -> bool: + return bool(extract_polygon_payloads(payload)) + + +def find_floor_item(items: list[Any]) -> dict[str, Any] | None: + for item in items: + if not isinstance(item, dict): + continue + label = str(item.get("label") or item.get("class") or item.get("name") or "").lower() + if label == "floor" and has_polygon_data(item): + return item + return None + + +def extract_polygon_payloads(payload: dict[str, Any]) -> list[Any]: + raw_polygons = payload.get("polygons") + if isinstance(raw_polygons, list): + return raw_polygons + + raw_polygon = payload.get("polygon") + if isinstance(raw_polygon, list): + if raw_polygon and all(isinstance(point, (list, tuple)) for point in raw_polygon): + return [{"points": raw_polygon}] + return raw_polygon + + raw_points = payload.get("points") + if isinstance(raw_points, list): + return [{"points": raw_points}] + + return [] + + +@dataclass(frozen=True) +class DetectedLine: + x1: int + y1: int + x2: int + y2: int + angle_degrees: float + length: float + + +@dataclass(frozen=True) +class TextureOrientation: + angle_degrees: float + confidence: float + support: int + concentration: float + + +@dataclass(frozen=True) +class LineFamilyCluster: + line_indices: list[int] + angle_degrees: float + weight: float + concentration: float + distinct_offset_count: int + score: float + + +@dataclass(frozen=True) +class DirectionResult: + angle_degrees: float | None + secondary_angle_degrees: float | None + direction_label: str + confidence: float + floor_area_ratio: float + line_count: int + dominant_line_count: int + grid_pattern_detected: bool + dominant_lines: list[DetectedLine] + warnings: list[str] + overlay_bgr: np.ndarray | None = None + render_angle_degrees: float | None = None + + +def analyze_floor_direction( + image_bgr: np.ndarray, + segmentation: FloorSegmentation, + *, + include_overlay: bool = False, + render_transform: list[float] | np.ndarray | None = None, + surface_uv: np.ndarray | None = None, + surface_indices: np.ndarray | None = None, + surface_plane_ids: np.ndarray | None = None, +) -> DirectionResult: + height, width = image_bgr.shape[:2] + warnings: list[str] = list(segmentation.warnings or []) + + warnings.extend(uploaded_image_quality_warnings(image_bgr)) + + mask = build_floor_mask( + width=width, + height=height, + polygons=segmentation.polygons, + source_width=segmentation.source_width, + source_height=segmentation.source_height, + ) + floor_pixels = int(np.count_nonzero(mask)) + total_pixels = height * width + floor_area_ratio = floor_pixels / total_pixels if total_pixels else 0.0 + + if segmentation.confidence < 0.75: + warnings.append("low_segmentation_confidence") + if segmentation_dimensions_differ(segmentation.source_width, segmentation.source_height, width, height): + warnings.append("segmentation_coordinate_scale_applied") + if not segmentation.polygons or floor_pixels == 0: + warnings.append("no_floor_polygon_detected") + return DirectionResult( + angle_degrees=None, + secondary_angle_degrees=None, + direction_label="unknown", + confidence=0.0, + floor_area_ratio=0.0, + line_count=0, + dominant_line_count=0, + grid_pattern_detected=False, + dominant_lines=[], + warnings=warnings, + overlay_bgr=create_overlay(image_bgr, mask, [], None) if include_overlay else None, + ) + if floor_area_ratio < 0.03: + warnings.append("floor_area_too_small") + + inner_mask = erode_mask(mask) + if int(np.count_nonzero(inner_mask)) == 0: + inner_mask = mask + + lines = detect_candidate_lines(image_bgr, inner_mask) + hough_orientation = dominant_orientation(lines, image_shape=inner_mask.shape[:2]) + texture_orientation = estimate_texture_orientation(image_bgr, inner_mask) + selected_orientation = select_orientation(hough_orientation, texture_orientation, warnings) + + if selected_orientation is None: + warnings.append("no_strong_floor_lines_detected") + return DirectionResult( + angle_degrees=None, + secondary_angle_degrees=None, + direction_label="unknown", + confidence=0.0, + floor_area_ratio=floor_area_ratio, + line_count=0, + dominant_line_count=0, + grid_pattern_detected=False, + dominant_lines=[], + warnings=warnings, + overlay_bgr=create_overlay(image_bgr, mask, [], None) if include_overlay else None, + ) + + angle_degrees, orientation_source = selected_orientation + render_angle_degrees = estimate_surface_uv_grout_rotation( + lines, + image_bgr=image_bgr, + surface_uv=surface_uv, + surface_indices=surface_indices, + surface_plane_ids=surface_plane_ids, + image_shape=(height, width), + ) + if render_angle_degrees is not None: + warnings.append("grout_direction_projected_to_surface_uv") + else: + render_angle_degrees = estimate_rectified_grout_rotation( + lines, + render_transform=render_transform, + ) + if render_angle_degrees is not None: + warnings.append("grout_direction_rectified_for_renderer") + dominant_lines: list[DetectedLine] = [] + peak_weight_ratio = 0.0 + concentration = 0.0 + orthogonal_ratio = 0.0 + if hough_orientation is not None: + ( + _hough_angle, + dominant_lines, + peak_weight_ratio, + concentration, + orthogonal_ratio, + ) = hough_orientation + secondary_angle_degrees = detect_secondary_grid_angle( + lines=lines, + primary_angle_degrees=angle_degrees, + primary_line_count=len(dominant_lines), + ) + grid_pattern_detected = secondary_angle_degrees is not None + + if len(dominant_lines) < 5: + warnings.append("weak_line_support") + if orthogonal_ratio > 0.65: + warnings.append("possible_square_tile_grid_or_ambiguous_perpendicular_lines") + if grid_pattern_detected: + warnings.append("grid_pattern_detected") + if orientation_source == "texture": + warnings.append("texture_orientation_used") + elif orientation_source == "combined": + warnings.append("hough_texture_orientation_combined") + + hough_confidence = score_confidence( + segmentation_confidence=segmentation.confidence, + floor_area_ratio=floor_area_ratio, + line_count=len(lines), + dominant_line_count=len(dominant_lines), + peak_weight_ratio=peak_weight_ratio, + concentration=concentration, + ) + texture_confidence = 0.0 + if texture_orientation is not None: + texture_confidence = score_texture_confidence( + segmentation_confidence=segmentation.confidence, + floor_area_ratio=floor_area_ratio, + texture_confidence=texture_orientation.confidence, + ) + confidence = final_orientation_confidence( + source=orientation_source, + hough_confidence=hough_confidence, + texture_confidence=texture_confidence, + ) + + direction_label = label_direction(angle_degrees) + overlay = ( + create_overlay(image_bgr, mask, lines, angle_degrees, secondary_angle_degrees) + if include_overlay + else None + ) + + return DirectionResult( + angle_degrees=round(angle_degrees, 2), + secondary_angle_degrees=round(secondary_angle_degrees, 2) + if secondary_angle_degrees is not None + else None, + direction_label=direction_label, + confidence=round(confidence, 3), + floor_area_ratio=round(floor_area_ratio, 4), + line_count=len(lines), + dominant_line_count=len(dominant_lines), + grid_pattern_detected=grid_pattern_detected, + dominant_lines=dominant_lines[:30], + warnings=warnings, + overlay_bgr=overlay, + render_angle_degrees=render_angle_degrees, + ) + + +def build_floor_mask( + *, + width: int, + height: int, + polygons: list[FloorPolygon], + source_width: int | None = None, + source_height: int | None = None, +) -> np.ndarray: + mask = np.zeros((height, width), dtype=np.uint8) + scale_x = width / source_width if source_width and source_width > 0 else 1.0 + scale_y = height / source_height if source_height and source_height > 0 else 1.0 + + for polygon in polygons: + points = np.array(polygon.points, dtype=np.float32) + if points.shape[0] < 3: + continue + + points[:, 0] *= scale_x + points[:, 1] *= scale_y + points[:, 0] = np.clip(points[:, 0], 0, width - 1) + points[:, 1] = np.clip(points[:, 1], 0, height - 1) + int_points = np.round(points).astype(np.int32) + cv2.fillPoly(mask, [int_points], 255) + + kernel_size = max(3, int(round(min(width, height) * 0.008))) + if kernel_size % 2 == 0: + kernel_size += 1 + kernel = np.ones((kernel_size, kernel_size), dtype=np.uint8) + return cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) + + +def segmentation_dimensions_differ( + source_width: int | None, + source_height: int | None, + image_width: int, + image_height: int, +) -> bool: + if not source_width or not source_height: + return False + return abs(source_width - image_width) > 2 or abs(source_height - image_height) > 2 + + +def uploaded_image_quality_warnings(image_bgr: np.ndarray) -> list[str]: + if largest_flat_row_region_ratio(image_bgr) >= 0.35: + return ["uploaded_image_contains_large_flat_filled_region"] + return [] + + +def largest_flat_row_region_ratio(image_bgr: np.ndarray) -> float: + height, width = image_bgr.shape[:2] + if height == 0 or width == 0: + return 0.0 + + gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY) + row_std = np.std(gray, axis=1) + flat_rows = row_std < 4.0 + + longest_run = 0 + current_run = 0 + for is_flat in flat_rows: + if bool(is_flat): + current_run += 1 + longest_run = max(longest_run, current_run) + else: + current_run = 0 + + return longest_run / height + + +def erode_mask(mask: np.ndarray) -> np.ndarray: + height, width = mask.shape[:2] + kernel_size = max(5, int(round(min(width, height) * 0.015))) + if kernel_size % 2 == 0: + kernel_size += 1 + kernel = np.ones((kernel_size, kernel_size), dtype=np.uint8) + return cv2.erode(mask, kernel, iterations=1) + + +def detect_candidate_lines(image_bgr: np.ndarray, mask: np.ndarray) -> list[DetectedLine]: + height, width = image_bgr.shape[:2] + floor_pixels = max(1, int(np.count_nonzero(mask))) + gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY) + + inside_pixels = gray[mask > 0] + fill_value = int(np.median(inside_pixels)) if inside_pixels.size else int(np.median(gray)) + prepared = gray.copy() + prepared[mask == 0] = fill_value + + clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) + enhanced = clahe.apply(prepared) + blurred = cv2.GaussianBlur(enhanced, (5, 5), 0) + + min_dimension = min(width, height) + min_line_length = max(28, int(min_dimension * 0.055)) + max_line_gap = max(8, int(min_dimension * 0.025)) + hough_threshold = max(18, int(math.sqrt(floor_pixels) * 0.035)) + + grout_edges = detect_grout_edges(enhanced, mask) + grout_lines = detect_hough_lines_from_edges( + grout_edges, + min_line_length=max(20, int(min_dimension * 0.045)), + max_line_gap=max(10, int(min_dimension * 0.03)), + thresholds=[ + max(10, int(math.sqrt(floor_pixels) * 0.02)), + max(8, int(math.sqrt(floor_pixels) * 0.015)), + ], + ) + grout_lines = deduplicate_lines(grout_lines) + if has_usable_grout_line_support(grout_lines, image_shape=(height, width)): + return grout_lines + + attempts = [ + (50, 150, hough_threshold, min_line_length), + (30, 100, max(12, int(hough_threshold * 0.75)), max(20, int(min_line_length * 0.8))), + (80, 220, hough_threshold, min_line_length), + ] + + best_lines: list[DetectedLine] = [] + for canny_low, canny_high, threshold, min_length in attempts: + edges = cv2.Canny(blurred, canny_low, canny_high) + edges = cv2.bitwise_and(edges, mask) + + raw_lines = cv2.HoughLinesP( + edges, + rho=1, + theta=np.pi / 180, + threshold=threshold, + minLineLength=min_length, + maxLineGap=max_line_gap, + ) + lines = normalize_hough_lines(raw_lines, min_length=min_length) + if len(lines) > len(best_lines): + best_lines = lines + if len(best_lines) >= 12: + break + + return deduplicate_lines(best_lines) + + +def detect_grout_edges(enhanced_gray: np.ndarray, mask: np.ndarray) -> np.ndarray: + height, width = enhanced_gray.shape[:2] + min_dimension = min(width, height) + if min_dimension <= 0 or int(np.count_nonzero(mask)) < 100: + return np.zeros_like(enhanced_gray) + + kernel_size = max(7, int(round(min_dimension * 0.018))) + if kernel_size % 2 == 0: + kernel_size += 1 + kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (kernel_size, kernel_size)) + + dark_response = cv2.morphologyEx(enhanced_gray, cv2.MORPH_BLACKHAT, kernel) + light_response = cv2.morphologyEx(enhanced_gray, cv2.MORPH_TOPHAT, kernel) + response = cv2.max(dark_response, light_response) + response = cv2.GaussianBlur(response, (3, 3), 0) + response = cv2.bitwise_and(response, mask) + + valid_response = response[mask > 0] + valid_response = valid_response[valid_response > 0] + if valid_response.size < 80: + return np.zeros_like(enhanced_gray) + + percentile_threshold = float(np.percentile(valid_response, 84)) + spread_threshold = float(np.mean(valid_response) + np.std(valid_response) * 0.35) + threshold = max(5.0, min(percentile_threshold, spread_threshold)) + + binary = np.zeros_like(response) + binary[response >= threshold] = 255 + cleanup_kernel = np.ones((3, 3), dtype=np.uint8) + binary = cv2.morphologyEx(binary, cv2.MORPH_OPEN, cleanup_kernel) + binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, cleanup_kernel) + + low_threshold = max(3, int(round(threshold * 0.45))) + high_threshold = max(low_threshold + 3, int(round(threshold * 1.35))) + edges = cv2.Canny(response, low_threshold, high_threshold) + support = cv2.dilate(binary, cleanup_kernel, iterations=1) + edges = cv2.bitwise_and(edges, support) + return cv2.bitwise_and(edges, mask) + + +def detect_hough_lines_from_edges( + edges: np.ndarray, + *, + min_line_length: int, + max_line_gap: int, + thresholds: list[int], +) -> list[DetectedLine]: + if int(np.count_nonzero(edges)) < max(24, min_line_length): + return [] + + best_lines: list[DetectedLine] = [] + for threshold in thresholds: + raw_lines = cv2.HoughLinesP( + edges, + rho=1, + theta=np.pi / 180, + threshold=threshold, + minLineLength=min_line_length, + maxLineGap=max_line_gap, + ) + lines = normalize_hough_lines(raw_lines, min_length=min_line_length) + if len(lines) > len(best_lines): + best_lines = lines + + return best_lines + + +def has_usable_grout_line_support( + lines: list[DetectedLine], + *, + image_shape: tuple[int, int], +) -> bool: + if len(lines) < 3: + return False + + clusters = cluster_line_families(lines, image_shape=image_shape) + if not clusters: + return False + + best_cluster = max(clusters, key=lambda cluster: cluster.score) + if best_cluster.concentration < 0.70: + return False + + return ( + len(best_cluster.line_indices) >= 4 + and best_cluster.distinct_offset_count >= 2 + ) or ( + len(best_cluster.line_indices) >= 3 + and best_cluster.distinct_offset_count >= 3 + ) + + +def normalize_hough_lines(raw_lines: np.ndarray | None, *, min_length: int) -> list[DetectedLine]: + if raw_lines is None: + return [] + + lines: list[DetectedLine] = [] + for raw_line in raw_lines.reshape(-1, 4): + x1, y1, x2, y2 = [int(value) for value in raw_line] + dx = x2 - x1 + dy = y2 - y1 + length = math.hypot(dx, dy) + if length < min_length: + continue + angle = normalized_line_angle(dx, dy) + lines.append( + DetectedLine( + x1=x1, + y1=y1, + x2=x2, + y2=y2, + angle_degrees=round(angle, 2), + length=round(length, 2), + ) + ) + return lines + + +def deduplicate_lines(lines: list[DetectedLine]) -> list[DetectedLine]: + seen: set[tuple[int, int, int, int, int]] = set() + unique: list[DetectedLine] = [] + + for line in sorted(lines, key=lambda item: item.length, reverse=True): + angle_bin = int(round(line.angle_degrees / 3.0)) + midpoint_x = int(round(((line.x1 + line.x2) / 2) / 8.0)) + midpoint_y = int(round(((line.y1 + line.y2) / 2) / 8.0)) + length_bin = int(round(line.length / 12.0)) + key = (angle_bin, midpoint_x, midpoint_y, length_bin, int(line.length > 80)) + if key in seen: + continue + seen.add(key) + unique.append(line) + + return unique[:200] + + +def dominant_orientation( + lines: list[DetectedLine], + image_shape: tuple[int, int] | None = None, +) -> tuple[float, list[DetectedLine], float, float, float] | None: + if not lines: + return None + + angles = np.array([line.angle_degrees for line in lines], dtype=np.float64) + weights = np.array([max(1.0, line.length) for line in lines], dtype=np.float64) + total_weight = float(np.sum(weights)) + if total_weight <= 0: + return None + + clusters = cluster_line_families(lines, image_shape=image_shape) + if not clusters: + return None + + dominant_cluster = max(clusters, key=lambda cluster: cluster.score) + dominant_angle = dominant_cluster.angle_degrees + peak_weight_ratio = dominant_cluster.weight / total_weight + concentration = dominant_cluster.concentration + + orthogonal_angle = (dominant_angle + 90.0) % 180.0 + orthogonal_weight = float( + np.sum( + [ + weight + for angle, weight in zip(angles, weights, strict=False) + if angular_distance_degrees(float(angle), orthogonal_angle) <= 12.0 + ] + ) + ) + orthogonal_ratio = orthogonal_weight / dominant_cluster.weight if dominant_cluster.weight else 0.0 + + dominant_lines = [lines[index] for index in dominant_cluster.line_indices] + dominant_lines = sorted(dominant_lines, key=lambda item: item.length, reverse=True) + + return dominant_angle, dominant_lines, peak_weight_ratio, concentration, orthogonal_ratio + + +def estimate_rectified_grout_rotation( + lines: list[DetectedLine], + *, + render_transform: list[float] | np.ndarray | None, +) -> float | None: + """Return a cardinal tile rotation in the renderer's floor-plane coordinates.""" + transform = normalize_render_transform(render_transform) + if transform is None or len(lines) < 4: + return None + + rectified_lines = transform_detected_lines(lines, transform) + orientation = dominant_orientation(rectified_lines) + if orientation is None: + return None + + angle_degrees, dominant_lines, _peak_weight_ratio, concentration, _orthogonal_ratio = orientation + if len(dominant_lines) < 4 or concentration < 0.76: + return None + + return snap_to_tile_axis(angle_degrees) + + +def estimate_surface_uv_grout_rotation( + lines: list[DetectedLine], + *, + image_bgr: np.ndarray | None = None, + surface_uv: np.ndarray | None, + surface_indices: np.ndarray | None, + surface_plane_ids: np.ndarray | None, + image_shape: tuple[int, int], +) -> float | None: + """Measure grout in the same surface-UV plane sampled by the renderer.""" + uv_grid, plane_grid = build_surface_uv_grids( + surface_uv=surface_uv, + surface_indices=surface_indices, + surface_plane_ids=surface_plane_ids, + image_shape=image_shape, + ) + if uv_grid is None: + return None + + # Image-space Hough families are unreliable for oblique views: parallel floor + # seams converge, while furniture edges remain parallel. Rectifying the source + # into surface UV makes the actual grout parallel before it is scored. + if image_bgr is not None: + rectified = rectify_floor_image_to_surface_uv(image_bgr, uv_grid, plane_grid) + if rectified is not None: + rectified_image, rectified_mask = rectified + rectified_lines = detect_candidate_lines(rectified_image, rectified_mask) + rectified_angle = estimate_repeated_grout_orientation( + rectified_lines, + image_shape=rectified_mask.shape[:2], + ) + if rectified_angle is not None: + return rectified_angle + + if len(lines) < 4: + return None + + uv_lines = project_lines_to_surface_uv(lines, uv_grid, plane_grid) + return estimate_repeated_grout_orientation(uv_lines) + + +def rectify_floor_image_to_surface_uv( + image_bgr: np.ndarray, + uv_grid: np.ndarray, + plane_grid: np.ndarray | None, +) -> tuple[np.ndarray, np.ndarray] | None: + """Splat source pixels into a uniform, metric surface-UV image. + + The output uses one scale for U and V so line angles are directly usable as + renderer rotations. When the floor contains multiple surfaces, retain only + the largest assigned plane: their local UV bases are intentionally separate. + """ + if image_bgr.shape[:2] != uv_grid.shape[:2]: + return None + + valid = np.isfinite(uv_grid).all(axis=2) + if plane_grid is not None: + plane_values = plane_grid[valid & (plane_grid != 255)] + if plane_values.size: + dominant_plane = int(np.bincount(plane_values).argmax()) + valid &= plane_grid == dominant_plane + if int(valid.sum()) < 600: + return None + + uv = uv_grid[valid].astype(np.float64) + lower = np.percentile(uv, 0.5, axis=0) + upper = np.percentile(uv, 99.5, axis=0) + span = upper - lower + if not np.isfinite(span).all() or float(np.min(span)) <= 1e-5: + return None + + # Keep the rectified image detailed enough for grout, without making this + # CPU-only preprocessing grow with the uploaded image resolution. + aspect = float(span[0] / span[1]) + target_long_side = int( + np.clip( + round(math.sqrt(int(valid.sum()) * max(aspect, 1.0 / aspect))), + 256, + 1024, + ) + ) + scale = target_long_side / float(np.max(span)) + rectified_width = int(np.clip(round(float(span[0]) * scale) + 1, 96, 1024)) + rectified_height = int(np.clip(round(float(span[1]) * scale) + 1, 96, 1024)) + if rectified_width < 96 or rectified_height < 96: + return None + + source_gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY) + source_values = source_gray[valid].astype(np.float64) + local_u = uv[:, 0] - lower[0] + local_v = uv[:, 1] - lower[1] + xs = np.clip(np.rint(local_u * scale).astype(np.int32), 0, rectified_width - 1) + ys = np.clip(np.rint(local_v * scale).astype(np.int32), 0, rectified_height - 1) + flat_indices = ys * rectified_width + xs + pixel_count = rectified_width * rectified_height + counts = np.bincount(flat_indices, minlength=pixel_count) + values = np.bincount(flat_indices, weights=source_values, minlength=pixel_count) + covered = counts > 0 + if int(covered.sum()) < max(500, int(pixel_count * 0.08)): + return None + + fill_value = int(np.median(source_values)) if source_values.size else 0 + rectified_gray = np.full(pixel_count, fill_value, dtype=np.uint8) + rectified_gray[covered] = np.clip(values[covered] / counts[covered], 0, 255).astype(np.uint8) + rectified_mask = (covered.reshape(rectified_height, rectified_width).astype(np.uint8) * 255) + rectified_gray = rectified_gray.reshape(rectified_height, rectified_width) + return cv2.cvtColor(rectified_gray, cv2.COLOR_GRAY2BGR), rectified_mask + + +def estimate_repeated_grout_orientation( + lines: list[DetectedLine], + *, + image_shape: tuple[int, int] | None = None, +) -> float | None: + """Select a direction only when it has repeated, regularly spaced seams.""" + if len(lines) < 4: + return None + + candidates: list[tuple[float, float]] = [] + for cluster in cluster_line_families(lines, image_shape=image_shape): + if len(cluster.line_indices) < 4 or cluster.concentration < 0.76: + continue + + offsets, offset_weights, median_length = consolidated_line_offsets( + lines, + cluster.line_indices, + angle_degrees=cluster.angle_degrees, + image_shape=image_shape, + ) + if len(offsets) < 3: + continue + + periodicity = repeated_offset_periodicity(offsets, offset_weights) + if periodicity < 0.76: + continue + + support = min(1.0, len(cluster.line_indices) / 12.0) + offset_support = min(1.0, (len(offsets) - 1) / 6.0) + length_support = min(1.0, median_length / max(1.0, offset_span_reference(offsets, image_shape))) + quality = ( + 0.28 * periodicity + + 0.24 * cluster.concentration + + 0.22 * support + + 0.18 * offset_support + + 0.08 * length_support + ) + candidates.append((quality, cluster.angle_degrees)) + + if not candidates: + return None + quality, angle_degrees = max(candidates, key=lambda candidate: candidate[0]) + return angle_degrees if quality >= 0.68 else None + + +def consolidated_line_offsets( + lines: list[DetectedLine], + line_indices: list[int], + *, + angle_degrees: float, + image_shape: tuple[int, int] | None, +) -> tuple[np.ndarray, np.ndarray, float]: + center_x, center_y, _min_dimension = hough_offset_reference_frame( + lines, + line_indices, + image_shape=image_shape, + ) + radians = math.radians(angle_degrees) + normal_x = -math.sin(radians) + normal_y = math.cos(radians) + values = [] + for index in line_indices: + line = lines[index] + midpoint_x = (line.x1 + line.x2) * 0.5 + midpoint_y = (line.y1 + line.y2) * 0.5 + offset = (midpoint_x - center_x) * normal_x + (midpoint_y - center_y) * normal_y + values.append((offset, max(1.0, line.length))) + if not values: + return np.empty(0), np.empty(0), 0.0 + + lengths = np.array([weight for _offset, weight in values], dtype=np.float64) + median_length = float(np.median(lengths)) + tolerance = max(1.5, median_length * 0.035) + if image_shape is not None: + # Canny commonly returns the two sides of one grout seam as separate + # Hough segments after rectification. Merge that pair before testing + # inter-seam periodicity, while keeping adjacent physical seams apart. + tolerance = max(tolerance, min(image_shape) * 0.024) + groups: list[list[float]] = [] + for offset, weight in sorted(values, key=lambda item: item[0]): + if not groups or abs(offset - groups[-1][0]) > tolerance: + groups.append([offset, weight]) + continue + previous_offset, previous_weight = groups[-1] + total_weight = previous_weight + weight + groups[-1][0] = (previous_offset * previous_weight + offset * weight) / total_weight + groups[-1][1] = total_weight + + return ( + np.array([group[0] for group in groups], dtype=np.float64), + np.array([group[1] for group in groups], dtype=np.float64), + median_length, + ) + + +def repeated_offset_periodicity(offsets: np.ndarray, weights: np.ndarray) -> float: + """Return how well seam offsets fit one regularly repeating lattice.""" + if len(offsets) < 3: + return 0.0 + span = float(offsets[-1] - offsets[0]) + if span <= 1e-6: + return 0.0 + + pairwise = offsets[np.newaxis, :] - offsets[:, np.newaxis] + distances = pairwise[np.triu_indices(len(offsets), k=1)] + distances = distances[distances > 1e-6] + if not len(distances): + return 0.0 + + minimum_spacing = span / max(40.0, float(len(offsets) * 4)) + candidates = [] + for distance in distances: + for divisor in range(1, 7): + spacing = float(distance / divisor) + if minimum_spacing <= spacing <= span * 0.85: + candidates.append(spacing) + if not candidates: + return 0.0 + + best = 0.0 + weights = np.maximum(np.asarray(weights, dtype=np.float64), 1.0) + for spacing in candidates: + normalized = (offsets - offsets[0]) / spacing + residual = np.abs(normalized - np.rint(normalized)) + alignment = np.exp(-((residual / 0.10) ** 2)) + support = float(np.average(alignment, weights=weights)) + occupied_steps = len(np.unique(np.rint(normalized))) + coverage = min(1.0, occupied_steps / max(3, len(offsets))) + best = max(best, support * (0.82 + 0.18 * coverage)) + return best + + +def offset_span_reference( + offsets: np.ndarray, + image_shape: tuple[int, int] | None, +) -> float: + if image_shape is not None: + return float(min(image_shape)) * 0.20 + return max(1e-6, float(offsets[-1] - offsets[0])) + + +def build_surface_uv_grids( + *, + surface_uv: np.ndarray | None, + surface_indices: np.ndarray | None, + surface_plane_ids: np.ndarray | None, + image_shape: tuple[int, int], +) -> tuple[np.ndarray | None, np.ndarray | None]: + if surface_uv is None or surface_indices is None: + return None, None + + height, width = image_shape + uv_values = np.asarray(surface_uv, dtype=np.float32) + indices = np.asarray(surface_indices, dtype=np.int64).reshape(-1) + if uv_values.ndim != 2 or uv_values.shape[1] != 2 or len(uv_values) != len(indices): + return None, None + if not len(indices) or np.any(indices < 0) or np.any(indices >= height * width): + return None, None + + uv_grid = np.full((height * width, 2), np.nan, dtype=np.float32) + uv_grid[indices] = uv_values + uv_grid = uv_grid.reshape(height, width, 2) + + plane_grid = None + if surface_plane_ids is not None: + plane_ids = np.asarray(surface_plane_ids, dtype=np.uint8).reshape(-1) + if len(plane_ids) == len(indices): + plane_grid = np.full(height * width, 255, dtype=np.uint8) + plane_grid[indices] = plane_ids + plane_grid = plane_grid.reshape(height, width) + + return uv_grid, plane_grid + + +def project_lines_to_surface_uv( + lines: list[DetectedLine], + uv_grid: np.ndarray, + plane_grid: np.ndarray | None, +) -> list[DetectedLine]: + height, width = uv_grid.shape[:2] + projected_lines: list[DetectedLine] = [] + + for line in lines: + sample_count = int(np.clip(round(line.length / 8.0) + 1, 9, 64)) + fractions = np.linspace(0.0, 1.0, sample_count, dtype=np.float32) + xs = np.clip( + np.rint(line.x1 + (line.x2 - line.x1) * fractions).astype(np.int32), + 0, + width - 1, + ) + ys = np.clip( + np.rint(line.y1 + (line.y2 - line.y1) * fractions).astype(np.int32), + 0, + height - 1, + ) + points = uv_grid[ys, xs] + valid = np.isfinite(points).all(axis=1) + + if plane_grid is not None: + sampled_planes = plane_grid[ys, xs] + valid_planes = sampled_planes[valid & (sampled_planes != 255)] + if valid_planes.size: + dominant_plane = int(np.bincount(valid_planes).argmax()) + valid &= sampled_planes == dominant_plane + + if int(valid.sum()) < max(6, int(math.ceil(sample_count * 0.55))): + continue + + sampled_points = points[valid].astype(np.float64) + center = np.mean(sampled_points, axis=0) + _unused, _singular_values, basis = np.linalg.svd(sampled_points - center, full_matrices=False) + direction = basis[0] + distances = (sampled_points - center) @ direction + start = center + direction * float(np.min(distances)) + end = center + direction * float(np.max(distances)) + dx = float(end[0] - start[0]) + dy = float(end[1] - start[1]) + length = math.hypot(dx, dy) + if length <= 1e-5: + continue + + projected_lines.append( + DetectedLine( + x1=float(start[0]), + y1=float(start[1]), + x2=float(end[0]), + y2=float(end[1]), + angle_degrees=normalized_line_angle(dx, dy), + length=length, + ) + ) + + return projected_lines + + +def normalize_render_transform( + value: list[float] | np.ndarray | None, +) -> np.ndarray | None: + if value is None: + return None + + transform = np.asarray(value, dtype=np.float64) + if transform.size != 9: + return None + transform = transform.reshape(3, 3) + if not np.isfinite(transform).all() or abs(float(np.linalg.det(transform))) < 1e-10: + return None + return transform.astype(np.float32) + + +def transform_detected_lines( + lines: list[DetectedLine], + transform: np.ndarray, +) -> list[DetectedLine]: + rectified_lines: list[DetectedLine] = [] + for line in lines: + source_points = np.array([[[line.x1, line.y1], [line.x2, line.y2]]], dtype=np.float32) + mapped_points = cv2.perspectiveTransform(source_points, transform)[0] + if not np.isfinite(mapped_points).all(): + continue + + start, end = mapped_points + dx = float(end[0] - start[0]) + dy = float(end[1] - start[1]) + length = math.hypot(dx, dy) + if length <= 1e-5: + continue + + rectified_lines.append( + DetectedLine( + x1=float(start[0]), + y1=float(start[1]), + x2=float(end[0]), + y2=float(end[1]), + angle_degrees=normalized_line_angle(dx, dy), + length=length, + ) + ) + + return rectified_lines + + +def snap_to_tile_axis(angle_degrees: float) -> float | None: + normalized_angle = angle_degrees % 180.0 + nearest_axis = 0.0 if angular_distance_degrees(normalized_angle, 0.0) <= 45.0 else 90.0 + if angular_distance_degrees(normalized_angle, nearest_axis) > 28.0: + return None + return nearest_axis + + +def cluster_line_families( + lines: list[DetectedLine], + *, + image_shape: tuple[int, int] | None = None, +) -> list[LineFamilyCluster]: + raw_clusters: list[list[int]] = [] + + for line_index in sorted(range(len(lines)), key=lambda index: lines[index].length, reverse=True): + line_angle = lines[line_index].angle_degrees + best_cluster_index = None + best_distance = float("inf") + + for cluster_index, cluster_indices in enumerate(raw_clusters): + cluster_angle, _concentration, _weight = line_family_stats(lines, cluster_indices) + distance = angular_distance_degrees(line_angle, cluster_angle) + if distance <= 10.0 and distance < best_distance: + best_cluster_index = cluster_index + best_distance = distance + + if best_cluster_index is None: + raw_clusters.append([line_index]) + else: + raw_clusters[best_cluster_index].append(line_index) + + raw_clusters = merge_nearby_line_family_clusters(lines, raw_clusters) + return [ + build_line_family_cluster(lines, cluster_indices, image_shape=image_shape) + for cluster_indices in raw_clusters + if cluster_indices + ] + + +def merge_nearby_line_family_clusters( + lines: list[DetectedLine], + raw_clusters: list[list[int]], +) -> list[list[int]]: + merged_clusters = [list(cluster) for cluster in raw_clusters] + changed = True + + while changed and len(merged_clusters) > 1: + changed = False + for first_index in range(len(merged_clusters)): + first_angle, _first_concentration, _first_weight = line_family_stats( + lines, + merged_clusters[first_index], + ) + for second_index in range(first_index + 1, len(merged_clusters)): + second_angle, _second_concentration, _second_weight = line_family_stats( + lines, + merged_clusters[second_index], + ) + if angular_distance_degrees(first_angle, second_angle) > 8.0: + continue + + merged_clusters[first_index].extend(merged_clusters[second_index]) + del merged_clusters[second_index] + changed = True + break + if changed: + break + + return merged_clusters + + +def build_line_family_cluster( + lines: list[DetectedLine], + line_indices: list[int], + *, + image_shape: tuple[int, int] | None = None, +) -> LineFamilyCluster: + angle, concentration, weight = line_family_stats(lines, line_indices) + distinct_offset_count = count_distinct_line_offsets( + lines, + line_indices, + angle_degrees=angle, + image_shape=image_shape, + ) + score = line_family_selection_score( + weight=weight, + concentration=concentration, + line_count=len(line_indices), + distinct_offset_count=distinct_offset_count, + ) + return LineFamilyCluster( + line_indices=list(line_indices), + angle_degrees=angle, + weight=weight, + concentration=concentration, + distinct_offset_count=distinct_offset_count, + score=score, + ) + + +def line_family_stats( + lines: list[DetectedLine], + line_indices: list[int], +) -> tuple[float, float, float]: + angles = np.array([lines[index].angle_degrees for index in line_indices], dtype=np.float64) + weights = np.array([max(1.0, lines[index].length) for index in line_indices], dtype=np.float64) + total_weight = float(np.sum(weights)) + if total_weight <= 0.0: + return 0.0, 0.0, 0.0 + + angle, concentration = circular_mean_with_concentration(angles, weights) + return angle, concentration, total_weight + + +def count_distinct_line_offsets( + lines: list[DetectedLine], + line_indices: list[int], + *, + angle_degrees: float, + image_shape: tuple[int, int] | None = None, +) -> int: + if not line_indices: + return 0 + + center_x, center_y, min_dimension = hough_offset_reference_frame( + lines, + line_indices, + image_shape=image_shape, + ) + tolerance = max(6.0, min_dimension * 0.018) + radians = math.radians(angle_degrees) + normal_x = -math.sin(radians) + normal_y = math.cos(radians) + + offsets = [] + for index in line_indices: + line = lines[index] + midpoint_x = (line.x1 + line.x2) * 0.5 + midpoint_y = (line.y1 + line.y2) * 0.5 + rho = (midpoint_x - center_x) * normal_x + (midpoint_y - center_y) * normal_y + offsets.append((rho, max(1.0, line.length))) + + offset_groups: list[list[float]] = [] + for rho, weight in sorted(offsets, key=lambda item: item[0]): + if not offset_groups or abs(rho - offset_groups[-1][0]) > tolerance: + offset_groups.append([rho, weight]) + continue + + previous_rho, previous_weight = offset_groups[-1] + combined_weight = previous_weight + weight + offset_groups[-1][0] = (previous_rho * previous_weight + rho * weight) / combined_weight + offset_groups[-1][1] = combined_weight + + return len(offset_groups) + + +def hough_offset_reference_frame( + lines: list[DetectedLine], + line_indices: list[int], + *, + image_shape: tuple[int, int] | None = None, +) -> tuple[float, float, float]: + if image_shape is not None: + height, width = image_shape + min_dimension = max(1.0, float(min(width, height))) + return (width - 1) * 0.5, (height - 1) * 0.5, min_dimension + + xs: list[float] = [] + ys: list[float] = [] + for index in line_indices: + line = lines[index] + xs.extend([float(line.x1), float(line.x2)]) + ys.extend([float(line.y1), float(line.y2)]) + + min_x = min(xs) if xs else 0.0 + max_x = max(xs) if xs else 1.0 + min_y = min(ys) if ys else 0.0 + max_y = max(ys) if ys else 1.0 + width = max(1.0, max_x - min_x) + height = max(1.0, max_y - min_y) + return min_x + width * 0.5, min_y + height * 0.5, min(width, height) + + +def line_family_selection_score( + *, + weight: float, + concentration: float, + line_count: int, + distinct_offset_count: int, +) -> float: + distinct_bonus = min(6, max(0, distinct_offset_count - 1)) + line_bonus = min(8, max(0, line_count - 1)) + repeated_line_multiplier = 1.0 + 0.18 * distinct_bonus + 0.05 * line_bonus + return weight * max(0.35, concentration) * repeated_line_multiplier + + +def detect_secondary_grid_angle( + *, + lines: list[DetectedLine], + primary_angle_degrees: float, + primary_line_count: int, +) -> float | None: + if len(lines) < 8 or primary_line_count < 4: + return None + + target_angle = (primary_angle_degrees + 90.0) % 180.0 + secondary_lines = [ + line + for line in lines + if angular_distance_degrees(line.angle_degrees, target_angle) <= 14.0 + ] + if len(secondary_lines) < max(4, int(round(primary_line_count * 0.35))): + return None + + primary_weight = sum( + line.length + for line in lines + if angular_distance_degrees(line.angle_degrees, primary_angle_degrees) <= 14.0 + ) + secondary_weight = sum(line.length for line in secondary_lines) + if secondary_weight < max(120.0, primary_weight * 0.24): + return None + + angle, concentration = circular_mean_with_concentration( + np.array([line.angle_degrees for line in secondary_lines], dtype=np.float64), + np.array([line.length for line in secondary_lines], dtype=np.float64), + ) + if concentration < 0.76: + return None + + return angle + + +def estimate_texture_orientation( + image_bgr: np.ndarray, + mask: np.ndarray, +) -> TextureOrientation | None: + component_mask = largest_mask_component(mask) + texture_mask = erode_mask(component_mask) + if int(np.count_nonzero(texture_mask)) == 0: + texture_mask = component_mask + + height, width = image_bgr.shape[:2] + floor_pixels = int(np.count_nonzero(texture_mask)) + if floor_pixels < max(500, int(height * width * 0.015)): + return None + + gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY) + inside_pixels = gray[texture_mask > 0] + fill_value = int(np.median(inside_pixels)) if inside_pixels.size else int(np.median(gray)) + prepared = gray.copy() + prepared[texture_mask == 0] = fill_value + + clahe = cv2.createCLAHE(clipLimit=1.7, tileGridSize=(8, 8)) + enhanced = clahe.apply(prepared) + blurred = cv2.GaussianBlur(enhanced, (3, 3), 0) + + gradient_x = cv2.Scharr(blurred, cv2.CV_32F, 1, 0) + gradient_y = cv2.Scharr(blurred, cv2.CV_32F, 0, 1) + gradient_magnitude = cv2.magnitude(gradient_x, gradient_y) + + valid_magnitudes = gradient_magnitude[texture_mask > 0] + valid_magnitudes = valid_magnitudes[valid_magnitudes > 0] + if valid_magnitudes.size < 200: + return None + + low_threshold = max(3.0, float(np.percentile(valid_magnitudes, 45))) + high_threshold = float(np.percentile(valid_magnitudes, 97)) + if high_threshold <= low_threshold: + high_threshold = float(np.max(valid_magnitudes)) + + valid_texture = ( + (texture_mask > 0) + & (gradient_magnitude >= low_threshold) + & (gradient_magnitude <= high_threshold) + ) + + cell_size = max(28, int(round(min(width, height) * 0.07))) + angles: list[float] = [] + weights: list[float] = [] + + for y in range(0, height, cell_size): + for x in range(0, width, cell_size): + cell_valid = valid_texture[y : y + cell_size, x : x + cell_size] + valid_count = int(np.count_nonzero(cell_valid)) + if valid_count < max(40, int(cell_size * cell_size * 0.08)): + continue + + cell_gx = gradient_x[y : y + cell_size, x : x + cell_size][cell_valid] + cell_gy = gradient_y[y : y + cell_size, x : x + cell_size][cell_valid] + cell_mag = gradient_magnitude[y : y + cell_size, x : x + cell_size][cell_valid] + + tensor_xx = float(np.sum(cell_gx * cell_gx)) + tensor_yy = float(np.sum(cell_gy * cell_gy)) + tensor_xy = float(np.sum(cell_gx * cell_gy)) + energy = tensor_xx + tensor_yy + if energy <= 0.0: + continue + + coherence = math.sqrt((tensor_xx - tensor_yy) ** 2 + 4.0 * tensor_xy**2) / energy + if coherence < 0.12: + continue + + gradient_angle = math.degrees( + 0.5 * math.atan2(2.0 * tensor_xy, tensor_xx - tensor_yy) + ) + line_angle = (gradient_angle + 90.0) % 180.0 + median_mag = float(np.median(cell_mag)) + weights.append(coherence * math.log1p(median_mag) * math.sqrt(valid_count)) + angles.append(line_angle) + + if len(angles) < 4: + return None + + angle_array = np.array(angles, dtype=np.float64) + weight_array = np.array(weights, dtype=np.float64) + if float(np.sum(weight_array)) <= 0.0: + return None + + cap = float(np.percentile(weight_array, 85)) + if cap > 0: + weight_array = np.minimum(weight_array, cap) + + angle, concentration = circular_mean_with_concentration(angle_array, weight_array) + support_score = min(1.0, len(angles) / 18.0) + confidence = max(0.0, min(1.0, (0.65 * concentration + 0.35 * support_score))) + confidence *= support_score + + if confidence < 0.22 or concentration < 0.22: + return None + + return TextureOrientation( + angle_degrees=angle, + confidence=confidence, + support=len(angles), + concentration=concentration, + ) + + +def select_orientation( + hough_orientation: tuple[float, list[DetectedLine], float, float, float] | None, + texture_orientation: TextureOrientation | None, + warnings: list[str], +) -> tuple[float, str] | None: + if hough_orientation is None and texture_orientation is None: + return None + + if hough_orientation is None: + return texture_orientation.angle_degrees, "texture" if texture_orientation else None + + hough_angle, dominant_lines, peak_weight_ratio, concentration, orthogonal_ratio = hough_orientation + if texture_orientation is None: + return hough_angle, "hough" + + hough_quality = hough_orientation_quality( + dominant_line_count=len(dominant_lines), + peak_weight_ratio=peak_weight_ratio, + concentration=concentration, + orthogonal_ratio=orthogonal_ratio, + ) + texture_quality = texture_orientation.confidence + distance = angular_distance_degrees(hough_angle, texture_orientation.angle_degrees) + + if is_strong_hough_grout_orientation( + dominant_line_count=len(dominant_lines), + peak_weight_ratio=peak_weight_ratio, + concentration=concentration, + orthogonal_ratio=orthogonal_ratio, + ): + if distance > 10.0: + warnings.append("strong_grout_lines_used_over_texture") + return hough_angle, "hough" + + if distance <= 10.0: + angle = circular_mean_degrees( + [hough_angle, texture_orientation.angle_degrees], + [max(hough_quality, 0.1), max(texture_quality, 0.1)], + ) + return angle, "combined" + + if ( + texture_quality >= 0.42 + and texture_orientation.support >= 6 + and ( + hough_quality < 0.62 + or len(dominant_lines) < 8 + or peak_weight_ratio < 0.56 + or orthogonal_ratio > 0.45 + ) + ): + warnings.append("hough_texture_disagreement_using_texture") + return texture_orientation.angle_degrees, "texture" + + if texture_quality >= hough_quality + 0.16 and texture_orientation.support >= 8: + warnings.append("hough_texture_disagreement_using_texture") + return texture_orientation.angle_degrees, "texture" + + if hough_quality >= texture_quality + 0.18: + warnings.append("hough_texture_disagreement_using_hough") + return hough_angle, "hough" + + angle = circular_mean_degrees( + [hough_angle, texture_orientation.angle_degrees], + [max(hough_quality, 0.1), max(texture_quality, 0.1)], + ) + warnings.append("hough_texture_orientation_combined_after_disagreement") + return angle, "combined" + + +def hough_orientation_quality( + *, + dominant_line_count: int, + peak_weight_ratio: float, + concentration: float, + orthogonal_ratio: float, +) -> float: + line_support = min(1.0, dominant_line_count / 12.0) + orthogonal_penalty = max(0.0, 1.0 - min(1.0, orthogonal_ratio)) + return max( + 0.0, + min( + 1.0, + 0.28 * line_support + + 0.32 * max(0.0, min(1.0, peak_weight_ratio)) + + 0.30 * max(0.0, min(1.0, concentration)) + + 0.10 * orthogonal_penalty, + ), + ) + + +def is_strong_hough_grout_orientation( + *, + dominant_line_count: int, + peak_weight_ratio: float, + concentration: float, + orthogonal_ratio: float, +) -> bool: + return ( + dominant_line_count >= 8 + and peak_weight_ratio >= 0.58 + and concentration >= 0.86 + and orthogonal_ratio <= 0.48 + ) or ( + dominant_line_count >= 12 + and peak_weight_ratio >= 0.50 + and concentration >= 0.82 + and orthogonal_ratio <= 0.55 + ) + + +def circular_mean_degrees(angles: list[float], weights: list[float]) -> float: + angle, _concentration = circular_mean_with_concentration( + np.array(angles, dtype=np.float64), + np.array(weights, dtype=np.float64), + ) + return angle + + +def circular_mean_with_concentration( + angles: np.ndarray, + weights: np.ndarray, +) -> tuple[float, float]: + total_weight = float(np.sum(weights)) + if total_weight <= 0.0: + return 0.0, 0.0 + + doubled_angles = np.deg2rad(angles * 2.0) + vector_x = float(np.sum(np.cos(doubled_angles) * weights)) + vector_y = float(np.sum(np.sin(doubled_angles) * weights)) + angle = (math.degrees(math.atan2(vector_y, vector_x)) / 2.0) % 180.0 + concentration = math.hypot(vector_x, vector_y) / total_weight + return angle, concentration + + +def normalized_line_angle(dx: float, dy: float) -> float: + angle = math.degrees(math.atan2(dy, dx)) % 180.0 + if angle >= 180.0: + angle -= 180.0 + return angle + + +def angular_distance_degrees(first: float, second: float) -> float: + diff = abs((first - second) % 180.0) + return min(diff, 180.0 - diff) + + +def score_confidence( + *, + segmentation_confidence: float, + floor_area_ratio: float, + line_count: int, + dominant_line_count: int, + peak_weight_ratio: float, + concentration: float, +) -> float: + segmentation_score = max(0.0, min(1.0, segmentation_confidence)) + area_score = max(0.0, min(1.0, floor_area_ratio / 0.28)) + line_score = max(0.0, min(1.0, line_count / 30.0)) + dominant_count_score = max(0.0, min(1.0, dominant_line_count / 14.0)) + peak_score = max(0.0, min(1.0, peak_weight_ratio)) + concentration_score = max(0.0, min(1.0, concentration)) + + score = ( + 0.18 * segmentation_score + + 0.10 * area_score + + 0.18 * line_score + + 0.16 * dominant_count_score + + 0.24 * peak_score + + 0.14 * concentration_score + ) + return max(0.0, min(1.0, score)) + + +def score_texture_confidence( + *, + segmentation_confidence: float, + floor_area_ratio: float, + texture_confidence: float, +) -> float: + segmentation_score = max(0.0, min(1.0, segmentation_confidence)) + area_score = max(0.0, min(1.0, floor_area_ratio / 0.28)) + texture_score = max(0.0, min(1.0, texture_confidence)) + score = 0.20 * segmentation_score + 0.14 * area_score + 0.66 * texture_score + return max(0.0, min(1.0, score)) + + +def final_orientation_confidence( + *, + source: str, + hough_confidence: float, + texture_confidence: float, +) -> float: + if source == "texture": + return texture_confidence + if source == "combined": + return max(hough_confidence, texture_confidence) * 0.96 + return hough_confidence + + +def label_direction(angle_degrees: float) -> str: + if angle_degrees < 10.0 or angle_degrees >= 170.0: + return "left_to_right" + if angle_degrees < 35.0: + return "slight_down_right" + if angle_degrees < 70.0: + return "diagonal_down_right" + if angle_degrees < 110.0: + return "top_to_bottom" + if angle_degrees < 145.0: + return "diagonal_up_right" + return "slight_up_right" + + +def create_overlay( + image_bgr: np.ndarray, + mask: np.ndarray, + _lines: list[DetectedLine], + angle_degrees: float | None, + secondary_angle_degrees: float | None = None, +) -> np.ndarray: + overlay = image_bgr.copy() + if secondary_angle_degrees is not None: + draw_direction_line(overlay, mask, secondary_angle_degrees, color_bgr=(255, 210, 20)) + if angle_degrees is not None: + draw_direction_line(overlay, mask, angle_degrees, color_bgr=(0, 255, 80)) + + return overlay + + +def draw_direction_line( + image_bgr: np.ndarray, + mask: np.ndarray, + angle_degrees: float, + *, + color_bgr: tuple[int, int, int], +) -> None: + endpoints = direction_line_endpoints(mask, angle_degrees) + if endpoints is None: + return + + start, end = endpoints + min_dimension = min(mask.shape[:2]) + thickness = max(5, int(round(min_dimension / 155))) + + cv2.line(image_bgr, start, end, (0, 0, 0), thickness + 6, cv2.LINE_AA) + cv2.line(image_bgr, start, end, color_bgr, thickness, cv2.LINE_AA) + cv2.circle(image_bgr, start, thickness + 1, color_bgr, -1, cv2.LINE_AA) + cv2.circle(image_bgr, end, thickness + 1, color_bgr, -1, cv2.LINE_AA) + + +def direction_line_endpoints( + mask: np.ndarray, + angle_degrees: float, +) -> tuple[tuple[int, int], tuple[int, int]] | None: + component_mask = largest_mask_component(mask) + points = cv2.findNonZero(component_mask) + if points is None: + return None + + height, width = mask.shape[:2] + floor_points = points.reshape(-1, 2).astype(np.float64) + center = floor_points.mean(axis=0) + center_x = int(round(center[0])) + center_y = int(round(center[1])) + + if ( + not (0 <= center_x < width and 0 <= center_y < height) + or component_mask[center_y, center_x] == 0 + ): + distances = np.sum((floor_points - center) ** 2, axis=1) + center = floor_points[int(np.argmin(distances))] + + unit = np.array( + [ + math.cos(math.radians(angle_degrees)), + math.sin(math.radians(angle_degrees)), + ], + dtype=np.float64, + ) + projections = (floor_points - center) @ unit + min_projection = float(np.percentile(projections, 1)) + max_projection = float(np.percentile(projections, 99)) + sample_count = max(2, int(round(max_projection - min_projection)) + 1) + sample_count = min(sample_count, max(width, height) * 3) + + samples = np.linspace(min_projection, max_projection, sample_count) + active_samples: list[float] = [] + runs: list[list[float]] = [] + current_run: list[float] = [] + + for sample in samples: + x, y = center + sample * unit + ix = int(round(x)) + iy = int(round(y)) + is_inside = 0 <= ix < width and 0 <= iy < height and component_mask[iy, ix] > 0 + if is_inside: + current_run.append(float(sample)) + active_samples.append(float(sample)) + elif current_run: + runs.append(current_run) + current_run = [] + + if current_run: + runs.append(current_run) + + if runs: + best_run = max(runs, key=len) + start_projection = best_run[0] + end_projection = best_run[-1] + elif active_samples: + start_projection = min(active_samples) + end_projection = max(active_samples) + else: + start_projection = min_projection + end_projection = max_projection + + minimum_length = max(30.0, min(width, height) * 0.08) + if end_projection - start_projection < minimum_length: + midpoint = (start_projection + end_projection) / 2.0 + start_projection = midpoint - minimum_length / 2.0 + end_projection = midpoint + minimum_length / 2.0 + + start = center + start_projection * unit + end = center + end_projection * unit + return clip_point_to_image(start, width, height), clip_point_to_image(end, width, height) + + +def largest_mask_component(mask: np.ndarray) -> np.ndarray: + binary_mask = np.where(mask > 0, 255, 0).astype(np.uint8) + component_count, labels, stats, _centroids = cv2.connectedComponentsWithStats(binary_mask, 8) + if component_count <= 1: + return binary_mask + + largest_label = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) + return np.where(labels == largest_label, 255, 0).astype(np.uint8) + + +def clip_point_to_image( + point: np.ndarray, + width: int, + height: int, +) -> tuple[int, int]: + x = int(round(float(point[0]))) + y = int(round(float(point[1]))) + return max(0, min(width - 1, x)), max(0, min(height - 1, y)) + diff --git a/apps/renderer/models/__init__.py b/apps/renderer/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bdad955192e055dc2580f0d8a2a1987bc2792a79 --- /dev/null +++ b/apps/renderer/models/__init__.py @@ -0,0 +1 @@ +# Model loading, inference helpers, and metadata utilities. diff --git a/apps/renderer/models/depth.py b/apps/renderer/models/depth.py new file mode 100644 index 0000000000000000000000000000000000000000..8efd98d4fc2159d223b861930f8f1cd7bfd40d3b --- /dev/null +++ b/apps/renderer/models/depth.py @@ -0,0 +1,174 @@ +"""Depth estimation and 3D geometry inference.""" + +import cv2 +import numpy as np +import torch +from PIL import Image + +import state +from config.models import DEPTH_MODEL_NAME, GEOMETRY_MODEL, MOGE_MODEL_NAME +from config.runtime import ENABLE_DEPTH_ESTIMATION, ENABLE_MOGE_GEOMETRY, ENABLE_ONNX_INFERENCE +from models.loader import _load_depth_model, _load_moge_model +from enums import GeometryProvider +from utils import to_numpy + + +def _estimate_depth_onnx(img: Image.Image, width: int, height: int) -> np.ndarray | None: + """Try running depth estimation via ONNX Runtime. Returns None if unavailable.""" + if not ENABLE_ONNX_INFERENCE: + return None + from models.onnx_loader import load_depth_onnx_session + session = load_depth_onnx_session() + if session is None: + return None + + if state.depth_processor is None: + _load_depth_model() + + inputs = state.depth_processor(images=img, return_tensors="np") + input_feed = {k: v for k, v in inputs.items() if k in [inp.name for inp in session.get_inputs()]} + outputs = session.run(None, input_feed) + + # outputs[0] is predicted_depth — interpolate to target size + depth_tensor = torch.from_numpy(outputs[0]) + if depth_tensor.ndim == 2: + depth_tensor = depth_tensor.unsqueeze(0).unsqueeze(0) + elif depth_tensor.ndim == 3: + depth_tensor = depth_tensor.unsqueeze(1) + depth = torch.nn.functional.interpolate( + depth_tensor, size=(height, width), mode="bicubic", align_corners=False, + ).squeeze().numpy() + return depth + + +def estimate_depth(img: Image.Image, width: int, height: int): + if not ENABLE_DEPTH_ESTIMATION: + return None + + try: + # Try ONNX first + depth = _estimate_depth_onnx(img, width, height) + if depth is not None: + depth = cv2.GaussianBlur(depth.astype(np.float32), (0, 0), sigmaX=3) + if "metric" in DEPTH_MODEL_NAME.lower(): + return depth + depth_min, depth_max = float(np.min(depth)), float(np.max(depth)) + if depth_max - depth_min < 1e-6: + return None + return (depth - depth_min) / (depth_max - depth_min) + + # Fallback to PyTorch + if not _load_depth_model(): + return None + + inputs = state.depth_processor(images=img, return_tensors="pt").to(state.device) + use_autocast = state.device.type == "cuda" + with torch.no_grad(): + if use_autocast: + with torch.autocast(device_type="cuda", dtype=torch.float16): + outputs = state.depth_model(**inputs) + else: + outputs = state.depth_model(**inputs) + depth = torch.nn.functional.interpolate( + outputs.predicted_depth.unsqueeze(1), + size=(height, width), + mode="bicubic", + align_corners=False, + ).squeeze().cpu().numpy() + depth = cv2.GaussianBlur(depth.astype(np.float32), (0, 0), sigmaX=3) + if "metric" in DEPTH_MODEL_NAME.lower(): + return depth + depth_min, depth_max = float(np.min(depth)), float(np.max(depth)) + if depth_max - depth_min < 1e-6: + return None + return (depth - depth_min) / (depth_max - depth_min) + except Exception as exc: + print(f"Depth estimation skipped ({exc}).", flush=True) + return None + + +def estimate_moge_geometry(img_np: np.ndarray, target_h: int | None = None, target_w: int | None = None): + """Run MoGe geometry on img_np, upscale outputs to target_h x target_w if provided.""" + if not ENABLE_MOGE_GEOMETRY or GEOMETRY_MODEL != "moge" or state.device.type != "cuda": + return None + + try: + if not _load_moge_model(): + return None + + image_tensor = torch.from_numpy(img_np.astype(np.float32) / 255.0).permute(2, 0, 1).to(state.device) + with torch.inference_mode(), torch.autocast(device_type="cuda", dtype=torch.float16): + output = state.moge_model.infer(image_tensor) + + points = to_numpy(output.get("points")) + depth = to_numpy(output.get("depth")) + normals = to_numpy(output.get("normal")) + valid_mask = to_numpy(output.get("mask")) + intrinsics = to_numpy(output.get("intrinsics")) + if points is None or points.ndim != 3 or points.shape[2] != 3: + raise RuntimeError("MoGe did not return an HxWx3 point map.") + out_h = target_h if target_h is not None else img_np.shape[0] + out_w = target_w if target_w is not None else img_np.shape[1] + if points.shape[:2] != (out_h, out_w): + points = cv2.resize(points, (out_w, out_h), interpolation=cv2.INTER_LINEAR) + if depth is not None and depth.shape[:2] != (out_h, out_w): + depth = cv2.resize(depth, (out_w, out_h), interpolation=cv2.INTER_LINEAR) + if normals is not None and normals.shape[:2] != (out_h, out_w): + normals = cv2.resize(normals, (out_w, out_h), interpolation=cv2.INTER_LINEAR) + if valid_mask is not None and valid_mask.shape[:2] != (out_h, out_w): + valid_mask = cv2.resize( + valid_mask.astype(np.uint8), + (out_w, out_h), + interpolation=cv2.INTER_NEAREST, + ).astype(bool) + if depth is None: + depth = points[:, :, 2] + if valid_mask is None: + valid_mask = np.isfinite(depth) & (depth > 0) + + print( + "[FLOOR_3D_POINTS] generated raw MoGe HxWx3 point map " + f"shape={points.shape} validPixels={int(valid_mask.sum())} provider=moge-2", + flush=True, + ) + return { + "provider": GeometryProvider.MOGE_2, + "points": points.astype(np.float32), + "depth": depth.astype(np.float32), + "normals": normals.astype(np.float32) if normals is not None else None, + "validMask": valid_mask.astype(bool), + "intrinsics": intrinsics.astype(np.float32) if intrinsics is not None else None, + } + except Exception as exc: + print(f"MoGe geometry estimation failed ({exc}); falling back to depth.", flush=True) + if state.device.type == "cuda": + torch.cuda.empty_cache() + return None + + +def estimate_scene_geometry(img: Image.Image, img_np: np.ndarray, width: int, height: int): + with state.gpu_inference(): + return _estimate_scene_geometry(img, img_np, width, height) + + +def _estimate_scene_geometry(img: Image.Image, img_np: np.ndarray, width: int, height: int): + geometry = estimate_moge_geometry(img_np, target_h=height, target_w=width) + if geometry is not None: + return geometry + + depth = estimate_depth(img, width, height) + depth_provider = GeometryProvider.HOMOGRAPHY + if depth is not None: + depth_provider = ( + GeometryProvider.DEPTH_ANYTHING_METRIC + if "metric" in DEPTH_MODEL_NAME.lower() + else GeometryProvider.RELATIVE_DEPTH + ) + return { + "provider": depth_provider, + "points": None, + "depth": depth, + "normals": None, + "validMask": np.isfinite(depth) & (depth > 0) if depth is not None else None, + "intrinsics": None, + } diff --git a/apps/renderer/models/loader.py b/apps/renderer/models/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..45dea96a2b80ed0658b598200cedf5ec61bc4734 --- /dev/null +++ b/apps/renderer/models/loader.py @@ -0,0 +1,199 @@ +"""Lazy model loading and warm-start logic.""" + +import time + +import torch + +import state +from config.models import ( + ONEFORMER_MODEL_NAME, + DEPTH_MODEL_NAME, + GEOMETRY_MODEL, + MOGE_MODEL_NAME, + SAM2_MODEL_CFG, + SAM2_CHECKPOINT, + SAM2_MODEL_NAME, + INTRINSIC_MODEL_VERSION, +) +from config.runtime import ( + ENABLE_MOGE_GEOMETRY, + ENABLE_SAM_REFINEMENT, + ENABLE_DEPTH_ESTIMATION, + ENABLE_INTRINSIC_SHADING, + ENABLE_SHADING_TRANSFER, + WARM_START_MODELS, +) +from transformers import ( + AutoImageProcessor, + AutoModelForDepthEstimation, + OneFormerForUniversalSegmentation, + OneFormerProcessor, +) + + +def _load_segmentation_model(): + if state.seg_processor is not None and state.seg_model is not None: + return + + print(f"Loading OneFormer: {ONEFORMER_MODEL_NAME} ...", flush=True) + state.seg_processor = OneFormerProcessor.from_pretrained( + ONEFORMER_MODEL_NAME, + local_files_only=state.hf_offline(), + ) + state.seg_model = OneFormerForUniversalSegmentation.from_pretrained( + ONEFORMER_MODEL_NAME, + local_files_only=state.hf_offline(), + ).to(state.device) + state.seg_model.eval() + print("OneFormer loaded.", flush=True) + + +def _load_intrinsic_model(): + if ENABLE_INTRINSIC_SHADING and state.intrinsic_models is None: + try: + print(f"Loading Intrinsic Image Decomposition model: {INTRINSIC_MODEL_VERSION} ...", flush=True) + from intrinsic.pipeline import load_models + state.intrinsic_models = load_models(INTRINSIC_MODEL_VERSION, device=str(state.device)) + print("Intrinsic model loaded.", flush=True) + except Exception as exc: + print(f"Intrinsic model failed to load ({exc}). Falling back to luminance shading.", flush=True) + + +def _load_depth_model() -> bool: + if not ENABLE_DEPTH_ESTIMATION: + return False + if state.depth_processor is not None and state.depth_model is not None: + return True + + print(f"Loading depth model: {DEPTH_MODEL_NAME} ...", flush=True) + state.depth_processor = AutoImageProcessor.from_pretrained( + DEPTH_MODEL_NAME, + local_files_only=state.hf_offline(), + ) + state.depth_model = AutoModelForDepthEstimation.from_pretrained( + DEPTH_MODEL_NAME, + local_files_only=state.hf_offline(), + ).to(state.device) + state.depth_model.eval() + print("Depth model loaded.", flush=True) + return True + + +def _load_moge_model() -> bool: + if not ENABLE_MOGE_GEOMETRY or GEOMETRY_MODEL != "moge" or state.device.type != "cuda": + return False + if state.moge_model is not None: + return True + + print(f"Loading MoGe geometry model: {MOGE_MODEL_NAME} ...", flush=True) + from moge.model.v2 import MoGeModel + state.moge_model = MoGeModel.from_pretrained(MOGE_MODEL_NAME).to(state.device) + state.moge_model.eval() + print("MoGe geometry model loaded.", flush=True) + return True + + +def _load_sam2_predictor(): + if not ENABLE_SAM_REFINEMENT: + return None + if state.sam2_predictor is not None: + return state.sam2_predictor + try: + from sam2.sam2_image_predictor import SAM2ImagePredictor + + if SAM2_MODEL_CFG and SAM2_CHECKPOINT: + from sam2.build_sam import build_sam2 + + model = build_sam2(SAM2_MODEL_CFG, SAM2_CHECKPOINT, device=str(state.device)) + model.eval() + state.sam2_predictor = SAM2ImagePredictor(model) + else: + state.sam2_predictor = SAM2ImagePredictor.from_pretrained(SAM2_MODEL_NAME) + if hasattr(state.sam2_predictor, "model"): + state.sam2_predictor.model.to(state.device) + state.sam2_predictor.model.eval() + print("SAM2 refinement model loaded.", flush=True) + return state.sam2_predictor + except Exception as exc: + print(f"SAM2 refinement unavailable ({exc}).", flush=True) + if state.device.type == "cuda": + torch.cuda.empty_cache() + return None + + +def warm_start_models(): + if not WARM_START_MODELS: + print("Model warm start disabled; models will load on first use.", flush=True) + return + + t_start = time.perf_counter() + print(f"Warm-starting visualizer models on {state.device} ...", flush=True) + + # Try ONNX sessions first + from config.runtime import ENABLE_ONNX_INFERENCE + if ENABLE_ONNX_INFERENCE: + from models.onnx_loader import load_seg_onnx_session, load_depth_onnx_session + load_seg_onnx_session() + load_depth_onnx_session() + + _load_segmentation_model() + + moge_loaded = False + if ENABLE_MOGE_GEOMETRY and GEOMETRY_MODEL == "moge": + try: + moge_loaded = _load_moge_model() + except Exception as exc: + print(f"MoGe warm start skipped ({exc}); depth fallback may be used.", flush=True) + if state.device.type == "cuda": + torch.cuda.empty_cache() + + if ENABLE_DEPTH_ESTIMATION and not moge_loaded: + try: + _load_depth_model() + except Exception as exc: + print(f"Depth model warm start skipped ({exc}); depth will be retried on first use.", flush=True) + if state.device.type == "cuda": + torch.cuda.empty_cache() + + if ENABLE_SAM_REFINEMENT: + _load_sam2_predictor() + + if ENABLE_SHADING_TRANSFER and ENABLE_INTRINSIC_SHADING: + _load_intrinsic_model() + + _warm_up_inference() + + print(f"[TIMING] Model warm start took {time.perf_counter() - t_start:.3f} seconds", flush=True) + + +def _warm_up_inference(): + """Run throwaway inference so the first real job doesn't pay CUDA kernel init. + + Loading weights alone leaves kernel compilation and autocast setup for the + first request, which made post-restart jobs take 16-48s instead of ~5s. + Both orientations are warmed because inference inputs are capped at + INFERENCE_MAX_DIMENSION on the long side (portrait and landscape shapes). + """ + # Deferred: models.depth / models.segmentation import from this module. + import numpy as np + from PIL import Image + + from config.runtime import INFERENCE_MAX_DIMENSION + from models.depth import estimate_scene_geometry + from models.segmentation import run_segmentation + + long_side = INFERENCE_MAX_DIMENSION + short_side = round(long_side * 0.75) + rng = np.random.default_rng(0) + for w, h in ((short_side, long_side), (long_side, short_side)): + t0 = time.perf_counter() + try: + img_np = rng.integers(0, 256, size=(h, w, 3), dtype=np.uint8) + img = Image.fromarray(img_np) + run_segmentation(img, img_np) + estimate_scene_geometry(img, img_np, w, h) + if state.device.type == "cuda": + torch.cuda.synchronize() + print(f"[TIMING] Warm-up inference {w}x{h} took {time.perf_counter() - t0:.3f} seconds", flush=True) + except Exception as exc: + print(f"Warm-up inference {w}x{h} skipped ({exc}); first job may be slower.", flush=True) diff --git a/apps/renderer/models/onnx_loader.py b/apps/renderer/models/onnx_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..f52000b847bd9db4aff14d5b20f31026cdec2328 --- /dev/null +++ b/apps/renderer/models/onnx_loader.py @@ -0,0 +1,69 @@ +"""ONNX Runtime model loading for accelerated inference.""" + +from pathlib import Path + +import state +from config.runtime import ENABLE_ONNX_INFERENCE, ONNX_MODEL_DIR + +ONNX_DIR = Path(ONNX_MODEL_DIR) + + +def _ort_providers() -> list[str]: + """Return available ONNX Runtime execution providers, preferring GPU.""" + providers = [] + if state.device.type == "cuda": + providers.append("CUDAExecutionProvider") + providers.append("CPUExecutionProvider") + return providers + + +def load_seg_onnx_session(): + """Load the OneFormer ONNX session if available.""" + if not ENABLE_ONNX_INFERENCE: + return None + if state.seg_onnx_session is not None: + return state.seg_onnx_session + + model_path = ONNX_DIR / "oneformer_seg.onnx" + if not model_path.exists(): + print(f"ONNX segmentation model not found at {model_path}, falling back to PyTorch.", flush=True) + return None + + try: + import onnxruntime as ort + sess_options = ort.SessionOptions() + sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL + state.seg_onnx_session = ort.InferenceSession( + str(model_path), sess_options, providers=_ort_providers(), + ) + print(f"ONNX segmentation model loaded from {model_path}", flush=True) + return state.seg_onnx_session + except Exception as exc: + print(f"Failed to load ONNX segmentation model ({exc}), falling back to PyTorch.", flush=True) + return None + + +def load_depth_onnx_session(): + """Load the Depth-Anything ONNX session if available.""" + if not ENABLE_ONNX_INFERENCE: + return None + if state.depth_onnx_session is not None: + return state.depth_onnx_session + + model_path = ONNX_DIR / "depth_anything.onnx" + if not model_path.exists(): + print(f"ONNX depth model not found at {model_path}, falling back to PyTorch.", flush=True) + return None + + try: + import onnxruntime as ort + sess_options = ort.SessionOptions() + sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL + state.depth_onnx_session = ort.InferenceSession( + str(model_path), sess_options, providers=_ort_providers(), + ) + print(f"ONNX depth model loaded from {model_path}", flush=True) + return state.depth_onnx_session + except Exception as exc: + print(f"Failed to load ONNX depth model ({exc}), falling back to PyTorch.", flush=True) + return None diff --git a/apps/renderer/models/segmentation.py b/apps/renderer/models/segmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..38b96b8df51cfc8fa479b09b0e566352496e7646 --- /dev/null +++ b/apps/renderer/models/segmentation.py @@ -0,0 +1,132 @@ +"""Segmentation inference and model metadata helpers.""" + +import numpy as np +import torch +from PIL import Image + +import state +from config.models import ( + DEPTH_MODEL_NAME, + INTRINSIC_MODEL_VERSION, + MOGE_MODEL_NAME, + ONEFORMER_MODEL_NAME, +) +from config.runtime import ENABLE_INTRINSIC_SHADING, ENABLE_ONNX_INFERENCE +from models.loader import _load_segmentation_model +from enums import GeometryProvider + + +def _run_segmentation_onnx(img: Image.Image, img_np: np.ndarray, out_h: int, out_w: int) -> np.ndarray | None: + """Try running segmentation via ONNX Runtime. Returns None if unavailable.""" + if not ENABLE_ONNX_INFERENCE: + return None + from models.onnx_loader import load_seg_onnx_session + session = load_seg_onnx_session() + if session is None: + return None + + if state.seg_processor is None: + _load_segmentation_model() + + inputs = state.seg_processor(images=img, task_inputs=["semantic"], return_tensors="np") + input_feed = {k: v for k, v in inputs.items() if k in [inp.name for inp in session.get_inputs()]} + outputs = session.run(None, input_feed) + + # Post-process: outputs[1] is masks_queries_logits — take argmax over class queries + class_queries = torch.from_numpy(outputs[0]) + mask_queries = torch.from_numpy(outputs[1]) + + # Replicate HuggingFace post-processing + masks = torch.nn.functional.interpolate( + mask_queries, size=(out_h, out_w), mode="bilinear", align_corners=False, + ) + # masks shape: [batch, num_queries, H, W], class_queries: [batch, num_queries, num_classes+1] + seg_map = torch.einsum("bqc,bqhw->bchw", class_queries.softmax(-1)[..., :-1], masks.sigmoid()) + seg_map = seg_map[0].argmax(0) + return seg_map.numpy().astype(np.uint8) + + +def run_segmentation(img: Image.Image, img_np: np.ndarray, target_h: int | None = None, target_w: int | None = None): + """Run segmentation on the given image. + + If target_h/target_w are provided, post-process outputs at that resolution + (used when inference runs on a downscaled image but masks are needed at original size). + """ + h, w = img_np.shape[:2] + out_h = target_h if target_h is not None else h + out_w = target_w if target_w is not None else w + + with state.gpu_inference(): + return _run_segmentation_model(img, img_np, out_h, out_w) + + +def _run_segmentation_model(img: Image.Image, img_np: np.ndarray, out_h: int, out_w: int) -> np.ndarray: + # Try ONNX first + result = _run_segmentation_onnx(img, img_np, out_h, out_w) + if result is not None: + return result + + # Fallback to PyTorch + if state.seg_model is None: + _load_segmentation_model() + inputs = state.seg_processor( + images=img, + task_inputs=["semantic"], + return_tensors="pt", + ).to(state.device) + use_autocast = state.device.type == "cuda" + with torch.no_grad(): + if use_autocast: + with torch.autocast(device_type="cuda", dtype=torch.float16): + outputs = state.seg_model(**inputs) + else: + outputs = state.seg_model(**inputs) + result = state.seg_processor.post_process_semantic_segmentation( + outputs, + target_sizes=[(out_h, out_w)], + )[0] + return result.cpu().numpy().astype(np.uint8) + + +def segmenter_metadata_name() -> str: + return "oneformer-ade20k-swin-large" + + +def active_segmentation_model_name() -> str: + return ONEFORMER_MODEL_NAME + + +def active_geometry_model_name(provider: str | None) -> str | None: + if provider == GeometryProvider.MOGE_2: + return MOGE_MODEL_NAME + if provider and provider != GeometryProvider.HOMOGRAPHY: + return DEPTH_MODEL_NAME + return None + + +def active_model_metadata( + geometry: dict | None, + depth: np.ndarray | None, + shade_map: np.ndarray | None, + intrinsic_lighting_used: bool = False, +) -> dict: + geometry_provider = geometry.get("provider") if geometry else None + intrinsic_enabled = ENABLE_INTRINSIC_SHADING and intrinsic_lighting_used and shade_map is not None + return { + "segmentation": { + "backend": state.segmentation_backend, + "name": active_segmentation_model_name(), + }, + "geometry": { + "provider": geometry_provider, + "name": active_geometry_model_name(geometry_provider), + }, + "depth": { + "enabled": depth is not None, + "name": DEPTH_MODEL_NAME if depth is not None else None, + }, + "intrinsic": { + "enabled": intrinsic_enabled, + "name": INTRINSIC_MODEL_VERSION if intrinsic_enabled else None, + }, + } diff --git a/apps/renderer/qa/__init__.py b/apps/renderer/qa/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0f056703f438b85a308d09bb48a7a1b533798669 --- /dev/null +++ b/apps/renderer/qa/__init__.py @@ -0,0 +1 @@ +# QA subsystem for floor visualizer backend. diff --git a/apps/renderer/qa/constants.py b/apps/renderer/qa/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..ec47e6434e6c5d02783aa29dbb5596acd2ac5eed --- /dev/null +++ b/apps/renderer/qa/constants.py @@ -0,0 +1,14 @@ +"""QA tile descriptions, aliases, and image extension whitelist.""" + +QA_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"} + +QA_TILE_DESCRIPTIONS = { + "White Wood Flooring": "light plank flooring", + "Black White Marble Checkered": "black and white marble checkerboard tile", + "Grey Checkerboard": "grey checkerboard floor tile", + "Lilac 20x20 Ceramic": "lilac 20x20 ceramic tile", +} + +QA_TILE_ALIASES = { + "Black White Marble Checker": "Black White Marble Checkered", +} diff --git a/apps/renderer/qa/images.py b/apps/renderer/qa/images.py new file mode 100644 index 0000000000000000000000000000000000000000..592021d8aadf39cd94eb5eb52cb3d0a7f45316f0 --- /dev/null +++ b/apps/renderer/qa/images.py @@ -0,0 +1,136 @@ +"""QA image listing and deduplication via DigitalOcean Spaces.""" + +import mimetypes +import urllib.parse +from datetime import timedelta +from pathlib import Path + +from config.qa import QA_PRESIGNED_URL_EXPIRES_SECONDS +from config.spaces import SPACES_BUCKET, SPACES_UPLOAD_PREFIX +from errors import bad_request +from qa.constants import QA_IMAGE_EXTENSIONS +from qa.store import qa_utc_now +from services.spaces.upload import spaces_client + + +def qa_parse_date(value: str | None, name: str): + if not value: + return None + try: + from datetime import datetime + return datetime.strptime(value, "%Y-%m-%d").date() + except ValueError as exc: + bad_request(f"{name} must use YYYY-MM-DD.", exc) + + +def qa_date_prefixes(range_name: str, from_value: str | None, to_value: str | None): + today = qa_utc_now().date() + range_key = (range_name or "week").lower() + + if range_key == "all": + return [SPACES_UPLOAD_PREFIX] if SPACES_UPLOAD_PREFIX else [""] + if range_key == "today": + start = today + end = today + elif range_key == "week": + start = today - timedelta(days=6) + end = today + elif range_key == "month": + start = today.replace(day=1) + end = today + elif range_key == "custom": + start = qa_parse_date(from_value, "from") or today + end = qa_parse_date(to_value, "to") or start + else: + bad_request("range must be today, week, month, all, or custom.") + + if start > end: + bad_request("from must be before or equal to to.") + if (end - start).days > 370: + bad_request("Date range is too large.") + + prefixes = [] + cursor = start + while cursor <= end: + prefixes.append("/".join(part for part in [SPACES_UPLOAD_PREFIX, cursor.strftime("%Y/%m/%d")] if part)) + cursor += timedelta(days=1) + return prefixes + + +def qa_clean_etag(value) -> str: + return str(value or "").strip().strip('"') + + +def qa_object_fingerprint(etag, size) -> str | None: + clean_etag = qa_clean_etag(etag) + if not clean_etag: + return None + return f"{clean_etag}:{size or 0}" + + +def dedupe_qa_image_keys(image_keys: list[str]) -> list[str]: + client = spaces_client() + unique_keys: list[str] = [] + seen_keys: set[str] = set() + seen_fingerprints: set[str] = set() + + for key in image_keys: + if key in seen_keys: + continue + seen_keys.add(key) + + try: + metadata = client.head_object(Bucket=SPACES_BUCKET, Key=key) + except Exception as exc: + bad_request(f"Could not read DigitalOcean image metadata for {key}.", exc) + + fingerprint = qa_object_fingerprint(metadata.get("ETag"), metadata.get("ContentLength")) + if fingerprint and fingerprint in seen_fingerprints: + continue + if fingerprint: + seen_fingerprints.add(fingerprint) + unique_keys.append(key) + + return unique_keys + + +def list_qa_spaces_images(range_name: str, from_value: str | None, to_value: str | None, max_items: int): + client = spaces_client() + paginator = client.get_paginator("list_objects_v2") + images: list[dict] = [] + seen: set[str] = set() + seen_fingerprints: set[str] = set() + + for prefix in qa_date_prefixes(range_name, from_value, to_value): + kwargs = {"Bucket": SPACES_BUCKET, "Prefix": prefix} + for page in paginator.paginate(**kwargs): + for item in page.get("Contents", []): + key = item.get("Key", "") + if not key or key in seen or Path(key).suffix.lower() not in QA_IMAGE_EXTENSIONS: + continue + fingerprint = qa_object_fingerprint(item.get("ETag"), item.get("Size")) + if fingerprint and fingerprint in seen_fingerprints: + continue + seen.add(key) + if fingerprint: + seen_fingerprints.add(fingerprint) + url = client.generate_presigned_url( + "get_object", + Params={"Bucket": SPACES_BUCKET, "Key": key}, + ExpiresIn=QA_PRESIGNED_URL_EXPIRES_SECONDS, + ) + last_modified = item.get("LastModified") + images.append({ + "key": key, + "fileName": urllib.parse.unquote(Path(key).name), + "url": url, + "thumbnailUrl": url, + "uploadedAt": last_modified.isoformat().replace("+00:00", "Z") if last_modified else None, + "sizeBytes": item.get("Size"), + "contentType": mimetypes.guess_type(key)[0] or "application/octet-stream", + "etag": qa_clean_etag(item.get("ETag")), + }) + if len(images) >= max_items: + return sorted(images, key=lambda image: image.get("uploadedAt") or "", reverse=True) + + return sorted(images, key=lambda image: image.get("uploadedAt") or "", reverse=True) diff --git a/apps/renderer/qa/report.py b/apps/renderer/qa/report.py new file mode 100644 index 0000000000000000000000000000000000000000..c6f08c1b5c0062c8ccb20d6950d47f43f91b793f --- /dev/null +++ b/apps/renderer/qa/report.py @@ -0,0 +1,264 @@ +"""QA HTML report generation: build a standalone HTML report from run data.""" + +import html + +from enums import QaResult, QaStatus +from qa.store import qa_int + + +def qa_html(value) -> str: + if value is None: + return "" + return html.escape(str(value), quote=True) + + +def qa_status_label(status) -> str: + value = str(status or "unknown").lower() + if value in {s.value for s in QaStatus} | {r.value for r in QaResult}: + return value + return "unknown" + + +def qa_yes_no(value) -> str: + if isinstance(value, bool): + return "yes" if value else "no" + return "n/a" + + +def qa_score_label(value) -> str: + if isinstance(value, (int, float)): + try: + import math + if math.isfinite(value): + return f"{float(value):.2f}" + except (TypeError, ValueError): + pass + return "n/a" + + +def qa_list_label(value) -> str: + if isinstance(value, list): + items = [str(item) for item in value if isinstance(item, str) and item.strip()] + if items: + return "; ".join(items) + return "none" + + +def qa_metric_html(label: str, value: str) -> str: + return f"{qa_html(value)}{qa_html(label)}" + + +def qa_image_html(label: str, url) -> str: + if not isinstance(url, str) or not url.strip(): + return f""" +
+ {qa_html(label)} +

Missing screenshot

+
+ """ + return f""" +
+ {qa_html(label)} + {qa_html(label)} QA screenshot +
+ """ + + +def qa_gemini_report_html(gemini) -> str: + if not isinstance(gemini, dict): + return '

Gemini was not used or did not return a judgment for this result.

' + + issue_rows = [] + if gemini.get("coverageGapDetected"): + issue_rows.append(f"
  • Coverage gaps: {qa_html(qa_list_label(gemini.get('missedFloorAreas')))}
  • ") + if gemini.get("directionMismatchDetected"): + issue_rows.append(f"
  • Direction issues: {qa_html(qa_list_label(gemini.get('directionIssues')))}
  • ") + if gemini.get("bleedDetected"): + issue_rows.append("
  • Bleed detected on non-target surfaces.
  • ") + if isinstance(gemini.get("failureReasons"), list) and gemini.get("failureReasons"): + issue_rows.append(f"
  • Failure reasons: {qa_html(qa_list_label(gemini.get('failureReasons')))}
  • ") + + issues_html = f"
      {''.join(issue_rows)}
    " if issue_rows else "" + metrics_html = "".join([ + qa_metric_html("overall", qa_yes_no(gemini.get("overallPass"))), + qa_metric_html("tile", qa_yes_no(gemini.get("tileApplied"))), + qa_metric_html("coverage gap", qa_yes_no(gemini.get("coverageGapDetected"))), + qa_metric_html("direction", qa_score_label(gemini.get("directionQuality"))), + qa_metric_html("surface", qa_score_label(gemini.get("surfaceCorrectness"))), + qa_metric_html("edge", qa_score_label(gemini.get("edgeCompleteness"))), + qa_metric_html("occlusion", qa_score_label(gemini.get("occlusionBoundaryQuality"))), + qa_metric_html("perspective", qa_score_label(gemini.get("perspectiveQuality"))), + qa_metric_html("lighting", qa_score_label(gemini.get("lightingPreserved"))), + qa_metric_html("realism", qa_score_label(gemini.get("realism"))), + ]) + + return f""" +
    +
    {metrics_html}
    +

    {qa_html(gemini.get("notes") or "No notes returned.")}

    + {issues_html} +
    + """ + + +def qa_result_report_html(result: dict, index: int) -> str: + status = qa_status_label(result.get("status")) + image_name = result.get("imageName") or result.get("imageKey") or "Unknown image" + tile_name = result.get("tileName") or "Unknown tile" + error_html = f'

    {qa_html(result.get("error"))}

    ' if result.get("error") else "" + return f""" +
    +
    +
    +

    {qa_html(tile_name)}

    +

    {index}. {qa_html(image_name)}

    +
    + {qa_html(status)} +
    +
    + {qa_image_html("Before", result.get("beforeImageUrl"))} + {qa_image_html("After Tile Applied", result.get("afterImageUrl"))} +
    + {error_html} +
    +

    Gemini Judgment

    + {qa_gemini_report_html(result.get("gemini"))} +
    +
    + """ + + +def build_qa_report_html(run: dict) -> str: + status = qa_status_label(run.get("status")) + results = run.get("results") if isinstance(run.get("results"), list) else [] + result_cards = "\n".join( + qa_result_report_html(result, index) + for index, result in enumerate(results, start=1) + if isinstance(result, dict) + ) + if not result_cards: + result_cards = """ +
    +

    No screenshots yet

    +

    The report will include screenshots and Gemini judgment after Playwright writes the final report.

    +
    + """ + error_html = f'

    {qa_html(run.get("error"))}

    ' if run.get("error") else "" + title = f"QA Report {run.get('id', '')}".strip() + + return f""" + + + + + {qa_html(title)} + + + +
    +
    +
    +

    Real Browser QA Report

    +

    {qa_html(run.get("id") or "QA run")}

    +

    Generated from backend QA run data. Screenshots are served as report assets, not embedded base64.

    +
    + {qa_html(status)} +
    +
    + {qa_metric_html("done", f"{qa_int(run.get('completed'))}/{qa_int(run.get('total'))}")} + {qa_metric_html("passed", str(qa_int(run.get("passed"))))} + {qa_metric_html("failed", str(qa_int(run.get("failed"))))} + {qa_metric_html("updated", str(run.get("updatedAt") or "unknown"))} +
    + {error_html} + {result_cards} +
    + + +""" diff --git a/apps/renderer/qa/results.py b/apps/renderer/qa/results.py new file mode 100644 index 0000000000000000000000000000000000000000..317b75a73361248876c80929c1d2b01219a352d8 --- /dev/null +++ b/apps/renderer/qa/results.py @@ -0,0 +1,198 @@ +"""QA result parsing: extract structured results from Playwright JSON reports.""" + +import base64 +import json +import shutil +import urllib.parse +from pathlib import Path + +from config.qa import QA_FRONTEND_DIR +from enums import QaResult +from qa.store import qa_int, qa_run_root + + +def qa_status_from_playwright(result_status: str | None, test_status: str | None) -> str: + status = result_status or "" + if status == "passed": + return QaResult.PASSED + if status == "skipped": + return QaResult.SKIPPED + if status: + return QaResult.FAILED + if test_status == "expected": + return QaResult.PASSED + if test_status == "skipped": + return QaResult.SKIPPED + return QaResult.FAILED + + +def qa_find_attachment(result: dict, name: str): + for attachment in result.get("attachments", []) or []: + if attachment.get("name") == name: + return attachment + return None + + +def qa_attachment_path(attachment: dict | None, report_path: Path): + if not attachment or not attachment.get("path"): + return None + raw_path = Path(str(attachment["path"])) + candidates = [ + raw_path if raw_path.is_absolute() else (QA_FRONTEND_DIR / raw_path), + raw_path if raw_path.is_absolute() else (report_path.parent / raw_path), + ] + for candidate in candidates: + if candidate.exists(): + return candidate.resolve() + return None + + +def qa_asset_url(run_id: str, source_path: Path | None): + if source_path is None: + return None + root = qa_run_root(run_id).resolve() + try: + relative = source_path.resolve().relative_to(root) + except ValueError: + assets_dir = root / "assets" + assets_dir.mkdir(parents=True, exist_ok=True) + destination = assets_dir / source_path.name + if not destination.exists(): + shutil.copy2(source_path, destination) + relative = destination.relative_to(root) + return f"/qa/runs/{run_id}/assets/{urllib.parse.quote(relative.as_posix())}" + + +def qa_read_attachment_text(attachment: dict | None, report_path: Path): + if not attachment: + return "" + source_path = qa_attachment_path(attachment, report_path) + if source_path is not None: + return source_path.read_text() + body = attachment.get("body") + if not isinstance(body, str): + return "" + stripped = body.strip() + if stripped.startswith("{") or stripped.startswith("["): + return body + try: + return base64.b64decode(body).decode("utf-8") + except Exception: + return "" + + +def qa_parse_json_text(text: str): + if not text.strip(): + return None + try: + return json.loads(text) + except Exception: + start = text.find("{") + end = text.rfind("}") + if start >= 0 and end > start: + try: + return json.loads(text[start:end + 1]) + except Exception: + return None + return None + + +def qa_title_parts(title: str): + if ": apply " not in title: + return title, "Unknown tile" + image_name, rest = title.split(": apply ", 1) + tile_name = rest.rsplit(" to ", 1)[0] if " to " in rest else rest + return image_name, tile_name + + +def qa_grouped_case_metas(result: dict, report_path: Path): + metas = [] + for attachment in result.get("attachments", []) or []: + name = str(attachment.get("name") or "") + if not name.startswith("qa-case-") or not name.endswith("-meta"): + continue + meta = qa_parse_json_text(qa_read_attachment_text(attachment, report_path)) + if not isinstance(meta, dict): + continue + prefix = str(meta.get("attachmentPrefix") or name.removesuffix("-meta")) + metas.append((prefix, meta)) + + def sort_key(item): + _, meta = item + return qa_int(meta.get("caseIndex"), 0) + + return sorted(metas, key=sort_key) + + +def qa_case_status(meta: dict, fallback_status: str) -> str: + status = str(meta.get("status") or "").lower() + if status in {QaResult.PASSED, QaResult.FAILED, QaResult.SKIPPED}: + return status + return fallback_status + + +def collect_playwright_specs(suite: dict, entries: list[tuple[str, dict]]): + for spec in suite.get("specs", []) or []: + title = spec.get("title") or "Untitled QA case" + for test in spec.get("tests", []) or []: + entries.append((title, test)) + for child in suite.get("suites", []) or []: + collect_playwright_specs(child, entries) + + +def parse_qa_results(run_id: str, report_path: Path): + if not report_path.exists(): + return [] + report = json.loads(report_path.read_text()) + entries: list[tuple[str, dict]] = [] + for suite in report.get("suites", []) or []: + collect_playwright_specs(suite, entries) + + results = [] + for index, (title, test) in enumerate(entries): + playwright_results = test.get("results", []) or [{}] + final_result = playwright_results[-1] + fallback_status = qa_status_from_playwright(final_result.get("status"), test.get("status")) + grouped_cases = qa_grouped_case_metas(final_result, report_path) + if grouped_cases: + has_case_failure = any(qa_case_status(meta, fallback_status) == "failed" for _, meta in grouped_cases) + global_error = final_result.get("error", {}).get("message") if isinstance(final_result.get("error"), dict) else None + for case_index, (prefix, meta) in enumerate(grouped_cases, start=1): + before_attachment = qa_find_attachment(final_result, f"{prefix}-before-canvas") + after_attachment = qa_find_attachment(final_result, f"{prefix}-after-texture-canvas") + gemini_attachment = qa_find_attachment(final_result, f"{prefix}-gemini-judge") + status = qa_case_status(meta, fallback_status) + if fallback_status == "failed" and not has_case_failure: + status = "failed" + case_id = qa_int(meta.get("caseIndex"), case_index) + results.append({ + "id": f"{run_id}-{case_id}", + "imageKey": meta.get("imageName") or meta.get("roomName") or title, + "imageName": meta.get("imageName") or meta.get("roomName") or title, + "tileName": meta.get("tileName") or "Unknown tile", + "status": status, + "beforeImageUrl": qa_asset_url(run_id, qa_attachment_path(before_attachment, report_path)), + "afterImageUrl": qa_asset_url(run_id, qa_attachment_path(after_attachment, report_path)), + "gemini": qa_parse_json_text(qa_read_attachment_text(gemini_attachment, report_path)), + "error": meta.get("error") if isinstance(meta.get("error"), str) else global_error, + }) + continue + + image_name, tile_name = qa_title_parts(title) + before_attachment = qa_find_attachment(final_result, "before-canvas") + after_attachment = qa_find_attachment(final_result, "after-texture-canvas") + gemini_attachment = qa_find_attachment(final_result, "gemini-judge") + error = final_result.get("error", {}).get("message") if isinstance(final_result.get("error"), dict) else None + + results.append({ + "id": f"{run_id}-{index + 1}", + "imageKey": image_name, + "imageName": image_name, + "tileName": tile_name, + "status": fallback_status, + "beforeImageUrl": qa_asset_url(run_id, qa_attachment_path(before_attachment, report_path)), + "afterImageUrl": qa_asset_url(run_id, qa_attachment_path(after_attachment, report_path)), + "gemini": qa_parse_json_text(qa_read_attachment_text(gemini_attachment, report_path)), + "error": error, + }) + return results diff --git a/apps/renderer/qa/runner.py b/apps/renderer/qa/runner.py new file mode 100644 index 0000000000000000000000000000000000000000..89dd27ce73e31b79d7b3ff58a070d0398ba42eb9 --- /dev/null +++ b/apps/renderer/qa/runner.py @@ -0,0 +1,163 @@ +"""QA runner: execute Playwright tests, sync progress, finalize results.""" + +import json +import os +import subprocess +import time +from pathlib import Path + +from config.gemini import GEMINI_API_KEY +from config.qa import QA_FRONTEND_DIR, QA_FRONTEND_URL, QA_RUN_TIMEOUT_SECONDS +from enums import QaStatus, QaResult +from qa.results import parse_qa_results +from qa.scenarios import build_qa_scenarios, download_qa_images +from qa.store import qa_int, qa_iso_now, qa_run_root, read_qa_run, write_qa_run + + +def qa_runner_env(run_root: Path, scenarios: list[dict], use_gemini: bool, backend_url: str): + env = os.environ.copy() + env.update({ + "API_URL": backend_url, + "PLAYWRIGHT_BASE_URL": QA_FRONTEND_URL, + "QA_HTML_REPORT_DIR": str(run_root / "html-report"), + "QA_PLAYWRIGHT_OUTPUT_DIR": str(run_root / "artifacts"), + "QA_PROGRESS_FILE": str(run_root / "progress.json"), + "QA_PROGRESS_MODE": "cases", + "QA_RESULTS_DIR": str(run_root / "results"), + "QA_SCENARIOS": json.dumps(scenarios), + "QA_SKIP_GEMINI": "0" if use_gemini else "1", + "QA_TEST_IMAGES_DIR": str(run_root / "images"), + "QA_WORKERS": "1", + "VITE_API_URL": backend_url, + }) + if use_gemini: + if not GEMINI_API_KEY: + raise RuntimeError("Gemini is enabled for this QA run, but GEMINI_API_KEY is not configured.") + env["GEMINI_API_KEY"] = GEMINI_API_KEY + env.setdefault("GEMINI_MODEL", "gemini-3.1-flash-lite") + return env + + +def finalize_qa_run_from_report(run: dict, report_path: Path): + results = parse_qa_results(run["id"], report_path) + passed = sum(1 for result in results if result["status"] == QaResult.PASSED) + failed = sum(1 for result in results if result["status"] == QaResult.FAILED) + completed = sum(1 for result in results if result["status"] in {QaResult.PASSED, QaResult.FAILED, QaResult.SKIPPED}) + run.update({ + "completed": completed, + "failed": failed, + "passed": passed, + "results": results, + "status": QaStatus.COMPLETED if report_path.exists() else QaStatus.FAILED, + }) + if failed: + run["status"] = QaStatus.FAILED + + +def sync_qa_run_progress(run_id: str, progress_path: Path): + if not progress_path.exists(): + return + + try: + progress = json.loads(progress_path.read_text()) + except Exception: + return + + run = read_qa_run(run_id) + updates = { + "completed": qa_int(progress.get("completed"), qa_int(run.get("completed"))), + "failed": qa_int(progress.get("failed"), qa_int(run.get("failed"))), + "passed": qa_int(progress.get("passed"), qa_int(run.get("passed"))), + "progressUpdatedAt": progress.get("updatedAt"), + "skipped": qa_int(progress.get("skipped"), qa_int(run.get("skipped"))), + "total": qa_int(progress.get("total"), qa_int(run.get("total"))), + } + if run.get("status") == QaStatus.QUEUED: + updates["status"] = QaStatus.RUNNING + if all(run.get(key) == value for key, value in updates.items()): + return + + run.update(updates) + write_qa_run(run) + + +def run_playwright_qa(run_id: str, run_root: Path, env: dict, log_file): + command = ["npm", "run", "qa:e2e"] + progress_path = run_root / "progress.json" + process = subprocess.Popen( + command, + cwd=QA_FRONTEND_DIR, + env=env, + stderr=subprocess.STDOUT, + stdout=log_file, + ) + deadline = time.monotonic() + QA_RUN_TIMEOUT_SECONDS + + while True: + return_code = process.poll() + sync_qa_run_progress(run_id, progress_path) + if return_code is not None: + return return_code + + if time.monotonic() >= deadline: + process.terminate() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=10) + sync_qa_run_progress(run_id, progress_path) + raise subprocess.TimeoutExpired(command, QA_RUN_TIMEOUT_SECONDS) + + time.sleep(1) + + +def run_qa_task(run_id: str, image_keys: list[str], tiles: list[str], descriptions: dict[str, str], use_gemini: bool, backend_url: str): + run = read_qa_run(run_id) + run_root = qa_run_root(run_id) + log_path = run_root / "runner.log" + report_path = run_root / "results" / "real-qa.json" + summary_path = run_root / "qa-summary.md" + try: + if not QA_FRONTEND_URL: + raise RuntimeError("QA_FRONTEND_URL must point to the hosted frontend.") + if not QA_FRONTEND_DIR.exists(): + raise RuntimeError(f"QA_FRONTEND_DIR does not exist: {QA_FRONTEND_DIR}") + if not (QA_FRONTEND_DIR / "package.json").exists(): + raise RuntimeError(f"QA_FRONTEND_DIR must point to frontend/viz2d-demo: {QA_FRONTEND_DIR}") + + run.update({"status": QaStatus.RUNNING, "startedAt": qa_iso_now()}) + write_qa_run(run) + + downloaded_images = download_qa_images(run_id, image_keys) + scenarios = build_qa_scenarios(downloaded_images, tiles, descriptions) + (run_root / "scenarios.json").write_text(json.dumps(scenarios, indent=2)) + env = qa_runner_env(run_root, scenarios, use_gemini, backend_url) + + with log_path.open("w") as log_file: + exit_code = run_playwright_qa(run_id, run_root, env, log_file) + log_file.write(f"\nqa:e2e exit code: {exit_code}\n") + + subprocess.run( + ["npm", "run", "qa:report", "--", str(report_path), str(summary_path)], + cwd=QA_FRONTEND_DIR, + env=env, + stderr=subprocess.STDOUT, + stdout=log_file, + timeout=300, + ) + + run = read_qa_run(run_id) + finalize_qa_run_from_report(run, report_path) + if not report_path.exists(): + run["error"] = "Playwright did not create a JSON report. Check runner.log." + run["reportUrl"] = f"/qa/runs/{run_id}/report" + write_qa_run(run) + except subprocess.TimeoutExpired: + run = read_qa_run(run_id) + run.update({"status": QaStatus.FAILED, "error": "QA run timed out.", "reportUrl": f"/qa/runs/{run_id}/report"}) + write_qa_run(run) + except Exception as exc: + run = read_qa_run(run_id) + run.update({"status": QaStatus.FAILED, "error": str(exc), "reportUrl": f"/qa/runs/{run_id}/report"}) + write_qa_run(run) diff --git a/apps/renderer/qa/scenarios.py b/apps/renderer/qa/scenarios.py new file mode 100644 index 0000000000000000000000000000000000000000..e3a48d67f5a9c4f6fb9c228cbf1324752de83b3b --- /dev/null +++ b/apps/renderer/qa/scenarios.py @@ -0,0 +1,73 @@ +"""QA scenario building: tile normalization, image download, scenario generation.""" + +from pathlib import Path + +from config.spaces import SPACES_BUCKET +from qa.constants import QA_IMAGE_EXTENSIONS, QA_TILE_ALIASES, QA_TILE_DESCRIPTIONS +from services.spaces.upload import spaces_client + + +def qa_safe_filename(value: str, fallback: str = "image") -> str: + stem = "".join(char.lower() if char.isalnum() else "-" for char in value).strip("-") + while "--" in stem: + stem = stem.replace("--", "-") + return (stem or fallback)[:90] + + +def normalize_qa_tile(tile_name: str) -> str: + name = str(tile_name).strip() + return QA_TILE_ALIASES.get(name, name) + + +def qa_tile_description(tile_name: str, supplied_descriptions: dict[str, str]) -> str: + return supplied_descriptions.get(tile_name) or QA_TILE_DESCRIPTIONS.get(tile_name) or f"{tile_name} flooring material" + + +def parse_tile_descriptions(values) -> dict[str, str]: + descriptions: dict[str, str] = {} + if not isinstance(values, list): + return descriptions + for value in values: + if not isinstance(value, str) or ":" not in value: + continue + name, description = value.split(":", 1) + normalized = normalize_qa_tile(name) + if normalized and description.strip(): + descriptions[normalized] = description.strip() + return descriptions + + +def build_qa_scenarios(downloaded_images: list[dict], tiles: list[str], descriptions: dict[str, str]): + scenarios = [] + for image in downloaded_images: + image_name = Path(image["key"]).stem + for tile in tiles: + scenarios.append({ + "imagePath": str(image["path"]), + "keyword": "floor", + "roomName": f"{image_name}", + "surfaceClass": "floor", + "textureName": tile, + "textureDescription": qa_tile_description(tile, descriptions), + "expectedDirectionDescription": ( + "The applied material direction should follow the floor perspective and should not look arbitrarily rotated." + ), + }) + return scenarios + + +def download_qa_images(run_id: str, image_keys: list[str]): + from qa.store import qa_run_root + + client = spaces_client() + images_dir = qa_run_root(run_id) / "images" + images_dir.mkdir(parents=True, exist_ok=True) + downloaded = [] + for index, key in enumerate(image_keys, start=1): + extension = Path(key).suffix.lower() + if extension not in QA_IMAGE_EXTENSIONS: + extension = ".jpg" + destination = images_dir / f"{index:03d}-{qa_safe_filename(Path(key).stem)}{extension}" + client.download_file(SPACES_BUCKET, key, str(destination)) + downloaded.append({"key": key, "path": destination}) + return downloaded diff --git a/apps/renderer/qa/store.py b/apps/renderer/qa/store.py new file mode 100644 index 0000000000000000000000000000000000000000..fa7ba5e5a7b900885e61e352d2285b2650bf80ad --- /dev/null +++ b/apps/renderer/qa/store.py @@ -0,0 +1,52 @@ +"""QA run persistence helpers: read/write run JSON, SSE formatting, utilities.""" + +import json +from datetime import datetime, timezone +from pathlib import Path + +from config.paths import QA_RUN_DIR +from errors import bad_request, not_found + + +def qa_utc_now() -> datetime: + return datetime.now(timezone.utc) + + +def qa_iso_now() -> str: + return qa_utc_now().isoformat().replace("+00:00", "Z") + + +def qa_run_root(run_id: str) -> Path: + if Path(run_id).name != run_id or not run_id: + bad_request("Invalid QA run id.") + return QA_RUN_DIR / run_id + + +def qa_run_file(run_id: str) -> Path: + return qa_run_root(run_id) / "run.json" + + +def read_qa_run(run_id: str) -> dict: + path = qa_run_file(run_id) + if not path.exists(): + not_found("QA run not found.") + return json.loads(path.read_text()) + + +def write_qa_run(run: dict): + run["updatedAt"] = qa_iso_now() + root = qa_run_root(run["id"]) + root.mkdir(parents=True, exist_ok=True) + qa_run_file(run["id"]).write_text(json.dumps(run, indent=2)) + + +def qa_sse_event(event_name: str, payload: dict) -> str: + data = json.dumps(payload, separators=(",", ":")) + return f"event: {event_name}\ndata: {data}\n\n" + + +def qa_int(value, default: int = 0) -> int: + try: + return int(value) + except (TypeError, ValueError): + return default diff --git a/apps/renderer/requirements-base.txt b/apps/renderer/requirements-base.txt new file mode 100644 index 0000000000000000000000000000000000000000..5ea6e5faf862dd394bf404f36627370444590762 --- /dev/null +++ b/apps/renderer/requirements-base.txt @@ -0,0 +1,17 @@ +aiofiles==24.1.0 +boto3>=1.34,<2 +fastapi==0.115.12 +huggingface-hub>=0.33.5,<2.0 +numpy==2.2.6 +opencv-python-headless==4.11.0.86 +pillow==11.2.1 +python-multipart==0.0.20 +python-dotenv>=1.0,<2 +safetensors==0.5.3 +timm==1.0.15 +tokenizers==0.20.3 +transformers==4.46.3 +uvicorn==0.34.2 +scipy +git+https://github.com/compphoto/Intrinsic.git +PyJWT>=2.9,<3 diff --git a/apps/renderer/requirements-gpu-cu126.txt b/apps/renderer/requirements-gpu-cu126.txt new file mode 100644 index 0000000000000000000000000000000000000000..6d718b49d113cf19808bed8fb0884b5c6a516538 --- /dev/null +++ b/apps/renderer/requirements-gpu-cu126.txt @@ -0,0 +1,7 @@ +-r requirements-base.txt +--extra-index-url https://download.pytorch.org/whl/cu126 +torch==2.7.0+cu126 +torchvision==0.22.0+cu126 +triton==3.3.0 +git+https://github.com/microsoft/MoGe.git +git+https://github.com/facebookresearch/sam2.git diff --git a/apps/renderer/requirements-linux-cpu.txt b/apps/renderer/requirements-linux-cpu.txt new file mode 100644 index 0000000000000000000000000000000000000000..3b0a98789f9d59ceee0d20f540976f4519d1f9dc --- /dev/null +++ b/apps/renderer/requirements-linux-cpu.txt @@ -0,0 +1,4 @@ +-r requirements-base.txt +--extra-index-url https://download.pytorch.org/whl/cpu +torch==2.7.0+cpu +torchvision==0.22.0+cpu diff --git a/apps/renderer/requirements-mac.txt b/apps/renderer/requirements-mac.txt new file mode 100644 index 0000000000000000000000000000000000000000..67e5932ecf7c09916ecf9a57036c1b0c41a9656d --- /dev/null +++ b/apps/renderer/requirements-mac.txt @@ -0,0 +1,3 @@ +-r requirements-base.txt +torch==2.7.0 +torchvision==0.22.0 diff --git a/apps/renderer/requirements.txt b/apps/renderer/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..dde81109f1e51ef126e84b243828f49af23cd8fc --- /dev/null +++ b/apps/renderer/requirements.txt @@ -0,0 +1,89 @@ +aiofiles==24.1.0 +annotated-types==0.7.0 +anyio==4.9.0 +certifi==2025.4.26 +charset-normalizer==3.4.2 +click==8.1.8 +contourpy==1.3.2 +cycler==0.12.1 +exceptiongroup==1.3.0 +fastapi==0.115.12 +ffmpy==0.5.0 +filelock==3.18.0 +fonttools==4.58.0 +fsspec==2025.5.1 +gradio==5.31.0 +gradio_client==1.10.1 +groovy==0.1.2 +h11==0.16.0 +hf-xet==1.1.2 +httpcore==1.0.9 +httpx==0.28.1 +huggingface-hub==0.32.0 +idna==3.10 +Jinja2==3.1.6 +kiwisolver==1.4.8 +markdown-it-py==3.0.0 +MarkupSafe==3.0.2 +matplotlib==3.10.3 +mdurl==0.1.2 +mpmath==1.3.0 +networkx==3.4.2 +numpy==2.2.6 +nvidia-cublas-cu12==12.6.4.1 +nvidia-cuda-cupti-cu12==12.6.80 +nvidia-cuda-nvrtc-cu12==12.6.77 +nvidia-cuda-runtime-cu12==12.6.77 +nvidia-cudnn-cu12==9.5.1.17 +nvidia-cufft-cu12==11.3.0.4 +nvidia-cufile-cu12==1.11.1.6 +nvidia-curand-cu12==10.3.7.77 +nvidia-cusolver-cu12==11.7.1.2 +nvidia-cusparse-cu12==12.5.4.2 +nvidia-cusparselt-cu12==0.6.3 +nvidia-nccl-cu12==2.26.2 +nvidia-nvjitlink-cu12==12.6.85 +nvidia-nvtx-cu12==12.6.77 +opencv-python==4.11.0.86 +orjson==3.10.18 +packaging==25.0 +pandas==2.2.3 +pillow==11.2.1 +pydantic==2.11.5 +pydantic_core==2.33.2 +pydub==0.25.1 +Pygments==2.19.1 +pyparsing==3.2.3 +python-dateutil==2.9.0.post0 +python-multipart==0.0.20 +pytz==2025.2 +PyYAML==6.0.2 +regex==2024.11.6 +requests==2.32.3 +rich==14.0.0 +ruff==0.11.11 +safehttpx==0.1.6 +safetensors==0.5.3 +semantic-version==2.10.0 +shellingham==1.5.4 +six==1.17.0 +sniffio==1.3.1 +starlette==0.46.2 +sympy==1.14.0 +timm==1.0.15 +tokenizers==0.15.2 +tomlkit==0.13.2 +torch==2.7.0 +torchvision==0.22.0 +tqdm==4.67.1 +transformers==4.38.2 +triton==3.3.0 +typer==0.15.4 +typing-inspection==0.4.1 +typing_extensions==4.13.2 +tzdata==2025.2 +urllib3==2.4.0 +uvicorn==0.34.2 +websockets==15.0.1 +scipy +git+https://github.com/compphoto/Intrinsic.git diff --git a/apps/renderer/routes/__init__.py b/apps/renderer/routes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a5a685ab79eee3c30e42e2d51b52cf8780bccdea --- /dev/null +++ b/apps/renderer/routes/__init__.py @@ -0,0 +1 @@ +# Route modules for the floor-visualizer API. diff --git a/apps/renderer/routes/floor_direction.py b/apps/renderer/routes/floor_direction.py new file mode 100644 index 0000000000000000000000000000000000000000..ac9fce02a3a13b52e134b194360ff8a83d0a6d9e --- /dev/null +++ b/apps/renderer/routes/floor_direction.py @@ -0,0 +1,47 @@ +"""Floor direction analysis route.""" + +import cv2 +from fastapi import APIRouter, Depends, File, Form, UploadFile + +from errors import bad_request +from floor_direction import ( + analyze_floor_direction as analyze_floor_direction_from_segmentation, + parse_floor_segmentation, +) +from services.access.policy import require_client +from services.direction.response import floor_direction_response +from services.image.loading import load_uploaded_rgb_image +from routes.segmentation import build_oneformer_polygon_response + +router = APIRouter(tags=["floor-direction"], dependencies=[Depends(require_client)]) + + +@router.post("/analyze-floor-direction") +async def analyze_floor_direction_endpoint( + file: UploadFile = File(...), + include_overlay: bool = Form(False), + threshold: float = Form(0.5), + mask_threshold: float = Form(0.5), + min_area: float = Form(32.0), + simplify_epsilon: float = Form(2.0), +): + contents = await file.read() + if not contents: + bad_request("Upload a non-empty image file in the 'file' field.") + + _img, img_np = load_uploaded_rgb_image(contents) + image_bgr = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR) + segmentation_payload = build_oneformer_polygon_response( + contents, + threshold=threshold, + mask_threshold=mask_threshold, + min_area=min_area, + simplify_epsilon=simplify_epsilon, + ) + floor_segmentation = parse_floor_segmentation(segmentation_payload) + result = analyze_floor_direction_from_segmentation( + image_bgr, + floor_segmentation, + include_overlay=include_overlay, + ) + return floor_direction_response(result, floor_segmentation) diff --git a/apps/renderer/routes/gemini.py b/apps/renderer/routes/gemini.py new file mode 100644 index 0000000000000000000000000000000000000000..486ca06d4401e5cfde86d599933e227327548719 --- /dev/null +++ b/apps/renderer/routes/gemini.py @@ -0,0 +1,86 @@ +"""Gemini passes over finished renders: 'Enhance with AI' for organizations that have it.""" + +import asyncio +import base64 + +from fastapi import APIRouter, Depends, HTTPException + +from config.gemini import GEMINI_IMAGE_MODEL +from errors import bad_request +from services.access.policy import Principal, require_feature +from services.gemini.client import decode_inline_image_payload +from services.gemini.enhance import Surface, enhance_render, rate_limiter + +router = APIRouter(prefix="/gemini", tags=["gemini"]) + +AI_REFINEMENT = "ai_refinement" +POSITIONS = ("the far left", "the left", "the middle", "the right", "the far right") + + +def _number(value) -> float | None: + return float(value) if isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0 else None + + +def _text(value, limit: int = 200) -> str | None: + return value.strip()[:limit] or None if isinstance(value, str) else None + + +def _surfaces(payload: dict) -> list[Surface]: + items = payload.get("surfaces") + if not isinstance(items, list): + # Old payload: one tile name for the whole render. + name = _text(payload.get("tileName")) + return [Surface(name="the tiled surface", kind="floor", tile_name=name)] if name else [] + surfaces = [] + for item in items[:6]: + if not isinstance(item, dict): + continue + surfaces.append(Surface( + name=_text(item.get("name"), 60) or "a surface", + kind="wall" if item.get("kind") == "wall" else "floor", + tile_name=_text(item.get("tileName")), + image_url=_text(item.get("imageUrl"), 2000), + width_mm=_number(item.get("widthMm")), + height_mm=_number(item.get("heightMm")), + mural=item.get("mural") is True, + position=item.get("position") if item.get("position") in POSITIONS else None, + )) + return surfaces + + +@router.post("/refine-tile-render") +async def refine_tile_render_with_gemini( + payload: dict, + principal: Principal = Depends(require_feature(AI_REFINEMENT)), +): + """The render (data URL), its surfaces and optional surface mask in; the finished image out. + + 422 PATTERN_CHANGED when Gemini's answer did not keep the render's design; + the visualizer then keeps showing its own render. + """ + image_value = payload.get("image") if isinstance(payload, dict) else None + if not isinstance(image_value, str): + bad_request("Image is required.") + if not rate_limiter.allow(principal.organization_id or principal.user_id): + raise HTTPException(status_code=429, detail="Too many AI enhancements this hour. Please try again later.") + + image_bytes, _mime = decode_inline_image_payload(image_value) + mask_value = payload.get("mask") + mask_bytes = decode_inline_image_payload(mask_value)[0] if isinstance(mask_value, str) and mask_value else None + result = await asyncio.to_thread(enhance_render, image_bytes, _surfaces(payload), mask_bytes) + if result.image is None: + raise HTTPException( + status_code=422, + detail={ + "code": "PATTERN_CHANGED", + "message": "The AI could not keep the design exact this time, so your render is unchanged. Try again.", + "similarity": result.similarity, + }, + ) + return { + "image": "data:image/jpeg;base64," + base64.b64encode(result.image).decode("ascii"), + "model": GEMINI_IMAGE_MODEL, + "similarity": result.similarity, + "attempts": result.attempts, + "timings": result.timings_ms, + } diff --git a/apps/renderer/routes/materials.py b/apps/renderer/routes/materials.py new file mode 100644 index 0000000000000000000000000000000000000000..31f628ece0f780d84fb07ae62d3358bea0f08e3a --- /dev/null +++ b/apps/renderer/routes/materials.py @@ -0,0 +1,22 @@ +"""Material map preparation route.""" + +from fastapi import APIRouter, Depends, File, Form, UploadFile + +from errors import bad_request +from services.access.policy import require_client +from services.materials.cache import build_tile_material_package + +router = APIRouter(prefix="/materials", tags=["materials"], dependencies=[Depends(require_client)]) + + +@router.post("/prepare") +async def prepare_material_maps( + file: UploadFile = File(...), + base_roughness: float = Form(0.42), +): + if file.content_type and not file.content_type.startswith("image/"): + bad_request("Upload must be a tile image.") + contents = await file.read() + if not contents: + bad_request("Upload must not be empty.") + return build_tile_material_package(contents, base_roughness) diff --git a/apps/renderer/routes/qa.py b/apps/renderer/routes/qa.py new file mode 100644 index 0000000000000000000000000000000000000000..1dd937a26b755bfd9b6456925572c23c933f80cc --- /dev/null +++ b/apps/renderer/routes/qa.py @@ -0,0 +1,170 @@ +"""QA run management and reporting routes.""" + +import asyncio +import json +import mimetypes +import time +import uuid + +from fastapi import APIRouter, BackgroundTasks, Body, Depends, Query, Request, Response +from fastapi.responses import StreamingResponse + +from config.qa import QA_BACKEND_URL, QA_MAX_IMAGES, QA_MAX_TESTS +from enums import QaStatus +from errors import bad_request, not_found +from qa.constants import QA_TILE_DESCRIPTIONS +from qa.images import dedupe_qa_image_keys, list_qa_spaces_images +from qa.report import build_qa_report_html +from qa.runner import run_qa_task +from qa.scenarios import normalize_qa_tile, parse_tile_descriptions +from qa.store import qa_iso_now, qa_run_root, qa_sse_event, read_qa_run, write_qa_run +from services.access.policy import require_admin + +router = APIRouter(prefix="/qa", tags=["qa"], dependencies=[Depends(require_admin)]) + + +@router.get("/images") +async def qa_images( + range: str = Query("week"), + from_value: str | None = Query(None, alias="from"), + to: str | None = Query(None), + max_items: int = Query(100, ge=1, le=500), +): + return {"images": list_qa_spaces_images(range, from_value, to, min(max_items, QA_MAX_IMAGES))} + + +@router.post("/runs") +async def create_qa_run( + request: Request, + background_tasks: BackgroundTasks, + payload: dict = Body(...), +): + raw_image_keys = payload.get("imageKeys") + if not isinstance(raw_image_keys, list): + bad_request("imageKeys must be a non-empty array.") + image_keys = [str(key).strip() for key in raw_image_keys if isinstance(key, str) and str(key).strip()] + if not image_keys: + bad_request("Select at least one image.") + image_keys = dedupe_qa_image_keys(image_keys) + if not image_keys: + bad_request("All selected images were duplicates.") + if len(image_keys) > QA_MAX_IMAGES: + bad_request(f"Select at most {QA_MAX_IMAGES} images.") + + raw_tiles = payload.get("tiles") + if raw_tiles is None: + raw_tiles = list(QA_TILE_DESCRIPTIONS) + if not isinstance(raw_tiles, list): + bad_request("tiles must be an array.") + tiles = [] + for tile in raw_tiles: + if not isinstance(tile, str) or not tile.strip(): + continue + normalized = normalize_qa_tile(tile) + if normalized not in tiles: + tiles.append(normalized) + if not tiles: + bad_request("Select at least one tile.") + + total = len(image_keys) * len(tiles) + if total > QA_MAX_TESTS: + bad_request(f"QA matrix is too large. Max tests: {QA_MAX_TESTS}.") + + run_id = f"qa_{uuid.uuid4().hex}" + use_gemini = bool(payload.get("useGemini", True)) + descriptions = parse_tile_descriptions(payload.get("tileDescriptions")) + backend_url = QA_BACKEND_URL or str(request.base_url).rstrip("/") + run = { + "id": run_id, + "status": QaStatus.QUEUED, + "createdAt": qa_iso_now(), + "updatedAt": qa_iso_now(), + "total": total, + "completed": 0, + "passed": 0, + "failed": 0, + "imageKeys": image_keys, + "tiles": tiles, + "useGemini": use_gemini, + "reportUrl": f"/qa/runs/{run_id}/report", + "results": [], + } + write_qa_run(run) + background_tasks.add_task(run_qa_task, run_id, image_keys, tiles, descriptions, use_gemini, backend_url) + return run + + +@router.get("/runs/{run_id}") +async def qa_run_status(run_id: str): + return read_qa_run(run_id) + + +@router.get("/runs/{run_id}/events") +async def qa_run_events(run_id: str, request: Request): + read_qa_run(run_id) + + async def event_stream(): + last_payload = "" + last_keepalive = time.monotonic() + while True: + if await request.is_disconnected(): + break + + run = read_qa_run(run_id) + payload = json.dumps(run, sort_keys=True) + if payload != last_payload: + last_payload = payload + yield qa_sse_event("run", run) + if run.get("status") not in {QaStatus.QUEUED, QaStatus.RUNNING}: + break + elif time.monotonic() - last_keepalive >= 15: + last_keepalive = time.monotonic() + yield ": keepalive\n\n" + + await asyncio.sleep(1) + + return StreamingResponse( + event_stream(), + media_type="text/event-stream", + headers={ + "Cache-Control": "no-cache, no-transform", + "Connection": "keep-alive", + "X-Accel-Buffering": "no", + }, + ) + + +@router.get("/runs/{run_id}/report") +async def qa_run_report(run_id: str): + run = read_qa_run(run_id) + return Response(content=build_qa_report_html(run), media_type="text/html", headers={"Cache-Control": "no-store"}) + + +@router.get("/runs/{run_id}/report.md") +async def qa_run_markdown_report(run_id: str): + root = qa_run_root(run_id) + report_path = root / "qa-summary.md" + if not report_path.exists(): + run = read_qa_run(run_id) + content = "\n".join([ + "# Real Browser QA Summary", + "", + f"Status: {run.get('status', 'unknown')}", + "", + run.get("error") or "The QA summary has not been generated yet.", + "", + ]) + return Response(content=content, media_type="text/markdown", headers={"Cache-Control": "no-store"}) + return Response(content=report_path.read_text(), media_type="text/markdown", headers={"Cache-Control": "no-store"}) + + +@router.get("/runs/{run_id}/assets/{asset_path:path}") +async def qa_run_asset(run_id: str, asset_path: str): + root = qa_run_root(run_id).resolve() + target = (root / asset_path).resolve() + if root != target and root not in target.parents: + bad_request("Invalid QA asset path.") + if not target.exists() or not target.is_file(): + not_found("QA asset not found.") + media_type = mimetypes.guess_type(target.name)[0] or "application/octet-stream" + return Response(content=target.read_bytes(), media_type=media_type, headers={"Cache-Control": "private, max-age=3600"}) diff --git a/apps/renderer/routes/segmentation.py b/apps/renderer/routes/segmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..0657ae36ecfbdf2eef07299c128ba35560ef4bc2 --- /dev/null +++ b/apps/renderer/routes/segmentation.py @@ -0,0 +1,123 @@ +"""Segmentation routes: panoptic polygon extraction and bundle generation.""" + +import numpy as np +import torch +from fastapi import APIRouter, Depends, File, Form, UploadFile + +from config.models import ONEFORMER_MODEL_NAME +from models.loader import _load_segmentation_model +from services.access.policy import require_client +from services.image.loading import load_uploaded_rgb_image +from services.image.polygons import mask_to_polygons +from services.pipeline.builder import build_segmentation_bundle +from state import class_name_for_id + +router = APIRouter(tags=["segmentation"], dependencies=[Depends(require_client)]) + + +def build_oneformer_polygon_response( + contents: bytes, + *, + threshold: float = 0.5, + mask_threshold: float = 0.5, + min_area: float = 32.0, + simplify_epsilon: float = 2.0, +) -> dict: + img, img_np = load_uploaded_rgb_image(contents) + h, w = img_np.shape[:2] + + threshold = float(np.clip(threshold, 0.0, 1.0)) + mask_threshold = float(np.clip(mask_threshold, 0.0, 1.0)) + min_area = max(0.0, float(min_area)) + simplify_epsilon = max(0.0, float(simplify_epsilon)) + + _load_segmentation_model() + + import state as _state + inputs = _state.seg_processor( + images=img, + task_inputs=["panoptic"], + return_tensors="pt", + ).to(_state.device) + with _state.gpu_inference(): + with torch.no_grad(): + outputs = _state.seg_model(**inputs) + + result = _state.seg_processor.post_process_panoptic_segmentation( + outputs, + threshold=threshold, + mask_threshold=mask_threshold, + target_sizes=[(h, w)], + )[0] + segmentation = result.get("segmentation") + if segmentation is None: + return { + "model": ONEFORMER_MODEL_NAME, + "task": "panoptic", + "width": int(w), + "height": int(h), + "segments": [], + } + + if isinstance(segmentation, torch.Tensor): + segment_map = segmentation.cpu().numpy() + else: + segment_map = np.asarray(segmentation) + + segments = [] + for segment_info in result.get("segments_info", []): + segment_id = int(segment_info["id"]) + label_id = int(segment_info["label_id"]) + mask = segment_map == segment_id + polygons = mask_to_polygons(mask, min_area, simplify_epsilon) + if not polygons: + continue + + score = segment_info.get("score") + segments.append({ + "id": segment_id, + "labelId": label_id, + "label": class_name_for_id(label_id), + "confidence": float(score) if score is not None else None, + "wasFused": bool(segment_info.get("was_fused", False)), + "pixelArea": int(mask.sum()), + "polygons": polygons, + }) + + segments.sort(key=lambda item: item["pixelArea"], reverse=True) + return { + "model": ONEFORMER_MODEL_NAME, + "task": "panoptic", + "width": int(w), + "height": int(h), + "threshold": threshold, + "maskThreshold": mask_threshold, + "minArea": min_area, + "simplifyEpsilon": simplify_epsilon, + "segmentCount": len(segments), + "segments": segments, + } + + +@router.post("/oneformer/polygons") +async def oneformer_polygons( + file: UploadFile = File(...), + threshold: float = Form(0.5), + mask_threshold: float = Form(0.5), + min_area: float = Form(32.0), + simplify_epsilon: float = Form(2.0), +): + contents = await file.read() + return build_oneformer_polygon_response( + contents, + threshold=threshold, + mask_threshold=mask_threshold, + min_area=min_area, + simplify_epsilon=simplify_epsilon, + ) + + +@router.post("/segment") +async def segment(file: UploadFile = File(...)): + contents = await file.read() + return build_segmentation_bundle(contents) diff --git a/apps/renderer/routes/viz2d.py b/apps/renderer/routes/viz2d.py new file mode 100644 index 0000000000000000000000000000000000000000..12a08c664bfc1c1bfca1407a8808b3bffc896dd7 --- /dev/null +++ b/apps/renderer/routes/viz2d.py @@ -0,0 +1,313 @@ +"""Viz2D conversion and job management routes.""" + +import asyncio +import json +import math +import time +import uuid +from datetime import datetime, timezone +from pathlib import Path + +from fastapi import APIRouter, BackgroundTasks, Body, Depends, File, Form, Query, Response, UploadFile + +from config.paths import JOB_DIR, SAMPLE_DIR, UPLOAD_DIR +from config.runtime import CONVERSION_TARGET_MS, DEBUG_ARTIFACTS_ENABLED +from errors import bad_request, conflict, not_found +from services.access.policy import Principal, ensure_job_access, owner_fields, require_admin, require_client +from services.access.usage import charge_free_try, refund_free_try +from services.image.loading import normalize_room_upload +from services.jobs.conversion import run_conversion_task +from services.jobs.store import read_job, write_job +from services.jobs.timing import estimate_conversion_ms +from services.spaces.upload import upload_input_image_to_spaces +from enums import JobStatus + +router = APIRouter(prefix="/viz2d", tags=["viz2d"]) + +JOB_STATUS_MAX_WAIT_MS = 10_000 +JOB_STATUS_WAIT_STEP_S = 0.05 +JOB_TERMINAL_STATUSES = {JobStatus.COMPLETED, JobStatus.PREVIEW_READY, JobStatus.FAILED} +# Sample rooms by name. Processed from the server's own copy, so they are never +# charged as a free try and the browser cannot pass off another photo as one. +SAMPLE_ROOMS = {"living-room": "living-room.jpg"} + + +@router.post("/convert") +async def convert_to_viz2d( + background_tasks: BackgroundTasks, + file: UploadFile | None = File(None), + sample: str | None = Form(None), + principal: Principal | None = Depends(require_client), +): + """Start a job for an uploaded room photo, or for a named sample room (`sample`). + + A Prevision account's upload uses one of its free tries, charged here + before the job is accepted (402 when none are left) and given back if the + job fails. Sample rooms are free. + """ + t_upload_start = time.perf_counter() + + if sample is not None: + if sample not in SAMPLE_ROOMS: + bad_request("Unknown sample room.") + contents = (SAMPLE_DIR / SAMPLE_ROOMS[sample]).read_bytes() + original_filename = SAMPLE_ROOMS[sample] + else: + if file is None: + bad_request("Upload a room photo.") + if file.content_type and not file.content_type.startswith("image/"): + bad_request("Upload must be a JPG or PNG image.") + contents = await file.read() + original_filename = file.filename + if not contents: + bad_request("Upload must not be empty.") + t_read = time.perf_counter() - t_upload_start + + t0 = time.perf_counter() + normalized_contents = normalize_room_upload(contents) + t_normalize = time.perf_counter() - t0 + + job_id = uuid.uuid4().hex + generation_id = None if sample is not None else await asyncio.to_thread(charge_free_try, principal, job_id) + try: + return _accept_job( + background_tasks, job_id, generation_id, principal, normalized_contents, contents, original_filename, + t_read, t_normalize, + ) + except Exception: + await asyncio.to_thread(refund_free_try, generation_id) + raise + + +def _accept_job( + background_tasks: BackgroundTasks, + job_id: str, + generation_id: str | None, + principal: Principal | None, + normalized_contents: bytes, + contents: bytes, + original_filename: str | None, + t_read: float, + t_normalize: float, +) -> dict: + content_type = "image/jpeg" + ext = ".jpg" + upload_path = UPLOAD_DIR / f"{job_id}{ext}" + t0 = time.perf_counter() + upload_path.write_bytes(normalized_contents) + t_persist = time.perf_counter() - t0 + + size_kb = len(contents) / 1024 + print( + f"\n[JOB {job_id[:8]}] Upload received: {original_filename} ({size_kb:.0f} KB)" + f" | read={t_read:.2f}s | normalize={t_normalize:.2f}s | persist={t_persist:.2f}s", + flush=True, + ) + + job = { + "id": job_id, + "status": JobStatus.QUEUED, + "phase": "queued", + "progress": 0, + "phaseProgress": 0, + "message": "Starting analysis\u2026", + "createdAt": datetime.now(timezone.utc).isoformat(), + **owner_fields(principal), + # The free try this job used (Prevision); refunded if the job fails. + **({"generationId": generation_id} if generation_id else {}), + "estimatedTotalMs": estimate_conversion_ms(), + "estimatedRemainingMs": estimate_conversion_ms(), + "targetMs": CONVERSION_TARGET_MS, + "inputUrl": f"/viz2d/jobs/{job_id}/input", + "outputUrl": f"/viz2d/jobs/{job_id}/file", + "debugUrl": f"/viz2d/jobs/{job_id}/debug" if DEBUG_ARTIFACTS_ENABLED else None, + "requestTimings": { + "serverReadMs": round(t_read * 1000), + "normalizeMs": round(t_normalize * 1000), + "persistMs": round(t_persist * 1000), + }, + } + write_job(job) + background_tasks.add_task(run_conversion_task, job_id, upload_path) + background_tasks.add_task(upload_input_image_to_spaces, job_id, upload_path, original_filename, content_type) + return job + + +@router.get("/jobs") +async def viz2d_list_jobs( + status: str | None = Query(None, description="Filter by status: COMPLETED, FAILED, PROCESSING"), + limit: int = Query(50, ge=1, le=200), + offset: int = Query(0, ge=0), + _admin: Principal = Depends(require_admin), +): + """List all jobs, newest first (administrators only).""" + job_files = sorted(JOB_DIR.glob("*.json"), key=lambda p: p.stat().st_mtime, reverse=True) + jobs = [] + for path in job_files: + try: + job = json.loads(path.read_text()) + except (json.JSONDecodeError, OSError): + continue + if status and job.get("status") != status: + continue + jobs.append(job) + total = len(jobs) + return {"total": total, "offset": offset, "limit": limit, "jobs": jobs[offset : offset + limit]} + + +@router.post("/jobs/{job_id}/client-timings") +async def viz2d_record_client_timings( + job_id: str, + payload: dict = Body(...), + principal: Principal | None = Depends(require_client), +): + """Persist bounded browser timing events alongside their conversion job.""" + ensure_job_access(read_job(job_id), principal) + raw_events = payload.get("events") + if not isinstance(raw_events, list): + bad_request("events must be a list.") + + events = [] + for raw_event in raw_events[:20]: + if not isinstance(raw_event, dict): + continue + event = {} + for key, value in list(raw_event.items())[:40]: + if not isinstance(key, str) or len(key) > 64: + continue + if isinstance(value, bool): + event[key] = value + elif isinstance(value, (int, float)): + try: + numeric_value = float(value) + except (OverflowError, ValueError): + continue + if math.isfinite(numeric_value): + event[key] = round(numeric_value, 3) + elif isinstance(value, str): + event[key] = value[:200] + if isinstance(event.get("type"), str): + events.append(event) + + job = read_job(job_id) + existing = job.get("clientTimingEvents") + if not isinstance(existing, list): + existing = [] + job["clientTimingEvents"] = (existing + events)[-50:] + job["clientTimingsUpdatedAt"] = datetime.now(timezone.utc).isoformat() + write_job(job) + return {"ok": True, "stored": len(events)} + + +@router.get("/jobs/{job_id}") +async def viz2d_job_status( + job_id: str, + wait_ms: int = Query(0, alias="waitMs", ge=0, le=JOB_STATUS_MAX_WAIT_MS), + principal: Principal | None = Depends(require_client), +): + """Return the job, optionally holding the request until it changes. + + With waitMs the response is sent as soon as status, phase or progress + moves (or the job finishes), so clients learn of completion within one + check step instead of up to a full client-side polling interval. + """ + job = read_job(job_id) + ensure_job_access(job, principal) + if wait_ms <= 0 or job.get("status") in JOB_TERMINAL_STATUSES: + return job + snapshot = (job.get("status"), job.get("phase"), job.get("progress")) + deadline = time.monotonic() + wait_ms / 1000 + while time.monotonic() < deadline: + await asyncio.sleep(JOB_STATUS_WAIT_STEP_S) + job = read_job(job_id) + if job.get("status") in JOB_TERMINAL_STATUSES: + return job + if (job.get("status"), job.get("phase"), job.get("progress")) != snapshot: + return job + return job + + +@router.get("/jobs/{job_id}/debug") +async def viz2d_job_debug(job_id: str, _admin: Principal = Depends(require_admin)): + read_job(job_id) + if not DEBUG_ARTIFACTS_ENABLED: + not_found("Debug artifacts are disabled on this server.") + manifest_path = JOB_DIR / f"{job_id}.debug" / "manifest.json" + if not manifest_path.exists(): + not_found("Debug artifacts are not available yet.") + return Response( + content=manifest_path.read_bytes(), + media_type="application/json", + headers={"Cache-Control": "no-store"}, + ) + + +@router.get("/jobs/{job_id}/debug/assets/{asset_name}") +async def viz2d_job_debug_asset( + job_id: str, asset_name: str, _admin: Principal = Depends(require_admin) +): + read_job(job_id) + if Path(asset_name).name != asset_name: + bad_request("Invalid debug asset name.") + asset_path = JOB_DIR / f"{job_id}.debug" / asset_name + if not asset_path.exists() or not asset_path.is_file(): + not_found("Debug asset not found.") + media_type = "image/jpeg" if asset_path.suffix.lower() in {".jpg", ".jpeg"} else "application/octet-stream" + return Response( + content=asset_path.read_bytes(), + media_type=media_type, + headers={"Cache-Control": "private, max-age=3600"}, + ) + + +@router.get("/jobs/{job_id}/file") +async def viz2d_job_file(job_id: str, principal: Principal | None = Depends(require_client)): + job = read_job(job_id) + ensure_job_access(job, principal) + if job.get("status") not in (JobStatus.COMPLETED, JobStatus.PREVIEW_READY): + conflict("Job is not completed yet.") + binary_bundle_path = JOB_DIR / f"{job_id}.vizbundle" + if not binary_bundle_path.exists(): + not_found("Job output not found.") + is_preview = job.get("status") == JobStatus.PREVIEW_READY + return Response( + content=binary_bundle_path.read_bytes(), + media_type="application/zip", + headers={ + "Content-Disposition": 'attachment; filename="visualizer.vizbundle"', + "X-Bundle-Quality": "preview" if is_preview else "full", + }, + ) + + +@router.get("/jobs/{job_id}/assets/{asset_name}") +async def viz2d_job_asset( + job_id: str, asset_name: str, principal: Principal | None = Depends(require_client) +): + ensure_job_access(read_job(job_id), principal) + if Path(asset_name).name != asset_name: + bad_request("Invalid asset name.") + asset_path = JOB_DIR / f"{job_id}.assets" / asset_name + if not asset_path.exists() or not asset_path.is_file(): + not_found("Job asset not found.") + return Response( + content=asset_path.read_bytes(), + media_type="application/octet-stream", + headers={"Cache-Control": "private, max-age=3600"}, + ) + + +@router.get("/jobs/{job_id}/input") +async def viz2d_job_input(job_id: str, principal: Principal | None = Depends(require_client)): + """The normalized upload, for its owner or an administrator (replaces the public /uploads mount).""" + if Path(job_id).name != job_id: + bad_request("Invalid job id.") + ensure_job_access(read_job(job_id), principal) + upload_path = UPLOAD_DIR / f"{job_id}.jpg" + if not upload_path.exists() or not upload_path.is_file(): + not_found("Upload not found.") + return Response( + content=upload_path.read_bytes(), + media_type="image/jpeg", + headers={"Cache-Control": "private, max-age=3600"}, + ) diff --git a/apps/renderer/samples/living-room.jpg b/apps/renderer/samples/living-room.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4b6df9c324171b41b4e3da971a3910f14d0d80dd --- /dev/null +++ b/apps/renderer/samples/living-room.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2bbc2fe7a9b2100a47fccf830ca282aceed4985590d929b5b122a46b10851ff +size 337930 diff --git a/apps/renderer/scripts/export_onnx.py b/apps/renderer/scripts/export_onnx.py new file mode 100644 index 0000000000000000000000000000000000000000..88940bb1b3c70a603302cae26659df693f262e6d --- /dev/null +++ b/apps/renderer/scripts/export_onnx.py @@ -0,0 +1,104 @@ +"""Export PyTorch models to ONNX format for accelerated inference. + +Usage: + python scripts/export_onnx.py --model seg # export segmentation model + python scripts/export_onnx.py --model depth # export depth model + python scripts/export_onnx.py --model all # export both + +Models are saved to the onnx_models/ directory. +Set VISUALIZER_CONFIG env var to use the correct model names from your TOML config. +""" + +import argparse +import sys +from pathlib import Path + +# Add parent dir to path so we can import project modules +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +import numpy as np +import torch +from PIL import Image + +ONNX_DIR = Path(__file__).resolve().parent.parent / "onnx_models" + + +def export_segmentation(): + from config.models import ONEFORMER_MODEL_NAME + from transformers import OneFormerProcessor, OneFormerForUniversalSegmentation + + print(f"Loading OneFormer: {ONEFORMER_MODEL_NAME} ...") + processor = OneFormerProcessor.from_pretrained(ONEFORMER_MODEL_NAME) + model = OneFormerForUniversalSegmentation.from_pretrained(ONEFORMER_MODEL_NAME) + model.eval() + + # Create dummy input (1024x1024 RGB) + dummy_image = Image.fromarray(np.random.randint(0, 255, (1024, 1024, 3), dtype=np.uint8)) + inputs = processor(images=dummy_image, task_inputs=["semantic"], return_tensors="pt") + + output_path = ONNX_DIR / "oneformer_seg.onnx" + ONNX_DIR.mkdir(parents=True, exist_ok=True) + + print(f"Exporting to {output_path} ...") + input_names = list(inputs.keys()) + torch.onnx.export( + model, + tuple(inputs[k] for k in input_names), + str(output_path), + input_names=input_names, + output_names=["class_queries_logits", "masks_queries_logits"], + dynamic_axes={ + name: {0: "batch", 2: "height", 3: "width"} if inputs[name].ndim == 4 + else {0: "batch"} for name in input_names + }, + opset_version=17, + do_constant_folding=True, + ) + print(f"Segmentation models exported: {output_path} ({output_path.stat().st_size / 1e6:.1f} MB)") + + +def export_depth(): + from config.models import DEPTH_MODEL_NAME + from transformers import AutoImageProcessor, AutoModelForDepthEstimation + + print(f"Loading Depth model: {DEPTH_MODEL_NAME} ...") + processor = AutoImageProcessor.from_pretrained(DEPTH_MODEL_NAME) + model = AutoModelForDepthEstimation.from_pretrained(DEPTH_MODEL_NAME) + model.eval() + + # Create dummy input (1024x768 RGB) + dummy_image = Image.fromarray(np.random.randint(0, 255, (768, 1024, 3), dtype=np.uint8)) + inputs = processor(images=dummy_image, return_tensors="pt") + + output_path = ONNX_DIR / "depth_anything.onnx" + ONNX_DIR.mkdir(parents=True, exist_ok=True) + + print(f"Exporting to {output_path} ...") + input_names = list(inputs.keys()) + torch.onnx.export( + model, + tuple(inputs[k] for k in input_names), + str(output_path), + input_names=input_names, + output_names=["predicted_depth"], + dynamic_axes={ + name: {0: "batch", 2: "height", 3: "width"} if inputs[name].ndim == 4 + else {0: "batch"} for name in input_names + }, + opset_version=17, + do_constant_folding=True, + ) + print(f"Depth model exported: {output_path} ({output_path.stat().st_size / 1e6:.1f} MB)") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Export models to ONNX") + parser.add_argument("--model", choices=["seg", "depth", "all"], required=True) + args = parser.parse_args() + + if args.model in ("seg", "all"): + export_segmentation() + if args.model in ("depth", "all"): + export_depth() + + print("\nDone! Enable ONNX inference by setting enable_onnx_inference = true in your TOML config.") diff --git a/apps/renderer/services/__init__.py b/apps/renderer/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..68078422fb43cfcc011b9ec1d1dbab14ccb44666 --- /dev/null +++ b/apps/renderer/services/__init__.py @@ -0,0 +1 @@ +# Services package for floor visualizer backend. diff --git a/apps/renderer/services/access/__init__.py b/apps/renderer/services/access/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/apps/renderer/services/access/policy.py b/apps/renderer/services/access/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..103e31dccfff52a5d457a6f07a6a71a1af14d5b6 --- /dev/null +++ b/apps/renderer/services/access/policy.py @@ -0,0 +1,162 @@ +"""Who may call which rendering route, and who owns which job.""" + +from __future__ import annotations + +import enum +import logging +from dataclasses import dataclass + +import jwt +from fastapi import Depends, HTTPException, Request + +from config.auth import ( + AUTH_ENFORCED, + PREVISION_TOKEN_ISSUER, + PROCESSING_TOKEN_AUDIENCE, + PROCESSING_TOKEN_SECRET, + TOKEN_ISSUERS, + TOKEN_LEEWAY_SECONDS, +) + +logger = logging.getLogger(__name__) + +class Role(str, enum.Enum): + ADMIN = "superadmin" + CLIENT = "client" + + +@dataclass(frozen=True) +class Principal: + # The job owner: a user id, or a widget session id ("widget:"). + user_id: str + role: Role + issuer: str = "" + # Optional feature entitlements supplied by the account service. + organization_id: str = "" + features: frozenset[str] = frozenset() + + @property + def is_admin(self) -> bool: + return self.role == Role.ADMIN + + @property + def has_free_tries(self) -> bool: + """Prevision accounts: every accepted job uses one of their free tries.""" + return self.issuer == PREVISION_TOKEN_ISSUER + + +def _unauthorized(detail: str) -> HTTPException: + return HTTPException(status_code=401, detail=detail, headers={"WWW-Authenticate": "Bearer"}) + + +def _bearer_token(request: Request) -> str | None: + header = request.headers.get("authorization", "") + scheme, _, token = header.partition(" ") + if scheme.lower() != "bearer" or not token.strip(): + return None + return token.strip() + + +def decode_processing_token(token: str) -> Principal: + if not PROCESSING_TOKEN_SECRET: + raise _unauthorized("Token verification is not configured on this server.") + try: + claims = jwt.decode( + token, + PROCESSING_TOKEN_SECRET, + algorithms=["HS256"], + audience=PROCESSING_TOKEN_AUDIENCE, + issuer=TOKEN_ISSUERS, + leeway=TOKEN_LEEWAY_SECONDS, + options={"require": ["exp", "iat", "sub", "aud", "iss"]}, + ) + except jwt.ExpiredSignatureError as exc: + raise _unauthorized("Your session expired. Please refresh the page.") from exc + except jwt.PyJWTError as exc: + raise _unauthorized("Invalid access token.") from exc + issuer = str(claims["iss"]) + try: + role = Role(claims.get("role")) + except ValueError: + role = None + if role is None: + raise HTTPException(status_code=403, detail="This account cannot use the visualizer.") + features = claims.get("feat") + return Principal( + user_id=str(claims["sub"]), + role=role, + issuer=issuer, + organization_id=str(claims.get("org") or ""), + features=frozenset(str(name) for name in features) if isinstance(features, list) else frozenset(), + ) + + +def optional_principal(request: Request) -> Principal | None: + """Resolve the caller. With enforcement on, a token is mandatory.""" + token = _bearer_token(request) + if token is None: + if AUTH_ENFORCED: + raise _unauthorized("Please sign in to use the visualizer.") + return None + try: + return decode_processing_token(token) + except HTTPException: + if AUTH_ENFORCED: + raise + # Enforcement off: a stale token must not break today's public flow. + logger.info("Ignoring invalid processing token while enforcement is off") + return None + + +def require_client(principal: Principal | None = Depends(optional_principal)) -> Principal | None: + """Approved client or admin (approval is checked when the token is minted).""" + return principal + + +def require_admin(request: Request) -> Principal: + """Always enforced, even with AUTH_ENFORCEMENT=off: job listings, debug + artifacts and QA runs expose every user's data, unlike a single job id.""" + token = _bearer_token(request) + if token is None: + raise _unauthorized("Administrator sign-in is required.") + principal = decode_processing_token(token) + if not principal.is_admin: + raise HTTPException(status_code=403, detail="Administrator access is required.") + return principal + + +def require_feature(feature: str): + """A route for organizations that have `feature` switched on (and administrators). + + Always enforced, like `require_admin`: these routes spend paid API calls. + """ + + def dependency(request: Request) -> Principal: + token = _bearer_token(request) + if token is None: + raise _unauthorized("Please sign in to use the visualizer.") + principal = decode_processing_token(token) + if not principal.is_admin and feature not in principal.features: + raise HTTPException(status_code=403, detail="This feature is not enabled for your account.") + return principal + + return dependency + + +def ensure_job_access(job: dict, principal: Principal | None) -> None: + """Owner or admin. Jobs created before ownership existed are admin-only. + + Returns 404 (not 403) for other users' jobs so job ids cannot be probed. + """ + if not AUTH_ENFORCED: + return + if principal is None: + raise _unauthorized("Please sign in to use the visualizer.") + if principal.is_admin: + return + if job.get("ownerId") != principal.user_id: + raise HTTPException(status_code=404, detail="Job not found.") + + +def owner_fields(principal: Principal | None) -> dict: + return {"ownerId": principal.user_id} if principal else {} diff --git a/apps/renderer/services/access/usage.py b/apps/renderer/services/access/usage.py new file mode 100644 index 0000000000000000000000000000000000000000..58b66c3507fa1328007a0a16d7eea8f9282d7e24 --- /dev/null +++ b/apps/renderer/services/access/usage.py @@ -0,0 +1,92 @@ +"""Free tries for Prevision accounts, charged when a job is accepted. + +The renderer has no database: the Prevision API (apps/prevision-api, same pod) +keeps the count. A job from a Prevision token is only accepted after that API +records the try (or answers 402 when none are left); a job that then fails on +our side gets its try back. Only authenticated Prevision principals can consume the allowance. + +Calls are authorized with a short HS256 token signed with the shared +PROCESSING_TOKEN_SECRET for the Prevision internal audience. +""" + +from __future__ import annotations + +import json +import logging +import time +import urllib.error +import urllib.request + +import jwt +from fastapi import HTTPException + +from config.auth import PREVISION_API_INTERNAL_URL, PREVISION_INTERNAL_AUDIENCE, PROCESSING_TOKEN_SECRET +from services.access.policy import Principal + +logger = logging.getLogger(__name__) + +TIMEOUT_SECONDS = 5 +REFUND_ATTEMPTS = 3 + + +def _internal_token() -> str: + now = int(time.time()) + return jwt.encode( + {"aud": PREVISION_INTERNAL_AUDIENCE, "iat": now, "exp": now + 60}, + PROCESSING_TOKEN_SECRET, + algorithm="HS256", + ) + + +def _post(path: str, body: dict | None = None) -> tuple[int, dict]: + request = urllib.request.Request( + f"{PREVISION_API_INTERNAL_URL}{path}", + data=json.dumps(body or {}).encode(), + method="POST", + headers={"Authorization": f"Bearer {_internal_token()}", "Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response: + raw = response.read() + return response.status, json.loads(raw) if raw else {} + except urllib.error.HTTPError as error: + try: + return error.code, json.loads(error.read() or b"{}") + except ValueError: + return error.code, {} + + +def charge_free_try(principal: Principal | None, job_id: str) -> str | None: + """Use one free try for this job before it is accepted. Returns the generation id to refund on failure. + + Blocking: call it from a worker thread. + """ + if principal is None or not principal.has_free_tries: + return None + try: + status, body = _post("/internal/generations", {"userId": principal.user_id, "jobId": job_id}) + except (urllib.error.URLError, TimeoutError, OSError) as exc: + logger.error("Could not reach the Prevision API to charge a try: %s", exc) + raise HTTPException(status_code=503, detail="The visualizer is busy. Please try again in a moment.") from exc + if status == 201: + return body["data"]["generationId"] + if status == 402: + raise HTTPException(status_code=402, detail="You've used all your free visualizations.") + logger.error("Prevision API refused to charge a try: HTTP %s %s", status, body) + raise HTTPException(status_code=503, detail="The visualizer is busy. Please try again in a moment.") + + +def refund_free_try(generation_id: str | None) -> None: + """Give the try back after our own failure. Best effort, never raises.""" + if not generation_id: + return + for attempt in range(1, REFUND_ATTEMPTS + 1): + try: + status, _ = _post(f"/internal/generations/{generation_id}/refund") + if status == 204: + return + logger.warning("Refund of generation %s answered HTTP %s", generation_id, status) + except (urllib.error.URLError, TimeoutError, OSError) as exc: + logger.warning("Refund of generation %s failed (attempt %s): %s", generation_id, attempt, exc) + time.sleep(attempt) + logger.error("Gave up refunding generation %s", generation_id) diff --git a/apps/renderer/services/debug/__init__.py b/apps/renderer/services/debug/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..03e17d8c6861974a1d86695ee1159d5fe41227cb --- /dev/null +++ b/apps/renderer/services/debug/__init__.py @@ -0,0 +1 @@ +# Debug services package for pipeline inspection artifacts. diff --git a/apps/renderer/services/debug/capture.py b/apps/renderer/services/debug/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..10c30a4be0074a9d0094c1cf2129947f6140893f --- /dev/null +++ b/apps/renderer/services/debug/capture.py @@ -0,0 +1,107 @@ +"""PipelineDebugCapture – writes versioned inspection manifests for conversion jobs.""" + +import json +import time + +import cv2 +import numpy as np + +from config.paths import JOB_DIR +from config.runtime import DEBUG_ARTIFACTS_ENABLED +from enums import JobStatus + +from services.debug.helpers import ( + _debug_json_default, + _debug_preview_rgb, + _debug_resize_rgb, +) + + +class PipelineDebugCapture: + """Writes a generic, versioned inspection manifest alongside a conversion job.""" + + def __init__(self, job_id: str): + self.job_id = job_id + self.root = JOB_DIR / f"{job_id}.debug" + self.root.mkdir(parents=True, exist_ok=True) + self.manifest_path = self.root / "manifest.json" + self.manifest = { + "schemaVersion": 2, + "jobId": job_id, + "status": JobStatus.PROCESSING, + "stages": [], + } + self._write_manifest() + + def _write_manifest(self): + self.manifest["updatedAtMs"] = int(time.time() * 1000) + self.manifest_path.write_text( + json.dumps(self.manifest, separators=(",", ":"), default=_debug_json_default), + encoding="utf-8", + ) + + def record_images( + self, + stage_id: str, + title: str, + description: str, + images: list[tuple[str, np.ndarray]], + metrics: dict | None = None, + elapsed_ms: float | None = None, + ): + if not DEBUG_ARTIFACTS_ENABLED: + return + try: + artifacts = [] + for index, (label, image_rgb) in enumerate(images): + filename = f"{len(self.manifest['stages']) + 1:02d}-{stage_id}-{index + 1}.jpg" + image_rgb = _debug_resize_rgb(image_rgb) + ok, encoded = cv2.imencode(".jpg", cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR), [cv2.IMWRITE_JPEG_QUALITY, 90]) + if not ok: + continue + (self.root / filename).write_bytes(encoded.tobytes()) + preview_filename = f"{filename[:-4]}.preview.jpg" + preview_rgb = _debug_preview_rgb(image_rgb) + preview_ok, preview_encoded = cv2.imencode( + ".jpg", + cv2.cvtColor(preview_rgb, cv2.COLOR_RGB2BGR), + [cv2.IMWRITE_JPEG_QUALITY, 82], + ) + if preview_ok: + (self.root / preview_filename).write_bytes(preview_encoded.tobytes()) + artifacts.append({ + "type": "image", + "label": label, + "url": f"/viz2d/jobs/{self.job_id}/debug/assets/{filename}", + "previewUrl": ( + f"/viz2d/jobs/{self.job_id}/debug/assets/{preview_filename}" + if preview_ok else None + ), + }) + stage = { + "id": stage_id, + "title": title, + "description": description, + "artifacts": artifacts, + "metrics": metrics or {}, + } + if elapsed_ms is not None: + stage["elapsedMs"] = round(float(elapsed_ms), 1) + self.manifest["stages"].append(stage) + self._write_manifest() + except Exception as exc: + print(f"[DEBUG] Could not capture {stage_id} for job {self.job_id}: {exc}", flush=True) + + def complete(self, total_elapsed_ms: float): + if not DEBUG_ARTIFACTS_ENABLED: + return + self.manifest["status"] = JobStatus.COMPLETED + self.manifest["totalElapsedMs"] = round(float(total_elapsed_ms), 1) + self._write_manifest() + + def fail(self, error: Exception): + if not DEBUG_ARTIFACTS_ENABLED: + return + self.manifest["status"] = JobStatus.FAILED + self.manifest["error"] = str(error) + self._write_manifest() diff --git a/apps/renderer/services/debug/helpers.py b/apps/renderer/services/debug/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..9c18fc1232c7046eaa9f8a3f3d0dafe76526de59 --- /dev/null +++ b/apps/renderer/services/debug/helpers.py @@ -0,0 +1,43 @@ +"""Small helper utilities shared by debug capture and overlay modules.""" + +import numpy as np +import cv2 + +from config.runtime import ( + DEBUG_ARTIFACTS_MAX_DIMENSION, + DEBUG_ARTIFACTS_PREVIEW_DIMENSION, +) + + +def _debug_resize_rgb(image_rgb: np.ndarray) -> np.ndarray: + height, width = image_rgb.shape[:2] + largest = max(height, width) + if largest <= DEBUG_ARTIFACTS_MAX_DIMENSION: + return image_rgb + scale = DEBUG_ARTIFACTS_MAX_DIMENSION / largest + return cv2.resize( + image_rgb, + (max(1, round(width * scale)), max(1, round(height * scale))), + interpolation=cv2.INTER_AREA, + ) + + +def _debug_preview_rgb(image_rgb: np.ndarray) -> np.ndarray: + height, width = image_rgb.shape[:2] + largest = max(height, width) + if largest <= DEBUG_ARTIFACTS_PREVIEW_DIMENSION: + return image_rgb + scale = DEBUG_ARTIFACTS_PREVIEW_DIMENSION / largest + return cv2.resize( + image_rgb, + (max(1, round(width * scale)), max(1, round(height * scale))), + interpolation=cv2.INTER_AREA, + ) + + +def _debug_json_default(value): + if isinstance(value, np.generic): + return value.item() + if isinstance(value, np.ndarray): + return value.tolist() + raise TypeError(f"Unsupported debug manifest value: {type(value).__name__}") diff --git a/apps/renderer/services/debug/overlays.py b/apps/renderer/services/debug/overlays.py new file mode 100644 index 0000000000000000000000000000000000000000..797cc0d9df8c9920318953b0b88e31ac3e307e0b --- /dev/null +++ b/apps/renderer/services/debug/overlays.py @@ -0,0 +1,182 @@ +"""Debug overlay / visualization functions for pipeline stages.""" + +import numpy as np +import cv2 + + +def debug_mask_overlay( + image_rgb: np.ndarray, + mask: np.ndarray, + color: tuple[int, int, int] = (45, 180, 255), +) -> np.ndarray: + """Overlay a binary analysis mask without changing the uploaded image.""" + output = image_rgb.copy() + valid = mask.astype(bool) + if valid.any(): + overlay = np.empty_like(output) + overlay[:] = color + output[valid] = cv2.addWeighted(output, 0.42, overlay, 0.58, 0)[valid] + return output + + +def debug_segmentation_overlay(image_rgb: np.ndarray, seg_map: np.ndarray) -> np.ndarray: + labels = seg_map.astype(np.int32) + hsv = np.zeros((*labels.shape, 3), dtype=np.uint8) + hsv[..., 0] = (labels * 37) % 180 + hsv[..., 1] = 180 + hsv[..., 2] = 255 + colors = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB) + return cv2.addWeighted(image_rgb, 0.42, colors, 0.58, 0) + + +def debug_scalar_map(values: np.ndarray, mask: np.ndarray | None = None) -> np.ndarray: + scalar = values.astype(np.float32) + finite = np.isfinite(scalar) + if mask is not None: + finite &= mask.astype(bool) + valid = scalar[finite] + if valid.size == 0: + return np.zeros((*scalar.shape[:2], 3), dtype=np.uint8) + low, high = np.percentile(valid, [2, 98]) + if high <= low: + high = low + 1.0 + normalized = np.clip((scalar - low) / (high - low), 0.0, 1.0) + normalized[~np.isfinite(normalized)] = 0.0 + output = cv2.applyColorMap(np.round(normalized * 255).astype(np.uint8), cv2.COLORMAP_TURBO) + output = cv2.cvtColor(output, cv2.COLOR_BGR2RGB) + if mask is not None: + output[~mask.astype(bool)] = 0 + return output + + +def debug_plane_overlay(image_rgb: np.ndarray, plane: dict | None) -> np.ndarray: + output = image_rgb.copy() + if not plane: + return output + raw_quad = plane.get("quad") + if not isinstance(raw_quad, list) or len(raw_quad) != 8: + return output + points = np.asarray(raw_quad, dtype=np.float32).reshape(-1, 2) + if not np.isfinite(points).all(): + return output + points_i = np.round(points).astype(np.int32) + overlay = output.copy() + cv2.fillConvexPoly(overlay, points_i, (45, 180, 255)) + output = cv2.addWeighted(output, 0.64, overlay, 0.36, 0) + cv2.polylines(output, [points_i], isClosed=True, color=(255, 255, 255), thickness=3, lineType=cv2.LINE_AA) + return output + + +def debug_surface_overlay(image_rgb: np.ndarray, floor_mask: np.ndarray, surface_mask: np.ndarray) -> np.ndarray: + output = image_rgb.copy() + removed = (floor_mask > 0) & (surface_mask == 0) + if removed.any(): + red = np.empty_like(output) + red[:] = (220, 80, 80) + output[removed] = cv2.addWeighted(output, 0.42, red, 0.58, 0)[removed] + return debug_mask_overlay(output, surface_mask, (45, 180, 255)) + + +def debug_floor_direction_overlay(image_rgb: np.ndarray, floor_direction: dict) -> np.ndarray: + output = image_rgb.copy() + direction_axis = floor_direction.get("directionAxis") + if isinstance(direction_axis, dict): + try: + start = ( + round(float(direction_axis["startX"])), + round(float(direction_axis["startY"])), + ) + end = ( + round(float(direction_axis["endX"])), + round(float(direction_axis["endY"])), + ) + cv2.arrowedLine( + output, + start, + end, + (45, 180, 255), + 4, + cv2.LINE_AA, + tipLength=0.08, + ) + except (KeyError, TypeError, ValueError): + pass + + geometry_axis = floor_direction.get("geometryAxis") + if isinstance(geometry_axis, dict): + try: + start = ( + round(float(geometry_axis["nearX"])), + round(float(geometry_axis["nearY"])), + ) + end = ( + round(float(geometry_axis["farX"])), + round(float(geometry_axis["farY"])), + ) + cv2.arrowedLine( + output, + start, + end, + (45, 180, 255), + 4, + cv2.LINE_AA, + tipLength=0.08, + ) + except (KeyError, TypeError, ValueError): + pass + + for line in floor_direction.get("dominantLines") or []: + try: + start = (round(float(line["x1"])), round(float(line["y1"]))) + end = (round(float(line["x2"])), round(float(line["y2"]))) + except (KeyError, TypeError, ValueError): + continue + cv2.line(output, start, end, (45, 180, 255), 3, cv2.LINE_AA) + + label = floor_direction.get("directionLabel") or "unknown" + angle = floor_direction.get("renderAngleDegrees") + confidence = floor_direction.get("confidence") + detail = f"{label}" + if isinstance(angle, (int, float)): + detail += f" {angle:.1f} deg" + if isinstance(confidence, (int, float)): + detail += f" {confidence:.0%}" + cv2.putText(output, detail, (16, 34), cv2.FONT_HERSHEY_SIMPLEX, 0.72, (255, 255, 255), 3, cv2.LINE_AA) + cv2.putText(output, detail, (16, 34), cv2.FONT_HERSHEY_SIMPLEX, 0.72, (25, 25, 25), 1, cv2.LINE_AA) + return output + + +def debug_uv_checkerboard( + height: int, + width: int, + surface_indices: np.ndarray, + uv: np.ndarray, +) -> np.ndarray: + output = np.zeros((height, width, 3), dtype=np.uint8) + valid = np.isfinite(uv).all(axis=1) + if not valid.any(): + return output + coords = uv[valid] + cells = (np.floor(coords[:, 0] * 8) + np.floor(coords[:, 1] * 8)).astype(np.int32) + colors = np.where((cells % 2)[:, None] == 0, np.array([45, 180, 255]), np.array([45, 80, 180])) + output.reshape(-1, 3)[surface_indices[valid]] = colors.astype(np.uint8) + return output + + +def debug_plane_id_map( + height: int, + width: int, + surface_indices: np.ndarray, + plane_ids: np.ndarray, +) -> np.ndarray: + output = np.zeros((height, width, 3), dtype=np.uint8) + valid = plane_ids >= 0 + if not valid.any(): + return output + ids = plane_ids[valid].astype(np.int32) + hsv = np.zeros((len(ids), 1, 3), dtype=np.uint8) + hsv[:, 0, 0] = (ids * 47) % 180 + hsv[:, 0, 1] = 190 + hsv[:, 0, 2] = 255 + output.reshape(-1, 3)[surface_indices[valid]] = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB).reshape(-1, 3) + return output diff --git a/apps/renderer/services/direction/__init__.py b/apps/renderer/services/direction/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b1d65e66a3f141494853fc64932a6372abdccd4f --- /dev/null +++ b/apps/renderer/services/direction/__init__.py @@ -0,0 +1 @@ +# Floor direction analysis and response formatting services. diff --git a/apps/renderer/services/direction/analysis.py b/apps/renderer/services/direction/analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..cdf17bd6dc1a85289d5bc4ffcd37ffdeddd358d8 --- /dev/null +++ b/apps/renderer/services/direction/analysis.py @@ -0,0 +1,84 @@ +"""Floor direction geometry helpers.""" + +import numpy as np + +from services.geometry.camera import default_camera_intrinsics +from services.geometry.multi_plane import geometry_point_maps + + +def floor_direction_geometry_inputs( + surface_mask: np.ndarray, + geometry: dict | None, + plane: dict | None, + surface_mapping: dict | None, + *, + use_surface_uv: bool, + geometry_maps: dict | None = None, +) -> dict: + direction_maps = surface_mapping + if direction_maps is None: + raw_maps = geometry_maps if geometry_maps is not None else geometry_point_maps(surface_mask, geometry) + if raw_maps is not None: + direction_maps = { + "normalMap": raw_maps["normals"], + "validMask": raw_maps["validMask"], + "intrinsics": raw_maps["intrinsics"], + "planes": [], + } + + normal_map = direction_maps.get("normalMap") if direction_maps else None + valid_mask = direction_maps.get("validMask") if direction_maps else None + intrinsics = direction_maps.get("intrinsics") if direction_maps else None + surface_planes = direction_maps.get("planes") or [] if direction_maps else [] + dominant_floor_plane = None + if surface_planes: + floor_planes = [item for item in surface_planes if item.get("isFloor")] + candidates = floor_planes or surface_planes + dominant_floor_plane = max( + candidates, + key=lambda item: int(item.get("assignedCount") or item.get("inlierCount") or 0), + ) + + floor_normal = None + render_u_axis = None + render_v_axis = None + if use_surface_uv and dominant_floor_plane is not None: + floor_normal = dominant_floor_plane.get("normal") + render_u_axis = dominant_floor_plane.get("uAxis") + render_v_axis = dominant_floor_plane.get("vAxis") + elif plane and plane.get("planeNormal"): + floor_normal = plane.get("planeNormal") + elif dominant_floor_plane is not None: + floor_normal = dominant_floor_plane.get("normal") + + if floor_normal is None and normal_map is not None and normal_map.shape[:2] == surface_mask.shape: + lengths = np.linalg.norm(normal_map, axis=2) + valid_floor = ( + (surface_mask > 0) + & np.isfinite(normal_map).all(axis=2) + & (lengths > 1e-4) + ) + if valid_mask is not None and valid_mask.shape == surface_mask.shape: + valid_floor &= valid_mask.astype(bool) + floor_normals = normal_map[valid_floor] + if len(floor_normals) >= 200: + floor_normals = floor_normals / np.linalg.norm(floor_normals, axis=1, keepdims=True) + reference = np.median(floor_normals, axis=0) + if reference[1] < 0: + reference = -reference + floor_normal = reference.tolist() + + if intrinsics is None and plane and plane.get("cameraIntrinsics"): + intrinsics = np.asarray(plane["cameraIntrinsics"], dtype=np.float32).reshape(3, 3) + if intrinsics is None: + height, width = surface_mask.shape[:2] + intrinsics = default_camera_intrinsics(width, height) + + return { + "normalsMap": normal_map, + "validMask": valid_mask, + "intrinsics": intrinsics, + "floorNormal": floor_normal, + "renderUAxis": render_u_axis, + "renderVAxis": render_v_axis, + } diff --git a/apps/renderer/services/direction/response.py b/apps/renderer/services/direction/response.py new file mode 100644 index 0000000000000000000000000000000000000000..de789399bcba157d66910c718b9ff7a98577af7a --- /dev/null +++ b/apps/renderer/services/direction/response.py @@ -0,0 +1,87 @@ +"""Floor direction response formatting: API payloads and metadata dicts.""" + +import base64 + +import cv2 +import numpy as np + +from errors import server_error + + +def encode_png_data_url(image_bgr: np.ndarray) -> str: + ok, encoded = cv2.imencode(".png", image_bgr) + if not ok: + server_error("Could not encode overlay image.") + payload = base64.b64encode(encoded.tobytes()).decode("ascii") + return f"data:image/png;base64,{payload}" + + +def floor_direction_response(result, segmentation) -> dict: + overlay_image_base64 = None + if result.overlay_bgr is not None: + overlay_image_base64 = encode_png_data_url(result.overlay_bgr) + + return { + "angle_degrees": result.angle_degrees, + "render_angle_degrees": result.render_angle_degrees, + "secondary_angle_degrees": result.secondary_angle_degrees, + "direction_label": result.direction_label, + "confidence": result.confidence, + "segmentation": { + "label": segmentation.label, + "confidence": segmentation.confidence, + "polygon_count": len(segmentation.polygons), + "floor_area_ratio": result.floor_area_ratio, + "source_path": segmentation.source_path, + "raw_keys": segmentation.raw_keys or [], + }, + "line_count": result.line_count, + "dominant_line_count": result.dominant_line_count, + "grid_pattern_detected": result.grid_pattern_detected, + "dominant_lines": [ + { + "x1": line.x1, + "y1": line.y1, + "x2": line.x2, + "y2": line.y2, + "angle_degrees": line.angle_degrees, + "length": line.length, + } + for line in result.dominant_lines + ], + "warnings": result.warnings, + "overlay_image_base64": overlay_image_base64, + } + + +def floor_direction_metadata(result, segmentation) -> dict: + return { + "source": "backend-floor-direction", + "angleDegrees": result.angle_degrees, + "renderAngleDegrees": result.render_angle_degrees, + "secondaryAngleDegrees": result.secondary_angle_degrees, + "directionLabel": result.direction_label, + "confidence": result.confidence, + "floorAreaRatio": result.floor_area_ratio, + "lineCount": result.line_count, + "dominantLineCount": result.dominant_line_count, + "gridPatternDetected": result.grid_pattern_detected, + "warnings": result.warnings, + "dominantLines": [ + { + "x1": line.x1, + "y1": line.y1, + "x2": line.x2, + "y2": line.y2, + "angleDegrees": line.angle_degrees, + "length": line.length, + } + for line in result.dominant_lines + ], + "segmentation": { + "label": segmentation.label, + "confidence": segmentation.confidence, + "polygonCount": len(segmentation.polygons), + "sourcePath": segmentation.source_path, + }, + } diff --git a/apps/renderer/services/floor/__init__.py b/apps/renderer/services/floor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4cd810640331a4c6735384902c8070115b57e726 --- /dev/null +++ b/apps/renderer/services/floor/__init__.py @@ -0,0 +1 @@ +# Floor surface detection, masking, and geometry services. diff --git a/apps/renderer/services/floor/detection.py b/apps/renderer/services/floor/detection.py new file mode 100644 index 0000000000000000000000000000000000000000..c641dfcf18e0d4e20b133ae3f10bb0c4b585cb72 --- /dev/null +++ b/apps/renderer/services/floor/detection.py @@ -0,0 +1,201 @@ +"""Floor plane detection via edge fitting, vanishing point estimation, and homography. + +Functions +--------- +fit_floor_edges - fit linear left/right floor boundary edges +detect_vanishing_point - estimate a perspective vanishing point from floor edges +estimate_floor_plane - compute a full floor plane (homography + optional metric geometry) +""" + +import cv2 +import numpy as np + +from enums import GeometryProvider +from config.runtime import ENABLE_PLANE_FIT +from services.geometry.plane_fitting import ( + estimate_metric_floor_transform, + fit_metric_floor_transform, +) + + +def fit_floor_edges(mask: np.ndarray): + h, w = mask.shape[:2] + row_ys, lefts, rights = [], [], [] + step = max(1, h // 260) + for y in range(0, h, step): + row_xs = np.where(mask[y] > 0)[0] + if len(row_xs) < max(8, w * 0.01): + continue + row_ys.append(float(y)) + lefts.append(float(np.percentile(row_xs, 3))) + rights.append(float(np.percentile(row_xs, 97))) + if len(row_ys) < 8: + return None + row_ys_np = np.asarray(row_ys, dtype=np.float32) + return np.polyfit(row_ys_np, np.asarray(lefts, dtype=np.float32), 1), np.polyfit( + row_ys_np, + np.asarray(rights, dtype=np.float32), + 1, + ) + + +def detect_vanishing_point(img_np: np.ndarray, floor_mask: np.ndarray): + gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY) + gray = cv2.GaussianBlur(gray, (5, 5), 0) + edges = cv2.Canny(gray, 60, 160) + edges[floor_mask == 0] = 0 + lines = cv2.HoughLinesP( + edges, + rho=1, + theta=np.pi / 180, + threshold=60, + minLineLength=max(40, min(img_np.shape[:2]) // 16), + maxLineGap=24, + ) + if lines is None: + return None + + h, w = img_np.shape[:2] + candidates = [] + for line in lines.reshape(-1, 4): + x1, y1, x2, y2 = [float(v) for v in line] + dx, dy = x2 - x1, y2 - y1 + length = float(np.hypot(dx, dy)) + if length < 40 or abs(dx) < 1: + continue + slope = dy / dx + if abs(slope) >= 0.18: + candidates.append((x1, y1, x2, y2, slope, length)) + + intersections = [] + for i, (x1, y1, _, _, s1, l1) in enumerate(candidates): + a1 = y1 - s1 * x1 + for x3, y3, _, _, s2, l2 in candidates[i + 1:]: + if s1 * s2 > 0 or abs(s1 - s2) < 0.12: + continue + a2 = y3 - s2 * x3 + x = (a2 - a1) / (s1 - s2) + y = s1 * x + a1 + if -w * 0.5 <= x <= w * 1.5 and -h <= y <= h * 0.95: + intersections.append((x, y, min(l1, l2))) + if not intersections: + return None + + pts = np.asarray([[p[0], p[1]] for p in intersections], dtype=np.float32) + weights = np.asarray([p[2] for p in intersections], dtype=np.float32) + center = np.average(pts, axis=0, weights=weights) + dist = np.linalg.norm(pts - center, axis=1) + keep = dist <= np.percentile(dist, 70) + if keep.sum() >= 3: + center = np.average(pts[keep], axis=0, weights=weights[keep]) + return {"x": float(center[0]), "y": float(center[1])} + + +def estimate_floor_plane(mask: np.ndarray, img_np: np.ndarray, geometry: dict | None = None): + ys, xs = np.where(mask > 0) + if len(xs) < 1000: + return None, None + + xs_f, ys_f = xs.astype(np.float32), ys.astype(np.float32) + x1, x2 = float(np.percentile(xs_f, 1)), float(np.percentile(xs_f, 99)) + y1, y2 = float(np.percentile(ys_f, 1)), float(np.percentile(ys_f, 99)) + width, height = x2 - x1, y2 - y1 + if width < 20 or height < 20: + return None, None + + top_y = float(np.percentile(ys_f, 8)) + bottom_y = float(np.percentile(ys_f, 97)) + edge_fits = fit_floor_edges(mask) + if edge_fits is None: + return None, None + left_fit, right_fit = edge_fits + + top_left = float(np.polyval(left_fit, top_y)) + top_right = float(np.polyval(right_fit, top_y)) + bottom_left = float(np.polyval(left_fit, bottom_y)) + bottom_right = float(np.polyval(right_fit, bottom_y)) + lower_xs = xs_f[ys_f >= np.percentile(ys_f, 80)] + bottom_left = min(bottom_left, float(np.percentile(lower_xs, 4))) + bottom_right = max(bottom_right, float(np.percentile(lower_xs, 96))) + + min_top_width = max(24.0, width * 0.18) + top_center = (top_left + top_right) * 0.5 + if top_right - top_left < min_top_width: + top_left = top_center - min_top_width * 0.5 + top_right = top_center + min_top_width * 0.5 + + min_bottom_width = max(min_top_width * 1.25, width * 0.45) + bottom_center = (bottom_left + bottom_right) * 0.5 + if bottom_right - bottom_left < min_bottom_width: + bottom_left = bottom_center - min_bottom_width * 0.5 + bottom_right = bottom_center + min_bottom_width * 0.5 + + h, w = mask.shape[:2] + src = np.float32([ + [np.clip(bottom_left, 0, w - 1), np.clip(bottom_y, 0, h - 1)], + [np.clip(bottom_right, 0, w - 1), np.clip(bottom_y, 0, h - 1)], + [np.clip(top_right, 0, w - 1), np.clip(top_y, 0, h - 1)], + [np.clip(top_left, 0, w - 1), np.clip(top_y, 0, h - 1)], + ]) + + vanishing_point = detect_vanishing_point(img_np, mask) + if vanishing_point is not None and vanishing_point["y"] < bottom_y: + vp_x = float(np.clip(vanishing_point["x"], -w * 0.25, w * 1.25)) + top_width = max(src[2][0] - src[3][0], width * 0.16) + horizon_gap = max(bottom_y - top_y, 1.0) + convergence = np.clip((top_y - vanishing_point["y"]) / horizon_gap, 0.12, 0.75) + top_center = top_center * (1 - convergence * 0.35) + vp_x * (convergence * 0.35) + src[3][0] = np.clip(top_center - top_width * 0.5, 0, w - 1) + src[2][0] = np.clip(top_center + top_width * 0.5, 0, w - 1) + + if cv2.contourArea(src) < 100: + return None, None + dst = np.float32([[x1, y2], [x2, y2], [x2, y1], [x1, y1]]) + homography = cv2.getPerspectiveTransform(src, dst).flatten().tolist() + metric_geometry = None + if ENABLE_PLANE_FIT and geometry and geometry.get("points") is not None: + metric_geometry = fit_metric_floor_transform( + mask, + geometry["points"], + geometry.get("validMask"), + geometry.get("normals"), + geometry.get("intrinsics"), + geometry.get("provider", GeometryProvider.MOGE_2), + ) + if ENABLE_PLANE_FIT and metric_geometry is None and geometry: + depth_provider = geometry.get("provider", GeometryProvider.DEPTH_ANYTHING) + if depth_provider == GeometryProvider.MOGE_2: + depth_provider = "moge-2-depth" + metric_geometry = estimate_metric_floor_transform( + mask, + geometry.get("depth"), + depth_provider, + geometry.get("intrinsics"), + ) + plane = { + "x": x1, + "y": y1, + "width": width, + "height": height, + "quad": src.flatten().tolist(), + "vanishingPoint": vanishing_point, + } + if metric_geometry: + plane.update(metric_geometry) + plane["camera"]["horizonY"] = ( + float(vanishing_point["y"]) if vanishing_point is not None else top_y + ) + else: + plane.update({ + "floorTransform": None, + "metersPerUnit": None, + "geometryConfidence": 0.25 if vanishing_point is not None else 0.1, + "geometryProvider": GeometryProvider.HOMOGRAPHY, + "cameraIntrinsics": None, + "camera": { + "focalLength": float(max(h, w) * 0.95), + "horizonY": float(vanishing_point["y"]) if vanishing_point is not None else top_y, + "confidence": 0.25 if vanishing_point is not None else 0.1, + }, + }) + return homography, plane diff --git a/apps/renderer/services/floor/edge_coverage.py b/apps/renderer/services/floor/edge_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..56c69204ec70f74f830b8713d3a8f55acabbcbdd --- /dev/null +++ b/apps/renderer/services/floor/edge_coverage.py @@ -0,0 +1,126 @@ +"""Surface edge coverage improvement and soft floor covering expansion. + +Functions +--------- +scaled_odd_kernel_size - compute an odd-sized kernel from image dimensions +improve_surface_edge_coverage - close gaps and dilate surface edges +expand_surface_over_soft_floor_coverings - grow surface into adjacent soft coverings +""" + +import cv2 +import numpy as np + +from config.surface import ( + ENABLE_SOFT_FLOOR_COVERING_EXPANSION, + SOFT_FLOOR_COVERING_DILATION_ITERATIONS, + SOFT_FLOOR_COVERING_KERNEL_RATIO, + SURFACE_EDGE_CLOSE_RATIO, + SURFACE_EDGE_DILATION_ITERATIONS, + SURFACE_EDGE_KERNEL_RATIO, +) + + +def scaled_odd_kernel_size( + height: int, + width: int, + ratio: float, + minimum: int = 3, + maximum: int = 31, +) -> int: + min_side = max(3, min(height, width)) + size = max(minimum, int(round(min_side * ratio))) + size = min(maximum, size) + return size | 1 + + +def improve_surface_edge_coverage( + surface: np.ndarray, + protected_mask: np.ndarray, +) -> tuple[np.ndarray, dict]: + h, w = surface.shape[:2] + before = int(surface.sum()) + repaired = surface.astype(np.uint8).copy() + protected = protected_mask.astype(bool) + + close_size = scaled_odd_kernel_size(h, w, SURFACE_EDGE_CLOSE_RATIO, minimum=3) + edge_size = scaled_odd_kernel_size(h, w, SURFACE_EDGE_KERNEL_RATIO, minimum=3) + + if close_size > 1: + close_kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (close_size, close_size)) + repaired = cv2.morphologyEx(repaired, cv2.MORPH_CLOSE, close_kern) + + if SURFACE_EDGE_DILATION_ITERATIONS > 0: + edge_kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (edge_size, edge_size)) + repaired = cv2.dilate(repaired, edge_kern, iterations=SURFACE_EDGE_DILATION_ITERATIONS) + + repaired[protected] = 0 + repaired = (repaired > 0).astype(np.uint8) + after = int(repaired.sum()) + + return repaired, { + "surfacePixelsBeforeEdgeFix": before, + "surfacePixelsAfterEdgeFix": after, + "surfaceEdgeCloseKernel": close_size, + "surfaceEdgeKernel": edge_size, + "surfaceEdgeDilationIterations": SURFACE_EDGE_DILATION_ITERATIONS, + } + + +def expand_surface_over_soft_floor_coverings( + surface: np.ndarray, + soft_covering_mask: np.ndarray, + protected_mask: np.ndarray, +) -> tuple[np.ndarray, dict]: + h, w = surface.shape[:2] + before = int(surface.sum()) + soft_pixels = int(soft_covering_mask.sum()) + metadata = { + "softFloorCoveringExpansionEnabled": ENABLE_SOFT_FLOOR_COVERING_EXPANSION, + "softFloorCoveringExpansionApplied": False, + "softFloorCoveringExpansionReason": ( + "disabled" if not ENABLE_SOFT_FLOOR_COVERING_EXPANSION else "unavailable" + ), + "softFloorCoveringPixels": soft_pixels, + "softFloorCoveringPixelsBefore": before, + "softFloorCoveringPixelsAfter": before, + "softFloorCoveringKernel": 0, + "softFloorCoveringDilationIterations": SOFT_FLOOR_COVERING_DILATION_ITERATIONS, + } + if not ENABLE_SOFT_FLOOR_COVERING_EXPANSION: + return surface, metadata + if before == 0: + metadata["softFloorCoveringExpansionReason"] = "empty-surface" + return surface, metadata + if soft_pixels == 0: + metadata["softFloorCoveringExpansionReason"] = "no-soft-floor-covering" + return surface, metadata + if SOFT_FLOOR_COVERING_DILATION_ITERATIONS <= 0: + metadata["softFloorCoveringExpansionReason"] = "zero-dilation" + return surface, metadata + + kernel_size = scaled_odd_kernel_size( + h, + w, + SOFT_FLOOR_COVERING_KERNEL_RATIO, + minimum=3, + ) + metadata["softFloorCoveringKernel"] = kernel_size + kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size, kernel_size)) + surface_reach = cv2.dilate( + surface.astype(np.uint8), + kernel, + iterations=SOFT_FLOOR_COVERING_DILATION_ITERATIONS, + ) + protected = protected_mask.astype(bool) + candidates = (surface_reach > 0) & (soft_covering_mask > 0) & (~protected) + expanded = surface.astype(np.uint8).copy() + expanded[candidates] = 1 + expanded[protected] = 0 + expanded = (expanded > 0).astype(np.uint8) + after = int(expanded.sum()) + metadata["softFloorCoveringPixelsAfter"] = after + metadata["softFloorCoveringExpansionApplied"] = after > before + metadata["softFloorCoveringExpansionReason"] = ( + "expanded-near-soft-floor-covering" if after > before else "no-adjacent-candidates" + ) + return expanded, metadata diff --git a/apps/renderer/services/floor/edge_refinement.py b/apps/renderer/services/floor/edge_refinement.py new file mode 100644 index 0000000000000000000000000000000000000000..b36a3e45564fc22336043db15694048b18c763a3 --- /dev/null +++ b/apps/renderer/services/floor/edge_refinement.py @@ -0,0 +1,344 @@ +"""Floor edge refinement: snap the mask edge to the photo and straighten it along walls. + +The floor mask is built from segmentation labels at roughly 1/8 of the photo's +resolution, so its edge wobbles 10-20 px around the real baseboard or furniture +foot. Two steps fix that: + +1. A colour guided filter (He et al., "Guided Image Filtering") with the photo as + guide moves the edge onto the photo's own edges. Its 0.5 level set, sharpened + by the local gradient, gives a sub-pixel, anti-aliased alpha. +2. Where the floor meets a wall, door or column, the edge is redrawn as straight + lines (the same line fitting walls use) and rasterised with anti-aliasing. + +Functions +--------- +guided_filter - fast colour guided filter (cv2.boxFilter + numpy) +refine_surface_edges - refined binary mask and per-pixel alpha for the floor +""" + +from __future__ import annotations + +import time + +import cv2 +import numpy as np + +from config.surface import ( + ENABLE_SURFACE_EDGE_REFINEMENT, + SURFACE_EDGE_REFINE_EPS, + SURFACE_EDGE_REFINE_RADIUS_RATIO, + SURFACE_EDGE_STRAIGHTEN_MIN_RUN_RATIO, + SURFACE_EDGE_STRAIGHTEN_RATIO, +) +from services.image.polygons import _contour_depths, _straight_polygon, straighten_polyline +from state import class_ids +from utils import seg_class_mask + +# Pixels covered by less than ~10% stay out of the mask (and so get no UVs). +ALPHA_FLOOR = 26 +# The floor's edge against these is an architectural straight line. +ARCHITECTURAL_CLASSES = {"wall", "door", "column"} +# Width in px of the anti-aliased transition from tile to photo. +EDGE_TRANSITION_PX = 1.0 +# Refinement that changes the floor area more than this is distrusted. +MAX_AREA_CHANGE = 0.15 +# Holes the filter punches into confident floor (textured carpet whose light +# specks look like the wall next to it) up to this size, as a fraction of the +# short image side squared, are filled. +SPECK_MAX_AREA_RATIO = 0.02 +# Sub-pixel precision for polygon fills (cv2 `shift` bits). +_FILL_SHIFT = 4 +# Straightened edges are rasterised at this many samples per pixel side. +_SUPERSAMPLE = 4 + + +def guided_filter(guide: np.ndarray, source: np.ndarray, radius: int, eps: float, subsample: int = 2) -> np.ndarray: + """Edge-preserving smoothing of `source` that follows the edges of the RGB `guide`. + + `guide` is HxWx3 float32 in [0, 1], `source` HxW float32. The linear + coefficients are computed at 1/`subsample` resolution and upsampled + ("fast guided filter"), which keeps it to a few tens of ms per megapixel. + """ + h, w = source.shape[:2] + scale = max(1, int(subsample)) if radius >= 4 else 1 + if scale > 1: + size = (max(1, w // scale), max(1, h // scale)) + guide_small = cv2.resize(guide, size, interpolation=cv2.INTER_AREA) + source_small = cv2.resize(source, size, interpolation=cv2.INTER_AREA) + else: + guide_small, source_small = guide, source + r = max(1, int(round(radius / scale))) + + def box(values: np.ndarray) -> np.ndarray: + return cv2.boxFilter(values, -1, (2 * r + 1, 2 * r + 1), borderType=cv2.BORDER_REFLECT) + + mean_i = box(guide_small) + mean_p = box(source_small) + cov_ip = box(guide_small * source_small[..., None]) - mean_i * mean_p[..., None] + + def var(i: int, j: int) -> np.ndarray: + return box(guide_small[..., i] * guide_small[..., j]) - mean_i[..., i] * mean_i[..., j] + + rr, rg, rb = var(0, 0) + eps, var(0, 1), var(0, 2) + gg, gb, bb = var(1, 1) + eps, var(1, 2), var(2, 2) + eps + # Inverse of the symmetric 3x3 covariance (adjugate / determinant), per pixel. + inv_rr = gg * bb - gb * gb + inv_rg = rb * gb - rg * bb + inv_rb = rg * gb - rb * gg + inv_gg = rr * bb - rb * rb + inv_gb = rg * rb - rr * gb + inv_bb = rr * gg - rg * rg + det = rr * inv_rr + rg * inv_rg + rb * inv_rb + c0, c1, c2 = cov_ip[..., 0], cov_ip[..., 1], cov_ip[..., 2] + a = np.stack(( + inv_rr * c0 + inv_rg * c1 + inv_rb * c2, + inv_rg * c0 + inv_gg * c1 + inv_gb * c2, + inv_rb * c0 + inv_gb * c1 + inv_bb * c2, + ), axis=-1) / det[..., None] + b = mean_p - (a * mean_i).sum(axis=-1) + + mean_a, mean_b = box(a), box(b) + if scale > 1: + mean_a = cv2.resize(mean_a, (w, h), interpolation=cv2.INTER_LINEAR) + mean_b = cv2.resize(mean_b, (w, h), interpolation=cv2.INTER_LINEAR) + return (mean_a * guide).sum(axis=-1) + mean_b + + +def refine_surface_edges( + img_np: np.ndarray, + surface_mask: np.ndarray, + seg_map: np.ndarray, +) -> tuple[np.ndarray, np.ndarray, dict]: + """Return (mask, alpha, metadata) for the floor surface. + + `alpha` is uint8 at full resolution (255 = fully tile); `mask` is every pixel + with visible coverage, so the renderer has UVs and lighting for the whole + anti-aliased edge. Disabled or distrusted refinement returns the input mask + with a hard alpha, which is the previous behaviour. + """ + started = time.perf_counter() + surface = (surface_mask > 0).astype(np.uint8) + before = int(surface.sum()) + metadata = { + "edgeRefinementEnabled": ENABLE_SURFACE_EDGE_REFINEMENT, + "edgeRefinementApplied": False, + "edgeRefinementReason": "disabled" if not ENABLE_SURFACE_EDGE_REFINEMENT else "empty-surface", + "edgeRefinementPixelsBefore": before, + "edgeRefinementPixelsAfter": before, + } + if not ENABLE_SURFACE_EDGE_REFINEMENT or before == 0: + return surface, surface * np.uint8(255), metadata + + h, w = surface.shape[:2] + short_side = min(h, w) + radius = max(2, int(round(short_side * SURFACE_EDGE_REFINE_RADIUS_RATIO))) + guide = img_np.astype(np.float32) / 255.0 + snapped = guided_filter(guide, surface.astype(np.float32), radius, SURFACE_EDGE_REFINE_EPS) + alpha = _crisp_alpha(snapped) + guided_ms = (time.perf_counter() - started) * 1000 + + straighten_started = time.perf_counter() + straight_stats = {"edgeStraightenedRuns": 0, "edgeStraightenedPixels": 0} + tolerance = SURFACE_EDGE_STRAIGHTEN_RATIO * short_side + if tolerance > 0: + architectural = seg_class_mask(seg_map, class_ids(ARCHITECTURAL_CLASSES)) + reach = 2 * (radius + int(np.ceil(tolerance))) + 1 + architectural_near = cv2.dilate( + architectural, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (reach, reach)), + ) + binary = (alpha >= 0.5).astype(np.uint8) + # Along walls, notches the filter cut into the edge (texture near a light + # wall) are closed first, so the fitted lines run past them. + notch = (2 * int(np.ceil(tolerance)) + 1) | 1 + closed = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (notch, notch))) + binary = np.where(architectural_near > 0, closed, binary).astype(np.uint8) + straightened = _straighten_along( + binary, + architectural_near, + tolerance, + min_run=max(8, int(round(short_side * SURFACE_EDGE_STRAIGHTEN_MIN_RUN_RATIO))), + ) + if straightened is not None: + coverage, band, straight_stats = straightened + alpha = np.where(band > 0, coverage.astype(np.float32) / 255.0, alpha) + straighten_ms = (time.perf_counter() - straighten_started) * 1000 + + alpha_u8 = np.clip(np.rint(alpha * 255.0), 0, 255).astype(np.uint8) + alpha_u8, filled_specks = _fill_specks(alpha_u8, surface, int((SPECK_MAX_AREA_RATIO * short_side) ** 2)) + refined = _keep_connected_to(alpha_u8 >= ALPHA_FLOOR, surface) + alpha_u8[refined == 0] = 0 + after = int(refined.sum()) + metadata.update({ + "edgeRefinementPixelsAfter": after, + "edgeRefinementRadius": radius, + "edgeRefinementEps": SURFACE_EDGE_REFINE_EPS, + "edgeStraightenTolerance": round(tolerance, 2), + "edgeFilledSpecks": filled_specks, + **straight_stats, + "edgeRefinementTimingMs": { + "guidedFilter": round(guided_ms, 2), + "straighten": round(straighten_ms, 2), + "total": round((time.perf_counter() - started) * 1000, 2), + }, + }) + if abs(after - before) > MAX_AREA_CHANGE * before: + metadata["edgeRefinementReason"] = "area-change-too-large" + metadata["edgeRefinementPixelsAfter"] = before + return surface, surface * np.uint8(255), metadata + + metadata["edgeRefinementApplied"] = True + metadata["edgeRefinementReason"] = "refined" + print( + "[EDGE_REFINEMENT] " + f"pixels {before}->{after} radius={radius} runs={straight_stats['edgeStraightenedRuns']} " + f"guided={guided_ms:.1f}ms straighten={straighten_ms:.1f}ms", + flush=True, + ) + return refined, alpha_u8, metadata + + +def _crisp_alpha(snapped: np.ndarray) -> np.ndarray: + """Anti-aliased coverage of the guided filter's 0.5 level set. + + Dividing by the local gradient turns the filter value into a signed distance + (in px) from that level set, so the edge is ~1 px wide wherever the photo's + edge was weak and the filter output is only a gentle ramp. + """ + grad_x = cv2.Sobel(snapped, cv2.CV_32F, 1, 0, ksize=1) * 0.5 + grad_y = cv2.Sobel(snapped, cv2.CV_32F, 0, 1, ksize=1) * 0.5 + gradient = np.maximum(np.sqrt(grad_x * grad_x + grad_y * grad_y), 1e-3) + distance = (snapped - 0.5) / gradient + return np.clip(0.5 + distance / EDGE_TRANSITION_PX, 0.0, 1.0).astype(np.float32) + + +def _straighten_along( + binary: np.ndarray, + architectural_near: np.ndarray, + tolerance: float, + min_run: int, +): + """Redraw the edge runs that lie along walls as straight lines. + + Returns (coverage, band, stats): anti-aliased coverage of the redrawn mask + (uint8), the band around the redrawn runs where it replaces the guided alpha, + and run statistics; or None when no run qualified. + """ + h, w = binary.shape[:2] + contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) + if hierarchy is None: + return None + depths = _contour_depths(hierarchy[0][:, 3]) + band = np.zeros((h, w), np.uint8) + band_width = max(3, int(np.ceil(2 * tolerance)) + 3) + scale = float(1 << _FILL_SHIFT) + runs = 0 + run_pixels = 0 + polygons: list[tuple[int, np.ndarray]] = [] + + for index in np.argsort(depths, kind="stable"): + points = contours[index].reshape(-1, 2) + if len(points) < 3: + continue + along = architectural_near[points[:, 1], points[:, 0]] > 0 + # The photo's border is already straight; leave it exactly in place. + along &= ~((points[:, 0] == 0) | (points[:, 1] == 0) | (points[:, 0] == w - 1) | (points[:, 1] == h - 1)) + if along.all() and len(points) >= min_run: + polygon = _straight_polygon(points, tolerance) + pieces = [(True, polygon)] + runs += 1 + run_pixels += len(points) + elif along.all() or not along.any(): + pieces = [(False, points.astype(np.float32))] + else: + # Start at an off-wall point so no run wraps around the array end. + start = int(np.flatnonzero(~along)[0]) + points, along = np.roll(points, -start, axis=0), np.roll(along, -start) + boundaries = np.flatnonzero(np.diff(along.astype(np.int8))) + 1 + pieces = [] + for run in np.split(np.arange(len(points)), boundaries): + run_points = points[run] + if along[run[0]] and len(run) >= min_run: + pieces.append((True, straighten_polyline(run_points, tolerance))) + runs += 1 + run_pixels += len(run) + else: + pieces.append((False, run_points.astype(np.float32))) + for straight, piece in pieces: + if straight and len(piece) >= 2: + closed = len(pieces) == 1 + cv2.polylines(band, [np.round(piece * scale).astype(np.int32)], closed, 1, + thickness=band_width, lineType=cv2.LINE_8, shift=_FILL_SHIFT) + polygons.append((int(depths[index]), np.concatenate([piece for _, piece in pieces]))) + + if runs == 0: + return None + return _polygon_coverage(polygons, band), band, {"edgeStraightenedRuns": runs, "edgeStraightenedPixels": run_pixels} + + +def _polygon_coverage(polygons: list[tuple[int, np.ndarray]], band: np.ndarray) -> np.ndarray: + """Exact pixel coverage of the redrawn mask inside the band's bounding box. + + The contours run through the centres of the outermost mask pixels, half a + pixel inside the mask's real outline, so the polygons are filled at + `_SUPERSAMPLE`x resolution, grown by half a pixel and box-averaged back down. + """ + h, w = band.shape[:2] + coverage = np.zeros((h, w), np.uint8) + ys, xs = np.nonzero(band) + if not len(ys): + return coverage + y0, y1, x0, x1 = int(ys.min()), int(ys.max()) + 1, int(xs.min()), int(xs.max()) + 1 + ss = _SUPERSAMPLE + fine = np.zeros(((y1 - y0) * ss, (x1 - x0) * ss), np.uint8) + scale = float(1 << _FILL_SHIFT) + origin = np.array([x0, y0], np.float32) + for depth, polygon in polygons: + if len(polygon) < 3: + continue + # Pixel centre (x, y) is fine pixel (x * ss + (ss - 1) / 2). + fine_points = (polygon - origin) * ss + (ss - 1) / 2.0 + # Outer edges fill, holes (furniture cut-outs) clear: nesting parity. + cv2.fillPoly(fine, [np.round(fine_points * scale).astype(np.int32)], 255 if depth % 2 == 0 else 0, + lineType=cv2.LINE_8, shift=_FILL_SHIFT) + grow = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (ss + 1, ss + 1)) + fine = cv2.dilate(fine, grow) + coverage[y0:y1, x0:x1] = cv2.resize(fine, (x1 - x0, y1 - y0), interpolation=cv2.INTER_AREA) + return coverage + + +def _fill_specks(alpha: np.ndarray, original: np.ndarray, max_area: int) -> tuple[np.ndarray, int]: + """Fill the small holes the filter punched into floor the segmentation was sure of. + + On textured floors (speckled carpet) next to a light wall, light specks look + like the wall to the guided filter and turn into holes where the photo shows + through the tile. A hole is filled when it is small, enclosed by tile and + mostly floor in the original mask; real cut-outs (a table base, a chair leg) + were never floor there. A small grey closing then removes partial specks. + """ + holes = (alpha < 128).astype(np.uint8) + count, labels, stats, _ = cv2.connectedComponentsWithStats(holes, connectivity=4) + filled = 0 + if count > 1: + area = stats[:, cv2.CC_STAT_AREA].astype(np.float64) + floor_share = np.bincount(labels.ravel(), weights=(original > 0).ravel(), minlength=count) / np.maximum(area, 1) + fill = (area <= max_area) & (floor_share > 0.5) + fill[0] = False + filled = int(fill.sum()) + if filled: + alpha = alpha.copy() + alpha[fill[labels]] = 255 + closed = cv2.morphologyEx(alpha, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))) + # Closing only fills: it never takes tile away from the original floor's outline. + return np.where(original > 0, closed, alpha), filled + + +def _keep_connected_to(candidate: np.ndarray, original: np.ndarray) -> np.ndarray: + """Drop islands the filter created away from the original surface.""" + candidate = candidate.astype(np.uint8) + count, labels = cv2.connectedComponents(candidate, connectivity=8) + if count <= 2: + return candidate + keep = np.zeros(count, dtype=bool) + keep[np.unique(labels[(original > 0) & (candidate > 0)])] = True + keep[0] = False + return keep[labels].astype(np.uint8) diff --git a/apps/renderer/services/floor/geometry_filter.py b/apps/renderer/services/floor/geometry_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a2db3712cb120d27a61770cb4e937619c3b974 --- /dev/null +++ b/apps/renderer/services/floor/geometry_filter.py @@ -0,0 +1,110 @@ +"""Geometry-aware surface filtering using 3D plane consistency. + +Functions +--------- +filter_surface_by_floor_geometry - remove surface pixels that are inconsistent + with the fitted floor plane +""" + +import cv2 +import numpy as np + +from config.surface import ( + ENABLE_GEOMETRY_SURFACE_FILTER, + SURFACE_EDGE_CLOSE_RATIO, + SURFACE_MIN_PLANE_PIXELS, + SURFACE_PLANE_DISTANCE_METERS, + SURFACE_PLANE_FILTER_MIN_KEEP_RATIO, + SURFACE_PLANE_NORMAL_MIN_COS, +) +from services.floor.edge_coverage import scaled_odd_kernel_size +from services.geometry.multi_plane import geometry_point_maps + + +def filter_surface_by_floor_geometry( + surface: np.ndarray, + geometry: dict | None, + plane: dict | None, + *, + geometry_maps: dict | None = None, +) -> tuple[np.ndarray, dict]: + before = int(surface.sum()) + metadata = { + "geometrySurfaceFilterEnabled": ENABLE_GEOMETRY_SURFACE_FILTER, + "geometrySurfaceFilterApplied": False, + "geometrySurfaceFilterReason": "disabled" if not ENABLE_GEOMETRY_SURFACE_FILTER else "unavailable", + "geometrySurfacePixelsBefore": before, + "geometrySurfacePixelsAfter": before, + "geometrySurfacePlaneDistanceThresholdMeters": SURFACE_PLANE_DISTANCE_METERS, + "geometrySurfacePlaneNormalMinCos": SURFACE_PLANE_NORMAL_MIN_COS, + } + if not ENABLE_GEOMETRY_SURFACE_FILTER or before == 0: + return surface, metadata + if geometry is None or plane is None: + return surface, metadata + if not plane.get("planeNormal") or not plane.get("planeOrigin"): + return surface, metadata + + maps = geometry_maps if geometry_maps is not None else geometry_point_maps(surface, geometry) + if maps is None: + metadata["geometrySurfaceFilterReason"] = "point-map-unavailable" + return surface, metadata + + points = maps["points"] + normals = maps["normals"] + valid = maps["validMask"] & (surface > 0) + if int(valid.sum()) < SURFACE_MIN_PLANE_PIXELS: + metadata["geometrySurfaceFilterReason"] = "too-few-valid-pixels" + return surface, metadata + + plane_normal = np.asarray(plane["planeNormal"], dtype=np.float32) + plane_origin = np.asarray(plane["planeOrigin"], dtype=np.float32) + normal_len = float(np.linalg.norm(plane_normal)) + if normal_len < 1e-6 or not np.isfinite(plane_normal).all() or not np.isfinite(plane_origin).all(): + metadata["geometrySurfaceFilterReason"] = "invalid-plane" + return surface, metadata + plane_normal /= normal_len + + distances = np.full(surface.shape, np.inf, dtype=np.float32) + distances[valid] = np.abs((points[valid] - plane_origin) @ plane_normal) + keep = valid & (distances <= SURFACE_PLANE_DISTANCE_METERS) + + if normals is not None and normals.shape[:2] == surface.shape: + prepared_normal_valid = maps.get("normalValidMask") + normal_valid = valid & ( + prepared_normal_valid + if prepared_normal_valid is not None and prepared_normal_valid.shape == surface.shape + else np.isfinite(normals).all(axis=2) & (np.linalg.norm(normals, axis=2) > 1e-4) + ) + if int(normal_valid.sum()) >= SURFACE_MIN_PLANE_PIXELS: + # geometry_point_maps returns normalized normals. Reuse them + # directly instead of allocating and normalizing another full-size + # HxWx3 array for every surface-filter pass. + alignment = np.abs(np.einsum("ijk,k->ij", normals, plane_normal, optimize=True)) + keep &= (~normal_valid) | (alignment >= SURFACE_PLANE_NORMAL_MIN_COS) + metadata["geometrySurfaceNormalPixels"] = int(normal_valid.sum()) + + after = int(keep.sum()) + keep_ratio = after / max(before, 1) + metadata["geometrySurfacePixelsAfter"] = after + metadata["geometrySurfaceFilterKeepRatio"] = float(keep_ratio) + + if after < SURFACE_MIN_PLANE_PIXELS or keep_ratio < SURFACE_PLANE_FILTER_MIN_KEEP_RATIO: + metadata["geometrySurfaceFilterReason"] = "filter-too-aggressive" + return surface, metadata + + filtered = keep.astype(np.uint8) + close_size = scaled_odd_kernel_size( + surface.shape[0], + surface.shape[1], + SURFACE_EDGE_CLOSE_RATIO, + minimum=3, + ) + if close_size > 1: + close_kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (close_size, close_size)) + filtered = cv2.morphologyEx(filtered, cv2.MORPH_CLOSE, close_kern) + filtered = (filtered > 0).astype(np.uint8) + metadata["geometrySurfaceFilterApplied"] = True + metadata["geometrySurfaceFilterReason"] = "floor-plane-consistent" + metadata["geometrySurfacePixelsAfter"] = int(filtered.sum()) + return filtered, metadata diff --git a/apps/renderer/services/floor/mask.py b/apps/renderer/services/floor/mask.py new file mode 100644 index 0000000000000000000000000000000000000000..aca4f360c27a67ea6b53c6f04cb69ddbf69daa61 --- /dev/null +++ b/apps/renderer/services/floor/mask.py @@ -0,0 +1,247 @@ +"""Floor mask creation and morphological cleanup. + +Functions +--------- +clean_floor_mask - morphological close/open + connected-component filtering +smooth_mask_edge - remove pixel speckle along the mask edge +wall_subtract - remove wall/reject pixels from a floor mask +build_floor_surface_mask - composite floor surface from segmentation, depth, and geometry +""" + +import time + +import cv2 +import numpy as np + +from config.runtime import ENABLE_FLOOR_MASK_CLEANUP +from state import ( + OCCLUDER_CLASSES, + REJECT_SURFACE_CLASSES, + SOFT_FLOOR_COVERING_CLASSES, + class_ids, +) +from utils import seg_class_mask +from services.floor.edge_coverage import ( + improve_surface_edge_coverage, + expand_surface_over_soft_floor_coverings, +) +from services.floor.geometry_filter import filter_surface_by_floor_geometry + + +def clean_floor_mask(mask: np.ndarray) -> np.ndarray: + if not ENABLE_FLOOR_MASK_CLEANUP: + return mask.astype(np.uint8, copy=False) + + if mask.dtype != np.uint8: + mask = mask.astype(np.uint8) + + h, w = mask.shape[:2] + min_side = max(3, min(h, w)) + close_size = max(5, int(round(min_side * 0.018))) | 1 + open_size = max(3, int(round(min_side * 0.006))) | 1 + closed = cv2.morphologyEx( + mask, + cv2.MORPH_CLOSE, + cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (close_size, close_size)), + ) + cleaned = cv2.morphologyEx( + closed, + cv2.MORPH_OPEN, + cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (open_size, open_size)), + ) + + count, labels, stats, _ = cv2.connectedComponentsWithStats(cleaned, connectivity=8) + if count <= 1: + return cleaned + + gravity_threshold = int(h * 0.60) + min_area = max(1000, int(h * w * 0.01)) + result = np.zeros_like(cleaned) + for component_id in range(1, count): + area = stats[component_id, cv2.CC_STAT_AREA] + if area < min_area: + continue + comp_bottom = stats[component_id, cv2.CC_STAT_TOP] + stats[component_id, cv2.CC_STAT_HEIGHT] + if comp_bottom <= gravity_threshold: + continue + result[labels == component_id] = 1 + + if result.any(): + return result + largest = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) + return (labels == largest).astype(np.uint8) + + +def smooth_mask_edge(mask: np.ndarray, sigma: float = 1.5) -> np.ndarray: + """Remove the single-pixel speckle and spikes the per-pixel depth and plane filters leave.""" + if not mask.any(): + return mask.astype(np.uint8, copy=False) + blurred = cv2.GaussianBlur(mask.astype(np.float32), (0, 0), sigmaX=sigma, sigmaY=sigma) + return (blurred >= 0.5).astype(np.uint8) + + +def wall_subtract(mask: np.ndarray, seg_map: np.ndarray, dilation: int = 1) -> np.ndarray: + reject_raw = seg_class_mask(seg_map, class_ids(REJECT_SURFACE_CLASSES)) + if dilation > 0: + kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) + reject_raw = cv2.dilate(reject_raw, kern, iterations=dilation) + result = mask.copy() + result[reject_raw > 0] = 0 + return result + + +def build_floor_surface_mask( + floor_mask: np.ndarray, + seg_map: np.ndarray, + quad: np.ndarray | None, + depth: np.ndarray | None, + geometry: dict | None, + plane: dict | None, + *, + geometry_maps: dict | None = None, +): + total_started = time.perf_counter() + phase_started = total_started + h, w = floor_mask.shape[:2] + kern_size = max(5, min(h, w) // 160) | 1 + kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kern_size, kern_size)) + occluder_mask = seg_class_mask(seg_map, class_ids(OCCLUDER_CLASSES)) + soft_covering_mask = seg_class_mask(seg_map, class_ids(SOFT_FLOOR_COVERING_CLASSES)) + reject_mask = seg_class_mask(seg_map, class_ids(REJECT_SURFACE_CLASSES)) + hard_protected_mask = (occluder_mask > 0) | (reject_mask > 0) + normal_edge_protected_mask = hard_protected_mask | (soft_covering_mask > 0) + + surface = floor_mask.copy() + surface[reject_mask > 0] = 0 + surface[soft_covering_mask > 0] = 0 + if not surface.any(): + surface = floor_mask.copy() + surface[soft_covering_mask > 0] = 0 + + contours, _ = cv2.findContours(surface, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + if contours: + filled = np.zeros((h, w), dtype=np.uint8) + cv2.drawContours(filled, contours, -1, 1, cv2.FILLED) + filled[reject_mask > 0] = 0 + filled[soft_covering_mask > 0] = 0 + surface = filled + + if quad is not None and surface.any(): + plane_mask = np.zeros((h, w), dtype=np.uint8) + cv2.fillConvexPoly(plane_mask, np.round(quad).astype(np.int32), 1) + plane_mask[reject_mask > 0] = 0 + plane_mask[soft_covering_mask > 0] = 0 + near_floor = cv2.dilate(surface, kern, iterations=6) + surface = cv2.bitwise_or(surface, cv2.bitwise_and(plane_mask, near_floor)) + surface[soft_covering_mask > 0] = 0 + + surface[occluder_mask > 0] = 0 + surface[soft_covering_mask > 0] = 0 + if depth is not None and floor_mask.any(): + floor_depth = depth[(floor_mask > 0) & np.isfinite(depth)] + if floor_depth.size == 0: + floor_depth = None + else: + floor_depth = None + if floor_depth is not None: + lo, hi = float(np.percentile(floor_depth, 2)), float(np.percentile(floor_depth, 98)) + margin = max(0.08, (hi - lo) * 0.35) + depth_keep = (depth >= lo - margin) & (depth <= hi + margin) + surface = (surface & depth_keep.astype(np.uint8)).astype(np.uint8) + surface[floor_mask > 0] = np.maximum(surface[floor_mask > 0], 1) + surface[occluder_mask > 0] = 0 + surface[reject_mask > 0] = 0 + surface[soft_covering_mask > 0] = 0 + preparation_ms = (time.perf_counter() - phase_started) * 1000 + + phase_started = time.perf_counter() + surface, geometry_filter_metadata = filter_surface_by_floor_geometry( + surface, + geometry, + plane, + geometry_maps=geometry_maps, + ) + initial_filter_ms = (time.perf_counter() - phase_started) * 1000 + surface[occluder_mask > 0] = 0 + surface[reject_mask > 0] = 0 + surface[soft_covering_mask > 0] = 0 + + phase_started = time.perf_counter() + surface = clean_floor_mask(surface) + surface[occluder_mask > 0] = 0 + surface[reject_mask > 0] = 0 + surface[soft_covering_mask > 0] = 0 + + surface, edge_metadata = improve_surface_edge_coverage(surface, normal_edge_protected_mask) + cleanup_and_edge_ms = (time.perf_counter() - phase_started) * 1000 + + phase_started = time.perf_counter() + surface, post_edge_filter_metadata = filter_surface_by_floor_geometry( + surface, + geometry, + plane, + geometry_maps=geometry_maps, + ) + post_edge_filter_ms = (time.perf_counter() - phase_started) * 1000 + surface[occluder_mask > 0] = 0 + surface[reject_mask > 0] = 0 + surface[soft_covering_mask > 0] = 0 + post_edge_filter_metadata = { + f"postEdge{k[0].upper()}{k[1:]}": value + for k, value in post_edge_filter_metadata.items() + } + + phase_started = time.perf_counter() + surface_before_soft_covering = surface + surface, soft_covering_metadata = expand_surface_over_soft_floor_coverings( + surface, + soft_covering_mask, + hard_protected_mask, + ) + soft_covering_ms = (time.perf_counter() - phase_started) * 1000 + + phase_started = time.perf_counter() + if surface is surface_before_soft_covering or not soft_covering_metadata["softFloorCoveringExpansionApplied"]: + post_soft_covering_filter_metadata = { + "geometrySurfaceFilterApplied": False, + "geometrySurfaceFilterReason": "soft-floor-surface-unchanged", + "geometrySurfacePixelsBefore": int(surface.sum()), + "geometrySurfacePixelsAfter": int(surface.sum()), + } + else: + surface, post_soft_covering_filter_metadata = filter_surface_by_floor_geometry( + surface, + geometry, + plane, + geometry_maps=geometry_maps, + ) + post_soft_filter_ms = (time.perf_counter() - phase_started) * 1000 + surface = smooth_mask_edge(surface) + surface[occluder_mask > 0] = 0 + surface[reject_mask > 0] = 0 + post_soft_covering_filter_metadata = { + f"postSoftFloorCovering{k[0].upper()}{k[1:]}": value + for k, value in post_soft_covering_filter_metadata.items() + } + timing_ms = { + "preparation": round(preparation_ms, 2), + "initialGeometryFilter": round(initial_filter_ms, 2), + "cleanupAndEdgeRepair": round(cleanup_and_edge_ms, 2), + "postEdgeGeometryFilter": round(post_edge_filter_ms, 2), + "softFloorExpansion": round(soft_covering_ms, 2), + "postSoftFloorGeometryFilter": round(post_soft_filter_ms, 2), + "total": round((time.perf_counter() - total_started) * 1000, 2), + } + print( + "[SURFACE_MASKING_TIMING] " + + " ".join(f"{name}={duration:.2f}ms" for name, duration in timing_ms.items()), + flush=True, + ) + return surface, { + **geometry_filter_metadata, + **edge_metadata, + **post_edge_filter_metadata, + **soft_covering_metadata, + **post_soft_covering_filter_metadata, + "surfaceMaskingTimingMs": timing_ms, + } diff --git a/apps/renderer/services/floor/sam_refinement.py b/apps/renderer/services/floor/sam_refinement.py new file mode 100644 index 0000000000000000000000000000000000000000..369fe8ac574974eef3329724c1bc540fa94c3b2e --- /dev/null +++ b/apps/renderer/services/floor/sam_refinement.py @@ -0,0 +1,138 @@ +"""SAM2-based floor mask refinement. + +Functions +--------- +sample_prompt_points - sample positive/negative prompt points from a mask +refine_floor_mask_with_sam2 - refine a floor mask using SAM2 predictions +""" + +import cv2 +import numpy as np + +from config.runtime import ENABLE_SAM_REFINEMENT +from config.surface import SURFACE_MIN_PLANE_PIXELS +from models.loader import _load_sam2_predictor +from services.floor.mask import clean_floor_mask +from utils import seg_class_mask +from state import ( + OCCLUDER_CLASSES, + REJECT_SURFACE_CLASSES, + class_ids, +) + + +def sample_prompt_points(mask: np.ndarray, count: int, positive: bool) -> list[list[float]]: + ys, xs = np.where(mask > 0) + if len(xs) == 0: + return [] + if positive: + step = max(1, len(xs) // max(count, 1)) + order = np.argsort(np.abs(ys - np.median(ys)) + np.abs(xs - np.median(xs))) + chosen = order[::step][:count] + else: + step = max(1, len(xs) // max(count, 1)) + chosen = np.arange(0, len(xs), step)[:count] + return [[float(xs[i]), float(ys[i])] for i in chosen] + + +def refine_floor_mask_with_sam2( + img_np: np.ndarray, + floor_mask: np.ndarray, + seg_map: np.ndarray, +) -> tuple[np.ndarray, dict]: + metadata = { + "samRefinementEnabled": ENABLE_SAM_REFINEMENT, + "samRefinementApplied": False, + "samRefinementReason": "disabled" if not ENABLE_SAM_REFINEMENT else "unavailable", + "samRefinementScore": None, + } + if not ENABLE_SAM_REFINEMENT or int(floor_mask.sum()) < SURFACE_MIN_PLANE_PIXELS: + return floor_mask, metadata + + predictor = _load_sam2_predictor() + if predictor is None: + return floor_mask, metadata + + ys, xs = np.where(floor_mask > 0) + if len(xs) == 0: + metadata["samRefinementReason"] = "empty-floor-mask" + return floor_mask, metadata + + h, w = floor_mask.shape[:2] + pad = max(4, min(h, w) // 80) + box = np.array([ + max(0, int(xs.min()) - pad), + max(0, int(ys.min()) - pad), + min(w - 1, int(xs.max()) + pad), + min(h - 1, int(ys.max()) + pad), + ], dtype=np.float32) + + positive_mask = cv2.erode( + floor_mask.astype(np.uint8), + cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 9)), + iterations=1, + ) + reject_mask = seg_class_mask(seg_map, class_ids(REJECT_SURFACE_CLASSES | OCCLUDER_CLASSES)) + negative_mask = cv2.dilate( + reject_mask, + cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7)), + iterations=1, + ) + + positive_points = sample_prompt_points(positive_mask, 4, positive=True) + negative_points = sample_prompt_points(negative_mask, 6, positive=False) + point_coords = np.asarray(positive_points + negative_points, dtype=np.float32) + point_labels = np.asarray( + [1] * len(positive_points) + [0] * len(negative_points), + dtype=np.int32, + ) + + try: + predictor.set_image(img_np) + masks, scores, _ = predictor.predict( + point_coords=point_coords if len(point_coords) else None, + point_labels=point_labels if len(point_labels) else None, + box=box, + multimask_output=True, + ) + except Exception as exc: + metadata["samRefinementReason"] = f"predict-failed:{exc}" + return floor_mask, metadata + + if masks is None or len(masks) == 0: + metadata["samRefinementReason"] = "no-mask" + return floor_mask, metadata + + best_idx = int(np.argmax(scores)) if scores is not None and len(scores) else 0 + sam_mask = masks[best_idx].astype(np.uint8) + if sam_mask.shape[:2] != floor_mask.shape: + sam_mask = cv2.resize(sam_mask, (w, h), interpolation=cv2.INTER_NEAREST) + + reject_dilated = cv2.dilate( + reject_mask, + cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)), + iterations=1, + ) + floor_dilated = cv2.dilate( + floor_mask.astype(np.uint8), + cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (max(5, min(h, w) // 80) | 1,) * 2), + iterations=2, + ) + refined = (sam_mask & floor_dilated).astype(np.uint8) + refined[reject_dilated > 0] = 0 + refined = clean_floor_mask(refined) + + refined_area = int(refined.sum()) + original_area = int(floor_mask.sum()) + if refined_area < SURFACE_MIN_PLANE_PIXELS or refined_area < original_area * 0.35: + metadata["samRefinementReason"] = "refined-mask-too-small" + return floor_mask, metadata + + metadata.update({ + "samRefinementApplied": True, + "samRefinementReason": "sam2-mask-refined", + "samRefinementScore": float(scores[best_idx]) if scores is not None and len(scores) else None, + "samRefinementOriginalPixels": original_area, + "samRefinementPixels": refined_area, + }) + return refined, metadata diff --git a/apps/renderer/services/gemini/__init__.py b/apps/renderer/services/gemini/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8181361c0bd7d2b1b6ea7b966ff7ca6d5977863d --- /dev/null +++ b/apps/renderer/services/gemini/__init__.py @@ -0,0 +1 @@ +# Gemini API integration services: prompt building and image refinement. diff --git a/apps/renderer/services/gemini/client.py b/apps/renderer/services/gemini/client.py new file mode 100644 index 0000000000000000000000000000000000000000..7cab680ab791c9b56eb50edad4c83fcfb5f231a8 --- /dev/null +++ b/apps/renderer/services/gemini/client.py @@ -0,0 +1,127 @@ +"""Gemini API client: decode inline images and call image refinement.""" + +import base64 +import io +import json +import urllib.error +import urllib.parse +import urllib.request + +from PIL import Image + +from config.gemini import ( + GEMINI_API_BASE_URL, + GEMINI_API_KEY, + GEMINI_IMAGE_MODEL, + GEMINI_TIMEOUT_SECONDS, +) +from errors import bad_gateway, bad_request, service_unavailable + + +def decode_inline_image_payload(image_value: str) -> tuple[bytes, str]: + if not image_value: + bad_request("Image is required.") + + mime_type = "image/png" + encoded = image_value + if image_value.startswith("data:"): + try: + header, encoded = image_value.split(",", 1) + except ValueError as exc: + bad_request("Image data URL is malformed.", exc) + mime_type = header[5:].split(";", 1)[0] or mime_type + + try: + image_bytes = base64.b64decode(encoded, validate=True) + except Exception as exc: + bad_request("Image must be base64 encoded.", exc) + + if not image_bytes: + bad_request("Image must not be empty.") + + try: + with Image.open(io.BytesIO(image_bytes)) as uploaded: + uploaded.verify() + detected_mime = Image.MIME.get(uploaded.format) + if detected_mime: + mime_type = detected_mime + except Exception as exc: + bad_request("Image must be a readable PNG, JPEG, or WebP.", exc) + + if mime_type not in {"image/png", "image/jpeg", "image/webp"}: + bad_request("Image must be a PNG, JPEG, or WebP.") + + return image_bytes, mime_type + + +def call_gemini_image_refinement(image_bytes: bytes, mime_type: str, prompt: str) -> tuple[str, str]: + """One image and one instruction in, one image out (base64, mime).""" + output, output_mime = call_gemini_image([(image_bytes, mime_type, None)], prompt) + return base64.b64encode(output).decode("ascii"), output_mime + + +def call_gemini_image( + images: list[tuple[bytes, str, str | None]], + prompt: str, + *, + aspect_ratio: str | None = None, + image_size: str | None = None, +) -> tuple[bytes, str]: + """Images (bytes, mime, optional caption placed before it) and an instruction in; one image out.""" + if not GEMINI_API_KEY: + service_unavailable("Gemini refinement is not configured. Set GEMINI_API_KEY.") + if not GEMINI_IMAGE_MODEL: + service_unavailable("Gemini image model is not configured.") + + parts: list[dict] = [{"text": prompt}] + for data, mime, caption in images: + if caption: + parts.append({"text": caption}) + parts.append({"inline_data": {"mime_type": mime, "data": base64.b64encode(data).decode("ascii")}}) + # Image only: no text answer to generate, which keeps the call short. + generation_config: dict = {"responseModalities": ["IMAGE"]} + image_config = {key: value for key, value in (("aspectRatio", aspect_ratio), ("imageSize", image_size)) if value} + if image_config: + generation_config["imageConfig"] = image_config + request_body = {"contents": [{"parts": parts}], "generationConfig": generation_config} + encoded_model = urllib.parse.quote(GEMINI_IMAGE_MODEL, safe="") + url = f"{GEMINI_API_BASE_URL}/{encoded_model}:generateContent" + request = urllib.request.Request( + url, + data=json.dumps(request_body).encode("utf-8"), + headers={ + "Content-Type": "application/json", + "x-goog-api-key": GEMINI_API_KEY, + }, + method="POST", + ) + + try: + with urllib.request.urlopen(request, timeout=GEMINI_TIMEOUT_SECONDS) as response: + response_body = response.read().decode("utf-8") + except urllib.error.HTTPError as exc: + detail = exc.read().decode("utf-8", errors="replace")[:1000] + bad_gateway(f"Gemini refinement failed ({exc.code}): {detail}", exc) + except (urllib.error.URLError, TimeoutError) as exc: + bad_gateway(f"Gemini refinement request failed: {getattr(exc, 'reason', exc)}", exc) + + try: + data = json.loads(response_body) + except json.JSONDecodeError as exc: + bad_gateway("Gemini returned invalid JSON.", exc) + + for candidate in data.get("candidates", []): + content = candidate.get("content") or {} + for part in content.get("parts", []): + inline_data = part.get("inlineData") or part.get("inline_data") + if not inline_data: + continue + output_b64 = inline_data.get("data") + if output_b64: + output_mime = inline_data.get("mimeType") or inline_data.get("mime_type") or "image/png" + return base64.b64decode(output_b64), output_mime + + reason = (data.get("promptFeedback") or {}).get("blockReason") or next( + (c["finishReason"] for c in data.get("candidates", []) if c.get("finishReason")), "no image" + ) + bad_gateway(f"Gemini did not return a refined image ({reason}).") diff --git a/apps/renderer/services/gemini/enhance.py b/apps/renderer/services/gemini/enhance.py new file mode 100644 index 0000000000000000000000000000000000000000..3b8a4c885d619deb694a69e80d4d52be9429684c --- /dev/null +++ b/apps/renderer/services/gemini/enhance.py @@ -0,0 +1,459 @@ +"""The "Enhance with AI" pass: a Gemini finish over a completed visualizer render. + +The render is the source of truth. Gemini gets it (downscaled, so the call is +short), plus a small reference image of each applied tile or wallpaper, and +returns the same room with natural shading and with wall gaps around furniture +filled. When the visualizer sends its surface mask, only the covered surfaces +(plus their gaps) are taken from Gemini; every other pixel stays the render's +own, so furniture, people, doors and windows can never be redrawn. Structure and +colour checks refuse answers that changed the pattern or the room. +""" + +from __future__ import annotations + +import io +import logging +import math +import threading +import time +import urllib.parse +import urllib.request +from collections import OrderedDict, deque +from dataclasses import dataclass, field + +import cv2 +import numpy as np +from PIL import Image, ImageOps + +from config.gemini import ( + GEMINI_ENHANCE_PER_HOUR, + GEMINI_IMAGE_SIZE, + GEMINI_MAX_INPUT_SIDE, + GEMINI_MAX_NEW_PATTERN, + GEMINI_MAX_RECOLOURED, + GEMINI_MIN_SIMILARITY, + GEMINI_REFERENCE_HOSTS, +) +from services.gemini.client import call_gemini_image +from services.gemini.prompt import build_room_enhancement_prompt, reference_caption + +logger = logging.getLogger(__name__) + +# The output shapes Gemini image models accept. +ASPECT_RATIOS = ("1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9") +REFERENCE_MAX_SIDE = 512 +REFERENCE_MAX_BYTES = 15 * 1024 * 1024 +REFERENCE_CACHE_SIZE = 64 +MAX_SURFACES = 6 +GUARD_SIDE = 256 +# Editable region, as fractions of the image height (see editable_region). +EDIT_CLOSE = 0.02 +EDIT_MAX_HOLE = 0.004 # of the image area +EDIT_REACH_DOWN = 0.12 +EDIT_GROW = 0.01 +EDIT_FEATHER = 0.004 +FILLED_SIDE = 512 +GAP_FILLED_SHARE = 0.25 # of a strip under a wall that must be papered for Gemini's version to be used +# Relighting (see relight): Gemini's brightness and light colour scales, and the band along +# each surface's edge where Gemini's own pixels are kept, as fractions of the image height. +RELIGHT_SHADE_SIGMA = 0.006 +RELIGHT_TINT_SIGMA = 0.03 +RELIGHT_EDGE_BAND = 0.008 +RELIGHT_MAX_TINT = 0.08 # a light can warm or cool a channel by at most this much + + +@dataclass +class Surface: + name: str + kind: str # "wall" | "floor" + tile_name: str | None = None + image_url: str | None = None + # Real size of one repeat (or of the whole mural), for the prompt. + width_mm: float | None = None + height_mm: float | None = None + mural: bool = False + # Where it is across the picture ("the far left" … "the far right"), so the AI never confuses two walls. + position: str | None = None + + +@dataclass +class Enhancement: + image: bytes | None + similarity: float + attempts: int + timings_ms: dict[str, int] = field(default_factory=dict) + + +def closest_aspect_ratio(width: float, height: float) -> str: + """The supported ratio nearest to width:height.""" + target = math.log(width / height) + + def distance(ratio: str) -> float: + w, h = ratio.split(":") + return abs(math.log(int(w) / int(h)) - target) + + return min(ASPECT_RATIOS, key=distance) + + +def _open_rgb(data: bytes) -> Image.Image: + with Image.open(io.BytesIO(data)) as opened: + return ImageOps.exif_transpose(opened).convert("RGB") + + +def _jpeg(image: Image.Image, quality: int = 90) -> bytes: + buffer = io.BytesIO() + image.save(buffer, format="JPEG", quality=quality) + return buffer.getvalue() + + +def prepare_render(data: bytes, max_side: int = GEMINI_MAX_INPUT_SIDE) -> tuple[Image.Image, bytes]: + """The render as uploaded, and the smaller JPEG sent to Gemini.""" + render = _open_rgb(data) + small = render.copy() + small.thumbnail((max_side, max_side), Image.Resampling.LANCZOS) + return render, _jpeg(small) + + +class _ReferenceCache: + """Tile images by URL, downscaled once; the catalog repeats across requests.""" + + def __init__(self, size: int = REFERENCE_CACHE_SIZE): + self._items: OrderedDict[str, bytes] = OrderedDict() + self._size = size + self._lock = threading.Lock() + + def get(self, url: str) -> bytes | None: + with self._lock: + if url in self._items: + self._items.move_to_end(url) + return self._items[url] + data = _download_reference(url) + if data is not None: + with self._lock: + self._items[url] = data + while len(self._items) > self._size: + self._items.popitem(last=False) + return data + + +def reference_allowed(url: str) -> bool: + parsed = urllib.parse.urlparse(url) + return parsed.scheme == "https" and (parsed.hostname or "").lower() in GEMINI_REFERENCE_HOSTS + + +def _download_reference(url: str) -> bytes | None: + """Only our tile CDN; anything else (or any failure) just means no reference.""" + if not reference_allowed(url): + return None + try: + with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": "baetes-renderer"}), timeout=10) as response: + raw = response.read(REFERENCE_MAX_BYTES + 1) + if len(raw) > REFERENCE_MAX_BYTES: + return None + image = _open_rgb(raw) + image.thumbnail((REFERENCE_MAX_SIDE, REFERENCE_MAX_SIDE), Image.Resampling.LANCZOS) + return _jpeg(image, quality=88) + except Exception as exc: # a missing reference must never fail the enhancement + logger.info("Reference image %s unavailable: %s", url, exc) + return None + + +references = _ReferenceCache() + + +def _structure(image: Image.Image, size: tuple[int, int]) -> np.ndarray: + gray = np.asarray(image.convert("L").resize(size, Image.Resampling.BOX), dtype=np.float32) / 255.0 + gray = cv2.GaussianBlur(gray, (0, 0), 1.0) + gx = cv2.Sobel(gray, cv2.CV_32F, 1, 0, ksize=3) + gy = cv2.Sobel(gray, cv2.CV_32F, 0, 1, ksize=3) + return np.stack([gx, gy], axis=-1) + + +def structure_similarity(reference: Image.Image, candidate: Image.Image) -> float: + """How much of the reference's edges (pattern, furniture, room lines) the candidate keeps, 0..1. + + Correlation of the two gradient fields at low resolution: shading, gloss and + small filled gaps barely move it; a redrawn pattern or a moved object does. + """ + width, height = reference.size + scale = GUARD_SIDE / max(width, height) + size = (max(8, round(width * scale)), max(8, round(height * scale))) + a = _structure(reference, size) + b = _structure(candidate, size) + denominator = float(np.sqrt((a * a).sum() * (b * b).sum())) + if denominator <= 1e-9: + return 0.0 + return max(0.0, float((a * b).sum()) / denominator) + + +NEW_PATTERN_SIDE = 384 + + +def _local_contrast(image: Image.Image, size: tuple[int, int]) -> np.ndarray: + lightness = cv2.cvtColor(np.asarray(image.resize(size, Image.Resampling.BOX)), cv2.COLOR_RGB2LAB)[..., 0] + lightness = lightness.astype(np.float32) + mean = cv2.blur(lightness, (5, 5)) + return np.sqrt(np.maximum(cv2.blur(lightness * lightness, (5, 5)) - mean * mean, 0.0)) + + +def invented_pattern(reference: Image.Image, candidate: Image.Image) -> float: + """Largest single area (fraction of the image) that was plain in the render and is patterned now. + + Catches a design spread onto a wall the shopper left plain. Gaps filled + between furniture are thin, broken strips; the opening removes them. + """ + width, height = reference.size + scale = NEW_PATTERN_SIDE / max(width, height) + size = (max(16, round(width * scale)), max(16, round(height * scale))) + before = _local_contrast(reference, size) + after = _local_contrast(candidate, size) + new = ((after - before > 4.0) & (before < 2.0)).astype(np.uint8) + new = cv2.morphologyEx(new, cv2.MORPH_CLOSE, np.ones((5, 5), np.uint8)) + new = cv2.morphologyEx(new, cv2.MORPH_OPEN, np.ones((7, 7), np.uint8)) + count, _labels, stats, _ = cv2.connectedComponentsWithStats(new) + largest = max((int(stats[i, cv2.CC_STAT_AREA]) for i in range(1, count)), default=0) + return largest / new.size + + +RECOLOUR_SIDE = 48 +RECOLOUR_SHIFT = 0.016 + + +def _chromaticity(image: Image.Image) -> np.ndarray: + """Each pixel's colour with its brightness divided out (r and g shares of r+g+b).""" + rgb = np.asarray(image, dtype=np.float32) + 8.0 # keeps near-black pixels from turning to noise + return rgb[..., :2] / rgb.sum(axis=-1, keepdims=True) + + +def recoloured_area(reference: Image.Image, candidate: Image.Image) -> float: + """Largest single area (fraction of the image) whose colour changed, ignoring brightness. + + Catches a design moved or swapped onto another wall (cream tulips repainted as + green leaves). Relighting changes lightness, not the r:g:b balance, so it barely counts. + """ + width, height = reference.size + scale = RECOLOUR_SIDE / max(width, height) + size = (max(8, round(width * scale)), max(8, round(height * scale))) + before = _chromaticity(reference.resize(size, Image.Resampling.BOX)) + after = _chromaticity(candidate.resize(size, Image.Resampling.BOX)) + shift = np.abs(after - before).sum(axis=-1) + changed = (shift > RECOLOUR_SHIFT).astype(np.uint8) + count, _labels, stats, _ = cv2.connectedComponentsWithStats(changed) + largest = max((int(stats[i, cv2.CC_STAT_AREA]) for i in range(1, count)), default=0) + return largest / changed.size + + +def _disc(radius: int) -> np.ndarray: + return cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * radius + 1, 2 * radius + 1)) + + +def _fill_small_holes(mask: np.ndarray, max_area: float) -> np.ndarray: + """Close enclosed holes smaller than max_area (fraction of the image): wall seen between chair backs.""" + count, labels, stats, _ = cv2.connectedComponentsWithStats((mask == 0).astype(np.uint8)) + height, width = mask.shape + small = [ + i for i in range(1, count) + if stats[i, cv2.CC_STAT_AREA] < max_area * mask.size + and stats[i, cv2.CC_STAT_LEFT] > 0 and stats[i, cv2.CC_STAT_TOP] > 0 + and stats[i, cv2.CC_STAT_LEFT] + stats[i, cv2.CC_STAT_WIDTH] < width + and stats[i, cv2.CC_STAT_TOP] + stats[i, cv2.CC_STAT_HEIGHT] < height + ] + return mask | np.isin(labels, small).astype(np.uint8) + + +@dataclass +class EditableRegion: + """Where Gemini's pixels may be used. `core` always: the covered surfaces and small holes in them. + `below` (the strip under a wall, down to the floor) only where Gemini continued the wallpaper there.""" + core: np.ndarray + below: np.ndarray + surfaces: np.ndarray + + +def editable_region(surfaces: np.ndarray, floor: np.ndarray | None) -> EditableRegion: + height = surfaces.shape[0] + core = cv2.morphologyEx(surfaces, cv2.MORPH_CLOSE, _disc(max(1, round(EDIT_CLOSE * height)))) + core = _fill_small_holes(core, EDIT_MAX_HOLE) + reach = max(1, round(EDIT_REACH_DOWN * height)) + below = cv2.dilate(surfaces, np.ones((reach, 1), np.uint8), anchor=(0, reach - 1)) & (1 - core) + if floor is not None: + below &= 1 - floor + return EditableRegion(core=core, below=below, surfaces=surfaces) + + +def _papered(render: Image.Image, candidate: Image.Image) -> np.ndarray: + """Pixels that were plain in the render and carry a pattern in the answer (a filled gap), at full size.""" + width, height = render.size + scale = FILLED_SIDE / max(width, height) + size = (max(16, round(width * scale)), max(16, round(height * scale))) + before = _local_contrast(render, size) + after = _local_contrast(candidate, size) + papered = ((after - before > 4.0) & (before < 2.5)).astype(np.uint8) + papered = cv2.morphologyEx(papered, cv2.MORPH_CLOSE, np.ones((5, 5), np.uint8)) + return cv2.resize(papered, (width, height), interpolation=cv2.INTER_NEAREST) + + +def _filled_gaps(below: np.ndarray, papered: np.ndarray) -> np.ndarray: + """Each strip under a wall, whole, when Gemini papered most of it; never part of one (a door).""" + count, labels, stats, _ = cv2.connectedComponentsWithStats(below) + if count <= 1: + return np.zeros_like(below) + covered = np.bincount(labels.ravel(), weights=papered.ravel().astype(np.float64), minlength=count) + share = covered / np.maximum(stats[:, cv2.CC_STAT_AREA], 1) + share[0] = 0.0 + return (share >= GAP_FILLED_SHARE)[labels].astype(np.uint8) + + +def blend_weights(region: EditableRegion, render: Image.Image, candidate: Image.Image) -> np.ndarray: + """0..1 per pixel: how much of Gemini's answer to use (feathered).""" + height = region.core.shape[0] + use = region.core | _filled_gaps(region.below, _papered(render, candidate)) + use = cv2.dilate(use, _disc(max(1, round(EDIT_GROW * height)))) + return cv2.GaussianBlur(use.astype(np.float32), (0, 0), max(0.5, EDIT_FEATHER * height)) + + +def decode_mask(data: bytes, size: tuple[int, int]) -> tuple[np.ndarray, np.ndarray | None] | None: + """The visualizer's mask PNG (red: covered surfaces, green: floor) at the render's size, or None if unusable.""" + try: + with Image.open(io.BytesIO(data)) as opened: + rgb = np.asarray(opened.convert("RGB").resize(size, Image.Resampling.NEAREST)) + except Exception as exc: + logger.info("Enhance mask unreadable: %s", exc) + return None + surfaces = (rgb[..., 0] > 127).astype(np.uint8) + if surfaces.mean() < 0.005: + return None + floor = (rgb[..., 1] > 127).astype(np.uint8) + return surfaces, (floor if floor.any() else None) + + +def _masked_blur(values: np.ndarray, mask: np.ndarray, sigma: float) -> np.ndarray: + """Gaussian average of values over the mask only, so light from outside a wall never leaks in.""" + weight = np.maximum(cv2.GaussianBlur(mask, (0, 0), sigma), 1e-4) + if values.ndim == 2: + return cv2.GaussianBlur(values * mask, (0, 0), sigma) / weight + return cv2.GaussianBlur(values * mask[..., None], (0, 0), sigma) / weight[..., None] + + +def relight(render: Image.Image, candidate: Image.Image, surfaces: np.ndarray) -> np.ndarray: + """Our render's exact design, lit the way Gemini lit it (float RGB). + + Like a retoucher's lighting layer: Gemini's brightness at a fine scale (falloff, + contact shadows) and its light colour at a coarse scale. The motifs' own colours + and lines stay the render's, so Gemini can never wash out or redraw the design. + """ + height = surfaces.shape[0] + mask = surfaces.astype(np.float32) + ours = np.asarray(render, np.float32) + 1.0 + theirs = np.asarray(candidate, np.float32) + 1.0 + luma = np.array([0.299, 0.587, 0.114], np.float32) + with np.errstate(divide="ignore", invalid="ignore"): # pixels far outside the surfaces; replaced below + return _relight(ours, theirs, mask, luma, height) + + +def _relight(ours: np.ndarray, theirs: np.ndarray, mask: np.ndarray, luma: np.ndarray, height: int) -> np.ndarray: + shade = (_masked_blur(theirs @ luma, mask, RELIGHT_SHADE_SIGMA * height) + / _masked_blur(ours @ luma, mask, RELIGHT_SHADE_SIGMA * height)) + # The light's colour shows on the design's pale, neutral ground, not on its coloured motifs. + neutral = (ours.max(axis=-1) - ours.min(axis=-1)) < 0.1 * (ours @ luma) + tint_mask = mask * neutral if (mask * neutral).sum() > 0.05 * mask.sum() else mask + theirs_coarse = _masked_blur(theirs, tint_mask, RELIGHT_TINT_SIGMA * height) + ours_coarse = _masked_blur(ours, tint_mask, RELIGHT_TINT_SIGMA * height) + tint = (theirs_coarse / (theirs_coarse @ luma)[..., None]) / (ours_coarse / (ours_coarse @ luma)[..., None]) + tint = np.clip(np.nan_to_num(tint, nan=1.0), 1.0 - RELIGHT_MAX_TINT, 1.0 + RELIGHT_MAX_TINT) + lit = ours * np.nan_to_num(shade, nan=1.0)[..., None] * tint - 1.0 + return np.clip(lit, 0, 255) + + +def finish(render: Image.Image, candidate: Image.Image, region: EditableRegion, surfaces: np.ndarray) -> Image.Image: + """The answer the shopper sees: Gemini's pixels only where it may edit, and inside the + covered surfaces our exact design relit by Gemini (its own pixels near the edges, where it + tidies cut lines and adds contact shadows).""" + height = surfaces.shape[0] + edited = np.asarray(composite(render, candidate, blend_weights(region, render, candidate)), np.float32) + band = max(1, round(RELIGHT_EDGE_BAND * height)) + interior = cv2.erode(surfaces, _disc(band)) + weight = cv2.GaussianBlur(interior.astype(np.float32), (0, 0), max(0.5, band / 2))[..., None] + final = relight(render, candidate, surfaces) * weight + edited * (1.0 - weight) + return Image.fromarray(np.clip(final + 0.5, 0, 255).astype(np.uint8)) + + +def composite(render: Image.Image, candidate: Image.Image, alpha: np.ndarray) -> Image.Image: + weight = alpha[..., None] + mixed = np.asarray(candidate, np.float32) * weight + np.asarray(render, np.float32) * (1.0 - weight) + return Image.fromarray(np.clip(mixed + 0.5, 0, 255).astype(np.uint8)) + + +class RateLimiter: + """Sliding one-hour window per key, in this process (one renderer worker per pod).""" + + def __init__(self, per_hour: int = GEMINI_ENHANCE_PER_HOUR): + self.per_hour = per_hour + self._hits: dict[str, deque[float]] = {} + self._lock = threading.Lock() + + def allow(self, key: str, now: float | None = None) -> bool: + now = time.monotonic() if now is None else now + with self._lock: + hits = self._hits.setdefault(key, deque()) + while hits and now - hits[0] > 3600: + hits.popleft() + if len(hits) >= self.per_hour: + return False + hits.append(now) + return True + + +rate_limiter = RateLimiter() + + +def enhance_render(render_bytes: bytes, surfaces: list[Surface], mask_bytes: bytes | None = None) -> Enhancement: + """Run the pass (blocking). Returns the image at the render's own size, or None when refused.""" + started = time.perf_counter() + timings: dict[str, int] = {} + render, sent = prepare_render(render_bytes) + masks = decode_mask(mask_bytes, render.size) if mask_bytes else None + region = editable_region(*masks) if masks else None + timings["prepareMs"] = round((time.perf_counter() - started) * 1000) + + images: list[tuple[bytes, str, str | None]] = [(sent, "image/jpeg", "The render to edit:")] + fetch_started = time.perf_counter() + for surface in surfaces[:MAX_SURFACES]: + reference = references.get(surface.image_url) if surface.image_url else None + if reference is not None: + images.append((reference, "image/jpeg", reference_caption(surface))) + timings["referencesMs"] = round((time.perf_counter() - fetch_started) * 1000) + + aspect = closest_aspect_ratio(*render.size) + best: tuple[float, Image.Image | None] = (-1.0, None) + attempts = 0 + for strict in (False, True): + attempts += 1 + call_started = time.perf_counter() + output, _mime = call_gemini_image( + images, + build_room_enhancement_prompt(surfaces, strict=strict), + aspect_ratio=aspect, + image_size=GEMINI_IMAGE_SIZE or None, + ) + timings[f"gemini{attempts}Ms"] = round((time.perf_counter() - call_started) * 1000) + candidate = _open_rgb(output).resize(render.size, Image.Resampling.LANCZOS) + if region is not None: + candidate = finish(render, candidate, region, masks[0]) + similarity = structure_similarity(render, candidate) + new_pattern = invented_pattern(render, candidate) + recoloured = recoloured_area(render, candidate) + accepted = (similarity >= GEMINI_MIN_SIMILARITY and new_pattern <= GEMINI_MAX_NEW_PATTERN + and recoloured <= GEMINI_MAX_RECOLOURED) + logger.info("[GEMINI_ENHANCE] attempt=%d similarity=%.3f newPattern=%.4f recoloured=%.3f accepted=%s", + attempts, similarity, new_pattern, recoloured, accepted) + if accepted: + best = (similarity, candidate) + break + best = max(best, (similarity, None), key=lambda item: item[0]) + + similarity, candidate = best + image = _jpeg(candidate, quality=92) if candidate is not None else None + timings["totalMs"] = round((time.perf_counter() - started) * 1000) + logger.info("[GEMINI_TIMING] %s accepted=%s", timings, image is not None) + return Enhancement(image=image, similarity=round(similarity, 3), attempts=attempts, timings_ms=timings) diff --git a/apps/renderer/services/gemini/prompt.py b/apps/renderer/services/gemini/prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..085dacf2d28a9e9d046a87e8ac330095cafd1cd6 --- /dev/null +++ b/apps/renderer/services/gemini/prompt.py @@ -0,0 +1,94 @@ +"""Gemini tile-refinement prompt construction.""" + + +def build_gemini_tile_refinement_prompt(tile_name: str | None = None) -> str: + tile_hint = f'\nTile/material label hint: "{tile_name}".' if tile_name else "" + return f"""You are performing a conservative photorealistic finishing pass on an interior tile visualizer render. + +Use the supplied image as the source of truth. The tile has already been selected, laid out, scaled, rotated, grouted, and composited by the renderer. + +Primary goal: +Make the already-applied tile surface look more naturally integrated into the room by refining missing realism: local reflections, gloss response, tiny contact shadows, ambient occlusion, edge blending, perspective-light consistency, color bleed, highlight rolloff, and surface micro-detail. + +Hard preservation rules: +- Do not replace, recreate, reinterpret, or redesign the tile. +- Do not change the tile pattern, print, veining, motif, color palette, layout, scale, grout spacing, grout color, rotation, perspective, or tile boundaries. +- Do not invent a different material, add new decorative features, or remove existing tile details. +- Do not alter furniture, walls, fixtures, objects, room architecture, camera angle, crop, image size, or composition. +- Do not smooth away the tile's existing texture or make repeated tiles look like a different product. +- If an improvement would require changing the tile design, leave that area unchanged. + +Allowed refinements only: +- Subtle physically plausible reflections and specular highlights that follow the existing room lighting. +- More natural shadowing where the tiled surface meets walls, cabinets, furniture legs, baseboards, or other occluding objects. +- Better blending at tile-mask edges while preserving the existing boundary. +- Gentle local contrast, roughness, and micro-surface detail so the tile feels photographed in the room. +- Correct small rendering artifacts, halos, missing reflection cues, or flat-looking areas without changing the design. + +Return only the refined image. Keep the same aspect ratio and composition. The result should look like the same rendered tile installation, just more realistic and finished.{tile_hint}""" + + +def _describe_surface(surface) -> str: + design = f'"{surface.tile_name}"' if surface.tile_name else "the applied design" + size = "" + if surface.width_mm and surface.height_mm: + width_cm, height_cm = surface.width_mm / 10, surface.height_mm / 10 + size = ( + f", a mural {width_cm:g} x {height_cm:g} cm hung from the top of the wall" if surface.mural + else f", one pattern repeat is {width_cm:g} x {height_cm:g} cm" + ) + material = "wallpaper" if surface.kind == "wall" else "tiles" + where = f" ({surface.position} of the image)" if getattr(surface, "position", None) else "" + return f"- {surface.name}{where}: {material} {design}{size}." + + +def reference_caption(surface) -> str: + """The text placed before a design's flat reference image.""" + return ( + f"Close-up of {surface.tile_name or 'a design'}, which is already on its wall in the render. Detail only: " + "it does not say where the design goes, and its flat, even light is not the room's light." + ) + + +def build_room_enhancement_prompt(surfaces, *, strict: bool = False) -> str: + """'Enhance with AI': relight and finish the render and fill wall gaps around furniture, never redesign it.""" + listed = "\n".join(_describe_surface(surface) for surface in surfaces) or "- The visible walls and floor." + has_walls = any(surface.kind == "wall" for surface in surfaces) or not surfaces + has_floor = any(surface.kind == "floor" for surface in surfaces) or not surfaces + gaps = ( + "\n1. Close the gaps the renderer missed. Where a papered wall still shows small patches of its old paint " + "colour along its edges, between or behind chairs, or under and beside cabinets and sideboards, continue " + "that same wall's own pattern into them, aligned with it at the same scale and perspective. A gap is a " + "small patch touching or surrounded by the design; a whole wall that the render left plain is not a gap." + if has_walls else "" + ) + wall_material = ( + "\n- Wallpaper is matte paper glued flat: a very fine paper texture, invisible seams, no gloss. A white or " + "pale ground is lit like the painted walls nearby, never pure white." + if has_walls else "" + ) + floor_material = ( + "\n- Tiles keep their grout lines; glazed tiles show soft, blurred reflections of windows and lights, " + "matte ones none." + if has_floor else "" + ) + strict_note = ( + "\nIMPORTANT: a previous answer moved a design, changed it, or papered a wall that is plain. Every wall " + "must keep exactly the design it has in the render; only the light and small gaps may change.\n" + if strict else "" + ) + return f"""Retouch the first image. It is a photo of a room in which a visualizer has already applied these products, at their real size and in correct perspective: +{listed} + +Where each design is in the render is final. Every wall and floor keeps exactly the design it shows now, in the same place, at the same size and alignment. Never move a design to another wall, swap designs between walls, or put a design on a wall, door, door frame, ceiling, window or piece of furniture that is plain in the render. + +Make it look like a real photograph of the products installed in this room:{gaps} +2. Light the products like the room. The design was pasted on evenly lit; give it the light the original surface had in this photo: brighter near windows and lamps, gently darker towards corners, the ceiling line and the floor, with the colour of daylight and warm lamp or cove light. Shadows cast by people, furniture and lamps fall across the design. Shade the design's colours, never repaint them. +3. Make it look installed: crisp, straight edges where the surface meets the ceiling, corners, skirting boards and frames, without halos; soft contact shadows where furniture and skirting meet it. +4. One photograph: the same white balance, contrast, sharpness and grain everywhere. + +Materials:{wall_material}{floor_material} + +Do not add, remove or change anything else: no new plants, decor, furniture, people or lights; doors, doorways and openings stay exactly as they are; the camera, crop and framing stay the same. No HDR look, extra saturation, vignette, blur, CGI finish, text or watermark. +{strict_note} +Return only the retouched image.""" diff --git a/apps/renderer/services/geometry/__init__.py b/apps/renderer/services/geometry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4dc8f9d479eea45cbbd3bb0be8f47a25fd9915f4 --- /dev/null +++ b/apps/renderer/services/geometry/__init__.py @@ -0,0 +1 @@ +# Geometry processing services: camera, normals, RANSAC, plane fitting, UV mapping. diff --git a/apps/renderer/services/geometry/camera.py b/apps/renderer/services/geometry/camera.py new file mode 100644 index 0000000000000000000000000000000000000000..9010f8c51ec0940d78bcbe79f3d244b1036f656c --- /dev/null +++ b/apps/renderer/services/geometry/camera.py @@ -0,0 +1,72 @@ +from __future__ import annotations + +import numpy as np + + +def default_camera_intrinsics(width: int, height: int) -> np.ndarray: + focal = float(max(height, width) * 0.95) + cx, cy = (width - 1) * 0.5, (height - 1) * 0.5 + return np.array([[focal, 0, cx], [0, focal, cy], [0, 0, 1]], dtype=np.float32) + + +def pixel_intrinsics_from_model( + intrinsics: np.ndarray | None, + width: int, + height: int, +) -> np.ndarray: + if intrinsics is None: + return default_camera_intrinsics(width, height) + + pixel_intrinsics = intrinsics.astype(np.float32).copy() + if abs(float(pixel_intrinsics[0, 0])) < 10: + pixel_intrinsics[0, 0] *= width + pixel_intrinsics[0, 2] *= width + pixel_intrinsics[1, 1] *= height + pixel_intrinsics[1, 2] *= height + return pixel_intrinsics + + +def prepare_depth_for_backprojection( + depth: np.ndarray, + mask: np.ndarray, + is_metric_depth: bool, +) -> tuple[np.ndarray, str]: + depth_float = depth.astype(np.float32).copy() + if is_metric_depth: + return depth_float, "metric" + + valid = (mask > 0) & np.isfinite(depth_float) + if valid.sum() < 1000: + return depth_float, "relative-raw" + + ys, xs = np.where(valid) + floor_depth = depth_float[ys, xs] + if floor_depth.size >= 1000: + corr = np.corrcoef(floor_depth, ys.astype(np.float32))[0, 1] + if np.isfinite(corr) and corr > 0: + depth_float = 1.0 - depth_float + floor_depth = depth_float[ys, xs] + + lo, hi = np.percentile(floor_depth[np.isfinite(floor_depth)], [2, 98]) + if hi - lo < 1e-6: + return depth_float, "relative-raw" + + normalized = np.clip((depth_float - lo) / (hi - lo), 0.0, 1.0) + return (0.8 + normalized * 3.2).astype(np.float32), "relative-normalized" + + +def backproject_depth( + depth: np.ndarray, + intrinsics: np.ndarray, +) -> np.ndarray: + h, w = depth.shape[:2] + yy, xx = np.mgrid[0:h, 0:w] + fx = max(float(intrinsics[0, 0]), 1e-6) + fy = max(float(intrinsics[1, 1]), 1e-6) + cx = float(intrinsics[0, 2]) + cy = float(intrinsics[1, 2]) + return np.dstack(( + (xx - cx) * depth / fx, + (yy - cy) * depth / fy, + depth, + )).astype(np.float32) diff --git a/apps/renderer/services/geometry/multi_plane.py b/apps/renderer/services/geometry/multi_plane.py new file mode 100644 index 0000000000000000000000000000000000000000..f1cdb0f5a925e5ed7127ad2ffdbba2a96ec226ae --- /dev/null +++ b/apps/renderer/services/geometry/multi_plane.py @@ -0,0 +1,201 @@ +from __future__ import annotations + +import numpy as np + +from enums import PlaneFitMode +from config.models import DEPTH_MODEL_NAME +from config.runtime import ENABLE_MULTI_PLANE_SURFACES +from config.surface import ( + SURFACE_MAX_PLANES, + SURFACE_MIN_PLANE_PIXELS, + SURFACE_NORMAL_ANGLE_DEGREES, + SURFACE_NORMAL_SMOOTHING_KERNEL, + SURFACE_RANSAC_DISTANCE, +) +from services.geometry.camera import ( + backproject_depth, + pixel_intrinsics_from_model, + prepare_depth_for_backprojection, +) +from services.geometry.normals import compute_normals_from_points, smooth_normal_map +from services.geometry.plane_fitting import plane_basis, surface_distance_threshold +from services.geometry.ransac import ransac_surface_plane, ransac_surface_plane_by_distance + + +MIN_SECONDARY_PLANE_RATIO = 0.05 + + +def _prune_weak_secondary_planes(planes: list[dict]) -> list[dict]: + if not planes: + return [] + + primary_inliers = max(plane["inlierCount"] for plane in planes) + retained_planes = [ + plane + for plane in planes + if plane["inlierCount"] >= primary_inliers * MIN_SECONDARY_PLANE_RATIO + ] + for plane_id, plane in enumerate(retained_planes): + plane["id"] = plane_id + return retained_planes + + +def geometry_point_maps(mask: np.ndarray, geometry: dict | None): + if not ENABLE_MULTI_PLANE_SURFACES or geometry is None: + return None + + h, w = mask.shape[:2] + points = geometry.get("points") + point_source = "raw-point-map" + valid_mask = geometry.get("validMask") + intrinsics = geometry.get("intrinsics") + depth_scale = None + + if points is None: + depth = geometry.get("depth") + if depth is None: + return None + provider = geometry.get("provider", "") + is_metric_depth = "metric" in DEPTH_MODEL_NAME.lower() or "metric" in provider.lower() + depth_for_points, depth_scale = prepare_depth_for_backprojection(depth, mask, is_metric_depth) + pixel_intrinsics = pixel_intrinsics_from_model(intrinsics, w, h) + points = backproject_depth(depth_for_points, pixel_intrinsics) + valid_mask = np.isfinite(depth_for_points) & (depth_for_points > 0.05) + point_source = f"{provider or 'depth'}-backprojection" + else: + points = points.astype(np.float32, copy=False) + pixel_intrinsics = pixel_intrinsics_from_model(intrinsics, w, h) + if valid_mask is None: + valid_mask = np.isfinite(points).all(axis=2) & (points[:, :, 2] > 0.05) + + valid_mask = valid_mask.astype(bool, copy=False) & np.isfinite(points).all(axis=2) & (points[:, :, 2] > 0.05) + print( + "[FLOOR_3D_POINTS] point map ready for floor mapping " + f"source={point_source} provider={geometry.get('provider')} shape={points.shape} " + f"validPixels={int(valid_mask.sum())} floorMaskPixels={int(mask.sum())}", + flush=True, + ) + normals = geometry.get("normals") + if normals is None or normals.shape[:2] != mask.shape: + normals = compute_normals_from_points(points, valid_mask, SURFACE_NORMAL_SMOOTHING_KERNEL) + else: + normals = smooth_normal_map(normals.astype(np.float32, copy=False), SURFACE_NORMAL_SMOOTHING_KERNEL) + normal_valid_mask = np.isfinite(normals).all(axis=2) & (np.linalg.norm(normals, axis=2) > 1e-4) + + return { + "points": points.astype(np.float32, copy=False), + "normals": normals.astype(np.float32, copy=False), + "normalValidMask": normal_valid_mask, + "validMask": valid_mask, + "intrinsics": pixel_intrinsics.astype(np.float32), + "depthScale": depth_scale, + } + + +def fit_multi_surface_planes( + points: np.ndarray, + normals: np.ndarray, + normals_reliable: bool = True, + max_planes: int | None = None, +): + """Sequential RANSAC plane fitting. + + max_planes defaults to SURFACE_MAX_PLANES (the floor's budget); walls pass + WALL_MAX_PLANES so they can split into several planes without changing + how the floor is fitted. + """ + plane_budget = SURFACE_MAX_PLANES if max_planes is None else max(1, int(max_planes)) + if len(points) < SURFACE_MIN_PLANE_PIXELS: + return [] + + distance_threshold = surface_distance_threshold(points) + normal_cos = float(np.cos(np.deg2rad(SURFACE_NORMAL_ANGLE_DEGREES))) + rng = np.random.default_rng(29) + sample_count = min(len(points), 26000) + sample_indices = rng.choice(len(points), size=sample_count, replace=False) + remaining = np.ones(len(points), dtype=bool) + planes = [] + + for plane_id in range(plane_budget): + candidates = sample_indices[remaining[sample_indices]] + if len(candidates) < max(300, SURFACE_MIN_PLANE_PIXELS // 6): + break + fit_mode = PlaneFitMode.NORMAL_AWARE + result = None + if normals_reliable: + result = ransac_surface_plane( + points, + normals, + candidates, + remaining, + distance_threshold, + normal_cos, + ) + if result is None: + fit_mode = "distance-only" + result = ransac_surface_plane_by_distance( + points, + candidates, + remaining, + distance_threshold, + ) + if result is None: + break + origin, normal, inliers = result + inlier_count = int(inliers.sum()) + if inlier_count < SURFACE_MIN_PLANE_PIXELS: + break + planes.append({ + "id": plane_id, + "origin": origin.astype(np.float32), + "normal": normal.astype(np.float32), + "offset": float(-origin @ normal), + "inlierCount": inlier_count, + "fitMode": fit_mode, + }) + remaining[inliers] = False + if int(remaining.sum()) < SURFACE_MIN_PLANE_PIXELS: + break + + if not planes: + return [] + + planes = _prune_weak_secondary_planes(planes) + + floor_id = int(np.argmax([ + plane["inlierCount"] * max(0.1, abs(float(plane["normal"][1]))) + for plane in planes + ])) + for idx, plane in enumerate(planes): + plane["isFloor"] = idx == floor_id + u_axis, v_axis = plane_basis(plane["normal"], plane["isFloor"]) + plane["uAxis"] = u_axis + plane["vAxis"] = v_axis + return planes + + +def assign_points_to_surface_planes( + points: np.ndarray, + normals: np.ndarray, + planes: list[dict], + normals_reliable: bool = True, +): + plane_normals = np.asarray([plane["normal"] for plane in planes], dtype=np.float32) + plane_origins = np.asarray([plane["origin"] for plane in planes], dtype=np.float32) + offsets = -np.sum(plane_normals * plane_origins, axis=1) + distances = np.abs(points @ plane_normals.T + offsets[None, :]) + if not normals_reliable: + return np.argmin(distances, axis=1).astype(np.int32) + + alignments = np.abs(normals @ plane_normals.T) + normal_cos = float(np.cos(np.deg2rad(SURFACE_NORMAL_ANGLE_DEGREES))) + distance_threshold = float(SURFACE_RANSAC_DISTANCE) * 1.5 + denom = max(1.0 - normal_cos, 1e-3) + score = distances / max(distance_threshold, 1e-6) + (1.0 - alignments) / denom + ok = (distances <= distance_threshold) & (alignments >= normal_cos) + score[~ok] = np.inf + assignment = np.argmin(score, axis=1).astype(np.int32) + has_match = np.isfinite(score[np.arange(len(points)), assignment]) + if not has_match.all(): + assignment[~has_match] = np.argmin(distances[~has_match], axis=1).astype(np.int32) + return assignment diff --git a/apps/renderer/services/geometry/normals.py b/apps/renderer/services/geometry/normals.py new file mode 100644 index 0000000000000000000000000000000000000000..e81b8b4038dfb1a1794344a17ef5aaa91ca4a386 --- /dev/null +++ b/apps/renderer/services/geometry/normals.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +import cv2 +import numpy as np + + +def normalize_vectors(vectors: np.ndarray) -> np.ndarray: + out = np.zeros_like(vectors, dtype=np.float32) + lengths = np.linalg.norm(vectors, axis=-1) + good = np.isfinite(vectors).all(axis=-1) & (lengths > 1e-6) + out[good] = vectors[good] / lengths[good, None] + return out + + +def smooth_normal_map(normals: np.ndarray, kernel_size: int) -> np.ndarray: + kernel_size = max(1, int(kernel_size)) | 1 + smoothed = normals.astype(np.float32) + if kernel_size > 1: + smoothed = cv2.GaussianBlur(smoothed, (kernel_size, kernel_size), 0) + return normalize_vectors(smoothed) + + +def compute_normals_from_points( + points_map: np.ndarray, + valid_mask: np.ndarray, + smoothing_kernel: int, +) -> np.ndarray: + points = points_map.astype(np.float32).copy() + valid = valid_mask.astype(bool) & np.isfinite(points).all(axis=2) + if not valid.any(): + return np.zeros_like(points, dtype=np.float32) + + filled = points.copy() + for channel_idx in range(3): + channel = filled[:, :, channel_idx] + fill_value = float(np.median(channel[valid])) + channel[~valid] = fill_value + filled[:, :, channel_idx] = channel + + kernel_size = max(1, int(smoothing_kernel)) | 1 + if kernel_size > 1: + filled = cv2.GaussianBlur(filled, (kernel_size, kernel_size), 0) + + dx = np.zeros_like(filled, dtype=np.float32) + dy = np.zeros_like(filled, dtype=np.float32) + dx[:, 1:-1] = filled[:, 2:] - filled[:, :-2] + dx[:, 0] = filled[:, 1] - filled[:, 0] + dx[:, -1] = filled[:, -1] - filled[:, -2] + dy[1:-1, :] = filled[2:, :] - filled[:-2, :] + dy[0, :] = filled[1, :] - filled[0, :] + dy[-1, :] = filled[-1, :] - filled[-2, :] + + normals = normalize_vectors(np.cross(dx, dy)) + normals[~valid] = 0.0 + return smooth_normal_map(normals, smoothing_kernel) diff --git a/apps/renderer/services/geometry/plane_fitting.py b/apps/renderer/services/geometry/plane_fitting.py new file mode 100644 index 0000000000000000000000000000000000000000..046e6763332d81140a63a5d2d1e0d24b24b0b0b0 --- /dev/null +++ b/apps/renderer/services/geometry/plane_fitting.py @@ -0,0 +1,225 @@ +from __future__ import annotations + +import cv2 +import numpy as np + +from enums import GeometryProvider, PlaneFitMode +from config.surface import SURFACE_RANSAC_DISTANCE +from services.geometry.camera import ( + backproject_depth, + pixel_intrinsics_from_model, + prepare_depth_for_backprojection, +) + + +def project_points_to_plane(points: np.ndarray, origin: np.ndarray, normal: np.ndarray): + normal = normal.astype(np.float32) + normal /= max(float(np.linalg.norm(normal)), 1e-6) + signed_distance = (points - origin) @ normal + projected = points - signed_distance[:, None] * normal + return projected.astype(np.float32), signed_distance.astype(np.float32) + + +def refine_plane(points: np.ndarray, normals: np.ndarray | None = None): + centroid = np.median(points, axis=0).astype(np.float32) + _, _, vh = np.linalg.svd(points - centroid, full_matrices=False) + normal = vh[-1].astype(np.float32) + normal /= max(float(np.linalg.norm(normal)), 1e-6) + if normals is not None and len(normals): + reference = np.median(normals, axis=0).astype(np.float32) + if float(np.linalg.norm(reference)) > 1e-6 and float(normal @ reference) < 0: + normal = -normal + elif normal[1] < 0: + normal = -normal + return centroid, normal + + +def plane_basis(normal: np.ndarray, is_floor: bool): + normal = normal.astype(np.float32) + normal /= max(float(np.linalg.norm(normal)), 1e-6) + if is_floor: + ref = np.array([1.0, 0.0, 0.0], dtype=np.float32) + u_axis = ref - normal * float(ref @ normal) + if float(np.linalg.norm(u_axis)) < 1e-5: + ref = np.array([0.0, 0.0, 1.0], dtype=np.float32) + u_axis = ref - normal * float(ref @ normal) + u_axis /= max(float(np.linalg.norm(u_axis)), 1e-6) + v_axis = np.cross(normal, u_axis) + else: + vertical_ref = np.array([0.0, 1.0, 0.0], dtype=np.float32) + v_axis = vertical_ref - normal * float(vertical_ref @ normal) + if float(np.linalg.norm(v_axis)) < 1e-5: + vertical_ref = np.array([0.0, 0.0, 1.0], dtype=np.float32) + v_axis = vertical_ref - normal * float(vertical_ref @ normal) + v_axis /= max(float(np.linalg.norm(v_axis)), 1e-6) + u_axis = np.cross(v_axis, normal) + u_axis /= max(float(np.linalg.norm(u_axis)), 1e-6) + v_axis /= max(float(np.linalg.norm(v_axis)), 1e-6) + return u_axis.astype(np.float32), v_axis.astype(np.float32) + + +def surface_distance_threshold(points: np.ndarray) -> float: + span = np.percentile(points, 95, axis=0) - np.percentile(points, 5, axis=0) + adaptive = max(0.025, float(np.linalg.norm(span)) * 0.012) + return float(np.clip(max(float(SURFACE_RANSAC_DISTANCE), adaptive), 0.025, 0.20)) + + +def fit_metric_floor_transform( + mask: np.ndarray, + points_map: np.ndarray, + valid_mask: np.ndarray | None = None, + normals_map: np.ndarray | None = None, + intrinsics: np.ndarray | None = None, + provider: str = GeometryProvider.METRIC_DEPTH, + surface_kind: str = "floor", +): + # Import here to avoid circular dependency with ransac module + from services.geometry.ransac import ransac_plane_fit + + h, w = mask.shape[:2] + valid = (mask > 0) & np.isfinite(points_map).all(axis=2) & (points_map[:, :, 2] > 0.05) + if valid_mask is not None: + valid &= valid_mask.astype(bool) + ys, xs = np.where(valid) + if len(xs) < 2000: + return None + + stride = max(1, len(xs) // 18000) + xs = xs[::stride] + ys = ys[::stride] + points = points_map[ys, xs].astype(np.float32) + + normal_consistency = 1.0 + if normals_map is not None and normals_map.shape[:2] == mask.shape: + sample_normals = normals_map[ys, xs].astype(np.float32) + lengths = np.linalg.norm(sample_normals, axis=1) + good_normals = np.isfinite(sample_normals).all(axis=1) & (lengths > 1e-4) + sample_normals[good_normals] /= lengths[good_normals, None] + if good_normals.sum() >= 1000: + reference = np.median(sample_normals[good_normals], axis=0) + reference /= max(float(np.linalg.norm(reference)), 1e-6) + aligned = np.abs(sample_normals @ reference) + normal_keep = good_normals & (aligned >= np.cos(np.deg2rad(30))) + normal_consistency = float(normal_keep.mean()) + if normal_keep.sum() >= 1000: + points = points[normal_keep] + xs = xs[normal_keep] + ys = ys[normal_keep] + + ransac_fit = ransac_plane_fit(points) + if ransac_fit is not None: + centroid, normal, keep = ransac_fit + else: + keep = np.ones(len(points), dtype=bool) + normal = np.array([0.0, 1.0, 0.0], dtype=np.float32) + centroid = np.median(points, axis=0) + for _ in range(4): + fit_points = points[keep] + if len(fit_points) < 1000: + return None + centroid = np.median(fit_points, axis=0) + _, _, vh = np.linalg.svd(fit_points - centroid, full_matrices=False) + normal = vh[-1].astype(np.float32) + distances = np.abs((points - centroid) @ normal) + threshold = max(0.025, float(np.percentile(distances[keep], 70)) * 1.8) + keep = distances <= threshold + + if normal[1] < 0: + normal = -normal + inlier_ratio = float(keep.mean()) + residual = float(np.median(np.abs((points[keep] - centroid) @ normal))) + if inlier_ratio < 0.45 or residual > 0.18: + return None + + # Use local horizontal/vertical axes for walls and horizontal/depth axes + # for floors. This keeps physical tile dimensions stable across surfaces. + u_axis, v_axis = plane_basis(normal, is_floor=surface_kind != "wall") + + projected_points, _ = project_points_to_plane(points[keep], centroid, normal) + floor_points = projected_points - centroid + uv = np.column_stack((floor_points @ u_axis, floor_points @ v_axis)).astype(np.float32) + uv_min = np.min(uv, axis=0) + uv_max = np.max(uv, axis=0) + image_points = np.column_stack((xs[keep], ys[keep])).astype(np.float32) + transform, ransac_mask = cv2.findHomography( + image_points, + uv, + method=cv2.RANSAC, + ransacReprojThreshold=0.08, + maxIters=3000, + confidence=0.995, + ) + if transform is None: + return None + + homography_inliers = float(ransac_mask.mean()) if ransac_mask is not None else 0.0 + confidence = float(np.clip( + 0.55 * inlier_ratio + + 0.30 * homography_inliers + + 0.15 * normal_consistency + - min(residual / 0.18, 1.0) * 0.25, + 0.0, + 1.0, + )) + pixel_intrinsics = ( + pixel_intrinsics_from_model(intrinsics, w, h) + if intrinsics is not None + else None + ) + + return { + "floorTransform": transform.flatten().tolist(), + "surfaceTransform": transform.flatten().tolist(), + "surfaceType": surface_kind, + "surfaceUAxis": u_axis.tolist(), + "surfaceVAxis": v_axis.tolist(), + "surfaceWidthMeters": float(max(uv_max[0] - uv_min[0], 0.05)), + "surfaceHeightMeters": float(max(uv_max[1] - uv_min[1], 0.05)), + "metersPerUnit": 1.0, + "geometryConfidence": confidence, + "geometryProvider": provider, + "cameraIntrinsics": pixel_intrinsics.flatten().tolist() if pixel_intrinsics is not None else None, + "camera": { + "focalLength": ( + float(pixel_intrinsics[0, 0]) + if pixel_intrinsics is not None + else float(max(h, w) * 0.95) + ), + "confidence": confidence, + }, + "planeNormal": normal.tolist(), + "planeOrigin": centroid.tolist(), + "fitResidualMeters": residual, + "fitInlierRatio": inlier_ratio, + "normalConsistency": normal_consistency, + "planeFit": PlaneFitMode.RANSAC, + } + + +def estimate_metric_floor_transform( + mask: np.ndarray, + depth: np.ndarray | None, + provider: str = GeometryProvider.DEPTH_ANYTHING, + intrinsics: np.ndarray | None = None, + surface_kind: str = "floor", +): + from config.models import DEPTH_MODEL_NAME + from config.runtime import ENABLE_PLANE_FIT + + if depth is None or not ENABLE_PLANE_FIT: + return None + h, w = mask.shape[:2] + is_metric_depth = "metric" in DEPTH_MODEL_NAME.lower() or "metric" in provider.lower() + depth_for_points, depth_scale = prepare_depth_for_backprojection(depth, mask, is_metric_depth) + pixel_intrinsics = pixel_intrinsics_from_model(intrinsics, w, h) + points = backproject_depth(depth_for_points, pixel_intrinsics) + result = fit_metric_floor_transform( + mask, + points, + intrinsics=pixel_intrinsics, + provider=provider, + surface_kind=surface_kind, + ) + if result is not None: + result["depthScale"] = depth_scale + return result diff --git a/apps/renderer/services/geometry/plane_uv.py b/apps/renderer/services/geometry/plane_uv.py new file mode 100644 index 0000000000000000000000000000000000000000..88274fcddad4139d4b156efef11439ab294479b6 --- /dev/null +++ b/apps/renderer/services/geometry/plane_uv.py @@ -0,0 +1,105 @@ +"""Analytic UV mapping for a fitted plane. + +Functions +--------- +upright_plane_basis - in-plane (u, v) axes with v aligned to a given "up" direction +ray_plane_uv - UV of pixels by intersecting camera rays with a plane +plane_to_image_transform - exact 3x3 pixel -> plane-UV homography for a plane +""" + +from __future__ import annotations + +import numpy as np + +# Hits farther than this (metres) are near-horizon rays and are rejected. +MAX_RAY_DISTANCE_METERS = 100.0 + + +def upright_plane_basis(normal: np.ndarray, up: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Return unit (u, v) axes spanning the plane, with v following `up`. + + For walls `up` is the floor normal, so textures stay upright even when the + camera is tilted. Falls back to the camera's +Y axis when `up` is (nearly) + parallel to the plane normal. + """ + normal = np.asarray(normal, dtype=np.float32) + normal = normal / max(float(np.linalg.norm(normal)), 1e-6) + for reference in (np.asarray(up, dtype=np.float32), np.array([0.0, 1.0, 0.0], dtype=np.float32)): + v_axis = reference - normal * float(reference @ normal) + length = float(np.linalg.norm(v_axis)) + if length > 1e-4: + v_axis = v_axis / length + u_axis = np.cross(v_axis, normal) + u_axis = u_axis / max(float(np.linalg.norm(u_axis)), 1e-6) + return u_axis.astype(np.float32), v_axis.astype(np.float32) + raise ValueError("Cannot build a plane basis: normal is degenerate.") + + +def ray_plane_uv( + flat_indices: np.ndarray, + image_width: int, + intrinsics: np.ndarray, + origin: np.ndarray, + normal: np.ndarray, + u_axis: np.ndarray, + v_axis: np.ndarray, +) -> tuple[np.ndarray, np.ndarray]: + """UV (metres, relative to `origin`) where each pixel's camera ray meets the plane. + + Uses the pinhole convention of services.geometry.camera.backproject_depth, + so results agree with depth-derived 3D points. Returns (uv, hit): uv is + float32 (N, 2) with NaN where the ray misses the plane in front of the + camera, and hit is the matching boolean mask. + """ + flat = np.asarray(flat_indices, dtype=np.int64) + xs = (flat % image_width).astype(np.float32) + ys = (flat // image_width).astype(np.float32) + fx = max(float(intrinsics[0, 0]), 1e-6) + fy = max(float(intrinsics[1, 1]), 1e-6) + rays = np.column_stack(( + (xs - float(intrinsics[0, 2])) / fx, + (ys - float(intrinsics[1, 2])) / fy, + np.ones_like(xs), + )) + + normal = np.asarray(normal, dtype=np.float32) + origin = np.asarray(origin, dtype=np.float32) + denom = rays @ normal + with np.errstate(divide="ignore", invalid="ignore"): + distance = np.where(np.abs(denom) > 1e-6, float(origin @ normal) / denom, np.nan) + hit = np.isfinite(distance) & (distance > 0) & (distance < MAX_RAY_DISTANCE_METERS) + + uv = np.full((len(flat), 2), np.nan, dtype=np.float32) + if hit.any(): + delta = rays[hit] * distance[hit, None] - origin + uv[hit, 0] = delta @ np.asarray(u_axis, dtype=np.float32) + uv[hit, 1] = delta @ np.asarray(v_axis, dtype=np.float32) + return uv, hit + + +def plane_to_image_transform( + intrinsics: np.ndarray, + origin: np.ndarray, + normal: np.ndarray, + u_axis: np.ndarray, + v_axis: np.ndarray, +) -> np.ndarray: + """3x3 homography H with (u, v, w) = H @ (x, y, 1) giving the same UV as ray_plane_uv. + + Intersecting ray r with the plane gives u = [(n.o)(u.r) - (o.u)(n.r)] / (n.r), + and likewise for v, which is projective in r and so in the pixel. A flat + wall therefore needs 9 numbers instead of a per-pixel UV array. Same + row-major, integer-pixel convention as fit_metric_floor_transform. + """ + normal = np.asarray(normal, dtype=np.float64) + origin = np.asarray(origin, dtype=np.float64) + u_axis = np.asarray(u_axis, dtype=np.float64) + v_axis = np.asarray(v_axis, dtype=np.float64) + offset = float(normal @ origin) + ray_to_uv = np.vstack(( + offset * u_axis - float(origin @ u_axis) * normal, + offset * v_axis - float(origin @ v_axis) * normal, + normal, + )) + transform = ray_to_uv @ np.linalg.inv(np.asarray(intrinsics, dtype=np.float64)) + return transform / transform[2, 2] if abs(transform[2, 2]) > 1e-12 else transform diff --git a/apps/renderer/services/geometry/ransac.py b/apps/renderer/services/geometry/ransac.py new file mode 100644 index 0000000000000000000000000000000000000000..d02b24dd8df7c23dcfef0f5800f563f8d771e8bf --- /dev/null +++ b/apps/renderer/services/geometry/ransac.py @@ -0,0 +1,200 @@ +from __future__ import annotations + +import numpy as np + +from config.surface import SURFACE_MIN_PLANE_PIXELS +from services.geometry.plane_fitting import refine_plane + +_HYPOTHESIS_BATCH_SIZE = 32 + + +def _candidate_hypotheses( + candidate_points: np.ndarray, + *, + iterations: int, + rng: np.random.Generator, +) -> tuple[np.ndarray, np.ndarray]: + """Generate the same deterministic RANSAC hypotheses without scoring each one separately.""" + origins = [] + normals = [] + for _ in range(iterations): + local = rng.choice(len(candidate_points), size=3, replace=False) + p0, p1, p2 = candidate_points[local] + normal = np.cross(p1 - p0, p2 - p0).astype(np.float32) + length = float(np.linalg.norm(normal)) + if length < 1e-6: + continue + origins.append(p0) + normals.append(normal / length) + if not origins: + return np.empty((0, 3), dtype=np.float32), np.empty((0, 3), dtype=np.float32) + return np.asarray(origins, dtype=np.float32), np.asarray(normals, dtype=np.float32) + + +def _best_surface_hypothesis( + candidate_points: np.ndarray, + origins: np.ndarray, + normals: np.ndarray, + distance_threshold: float, + *, + candidate_normals: np.ndarray | None = None, + normal_cos: float | None = None, +) -> tuple[np.ndarray, np.ndarray] | None: + """Score RANSAC hypotheses in bounded batches to avoid hundreds of tiny NumPy calls.""" + best_count = 0 + best_index = -1 + for start in range(0, len(origins), _HYPOTHESIS_BATCH_SIZE): + stop = min(start + _HYPOTHESIS_BATCH_SIZE, len(origins)) + batch_normals = normals[start:stop] + batch_origins = origins[start:stop] + offsets = np.sum(batch_origins * batch_normals, axis=1) + distances = np.abs(candidate_points @ batch_normals.T - offsets[None, :]) + accepted = distances <= distance_threshold + if candidate_normals is not None and normal_cos is not None: + alignments = np.abs(candidate_normals @ batch_normals.T) + accepted &= alignments >= normal_cos + counts = accepted.sum(axis=0) + local_index = int(np.argmax(counts)) + local_count = int(counts[local_index]) + if local_count > best_count: + best_count = local_count + best_index = start + local_index + if best_index < 0: + return None + return origins[best_index], normals[best_index] + + +def ransac_plane_fit(points: np.ndarray): + if len(points) < 1000: + return None + + rng = np.random.default_rng(17) + span = np.percentile(points, 95, axis=0) - np.percentile(points, 5, axis=0) + threshold = max(0.025, float(np.linalg.norm(span)) * 0.012) + best_keep = None + best_count = 0 + best_normal = None + best_centroid = None + iterations = min(160, max(48, len(points) // 120)) + + for _ in range(iterations): + sample_idx = rng.choice(len(points), size=3, replace=False) + p0, p1, p2 = points[sample_idx] + normal = np.cross(p1 - p0, p2 - p0).astype(np.float32) + length = float(np.linalg.norm(normal)) + if length < 1e-6: + continue + normal /= length + distances = np.abs((points - p0) @ normal) + keep = distances <= threshold + count = int(keep.sum()) + if count > best_count: + best_keep = keep + best_count = count + best_normal = normal + best_centroid = p0.astype(np.float32) + + if best_keep is None or best_count < 1000: + return None + return best_centroid, best_normal, best_keep + + +def ransac_surface_plane( + points: np.ndarray, + normals: np.ndarray, + candidate_indices: np.ndarray, + remaining: np.ndarray, + distance_threshold: float, + normal_cos: float, +): + if len(candidate_indices) < 3: + return None + + rng = np.random.default_rng(41) + candidate_points = points[candidate_indices] + candidate_normals = normals[candidate_indices] + relaxed_cos = max(0.0, normal_cos - 0.15) + origins, hypothesis_normals = _candidate_hypotheses( + candidate_points, + iterations=220, + rng=rng, + ) + best = _best_surface_hypothesis( + candidate_points, + origins, + hypothesis_normals, + distance_threshold, + candidate_normals=candidate_normals, + normal_cos=relaxed_cos, + ) + if best is None: + return None + best_origin, best_normal = best + + distances = np.abs((points - best_origin) @ best_normal) + align = np.abs(normals @ best_normal) + inliers = remaining & (distances <= distance_threshold) & (align >= relaxed_cos) + if int(inliers.sum()) < SURFACE_MIN_PLANE_PIXELS: + return None + + refine_idx = np.flatnonzero(inliers) + if len(refine_idx) > 50000: + refine_idx = refine_idx[:: max(1, len(refine_idx) // 50000)] + origin, normal = refine_plane(points[refine_idx], normals[refine_idx]) + distances = np.abs((points - origin) @ normal) + align = np.abs(normals @ normal) + inliers = remaining & (distances <= distance_threshold) & (align >= normal_cos) + if int(inliers.sum()) < SURFACE_MIN_PLANE_PIXELS: + return None + final_idx = np.flatnonzero(inliers) + if len(final_idx) > 50000: + final_idx = final_idx[:: max(1, len(final_idx) // 50000)] + origin, normal = refine_plane(points[final_idx], normals[final_idx]) + return origin, normal, inliers + + +def ransac_surface_plane_by_distance( + points: np.ndarray, + candidate_indices: np.ndarray, + remaining: np.ndarray, + distance_threshold: float, +): + if len(candidate_indices) < 3: + return None + + rng = np.random.default_rng(53) + candidate_points = points[candidate_indices] + origins, hypothesis_normals = _candidate_hypotheses( + candidate_points, + iterations=260, + rng=rng, + ) + best = _best_surface_hypothesis( + candidate_points, + origins, + hypothesis_normals, + distance_threshold, + ) + if best is None: + return None + best_origin, best_normal = best + + distances = np.abs((points - best_origin) @ best_normal) + inliers = remaining & (distances <= distance_threshold) + if int(inliers.sum()) < SURFACE_MIN_PLANE_PIXELS: + return None + + refine_idx = np.flatnonzero(inliers) + if len(refine_idx) > 50000: + refine_idx = refine_idx[:: max(1, len(refine_idx) // 50000)] + origin, normal = refine_plane(points[refine_idx], None) + distances = np.abs((points - origin) @ normal) + inliers = remaining & (distances <= distance_threshold * 1.25) + if int(inliers.sum()) < SURFACE_MIN_PLANE_PIXELS: + return None + + final_idx = np.flatnonzero(inliers) + if len(final_idx) > 50000: + final_idx = final_idx[:: max(1, len(final_idx) // 50000)] + origin, normal = refine_plane(points[final_idx], None) + return origin, normal, inliers diff --git a/apps/renderer/services/geometry/uv_mapping.py b/apps/renderer/services/geometry/uv_mapping.py new file mode 100644 index 0000000000000000000000000000000000000000..e7499b77e4a3e7eb310325619bc7dbcc2b69bc24 --- /dev/null +++ b/apps/renderer/services/geometry/uv_mapping.py @@ -0,0 +1,376 @@ +from __future__ import annotations + +import time + +import cv2 +import numpy as np + +from enums import TextureMappingMode, TextureMappingReason, PlaneFitMode +from config.surface import ( + SURFACE_MIN_PLANE_PIXELS, + SURFACE_PLANE_DISTANCE_METERS, + SURFACE_RANSAC_DISTANCE, + SURFACE_UV_ABSOLUTE_JUMP_METERS, + SURFACE_UV_MAX_BAD_NEIGHBOR_RATIO, + SURFACE_UV_MAX_JUMP_RATIO, + SURFACE_UV_EDGE_BAND_RATIO, + SURFACE_UV_MIN_COVERAGE, +) +from config.runtime import ENABLE_MULTI_PLANE_SURFACES +from services.geometry.multi_plane import ( + assign_points_to_surface_planes, + fit_multi_surface_planes, + geometry_point_maps, +) +from services.geometry.plane_fitting import project_points_to_plane, surface_distance_threshold +from services.geometry.plane_uv import ray_plane_uv + + +def analyze_surface_uv_quality( + surface_mask: np.ndarray, + surface_indices: np.ndarray, + uv_by_mask: np.ndarray, + plane_ids: np.ndarray, +) -> dict: + total_pixels = int(len(surface_indices)) + finite_uv = np.isfinite(uv_by_mask).all(axis=1) if total_pixels else np.zeros(0, dtype=bool) + finite_pixels = int(finite_uv.sum()) + coverage = float(finite_pixels / max(total_pixels, 1)) + active_plane_ids = sorted({ + int(plane_id) + for plane_id in np.unique(plane_ids[finite_uv]) + if int(plane_id) != 255 + }) + + quality = { + "surfaceUvEnabled": False, + "textureMappingMode": TextureMappingMode.REGULARIZED_FLOOR_PLANE, + "textureMappingReason": TextureMappingReason.SURFACE_UV_UNAVAILABLE, + "surfaceUvCoverage": coverage, + "surfaceUvFinitePixels": finite_pixels, + "surfaceUvTotalPixels": total_pixels, + "surfaceUvNeighborCount": 0, + "surfaceUvMedianNeighborDelta": None, + "surfaceUvP95NeighborDelta": None, + "surfaceUvP99NeighborDelta": None, + "surfaceUvJumpLimit": None, + "surfaceUvBadNeighborRatio": None, + "surfaceUvPlaneBoundaryRatio": None, + "surfaceUvAssignedPlaneCount": len(active_plane_ids), + } + + if total_pixels == 0: + quality["textureMappingReason"] = TextureMappingReason.EMPTY_SURFACE + return quality + if coverage < SURFACE_UV_MIN_COVERAGE: + quality["textureMappingReason"] = TextureMappingReason.INCOMPLETE_SURFACE_UV + return quality + h, w = surface_mask.shape[:2] + uv_grid = np.full((h * w, 2), np.nan, dtype=np.float32) + plane_grid = np.full(h * w, 255, dtype=np.uint8) + uv_grid[surface_indices[finite_uv]] = uv_by_mask[finite_uv] + plane_grid[surface_indices[finite_uv]] = plane_ids[finite_uv] + uv_grid = uv_grid.reshape(h, w, 2) + plane_grid = plane_grid.reshape(h, w) + finite_grid = np.isfinite(uv_grid).all(axis=2) + surface_bool = surface_mask.astype(bool) + + right = surface_bool[:, :-1] & surface_bool[:, 1:] & finite_grid[:, :-1] & finite_grid[:, 1:] + down = surface_bool[:-1, :] & surface_bool[1:, :] & finite_grid[:-1, :] & finite_grid[1:, :] + right_plane_boundary = right & (plane_grid[:, :-1] != plane_grid[:, 1:]) + down_plane_boundary = down & (plane_grid[:-1, :] != plane_grid[1:, :]) + same_right = right & ~right_plane_boundary + same_down = down & ~down_plane_boundary + + deltas = [] + if same_right.any(): + deltas.append(np.linalg.norm(uv_grid[:, 1:][same_right] - uv_grid[:, :-1][same_right], axis=1)) + if same_down.any(): + deltas.append(np.linalg.norm(uv_grid[1:, :][same_down] - uv_grid[:-1, :][same_down], axis=1)) + + neighbor_count = int(right.sum() + down.sum()) + plane_boundary_count = int(right_plane_boundary.sum() + down_plane_boundary.sum()) + quality["surfaceUvNeighborCount"] = neighbor_count + quality["surfaceUvPlaneBoundaryRatio"] = float(plane_boundary_count / max(neighbor_count, 1)) + + if not deltas: + quality["textureMappingReason"] = TextureMappingReason.INSUFFICIENT_UV_NEIGHBORS + return quality + + all_deltas = np.concatenate(deltas).astype(np.float32) + median_delta = float(np.median(all_deltas)) + p95_delta = float(np.percentile(all_deltas, 95)) + p99_delta = float(np.percentile(all_deltas, 99)) + jump_limit = max(SURFACE_UV_ABSOLUTE_JUMP_METERS, median_delta * SURFACE_UV_MAX_JUMP_RATIO) + bad_ratio = float((all_deltas > jump_limit).mean()) + + quality.update({ + "surfaceUvMedianNeighborDelta": median_delta, + "surfaceUvP95NeighborDelta": p95_delta, + "surfaceUvP99NeighborDelta": p99_delta, + "surfaceUvJumpLimit": float(jump_limit), + "surfaceUvBadNeighborRatio": bad_ratio, + }) + + if bad_ratio > SURFACE_UV_MAX_BAD_NEIGHBOR_RATIO: + quality["textureMappingReason"] = TextureMappingReason.NOISY_SURFACE_UV + return quality + quality["surfaceUvEnabled"] = True + quality["textureMappingMode"] = TextureMappingMode.SURFACE_UV + quality["textureMappingReason"] = ( + TextureMappingReason.SURFACE_UV_QUALITY_OK + if len(active_plane_ids) <= 1 + else TextureMappingReason.MULTI_PLANE_SURFACE_UV_QUALITY_OK + ) + return quality + + +def _plane_uvs_along_edge( + surface_mask: np.ndarray, + surface_indices: np.ndarray, + intrinsics: np.ndarray, + planes: list[dict], + uv_by_mask: np.ndarray, + plane_ids: np.ndarray, + ray_fill_mask: np.ndarray | None, +) -> tuple[int, int]: + """Floor-plane UVs where measured depth is unreliable: at the surface's edge. + + Depth is blurry where the floor meets a wall or furniture, and edge pixels + often carry the 3D point of the object itself (a speaker's foot sits within + the plane distance limit), which stretches the tile into a smear. In the + outer half of the edge band the UV is where the pixel's camera ray meets the + main plane; across the inner half it hands over to the measured point, so + there is no seam. + `ray_fill_mask` pixels with no UV at all also take the plane's UV. + Returns (pixels filled, pixels blended); updates the arrays in place. + """ + if not planes or not len(surface_indices): + return 0, 0 + main = max(range(len(planes)), key=lambda idx: planes[idx].get("assignedCount", 0)) + plane = planes[main] + finite = np.isfinite(uv_by_mask).all(axis=1) + on_main = finite & (plane_ids == main) + + band = SURFACE_UV_EDGE_BAND_RATIO * min(surface_mask.shape[:2]) + # Distance (px) to the nearest pixel outside the surface; the photo's border is not an edge. + distance = cv2.distanceTransform((surface_mask > 0).astype(np.uint8), cv2.DIST_L2, 3).ravel()[surface_indices] + blend = (distance < band) & on_main + fill = ~finite & ( + ray_fill_mask.ravel()[surface_indices].astype(bool) if ray_fill_mask is not None else False + ) + targets = blend | fill + if not targets.any(): + return 0, 0 + + uv, hit = ray_plane_uv( + surface_indices[targets], surface_mask.shape[1], intrinsics, + plane["origin"], plane["normal"], plane["uAxis"], plane["vAxis"], + ) + positions = np.flatnonzero(targets)[hit] + uv = uv[hit] + # Plane UVs across the outer half of the band, then a linear hand-over to the measured ones. + weight = np.clip(2.0 * (1.0 - distance[positions] / max(band, 1.0)), 0.0, 1.0)[:, None] + measured = uv_by_mask[positions] + has_measured = np.isfinite(measured).all(axis=1) + uv_by_mask[positions] = np.where(has_measured[:, None], weight * uv + (1.0 - weight) * measured, uv) + plane_ids[positions] = main + return int((~has_measured).sum()), int(has_measured.sum()) + + +def build_surface_uv_mapping( + surface_mask: np.ndarray, + surface_indices: np.ndarray, + geometry: dict | None, + *, + geometry_maps: dict | None = None, + ray_fill_mask: np.ndarray | None = None, +): + """Per-pixel floor UVs from the 3D point map, plane by plane. + + `ray_fill_mask` marks pixels (edge refinement's additions along walls and + furniture) whose measured depth is unreliable: where they get no UV from + their own 3D point, the UV comes from their camera ray meeting the main plane. + """ + total_started = time.perf_counter() + phase_started = total_started + maps = geometry_maps if geometry_maps is not None else geometry_point_maps(surface_mask, geometry) + geometry_maps_ms = (time.perf_counter() - phase_started) * 1000 + if maps is None: + print( + "[SURFACE_MAPPING] skipped: no point maps " + f"enabled={ENABLE_MULTI_PLANE_SURFACES} " + f"provider={geometry.get('provider') if geometry else None}", + flush=True, + ) + return None + + points_map = maps["points"] + normals_map = maps["normals"] + valid_mask = maps["validMask"] & (surface_mask > 0) + valid_flat = np.flatnonzero(valid_mask.ravel()).astype(np.uint32) + if len(valid_flat) < SURFACE_MIN_PLANE_PIXELS: + print( + "[SURFACE_MAPPING] skipped: too few valid surface pixels " + f"valid={len(valid_flat)} min={SURFACE_MIN_PLANE_PIXELS}", + flush=True, + ) + return None + + points = points_map.reshape(-1, 3)[valid_flat] + normals = normals_map.reshape(-1, 3)[valid_flat] + good_points = np.isfinite(points).all(axis=1) + if int(good_points.sum()) < SURFACE_MIN_PLANE_PIXELS: + print( + "[SURFACE_MAPPING] skipped: too few finite 3D points " + f"finitePoints={int(good_points.sum())} min={SURFACE_MIN_PLANE_PIXELS}", + flush=True, + ) + return None + + valid_flat = valid_flat[good_points] + points = points[good_points] + normals = normals[good_points] + prepared_normal_valid = maps.get("normalValidMask") + if prepared_normal_valid is not None and prepared_normal_valid.shape == surface_mask.shape: + normal_good = prepared_normal_valid.ravel()[valid_flat] + else: + normal_good = np.isfinite(normals).all(axis=1) & (np.linalg.norm(normals, axis=1) > 1e-4) + normals_reliable = int(normal_good.sum()) >= SURFACE_MIN_PLANE_PIXELS + gather_ms = (time.perf_counter() - phase_started) * 1000 - geometry_maps_ms + + print( + "[SURFACE_MAPPING] candidates " + f"surfacePixels={int(surface_mask.sum())} validPixels={len(points)} " + f"normalPixels={int(normal_good.sum())} normalsReliable={normals_reliable} " + f"provider={geometry.get('provider') if geometry else None}", + flush=True, + ) + + phase_started = time.perf_counter() + planes = fit_multi_surface_planes(points, normals, normals_reliable) + plane_fit_ms = (time.perf_counter() - phase_started) * 1000 + if not planes: + print( + "[SURFACE_MAPPING] skipped: no dominant planes fitted " + f"validPixels={len(points)} threshold={surface_distance_threshold(points):.4f} " + f"normalsReliable={normals_reliable}", + flush=True, + ) + return None + + phase_started = time.perf_counter() + assignment = assign_points_to_surface_planes(points, normals, planes, normals_reliable) + assignment_ms = (time.perf_counter() - phase_started) * 1000 + + phase_started = time.perf_counter() + uv_by_mask = np.full((len(surface_indices), 2), np.nan, dtype=np.float32) + plane_ids = np.full(len(surface_indices), 255, dtype=np.uint8) + ordinal = np.full(surface_mask.size, -1, dtype=np.int32) + ordinal[surface_indices] = np.arange(len(surface_indices), dtype=np.int32) + positions = ordinal[valid_flat] + assignment_distance_limit = max( + float(SURFACE_RANSAC_DISTANCE) * 1.5, + min(float(SURFACE_PLANE_DISTANCE_METERS), surface_distance_threshold(points) * 1.35), + ) + rejected_by_distance = 0 + + for plane_idx, plane in enumerate(planes): + assigned = assignment == plane_idx + if not assigned.any(): + plane["assignedCount"] = 0 + continue + projected_points, signed_distances = project_points_to_plane( + points[assigned], + plane["origin"], + plane["normal"], + ) + near_plane = np.abs(signed_distances) <= assignment_distance_limit + rejected_by_distance += int((~near_plane).sum()) + if not near_plane.any(): + plane["assignedCount"] = 0 + continue + delta = projected_points[near_plane] - plane["origin"] + uv = np.column_stack((delta @ plane["uAxis"], delta @ plane["vAxis"])).astype(np.float32) + assigned_positions = positions[assigned][near_plane] + assigned_keep = assigned_positions >= 0 + assigned_positions = assigned_positions[assigned_keep] + uv_by_mask[assigned_positions] = uv[assigned_keep] + plane_ids[assigned_positions] = plane_idx + plane["assignedCount"] = int(assigned_keep.sum()) + + ray_filled, edge_blended = _plane_uvs_along_edge( + surface_mask, surface_indices, maps["intrinsics"], planes, uv_by_mask, plane_ids, ray_fill_mask, + ) + + serializable_planes = [] + for plane in planes: + assigned_plane_uv = uv_by_mask[plane_ids == int(plane["id"])] + assigned_plane_uv = assigned_plane_uv[np.isfinite(assigned_plane_uv).all(axis=1)] + if len(assigned_plane_uv): + uv_min = np.min(assigned_plane_uv, axis=0) + uv_max = np.max(assigned_plane_uv, axis=0) + else: + uv_min = np.zeros(2, dtype=np.float32) + uv_max = np.ones(2, dtype=np.float32) + serializable_planes.append({ + "id": int(plane["id"]), + "normal": plane["normal"].astype(float).tolist(), + "origin": plane["origin"].astype(float).tolist(), + "offset": float(plane["offset"]), + "uAxis": plane["uAxis"].astype(float).tolist(), + "vAxis": plane["vAxis"].astype(float).tolist(), + "inlierCount": int(plane["inlierCount"]), + "assignedCount": int(plane.get("assignedCount", 0)), + "isFloor": bool(plane["isFloor"]), + "fitMode": str(plane.get("fitMode", PlaneFitMode.NORMAL_AWARE)), + "uvMin": uv_min.astype(float).tolist(), + "uvMax": uv_max.astype(float).tolist(), + "uvWidth": float(max(uv_max[0] - uv_min[0], 0.05)), + "uvHeight": float(max(uv_max[1] - uv_min[1], 0.05)), + }) + projection_ms = (time.perf_counter() - phase_started) * 1000 + + phase_started = time.perf_counter() + finite_uv = np.isfinite(uv_by_mask).all(axis=1) + uv_quality = analyze_surface_uv_quality(surface_mask, surface_indices, uv_by_mask, plane_ids) + quality_ms = (time.perf_counter() - phase_started) * 1000 + uv_quality["surfaceUvPlaneDistanceLimitMeters"] = float(assignment_distance_limit) + uv_quality["surfaceUvRejectedByPlaneDistance"] = int(rejected_by_distance) + uv_quality["surfaceUvRayFilledPixels"] = ray_filled + uv_quality["surfaceUvEdgeBlendedPixels"] = edge_blended + timing_ms = { + "geometryMaps": round(geometry_maps_ms, 2), + "pixelGather": round(gather_ms, 2), + "planeFit": round(plane_fit_ms, 2), + "planeAssignment": round(assignment_ms, 2), + "projection": round(projection_ms, 2), + "qualityAnalysis": round(quality_ms, 2), + "total": round((time.perf_counter() - total_started) * 1000, 2), + } + uv_quality["surfaceUvTimingMs"] = timing_ms + print( + "[SURFACE_MAPPING] success " + f"planes={len(serializable_planes)} assignedPixels={int(finite_uv.sum())}/{len(surface_indices)} " + f"fitModes={[plane['fitMode'] for plane in serializable_planes]} " + f"mode={uv_quality['textureMappingMode']} reason={uv_quality['textureMappingReason']}", + flush=True, + ) + print( + "[SURFACE_MAPPING_TIMING] " + + " ".join(f"{name}={duration:.2f}ms" for name, duration in timing_ms.items()), + flush=True, + ) + + return { + "uv": uv_by_mask, + "planeIds": plane_ids, + "planes": serializable_planes, + "normalMap": normals_map, + "validMask": valid_mask, + "intrinsics": maps["intrinsics"], + "depthScale": maps["depthScale"], + "normalsReliable": normals_reliable, + "useSurfaceUv": bool(uv_quality["surfaceUvEnabled"]), + "metadata": uv_quality, + } diff --git a/apps/renderer/services/image/__init__.py b/apps/renderer/services/image/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8383283dd3f7dff37e07a41ea0f0efeb4c59fa5c --- /dev/null +++ b/apps/renderer/services/image/__init__.py @@ -0,0 +1 @@ +"""Image loading and polygon extraction utilities.""" diff --git a/apps/renderer/services/image/loading.py b/apps/renderer/services/image/loading.py new file mode 100644 index 0000000000000000000000000000000000000000..9dabdc8f7234040be0228fb813b991fc26da92a3 --- /dev/null +++ b/apps/renderer/services/image/loading.py @@ -0,0 +1,69 @@ +"""Image loading and normalisation helpers.""" + +import io + +import cv2 +import numpy as np +from PIL import Image, ImageOps + +from config.runtime import ROOM_UPLOAD_JPEG_QUALITY, ROOM_UPLOAD_MAX_DIMENSION +from errors import bad_request + + +def load_tile_image(contents: bytes) -> np.ndarray: + try: + return np.array(Image.open(io.BytesIO(contents)).convert("RGB")) + except Exception as exc: + bad_request("Upload must be a readable tile image.", exc) + + +def load_uploaded_rgb_image(contents: bytes) -> tuple[Image.Image, np.ndarray]: + try: + image = Image.open(io.BytesIO(contents)).convert("RGB") + except Exception as exc: + bad_request("Upload must be a readable image.", exc) + return image, np.array(image) + + +def normalize_room_upload(contents: bytes) -> bytes: + try: + image = Image.open(io.BytesIO(contents)) + image.load() + except Exception as exc: + bad_request("Upload must be a readable image.", exc) + + source_format = (image.format or "").upper() + has_alpha = image.mode in {"RGBA", "LA"} or (image.mode == "P" and "transparency" in image.info) + width, height = image.size + largest = max(width, height) + needs_resize = largest > ROOM_UPLOAD_MAX_DIMENSION + try: + orientation = image.getexif().get(274) + except Exception: + orientation = None + needs_orientation = orientation not in {None, 1} + if source_format == "JPEG" and not has_alpha and not needs_resize and not needs_orientation: + return contents + + image = ImageOps.exif_transpose(image) + if has_alpha: + alpha = image.convert("RGBA") + background = Image.new("RGB", alpha.size, (255, 255, 255)) + background.paste(alpha, mask=alpha.getchannel("A")) + image = background + else: + image = image.convert("RGB") + + width, height = image.size + largest = max(width, height) + if largest > ROOM_UPLOAD_MAX_DIMENSION: + scale = ROOM_UPLOAD_MAX_DIMENSION / float(largest) + target_size = ( + max(1, int(round(width * scale))), + max(1, int(round(height * scale))), + ) + image = image.resize(target_size, Image.Resampling.LANCZOS) + + buffer = io.BytesIO() + image.save(buffer, format="JPEG", quality=ROOM_UPLOAD_JPEG_QUALITY, optimize=True) + return buffer.getvalue() diff --git a/apps/renderer/services/image/polygons.py b/apps/renderer/services/image/polygons.py new file mode 100644 index 0000000000000000000000000000000000000000..cfbd7e4c6ee78498fef7952af8a5920b9c0e353e --- /dev/null +++ b/apps/renderer/services/image/polygons.py @@ -0,0 +1,164 @@ +"""Mask-to-polygon conversion utilities.""" + +import cv2 +import numpy as np + + +def contour_to_polygon(contour: np.ndarray, simplify_epsilon: float) -> np.ndarray: + if simplify_epsilon > 0: + contour = cv2.approxPolyDP(contour, simplify_epsilon, True) + return contour.reshape(-1, 2) + + +def mask_to_polygons( + mask: np.ndarray, + min_area: float, + simplify_epsilon: float, +) -> list[dict]: + mask_u8 = (mask > 0).astype(np.uint8) + contours, _ = cv2.findContours(mask_u8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + polygons = [] + for contour in contours: + area = float(cv2.contourArea(contour)) + if area < min_area: + continue + + polygon = contour_to_polygon(contour, simplify_epsilon) + if len(polygon) < 3: + continue + + x, y, width, height = cv2.boundingRect(polygon.astype(np.int32).reshape(-1, 1, 2)) + polygons.append({ + "points": [[int(px), int(py)] for px, py in polygon], + "area": area, + "bbox": [int(x), int(y), int(width), int(height)], + }) + + polygons.sort(key=lambda item: item["area"], reverse=True) + return polygons + + +# Sub-pixel precision used when filling straightened polygons (cv2 `shift` bits). +_FILL_SHIFT = 4 + + +def straighten_mask_edges(mask: np.ndarray, tolerance: float, min_area: float = 0.0) -> np.ndarray: + """Redraw a binary mask so its boundaries are straight lines. + + Each boundary (outer edges and holes such as door or window cut-outs) is + split where it really changes direction (Douglas-Peucker, `tolerance` px), + every run is replaced by its least-squares line, and corners are placed + where neighbouring lines meet. Pixel-level zig-zag within `tolerance` + therefore becomes one straight edge through the middle of the wobble. + Boundaries enclosing less than `min_area` px are dropped (specks vanish, + pinholes are filled). + """ + mask_u8 = (mask > 0).astype(np.uint8) + if tolerance <= 0 or not mask_u8.any(): + return mask_u8 + contours, hierarchy = cv2.findContours(mask_u8, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) + if hierarchy is None: + return mask_u8 + + depths = _contour_depths(hierarchy[0][:, 3]) + scale = float(1 << _FILL_SHIFT) + out = np.zeros_like(mask_u8) + for index in np.argsort(depths, kind="stable"): + contour = contours[index] + if abs(cv2.contourArea(contour)) < min_area: + continue + polygon = np.round(_straight_polygon(contour.reshape(-1, 2), tolerance) * scale).astype(np.int32) + if len(polygon) < 3: + continue + if depths[index] % 2 == 0: + cv2.fillPoly(out, [polygon], 1, lineType=cv2.LINE_8, shift=_FILL_SHIFT) + else: + # A hole's contour runs through the mask pixels bordering it, so + # redraw that edge line after clearing to keep the mask flush with it. + cv2.fillPoly(out, [polygon], 0, lineType=cv2.LINE_8, shift=_FILL_SHIFT) + cv2.polylines(out, [polygon], True, 1, lineType=cv2.LINE_8, shift=_FILL_SHIFT) + return out + + +def _contour_depths(parents: np.ndarray) -> np.ndarray: + """Nesting depth of each contour from cv2 RETR_TREE parent indices (0 = outer).""" + depths = np.zeros(len(parents), dtype=np.int32) + for index in range(len(parents)): + parent = parents[index] + while parent >= 0: + depths[index] += 1 + parent = parents[parent] + return depths + + +def _straight_polygon(points: np.ndarray, tolerance: float) -> np.ndarray: + """Polygon whose edges are the best-fit lines of the contour's straight runs.""" + approx = cv2.approxPolyDP(points.reshape(-1, 1, 2), tolerance, True).reshape(-1, 2) + if len(approx) < 3: + return approx.astype(np.float32) + + position = {(int(x), int(y)): i for i, (x, y) in enumerate(points)} + anchors = sorted(position[(int(x), int(y))] for x, y in approx) + count = len(points) + lines = [] + for k, start in enumerate(anchors): + end = anchors[(k + 1) % len(anchors)] + run = points[start:end + 1] if end > start else np.concatenate((points[start:], points[:end + 1])) + lines.append(_fit_line(run)) + + vertices = [] + for k, anchor in enumerate(anchors): + corner = _line_intersection(lines[k - 1], lines[k]) + original = points[anchor % count].astype(np.float64) + # Near-parallel neighbours or a far-away intersection: keep the traced corner. + if corner is None or np.linalg.norm(corner - original) > 2.0 * tolerance: + corner = original + vertices.append(corner) + return np.asarray(vertices, dtype=np.float32) + + +def straighten_polyline(points: np.ndarray, tolerance: float) -> np.ndarray: + """Open-path version of `_straight_polygon`: the run's best-fit lines. + + The path is split where it really changes direction (Douglas-Peucker, + `tolerance` px), each piece becomes its least-squares line, inner corners go + where neighbouring lines meet and the two ends are projected onto their line. + """ + points = np.asarray(points, dtype=np.float32).reshape(-1, 2) + if len(points) < 3 or tolerance <= 0: + return points.copy() + approx = cv2.approxPolyDP(points.reshape(-1, 1, 2), tolerance, False).reshape(-1, 2) + anchors = sorted({0, len(points) - 1} | { + int(np.flatnonzero((points == vertex).all(axis=1))[0]) for vertex in approx + }) + lines = [_fit_line(points[start:end + 1]) for start, end in zip(anchors, anchors[1:])] + + vertices = [_project_onto_line(points[0], lines[0])] + for k in range(1, len(lines)): + corner = _line_intersection(lines[k - 1], lines[k]) + original = points[anchors[k]].astype(np.float64) + if corner is None or np.linalg.norm(corner - original) > 2.0 * tolerance: + corner = original + vertices.append(corner) + vertices.append(_project_onto_line(points[-1], lines[-1])) + return np.asarray(vertices, dtype=np.float32) + + +def _fit_line(run: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + vx, vy, x0, y0 = cv2.fitLine(run.astype(np.float32), cv2.DIST_L2, 0, 0.01, 0.01).ravel() + return np.array([x0, y0], np.float64), np.array([vx, vy], np.float64) + + +def _project_onto_line(point: np.ndarray, line) -> np.ndarray: + origin, direction = line + offset = np.asarray(point, np.float64) - origin + return origin + float(offset @ direction) * direction + + +def _line_intersection(first, second) -> np.ndarray | None: + (p1, d1), (p2, d2) = first, second + denom = d1[0] * d2[1] - d1[1] * d2[0] + if abs(denom) < 1e-3: + return None + t = ((p2[0] - p1[0]) * d2[1] - (p2[1] - p1[1]) * d2[0]) / denom + return p1 + t * d1 diff --git a/apps/renderer/services/jobs/__init__.py b/apps/renderer/services/jobs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e728113ef50ef8aba809de7007274888ade4e9ed --- /dev/null +++ b/apps/renderer/services/jobs/__init__.py @@ -0,0 +1 @@ +# Job management services: storage, timing baselines, conversion tasks. diff --git a/apps/renderer/services/jobs/conversion.py b/apps/renderer/services/jobs/conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..c68199cfdc5eedcfef75d39f32f2227add8a0e64 --- /dev/null +++ b/apps/renderer/services/jobs/conversion.py @@ -0,0 +1,212 @@ +"""Background conversion task: segment an uploaded image into a vizbundle.""" + +import time +import threading +from contextlib import contextmanager +from datetime import datetime, timezone +from pathlib import Path + +from fastapi import HTTPException + +from config.paths import JOB_DIR +from config.runtime import DEBUG_ARTIFACTS_ENABLED, MAX_CONCURRENT_CONVERSIONS +from services.access.usage import refund_free_try +from services.jobs.store import read_job, release_live_job, write_job +from services.jobs.timing import estimate_conversion_ms, record_conversion_ms +from enums import JobStatus, PipelinePhase + +CONVERSION_STAGE_WEIGHTS = { + PipelinePhase.SEGMENTATION: 0.28, + PipelinePhase.MASKING: 0.08, + PipelinePhase.GEOMETRY: 0.18, + PipelinePhase.SURFACE_MAPPING: 0.12, + PipelinePhase.LIGHTING: 0.15, + PipelinePhase.DIRECTION: 0.08, + PipelinePhase.PACKAGING: 0.11, +} +CONVERSION_STAGE_ORDER = tuple(CONVERSION_STAGE_WEIGHTS) +CONVERSION_SLOTS = threading.BoundedSemaphore(MAX_CONCURRENT_CONVERSIONS) + + +@contextmanager +def conversion_slot(on_wait): + """Hold a conversion slot; call on_wait only if the job must actually queue.""" + if not CONVERSION_SLOTS.acquire(blocking=False): + on_wait() + CONVERSION_SLOTS.acquire() + try: + yield + finally: + CONVERSION_SLOTS.release() + + +def update_conversion_job( + job_id: str, + *, + phase: str | None = None, + progress: int | None = None, + phase_progress: int | None = None, + message: str | None = None, + **values, +): + """Persist live conversion state for the browser's progress and ETA display.""" + try: + job = read_job(job_id) + except HTTPException: + return + if phase is not None: + job["phase"] = phase + if progress is not None: + job["progress"] = max(0, min(100, int(progress))) + if phase_progress is not None: + job["phaseProgress"] = max(0, min(100, int(phase_progress))) + if message is not None: + job["message"] = message + job.update(values) + write_job(job, durable=False) + + +def weighted_conversion_progress(completed_phases: set[str], phase: str, phase_progress: float) -> int: + completed_weight = sum( + CONVERSION_STAGE_WEIGHTS.get(item, 0.0) + for item in completed_phases + if item != phase + ) + current_weight = CONVERSION_STAGE_WEIGHTS.get(phase, 0.0) * max(0.0, min(1.0, phase_progress / 100.0)) + return round((completed_weight + current_weight) * 100) + + +def run_conversion_task(job_id: str, upload_path: Path): + # Deferred imports to avoid circular dependencies with pipeline modules + from services.debug.capture import PipelineDebugCapture + from services.pipeline.packaging import build_manifest_segmentation_bundle + + task_started = time.perf_counter() + debug = PipelineDebugCapture(job_id) if DEBUG_ARTIFACTS_ENABLED else None + estimate_ms = estimate_conversion_ms() + t_read = time.perf_counter() + image_bytes = upload_path.read_bytes() + input_read_ms = (time.perf_counter() - t_read) * 1000 + image_url = f"/uploads/{upload_path.name}" + + def announce_queued(): + update_conversion_job( + job_id, + status=JobStatus.QUEUED, + phase="queued", + progress=0, + phase_progress=0, + message="Waiting for an analysis slot\u2026", + estimatedTotalMs=estimate_ms, + estimatedRemainingMs=estimate_ms, + ) + + try: + # Run one authoritative HD pass. The former preview repeated + # segmentation and full-resolution CPU work, then was normally missed + # before the status returned to PROCESSING. + gpu_wait_started = time.perf_counter() + with conversion_slot(announce_queued): + gpu_queue_wait_ms = (time.perf_counter() - gpu_wait_started) * 1000 + t_start = time.perf_counter() + update_conversion_job( + job_id, + status=JobStatus.PROCESSING, + phase=PipelinePhase.SEGMENTATION, + progress=0, + phase_progress=0, + message="Analyzing floor (HD)\u2026", + estimatedTotalMs=estimate_ms, + estimatedRemainingMs=estimate_ms, + gpuQueueWaitMs=round(gpu_queue_wait_ms), + ) + completed_phases: set[str] = set() + + def report_stage(phase: str, phase_progress: float): + if phase_progress >= 100: + completed_phases.add(phase) + elapsed_ms = (time.perf_counter() - t_start) * 1000 + remaining_ms = max(0, estimate_ms - elapsed_ms) + hd_progress = weighted_conversion_progress(completed_phases, phase, phase_progress) + update_conversion_job( + job_id, + phase=phase, + progress=hd_progress, + phase_progress=round(phase_progress), + message=f"Enhancing {phase.replace('-', ' ')}\u2026", + estimatedRemainingMs=round(remaining_ms), + ) + + from services.pipeline.builder import build_segmentation_bundle + + bundle = build_segmentation_bundle( + image_bytes, debug=debug, progress_callback=report_stage, include_pixels=False, + ) + report_stage(PipelinePhase.PACKAGING, 25) + serialization_started = time.perf_counter() + binary_bundle = build_manifest_segmentation_bundle( + bundle, job_id, image_url=image_url, include_image=False, + ) + (JOB_DIR / f"{job_id}.vizbundle").write_bytes(binary_bundle) + serialization_ms = (time.perf_counter() - serialization_started) * 1000 + report_stage(PipelinePhase.PACKAGING, 100) + elapsed_ms = (time.perf_counter() - t_start) * 1000 + record_conversion_ms(elapsed_ms) + pipeline_stages = [ + stage for stage in (bundle.get("pipelineStages") or []) + if stage.get("name") != "TOTAL" + ] + pipeline_stages.append({ + "name": "Bundle Serialization", + "elapsed_s": round(serialization_ms / 1000, 3), + "detail": f"{len(binary_bundle) / 1024:.0f} KB", + }) + accounted_s = sum(float(stage.get("elapsed_s") or 0.0) for stage in pipeline_stages) + conversion_overhead_s = max(0.0, elapsed_ms / 1000 - accounted_s) + if conversion_overhead_s >= 0.001: + pipeline_stages.append({ + "name": "Conversion Overhead", + "elapsed_s": round(conversion_overhead_s, 3), + "detail": "job-state updates and orchestration", + }) + pipeline_stages.append({ + "name": "TOTAL", + "elapsed_s": round(elapsed_ms / 1000, 3), + "detail": "full HD conversion", + }) + job = read_job(job_id) + job["status"] = JobStatus.COMPLETED + job["phase"] = "completed" + job["progress"] = 100 + job["phaseProgress"] = 100 + job["message"] = "Surfaces ready" + job["estimatedRemainingMs"] = 0 + job["completedAt"] = datetime.now(timezone.utc).isoformat() + job["durationMs"] = round(elapsed_ms) + job["modelName"] = bundle.get("modelName") + job["models"] = bundle.get("models") + job["pipelineStages"] = pipeline_stages + job["inputReadMs"] = round(input_read_ms) + job["gpuQueueWaitMs"] = round(gpu_queue_wait_ms) + job["bundleSerializationMs"] = round(serialization_ms) + job["taskDurationMs"] = round((time.perf_counter() - task_started) * 1000) + job["outputFormat"] = "split-vizbundle" + write_job(job) + print(f"\n[JOB {job_id[:8]}] HD conversion completed in around {elapsed_ms / 1000:.2f}s\n", flush=True) + except Exception as exc: + print(f"Background conversion failed: {exc}", flush=True) + if debug is not None: + debug.fail(exc) + try: + job = read_job(job_id) + job["status"] = JobStatus.FAILED + job["phase"] = "failed" + job["estimatedRemainingMs"] = None + job["error"] = str(exc) + write_job(job) + except Exception: + job = None + # Our failure, not the user's: give a Prevision free try back. + refund_free_try((job or {}).get("generationId")) + finally: + release_live_job(job_id) diff --git a/apps/renderer/services/jobs/store.py b/apps/renderer/services/jobs/store.py new file mode 100644 index 0000000000000000000000000000000000000000..5b2cda08cf5d8178f6b731dca963be42a9a81122 --- /dev/null +++ b/apps/renderer/services/jobs/store.py @@ -0,0 +1,66 @@ +"""Job persistence: read / write JSON job files. + +Jobs that are being converted also have a live in-memory copy. Progress +updates only touch that copy, because rewriting the JSON file ~16 times per +job occasionally stalled on the pod's disk and added 5-9s of untimed +"Pipeline Overhead". The file is still written when a job is created and when +it finishes, and every read prefers the live copy so status checks stay current. +""" + +import copy +import json +import os +import threading +from pathlib import Path + +from fastapi import HTTPException + +from config.paths import JOB_DIR +from enums import JobStatus +from errors import not_found + +_FINISHED = {JobStatus.COMPLETED, JobStatus.FAILED} + +_live_jobs: dict[str, dict] = {} +_live_jobs_lock = threading.Lock() + + +def job_path(job_id: str) -> Path: + return JOB_DIR / f"{job_id}.json" + + +def read_job(job_id: str): + with _live_jobs_lock: + live = _live_jobs.get(job_id) + if live is not None: + return copy.deepcopy(live) + path = job_path(job_id) + if not path.exists(): + not_found("Job not found.") + return json.loads(path.read_text()) + + +def write_job(job: dict, *, durable: bool = True): + """Store a job. durable=False keeps the update in memory only (live progress).""" + job_id = job["id"] + with _live_jobs_lock: + if job_id in _live_jobs: + _live_jobs[job_id] = copy.deepcopy(job) + elif not durable: + # A progress update that lands after release_live_job() would + # otherwise pin a finished job in memory for the process lifetime. + if job.get("status") in _FINISHED: + return + _live_jobs[job_id] = copy.deepcopy(job) + if not durable: + return + path = job_path(job_id) + temporary = path.with_suffix(f"{path.suffix}.{os.getpid()}.{threading.get_ident()}.tmp") + temporary.write_text(json.dumps(job, separators=(",", ":"))) + temporary.replace(path) + + +def release_live_job(job_id: str): + """Drop the in-memory copy once the job's final state is on disk.""" + with _live_jobs_lock: + _live_jobs.pop(job_id, None) diff --git a/apps/renderer/services/jobs/timing.py b/apps/renderer/services/jobs/timing.py new file mode 100644 index 0000000000000000000000000000000000000000..c69f73560c9c215c27558086f0c1f103796ea6c8 --- /dev/null +++ b/apps/renderer/services/jobs/timing.py @@ -0,0 +1,44 @@ +"""Conversion timing baseline: estimate and record durations.""" + +import json +import os +import threading +from pathlib import Path + +from config.paths import TIMING_BASELINE_PATH +from config.runtime import CONVERSION_TARGET_MS + +TIMING_BASELINE_LOCK = threading.Lock() + + +def estimate_conversion_ms() -> int: + default_ms = CONVERSION_TARGET_MS + if TIMING_BASELINE_PATH is None or not TIMING_BASELINE_PATH.exists(): + return default_ms + try: + data = json.loads(TIMING_BASELINE_PATH.read_text()) + samples = [float(value) for value in data.get("totalMs", []) if float(value) > 0] + if len(samples) < 3: + return default_ms + samples.sort() + return max(5_000, round(samples[min(len(samples) - 1, int(len(samples) * 0.75))])) + except (OSError, TypeError, ValueError, json.JSONDecodeError): + return default_ms + + +def record_conversion_ms(duration_ms: float): + if TIMING_BASELINE_PATH is None: + return + with TIMING_BASELINE_LOCK: + data = {"totalMs": []} + try: + if TIMING_BASELINE_PATH.exists(): + data = json.loads(TIMING_BASELINE_PATH.read_text()) + except (OSError, TypeError, ValueError, json.JSONDecodeError): + data = {"totalMs": []} + samples = [float(value) for value in data.get("totalMs", []) if float(value) > 0] + samples.append(float(duration_ms)) + data["totalMs"] = samples[-40:] + temporary = TIMING_BASELINE_PATH.with_suffix(f"{TIMING_BASELINE_PATH.suffix}.{os.getpid()}.tmp") + temporary.write_text(json.dumps(data, separators=(",", ":"))) + temporary.replace(TIMING_BASELINE_PATH) diff --git a/apps/renderer/services/lighting/__init__.py b/apps/renderer/services/lighting/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6a4c824bbd202d844ee1d8ab2f075c45ffcd23f7 --- /dev/null +++ b/apps/renderer/services/lighting/__init__.py @@ -0,0 +1 @@ +# Lighting extraction and shading services. diff --git a/apps/renderer/services/lighting/intrinsic.py b/apps/renderer/services/lighting/intrinsic.py new file mode 100644 index 0000000000000000000000000000000000000000..b834552e0b8a31514b3122b61f32dc24beeb70db --- /dev/null +++ b/apps/renderer/services/lighting/intrinsic.py @@ -0,0 +1,198 @@ +"""Intrinsic-decomposition shading extraction and lighting map construction.""" + +from __future__ import annotations + +import numpy as np + +from config.lighting import ( + SHADE_MAP_MAX, + SHADE_MAP_MIN, +) +from config.runtime import ENABLE_INTRINSIC_SHADING +from state import intrinsic_models, device, gpu_inference +from enums import IntrinsicAlignment +from utils import to_numpy +from services.lighting.luminance import ( + broad_luminance_relative, + decode_relative_map, + encode_relative_map, + masked_gaussian_blur, + normalize_relative_field, +) +from services.lighting.shading import ( + build_luminance_lighting_maps, + preserve_observed_lighting, + smooth_relative_lighting, + suppress_replaced_material_lighting, +) + + +# --------------------------------------------------------------------------- +# Intrinsic shading extraction +# --------------------------------------------------------------------------- + +def extract_intrinsic_shading(results: dict) -> np.ndarray | None: + shading = None + if "gry_shd" in results: + shading = results["gry_shd"] + elif "dif_shd" in results: + shading = results["dif_shd"] + else: + for key, value in results.items(): + if "shd" in key or "shading" in key: + shading = value + break + + if shading is None: + return None + + shading = to_numpy(shading) + if shading is None: + return None + if shading.ndim == 3: + if shading.shape[2] == 1: + shading = shading[:, :, 0] + else: + shading = ( + shading[:, :, 0] * 0.299 + + shading[:, :, 1] * 0.587 + + shading[:, :, 2] * 0.114 + ) + if shading.ndim != 2: + return None + return shading.astype(np.float32) + + +# --------------------------------------------------------------------------- +# Normalization and alignment +# --------------------------------------------------------------------------- + +def normalize_relative_shading( + shading: np.ndarray, + surface_mask: np.ndarray, +) -> np.ndarray | None: + import cv2 + h, w = surface_mask.shape[:2] + if shading.shape[:2] != (h, w): + shading = cv2.resize(shading, (w, h), interpolation=cv2.INTER_LINEAR) + + shading = shading.astype(np.float32) + floor_vals = shading[surface_mask > 0] + floor_vals = floor_vals[np.isfinite(floor_vals) & (floor_vals > 1e-6)] + if floor_vals.size == 0: + return None + + median_val = float(np.median(floor_vals)) + if median_val < 1e-6: + return None + + relative = shading / median_val + relative[~np.isfinite(relative)] = 1.0 + relative[surface_mask == 0] = 1.0 + return relative.astype(np.float32) + + +def align_intrinsic_shading_to_luminance( + relative_shading: np.ndarray, + img_np: np.ndarray, + surface_mask: np.ndarray, +) -> tuple[np.ndarray, str]: + """Correct intrinsic maps that encode lightness with the opposite polarity.""" + observed = broad_luminance_relative(img_np, surface_mask) + if observed is None: + return relative_shading, IntrinsicAlignment.UNCHECKED + + sigma = max(12.0, min(surface_mask.shape[:2]) / 32.0) + intrinsic_broad = masked_gaussian_blur(relative_shading, surface_mask, sigma) + intrinsic_broad = normalize_relative_field(intrinsic_broad, surface_mask) + if intrinsic_broad is None: + return relative_shading, IntrinsicAlignment.UNCHECKED + + valid = ( + (surface_mask > 0) + & np.isfinite(observed) + & np.isfinite(intrinsic_broad) + & (observed > 1e-4) + & (intrinsic_broad > 1e-4) + ) + if int(valid.sum()) < 256: + return relative_shading, IntrinsicAlignment.UNCHECKED + + observed_log = np.log(observed[valid]) + intrinsic_log = np.log(intrinsic_broad[valid]) + if float(np.std(observed_log)) < 1e-4 or float(np.std(intrinsic_log)) < 1e-4: + return relative_shading, IntrinsicAlignment.UNCHECKED + + correlation = float(np.corrcoef(observed_log, intrinsic_log)[0, 1]) + if correlation < -0.12: + corrected = normalize_relative_field(1.0 / np.maximum(relative_shading, 1e-4), surface_mask) + if corrected is not None: + return corrected, IntrinsicAlignment.INVERTED_CORRECTED + return relative_shading, IntrinsicAlignment.ALIGNED if correlation >= 0.10 else IntrinsicAlignment.LOW_CONFIDENCE + + +# --------------------------------------------------------------------------- +# Intrinsic lighting maps +# --------------------------------------------------------------------------- + +def build_intrinsic_lighting_maps( + img_np: np.ndarray, + surface_mask: np.ndarray, + replaced_material_mask: np.ndarray | None = None, +) -> dict[str, np.ndarray | None] | None: + if not surface_mask.any() or intrinsic_models is None: + return None + + try: + img_float = img_np.astype(np.float32) / 255.0 + from intrinsic.pipeline import run_pipeline + with gpu_inference(): + results = run_pipeline(intrinsic_models, img_float, device=str(device)) + shading = extract_intrinsic_shading(results) + if shading is None: + return None + + relative = normalize_relative_shading(shading, surface_mask) + if relative is None: + return None + relative, alignment = align_intrinsic_shading_to_luminance(relative, img_np, surface_mask) + smoothed = smooth_relative_lighting(relative, surface_mask) + if smoothed is None: + return None + + luminance_maps = build_luminance_lighting_maps( + img_np, + surface_mask, + replaced_material_mask, + ) + if luminance_maps and luminance_maps.get("shadeMap") is not None: + observed = decode_relative_map( + luminance_maps["shadeMap"], + SHADE_MAP_MIN, + SHADE_MAP_MAX, + ) + smoothed = preserve_observed_lighting(smoothed, observed, surface_mask) + alignment = f"{alignment}+observed-lighting" + smoothed = suppress_replaced_material_lighting( + smoothed, + surface_mask, + replaced_material_mask, + ) + print(f"[LIGHTING] intrinsic shading alignment={alignment}", flush=True) + + from services.lighting.showroom import build_showroom_shade_map_from_relative + from services.lighting.reflection import build_reflection_map + + return { + "shadeMap": encode_relative_map(smoothed, SHADE_MAP_MIN, SHADE_MAP_MAX), + "showroomShadeMap": build_showroom_shade_map_from_relative(smoothed, surface_mask), + "reflectionMap": build_reflection_map( + img_np, + surface_mask, + smoothed, + replaced_material_mask, + ), + } + except Exception as exc: + print(f"Intrinsic shading decomposition failed: {exc}. Falling back to default luminance shading.", flush=True) + return None diff --git a/apps/renderer/services/lighting/luminance.py b/apps/renderer/services/lighting/luminance.py new file mode 100644 index 0000000000000000000000000000000000000000..8cd7e529a9f59124b9de43421cbefdad123787f8 --- /dev/null +++ b/apps/renderer/services/lighting/luminance.py @@ -0,0 +1,127 @@ +"""Luminance computation, relative-field helpers, and surface inpainting.""" + +from __future__ import annotations + +import cv2 +import numpy as np + +from config.lighting import ( + SHADE_MAP_MAX, + SHADE_MAP_MIN, +) + + +# --------------------------------------------------------------------------- +# Encoding / Decoding +# --------------------------------------------------------------------------- + +def encode_relative_map(values: np.ndarray, minimum: float, maximum: float) -> np.ndarray: + clipped = np.clip(values, minimum, maximum) + scale = 255.0 / max(maximum - minimum, 1e-6) + return np.round((clipped - minimum) * scale).clip(0, 255).astype(np.uint8) + + +def decode_relative_map(encoded: np.ndarray, minimum: float, maximum: float) -> np.ndarray: + return minimum + (encoded.astype(np.float32) / 255.0) * (maximum - minimum) + + +# --------------------------------------------------------------------------- +# Luminance +# --------------------------------------------------------------------------- + +def image_luminance(img_np: np.ndarray) -> np.ndarray: + return ( + img_np[:, :, 0].astype(np.float32) * 0.299 + + img_np[:, :, 1].astype(np.float32) * 0.587 + + img_np[:, :, 2].astype(np.float32) * 0.114 + ) + + +def image_linear_luminance(img_np: np.ndarray) -> np.ndarray: + """Return linear-light luminance in the same 0..255 scale as image_luminance.""" + srgb = np.clip(img_np.astype(np.float32) / 255.0, 0.0, 1.0) + linear = np.where( + srgb <= 0.04045, + srgb / 12.92, + np.power((srgb + 0.055) / 1.055, 2.4), + ) + luminance = ( + linear[:, :, 0] * 0.2126 + + linear[:, :, 1] * 0.7152 + + linear[:, :, 2] * 0.0722 + ) + return luminance * 255.0 + + +# --------------------------------------------------------------------------- +# Surface inpainting +# --------------------------------------------------------------------------- + +def inpaint_surface_values(values: np.ndarray, mask: np.ndarray, fill_value: float) -> np.ndarray: + h, w = mask.shape[:2] + filled = values.astype(np.float32).copy() + filled[mask == 0] = fill_value + missing = (mask == 0).astype(np.uint8) * 255 + try: + source = np.clip(filled, 0, 255).astype(np.uint8) + filled = cv2.inpaint( + source, + missing, + max(3, min(h, w) // 160), + cv2.INPAINT_TELEA, + ).astype(np.float32) + except cv2.error: + pass + return filled + + +# --------------------------------------------------------------------------- +# Gaussian blur helpers +# --------------------------------------------------------------------------- + +def masked_gaussian_blur( + values: np.ndarray, + surface_mask: np.ndarray, + sigma: float, +) -> np.ndarray: + mask = surface_mask.astype(np.float32) + numerator = cv2.GaussianBlur(values.astype(np.float32) * mask, (0, 0), sigmaX=sigma, sigmaY=sigma) + denominator = cv2.GaussianBlur(mask, (0, 0), sigmaX=sigma, sigmaY=sigma) + return numerator / np.maximum(denominator, 1e-4) + + +# --------------------------------------------------------------------------- +# Field normalization +# --------------------------------------------------------------------------- + +def normalize_relative_field(values: np.ndarray, surface_mask: np.ndarray) -> np.ndarray | None: + relative = values.astype(np.float32).copy() + valid = relative[surface_mask > 0] + valid = valid[np.isfinite(valid) & (valid > 1e-6)] + if valid.size == 0: + return None + median = float(np.median(valid)) + if median < 1e-6: + return None + relative /= median + relative[~np.isfinite(relative)] = 1.0 + relative[surface_mask == 0] = 1.0 + return relative + + +# --------------------------------------------------------------------------- +# Broad luminance relative +# --------------------------------------------------------------------------- + +def broad_luminance_relative( + img_np: np.ndarray, + surface_mask: np.ndarray, +) -> np.ndarray | None: + luminance = image_linear_luminance(img_np) / 255.0 + floor_values = luminance[surface_mask > 0] + floor_values = floor_values[np.isfinite(floor_values) & (floor_values > 1e-6)] + if floor_values.size == 0: + return None + sigma = max(12.0, min(surface_mask.shape[:2]) / 32.0) + broad = masked_gaussian_blur(luminance, surface_mask, sigma) + return normalize_relative_field(broad, surface_mask) diff --git a/apps/renderer/services/lighting/reflection.py b/apps/renderer/services/lighting/reflection.py new file mode 100644 index 0000000000000000000000000000000000000000..dfc184b8b5e57b7dca77f90248d4d1baeb2a9275 --- /dev/null +++ b/apps/renderer/services/lighting/reflection.py @@ -0,0 +1,101 @@ +"""Reflection map extraction for specular highlights on replacement materials.""" + +from __future__ import annotations + +import cv2 +import numpy as np + +from config.lighting import ( + REFLECTION_MAP_MAX, + REFLECTION_MAP_MIN, +) +from services.lighting.luminance import image_luminance +from services.lighting.shading import suppress_replaced_material_lighting + + +def build_reflection_map( + img_np: np.ndarray, + surface_mask: np.ndarray, + relative_shading: np.ndarray | None = None, + replaced_material_mask: np.ndarray | None = None, +) -> np.ndarray | None: + if not surface_mask.any(): + return None + + mask = surface_mask.astype(np.uint8) + h, w = mask.shape[:2] + reflection_candidates: list[np.ndarray] = [] + min_side = min(h, w) + + # High-pass filtering before removing a rug or carpet creates a bright halo + # just outside its mask. Exclude a scale-aware feather around replaced + # material, and a narrow surface boundary, before extracting reflections. + boundary_radius = max(1, int(round(min_side / 320.0))) + boundary_kernel = cv2.getStructuringElement( + cv2.MORPH_ELLIPSE, + (boundary_radius * 2 + 1, boundary_radius * 2 + 1), + ) + reflection_surface = cv2.erode(mask, boundary_kernel) > 0 + replacement_exclusion = np.zeros((h, w), dtype=bool) + if replaced_material_mask is not None and replaced_material_mask.shape[:2] == (h, w): + replacement = ((replaced_material_mask > 0) & (mask > 0)).astype(np.uint8) + if replacement.any(): + replacement_radius = max(3, int(round(min_side / 80.0))) + replacement_kernel = cv2.getStructuringElement( + cv2.MORPH_ELLIPSE, + (replacement_radius * 2 + 1, replacement_radius * 2 + 1), + ) + replacement_exclusion = cv2.dilate(replacement, replacement_kernel) > 0 + reflection_surface &= ~replacement_exclusion + + if relative_shading is not None: + rel = relative_shading.astype(np.float32).copy() + rel = suppress_replaced_material_lighting( + rel, + mask, + replacement_exclusion.astype(np.uint8), + ) + rel[mask == 0] = 1.0 + broad_sigma = max(6.0, min(h, w) / 44.0) + broad = cv2.GaussianBlur(rel, (0, 0), sigmaX=broad_sigma, sigmaY=broad_sigma) + detail = rel / np.maximum(broad, 1e-3) + candidate = np.clip((detail - 1.05) / 0.30, 0.0, 1.0) + broad_excess = np.clip((broad - 1.05) / 0.45, 0.0, 1.0) + reflection_candidates.append(candidate * (1.0 - 0.75 * broad_excess)) + + luminance = image_luminance(img_np) / 255.0 + floor_values = luminance[mask > 0] + floor_values = floor_values[np.isfinite(floor_values)] + if floor_values.size >= max(256, int(h * w * 0.002)): + median_lum = float(np.median(floor_values)) + if median_lum > 1e-3: + filled = luminance / median_lum + filled = suppress_replaced_material_lighting( + filled, + mask, + replacement_exclusion.astype(np.uint8), + ) + filled[mask == 0] = 1.0 + broad_sigma = max(8.0, min(h, w) / 36.0) + broad = cv2.GaussianBlur(filled, (0, 0), sigmaX=broad_sigma, sigmaY=broad_sigma) + detail = filled / np.maximum(broad, 1e-3) + candidate = np.clip((detail - 1.08) / 0.30, 0.0, 1.0) + broad_excess = np.clip((broad - 1.05) / 0.45, 0.0, 1.0) + reflection_candidates.append(candidate * (1.0 - 0.75 * broad_excess)) + + if not reflection_candidates: + return None + + # A reflection is additive light. Dark source-floor detail belongs to the + # illumination map; transferring it here would turn old material color or + # texture into an artificial dark reflection on the replacement material. + reflection = np.maximum.reduce(reflection_candidates).astype(np.float32) + if min(h, w) > 120: + sigma = max(0.6, min(h, w) / 520.0) + reflection = cv2.GaussianBlur(reflection, (0, 0), sigmaX=sigma, sigmaY=sigma) + reflection = np.clip(reflection, REFLECTION_MAP_MIN, min(REFLECTION_MAP_MAX, 0.20)) + reflection[~reflection_surface] = 0.0 + if float(np.max(np.abs(reflection[mask > 0]))) < 0.025: + return None + encoded = (reflection - REFLECTION_MAP_MIN) / (REFLECTION_MAP_MAX - REFLECTION_MAP_MIN) + return np.round(encoded * 255.0).clip(0, 255).astype(np.uint8) diff --git a/apps/renderer/services/lighting/shading.py b/apps/renderer/services/lighting/shading.py new file mode 100644 index 0000000000000000000000000000000000000000..2b09288d1c15ab814ae67533b8856f14539ad12b --- /dev/null +++ b/apps/renderer/services/lighting/shading.py @@ -0,0 +1,281 @@ +"""Shading map construction, smoothing, and luminance-based lighting maps.""" + +from __future__ import annotations + +import cv2 +import numpy as np + +from config.lighting import ( + SHADE_MAP_MAX, + SHADE_MAP_MIN, +) +from config.runtime import FAST_SHADOW_MAX_DIMENSION +from services.lighting.luminance import ( + encode_relative_map, + image_linear_luminance, + inpaint_surface_values, + masked_gaussian_blur, + normalize_relative_field, +) + + +# --------------------------------------------------------------------------- +# Smoothing +# --------------------------------------------------------------------------- + +def smooth_relative_lighting( + relative_shading: np.ndarray, + surface_mask: np.ndarray, + fill_outside: bool = False, +) -> np.ndarray | None: + """Keep room and cast-shadow illumination while rejecting old material detail. + + Uses a reduced broad-blur sigma and a higher local-detail blend (85 %) + compared to the original (70 %) so that contact shadows and sharp light + boundaries are preserved rather than smeared into vague gradients. + """ + min_side = min(surface_mask.shape[:2]) + broad_sigma = max(8.0, min_side / 52.0) + local_sigma = max(2.0, min_side / 180.0) + bounded = np.clip(relative_shading.astype(np.float32), 0.04, 4.0) + broad = masked_gaussian_blur(bounded, surface_mask, broad_sigma) + local = masked_gaussian_blur(bounded, surface_mask, local_sigma) + broad_relative = normalize_relative_field(broad, surface_mask) + if broad_relative is None: + return None + + local_contrast = local / np.maximum(broad, 1e-4) + local_log = np.log(np.maximum(local_contrast, 1e-4)) + local_log = np.clip(local_log, np.log(0.50), np.log(1.08)) + combined = broad_relative * np.exp(local_log * 0.35) + normalized = normalize_relative_field(combined, surface_mask) + if normalized is None: + return None + normalized = np.clip(normalized, SHADE_MAP_MIN, 1.08) + if fill_outside: + # Continue the surface's own light past its edge rather than neutral 1.0: the + # renderer samples this low-resolution map linearly, so a neutral outside + # would brighten the edge into a halo (and pixels the mask gained later, + # such as wall between stems, would get no shading at all). + outside = surface_mask == 0 + normalized[outside] = masked_gaussian_blur(normalized, surface_mask, broad_sigma)[outside] + normalized = np.clip(normalized, SHADE_MAP_MIN, 1.08) + else: + normalized[surface_mask == 0] = 1.0 + return normalized + + +# --------------------------------------------------------------------------- +# Replaced-material suppression +# --------------------------------------------------------------------------- + +def suppress_replaced_material_lighting( + relative: np.ndarray, + surface_mask: np.ndarray, + replaced_material_mask: np.ndarray | None, +) -> np.ndarray: + """Replace rug/carpet appearance with lighting extrapolated from nearby hard floor.""" + if replaced_material_mask is None or replaced_material_mask.shape != surface_mask.shape: + return relative + + replacement = (replaced_material_mask > 0) & (surface_mask > 0) + if not replacement.any(): + return relative + + known_surface = (surface_mask > 0) & (~replacement) + known_values = relative[known_surface] + known_values = known_values[np.isfinite(known_values) & (known_values > 1e-6)] + output = relative.astype(np.float32).copy() + if known_values.size < 64: + output[replacement] = 1.0 + output[surface_mask == 0] = 1.0 + return output + + median = float(np.median(known_values)) + source = output.copy() + source[~np.isfinite(source)] = median + source[surface_mask == 0] = median + radius = max(3.0, min(surface_mask.shape[:2]) / 120.0) + extrapolated = cv2.inpaint( + source.astype(np.float32), + replacement.astype(np.uint8), + radius, + cv2.INPAINT_TELEA, + ) + sigma = max(8.0, min(surface_mask.shape[:2]) / 48.0) + extrapolated = masked_gaussian_blur(extrapolated, surface_mask, sigma) + output[replacement] = extrapolated[replacement] + output = np.clip(output, SHADE_MAP_MIN, 1.08) + output[surface_mask == 0] = 1.0 + return output + + +# --------------------------------------------------------------------------- +# Luminance-based lighting maps +# --------------------------------------------------------------------------- + +def build_fast_shadow_lighting_maps( + img_np: np.ndarray, + surface_mask: np.ndarray, + replaced_material_mask: np.ndarray | None = None, + fill_outside: bool = False, +) -> dict[str, np.ndarray | None] | None: + """Extract broad room shadows on a bounded working image. + + Unlike the legacy lighting path, this does not run intrinsic inference, + calculate reflections, or process several full-resolution float maps. The + resulting low-resolution shade texture is sampled linearly by the renderer. + """ + if not surface_mask.any(): + return None + + source_h, source_w = surface_mask.shape[:2] + scale = min(1.0, FAST_SHADOW_MAX_DIMENSION / float(max(source_h, source_w))) + work_w = max(1, int(round(source_w * scale))) + work_h = max(1, int(round(source_h * scale))) + + if (work_w, work_h) == (source_w, source_h): + work_image = img_np + work_mask = surface_mask.astype(np.uint8) + work_replaced_mask = replaced_material_mask + else: + work_image = cv2.resize(img_np, (work_w, work_h), interpolation=cv2.INTER_AREA) + work_mask = cv2.resize( + surface_mask.astype(np.uint8), + (work_w, work_h), + interpolation=cv2.INTER_NEAREST, + ) + work_replaced_mask = ( + cv2.resize( + replaced_material_mask.astype(np.uint8), + (work_w, work_h), + interpolation=cv2.INTER_NEAREST, + ) + if replaced_material_mask is not None + else None + ) + + luminance = image_linear_luminance(work_image) + floor_values = luminance[work_mask > 0] + floor_values = floor_values[np.isfinite(floor_values) & (floor_values > 1e-6)] + if floor_values.size < max(64, int(work_h * work_w * 0.002)): + return None + + median_lum = float(np.median(floor_values)) + if median_lum < 1e-3: + return None + + relative = luminance / median_lum + relative[~np.isfinite(relative)] = 1.0 + relative[work_mask == 0] = 1.0 + relative = suppress_replaced_material_lighting( + relative, + work_mask, + work_replaced_mask, + ) + shade = smooth_relative_lighting(relative, work_mask, fill_outside=fill_outside) + if shade is None: + return None + + return { + "shadeMap": encode_relative_map(shade, SHADE_MAP_MIN, SHADE_MAP_MAX), + "showroomShadeMap": None, + "reflectionMap": None, + } + +def build_luminance_lighting_maps( + img_np: np.ndarray, + surface_mask: np.ndarray, + replaced_material_mask: np.ndarray | None = None, +) -> dict[str, np.ndarray | None] | None: + if not surface_mask.any(): + return None + + mask = surface_mask.astype(np.uint8) + luminance = image_linear_luminance(img_np) + h, w = mask.shape[:2] + floor_values = luminance[mask > 0] + if floor_values.size < max(256, int(h * w * 0.002)): + return None + + median_lum = float(np.median(floor_values)) + if median_lum < 1e-3: + return None + + filled = inpaint_surface_values(luminance, mask, median_lum) + + relative = filled / median_lum + relative[~np.isfinite(relative)] = 1.0 + relative = suppress_replaced_material_lighting( + relative, + mask, + replaced_material_mask, + ) + shade = smooth_relative_lighting(relative, mask) + if shade is None: + return None + + from services.lighting.showroom import build_showroom_shade_map_from_relative + from services.lighting.reflection import build_reflection_map + + return { + "shadeMap": encode_relative_map(shade, SHADE_MAP_MIN, SHADE_MAP_MAX), + "showroomShadeMap": build_showroom_shade_map_from_relative(shade, mask), + "reflectionMap": build_reflection_map( + img_np, + surface_mask, + None, + replaced_material_mask, + ), + } + + +# --------------------------------------------------------------------------- +# Statistics +# --------------------------------------------------------------------------- + +def lighting_map_statistics(encoded: np.ndarray | None, surface_mask: np.ndarray) -> dict | None: + if encoded is None: + return None + if encoded.shape[:2] != surface_mask.shape[:2]: + surface_mask = cv2.resize( + surface_mask.astype(np.uint8), + (encoded.shape[1], encoded.shape[0]), + interpolation=cv2.INTER_NEAREST, + ) + decoded = SHADE_MAP_MIN + (encoded.astype(np.float32) / 255.0) * (SHADE_MAP_MAX - SHADE_MAP_MIN) + values = decoded[surface_mask > 0] + if values.size == 0: + return None + percentiles = np.percentile(values, [1, 5, 50, 95, 99]) + return { + "minimum": round(float(values.min()), 4), + "p01": round(float(percentiles[0]), 4), + "p05": round(float(percentiles[1]), 4), + "median": round(float(percentiles[2]), 4), + "p95": round(float(percentiles[3]), 4), + "p99": round(float(percentiles[4]), 4), + "maximum": round(float(values.max()), 4), + } + + +def preserve_observed_lighting( + intrinsic_relative: np.ndarray, + observed_relative: np.ndarray, + surface_mask: np.ndarray, +) -> np.ndarray: + """Keep observed room shadows and highlights from being weakened by intrinsic decomposition.""" + fused = intrinsic_relative.astype(np.float32).copy() + shadow_pixels = (surface_mask > 0) & (observed_relative < 1.0) + highlight_pixels = (surface_mask > 0) & (observed_relative > 1.0) + fused[shadow_pixels] = np.minimum( + fused[shadow_pixels], + observed_relative[shadow_pixels], + ) + fused[highlight_pixels] = np.maximum( + fused[highlight_pixels], + observed_relative[highlight_pixels], + ) + fused = np.clip(fused, SHADE_MAP_MIN, 1.20) + fused[surface_mask == 0] = 1.0 + return fused diff --git a/apps/renderer/services/lighting/showroom.py b/apps/renderer/services/lighting/showroom.py new file mode 100644 index 0000000000000000000000000000000000000000..c6bafc1a2a2f4295e5b3ab6b5cc61220f800f47c --- /dev/null +++ b/apps/renderer/services/lighting/showroom.py @@ -0,0 +1,56 @@ +"""Showroom shade-map construction for neutral-lighting previews.""" + +from __future__ import annotations + +import cv2 +import numpy as np + +from config.lighting import ( + SHOWROOM_SHADE_MAP_MAX, + SHOWROOM_SHADE_MAP_MIN, +) +from services.lighting.luminance import encode_relative_map + + +def build_showroom_shade_map_from_relative( + relative: np.ndarray, + surface_mask: np.ndarray, +) -> np.ndarray | None: + if not surface_mask.any(): + return None + + mask = surface_mask.astype(np.uint8) + h, w = mask.shape[:2] + if relative.shape[:2] != (h, w): + relative = cv2.resize(relative.astype(np.float32), (w, h), interpolation=cv2.INTER_LINEAR) + + rel = relative.astype(np.float32).copy() + floor_values = rel[mask > 0] + floor_values = floor_values[np.isfinite(floor_values) & (floor_values > 1e-6)] + if floor_values.size < max(256, int(h * w * 0.002)): + return None + + median_rel = float(np.median(floor_values)) + if median_rel < 1e-6: + return None + + rel[~np.isfinite(rel)] = median_rel + rel[mask == 0] = median_rel + rel = rel / median_rel + + broad_sigma = max(18.0, min(h, w) / 18.0) + broad = cv2.GaussianBlur(rel, (0, 0), sigmaX=broad_sigma, sigmaY=broad_sigma) + broad_values = broad[mask > 0] + broad_values = broad_values[np.isfinite(broad_values) & (broad_values > 1e-6)] + if broad_values.size == 0: + return None + + broad_median = float(np.median(broad_values)) + if broad_median < 1e-6: + return None + + showroom = broad / broad_median + showroom = 1.0 + (showroom - 1.0) * 0.45 + showroom = np.clip(showroom, SHOWROOM_SHADE_MAP_MIN, SHOWROOM_SHADE_MAP_MAX) + showroom[mask == 0] = 1.0 + return encode_relative_map(showroom, SHOWROOM_SHADE_MAP_MIN, SHOWROOM_SHADE_MAP_MAX) diff --git a/apps/renderer/services/materials/__init__.py b/apps/renderer/services/materials/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..46330569d268ccfd3a9f6c5d8279baa9c746dc5a --- /dev/null +++ b/apps/renderer/services/materials/__init__.py @@ -0,0 +1 @@ +"""Tile material map generation and caching.""" diff --git a/apps/renderer/services/materials/cache.py b/apps/renderer/services/materials/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..929245144e2a198c9fb303c3b3d01191cc63de7f --- /dev/null +++ b/apps/renderer/services/materials/cache.py @@ -0,0 +1,82 @@ +"""Material package caching: key generation, lookup, and build.""" + +import hashlib +import json +from pathlib import Path + +from PIL import Image + +from config.paths import MATERIAL_DIR +from services.image.loading import load_tile_image +from services.materials.generator import ( + MATERIAL_GENERATOR_VERSION, + generate_tile_material_maps, +) + + +def material_cache_key(contents: bytes, base_roughness: float) -> str: + digest = hashlib.sha256() + digest.update(MATERIAL_GENERATOR_VERSION.encode("utf-8")) + digest.update(f":{float(base_roughness):.4f}:".encode("utf-8")) + digest.update(contents) + return digest.hexdigest()[:32] + + +def material_package_from_cache(cache_key: str) -> dict | None: + metadata_path = MATERIAL_DIR / cache_key / "metadata.json" + if not metadata_path.exists(): + return None + try: + metadata = json.loads(metadata_path.read_text()) + except Exception: + return None + maps = material_map_urls(cache_key) + if not all((MATERIAL_DIR / cache_key / Path(url).name).exists() for url in maps.values()): + return None + return { + "id": cache_key, + "cached": True, + "maps": maps, + "metadata": metadata, + } + + +def build_tile_material_package(contents: bytes, base_roughness: float = 0.42) -> dict: + cache_key = material_cache_key(contents, base_roughness) + cached = material_package_from_cache(cache_key) + if cached is not None: + return cached + + img_np = load_tile_image(contents) + maps, metadata = generate_tile_material_maps(img_np, base_roughness) + package_dir = MATERIAL_DIR / cache_key + package_dir.mkdir(parents=True, exist_ok=True) + filenames = { + "albedoMap": "albedo.png", + "normalMap": "normal.png", + "heightMap": "height.png", + "roughnessMap": "roughness.png", + "aoMap": "ao.png", + "specularMap": "specular.png", + } + for key, filename in filenames.items(): + Image.fromarray(maps[key]).save(package_dir / filename, format="PNG", optimize=True) + metadata_path = package_dir / "metadata.json" + metadata_path.write_text(json.dumps(metadata)) + return { + "id": cache_key, + "cached": False, + "maps": material_map_urls(cache_key), + "metadata": metadata, + } + + +def material_map_urls(cache_key: str) -> dict[str, str]: + return { + "albedoMap": f"/materials/{cache_key}/albedo.png", + "normalMap": f"/materials/{cache_key}/normal.png", + "heightMap": f"/materials/{cache_key}/height.png", + "roughnessMap": f"/materials/{cache_key}/roughness.png", + "aoMap": f"/materials/{cache_key}/ao.png", + "specularMap": f"/materials/{cache_key}/specular.png", + } diff --git a/apps/renderer/services/materials/generator.py b/apps/renderer/services/materials/generator.py new file mode 100644 index 0000000000000000000000000000000000000000..b879c2f20730c1e1f7ba6feb26fea3dc128b1ace --- /dev/null +++ b/apps/renderer/services/materials/generator.py @@ -0,0 +1,78 @@ +"""Procedural PBR material map generation from tile images.""" + +import cv2 +import numpy as np + +MATERIAL_GENERATOR_VERSION = "opencv-procedural-pbr-v1" +MATERIAL_MAX_DIMENSION = 1024 + + +def limit_material_image_size(img_np: np.ndarray, max_dimension: int = MATERIAL_MAX_DIMENSION) -> np.ndarray: + h, w = img_np.shape[:2] + largest = max(h, w) + if largest <= max_dimension: + return img_np + scale = max_dimension / float(largest) + new_w = max(1, int(round(w * scale))) + new_h = max(1, int(round(h * scale))) + return cv2.resize(img_np, (new_w, new_h), interpolation=cv2.INTER_AREA) + + +def generate_tile_material_maps(img_np: np.ndarray, base_roughness: float = 0.42) -> tuple[dict[str, np.ndarray], dict]: + albedo = limit_material_image_size(img_np) + rgb = albedo.astype(np.float32) / 255.0 + height = ( + rgb[:, :, 0] * 0.299 + + rgb[:, :, 1] * 0.587 + + rgb[:, :, 2] * 0.114 + ).astype(np.float32) + h_min = float(np.min(height)) + h_max = float(np.max(height)) + height = np.clip((height - h_min) / max(h_max - h_min, 1e-3), 0.0, 1.0) + height_smooth = cv2.GaussianBlur(height, (3, 3), 0) + + dx = np.roll(height_smooth, -1, axis=1) - np.roll(height_smooth, 1, axis=1) + dy = np.roll(height_smooth, -1, axis=0) - np.roll(height_smooth, 1, axis=0) + edge = np.clip((np.abs(dx) + np.abs(dy)) * 3.5, 0.0, 1.0) + + normal_strength = 3.0 + nx = -dx * normal_strength + ny = -dy * normal_strength + nz = np.ones_like(height_smooth) + norm = np.maximum(np.sqrt(nx * nx + ny * ny + nz * nz), 1e-4) + normal = np.dstack(( + (nx / norm) * 0.5 + 0.5, + (ny / norm) * 0.5 + 0.5, + (nz / norm) * 0.5 + 0.5, + )) + + roughness_base = float(np.clip(base_roughness, 0.04, 0.96)) + roughness = np.clip(roughness_base + edge * 0.34 + (0.5 - height_smooth) * 0.16, 0.04, 0.98) + ao = np.clip(0.74 + height_smooth * 0.26 - edge * 0.28, 0.45, 1.0) + specular = np.clip((1.0 - roughness) * 0.72 + height_smooth * 0.22, 0.02, 1.0) + + maps = { + "albedoMap": albedo, + "normalMap": float_to_rgb8(normal), + "heightMap": gray_to_rgb8(height_smooth), + "roughnessMap": gray_to_rgb8(roughness), + "aoMap": gray_to_rgb8(ao), + "specularMap": gray_to_rgb8(specular), + } + metadata = { + "generator": MATERIAL_GENERATOR_VERSION, + "generatedKinds": ["normalMap", "heightMap", "roughnessMap", "aoMap", "specularMap"], + "width": int(albedo.shape[1]), + "height": int(albedo.shape[0]), + "baseRoughness": roughness_base, + } + return maps, metadata + + +def float_to_rgb8(values: np.ndarray) -> np.ndarray: + return np.clip(values * 255.0, 0, 255).round().astype(np.uint8) + + +def gray_to_rgb8(values: np.ndarray) -> np.ndarray: + gray = np.clip(values * 255.0, 0, 255).round().astype(np.uint8) + return np.dstack((gray, gray, gray)) diff --git a/apps/renderer/services/pipeline/__init__.py b/apps/renderer/services/pipeline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..907f5b62253a3425c9bf22a0c81e85575d130d8f --- /dev/null +++ b/apps/renderer/services/pipeline/__init__.py @@ -0,0 +1 @@ +# Pipeline orchestration and bundle packaging. diff --git a/apps/renderer/services/pipeline/builder.py b/apps/renderer/services/pipeline/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..9650901972e9c425285c5de90791f1d44c75cc07 --- /dev/null +++ b/apps/renderer/services/pipeline/builder.py @@ -0,0 +1,459 @@ +"""Main pipeline orchestrator: build_segmentation_bundle.""" + +from __future__ import annotations + +import io +import time + +import cv2 +import numpy as np +from PIL import Image + +from config.runtime import ( + ENABLE_FAST_SHADOW_TRANSFER, + ENABLE_INTRINSIC_SHADING, + ENABLE_SHADING_TRANSFER, + ENABLE_WALL_SEGMENTS, +) +from models.depth import estimate_scene_geometry +from models.loader import _load_intrinsic_model +from models.segmentation import active_model_metadata, active_segmentation_model_name, run_segmentation +from services.debug.capture import PipelineDebugCapture +from services.direction.analysis import floor_direction_geometry_inputs +from services.floor.edge_coverage import scaled_odd_kernel_size +from services.floor.mask import build_floor_surface_mask, clean_floor_mask, wall_subtract +from services.floor.detection import estimate_floor_plane +from services.floor.edge_refinement import refine_surface_edges +from services.geometry.multi_plane import geometry_point_maps +from services.geometry.uv_mapping import build_surface_uv_mapping +from services.lighting.intrinsic import build_intrinsic_lighting_maps +from services.lighting.shading import ( + build_fast_shadow_lighting_maps, + build_luminance_lighting_maps, + lighting_map_statistics, +) +from services.pipeline.packaging import encode_bundle_image_data_url, foreground_occlusion_mask +from services.pipeline.bundle_assembly import build_fallback_segments, build_floor_segment +from services.pipeline import debug_stages +from services.pipeline.inference_utils import downscale_for_inference +from services.wall.pipeline import WallResult, build_wall_segments +from direction_finder import find_floor_direction +import state +from state import FLOOR_SURFACE_CLASSES, PRIMARY_FLOOR_CLASSES, REPLACEABLE_SOFT_FLOOR_CLASSES, class_ids +from enums import FloorMaskSource, PipelinePhase +from utils import mask_to_indices, seg_class_mask, timed_stage + +from enums import TextureMappingMode, TextureMappingReason + +_DEFAULT_MAPPING_META = { + "surfaceUvEnabled": False, "textureMappingMode": TextureMappingMode.REGULARIZED_FLOOR_PLANE, + "textureMappingReason": TextureMappingReason.SURFACE_UV_UNAVAILABLE, "surfaceUvCoverage": 0.0, + "surfaceUvFinitePixels": 0, "surfaceUvTotalPixels": 0, "surfaceUvNeighborCount": 0, + "surfaceUvMedianNeighborDelta": None, "surfaceUvP95NeighborDelta": None, + "surfaceUvP99NeighborDelta": None, "surfaceUvJumpLimit": None, + "surfaceUvBadNeighborRatio": None, "surfaceUvPlaneBoundaryRatio": None, + "surfaceUvAssignedPlaneCount": 0, +} + + +def build_segmentation_bundle( + contents: bytes, + debug: PipelineDebugCapture | None = None, + progress_callback=None, + include_pixels: bool = True, +): + t_start = time.perf_counter() + d = debug # shorthand + stage_times: list[tuple[str, float, str]] = [] # (stage_name, seconds, detail) + + def _log_stage(name: str, t0: float, detail: str = ""): + elapsed = time.perf_counter() - t0 + stage_times.append((name, elapsed, detail)) + + # Time job-progress updates so they show as their own report line instead + # of hiding inside "Pipeline Overhead". Every call below sits between + # timed stages, never inside one, so nothing is counted twice. + progress_elapsed = 0.0 + progress_calls = 0 + report_progress = progress_callback + + def progress_callback(phase, phase_progress): + nonlocal progress_elapsed, progress_calls + if report_progress is None: + return + started = time.perf_counter() + try: + report_progress(phase, phase_progress) + finally: + progress_elapsed += time.perf_counter() - started + progress_calls += 1 + + t0 = time.perf_counter() + img = Image.open(io.BytesIO(contents)).convert("RGB") + img_np = np.array(img) + h, w = img_np.shape[:2] + min_floor_area = max(1200, int(w * h * 0.015)) + + # Downscale for faster inference — masks/depth are output at full resolution + inf_img, inf_np, inf_scale = downscale_for_inference(img, img_np) + inf_h, inf_w = inf_np.shape[:2] + el = (time.perf_counter() - t0) * 1000 + if inf_scale < 1.0: + _log_stage("Image Loading", t0, f"{w}x{h} (inference@{inf_w}x{inf_h})") + else: + _log_stage("Image Loading", t0, f"{w}x{h}") + if d: + debug_stages.record_source_image(d, img_np, w, h, min_floor_area, el) + + # --- Segmentation + Geometry (parallel on CPU, sequential on single GPU) --- + if progress_callback: + progress_callback(PipelinePhase.SEGMENTATION, 0) + + use_parallel = state.device.type == "cpu" + if use_parallel: + from concurrent.futures import ThreadPoolExecutor + t0 = time.perf_counter() + with ThreadPoolExecutor(max_workers=2) as pool: + seg_future = pool.submit(run_segmentation, inf_img, inf_np, h, w) + geo_future = pool.submit(estimate_scene_geometry, inf_img, inf_np, w, h) + seg_map = seg_future.result() + geometry = geo_future.result() + t_seg_geo = time.perf_counter() - t0 + _log_stage("Segmentation+Geometry (parallel)", t0) + else: + t0 = time.perf_counter() + seg_map = run_segmentation(inf_img, inf_np, target_h=h, target_w=w) + _log_stage("Segmentation", t0) + t0 = time.perf_counter() + geometry = estimate_scene_geometry(inf_img, inf_np, w, h) + _log_stage("Geometry", t0, f"provider={geometry.get('provider')}") + + depth = geometry.get("depth") + el = (time.perf_counter() - t0) * 1000 + if d: + debug_stages.record_segmentation(d, img_np, seg_map, state.segmentation_backend, w, h, el) + debug_stages.record_geometry(d, depth, None, geometry, el) + if progress_callback: + progress_callback(PipelinePhase.SEGMENTATION, 100) + progress_callback(PipelinePhase.GEOMETRY, 55) + + # --- Walls: one background thread, overlapping every floor stage below --- + # All wall work runs at working resolution (see services.wall.pipeline), so + # it normally finishes before the floor does and "Wall Wait" stays ~0. + wall_future = None + wall_pool = None + if ENABLE_WALL_SEGMENTS: + from concurrent.futures import ThreadPoolExecutor as _WallPool + wall_pool = _WallPool(max_workers=1, thread_name_prefix="walls") + wall_future = wall_pool.submit( + build_wall_segments, img_np, seg_map, geometry, min_floor_area, + active_segmentation_model_name(), 1, + ) + + # --- Encode room image in background (overlaps with masking + later stages) --- + # Skipped for job conversions: the split vizbundle references the uploaded + # image by URL, so a full-resolution re-encode would be discarded. + _img_pool = None + _pixels_b64_future = None + if include_pixels: + from concurrent.futures import ThreadPoolExecutor as _TP + _img_pool = _TP(max_workers=1) + _pixels_b64_future = _img_pool.submit(encode_bundle_image_data_url, img_np) + + # --- Floor masking (SAM2 removed — morphological cleanup only) --- + if progress_callback: + progress_callback(PipelinePhase.MASKING, 0) + t0 = time.perf_counter() + raw_primary = seg_class_mask(seg_map, class_ids(PRIMARY_FLOOR_CLASSES)) + floor_mask = clean_floor_mask(wall_subtract(raw_primary.copy(), seg_map, dilation=0)) + floor_mask_source = FloorMaskSource.PRIMARY_FLOOR + if int(floor_mask.sum()) < min_floor_area: + floor_mask = clean_floor_mask(wall_subtract( + seg_class_mask(seg_map, class_ids(FLOOR_SURFACE_CLASSES)), seg_map, dilation=0)) + floor_mask_source = FloorMaskSource.FLOOR_SURFACE_FALLBACK + cleaned = floor_mask.copy() + sam_metadata = {"samRefinementEnabled": False, "samRefinementApplied": False, "samRefinementReason": "removed"} + el = (time.perf_counter() - t0) * 1000 + _log_stage("Floor Masking", t0, f"source={floor_mask_source}") + if d: + debug_stages.record_floor_mask(d, img_np, raw_primary, cleaned, floor_mask, floor_mask_source, sam_metadata, el) + if progress_callback: + progress_callback(PipelinePhase.MASKING, 100) + + t0 = time.perf_counter() + homography, plane = estimate_floor_plane(floor_mask, img_np, geometry) + el = (time.perf_counter() - t0) * 1000 + _log_stage("Plane Fitting", t0) + if d: + debug_stages.record_plane(d, img_np, plane, homography, el) + if progress_callback: + progress_callback(PipelinePhase.GEOMETRY, 100) + + # --- Surface mask --- + t0 = time.perf_counter() + geometry_maps_started = time.perf_counter() + prepared_geometry_maps = geometry_point_maps(floor_mask, geometry) + geometry_maps_ms = (time.perf_counter() - geometry_maps_started) * 1000 + quad = np.asarray(plane["quad"], dtype=np.float32).reshape(4, 2) if plane and plane.get("quad") else None + surface_mask, edge_metadata = build_floor_surface_mask( + floor_mask, + seg_map, + quad, + depth, + geometry, + plane, + geometry_maps=prepared_geometry_maps, + ) + unrefined_surface_mask = surface_mask + surface_mask, edge_alpha_map, refinement_metadata = refine_surface_edges(img_np, surface_mask, seg_map) + edge_metadata = {**edge_metadata, **refinement_metadata} + replaced_material_mask = (seg_class_mask(seg_map, class_ids(REPLACEABLE_SOFT_FLOOR_CLASSES)).astype(bool) & (surface_mask > 0)).astype(np.uint8) + surface_indices = mask_to_indices(surface_mask) + # One alpha byte per mask pixel, in mask order; the renderer blends the tile with it. + edge_alpha = edge_alpha_map.reshape(-1)[surface_indices] + occlusion_mask = foreground_occlusion_mask(surface_mask, seg_map) + occlusion_indices = mask_to_indices(occlusion_mask) + el = (time.perf_counter() - t0) * 1000 + surface_timing = edge_metadata.get("surfaceMaskingTimingMs") or {} + filter_ms = sum(float(surface_timing.get(name) or 0.0) for name in ( + "initialGeometryFilter", + "postEdgeGeometryFilter", + "postSoftFloorGeometryFilter", + )) + _log_stage( + "Surface Masking", + t0, + f"geometry-prep={geometry_maps_ms:.0f}ms filters={filter_ms:.0f}ms " + f"edges={float((refinement_metadata.get('edgeRefinementTimingMs') or {}).get('total') or 0.0):.0f}ms", + ) + if d: + debug_stages.record_surface(d, img_np, floor_mask, surface_mask, occlusion_mask, edge_metadata, el) + + # --- Surface UV mapping --- + if progress_callback: + progress_callback(PipelinePhase.SURFACE_MAPPING, 0) + t0 = time.perf_counter() + surface_mapping = build_surface_uv_mapping( + surface_mask, + surface_indices, + geometry, + geometry_maps=prepared_geometry_maps, + # Depth is blurry where the floor meets a wall, so the edge pixels the + # refinement added get their UV from the floor plane instead. + ray_fill_mask=(surface_mask > 0) & (unrefined_surface_mask == 0), + ) + use_surface_uv = bool(surface_mapping and surface_mapping.get("useSurfaceUv")) + mapping_metadata = surface_mapping["metadata"] if surface_mapping is not None else { + **_DEFAULT_MAPPING_META, "surfaceUvTotalPixels": int(len(surface_indices))} + el = (time.perf_counter() - t0) * 1000 + uv_timing = mapping_metadata.get("surfaceUvTimingMs") or {} + uv_detail = f"uv={'yes' if use_surface_uv else 'no'}" + if uv_timing: + uv_detail += ( + f" fit={float(uv_timing.get('planeFit') or 0.0):.0f}ms" + f" assign={float(uv_timing.get('planeAssignment') or 0.0):.0f}ms" + f" quality={float(uv_timing.get('qualityAnalysis') or 0.0):.0f}ms" + ) + _log_stage("UV Mapping", t0, uv_detail) + if d: + debug_stages.record_surface_mapping(d, h, w, surface_indices, surface_mapping, use_surface_uv, mapping_metadata, el) + if progress_callback: + progress_callback(PipelinePhase.SURFACE_MAPPING, 100) + + # --- Lighting --- + if progress_callback: + progress_callback(PipelinePhase.LIGHTING, 0) + t0 = time.perf_counter() + lighting_maps, shade_map, showroom_shade_map, reflection_map = None, None, None, None + lighting_source, intrinsic_lighting_used = None, False + if ENABLE_SHADING_TRANSFER and ENABLE_INTRINSIC_SHADING: + if state.intrinsic_models is None: + _load_intrinsic_model() + if state.intrinsic_models is not None: + lighting_maps = build_intrinsic_lighting_maps(img_np, surface_mask, replaced_material_mask) + if lighting_maps and lighting_maps.get("shadeMap") is not None: + from config.models import INTRINSIC_MODEL_VERSION + lighting_source, intrinsic_lighting_used = f"intrinsic-{INTRINSIC_MODEL_VERSION}", True + if ENABLE_FAST_SHADOW_TRANSFER and (not lighting_maps or lighting_maps.get("shadeMap") is None): + lighting_maps = build_fast_shadow_lighting_maps( + img_np, + surface_mask, + replaced_material_mask, + ) + if lighting_maps and lighting_maps.get("shadeMap") is not None: + lighting_source = "fast-luminance" + if ENABLE_SHADING_TRANSFER and (not lighting_maps or lighting_maps.get("shadeMap") is None): + lighting_maps = build_luminance_lighting_maps(img_np, surface_mask, replaced_material_mask) + if lighting_maps and lighting_maps.get("shadeMap") is not None: + lighting_source = "luminance" + if lighting_maps: + shade_map, showroom_shade_map, reflection_map = lighting_maps.get("shadeMap"), lighting_maps.get("showroomShadeMap"), lighting_maps.get("reflectionMap") + shade_statistics = lighting_map_statistics(shade_map, surface_mask) + el = (time.perf_counter() - t0) * 1000 + lighting_detail = f"source={lighting_source}" + if shade_map is not None: + lighting_detail += f" map={shade_map.shape[1]}x{shade_map.shape[0]}" + _log_stage("Lighting", t0, lighting_detail) + if d: + debug_stages.record_lighting(d, shade_map, showroom_shade_map, reflection_map, surface_mask, lighting_source, el) + + # The semantic wall mask remains useful as a structural cue for floor + # direction, even when wall surfaces are not emitted in the bundle. + wall_mask = seg_class_mask(seg_map, class_ids({"wall"})) + + if progress_callback: + progress_callback(PipelinePhase.LIGHTING, 100) + + # --- Floor direction --- + if progress_callback: + progress_callback(PipelinePhase.DIRECTION, 0) + t0 = time.perf_counter() + dir_xform = plane.get("floorTransform") if plane and plane.get("floorTransform") and float(plane.get("geometryConfidence") or 0.0) >= 0.35 else homography + dir_inputs = floor_direction_geometry_inputs( + surface_mask, + geometry, + plane, + surface_mapping, + use_surface_uv=use_surface_uv, + geometry_maps=prepared_geometry_maps, + ) + struct_mask = seg_class_mask(seg_map, class_ids({"wall", "ceiling", "door", "window", "column", "base", "railing"})) + sk = scaled_odd_kernel_size(h, w, 0.006, minimum=3) + struct_mask = cv2.dilate(struct_mask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (sk, sk)), iterations=1) + floor_direction = find_floor_direction( + img_np, surface_mask, wall_mask=wall_mask, structure_mask=struct_mask, + normals_map=dir_inputs["normalsMap"], geometry_valid_mask=dir_inputs["validMask"], + intrinsics=dir_inputs["intrinsics"], floor_normal=dir_inputs["floorNormal"], + render_u_axis=dir_inputs["renderUAxis"], render_v_axis=dir_inputs["renderVAxis"], + render_transform=dir_xform, + surface_uv=surface_mapping["uv"] if use_surface_uv else None, + surface_indices=surface_indices if use_surface_uv else None, + surface_plane_ids=surface_mapping["planeIds"] if use_surface_uv else None, + ) + el = (time.perf_counter() - t0) * 1000 + _log_stage("Floor Direction", t0, f"method={floor_direction.get('directionMethod')}") + if d: + debug_stages.record_direction(d, img_np, floor_direction, el) + if progress_callback: + progress_callback(PipelinePhase.DIRECTION, 100) + + walls = _collect_walls(wall_future, wall_pool, _log_stage) + + # --- Package segments --- + if progress_callback: + progress_callback(PipelinePhase.PACKAGING, 0) + t0 = time.perf_counter() + models = active_model_metadata(geometry, depth, shade_map, intrinsic_lighting_used) + segments = [] + if len(surface_indices) >= min_floor_area: + segments.append(build_floor_segment( + surface_indices=surface_indices, occlusion_indices=occlusion_indices, edge_alpha=edge_alpha, + homography=homography, plane=plane, surface_mapping=surface_mapping, + use_surface_uv=use_surface_uv, shade_map=shade_map, + showroom_shade_map=showroom_shade_map, reflection_map=reflection_map, + floor_mask=floor_mask, surface_mask=surface_mask, + replaced_material_mask=replaced_material_mask, occlusion_mask=occlusion_mask, + floor_direction=floor_direction, sam_metadata=sam_metadata, + edge_metadata=edge_metadata, mapping_metadata=mapping_metadata, + shade_statistics=shade_statistics, lighting_source=lighting_source, + intrinsic_lighting_used=intrinsic_lighting_used, models=models, depth=depth, geometry=geometry)) + segments.extend(walls.segments) + if not segments: + segments = build_fallback_segments(seg_map, depth, models) + + _log_stage("Packaging", t0, f"segments={len(segments)}") + if progress_callback: + progress_callback(PipelinePhase.PACKAGING, 100) + pixels_b64 = None + if _pixels_b64_future is not None: + t0 = time.perf_counter() + pixels_b64 = _pixels_b64_future.result() + _img_pool.shutdown(wait=False) + _log_stage("Image Encoding Wait", t0) + + if progress_calls: + stage_times.append(("Progress Updates", progress_elapsed, f"calls={progress_calls}")) + + total_elapsed = time.perf_counter() - t_start + accounted_elapsed = sum(elapsed for _, elapsed, _ in stage_times) + overhead_elapsed = max(0.0, total_elapsed - accounted_elapsed) + if overhead_elapsed >= 0.001: + stage_times.append(( + "Pipeline Overhead", + overhead_elapsed, + "callbacks, metadata and untimed glue", + )) + + # ── Print clean timing summary ── + _print_pipeline_summary(stage_times, total_elapsed, w, h) + + if d: + d.complete(total_elapsed * 1000) + pipeline_stages = [ + {"name": name, "elapsed_s": round(elapsed, 3), "detail": detail} + for name, elapsed, detail in stage_times + ] + pipeline_stages.append({ + "name": "TOTAL", "elapsed_s": round(total_elapsed, 3), "detail": f"{w}x{h}", + }) + + return {"width": w, "height": h, "pixels": pixels_b64, "segments": segments, + "modelName": models["segmentation"]["name"], "models": models, + "pipelineStages": pipeline_stages} + + +def _collect_walls(wall_future, wall_pool, log_stage) -> WallResult: + """Wait for the background wall thread and log its cost. + + "Wall Wait" is the only time walls add to the pipeline (the floor was + already done); its detail carries the walls' own (overlapped) timings. + A wall failure never fails the job: the floor ships without walls. + """ + if wall_future is None: + return WallResult() + t0 = time.perf_counter() + try: + walls = wall_future.result() + except Exception as exc: + print(f"[WALLS] skipped: wall stage failed ({exc})", flush=True) + walls = WallResult() + finally: + wall_pool.shutdown(wait=False) + # Wall timings go in the detail, not as their own stages, because they + # overlapped the floor stages and would otherwise be counted twice. + log_stage("Wall Wait", t0, walls.detail) + print(f"[WALLS] {walls.detail}", flush=True) + return walls + + +def _print_pipeline_summary( + stage_times: list[tuple[str, float, str]], + total_elapsed: float, + w: int, + h: int, +): + """Print a formatted pipeline timing summary to stdout.""" + sep = "─" * 60 + lines = [ + "", + f"┌{sep}┐", + f"│ {'PIPELINE TIMING REPORT':^58} │", + f"│ {'Image: ' + f'{w}x{h}':^58} │", + f"├{'─' * 30}┬{'─' * 14}┬{'─' * 14}┤", + f"│ {'Stage':<28} │ {'Time':>12} │ {'% Total':>12} │", + f"├{'─' * 30}┼{'─' * 14}┼{'─' * 14}┤", + ] + for name, elapsed, detail in stage_times: + pct = (elapsed / total_elapsed * 100) if total_elapsed > 0 else 0 + time_str = f"{elapsed:.2f}s" + pct_str = f"{pct:.1f}%" + label = f"{name} ({detail})" if detail else name + if len(label) > 28: + label = label[:27] + "\u2026" + lines.append(f"│ {label:<28} │ {time_str:>12} │ {pct_str:>12} │") + lines.append(f"├{'─' * 30}┼{'─' * 14}┼{'─' * 14}┤") + total_str = f"{total_elapsed:.2f}s" + lines.append(f"│ {'TOTAL':.<28} │ {total_str:>12} │ {'100%':>12} │") + lines.append(f"└{'─' * 30}┴{'─' * 14}┴{'─' * 14}┘") + lines.append("") + print("\n".join(lines), flush=True) diff --git a/apps/renderer/services/pipeline/bundle_assembly.py b/apps/renderer/services/pipeline/bundle_assembly.py new file mode 100644 index 0000000000000000000000000000000000000000..3397c01039e9e1656548f068ac4422b4cbfd5355 --- /dev/null +++ b/apps/renderer/services/pipeline/bundle_assembly.py @@ -0,0 +1,237 @@ +"""Segment dict construction for the visualization bundle.""" + +from __future__ import annotations + +import numpy as np + +from config.lighting import ( + LIGHTING_TRANSFER_VERSION, + REFLECTION_MAP_MAX, + REFLECTION_MAP_MIN, + SHADE_MAP_ENCODING, + SHADE_MAP_MAX, + SHADE_MAP_MIN, + SHOWROOM_SHADE_MAP_MAX, + SHOWROOM_SHADE_MAP_MIN, +) +from config.runtime import ( + ENABLE_FAST_SHADOW_TRANSFER, + ENABLE_MULTI_PLANE_SURFACES, + ENABLE_PLANE_FIT, + ENABLE_SAM_REFINEMENT, + ENABLE_SHADING_TRANSFER, +) +from models.segmentation import segmenter_metadata_name +from state import class_ids, class_name_for_id +from enums import SurfaceType, TextureMappingMode +from utils import encode_b64 + + +def build_floor_segment( + *, + surface_indices: np.ndarray, + occlusion_indices: np.ndarray, + edge_alpha: np.ndarray | None = None, + homography, + plane: dict | None, + surface_mapping: dict | None, + use_surface_uv: bool, + shade_map: np.ndarray | None, + showroom_shade_map: np.ndarray | None, + reflection_map: np.ndarray | None, + floor_mask: np.ndarray, + surface_mask: np.ndarray, + replaced_material_mask: np.ndarray, + occlusion_mask: np.ndarray, + floor_direction: dict, + sam_metadata: dict, + edge_metadata: dict, + mapping_metadata: dict, + shade_statistics: dict | None, + lighting_source: str | None, + intrinsic_lighting_used: bool, + models: dict, + depth, + geometry: dict, +) -> dict: + return { + "id": 0, + "className": SurfaceType.FLOOR, + "mask": encode_b64(surface_indices), + "occlusionMask": encode_b64(occlusion_indices) if len(occlusion_indices) else None, + "homography": homography, + "floorTransform": plane.get("floorTransform") if plane else None, + "plane": plane, + # Pass raw numpy arrays for lazy assets — packaging writes them directly + # to disk, avoiding the costly base64 encode/decode round-trip. + "surfaceUv": ( + surface_mapping["uv"].astype(np.float32) + if use_surface_uv else None + ), + "surfacePlaneIds": ( + surface_mapping["planeIds"].astype(np.uint8) + if use_surface_uv else None + ), + "surfacePlanes": surface_mapping["planes"] if surface_mapping is not None else None, + "shadeMap": shade_map, + "showroomShadeMap": showroom_shade_map, + "reflectionMap": reflection_map, + # Anti-aliased coverage, one byte per `mask` pixel in the same order. + "edgeAlpha": edge_alpha.astype(np.uint8) if edge_alpha is not None else None, + "metadata": { + "segmenter": segmenter_metadata_name(), + "edgeAlphaEncoding": "per-mask-index-u8" if edge_alpha is not None else None, + "segmentationModel": models["segmentation"]["name"], + "floorPixels": int(floor_mask.sum()), + "surfacePixels": int(surface_mask.sum()), + "replacedSoftFloorPixels": int(replaced_material_mask.sum()), + "occlusionPixels": int(occlusion_mask.sum()), + "floorDirection": floor_direction, + **sam_metadata, + **edge_metadata, + **mapping_metadata, + "depthEnabled": depth is not None, + "shadingEnabled": shade_map is not None, + "planeFitEnabled": ENABLE_PLANE_FIT, + "multiPlaneSurfacesEnabled": ENABLE_MULTI_PLANE_SURFACES, + "multiPlaneSurfaceCount": len(surface_mapping["planes"]) if surface_mapping is not None else 0, + "multiPlaneNormalsReliable": ( + bool(surface_mapping.get("normalsReliable")) + if surface_mapping is not None else False + ), + "multiPlaneFitModes": ( + [p.get("fitMode") for p in surface_mapping["planes"]] + if surface_mapping is not None else [] + ), + "shadingTransferEnabled": ENABLE_SHADING_TRANSFER or ENABLE_FAST_SHADOW_TRANSFER, + "fastShadowTransferEnabled": ENABLE_FAST_SHADOW_TRANSFER, + "lightingSource": lighting_source, + "lightingTransferVersion": LIGHTING_TRANSFER_VERSION, + "shadeMapEncoding": SHADE_MAP_ENCODING, + "shadeMapStatistics": shade_statistics, + "shadeMapRange": [SHADE_MAP_MIN, SHADE_MAP_MAX], + "shadeMapSize": ( + [int(shade_map.shape[1]), int(shade_map.shape[0])] + if shade_map is not None else None + ), + "showroomShadeMapRange": [SHOWROOM_SHADE_MAP_MIN, SHOWROOM_SHADE_MAP_MAX], + "renderPresetDefaults": { + "preset": "realistic", + "shadingStrength": 0.30, + "reflectionTransfer": True, + "edgeFeatherPixels": 2, + }, + "reflectionTransferEnabled": reflection_map is not None, + "reflectionMapRange": [REFLECTION_MAP_MIN, REFLECTION_MAP_MAX], + "geometryConfidence": plane.get("geometryConfidence", 0.0) if plane else 0.0, + "metricGeometry": bool(plane and plane.get("floorTransform")), + "geometryProvider": ( + plane.get("geometryProvider", geometry.get("provider")) + if plane else geometry.get("provider") + ), + "geometryModel": models["geometry"]["name"], + }, + } + + +def build_wall_segment( + *, + wall_id: int, + wall_index: int, + wall_indices: np.ndarray, + homography, + plane: dict, + lighting_maps: dict | None, + segmentation_model: str, + edge_alpha: np.ndarray | None = None, +) -> dict: + """Bundle dict for one wall. All heavy inputs are prepared by services.wall.pipeline, + which also sets metadata["wallComponentCount"] once every wall is built.""" + shade_map = lighting_maps.get("shadeMap") if lighting_maps else None + showroom_shade_map = lighting_maps.get("showroomShadeMap") if lighting_maps else None + reflection_map = lighting_maps.get("reflectionMap") if lighting_maps else None + mapping_mode = ( + TextureMappingMode.WALL_PLANE if plane.get("surfaceTransform") + else TextureMappingMode.WALL_CONTOUR_HOMOGRAPHY + ) + return { + "id": wall_id, + "className": SurfaceType.WALL, + "surfaceType": SurfaceType.WALL, + "mask": encode_b64(wall_indices), + # Wall masks already exclude (dilated) doors, windows and furniture, so + # a separate occlusion mask would only duplicate that cut-out. + "occlusionMask": None, + "homography": homography, + "floorTransform": plane.get("floorTransform"), + "surfaceTransform": plane.get("surfaceTransform"), + "plane": plane, + # A wall is one plane: its exact pixel -> metres mapping is the 3x3 + # surfaceTransform, so no per-pixel UV arrays are shipped. + "surfaceUv": None, + "surfacePlaneIds": None, + "surfacePlanes": None, + "shadeMap": shade_map, + "showroomShadeMap": showroom_shade_map, + "reflectionMap": reflection_map, + # Coverage per `mask` pixel where the wall shows between the stems of decor (edgeAlpha + # of the floor's format); None keeps the browser's own edge feather. + "edgeAlpha": edge_alpha.astype(np.uint8) if edge_alpha is not None else None, + "metadata": { + "segmenter": segmenter_metadata_name(), + "edgeAlphaEncoding": "per-mask-index-u8" if edge_alpha is not None else None, + "segmentationModel": segmentation_model, + "wallPixels": int(len(wall_indices)), + "wallComponent": wall_index, + "shadingEnabled": shade_map is not None, + "reflectionTransferEnabled": reflection_map is not None, + "textureMappingMode": mapping_mode, + "geometryConfidence": plane.get("geometryConfidence", 0.0), + "geometryProvider": plane.get("geometryProvider"), + "surfaceWidthMeters": plane.get("surfaceWidthMeters"), + "surfaceHeightMeters": plane.get("surfaceHeightMeters"), + "lightingTransferVersion": LIGHTING_TRANSFER_VERSION, + "shadeMapEncoding": SHADE_MAP_ENCODING, + "shadeMapRange": [SHADE_MAP_MIN, SHADE_MAP_MAX], + "shadeMapSize": ( + [int(shade_map.shape[1]), int(shade_map.shape[0])] + if shade_map is not None else None + ), + "showroomShadeMapRange": [SHOWROOM_SHADE_MAP_MIN, SHOWROOM_SHADE_MAP_MAX], + "reflectionMapRange": [REFLECTION_MAP_MIN, REFLECTION_MAP_MAX], + }, + } + + +def build_fallback_segments( + seg_map: np.ndarray, + depth, + models: dict, +) -> list[dict]: + segments = [] + flat_seg = seg_map.ravel() + for seg_id, class_id in enumerate(np.unique(flat_seg)): + indices = np.where(flat_seg == class_id)[0].astype(np.uint32) + if len(indices) < 1000: + continue + segments.append({ + "id": int(seg_id), + "className": class_name_for_id(int(class_id)), + "mask": encode_b64(indices), + "homography": None, + "plane": None, + "shadeMap": None, + "showroomShadeMap": None, + "reflectionMap": None, + "metadata": { + "segmenter": segmenter_metadata_name(), + "segmentationModel": models["segmentation"]["name"], + "depthEnabled": depth is not None, + "shadingEnabled": False, + "planeFitEnabled": ENABLE_PLANE_FIT, + "samRefinementEnabled": ENABLE_SAM_REFINEMENT, + "shadingTransferEnabled": ENABLE_SHADING_TRANSFER, + "reflectionTransferEnabled": False, + }, + }) + return segments diff --git a/apps/renderer/services/pipeline/debug_stages.py b/apps/renderer/services/pipeline/debug_stages.py new file mode 100644 index 0000000000000000000000000000000000000000..06581db9b26f784bcaa931d326247b2d0dedc5fb --- /dev/null +++ b/apps/renderer/services/pipeline/debug_stages.py @@ -0,0 +1,140 @@ +"""Debug recording for each pipeline stage.""" + +from __future__ import annotations + +import numpy as np + +from models.segmentation import active_segmentation_model_name +from services.debug.capture import PipelineDebugCapture +from services.debug.overlays import ( + debug_floor_direction_overlay, + debug_mask_overlay, + debug_plane_id_map, + debug_plane_overlay, + debug_scalar_map, + debug_segmentation_overlay, + debug_surface_overlay, + debug_uv_checkerboard, +) +from state import class_name_for_id + + +def record_source_image(debug: PipelineDebugCapture, img_np, w, h, min_floor_area, elapsed_ms): + debug.record_images( + "source-image", "Uploaded image", + "The RGB image passed to the analysis pipeline.", + [("Source", img_np)], + {"width": int(w), "height": int(h), "minimumFloorPixels": int(min_floor_area)}, + elapsed_ms, + ) + + +def record_segmentation(debug: PipelineDebugCapture, img_np, seg_map, backend, w, h, elapsed_ms): + label_ids, label_counts = np.unique(seg_map, return_counts=True) + class_areas = { + class_name_for_id(int(lid)): int(cnt) + for lid, cnt in zip(label_ids, label_counts) + if int(cnt) >= max(128, int(w * h * 0.001)) + } + debug.record_images( + "semantic-segmentation", "Semantic segmentation", + "Colour overlay of the ADE20K semantic labels used to find the floor and reject room objects.", + [("Class overlay", debug_segmentation_overlay(img_np, seg_map))], + {"backend": backend, "model": active_segmentation_model_name(), "classPixels": class_areas}, + elapsed_ms, + ) + + +def record_floor_mask(debug: PipelineDebugCapture, img_np, raw_mask, cleaned_mask, final_mask, + source, sam_metadata, elapsed_ms): + debug.record_images( + "floor-mask", "Floor mask selection", + "Compare the raw floor prediction with cleanup and optional SAM refinement before geometry is estimated.", + [("Raw floor class", debug_mask_overlay(img_np, raw_mask)), + ("Cleaned candidate", debug_mask_overlay(img_np, cleaned_mask)), + ("Final floor mask", debug_mask_overlay(img_np, final_mask))], + {"selection": source, "rawFloorPixels": int(raw_mask.sum()), + "cleanedFloorPixels": int(cleaned_mask.sum()), "finalFloorPixels": int(final_mask.sum()), + **sam_metadata}, + elapsed_ms, + ) + + +def record_geometry(debug: PipelineDebugCapture, depth, floor_mask, geometry, elapsed_ms): + imgs = [("Depth", debug_scalar_map(depth, floor_mask))] if depth is not None else [] + debug.record_images( + "scene-geometry", "Scene geometry", + "Depth or metric geometry used to fit and validate the floor plane.", + imgs, + {"provider": geometry.get("provider"), "depthAvailable": depth is not None, + "metric": bool(geometry.get("metric"))}, + elapsed_ms, + ) + + +def record_plane(debug: PipelineDebugCapture, img_np, plane, homography, elapsed_ms): + debug.record_images( + "floor-plane", "Floor plane and perspective", + "The fitted floor quadrilateral is the source of the perspective transform used for tile placement.", + [("Fitted quadrilateral", debug_plane_overlay(img_np, plane))], + {"planeFound": plane is not None, "homographyAvailable": homography is not None, + "geometryProvider": plane.get("geometryProvider") if plane else None, + "geometryConfidence": plane.get("geometryConfidence") if plane else 0.0, + "metricGeometry": bool(plane and plane.get("floorTransform")), + "quad": plane.get("quad") if plane else None}, + elapsed_ms, + ) + + +def record_surface(debug: PipelineDebugCapture, img_np, floor_mask, surface_mask, + occlusion_mask, edge_metadata, elapsed_ms): + debug.record_images( + "renderable-surface", "Renderable floor surface", + "Gold pixels are retained for rendering; red pixels were part of the floor mask but removed.", + [("Final surface", debug_surface_overlay(img_np, floor_mask, surface_mask))], + {"floorPixels": int(floor_mask.sum()), "surfacePixels": int(surface_mask.sum()), + "occlusionPixels": int(occlusion_mask.sum()), + "surfaceCoverage": round(float(surface_mask.sum()) / max(int(floor_mask.sum()), 1), 4), + **edge_metadata}, + elapsed_ms, + ) + + +def record_surface_mapping(debug: PipelineDebugCapture, h, w, surface_indices, + surface_mapping, use_surface_uv, metadata, elapsed_ms): + imgs = [] + if use_surface_uv: + imgs.append(("UV checkerboard", debug_uv_checkerboard(h, w, surface_indices, surface_mapping["uv"]))) + imgs.append(("Surface planes", debug_plane_id_map(h, w, surface_indices, surface_mapping["planeIds"]))) + debug.record_images( + "surface-mapping", "Texture-coordinate mapping", + "The checkerboard shows the coordinates sent to the renderer. Plane colours identify separately fitted surface planes.", + imgs, metadata, elapsed_ms, + ) + + +def record_lighting(debug: PipelineDebugCapture, shade_map, showroom_shade_map, + reflection_map, surface_mask, lighting_source, elapsed_ms): + imgs = [] + if shade_map is not None: + imgs.append(("Shade map", debug_scalar_map(shade_map, surface_mask))) + if showroom_shade_map is not None: + imgs.append(("Showroom shade map", debug_scalar_map(showroom_shade_map, surface_mask))) + if reflection_map is not None: + imgs.append(("Reflection map", debug_scalar_map(reflection_map, surface_mask))) + debug.record_images( + "lighting-transfer", "Lighting and reflections", + "Maps transferred from the room image to make the replacement material fit its surrounding light.", + imgs, {"source": lighting_source, "shadingAvailable": shade_map is not None, + "reflectionsAvailable": reflection_map is not None}, + elapsed_ms, + ) + + +def record_direction(debug: PipelineDebugCapture, img_np, floor_direction, elapsed_ms): + debug.record_images( + "floor-direction", "Floor direction", + "Independent material, 3D wall-normal, and architectural cues are scored in renderer coordinates.", + [("Direction analysis", debug_floor_direction_overlay(img_np, floor_direction))], + floor_direction, elapsed_ms, + ) diff --git a/apps/renderer/services/pipeline/inference_utils.py b/apps/renderer/services/pipeline/inference_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4d166ad5289ca1c156436384a186e75acfb05582 --- /dev/null +++ b/apps/renderer/services/pipeline/inference_utils.py @@ -0,0 +1,44 @@ +"""Helpers for downscaling images before inference and upscaling results back.""" + +import cv2 +import numpy as np +from PIL import Image + +from config.runtime import INFERENCE_MAX_DIMENSION + + +def downscale_for_inference( + img: Image.Image, + img_np: np.ndarray, +) -> tuple[Image.Image, np.ndarray, float]: + """Downscale image to INFERENCE_MAX_DIMENSION for model inference. + + Returns (resized_pil, resized_np, scale_factor). + scale_factor is 1.0 if no resizing was needed. + """ + h, w = img_np.shape[:2] + largest = max(h, w) + if largest <= INFERENCE_MAX_DIMENSION: + return img, img_np, 1.0 + + scale = INFERENCE_MAX_DIMENSION / float(largest) + new_w = max(1, int(round(w * scale))) + new_h = max(1, int(round(h * scale))) + + resized_pil = img.resize((new_w, new_h), Image.Resampling.LANCZOS) + resized_np = np.array(resized_pil) + return resized_pil, resized_np, scale + + +def upscale_mask(mask: np.ndarray, target_h: int, target_w: int) -> np.ndarray: + """Upscale a segmentation mask back to original resolution using nearest-neighbor.""" + if mask.shape[0] == target_h and mask.shape[1] == target_w: + return mask + return cv2.resize(mask, (target_w, target_h), interpolation=cv2.INTER_NEAREST) + + +def upscale_depth(depth: np.ndarray, target_h: int, target_w: int) -> np.ndarray: + """Upscale a depth map back to original resolution using bicubic interpolation.""" + if depth.shape[0] == target_h and depth.shape[1] == target_w: + return depth + return cv2.resize(depth, (target_w, target_h), interpolation=cv2.INTER_CUBIC) diff --git a/apps/renderer/services/pipeline/packaging.py b/apps/renderer/services/pipeline/packaging.py new file mode 100644 index 0000000000000000000000000000000000000000..0f6ce70ce9e1c68756b45a4c6afc6e2e337ac35a --- /dev/null +++ b/apps/renderer/services/pipeline/packaging.py @@ -0,0 +1,253 @@ +"""Bundle encoding, mask compression, and manifest packaging utilities.""" + +from __future__ import annotations + +import base64 +import io +import json +import zipfile + +import cv2 +import numpy as np +from PIL import Image + +from config.paths import JOB_DIR +from config.runtime import BUNDLE_IMAGE_FORMAT, BUNDLE_IMAGE_QUALITY +from state import OCCLUDER_CLASSES, class_ids +from utils import seg_class_mask + + +# --------------------------------------------------------------------------- +# Image encoding helpers +# --------------------------------------------------------------------------- + +def encode_bundle_image_data_url(img_np: np.ndarray) -> str: + image_format = BUNDLE_IMAGE_FORMAT + if image_format in {"jpg", "jpeg"}: + pil_format = "JPEG" + mime_type = "image/jpeg" + extension = "jpg" + elif image_format == "webp": + pil_format = "WEBP" + mime_type = "image/webp" + extension = "webp" + else: + pil_format = "JPEG" + mime_type = "image/jpeg" + extension = "jpg" + + image = Image.fromarray(img_np.astype(np.uint8)) + buffer = io.BytesIO() + try: + save_kwargs = { + "quality": int(np.clip(BUNDLE_IMAGE_QUALITY, 1, 100)), + "optimize": True, + } + if pil_format == "WEBP": + save_kwargs["method"] = 4 + image.save(buffer, format=pil_format, **save_kwargs) + except Exception as exc: + print(f"Bundle {extension} encoding failed ({exc}); falling back to JPEG.", flush=True) + buffer = io.BytesIO() + image.save(buffer, format="JPEG", quality=92, optimize=True) + mime_type = "image/jpeg" + + encoded = base64.b64encode(buffer.getvalue()).decode() + return f"data:{mime_type};base64,{encoded}" + + +def data_url_to_bytes(value: str) -> tuple[str, bytes]: + if value.startswith("data:"): + header, encoded = value.split(",", 1) + mime_type = header[5:].split(";", 1)[0] or "application/octet-stream" + return mime_type, base64.b64decode(encoded) + return "application/octet-stream", base64.b64decode(value) + + +def bundle_image_extension(mime_type: str) -> str: + if mime_type == "image/webp": + return "webp" + if mime_type == "image/png": + return "png" + return "jpg" + + +# --------------------------------------------------------------------------- +# Binary reference / mask helpers +# --------------------------------------------------------------------------- + +def make_binary_ref(path: str, data: bytes, dtype: str) -> dict: + return { + "path": path, + "dtype": dtype, + "byteLength": len(data), + } + + +def encode_surface_uv_asset(value) -> tuple[bytes, dict]: + """Quantize smooth metric UV pairs and delta-code them for HTTP gzip.""" + if isinstance(value, np.ndarray): + surface_uv = np.asarray(value, dtype=np.float32).reshape(-1) + elif isinstance(value, str): + surface_uv = np.frombuffer(base64.b64decode(value), dtype=np.float32) + else: + surface_uv = np.frombuffer(bytes(value), dtype=np.float32) + + if surface_uv.size == 0 or surface_uv.size % 2: + data = surface_uv.astype(" 0, uv_scale, 1.0) + quantized = np.full(uv_pairs.shape, 65535, dtype=np.uint16) + finite_quantized = np.rint((finite_uv - uv_offset) / safe_scale) + quantized[valid_pairs] = np.clip(finite_quantized, 0, 65534).astype(np.uint16) + + delta = np.empty_like(quantized) + if len(quantized): + delta[0] = quantized[0] + if len(quantized) > 1: + difference = quantized[1:].astype(np.int32) - quantized[:-1].astype(np.int32) + delta[1:] = np.bitwise_and(difference, 0xFFFF).astype(np.uint16) + + data = delta.astype(" bytes: + """Encode uint32 pixel indices as an exact, least-significant-bit-first bitset.""" + indices = np.frombuffer(mask_bytes, dtype=np.uint32) + if indices.size and int(indices.max()) >= pixel_count: + raise ValueError("Mask contains a pixel index outside the source image.") + + bits = np.zeros(pixel_count, dtype=np.uint8) + bits[indices] = 1 + return np.packbits(bits, bitorder="little").tobytes() + + +def foreground_occlusion_mask(surface_mask: np.ndarray, seg_map: np.ndarray) -> np.ndarray: + h, w = surface_mask.shape[:2] + kern_size = max(5, min(h, w) // 180) | 1 + kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kern_size, kern_size)) + occluder_mask = seg_class_mask(seg_map, class_ids(OCCLUDER_CLASSES)) + if not occluder_mask.any() or not surface_mask.any(): + return np.zeros((h, w), dtype=np.uint8) + + near_surface = cv2.dilate(surface_mask.astype(np.uint8), kern, iterations=5) + # The surface's own (anti-aliased) edge pixels are never hidden behind an occluder. + return ((occluder_mask > 0) & (near_surface > 0) & (surface_mask == 0)).astype(np.uint8) + + +# --------------------------------------------------------------------------- +# Manifest / zip bundle +# --------------------------------------------------------------------------- + +def build_manifest_segmentation_bundle( + bundle: dict, + job_id: str, + *, + image_url: str | None = None, + include_image: bool = False, +) -> bytes: + metadata = dict(bundle) + metadata["format"] = "baetes-vizbundle" + metadata["bundleVersion"] = 3 + metadata["encoding"] = "zip-store" + metadata["assetBaseUrl"] = f"/viz2d/jobs/{job_id}/assets/" + metadata["pixels"] = None + if image_url: + metadata["imageUrl"] = image_url + metadata["segments"] = [] + asset_dir = JOB_DIR / f"{job_id}.assets" + asset_dir.mkdir(parents=True, exist_ok=True) + + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_STORED) as archive: + if include_image: + pixels_mime, pixels = data_url_to_bytes(bundle["pixels"]) + image_path = f"image.{bundle_image_extension(pixels_mime)}" + archive.writestr(image_path, pixels) + metadata["pixels"] = { + "path": image_path, + "mimeType": pixels_mime, + "byteLength": len(pixels), + } + + lazy_asset_fields = { + "surfacePlaneIds": ("surface-plane-ids.u8", "uint8"), + "shadeMap": ("shade.u8", "uint8"), + "showroomShadeMap": ("showroom-shade.u8", "uint8"), + "reflectionMap": ("reflection.u8", "uint8"), + "edgeAlpha": ("edge-alpha.u8", "uint8"), + } + + for segment_index, segment in enumerate(bundle.get("segments", [])): + segment_metadata = dict(segment) + pixel_count = int(metadata["width"]) * int(metadata["height"]) + for mask_field in ("mask", "occlusionMask"): + mask_value = segment.get(mask_field) + if mask_value: + mask_bytes = base64.b64decode(mask_value) + mask_bitset = encode_mask_bitset(mask_bytes, pixel_count) + mask_path = f"segments/{segment_index}/{mask_field}.bitset" + archive.writestr(mask_path, mask_bitset) + segment_metadata[mask_field] = { + **make_binary_ref(mask_path, mask_bitset, "bitset"), + "encoding": "bitset-lsb0", + "pixelCount": pixel_count, + } + print( + f"[BUNDLE] Compressed {mask_field} for job {job_id}: " + f"{len(mask_bytes)} -> {len(mask_bitset)} bytes", + flush=True, + ) + surface_uv = segment.get("surfaceUv") + if surface_uv is not None: + data, encoding_metadata = encode_surface_uv_asset(surface_uv) + extension = "u16" if encoding_metadata["dtype"] == "uint16" else "f32" + asset_path = f"segments/{segment_index}/surface-uv.{extension}" + archive.writestr(asset_path, data) + segment_metadata["surfaceUv"] = { + **make_binary_ref(asset_path, data, encoding_metadata["dtype"]), + **encoding_metadata, + } + for field, (filename, dtype) in lazy_asset_fields.items(): + value = segment.get(field) + if value is None: + continue + # Accept both raw numpy arrays and base64-encoded strings + if isinstance(value, np.ndarray): + data = value.tobytes() + elif isinstance(value, str): + data = base64.b64decode(value) + else: + data = bytes(value) + asset_path = f"segments/{segment_index}/{filename}" + archive.writestr(asset_path, data) + segment_metadata[field] = { + **make_binary_ref(asset_path, data, dtype), + } + metadata["segments"].append(segment_metadata) + + archive.writestr( + "metadata.json", + json.dumps(metadata, separators=(",", ":")).encode("utf-8"), + ) + + return buffer.getvalue() diff --git a/apps/renderer/services/pipeline/preview_builder.py b/apps/renderer/services/pipeline/preview_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..edf71aeac2a415027d0d452119daabaf45f3afd5 --- /dev/null +++ b/apps/renderer/services/pipeline/preview_builder.py @@ -0,0 +1,139 @@ +"""Fast preview pipeline — ~3s segmentation-only bundle for immediate user interaction. + +Runs segmentation at 512px, skips depth/UV/intrinsic lighting, and uses basic +luminance shading. Returns a minimal vizbundle that the frontend can render +while the full HD pipeline runs in the background. +""" + +from __future__ import annotations + +import io +import time + +import cv2 +import numpy as np +from PIL import Image + +from models.segmentation import run_segmentation +from services.floor.mask import build_floor_surface_mask, clean_floor_mask, wall_subtract +from services.floor.detection import estimate_floor_plane +from services.lighting.shading import build_luminance_lighting_maps, lighting_map_statistics +from services.pipeline.packaging import encode_bundle_image_data_url, foreground_occlusion_mask +from services.pipeline.bundle_assembly import build_fallback_segments, build_floor_segment +from services.pipeline.inference_utils import downscale_for_inference +from direction_finder import find_floor_direction +import state +from state import FLOOR_SURFACE_CLASSES, PRIMARY_FLOOR_CLASSES, REPLACEABLE_SOFT_FLOOR_CLASSES, class_ids +from enums import FloorMaskSource, GeometryProvider +from utils import mask_to_indices, seg_class_mask + +PREVIEW_MAX_DIM = 512 + + +def _downscale_to(img: Image.Image, img_np: np.ndarray, max_dim: int): + """Downscale for preview inference at a fixed small size.""" + h, w = img_np.shape[:2] + largest = max(h, w) + if largest <= max_dim: + return img, img_np, 1.0 + scale = max_dim / float(largest) + new_w = max(1, int(round(w * scale))) + new_h = max(1, int(round(h * scale))) + resized_pil = img.resize((new_w, new_h), Image.Resampling.LANCZOS) + resized_np = np.array(resized_pil) + return resized_pil, resized_np, scale + + +def build_preview_bundle(contents: bytes) -> dict: + """Build a fast preview bundle (seg + basic shading, no depth/UV).""" + t_start = time.perf_counter() + + img = Image.open(io.BytesIO(contents)).convert("RGB") + img_np = np.array(img) + h, w = img_np.shape[:2] + min_floor_area = max(1200, int(w * h * 0.015)) + + # Downscale aggressively for speed + inf_img, inf_np, _ = _downscale_to(img, img_np, PREVIEW_MAX_DIM) + + # Segmentation at 512px, output at full res + seg_map = run_segmentation(inf_img, inf_np, target_h=h, target_w=w) + + # Floor masking (no SAM2) + pixels_b64 = encode_bundle_image_data_url(img_np) + raw_primary = seg_class_mask(seg_map, class_ids(PRIMARY_FLOOR_CLASSES)) + floor_mask = clean_floor_mask(wall_subtract(raw_primary.copy(), seg_map, dilation=0)) + floor_mask_source = FloorMaskSource.PRIMARY_FLOOR + if int(floor_mask.sum()) < min_floor_area: + floor_mask = clean_floor_mask(wall_subtract( + seg_class_mask(seg_map, class_ids(FLOOR_SURFACE_CLASSES)), seg_map, dilation=0)) + floor_mask_source = FloorMaskSource.FLOOR_SURFACE_FALLBACK + + # Homography-only plane (no depth) + geometry = { + "provider": GeometryProvider.HOMOGRAPHY, + "points": None, "depth": None, "normals": None, + "validMask": None, "intrinsics": None, + } + homography, plane = estimate_floor_plane(floor_mask, img_np, geometry) + + # Surface mask + quad = np.asarray(plane["quad"], dtype=np.float32).reshape(4, 2) if plane and plane.get("quad") else None + surface_mask, edge_metadata = build_floor_surface_mask(floor_mask, seg_map, quad, None, geometry, plane) + replaced_material_mask = (seg_class_mask(seg_map, class_ids(REPLACEABLE_SOFT_FLOOR_CLASSES)).astype(bool) & (surface_mask > 0)).astype(np.uint8) + surface_indices = mask_to_indices(surface_mask) + occlusion_mask = foreground_occlusion_mask(surface_mask, seg_map) + occlusion_indices = mask_to_indices(occlusion_mask) + + # Basic luminance shading (fast, CPU-only) + lighting_maps = build_luminance_lighting_maps(img_np, surface_mask, replaced_material_mask) + shade_map = lighting_maps.get("shadeMap") if lighting_maps else None + showroom_shade_map = lighting_maps.get("showroomShadeMap") if lighting_maps else None + reflection_map = lighting_maps.get("reflectionMap") if lighting_maps else None + shade_statistics = lighting_map_statistics(shade_map, surface_mask) + + # Minimal floor direction + wall_mask = seg_class_mask(seg_map, class_ids({"wall"})) + struct_mask = seg_class_mask(seg_map, class_ids({"wall", "ceiling", "door", "window", "column", "base", "railing"})) + floor_direction = find_floor_direction( + img_np, surface_mask, wall_mask=wall_mask, + structure_mask=struct_mask, + normals_map=None, geometry_valid_mask=None, + intrinsics=None, floor_normal=None, + render_u_axis=None, render_v_axis=None, + render_transform=homography, + surface_uv=None, surface_indices=None, surface_plane_ids=None, + ) + + # Package + sam_metadata = {"samRefinementEnabled": False, "samRefinementApplied": False, "samRefinementReason": "preview"} + mapping_metadata = {"surfaceUvEnabled": False, "textureMappingMode": "regularized-floor-plane"} + models = { + "segmentation": {"backend": state.segmentation_backend, "name": "oneformer-preview"}, + "geometry": {"provider": GeometryProvider.HOMOGRAPHY, "name": None}, + "depth": {"enabled": False, "name": None}, + "intrinsic": {"enabled": False, "name": None}, + } + + segments = [] + if len(surface_indices) >= min_floor_area: + segments.append(build_floor_segment( + surface_indices=surface_indices, occlusion_indices=occlusion_indices, + homography=homography, plane=plane, surface_mapping=None, + use_surface_uv=False, shade_map=shade_map, + showroom_shade_map=showroom_shade_map, reflection_map=reflection_map, + floor_mask=floor_mask, surface_mask=surface_mask, + replaced_material_mask=replaced_material_mask, occlusion_mask=occlusion_mask, + floor_direction=floor_direction, sam_metadata=sam_metadata, + edge_metadata=edge_metadata, mapping_metadata=mapping_metadata, + shade_statistics=shade_statistics, lighting_source="luminance", + intrinsic_lighting_used=False, models=models, depth=None, geometry=geometry)) + if not segments: + segments = build_fallback_segments(seg_map, None, models) + + total_elapsed = time.perf_counter() - t_start + print(f"[PREVIEW] Built in {total_elapsed:.2f}s ({w}x{h}, inference@{PREVIEW_MAX_DIM}px)", flush=True) + + return {"width": w, "height": h, "pixels": pixels_b64, "segments": segments, + "modelName": models["segmentation"]["name"], "models": models, + "isPreview": True} diff --git a/apps/renderer/services/spaces/__init__.py b/apps/renderer/services/spaces/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f8fd3344ee3a05cec9fbba61fc929ac6067e8f --- /dev/null +++ b/apps/renderer/services/spaces/__init__.py @@ -0,0 +1 @@ +# DigitalOcean Spaces upload services. diff --git a/apps/renderer/services/spaces/upload.py b/apps/renderer/services/spaces/upload.py new file mode 100644 index 0000000000000000000000000000000000000000..37bee4702775e0d6f8046f15f86efd2397e6f102 --- /dev/null +++ b/apps/renderer/services/spaces/upload.py @@ -0,0 +1,107 @@ +"""DigitalOcean Spaces helpers: upload input images, create S3 clients.""" + +import time +import urllib.parse +from pathlib import Path + +from config.spaces import ( + SPACES_ACCESS_KEY_ID, + SPACES_ACL, + SPACES_BUCKET, + SPACES_ENDPOINT_URL, + SPACES_REGION, + SPACES_SECRET_ACCESS_KEY, + SPACES_UPLOAD_PREFIX, +) +from errors import service_unavailable +from services.jobs.store import read_job, write_job + + +def spaces_upload_enabled() -> bool: + return bool(SPACES_BUCKET and SPACES_REGION and SPACES_ACCESS_KEY_ID and SPACES_SECRET_ACCESS_KEY) + + +def spaces_endpoint_url() -> str: + return SPACES_ENDPOINT_URL or f"https://{SPACES_REGION}.digitaloceanspaces.com" + + +def spaces_upload_key(job_id: str, upload_path: Path) -> str: + suffix = upload_path.suffix.lower() + if suffix not in {".jpg", ".jpeg", ".png", ".webp"}: + suffix = ".jpg" + date_prefix = time.strftime("%Y/%m/%d", time.gmtime()) + filename = f"{job_id}{suffix}" + return "/".join(part for part in [SPACES_UPLOAD_PREFIX, date_prefix, filename] if part) + + +def upload_input_image_to_spaces( + job_id: str, + upload_path: Path, + original_filename: str | None, + content_type: str | None, +): + if not spaces_upload_enabled(): + return + + try: + import boto3 + from botocore.config import Config + except ImportError: + print("DigitalOcean Spaces upload skipped; install boto3 to enable object storage.", flush=True) + return + + try: + key = spaces_upload_key(job_id, upload_path) + metadata = {"job-id": job_id} + if original_filename: + metadata["original-filename"] = urllib.parse.quote(original_filename)[:900] + + extra_args = { + "ContentType": content_type or "application/octet-stream", + "Metadata": metadata, + } + if SPACES_ACL: + extra_args["ACL"] = SPACES_ACL + + client = boto3.client( + "s3", + region_name=SPACES_REGION, + endpoint_url=spaces_endpoint_url(), + aws_access_key_id=SPACES_ACCESS_KEY_ID, + aws_secret_access_key=SPACES_SECRET_ACCESS_KEY, + config=Config(signature_version="s3v4"), + ) + client.upload_file(str(upload_path), SPACES_BUCKET, key, ExtraArgs=extra_args) + + job = read_job(job_id) + job["inputObjectStorage"] = { + "provider": "digitalocean-spaces", + "bucket": SPACES_BUCKET, + "region": SPACES_REGION, + "key": key, + "endpointUrl": spaces_endpoint_url(), + } + write_job(job) + print(f"Uploaded input image for job {job_id} to DigitalOcean Spaces: {SPACES_BUCKET}/{key}", flush=True) + except Exception as exc: + print(f"DigitalOcean Spaces upload failed for job {job_id}: {exc}", flush=True) + + +def spaces_client(): + if not spaces_upload_enabled(): + service_unavailable("DigitalOcean Spaces is not configured.") + + try: + import boto3 + from botocore.config import Config + except ImportError as exc: + service_unavailable("Install boto3 to use DigitalOcean Spaces QA images.", exc) + + return boto3.client( + "s3", + region_name=SPACES_REGION, + endpoint_url=spaces_endpoint_url(), + aws_access_key_id=SPACES_ACCESS_KEY_ID, + aws_secret_access_key=SPACES_SECRET_ACCESS_KEY, + config=Config(signature_version="s3v4"), + ) diff --git a/apps/renderer/services/wall/__init__.py b/apps/renderer/services/wall/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..810cee956ce51782f24deda5866ee7f04f095c06 --- /dev/null +++ b/apps/renderer/services/wall/__init__.py @@ -0,0 +1 @@ +# Wall surface detection, plane estimation, and component extraction services. diff --git a/apps/renderer/services/wall/components.py b/apps/renderer/services/wall/components.py new file mode 100644 index 0000000000000000000000000000000000000000..f90d0757c294d6c63736ced84df8e0759b50ed5f --- /dev/null +++ b/apps/renderer/services/wall/components.py @@ -0,0 +1,323 @@ +"""Wall discovery: split the semantic wall mask into one region per physical wall. + +Functions +--------- +discover_wall_components - wall regions (full-res masks + fitted planes) for a room + +Splitting and plane fitting run on a strided copy of the segmentation and +geometry maps (long side <= WALL_WORK_MAX_DIMENSION). Each wall's final +outline, like the floor's, comes from the full-resolution segmentation; the +low-resolution pieces only decide which wall owns each pixel. Walls use their +own plane budget (WALL_MAX_PLANES), so the floor's `max_planes` is never touched. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass + +import cv2 +import numpy as np + +from config.models import DEPTH_MODEL_NAME +from config.surface import ( + SURFACE_MIN_PLANE_PIXELS, + SURFACE_NORMAL_SMOOTHING_KERNEL, + WALL_COPLANAR_ANGLE_DEGREES, + WALL_COPLANAR_OFFSET_METERS, + WALL_EDGE_STRAIGHTEN_RATIO, + WALL_MAX_NORMAL_Y, + WALL_MAX_PLANES, + WALL_MAX_SEGMENTS, + WALL_WORK_MAX_DIMENSION, +) +from services.geometry.camera import backproject_depth, pixel_intrinsics_from_model +from services.geometry.multi_plane import assign_points_to_surface_planes, fit_multi_surface_planes +from services.geometry.normals import compute_normals_from_points, normalize_vectors, smooth_normal_map +from services.geometry.plane_fitting import refine_plane +from services.image.polygons import straighten_mask_edges +from state import OCCLUDER_CLASSES, PRIMARY_FLOOR_CLASSES, class_ids +from utils import seg_class_mask + +# Classes cut out of walls before splitting; they bridge physically separate walls. +WALL_PROTECTED_CLASSES = OCCLUDER_CLASSES | { + "door", "window", "column", "base", "railing", "ceiling", + "building", "painting", "mirror", "curtain", +} +# Morphology radius as a fraction of the short image side (matches the old full-res value). +# Only used to separate walls at working resolution, never to cut the final outline. +PROTECTED_DILATION_RATIO = 0.006 +# Light speck cleanup of the full-resolution outline (fraction of the short side). +OUTLINE_CLEANUP_RATIO = 0.002 +# Wall ownership is taken from pieces blurred by this many working-res pixels per +# dilation radius, so the separation margin is filled and wall seams are smooth. +OWNERSHIP_SIGMA_SCALE = 1.5 +OWNERSHIP_MIN_WEIGHT = 0.02 +# Points sampled when refitting each wall's final plane. +PLANE_REFIT_SAMPLES = 20000 +MIN_DEPTH_METERS = 0.05 + + +@dataclass(frozen=True) +class WallPlane: + origin: np.ndarray + normal: np.ndarray + + +@dataclass +class WallComponent: + mask: np.ndarray # full-resolution uint8 mask + work_mask: np.ndarray # same wall at working resolution + plane: WallPlane | None + area: int # full-resolution pixel count + + +@dataclass +class WallDiscovery: + components: list[WallComponent] + vertical: np.ndarray # unit "up" direction (camera +Y hemisphere) from the floor + stride: int + geometry_used: bool + + +def discover_wall_components(seg_map: np.ndarray, geometry: dict | None, min_area: int) -> WallDiscovery: + """Find up to WALL_MAX_SEGMENTS walls, ordered left to right.""" + full_h, full_w = seg_map.shape[:2] + stride = max(1, math.ceil(max(full_h, full_w) / WALL_WORK_MAX_DIMENSION)) + seg_low = seg_map[::stride, ::stride] + min_area_low = max(1, min_area // (stride * stride)) + + wall_low = _clean_wall_mask(seg_low) + point_maps = _working_point_maps(geometry, stride, full_w, full_h) + vertical = _vertical_reference(seg_low, point_maps) + + pieces: list[tuple[np.ndarray, WallPlane | None]] = [] + count, labels, stats, _ = cv2.connectedComponentsWithStats(wall_low, connectivity=8) + for region_id in range(1, count): + if int(stats[region_id, cv2.CC_STAT_AREA]) < min_area_low: + continue + region = labels == region_id + pieces.extend(_split_region(region, point_maps, min_area_low)) + + pieces.sort(key=lambda piece: int(piece[0].sum()), reverse=True) + pieces = pieces[:WALL_MAX_SEGMENTS] + pieces.sort(key=lambda piece: float(np.nonzero(piece[0])[1].mean())) + + wall_full = _full_resolution_wall_mask(seg_map) + owner = _wall_owner_map([piece for piece, _ in pieces], seg_low.shape, full_w, full_h) + tolerance = WALL_EDGE_STRAIGHTEN_RATIO * min(full_h, full_w) + claimed = np.zeros((full_h, full_w), dtype=bool) + components = [] + for index, (work_mask, plane) in enumerate(pieces): + mask = ((owner == index) & wall_full).astype(np.uint8) + # Architectural edges are straight: redraw the outline as lines. Where two + # straightened walls overlap at a corner, the earlier wall keeps the pixels. + mask = straighten_mask_edges(mask, tolerance, min_area=(2.0 * tolerance) ** 2) + mask[claimed] = 0 + area = int(mask.sum()) + if area < min_area: + continue + claimed |= mask > 0 + components.append(WallComponent(mask=mask, work_mask=work_mask.astype(np.uint8), plane=plane, area=area)) + + return WallDiscovery( + components=components, + vertical=vertical, + stride=stride, + geometry_used=point_maps is not None, + ) + + +def _clean_wall_mask(seg_low: np.ndarray) -> np.ndarray: + """Working-res wall mask with protected classes cut out (with a margin, so + walls touching only across a door or column separate).""" + wall = seg_class_mask(seg_low, class_ids({"wall"})) + protected = seg_class_mask(seg_low, class_ids(WALL_PROTECTED_CLASSES)) + radius = max(1, int(round(min(seg_low.shape[:2]) * PROTECTED_DILATION_RATIO))) + kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius * 2 + 1, radius * 2 + 1)) + protected = cv2.dilate(protected, kernel, iterations=1) + wall[protected > 0] = 0 + wall = cv2.morphologyEx(wall, cv2.MORPH_CLOSE, kernel) + wall = cv2.morphologyEx(wall, cv2.MORPH_OPEN, kernel) + wall[protected > 0] = 0 + return wall + + +def _working_point_maps(geometry: dict | None, stride: int, full_w: int, full_h: int): + """Strided (points, normals, valid) maps, or None when there is no metric geometry.""" + if geometry is None: + return None + points = geometry.get("points") + if points is not None: + points = points[::stride, ::stride].astype(np.float32, copy=False) + valid = geometry.get("validMask") + valid = valid[::stride, ::stride].astype(bool) if valid is not None else np.ones(points.shape[:2], bool) + else: + depth = geometry.get("depth") + provider = str(geometry.get("provider") or "") + if depth is None or ("metric" not in DEPTH_MODEL_NAME.lower() and "metric" not in provider.lower()): + return None + depth = depth[::stride, ::stride].astype(np.float32) + intrinsics = pixel_intrinsics_from_model(geometry.get("intrinsics"), full_w, full_h).copy() + intrinsics[:2, :] /= stride + points = backproject_depth(depth, intrinsics) + valid = np.ones(depth.shape, bool) + + valid &= np.isfinite(points).all(axis=2) & (points[:, :, 2] > MIN_DEPTH_METERS) + if not valid.any(): + return None + + normals = geometry.get("normals") + if normals is not None and normals.shape[:2] == (full_h, full_w): + normals = smooth_normal_map(normals[::stride, ::stride], SURFACE_NORMAL_SMOOTHING_KERNEL) + else: + normals = compute_normals_from_points(points, valid, SURFACE_NORMAL_SMOOTHING_KERNEL) + valid &= np.linalg.norm(normals, axis=2) > 1e-4 + return points, normals, valid + + +def _vertical_reference(seg_low: np.ndarray, point_maps) -> np.ndarray: + """Room "up" axis from floor normals, oriented like camera +Y (the renderer's v).""" + fallback = np.array([0.0, 1.0, 0.0], dtype=np.float32) + if point_maps is None: + return fallback + _, normals, valid = point_maps + floor = (seg_class_mask(seg_low, class_ids(PRIMARY_FLOOR_CLASSES)) > 0) & valid + if int(floor.sum()) < SURFACE_MIN_PLANE_PIXELS // 4: + return fallback + up = np.median(normals[floor], axis=0).astype(np.float32) + length = float(np.linalg.norm(up)) + if length < 1e-4: + return fallback + up /= length + return up if up[1] >= 0 else -up + + +def _split_region(region: np.ndarray, point_maps, min_area_low: int) -> list[tuple[np.ndarray, WallPlane | None]]: + """Split one connected wall region into per-plane pieces.""" + if point_maps is None: + return [(region, None)] + points_map, normals_map, valid_map = point_maps + valid = region & valid_map + ys, xs = np.nonzero(valid) + if len(ys) < SURFACE_MIN_PLANE_PIXELS: + return [(region, None)] + points = points_map[ys, xs] + normals = normalize_vectors(normals_map[ys, xs]) + + planes = fit_multi_surface_planes(points, normals, True, max_planes=WALL_MAX_PLANES) + planes = _merge_coplanar([p for p in planes if abs(float(p["normal"][1])) <= WALL_MAX_NORMAL_Y]) + if len(planes) <= 1: + return [(region, _refit_plane(points, normals))] + + assignment = assign_points_to_surface_planes(points, normals, planes, True) + labels = np.full(region.shape, -1, dtype=np.int32) + labels[ys, xs] = assignment + _fill_unassigned(labels, region) + + pieces = [] + for plane_index in range(len(planes)): + count, components, stats, _ = cv2.connectedComponentsWithStats( + (labels == plane_index).astype(np.uint8), connectivity=8, + ) + for component_id in range(1, count): + if int(stats[component_id, cv2.CC_STAT_AREA]) < min_area_low: + continue + piece = components == component_id + piece_valid = piece & valid_map + pieces.append((piece, _refit_plane(points_map[piece_valid], normals_map[piece_valid]))) + return pieces or [(region, _refit_plane(points, normals))] + + +def _merge_coplanar(planes: list[dict]) -> list[dict]: + """Drop planes that describe the same flat wall as a larger plane already kept.""" + min_cos = float(np.cos(np.deg2rad(WALL_COPLANAR_ANGLE_DEGREES))) + kept: list[dict] = [] + for plane in sorted(planes, key=lambda p: p["inlierCount"], reverse=True): + normal = np.asarray(plane["normal"], dtype=np.float32) + origin = np.asarray(plane["origin"], dtype=np.float32) + duplicate = any( + abs(float(normal @ k["normal"])) >= min_cos + and abs(float((origin - k["origin"]) @ k["normal"])) <= WALL_COPLANAR_OFFSET_METERS + for k in kept + ) + if not duplicate: + kept.append(plane) + return kept + + +def _fill_unassigned(labels: np.ndarray, region: np.ndarray) -> None: + """Give region pixels without valid geometry the label of their nearest labelled neighbour.""" + kernel = np.ones((3, 3), np.uint8) + unassigned = region & (labels < 0) + while unassigned.any(): + grown = False + for label in np.unique(labels[labels >= 0]): + reach = cv2.dilate((labels == label).astype(np.uint8), kernel) > 0 + take = reach & unassigned + if take.any(): + labels[take] = label + unassigned &= ~take + grown = True + if not grown: + break + + +def _refit_plane(points: np.ndarray, normals: np.ndarray) -> WallPlane | None: + """Least-squares plane over a wall's own points (subsampled), or None if not wall-like.""" + finite = np.isfinite(points).all(axis=1) + points, normals = points[finite], normals[finite] + if len(points) < SURFACE_MIN_PLANE_PIXELS // 4: + return None + if len(points) > PLANE_REFIT_SAMPLES: + step = len(points) // PLANE_REFIT_SAMPLES + points, normals = points[::step], normals[::step] + origin, normal = refine_plane(points, normals) + if abs(float(normal[1])) > WALL_MAX_NORMAL_Y: + return None + return WallPlane(origin=origin.astype(np.float32), normal=normal.astype(np.float32)) + + +def _full_resolution_wall_mask(seg_map: np.ndarray) -> np.ndarray: + """Wall pixels at full resolution with protected classes cut out exactly. + + Mirrors the floor: the outline follows the (smoothly upsampled) semantic + boundary, with only light speck cleanup and no widened margin around + doors, ceilings or furniture. + """ + wall = seg_class_mask(seg_map, class_ids({"wall"})) + protected = seg_class_mask(seg_map, class_ids(WALL_PROTECTED_CLASSES)) > 0 + wall[protected] = 0 + radius = max(1, int(round(min(seg_map.shape[:2]) * OUTLINE_CLEANUP_RATIO))) + kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius * 2 + 1, radius * 2 + 1)) + wall = cv2.morphologyEx(wall, cv2.MORPH_OPEN, kernel) + wall = cv2.morphologyEx(wall, cv2.MORPH_CLOSE, kernel) + wall[protected] = 0 + return wall > 0 + + +def _wall_owner_map( + pieces: list[np.ndarray], + work_shape: tuple[int, int], + full_w: int, + full_h: int, +) -> np.ndarray: + """Full-resolution index of the wall piece each pixel belongs to (-1 for none). + + Each piece is blurred at working resolution so its influence reaches across + the separation margin cut around doors; the argmax then places seams + between neighbouring walls midway and, after linear upscaling, smoothly. + """ + owner = np.full((full_h, full_w), -1, dtype=np.int8) + if not pieces: + return owner + radius = max(1, int(round(min(work_shape) * PROTECTED_DILATION_RATIO))) + sigma = max(1.0, radius * OWNERSHIP_SIGMA_SCALE) + best = np.full((full_h, full_w), OWNERSHIP_MIN_WEIGHT, dtype=np.float32) + for index, piece in enumerate(pieces): + weight = cv2.GaussianBlur(piece.astype(np.float32), (0, 0), sigmaX=sigma, sigmaY=sigma) + weight = cv2.resize(weight, (full_w, full_h), interpolation=cv2.INTER_LINEAR) + wins = weight > best + best[wins] = weight[wins] + owner[wins] = index + return owner diff --git a/apps/renderer/services/wall/edges.py b/apps/renderer/services/wall/edges.py new file mode 100644 index 0000000000000000000000000000000000000000..98183d2806cbe3beea58d6582bbd7012f249556e --- /dev/null +++ b/apps/renderer/services/wall/edges.py @@ -0,0 +1,134 @@ +"""Wall edges around objects in front of it: wallpaper up to their real outline. + +Segmentation marks a bouquet, a lamp or a vase as one coarse blob (and often +with the wrong class: a dried bouquet came back as "bulletin board"), so the +wall mask stopped at a blocky outline and the old wall showed around and +between the stems. Next to each wall, a pixel that lies on the wall's own +plane (by depth) is bare wall; there each pixel is keyed against the bare +wall's colour (filled in from the wall around it), so what still looks like +that wall gets the wallpaper with soft coverage, and every stem, leaf and +object keeps its photographed pixels. Solid things in front of the wall (a +vase, a chair) are off the plane and are never touched. + +Functions +--------- +matte_wall_decor - the wall mask grown into decor, and its per-pixel coverage +""" + +from __future__ import annotations + +import cv2 +import numpy as np + +from state import class_ids +from utils import seg_class_mask + +# Never keyed: the wall's architectural neighbours. +ARCHITECTURE_CLASSES = {"floor", "ceiling", "door", "window", "column", "stairs", "windowpane", "rug", "curtain"} +# How far from the wall pixels may be keyed (fraction of the short side). +DECOR_REACH_RATIO = 0.08 +# On the wall's plane: within this distance of it (metres, or this share of the depth if larger). +PLANE_TOLERANCE_M = 0.04 +PLANE_TOLERANCE_RATIO = 0.015 +# Plane distances are computed on every n-th pixel and interpolated. +PLANE_STRIDE = 2 +# Bare-wall colour estimate resolution (long side, px). +BACKGROUND_SIDE = 640 +BACKGROUND_SIGMA_RATIO = 0.012 # of the long side +# A pixel is decor, not wall, from these differences to the bare wall (OpenCV Lab units): +# colour (a dried flower, a leaf) or brightness well beyond the wall's own shading. +CHROMA_FROM, CHROMA_TO = 6.0, 14.0 +LIGHTNESS_FROM, LIGHTNESS_TO = 24.0, 40.0 +# Pixels the wall covers less than this stay out of the mask. +MIN_COVERAGE = 0.1 +# Matches the browser's own edge feather (edge-weight.ts EDGE_FEATHER_PX), which no longer +# applies once a wall ships its own coverage. +EDGE_FEATHER_PX = 2.0 + + +def _feather(mask: np.ndarray) -> np.ndarray: + """0..1: the browser's edge feather (distance to the nearest outside pixel / 2); the photo border is no edge.""" + padded = cv2.copyMakeBorder(mask, 1, 1, 1, 1, cv2.BORDER_REPLICATE) + distance = cv2.distanceTransform(padded, cv2.DIST_L2, 5)[1:-1, 1:-1] + return np.minimum(distance / EDGE_FEATHER_PX, 1.0).astype(np.float32) + + +def _bare_wall(img_np: np.ndarray, wall: np.ndarray) -> np.ndarray: + """The photo's wall colour everywhere near the wall, spread from the wall's own pixels (Lab, float). + + A masked (normalised) Gaussian blur: each pixel gets the average colour of the + wall around it, so the wall's own shading carries over. A wider pass covers + pixels farther from the wall than the narrow one reaches. + """ + height, width = wall.shape + scale = BACKGROUND_SIDE / max(height, width) + size = (max(8, round(width * scale)), max(8, round(height * scale))) + small = cv2.cvtColor(cv2.resize(img_np, size, interpolation=cv2.INTER_AREA), cv2.COLOR_RGB2LAB).astype(np.float32) + known = cv2.erode(cv2.resize(wall, size, interpolation=cv2.INTER_NEAREST), np.ones((3, 3), np.uint8)).astype(np.float32) + result = np.zeros_like(small) + weight_done = np.zeros(known.shape, np.float32) + for sigma in (BACKGROUND_SIGMA_RATIO * max(size), 4 * BACKGROUND_SIGMA_RATIO * max(size)): + weight = cv2.GaussianBlur(known, (0, 0), sigma) + colour = cv2.GaussianBlur(small * known[..., None], (0, 0), sigma) / np.maximum(weight, 1e-6)[..., None] + take = (weight_done < 0.05) & (weight >= 0.05) + result[take] = colour[take] + weight_done = np.maximum(weight_done, np.where(take, weight, 0)) + return cv2.resize(result, (width, height), interpolation=cv2.INTER_LINEAR) + + +def _on_plane(points: np.ndarray, origin: np.ndarray, normal: np.ndarray, shape: tuple[int, int]) -> np.ndarray: + """0..1 per pixel: how surely its 3D point lies on the wall's plane (full resolution, smooth).""" + sampled = points[::PLANE_STRIDE, ::PLANE_STRIDE].astype(np.float32) + distance = np.abs((sampled - origin.astype(np.float32)) @ normal.astype(np.float32)) + tolerance = np.maximum(PLANE_TOLERANCE_M, PLANE_TOLERANCE_RATIO * np.abs(sampled[..., 2])) + closeness = ((distance <= tolerance) & np.isfinite(distance)).astype(np.float32) + closeness = cv2.resize(closeness, (shape[1], shape[0]), interpolation=cv2.INTER_LINEAR) + # Only anti-aliased (no wider ramp): glass a few centimetres off the wall must stay glass. + return cv2.GaussianBlur(closeness, (0, 0), 0.75) + + +def matte_wall_decor( + img_np: np.ndarray, + seg_map: np.ndarray, + wall: np.ndarray, + points: np.ndarray | None, + plane, +) -> tuple[np.ndarray, np.ndarray | None]: + """(mask, alpha): the wall grown up to the real outline of objects in front of it, and uint8 + coverage per pixel. alpha is None when nothing changes (no depth, no plane, nothing to key).""" + wall = (wall > 0).astype(np.uint8) + if points is None or plane is None or not wall.any() or points.shape[:2] != wall.shape: + return wall, None + short_side = min(wall.shape) + from_wall = cv2.distanceTransform(1 - wall, cv2.DIST_L2, 3) + architecture = seg_class_mask(seg_map, class_ids(ARCHITECTURE_CLASSES)) > 0 + near = (from_wall > 0) & (from_wall <= DECOR_REACH_RATIO * short_side) & ~architecture + if not near.any(): + return wall, None + on_plane = _on_plane(points, plane.origin, plane.normal, wall.shape) + keyed = near & (on_plane > 0.5) + if not keyed.any(): + return wall, None + + bare = _bare_wall(img_np, wall) # already Lab + photo = cv2.cvtColor(img_np, cv2.COLOR_RGB2LAB).astype(np.float32) + chroma = np.hypot(photo[..., 1] - bare[..., 1], photo[..., 2] - bare[..., 2]) + lightness = np.abs(photo[..., 0] - bare[..., 0]) + is_object = np.maximum( + np.clip((chroma - CHROMA_FROM) / (CHROMA_TO - CHROMA_FROM), 0.0, 1.0), + np.clip((lightness - LIGHTNESS_FROM) / (LIGHTNESS_TO - LIGHTNESS_FROM), 0.0, 1.0), + ) + is_object = cv2.GaussianBlur(is_object, (0, 0), 0.7) # anti-aliased stem edges + + keyed_coverage = (1.0 - is_object) * np.clip(2.0 * on_plane - 1.0, 0.0, 1.0) + grown = keyed & (keyed_coverage >= MIN_COVERAGE) + # Only what joins the wall: a patch of wall colour on the far side of a chair is not this wall. + count, labels = cv2.connectedComponents((wall | grown).astype(np.uint8), connectivity=8) + joined = np.isin(labels, np.unique(labels[wall > 0])) + mask = (wall > 0) | (grown & joined) + if int(mask.sum()) == int(wall.sum()): + return wall, None + coverage = np.where(grown & joined, keyed_coverage, _feather(mask.astype(np.uint8))) + coverage[~mask] = 0.0 + alpha = np.clip(np.rint(coverage * 255.0), 0, 255).astype(np.uint8) + return mask.astype(np.uint8), alpha diff --git a/apps/renderer/services/wall/pipeline.py b/apps/renderer/services/wall/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..ce991843aa603c3c5f8842bd84ebabfe3e42709a --- /dev/null +++ b/apps/renderer/services/wall/pipeline.py @@ -0,0 +1,233 @@ +"""Wall stage of the conversion pipeline: one bundle segment per physical wall. + +Functions +--------- +build_wall_segments - discover walls and build their bundle segments + +Designed to run in a background thread alongside the floor stages: all +analysis is at working resolution, and full-resolution work is limited to +each wall's own pixels (mask upscale, index encoding). Each wall's texture +mapping is an exact 3x3 plane transform, so no per-pixel UV is shipped. +""" + +from __future__ import annotations + +import time +from dataclasses import dataclass, field, replace + +import cv2 +import numpy as np + +from config.runtime import ENABLE_FAST_SHADOW_TRANSFER, ENABLE_SHADING_TRANSFER +from config.surface import WALL_UV_MIN_COVERAGE +from services.geometry.camera import backproject_depth, pixel_intrinsics_from_model +from services.geometry.plane_uv import plane_to_image_transform, ray_plane_uv, upright_plane_basis +from services.lighting.shading import build_fast_shadow_lighting_maps, build_luminance_lighting_maps +from services.pipeline.bundle_assembly import build_wall_segment +from services.wall.components import WallComponent, WallDiscovery, discover_wall_components +from services.wall.edges import matte_wall_decor +from services.wall.plane import estimate_wall_plane + +# Wall pixels at least this covered (of 255) count as pure wall when measuring its light. +PURE_WALL_ALPHA = 230 +# Pixels sampled per wall to measure plane coverage and size. +MAPPING_SAMPLE_PIXELS = 20000 + + +@dataclass +class WallResult: + segments: list[dict] = field(default_factory=list) + timings_ms: dict[str, float] = field(default_factory=dict) + + @property + def detail(self) -> str: + parts = [f"walls={len(self.segments)}"] + parts += [f"{name}={ms:.0f}ms" for name, ms in self.timings_ms.items()] + return " ".join(parts) + + +def build_wall_segments( + img_np: np.ndarray, + seg_map: np.ndarray, + geometry: dict | None, + min_area: int, + segmentation_model: str, + first_segment_id: int = 1, +) -> WallResult: + """Discover walls and return their bundle segments (ids start at first_segment_id).""" + result = WallResult() + started = time.perf_counter() + discovery = discover_wall_components(seg_map, geometry, min_area) + result.timings_ms["discovery"] = (time.perf_counter() - started) * 1000 + if not discovery.components: + return result + + started = time.perf_counter() + full_h, full_w = seg_map.shape[:2] + intrinsics = ( + pixel_intrinsics_from_model(geometry.get("intrinsics"), full_w, full_h) + if geometry is not None else None + ) + work_h, work_w = discovery.components[0].work_mask.shape[:2] + work_image = cv2.resize(img_np, (work_w, work_h), interpolation=cv2.INTER_AREA) + + for index, component in enumerate(discovery.components): + segment = _build_segment( + component, + discovery, + index=index, + segment_id=first_segment_id + index, + intrinsics=intrinsics, + geometry=geometry, + img_np=img_np, + seg_map=seg_map, + work_image=work_image, + segmentation_model=segmentation_model, + ) + if segment is not None: + result.segments.append(segment) + for segment in result.segments: + segment["metadata"]["wallComponentCount"] = len(result.segments) + result.timings_ms["segments"] = (time.perf_counter() - started) * 1000 + return result + + +def _build_segment( + component: WallComponent, + discovery: WallDiscovery, + *, + index: int, + segment_id: int, + intrinsics: np.ndarray | None, + geometry: dict | None, + img_np: np.ndarray, + seg_map: np.ndarray, + work_image: np.ndarray, + segmentation_model: str, +) -> dict | None: + # Wallpaper between the stems of flowers and plants in front of the wall. + points = _full_points(geometry, intrinsics, component.mask.shape) + mask, alpha = matte_wall_decor(img_np, seg_map, component.mask, points, component.plane) + if alpha is not None: + component = replace(component, mask=mask, area=int(mask.sum())) + wall_indices = np.flatnonzero(component.mask.ravel()).astype(np.uint32) + mapping = _wall_plane_mapping(component, discovery.vertical, wall_indices, intrinsics) + + # With an exact plane mapping, skip estimate_wall_plane's second RANSAC fit + # and keep only its cheap contour quad as a fallback homography. + homography, plane = estimate_wall_plane(component.mask, None if mapping else geometry) + if homography is None or plane is None: + return None + if mapping: + plane.update(mapping) + plane["geometryProvider"] = (geometry or {}).get("provider") + + return build_wall_segment( + wall_id=segment_id, + wall_index=index, + wall_indices=wall_indices, + homography=homography, + plane=plane, + lighting_maps=_wall_lighting(component, img_np, work_image, alpha), + segmentation_model=segmentation_model, + edge_alpha=alpha.ravel()[wall_indices] if alpha is not None else None, + ) + + +def _full_points(geometry: dict | None, intrinsics: np.ndarray | None, shape: tuple[int, int]) -> np.ndarray | None: + """Camera-space 3D point per pixel (the frame the wall planes were fitted in), or None.""" + if geometry is None: + return None + points = geometry.get("points") + if points is not None and points.shape[:2] == shape: + return points + depth = geometry.get("depth") + if depth is None or intrinsics is None or depth.shape[:2] != shape: + return None + return backproject_depth(depth.astype(np.float32), intrinsics) + + +def _wall_plane_mapping( + component: WallComponent, + vertical: np.ndarray, + wall_indices: np.ndarray, + intrinsics: np.ndarray | None, +) -> dict | None: + """Exact metric plane mapping for the wall, or None to use the contour homography. + + Coverage and the wall's size in metres are measured on a pixel sample; the + renderer gets the 3x3 surfaceTransform, which is exact for every pixel. + """ + if component.plane is None or intrinsics is None or not len(wall_indices): + return None + u_axis, v_axis = upright_plane_basis(component.plane.normal, vertical) + sample = wall_indices[:: max(1, len(wall_indices) // MAPPING_SAMPLE_PIXELS)] + uv, hit = ray_plane_uv( + sample, component.mask.shape[1], intrinsics, + component.plane.origin, component.plane.normal, u_axis, v_axis, + ) + coverage = float(hit.mean()) + if coverage < WALL_UV_MIN_COVERAGE: + return None + + uv_min = np.nanmin(uv, axis=0) + uv_max = np.nanmax(uv, axis=0) + top_v, up_sign = wall_top(uv[:, 1], sample // component.mask.shape[1]) + transform = plane_to_image_transform( + intrinsics, component.plane.origin, component.plane.normal, u_axis, v_axis, + ).flatten().tolist() + return { + "floorTransform": transform, + "surfaceTransform": transform, + "surfaceUAxis": u_axis.astype(float).tolist(), + "surfaceVAxis": v_axis.astype(float).tolist(), + "planeNormal": component.plane.normal.astype(float).tolist(), + "planeOrigin": component.plane.origin.astype(float).tolist(), + "surfaceWidthMeters": float(max(uv_max[0] - uv_min[0], 0.05)), + "surfaceHeightMeters": float(max(uv_max[1] - uv_min[1], 0.05)), + # Murals hang from here: the plane-v (metres) of the wall's visible top + # edge, and whether +v points up (1) or down (-1) on the wall. + "wallTopV": top_v, + "wallUpSign": up_sign, + # The renderer treats the transform as metric at >= 0.35 confidence. + "geometryConfidence": coverage, + } + + +def wall_top(v: np.ndarray, rows: np.ndarray) -> tuple[float, int]: + """The plane-v of the wall's top edge and the sign of "up" along v. + + v is gravity-aligned (upright_plane_basis), so the top edge is one v value. + "Up" is whichever v direction the image rows go up in. A high percentile + rather than the extreme keeps stray mask pixels from setting the top. + """ + valid = np.isfinite(v) + v, rows = v[valid].astype(np.float64), rows[valid].astype(np.float64) + if len(v) < 2 or float(np.std(rows)) < 1e-6: + return float(np.nanmax(v)) if len(v) else 0.0, 1 + up_sign = -1 if float(np.corrcoef(rows, v)[0, 1]) > 0 else 1 + top = np.percentile(v, 99.5) if up_sign > 0 else np.percentile(v, 0.5) + return float(top), up_sign + + +def _wall_lighting( + component: WallComponent, + img_np: np.ndarray, + work_image: np.ndarray, + alpha: np.ndarray | None = None, +) -> dict | None: + """Same lighting switches as the floor; the fast path runs at working resolution. + + The light is measured on pure wall only (never on stems or objects the wall + shows between) and continues past the wall's edge, so no halo forms there. + """ + if ENABLE_FAST_SHADOW_TRANSFER: + work_h, work_w = work_image.shape[:2] + pure = component.mask if alpha is None else (alpha >= PURE_WALL_ALPHA).astype(np.uint8) + work_mask = (cv2.resize(pure.astype(np.float32), (work_w, work_h), interpolation=cv2.INTER_AREA) > 0.99) + maps = build_fast_shadow_lighting_maps(work_image, work_mask.astype(np.uint8), fill_outside=True) + if maps and maps.get("shadeMap") is not None: + return maps + if ENABLE_SHADING_TRANSFER: + return build_luminance_lighting_maps(img_np, component.mask) + return None diff --git a/apps/renderer/services/wall/plane.py b/apps/renderer/services/wall/plane.py new file mode 100644 index 0000000000000000000000000000000000000000..4e2ff890889f61b32f7ac7a881f5d53ea12425f4 --- /dev/null +++ b/apps/renderer/services/wall/plane.py @@ -0,0 +1,140 @@ +"""Wall plane estimation and metric geometry validation. + +Functions +--------- +estimate_wall_plane - compute wall homography from contour analysis +validate_wall_metric_geometry - sanity-check metric wall geometry +""" + +import cv2 +import numpy as np + +from enums import GeometryProvider, SurfaceType +from config.runtime import ENABLE_PLANE_FIT +from services.geometry.plane_fitting import ( + estimate_metric_floor_transform, + fit_metric_floor_transform, +) + + +def estimate_wall_plane(mask: np.ndarray, geometry: dict | None = None): + """Return a stable image-space homography for a semantic wall mask. + + Walls do not currently have metric depth fitting, so use the visible wall + contour as the source quad and its bounding rectangle as the planar target. + This preserves perspective convergence while keeping physical tile sizes + deterministic until wall-specific depth calibration is available. + """ + ys, xs = np.where(mask > 0) + if len(xs) < 1000: + return None, None + + h, w = mask.shape[:2] + contours, _ = cv2.findContours((mask > 0).astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + contour = max(contours, key=cv2.contourArea) if contours else None + if contour is None or cv2.contourArea(contour) < 1000: + return None, None + + perimeter = cv2.arcLength(contour, True) + approx = cv2.approxPolyDP(contour, max(2.0, perimeter * 0.02), True) + if len(approx) >= 4: + points = approx.reshape(-1, 2).astype(np.float32) + hull = cv2.convexHull(points) + if len(hull) >= 4: + points = hull.reshape(-1, 2) + else: + points = np.empty((0, 2), dtype=np.float32) + + if len(points) != 4: + rect = cv2.minAreaRect(contour) + points = cv2.boxPoints(rect).astype(np.float32) + + # Order corners as top-left, top-right, bottom-right, bottom-left. + sums = points.sum(axis=1) + diffs = points[:, 1] - points[:, 0] + ordered = np.float32([ + points[np.argmin(sums)], + points[np.argmin(diffs)], + points[np.argmax(sums)], + points[np.argmax(diffs)], + ]) + x1, y1 = float(np.min(ordered[:, 0])), float(np.min(ordered[:, 1])) + x2, y2 = float(np.max(ordered[:, 0])), float(np.max(ordered[:, 1])) + if x2 - x1 < 20 or y2 - y1 < 20: + return None, None + + destination = np.float32([[x1, y1], [x2, y1], [x2, y2], [x1, y2]]) + homography = cv2.getPerspectiveTransform(ordered, destination).flatten().tolist() + metric_geometry = None + if ENABLE_PLANE_FIT and geometry: + points = geometry.get("points") + if points is not None: + metric_geometry = fit_metric_floor_transform( + mask, + points, + geometry.get("validMask"), + geometry.get("normals"), + geometry.get("intrinsics"), + geometry.get("provider", GeometryProvider.METRIC_DEPTH), + surface_kind="wall", + ) + if metric_geometry is None: + metric_geometry = estimate_metric_floor_transform( + mask, + geometry.get("depth"), + geometry.get("provider", GeometryProvider.DEPTH_ANYTHING), + geometry.get("intrinsics"), + surface_kind="wall", + ) + + plane = { + "x": x1, + "y": y1, + "width": x2 - x1, + "height": y2 - y1, + "quad": ordered.flatten().tolist(), + "geometryConfidence": 0.45, + "geometryProvider": GeometryProvider.WALL_CONTOUR_HOMOGRAPHY, + "floorTransform": None, + "surfaceTransform": None, + "surfaceType": SurfaceType.WALL, + "surfaceWidthMeters": max(0.5, 2.4 * (x2 - x1) / max(y2 - y1, 1.0)), + "surfaceHeightMeters": 2.4, + "metersPerUnit": None, + "cameraIntrinsics": None, + "camera": {"focalLength": float(max(h, w) * 0.95), "horizonY": y1, "confidence": 0.45}, + } + if metric_geometry and not validate_wall_metric_geometry(metric_geometry): + print( + "[WALL_GEOMETRY] rejected metric wall fit; using contour homography " + f"confidence={metric_geometry.get('geometryConfidence')} " + f"normal={metric_geometry.get('planeNormal')} " + f"size={metric_geometry.get('surfaceWidthMeters')}x{metric_geometry.get('surfaceHeightMeters')}", + flush=True, + ) + metric_geometry = None + + if metric_geometry: + plane.update(metric_geometry) + plane["surfaceType"] = SurfaceType.WALL + plane["geometryProvider"] = metric_geometry.get("geometryProvider", GeometryProvider.WALL_DEPTH) + return homography, plane + + +def validate_wall_metric_geometry(geometry: dict) -> bool: + confidence = float(geometry.get("geometryConfidence") or 0.0) + normal = np.asarray(geometry.get("planeNormal") or [], dtype=np.float32) + width = float(geometry.get("surfaceWidthMeters") or 0.0) + height = float(geometry.get("surfaceHeightMeters") or 0.0) + if confidence < 0.45 or normal.shape != (3,) or not np.isfinite(normal).all(): + return False + # In the indoor coordinate system Y is vertical; a wall normal should be + # mostly horizontal, unlike the floor normal. + normal /= max(float(np.linalg.norm(normal)), 1e-6) + if abs(float(normal[1])) > 0.45: + return False + if not (0.25 <= width <= 30.0 and 0.25 <= height <= 15.0): + return False + if width / max(height, 1e-6) > 20.0 or height / max(width, 1e-6) > 20.0: + return False + return True diff --git a/apps/renderer/start.sh b/apps/renderer/start.sh new file mode 100644 index 0000000000000000000000000000000000000000..7ed9707ae8357cca3228428588785460bf2546aa --- /dev/null +++ b/apps/renderer/start.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# Startup script for the floor visualizer backend. +# Run once after cloning the repo on the server. + +set -e + +echo "==> Installing dependencies..." +pip install --no-cache-dir -r requirements-gpu-cu126.txt + +echo "==> Creating data directories..." +mkdir -p data/uploads data/jobs + +echo "==> Starting server..." +VISUALIZER_CONFIG=visualizer.gpu.toml uvicorn app:app --host 0.0.0.0 --port 8002 --workers 1 diff --git a/apps/renderer/state.py b/apps/renderer/state.py new file mode 100644 index 0000000000000000000000000000000000000000..44603c0ee329202ad015d62d923e6c48683702a7 --- /dev/null +++ b/apps/renderer/state.py @@ -0,0 +1,94 @@ +"""Mutable global model state and semantic class definitions.""" + +import os +import threading +from contextlib import nullcontext + +import torch + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + +# Serialises model inference on the single GPU while letting the CPU-bound +# pipeline stages of concurrent jobs overlap. Re-entrant so nested calls +# (e.g. warm-up -> run_segmentation) are safe. +_gpu_inference_lock = threading.RLock() + + +def gpu_inference(): + """Context manager guarding GPU model calls; a no-op on CPU, where the + pipeline deliberately runs segmentation and geometry in parallel.""" + return _gpu_inference_lock if device.type == "cuda" else nullcontext() + +# Model references (populated lazily by models/loader.py) +seg_processor = None +seg_model = None +segmentation_backend = "oneformer" +depth_processor = None +depth_model = None +moge_model = None +sam2_predictor = None +intrinsic_models = None + +# ONNX Runtime sessions (populated lazily by models/onnx_loader.py) +seg_onnx_session = None +depth_onnx_session = None + +ADE20K_CLASSES = [ + "wall", "building", "sky", "floor", "tree", "ceiling", "road", "bed", + "window", "grass", "cabinet", "sidewalk", "person", "ground", "door", + "table", "mountain", "plant", "curtain", "chair", "car", "water", + "painting", "sofa", "shelf", "house", "sea", "mirror", "rug", "field", + "armchair", "seat", "fence", "desk", "rock", "wardrobe", "lamp", + "bathtub", "railing", "cushion", "base", "box", "column", "signboard", + "chest of drawers", "counter", "sand", "sink", "skyscraper", "fireplace", + "refrigerator", "stairs", "runway", "bookcase", "blind", "coffee table", + "toilet", "flower", "book", "hill", "bench", "countertop", "stove", + "palm", "kitchen island", "computer", "swivel chair", "boat", "bar", + "arcade machine", "hovel", "bus", "towel", "light", "truck", "tower", + "chandelier", "awning", "streetlight", "booth", "television", "airplane", + "dirt track", "apparel", "pole", "land", "bannister", "escalator", + "ottoman", "bottle", "buffet", "poster", "stage", "van", "ship", + "fountain", "conveyer belt", "canopy", "washer", "plaything", + "swimming pool", "stool", "barrel", "basket", "waterfall", "tent", + "bag", "minibike", "cradle", "oven", "ball", "food", "step", "tank", + "trade name", "microwave", "pot", "animal", "bicycle", "lake", + "dishwasher", "screen", "blanket", "sculpture", "hood", "sconce", + "vase", "traffic light", "tray", "ashcan", "fan", "pier", "crt screen", + "plate", "monitor", "bulletin board", "shower", "radiator", "glass", + "clock", "flag", +] + +PRIMARY_FLOOR_CLASSES = {"floor", "rug", "carpet", "mat"} +REPLACEABLE_SOFT_FLOOR_CLASSES = {"rug", "carpet", "mat"} +FLOOR_SURFACE_CLASSES = { + "floor", "road", "sidewalk", "ground", "field", "grass", "sand", + "runway", "dirt track", "land", "stairs", "step", "rug", "carpet", "mat", +} +REJECT_SURFACE_CLASSES = {"wall", "ceiling", "building", "sky", "window"} +# TODO: This set is empty — all downstream soft_covering_mask logic in floor/mask.py is currently a no-op. +# Populate with class names (e.g. {"rug", "carpet"}) if soft-covering removal is needed. +SOFT_FLOOR_COVERING_CLASSES: set[str] = set() +OCCLUDER_CLASSES = { + "bed", "cabinet", "person", "door", "table", "plant", "curtain", "chair", + "car", "painting", "sofa", "shelf", "mirror", "armchair", "seat", "desk", + "wardrobe", "lamp", "bathtub", "railing", "cushion", "base", "box", + "column", "chest of drawers", "counter", "sink", "fireplace", + "refrigerator", "bookcase", "blind", "coffee table", "toilet", "bench", + "countertop", "stove", "kitchen island", "computer", "swivel chair", + "bar", "ottoman", "bottle", "buffet", "poster", "towel", "television", + "washer", "plaything", "stool", "basket", "bag", "cradle", "oven", + "ball", "food", "microwave", "pot", "dishwasher", "blanket", "sculpture", + "vase", "tray", "fan", "plate", "monitor", "shower", "radiator", "clock", +} + + +def hf_offline() -> bool: + return os.getenv("HF_HUB_OFFLINE") == "1" or os.getenv("TRANSFORMERS_OFFLINE") == "1" + + +def class_name_for_id(class_id: int) -> str: + return ADE20K_CLASSES[class_id] if class_id < len(ADE20K_CLASSES) else f"class_{class_id}" + + +def class_ids(names: set[str]) -> list[int]: + return [idx for idx, name in enumerate(ADE20K_CLASSES) if name in names] diff --git a/apps/renderer/test_access_policy.py b/apps/renderer/test_access_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..37ccf8bf47ac71ad1c0c38bdc096b5e8127f4810 --- /dev/null +++ b/apps/renderer/test_access_policy.py @@ -0,0 +1,132 @@ +"""Access policy for the rendering service (no models required). + + python -m unittest test_access_policy +""" + +import importlib +import os +import time +import unittest +from unittest import mock + +import jwt +from fastapi import Depends, FastAPI +from fastapi.testclient import TestClient + +SECRET = "test-processing-secret-0123456789abcdef012" + + +def make_token(role="client", sub="user-1", *, secret=SECRET, aud="prevision-processing", exp_offset=600, + iss="prevision-api"): + now = int(time.time()) + return jwt.encode( + {"iss": iss, "aud": aud, "sub": sub, "role": role, "iat": now, "exp": now + exp_offset}, + secret, + algorithm="HS256", + ) + + +def load_policy(enforcement: str): + env = {"AUTH_ENFORCEMENT": enforcement, "PROCESSING_TOKEN_SECRET": SECRET} + with mock.patch.dict(os.environ, env): + import config.auth + import services.access.policy + + importlib.reload(config.auth) + return importlib.reload(services.access.policy) + + +def build_app(policy): + app = FastAPI() + jobs = {"mine": {"ownerId": "user-1"}, "theirs": {"ownerId": "user-2"}, "legacy": {}} + + @app.post("/convert") + def convert(principal=Depends(policy.require_client)): + return {"job": policy.owner_fields(principal)} + + @app.get("/jobs/{job_id}") + def job(job_id: str, principal=Depends(policy.require_client)): + policy.ensure_job_access(jobs[job_id], principal) + return {"ok": True} + + @app.get("/admin") + def admin(_=Depends(policy.require_admin)): + return {"ok": True} + + return TestClient(app) + + +def bearer(token): + return {"Authorization": f"Bearer {token}"} + + +class EnforcementOffTest(unittest.TestCase): + def setUp(self): + self.client = build_app(load_policy("off")) + + def test_public_flow_keeps_working(self): + self.assertEqual(self.client.post("/convert").json(), {"job": {}}) + self.assertEqual(self.client.get("/jobs/theirs").status_code, 200) + + def test_admin_routes_are_protected_even_when_off(self): + self.assertEqual(self.client.get("/admin").status_code, 401) + self.assertEqual(self.client.get("/admin", headers=bearer(make_token())).status_code, 403) + self.assertEqual(self.client.get("/admin", headers=bearer(make_token(role="superadmin"))).status_code, 200) + + def test_valid_token_still_records_owner(self): + response = self.client.post("/convert", headers=bearer(make_token())) + self.assertEqual(response.json(), {"job": {"ownerId": "user-1"}}) + + def test_bad_token_is_ignored(self): + response = self.client.post("/convert", headers=bearer(make_token(secret="x" * 40))) + self.assertEqual(response.status_code, 200) + + +class EnforcementOnTest(unittest.TestCase): + def setUp(self): + self.client = build_app(load_policy("on")) + + def test_token_required(self): + response = self.client.post("/convert") + self.assertEqual(response.status_code, 401) + self.assertEqual(response.headers["www-authenticate"], "Bearer") + + def test_rejects_forged_expired_and_wrong_audience_tokens(self): + for token in ( + make_token(secret="y" * 40), + make_token(exp_offset=-120), + make_token(aud="something-else"), + make_token(iss="foreign-product"), + "not-a-jwt", + ): + self.assertEqual(self.client.post("/convert", headers=bearer(token)).status_code, 401, token) + self.assertEqual(self.client.post("/convert", headers=bearer(make_token(role="customer"))).status_code, 403) + + def test_owner_or_admin_only(self): + client_token = bearer(make_token()) + self.assertEqual(self.client.get("/jobs/mine", headers=client_token).status_code, 200) + self.assertEqual(self.client.get("/jobs/theirs", headers=client_token).status_code, 404) + self.assertEqual(self.client.get("/jobs/legacy", headers=client_token).status_code, 404) + admin_token = bearer(make_token(role="superadmin", sub="admin-1")) + for job in ("mine", "theirs", "legacy"): + self.assertEqual(self.client.get(f"/jobs/{job}", headers=admin_token).status_code, 200) + + def test_admin_routes(self): + self.assertEqual(self.client.get("/admin", headers=bearer(make_token())).status_code, 403) + self.assertEqual(self.client.get("/admin", headers=bearer(make_token(role="superadmin"))).status_code, 200) + + def test_foreign_issuer_and_widget_role_are_rejected(self): + self.assertEqual(self.client.post("/convert", headers=bearer(make_token(iss="baetes-accounts"))).status_code, 401) + self.assertEqual(self.client.post("/convert", headers=bearer(make_token(iss="baetes-widget"))).status_code, 401) + self.assertEqual(self.client.post("/convert", headers=bearer(make_token(role="widget"))).status_code, 403) + + def test_enforcement_requires_a_secret(self): + with mock.patch.dict(os.environ, {"AUTH_ENFORCEMENT": "on", "PROCESSING_TOKEN_SECRET": "short"}): + import config.auth + + with self.assertRaises(RuntimeError): + importlib.reload(config.auth) + + +if __name__ == "__main__": + unittest.main() diff --git a/apps/renderer/test_fast_shadow_transfer.py b/apps/renderer/test_fast_shadow_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..f225d7b518782501214c5b8b47abe0f11c8bf034 --- /dev/null +++ b/apps/renderer/test_fast_shadow_transfer.py @@ -0,0 +1,36 @@ +"""Focused regression checks for the low-cost room-shadow extraction path.""" + +import unittest + +import numpy as np + +from config.lighting import SHADE_MAP_MAX, SHADE_MAP_MIN +from config.runtime import FAST_SHADOW_MAX_DIMENSION +from services.lighting.luminance import decode_relative_map +from services.lighting.shading import build_fast_shadow_lighting_maps + + +class FastShadowTransferTests(unittest.TestCase): + def test_returns_compact_map_that_preserves_a_cast_shadow(self): + height, width = 1200, 1600 + image = np.full((height, width, 3), 190, dtype=np.uint8) + image[650:1050, 850:1250] = 70 + mask = np.zeros((height, width), dtype=np.uint8) + mask[400:1150, 100:1500] = 1 + + result = build_fast_shadow_lighting_maps(image, mask) + + self.assertIsNotNone(result) + shade_map = result["shadeMap"] + self.assertLessEqual(max(shade_map.shape), FAST_SHADOW_MAX_DIMENSION) + self.assertLess(shade_map.size, height * width) + decoded = decode_relative_map(shade_map, SHADE_MAP_MIN, SHADE_MAP_MAX) + shadow = decoded[int(850 * shade_map.shape[0] / height), int(1050 * shade_map.shape[1] / width)] + lit = decoded[int(850 * shade_map.shape[0] / height), int(450 * shade_map.shape[1] / width)] + self.assertLess(shadow, lit) + self.assertIsNone(result["showroomShadeMap"]) + self.assertIsNone(result["reflectionMap"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/apps/renderer/test_free_tries.py b/apps/renderer/test_free_tries.py new file mode 100644 index 0000000000000000000000000000000000000000..30a43fde4f25f16576785e74a8c93c1da8aa84a1 --- /dev/null +++ b/apps/renderer/test_free_tries.py @@ -0,0 +1,129 @@ +"""Prevision free tries as seen by the renderer (no models required). + + python -m unittest test_free_tries + +A tiny in-process HTTP server stands in for the Prevision API's internal routes. +""" + +import importlib +import json +import os +import threading +import time +import unittest +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from unittest import mock + +import jwt +from fastapi import HTTPException + +SECRET = "test-processing-secret-0123456789abcdef012" + + +class FakePrevisionApi(BaseHTTPRequestHandler): + remaining = 0 + calls: list = [] + + def log_message(self, *args): # keep test output quiet + pass + + def do_POST(self): + token = self.headers.get("Authorization", "").removeprefix("Bearer ") + try: + jwt.decode(token, SECRET, algorithms=["HS256"], audience="prevision-internal") + except jwt.PyJWTError: + return self._reply(401, {"error": {"code": "UNAUTHENTICATED"}}) + body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}") + FakePrevisionApi.calls.append((self.path, body)) + if self.path == "/internal/generations": + if FakePrevisionApi.remaining <= 0: + return self._reply(402, {"error": {"code": "NO_FREE_TRIES"}}) + FakePrevisionApi.remaining -= 1 + return self._reply(201, {"success": True, "data": {"generationId": f"gen-{body['jobId']}"}}) + if self.path.endswith("/refund"): + return self._reply(204, None) + return self._reply(404, {}) + + def _reply(self, status, body): + self.send_response(status) + payload = b"" if body is None else json.dumps(body).encode() + self.send_header("Content-Length", str(len(payload))) + self.end_headers() + self.wfile.write(payload) + + +def load(url): + env = {"AUTH_ENFORCEMENT": "on", "PROCESSING_TOKEN_SECRET": SECRET, "PREVISION_API_INTERNAL_URL": url} + with mock.patch.dict(os.environ, env): + import config.auth + import services.access.policy + import services.access.usage + + importlib.reload(config.auth) + policy = importlib.reload(services.access.policy) + return policy, importlib.reload(services.access.usage) + + +def token(iss, sub="user-1", role="client"): + now = int(time.time()) + return jwt.encode( + {"iss": iss, "aud": "prevision-processing", "sub": sub, "role": role, "iat": now, "exp": now + 600}, + SECRET, + algorithm="HS256", + ) + + +class FreeTriesTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.server = ThreadingHTTPServer(("127.0.0.1", 0), FakePrevisionApi) + threading.Thread(target=cls.server.serve_forever, daemon=True).start() + cls.policy, cls.usage = load(f"http://127.0.0.1:{cls.server.server_port}") + + @classmethod + def tearDownClass(cls): + cls.server.shutdown() + cls.server.server_close() + + def setUp(self): + FakePrevisionApi.calls = [] + FakePrevisionApi.remaining = 2 + + def test_only_prevision_tokens_are_accepted(self): + principal = self.policy.decode_processing_token(token("prevision-api")) + self.assertTrue(principal.has_free_tries) + for issuer in ("baetes-accounts", "baetes-widget", "someone-else"): + with self.assertRaises(HTTPException) as refused: + self.policy.decode_processing_token(token(issuer)) + self.assertEqual(refused.exception.status_code, 401) + + def test_charges_prevision_jobs_until_the_tries_run_out(self): + principal = self.policy.decode_processing_token(token("prevision-api")) + self.assertEqual(self.usage.charge_free_try(principal, "job1"), "gen-job1") + self.assertEqual(self.usage.charge_free_try(principal, "job2"), "gen-job2") + with self.assertRaises(HTTPException) as refused: + self.usage.charge_free_try(principal, "job3") + self.assertEqual(refused.exception.status_code, 402) + self.assertEqual(FakePrevisionApi.calls[0], ("/internal/generations", {"userId": "user-1", "jobId": "job1"})) + + def test_anonymous_jobs_are_never_charged(self): + self.assertIsNone(self.usage.charge_free_try(None, "job1")) + self.assertEqual(FakePrevisionApi.calls, []) + + def test_refund_after_a_failed_job(self): + self.usage.refund_free_try("gen-job1") + self.assertEqual(FakePrevisionApi.calls, [("/internal/generations/gen-job1/refund", {})]) + self.usage.refund_free_try(None) + self.assertEqual(len(FakePrevisionApi.calls), 1) + + def test_no_free_job_when_the_prevision_api_is_down(self): + principal = self.policy.decode_processing_token(token("prevision-api")) + # Nothing listens on the discard port. + with mock.patch.object(self.usage, "PREVISION_API_INTERNAL_URL", "http://127.0.0.1:9"): + with self.assertRaises(HTTPException) as unavailable: + self.usage.charge_free_try(principal, "job1") + self.assertEqual(unavailable.exception.status_code, 503) + + +if __name__ == "__main__": + unittest.main() diff --git a/apps/renderer/test_gemini_enhance.py b/apps/renderer/test_gemini_enhance.py new file mode 100644 index 0000000000000000000000000000000000000000..6c7836e1b0e36dee454cd5095675c324cb633100 --- /dev/null +++ b/apps/renderer/test_gemini_enhance.py @@ -0,0 +1,245 @@ +"""'Enhance with AI': feature gate, pattern guard, rate limit (no models, Gemini stubbed). + + python -m unittest test_gemini_enhance +""" + +import base64 +import importlib +import io +import os +import time +import unittest +from unittest import mock + +import jwt +import numpy as np +from fastapi import FastAPI +from fastapi.testclient import TestClient +from PIL import Image, ImageFilter + +SECRET = "test-processing-secret-0123456789abcdef012" + + +def make_token(role="client", feat=None, org="org-1"): + now = int(time.time()) + claims = {"iss": "baetes-accounts", "aud": "prevision-processing", "sub": "user-1", "role": role, + "iat": now, "exp": now + 600, "org": org} + if feat is not None: + claims["feat"] = feat + return jwt.encode(claims, SECRET, algorithm="HS256") + + +def pattern_image(size=(480, 320), seed=1) -> Image.Image: + """A room-like render: a busy repeating motif on a wall and a dark 'sideboard'.""" + rng = np.random.default_rng(seed) + tile = (rng.random((24, 24)) * 255).astype(np.uint8) + tile = np.asarray(Image.fromarray(tile).filter(ImageFilter.GaussianBlur(1.2))) + wall = np.tile(tile, (size[1] // 24 + 1, size[0] // 24 + 1))[: size[1], : size[0]] + rgb = np.stack([wall, wall * 0.8, wall * 0.6], axis=-1).astype(np.uint8) + rgb[size[1] * 2 // 3 :, size[0] // 4 : size[0] * 3 // 4] = 40 + return Image.fromarray(rgb) + + +def jpeg_bytes(image: Image.Image) -> bytes: + buffer = io.BytesIO() + image.save(buffer, format="JPEG", quality=92) + return buffer.getvalue() + + +def png_bytes(image: Image.Image) -> bytes: + buffer = io.BytesIO() + image.save(buffer, format="PNG") + return buffer.getvalue() + + +def load_modules(): + env = {"AUTH_ENFORCEMENT": "off", "PROCESSING_TOKEN_SECRET": SECRET, "GEMINI_API_KEY": "test-key"} + with mock.patch.dict(os.environ, env): + import config.auth + import config.gemini + import routes.gemini + import services.access.policy + import services.gemini.client + import services.gemini.enhance + + for module in (config.auth, config.gemini, services.access.policy, services.gemini.client, + services.gemini.enhance, routes.gemini): + importlib.reload(module) + return services.gemini.enhance, routes.gemini + + +class StructureGuardTest(unittest.TestCase): + def setUp(self): + self.enhance, _ = load_modules() + + def test_shading_and_small_fills_pass(self): + render = pattern_image() + shaded = np.asarray(render, dtype=np.float32) + shaded *= np.linspace(0.75, 1.0, shaded.shape[1])[None, :, None] # vignette-like light + shaded[200:215, 150:300] = shaded[180:195, 150:300] # a filled gap + shaded = Image.fromarray(np.clip(shaded, 0, 255).astype(np.uint8)) + self.assertGreater(self.enhance.structure_similarity(render, shaded), 0.8) + self.assertAlmostEqual(self.enhance.structure_similarity(render, render), 1.0, places=5) + + def test_a_redrawn_pattern_fails(self): + render = pattern_image(seed=1) + redesigned = pattern_image(seed=7) + self.assertLess(self.enhance.structure_similarity(render, redesigned), 0.5) + + def test_papering_a_plain_wall_is_caught_but_filled_gaps_are_not(self): + render = np.asarray(pattern_image(), dtype=np.uint8).copy() + render[:, 330:] = 225 # a plain wall the shopper left alone + patterned = np.asarray(pattern_image(seed=3)) + papered = render.copy() + papered[:, 330:] = patterned[:, 330:] + gaps = render.copy() + for x in range(340, 470, 40): # thin strips, like wall between chair slats + gaps[120:300, x:x + 3] = patterned[120:300, x:x + 3] + as_image = Image.fromarray + self.assertGreater(self.enhance.invented_pattern(as_image(render), as_image(papered)), 0.1) + self.assertLess(self.enhance.invented_pattern(as_image(render), as_image(gaps)), 0.004) + self.assertEqual(self.enhance.invented_pattern(as_image(render), as_image(render)), 0.0) + + def test_a_design_moved_to_another_wall_is_caught_but_relighting_is_not(self): + render = np.asarray(pattern_image(), dtype=np.float32) + relit = render * np.linspace(0.6, 1.0, render.shape[1])[None, :, None] + swapped = render.copy() + swapped[:, 240:] = swapped[:, 240:, ::-1] # the right wall painted in the other design's colours + as_image = lambda array: Image.fromarray(np.clip(array, 0, 255).astype(np.uint8)) + self.assertLess(self.enhance.recoloured_area(as_image(render), as_image(relit)), 0.03) + self.assertGreater(self.enhance.recoloured_area(as_image(render), as_image(swapped)), 0.3) + + def test_editable_region_takes_filled_gaps_and_leaves_the_rest_alone(self): + render = np.full((200, 300, 3), 200, np.uint8) + patterned = np.asarray(pattern_image((300, 200))) + surfaces = np.zeros((200, 300), np.uint8) + surfaces[20:120, 40:130] = 1 # wall A, over a floating sideboard + surfaces[60:70, 80:86] = 0 # wall seen between two chair backs + surfaces[20:100, 170:260] = 1 # wall B, over a door + render[surfaces == 1] = patterned[surfaces == 1] + floor = np.zeros_like(surfaces) + floor[150:] = 1 + region = self.enhance.editable_region(surfaces, floor) + filled = render.copy() + filled[120:150, 40:130] = patterned[120:150, 40:130] # Gemini papered the strip under the sideboard + filled[100:106, 200:230] = patterned[100:106, 200:230] # and a sliver of the door + alpha = self.enhance.blend_weights(region, Image.fromarray(render), Image.fromarray(filled)) + self.assertGreater(alpha[65, 83], 0.9) # the small hole + self.assertGreater(alpha[135, 85], 0.9) # the filled strip under wall A + self.assertLess(alpha[125, 215], 0.01) # the door under wall B: keeps the render + self.assertLess(alpha[175, 150], 0.01) # the floor + self.assertLess(alpha[60, 150], 0.01) # between the walls: a window, a person + self.assertLess(alpha[3, 150], 0.01) # the ceiling + + def test_relight_keeps_our_design_and_takes_geminis_light(self): + render = pattern_image() + surfaces = np.ones((320, 480), np.uint8) + ours = np.asarray(render, np.float32) + light = np.linspace(0.7, 1.0, 480, dtype=np.float32)[None, :, None] + washed = ours.mean(axis=-1, keepdims=True) * 0.7 + ours * 0.3 # Gemini drains the colour + candidate = Image.fromarray(np.clip(washed * light, 0, 255).astype(np.uint8)) + lit = self.enhance.relight(render, candidate, surfaces) + expected = ours * light + self.assertLess(np.abs(lit - expected)[20:-20, 20:-20].mean(), 6) # our colours, Gemini's light + self.assertGreater(np.abs(np.asarray(candidate, np.float32) - expected)[20:-20, 20:-20].mean(), 8) + + def test_rate_limit_window(self): + limiter = self.enhance.RateLimiter(per_hour=2) + self.assertTrue(limiter.allow("org", now=0)) + self.assertTrue(limiter.allow("org", now=1)) + self.assertFalse(limiter.allow("org", now=2)) + self.assertTrue(limiter.allow("other", now=2)) + self.assertTrue(limiter.allow("org", now=3602)) + + def test_references_only_from_our_cdn(self): + self.assertTrue(self.enhance.reference_allowed( + "https://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/tiles/x/image.jpg")) + for url in ("http://baetes-space-bucket.sfo3.cdn.digitaloceanspaces.com/a.jpg", + "https://169.254.169.254/latest", "https://evil.example/a.jpg", "file:///etc/passwd"): + self.assertFalse(self.enhance.reference_allowed(url), url) + + +class EnhanceRouteTest(unittest.TestCase): + def setUp(self): + self.enhance, self.route = load_modules() + app = FastAPI() + app.include_router(self.route.router) + self.http = TestClient(app) + self.render = pattern_image() + self.body = { + "image": "data:image/jpeg;base64," + base64.b64encode(jpeg_bytes(self.render)).decode(), + "surfaces": [{"name": "Wall 1", "kind": "wall", "tileName": "Dahlia Garden", "widthMm": 530, "heightMm": 530, + "position": "the far left"}], + } + + def post(self, token=None, gemini_output=None): + output = jpeg_bytes(gemini_output if gemini_output is not None else self.render.resize((960, 640))) + calls = [] + + def fake_call(images, prompt, **kwargs): + calls.append((images, prompt, kwargs)) + return output, "image/jpeg" + + headers = {"Authorization": f"Bearer {token}"} if token else {} + with mock.patch.object(self.enhance, "call_gemini_image", fake_call): + response = self.http.post("/gemini/refine-tile-render", json=self.body, headers=headers) + return response, calls + + def test_needs_a_token_even_with_enforcement_off(self): + response, calls = self.post() + self.assertEqual(response.status_code, 401) + self.assertEqual(calls, []) + + def test_organizations_without_the_feature_are_refused(self): + for token in (make_token(), make_token(feat=[]), make_token(feat=["other"]), + make_token(role="widget", feat=["ai_refinement"])): + response, calls = self.post(token) + self.assertIn(response.status_code, (403,), response.text) + self.assertEqual(calls, []) + + def test_enabled_organization_gets_the_image_at_render_size(self): + response, calls = self.post(make_token(feat=["ai_refinement"])) + self.assertEqual(response.status_code, 200, response.text) + data = response.json() + image = Image.open(io.BytesIO(base64.b64decode(data["image"].split(",", 1)[1]))) + self.assertEqual(image.size, self.render.size) + self.assertEqual(data["attempts"], 1) + images, prompt, kwargs = calls[0] + self.assertIn("Dahlia Garden", prompt) + self.assertIn("53 x 53 cm", prompt) + self.assertIn("Wall 1 (the far left of the image)", prompt) + self.assertEqual(kwargs["aspect_ratio"], "3:2") + + def test_with_a_mask_only_the_covered_surfaces_come_from_gemini(self): + mask = np.zeros((320, 480, 3), np.uint8) + mask[:150, :, 0] = 255 # the wall + self.body["mask"] = "data:image/png;base64," + base64.b64encode(png_bytes(Image.fromarray(mask))).decode() + shaded = np.asarray(self.render, np.float32) * 0.85 # Gemini darkens everything + response, _ = self.post(make_token(feat=["ai_refinement"]), gemini_output=Image.fromarray(shaded.astype(np.uint8))) + self.assertEqual(response.status_code, 200, response.text) + image = np.asarray(Image.open(io.BytesIO(base64.b64decode(response.json()["image"].split(",", 1)[1]))), np.float32) + original = np.asarray(self.render, np.float32) + self.assertLess(np.abs(image[260:, :] - original[260:, :]).mean(), 3) # outside: the render, unchanged + self.assertGreater(np.abs(image[:100, :] - original[:100, :]).mean(), 8) # the wall: Gemini's shading + + def test_admins_may_use_it(self): + response, _ = self.post(make_token(role="superadmin")) + self.assertEqual(response.status_code, 200, response.text) + + def test_a_changed_pattern_is_retried_then_refused(self): + response, calls = self.post(make_token(feat=["ai_refinement"]), gemini_output=pattern_image(seed=9)) + self.assertEqual(response.status_code, 422, response.text) + self.assertEqual(response.json()["detail"]["code"], "PATTERN_CHANGED") + self.assertEqual(len(calls), 2) + self.assertIn("previous answer moved a design", calls[1][1]) + + def test_rate_limited_per_organization(self): + self.enhance.rate_limiter.per_hour = 1 + self.enhance.rate_limiter._hits.clear() + self.assertEqual(self.post(make_token(feat=["ai_refinement"]))[0].status_code, 200) + self.assertEqual(self.post(make_token(feat=["ai_refinement"]))[0].status_code, 429) + self.assertEqual(self.post(make_token(feat=["ai_refinement"], org="org-2"))[0].status_code, 200) + + +if __name__ == "__main__": + unittest.main() diff --git a/apps/renderer/test_geometry_optimization.py b/apps/renderer/test_geometry_optimization.py new file mode 100644 index 0000000000000000000000000000000000000000..71e209f422b88d375d766116775f718abc679c74 --- /dev/null +++ b/apps/renderer/test_geometry_optimization.py @@ -0,0 +1,116 @@ +import unittest + +import numpy as np + +from services.floor.geometry_filter import filter_surface_by_floor_geometry +from services.geometry.multi_plane import ( + _prune_weak_secondary_planes, + geometry_point_maps, +) +from services.geometry.ransac import ( + _best_surface_hypothesis, + _candidate_hypotheses, +) + + +class GeometryOptimizationTests(unittest.TestCase): + def test_weak_secondary_planes_are_removed_and_ids_are_reindexed(self): + planes = [ + {"id": 0, "inlierCount": 325_002}, + {"id": 1, "inlierCount": 5_302}, + {"id": 2, "inlierCount": 26_000}, + ] + + retained = _prune_weak_secondary_planes(planes) + + self.assertEqual( + [plane["inlierCount"] for plane in retained], + [325_002, 26_000], + ) + self.assertEqual([plane["id"] for plane in retained], [0, 1]) + + def test_batched_ransac_scoring_matches_sequential_scoring(self): + rng = np.random.default_rng(7) + xz = rng.uniform(-2, 2, size=(4_000, 2)).astype(np.float32) + points = np.column_stack(( + xz[:, 0], + rng.normal(0, 0.008, len(xz)), + xz[:, 1], + )).astype(np.float32) + normals = np.tile(np.array([0, 1, 0], dtype=np.float32), (len(points), 1)) + normals += rng.normal(0, 0.02, normals.shape).astype(np.float32) + normals /= np.linalg.norm(normals, axis=1, keepdims=True) + + origins, hypotheses = _candidate_hypotheses( + points, + iterations=90, + rng=np.random.default_rng(41), + ) + distance_threshold = 0.03 + normal_cos = 0.75 + expected_index = -1 + expected_count = 0 + for index, (origin, normal) in enumerate(zip(origins, hypotheses, strict=True)): + distances = np.abs((points - origin) @ normal) + alignments = np.abs(normals @ normal) + count = int(((distances <= distance_threshold) & (alignments >= normal_cos)).sum()) + if count > expected_count: + expected_count = count + expected_index = index + + result = _best_surface_hypothesis( + points, + origins, + hypotheses, + distance_threshold, + candidate_normals=normals, + normal_cos=normal_cos, + ) + + self.assertIsNotNone(result) + origin, normal = result + np.testing.assert_array_equal(origin, origins[expected_index]) + np.testing.assert_array_equal(normal, hypotheses[expected_index]) + + def test_prepared_geometry_maps_preserve_filter_output(self): + height, width = 120, 160 + y_coordinates = np.arange(height, dtype=np.float32)[:, None] + x_coordinates = np.arange(width, dtype=np.float32)[None, :] + points = np.empty((height, width, 3), dtype=np.float32) + points[:, :, 0] = (x_coordinates - width / 2) / 100 + points[:, :, 1] = 0 + points[:, :, 2] = 1 + y_coordinates / 100 + normals = np.zeros_like(points) + normals[:, :, 1] = 1 + surface = np.zeros((height, width), dtype=np.uint8) + surface[height // 3:] = 1 + geometry = { + "provider": "moge-2", + "points": points, + "normals": normals, + "validMask": np.ones((height, width), dtype=bool), + "intrinsics": np.eye(3, dtype=np.float32), + } + plane = { + "planeNormal": [0, 1, 0], + "planeOrigin": [0, 0, 0], + } + + expected, expected_metadata = filter_surface_by_floor_geometry(surface, geometry, plane) + prepared_maps = geometry_point_maps(surface, geometry) + actual, actual_metadata = filter_surface_by_floor_geometry( + surface, + geometry, + plane, + geometry_maps=prepared_maps, + ) + + np.testing.assert_array_equal(actual, expected) + self.assertEqual( + actual_metadata["geometrySurfaceFilterReason"], + expected_metadata["geometrySurfaceFilterReason"], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/apps/renderer/test_surface_edges.py b/apps/renderer/test_surface_edges.py new file mode 100644 index 0000000000000000000000000000000000000000..68ddce35e15dffb7409316338612d2ebd130a82b --- /dev/null +++ b/apps/renderer/test_surface_edges.py @@ -0,0 +1,279 @@ +"""Floor edge refinement: edges snap to the photo, run straight along walls, ship as alpha. + +Run from apps/renderer: python -m unittest test_surface_edges +No models needed: synthetic photos and segmentation maps only. +""" + +import base64 +import io +import json +import os +import tempfile +import unittest +import zipfile +from pathlib import Path +from unittest import mock + +# The production profile, as test_wall_segments uses (config is read once per process). +os.environ.setdefault("VISUALIZER_CONFIG", "visualizer.gpu.toml") + +import cv2 # noqa: E402 +import numpy as np # noqa: E402 + +from services.floor import edge_refinement # noqa: E402 +from services.floor.edge_refinement import ALPHA_FLOOR, guided_filter, refine_surface_edges # noqa: E402 +from services.geometry.multi_plane import geometry_point_maps # noqa: E402 +from services.geometry.uv_mapping import build_surface_uv_mapping # noqa: E402 +from services.image.polygons import straighten_polyline # noqa: E402 +from services.pipeline import packaging # noqa: E402 +from state import class_ids # noqa: E402 +from test_wall_segments import synthetic_room # noqa: E402 +from utils import mask_to_indices # noqa: E402 + +HEIGHT, WIDTH = 900, 1200 +WALL_LINE = 420 # the baseboard at the image centre: above is wall, below is floor +SLOPE = 0.04 # the baseboard is slightly tilted, as in a real photo +FLOOR_ID = class_ids({"floor"})[0] +WALL_ID = class_ids({"wall"})[0] +SOFA_ID = class_ids({"sofa"})[0] + + +def baseboard(xs: np.ndarray) -> np.ndarray: + return WALL_LINE + SLOPE * (xs - WIDTH / 2) + + +def room_photo() -> np.ndarray: + """Light wall over a darker, slightly grainy floor with a perfectly straight, anti-aliased join.""" + rng = np.random.default_rng(7) + rows = np.arange(HEIGHT, dtype=np.float32)[:, None] + floor_share = np.clip(rows + 0.5 - baseboard(np.arange(WIDTH))[None, :], 0, 1)[..., None] + photo = (1 - floor_share) * np.array((225, 222, 216), np.float32) + floor_share * np.array((150, 118, 90), np.float32) + photo += rng.normal(0, 4, photo.shape) + return np.clip(photo, 0, 255).astype(np.uint8) + + +def wobbly_floor(amplitude: float, period: float, offset: float = 0.0) -> np.ndarray: + """Floor mask whose top edge wobbles around the wall line, like an upsampled label map.""" + xs = np.arange(WIDTH) + top = baseboard(xs) + offset + amplitude * np.sin(xs / period) + 0.6 * amplitude * np.sin(xs / (period * 0.37) + 1.0) + rows = np.arange(HEIGHT)[:, None] + return (rows >= np.round(top)[None, :]).astype(np.uint8) + + +def seg_for(floor: np.ndarray) -> np.ndarray: + seg = np.full((HEIGHT, WIDTH), WALL_ID, np.uint8) + seg[floor > 0] = FLOOR_ID + return seg + + +MARGIN = WIDTH // 20 # columns where the filter meets the image border are ignored + + +def top_edge_rows(mask: np.ndarray) -> np.ndarray: + """First floor row in each column.""" + return np.argmax(mask[:, MARGIN:-MARGIN] > 0, axis=0).astype(np.float32) + + +def baseboard_error(mask: np.ndarray) -> np.ndarray: + """Distance from each column's first floor row to the baseboard's first (partly) floor row.""" + expected = np.floor(baseboard(np.arange(MARGIN, WIDTH - MARGIN)) + 0.5) + return np.abs(top_edge_rows(mask) - expected) + + +class GuidedFilterTest(unittest.TestCase): + def test_constant_source_is_unchanged(self): + guide = room_photo().astype(np.float32) / 255.0 + ones = np.ones((HEIGHT, WIDTH), np.float32) + np.testing.assert_allclose(guided_filter(guide, ones, 11, 2e-3), 1.0, atol=1e-3) + + +class RefineSurfaceEdgesTest(unittest.TestCase): + def test_wobbly_edge_snaps_to_the_baseboard(self): + floor = wobbly_floor(amplitude=7, period=40, offset=3) + before = baseboard_error(floor) + mask, alpha, metadata = refine_surface_edges(room_photo(), floor, seg_for(floor)) + + after = baseboard_error(mask) + self.assertTrue(metadata["edgeRefinementApplied"], metadata) + self.assertGreater(before.mean(), 3.0) + self.assertLess(after.mean(), 1.0) + self.assertLessEqual(after.max(), 2.0) + + def test_alpha_is_anti_aliased_and_mask_covers_it(self): + floor = wobbly_floor(amplitude=5, period=60) + mask, alpha, _ = refine_surface_edges(room_photo(), floor, seg_for(floor)) + + self.assertTrue(((alpha >= ALPHA_FLOOR) == (mask > 0)).all()) + partial = (alpha > 0) & (alpha < 255) + self.assertGreater(int(partial.sum()), WIDTH // 2) # a soft edge exists... + rows, cols = np.nonzero(partial) + self.assertLess(np.percentile(np.abs(rows - baseboard(cols)), 95), 2) # ...and only along the edge + self.assertTrue((alpha[WALL_LINE + 60:] == 255).all()) # the interior is fully tiled + + def test_edge_along_a_wall_is_straight_even_without_a_photo_edge(self): + flat = np.full((HEIGHT, WIDTH, 3), 180, np.uint8) # nothing for the filter to snap to + floor = wobbly_floor(amplitude=2.5, period=25) + mask, _, metadata = refine_surface_edges(flat, floor, seg_for(floor)) + + rows = top_edge_rows(mask) + self.assertGreaterEqual(metadata["edgeStraightenedRuns"], 1) + residual = rows - np.polyval(np.polyfit(np.arange(len(rows)), rows, 1), np.arange(len(rows))) + self.assertLessEqual(np.abs(residual).max(), 1.0) + + def test_edge_against_furniture_is_not_straightened(self): + floor = np.zeros((HEIGHT, WIDTH), np.uint8) + floor[200:] = 1 + seg = np.full((HEIGHT, WIDTH), SOFA_ID, np.uint8) + seg[floor > 0] = FLOOR_ID + flat = np.full((HEIGHT, WIDTH, 3), 180, np.uint8) + _, _, metadata = refine_surface_edges(flat, floor, seg) + self.assertEqual(metadata["edgeStraightenedRuns"], 0) + + def test_speckled_carpet_next_to_a_light_wall_gets_no_holes(self): + """Light carpet specks look like the wall to the filter; they must not punch holes in the tile.""" + photo = room_photo() + rng = np.random.default_rng(3) + rows, cols = np.nonzero(np.arange(HEIGHT)[:, None] >= baseboard(np.arange(WIDTH))[None, :] + 4) + specks = rng.random(len(rows)) < 0.08 + photo[rows[specks], cols[specks]] = (225, 222, 216) # the wall's colour + photo = cv2.GaussianBlur(photo, (3, 3), 0) + floor = wobbly_floor(amplitude=5, period=60) + mask, alpha, _ = refine_surface_edges(photo, floor, seg_for(floor)) + + holes = (alpha < 128).astype(np.uint8) + count, labels = cv2.connectedComponents(holes, connectivity=4) + enclosed = [label for label in range(1, count) if not (labels[0] == label).any()] # not the wall region + self.assertEqual(enclosed, []) + self.assertTrue((alpha[WALL_LINE + 60:] == 255).all()) + + def test_disabled_returns_the_mask_with_a_hard_edge(self): + floor = wobbly_floor(amplitude=5, period=40) + with mock.patch.object(edge_refinement, "ENABLE_SURFACE_EDGE_REFINEMENT", False): + mask, alpha, metadata = refine_surface_edges(room_photo(), floor, seg_for(floor)) + self.assertFalse(metadata["edgeRefinementApplied"]) + np.testing.assert_array_equal(mask, floor) + np.testing.assert_array_equal(alpha, floor * 255) + + def test_large_area_change_falls_back_to_the_input(self): + floor = wobbly_floor(amplitude=5, period=40) + with mock.patch.object(edge_refinement, "MAX_AREA_CHANGE", 0.0): + mask, _, metadata = refine_surface_edges(room_photo(), floor, seg_for(floor)) + self.assertEqual(metadata["edgeRefinementReason"], "area-change-too-large") + np.testing.assert_array_equal(mask, floor) + + +class EdgeUvTest(unittest.TestCase): + """Depth is blurry where the floor meets a wall; refined edge pixels still get floor UVs.""" + + @classmethod + def setUpClass(cls): + _, cls.geometry, labels = synthetic_room() + cls.floor = (labels == 0).astype(np.uint8) + cls.indices = mask_to_indices(cls.floor) + # The 8 floor rows nearest the walls: their 3D points slide towards the wall. + far_edge = cv2.dilate(1 - cls.floor, np.ones((17, 17), np.uint8)) & cls.floor + cls.blurry = far_edge.astype(bool) + blurred = dict(cls.geometry) + blurred["points"] = cls.geometry["points"].copy() + blurred["points"][cls.blurry] *= 1.15 + cls.blurred_maps = geometry_point_maps(cls.floor, blurred) + cls.blurred_geometry = blurred + + def test_blurry_edge_pixels_lose_their_uv_without_the_fill(self): + mapping = build_surface_uv_mapping(self.floor, self.indices, self.blurred_geometry, geometry_maps=self.blurred_maps) + self.assertLess(mapping["metadata"]["surfaceUvCoverage"], 0.995) + + def test_refined_edge_pixels_get_their_uv_from_the_floor_plane(self): + mapping = build_surface_uv_mapping( + self.floor, self.indices, self.blurred_geometry, geometry_maps=self.blurred_maps, ray_fill_mask=self.blurry, + ) + metadata = mapping["metadata"] + self.assertGreater(metadata["surfaceUvRayFilledPixels"], 0) + self.assertGreaterEqual(metadata["surfaceUvCoverage"], 0.999) + # The true floor points, in this mapping's own plane coordinates. + plane = mapping["planes"][0] + filled = self.blurry.ravel()[self.indices] + true_points = self.geometry["points"].reshape(-1, 3)[self.indices[filled]] + delta = true_points - np.asarray(plane["origin"], np.float32) + expected = np.column_stack((delta @ np.asarray(plane["uAxis"]), delta @ np.asarray(plane["vAxis"]))) + np.testing.assert_allclose(mapping["uv"][filled], expected, atol=0.005) + + +class EdgeSmearTest(unittest.TestCase): + """Edge pixels carrying a wrong but on-plane 3D point (a furniture foot) must not smear the tile.""" + + def test_edge_band_follows_the_floor_plane(self): + from services.geometry import uv_mapping + + _, geometry, labels = synthetic_room() + floor = (labels == 0).astype(np.uint8) + indices = mask_to_indices(floor) + edge = (cv2.dilate(1 - floor, np.ones((9, 9), np.uint8)) & floor).astype(bool) + smeared = dict(geometry) + smeared["points"] = geometry["points"].copy() + ys, xs = np.nonzero(edge) + # Each edge pixel reports the floor point 10 rows nearer the camera: on the plane, wrong place. + smeared["points"][ys, xs] = geometry["points"][np.minimum(ys + 10, floor.shape[0] - 1), xs] + maps = geometry_point_maps(floor, smeared) + + def edge_error(mapping): + plane = mapping["planes"][0] + on_edge = edge.ravel()[indices] + delta = geometry["points"].reshape(-1, 3)[indices[on_edge]] - np.asarray(plane["origin"], np.float32) + expected = np.column_stack((delta @ np.asarray(plane["uAxis"]), delta @ np.asarray(plane["vAxis"]))) + return np.abs(mapping["uv"][on_edge] - expected).max(axis=1) + + with mock.patch.object(uv_mapping, "SURFACE_UV_EDGE_BAND_RATIO", 0.0): + unblended = edge_error(build_surface_uv_mapping(floor, indices, smeared, geometry_maps=maps)) + blended = edge_error(build_surface_uv_mapping(floor, indices, smeared, geometry_maps=maps)) + self.assertGreater(np.percentile(unblended, 50), 0.02) # the smear is real without the band... + self.assertLess(np.percentile(blended, 50), 0.005) # ...and gone with it + + +class StraightenPolylineTest(unittest.TestCase): + def test_noisy_line_becomes_one_segment(self): + xs = np.arange(0, 300) + ys = 100 + np.round(1.5 * np.sin(xs / 7.0)) + line = straighten_polyline(np.stack([xs, ys], axis=1), tolerance=4) + self.assertEqual(len(line), 2) + np.testing.assert_allclose(line[:, 1], 100, atol=0.5) + + def test_real_corner_is_kept(self): + down = np.stack([np.zeros(100), np.arange(100)], axis=1) + across = np.stack([np.arange(1, 100), np.full(99, 99)], axis=1) + corner = straighten_polyline(np.concatenate([down, across]), tolerance=3) + self.assertEqual(len(corner), 3) + np.testing.assert_allclose(corner[1], (0, 99), atol=1.0) + + +class PackagingTest(unittest.TestCase): + def test_edge_alpha_ships_as_a_lazy_asset(self): + w, h = 40, 30 + indices = np.arange(200, 500, dtype=np.uint32) + alpha = np.linspace(0, 255, len(indices)).astype(np.uint8) + bundle = { + "width": w, + "height": h, + "pixels": None, + "segments": [{"id": 0, "mask": base64.b64encode(indices.tobytes()).decode(), "edgeAlpha": alpha}], + } + with tempfile.TemporaryDirectory() as tmp, mock.patch.object(packaging, "JOB_DIR", Path(tmp)): + data = packaging.build_manifest_segmentation_bundle(bundle, "job") + archive = zipfile.ZipFile(io.BytesIO(data)) + metadata = json.loads(archive.read("metadata.json")) + ref = metadata["segments"][0]["edgeAlpha"] + self.assertEqual(ref["path"], "segments/0/edge-alpha.u8") + self.assertEqual(archive.read(ref["path"]), alpha.tobytes()) + + def test_occlusion_never_covers_the_surface(self): + seg = np.full((60, 80), FLOOR_ID, np.uint8) + seg[:20] = SOFA_ID + surface = np.zeros((60, 80), np.uint8) + surface[18:] = 1 # the soft edge reaches two rows into the sofa label + occlusion = packaging.foreground_occlusion_mask(surface, seg) + self.assertTrue(occlusion[:18].any()) + self.assertFalse((occlusion & surface).any()) + + +if __name__ == "__main__": + unittest.main() diff --git a/apps/renderer/test_wall_decor_matte.py b/apps/renderer/test_wall_decor_matte.py new file mode 100644 index 0000000000000000000000000000000000000000..98d0385e8b5d8a14d25780e6eca3b9d4712b8837 --- /dev/null +++ b/apps/renderer/test_wall_decor_matte.py @@ -0,0 +1,69 @@ +"""Wallpaper up to the real outline of objects in front of a wall (no models needed). + + python -m unittest test_wall_decor_matte +""" + +import unittest + +import numpy as np + +from services.wall.components import WallPlane +from services.wall.edges import matte_wall_decor +from state import class_ids + +WALL_Z = 2.0 + + +def scene(): + """A grey wall 2 m away. A bouquet blob (labelled anything) with bare wall between its stems, + a glass vase and a chair the wall's colour standing in front of it.""" + img = np.full((200, 300, 3), 110, np.uint8) + seg = np.full((200, 300), class_ids({"wall"})[0], np.int32) + points = np.zeros((200, 300, 3), np.float32) + ys, xs = np.mgrid[0:200, 0:300] + points[..., 0] = (xs - 150) / 100.0 + points[..., 1] = (ys - 100) / 100.0 + points[..., 2] = WALL_Z + + seg[60:140, 100:180] = class_ids({"bulletin board"})[0] # a bouquet, misclassified + for x in range(105, 180, 12): # its stems, 30 cm in front + img[60:140, x:x + 3] = 235 + points[60:140, x:x + 3, 2] = WALL_Z - 0.3 + seg[60:140, 200:240] = class_ids({"vase"})[0] + img[60:140, 200:240] = 112 # glass, the wall's colour, 20 cm in front + points[60:140, 200:240, 2] = WALL_Z - 0.2 + seg[170:200, 0:60] = class_ids({"chair"})[0] + img[170:200, 0:60] = 112 + points[170:200, 0:60, 2] = WALL_Z - 0.5 + wall = (seg == class_ids({"wall"})[0]).astype(np.uint8) + plane = WallPlane(origin=np.array([0.0, 0.0, WALL_Z]), normal=np.array([0.0, 0.0, 1.0])) + return img, seg, wall, points, plane + + +def coverage_of(mask, alpha): + coverage = np.zeros(mask.shape, np.float32) + coverage[mask > 0] = alpha[mask > 0] / 255.0 + return coverage + + +class WallDecorMatteTest(unittest.TestCase): + def test_wall_shows_around_the_stems_and_solid_things_stay(self): + img, seg, wall, points, plane = scene() + mask, alpha = matte_wall_decor(img, seg, wall, points, plane) + self.assertIsNotNone(alpha) + coverage = coverage_of(mask, alpha) + self.assertGreater(coverage[100, 111], 0.9) # bare wall between two stems: papered + self.assertLess(coverage[100, 106], 0.1) # a stem: the photo + self.assertEqual(coverage[100, 220], 0.0) # the glass vase, off the wall: untouched + self.assertEqual(coverage[185, 30], 0.0) # the chair: untouched + self.assertEqual(coverage[30, 30], 1.0) # open wall + + def test_without_depth_nothing_changes(self): + img, seg, wall, _points, plane = scene() + mask, alpha = matte_wall_decor(img, seg, wall, None, plane) + self.assertIsNone(alpha) + self.assertTrue(np.array_equal(mask, wall)) + + +if __name__ == "__main__": + unittest.main() diff --git a/apps/renderer/test_wall_mural_top.py b/apps/renderer/test_wall_mural_top.py new file mode 100644 index 0000000000000000000000000000000000000000..3c37283362a0cb2c382b2f518d6f5bef29a200b1 --- /dev/null +++ b/apps/renderer/test_wall_mural_top.py @@ -0,0 +1,43 @@ +"""Murals hang from the wall's top edge: wall_top finds it in plane-v (no models). + + python -m unittest test_wall_mural_top +""" + +import os +import unittest + +import numpy as np + +# Same profile as the other wall tests: the first import fixes the config. +os.environ.setdefault("VISUALIZER_CONFIG", "visualizer.gpu.toml") + +from services.wall.pipeline import wall_top + + +class WallTopTest(unittest.TestCase): + def test_v_pointing_up(self): + rows = np.repeat(np.arange(100), 50) + v = 2.4 - rows * 0.02 # higher in the image (smaller row) = larger v + top, sign = wall_top(v, rows) + self.assertEqual(sign, 1) + self.assertAlmostEqual(top, 2.4, delta=0.03) + + def test_v_pointing_down(self): + rows = np.repeat(np.arange(100), 50) + v = -1.0 + rows * 0.02 + top, sign = wall_top(v, rows) + self.assertEqual(sign, -1) + self.assertAlmostEqual(top, -1.0, delta=0.03) + + def test_ignores_misses_and_stray_pixels(self): + rows = np.repeat(np.arange(100), 50).astype(float) + v = 2.0 - rows * 0.02 + v[::97] = np.nan + v[5] = 50.0 # one stray pixel far above + top, sign = wall_top(v, rows) + self.assertEqual(sign, 1) + self.assertLess(top, 2.1) + + +if __name__ == "__main__": + unittest.main() diff --git a/apps/renderer/test_wall_segments.py b/apps/renderer/test_wall_segments.py new file mode 100644 index 0000000000000000000000000000000000000000..7656d3e3db6e97f78c468dafe67b8f68f1facdb3 --- /dev/null +++ b/apps/renderer/test_wall_segments.py @@ -0,0 +1,218 @@ +"""Wall segmentation: one segment per physical wall, floor plane budget untouched, fast. + +Run from apps/renderer: python -m unittest test_wall_segments +Uses the GPU profile so the floor's max_planes (1) is the production value. +""" + +import base64 +import os +import time +import unittest + +os.environ.setdefault("VISUALIZER_CONFIG", "visualizer.gpu.toml") + +import cv2 # noqa: E402 +import numpy as np # noqa: E402 + +from config.surface import SURFACE_MAX_PLANES, WALL_MAX_PLANES # noqa: E402 +from services.geometry.multi_plane import fit_multi_surface_planes # noqa: E402 +from services.geometry.plane_uv import plane_to_image_transform, ray_plane_uv, upright_plane_basis # noqa: E402 +from services.wall.components import discover_wall_components # noqa: E402 +from services.wall.pipeline import build_wall_segments # noqa: E402 +from state import class_ids # noqa: E402 + +WIDTH, HEIGHT = 1920, 1440 +FOCAL = 1400.0 +INTRINSICS = np.array([[FOCAL, 0, (WIDTH - 1) / 2], [0, FOCAL, (HEIGHT - 1) / 2], [0, 0, 1]], np.float32) +FLOOR_ID = class_ids({"floor"})[0] +WALL_ID = class_ids({"wall"})[0] +CEILING_ID = class_ids({"ceiling"})[0] +DOOR_ID = class_ids({"door"})[0] +# Wall budget for the whole test run: generous for a CI CPU, well under the +# ~3s of floor CPU stages the wall thread overlaps with in production. +WALL_TIME_BUDGET_SECONDS = 1.5 + + +def synthetic_room(walls=("left", "back", "right")): + """Camera inside a box room, OpenCV axes (x right, y down, z forward). + + Returns (seg_map, geometry, labels) with MoGe-style full-res points/normals. + labels: 0 floor, 1 ceiling, 2+ walls in the order given. + """ + planes = [ # (normal pointing into the room, offset d) for n.p + d = 0 + (np.array([0, -1, 0], np.float32), 1.5, FLOOR_ID), # floor y = 1.5 + (np.array([0, 1, 0], np.float32), 1.2, CEILING_ID), # ceiling y = -1.2 + ] + wall_planes = { + "left": (np.array([1, 0, 0], np.float32), 2.2), # x = -2.2 + "back": (np.array([0, 0, -1], np.float32), 5.0), # z = 5 + "right": (np.array([-1, 0, 0], np.float32), 2.2), # x = 2.2 + } + planes += [(wall_planes[name][0], wall_planes[name][1], WALL_ID) for name in walls] + + yy, xx = np.mgrid[0:HEIGHT, 0:WIDTH].astype(np.float32) + rays = np.dstack(((xx - INTRINSICS[0, 2]) / FOCAL, (yy - INTRINSICS[1, 2]) / FOCAL, np.ones_like(xx))) + best_t = np.full((HEIGHT, WIDTH), np.inf, np.float32) + labels = np.full((HEIGHT, WIDTH), -1, np.int32) + for index, (normal, offset, _) in enumerate(planes): + with np.errstate(divide="ignore", invalid="ignore"): + t = -offset / (rays @ normal) + closer = (t > 0) & (t < best_t) + best_t[closer] = t[closer] + labels[closer] = index + + valid = np.isfinite(best_t) + points = rays * np.where(valid, best_t, 0)[..., None] + seg_map = np.zeros((HEIGHT, WIDTH), np.uint8) + normals = np.zeros((HEIGHT, WIDTH, 3), np.float32) + for index, (normal, _, class_id) in enumerate(planes): + seg_map[labels == index] = class_id + normals[labels == index] = normal # into the room == facing the camera (MoGe-style) + geometry = { + "provider": "moge-2", + "points": points.astype(np.float32), + "normals": normals, + "validMask": valid, + "depth": points[..., 2].astype(np.float32), + "intrinsics": INTRINSICS, + } + return seg_map, geometry, labels + + +class WallSegmentTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.seg_map, cls.geometry, cls.labels = synthetic_room() + cls.min_area = max(1200, int(WIDTH * HEIGHT * 0.015)) + + def test_three_walls_become_three_ordered_segments(self): + discovery = discover_wall_components(self.seg_map, self.geometry, self.min_area) + self.assertEqual(len(discovery.components), 3) + expected_normals = ([1, 0, 0], [0, 0, 1], [1, 0, 0]) # left, back, right (up to sign) + for component, expected, true_label in zip(discovery.components, expected_normals, (2, 3, 4)): + purity = float((self.labels[component.mask > 0] == true_label).mean()) + self.assertGreater(purity, 0.97, "a wall segment leaked into another wall") + plane = component.plane + assert plane is not None + self.assertGreater(abs(float(plane.normal @ np.array(expected, np.float32))), 0.98) + + def test_wall_outline_reaches_the_door_frame(self): + """Walls must follow the semantic boundary like the floor: no gap band, no bleed.""" + seg_map = self.seg_map.copy() + door = np.array([[1150, 520], [1330, 505], [1340, 1000], [1160, 1010]], np.int32) # slanted frame + cv2.fillPoly(seg_map, [door], int(DOOR_ID)) + discovery = discover_wall_components(seg_map, self.geometry, self.min_area) + walls = np.zeros(seg_map.shape, bool) + for component in discovery.components: + walls |= component.mask > 0 + + door_mask = seg_map == DOOR_ID + depth_into_door = cv2.distanceTransform(door_mask.astype(np.uint8), cv2.DIST_L2, 3) + bleed = walls & door_mask + # Rasterising a straight slanted edge may touch the door's first pixel row only. + self.assertLessEqual(float(depth_into_door[bleed].max()) if bleed.any() else 0.0, 1.5, + "wall texture bled onto the door") + near_door = cv2.dilate(door_mask.astype(np.uint8), np.ones((7, 7), np.uint8)) > 0 + wall_near_door = near_door & ~door_mask & (seg_map == WALL_ID) + covered = float(walls[wall_near_door].mean()) + self.assertGreater(covered, 0.97, f"only {covered:.0%} of wall pixels next to the door are textured") + + def test_zigzag_door_edge_becomes_one_straight_line(self): + """A wobbly semantic boundary (as OneFormer produces) is redrawn as a straight edge.""" + seg_map = self.seg_map.copy() + rng = np.random.default_rng(3) + top, bottom, edge_x = 520, 1000, 1150 + for y in range(top, bottom): + wobble = int(rng.integers(-4, 5)) # +-4px zig-zag per row + seg_map[y, edge_x + wobble:1330] = DOOR_ID + discovery = discover_wall_components(seg_map, self.geometry, self.min_area) + walls = np.zeros(seg_map.shape, bool) + for component in discovery.components: + walls |= component.mask > 0 + + rows = np.arange(top + 40, bottom - 40) # away from the corners + window = walls[rows, edge_x - 40:edge_x + 40] + edge = edge_x - 40 + window.shape[1] - np.argmax(window[:, ::-1], axis=1) # last wall px + 1 + fitted = np.polyval(np.polyfit(rows, edge, 1), rows) + self.assertLess(float(np.abs(edge - fitted).max()), 1.01, "wall edge along the door is not straight") + self.assertLess(float(np.abs(fitted - edge_x).max()), 2.5, "straight edge drifted off the true boundary") + + def test_single_flat_wall_is_not_split(self): + seg_map, geometry, _ = synthetic_room(walls=("back",)) + discovery = discover_wall_components(seg_map, geometry, self.min_area) + self.assertEqual(len(discovery.components), 1) + + def test_floor_keeps_its_own_plane_budget(self): + self.assertEqual(SURFACE_MAX_PLANES, 1, "GPU profile floor max_planes must stay 1") + self.assertGreater(WALL_MAX_PLANES, 1) + mask = self.labels >= 2 + points = self.geometry["points"][mask][::20] + normals = self.geometry["normals"][mask][::20] + self.assertLessEqual(len(fit_multi_surface_planes(points, normals, True)), 1) + self.assertGreaterEqual(len(fit_multi_surface_planes(points, normals, True, max_planes=WALL_MAX_PLANES)), 3) + + def test_ray_plane_uv_matches_true_points(self): + normal = np.array([0, 0, -1], np.float32) + origin = np.array([0, 0, 5], np.float32) + u_axis, v_axis = upright_plane_basis(normal, np.array([0, 1, 0], np.float32)) + flat = np.flatnonzero((self.labels == 3).ravel())[::50] + uv, hit = ray_plane_uv(flat, WIDTH, INTRINSICS, origin, normal, u_axis, v_axis) + self.assertTrue(hit.all()) + true_points = self.geometry["points"].reshape(-1, 3)[flat] + true_uv = np.column_stack(((true_points - origin) @ u_axis, (true_points - origin) @ v_axis)) + self.assertLess(float(np.abs(uv - true_uv).max()), 1e-3) + + def test_plane_transform_equals_ray_plane_uv(self): + normal = np.array([0.6, 0.0, -0.8], np.float32) + origin = np.array([0.5, 0.2, 4.0], np.float32) + u_axis, v_axis = upright_plane_basis(normal, np.array([0, 1, 0], np.float32)) + flat = np.arange(0, WIDTH * HEIGHT, 997) + uv, hit = ray_plane_uv(flat, WIDTH, INTRINSICS, origin, normal, u_axis, v_axis) + transform = plane_to_image_transform(INTRINSICS, origin, normal, u_axis, v_axis) + pixels = np.column_stack((flat % WIDTH, flat // WIDTH, np.ones(len(flat)))) + mapped = pixels @ transform.T + mapped_uv = mapped[:, :2] / mapped[:, 2:3] + self.assertLess(float(np.abs(mapped_uv[hit] - uv[hit]).max()), 1e-3) + + def test_wall_texture_axis_is_upright(self): + u_axis, v_axis = upright_plane_basis(np.array([1, 0, 0], np.float32), np.array([0, 1, 0], np.float32)) + self.assertGreater(abs(float(v_axis[1])), 0.99) + self.assertLess(abs(float(u_axis[1])), 1e-3) + + def test_segments_have_exact_plane_mapping_small_payload_and_fit_budget(self): + started = time.perf_counter() + result = build_wall_segments( + np.full((HEIGHT, WIDTH, 3), 180, np.uint8), self.seg_map, self.geometry, + self.min_area, "test-model", + ) + elapsed = time.perf_counter() - started + print(f"\n[wall benchmark] {WIDTH}x{HEIGHT}: {elapsed * 1000:.0f}ms {result.detail}") + self.assertEqual([s["id"] for s in result.segments], [1, 2, 3]) + points = self.geometry["points"].reshape(-1, 3) + true_labels = self.labels.ravel() + for segment, wall_label in zip(result.segments, (2, 3, 4)): # left, back, right + plane = segment["plane"] + self.assertIsNone(segment["surfaceUv"], "walls ship a 3x3 transform, not per-pixel UV") + self.assertEqual(segment["metadata"]["textureMappingMode"], "wall-plane") + self.assertGreaterEqual(plane["geometryConfidence"], 0.99) + self.assertEqual(segment["metadata"]["wallComponentCount"], 3) + # The transform reproduces the true metric position of the wall's own pixels + # (edge pixels shared with a neighbouring surface lie on that surface's plane). + flat = np.frombuffer(base64.b64decode(segment["mask"]), np.uint32)[::101] + flat = flat[true_labels[flat] == wall_label] + transform = np.asarray(segment["surfaceTransform"], np.float64).reshape(3, 3) + mapped = np.column_stack((flat % WIDTH, flat // WIDTH, np.ones(len(flat)))) @ transform.T + origin = np.asarray(plane["planeOrigin"]) + true_uv = np.column_stack(( + (points[flat] - origin) @ np.asarray(plane["surfaceUAxis"]), + (points[flat] - origin) @ np.asarray(plane["surfaceVAxis"]), + )) + self.assertLess(float(np.abs(mapped[:, :2] / mapped[:, 2:3] - true_uv).max()), 0.005) + shade = segment["shadeMap"] + if shade is not None: + self.assertLessEqual(max(shade.shape), 768) + self.assertLess(elapsed, WALL_TIME_BUDGET_SECONDS) + + +if __name__ == "__main__": + unittest.main() diff --git a/apps/renderer/utils.py b/apps/renderer/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..52f0b68c508fbdf18a23acc35414e5d56748112f --- /dev/null +++ b/apps/renderer/utils.py @@ -0,0 +1,60 @@ +"""Shared utility functions used across the floor-visualizer backend.""" + +from __future__ import annotations + +import time +from contextlib import contextmanager + +import numpy as np + + +@contextmanager +def timed_stage(label: str): + """Context manager that measures elapsed time and prints a timing line. + + Yields a dict with an ``elapsed_ms`` key that is populated on exit. + + Usage:: + + with timed_stage("Floor segmentation") as t: + result = run_segmentation(img) + print(t["elapsed_ms"]) + """ + info: dict = {"elapsed_ms": 0.0} + t0 = time.perf_counter() + try: + yield info + finally: + info["elapsed_ms"] = (time.perf_counter() - t0) * 1000 + print(f"[TIMING] {label} took {info['elapsed_ms'] / 1000:.3f} seconds", flush=True) + + +def to_numpy(value): + """Convert a torch.Tensor or array-like to a numpy array.""" + if value is None: + return None + try: + import torch + if isinstance(value, torch.Tensor): + return value.detach().float().cpu().numpy() + except ImportError: + pass + return np.asarray(value) + + +def seg_class_mask(seg_map: np.ndarray, class_id_list: list[int]) -> np.ndarray: + """Return a uint8 binary mask for pixels whose seg_map value is in *class_id_list*.""" + return np.isin(seg_map, class_id_list).astype(np.uint8) + + +def mask_to_indices(mask: np.ndarray) -> np.ndarray: + """Return the flat uint32 indices of non-zero pixels in *mask*.""" + return np.flatnonzero(mask.ravel()).astype(np.uint32) + + +def encode_b64(arr: np.ndarray | None) -> str | None: + """Base64-encode a numpy array's raw bytes, or return None.""" + if arr is None: + return None + import base64 + return base64.b64encode(arr.tobytes()).decode() diff --git a/apps/renderer/visualizer.gpu.toml b/apps/renderer/visualizer.gpu.toml new file mode 100644 index 0000000000000000000000000000000000000000..618b5cd7f5c902c0739a3c12429e42c01e2fc572 --- /dev/null +++ b/apps/renderer/visualizer.gpu.toml @@ -0,0 +1,63 @@ +# GPU quality preset for the floor visualizer backend. +# Run with: +# VISUALIZER_CONFIG=visualizer.gpu.toml uvicorn app:app --host 0.0.0.0 --port 8002 + +[models] +geometry_model = "moge" +moge_model_name = "Ruicheng/moge-2-vitl-normal" +oneformer_model_name = "shi-labs/oneformer_ade20k_swin_large" +depth_model_name = "depth-anything/Depth-Anything-V2-Metric-Indoor-Large-hf" +intrinsic_model_version = "v2" +sam2_model_name = "facebook/sam2-hiera-large" +sam2_model_cfg = "" +sam2_checkpoint = "" + +[runtime] +enable_depth_estimation = true +enable_moge_geometry = true +enable_plane_fit = true +enable_multi_plane_surfaces = true +enable_wall_segments = true +enable_intrinsic_shading = false +enable_shading_transfer = false +enable_fast_shadow_transfer = true +fast_shadow_max_dimension = 640 +enable_sam_refinement = false +enable_floor_mask_cleanup = true +warm_start_models = true +debug_artifacts_enabled = false +inference_max_dimension = 1024 +conversion_target_ms = 30000 +max_concurrent_conversions = 2 +bundle_image_format = "jpeg" +bundle_image_quality = 92 +data_dir = "data" + +[surface_mapping] +ransac_distance_threshold = 0.04 +max_planes = 1 +# Walls have their own plane budget; the floor keeps max_planes above. +wall_max_planes = 4 +max_walls = 6 +wall_work_max_dimension = 768 +wall_edge_straighten_ratio = 0.004 +normal_angle_threshold_degrees = 35 +normal_smoothing_kernel = 5 +min_plane_pixels = 1500 +edge_close_ratio = 0.009 +edge_kernel_ratio = 0.006 +edge_dilation_iterations = 0 +soft_floor_covering_expansion_enabled = true +soft_floor_covering_kernel_ratio = 0.008 +soft_floor_covering_dilation_iterations = 2 +uv_min_coverage = 0.995 +uv_max_bad_neighbor_ratio = 0.035 +uv_max_jump_ratio = 8.0 +uv_absolute_jump_meters = 0.35 +enable_geometry_surface_filter = true +plane_distance_threshold_meters = 0.12 +plane_normal_min_cos = 0.45 +plane_filter_min_keep_ratio = 0.45 + +[gemini] +image_model = "gemini-3.1-flash-image" diff --git a/apps/renderer/visualizer.hf.toml b/apps/renderer/visualizer.hf.toml new file mode 100644 index 0000000000000000000000000000000000000000..dff557050ff818d4950591c4d80a1df280f786e4 --- /dev/null +++ b/apps/renderer/visualizer.hf.toml @@ -0,0 +1,57 @@ +# Preset for Hugging Face GPU Spaces. +# Run with: +# VISUALIZER_CONFIG=visualizer.hf.toml uvicorn app:app --host 0.0.0.0 --port 7860 + +[models] +geometry_model = "moge" +moge_model_name = "Ruicheng/moge-2-vitl-normal" +oneformer_model_name = "shi-labs/oneformer_ade20k_swin_large" +depth_model_name = "depth-anything/Depth-Anything-V2-Metric-Indoor-Large-hf" +intrinsic_model_version = "v2" +sam2_model_name = "facebook/sam2-hiera-large" +sam2_model_cfg = "" +sam2_checkpoint = "" + +[runtime] +enable_depth_estimation = true +enable_moge_geometry = true +enable_plane_fit = true +enable_multi_plane_surfaces = true +enable_wall_segments = true +enable_intrinsic_shading = false +enable_shading_transfer = false +enable_fast_shadow_transfer = true +fast_shadow_max_dimension = 640 +enable_sam_refinement = false +enable_floor_mask_cleanup = true +debug_artifacts_enabled = false +inference_max_dimension = 1024 +conversion_target_ms = 30000 +max_concurrent_conversions = 2 +data_dir = "data" + +[surface_mapping] +ransac_distance_threshold = 0.04 +max_planes = 1 +# Walls have their own plane budget; the floor keeps max_planes above. +wall_max_planes = 4 +max_walls = 6 +wall_work_max_dimension = 768 +wall_edge_straighten_ratio = 0.004 +normal_angle_threshold_degrees = 35 +normal_smoothing_kernel = 5 +min_plane_pixels = 1500 +edge_close_ratio = 0.009 +edge_kernel_ratio = 0.006 +edge_dilation_iterations = 0 +soft_floor_covering_expansion_enabled = true +soft_floor_covering_kernel_ratio = 0.008 +soft_floor_covering_dilation_iterations = 2 +uv_min_coverage = 0.995 +uv_max_bad_neighbor_ratio = 0.035 +uv_max_jump_ratio = 8.0 +uv_absolute_jump_meters = 0.35 +enable_geometry_surface_filter = true +plane_distance_threshold_meters = 0.12 +plane_normal_min_cos = 0.45 +plane_filter_min_keep_ratio = 0.45 diff --git a/apps/renderer/visualizer.local.toml b/apps/renderer/visualizer.local.toml new file mode 100644 index 0000000000000000000000000000000000000000..52883e59fceb3cf881e1b146b18905edc5c43429 --- /dev/null +++ b/apps/renderer/visualizer.local.toml @@ -0,0 +1,52 @@ +# Lightweight local preset for CPU-only development on macOS. +# Run with: +# VISUALIZER_CONFIG=visualizer.local.toml uvicorn app:app --host 0.0.0.0 --port 8002 + +[models] +oneformer_model_name = "shi-labs/oneformer_ade20k_swin_large" +depth_model_name = "Intel/dpt-large" +sam2_model_name = "facebook/sam2-hiera-large" +sam2_model_cfg = "" +sam2_checkpoint = "" + +[runtime] +enable_depth_estimation = false +enable_plane_fit = true +enable_multi_plane_surfaces = true +enable_wall_segments = true +enable_intrinsic_shading = false +enable_shading_transfer = false +enable_fast_shadow_transfer = true +fast_shadow_max_dimension = 640 +enable_sam_refinement = false +warm_start_models = true +inference_max_dimension = 1024 +bundle_image_format = "jpeg" +bundle_image_quality = 92 +data_dir = "data" + +[surface_mapping] +ransac_distance_threshold = 0.04 +max_planes = 1 +# Walls have their own plane budget; the floor keeps max_planes above. +wall_max_planes = 4 +max_walls = 6 +wall_work_max_dimension = 768 +wall_edge_straighten_ratio = 0.004 +normal_angle_threshold_degrees = 35 +normal_smoothing_kernel = 5 +min_plane_pixels = 1500 +edge_close_ratio = 0.009 +edge_kernel_ratio = 0.006 +edge_dilation_iterations = 0 +soft_floor_covering_expansion_enabled = true +soft_floor_covering_kernel_ratio = 0.008 +soft_floor_covering_dilation_iterations = 2 +uv_min_coverage = 0.995 +uv_max_bad_neighbor_ratio = 0.035 +uv_max_jump_ratio = 8.0 +uv_absolute_jump_meters = 0.35 +enable_geometry_surface_filter = false +plane_distance_threshold_meters = 0.12 +plane_normal_min_cos = 0.45 +plane_filter_min_keep_ratio = 0.45 diff --git a/infra/huggingface/nginx.conf b/infra/huggingface/nginx.conf new file mode 100644 index 0000000000000000000000000000000000000000..adaea1d4988479ebf462faf4c6d34b3e869ce946 --- /dev/null +++ b/infra/huggingface/nginx.conf @@ -0,0 +1,41 @@ +# Runs as the unprivileged Space user, so every writable path is under /tmp. +worker_processes 1; +pid /tmp/nginx.pid; +error_log stderr warn; + +events { + worker_connections 1024; +} + +http { + access_log off; + client_body_temp_path /tmp/nginx-client-body; + proxy_temp_path /tmp/nginx-proxy; + fastcgi_temp_path /tmp/nginx-fastcgi; + uwsgi_temp_path /tmp/nginx-uwsgi; + scgi_temp_path /tmp/nginx-scgi; + + client_max_body_size 50m; + proxy_http_version 1.1; + proxy_read_timeout 300s; + proxy_send_timeout 300s; + # QA run progress is streamed as Server-Sent Events. + proxy_buffering off; + proxy_request_buffering off; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto; + + server { + listen 7860; + + # Account API. Its unprefixed /health, /ready and /internal routes stay private. + location /api/ { + proxy_pass http://127.0.0.1:8001; + } + + location / { + proxy_pass http://127.0.0.1:7861; + } + } +} diff --git a/infra/huggingface/start.sh b/infra/huggingface/start.sh new file mode 100755 index 0000000000000000000000000000000000000000..2d2dc67060fcf14707657ecf60f7f78f3d5c6e20 --- /dev/null +++ b/infra/huggingface/start.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# Hugging Face entrypoint: nginx on :7860 routes /api/* to the account API and +# everything else to the renderer, then the shared supervisor starts both. +set -euo pipefail + +nginx -e stderr -c /etc/prevision/nginx.conf +exec /usr/local/bin/start-services diff --git a/infra/runpod/start.sh b/infra/runpod/start.sh new file mode 100755 index 0000000000000000000000000000000000000000..2884bad44ccccd4aa80758aefff71dbf5e91334a --- /dev/null +++ b/infra/runpod/start.sh @@ -0,0 +1,98 @@ +#!/usr/bin/env bash +# Runs the product account API and GPU renderer. +set -uo pipefail + +VISUALIZER_PORT="${VISUALIZER_PORT:-7860}" +export PREVISION_API_PORT="${PREVISION_API_PORT:-8001}" + +log() { echo "[start-services] $*"; } + + +run_prevision_api() { + cd /srv/prevision || return 1 + local delay=5 + while true; do + log "prevision API: applying migrations and seeding the catalog" + if ./node_modules/.bin/prisma migrate deploy && node dist/scripts/seed-catalog.js; then + log "prevision API: serving on :${PREVISION_API_PORT}" + delay=5 + node dist/main.js + log "prevision API exited with status $?" + else + log "prevision API: migration or catalog seed failed" + fi + log "prevision API: restarting in ${delay}s" + sleep "${delay}" + delay=$(( delay * 2 > 300 ? 300 : delay * 2 )) + done +} + +prevision_pid="" +if [[ -n "${PREVISION_DATABASE_URL:-}" && -n "${CLERK_SECRET_KEY:-}" ]]; then + run_prevision_api & + prevision_pid=$! +else + log "PREVISION_DATABASE_URL or CLERK_SECRET_KEY is not set; the Prevision API is disabled" +fi + +stop_supervisor() { + [[ -n "$1" ]] && pkill -TERM -P "$1" 2>/dev/null && kill -TERM "$1" 2>/dev/null +} + +# Developer access, staging only: both are off unless the pod opts in. +# - DEV_SSH=1 with PUBLIC_KEY (RunPod's ssh key variable): sshd on port 22 for +# `user`, key login only. RunPod may set PUBLIC_KEY on any pod, hence the flag. +# - RENDERER_DEV_RELOAD=1: the renderer restarts when its Python code changes +# (copy files into /app over ssh) and also logs to /tmp/renderer.log. +start_dev_ssh() { + [[ "${DEV_SSH:-0}" == "1" && -n "${PUBLIC_KEY:-}" ]] || return 0 + local dir="${HOME}/.dev-sshd" + mkdir -p "${HOME}/.ssh" "${dir}" + chmod 700 "${HOME}/.ssh" "${dir}" + printf '%s\n' "${PUBLIC_KEY}" > "${HOME}/.ssh/authorized_keys" + chmod 600 "${HOME}/.ssh/authorized_keys" + [[ -f "${dir}/host_ed25519" ]] || ssh-keygen -q -t ed25519 -N "" -f "${dir}/host_ed25519" + cat > "${dir}/sshd_config" <> "${HOME}/.bashrc" + /usr/sbin/sshd -f "${dir}/sshd_config" -E "${dir}/sshd.log" && log "dev ssh: listening on :22" \ + || log "dev ssh: sshd failed to start (see ${dir}/sshd.log)" +} +start_dev_ssh + +cd /app +if [[ "${RENDERER_DEV_RELOAD:-0}" == "1" ]]; then + # Only the code folders are watched: data/ holds many job files and no code. + log "floor-visualizer: reloading on code changes" + uvicorn app:app --host 0.0.0.0 --port "${VISUALIZER_PORT}" --workers 1 --reload \ + --reload-dir /app/services --reload-dir /app/routes --reload-dir /app/config --reload-dir /app/models \ + > >(tee -a /tmp/renderer.log) 2>&1 & +else + uvicorn app:app --host 0.0.0.0 --port "${VISUALIZER_PORT}" --workers 1 & +fi +visualizer_pid=$! + +shutdown() { + log "stopping" + kill -TERM "${visualizer_pid}" 2>/dev/null + stop_supervisor "${prevision_pid}" + wait + exit 0 +} +trap shutdown SIGTERM SIGINT + +wait "${visualizer_pid}" +status=$? +log "floor-visualizer exited with status ${status}" +stop_supervisor "${prevision_pid}" +exit "${status}" diff --git a/package.json b/package.json new file mode 100644 index 0000000000000000000000000000000000000000..93ce533b4a94aca9ab59e0a2245937ed6af54e29 --- /dev/null +++ b/package.json @@ -0,0 +1,19 @@ +{ + "name": "prevision", + "private": true, + "description": "PREVISION web application, account API and GPU renderer.", + "packageManager": "pnpm@10.13.1", + "engines": { + "node": ">=22" + }, + "scripts": { + "dev": "turbo run dev", + "build": "turbo run build", + "lint": "turbo run lint", + "test": "turbo run test", + "dev:prevision": "turbo run dev --filter=@prevision/web --filter=@prevision/api" + }, + "devDependencies": { + "turbo": "^2.11.7" + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2750dbaa9b0373cb801d3208ddd510eb59070409 --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,7257 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + devDependencies: + turbo: + specifier: ^2.11.7 + version: 2.11.7 + + apps/prevision-api: + dependencies: + '@clerk/backend': + specifier: ^3.22.0 + version: 3.22.0(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@nestjs/common': + specifier: ^12.0.1 + version: 12.1.2(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2) + '@nestjs/core': + specifier: ^12.0.1 + version: 12.1.2(@nestjs/common@12.1.2(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@12.1.2)(reflect-metadata@0.2.2)(rxjs@7.8.2) + '@nestjs/platform-express': + specifier: ^12.0.1 + version: 12.1.2(@nestjs/common@12.1.2(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@12.1.2) + '@prisma/adapter-pg': + specifier: ^7.10.0 + version: 7.10.0 + '@prisma/client': + specifier: ^7.10.0 + version: 7.10.0(prisma@7.10.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(magicast@0.5.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(typescript@6.0.3))(typescript@6.0.3) + class-transformer: + specifier: ^0.5.1 + version: 0.5.1 + class-validator: + specifier: ^0.15.1 + version: 0.15.1 + dotenv: + specifier: ^18.0.5 + version: 18.0.5 + jose: + specifier: ^6.2.12 + version: 6.2.12 + pg: + specifier: ^8.23.1 + version: 8.23.1 + prisma: + specifier: ^7.10.0 + version: 7.10.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(magicast@0.5.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(typescript@6.0.3) + reflect-metadata: + specifier: ^0.2.2 + version: 0.2.2 + rxjs: + specifier: ^7.8.1 + version: 7.8.2 + stripe: + specifier: ^23.0.0 + version: 23.0.0(@types/node@24.19.1) + devDependencies: + '@nestjs/cli': + specifier: ^12.0.0 + version: 12.0.8(@types/node@24.19.1)(prettier@3.9.9) + '@nestjs/schematics': + specifier: ^12.0.0 + version: 12.0.6(chokidar@5.0.0)(prettier@3.9.9)(typescript@6.0.3) + '@nestjs/testing': + specifier: ^12.0.1 + version: 12.1.2(@nestjs/common@12.1.2(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@12.1.2)(@nestjs/platform-express@12.1.2) + '@types/express': + specifier: ^5.0.0 + version: 5.0.6 + '@types/node': + specifier: ^24.0.0 + version: 24.19.1 + '@types/pg': + specifier: ^8.23.1 + version: 8.23.1 + '@types/supertest': + specifier: ^7.0.0 + version: 7.2.1 + '@vitest/coverage-v8': + specifier: ^4.1.2 + version: 4.1.11(vitest@4.1.11) + oxlint: + specifier: ^1.58.0 + version: 1.86.0(oxlint-tsgolint@7.0.2003) + oxlint-tsgolint: + specifier: ^7.0.2001 + version: 7.0.2003 + prettier: + specifier: ^3.4.2 + version: 3.9.9 + supertest: + specifier: ^7.0.0 + version: 7.3.1 + typescript: + specifier: ^6.0.2 + version: 6.0.3 + vite: + specifier: ^8.3.2 + version: 8.3.2(@types/node@24.19.1)(esbuild@0.28.2)(jiti@2.7.0) + vitest: + specifier: ^4.1.2 + version: 4.1.11(@types/node@24.19.1)(@vitest/coverage-v8@4.1.11)(vite@8.3.2(@types/node@24.19.1)(esbuild@0.28.2)(jiti@2.7.0)) + + apps/prevision-web: + dependencies: + '@clerk/react': + specifier: ^6.17.5 + version: 6.17.5(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@prevision/tiles': + specifier: workspace:* + version: link:../../packages/tiles + '@tanstack/react-query': + specifier: ^5.104.0 + version: 5.104.1(react@18.3.1) + '@vercel/functions': + specifier: ^3.9.9 + version: 3.9.11 + '@viz2d/core': + specifier: ^0.1.0 + version: 0.1.0 + '@viz2d/sdk': + specifier: ^0.1.4 + version: 0.1.4 + clsx: + specifier: ^2.1.1 + version: 2.1.1 + react: + specifier: ^18.3.1 + version: 18.3.1 + react-dom: + specifier: ^18.3.1 + version: 18.3.1(react@18.3.1) + react-router-dom: + specifier: ^6.30.6 + version: 6.30.6(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + tailwind-merge: + specifier: ^2.6.1 + version: 2.6.1 + devDependencies: + '@types/node': + specifier: ^26.6.3 + version: 26.6.4 + '@types/react': + specifier: ^18.3.31 + version: 18.3.31 + '@types/react-dom': + specifier: ^18.3.7 + version: 18.3.7(@types/react@18.3.31) + '@typescript-eslint/eslint-plugin': + specifier: ^7.18.0 + version: 7.18.0(@typescript-eslint/parser@7.18.0(eslint@8.57.1)(typescript@5.9.3))(eslint@8.57.1)(typescript@5.9.3) + '@typescript-eslint/parser': + specifier: ^7.18.0 + version: 7.18.0(eslint@8.57.1)(typescript@5.9.3) + '@vitejs/plugin-react': + specifier: ^4.7.0 + version: 4.7.0(vite@5.4.21(@types/node@26.6.4)(lightningcss@1.33.0)) + autoprefixer: + specifier: ^10.6.1 + version: 10.6.1(postcss@8.5.28) + eslint: + specifier: ^8.57.1 + version: 8.57.1 + eslint-plugin-react-hooks: + specifier: ^4.6.2 + version: 4.6.2(eslint@8.57.1) + eslint-plugin-react-refresh: + specifier: ^0.4.26 + version: 0.4.26(eslint@8.57.1) + postcss: + specifier: ^8.5.28 + version: 8.5.28 + tailwindcss: + specifier: ^3.4.19 + version: 3.4.19 + typescript: + specifier: ~5.9.3 + version: 5.9.3 + vite: + specifier: ^5.4.21 + version: 5.4.21(@types/node@26.6.4)(lightningcss@1.33.0) + vite-plugin-wasm: + specifier: ^3.6.0 + version: 3.6.0(vite@5.4.21(@types/node@26.6.4)(lightningcss@1.33.0)) + + packages/tiles: + devDependencies: + '@prevision/tsconfig': + specifier: workspace:* + version: link:../tsconfig + typescript: + specifier: ~5.9.3 + version: 5.9.3 + + packages/tsconfig: {} + +packages: + + '@alloc/quick-lru@5.3.0': + resolution: {integrity: sha512-U4+70Pc5ZS9osnCBCE5Jha/ciHM+Yp+CNMNC/7HvYbNRk1Ldd+f7qO65W5qfhu/TCv+/ozljlXXe9Nj8419DMA==} + engines: {node: '>=10'} + + '@angular-devkit/core@22.2.0': + resolution: {integrity: sha512-dELBwXtJWUxFALdEVvdk8qK+XBa17EH5H9NZm+041/esjNi6SaZMusqBgr2PZKq7hD+O2jSCEHbey/hwkz2Awg==} + engines: {node: ^22.22.3 || ^24.15.0 || >=26.0.0, npm: ^6.11.0 || ^7.5.6 || >=8.0.0, yarn: '>= 1.13.0'} + peerDependencies: + chokidar: ^5.0.0 + peerDependenciesMeta: + chokidar: + optional: true + + '@angular-devkit/schematics-cli@22.2.0': + resolution: {integrity: sha512-BGKAyxEpbZYKtCPwCMv8B9TPYb8qKHUZ2BRi61cfbMGcsrKPU4nHCPlz7Z84yDENuuQERZJh12p95mlkMC69yw==} + engines: {node: ^22.22.3 || ^24.15.0 || >=26.0.0, npm: ^6.11.0 || ^7.5.6 || >=8.0.0, yarn: '>= 1.13.0'} + hasBin: true + + '@angular-devkit/schematics@22.2.0': + resolution: {integrity: sha512-yhp/LRzKHJOzo2gFm9+H5DKnsT9adi+ItO2pW0pW2B455sqZYE8RJaSku+TSlv+PvWSmbtFsPXNgSRLA6pSk8Q==} + engines: {node: ^22.22.3 || ^24.15.0 || >=26.0.0, npm: ^6.11.0 || ^7.5.6 || >=8.0.0, yarn: '>= 1.13.0'} + + '@babel/code-frame@7.29.7': + resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==} + engines: {node: '>=6.9.0'} + + '@babel/compat-data@7.29.7': + resolution: {integrity: sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==} + engines: {node: '>=6.9.0'} + + '@babel/core@7.29.7': + resolution: {integrity: sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==} + engines: {node: '>=6.9.0'} + + '@babel/generator@7.29.8': + resolution: {integrity: sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==} + engines: {node: '>=6.9.0'} + + '@babel/helper-compilation-targets@7.29.7': + resolution: {integrity: sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==} + engines: {node: '>=6.9.0'} + + '@babel/helper-globals@7.29.7': + resolution: {integrity: sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==} + engines: {node: '>=6.9.0'} + + '@babel/helper-module-imports@7.29.7': + resolution: {integrity: sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==} + engines: {node: '>=6.9.0'} + + '@babel/helper-module-transforms@7.29.7': + resolution: {integrity: sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0 + + '@babel/helper-plugin-utils@7.29.7': + resolution: {integrity: sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-string-parser@7.29.7': + resolution: {integrity: sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-identifier@7.29.7': + resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-option@7.29.7': + resolution: {integrity: sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==} + engines: {node: '>=6.9.0'} + + '@babel/helpers@7.29.7': + resolution: {integrity: sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==} + engines: {node: '>=6.9.0'} + + '@babel/parser@7.29.9': + resolution: {integrity: sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==} + engines: {node: '>=6.0.0'} + hasBin: true + + '@babel/plugin-transform-react-jsx-self@7.29.7': + resolution: {integrity: sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0-0 + + '@babel/plugin-transform-react-jsx-source@7.29.7': + resolution: {integrity: sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0-0 + + '@babel/template@7.29.7': + resolution: {integrity: sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==} + engines: {node: '>=6.9.0'} + + '@babel/traverse@7.29.8': + resolution: {integrity: sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==} + engines: {node: '>=6.9.0'} + + '@babel/types@7.29.8': + resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==} + engines: {node: '>=6.9.0'} + + '@bcoe/v8-coverage@1.0.2': + resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==} + engines: {node: '>=18'} + + '@borewit/text-codec@0.2.2': + resolution: {integrity: sha512-DDaRehssg1aNrH4+2hnj1B7vnUGEjU6OIlyRdkMd0aUdIUvKXrJfXsy8LVtXAy7DRvYVluWbMspsRhz2lcW0mQ==} + + '@clerk/backend@3.22.0': + resolution: {integrity: sha512-YBJtclx3ytvQGNYhf0/pG+WHUk1ams7Aai3D2AB8c96AkSnzUE+i1Q98HyupIulPDr3fUWeQJtex4DYyO9D4fA==} + engines: {node: '>=20.9.0'} + + '@clerk/react@6.17.5': + resolution: {integrity: sha512-ibTMS/bvo4W7+r+JrnzTig9s4QMVyybxxKCED8VgZE9LSE8XJ0VCH+dVj36hmvndXmpEqNuHRC61SQVJvv+40w==} + engines: {node: '>=20.9.0'} + peerDependencies: + react: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0 + react-dom: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0 + + '@clerk/shared@4.38.0': + resolution: {integrity: sha512-jVHz03682SJ3xsjsSjNX8YyWHllnr91qQEQZpZjCHGUIwGz3rYVavh69cofSuvPrqwOtXReukVEMtodzG2vVCQ==} + engines: {node: '>=20.9.0'} + peerDependencies: + react: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0 + react-dom: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0 + peerDependenciesMeta: + react: + optional: true + react-dom: + optional: true + + '@colors/colors@1.5.0': + resolution: {integrity: sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==} + engines: {node: '>=0.1.90'} + + '@electric-sql/pglite-socket@0.1.3': + resolution: {integrity: sha512-LAciWM0M1dCL8hlsxu2venbVZcdxema0BtDfpWYVqr+Y468UADw0pFWidhKw1M8sfJ8rdLT71tjMmnirf/IZRQ==} + hasBin: true + peerDependencies: + '@electric-sql/pglite': 0.4.3 + + '@electric-sql/pglite-tools@0.3.3': + resolution: {integrity: sha512-AlzLJTRJ8+UFgK8CmxIpyIpJ0+YaFw02IiOSdYrqxwPXdSyeIShz8aa9Tq+tYFXdPwcaMp/Fc80mQZ1dkOQ/wg==} + peerDependencies: + '@electric-sql/pglite': 0.4.3 + + '@electric-sql/pglite@0.4.3': + resolution: {integrity: sha512-ichuWTgtd4mOM1G4SpyGJa5trT03lWbMypDV0fUXUCXg5hiHqVAz/bZyV68NqmkLB7WcYmj1RMJVSp8HV/v/ZQ==} + + '@esbuild/aix-ppc64@0.21.5': + resolution: {integrity: sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [aix] + + '@esbuild/aix-ppc64@0.28.2': + resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.21.5': + resolution: {integrity: sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==} + engines: {node: '>=12'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm64@0.28.2': + resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.21.5': + resolution: {integrity: sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==} + engines: {node: '>=12'} + cpu: [arm] + os: [android] + + '@esbuild/android-arm@0.28.2': + resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.21.5': + resolution: {integrity: sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==} + engines: {node: '>=12'} + cpu: [x64] + os: [android] + + '@esbuild/android-x64@0.28.2': + resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.21.5': + resolution: {integrity: sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==} + engines: {node: '>=12'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-arm64@0.28.2': + resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.21.5': + resolution: {integrity: sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==} + engines: {node: '>=12'} + cpu: [x64] + os: [darwin] + + '@esbuild/darwin-x64@0.28.2': + resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.21.5': + resolution: {integrity: sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==} + engines: {node: '>=12'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-arm64@0.28.2': + resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.21.5': + resolution: {integrity: sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.28.2': + resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.21.5': + resolution: {integrity: sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==} + engines: {node: '>=12'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm64@0.28.2': + resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.21.5': + resolution: {integrity: sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==} + engines: {node: '>=12'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-arm@0.28.2': + resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.21.5': + resolution: {integrity: sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==} + engines: {node: '>=12'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-ia32@0.28.2': + resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.21.5': + resolution: {integrity: sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==} + engines: {node: '>=12'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-loong64@0.28.2': + resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.21.5': + resolution: {integrity: sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==} + engines: {node: '>=12'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-mips64el@0.28.2': + resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.21.5': + resolution: {integrity: sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-ppc64@0.28.2': + resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.21.5': + resolution: {integrity: sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==} + engines: {node: '>=12'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-riscv64@0.28.2': + resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.21.5': + resolution: {integrity: sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==} + engines: {node: '>=12'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-s390x@0.28.2': + resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.21.5': + resolution: {integrity: sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [linux] + + '@esbuild/linux-x64@0.28.2': + resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-arm64@0.28.2': + resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.21.5': + resolution: {integrity: sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==} + engines: {node: '>=12'} + cpu: [x64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.28.2': + resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-arm64@0.28.2': + resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.21.5': + resolution: {integrity: sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==} + engines: {node: '>=12'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.28.2': + resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openharmony-arm64@0.28.2': + resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/sunos-x64@0.21.5': + resolution: {integrity: sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==} + engines: {node: '>=12'} + cpu: [x64] + os: [sunos] + + '@esbuild/sunos-x64@0.28.2': + resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.21.5': + resolution: {integrity: sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==} + engines: {node: '>=12'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-arm64@0.28.2': + resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.21.5': + resolution: {integrity: sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==} + engines: {node: '>=12'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-ia32@0.28.2': + resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.21.5': + resolution: {integrity: sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==} + engines: {node: '>=12'} + cpu: [x64] + os: [win32] + + '@esbuild/win32-x64@0.28.2': + resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@eslint-community/eslint-utils@4.10.1': + resolution: {integrity: sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + peerDependencies: + eslint: ^6.0.0 || ^7.0.0 || >=8.0.0 + + '@eslint-community/regexpp@4.12.2': + resolution: {integrity: sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==} + engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} + + '@eslint/eslintrc@2.1.4': + resolution: {integrity: sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + '@eslint/js@8.57.1': + resolution: {integrity: sha512-d9zaMRSTIKDLhctzH12MtXvJKSSUhaHcjV+2Z+GK+EEY7XKpP5yR4x+N3TAcHTcu963nIr+TMcCb4DBCYX1z6Q==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + '@humanwhocodes/config-array@0.13.0': + resolution: {integrity: sha512-DZLEEqFWQFiyK6h5YIeynKx7JlvCYWL0cImfSRXZ9l4Sg2efkFGTuFf6vzXjK1cq6IYkU+Eg/JizXw+TD2vRNw==} + engines: {node: '>=10.10.0'} + deprecated: Use @eslint/config-array instead + + '@humanwhocodes/module-importer@1.0.1': + resolution: {integrity: sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==} + engines: {node: '>=12.22'} + + '@humanwhocodes/object-schema@2.0.3': + resolution: {integrity: sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==} + deprecated: Use @eslint/object-schema instead + + '@inquirer/ansi@2.0.8': + resolution: {integrity: sha512-WpQM+Ti6Z40EFwwt+uL2p4UabT+W179zHp6HhLVOzfbwnVn05IPO/eXIZXGNqcT1jbQ15SujNLzQ39k4QPPxBQ==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + + '@inquirer/checkbox@5.2.5': + resolution: {integrity: sha512-bRt8J8m+Fot9CXv+zNQGXUq2ET0MggR1fPz7v6edN6MFYmsbfGnMmkmWZJEegMKqrAC8ej/o1sqisHZXZJMAfQ==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/confirm@6.3.2': + resolution: {integrity: sha512-Xvr/0HggjddPtGppuqVmxhTw+Hr8PvsZ/k0HmOEaAqQEt80OITNkFWnsdNmyT0/eM4Ab+iJLx2R8rctlEyfSVg==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/core@12.0.3': + resolution: {integrity: sha512-wsSy0sznmXwkty+2PzZwx00Cazc/E0r0B7mAzdGROz2Ct+DFZXaK7WDjGZvgjRldxH5ZhFVfF2lgkYrqgOw2KA==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/editor@5.3.3': + resolution: {integrity: sha512-YsKkS2q63IiLtaDK/9nqzdComN97SDQrmKiyNggN+ceP4ty+Z6VwyTz3FpjeUWeW1Efss2xHFKCC9sx7hnrsxg==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/expand@5.1.5': + resolution: {integrity: sha512-uHuXLmXW+TtIfT/9vSBotypAkqn1n34Ul+CLGPos/xANyO4Ff5xZzkYhbKR4NEcfVK4a9mHQOpwVZzluSHFRGw==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/external-editor@3.0.5': + resolution: {integrity: sha512-f3QQJRIX5ZEneBHNUIuPjmbdzHnmRFJA8r2dkcb8q+OM5Uv5KtnuAttQumnrjcBVBM3mcTX1CkmtAkU58VRZxg==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/figures@2.0.9': + resolution: {integrity: sha512-EAWgUTGQ/Umgga51dE3B2PUHbufuXarDfg86uVgoSgNHNNQnyFKcOrQLWVqYMghuSyHh8+2HUH0Js9cTC1WAdg==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + + '@inquirer/input@5.1.6': + resolution: {integrity: sha512-HtcJhB2QFVXbLuJ5S3syhNbTUVxYvwqV4VRBDkQceBloC9bmTViUoRFP5PbSaDZb3HzfPmpuU/gG4ybVBz4FHA==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/number@4.2.3': + resolution: {integrity: sha512-6Yuwh1NGSbu1Lo4N1EWjXs1jKRntLg/ZCwhmeorEHde90v1XxAozdbd4Iu30eOQLW+6h1hp2O9ujNfLSbTPJnA==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/password@5.2.2': + resolution: {integrity: sha512-W9zYdyzogK+6110mqwaSJWCBu2yA5Q/OfnGSjjZB1bNpHlmUozXxTl0+QOZBNeVd6Qo81/qT75gW05gLAtITxw==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/prompts@8.7.2': + resolution: {integrity: sha512-QoRB4wFIjgH5iOhSjoIKMkTvSHDuV+O3OITlIqAYO0oK5x364GJILXiMBvlPiE+klg7Xx9tq5XVqQHcGUDYYPA==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/rawlist@5.3.5': + resolution: {integrity: sha512-1oHky1ONfCOwNrnkQGDE1oaSij/3fI6HFMSf2H/WsGO2lEyDX9My82iggITSy9ddSZ8yk8j9v41OI0fVoSIoaA==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/search@4.3.3': + resolution: {integrity: sha512-fyuIU1Nbpvwlikjg3gXwJFDI11+EFjqQ7P+iByfmivIKQ1vmaykNrD/vy5unHuUqUpsOsnvJ25//tPF7E/RBRA==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/select@5.2.5': + resolution: {integrity: sha512-9kc15hr8r/kI+3DO/xLog5nOzTz1jqsHXa6JBFzmQKhkoJ8Slda1I1L/uD8ZSZ9tF1yp79wwXe7mclvX1rqR2Q==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/type@4.1.1': + resolution: {integrity: sha512-yJoHYrMnxIsJZCY+0Vb66Dy3he3kL3e2wOBKhoSwWWAzZAY82emlxwgprCtp6yRixvNRNq9ztfRWQYPNr3Go7A==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@jridgewell/gen-mapping@0.3.13': + resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} + + '@jridgewell/remapping@2.3.5': + resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==} + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@lukeed/csprng@1.1.0': + resolution: {integrity: sha512-Z7C/xXCiGWsg0KuKsHTKJxbWhpI3Vs5GwLfOean7MGyVFGqdRgBbAjOCh6u4bbjPc/8MJ2pZmK/0DLdCbivLDA==} + engines: {node: '>=8'} + + '@napi-rs/lzma-linux-x64-gnu@1.5.1': + resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==} + engines: {node: ^22.20 || ^24.12 || >=25} + cpu: [x64] + os: [linux] + + '@nestjs/cli@12.0.8': + resolution: {integrity: sha512-iqm+KXb8cnpnlD4hMBf1w2/4i1GSs0DCLI7oyP4MTmwf9KmjTG1SpAjkl/D+kKuUToycBrMF4+eSwyPVdTMGKQ==} + engines: {node: '>= 20.11'} + hasBin: true + peerDependencies: + '@rspack/core': ^1.7.7 || ^2.1.10 + '@swc/cli': ^0.8.0 + '@swc/core': ^1.15.18 + fork-ts-checker-webpack-plugin: ^9.1.0 + ts-loader: ^9.5.4 + tsconfig-paths-webpack-plugin: ^4.2.0 + webpack: ^5.105.4 + webpack-node-externals: ^3.0.0 + peerDependenciesMeta: + '@rspack/core': + optional: true + '@swc/cli': + optional: true + '@swc/core': + optional: true + fork-ts-checker-webpack-plugin: + optional: true + ts-loader: + optional: true + tsconfig-paths-webpack-plugin: + optional: true + webpack: + optional: true + webpack-node-externals: + optional: true + + '@nestjs/common@12.1.2': + resolution: {integrity: sha512-e2tvLcEaG18sJy5IXrdSLv0ZBpR5djWxypCLkLuMAEFCvVPYL1lEIhvAMBkarlg+ZA8tbZN40J0tFurUl9NpdA==} + peerDependencies: + class-transformer: '>=0.4.1' + class-validator: '>=0.13.2' + reflect-metadata: ^0.1.12 || ^0.2.0 + rxjs: ^7.1.0 + peerDependenciesMeta: + class-transformer: + optional: true + class-validator: + optional: true + + '@nestjs/core@12.1.2': + resolution: {integrity: sha512-ieNRDv6P6dLsF/wMz9IUjwnyQbj7/Oluq1FXe3Xhje7TFSKPprLc83QniA2I6tjkr7YVDosdL2Dj7CVv9kU8og==} + engines: {node: '>= 20'} + peerDependencies: + '@nestjs/common': ^12.0.0 + '@nestjs/microservices': ^12.0.0 + '@nestjs/platform-express': ^12.0.0 + '@nestjs/websockets': ^12.0.0 + reflect-metadata: ^0.1.12 || ^0.2.0 + rxjs: ^7.1.0 + peerDependenciesMeta: + '@nestjs/microservices': + optional: true + '@nestjs/platform-express': + optional: true + '@nestjs/websockets': + optional: true + + '@nestjs/platform-express@12.1.2': + resolution: {integrity: sha512-//ftPv5+UONizm5zcme/AP91EFo1EsqFFyC2I3HC2w8swYVXadHKW1L3A2mgUuOhM1sdKkd2gzjQmL9504x85Q==} + peerDependencies: + '@nestjs/common': ^12.0.0 + '@nestjs/core': ^12.0.0 + + '@nestjs/schematics@12.0.6': + resolution: {integrity: sha512-2OG0BUhGPJqVvWFhiy+7oaQa4VQUvTS9Dw8YRfvweznl4KS3YyZrdPi4cVGuRAThoEIsbdfguZzSOv1+t8U1tg==} + engines: {node: ^22.22.3 || ^24.15.0 || >=26.0.0} + peerDependencies: + prettier: ^3.0.0 + typescript: '>=6.0.0' + peerDependenciesMeta: + prettier: + optional: true + + '@nestjs/testing@12.1.2': + resolution: {integrity: sha512-JgetYeGHGK6iUEztXyiQLOfYLWqUgAyexLMzhuAMasgLiDgYShh/PoRESE9tzpRZo4eWKme3uSZ9DFR6Myuojw==} + peerDependencies: + '@nestjs/common': ^12.0.0 + '@nestjs/core': ^12.0.0 + '@nestjs/microservices': ^12.0.0 + '@nestjs/platform-express': ^12.0.0 + peerDependenciesMeta: + '@nestjs/microservices': + optional: true + '@nestjs/platform-express': + optional: true + + '@noble/hashes@1.8.0': + resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==} + engines: {node: ^14.21.3 || >=16} + + '@nodelib/fs.scandir@2.1.5': + resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==} + engines: {node: '>= 8'} + + '@nodelib/fs.stat@2.0.5': + resolution: {integrity: sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==} + engines: {node: '>= 8'} + + '@nodelib/fs.walk@1.2.8': + resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==} + engines: {node: '>= 8'} + + '@oxc-project/types@0.152.0': + resolution: {integrity: sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw==} + + '@oxlint-tsgolint/darwin-arm64@7.0.2003': + resolution: {integrity: sha512-TgV33rXr6ueXBwvc+0nssUkTBSXHJxv77I8p4RCjDjCnvexHtmoPiudVRDfj3S3puMDdeQdHW6jdUgUPy3nr/w==} + cpu: [arm64] + os: [darwin] + + '@oxlint-tsgolint/darwin-x64@7.0.2003': + resolution: {integrity: sha512-hY3FMAjIaPDdK3FNxyRXRfHPOFeoBn6dmnLyKZgQ2IbTTD1adXhl6PfCIqHhCPvurigv7nf7mYuWZZ19MmJzmg==} + cpu: [x64] + os: [darwin] + + '@oxlint-tsgolint/linux-arm64@7.0.2003': + resolution: {integrity: sha512-eAET4JpyfBbg8SO0K74o4R55tEjVC292pIyxGOw2XGf8x/HrPNyxwQ478jMYOM54FIVOHc8sJ6VRHxluy6lucw==} + cpu: [arm64] + os: [linux] + + '@oxlint-tsgolint/linux-x64@7.0.2003': + resolution: {integrity: sha512-GXdyO/XyqDJ3s/llR/oOktLsYNjZtWSQBy0JMc+/0gsNPvTcseKPhn9c6KcFyWmnr6H4vljYALbujonqSzzEGw==} + cpu: [x64] + os: [linux] + + '@oxlint-tsgolint/win32-arm64@7.0.2003': + resolution: {integrity: sha512-TWauXnPfet0VgpmrstoAK58eJ4gbuwPUuUTQmYQAzE/RG1CpnxXtrKUJULf6lyerPE4KN3gM+DflIA1hOH+38Q==} + cpu: [arm64] + os: [win32] + + '@oxlint-tsgolint/win32-x64@7.0.2003': + resolution: {integrity: sha512-DoRmfe7j8VqNlukp8liRVW45GQDhzRccNenjD/pdzelgtffW47pCMd1xbJLkPaPbKnTwID3onn3VZlL7JbebEA==} + cpu: [x64] + os: [win32] + + '@oxlint/binding-android-arm-eabi@1.86.0': + resolution: {integrity: sha512-63Ozq6yQn79B2UxjSZ9huJmI+3/ZPI7hxAe6TyFh9oQL447KnIMoffOdtog+h4KILbQr61ZRvFPW5gYbAUgpgQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@oxlint/binding-android-arm64@1.86.0': + resolution: {integrity: sha512-JdLGp44phbf/0Du236Dt06yfK6Qw8xhTFeDvHJdjk167r59OfP5+BL31mgMYVnswS8e+j6tFuccSY0QDC/lgCw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@oxlint/binding-darwin-arm64@1.86.0': + resolution: {integrity: sha512-h+vkOr4ik6KLFCXdtNVEj9xfnXfNUpPoF95QjORdhiSpLqQePzcN81kGHjAgsw1/G7WBWK5KsFKbI2UK8EyzMA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@oxlint/binding-darwin-x64@1.86.0': + resolution: {integrity: sha512-wbglRuH5eKsp68keTOOeKDHU1astWSRYFsh2bwKQTAPb44rD6kVgzYI1ZrAJRTc6/7PH55ZXFCQx0rQXrj0UdA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@oxlint/binding-freebsd-x64@1.86.0': + resolution: {integrity: sha512-yTQ7QSOlNfQsrfbeVweTiegQJLKPjUKgXp/JpGiFzza6Hp29S9LAoH77TM3L0RjK39iQRZB5lk5iq2t241Mfag==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@oxlint/binding-linux-arm-gnueabihf@1.86.0': + resolution: {integrity: sha512-QYJGy0E2Tv8GAayyBIeHFTwQb8u+zrvrOYrifuDGZDr9ad5XsDhiMScpZymhS9fwWjqrgG2ZUwT4vpY0ISqp4Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxlint/binding-linux-arm-musleabihf@1.86.0': + resolution: {integrity: sha512-oQo83CafLT8p3qh0AGkN0tSUIh5Hm63mfDsoqUmBQUBnSZLNBAbyRaAftfGY5a0cKZ34dG6jAtMYgcY5kZqt5g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxlint/binding-linux-arm64-gnu@1.86.0': + resolution: {integrity: sha512-EM6wy5c2UM12qPb7iDJDBAZvHyfEJGH6iosFgaFiaRZpirz99//EHcUyD2KAskz07x1TULuiAtsojf4nvWWksw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + + '@oxlint/binding-linux-arm64-musl@1.86.0': + resolution: {integrity: sha512-vCiUQb9ZNzZalxYRU4mlZwUqT5f+c7Sk9DwUOplWHtik3Dl4r3DVnUB5tBeRuTAUe6MUVCTylNW7TkkN8J1oTw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + + '@oxlint/binding-linux-ppc64-gnu@1.86.0': + resolution: {integrity: sha512-T0AzE89yjTYmOhB/hb6i+rWTpe2mYt+xiguBhs9DEPIJTZ1H8OYqsE4VxJHHw2Wlq8Mztwvp2P8NV87ZOuhPRw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + + '@oxlint/binding-linux-riscv64-gnu@1.86.0': + resolution: {integrity: sha512-s49r0K2f5Oc7fJoMUO1WkdhYK5Ob79uYRwWQ/XNoGysaOq3RUGmGUbHSuXiyydTTA+P9xEdDEnnlZVXiaSJhlw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + + '@oxlint/binding-linux-riscv64-musl@1.86.0': + resolution: {integrity: sha512-JIa2tYR8ayb3nvcMSZzn4O/xTy13S7MHllu7cBD+B5qDQXXSRy/Vwk1aNpiTjZmBJGwKCHOy/NvnY5Xcwg27uQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + + '@oxlint/binding-linux-s390x-gnu@1.86.0': + resolution: {integrity: sha512-XwXMyBsAuWZkhZU74UNcfQKr1CJJAKnS80dZzOnjl6A4fKcf91IjFgidegQugMHA5SN8ulwDXEDV1yPntjXgQQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + + '@oxlint/binding-linux-x64-gnu@1.86.0': + resolution: {integrity: sha512-C1WjukSyMnr66b+w1/tV8RFVv6d9v0MzDf4p9IxVXknqgmTHBgZh1pccN1eHzFr0b9Tbb3OXoPsAAdAuHAQfeA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + + '@oxlint/binding-linux-x64-musl@1.86.0': + resolution: {integrity: sha512-ap6KLmvC38c6MdYzsIh25cXQupqYvjd37tMNftzrX1DCtkX1Gcf2B+S2B17dD4lKa5c5gJog7DQJyDo82PBKyw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + + '@oxlint/binding-openharmony-arm64@1.86.0': + resolution: {integrity: sha512-996Q9w/2GLwNyy5Djs39Jt09aFlr4b7TPhoj7dvo5FHmcyiF68nPz73HNc5UAYKIYeK+M9JzPQ4Wg1r1dXvP6A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@oxlint/binding-win32-arm64-msvc@1.86.0': + resolution: {integrity: sha512-9uTCHYTknNkug5+46ViSoUMuOuGWK61D87QnblU6CXaWKJC630Z7dbls61vdHxya/cR2ycQZ6Mm6ckgF6Cag5g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@oxlint/binding-win32-ia32-msvc@1.86.0': + resolution: {integrity: sha512-a47ga7EKVfMU8rO0i1m3mGwfNRj3FhQyt1d/ukO/E9u1HHF3KpR3tyb3VhuJBGEVPF8uR4exSyHUyx7xbE+uxw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ia32] + os: [win32] + + '@oxlint/binding-win32-x64-msvc@1.86.0': + resolution: {integrity: sha512-az4dzifCRzES1crwu6pDFXzJTIanrdxXFL9TbiJWrx9LKcuacbR83aPvxDA1LKLNswi/RoqitC7Afcflhu3zBQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@paralleldrive/cuid2@2.3.1': + resolution: {integrity: sha512-XO7cAxhnTZl0Yggq6jOgjiOHhbgcO4NqFqwSmQpjK3b6TEE6Uj/jfSk6wzYyemh3+I0sHirKSetjQwn5cZktFw==} + + '@prisma/adapter-pg@7.10.0': + resolution: {integrity: sha512-N7nwSor0HO1Kz6xBv0TPAjAPysKK0fac6p4fVN3ensLOuzc/83Fgmln5k92eK/cvzqdkSR/2kkAqlbcdwVrwpw==} + + '@prisma/client-runtime-utils@7.10.0': + resolution: {integrity: sha512-cnCy7lUV8/CctgKVEmqAbSLAmwqJdE/qAlqTBk/0NDk59zEb2cZ0M0M0E4vVPnqbSEYudRroQDvOWfUZH6RIfw==} + + '@prisma/client@7.10.0': + resolution: {integrity: sha512-Ubw/QS9JGIBSBUsyxAUQuK/Jcu0Tsva7le7QbLd91Kix9yJvYDdj5QkwgEbbZniH80dd+sziQcALPc+HnvQC8Q==} + engines: {node: ^20.19 || ^22.12 || >=24.0} + peerDependencies: + prisma: '*' + typescript: '>=5.4.0' + peerDependenciesMeta: + prisma: + optional: true + typescript: + optional: true + + '@prisma/config@7.10.0': + resolution: {integrity: sha512-Rcg828gIRE3HOQ3pOATFjV5d/P0U9OIobxhd/IMxlfWjA4vru0eGwb0AIwFw0rmcLMVShohZYWPixVxkBHsxUA==} + + '@prisma/debug@7.10.0': + resolution: {integrity: sha512-caygJKtltmRIgdJ3jRpkOr7yM4DW6zxo5uOmojKWFb3asnxWoRkQOwZmXBgD8FZp4htrX+nMpcWqDwzlQ1+Y4g==} + + '@prisma/debug@7.2.0': + resolution: {integrity: sha512-YSGTiSlBAVJPzX4ONZmMotL+ozJwQjRmZweQNIq/ER0tQJKJynNkRB3kyvt37eOfsbMCXk3gnLF6J9OJ4QWftw==} + + '@prisma/dev@0.24.17': + resolution: {integrity: sha512-UvdZzmpFwknnfreh6Jije84ekkYGPYEJhXG1tFzCsCfQyzJifrOo38eZc0qajzvaC6OLUOrN9ML5XfCnEZL9DA==} + + '@prisma/driver-adapter-utils@7.10.0': + resolution: {integrity: sha512-u8zkcRLlaryO652T4qavBg0HmzNW5tSKdsCn6hc1PhWAp/J6k0vrxLuUs+b9o+HcjsK7Dfa01o4OFSn0frauJA==} + + '@prisma/engines-version@7.10.0-4.0edf323efd1d98336f3f0a68684b56f689b900d3': + resolution: {integrity: sha512-8OJ6RuZTZ06eFUOtBwxVmv8XMmOW6HWN5F+uxUbZkGxR0Bfab1dfAdXaHPmR5mb59E+fmUo8IOzXlbLY1SClbw==} + + '@prisma/engines@7.10.0': + resolution: {integrity: sha512-KNumN6NHFwybvfdYzTee9pqwx5PvknpWAaHn6L5NsbrKdl+SQrsVZs9opKs6U6SAsvB26HDt3WybRjOhgoWOYQ==} + + '@prisma/fetch-engine@7.10.0': + resolution: {integrity: sha512-Zqyu8DY14t6W/xwmAxUYWCXtHrvQnSvT644EAZSsdM8NSmCS74vJJbBKdVsK3ucFpnUWkEpbO1a0CxJXrg130g==} + + '@prisma/get-platform@7.10.0': + resolution: {integrity: sha512-0bra1LFYi8xNw0yqV62bHJNQk4BKleOngZiqPWIQc7a3+9q6rqsnqJ15BuepP8943PFMvtmgnP52juZsyYkA6w==} + + '@prisma/get-platform@7.2.0': + resolution: {integrity: sha512-k1V0l0Td1732EHpAfi2eySTezyllok9dXb6UQanajkJQzPUGi3vO2z7jdkz67SypFTdmbnyGYxvEvYZdZsMAVA==} + + '@prisma/query-plan-executor@7.2.0': + resolution: {integrity: sha512-EOZmNzcV8uJ0mae3DhTsiHgoNCuu1J9mULQpGCh62zN3PxPTd+qI9tJvk5jOst8WHKQNwJWR3b39t0XvfBB0WQ==} + + '@prisma/streams-local@0.1.11': + resolution: {integrity: sha512-0TcebL559MByKqTJ+SsrFIEg228iw8UCVRFckzgfRSiJqczhs+MuAgWOF9lnOIV/IVqvu+KMnFTH0eDeTQMpUg==} + engines: {bun: '>=1.2.0', node: '>=22.0.0'} + + '@prisma/studio-core@0.33.0': + resolution: {integrity: sha512-V2fX/nKEymNTrHXwfP26PGjoLStO35Ogu+ex7CFJbLrMYEcZxxZpiSNOs7px23Hk5mzLWvM5RsqG6Ka+rha+wg==} + engines: {node: ^20.19 || ^22.12 || >=24.0, pnpm: '8'} + peerDependencies: + '@types/react': ^18.0.0 || ^19.0.0 + react: ^18.0.0 || ^19.0.0 + react-dom: ^18.0.0 || ^19.0.0 + + '@radix-ui/primitive@1.1.3': + resolution: {integrity: sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==} + + '@radix-ui/react-compose-refs@1.1.2': + resolution: {integrity: sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-primitive@2.1.3': + resolution: {integrity: sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-slot@1.2.3': + resolution: {integrity: sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-toggle@1.1.10': + resolution: {integrity: sha512-lS1odchhFTeZv3xwHH31YPObmJn8gOg7Lq12inrr0+BH/l3Tsq32VfjqH1oh80ARM3mlkfMic15n0kg4sD1poQ==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-use-controllable-state@1.2.2': + resolution: {integrity: sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-effect-event@0.0.2': + resolution: {integrity: sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-layout-effect@1.1.1': + resolution: {integrity: sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@remix-run/router@1.23.4': + resolution: {integrity: sha512-q7j5geK7xs3UJSdm9/iytUNclBnLmYx1EnSeCFXHPeutdqgIMeFeHtUZgS3EhlKxdBEAu8OwtJCwmLrEzpSs7Q==} + engines: {node: '>=14.0.0'} + + '@rolldown/binding-android-arm-eabi@1.2.12': + resolution: {integrity: sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@rolldown/binding-android-arm64@1.2.12': + resolution: {integrity: sha512-7KHFgQ5VJxIHcLlrwrc3Xbds7oTNQT7Pgi9gQCJKrd2VGab/UksIOYp6VD8MzCstGxOKMgNamPwUCfxPdP1OHg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.2.12': + resolution: {integrity: sha512-3YIhqHD96nA5SaYNRBR16HnGv4oavZvXfD/ayHM+oYZ0WD/8lBAtf6zQua4kEyAvpqrluKXl0lnOBoiNby7x9w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.2.12': + resolution: {integrity: sha512-UuuJ35MFw4gmFOrE9pEqIV+K3syIKveph+Qc1/ljHZVdoDW4pz/JHR/eMVom+TZGl/5OOvGJOWaOCVt3ZfqhxA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.2.12': + resolution: {integrity: sha512-uMvssit0a4W+/7D8CbHUvG719mH3R2jwXAlh/XcPvuHTE0g++LymF88DCGNX0HM2rBOn0xrzgXktIB6fLSJBTQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.2.12': + resolution: {integrity: sha512-XcFu0R0xWnwzSf4IQgFH1rJIckPN1pLy2R+4r9IDB7Yfu/ys9cVqfa4pBrMHj7a3gl8mIR4nRNPg0e5IvEVs6g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.2.12': + resolution: {integrity: sha512-260UrKgn8tz39ak+SMDOirKzr7V04M9dWPw5llW00SwBivCZoWcRBKV1d8cXnRkUmSZA3BdiUmBHWk7734Ulpw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + + '@rolldown/binding-linux-arm64-musl@1.2.12': + resolution: {integrity: sha512-5YK1I9SqDkbPgc1IA8BgDl34suqUS2q0KWnBrirm0E51YjOs6eo6dV6jbQfNE/argHRSvd0QUGgtpIoYx+WWpw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + + '@rolldown/binding-linux-ppc64-gnu@1.2.12': + resolution: {integrity: sha512-Rkcrmp7eFRg74yL5fXEU91JEWbdEPLevWwGtXpmhbjlD1StScbWTmO94Bhly+Mo+ketKYkdmM1vNUKeWSlx8cQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + + '@rolldown/binding-linux-s390x-gnu@1.2.12': + resolution: {integrity: sha512-qvK4DuAsQc2BSjlx+Xr+IzOIvvxbGZqxFwdWfG6F518Erj0GGISyQbJ6pIappnOxlNPzNHvo/L0BwB30GZ+zVw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + + '@rolldown/binding-linux-x64-gnu@1.2.12': + resolution: {integrity: sha512-Q9uLBO53Xd4QIq1WOycVQyPP1O4HhraEV2qqb3uTrnVw6QZih9duY4vNXOivL1xoUS1/z+W8eF4NMfl2a8Sdjw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + + '@rolldown/binding-linux-x64-musl@1.2.12': + resolution: {integrity: sha512-3IBxWFMjbOZskDPKv8Lf9BCnahlKuHthWkYnyIxOH/QcJrFcS4EmcenthApkwr/5+nEqZlLzeYbxeMaX7A5u4g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + + '@rolldown/binding-openharmony-arm64@1.2.12': + resolution: {integrity: sha512-xtX61xg4LKPkPWilZU1ynKClz5Gj4bf74LML4r3eVLWumKnGjoEr1OSHQhMdbBDoYTi+yjrujvpZe2pUnqCrrA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-win32-arm64-msvc@1.2.12': + resolution: {integrity: sha512-At7fPB6PCaIjzgIhEZFxuT+BBFqiQibJDT4d3PhiR3f4E7bbMZF4aKblbFfEM3sETRDd1YiQx/+U/g/B/ou5Ew==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.2.12': + resolution: {integrity: sha512-WIw2haVKwjuYdXkHaoC0mF8Le71TuCBxjrdKqLbJGctbBABj+ClfmNvtbOnzpq3RokNo5+V1qhtSzJyXorsklQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.0.0-beta.27': + resolution: {integrity: sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==} + + '@rolldown/pluginutils@1.0.1': + resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + + '@rollup/rollup-android-arm-eabi@4.64.0': + resolution: {integrity: sha512-FLLpX941CD/7aBvX3GqLGBM9OvY5PGXTryPJkG5r5/OuBpZpV5k45Uo3RxAvqd35tsyc3hH1bhtz921IKzoIzg==} + cpu: [arm] + os: [android] + + '@rollup/rollup-android-arm64@4.64.0': + resolution: {integrity: sha512-iI32XM/jnDYJsvx5ai/za/7gWO9XoSeFFtU06/ZCaRgyilfJOjaopD3nOpk2WrTCGOyeDt4hleUiGOAnd5tHNg==} + cpu: [arm64] + os: [android] + + '@rollup/rollup-darwin-arm64@4.64.0': + resolution: {integrity: sha512-dRBZlbt2sEtF8Mn4MODThze9fIPdDoOhVSlXMAKy5dQbOYK9pOOoPY4Fat3OTtr0+8zbJo5TTZwlsfxY/kDNJg==} + cpu: [arm64] + os: [darwin] + + '@rollup/rollup-darwin-x64@4.64.0': + resolution: {integrity: sha512-Y3whrJOMucfkhgNkvcM93M6j8C53iEAMmPMYD99C6G1kUy4ELigLWk9ar2/4aCBSRgsql0zdlOemLgW2m5GZgQ==} + cpu: [x64] + os: [darwin] + + '@rollup/rollup-freebsd-arm64@4.64.0': + resolution: {integrity: sha512-S6S1GEzPjFF6IONYJX3AKt/799+8RgBgCcwRnUo+Ep1IvBxUbw5M51iU0TDdK2NWWVnSvCQ8yi6Em0fGASMOng==} + cpu: [arm64] + os: [freebsd] + + '@rollup/rollup-freebsd-x64@4.64.0': + resolution: {integrity: sha512-Ed1DPoFENkXj4IGzSB12SesV40iP6LxCCrbTIkSGIQBpOOxpBM+0kj62lmaeIHfMWTDoddqTOtqc7s8LYfn+Pw==} + cpu: [x64] + os: [freebsd] + + '@rollup/rollup-linux-arm-gnueabihf@4.64.0': + resolution: {integrity: sha512-J/6xhutJPtFyIkmHdf4olOdHHKH5kOJNumojdWn+Elv5ICEYTVOa362Vw27TxsK0BLzb1le3EDlO3UbvFK1lnQ==} + cpu: [arm] + os: [linux] + + '@rollup/rollup-linux-arm-musleabihf@4.64.0': + resolution: {integrity: sha512-G4L/Nnx59d2LvDoV/P4S5lZ7oVLT6hodOHMacqjiq2LL2gts86KbkEBTYL53+fBt0odhf7XPIbIATGoYiJctxg==} + cpu: [arm] + os: [linux] + + '@rollup/rollup-linux-arm64-gnu@4.64.0': + resolution: {integrity: sha512-zF16pvJDEUksGYRbfnXne7pdklAyj2XDmJeYKgP93oq0cUyX9Y8O7lUo1R+IY1GagP/YBvCEDCe7eEcAKpw//g==} + cpu: [arm64] + os: [linux] + + '@rollup/rollup-linux-arm64-musl@4.64.0': + resolution: {integrity: sha512-nIggWn8n+w12+R5lsV+PYYoUY8vuObxPAQqJI7WES+9v0qspYuAHoZMfYM0yLxlipasT5BY9ht5W8t5c/rSCkg==} + cpu: [arm64] + os: [linux] + + '@rollup/rollup-linux-loong64-gnu@4.64.0': + resolution: {integrity: sha512-WLOTiHPzszP0dxIMsHpFeDSOSB5I49Mj8K4+yKE3H1X/D0JRG5XZ5jrctJLMjnUc/LUzaKiwq6EHWNJ8pup8PA==} + cpu: [loong64] + os: [linux] + + '@rollup/rollup-linux-loong64-musl@4.64.0': + resolution: {integrity: sha512-35RK9aRhh7g7Pmeu5gQ01aCvrhXzj9LoBE6xtUcEH1ns+nyTaSzxSpADmBQINu4QiTDGvmQYwo1j5hlg1rRXFw==} + cpu: [loong64] + os: [linux] + + '@rollup/rollup-linux-ppc64-gnu@4.64.0': + resolution: {integrity: sha512-RqTfnpoTjuWfPAmqK5p2edt2AMCDJWm6oTn7sKfmyx+6tRga0ip05SJ977o6udTcIiDeF/CJMUfkaN4gtWt6Aw==} + cpu: [ppc64] + os: [linux] + + '@rollup/rollup-linux-ppc64-musl@4.64.0': + resolution: {integrity: sha512-RQjZPigjxFvFZDijG6rjlSXxhRaTf9zLYVpGK+lVcga64oMqP1GbgVqCb46eHTTceSIgp89Ja0y5aPe3GFBYHg==} + cpu: [ppc64] + os: [linux] + + '@rollup/rollup-linux-riscv64-gnu@4.64.0': + resolution: {integrity: sha512-tjL58mgQcTRnDRpeky+Sth1MKQeYi2Ct6r3Luq9E5aTSjnM/i/JbozqZkKqp9thM5+oDSZxo+05f9kdQedfTGA==} + cpu: [riscv64] + os: [linux] + + '@rollup/rollup-linux-riscv64-musl@4.64.0': + resolution: {integrity: sha512-ictoRyVaoZ8C67myHef+8hhCa6IplXJJ/xUCkVCxziV4zxMZh+jvhkhGsPBLqj1S72fnqD0QH5zL4lcaa4X7DQ==} + cpu: [riscv64] + os: [linux] + + '@rollup/rollup-linux-s390x-gnu@4.64.0': + resolution: {integrity: sha512-8aVvZ2hfr9RLFzBQkQNmYeHLDja8fLeQAmLt757zdKN/B+8L809KlLJKctQjS22wZotptV8G6o7fVPuAs8S1tQ==} + cpu: [s390x] + os: [linux] + + '@rollup/rollup-linux-x64-gnu@4.64.0': + resolution: {integrity: sha512-2dEF8GAcDKwshUfydD+GhosppNyBzhVUHkdFF3CXd3FpOkzj/RZzF5aoEtzklujklT5qFVRU2GK/cFeLaTNKVg==} + cpu: [x64] + os: [linux] + + '@rollup/rollup-linux-x64-musl@4.64.0': + resolution: {integrity: sha512-3XHTvoo2hKkh0MiOfS7SkhHjMaaWF7P4F3drocZZaho/Z8w7h/jpnuBHm91BOQLfvrKHs1yR+zir4E8RI3XzTQ==} + cpu: [x64] + os: [linux] + + '@rollup/rollup-openbsd-x64@4.64.0': + resolution: {integrity: sha512-HKtkzodL4a3KFWDXDoO61cRynAWTR3LnAE0oGtfG9lcNFpNuVYUFOByxDgNqEvic9rvaQbAj+SFwTEWDptRaIw==} + cpu: [x64] + os: [openbsd] + + '@rollup/rollup-openharmony-arm64@4.64.0': + resolution: {integrity: sha512-JBsxqiY16uyyCujtoC3s7zL+SrYyNElptD7K4V+KUoJ2V8/XG3hPWpheK+SuPwNh1cikJvIZmIdsrYXvD6PLJw==} + cpu: [arm64] + os: [openharmony] + + '@rollup/rollup-win32-arm64-msvc@4.64.0': + resolution: {integrity: sha512-S5Qrijh37qhnUYQ0ay8WN3LuWeKjow7wTUyCOPMZtnXiBXYXdsZETI6ZLfYnQAKovltckPLBFdNeD61P2rJc7g==} + cpu: [arm64] + os: [win32] + + '@rollup/rollup-win32-ia32-msvc@4.64.0': + resolution: {integrity: sha512-zbZ6iMmLFEsCtTdc2/y1F/cDFVNNCPF7Ae8PCT/wdPE//hGwYp6r+MyCLMFX+kOeIe09Pz6ASfnnfpSTN1FJQQ==} + cpu: [ia32] + os: [win32] + + '@rollup/rollup-win32-x64-gnu@4.64.0': + resolution: {integrity: sha512-L6Hw69oNpuYaOr1zCG30v0/DqKYCSRwodPGwIcVZ/6f8SOzq9rxtL/xNVI5MO4wjli+Ko0ErK9uHJL3mNPt8wQ==} + cpu: [x64] + os: [win32] + + '@rollup/rollup-win32-x64-msvc@4.64.0': + resolution: {integrity: sha512-nl+CTWIgOGszQmUz/kanfgrfFZ4qiwxKIfT/ryl3N3Ewk5tqizmYtNXiqb7Bu/fDtNgu1kyxdFiAUJNur3iysg==} + cpu: [x64] + os: [win32] + + '@sindresorhus/is@4.6.0': + resolution: {integrity: sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==} + engines: {node: '>=10'} + + '@stablelib/base64@1.0.1': + resolution: {integrity: sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==} + + '@standard-schema/spec@1.1.0': + resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + + '@tanstack/query-core@5.104.1': + resolution: {integrity: sha512-TiRghcrGkUTE+M4JBxvpPSpBhxvIzQairw+cksrHYGr+2uwC77yW1SY9nYxnYRYOppvucf8rEg6b5byoz4rTpw==} + + '@tanstack/react-query@5.104.1': + resolution: {integrity: sha512-Zz70EgjahNI7aCz8BZxM3vUGU44ycxEAzMuCUjLeA7SVhhOkg3ZgPjPJPvHjs6Rmky/dtmnu1WzjGHNHmhCoZQ==} + peerDependencies: + react: ^18 || ^19 + + '@tokenizer/inflate@0.4.1': + resolution: {integrity: sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==} + engines: {node: '>=18'} + + '@tokenizer/token@0.3.0': + resolution: {integrity: sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==} + + '@turbo/darwin-64@2.11.7': + resolution: {integrity: sha512-Z2LFOxwbiJueD1miByXJS/BrW21vv6YaQXZustty5jEX4vQYw6zyh101Sz1QO7WG0mqBzKagZ/DoAeeujI0/Sw==} + cpu: [x64] + os: [darwin] + + '@turbo/darwin-arm64@2.11.7': + resolution: {integrity: sha512-Vhv8ybgIflosNDSSRD9fNXHlCFA60dsGyTqQmc7l28SEX5jOaweCCD4BBYNd8/p0WGkw3e7tZbfA9w6FsujGvw==} + cpu: [arm64] + os: [darwin] + + '@turbo/linux-64@2.11.7': + resolution: {integrity: sha512-rAqRp3blQKk1+ylMGlZHAW0eJjVNuuGUm4ZrC6RU1Im8tLryvaO4a2zLQ/FQi1TRlmKqKV9YXBki2YeytlLbXA==} + cpu: [x64] + os: [android, linux] + + '@turbo/linux-arm64@2.11.7': + resolution: {integrity: sha512-thVYGov7S+llXAxrl3kBb/efalav0xhrjl5NHCR6AfKx14JkbqaetvbVwyss4FvZ9rt+Pv3xsTb+8SIYix8DTg==} + cpu: [arm64] + os: [android, linux] + + '@turbo/windows-64@2.11.7': + resolution: {integrity: sha512-ZIoKT7J7KutgYl4bGxmmgeUQjG+7E0nY8BF9dxUOiMH2vdTsM4JQ2uSwTYFkTR2Llbg6ghGjSmuZ8LQtkLEYjg==} + cpu: [x64] + os: [win32] + + '@turbo/windows-arm64@2.11.7': + resolution: {integrity: sha512-88Xv2f7SLGVJ68lRRx8o375dKmnZYNdDtvlKcPA0kZpcF93eAQd8l96BKQ0/AMHG0bMJA0Z5QqoqtetxzNsC+g==} + cpu: [arm64] + os: [win32] + + '@types/babel__core@7.20.5': + resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==} + + '@types/babel__generator@7.27.0': + resolution: {integrity: sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==} + + '@types/babel__template@7.4.4': + resolution: {integrity: sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==} + + '@types/babel__traverse@7.28.0': + resolution: {integrity: sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==} + + '@types/body-parser@1.19.6': + resolution: {integrity: sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==} + + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/connect@3.4.38': + resolution: {integrity: sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==} + + '@types/cookiejar@2.1.5': + resolution: {integrity: sha512-he+DHOWReW0nghN24E1WUqM0efK4kI9oTqDm6XmK8ZPe2djZ90BSNdGnIyCLzCPw7/pogPlGbzI2wHGGmi4O/Q==} + + '@types/d3-array@3.0.3': + resolution: {integrity: sha512-Reoy+pKnvsksN0lQUlcH6dOGjRZ/3WRwXR//m+/8lt1BXeI4xyaUZoqULNjyXXRuh0Mj4LNpkCvhUpQlY3X5xQ==} + + '@types/d3-color@3.1.0': + resolution: {integrity: sha512-HKuicPHJuvPgCD+np6Se9MQvS6OCbJmOjGvylzMJRlDwUXjKTTXs6Pwgk79O09Vj/ho3u1ofXnhFOaEWWPrlwA==} + + '@types/d3-delaunay@6.0.1': + resolution: {integrity: sha512-tLxQ2sfT0p6sxdG75c6f/ekqxjyYR0+LwPrsO1mbC9YDBzPJhs2HbJJRrn8Ez1DBoHRo2yx7YEATI+8V1nGMnQ==} + + '@types/d3-format@3.0.1': + resolution: {integrity: sha512-5KY70ifCCzorkLuIkDe0Z9YTf9RR2CjBX1iaJG+rgM/cPP+sO+q9YdQ9WdhQcgPj1EQiJ2/0+yUkkziTG6Lubg==} + + '@types/d3-geo@3.1.0': + resolution: {integrity: sha512-856sckF0oP/diXtS4jNsiQw/UuK5fQG8l/a9VVLeSouf1/PPbBE1i1W852zVwKwYCBkFJJB7nCFTbk6UMEXBOQ==} + + '@types/d3-interpolate@3.0.1': + resolution: {integrity: sha512-jx5leotSeac3jr0RePOH1KdR9rISG91QIE4Q2PYTu4OymLTZfA3SrnURSLzKH48HmXVUru50b8nje4E79oQSQw==} + + '@types/d3-path@3.1.1': + resolution: {integrity: sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==} + + '@types/d3-scale@4.0.2': + resolution: {integrity: sha512-Yk4htunhPAwN0XGlIwArRomOjdoBFXC3+kCxK2Ubg7I9shQlVSJy/pG/Ht5ASN+gdMIalpk8TJ5xV74jFsetLA==} + + '@types/d3-shape@3.1.7': + resolution: {integrity: sha512-VLvUQ33C+3J+8p+Daf+nYSOsjB4GXp19/S/aGo60m9h1v6XaxjiT82lKVWJCfzhtuZ3yD7i/TPeC/fuKLLOSmg==} + + '@types/d3-time-format@2.1.0': + resolution: {integrity: sha512-/myT3I7EwlukNOX2xVdMzb8FRgNzRMpsZddwst9Ld/VFe6LyJyRp0s32l/V9XoUzk+Gqu56F/oGk6507+8BxrA==} + + '@types/d3-time@3.0.0': + resolution: {integrity: sha512-sZLCdHvBUcNby1cB6Fd3ZBrABbjz3v1Vm90nysCQ6Vt7vd6e/h9Lt7SiJUoEX0l4Dzc7P5llKyhqSi1ycSf1Hg==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + + '@types/express-serve-static-core@5.1.3': + resolution: {integrity: sha512-dPfW8NFiOF4wOHc7+N/QSxlY9cfSsenewGbAz8C8U/MULPd/YZ27LvJUIlzaXie7e6Ove9YunJGgC9tbHD2cKw==} + + '@types/express@5.0.6': + resolution: {integrity: sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==} + + '@types/geojson@7946.0.16': + resolution: {integrity: sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==} + + '@types/http-errors@2.0.5': + resolution: {integrity: sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==} + + '@types/lodash@4.17.25': + resolution: {integrity: sha512-+K1NIO8I+F9/wNulfVvu23QYd0Pe9/OCqRrim4NoYIf1VoEDL90Ve4ClzpyqBLc7NpGGWRvYNCKZ1BE/Jpf8dQ==} + + '@types/methods@1.1.4': + resolution: {integrity: sha512-ymXWVrDiCxTBE3+RIrrP533E70eA+9qu7zdWoHuOmGujkYtzf4HQF96b8nwHLqhuf4ykX61IGRIB38CC6/sImQ==} + + '@types/node@24.19.1': + resolution: {integrity: sha512-aS3/DG0oM05K0RIXXP+hKjinGG5IgSSVGzswZxW3O0sS3pH4/fycXundUC9XsszgKCk4gHXylTEK6hyFxVxnoQ==} + + '@types/node@26.6.4': + resolution: {integrity: sha512-ldVPDCzj7fsaGZrLB0NuHuTvJcsNasysBAqMolr/cgxrLd1xbqxIr3XJiPnHHJUCxj5sNF1vnRj9aWnrVh5Jcg==} + + '@types/pg@8.23.1': + resolution: {integrity: sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==} + + '@types/prop-types@15.7.15': + resolution: {integrity: sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==} + + '@types/qs@6.15.1': + resolution: {integrity: sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw==} + + '@types/range-parser@1.2.7': + resolution: {integrity: sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==} + + '@types/react-dom@18.3.7': + resolution: {integrity: sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==} + peerDependencies: + '@types/react': ^18.0.0 + + '@types/react@18.3.31': + resolution: {integrity: sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==} + + '@types/send@1.2.1': + resolution: {integrity: sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==} + + '@types/serve-static@2.2.0': + resolution: {integrity: sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ==} + + '@types/superagent@8.1.11': + resolution: {integrity: sha512-KA7srSW/HENDtOw9DOqaFLgWuMqN9WgjEw62lh9dpvRaZDkhdOkazASd7X7i2eMUYLHa1U37ZttnePsH5zTDHw==} + + '@types/supertest@7.2.1': + resolution: {integrity: sha512-4CbBvoYVLHL7+yhbYrZET0vsvuyXTC05aRe7dNQkwMzm56auceoy6Yu3K50uZmwfHna1os3CMSgM/3QVkUtPTw==} + + '@types/validator@13.15.10': + resolution: {integrity: sha512-T8L6i7wCuyoK8A/ZeLYt1+q0ty3Zb9+qbSSvrIVitzT3YjZqkTZ40IbRsPanlB4h1QB3JVL1SYCdR6ngtFYcuA==} + + '@typescript-eslint/eslint-plugin@7.18.0': + resolution: {integrity: sha512-94EQTWZ40mzBc42ATNIBimBEDltSJ9RQHCC8vc/PDbxi4k8dVwUAv4o98dk50M1zB+JGFxp43FP7f8+FP8R6Sw==} + engines: {node: ^18.18.0 || >=20.0.0} + peerDependencies: + '@typescript-eslint/parser': ^7.0.0 + eslint: ^8.56.0 + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + '@typescript-eslint/parser@7.18.0': + resolution: {integrity: sha512-4Z+L8I2OqhZV8qA132M4wNL30ypZGYOQVBfMgxDH/K5UX0PNqTu1c6za9ST5r9+tavvHiTWmBnKzpCJ/GlVFtg==} + engines: {node: ^18.18.0 || >=20.0.0} + peerDependencies: + eslint: ^8.56.0 + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + '@typescript-eslint/scope-manager@7.18.0': + resolution: {integrity: sha512-jjhdIE/FPF2B7Z1uzc6i3oWKbGcHb87Qw7AWj6jmEqNOfDFbJWtjt/XfwCpvNkpGWlcJaog5vTR+VV8+w9JflA==} + engines: {node: ^18.18.0 || >=20.0.0} + + '@typescript-eslint/type-utils@7.18.0': + resolution: {integrity: sha512-XL0FJXuCLaDuX2sYqZUUSOJ2sG5/i1AAze+axqmLnSkNEVMVYLF+cbwlB2w8D1tinFuSikHmFta+P+HOofrLeA==} + engines: {node: ^18.18.0 || >=20.0.0} + peerDependencies: + eslint: ^8.56.0 + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + '@typescript-eslint/types@7.18.0': + resolution: {integrity: sha512-iZqi+Ds1y4EDYUtlOOC+aUmxnE9xS/yCigkjA7XpTKV6nCBd3Hp/PRGGmdwnfkV2ThMyYldP1wRpm/id99spTQ==} + engines: {node: ^18.18.0 || >=20.0.0} + + '@typescript-eslint/typescript-estree@7.18.0': + resolution: {integrity: sha512-aP1v/BSPnnyhMHts8cf1qQ6Q1IFwwRvAQGRvBFkWlo3/lH29OXA3Pts+c10nxRxIBrDnoMqzhgdwVe5f2D6OzA==} + engines: {node: ^18.18.0 || >=20.0.0} + peerDependencies: + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + '@typescript-eslint/utils@7.18.0': + resolution: {integrity: sha512-kK0/rNa2j74XuHVcoCZxdFBMF+aq/vH83CXAOHieC+2Gis4mF8jJXT5eAfyD3K0sAxtPuwxaIOIOvhwzVDt/kw==} + engines: {node: ^18.18.0 || >=20.0.0} + peerDependencies: + eslint: ^8.56.0 + + '@typescript-eslint/visitor-keys@7.18.0': + resolution: {integrity: sha512-cDF0/Gf81QpY3xYyJKDV14Zwdmid5+uuENhjH2EqFaF0ni+yAyq/LzMaIJdhNJXZI7uLzwIlA+V7oWoyn6Curg==} + engines: {node: ^18.18.0 || >=20.0.0} + + '@ungap/structured-clone@1.4.0': + resolution: {integrity: sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ==} + + '@vercel/cli-config@0.3.1': + resolution: {integrity: sha512-sISbygqlFXYb8qfPu/+2Cf/A8IjrlAuZePdag3EDQr2PRA455s7UZtl9Ro674CWsB/saBRmz3jEkw0YsQs8OoQ==} + + '@vercel/cli-exec@1.0.1': + resolution: {integrity: sha512-g9XerViJ/paZujufXYcu5XYI2vU2rtB4sgdpjUHde5RnOkdmpu0ngH46LCFGHoPXO/C+qDPSczIHIRN+8Q2YKQ==} + engines: {node: '>= 18'} + + '@vercel/functions@3.9.11': + resolution: {integrity: sha512-DbqKqcbUHGBTYgHZieSNDuF1/L2iSPZV0OGm0Xkm/t+s61lFk4VX8yGQ22Og3WYGxypW1l4Elx1NP8BL928u8Q==} + engines: {node: '>= 20'} + peerDependencies: + '@aws-sdk/credential-provider-web-identity': '*' + ws: '>=8' + peerDependenciesMeta: + '@aws-sdk/credential-provider-web-identity': + optional: true + ws: + optional: true + + '@vercel/oidc@4.0.0': + resolution: {integrity: sha512-ko6ATeRUlHZMB5hLFdC7+/Q1dI2f3NX3gZHxtpALdkxurwjD5HFHGWYF+4o+4SF0E47jg6KzcHknmRpHcKgJ5A==} + engines: {node: '>= 20'} + + '@visx/curve@4.0.1-alpha.0': + resolution: {integrity: sha512-jRu61Uz274pV1zyioXmboyrLutYbnKsgjj4njSGCnhdXj5GkZvZbg+ThDb6oOzoAnJOBRLz4rzPlWvNJOzuVMg==} + + '@visx/event@4.0.1-alpha.0': + resolution: {integrity: sha512-EQqCMSv/s8NbFjo+hz3FKsvvYfP+2QslsFJ/24/O5l/W+7UC6J6aAvO0ujVwrTwdYbuQ+vhxKi1xdPdKR/qj1g==} + + '@visx/grid@4.0.1-alpha.0': + resolution: {integrity: sha512-rycutGmTHO+znNdPumheWMglm7YfpffvRwUkVy5zy4WoORIuKTMkDxwnOzHG2xMxU3EE/YCd37xFV5AxA30yeg==} + peerDependencies: + react: ^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0 + + '@visx/group@4.0.1-alpha.0': + resolution: {integrity: sha512-V19l7iQ7jccBv8kao/EByuI6o4xtxzzLV9nqVI1hRvmdzTVsuLpqlwzYCZUXJaTVvUWf8s4D2SQFjGkj/Nw+0w==} + peerDependencies: + react: ^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0 + + '@visx/point@4.0.1-alpha.0': + resolution: {integrity: sha512-ijTfr/Nx09f03vIj9nyTr3z4Xth4Y75427UaogJh6dnIRLMEFHQOwNu791sbfiNj0a+ZXuaE32h0vKrFe4/8Qg==} + + '@visx/responsive@4.0.1-alpha.0': + resolution: {integrity: sha512-o+1zGywQZY0+yOx3Iw87wc4bbPJRr/HnIukTwfOz4UVyj9pB1OQNVHB7OORO1+LBHJceWpB31co/ZV9KHncKrA==} + peerDependencies: + react: ^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0 + + '@visx/scale@4.0.1-alpha.0': + resolution: {integrity: sha512-nzjeE87vFSAXGWFiiNfBpNLAf0Q8Qmf6syvKLjqNi4kGZkdhbUll3E/59YsgWXmjM8+llPLWzGsP+JPvo5eq1A==} + + '@visx/shape@4.0.1-alpha.0': + resolution: {integrity: sha512-62QeiVNmPlterQGwhkEDcbq7M0MqY0lBsK5QKXtM9ZoPZWkuGV3aykA3+Xu20B2FAvyJq4LqJzBc7Sxr+EAdbA==} + peerDependencies: + react: ^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0 + + '@visx/vendor@4.0.0-alpha.0': + resolution: {integrity: sha512-6I+MuqXBcv9jnlcVowHoHKSdk9gXTWkHLKyqBwRWg7LY6A3Ei8SHfubpqGV5rBUSppxMq2RszPJUS6w+H0YgmQ==} + + '@vitejs/plugin-react@4.7.0': + resolution: {integrity: sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==} + engines: {node: ^14.18.0 || >=16.0.0} + peerDependencies: + vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 + + '@vitest/coverage-v8@4.1.11': + resolution: {integrity: sha512-8MVGEFnJIcdGjcbfKmeq8z0pZHH0JlVtoVZH9Q/qwUp6wyFnEJUBMrw9DCaj+ra3vShGmhavjalMIhPNxZAUcw==} + peerDependencies: + '@vitest/browser': 4.1.11 + vitest: 4.1.11 + peerDependenciesMeta: + '@vitest/browser': + optional: true + + '@vitest/expect@4.1.11': + resolution: {integrity: sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==} + + '@vitest/mocker@4.1.11': + resolution: {integrity: sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==} + peerDependencies: + msw: ^2.4.9 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@4.1.11': + resolution: {integrity: sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==} + + '@vitest/runner@4.1.11': + resolution: {integrity: sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==} + + '@vitest/snapshot@4.1.11': + resolution: {integrity: sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==} + + '@vitest/spy@4.1.11': + resolution: {integrity: sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==} + + '@vitest/utils@4.1.11': + resolution: {integrity: sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==} + + '@viz2d/core@0.1.0': + resolution: {integrity: sha512-BGscvuYJN6JMpDpN9pIJV7JyCFeokYZXBjXDXlUf4dbpBF6TcNwFIAiAKXTA42F2v8v3K39ruCTIfS7p7eMRcg==} + + '@viz2d/sdk@0.1.4': + resolution: {integrity: sha512-J/wS5rIkMVZapcuOImaIMdz1taW2S7GlCE7UH1HFPV/cb0Cj/tlrYI+b+p7na7f9VmNycJz3baQLc8XwwsxAng==} + + accepts@2.0.0: + resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==} + engines: {node: '>= 0.6'} + + acorn-jsx@5.3.2: + resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} + peerDependencies: + acorn: ^6.0.0 || ^7.0.0 || ^8.0.0 + + acorn@8.18.0: + resolution: {integrity: sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==} + engines: {node: '>=0.4.0'} + hasBin: true + + ajv-formats@3.0.1: + resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==} + peerDependencies: + ajv: ^8.0.0 + peerDependenciesMeta: + ajv: + optional: true + + ajv@6.15.0: + resolution: {integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==} + + ajv@8.20.0: + resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} + + ansi-regex@5.0.1: + resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} + engines: {node: '>=8'} + + ansi-regex@6.4.0: + resolution: {integrity: sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==} + engines: {node: '>=12'} + + ansi-styles@4.3.0: + resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} + engines: {node: '>=8'} + + ansis@4.4.0: + resolution: {integrity: sha512-9k3v7xcHwgdO/DruxGIg4HtjvlAZlcnsX/mzqUb1t3NkYnl9kK2UJ+Gq0io+vQf7iT//BD/HB/NBkUR1LWxoeA==} + engines: {node: '>=14'} + + any-promise@1.3.0: + resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==} + + anymatch@3.1.3: + resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==} + engines: {node: '>= 8'} + + append-field@1.0.0: + resolution: {integrity: sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==} + + arg@5.0.2: + resolution: {integrity: sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==} + + argparse@2.0.1: + resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} + + array-timsort@1.0.3: + resolution: {integrity: sha512-/+3GRL7dDAGEfM6TseQk/U+mi18TU2Ms9I3UlLdUMhz2hbvGNTKdj9xniwXfUqgYhHxRx0+8UnKkvlNwVU+cWQ==} + + array-union@2.1.0: + resolution: {integrity: sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==} + engines: {node: '>=8'} + + asap@2.0.6: + resolution: {integrity: sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + ast-v8-to-istanbul@1.0.7: + resolution: {integrity: sha512-kFL68AG6ajd8fg248zwM9GQrUWEp79gsmjum34OEXjs4yHuUMZfYKwOLW9GMmB4oNvVrj+EAGxsP7ye2UR9UlA==} + + asynckit@0.4.0: + resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==} + + autoprefixer@10.6.1: + resolution: {integrity: sha512-cL1Qz6ADZhcEbny/8HPfe99J6HhNoYtpX2LFLIbhgGE7Q1hlQVkYFdetDN7Id3KiQxhDrHwzlHr/YQCnZ8+xSA==} + engines: {node: ^10 || ^12 || >=14} + hasBin: true + peerDependencies: + postcss: ^8.1.0 + + aws-ssl-profiles@1.1.2: + resolution: {integrity: sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==} + engines: {node: '>= 6.0.0'} + + balanced-match@1.0.2: + resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + + balanced-match@4.0.4: + resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} + engines: {node: 18 || 20 || >=22} + + baseline-browser-mapping@2.11.27: + resolution: {integrity: sha512-ElY12DaROGuan+lMmZ8Cvo/ZUbXPe7Enc/9VU/b1T3Kp4dwytRcNdR8DoSJN5SNJT/CuvcCA0DHDVmMOCePdRQ==} + engines: {node: '>=6.0.0'} + hasBin: true + + better-result@2.10.0: + resolution: {integrity: sha512-oQhh0y1qo2/ZKdAAEvHZAqKKiHOFU5k/bW96fE2ScgQOVkJRiHwB+nOS1SgFsYqRlxMDWvefXi9Q3px7QvgNDw==} + + binary-extensions@2.3.0: + resolution: {integrity: sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==} + engines: {node: '>=8'} + + body-parser@2.3.0: + resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==} + engines: {node: '>=18'} + + brace-expansion@1.1.21: + resolution: {integrity: sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==} + + brace-expansion@2.1.7: + resolution: {integrity: sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==} + + brace-expansion@5.0.12: + resolution: {integrity: sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==} + engines: {node: 20 || >=22} + + braces@3.0.3: + resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} + engines: {node: '>=8'} + + browserslist@4.29.3: + resolution: {integrity: sha512-1R4kiYKXGViqEN0CnoDrXc1StD9niAwu+j2dukWzrD4bJgsD4lDmEp0CRbc6E/vYJIfTHwPmwyaKtVSudICdPA==} + engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} + hasBin: true + + busboy@1.6.0: + resolution: {integrity: sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==} + engines: {node: '>=10.16.0'} + + bytes@3.1.2: + resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==} + engines: {node: '>= 0.8'} + + c12@3.3.4: + resolution: {integrity: sha512-cM0ApFQSBXuourJejzwv/AuPRvAxordTyParRVcHjjtXirtkzM0uK2L9TTn9s0cXZbG7E55jCivRQzoxYmRAlA==} + peerDependencies: + magicast: '*' + peerDependenciesMeta: + magicast: + optional: true + + call-bind-apply-helpers@1.0.2: + resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==} + engines: {node: '>= 0.4'} + + call-bound@1.0.4: + resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==} + engines: {node: '>= 0.4'} + + callsites@3.1.0: + resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} + engines: {node: '>=6'} + + camelcase-css@2.0.1: + resolution: {integrity: sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==} + engines: {node: '>= 6'} + + caniuse-lite@1.0.30001814: + resolution: {integrity: sha512-/Uaf1lAzr59XcMpW0o96WoEfr+VXK2OX4U9AgFoiSHsVJ4HppnIFUjtYzsyDH2+tgANaQb2/oxYGwCPapN1FpA==} + + chai@6.3.0: + resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} + engines: {node: '>=18'} + + chalk@4.1.2: + resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} + engines: {node: '>=10'} + + chalk@5.6.2: + resolution: {integrity: sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==} + engines: {node: ^12.17.0 || ^14.13 || >=16.0.0} + + char-regex@1.0.2: + resolution: {integrity: sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==} + engines: {node: '>=10'} + + chardet@2.2.0: + resolution: {integrity: sha512-rddelWYNPRrXq6PtNEN2S3f6t9ILzvqaN5pVgi4kqt9jHQaXIial9PznB5iSPVlQSLNaaH22ItWz3EJtQ10+OA==} + + chokidar@3.6.0: + resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==} + engines: {node: '>= 8.10.0'} + + chokidar@5.0.0: + resolution: {integrity: sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==} + engines: {node: '>= 20.19.0'} + + class-transformer@0.5.1: + resolution: {integrity: sha512-SQa1Ws6hUbfC98vKGxZH3KFY0Y1lm5Zm0SY8XX9zbK7FJCyVEac3ATW0RIpwzW+oOfmHE5PMPufDG9hCfoEOMw==} + + class-validator@0.15.1: + resolution: {integrity: sha512-LqoS80HBBSCVhz/3KloUly0ovokxpdOLR++Al3J3+dHXWt9sTKlKd4eYtoxhxyUjoe5+UcIM+5k9MIxyBWnRTw==} + + classnames@2.5.1: + resolution: {integrity: sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==} + + cli-cursor@5.0.0: + resolution: {integrity: sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==} + engines: {node: '>=18'} + + cli-spinners@3.4.0: + resolution: {integrity: sha512-bXfOC4QcT1tKXGorxL3wbJm6XJPDqEnij2gQ2m7ESQuE+/z9YFIWnl/5RpTiKWbMq3EVKR4fRLJGn6DVfu0mpw==} + engines: {node: '>=18.20'} + + cli-table3@0.6.5: + resolution: {integrity: sha512-+W/5efTR7y5HRD7gACw9yQjqMVvEMLBHmboM/kPWam+H+Hmyrgjh6YncVKK122YZkXrLudzTuAukUw9FnMf7IQ==} + engines: {node: 10.* || >= 12.*} + + cli-width@4.1.0: + resolution: {integrity: sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==} + engines: {node: '>= 12'} + + clsx@2.1.1: + resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} + engines: {node: '>=6'} + + color-convert@2.0.1: + resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} + engines: {node: '>=7.0.0'} + + color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + + combined-stream@1.0.8: + resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==} + engines: {node: '>= 0.8'} + + commander@15.0.0: + resolution: {integrity: sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg==} + engines: {node: '>=22.12.0'} + + commander@4.1.1: + resolution: {integrity: sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==} + engines: {node: '>= 6'} + + comment-json@5.0.0: + resolution: {integrity: sha512-uiqLcOiVDJtBP8WGkZHEP+FZIhTzP1dxvn59EfoYUi9gqupjrBWVQkO2atDrbnKPwLeotFYDsuNb26uBMqB+hw==} + engines: {node: '>= 6'} + + component-emitter@1.3.1: + resolution: {integrity: sha512-T0+barUSQRTUQASh8bx02dl+DhF54GtIDY13Y3m9oWTklKbb3Wv974meRpeZ3lp1JpLVECWWNHC4vaG2XHXouQ==} + + concat-map@0.0.1: + resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} + + confbox@0.2.4: + resolution: {integrity: sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==} + + confbox@0.3.1: + resolution: {integrity: sha512-cKUSoKa8YxFZZSmraVi7onONx3amu77ngK3kGpsYHDH7drPwCRkQE1RYMPlLRrMtnciRj274XNRxcHxnKmDSnA==} + + content-disposition@1.1.0: + resolution: {integrity: sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==} + engines: {node: '>=18'} + + content-type@1.0.5: + resolution: {integrity: sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==} + engines: {node: '>= 0.6'} + + content-type@2.1.0: + resolution: {integrity: sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==} + engines: {node: '>=18'} + + convert-source-map@2.0.0: + resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} + + cookie-signature@1.2.2: + resolution: {integrity: sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==} + engines: {node: '>=6.6.0'} + + cookie@0.7.2: + resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==} + engines: {node: '>= 0.6'} + + cookiejar@2.1.4: + resolution: {integrity: sha512-LDx6oHrK+PhzLKJU9j5S7/Y3jM/mUHvD/DeI1WQmJn652iPC5Y4TBzC9l+5OMOXlyTTA+SmVUPm0HQUwpD5Jqw==} + + cors@2.8.6: + resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==} + engines: {node: '>= 0.10'} + + cross-spawn@7.0.6: + resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + engines: {node: '>= 8'} + + cssesc@3.0.0: + resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==} + engines: {node: '>=4'} + hasBin: true + + csstype@3.2.3: + resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + + d3-array@3.2.1: + resolution: {integrity: sha512-gUY/qeHq/yNqqoCKNq4vtpFLdoCdvyNpWoC/KNjhGbhDuQpAM9sIQQKkXSNpXa9h5KySs/gzm7R88WkUutgwWQ==} + engines: {node: '>=12'} + + d3-array@3.2.4: + resolution: {integrity: sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==} + engines: {node: '>=12'} + + d3-color@3.1.0: + resolution: {integrity: sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==} + engines: {node: '>=12'} + + d3-delaunay@6.0.2: + resolution: {integrity: sha512-IMLNldruDQScrcfT+MWnazhHbDJhcRJyOEBAJfwQnHle1RPh6WDuLvxNArUju2VSMSUuKlY5BGHRJ2cYyoFLQQ==} + engines: {node: '>=12'} + + d3-format@3.1.0: + resolution: {integrity: sha512-YyUI6AEuY/Wpt8KWLgZHsIU86atmikuoOmCfommt0LYHiQSPjvX2AcFc38PX0CBpr2RCyZhjex+NS/LPOv6YqA==} + engines: {node: '>=12'} + + d3-geo@3.1.0: + resolution: {integrity: sha512-JEo5HxXDdDYXCaWdwLRt79y7giK8SbhZJbFWXqbRTolCHFI5jRqteLzCsq51NKbUoX0PjBVSohxrx+NoOUujYA==} + engines: {node: '>=12'} + + d3-interpolate@3.0.1: + resolution: {integrity: sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==} + engines: {node: '>=12'} + + d3-path@3.1.0: + resolution: {integrity: sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==} + engines: {node: '>=12'} + + d3-scale@4.0.2: + resolution: {integrity: sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==} + engines: {node: '>=12'} + + d3-shape@3.2.0: + resolution: {integrity: sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==} + engines: {node: '>=12'} + + d3-time-format@4.1.0: + resolution: {integrity: sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==} + engines: {node: '>=12'} + + d3-time@3.1.0: + resolution: {integrity: sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==} + engines: {node: '>=12'} + + debug@4.4.3: + resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + deep-is@0.1.4: + resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} + + deepmerge-ts@7.1.5: + resolution: {integrity: sha512-HOJkrhaYsweh+W+e74Yn7YStZOilkoPb6fycpwNLKzSPtruFs48nYis0zy5yJz1+ktUhHxoRDJ27RQAWLIJVJw==} + engines: {node: '>=16.0.0'} + + defu@6.1.7: + resolution: {integrity: sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==} + + delaunator@5.1.0: + resolution: {integrity: sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==} + + delayed-stream@1.0.0: + resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} + engines: {node: '>=0.4.0'} + + denque@2.1.0: + resolution: {integrity: sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==} + engines: {node: '>=0.10'} + + depd@2.0.0: + resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==} + engines: {node: '>= 0.8'} + + dequal@2.0.3: + resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} + engines: {node: '>=6'} + + destr@2.0.5: + resolution: {integrity: sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + dezalgo@1.0.4: + resolution: {integrity: sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig==} + + didyoumean@1.2.2: + resolution: {integrity: sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==} + + dir-glob@3.0.1: + resolution: {integrity: sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==} + engines: {node: '>=8'} + + dlv@1.1.3: + resolution: {integrity: sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==} + + doctrine@3.0.0: + resolution: {integrity: sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==} + engines: {node: '>=6.0.0'} + + dotenv@17.4.2: + resolution: {integrity: sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==} + engines: {node: '>=12'} + + dotenv@18.0.5: + resolution: {integrity: sha512-aBrGvt6KhjxbEnatqMWOMidftwsrCiCvqh1yNIGB9QyF0J+VcWkKDMsvYOEm7ZS82oiV+BT1sTOtIlAmUlTpwQ==} + engines: {node: '>=12'} + hasBin: true + + dunder-proto@1.0.1: + resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} + engines: {node: '>= 0.4'} + + ee-first@1.1.1: + resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==} + + effect@3.20.0: + resolution: {integrity: sha512-qMLfDJscrNG8p/aw+IkT9W7fgj50Z4wG5bLBy0Txsxz8iUHjDIkOgO3SV0WZfnQbNG2VJYb0b+rDLMrhM4+Krw==} + + electron-to-chromium@1.5.444: + resolution: {integrity: sha512-5ss/uJfoDYDHT0lfJzT6FbcskIzROIOPf0BbbFkGcvDzoJU7i//9GDrwwIHQVmIsrAGiF3ihpADBRIsrEFt1rQ==} + + elkjs@0.11.1: + resolution: {integrity: sha512-zxxR9k+rx5ktMwT/FwyLdPCrq7xN6e4VGGHH8hA01vVYKjTFik7nHOxBnAYtrgYUB1RpAiLvA1/U2YraWxyKKg==} + + emoji-regex@8.0.0: + resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} + + emojilib@2.4.0: + resolution: {integrity: sha512-5U0rVMU5Y2n2+ykNLQqMoqklN9ICBT/KsvC1Gz6vqHbz2AXXGkG+Pm5rMWk/8Vjrr/mY9985Hi8DYzn1F09Nyw==} + + empathic@2.0.0: + resolution: {integrity: sha512-i6UzDscO/XfAcNYD75CfICkmfLedpyPDdozrLMmQc5ORaQcdMoc21OnlEylMIqI7U8eniKrPMxxtj8k0vhmJhA==} + engines: {node: '>=14'} + + encodeurl@2.0.0: + resolution: {integrity: sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==} + engines: {node: '>= 0.8'} + + env-paths@3.0.0: + resolution: {integrity: sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + + es-define-property@1.0.1: + resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} + engines: {node: '>= 0.4'} + + es-errors@1.3.0: + resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} + engines: {node: '>= 0.4'} + + es-module-lexer@2.3.2: + resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} + + es-object-atoms@1.1.2: + resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==} + engines: {node: '>= 0.4'} + + es-set-tostringtag@2.1.0: + resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==} + engines: {node: '>= 0.4'} + + esbuild@0.21.5: + resolution: {integrity: sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==} + engines: {node: '>=12'} + hasBin: true + + esbuild@0.28.2: + resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==} + engines: {node: '>=18'} + hasBin: true + + escalade@3.2.0: + resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} + engines: {node: '>=6'} + + escape-html@1.0.3: + resolution: {integrity: sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==} + + escape-string-regexp@4.0.0: + resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} + engines: {node: '>=10'} + + eslint-plugin-react-hooks@4.6.2: + resolution: {integrity: sha512-QzliNJq4GinDBcD8gPB5v0wh6g8q3SUi6EFF0x8N/BL9PoVs0atuGc47ozMRyOWAKdwaZ5OnbOEa3WR+dSGKuQ==} + engines: {node: '>=10'} + peerDependencies: + eslint: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 + + eslint-plugin-react-refresh@0.4.26: + resolution: {integrity: sha512-1RETEylht2O6FM/MvgnyvT+8K21wLqDNg4qD51Zj3guhjt433XbnnkVttHMyaVyAFD03QSV4LPS5iE3VQmO7XQ==} + peerDependencies: + eslint: '>=8.40' + + eslint-scope@7.2.2: + resolution: {integrity: sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + eslint-visitor-keys@3.4.3: + resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + eslint@8.57.1: + resolution: {integrity: sha512-ypowyDxpVSYpkXr9WPv2PAZCtNip1Mv5KTW0SCurXv/9iOpcrH9PaqUElksqEB6pChqHGDRCFTyrZlGhnLNGiA==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + deprecated: This version is no longer supported. Please see https://eslint.org/version-support for other options. + hasBin: true + + espree@9.6.1: + resolution: {integrity: sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + esprima@4.0.1: + resolution: {integrity: sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==} + engines: {node: '>=4'} + hasBin: true + + esquery@1.7.0: + resolution: {integrity: sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==} + engines: {node: '>=0.10'} + + esrecurse@4.3.0: + resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==} + engines: {node: '>=4.0'} + + estraverse@5.3.0: + resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==} + engines: {node: '>=4.0'} + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + esutils@2.0.3: + resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} + engines: {node: '>=0.10.0'} + + etag@1.8.1: + resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} + engines: {node: '>= 0.6'} + + execa@5.1.1: + resolution: {integrity: sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==} + engines: {node: '>=10'} + + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + + express@5.2.1: + resolution: {integrity: sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==} + engines: {node: '>= 18'} + + exsolve@1.1.3: + resolution: {integrity: sha512-kuzL9zherLQoqDeQaS55AiiIg1kb4KYXaSusTtgZTPlvKP2gGCI82LNmBNh5RjDVUXIcmgx+/Mx7vPwRzBbhJA==} + + fast-check@3.23.2: + resolution: {integrity: sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A==} + engines: {node: '>=8.0.0'} + + fast-decode-uri-component@1.0.1: + resolution: {integrity: sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg==} + + fast-deep-equal@3.1.3: + resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + + fast-glob@3.3.3: + resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==} + engines: {node: '>=8.6.0'} + + fast-json-stable-stringify@2.1.0: + resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} + + fast-levenshtein@2.0.6: + resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + + fast-querystring@1.1.2: + resolution: {integrity: sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==} + + fast-safe-stringify@2.1.1: + resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==} + + fast-sha256@1.3.0: + resolution: {integrity: sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==} + + fast-string-truncated-width@3.0.3: + resolution: {integrity: sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==} + + fast-string-width@3.0.2: + resolution: {integrity: sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==} + + fast-uri@3.1.8: + resolution: {integrity: sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==} + + fast-wrap-ansi@0.2.2: + resolution: {integrity: sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==} + + fastq@1.20.3: + resolution: {integrity: sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + file-entry-cache@6.0.1: + resolution: {integrity: sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==} + engines: {node: ^10.12.0 || >=12.0.0} + + file-type@22.1.1: + resolution: {integrity: sha512-sEB0oStmeLGtpmSAD88RDNuLsvhv4iC3u0lE25CUvfCULvj49xoQ3l3K525Vn+ZzsZ6DOLajQCV6RmhwwhqiJg==} + engines: {node: '>=22'} + + fill-range@7.1.1: + resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} + engines: {node: '>=8'} + + finalhandler@2.1.1: + resolution: {integrity: sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==} + engines: {node: '>= 18.0.0'} + + find-my-way@9.7.0: + resolution: {integrity: sha512-f2JHn75x2JlwUwLenZypgczR7YWMb/uO9BvUXtus+JMgkbIkLADd38cI4EiV+OQqrGo1Zlq6V8wnqMJ8e62wUQ==} + engines: {node: '>=20'} + + find-up@5.0.0: + resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} + engines: {node: '>=10'} + + flat-cache@3.2.0: + resolution: {integrity: sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==} + engines: {node: ^10.12.0 || >=12.0.0} + + flatted@3.4.4: + resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} + + foreground-child@3.3.1: + resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==} + engines: {node: '>=14'} + + form-data@4.0.6: + resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==} + engines: {node: '>= 6'} + + formidable@3.5.4: + resolution: {integrity: sha512-YikH+7CUTOtP44ZTnUhR7Ic2UASBPOqmaRkRKxRbywPTe5VxF7RRCck4af9wutiZ/QKM5nME9Bie2fFaPz5Gug==} + engines: {node: '>=14.0.0'} + + forwarded@0.2.0: + resolution: {integrity: sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==} + engines: {node: '>= 0.6'} + + fraction.js@5.3.4: + resolution: {integrity: sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==} + + fresh@2.0.0: + resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==} + engines: {node: '>= 0.8'} + + fs.realpath@1.0.0: + resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==} + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + function-bind@1.1.2: + resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} + + generate-function@2.3.1: + resolution: {integrity: sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==} + + gensync@1.0.0-beta.2: + resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==} + engines: {node: '>=6.9.0'} + + get-east-asian-width@1.7.0: + resolution: {integrity: sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==} + engines: {node: '>=18'} + + get-intrinsic@1.3.0: + resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==} + engines: {node: '>= 0.4'} + + get-port-please@3.2.0: + resolution: {integrity: sha512-I9QVvBw5U/hw3RmWpYKRumUeaDgxTPd401x364rLmWBJcOQ753eov1eTgzDqRG9bqFIfDc7gfzcQEWrUri3o1A==} + + get-proto@1.0.1: + resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==} + engines: {node: '>= 0.4'} + + get-stream@6.0.1: + resolution: {integrity: sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==} + engines: {node: '>=10'} + + giget@3.3.1: + resolution: {integrity: sha512-r+mvuDjrjMpsdw46Kmeydb8bdHm7wOKw8wNBtTndkjbPjgAp5oUJUxRE76wZFknxIPokfWvep2qSXK37aXE6zg==} + hasBin: true + + glob-parent@5.1.2: + resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} + engines: {node: '>= 6'} + + glob-parent@6.0.2: + resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} + engines: {node: '>=10.13.0'} + + glob-to-regexp@0.4.1: + resolution: {integrity: sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==} + + glob@7.2.3: + resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} + deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me + + globals@13.24.0: + resolution: {integrity: sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==} + engines: {node: '>=8'} + + globby@11.1.0: + resolution: {integrity: sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==} + engines: {node: '>=10'} + + gopd@1.2.0: + resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} + engines: {node: '>= 0.4'} + + graceful-fs@4.2.11: + resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} + + grammex@3.1.13: + resolution: {integrity: sha512-LnPnhOBLEJEVKS8WFDVaA397L9Kq55Q9oSITJiVLHVdhAclfUkWzQv74KhvZHKL2Q09Pb1XdsrOsZ4LfTFFTEg==} + + graphemer@1.4.0: + resolution: {integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==} + + graphmatch@1.1.1: + resolution: {integrity: sha512-5ykVn/EXM1hF0XCaWh05VbYvEiOL2lY1kBxZtaYsyvjp7cmWOU1XsAdfQBwClraEofXDT197lFbXOEVMHpvQOg==} + + has-flag@4.0.0: + resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} + engines: {node: '>=8'} + + has-symbols@1.1.0: + resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} + engines: {node: '>= 0.4'} + + has-tostringtag@1.0.2: + resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==} + engines: {node: '>= 0.4'} + + hasown@2.0.4: + resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==} + engines: {node: '>= 0.4'} + + html-escaper@2.0.2: + resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==} + + http-errors@2.0.1: + resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==} + engines: {node: '>= 0.8'} + + human-signals@2.1.0: + resolution: {integrity: sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==} + engines: {node: '>=10.17.0'} + + iconv-lite@0.7.3: + resolution: {integrity: sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==} + engines: {node: '>=0.10.0'} + + ieee754@1.2.1: + resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==} + + ignore@5.3.2: + resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} + engines: {node: '>= 4'} + + import-fresh@3.3.1: + resolution: {integrity: sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==} + engines: {node: '>=6'} + + imurmurhash@0.1.4: + resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} + engines: {node: '>=0.8.19'} + + inflight@1.0.6: + resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==} + deprecated: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful. + + inherits@2.0.4: + resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} + + internmap@2.0.3: + resolution: {integrity: sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==} + engines: {node: '>=12'} + + ipaddr.js@1.9.1: + resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==} + engines: {node: '>= 0.10'} + + is-binary-path@2.1.0: + resolution: {integrity: sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==} + engines: {node: '>=8'} + + is-core-module@2.17.0: + resolution: {integrity: sha512-J/vG0zBCbIKOQFfufSwyXdMrsohyJIUNkrnmo6WZGzoM7tr/lsbfW5b2BvisL6zsyMzK9UxV9L6c7AoFbyXHOA==} + engines: {node: '>= 0.4'} + + is-extglob@2.1.1: + resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} + engines: {node: '>=0.10.0'} + + is-fullwidth-code-point@3.0.0: + resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} + engines: {node: '>=8'} + + is-glob@4.0.3: + resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} + engines: {node: '>=0.10.0'} + + is-interactive@2.0.0: + resolution: {integrity: sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ==} + engines: {node: '>=12'} + + is-number@7.0.0: + resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} + engines: {node: '>=0.12.0'} + + is-path-inside@3.0.3: + resolution: {integrity: sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==} + engines: {node: '>=8'} + + is-promise@4.0.0: + resolution: {integrity: sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==} + + is-property@1.0.2: + resolution: {integrity: sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==} + + is-stream@2.0.1: + resolution: {integrity: sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==} + engines: {node: '>=8'} + + is-unicode-supported@2.1.0: + resolution: {integrity: sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==} + engines: {node: '>=18'} + + isexe@2.0.0: + resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + + istanbul-lib-coverage@3.2.2: + resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==} + engines: {node: '>=8'} + + istanbul-lib-report@3.0.1: + resolution: {integrity: sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==} + engines: {node: '>=10'} + + istanbul-reports@3.2.0: + resolution: {integrity: sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==} + engines: {node: '>=8'} + + iterare@1.2.1: + resolution: {integrity: sha512-RKYVTCjAnRthyJes037NX/IiqeidgN1xc3j1RjFfECFp28A1GVwK9nA+i0rJPaHqSZwygLzRnFlzUuHFoWWy+Q==} + engines: {node: '>=6'} + + jiti@1.21.7: + resolution: {integrity: sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==} + hasBin: true + + jiti@2.7.0: + resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} + hasBin: true + + jose@5.10.0: + resolution: {integrity: sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg==} + + jose@6.2.12: + resolution: {integrity: sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==} + + js-cookie@3.0.8: + resolution: {integrity: sha512-yeJd4aNAdYZQjaon2bpD/Gb0B/omw7HQOsynXXcOiWVCacbBcPlgn8S/d1X6blFSaHao7ozqtW7NZW19xpCtIw==} + + js-tokens@10.0.0: + resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==} + + js-tokens@4.0.0: + resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + + js-yaml@4.3.2: + resolution: {integrity: sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==} + hasBin: true + + jsesc@3.1.0: + resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==} + engines: {node: '>=6'} + hasBin: true + + json-buffer@3.0.1: + resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==} + + json-schema-traverse@0.4.1: + resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} + + json-schema-traverse@1.0.0: + resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==} + + json-stable-stringify-without-jsonify@1.0.1: + resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} + + json5@2.2.3: + resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==} + engines: {node: '>=6'} + hasBin: true + + jsonc-parser@3.3.1: + resolution: {integrity: sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==} + + keyv@4.5.4: + resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} + + levn@0.4.1: + resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} + engines: {node: '>= 0.8.0'} + + libphonenumber-js@1.13.14: + resolution: {integrity: sha512-llihgCcx0BFLksecLP+x1J+6JDE1GsXS1RN/LoPF6qcwpeQcnjj0lcvZxY8AzbEpYwyZWPZW/nDuqkqzm3amiw==} + + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + + lilconfig@3.1.3: + resolution: {integrity: sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==} + engines: {node: '>=14'} + + lines-and-columns@1.2.4: + resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==} + + load-esm@1.0.3: + resolution: {integrity: sha512-v5xlu8eHD1+6r8EHTg6hfmO97LN8ugKtiXcy5e6oN72iD2r6u0RPfLl6fxM+7Wnh2ZRq15o0russMst44WauPA==} + engines: {node: '>=13.2.0'} + + locate-path@6.0.0: + resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} + engines: {node: '>=10'} + + lodash.merge@4.6.2: + resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==} + + lodash@4.18.1: + resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==} + + log-symbols@7.0.1: + resolution: {integrity: sha512-ja1E3yCr9i/0hmBVaM0bfwDjnGy8I/s6PP4DFp+yP+a+mrHO4Rm7DtmnqROTUkHIkqffC84YY7AeqX6oFk0WFg==} + engines: {node: '>=18'} + + long@5.3.2: + resolution: {integrity: sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==} + + loose-envify@1.4.0: + resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==} + hasBin: true + + lru-cache@5.1.1: + resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==} + + lru.min@1.1.5: + resolution: {integrity: sha512-5J9ysMYUpYIg9RF2vJpy9SinEmSviFSe0GyPpCQ4L5QSkLAgeLXlTAOu2ZwWUU5m+0SBl6gUU1R1ZQB3aKypfA==} + engines: {bun: '>=1.0.0', deno: '>=1.30.0', node: '>=8.0.0'} + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + magic-string@1.4.1: + resolution: {integrity: sha512-8lyCu36ErXR0J9uaGKlKQoiLZKmtI63YGLE8G2o9jyRPdr4X47LusSOwgOJOzcVtp81fTAAjxR7BwKz682Jhow==} + + magicast@0.5.5: + resolution: {integrity: sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==} + + make-dir@4.0.0: + resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==} + engines: {node: '>=10'} + + math-intrinsics@1.1.0: + resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} + engines: {node: '>= 0.4'} + + media-typer@0.3.0: + resolution: {integrity: sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==} + engines: {node: '>= 0.6'} + + media-typer@1.1.1: + resolution: {integrity: sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==} + engines: {node: '>= 0.8'} + + merge-descriptors@2.0.0: + resolution: {integrity: sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==} + engines: {node: '>=18'} + + merge-stream@2.0.0: + resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==} + + merge2@1.4.1: + resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==} + engines: {node: '>= 8'} + + methods@1.1.2: + resolution: {integrity: sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==} + engines: {node: '>= 0.6'} + + micromatch@4.0.8: + resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==} + engines: {node: '>=8.6'} + + mime-db@1.52.0: + resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==} + engines: {node: '>= 0.6'} + + mime-db@1.54.0: + resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==} + engines: {node: '>= 0.6'} + + mime-types@2.1.35: + resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==} + engines: {node: '>= 0.6'} + + mime-types@3.0.2: + resolution: {integrity: sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==} + engines: {node: '>=18'} + + mime@2.6.0: + resolution: {integrity: sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==} + engines: {node: '>=4.0.0'} + hasBin: true + + mimic-fn@2.1.0: + resolution: {integrity: sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==} + engines: {node: '>=6'} + + mimic-function@5.0.1: + resolution: {integrity: sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==} + engines: {node: '>=18'} + + minimatch@10.2.6: + resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==} + engines: {node: 18 || 20 || >=22} + + minimatch@3.1.5: + resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==} + + minimatch@9.0.9: + resolution: {integrity: sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==} + engines: {node: '>=16 || 14 >=14.17'} + + minimist@1.2.8: + resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} + + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + + multer@2.4.0: + resolution: {integrity: sha512-7dqa0ZcFfzbefdTuIkzOSMvZWC0J7FLqBOjJUZvDCXShIURWKxAyTT1wHhnE5q19c7jOJf43IYYKjBmZVZmvhg==} + engines: {node: '>= 10.16.0'} + + mute-stream@3.0.0: + resolution: {integrity: sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==} + engines: {node: ^20.17.0 || >=22.9.0} + + mysql2@3.15.3: + resolution: {integrity: sha512-FBrGau0IXmuqg4haEZRBfHNWB5mUARw6hNwPDXXGg0XzVJ50mr/9hb267lvpVMnhZ1FON3qNd4Xfcez1rbFwSg==} + engines: {node: '>= 8.0'} + + mz@2.7.0: + resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==} + + named-placeholders@1.1.6: + resolution: {integrity: sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==} + engines: {node: '>=8.0.0'} + + nanoid@3.3.19: + resolution: {integrity: sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + natural-compare@1.4.0: + resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} + + negotiator@1.1.0: + resolution: {integrity: sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==} + engines: {node: '>=18'} + + node-emoji@2.2.0: + resolution: {integrity: sha512-Z3lTE9pLaJF47NyMhd4ww1yFTAP8YhYI8SleJiHzM46Fgpm5cnNzSl9XfzFNqbaz+VlJrIj3fXQ4DeN1Rjm6cw==} + engines: {node: '>=18'} + + node-releases@2.0.57: + resolution: {integrity: sha512-kQK9LGGFiHtrWiNhZtA7Qbw17AQz+dmsEKODRIVTXA9+e5MS/2gZEBhYJt13GrAz5/IOZKddH/0Z3TP/Zgo+yw==} + engines: {node: '>=18'} + + normalize-path@3.0.0: + resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==} + engines: {node: '>=0.10.0'} + + npm-run-path@4.0.1: + resolution: {integrity: sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==} + engines: {node: '>=8'} + + object-assign@4.1.1: + resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} + engines: {node: '>=0.10.0'} + + object-hash@3.0.0: + resolution: {integrity: sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==} + engines: {node: '>= 6'} + + object-inspect@1.13.4: + resolution: {integrity: sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==} + engines: {node: '>= 0.4'} + + obug@2.2.1: + resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==} + engines: {node: '>=12.20.0'} + + ohash@2.0.12: + resolution: {integrity: sha512-65S/5gk9YSsaRjcyf7Nfa6h/d3E8/1gslpXfI4W7Dxn/oap8IKRuNT5VXkLQ1YFKIEg4apRY4Pj6aiwFzrDdmw==} + + on-finished@2.4.1: + resolution: {integrity: sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==} + engines: {node: '>= 0.8'} + + once@1.4.0: + resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} + + onetime@5.1.2: + resolution: {integrity: sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==} + engines: {node: '>=6'} + + onetime@7.0.0: + resolution: {integrity: sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==} + engines: {node: '>=18'} + + optionator@0.9.4: + resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} + engines: {node: '>= 0.8.0'} + + ora@9.4.1: + resolution: {integrity: sha512-6VlU9MLXbjVQD04AZCMX28hVtA5bUoadvUqO76MUCVA0ilwJbMiHsITRPfyVm6p/BC0Av/BXMujx39WCe1LEqw==} + engines: {node: '>=20'} + + os-paths@4.4.0: + resolution: {integrity: sha512-wrAwOeXp1RRMFfQY8Sy7VaGVmPocaLwSFOYCGKSyo8qmJ+/yaafCl5BCA1IQZWqFSRBrKDYFeR9d/VyQzfH/jg==} + engines: {node: '>= 6.0'} + + oxlint-tsgolint@7.0.2003: + resolution: {integrity: sha512-VnK4zlqgmgq/7ZcjzCk/WpN8kKFsYGcB85Io9qT3wL4K8Un3RKmJkp793crNETieMusPMKOA4a+Mw2wbteI6TQ==} + hasBin: true + + oxlint@1.86.0: + resolution: {integrity: sha512-og0lhgvZfgGF//gOOmZXvtr+GmBbAGEnbEhv/QUg7UW2Wi4wHMnJbnMD+zuHgPdJxdklfgpPupdlAaAySyxrZg==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + oxlint-tsgolint: '>=7.0.2003' + vite-plus: '*' + peerDependenciesMeta: + oxlint-tsgolint: + optional: true + vite-plus: + optional: true + + p-limit@3.1.0: + resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==} + engines: {node: '>=10'} + + p-locate@5.0.0: + resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} + engines: {node: '>=10'} + + parent-module@1.0.1: + resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} + engines: {node: '>=6'} + + parseurl@1.3.3: + resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==} + engines: {node: '>= 0.8'} + + path-exists@4.0.0: + resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} + engines: {node: '>=8'} + + path-is-absolute@1.0.1: + resolution: {integrity: sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==} + engines: {node: '>=0.10.0'} + + path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + + path-parse@1.0.7: + resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} + + path-to-regexp@8.4.2: + resolution: {integrity: sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==} + + path-type@4.0.0: + resolution: {integrity: sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==} + engines: {node: '>=8'} + + pathe@2.0.3: + resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + + perfect-debounce@2.1.0: + resolution: {integrity: sha512-LjgdTytVFXeUgtHZr9WYViYSM/g8MkcTPYDlPa3cDqMirHjKiSZPYd6DoL7pK8AJQr+uWkQvCjHNdiMqsrJs+g==} + + pg-cloudflare@1.4.1: + resolution: {integrity: sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==} + + pg-connection-string@2.14.1: + resolution: {integrity: sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==} + + pg-int8@1.0.1: + resolution: {integrity: sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==} + engines: {node: '>=4.0.0'} + + pg-pool@3.14.0: + resolution: {integrity: sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==} + peerDependencies: + pg: '>=8.0' + + pg-protocol@1.16.1: + resolution: {integrity: sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==} + + pg-types@2.2.0: + resolution: {integrity: sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==} + engines: {node: '>=4'} + + pg@8.23.1: + resolution: {integrity: sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ==} + engines: {node: '>= 16.0.0'} + peerDependencies: + pg-native: '>=3.0.1' + peerDependenciesMeta: + pg-native: + optional: true + + pgpass@1.0.5: + resolution: {integrity: sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@2.3.2: + resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==} + engines: {node: '>=8.6'} + + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + + pirates@4.0.7: + resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==} + engines: {node: '>= 6'} + + pkg-types@2.3.3: + resolution: {integrity: sha512-j/lCFdcppV0JxWpCEITdbDltBxPP6cHT+yNJ6Go2OgoSA9518X847X9z0p6LtA4Nc16+eQzCZjRrWanTGvHJ5w==} + + pluralize@8.0.0: + resolution: {integrity: sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==} + engines: {node: '>=4'} + + postcss-import@15.1.0: + resolution: {integrity: sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==} + engines: {node: '>=14.0.0'} + peerDependencies: + postcss: ^8.0.0 + + postcss-js@4.1.0: + resolution: {integrity: sha512-oIAOTqgIo7q2EOwbhb8UalYePMvYoIeRY2YKntdpFQXNosSu3vLrniGgmH9OKs/qAkfoj5oB3le/7mINW1LCfw==} + engines: {node: ^12 || ^14 || >= 16} + peerDependencies: + postcss: ^8.4.21 + + postcss-load-config@6.0.1: + resolution: {integrity: sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==} + engines: {node: '>= 18'} + peerDependencies: + jiti: '>=1.21.0' + postcss: '>=8.0.9' + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + jiti: + optional: true + postcss: + optional: true + tsx: + optional: true + yaml: + optional: true + + postcss-nested@6.2.0: + resolution: {integrity: sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==} + engines: {node: '>=12.0'} + peerDependencies: + postcss: ^8.2.14 + + postcss-selector-parser@6.1.4: + resolution: {integrity: sha512-bIoJLOmjCO1S9XdY/DcnR5hJxvrDir1PbGChrzXG3vw0/FOliy/fA3dmdhQ441kah4gKv+TwckGzex6wNS5cnQ==} + engines: {node: '>=4'} + + postcss-value-parser@4.2.0: + resolution: {integrity: sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==} + + postcss@8.5.28: + resolution: {integrity: sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==} + engines: {node: ^10 || ^12 || >=14} + + postgres-array@2.0.0: + resolution: {integrity: sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==} + engines: {node: '>=4'} + + postgres-array@3.0.4: + resolution: {integrity: sha512-nAUSGfSDGOaOAEGwqsRY27GPOea7CNipJPOA7lPbdEpx5Kg3qzdP0AaWC5MlhTWV9s4hFX39nomVZ+C4tnGOJQ==} + engines: {node: '>=12'} + + postgres-bytea@1.0.1: + resolution: {integrity: sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==} + engines: {node: '>=0.10.0'} + + postgres-date@1.0.7: + resolution: {integrity: sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==} + engines: {node: '>=0.10.0'} + + postgres-interval@1.2.0: + resolution: {integrity: sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==} + engines: {node: '>=0.10.0'} + + postgres@3.4.7: + resolution: {integrity: sha512-Jtc2612XINuBjIl/QTWsV5UvE8UHuNblcO3vVADSrKsrc6RqGX6lOW1cEo3CM2v0XG4Nat8nI+YM7/f26VxXLw==} + engines: {node: '>=12'} + + prelude-ls@1.2.1: + resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} + engines: {node: '>= 0.8.0'} + + prettier@3.9.9: + resolution: {integrity: sha512-Z/CJHIkdujO/OtN7nXUii0Rf3VT5SRuhjBA82Xvu2XhBUgX3nhP67T0LHceBdQLex7OOFGTox+Q5Yg8Jk2Qivg==} + engines: {node: '>=14'} + hasBin: true + + prisma@7.10.0: + resolution: {integrity: sha512-o0ornyJOWgygVAzGCpr8PdXV8EJLHyVGDDUr/voBQt8Azzw8cYTByzzPGcA/m4tCkPcnJA8raEOv2CslsKhPEw==} + engines: {node: ^20.19 || ^22.12 || >=24.0} + hasBin: true + peerDependencies: + better-sqlite3: '>=9.0.0' + typescript: '>=5.4.0' + peerDependenciesMeta: + better-sqlite3: + optional: true + typescript: + optional: true + + proper-lockfile@4.1.2: + resolution: {integrity: sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==} + + proxy-addr@2.0.8: + resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==} + engines: {node: '>= 0.10'} + + punycode@2.3.1: + resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} + engines: {node: '>=6'} + + pure-rand@6.1.0: + resolution: {integrity: sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==} + + qs@6.16.0: + resolution: {integrity: sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==} + engines: {node: '>=0.6'} + + queue-microtask@1.2.3: + resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==} + + range-parser@1.3.0: + resolution: {integrity: sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==} + engines: {node: '>= 0.6'} + + raw-body@3.0.2: + resolution: {integrity: sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==} + engines: {node: '>= 0.10'} + + rc9@3.1.0: + resolution: {integrity: sha512-ufjkNVzbRHKcCOmTahZkmVsyc3W+MSk3jY03m+a7tGHkIsdVMG9l10/3HvFbWkkKzY5VFp3pkRsIo/UYgmFL7Q==} + + react-dom@18.3.1: + resolution: {integrity: sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==} + peerDependencies: + react: ^18.3.1 + + react-refresh@0.17.0: + resolution: {integrity: sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==} + engines: {node: '>=0.10.0'} + + react-router-dom@6.30.6: + resolution: {integrity: sha512-0RHKZz7wwffvkU+2MFVT2NnjK44ssLEV+m0CAJaS2Ksmorrwj7WxH00jO0SOCW26/tINUnJHToXblDs33I38YQ==} + engines: {node: '>=14.0.0'} + peerDependencies: + react: '>=16.8' + react-dom: '>=16.8' + + react-router@6.30.6: + resolution: {integrity: sha512-5HfK7k5im7LTOB0EqCQmfvy4C13G92Ssj1VTmouTK3AJvyjKTnFuCV0vcMAD/JS+JC4DvDIBRrlAeJIFjh5VWg==} + engines: {node: '>=14.0.0'} + peerDependencies: + react: '>=16.8' + + react@18.3.1: + resolution: {integrity: sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==} + engines: {node: '>=0.10.0'} + + read-cache@1.0.2: + resolution: {integrity: sha512-/peqiBB/n07gQGLsWaHho3WfvUyRscw0gYTsEFMhrIe/nWLkYaf5SbKYjGYqtRV3aPwykJgF2VEMo1ac4bnsGA==} + + readdirp@3.6.0: + resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==} + engines: {node: '>=8.10.0'} + + readdirp@5.1.1: + resolution: {integrity: sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==} + engines: {node: '>= 20.19.0'} + + reflect-metadata@0.2.2: + resolution: {integrity: sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==} + + remeda@2.33.4: + resolution: {integrity: sha512-ygHswjlc/opg2VrtiYvUOPLjxjtdKvjGz1/plDhkG66hjNjFr1xmfrs2ClNFo/E6TyUFiwYNh53bKV26oBoMGQ==} + + require-from-string@2.0.2: + resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} + engines: {node: '>=0.10.0'} + + resolve-from@4.0.0: + resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} + engines: {node: '>=4'} + + resolve@1.22.12: + resolution: {integrity: sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==} + engines: {node: '>= 0.4'} + hasBin: true + + restore-cursor@5.1.0: + resolution: {integrity: sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==} + engines: {node: '>=18'} + + ret@0.5.0: + resolution: {integrity: sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw==} + engines: {node: '>=10'} + + retry@0.12.0: + resolution: {integrity: sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==} + engines: {node: '>= 4'} + + reusify@1.1.0: + resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==} + engines: {iojs: '>=1.0.0', node: '>=0.10.0'} + + rimraf@3.0.2: + resolution: {integrity: sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==} + deprecated: Rimraf versions prior to v4 are no longer supported + hasBin: true + + robust-predicates@3.0.3: + resolution: {integrity: sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==} + + rolldown@1.2.12: + resolution: {integrity: sha512-8wafseiaG80xmXSfqidUNqZcylTlhmPZZt+za2m+js2sFZ8dTNlhIOV2WcbIPx2hgwPBJpEUGFAMZ9bgBBLTSQ==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + rollup@4.64.0: + resolution: {integrity: sha512-gjA/kFeDfffII8COoPsvLPvE16hWDTEc1+0QKQNKUkuV8iJjqsC4xXs8/FzuL0v9EV39kuxTbAgcFoTRyy2TGQ==} + engines: {node: '>=18.0.0', npm: '>=8.0.0'} + hasBin: true + + router@2.2.0: + resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==} + engines: {node: '>= 18'} + + run-parallel@1.2.0: + resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==} + + rxjs@7.8.2: + resolution: {integrity: sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==} + + safe-regex2@5.1.1: + resolution: {integrity: sha512-mOSBvHGDZMuIEZMdOz/aCEYDCv0E7nfcNsIhUF+/P+xC7Hyf3FkvymqgPbg9D1EdSGu+uKbJgy09K/RKKc7kJA==} + hasBin: true + + safer-buffer@2.1.2: + resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + + scheduler@0.23.2: + resolution: {integrity: sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==} + + semver@6.3.1: + resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==} + hasBin: true + + semver@7.8.5: + resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} + engines: {node: '>=10'} + hasBin: true + + send@1.2.1: + resolution: {integrity: sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==} + engines: {node: '>= 18'} + + seq-queue@0.0.5: + resolution: {integrity: sha512-hr3Wtp/GZIc/6DAGPDcV4/9WoZhjrkXsi5B/07QgX8tsdc6ilr7BFM6PM6rbdAX1kFSDYeZGLipIZZKyQP0O5Q==} + + serve-static@2.2.1: + resolution: {integrity: sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==} + engines: {node: '>= 18'} + + setprototypeof@1.2.0: + resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==} + + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + + shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + + side-channel-list@1.0.1: + resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==} + engines: {node: '>= 0.4'} + + side-channel-map@1.0.1: + resolution: {integrity: sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==} + engines: {node: '>= 0.4'} + + side-channel-weakmap@1.0.2: + resolution: {integrity: sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==} + engines: {node: '>= 0.4'} + + side-channel@1.1.1: + resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==} + engines: {node: '>= 0.4'} + + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + + signal-exit@3.0.7: + resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==} + + signal-exit@4.1.0: + resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} + engines: {node: '>=14'} + + skin-tone@2.0.0: + resolution: {integrity: sha512-kUMbT1oBJCpgrnKoSr0o6wPtvRWT9W9UKvGLwfJYO2WuahZRHOpEyL1ckyMGgMWh0UdpmaoFqKKD29WTomNEGA==} + engines: {node: '>=8'} + + slash@3.0.0: + resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==} + engines: {node: '>=8'} + + source-map-js@1.2.2: + resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} + engines: {node: '>=0.10.0'} + + source-map@0.8.0: + resolution: {integrity: sha512-d8EqvL+k/SOXCreS/SUzg2ciyHqBBLcN/yuRjFsbvVhHTE2pgei7oAhmPM7kWFbkX6OSMQfUq4KbkF3au9lhYQ==} + engines: {node: '>= 12'} + + split2@4.2.0: + resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==} + engines: {node: '>= 10.x'} + + sqlstring@2.3.3: + resolution: {integrity: sha512-qC9iz2FlN7DQl3+wjwn3802RTyjCx7sDvfQEXchwa6CWOx07/WVfh91gBmQ9fahw8snwGEWU3xGzOt4tFyHLxg==} + engines: {node: '>= 0.6'} + + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + + standardwebhooks@1.1.1: + resolution: {integrity: sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==} + + statuses@2.0.2: + resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==} + engines: {node: '>= 0.8'} + + std-env@3.10.0: + resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==} + + std-env@4.3.0: + resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} + + stdin-discarder@0.3.2: + resolution: {integrity: sha512-eCPu1qRxPVkl5605OTWF8Wz40b4Mf45NY5LQmVPQ599knfs5QhASUm9GbJ5BDMDOXgrnh0wyEdvzmL//YMlw0A==} + engines: {node: '>=18'} + + streamsearch@1.1.0: + resolution: {integrity: sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==} + engines: {node: '>=10.0.0'} + + string-width@4.2.3: + resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} + engines: {node: '>=8'} + + string-width@8.3.0: + resolution: {integrity: sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==} + engines: {node: '>=20'} + + strip-ansi@6.0.1: + resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} + engines: {node: '>=8'} + + strip-ansi@7.2.0: + resolution: {integrity: sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==} + engines: {node: '>=12'} + + strip-bom@3.0.0: + resolution: {integrity: sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==} + engines: {node: '>=4'} + + strip-final-newline@2.0.0: + resolution: {integrity: sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==} + engines: {node: '>=6'} + + strip-json-comments@3.1.1: + resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==} + engines: {node: '>=8'} + + stripe@23.0.0: + resolution: {integrity: sha512-MDE2A5ZVVluYURORaZEVghSmnLJc3w6aHAlZSxDQMsOjOb3V0O6ro/CiaeFlJS4N7uIVmsg98ocRsPmUK6YfyA==} + engines: {node: '>=20'} + peerDependencies: + '@types/node': '>=20' + peerDependenciesMeta: + '@types/node': + optional: true + + strtok3@10.3.5: + resolution: {integrity: sha512-ki4hZQfh5rX0QDLLkOCj+h+CVNkqmp/CMf8v8kZpkNVK6jGQooMytqzLZYUVYIZcFZ6yDB70EfD8POcFXiF5oA==} + engines: {node: '>=18'} + + sucrase@3.35.1: + resolution: {integrity: sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==} + engines: {node: '>=16 || 14 >=14.17'} + hasBin: true + + superagent@10.4.1: + resolution: {integrity: sha512-PVMkMrhKrSTtFhUU8jiWuGh/gyRMKiyCTCmm0+qVzRNxlfntmRKJkDhlEXN62x3HIb33sQ4kmL8lcSdccWAchQ==} + engines: {node: '>=14.18.0'} + + supertest@7.3.1: + resolution: {integrity: sha512-vNaNCFoCR/edDbErQZp5KLNT8R4dSPHX7rlDLoE8hWLAm/878j6ShMbe8HK/E6RwwuhlSXVelXAIg9AxR5WWPw==} + engines: {node: '>=14.18.0'} + + supports-color@7.2.0: + resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} + engines: {node: '>=8'} + + supports-preserve-symlinks-flag@1.0.0: + resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} + engines: {node: '>= 0.4'} + + tailwind-merge@2.6.1: + resolution: {integrity: sha512-Oo6tHdpZsGpkKG88HJ8RR1rg/RdnEkQEfMoEk2x1XRI3F1AxeU+ijRXpiVUF4UbLfcxxRGw6TbUINKYdWVsQTQ==} + + tailwindcss@3.4.19: + resolution: {integrity: sha512-3ofp+LL8E+pK/JuPLPggVAIaEuhvIz4qNcf3nA1Xn2o/7fb7s/TYpHhwGDv1ZU3PkBluUVaF8PyCHcm48cKLWQ==} + engines: {node: '>=14.0.0'} + hasBin: true + + text-table@0.2.0: + resolution: {integrity: sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==} + + thenify-all@1.6.0: + resolution: {integrity: sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==} + engines: {node: '>=0.8'} + + thenify@3.3.1: + resolution: {integrity: sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==} + + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + + tinyexec@1.3.1: + resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} + engines: {node: '>=18'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + tinyrainbow@3.2.0: + resolution: {integrity: sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A==} + engines: {node: '>=14.0.0'} + + to-regex-range@5.0.1: + resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} + engines: {node: '>=8.0'} + + toidentifier@1.0.1: + resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==} + engines: {node: '>=0.6'} + + token-types@6.1.2: + resolution: {integrity: sha512-dRXchy+C0IgK8WPC6xvCHFRIWYUbqqdEIKPaKo/AcTUNzwLTK6AH7RjdLWsEZcAN/TBdtfUw3PYEgPr5VPr6ww==} + engines: {node: '>=14.16'} + + ts-api-utils@1.4.3: + resolution: {integrity: sha512-i3eMG77UTMD0hZhgRS562pv83RC6ukSAC2GMNWc+9dieh/+jDM5u5YG+NHX6VNDRHQcHwmsTHctP9LhbC3WxVw==} + engines: {node: '>=16'} + peerDependencies: + typescript: '>=4.2.0' + + ts-interface-checker@0.1.13: + resolution: {integrity: sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==} + + tsconfig-paths@4.2.0: + resolution: {integrity: sha512-NoZ4roiN7LnbKn9QqE1amc9DJfzvZXxF4xDavcOWt1BPkdx+m+0gJuPM+S0vCe7zTJMYUP0R8pO2XMr+Y8oLIg==} + engines: {node: '>=6'} + + tslib@2.8.1: + resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + + turbo@2.11.7: + resolution: {integrity: sha512-RhXHbqfvY6o3xt/zSHCwSNwLrZlXiqHzewi4eAj9PtZ1T1CqgMJ2yIDb7SKPTG9IikTm925mfzL6hldQVdyNWw==} + hasBin: true + + type-check@0.4.0: + resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} + engines: {node: '>= 0.8.0'} + + type-fest@0.20.2: + resolution: {integrity: sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==} + engines: {node: '>=10'} + + type-is@1.6.18: + resolution: {integrity: sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==} + engines: {node: '>= 0.6'} + + type-is@2.1.0: + resolution: {integrity: sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==} + engines: {node: '>= 18'} + + typescript@5.9.3: + resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} + engines: {node: '>=14.17'} + hasBin: true + + typescript@6.0.3: + resolution: {integrity: sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==} + engines: {node: '>=14.17'} + hasBin: true + + uid@2.0.2: + resolution: {integrity: sha512-u3xV3X7uzvi5b1MncmZo3i2Aw222Zk1keqLA1YkHldREkAhAqi65wuPfe7lHx8H/Wzy+8CE7S7uS3jekIM5s8g==} + engines: {node: '>=8'} + + uint8array-extras@1.6.0: + resolution: {integrity: sha512-8iAasVS4wUx0gPLjH8Xtz2PeDzTSiy8QiLGu2DT3X5GU+egFEQhpnbtkehbAwjvDcxIERmCYcysiODFmE3Ud0Q==} + engines: {node: '>=18'} + + undici-types@7.24.6: + resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==} + + undici-types@8.9.0: + resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==} + + unicode-emoji-modifier-base@1.0.0: + resolution: {integrity: sha512-yLSH4py7oFH3oG/9K+XWrz1pSi3dfUrWEnInbxMfArOfc1+33BlGPQtLsOYwvdMy11AwUBetYuaRxSPqgkq+8g==} + engines: {node: '>=4'} + + unpipe@1.0.0: + resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==} + engines: {node: '>= 0.8'} + + update-browserslist-db@1.3.3: + resolution: {integrity: sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==} + hasBin: true + peerDependencies: + browserslist: '>= 4.21.0' + + uri-js@4.4.1: + resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} + + util-deprecate@1.0.2: + resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} + + valibot@1.4.2: + resolution: {integrity: sha512-gjdCvJ6d3RyHAneqxMYMW9QMCwYMb3jpOO0IyHZV1bnRHFBHrX3VkIILt5XYR0WhwHiH7Mty8ovuPZ/O3gamrg==} + peerDependencies: + typescript: '>=5' + peerDependenciesMeta: + typescript: + optional: true + + validator@13.15.35: + resolution: {integrity: sha512-TQ5pAGhd5whStmqWvYF4OjQROlmv9SMFVt37qoCBdqRffuuklWYQlCNnEs2ZaIBD1kZRNnikiZOS1eqgkar0iw==} + engines: {node: '>= 0.10'} + + vary@1.1.2: + resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==} + engines: {node: '>= 0.8'} + + vite-plugin-wasm@3.6.0: + resolution: {integrity: sha512-mL/QPziiIA4RAA6DkaZZzOstdwbW5jO4Vz7Zenj0wieKWBlNvIvX5L5ljum9lcUX0ShNfBgCNLKTjNkRVVqcsw==} + peerDependencies: + vite: ^2 || ^3 || ^4 || ^5 || ^6 || ^7 || ^8 + + vite@5.4.21: + resolution: {integrity: sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==} + engines: {node: ^18.0.0 || >=20.0.0} + hasBin: true + peerDependencies: + '@types/node': ^18.0.0 || >=20.0.0 + less: '*' + lightningcss: ^1.21.0 + sass: '*' + sass-embedded: '*' + stylus: '*' + sugarss: '*' + terser: ^5.4.0 + peerDependenciesMeta: + '@types/node': + optional: true + less: + optional: true + lightningcss: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + + vite@8.3.2: + resolution: {integrity: sha512-SQr1x6W5vVSbROg7vsyXIaxK9b0G7zsT68acdWWRmnBUsgDieLCRG+Rep9WdZgcposvv/GSnr4GUUBqB3vXq6w==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + '@vitejs/devtools': ^0.7.1 + esbuild: ^0.27.0 || ^0.28.0 + jiti: '>=1.21.0' + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + '@vitejs/devtools': + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitest@4.1.11: + resolution: {integrity: sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==} + engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 4.1.11 + '@vitest/browser-preview': 4.1.11 + '@vitest/browser-webdriverio': 4.1.11 + '@vitest/coverage-istanbul': 4.1.11 + '@vitest/coverage-v8': 4.1.11 + '@vitest/ui': 4.1.11 + happy-dom: '*' + jsdom: '*' + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + which@2.0.2: + resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} + engines: {node: '>= 8'} + hasBin: true + + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + + word-wrap@1.2.5: + resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} + engines: {node: '>=0.10.0'} + + wrappy@1.0.2: + resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} + + xdg-app-paths@5.5.1: + resolution: {integrity: sha512-hI3flOB4PLZIy5prbtTpirobtPE2ZtZ52szO+2mM9Efp6ErM398La+C1lIpNWDfNoQk+6Lsi6nMcCwVB7pxeMQ==} + engines: {node: '>= 6.0'} + + xdg-portable@7.3.0: + resolution: {integrity: sha512-sqMMuL1rc0FmMBOzCpd0yuy9trqF2yTTVe+E9ogwCSWQCdDEtQUwrZPT6AxqtsFGRNxycgncbP/xmOOSPw5ZUw==} + engines: {node: '>= 6.0'} + + xtend@4.0.2: + resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==} + engines: {node: '>=0.4'} + + yallist@3.1.1: + resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} + + yocto-queue@0.1.0: + resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} + engines: {node: '>=10'} + + yoctocolors@2.2.0: + resolution: {integrity: sha512-xYqdZFUK/VYazNl/oCDYN+3WloWQwMfZxBoiNt6qNyk+xfOdi598muWE42rNZFp1kNOiqW936q5RhUdnpqElSg==} + engines: {node: '>=18'} + + zeptomatch@2.1.0: + resolution: {integrity: sha512-KiGErG2J0G82LSpniV0CtIzjlJ10E04j02VOudJsPyPwNZgGnRKQy7I1R7GMyg/QswnE4l7ohSGrQbQbjXPPDA==} + + zod@4.1.11: + resolution: {integrity: sha512-WPsqwxITS2tzx1bzhIKsEs19ABD5vmCVa4xBo2tq/SrV4RNZtfws1EnCWQXM6yh8bD08a1idvkB5MZSBiZsjwg==} + +snapshots: + + '@alloc/quick-lru@5.3.0': {} + + '@angular-devkit/core@22.2.0(chokidar@5.0.0)': + dependencies: + ajv: 8.20.0 + ajv-formats: 3.0.1(ajv@8.20.0) + jsonc-parser: 3.3.1 + picomatch: 4.0.7 + rxjs: 7.8.2 + source-map: 0.8.0 + optionalDependencies: + chokidar: 5.0.0 + + '@angular-devkit/schematics-cli@22.2.0(@types/node@24.19.1)(chokidar@5.0.0)': + dependencies: + '@angular-devkit/core': 22.2.0(chokidar@5.0.0) + '@angular-devkit/schematics': 22.2.0(chokidar@5.0.0) + '@inquirer/prompts': 8.7.2(@types/node@24.19.1) + transitivePeerDependencies: + - '@types/node' + - chokidar + + '@angular-devkit/schematics@22.2.0(chokidar@5.0.0)': + dependencies: + '@angular-devkit/core': 22.2.0(chokidar@5.0.0) + jsonc-parser: 3.3.1 + magic-string: 1.4.1 + ora: 9.4.1 + rxjs: 7.8.2 + transitivePeerDependencies: + - chokidar + + '@babel/code-frame@7.29.7': + dependencies: + '@babel/helper-validator-identifier': 7.29.7 + js-tokens: 4.0.0 + picocolors: 1.1.1 + + '@babel/compat-data@7.29.7': {} + + '@babel/core@7.29.7': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/generator': 7.29.8 + '@babel/helper-compilation-targets': 7.29.7 + '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) + '@babel/helpers': 7.29.7 + '@babel/parser': 7.29.9 + '@babel/template': 7.29.7 + '@babel/traverse': 7.29.8 + '@babel/types': 7.29.8 + '@jridgewell/remapping': 2.3.5 + convert-source-map: 2.0.0 + debug: 4.4.3 + gensync: 1.0.0-beta.2 + json5: 2.2.3 + semver: 6.3.1 + transitivePeerDependencies: + - supports-color + + '@babel/generator@7.29.8': + dependencies: + '@babel/parser': 7.29.9 + '@babel/types': 7.29.8 + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + jsesc: 3.1.0 + + '@babel/helper-compilation-targets@7.29.7': + dependencies: + '@babel/compat-data': 7.29.7 + '@babel/helper-validator-option': 7.29.7 + browserslist: 4.29.3 + lru-cache: 5.1.1 + semver: 6.3.1 + + '@babel/helper-globals@7.29.7': {} + + '@babel/helper-module-imports@7.29.7': + dependencies: + '@babel/traverse': 7.29.8 + '@babel/types': 7.29.8 + transitivePeerDependencies: + - supports-color + + '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-module-imports': 7.29.7 + '@babel/helper-validator-identifier': 7.29.7 + '@babel/traverse': 7.29.8 + transitivePeerDependencies: + - supports-color + + '@babel/helper-plugin-utils@7.29.7': {} + + '@babel/helper-string-parser@7.29.7': {} + + '@babel/helper-validator-identifier@7.29.7': {} + + '@babel/helper-validator-option@7.29.7': {} + + '@babel/helpers@7.29.7': + dependencies: + '@babel/template': 7.29.7 + '@babel/types': 7.29.8 + + '@babel/parser@7.29.9': + dependencies: + '@babel/types': 7.29.8 + + '@babel/plugin-transform-react-jsx-self@7.29.7(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 + + '@babel/plugin-transform-react-jsx-source@7.29.7(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 + + '@babel/template@7.29.7': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/parser': 7.29.9 + '@babel/types': 7.29.8 + + '@babel/traverse@7.29.8': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/generator': 7.29.8 + '@babel/helper-globals': 7.29.7 + '@babel/parser': 7.29.9 + '@babel/template': 7.29.7 + '@babel/types': 7.29.8 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + '@babel/types@7.29.8': + dependencies: + '@babel/helper-string-parser': 7.29.7 + '@babel/helper-validator-identifier': 7.29.7 + + '@bcoe/v8-coverage@1.0.2': {} + + '@borewit/text-codec@0.2.2': {} + + '@clerk/backend@3.22.0(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@clerk/shared': 4.38.0(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + standardwebhooks: 1.1.1 + tslib: 2.8.1 + transitivePeerDependencies: + - react + - react-dom + + '@clerk/react@6.17.5(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@clerk/shared': 4.38.0(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + tslib: 2.8.1 + + '@clerk/shared@4.38.0(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@tanstack/query-core': 5.104.1 + dequal: 2.0.3 + glob-to-regexp: 0.4.1 + js-cookie: 3.0.8 + optionalDependencies: + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + + '@colors/colors@1.5.0': + optional: true + + '@electric-sql/pglite-socket@0.1.3(@electric-sql/pglite@0.4.3)': + dependencies: + '@electric-sql/pglite': 0.4.3 + + '@electric-sql/pglite-tools@0.3.3(@electric-sql/pglite@0.4.3)': + dependencies: + '@electric-sql/pglite': 0.4.3 + + '@electric-sql/pglite@0.4.3': {} + + '@esbuild/aix-ppc64@0.21.5': + optional: true + + '@esbuild/aix-ppc64@0.28.2': + optional: true + + '@esbuild/android-arm64@0.21.5': + optional: true + + '@esbuild/android-arm64@0.28.2': + optional: true + + '@esbuild/android-arm@0.21.5': + optional: true + + '@esbuild/android-arm@0.28.2': + optional: true + + '@esbuild/android-x64@0.21.5': + optional: true + + '@esbuild/android-x64@0.28.2': + optional: true + + '@esbuild/darwin-arm64@0.21.5': + optional: true + + '@esbuild/darwin-arm64@0.28.2': + optional: true + + '@esbuild/darwin-x64@0.21.5': + optional: true + + '@esbuild/darwin-x64@0.28.2': + optional: true + + '@esbuild/freebsd-arm64@0.21.5': + optional: true + + '@esbuild/freebsd-arm64@0.28.2': + optional: true + + '@esbuild/freebsd-x64@0.21.5': + optional: true + + '@esbuild/freebsd-x64@0.28.2': + optional: true + + '@esbuild/linux-arm64@0.21.5': + optional: true + + '@esbuild/linux-arm64@0.28.2': + optional: true + + '@esbuild/linux-arm@0.21.5': + optional: true + + '@esbuild/linux-arm@0.28.2': + optional: true + + '@esbuild/linux-ia32@0.21.5': + optional: true + + '@esbuild/linux-ia32@0.28.2': + optional: true + + '@esbuild/linux-loong64@0.21.5': + optional: true + + '@esbuild/linux-loong64@0.28.2': + optional: true + + '@esbuild/linux-mips64el@0.21.5': + optional: true + + '@esbuild/linux-mips64el@0.28.2': + optional: true + + '@esbuild/linux-ppc64@0.21.5': + optional: true + + '@esbuild/linux-ppc64@0.28.2': + optional: true + + '@esbuild/linux-riscv64@0.21.5': + optional: true + + '@esbuild/linux-riscv64@0.28.2': + optional: true + + '@esbuild/linux-s390x@0.21.5': + optional: true + + '@esbuild/linux-s390x@0.28.2': + optional: true + + '@esbuild/linux-x64@0.21.5': + optional: true + + '@esbuild/linux-x64@0.28.2': + optional: true + + '@esbuild/netbsd-arm64@0.28.2': + optional: true + + '@esbuild/netbsd-x64@0.21.5': + optional: true + + '@esbuild/netbsd-x64@0.28.2': + optional: true + + '@esbuild/openbsd-arm64@0.28.2': + optional: true + + '@esbuild/openbsd-x64@0.21.5': + optional: true + + '@esbuild/openbsd-x64@0.28.2': + optional: true + + '@esbuild/openharmony-arm64@0.28.2': + optional: true + + '@esbuild/sunos-x64@0.21.5': + optional: true + + '@esbuild/sunos-x64@0.28.2': + optional: true + + '@esbuild/win32-arm64@0.21.5': + optional: true + + '@esbuild/win32-arm64@0.28.2': + optional: true + + '@esbuild/win32-ia32@0.21.5': + optional: true + + '@esbuild/win32-ia32@0.28.2': + optional: true + + '@esbuild/win32-x64@0.21.5': + optional: true + + '@esbuild/win32-x64@0.28.2': + optional: true + + '@eslint-community/eslint-utils@4.10.1(eslint@8.57.1)': + dependencies: + eslint: 8.57.1 + eslint-visitor-keys: 3.4.3 + + '@eslint-community/regexpp@4.12.2': {} + + '@eslint/eslintrc@2.1.4': + dependencies: + ajv: 6.15.0 + debug: 4.4.3 + espree: 9.6.1 + globals: 13.24.0 + ignore: 5.3.2 + import-fresh: 3.3.1 + js-yaml: 4.3.2 + minimatch: 3.1.5 + strip-json-comments: 3.1.1 + transitivePeerDependencies: + - supports-color + + '@eslint/js@8.57.1': {} + + '@humanwhocodes/config-array@0.13.0': + dependencies: + '@humanwhocodes/object-schema': 2.0.3 + debug: 4.4.3 + minimatch: 3.1.5 + transitivePeerDependencies: + - supports-color + + '@humanwhocodes/module-importer@1.0.1': {} + + '@humanwhocodes/object-schema@2.0.3': {} + + '@inquirer/ansi@2.0.8': {} + + '@inquirer/checkbox@5.2.5(@types/node@24.19.1)': + dependencies: + '@inquirer/ansi': 2.0.8 + '@inquirer/core': 12.0.3(@types/node@24.19.1) + '@inquirer/figures': 2.0.9 + '@inquirer/type': 4.1.1(@types/node@24.19.1) + optionalDependencies: + '@types/node': 24.19.1 + + '@inquirer/confirm@6.3.2(@types/node@24.19.1)': + dependencies: + '@inquirer/core': 12.0.3(@types/node@24.19.1) + '@inquirer/type': 4.1.1(@types/node@24.19.1) + optionalDependencies: + '@types/node': 24.19.1 + + '@inquirer/core@12.0.3(@types/node@24.19.1)': + dependencies: + '@inquirer/ansi': 2.0.8 + '@inquirer/figures': 2.0.9 + '@inquirer/type': 4.1.1(@types/node@24.19.1) + cli-width: 4.1.0 + fast-wrap-ansi: 0.2.2 + mute-stream: 3.0.0 + signal-exit: 4.1.0 + optionalDependencies: + '@types/node': 24.19.1 + + '@inquirer/editor@5.3.3(@types/node@24.19.1)': + dependencies: + '@inquirer/core': 12.0.3(@types/node@24.19.1) + '@inquirer/external-editor': 3.0.5(@types/node@24.19.1) + '@inquirer/type': 4.1.1(@types/node@24.19.1) + optionalDependencies: + '@types/node': 24.19.1 + + '@inquirer/expand@5.1.5(@types/node@24.19.1)': + dependencies: + '@inquirer/core': 12.0.3(@types/node@24.19.1) + '@inquirer/type': 4.1.1(@types/node@24.19.1) + optionalDependencies: + '@types/node': 24.19.1 + + '@inquirer/external-editor@3.0.5(@types/node@24.19.1)': + dependencies: + chardet: 2.2.0 + iconv-lite: 0.7.3 + optionalDependencies: + '@types/node': 24.19.1 + + '@inquirer/figures@2.0.9': {} + + '@inquirer/input@5.1.6(@types/node@24.19.1)': + dependencies: + '@inquirer/core': 12.0.3(@types/node@24.19.1) + '@inquirer/type': 4.1.1(@types/node@24.19.1) + optionalDependencies: + '@types/node': 24.19.1 + + '@inquirer/number@4.2.3(@types/node@24.19.1)': + dependencies: + '@inquirer/core': 12.0.3(@types/node@24.19.1) + '@inquirer/type': 4.1.1(@types/node@24.19.1) + optionalDependencies: + '@types/node': 24.19.1 + + '@inquirer/password@5.2.2(@types/node@24.19.1)': + dependencies: + '@inquirer/ansi': 2.0.8 + '@inquirer/core': 12.0.3(@types/node@24.19.1) + '@inquirer/type': 4.1.1(@types/node@24.19.1) + optionalDependencies: + '@types/node': 24.19.1 + + '@inquirer/prompts@8.7.2(@types/node@24.19.1)': + dependencies: + '@inquirer/checkbox': 5.2.5(@types/node@24.19.1) + '@inquirer/confirm': 6.3.2(@types/node@24.19.1) + '@inquirer/editor': 5.3.3(@types/node@24.19.1) + '@inquirer/expand': 5.1.5(@types/node@24.19.1) + '@inquirer/input': 5.1.6(@types/node@24.19.1) + '@inquirer/number': 4.2.3(@types/node@24.19.1) + '@inquirer/password': 5.2.2(@types/node@24.19.1) + '@inquirer/rawlist': 5.3.5(@types/node@24.19.1) + '@inquirer/search': 4.3.3(@types/node@24.19.1) + '@inquirer/select': 5.2.5(@types/node@24.19.1) + optionalDependencies: + '@types/node': 24.19.1 + + '@inquirer/rawlist@5.3.5(@types/node@24.19.1)': + dependencies: + '@inquirer/core': 12.0.3(@types/node@24.19.1) + '@inquirer/type': 4.1.1(@types/node@24.19.1) + optionalDependencies: + '@types/node': 24.19.1 + + '@inquirer/search@4.3.3(@types/node@24.19.1)': + dependencies: + '@inquirer/core': 12.0.3(@types/node@24.19.1) + '@inquirer/figures': 2.0.9 + '@inquirer/type': 4.1.1(@types/node@24.19.1) + optionalDependencies: + '@types/node': 24.19.1 + + '@inquirer/select@5.2.5(@types/node@24.19.1)': + dependencies: + '@inquirer/ansi': 2.0.8 + '@inquirer/core': 12.0.3(@types/node@24.19.1) + '@inquirer/figures': 2.0.9 + '@inquirer/type': 4.1.1(@types/node@24.19.1) + optionalDependencies: + '@types/node': 24.19.1 + + '@inquirer/type@4.1.1(@types/node@24.19.1)': + optionalDependencies: + '@types/node': 24.19.1 + + '@jridgewell/gen-mapping@0.3.13': + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/remapping@2.3.5': + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.6.0 + + '@lukeed/csprng@1.1.0': {} + + '@napi-rs/lzma-linux-x64-gnu@1.5.1': + optional: true + + '@nestjs/cli@12.0.8(@types/node@24.19.1)(prettier@3.9.9)': + dependencies: + '@angular-devkit/core': 22.2.0(chokidar@5.0.0) + '@angular-devkit/schematics': 22.2.0(chokidar@5.0.0) + '@angular-devkit/schematics-cli': 22.2.0(@types/node@24.19.1)(chokidar@5.0.0) + '@inquirer/prompts': 8.7.2(@types/node@24.19.1) + '@nestjs/schematics': 12.0.6(chokidar@5.0.0)(prettier@3.9.9)(typescript@6.0.3) + ansis: 4.4.0 + chokidar: 5.0.0 + cli-table3: 0.6.5 + commander: 15.0.0 + jsonc-parser: 3.3.1 + minimatch: 10.2.6 + node-emoji: 2.2.0 + ora: 9.4.1 + tsconfig-paths: 4.2.0 + typescript: 6.0.3 + transitivePeerDependencies: + - '@types/node' + - prettier + + '@nestjs/common@12.1.2(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2)': + dependencies: + '@standard-schema/spec': 1.1.0 + file-type: 22.1.1 + iterare: 1.2.1 + load-esm: 1.0.3 + reflect-metadata: 0.2.2 + rxjs: 7.8.2 + tslib: 2.8.1 + uid: 2.0.2 + optionalDependencies: + class-transformer: 0.5.1 + class-validator: 0.15.1 + transitivePeerDependencies: + - supports-color + + '@nestjs/core@12.1.2(@nestjs/common@12.1.2(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@12.1.2)(reflect-metadata@0.2.2)(rxjs@7.8.2)': + dependencies: + '@nestjs/common': 12.1.2(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2) + fast-safe-stringify: 2.1.1 + iterare: 1.2.1 + path-to-regexp: 8.4.2 + reflect-metadata: 0.2.2 + rxjs: 7.8.2 + tslib: 2.8.1 + uid: 2.0.2 + optionalDependencies: + '@nestjs/platform-express': 12.1.2(@nestjs/common@12.1.2(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@12.1.2) + + '@nestjs/platform-express@12.1.2(@nestjs/common@12.1.2(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@12.1.2)': + dependencies: + '@nestjs/common': 12.1.2(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2) + '@nestjs/core': 12.1.2(@nestjs/common@12.1.2(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@12.1.2)(reflect-metadata@0.2.2)(rxjs@7.8.2) + cors: 2.8.6 + express: 5.2.1 + multer: 2.4.0 + path-to-regexp: 8.4.2 + tslib: 2.8.1 + transitivePeerDependencies: + - supports-color + + '@nestjs/schematics@12.0.6(chokidar@5.0.0)(prettier@3.9.9)(typescript@6.0.3)': + dependencies: + '@angular-devkit/core': 22.2.0(chokidar@5.0.0) + '@angular-devkit/schematics': 22.2.0(chokidar@5.0.0) + comment-json: 5.0.0 + jsonc-parser: 3.3.1 + pluralize: 8.0.0 + typescript: 6.0.3 + optionalDependencies: + prettier: 3.9.9 + transitivePeerDependencies: + - chokidar + + '@nestjs/testing@12.1.2(@nestjs/common@12.1.2(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@12.1.2)(@nestjs/platform-express@12.1.2)': + dependencies: + '@nestjs/common': 12.1.2(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2) + '@nestjs/core': 12.1.2(@nestjs/common@12.1.2(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@12.1.2)(reflect-metadata@0.2.2)(rxjs@7.8.2) + tslib: 2.8.1 + optionalDependencies: + '@nestjs/platform-express': 12.1.2(@nestjs/common@12.1.2(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@12.1.2) + + '@noble/hashes@1.8.0': {} + + '@nodelib/fs.scandir@2.1.5': + dependencies: + '@nodelib/fs.stat': 2.0.5 + run-parallel: 1.2.0 + + '@nodelib/fs.stat@2.0.5': {} + + '@nodelib/fs.walk@1.2.8': + dependencies: + '@nodelib/fs.scandir': 2.1.5 + fastq: 1.20.3 + + '@oxc-project/types@0.152.0': {} + + '@oxlint-tsgolint/darwin-arm64@7.0.2003': + optional: true + + '@oxlint-tsgolint/darwin-x64@7.0.2003': + optional: true + + '@oxlint-tsgolint/linux-arm64@7.0.2003': + optional: true + + '@oxlint-tsgolint/linux-x64@7.0.2003': + optional: true + + '@oxlint-tsgolint/win32-arm64@7.0.2003': + optional: true + + '@oxlint-tsgolint/win32-x64@7.0.2003': + optional: true + + '@oxlint/binding-android-arm-eabi@1.86.0': + optional: true + + '@oxlint/binding-android-arm64@1.86.0': + optional: true + + '@oxlint/binding-darwin-arm64@1.86.0': + optional: true + + '@oxlint/binding-darwin-x64@1.86.0': + optional: true + + '@oxlint/binding-freebsd-x64@1.86.0': + optional: true + + '@oxlint/binding-linux-arm-gnueabihf@1.86.0': + optional: true + + '@oxlint/binding-linux-arm-musleabihf@1.86.0': + optional: true + + '@oxlint/binding-linux-arm64-gnu@1.86.0': + optional: true + + '@oxlint/binding-linux-arm64-musl@1.86.0': + optional: true + + '@oxlint/binding-linux-ppc64-gnu@1.86.0': + optional: true + + '@oxlint/binding-linux-riscv64-gnu@1.86.0': + optional: true + + '@oxlint/binding-linux-riscv64-musl@1.86.0': + optional: true + + '@oxlint/binding-linux-s390x-gnu@1.86.0': + optional: true + + '@oxlint/binding-linux-x64-gnu@1.86.0': + optional: true + + '@oxlint/binding-linux-x64-musl@1.86.0': + optional: true + + '@oxlint/binding-openharmony-arm64@1.86.0': + optional: true + + '@oxlint/binding-win32-arm64-msvc@1.86.0': + optional: true + + '@oxlint/binding-win32-ia32-msvc@1.86.0': + optional: true + + '@oxlint/binding-win32-x64-msvc@1.86.0': + optional: true + + '@paralleldrive/cuid2@2.3.1': + dependencies: + '@noble/hashes': 1.8.0 + + '@prisma/adapter-pg@7.10.0': + dependencies: + '@prisma/driver-adapter-utils': 7.10.0 + '@types/pg': 8.23.1 + pg: 8.23.1 + postgres-array: 3.0.4 + transitivePeerDependencies: + - pg-native + + '@prisma/client-runtime-utils@7.10.0': {} + + '@prisma/client@7.10.0(prisma@7.10.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(magicast@0.5.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(typescript@6.0.3))(typescript@6.0.3)': + dependencies: + '@prisma/client-runtime-utils': 7.10.0 + optionalDependencies: + prisma: 7.10.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(magicast@0.5.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(typescript@6.0.3) + typescript: 6.0.3 + + '@prisma/config@7.10.0(magicast@0.5.5)': + dependencies: + c12: 3.3.4(magicast@0.5.5) + deepmerge-ts: 7.1.5 + effect: 3.20.0 + empathic: 2.0.0 + transitivePeerDependencies: + - magicast + + '@prisma/debug@7.10.0': {} + + '@prisma/debug@7.2.0': {} + + '@prisma/dev@0.24.17(typescript@6.0.3)': + dependencies: + '@electric-sql/pglite': 0.4.3 + '@electric-sql/pglite-socket': 0.1.3(@electric-sql/pglite@0.4.3) + '@electric-sql/pglite-tools': 0.3.3(@electric-sql/pglite@0.4.3) + '@prisma/get-platform': 7.2.0 + '@prisma/query-plan-executor': 7.2.0 + '@prisma/streams-local': 0.1.11 + find-my-way: 9.7.0 + foreground-child: 3.3.1 + get-port-please: 3.2.0 + pathe: 2.0.3 + proper-lockfile: 4.1.2 + remeda: 2.33.4 + std-env: 3.10.0 + valibot: 1.4.2(typescript@6.0.3) + zeptomatch: 2.1.0 + transitivePeerDependencies: + - typescript + + '@prisma/driver-adapter-utils@7.10.0': + dependencies: + '@prisma/debug': 7.10.0 + + '@prisma/engines-version@7.10.0-4.0edf323efd1d98336f3f0a68684b56f689b900d3': {} + + '@prisma/engines@7.10.0': + dependencies: + '@prisma/debug': 7.10.0 + '@prisma/engines-version': 7.10.0-4.0edf323efd1d98336f3f0a68684b56f689b900d3 + '@prisma/fetch-engine': 7.10.0 + '@prisma/get-platform': 7.10.0 + + '@prisma/fetch-engine@7.10.0': + dependencies: + '@prisma/debug': 7.10.0 + '@prisma/engines-version': 7.10.0-4.0edf323efd1d98336f3f0a68684b56f689b900d3 + '@prisma/get-platform': 7.10.0 + + '@prisma/get-platform@7.10.0': + dependencies: + '@prisma/debug': 7.10.0 + + '@prisma/get-platform@7.2.0': + dependencies: + '@prisma/debug': 7.2.0 + + '@prisma/query-plan-executor@7.2.0': {} + + '@prisma/streams-local@0.1.11': + dependencies: + ajv: 8.20.0 + better-result: 2.10.0 + env-paths: 3.0.0 + proper-lockfile: 4.1.2 + + '@prisma/studio-core@0.33.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@radix-ui/react-toggle': 1.1.10(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@types/react': 18.3.31 + '@visx/curve': 4.0.1-alpha.0 + '@visx/event': 4.0.1-alpha.0 + '@visx/grid': 4.0.1-alpha.0(react@18.3.1) + '@visx/group': 4.0.1-alpha.0(react@18.3.1) + '@visx/responsive': 4.0.1-alpha.0(react@18.3.1) + '@visx/scale': 4.0.1-alpha.0 + '@visx/shape': 4.0.1-alpha.0(react@18.3.1) + d3-array: 3.2.4 + d3-shape: 3.2.0 + elkjs: 0.11.1 + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + transitivePeerDependencies: + - '@types/react-dom' + + '@radix-ui/primitive@1.1.3': {} + + '@radix-ui/react-compose-refs@1.1.2(@types/react@18.3.31)(react@18.3.1)': + dependencies: + react: 18.3.1 + optionalDependencies: + '@types/react': 18.3.31 + + '@radix-ui/react-primitive@2.1.3(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@radix-ui/react-slot': 1.2.3(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) + + '@radix-ui/react-slot@1.2.3(@types/react@18.3.31)(react@18.3.1)': + dependencies: + '@radix-ui/react-compose-refs': 1.1.2(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + optionalDependencies: + '@types/react': 18.3.31 + + '@radix-ui/react-toggle@1.1.10(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@radix-ui/primitive': 1.1.3 + '@radix-ui/react-primitive': 2.1.3(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) + + '@radix-ui/react-use-controllable-state@1.2.2(@types/react@18.3.31)(react@18.3.1)': + dependencies: + '@radix-ui/react-use-effect-event': 0.0.2(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-use-layout-effect': 1.1.1(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + optionalDependencies: + '@types/react': 18.3.31 + + '@radix-ui/react-use-effect-event@0.0.2(@types/react@18.3.31)(react@18.3.1)': + dependencies: + '@radix-ui/react-use-layout-effect': 1.1.1(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + optionalDependencies: + '@types/react': 18.3.31 + + '@radix-ui/react-use-layout-effect@1.1.1(@types/react@18.3.31)(react@18.3.1)': + dependencies: + react: 18.3.1 + optionalDependencies: + '@types/react': 18.3.31 + + '@remix-run/router@1.23.4': {} + + '@rolldown/binding-android-arm-eabi@1.2.12': + optional: true + + '@rolldown/binding-android-arm64@1.2.12': + optional: true + + '@rolldown/binding-darwin-arm64@1.2.12': + optional: true + + '@rolldown/binding-darwin-x64@1.2.12': + optional: true + + '@rolldown/binding-freebsd-x64@1.2.12': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.2.12': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.2.12': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.2.12': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.2.12': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.2.12': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.2.12': + optional: true + + '@rolldown/binding-linux-x64-musl@1.2.12': + optional: true + + '@rolldown/binding-openharmony-arm64@1.2.12': + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.2.12': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.2.12': + optional: true + + '@rolldown/pluginutils@1.0.0-beta.27': {} + + '@rolldown/pluginutils@1.0.1': {} + + '@rollup/rollup-android-arm-eabi@4.64.0': + optional: true + + '@rollup/rollup-android-arm64@4.64.0': + optional: true + + '@rollup/rollup-darwin-arm64@4.64.0': + optional: true + + '@rollup/rollup-darwin-x64@4.64.0': + optional: true + + '@rollup/rollup-freebsd-arm64@4.64.0': + optional: true + + '@rollup/rollup-freebsd-x64@4.64.0': + optional: true + + '@rollup/rollup-linux-arm-gnueabihf@4.64.0': + optional: true + + '@rollup/rollup-linux-arm-musleabihf@4.64.0': + optional: true + + '@rollup/rollup-linux-arm64-gnu@4.64.0': + optional: true + + '@rollup/rollup-linux-arm64-musl@4.64.0': + optional: true + + '@rollup/rollup-linux-loong64-gnu@4.64.0': + optional: true + + '@rollup/rollup-linux-loong64-musl@4.64.0': + optional: true + + '@rollup/rollup-linux-ppc64-gnu@4.64.0': + optional: true + + '@rollup/rollup-linux-ppc64-musl@4.64.0': + optional: true + + '@rollup/rollup-linux-riscv64-gnu@4.64.0': + optional: true + + '@rollup/rollup-linux-riscv64-musl@4.64.0': + optional: true + + '@rollup/rollup-linux-s390x-gnu@4.64.0': + optional: true + + '@rollup/rollup-linux-x64-gnu@4.64.0': + optional: true + + '@rollup/rollup-linux-x64-musl@4.64.0': + optional: true + + '@rollup/rollup-openbsd-x64@4.64.0': + optional: true + + '@rollup/rollup-openharmony-arm64@4.64.0': + optional: true + + '@rollup/rollup-win32-arm64-msvc@4.64.0': + optional: true + + '@rollup/rollup-win32-ia32-msvc@4.64.0': + optional: true + + '@rollup/rollup-win32-x64-gnu@4.64.0': + optional: true + + '@rollup/rollup-win32-x64-msvc@4.64.0': + optional: true + + '@sindresorhus/is@4.6.0': {} + + '@stablelib/base64@1.0.1': {} + + '@standard-schema/spec@1.1.0': {} + + '@tanstack/query-core@5.104.1': {} + + '@tanstack/react-query@5.104.1(react@18.3.1)': + dependencies: + '@tanstack/query-core': 5.104.1 + react: 18.3.1 + + '@tokenizer/inflate@0.4.1': + dependencies: + debug: 4.4.3 + token-types: 6.1.2 + transitivePeerDependencies: + - supports-color + + '@tokenizer/token@0.3.0': {} + + '@turbo/darwin-64@2.11.7': + optional: true + + '@turbo/darwin-arm64@2.11.7': + optional: true + + '@turbo/linux-64@2.11.7': + optional: true + + '@turbo/linux-arm64@2.11.7': + optional: true + + '@turbo/windows-64@2.11.7': + optional: true + + '@turbo/windows-arm64@2.11.7': + optional: true + + '@types/babel__core@7.20.5': + dependencies: + '@babel/parser': 7.29.9 + '@babel/types': 7.29.8 + '@types/babel__generator': 7.27.0 + '@types/babel__template': 7.4.4 + '@types/babel__traverse': 7.28.0 + + '@types/babel__generator@7.27.0': + dependencies: + '@babel/types': 7.29.8 + + '@types/babel__template@7.4.4': + dependencies: + '@babel/parser': 7.29.9 + '@babel/types': 7.29.8 + + '@types/babel__traverse@7.28.0': + dependencies: + '@babel/types': 7.29.8 + + '@types/body-parser@1.19.6': + dependencies: + '@types/connect': 3.4.38 + '@types/node': 26.6.4 + + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/connect@3.4.38': + dependencies: + '@types/node': 26.6.4 + + '@types/cookiejar@2.1.5': {} + + '@types/d3-array@3.0.3': {} + + '@types/d3-color@3.1.0': {} + + '@types/d3-delaunay@6.0.1': {} + + '@types/d3-format@3.0.1': {} + + '@types/d3-geo@3.1.0': + dependencies: + '@types/geojson': 7946.0.16 + + '@types/d3-interpolate@3.0.1': + dependencies: + '@types/d3-color': 3.1.0 + + '@types/d3-path@3.1.1': {} + + '@types/d3-scale@4.0.2': + dependencies: + '@types/d3-time': 3.0.0 + + '@types/d3-shape@3.1.7': + dependencies: + '@types/d3-path': 3.1.1 + + '@types/d3-time-format@2.1.0': {} + + '@types/d3-time@3.0.0': {} + + '@types/deep-eql@4.0.2': {} + + '@types/estree@1.0.9': {} + + '@types/express-serve-static-core@5.1.3': + dependencies: + '@types/node': 26.6.4 + '@types/qs': 6.15.1 + '@types/range-parser': 1.2.7 + '@types/send': 1.2.1 + + '@types/express@5.0.6': + dependencies: + '@types/body-parser': 1.19.6 + '@types/express-serve-static-core': 5.1.3 + '@types/serve-static': 2.2.0 + + '@types/geojson@7946.0.16': {} + + '@types/http-errors@2.0.5': {} + + '@types/lodash@4.17.25': {} + + '@types/methods@1.1.4': {} + + '@types/node@24.19.1': + dependencies: + undici-types: 7.24.6 + + '@types/node@26.6.4': + dependencies: + undici-types: 8.9.0 + + '@types/pg@8.23.1': + dependencies: + '@types/node': 26.6.4 + pg-protocol: 1.16.1 + pg-types: 2.2.0 + + '@types/prop-types@15.7.15': {} + + '@types/qs@6.15.1': {} + + '@types/range-parser@1.2.7': {} + + '@types/react-dom@18.3.7(@types/react@18.3.31)': + dependencies: + '@types/react': 18.3.31 + + '@types/react@18.3.31': + dependencies: + '@types/prop-types': 15.7.15 + csstype: 3.2.3 + + '@types/send@1.2.1': + dependencies: + '@types/node': 26.6.4 + + '@types/serve-static@2.2.0': + dependencies: + '@types/http-errors': 2.0.5 + '@types/node': 26.6.4 + + '@types/superagent@8.1.11': + dependencies: + '@types/cookiejar': 2.1.5 + '@types/methods': 1.1.4 + '@types/node': 26.6.4 + form-data: 4.0.6 + + '@types/supertest@7.2.1': + dependencies: + '@types/methods': 1.1.4 + '@types/superagent': 8.1.11 + + '@types/validator@13.15.10': {} + + '@typescript-eslint/eslint-plugin@7.18.0(@typescript-eslint/parser@7.18.0(eslint@8.57.1)(typescript@5.9.3))(eslint@8.57.1)(typescript@5.9.3)': + dependencies: + '@eslint-community/regexpp': 4.12.2 + '@typescript-eslint/parser': 7.18.0(eslint@8.57.1)(typescript@5.9.3) + '@typescript-eslint/scope-manager': 7.18.0 + '@typescript-eslint/type-utils': 7.18.0(eslint@8.57.1)(typescript@5.9.3) + '@typescript-eslint/utils': 7.18.0(eslint@8.57.1)(typescript@5.9.3) + '@typescript-eslint/visitor-keys': 7.18.0 + eslint: 8.57.1 + graphemer: 1.4.0 + ignore: 5.3.2 + natural-compare: 1.4.0 + ts-api-utils: 1.4.3(typescript@5.9.3) + optionalDependencies: + typescript: 5.9.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/parser@7.18.0(eslint@8.57.1)(typescript@5.9.3)': + dependencies: + '@typescript-eslint/scope-manager': 7.18.0 + '@typescript-eslint/types': 7.18.0 + '@typescript-eslint/typescript-estree': 7.18.0(typescript@5.9.3) + '@typescript-eslint/visitor-keys': 7.18.0 + debug: 4.4.3 + eslint: 8.57.1 + optionalDependencies: + typescript: 5.9.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/scope-manager@7.18.0': + dependencies: + '@typescript-eslint/types': 7.18.0 + '@typescript-eslint/visitor-keys': 7.18.0 + + '@typescript-eslint/type-utils@7.18.0(eslint@8.57.1)(typescript@5.9.3)': + dependencies: + '@typescript-eslint/typescript-estree': 7.18.0(typescript@5.9.3) + '@typescript-eslint/utils': 7.18.0(eslint@8.57.1)(typescript@5.9.3) + debug: 4.4.3 + eslint: 8.57.1 + ts-api-utils: 1.4.3(typescript@5.9.3) + optionalDependencies: + typescript: 5.9.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/types@7.18.0': {} + + '@typescript-eslint/typescript-estree@7.18.0(typescript@5.9.3)': + dependencies: + '@typescript-eslint/types': 7.18.0 + '@typescript-eslint/visitor-keys': 7.18.0 + debug: 4.4.3 + globby: 11.1.0 + is-glob: 4.0.3 + minimatch: 9.0.9 + semver: 7.8.5 + ts-api-utils: 1.4.3(typescript@5.9.3) + optionalDependencies: + typescript: 5.9.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/utils@7.18.0(eslint@8.57.1)(typescript@5.9.3)': + dependencies: + '@eslint-community/eslint-utils': 4.10.1(eslint@8.57.1) + '@typescript-eslint/scope-manager': 7.18.0 + '@typescript-eslint/types': 7.18.0 + '@typescript-eslint/typescript-estree': 7.18.0(typescript@5.9.3) + eslint: 8.57.1 + transitivePeerDependencies: + - supports-color + - typescript + + '@typescript-eslint/visitor-keys@7.18.0': + dependencies: + '@typescript-eslint/types': 7.18.0 + eslint-visitor-keys: 3.4.3 + + '@ungap/structured-clone@1.4.0': {} + + '@vercel/cli-config@0.3.1': + dependencies: + xdg-app-paths: 5.5.1 + zod: 4.1.11 + + '@vercel/cli-exec@1.0.1': + dependencies: + execa: 5.1.1 + + '@vercel/functions@3.9.11': + dependencies: + '@vercel/oidc': 4.0.0 + + '@vercel/oidc@4.0.0': + dependencies: + '@vercel/cli-config': 0.3.1 + '@vercel/cli-exec': 1.0.1 + jose: 5.10.0 + + '@visx/curve@4.0.1-alpha.0': + dependencies: + '@visx/vendor': 4.0.0-alpha.0 + + '@visx/event@4.0.1-alpha.0': + dependencies: + '@types/react': 18.3.31 + '@visx/point': 4.0.1-alpha.0 + + '@visx/grid@4.0.1-alpha.0(react@18.3.1)': + dependencies: + '@types/react': 18.3.31 + '@visx/curve': 4.0.1-alpha.0 + '@visx/group': 4.0.1-alpha.0(react@18.3.1) + '@visx/point': 4.0.1-alpha.0 + '@visx/scale': 4.0.1-alpha.0 + '@visx/shape': 4.0.1-alpha.0(react@18.3.1) + classnames: 2.5.1 + react: 18.3.1 + + '@visx/group@4.0.1-alpha.0(react@18.3.1)': + dependencies: + '@types/react': 18.3.31 + classnames: 2.5.1 + react: 18.3.1 + + '@visx/point@4.0.1-alpha.0': {} + + '@visx/responsive@4.0.1-alpha.0(react@18.3.1)': + dependencies: + '@types/lodash': 4.17.25 + '@types/react': 18.3.31 + lodash: 4.18.1 + react: 18.3.1 + + '@visx/scale@4.0.1-alpha.0': + dependencies: + '@visx/vendor': 4.0.0-alpha.0 + + '@visx/shape@4.0.1-alpha.0(react@18.3.1)': + dependencies: + '@types/lodash': 4.17.25 + '@types/react': 18.3.31 + '@visx/curve': 4.0.1-alpha.0 + '@visx/group': 4.0.1-alpha.0(react@18.3.1) + '@visx/scale': 4.0.1-alpha.0 + '@visx/vendor': 4.0.0-alpha.0 + classnames: 2.5.1 + lodash: 4.18.1 + react: 18.3.1 + + '@visx/vendor@4.0.0-alpha.0': + dependencies: + '@types/d3-array': 3.0.3 + '@types/d3-color': 3.1.0 + '@types/d3-delaunay': 6.0.1 + '@types/d3-format': 3.0.1 + '@types/d3-geo': 3.1.0 + '@types/d3-interpolate': 3.0.1 + '@types/d3-path': 3.1.1 + '@types/d3-scale': 4.0.2 + '@types/d3-shape': 3.1.7 + '@types/d3-time': 3.0.0 + '@types/d3-time-format': 2.1.0 + d3-array: 3.2.1 + d3-color: 3.1.0 + d3-delaunay: 6.0.2 + d3-format: 3.1.0 + d3-geo: 3.1.0 + d3-interpolate: 3.0.1 + d3-path: 3.1.0 + d3-scale: 4.0.2 + d3-shape: 3.2.0 + d3-time: 3.1.0 + d3-time-format: 4.1.0 + internmap: 2.0.3 + + '@vitejs/plugin-react@4.7.0(vite@5.4.21(@types/node@26.6.4)(lightningcss@1.33.0))': + dependencies: + '@babel/core': 7.29.7 + '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7) + '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/core@7.29.7) + '@rolldown/pluginutils': 1.0.0-beta.27 + '@types/babel__core': 7.20.5 + react-refresh: 0.17.0 + vite: 5.4.21(@types/node@26.6.4)(lightningcss@1.33.0) + transitivePeerDependencies: + - supports-color + + '@vitest/coverage-v8@4.1.11(vitest@4.1.11)': + dependencies: + '@bcoe/v8-coverage': 1.0.2 + '@vitest/utils': 4.1.11 + ast-v8-to-istanbul: 1.0.7 + istanbul-lib-coverage: 3.2.2 + istanbul-lib-report: 3.0.1 + istanbul-reports: 3.2.0 + magicast: 0.5.5 + obug: 2.2.1 + std-env: 4.3.0 + tinyrainbow: 3.2.0 + vitest: 4.1.11(@types/node@24.19.1)(@vitest/coverage-v8@4.1.11)(vite@8.3.2(@types/node@24.19.1)(esbuild@0.28.2)(jiti@2.7.0)) + + '@vitest/expect@4.1.11': + dependencies: + '@standard-schema/spec': 1.1.0 + '@types/chai': 5.2.3 + '@vitest/spy': 4.1.11 + '@vitest/utils': 4.1.11 + chai: 6.3.0 + tinyrainbow: 3.2.0 + + '@vitest/mocker@4.1.11(vite@8.3.2(@types/node@24.19.1)(esbuild@0.28.2)(jiti@2.7.0))': + dependencies: + '@vitest/spy': 4.1.11 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 8.3.2(@types/node@24.19.1)(esbuild@0.28.2)(jiti@2.7.0) + + '@vitest/pretty-format@4.1.11': + dependencies: + tinyrainbow: 3.2.0 + + '@vitest/runner@4.1.11': + dependencies: + '@vitest/utils': 4.1.11 + pathe: 2.0.3 + + '@vitest/snapshot@4.1.11': + dependencies: + '@vitest/pretty-format': 4.1.11 + '@vitest/utils': 4.1.11 + magic-string: 0.30.21 + pathe: 2.0.3 + + '@vitest/spy@4.1.11': {} + + '@vitest/utils@4.1.11': + dependencies: + '@vitest/pretty-format': 4.1.11 + convert-source-map: 2.0.0 + tinyrainbow: 3.2.0 + + '@viz2d/core@0.1.0': {} + + '@viz2d/sdk@0.1.4': + dependencies: + '@viz2d/core': 0.1.0 + + accepts@2.0.0: + dependencies: + mime-types: 3.0.2 + negotiator: 1.1.0 + + acorn-jsx@5.3.2(acorn@8.18.0): + dependencies: + acorn: 8.18.0 + + acorn@8.18.0: {} + + ajv-formats@3.0.1(ajv@8.20.0): + optionalDependencies: + ajv: 8.20.0 + + ajv@6.15.0: + dependencies: + fast-deep-equal: 3.1.3 + fast-json-stable-stringify: 2.1.0 + json-schema-traverse: 0.4.1 + uri-js: 4.4.1 + + ajv@8.20.0: + dependencies: + fast-deep-equal: 3.1.3 + fast-uri: 3.1.8 + json-schema-traverse: 1.0.0 + require-from-string: 2.0.2 + + ansi-regex@5.0.1: {} + + ansi-regex@6.4.0: {} + + ansi-styles@4.3.0: + dependencies: + color-convert: 2.0.1 + + ansis@4.4.0: {} + + any-promise@1.3.0: {} + + anymatch@3.1.3: + dependencies: + normalize-path: 3.0.0 + picomatch: 2.3.2 + + append-field@1.0.0: {} + + arg@5.0.2: {} + + argparse@2.0.1: {} + + array-timsort@1.0.3: {} + + array-union@2.1.0: {} + + asap@2.0.6: {} + + assertion-error@2.0.1: {} + + ast-v8-to-istanbul@1.0.7: + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + estree-walker: 3.0.3 + js-tokens: 10.0.0 + + asynckit@0.4.0: {} + + autoprefixer@10.6.1(postcss@8.5.28): + dependencies: + browserslist: 4.29.3 + caniuse-lite: 1.0.30001814 + fraction.js: 5.3.4 + picocolors: 1.1.1 + postcss: 8.5.28 + postcss-value-parser: 4.2.0 + + aws-ssl-profiles@1.1.2: {} + + balanced-match@1.0.2: {} + + balanced-match@4.0.4: {} + + baseline-browser-mapping@2.11.27: {} + + better-result@2.10.0: {} + + binary-extensions@2.3.0: {} + + body-parser@2.3.0: + dependencies: + bytes: 3.1.2 + content-type: 2.1.0 + debug: 4.4.3 + http-errors: 2.0.1 + iconv-lite: 0.7.3 + on-finished: 2.4.1 + qs: 6.16.0 + raw-body: 3.0.2 + type-is: 2.1.0 + transitivePeerDependencies: + - supports-color + + brace-expansion@1.1.21: + dependencies: + balanced-match: 1.0.2 + concat-map: 0.0.1 + + brace-expansion@2.1.7: + dependencies: + balanced-match: 1.0.2 + + brace-expansion@5.0.12: + dependencies: + balanced-match: 4.0.4 + + braces@3.0.3: + dependencies: + fill-range: 7.1.1 + + browserslist@4.29.3: + dependencies: + baseline-browser-mapping: 2.11.27 + caniuse-lite: 1.0.30001814 + electron-to-chromium: 1.5.444 + node-releases: 2.0.57 + update-browserslist-db: 1.3.3(browserslist@4.29.3) + + busboy@1.6.0: + dependencies: + streamsearch: 1.1.0 + + bytes@3.1.2: {} + + c12@3.3.4(magicast@0.5.5): + dependencies: + chokidar: 5.0.0 + confbox: 0.2.4 + defu: 6.1.7 + dotenv: 17.4.2 + exsolve: 1.1.3 + giget: 3.3.1 + jiti: 2.7.0 + ohash: 2.0.12 + pathe: 2.0.3 + perfect-debounce: 2.1.0 + pkg-types: 2.3.3 + rc9: 3.1.0 + optionalDependencies: + magicast: 0.5.5 + + call-bind-apply-helpers@1.0.2: + dependencies: + es-errors: 1.3.0 + function-bind: 1.1.2 + + call-bound@1.0.4: + dependencies: + call-bind-apply-helpers: 1.0.2 + get-intrinsic: 1.3.0 + + callsites@3.1.0: {} + + camelcase-css@2.0.1: {} + + caniuse-lite@1.0.30001814: {} + + chai@6.3.0: {} + + chalk@4.1.2: + dependencies: + ansi-styles: 4.3.0 + supports-color: 7.2.0 + + chalk@5.6.2: {} + + char-regex@1.0.2: {} + + chardet@2.2.0: {} + + chokidar@3.6.0: + dependencies: + anymatch: 3.1.3 + braces: 3.0.3 + glob-parent: 5.1.2 + is-binary-path: 2.1.0 + is-glob: 4.0.3 + normalize-path: 3.0.0 + readdirp: 3.6.0 + optionalDependencies: + fsevents: 2.3.3 + + chokidar@5.0.0: + dependencies: + readdirp: 5.1.1 + + class-transformer@0.5.1: {} + + class-validator@0.15.1: + dependencies: + '@types/validator': 13.15.10 + libphonenumber-js: 1.13.14 + validator: 13.15.35 + + classnames@2.5.1: {} + + cli-cursor@5.0.0: + dependencies: + restore-cursor: 5.1.0 + + cli-spinners@3.4.0: {} + + cli-table3@0.6.5: + dependencies: + string-width: 4.2.3 + optionalDependencies: + '@colors/colors': 1.5.0 + + cli-width@4.1.0: {} + + clsx@2.1.1: {} + + color-convert@2.0.1: + dependencies: + color-name: 1.1.4 + + color-name@1.1.4: {} + + combined-stream@1.0.8: + dependencies: + delayed-stream: 1.0.0 + + commander@15.0.0: {} + + commander@4.1.1: {} + + comment-json@5.0.0: + dependencies: + array-timsort: 1.0.3 + esprima: 4.0.1 + + component-emitter@1.3.1: {} + + concat-map@0.0.1: {} + + confbox@0.2.4: {} + + confbox@0.3.1: {} + + content-disposition@1.1.0: {} + + content-type@1.0.5: {} + + content-type@2.1.0: {} + + convert-source-map@2.0.0: {} + + cookie-signature@1.2.2: {} + + cookie@0.7.2: {} + + cookiejar@2.1.4: {} + + cors@2.8.6: + dependencies: + object-assign: 4.1.1 + vary: 1.1.2 + + cross-spawn@7.0.6: + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.2 + + cssesc@3.0.0: {} + + csstype@3.2.3: {} + + d3-array@3.2.1: + dependencies: + internmap: 2.0.3 + + d3-array@3.2.4: + dependencies: + internmap: 2.0.3 + + d3-color@3.1.0: {} + + d3-delaunay@6.0.2: + dependencies: + delaunator: 5.1.0 + + d3-format@3.1.0: {} + + d3-geo@3.1.0: + dependencies: + d3-array: 3.2.4 + + d3-interpolate@3.0.1: + dependencies: + d3-color: 3.1.0 + + d3-path@3.1.0: {} + + d3-scale@4.0.2: + dependencies: + d3-array: 3.2.4 + d3-format: 3.1.0 + d3-interpolate: 3.0.1 + d3-time: 3.1.0 + d3-time-format: 4.1.0 + + d3-shape@3.2.0: + dependencies: + d3-path: 3.1.0 + + d3-time-format@4.1.0: + dependencies: + d3-time: 3.1.0 + + d3-time@3.1.0: + dependencies: + d3-array: 3.2.4 + + debug@4.4.3: + dependencies: + ms: 2.1.3 + + deep-is@0.1.4: {} + + deepmerge-ts@7.1.5: {} + + defu@6.1.7: {} + + delaunator@5.1.0: + dependencies: + robust-predicates: 3.0.3 + + delayed-stream@1.0.0: {} + + denque@2.1.0: {} + + depd@2.0.0: {} + + dequal@2.0.3: {} + + destr@2.0.5: {} + + detect-libc@2.1.2: {} + + dezalgo@1.0.4: + dependencies: + asap: 2.0.6 + wrappy: 1.0.2 + + didyoumean@1.2.2: {} + + dir-glob@3.0.1: + dependencies: + path-type: 4.0.0 + + dlv@1.1.3: {} + + doctrine@3.0.0: + dependencies: + esutils: 2.0.3 + + dotenv@17.4.2: {} + + dotenv@18.0.5: {} + + dunder-proto@1.0.1: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-errors: 1.3.0 + gopd: 1.2.0 + + ee-first@1.1.1: {} + + effect@3.20.0: + dependencies: + '@standard-schema/spec': 1.1.0 + fast-check: 3.23.2 + + electron-to-chromium@1.5.444: {} + + elkjs@0.11.1: {} + + emoji-regex@8.0.0: {} + + emojilib@2.4.0: {} + + empathic@2.0.0: {} + + encodeurl@2.0.0: {} + + env-paths@3.0.0: {} + + es-define-property@1.0.1: {} + + es-errors@1.3.0: {} + + es-module-lexer@2.3.2: {} + + es-object-atoms@1.1.2: + dependencies: + es-errors: 1.3.0 + + es-set-tostringtag@2.1.0: + dependencies: + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + has-tostringtag: 1.0.2 + hasown: 2.0.4 + + esbuild@0.21.5: + optionalDependencies: + '@esbuild/aix-ppc64': 0.21.5 + '@esbuild/android-arm': 0.21.5 + '@esbuild/android-arm64': 0.21.5 + '@esbuild/android-x64': 0.21.5 + '@esbuild/darwin-arm64': 0.21.5 + '@esbuild/darwin-x64': 0.21.5 + '@esbuild/freebsd-arm64': 0.21.5 + '@esbuild/freebsd-x64': 0.21.5 + '@esbuild/linux-arm': 0.21.5 + '@esbuild/linux-arm64': 0.21.5 + '@esbuild/linux-ia32': 0.21.5 + '@esbuild/linux-loong64': 0.21.5 + '@esbuild/linux-mips64el': 0.21.5 + '@esbuild/linux-ppc64': 0.21.5 + '@esbuild/linux-riscv64': 0.21.5 + '@esbuild/linux-s390x': 0.21.5 + '@esbuild/linux-x64': 0.21.5 + '@esbuild/netbsd-x64': 0.21.5 + '@esbuild/openbsd-x64': 0.21.5 + '@esbuild/sunos-x64': 0.21.5 + '@esbuild/win32-arm64': 0.21.5 + '@esbuild/win32-ia32': 0.21.5 + '@esbuild/win32-x64': 0.21.5 + + esbuild@0.28.2: + optionalDependencies: + '@esbuild/aix-ppc64': 0.28.2 + '@esbuild/android-arm': 0.28.2 + '@esbuild/android-arm64': 0.28.2 + '@esbuild/android-x64': 0.28.2 + '@esbuild/darwin-arm64': 0.28.2 + '@esbuild/darwin-x64': 0.28.2 + '@esbuild/freebsd-arm64': 0.28.2 + '@esbuild/freebsd-x64': 0.28.2 + '@esbuild/linux-arm': 0.28.2 + '@esbuild/linux-arm64': 0.28.2 + '@esbuild/linux-ia32': 0.28.2 + '@esbuild/linux-loong64': 0.28.2 + '@esbuild/linux-mips64el': 0.28.2 + '@esbuild/linux-ppc64': 0.28.2 + '@esbuild/linux-riscv64': 0.28.2 + '@esbuild/linux-s390x': 0.28.2 + '@esbuild/linux-x64': 0.28.2 + '@esbuild/netbsd-arm64': 0.28.2 + '@esbuild/netbsd-x64': 0.28.2 + '@esbuild/openbsd-arm64': 0.28.2 + '@esbuild/openbsd-x64': 0.28.2 + '@esbuild/openharmony-arm64': 0.28.2 + '@esbuild/sunos-x64': 0.28.2 + '@esbuild/win32-arm64': 0.28.2 + '@esbuild/win32-ia32': 0.28.2 + '@esbuild/win32-x64': 0.28.2 + optional: true + + escalade@3.2.0: {} + + escape-html@1.0.3: {} + + escape-string-regexp@4.0.0: {} + + eslint-plugin-react-hooks@4.6.2(eslint@8.57.1): + dependencies: + eslint: 8.57.1 + + eslint-plugin-react-refresh@0.4.26(eslint@8.57.1): + dependencies: + eslint: 8.57.1 + + eslint-scope@7.2.2: + dependencies: + esrecurse: 4.3.0 + estraverse: 5.3.0 + + eslint-visitor-keys@3.4.3: {} + + eslint@8.57.1: + dependencies: + '@eslint-community/eslint-utils': 4.10.1(eslint@8.57.1) + '@eslint-community/regexpp': 4.12.2 + '@eslint/eslintrc': 2.1.4 + '@eslint/js': 8.57.1 + '@humanwhocodes/config-array': 0.13.0 + '@humanwhocodes/module-importer': 1.0.1 + '@nodelib/fs.walk': 1.2.8 + '@ungap/structured-clone': 1.4.0 + ajv: 6.15.0 + chalk: 4.1.2 + cross-spawn: 7.0.6 + debug: 4.4.3 + doctrine: 3.0.0 + escape-string-regexp: 4.0.0 + eslint-scope: 7.2.2 + eslint-visitor-keys: 3.4.3 + espree: 9.6.1 + esquery: 1.7.0 + esutils: 2.0.3 + fast-deep-equal: 3.1.3 + file-entry-cache: 6.0.1 + find-up: 5.0.0 + glob-parent: 6.0.2 + globals: 13.24.0 + graphemer: 1.4.0 + ignore: 5.3.2 + imurmurhash: 0.1.4 + is-glob: 4.0.3 + is-path-inside: 3.0.3 + js-yaml: 4.3.2 + json-stable-stringify-without-jsonify: 1.0.1 + levn: 0.4.1 + lodash.merge: 4.6.2 + minimatch: 3.1.5 + natural-compare: 1.4.0 + optionator: 0.9.4 + strip-ansi: 6.0.1 + text-table: 0.2.0 + transitivePeerDependencies: + - supports-color + + espree@9.6.1: + dependencies: + acorn: 8.18.0 + acorn-jsx: 5.3.2(acorn@8.18.0) + eslint-visitor-keys: 3.4.3 + + esprima@4.0.1: {} + + esquery@1.7.0: + dependencies: + estraverse: 5.3.0 + + esrecurse@4.3.0: + dependencies: + estraverse: 5.3.0 + + estraverse@5.3.0: {} + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.9 + + esutils@2.0.3: {} + + etag@1.8.1: {} + + execa@5.1.1: + dependencies: + cross-spawn: 7.0.6 + get-stream: 6.0.1 + human-signals: 2.1.0 + is-stream: 2.0.1 + merge-stream: 2.0.0 + npm-run-path: 4.0.1 + onetime: 5.1.2 + signal-exit: 3.0.7 + strip-final-newline: 2.0.0 + + expect-type@1.4.0: {} + + express@5.2.1: + dependencies: + accepts: 2.0.0 + body-parser: 2.3.0 + content-disposition: 1.1.0 + content-type: 1.0.5 + cookie: 0.7.2 + cookie-signature: 1.2.2 + debug: 4.4.3 + depd: 2.0.0 + encodeurl: 2.0.0 + escape-html: 1.0.3 + etag: 1.8.1 + finalhandler: 2.1.1 + fresh: 2.0.0 + http-errors: 2.0.1 + merge-descriptors: 2.0.0 + mime-types: 3.0.2 + on-finished: 2.4.1 + once: 1.4.0 + parseurl: 1.3.3 + proxy-addr: 2.0.8 + qs: 6.16.0 + range-parser: 1.3.0 + router: 2.2.0 + send: 1.2.1 + serve-static: 2.2.1 + statuses: 2.0.2 + type-is: 2.1.0 + vary: 1.1.2 + transitivePeerDependencies: + - supports-color + + exsolve@1.1.3: {} + + fast-check@3.23.2: + dependencies: + pure-rand: 6.1.0 + + fast-decode-uri-component@1.0.1: {} + + fast-deep-equal@3.1.3: {} + + fast-glob@3.3.3: + dependencies: + '@nodelib/fs.stat': 2.0.5 + '@nodelib/fs.walk': 1.2.8 + glob-parent: 5.1.2 + merge2: 1.4.1 + micromatch: 4.0.8 + + fast-json-stable-stringify@2.1.0: {} + + fast-levenshtein@2.0.6: {} + + fast-querystring@1.1.2: + dependencies: + fast-decode-uri-component: 1.0.1 + + fast-safe-stringify@2.1.1: {} + + fast-sha256@1.3.0: {} + + fast-string-truncated-width@3.0.3: {} + + fast-string-width@3.0.2: + dependencies: + fast-string-truncated-width: 3.0.3 + + fast-uri@3.1.8: {} + + fast-wrap-ansi@0.2.2: + dependencies: + fast-string-width: 3.0.2 + + fastq@1.20.3: + dependencies: + reusify: 1.1.0 + + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + + file-entry-cache@6.0.1: + dependencies: + flat-cache: 3.2.0 + + file-type@22.1.1: + dependencies: + '@tokenizer/inflate': 0.4.1 + strtok3: 10.3.5 + token-types: 6.1.2 + uint8array-extras: 1.6.0 + transitivePeerDependencies: + - supports-color + + fill-range@7.1.1: + dependencies: + to-regex-range: 5.0.1 + + finalhandler@2.1.1: + dependencies: + debug: 4.4.3 + encodeurl: 2.0.0 + escape-html: 1.0.3 + on-finished: 2.4.1 + parseurl: 1.3.3 + statuses: 2.0.2 + transitivePeerDependencies: + - supports-color + + find-my-way@9.7.0: + dependencies: + fast-deep-equal: 3.1.3 + fast-querystring: 1.1.2 + safe-regex2: 5.1.1 + + find-up@5.0.0: + dependencies: + locate-path: 6.0.0 + path-exists: 4.0.0 + + flat-cache@3.2.0: + dependencies: + flatted: 3.4.4 + keyv: 4.5.4 + rimraf: 3.0.2 + + flatted@3.4.4: {} + + foreground-child@3.3.1: + dependencies: + cross-spawn: 7.0.6 + signal-exit: 4.1.0 + + form-data@4.0.6: + dependencies: + asynckit: 0.4.0 + combined-stream: 1.0.8 + es-set-tostringtag: 2.1.0 + hasown: 2.0.4 + mime-types: 2.1.35 + + formidable@3.5.4: + dependencies: + '@paralleldrive/cuid2': 2.3.1 + dezalgo: 1.0.4 + once: 1.4.0 + + forwarded@0.2.0: {} + + fraction.js@5.3.4: {} + + fresh@2.0.0: {} + + fs.realpath@1.0.0: {} + + fsevents@2.3.3: + optional: true + + function-bind@1.1.2: {} + + generate-function@2.3.1: + dependencies: + is-property: 1.0.2 + + gensync@1.0.0-beta.2: {} + + get-east-asian-width@1.7.0: {} + + get-intrinsic@1.3.0: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-define-property: 1.0.1 + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + function-bind: 1.1.2 + get-proto: 1.0.1 + gopd: 1.2.0 + has-symbols: 1.1.0 + hasown: 2.0.4 + math-intrinsics: 1.1.0 + + get-port-please@3.2.0: {} + + get-proto@1.0.1: + dependencies: + dunder-proto: 1.0.1 + es-object-atoms: 1.1.2 + + get-stream@6.0.1: {} + + giget@3.3.1: {} + + glob-parent@5.1.2: + dependencies: + is-glob: 4.0.3 + + glob-parent@6.0.2: + dependencies: + is-glob: 4.0.3 + + glob-to-regexp@0.4.1: {} + + glob@7.2.3: + dependencies: + fs.realpath: 1.0.0 + inflight: 1.0.6 + inherits: 2.0.4 + minimatch: 3.1.5 + once: 1.4.0 + path-is-absolute: 1.0.1 + + globals@13.24.0: + dependencies: + type-fest: 0.20.2 + + globby@11.1.0: + dependencies: + array-union: 2.1.0 + dir-glob: 3.0.1 + fast-glob: 3.3.3 + ignore: 5.3.2 + merge2: 1.4.1 + slash: 3.0.0 + + gopd@1.2.0: {} + + graceful-fs@4.2.11: {} + + grammex@3.1.13: {} + + graphemer@1.4.0: {} + + graphmatch@1.1.1: {} + + has-flag@4.0.0: {} + + has-symbols@1.1.0: {} + + has-tostringtag@1.0.2: + dependencies: + has-symbols: 1.1.0 + + hasown@2.0.4: + dependencies: + function-bind: 1.1.2 + + html-escaper@2.0.2: {} + + http-errors@2.0.1: + dependencies: + depd: 2.0.0 + inherits: 2.0.4 + setprototypeof: 1.2.0 + statuses: 2.0.2 + toidentifier: 1.0.1 + + human-signals@2.1.0: {} + + iconv-lite@0.7.3: + dependencies: + safer-buffer: 2.1.2 + + ieee754@1.2.1: {} + + ignore@5.3.2: {} + + import-fresh@3.3.1: + dependencies: + parent-module: 1.0.1 + resolve-from: 4.0.0 + + imurmurhash@0.1.4: {} + + inflight@1.0.6: + dependencies: + once: 1.4.0 + wrappy: 1.0.2 + + inherits@2.0.4: {} + + internmap@2.0.3: {} + + ipaddr.js@1.9.1: {} + + is-binary-path@2.1.0: + dependencies: + binary-extensions: 2.3.0 + + is-core-module@2.17.0: + dependencies: + hasown: 2.0.4 + + is-extglob@2.1.1: {} + + is-fullwidth-code-point@3.0.0: {} + + is-glob@4.0.3: + dependencies: + is-extglob: 2.1.1 + + is-interactive@2.0.0: {} + + is-number@7.0.0: {} + + is-path-inside@3.0.3: {} + + is-promise@4.0.0: {} + + is-property@1.0.2: {} + + is-stream@2.0.1: {} + + is-unicode-supported@2.1.0: {} + + isexe@2.0.0: {} + + istanbul-lib-coverage@3.2.2: {} + + istanbul-lib-report@3.0.1: + dependencies: + istanbul-lib-coverage: 3.2.2 + make-dir: 4.0.0 + supports-color: 7.2.0 + + istanbul-reports@3.2.0: + dependencies: + html-escaper: 2.0.2 + istanbul-lib-report: 3.0.1 + + iterare@1.2.1: {} + + jiti@1.21.7: {} + + jiti@2.7.0: {} + + jose@5.10.0: {} + + jose@6.2.12: {} + + js-cookie@3.0.8: {} + + js-tokens@10.0.0: {} + + js-tokens@4.0.0: {} + + js-yaml@4.3.2: + dependencies: + argparse: 2.0.1 + + jsesc@3.1.0: {} + + json-buffer@3.0.1: {} + + json-schema-traverse@0.4.1: {} + + json-schema-traverse@1.0.0: {} + + json-stable-stringify-without-jsonify@1.0.1: {} + + json5@2.2.3: {} + + jsonc-parser@3.3.1: {} + + keyv@4.5.4: + dependencies: + json-buffer: 3.0.1 + + levn@0.4.1: + dependencies: + prelude-ls: 1.2.1 + type-check: 0.4.0 + + libphonenumber-js@1.13.14: {} + + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + + lilconfig@3.1.3: {} + + lines-and-columns@1.2.4: {} + + load-esm@1.0.3: {} + + locate-path@6.0.0: + dependencies: + p-locate: 5.0.0 + + lodash.merge@4.6.2: {} + + lodash@4.18.1: {} + + log-symbols@7.0.1: + dependencies: + is-unicode-supported: 2.1.0 + yoctocolors: 2.2.0 + + long@5.3.2: {} + + loose-envify@1.4.0: + dependencies: + js-tokens: 4.0.0 + + lru-cache@5.1.1: + dependencies: + yallist: 3.1.1 + + lru.min@1.1.5: {} + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + magic-string@1.4.1: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + magicast@0.5.5: + dependencies: + '@babel/parser': 7.29.9 + '@babel/types': 7.29.8 + source-map-js: 1.2.2 + + make-dir@4.0.0: + dependencies: + semver: 7.8.5 + + math-intrinsics@1.1.0: {} + + media-typer@0.3.0: {} + + media-typer@1.1.1: {} + + merge-descriptors@2.0.0: {} + + merge-stream@2.0.0: {} + + merge2@1.4.1: {} + + methods@1.1.2: {} + + micromatch@4.0.8: + dependencies: + braces: 3.0.3 + picomatch: 2.3.2 + + mime-db@1.52.0: {} + + mime-db@1.54.0: {} + + mime-types@2.1.35: + dependencies: + mime-db: 1.52.0 + + mime-types@3.0.2: + dependencies: + mime-db: 1.54.0 + + mime@2.6.0: {} + + mimic-fn@2.1.0: {} + + mimic-function@5.0.1: {} + + minimatch@10.2.6: + dependencies: + brace-expansion: 5.0.12 + + minimatch@3.1.5: + dependencies: + brace-expansion: 1.1.21 + + minimatch@9.0.9: + dependencies: + brace-expansion: 2.1.7 + + minimist@1.2.8: {} + + ms@2.1.3: {} + + multer@2.4.0: + dependencies: + append-field: 1.0.0 + busboy: 1.6.0 + type-is: 1.6.18 + + mute-stream@3.0.0: {} + + mysql2@3.15.3: + dependencies: + aws-ssl-profiles: 1.1.2 + denque: 2.1.0 + generate-function: 2.3.1 + iconv-lite: 0.7.3 + long: 5.3.2 + lru.min: 1.1.5 + named-placeholders: 1.1.6 + seq-queue: 0.0.5 + sqlstring: 2.3.3 + + mz@2.7.0: + dependencies: + any-promise: 1.3.0 + object-assign: 4.1.1 + thenify-all: 1.6.0 + + named-placeholders@1.1.6: + dependencies: + lru.min: 1.1.5 + + nanoid@3.3.19: {} + + natural-compare@1.4.0: {} + + negotiator@1.1.0: + dependencies: + content-type: 2.1.0 + + node-emoji@2.2.0: + dependencies: + '@sindresorhus/is': 4.6.0 + char-regex: 1.0.2 + emojilib: 2.4.0 + skin-tone: 2.0.0 + + node-releases@2.0.57: {} + + normalize-path@3.0.0: {} + + npm-run-path@4.0.1: + dependencies: + path-key: 3.1.1 + + object-assign@4.1.1: {} + + object-hash@3.0.0: {} + + object-inspect@1.13.4: {} + + obug@2.2.1: {} + + ohash@2.0.12: {} + + on-finished@2.4.1: + dependencies: + ee-first: 1.1.1 + + once@1.4.0: + dependencies: + wrappy: 1.0.2 + + onetime@5.1.2: + dependencies: + mimic-fn: 2.1.0 + + onetime@7.0.0: + dependencies: + mimic-function: 5.0.1 + + optionator@0.9.4: + dependencies: + deep-is: 0.1.4 + fast-levenshtein: 2.0.6 + levn: 0.4.1 + prelude-ls: 1.2.1 + type-check: 0.4.0 + word-wrap: 1.2.5 + + ora@9.4.1: + dependencies: + chalk: 5.6.2 + cli-cursor: 5.0.0 + cli-spinners: 3.4.0 + is-interactive: 2.0.0 + is-unicode-supported: 2.1.0 + log-symbols: 7.0.1 + stdin-discarder: 0.3.2 + string-width: 8.3.0 + + os-paths@4.4.0: {} + + oxlint-tsgolint@7.0.2003: + optionalDependencies: + '@oxlint-tsgolint/darwin-arm64': 7.0.2003 + '@oxlint-tsgolint/darwin-x64': 7.0.2003 + '@oxlint-tsgolint/linux-arm64': 7.0.2003 + '@oxlint-tsgolint/linux-x64': 7.0.2003 + '@oxlint-tsgolint/win32-arm64': 7.0.2003 + '@oxlint-tsgolint/win32-x64': 7.0.2003 + + oxlint@1.86.0(oxlint-tsgolint@7.0.2003): + optionalDependencies: + '@oxlint/binding-android-arm-eabi': 1.86.0 + '@oxlint/binding-android-arm64': 1.86.0 + '@oxlint/binding-darwin-arm64': 1.86.0 + '@oxlint/binding-darwin-x64': 1.86.0 + '@oxlint/binding-freebsd-x64': 1.86.0 + '@oxlint/binding-linux-arm-gnueabihf': 1.86.0 + '@oxlint/binding-linux-arm-musleabihf': 1.86.0 + '@oxlint/binding-linux-arm64-gnu': 1.86.0 + '@oxlint/binding-linux-arm64-musl': 1.86.0 + '@oxlint/binding-linux-ppc64-gnu': 1.86.0 + '@oxlint/binding-linux-riscv64-gnu': 1.86.0 + '@oxlint/binding-linux-riscv64-musl': 1.86.0 + '@oxlint/binding-linux-s390x-gnu': 1.86.0 + '@oxlint/binding-linux-x64-gnu': 1.86.0 + '@oxlint/binding-linux-x64-musl': 1.86.0 + '@oxlint/binding-openharmony-arm64': 1.86.0 + '@oxlint/binding-win32-arm64-msvc': 1.86.0 + '@oxlint/binding-win32-ia32-msvc': 1.86.0 + '@oxlint/binding-win32-x64-msvc': 1.86.0 + oxlint-tsgolint: 7.0.2003 + + p-limit@3.1.0: + dependencies: + yocto-queue: 0.1.0 + + p-locate@5.0.0: + dependencies: + p-limit: 3.1.0 + + parent-module@1.0.1: + dependencies: + callsites: 3.1.0 + + parseurl@1.3.3: {} + + path-exists@4.0.0: {} + + path-is-absolute@1.0.1: {} + + path-key@3.1.1: {} + + path-parse@1.0.7: {} + + path-to-regexp@8.4.2: {} + + path-type@4.0.0: {} + + pathe@2.0.3: {} + + perfect-debounce@2.1.0: {} + + pg-cloudflare@1.4.1: + optional: true + + pg-connection-string@2.14.1: {} + + pg-int8@1.0.1: {} + + pg-pool@3.14.0(pg@8.23.1): + dependencies: + pg: 8.23.1 + + pg-protocol@1.16.1: {} + + pg-types@2.2.0: + dependencies: + pg-int8: 1.0.1 + postgres-array: 2.0.0 + postgres-bytea: 1.0.1 + postgres-date: 1.0.7 + postgres-interval: 1.2.0 + + pg@8.23.1: + dependencies: + pg-connection-string: 2.14.1 + pg-pool: 3.14.0(pg@8.23.1) + pg-protocol: 1.16.1 + pg-types: 2.2.0 + pgpass: 1.0.5 + optionalDependencies: + pg-cloudflare: 1.4.1 + + pgpass@1.0.5: + dependencies: + split2: 4.2.0 + + picocolors@1.1.1: {} + + picomatch@2.3.2: {} + + picomatch@4.0.7: {} + + pirates@4.0.7: {} + + pkg-types@2.3.3: + dependencies: + confbox: 0.3.1 + exsolve: 1.1.3 + pathe: 2.0.3 + + pluralize@8.0.0: {} + + postcss-import@15.1.0(postcss@8.5.28): + dependencies: + postcss: 8.5.28 + postcss-value-parser: 4.2.0 + read-cache: 1.0.2 + resolve: 1.22.12 + + postcss-js@4.1.0(postcss@8.5.28): + dependencies: + camelcase-css: 2.0.1 + postcss: 8.5.28 + + postcss-load-config@6.0.1(jiti@1.21.7)(postcss@8.5.28): + dependencies: + lilconfig: 3.1.3 + optionalDependencies: + jiti: 1.21.7 + postcss: 8.5.28 + + postcss-nested@6.2.0(postcss@8.5.28): + dependencies: + postcss: 8.5.28 + postcss-selector-parser: 6.1.4 + + postcss-selector-parser@6.1.4: + dependencies: + cssesc: 3.0.0 + util-deprecate: 1.0.2 + + postcss-value-parser@4.2.0: {} + + postcss@8.5.28: + dependencies: + nanoid: 3.3.19 + picocolors: 1.1.1 + source-map-js: 1.2.2 + + postgres-array@2.0.0: {} + + postgres-array@3.0.4: {} + + postgres-bytea@1.0.1: {} + + postgres-date@1.0.7: {} + + postgres-interval@1.2.0: + dependencies: + xtend: 4.0.2 + + postgres@3.4.7: {} + + prelude-ls@1.2.1: {} + + prettier@3.9.9: {} + + prisma@7.10.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(magicast@0.5.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(typescript@6.0.3): + dependencies: + '@prisma/config': 7.10.0(magicast@0.5.5) + '@prisma/dev': 0.24.17(typescript@6.0.3) + '@prisma/engines': 7.10.0 + '@prisma/studio-core': 0.33.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + mysql2: 3.15.3 + postgres: 3.4.7 + optionalDependencies: + typescript: 6.0.3 + transitivePeerDependencies: + - '@types/react' + - '@types/react-dom' + - magicast + - react + - react-dom + + proper-lockfile@4.1.2: + dependencies: + graceful-fs: 4.2.11 + retry: 0.12.0 + signal-exit: 3.0.7 + + proxy-addr@2.0.8: + dependencies: + forwarded: 0.2.0 + ipaddr.js: 1.9.1 + + punycode@2.3.1: {} + + pure-rand@6.1.0: {} + + qs@6.16.0: + dependencies: + es-define-property: 1.0.1 + side-channel: 1.1.1 + + queue-microtask@1.2.3: {} + + range-parser@1.3.0: {} + + raw-body@3.0.2: + dependencies: + bytes: 3.1.2 + http-errors: 2.0.1 + iconv-lite: 0.7.3 + unpipe: 1.0.0 + + rc9@3.1.0: + dependencies: + defu: 6.1.7 + destr: 2.0.5 + + react-dom@18.3.1(react@18.3.1): + dependencies: + loose-envify: 1.4.0 + react: 18.3.1 + scheduler: 0.23.2 + + react-refresh@0.17.0: {} + + react-router-dom@6.30.6(react-dom@18.3.1(react@18.3.1))(react@18.3.1): + dependencies: + '@remix-run/router': 1.23.4 + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + react-router: 6.30.6(react@18.3.1) + + react-router@6.30.6(react@18.3.1): + dependencies: + '@remix-run/router': 1.23.4 + react: 18.3.1 + + react@18.3.1: + dependencies: + loose-envify: 1.4.0 + + read-cache@1.0.2: {} + + readdirp@3.6.0: + dependencies: + picomatch: 2.3.2 + + readdirp@5.1.1: {} + + reflect-metadata@0.2.2: {} + + remeda@2.33.4: {} + + require-from-string@2.0.2: {} + + resolve-from@4.0.0: {} + + resolve@1.22.12: + dependencies: + es-errors: 1.3.0 + is-core-module: 2.17.0 + path-parse: 1.0.7 + supports-preserve-symlinks-flag: 1.0.0 + + restore-cursor@5.1.0: + dependencies: + onetime: 7.0.0 + signal-exit: 4.1.0 + + ret@0.5.0: {} + + retry@0.12.0: {} + + reusify@1.1.0: {} + + rimraf@3.0.2: + dependencies: + glob: 7.2.3 + + robust-predicates@3.0.3: {} + + rolldown@1.2.12: + dependencies: + '@oxc-project/types': 0.152.0 + '@rolldown/pluginutils': 1.0.1 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.2.12 + '@rolldown/binding-android-arm64': 1.2.12 + '@rolldown/binding-darwin-arm64': 1.2.12 + '@rolldown/binding-darwin-x64': 1.2.12 + '@rolldown/binding-freebsd-x64': 1.2.12 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.12 + '@rolldown/binding-linux-arm64-gnu': 1.2.12 + '@rolldown/binding-linux-arm64-musl': 1.2.12 + '@rolldown/binding-linux-ppc64-gnu': 1.2.12 + '@rolldown/binding-linux-s390x-gnu': 1.2.12 + '@rolldown/binding-linux-x64-gnu': 1.2.12 + '@rolldown/binding-linux-x64-musl': 1.2.12 + '@rolldown/binding-openharmony-arm64': 1.2.12 + '@rolldown/binding-win32-arm64-msvc': 1.2.12 + '@rolldown/binding-win32-x64-msvc': 1.2.12 + + rollup@4.64.0: + dependencies: + '@types/estree': 1.0.9 + optionalDependencies: + '@napi-rs/lzma-linux-x64-gnu': 1.5.1 + '@rollup/rollup-android-arm-eabi': 4.64.0 + '@rollup/rollup-android-arm64': 4.64.0 + '@rollup/rollup-darwin-arm64': 4.64.0 + '@rollup/rollup-darwin-x64': 4.64.0 + '@rollup/rollup-freebsd-arm64': 4.64.0 + '@rollup/rollup-freebsd-x64': 4.64.0 + '@rollup/rollup-linux-arm-gnueabihf': 4.64.0 + '@rollup/rollup-linux-arm-musleabihf': 4.64.0 + '@rollup/rollup-linux-arm64-gnu': 4.64.0 + '@rollup/rollup-linux-arm64-musl': 4.64.0 + '@rollup/rollup-linux-loong64-gnu': 4.64.0 + '@rollup/rollup-linux-loong64-musl': 4.64.0 + '@rollup/rollup-linux-ppc64-gnu': 4.64.0 + '@rollup/rollup-linux-ppc64-musl': 4.64.0 + '@rollup/rollup-linux-riscv64-gnu': 4.64.0 + '@rollup/rollup-linux-riscv64-musl': 4.64.0 + '@rollup/rollup-linux-s390x-gnu': 4.64.0 + '@rollup/rollup-linux-x64-gnu': 4.64.0 + '@rollup/rollup-linux-x64-musl': 4.64.0 + '@rollup/rollup-openbsd-x64': 4.64.0 + '@rollup/rollup-openharmony-arm64': 4.64.0 + '@rollup/rollup-win32-arm64-msvc': 4.64.0 + '@rollup/rollup-win32-ia32-msvc': 4.64.0 + '@rollup/rollup-win32-x64-gnu': 4.64.0 + '@rollup/rollup-win32-x64-msvc': 4.64.0 + fsevents: 2.3.3 + + router@2.2.0: + dependencies: + debug: 4.4.3 + depd: 2.0.0 + is-promise: 4.0.0 + parseurl: 1.3.3 + path-to-regexp: 8.4.2 + transitivePeerDependencies: + - supports-color + + run-parallel@1.2.0: + dependencies: + queue-microtask: 1.2.3 + + rxjs@7.8.2: + dependencies: + tslib: 2.8.1 + + safe-regex2@5.1.1: + dependencies: + ret: 0.5.0 + + safer-buffer@2.1.2: {} + + scheduler@0.23.2: + dependencies: + loose-envify: 1.4.0 + + semver@6.3.1: {} + + semver@7.8.5: {} + + send@1.2.1: + dependencies: + debug: 4.4.3 + encodeurl: 2.0.0 + escape-html: 1.0.3 + etag: 1.8.1 + fresh: 2.0.0 + http-errors: 2.0.1 + mime-types: 3.0.2 + ms: 2.1.3 + on-finished: 2.4.1 + range-parser: 1.3.0 + statuses: 2.0.2 + transitivePeerDependencies: + - supports-color + + seq-queue@0.0.5: {} + + serve-static@2.2.1: + dependencies: + encodeurl: 2.0.0 + escape-html: 1.0.3 + parseurl: 1.3.3 + send: 1.2.1 + transitivePeerDependencies: + - supports-color + + setprototypeof@1.2.0: {} + + shebang-command@2.0.0: + dependencies: + shebang-regex: 3.0.0 + + shebang-regex@3.0.0: {} + + side-channel-list@1.0.1: + dependencies: + es-errors: 1.3.0 + object-inspect: 1.13.4 + + side-channel-map@1.0.1: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + object-inspect: 1.13.4 + + side-channel-weakmap@1.0.2: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + object-inspect: 1.13.4 + side-channel-map: 1.0.1 + + side-channel@1.1.1: + dependencies: + es-errors: 1.3.0 + object-inspect: 1.13.4 + side-channel-list: 1.0.1 + side-channel-map: 1.0.1 + side-channel-weakmap: 1.0.2 + + siginfo@2.0.0: {} + + signal-exit@3.0.7: {} + + signal-exit@4.1.0: {} + + skin-tone@2.0.0: + dependencies: + unicode-emoji-modifier-base: 1.0.0 + + slash@3.0.0: {} + + source-map-js@1.2.2: {} + + source-map@0.8.0: {} + + split2@4.2.0: {} + + sqlstring@2.3.3: {} + + stackback@0.0.2: {} + + standardwebhooks@1.1.1: + dependencies: + '@stablelib/base64': 1.0.1 + fast-sha256: 1.3.0 + + statuses@2.0.2: {} + + std-env@3.10.0: {} + + std-env@4.3.0: {} + + stdin-discarder@0.3.2: {} + + streamsearch@1.1.0: {} + + string-width@4.2.3: + dependencies: + emoji-regex: 8.0.0 + is-fullwidth-code-point: 3.0.0 + strip-ansi: 6.0.1 + + string-width@8.3.0: + dependencies: + get-east-asian-width: 1.7.0 + strip-ansi: 7.2.0 + + strip-ansi@6.0.1: + dependencies: + ansi-regex: 5.0.1 + + strip-ansi@7.2.0: + dependencies: + ansi-regex: 6.4.0 + + strip-bom@3.0.0: {} + + strip-final-newline@2.0.0: {} + + strip-json-comments@3.1.1: {} + + stripe@23.0.0(@types/node@24.19.1): + optionalDependencies: + '@types/node': 24.19.1 + + strtok3@10.3.5: + dependencies: + '@tokenizer/token': 0.3.0 + + sucrase@3.35.1: + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + commander: 4.1.1 + lines-and-columns: 1.2.4 + mz: 2.7.0 + pirates: 4.0.7 + tinyglobby: 0.2.17 + ts-interface-checker: 0.1.13 + + superagent@10.4.1: + dependencies: + component-emitter: 1.3.1 + cookiejar: 2.1.4 + debug: 4.4.3 + fast-safe-stringify: 2.1.1 + form-data: 4.0.6 + formidable: 3.5.4 + methods: 1.1.2 + mime: 2.6.0 + qs: 6.16.0 + transitivePeerDependencies: + - supports-color + + supertest@7.3.1: + dependencies: + cookie-signature: 1.2.2 + methods: 1.1.2 + superagent: 10.4.1 + transitivePeerDependencies: + - supports-color + + supports-color@7.2.0: + dependencies: + has-flag: 4.0.0 + + supports-preserve-symlinks-flag@1.0.0: {} + + tailwind-merge@2.6.1: {} + + tailwindcss@3.4.19: + dependencies: + '@alloc/quick-lru': 5.3.0 + arg: 5.0.2 + chokidar: 3.6.0 + didyoumean: 1.2.2 + dlv: 1.1.3 + fast-glob: 3.3.3 + glob-parent: 6.0.2 + is-glob: 4.0.3 + jiti: 1.21.7 + lilconfig: 3.1.3 + micromatch: 4.0.8 + normalize-path: 3.0.0 + object-hash: 3.0.0 + picocolors: 1.1.1 + postcss: 8.5.28 + postcss-import: 15.1.0(postcss@8.5.28) + postcss-js: 4.1.0(postcss@8.5.28) + postcss-load-config: 6.0.1(jiti@1.21.7)(postcss@8.5.28) + postcss-nested: 6.2.0(postcss@8.5.28) + postcss-selector-parser: 6.1.4 + resolve: 1.22.12 + sucrase: 3.35.1 + transitivePeerDependencies: + - tsx + - yaml + + text-table@0.2.0: {} + + thenify-all@1.6.0: + dependencies: + thenify: 3.3.1 + + thenify@3.3.1: + dependencies: + any-promise: 1.3.0 + + tinybench@2.9.0: {} + + tinyexec@1.3.1: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + + tinyrainbow@3.2.0: {} + + to-regex-range@5.0.1: + dependencies: + is-number: 7.0.0 + + toidentifier@1.0.1: {} + + token-types@6.1.2: + dependencies: + '@borewit/text-codec': 0.2.2 + '@tokenizer/token': 0.3.0 + ieee754: 1.2.1 + + ts-api-utils@1.4.3(typescript@5.9.3): + dependencies: + typescript: 5.9.3 + + ts-interface-checker@0.1.13: {} + + tsconfig-paths@4.2.0: + dependencies: + json5: 2.2.3 + minimist: 1.2.8 + strip-bom: 3.0.0 + + tslib@2.8.1: {} + + turbo@2.11.7: + optionalDependencies: + '@turbo/darwin-64': 2.11.7 + '@turbo/darwin-arm64': 2.11.7 + '@turbo/linux-64': 2.11.7 + '@turbo/linux-arm64': 2.11.7 + '@turbo/windows-64': 2.11.7 + '@turbo/windows-arm64': 2.11.7 + + type-check@0.4.0: + dependencies: + prelude-ls: 1.2.1 + + type-fest@0.20.2: {} + + type-is@1.6.18: + dependencies: + media-typer: 0.3.0 + mime-types: 2.1.35 + + type-is@2.1.0: + dependencies: + content-type: 2.1.0 + media-typer: 1.1.1 + mime-types: 3.0.2 + + typescript@5.9.3: {} + + typescript@6.0.3: {} + + uid@2.0.2: + dependencies: + '@lukeed/csprng': 1.1.0 + + uint8array-extras@1.6.0: {} + + undici-types@7.24.6: {} + + undici-types@8.9.0: {} + + unicode-emoji-modifier-base@1.0.0: {} + + unpipe@1.0.0: {} + + update-browserslist-db@1.3.3(browserslist@4.29.3): + dependencies: + browserslist: 4.29.3 + escalade: 3.2.0 + picocolors: 1.1.1 + + uri-js@4.4.1: + dependencies: + punycode: 2.3.1 + + util-deprecate@1.0.2: {} + + valibot@1.4.2(typescript@6.0.3): + optionalDependencies: + typescript: 6.0.3 + + validator@13.15.35: {} + + vary@1.1.2: {} + + vite-plugin-wasm@3.6.0(vite@5.4.21(@types/node@26.6.4)(lightningcss@1.33.0)): + dependencies: + vite: 5.4.21(@types/node@26.6.4)(lightningcss@1.33.0) + + vite@5.4.21(@types/node@26.6.4)(lightningcss@1.33.0): + dependencies: + esbuild: 0.21.5 + postcss: 8.5.28 + rollup: 4.64.0 + optionalDependencies: + '@types/node': 26.6.4 + fsevents: 2.3.3 + lightningcss: 1.33.0 + + vite@8.3.2(@types/node@24.19.1)(esbuild@0.28.2)(jiti@2.7.0): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.28 + rolldown: 1.2.12 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 24.19.1 + esbuild: 0.28.2 + fsevents: 2.3.3 + jiti: 2.7.0 + + vitest@4.1.11(@types/node@24.19.1)(@vitest/coverage-v8@4.1.11)(vite@8.3.2(@types/node@24.19.1)(esbuild@0.28.2)(jiti@2.7.0)): + dependencies: + '@vitest/expect': 4.1.11 + '@vitest/mocker': 4.1.11(vite@8.3.2(@types/node@24.19.1)(esbuild@0.28.2)(jiti@2.7.0)) + '@vitest/pretty-format': 4.1.11 + '@vitest/runner': 4.1.11 + '@vitest/snapshot': 4.1.11 + '@vitest/spy': 4.1.11 + '@vitest/utils': 4.1.11 + es-module-lexer: 2.3.2 + expect-type: 1.4.0 + magic-string: 0.30.21 + obug: 2.2.1 + pathe: 2.0.3 + picomatch: 4.0.7 + std-env: 4.3.0 + tinybench: 2.9.0 + tinyexec: 1.3.1 + tinyglobby: 0.2.17 + tinyrainbow: 3.2.0 + vite: 8.3.2(@types/node@24.19.1)(esbuild@0.28.2)(jiti@2.7.0) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 24.19.1 + '@vitest/coverage-v8': 4.1.11(vitest@4.1.11) + transitivePeerDependencies: + - msw + + which@2.0.2: + dependencies: + isexe: 2.0.0 + + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + + word-wrap@1.2.5: {} + + wrappy@1.0.2: {} + + xdg-app-paths@5.5.1: + dependencies: + os-paths: 4.4.0 + xdg-portable: 7.3.0 + + xdg-portable@7.3.0: + dependencies: + os-paths: 4.4.0 + + xtend@4.0.2: {} + + yallist@3.1.1: {} + + yocto-queue@0.1.0: {} + + yoctocolors@2.2.0: {} + + zeptomatch@2.1.0: + dependencies: + grammex: 3.1.13 + graphmatch: 1.1.1 + + zod@4.1.11: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 0000000000000000000000000000000000000000..69df65b598421ca98aadb05cd71e2f7b2cc557dd --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,9 @@ +packages: + - apps/prevision-web + - apps/prevision-api + - packages/* + +onlyBuiltDependencies: + - '@prisma/engines' + - 'esbuild' + - 'prisma'