# Planline architecture

## Product boundary

Planline is a **local-first 2D scanned-drawing digitisation and verification application**. Its target output is editable 2D vector/CAD geometry, not a 3D building model.

Scanned plans may be rotated, skewed, faded, low-resolution or drawn approximately rather than to scale. Pixel coordinates are image-space evidence, not physical measurements. Written dimensions become metric authority only after their text, units, dimension line and measured span have been checked.

Unreadable, ambiguous, unassociated, contradictory or under-constrained information must remain unresolved and visible for review. Planline must not silently invent dimensions, force walls to close, or present detector confidence as measurement confidence.

## Current implementation

The active application is served from the `web/` directory by the local FastAPI service in `planline/api.py`. The Windows desktop shell hosts this local workspace.

| Component | Current state |
| --- | --- |
| Workspace UI | Dashboard, drawing workspace, OCR Studio, settings, documentation and architecture pages; shared navigation and dark-first theme |
| Input | PNG, JPG, WEBP, TIFF and PDF; explicit multi-page PDF page selection; bounded upload and decoded-image dimensions |
| Detection | Bundled YOLO model proposes wall, dimension-line and dimension-value regions |
| Review | Overlay, zoom, confidence threshold, class filtering, candidate selection, crops, manual transcription and versioned review JSON |
| OCR inference | Optional local PaddleOCR recognition on dimension crops; output is an unverified suggestion until a person checks it |
| OCR Studio | Verified crop library, crop editor, review/CSV+ZIP import and export, source-/writer-grouped splits, quality audits, training-job orchestration and held-out benchmark reporting |
| Dimension interpretation | Numeric/unit parsing that retains ambiguous or unitless readings for explicit review |
| Dimension association | Geometric ranking of text-to-line and line-to-wall-gap hypotheses, with global assignment and chained-line support; all links require confirmation |
| Dimension checks | Manual dimension-chain arithmetic, wall-to-dimension comparison and an endpoint-based X/Y constraint graph; only explicitly verified constraints are solved |
| Wall reconstruction | A limited, review-gated draft of axis-aligned wall-face edges from confirmed horizontal and vertical dimension-to-wall matches; separate X/Y scales and source provenance are retained |
| Manual geometry | Editable wall segments and room polygons, endpoint editing/snapping, room area calculations and manually classified opening markers |
| Projects | Portable `.planline` save/open with source, analysis, review state, geometry and relevant scale/constraint provenance; saving is explicit |
| SVG/DXF | Export of editable manual geometry, room polygons, reviewed dimension annotations and selected wall/opening drafts on separate layers |
| DWG | Optional native DWG conversion through a separately installed ODA File Converter; DXF remains available without it |
| Updates | Settings page checks stable GitHub Releases; Windows update installer verifies SHA-256 before handing off installation |

The legacy command-line pipeline remains in the repository as a separate research baseline. It is not called by the active Planline API and must not be treated as the production reconstruction engine.

## Current data flow

```mermaid
flowchart TD
  A[Scanned plan or PDF] --> B[Local workspace upload]
  B --> C[Bounded decode / selected PDF page]
  C --> D[YOLO candidate detection]
  D --> E[Review boxes and dimension crops]
  E --> F[Optional local PaddleOCR suggestions]
  E --> G[Human review and transcription]
  F --> G
  G --> H[Confirm text, units, line and wall span]
  H --> I[Dimension checks and X/Y constraint graph]
  I --> J[Review-gated wall-face draft]
  J --> K[Manual geometry correction]
  K --> L[SVG / DXF export]
  L --> M[Optional ODA conversion to DWG]
  G --> N[Verified OCR crop dataset]
  N --> O[Grouped splits, training and held-out evaluation]
```

The API uses bounded image decoding and explicit PDF page selection. Uploads are parsed by the web framework before the endpoint's application-level size check; multipart parsing can therefore spool data to temporary storage. Do not describe the upload path as memory-only. For sensitive drawings, keep the service local, review temporary-file handling and use appropriate request-body limits at the server boundary.

## Recognition and association boundaries

The bundled YOLO model detects candidate regions; it does not read dimensions. When the optional PaddleOCR runtime is available, recognition runs on dimension crops and returns draft text. Printed and handwritten dimension performance has not been established on a representative, independent Planline benchmark. Every suggestion remains unverified until checked against the source crop.

Association ranks candidate relationships using local geometry: dimension-value location, dimension-line alignment, wall-box orientation, projected overlap and candidate wall gaps. A global assignment can reduce competing text-to-gap suggestions, while a single line can be shared by chained labels. These scores are relative geometric-fit hints, not probabilities or proof. Current association logic is primarily axis-aligned; rotated/diagonal annotation and wall geometry remain a limitation.

The constraint graph operates on explicitly named points and verified X/Y spans. It can identify disconnected components, inconsistent cycles and certain missing-span proposals. It does not yet infer a complete set of shared wall junctions automatically.

## Reconstruction and export boundaries

The current reconstruction step is deliberately narrower than full floor-plan vectorisation:

- It requires confirmed horizontal and vertical dimension-to-wall matches.
- It creates editable wall-face draft edges from axis-aligned detected wall regions and derives independent X/Y scales.
- Generated edges preserve detection provenance and remain a draft requiring inspection.
- Near-coincident endpoints can be presented as review candidates; a person must explicitly join or reject them.
- Room polygons can be reviewed and added from joined wall-edge cycles; they are not silently created.
- Door/window/opening markers are review-driven annotations, not complete parametric door or window objects.
- Manual walls and rooms remain available when automated draft geometry is unsuitable.

DXF/SVG export serialises editable geometry and reviewed annotations on typed layers. It does **not** certify that the drawing is survey-accurate, complete, topologically valid for every CAD workflow, or suitable for construction. Native DWG conversion is optional and depends on a separately installed ODA File Converter. The installer does not bundle that third-party converter.

## OCR data and evaluation

OCR Studio supports local crop curation, verified labels, dataset manifests, CSV-plus-image ZIP import/export, quality audits, source-/writer-aware grouped splits, training orchestration and held-out benchmarking. Training requires compatible local PaddlePaddle/PaddleOCR source and pretrained assets. The presence of training controls does not mean a recogniser has been trained or proven accurate on the user's drawings.

Split by original drawing and writer, not by crop. Keep duplicate/near-duplicate crops in one partition and preserve the test split during model selection. Use only drawings that are owned, licensed or explicitly permitted for the intended use. Do not place private customer drawings into public datasets without an appropriate rights and privacy basis.

Measure the complete workflow, not only OCR character accuracy:

- Exact complete-dimension accuracy and prediction coverage.
- Character error rate, including decimal separators and unit errors.
- Dimension-text-to-line and line-to-span association accuracy.
- Ambiguity rejection and reviewer correction rate.
- Constraint consistency and under-constrained-case detection.
- Geometry connectivity, topology and physical-unit residuals.
- DXF correctness in an independent CAD reader.
- Human correction time per drawing.

The regular API test suite uses a fake detector. Passing CI verifies software contracts and UI behaviour, not the accuracy of the real YOLO weights or OCR on representative plans.

## Target processing architecture

1. **Ingest and prepare.** Preserve source identity and original coordinates. Add reversible rotation/deskew/dewarp only when transformed coordinates can be mapped back reliably.
2. **Detect primitives and annotations.** Improve recall for walls, openings, dimension lines, arrowheads, dimension strings and symbols; preserve candidate provenance.
3. **Recognise complete dimension strings.** Benchmark printed and handwritten numeric recognisers on the same independent crops. Preserve raw text, alternatives, confidence and model version.
4. **Associate annotations.** Link each value to a dimension line and measured span using endpoints, extension lines, orientation and competing hypotheses. Retain ambiguity rather than forcing a choice.
5. **Solve constraints.** Use verified dimensions, units and tolerances. Report contradictions and under-constrained systems.
6. **Reconstruct topology.** Build connected wall/opening geometry from reviewed evidence; validate junctions, overlaps, closed boundaries and dimensional residuals.
7. **Gate CAD export.** Export only the reviewed geometry state, with explicit units, layers, source links and provenance. Validate files in an independent CAD reader.

## Current engineering priorities

1. Evaluate the real detector weights on representative, permissioned older scans; report per-class precision/recall and small-dimension recall.
2. Compare full-page and overlapping-tile inference, including duplicate suppression and runtime.
3. Benchmark complete printed and handwritten dimension strings on independent drawings and writers.
4. Measure association top-1 accuracy, ambiguity rejection and human correction rate.
5. Connect verified dimension associations and constraint-graph nodes to detected wall junctions.
6. Extend the limited axis-aligned wall-face draft into connected wall topology with explicit correction and undo.
7. Improve rotated/diagonal wall and annotation support, including reversible scan dewarping.
8. Add independent CAD-reader validation for units, layers, coordinates and entity counts.
9. Exercise the installer and updater on clean Windows machines and on existing installations containing user data.

## Local compute and scope

The initial local development target is a compact OCR/detection workflow that can run within consumer GPU memory limits. Prefer staged processing, high-resolution crops and conservative batches over a large end-to-end model. Choose models from representative-plan evaluation rather than generic benchmark claims.

**Scope:** 2D floor-plan digitisation and editable CAD output. Full 3D building reconstruction is not a current goal.

See [PLANLINE_ARCHITECTURE.md](PLANLINE_ARCHITECTURE.md) for detailed research notes, model comparisons, risks and the engineering backlog.
