PlanQuant
Automatic quantity take-off from structural PDF plans, every value flagged by confidence.
- Document AI
- Computer vision
- Role
- Architect and engineer, client proof of concept
- Client
- French construction-engineering firm (confidential)
- Timeline
- Jun 12 - 19, 2026
- Status
- Prototype

- commits in 8 days
- 76
- commits in 8 days
- automated tests (136 pytest, 8 Vitest)
- 144
- automated tests (136 pytest, 8 Vitest)
- vector paths extracted from a real A0 plan in the feasibility check
- 70,752
- vector paths extracted from a real A0 plan in the feasibility check
- REST endpoints
- 15
- REST endpoints
The problem
In France, a métré (quantity take-off) from structural plans is done by hand. It takes hours to days per drawing, and every error flows straight into cost estimates and bids.
The plans are vector PDFs with no text layer: pdffonts and pdftotext return nothing, because every dimension and label is drawn as outlined glyphs. The geometry is machine-exact, but the numbers that give it meaning have to be read visually. The rule from the spec: measure exactly where possible, ask where not, and never invent a number.
Architecture
Parse and lock the scale
The upload is parsed with pdfminer into primitives with line width and colours, and the pen profiler splits the document's own line weights into structure and annotation. Detection returns HTTP 409 until the user confirms the title-block scale or calibrates two points.
- Service
- Data
- AI model
- External
Hard problems I solved
Dimensions drawn as pictures
With no text layer, every dimension, level and element mark is a set of vector outlines. Geometry is exact, but the numbers that give it meaning are not machine-readable.
Approach. Two independent pipelines joined spatially. Geometry comes from the vector paths; text comes from Claude vision on rendered tiles through a forced tool call, so the output is strict JSON with per-string confidence and boxes. Tile pixel coordinates (y-down) are mapped back to PDF points (y-up), and a tile that fails returns nothing instead of failing the page.
On a real client plan, tile overlap produced about 188 duplicates out of 440 labels; same-text overlap dedup removes them.
A detector that found nothing on the second plan
The first detector keyed on fill colours (grey footings, tan walls) and worked on the first client plan. On the second it found 0 footings: that plan uses 2 colours across 18,323 primitives.
Approach. Analysis showed pen weight is the real convention (0.3 pt for dimensions, 1.68 pt for structure, 0 for text). The pen profiler sorts each document's own line weights, splits at the first jump of 1.5x or more, checks that the structural strokes sit in the drawing core, and falls back to 'all structural' when ambiguous. No per-firm constants.
It recovered the structure layer (about 5,093 strokes) and excluded the dimension lines.
Elements drawn as loose segments
On the same plan, 9,854 of the 18,323 paths were 2-point segments, and only 223 of the 5,093 structural primitives were closed shapes. There were no rectangles to measure.
Approach. Outlines are rebuilt with shapely polygonize(unary_union(lines)), merged with the shapes that were already closed, size-filtered to plausible members between 15 cm and 15 m, and de-duplicated. Footing labels are then anchored to the region that contains them, which gives real areas for isolated footings and real lengths for strips.
Deciding what not to automate
Slab and wall areas looked automatable, but polygonized regions came out either as the whole floor (about 600 m²) or as tiny detail cells (about 3 m²), several thickness labels fell in one region, and a naive run double-counted to a bogus 1,552 m³ of concrete.
Approach. Slabs became assisted-manual: the app detects the slab marker and reads its thickness, and the user drags the area. Automatic floor segmentation was also unreliable, so the user draws floor boxes and detection runs per floor. The tool states what it cannot do instead of fabricating numbers.
Vision that answers differently each run
The same page returned 39 footing-code labels on one run and about 120 on another, roughly a 3x swing.
Approach. Labels are cached in a .labels.json sidecar for reproducible offline iteration, per-tile failures are isolated, and anything a measurement does not corroborate shows amber or red, never silently green.
Trust by construction
A take-off is only useful if an engineer can see where every number came from and trust that missing data was not filled in.
Approach. One ±3% cross-check helper is shared by association and confidence so the two stages cannot disagree. A missing height stays red even after confirmation until a real height exists, every value carries its provenance, and the UI warns before exporting with red flags. Tests are hermetic: conftest forces the fake vision provider and strips the API key before config loads, so the suite never reaches the network.
Code
The split comes from each document's own line weights, so a new design office needs no configuration. When the evidence is ambiguous it falls back to keeping everything, never to dropping structure.
MIN_GAP_RATIO = 1.5 # adjacent-weight ratio that counts as a real cluster boundary
CORE_COVERAGE_MIN = 0.5 # >= half of structural strokes must sit in the drawing core
def classify_pens(prims) -> PenProfile:
strokes = [p for p in prims if p.stroked and p.line_width > 0]
weights = sorted({round(p.line_width, 3) for p in strokes})
everything = frozenset(weights)
if len(weights) < 2:
return PenProfile(structural=everything, annotation=frozenset(), fallback=True)
split = next((i for i in range(len(weights) - 1)
if weights[i + 1] / weights[i] >= MIN_GAP_RATIO), None)
if split is None:
return PenProfile(structural=everything, annotation=frozenset(), fallback=True)
annotation = frozenset(weights[:split + 1])
structural = frozenset(weights[split + 1:])
core = _drawing_core(strokes)
struct_strokes = [p for p in strokes if round(p.line_width, 3) in structural]
if struct_strokes:
inside = sum(1 for p in struct_strokes if _in(core, *p.centroid))
if inside / len(struct_strokes) < CORE_COVERAGE_MIN:
return PenProfile(structural=everything, annotation=frozenset(), fallback=True)
return PenProfile(structural=structural, annotation=annotation, fallback=False)def _read_tile(self, pil, tile, page_h_pt: float) -> list[ReadLabel]:
... # crop the tile and encode it as a base64 PNG
try:
msg = self._client.messages.create(
model=config.VISION_MODEL, max_tokens=4096, tools=[_TOOL],
tool_choice={"type": "tool", "name": "report_labels"},
messages=[{"role": "user", "content": [{"type": "image", "source": {...}},
{"type": "text", "text": _PROMPT}]}])
block = next((b for b in msg.content if b.type == "tool_use"), None)
raw = (block.input.get("labels") if block and isinstance(block.input, dict) else None) or []
except Exception:
return [] # one bad/slow tile shouldn't sink the whole read
return _tile_labels(raw, tile, page_h_pt)
def _tile_labels(raw, tile, page_h_pt: float) -> list[ReadLabel]: # pixels, y-down -> page pts, y-up
out: list[ReadLabel] = []
for l in raw or []:
try:
x0 = (tile.x0 + l["x0"]) / RENDER_SCALE
x1 = (tile.x0 + l["x1"]) / RENDER_SCALE
y_top_pdf = page_h_pt - (tile.y0 + l["y0"]) / RENDER_SCALE
y_bot_pdf = page_h_pt - (tile.y0 + l["y1"]) / RENDER_SCALE
out.append(ReadLabel(text=l["text"], bbox=(x0, y_bot_pdf, x1, y_top_pdf), ...))
except (KeyError, TypeError, ValueError):
continue # skip a malformed label entry, keep the rest
return outdef evaluate(measured: dict, read: ReadInfo, final: dict, status: str) -> tuple[Confidence, list[FlagReason]]:
flags: list[FlagReason] = []
verdict = cross_check(measured, read, config.DIMENSION_TOLERANCE)
if verdict is False:
flags.append(FlagReason.CONFLICT)
if verdict is None:
flags.append(FlagReason.NO_DIMENSION)
if read.ocr_conf is not None and read.ocr_conf < config.LOW_OCR_CONF:
flags.append(FlagReason.LOW_CONF_LABEL)
if status in _USER_RESOLVED_STATUSES:
flags = [] # user has looked at it / entered it
if final.get("height_cm") is None:
flags.append(FlagReason.MISSING_HEIGHT) # required-missing survives everything
if FlagReason.CONFLICT in flags or FlagReason.MISSING_HEIGHT in flags:
return Confidence.RED, flags
if FlagReason.NO_DIMENSION in flags or FlagReason.LOW_CONF_LABEL in flags:
return Confidence.AMBER, flags
return Confidence.GREEN, flagsWhat I built
Geometry pipeline
- pdfminer path walk that records line width, stroke and fill colour per primitive
- Self-configuring pen profiler that separates structure from annotation by line weight
- Element outlines assembled from loose strokes with shapely polygonize, filtered to 15 cm - 15 m
- Hard scale gate: detection returns HTTP 409 until the scale is locked from the title block or two-point calibration
Reading the drawing
- Page rendered at 144 dpi, tiled, up to 8 tiles read concurrently by Claude vision
- Forced tool call returns strict JSON with per-label confidence and bounding box
- Tile pixel boxes mapped back to PDF points, duplicates from tile overlap removed
- Token parser for sections, heights, NGF levels, concrete grades and footing codes, French decimal commas included
Trust and quantities
- Labels joined to the containing or nearest element, measured vs read cross-checked at ±3%
- Green, amber or red verdict with provenance per value: measured, read or user
- Surface, volume and weight (2.5 t/m³) per element and per floor
- Excel bill of quantities with element id and centroid on every row, plus a totals sheet
Review UI
- PDF.js underlay with an SVG confidence overlay and a canvas structural overlay
- Flag queue and inspector with measured, read and final values side by side
- Add a missed element, draw floor boxes, enter slab areas by hand
- Live totals that warn before export while red flags remain
Screens
Amber: the footing label was read with low confidence. Surface, volume and weight are computed, but a person confirms the reading.
A reviewer enters a missing height: the footing turns green and the volume and weight totals update live.
Stack
Geometry
- pdfminer.six (vector paths)
- shapely 2 (polygonize, unary_union)
- numpy
Vision
- Claude vision (claude-sonnet-4-6)
- Forced tool call for strict JSON
- pypdfium2 rendering
Backend
- Python 3.11+ with uv
- FastAPI
- SQLAlchemy 2 on SQLite
- openpyxl
- reportlab (synthetic fixtures)
Frontend
- React 19
- TypeScript
- Vite 8
- pdfjs-dist
- Zustand
- Tailwind
Quality
- pytest
- Vitest
- Hermetic fake vision provider
How it was built
Built in 8 days from a design spec I wrote and handed to Claude Code, then implementation plans executed task by task with tests first and review-fix passes; 75 of the 76 commits carry a Claude co-author trailer. When the real plans broke the first approach, investigation of the drawings (pen weights, loose segments, what cannot be automated) led to two further specs and plans mid-build.
The client and its plans are confidential: every screenshot uses the synthetic test plan, and figures from real plans are shown only as counts.