AI / Computer VisionFull-StackKeystoneSTSSole developer · Aug–Oct 2026

LightDesign: AI roof measurement and Christmas light design from a single photo

KeystoneSTS, a Christmas and holiday-lighting installer, needed its sales team to quote jobs without a ladder and a tape measure. I built a platform where a salesperson photographs a house, types what they want in plain English, and gets back an editable, measured design: every roof edge found and typed, its real length in feet, and every bulb placed at true spacing in perspective, using products from the company's own catalogue.

0.88Roof-line F1 on held-out photos
98%Median overlap of the auto-picked house
~37kLines of code (Python + TypeScript)
95Commits across 4 milestones

Quoting a Christmas lighting job needed a site visit, a tape measure and a manual mock-up

Holiday-lighting installers price each job by how many feet of roofline, hedge and tree they will light, and then show the customer what it will look like. Both normally mean a site visit with a tape measure, followed by mock-ups by hand. The client wanted a tool their sales team could use from one phone photo.

  • Roof lines must be exact and typed. An eave, rake, hip, ridge or valley takes different products, and the line has to sit on the gutter, not near it. Neighbouring houses in the frame must be ignored.
  • Real lengths from one photo. A photo has no scale and phone browsers strip EXIF data, so the camera itself has to be recovered from the image before anything can be measured.
  • Things in the way. Palms, trees and cars hide parts of the roof. The hidden stretch is still installed and billed, so it has to be measured, not dropped.
  • Free-text requests. Salespeople type instructions in their own words, and these must map onto real catalogue products, never invented ones.
  • Cost and reliability. Hosted AI models are billed per call and sometimes fail or time out. The app has to stay usable and predictable either way.

Sole developer, from architecture to deployment

I designed and delivered the whole product: architecture, the ML detection pipeline, 3-D geometry, the API and database, the canvas editor and the Docker deployment. It shipped in four milestones with client demos, feature flags and written documentation for every mode.

SAM 3 + vision-LLM detection
Single-photo 3-D measurement
React canvas editor + FastAPI

From one photo to an approved estimate in five steps

A salesperson types something like “C9 warm white on the front roofline at 12-inch spacing, mini lights in the hedges, wrap the palm trunks” and the app walks them through a guided step bar:

LightDesign user workflow
StepWhat happens
UploadThe photo is EXIF-rotated, size-checked and stored, and a project is created with a thumbnail.
DetectAI finds the target house, its typed roof lines, hedges, shrubs, palms (trunk, collar, fronds), trees and obstructions.
Check linesThe salesperson reviews and corrects in the editor: drag points, draw missing lines, tap roofs in or out of the house, or “find lines in box”.
MeasureOne known length is entered (for example a 16 ft garage door). Every line gets a real length, a confidence and a “measure next” hint if a wall is unreached.
Lighting & approveThe instruction is read into requests, matched to products and colours, confirmed, and bulbs are placed and counted for the estimate.

A three-container stack behind one origin

nginx serves the compiled React app and forwards API traffic, so the browser only ever talks to one host and the session cookie stays first-party. FastAPI holds all business logic in a thin-router, thick-service layout: routers validate and authorise, and services are plain, testable Python with no web-framework dependency.

LightDesign architecture: a React and TypeScript browser app talks to an nginx container that reverse-proxies to a FastAPI container with auth, photos, regions, products and files routers and a pure-Python service layer. FastAPI stores data in PostgreSQL 15 and a file volume, and calls SAM 3 on fal.ai and a vision LLM through OpenRouter.
Fig 1. Deployment and component view: nginx, FastAPI, PostgreSQL and file storage in Docker Compose, with SAM 3 and a vision LLM as external services

A foundation segmentation model, a vision LLM and classical computer vision, each doing what it does best

SAM 3 (Segment Anything 3, hosted on fal.ai) returns pixel masks for every roof plane and every object a light can go on or behind. A vision LLM (via OpenRouter, with strict JSON-schema output) sees only a crop of the house being quoted and returns typed roof lines. Classical computer vision then refines those lines conservatively: it may nudge an endpoint onto a strong image edge, but it never redraws what the model said.

  1. Upload & normaliseEXIF rotation, size limits, working copy at 1280 px.
  2. SAM 3 segmentationMasks for roof planes, hedge, bush, topiary, palm, tree, car and sky.Customer photos are sent inline as base64, never uploaded to third-party storage.
  3. Target-house selectionSeed on the largest central roof and grow across shared seams, with no extra model call.Frame-cut and set-back neighbouring houses are rejected.
  4. Sky-bounded cropA padded house box whose top extends to where the sky begins.
  5. Vision-LLM roof linesTyped lines drawn on the crop, cached by pixel hash.If the LLM fails (key, timeout, bad JSON), a geometric partition pipeline draws the lines instead.
  6. Crop → photo coordinatesOne canonical RoofLine type for every source.
  7. Conservative geometryEdge snapping, vanishing-point facades and corner closure.An endpoint moves only on strong, parallel, local evidence, and a line never turns more than 2.5°.
  8. OcclusionJoin pieces behind palms and cars, and mark the hidden stretches.A join needs a detected blocker covering the gap.
  9. Confidence & editor regionsEvidence-weighted score from source, edge strength, VP fit, connectivity, plane agreement and visibility. Low scores are drawn dashed.

Fallback: plane-partition geometry, so detection never hard-fails

When the LLM is unavailable or switched off, roof lines are derived from the SAM masks with an eight-stage geometric method: a hard pixel partition of the planes, morphological clean-up, Douglas-Peucker corner seeding with Huber and total-least-squares line fits, LSD vanishing points as direction priors, a planar graph relaxed by block coordinate descent, interior crease detection, and ridge, hip, valley, eave and rake roles from topology.

Real lengths in feet from one ordinary photo and one tape-measured length

The most technically demanding part of the project. It is built from first principles on a pinhole camera model, and every line records what it had to assume.

  1. Vanishing pointsLSD line segments give a vertical VP plus one per facade.
  2. Camera focal lengthf² = −(v₁ − c)·(v₂ − c), with EXIF used only as a cross-check.Ill-conditioned VP pairs are rejected by jittering each point and measuring the spread in f.
  3. Facade planesEach facade normal is the facade direction crossed with the vertical.
  4. Wall assignmentDirection with a margin, else structure, else try every candidate.Near eye level every facade's VP lies on the horizon, so direction alone is not trusted.
  5. One known lengthFixes the measured wall's distance from the camera.
  6. Propagate through cornersShared eave and rake corners, and roof faces at pitch, carry scale to every other wall.Set-back walls (dormers, upper storeys) link to the main wall through the roof pitch.
  7. Independent checksDoor sizes, roof pitch, eave height and plausibility.Checks use outside knowledge, so a wrong wall choice cannot validate itself.
  8. Bulbs at real spacingLaid every N inches in 3-D and projected back, so on-screen spacing is correctly uneven and bulb size is f · diameter / depth.

Ambiguity is solved, not guessed

A line whose wall cannot be decided is tried on every candidate facade, and the choice under which the whole house passes the independent checks is kept. Level lines of the same kind at the same roof height form one continuous run, so bulb spacing carries around corners without resetting.

Verified on synthetic ground truth

A test renders a corner house through a known camera. The app recovers the focal length within 3%, the measured wall within 1% and inherited walls within 5%.

Hidden bulbs are counted, and every solve is explainable

Lights behind a palm or car are flagged hidden, not drawn, but still appear in the estimate. A debug mode writes nine step-by-step overlays per solve (camera, sides, walls, pitch, anchors, wall choices, checks, lengths) so any measurement can be diagnosed.

Plain-English requests that can only name products the company sells

  • Two interchangeable readers sit behind one interface: an LLM reader and an offline, deterministic rules reader. The confirmation screen always says which one was used and why.
  • The LLM's vocabulary is generated from live data (place kinds, roof edges, sides, and the customer's own product library and palette), so it cannot name a product the company does not sell.
  • Every model answer is validated against that vocabulary; anything unknown is dropped and reported, and on any failure the rules answer is used. Only the instruction text is sent, never the photo.
  • One sentence can hold several requests, and each is confirmed separately before anything is generated.

Products (C9, C7, mini lights, icicle, garland, wreath) are data with category-specific attributes, archived rather than deleted. Colour patterns, spacing and twinkle are render parameters, never baked into pixels. Palms are split automatically into trunk, collar and frond zones, with trunks wrapped and fronds lit as strands from crown to tip.

Canvas editor (React + TypeScript)

LightDesign editor tools
ToolPurpose
Select / Points / MovePick lines and areas, drag vertices, move or extend lines with snapping to existing ends.
HouseTap a roof plane in or out of the quoted house; lines are redrawn from stored data with no model call.
Find linesDraw a box around a missed edge; the server runs detection on just that box and adds only new lines.
Add object / Brush / EraseClick-to-segment with SAM point and box prompts, and paint masks larger or smaller.
MeasureTap a line and type its length; review per-line lengths, confidence and “measure next”.
WreathPlace wreaths on the facade at real size.

Hand-drawn lines snap their ends to nearby corners and get a suggested type from vanishing points and what their ends touch, confirmed with one tap. Undo and redo, toasts with undo, a shortcut sheet and the guided step bar round out the UX.

Measured with a purpose-built benchmark, not impressions

I built a separate annotation app that runs the product's exact detection code, lets a reviewer correct the lines into ground truth, and scores every prediction. Each prediction is frozen with a fingerprint (settings, prompt hash, git commit), and every error is traced to the stage that caused it: house selection, a crop that was too small, a line the model never drew, or a geometry stage that moved it.

0.87Mean F1, all 21 photos
0.88Mean F1, held-out set (7)
0.92Precision, held-out set
273/323Truth roof edges found
Roof-line detection benchmark, mean over photos
Metric (mean over photos)Tuning set (14)Held-out set (7)All (21)
F1 score0.8580.8780.865
Recall, visible length0.8630.8650.864
Precision0.8600.9160.878
Eave recall0.8910.7800.854
Auto vs. human house box, IoU (median)0.990.950.98

Scores from the annotator's latest run over hand-corrected truth; tolerance is max(6 px, 0.8% of the house diagonal). The held-out photos were never used for tuning.

Built to be tested, rolled out safely and kept cheap to run

Testing

74 pytest unit tests (camera, scale, placement, drawn lines, plane filter, and the LLM provider with a mocked network), an end-to-end API smoke test, offline evaluation scripts for detection, parsing and measurement, and Playwright UI smoke tests.

Cost control

Model answers are cached on disk by image pixels, crop, model and prompt, never by filename. Editor actions never call a paid model, and latency, tokens and cost are recorded for every detection.

Safe rollout and observability

Every new detection behaviour ships behind a feature flag that is off by default, and /health reports which mode is live. Per-stage counts and optional overlays show the first stage that damaged a good line.

Security

Argon2 password hashing with a constant-time path for unknown emails, HTTP-only SameSite session cookies with expiry, owner-scoped file serving, upload type and size validation, and customer-owned API keys kept out of the repository.

Technologies used

  • Python
  • FastAPI
  • SAM 3
  • Vision LLM
  • OpenRouter
  • fal.ai
  • OpenCV
  • NumPy
  • Projective geometry
  • React 18
  • TypeScript
  • HTML5 Canvas
  • PostgreSQL
  • SQLAlchemy 2
  • Alembic
  • Docker
  • nginx
  • pytest
  • Playwright
LightDesign technology stack by category
CategoryTechnologies
BackendPython 3.11, FastAPI 0.115, Uvicorn, Pydantic v2 + pydantic-settings, httpx
Computer visionOpenCV 4.10 (LSD line segments, morphology, contours), NumPy 2, Pillow; custom pinhole-camera and projective-geometry code
AI modelsSAM 3 (Segment Anything 3) via fal.ai with text, box and point prompts; multimodal GPT-class vision LLM via OpenRouter with strict JSON-schema output
DatabasePostgreSQL 15, SQLAlchemy 2.0 ORM, Alembic migrations, psycopg 3
Auth & securityArgon2 (argon2-cffi), server-side sessions, HTTP-only cookies, email-validator, CORS policy
FrontendReact 18, TypeScript 5.7, Vite 6, HTML5 Canvas rendering, CSS custom properties (light / dark)
Testingpytest, Playwright, offline evaluation and benchmark scripts
DevOpsDocker, Docker Compose, nginx 1.27 reverse proxy, multi-stage builds, health checks, environment-based configuration
ResearchApple Depth Pro (monocular depth) experiment in Google Colab on a T4 GPU, compared against the geometric solve

Customer photos and proprietary prompts are omitted for confidentiality. Figures come from the project's own benchmark output and repository history (August to October 2026).

Hire a computer vision engineer to build yours end to end

I combine foundation models, LLMs and classical computer vision into products that measure, explain and fall back gracefully, with the backend, editor and deployment to match.

Let's talk →